repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
chrislusf/gleam | sql/plan/typeinferer.go | InferType | func InferType(sc *variable.StatementContext, node ast.Node) error {
var inferrer typeInferrer
inferrer.sc = sc
// TODO: get the default charset from ctx
inferrer.defaultCharset = "utf8"
node.Accept(&inferrer)
return inferrer.err
} | go | func InferType(sc *variable.StatementContext, node ast.Node) error {
var inferrer typeInferrer
inferrer.sc = sc
// TODO: get the default charset from ctx
inferrer.defaultCharset = "utf8"
node.Accept(&inferrer)
return inferrer.err
} | [
"func",
"InferType",
"(",
"sc",
"*",
"variable",
".",
"StatementContext",
",",
"node",
"ast",
".",
"Node",
")",
"error",
"{",
"var",
"inferrer",
"typeInferrer",
"\n",
"inferrer",
".",
"sc",
"=",
"sc",
"\n",
"// TODO: get the default charset from ctx",
"inferrer",
".",
"defaultCharset",
"=",
"\"",
"\"",
"\n",
"node",
".",
"Accept",
"(",
"&",
"inferrer",
")",
"\n",
"return",
"inferrer",
".",
"err",
"\n",
"}"
] | // InferType infers result type for ast.ExprNode. | [
"InferType",
"infers",
"result",
"type",
"for",
"ast",
".",
"ExprNode",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/typeinferer.go#L31-L38 | train |
chrislusf/gleam | sql/plan/typeinferer.go | handleCaseExpr | func (v *typeInferrer) handleCaseExpr(x *ast.CaseExpr) {
var currType types.FieldType
for _, w := range x.WhenClauses {
t := w.Result.GetType()
if currType.Tp == mysql.TypeUnspecified {
currType = *t
continue
}
mtp := types.MergeFieldType(currType.Tp, t.Tp)
if mtp == t.Tp && mtp != currType.Tp {
currType.Charset = t.Charset
currType.Collate = t.Collate
}
currType.Tp = mtp
}
if x.ElseClause != nil {
t := x.ElseClause.GetType()
if currType.Tp == mysql.TypeUnspecified {
currType = *t
} else {
mtp := types.MergeFieldType(currType.Tp, t.Tp)
if mtp == t.Tp && mtp != currType.Tp {
currType.Charset = t.Charset
currType.Collate = t.Collate
}
currType.Tp = mtp
}
}
x.SetType(&currType)
// TODO: We need a better way to set charset/collation
x.Type.Charset, x.Type.Collate = types.DefaultCharsetForType(x.Type.Tp)
} | go | func (v *typeInferrer) handleCaseExpr(x *ast.CaseExpr) {
var currType types.FieldType
for _, w := range x.WhenClauses {
t := w.Result.GetType()
if currType.Tp == mysql.TypeUnspecified {
currType = *t
continue
}
mtp := types.MergeFieldType(currType.Tp, t.Tp)
if mtp == t.Tp && mtp != currType.Tp {
currType.Charset = t.Charset
currType.Collate = t.Collate
}
currType.Tp = mtp
}
if x.ElseClause != nil {
t := x.ElseClause.GetType()
if currType.Tp == mysql.TypeUnspecified {
currType = *t
} else {
mtp := types.MergeFieldType(currType.Tp, t.Tp)
if mtp == t.Tp && mtp != currType.Tp {
currType.Charset = t.Charset
currType.Collate = t.Collate
}
currType.Tp = mtp
}
}
x.SetType(&currType)
// TODO: We need a better way to set charset/collation
x.Type.Charset, x.Type.Collate = types.DefaultCharsetForType(x.Type.Tp)
} | [
"func",
"(",
"v",
"*",
"typeInferrer",
")",
"handleCaseExpr",
"(",
"x",
"*",
"ast",
".",
"CaseExpr",
")",
"{",
"var",
"currType",
"types",
".",
"FieldType",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"x",
".",
"WhenClauses",
"{",
"t",
":=",
"w",
".",
"Result",
".",
"GetType",
"(",
")",
"\n",
"if",
"currType",
".",
"Tp",
"==",
"mysql",
".",
"TypeUnspecified",
"{",
"currType",
"=",
"*",
"t",
"\n",
"continue",
"\n",
"}",
"\n",
"mtp",
":=",
"types",
".",
"MergeFieldType",
"(",
"currType",
".",
"Tp",
",",
"t",
".",
"Tp",
")",
"\n",
"if",
"mtp",
"==",
"t",
".",
"Tp",
"&&",
"mtp",
"!=",
"currType",
".",
"Tp",
"{",
"currType",
".",
"Charset",
"=",
"t",
".",
"Charset",
"\n",
"currType",
".",
"Collate",
"=",
"t",
".",
"Collate",
"\n",
"}",
"\n",
"currType",
".",
"Tp",
"=",
"mtp",
"\n\n",
"}",
"\n",
"if",
"x",
".",
"ElseClause",
"!=",
"nil",
"{",
"t",
":=",
"x",
".",
"ElseClause",
".",
"GetType",
"(",
")",
"\n",
"if",
"currType",
".",
"Tp",
"==",
"mysql",
".",
"TypeUnspecified",
"{",
"currType",
"=",
"*",
"t",
"\n",
"}",
"else",
"{",
"mtp",
":=",
"types",
".",
"MergeFieldType",
"(",
"currType",
".",
"Tp",
",",
"t",
".",
"Tp",
")",
"\n",
"if",
"mtp",
"==",
"t",
".",
"Tp",
"&&",
"mtp",
"!=",
"currType",
".",
"Tp",
"{",
"currType",
".",
"Charset",
"=",
"t",
".",
"Charset",
"\n",
"currType",
".",
"Collate",
"=",
"t",
".",
"Collate",
"\n",
"}",
"\n",
"currType",
".",
"Tp",
"=",
"mtp",
"\n",
"}",
"\n",
"}",
"\n",
"x",
".",
"SetType",
"(",
"&",
"currType",
")",
"\n",
"// TODO: We need a better way to set charset/collation",
"x",
".",
"Type",
".",
"Charset",
",",
"x",
".",
"Type",
".",
"Collate",
"=",
"types",
".",
"DefaultCharsetForType",
"(",
"x",
".",
"Type",
".",
"Tp",
")",
"\n",
"}"
] | // The return type of a CASE expression is the compatible aggregated type of all return values,
// but also depends on the context in which it is used.
// If used in a string context, the result is returned as a string.
// If used in a numeric context, the result is returned as a decimal, real, or integer value. | [
"The",
"return",
"type",
"of",
"a",
"CASE",
"expression",
"is",
"the",
"compatible",
"aggregated",
"type",
"of",
"all",
"return",
"values",
"but",
"also",
"depends",
"on",
"the",
"context",
"in",
"which",
"it",
"is",
"used",
".",
"If",
"used",
"in",
"a",
"string",
"context",
"the",
"result",
"is",
"returned",
"as",
"a",
"string",
".",
"If",
"used",
"in",
"a",
"numeric",
"context",
"the",
"result",
"is",
"returned",
"as",
"a",
"decimal",
"real",
"or",
"integer",
"value",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/typeinferer.go#L371-L403 | train |
chrislusf/gleam | sql/plan/typeinferer.go | handleLikeExpr | func (v *typeInferrer) handleLikeExpr(x *ast.PatternLikeExpr) {
x.SetType(types.NewFieldType(mysql.TypeLonglong))
x.Type.Charset = charset.CharsetBin
x.Type.Collate = charset.CollationBin
x.Expr = v.addCastToString(x.Expr)
x.Pattern = v.addCastToString(x.Pattern)
} | go | func (v *typeInferrer) handleLikeExpr(x *ast.PatternLikeExpr) {
x.SetType(types.NewFieldType(mysql.TypeLonglong))
x.Type.Charset = charset.CharsetBin
x.Type.Collate = charset.CollationBin
x.Expr = v.addCastToString(x.Expr)
x.Pattern = v.addCastToString(x.Pattern)
} | [
"func",
"(",
"v",
"*",
"typeInferrer",
")",
"handleLikeExpr",
"(",
"x",
"*",
"ast",
".",
"PatternLikeExpr",
")",
"{",
"x",
".",
"SetType",
"(",
"types",
".",
"NewFieldType",
"(",
"mysql",
".",
"TypeLonglong",
")",
")",
"\n",
"x",
".",
"Type",
".",
"Charset",
"=",
"charset",
".",
"CharsetBin",
"\n",
"x",
".",
"Type",
".",
"Collate",
"=",
"charset",
".",
"CollationBin",
"\n",
"x",
".",
"Expr",
"=",
"v",
".",
"addCastToString",
"(",
"x",
".",
"Expr",
")",
"\n",
"x",
".",
"Pattern",
"=",
"v",
".",
"addCastToString",
"(",
"x",
".",
"Pattern",
")",
"\n",
"}"
] | // like expression expects the target expression and pattern to be a string, if it's not, we add a cast function. | [
"like",
"expression",
"expects",
"the",
"target",
"expression",
"and",
"pattern",
"to",
"be",
"a",
"string",
"if",
"it",
"s",
"not",
"we",
"add",
"a",
"cast",
"function",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/typeinferer.go#L406-L412 | train |
chrislusf/gleam | sql/plan/typeinferer.go | addCastToString | func (v *typeInferrer) addCastToString(expr ast.ExprNode) ast.ExprNode {
if !mysql.IsUTF8Charset(expr.GetType().Charset) {
castTp := types.NewFieldType(mysql.TypeString)
castTp.Charset, castTp.Collate = types.DefaultCharsetForType(mysql.TypeString)
if val, ok := expr.(*ast.ValueExpr); ok {
newVal, err := val.Datum.ConvertTo(v.sc, castTp)
if err != nil {
v.err = errors.Trace(err)
}
expr.SetDatum(newVal)
} else {
castFunc := &ast.FuncCastExpr{
Expr: expr,
Tp: castTp,
FunctionType: ast.CastFunction,
}
expr = castFunc
}
expr.SetType(castTp)
}
return expr
} | go | func (v *typeInferrer) addCastToString(expr ast.ExprNode) ast.ExprNode {
if !mysql.IsUTF8Charset(expr.GetType().Charset) {
castTp := types.NewFieldType(mysql.TypeString)
castTp.Charset, castTp.Collate = types.DefaultCharsetForType(mysql.TypeString)
if val, ok := expr.(*ast.ValueExpr); ok {
newVal, err := val.Datum.ConvertTo(v.sc, castTp)
if err != nil {
v.err = errors.Trace(err)
}
expr.SetDatum(newVal)
} else {
castFunc := &ast.FuncCastExpr{
Expr: expr,
Tp: castTp,
FunctionType: ast.CastFunction,
}
expr = castFunc
}
expr.SetType(castTp)
}
return expr
} | [
"func",
"(",
"v",
"*",
"typeInferrer",
")",
"addCastToString",
"(",
"expr",
"ast",
".",
"ExprNode",
")",
"ast",
".",
"ExprNode",
"{",
"if",
"!",
"mysql",
".",
"IsUTF8Charset",
"(",
"expr",
".",
"GetType",
"(",
")",
".",
"Charset",
")",
"{",
"castTp",
":=",
"types",
".",
"NewFieldType",
"(",
"mysql",
".",
"TypeString",
")",
"\n",
"castTp",
".",
"Charset",
",",
"castTp",
".",
"Collate",
"=",
"types",
".",
"DefaultCharsetForType",
"(",
"mysql",
".",
"TypeString",
")",
"\n",
"if",
"val",
",",
"ok",
":=",
"expr",
".",
"(",
"*",
"ast",
".",
"ValueExpr",
")",
";",
"ok",
"{",
"newVal",
",",
"err",
":=",
"val",
".",
"Datum",
".",
"ConvertTo",
"(",
"v",
".",
"sc",
",",
"castTp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"v",
".",
"err",
"=",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"expr",
".",
"SetDatum",
"(",
"newVal",
")",
"\n",
"}",
"else",
"{",
"castFunc",
":=",
"&",
"ast",
".",
"FuncCastExpr",
"{",
"Expr",
":",
"expr",
",",
"Tp",
":",
"castTp",
",",
"FunctionType",
":",
"ast",
".",
"CastFunction",
",",
"}",
"\n",
"expr",
"=",
"castFunc",
"\n",
"}",
"\n",
"expr",
".",
"SetType",
"(",
"castTp",
")",
"\n",
"}",
"\n",
"return",
"expr",
"\n",
"}"
] | // AddCastToString adds a cast function to string type if the expr charset is not UTF8. | [
"AddCastToString",
"adds",
"a",
"cast",
"function",
"to",
"string",
"type",
"if",
"the",
"expr",
"charset",
"is",
"not",
"UTF8",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/typeinferer.go#L424-L445 | train |
chrislusf/gleam | sql/plan/typeinferer.go | convertValueToColumnTypeIfNeeded | func (v *typeInferrer) convertValueToColumnTypeIfNeeded(x *ast.PatternInExpr) {
if cn, ok := x.Expr.(*ast.ColumnNameExpr); ok && cn.Refer != nil {
ft := cn.Refer.Column.FieldType
for _, expr := range x.List {
if valueExpr, ok := expr.(*ast.ValueExpr); ok {
newDatum, err := valueExpr.Datum.ConvertTo(v.sc, &ft)
if err != nil {
v.err = errors.Trace(err)
}
cmp, err := newDatum.CompareDatum(v.sc, valueExpr.Datum)
if err != nil {
v.err = errors.Trace(err)
}
if cmp != 0 {
// The value will never match the column, do not set newDatum.
continue
}
valueExpr.SetDatum(newDatum)
}
}
if v.err != nil {
// TODO: Errors should be handled differently according to query context.
log.Printf("inferor type for pattern in error %v", v.err)
v.err = nil
}
}
} | go | func (v *typeInferrer) convertValueToColumnTypeIfNeeded(x *ast.PatternInExpr) {
if cn, ok := x.Expr.(*ast.ColumnNameExpr); ok && cn.Refer != nil {
ft := cn.Refer.Column.FieldType
for _, expr := range x.List {
if valueExpr, ok := expr.(*ast.ValueExpr); ok {
newDatum, err := valueExpr.Datum.ConvertTo(v.sc, &ft)
if err != nil {
v.err = errors.Trace(err)
}
cmp, err := newDatum.CompareDatum(v.sc, valueExpr.Datum)
if err != nil {
v.err = errors.Trace(err)
}
if cmp != 0 {
// The value will never match the column, do not set newDatum.
continue
}
valueExpr.SetDatum(newDatum)
}
}
if v.err != nil {
// TODO: Errors should be handled differently according to query context.
log.Printf("inferor type for pattern in error %v", v.err)
v.err = nil
}
}
} | [
"func",
"(",
"v",
"*",
"typeInferrer",
")",
"convertValueToColumnTypeIfNeeded",
"(",
"x",
"*",
"ast",
".",
"PatternInExpr",
")",
"{",
"if",
"cn",
",",
"ok",
":=",
"x",
".",
"Expr",
".",
"(",
"*",
"ast",
".",
"ColumnNameExpr",
")",
";",
"ok",
"&&",
"cn",
".",
"Refer",
"!=",
"nil",
"{",
"ft",
":=",
"cn",
".",
"Refer",
".",
"Column",
".",
"FieldType",
"\n",
"for",
"_",
",",
"expr",
":=",
"range",
"x",
".",
"List",
"{",
"if",
"valueExpr",
",",
"ok",
":=",
"expr",
".",
"(",
"*",
"ast",
".",
"ValueExpr",
")",
";",
"ok",
"{",
"newDatum",
",",
"err",
":=",
"valueExpr",
".",
"Datum",
".",
"ConvertTo",
"(",
"v",
".",
"sc",
",",
"&",
"ft",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"v",
".",
"err",
"=",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"cmp",
",",
"err",
":=",
"newDatum",
".",
"CompareDatum",
"(",
"v",
".",
"sc",
",",
"valueExpr",
".",
"Datum",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"v",
".",
"err",
"=",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"cmp",
"!=",
"0",
"{",
"// The value will never match the column, do not set newDatum.",
"continue",
"\n",
"}",
"\n",
"valueExpr",
".",
"SetDatum",
"(",
"newDatum",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"v",
".",
"err",
"!=",
"nil",
"{",
"// TODO: Errors should be handled differently according to query context.",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"v",
".",
"err",
")",
"\n",
"v",
".",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // ConvertValueToColumnTypeIfNeeded checks if the expr in PatternInExpr is column name,
// and casts function to the items in the list. | [
"ConvertValueToColumnTypeIfNeeded",
"checks",
"if",
"the",
"expr",
"in",
"PatternInExpr",
"is",
"column",
"name",
"and",
"casts",
"function",
"to",
"the",
"items",
"in",
"the",
"list",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/typeinferer.go#L449-L475 | train |
chrislusf/gleam | sql/util/types/mydecimal.go | DecimalDiv | func DecimalDiv(from1, from2, to *MyDecimal, fracIncr int) error {
to.resultFrac = myMinInt8(from1.resultFrac+int8(fracIncr), MaxFraction)
return doDivMod(from1, from2, to, nil, fracIncr)
} | go | func DecimalDiv(from1, from2, to *MyDecimal, fracIncr int) error {
to.resultFrac = myMinInt8(from1.resultFrac+int8(fracIncr), MaxFraction)
return doDivMod(from1, from2, to, nil, fracIncr)
} | [
"func",
"DecimalDiv",
"(",
"from1",
",",
"from2",
",",
"to",
"*",
"MyDecimal",
",",
"fracIncr",
"int",
")",
"error",
"{",
"to",
".",
"resultFrac",
"=",
"myMinInt8",
"(",
"from1",
".",
"resultFrac",
"+",
"int8",
"(",
"fracIncr",
")",
",",
"MaxFraction",
")",
"\n",
"return",
"doDivMod",
"(",
"from1",
",",
"from2",
",",
"to",
",",
"nil",
",",
"fracIncr",
")",
"\n",
"}"
] | // DecimalDiv does division of two decimals.
//
// from1 - dividend
// from2 - divisor
// to - quotient
// fracIncr - increment of fraction | [
"DecimalDiv",
"does",
"division",
"of",
"two",
"decimals",
".",
"from1",
"-",
"dividend",
"from2",
"-",
"divisor",
"to",
"-",
"quotient",
"fracIncr",
"-",
"increment",
"of",
"fraction"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/mydecimal.go#L1792-L1795 | train |
chrislusf/gleam | distributed/driver/scheduler/scheduler_fetch.go | Fetch | func (s *Scheduler) Fetch(demands []market.Demand) {
var request pb.ComputeRequest
request.Username = s.Option.Username
request.Hostname = s.Option.Hostname
request.FlowHashCode = s.Option.FlowHashcode
request.DataCenter = s.Option.DataCenter
for _, d := range demands {
taskGroup := d.Requirement.(*plan.TaskGroup)
requiredResource := taskGroup.RequiredResources()
request.ComputeResources = append(request.ComputeResources, requiredResource)
}
result, err := getResources(s.Master, &request)
if err != nil {
log.Printf("%s Failed to allocate: %v", s.Master, err)
time.Sleep(time.Millisecond * time.Duration(15000+rand.Int63n(5000)))
} else {
if len(result.Allocations) == 0 {
// log.Printf("%s No more new executors.", s.Master)
time.Sleep(time.Millisecond * time.Duration(2000+rand.Int63n(1000)))
} else {
if s.Option.DataCenter == "" {
s.Option.DataCenter = result.Allocations[0].Location.DataCenter
}
var allocatedMemory int64
for _, allocation := range result.Allocations {
s.Market.AddSupply(market.Supply{
Object: allocation,
})
allocatedMemory += allocation.Allocated.MemoryMb
}
// log.Printf("%s allocated %d executors with %d MB memory.", s.Master, len(result.Allocations), allocatedMemory)
}
}
} | go | func (s *Scheduler) Fetch(demands []market.Demand) {
var request pb.ComputeRequest
request.Username = s.Option.Username
request.Hostname = s.Option.Hostname
request.FlowHashCode = s.Option.FlowHashcode
request.DataCenter = s.Option.DataCenter
for _, d := range demands {
taskGroup := d.Requirement.(*plan.TaskGroup)
requiredResource := taskGroup.RequiredResources()
request.ComputeResources = append(request.ComputeResources, requiredResource)
}
result, err := getResources(s.Master, &request)
if err != nil {
log.Printf("%s Failed to allocate: %v", s.Master, err)
time.Sleep(time.Millisecond * time.Duration(15000+rand.Int63n(5000)))
} else {
if len(result.Allocations) == 0 {
// log.Printf("%s No more new executors.", s.Master)
time.Sleep(time.Millisecond * time.Duration(2000+rand.Int63n(1000)))
} else {
if s.Option.DataCenter == "" {
s.Option.DataCenter = result.Allocations[0].Location.DataCenter
}
var allocatedMemory int64
for _, allocation := range result.Allocations {
s.Market.AddSupply(market.Supply{
Object: allocation,
})
allocatedMemory += allocation.Allocated.MemoryMb
}
// log.Printf("%s allocated %d executors with %d MB memory.", s.Master, len(result.Allocations), allocatedMemory)
}
}
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Fetch",
"(",
"demands",
"[",
"]",
"market",
".",
"Demand",
")",
"{",
"var",
"request",
"pb",
".",
"ComputeRequest",
"\n",
"request",
".",
"Username",
"=",
"s",
".",
"Option",
".",
"Username",
"\n",
"request",
".",
"Hostname",
"=",
"s",
".",
"Option",
".",
"Hostname",
"\n",
"request",
".",
"FlowHashCode",
"=",
"s",
".",
"Option",
".",
"FlowHashcode",
"\n",
"request",
".",
"DataCenter",
"=",
"s",
".",
"Option",
".",
"DataCenter",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"demands",
"{",
"taskGroup",
":=",
"d",
".",
"Requirement",
".",
"(",
"*",
"plan",
".",
"TaskGroup",
")",
"\n",
"requiredResource",
":=",
"taskGroup",
".",
"RequiredResources",
"(",
")",
"\n",
"request",
".",
"ComputeResources",
"=",
"append",
"(",
"request",
".",
"ComputeResources",
",",
"requiredResource",
")",
"\n",
"}",
"\n\n",
"result",
",",
"err",
":=",
"getResources",
"(",
"s",
".",
"Master",
",",
"&",
"request",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"s",
".",
"Master",
",",
"err",
")",
"\n",
"time",
".",
"Sleep",
"(",
"time",
".",
"Millisecond",
"*",
"time",
".",
"Duration",
"(",
"15000",
"+",
"rand",
".",
"Int63n",
"(",
"5000",
")",
")",
")",
"\n",
"}",
"else",
"{",
"if",
"len",
"(",
"result",
".",
"Allocations",
")",
"==",
"0",
"{",
"// log.Printf(\"%s No more new executors.\", s.Master)",
"time",
".",
"Sleep",
"(",
"time",
".",
"Millisecond",
"*",
"time",
".",
"Duration",
"(",
"2000",
"+",
"rand",
".",
"Int63n",
"(",
"1000",
")",
")",
")",
"\n",
"}",
"else",
"{",
"if",
"s",
".",
"Option",
".",
"DataCenter",
"==",
"\"",
"\"",
"{",
"s",
".",
"Option",
".",
"DataCenter",
"=",
"result",
".",
"Allocations",
"[",
"0",
"]",
".",
"Location",
".",
"DataCenter",
"\n",
"}",
"\n",
"var",
"allocatedMemory",
"int64",
"\n",
"for",
"_",
",",
"allocation",
":=",
"range",
"result",
".",
"Allocations",
"{",
"s",
".",
"Market",
".",
"AddSupply",
"(",
"market",
".",
"Supply",
"{",
"Object",
":",
"allocation",
",",
"}",
")",
"\n",
"allocatedMemory",
"+=",
"allocation",
".",
"Allocated",
".",
"MemoryMb",
"\n",
"}",
"\n",
"// log.Printf(\"%s allocated %d executors with %d MB memory.\", s.Master, len(result.Allocations), allocatedMemory)",
"}",
"\n",
"}",
"\n",
"}"
] | // Requirement is TaskGroup
// Object is Agent's Location | [
"Requirement",
"is",
"TaskGroup",
"Object",
"is",
"Agent",
"s",
"Location"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/driver/scheduler/scheduler_fetch.go#L15-L49 | train |
chrislusf/gleam | flow/dataset_reduce.go | ReduceByKey | func (d *Dataset) ReduceByKey(name string, reducerId gio.ReducerId) (ret *Dataset) {
sortOption := Field(1)
return d.ReduceBy(name, reducerId, sortOption)
} | go | func (d *Dataset) ReduceByKey(name string, reducerId gio.ReducerId) (ret *Dataset) {
sortOption := Field(1)
return d.ReduceBy(name, reducerId, sortOption)
} | [
"func",
"(",
"d",
"*",
"Dataset",
")",
"ReduceByKey",
"(",
"name",
"string",
",",
"reducerId",
"gio",
".",
"ReducerId",
")",
"(",
"ret",
"*",
"Dataset",
")",
"{",
"sortOption",
":=",
"Field",
"(",
"1",
")",
"\n",
"return",
"d",
".",
"ReduceBy",
"(",
"name",
",",
"reducerId",
",",
"sortOption",
")",
"\n",
"}"
] | // ReduceByKey runs the reducer registered to the reducerId,
// combining rows with the same key fields into one row | [
"ReduceByKey",
"runs",
"the",
"reducer",
"registered",
"to",
"the",
"reducerId",
"combining",
"rows",
"with",
"the",
"same",
"key",
"fields",
"into",
"one",
"row"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_reduce.go#L14-L17 | train |
chrislusf/gleam | flow/dataset_reduce.go | Reduce | func (d *Dataset) Reduce(name string, reducerId gio.ReducerId) (ret *Dataset) {
name = name + ".Reduce"
ret = d.LocalReduceBy(name+".LocalReduce", reducerId, nil)
if len(d.Shards) > 1 {
ret = ret.MergeTo(name, 1).LocalReduceBy(name+".LocalReduce2", reducerId, nil)
}
return ret
} | go | func (d *Dataset) Reduce(name string, reducerId gio.ReducerId) (ret *Dataset) {
name = name + ".Reduce"
ret = d.LocalReduceBy(name+".LocalReduce", reducerId, nil)
if len(d.Shards) > 1 {
ret = ret.MergeTo(name, 1).LocalReduceBy(name+".LocalReduce2", reducerId, nil)
}
return ret
} | [
"func",
"(",
"d",
"*",
"Dataset",
")",
"Reduce",
"(",
"name",
"string",
",",
"reducerId",
"gio",
".",
"ReducerId",
")",
"(",
"ret",
"*",
"Dataset",
")",
"{",
"name",
"=",
"name",
"+",
"\"",
"\"",
"\n\n",
"ret",
"=",
"d",
".",
"LocalReduceBy",
"(",
"name",
"+",
"\"",
"\"",
",",
"reducerId",
",",
"nil",
")",
"\n",
"if",
"len",
"(",
"d",
".",
"Shards",
")",
">",
"1",
"{",
"ret",
"=",
"ret",
".",
"MergeTo",
"(",
"name",
",",
"1",
")",
".",
"LocalReduceBy",
"(",
"name",
"+",
"\"",
"\"",
",",
"reducerId",
",",
"nil",
")",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // Reduce runs the reducer registered to the reducerId,
// combining all rows into one row | [
"Reduce",
"runs",
"the",
"reducer",
"registered",
"to",
"the",
"reducerId",
"combining",
"all",
"rows",
"into",
"one",
"row"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_reduce.go#L33-L42 | train |
chrislusf/gleam | sql/plan/decorrelate.go | decorrelate | func decorrelate(p LogicalPlan) LogicalPlan {
if apply, ok := p.(*Apply); ok {
outerPlan := apply.children[0]
innerPlan := apply.children[1].(LogicalPlan)
apply.extractCorColumnsBySchema()
if len(apply.corCols) == 0 {
// If the inner plan is non-correlated, the apply will be simplified to join.
join := &apply.Join
innerPlan.SetParents(join)
outerPlan.SetParents(join)
p = join
} else if sel, ok := innerPlan.(*Selection); ok {
// If the inner plan is a selection, we add this condition to join predicates.
// Notice that no matter what kind of join is, it's always right.
newConds := make([]expression.Expression, 0, len(sel.Conditions))
for _, cond := range sel.Conditions {
newConds = append(newConds, cond.Decorrelate(outerPlan.GetSchema()))
}
apply.attachOnConds(newConds)
innerPlan = sel.children[0].(LogicalPlan)
apply.SetChildren(outerPlan, innerPlan)
innerPlan.SetParents(apply)
return decorrelate(p)
}
// TODO: Deal with aggregation and projection.
}
newChildren := make([]Plan, 0, len(p.GetChildren()))
for _, child := range p.GetChildren() {
newChildren = append(newChildren, decorrelate(child.(LogicalPlan)))
child.SetParents(p)
}
p.SetChildren(newChildren...)
return p
} | go | func decorrelate(p LogicalPlan) LogicalPlan {
if apply, ok := p.(*Apply); ok {
outerPlan := apply.children[0]
innerPlan := apply.children[1].(LogicalPlan)
apply.extractCorColumnsBySchema()
if len(apply.corCols) == 0 {
// If the inner plan is non-correlated, the apply will be simplified to join.
join := &apply.Join
innerPlan.SetParents(join)
outerPlan.SetParents(join)
p = join
} else if sel, ok := innerPlan.(*Selection); ok {
// If the inner plan is a selection, we add this condition to join predicates.
// Notice that no matter what kind of join is, it's always right.
newConds := make([]expression.Expression, 0, len(sel.Conditions))
for _, cond := range sel.Conditions {
newConds = append(newConds, cond.Decorrelate(outerPlan.GetSchema()))
}
apply.attachOnConds(newConds)
innerPlan = sel.children[0].(LogicalPlan)
apply.SetChildren(outerPlan, innerPlan)
innerPlan.SetParents(apply)
return decorrelate(p)
}
// TODO: Deal with aggregation and projection.
}
newChildren := make([]Plan, 0, len(p.GetChildren()))
for _, child := range p.GetChildren() {
newChildren = append(newChildren, decorrelate(child.(LogicalPlan)))
child.SetParents(p)
}
p.SetChildren(newChildren...)
return p
} | [
"func",
"decorrelate",
"(",
"p",
"LogicalPlan",
")",
"LogicalPlan",
"{",
"if",
"apply",
",",
"ok",
":=",
"p",
".",
"(",
"*",
"Apply",
")",
";",
"ok",
"{",
"outerPlan",
":=",
"apply",
".",
"children",
"[",
"0",
"]",
"\n",
"innerPlan",
":=",
"apply",
".",
"children",
"[",
"1",
"]",
".",
"(",
"LogicalPlan",
")",
"\n",
"apply",
".",
"extractCorColumnsBySchema",
"(",
")",
"\n",
"if",
"len",
"(",
"apply",
".",
"corCols",
")",
"==",
"0",
"{",
"// If the inner plan is non-correlated, the apply will be simplified to join.",
"join",
":=",
"&",
"apply",
".",
"Join",
"\n",
"innerPlan",
".",
"SetParents",
"(",
"join",
")",
"\n",
"outerPlan",
".",
"SetParents",
"(",
"join",
")",
"\n",
"p",
"=",
"join",
"\n",
"}",
"else",
"if",
"sel",
",",
"ok",
":=",
"innerPlan",
".",
"(",
"*",
"Selection",
")",
";",
"ok",
"{",
"// If the inner plan is a selection, we add this condition to join predicates.",
"// Notice that no matter what kind of join is, it's always right.",
"newConds",
":=",
"make",
"(",
"[",
"]",
"expression",
".",
"Expression",
",",
"0",
",",
"len",
"(",
"sel",
".",
"Conditions",
")",
")",
"\n",
"for",
"_",
",",
"cond",
":=",
"range",
"sel",
".",
"Conditions",
"{",
"newConds",
"=",
"append",
"(",
"newConds",
",",
"cond",
".",
"Decorrelate",
"(",
"outerPlan",
".",
"GetSchema",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"apply",
".",
"attachOnConds",
"(",
"newConds",
")",
"\n",
"innerPlan",
"=",
"sel",
".",
"children",
"[",
"0",
"]",
".",
"(",
"LogicalPlan",
")",
"\n",
"apply",
".",
"SetChildren",
"(",
"outerPlan",
",",
"innerPlan",
")",
"\n",
"innerPlan",
".",
"SetParents",
"(",
"apply",
")",
"\n",
"return",
"decorrelate",
"(",
"p",
")",
"\n",
"}",
"\n",
"// TODO: Deal with aggregation and projection.",
"}",
"\n",
"newChildren",
":=",
"make",
"(",
"[",
"]",
"Plan",
",",
"0",
",",
"len",
"(",
"p",
".",
"GetChildren",
"(",
")",
")",
")",
"\n",
"for",
"_",
",",
"child",
":=",
"range",
"p",
".",
"GetChildren",
"(",
")",
"{",
"newChildren",
"=",
"append",
"(",
"newChildren",
",",
"decorrelate",
"(",
"child",
".",
"(",
"LogicalPlan",
")",
")",
")",
"\n",
"child",
".",
"SetParents",
"(",
"p",
")",
"\n",
"}",
"\n",
"p",
".",
"SetChildren",
"(",
"newChildren",
"...",
")",
"\n",
"return",
"p",
"\n",
"}"
] | // decorrelate function tries to convert apply plan to join plan. | [
"decorrelate",
"function",
"tries",
"to",
"convert",
"apply",
"plan",
"to",
"join",
"plan",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/decorrelate.go#L52-L85 | train |
chrislusf/gleam | util/buf_writer.go | BufWrites | func BufWrites(rawWriters []io.Writer, function func([]io.Writer)) {
var writers []io.Writer
var bufWriters []*bufio.Writer
for _, w := range rawWriters {
if bufWriter, ok := w.(*bufio.Writer); ok {
writers = append(writers, bufWriter)
} else {
bufWriter = bufio.NewWriter(w)
bufWriters = append(bufWriters, bufWriter)
writers = append(writers, bufWriter)
}
}
function(writers)
for _, w := range bufWriters {
w.Flush()
}
} | go | func BufWrites(rawWriters []io.Writer, function func([]io.Writer)) {
var writers []io.Writer
var bufWriters []*bufio.Writer
for _, w := range rawWriters {
if bufWriter, ok := w.(*bufio.Writer); ok {
writers = append(writers, bufWriter)
} else {
bufWriter = bufio.NewWriter(w)
bufWriters = append(bufWriters, bufWriter)
writers = append(writers, bufWriter)
}
}
function(writers)
for _, w := range bufWriters {
w.Flush()
}
} | [
"func",
"BufWrites",
"(",
"rawWriters",
"[",
"]",
"io",
".",
"Writer",
",",
"function",
"func",
"(",
"[",
"]",
"io",
".",
"Writer",
")",
")",
"{",
"var",
"writers",
"[",
"]",
"io",
".",
"Writer",
"\n",
"var",
"bufWriters",
"[",
"]",
"*",
"bufio",
".",
"Writer",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"rawWriters",
"{",
"if",
"bufWriter",
",",
"ok",
":=",
"w",
".",
"(",
"*",
"bufio",
".",
"Writer",
")",
";",
"ok",
"{",
"writers",
"=",
"append",
"(",
"writers",
",",
"bufWriter",
")",
"\n",
"}",
"else",
"{",
"bufWriter",
"=",
"bufio",
".",
"NewWriter",
"(",
"w",
")",
"\n",
"bufWriters",
"=",
"append",
"(",
"bufWriters",
",",
"bufWriter",
")",
"\n",
"writers",
"=",
"append",
"(",
"writers",
",",
"bufWriter",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"function",
"(",
"writers",
")",
"\n\n",
"for",
"_",
",",
"w",
":=",
"range",
"bufWriters",
"{",
"w",
".",
"Flush",
"(",
")",
"\n",
"}",
"\n\n",
"}"
] | // BufWrites ensures all writers are bufio.Writer
// For any bufio.Writer created here, flush it before returning. | [
"BufWrites",
"ensures",
"all",
"writers",
"are",
"bufio",
".",
"Writer",
"For",
"any",
"bufio",
".",
"Writer",
"created",
"here",
"flush",
"it",
"before",
"returning",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/buf_writer.go#L10-L29 | train |
chrislusf/gleam | sql/parser/lexer.go | reset | func (s *Scanner) reset(sql string) {
s.r = reader{s: sql}
s.buf.Reset()
s.errs = s.errs[:0]
s.stmtStartPos = 0
} | go | func (s *Scanner) reset(sql string) {
s.r = reader{s: sql}
s.buf.Reset()
s.errs = s.errs[:0]
s.stmtStartPos = 0
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"reset",
"(",
"sql",
"string",
")",
"{",
"s",
".",
"r",
"=",
"reader",
"{",
"s",
":",
"sql",
"}",
"\n",
"s",
".",
"buf",
".",
"Reset",
"(",
")",
"\n",
"s",
".",
"errs",
"=",
"s",
".",
"errs",
"[",
":",
"0",
"]",
"\n",
"s",
".",
"stmtStartPos",
"=",
"0",
"\n",
"}"
] | // reset resets the sql string to be scanned. | [
"reset",
"resets",
"the",
"sql",
"string",
"to",
"be",
"scanned",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/parser/lexer.go#L56-L61 | train |
chrislusf/gleam | sql/parser/lexer.go | Errorf | func (s *Scanner) Errorf(format string, a ...interface{}) {
str := fmt.Sprintf(format, a...)
val := s.r.s[s.r.pos().Offset:]
if len(val) > 2048 {
val = val[:2048]
}
err := fmt.Errorf("line %d column %d near \"%s\"%s (total length %d)", s.r.p.Line, s.r.p.Col, val, str, len(s.r.s))
s.errs = append(s.errs, err)
} | go | func (s *Scanner) Errorf(format string, a ...interface{}) {
str := fmt.Sprintf(format, a...)
val := s.r.s[s.r.pos().Offset:]
if len(val) > 2048 {
val = val[:2048]
}
err := fmt.Errorf("line %d column %d near \"%s\"%s (total length %d)", s.r.p.Line, s.r.p.Col, val, str, len(s.r.s))
s.errs = append(s.errs, err)
} | [
"func",
"(",
"s",
"*",
"Scanner",
")",
"Errorf",
"(",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"{",
"str",
":=",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"a",
"...",
")",
"\n",
"val",
":=",
"s",
".",
"r",
".",
"s",
"[",
"s",
".",
"r",
".",
"pos",
"(",
")",
".",
"Offset",
":",
"]",
"\n",
"if",
"len",
"(",
"val",
")",
">",
"2048",
"{",
"val",
"=",
"val",
"[",
":",
"2048",
"]",
"\n",
"}",
"\n",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"s",
".",
"r",
".",
"p",
".",
"Line",
",",
"s",
".",
"r",
".",
"p",
".",
"Col",
",",
"val",
",",
"str",
",",
"len",
"(",
"s",
".",
"r",
".",
"s",
")",
")",
"\n",
"s",
".",
"errs",
"=",
"append",
"(",
"s",
".",
"errs",
",",
"err",
")",
"\n",
"}"
] | // Errorf tells scanner something is wrong.
// Scanner satisfies yyLexer interface which need this function. | [
"Errorf",
"tells",
"scanner",
"something",
"is",
"wrong",
".",
"Scanner",
"satisfies",
"yyLexer",
"interface",
"which",
"need",
"this",
"function",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/parser/lexer.go#L80-L88 | train |
chrislusf/gleam | sql/parser/lexer.go | handleEscape | func handleEscape(s *Scanner) rune {
s.r.inc()
ch0 := s.r.peek()
/*
\" \' \\ \n \0 \b \Z \r \t ==> escape to one char
\% \_ ==> preserve both char
other ==> remove \
*/
switch ch0 {
case 'n':
ch0 = '\n'
case '0':
ch0 = 0
case 'b':
ch0 = 8
case 'Z':
ch0 = 26
case 'r':
ch0 = '\r'
case 't':
ch0 = '\t'
case '%', '_':
s.buf.WriteByte('\\')
}
return ch0
} | go | func handleEscape(s *Scanner) rune {
s.r.inc()
ch0 := s.r.peek()
/*
\" \' \\ \n \0 \b \Z \r \t ==> escape to one char
\% \_ ==> preserve both char
other ==> remove \
*/
switch ch0 {
case 'n':
ch0 = '\n'
case '0':
ch0 = 0
case 'b':
ch0 = 8
case 'Z':
ch0 = 26
case 'r':
ch0 = '\r'
case 't':
ch0 = '\t'
case '%', '_':
s.buf.WriteByte('\\')
}
return ch0
} | [
"func",
"handleEscape",
"(",
"s",
"*",
"Scanner",
")",
"rune",
"{",
"s",
".",
"r",
".",
"inc",
"(",
")",
"\n",
"ch0",
":=",
"s",
".",
"r",
".",
"peek",
"(",
")",
"\n",
"/*\n\t\t\\\" \\' \\\\ \\n \\0 \\b \\Z \\r \\t ==> escape to one char\n\t\t\\% \\_ ==> preserve both char\n\t\tother ==> remove \\\n\t*/",
"switch",
"ch0",
"{",
"case",
"'n'",
":",
"ch0",
"=",
"'\\n'",
"\n",
"case",
"'0'",
":",
"ch0",
"=",
"0",
"\n",
"case",
"'b'",
":",
"ch0",
"=",
"8",
"\n",
"case",
"'Z'",
":",
"ch0",
"=",
"26",
"\n",
"case",
"'r'",
":",
"ch0",
"=",
"'\\r'",
"\n",
"case",
"'t'",
":",
"ch0",
"=",
"'\\t'",
"\n",
"case",
"'%'",
",",
"'_'",
":",
"s",
".",
"buf",
".",
"WriteByte",
"(",
"'\\\\'",
")",
"\n",
"}",
"\n",
"return",
"ch0",
"\n",
"}"
] | // handleEscape handles the case in scanString when previous char is '\'. | [
"handleEscape",
"handles",
"the",
"case",
"in",
"scanString",
"when",
"previous",
"char",
"is",
"\\",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/parser/lexer.go#L450-L475 | train |
chrislusf/gleam | sql/parser/lexer.go | inc | func (r *reader) inc() {
if r.s[r.p.Offset] == '\n' {
r.p.Line++
r.p.Col = 0
}
r.p.Offset += r.w
r.p.Col++
} | go | func (r *reader) inc() {
if r.s[r.p.Offset] == '\n' {
r.p.Line++
r.p.Col = 0
}
r.p.Offset += r.w
r.p.Col++
} | [
"func",
"(",
"r",
"*",
"reader",
")",
"inc",
"(",
")",
"{",
"if",
"r",
".",
"s",
"[",
"r",
".",
"p",
".",
"Offset",
"]",
"==",
"'\\n'",
"{",
"r",
".",
"p",
".",
"Line",
"++",
"\n",
"r",
".",
"p",
".",
"Col",
"=",
"0",
"\n",
"}",
"\n",
"r",
".",
"p",
".",
"Offset",
"+=",
"r",
".",
"w",
"\n",
"r",
".",
"p",
".",
"Col",
"++",
"\n",
"}"
] | // inc increase the position offset of the reader.
// peek must be called before calling inc! | [
"inc",
"increase",
"the",
"position",
"offset",
"of",
"the",
"reader",
".",
"peek",
"must",
"be",
"called",
"before",
"calling",
"inc!"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/parser/lexer.go#L622-L629 | train |
chrislusf/gleam | sql/plan/logical_plans.go | addChild | func addChild(parent Plan, child Plan) {
if child == nil || parent == nil {
return
}
child.AddParent(parent)
parent.AddChild(child)
} | go | func addChild(parent Plan, child Plan) {
if child == nil || parent == nil {
return
}
child.AddParent(parent)
parent.AddChild(child)
} | [
"func",
"addChild",
"(",
"parent",
"Plan",
",",
"child",
"Plan",
")",
"{",
"if",
"child",
"==",
"nil",
"||",
"parent",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"child",
".",
"AddParent",
"(",
"parent",
")",
"\n",
"parent",
".",
"AddChild",
"(",
"child",
")",
"\n",
"}"
] | // AddChild for parent. | [
"AddChild",
"for",
"parent",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/logical_plans.go#L288-L294 | train |
chrislusf/gleam | sql/plan/logical_plans.go | InsertPlan | func InsertPlan(parent Plan, child Plan, insert Plan) error {
err := child.ReplaceParent(parent, insert)
if err != nil {
return errors.Trace(err)
}
err = parent.ReplaceChild(child, insert)
if err != nil {
return errors.Trace(err)
}
insert.AddChild(child)
insert.AddParent(parent)
return nil
} | go | func InsertPlan(parent Plan, child Plan, insert Plan) error {
err := child.ReplaceParent(parent, insert)
if err != nil {
return errors.Trace(err)
}
err = parent.ReplaceChild(child, insert)
if err != nil {
return errors.Trace(err)
}
insert.AddChild(child)
insert.AddParent(parent)
return nil
} | [
"func",
"InsertPlan",
"(",
"parent",
"Plan",
",",
"child",
"Plan",
",",
"insert",
"Plan",
")",
"error",
"{",
"err",
":=",
"child",
".",
"ReplaceParent",
"(",
"parent",
",",
"insert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"parent",
".",
"ReplaceChild",
"(",
"child",
",",
"insert",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"insert",
".",
"AddChild",
"(",
"child",
")",
"\n",
"insert",
".",
"AddParent",
"(",
"parent",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // InsertPlan means inserting plan between two plans. | [
"InsertPlan",
"means",
"inserting",
"plan",
"between",
"two",
"plans",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/logical_plans.go#L297-L309 | train |
chrislusf/gleam | sql/plan/logical_plans.go | RemovePlan | func RemovePlan(p Plan) error {
parents := p.GetParents()
children := p.GetChildren()
if len(parents) > 1 || len(children) != 1 {
return SystemInternalErrorType.Gen("can't remove this plan")
}
if len(parents) == 0 {
child := children[0]
child.SetParents()
return nil
}
parent, child := parents[0], children[0]
err := parent.ReplaceChild(p, child)
if err != nil {
return errors.Trace(err)
}
err = child.ReplaceParent(p, parent)
return errors.Trace(err)
} | go | func RemovePlan(p Plan) error {
parents := p.GetParents()
children := p.GetChildren()
if len(parents) > 1 || len(children) != 1 {
return SystemInternalErrorType.Gen("can't remove this plan")
}
if len(parents) == 0 {
child := children[0]
child.SetParents()
return nil
}
parent, child := parents[0], children[0]
err := parent.ReplaceChild(p, child)
if err != nil {
return errors.Trace(err)
}
err = child.ReplaceParent(p, parent)
return errors.Trace(err)
} | [
"func",
"RemovePlan",
"(",
"p",
"Plan",
")",
"error",
"{",
"parents",
":=",
"p",
".",
"GetParents",
"(",
")",
"\n",
"children",
":=",
"p",
".",
"GetChildren",
"(",
")",
"\n",
"if",
"len",
"(",
"parents",
")",
">",
"1",
"||",
"len",
"(",
"children",
")",
"!=",
"1",
"{",
"return",
"SystemInternalErrorType",
".",
"Gen",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"parents",
")",
"==",
"0",
"{",
"child",
":=",
"children",
"[",
"0",
"]",
"\n",
"child",
".",
"SetParents",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"parent",
",",
"child",
":=",
"parents",
"[",
"0",
"]",
",",
"children",
"[",
"0",
"]",
"\n",
"err",
":=",
"parent",
".",
"ReplaceChild",
"(",
"p",
",",
"child",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"child",
".",
"ReplaceParent",
"(",
"p",
",",
"parent",
")",
"\n",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // RemovePlan means removing a plan. | [
"RemovePlan",
"means",
"removing",
"a",
"plan",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/logical_plans.go#L312-L330 | train |
chrislusf/gleam | flow/dataset_map.go | Map | func (d *Dataset) Map(name string, mapperId gio.MapperId) *Dataset {
ret, step := add1ShardTo1Step(d)
step.Name = name + ".Map"
step.IsPipe = false
step.IsGoCode = true
ex, _ := os.Executable()
mapper, _ := gio.GetMapper(mapperId)
step.Description = mapper.Name
var args []string
args = append(args, os.Args[1:]...)
args = append(args, "-gleam.mapper", string(mapperId))
step.Command = &script.Command{
Path: ex,
Args: args,
}
return ret
} | go | func (d *Dataset) Map(name string, mapperId gio.MapperId) *Dataset {
ret, step := add1ShardTo1Step(d)
step.Name = name + ".Map"
step.IsPipe = false
step.IsGoCode = true
ex, _ := os.Executable()
mapper, _ := gio.GetMapper(mapperId)
step.Description = mapper.Name
var args []string
args = append(args, os.Args[1:]...)
args = append(args, "-gleam.mapper", string(mapperId))
step.Command = &script.Command{
Path: ex,
Args: args,
}
return ret
} | [
"func",
"(",
"d",
"*",
"Dataset",
")",
"Map",
"(",
"name",
"string",
",",
"mapperId",
"gio",
".",
"MapperId",
")",
"*",
"Dataset",
"{",
"ret",
",",
"step",
":=",
"add1ShardTo1Step",
"(",
"d",
")",
"\n",
"step",
".",
"Name",
"=",
"name",
"+",
"\"",
"\"",
"\n",
"step",
".",
"IsPipe",
"=",
"false",
"\n",
"step",
".",
"IsGoCode",
"=",
"true",
"\n\n",
"ex",
",",
"_",
":=",
"os",
".",
"Executable",
"(",
")",
"\n\n",
"mapper",
",",
"_",
":=",
"gio",
".",
"GetMapper",
"(",
"mapperId",
")",
"\n",
"step",
".",
"Description",
"=",
"mapper",
".",
"Name",
"\n\n",
"var",
"args",
"[",
"]",
"string",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"os",
".",
"Args",
"[",
"1",
":",
"]",
"...",
")",
"\n",
"args",
"=",
"append",
"(",
"args",
",",
"\"",
"\"",
",",
"string",
"(",
"mapperId",
")",
")",
"\n",
"step",
".",
"Command",
"=",
"&",
"script",
".",
"Command",
"{",
"Path",
":",
"ex",
",",
"Args",
":",
"args",
",",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // Mapper runs the mapper registered to the mapperId.
// This is used to execute pure Go code. | [
"Mapper",
"runs",
"the",
"mapper",
"registered",
"to",
"the",
"mapperId",
".",
"This",
"is",
"used",
"to",
"execute",
"pure",
"Go",
"code",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_map.go#L14-L33 | train |
chrislusf/gleam | flow/dataset_map.go | Select | func (d *Dataset) Select(name string, sortOption *SortOption) *Dataset {
ret, step := add1ShardTo1Step(d)
indexes := sortOption.Indexes()
step.SetInstruction(name, instruction.NewSelect([]int{indexes[0]}, indexes[1:]))
step.Description = fmt.Sprintf("select %v", sortOption.Indexes())
return ret
} | go | func (d *Dataset) Select(name string, sortOption *SortOption) *Dataset {
ret, step := add1ShardTo1Step(d)
indexes := sortOption.Indexes()
step.SetInstruction(name, instruction.NewSelect([]int{indexes[0]}, indexes[1:]))
step.Description = fmt.Sprintf("select %v", sortOption.Indexes())
return ret
} | [
"func",
"(",
"d",
"*",
"Dataset",
")",
"Select",
"(",
"name",
"string",
",",
"sortOption",
"*",
"SortOption",
")",
"*",
"Dataset",
"{",
"ret",
",",
"step",
":=",
"add1ShardTo1Step",
"(",
"d",
")",
"\n",
"indexes",
":=",
"sortOption",
".",
"Indexes",
"(",
")",
"\n",
"step",
".",
"SetInstruction",
"(",
"name",
",",
"instruction",
".",
"NewSelect",
"(",
"[",
"]",
"int",
"{",
"indexes",
"[",
"0",
"]",
"}",
",",
"indexes",
"[",
"1",
":",
"]",
")",
")",
"\n",
"step",
".",
"Description",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sortOption",
".",
"Indexes",
"(",
")",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // Select selects multiple fields into the next dataset. The index starts from 1.
// The first one is the key | [
"Select",
"selects",
"multiple",
"fields",
"into",
"the",
"next",
"dataset",
".",
"The",
"index",
"starts",
"from",
"1",
".",
"The",
"first",
"one",
"is",
"the",
"key"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_map.go#L43-L49 | train |
chrislusf/gleam | flow/dataset_map.go | SelectKV | func (d *Dataset) SelectKV(name string, keys, values *SortOption) *Dataset {
ret, step := add1ShardTo1Step(d)
step.SetInstruction(name, instruction.NewSelect(keys.Indexes(), values.Indexes()))
return ret
} | go | func (d *Dataset) SelectKV(name string, keys, values *SortOption) *Dataset {
ret, step := add1ShardTo1Step(d)
step.SetInstruction(name, instruction.NewSelect(keys.Indexes(), values.Indexes()))
return ret
} | [
"func",
"(",
"d",
"*",
"Dataset",
")",
"SelectKV",
"(",
"name",
"string",
",",
"keys",
",",
"values",
"*",
"SortOption",
")",
"*",
"Dataset",
"{",
"ret",
",",
"step",
":=",
"add1ShardTo1Step",
"(",
"d",
")",
"\n",
"step",
".",
"SetInstruction",
"(",
"name",
",",
"instruction",
".",
"NewSelect",
"(",
"keys",
".",
"Indexes",
"(",
")",
",",
"values",
".",
"Indexes",
"(",
")",
")",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // Select selects multiple fields into the next dataset. The index starts from 1. | [
"Select",
"selects",
"multiple",
"fields",
"into",
"the",
"next",
"dataset",
".",
"The",
"index",
"starts",
"from",
"1",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_map.go#L52-L56 | train |
chrislusf/gleam | flow/dataset_map.go | LocalLimit | func (d *Dataset) LocalLimit(name string, n int, offset int) *Dataset {
ret, step := add1ShardTo1Step(d)
ret.IsLocalSorted = d.IsLocalSorted
ret.IsPartitionedBy = d.IsPartitionedBy
step.SetInstruction(name, instruction.NewLocalLimit(n, offset))
step.Description = fmt.Sprintf("local limit %d", n)
return ret
} | go | func (d *Dataset) LocalLimit(name string, n int, offset int) *Dataset {
ret, step := add1ShardTo1Step(d)
ret.IsLocalSorted = d.IsLocalSorted
ret.IsPartitionedBy = d.IsPartitionedBy
step.SetInstruction(name, instruction.NewLocalLimit(n, offset))
step.Description = fmt.Sprintf("local limit %d", n)
return ret
} | [
"func",
"(",
"d",
"*",
"Dataset",
")",
"LocalLimit",
"(",
"name",
"string",
",",
"n",
"int",
",",
"offset",
"int",
")",
"*",
"Dataset",
"{",
"ret",
",",
"step",
":=",
"add1ShardTo1Step",
"(",
"d",
")",
"\n",
"ret",
".",
"IsLocalSorted",
"=",
"d",
".",
"IsLocalSorted",
"\n",
"ret",
".",
"IsPartitionedBy",
"=",
"d",
".",
"IsPartitionedBy",
"\n",
"step",
".",
"SetInstruction",
"(",
"name",
",",
"instruction",
".",
"NewLocalLimit",
"(",
"n",
",",
"offset",
")",
")",
"\n",
"step",
".",
"Description",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"n",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // LocalLimit take the local first n rows and skip all other rows. | [
"LocalLimit",
"take",
"the",
"local",
"first",
"n",
"rows",
"and",
"skip",
"all",
"other",
"rows",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_map.go#L59-L66 | train |
chrislusf/gleam | distributed/plan/plan_logical.go | findAncestorStepId | func findAncestorStepId(step *flow.Step) (int, bool) {
current := step
taskCount := len(current.Tasks)
// println("find step", step.Name)
for taskCount == len(current.Tasks) {
if len(current.InputDatasets) > 1 {
// more than 2 dataset inputs
break
}
if len(current.InputDatasets) == 0 {
// no dataset inputs
break
}
if !isMergeableDataset(current.InputDatasets[0], taskCount) {
break
}
if (!current.IsOnDriverSide && current.InputDatasets[0].Step.IsOnDriverSide) ||
(current.IsOnDriverSide && !current.InputDatasets[0].Step.IsOnDriverSide) {
break
}
current = current.InputDatasets[0].Step
taskCount = len(current.Tasks)
}
return current.Id, true
} | go | func findAncestorStepId(step *flow.Step) (int, bool) {
current := step
taskCount := len(current.Tasks)
// println("find step", step.Name)
for taskCount == len(current.Tasks) {
if len(current.InputDatasets) > 1 {
// more than 2 dataset inputs
break
}
if len(current.InputDatasets) == 0 {
// no dataset inputs
break
}
if !isMergeableDataset(current.InputDatasets[0], taskCount) {
break
}
if (!current.IsOnDriverSide && current.InputDatasets[0].Step.IsOnDriverSide) ||
(current.IsOnDriverSide && !current.InputDatasets[0].Step.IsOnDriverSide) {
break
}
current = current.InputDatasets[0].Step
taskCount = len(current.Tasks)
}
return current.Id, true
} | [
"func",
"findAncestorStepId",
"(",
"step",
"*",
"flow",
".",
"Step",
")",
"(",
"int",
",",
"bool",
")",
"{",
"current",
":=",
"step",
"\n",
"taskCount",
":=",
"len",
"(",
"current",
".",
"Tasks",
")",
"\n\n",
"// println(\"find step\", step.Name)",
"for",
"taskCount",
"==",
"len",
"(",
"current",
".",
"Tasks",
")",
"{",
"if",
"len",
"(",
"current",
".",
"InputDatasets",
")",
">",
"1",
"{",
"// more than 2 dataset inputs",
"break",
"\n",
"}",
"\n",
"if",
"len",
"(",
"current",
".",
"InputDatasets",
")",
"==",
"0",
"{",
"// no dataset inputs",
"break",
"\n",
"}",
"\n",
"if",
"!",
"isMergeableDataset",
"(",
"current",
".",
"InputDatasets",
"[",
"0",
"]",
",",
"taskCount",
")",
"{",
"break",
"\n",
"}",
"\n",
"if",
"(",
"!",
"current",
".",
"IsOnDriverSide",
"&&",
"current",
".",
"InputDatasets",
"[",
"0",
"]",
".",
"Step",
".",
"IsOnDriverSide",
")",
"||",
"(",
"current",
".",
"IsOnDriverSide",
"&&",
"!",
"current",
".",
"InputDatasets",
"[",
"0",
"]",
".",
"Step",
".",
"IsOnDriverSide",
")",
"{",
"break",
"\n",
"}",
"\n\n",
"current",
"=",
"current",
".",
"InputDatasets",
"[",
"0",
"]",
".",
"Step",
"\n",
"taskCount",
"=",
"len",
"(",
"current",
".",
"Tasks",
")",
"\n\n",
"}",
"\n",
"return",
"current",
".",
"Id",
",",
"true",
"\n",
"}"
] | // find mergeable parent step or itself if parent is not mergeable | [
"find",
"mergeable",
"parent",
"step",
"or",
"itself",
"if",
"parent",
"is",
"not",
"mergeable"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/plan/plan_logical.go#L28-L56 | train |
chrislusf/gleam | distributed/plan/plan_logical.go | translateToStepGroups | func translateToStepGroups(fc *flow.Flow) []*StepGroup {
// use array instead of map to ensure consistent ordering
stepId2StepGroup := make([]*StepGroup, len(fc.Steps))
for _, step := range fc.Steps {
// println("step:", step.Name, step.Id, "starting...")
ancestorStepId, foundStepId := findAncestorStepId(step)
if !foundStepId {
println("step:", step.Id, "Not found ancestorStepId.")
continue
}
// println("step:", step.Name, step.Id, "ancestorStepId", ancestorStepId)
if stepId2StepGroup[ancestorStepId] == nil {
stepId2StepGroup[ancestorStepId] = NewStepGroup()
for _, ds := range step.InputDatasets {
parentDsId, hasParentIdId := findAncestorStepId(ds.Step)
if !hasParentIdId {
// since we add steps following the same order as the code
log.Panic("parent StepGroup should already be in the map")
}
parentSg := stepId2StepGroup[parentDsId]
if parentSg == nil {
// since we add steps following the same order as the code
log.Panic("parent StepGroup should already be in the map")
}
stepId2StepGroup[ancestorStepId].AddParent(parentSg)
}
}
stepId2StepGroup[ancestorStepId].AddStep(step)
}
// shrink
var ret []*StepGroup
for _, stepGroup := range stepId2StepGroup {
if stepGroup == nil || len(stepGroup.Steps) == 0 {
continue
}
// println("add step group started by", stepGroup.Steps[0].Name, "with", len(stepGroup.Steps), "steps")
ret = append(ret, stepGroup)
}
return ret
} | go | func translateToStepGroups(fc *flow.Flow) []*StepGroup {
// use array instead of map to ensure consistent ordering
stepId2StepGroup := make([]*StepGroup, len(fc.Steps))
for _, step := range fc.Steps {
// println("step:", step.Name, step.Id, "starting...")
ancestorStepId, foundStepId := findAncestorStepId(step)
if !foundStepId {
println("step:", step.Id, "Not found ancestorStepId.")
continue
}
// println("step:", step.Name, step.Id, "ancestorStepId", ancestorStepId)
if stepId2StepGroup[ancestorStepId] == nil {
stepId2StepGroup[ancestorStepId] = NewStepGroup()
for _, ds := range step.InputDatasets {
parentDsId, hasParentIdId := findAncestorStepId(ds.Step)
if !hasParentIdId {
// since we add steps following the same order as the code
log.Panic("parent StepGroup should already be in the map")
}
parentSg := stepId2StepGroup[parentDsId]
if parentSg == nil {
// since we add steps following the same order as the code
log.Panic("parent StepGroup should already be in the map")
}
stepId2StepGroup[ancestorStepId].AddParent(parentSg)
}
}
stepId2StepGroup[ancestorStepId].AddStep(step)
}
// shrink
var ret []*StepGroup
for _, stepGroup := range stepId2StepGroup {
if stepGroup == nil || len(stepGroup.Steps) == 0 {
continue
}
// println("add step group started by", stepGroup.Steps[0].Name, "with", len(stepGroup.Steps), "steps")
ret = append(ret, stepGroup)
}
return ret
} | [
"func",
"translateToStepGroups",
"(",
"fc",
"*",
"flow",
".",
"Flow",
")",
"[",
"]",
"*",
"StepGroup",
"{",
"// use array instead of map to ensure consistent ordering",
"stepId2StepGroup",
":=",
"make",
"(",
"[",
"]",
"*",
"StepGroup",
",",
"len",
"(",
"fc",
".",
"Steps",
")",
")",
"\n",
"for",
"_",
",",
"step",
":=",
"range",
"fc",
".",
"Steps",
"{",
"// println(\"step:\", step.Name, step.Id, \"starting...\")",
"ancestorStepId",
",",
"foundStepId",
":=",
"findAncestorStepId",
"(",
"step",
")",
"\n",
"if",
"!",
"foundStepId",
"{",
"println",
"(",
"\"",
"\"",
",",
"step",
".",
"Id",
",",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"// println(\"step:\", step.Name, step.Id, \"ancestorStepId\", ancestorStepId)",
"if",
"stepId2StepGroup",
"[",
"ancestorStepId",
"]",
"==",
"nil",
"{",
"stepId2StepGroup",
"[",
"ancestorStepId",
"]",
"=",
"NewStepGroup",
"(",
")",
"\n",
"for",
"_",
",",
"ds",
":=",
"range",
"step",
".",
"InputDatasets",
"{",
"parentDsId",
",",
"hasParentIdId",
":=",
"findAncestorStepId",
"(",
"ds",
".",
"Step",
")",
"\n",
"if",
"!",
"hasParentIdId",
"{",
"// since we add steps following the same order as the code",
"log",
".",
"Panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"parentSg",
":=",
"stepId2StepGroup",
"[",
"parentDsId",
"]",
"\n",
"if",
"parentSg",
"==",
"nil",
"{",
"// since we add steps following the same order as the code",
"log",
".",
"Panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"stepId2StepGroup",
"[",
"ancestorStepId",
"]",
".",
"AddParent",
"(",
"parentSg",
")",
"\n",
"}",
"\n",
"}",
"\n",
"stepId2StepGroup",
"[",
"ancestorStepId",
"]",
".",
"AddStep",
"(",
"step",
")",
"\n",
"}",
"\n",
"// shrink",
"var",
"ret",
"[",
"]",
"*",
"StepGroup",
"\n",
"for",
"_",
",",
"stepGroup",
":=",
"range",
"stepId2StepGroup",
"{",
"if",
"stepGroup",
"==",
"nil",
"||",
"len",
"(",
"stepGroup",
".",
"Steps",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"// println(\"add step group started by\", stepGroup.Steps[0].Name, \"with\", len(stepGroup.Steps), \"steps\")",
"ret",
"=",
"append",
"(",
"ret",
",",
"stepGroup",
")",
"\n",
"}",
"\n\n",
"return",
"ret",
"\n",
"}"
] | // group local steps into one step group | [
"group",
"local",
"steps",
"into",
"one",
"step",
"group"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/plan/plan_logical.go#L59-L99 | train |
chrislusf/gleam | sql/util/types/field_type.go | Init | func (ft *FieldType) Init(tp byte) {
ft.Tp = tp
ft.Flen = UnspecifiedLength
ft.Decimal = UnspecifiedLength
} | go | func (ft *FieldType) Init(tp byte) {
ft.Tp = tp
ft.Flen = UnspecifiedLength
ft.Decimal = UnspecifiedLength
} | [
"func",
"(",
"ft",
"*",
"FieldType",
")",
"Init",
"(",
"tp",
"byte",
")",
"{",
"ft",
".",
"Tp",
"=",
"tp",
"\n",
"ft",
".",
"Flen",
"=",
"UnspecifiedLength",
"\n",
"ft",
".",
"Decimal",
"=",
"UnspecifiedLength",
"\n",
"}"
] | // Init initializes the FieldType data. | [
"Init",
"initializes",
"the",
"FieldType",
"data",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/field_type.go#L52-L56 | train |
chrislusf/gleam | sql/util/types/field_type.go | String | func (ft *FieldType) String() string {
strs := []string{ft.CompactStr()}
if mysql.HasUnsignedFlag(ft.Flag) {
strs = append(strs, "UNSIGNED")
}
if mysql.HasZerofillFlag(ft.Flag) {
strs = append(strs, "ZEROFILL")
}
if mysql.HasBinaryFlag(ft.Flag) {
strs = append(strs, "BINARY")
}
if IsTypeChar(ft.Tp) || IsTypeBlob(ft.Tp) {
if ft.Charset != "" && ft.Charset != charset.CharsetBin {
strs = append(strs, fmt.Sprintf("CHARACTER SET %s", ft.Charset))
}
if ft.Collate != "" && ft.Collate != charset.CharsetBin {
strs = append(strs, fmt.Sprintf("COLLATE %s", ft.Collate))
}
}
return strings.Join(strs, " ")
} | go | func (ft *FieldType) String() string {
strs := []string{ft.CompactStr()}
if mysql.HasUnsignedFlag(ft.Flag) {
strs = append(strs, "UNSIGNED")
}
if mysql.HasZerofillFlag(ft.Flag) {
strs = append(strs, "ZEROFILL")
}
if mysql.HasBinaryFlag(ft.Flag) {
strs = append(strs, "BINARY")
}
if IsTypeChar(ft.Tp) || IsTypeBlob(ft.Tp) {
if ft.Charset != "" && ft.Charset != charset.CharsetBin {
strs = append(strs, fmt.Sprintf("CHARACTER SET %s", ft.Charset))
}
if ft.Collate != "" && ft.Collate != charset.CharsetBin {
strs = append(strs, fmt.Sprintf("COLLATE %s", ft.Collate))
}
}
return strings.Join(strs, " ")
} | [
"func",
"(",
"ft",
"*",
"FieldType",
")",
"String",
"(",
")",
"string",
"{",
"strs",
":=",
"[",
"]",
"string",
"{",
"ft",
".",
"CompactStr",
"(",
")",
"}",
"\n",
"if",
"mysql",
".",
"HasUnsignedFlag",
"(",
"ft",
".",
"Flag",
")",
"{",
"strs",
"=",
"append",
"(",
"strs",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"mysql",
".",
"HasZerofillFlag",
"(",
"ft",
".",
"Flag",
")",
"{",
"strs",
"=",
"append",
"(",
"strs",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"mysql",
".",
"HasBinaryFlag",
"(",
"ft",
".",
"Flag",
")",
"{",
"strs",
"=",
"append",
"(",
"strs",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"IsTypeChar",
"(",
"ft",
".",
"Tp",
")",
"||",
"IsTypeBlob",
"(",
"ft",
".",
"Tp",
")",
"{",
"if",
"ft",
".",
"Charset",
"!=",
"\"",
"\"",
"&&",
"ft",
".",
"Charset",
"!=",
"charset",
".",
"CharsetBin",
"{",
"strs",
"=",
"append",
"(",
"strs",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ft",
".",
"Charset",
")",
")",
"\n",
"}",
"\n",
"if",
"ft",
".",
"Collate",
"!=",
"\"",
"\"",
"&&",
"ft",
".",
"Collate",
"!=",
"charset",
".",
"CharsetBin",
"{",
"strs",
"=",
"append",
"(",
"strs",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ft",
".",
"Collate",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"strings",
".",
"Join",
"(",
"strs",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // String joins the information of FieldType and
// returns a string. | [
"String",
"joins",
"the",
"information",
"of",
"FieldType",
"and",
"returns",
"a",
"string",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/field_type.go#L94-L116 | train |
chrislusf/gleam | sql/util/auth.go | Sha1Hash | func Sha1Hash(bs []byte) []byte {
crypt := sha1.New()
crypt.Write(bs)
return crypt.Sum(nil)
} | go | func Sha1Hash(bs []byte) []byte {
crypt := sha1.New()
crypt.Write(bs)
return crypt.Sum(nil)
} | [
"func",
"Sha1Hash",
"(",
"bs",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"crypt",
":=",
"sha1",
".",
"New",
"(",
")",
"\n",
"crypt",
".",
"Write",
"(",
"bs",
")",
"\n",
"return",
"crypt",
".",
"Sum",
"(",
"nil",
")",
"\n",
"}"
] | // Sha1Hash is an util function to calculate sha1 hash. | [
"Sha1Hash",
"is",
"an",
"util",
"function",
"to",
"calculate",
"sha1",
"hash",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/auth.go#L46-L50 | train |
chrislusf/gleam | sql/util/auth.go | EncodePassword | func EncodePassword(pwd string) string {
if len(pwd) == 0 {
return ""
}
hash := Sha1Hash([]byte(pwd))
return hex.EncodeToString(hash)
} | go | func EncodePassword(pwd string) string {
if len(pwd) == 0 {
return ""
}
hash := Sha1Hash([]byte(pwd))
return hex.EncodeToString(hash)
} | [
"func",
"EncodePassword",
"(",
"pwd",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"pwd",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"hash",
":=",
"Sha1Hash",
"(",
"[",
"]",
"byte",
"(",
"pwd",
")",
")",
"\n",
"return",
"hex",
".",
"EncodeToString",
"(",
"hash",
")",
"\n",
"}"
] | // EncodePassword converts plaintext password to hashed hex string. | [
"EncodePassword",
"converts",
"plaintext",
"password",
"to",
"hashed",
"hex",
"string",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/auth.go#L53-L59 | train |
chrislusf/gleam | sql/util/auth.go | DecodePassword | func DecodePassword(pwd string) ([]byte, error) {
x, err := hex.DecodeString(pwd)
if err != nil {
return nil, errors.Trace(err)
}
return x, nil
} | go | func DecodePassword(pwd string) ([]byte, error) {
x, err := hex.DecodeString(pwd)
if err != nil {
return nil, errors.Trace(err)
}
return x, nil
} | [
"func",
"DecodePassword",
"(",
"pwd",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"x",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"pwd",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"x",
",",
"nil",
"\n",
"}"
] | // DecodePassword converts hex string password to byte array. | [
"DecodePassword",
"converts",
"hex",
"string",
"password",
"to",
"byte",
"array",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/auth.go#L62-L68 | train |
chrislusf/gleam | flow/dataset_join.go | Join | func (d *Dataset) Join(name string, other *Dataset, sortOption *SortOption) *Dataset {
return d.DoJoin(name, other, false, false, sortOption)
} | go | func (d *Dataset) Join(name string, other *Dataset, sortOption *SortOption) *Dataset {
return d.DoJoin(name, other, false, false, sortOption)
} | [
"func",
"(",
"d",
"*",
"Dataset",
")",
"Join",
"(",
"name",
"string",
",",
"other",
"*",
"Dataset",
",",
"sortOption",
"*",
"SortOption",
")",
"*",
"Dataset",
"{",
"return",
"d",
".",
"DoJoin",
"(",
"name",
",",
"other",
",",
"false",
",",
"false",
",",
"sortOption",
")",
"\n",
"}"
] | // Join joins two datasets by the key. | [
"Join",
"joins",
"two",
"datasets",
"by",
"the",
"key",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_join.go#L8-L10 | train |
chrislusf/gleam | flow/dataset_join.go | JoinPartitionedSorted | func (this *Dataset) JoinPartitionedSorted(name string, that *Dataset, sortOption *SortOption,
isLeftOuterJoin, isRightOuterJoin bool) *Dataset {
ret := this.Flow.NewNextDataset(len(this.Shards))
ret.IsPartitionedBy = that.IsPartitionedBy
ret.IsLocalSorted = that.IsLocalSorted
inputs := []*Dataset{this, that}
step := this.Flow.MergeDatasets1ShardTo1Step(inputs, ret)
step.SetInstruction(name, instruction.NewJoinPartitionedSorted(isLeftOuterJoin, isRightOuterJoin, sortOption.Indexes()))
return ret
} | go | func (this *Dataset) JoinPartitionedSorted(name string, that *Dataset, sortOption *SortOption,
isLeftOuterJoin, isRightOuterJoin bool) *Dataset {
ret := this.Flow.NewNextDataset(len(this.Shards))
ret.IsPartitionedBy = that.IsPartitionedBy
ret.IsLocalSorted = that.IsLocalSorted
inputs := []*Dataset{this, that}
step := this.Flow.MergeDatasets1ShardTo1Step(inputs, ret)
step.SetInstruction(name, instruction.NewJoinPartitionedSorted(isLeftOuterJoin, isRightOuterJoin, sortOption.Indexes()))
return ret
} | [
"func",
"(",
"this",
"*",
"Dataset",
")",
"JoinPartitionedSorted",
"(",
"name",
"string",
",",
"that",
"*",
"Dataset",
",",
"sortOption",
"*",
"SortOption",
",",
"isLeftOuterJoin",
",",
"isRightOuterJoin",
"bool",
")",
"*",
"Dataset",
"{",
"ret",
":=",
"this",
".",
"Flow",
".",
"NewNextDataset",
"(",
"len",
"(",
"this",
".",
"Shards",
")",
")",
"\n",
"ret",
".",
"IsPartitionedBy",
"=",
"that",
".",
"IsPartitionedBy",
"\n",
"ret",
".",
"IsLocalSorted",
"=",
"that",
".",
"IsLocalSorted",
"\n\n",
"inputs",
":=",
"[",
"]",
"*",
"Dataset",
"{",
"this",
",",
"that",
"}",
"\n",
"step",
":=",
"this",
".",
"Flow",
".",
"MergeDatasets1ShardTo1Step",
"(",
"inputs",
",",
"ret",
")",
"\n",
"step",
".",
"SetInstruction",
"(",
"name",
",",
"instruction",
".",
"NewJoinPartitionedSorted",
"(",
"isLeftOuterJoin",
",",
"isRightOuterJoin",
",",
"sortOption",
".",
"Indexes",
"(",
")",
")",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // JoinPartitionedSorted Join multiple datasets that are sharded by the same key, and locally sorted within the shard | [
"JoinPartitionedSorted",
"Join",
"multiple",
"datasets",
"that",
"are",
"sharded",
"by",
"the",
"same",
"key",
"and",
"locally",
"sorted",
"within",
"the",
"shard"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_join.go#L46-L56 | train |
chrislusf/gleam | sql/expression/expression.go | EvalBool | func EvalBool(expr Expression, row []types.Datum, ctx context.Context) (bool, error) {
data, err := expr.Eval(row, ctx)
if err != nil {
return false, errors.Trace(err)
}
if data.IsNull() {
return false, nil
}
i, err := data.ToBool(ctx.GetSessionVars().StmtCtx)
if err != nil {
return false, errors.Trace(err)
}
return i != 0, nil
} | go | func EvalBool(expr Expression, row []types.Datum, ctx context.Context) (bool, error) {
data, err := expr.Eval(row, ctx)
if err != nil {
return false, errors.Trace(err)
}
if data.IsNull() {
return false, nil
}
i, err := data.ToBool(ctx.GetSessionVars().StmtCtx)
if err != nil {
return false, errors.Trace(err)
}
return i != 0, nil
} | [
"func",
"EvalBool",
"(",
"expr",
"Expression",
",",
"row",
"[",
"]",
"types",
".",
"Datum",
",",
"ctx",
"context",
".",
"Context",
")",
"(",
"bool",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"expr",
".",
"Eval",
"(",
"row",
",",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"data",
".",
"IsNull",
"(",
")",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"i",
",",
"err",
":=",
"data",
".",
"ToBool",
"(",
"ctx",
".",
"GetSessionVars",
"(",
")",
".",
"StmtCtx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"i",
"!=",
"0",
",",
"nil",
"\n",
"}"
] | // EvalBool evaluates expression to a boolean value. | [
"EvalBool",
"evaluates",
"expression",
"to",
"a",
"boolean",
"value",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/expression.go#L78-L92 | train |
chrislusf/gleam | sql/expression/expression.go | TableInfo2Schema | func TableInfo2Schema(tbl *model.TableInfo) Schema {
schema := NewSchema(make([]*Column, 0, len(tbl.Columns)))
keys := make([]KeyInfo, 0, len(tbl.Indices)+1)
for i, col := range tbl.Columns {
newCol := &Column{
ColName: col.Name,
TblName: tbl.Name,
RetType: &col.FieldType,
Position: i,
}
schema.Append(newCol)
}
for _, idx := range tbl.Indices {
if !idx.Unique {
continue
}
ok := true
newKey := make([]*Column, 0, len(idx.Columns))
for _, idxCol := range idx.Columns {
find := false
for i, col := range tbl.Columns {
if idxCol.Name.L == col.Name.L {
if !mysql.HasNotNullFlag(col.Flag) {
break
}
newKey = append(newKey, schema.Columns[i])
find = true
break
}
}
if !find {
ok = false
break
}
}
if ok {
keys = append(keys, newKey)
}
}
schema.SetUniqueKeys(keys)
return schema
} | go | func TableInfo2Schema(tbl *model.TableInfo) Schema {
schema := NewSchema(make([]*Column, 0, len(tbl.Columns)))
keys := make([]KeyInfo, 0, len(tbl.Indices)+1)
for i, col := range tbl.Columns {
newCol := &Column{
ColName: col.Name,
TblName: tbl.Name,
RetType: &col.FieldType,
Position: i,
}
schema.Append(newCol)
}
for _, idx := range tbl.Indices {
if !idx.Unique {
continue
}
ok := true
newKey := make([]*Column, 0, len(idx.Columns))
for _, idxCol := range idx.Columns {
find := false
for i, col := range tbl.Columns {
if idxCol.Name.L == col.Name.L {
if !mysql.HasNotNullFlag(col.Flag) {
break
}
newKey = append(newKey, schema.Columns[i])
find = true
break
}
}
if !find {
ok = false
break
}
}
if ok {
keys = append(keys, newKey)
}
}
schema.SetUniqueKeys(keys)
return schema
} | [
"func",
"TableInfo2Schema",
"(",
"tbl",
"*",
"model",
".",
"TableInfo",
")",
"Schema",
"{",
"schema",
":=",
"NewSchema",
"(",
"make",
"(",
"[",
"]",
"*",
"Column",
",",
"0",
",",
"len",
"(",
"tbl",
".",
"Columns",
")",
")",
")",
"\n",
"keys",
":=",
"make",
"(",
"[",
"]",
"KeyInfo",
",",
"0",
",",
"len",
"(",
"tbl",
".",
"Indices",
")",
"+",
"1",
")",
"\n",
"for",
"i",
",",
"col",
":=",
"range",
"tbl",
".",
"Columns",
"{",
"newCol",
":=",
"&",
"Column",
"{",
"ColName",
":",
"col",
".",
"Name",
",",
"TblName",
":",
"tbl",
".",
"Name",
",",
"RetType",
":",
"&",
"col",
".",
"FieldType",
",",
"Position",
":",
"i",
",",
"}",
"\n",
"schema",
".",
"Append",
"(",
"newCol",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"idx",
":=",
"range",
"tbl",
".",
"Indices",
"{",
"if",
"!",
"idx",
".",
"Unique",
"{",
"continue",
"\n",
"}",
"\n",
"ok",
":=",
"true",
"\n",
"newKey",
":=",
"make",
"(",
"[",
"]",
"*",
"Column",
",",
"0",
",",
"len",
"(",
"idx",
".",
"Columns",
")",
")",
"\n",
"for",
"_",
",",
"idxCol",
":=",
"range",
"idx",
".",
"Columns",
"{",
"find",
":=",
"false",
"\n",
"for",
"i",
",",
"col",
":=",
"range",
"tbl",
".",
"Columns",
"{",
"if",
"idxCol",
".",
"Name",
".",
"L",
"==",
"col",
".",
"Name",
".",
"L",
"{",
"if",
"!",
"mysql",
".",
"HasNotNullFlag",
"(",
"col",
".",
"Flag",
")",
"{",
"break",
"\n",
"}",
"\n",
"newKey",
"=",
"append",
"(",
"newKey",
",",
"schema",
".",
"Columns",
"[",
"i",
"]",
")",
"\n",
"find",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"find",
"{",
"ok",
"=",
"false",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"ok",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"newKey",
")",
"\n",
"}",
"\n",
"}",
"\n",
"schema",
".",
"SetUniqueKeys",
"(",
"keys",
")",
"\n",
"return",
"schema",
"\n",
"}"
] | // TableInfo2Schema converts table info to schema. | [
"TableInfo2Schema",
"converts",
"table",
"info",
"to",
"schema",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/expression.go#L279-L320 | train |
chrislusf/gleam | sql/expression/expression.go | NewCastFunc | func NewCastFunc(tp *types.FieldType, arg Expression, ctx context.Context) *ScalarFunction {
bt := &builtinCastSig{newBaseBuiltinFunc([]Expression{arg}, ctx), tp}
return &ScalarFunction{
FuncName: model.NewCIStr(ast.Cast),
RetType: tp,
Function: bt,
}
} | go | func NewCastFunc(tp *types.FieldType, arg Expression, ctx context.Context) *ScalarFunction {
bt := &builtinCastSig{newBaseBuiltinFunc([]Expression{arg}, ctx), tp}
return &ScalarFunction{
FuncName: model.NewCIStr(ast.Cast),
RetType: tp,
Function: bt,
}
} | [
"func",
"NewCastFunc",
"(",
"tp",
"*",
"types",
".",
"FieldType",
",",
"arg",
"Expression",
",",
"ctx",
"context",
".",
"Context",
")",
"*",
"ScalarFunction",
"{",
"bt",
":=",
"&",
"builtinCastSig",
"{",
"newBaseBuiltinFunc",
"(",
"[",
"]",
"Expression",
"{",
"arg",
"}",
",",
"ctx",
")",
",",
"tp",
"}",
"\n",
"return",
"&",
"ScalarFunction",
"{",
"FuncName",
":",
"model",
".",
"NewCIStr",
"(",
"ast",
".",
"Cast",
")",
",",
"RetType",
":",
"tp",
",",
"Function",
":",
"bt",
",",
"}",
"\n",
"}"
] | // NewCastFunc creates a new cast function. | [
"NewCastFunc",
"creates",
"a",
"new",
"cast",
"function",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/expression.go#L323-L330 | train |
chrislusf/gleam | sql/expression/constant_fold.go | FoldConstant | func FoldConstant(ctx context.Context, expr Expression) Expression {
scalarFunc, ok := expr.(*ScalarFunction)
if !ok {
return expr
}
if _, isDynamic := DynamicFuncs[scalarFunc.FuncName.L]; isDynamic {
return expr
}
args := scalarFunc.GetArgs()
canFold := true
for i := 0; i < len(args); i++ {
foldedArg := FoldConstant(ctx, args[i])
scalarFunc.GetArgs()[i] = foldedArg
if _, ok := foldedArg.(*Constant); !ok {
canFold = false
}
}
if !canFold {
return expr
}
value, err := scalarFunc.Eval(nil, ctx)
if err != nil {
log.Printf("There may exist an error during constant folding. The function name is %s, args are %s", scalarFunc.FuncName, args)
return expr
}
return &Constant{
Value: value,
RetType: scalarFunc.RetType,
}
} | go | func FoldConstant(ctx context.Context, expr Expression) Expression {
scalarFunc, ok := expr.(*ScalarFunction)
if !ok {
return expr
}
if _, isDynamic := DynamicFuncs[scalarFunc.FuncName.L]; isDynamic {
return expr
}
args := scalarFunc.GetArgs()
canFold := true
for i := 0; i < len(args); i++ {
foldedArg := FoldConstant(ctx, args[i])
scalarFunc.GetArgs()[i] = foldedArg
if _, ok := foldedArg.(*Constant); !ok {
canFold = false
}
}
if !canFold {
return expr
}
value, err := scalarFunc.Eval(nil, ctx)
if err != nil {
log.Printf("There may exist an error during constant folding. The function name is %s, args are %s", scalarFunc.FuncName, args)
return expr
}
return &Constant{
Value: value,
RetType: scalarFunc.RetType,
}
} | [
"func",
"FoldConstant",
"(",
"ctx",
"context",
".",
"Context",
",",
"expr",
"Expression",
")",
"Expression",
"{",
"scalarFunc",
",",
"ok",
":=",
"expr",
".",
"(",
"*",
"ScalarFunction",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"expr",
"\n",
"}",
"\n",
"if",
"_",
",",
"isDynamic",
":=",
"DynamicFuncs",
"[",
"scalarFunc",
".",
"FuncName",
".",
"L",
"]",
";",
"isDynamic",
"{",
"return",
"expr",
"\n",
"}",
"\n",
"args",
":=",
"scalarFunc",
".",
"GetArgs",
"(",
")",
"\n",
"canFold",
":=",
"true",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"args",
")",
";",
"i",
"++",
"{",
"foldedArg",
":=",
"FoldConstant",
"(",
"ctx",
",",
"args",
"[",
"i",
"]",
")",
"\n",
"scalarFunc",
".",
"GetArgs",
"(",
")",
"[",
"i",
"]",
"=",
"foldedArg",
"\n",
"if",
"_",
",",
"ok",
":=",
"foldedArg",
".",
"(",
"*",
"Constant",
")",
";",
"!",
"ok",
"{",
"canFold",
"=",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"canFold",
"{",
"return",
"expr",
"\n",
"}",
"\n",
"value",
",",
"err",
":=",
"scalarFunc",
".",
"Eval",
"(",
"nil",
",",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"scalarFunc",
".",
"FuncName",
",",
"args",
")",
"\n",
"return",
"expr",
"\n",
"}",
"\n",
"return",
"&",
"Constant",
"{",
"Value",
":",
"value",
",",
"RetType",
":",
"scalarFunc",
".",
"RetType",
",",
"}",
"\n",
"}"
] | // FoldConstant does constant folding optimization on an expression. | [
"FoldConstant",
"does",
"constant",
"folding",
"optimization",
"on",
"an",
"expression",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/constant_fold.go#L22-L51 | train |
chrislusf/gleam | util/message_read.go | TakeMessage | func TakeMessage(reader io.Reader, count int, f func([]byte) error) (err error) {
if _, isBufioReader := reader.(*bufio.Reader); !isBufioReader {
reader = bufio.NewReader(reader)
}
for err == nil {
if count == 0 {
io.Copy(ioutil.Discard, reader)
return nil
}
message, readError := ReadMessage(reader)
if readError == io.EOF {
break
}
if readError == nil {
err = f(message)
} else {
return fmt.Errorf("Failed to read message: %v\n", readError)
}
count--
}
return
} | go | func TakeMessage(reader io.Reader, count int, f func([]byte) error) (err error) {
if _, isBufioReader := reader.(*bufio.Reader); !isBufioReader {
reader = bufio.NewReader(reader)
}
for err == nil {
if count == 0 {
io.Copy(ioutil.Discard, reader)
return nil
}
message, readError := ReadMessage(reader)
if readError == io.EOF {
break
}
if readError == nil {
err = f(message)
} else {
return fmt.Errorf("Failed to read message: %v\n", readError)
}
count--
}
return
} | [
"func",
"TakeMessage",
"(",
"reader",
"io",
".",
"Reader",
",",
"count",
"int",
",",
"f",
"func",
"(",
"[",
"]",
"byte",
")",
"error",
")",
"(",
"err",
"error",
")",
"{",
"if",
"_",
",",
"isBufioReader",
":=",
"reader",
".",
"(",
"*",
"bufio",
".",
"Reader",
")",
";",
"!",
"isBufioReader",
"{",
"reader",
"=",
"bufio",
".",
"NewReader",
"(",
"reader",
")",
"\n",
"}",
"\n",
"for",
"err",
"==",
"nil",
"{",
"if",
"count",
"==",
"0",
"{",
"io",
".",
"Copy",
"(",
"ioutil",
".",
"Discard",
",",
"reader",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"message",
",",
"readError",
":=",
"ReadMessage",
"(",
"reader",
")",
"\n",
"if",
"readError",
"==",
"io",
".",
"EOF",
"{",
"break",
"\n",
"}",
"\n",
"if",
"readError",
"==",
"nil",
"{",
"err",
"=",
"f",
"(",
"message",
")",
"\n",
"}",
"else",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"readError",
")",
"\n",
"}",
"\n",
"count",
"--",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // TakeMessage Reads and processes MessagePack encoded messages.
// If count is less than 0, all lines are processed. | [
"TakeMessage",
"Reads",
"and",
"processes",
"MessagePack",
"encoded",
"messages",
".",
"If",
"count",
"is",
"less",
"than",
"0",
"all",
"lines",
"are",
"processed",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/message_read.go#L58-L80 | train |
chrislusf/gleam | util/message_read.go | ProcessMessage | func ProcessMessage(reader io.Reader, f func([]byte) error) (err error) {
return TakeMessage(reader, -1, f)
} | go | func ProcessMessage(reader io.Reader, f func([]byte) error) (err error) {
return TakeMessage(reader, -1, f)
} | [
"func",
"ProcessMessage",
"(",
"reader",
"io",
".",
"Reader",
",",
"f",
"func",
"(",
"[",
"]",
"byte",
")",
"error",
")",
"(",
"err",
"error",
")",
"{",
"return",
"TakeMessage",
"(",
"reader",
",",
"-",
"1",
",",
"f",
")",
"\n",
"}"
] | // ProcessMessage Reads and processes MessagePack encoded messages until EOF | [
"ProcessMessage",
"Reads",
"and",
"processes",
"MessagePack",
"encoded",
"messages",
"until",
"EOF"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/message_read.go#L83-L85 | train |
chrislusf/gleam | distributed/store/single_file_store.go | Write | func (l *SingleFileStore) Write(p []byte) (n int, err error) {
l.mu.Lock()
defer l.mu.Unlock()
if l.file == nil {
if err = l.openNew(); err != nil {
return 0, err
}
}
l.file.Seek(0, 2)
n, err = l.file.Write(p)
l.size += int64(n)
l.Position += int64(n)
l.waitForReading.Broadcast()
return n, err
} | go | func (l *SingleFileStore) Write(p []byte) (n int, err error) {
l.mu.Lock()
defer l.mu.Unlock()
if l.file == nil {
if err = l.openNew(); err != nil {
return 0, err
}
}
l.file.Seek(0, 2)
n, err = l.file.Write(p)
l.size += int64(n)
l.Position += int64(n)
l.waitForReading.Broadcast()
return n, err
} | [
"func",
"(",
"l",
"*",
"SingleFileStore",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"l",
".",
"file",
"==",
"nil",
"{",
"if",
"err",
"=",
"l",
".",
"openNew",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"l",
".",
"file",
".",
"Seek",
"(",
"0",
",",
"2",
")",
"\n",
"n",
",",
"err",
"=",
"l",
".",
"file",
".",
"Write",
"(",
"p",
")",
"\n",
"l",
".",
"size",
"+=",
"int64",
"(",
"n",
")",
"\n",
"l",
".",
"Position",
"+=",
"int64",
"(",
"n",
")",
"\n",
"l",
".",
"waitForReading",
".",
"Broadcast",
"(",
")",
"\n\n",
"return",
"n",
",",
"err",
"\n",
"}"
] | // Write implements io.Writer. If a write would cause the log file to be larger
// than MaxMegaByte, the file is closed, renamed to include a timestamp of the
// current time, and a new log file is created using the original log file name.
// If the length of the write is greater than MaxMegaByte, an error is returned. | [
"Write",
"implements",
"io",
".",
"Writer",
".",
"If",
"a",
"write",
"would",
"cause",
"the",
"log",
"file",
"to",
"be",
"larger",
"than",
"MaxMegaByte",
"the",
"file",
"is",
"closed",
"renamed",
"to",
"include",
"a",
"timestamp",
"of",
"the",
"current",
"time",
"and",
"a",
"new",
"log",
"file",
"is",
"created",
"using",
"the",
"original",
"log",
"file",
"name",
".",
"If",
"the",
"length",
"of",
"the",
"write",
"is",
"greater",
"than",
"MaxMegaByte",
"an",
"error",
"is",
"returned",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/store/single_file_store.go#L62-L79 | train |
chrislusf/gleam | distributed/driver/scheduler/grpc_client_to_agent.go | mergeStats | func mergeStats(a, b []*pb.InstructionStat) (ret []*pb.InstructionStat) {
var nonOverlapping []*pb.InstructionStat
for _, ai := range a {
var found bool
for _, bi := range b {
if ai.StepId == bi.StepId {
found = true
if ai.InputCounter > bi.InputCounter {
ret = append(ret, ai)
} else {
ret = append(ret, bi)
}
}
}
if !found {
nonOverlapping = append(nonOverlapping, ai)
}
}
for _, bi := range b {
var found bool
for _, ai := range a {
if ai.StepId == bi.StepId {
found = true
}
}
if !found {
nonOverlapping = append(nonOverlapping, bi)
}
}
ret = append(ret, nonOverlapping...)
return ret
} | go | func mergeStats(a, b []*pb.InstructionStat) (ret []*pb.InstructionStat) {
var nonOverlapping []*pb.InstructionStat
for _, ai := range a {
var found bool
for _, bi := range b {
if ai.StepId == bi.StepId {
found = true
if ai.InputCounter > bi.InputCounter {
ret = append(ret, ai)
} else {
ret = append(ret, bi)
}
}
}
if !found {
nonOverlapping = append(nonOverlapping, ai)
}
}
for _, bi := range b {
var found bool
for _, ai := range a {
if ai.StepId == bi.StepId {
found = true
}
}
if !found {
nonOverlapping = append(nonOverlapping, bi)
}
}
ret = append(ret, nonOverlapping...)
return ret
} | [
"func",
"mergeStats",
"(",
"a",
",",
"b",
"[",
"]",
"*",
"pb",
".",
"InstructionStat",
")",
"(",
"ret",
"[",
"]",
"*",
"pb",
".",
"InstructionStat",
")",
"{",
"var",
"nonOverlapping",
"[",
"]",
"*",
"pb",
".",
"InstructionStat",
"\n",
"for",
"_",
",",
"ai",
":=",
"range",
"a",
"{",
"var",
"found",
"bool",
"\n",
"for",
"_",
",",
"bi",
":=",
"range",
"b",
"{",
"if",
"ai",
".",
"StepId",
"==",
"bi",
".",
"StepId",
"{",
"found",
"=",
"true",
"\n",
"if",
"ai",
".",
"InputCounter",
">",
"bi",
".",
"InputCounter",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"ai",
")",
"\n",
"}",
"else",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"bi",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"nonOverlapping",
"=",
"append",
"(",
"nonOverlapping",
",",
"ai",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"bi",
":=",
"range",
"b",
"{",
"var",
"found",
"bool",
"\n",
"for",
"_",
",",
"ai",
":=",
"range",
"a",
"{",
"if",
"ai",
".",
"StepId",
"==",
"bi",
".",
"StepId",
"{",
"found",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"nonOverlapping",
"=",
"append",
"(",
"nonOverlapping",
",",
"bi",
")",
"\n",
"}",
"\n",
"}",
"\n",
"ret",
"=",
"append",
"(",
"ret",
",",
"nonOverlapping",
"...",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // merge existing stats with incoming stats | [
"merge",
"existing",
"stats",
"with",
"incoming",
"stats"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/driver/scheduler/grpc_client_to_agent.go#L148-L179 | train |
chrislusf/gleam | sql/plan/physical_plan_builder.go | tryToConvert2DummyScan | func (p *DataSource) tryToConvert2DummyScan(prop *requiredProperty) (*physicalPlanInfo, error) {
sel, isSel := p.GetParentByIndex(0).(*Selection)
if !isSel {
return nil, nil
}
for _, cond := range sel.Conditions {
if con, ok := cond.(*expression.Constant); ok {
result, err := expression.EvalBool(con, nil, p.ctx)
if err != nil {
return nil, errors.Trace(err)
}
if !result {
dummy := &PhysicalDummyScan{}
dummy.tp = "Dummy"
dummy.allocator = p.allocator
dummy.initIDAndContext(p.ctx)
dummy.SetSchema(p.schema)
info := &physicalPlanInfo{p: dummy}
p.storePlanInfo(prop, info)
return info, nil
}
}
}
return nil, nil
} | go | func (p *DataSource) tryToConvert2DummyScan(prop *requiredProperty) (*physicalPlanInfo, error) {
sel, isSel := p.GetParentByIndex(0).(*Selection)
if !isSel {
return nil, nil
}
for _, cond := range sel.Conditions {
if con, ok := cond.(*expression.Constant); ok {
result, err := expression.EvalBool(con, nil, p.ctx)
if err != nil {
return nil, errors.Trace(err)
}
if !result {
dummy := &PhysicalDummyScan{}
dummy.tp = "Dummy"
dummy.allocator = p.allocator
dummy.initIDAndContext(p.ctx)
dummy.SetSchema(p.schema)
info := &physicalPlanInfo{p: dummy}
p.storePlanInfo(prop, info)
return info, nil
}
}
}
return nil, nil
} | [
"func",
"(",
"p",
"*",
"DataSource",
")",
"tryToConvert2DummyScan",
"(",
"prop",
"*",
"requiredProperty",
")",
"(",
"*",
"physicalPlanInfo",
",",
"error",
")",
"{",
"sel",
",",
"isSel",
":=",
"p",
".",
"GetParentByIndex",
"(",
"0",
")",
".",
"(",
"*",
"Selection",
")",
"\n",
"if",
"!",
"isSel",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"cond",
":=",
"range",
"sel",
".",
"Conditions",
"{",
"if",
"con",
",",
"ok",
":=",
"cond",
".",
"(",
"*",
"expression",
".",
"Constant",
")",
";",
"ok",
"{",
"result",
",",
"err",
":=",
"expression",
".",
"EvalBool",
"(",
"con",
",",
"nil",
",",
"p",
".",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"!",
"result",
"{",
"dummy",
":=",
"&",
"PhysicalDummyScan",
"{",
"}",
"\n",
"dummy",
".",
"tp",
"=",
"\"",
"\"",
"\n",
"dummy",
".",
"allocator",
"=",
"p",
".",
"allocator",
"\n",
"dummy",
".",
"initIDAndContext",
"(",
"p",
".",
"ctx",
")",
"\n",
"dummy",
".",
"SetSchema",
"(",
"p",
".",
"schema",
")",
"\n",
"info",
":=",
"&",
"physicalPlanInfo",
"{",
"p",
":",
"dummy",
"}",
"\n",
"p",
".",
"storePlanInfo",
"(",
"prop",
",",
"info",
")",
"\n",
"return",
"info",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // tryToConvert2DummyScan is an optimization which checks if its parent is a selection with a constant condition
// that evaluates to false. If it is, there is no need for a real physical scan, a dummy scan will do. | [
"tryToConvert2DummyScan",
"is",
"an",
"optimization",
"which",
"checks",
"if",
"its",
"parent",
"is",
"a",
"selection",
"with",
"a",
"constant",
"condition",
"that",
"evaluates",
"to",
"false",
".",
"If",
"it",
"is",
"there",
"is",
"no",
"need",
"for",
"a",
"real",
"physical",
"scan",
"a",
"dummy",
"scan",
"will",
"do",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/physical_plan_builder.go#L146-L171 | train |
chrislusf/gleam | sql/plan/physical_plan_builder.go | removeLimit | func removeLimit(prop *requiredProperty) *requiredProperty {
ret := &requiredProperty{
props: prop.props,
sortKeyLen: prop.sortKeyLen,
}
return ret
} | go | func removeLimit(prop *requiredProperty) *requiredProperty {
ret := &requiredProperty{
props: prop.props,
sortKeyLen: prop.sortKeyLen,
}
return ret
} | [
"func",
"removeLimit",
"(",
"prop",
"*",
"requiredProperty",
")",
"*",
"requiredProperty",
"{",
"ret",
":=",
"&",
"requiredProperty",
"{",
"props",
":",
"prop",
".",
"props",
",",
"sortKeyLen",
":",
"prop",
".",
"sortKeyLen",
",",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // removeLimit removes the limit from prop. | [
"removeLimit",
"removes",
"the",
"limit",
"from",
"prop",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/physical_plan_builder.go#L222-L228 | train |
chrislusf/gleam | sql/plan/physical_plan_builder.go | replaceColsInPropBySchema | func replaceColsInPropBySchema(prop *requiredProperty, schema expression.Schema) *requiredProperty {
newProps := make([]*columnProp, 0, len(prop.props))
for _, p := range prop.props {
idx := schema.GetColumnIndex(p.col)
if idx == -1 {
log.Printf("Can't find column %s in schema", p.col)
}
newProps = append(newProps, &columnProp{col: schema.Columns[idx], desc: p.desc})
}
return &requiredProperty{
props: newProps,
sortKeyLen: prop.sortKeyLen,
limit: prop.limit,
}
} | go | func replaceColsInPropBySchema(prop *requiredProperty, schema expression.Schema) *requiredProperty {
newProps := make([]*columnProp, 0, len(prop.props))
for _, p := range prop.props {
idx := schema.GetColumnIndex(p.col)
if idx == -1 {
log.Printf("Can't find column %s in schema", p.col)
}
newProps = append(newProps, &columnProp{col: schema.Columns[idx], desc: p.desc})
}
return &requiredProperty{
props: newProps,
sortKeyLen: prop.sortKeyLen,
limit: prop.limit,
}
} | [
"func",
"replaceColsInPropBySchema",
"(",
"prop",
"*",
"requiredProperty",
",",
"schema",
"expression",
".",
"Schema",
")",
"*",
"requiredProperty",
"{",
"newProps",
":=",
"make",
"(",
"[",
"]",
"*",
"columnProp",
",",
"0",
",",
"len",
"(",
"prop",
".",
"props",
")",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"prop",
".",
"props",
"{",
"idx",
":=",
"schema",
".",
"GetColumnIndex",
"(",
"p",
".",
"col",
")",
"\n",
"if",
"idx",
"==",
"-",
"1",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"p",
".",
"col",
")",
"\n",
"}",
"\n",
"newProps",
"=",
"append",
"(",
"newProps",
",",
"&",
"columnProp",
"{",
"col",
":",
"schema",
".",
"Columns",
"[",
"idx",
"]",
",",
"desc",
":",
"p",
".",
"desc",
"}",
")",
"\n",
"}",
"\n",
"return",
"&",
"requiredProperty",
"{",
"props",
":",
"newProps",
",",
"sortKeyLen",
":",
"prop",
".",
"sortKeyLen",
",",
"limit",
":",
"prop",
".",
"limit",
",",
"}",
"\n",
"}"
] | // replaceColsInPropBySchema replaces the columns in original prop with the columns in schema. | [
"replaceColsInPropBySchema",
"replaces",
"the",
"columns",
"in",
"original",
"prop",
"with",
"the",
"columns",
"in",
"schema",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/physical_plan_builder.go#L375-L389 | train |
chrislusf/gleam | sql/plan/physical_plan_builder.go | convert2PhysicalPlanHash | func (p *Aggregation) convert2PhysicalPlanHash() (*physicalPlanInfo, error) {
childInfo, err := p.children[0].(LogicalPlan).convert2PhysicalPlan(&requiredProperty{})
if err != nil {
return nil, errors.Trace(err)
}
distinct := false
for _, fun := range p.AggFuncs {
if fun.IsDistinct() {
distinct = true
break
}
}
if !distinct {
if x, ok := childInfo.p.(physicalDistSQLPlan); ok {
info := p.convert2PhysicalPlanFinalHash(x, childInfo)
if info != nil {
return info, nil
}
}
}
return p.convert2PhysicalPlanCompleteHash(childInfo), nil
} | go | func (p *Aggregation) convert2PhysicalPlanHash() (*physicalPlanInfo, error) {
childInfo, err := p.children[0].(LogicalPlan).convert2PhysicalPlan(&requiredProperty{})
if err != nil {
return nil, errors.Trace(err)
}
distinct := false
for _, fun := range p.AggFuncs {
if fun.IsDistinct() {
distinct = true
break
}
}
if !distinct {
if x, ok := childInfo.p.(physicalDistSQLPlan); ok {
info := p.convert2PhysicalPlanFinalHash(x, childInfo)
if info != nil {
return info, nil
}
}
}
return p.convert2PhysicalPlanCompleteHash(childInfo), nil
} | [
"func",
"(",
"p",
"*",
"Aggregation",
")",
"convert2PhysicalPlanHash",
"(",
")",
"(",
"*",
"physicalPlanInfo",
",",
"error",
")",
"{",
"childInfo",
",",
"err",
":=",
"p",
".",
"children",
"[",
"0",
"]",
".",
"(",
"LogicalPlan",
")",
".",
"convert2PhysicalPlan",
"(",
"&",
"requiredProperty",
"{",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"distinct",
":=",
"false",
"\n",
"for",
"_",
",",
"fun",
":=",
"range",
"p",
".",
"AggFuncs",
"{",
"if",
"fun",
".",
"IsDistinct",
"(",
")",
"{",
"distinct",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"distinct",
"{",
"if",
"x",
",",
"ok",
":=",
"childInfo",
".",
"p",
".",
"(",
"physicalDistSQLPlan",
")",
";",
"ok",
"{",
"info",
":=",
"p",
".",
"convert2PhysicalPlanFinalHash",
"(",
"x",
",",
"childInfo",
")",
"\n",
"if",
"info",
"!=",
"nil",
"{",
"return",
"info",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"p",
".",
"convert2PhysicalPlanCompleteHash",
"(",
"childInfo",
")",
",",
"nil",
"\n",
"}"
] | // convert2PhysicalPlanHash converts the logical aggregation to the physical hash aggregation. | [
"convert2PhysicalPlanHash",
"converts",
"the",
"logical",
"aggregation",
"to",
"the",
"physical",
"hash",
"aggregation",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/physical_plan_builder.go#L587-L608 | train |
chrislusf/gleam | sql/plan/physical_plan_builder.go | physicalInitialize | func physicalInitialize(p PhysicalPlan) {
for _, child := range p.GetChildren() {
physicalInitialize(child.(PhysicalPlan))
}
// initialize attributes
p.SetCorrelated()
} | go | func physicalInitialize(p PhysicalPlan) {
for _, child := range p.GetChildren() {
physicalInitialize(child.(PhysicalPlan))
}
// initialize attributes
p.SetCorrelated()
} | [
"func",
"physicalInitialize",
"(",
"p",
"PhysicalPlan",
")",
"{",
"for",
"_",
",",
"child",
":=",
"range",
"p",
".",
"GetChildren",
"(",
")",
"{",
"physicalInitialize",
"(",
"child",
".",
"(",
"PhysicalPlan",
")",
")",
"\n",
"}",
"\n",
"// initialize attributes",
"p",
".",
"SetCorrelated",
"(",
")",
"\n",
"}"
] | // physicalInitialize will set value of some attributes after convert2PhysicalPlan process.
// Currently, only attribute "correlated" is considered. | [
"physicalInitialize",
"will",
"set",
"value",
"of",
"some",
"attributes",
"after",
"convert2PhysicalPlan",
"process",
".",
"Currently",
"only",
"attribute",
"correlated",
"is",
"considered",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/physical_plan_builder.go#L900-L906 | train |
chrislusf/gleam | sql/util/codec/number.go | EncodeInt | func EncodeInt(b []byte, v int64) []byte {
var data [8]byte
u := encodeIntToCmpUint(v)
binary.BigEndian.PutUint64(data[:], u)
return append(b, data[:]...)
} | go | func EncodeInt(b []byte, v int64) []byte {
var data [8]byte
u := encodeIntToCmpUint(v)
binary.BigEndian.PutUint64(data[:], u)
return append(b, data[:]...)
} | [
"func",
"EncodeInt",
"(",
"b",
"[",
"]",
"byte",
",",
"v",
"int64",
")",
"[",
"]",
"byte",
"{",
"var",
"data",
"[",
"8",
"]",
"byte",
"\n",
"u",
":=",
"encodeIntToCmpUint",
"(",
"v",
")",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint64",
"(",
"data",
"[",
":",
"]",
",",
"u",
")",
"\n",
"return",
"append",
"(",
"b",
",",
"data",
"[",
":",
"]",
"...",
")",
"\n",
"}"
] | // EncodeInt appends the encoded value to slice b and returns the appended slice.
// EncodeInt guarantees that the encoded value is in ascending order for comparison. | [
"EncodeInt",
"appends",
"the",
"encoded",
"value",
"to",
"slice",
"b",
"and",
"returns",
"the",
"appended",
"slice",
".",
"EncodeInt",
"guarantees",
"that",
"the",
"encoded",
"value",
"is",
"in",
"ascending",
"order",
"for",
"comparison",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/codec/number.go#L35-L40 | train |
chrislusf/gleam | sql/util/codec/number.go | DecodeIntDesc | func DecodeIntDesc(b []byte) ([]byte, int64, error) {
if len(b) < 8 {
return nil, 0, errors.New("insufficient bytes to decode value")
}
u := binary.BigEndian.Uint64(b[:8])
v := decodeCmpUintToInt(^u)
b = b[8:]
return b, v, nil
} | go | func DecodeIntDesc(b []byte) ([]byte, int64, error) {
if len(b) < 8 {
return nil, 0, errors.New("insufficient bytes to decode value")
}
u := binary.BigEndian.Uint64(b[:8])
v := decodeCmpUintToInt(^u)
b = b[8:]
return b, v, nil
} | [
"func",
"DecodeIntDesc",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"int64",
",",
"error",
")",
"{",
"if",
"len",
"(",
"b",
")",
"<",
"8",
"{",
"return",
"nil",
",",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"u",
":=",
"binary",
".",
"BigEndian",
".",
"Uint64",
"(",
"b",
"[",
":",
"8",
"]",
")",
"\n",
"v",
":=",
"decodeCmpUintToInt",
"(",
"^",
"u",
")",
"\n",
"b",
"=",
"b",
"[",
"8",
":",
"]",
"\n",
"return",
"b",
",",
"v",
",",
"nil",
"\n",
"}"
] | // DecodeIntDesc decodes value encoded by EncodeInt before.
// It returns the leftover un-decoded slice, decoded value if no error. | [
"DecodeIntDesc",
"decodes",
"value",
"encoded",
"by",
"EncodeInt",
"before",
".",
"It",
"returns",
"the",
"leftover",
"un",
"-",
"decoded",
"slice",
"decoded",
"value",
"if",
"no",
"error",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/codec/number.go#L66-L75 | train |
chrislusf/gleam | sql/util/types/convert.go | StrToInt | func StrToInt(sc *variable.StatementContext, str string) (int64, error) {
str = strings.TrimSpace(str)
validPrefix, err := getValidIntPrefix(sc, str)
iVal, err1 := strconv.ParseInt(validPrefix, 10, 64)
if err1 != nil {
return iVal, errors.Trace(ErrOverflow)
}
return iVal, errors.Trace(err)
} | go | func StrToInt(sc *variable.StatementContext, str string) (int64, error) {
str = strings.TrimSpace(str)
validPrefix, err := getValidIntPrefix(sc, str)
iVal, err1 := strconv.ParseInt(validPrefix, 10, 64)
if err1 != nil {
return iVal, errors.Trace(ErrOverflow)
}
return iVal, errors.Trace(err)
} | [
"func",
"StrToInt",
"(",
"sc",
"*",
"variable",
".",
"StatementContext",
",",
"str",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"str",
"=",
"strings",
".",
"TrimSpace",
"(",
"str",
")",
"\n",
"validPrefix",
",",
"err",
":=",
"getValidIntPrefix",
"(",
"sc",
",",
"str",
")",
"\n",
"iVal",
",",
"err1",
":=",
"strconv",
".",
"ParseInt",
"(",
"validPrefix",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err1",
"!=",
"nil",
"{",
"return",
"iVal",
",",
"errors",
".",
"Trace",
"(",
"ErrOverflow",
")",
"\n",
"}",
"\n",
"return",
"iVal",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // StrToInt converts a string to an integer at the best-effort. | [
"StrToInt",
"converts",
"a",
"string",
"to",
"an",
"integer",
"at",
"the",
"best",
"-",
"effort",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/convert.go#L138-L146 | train |
chrislusf/gleam | sql/util/types/convert.go | floatStrToIntStr | func floatStrToIntStr(validFloat string) (string, error) {
var dotIdx = -1
var eIdx = -1
for i := 0; i < len(validFloat); i++ {
switch validFloat[i] {
case '.':
dotIdx = i
case 'e', 'E':
eIdx = i
}
}
if eIdx == -1 {
if dotIdx == -1 {
return validFloat, nil
}
return validFloat[:dotIdx], nil
}
var intCnt int
digits := make([]byte, 0, len(validFloat))
if dotIdx == -1 {
digits = append(digits, validFloat[:eIdx]...)
intCnt = len(digits)
} else {
digits = append(digits, validFloat[:dotIdx]...)
intCnt = len(digits)
digits = append(digits, validFloat[dotIdx+1:eIdx]...)
}
exp, err := strconv.Atoi(validFloat[eIdx+1:])
if err != nil {
return validFloat, errors.Trace(err)
}
if exp > 0 && intCnt > (math.MaxInt64-exp) {
// (exp + incCnt) overflows MaxInt64.
return validFloat, errors.Trace(ErrOverflow)
}
intCnt += exp
if intCnt <= 0 {
return "0", nil
}
if intCnt == 1 && (digits[0] == '-' || digits[0] == '+') {
return "0", nil
}
var validInt string
if intCnt <= len(digits) {
validInt = string(digits[:intCnt])
} else {
extraZeroCount := intCnt - len(digits)
if extraZeroCount > 20 {
// Return overflow to avoid allocating too much memory.
return validFloat, errors.Trace(ErrOverflow)
}
validInt = string(digits) + strings.Repeat("0", extraZeroCount)
}
return validInt, nil
} | go | func floatStrToIntStr(validFloat string) (string, error) {
var dotIdx = -1
var eIdx = -1
for i := 0; i < len(validFloat); i++ {
switch validFloat[i] {
case '.':
dotIdx = i
case 'e', 'E':
eIdx = i
}
}
if eIdx == -1 {
if dotIdx == -1 {
return validFloat, nil
}
return validFloat[:dotIdx], nil
}
var intCnt int
digits := make([]byte, 0, len(validFloat))
if dotIdx == -1 {
digits = append(digits, validFloat[:eIdx]...)
intCnt = len(digits)
} else {
digits = append(digits, validFloat[:dotIdx]...)
intCnt = len(digits)
digits = append(digits, validFloat[dotIdx+1:eIdx]...)
}
exp, err := strconv.Atoi(validFloat[eIdx+1:])
if err != nil {
return validFloat, errors.Trace(err)
}
if exp > 0 && intCnt > (math.MaxInt64-exp) {
// (exp + incCnt) overflows MaxInt64.
return validFloat, errors.Trace(ErrOverflow)
}
intCnt += exp
if intCnt <= 0 {
return "0", nil
}
if intCnt == 1 && (digits[0] == '-' || digits[0] == '+') {
return "0", nil
}
var validInt string
if intCnt <= len(digits) {
validInt = string(digits[:intCnt])
} else {
extraZeroCount := intCnt - len(digits)
if extraZeroCount > 20 {
// Return overflow to avoid allocating too much memory.
return validFloat, errors.Trace(ErrOverflow)
}
validInt = string(digits) + strings.Repeat("0", extraZeroCount)
}
return validInt, nil
} | [
"func",
"floatStrToIntStr",
"(",
"validFloat",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"dotIdx",
"=",
"-",
"1",
"\n",
"var",
"eIdx",
"=",
"-",
"1",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"validFloat",
")",
";",
"i",
"++",
"{",
"switch",
"validFloat",
"[",
"i",
"]",
"{",
"case",
"'.'",
":",
"dotIdx",
"=",
"i",
"\n",
"case",
"'e'",
",",
"'E'",
":",
"eIdx",
"=",
"i",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"eIdx",
"==",
"-",
"1",
"{",
"if",
"dotIdx",
"==",
"-",
"1",
"{",
"return",
"validFloat",
",",
"nil",
"\n",
"}",
"\n",
"return",
"validFloat",
"[",
":",
"dotIdx",
"]",
",",
"nil",
"\n",
"}",
"\n",
"var",
"intCnt",
"int",
"\n",
"digits",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"len",
"(",
"validFloat",
")",
")",
"\n",
"if",
"dotIdx",
"==",
"-",
"1",
"{",
"digits",
"=",
"append",
"(",
"digits",
",",
"validFloat",
"[",
":",
"eIdx",
"]",
"...",
")",
"\n",
"intCnt",
"=",
"len",
"(",
"digits",
")",
"\n",
"}",
"else",
"{",
"digits",
"=",
"append",
"(",
"digits",
",",
"validFloat",
"[",
":",
"dotIdx",
"]",
"...",
")",
"\n",
"intCnt",
"=",
"len",
"(",
"digits",
")",
"\n",
"digits",
"=",
"append",
"(",
"digits",
",",
"validFloat",
"[",
"dotIdx",
"+",
"1",
":",
"eIdx",
"]",
"...",
")",
"\n",
"}",
"\n",
"exp",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"validFloat",
"[",
"eIdx",
"+",
"1",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"validFloat",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"exp",
">",
"0",
"&&",
"intCnt",
">",
"(",
"math",
".",
"MaxInt64",
"-",
"exp",
")",
"{",
"// (exp + incCnt) overflows MaxInt64.",
"return",
"validFloat",
",",
"errors",
".",
"Trace",
"(",
"ErrOverflow",
")",
"\n",
"}",
"\n",
"intCnt",
"+=",
"exp",
"\n",
"if",
"intCnt",
"<=",
"0",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"if",
"intCnt",
"==",
"1",
"&&",
"(",
"digits",
"[",
"0",
"]",
"==",
"'-'",
"||",
"digits",
"[",
"0",
"]",
"==",
"'+'",
")",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"var",
"validInt",
"string",
"\n",
"if",
"intCnt",
"<=",
"len",
"(",
"digits",
")",
"{",
"validInt",
"=",
"string",
"(",
"digits",
"[",
":",
"intCnt",
"]",
")",
"\n",
"}",
"else",
"{",
"extraZeroCount",
":=",
"intCnt",
"-",
"len",
"(",
"digits",
")",
"\n",
"if",
"extraZeroCount",
">",
"20",
"{",
"// Return overflow to avoid allocating too much memory.",
"return",
"validFloat",
",",
"errors",
".",
"Trace",
"(",
"ErrOverflow",
")",
"\n",
"}",
"\n",
"validInt",
"=",
"string",
"(",
"digits",
")",
"+",
"strings",
".",
"Repeat",
"(",
"\"",
"\"",
",",
"extraZeroCount",
")",
"\n",
"}",
"\n",
"return",
"validInt",
",",
"nil",
"\n",
"}"
] | // floatStrToIntStr converts a valid float string into valid integer string which can be parsed by
// strconv.ParseInt, we can't parse float first then convert it to string because precision will
// be lost. | [
"floatStrToIntStr",
"converts",
"a",
"valid",
"float",
"string",
"into",
"valid",
"integer",
"string",
"which",
"can",
"be",
"parsed",
"by",
"strconv",
".",
"ParseInt",
"we",
"can",
"t",
"parse",
"float",
"first",
"then",
"convert",
"it",
"to",
"string",
"because",
"precision",
"will",
"be",
"lost",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/convert.go#L174-L228 | train |
chrislusf/gleam | sql/util/types/convert.go | getValidFloatPrefix | func getValidFloatPrefix(sc *variable.StatementContext, s string) (valid string, err error) {
var (
sawDot bool
sawDigit bool
validLen int
eIdx int
)
for i := 0; i < len(s); i++ {
c := s[i]
if c == '+' || c == '-' {
if i != 0 && i != eIdx+1 { // "1e+1" is valid.
break
}
} else if c == '.' {
if sawDot || eIdx > 0 { // "1.1." or "1e1.1"
break
}
sawDot = true
if sawDigit { // "123." is valid.
validLen = i + 1
}
} else if c == 'e' || c == 'E' {
if !sawDigit { // "+.e"
break
}
if eIdx != 0 { // "1e5e"
break
}
eIdx = i
} else if c < '0' || c > '9' {
break
} else {
sawDigit = true
validLen = i + 1
}
}
valid = s[:validLen]
if valid == "" {
valid = "0"
}
if validLen == 0 || validLen != len(s) {
err = errors.Trace(handleTruncateError(sc))
}
return valid, err
} | go | func getValidFloatPrefix(sc *variable.StatementContext, s string) (valid string, err error) {
var (
sawDot bool
sawDigit bool
validLen int
eIdx int
)
for i := 0; i < len(s); i++ {
c := s[i]
if c == '+' || c == '-' {
if i != 0 && i != eIdx+1 { // "1e+1" is valid.
break
}
} else if c == '.' {
if sawDot || eIdx > 0 { // "1.1." or "1e1.1"
break
}
sawDot = true
if sawDigit { // "123." is valid.
validLen = i + 1
}
} else if c == 'e' || c == 'E' {
if !sawDigit { // "+.e"
break
}
if eIdx != 0 { // "1e5e"
break
}
eIdx = i
} else if c < '0' || c > '9' {
break
} else {
sawDigit = true
validLen = i + 1
}
}
valid = s[:validLen]
if valid == "" {
valid = "0"
}
if validLen == 0 || validLen != len(s) {
err = errors.Trace(handleTruncateError(sc))
}
return valid, err
} | [
"func",
"getValidFloatPrefix",
"(",
"sc",
"*",
"variable",
".",
"StatementContext",
",",
"s",
"string",
")",
"(",
"valid",
"string",
",",
"err",
"error",
")",
"{",
"var",
"(",
"sawDot",
"bool",
"\n",
"sawDigit",
"bool",
"\n",
"validLen",
"int",
"\n",
"eIdx",
"int",
"\n",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"s",
")",
";",
"i",
"++",
"{",
"c",
":=",
"s",
"[",
"i",
"]",
"\n",
"if",
"c",
"==",
"'+'",
"||",
"c",
"==",
"'-'",
"{",
"if",
"i",
"!=",
"0",
"&&",
"i",
"!=",
"eIdx",
"+",
"1",
"{",
"// \"1e+1\" is valid.",
"break",
"\n",
"}",
"\n",
"}",
"else",
"if",
"c",
"==",
"'.'",
"{",
"if",
"sawDot",
"||",
"eIdx",
">",
"0",
"{",
"// \"1.1.\" or \"1e1.1\"",
"break",
"\n",
"}",
"\n",
"sawDot",
"=",
"true",
"\n",
"if",
"sawDigit",
"{",
"// \"123.\" is valid.",
"validLen",
"=",
"i",
"+",
"1",
"\n",
"}",
"\n",
"}",
"else",
"if",
"c",
"==",
"'e'",
"||",
"c",
"==",
"'E'",
"{",
"if",
"!",
"sawDigit",
"{",
"// \"+.e\"",
"break",
"\n",
"}",
"\n",
"if",
"eIdx",
"!=",
"0",
"{",
"// \"1e5e\"",
"break",
"\n",
"}",
"\n",
"eIdx",
"=",
"i",
"\n",
"}",
"else",
"if",
"c",
"<",
"'0'",
"||",
"c",
">",
"'9'",
"{",
"break",
"\n",
"}",
"else",
"{",
"sawDigit",
"=",
"true",
"\n",
"validLen",
"=",
"i",
"+",
"1",
"\n",
"}",
"\n",
"}",
"\n",
"valid",
"=",
"s",
"[",
":",
"validLen",
"]",
"\n",
"if",
"valid",
"==",
"\"",
"\"",
"{",
"valid",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"validLen",
"==",
"0",
"||",
"validLen",
"!=",
"len",
"(",
"s",
")",
"{",
"err",
"=",
"errors",
".",
"Trace",
"(",
"handleTruncateError",
"(",
"sc",
")",
")",
"\n",
"}",
"\n",
"return",
"valid",
",",
"err",
"\n",
"}"
] | // getValidFloatPrefix gets prefix of string which can be successfully parsed as float. | [
"getValidFloatPrefix",
"gets",
"prefix",
"of",
"string",
"which",
"can",
"be",
"successfully",
"parsed",
"as",
"float",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/convert.go#L242-L286 | train |
chrislusf/gleam | sql/util/types/convert.go | ToString | func ToString(value interface{}) (string, error) {
switch v := value.(type) {
case bool:
if v {
return "1", nil
}
return "0", nil
case int:
return strconv.FormatInt(int64(v), 10), nil
case int64:
return strconv.FormatInt(int64(v), 10), nil
case uint64:
return strconv.FormatUint(uint64(v), 10), nil
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32), nil
case float64:
return strconv.FormatFloat(float64(v), 'f', -1, 64), nil
case string:
return v, nil
case []byte:
return string(v), nil
case Time:
return v.String(), nil
case Duration:
return v.String(), nil
case *MyDecimal:
return v.String(), nil
case Hex:
return v.ToString(), nil
case Bit:
return v.ToString(), nil
case Enum:
return v.String(), nil
case Set:
return v.String(), nil
default:
return "", errors.Errorf("cannot convert %v(type %T) to string", value, value)
}
} | go | func ToString(value interface{}) (string, error) {
switch v := value.(type) {
case bool:
if v {
return "1", nil
}
return "0", nil
case int:
return strconv.FormatInt(int64(v), 10), nil
case int64:
return strconv.FormatInt(int64(v), 10), nil
case uint64:
return strconv.FormatUint(uint64(v), 10), nil
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32), nil
case float64:
return strconv.FormatFloat(float64(v), 'f', -1, 64), nil
case string:
return v, nil
case []byte:
return string(v), nil
case Time:
return v.String(), nil
case Duration:
return v.String(), nil
case *MyDecimal:
return v.String(), nil
case Hex:
return v.ToString(), nil
case Bit:
return v.ToString(), nil
case Enum:
return v.String(), nil
case Set:
return v.String(), nil
default:
return "", errors.Errorf("cannot convert %v(type %T) to string", value, value)
}
} | [
"func",
"ToString",
"(",
"value",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"switch",
"v",
":=",
"value",
".",
"(",
"type",
")",
"{",
"case",
"bool",
":",
"if",
"v",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"case",
"int",
":",
"return",
"strconv",
".",
"FormatInt",
"(",
"int64",
"(",
"v",
")",
",",
"10",
")",
",",
"nil",
"\n",
"case",
"int64",
":",
"return",
"strconv",
".",
"FormatInt",
"(",
"int64",
"(",
"v",
")",
",",
"10",
")",
",",
"nil",
"\n",
"case",
"uint64",
":",
"return",
"strconv",
".",
"FormatUint",
"(",
"uint64",
"(",
"v",
")",
",",
"10",
")",
",",
"nil",
"\n",
"case",
"float32",
":",
"return",
"strconv",
".",
"FormatFloat",
"(",
"float64",
"(",
"v",
")",
",",
"'f'",
",",
"-",
"1",
",",
"32",
")",
",",
"nil",
"\n",
"case",
"float64",
":",
"return",
"strconv",
".",
"FormatFloat",
"(",
"float64",
"(",
"v",
")",
",",
"'f'",
",",
"-",
"1",
",",
"64",
")",
",",
"nil",
"\n",
"case",
"string",
":",
"return",
"v",
",",
"nil",
"\n",
"case",
"[",
"]",
"byte",
":",
"return",
"string",
"(",
"v",
")",
",",
"nil",
"\n",
"case",
"Time",
":",
"return",
"v",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"case",
"Duration",
":",
"return",
"v",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"case",
"*",
"MyDecimal",
":",
"return",
"v",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"case",
"Hex",
":",
"return",
"v",
".",
"ToString",
"(",
")",
",",
"nil",
"\n",
"case",
"Bit",
":",
"return",
"v",
".",
"ToString",
"(",
")",
",",
"nil",
"\n",
"case",
"Enum",
":",
"return",
"v",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"case",
"Set",
":",
"return",
"v",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"default",
":",
"return",
"\"",
"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"value",
",",
"value",
")",
"\n",
"}",
"\n",
"}"
] | // ToString converts an interface to a string. | [
"ToString",
"converts",
"an",
"interface",
"to",
"a",
"string",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/convert.go#L289-L327 | train |
chrislusf/gleam | sql/plan/validator.go | Validate | func Validate(node ast.Node, inPrepare bool) error {
v := validator{inPrepare: inPrepare}
node.Accept(&v)
return v.err
} | go | func Validate(node ast.Node, inPrepare bool) error {
v := validator{inPrepare: inPrepare}
node.Accept(&v)
return v.err
} | [
"func",
"Validate",
"(",
"node",
"ast",
".",
"Node",
",",
"inPrepare",
"bool",
")",
"error",
"{",
"v",
":=",
"validator",
"{",
"inPrepare",
":",
"inPrepare",
"}",
"\n",
"node",
".",
"Accept",
"(",
"&",
"v",
")",
"\n",
"return",
"v",
".",
"err",
"\n",
"}"
] | // Validate checkes whether the node is valid. | [
"Validate",
"checkes",
"whether",
"the",
"node",
"is",
"valid",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/validator.go#L29-L33 | train |
chrislusf/gleam | sql/plan/predicate_push_down.go | outerJoinSimplify | func outerJoinSimplify(p *Join, predicates []expression.Expression) error {
var innerTable, outerTable LogicalPlan
child1 := p.GetChildByIndex(0).(LogicalPlan)
child2 := p.GetChildByIndex(1).(LogicalPlan)
var fullConditions []expression.Expression
if p.JoinType == LeftOuterJoin {
innerTable = child2
outerTable = child1
} else if p.JoinType == RightOuterJoin || p.JoinType == InnerJoin {
innerTable = child1
outerTable = child2
} else {
return nil
}
// first simplify embedded outer join.
// When trying to simplify an embedded outer join operation in a query,
// we must take into account the join condition for the embedding outer join together with the WHERE condition.
if innerPlan, ok := innerTable.(*Join); ok {
fullConditions = concatOnAndWhereConds(p, predicates)
err := outerJoinSimplify(innerPlan, fullConditions)
if err != nil {
return errors.Trace(err)
}
}
if outerPlan, ok := outerTable.(*Join); ok {
if fullConditions != nil {
fullConditions = concatOnAndWhereConds(p, predicates)
}
err := outerJoinSimplify(outerPlan, fullConditions)
if err != nil {
return errors.Trace(err)
}
}
if p.JoinType == InnerJoin {
return nil
}
// then simplify embedding outer join.
canBeSimplified := false
for _, expr := range predicates {
isOk, err := isNullRejected(p.ctx, innerTable.GetSchema(), expr)
if err != nil {
return errors.Trace(err)
}
if isOk {
canBeSimplified = true
break
}
}
if canBeSimplified {
p.JoinType = InnerJoin
}
return nil
} | go | func outerJoinSimplify(p *Join, predicates []expression.Expression) error {
var innerTable, outerTable LogicalPlan
child1 := p.GetChildByIndex(0).(LogicalPlan)
child2 := p.GetChildByIndex(1).(LogicalPlan)
var fullConditions []expression.Expression
if p.JoinType == LeftOuterJoin {
innerTable = child2
outerTable = child1
} else if p.JoinType == RightOuterJoin || p.JoinType == InnerJoin {
innerTable = child1
outerTable = child2
} else {
return nil
}
// first simplify embedded outer join.
// When trying to simplify an embedded outer join operation in a query,
// we must take into account the join condition for the embedding outer join together with the WHERE condition.
if innerPlan, ok := innerTable.(*Join); ok {
fullConditions = concatOnAndWhereConds(p, predicates)
err := outerJoinSimplify(innerPlan, fullConditions)
if err != nil {
return errors.Trace(err)
}
}
if outerPlan, ok := outerTable.(*Join); ok {
if fullConditions != nil {
fullConditions = concatOnAndWhereConds(p, predicates)
}
err := outerJoinSimplify(outerPlan, fullConditions)
if err != nil {
return errors.Trace(err)
}
}
if p.JoinType == InnerJoin {
return nil
}
// then simplify embedding outer join.
canBeSimplified := false
for _, expr := range predicates {
isOk, err := isNullRejected(p.ctx, innerTable.GetSchema(), expr)
if err != nil {
return errors.Trace(err)
}
if isOk {
canBeSimplified = true
break
}
}
if canBeSimplified {
p.JoinType = InnerJoin
}
return nil
} | [
"func",
"outerJoinSimplify",
"(",
"p",
"*",
"Join",
",",
"predicates",
"[",
"]",
"expression",
".",
"Expression",
")",
"error",
"{",
"var",
"innerTable",
",",
"outerTable",
"LogicalPlan",
"\n",
"child1",
":=",
"p",
".",
"GetChildByIndex",
"(",
"0",
")",
".",
"(",
"LogicalPlan",
")",
"\n",
"child2",
":=",
"p",
".",
"GetChildByIndex",
"(",
"1",
")",
".",
"(",
"LogicalPlan",
")",
"\n",
"var",
"fullConditions",
"[",
"]",
"expression",
".",
"Expression",
"\n",
"if",
"p",
".",
"JoinType",
"==",
"LeftOuterJoin",
"{",
"innerTable",
"=",
"child2",
"\n",
"outerTable",
"=",
"child1",
"\n",
"}",
"else",
"if",
"p",
".",
"JoinType",
"==",
"RightOuterJoin",
"||",
"p",
".",
"JoinType",
"==",
"InnerJoin",
"{",
"innerTable",
"=",
"child1",
"\n",
"outerTable",
"=",
"child2",
"\n",
"}",
"else",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"// first simplify embedded outer join.",
"// When trying to simplify an embedded outer join operation in a query,",
"// we must take into account the join condition for the embedding outer join together with the WHERE condition.",
"if",
"innerPlan",
",",
"ok",
":=",
"innerTable",
".",
"(",
"*",
"Join",
")",
";",
"ok",
"{",
"fullConditions",
"=",
"concatOnAndWhereConds",
"(",
"p",
",",
"predicates",
")",
"\n",
"err",
":=",
"outerJoinSimplify",
"(",
"innerPlan",
",",
"fullConditions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"outerPlan",
",",
"ok",
":=",
"outerTable",
".",
"(",
"*",
"Join",
")",
";",
"ok",
"{",
"if",
"fullConditions",
"!=",
"nil",
"{",
"fullConditions",
"=",
"concatOnAndWhereConds",
"(",
"p",
",",
"predicates",
")",
"\n",
"}",
"\n",
"err",
":=",
"outerJoinSimplify",
"(",
"outerPlan",
",",
"fullConditions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"p",
".",
"JoinType",
"==",
"InnerJoin",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"// then simplify embedding outer join.",
"canBeSimplified",
":=",
"false",
"\n",
"for",
"_",
",",
"expr",
":=",
"range",
"predicates",
"{",
"isOk",
",",
"err",
":=",
"isNullRejected",
"(",
"p",
".",
"ctx",
",",
"innerTable",
".",
"GetSchema",
"(",
")",
",",
"expr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"isOk",
"{",
"canBeSimplified",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"canBeSimplified",
"{",
"p",
".",
"JoinType",
"=",
"InnerJoin",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // outerJoinSimplify simplifies outer join. | [
"outerJoinSimplify",
"simplifies",
"outer",
"join",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/predicate_push_down.go#L145-L197 | train |
chrislusf/gleam | sql/plan/predicate_push_down.go | concatOnAndWhereConds | func concatOnAndWhereConds(join *Join, predicates []expression.Expression) []expression.Expression {
equalConds, leftConds, rightConds, otherConds := join.EqualConditions, join.LeftConditions, join.RightConditions, join.OtherConditions
ans := make([]expression.Expression, 0, len(equalConds)+len(leftConds)+len(rightConds)+len(predicates))
for _, v := range equalConds {
ans = append(ans, v)
}
ans = append(ans, leftConds...)
ans = append(ans, rightConds...)
ans = append(ans, otherConds...)
ans = append(ans, predicates...)
return ans
} | go | func concatOnAndWhereConds(join *Join, predicates []expression.Expression) []expression.Expression {
equalConds, leftConds, rightConds, otherConds := join.EqualConditions, join.LeftConditions, join.RightConditions, join.OtherConditions
ans := make([]expression.Expression, 0, len(equalConds)+len(leftConds)+len(rightConds)+len(predicates))
for _, v := range equalConds {
ans = append(ans, v)
}
ans = append(ans, leftConds...)
ans = append(ans, rightConds...)
ans = append(ans, otherConds...)
ans = append(ans, predicates...)
return ans
} | [
"func",
"concatOnAndWhereConds",
"(",
"join",
"*",
"Join",
",",
"predicates",
"[",
"]",
"expression",
".",
"Expression",
")",
"[",
"]",
"expression",
".",
"Expression",
"{",
"equalConds",
",",
"leftConds",
",",
"rightConds",
",",
"otherConds",
":=",
"join",
".",
"EqualConditions",
",",
"join",
".",
"LeftConditions",
",",
"join",
".",
"RightConditions",
",",
"join",
".",
"OtherConditions",
"\n",
"ans",
":=",
"make",
"(",
"[",
"]",
"expression",
".",
"Expression",
",",
"0",
",",
"len",
"(",
"equalConds",
")",
"+",
"len",
"(",
"leftConds",
")",
"+",
"len",
"(",
"rightConds",
")",
"+",
"len",
"(",
"predicates",
")",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"equalConds",
"{",
"ans",
"=",
"append",
"(",
"ans",
",",
"v",
")",
"\n",
"}",
"\n",
"ans",
"=",
"append",
"(",
"ans",
",",
"leftConds",
"...",
")",
"\n",
"ans",
"=",
"append",
"(",
"ans",
",",
"rightConds",
"...",
")",
"\n",
"ans",
"=",
"append",
"(",
"ans",
",",
"otherConds",
"...",
")",
"\n",
"ans",
"=",
"append",
"(",
"ans",
",",
"predicates",
"...",
")",
"\n",
"return",
"ans",
"\n",
"}"
] | // concatOnAndWhereConds concatenate ON conditions with WHERE conditions. | [
"concatOnAndWhereConds",
"concatenate",
"ON",
"conditions",
"with",
"WHERE",
"conditions",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/predicate_push_down.go#L223-L234 | train |
chrislusf/gleam | util/row_codec.go | fieldsNotEmpty | func (z *Row) fieldsNotEmpty(isempty []bool) uint32 {
if len(isempty) == 0 {
return 3
}
var fieldsInUse uint32 = 3
isempty[0] = (len(z.K) == 0) // string, omitempty
if isempty[0] {
fieldsInUse--
}
isempty[1] = (len(z.V) == 0) // string, omitempty
if isempty[1] {
fieldsInUse--
}
isempty[2] = (z.T == 0) // number, omitempty
if isempty[2] {
fieldsInUse--
}
return fieldsInUse
} | go | func (z *Row) fieldsNotEmpty(isempty []bool) uint32 {
if len(isempty) == 0 {
return 3
}
var fieldsInUse uint32 = 3
isempty[0] = (len(z.K) == 0) // string, omitempty
if isempty[0] {
fieldsInUse--
}
isempty[1] = (len(z.V) == 0) // string, omitempty
if isempty[1] {
fieldsInUse--
}
isempty[2] = (z.T == 0) // number, omitempty
if isempty[2] {
fieldsInUse--
}
return fieldsInUse
} | [
"func",
"(",
"z",
"*",
"Row",
")",
"fieldsNotEmpty",
"(",
"isempty",
"[",
"]",
"bool",
")",
"uint32",
"{",
"if",
"len",
"(",
"isempty",
")",
"==",
"0",
"{",
"return",
"3",
"\n",
"}",
"\n",
"var",
"fieldsInUse",
"uint32",
"=",
"3",
"\n",
"isempty",
"[",
"0",
"]",
"=",
"(",
"len",
"(",
"z",
".",
"K",
")",
"==",
"0",
")",
"// string, omitempty",
"\n",
"if",
"isempty",
"[",
"0",
"]",
"{",
"fieldsInUse",
"--",
"\n",
"}",
"\n",
"isempty",
"[",
"1",
"]",
"=",
"(",
"len",
"(",
"z",
".",
"V",
")",
"==",
"0",
")",
"// string, omitempty",
"\n",
"if",
"isempty",
"[",
"1",
"]",
"{",
"fieldsInUse",
"--",
"\n",
"}",
"\n",
"isempty",
"[",
"2",
"]",
"=",
"(",
"z",
".",
"T",
"==",
"0",
")",
"// number, omitempty",
"\n",
"if",
"isempty",
"[",
"2",
"]",
"{",
"fieldsInUse",
"--",
"\n",
"}",
"\n\n",
"return",
"fieldsInUse",
"\n",
"}"
] | // fieldsNotEmpty supports omitempty tags | [
"fieldsNotEmpty",
"supports",
"omitempty",
"tags"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/util/row_codec.go#L145-L164 | train |
chrislusf/gleam | sql/expression/constant_propagation.go | PropagateConstant | func PropagateConstant(ctx context.Context, conditions []Expression) []Expression {
solver := &propagateConstantSolver{
colMapper: make(map[string]int),
ctx: ctx,
}
return solver.solve(conditions)
} | go | func PropagateConstant(ctx context.Context, conditions []Expression) []Expression {
solver := &propagateConstantSolver{
colMapper: make(map[string]int),
ctx: ctx,
}
return solver.solve(conditions)
} | [
"func",
"PropagateConstant",
"(",
"ctx",
"context",
".",
"Context",
",",
"conditions",
"[",
"]",
"Expression",
")",
"[",
"]",
"Expression",
"{",
"solver",
":=",
"&",
"propagateConstantSolver",
"{",
"colMapper",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
")",
",",
"ctx",
":",
"ctx",
",",
"}",
"\n",
"return",
"solver",
".",
"solve",
"(",
"conditions",
")",
"\n",
"}"
] | // PropagateConstant propagate constant values of equality predicates and inequality predicates in a condition. | [
"PropagateConstant",
"propagate",
"constant",
"values",
"of",
"equality",
"predicates",
"and",
"inequality",
"predicates",
"in",
"a",
"condition",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/constant_propagation.go#L255-L261 | train |
chrislusf/gleam | flow/dataset_sort_option.go | By | func (o *SortOption) By(index int, ascending bool) *SortOption {
order := instruction.Descending
if ascending {
order = instruction.Ascending
}
o.orderByList = append(o.orderByList, instruction.OrderBy{
Index: index,
Order: order,
})
return o
} | go | func (o *SortOption) By(index int, ascending bool) *SortOption {
order := instruction.Descending
if ascending {
order = instruction.Ascending
}
o.orderByList = append(o.orderByList, instruction.OrderBy{
Index: index,
Order: order,
})
return o
} | [
"func",
"(",
"o",
"*",
"SortOption",
")",
"By",
"(",
"index",
"int",
",",
"ascending",
"bool",
")",
"*",
"SortOption",
"{",
"order",
":=",
"instruction",
".",
"Descending",
"\n",
"if",
"ascending",
"{",
"order",
"=",
"instruction",
".",
"Ascending",
"\n",
"}",
"\n",
"o",
".",
"orderByList",
"=",
"append",
"(",
"o",
".",
"orderByList",
",",
"instruction",
".",
"OrderBy",
"{",
"Index",
":",
"index",
",",
"Order",
":",
"order",
",",
"}",
")",
"\n",
"return",
"o",
"\n",
"}"
] | // OrderBy chains a list of sorting order by | [
"OrderBy",
"chains",
"a",
"list",
"of",
"sorting",
"order",
"by"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_sort_option.go#L41-L51 | train |
chrislusf/gleam | flow/dataset_sort_option.go | Indexes | func (o *SortOption) Indexes() []int {
var ret []int
for _, x := range o.orderByList {
ret = append(ret, x.Index)
}
return ret
} | go | func (o *SortOption) Indexes() []int {
var ret []int
for _, x := range o.orderByList {
ret = append(ret, x.Index)
}
return ret
} | [
"func",
"(",
"o",
"*",
"SortOption",
")",
"Indexes",
"(",
")",
"[",
"]",
"int",
"{",
"var",
"ret",
"[",
"]",
"int",
"\n",
"for",
"_",
",",
"x",
":=",
"range",
"o",
".",
"orderByList",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"x",
".",
"Index",
")",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // return a list of indexes | [
"return",
"a",
"list",
"of",
"indexes"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_sort_option.go#L54-L60 | train |
chrislusf/gleam | sql/expression/schema.go | RetrieveColumn | func (s Schema) RetrieveColumn(col *Column) *Column {
index := s.GetColumnIndex(col)
if index != -1 {
return s.Columns[index]
}
return nil
} | go | func (s Schema) RetrieveColumn(col *Column) *Column {
index := s.GetColumnIndex(col)
if index != -1 {
return s.Columns[index]
}
return nil
} | [
"func",
"(",
"s",
"Schema",
")",
"RetrieveColumn",
"(",
"col",
"*",
"Column",
")",
"*",
"Column",
"{",
"index",
":=",
"s",
".",
"GetColumnIndex",
"(",
"col",
")",
"\n",
"if",
"index",
"!=",
"-",
"1",
"{",
"return",
"s",
".",
"Columns",
"[",
"index",
"]",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RetrieveColumn retrieves column in expression from the columns in schema. | [
"RetrieveColumn",
"retrieves",
"column",
"in",
"expression",
"from",
"the",
"columns",
"in",
"schema",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/schema.go#L97-L103 | train |
chrislusf/gleam | sql/expression/schema.go | GetColumnIndex | func (s Schema) GetColumnIndex(col *Column) int {
for i, c := range s.Columns {
if c.FromID == col.FromID && c.Position == col.Position {
return i
}
}
return -1
} | go | func (s Schema) GetColumnIndex(col *Column) int {
for i, c := range s.Columns {
if c.FromID == col.FromID && c.Position == col.Position {
return i
}
}
return -1
} | [
"func",
"(",
"s",
"Schema",
")",
"GetColumnIndex",
"(",
"col",
"*",
"Column",
")",
"int",
"{",
"for",
"i",
",",
"c",
":=",
"range",
"s",
".",
"Columns",
"{",
"if",
"c",
".",
"FromID",
"==",
"col",
".",
"FromID",
"&&",
"c",
".",
"Position",
"==",
"col",
".",
"Position",
"{",
"return",
"i",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] | // GetColumnIndex finds the index for a column. | [
"GetColumnIndex",
"finds",
"the",
"index",
"for",
"a",
"column",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/schema.go#L106-L113 | train |
chrislusf/gleam | sql/expression/schema.go | Append | func (s *Schema) Append(col *Column) {
s.Columns = append(s.Columns, col)
} | go | func (s *Schema) Append(col *Column) {
s.Columns = append(s.Columns, col)
} | [
"func",
"(",
"s",
"*",
"Schema",
")",
"Append",
"(",
"col",
"*",
"Column",
")",
"{",
"s",
".",
"Columns",
"=",
"append",
"(",
"s",
".",
"Columns",
",",
"col",
")",
"\n",
"}"
] | // Append append new column to the columns stored in schema. | [
"Append",
"append",
"new",
"column",
"to",
"the",
"columns",
"stored",
"in",
"schema",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/schema.go#L121-L123 | train |
chrislusf/gleam | sql/expression/schema.go | GetColumnsIndices | func (s Schema) GetColumnsIndices(cols []*Column) (ret []int) {
ret = make([]int, 0, len(cols))
for _, col := range cols {
pos := s.GetColumnIndex(col)
if pos != -1 {
ret = append(ret, pos)
} else {
return nil
}
}
return
} | go | func (s Schema) GetColumnsIndices(cols []*Column) (ret []int) {
ret = make([]int, 0, len(cols))
for _, col := range cols {
pos := s.GetColumnIndex(col)
if pos != -1 {
ret = append(ret, pos)
} else {
return nil
}
}
return
} | [
"func",
"(",
"s",
"Schema",
")",
"GetColumnsIndices",
"(",
"cols",
"[",
"]",
"*",
"Column",
")",
"(",
"ret",
"[",
"]",
"int",
")",
"{",
"ret",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
",",
"len",
"(",
"cols",
")",
")",
"\n",
"for",
"_",
",",
"col",
":=",
"range",
"cols",
"{",
"pos",
":=",
"s",
".",
"GetColumnIndex",
"(",
"col",
")",
"\n",
"if",
"pos",
"!=",
"-",
"1",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"pos",
")",
"\n",
"}",
"else",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // GetColumnsIndices will return a slice which contains the position of each column in schema.
// If there is one column that doesn't match, nil will be returned. | [
"GetColumnsIndices",
"will",
"return",
"a",
"slice",
"which",
"contains",
"the",
"position",
"of",
"each",
"column",
"in",
"schema",
".",
"If",
"there",
"is",
"one",
"column",
"that",
"doesn",
"t",
"match",
"nil",
"will",
"be",
"returned",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/schema.go#L132-L143 | train |
chrislusf/gleam | sql/expression/schema.go | MergeSchema | func MergeSchema(lSchema, rSchema Schema) Schema {
tmpL := lSchema.Clone()
tmpR := rSchema.Clone()
ret := NewSchema(append(tmpL.Columns, tmpR.Columns...))
ret.SetUniqueKeys(append(tmpL.Keys, tmpR.Keys...))
return ret
} | go | func MergeSchema(lSchema, rSchema Schema) Schema {
tmpL := lSchema.Clone()
tmpR := rSchema.Clone()
ret := NewSchema(append(tmpL.Columns, tmpR.Columns...))
ret.SetUniqueKeys(append(tmpL.Keys, tmpR.Keys...))
return ret
} | [
"func",
"MergeSchema",
"(",
"lSchema",
",",
"rSchema",
"Schema",
")",
"Schema",
"{",
"tmpL",
":=",
"lSchema",
".",
"Clone",
"(",
")",
"\n",
"tmpR",
":=",
"rSchema",
".",
"Clone",
"(",
")",
"\n",
"ret",
":=",
"NewSchema",
"(",
"append",
"(",
"tmpL",
".",
"Columns",
",",
"tmpR",
".",
"Columns",
"...",
")",
")",
"\n",
"ret",
".",
"SetUniqueKeys",
"(",
"append",
"(",
"tmpL",
".",
"Keys",
",",
"tmpR",
".",
"Keys",
"...",
")",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // MergeSchema will merge two schema into one schema. | [
"MergeSchema",
"will",
"merge",
"two",
"schema",
"into",
"one",
"schema",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/expression/schema.go#L146-L152 | train |
chrislusf/gleam | flow/dataset_join_hash.go | HashJoin | func (bigger *Dataset) HashJoin(name string, smaller *Dataset, sortOption *SortOption) *Dataset {
return smaller.Broadcast(name, len(bigger.Shards)).LocalHashAndJoinWith(name, bigger, sortOption)
} | go | func (bigger *Dataset) HashJoin(name string, smaller *Dataset, sortOption *SortOption) *Dataset {
return smaller.Broadcast(name, len(bigger.Shards)).LocalHashAndJoinWith(name, bigger, sortOption)
} | [
"func",
"(",
"bigger",
"*",
"Dataset",
")",
"HashJoin",
"(",
"name",
"string",
",",
"smaller",
"*",
"Dataset",
",",
"sortOption",
"*",
"SortOption",
")",
"*",
"Dataset",
"{",
"return",
"smaller",
".",
"Broadcast",
"(",
"name",
",",
"len",
"(",
"bigger",
".",
"Shards",
")",
")",
".",
"LocalHashAndJoinWith",
"(",
"name",
",",
"bigger",
",",
"sortOption",
")",
"\n",
"}"
] | // HashJoin joins two datasets by putting the smaller dataset in memory on all
// executors and streams through the bigger dataset. | [
"HashJoin",
"joins",
"two",
"datasets",
"by",
"putting",
"the",
"smaller",
"dataset",
"in",
"memory",
"on",
"all",
"executors",
"and",
"streams",
"through",
"the",
"bigger",
"dataset",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_join_hash.go#L9-L11 | train |
chrislusf/gleam | flow/dataset_join_hash.go | Broadcast | func (d *Dataset) Broadcast(name string, shardCount int) *Dataset {
if shardCount == 1 && len(d.Shards) == shardCount {
return d
}
ret := d.Flow.NewNextDataset(shardCount)
step := d.Flow.AddOneToAllStep(d, ret)
step.SetInstruction(name, instruction.NewBroadcast())
return ret
} | go | func (d *Dataset) Broadcast(name string, shardCount int) *Dataset {
if shardCount == 1 && len(d.Shards) == shardCount {
return d
}
ret := d.Flow.NewNextDataset(shardCount)
step := d.Flow.AddOneToAllStep(d, ret)
step.SetInstruction(name, instruction.NewBroadcast())
return ret
} | [
"func",
"(",
"d",
"*",
"Dataset",
")",
"Broadcast",
"(",
"name",
"string",
",",
"shardCount",
"int",
")",
"*",
"Dataset",
"{",
"if",
"shardCount",
"==",
"1",
"&&",
"len",
"(",
"d",
".",
"Shards",
")",
"==",
"shardCount",
"{",
"return",
"d",
"\n",
"}",
"\n",
"ret",
":=",
"d",
".",
"Flow",
".",
"NewNextDataset",
"(",
"shardCount",
")",
"\n",
"step",
":=",
"d",
".",
"Flow",
".",
"AddOneToAllStep",
"(",
"d",
",",
"ret",
")",
"\n",
"step",
".",
"SetInstruction",
"(",
"name",
",",
"instruction",
".",
"NewBroadcast",
"(",
")",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // Broadcast replicates itself to all shards. | [
"Broadcast",
"replicates",
"itself",
"to",
"all",
"shards",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_join_hash.go#L24-L32 | train |
chrislusf/gleam | distributed/master/ui/svg_writer_helper.go | linelabel | func linelabel(canvas *svg.SVG, x1, y1, x2, y2 int, label string, mark string, d1 string, d2 string, dir string, color string) {
aw := linesize * 4
ah := linesize * 3
if len(color) == 0 {
color = lcolor
}
switch mark {
case "b":
lx1, ly1 := arrow(canvas, x1, y1, aw, ah, d1, color)
lx2, ly2 := arrow(canvas, x2, y2, aw, ah, d2, color)
doline(canvas, lx1, ly1, lx2, ly2, linestyle(color), dir, label)
case "s":
lx1, ly1 := arrow(canvas, x1, y1, aw, ah, d1, color)
doline(canvas, lx1, ly1, x2, y2, linestyle(color), dir, label)
case "d":
lx2, ly2 := arrow(canvas, x2, y2, aw, ah, d2, color)
doline(canvas, x1, y1, lx2, ly2, linestyle(color), dir, label)
default:
doline(canvas, x1, y1, x2, y2, linestyle(color), dir, label)
}
} | go | func linelabel(canvas *svg.SVG, x1, y1, x2, y2 int, label string, mark string, d1 string, d2 string, dir string, color string) {
aw := linesize * 4
ah := linesize * 3
if len(color) == 0 {
color = lcolor
}
switch mark {
case "b":
lx1, ly1 := arrow(canvas, x1, y1, aw, ah, d1, color)
lx2, ly2 := arrow(canvas, x2, y2, aw, ah, d2, color)
doline(canvas, lx1, ly1, lx2, ly2, linestyle(color), dir, label)
case "s":
lx1, ly1 := arrow(canvas, x1, y1, aw, ah, d1, color)
doline(canvas, lx1, ly1, x2, y2, linestyle(color), dir, label)
case "d":
lx2, ly2 := arrow(canvas, x2, y2, aw, ah, d2, color)
doline(canvas, x1, y1, lx2, ly2, linestyle(color), dir, label)
default:
doline(canvas, x1, y1, x2, y2, linestyle(color), dir, label)
}
} | [
"func",
"linelabel",
"(",
"canvas",
"*",
"svg",
".",
"SVG",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"int",
",",
"label",
"string",
",",
"mark",
"string",
",",
"d1",
"string",
",",
"d2",
"string",
",",
"dir",
"string",
",",
"color",
"string",
")",
"{",
"aw",
":=",
"linesize",
"*",
"4",
"\n",
"ah",
":=",
"linesize",
"*",
"3",
"\n\n",
"if",
"len",
"(",
"color",
")",
"==",
"0",
"{",
"color",
"=",
"lcolor",
"\n",
"}",
"\n",
"switch",
"mark",
"{",
"case",
"\"",
"\"",
":",
"lx1",
",",
"ly1",
":=",
"arrow",
"(",
"canvas",
",",
"x1",
",",
"y1",
",",
"aw",
",",
"ah",
",",
"d1",
",",
"color",
")",
"\n",
"lx2",
",",
"ly2",
":=",
"arrow",
"(",
"canvas",
",",
"x2",
",",
"y2",
",",
"aw",
",",
"ah",
",",
"d2",
",",
"color",
")",
"\n",
"doline",
"(",
"canvas",
",",
"lx1",
",",
"ly1",
",",
"lx2",
",",
"ly2",
",",
"linestyle",
"(",
"color",
")",
",",
"dir",
",",
"label",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"lx1",
",",
"ly1",
":=",
"arrow",
"(",
"canvas",
",",
"x1",
",",
"y1",
",",
"aw",
",",
"ah",
",",
"d1",
",",
"color",
")",
"\n",
"doline",
"(",
"canvas",
",",
"lx1",
",",
"ly1",
",",
"x2",
",",
"y2",
",",
"linestyle",
"(",
"color",
")",
",",
"dir",
",",
"label",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"lx2",
",",
"ly2",
":=",
"arrow",
"(",
"canvas",
",",
"x2",
",",
"y2",
",",
"aw",
",",
"ah",
",",
"d2",
",",
"color",
")",
"\n",
"doline",
"(",
"canvas",
",",
"x1",
",",
"y1",
",",
"lx2",
",",
"ly2",
",",
"linestyle",
"(",
"color",
")",
",",
"dir",
",",
"label",
")",
"\n\n",
"default",
":",
"doline",
"(",
"canvas",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"linestyle",
"(",
"color",
")",
",",
"dir",
",",
"label",
")",
"\n",
"}",
"\n",
"}"
] | // linelabel determines the connection and arrow geometry | [
"linelabel",
"determines",
"the",
"connection",
"and",
"arrow",
"geometry"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/master/ui/svg_writer_helper.go#L65-L89 | train |
chrislusf/gleam | distributed/master/ui/svg_writer_helper.go | arrow | func arrow(canvas *svg.SVG, x, y, w, h int, dir string, color string) (xl, yl int) {
var xp = []int{x, x, x, x}
var yp = []int{y, y, y, y}
n := notchsize
switch dir {
case "r":
xp[1] = x - w
yp[1] = y - h/2
xp[2] = (x - w) + n
yp[2] = y
xp[3] = x - w
yp[3] = y + h/2
xl, yl = xp[2], y
case "l":
xp[1] = x + w
yp[1] = y - h/2
xp[2] = (x + w) - n
yp[2] = y
xp[3] = x + w
yp[3] = y + h/2
xl, yl = xp[2], y
case "u":
xp[1] = x - w/2
yp[1] = y + h
xp[2] = x
yp[2] = (y + h) - n
xp[3] = x + w/2
yp[3] = y + h
xl, yl = x, yp[2]
case "d":
xp[1] = x - w/2
yp[1] = y - h
xp[2] = x
yp[2] = (y - h) + n
xp[3] = x + w/2
yp[3] = y - h
xl, yl = x, yp[2]
}
canvas.Polygon(xp, yp, "fill:"+color+";fill-opacity:"+lopacity)
return xl, yl
} | go | func arrow(canvas *svg.SVG, x, y, w, h int, dir string, color string) (xl, yl int) {
var xp = []int{x, x, x, x}
var yp = []int{y, y, y, y}
n := notchsize
switch dir {
case "r":
xp[1] = x - w
yp[1] = y - h/2
xp[2] = (x - w) + n
yp[2] = y
xp[3] = x - w
yp[3] = y + h/2
xl, yl = xp[2], y
case "l":
xp[1] = x + w
yp[1] = y - h/2
xp[2] = (x + w) - n
yp[2] = y
xp[3] = x + w
yp[3] = y + h/2
xl, yl = xp[2], y
case "u":
xp[1] = x - w/2
yp[1] = y + h
xp[2] = x
yp[2] = (y + h) - n
xp[3] = x + w/2
yp[3] = y + h
xl, yl = x, yp[2]
case "d":
xp[1] = x - w/2
yp[1] = y - h
xp[2] = x
yp[2] = (y - h) + n
xp[3] = x + w/2
yp[3] = y - h
xl, yl = x, yp[2]
}
canvas.Polygon(xp, yp, "fill:"+color+";fill-opacity:"+lopacity)
return xl, yl
} | [
"func",
"arrow",
"(",
"canvas",
"*",
"svg",
".",
"SVG",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
"int",
",",
"dir",
"string",
",",
"color",
"string",
")",
"(",
"xl",
",",
"yl",
"int",
")",
"{",
"var",
"xp",
"=",
"[",
"]",
"int",
"{",
"x",
",",
"x",
",",
"x",
",",
"x",
"}",
"\n",
"var",
"yp",
"=",
"[",
"]",
"int",
"{",
"y",
",",
"y",
",",
"y",
",",
"y",
"}",
"\n\n",
"n",
":=",
"notchsize",
"\n",
"switch",
"dir",
"{",
"case",
"\"",
"\"",
":",
"xp",
"[",
"1",
"]",
"=",
"x",
"-",
"w",
"\n",
"yp",
"[",
"1",
"]",
"=",
"y",
"-",
"h",
"/",
"2",
"\n",
"xp",
"[",
"2",
"]",
"=",
"(",
"x",
"-",
"w",
")",
"+",
"n",
"\n",
"yp",
"[",
"2",
"]",
"=",
"y",
"\n",
"xp",
"[",
"3",
"]",
"=",
"x",
"-",
"w",
"\n",
"yp",
"[",
"3",
"]",
"=",
"y",
"+",
"h",
"/",
"2",
"\n",
"xl",
",",
"yl",
"=",
"xp",
"[",
"2",
"]",
",",
"y",
"\n",
"case",
"\"",
"\"",
":",
"xp",
"[",
"1",
"]",
"=",
"x",
"+",
"w",
"\n",
"yp",
"[",
"1",
"]",
"=",
"y",
"-",
"h",
"/",
"2",
"\n",
"xp",
"[",
"2",
"]",
"=",
"(",
"x",
"+",
"w",
")",
"-",
"n",
"\n",
"yp",
"[",
"2",
"]",
"=",
"y",
"\n",
"xp",
"[",
"3",
"]",
"=",
"x",
"+",
"w",
"\n",
"yp",
"[",
"3",
"]",
"=",
"y",
"+",
"h",
"/",
"2",
"\n",
"xl",
",",
"yl",
"=",
"xp",
"[",
"2",
"]",
",",
"y",
"\n",
"case",
"\"",
"\"",
":",
"xp",
"[",
"1",
"]",
"=",
"x",
"-",
"w",
"/",
"2",
"\n",
"yp",
"[",
"1",
"]",
"=",
"y",
"+",
"h",
"\n",
"xp",
"[",
"2",
"]",
"=",
"x",
"\n",
"yp",
"[",
"2",
"]",
"=",
"(",
"y",
"+",
"h",
")",
"-",
"n",
"\n",
"xp",
"[",
"3",
"]",
"=",
"x",
"+",
"w",
"/",
"2",
"\n",
"yp",
"[",
"3",
"]",
"=",
"y",
"+",
"h",
"\n",
"xl",
",",
"yl",
"=",
"x",
",",
"yp",
"[",
"2",
"]",
"\n",
"case",
"\"",
"\"",
":",
"xp",
"[",
"1",
"]",
"=",
"x",
"-",
"w",
"/",
"2",
"\n",
"yp",
"[",
"1",
"]",
"=",
"y",
"-",
"h",
"\n",
"xp",
"[",
"2",
"]",
"=",
"x",
"\n",
"yp",
"[",
"2",
"]",
"=",
"(",
"y",
"-",
"h",
")",
"+",
"n",
"\n",
"xp",
"[",
"3",
"]",
"=",
"x",
"+",
"w",
"/",
"2",
"\n",
"yp",
"[",
"3",
"]",
"=",
"y",
"-",
"h",
"\n",
"xl",
",",
"yl",
"=",
"x",
",",
"yp",
"[",
"2",
"]",
"\n",
"}",
"\n",
"canvas",
".",
"Polygon",
"(",
"xp",
",",
"yp",
",",
"\"",
"\"",
"+",
"color",
"+",
"\"",
"\"",
"+",
"lopacity",
")",
"\n",
"return",
"xl",
",",
"yl",
"\n",
"}"
] | // arrow constructs line-ending arrows according to connecting points | [
"arrow",
"constructs",
"line",
"-",
"ending",
"arrows",
"according",
"to",
"connecting",
"points"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/master/ui/svg_writer_helper.go#L97-L138 | train |
chrislusf/gleam | distributed/master/ui/svg_writer_helper.go | doline | func doline(canvas *svg.SVG, x1, y1, x2, y2 int, style, direction, label string) {
var labelstyle string
var upflag bool
tadjust := 6
mx := (x2 - x1) / 2
my := (y2 - y1) / 2
lx := x1 + mx
ly := y1 + my
m, _ := sloper(x1, y1, x2, y2)
hline := m == 0
vline := m == math.Inf(-1) || m == math.Inf(1)
straight := hline || vline
switch {
case m < 0: // upwards line
upflag = true
labelstyle += "text-anchor:end;"
lx -= tadjust
case hline: // horizontal line
labelstyle += "text-anchor:middle;baseline-shift:20%;"
ly -= tadjust
case m > 0: // downwards line
upflag = false
labelstyle += "text-anchor:start;"
lx += tadjust
}
if !straight && direction != "straight" {
cx, cy := x1, y2 // initial control points
// fmt.Fprintf(os.Stderr, "%s slope = %.3f\n", label, m)
if upflag {
if direction == "ccw" {
cx, cy = x2, y1
} else {
cx, cy = x1, y2
}
} else {
if direction == "ccw" {
cx, cy = x1, y2
} else {
cx, cy = x2, y1
}
}
canvas.Qbez(x1, y1, cx, cy, x2, y2, style)
labelstyle += "text-anchor:middle"
canvas.Text(lx, ly, label, labelstyle)
} else {
canvas.Line(x1, y1, x2, y2, style)
canvas.Text(lx, ly, label, labelstyle) // midpoint
}
} | go | func doline(canvas *svg.SVG, x1, y1, x2, y2 int, style, direction, label string) {
var labelstyle string
var upflag bool
tadjust := 6
mx := (x2 - x1) / 2
my := (y2 - y1) / 2
lx := x1 + mx
ly := y1 + my
m, _ := sloper(x1, y1, x2, y2)
hline := m == 0
vline := m == math.Inf(-1) || m == math.Inf(1)
straight := hline || vline
switch {
case m < 0: // upwards line
upflag = true
labelstyle += "text-anchor:end;"
lx -= tadjust
case hline: // horizontal line
labelstyle += "text-anchor:middle;baseline-shift:20%;"
ly -= tadjust
case m > 0: // downwards line
upflag = false
labelstyle += "text-anchor:start;"
lx += tadjust
}
if !straight && direction != "straight" {
cx, cy := x1, y2 // initial control points
// fmt.Fprintf(os.Stderr, "%s slope = %.3f\n", label, m)
if upflag {
if direction == "ccw" {
cx, cy = x2, y1
} else {
cx, cy = x1, y2
}
} else {
if direction == "ccw" {
cx, cy = x1, y2
} else {
cx, cy = x2, y1
}
}
canvas.Qbez(x1, y1, cx, cy, x2, y2, style)
labelstyle += "text-anchor:middle"
canvas.Text(lx, ly, label, labelstyle)
} else {
canvas.Line(x1, y1, x2, y2, style)
canvas.Text(lx, ly, label, labelstyle) // midpoint
}
} | [
"func",
"doline",
"(",
"canvas",
"*",
"svg",
".",
"SVG",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"int",
",",
"style",
",",
"direction",
",",
"label",
"string",
")",
"{",
"var",
"labelstyle",
"string",
"\n",
"var",
"upflag",
"bool",
"\n\n",
"tadjust",
":=",
"6",
"\n",
"mx",
":=",
"(",
"x2",
"-",
"x1",
")",
"/",
"2",
"\n",
"my",
":=",
"(",
"y2",
"-",
"y1",
")",
"/",
"2",
"\n",
"lx",
":=",
"x1",
"+",
"mx",
"\n",
"ly",
":=",
"y1",
"+",
"my",
"\n",
"m",
",",
"_",
":=",
"sloper",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
"\n",
"hline",
":=",
"m",
"==",
"0",
"\n",
"vline",
":=",
"m",
"==",
"math",
".",
"Inf",
"(",
"-",
"1",
")",
"||",
"m",
"==",
"math",
".",
"Inf",
"(",
"1",
")",
"\n",
"straight",
":=",
"hline",
"||",
"vline",
"\n\n",
"switch",
"{",
"case",
"m",
"<",
"0",
":",
"// upwards line",
"upflag",
"=",
"true",
"\n",
"labelstyle",
"+=",
"\"",
"\"",
"\n",
"lx",
"-=",
"tadjust",
"\n",
"case",
"hline",
":",
"// horizontal line",
"labelstyle",
"+=",
"\"",
"\"",
"\n",
"ly",
"-=",
"tadjust",
"\n",
"case",
"m",
">",
"0",
":",
"// downwards line",
"upflag",
"=",
"false",
"\n",
"labelstyle",
"+=",
"\"",
"\"",
"\n",
"lx",
"+=",
"tadjust",
"\n",
"}",
"\n",
"if",
"!",
"straight",
"&&",
"direction",
"!=",
"\"",
"\"",
"{",
"cx",
",",
"cy",
":=",
"x1",
",",
"y2",
"// initial control points",
"\n",
"// fmt.Fprintf(os.Stderr, \"%s slope = %.3f\\n\", label, m)",
"if",
"upflag",
"{",
"if",
"direction",
"==",
"\"",
"\"",
"{",
"cx",
",",
"cy",
"=",
"x2",
",",
"y1",
"\n",
"}",
"else",
"{",
"cx",
",",
"cy",
"=",
"x1",
",",
"y2",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"direction",
"==",
"\"",
"\"",
"{",
"cx",
",",
"cy",
"=",
"x1",
",",
"y2",
"\n",
"}",
"else",
"{",
"cx",
",",
"cy",
"=",
"x2",
",",
"y1",
"\n",
"}",
"\n",
"}",
"\n",
"canvas",
".",
"Qbez",
"(",
"x1",
",",
"y1",
",",
"cx",
",",
"cy",
",",
"x2",
",",
"y2",
",",
"style",
")",
"\n",
"labelstyle",
"+=",
"\"",
"\"",
"\n",
"canvas",
".",
"Text",
"(",
"lx",
",",
"ly",
",",
"label",
",",
"labelstyle",
")",
"\n",
"}",
"else",
"{",
"canvas",
".",
"Line",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"style",
")",
"\n",
"canvas",
".",
"Text",
"(",
"lx",
",",
"ly",
",",
"label",
",",
"labelstyle",
")",
"// midpoint",
"\n",
"}",
"\n",
"}"
] | // doline draws a line between to coordinates | [
"doline",
"draws",
"a",
"line",
"between",
"to",
"coordinates"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/master/ui/svg_writer_helper.go#L141-L191 | train |
chrislusf/gleam | distributed/master/ui/svg_writer_helper.go | sloper | func sloper(x1, y1, x2, y2 int) (m, r float64) {
dy := float64(y1 - y2)
dx := float64(x1 - x2)
m = dy / dx
r = math.Atan2(dy, dx) * (180 / math.Pi)
return m, r
} | go | func sloper(x1, y1, x2, y2 int) (m, r float64) {
dy := float64(y1 - y2)
dx := float64(x1 - x2)
m = dy / dx
r = math.Atan2(dy, dx) * (180 / math.Pi)
return m, r
} | [
"func",
"sloper",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"int",
")",
"(",
"m",
",",
"r",
"float64",
")",
"{",
"dy",
":=",
"float64",
"(",
"y1",
"-",
"y2",
")",
"\n",
"dx",
":=",
"float64",
"(",
"x1",
"-",
"x2",
")",
"\n",
"m",
"=",
"dy",
"/",
"dx",
"\n",
"r",
"=",
"math",
".",
"Atan2",
"(",
"dy",
",",
"dx",
")",
"*",
"(",
"180",
"/",
"math",
".",
"Pi",
")",
"\n",
"return",
"m",
",",
"r",
"\n",
"}"
] | // sloper computes the slope and r of a line | [
"sloper",
"computes",
"the",
"slope",
"and",
"r",
"of",
"a",
"line"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/master/ui/svg_writer_helper.go#L194-L200 | train |
chrislusf/gleam | gio/map_reduce.go | RegisterMapper | func RegisterMapper(fn Mapper) MapperId {
mappersLock.Lock()
defer mappersLock.Unlock()
mapperId := MapperId(fmt.Sprintf("m%d", len(mappers)+1))
mappers[mapperId] = MapperObject{fn, runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()}
return mapperId
} | go | func RegisterMapper(fn Mapper) MapperId {
mappersLock.Lock()
defer mappersLock.Unlock()
mapperId := MapperId(fmt.Sprintf("m%d", len(mappers)+1))
mappers[mapperId] = MapperObject{fn, runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()}
return mapperId
} | [
"func",
"RegisterMapper",
"(",
"fn",
"Mapper",
")",
"MapperId",
"{",
"mappersLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mappersLock",
".",
"Unlock",
"(",
")",
"\n\n",
"mapperId",
":=",
"MapperId",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"len",
"(",
"mappers",
")",
"+",
"1",
")",
")",
"\n",
"mappers",
"[",
"mapperId",
"]",
"=",
"MapperObject",
"{",
"fn",
",",
"runtime",
".",
"FuncForPC",
"(",
"reflect",
".",
"ValueOf",
"(",
"fn",
")",
".",
"Pointer",
"(",
")",
")",
".",
"Name",
"(",
")",
"}",
"\n\n",
"return",
"mapperId",
"\n",
"}"
] | // RegisterMapper register a mapper function to process a command | [
"RegisterMapper",
"register",
"a",
"mapper",
"function",
"to",
"process",
"a",
"command"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/gio/map_reduce.go#L75-L83 | train |
chrislusf/gleam | gio/map_reduce.go | ListRegisteredFunctions | func ListRegisteredFunctions() {
for k, fn := range mappers {
println(k, "=>", fn.Name)
}
for k, fn := range reducers {
println(k, "=>", fn.Name)
}
} | go | func ListRegisteredFunctions() {
for k, fn := range mappers {
println(k, "=>", fn.Name)
}
for k, fn := range reducers {
println(k, "=>", fn.Name)
}
} | [
"func",
"ListRegisteredFunctions",
"(",
")",
"{",
"for",
"k",
",",
"fn",
":=",
"range",
"mappers",
"{",
"println",
"(",
"k",
",",
"\"",
"\"",
",",
"fn",
".",
"Name",
")",
"\n",
"}",
"\n",
"for",
"k",
",",
"fn",
":=",
"range",
"reducers",
"{",
"println",
"(",
"k",
",",
"\"",
"\"",
",",
"fn",
".",
"Name",
")",
"\n",
"}",
"\n",
"}"
] | // ListRegisteredFunctions lists out all registered mappers and reducers | [
"ListRegisteredFunctions",
"lists",
"out",
"all",
"registered",
"mappers",
"and",
"reducers"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/gio/map_reduce.go#L129-L136 | train |
chrislusf/gleam | sql/plan/plan.go | getHashKey | func (p *requiredProperty) getHashKey() ([]byte, error) {
datums := make([]types.Datum, 0, len(p.props)*3+1)
datums = append(datums, types.NewDatum(p.sortKeyLen))
for _, c := range p.props {
datums = append(datums, types.NewDatum(c.desc), types.NewDatum(c.col.FromID), types.NewDatum(c.col.Index))
}
bytes, err := codec.EncodeValue(nil, datums...)
return bytes, errors.Trace(err)
} | go | func (p *requiredProperty) getHashKey() ([]byte, error) {
datums := make([]types.Datum, 0, len(p.props)*3+1)
datums = append(datums, types.NewDatum(p.sortKeyLen))
for _, c := range p.props {
datums = append(datums, types.NewDatum(c.desc), types.NewDatum(c.col.FromID), types.NewDatum(c.col.Index))
}
bytes, err := codec.EncodeValue(nil, datums...)
return bytes, errors.Trace(err)
} | [
"func",
"(",
"p",
"*",
"requiredProperty",
")",
"getHashKey",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"datums",
":=",
"make",
"(",
"[",
"]",
"types",
".",
"Datum",
",",
"0",
",",
"len",
"(",
"p",
".",
"props",
")",
"*",
"3",
"+",
"1",
")",
"\n",
"datums",
"=",
"append",
"(",
"datums",
",",
"types",
".",
"NewDatum",
"(",
"p",
".",
"sortKeyLen",
")",
")",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"p",
".",
"props",
"{",
"datums",
"=",
"append",
"(",
"datums",
",",
"types",
".",
"NewDatum",
"(",
"c",
".",
"desc",
")",
",",
"types",
".",
"NewDatum",
"(",
"c",
".",
"col",
".",
"FromID",
")",
",",
"types",
".",
"NewDatum",
"(",
"c",
".",
"col",
".",
"Index",
")",
")",
"\n",
"}",
"\n",
"bytes",
",",
"err",
":=",
"codec",
".",
"EncodeValue",
"(",
"nil",
",",
"datums",
"...",
")",
"\n",
"return",
"bytes",
",",
"errors",
".",
"Trace",
"(",
"err",
")",
"\n",
"}"
] | // getHashKey encodes a requiredProperty to a unique hash code. | [
"getHashKey",
"encodes",
"a",
"requiredProperty",
"to",
"a",
"unique",
"hash",
"code",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/plan.go#L132-L140 | train |
chrislusf/gleam | sql/plan/plan.go | ResolveIndicesAndCorCols | func (p *baseLogicalPlan) ResolveIndicesAndCorCols() {
for _, child := range p.children {
child.(LogicalPlan).ResolveIndicesAndCorCols()
}
} | go | func (p *baseLogicalPlan) ResolveIndicesAndCorCols() {
for _, child := range p.children {
child.(LogicalPlan).ResolveIndicesAndCorCols()
}
} | [
"func",
"(",
"p",
"*",
"baseLogicalPlan",
")",
"ResolveIndicesAndCorCols",
"(",
")",
"{",
"for",
"_",
",",
"child",
":=",
"range",
"p",
".",
"children",
"{",
"child",
".",
"(",
"LogicalPlan",
")",
".",
"ResolveIndicesAndCorCols",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // ResolveIndicesAndCorCols implements LogicalPlan interface. | [
"ResolveIndicesAndCorCols",
"implements",
"LogicalPlan",
"interface",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/plan.go#L293-L297 | train |
chrislusf/gleam | sql/plan/plan.go | AddParent | func (p *basePlan) AddParent(parent Plan) {
p.parents = append(p.parents, parent)
} | go | func (p *basePlan) AddParent(parent Plan) {
p.parents = append(p.parents, parent)
} | [
"func",
"(",
"p",
"*",
"basePlan",
")",
"AddParent",
"(",
"parent",
"Plan",
")",
"{",
"p",
".",
"parents",
"=",
"append",
"(",
"p",
".",
"parents",
",",
"parent",
")",
"\n",
"}"
] | // AddParent implements Plan AddParent interface. | [
"AddParent",
"implements",
"Plan",
"AddParent",
"interface",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/plan.go#L372-L374 | train |
chrislusf/gleam | sql/plan/plan.go | AddChild | func (p *basePlan) AddChild(child Plan) {
p.children = append(p.children, child)
} | go | func (p *basePlan) AddChild(child Plan) {
p.children = append(p.children, child)
} | [
"func",
"(",
"p",
"*",
"basePlan",
")",
"AddChild",
"(",
"child",
"Plan",
")",
"{",
"p",
".",
"children",
"=",
"append",
"(",
"p",
".",
"children",
",",
"child",
")",
"\n",
"}"
] | // AddChild implements Plan AddChild interface. | [
"AddChild",
"implements",
"Plan",
"AddChild",
"interface",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/plan.go#L377-L379 | train |
chrislusf/gleam | sql/plan/plan.go | ReplaceParent | func (p *basePlan) ReplaceParent(parent, newPar Plan) error {
for i, par := range p.parents {
if par.GetID() == parent.GetID() {
p.parents[i] = newPar
return nil
}
}
return SystemInternalErrorType.Gen("ReplaceParent Failed!")
} | go | func (p *basePlan) ReplaceParent(parent, newPar Plan) error {
for i, par := range p.parents {
if par.GetID() == parent.GetID() {
p.parents[i] = newPar
return nil
}
}
return SystemInternalErrorType.Gen("ReplaceParent Failed!")
} | [
"func",
"(",
"p",
"*",
"basePlan",
")",
"ReplaceParent",
"(",
"parent",
",",
"newPar",
"Plan",
")",
"error",
"{",
"for",
"i",
",",
"par",
":=",
"range",
"p",
".",
"parents",
"{",
"if",
"par",
".",
"GetID",
"(",
")",
"==",
"parent",
".",
"GetID",
"(",
")",
"{",
"p",
".",
"parents",
"[",
"i",
"]",
"=",
"newPar",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"SystemInternalErrorType",
".",
"Gen",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // ReplaceParent means replace a parent for another one. | [
"ReplaceParent",
"means",
"replace",
"a",
"parent",
"for",
"another",
"one",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/plan.go#L382-L390 | train |
chrislusf/gleam | sql/plan/plan.go | ReplaceChild | func (p *basePlan) ReplaceChild(child, newChild Plan) error {
for i, ch := range p.children {
if ch.GetID() == child.GetID() {
p.children[i] = newChild
return nil
}
}
return SystemInternalErrorType.Gen("ReplaceChildren Failed!")
} | go | func (p *basePlan) ReplaceChild(child, newChild Plan) error {
for i, ch := range p.children {
if ch.GetID() == child.GetID() {
p.children[i] = newChild
return nil
}
}
return SystemInternalErrorType.Gen("ReplaceChildren Failed!")
} | [
"func",
"(",
"p",
"*",
"basePlan",
")",
"ReplaceChild",
"(",
"child",
",",
"newChild",
"Plan",
")",
"error",
"{",
"for",
"i",
",",
"ch",
":=",
"range",
"p",
".",
"children",
"{",
"if",
"ch",
".",
"GetID",
"(",
")",
"==",
"child",
".",
"GetID",
"(",
")",
"{",
"p",
".",
"children",
"[",
"i",
"]",
"=",
"newChild",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"SystemInternalErrorType",
".",
"Gen",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // ReplaceChild means replace a child with another one. | [
"ReplaceChild",
"means",
"replace",
"a",
"child",
"with",
"another",
"one",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/plan.go#L393-L401 | train |
chrislusf/gleam | sql/plan/plan.go | GetParentByIndex | func (p *basePlan) GetParentByIndex(index int) (parent Plan) {
if index < len(p.parents) && index >= 0 {
return p.parents[index]
}
return nil
} | go | func (p *basePlan) GetParentByIndex(index int) (parent Plan) {
if index < len(p.parents) && index >= 0 {
return p.parents[index]
}
return nil
} | [
"func",
"(",
"p",
"*",
"basePlan",
")",
"GetParentByIndex",
"(",
"index",
"int",
")",
"(",
"parent",
"Plan",
")",
"{",
"if",
"index",
"<",
"len",
"(",
"p",
".",
"parents",
")",
"&&",
"index",
">=",
"0",
"{",
"return",
"p",
".",
"parents",
"[",
"index",
"]",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // GetParentByIndex implements Plan GetParentByIndex interface. | [
"GetParentByIndex",
"implements",
"Plan",
"GetParentByIndex",
"interface",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/plan.go#L404-L409 | train |
chrislusf/gleam | sql/plan/plan.go | GetChildByIndex | func (p *basePlan) GetChildByIndex(index int) (parent Plan) {
if index < len(p.children) && index >= 0 {
return p.children[index]
}
return nil
} | go | func (p *basePlan) GetChildByIndex(index int) (parent Plan) {
if index < len(p.children) && index >= 0 {
return p.children[index]
}
return nil
} | [
"func",
"(",
"p",
"*",
"basePlan",
")",
"GetChildByIndex",
"(",
"index",
"int",
")",
"(",
"parent",
"Plan",
")",
"{",
"if",
"index",
"<",
"len",
"(",
"p",
".",
"children",
")",
"&&",
"index",
">=",
"0",
"{",
"return",
"p",
".",
"children",
"[",
"index",
"]",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // GetChildByIndex implements Plan GetChildByIndex interface. | [
"GetChildByIndex",
"implements",
"Plan",
"GetChildByIndex",
"interface",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/plan.go#L412-L417 | train |
chrislusf/gleam | distributed/agent/agent_server.go | serveTcp | func (as *AgentServer) serveTcp(listener net.Listener) {
for {
// Listen for an incoming connection.
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
continue
}
// Handle connections in a new goroutine.
go func() {
defer conn.Close()
if err = conn.SetDeadline(time.Time{}); err != nil {
fmt.Printf("Failed to set timeout: %v\n", err)
}
if c, ok := conn.(*net.TCPConn); ok {
c.SetKeepAlive(true)
}
as.handleRequest(conn)
}()
}
} | go | func (as *AgentServer) serveTcp(listener net.Listener) {
for {
// Listen for an incoming connection.
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
continue
}
// Handle connections in a new goroutine.
go func() {
defer conn.Close()
if err = conn.SetDeadline(time.Time{}); err != nil {
fmt.Printf("Failed to set timeout: %v\n", err)
}
if c, ok := conn.(*net.TCPConn); ok {
c.SetKeepAlive(true)
}
as.handleRequest(conn)
}()
}
} | [
"func",
"(",
"as",
"*",
"AgentServer",
")",
"serveTcp",
"(",
"listener",
"net",
".",
"Listener",
")",
"{",
"for",
"{",
"// Listen for an incoming connection.",
"conn",
",",
"err",
":=",
"listener",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"// Handle connections in a new goroutine.",
"go",
"func",
"(",
")",
"{",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"=",
"conn",
".",
"SetDeadline",
"(",
"time",
".",
"Time",
"{",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"c",
",",
"ok",
":=",
"conn",
".",
"(",
"*",
"net",
".",
"TCPConn",
")",
";",
"ok",
"{",
"c",
".",
"SetKeepAlive",
"(",
"true",
")",
"\n",
"}",
"\n",
"as",
".",
"handleRequest",
"(",
"conn",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Run starts the heartbeating to master and starts accepting requests. | [
"Run",
"starts",
"the",
"heartbeating",
"to",
"master",
"and",
"starts",
"accepting",
"requests",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/distributed/agent/agent_server.go#L104-L125 | train |
chrislusf/gleam | sql/util/types/etc.go | IsTypeBlob | func IsTypeBlob(tp byte) bool {
switch tp {
case mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeBlob, mysql.TypeLongBlob:
return true
default:
return false
}
} | go | func IsTypeBlob(tp byte) bool {
switch tp {
case mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeBlob, mysql.TypeLongBlob:
return true
default:
return false
}
} | [
"func",
"IsTypeBlob",
"(",
"tp",
"byte",
")",
"bool",
"{",
"switch",
"tp",
"{",
"case",
"mysql",
".",
"TypeTinyBlob",
",",
"mysql",
".",
"TypeMediumBlob",
",",
"mysql",
".",
"TypeBlob",
",",
"mysql",
".",
"TypeLongBlob",
":",
"return",
"true",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // IsTypeBlob returns a boolean indicating whether the tp is a blob type. | [
"IsTypeBlob",
"returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"tp",
"is",
"a",
"blob",
"type",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/etc.go#L32-L39 | train |
chrislusf/gleam | sql/util/types/etc.go | IsTypeChar | func IsTypeChar(tp byte) bool {
switch tp {
case mysql.TypeString, mysql.TypeVarchar:
return true
default:
return false
}
} | go | func IsTypeChar(tp byte) bool {
switch tp {
case mysql.TypeString, mysql.TypeVarchar:
return true
default:
return false
}
} | [
"func",
"IsTypeChar",
"(",
"tp",
"byte",
")",
"bool",
"{",
"switch",
"tp",
"{",
"case",
"mysql",
".",
"TypeString",
",",
"mysql",
".",
"TypeVarchar",
":",
"return",
"true",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // IsTypeChar returns a boolean indicating
// whether the tp is the char type like a string type or a varchar type. | [
"IsTypeChar",
"returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"tp",
"is",
"the",
"char",
"type",
"like",
"a",
"string",
"type",
"or",
"a",
"varchar",
"type",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/etc.go#L43-L50 | train |
chrislusf/gleam | sql/util/types/etc.go | overflow | func overflow(v interface{}, tp byte) error {
return errors.Errorf("constant %v overflows %s", v, TypeStr(tp))
} | go | func overflow(v interface{}, tp byte) error {
return errors.Errorf("constant %v overflows %s", v, TypeStr(tp))
} | [
"func",
"overflow",
"(",
"v",
"interface",
"{",
"}",
",",
"tp",
"byte",
")",
"error",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
",",
"TypeStr",
"(",
"tp",
")",
")",
"\n",
"}"
] | // Overflow returns an overflowed error. | [
"Overflow",
"returns",
"an",
"overflowed",
"error",
"."
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/etc.go#L132-L134 | train |
chrislusf/gleam | instruction/select.go | DoSelect | func DoSelect(reader io.Reader, writer io.Writer, keyIndexes, valueIndexes []int, stats *pb.InstructionStat) error {
return util.ProcessRow(reader, nil, func(row *util.Row) error {
stats.InputCounter++
var keys, values []interface{}
kLen := len(row.K)
for _, x := range keyIndexes {
if x <= kLen {
keys = append(keys, row.K[x-1])
} else {
keys = append(keys, row.V[x-1-kLen])
}
}
for _, x := range valueIndexes {
if x <= kLen {
values = append(values, row.K[x-1])
} else {
values = append(values, row.V[x-1-kLen])
}
}
row.K, row.V = keys, values
row.WriteTo(writer)
stats.OutputCounter++
return nil
})
} | go | func DoSelect(reader io.Reader, writer io.Writer, keyIndexes, valueIndexes []int, stats *pb.InstructionStat) error {
return util.ProcessRow(reader, nil, func(row *util.Row) error {
stats.InputCounter++
var keys, values []interface{}
kLen := len(row.K)
for _, x := range keyIndexes {
if x <= kLen {
keys = append(keys, row.K[x-1])
} else {
keys = append(keys, row.V[x-1-kLen])
}
}
for _, x := range valueIndexes {
if x <= kLen {
values = append(values, row.K[x-1])
} else {
values = append(values, row.V[x-1-kLen])
}
}
row.K, row.V = keys, values
row.WriteTo(writer)
stats.OutputCounter++
return nil
})
} | [
"func",
"DoSelect",
"(",
"reader",
"io",
".",
"Reader",
",",
"writer",
"io",
".",
"Writer",
",",
"keyIndexes",
",",
"valueIndexes",
"[",
"]",
"int",
",",
"stats",
"*",
"pb",
".",
"InstructionStat",
")",
"error",
"{",
"return",
"util",
".",
"ProcessRow",
"(",
"reader",
",",
"nil",
",",
"func",
"(",
"row",
"*",
"util",
".",
"Row",
")",
"error",
"{",
"stats",
".",
"InputCounter",
"++",
"\n\n",
"var",
"keys",
",",
"values",
"[",
"]",
"interface",
"{",
"}",
"\n",
"kLen",
":=",
"len",
"(",
"row",
".",
"K",
")",
"\n",
"for",
"_",
",",
"x",
":=",
"range",
"keyIndexes",
"{",
"if",
"x",
"<=",
"kLen",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"row",
".",
"K",
"[",
"x",
"-",
"1",
"]",
")",
"\n",
"}",
"else",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"row",
".",
"V",
"[",
"x",
"-",
"1",
"-",
"kLen",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"x",
":=",
"range",
"valueIndexes",
"{",
"if",
"x",
"<=",
"kLen",
"{",
"values",
"=",
"append",
"(",
"values",
",",
"row",
".",
"K",
"[",
"x",
"-",
"1",
"]",
")",
"\n",
"}",
"else",
"{",
"values",
"=",
"append",
"(",
"values",
",",
"row",
".",
"V",
"[",
"x",
"-",
"1",
"-",
"kLen",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"row",
".",
"K",
",",
"row",
".",
"V",
"=",
"keys",
",",
"values",
"\n\n",
"row",
".",
"WriteTo",
"(",
"writer",
")",
"\n",
"stats",
".",
"OutputCounter",
"++",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n\n",
"}"
] | // DoSelect projects the fields | [
"DoSelect",
"projects",
"the",
"fields"
] | a7aa467b545f5e5e452aaf818299a5f6e6b23760 | https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/instruction/select.go#L57-L86 | train |
gojektech/heimdall | retry.go | NextInterval | func (r *retrier) NextInterval(retry int) time.Duration {
return r.backoff.Next(retry)
} | go | func (r *retrier) NextInterval(retry int) time.Duration {
return r.backoff.Next(retry)
} | [
"func",
"(",
"r",
"*",
"retrier",
")",
"NextInterval",
"(",
"retry",
"int",
")",
"time",
".",
"Duration",
"{",
"return",
"r",
".",
"backoff",
".",
"Next",
"(",
"retry",
")",
"\n",
"}"
] | // NextInterval returns next retriable time | [
"NextInterval",
"returns",
"next",
"retriable",
"time"
] | ef69e0bb0cbf72e832303efe6362855811e8cc89 | https://github.com/gojektech/heimdall/blob/ef69e0bb0cbf72e832303efe6362855811e8cc89/retry.go#L36-L38 | train |
gojektech/heimdall | hystrix/options.go | WithHTTPTimeout | func WithHTTPTimeout(timeout time.Duration) Option {
return func(c *Client) {
c.timeout = timeout
}
} | go | func WithHTTPTimeout(timeout time.Duration) Option {
return func(c *Client) {
c.timeout = timeout
}
} | [
"func",
"WithHTTPTimeout",
"(",
"timeout",
"time",
".",
"Duration",
")",
"Option",
"{",
"return",
"func",
"(",
"c",
"*",
"Client",
")",
"{",
"c",
".",
"timeout",
"=",
"timeout",
"\n",
"}",
"\n",
"}"
] | // WithHTTPTimeout sets hystrix timeout | [
"WithHTTPTimeout",
"sets",
"hystrix",
"timeout"
] | ef69e0bb0cbf72e832303efe6362855811e8cc89 | https://github.com/gojektech/heimdall/blob/ef69e0bb0cbf72e832303efe6362855811e8cc89/hystrix/options.go#L20-L24 | train |
gojektech/heimdall | hystrix/options.go | WithHystrixTimeout | func WithHystrixTimeout(timeout time.Duration) Option {
return func(c *Client) {
c.hystrixTimeout = timeout
}
} | go | func WithHystrixTimeout(timeout time.Duration) Option {
return func(c *Client) {
c.hystrixTimeout = timeout
}
} | [
"func",
"WithHystrixTimeout",
"(",
"timeout",
"time",
".",
"Duration",
")",
"Option",
"{",
"return",
"func",
"(",
"c",
"*",
"Client",
")",
"{",
"c",
".",
"hystrixTimeout",
"=",
"timeout",
"\n",
"}",
"\n",
"}"
] | // WithHystrixTimeout sets hystrix timeout | [
"WithHystrixTimeout",
"sets",
"hystrix",
"timeout"
] | ef69e0bb0cbf72e832303efe6362855811e8cc89 | https://github.com/gojektech/heimdall/blob/ef69e0bb0cbf72e832303efe6362855811e8cc89/hystrix/options.go#L27-L31 | train |
gojektech/heimdall | hystrix/options.go | WithRetrier | func WithRetrier(retrier heimdall.Retriable) Option {
return func(c *Client) {
c.retrier = retrier
}
} | go | func WithRetrier(retrier heimdall.Retriable) Option {
return func(c *Client) {
c.retrier = retrier
}
} | [
"func",
"WithRetrier",
"(",
"retrier",
"heimdall",
".",
"Retriable",
")",
"Option",
"{",
"return",
"func",
"(",
"c",
"*",
"Client",
")",
"{",
"c",
".",
"retrier",
"=",
"retrier",
"\n",
"}",
"\n",
"}"
] | // WithRetrier sets the strategy for retrying | [
"WithRetrier",
"sets",
"the",
"strategy",
"for",
"retrying"
] | ef69e0bb0cbf72e832303efe6362855811e8cc89 | https://github.com/gojektech/heimdall/blob/ef69e0bb0cbf72e832303efe6362855811e8cc89/hystrix/options.go#L76-L80 | train |
gojektech/heimdall | hystrix/options.go | WithHTTPClient | func WithHTTPClient(client heimdall.Doer) Option {
return func(c *Client) {
c.client = client
}
} | go | func WithHTTPClient(client heimdall.Doer) Option {
return func(c *Client) {
c.client = client
}
} | [
"func",
"WithHTTPClient",
"(",
"client",
"heimdall",
".",
"Doer",
")",
"Option",
"{",
"return",
"func",
"(",
"c",
"*",
"Client",
")",
"{",
"c",
".",
"client",
"=",
"client",
"\n",
"}",
"\n",
"}"
] | // WithHTTPClient sets a custom http client for hystrix client | [
"WithHTTPClient",
"sets",
"a",
"custom",
"http",
"client",
"for",
"hystrix",
"client"
] | ef69e0bb0cbf72e832303efe6362855811e8cc89 | https://github.com/gojektech/heimdall/blob/ef69e0bb0cbf72e832303efe6362855811e8cc89/hystrix/options.go#L83-L87 | train |
gojektech/heimdall | httpclient/client.go | NewClient | func NewClient(opts ...Option) *Client {
client := Client{
timeout: defaultHTTPTimeout,
retryCount: defaultRetryCount,
retrier: heimdall.NewNoRetrier(),
}
for _, opt := range opts {
opt(&client)
}
if client.client == nil {
client.client = &http.Client{
Timeout: client.timeout,
}
}
return &client
} | go | func NewClient(opts ...Option) *Client {
client := Client{
timeout: defaultHTTPTimeout,
retryCount: defaultRetryCount,
retrier: heimdall.NewNoRetrier(),
}
for _, opt := range opts {
opt(&client)
}
if client.client == nil {
client.client = &http.Client{
Timeout: client.timeout,
}
}
return &client
} | [
"func",
"NewClient",
"(",
"opts",
"...",
"Option",
")",
"*",
"Client",
"{",
"client",
":=",
"Client",
"{",
"timeout",
":",
"defaultHTTPTimeout",
",",
"retryCount",
":",
"defaultRetryCount",
",",
"retrier",
":",
"heimdall",
".",
"NewNoRetrier",
"(",
")",
",",
"}",
"\n\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
"(",
"&",
"client",
")",
"\n",
"}",
"\n\n",
"if",
"client",
".",
"client",
"==",
"nil",
"{",
"client",
".",
"client",
"=",
"&",
"http",
".",
"Client",
"{",
"Timeout",
":",
"client",
".",
"timeout",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"client",
"\n",
"}"
] | // NewClient returns a new instance of http Client | [
"NewClient",
"returns",
"a",
"new",
"instance",
"of",
"http",
"Client"
] | ef69e0bb0cbf72e832303efe6362855811e8cc89 | https://github.com/gojektech/heimdall/blob/ef69e0bb0cbf72e832303efe6362855811e8cc89/httpclient/client.go#L32-L50 | train |
gojektech/heimdall | backoff.go | Next | func (cb *constantBackoff) Next(retry int) time.Duration {
if retry <= 0 {
return 0 * time.Millisecond
}
return (time.Duration(cb.backoffInterval) * time.Millisecond) + (time.Duration(rand.Int63n(cb.maximumJitterInterval)) * time.Millisecond)
} | go | func (cb *constantBackoff) Next(retry int) time.Duration {
if retry <= 0 {
return 0 * time.Millisecond
}
return (time.Duration(cb.backoffInterval) * time.Millisecond) + (time.Duration(rand.Int63n(cb.maximumJitterInterval)) * time.Millisecond)
} | [
"func",
"(",
"cb",
"*",
"constantBackoff",
")",
"Next",
"(",
"retry",
"int",
")",
"time",
".",
"Duration",
"{",
"if",
"retry",
"<=",
"0",
"{",
"return",
"0",
"*",
"time",
".",
"Millisecond",
"\n",
"}",
"\n",
"return",
"(",
"time",
".",
"Duration",
"(",
"cb",
".",
"backoffInterval",
")",
"*",
"time",
".",
"Millisecond",
")",
"+",
"(",
"time",
".",
"Duration",
"(",
"rand",
".",
"Int63n",
"(",
"cb",
".",
"maximumJitterInterval",
")",
")",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"}"
] | // Next returns next time for retrying operation with constant strategy | [
"Next",
"returns",
"next",
"time",
"for",
"retrying",
"operation",
"with",
"constant",
"strategy"
] | ef69e0bb0cbf72e832303efe6362855811e8cc89 | https://github.com/gojektech/heimdall/blob/ef69e0bb0cbf72e832303efe6362855811e8cc89/backoff.go#L33-L38 | train |
gojektech/heimdall | backoff.go | Next | func (eb *exponentialBackoff) Next(retry int) time.Duration {
if retry <= 0 {
return 0 * time.Millisecond
}
return time.Duration(math.Min(eb.initialTimeout+math.Pow(eb.exponentFactor, float64(retry)), eb.maxTimeout)+float64(rand.Int63n(eb.maximumJitterInterval))) * time.Millisecond
} | go | func (eb *exponentialBackoff) Next(retry int) time.Duration {
if retry <= 0 {
return 0 * time.Millisecond
}
return time.Duration(math.Min(eb.initialTimeout+math.Pow(eb.exponentFactor, float64(retry)), eb.maxTimeout)+float64(rand.Int63n(eb.maximumJitterInterval))) * time.Millisecond
} | [
"func",
"(",
"eb",
"*",
"exponentialBackoff",
")",
"Next",
"(",
"retry",
"int",
")",
"time",
".",
"Duration",
"{",
"if",
"retry",
"<=",
"0",
"{",
"return",
"0",
"*",
"time",
".",
"Millisecond",
"\n",
"}",
"\n",
"return",
"time",
".",
"Duration",
"(",
"math",
".",
"Min",
"(",
"eb",
".",
"initialTimeout",
"+",
"math",
".",
"Pow",
"(",
"eb",
".",
"exponentFactor",
",",
"float64",
"(",
"retry",
")",
")",
",",
"eb",
".",
"maxTimeout",
")",
"+",
"float64",
"(",
"rand",
".",
"Int63n",
"(",
"eb",
".",
"maximumJitterInterval",
")",
")",
")",
"*",
"time",
".",
"Millisecond",
"\n",
"}"
] | // Next returns next time for retrying operation with exponential strategy | [
"Next",
"returns",
"next",
"time",
"for",
"retrying",
"operation",
"with",
"exponential",
"strategy"
] | ef69e0bb0cbf72e832303efe6362855811e8cc89 | https://github.com/gojektech/heimdall/blob/ef69e0bb0cbf72e832303efe6362855811e8cc89/backoff.go#L59-L64 | train |
gojektech/heimdall | hystrix/hystrix_client.go | NewClient | func NewClient(opts ...Option) *Client {
client := Client{
timeout: defaultHTTPTimeout,
hystrixTimeout: defaultHystrixTimeout,
maxConcurrentRequests: defaultMaxConcurrentRequests,
errorPercentThreshold: defaultErrorPercentThreshold,
sleepWindow: defaultSleepWindow,
requestVolumeThreshold: defaultRequestVolumeThreshold,
retryCount: defaultHystrixRetryCount,
retrier: heimdall.NewNoRetrier(),
}
for _, opt := range opts {
opt(&client)
}
if client.client == nil {
client.client = &http.Client{
Timeout: client.timeout,
}
}
hystrix.ConfigureCommand(client.hystrixCommandName, hystrix.CommandConfig{
Timeout: durationToInt(client.hystrixTimeout, time.Millisecond),
MaxConcurrentRequests: client.maxConcurrentRequests,
RequestVolumeThreshold: client.requestVolumeThreshold,
SleepWindow: client.sleepWindow,
ErrorPercentThreshold: client.errorPercentThreshold,
})
return &client
} | go | func NewClient(opts ...Option) *Client {
client := Client{
timeout: defaultHTTPTimeout,
hystrixTimeout: defaultHystrixTimeout,
maxConcurrentRequests: defaultMaxConcurrentRequests,
errorPercentThreshold: defaultErrorPercentThreshold,
sleepWindow: defaultSleepWindow,
requestVolumeThreshold: defaultRequestVolumeThreshold,
retryCount: defaultHystrixRetryCount,
retrier: heimdall.NewNoRetrier(),
}
for _, opt := range opts {
opt(&client)
}
if client.client == nil {
client.client = &http.Client{
Timeout: client.timeout,
}
}
hystrix.ConfigureCommand(client.hystrixCommandName, hystrix.CommandConfig{
Timeout: durationToInt(client.hystrixTimeout, time.Millisecond),
MaxConcurrentRequests: client.maxConcurrentRequests,
RequestVolumeThreshold: client.requestVolumeThreshold,
SleepWindow: client.sleepWindow,
ErrorPercentThreshold: client.errorPercentThreshold,
})
return &client
} | [
"func",
"NewClient",
"(",
"opts",
"...",
"Option",
")",
"*",
"Client",
"{",
"client",
":=",
"Client",
"{",
"timeout",
":",
"defaultHTTPTimeout",
",",
"hystrixTimeout",
":",
"defaultHystrixTimeout",
",",
"maxConcurrentRequests",
":",
"defaultMaxConcurrentRequests",
",",
"errorPercentThreshold",
":",
"defaultErrorPercentThreshold",
",",
"sleepWindow",
":",
"defaultSleepWindow",
",",
"requestVolumeThreshold",
":",
"defaultRequestVolumeThreshold",
",",
"retryCount",
":",
"defaultHystrixRetryCount",
",",
"retrier",
":",
"heimdall",
".",
"NewNoRetrier",
"(",
")",
",",
"}",
"\n\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
"(",
"&",
"client",
")",
"\n",
"}",
"\n\n",
"if",
"client",
".",
"client",
"==",
"nil",
"{",
"client",
".",
"client",
"=",
"&",
"http",
".",
"Client",
"{",
"Timeout",
":",
"client",
".",
"timeout",
",",
"}",
"\n",
"}",
"\n\n",
"hystrix",
".",
"ConfigureCommand",
"(",
"client",
".",
"hystrixCommandName",
",",
"hystrix",
".",
"CommandConfig",
"{",
"Timeout",
":",
"durationToInt",
"(",
"client",
".",
"hystrixTimeout",
",",
"time",
".",
"Millisecond",
")",
",",
"MaxConcurrentRequests",
":",
"client",
".",
"maxConcurrentRequests",
",",
"RequestVolumeThreshold",
":",
"client",
".",
"requestVolumeThreshold",
",",
"SleepWindow",
":",
"client",
".",
"sleepWindow",
",",
"ErrorPercentThreshold",
":",
"client",
".",
"errorPercentThreshold",
",",
"}",
")",
"\n\n",
"return",
"&",
"client",
"\n",
"}"
] | // NewClient returns a new instance of hystrix Client | [
"NewClient",
"returns",
"a",
"new",
"instance",
"of",
"hystrix",
"Client"
] | ef69e0bb0cbf72e832303efe6362855811e8cc89 | https://github.com/gojektech/heimdall/blob/ef69e0bb0cbf72e832303efe6362855811e8cc89/hystrix/hystrix_client.go#L50-L81 | train |
gojektech/heimdall | hystrix/hystrix_client.go | Patch | func (hhc *Client) Patch(url string, body io.Reader, headers http.Header) (*http.Response, error) {
var response *http.Response
request, err := http.NewRequest(http.MethodPatch, url, body)
if err != nil {
return response, errors.Wrap(err, "PATCH - request creation failed")
}
request.Header = headers
return hhc.Do(request)
} | go | func (hhc *Client) Patch(url string, body io.Reader, headers http.Header) (*http.Response, error) {
var response *http.Response
request, err := http.NewRequest(http.MethodPatch, url, body)
if err != nil {
return response, errors.Wrap(err, "PATCH - request creation failed")
}
request.Header = headers
return hhc.Do(request)
} | [
"func",
"(",
"hhc",
"*",
"Client",
")",
"Patch",
"(",
"url",
"string",
",",
"body",
"io",
".",
"Reader",
",",
"headers",
"http",
".",
"Header",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"var",
"response",
"*",
"http",
".",
"Response",
"\n",
"request",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"http",
".",
"MethodPatch",
",",
"url",
",",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"response",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"request",
".",
"Header",
"=",
"headers",
"\n\n",
"return",
"hhc",
".",
"Do",
"(",
"request",
")",
"\n",
"}"
] | // Patch makes a HTTP PATCH request to provided URL and requestBody | [
"Patch",
"makes",
"a",
"HTTP",
"PATCH",
"request",
"to",
"provided",
"URL",
"and",
"requestBody"
] | ef69e0bb0cbf72e832303efe6362855811e8cc89 | https://github.com/gojektech/heimdall/blob/ef69e0bb0cbf72e832303efe6362855811e8cc89/hystrix/hystrix_client.go#L135-L145 | train |
gojektech/heimdall | hystrix/hystrix_client.go | Delete | func (hhc *Client) Delete(url string, headers http.Header) (*http.Response, error) {
var response *http.Response
request, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
return response, errors.Wrap(err, "DELETE - request creation failed")
}
request.Header = headers
return hhc.Do(request)
} | go | func (hhc *Client) Delete(url string, headers http.Header) (*http.Response, error) {
var response *http.Response
request, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
return response, errors.Wrap(err, "DELETE - request creation failed")
}
request.Header = headers
return hhc.Do(request)
} | [
"func",
"(",
"hhc",
"*",
"Client",
")",
"Delete",
"(",
"url",
"string",
",",
"headers",
"http",
".",
"Header",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"var",
"response",
"*",
"http",
".",
"Response",
"\n",
"request",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"http",
".",
"MethodDelete",
",",
"url",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"response",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"request",
".",
"Header",
"=",
"headers",
"\n\n",
"return",
"hhc",
".",
"Do",
"(",
"request",
")",
"\n",
"}"
] | // Delete makes a HTTP DELETE request with provided URL | [
"Delete",
"makes",
"a",
"HTTP",
"DELETE",
"request",
"with",
"provided",
"URL"
] | ef69e0bb0cbf72e832303efe6362855811e8cc89 | https://github.com/gojektech/heimdall/blob/ef69e0bb0cbf72e832303efe6362855811e8cc89/hystrix/hystrix_client.go#L148-L158 | train |
gopasspw/gopass | pkg/clipboard/clipboard.go | CopyTo | func CopyTo(ctx context.Context, name string, content []byte) error {
if clipboard.Unsupported {
out.Yellow(ctx, "%s", ErrNotSupported)
return nil
}
if err := clipboard.WriteAll(string(content)); err != nil {
return errors.Wrapf(err, "failed to write to clipboard")
}
if err := clear(ctx, content, ctxutil.GetClipTimeout(ctx)); err != nil {
return errors.Wrapf(err, "failed to clear clipboard")
}
out.Print(ctx, "✔ Copied %s to clipboard. Will clear in %d seconds.", color.YellowString(name), ctxutil.GetClipTimeout(ctx))
return nil
} | go | func CopyTo(ctx context.Context, name string, content []byte) error {
if clipboard.Unsupported {
out.Yellow(ctx, "%s", ErrNotSupported)
return nil
}
if err := clipboard.WriteAll(string(content)); err != nil {
return errors.Wrapf(err, "failed to write to clipboard")
}
if err := clear(ctx, content, ctxutil.GetClipTimeout(ctx)); err != nil {
return errors.Wrapf(err, "failed to clear clipboard")
}
out.Print(ctx, "✔ Copied %s to clipboard. Will clear in %d seconds.", color.YellowString(name), ctxutil.GetClipTimeout(ctx))
return nil
} | [
"func",
"CopyTo",
"(",
"ctx",
"context",
".",
"Context",
",",
"name",
"string",
",",
"content",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"clipboard",
".",
"Unsupported",
"{",
"out",
".",
"Yellow",
"(",
"ctx",
",",
"\"",
"\"",
",",
"ErrNotSupported",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"clipboard",
".",
"WriteAll",
"(",
"string",
"(",
"content",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"clear",
"(",
"ctx",
",",
"content",
",",
"ctxutil",
".",
"GetClipTimeout",
"(",
"ctx",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"out",
".",
"Print",
"(",
"ctx",
",",
"\"",
" ",
"c",
"lor.Y",
"e",
"llowString(n",
"a",
"me),",
" ",
"c",
"xutil.G",
"e",
"tClipTimeout(c",
"t",
"x))",
"",
"",
"\n",
"return",
"nil",
"\n",
"}"
] | // CopyTo copies the given data to the clipboard and enqueues automatic
// clearing of the clipboard | [
"CopyTo",
"copies",
"the",
"given",
"data",
"to",
"the",
"clipboard",
"and",
"enqueues",
"automatic",
"clearing",
"of",
"the",
"clipboard"
] | fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4 | https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/clipboard/clipboard.go#L23-L39 | train |
gopasspw/gopass | pkg/store/sub/crypto.go | GetCryptoBackend | func GetCryptoBackend(ctx context.Context, cb backend.CryptoBackend, cfgdir string, agent *client.Client) (backend.Crypto, error) {
ctx = client.WithClient(ctx, agent)
ctx = ctxutil.WithConfigDir(ctx, cfgdir)
crypto, err := backend.NewCrypto(ctx, cb)
if err != nil {
return nil, errors.Wrapf(err, "unknown crypto backend")
}
return crypto, nil
} | go | func GetCryptoBackend(ctx context.Context, cb backend.CryptoBackend, cfgdir string, agent *client.Client) (backend.Crypto, error) {
ctx = client.WithClient(ctx, agent)
ctx = ctxutil.WithConfigDir(ctx, cfgdir)
crypto, err := backend.NewCrypto(ctx, cb)
if err != nil {
return nil, errors.Wrapf(err, "unknown crypto backend")
}
return crypto, nil
} | [
"func",
"GetCryptoBackend",
"(",
"ctx",
"context",
".",
"Context",
",",
"cb",
"backend",
".",
"CryptoBackend",
",",
"cfgdir",
"string",
",",
"agent",
"*",
"client",
".",
"Client",
")",
"(",
"backend",
".",
"Crypto",
",",
"error",
")",
"{",
"ctx",
"=",
"client",
".",
"WithClient",
"(",
"ctx",
",",
"agent",
")",
"\n",
"ctx",
"=",
"ctxutil",
".",
"WithConfigDir",
"(",
"ctx",
",",
"cfgdir",
")",
"\n",
"crypto",
",",
"err",
":=",
"backend",
".",
"NewCrypto",
"(",
"ctx",
",",
"cb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"crypto",
",",
"nil",
"\n",
"}"
] | // GetCryptoBackend initialized the correct crypto backend | [
"GetCryptoBackend",
"initialized",
"the",
"correct",
"crypto",
"backend"
] | fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4 | https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/store/sub/crypto.go#L22-L30 | train |
gopasspw/gopass | pkg/action/generate.go | Generate | func (s *Action) Generate(ctx context.Context, c *cli.Context) error {
force := c.Bool("force")
edit := c.Bool("edit")
args, kvps := parseArgs(c)
name := args.Get(0)
key, length := keyAndLength(args)
// ask for name of the secret if it wasn't provided already
if name == "" {
var err error
name, err = termio.AskForString(ctx, "Which name do you want to use?", "")
if err != nil || name == "" {
return ExitError(ctx, ExitNoName, err, "please provide a password name")
}
}
ctx = s.Store.WithConfig(ctx, name)
// ask for confirmation before overwriting existing entry
if !force { // don't check if it's force anyway
if s.Store.Exists(ctx, name) && key == "" && !termio.AskForConfirmation(ctx, fmt.Sprintf("An entry already exists for %s. Overwrite the current password?", name)) {
return ExitError(ctx, ExitAborted, nil, "user aborted. not overwriting your current password")
}
}
// generate password
password, err := s.generatePassword(ctx, c, length)
if err != nil {
return err
}
// write generated password to store
ctx, err = s.generateSetPassword(ctx, name, key, password, kvps)
if err != nil {
return err
}
// if requested launch editor to add more data to the generated secret
if (edit || ctxutil.IsAskForMore(ctx)) && termio.AskForConfirmation(ctx, fmt.Sprintf("Do you want to add more data for %s?", name)) {
if err := s.Edit(ctx, c); err != nil {
return ExitError(ctx, ExitUnknown, err, "failed to edit '%s': %s", name, err)
}
}
// display or copy to clipboard
return s.generateCopyOrPrint(ctx, c, name, key, password)
} | go | func (s *Action) Generate(ctx context.Context, c *cli.Context) error {
force := c.Bool("force")
edit := c.Bool("edit")
args, kvps := parseArgs(c)
name := args.Get(0)
key, length := keyAndLength(args)
// ask for name of the secret if it wasn't provided already
if name == "" {
var err error
name, err = termio.AskForString(ctx, "Which name do you want to use?", "")
if err != nil || name == "" {
return ExitError(ctx, ExitNoName, err, "please provide a password name")
}
}
ctx = s.Store.WithConfig(ctx, name)
// ask for confirmation before overwriting existing entry
if !force { // don't check if it's force anyway
if s.Store.Exists(ctx, name) && key == "" && !termio.AskForConfirmation(ctx, fmt.Sprintf("An entry already exists for %s. Overwrite the current password?", name)) {
return ExitError(ctx, ExitAborted, nil, "user aborted. not overwriting your current password")
}
}
// generate password
password, err := s.generatePassword(ctx, c, length)
if err != nil {
return err
}
// write generated password to store
ctx, err = s.generateSetPassword(ctx, name, key, password, kvps)
if err != nil {
return err
}
// if requested launch editor to add more data to the generated secret
if (edit || ctxutil.IsAskForMore(ctx)) && termio.AskForConfirmation(ctx, fmt.Sprintf("Do you want to add more data for %s?", name)) {
if err := s.Edit(ctx, c); err != nil {
return ExitError(ctx, ExitUnknown, err, "failed to edit '%s': %s", name, err)
}
}
// display or copy to clipboard
return s.generateCopyOrPrint(ctx, c, name, key, password)
} | [
"func",
"(",
"s",
"*",
"Action",
")",
"Generate",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"*",
"cli",
".",
"Context",
")",
"error",
"{",
"force",
":=",
"c",
".",
"Bool",
"(",
"\"",
"\"",
")",
"\n",
"edit",
":=",
"c",
".",
"Bool",
"(",
"\"",
"\"",
")",
"\n\n",
"args",
",",
"kvps",
":=",
"parseArgs",
"(",
"c",
")",
"\n",
"name",
":=",
"args",
".",
"Get",
"(",
"0",
")",
"\n",
"key",
",",
"length",
":=",
"keyAndLength",
"(",
"args",
")",
"\n\n",
"// ask for name of the secret if it wasn't provided already",
"if",
"name",
"==",
"\"",
"\"",
"{",
"var",
"err",
"error",
"\n",
"name",
",",
"err",
"=",
"termio",
".",
"AskForString",
"(",
"ctx",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"name",
"==",
"\"",
"\"",
"{",
"return",
"ExitError",
"(",
"ctx",
",",
"ExitNoName",
",",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"ctx",
"=",
"s",
".",
"Store",
".",
"WithConfig",
"(",
"ctx",
",",
"name",
")",
"\n\n",
"// ask for confirmation before overwriting existing entry",
"if",
"!",
"force",
"{",
"// don't check if it's force anyway",
"if",
"s",
".",
"Store",
".",
"Exists",
"(",
"ctx",
",",
"name",
")",
"&&",
"key",
"==",
"\"",
"\"",
"&&",
"!",
"termio",
".",
"AskForConfirmation",
"(",
"ctx",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
")",
"{",
"return",
"ExitError",
"(",
"ctx",
",",
"ExitAborted",
",",
"nil",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// generate password",
"password",
",",
"err",
":=",
"s",
".",
"generatePassword",
"(",
"ctx",
",",
"c",
",",
"length",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// write generated password to store",
"ctx",
",",
"err",
"=",
"s",
".",
"generateSetPassword",
"(",
"ctx",
",",
"name",
",",
"key",
",",
"password",
",",
"kvps",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// if requested launch editor to add more data to the generated secret",
"if",
"(",
"edit",
"||",
"ctxutil",
".",
"IsAskForMore",
"(",
"ctx",
")",
")",
"&&",
"termio",
".",
"AskForConfirmation",
"(",
"ctx",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
")",
"{",
"if",
"err",
":=",
"s",
".",
"Edit",
"(",
"ctx",
",",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"ExitError",
"(",
"ctx",
",",
"ExitUnknown",
",",
"err",
",",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// display or copy to clipboard",
"return",
"s",
".",
"generateCopyOrPrint",
"(",
"ctx",
",",
"c",
",",
"name",
",",
"key",
",",
"password",
")",
"\n",
"}"
] | // Generate and save a password | [
"Generate",
"and",
"save",
"a",
"password"
] | fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4 | https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/action/generate.go#L36-L83 | train |
gopasspw/gopass | pkg/action/generate.go | generateCopyOrPrint | func (s *Action) generateCopyOrPrint(ctx context.Context, c *cli.Context, name, key, password string) error {
if ctxutil.IsAutoPrint(ctx) || c.Bool("print") {
if key != "" {
key = " " + key
}
out.Print(
ctx,
"The generated password for %s%s is:\n%s", name, key,
color.YellowString(password),
)
}
if ctxutil.IsAutoClip(ctx) || c.Bool("clip") {
if err := clipboard.CopyTo(ctx, name, []byte(password)); err != nil {
return ExitError(ctx, ExitIO, err, "failed to copy to clipboard: %s", err)
}
}
if c.Bool("print") || c.Bool("clip") {
return nil
}
entry := name
if key != "" {
entry += ":" + key
}
out.Print(ctx, "Password for %s generated", entry)
return nil
} | go | func (s *Action) generateCopyOrPrint(ctx context.Context, c *cli.Context, name, key, password string) error {
if ctxutil.IsAutoPrint(ctx) || c.Bool("print") {
if key != "" {
key = " " + key
}
out.Print(
ctx,
"The generated password for %s%s is:\n%s", name, key,
color.YellowString(password),
)
}
if ctxutil.IsAutoClip(ctx) || c.Bool("clip") {
if err := clipboard.CopyTo(ctx, name, []byte(password)); err != nil {
return ExitError(ctx, ExitIO, err, "failed to copy to clipboard: %s", err)
}
}
if c.Bool("print") || c.Bool("clip") {
return nil
}
entry := name
if key != "" {
entry += ":" + key
}
out.Print(ctx, "Password for %s generated", entry)
return nil
} | [
"func",
"(",
"s",
"*",
"Action",
")",
"generateCopyOrPrint",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"*",
"cli",
".",
"Context",
",",
"name",
",",
"key",
",",
"password",
"string",
")",
"error",
"{",
"if",
"ctxutil",
".",
"IsAutoPrint",
"(",
"ctx",
")",
"||",
"c",
".",
"Bool",
"(",
"\"",
"\"",
")",
"{",
"if",
"key",
"!=",
"\"",
"\"",
"{",
"key",
"=",
"\"",
"\"",
"+",
"key",
"\n",
"}",
"\n",
"out",
".",
"Print",
"(",
"ctx",
",",
"\"",
"\\n",
"\"",
",",
"name",
",",
"key",
",",
"color",
".",
"YellowString",
"(",
"password",
")",
",",
")",
"\n",
"}",
"\n\n",
"if",
"ctxutil",
".",
"IsAutoClip",
"(",
"ctx",
")",
"||",
"c",
".",
"Bool",
"(",
"\"",
"\"",
")",
"{",
"if",
"err",
":=",
"clipboard",
".",
"CopyTo",
"(",
"ctx",
",",
"name",
",",
"[",
"]",
"byte",
"(",
"password",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"ExitError",
"(",
"ctx",
",",
"ExitIO",
",",
"err",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"Bool",
"(",
"\"",
"\"",
")",
"||",
"c",
".",
"Bool",
"(",
"\"",
"\"",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"entry",
":=",
"name",
"\n",
"if",
"key",
"!=",
"\"",
"\"",
"{",
"entry",
"+=",
"\"",
"\"",
"+",
"key",
"\n",
"}",
"\n",
"out",
".",
"Print",
"(",
"ctx",
",",
"\"",
"\"",
",",
"entry",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // generateCopyOrPrint will print the password to the screen or copy to the
// clipboard | [
"generateCopyOrPrint",
"will",
"print",
"the",
"password",
"to",
"the",
"screen",
"or",
"copy",
"to",
"the",
"clipboard"
] | fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4 | https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/action/generate.go#L103-L131 | train |
gopasspw/gopass | pkg/action/generate.go | generatePassword | func (s *Action) generatePassword(ctx context.Context, c *cli.Context, length string) (string, error) {
if c.Bool("xkcd") || c.IsSet("xkcdsep") {
return s.generatePasswordXKCD(ctx, c, length)
}
symbols := ctxutil.IsUseSymbols(ctx)
if c.IsSet("symbols") {
symbols = c.Bool("symbols")
}
var pwlen int
if length == "" {
candidateLength := defaultLength
question := "How long should the password be?"
iv, err := termio.AskForInt(ctx, question, candidateLength)
if err != nil {
return "", ExitError(ctx, ExitUsage, err, "password length must be a number")
}
pwlen = iv
} else {
iv, err := strconv.Atoi(length)
if err != nil {
return "", ExitError(ctx, ExitUsage, err, "password length must be a number")
}
pwlen = iv
}
if pwlen < 1 {
return "", ExitError(ctx, ExitUsage, nil, "password length must not be zero")
}
corp, err := termio.AskForBool(ctx, "Do you have strict rules to include different character classes?", false)
if err != nil {
return "", err
}
if corp {
return pwgen.GeneratePasswordWithAllClasses(pwlen)
}
return pwgen.GeneratePassword(pwlen, symbols), nil
} | go | func (s *Action) generatePassword(ctx context.Context, c *cli.Context, length string) (string, error) {
if c.Bool("xkcd") || c.IsSet("xkcdsep") {
return s.generatePasswordXKCD(ctx, c, length)
}
symbols := ctxutil.IsUseSymbols(ctx)
if c.IsSet("symbols") {
symbols = c.Bool("symbols")
}
var pwlen int
if length == "" {
candidateLength := defaultLength
question := "How long should the password be?"
iv, err := termio.AskForInt(ctx, question, candidateLength)
if err != nil {
return "", ExitError(ctx, ExitUsage, err, "password length must be a number")
}
pwlen = iv
} else {
iv, err := strconv.Atoi(length)
if err != nil {
return "", ExitError(ctx, ExitUsage, err, "password length must be a number")
}
pwlen = iv
}
if pwlen < 1 {
return "", ExitError(ctx, ExitUsage, nil, "password length must not be zero")
}
corp, err := termio.AskForBool(ctx, "Do you have strict rules to include different character classes?", false)
if err != nil {
return "", err
}
if corp {
return pwgen.GeneratePasswordWithAllClasses(pwlen)
}
return pwgen.GeneratePassword(pwlen, symbols), nil
} | [
"func",
"(",
"s",
"*",
"Action",
")",
"generatePassword",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"*",
"cli",
".",
"Context",
",",
"length",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"c",
".",
"Bool",
"(",
"\"",
"\"",
")",
"||",
"c",
".",
"IsSet",
"(",
"\"",
"\"",
")",
"{",
"return",
"s",
".",
"generatePasswordXKCD",
"(",
"ctx",
",",
"c",
",",
"length",
")",
"\n",
"}",
"\n\n",
"symbols",
":=",
"ctxutil",
".",
"IsUseSymbols",
"(",
"ctx",
")",
"\n",
"if",
"c",
".",
"IsSet",
"(",
"\"",
"\"",
")",
"{",
"symbols",
"=",
"c",
".",
"Bool",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"pwlen",
"int",
"\n",
"if",
"length",
"==",
"\"",
"\"",
"{",
"candidateLength",
":=",
"defaultLength",
"\n",
"question",
":=",
"\"",
"\"",
"\n",
"iv",
",",
"err",
":=",
"termio",
".",
"AskForInt",
"(",
"ctx",
",",
"question",
",",
"candidateLength",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"ExitError",
"(",
"ctx",
",",
"ExitUsage",
",",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"pwlen",
"=",
"iv",
"\n",
"}",
"else",
"{",
"iv",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"length",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"ExitError",
"(",
"ctx",
",",
"ExitUsage",
",",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"pwlen",
"=",
"iv",
"\n",
"}",
"\n\n",
"if",
"pwlen",
"<",
"1",
"{",
"return",
"\"",
"\"",
",",
"ExitError",
"(",
"ctx",
",",
"ExitUsage",
",",
"nil",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"corp",
",",
"err",
":=",
"termio",
".",
"AskForBool",
"(",
"ctx",
",",
"\"",
"\"",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"corp",
"{",
"return",
"pwgen",
".",
"GeneratePasswordWithAllClasses",
"(",
"pwlen",
")",
"\n",
"}",
"\n\n",
"return",
"pwgen",
".",
"GeneratePassword",
"(",
"pwlen",
",",
"symbols",
")",
",",
"nil",
"\n",
"}"
] | // generatePassword will run through the password generation steps | [
"generatePassword",
"will",
"run",
"through",
"the",
"password",
"generation",
"steps"
] | fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4 | https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/action/generate.go#L134-L174 | train |
gopasspw/gopass | pkg/action/generate.go | generatePasswordXKCD | func (s *Action) generatePasswordXKCD(ctx context.Context, c *cli.Context, length string) (string, error) {
xkcdSeparator := " "
if c.IsSet("xkcdsep") {
xkcdSeparator = c.String("xkcdsep")
}
var pwlen int
if length == "" {
candidateLength := defaultXKCDLength
question := "How many words should be combined to a password?"
iv, err := termio.AskForInt(ctx, question, candidateLength)
if err != nil {
return "", ExitError(ctx, ExitUsage, err, "password length must be a number")
}
pwlen = iv
} else {
iv, err := strconv.Atoi(length)
if err != nil {
return "", ExitError(ctx, ExitUsage, err, "password length must be a number: %s", err)
}
pwlen = iv
}
if pwlen < 1 {
return "", ExitError(ctx, ExitUsage, nil, "password length must not be zero")
}
return xkcdgen.RandomLengthDelim(pwlen, xkcdSeparator, c.String("xkcdlang"))
} | go | func (s *Action) generatePasswordXKCD(ctx context.Context, c *cli.Context, length string) (string, error) {
xkcdSeparator := " "
if c.IsSet("xkcdsep") {
xkcdSeparator = c.String("xkcdsep")
}
var pwlen int
if length == "" {
candidateLength := defaultXKCDLength
question := "How many words should be combined to a password?"
iv, err := termio.AskForInt(ctx, question, candidateLength)
if err != nil {
return "", ExitError(ctx, ExitUsage, err, "password length must be a number")
}
pwlen = iv
} else {
iv, err := strconv.Atoi(length)
if err != nil {
return "", ExitError(ctx, ExitUsage, err, "password length must be a number: %s", err)
}
pwlen = iv
}
if pwlen < 1 {
return "", ExitError(ctx, ExitUsage, nil, "password length must not be zero")
}
return xkcdgen.RandomLengthDelim(pwlen, xkcdSeparator, c.String("xkcdlang"))
} | [
"func",
"(",
"s",
"*",
"Action",
")",
"generatePasswordXKCD",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"*",
"cli",
".",
"Context",
",",
"length",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"xkcdSeparator",
":=",
"\"",
"\"",
"\n",
"if",
"c",
".",
"IsSet",
"(",
"\"",
"\"",
")",
"{",
"xkcdSeparator",
"=",
"c",
".",
"String",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"pwlen",
"int",
"\n",
"if",
"length",
"==",
"\"",
"\"",
"{",
"candidateLength",
":=",
"defaultXKCDLength",
"\n",
"question",
":=",
"\"",
"\"",
"\n",
"iv",
",",
"err",
":=",
"termio",
".",
"AskForInt",
"(",
"ctx",
",",
"question",
",",
"candidateLength",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"ExitError",
"(",
"ctx",
",",
"ExitUsage",
",",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"pwlen",
"=",
"iv",
"\n",
"}",
"else",
"{",
"iv",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"length",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"ExitError",
"(",
"ctx",
",",
"ExitUsage",
",",
"err",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"pwlen",
"=",
"iv",
"\n",
"}",
"\n\n",
"if",
"pwlen",
"<",
"1",
"{",
"return",
"\"",
"\"",
",",
"ExitError",
"(",
"ctx",
",",
"ExitUsage",
",",
"nil",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"xkcdgen",
".",
"RandomLengthDelim",
"(",
"pwlen",
",",
"xkcdSeparator",
",",
"c",
".",
"String",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // generatePasswordXKCD walks through the steps necessary to create an XKCD-style
// password | [
"generatePasswordXKCD",
"walks",
"through",
"the",
"steps",
"necessary",
"to",
"create",
"an",
"XKCD",
"-",
"style",
"password"
] | fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4 | https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/action/generate.go#L178-L206 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.