// eval the expression
191060
func eval(e *Expr, getter VarGetter, node ast.Expr) (Value, error) {
	switch n := node.(type) {
	case *ast.Ident:
		if getter == nil {
			return e.pool.onVarMissing(n.Name)
		}
		val, ok := getter.GetVar(n.Name)
		if !ok {
			return e.pool.onVarMissing(n.Name)
		}
		return val, nil

	case *ast.BasicLit:
		switch n.Kind {
		case token.INT:
			i, err := strconv.ParseInt(n.Value, 10, 64)
			if err != nil {
				return Zero(), err
			}
			return Int(i), nil
		case token.FLOAT:
			f, err := strconv.ParseFloat(n.Value, 64)
			if err != nil {
				return Zero(), err
			}
			return Float(f), nil
		case token.CHAR, token.STRING:
			s, err := strconv.Unquote(n.Value)
			if err != nil {
				return Zero(), err
			}
			return String(s), nil
		default:
			return Zero(), fmt.Errorf("unsupported token: %s(%v)", n.Value, n.Kind)
		}

	case *ast.ParenExpr:
		return eval(e, getter, n.X)

	case *ast.CallExpr:
		args := make([]Value, 0, len(n.Args))
		for _, arg := range n.Args {
			if val, err := eval(e, getter, arg); err != nil {
				return Zero(), err
			} else {
				args = append(args, val)
			}
		}
		if fnIdent, ok := n.Fun.(*ast.Ident); ok {
			if fn, ok := e.pool.fn(fnIdent.Name); !ok {
				return Zero(), fmt.Errorf("undefined function `%v`", fnIdent.Name)
			} else {
				return fn(args...)
			}
		}
		return Zero(), fmt.Errorf("unexpected func type: %T", n.Fun)

	case *ast.UnaryExpr:
		switch n.Op {
		case token.ADD:
			return eval(e, getter, n.X)
		case token.SUB:
			x, err := eval(e, getter, n.X)
			if err == nil {
				x, err = Zero().Sub(x)
			}
			return x, err
		case token.NOT:
			x, err := eval(e, getter, n.X)
			if err == nil {
				x = x.Not()
			}
			return x, err
		default:
			return Zero(), fmt.Errorf("unsupported unary op: %v", n.Op)
		}

	case *ast.BinaryExpr:
		x, err := eval(e, getter, n.X)
		if err != nil {
			return Zero(), err
		}
		y, err := eval(e, getter, n.Y)
		if err != nil {
			return Zero(), err
		}
		switch n.Op {
		case token.ADD:
			return x.Add(y)
		case token.SUB:
			return x.Sub(y)
		case token.MUL:
			return x.Mul(y)
		case token.QUO:
			return x.Quo(y)
		case token.REM:
			return x.Rem(y)
		case token.XOR:
			return x.Pow(y)
		case token.LAND:
			return x.And(y), nil
		case token.LOR:
			return x.Or(y), nil
		case token.EQL:
			return x.Eq(y)
		case token.NEQ:
			return x.Ne(y)
		case token.GTR:
			return x.Gt(y)
		case token.GEQ:
			return x.Ge(y)
		case token.LSS:
			return x.Lt(y)
		case token.LEQ:
			return x.Le(y)
		default:
			return Zero(), fmt.Errorf("unexpected binary operator: %v", n.Op)
		}

	default:
		return Zero(), fmt.Errorf("unexpected node type %T", n)
	}
}
1076636
func (f stringLikeFunc) evaluate(values map[string][]string) bool {
	requestValue, ok := values[http.CanonicalHeaderKey(f.k.Name())]
	if !ok {
		requestValue = values[f.k.Name()]
	}

	fvalues := f.values.ApplyFunc(substFuncFromValues(values))

	for _, v := range requestValue {
		if !fvalues.FuncMatch(wildcard.Match, v).IsEmpty() {
			return true
		}
	}

	return false
}
737915
func (a Anomalyzer) Eval() float64 {
	threshold := a.Conf.referenceSize + a.Conf.ActiveSize
	if a.Conf.Delay && len(a.Data) < threshold {
		return 0.0
	}
	probmap := make(map[string]float64)
	for _, method := range a.Conf.Methods {

		algorithm := Algorithms[method]
		prob := cap(algorithm(a.Data, *a.Conf), 0, 1)
		if prob != NA {
			// if highrank and lowrank methods exist then only listen to
			// the max of either
			if method == "highrank" || method == "lowrank" {
				if math.IsNaN(probmap["rank"]) {
					probmap["rank"] = 0
				}
				probmap["rank"] = math.Max(probmap["rank"], prob)
			} else {
				probmap[method] = prob
			}
		}
	}

	probs := make(govector.Vector, 0, len(probmap))
	weights := make(govector.Vector, 0, len(probmap))

	for method, prob := range probmap {
		if method == "magnitude" && prob < a.Conf.Sensitivity {
			return 0.0
		}
		probs = append(probs, prob)
		weights = append(weights, a.getWeight(method, prob))
	}

	// ignore the error since we force the length of probs
	// and the weights to be equal
	weighted, _ := probs.WeightedMean(weights)

	// if all the weights are zero, then our weighted mean
	// function attempts to divide by zero which returns a
	// NaN. we'd like it to return 0.
	if math.IsNaN(weighted) {
		weighted = 0
	}

	return weighted
}
1350433
func (remote *RemoteDebugger) EvaluateWrap(expr string) (interface{}, error) {
	expr = fmt.Sprintf("(function(){%v})()", expr)
	return remote.Evaluate(expr)
}
528238
func Eval(ctx context.Context, usage string, args []string, store storage.Store, bulkSize int) int {
	if len(args) < 3 {
		log.Printf("[ERROR] Missing required file path and/or graph names.\n\n%s", usage)
		return 2
	}
	graphs, path := strings.Split(args[len(args)-2], ","), args[len(args)-1]
	f, err := os.Create(path)
	if err != nil {
		log.Printf("[ERROR] Failed to open target file %q with error %v.\n\n", path, err)
		return 2
	}
	defer f.Close()
	var sgs []storage.Graph
	for _, gr := range graphs {
		g, err := store.Graph(ctx, gr)
		if err != nil {
			log.Printf("[ERROR] Failed to retrieve graph %q with error %v.\n\n", gr, err)
			return 2
		}
		sgs = append(sgs, g)
	}

	cnt := 0
	var errs []error
	var mu sync.Mutex
	chn := make(chan *triple.Triple, bulkSize)
	for _, vg := range sgs {
		go func(g storage.Graph) {
			err := g.Triples(ctx, storage.DefaultLookup, chn)
			mu.Lock()
			errs = append(errs, err)
			mu.Unlock()
		}(vg)
	}

	for t := range chn {
		if _, err := f.WriteString(t.String() + "\n"); err != nil {
			log.Printf("[ERROR] Failed to write triple %s to file %q, %v.\n\n", t.String(), path, err)
			return 2
		}
		cnt++
	}
	for _, err := range errs {
		if err != nil {
			log.Printf("[ERROR] Failed to retrieve triples with error %v.\n\n", err)
			return 2
		}
	}

	fmt.Printf("Successfully written %d triples to file %q.\nTriples exported from graphs:\n\t- %s\n", cnt, path, strings.Join(graphs, "\n\t- "))
	return 0
}
1152105
func (e *SelectStatement) Eval(input, output Record) (Record, error) {
	ok, err := e.isPassingWhereClause(input)
	if err != nil || !ok {
		// Either error or row did not pass where clause
		return nil, err
	}

	if e.selectAST.Expression.All {
		// Return the input record for `SELECT * FROM
		// .. WHERE ..`

		// Update count of records output.
		if e.limitValue > -1 {
			e.outputCount++
		}

		return input, nil
	}

	for i, expr := range e.selectAST.Expression.Expressions {
		v, err := expr.evalNode(input)
		if err != nil {
			return nil, err
		}

		// Pick output column names
		if expr.As != "" {
			output.Set(expr.As, v)
		} else if comp, ok := getLastKeypathComponent(expr.Expression); ok {
			output.Set(comp, v)
		} else {
			output.Set(fmt.Sprintf("_%d", i+1), v)
		}
	}

	// Update count of records output.
	if e.limitValue > -1 {
		e.outputCount++
	}

	return output, nil
}
161300
func (scope *EvalScope) EvalExpression(expr string, cfg LoadConfig) (*Variable, error) {
	t, err := parser.ParseExpr(expr)
	if err != nil {
		return nil, err
	}

	ev, err := scope.evalToplevelTypeCast(t, cfg)
	if ev == nil && err == nil {
		ev, err = scope.evalAST(t)
	}
	if err != nil {
		return nil, err
	}
	ev.loadValue(cfg)
	if ev.Name == "" {
		ev.Name = expr
	}
	return ev, nil
}
1025256
func (col *CorrelatedColumn) Eval(row []types.Datum, _ context.Context) (types.Datum, error) {
	return *col.Data, nil
}
1312384
func (m *rewrite) eval(arg expr.Node) (value.Value, bool, bool) {
	switch arg := arg.(type) {
	case *expr.NumberNode, *expr.StringNode:
		val, ok := vm.Eval(nil, arg)
		return val, ok, false
	case *expr.IdentityNode:
		if arg.IsBooleanIdentity() {
			return value.NewBoolValue(arg.Bool()), true, false
		}
		return value.NewStringValue(arg.Text), true, true
	case *expr.ArrayNode:
		val, ok := vm.Eval(nil, arg)
		return val, ok, false
	}
	return nil, false, false
}
210423
func EvalExpr(node ast.Node) (val data.Value, err error) {
	state := &state{wr: ioutil.Discard}
	defer state.errRecover(&err)
	state.walk(node)
	return state.val, nil
}
844542
func (csf *CubicSplineFunction) Eval(x float64) float64 {
	if !csf.points.XInRange(x) {
		panic("X out of range!")
	}
	idx := csf.points.SearchNextIndex(x)
	if idx >= len(csf.polynomials) {
		idx = len(csf.polynomials) - 1
	}
	return csf.polynomials[idx].Eval(x - csf.points.XAt(idx))
}
738405
func (env *Zlisp) EvalExpressions(xs []Sexp) (Sexp, error) {
	//P("inside EvalExpressions with env %p: xs[0] = %s", env, xs[0].SexpString(0))
	err := env.LoadExpressions(xs)
	if err != nil {
		return SexpNull, err
	}
	return env.Run()
}
931441
func (c *cmdable) Eval(script string, keys []string, args ...interface{}) *Cmd {
	cmdArgs := make([]interface{}, 3+len(keys), 3+len(keys)+len(args))
	cmdArgs[0] = "eval"
	cmdArgs[1] = script
	cmdArgs[2] = len(keys)
	for i, key := range keys {
		cmdArgs[3+i] = key
	}
	cmdArgs = appendArgs(cmdArgs, args)
	cmd := NewCmd(cmdArgs...)
	c.process(cmd)
	return cmd
}
959597
func REPL(env *eval.SimpleEnv) {

	var err error

	// A place to store result values of expressions entered
	// interactively
	results := make([]interface{}, 0, 10)
	env.Vars["results"] = reflect.ValueOf(&results)

	exprs := 0
	in := bufio.NewReader(os.Stdin)
	line, err := readline("go> ", in)
	for line != "quit" {
		if err != nil {
			if err == io.EOF { break }
			panic(err)
		}
		if expr, err := parser.ParseExpr(line); err != nil {
			if pair := eval.FormatErrorPos(line, err.Error()); len(pair) == 2 {
				fmt.Println(pair[0])
				fmt.Println(pair[1])
			}
			fmt.Printf("parse error: %s\n", err)
		} else if cexpr, errs := eval.CheckExpr(expr, env); len(errs) != 0 {
			for _, cerr := range errs {
				fmt.Printf("check error: %v\n", cerr)
			}
		} else if vals, err := eval.EvalExpr(cexpr, env); err != nil {
			fmt.Printf("panic: %s\n", err)
		} else if len(vals) == 0 {
			fmt.Printf("Kind=Slice\nvoid\n")
		} else if len(vals) == 1 {
			value := (vals)[0]
			if value.IsValid() {
				kind := value.Kind().String()
				typ  := value.Type().String()
				if typ != kind {
					fmt.Printf("Kind = %v\n", kind)
					fmt.Printf("Type = %v\n", typ)
				} else {
					fmt.Printf("Kind = Type = %v\n", kind)
				}
				fmt.Printf("results[%d] = %s\n", exprs, eval.Inspect(value))
				exprs += 1
				results = append(results, (vals)[0].Interface())
			} else {
				fmt.Printf("%s\n", value)
			}
		} else {
			fmt.Printf("Kind = Multi-Value\n")
			size := len(vals)
			for i, v := range vals {
				fmt.Printf("%s", eval.Inspect(v))
				if i < size-1 { fmt.Printf(", ") }
			}
			fmt.Printf("\n")
			exprs += 1
			results = append(results, vals)
		}

		line, err = readline("go> ", in)
	}
}
472397
func (rs Rules) Eval(ctx context.Context, e *executor.Event, err error, ch Chain) (context.Context, *executor.Event, error) {
	return ch(rs.Chain()(ctx, e, err))
}
71159
func evalBool(exprs []expression.Expression, row []types.Datum, ctx *stmtctx.StatementContext) (bool, error) {
	for _, expr := range exprs {
		data, err := expr.Eval(chunk.MutRowFromDatums(row).ToRow())
		if err != nil {
			return false, errors.Trace(err)
		}
		if data.IsNull() {
			return false, nil
		}

		isBool, err := data.ToBool(ctx)
		if err != nil {
			return false, errors.Trace(err)
		}
		if isBool == 0 {
			return false, nil
		}
	}
	return true, nil
}
464349
func (expr *Expr) Evaluate(root NodeNavigator) interface{} {
	val := expr.q.Evaluate(iteratorFunc(func() NodeNavigator { return root }))
	switch val.(type) {
	case query:
		return &NodeIterator{query: expr.q.Clone(), node: root}
	}
	return val
}