Substitute the variables in the given expression with the
values from the resolver

@param pResolver
@param pExpression
764018
public static String replaceVariables( final VariableResolver pResolver, final String pExpression, final String pOpen, final String pClose ) {
        final char[] open = pOpen.toCharArray();
        final char[] close = pClose.toCharArray();

        final StringBuilder out = new StringBuilder();
        StringBuilder sb = new StringBuilder();
        char[] last = null;
        int wo = 0;
        int wc = 0;
        int level = 0;
        for (char c : pExpression.toCharArray()) {
            if (c == open[wo]) {
                if (wc > 0) {
                    sb.append(close, 0, wc);
                }
                wc = 0;
                wo++;
                if (open.length == wo) {
                    // found open
                    if (last == open) {
                        out.append(open);
                    }
                    level++;
                    out.append(sb);
                    sb = new StringBuilder();
                    wo = 0;
                    last = open;
                }
            } else if (c == close[wc]) {
                if (wo > 0) {
                    sb.append(open, 0, wo);
                }
                wo = 0;
                wc++;
                if (close.length == wc) {
                    // found close
                    if (last == open) {
                        final String variable = pResolver.get(sb.toString());
                        if (variable != null) {
                            out.append(variable);
                        } else {
                            out.append(open);
                            out.append(sb);
                            out.append(close);
                        }
                    } else {
                        out.append(sb);
                        out.append(close);
                    }
                    sb = new StringBuilder();
                    level--;
                    wc = 0;
                    last = close;
                }
            } else {

                if (wo > 0) {
                    sb.append(open, 0, wo);
                }

                if (wc > 0) {
                    sb.append(close, 0, wc);
                }

                sb.append(c);

                wo = wc = 0;
            }
        }

        if (wo > 0) {
            sb.append(open, 0, wo);
        }

        if (wc > 0) {
            sb.append(close, 0, wc);
        }

        if (level > 0) {
            out.append(open);
        }
        out.append(sb);

        return out.toString();
    }
614886
@Override
  public void evaluate(DoubleSolution solution) {

    int numberOfVariables_ = solution.getNumberOfVariables();
    int numberOfObjectives_ = solution.getNumberOfObjectives();

    double[] x = new double[numberOfVariables_];
    double[] f = new double[numberOfObjectives_];

    for (int i = 0; i < numberOfVariables_; i++) {
      x[i] = solution.getVariableValue(i);
    }

    // evaluate J,y,sub1,sub2,sub3,sub4
    double[] y = new double[numberOfVariables_];
    for (int i = 0; i < numberOfVariables_; i++) {
      y[i] =
          x[i] - 2 * x[1] * Math.sin(2 * Math.PI * x[0] + (i + 1) * Math.PI / numberOfVariables_);
    }
    ArrayList<Integer> J1 = new ArrayList<Integer>();
    ArrayList<Integer> J2 = new ArrayList<Integer>();
    ArrayList<Integer> J3 = new ArrayList<Integer>();
    ArrayList<Integer> J4 = new ArrayList<Integer>();
    double sub1 = 0, sub2 = 0, sub3 = 0, sub4 = 0;
    for (int i = 4; i <= numberOfVariables_; i = i + 3) {
      J1.add(i);
      sub1 += Math.pow(y[i - 1], 2);
    }
    sub1 = 2 * sub1 / J1.size();
    for (int i = 5; i <= numberOfVariables_; i = i + 3) {
      J2.add(i);
      sub2 += Math.pow(y[i - 1], 2);
    }
    sub2 = 2 * sub2 / J2.size();
    for (int i = 3; i <= numberOfVariables_; i = i + 3) {
      J3.add(i);
      sub3 += Math.pow(y[i - 1], 2);
    }
    sub3 = 2 * sub3 / J3.size();
    for (int i = 4; i <= numberOfVariables_; i++) {
      J4.add(i);
      sub4 += Math.pow(y[i - 1], 2);
    }
    sub4 = 2 * sub4 / J4.size();
    // evaluate f1,f2,f3,f4,...m
    f[0] = Math.sin(Math.PI * x[0] / 2) + sub1;
    f[1] = Math.cos(Math.PI * x[0] / 2) * Math.sin(Math.PI * x[1] / 2) + sub2;
    f[2] = Math.cos(Math.PI * x[0] / 2) * Math.cos(Math.PI * x[1] / 2) + sub3;
    for (int i = 3; i < numberOfObjectives_; i++) {
      f[i] = Math.pow(f[0], 2) + Math.pow(f[1], 10) + Math.pow(f[2], 10) + sub4;
    }

    for (int i = 0; i < numberOfObjectives_; i++) {
      solution.setObjective(i, f[i]);
    }
  }
1278699
@Nonnull
  public static Value evalExpression(@Nonnull final String expression, @Nonnull final PreprocessorContext context) {
    try {
      final ExpressionTree tree = ExpressionParser.getInstance().parse(expression, context);
      return evalTree(tree, context);
    } catch (IOException unexpected) {
      throw context.makeException("[Expression]Wrong expression format detected [" + expression + ']', unexpected);
    }
  }
1232592
private static String resolve(final String value, final Resolver resolver) {
		StringBuilder builder = new StringBuilder();
		int position = 0;

		String prefix = resolver.getPrefix() + "{";
		String postfix = "}";

		for (int index = value.indexOf(prefix); index != -1; index = value.indexOf(prefix, position)) {
			builder.append(value, position, index);

			int start = index + 2;
			int end = value.indexOf(postfix, start);

			if (end == -1) {
				InternalLogger.log(Level.WARN, "Closing curly bracket is missing for '" + value + "'");
				return value;
			}

			String name = value.substring(start, end);
			if (name.length() == 0) {
				InternalLogger.log(Level.WARN, "Empty variable names cannot be resolved: " + value);
				return value;
			}

			String data = resolver.resolve(name);
			if (data == null) {
				InternalLogger.log(Level.WARN, "'" + name + "' could not be found in " + resolver.getName());
				return value;
			} else {
				builder.append(data);
			}

			position = end + 1;
		}

		builder.append(value, position, value.length());
		return builder.toString();
	}
242165
def solve_select(expr, vars):
    
    data, _ = __solve_for_repeated(expr.lhs, vars)
    key = solve(expr.rhs, vars).value

    try:
        results = [associative.select(d, key) for d in repeated.getvalues(data)]
    except (KeyError, AttributeError):
        # Raise a better exception for accessing a non-existent key.
        raise errors.EfilterKeyError(root=expr, key=key, query=expr.source)
    except (TypeError, ValueError):
        # Raise a better exception for what is probably a null pointer error.
        if vars.locals is None:
            raise errors.EfilterNoneError(
                root=expr, query=expr.source,
                message="Cannot select key %r from a null." % key)
        else:
            raise
    except NotImplementedError:
        raise errors.EfilterError(
            root=expr, query=expr.source,
            message="Cannot select keys from a non-associative value.")

    return Result(repeated.meld(*results), ())
89088
@SuppressWarnings("unchecked")
    public static <T> Expression<T> extract(Expression<T> expr) {
        if (expr != null) {
            final Class<?> clazz = expr.getClass();
            if (clazz == PathImpl.class || clazz == PredicateOperation.class || clazz == ConstantImpl.class) {
                return expr;
            } else {
                return (Expression<T>) expr.accept(ExtractorVisitor.DEFAULT, null);
            }
        } else {
            return null;
        }
    }
816716
private static Optional<Expression> tryResolveMissingExpression(PlanBuilder subPlan, Expression expression)
    {
        Expression rewritten = subPlan.rewrite(expression);
        if (rewritten != expression) {
            return Optional.of(rewritten);
        }
        return Optional.empty();
    }
877722
private PExp readApplicatorExpression() throws ParserException,
			LexException
	{
		PExp exp = readBasicExpression();
		boolean more = true;

		while (more)
		{
			LexToken token = lastToken();

			switch (token.type)
			{
				case BRA:
					// Either sequence(from, ..., to) or func(args) or map(key)
					// or mk_*(), is_*(), mu(), pre_*(), post_*(),
					// init_*() or inv_*()

					if (nextToken().is(VDMToken.KET))
					{
						if (exp instanceof AVariableExp)
						{
							AVariableExp ve = (AVariableExp) exp;
							String name = ve.getName().getName();

							if (name.startsWith("mk_"))
							{
								// a mk_TYPE() with no field values
								exp = readMkExpression(ve);
								break;
							}
						}

						exp = AstFactory.newAApplyExp(exp);
						nextToken();
					} else
					{
						if (exp instanceof AVariableExp)
						{
							AVariableExp ve = (AVariableExp) exp;
							String name = ve.getName().getName();

							if (name.equals("mu"))
							{
								exp = readMuExpression(ve);
								break;
							} else if (name.startsWith("mk_"))
							{
								exp = readMkExpression(ve);
								break;
							} else if (name.startsWith("is_"))
							{
								exp = readIsExpression(ve);
								break;
							} else if (name.equals("pre_"))
							{
								exp = readPreExpression(ve);
								break;
							} else if (name.equals("narrow_"))
							{
								if (Settings.release == Release.CLASSIC)
								{
									throwMessage(2303, "Narrow not available in VDM classic", ve.getName());
								} else
								{
									exp = readNarrowExpression(ve);
								}
								break;
							}
						}

						// So we're a function/operation call, a list subsequence or
						// a map index...

						PExp first = readExpression();

						if (lastToken().is(VDMToken.COMMA))
						{
							reader.push();

							if (nextToken().is(VDMToken.RANGE))
							{
								nextToken();
								checkFor(VDMToken.COMMA, 2120, "Expecting 'e1,...,e2' in subsequence");
								PExp last = readExpression();
								checkFor(VDMToken.KET, 2121, "Expecting ')' after subsequence");
								reader.unpush();
								exp = AstFactory.newASubseqExp(exp, first, last);
								break;
							}

							reader.pop(); // Not a subsequence then...
						}

						// OK, so read a (list, of, arguments)...

						List<PExp> args = new NodeList<PExp>(null);
						args.add(first);

						while (ignore(VDMToken.COMMA))
						{
							args.add(readExpression());
						}

						checkFor(VDMToken.KET, 2122, "Expecting ')' after function args");
						exp = AstFactory.newAApplyExp(exp, args);
					}
					break;

				case SEQ_OPEN:
					// Polymorphic function instantiation
					List<PType> types = new Vector<PType>();
					TypeReader tr = getTypeReader();

					nextToken();
					types.add(tr.readType());

					while (ignore(VDMToken.COMMA))
					{
						types.add(tr.readType());
					}

					checkFor(VDMToken.SEQ_CLOSE, 2123, "Expecting ']' after function instantiation");
					exp = AstFactory.newAFuncInstatiationExp(exp, types);
					break;

				case POINT:
					// Field selection by name or number
					switch (nextToken().type)
					{
						case NAME:
							if (dialect != Dialect.VDM_SL)
							{
								exp = AstFactory.newAFieldExp(exp, lastNameToken());
							} else
							{
								throwMessage(2030, "Expecting simple field identifier");
							}
							break;

						case IDENTIFIER:
							exp = AstFactory.newAFieldExp(exp, lastIdToken());
							break;

						case HASH:
							if (nextToken().isNot(VDMToken.NUMBER))
							{
								throwMessage(2031, "Expecting field number after .#");
							}

							LexIntegerToken num = (LexIntegerToken) lastToken();
							exp = AstFactory.newAFieldNumberExp(exp, num);
							break;

						default:
							throwMessage(2032, "Expecting field name");
					}

					nextToken();
					break;

				default:
					more = false;
					break;
			}
		}

		// If we've collected as many applicators as we can, but we're still
		// just a variable, this is a bare variable expression. In VDM++, these
		// are always qualified (ie. x refers to C`x where it was declared, not
		// an overriding version lower down).

		if (exp instanceof AVariableExp)
		{
			AVariableExp ve = (AVariableExp) exp;
			ve.setName(ve.getName().getExplicit(true));
		}

		// Combinator Family. Right grouping.
		LexToken token = lastToken();

		if (token.is(VDMToken.COMP))
		{
			nextToken();
			return AstFactory.newACompBinaryExp(exp, token, readApplicatorExpression());
		}

		if (token.is(VDMToken.STARSTAR))
		{
			nextToken();
			return AstFactory.newAStarStarBinaryExp(exp, token, readEvaluatorP6Expression());
		}

		return exp;
	}
598543
public Object resolveExpression(String expression) {
    if (StringUtils.isBlank(expression)) {
      return null;
    }

    interpreter.getContext().addResolvedExpression(expression.trim());

    try {
      String elExpression = EXPRESSION_START_TOKEN + expression.trim() + EXPRESSION_END_TOKEN;
      ValueExpression valueExp = expressionFactory.createValueExpression(elContext, elExpression, Object.class);
      Object result = valueExp.getValue(elContext);

      validateResult(result);

      return result;

    } catch (PropertyNotFoundException e) {
      interpreter.addError(new TemplateError(ErrorType.WARNING, ErrorReason.UNKNOWN, ErrorItem.PROPERTY, e.getMessage(), "", interpreter.getLineNumber(), interpreter.getPosition(), e,
          BasicTemplateErrorCategory.UNKNOWN, ImmutableMap.of("exception", e.getMessage())));
    } catch (TreeBuilderException e) {
      int position = interpreter.getPosition() + e.getPosition();
      // replacing the position in the string like this isn't great, but JUEL's parser does not allow passing in a starting position
      String errorMessage = StringUtils.substringAfter(e.getMessage(), "': ").replaceFirst("position [0-9]+", "position " + position);
      interpreter.addError(TemplateError.fromException(new TemplateSyntaxException(expression.substring(e.getPosition() - EXPRESSION_START_TOKEN.length()),
          "Error parsing '" + expression + "': " + errorMessage, interpreter.getLineNumber(), position, e)));
    }
    catch (ELException e) {
      if (e.getCause() != null && e.getCause() instanceof DeferredValueException) {
        throw (DeferredValueException) e.getCause();
      }
      if (e.getCause() != null && e.getCause() instanceof TemplateSyntaxException) {
        interpreter.addError(TemplateError.fromException((TemplateSyntaxException) e.getCause()));
      }
      else if (e.getCause() != null && e.getCause() instanceof InvalidInputException) {
        interpreter.addError(TemplateError.fromInvalidInputException((InvalidInputException) e.getCause()));
      }
      else if (e.getCause() != null && e.getCause() instanceof InvalidArgumentException) {
        interpreter.addError(TemplateError.fromInvalidArgumentException((InvalidArgumentException) e.getCause()));
      }
      else {
        interpreter.addError(TemplateError.fromException(new TemplateSyntaxException(expression, e.getMessage(), interpreter.getLineNumber(), e)));
      }
    }
    catch (DisabledException e) {
      interpreter.addError(new TemplateError(ErrorType.FATAL, ErrorReason.DISABLED, ErrorItem.FUNCTION, e.getMessage(), expression, interpreter.getLineNumber(), interpreter.getPosition(), e));
    } catch (UnknownTokenException e) {
      // Re-throw the exception because you only get this when the config failOnUnknownTokens is enabled.
      throw e;
    } catch (DeferredValueException e) {
      // Re-throw so that it can be handled in JinjavaInterpreter
      throw e;
    } catch (InvalidInputException e) {
      interpreter.addError(TemplateError.fromInvalidInputException(e));
    } catch (InvalidArgumentException e) {
      interpreter.addError(TemplateError.fromInvalidArgumentException(e));
    } catch (Exception e) {
      interpreter.addError(TemplateError.fromException(new InterpretException(
          String.format("Error resolving expression [%s]: " + getRootCauseMessage(e), expression), e, interpreter.getLineNumber(), interpreter.getPosition())));
    }

    return null;
  }
283762
@Override
    public boolean beforeSolve(ReconfigurationProblem p) throws SchedulerException {
        for (VM vm : source.getMapping().getAllVMs()) {
            int vmId = p.getVM(vm);
            int v = getVMAllocation(vmId);
            if (v < 0) {
                int prevUsage = rc.getConsumption(vm);
                minVMAllocation(vmId, prevUsage);
            }

        }

        ChocoView v = rp.getView(Packing.VIEW_ID);
        if (v == null) {
            throw SchedulerModelingException.missingView(rp.getSourceModel(), Packing.VIEW_ID);
        }

        IntVar[] host = new IntVar[p.getFutureRunningVMs().size()];
        int[] demand = new int[host.length];
        int i = 0;
        for (VM vm : p.getFutureRunningVMs()) {
            host[i] = rp.getVMAction(vm).getDSlice().getHoster();
            demand[i] = getVMAllocation(p.getVM(vm));
            i++;
        }
        ((Packing) v).addDim(rc.getResourceIdentifier(),
                virtRcUsage,
                demand,
                host);

        return linkVirtualToPhysicalUsage();
    }
618028
public Object evaluate(Object pContext,
                           VariableResolver pResolver,
                           Map functions,
                           String defaultPrefix,
                           Logger pLogger)
            throws ELException {
        if (pResolver == null) {
            return null;
        } else {
            return pResolver.resolveVariable(mName, pContext);
        }
    }
112645
private String resolveExpressionString(final String unresolvedString) throws OperationFailedException {

        // parseAndResolve should only be providing expressions with no leading or trailing chars
        assert unresolvedString.startsWith("${") && unresolvedString.endsWith("}");

        // Default result is no change from input
        String result = unresolvedString;

        ModelNode resolveNode = new ModelNode(new ValueExpression(unresolvedString));

        // Try plug-in resolution; i.e. vault
        resolvePluggableExpression(resolveNode);

        if (resolveNode.getType() == ModelType.EXPRESSION ) {
            // resolvePluggableExpression did nothing. Try standard resolution
            String resolvedString = resolveStandardExpression(resolveNode);
            if (!unresolvedString.equals(resolvedString)) {
                // resolveStandardExpression made progress
                result = resolvedString;
            } // else there is nothing more we can do with this string
        } else {
            // resolvePluggableExpression made progress
            result = resolveNode.asString();
        }

        return result;
    }
826487
private static String resolveVariableExpression(final String value, final int last,
      final JexlEngine jexl) {
    final int lastIndex = value.lastIndexOf("$(", last);
    if (lastIndex == -1) {
      return value;
    }

    // Want to check that everything is well formed, and that
    // we properly capture $( ...(...)...).
    int bracketCount = 0;
    int nextClosed = lastIndex + 2;
    for (; nextClosed < value.length(); ++nextClosed) {
      if (value.charAt(nextClosed) == '(') {
        bracketCount++;
      } else if (value.charAt(nextClosed) == ')') {
        bracketCount--;
        if (bracketCount == -1) {
          break;
        }
      }
    }

    if (nextClosed == value.length()) {
      throw new IllegalArgumentException("Expression " + value
          + " not well formed.");
    }

    final String innerExpression = value.substring(lastIndex + 2, nextClosed);
    Object result = null;
    try {
      final Expression e = jexl.createExpression(innerExpression);
      result = e.evaluate(new MapContext());
    } catch (final JexlException e) {
      throw new IllegalArgumentException("Expression " + value
          + " not well formed. " + e.getMessage(), e);
    }

    if (result == null) {
      // for backward compatibility it is best to return value
      return value;
    }

    final String newValue =
        value.substring(0, lastIndex) + result.toString()
            + value.substring(nextClosed + 1);
    return resolveVariableExpression(newValue, lastIndex, jexl);
  }
102953
public Object resolveVariable(String pName) throws ELException {
		ELContext ctx = this.getELContext();
		return ctx.getELResolver().getValue(ctx, null, pName);
	}
358158
@Override
	public PExp caseAExistsExp(AExistsExp node, Substitution question)
			throws AnalysisException
	{
		PExp sub = node.getPredicate().clone().apply(main, question);
		node.setPredicate(sub.clone());
		return node;

	}
121897
@Nullable
    protected <T> T resolveExpression(String context, String expression, Class<T> type) {
        if (environment.containsProperty(expression)) {
            return environment.getProperty(expression, type)
                    .orElseThrow(() ->
                            new ConfigurationException("Could not resolve expression: [" + expression + "] in placeholder ${" + context + "}"));
        }
        if (NameUtils.isEnvironmentName(expression)) {
            String envVar = System.getenv(expression);
            if (StringUtils.isNotEmpty(envVar)) {
                return conversionService.convert(envVar, type)
                        .orElseThrow(() ->
                                new ConfigurationException("Could not resolve expression: [" + expression + "] in placeholder ${" + context + "}"));
            }
        }
        return null;
    }
1180915
public static SearchExpressionResolver findResolver(final String expression) {
        SearchExpressionResolver resolver = null;

        if (expression.startsWith(SearchExpressionConstants.KEYWORD_PREFIX)) {
            // check if it's an expression with parameter
            int parenthesisPosition = expression.indexOf('(');
            if (parenthesisPosition > 0) {
                String expressionWithoutParam = expression.substring(0, parenthesisPosition);
                resolver = RESOLVER_MAPPING.get(expressionWithoutParam);
            }
            else {
                resolver = RESOLVER_MAPPING.get(expression);
            }
        }
        else {
            // if it's not a keyword, just delegate it to JSF
            resolver = FIND_COMPONENT_EXPRESSION_RESOLVER;
        }

        if (resolver == null) {
            throw new FacesException("No SearchExpressionResolver available for expression \"" + expression + "\"");
        }

        return resolver;
    }