Access the module's instance.  The callback
runs asynchronously, once the necessary
code has downloaded.
337247
public static void createAsync(final TemplateBasedViewBuilderClient client) {
        GWT.runAsync(new RunAsyncCallback() {
            public void onFailure(Throwable err) {
                client.onUnavailable();
                throw new IllegalStateException(err);
            }

            public void onSuccess() {
                GWTVizPlot.createAsync(new GWTVizPlot.GWTVizPlotClient() {
                    @Override
                    public void onSuccess(GWTVizPlot gwtVizPlot) {
                        if (instance == null) {
                            instance = new TemplateBasedViewBuilder(gwtVizPlot);
                        }
                        client.onSuccess(instance);
                    }

                    @Override
                    public void onUnavailable() {
                        throw new IllegalStateException("unable to load plotter");
                    }
                });


            }
        });
    }
51613
def instantiate(self):
        
        if self.instance is None:
            self.instance = checked_call(self.cls, self.kwds)
        #endif
        try:
            self.instance.yaml_src = self.yaml_src
        except AttributeError:
            pass
        return self.instance
726844
def scan(self, callback=None):
        
        def scan_finished():
            """
            Callback when scan is finished
            """
            time.sleep(3)
            logging.info('Scan finished')
            self._nb_of_modules_loaded = 0

            def module_loaded():
                self._nb_of_modules_loaded += 1
                if self._nb_of_modules_loaded >= len(self._modules):
                    callback()
            for module in self._modules:
                self._modules[module].load(module_loaded)
        for address in range(0, 256):
            message = velbus.ModuleTypeRequestMessage(address)
            if address == 255:
                self.send(message, scan_finished)
            else:
                self.send(message)
497281
function () {
        function checkUpdate() {
            var current = module.exports.current();
            if (current !== last) {
                last = current;
                events.trigger('update', current);
            }
        }

        // Do not run unless breakpoints are available.
        if (!running && breakpoints.length) {
            running = true;
            global.addEventListener('resize', function () {
                if (!working) {
                    working = true;
                    global.requestAnimationFrame(function () {
                        checkUpdate();
                        working = false;
                    });
                }
            });
        }
        checkUpdate();
    }
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);

}
804111
def _init():
    
    # If there is a context and it is initialized to this request,
    # return, otherwise reinitialize the _local_context.
    if (hasattr(_local_context, '_initialized') and
            _local_context._initialized == os.environ.get('REQUEST_ID_HASH')):
        return

    # Used to track the context object stack.
    _local_context.registry = []

    # Used to provide easy access to the currently running Async job.
    _local_context._executing_async_context = None
    _local_context._executing_async = []

    # So that we do not inadvertently reinitialize the local context.
    _local_context._initialized = os.environ.get('REQUEST_ID_HASH')

    return _local_context
244685
def run(self):
        
        if self._py3_wrapper.running:
            cache_time = None
            # execute each method of this module
            for meth, obj in self.methods.items():
                my_method = self.methods[meth]

                # always check py3status is running
                if not self._py3_wrapper.running:
                    break

                # respect the cache set for this method
                if time() < obj["cached_until"]:
                    if not cache_time or obj["cached_until"] < cache_time:
                        cache_time = obj["cached_until"]
                    continue

                try:
                    # execute method and get its output
                    method = getattr(self.module_class, meth)
                    if my_method["call_type"] == self.PARAMS_NEW:
                        # new style modules
                        response = method()
                    else:
                        # legacy modules had parameters passed
                        response = method(
                            self.i3status_thread.json_list,
                            self.config["py3_config"]["general"],
                        )

                    if isinstance(response, dict):
                        # this is a shiny new module giving a dict response
                        result = response
                    elif isinstance(response, tuple):
                        # this is an old school module reporting its position
                        position, result = response
                        if not isinstance(result, dict):
                            raise TypeError("response should be a dict")
                    else:
                        raise TypeError("response should be a dict")

                    if isinstance(response.get("full_text"), (list, Composite)):
                        response["composite"] = response["full_text"]
                        del response["full_text"]
                    if "composite" in response:
                        self.process_composite(response)
                    else:
                        # validate the response
                        if "full_text" not in result:
                            err = 'missing "full_text" key in response'
                            raise KeyError(err)
                        # Remove any none color from our output
                        if hasattr(result.get("color"), "none_setting"):
                            del result["color"]
                        # remove urgent if not allowed
                        if not self.allow_urgent and "urgent" in result:
                            del result["urgent"]
                        # set universal module options in result
                        result.update(self.i3bar_module_options)

                    result["instance"] = self.module_inst
                    result["name"] = self.module_name

                    # initialize method object
                    if my_method["name"] is None:
                        my_method["name"] = result["name"]
                        if "instance" in result:
                            my_method["instance"] = result["instance"]
                        else:
                            my_method["instance"] = result["name"]

                    # update method object cache
                    if "cached_until" in result:
                        cached_until = result["cached_until"]
                        # remove this so we can check later for output changes
                        del result["cached_until"]
                    else:
                        # get module default cached_until
                        cached_until = self.module_class.py3.time_in()
                    my_method["cached_until"] = cached_until
                    if not cache_time or cached_until < cache_time:
                        cache_time = cached_until

                    # update method object output
                    if "composite" in response:
                        my_method["last_output"] = result["composite"]
                    else:
                        my_method["last_output"] = result

                    # debug info
                    if self.config["debug"]:
                        self._py3_wrapper.log(
                            "method {} returned {} ".format(meth, result)
                        )
                    # module working correctly so ensure module works as
                    # expected
                    self.allow_config_clicks = True
                    self.error_messages = None
                    self.error_hide = False

                    # mark module as updated
                    self.set_updated()

                except ModuleErrorException as e:
                    # module has indicated that it has an error
                    self.runtime_error(e.msg, meth)
                    if e.timeout:
                        if e.timeout is PY3_CACHE_FOREVER:
                            cache_time = PY3_CACHE_FOREVER
                        else:
                            cache_time = time() + e.timeout
                    else:
                        cache_time = time() + getattr(
                            self.module_class,
                            "cache_timeout",
                            self.config["cache_timeout"],
                        )

                except Exception as e:
                    msg = "Instance `{}`, user method `{}` failed"
                    msg = msg.format(self.module_full_name, meth)
                    if not self.testing:
                        self._py3_wrapper.report_exception(msg, notify_user=False)
                    # added error
                    self.runtime_error(str(e) or e.__class__.__name__, meth)
                    cache_time = time() + getattr(
                        self.module_class, "cache_timeout", self.config["cache_timeout"]
                    )

            if cache_time is None:
                cache_time = time() + self.config["cache_timeout"]
            self.cache_time = cache_time
            # new style modules can signal they want to cache forever
            if cache_time == PY3_CACHE_FOREVER:
                return
            # don't be hasty mate
            # set timeout to do update next time one is needed
            if not cache_time:
                cache_time = time() + self.config["minimum_interval"]

            self._py3_wrapper.timeout_queue_add(self, cache_time)
656763
def instance(self, *args, **kwargs):
        
        mod, cls = self.get_module_class()
        inst = cls(*args, **kwargs)
        logger.debug(f'inst: {inst}')
        return inst
1161511
function() {
        if (this.layer.async) {
            // Asynchronous image requests call the asynchronous getURL method
            // on the layer to fetch an image that covers 'this.bounds'.
            var id = this.asyncRequestId = (this.asyncRequestId || 0) + 1;
            this.layer.getURLasync(this.bounds, function(url) {
                if (id == this.asyncRequestId) {
                    this.url = url;
                    this.initImage();
                }
            }, this);
        } else {
            // synchronous image requests get the url immediately.
            this.url = this.layer.getURL(this.bounds);
            this.initImage();
        }
    }
1318525
function fetchGetModule(data, callback) {
    var fullModuleName = data.moduleName;

    // try and load the module the old way...
    console.log("loadModule("+fullModuleName+")");

    var urls = []; // Array of where to look for this module
    var modName; // Simple name of the module
    if(Espruino.Core.Utils.isURL(fullModuleName)) {
      modName = fullModuleName.substr(fullModuleName.lastIndexOf("/") + 1).split(".")[0];
      urls = [ fullModuleName ];
    } else {
      modName = fullModuleName;
      Espruino.Config.MODULE_URL.split("|").forEach(function (url) {
        url = url.trim();
        if (url.length!=0)
        Espruino.Config.MODULE_EXTENSIONS.split("|").forEach(function (extension) {
          urls.push(url + "/" + fullModuleName + extension);
        })
      });
    };

    // Recursively go through all the urls
    (function download(urls) {
      if (urls.length==0) {
        return callback(data);
      }
      var dlUrl = urls[0];
      Espruino.Core.Utils.getURL(dlUrl, function (code) {
        if (code!==undefined) {
          // we got it!
          data.moduleCode = code;
          data.isMinified = dlUrl.substr(-7)==".min.js";
          return callback(data);
        } else {
          // else try next
          download(urls.slice(1));
        }
      });
    })(urls);
  }
180358
def fetch
      requests = instantiate_modules.select(&:fetch?).map(&:requests).flatten

      total, done = requests.size, 0
      update_progress(total, done)

      before_fetch

      backend.new(requests).run do
        update_progress(total, done += 1)
      end

      after_fetch

      true
    rescue => e
      error(e)
      raise e
    end
1122965
function () {
            if (this._isProcessing) {
                return;
            }
            this.$assert(33, this._logicalPaths.length > 0);
            this._isProcessing = true;
            (require("./IO")).asyncRequest({
                sender : {
                    classpath : this.$classpath,
                    logicalPaths : this._logicalPaths
                },
                url : require("./DownloadMgr").getURLWithTimestamp(this._url), // add a timestamp to the URL if
                // required
                callback : {
                    fn : this._onFileReceive,
                    onerror : this._onFileReceive,
                    scope : this
                },
                expectedResponseType : "text"
            });
        }
1359919
def _get_calling_module(self):
        
        for frame in inspect.stack():
            mod = inspect.getmodule(frame[0])
            logger.debug(f'calling module: {mod}')
            if mod is not None:
                mod_name = mod.__name__
                if mod_name != __name__:
                    return mod
762884
def _watch_callback(obj_weakref, method_name, *args, **kwargs):
    
    obj = obj_weakref()
    if obj is None:
        return
    getattr(obj, method_name)(*args, **kwargs)
526147
def download_object(self, object_name):
        
        return self._client.download_object(
            self._instance, self.name, object_name)
1122101
def init():
    
    loop = asyncio.get_event_loop()
    if loop.is_running():
        raise Exception("You must initialize the Ray async API by calling "
                        "async_api.init() or async_api.as_future(obj) before "
                        "the event loop starts.")
    else:
        asyncio.get_event_loop().run_until_complete(_async_init())
552055
def run_callback(self):
        

        if self._callback_func is not None:
            try:
                self._callback_func(self._request, self._result)
            except Exception:  # pylint: disable=broad-except
                LOGGER.exception('An unhandled error occurred while running '
                                 'future callback')