_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q12400
NewRandomGraph
train
func NewRandomGraph(n int) (generator.Generator, error) { if n < 1 { return nil, fmt.Errorf("invalid number of nodes %d<1", n) } nt, err := node.NewType("/gn") if err != nil { return nil, err } p, err := predicate.NewImmutable("follow") if err != nil { return nil, err } return &randomGraph{ nodes: n, nodeType: nt, predicate: p, }, nil }
go
{ "resource": "" }
q12401
newTriple
train
func (r *randomGraph) newTriple(i, j int) (*triple.Triple, error) { s, err := r.newNode(i) if err != nil { return nil, err } o, err := r.newNode(j) if err != nil { return nil, err } return triple.New(s, r.predicate, triple.NewNodeObject(o)) }
go
{ "resource": "" }
q12402
Generate
train
func (r *randomGraph) Generate(n int) ([]*triple.Triple, error) { maxEdges := r.nodes * r.nodes if n > maxEdges { return nil, fmt.Errorf("current configuration only allow a max of %d triples (%d requested)", maxEdges, n) } var trpls []*triple.Triple for _, idx := range rand.Perm(maxEdges)[:n] { i, j := idx/r.nodes, idx%r.nodes t, err := r.newTriple(i, j) if err != nil { return nil, err } trpls = append(trpls, t) } return trpls, nil }
go
{ "resource": "" }
q12403
New
train
func New(bs []string) (*Table, error) { m := make(map[string]bool) for _, b := range bs { m[b] = true } if len(m) != len(bs) { return nil, fmt.Errorf("table.New does not allow duplicated bindings in %s", bs) } return &Table{ AvailableBindings: bs, mbs: m, }, nil }
go
{ "resource": "" }
q12404
String
train
func (c *Cell) String() string { if c.S != nil { return *c.S } if c.N != nil { return c.N.String() } if c.P != nil { return c.P.String() } if c.L != nil { return c.L.String() } if c.T != nil { return c.T.Format(time.RFC3339Nano) } return "<NULL>" }
go
{ "resource": "" }
q12405
ToTextLine
train
func (r Row) ToTextLine(res *bytes.Buffer, bs []string, sep string) error { cnt := len(bs) if sep == "" { sep = "\t" } for _, b := range bs { cnt-- v := "<NULL>" if c, ok := r[b]; ok { v = c.String() } if _, err := res.WriteString(v); err != nil { return err } if cnt > 0 { res.WriteString(sep) } } return nil }
go
{ "resource": "" }
q12406
AddRow
train
func (t *Table) AddRow(r Row) { t.mu.Lock() if len(r) > 0 { delete(r, "") t.Data = append(t.Data, r) } t.mu.Unlock() }
go
{ "resource": "" }
q12407
NumRows
train
func (t *Table) NumRows() int { t.mu.RLock() defer t.mu.RUnlock() return len(t.Data) }
go
{ "resource": "" }
q12408
Row
train
func (t *Table) Row(i int) (Row, bool) { t.mu.RLock() defer t.mu.RUnlock() if i < 0 || i >= len(t.Data) { return nil, false } return t.Data[i], true }
go
{ "resource": "" }
q12409
Rows
train
func (t *Table) Rows() []Row { t.mu.RLock() defer t.mu.RUnlock() return t.Data }
go
{ "resource": "" }
q12410
unsafeAddBindings
train
func (t *Table) unsafeAddBindings(bs []string) { for _, b := range bs { if !t.mbs[b] { t.mbs[b] = true t.AvailableBindings = append(t.AvailableBindings, b) } } }
go
{ "resource": "" }
q12411
AddBindings
train
func (t *Table) AddBindings(bs []string) { t.mu.Lock() t.unsafeAddBindings(bs) t.mu.Unlock() }
go
{ "resource": "" }
q12412
ProjectBindings
train
func (t *Table) ProjectBindings(bs []string) error { t.mu.Lock() defer t.mu.Unlock() if len(t.Data) == 0 || len(t.mbs) == 0 { return nil } for _, b := range bs { if !t.mbs[b] { return fmt.Errorf("cannot project against unknown binding %s; known bindinds are %v", b, t.AvailableBindings) } } t.AvailableBindings = []string{} t.mbs = make(map[string]bool) t.unsafeAddBindings(bs) return nil }
go
{ "resource": "" }
q12413
HasBinding
train
func (t *Table) HasBinding(b string) bool { t.mu.RLock() defer t.mu.RUnlock() return t.mbs[b] }
go
{ "resource": "" }
q12414
Bindings
train
func (t *Table) Bindings() []string { t.mu.RLock() defer t.mu.RUnlock() return t.AvailableBindings }
go
{ "resource": "" }
q12415
equalBindings
train
func equalBindings(b1, b2 map[string]bool) bool { if len(b1) != len(b2) { return false } for k := range b1 { if !b2[k] { return false } } return true }
go
{ "resource": "" }
q12416
AppendTable
train
func (t *Table) AppendTable(t2 *Table) error { t.mu.Lock() defer t.mu.Unlock() if t2 == nil { return nil } if len(t.AvailableBindings) > 0 && !equalBindings(t.mbs, t2.mbs) { return fmt.Errorf("AppendTable can only append to an empty table or equally binded table; intead got %v and %v", t.AvailableBindings, t2.AvailableBindings) } if len(t.AvailableBindings) == 0 { t.AvailableBindings, t.mbs = t2.AvailableBindings, t2.mbs } t.Data = append(t.Data, t2.Data...) return nil }
go
{ "resource": "" }
q12417
disjointBinding
train
func disjointBinding(b1, b2 map[string]bool) bool { for k := range b1 { if b2[k] { return false } } return true }
go
{ "resource": "" }
q12418
MergeRows
train
func MergeRows(ms []Row) Row { res := make(map[string]*Cell) for _, om := range ms { for k, v := range om { if k != "" { res[k] = v } } } return res }
go
{ "resource": "" }
q12419
DotProduct
train
func (t *Table) DotProduct(t2 *Table) error { t.mu.Lock() defer t.mu.Unlock() if !disjointBinding(t.mbs, t2.mbs) { return fmt.Errorf("DotProduct operations requires disjoint bindings; instead got %v and %v", t.mbs, t2.mbs) } // Update the table metadata. m := make(map[string]bool) for k := range t.mbs { m[k] = true } for k := range t2.mbs { m[k] = true } t.mbs = m t.AvailableBindings = []string{} for k := range t.mbs { t.AvailableBindings = append(t.AvailableBindings, k) } // Update the data. td := t.Data cnt, size := 0, len(td)*len(t2.Data) t.Data = make([]Row, size, size) // Preallocate resulting table. for _, r1 := range td { for _, r2 := range t2.Data { t.Data[cnt] = MergeRows([]Row{r1, r2}) cnt++ } } return nil }
go
{ "resource": "" }
q12420
Truncate
train
func (t *Table) Truncate() { t.mu.Lock() defer t.mu.Unlock() t.Data = nil }
go
{ "resource": "" }
q12421
Limit
train
func (t *Table) Limit(i int64) { t.mu.Lock() defer t.mu.Unlock() if int64(len(t.Data)) > i { td := make([]Row, i, i) // Preallocate resulting table. copy(td, t.Data[:i]) t.Data = td } }
go
{ "resource": "" }
q12422
Swap
train
func (c bySortConfig) Swap(i, j int) { c.rows[i], c.rows[j] = c.rows[j], c.rows[i] }
go
{ "resource": "" }
q12423
Less
train
func (c bySortConfig) Less(i, j int) bool { ri, rj, cfg := c.rows[i], c.rows[j], c.cfg return rowLess(ri, rj, cfg) }
go
{ "resource": "" }
q12424
unsafeSort
train
func (t *Table) unsafeSort(cfg SortConfig) { if cfg == nil { return } sort.Sort(bySortConfig{t.Data, cfg}) }
go
{ "resource": "" }
q12425
Sort
train
func (t *Table) Sort(cfg SortConfig) { t.mu.Lock() t.unsafeSort(cfg) t.mu.Unlock() }
go
{ "resource": "" }
q12426
groupRangeReduce
train
func (t *Table) groupRangeReduce(i, j int, alias map[string]string, acc map[string]Accumulator) (Row, error) { t.mu.Lock() defer t.mu.Unlock() if i > j { return nil, fmt.Errorf("cannot aggregate empty ranges [%d, %d)", i, j) } // Initialize the range and accumulator results. rng := t.Data[i:j] vaccs := make(map[string]interface{}) // Reset the accumulators. for _, a := range acc { a.Reset() } // Aggregate the range using the provided aggregators. for _, r := range rng { for b, a := range acc { av, err := a.Accumulate(r[b]) if err != nil { return nil, err } vaccs[b] = av } } // Create a new row based on the resulting aggregations with the proper // binding aliasing and the non aggregated values. newRow := Row{} for b, v := range rng[0] { acc, ok := vaccs[b] if !ok { if a, ok := alias[b]; ok { newRow[a] = v } else { newRow[b] = v } } else { a, ok := alias[b] if !ok { return nil, fmt.Errorf("aggregated bindings require and alias; binding %s missing alias", b) } // Accumulators currently only can return numeric literals. switch acc.(type) { case int64: l, err := literal.DefaultBuilder().Build(literal.Int64, acc) if err != nil { return nil, err } newRow[a] = &Cell{L: l} case float64: l, err := literal.DefaultBuilder().Build(literal.Float64, acc) if err != nil { return nil, err } newRow[a] = &Cell{L: l} default: return nil, fmt.Errorf("aggregation of binding %s returned unknown value %v or type", b, acc) } } } return newRow, nil }
go
{ "resource": "" }
q12427
unsafeFullGroupRangeReduce
train
func (t *Table) unsafeFullGroupRangeReduce(i, j int, acc map[string]map[string]AliasAccPair) (Row, error) { if i > j { return nil, fmt.Errorf("cannot aggregate empty ranges [%d, %d)", i, j) } // Initialize the range and accumulator results. rng := t.Data[i:j] // Reset the accumulators. for _, aap := range acc { for _, a := range aap { if a.Acc != nil { a.Acc.Reset() } } } // Aggregate the range using the provided aggregators. vaccs := make(map[string]map[string]interface{}) for _, r := range rng { for _, aap := range acc { for _, a := range aap { if a.Acc == nil { continue } av, err := a.Acc.Accumulate(r[a.InAlias]) if err != nil { return nil, err } if _, ok := vaccs[a.InAlias]; !ok { vaccs[a.InAlias] = make(map[string]interface{}) } vaccs[a.InAlias][a.OutAlias] = av } } } // Create a new row based on the resulting aggregations with the proper // binding aliasing and the non aggregated values. newRow := Row{} for b, v := range rng[0] { for _, app := range acc[b] { //macc { if app.Acc == nil { newRow[app.OutAlias] = v } else { // Accumulators currently only can return numeric literals. switch vaccs[app.InAlias][app.OutAlias].(type) { case int64: l, err := literal.DefaultBuilder().Build(literal.Int64, vaccs[app.InAlias][app.OutAlias]) if err != nil { return nil, err } newRow[app.OutAlias] = &Cell{L: l} case float64: l, err := literal.DefaultBuilder().Build(literal.Float64, vaccs[app.InAlias][app.OutAlias]) if err != nil { return nil, err } newRow[app.OutAlias] = &Cell{L: l} default: return nil, fmt.Errorf("aggregation of binding %s returned unknown value %v or type", b, acc) } } } } if len(newRow) == 0 { return nil, errors.New("failed to reduced row range returning an empty one") } return newRow, nil }
go
{ "resource": "" }
q12428
toMap
train
func toMap(aaps []AliasAccPair) map[string]map[string]AliasAccPair { resMap := make(map[string]map[string]AliasAccPair) for _, aap := range aaps { m, ok := resMap[aap.InAlias] if !ok { m = make(map[string]AliasAccPair) resMap[aap.InAlias] = m } m[aap.OutAlias] = aap } return resMap }
go
{ "resource": "" }
q12429
Reduce
train
func (t *Table) Reduce(cfg SortConfig, aaps []AliasAccPair) error { t.mu.Lock() defer t.mu.Unlock() maaps := toMap(aaps) // Input validation tests. if len(t.AvailableBindings) != len(maaps) { return fmt.Errorf("table.Reduce cannot project bindings; current %v, requested %v", t.AvailableBindings, aaps) } for _, b := range t.AvailableBindings { if _, ok := maaps[b]; !ok { return fmt.Errorf("table.Reduce missing binding alias for %q", b) } } cnt := 0 for b := range maaps { if _, ok := t.mbs[b]; !ok { return fmt.Errorf("table.Reduce unknown reducer binding %q; available bindings %v", b, t.AvailableBindings) } cnt++ } if cnt != len(t.AvailableBindings) { return fmt.Errorf("table.Reduce invalid reduce configuration in cfg=%v, aap=%v for table with binding %v", cfg, aaps, t.AvailableBindings) } // Valid reduce configuration. Reduce sorts the table and then reduces // contiguous groups row groups. if len(t.Data) == 0 { return nil } t.unsafeSort(cfg) last, lastIdx, current, newData := "", 0, "", []Row{} id := func(r Row) string { res := bytes.NewBufferString("") for _, c := range cfg { res.WriteString(r[c.Binding].String()) res.WriteString(";") } return res.String() } for idx, r := range t.Data { current = id(r) // First time. if last == "" { last, lastIdx = current, idx continue } // Still in the same group. if last == current { continue } // A group reduce operation is needed. nr, err := t.unsafeFullGroupRangeReduce(lastIdx, idx, maaps) if err != nil { return err } newData = append(newData, nr) last, lastIdx = current, idx } nr, err := t.unsafeFullGroupRangeReduce(lastIdx, len(t.Data), maaps) if err != nil { return err } newData = append(newData, nr) // Update the table. t.AvailableBindings, t.mbs = []string{}, make(map[string]bool) for _, aap := range aaps { if !t.mbs[aap.OutAlias] { t.AvailableBindings = append(t.AvailableBindings, aap.OutAlias) } t.mbs[aap.OutAlias] = true } t.Data = newData return nil }
go
{ "resource": "" }
q12430
Filter
train
func (t *Table) Filter(f func(Row) bool) { t.mu.Lock() defer t.mu.Unlock() var newData []Row for _, r := range t.Data { if !f(r) { newData = append(newData, r) } } t.Data = newData }
go
{ "resource": "" }
q12431
ToText
train
func (t *Table) ToText(sep string) (*bytes.Buffer, error) { t.mu.RLock() defer t.mu.RUnlock() res, row := &bytes.Buffer{}, &bytes.Buffer{} res.WriteString(strings.Join(t.AvailableBindings, sep)) res.WriteString("\n") for _, r := range t.Data { err := r.ToTextLine(row, t.AvailableBindings, sep) if err != nil { return nil, err } if _, err := res.Write(row.Bytes()); err != nil { return nil, err } if _, err := res.WriteString("\n"); err != nil { return nil, err } row.Reset() } return res, nil }
go
{ "resource": "" }
q12432
String
train
func (t *Table) String() string { t.mu.RLock() defer t.mu.RUnlock() b, err := t.ToText("\t") if err != nil { return fmt.Sprintf("Failed to serialize to text! Error: %s", err) } return b.String() }
go
{ "resource": "" }
q12433
Trace
train
func Trace(w io.Writer, msgs func() []string) { if w == nil { return } c <- &event{w, time.Now(), msgs} }
go
{ "resource": "" }
q12434
String
train
func (l *LookupOptions) String() string { b := bytes.NewBufferString("<limit=") b.WriteString(strconv.Itoa(l.MaxElements)) b.WriteString(", lower_anchor=") if l.LowerAnchor != nil { b.WriteString(l.LowerAnchor.Format(time.RFC3339Nano)) } else { b.WriteString("nil") } b.WriteString(", upper_anchor=") if l.UpperAnchor != nil { b.WriteString(l.UpperAnchor.Format(time.RFC3339Nano)) } else { b.WriteString("nil") } b.WriteString(fmt.Sprintf(", LatestAnchor=%v", l.LatestAnchor)) b.WriteString(">") return b.String() }
go
{ "resource": "" }
q12435
UUID
train
func (l *LookupOptions) UUID() uuid.UUID { var buffer bytes.Buffer buffer.WriteString(l.String()) return uuid.NewSHA1(uuid.NIL, buffer.Bytes()) }
go
{ "resource": "" }
q12436
NewGraph
train
func (s *memoryStore) NewGraph(ctx context.Context, id string) (storage.Graph, error) { g := &memory{ id: id, idx: make(map[string]*triple.Triple, initialAllocation), idxS: make(map[string]map[string]*triple.Triple, initialAllocation), idxP: make(map[string]map[string]*triple.Triple, initialAllocation), idxO: make(map[string]map[string]*triple.Triple, initialAllocation), idxSP: make(map[string]map[string]*triple.Triple, initialAllocation), idxPO: make(map[string]map[string]*triple.Triple, initialAllocation), idxSO: make(map[string]map[string]*triple.Triple, initialAllocation), } s.rwmu.Lock() defer s.rwmu.Unlock() if _, ok := s.graphs[id]; ok { return nil, fmt.Errorf("memory.NewGraph(%q): graph already exists", id) } s.graphs[id] = g return g, nil }
go
{ "resource": "" }
q12437
Graph
train
func (s *memoryStore) Graph(ctx context.Context, id string) (storage.Graph, error) { s.rwmu.RLock() defer s.rwmu.RUnlock() if g, ok := s.graphs[id]; ok { return g, nil } return nil, fmt.Errorf("memory.Graph(%q): graph does not exist", id) }
go
{ "resource": "" }
q12438
AddTriples
train
func (m *memory) AddTriples(ctx context.Context, ts []*triple.Triple) error { m.rwmu.Lock() defer m.rwmu.Unlock() for _, t := range ts { tuuid := UUIDToByteString(t.UUID()) sUUID := UUIDToByteString(t.Subject().UUID()) pUUID := UUIDToByteString(t.Predicate().PartialUUID()) oUUID := UUIDToByteString(t.Object().UUID()) // Update master index m.idx[tuuid] = t if _, ok := m.idxS[sUUID]; !ok { m.idxS[sUUID] = make(map[string]*triple.Triple) } m.idxS[sUUID][tuuid] = t if _, ok := m.idxP[pUUID]; !ok { m.idxP[pUUID] = make(map[string]*triple.Triple) } m.idxP[pUUID][tuuid] = t if _, ok := m.idxO[oUUID]; !ok { m.idxO[oUUID] = make(map[string]*triple.Triple) } m.idxO[oUUID][tuuid] = t key := sUUID + pUUID if _, ok := m.idxSP[key]; !ok { m.idxSP[key] = make(map[string]*triple.Triple) } m.idxSP[key][tuuid] = t key = pUUID + oUUID if _, ok := m.idxPO[key]; !ok { m.idxPO[key] = make(map[string]*triple.Triple) } m.idxPO[key][tuuid] = t key = sUUID + oUUID if _, ok := m.idxSO[key]; !ok { m.idxSO[key] = make(map[string]*triple.Triple) } m.idxSO[key][tuuid] = t } return nil }
go
{ "resource": "" }
q12439
RemoveTriples
train
func (m *memory) RemoveTriples(ctx context.Context, ts []*triple.Triple) error { for _, t := range ts { suuid := UUIDToByteString(t.UUID()) sUUID := UUIDToByteString(t.Subject().UUID()) pUUID := UUIDToByteString(t.Predicate().PartialUUID()) oUUID := UUIDToByteString(t.Object().UUID()) // Update master index m.rwmu.Lock() delete(m.idx, suuid) delete(m.idxS[sUUID], suuid) delete(m.idxP[pUUID], suuid) delete(m.idxO[oUUID], suuid) key := sUUID + pUUID delete(m.idxSP[key], suuid) if len(m.idxSP[key]) == 0 { delete(m.idxSP, key) } key = pUUID + oUUID delete(m.idxPO[key], suuid) if len(m.idxPO[key]) == 0 { delete(m.idxPO, key) } key = sUUID + oUUID delete(m.idxSO[key], suuid) if len(m.idxSO[key]) == 0 { delete(m.idxSO, key) } m.rwmu.Unlock() } return nil }
go
{ "resource": "" }
q12440
newChecker
train
func newChecker(o *storage.LookupOptions, op *predicate.Predicate) *checker { var ta *time.Time if op != nil { if t, err := op.TimeAnchor(); err == nil { ta = t } } return &checker{ max: o.MaxElements > 0, c: o.MaxElements, o: o, op: op, ota: ta, } }
go
{ "resource": "" }
q12441
CheckAndUpdate
train
func (c *checker) CheckAndUpdate(p *predicate.Predicate) bool { if c.max && c.c <= 0 { return false } if p.Type() == predicate.Immutable { c.c-- return true } if t, err := p.TimeAnchor(); err == nil { if c.ota != nil && !c.ota.Equal(*t) { return false } if c.o.LowerAnchor != nil && t.Before(*c.o.LowerAnchor) { return false } if c.o.UpperAnchor != nil && t.After(*c.o.UpperAnchor) { return false } } c.c-- return true }
go
{ "resource": "" }
q12442
Objects
train
func (m *memory) Objects(ctx context.Context, s *node.Node, p *predicate.Predicate, lo *storage.LookupOptions, objs chan<- *triple.Object) error { if objs == nil { return fmt.Errorf("cannot provide an empty channel") } sUUID := UUIDToByteString(s.UUID()) pUUID := UUIDToByteString(p.PartialUUID()) spIdx := sUUID + pUUID m.rwmu.RLock() defer m.rwmu.RUnlock() defer close(objs) if lo.LatestAnchor { lastTA := make(map[string]*time.Time) trps := make(map[string]*triple.Triple) for _, t := range m.idxSP[spIdx] { p := t.Predicate() ppUUID := p.PartialUUID().String() if p.Type() == predicate.Temporal { ta, err := p.TimeAnchor() if err != nil { return err } if lta := lastTA[ppUUID]; lta == nil || ta.Sub(*lta) > 0 { trps[ppUUID] = t lastTA[ppUUID] = ta } } } for _, trp := range trps { if trp != nil { objs <- trp.Object() } } return nil } ckr := newChecker(lo, p) for _, t := range m.idxSP[spIdx] { if ckr.CheckAndUpdate(t.Predicate()) { objs <- t.Object() } } return nil }
go
{ "resource": "" }
q12443
Evaluate
train
func (a *AlwaysReturn) Evaluate(r table.Row) (bool, error) { return a.V, nil }
go
{ "resource": "" }
q12444
String
train
func (o OP) String() string { switch o { case LT: return "<" case GT: return ">" case EQ: return "=" case NOT: return "not" case AND: return "and" case OR: return "or" default: return "@UNKNOWN@" } }
go
{ "resource": "" }
q12445
NewEvaluationExpression
train
func NewEvaluationExpression(op OP, lB, rB string) (Evaluator, error) { l, r := strings.TrimSpace(lB), strings.TrimSpace(rB) if l == "" || r == "" { return nil, fmt.Errorf("bindings cannot be empty; got %q, %q", l, r) } switch op { case EQ, LT, GT: return &evaluationNode{ op: op, lB: lB, rB: rB, }, nil default: return nil, errors.New("evaluation expressions require the operation to be one for the follwing '=', '<', '>'") } }
go
{ "resource": "" }
q12446
NewBinaryBooleanExpression
train
func NewBinaryBooleanExpression(op OP, lE, rE Evaluator) (Evaluator, error) { switch op { case AND, OR: return &booleanNode{ op: op, lS: true, lE: lE, rS: true, rE: rE, }, nil default: return nil, errors.New("binary boolean expressions require the operation to be one for the follwing 'and', 'or'") } }
go
{ "resource": "" }
q12447
NewUnaryBooleanExpression
train
func NewUnaryBooleanExpression(op OP, lE Evaluator) (Evaluator, error) { switch op { case NOT: return &booleanNode{ op: op, lS: true, lE: lE, rS: false, }, nil default: return nil, errors.New("unary boolean expressions require the operation to be one for the follwing 'not'") } }
go
{ "resource": "" }
q12448
NewEvaluator
train
func NewEvaluator(ce []ConsumedElement) (Evaluator, error) { e, tailCEs, err := internalNewEvaluator(ce) if err != nil { return nil, err } if len(tailCEs) > 1 || (len(tailCEs) == 1 && tailCEs[0].Token().Type != lexer.ItemRPar) { return nil, fmt.Errorf("failed to consume all token; left over %v", tailCEs) } return e, nil }
go
{ "resource": "" }
q12449
String
train
func (t Type) String() string { switch t { case Bool: return "bool" case Int64: return "int64" case Float64: return "float64" case Text: return "text" case Blob: return "blob" default: return "UNKNOWN" } }
go
{ "resource": "" }
q12450
ToComparableString
train
func (l *Literal) ToComparableString() string { s := "" switch l.t { case Int64: s = fmt.Sprintf("\"%032d\"^^type:%v", l.Interface(), l.Type()) case Float64: s = fmt.Sprintf("\"%032f\"^^type:%v", l.Interface(), l.Type()) default: s = l.String() } return s }
go
{ "resource": "" }
q12451
Bool
train
func (l *Literal) Bool() (bool, error) { if l.t != Bool { return false, fmt.Errorf("literal.Bool: literal is of type %v; cannot be converted to a bool", l.t) } return l.v.(bool), nil }
go
{ "resource": "" }
q12452
Int64
train
func (l *Literal) Int64() (int64, error) { if l.t != Int64 { return 0, fmt.Errorf("literal.Int64: literal is of type %v; cannot be converted to a int64", l.t) } return l.v.(int64), nil }
go
{ "resource": "" }
q12453
Float64
train
func (l *Literal) Float64() (float64, error) { if l.t != Float64 { return 0, fmt.Errorf("literal.Float64: literal is of type %v; cannot be converted to a float64", l.t) } return l.v.(float64), nil }
go
{ "resource": "" }
q12454
Text
train
func (l *Literal) Text() (string, error) { if l.t != Text { return "", fmt.Errorf("literal.Text: literal is of type %v; cannot be converted to a string", l.t) } return l.v.(string), nil }
go
{ "resource": "" }
q12455
Build
train
func (b *unboundBuilder) Build(t Type, v interface{}) (*Literal, error) { switch v.(type) { case bool: if t != Bool { return nil, fmt.Errorf("literal.Build: type %v does not match type of value %v", t, v) } case int64: if t != Int64 { return nil, fmt.Errorf("literal.Build: type %v does not match type of value %v", t, v) } case float64: if t != Float64 { return nil, fmt.Errorf("literal.Build: type %v does not match type of value %v", t, v) } case string: if t != Text { return nil, fmt.Errorf("literal.Build: type %v does not match type of value %v", t, v) } case []byte: if t != Blob { return nil, fmt.Errorf("literal.Build: type %v does not match type of value %v", t, v) } default: return nil, fmt.Errorf("literal.Build: type %T is not supported when building literals", v) } return &Literal{ t: t, v: v, }, nil }
go
{ "resource": "" }
q12456
Parse
train
func (b *unboundBuilder) Parse(s string) (*Literal, error) { raw := strings.TrimSpace(s) if len(raw) == 0 { return nil, fmt.Errorf("literal.Parse: cannot parse and empty string into a literal; provided string %q", s) } if raw[0] != '"' { return nil, fmt.Errorf("literal.Parse: text encoded literals must start with \", missing in %s", raw) } idx := strings.Index(raw, "\"^^type:") if idx < 0 { return nil, fmt.Errorf("literal.Parse: text encoded literals must have a type; missing in %s", raw) } v := raw[1:idx] t := raw[idx+len("\"^^type:"):] switch t { case "bool": pv, err := strconv.ParseBool(v) if err != nil { return nil, fmt.Errorf("literal.Parse: could not convert value %q to bool", v) } return b.Build(Bool, pv) case "int64": pv, err := strconv.ParseInt(v, 10, 64) if err != nil { return nil, fmt.Errorf("literal.Parse: could not convert value %q to int64", v) } return b.Build(Int64, int64(pv)) case "float64": pv, err := strconv.ParseFloat(v, 64) if err != nil { return nil, fmt.Errorf("literal.Parse: could not convert value %q to float64", v) } return b.Build(Float64, float64(pv)) case "text": return b.Build(Text, v) case "blob": values := v[1 : len(v)-1] if values == "" { return b.Build(Blob, []byte{}) } bs := []byte{} for _, s := range strings.Split(values, " ") { b, err := strconv.ParseUint(s, 10, 8) if err != nil { return nil, fmt.Errorf("literal.Parse: failed to decode byte array on %q with error %v", s, err) } bs = append(bs, byte(b)) } return b.Build(Blob, bs) default: return nil, nil } }
go
{ "resource": "" }
q12457
Build
train
func (b *boundedBuilder) Build(t Type, v interface{}) (*Literal, error) { switch v.(type) { case string: if l := len(v.(string)); l > b.max { return nil, fmt.Errorf("literal.Build: cannot create literal due to size of %v (%d>%d)", v, l, b.max) } case []byte: if l := len(v.([]byte)); l > b.max { return nil, fmt.Errorf("literal.Build: cannot create literal due to size of %v (%d>%d)", v, l, b.max) } } return defaultBuilder.Build(t, v) }
go
{ "resource": "" }
q12458
Parse
train
func (b *boundedBuilder) Parse(s string) (*Literal, error) { l, err := defaultBuilder.Parse(s) if err != nil { return nil, err } t := l.Type() switch t { case Text: if text, err := l.Text(); err != nil || len(text) > b.max { return nil, fmt.Errorf("literal.Parse: cannot create literal due to size of %v (%d>%d)", t, len(text), b.max) } case Blob: if blob, err := l.Blob(); err != nil || len(blob) > b.max { return nil, fmt.Errorf("literal.Parse: cannot create literal due to size of %v (%d>%d)", t, len(blob), b.max) } } return l, nil }
go
{ "resource": "" }
q12459
UUID
train
func (l *Literal) UUID() uuid.UUID { var buffer bytes.Buffer switch v := l.v.(type) { case bool: if v { buffer.WriteString("true") } else { buffer.WriteString("false") } case int64: b := make([]byte, 8) binary.PutVarint(b, v) buffer.Write(b) case float64: bs := math.Float64bits(v) b := make([]byte, 8) binary.LittleEndian.PutUint64(b, bs) buffer.Write(b) case string: buffer.Write([]byte(v)) case []byte: buffer.Write(v) } return uuid.NewSHA1(uuid.NIL, buffer.Bytes()) }
go
{ "resource": "" }
q12460
String
train
func (p *Predicate) String() string { if p.anchor == nil { return fmt.Sprintf("%q@[]", p.id) } return fmt.Sprintf("%q@[%s]", p.id, p.anchor.Format(time.RFC3339Nano)) }
go
{ "resource": "" }
q12461
Parse
train
func Parse(s string) (*Predicate, error) { raw := strings.TrimSpace(s) if raw == "" { return nil, fmt.Errorf("predicate.Parse cannot create predicate from empty string %q", s) } if raw[0] != '"' { return nil, fmt.Errorf("predicate.Parse failed to parse since string does not start with \" in %s", s) } idx := strings.Index(raw, "\"@[") if idx < 0 { return nil, fmt.Errorf("predicate.Parse could not find anchor definition in %s", raw) } id, ta := raw[0:idx+1], raw[idx+3:len(raw)-1] id, err := strconv.Unquote(id) if err != nil { return nil, fmt.Errorf("predicate.Parse can't unquote id in %s: %v", raw, err) } // TODO: if id has \" inside, it should be unquoted. if ta == "" { return &Predicate{ id: ID(id), }, nil } if ta[0] == '"' { ta = ta[1:] } if ta[len(ta)-1] == '"' { ta = ta[:len(ta)-1] } pta, err := time.Parse(time.RFC3339Nano, ta) if err != nil { return nil, fmt.Errorf("predicate.Parse failed to parse time anchor %s in %s with error %v", ta, raw, err) } return &Predicate{ id: ID(id), anchor: &pta, }, nil }
go
{ "resource": "" }
q12462
TimeAnchor
train
func (p *Predicate) TimeAnchor() (*time.Time, error) { if p.anchor == nil { return nil, fmt.Errorf("predicate.TimeAnchor cannot return anchor for immutable predicate %v", p) } return p.anchor, nil }
go
{ "resource": "" }
q12463
NewImmutable
train
func NewImmutable(id string) (*Predicate, error) { if id == "" { return nil, fmt.Errorf("predicate.NewImmutable(%q) cannot create a immutable predicate with empty ID", id) } return &Predicate{ id: ID(id), }, nil }
go
{ "resource": "" }
q12464
NewTemporal
train
func NewTemporal(id string, t time.Time) (*Predicate, error) { if id == "" { return nil, fmt.Errorf("predicate.NewTemporal(%q, %v) cannot create a temporal predicate with empty ID", id, t) } return &Predicate{ id: ID(id), anchor: &t, }, nil }
go
{ "resource": "" }
q12465
UUID
train
func (p *Predicate) UUID() uuid.UUID { var buffer bytes.Buffer buffer.WriteString(string(p.id)) if p.anchor == nil { buffer.WriteString("immutable") } else { b := make([]byte, 16) binary.PutVarint(b, p.anchor.UnixNano()) buffer.Write(b) } return uuid.NewSHA1(uuid.NIL, buffer.Bytes()) }
go
{ "resource": "" }
q12466
PartialUUID
train
func (p *Predicate) PartialUUID() uuid.UUID { var buffer bytes.Buffer buffer.WriteString(string(p.id)) return uuid.NewSHA1(uuid.NIL, buffer.Bytes()) }
go
{ "resource": "" }
q12467
UsageString
train
func (c *Command) UsageString() string { return fmt.Sprintf("usage:\n\n\t$ badwolf %s\n\n%s\n", c.UsageLine, strings.TrimSpace(c.Long)) }
go
{ "resource": "" }
q12468
New
train
func New(branch int) (generator.Generator, error) { if branch < 1 { return nil, fmt.Errorf("invalid branch factor %d", branch) } nt, err := node.NewType("/tn") if err != nil { return nil, err } p, err := predicate.NewImmutable("parent_of") if err != nil { return nil, err } return &treeGenerator{ branch: branch, nodeType: nt, predicate: p, }, nil }
go
{ "resource": "" }
q12469
newTriple
train
func (t *treeGenerator) newTriple(parent, descendant *node.Node) (*triple.Triple, error) { return triple.New(parent, t.predicate, triple.NewNodeObject(descendant)) }
go
{ "resource": "" }
q12470
recurse
train
func (t *treeGenerator) recurse(parent *node.Node, left *int, currentDepth, maxDepth int, trpls []*triple.Triple) ([]*triple.Triple, error) { if *left < 1 { return trpls, nil } for i, last := 0, *left <= t.branch; i < t.branch; i++ { offspring, err := t.newNode(i, parent.ID().String()) if err != nil { return trpls, err } trpl, err := t.newTriple(parent, offspring) if err != nil { return trpls, err } trpls = append(trpls, trpl) (*left)-- if *left < 1 { break } if currentDepth < maxDepth && !last { ntrpls, err := t.recurse(offspring, left, currentDepth+1, maxDepth, trpls) if err != nil { return ntrpls, err } trpls = ntrpls } if *left < 1 { break } } return trpls, nil }
go
{ "resource": "" }
q12471
Generate
train
func (t *treeGenerator) Generate(n int) ([]*triple.Triple, error) { var trpls []*triple.Triple if n <= 0 { return trpls, nil } root, err := t.newNode(0, "") if err != nil { return nil, err } depth := int(math.Log(float64(n)) / math.Log(float64(t.branch))) ntrpls, err := t.recurse(root, &n, 0, depth, trpls) if err != nil { return nil, err } return ntrpls, nil }
go
{ "resource": "" }
q12472
String
train
func (o *Object) String() string { if o.n != nil { return o.n.String() } if o.l != nil { return o.l.String() } if o.p != nil { return o.p.String() } return "@@@INVALID_OBJECT@@@" }
go
{ "resource": "" }
q12473
UUID
train
func (o *Object) UUID() uuid.UUID { switch { case o.l != nil: return o.l.UUID() case o.p != nil: return o.p.UUID() default: return o.n.UUID() } }
go
{ "resource": "" }
q12474
Node
train
func (o *Object) Node() (*node.Node, error) { if o.n == nil { return nil, fmt.Errorf("triple.Literal does not box a node in %s", o) } return o.n, nil }
go
{ "resource": "" }
q12475
Predicate
train
func (o *Object) Predicate() (*predicate.Predicate, error) { if o.p == nil { return nil, fmt.Errorf("triple.Literal does not box a predicate in %s", o) } return o.p, nil }
go
{ "resource": "" }
q12476
Literal
train
func (o *Object) Literal() (*literal.Literal, error) { if o.l == nil { return nil, fmt.Errorf("triple.Literal does not box a literal in %s", o) } return o.l, nil }
go
{ "resource": "" }
q12477
ParseObject
train
func ParseObject(s string, b literal.Builder) (*Object, error) { n, err := node.Parse(s) if err == nil { return NewNodeObject(n), nil } l, err := b.Parse(s) if err == nil { return NewLiteralObject(l), nil } o, err := predicate.Parse(s) if err == nil { return NewPredicateObject(o), nil } return nil, err }
go
{ "resource": "" }
q12478
New
train
func New(s *node.Node, p *predicate.Predicate, o *Object) (*Triple, error) { if s == nil || p == nil || o == nil { return nil, fmt.Errorf("triple.New cannot create triples from nil components in <%v %v %v>", s, p, o) } return &Triple{ s: s, p: p, o: o, }, nil }
go
{ "resource": "" }
q12479
Equal
train
func (t *Triple) Equal(t2 *Triple) bool { return uuid.Equal(t.UUID(), t2.UUID()) }
go
{ "resource": "" }
q12480
String
train
func (t *Triple) String() string { return fmt.Sprintf("%s\t%s\t%s", t.s, t.p, t.o) }
go
{ "resource": "" }
q12481
Parse
train
func Parse(line string, b literal.Builder) (*Triple, error) { raw := strings.TrimSpace(line) idxp := pSplit.FindIndex([]byte(raw)) idxo := oSplit.FindIndex([]byte(raw)) if len(idxp) == 0 || len(idxo) == 0 { return nil, fmt.Errorf("triple.Parse could not split s p o out of %s", raw) } ss, sp, so := raw[0:idxp[0]+1], raw[idxp[1]-1:idxo[0]+1], raw[idxo[1]-1:] s, err := node.Parse(ss) if err != nil { return nil, fmt.Errorf("triple.Parse failed to parse subject %s with error %v", ss, err) } p, err := predicate.Parse(sp) if err != nil { return nil, fmt.Errorf("triple.Parse failed to parse predicate %s with error %v", sp, err) } o, err := ParseObject(so, b) if err != nil { return nil, fmt.Errorf("triple.Parse failed to parse object %s with error %v", so, err) } return New(s, p, o) }
go
{ "resource": "" }
q12482
Reify
train
func (t *Triple) Reify() ([]*Triple, *node.Node, error) { // Function that creates the proper reification predicates. rp := func(id string, p *predicate.Predicate) (*predicate.Predicate, error) { if p.Type() == predicate.Temporal { ta, _ := p.TimeAnchor() return predicate.NewTemporal(id, *ta) } return predicate.NewImmutable(id) } b := node.NewBlankNode() s, err := rp("_subject", t.p) if err != nil { return nil, nil, err } ts, _ := New(b, s, NewNodeObject(t.s)) p, err := rp("_predicate", t.p) if err != nil { return nil, nil, err } tp, _ := New(b, p, NewPredicateObject(t.p)) var to *Triple if t.o.l != nil { o, err := rp("_object", t.p) if err != nil { return nil, nil, err } to, _ = New(b, o, NewLiteralObject(t.o.l)) } if t.o.n != nil { o, err := rp("_object", t.p) if err != nil { return nil, nil, err } to, _ = New(b, o, NewNodeObject(t.o.n)) } if t.o.p != nil { o, err := rp("_object", t.p) if err != nil { return nil, nil, err } to, _ = New(b, o, NewPredicateObject(t.o.p)) } return []*Triple{t, ts, tp, to}, b, nil }
go
{ "resource": "" }
q12483
UUID
train
func (t *Triple) UUID() uuid.UUID { var buffer bytes.Buffer buffer.Write([]byte(t.s.UUID())) buffer.Write([]byte(t.p.UUID())) buffer.Write([]byte(t.o.UUID())) return uuid.NewSHA1(uuid.NIL, buffer.Bytes()) }
go
{ "resource": "" }
q12484
TypeBindingClauseHook
train
func TypeBindingClauseHook(t StatementType) ClauseHook { var f ClauseHook f = func(s *Statement, _ Symbol) (ClauseHook, error) { s.BindType(t) return f, nil } return f }
go
{ "resource": "" }
q12485
dataAccumulator
train
func dataAccumulator(b literal.Builder) ElementHook { var ( hook ElementHook s *node.Node p *predicate.Predicate o *triple.Object ) hook = func(st *Statement, ce ConsumedElement) (ElementHook, error) { if ce.IsSymbol() { return hook, nil } tkn := ce.Token() if tkn.Type != lexer.ItemNode && tkn.Type != lexer.ItemPredicate && tkn.Type != lexer.ItemLiteral { return hook, nil } if s == nil { if tkn.Type != lexer.ItemNode { return nil, fmt.Errorf("hook.DataAccumulator requires a node to create a subject, got %v instead", tkn) } tmp, err := node.Parse(tkn.Text) if err != nil { return nil, err } s = tmp return hook, nil } if p == nil { if tkn.Type != lexer.ItemPredicate { return nil, fmt.Errorf("hook.DataAccumulator requires a predicate to create a predicate, got %v instead", tkn) } tmp, err := predicate.Parse(tkn.Text) if err != nil { return nil, err } p = tmp return hook, nil } if o == nil { tmp, err := triple.ParseObject(tkn.Text, b) if err != nil { return nil, err } o = tmp trpl, err := triple.New(s, p, o) if err != nil { return nil, err } st.AddData(trpl) s, p, o = nil, nil, nil return hook, nil } return nil, fmt.Errorf("hook.DataAccumulator has failed to flush the triple %s, %s, %s", s, p, o) } return hook }
go
{ "resource": "" }
q12486
graphAccumulator
train
func graphAccumulator() ElementHook { var hook ElementHook hook = func(st *Statement, ce ConsumedElement) (ElementHook, error) { if ce.IsSymbol() { return hook, nil } tkn := ce.Token() switch tkn.Type { case lexer.ItemComma: return hook, nil case lexer.ItemBinding: st.AddGraph(strings.TrimSpace(tkn.Text)) return hook, nil default: return nil, fmt.Errorf("hook.GraphAccumulator requires a binding to refer to a graph, got %v instead", tkn) } } return hook }
go
{ "resource": "" }
q12487
whereNextWorkingClause
train
func whereNextWorkingClause() ClauseHook { var f ClauseHook f = func(s *Statement, _ Symbol) (ClauseHook, error) { s.AddWorkingGraphClause() return f, nil } return f }
go
{ "resource": "" }
q12488
whereInitWorkingClause
train
func whereInitWorkingClause() ClauseHook { var f ClauseHook f = func(s *Statement, _ Symbol) (ClauseHook, error) { s.ResetWorkingGraphClause() return f, nil } return f }
go
{ "resource": "" }
q12489
whereSubjectClause
train
func whereSubjectClause() ElementHook { var ( f ElementHook lastNopToken *lexer.Token ) f = func(st *Statement, ce ConsumedElement) (ElementHook, error) { if ce.IsSymbol() { return f, nil } tkn := ce.Token() c := st.WorkingClause() switch tkn.Type { case lexer.ItemNode: if c.S != nil { return nil, fmt.Errorf("invalid node in where clause that already has a subject; current %v, got %v", c.S, tkn.Type) } n, err := ToNode(ce) if err != nil { return nil, err } c.S = n lastNopToken = nil return f, nil case lexer.ItemBinding: if lastNopToken == nil { if c.SBinding != "" { return nil, fmt.Errorf("subject binding %q is already set to %q", tkn.Text, c.SBinding) } c.SBinding = tkn.Text lastNopToken = nil return f, nil } if lastNopToken.Type == lexer.ItemAs { if c.SAlias != "" { return nil, fmt.Errorf("AS alias binding for subject has already being assigned on %v", st) } c.SAlias = tkn.Text lastNopToken = nil return f, nil } if lastNopToken.Type == lexer.ItemType { if c.STypeAlias != "" { return nil, fmt.Errorf("TYPE alias binding for subject has already being assigned on %v", st) } c.STypeAlias = tkn.Text lastNopToken = nil return f, nil } if c.SIDAlias == "" && lastNopToken.Type == lexer.ItemID { if c.SIDAlias != "" { return nil, fmt.Errorf("ID alias binding for subject has already being assigned on %v", st) } c.SIDAlias = tkn.Text lastNopToken = nil return f, nil } } lastNopToken = tkn return f, nil } return f }
go
{ "resource": "" }
q12490
processPredicate
train
func processPredicate(ce ConsumedElement) (*predicate.Predicate, string, string, bool, error) { var ( nP *predicate.Predicate pID string pAnchorBinding string temporal bool ) raw := ce.Token().Text p, err := predicate.Parse(raw) if err == nil { // A fully specified predicate was provided. nP = p return nP, pID, pAnchorBinding, nP.Type() == predicate.Temporal, nil } // The predicate may have a binding on the anchor. cmps := predicateRegexp.FindAllStringSubmatch(raw, 2) if len(cmps) != 1 || (len(cmps) == 1 && len(cmps[0]) != 3) { return nil, "", "", false, fmt.Errorf("failed to extract partially defined predicate %q, got %v instead", raw, cmps) } id, ta := cmps[0][1], cmps[0][2] pID = id if ta != "" { pAnchorBinding = ta temporal = true } return nil, pID, pAnchorBinding, temporal, nil }
go
{ "resource": "" }
q12491
processPredicateBound
train
func processPredicateBound(ce ConsumedElement) (string, string, string, *time.Time, *time.Time, bool, error) { var ( pID string pLowerBoundAlias string pUpperBoundAlias string pLowerBound *time.Time pUpperBound *time.Time ) raw := ce.Token().Text cmps := boundRegexp.FindAllStringSubmatch(raw, 2) if len(cmps) != 1 || (len(cmps) == 1 && len(cmps[0]) != 4) { return "", "", "", nil, nil, false, fmt.Errorf("failed to extract partially defined predicate bound %q, got %v instead", raw, cmps) } id, tl, tu := cmps[0][1], cmps[0][2], cmps[0][3] pID = id // Lower bound processing. if strings.Index(tl, "?") != -1 { pLowerBoundAlias = tl } else { stl := strings.TrimSpace(tl) if stl != "" { ptl, err := time.Parse(time.RFC3339Nano, stl) if err != nil { return "", "", "", nil, nil, false, fmt.Errorf("predicate.Parse failed to parse time anchor %s in %s with error %v", tl, raw, err) } pLowerBound = &ptl } } // Lower bound processing. if strings.Index(tu, "?") != -1 { pUpperBoundAlias = tu } else { stu := strings.TrimSpace(tu) if stu != "" { ptu, err := time.Parse(time.RFC3339Nano, stu) if err != nil { return "", "", "", nil, nil, false, fmt.Errorf("predicate.Parse failed to parse time anchor %s in %s with error %v", tu, raw, err) } pUpperBound = &ptu } } if pLowerBound != nil && pUpperBound != nil { if pLowerBound.After(*pUpperBound) { lb, up := pLowerBound.Format(time.RFC3339Nano), pUpperBound.Format(time.RFC3339Nano) return "", "", "", nil, nil, false, fmt.Errorf("invalid time bound; lower bound %s after upper bound %s", lb, up) } } return pID, pLowerBoundAlias, pUpperBoundAlias, pLowerBound, pUpperBound, true, nil }
go
{ "resource": "" }
q12492
wherePredicateClause
train
func wherePredicateClause() ElementHook { var ( f ElementHook lastNopToken *lexer.Token ) f = func(st *Statement, ce ConsumedElement) (ElementHook, error) { if ce.IsSymbol() { return f, nil } tkn := ce.Token() c := st.WorkingClause() switch tkn.Type { case lexer.ItemPredicate: lastNopToken = nil if c.P != nil { return nil, fmt.Errorf("invalid predicate %s on graph clause since already set to %s", tkn.Text, c.P) } p, pID, pAnchorBinding, pTemporal, err := processPredicate(ce) if err != nil { return nil, err } c.P, c.PID, c.PAnchorBinding, c.PTemporal = p, pID, pAnchorBinding, pTemporal return f, nil case lexer.ItemPredicateBound: lastNopToken = nil if c.PLowerBound != nil || c.PUpperBound != nil || c.PLowerBoundAlias != "" || c.PUpperBoundAlias != "" { return nil, fmt.Errorf("invalid predicate bound %s on graph clause since already set to %s", tkn.Text, c.P) } pID, pLowerBoundAlias, pUpperBoundAlias, pLowerBound, pUpperBound, pTemp, err := processPredicateBound(ce) if err != nil { return nil, err } c.PID, c.PLowerBoundAlias, c.PUpperBoundAlias, c.PLowerBound, c.PUpperBound, c.PTemporal = pID, pLowerBoundAlias, pUpperBoundAlias, pLowerBound, pUpperBound, pTemp return f, nil case lexer.ItemBinding: if lastNopToken == nil { if c.PBinding != "" { return nil, fmt.Errorf("invalid binding %q loose after no valid modifier", tkn.Text) } c.PBinding = tkn.Text return f, nil } switch lastNopToken.Type { case lexer.ItemAs: if c.PAlias != "" { return nil, fmt.Errorf("AS alias binding for predicate has already being assigned on %v", st) } c.PAlias = tkn.Text case lexer.ItemID: if c.PIDAlias != "" { return nil, fmt.Errorf("ID alias binding for predicate has already being assigned on %v", st) } c.PIDAlias = tkn.Text case lexer.ItemAt: if c.PAnchorAlias != "" { return nil, fmt.Errorf("AT alias binding for predicate has already being assigned on %v", st) } c.PAnchorAlias = tkn.Text default: return nil, fmt.Errorf("binding %q found after invalid token %s", tkn.Text, lastNopToken) } lastNopToken = nil return f, nil } lastNopToken = tkn return f, nil } return f }
go
{ "resource": "" }
q12493
varAccumulator
train
func varAccumulator() ElementHook { var ( lastNopToken *lexer.Token f func(st *Statement, ce ConsumedElement) (ElementHook, error) ) f = func(st *Statement, ce ConsumedElement) (ElementHook, error) { if ce.IsSymbol() { return f, nil } tkn := ce.Token() p := st.WorkingProjection() switch tkn.Type { case lexer.ItemBinding: if p.Binding == "" { p.Binding = tkn.Text } else { if lastNopToken != nil && lastNopToken.Type == lexer.ItemAs { p.Alias = tkn.Text lastNopToken = nil st.AddWorkingProjection() } else { return nil, fmt.Errorf("invalid token %s for variable projection %s", tkn.Type, p) } } case lexer.ItemAs: lastNopToken = tkn case lexer.ItemSum, lexer.ItemCount: p.OP = tkn.Type case lexer.ItemDistinct: p.Modifier = tkn.Type case lexer.ItemComma: st.AddWorkingProjection() default: lastNopToken = nil } return f, nil } return f }
go
{ "resource": "" }
q12494
bindingsGraphChecker
train
func bindingsGraphChecker() ClauseHook { var f ClauseHook f = func(s *Statement, _ Symbol) (ClauseHook, error) { // Force working projection flush. s.AddWorkingProjection() bs := s.BindingsMap() for _, b := range s.InputBindings() { if _, ok := bs[b]; !ok { return nil, fmt.Errorf("specified binding %s not found in where clause, only %v bindings are available", b, s.Bindings()) } } return f, nil } return f }
go
{ "resource": "" }
q12495
groupByBindings
train
func groupByBindings() ElementHook { var f func(st *Statement, ce ConsumedElement) (ElementHook, error) f = func(st *Statement, ce ConsumedElement) (ElementHook, error) { if ce.IsSymbol() { return f, nil } tkn := ce.Token() if tkn.Type == lexer.ItemBinding { st.groupBy = append(st.groupBy, tkn.Text) } return f, nil } return f }
go
{ "resource": "" }
q12496
groupByBindingsChecker
train
func groupByBindingsChecker() ClauseHook { var f ClauseHook f = func(s *Statement, _ Symbol) (ClauseHook, error) { // Force working projection flush. var idxs map[int]bool idxs = make(map[int]bool) for _, gb := range s.groupBy { found := false for idx, prj := range s.projection { if gb == prj.Alias || (prj.Alias == "" && gb == prj.Binding) { if prj.OP != lexer.ItemError || prj.Modifier != lexer.ItemError { return nil, fmt.Errorf("GROUP BY %s binding cannot refer to an aggregation function", gb) } idxs[idx] = true found = true } } if !found { return nil, fmt.Errorf("invalid GROUP BY binging %s; available bindings %v", gb, s.OutputBindings()) } } for idx, prj := range s.projection { if idxs[idx] { continue } if len(s.groupBy) > 0 && prj.OP == lexer.ItemError { return nil, fmt.Errorf("Binding %q not listed on GROUP BY requires an aggregation function", prj.Binding) } if len(s.groupBy) == 0 && prj.OP != lexer.ItemError { s := prj.Alias if s == "" { s = prj.Binding } return nil, fmt.Errorf("Binding %q with aggregation %s function requires GROUP BY clause", s, prj.OP) } } return f, nil } return f }
go
{ "resource": "" }
q12497
orderByBindings
train
func orderByBindings() ElementHook { var f func(st *Statement, ce ConsumedElement) (ElementHook, error) f = func(st *Statement, ce ConsumedElement) (ElementHook, error) { if ce.IsSymbol() { return f, nil } tkn := ce.Token() switch tkn.Type { case lexer.ItemBinding: st.orderBy = append(st.orderBy, table.SortConfig{{Binding: tkn.Text}}...) case lexer.ItemAsc: st.orderBy[len(st.orderBy)-1].Desc = false case lexer.ItemDesc: st.orderBy[len(st.orderBy)-1].Desc = true } return f, nil } return f }
go
{ "resource": "" }
q12498
orderByBindingsChecker
train
func orderByBindingsChecker() ClauseHook { var f ClauseHook f = func(s *Statement, _ Symbol) (ClauseHook, error) { // Force working projection flush. outs := make(map[string]bool) for _, out := range s.OutputBindings() { outs[out] = true } seen, dups := make(map[string]bool), false for _, cfg := range s.orderBy { // Check there are no contradictions if b, ok := seen[cfg.Binding]; ok { if b != cfg.Desc { return nil, fmt.Errorf("inconsisting sorting direction for %q binding", cfg.Binding) } dups = true } else { seen[cfg.Binding] = cfg.Desc } // Check that the binding exist. if _, ok := outs[cfg.Binding]; !ok { return nil, fmt.Errorf("order by binding %q unknown; available bindings are %v", cfg.Binding, s.OutputBindings()) } } // If dups exist rewrite the order by SortConfig. if dups { s.orderBy = table.SortConfig{} for b, d := range seen { s.orderBy = append(s.orderBy, table.SortConfig{{Binding: b, Desc: d}}...) } } return f, nil } return f }
go
{ "resource": "" }
q12499
havingExpression
train
func havingExpression() ElementHook { var f func(st *Statement, ce ConsumedElement) (ElementHook, error) f = func(st *Statement, ce ConsumedElement) (ElementHook, error) { if ce.IsSymbol() { return f, nil } if ce.token.Type != lexer.ItemHaving { st.havingExpression = append(st.havingExpression, ce) } return f, nil } return f }
go
{ "resource": "" }