Instruction:
Make a summary of the following Python 3 code
def run(self):
        if self.running or self.finished:
            return
        try:
            self.running = True
            while True:
                future = self.future
                if not future.done():
                    return
                self.future = None
                try:
                    orig_stack_contexts = stack_context._state.contexts
                    exc_info = None

                    try:
                        value = future.result()
                    except Exception:
                        self.had_exception = True
                        exc_info = sys.exc_info()
                    future = None

                    if exc_info is not None:
                        try:
                            yielded = self.gen.throw(*exc_info)
                        finally:
                            # Break up a reference to itself
                            # for faster GC on CPython.
                            exc_info = None
                    else:
                        yielded = self.gen.send(value)

                    if stack_context._state.contexts is not orig_stack_contexts:
                        self.gen.throw(
                            stack_context.StackContextInconsistentError(
                                'stack_context inconsistency (probably caused '
                                'by yield within a "with StackContext" block)'))
                except (StopIteration, Return) as e:
                    self.finished = True
                    self.future = _null_future
                    if self.pending_callbacks and not self.had_exception:
                        # If we ran cleanly without waiting on all callbacks
                        # raise an error (really more of a warning).  If we
                        # had an exception then some callbacks may have been
                        # orphaned, so skip the check in that case.
                        raise LeakedCallbackError(
                            "finished without waiting for callbacks %r" %
                            self.pending_callbacks)
                    self.result_future.set_result(_value_from_stopiteration(e))
                    self.result_future = None
                    self._deactivate_stack_context()
                    return
                except Exception:
                    self.finished = True
                    self.future = _null_future
                    self.result_future.set_exc_info(sys.exc_info())
                    self.result_future = None
                    self._deactivate_stack_context()
                    return
                if not self.handle_yield(yielded):
                    return
                yielded = None
        finally:
            self.running = False

Response: Starts or resumes the generator until it reaches a heartbeat point.


Instruction:
Given the following Python 3 function, write the documentation
def create_widget(self):
        d = self.declaration
        self.widget = RadioButton(self.get_context(), None,
                                  d.style or '@attr/radioButtonStyle')

Response: Create the underlying widget.


Instruction:
Write a Python 3 script to
write a message to the client

Response:
def write_message(self, data, binary=False):
        """ Write a message to the client """
        self.connection.write_message(data, binary)


Instruction:
Given the following Python 3 function, write the documentation
def render_files(self, root=None):
        if root is None:
            tmp =  os.environ.get('TMP')
            root = sys.path[1 if tmp and tmp in sys.path else 0]
        items = []
        for filename in os.listdir(root):
            # for subdirname in dirnames:
            #     path = os.path.join(dirname, subdirname)
            #     items.append(FOLDER_TMPL.format(
            #         name=subdirname,
            #         id=path,
            #         items=self.render_files(path)
            #     ))
            #for filename in filenames:
            f,ext = os.path.splitext(filename)
            if ext in ['.py', '.enaml']:
                items.append(FILE_TMPL.format(
                    name=filename,
                    id=filename
                ))

        return "".join(items)

Response: Render the file path as accordions


Instruction:
Here you have a function in Python 3, explain what it does
def render_code(self):
        tmp_dir = os.environ.get('TMP','')
        view_code = os.path.join(tmp_dir,'view.enaml')
        if os.path.exists(view_code):
            try:
                with open(view_code) as f:
                    return f.read()
            except:
                pass
        return DEFAULT_CODE

Response: Try to load the previous code if we had a crash or something else return the default code


Instruction:
Can you generate a brief explanation for the following Python 3 code
def render_component(self, declaration):
        items = ["""
{name}	{type}
"""
                 .format(name=m.name,
                         type=self.render_component_types(declaration, m))
                 for m in self.get_component_members(declaration)]

        info = []
        parent = declaration.__mro__[1]
        #: Superclass
        info.append("
extends component	"
                    "{name}		"
                    .format(id=parent.__name__.lower(), name=parent.__name__))

        #: Source and example, only works with enamlnative builtins
        source_path = inspect.getfile(declaration).replace(
                        ".pyo", ".py").replace(".pyc", ".py")
        if 'enamlnative' in source_path:
            source_link = "https://github.com/frmdstryr/" \
                          "enaml-native/tree/master/src/{}".format(
                source_path.split("assets/python")[1]
            )
            info.append("
source code	"
                        "show		"
                        .format(source_link))

            #: Examples link
            example_link = "https://www.codelv.com/projects/" \
                           "enaml-native/docs/components#{}" \
                .format(declaration.__name__.lower())
            info.append("
example usage	"
                        "view		"
                        .format(example_link))

        return COMPONENT_TMPL.format(id=declaration.__name__.lower(),
                                     name=declaration.__name__,
                                     info="".join(info),
                                     items="".join(items))

Response: Render a row of all the attributes of the component.


Instruction:
Implement a function in Python 3 to
start the dev session.

Response:
def start(self):
        """ Start the dev session. Attempt to use tornado first, then try
        twisted

        """
        print("Starting debug client cwd: {}".format(os.getcwd()))
        print("Sys path: {}".format(sys.path))

        #: Initialize the hotswapper
        self.hotswap = Hotswapper(debug=False)

        if self.mode == 'server':
            self.server.start(self)
        else:
            self.client.start(self)


Instruction:
Here you have a function in Python 3, explain what it does
def _default_url(self):
        host = 'localhost' if self.mode == 'remote' else self.host
        return 'ws://{}:{}/dev'.format(host, self.port)

Response: Default websocket URL to connect to and listen for reload requests


Instruction:
Explain what the following Python 3 code does
def write_message(self, data, binary=False):
        self.client.write_message(data, binary=binary)

Response: Write a message to the active client


Instruction:
Can you create a Python 3 function that
calls when the dev server wants to reload the view.

Response:
def do_reload(self, msg):
        """ Called when the dev server wants to reload the view. """
        #: TODO: This should use the autorelaoder
        app = self.app

        #: Show loading screen
        try:
            self.app.widget.showLoading("Reloading... Please wait.", now=True)
            #self.app.widget.restartPython(now=True)
            #sys.exit(0)
        except:
            #: TODO: Implement for iOS...
            pass
        self.save_changed_files(msg)

        if app.load_view is None:
            print("Warning: Reloading the view is not implemented. "
                  "Please set `app.load_view` to support this.")
            return
        if app.view is not None:
            try:
                app.view.destroy()
            except:
                pass

        def wrapped(f):
            def safe_reload(*args, **kwargs):
                try:
                    return f(*args, **kwargs)
                except:
                    #: Display the error
                    app.send_event(Command.ERROR, traceback.format_exc())
            return safe_reload

        app.deferred_call(wrapped(app.load_view), app)


Instruction:
Can you tell what is the following Python 3 function doing
def do_hotswap(self, msg):
        #: Show hotswap tooltip
        try:
            self.app.widget.showTooltip("Hot swapping...", now=True)
        except:
            pass
        self.save_changed_files(msg)

        hotswap = self.hotswap
        app = self.app
        try:
            print("Attempting hotswap....")
            with hotswap.active():
                hotswap.update(app.view)
        except:
            #: Display the error
            app.send_event(Command.ERROR, traceback.format_exc())

Response: Attempt to hotswap the code


Instruction:
Create a Python 3 function to
update the proxy state.

Response:
def _update_proxy(self, change):
        """ An observer which sends the state change to the proxy.

        """
        if change['type'] == 'event':
            name = 'do_'+change['name']
            if hasattr(self.proxy, name):
                handler = getattr(self.proxy, name)
                handler()
        else:
            super(WebView, self)._update_proxy(change)


Instruction:
Implement a Python 3 function for
creating the underlying widget.

Response:
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.

        """
        d = self.declaration
        style = d.style or '@style/Widget.DeviceDefault.PopupMenu'
        self.window = PopupWindow(self.get_context(), None, 0, style)
        self.showing = False


Instruction:
Explain what the following Python 3 code does
def init_widget(self):
        w = self.window
        d = self.declaration
        self.set_background_color(d.background_color)
        self.set_touchable(d.touchable)
        self.set_outside_touchable(d.outside_touchable)

        # Listen for events
        w.setOnDismissListener(w.getId())
        w.onDismiss.connect(self.on_dismiss)
        super(AndroidPopupWindow, self).init_widget()

Response: Initialize the popup widget.


Instruction:
Can you write a function in Python 3 where it
initializes the layout of the popup window.

Response:
def init_layout(self):
        """ If a view is given show it

        """
        super(AndroidPopupWindow, self).init_layout()

        #: Set the content
        for view in self.child_widgets():
            self.window.setContentView(view)
            break

        #: Show it if needed
        d = self.declaration
        if d.show:
            self.set_show(d.show)


Instruction:
Write a Python 3 function that can
overwrite the content view of the child.

Response:
def child_added(self, child):
        """ Overwrite the content view """
        view = child.widget
        if view is not None:
            self.window.setContentView(view)


Instruction:
Can you generate the documentation for the following Python 3 function
def destroy(self):
        super(AndroidPopupWindow, self).destroy()
        window = self.window
        if window:
            #: Clear the dismiss listener
            #: (or we get an error during the callback)
            window.setOnDismissListener(None)
            #window.dismiss()
            del self.window

Response:
A reimplemented destructor that cancels
        the dialog before destroying.


Instruction:
Implement a Python 3 function for
updating the PopupWindow if it is currently showing.

Response:
def update(self):
        """ Update the PopupWindow if it is currently showing. This avoids
        calling update during initialization.
        """
        if not self.showing:
            return
        d = self.declaration
        self.set_show(d.show)


Instruction:
Can you generate the documentation for the following Python 3 function
def refresh_items(self):
        items = []
        if self.condition:
            for nodes, key, f_locals in self.pattern_nodes:
                with new_scope(key, f_locals):
                    for node in nodes:
                        child = node(None)
                        if isinstance(child, list):
                            items.extend(child)
                        else:
                            items.append(child)

        for old in self.items:
            if not old.is_destroyed:
                old.destroy()

        #: Insert items into THIS node, NOT the PARENT
        #if len(items) > 0:
        #    self.parent.insert_children(self, items)
        self.items = items

Response: Refresh the items of the pattern.


Instruction:
Can you implement a function in Python 3 that
initializes the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        super(AndroidSwipeRefreshLayout, self).init_widget()
        d = self.declaration
        w = self.widget
        if not d.enabled:
            self.set_enabled(d.enabled)
        if d.indicator_background_color:
            self.set_indicator_background_color(d.indicator_background_color)
        if d.indicator_color:
            self.set_indicator_color(d.indicator_color)
        if d.trigger_distance:
            self.set_trigger_distance(d.trigger_distance)
        w.onRefresh.connect(self.on_refresh)
        w.setOnRefreshListener(w.getId())


Instruction:
Can you create a Python 3 function that
loads the extension module using the load_dynamic method.

Response:
def load_module(self, mod):
        """ Load the extension using the load_dynamic method. """
        try:
            return sys.modules[mod]
        except KeyError:
            pass

        lib = ExtensionImporter.extension_modules[mod]
        m = imp.load_dynamic(mod, lib)
        sys.modules[mod] = m
        return m


Instruction:
Create a Python 3 function for
creating the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        d = self.declaration
        self.widget = TabLayout(self.get_context(), None, d.style)


Instruction:
Can you generate the documentation for the following Python 3 function
def init_widget(self):
        super(AndroidTabLayout, self).init_widget()
        w = self.widget
        w.addOnTabSelectedListener(w.getId())
        w.onTabSelected.connect(self.on_tab_selected)
        w.onTabUnselected.connect(self.on_tab_unselected)

Response: Initialize the underlying widget.


Instruction:
Given the following Python 3 function, write the documentation
def destroy(self):
        super(AndroidTabLayout, self).destroy()
        if self.tabs:
            del self.tabs

Response: Destroy all tabs when destroyed


Instruction:
How would you explain what the following Python 3 function does
def update_atom_members(old, new):
    old_keys = old.members().keys()
    new_keys = new.members().keys()
    for key in old_keys:
        old_obj = getattr(old, key)
        try:
            new_obj = getattr(new, key)
            if old_obj == new_obj:
                continue
        except AttributeError:
            # Remove any obsolete members
            try:
                delattr(old, key)
            except (AttributeError, TypeError):
                pass
            continue

        try:
            #: Update any changed members
            #: TODO: We have to somehow know if this was changed by the user or the code!
            #: and ONLY update if it's due to the code changing! Without this, the entire concept
            #: is broken and useless...
            setattr(old, key, getattr(new, key))
        except (AttributeError, TypeError):
            pass  # skip non-writable attributes

    #: Add any new members
    for key in set(new_keys)-set(old_keys):
        try:
            setattr(old, key, getattr(new, key))
        except (AttributeError, TypeError):
            pass

Response: Update an atom member with a new one.


Instruction:
Write a Python 3 script to
update declarative classes or fallback on default

Response:
def update_class_by_type(old, new):
    """ Update declarative classes or fallback on default """
    autoreload.update_class(old, new)
    if isinstance2(old, new, AtomMeta):
        update_atom_members(old, new)


Instruction:
Given the following Python 3 function, write the documentation
def check(self, check_all=True, do_reload=True):
        with enaml.imports():
            super(EnamlReloader, self).check(check_all=check_all, do_reload=do_reload)

Response: Check whether all modules need to be reloaded.


Instruction:
How would you implement a function in Python 3 that
updates the view instance with the given declaration and new declaration.

Response:
def update(self, old, new=None):
        """ Update given view declaration with new declaration

        Parameters
        -----------
        old: Declarative
            The existing view instance that needs to be updated
        new: Declarative or None
            The new or reloaded view instance to that will be used to update the
            existing view. If none is given, one of the same type as old will be
            created and initialized with no attributes passed.

        """
        #: Create and initialize
        if not new:
            new = type(old)()
            if not new.is_initialized:
                 new.initialize()
        if self.debug:
            print("Updating {} with {}".format(old, new))

        #: Update attrs, funcs, and bindings of this node
        self.update_attrs(old, new)
        self.update_funcs(old, new)
        self.update_bindings(old, new)

        #: Update any child pattern nodes before the children
        self.update_pattern_nodes(old, new)

        #: Now update any children
        self.update_children(old, new)


Instruction:
Create a Python 3 function for
finding the node that best matches the new node given the old nodes.

Response:
def find_best_matching_node(self, new, old_nodes):
        """ Find the node that best matches the new node given the old nodes. If no
            good match exists return `None`.

        """
        name = new.__class__.__name__
        #: TODO: We should pick the BEST one from this list
        #: based on some "matching" criteria (such as matching ref name or params)
        matches = [c for c in old_nodes if name == c.__class__.__name__]
        if self.debug:
            print("Found matches for {}: {} ".format(new, matches))
        return matches[0] if matches else None


Instruction:
Implement a function in Python 3 to
update any attr members.

Response:
def update_attrs(self, old, new):
        """ Update any `attr` members.

            Parameters
            -----------
            old: Declarative
                The existing view instance that needs to be updated
            new: Declarative
                The new view instance that should be used for updating

        """
        #: Copy in storage from new node
        if new._d_storage:
            old._d_storage = new._d_storage


Instruction:
Implement a Python 3 function for
updating any enaml operator bindings.

Response:
def update_bindings(self, old, new):
        """ Update any enaml operator bindings.

            Parameters
            -----------
            old: Declarative
                The existing view instance that needs to be updated
            new: Declarative
                The new view instance that should be used for updating

        """
        #: Copy the Expression Engine
        if new._d_engine:
            old._d_engine = new._d_engine
            engine = old._d_engine

            #: Rerun any read expressions which should trigger
            #: any dependent writes
            for k in engine._handlers.keys():
                try:
                    engine.update(old, k)
                except:
                    if self.debug:
                        print(traceback.format_exc())
                    pass


Instruction:
Can you generate the documentation for the following Python 3 function
def init_widget(self):
        super(UiKitProgressView, self).init_widget()

        d = self.declaration
        if d.progress:
            self.set_progress(d.progress)

Response: Initialize the state of the toolkit widget.


Instruction:
Can you generate the documentation for the following Python 3 function
def create_widget(self):
        d = self.declaration
        self.widget = View(self.get_context(), None, d.style)

Response: Create the underlying label widget.


Instruction:
Write a Python 3 function for
initializing the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        This reads all items declared in the enamldef block for this node
        and sets only the values that have been specified. All other values
        will be left as default. Doing it this way makes atom to only create
        the properties that need to be overridden from defaults thus greatly
        reducing the number of initialization checks, saving time and memory.

        If you don't want this to happen override `get_declared_keys`
        to return an empty list.

        """
        super(AndroidView, self).init_widget()

        # Initialize the widget by updating only the members that
        # have read expressions declared. This saves a lot of time and
        # simplifies widget initialization code
        for k, v in self.get_declared_items():
            handler = getattr(self, 'set_'+k, None)
            if handler:
                handler(v)


Instruction:
Can you create a Python 3 function that
gets the members that were set for this widget in the enamldef block for this Declaration.

Response:
def get_declared_items(self):
        """ Get the members that were set in the enamldef block for this
        Declaration. Layout keys are grouped together until the end so as
        to avoid triggering multiple updates.

        Returns
        -------
        result: List of (k,v) pairs that were defined for this widget in enaml
            List of keys and values

        """
        d = self.declaration
        engine = d._d_engine
        if engine:
            layout = {}
            for k, h in engine._handlers.items():
                # Handlers with read operations
                if not h.read_pair:
                    continue
                v = getattr(d, k)
                if k in LAYOUT_KEYS:
                    layout[k] = v
                    continue
                yield (k, v)

            if layout:
                yield ('layout', layout)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def on_key(self, view, key, event):
        d = self.declaration
        r = {'key': key, 'result': False}
        d.key_event(r)
        return r['result']

Response: Trigger the key event


Instruction:
How would you explain what the following Python 3 function does
def on_touch(self, view, event):
        d = self.declaration
        r = {'event': event, 'result': False}
        d.touch_event(r)
        return r['result']

Response: Trigger the touch event


Instruction:
Implement a function in Python 3 to
set the visibility of the widget.

Response:
def set_visible(self, visible):
        """ Set the visibility of the widget.

        """
        v = View.VISIBILITY_VISIBLE if visible else View.VISIBILITY_GONE
        self.widget.setVisibility(v)


Instruction:
Write a Python 3 function for
setting the layout parameters of this node and the parent node.

Response:
def set_layout(self, layout):
        """ Sets the LayoutParams of this widget.

        Since the available properties that may be set for the layout params
        depends on the parent, actual creation of the params is delegated to
        the parent

        Parameters
        ----------
        layout: Dict
            A dict of layout parameters the parent should used to layout this
            child.  The widget defaults are updated with user passed values.

        """
        # Update the layout with the widget defaults
        update = self.layout_params is not None
        params = self.default_layout.copy()
        params.update(layout)

        # Create the layout params
        parent = self.parent()

        if not isinstance(parent, AndroidView):
            # Root node
            parent = self
            update = True

        parent.apply_layout(self, params)
        if update:
            self.widget.setLayoutParams(self.layout_params)


Instruction:
How would you code a function in Python 3 to
create the LayoutParams object for a child with the requested layout parameters. Subclasses should override this as needed to handle layout specific needs.

Response:
def create_layout_params(self, child, layout):
        """ Create the LayoutParams for a child with it's requested
        layout parameters. Subclasses should override this as needed
        to handle layout specific needs.

        Parameters
        ----------
        child: AndroidView
            A view to create layout params for.
        layout: Dict
            A dict of layout parameters to use to create the layout.

        Returns
        -------
        layout_params: LayoutParams
            A LayoutParams bridge object with the requested layout options.

        """
        dp = self.dp
        w, h = (coerce_size(layout.get('width', 'wrap_content')),
                coerce_size(layout.get('height', 'wrap_content')))
        w = w if w < 0 else int(w * dp)
        h = h if h < 0 else int(h * dp)
        layout_params = self.layout_param_type(w, h)

        if layout.get('margin'):
            l, t, r, b = layout['margin']
            layout_params.setMargins(int(l*dp), int(t*dp),
                                     int(r*dp), int(b*dp))
        return layout_params


Instruction:
Can you generate a brief explanation for the following Python 3 code
def apply_layout(self, child, layout):
        layout_params = child.layout_params
        if not layout_params:
            layout_params = self.create_layout_params(child, layout)
        w = child.widget
        if w:
            dp = self.dp
            # padding
            if 'padding' in layout:
                l, t, r, b = layout['padding']
                w.setPadding(int(l*dp), int(t*dp),
                             int(r*dp), int(b*dp))

            # left, top, right, bottom
            if 'left' in layout:
                w.setLeft(int(layout['left']*dp))
            if 'top' in layout:
                w.setTop(int(layout['top']*dp))
            if 'right' in layout:
                w.setRight(int(layout['right']*dp))
            if 'bottom' in layout:
                w.setBottom(int(layout['bottom']*dp))

            # x, y, z
            if 'x' in layout:
                w.setX(layout['x']*dp)
            if 'y' in layout:
                w.setY(layout['y']*dp)
            if 'z' in layout:
                w.setZ(layout['z']*dp)

            # set min width and height
            # maximum is not supported by AndroidViews (without flexbox)
            if 'min_height' in layout:
                w.setMinimumHeight(int(layout['min_height']*dp))
            if 'min_width' in layout:
                w.setMinimumWidth(int(layout['min_width']*dp))

        child.layout_params = layout_params

Response: Applies a layout to a child.


Instruction:
Here you have a function in Python 3, explain what it does
def default(cls):
        with enamlnative.imports():
            for impl in [
                TornadoEventLoop,
                TwistedEventLoop,
                BuiltinEventLoop,
            ]:
                if impl.available():
                    print("Using {} event loop!".format(impl))
                    return impl()
        raise RuntimeError("No event loop implementation is available. "
                           "Install tornado or twisted.")

Response: Returns the default event loop implementation.


Instruction:
Can you write a function in Python 3 where it
logs the error that occurred when running the given callback.

Response:
def log_error(self, callback, error=None):
        """ Log the error that occurred when running the given callback. """
        print("Uncaught error during callback: {}".format(callback))
        print("Error: {}".format(error))


Instruction:
Can you tell what is the following Python 3 function doing
def deferred_call(self, callback, *args, **kwargs):
        loop = self.loop
        r = loop.callLater(0, callback, *args, **kwargs)
        loop.wakeUp()
        return r

Response: Call the callback with args and kwargs and return the result.


Instruction:
Explain what the following Python 3 code does
def timed_call(self, ms, callback, *args, **kwargs):
        loop = self.loop
        r = loop.callLater(ms/1000.0, callback, *args, **kwargs)
        loop.wakeUp()
        return r

Response: Call the callback function every ms seconds.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def init_widget(self):
        super(UiKitView, self).init_widget()

        self.widget.yoga.isEnabled = True

        # Initialize the widget by updating only the members that
        # have read expressions declared. This saves a lot of time and
        # simplifies widget initialization code
        for k, v in self.get_declared_items():
            handler = getattr(self, 'set_'+k, None)
            if handler:
                handler(v)

Response: Initialize the underlying widget.


Instruction:
Make a summary of the following Python 3 code
def init_layout(self):
        widget = self.widget
        for child_widget in self.child_widgets():
            widget.addSubview(child_widget)

Response: Initialize the layout of the toolkit widget.


Instruction:
Can you create a Python 3 function that
updates the frame for this widgets

Response:
def update_frame(self):
        """ Define the view frame for this widgets"""
        d = self.declaration
        if d.x or d.y or d.width or d.height:
            self.frame = (d.x, d.y, d.width, d.height)


Instruction:
Write a Python 3 function that can
handle the child added event from the declaration.

Response:
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.

        """
        super(UiKitView, self).child_added(child)

        widget = self.widget
        #: TODO: Should index be cached?
        for i, child_widget in enumerate(self.child_widgets()):
            if child_widget == child.widget:
                widget.insertSubview(child_widget, atIndex=i)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def child_moved(self, child):
        super(UiKitView, self).child_moved(child)
        #: Remove and re-add in correct spot
        #: TODO: Should use exchangeSubviewAtIndex
        self.child_removed(child)
        self.child_added(child)

Response: Handle the child moved event from the declaration.


Instruction:
Given the following Python 3 function, write the documentation
def child_removed(self, child):
        super(UiKitView, self).child_removed(child)
        if child.widget is not None:
            child.widget.removeFromSuperview()

Response: Handle the child removed event from the declaration.


Instruction:
Here you have a function in Python 3, explain what it does
def init_layout(self):
        super(AndroidSurfaceView, self).init_layout()

        # Force layout using the default params
        if not self.layout_params:
            self.set_layout({})

Response: Initialize the layout of the view


Instruction:
Here you have a function in Python 3, explain what it does
def main():

    #: If we set the TMP env variable the dev reloader will save file
    #: and load changes in this directory instead of overwriting the
    #: ones installed with the app.
    os.environ['TMP'] = os.path.join(sys.path[0], '../tmp')

    from enamlnative.android.app import AndroidApplication

    app = AndroidApplication(
        debug=True,  #: Makes a lot of lag!
        dev='server',
        load_view=load_view,
    )
    app.start()

Response: Main function for the base application.


Instruction:
Create a Python 3 function for
initializing the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        super(AndroidViewAnimator, self).init_widget()
        d = self.declaration
        if d.animate_first_view:
            self.set_animate_first_view(d.animate_first_view)
        if d.displayed_child:
            self.set_displayed_child(d.displayed_child)


Instruction:
Write a Python 3 function for
creating the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        self.widget = ViewPager(self.get_context())
        self.adapter = BridgedFragmentStatePagerAdapter()


Instruction:
Given the following Python 3 function, write the documentation
def child_added(self, child):
        super(AndroidViewPager, self).child_added(child)
        self._notify_count += 1
        self.get_context().timed_call(
            self._notify_delay, self._notify_change)

Response: Called by the child class when a new child is added to the pager.


Instruction:
Write a Python 3 script to
notify Java that a change has happened

Response:
def _notify_change(self):
        """ After all changes have settled, tell Java it changed """
        d = self.declaration
        self._notify_count -= 1
        if self._notify_count == 0:
            #: Tell the UI we made changes
            self.adapter.notifyDataSetChanged(now=True)
            self.get_context().timed_call(
                500, self._queue_pending_calls)


Instruction:
Explain what the following Python 3 code does
def set_current_index(self, index):
        # d = self.declaration
        # #: We have to wait for the current_index to be ready before we can
        # #: change pages
        if self._notify_count > 0:
            self._pending_calls.append(
                lambda index=index: self.widget.setCurrentItem(index))
        else:
            self.widget.setCurrentItem(index)

Response: Set the current index of the page.


Instruction:
Can you implement a function in Python 3 that
overrides as there is no width height constructor.

Response:
def create_layout_params(self, child, layout):
        """ Override as there is no (width, height) constructor.

        """
        from .android_fragment import AndroidFragment
        if isinstance(child, AndroidFragment):
            return super(AndroidViewPager, self).create_layout_params(child,
                                                                      layout)
        # Only apply to decor views
        dp = self.dp
        w, h = (coerce_size(layout.get('width', 'match_parent')),
                coerce_size(layout.get('height', 'wrap_content')))
        w = w if w < 0 else int(w * dp)
        h = h if h < 0 else int(h * dp)
        # No (w,h) constructor
        params = ViewPagerLayoutParams()
        params.width = w
        params.height = h
        params.isDecor = True
        return params


Instruction:
Create a Python 3 function for
creating the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        d = self.declaration
        self.widget = CardView(self.get_context(), None, d.style)


Instruction:
Write a Python 3 script to
create the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        d = self.declaration
        self.widget = TextClock(self.get_context(), None, d.style)


Instruction:
Write a Python 3 function for
initializing the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        super(AndroidTextClock, self).init_widget()
        d = self.declaration
        if d.format_12_hour:
            self.set_format_12_hour(d.format_12_hour)
        if d.format_24_hour:
            self.set_format_24_hour(d.format_24_hour)
        if d.time_zone:
            self.set_time_zone(d.time_zone)


Instruction:
How would you explain what the following Python 3 function does
def create_widget(self):
        d = self.declaration

        if self.indeterminate:
            #: Note: Style will only exist on activity indicators!
            style = ProgressBar.STYLES[d.size]
        else:
            style = ProgressBar.STYLE_HORIZONTAL
        self.widget = ProgressBar(self.get_context(), None, style)

Response: Create the underlying widget.


Instruction:
Can you tell what is the following Python 3 function doing
def init_widget(self):
        super(AndroidProgressBar, self).init_widget()
        d = self.declaration
        self.set_indeterminate(self.indeterminate)

        if not self.indeterminate:
            if d.max:
                self.set_max(d.max)
            if d.min:
                self.set_min(d.min)

            self.set_progress(d.progress)

            if d.secondary_progress:
                self.set_secondary_progress(d.secondary_progress)

Response: Initialize the underlying widget.


Instruction:
How would you implement a function in Python 3 that
creates the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        d = self.declaration
        self.widget = Flexbox(self.get_context(), None, d.style)


Instruction:
Write a Python 3 function that can
apply the flexbox specific layout.

Response:
def apply_layout(self, child, layout):
        """ Apply the flexbox specific layout.

        """
        params = self.create_layout_params(child, layout)
        w = child.widget
        if w:
            # padding
            if layout.get('padding'):
                dp = self.dp
                l, t, r, b = layout['padding']
                w.setPadding(int(l*dp), int(t*dp),
                             int(r*dp), int(b*dp))
        child.layout_params = params


Instruction:
Make a summary of the following Python 3 code
def toggle_keyboard(cls, flag=HIDE_IMPLICIT_ONLY):
        app = AndroidApplication.instance()
        f = app.create_future()

        def on_ready(ims):
            ims.toggleSoftInput(flag, 0)
            f.set_result(True)

        cls.get().then(on_ready)
        return f

Response: Toggle the keyboard on and off


Instruction:
Explain what the following Python 3 code does
def hide_keyboard(cls):
        app = AndroidApplication.instance()
        f = app.create_future()

        def on_ready(ims):
            view = app.view.proxy.widget

            def on_token(__id__):
                ims.hideSoftInputFromWindow(
                    JavaBridgeObject(__id__=__id__), 0).then(f.set_result)
            view.getWindowToken().then(on_token)

        cls.get().then(on_ready)
        return f

Response:
Hide keyboard if it s open

        Returns -------- result : Future that resolves when the hide is complete


Instruction:
Can you write a function in Python 3 where it
acquires the NotificationManager service async.

Response:
def get(cls):
        """ Acquires the NotificationManager service async. """
        app = AndroidApplication.instance()
        f = app.create_future()

        if cls._instance:
            f.set_result(cls._instance)
            return f

        def on_service(obj_id):
            #: Create the manager
            if not cls.instance():
                m = cls(__id__=obj_id)
            else:
                m = cls.instance()
            f.set_result(m)

        cls.from_(app).then(on_service)

        return f


Instruction:
How would you implement a function in Python 3 that
creates a new NotificationChannel.

Response:
def create_channel(cls, channel_id, name, importance=IMPORTANCE_DEFAULT,
                       description=""):
        """ Before you can deliver the notification on Android 8.0 and higher,
        you must register your app's notification channel with the system by
        passing an instance of NotificationChannel
        to createNotificationChannel().

        Parameters
        ----------
        channel_id: String-
            Channel ID
        name: String
            Channel name
        importance: Int
            One of the IMPORTANCE levels
        description: String
            Channel description

        Returns
        -------
        channel: NotificationChannel or None
            The channel that was created.

        """
        app = AndroidApplication.instance()
        if app.api_level >= 26:
            channel = NotificationChannel(channel_id, name, importance)
            channel.setDescription(description)

            NotificationChannelManager.get().then(
                lambda mgr: mgr.createNotificationChannel(channel))

            return channel


Instruction:
How would you explain what the following Python 3 function does
def show_notification(cls, channel_id, *args, **kwargs):
        app = AndroidApplication.instance()
        builder = Notification.Builder(app, channel_id)
        builder.update(*args, **kwargs)
        return builder.show()

Response: Create and show a Notification.


Instruction:
Implement a function in Python 3 to
cancel the specified notification.

Response:
def cancel_notification(cls, notification_or_id, tag=None):
        """ Cancel the notification.

        Parameters
        ----------
        notification_or_id: Notification.Builder or int
            The notification or id of a notification to clear
        tag: String
            The tag of the notification to clear

        """
        def on_ready(mgr):
            if isinstance(notification_or_id, JavaBridgeObject):
                nid = notification_or_id.__id__
            else:
                nid = notification_or_id
            if tag is None:
                mgr.cancel_(nid)
            else:
                mgr.cancel(tag, nid)
        cls.get().then(on_ready)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def init_layout(self):
        d = self.declaration
        self.create_notification()
        if d.show:
            self.set_show(d.show)

Response: Create the notification in the top down pass if show = True


Instruction:
Here you have a function in Python 3, explain what it does
def create_notification(self):
        d = self.declaration
        builder = self.builder = Notification.Builder(self.get_context(),
                                                      d.channel_id)
        d = self.declaration

        # Apply any custom settings
        if d.settings:
            builder.update(**d.settings)

        for k, v in self.get_declared_items():
            handler = getattr(self, 'set_{}'.format(k))
            handler(v)

        builder.setSmallIcon(d.icon or '@mipmap/ic_launcher')
        # app = self.get_context()
        # intent = Intent()
        # intent.setClass(app, )
        # builder.setContentIntent(PendingIntent.getActivity(app, 0, intent, 0))

        #: Set custom content if present
        for view in self.child_widgets():
            builder.setCustomContentView(view)
            break

Response: Create a new Notification.


Instruction:
Given the following Python 3 function, write the documentation
def create_widget(self):
        d = self.declaration
        button_type = UIButton.UIButtonTypeSystem if d.flat else UIButton.UIButtonTypeRoundedRect
        self.widget = UIButton(buttonWithType=button_type)

Response: Create the toolkit widget for the proxy object.


Instruction:
Can you tell what is the following Python 3 function doing
def initialize(self):
        super(Block, self).initialize()

        block = self.block

        if block: #: This block is setting the content of another block
            #: Remove the existing blocks children
            if self.mode == 'replace':
                #: Clear the blocks children
                for c in block.children:
                    c.destroy()
            #: Add this blocks children to the other block
            block.insert_children(None, self.children)

        else: #: This block is inserting it's children into it's parent
            self.parent.insert_children(self, self.children)

Response: This method is called by the block manager when the content of the block is changed.


Instruction:
How would you explain what the following Python 3 function does
def init_text(self):
        d = self.declaration
        if d.text:
            self.set_text(d.text)
        if d.text_color:
            self.set_text_color(d.text_color)
        if d.text_alignment:
            self.set_text_alignment(d.text_alignment)
        if d.font_family or d.text_size:
            self.refresh_font()
        if hasattr(d, 'max_lines') and d.max_lines:
            self.set_max_lines(d.max_lines)

Response: Initialize text properties for this widget


Instruction:
Explain what the following Python 3 code does
def init_layout(self):
        super(AndroidViewGroup, self).init_layout()
        widget = self.widget
        i = 0
        for child in self.children():
            child_widget = child.widget
            if child_widget:
                if child.layout_params:
                    widget.addView_(child_widget, i,
                                             child.layout_params)
                else:
                    widget.addView(child_widget, i)
                i += 1

        # Force layout using the default params
        if not self.layout_params:
            self.set_layout({})

Response: Add all child widgets to the view and force layout using the default params


Instruction:
Here you have a function in Python 3, explain what it does
def child_added(self, child):
        super(AndroidViewGroup, self).child_added(child)

        widget = self.widget
        #: TODO: Should index be cached?
        for i, child_widget in enumerate(self.child_widgets()):
            if child_widget == child.widget:
                if child.layout_params:
                    widget.addView_(child_widget, i,
                                             child.layout_params)
                else:
                    widget.addView(child_widget, i)

Response: Handle the child added event from the declaration.


Instruction:
Explain what the following Python 3 code does
def child_moved(self, child):
        super(AndroidViewGroup, self).child_moved(child)
        #: Remove and re-add in correct spot
        self.child_removed(child)
        self.child_added(child)

Response: Handle the child moved event from the view group.


Instruction:
Implement a function in Python 3 to
handle the child removed event from the declaration.

Response:
def child_removed(self, child):
        """ Handle the child removed event from the declaration.

        This handler will unparent the child toolkit widget. Subclasses
        which need more control should reimplement this method.

        """
        super(AndroidViewGroup, self).child_removed(child)
        if child.widget is not None:
            self.widget.removeView(child.widget)


Instruction:
Write a Python 3 function for
creating the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        d = self.declaration
        self.widget = TimePicker(self.get_context(), None,
                                 d.style or '@attr/timePickerStyle')


Instruction:
How would you explain what the following Python 3 function does
def init_widget(self):
        super(AndroidTimePicker, self).init_widget()
        d = self.declaration
        w = self.widget
        self.set_hour(d.hour)
        self.set_minute(d.minute)
        self.set_hour_mode(d.hour_mode)

        w.setOnTimeChangedListener(w.getId())
        w.onTimeChanged.connect(self.on_time_changed)

Response: Initialize the underlying widget.


Instruction:
Make a summary of the following Python 3 code
def destroy(self):
        widget = self.widget
        if widget is not None:
            parent = self.parent_widget()
            if parent is not None:
                parent.removeView(widget)
            del self.widget
        super(AndroidToolkitObject, self).destroy()

Response:
A reimplemented destructor. This destructor will clear the reference to the toolkit widget
        and set its parent to None.


Instruction:
Can you generate the documentation for the following Python 3 function
def create_widget(self):
        d = self.declaration
        self.widget = ToggleButton(self.get_context(), None,
                                   d.style or "@attr/buttonStyleToggle")

Response: Create the underlying widget.


Instruction:
Can you implement a function in Python 3 that
initializes the UIKitSwitch widget.

Response:
def init_widget(self):
        """ Bind the on property to the checked state """
        super(UiKitSwitch, self).init_widget()

        d = self.declaration
        if d.checked:
            self.set_checked(d.checked)

        #: Watch the on property for change
        #: So apparently UISwitch is not KVO compliant...
        # self.widget.addObserver(
        #     self.get_app().view_controller,
        #     forKeyPath="on",
        #     options=UISwitch.NSKeyValueObservingOptionNew|UISwitch.NSKeyValueObservingOptionOld,
        #     context=self.widget
        #)

        #: 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=UISwitch.UIControlEventValueChanged,
            andCallback=self.widget.getId(),
            usingMethod="onValueChanged",
            withValues=["on"]#,"selected"]
        )

        self.widget.onValueChanged.connect(self.on_checked_changed)


Instruction:
Can you generate the documentation for the following Python 3 function
def on_checked_changed(self, on):
        #: Since iOS decides to call this like 100 times for each defer it
        d = self.declaration
        with self.widget.setOn.suppressed():
            d.checked = on

Response: Called when the check button is changed.


Instruction:
Write a Python 3 function for
creating the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        d = self.declaration
        self.widget = Chronometer(self.get_context(), None, d.style)


Instruction:
How would you code a function in Python 3 to
initialize the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        super(AndroidChronometer, self).init_widget()
        w = self.widget
        w.setOnChronometerTickListener(w.getId())
        w.onChronometerTick.connect(self.on_chronometer_tick)


Instruction:
Explain what the following Python 3 code does
def update_function(old, new):
    for name in func_attrs:
        try:
            setattr(old, name, getattr(new, name))
        except (AttributeError, TypeError):
            pass

Response: Update the code object of a function


Instruction:
Can you implement a function in Python 3 that
replaces get set and delete functions of a property

Response:
def update_property(old, new):
    """Replace get/set/del functions of a property"""
    update_generic(old.fdel, new.fdel)
    update_generic(old.fget, new.fget)
    update_generic(old.fset, new.fset)


Instruction:
Given the following Python 3 function, write the documentation
def superreload(module, reload=reload, old_objects={}):

    # collect old objects in the module
    for name, obj in list(module.__dict__.items()):
        if not hasattr(obj, '__module__') or obj.__module__ != module.__name__:
            continue
        key = (module.__name__, name)
        try:
            old_objects.setdefault(key, []).append(weakref.ref(obj))
        except TypeError:
            pass

    # reload module
    try:
        # clear namespace first from old cruft
        old_dict = module.__dict__.copy()
        old_name = module.__name__
        module.__dict__.clear()
        module.__dict__['__name__'] = old_name
        module.__dict__['__loader__'] = old_dict['__loader__']
    except (TypeError, AttributeError, KeyError):
        pass

    try:
        module = reload(module)
    except:
        # restore module dictionary on failed reload
        module.__dict__.update(old_dict)
        raise

    # iterate over all objects and update functions & classes
    for name, new_obj in list(module.__dict__.items()):
        key = (module.__name__, name)
        if key not in old_objects: continue

        new_refs = []
        for old_ref in old_objects[key]:
            old_obj = old_ref()
            if old_obj is None: continue
            new_refs.append(old_ref)
            update_generic(old_obj, new_obj)

        if new_refs:
            old_objects[key] = new_refs
        else:
            del old_objects[key]

    return module

Response: Enhanced version of the builtin reload function.


Instruction:
Make a summary of the following Python 3 code
def mark_module_skipped(self, module_name):
        try:
            del self.modules[module_name]
        except KeyError:
            pass
        self.skip_modules[module_name] = True

Response: Mark the named module as skipped


Instruction:
Write a Python 3 script to
mark a named module as reloadable.

Response:
def mark_module_reloadable(self, module_name):
        """Reload the named module in the future (if it is imported)"""
        try:
            del self.skip_modules[module_name]
        except KeyError:
            pass
        self.modules[module_name] = True


Instruction:
Can you generate a brief explanation for the following Python 3 code
def aimport_module(self, module_name):
        self.mark_module_reloadable(module_name)

        import_module(module_name)
        top_name = module_name.split('.')[0]
        top_module = sys.modules[top_name]
        return top_module, top_name

Response: Import a module and mark it reloadable.


Instruction:
Given the following Python 3 function, write the documentation
def check(self, check_all=False, do_reload=True):

        if not self.enabled and not check_all:
            return

        if check_all or self.check_all:
            modules = list(sys.modules.keys())
        else:
            modules = list(self.modules.keys())

        for modname in modules:

            m = sys.modules.get(modname, None)
            if modname in self.skip_modules:
                continue

            py_filename, pymtime = self.filename_and_mtime(m)
            if py_filename is None:
                continue

            try:
                if pymtime <= self.modules_mtimes[modname]:
                    continue
            except KeyError:
                self.modules_mtimes[modname] = pymtime
                continue
            else:
                if self.failed.get(py_filename, None) == pymtime:
                    continue

            self.modules_mtimes[modname] = pymtime

            # If we've reached this point, we should try to reload the module
            if do_reload:
                try:
                    if self.debug:
                        print("Reloading {}".format(m))
                    superreload(m, reload, self.old_objects)
                    if py_filename in self.failed:
                        del self.failed[py_filename]
                except:
                    print("[autoreload of %s failed: %s]" % (
                        modname, traceback.format_exc(10)))
                    self.failed[py_filename] = pymtime

Response: Check whether some modules need to be reloaded.


Instruction:
Create a Python 3 function for
importing modules for automatic reloading.

Response:
def aimport(self, parameter_s='', stream=None):
        """%aimport => Import modules for automatic reloading.

        %aimport
        List modules to automatically import and not to import.

        %aimport foo
        Import module 'foo' and mark it to be autoreloaded for %autoreload 1

        %aimport foo, bar
        Import modules 'foo', 'bar' and mark them to be autoreloaded for %autoreload 1

        %aimport -foo
        Mark module 'foo' to not be autoreloaded for %autoreload 1
        """
        modname = parameter_s
        if not modname:
            to_reload = sorted(self._reloader.modules.keys())
            to_skip = sorted(self._reloader.skip_modules.keys())
            if stream is None:
                stream = sys.stdout
            if self._reloader.check_all:
                stream.write("Modules to reload:\nall-except-skipped\n")
            else:
                stream.write("Modules to reload:\n%s\n" % ' '.join(to_reload))
            stream.write("\nModules to skip:\n%s\n" % ' '.join(to_skip))
        elif modname.startswith('-'):
            modname = modname[1:]
            self._reloader.mark_module_skipped(modname)
        else:
            for _module in ([_.strip() for _ in modname.split(',')]):
                top_module, top_name = self._reloader.aimport_module(_module)

                # Inject module to user namespace
                self.shell.push({top_name: top_module})


Instruction:
Write a Python 3 script for
caching the modification times of any modules imported in this execution

Response:
def post_execute(self):
        """Cache the modification times of any modules imported in this execution
        """
        newly_loaded_modules = set(sys.modules) - self.loaded_modules
        for modname in newly_loaded_modules:
            _, pymtime = self._reloader.filename_and_mtime(sys.modules[modname])
            if pymtime is not None:
                self._reloader.modules_mtimes[modname] = pymtime

        self.loaded_modules.update(newly_loaded_modules)


Instruction:
Make a summary of the following Python 3 code
def create_widget(self):
        d = self.declaration
        self.widget = EditText(self.get_context(), None,
                               d.style or "@attr/editTextStyle")

Response: Create the underlying widget.


Instruction:
Given the following Python 3 function, write the documentation
def create_widget(self):
        d = self.declaration
        style = d.style if d.style else (
            '@attr/borderlessButtonStyle' if d.flat else '@attr/buttonStyle')
        self.widget = Button(self.get_context(), None, style)

Response: Create the underlying widget.


Instruction:
How would you explain what the following Python 3 function does
def create_widget(self):
        d = self.declaration
        self.widget = FloatingActionButton(self.get_context(), None, d.style)

Response: Create the underlying widget.


Instruction:
Explain what the following Python 3 code does
def create_widget(self):
        d = self.declaration
        self.widget = Picker(self.get_context(), None,
                             d.style or '@attr/numberPickerStyle')

Response: Create the underlying widget.


Instruction:
Explain what the following Python 3 code does
def init_widget(self):
        super(AndroidPicker, self).init_widget()
        d = self.declaration
        w = self.widget
        if d.items:
            self.set_items(d.items)
        else:
            if d.max_value:
                self.set_max_value(d.max_value)
            if d.min_value:
                self.set_min_value(d.min_value)
        self.set_value(d.value)
        if d.wraps:
            self.set_wraps(d.wraps)

        if d.long_press_update_interval:
            self.set_long_press_update_interval(d.long_press_update_interval)

        w.setOnValueChangedListener(w.getId())
        w.onValueChange.connect(self.on_value_change)

Response: Initialize the AndroidPicker widget.


Instruction:
Can you write a function in Python 3 where it
sets the checked property based on the checked state of all the children and the new value.

Response:
def on_value_change(self, picker, old, new):
        """ Set the checked property based on the checked state
        of all the children

        """
        d = self.declaration
        with self.widget.setValue.suppressed():
            d.value = new


Instruction:
Write a Python 3 function that can
create the underlying label widget.

Response:
def create_widget(self):
        """ Create the underlying label widget.

        """
        d = self.declaration
        mode = 1 if d.mode == 'dropdown' else 0
        self.widget = Spinner(self.get_context(), mode)

        # Create the adapter simple_spinner_item = 0x01090008
        self.adapter = ArrayAdapter(self.get_context(),
                                    '@layout/simple_spinner_dropdown_item')


Instruction:
Can you create a Python 3 function that
initializes the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        w = self.widget
        # Selection listener
        w.setAdapter(self.adapter)
        w.setOnItemSelectedListener(w.getId())
        w.onItemSelected.connect(self.on_item_selected)
        w.onNothingSelected.connect(self.on_nothing_selected)
        super(AndroidSpinner, self).init_widget()


Instruction:
How would you explain what the following Python 3 function does
def set_items(self, items):
        self.adapter.clear()
        self.adapter.addAll(items)

Response: Generate the view cache


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _default_objc(self):
        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

Response: Load the objc library using ctypes.


Instruction:
Here you have a function in Python 3, explain what it does
def _default_bridge(self):
        objc = self.objc
        ENBridge = objc.objc_getClass('ENBridge')
        return objc.objc_msgSend(ENBridge, objc.sel_registerName('instance'))

Response: Get an instance of the ENBridge class using ctypes.


Instruction:
How would you implement a function in Python 3 that
sends msgpack data to the ENBridge instance holding the data.

Response:
def processEvents(self, data):
        """ Sends msgpack data to the ENBridge instance
            by calling the processEvents method via ctypes. """
        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))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def current(instance=True):
        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

Response: Returns the current thread s IOLoop.


Instruction:
How would you code a function in Python 3 to
signal handler to log the stack trace of the current thread.

Response:
def log_stack(self, signal, frame):
        """Signal handler to log the stack trace of the current thread.

        For use with `set_blocking_signal_threshold`.
        """
        gen_log.warning('IOLoop blocked for %f seconds in\n%s',
                        self._blocking_signal_threshold,
                        ''.join(traceback.format_stack(frame)))


Instruction:
Can you write a function in Python 3 where it
starts the IOLoop runs the given function and stops the loop.

Response:
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.
        """
        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()


Instruction:
Can you tell what is the following Python 3 function doing
def add_timeout(self, deadline, callback, *args, **kwargs):
        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)

Response: Adds a timeout to the current time for the specified time.


Instruction:
Write a Python 3 script for
running the callback at the given delay seconds. Returns an opaque handle that can be passed to remove_timeout.

Response:
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
        """
        return self.call_at(self.time() + delay, callback, *args, **kwargs)


Instruction:
Create a Python 3 function for
running the callback at the absolute time designated by when. Returns an opaque handle that can be used to cancel the call.

Response:
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
        """
        return self.add_timeout(when, callback, *args, **kwargs)


Instruction:
Can you create a Python 3 function that
spawns a callback on the next IOLoop iteration.

Response:
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
        """
        with stack_context.NullContext():
            self.add_callback(callback, *args, **kwargs)


Instruction:
Here you have a function in Python 3, explain what it does
def add_future(self, future, callback):
        assert is_future(future)
        callback = stack_context.wrap(callback)
        future.add_done_callback(
            lambda future: self.add_callback(callback, future))

Response:
Schedules a callback on the IOLoop when the given
       . Future is finished.


Instruction:
Create a Python 3 function for
running a callback with error handling.

Response:
def _run_callback(self, callback):
        """Runs a callback with error handling.

        For use in subclasses.
        """
        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)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def close_fd(self, fd):
        try:
            try:
                fd.close()
            except AttributeError:
                os.close(fd)
        except OSError:
            pass

Response: Utility method to close an fd.


Instruction:
Create a Python 3 function for
initializing the state of the toolkit widget.

Response:
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!

        """
        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)


Instruction:
Implement a function in Python 3 to
create the underlying widget.

Response:
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).

        """
        d = self.declaration
        Snackbar.make(self.parent_widget(), d.text,
                      0 if d.duration else -2).then(self.on_widget_created)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def init_widget(self):
        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)

Response: Initialize the Android Snackbar widget.


Instruction:
Explain what the following Python 3 code does
def on_widget_created(self, ref):
        d = self.declaration
        self.widget = Snackbar(__id__=ref)
        self.init_widget()

Response:
Using Snackbar. make returns async so we have to
        initialize it later.


Instruction:
How would you code a function in Python 3 to
set the duration of the current time .

Response:
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`.

        """
        if duration == 0:
            self.widget.setDuration(-2) #: Infinite
        else:
            self.widget.setDuration(0)


Instruction:
Write a Python 3 script for
creating the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        d = self.declaration
        self.widget = SeekBar(self.get_context(), None,
                              d.style or '@attr/seekBarStyle')


Instruction:
Can you implement a function in Python 3 that
initializes the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        super(AndroidSeekBar, self).init_widget()
        w = self.widget

        #: Setup listener
        w.setOnSeekBarChangeListener(w.getId())
        w.onProgressChanged.connect(self.on_progress_changed)


Instruction:
Create a Python 3 function to
create the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        d = self.declaration
        self.widget = TextView(self.get_context(), None,
                               d.style or '@attr/textViewStyle')


Instruction:
Implement a function in Python 3 to
initialize the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        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)


Instruction:
How would you implement a function in Python 3 that
sets the text in the widget.

Response:
def set_text(self, text):
        """ Set the text in the widget.

        """
        d = self.declaration
        if d.input_type == 'html':
            text = Spanned(__id__=Html.fromHtml(text))
        self.widget.setTextKeepState(text)


Instruction:
How would you implement a function in Python 3 that
creates the underlying widget.

Response:
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.

        """
        d = self.declaration
        self.dialog = BottomSheetDialog(self.get_context(), d.style)


Instruction:
Create a Python 3 function for
encoding an object for proper decoding by Java or ObjC

Response:
def encode(obj):
    """ Encode an object for proper decoding by Java or ObjC
    """
    if hasattr(obj, '__id__'):
        return msgpack.ExtType(ExtType.REF, msgpack.packb(obj.__id__))
    return obj


Instruction:
Can you tell what is the following Python 3 function doing
def get_handler(ptr, method):
    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)

Response: Dereference the pointer and return the handler method.


Instruction:
Given the following Python 3 function, write the documentation
def suppressed(self, obj):
        obj.__suppressed__[self.name] = True
        yield
        obj.__suppressed__[self.name] = False

Response: Suppress calls within this context to avoid feedback loops


Instruction:
Implement a function in Python 3 to
initialize the state of the toolkit widget.

Response:
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.

        """
        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()


Instruction:
Implement a function in Python 3 to
check if wifi is currently enabled. Returns a future that resolves with the value.

Response:
def is_wifi_enabled(cls):
        """ Check if wifi is currently enabled.

        Returns
        --------
            result: future
              A future that resolves with the value.

        """
        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


Instruction:
Write a Python 3 script to
set the wifi enabled state.

Response:
def set_wifi_enabled(cls, state=True):
        """ Set the wifi enabled state.

        Returns
        --------
            result: future
              A future that resolves with whether the operation succeeded.

        """
        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


Instruction:
Can you tell what is the following Python 3 function doing
def get_networks(cls):
        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

Response: Get the list of wifi networks currently available.


Instruction:
Write a Python 3 function for
disconnecting from the current network.

Response:
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.

        """
        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


Instruction:
How would you code a function in Python 3 to
connect to the given ssid using the given key.

Response:
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

        """
        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


Instruction:
Implement a function in Python 3 to
get info about current wifi connection.

Response:
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

         """
        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


Instruction:
How would you code a function in Python 3 to
request permission and returns an future result that returns a boolean indicating if all the given permissions were granted or denied.

Response:
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.

        """
        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


Instruction:
How would you implement a function in Python 3 that
initializes the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        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)


Instruction:
Can you generate the documentation for the following Python 3 function
def _update_proxy(self, change):
        if change['type'] == 'event':
            self.proxy.set_refreshed(True)
        else:
            super(SwipeRefreshLayout, self)._update_proxy(change)

Response: An observer which sends the state change to the proxy.


Instruction:
Make a summary of the following Python 3 code
def return_future(f):
    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

Response:
Decorator to make a function that returns via callback return a
Formula


Instruction:
Can you create a Python 3 function that
chains two futures together so that when one completes then does the other.

Response:
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.
    """
    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)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def result(self, timeout=None):
        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

Response: If the operation succeeded return its result. If it failed return its exception.


Instruction:
Can you generate the documentation for the following Python 3 function
def exception(self, timeout=None):
        self._clear_tb_log()
        if self._exc_info is not None:
            return self._exc_info[1]
        else:
            self._check_done()
            return None

Response: Returns the Exception object if the operation raised an exception otherwise returns None.


Instruction:
Can you tell what is the following Python 3 function doing
def add_done_callback(self, fn):
        if self._done:
            fn(self)
        else:
            self._callbacks.append(fn)

Response: Attaches the given callback to the Future.


Instruction:
Here you have a function in Python 3, explain what it does
def set_exception(self, exception):
        self.set_exc_info(
            (exception.__class__,
             exception,
             getattr(exception, '__traceback__', None)))

Response: Sets the exception of a Future.


Instruction:
Implement a function in Python 3 to
set the exception information of a Future.

Response:
def set_exc_info(self, exc_info):
        """Sets the exception information of a ``Future.``

        Preserves tracebacks on Python 2.

        .. versionadded:: 4.0
        """
        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


Instruction:
Can you write a function in Python 3 where it
creates the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        d = self.declaration
        self.widget = CoordinatorLayout(self.get_context(), None, d.style)


Instruction:
Implement a function in Python 3 to
initialize the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        super(AndroidCompoundButton, self).init_widget()
        w = self.widget
        w.setOnCheckedChangeListener(w.getId())
        w.onCheckedChanged.connect(self.on_checked)


Instruction:
Given the following Python 3 function, write the documentation
def create_widget(self):
        d = self.declaration
        self.widget = RelativeLayout(self.get_context(), None, d.style)

Response: Create the underlying widget.


Instruction:
Write a Python 3 script to
initialize the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        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)


Instruction:
Can you generate the documentation for the following Python 3 function
def init_widget(self):
        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)

Response: Initialize the underlying widget.


Instruction:
Given the following Python 3 function, write the documentation
def init_layout(self):
        super(AndroidTextureView, self).init_layout()

        # Force layout using the default params
        if not self.layout_params:
            self.set_layout({})

Response: Initialize the layout of the AndroidTextureView.


Instruction:
Can you write a function in Python 3 where it
creates the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        d = self.declaration
        self.widget = DrawerLayout(self.get_context(),  None, d.style)


Instruction:
How would you implement a function in Python 3 that
initializes the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        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)


Instruction:
Make a summary of the following Python 3 code
def init_layout(self):
        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)

Response: Initialize the layout of the toolkit widget.


Instruction:
Write a Python 3 function for
handling the child added event from the declaration.

Response:
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.

        """
        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)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def child_removed(self, child):
        layout = self.layout
        if child.widget is not None:
            layout.removeArrangedSubview(child.widget)
            layout.removeSubview(child.widget)

Response: Handle the child removed event from the declaration.