Instruction:
Implement a function in Python 3 to
pack the arguments passed to the method into a list of strings.

Response:
def pack_args(self, obj, *args, **kwargs):
        """ Arguments must be packed according to the kwargs passed and
        the signature defined.

        """
        signature = self.__signature__
        #: No arguments expected
        if not signature:
            return (self.name, [])

        #: Build args, first is a string, subsequent are dictionaries
        method_name = [self.name]
        bridge_args = []
        for i, sig in enumerate(signature):
            if i == 0:
                method_name.append(":")
                bridge_args.append(msgpack_encoder(sig, args[0]))
                continue

            #: Sig is a dict so we must pull out the matching kwarg
            found = False
            for k in sig:
                if k in kwargs:
                    method_name.append("{}:".format(k))
                    bridge_args.append(msgpack_encoder(sig[k], kwargs[k]))
                    found = True
                    break
            if not found:
                #: If we get here something is wrong
                raise ValueError("Unexpected or missing argument at index {}. "
                                 "Expected {}".format(i, sig))

        return ("".join(method_name), bridge_args)


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

Response: Create the underlying widget.


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

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

        """
        super(AndroidRatingBar, self).init_widget()
        d = self.declaration
        self.set_rating(d.rating)
        w = self.widget
        w.setOnRatingBarChangeListener(w.getId())
        w.onRatingChanged.connect(self.on_rating_changed)


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 = LinearLayout(self.get_context(), None, d.style)


Instruction:
Here you have a function in Python 3, explain what it does
def create_widget(self):
        d = self.declaration
        self.widget = FrameLayout(self.get_context(), None, d.style)

Response: Create the underlying widget.


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

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

        """
        context = self.get_context()
        d = self.declaration
        style = d.style or '@attr/autoCompleteTextViewStyle'
        self.widget = AutoCompleteTextView(context, None, style)
        self.adapter = ArrayAdapter(context, '@layout/simple_list_item_1')


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

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

        """
        super(AndroidAutoCompleteTextView, self).init_widget()
        self.widget.setAdapter(self.adapter)


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 = Icon(self.get_context(), None, d.style)


Instruction:
Write a Python 3 function for
removing deactivated handlers from the chain

Response:
def _remove_deactivated(contexts):
    """Remove deactivated handlers from the chain"""
    # Clean ctx handlers
    stack_contexts = tuple([h for h in contexts[0] if h.active])

    # Find new head
    head = contexts[1]
    while head is not None and not head.active:
        head = head.old_contexts[1]

    # Process chain
    ctx = head
    while ctx is not None:
        parent = ctx.old_contexts[1]

        while parent is not None:
            if parent.active:
                break
            ctx.old_contexts = parent.old_contexts
            parent = parent.old_contexts[1]

        ctx = parent

    return (stack_contexts, head)


Instruction:
Can you generate the documentation for the following Python 3 function
def wrap(fn):
    # Check if function is already wrapped
    if fn is None or hasattr(fn, '_wrapped'):
        return fn

    # Capture current stack head
    # TODO: Any other better way to store contexts and update them in wrapped function?
    cap_contexts = [_state.contexts]

    if not cap_contexts[0][0] and not cap_contexts[0][1]:
        # Fast path when there are no active contexts.
        def null_wrapper(*args, **kwargs):
            try:
                current_state = _state.contexts
                _state.contexts = cap_contexts[0]
                return fn(*args, **kwargs)
            finally:
                _state.contexts = current_state
        null_wrapper._wrapped = True
        return null_wrapper

    def wrapped(*args, **kwargs):
        ret = None
        try:
            # Capture old state
            current_state = _state.contexts

            # Remove deactivated items
            cap_contexts[0] = contexts = _remove_deactivated(cap_contexts[0])

            # Force new state
            _state.contexts = contexts

            # Current exception
            exc = (None, None, None)
            top = None

            # Apply stack contexts
            last_ctx = 0
            stack = contexts[0]

            # Apply state
            for n in stack:
                try:
                    n.enter()
                    last_ctx += 1
                except:
                    # Exception happened. Record exception info and store top-most handler
                    exc = sys.exc_info()
                    top = n.old_contexts[1]

            # Execute callback if no exception happened while restoring state
            if top is None:
                try:
                    ret = fn(*args, **kwargs)
                except:
                    exc = sys.exc_info()
                    top = contexts[1]

            # If there was exception, try to handle it by going through the exception chain
            if top is not None:
                exc = _handle_exception(top, exc)
            else:
                # Otherwise take shorter path and run stack contexts in reverse order
                while last_ctx > 0:
                    last_ctx -= 1
                    c = stack[last_ctx]

                    try:
                        c.exit(*exc)
                    except:
                        exc = sys.exc_info()
                        top = c.old_contexts[1]
                        break
                else:
                    top = None

                # If if exception happened while unrolling, take longer exception handler path
                if top is not None:
                    exc = _handle_exception(top, exc)

            # If exception was not handled, raise it
            if exc != (None, None, None):
                raise_exc_info(exc)
        finally:
            _state.contexts = current_state
        return ret

    wrapped._wrapped = True
    return wrapped

Response: Wraps a function that will restore the current stack head when executed.


Instruction:
Here you have a function in Python 3, explain what it does
def start(self, callback, rate=SENSOR_DELAY_NORMAL):
        if not self.manager:
            raise RuntimeError(
                "Cannot start a sensor without a SensorManager!")
        self.onSensorChanged.connect(callback)
        return self.manager.registerListener(self.getId(), self, rate)

Response: Starts listening to events for this sensor.


Instruction:
Can you generate the documentation for the following Python 3 function
def init_widget(self):
        super(AndroidListView, self).init_widget()
        d = self.declaration
        self.set_arrangement(d.arrangement)

Response: Initialize the underlying widget.


Instruction:
Explain what the following Python 3 code does
def get_declared_items(self):
        for k, v in super(AndroidListView, self).get_declared_items():
            if k == 'layout':
                yield k, v
                break

Response: Return a generator of all items that are declared in this list view.


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

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

        """
        super(AndroidListView, self).init_layout()
        d = self.declaration
        w = self.widget

        # Prepare adapter
        adapter = self.adapter = BridgedRecyclerAdapter(w)

        # I'm sure this will make someone upset haha
        adapter.setRecyleListener(adapter.getId())
        adapter.onRecycleView.connect(self.on_recycle_view)
        #adapter.onVisibleCountChanged.connect(self.on_visible_count_changed)
        #adapter.onScrollStateChanged.connect(self.on_scroll_state_changed)
        self.set_items(d.items)
        w.setAdapter(adapter)
        #self.set_selected(d.selected)
        self.refresh_views()


Instruction:
Here you have a function in Python 3, explain what it does
def on_recycle_view(self, index, position):
        item = self.list_items[index]
        self.item_mapping[position] = item
        item.recycle_view(position)

Response: Recycle the item at the given index


Instruction:
Write a Python 3 script to
refresh the views that the adapter will cycle through.

Response:
def refresh_views(self, change=None):
        """ Set the views that the adapter will cycle through. """
        adapter = self.adapter

        # Set initial ListItem state
        item_mapping = self.item_mapping
        for i, item in enumerate(self.list_items):
            item_mapping[i] = item
            item.recycle_view(i)

        if adapter:
           adapter.clearRecycleViews()
           adapter.setRecycleViews(
                [encode(li.get_view()) for li in self.list_items])


Instruction:
Here you have a function in Python 3, explain what it does
def _on_items_changed(self, change):
        if change['type'] != 'container':
            return
        op = change['operation']
        if op == 'append':
            i = len(change['value'])-1
            self.adapter.notifyItemInserted(i)
        elif op == 'insert':
            self.adapter.notifyItemInserted(change['index'])
        elif op in ('pop', '__delitem__'):
            self.adapter.notifyItemRemoved(change['index'])
        elif op == '__setitem__':
            self.adapter.notifyItemChanged(change['index'])
        elif op == 'extend':
            n = len(change['items'])
            i = len(change['value'])-n
            self.adapter.notifyItemRangeInserted(i, n)
        elif op in ('remove', 'reverse', 'sort'):
            # Reset everything for these
            self.adapter.notifyDataSetChanged()

Response: Observe items changed and update the adapter appropriately.


Instruction:
Can you implement a function in Python 3 that
tells the view to render the item at the given position

Response:
def recycle_view(self, position):
        """ Tell the view to render the item at the given position """
        d = self.declaration

        if position < len(d.parent.items):
            d.index = position
            d.item = d.parent.items[position]
        else:
            d.index = -1
            d.item = None


Instruction:
Make a summary of the following Python 3 code
def errno_from_exception(e):
    # type: (BaseException) -> Optional[int]
    """Provides the errno from an Exception object.

    There are cases that the errno attribute was not set so we pull
    the errno out of the args but if someone instantiates an Exception
    without any args you will get a tuple error. So this function
    abstracts all that behavior to give you a safe way to get the
    errno.
    """

    if hasattr(e, 'errno'):
        return e.errno  # type: ignore
    elif e.args:
        return e.args[0]
    else:
        return None

Response: Provides the errno attribute from an exception object.


Instruction:
Make a summary of the following Python 3 code
def _websocket_mask_python(mask, data):
    # type: (bytes, bytes) -> bytes
    """Websocket masking function.

    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.
    Returns a `bytes` object of the same length as `data` with the mask applied
    as specified in section 5.3 of RFC 6455.

    This pure-python implementation may be replaced by an optimized version when available.
    """
    mask_arr = array.array("B", mask)
    unmasked_arr = array.array("B", data)
    for i in xrange(len(data)):
        unmasked_arr[i] = unmasked_arr[i] ^ mask_arr[i % 4]
    if PY3:
        # tostring was deprecated in py32.  It hasn't been removed,
        # but since we turn on deprecation warnings in our tests
        # we need to use the right one.
        return unmasked_arr.tobytes()
    else:
        return unmasked_arr.tostring()

Response:
Websocket masking function.

    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.
    Returns a `bytes` object of the same length as `data` with the mask applied
    as specified in section 5.3 of RFC 6455.

    This pure-python implementation may be replaced by an optimized version when available.


Instruction:
Here you have a function in Python 3, explain what it does
def configure(cls, impl, **kwargs):
        # type: (Any, **Any) -> None
        """Sets the class to use when the base class is instantiated.

        Keyword arguments will be saved and added to the arguments passed
        to the constructor.  This can be used to set global defaults for
        some parameters.
        """
        base = cls.configurable_base()
        if isinstance(impl, (str, unicode_type)):
            impl = import_object(impl)
        if impl is not None and not issubclass(impl, cls):
            raise ValueError("Invalid subclass of %s" % cls)
        base.__impl_class = impl
        base.__impl_kwargs = kwargs

Response: Sets the class to use when the base class is instantiated.


Instruction:
Create a Python 3 function to
return the currently configured class.

Response:
def configured_class(cls):
        # type: () -> type
        """Returns the currently configured class."""
        base = cls.configurable_base()
        # Manually mangle the private name to see whether this base
        # has been configured (and not another base higher in the
        # hierarchy).
        if base.__dict__.get('_Configurable__impl_class') is None:
            base.__impl_class = cls.configurable_default()
        return base.__impl_class


Instruction:
Explain what the following Python 3 code does
def get_old_value(self, args, kwargs, default=None):
        # type: (List[Any], Dict[str, Any], Any) -> Any
        """Returns the old value of the named argument without replacing it.

        Returns ``default`` if the argument is not present.
        """
        if self.arg_pos is not None and len(args) > self.arg_pos:
            return args[self.arg_pos]
        else:
            return kwargs.get(self.name, default)

Response: Returns the old value of the named argument without replacing it.


Instruction:
Write a Python 3 script for
replacing the named argument in args with new_value.

Response:
def replace(self, new_value, args, kwargs):
        # type: (Any, List[Any], Dict[str, Any]) -> Tuple[Any, List[Any], Dict[str, Any]]
        """Replace the named argument in ``args, kwargs`` with ``new_value``.

        Returns ``(old_value, args, kwargs)``.  The returned ``args`` and
        ``kwargs`` objects may not be the same as the input objects, or
        the input objects may be mutated.

        If the named argument was not found, ``new_value`` will be added
        to ``kwargs`` and None will be returned as ``old_value``.
        """
        if self.arg_pos is not None and len(args) > self.arg_pos:
            # The arg to replace is passed positionally
            old_value = args[self.arg_pos]
            args = list(args)  # *args is normally a tuple
            args[self.arg_pos] = new_value
        else:
            # The arg to replace is either omitted or passed by keyword.
            old_value = kwargs.get(self.name)
            kwargs[self.name] = new_value
        return old_value, args, kwargs


Instruction:
Implement a function in Python 3 to
show the notification from code.

Response:
def popup(self):
        """ Show the notification from code. This will initialize and activate
        if needed.

        Notes
        ------
        This does NOT block. Callbacks should be used to handle click events
        or the `show` state should be observed to know when it is closed.

        """
        if not self.is_initialized:
            self.initialize()
        if not self.proxy_is_active:
            self.activate_proxy()
        self.show = True


Instruction:
Can you generate the documentation for the following Python 3 function
def create_widget(self):
        d = self.declaration
        if d.text:
            Toast.makeText(self.get_context(),
                           d.text, 1).then(self.on_make_toast)
            self.made_toast = True
        else:
            self.toast = Toast(self.get_context())

Response: Create the underlying toast.


Instruction:
Can you tell what is the following Python 3 function doing
def init_widget(self):
        if not self.toast:
            return
        super(AndroidToast, self).init_widget()

        d = self.declaration
        if not self.made_toast:
            #: Set it to LONG
            self.toast.setDuration(1)
        if d.gravity:
            self.set_gravity(d.gravity)
        if d.show:
            self.set_show(d.show)

Response: Initialize the AndroidToast widget.


Instruction:
Implement a Python 3 function for
initializing the layout of the toast.

Response:
def init_layout(self):
        """ If a view is given show it """
        super(AndroidToast, self).init_layout()
        if not self.made_toast:
            for view in self.child_widgets():
                self.toast.setView(view)
                break


Instruction:
Explain what the following Python 3 code does
def child_added(self, child):
        view = child.widget
        if view is not None:
            self.toast.setView(view)

Response: Overwrite the view of the child


Instruction:
Can you tell what is the following Python 3 function doing
def on_make_toast(self, ref):
        d = self.declaration
        self.toast = Toast(__id__=ref)
        self.init_widget()

Response: Using Toast. makeToast returns async so we have to initialize it


Instruction:
How would you explain what the following Python 3 function does
def _refresh_show(self, dt):
        d = self.declaration
        if dt <= 0:
            #: Done, hide
            d.show = False
        elif d.show:
            #: If user didn't cancel it, keep it alive
            self.toast.show()

            t = min(1000, dt)
            app = self.get_context()
            app.timed_call(t, self._refresh_show, dt-t)

Response:
Keep calling. show until the
        duration dt expires.


Instruction:
Explain what the following Python 3 code does
def create_widget(self):
        d = self.declaration
        self.dialog = Dialog(self.get_context(), d.style)

Response: Create the underlying dialog.


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

Response:
def init_widget(self):
        """ Set the listeners
        """
        w = self.dialog
        # Listen for events
        w.setOnDismissListener(w.getId())
        w.onDismiss.connect(self.on_dismiss)
        w.setOnCancelListener(w.getId())
        w.onCancel.connect(self.on_cancel)
        super(AndroidDialog, self).init_widget()


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

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

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

Response: Initialize the layout of the dialog.


Instruction:
Can you generate the documentation for the following Python 3 function
def child_added(self, child):
        view = child.widget
        if view is not None:
            self.dialog.setContentView(view)

Response: Overwrite the content view of the given child.


Instruction:
Make a summary of the following Python 3 code
def destroy(self):
        dialog = self.dialog
        if dialog:
            #: Clear the dismiss listener
            #: (or we get an error during the callback)
            dialog.setOnDismissListener(None)
            dialog.dismiss()
            del self.dialog
        super(AndroidDialog, self).destroy()

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


Instruction:
Implement a Python 3 function for
starting a new instance of LocationManager.

Response:
def start(cls, callback, provider='gps', min_time=1000, min_distance=0):
        """ Convenience method that checks and requests permission if necessary
        and if successful calls the callback with a populated `Location`
        instance on updates.

        Note you must have the permissions in your manifest or requests
        will be denied immediately.

        """
        app = AndroidApplication.instance()
        f = app.create_future()

        def on_success(lm):
            #: When we have finally have permission
            lm.onLocationChanged.connect(callback)

            #: Save a reference to our listener
            #: because we may want to stop updates
            listener = LocationManager.LocationListener(lm)
            lm.listeners.append(listener)

            lm.requestLocationUpdates(provider, min_time, min_distance,
                                      listener)
            app.set_future_result(f, True)

        def on_perm_request_result(allowed):
            #: When our permission request is accepted or decliend.
            if allowed:
                LocationManager.get().then(on_success)
            else:
                #: Access denied
                app.set_future_result(f, False)

        def on_perm_check(allowed):
            if allowed:
                LocationManager.get().then(on_success)
            else:
                LocationManager.request_permission(
                    fine=provider == 'gps').then(on_perm_request_result)

        #: Check permission
        LocationManager.check_permission(
            fine=provider == 'gps').then(on_perm_check)

        return f


Instruction:
How would you explain what the following Python 3 function does
def stop(cls):
        manager = LocationManager.instance()
        if manager:
            for l in manager.listeners:
                manager.removeUpdates(l)
            manager.listeners = []

Response: Stops location updates if currently updating.


Instruction:
Implement a function in Python 3 to
return a future that returns a boolean indicating if permission is currently granted or denied.

Response:
def check_permission(cls, fine=True):
        """ Returns a future that returns a boolean indicating if permission
        is currently granted or denied. If permission is denied, you can
        request using `LocationManager.request_permission()` below.

        """
        app = AndroidApplication.instance()
        permission = (cls.ACCESS_FINE_PERMISSION
                      if fine else cls.ACCESS_COARSE_PERMISSION)
        return app.has_permission(permission)


Instruction:
Given the following Python 3 function, write the documentation
def request_permission(cls, fine=True):
        app = AndroidApplication.instance()
        permission = (cls.ACCESS_FINE_PERMISSION
                      if fine else cls.ACCESS_COARSE_PERMISSION)
        f = app.create_future()

        def on_result(perms):
            app.set_future_result(f, perms[permission])

        app.request_permissions([permission]).then(on_result)

        return f

Response:
Requests permission and returns an async result that returns
        a boolean indicating if the permission was granted or denied.


Instruction:
Here you have a function in Python 3, explain what it does
def create_widget(self):
        d = self.declaration
        self.widget = WebView(self.get_context(), None, d.style)

Response: Create the underlying widget.


Instruction:
Can you generate the documentation for the following Python 3 function
def init_widget(self):
        # Create and init the client
        c = self.client = BridgedWebViewClient()
        c.setWebView(self.widget, c.getId())
        c.onLoadResource.connect(self.on_load_resource)
        c.onPageFinished.connect(self.on_page_finished)
        c.onPageStarted.connect(self.on_page_started)
        c.onReceivedError.connect(self.on_received_error)
        c.onScaleChanged.connect(self.on_scale_changed)
        c.onProgressChanged.connect(self.on_progress_changed)
        c.onReceivedTitle.connect(self.on_page_title_changed)

        super(AndroidWebView, self).init_widget()

Response: Initialize the underlying webview.


Instruction:
Here you have a function in Python 3, explain what it does
def destroy(self):
        if self.client:
            #: Stop listening
            self.client.setWebView(self.widget, None)
            del self.client
        super(AndroidWebView, self).destroy()

Response: Destroy the client and the widget.


Instruction:
Create a Python 3 function to
bind the on property to the checked state

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

        d = self.declaration
        if d.min:
            self.set_min(d.min)
        if d.max:
            self.set_max(d.max)
        if d.progress:
            self.set_progress(d.progress)

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

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


Instruction:
How would you explain what the following Python 3 function does
def on_checked_changed(self, value):
        #: Since iOS decides to call this like 100 times for each defer it
        d = self.declaration
        with self.widget.setValue.suppressed():
            d.progress = int(value)

Response: Update the progress of the check button.


Instruction:
Implement a function in Python 3 to
initialize the radio group.

Response:
def init_layout(self):
        """ Set the checked state after all children have
        been populated.

        """
        super(AndroidRadioGroup, self).init_layout()
        d = self.declaration
        w = self.widget
        if d.checked:
            self.set_checked(d.checked)
        else:
            #: Check if any of the children have "checked = True"
            for c in d.children:
                if c.checked:
                    d.checked = c

        w.setOnCheckedChangeListener(w.getId())
        w.onCheckedChanged.connect(self.on_checked_changed)


Instruction:
Explain what the following Python 3 code does
def on_checked_changed(self, group, checked_id):
        d = self.declaration
        if checked_id < 0:
            with self.widget.clearCheck.suppressed():
                d.checked = None
            return
        else:
            for c in self.children():
                if c.widget.getId() == checked_id:
                    with self.widget.check.suppressed():
                        d.checked = c.declaration
                    return

Response: Called when a checked attribute is changed in the group.


Instruction:
Write a Python 3 function for
setting the radio button to be checked.

Response:
def set_checked(self, checked):
        """ Properly check the correct radio button.

        """
        if not checked:
            self.widget.clearCheck()
        else:
            #: Checked is a reference to the radio declaration
            #: so we need to get the ID of it
            rb = checked.proxy.widget
            if not rb:
                return
            self.widget.check(rb.getId())


Instruction:
Can you generate the documentation for the following Python 3 function
def init_widget(self):
        #: Add a ActivityLifecycleListener to update the application state
        activity = self.widget
        activity.addActivityLifecycleListener(activity.getId())
        activity.onActivityLifecycleChanged.connect(
            self.on_activity_lifecycle_changed)

        #: Add BackPressedListener to trigger the event
        activity.addBackPressedListener(activity.getId())
        activity.onBackPressed.connect(self.on_back_pressed)

        #: Add ConfigurationChangedListener to trigger the event
        activity.addConfigurationChangedListener(activity.getId())
        activity.onConfigurationChanged.connect(self.on_configuration_changed)

Response: Initialize on the first call to the widget.


Instruction:
Given the following Python 3 function, write the documentation
def has_permission(self, permission):
        f = self.create_future()

        #: Old versions of android did permissions at install time
        if self.api_level < 23:
            f.set_result(True)
            return f

        def on_result(allowed):
            result = allowed == Activity.PERMISSION_GRANTED
            self.set_future_result(f, result)

        self.widget.checkSelfPermission(permission).then(on_result)

        return f

Response:
Return a future that resolves with the result of the permission
RUKnce.


Instruction:
Can you implement a function in Python 3 that
requests the permissions of the specified set of permissions.

Response:
def request_permissions(self, permissions):
        """ Return a future that resolves with the results
        of the permission requests

        """
        f = self.create_future()

        #: Old versions of android did permissions at install time
        if self.api_level < 23:
            f.set_result({p: True for p in permissions})
            return f

        w = self.widget
        request_code = self._permission_code
        self._permission_code += 1  #: So next call has a unique code

        #: On first request, setup our listener, and request the permission
        if request_code == 0:
            w.setPermissionResultListener(w.getId())
            w.onRequestPermissionsResult.connect(self._on_permission_result)

        def on_results(code, perms, results):
            #: Check permissions
            f.set_result({p: r == Activity.PERMISSION_GRANTED
                          for (p, r) in zip(perms, results)})

        #: Save a reference
        self._permission_requests[request_code] = on_results

        #: Send out the request
        self.widget.requestPermissions(permissions, request_code)

        return f


Instruction:
Implement a Python 3 function for
showing a toast message for the given duration.

Response:
def show_toast(self, msg, long=True):
        """ Show a toast message for the given duration.
        This is an android specific api.

        Parameters
        -----------
        msg: str
            Text to display in the toast message
        long: bool
            Display for a long or short (system defined) duration

        """
        from .android_toast import Toast

        def on_toast(ref):
            t = Toast(__id__=ref)
            t.show()

        Toast.makeText(self, msg, 1 if long else 0).then(on_toast)


Instruction:
Here you have a function in Python 3, explain what it does
def on_back_pressed(self):
        try:
            event = {'handled': False}
            self.back_pressed(event)
            return bool(event.get('handled', False))
        except Exception as e:
            #: Must return a boolean or we will cause android to abort
            return False

Response:
Fire the back_pressed event with a dictionary with a handled key that evaluates to True and return a boolean that is True if the back hardware button is pressed
AttributeNames
            is not set to any value that evaluates to True.


Instruction:
Can you generate the documentation for the following Python 3 function
def on_configuration_changed(self, config):
        self.width = config['width']
        self.height = config['height']
        self.orientation = ('square', 'portrait', 'landscape')[
                            config['orientation']]

Response: Handles a screen configuration change.


Instruction:
Create a Python 3 function to
show the current view. This will fade out the previous view. This will fade out the new view.

Response:
def show_view(self):
        """ Show the current `app.view`. This will fade out the previous
            with the new view.

        """
        if not self.build_info:
            def on_build_info(info):
                """ Make sure the build info is ready before we
                display the view

                """
                self.dp = info['DISPLAY_DENSITY']
                self.width = info['DISPLAY_WIDTH']
                self.height = info['DISPLAY_HEIGHT']
                self.orientation = ('square', 'portrait', 'landscape')[
                                    info['DISPLAY_ORIENTATION']]
                self.api_level = info['SDK_INT']
                self.build_info = info
                self._show_view()

            self.init_widget()
            self.widget.getBuildInfo().then(on_build_info)
        else:
            self._show_view()


Instruction:
Implement a function in Python 3 to
handle a permission request result by passing it to the appropriate handler with the given code.

Response:
def _on_permission_result(self, code, perms, results):
        """ Handles a permission request result by passing it to the
         handler with the given code.

        """
        #: Get the handler for this request
        handler = self._permission_requests.get(code, None)
        if handler is not None:
            del self._permission_requests[code]

            #: Invoke that handler with the permission request response
            handler(code, perms, results)


Instruction:
Write a Python 3 function for
setting or clears the flag to keep the screen on.

Response:
def _observe_keep_screen_on(self, change):
        """ Sets or clears the flag to keep the screen on.

        """
        def set_screen_on(window):
            from .android_window import Window
            window = Window(__id__=window)
            if self.keep_screen_on:
                window.addFlags(Window.FLAG_KEEP_SCREEN_ON)
            else:
                window.clearFlags(Window.FLAG_KEEP_SCREEN_ON)

        self.widget.getWindow().then(set_screen_on)


Instruction:
How would you explain what the following Python 3 function does
def load_plugin_factories(self):
        for plugin in self.get_plugins(group='enaml_native_android_factories'):
            get_factories = plugin.load()
            PLUGIN_FACTORIES = get_factories()
            factories.ANDROID_FACTORIES.update(PLUGIN_FACTORIES)

Response: Load all plugin toolkit widgets into the ANDROID_FACTORIES dictionary.


Instruction:
Make a summary of the following Python 3 code
def init_widget(self):
        super(UiKitEditText, self).init_widget()

        #: Init font properties etc...
        self.init_text()

        d = self.declaration
        if d.placeholder:
            self.set_placeholder(d.placeholder)
        if d.input_type != 'text':
            self.set_input_type(d.input_type)
        if d.style:
            self.set_style(d.style)

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

        self.widget.onValueChanged.connect(self.on_value_changed)

Response: Initialize the widget and bind the on property to the checked state


Instruction:
Can you generate a brief explanation for the following Python 3 code
def on_value_changed(self, text):
        d = self.declaration
        with self.widget.get_member('text').suppressed(self.widget):
            d.text = text

Response: Update the text field of the resource entry.


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

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

        """
        d = self.declaration
        self.widget = DatePicker(self.get_context(), None,
                                 d.style or "@attr/datePickerStyle")


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

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

        """
        d = self.declaration
        w = self.widget
        date = d.date
        w.init(date.year, date.month-1, date.day, w.getId())
        super(AndroidDatePicker, self).init_widget()
        w.onDateChanged.connect(self.on_date_changed)


Instruction:
Write a Python 3 function for
installing the import hook to load python extensions from app s lib folder during the context of this block.

Response:
def imports():
    """ Install the import hook to load python extensions from app's lib folder
        during the context of this block.

        This method is preferred as it's faster than using install.
    """
    from .core.import_hooks import ExtensionImporter
    importer = ExtensionImporter()
    sys.meta_path.append(importer)
    yield
    sys.meta_path.remove(importer)


Instruction:
Write a Python 3 function that can
install the import hook to load extensions from the app Lib folder.

Response:
def install():
    """ Install the import hook to load extensions from the app Lib folder.
        Like imports but leaves it in the meta_path, thus it is slower.
    """
    from .core.import_hooks import ExtensionImporter
    importer = ExtensionImporter()
    sys.meta_path.append(importer)


Instruction:
Implement a Python 3 function for
giving the path to a. pyc. file return the path to its. py file.

Response:
def source_from_cache(path):
    """Given the path to a .pyc. file, return the path to its .py file.
    The .pyc file does not need to exist; this simply returns the path to
    the .py file calculated to correspond to the .pyc file.  If path does
    not conform to PEP 3147/488 format, ValueError will be raised. If
    sys.implementation.cache_tag is None then NotImplementedError is raised.
    """
    #if sys.implementation.cache_tag is None:
    #    raise NotImplementedError('sys.implementation.cache_tag is None')
    #path = os.fspath(path)
    head, pycache_filename = os.path.split(path)
    head, pycache = os.path.split(head)
    if pycache != _PYCACHE:
        raise ValueError('{} not bottom-level directory in '
                         '{!r}'.format(_PYCACHE, path))
    dot_count = pycache_filename.count('.')
    if dot_count not in {2, 3}:
        raise ValueError('expected only 2 or 3 dots in '
                         '{!r}'.format(pycache_filename))
    elif dot_count == 3:
        optimization = pycache_filename.rsplit('.', 2)[-2]
        if not optimization.startswith(_OPT):
            raise ValueError("optimization portion of filename does not start "
                             "with {!r}".format(_OPT))
        opt_level = optimization[len(_OPT):]
        if not opt_level.isalnum():
            raise ValueError("optimization level {!r} is not an alphanumeric "
                             "value".format(optimization))
    base_filename = pycache_filename.partition('.')[0]
    return os.path.join(head, base_filename + SOURCE_SUFFIXES[0])


Instruction:
How would you implement a function in Python 3 that
initializes the native request based on the method and content type.

Response:
def init_request(self):
        """ Init the native request using the okhttp3.Request.Builder """

        #: Build the request
        builder = Request.Builder()
        builder.url(self.url)

        #: Set any headers
        for k, v in self.headers.items():
            builder.addHeader(k, v)

        #: Get the body or generate from the data given
        body = self.body

        if body:
            #: Create the request body
            media_type = MediaType(
                __id__=MediaType.parse(self.content_type))
            request_body = RequestBody(
                __id__=RequestBody.create(media_type, body))
            #: Set the request method
            builder.method(self.method, request_body)
        elif self.method in ['get', 'delete', 'head']:
            #: Set the method
            getattr(builder, self.method)()
        else:
            raise ValueError("Cannot do a '{}' request "
                             "without a body".format(self.method))

        #: Save the okhttp request
        self.request = Request(__id__=builder.build())


Instruction:
Explain what the following Python 3 code does
def _default_body(self):
        if not self.data:
            return ""
        if self.content_type == 'application/json':
            import json
            return json.dumps(self.data)
        elif self.content_type == 'application/x-www-form-urlencoded':
            import urllib
            return urllib.urlencode(self.data)
        else:
            raise NotImplementedError(
                "You must manually encode the request "
                "body for '{}'".format(self.content_type)
            )

Response: Default body for the resource.


Instruction:
Can you write a function in Python 3 where it
calls regardless of success or failure

Response:
def on_finish(self):
        """ Called regardless of success or failure """
        r = self.response
        r.request_time = time.time() - self.start_time
        if self.callback:
            self.callback(r)


Instruction:
How would you code a function in Python 3 to
fetch the request using the OkHttpClient

Response:
def _fetch(self, request):
        """ Fetch using the OkHttpClient """
        client = self.client

        #: Dispatch the async call
        call = Call(__id__=client.newCall(request.request))
        call.enqueue(request.handler)

        #: Save the call reference
        request.call = call


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

Response: Create the underlying widget.


Instruction:
Here you have a function in Python 3, explain what it does
def fetch(self, url, callback=None, raise_error=True, **kwargs):
        app = BridgedApplication.instance()
        f = app.create_future()

        #: Set callback for when response is in
        if callback is not None:
            f.then(callback)

        def handle_response(response):
            """ Callback when the request is complete. """
            self.requests.remove(response.request)
            f.set_result(response)

        #: Create and dispatch the request object
        request = self.request_factory(url=url,
                                       callback=handle_response,
                                       **kwargs)

        #: Save a reference
        #: This gets removed in the handle response
        self.requests.append(request)

        #: Run the request
        self._fetch(request)

        #: Save it on the future so it can be accessed and observed
        #: from a view if needed
        f.request = request
        return f

Response: Fetch the given url and fire the callback when ready.


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 = GridLayout(self.get_context(), None, d.style)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_widget(self):
        d = self.declaration
        self.widget = Switch(self.get_context(), None,
                             d.style or '@attr/switchStyle')

Response: Create the underlying widget.


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

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

        """
        super(AndroidSwitch, self).init_widget()
        d = self.declaration
        self.set_show_text(d.show_text)
        if d.split_track:
            self.set_split_track(d.split_track)
        if d.text_off:
            self.set_text_off(d.text_off)
        if d.text_on:
            self.set_text_on(d.text_on)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def load(self):
        print("[DEBUG] Loading plugin {} from {}".format(self.name,
                                                         self.source))
        import pydoc
        path, attr = self.source.split(":")
        module = pydoc.locate(path)
        return getattr(module, attr)

Response: Load the object defined by the plugin entry point


Instruction:
Can you write a function in Python 3 where it
gets entry points to load any plugins installed.

Response:
def _default_plugins(self):
        """ Get entry points to load any plugins installed.
        The build process should create an "entry_points.json" file
        with all of the data from the installed entry points.

        """
        plugins = {}
        try:
            with open('entry_points.json') as f:
                entry_points = json.load(f)
            for ep, obj in entry_points.items():
                plugins[ep] = []
                for name, src in obj.items():
                    plugins[ep].append(Plugin(name=name, source=src))
        except Exception as e:
            print("Failed to load entry points {}".format(e))
        return plugins


Instruction:
Make a summary of the following Python 3 code
def start(self):
        #: Schedule a load view if given and remote debugging is not active
        #: the remote debugging init call this after dev connection is ready
        if self.load_view and self.dev != "remote":
            self.deferred_call(self.load_view, self)

        self.loop.start()

Response: Start the application s main event loop using either twisted or tornado.


Instruction:
Create a Python 3 function to
invoke a callable on the main event loop thread at some time in milliseconds.

Response:
def timed_call(self, ms, callback, *args, **kwargs):
        """ Invoke a callable on the main event loop thread at a
        specified time in the future.

        Parameters
        ----------
        ms : int
            The time to delay, in milliseconds, before executing the
            callable.

        callback : callable
            The callable object to execute at some point in the future.

        *args, **kwargs
            Any additional positional and keyword arguments to pass to
            the callback.

        """
        return self.loop.timed_call(ms, callback, *args, **kwargs)


Instruction:
Make a summary of the following Python 3 code
def add_done_callback(self, future, callback):
        if future is None:
            raise bridge.BridgeReferenceError(
                "Tried to add a callback to a nonexistent Future. "
                "Make sure you pass the `returns` argument to your JavaMethod")
        return self.loop.add_done_callback(future, callback)

Response: Add a callback to invoke when the current event loop is done.


Instruction:
Write a Python 3 function that can
get the root view to display. Make sure it is properly initialized.

Response:
def get_view(self):
        """ Get the root view to display. Make sure it is
        properly initialized.

        """
        view = self.view
        if not view.is_initialized:
            view.initialize()
        if not view.proxy_is_active:
            view.activate_proxy()
        return view.proxy.widget


Instruction:
Create a Python 3 function to
send an event to the native handler.

Response:
def send_event(self, name, *args, **kwargs):
        """ Send an event to the native handler. This call is queued and
        batched.

        Parameters
        ----------
        name : str
            The event name to be processed by MainActivity.processMessages.
        *args: args
            The arguments required by the event.
        **kwargs: kwargs
            Options for sending. These are:

            now: boolean
                Send the event now

        """
        n = len(self._bridge_queue)

        # Add to queue
        self._bridge_queue.append((name, args))

        if n == 0:
            # First event, send at next available time
            self._bridge_last_scheduled = time()
            self.deferred_call(self._bridge_send)
            return
        elif kwargs.get('now'):
            self._bridge_send(now=True)
            return

        # If it's been over 5 ms since we last scheduled, run now
        dt = time() - self._bridge_last_scheduled
        if dt > self._bridge_max_delay:
            self._bridge_send(now=True)


Instruction:
Can you generate the documentation for the following Python 3 function
def _bridge_send(self, now=False):
        if len(self._bridge_queue):
            if self.debug:
                print("======== Py --> Native ======")
                for event in self._bridge_queue:
                    print(event)
                print("===========================")
            self.dispatch_events(bridge.dumps(self._bridge_queue))
            self._bridge_queue = []

Response: Send the events over the bridge.


Instruction:
Here you have a function in Python 3, explain what it does
def process_events(self, data):
        events = bridge.loads(data)
        if self.debug:
            print("======== Py <-- Native ======")
            for event in events:
                print(event)
            print("===========================")
        for event in events:
            if event[0] == 'event':
                self.handle_event(event)

Response: Process events from the native implementation.


Instruction:
Explain what the following Python 3 code does
def handle_event(self, event):
        result_id, ptr, method, args = event[1]
        obj = None
        result = None
        try:
            obj, handler = bridge.get_handler(ptr, method)
            result = handler(*[v for t, v in args])
        except bridge.BridgeReferenceError as e:
            #: Log the event, don't blow up here
            msg = "Error processing event: {} - {}".format(
                  event, e).encode("utf-8")
            print(msg)
            self.show_error(msg)
        except:
            #: Log the event, blow up in user's face
            msg = "Error processing event: {} - {}".format(
                  event, traceback.format_exc()).encode("utf-8")
            print(msg)
            self.show_error(msg)
            raise
        finally:
            if result_id:
                if hasattr(obj, '__nativeclass__'):
                    sig = getattr(type(obj), method).__returns__
                else:
                    sig = type(result).__name__

                self.send_event(
                    bridge.Command.RESULT,  #: method
                    result_id,
                    bridge.msgpack_encoder(sig, result)  #: args
                )

Response: When we get an event from the bridge we handle it by invoking the handler and sending back the result.


Instruction:
Can you implement a function in Python 3 that
calls when an error occurs in an event loop callback.

Response:
def handle_error(self, callback):
        """ Called when an error occurs in an event loop callback.
        By default, sets the error view.

        """
        self.loop.log_error(callback)
        msg = "\n".join([
            "Exception in callback %r"%callback,
            traceback.format_exc()
        ])
        self.show_error(msg.encode('utf-8'))


Instruction:
How would you explain what the following Python 3 function does
def start_dev_session(self):
        try:
            from .dev import DevServerSession
            session = DevServerSession.initialize(host=self.dev)
            session.start()

            #: Save a reference
            self._dev_session = session
        except:
            self.show_error(traceback.format_exc())

Response:
Start a client that attempts to connect to the dev server
alid


Instruction:
Implement a Python 3 function for
loading widgets added via plugins using the enaml_native_widgets entry point.

Response:
def load_plugin_widgets(self):
        """ Pull widgets added via plugins using the `enaml_native_widgets`
        entry point. The entry point function must return a dictionary of
        Widget declarations to add to the core api.

        def install():
            from charts.widgets.chart_view import BarChart, LineChart
            return {
                'BarChart': BarChart,
                'LineCart': LineChart,
            }

        """
        from enamlnative.widgets import api
        for plugin in self.get_plugins(group='enaml_native_widgets'):
            get_widgets = plugin.load()
            for name, widget in iter(get_widgets()):
                #: Update the core api with these widgets
                setattr(api, name, widget)


Instruction:
Write a Python 3 script to
create a BroadcastReceiver that is invoked when the given action is received.

Response:
def for_action(cls, action, callback, single_shot=True):
        """ Create a BroadcastReceiver that is invoked when the given
        action is received.

        Parameters
        ----------
        action: String
            Action to receive
        callback: Callable
            Callback to invoke when the action is received
        single_shot: Bool
            Cleanup after one callback

        Returns
        -------
            receiver: BroadcastReceiver
                The receiver that was created. You must hold on to this
                or the GC will clean it up.

        """
        receiver = cls()
        activity = receiver.__app__.widget
        receiver.setReceiver(receiver.getId())

        def on_receive(ctx, intent):
            callback(intent)

        receiver.onReceive.connect(on_receive)
        activity.registerReceiver(receiver, IntentFilter(action))
        return receiver


Instruction:
Can you tell what is the following Python 3 function doing
def get(self, measurement_class):
        name = Measurement.name_from_class(measurement_class)
        return self._construct_measurement(name)

Response: Return the latest measurement for the given class.


Instruction:
Write a Python 3 function that can
add a vehicle data source to the instance.

Response:
def add_source(self, source):
        """Add a vehicle data source to the instance.

        The Vehicle instance will be set as the callback of the source, and the
        source will be started if it is startable. (i.e. it has a ``start()``
        method).
        """
        if source is not None:
            self.sources.add(source)
            source.callback = self._receive
            if hasattr(source, 'start'):
                source.start()


Instruction:
Explain what the following Python 3 code does
def add_sink(self, sink):
        if sink is not None:
            self.sinks.add(sink)
            if hasattr(sink, 'start'):
                sink.start()

Response: Add a vehicle data sink to the instance.


Instruction:
Create a Python 3 function to
register a callback for any new values of measurement_class received.

Response:
def register(self, measurement_class, callback):
        """Call the ``callback`` with any new values of ``measurement_class``
        received.
        """
        self.callbacks[Measurement.name_from_class(measurement_class)
                ].add(callback)


Instruction:
Can you generate the documentation for the following Python 3 function
def unregister(self, measurement_class, callback):
        self.callbacks[Measurement.name_from_class(measurement_class)
                ].remove(callback)

Response: Unregister a callback for a specific measurement class.


Instruction:
Can you tell what is the following Python 3 function doing
def _send_complex_request(self, request):
        self.device.ctrl_transfer(0x40, self.COMPLEX_CONTROL_COMMAND, 0, 0,
                self.streamer.serialize_for_stream(request))

Response: Send a request via the USB control request endpoint rather than as abulk transfer.


Instruction:
Create a Python 3 function for
opening a reference to the USB device s only OUT endpoint. This method returns None if the USB device configuration has already been set.

Response:
def out_endpoint(self):
        """Open a reference to the USB device's only OUT endpoint. This method
        assumes that the USB device configuration has already been set.
        """
        if getattr(self, '_out_endpoint', None) is None:
            config = self.device.get_active_configuration()
            interface_number = config[(0, 0)].bInterfaceNumber
            interface = usb.util.find_descriptor(config,
                    bInterfaceNumber=interface_number)

            self._out_endpoint = usb.util.find_descriptor(interface,
                    custom_match = \
                            lambda e: \
                            usb.util.endpoint_direction(e.bEndpointAddress) == \
                            usb.util.ENDPOINT_OUT)

            if not self._out_endpoint:
                raise ControllerError(
                        "Couldn't find OUT endpoint on the USB device")
        return self._out_endpoint


Instruction:
Explain what the following Python 3 code does
def wait_for_responses(self):

        self.thread.join(self.COMMAND_RESPONSE_TIMEOUT_S)
        self.running = False

        return self.responses

Response: Block the thread and wait for the response to arrive from the VI.


Instruction:
Can you generate the documentation for the following Python 3 function
def handle_responses(self):
        while self.running:
            try:
                response = self.queue.get(
                        timeout=self.COMMAND_RESPONSE_TIMEOUT_S)
                if self._response_matches_request(response):
                    self.responses.append(response)
                    if self.quit_after_first:
                        self.running = False
                self.queue.task_done()
            except Empty:
                break

Response: Block and wait for responses to this object s original request or None if no responses were received before the timeout.


Instruction:
Make a summary of the following Python 3 code
def _response_matches_request(self, response):
        # Accept success/failure command responses
        if super(DiagnosticResponseReceiver,
                self)._response_matches_request(response):
            return True

        if ('bus' in self.diagnostic_request and
                response.get('bus', None) != self.diagnostic_request['bus']):
            return False
        if (self.diagnostic_request['id'] != 0x7df and
                response.get('id', None) != self.diagnostic_request['id']):
            return False

        if (response.get('success', True) and
                response.get('pid', None) !=
                    self.diagnostic_request.get('pid', None)):
            return False

        return response.get('mode', None) == self.diagnostic_request['mode']

Response: Return true if the response is to a diagnostic request and the bus id mode match.


Instruction:
Create a Python 3 function for
sending a compound command request to the interface over the normal data channel.

Response:
def complex_request(self, request, wait_for_first_response=True):
        """Send a compound command request to the interface over the normal data
        channel.

        request - A dict storing the request to send to the VI. It will be
            serialized to the currently selected output format.
        wait_for_first_response - If true, this function will block waiting for
            a response from the VI and return it to the caller. Otherwise, it
            will send the command and return immediately and any response will
            be lost.
        """
        receiver = self._prepare_response_receiver(request,
                receiver_class=CommandResponseReceiver)
        self._send_complex_request(request)

        responses = []
        if wait_for_first_response:
            responses = receiver.wait_for_responses()
        return responses


Instruction:
Create a Python 3 function for
creating a new diagnostic message request to the VI and returns it.

Response:
def create_diagnostic_request(self, message_id, mode, bus=None, pid=None,
            frequency=None, payload=None, wait_for_ack=True,
            wait_for_first_response=False, decoded_type=None):
        """Send a new diagnostic message request to the VI

        Required:

        message_id - The message ID (arbitration ID) for the request.
        mode - the diagnostic mode (or service).

        Optional:

        bus - The address of the CAN bus controller to send the request, either
            1 or 2 for current VI hardware.
        pid - The parameter ID, or PID, for the request (e.g. for a mode 1
            request).
        frequency - The frequency in hertz to add this as a recurring diagnostic
            requests. Must be greater than 0, or None if it is a one-time
            request.
        payload - A bytearray to send as the request's optional payload. Only
            single frame diagnostic requests are supported by the VI firmware in
            the current version, so the payload has a maximum length of 6.
        wait_for_ack - If True, will wait for an ACK of the command message.
        wait_for_first_response - If True, this function will block waiting for
            a diagnostic response to be received for the request. It will return
            either after timing out or after 1 matching response is received -
            there may be more responses to functional broadcast requests that
            arrive after returning.

        Returns a tuple of
            ([list of ACK responses to create request],
                [list of diagnostic responses received])

        """

        request = self._build_diagnostic_request(message_id, mode, bus, pid,
                frequency, payload, decoded_type)

        diag_response_receiver = None
        if wait_for_first_response:
            diag_response_receiver = self._prepare_response_receiver(
                    request, DiagnosticResponseReceiver)

        request['action'] = 'add'
        ack_responses = self.complex_request(request, wait_for_ack)

        diag_responses = None
        if diag_response_receiver is not None:
            diag_responses = diag_response_receiver.wait_for_responses()

        return ack_responses, diag_responses


Instruction:
Write a Python 3 script to
control the status of a CAN message passthrough for a bus. Returns True if the command was successful.

Response:
def set_passthrough(self, bus, enabled):
        """Control the status of CAN message passthrough for a bus.

        Returns True if the command was successful.
        """
        request = {
            "command": "passthrough",
            "bus": bus,
            "enabled": enabled
        }
        return self._check_command_response_status(request)


Instruction:
How would you code a function in Python 3 to
set the payload format for messages sent to and from the VI. Returns True if the command was successful.

Response:
def set_payload_format(self, payload_format):
        """Set the payload format for messages sent to and from the VI.

        Returns True if the command was successful.
        """
        request = {
            "command": "payload_format",
            "format": payload_format
        }
        status = self._check_command_response_status(request)
        # Always change the format regardless because if it was already in the
        # right format, the command will have failed.
        self.format = payload_format
        return status


Instruction:
Create a Python 3 function to
set the Unix time if RTC is supported on the device. Returns True if the command was successful.

Response:
def rtc_configuration(self, unix_time):
        """Set the Unix time if RTC is supported on the device.

        Returns True if the command was successful.
        """
        request = {
            "command": "rtc_configuration",
            "unix_time": unix_time
        }
        status = self._check_command_response_status(request)
        return status


Instruction:
Explain what the following Python 3 code does
def modem_configuration(self, host, port):
        request = {
            "command": "modem_configuration",
            "host": host,
            "port": port
        }
        status = self._check_command_response_status(request)
        return status

Response: Send the modem_configuration command to the Cellular device to send data to. Returns True if the command was successful.


Instruction:
Write a Python 3 function for
controlling the status of CAN acceptance filter for a bus.

Response:
def set_acceptance_filter_bypass(self, bus, bypass):
        """Control the status of CAN acceptance filter for a bus.

        Returns True if the command was successful.
        """
        request = {
            "command": "af_bypass",
            "bus": bus,
            "bypass": bypass
        }
        return self._check_command_response_status(request)


Instruction:
How would you explain what the following Python 3 function does
def sd_mount_status(self):
        request = {
            "command": "sd_mount_status"
        }
        responses = self.complex_request(request)
        result = None
        if len(responses) > 0:
            result = responses[0].get('status')
        return result

Response: Request for SD Mount status if available.


Instruction:
Implement a function in Python 3 to
serialize a raw or translated write request and send it to the VI

Response:
def write(self, **kwargs):
        """Serialize a raw or translated write request and send it to the VI,
        following the OpenXC message format.
        """
        if 'id' in kwargs and 'data' in kwargs:
            result = self.write_raw(kwargs['id'], kwargs['data'],
                    bus=kwargs.get('bus', None),
                    frame_format=kwargs.get('frame_format', None))
        else:
            result = self.write_translated(kwargs['name'], kwargs['value'],
                    event=kwargs.get('event', None))
        return result


Instruction:
Explain what the following Python 3 code does
def write_translated(self, name, value, event=None):
        data = {'name': name}
        if value is not None:
            data['value'] = self._massage_write_value(value)
        if event is not None:
            data['event'] = self._massage_write_value(event);
        message = self.streamer.serialize_for_stream(data)
        bytes_written = self.write_bytes(message)
        assert bytes_written == len(message)
        return bytes_written

Response: Send a translated write request to the VI.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write_raw(self, message_id, data, bus=None, frame_format=None):
        if not isinstance(message_id, numbers.Number):
            try:
                message_id = int(message_id, 0)
            except ValueError:
                raise ValueError("ID must be numerical")
        data = {'id': message_id, 'data': data}
        if bus is not None:
            data['bus'] = bus
        if frame_format is not None:
            data['frame_format'] = frame_format
        message = self.streamer.serialize_for_stream(data)
        bytes_written = self.write_bytes(message)
        assert bytes_written == len(message)
        return bytes_written

Response: Send a raw write request to the VI.


Instruction:
Explain what the following Python 3 code does
def _massage_write_value(cls, value):
        if not isinstance(value, numbers.Number):
            if value == "true":
                value = True
            elif value == "false":
                value = False
            elif value[0] == '"' and value[-1] == '"':
                value = value[1:-1]
            else:
                try:
                    value = float(value)
                except ValueError:
                    pass
        return value

Response: Convert string values from command - line arguments into first - order boolean and float objects if applicable.


Instruction:
Can you generate the documentation for the following Python 3 function
def _validate(cls, message):
        valid = False
        if(('name' in message and 'value' in message) or
                ('id' in message and 'data' in message)):
            valid = True
        return valid

Response: Confirm the validitiy of a given dict as an OpenXC message.


Instruction:
Write a Python 3 script for
setting the value of this measurement.

Response:
def value(self, new_value):
        """Set the value of this measurement.

        Raises:
            AttributeError: if the new value isn't of the correct units.
        """
        if self.unit != units.Undefined and new_value.unit != self.unit:
            raise AttributeError("%s must be in %s" % (
                self.__class__, self.unit))
        self._value = new_value


Instruction:
Can you generate a brief explanation for the following Python 3 code
def from_dict(cls, data):

        args = []

        if 'id' in data and 'data' in data:
            measurement_class = CanMessage
            args.append("Bus %s: 0x%x" % (data.get('bus', '?'), data['id']))
            args.append(data['data'])
            # TODO grab bus
        else:
            measurement_class = cls._class_from_name(data['name'])
            if measurement_class == Measurement:
                args.append(data['name'])
            args.append(data['value'])

        return measurement_class(*args, event=data.get('event', None),
                override_unit=True)

Response: Create a new Measurement subclass instance from a dictionary.


Instruction:
Write a Python 3 function that can
return the generic name for a given measurement class.

Response:
def name_from_class(cls, measurement_class):
        """For a given measurement class, return its generic name.

        The given class is expected to have a ``name`` attribute, otherwise this
        function will raise an execption. The point of using this method instead
        of just trying to grab that attribute in the application is to cache
        measurement name to class mappings for future use.

        Returns:
            the generic OpenXC name for a measurement class.

        Raise:
            UnrecognizedMeasurementError: if the class does not have a valid
                generic name
        """
        if not getattr(cls, '_measurements_initialized', False):
            cls._measurement_map = dict((m.name, m) for m in all_measurements())
            cls._measurements_initialized = True

        try:
            name = getattr(measurement_class, 'name')
        except AttributeError:
            raise UnrecognizedMeasurementError("No 'name' attribute in %s" %
                    measurement_class)
        else:
            cls._measurement_map[name] = measurement_class
            return name


Instruction:
Write a Python 3 script for
storing the first timestamp of the trace file.

Response:
def _store_timestamp(self, timestamp):
        """If not already saved, cache the first timestamp in the active trace
        file on the instance.
        """
        if getattr(self, 'first_timestamp', None) is None:
            self.first_timestamp = timestamp
            LOG.debug("Storing %d as the first timestamp of the trace file %s",
                    self.first_timestamp, self.filename)


Instruction:
Implement a function in Python 3 to
read a line of data from the input source at a time.

Response:
def read(self):
        """Read a line of data from the input source at a time."""
        line = self.trace_file.readline()
        if line == '':
            if self.loop:
                self._reopen_file()
            else:
                self.trace_file.close()
                self.trace_file = None
                raise DataSourceError()

        message = JsonFormatter.deserialize(line)
        timestamp = message.get('timestamp', None)
        if self.realtime and timestamp is not None:
            self._store_timestamp(timestamp)
            self._wait(self.starting_time, self.first_timestamp, timestamp)
        return line + "\x00"


Instruction:
Write a Python 3 script to
attempt to open the file at filename for reading.

Response:
def _open_file(filename):
        """Attempt to open the the file at ``filename`` for reading.

        Raises:
            DataSourceError, if the file cannot be opened.
        """
        if filename is None:
            raise DataSourceError("Trace filename is not defined")

        try:
            trace_file = open(filename, "r")
        except IOError as e:
            raise DataSourceError("Unable to open trace file %s" % filename, e)
        else:
            LOG.debug("Opened trace file %s", filename)
            return trace_file


Instruction:
Implement a function in Python 3 to
block until the current timestamp is reached.

Response:
def _wait(starting_time, first_timestamp, timestamp):
        """Given that the first timestamp in the trace file is
        ``first_timestamp`` and we started playing back the file at
        ``starting_time``, block until the current ``timestamp`` should occur.
        """
        target_time = starting_time + (timestamp - first_timestamp)
        time.sleep(max(target_time - time.time(), 0))


Instruction:
Write a Python 3 script for
merging two deep dicts non - destructively generates a new tree structure

Response:
def merge(a, b):
    """Merge two deep dicts non-destructively

    Uses a stack to avoid maximum recursion depth exceptions

    >>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
    >>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
    >>> c = merge(a, b)
    >>> from pprint import pprint; pprint(c)
    {'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd': {'z': [1, 2, 3]}}
    """
    assert quacks_like_dict(a), quacks_like_dict(b)
    dst = a.copy()

    stack = [(dst, b)]
    while stack:
        current_dst, current_src = stack.pop()
        for key in current_src:
            if key not in current_dst:
                current_dst[key] = current_src[key]
            else:
                if (quacks_like_dict(current_src[key]) and
                        quacks_like_dict(current_dst[key])):
                    stack.append((current_dst[key], current_src[key]))
                elif (quacks_like_list(current_src[key]) and
                        quacks_like_list(current_dst[key])):
                    current_dst[key].extend(current_src[key])
                else:
                    current_dst[key] = current_src[key]
    return dst


Instruction:
Implement a Python 3 function for
constructing a Signal instance from an XML node exported from a Vector CANoe.dbc file.

Response:
def from_xml_node(cls, node):
        """Construct a Signal instance from an XML node exported from a Vector
        CANoe .dbc file."""
        return cls(name=node.find("Name").text,
                bit_position=int(node.find("Bitposition").text),
                bit_size=int(node.find("Bitsize").text),
                factor=float(node.find("Factor").text),
                offset=float(node.find("Offset").text),
                min_value=float(node.find("Minimum").text),
                max_value=float(node.find("Maximum").text))


Instruction:
How would you explain what the following Python 3 function does
def run(self):
        message_buffer = b""
        while self.running:
            try:
                message_buffer += self.source.read_logs()
            except DataSourceError as e:
                if self.running:
                    LOG.warn("Can't read logs from data source -- stopping: %s", e)
                break
            except NotImplementedError as e:
                LOG.info("%s doesn't support logging" % self)
                break

            while True:
                if "\x00" not in message_buffer:
                    break
                record, _, remainder = message_buffer.partition(b"\x00")
                self.record(record)
                message_buffer = remainder

Response:
Continuously read data from the source and attempt to parse a valid
        message from the buffer of bytes.


Instruction:
How would you explain what the following Python 3 function does
def compare_versions(x, y):
    def version_to_tuple(version):
        # Trim off the leading v
        version_list = version[1:].split('.', 2)
        if len(version_list) <= 3:
            [version_list.append(0) for _ in range(3 - len(version_list))]
        try:
            return tuple((int(version) for version in version_list))
        except ValueError: # not an integer, so it goes to the bottom
            return (0, 0, 0)

    x_major, x_minor, x_bugfix = version_to_tuple(x)
    y_major, y_minor, y_bugfix = version_to_tuple(y)
    return (cmp(x_major, y_major) or cmp(x_minor, y_minor)
            or cmp(x_bugfix, y_bugfix))

Response: This function will compare two strings of X. Y. Z and returns a boolean indicating if the two strings are the same.


Instruction:
Make a summary of the following Python 3 code
def compute(self, t, yerr=1.123e-12, check_sorted=True,
                A=None, U=None, V=None):
        """
        Compute the extended form of the covariance matrix and factorize

        Args:
            x (array[n]): The independent coordinates of the data points.
                This array must be _sorted_ in ascending order.
            yerr (Optional[float or array[n]]): The measurement uncertainties
                for the data points at coordinates ``x``. These values will be
                added in quadrature to the diagonal of the covariance matrix.
                (default: ``1.123e-12``)
            check_sorted (bool): If ``True``, ``x`` will be checked to make
                sure that it is properly sorted. If ``False``, the coordinates
                will be assumed to be in the correct order.

        Raises:
            ValueError: For un-sorted data or mismatched dimensions.
            solver.LinAlgError: For non-positive definite matrices.

        """
        t = np.atleast_1d(t)
        if check_sorted and np.any(np.diff(t) < 0.0):
            raise ValueError("the input coordinates must be sorted")
        if check_sorted and len(t.shape) > 1:
            raise ValueError("dimension mismatch")
        self._t = t
        self._yerr = np.empty_like(self._t)
        self._yerr[:] = yerr
        (alpha_real, beta_real, alpha_complex_real, alpha_complex_imag,
         beta_complex_real, beta_complex_imag) = self.kernel.coefficients
        self._A = np.empty(0) if A is None else A
        self._U = np.empty((0, 0)) if U is None else U
        self._V = np.empty((0, 0)) if V is None else V
        self.solver.compute(
            self.kernel.jitter,
            alpha_real, beta_real,
            alpha_complex_real, alpha_complex_imag,
            beta_complex_real, beta_complex_imag,
            self._A, self._U, self._V,
            t, self._yerr**2
        )
        self.dirty = False

Response: Compute the extended form of the covariance matrix and factorize the uncertainties of the data points at the specified coordinates.


Instruction:
How would you code a function in Python 3 to
compute the marginalized likelihood of the GP model.

Response:
def log_likelihood(self, y, _const=math.log(2.0*math.pi), quiet=False):
        """
        Compute the marginalized likelihood of the GP model

        The factorized matrix from the previous call to :func:`GP.compute` is
        used so ``compute`` must be called first.

        Args:
            y (array[n]): The observations at coordinates ``x`` from
                :func:`GP.compute`.
            quiet (bool): If true, return ``-numpy.inf`` for non-positive
                definite matrices instead of throwing an error.

        Returns:
            float: The marginalized likelihood of the GP model.

        Raises:
            ValueError: For mismatched dimensions.
            solver.LinAlgError: For non-positive definite matrices.

        """
        y = self._process_input(y)
        resid = y - self.mean.get_value(self._t)
        try:
            self._recompute()
        except solver.LinAlgError:
            if quiet:
                return -np.inf
            raise
        if len(y.shape) > 1:
            raise ValueError("dimension mismatch")
        logdet = self.solver.log_determinant()
        if not np.isfinite(logdet):
            return -np.inf
        loglike = -0.5*(self.solver.dot_solve(resid)+logdet+len(y)*_const)
        if not np.isfinite(loglike):
            return -np.inf
        return loglike


Instruction:
Write a Python 3 script to
compute the gradient of the marginalized likelihood of the log likelihood.

Response:
def grad_log_likelihood(self, y, quiet=False):
        """
        Compute the gradient of the marginalized likelihood

        The factorized matrix from the previous call to :func:`GP.compute` is
        used so ``compute`` must be called first. The gradient is taken with
        respect to the parameters returned by :func:`GP.get_parameter_vector`.
        This function requires the `autograd
        <https://github.com/HIPS/autograd>`_ package.

        Args:
            y (array[n]): The observations at coordinates ``x`` from
                :func:`GP.compute`.
            quiet (bool): If true, return ``-numpy.inf`` and a gradient vector
                of zeros for non-positive definite matrices instead of
                throwing an error.

        Returns:
            The gradient of marginalized likelihood with respect to the
            parameter vector.

        Raises:
            ValueError: For mismatched dimensions.
            solver.LinAlgError: For non-positive definite matrices.

        """
        if not solver.has_autodiff():
            raise RuntimeError("celerite must be compiled with autodiff "
                               "support to use the gradient methods")

        if not self.kernel.vector_size:
            return self.log_likelihood(y, quiet=quiet), np.empty(0)

        y = self._process_input(y)
        if len(y.shape) > 1:
            raise ValueError("dimension mismatch")
        resid = y - self.mean.get_value(self._t)

        (alpha_real, beta_real, alpha_complex_real, alpha_complex_imag,
         beta_complex_real, beta_complex_imag) = self.kernel.coefficients
        try:
            val, grad = self.solver.grad_log_likelihood(
                self.kernel.jitter,
                alpha_real, beta_real,
                alpha_complex_real, alpha_complex_imag,
                beta_complex_real, beta_complex_imag,
                self._A, self._U, self._V,
                self._t, resid, self._yerr**2
            )
        except solver.LinAlgError:
            if quiet:
                return -np.inf, np.zeros(self.vector_size)
            raise

        if self.kernel._has_coeffs:
            coeffs_jac = self.kernel.get_coeffs_jacobian()
            full_grad = np.dot(coeffs_jac, grad[1:])
        else:
            full_grad = np.zeros(self.kernel.vector_size)
        if self.kernel._has_jitter:
            jitter_jac = self.kernel.get_jitter_jacobian()
            full_grad += jitter_jac * grad[0]

        if self.mean.vector_size:
            self._recompute()
            alpha = self.solver.solve(resid)
            g = self.mean.get_gradient(self._t)
            full_grad = np.append(full_grad, np.dot(g, alpha))

        return val, full_grad


Instruction:
Given the following Python 3 function, write the documentation
def apply_inverse(self, y):
        self._recompute()
        return self.solver.solve(self._process_input(y))

Response: Applies the inverse of the covariance matrix to a vector or matrix y


Instruction:
Implement a function in Python 3 to
dot product of the covariance matrix into a vector or matrix.

Response:
def dot(self, y, t=None, A=None, U=None, V=None, kernel=None,
            check_sorted=True):
        """
        Dot the covariance matrix into a vector or matrix

        Compute ``K.y`` where ``K`` is the covariance matrix of the GP without
        the white noise or ``yerr`` values on the diagonal.

        Args:
            y (array[n] or array[n, nrhs]): The vector or matrix ``y``
                described above.
            kernel (Optional[terms.Term]): A different kernel can optionally
                be provided to compute the matrix ``K`` from a different
                kernel than the ``kernel`` property on this object.

        Returns:
            array[n] or array[n, nrhs]: The dot product ``K.y`` as described
            above. This will have the same shape as ``y``.

        Raises:
            ValueError: For mismatched dimensions.

        """
        if kernel is None:
            kernel = self.kernel

        if t is not None:
            t = np.atleast_1d(t)
            if check_sorted and np.any(np.diff(t) < 0.0):
                raise ValueError("the input coordinates must be sorted")
            if check_sorted and len(t.shape) > 1:
                raise ValueError("dimension mismatch")

            A = np.empty(0) if A is None else A
            U = np.empty((0, 0)) if U is None else U
            V = np.empty((0, 0)) if V is None else V
        else:
            if not self.computed:
                raise RuntimeError("you must call 'compute' first")
            t = self._t
            A = self._A
            U = self._U
            V = self._V

        (alpha_real, beta_real, alpha_complex_real, alpha_complex_imag,
         beta_complex_real, beta_complex_imag) = kernel.coefficients

        return self.solver.dot(
            kernel.jitter,
            alpha_real, beta_real,
            alpha_complex_real, alpha_complex_imag,
            beta_complex_real, beta_complex_imag,
            A, U, V, t, np.ascontiguousarray(y, dtype=float)
        )


Instruction:
Explain what the following Python 3 code does
def predict(self, y, t=None, return_cov=True, return_var=False):
        y = self._process_input(y)
        if len(y.shape) > 1:
            raise ValueError("dimension mismatch")

        if t is None:
            xs = self._t
        else:
            xs = np.ascontiguousarray(t, dtype=float)
            if len(xs.shape) > 1:
                raise ValueError("dimension mismatch")

        # Make sure that the model is computed
        self._recompute()

        # Compute the predictive mean.
        resid = y - self.mean.get_value(self._t)

        if t is None:
            alpha = self.solver.solve(resid).flatten()
            alpha = resid - (self._yerr**2 + self.kernel.jitter) * alpha
        elif not len(self._A):
            alpha = self.solver.predict(resid, xs)
        else:
            Kxs = self.get_matrix(xs, self._t)
            alpha = np.dot(Kxs, alpha)

        mu = self.mean.get_value(xs) + alpha
        if not (return_var or return_cov):
            return mu

        # Predictive variance.
        Kxs = self.get_matrix(xs, self._t)
        KxsT = np.ascontiguousarray(Kxs.T, dtype=np.float64)
        if return_var:
            var = -np.sum(KxsT*self.apply_inverse(KxsT), axis=0)
            var += self.kernel.get_value(0.0)
            return mu, var

        # Predictive covariance
        cov = self.kernel.get_value(xs[:, None] - xs[None, :])
        cov -= np.dot(Kxs, self.apply_inverse(KxsT))
        return mu, cov

Response: Compute the conditional predictive distribution of the model at the specified observations at the specified coordinates.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_matrix(self, x1=None, x2=None, include_diagonal=None,
                   include_general=None):
        """
        Get the covariance matrix at given independent coordinates

        Args:
            x1 (Optional[array[n1]]): The first set of independent coordinates.
                If this is omitted, ``x1`` will be assumed to be equal to ``x``
                from a previous call to :func:`GP.compute`.
            x2 (Optional[array[n2]]): The second set of independent
                coordinates. If this is omitted, ``x2`` will be assumed to be
                ``x1``.
            include_diagonal (Optional[bool]): Should the white noise and
                ``yerr`` terms be included on the diagonal?
                (default: ``False``)

        """
        if x1 is None and x2 is None:
            if self._t is None or not self.computed:
                raise RuntimeError("you must call 'compute' first")
            K = self.kernel.get_value(self._t[:, None] - self._t[None, :])
            if include_diagonal is None or include_diagonal:
                K[np.diag_indices_from(K)] += (
                    self._yerr**2 + self.kernel.jitter
                )
            if (include_general is None or include_general) and len(self._A):
                K[np.diag_indices_from(K)] += self._A
                K += np.tril(np.dot(self._U.T, self._V), -1)
                K += np.triu(np.dot(self._V.T, self._U), 1)
            return K

        incl = False
        x1 = np.ascontiguousarray(x1, dtype=float)
        if x2 is None:
            x2 = x1
            incl = include_diagonal is not None and include_diagonal
        K = self.kernel.get_value(x1[:, None] - x2[None, :])
        if incl:
            K[np.diag_indices_from(K)] += self.kernel.jitter
        return K

Response: Get the covariance matrix at given independent coordinates.


Instruction:
Given the following Python 3 function, write the documentation
def sample(self, size=None):
        self._recompute()
        if size is None:
            n = np.random.randn(len(self._t))
        else:
            n = np.random.randn(len(self._t), size)
        n = self.solver.dot_L(n)
        if size is None:
            return self.mean.get_value(self._t) + n[:, 0]
        return self.mean.get_value(self._t)[None, :] + n.T

Response:
Returns a random sample from the prior distribution over datasets
           .


Instruction:
How would you explain what the following Python 3 function does
def sample_conditional(self, y, t=None, size=None):
        mu, cov = self.predict(y, t, return_cov=True)
        return np.random.multivariate_normal(mu, cov, size=size)

Response: Sample from the conditional distribution.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_value(self, tau):
        tau = np.asarray(tau)
        (alpha_real, beta_real, alpha_complex_real, alpha_complex_imag,
         beta_complex_real, beta_complex_imag) = self.coefficients
        k = get_kernel_value(
            alpha_real, beta_real,
            alpha_complex_real, alpha_complex_imag,
            beta_complex_real, beta_complex_imag,
            tau.flatten(),
        )
        return np.asarray(k).reshape(tau.shape)

Response: Compute the value of the term for an array of lags


Instruction:
Write a Python 3 function that can
compute the PSD of the term for an array of angular frequencies .

Response:
def get_psd(self, omega):
        """
        Compute the PSD of the term for an array of angular frequencies

        Args:
            omega (array[...]): An array of frequencies where the PSD should
                be evaluated.

        Returns:
            The value of the PSD for each ``omega``. This will have the same
            shape as ``omega``.

        """
        w = np.asarray(omega)
        (alpha_real, beta_real, alpha_complex_real, alpha_complex_imag,
         beta_complex_real, beta_complex_imag) = self.coefficients
        p = get_psd_value(
            alpha_real, beta_real,
            alpha_complex_real, alpha_complex_imag,
            beta_complex_real, beta_complex_imag,
            w.flatten(),
        )
        return p.reshape(w.shape)


Instruction:
Create a Python 3 function for
getting the arrays alpha_complex_real alpha_complex_imag beta_complex_real and beta_complex_imag.

Response:
def get_complex_coefficients(self, params):
        """
        Get the arrays ``alpha_complex_*`` and ``beta_complex_*``

        This method should be overloaded by subclasses to return the arrays
        ``alpha_complex_real``, ``alpha_complex_imag``, ``beta_complex_real``,
        and ``beta_complex_imag`` given the current parameter settings. By
        default, this term is empty.

        Returns:
            (array[j_complex], array[j_complex], array[j_complex],
            array[j_complex]): ``alpha_complex_real``, ``alpha_complex_imag``,
            ``beta_complex_real``, and ``beta_complex_imag`` as described
            above. ``alpha_complex_imag`` can be omitted and it will be
            assumed to be zero.

        """
        return np.empty(0), np.empty(0), np.empty(0), np.empty(0)


Instruction:
Can you implement a function in Python 3 that
returns the coefficients of the current term as a tuple of length 6.

Response:
def coefficients(self):
        """
        All of the coefficient arrays

        This property is the concatenation of the results from
        :func:`terms.Term.get_real_coefficients` and
        :func:`terms.Term.get_complex_coefficients` but it will always return
        a tuple of length 6, even if ``alpha_complex_imag`` was omitted from
        ``get_complex_coefficients``.

        Returns:
            (array[j_real], array[j_real], array[j_complex], array[j_complex],
            array[j_complex], array[j_complex]): ``alpha_real``, ``beta_real``,
            ``alpha_complex_real``, ``alpha_complex_imag``,
            ``beta_complex_real``, and ``beta_complex_imag`` as described
            above.

        Raises:
            ValueError: For invalid dimensions for the coefficients.

        """
        vector = self.get_parameter_vector(include_frozen=True)
        pars = self.get_all_coefficients(vector)
        if len(pars) != 6:
            raise ValueError("there must be 6 coefficient blocks")
        if any(len(p.shape) != 1 for p in pars):
            raise ValueError("coefficient blocks must be 1D")
        if len(pars[0]) != len(pars[1]):
            raise ValueError("coefficient blocks must have the same shape")
        if any(len(pars[2]) != len(p) for p in pars[3:]):
            raise ValueError("coefficient blocks must have the same shape")
        return pars


Instruction:
Write a Python 3 script for
removing *key* from maps [ 0 ] and return its value. Raise KeyError.

Response:
def pop(self, key, *args):
        'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
        try:
            return self.maps[0].pop(key, *args)
        except KeyError:
            raise KeyError('Key not found in the first mapping: {!r}'.format(key))


Instruction:
How would you explain what the following Python 3 function does
def _create_dim_scales(self):
        dim_order = self._dim_order.maps[0]
        for dim in sorted(dim_order, key=lambda d: dim_order[d]):
            if dim not in self._h5group:
                size = self._current_dim_sizes[dim]
                kwargs = {}
                if self._dim_sizes[dim] is None:
                    kwargs["maxshape"] = (None,)
                self._h5group.create_dataset(
                    name=dim, shape=(size,), dtype='S1', **kwargs)

            h5ds = self._h5group[dim]
            h5ds.attrs['_Netcdf4Dimid'] = dim_order[dim]

            if len(h5ds.shape) > 1:
                dims = self._variables[dim].dimensions
                coord_ids = np.array([dim_order[d] for d in dims], 'int32')
                h5ds.attrs['_Netcdf4Coordinates'] = coord_ids

            scale_name = dim if dim in self.variables else NOT_A_VARIABLE
            h5ds.dims.create_scale(h5ds, scale_name)

        for subgroup in self.groups.values():
            subgroup._create_dim_scales()

Response: Create all necessary HDF5 dimension scales.


Instruction:
Write a Python 3 script for
attaching dimension scales to all variables and groups.

Response:
def _attach_dim_scales(self):
        """Attach dimension scales to all variables."""
        for name, var in self.variables.items():
            if name not in self.dimensions:
                for n, dim in enumerate(var.dimensions):
                    var._h5ds.dims[n].attach_scale(self._all_h5groups[dim])

        for subgroup in self.groups.values():
            subgroup._attach_dim_scales()


Instruction:
Can you tell what is the following Python 3 function doing
def _detach_dim_scale(self, name):
        for var in self.variables.values():
            for n, dim in enumerate(var.dimensions):
                if dim == name:
                    var._h5ds.dims[n].detach_scale(self._all_h5groups[dim])

        for subgroup in self.groups.values():
            if dim not in subgroup._h5group:
                subgroup._detach_dim_scale(name)

Response: Detach the dimension scale corresponding to a dimension name.


Instruction:
Here you have a function in Python 3, explain what it does
def multiplyQuats(q1, q2):
    return np.array([
            q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3],
            q1[2]*q2[3] - q2[2]*q1[3] + q1[0]*q2[1] + q2[0]*q1[1],
            q1[3]*q2[1] - q2[3]*q1[1] + q1[0]*q2[2] + q2[0]*q1[2],
            q1[1]*q2[2] - q2[1]*q1[2] + q1[0]*q2[3] + q2[0]*q1[3]])

Response: multiplies q1 and q2 by q1 and q2


Instruction:
Write a Python 3 function for
returning QBar such that Q = 1

Response:
def quatInv(q):
    """Returns QBar such that Q*QBar = 1"""
    qConj = -q
    qConj[0] = -qConj[0]
    normSqr = multiplyQuats(q, qConj)[0]
    return qConj/normSqr