Return a module instance for the modules manager

    :param mod_conf: the module properties as defined globally in this file
    :return:
549304
def get_instance(mod_conf):
    
    logger.info("Giving an instance of %s for alias: %s",
                mod_conf.python_name, mod_conf.module_alias)

    return InnerMetrics(mod_conf)
318320
function createModuleConfig(loader) {
	var tmp = require("tmp");
	var config = {};
	var virtualModules = loader.virtualModules || {};
	for(var moduleName in virtualModules) {
		var filename = tmp.fileSync().name;
		var source = virtualModules[moduleName];
		fs.writeFileSync(filename, source, "utf8");

		var paths = config.paths = config.paths || {};
		paths[moduleName] = "file:"+filename;
	}
	return config;
}
445031
def import_mod(mod_name:str, ignore_errors=False):
    ""
    splits = str.split(mod_name, '.')
    try:
        if len(splits) > 1 : mod = importlib.import_module('.' + '.'.join(splits[1:]), splits[0])
        else: mod = importlib.import_module(mod_name)
        return mod
    except:
        if not ignore_errors: print(f"Module {mod_name} doesn't exist.")
938331
def module2md(self, module):
        
        modname = module.__name__
        path = self.get_src_path(module, append_base=False)
        path = "[{}]({})".format(path, os.path.join(self.github_link, path))
        found = set()

        classes = []
        line_nos = []
        for name, obj in getmembers(module, inspect.isclass):
            # handle classes
            found.add(name)
            if not name.startswith("_") and hasattr(obj, "__module__") and obj.__module__ == modname:
                classes.append(self.class2md(obj))
                line_nos.append(self.get_line_no(obj) or 0)
        classes = order_by_line_nos(classes, line_nos)

        # Since functions can have multiple aliases.
        func2names = defaultdict(list)
        for name, obj in getmembers(module, inspect.isfunction):
            func2names[obj].append(name)

        functions = []
        line_nos = []
        for obj in func2names:
            names = func2names[obj]
            found.update(names)

            # Include if within module or included modules within __init__.py and exclude from global variables
            is_module_within_init = '__init__.py' in path and obj.__module__.startswith(modname)
            if is_module_within_init:
                found.add(obj.__module__.replace(modname + '.', ''))

            if hasattr(obj, "__module__") and (obj.__module__ == modname or is_module_within_init):
                names = list(filter(lambda name: not name.startswith("_"), names))
                if len(names) > 0:
                    functions.append(self.func2md(obj, names=names))
                    line_nos.append(self.get_line_no(obj) or 0)
        functions = order_by_line_nos(functions, line_nos)

        variables = []
        line_nos = []
        for name, obj in module.__dict__.items():
            if not name.startswith("_") and name not in found:
                if hasattr(obj, "__module__") and obj.__module__ != modname:
                    continue
                if hasattr(obj, "__name__") and not obj.__name__.startswith(modname):
                    continue

                comments = inspect.getcomments(obj)
                comments = ": %s" % comments if comments else ""
                variables.append("- **%s**%s" % (name, comments))
                line_nos.append(self.get_line_no(obj) or 0)

        variables = order_by_line_nos(variables, line_nos)
        if variables:
            new_list = ["**Global Variables**", "---------------"]
            new_list.extend(variables)
            variables = new_list

        string = MODULE_TEMPLATE.format(path=path,
                                        global_vars="\n".join(variables) if variables else "",
                                        functions="\n".join(functions) if functions else "",
                                        classes="".join(classes) if classes else "")
        return string
116416
def _mod_info(modname, toskip=[], onlylocals=True):
    

    hascls = hasfunc = False

    for localnm, fqnm, obj in zip(*find_mod_objs(modname, onlylocals=onlylocals)):
        if localnm not in toskip:
            hascls = hascls or inspect.isclass(obj)
            hasfunc = hasfunc or inspect.isroutine(obj)
            if hascls and hasfunc:
                break

    # find_mod_objs has already imported modname
    # TODO: There is probably a cleaner way to do this, though this is pretty
    # reliable for all Python versions for most cases that we care about.
    pkg = sys.modules[modname]
    ispkg = (hasattr(pkg, '__file__') and isinstance(pkg.__file__, str) and
             os.path.split(pkg.__file__)[1].startswith('__init__.py'))

    return ispkg, hascls, hasfunc
455614
def get_module_parser(mod, modname, parents=[], add_help=True):
    
    return argparse.ArgumentParser(
        usage=configuration.EXECUTABLE_NAME + ' ' + modname + ' [options]',
        description=mod.get_description(), parents=parents,
        add_help=add_help)
571689
def load_missing_constant(from_mod, const_name)
      log_call from_mod, const_name
      if from_mod == Kernel
        if ::Object.const_defined?(const_name)
          log "Returning Object::#{const_name} for Kernel::#{const_name}"
          return ::Object.const_get(const_name)
        else
          log "Substituting Object for Kernel"
          from_mod = Object
        end
      end

      # If we have an anonymous module, all we can do is attempt to load from Object.
      from_mod = Object if from_mod.name.blank?

      unless qualified_const_defined?(from_mod.name) && from_mod.name.constantize.object_id == from_mod.object_id
        raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
      end

      raise ArgumentError, "#{from_mod} is not missing constant #{const_name}!" if uninherited_const_defined?(from_mod, const_name)

      qualified_name = qualified_name_for from_mod, const_name
      path_suffix = qualified_name.underscore
      name_error = NameError.new("uninitialized constant #{qualified_name}")

      file_path = search_for_file(path_suffix)
      if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load
        require_or_load file_path
        raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless uninherited_const_defined?(from_mod, const_name)
        return from_mod.const_get(const_name)
      elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
        return mod
      elsif (parent = from_mod.parent) && parent != from_mod &&
            ! from_mod.parents.any? { |p| uninherited_const_defined?(p, const_name) }
        # If our parents do not have a constant named +const_name+ then we are free
        # to attempt to load upwards. If they do have such a constant, then this
        # const_missing must be due to from_mod::const_name, which should not
        # return constants from from_mod's parents.
        begin
          return parent.const_missing(const_name)
        rescue NameError => e
          raise unless e.missing_name? qualified_name_for(parent, const_name)
          raise name_error
        end
      else
        raise name_error
      end
    end
323947
def extract_conf_from(mod, conf=ModuleConfig(CONF_SPEC), depth=0, max_depth=2):
    

    # extract config keys from module or object
    for key, default_value in six.iteritems(conf):
        conf[key] = _get_key_from_module(mod, key, default_value)

    # support for recursive dependecies
    try:
        filtered_apps = [app for app in conf['apps'] if app not in BLACKLIST]
    except TypeError:
        pass
    except Exception as e:
        warnings.warn('Error %s during loading %s' % (e, conf['apps']))

    for app in filtered_apps:
        try:
            app_module = import_module(app)
            if app_module != mod:
                app_module = _get_correct_module(app_module)
                if depth < max_depth:
                    mod_conf = extract_conf_from(app_module, depth=depth+1)
                    for k, v in six.iteritems(mod_conf):
                        # prevent config duplicity
                        # skip config merge
                        if k == 'config':
                            continue
                        if isinstance(v, dict):
                            conf[k].update(v)
                        elif isinstance(v, (list, tuple)):
                            conf[k] = merge(conf[k], v)
        except Exception as e:
            pass  # swallow, but maybe log for info what happens
    return conf
704021
def _set_persistent_module(mod):
    '''
    
    '''
    if not mod or mod in mod_list(True) or mod not in \
            available():
        return set()
    __salt__['file.append'](_LOADER_CONF, _LOAD_MODULE.format(mod))
    return set([mod])
198884
def _getModules(self):
        
        modules = {}
        modulesPath = os.path.join("application", "module")
        moduleList = os.listdir(modulesPath)

        for moduleName in moduleList:
            modulePath = os.path.join(modulesPath, moduleName, "module.py")
            if not os.path.isfile(modulePath):
                continue

            # importing module
            moduleSpec = importlib.util.spec_from_file_location(
                moduleName,
                modulePath
            )
            module = importlib.util.module_from_spec(moduleSpec)
            moduleSpec.loader.exec_module(module)

            # initializing module
            moduleInstance = module.Module(self)
            modules[moduleName] = moduleInstance

        return modules
770948
private function get_mod_instance($cmid) {
        global $DB;
        $rec = $DB->get_record_sql("SELECT md.name
                               FROM {course_modules} cm,
                                    {modules} md
                               WHERE cm.id = ? AND
                                     md.id = cm.module", array($cmid));

        if ($rec) {
            return get_coursemodule_from_id($rec->name, $cmid);
        } else {
            return null;
        }
    }
1147054
def module_for(args)
      registry = self
      mod = Module.new

      args.each do |visibility, exports|
        exports.each do |dependency_name, method_name|
          # equivalent to (e.g.):
          #
          #   def foo
          #     registry.fetch(:foo)
          #   end
          mod.send(:define_method, method_name) do
            registry.fetch(dependency_name)
          end

          # equivalent to (e.g.):
          #
          #   private :foo
          mod.send(visibility, method_name)
        end
      end

      mod
    end
241774
private JsonObject loadModuleConfig(ModuleIdentifier modID, File modJsonFile) {
    try (@SuppressWarnings("resource") Scanner scanner = new Scanner(modJsonFile, "UTF-8").useDelimiter("\\A")) {
      return new JsonObject(scanner.next());
    } catch (FileNotFoundException e) {
      throw new PlatformManagerException("Module " + modID + " does not contains a mod.json file");
    } catch (NoSuchElementException e) {
      throw new PlatformManagerException("Module " + modID + " contains an empty mod.json");
    } catch (DecodeException e) {
      throw new PlatformManagerException("Module " + modID + " mod.json contains invalid json");
    }
  }
1007717
public static ModuleConfig getModuleConfig( String modulePath, ServletContext context )
    {
        return ( ModuleConfig ) context.getAttribute( Globals.MODULE_KEY + modulePath );
    }
1030270
def identify_module(arg):
    
    try:
        __import__(arg)
    except Exception:
        exc = sys.exc_info()[1]
        raise ModuleNotFound("%s: %s" % (type(exc).__name__, str(exc)))

    mod = sys.modules[arg]
    return mod
1205041
def instantiate_client(self, config):
        
        modules = config.module.split('.')
        class_name = modules.pop()
        module_path = '.'.join(modules)

        client_instance = getattr(
            __import__(module_path, {}, {}, ['']),
            class_name
        )()

        client_instance.add_config(config)

        return client_instance
403848
def load(mod, persist=False):
    '''
    
    '''
    pre_mods = lsmod()
    res = __salt__['cmd.run_all']('modprobe {0}'.format(mod), python_shell=False)
    if res['retcode'] == 0:
        post_mods = lsmod()
        mods = _new_mods(pre_mods, post_mods)
        persist_mods = set()
        if persist:
            persist_mods = _set_persistent_module(mod)
        return sorted(list(mods | persist_mods))
    else:
        return 'Error loading module {0}: {1}'.format(mod, res['stderr'])