Select dict-like class based on merge strategy and orderness of keys.

    :param merge: Specify strategy from MERGE_STRATEGIES of how to merge dicts.
    :return: Callable to update objects
424369
def _get_update_fn(strategy):
    
    if strategy is None:
        strategy = MS_DICTS
    try:
        return _MERGE_FNS[strategy]
    except KeyError:
        if callable(strategy):
            return strategy

        raise ValueError("Wrong merge strategy: %r" % strategy)
151016
def _merge_a_into_b(self, a, b):
        
        from easydict import EasyDict as edict
        if type(a) is not edict:
            return

        for k, v in a.items():
            # a must specify keys that are in b
            if k not in b:
                raise KeyError('{} is not a valid config key'.format(k))

            # the types must match, too
            old_type = type(b[k])
            if old_type is not type(v):
                if isinstance(b[k], np.ndarray):
                    v = np.array(v, dtype=b[k].dtype)
                else:
                    raise ValueError(('Type mismatch ({} vs. {}) '
                                      'for config key: {}').format(type(b[k]),
                                                                   type(v), k))

            # recursively merge dicts
            if type(v) is edict:
                try:
                    self._merge_a_into_b(a[k], b[k])
                except:
                    print('Error under config key: {}'.format(k))
                    raise
            else:
                b[k] = v
        return b
964463
def _candidate_merges(self, f):
        
        candidates = [self._get_feature(f.id)]
        c = self.conn.cursor()
        results = c.execute(
            constants._SELECT + '''
            JOIN duplicates ON
            duplicates.newid = features.id WHERE duplicates.idspecid = ?''',
            (f.id,)
        )
        for i in results:
            candidates.append(
                feature.Feature(dialect=self.iterator.dialect, **i))
        return list(set(candidates))
542897
def _merge_ex_dicts(sexdict, oexdict):
    """"""
    # pylint: disable=R0101
    for okey, ovalue in oexdict.items():
        # Keys in other dictionary are callable paths or
        # callables ids depending on the full_cname argument
        # of the handler
        if okey in sexdict:
            svalue = sexdict[okey]
            # Each callable dictionary entry is itself a dictionary where the
            # key is (exception type, exception message) and the value is a
            # dictionary with keys 'function' (a list of callable paths to
            # the function), 'raised' (list of booleans indicating whether the
            # exception though each callable path was raised or not) and name
            for fkey, fvalue in ovalue.items():
                if fkey not in svalue:
                    # The other dictionary has a callable path not present in
                    # the self dictionary, add it unmodified
                    sexdict[okey][fkey] = fvalue
                else:
                    # The other dictionary has a callable and exception
                    # present in the self dictionary, have to check whether
                    # the callable path is the same (in which case update
                    # raise flag) or not (in which case add to 'function' and
                    # 'raise' keys
                    iobj = zip(fvalue["function"], fvalue["raised"])
                    for func, raised in iobj:
                        if func not in sexdict[okey][fkey]["function"]:
                            sexdict[okey][fkey]["function"].append(func)
                            sexdict[okey][fkey]["raised"].append(raised)
                        else:
                            idx = sexdict[okey][fkey]["function"].index(func)
                            sraised = sexdict[okey][fkey]["raised"][idx]
                            if sraised or raised:
                                sexdict[okey][fkey]["raised"][idx] = True
        else:
            sexdict[okey] = ovalue
1020429
def _dict_merge_right(dict_left, dict_right, merge_method):
    """"""
    new_dict = deepcopy(dict_left)
    for key, value in dict_right.items():
        if key not in new_dict:
            new_dict[key] = value
        else:
            recurse = (merge_method == 'take_right_deep' and
                       isinstance(dict_left[key], dict) and
                       isinstance(dict_right[key], dict))
            if recurse:
                new_dict[key] = dict_merge(dict_left[key],
                                           dict_right[key],
                                           merge_method='take_right_deep')
            else:
                new_dict[key] = value
    return new_dict
537824
def merge_dict(d1, d2):
    
    for k,v2 in d2.items():
        v1 = d1.get(k) # returns None if v1 has no value for this key
        if ( isinstance(v1, collections.Mapping) and
             isinstance(v2, collections.Mapping) ):
            merge_dict(v1, v2)
        else:
            d1[k] = v2
1131856
def _merge_metadata_dictionaries(cls, dictionaries):
        
        # three levels of nested dictionaries!
        #   {source name: {variant: {attribute: value}}}
        combined_dictionary = {}
        for source_to_metadata_dict in dictionaries:
            for source_name, variant_to_metadata_dict in source_to_metadata_dict.items():
                combined_dictionary.setdefault(source_name, {})
                combined_source_dict = combined_dictionary[source_name]
                for variant, metadata_dict in variant_to_metadata_dict.items():
                    combined_source_dict.setdefault(variant, {})
                    combined_source_dict[variant].update(metadata_dict)
        return combined_dictionary
1173837
def _deep_merge_dict(a, b):
    """"""
    for k, v in b.items():
        if k in a and isinstance(a[k], dict) and isinstance(v, dict):
            _deep_merge_dict(a[k], v)
        else:
            a[k] = v
640396
def merge(self, dict_=None):
        """"""
        if dict_ is None and hasattr(self, '__dict__'):
            dict_ = self.__dict__  
            # doesn't work anymore as we have _lock attribute
        if dict_ is None:
            return self
        self.update(dict_)
        return self
512052
def _merge(d, u):
    
    for k, v in u.items():
        # if we have a mapping, recursively merge the values
        if isinstance(v, collections.Mapping):
            d[k] = _merge(d.get(k, {}), v)

        # if d (the dict to merge into) is a dict, just add the
        # value to the dict.
        elif isinstance(d, collections.MutableMapping):
            d[k] = v

        # otherwise if d (the dict to merge into) is not a dict (e.g. when
        # recursing into it, `d.get(k, {})` may not be a dict), then do what
        # `update` does and prefer the new value.
        #
        # this means that something like `{'foo': 1}` when updated with
        # `{'foo': {'bar': 1}}` would have the original value (`1`) overwritten
        # and would become: `{'foo': {'bar': 1}}`
        else:
            d = {k: v}

    return d
1191874
def merge(self, others, merge_conditions, common_ancestor=None): # pylint: disable=unused-argument
        

        changed_bytes = self._changes_to_merge(others)

        l.info("Merging %d bytes", len(changed_bytes))
        l.info("... %s has changed bytes %s", self.id, changed_bytes)

        self.read_strategies = self._merge_strategies(self.read_strategies, *[
            o.read_strategies for o in others
        ])
        self.write_strategies = self._merge_strategies(self.write_strategies, *[
            o.write_strategies for o in others
        ])
        merged_bytes = self._merge(others, changed_bytes, merge_conditions=merge_conditions)

        return len(merged_bytes) > 0
543882
def merge_tops(self, tops):
        '''
        
        '''
        merging_strategy = self.opts['top_file_merging_strategy']
        try:
            merge_attr = '_merge_tops_{0}'.format(merging_strategy)
            merge_func = getattr(self, merge_attr)
            if not hasattr(merge_func, '__call__'):
                msg = '\'{0}\' is not callable'.format(merge_attr)
                log.error(msg)
                raise TypeError(msg)
        except (AttributeError, TypeError):
            log.warning(
                'Invalid top_file_merging_strategy \'%s\', falling back to '
                '\'merge\'', merging_strategy
            )
            merge_func = self._merge_tops_merge
        return merge_func(tops)
862091
def merge_extends(self, target, extends, inherit_key="inherit", inherit=False):
        
        if isinstance(target, dict):
            if inherit and inherit_key in target and not to_boolean(target[inherit_key]):
                return
            if not isinstance(extends, dict):
                raise ValueError("Unable to merge: Dictionnary expected")
            for key in extends:
                if key not in target:
                    target[str(key)] = extends[key]
                else:
                    self.merge_extends(target[key], extends[key], inherit_key, True)
        elif isinstance(target, list):
            if not isinstance(extends, list):
                raise ValueError("Unable to merge: List expected")
            target += extends
829293
def merge_dict(lhs, rhs):
    
    assert isinstance(lhs, dict)
    assert isinstance(rhs, dict)
    for k, v in rhs.iteritems():
        if k not in lhs:
            lhs[k] = v
        else:
            lhs[k] = merge_dict(lhs[k], v)
    return lhs
873113
def merge_dicts(dicts, deepcopy=False):
    
    assert isinstance(dicts, list) and all(isinstance(d, dict) for d in dicts)
    return dict(chain(*[copy.deepcopy(d).items() if deepcopy else d.items()
                        for d in dicts]))
621197
def deep_merge(source, options = {})
      default_opts = {:preserve_unmergeables => true}
      DeepMerge::deep_merge!(source, self, default_opts.merge(options))
    end
363396
def apply_strategy(self):
        
        method_id = self.conf.strategy.replace('-', '_')
        if not hasattr(DuplicateSet, method_id):
            raise NotImplementedError(
                "DuplicateSet.{}() method.".format(method_id))
        return getattr(self, method_id)()