Load a module if it exists
@param path
@param moduleStack
@param errMsg
@returns {*}
334667
function loadIfExists(path, moduleStack, errMsg) {
        var servicesDir = this.injector.servicesDir;
        var servicesFullPath = this.injector.rootDir + '/' + servicesDir;

        // if the file doesn't exist, either throw an error (if msg passed in), else just return null
        if (!fs.existsSync(p.join(servicesFullPath, path + '.js'))) {
            if (errMsg) {
                throw new Error(errMsg + ' ' + servicesFullPath + path + '.js');
            }
            else {
                return null;
            }
        }

        // else load the module
        return this.injector.loadModule(servicesDir + path, moduleStack);
    }
1011310
def get_module(app, modname, verbose=False, failfast=False):
    
    module_name = '%s.%s' % (app, modname)
    try:
        module = import_module(module_name)
    except ImportError as e:
        if failfast:
            raise e
        elif verbose:
            print("Could not load %r from %r: %s" % (modname, app, e))
        return None
    if verbose:
        print("Loaded %r from %r" % (modname, app))
    return module
63793
def load_module(path):
    '''
        
    '''
    with add_to_path(os.path.dirname(path)):
        spec    = importlib.util.spec_from_file_location(os.path.basename(path).replace('.py',''), path)
        module  = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
    return module
1088347
def _load_module(module):
    
    modclass = type(module)
    # We only take care of our own LazyModule instances
    if not issubclass(modclass, LazyModule):
        raise TypeError("Passed module is not a LazyModule instance.")
    with _ImportLockContext():
        parent, _, modname = module.__name__.rpartition('.')
        logger.debug("loading module {}".format(modname))
        # We first identify whether this is a loadable LazyModule, then we
        # strip as much of lazy_import behavior as possible (keeping it cached,
        # in case loading fails and we need to reset the lazy state).
        if not hasattr(modclass, '_lazy_import_error_msgs'):
            # Alreay loaded (no _lazy_import_error_msgs attr). Not reloading.
            return
        # First, ensure the parent is loaded (using recursion; *very* unlikely
        # we'll ever hit a stack limit in this case).
        modclass._LOADING = True
        try:
            if parent:
                logger.debug("first loading parent module {}".format(parent))
                setattr(sys.modules[parent], modname, module)
            if not hasattr(modclass, '_LOADING'):
                logger.debug("Module {} already loaded by the parent"
                             .format(modname))
                # We've been loaded by the parent. Let's bail.
                return
            cached_data = _clean_lazymodule(module)
            try:
                # Get Python to do the real import!
                reload_module(module)           
            except:
                # Loading failed. We reset our lazy state.
                logger.debug("Failed to load module {}. Resetting..."
                             .format(modname))
                _reset_lazymodule(module, cached_data)
                raise
            else:
                # Successful load
                logger.debug("Successfully loaded module {}".format(modname))
                delattr(modclass, '_LOADING')
                _reset_lazy_submod_refs(module)

        except (AttributeError, ImportError) as err:
            logger.debug("Failed to load {}.\n{}: {}"
                         .format(modname, err.__class__.__name__, err))
            logger.lazy_trace()
            # Under Python 3 reloading our dummy LazyModule instances causes an
            # AttributeError if the module can't be found. Would be preferrable
            # if we could always rely on an ImportError. As it is we vet the
            # AttributeError as thoroughly as possible.
            if ((six.PY3 and isinstance(err, AttributeError)) and not
                err.args[0] == "'NoneType' object has no attribute 'name'"):
                # Not the AttributeError we were looking for.
                raise
            msg = modclass._lazy_import_error_msgs['msg']
            raise_from(ImportError(
                msg.format(**modclass._lazy_import_error_strings)), None)
401838
function loadViewModule(path) {
    var Module = module.constructor,
        _module = new Module(path,module);
    _module.load(path);
    return (typeof _module.exports === 'function') ? _module.exports :
        function(context) {
            return extend(_module.exports, context);
        };
}
783704
function create(modulePath, moduleStack) {

        // first check the cache to see if we already loaded it
        if (this.cache[modulePath]) {
            return this.cache[modulePath];
        }

        // try to get the resource for this module
        var resource;
        if (this.resources[modulePath]) {
            resource = this.resources[modulePath];
        }
        else if (this.resourceNames[modulePath]) {
            resource = this.injector.loadModule(this.resourceNames[modulePath] + 'Resource');
        }
        else {
            return null;
        }

        // get the service for this model
        var serviceName = modulePath.substring(0, 1).toLowerCase() + modulePath.substring(1) + 'Service';
        var service = this.injector.loadModule(serviceName, moduleStack);

        // save the model to cache and return it
        var Model = this.getModel(service, resource.mixins);
        this.cache[modulePath] = Model;
        return Model;
    }
1315873
function load(path, callback, errorCallback) {
  try {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", path, true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        if (xhr.status === 200 || xhr.status === 304) {
          try {
            var response = JSON.parse(xhr.responseText);
            callback(response);
          } catch (e) {
            errorCallback(e);
          }
        } else {
          errorCallback(xhr);
        }
      }
    };
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.send();
  } catch (e) {
    errorCallback(e);
  }
}
1025204
function requireMaybe(moduleName) {
  try {
    var modulePath = require.resolve(moduleName);
  } catch (e) {
    return null;
  }
  // just let this fall through
  return require(moduleName);
}
423129
function(parentModule, id, callback) {

  // Try to load the module.
  return Promise.try(function() {
    return parentModule.require(id);
  })
  // Ignore module not found errors, and decorate all others.
  .catch(function(err) {
    if (err.code !== 'MODULE_NOT_FOUND') {
      throw new KboxRequireError(id, err);
    }
  })
  // Return.
  .nodeify(callback);

}
1049198
function requireProxy(path) {
    reset();
    currentModule.require = nodeRequire;
    return nodeRequire.call(currentModule, path);  // node's require only works when "this" points to the module
}
573611
async def loadmodule(self, module):
        '''
        
        '''
        self._logger.debug('Try to load module %r', module)
        if hasattr(module, '_instance'):
            self._logger.debug('Module is already initialized, module state is: %r', module._instance.state)
            if module._instance.state == ModuleLoadStateChanged.UNLOADING or module._instance.state == ModuleLoadStateChanged.UNLOADED:
                # Wait for unload
                um = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.UNLOADED)
                await um
            elif module._instance.state == ModuleLoadStateChanged.SUCCEEDED:
                pass
            elif module._instance.state == ModuleLoadStateChanged.FAILED:
                raise ModuleLoadException('Cannot load module %r before unloading the failed instance' % (module,))
            elif module._instance.state == ModuleLoadStateChanged.NOTLOADED or module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
                # Wait for succeeded or failed
                sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
                fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
                _, m = await M_(sm, fm)
                if m is sm:
                    pass
                else:
                    raise ModuleLoadException('Module load failed for %r' % (module,))
        if not hasattr(module, '_instance'):
            self._logger.info('Loading module %r', module)
            inst = module(self.server)
            # Avoid duplicated loading
            module._instance = inst
            # When reloading, some of the dependencies are broken, repair them
            if hasattr(module, 'referencedBy'):
                inst.dependedBy = set([m for m in module.referencedBy if hasattr(m, '_instance') and m._instance.state != ModuleLoadStateChanged.UNLOADED])
            # Load Module
            for d in module.depends:
                if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.FAILED:
                    raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, d))
            try:
                for d in module.depends:
                    if hasattr(d, '_instance') and d._instance.state == ModuleLoadStateChanged.SUCCEEDED:
                        d._instance.dependedBy.add(module)
                preloads = [d for d in module.depends if not hasattr(d, '_instance') or \
                            d._instance.state != ModuleLoadStateChanged.SUCCEEDED]
                for d in preloads:
                    self.subroutine(self.loadmodule(d), False)
                sms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.SUCCEEDED) for d in preloads]
                fms = [ModuleLoadStateChanged.createMatcher(d, ModuleLoadStateChanged.FAILED) for d in preloads]
                def _callback(event, matcher):
                    raise ModuleLoadException('Cannot load module %r, it depends on %r, which is in failed state.' % (module, event.module))
                await self.with_callback(self.wait_for_all(*sms), _callback, *fms)
            except:
                for d in module.depends:
                    if hasattr(d, '_instance') and module in d._instance.dependedBy:
                        self._removeDepend(module, d)
                self._logger.warning('Loading module %r stopped', module, exc_info=True)
                # Not loaded, send a message to notify that parents can not 
                async def _msg():
                    await self.wait_for_send(ModuleLoadStateChanged(module, ModuleLoadStateChanged.UNLOADED, inst))
                self.subroutine(_msg(), False)
                del module._instance
                raise
            for d in preloads:
                d._instance.dependedBy.add(module)
            self.activeModules[inst.getServiceName()] = module
            await module._instance.changestate(ModuleLoadStateChanged.LOADING, self)
            await module._instance.load(self)
            if module._instance.state == ModuleLoadStateChanged.LOADED or module._instance.state == ModuleLoadStateChanged.LOADING:
                sm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.SUCCEEDED)
                fm = ModuleLoadStateChanged.createMatcher(module._instance.target, ModuleLoadStateChanged.FAILED)
                _, m = await M_(sm, fm)
                if m is sm:
                    pass
                else:
                    raise ModuleLoadException('Module load failed for %r' % (module,))
            self._logger.info('Loading module %r completed, module state is %r', module, module._instance.state)
            if module._instance.state == ModuleLoadStateChanged.FAILED:
                raise ModuleLoadException('Module load failed for %r' % (module,))
235759
function (events) {
        "use strict";
    
        requirejs.onError = function (err) {
    
            if (err.requireType === 'timeout') {
    
                events.trigger('error');
                for (var i in err.requireModules) {
                    requirejs.undef(err.requireModules[i]);
                }
    
                // try again loading modules
                require(err.requireModules, function () {
                    events.trigger('retried');
                });
    
            }
            else {
                console.log(err.stack);
            }
    
        };
    
    }
1108204
function require(path) {
  var module = require.modules[path];
  if(!module) {
    throw("couldn't find module for: " + path);
  }
  if(!module.exports) {
    module.exports = {};
    module.call(module.exports, module, module.exports, require.bind(path));
  }
  return module.exports;
}
923620
async def unload_by_path(self, path):
        
        p, module = findModule(path, False)
        if module is None:
            raise ModuleLoadException('Cannot find module: ' + repr(path))
        return await self.unloadmodule(module)
397563
function loaded(err)
  {
    if(err)
    {
      log.error(err);
      cbMesh(err);
      return false;
    }

    return telehash.mesh(args, function(err, mesh){
      if(!mesh) return cbMesh(err);

      // sync links automatically to file whenever they change
      if(linksFile) mesh.linked(function(json, str){
        log.debug('syncing links json',linksFile,str.length);
        fs.writeFileSync(linksFile, str);
      });

      cbMesh(err, mesh);
    });
  }
814031
function(parentModule, kbox, id, app, callback) {

  if (typeof callback === 'undefined' && typeof app === 'function') {
    callback = app;
    app = undefined;
  }

  // Try to load module from node_module directories.
  return requireFromNodeModules(parentModule, id)
  // If module was not found in node_module directories, try to load
  // from other directories.
  .then(function(mod) {
    if (mod) {
      return mod;
    } else {
      return requireFromOtherDirs(kbox, id, app);
    }
  })
  // Return.
  .nodeify(callback);

}
1329196
function preloadRequire (module) {
  if (loadedModules.has(module)) {
    return loadedModules.get(module)
  }
  throw new Error(`module not found: ${module}`)
}