Substitute symbols or (sub-)expressions with the given replacements and
    re-evalute the result

    Args:
        expr: The expression in which to perform the substitution
        var_map (dict): The substitution dictionary.
481609
def substitute(expr, var_map):
    
    try:
        if isinstance(expr, SympyBasic):
            sympy_var_map = {
                k: v for (k, v) in var_map.items()
                if isinstance(k, SympyBasic)}
            return expr.subs(sympy_var_map)
        else:
            return expr.substitute(var_map)
    except AttributeError:
        if expr in var_map:
            return var_map[expr]
        return expr
1347642
public Expression2 substitute(Expression2 value, Expression2 replacement) {
    if (this.equals(value)) {
      return replacement;
    } else if (this.isConstant()) {
      return this;
    } else {
      List<Expression2> newSubexpressions = Lists.newArrayList();
      for (Expression2 sub : subexpressions) {
        newSubexpressions.add(sub.substitute(value, replacement));
      }
      return Expression2.nested(newSubexpressions);
    }
  }
749040
def map_expression(expr):
    
    if callable(expr):
        return expr

    # first, split the string on commas to get key/value bits
    # XXX: should we allow people to escape commas here?
    # XXX: what's a good test case for commas in an expression?
    bits = expr.split(',')
    # then, split each bit on '=' to get the key and expression strings
    exprs = [
        (bit[0].strip(), len(bit) > 1 and bit[1].strip() or '')
        for bit in [bit.split('=') for bit in bits]
    ]
    # then, convert those into a dict where each key indicates an expression()
    keys = [
        (k[0], k[1] and expression(k[1]) or None)
        for k in exprs
    ]
    key_dict = dict(keys)
    def _expr(data, **kwargs):
        vals = {}
        for key, expr in key_dict.items():
            # the SQL * selects all keys
            if key == '*':
                vals.update(data)
                continue
            # and if there's no expression, just grab the named key
            elif not expr:
                vals[key] = data.get(key)
                continue
            # otherwise, execute the expression
            # XXX: this will throw an exception if the named key doesn't exist
            # in the data dict!
            else:
                vals[key] = expr(data, **kwargs)
        return vals
    _expr.__doc__ = expr
    _expr.keys = map(lambda k: k[0], keys)
    return _expr
1351235
function evalExpr(expr, data, owner) {
    if (expr.value != null) {
        return expr.value;
    }

    var value;

    switch (expr.type) {
        case ExprType.UNARY:
            value = evalExpr(expr.expr, data, owner);
            switch (expr.operator) {
                case 33:
                    value = !value;
                    break;

                case 45:
                    value = 0 - value;
                    break;
            }
            return value;

        case ExprType.BINARY:
            value = evalExpr(expr.segs[0], data, owner);
            var rightValue = evalExpr(expr.segs[1], data, owner);

            /* eslint-disable eqeqeq */
            switch (expr.operator) {
                case 37:
                    value = value % rightValue;
                    break;

                case 43:
                    value = value + rightValue;
                    break;

                case 45:
                    value = value - rightValue;
                    break;

                case 42:
                    value = value * rightValue;
                    break;

                case 47:
                    value = value / rightValue;
                    break;

                case 60:
                    value = value < rightValue;
                    break;

                case 62:
                    value = value > rightValue;
                    break;

                case 76:
                    value = value && rightValue;
                    break;

                case 94:
                    value = value != rightValue;
                    break;

                case 121:
                    value = value <= rightValue;
                    break;

                case 122:
                    value = value == rightValue;
                    break;

                case 123:
                    value = value >= rightValue;
                    break;

                case 155:
                    value = value !== rightValue;
                    break;

                case 183:
                    value = value === rightValue;
                    break;

                case 248:
                    value = value || rightValue;
                    break;

            }
            /* eslint-enable eqeqeq */
            return value;

        case ExprType.TERTIARY:
            return evalExpr(
                expr.segs[evalExpr(expr.segs[0], data, owner) ? 1 : 2],
                data,
                owner
            );


        case ExprType.ARRAY:
            value = [];
            for (var i = 0, l = expr.items.length; i < l; i++) {
                var item = expr.items[i];
                var itemValue = evalExpr(item.expr, data, owner);

                if (item.spread) {
                    itemValue && (value = value.concat(itemValue));
                }
                else {
                    value.push(itemValue);
                }
            }
            return value;

        case ExprType.OBJECT:
            value = {};
            for (var i = 0, l = expr.items.length; i < l; i++) {
                var item = expr.items[i];
                var itemValue = evalExpr(item.expr, data, owner);

                if (item.spread) {
                    itemValue && extend(value, itemValue);
                }
                else {
                    value[evalExpr(item.name, data, owner)] = itemValue;
                }
            }
            return value;

        case ExprType.ACCESSOR:
            return data.get(expr);


        case ExprType.INTERP:
            value = evalExpr(expr.expr, data, owner);

            if (owner) {
                for (var i = 0, l = expr.filters.length; i < l; i++) {
                    var filter = expr.filters[i];
                    var filterName = filter.name.paths[0].value;

                    if (owner.filters[filterName]) {
                        value = owner.filters[filterName].apply(
                            owner,
                            [value].concat(evalArgs(filter.args, data, owner))
                        );
                    }
                    else if (DEFAULT_FILTERS[filterName]) {
                        value = DEFAULT_FILTERS[filterName](value);
                    }
                }
            }

            if (value == null) {
                value = '';
            }

            return value;

        case ExprType.CALL:
            if (owner && expr.name.type === ExprType.ACCESSOR) {
                var method = owner;
                var pathsLen = expr.name.paths.length;

                for (var i = 0; method && i < pathsLen; i++) {
                    method = method[evalExpr(expr.name.paths[i], data, owner)];
                }

                if (method) {
                    value = method.apply(owner, evalArgs(expr.args, data, owner));
                }
            }

            break;

        /* eslint-disable no-redeclare */
        case ExprType.TEXT:
            var buf = '';
            for (var i = 0, l = expr.segs.length; i < l; i++) {
                var seg = expr.segs[i];
                buf += seg.value || evalExpr(seg, data, owner);
            }
            return buf;
    }

    return value;
}
1156609
def __replace_base_variables(text, req_len, idx):
        
        return text \
            .replace("{i}", str(idx + 1)) \
            .replace("{n}", str(req_len))
1321465
public static Expression replace(Expression expression, String substring, String repl) {
        return x("REPLACE(" + expression.toString() + ", \"" + substring + "\", \"" + repl + "\")");
    }
331729
def substitute_variables(command, level, name, value, target=None, **kwargs):
    """"""
    rule = kwargs.get('rule', {})
    rule_value = rule.get('value', '') if rule else ''
    substitutes = {
        '${level}': str(level),
        '${target}': str(target),
        '${name}': '"' + str(name) + '"',
        '${value}': str(value),
        '${limit_value}': str(rule_value),
    }

    result = command
    for pattern, value in substitutes.items():
        result = result.replace(pattern, value)

    return result
562318
def var_replace(self, text):
        
        result = text
        for var in self._vardict:
            result = result.replace("@{}".format(var), self._vardict[var])
        return result
172785
def substitute(self, values: Dict[str, Any]) -> str:
        
        return self.template.substitute(values)
1280705
def tokenize(expr):
    
    tokens = []
    escape = False
    cur_token = ''

    for c in expr:
        if escape == True:
            cur_token += c
            escape = False
        else:
            if c == '\\':
                # Next char will be escaped
                escape = True
                continue
            elif c == '[':
                # Next token is of type index (list)
                if len(cur_token) > 0:
                    tokens.append(cur_token)
                    cur_token = ''
            elif c == ']':
                # End of index token. Next token defaults to a key (dict)
                if len(cur_token) > 0:
                    tokens.append(int(cur_token))
                    cur_token = ''
            elif c == '.':
                # End of key token. Next token defaults to a key (dict)
                if len(cur_token) > 0:
                    tokens.append(cur_token)
                    cur_token = ''
            else:
                # Append char to token name
                cur_token += c
    if len(cur_token) > 0:
        tokens.append(cur_token)

    return tokens
1008730
def substitute(self, text, subvars={},
                   trim_leading_lf=None, checkmissing=None):
        ''''''

        if trim_leading_lf is None:
            trim_leading_lf = self.trim_leading_lf
        if checkmissing is None:
            checkmissing = self.checkmissing

        # handle repititions
        while True:
            subidx = text.find(self.start_rep_token)
            if subidx == -1:
                break
            endidx = self.find_rep_end(text[subidx:])
            if endidx == -1:
                raise MAVParseError("missing end macro in %s" % text[subidx:])
            part1 = text[0:subidx]
            part2 = text[subidx+len(self.start_rep_token):subidx+(endidx-len(self.end_rep_token))]
            part3 = text[subidx+endidx:]
            a = part2.split(':')
            field_name = a[0]
            rest = ':'.join(a[1:])
            v = None
            if isinstance(subvars, dict):
                v = subvars.get(field_name, None)
            else:
                v = getattr(subvars, field_name, None)
            if v is None:
                raise MAVParseError('unable to find field %s' % field_name)
            t1 = part1
            for f in v:
                t1 += self.substitute(rest, f, trim_leading_lf=False, checkmissing=False)
            if len(v) != 0 and t1[-1] in ["\n", ","]:
                t1 = t1[:-1]
            t1 += part3
            text = t1
                
        if trim_leading_lf:
            if text[0] == '\n':
                text = text[1:]
        while True:
            idx = text.find(self.start_var_token)
            if idx == -1:
                return text
            endidx = text[idx:].find(self.end_var_token)
            if endidx == -1:
                raise MAVParseError('missing end of variable: %s' % text[idx:idx+10])
            varname = text[idx+2:idx+endidx]
            if isinstance(subvars, dict):
                if not varname in subvars:
                    if checkmissing:
                        raise MAVParseError("unknown variable in '%s%s%s'" % (
                            self.start_var_token, varname, self.end_var_token))
                    return text[0:idx+endidx] + self.substitute(text[idx+endidx:], subvars,
                                                                trim_leading_lf=False, checkmissing=False)
                value = subvars[varname]
            else:
                value = getattr(subvars, varname, None)
                if value is None:
                    if checkmissing:
                        raise MAVParseError("unknown variable in '%s%s%s'" % (
                            self.start_var_token, varname, self.end_var_token))
                    return text[0:idx+endidx] + self.substitute(text[idx+endidx:], subvars,
                                                                trim_leading_lf=False, checkmissing=False)
            text = text.replace("%s%s%s" % (self.start_var_token, varname, self.end_var_token), str(value))
        return text
1012512
function _regExpOrGTFO(expr){
  var exp;

  if(typeof expr === 'string'){
    exp = new RegExp('^'+expr+'$');
  } else if (expr instanceof RegExp){
    exp = expr;
  } else {
    throw new Error('Needle must be either a string or a RegExp');
  }

  return exp;
}
1230545
def _expr2code(self, arg_list, expr):
        """"""
        code = lambdastr(arg_list, expr)
        function_code = code.split(':')[1].strip()
        #for arg in arg_list:
        #    function_code = function_code.replace(arg.name, 'self.'+arg.name)

        return function_code
393743
def substitute(self, text, subvars={},
                   checkmissing=None):
        ''''''

        if checkmissing is None:
            checkmissing = self.checkmissing

        while True:
            idx = text.find(self.start_var_token)
            if idx == -1:
                return text
            endidx = text[idx:].find(self.end_var_token)
            if endidx == -1:
                raise MAVSubstituteError('missing end of variable: %s' % text[idx:idx+10])
            varname = text[idx+2:idx+endidx]
            fullvar = varname

            # allow default value after a :
            def_value = None
            colon = varname.find(':')
            if colon != -1:
                def_value = varname[colon+1:]
                varname = varname[:colon]

            if varname in subvars:
                value = subvars[varname]
            elif def_value is not None:
                value = def_value
            elif checkmissing:
                raise MAVSubstituteError("unknown variable in '%s%s%s'" % (
                    self.start_var_token, varname, self.end_var_token))
            else:
                return text[0:idx+endidx] + self.substitute(text[idx+endidx:], subvars, checkmissing=False)
            text = text.replace("%s%s%s" % (self.start_var_token, fullvar, self.end_var_token), str(value))
        return text
392374
def varReplace(basedir, raw, vars, lookup_fatal=True, depth=0, expand_lists=False):
    '''  '''
    # this code originally from yum

    if (depth > 20):
        raise errors.AnsibleError("template recursion depth exceeded")

    done = [] # Completed chunks to return

    while raw:
        m = _varFind(basedir, raw, vars, lookup_fatal, depth)
        if not m:
            done.append(raw)
            break

        # Determine replacement value (if unknown variable then preserve
        # original)

        replacement = m['replacement']
        if expand_lists and isinstance(replacement, (list, tuple)):
            replacement = ",".join(replacement)
        if isinstance(replacement, (str, unicode)):
            replacement = varReplace(basedir, replacement, vars, lookup_fatal, depth=depth+1, expand_lists=expand_lists)
        if replacement is None:
            replacement = raw[m['start']:m['end']]

        start, end = m['start'], m['end']
        done.append(raw[:start])          # Keep stuff leading up to token
        done.append(unicode(replacement)) # Append replacement value
        raw = raw[end:]                   # Continue with remainder of string

    return ''.join(done)
912557
public Expression2 substitute(int index, Expression2 newExpression) {
    Preconditions.checkArgument(index < size);
    if (index == 0) {
      return newExpression;
    } else {
      int[] parts = findSubexpression(index);
      
      Expression2 substituted = subexpressions.get(parts[0]).substitute(parts[1], newExpression);
      List<Expression2> newSubexpressions = Lists.newArrayList(subexpressions);
      newSubexpressions.set(parts[0], substituted);
      return Expression2.nested(newSubexpressions);
    }
  }
1038218
def expand(string, vars, local_vars={}):
    
    def exp(m):
        var = m.group(1)
        if var == '$':
            return '$'
        return local_vars.get(var, vars.get(var, ''))
    return re.sub(r'\$(\$|\w*)', exp, string)