code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
objc = ctypes.cdll.LoadLibrary(find_library('objc'))
objc.objc_getClass.restype = ctypes.c_void_p
objc.sel_registerName.restype = ctypes.c_void_p
objc.objc_msgSend.restype = ctypes.c_void_p
objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
return objc | def _default_objc(self) | Load the objc library using ctypes. | 1.713159 | 1.52693 | 1.121963 |
objc = self.objc
ENBridge = objc.objc_getClass('ENBridge')
return objc.objc_msgSend(ENBridge, objc.sel_registerName('instance')) | def _default_bridge(self) | Get an instance of the ENBridge object using ctypes. | 5.885173 | 3.666495 | 1.605122 |
objc = self.objc
bridge = self.bridge
#: This must come after the above as it changes the arguments!
objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_char_p, ctypes.c_int]
objc.objc_msgSend(
bridge, objc.sel_registerName('processEvents:length:'),
data, len(data)) | def processEvents(self, data) | Sends msgpack data to the ENBridge instance
by calling the processEvents method via ctypes. | 4.684947 | 4.257049 | 1.100515 |
if change['type'] == 'event' and self.proxy_is_active:
self.proxy.set_opened(change['name'] == 'show')
else:
super(ActionMenuView, self)._update_proxy(change) | def _update_proxy(self, change) | An observer which sends the state change to the proxy. | 6.014739 | 5.346504 | 1.124985 |
current = getattr(IOLoop._current, "instance", None)
if current is None and instance:
current = None
#if asyncio is not None:
# from tornado.platform.asyncio import AsyncIOLoop, AsyncIOMainLoop
# if IOLoop.configured_class() is AsyncIOLoop:
# current = AsyncIOMainLoop()
if current is None:
if sys.platform == 'darwin':
from .platforms import KQueueIOLoop
current = KQueueIOLoop()
else:
from .platforms import EPollIOLoop
current = EPollIOLoop()
current.initialize()
#current = IOLoop()
if IOLoop._current.instance is not current:
raise RuntimeError("new IOLoop did not become current")
return current | def current(instance=True) | Returns the current thread's `IOLoop`.
If an `IOLoop` is currently running or has been marked as
current by `make_current`, returns that instance. If there is
no current `IOLoop` and ``instance`` is true, creates one.
.. versionchanged:: 4.1
Added ``instance`` argument to control the fallback to
`IOLoop.instance()`.
.. versionchanged:: 5.0
The ``instance`` argument now controls whether an `IOLoop`
is created automatically when there is none, instead of
whether we fall back to `IOLoop.instance()` (which is now
an alias for this method) | 3.530514 | 3.728077 | 0.947007 |
gen_log.warning('IOLoop blocked for %f seconds in\n%s',
self._blocking_signal_threshold,
''.join(traceback.format_stack(frame))) | def log_stack(self, signal, frame) | Signal handler to log the stack trace of the current thread.
For use with `set_blocking_signal_threshold`. | 12.149036 | 7.721684 | 1.573366 |
future_cell = [None]
def run():
try:
result = func()
if result is not None:
from .gen import convert_yielded
result = convert_yielded(result)
except Exception:
future_cell[0] = TracebackFuture()
future_cell[0].set_exc_info(sys.exc_info())
else:
if is_future(result):
future_cell[0] = result
else:
future_cell[0] = TracebackFuture()
future_cell[0].set_result(result)
self.add_future(future_cell[0], lambda future: self.stop())
self.add_callback(run)
if timeout is not None:
timeout_handle = self.add_timeout(self.time() + timeout, self.stop)
self.start()
if timeout is not None:
self.remove_timeout(timeout_handle)
if not future_cell[0].done():
raise TimeoutError('Operation timed out after %s seconds' % timeout)
return future_cell[0].result() | def run_sync(self, func, timeout=None) | Starts the `IOLoop`, runs the given function, and stops the loop.
The function must return either a yieldable object or
``None``. If the function returns a yieldable object, the
`IOLoop` will run until the yieldable is resolved (and
`run_sync()` will return the yieldable's result). If it raises
an exception, the `IOLoop` will stop and the exception will be
re-raised to the caller.
The keyword-only argument ``timeout`` may be used to set
a maximum duration for the function. If the timeout expires,
a `tornado.util.TimeoutError` is raised.
This method is useful in conjunction with `tornado.gen.coroutine`
to allow asynchronous calls in a ``main()`` function::
@gen.coroutine
def main():
# do stuff...
if __name__ == '__main__':
IOLoop.current().run_sync(main)
.. versionchanged:: 4.3
Returning a non-``None``, non-yieldable value is now an error. | 2.466401 | 2.350971 | 1.049099 |
if isinstance(deadline, numbers.Real):
return self.call_at(deadline, callback, *args, **kwargs)
elif isinstance(deadline, datetime.timedelta):
return self.call_at(self.time() + timedelta_to_seconds(deadline),
callback, *args, **kwargs)
else:
raise TypeError("Unsupported deadline %r" % deadline) | def add_timeout(self, deadline, callback, *args, **kwargs) | Runs the ``callback`` at the time ``deadline`` from the I/O loop.
Returns an opaque handle that may be passed to
`remove_timeout` to cancel.
``deadline`` may be a number denoting a time (on the same
scale as `IOLoop.time`, normally `time.time`), or a
`datetime.timedelta` object for a deadline relative to the
current time. Since Tornado 4.0, `call_later` is a more
convenient alternative for the relative case since it does not
require a timedelta object.
Note that it is not safe to call `add_timeout` from other threads.
Instead, you must use `add_callback` to transfer control to the
`IOLoop`'s thread, and then call `add_timeout` from there.
Subclasses of IOLoop must implement either `add_timeout` or
`call_at`; the default implementations of each will call
the other. `call_at` is usually easier to implement, but
subclasses that wish to maintain compatibility with Tornado
versions prior to 4.0 must use `add_timeout` instead.
.. versionchanged:: 4.0
Now passes through ``*args`` and ``**kwargs`` to the callback. | 2.47719 | 2.218673 | 1.116519 |
return self.call_at(self.time() + delay, callback, *args, **kwargs) | def call_later(self, delay, callback, *args, **kwargs) | Runs the ``callback`` after ``delay`` seconds have passed.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method of the same
name, the returned object does not have a ``cancel()`` method.
See `add_timeout` for comments on thread-safety and subclassing.
.. versionadded:: 4.0 | 3.542999 | 5.52107 | 0.641723 |
return self.add_timeout(when, callback, *args, **kwargs) | def call_at(self, when, callback, *args, **kwargs) | Runs the ``callback`` at the absolute time designated by ``when``.
``when`` must be a number using the same reference point as
`IOLoop.time`.
Returns an opaque handle that may be passed to `remove_timeout`
to cancel. Note that unlike the `asyncio` method of the same
name, the returned object does not have a ``cancel()`` method.
See `add_timeout` for comments on thread-safety and subclassing.
.. versionadded:: 4.0 | 4.732971 | 6.751899 | 0.700984 |
with stack_context.NullContext():
self.add_callback(callback, *args, **kwargs) | def spawn_callback(self, callback, *args, **kwargs) | Calls the given callback on the next IOLoop iteration.
Unlike all other callback-related methods on IOLoop,
``spawn_callback`` does not associate the callback with its caller's
``stack_context``, so it is suitable for fire-and-forget callbacks
that should not interfere with the caller.
.. versionadded:: 4.0 | 5.28485 | 7.682694 | 0.68789 |
assert is_future(future)
callback = stack_context.wrap(callback)
future.add_done_callback(
lambda future: self.add_callback(callback, future)) | def add_future(self, future, callback) | Schedules a callback on the ``IOLoop`` when the given
`.Future` is finished.
The callback is invoked with one argument, the
`.Future`. | 4.629739 | 4.726755 | 0.979475 |
try:
ret = callback()
if ret is not None:
from . import gen
# Functions that return Futures typically swallow all
# exceptions and store them in the Future. If a Future
# makes it out to the IOLoop, ensure its exception (if any)
# gets logged too.
try:
ret = gen.convert_yielded(ret)
except gen.BadYieldError:
# It's not unusual for add_callback to be used with
# methods returning a non-None and non-yieldable
# result, which should just be ignored.
pass
else:
self.add_future(ret, self._discard_future_result)
except Exception:
self.handle_callback_exception(callback) | def _run_callback(self, callback) | Runs a callback with error handling.
For use in subclasses. | 8.206632 | 8.328728 | 0.98534 |
if self._error_handler:
self._error_handler(callback)
else:
app_log.error("Exception in callback %r", callback, exc_info=True) | def handle_callback_exception(self, callback) | This method is called whenever a callback run by the `IOLoop`
throws an exception.
By default simply logs the exception as an error. Subclasses
may override this method to customize reporting of exceptions.
The exception itself is not passed explicitly, but is available
in `sys.exc_info`. | 3.91222 | 4.033887 | 0.969839 |
try:
try:
fd.close()
except AttributeError:
os.close(fd)
except OSError:
pass | def close_fd(self, fd) | Utility method to close an ``fd``.
If ``fd`` is a file-like object, we close it directly; otherwise
we use `os.close`.
This method is provided for use by `IOLoop` subclasses (in
implementations of ``IOLoop.close(all_fds=True)`` and should
not generally be used by application code.
.. versionadded:: 4.0 | 3.15136 | 4.341397 | 0.725886 |
super(UiKitControl, self).init_widget()
d = self.declaration
if d.clickable:
#: A really ugly way to add the target
#: would be nice if we could just pass the block pointer here :)
self.get_app().bridge.addTarget(
self.widget,
forControlEvents=UIControl.UIControlEventTouchUpInside,
andCallback=self.widget.getId(),
usingMethod="onClicked",
withValues=[]
)
self.widget.onClicked.connect(self.on_clicked) | def init_widget(self) | Initialize the state of the toolkit widget.
This method is called during the top-down pass, just after the
'create_widget()' method is called. This method should init the
state of the widget. The child widgets will not yet be created.
Note: This does NOT initialize text properties by default! | 15.673599 | 14.652138 | 1.069714 |
d = self.declaration
Snackbar.make(self.parent_widget(), d.text,
0 if d.duration else -2).then(self.on_widget_created) | def create_widget(self) | Create the underlying widget.
A toast is not a subclass of view, hence we don't set name as widget
or children will try to use it as their parent (which crashes). | 15.113091 | 12.483294 | 1.210665 |
if not self.widget:
return
super(AndroidSnackbar, self).init_widget()
d = self.declaration
#: Bind events
self.widget.onClick.connect(self.on_click)
#: Use the custom callback to listen to events
callback = BridgedSnackbarCallback()
callback.setListener(self.widget.getId())
self.widget.onDismissed.connect(self.on_dismissed)
self.widget.onShown.connect(self.on_shown)
self.widget.addCallback(callback)
#: if d.text: #: Set during creation
#: self.set_duration(d.duration) #: Set during creation
if d.action_text:
self.set_action_text(d.action_text)
if d.action_text_color:
self.set_action_text_color(d.action_text_color)
if d.show:
self.set_show(d.show) | def init_widget(self) | Our widget may not exist yet so we have to diverge from the normal
way of doing initialization. See `update_widget` | 4.171269 | 4.156281 | 1.003606 |
d = self.declaration
self.widget = Snackbar(__id__=ref)
self.init_widget() | def on_widget_created(self, ref) | Using Snackbar.make returns async so we have to
initialize it later. | 19.656418 | 9.42444 | 2.085685 |
if duration == 0:
self.widget.setDuration(-2) #: Infinite
else:
self.widget.setDuration(0) | def set_duration(self, duration) | Android for whatever stupid reason doesn't let you set the time
it only allows 1-long or 0-short. So we have to repeatedly call show
until the duration expires, hence this method does nothing see
`set_show`. | 7.132791 | 6.470695 | 1.102322 |
d = self.declaration
self.widget = SeekBar(self.get_context(), None,
d.style or '@attr/seekBarStyle') | def create_widget(self) | Create the underlying widget. | 14.588739 | 11.100181 | 1.314279 |
super(AndroidSeekBar, self).init_widget()
w = self.widget
#: Setup listener
w.setOnSeekBarChangeListener(w.getId())
w.onProgressChanged.connect(self.on_progress_changed) | def init_widget(self) | Initialize the underlying widget. | 7.681277 | 6.576494 | 1.16799 |
d = self.declaration
self.widget = TextView(self.get_context(), None,
d.style or '@attr/textViewStyle') | def create_widget(self) | Create the underlying widget. | 13.412027 | 10.387121 | 1.291217 |
super(AndroidTextView, self).init_widget()
d = self.declaration
w = self.widget
if d.input_type:
self.set_input_type(d.input_type)
w.addTextChangedListener(w.getId())
w.onTextChanged.connect(self.on_text_changed) | def init_widget(self) | Initialize the underlying widget. | 4.561234 | 3.911486 | 1.166113 |
d = self.declaration
if d.input_type == 'html':
text = Spanned(__id__=Html.fromHtml(text))
self.widget.setTextKeepState(text) | def set_text(self, text) | Set the text in the widget. | 18.223825 | 16.011116 | 1.138198 |
d = self.declaration
self.dialog = BottomSheetDialog(self.get_context(), d.style) | def create_widget(self) | Create the underlying widget.
A dialog is not a subclass of view, hence we don't set name as widget
or children will try to use it as their parent. | 15.874882 | 12.848646 | 1.23553 |
if hasattr(obj, '__id__'):
return msgpack.ExtType(ExtType.REF, msgpack.packb(obj.__id__))
return obj | def encode(obj) | Encode an object for proper decoding by Java or ObjC | 5.646602 | 5.759226 | 0.980444 |
obj = CACHE.get(ptr, None)
if obj is None:
raise BridgeReferenceError(
"Reference id={} never existed or has already been destroyed"
.format(ptr))
elif not hasattr(obj, method):
raise NotImplementedError("{}.{} is not implemented.".format(obj,
method))
return obj, getattr(obj, method) | def get_handler(ptr, method) | Dereference the pointer and return the handler method. | 5.939595 | 5.914376 | 1.004264 |
obj.__suppressed__[self.name] = True
yield
obj.__suppressed__[self.name] = False | def suppressed(self, obj) | Suppress calls within this context to avoid feedback loops | 5.168355 | 4.648127 | 1.111922 |
super(UiKitActivityIndicator, self).init_widget()
d = self.declaration
if d.size != 'normal':
self.set_size(d.size)
if d.color:
self.set_color(d.color)
#: Why would you want to stop an activity indicator?
self.widget.startAnimating() | def init_widget(self) | Initialize the state of the toolkit widget.
This method is called during the top-down pass, just after the
'create_widget()' method is called. This method should init the
state of the widget. The child widgets will not yet be created. | 6.567888 | 6.049592 | 1.085675 |
app = AndroidApplication.instance()
f = app.create_future()
def on_permission_result(result):
if not result:
f.set_result(None)
return
def on_ready(m):
m.isWifiEnabled().then(f.set_result)
WifiManager.get().then(on_ready)
#: Check permission
WifiManager.request_permission([
WifiManager.PERMISSION_ACCESS_WIFI_STATE
]).then(on_permission_result)
return f | def is_wifi_enabled(cls) | Check if wifi is currently enabled.
Returns
--------
result: future
A future that resolves with the value. | 4.88647 | 4.583971 | 1.065991 |
app = AndroidApplication.instance()
f = app.create_future()
def on_permission_result(result):
if not result:
#: Permission denied
f.set_result(None)
return
def on_ready(m):
m.setWifiEnabled(state).then(f.set_result)
WifiManager.get().then(on_ready)
#: Check permission
WifiManager.request_permission([
WifiManager.PERMISSION_CHANGE_WIFI_STATE
]).then(on_permission_result)
return f | def set_wifi_enabled(cls, state=True) | Set the wifi enabled state.
Returns
--------
result: future
A future that resolves with whether the operation succeeded. | 4.658221 | 4.511437 | 1.032536 |
app = AndroidApplication.instance()
activity = app.widget
f = app.create_future()
def on_permission_result(result):
if not result:
f.set_result(None)
return
def on_ready(mgr):
#: Register a receiver so we know when the scan
#: is complete
receiver = BroadcastReceiver()
receiver.setReceiver(receiver.getId())
def on_scan_complete(context, intent):
#: Finally, pull the scan results
mgr.getScanResults().then(f.set_result)
#: Cleanup receiver
mgr._receivers.remove(receiver)
activity.unregisterReceiver(receiver)
def on_wifi_enabled(enabled):
if not enabled:
#: Access denied or failed to enable
f.set_result(None)
#: Cleanup receiver
mgr._receivers.remove(receiver)
activity.unregisterReceiver(receiver)
return
#: Hook up a callback that's fired when the scan
#: results are ready
receiver.onReceive.connect(on_scan_complete)
#: Save a reference as this must stay alive
mgr._receivers.append(receiver)
#: Register the receiver
intent_filter = IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
activity.registerReceiver(receiver,
intent_filter)
#: Trigger a scan (which "should" eventually
#: call the on on_scan_complete)
mgr.startScan()
#: Enable if needed
mgr.setWifiEnabled(True).then(on_wifi_enabled)
#: Get the service
WifiManager.get().then(on_ready)
#: Request permissions
WifiManager.request_permission(
WifiManager.PERMISSIONS_REQUIRED).then(on_permission_result)
return f | def get_networks(cls) | Get the wifi networks currently available.
Returns
--------
result: future
A future that resolves with the list of networks available
or None if wifi could not be enabled (permission denied,
etc...) | 4.534926 | 4.271912 | 1.061568 |
app = AndroidApplication.instance()
f = app.create_future()
def on_permission_result(result):
if not result:
f.set_result(None)
return
def on_ready(mgr):
mgr.disconnect().then(f.set_result)
#: Get the service
WifiManager.get().then(on_ready)
#: Request permissions
WifiManager.request_permission([
WifiManager.PERMISSION_CHANGE_WIFI_STATE
]).then(on_permission_result)
return f | def disconnect(cls) | Disconnect from the current network (if connected).
Returns
--------
result: future
A future that resolves to true if the disconnect was
successful. Will be set to None if the change network
permission is denied. | 5.258011 | 4.877695 | 1.07797 |
app = AndroidApplication.instance()
f = app.create_future()
config = WifiConfiguration()
config.SSID = '"{}"'.format(ssid)
if key is not None:
config.preSharedKey = '"{}"'.format(key)
#: Set any other parameters
for k, v in kwargs.items():
setattr(config, k, v)
def on_permission_result(result):
if not result:
f.set_result(None)
return
def on_ready(mgr):
def on_disconnect(result):
if not result:
f.set_result(None)
return #: Done
mgr.setWifiEnabled(True).then(on_wifi_enabled)
def on_wifi_enabled(enabled):
if not enabled:
#: Access denied or failed to enable
f.set_result(None)
return
mgr.addNetwork(config).then(on_network_added)
def on_network_added(net_id):
if net_id == -1:
f.set_result(False)
print("Warning: Invalid network "
"configuration id {}".format(net_id))
return
mgr.enableNetwork(net_id, True).then(on_network_enabled)
def on_network_enabled(result):
if not result:
#: TODO: Should probably say
#: which state it failed at...
f.set_result(None)
return
mgr.reconnect().then(f.set_result)
#: Enable if needed
mgr.disconnect_().then(on_disconnect)
#: Get the service
WifiManager.get().then(on_ready)
#: Request permissions
WifiManager.request_permission(
WifiManager.PERMISSIONS_REQUIRED).then(on_permission_result)
return f | def connect(cls, ssid, key=None, **kwargs) | Connect to the given ssid using the key (if given).
Returns
--------
result: future
A future that resolves with the result of the connect | 3.544187 | 3.598924 | 0.984791 |
app = AndroidApplication.instance()
f = app.create_future()
def on_permission_result(result):
if not result:
f.set_result(None)
return
def on_ready(mgr):
mgr.getConnectionInfo().then(f.set_result)
#: Get the service
WifiManager.get().then(on_ready)
#: Request permissions
WifiManager.request_permission([
WifiManager.PERMISSION_ACCESS_WIFI_STATE
]).then(on_permission_result)
return f | def get_connection_info(cls) | Get info about current wifi connection (if any). Returns
info such as the IP address, BSSID, link speed, signal, etc..
Returns
--------
result: future
A future that resolves with a dict of the connection info
or None if an error occurred (ie permission denied).s | 5.545189 | 4.576187 | 1.211749 |
app = AndroidApplication.instance()
f = app.create_future()
def on_result(perms):
allowed = True
for p in permissions:
allowed = allowed and perms.get(p, False)
f.set_result(allowed)
app.request_permissions(permissions).then(on_result)
return f | def request_permission(cls, permissions) | Requests permission and returns an future result that returns a
boolean indicating if all the given permission were granted or denied. | 4.207975 | 3.332491 | 1.262711 |
super(AndroidActionMenuView, self).init_widget()
d = self.declaration
w = self.widget
#: Kinda hackish, but when we get the menu back, load it
w.getMenu().then(self.on_menu)
w.setOnMenuItemClickListener(w.getId())
w.onMenuItemClick.connect(self.on_menu_item_click) | def init_widget(self) | Initialize the underlying widget. | 8.519437 | 7.794878 | 1.092953 |
if change['type'] == 'event':
self.proxy.set_refreshed(True)
else:
super(SwipeRefreshLayout, self)._update_proxy(change) | def _update_proxy(self, change) | An observer which sends the state change to the proxy. | 6.225101 | 5.190383 | 1.199353 |
if change['type'] in ['event', 'update'] and self.proxy_is_active:
handler = getattr(self.proxy, 'set_' + change['name'], None)
if handler is not None:
handler(change['value']) | def _update_proxy(self, change) | An observer which sends the state change to the proxy. | 3.771883 | 3.241324 | 1.163686 |
def run_on_executor_decorator(fn):
executor = kwargs.get("executor", "executor")
@functools.wraps(fn)
def wrapper(self, *args, **kwargs):
callback = kwargs.pop("callback", None)
future = getattr(self, executor).submit(fn, self, *args, **kwargs)
if callback:
from .ioloop import IOLoop
IOLoop.current().add_future(
future, lambda future: callback(future.result()))
return future
return wrapper
if args and kwargs:
raise ValueError("cannot combine positional and keyword args")
if len(args) == 1:
return run_on_executor_decorator(args[0])
elif len(args) != 0:
raise ValueError("expected 1 argument, got %d", len(args))
return run_on_executor_decorator | def run_on_executor(*args, **kwargs) | Decorator to run a synchronous method asynchronously on an executor.
The decorated method may be called with a ``callback`` keyword
argument and returns a future.
The executor to be used is determined by the ``executor``
attributes of ``self``. To use a different attribute name, pass a
keyword argument to the decorator::
@run_on_executor(executor='_thread_pool')
def foo(self):
pass
.. versionchanged:: 4.2
Added keyword arguments to use alternative attributes.
.. versionchanged:: 5.0
Always uses the current IOLoop instead of ``self.io_loop``. | 2.260233 | 2.32558 | 0.971901 |
replacer = ArgReplacer(f, 'callback')
@functools.wraps(f)
def wrapper(*args, **kwargs):
future = TracebackFuture()
callback, args, kwargs = replacer.replace(
lambda value=_NO_RESULT: future.set_result(value),
args, kwargs)
def handle_error(typ, value, tb):
future.set_exc_info((typ, value, tb))
return True
exc_info = None
with ExceptionStackContext(handle_error):
try:
result = f(*args, **kwargs)
if result is not None:
raise ReturnValueIgnoredError(
"@return_future should not be used with functions "
"that return values")
except:
exc_info = sys.exc_info()
raise
if exc_info is not None:
# If the initial synchronous part of f() raised an exception,
# go ahead and raise it to the caller directly without waiting
# for them to inspect the Future.
future.result()
# If the caller passed in a callback, schedule it to be called
# when the future resolves. It is important that this happens
# just before we return the future, or else we risk confusing
# stack contexts with multiple exceptions (one here with the
# immediate exception, and again when the future resolves and
# the callback triggers its exception by calling future.result()).
if callback is not None:
def run_callback(future):
result = future.result()
if result is _NO_RESULT:
callback()
else:
callback(future.result())
future.add_done_callback(wrap(run_callback))
return future
return wrapper | def return_future(f) | Decorator to make a function that returns via callback return a
`Future`.
The wrapped function should take a ``callback`` keyword argument
and invoke it with one argument when it has finished. To signal failure,
the function can simply raise an exception (which will be
captured by the `.StackContext` and passed along to the ``Future``).
From the caller's perspective, the callback argument is optional.
If one is given, it will be invoked when the function is complete
with `Future.result()` as an argument. If the function fails, the
callback will not be run and an exception will be raised into the
surrounding `.StackContext`.
If no callback is given, the caller should use the ``Future`` to
wait for the function to complete (perhaps by yielding it in a
`.gen.engine` function, or passing it to `.IOLoop.add_future`).
Usage:
.. testcode::
@return_future
def future_func(arg1, arg2, callback):
# Do stuff (possibly asynchronous)
callback(result)
@gen.engine
def caller(callback):
yield future_func(arg1, arg2)
callback()
..
Note that ``@return_future`` and ``@gen.engine`` can be applied to the
same function, provided ``@return_future`` appears first. However,
consider using ``@gen.coroutine`` instead of this combination. | 4.747825 | 4.804259 | 0.988253 |
def copy(future):
assert future is a
if b.done():
return
if (isinstance(a, TracebackFuture) and
isinstance(b, TracebackFuture) and
a.exc_info() is not None):
b.set_exc_info(a.exc_info())
elif a.exception() is not None:
b.set_exception(a.exception())
else:
b.set_result(a.result())
a.add_done_callback(copy) | def chain_future(a, b) | Chain two futures together so that when one completes, so does the other.
The result (success or failure) of ``a`` will be copied to ``b``, unless
``b`` has already been completed or cancelled by the time ``a`` finishes. | 2.883648 | 2.738179 | 1.053126 |
self._clear_tb_log()
if self._result is not None:
return self._result
if self._exc_info is not None:
try:
raise_exc_info(self._exc_info)
finally:
self = None
self._check_done()
return self._result | def result(self, timeout=None) | If the operation succeeded, return its result. If it failed,
re-raise its exception.
This method takes a ``timeout`` argument for compatibility with
`concurrent.futures.Future` but it is an error to call it
before the `Future` is done, so the ``timeout`` is never used. | 4.396343 | 4.283458 | 1.026354 |
self._clear_tb_log()
if self._exc_info is not None:
return self._exc_info[1]
else:
self._check_done()
return None | def exception(self, timeout=None) | If the operation raised an exception, return the `Exception`
object. Otherwise returns None.
This method takes a ``timeout`` argument for compatibility with
`concurrent.futures.Future` but it is an error to call it
before the `Future` is done, so the ``timeout`` is never used. | 6.252612 | 5.593173 | 1.117901 |
if self._done:
fn(self)
else:
self._callbacks.append(fn) | def add_done_callback(self, fn) | Attaches the given callback to the `Future`.
It will be invoked with the `Future` as its argument when the Future
has finished running and its result is available. In Tornado
consider using `.IOLoop.add_future` instead of calling
`add_done_callback` directly. | 3.708391 | 3.856989 | 0.961473 |
self.set_exc_info(
(exception.__class__,
exception,
getattr(exception, '__traceback__', None))) | def set_exception(self, exception) | Sets the exception of a ``Future.`` | 4.3828 | 4.174569 | 1.049881 |
self._exc_info = exc_info
self._log_traceback = True
if not _GC_CYCLE_FINALIZERS:
self._tb_logger = _TracebackLogger(exc_info)
try:
self._set_done()
finally:
# Activate the logger after all callbacks have had a
# chance to call result() or exception().
if self._log_traceback and self._tb_logger is not None:
self._tb_logger.activate()
self._exc_info = exc_info | def set_exc_info(self, exc_info) | Sets the exception information of a ``Future.``
Preserves tracebacks on Python 2.
.. versionadded:: 4.0 | 5.326601 | 5.282964 | 1.00826 |
d = self.declaration
self.widget = CoordinatorLayout(self.get_context(), None, d.style) | def create_widget(self) | Create the underlying widget. | 13.973615 | 10.775544 | 1.29679 |
super(AndroidCompoundButton, self).init_widget()
w = self.widget
w.setOnCheckedChangeListener(w.getId())
w.onCheckedChanged.connect(self.on_checked) | def init_widget(self) | Initialize the underlying widget. | 5.906914 | 4.792776 | 1.232462 |
d = self.declaration
self.widget = RelativeLayout(self.get_context(), None, d.style) | def create_widget(self) | Create the underlying widget. | 12.711004 | 9.679862 | 1.313139 |
super(AndroidRelativeLayout, self).init_widget()
d = self.declaration
if d.gravity:
self.set_gravity(d.gravity)
if d.horizontal_gravity:
self.set_horizontal_gravity(d.horizontal_gravity)
if d.vertical_gravity:
self.set_vertical_gravity(d.vertical_gravity) | def init_widget(self) | Initialize the underlying widget. | 2.459161 | 2.19861 | 1.118507 |
super(AndroidTextureView, self).__init__(self)
w = self.widget
w.setSurfaceTextureListener(w.getId())
w.onSurfaceTextureAvailable.connect(self.on_surface_texture_available)
w.onSurfaceTextureDestroyed.connect(self.on_surface_texture_destroyed)
w.onSurfaceTextureChanged.connect(self.on_surface_texture_changed)
w.onSurfaceTextureUpdated.connect(self.on_surface_texture_updated) | def init_widget(self) | Initialize the underlying widget. | 2.753855 | 2.578042 | 1.068196 |
super(AndroidTextureView, self).init_layout()
# Force layout using the default params
if not self.layout_params:
self.set_layout({}) | def init_layout(self) | Add all child widgets to the view | 12.041255 | 10.327166 | 1.165979 |
d = self.declaration
self.widget = DrawerLayout(self.get_context(), None, d.style) | def create_widget(self) | Create the underlying widget. | 15.896738 | 12.381683 | 1.283892 |
super(AndroidDrawerLayout, self).init_widget()
d = self.declaration
if d.title:
self.set_title(d.title)
if d.drawer_elevation:
self.set_drawer_elevation(d.drawer_elevation)
if d.lock_mode:
self.set_lock_mode(d.lock_mode)
if d.scrim_color:
self.set_scrim_color(d.scrim_color)
if d.status_bar_background_color:
self.set_status_bar_background_color(d.status_bar_background_color) | def init_widget(self) | Initialize the underlying widget. | 2.057156 | 1.906584 | 1.078975 |
layout = self.layout
#: Add the layout as a subview
self.widget.addSubview(layout)
#: Add all child widgets to the layout
for child_widget in self.child_widgets():
layout.addArrangedSubview(child_widget) | def init_layout(self) | Initialize the layout of the toolkit widget.
This method is called during the bottom-up pass. This method
should initialize the layout of the widget. The child widgets
will be fully initialized and layed out when this is called.
This | 6.495561 | 6.969579 | 0.931988 |
super(UiKitView, self).child_added(child)
layout = self.layout
for i, child_widget in enumerate(self.child_widgets()):
if child_widget == child.widget:
layout.insertArrangedSubview(child_widget, atIndex=i)
layout.insertSubview(child_widget, atIndex=i) | def child_added(self, child) | Handle the child added event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method. | 4.913321 | 4.750382 | 1.0343 |
layout = self.layout
if child.widget is not None:
layout.removeArrangedSubview(child.widget)
layout.removeSubview(child.widget) | def child_removed(self, child) | Handle the child removed event from the declaration.
The child must be both removed from the arrangement and removed
normally. | 6.096566 | 6.404364 | 0.951939 |
layout = self.layout
if layout is not None:
layout.removeFromSuperview()
self.layout = None
super(UiKitViewGroup, self).destroy() | def destroy(self) | A reimplemented destructor that destroys the layout widget. | 7.711149 | 4.671473 | 1.650689 |
signature = self.__signature__
#: No arguments expected
if not signature:
return (self.name, [])
#: Build args, first is a string, subsequent are dictionaries
method_name = [self.name]
bridge_args = []
for i, sig in enumerate(signature):
if i == 0:
method_name.append(":")
bridge_args.append(msgpack_encoder(sig, args[0]))
continue
#: Sig is a dict so we must pull out the matching kwarg
found = False
for k in sig:
if k in kwargs:
method_name.append("{}:".format(k))
bridge_args.append(msgpack_encoder(sig[k], kwargs[k]))
found = True
break
if not found:
#: If we get here something is wrong
raise ValueError("Unexpected or missing argument at index {}. "
"Expected {}".format(i, sig))
return ("".join(method_name), bridge_args) | def pack_args(self, obj, *args, **kwargs) | Arguments must be packed according to the kwargs passed and
the signature defined. | 4.732117 | 4.65334 | 1.016929 |
d = self.declaration
self.widget = RatingBar(self.get_context(), None,
d.style or '@attr/ratingBarStyle') | def create_widget(self) | Create the underlying widget. | 14.217733 | 10.662492 | 1.333434 |
super(AndroidRatingBar, self).init_widget()
d = self.declaration
self.set_rating(d.rating)
w = self.widget
w.setOnRatingBarChangeListener(w.getId())
w.onRatingChanged.connect(self.on_rating_changed) | def init_widget(self) | Initialize the underlying widget. | 4.296046 | 3.702593 | 1.16028 |
d = self.declaration
self.widget = LinearLayout(self.get_context(), None, d.style) | def create_widget(self) | Create the underlying widget. | 12.23686 | 9.064757 | 1.349938 |
d = self.declaration
self.widget = FrameLayout(self.get_context(), None, d.style) | def create_widget(self) | Create the underlying widget. | 11.667867 | 8.869785 | 1.315462 |
context = self.get_context()
d = self.declaration
style = d.style or '@attr/autoCompleteTextViewStyle'
self.widget = AutoCompleteTextView(context, None, style)
self.adapter = ArrayAdapter(context, '@layout/simple_list_item_1') | def create_widget(self) | Create the underlying widget. | 7.857214 | 7.413109 | 1.059908 |
super(AndroidAutoCompleteTextView, self).init_widget()
self.widget.setAdapter(self.adapter) | def init_widget(self) | Initialize the underlying widget. | 7.934175 | 5.708772 | 1.389822 |
d = self.declaration
self.widget = Icon(self.get_context(), None, d.style) | def create_widget(self) | Create the underlying widget. | 13.92519 | 10.001359 | 1.39233 |
# Clean ctx handlers
stack_contexts = tuple([h for h in contexts[0] if h.active])
# Find new head
head = contexts[1]
while head is not None and not head.active:
head = head.old_contexts[1]
# Process chain
ctx = head
while ctx is not None:
parent = ctx.old_contexts[1]
while parent is not None:
if parent.active:
break
ctx.old_contexts = parent.old_contexts
parent = parent.old_contexts[1]
ctx = parent
return (stack_contexts, head) | def _remove_deactivated(contexts) | Remove deactivated handlers from the chain | 4.579332 | 4.314495 | 1.061383 |
# Check if function is already wrapped
if fn is None or hasattr(fn, '_wrapped'):
return fn
# Capture current stack head
# TODO: Any other better way to store contexts and update them in wrapped function?
cap_contexts = [_state.contexts]
if not cap_contexts[0][0] and not cap_contexts[0][1]:
# Fast path when there are no active contexts.
def null_wrapper(*args, **kwargs):
try:
current_state = _state.contexts
_state.contexts = cap_contexts[0]
return fn(*args, **kwargs)
finally:
_state.contexts = current_state
null_wrapper._wrapped = True
return null_wrapper
def wrapped(*args, **kwargs):
ret = None
try:
# Capture old state
current_state = _state.contexts
# Remove deactivated items
cap_contexts[0] = contexts = _remove_deactivated(cap_contexts[0])
# Force new state
_state.contexts = contexts
# Current exception
exc = (None, None, None)
top = None
# Apply stack contexts
last_ctx = 0
stack = contexts[0]
# Apply state
for n in stack:
try:
n.enter()
last_ctx += 1
except:
# Exception happened. Record exception info and store top-most handler
exc = sys.exc_info()
top = n.old_contexts[1]
# Execute callback if no exception happened while restoring state
if top is None:
try:
ret = fn(*args, **kwargs)
except:
exc = sys.exc_info()
top = contexts[1]
# If there was exception, try to handle it by going through the exception chain
if top is not None:
exc = _handle_exception(top, exc)
else:
# Otherwise take shorter path and run stack contexts in reverse order
while last_ctx > 0:
last_ctx -= 1
c = stack[last_ctx]
try:
c.exit(*exc)
except:
exc = sys.exc_info()
top = c.old_contexts[1]
break
else:
top = None
# If if exception happened while unrolling, take longer exception handler path
if top is not None:
exc = _handle_exception(top, exc)
# If exception was not handled, raise it
if exc != (None, None, None):
raise_exc_info(exc)
finally:
_state.contexts = current_state
return ret
wrapped._wrapped = True
return wrapped | def wrap(fn) | Returns a callable object that will restore the current `StackContext`
when executed.
Use this whenever saving a callback to be executed later in a
different execution context (either in a different thread or
asynchronously in the same thread). | 4.064425 | 4.064 | 1.000105 |
app = AndroidApplication.instance()
f = app.create_future()
def on_sensor(sid, mgr):
if sid is None:
f.set_result(None)
else:
f.set_result(Sensor(__id__=sid, manager=mgr, type=sensor_type))
SensorManager.get().then(
lambda sm: sm.getDefaultSensor(sensor_type).then(
lambda sid, sm=sm:on_sensor(sid, sm)))
return f | def get(cls, sensor_type) | Shortcut that acquires the default Sensor of a given type.
Parameters
----------
sensor_type: int
Type of sensor to get.
Returns
-------
result: Future
A future that resolves to an instance of the Sensor or None
if the sensor is not present or access is not allowed. | 5.493978 | 5.355649 | 1.025828 |
if not self.manager:
raise RuntimeError(
"Cannot start a sensor without a SensorManager!")
self.onSensorChanged.connect(callback)
return self.manager.registerListener(self.getId(), self, rate) | def start(self, callback, rate=SENSOR_DELAY_NORMAL) | Start listening to sensor events. Sensor event data depends
on the type of sensor that was given to
Parameters
----------
callback: Callable
A callback that takes one argument that will be passed
the sensor data. Sensor data is a dict with data based on
the type of sensor.
rate: Integer
How fast to update. One of the Sensor.SENSOR_DELAY values
Returns
-------
result: Future
A future that resolves to whether the register call
completed. | 6.43931 | 6.683201 | 0.963507 |
super(AndroidListView, self).init_widget()
d = self.declaration
self.set_arrangement(d.arrangement) | def init_widget(self) | Initialize the underlying widget. | 7.365936 | 5.708425 | 1.290362 |
for k, v in super(AndroidListView, self).get_declared_items():
if k == 'layout':
yield k, v
break | def get_declared_items(self) | Override to do it manually | 6.978957 | 5.658955 | 1.233259 |
super(AndroidListView, self).init_layout()
d = self.declaration
w = self.widget
# Prepare adapter
adapter = self.adapter = BridgedRecyclerAdapter(w)
# I'm sure this will make someone upset haha
adapter.setRecyleListener(adapter.getId())
adapter.onRecycleView.connect(self.on_recycle_view)
#adapter.onVisibleCountChanged.connect(self.on_visible_count_changed)
#adapter.onScrollStateChanged.connect(self.on_scroll_state_changed)
self.set_items(d.items)
w.setAdapter(adapter)
#self.set_selected(d.selected)
self.refresh_views() | def init_layout(self) | Initialize the underlying widget. | 5.81513 | 5.35143 | 1.08665 |
item = self.list_items[index]
self.item_mapping[position] = item
item.recycle_view(position) | def on_recycle_view(self, index, position) | Update the item the view at the given index should display | 5.63112 | 5.985649 | 0.94077 |
adapter = self.adapter
# Set initial ListItem state
item_mapping = self.item_mapping
for i, item in enumerate(self.list_items):
item_mapping[i] = item
item.recycle_view(i)
if adapter:
adapter.clearRecycleViews()
adapter.setRecycleViews(
[encode(li.get_view()) for li in self.list_items]) | def refresh_views(self, change=None) | Set the views that the adapter will cycle through. | 8.229736 | 7.229687 | 1.138325 |
if change['type'] != 'container':
return
op = change['operation']
if op == 'append':
i = len(change['value'])-1
self.adapter.notifyItemInserted(i)
elif op == 'insert':
self.adapter.notifyItemInserted(change['index'])
elif op in ('pop', '__delitem__'):
self.adapter.notifyItemRemoved(change['index'])
elif op == '__setitem__':
self.adapter.notifyItemChanged(change['index'])
elif op == 'extend':
n = len(change['items'])
i = len(change['value'])-n
self.adapter.notifyItemRangeInserted(i, n)
elif op in ('remove', 'reverse', 'sort'):
# Reset everything for these
self.adapter.notifyDataSetChanged() | def _on_items_changed(self, change) | Observe container events on the items list and update the
adapter appropriately. | 2.604455 | 2.40755 | 1.081787 |
d = self.declaration
if position < len(d.parent.items):
d.index = position
d.item = d.parent.items[position]
else:
d.index = -1
d.item = None | def recycle_view(self, position) | Tell the view to render the item at the given position | 4.064119 | 4.058053 | 1.001495 |
# type: (BaseException) -> Optional[int]
if hasattr(e, 'errno'):
return e.errno # type: ignore
elif e.args:
return e.args[0]
else:
return None | def errno_from_exception(e) | Provides the errno from an Exception object.
There are cases that the errno attribute was not set so we pull
the errno out of the args but if someone instantiates an Exception
without any args you will get a tuple error. So this function
abstracts all that behavior to give you a safe way to get the
errno. | 2.66422 | 3.458538 | 0.770331 |
# type: (bytes, bytes) -> bytes
mask_arr = array.array("B", mask)
unmasked_arr = array.array("B", data)
for i in xrange(len(data)):
unmasked_arr[i] = unmasked_arr[i] ^ mask_arr[i % 4]
if PY3:
# tostring was deprecated in py32. It hasn't been removed,
# but since we turn on deprecation warnings in our tests
# we need to use the right one.
return unmasked_arr.tobytes()
else:
return unmasked_arr.tostring() | def _websocket_mask_python(mask, data) | Websocket masking function.
`mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.
Returns a `bytes` object of the same length as `data` with the mask applied
as specified in section 5.3 of RFC 6455.
This pure-python implementation may be replaced by an optimized version when available. | 4.006926 | 4.435024 | 0.903473 |
# type: (Any, **Any) -> None
base = cls.configurable_base()
if isinstance(impl, (str, unicode_type)):
impl = import_object(impl)
if impl is not None and not issubclass(impl, cls):
raise ValueError("Invalid subclass of %s" % cls)
base.__impl_class = impl
base.__impl_kwargs = kwargs | def configure(cls, impl, **kwargs) | Sets the class to use when the base class is instantiated.
Keyword arguments will be saved and added to the arguments passed
to the constructor. This can be used to set global defaults for
some parameters. | 4.721506 | 5.001629 | 0.943994 |
# type: () -> type
base = cls.configurable_base()
# Manually mangle the private name to see whether this base
# has been configured (and not another base higher in the
# hierarchy).
if base.__dict__.get('_Configurable__impl_class') is None:
base.__impl_class = cls.configurable_default()
return base.__impl_class | def configured_class(cls) | Returns the currently configured class. | 10.811888 | 9.976895 | 1.083693 |
# type: (List[Any], Dict[str, Any], Any) -> Any
if self.arg_pos is not None and len(args) > self.arg_pos:
return args[self.arg_pos]
else:
return kwargs.get(self.name, default) | def get_old_value(self, args, kwargs, default=None) | Returns the old value of the named argument without replacing it.
Returns ``default`` if the argument is not present. | 2.421699 | 2.883914 | 0.839727 |
# type: (Any, List[Any], Dict[str, Any]) -> Tuple[Any, List[Any], Dict[str, Any]]
if self.arg_pos is not None and len(args) > self.arg_pos:
# The arg to replace is passed positionally
old_value = args[self.arg_pos]
args = list(args) # *args is normally a tuple
args[self.arg_pos] = new_value
else:
# The arg to replace is either omitted or passed by keyword.
old_value = kwargs.get(self.name)
kwargs[self.name] = new_value
return old_value, args, kwargs | def replace(self, new_value, args, kwargs) | Replace the named argument in ``args, kwargs`` with ``new_value``.
Returns ``(old_value, args, kwargs)``. The returned ``args`` and
``kwargs`` objects may not be the same as the input objects, or
the input objects may be mutated.
If the named argument was not found, ``new_value`` will be added
to ``kwargs`` and None will be returned as ``old_value``. | 2.662086 | 2.879799 | 0.9244 |
if not self.is_initialized:
self.initialize()
if not self.proxy_is_active:
self.activate_proxy()
self.show = True | def popup(self) | Show the notification from code. This will initialize and activate
if needed.
Notes
------
This does NOT block. Callbacks should be used to handle click events
or the `show` state should be observed to know when it is closed. | 5.155578 | 4.659825 | 1.106389 |
d = self.declaration
if d.text:
Toast.makeText(self.get_context(),
d.text, 1).then(self.on_make_toast)
self.made_toast = True
else:
self.toast = Toast(self.get_context()) | def create_widget(self) | Create the underlying widget.
A toast is not a subclass of view, hence we don't set name as widget
or children will try to use it as their parent (which crashes). | 6.796915 | 5.47128 | 1.24229 |
if not self.toast:
return
super(AndroidToast, self).init_widget()
d = self.declaration
if not self.made_toast:
#: Set it to LONG
self.toast.setDuration(1)
if d.gravity:
self.set_gravity(d.gravity)
if d.show:
self.set_show(d.show) | def init_widget(self) | Our widget may not exist yet so we have to diverge from the normal
way of doing initialization. See `update_widget` | 6.267761 | 6.200671 | 1.01082 |
super(AndroidToast, self).init_layout()
if not self.made_toast:
for view in self.child_widgets():
self.toast.setView(view)
break | def init_layout(self) | If a view is given show it | 11.093541 | 9.66694 | 1.147575 |
view = child.widget
if view is not None:
self.toast.setView(view) | def child_added(self, child) | Overwrite the view | 12.864146 | 10.144764 | 1.268058 |
d = self.declaration
self.toast = Toast(__id__=ref)
self.init_widget() | def on_make_toast(self, ref) | Using Toast.makeToast returns async so we have to initialize it
later. | 18.785515 | 13.531516 | 1.388279 |
d = self.declaration
if dt <= 0:
#: Done, hide
d.show = False
elif d.show:
#: If user didn't cancel it, keep it alive
self.toast.show()
t = min(1000, dt)
app = self.get_context()
app.timed_call(t, self._refresh_show, dt-t) | def _refresh_show(self, dt) | While the toast.show is true, keep calling .show() until the
duration `dt` expires.
Parameters
------------
dt: int
Time left to keep showing | 9.719417 | 8.82712 | 1.101086 |
d = self.declaration
self.dialog = Dialog(self.get_context(), d.style) | def create_widget(self) | Create the underlying widget.
A dialog is not a subclass of view, hence we don't set name as widget
or children will try to use it as their parent. | 13.389215 | 9.897674 | 1.352764 |
w = self.dialog
# Listen for events
w.setOnDismissListener(w.getId())
w.onDismiss.connect(self.on_dismiss)
w.setOnCancelListener(w.getId())
w.onCancel.connect(self.on_cancel)
super(AndroidDialog, self).init_widget() | def init_widget(self) | Set the listeners | 4.38099 | 4.167689 | 1.051179 |
super(AndroidDialog, self).init_layout()
#: Set the content
for view in self.child_widgets():
self.dialog.setContentView(view)
break
#: Show it if needed
d = self.declaration
if d.show:
self.set_show(d.show) | def init_layout(self) | If a view is given show it | 8.278489 | 7.231628 | 1.144761 |
view = child.widget
if view is not None:
self.dialog.setContentView(view) | def child_added(self, child) | Overwrite the content view | 9.982884 | 7.187938 | 1.388838 |
dialog = self.dialog
if dialog:
#: Clear the dismiss listener
#: (or we get an error during the callback)
dialog.setOnDismissListener(None)
dialog.dismiss()
del self.dialog
super(AndroidDialog, self).destroy() | def destroy(self) | A reimplemented destructor that cancels
the dialog before destroying. | 9.162381 | 7.724415 | 1.186159 |
app = AndroidApplication.instance()
f = app.create_future()
def on_success(lm):
#: When we have finally have permission
lm.onLocationChanged.connect(callback)
#: Save a reference to our listener
#: because we may want to stop updates
listener = LocationManager.LocationListener(lm)
lm.listeners.append(listener)
lm.requestLocationUpdates(provider, min_time, min_distance,
listener)
app.set_future_result(f, True)
def on_perm_request_result(allowed):
#: When our permission request is accepted or decliend.
if allowed:
LocationManager.get().then(on_success)
else:
#: Access denied
app.set_future_result(f, False)
def on_perm_check(allowed):
if allowed:
LocationManager.get().then(on_success)
else:
LocationManager.request_permission(
fine=provider == 'gps').then(on_perm_request_result)
#: Check permission
LocationManager.check_permission(
fine=provider == 'gps').then(on_perm_check)
return f | def start(cls, callback, provider='gps', min_time=1000, min_distance=0) | Convenience method that checks and requests permission if necessary
and if successful calls the callback with a populated `Location`
instance on updates.
Note you must have the permissions in your manifest or requests
will be denied immediately. | 4.872751 | 4.698566 | 1.037072 |
manager = LocationManager.instance()
if manager:
for l in manager.listeners:
manager.removeUpdates(l)
manager.listeners = [] | def stop(cls) | Stops location updates if currently updating. | 8.263198 | 5.474822 | 1.509309 |
app = AndroidApplication.instance()
permission = (cls.ACCESS_FINE_PERMISSION
if fine else cls.ACCESS_COARSE_PERMISSION)
return app.has_permission(permission) | def check_permission(cls, fine=True) | Returns a future that returns a boolean indicating if permission
is currently granted or denied. If permission is denied, you can
request using `LocationManager.request_permission()` below. | 5.663349 | 4.796931 | 1.180619 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.