Internal function. Reduces a compiled pattern tree to an
    intermediate representation suitable for feeding the
    automaton. This also trims off any optional pattern elements(like
    [a], a*).
167250
def reduce_tree(node, parent=None):
    

    new_node = None
    #switch on the node type
    if node.type == syms.Matcher:
        #skip
        node = node.children[0]

    if node.type == syms.Alternatives  :
        #2 cases
        if len(node.children) <= 2:
            #just a single 'Alternative', skip this node
            new_node = reduce_tree(node.children[0], parent)
        else:
            #real alternatives
            new_node = MinNode(type=TYPE_ALTERNATIVES)
            #skip odd children('|' tokens)
            for child in node.children:
                if node.children.index(child)%2:
                    continue
                reduced = reduce_tree(child, new_node)
                if reduced is not None:
                    new_node.children.append(reduced)
    elif node.type == syms.Alternative:
        if len(node.children) > 1:

            new_node = MinNode(type=TYPE_GROUP)
            for child in node.children:
                reduced = reduce_tree(child, new_node)
                if reduced:
                    new_node.children.append(reduced)
            if not new_node.children:
                # delete the group if all of the children were reduced to None
                new_node = None

        else:
            new_node = reduce_tree(node.children[0], parent)

    elif node.type == syms.Unit:
        if (isinstance(node.children[0], pytree.Leaf) and
            node.children[0].value == '('):
            #skip parentheses
            return reduce_tree(node.children[1], parent)
        if ((isinstance(node.children[0], pytree.Leaf) and
               node.children[0].value == '[')
               or
               (len(node.children)>1 and
               hasattr(node.children[1], "value") and
               node.children[1].value == '[')):
            #skip whole unit if its optional
            return None

        leaf = True
        details_node = None
        alternatives_node = None
        has_repeater = False
        repeater_node = None
        has_variable_name = False

        for child in node.children:
            if child.type == syms.Details:
                leaf = False
                details_node = child
            elif child.type == syms.Repeater:
                has_repeater = True
                repeater_node = child
            elif child.type == syms.Alternatives:
                alternatives_node = child
            if hasattr(child, 'value') and child.value == '=': # variable name
                has_variable_name = True

        #skip variable name
        if has_variable_name:
            #skip variable name, '='
            name_leaf = node.children[2]
            if hasattr(name_leaf, 'value') and name_leaf.value == '(':
                # skip parenthesis
                name_leaf = node.children[3]
        else:
            name_leaf = node.children[0]

        #set node type
        if name_leaf.type == token_labels.NAME:
            #(python) non-name or wildcard
            if name_leaf.value == 'any':
                new_node = MinNode(type=TYPE_ANY)
            else:
                if hasattr(token_labels, name_leaf.value):
                    new_node = MinNode(type=getattr(token_labels, name_leaf.value))
                else:
                    new_node = MinNode(type=getattr(pysyms, name_leaf.value))

        elif name_leaf.type == token_labels.STRING:
            #(python) name or character; remove the apostrophes from
            #the string value
            name = name_leaf.value.strip("'")
            if name in tokens:
                new_node = MinNode(type=tokens[name])
            else:
                new_node = MinNode(type=token_labels.NAME, name=name)
        elif name_leaf.type == syms.Alternatives:
            new_node = reduce_tree(alternatives_node, parent)

        #handle repeaters
        if has_repeater:
            if repeater_node.children[0].value == '*':
                #reduce to None
                new_node = None
            elif repeater_node.children[0].value == '+':
                #reduce to a single occurence i.e. do nothing
                pass
            else:
                #TODO: handle {min, max} repeaters
                raise NotImplementedError
                pass

        #add children
        if details_node and new_node is not None:
            for child in details_node.children[1:-1]:
                #skip '<', '>' markers
                reduced = reduce_tree(child, new_node)
                if reduced is not None:
                    new_node.children.append(reduced)
    if new_node:
        new_node.parent = parent
    return new_node
66956
def simplify_recursive(typ):
    # type: (AbstractType) -> AbstractType
    """"""
    if isinstance(typ, UnionType):
        return combine_types(typ.items)
    elif isinstance(typ, ClassType):
        simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args])
        args = simplified.args
        if (simplified.name == 'Dict' and len(args) == 2
                and isinstance(args[0], ClassType) and args[0].name in ('str', 'Text')
                and isinstance(args[1], UnionType) and not is_optional(args[1])):
            # Looks like a potential case for TypedDict, which we don't properly support yet.
            return ClassType('Dict', [args[0], AnyType()])
        return simplified
    elif isinstance(typ, TupleType):
        return TupleType([simplify_recursive(item) for item in typ.items])
    return typ
1138738
function getOrCompile (patternStr) {
    var tree, fn;
    if (!patterns.hasOwnProperty(patternStr)) {
      tree = parse(patternStr);
      if (!normalized.hasOwnProperty(tree.pattern)) {
        fn = compile(tree);
        fn.pattern = tree.pattern;
        normalized[tree.pattern] = fn;
      }
      patterns[patternStr] = normalized[tree.pattern];
    }
    return patterns[patternStr];
  }
657725
def simplify(self):
        
        expr = self.expr
        self.expr = _cancel_mul(expr, self.registry)
        return self
151173
function renderDesructuration(pattern, expr, traverse, path, state) {
  utils.catchupNewlines(pattern.range[1], state);

  var id;

  if (pattern.type === Syntax.ObjectPattern && pattern.properties.length === 1) {
    id = expr;
  } else if (pattern.type === Syntax.ArrayPattern && pattern.elements.length === 1) {
    id = expr;
  } else {
    id = renderExpressionMemoized(expr, traverse, path, state);
  }

  if (pattern.type === Syntax.ObjectPattern) {

    pattern.properties.forEach(function(prop, idx) {
      var comma = (idx !== pattern.properties.length - 1) ? ', ' : '';

      if (isPattern(prop.value)) {
        renderDesructuration(prop.value, [id, '.', prop.key.name], traverse, path, state);
      } else {
        utils.append(prop.value.name + ' = ', state);
        render([id, '.' + prop.key.name], traverse, path, state);
        utils.append(comma, state);
      }
    });

  } else {

    pattern.elements.forEach(function(elem, idx) {
      // null means skip
      if (elem === null) {
        return;
      }

      var comma = (idx !== pattern.elements.length - 1) ? ', ' : '';

      if (isPattern(elem)) {
        renderDesructuration(elem, [id, '[' + idx + ']'], traverse, path, state);
      } else if (elem.type === Syntax.SpreadElement) {
        utils.append(elem.argument.name + ' = ', state);
        render([id, '.slice(' + idx + ')'], traverse, path, state);
        utils.append(comma, state);
      } else {
        utils.append(elem.name + ' = ', state);
        render([id, '[' + idx + ']'], traverse, path, state);
        utils.append(comma, state);
      }
    });
  }
}
622180
private static <E> boolean removeOccurrencesImpl(
      Multiset<E> multisetToModify, Multiset<?> occurrencesToRemove) {
    // TODO(user): generalize to removing an Iterable, perhaps
    checkNotNull(multisetToModify);
    checkNotNull(occurrencesToRemove);

    boolean changed = false;
    Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator();
    while (entryIterator.hasNext()) {
      Entry<E> entry = entryIterator.next();
      int removeCount = occurrencesToRemove.count(entry.getElement());
      if (removeCount >= entry.getCount()) {
        entryIterator.remove();
        changed = true;
      } else if (removeCount > 0) {
        multisetToModify.remove(entry.getElement(), removeCount);
        changed = true;
      }
    }
    return changed;
  }
1074412
def delete(pattern)      
      Klass.removeKey(@handle, (pattern.kind_of?(Regexp) ? pattern.source : pattern.to_s))
      true
    end
598421
@Override
    public final void applyPattern(String pattern)
    {

        if (hasRegistry())
        {
            super.applyPattern(pattern);
            toPattern = super.toPattern();
            return;
        }

        ArrayList<Format> foundFormats = new ArrayList<Format>();
        ArrayList<String> foundDescriptions = new ArrayList<String>();
        StringBuilder stripCustom = new StringBuilder(pattern.length());

        ParsePosition pos = new ParsePosition(0);
        char[] c = pattern.toCharArray();
        int fmtCount = 0;

        while (pos.getIndex() < pattern.length())
        {

            char charType = c[pos.getIndex()];

            if (QUOTE == charType)
            {

                appendQuotedString(pattern, pos, stripCustom, true);
                continue;

            }

            if (START_FE == charType)
            {

                fmtCount++;
                seekNonWs(pattern, pos);
                int start = pos.getIndex();
                int index = readArgumentIndex(pattern, next(pos));
                stripCustom.append(START_FE).append(index);
                seekNonWs(pattern, pos);
                Format format = null;
                String formatDescription = null;
                if (c[pos.getIndex()] == START_FMT)
                {
                    formatDescription = parseFormatDescription(pattern, next(pos));
                    format = getFormat(formatDescription);
                    if (format == null)
                    {
                        stripCustom.append(START_FMT).append(formatDescription);
                    }
                }
                foundFormats.add(format);
                foundDescriptions.add(format == null ? null : formatDescription);

                Preconditions.checkState(foundFormats.size() == fmtCount);
                Preconditions.checkState(foundDescriptions.size() == fmtCount);

                if (c[pos.getIndex()] != END_FE)
                {
                    throw new IllegalArgumentException("Unreadable format element at position " + start);
                }

            }

            //$FALL-THROUGH$
            stripCustom.append(c[pos.getIndex()]);
            next(pos);

        }

        super.applyPattern(stripCustom.toString());

        toPattern = insertFormats(super.toPattern(), foundDescriptions);

        if (containsElements(foundFormats))
        {
            Format[] origFormats = getFormats();
            // only loop over what we know we have, as MessageFormat on Java 1.3
            // seems to provide an extra format element:
            Iterator<Format> it = foundFormats.iterator();
            for (int i = 0; it.hasNext(); i++)
            {
                Format f = it.next();
                if (f != null)
                {
                    origFormats[i] = f;
                }
            }
            super.setFormats(origFormats);
        }

    }
1076191
public int removeAll (String pattern)
    {
        Pattern pat = makePattern(pattern);
        int removed = 0;
        Iterator<String> i = _imports.iterator();
        while (i.hasNext()) {
            String name = i.next();
            if (pat.matcher(name).matches()) {
                i.remove();
                ++removed;
            }
        }
        return removed;
    }
75431
public void apply(HyphenationPattern pattern) {

    String wordPart = pattern.getWordPart();
    int wordPartLength = wordPart.length();
    int wordPartHash = pattern.getWordPartHash();
    int[] subHashes = getHashes(wordPartLength);
    if (subHashes.length == 0) {
      return;
    }
    int start = 0;
    int end = subHashes.length - 1;
    if (wordPart.charAt(0) == HyphenationPattern.TERMINATOR) {
      end = 0;
    } else if (wordPart.charAt(wordPartLength - 1) == HyphenationPattern.TERMINATOR) {
      start = end;
    }
    for (int i = start; i <= end; i++) {
      if (subHashes[i] == wordPartHash) {
        if (isSubstring(this.normalizedWord, wordPart, i)) {
          apply(pattern, i);
        }
      }
    }
  }
102720
def compile_pattern(self, input, debug=False, with_tree=False):
        """"""
        tokens = tokenize_wrapper(input)
        try:
            root = self.driver.parse_tokens(tokens, debug=debug)
        except parse.ParseError as e:
            raise PatternSyntaxError(str(e))
        if with_tree:
            return self.compile_node(root), root
        else:
            return self.compile_node(root)
626168
public static ExpressionTree stripParentheses(ExpressionTree tree) {
    while (tree instanceof ParenthesizedTree) {
      tree = ((ParenthesizedTree) tree).getExpression();
    }
    return tree;
  }
1093729
def cleanup(arg):
    """"""
    arg = numpy.asarray(arg)
    if len(arg.shape) <= 1:
        arg = arg.reshape(arg.size, 1)
    elif len(arg.shape) > 2:
        raise ValueError("shapes must be smaller than 3")
    return arg
1118256
public static void simplify(Throwable e) {
		if (!isSimplifyStackTrace()) {
			return;
		}

		if (e.getCause() != null) {
			simplify(e.getCause());
		}

		StackTraceElement[] trace = e.getStackTrace();
		
		if (trace == null || trace.length == 0) {
			return;
		}

		List<StackTraceElement> simpleTrace = new ArrayList<StackTraceElement>(
				trace.length);
		simpleTrace.add(trace[0]);

		// Remove unnecessary stack trace elements.
		for (int i = 1; i < trace.length; i++) {
			if (EXCLUDED_STACK_TRACE.matcher(trace[i].getClassName()).matches()) {
				continue;
			}
			simpleTrace.add(trace[i]);
		}
		
		e.setStackTrace(simpleTrace.toArray(new StackTraceElement[simpleTrace
				.size()]));
	}
784224
def compile_node(self, node):
        
        # XXX Optimize certain Wildcard-containing-Wildcard patterns
        # that can be merged
        if node.type == self.syms.Matcher:
            node = node.children[0] # Avoid unneeded recursion

        if node.type == self.syms.Alternatives:
            # Skip the odd children since they are just '|' tokens
            alts = [self.compile_node(ch) for ch in node.children[::2]]
            if len(alts) == 1:
                return alts[0]
            p = pytree.WildcardPattern([[a] for a in alts], min=1, max=1)
            return p.optimize()

        if node.type == self.syms.Alternative:
            units = [self.compile_node(ch) for ch in node.children]
            if len(units) == 1:
                return units[0]
            p = pytree.WildcardPattern([units], min=1, max=1)
            return p.optimize()

        if node.type == self.syms.NegatedUnit:
            pattern = self.compile_basic(node.children[1:])
            p = pytree.NegatedPattern(pattern)
            return p.optimize()

        assert node.type == self.syms.Unit

        name = None
        nodes = node.children
        if len(nodes) >= 3 and nodes[1].type == token.EQUAL:
            name = nodes[0].value
            nodes = nodes[2:]
        repeat = None
        if len(nodes) >= 2 and nodes[-1].type == self.syms.Repeater:
            repeat = nodes[-1]
            nodes = nodes[:-1]

        # Now we've reduced it to: STRING | NAME [Details] | (...) | [...]
        pattern = self.compile_basic(nodes, repeat)

        if repeat is not None:
            assert repeat.type == self.syms.Repeater
            children = repeat.children
            child = children[0]
            if child.type == token.STAR:
                min = 0
                max = pytree.HUGE
            elif child.type == token.PLUS:
                min = 1
                max = pytree.HUGE
            elif child.type == token.LBRACE:
                assert children[-1].type == token.RBRACE
                assert  len(children) in (3, 5)
                min = max = self.get_int(children[1])
                if len(children) == 5:
                    max = self.get_int(children[3])
            else:
                assert False
            if min != 1 or max != 1:
                pattern = pattern.optimize()
                pattern = pytree.WildcardPattern([[pattern]], min=min, max=max)

        if name is not None:
            pattern.name = name
        return pattern.optimize()
1008776
function(node, pattern) {
		if (!!node && (node.nodeType === 3) && pattern.exec(node.nodeValue)) {
			node.nodeValue = node.nodeValue.replace(pattern, '');
		}
	}
348583
def _simplify(elements):
        """"""
        simplified = []
        previous = None
        for element in elements:
            if element == "..":
                raise FormicError("Invalid glob:"
                                  " Cannot have '..' in a glob: {0}".format(
                                      "/".join(elements)))
            elif element == ".":
                # . in a path does not do anything
                pass
            elif element == "**" and previous == "**":
                # Remove repeated "**"s
                pass
            else:
                simplified.append(os.path.normcase(element))
                previous = element

        if simplified[-1] == "":
            # Trailing slash shorthand for /**
            simplified[-1] = "**"

        # Ensure the pattern either:
        #  * Starts with a "**", or
        #  * Starts with the first real element of the glob
        if simplified[0] == "":
            # "" means the pattern started with a slash.
            del simplified[0]
        else:
            if simplified[0] != "**":
                simplified.insert(0, "**")

        return simplified