Substitute sub-expressions both on the lhs and rhs

        Args:
            var_map (dict): Dictionary with entries of the form
                ``{expr: substitution}``
433385
def substitute(self, var_map, cont=False, tag=None):
        
        return self.apply(substitute, var_map=var_map, cont=cont, tag=tag)
233414
def solve_filter(expr, vars):
    
    lhs_values, _ = __solve_for_repeated(expr.lhs, vars)

    def lazy_filter():
        for lhs_value in repeated.getvalues(lhs_values):
            if solve(expr.rhs, __nest_scope(expr.lhs, vars, lhs_value)).value:
                yield lhs_value

    return Result(repeated.lazy(lazy_filter), ())
1090373
def substitution_set(string, indexes):
    
    strlen = len(string)
    return {mutate_string(string, x) for x in indexes if valid_substitution(strlen, x)}
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);
    }
  }
1018815
def add_substitution(self, substitution):
        
        if isinstance(substitution, dict):
            self._substitutions.append(substitution)
        else:
            self._substitutions.append(substitution.get())
228364
def _map_in_out(self, inside_var_name):
        """"""
        for out_name, in_name in self.outside_name_map.items():
            if inside_var_name == in_name:
                return out_name
        return None
284862
def apply_format(var, format_str):
    
    if isinstance(var, (list, tuple)):
        new_var = map(lambda x: apply_format(x, format_str), var)
        if isinstance(var, tuple):
            new_var = '(' + ', '.join(new_var) + ')'
        elif isinstance(var, list):
            new_var = '[' + ', '.join(new_var) + ']'
        return '{}'.format(new_var)
    else:
        return format_str.format(var)
474667
def _expand_rec_to_vars(var_items, rec_items, input_order, items_by_key, parallel):
    
    num_items = var_items
    var_items = list(var_items)[0]
    if rec_items:
        for rec_key in (k for (k, t) in input_order.items() if t == "record"):
            rec_vals = items_by_key[rec_key]
            if len(rec_vals) == 1 and var_items > 1:
                items_by_key[rec_key] = rec_vals * var_items
            else:
                assert var_items == len(rec_vals), (var_items, rec_vals)
    return items_by_key, num_items
1227112
def _rebind_variables(self, new_inputs):
        
        expr = self._expr

        # If we have 11+ variables, some of our variable names may be
        # substrings of other variable names. For example, we might have x_1,
        # x_10, and x_100. By enumerating in reverse order, we ensure that
        # every variable name which is a substring of another variable name is
        # processed after the variable of which it is a substring. This
        # guarantees that the substitution of any given variable index only
        # ever affects exactly its own index. For example, if we have variables
        # with indices going up to 100, we will process all of the x_1xx names
        # before x_1x, which will be before x_1, so the substitution of x_1
        # will not affect x_1x, which will not affect x_1xx.
        for idx, input_ in reversed(list(enumerate(self.inputs))):
            old_varname = "x_%d" % idx
            # Temporarily rebind to x_temp_N so that we don't overwrite the
            # same value multiple times.
            temp_new_varname = "x_temp_%d" % new_inputs.index(input_)
            expr = expr.replace(old_varname, temp_new_varname)
        # Clear out the temp variables now that we've finished iteration.
        return expr.replace("_temp_", "_")
1367544
def multi_substitution(*substitutions):
	
	substitutions = itertools.starmap(substitution, substitutions)
	# compose function applies last function first, so reverse the
	#  substitutions to get the expected order.
	substitutions = reversed(tuple(substitutions))
	return compose(*substitutions)
825811
def alias(self, maps):
        
        for k, v in maps.items():  # pylint: disable=invalid-name
            if self.verbose_mode:
                print(
                    " * Mapping a specified var as a alias:"
                    " {0} -> {1}".format(v, k))
            self.app.config[v] = self.app.config[k]
512579
def translate(self):
        """"""
        varnames = set()
        ident = self.ident
        funcnames = set([ident])

        arg_exprs = []
        for arg in self.args:
            subexprs, subvars, subfuncs = arg.translate()
            varnames.update(subvars)
            funcnames.update(subfuncs)

            # Create a subexpression that joins the result components of
            # the arguments.
            arg_exprs.append(ex_call(
                ast.Attribute(ex_literal(u''), 'join', ast.Load()),
                [ex_call(
                    'map',
                    [
                        ex_rvalue(str.__name__),
                        ast.List(subexprs, ast.Load()),
                    ]
                )],
            ))

        subexpr_call = ex_call(
            FUNCTION_PREFIX + ident,
            arg_exprs
        )
        return [subexpr_call], varnames, funcnames
1001061
private Stream<ImmutableExpression> extractEqualities(ImmutableSubstitution<ImmutableTerm> substitution,
                                                          ImmutableSet<Variable> leftVariables) {
        return substitution.getImmutableMap().entrySet().stream()
                .filter(e -> leftVariables.contains(e.getKey()) || leftVariables.contains(e.getValue()))
                .map(e -> termFactory.getImmutableExpression(EQ, e.getKey(), e.getValue()));
    }
1373155
def substitute(self, msg, kind):
        

        # Safety checking.
        if 'lists' not in self.master._sorted:
            raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
        if kind not in self.master._sorted["lists"]:
            raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")

        # Get the substitution map.
        subs = None
        if kind == 'sub':
            subs = self.master._sub
        else:
            subs = self.master._person

        # Make placeholders each time we substitute something.
        ph = []
        i  = 0

        for pattern in self.master._sorted["lists"][kind]:
            result = subs[pattern]

            # Make a placeholder.
            ph.append(result)
            placeholder = "\x00%d\x00" % i
            i += 1

            cache = self.master._regexc[kind][pattern]
            msg = re.sub(cache["sub1"], placeholder, msg)
            msg = re.sub(cache["sub2"], placeholder + r'\1', msg)
            msg = re.sub(cache["sub3"], r'\1' + placeholder + r'\2', msg)
            msg = re.sub(cache["sub4"], r'\1' + placeholder, msg)

        placeholders = re.findall(RE.placeholder, msg)
        for match in placeholders:
            i = int(match)
            result = ph[i]
            msg = msg.replace('\x00' + match + '\x00', result)

        # Strip & return.
        return msg.strip()
468629
public Expression2 substitute(String value, String replacement) {
    return substitute(Expression2.constant(value), Expression2.constant(replacement));
  }
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
456767
def substitution(self, substitution):
        
        if isinstance(substitution, list):
            for s in substitution:
                self.add_substitution(s)
        else:
            self.add_substitution(substitution)