repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
chrislusf/gleam
sql/terror/terror.go
ErrorEqual
func ErrorEqual(err1, err2 error) bool { e1 := errors.Cause(err1) e2 := errors.Cause(err2) if e1 == e2 { return true } if e1 == nil || e2 == nil { return e1 == e2 } te1, ok1 := e1.(*Error) te2, ok2 := e2.(*Error) if ok1 && ok2 { return te1.class == te2.class && te1.code == te2.code } return e1.Error() == e2.Error() }
go
func ErrorEqual(err1, err2 error) bool { e1 := errors.Cause(err1) e2 := errors.Cause(err2) if e1 == e2 { return true } if e1 == nil || e2 == nil { return e1 == e2 } te1, ok1 := e1.(*Error) te2, ok2 := e2.(*Error) if ok1 && ok2 { return te1.class == te2.class && te1.code == te2.code } return e1.Error() == e2.Error() }
[ "func", "ErrorEqual", "(", "err1", ",", "err2", "error", ")", "bool", "{", "e1", ":=", "errors", ".", "Cause", "(", "err1", ")", "\n", "e2", ":=", "errors", ".", "Cause", "(", "err2", ")", "\n", "if", "e1", "==", "e2", "{", "return", "true", "\n", "}", "\n", "if", "e1", "==", "nil", "||", "e2", "==", "nil", "{", "return", "e1", "==", "e2", "\n", "}", "\n", "te1", ",", "ok1", ":=", "e1", ".", "(", "*", "Error", ")", "\n", "te2", ",", "ok2", ":=", "e2", ".", "(", "*", "Error", ")", "\n", "if", "ok1", "&&", "ok2", "{", "return", "te1", ".", "class", "==", "te2", ".", "class", "&&", "te1", ".", "code", "==", "te2", ".", "code", "\n", "}", "\n", "return", "e1", ".", "Error", "(", ")", "==", "e2", ".", "Error", "(", ")", "\n", "}" ]
// ErrorEqual returns a boolean indicating whether err1 is equal to err2.
[ "ErrorEqual", "returns", "a", "boolean", "indicating", "whether", "err1", "is", "equal", "to", "err2", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/terror/terror.go#L296-L315
train
chrislusf/gleam
flow/context.go
AddOneToOneStep
func (f *Flow) AddOneToOneStep(input *Dataset, output *Dataset) (step *Step) { step = f.NewStep() step.NetworkType = OneShardToOneShard fromStepToDataset(step, output) fromDatasetToStep(input, step) if input == nil { task := step.NewTask() if output != nil && output.Shards != nil { fromTaskToDatasetShard(task, output.GetShards()[0]) } return } // setup the network for i, shard := range input.GetShards() { task := step.NewTask() if output != nil && output.Shards != nil { fromTaskToDatasetShard(task, output.GetShards()[i]) } fromDatasetShardToTask(shard, task) } return }
go
func (f *Flow) AddOneToOneStep(input *Dataset, output *Dataset) (step *Step) { step = f.NewStep() step.NetworkType = OneShardToOneShard fromStepToDataset(step, output) fromDatasetToStep(input, step) if input == nil { task := step.NewTask() if output != nil && output.Shards != nil { fromTaskToDatasetShard(task, output.GetShards()[0]) } return } // setup the network for i, shard := range input.GetShards() { task := step.NewTask() if output != nil && output.Shards != nil { fromTaskToDatasetShard(task, output.GetShards()[i]) } fromDatasetShardToTask(shard, task) } return }
[ "func", "(", "f", "*", "Flow", ")", "AddOneToOneStep", "(", "input", "*", "Dataset", ",", "output", "*", "Dataset", ")", "(", "step", "*", "Step", ")", "{", "step", "=", "f", ".", "NewStep", "(", ")", "\n", "step", ".", "NetworkType", "=", "OneShardToOneShard", "\n", "fromStepToDataset", "(", "step", ",", "output", ")", "\n", "fromDatasetToStep", "(", "input", ",", "step", ")", "\n", "if", "input", "==", "nil", "{", "task", ":=", "step", ".", "NewTask", "(", ")", "\n", "if", "output", "!=", "nil", "&&", "output", ".", "Shards", "!=", "nil", "{", "fromTaskToDatasetShard", "(", "task", ",", "output", ".", "GetShards", "(", ")", "[", "0", "]", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "for", "i", ",", "shard", ":=", "range", "input", ".", "GetShards", "(", ")", "{", "task", ":=", "step", ".", "NewTask", "(", ")", "\n", "if", "output", "!=", "nil", "&&", "output", ".", "Shards", "!=", "nil", "{", "fromTaskToDatasetShard", "(", "task", ",", "output", ".", "GetShards", "(", ")", "[", "i", "]", ")", "\n", "}", "\n", "fromDatasetShardToTask", "(", "shard", ",", "task", ")", "\n", "}", "\n", "return", "\n", "}" ]
// the tasks should run on the source dataset shard
[ "the", "tasks", "should", "run", "on", "the", "source", "dataset", "shard" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/context.go#L52-L75
train
chrislusf/gleam
flow/context.go
AddAllToOneStep
func (f *Flow) AddAllToOneStep(input *Dataset, output *Dataset) (step *Step) { step = f.NewStep() step.NetworkType = AllShardToOneShard fromStepToDataset(step, output) fromDatasetToStep(input, step) // setup the network task := step.NewTask() if output != nil { fromTaskToDatasetShard(task, output.GetShards()[0]) } for _, shard := range input.GetShards() { fromDatasetShardToTask(shard, task) } return }
go
func (f *Flow) AddAllToOneStep(input *Dataset, output *Dataset) (step *Step) { step = f.NewStep() step.NetworkType = AllShardToOneShard fromStepToDataset(step, output) fromDatasetToStep(input, step) // setup the network task := step.NewTask() if output != nil { fromTaskToDatasetShard(task, output.GetShards()[0]) } for _, shard := range input.GetShards() { fromDatasetShardToTask(shard, task) } return }
[ "func", "(", "f", "*", "Flow", ")", "AddAllToOneStep", "(", "input", "*", "Dataset", ",", "output", "*", "Dataset", ")", "(", "step", "*", "Step", ")", "{", "step", "=", "f", ".", "NewStep", "(", ")", "\n", "step", ".", "NetworkType", "=", "AllShardToOneShard", "\n", "fromStepToDataset", "(", "step", ",", "output", ")", "\n", "fromDatasetToStep", "(", "input", ",", "step", ")", "\n", "task", ":=", "step", ".", "NewTask", "(", ")", "\n", "if", "output", "!=", "nil", "{", "fromTaskToDatasetShard", "(", "task", ",", "output", ".", "GetShards", "(", ")", "[", "0", "]", ")", "\n", "}", "\n", "for", "_", ",", "shard", ":=", "range", "input", ".", "GetShards", "(", ")", "{", "fromDatasetShardToTask", "(", "shard", ",", "task", ")", "\n", "}", "\n", "return", "\n", "}" ]
// the task should run on the destination dataset shard
[ "the", "task", "should", "run", "on", "the", "destination", "dataset", "shard" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/context.go#L78-L93
train
chrislusf/gleam
flow/context.go
MergeDatasets1ShardTo1Step
func (f *Flow) MergeDatasets1ShardTo1Step(inputs []*Dataset, output *Dataset) (step *Step) { step = f.NewStep() step.NetworkType = MergeTwoShardToOneShard fromStepToDataset(step, output) for _, input := range inputs { fromDatasetToStep(input, step) } // setup the network if output != nil { for shardId, outShard := range output.Shards { task := step.NewTask() for _, input := range inputs { fromDatasetShardToTask(input.GetShards()[shardId], task) } fromTaskToDatasetShard(task, outShard) } } return }
go
func (f *Flow) MergeDatasets1ShardTo1Step(inputs []*Dataset, output *Dataset) (step *Step) { step = f.NewStep() step.NetworkType = MergeTwoShardToOneShard fromStepToDataset(step, output) for _, input := range inputs { fromDatasetToStep(input, step) } // setup the network if output != nil { for shardId, outShard := range output.Shards { task := step.NewTask() for _, input := range inputs { fromDatasetShardToTask(input.GetShards()[shardId], task) } fromTaskToDatasetShard(task, outShard) } } return }
[ "func", "(", "f", "*", "Flow", ")", "MergeDatasets1ShardTo1Step", "(", "inputs", "[", "]", "*", "Dataset", ",", "output", "*", "Dataset", ")", "(", "step", "*", "Step", ")", "{", "step", "=", "f", ".", "NewStep", "(", ")", "\n", "step", ".", "NetworkType", "=", "MergeTwoShardToOneShard", "\n", "fromStepToDataset", "(", "step", ",", "output", ")", "\n", "for", "_", ",", "input", ":=", "range", "inputs", "{", "fromDatasetToStep", "(", "input", ",", "step", ")", "\n", "}", "\n", "if", "output", "!=", "nil", "{", "for", "shardId", ",", "outShard", ":=", "range", "output", ".", "Shards", "{", "task", ":=", "step", ".", "NewTask", "(", ")", "\n", "for", "_", ",", "input", ":=", "range", "inputs", "{", "fromDatasetShardToTask", "(", "input", ".", "GetShards", "(", ")", "[", "shardId", "]", ",", "task", ")", "\n", "}", "\n", "fromTaskToDatasetShard", "(", "task", ",", "outShard", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// All dataset should have the same number of shards.
[ "All", "dataset", "should", "have", "the", "same", "number", "of", "shards", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/context.go#L167-L186
train
chrislusf/gleam
sql/plan/plans.go
IsPoint
func (ir *IndexRange) IsPoint(sc *variable.StatementContext) bool { if len(ir.LowVal) != len(ir.HighVal) { return false } for i := range ir.LowVal { a := ir.LowVal[i] b := ir.HighVal[i] if a.Kind() == types.KindMinNotNull || b.Kind() == types.KindMaxValue { return false } cmp, err := a.CompareDatum(sc, b) if err != nil { return false } if cmp != 0 { return false } } return !ir.LowExclude && !ir.HighExclude }
go
func (ir *IndexRange) IsPoint(sc *variable.StatementContext) bool { if len(ir.LowVal) != len(ir.HighVal) { return false } for i := range ir.LowVal { a := ir.LowVal[i] b := ir.HighVal[i] if a.Kind() == types.KindMinNotNull || b.Kind() == types.KindMaxValue { return false } cmp, err := a.CompareDatum(sc, b) if err != nil { return false } if cmp != 0 { return false } } return !ir.LowExclude && !ir.HighExclude }
[ "func", "(", "ir", "*", "IndexRange", ")", "IsPoint", "(", "sc", "*", "variable", ".", "StatementContext", ")", "bool", "{", "if", "len", "(", "ir", ".", "LowVal", ")", "!=", "len", "(", "ir", ".", "HighVal", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ":=", "range", "ir", ".", "LowVal", "{", "a", ":=", "ir", ".", "LowVal", "[", "i", "]", "\n", "b", ":=", "ir", ".", "HighVal", "[", "i", "]", "\n", "if", "a", ".", "Kind", "(", ")", "==", "types", ".", "KindMinNotNull", "||", "b", ".", "Kind", "(", ")", "==", "types", ".", "KindMaxValue", "{", "return", "false", "\n", "}", "\n", "cmp", ",", "err", ":=", "a", ".", "CompareDatum", "(", "sc", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "if", "cmp", "!=", "0", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "!", "ir", ".", "LowExclude", "&&", "!", "ir", ".", "HighExclude", "\n", "}" ]
// IsPoint returns if the index range is a point.
[ "IsPoint", "returns", "if", "the", "index", "range", "is", "a", "point", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/plan/plans.go#L54-L73
train
chrislusf/gleam
flow/dataset_source.go
Read
func (fc *Flow) Read(s Sourcer) (ret *Dataset) { return s.Generate(fc) }
go
func (fc *Flow) Read(s Sourcer) (ret *Dataset) { return s.Generate(fc) }
[ "func", "(", "fc", "*", "Flow", ")", "Read", "(", "s", "Sourcer", ")", "(", "ret", "*", "Dataset", ")", "{", "return", "s", ".", "Generate", "(", "fc", ")", "\n", "}" ]
// Read accepts a function to read data into the flow, creating a new dataset. // This allows custom complicated pre-built logic for new data sources.
[ "Read", "accepts", "a", "function", "to", "read", "data", "into", "the", "flow", "creating", "a", "new", "dataset", ".", "This", "allows", "custom", "complicated", "pre", "-", "built", "logic", "for", "new", "data", "sources", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_source.go#L18-L20
train
chrislusf/gleam
flow/dataset_source.go
Listen
func (fc *Flow) Listen(network, address string) (ret *Dataset) { fn := func(writer io.Writer, stats *pb.InstructionStat) error { listener, err := net.Listen(network, address) if err != nil { return fmt.Errorf("Fail to listen on %s %s: %v", network, address, err) } conn, err := listener.Accept() if err != nil { return fmt.Errorf("Fail to accept on %s %s: %v", network, address, err) } defer conn.Close() return util.TakeTsv(conn, -1, func(message []string) error { stats.InputCounter++ var row []interface{} for _, m := range message { row = append(row, m) } stats.OutputCounter++ return util.NewRow(util.Now(), row...).WriteTo(writer) }) } return fc.Source(address, fn) }
go
func (fc *Flow) Listen(network, address string) (ret *Dataset) { fn := func(writer io.Writer, stats *pb.InstructionStat) error { listener, err := net.Listen(network, address) if err != nil { return fmt.Errorf("Fail to listen on %s %s: %v", network, address, err) } conn, err := listener.Accept() if err != nil { return fmt.Errorf("Fail to accept on %s %s: %v", network, address, err) } defer conn.Close() return util.TakeTsv(conn, -1, func(message []string) error { stats.InputCounter++ var row []interface{} for _, m := range message { row = append(row, m) } stats.OutputCounter++ return util.NewRow(util.Now(), row...).WriteTo(writer) }) } return fc.Source(address, fn) }
[ "func", "(", "fc", "*", "Flow", ")", "Listen", "(", "network", ",", "address", "string", ")", "(", "ret", "*", "Dataset", ")", "{", "fn", ":=", "func", "(", "writer", "io", ".", "Writer", ",", "stats", "*", "pb", ".", "InstructionStat", ")", "error", "{", "listener", ",", "err", ":=", "net", ".", "Listen", "(", "network", ",", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Fail to listen on %s %s: %v\"", ",", "network", ",", "address", ",", "err", ")", "\n", "}", "\n", "conn", ",", "err", ":=", "listener", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Fail to accept on %s %s: %v\"", ",", "network", ",", "address", ",", "err", ")", "\n", "}", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "return", "util", ".", "TakeTsv", "(", "conn", ",", "-", "1", ",", "func", "(", "message", "[", "]", "string", ")", "error", "{", "stats", ".", "InputCounter", "++", "\n", "var", "row", "[", "]", "interface", "{", "}", "\n", "for", "_", ",", "m", ":=", "range", "message", "{", "row", "=", "append", "(", "row", ",", "m", ")", "\n", "}", "\n", "stats", ".", "OutputCounter", "++", "\n", "return", "util", ".", "NewRow", "(", "util", ".", "Now", "(", ")", ",", "row", "...", ")", ".", "WriteTo", "(", "writer", ")", "\n", "}", ")", "\n", "}", "\n", "return", "fc", ".", "Source", "(", "address", ",", "fn", ")", "\n", "}" ]
// Listen receives textual inputs via a socket. // Multiple parameters are separated via tab.
[ "Listen", "receives", "textual", "inputs", "via", "a", "socket", ".", "Multiple", "parameters", "are", "separated", "via", "tab", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/dataset_source.go#L24-L48
train
chrislusf/gleam
flow/context_hint.go
Hint
func (d *Flow) Hint(options ...FlowHintOption) { var config FlowConfig for _, option := range options { option(&config) } }
go
func (d *Flow) Hint(options ...FlowHintOption) { var config FlowConfig for _, option := range options { option(&config) } }
[ "func", "(", "d", "*", "Flow", ")", "Hint", "(", "options", "...", "FlowHintOption", ")", "{", "var", "config", "FlowConfig", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "&", "config", ")", "\n", "}", "\n", "}" ]
// Hint adds hints to the flow.
[ "Hint", "adds", "hints", "to", "the", "flow", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/context_hint.go#L10-L15
train
chrislusf/gleam
flow/context_hint.go
GetTotalSize
func (d *Dataset) GetTotalSize() int64 { if d.Meta.TotalSize >= 0 { return d.Meta.TotalSize } var currentDatasetTotalSize int64 for _, ds := range d.Step.InputDatasets { currentDatasetTotalSize += ds.GetTotalSize() } d.Meta.TotalSize = currentDatasetTotalSize return currentDatasetTotalSize }
go
func (d *Dataset) GetTotalSize() int64 { if d.Meta.TotalSize >= 0 { return d.Meta.TotalSize } var currentDatasetTotalSize int64 for _, ds := range d.Step.InputDatasets { currentDatasetTotalSize += ds.GetTotalSize() } d.Meta.TotalSize = currentDatasetTotalSize return currentDatasetTotalSize }
[ "func", "(", "d", "*", "Dataset", ")", "GetTotalSize", "(", ")", "int64", "{", "if", "d", ".", "Meta", ".", "TotalSize", ">=", "0", "{", "return", "d", ".", "Meta", ".", "TotalSize", "\n", "}", "\n", "var", "currentDatasetTotalSize", "int64", "\n", "for", "_", ",", "ds", ":=", "range", "d", ".", "Step", ".", "InputDatasets", "{", "currentDatasetTotalSize", "+=", "ds", ".", "GetTotalSize", "(", ")", "\n", "}", "\n", "d", ".", "Meta", ".", "TotalSize", "=", "currentDatasetTotalSize", "\n", "return", "currentDatasetTotalSize", "\n", "}" ]
// GetTotalSize returns the total size in MB for the dataset. // This is based on the given hint.
[ "GetTotalSize", "returns", "the", "total", "size", "in", "MB", "for", "the", "dataset", ".", "This", "is", "based", "on", "the", "given", "hint", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/context_hint.go#L19-L29
train
chrislusf/gleam
flow/context_hint.go
GetPartitionSize
func (d *Dataset) GetPartitionSize() int64 { return d.GetTotalSize() / int64(len(d.Shards)) }
go
func (d *Dataset) GetPartitionSize() int64 { return d.GetTotalSize() / int64(len(d.Shards)) }
[ "func", "(", "d", "*", "Dataset", ")", "GetPartitionSize", "(", ")", "int64", "{", "return", "d", ".", "GetTotalSize", "(", ")", "/", "int64", "(", "len", "(", "d", ".", "Shards", ")", ")", "\n", "}" ]
// GetPartitionSize returns the size in MB for each partition of // the dataset. This is based on the hinted total size divided by // the number of partitions.
[ "GetPartitionSize", "returns", "the", "size", "in", "MB", "for", "each", "partition", "of", "the", "dataset", ".", "This", "is", "based", "on", "the", "hinted", "total", "size", "divided", "by", "the", "number", "of", "partitions", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/flow/context_hint.go#L34-L36
train
chrislusf/gleam
sql/util/types/time.go
CompareString
func (t Time) CompareString(str string) (int, error) { // use MaxFsp to parse the string o, err := ParseTime(str, t.Type, MaxFsp) if err != nil { return 0, errors.Trace(err) } return t.Compare(o), nil }
go
func (t Time) CompareString(str string) (int, error) { // use MaxFsp to parse the string o, err := ParseTime(str, t.Type, MaxFsp) if err != nil { return 0, errors.Trace(err) } return t.Compare(o), nil }
[ "func", "(", "t", "Time", ")", "CompareString", "(", "str", "string", ")", "(", "int", ",", "error", ")", "{", "o", ",", "err", ":=", "ParseTime", "(", "str", ",", "t", ".", "Type", ",", "MaxFsp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "return", "t", ".", "Compare", "(", "o", ")", ",", "nil", "\n", "}" ]
// CompareString is like Compare, // but parses string to Time then compares.
[ "CompareString", "is", "like", "Compare", "but", "parses", "string", "to", "Time", "then", "compares", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/time.go#L297-L305
train
chrislusf/gleam
sql/util/types/time.go
AdjustYear
func AdjustYear(y int64) (int64, error) { y = int64(adjustYear(int(y))) if y < int64(MinYear) || y > int64(MaxYear) { return 0, errors.Trace(ErrInvalidYear) } return y, nil }
go
func AdjustYear(y int64) (int64, error) { y = int64(adjustYear(int(y))) if y < int64(MinYear) || y > int64(MaxYear) { return 0, errors.Trace(ErrInvalidYear) } return y, nil }
[ "func", "AdjustYear", "(", "y", "int64", ")", "(", "int64", ",", "error", ")", "{", "y", "=", "int64", "(", "adjustYear", "(", "int", "(", "y", ")", ")", ")", "\n", "if", "y", "<", "int64", "(", "MinYear", ")", "||", "y", ">", "int64", "(", "MaxYear", ")", "{", "return", "0", ",", "errors", ".", "Trace", "(", "ErrInvalidYear", ")", "\n", "}", "\n", "return", "y", ",", "nil", "\n", "}" ]
// AdjustYear is used for adjusting year and checking its validation.
[ "AdjustYear", "is", "used", "for", "adjusting", "year", "and", "checking", "its", "validation", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/time.go#L662-L669
train
chrislusf/gleam
sql/util/types/time.go
extractSecondMicrosecond
func extractSecondMicrosecond(format string) (int64, int64, int64, gotime.Duration, error) { fields := strings.Split(format, ".") if len(fields) != 2 { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } seconds, err := strconv.ParseInt(fields[0], 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } microseconds, err := strconv.ParseInt(alignFrac(fields[1], MaxFsp), 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } return 0, 0, 0, gotime.Duration(seconds)*gotime.Second + gotime.Duration(microseconds)*gotime.Microsecond, nil }
go
func extractSecondMicrosecond(format string) (int64, int64, int64, gotime.Duration, error) { fields := strings.Split(format, ".") if len(fields) != 2 { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } seconds, err := strconv.ParseInt(fields[0], 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } microseconds, err := strconv.ParseInt(alignFrac(fields[1], MaxFsp), 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } return 0, 0, 0, gotime.Duration(seconds)*gotime.Second + gotime.Duration(microseconds)*gotime.Microsecond, nil }
[ "func", "extractSecondMicrosecond", "(", "format", "string", ")", "(", "int64", ",", "int64", ",", "int64", ",", "gotime", ".", "Duration", ",", "error", ")", "{", "fields", ":=", "strings", ".", "Split", "(", "format", ",", "\".\"", ")", "\n", "if", "len", "(", "fields", ")", "!=", "2", "{", "return", "0", ",", "0", ",", "0", ",", "0", ",", "errors", ".", "Errorf", "(", "\"invalid time format - %s\"", ",", "format", ")", "\n", "}", "\n", "seconds", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "fields", "[", "0", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "0", ",", "0", ",", "errors", ".", "Errorf", "(", "\"invalid time format - %s\"", ",", "format", ")", "\n", "}", "\n", "microseconds", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "alignFrac", "(", "fields", "[", "1", "]", ",", "MaxFsp", ")", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "0", ",", "0", ",", "errors", ".", "Errorf", "(", "\"invalid time format - %s\"", ",", "format", ")", "\n", "}", "\n", "return", "0", ",", "0", ",", "0", ",", "gotime", ".", "Duration", "(", "seconds", ")", "*", "gotime", ".", "Second", "+", "gotime", ".", "Duration", "(", "microseconds", ")", "*", "gotime", ".", "Microsecond", ",", "nil", "\n", "}" ]
// Format is `SS.FFFFFF`.
[ "Format", "is", "SS", ".", "FFFFFF", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/time.go#L1342-L1359
train
chrislusf/gleam
sql/util/types/time.go
extractDayHour
func extractDayHour(format string) (int64, int64, int64, gotime.Duration, error) { fields := strings.Split(format, " ") if len(fields) != 2 { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } days, err := strconv.ParseInt(fields[0], 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } hours, err := strconv.ParseInt(fields[1], 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } return 0, 0, days, gotime.Duration(hours) * gotime.Hour, nil }
go
func extractDayHour(format string) (int64, int64, int64, gotime.Duration, error) { fields := strings.Split(format, " ") if len(fields) != 2 { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } days, err := strconv.ParseInt(fields[0], 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } hours, err := strconv.ParseInt(fields[1], 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } return 0, 0, days, gotime.Duration(hours) * gotime.Hour, nil }
[ "func", "extractDayHour", "(", "format", "string", ")", "(", "int64", ",", "int64", ",", "int64", ",", "gotime", ".", "Duration", ",", "error", ")", "{", "fields", ":=", "strings", ".", "Split", "(", "format", ",", "\" \"", ")", "\n", "if", "len", "(", "fields", ")", "!=", "2", "{", "return", "0", ",", "0", ",", "0", ",", "0", ",", "errors", ".", "Errorf", "(", "\"invalid time format - %s\"", ",", "format", ")", "\n", "}", "\n", "days", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "fields", "[", "0", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "0", ",", "0", ",", "errors", ".", "Errorf", "(", "\"invalid time format - %s\"", ",", "format", ")", "\n", "}", "\n", "hours", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "fields", "[", "1", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "0", ",", "0", ",", "errors", ".", "Errorf", "(", "\"invalid time format - %s\"", ",", "format", ")", "\n", "}", "\n", "return", "0", ",", "0", ",", "days", ",", "gotime", ".", "Duration", "(", "hours", ")", "*", "gotime", ".", "Hour", ",", "nil", "\n", "}" ]
// Format is `DD HH`.
[ "Format", "is", "DD", "HH", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/time.go#L1532-L1549
train
chrislusf/gleam
sql/util/types/time.go
extractYearMonth
func extractYearMonth(format string) (int64, int64, int64, gotime.Duration, error) { fields := strings.Split(format, "-") if len(fields) != 2 { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } years, err := strconv.ParseInt(fields[0], 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } months, err := strconv.ParseInt(fields[1], 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } return years, months, 0, 0, nil }
go
func extractYearMonth(format string) (int64, int64, int64, gotime.Duration, error) { fields := strings.Split(format, "-") if len(fields) != 2 { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } years, err := strconv.ParseInt(fields[0], 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } months, err := strconv.ParseInt(fields[1], 10, 64) if err != nil { return 0, 0, 0, 0, errors.Errorf("invalid time format - %s", format) } return years, months, 0, 0, nil }
[ "func", "extractYearMonth", "(", "format", "string", ")", "(", "int64", ",", "int64", ",", "int64", ",", "gotime", ".", "Duration", ",", "error", ")", "{", "fields", ":=", "strings", ".", "Split", "(", "format", ",", "\"-\"", ")", "\n", "if", "len", "(", "fields", ")", "!=", "2", "{", "return", "0", ",", "0", ",", "0", ",", "0", ",", "errors", ".", "Errorf", "(", "\"invalid time format - %s\"", ",", "format", ")", "\n", "}", "\n", "years", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "fields", "[", "0", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "0", ",", "0", ",", "errors", ".", "Errorf", "(", "\"invalid time format - %s\"", ",", "format", ")", "\n", "}", "\n", "months", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "fields", "[", "1", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "0", ",", "0", ",", "errors", ".", "Errorf", "(", "\"invalid time format - %s\"", ",", "format", ")", "\n", "}", "\n", "return", "years", ",", "months", ",", "0", ",", "0", ",", "nil", "\n", "}" ]
// Format is `YYYY-MM`.
[ "Format", "is", "YYYY", "-", "MM", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/time.go#L1552-L1569
train
chrislusf/gleam
sql/util/types/time.go
mysqlTimeFix
func mysqlTimeFix(t *mysqlTime, ctx map[string]int) error { // Key of the ctx is the format char, such as `%j` `%p` and so on. if yearOfDay, ok := ctx["%j"]; ok { // TODO: Implement the function that converts day of year to yy:mm:dd. _ = yearOfDay } if valueAMorPm, ok := ctx["%p"]; ok { if t.hour == 0 { return ErrInvalidTimeFormat } if t.hour == 12 { // 12 is a special hour. switch valueAMorPm { case constForAM: t.hour = 0 case constForPM: t.hour = 12 } return nil } if valueAMorPm == constForPM { t.hour += 12 } } return nil }
go
func mysqlTimeFix(t *mysqlTime, ctx map[string]int) error { // Key of the ctx is the format char, such as `%j` `%p` and so on. if yearOfDay, ok := ctx["%j"]; ok { // TODO: Implement the function that converts day of year to yy:mm:dd. _ = yearOfDay } if valueAMorPm, ok := ctx["%p"]; ok { if t.hour == 0 { return ErrInvalidTimeFormat } if t.hour == 12 { // 12 is a special hour. switch valueAMorPm { case constForAM: t.hour = 0 case constForPM: t.hour = 12 } return nil } if valueAMorPm == constForPM { t.hour += 12 } } return nil }
[ "func", "mysqlTimeFix", "(", "t", "*", "mysqlTime", ",", "ctx", "map", "[", "string", "]", "int", ")", "error", "{", "if", "yearOfDay", ",", "ok", ":=", "ctx", "[", "\"%j\"", "]", ";", "ok", "{", "_", "=", "yearOfDay", "\n", "}", "\n", "if", "valueAMorPm", ",", "ok", ":=", "ctx", "[", "\"%p\"", "]", ";", "ok", "{", "if", "t", ".", "hour", "==", "0", "{", "return", "ErrInvalidTimeFormat", "\n", "}", "\n", "if", "t", ".", "hour", "==", "12", "{", "switch", "valueAMorPm", "{", "case", "constForAM", ":", "t", ".", "hour", "=", "0", "\n", "case", "constForPM", ":", "t", ".", "hour", "=", "12", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "if", "valueAMorPm", "==", "constForPM", "{", "t", ".", "hour", "+=", "12", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// mysqlTimeFix fixes the mysqlTime use the values in the context.
[ "mysqlTimeFix", "fixes", "the", "mysqlTime", "use", "the", "values", "in", "the", "context", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/time.go#L1821-L1846
train
chrislusf/gleam
sql/util/types/time.go
strToDate
func strToDate(t *mysqlTime, date string, format string, ctx map[string]int) bool { date = skipWhiteSpace(date) format = skipWhiteSpace(format) token, formatRemain, succ := getFormatToken(format) if !succ { return false } if token == "" { // Extra characters at the end of date are ignored. return true } dateRemain, succ := matchDateWithToken(t, date, token, ctx) if !succ { return false } return strToDate(t, dateRemain, formatRemain, ctx) }
go
func strToDate(t *mysqlTime, date string, format string, ctx map[string]int) bool { date = skipWhiteSpace(date) format = skipWhiteSpace(format) token, formatRemain, succ := getFormatToken(format) if !succ { return false } if token == "" { // Extra characters at the end of date are ignored. return true } dateRemain, succ := matchDateWithToken(t, date, token, ctx) if !succ { return false } return strToDate(t, dateRemain, formatRemain, ctx) }
[ "func", "strToDate", "(", "t", "*", "mysqlTime", ",", "date", "string", ",", "format", "string", ",", "ctx", "map", "[", "string", "]", "int", ")", "bool", "{", "date", "=", "skipWhiteSpace", "(", "date", ")", "\n", "format", "=", "skipWhiteSpace", "(", "format", ")", "\n", "token", ",", "formatRemain", ",", "succ", ":=", "getFormatToken", "(", "format", ")", "\n", "if", "!", "succ", "{", "return", "false", "\n", "}", "\n", "if", "token", "==", "\"\"", "{", "return", "true", "\n", "}", "\n", "dateRemain", ",", "succ", ":=", "matchDateWithToken", "(", "t", ",", "date", ",", "token", ",", "ctx", ")", "\n", "if", "!", "succ", "{", "return", "false", "\n", "}", "\n", "return", "strToDate", "(", "t", ",", "dateRemain", ",", "formatRemain", ",", "ctx", ")", "\n", "}" ]
// strToDate converts date string according to format, returns true on success, // the value will be stored in argument t or ctx.
[ "strToDate", "converts", "date", "string", "according", "to", "format", "returns", "true", "on", "success", "the", "value", "will", "be", "stored", "in", "argument", "t", "or", "ctx", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/time.go#L1850-L1870
train
chrislusf/gleam
sql/util/types/time.go
dayOfMonthWithSuffix
func dayOfMonthWithSuffix(t *mysqlTime, input string, ctx map[string]int) (string, bool) { month, remain := parseOrdinalNumbers(input) if month >= 0 { t.month = uint8(month) return remain, true } return input, false }
go
func dayOfMonthWithSuffix(t *mysqlTime, input string, ctx map[string]int) (string, bool) { month, remain := parseOrdinalNumbers(input) if month >= 0 { t.month = uint8(month) return remain, true } return input, false }
[ "func", "dayOfMonthWithSuffix", "(", "t", "*", "mysqlTime", ",", "input", "string", ",", "ctx", "map", "[", "string", "]", "int", ")", "(", "string", ",", "bool", ")", "{", "month", ",", "remain", ":=", "parseOrdinalNumbers", "(", "input", ")", "\n", "if", "month", ">=", "0", "{", "t", ".", "month", "=", "uint8", "(", "month", ")", "\n", "return", "remain", ",", "true", "\n", "}", "\n", "return", "input", ",", "false", "\n", "}" ]
// 0th 1st 2nd 3rd ...
[ "0th", "1st", "2nd", "3rd", "..." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/util/types/time.go#L2240-L2247
train
chrislusf/gleam
gio/emit.go
TsEmit
func TsEmit(ts int64, anyObject ...interface{}) error { stat.Stats[0].OutputCounter++ return util.NewRow(ts, anyObject...).WriteTo(os.Stdout) }
go
func TsEmit(ts int64, anyObject ...interface{}) error { stat.Stats[0].OutputCounter++ return util.NewRow(ts, anyObject...).WriteTo(os.Stdout) }
[ "func", "TsEmit", "(", "ts", "int64", ",", "anyObject", "...", "interface", "{", "}", ")", "error", "{", "stat", ".", "Stats", "[", "0", "]", ".", "OutputCounter", "++", "\n", "return", "util", ".", "NewRow", "(", "ts", ",", "anyObject", "...", ")", ".", "WriteTo", "(", "os", ".", "Stdout", ")", "\n", "}" ]
// TsEmit encode and write a row of data to os.Stdout // with ts in milliseconds epoch time
[ "TsEmit", "encode", "and", "write", "a", "row", "of", "data", "to", "os", ".", "Stdout", "with", "ts", "in", "milliseconds", "epoch", "time" ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/gio/emit.go#L16-L19
train
chrislusf/gleam
sql/parser/yy_parser.go
Parse
func (parser *Parser) Parse(sql, charset, collation string) ([]ast.StmtNode, error) { if charset == "" { charset = mysql.DefaultCharset } if collation == "" { collation = mysql.DefaultCollationName } parser.charset = charset parser.collation = collation parser.src = sql parser.result = parser.result[:0] var l yyLexer parser.lexer.reset(sql) l = &parser.lexer yyParse(l, parser) if len(l.Errors()) != 0 { return nil, errors.Trace(l.Errors()[0]) } for _, stmt := range parser.result { ast.SetFlag(stmt) } return parser.result, nil }
go
func (parser *Parser) Parse(sql, charset, collation string) ([]ast.StmtNode, error) { if charset == "" { charset = mysql.DefaultCharset } if collation == "" { collation = mysql.DefaultCollationName } parser.charset = charset parser.collation = collation parser.src = sql parser.result = parser.result[:0] var l yyLexer parser.lexer.reset(sql) l = &parser.lexer yyParse(l, parser) if len(l.Errors()) != 0 { return nil, errors.Trace(l.Errors()[0]) } for _, stmt := range parser.result { ast.SetFlag(stmt) } return parser.result, nil }
[ "func", "(", "parser", "*", "Parser", ")", "Parse", "(", "sql", ",", "charset", ",", "collation", "string", ")", "(", "[", "]", "ast", ".", "StmtNode", ",", "error", ")", "{", "if", "charset", "==", "\"\"", "{", "charset", "=", "mysql", ".", "DefaultCharset", "\n", "}", "\n", "if", "collation", "==", "\"\"", "{", "collation", "=", "mysql", ".", "DefaultCollationName", "\n", "}", "\n", "parser", ".", "charset", "=", "charset", "\n", "parser", ".", "collation", "=", "collation", "\n", "parser", ".", "src", "=", "sql", "\n", "parser", ".", "result", "=", "parser", ".", "result", "[", ":", "0", "]", "\n", "var", "l", "yyLexer", "\n", "parser", ".", "lexer", ".", "reset", "(", "sql", ")", "\n", "l", "=", "&", "parser", ".", "lexer", "\n", "yyParse", "(", "l", ",", "parser", ")", "\n", "if", "len", "(", "l", ".", "Errors", "(", ")", ")", "!=", "0", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "l", ".", "Errors", "(", ")", "[", "0", "]", ")", "\n", "}", "\n", "for", "_", ",", "stmt", ":=", "range", "parser", ".", "result", "{", "ast", ".", "SetFlag", "(", "stmt", ")", "\n", "}", "\n", "return", "parser", ".", "result", ",", "nil", "\n", "}" ]
// Parse parses a query string to raw ast.StmtNode. // If charset or collation is "", default charset and collation will be used.
[ "Parse", "parses", "a", "query", "string", "to", "raw", "ast", ".", "StmtNode", ".", "If", "charset", "or", "collation", "is", "default", "charset", "and", "collation", "will", "be", "used", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/parser/yy_parser.go#L78-L102
train
chrislusf/gleam
sql/parser/yy_parser.go
ParseOneStmt
func (parser *Parser) ParseOneStmt(sql, charset, collation string) (ast.StmtNode, error) { stmts, err := parser.Parse(sql, charset, collation) if err != nil { return nil, errors.Trace(err) } if len(stmts) != 1 { return nil, ErrSyntax } ast.SetFlag(stmts[0]) return stmts[0], nil }
go
func (parser *Parser) ParseOneStmt(sql, charset, collation string) (ast.StmtNode, error) { stmts, err := parser.Parse(sql, charset, collation) if err != nil { return nil, errors.Trace(err) } if len(stmts) != 1 { return nil, ErrSyntax } ast.SetFlag(stmts[0]) return stmts[0], nil }
[ "func", "(", "parser", "*", "Parser", ")", "ParseOneStmt", "(", "sql", ",", "charset", ",", "collation", "string", ")", "(", "ast", ".", "StmtNode", ",", "error", ")", "{", "stmts", ",", "err", ":=", "parser", ".", "Parse", "(", "sql", ",", "charset", ",", "collation", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Trace", "(", "err", ")", "\n", "}", "\n", "if", "len", "(", "stmts", ")", "!=", "1", "{", "return", "nil", ",", "ErrSyntax", "\n", "}", "\n", "ast", ".", "SetFlag", "(", "stmts", "[", "0", "]", ")", "\n", "return", "stmts", "[", "0", "]", ",", "nil", "\n", "}" ]
// ParseOneStmt parses a query and returns an ast.StmtNode. // The query must have one statement, otherwise ErrSyntax is returned.
[ "ParseOneStmt", "parses", "a", "query", "and", "returns", "an", "ast", ".", "StmtNode", ".", "The", "query", "must", "have", "one", "statement", "otherwise", "ErrSyntax", "is", "returned", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/parser/yy_parser.go#L106-L116
train
chrislusf/gleam
sql/parser/yy_parser.go
setLastSelectFieldText
func (parser *Parser) setLastSelectFieldText(st *ast.SelectStmt, lastEnd int) { lastField := st.Fields.Fields[len(st.Fields.Fields)-1] if lastField.Offset+len(lastField.Text()) >= len(parser.src)-1 { lastField.SetText(parser.src[lastField.Offset:lastEnd]) } }
go
func (parser *Parser) setLastSelectFieldText(st *ast.SelectStmt, lastEnd int) { lastField := st.Fields.Fields[len(st.Fields.Fields)-1] if lastField.Offset+len(lastField.Text()) >= len(parser.src)-1 { lastField.SetText(parser.src[lastField.Offset:lastEnd]) } }
[ "func", "(", "parser", "*", "Parser", ")", "setLastSelectFieldText", "(", "st", "*", "ast", ".", "SelectStmt", ",", "lastEnd", "int", ")", "{", "lastField", ":=", "st", ".", "Fields", ".", "Fields", "[", "len", "(", "st", ".", "Fields", ".", "Fields", ")", "-", "1", "]", "\n", "if", "lastField", ".", "Offset", "+", "len", "(", "lastField", ".", "Text", "(", ")", ")", ">=", "len", "(", "parser", ".", "src", ")", "-", "1", "{", "lastField", ".", "SetText", "(", "parser", ".", "src", "[", "lastField", ".", "Offset", ":", "lastEnd", "]", ")", "\n", "}", "\n", "}" ]
// The select statement is not at the end of the whole statement, if the last // field text was set from its offset to the end of the src string, update // the last field text.
[ "The", "select", "statement", "is", "not", "at", "the", "end", "of", "the", "whole", "statement", "if", "the", "last", "field", "text", "was", "set", "from", "its", "offset", "to", "the", "end", "of", "the", "src", "string", "update", "the", "last", "field", "text", "." ]
a7aa467b545f5e5e452aaf818299a5f6e6b23760
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/parser/yy_parser.go#L121-L126
train
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", "inferrer", ".", "defaultCharset", "=", "\"utf8\"", "\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", "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", "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", "{", "continue", "\n", "}", "\n", "valueExpr", ".", "SetDatum", "(", "newDatum", ")", "\n", "}", "\n", "}", "\n", "if", "v", ".", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"inferor type for pattern in error %v\"", ",", "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", "result", ",", "err", ":=", "getResources", "(", "s", ".", "Master", ",", "&", "request", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"%s Failed to allocate: %v\"", ",", "s", ".", "Master", ",", "err", ")", "\n", "time", ".", "Sleep", "(", "time", ".", "Millisecond", "*", "time", ".", "Duration", "(", "15000", "+", "rand", ".", "Int63n", "(", "5000", ")", ")", ")", "\n", "}", "else", "{", "if", "len", "(", "result", ".", "Allocations", ")", "==", "0", "{", "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", "}", "\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", "+", "\".Reduce\"", "\n", "ret", "=", "d", ".", "LocalReduceBy", "(", "name", "+", "\".LocalReduce\"", ",", "reducerId", ",", "nil", ")", "\n", "if", "len", "(", "d", ".", "Shards", ")", ">", "1", "{", "ret", "=", "ret", ".", "MergeTo", "(", "name", ",", "1", ")", ".", "LocalReduceBy", "(", "name", "+", "\".LocalReduce2\"", ",", "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", "{", "join", ":=", "&", "apply", ".", "Join", "\n", "innerPlan", ".", "SetParents", "(", "join", ")", "\n", "outerPlan", ".", "SetParents", "(", "join", ")", "\n", "p", "=", "join", "\n", "}", "else", "if", "sel", ",", "ok", ":=", "innerPlan", ".", "(", "*", "Selection", ")", ";", "ok", "{", "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", "}", "\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", "function", "(", "writers", ")", "\n", "for", "_", ",", "w", ":=", "range", "bufWriters", "{", "w", ".", "Flush", "(", ")", "\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", "(", "\"line %d column %d near \\\"%s\\\"%s (total length %d)\"", ",", "\\\"", ",", "\\\"", ",", "s", ".", "r", ".", "p", ".", "Line", ",", "s", ".", "r", ".", "p", ".", "Col", ",", "val", ")", "\n", "str", "\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", "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", "(", "\"can't remove this plan\"", ")", "\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", "+", "\".Map\"", "\n", "step", ".", "IsPipe", "=", "false", "\n", "step", ".", "IsGoCode", "=", "true", "\n", "ex", ",", "_", ":=", "os", ".", "Executable", "(", ")", "\n", "mapper", ",", "_", ":=", "gio", ".", "GetMapper", "(", "mapperId", ")", "\n", "step", ".", "Description", "=", "mapper", ".", "Name", "\n", "var", "args", "[", "]", "string", "\n", "args", "=", "append", "(", "args", ",", "os", ".", "Args", "[", "1", ":", "]", "...", ")", "\n", "args", "=", "append", "(", "args", ",", "\"-gleam.mapper\"", ",", "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", "(", "\"select %v\"", ",", "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", "(", "\"local limit %d\"", ",", "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", "for", "taskCount", "==", "len", "(", "current", ".", "Tasks", ")", "{", "if", "len", "(", "current", ".", "InputDatasets", ")", ">", "1", "{", "break", "\n", "}", "\n", "if", "len", "(", "current", ".", "InputDatasets", ")", "==", "0", "{", "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", "current", "=", "current", ".", "InputDatasets", "[", "0", "]", ".", "Step", "\n", "taskCount", "=", "len", "(", "current", ".", "Tasks", ")", "\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", "{", "stepId2StepGroup", ":=", "make", "(", "[", "]", "*", "StepGroup", ",", "len", "(", "fc", ".", "Steps", ")", ")", "\n", "for", "_", ",", "step", ":=", "range", "fc", ".", "Steps", "{", "ancestorStepId", ",", "foundStepId", ":=", "findAncestorStepId", "(", "step", ")", "\n", "if", "!", "foundStepId", "{", "println", "(", "\"step:\"", ",", "step", ".", "Id", ",", "\"Not found ancestorStepId.\"", ")", "\n", "continue", "\n", "}", "\n", "if", "stepId2StepGroup", "[", "ancestorStepId", "]", "==", "nil", "{", "stepId2StepGroup", "[", "ancestorStepId", "]", "=", "NewStepGroup", "(", ")", "\n", "for", "_", ",", "ds", ":=", "range", "step", ".", "InputDatasets", "{", "parentDsId", ",", "hasParentIdId", ":=", "findAncestorStepId", "(", "ds", ".", "Step", ")", "\n", "if", "!", "hasParentIdId", "{", "log", ".", "Panic", "(", "\"parent StepGroup should already be in the map\"", ")", "\n", "}", "\n", "parentSg", ":=", "stepId2StepGroup", "[", "parentDsId", "]", "\n", "if", "parentSg", "==", "nil", "{", "log", ".", "Panic", "(", "\"parent StepGroup should already be in the map\"", ")", "\n", "}", "\n", "stepId2StepGroup", "[", "ancestorStepId", "]", ".", "AddParent", "(", "parentSg", ")", "\n", "}", "\n", "}", "\n", "stepId2StepGroup", "[", "ancestorStepId", "]", ".", "AddStep", "(", "step", ")", "\n", "}", "\n", "var", "ret", "[", "]", "*", "StepGroup", "\n", "for", "_", ",", "stepGroup", ":=", "range", "stepId2StepGroup", "{", "if", "stepGroup", "==", "nil", "||", "len", "(", "stepGroup", ".", "Steps", ")", "==", "0", "{", "continue", "\n", "}", "\n", "ret", "=", "append", "(", "ret", ",", "stepGroup", ")", "\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", ",", "\"UNSIGNED\"", ")", "\n", "}", "\n", "if", "mysql", ".", "HasZerofillFlag", "(", "ft", ".", "Flag", ")", "{", "strs", "=", "append", "(", "strs", ",", "\"ZEROFILL\"", ")", "\n", "}", "\n", "if", "mysql", ".", "HasBinaryFlag", "(", "ft", ".", "Flag", ")", "{", "strs", "=", "append", "(", "strs", ",", "\"BINARY\"", ")", "\n", "}", "\n", "if", "IsTypeChar", "(", "ft", ".", "Tp", ")", "||", "IsTypeBlob", "(", "ft", ".", "Tp", ")", "{", "if", "ft", ".", "Charset", "!=", "\"\"", "&&", "ft", ".", "Charset", "!=", "charset", ".", "CharsetBin", "{", "strs", "=", "append", "(", "strs", ",", "fmt", ".", "Sprintf", "(", "\"CHARACTER SET %s\"", ",", "ft", ".", "Charset", ")", ")", "\n", "}", "\n", "if", "ft", ".", "Collate", "!=", "\"\"", "&&", "ft", ".", "Collate", "!=", "charset", ".", "CharsetBin", "{", "strs", "=", "append", "(", "strs", ",", "fmt", ".", "Sprintf", "(", "\"COLLATE %s\"", ",", "ft", ".", "Collate", ")", ")", "\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", "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", "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", "(", "\"There may exist an error during constant folding. The function name is %s, args are %s\"", ",", "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", "(", "\"Failed to read message: %v\\n\"", ",", "\\n", ")", "\n", "}", "\n", "readError", "\n", "}", "\n", "count", "--", "\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", "if", "l", ".", "file", "==", "nil", "{", "if", "err", "=", "l", ".", "openNew", "(", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\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", "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", "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", "=", "\"Dummy\"", "\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", "(", "\"Can't find column %s in schema\"", ",", "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", "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", "(", "\"insufficient bytes to decode value\"", ")", "\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", ")", "{", "return", "validFloat", ",", "errors", ".", "Trace", "(", "ErrOverflow", ")", "\n", "}", "\n", "intCnt", "+=", "exp", "\n", "if", "intCnt", "<=", "0", "{", "return", "\"0\"", ",", "nil", "\n", "}", "\n", "if", "intCnt", "==", "1", "&&", "(", "digits", "[", "0", "]", "==", "'-'", "||", "digits", "[", "0", "]", "==", "'+'", ")", "{", "return", "\"0\"", ",", "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", "validFloat", ",", "errors", ".", "Trace", "(", "ErrOverflow", ")", "\n", "}", "\n", "validInt", "=", "string", "(", "digits", ")", "+", "strings", ".", "Repeat", "(", "\"0\"", ",", "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", "{", "break", "\n", "}", "\n", "}", "else", "if", "c", "==", "'.'", "{", "if", "sawDot", "||", "eIdx", ">", "0", "{", "break", "\n", "}", "\n", "sawDot", "=", "true", "\n", "if", "sawDigit", "{", "validLen", "=", "i", "+", "1", "\n", "}", "\n", "}", "else", "if", "c", "==", "'e'", "||", "c", "==", "'E'", "{", "if", "!", "sawDigit", "{", "break", "\n", "}", "\n", "if", "eIdx", "!=", "0", "{", "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", "=", "\"0\"", "\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", "\"1\"", ",", "nil", "\n", "}", "\n", "return", "\"0\"", ",", "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", "(", "\"cannot convert %v(type %T) to string\"", ",", "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", "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", "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", ")", "\n", "if", "isempty", "[", "0", "]", "{", "fieldsInUse", "--", "\n", "}", "\n", "isempty", "[", "1", "]", "=", "(", "len", "(", "z", ".", "V", ")", "==", "0", ")", "\n", "if", "isempty", "[", "1", "]", "{", "fieldsInUse", "--", "\n", "}", "\n", "isempty", "[", "2", "]", "=", "(", "z", ".", "T", "==", "0", ")", "\n", "if", "isempty", "[", "2", "]", "{", "fieldsInUse", "--", "\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", "if", "len", "(", "color", ")", "==", "0", "{", "color", "=", "lcolor", "\n", "}", "\n", "switch", "mark", "{", "case", "\"b\"", ":", "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", "case", "\"s\"", ":", "lx1", ",", "ly1", ":=", "arrow", "(", "canvas", ",", "x1", ",", "y1", ",", "aw", ",", "ah", ",", "d1", ",", "color", ")", "\n", "doline", "(", "canvas", ",", "lx1", ",", "ly1", ",", "x2", ",", "y2", ",", "linestyle", "(", "color", ")", ",", "dir", ",", "label", ")", "\n", "case", "\"d\"", ":", "lx2", ",", "ly2", ":=", "arrow", "(", "canvas", ",", "x2", ",", "y2", ",", "aw", ",", "ah", ",", "d2", ",", "color", ")", "\n", "doline", "(", "canvas", ",", "x1", ",", "y1", ",", "lx2", ",", "ly2", ",", "linestyle", "(", "color", ")", ",", "dir", ",", "label", ")", "\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", ":=", "notchsize", "\n", "switch", "dir", "{", "case", "\"r\"", ":", "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", "\"l\"", ":", "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", "\"u\"", ":", "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", "\"d\"", ":", "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", ",", "\"fill:\"", "+", "color", "+", "\";fill-opacity:\"", "+", "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", "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", "switch", "{", "case", "m", "<", "0", ":", "upflag", "=", "true", "\n", "labelstyle", "+=", "\"text-anchor:end;\"", "\n", "lx", "-=", "tadjust", "\n", "case", "hline", ":", "labelstyle", "+=", "\"text-anchor:middle;baseline-shift:20%;\"", "\n", "ly", "-=", "tadjust", "\n", "case", "m", ">", "0", ":", "upflag", "=", "false", "\n", "labelstyle", "+=", "\"text-anchor:start;\"", "\n", "lx", "+=", "tadjust", "\n", "}", "\n", "if", "!", "straight", "&&", "direction", "!=", "\"straight\"", "{", "cx", ",", "cy", ":=", "x1", ",", "y2", "\n", "if", "upflag", "{", "if", "direction", "==", "\"ccw\"", "{", "cx", ",", "cy", "=", "x2", ",", "y1", "\n", "}", "else", "{", "cx", ",", "cy", "=", "x1", ",", "y2", "\n", "}", "\n", "}", "else", "{", "if", "direction", "==", "\"ccw\"", "{", "cx", ",", "cy", "=", "x1", ",", "y2", "\n", "}", "else", "{", "cx", ",", "cy", "=", "x2", ",", "y1", "\n", "}", "\n", "}", "\n", "canvas", ".", "Qbez", "(", "x1", ",", "y1", ",", "cx", ",", "cy", ",", "x2", ",", "y2", ",", "style", ")", "\n", "labelstyle", "+=", "\"text-anchor:middle\"", "\n", "canvas", ".", "Text", "(", "lx", ",", "ly", ",", "label", ",", "labelstyle", ")", "\n", "}", "else", "{", "canvas", ".", "Line", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "style", ")", "\n", "canvas", ".", "Text", "(", "lx", ",", "ly", ",", "label", ",", "labelstyle", ")", "\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", "mapperId", ":=", "MapperId", "(", "fmt", ".", "Sprintf", "(", "\"m%d\"", ",", "len", "(", "mappers", ")", "+", "1", ")", ")", "\n", "mappers", "[", "mapperId", "]", "=", "MapperObject", "{", "fn", ",", "runtime", ".", "FuncForPC", "(", "reflect", ".", "ValueOf", "(", "fn", ")", ".", "Pointer", "(", ")", ")", ".", "Name", "(", ")", "}", "\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", "(", "\"ReplaceParent Failed!\"", ")", "\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", "(", "\"ReplaceChildren Failed!\"", ")", "\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