Constructs an object given a dictionary containing an "ENGINE" key
        which contains the full module path to the class, and an "OPTIONS"
        key which contains a dictionary that will be passed in to the
        constructor as keyword args.
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)
573152
def make_module_class(name):
    

    source = sys.modules[name]

    members = vars(source)
    is_descriptor = lambda x: not isinstance(x, type) and hasattr(x, '__get__')
    descriptors = {k: v for (k, v) in members.items() if is_descriptor(v)}
    members = {k: v for (k, v) in members.items() if k not in descriptors}
    descriptors['__source'] = source

    target = type(name, (types.ModuleType,), descriptors)(name)
    target.__dict__.update(members)

    sys.modules[name] = target
339165
def make(cls, **kwargs):
    
    cls_attrs = {f.name: f for f in attr.fields(cls)}

    unknown = {k: v for k, v in kwargs.items() if k not in cls_attrs}
    if len(unknown) > 0:
        _LOGGER.warning(
            "Got unknowns for %s: %s - please create an issue!", cls.__name__, unknown
        )

    missing = [k for k in cls_attrs if k not in kwargs]

    data = {k: v for k, v in kwargs.items() if k in cls_attrs}

    # initialize missing values to avoid passing default=None
    # for the attrs attribute definitions
    for m in missing:
        default = cls_attrs[m].default
        if isinstance(default, attr.Factory):
            if not default.takes_self:
                data[m] = default.factory()
            else:
                raise NotImplementedError
        else:
            _LOGGER.debug("Missing key %s with no default for %s", m, cls.__name__)
            data[m] = None

    # initialize and store raw data for debug purposes
    inst = cls(**data)
    setattr(inst, "raw", kwargs)

    return inst
842110
function(obj, env, keypath) {
    if (!_.isObject(obj) || _.isArray(obj)) { return; }

    if (hasKeyPath(obj, ['options', 'reconfigureOverrides', env])) {
      var options = obj.options,
          overrides = obj.options.reconfigureOverrides[env];

      for (var key in overrides) {
        var update = { 
          key: keypath+'.options.'+key,
          oldVal: (typeof options[key] === 'undefined') ? 'undefined' : util.inspect(options[key]),
        };

        if (_.isObject(options[key]) && _.isObject(overrides[key])) { 
          var newVal = _.extend(options[key], overrides[key]);
          update.newVal = util.inspect(newVal);
        } else {
          options[key] = overrides[key];
          update.newVal = util.inspect(overrides[key]);
        }

        updates.push(update);
      }
    }
    
    for (var objKey in obj) {
      updateOptions(obj[objKey], env, keypath+'.'+objKey);
    }
  }
1015743
def _constructor(cls, mapping, configuration):
        
        sequence_type, default_factory, pass_key = configuration
        return cls(default_factory, mapping, sequence_type=sequence_type,
                   pass_key=pass_key)
16282
def from_dict(cls, d):
        
        conf = {}
        for k in d["config"]:
            v = d["config"][k]
            if isinstance(v, dict):
                conf[str(k)] = get_dict_handler(d["config"]["type"])(v)
            else:
                conf[str(k)] = v
        return get_class(str(d["class"]))(config=conf)
79980
def construct(key_data, algorithm=None):
    

    # Allow for pulling the algorithm off of the passed in jwk.
    if not algorithm and isinstance(key_data, dict):
        algorithm = key_data.get('alg', None)

    if not algorithm:
        raise JWKError('Unable to find a algorithm for key: %s' % key_data)

    key_class = get_key(algorithm)
    if not key_class:
        raise JWKError('Unable to find a algorithm for key: %s' % key_data)
    return key_class(key_data, algorithm)
1174781
function build(ctx, keypath, value) {
  const sets = [];

  // set multiple keypaths in one go
  if (isObject(keypath)) {
    for (const k in keypath) {
      if (hasOwn(keypath, k)) {
        sets.push([findModel(ctx, k).model, keypath[k]]);
      }
    }
  } else {
    // set a single keypath
    sets.push([findModel(ctx, keypath).model, value]);
  }

  return sets;
}
972876
def from_config(cls, config, prefix="postmark_", is_uppercase=False):
        
        kwargs = {}
        for arg in get_args(cls):
            key = prefix + arg
            if is_uppercase:
                key = key.upper()
            else:
                key = key.lower()
            if key in config:
                kwargs[arg] = config[key]
        return cls(**kwargs)
599402
def process_kwargs(obj, kwargs):
    '''
    
    '''
    with Modules() as m:
        kwargs = m.kwargs(obj, kwargs)
    return kwargs
746271
function thisModule() {
    var self = this;

    /**
     * Loads iteratively all modules at given path, builds and returns a directory of modules as tree or as list
     *
     * Go through each object, include the code, and determine its identity.
     * Tolerates non-existent files/directories by ignoring them (if 'optional' is specified)
     *
     * @param {Object} options {
        dirname			:: the path to the source directory

        mode            :: options: {list, tree}
                           - list: generate a flat key-value map of modules
                           - tree: generate a full tree of modules

        injectIdentity	:: If disabled, (explicitly set to false) don't inject an identity into the module
                           default: true

        optional		:: if enabled, fail silently and return {} when source directory does not exist
                           or cannot be read (otherwise, exit w/ an error)
                           default: false

        depth			:: the level of recursion where modules will be included
                           default is to infinity

        useVersions  :: creates a sub grouping based on version property (only valid for list mode)
                           default: 'false'

        fileNameFilter	:: only include modules whose FILENAME matches this regex,
                           if 'undefined' - include all, default 'undefined'

        relativePathFilter	:: only include modules whose RELATIVE PATH (path with filename) matches this regex
                           (relative from the entry point directory), if 'undefined' - include all,
                           default 'undefined'

        excludeDirs	    :: regex to exclude directories

        dontLoad		:: if `dontLoad` is set to true, don't run the module w/ V8 or load it into memory--
                           instead, return a tree representing the directory structure
                           (all extant file leaves are included as keys, with their value = `true`)
     }
     * @returns dictionary of modules as list or as tree
     */
    self.requireAll = function (options) {

        //================
        // check options and extend default values
        options.replaceVal = options.replaceVal || '';

        if (!options.mode) {
            options.mode = 'list';
        }

        // exclude source control directories
        if (!options.excludeDirs) {
            options.excludeDirs = /^\.(git|svn)$/;
        }

        // default for 'fileNameFilter' option
        if (!options.fileNameFilter) {
            options.fileNameFilter = /(.*)/;
        }

        var iterationInfo = {
            currentDepth: 0,
            dirName: options.dirName,
            initialDirName: options.dirName
        };


        if (options.moduleDir) {
            return  checkModuleDir(options, iterationInfo);
        }
        else {
            return doInterations(options, iterationInfo);
        }
    };

    /**
     * Parses a directory and searches for options.module subdir. If found subdir is searched for required files
     * @param options
     * @param iterationInfo
     * @returns {{}}
     */
    var checkModuleDir = function (options, iterationInfo) {
        var files;
        var modules = {};
        var result = {};

        // remember the starting directory
        try {
            files = fs.readdirSync(iterationInfo.dirName);
        } catch (e) {
            if (options.optional)
                return {};
            else
                throw new Error('Directory not found: ' + iterationInfo.dirName);
        }

        // iterate through files in the current directory
        files.forEach(function (fileName) {
            iterationInfo.dirName = iterationInfo.initialDirName + '/' + fileName + '/' + options.moduleDir;
            iterationInfo.projectDir = iterationInfo.initialDirName + '/' + fileName;
            result = _.assign(doInterations(options, iterationInfo), result);
        });

        return result;
    };

    /**
     * Parses a directory (will be then iteratively called for all subdirectories) or loads a file.
     * @param options
     * @param iterationInfo
     * @returns {{}}
     */
    var doInterations = function (options, iterationInfo) {
        var files;
        var modules = {};

        // check if the counter has reached the desired depth indicated in options.depth
        if (typeof options.depth !== 'undefined' &&
            iterationInfo.currentDepth >= options.depth) {
            return;
        }

        // remember the starting directory
        try {
            files = fs.readdirSync(iterationInfo.dirName);
        } catch (e) {
            if (options.optional)
                return {};
            else
                throw new Error('Directory not found: ' + iterationInfo.dirName);
        }

        // iterate through files in the current directory
        files.forEach(function (fileName) {
            iterationInfo.fileName = fileName;
            //get absolute path
            iterationInfo.absolutePath = rtrim(iterationInfo.dirName, '/');
            iterationInfo.absoluteFullPath = iterationInfo.absolutePath + '/' + fileName;
            //get relative path
            iterationInfo.relativePath = iterationInfo.absolutePath.replace(iterationInfo.initialDirName, '');
            iterationInfo.relativeFullPath = iterationInfo.absoluteFullPath.replace(iterationInfo.initialDirName, '');
            // make sure a slash exists on the left side of relative paths
            iterationInfo.relativePath = '/' + ltrim(iterationInfo.relativePath, '/');
            iterationInfo.relativeFullPath = '/' + ltrim(iterationInfo.relativeFullPath, '/');

            if (fs.statSync(iterationInfo.absoluteFullPath).isDirectory()) {
                processDirectory(options, iterationInfo, modules)
            }
            else {
                processFile(options, iterationInfo, modules);
            }
        });

        return modules;
    };

    /**
     * Process single file to module dictionary
     * @param options
     * @param fileName
     * @param modules
     */
    var processFile = function (options, iterationInfo, modules) {
        // filename filter
        if (options.fileNameFilter) {
            var match = iterationInfo.fileName.match(options.fileNameFilter);
            if (!match) {
                return;
            }
        }

        // Filter spec.js files
        var match = iterationInfo.fileName.match(/.spec.js/i);
        if (match) {
            return;
        }

        // relative path filter
        if (options.relativePathFilter) {
            var pathMatch = iterationInfo.relativeFullPath.match(options.relativePathFilter);
            if (!pathMatch)
                return;
        }

        //load module
        loadModule(modules, options, iterationInfo);
    };

    /**
     * Load single module
     * @param modules
     * @param options
     * @param iterationInfo
     */
    var loadModule = function (modules, options, iterationInfo) {
        // load module into memory (unless `dontLoad` is true)

        var module = true;

        //default is options.dontLoad === false
        if (options.dontLoad !== true) {
            //if module is to be loaded
            module = require(iterationInfo.absoluteFullPath);

            // If a module is found but was loaded as 'undefined', don't include it (since it's probably unusable)
            if (typeof module === 'undefined') {
                throw new Error('Invalid module:' + iterationInfo.absoluteFullPath);
            }

            var identity;
            //var name;
            var version;

            if (options.useVersions === true) {
                if (module.version) {
                    version = module.version;
                }
                else {
                    version = '1.0';
                }
            }

            if (module.identity) {
                identity = module.identity;
                //name = identity;
            }
            else {
                identity = generateIdentity(options, iterationInfo);
                //name = identity;
            }

            //consider default options.injectIdentity === true
            if (options.injectIdentity !== false) {
                module.fileName = iterationInfo.fileName;
                module.projectDir = iterationInfo.projectDir;
                module.relativePath = iterationInfo.relativePath;
                module.relativeFullPath = iterationInfo.relativeFullPath;
                module.absolutePath = iterationInfo.absolutePath;
                module.absoluteFullPath = iterationInfo.absoluteFullPath;
                module.identity = identity;
                //module.name = name;
                if (options.useVersions === true) {
                    module.version = version;
                }
            }
            else {
                identity = generateIdentity(options, iterationInfo);
            }

            //check if identity is unique within the collection and add to dictionary
            if (options.useVersions === true) {
                if (modules[identity] && modules[identity][version]) {
                    var anotherModule = modules[identity][version];
                    throw new Error("Identity '" + identity + "' with version '" + version + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'");
                }
                modules[identity] = modules[identity] || {};
                modules[identity][version] = module;
            }
            else {
                var anotherModule = modules[identity];
                if (anotherModule) {
                    throw new Error("Identity '" + identity + "' is already registered by module at '" + anotherModule.absoluteFullPath + "'");
                }
                modules[identity] = module;
            }
        }
    };

    /**
     * Generates identity for a module
     * @param options
     * @param iterationInfo
     * @returns {string}
     */
    var generateIdentity = function (options, iterationInfo) {
        // Use the identity for the key name
        var identity;
        if (options.mode === 'list') {
            identity = iterationInfo.relativeFullPath;
            //identity = identity.toLowerCase();
            //find and replace all containments of '/', ':' and '\' within the string
            identity = identity.replace(/\/|\\|:/g, '');
        }
        else if (options.mode === 'tree') {
            identity = iterationInfo.fileName;
            //identity = identity.toLowerCase();
        }
        else
            throw new Error('Unknown mode');

        //remove extention
        identity = identity.substr(0, identity.lastIndexOf('.')) || identity;

        return identity;
    };

    /**
     * Processes one directory level
     * @param options :: general options
     * @param iterationInfo :: iteration options
     * @param modules :: object in which output will be loaded
     */
    var processDirectory = function (options, iterationInfo, modules) {

        // Ignore explicitly excluded directories
        if (options.excludeDirs) {
            var match = iterationInfo.fileName.match(options.excludeDirs);
            if (match)
                return;
        }

        // Recursively call requireAll on each child directory
        var subIterationInfo = _.clone(iterationInfo);
        ++subIterationInfo.depth;
        subIterationInfo.dirName = iterationInfo.absoluteFullPath;

        //process subtree recursively
        var subTreeResult = doInterations(options, subIterationInfo);

        //omit empty dirs
        if (_.isEmpty(subTreeResult))
            return;

        //add to the list or to the subtree
        if (options.mode === 'list') {
            //check uniqueness
            _.forEach(subTreeResult, function (value, index) {
                if (options.useVersions === true) {
                    modules[index] = modules[index] || {};
                    _.forEach(value, function (versionValue, versionIndex) {
                        if (modules[index][versionIndex])
                            throw new Error("Identity '" + index + "' with version '" + versionIndex + "' is already registered by module at '" + modules[index][versionIndex].absoluteFullPath + "'");
                        modules[index][versionIndex] = versionValue;
                    });
                }
                else {
                    if (modules[index])
                        throw new Error("Identity '" + index + "' is already registered by module at '" + modules[index].absoluteFullPath + "'");
                    modules[index] = value;
                }
            })
        }
        else if (options.mode === 'tree') {
            if (options.markDirectories !== false) {
                subTreeResult.isDirectory = true;
            }

            var identity = generateIdentity(options, iterationInfo);
            modules[identity] = subTreeResult;
        }
        else
            throw new Error('Unknown mode');
    };

    return self;
}
191522
def from_dict(cls, ctx):
        ''
        ctx = Context(ctx)
        s = cls()
        ContextFlags = ctx['ContextFlags']
        s.ContextFlags = ContextFlags
        for key in cls._others:
            if key != 'VectorRegister':
                setattr(s, key, ctx[key])
            else:
                w = ctx[key]
                v = (M128A * len(w))()
                i = 0
                for x in w:
                    y = M128A()
                    y.High = x >> 64
                    y.Low = x - (x >> 64)
                    v[i] = y
                    i += 1
                setattr(s, key, v)
        if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL:
            for key in cls._control:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER:
            for key in cls._integer:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS:
            for key in cls._segments:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
            for key in cls._debug:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_MMX_REGISTERS) == CONTEXT_MMX_REGISTERS:
            xmm = s.FltSave.xmm
            for key in cls._mmx:
                y = M128A()
                y.High = x >> 64
                y.Low = x - (x >> 64)
                setattr(xmm, key, y)
        return s
492584
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'configuration_id' in _dict:
            args['configuration_id'] = _dict.get('configuration_id')
        if 'name' in _dict:
            args['name'] = _dict.get('name')
        else:
            raise ValueError(
                'Required property \'name\' not present in Configuration JSON')
        if 'created' in _dict:
            args['created'] = string_to_datetime(_dict.get('created'))
        if 'updated' in _dict:
            args['updated'] = string_to_datetime(_dict.get('updated'))
        if 'description' in _dict:
            args['description'] = _dict.get('description')
        if 'conversions' in _dict:
            args['conversions'] = Conversions._from_dict(
                _dict.get('conversions'))
        if 'enrichments' in _dict:
            args['enrichments'] = [
                Enrichment._from_dict(x) for x in (_dict.get('enrichments'))
            ]
        if 'normalizations' in _dict:
            args['normalizations'] = [
                NormalizationOperation._from_dict(x)
                for x in (_dict.get('normalizations'))
            ]
        if 'source' in _dict:
            args['source'] = Source._from_dict(_dict.get('source'))
        return cls(**args)
547351
def kwargs(self, obj, kwargs):
        '''
        
        '''
        if hasattr(obj, "KWARGS"):
            for module_argument in obj.KWARGS:
                if has_key(kwargs, module_argument.name):
                    arg_value = kwargs[module_argument.name]
                else:
                    arg_value = copy(module_argument.default)

                setattr(obj, module_argument.name, arg_value)

            for (k, v) in iterator(kwargs):
                if not hasattr(obj, k):
                    setattr(obj, k, v)
        else:
            raise Exception("binwalk.core.module.Modules.process_kwargs: %s has no attribute 'KWARGS'" % str(obj))
200784
def map_constructor(self, loader,  node, deep=False):
        
        mapping = {}
        for key_node, value_node in node.value:
            key = loader.construct_object(key_node, deep=deep)
            value = loader.construct_object(value_node, deep=deep)
            if key in mapping:
                raise ValueError(f"Duplicate key: \"{key}\"")
            mapping[key] = value

        return mapping
1100184
def _construct_direct(cls, variables, coord_names, dims, attrs=None,
                          indexes=None, encoding=None, file_obj=None):
        
        obj = object.__new__(cls)
        obj._variables = variables
        obj._coord_names = coord_names
        obj._dims = dims
        obj._indexes = indexes
        obj._attrs = attrs
        obj._file_obj = file_obj
        obj._encoding = encoding
        obj._initialized = True
        return obj
384732
function( name, options, callback ) {
		var self = this;

		// Can only create sub modules if this modules isn't finished
		self.requireMaxState( munit.ASSERT_STATE_ACTIVE, self.module );

		// Module creation is done on the main object (pass this modules prefix path)
		return munit._module( name, options, callback, { nsprefix: self.nsPath } );
	}