Given a dictionary of defaults, ie {attribute: value},
        this classmethod constructs a new instance of the class and
        merges the defaults
542486
def from_defaults(clz, defaults):
        
        if isinstance(defaults, (str, unicode)):
            defaults = json.loads(defaults)
        
        c = clz()
        for attribute in defaults.keys():
            if attribute in c:
                value = defaults[attribute]
                c[attribute].merge(value)
        # in case any values were not specified, attempt to merge them with 
        # the settings provided by clz.random()
        cr = clz.random()
        for attribute, value in cr:
            try:
                c[attribute].merge(value)
            except Contradiction:
                pass
        return c
34636
def normalize_defaults
      new_options = {}
      options.each do |key,value|
        unless value.nil?
          new_options[key.to_s] = value
          new_options[key.to_sym] = value
        end
      end
      options.merge!(new_options)
    end
1093080
function mergeOptions(defaults, settings) {
  var options = _extends({}, defaults, settings);

  // `Object.assign` do not deeply merge objects, so we
  // have to do it manually for every nested object
  // in options. Although it does not look smart,
  // it's smaller and faster than some fancy
  // merging deep-merge algorithm script.
  if (settings.hasOwnProperty('classes')) {
    options.classes = _extends({}, defaults.classes, settings.classes);

    if (settings.classes.hasOwnProperty('direction')) {
      options.classes.direction = _extends({}, defaults.classes.direction, settings.classes.direction);
    }
  }

  if (settings.hasOwnProperty('breakpoints')) {
    options.breakpoints = _extends({}, defaults.breakpoints, settings.breakpoints);
  }

  return options;
}
966316
def instantiate_from_dict(self, values):
        

        name = values['ENGINE']
        options = values.get('OPTIONS', {})

        # Parse the name
        parts = name.split('.')
        module_name = '.'.join(parts[:-1])
        class_name = parts[-1]

        # Get the class
        try:
            module = import_module(module_name)
            cls = getattr(module, class_name)
        except (ValueError, AttributeError, TypeError, ImportError):
            raise ValueError('Cannot find class %s' % name)

        options = self.instantiate_objects(options)

        return cls(**options)
1080308
def _apply_default(self, config, default):
        
        # No default, nothing to be done here
        if not default:
            return config

        # If the entire config is just a string, return default TaggedValue
        if isinstance(config, str):
            return TaggedValue(config, default, default, *self._global_tags)

        if isinstance(config, dict):
            # Recursively apply defaults for  each item in the config
            for key, val in config.items():
                config[key] = self._apply_default(val, default)

        elif isinstance(config, list):
            # Recursively apply defaults for each item in the config
            for i, val in enumerate(config):
                config[i] = self._apply_default(val, default)

        elif isinstance(config, TaggedValue):
            # Make sure each TaggedValue knows about the default tag
            config.tags.add(default)

        return config
881332
def __merge_values(self, from_dict, to_dict):
        
        for key, value in from_dict.iteritems():

            # Only if the key already exists
            if key in to_dict:

                # Make sure the values are the same datatype
                assert type(to_dict[key]) is type(from_dict[key]), 'Data type for {0} is incorrect: {1}, should be {2}'.format(key, type(from_dict[key]), type(to_dict[key]))

                # Recursively dive into the next dictionary
                if type(to_dict[key]) is dict:
                    to_dict[key] = self.__merge_values(from_dict[key], to_dict[key])

                # Replace value
                else:
                    to_dict[key] = from_dict[key]

        return to_dict
1068255
public void mergeWithDefaults(GlobalMetadata defaults) {
    List<String> defaultTransferEncoding = defaults.getTransferEncoding();
    List<String> myEncoding = getTransferEncoding();

    if (defaultTransferEncoding != null) {
      if (myEncoding == null) {
        setDatasetMetadata(TRANSFER_ENCODING_KEY, defaultTransferEncoding);
      } else {
        List<String> combinedEncoding = new ArrayList<>();
        combinedEncoding.addAll(myEncoding);
        combinedEncoding.addAll(defaultTransferEncoding);

        setDatasetMetadata(TRANSFER_ENCODING_KEY, combinedEncoding);
      }
    }

    for (Map.Entry<String, Object> entry : defaults.datasetLevel.entrySet()) {
      if (!datasetLevel.containsKey(entry.getKey())) {
        setDatasetMetadata(entry.getKey(), entry.getValue());
      }
    }
  }
287337
private static CompositeValue createCompositeValue(final String name, final Collection<? extends ParsedAttribute<?>> value) {
		final Map<String, Value> map = new HashMap<>(value.size());
    	for (final ParsedAttribute<?> attr : value) {
    		map.put(attr.getName(), attr.getValue());
    	}
		return new CompositeValue(name, map);
	}
339566
def _set_default_attr(self, default_attr):
        
        for attr, val in six.iteritems(default_attr):
            if getattr(self, attr, None) is None:
                setattr(self, attr, val)
726821
def buildable(self, values: Optional[dict]=None, method: Optional[str]=None) -> bool:
        """"""
        if method is not None and method not in self.methods:
            return False
        defaults_match = all(
            values[key] == self.defaults[key] for key in self.defaults if key in values  # noqa: S101, E501
        )
        return defaults_match and set(values.keys()) >= set(self._converters.keys())
1100525
def _construct_instance(cls, values):
        
        # we're going to take the values, which is from the DB as a dict
        # and translate that into our local fields
        # the db_map is a db_field -> model field map
        if cls._db_map:
            values = dict((cls._db_map.get(k, k), v) for k, v in values.items())

        if cls._is_polymorphic:
            disc_key = values.get(cls._discriminator_column_name)

            if disc_key is None:
                raise PolymorphicModelException('discriminator value was not found in values')

            poly_base = cls if cls._is_polymorphic_base else cls._polymorphic_base

            klass = poly_base._get_model_by_discriminator_value(disc_key)
            if klass is None:
                poly_base._discover_polymorphic_submodels()
                klass = poly_base._get_model_by_discriminator_value(disc_key)
                if klass is None:
                    raise PolymorphicModelException(
                        'unrecognized discriminator column {0} for class {1}'.format(disc_key, poly_base.__name__)
                    )

            if not issubclass(klass, cls):
                raise PolymorphicModelException(
                    '{0} is not a subclass of {1}'.format(klass.__name__, cls.__name__)
                )

            values = dict((k, v) for k, v in values.items() if k in klass._columns.keys())

        else:
            klass = cls

        instance = klass(**values)
        instance._set_persisted(force=True)
        return instance
1073928
def new_instance(settings):
    
    settings = set_default({}, settings)
    if not settings["class"]:
        Log.error("Expecting 'class' attribute with fully qualified class name")

    # IMPORT MODULE FOR HANDLER
    path = settings["class"].split(".")
    class_name = path[-1]
    path = ".".join(path[:-1])
    constructor = None
    try:
        temp = __import__(path, globals(), locals(), [class_name], 0)
        constructor = object.__getattribute__(temp, class_name)
    except Exception as e:
        Log.error("Can not find class {{class}}", {"class": path}, cause=e)

    settings['class'] = None
    try:
        return constructor(kwargs=settings)  # MAYBE IT TAKES A KWARGS OBJECT
    except Exception as e:
        pass

    try:
        return constructor(**settings)
    except Exception as e:
        Log.error("Can not create instance of {{name}}", name=".".join(path), cause=e)
573027
def _insert_defaults(self):
        
        merged = merge_defaults(self.structure, self)
        self.update(merged)
982722
def _add_standard_attributes(cls):
        
        setattr(
            cls.context.new_class,
            cls.context.new_meta['state_attribute_name'],
            cls.context.state_value)
        setattr(
            cls.context.new_class,
            cls.context.state_name,
            utils.state_property)

        setattr(cls.context.new_class, 'is_', utils.is_)
        setattr(cls.context.new_class, 'can_be_', utils.can_be_)
        setattr(cls.context.new_class, 'set_', utils.set_)
626189
function defaultAttrs(attrs) {
  let defaults = Object.create(null)
  for (let attrName in attrs) {
    let attr = attrs[attrName]
    if (!attr.hasDefault) return null
    defaults[attrName] = attr.default
  }
  return defaults
}
1051015
def _simple_new(cls, values, name=None, dtype=None, **kwargs):
        
        if not hasattr(values, 'dtype'):
            if (values is None or not len(values)) and dtype is not None:
                values = np.empty(0, dtype=dtype)
            else:
                values = np.array(values, copy=False)
                if is_object_dtype(values):
                    values = cls(values, name=name, dtype=dtype,
                                 **kwargs)._ndarray_values

        if isinstance(values, (ABCSeries, ABCIndexClass)):
            # Index._data must always be an ndarray.
            # This is no-copy for when _values is an ndarray,
            # which should be always at this point.
            values = np.asarray(values._values)

        result = object.__new__(cls)
        result._data = values
        # _index_data is a (temporary?) fix to ensure that the direct data
        # manipulation we do in `_libs/reduction.pyx` continues to work.
        # We need access to the actual ndarray, since we're messing with
        # data buffers and strides. We don't re-use `_ndarray_values`, since
        # we actually set this value too.
        result._index_data = values
        result.name = name
        for k, v in kwargs.items():
            setattr(result, k, v)
        return result._reset_identity()
1006572
def from_dict(cls, d):
        
        conf = {}
        for k in d["config"]:
            v = d["config"][k]
            if isinstance(v, dict):
                if u"type" in v:
                    typestr = v[u"type"]
                else:
                    typestr = v["type"]
                conf[str(k)] = classes.get_dict_handler(typestr)(v)
            else:
                conf[str(k)] = v
        return classes.get_class(d["class"])(name=d["name"], config=conf)