Return dict noting the substitution values (or False for no match)
778813
def constraint_matches(self, c, m):
        
        if isinstance(m, tuple):
            d = {}
            if isinstance(c, Operator) and c._op_name == m[0]:
                for c1, m1 in zip(c._args, m[1:]):
                    r = self.constraint_matches(c1, m1)
                    if r is False:
                        return r
                    d.update(r)
                return d
            return False
        return m.match(c)
662682
def cmp_dict(d1, d2, ignore_keys=[]):
    """"""
    # https://stackoverflow.com/questions/10480806/compare-dictionaries-ignoring-specific-keys
    return {k: v for k, v in d1.items() if k not in ignore_keys} \
        == {k: v for k, v in d2.items() if k not in ignore_keys}
1276957
def get_substituted_contents(contents, substitutions):
    
    result = contents
    for sub in substitutions:
        result = sub.apply_and_get_result(result)
    return result
397425
def dict_filter(d, exclude=[]):
    

    if isinstance(d, list):
        ret = []
        for e in d:
            ret.append(dict_filter(e, exclude))
        return ret
    elif isinstance(d, dict):
        ret = {}
        for k, v in d.items():
            if isinstance(k, builtin_str):
                k = str(k)

            assert isinstance(k, str)
            if k in exclude:
                continue
            ret[k] = dict_filter(v, exclude)
        return ret

    return d
1052605
def _substitute(self, query, model_class=None):
        '''
        
        '''
        if '$' in query:
            mapping = dict(db="`%s`" % self.db_name)
            if model_class:
                mapping['table'] = "`%s`.`%s`" % (self.db_name, model_class.table_name())
            query = Template(query).safe_substitute(mapping)
        return query
1097556
def invert_dict(d):
    """"""
    # Based on recipe from ASPN
    result = {}
    for k, v in d.items():
        keys = result.setdefault(v, [])
        keys.append(k)
    return result
894288
def get_data_dict_from_config(self, config_dict):
        """"""
        return {
            key: self.parsedpage.get_filtered_values_by_selector(
                item_dict['selector'],
                item_dict.get('regex_filter', None),
                item_dict.get('regex_group', 1)
            )
            for key, item_dict in config_dict.iteritems()
            if item_dict.get('selector', None) is not None
        }
1137268
def match_item(key, value, item):
    
    if isinstance(value, (list, tuple)):
        return any(match_item(key, sub_value, item) for sub_value in value)
    else:
        return key not in item or str(item.get(key)).lower() == str(value).lower()
866829
def _iter_valid_subtotal_dicts(self):
        """"""
        for insertion_dict in self._insertion_dicts:
            # ---skip any non-dicts---
            if not isinstance(insertion_dict, dict):
                continue

            # ---skip any non-subtotal insertions---
            if insertion_dict.get("function") != "subtotal":
                continue

            # ---skip any malformed subtotal-dicts---
            if not {"anchor", "args", "name"}.issubset(insertion_dict.keys()):
                continue

            # ---skip if doesn't reference at least one non-missing element---
            if not self._element_ids.intersection(insertion_dict["args"]):
                continue

            # ---an insertion-dict that successfully runs this gauntlet
            # ---is a valid subtotal dict
            yield insertion_dict
704264
def dictstr(arg):
    
    key, value = arg.split("=")

    if value.lower() == "true" or value.lower() == "false":
        value = bool(value)
    elif INT_RE.match(value):
        value = int(value)
    elif FLOAT_RE.match(value):
        value = float(value)
    return (key, value)
1140426
function getSubstitution(matched, str, position, captures, namedCaptures, replacement) {
    var tailPos = position + matched.length;
    var m = captures.length;
    var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
    if (namedCaptures !== undefined) {
      namedCaptures = toObject(namedCaptures);
      symbols = SUBSTITUTION_SYMBOLS;
    }
    return $replace.call(replacement, symbols, function (match, ch) {
      var capture;
      switch (ch.charAt(0)) {
        case '$': return '$';
        case '&': return matched;
        case '`': return str.slice(0, position);
        case "'": return str.slice(tailPos);
        case '<':
          capture = namedCaptures[ch.slice(1, -1)];
          break;
        default: // \d\d?
          var n = +ch;
          if (n === 0) return match;
          if (n > m) {
            var f = floor(n / 10);
            if (f === 0) return match;
            if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
            return match;
          }
          capture = captures[n - 1];
      }
      return capture === undefined ? '' : capture;
    });
  }
381016
def filter_by(lookup_dict,
              lookup,
              traverse,
              merge=None,
              default='default',
              base=None):
    '''
    
    '''
    ret = None
    # Default value would be an empty list if lookup not found
    val = traverse_dict_and_list(traverse, lookup, [])

    # Iterate over the list of values to match against patterns in the
    # lookup_dict keys
    for each in val if isinstance(val, list) else [val]:
        for key in lookup_dict:
            test_key = key if isinstance(key, six.string_types) \
                else six.text_type(key)
            test_each = each if isinstance(each, six.string_types) \
                else six.text_type(each)
            if fnmatch.fnmatchcase(test_each, test_key):
                ret = lookup_dict[key]
                break
        if ret is not None:
            break

    if ret is None:
        ret = lookup_dict.get(default, None)

    if base and base in lookup_dict:
        base_values = lookup_dict[base]
        if ret is None:
            ret = base_values

        elif isinstance(base_values, Mapping):
            if not isinstance(ret, Mapping):
                raise SaltException(
                    'filter_by default and look-up values must both be '
                    'dictionaries.')
            ret = salt.utils.dictupdate.update(copy.deepcopy(base_values), ret)

    if merge:
        if not isinstance(merge, Mapping):
            raise SaltException(
                'filter_by merge argument must be a dictionary.')

        if ret is None:
            ret = merge
        else:
            salt.utils.dictupdate.update(ret, copy.deepcopy(merge))

    return ret
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
411375
def substitution_scores_match(self, other):
        ''''''
        overlap = set(self.substitution_scores.keys()).intersection(set(other.substitution_scores.keys()))
        for k in overlap:
            if not(self.substitution_scores[k] == None or other.substitution_scores[k] == None):
                if self.substitution_scores[k] != other.substitution_scores[k]:
                    return False
        return True
331116
def pretty_dict_str(d, indent=2):
    """"""
    b = StringIO()
    write_pretty_dict_str(b, d, indent=indent)
    return b.getvalue()
1354336
def valid_substitution(strlen, index):
    
    values = index[0]
    return all([strlen > i for i in values])
945251
def get_match_value(rexobj, key, index=0):
    '''
    
    '''
    if rexobj is None:
        return None

    if rexobj.res_count == 0:
        return None

    try:
        return rexobj.matches[index].named_groups[key]
    except IndexError:
        return None
    except KeyError:
        return None