Instruction:
How would you explain what the following Python 3 function does
def execution_history_focus(self, model, prop_name, info):
        if state_machine_execution_engine.status.execution_mode in \
                [StateMachineExecutionStatus.STARTED, StateMachineExecutionStatus.STOPPED,
                 StateMachineExecutionStatus.FINISHED]:
            if self.parent is not None and hasattr(self.parent, "focus_notebook_page_of_controller"):
                # request focus -> which has not have to be satisfied
                self.parent.focus_notebook_page_of_controller(self)

        if state_machine_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STARTED:
            if not self.model.selected_state_machine_id == self.model.state_machine_manager.active_state_machine_id:
                pass
            else:
                self.update()

Response: Arranges to put execution - history widget page to become top page in notebook when execution starts and stops and resets modification_history_was_focused to False each time this notification are observed.


Instruction:
How would you explain what the following Python 3 function does
def clean_history(self, widget, event=None):
        self.history_tree_store.clear()
        selected_sm_m = self.model.get_selected_state_machine_model()
        if selected_sm_m:
            # the core may continue running without the GUI and for this it needs its execution histories
            if state_machine_execution_engine.finished_or_stopped():
                selected_sm_m.state_machine.destroy_execution_histories()
                self.update()

Response: Triggered when the Clean History button is clicked.


Instruction:
Write a Python 3 script to
rebuild the tree view of the history item tree store

Response:
def update(self):
        """
        rebuild the tree view of the history item tree store
        :return:
        """
        # with self._update_lock:
        self._update_lock.acquire()
        self._store_expansion_state()
        self.history_tree_store.clear()
        selected_sm_m = self.model.get_selected_state_machine_model()
        if not selected_sm_m:
            return

        for execution_number, execution_history in enumerate(selected_sm_m.state_machine.execution_histories):
            if len(execution_history) > 0:
                first_history_item = execution_history[0]
                # the next lines filter out the StateMachineStartItem, which is not intended to
                # be displayed, but merely as convenient entry point in the saved log file
                if isinstance(first_history_item, StateMachineStartItem):
                    if len(execution_history) > 1:
                        first_history_item = execution_history[1]
                        tree_item = self.history_tree_store.insert_after(
                            None,
                            None,
                            (first_history_item.state_reference.name + " - Run " + str(execution_number + 1),
                             first_history_item, self.TOOL_TIP_TEXT))
                        self.insert_execution_history(tree_item, execution_history[1:], is_root=True)
                    else:
                        pass  # there was only the Start item in the history
                else:
                    tree_item = self.history_tree_store.insert_after(
                        None,
                        None,
                        (first_history_item.state_reference.name + " - Run " + str(execution_number + 1),
                         first_history_item, self.TOOL_TIP_TEXT))
                    self.insert_execution_history(tree_item, execution_history, is_root=True)

        self._restore_expansion_state()
        self._update_lock.release()


Instruction:
Can you implement a function in Python 3 that
inserts a single history item into the tree store.

Response:
def insert_history_item(self, parent, history_item, description, dummy=False):
        """Enters a single history item into the tree store

        :param Gtk.TreeItem parent: Parent tree item
        :param HistoryItem history_item: History item to be inserted
        :param str description: A description to be added to the entry
        :param None dummy: Whether this is just a dummy entry (wrapper for concurrency items)
        :return: Inserted tree item
        :rtype: Gtk.TreeItem
        """
        if not history_item.state_reference:
            logger.error("This must never happen! Current history_item is {}".format(history_item))
            return None
        content = None

        if global_gui_config.get_config_value("SHOW_PATH_NAMES_IN_EXECUTION_HISTORY", False):
            content = (history_item.state_reference.name + " - " +
                           history_item.state_reference.get_path() + " - " +
                           description, None if dummy else history_item,
                           None if dummy else self.TOOL_TIP_TEXT)
        else:
            content = (history_item.state_reference.name + " - " +
                           description, None if dummy else history_item,
                           None if dummy else self.TOOL_TIP_TEXT)

        tree_item = self.history_tree_store.insert_before(
            parent, None, content)
        return tree_item


Instruction:
Can you generate the documentation for the following Python 3 function
def insert_execution_history(self, parent, execution_history, is_root=False):
        current_parent = parent
        execution_history_iterator = iter(execution_history)
        for history_item in execution_history_iterator:
            if isinstance(history_item, ConcurrencyItem):
                self.insert_concurrent_execution_histories(current_parent, history_item.execution_histories)

            elif isinstance(history_item, CallItem):
                tree_item = self.insert_history_item(current_parent, history_item, "Enter" if is_root else "Call")
                if not tree_item:
                    return
                if history_item.call_type is CallType.EXECUTE:
                    # this is necessary that already the CallType.EXECUTE item opens a new hierarchy in the
                    # tree view and not the CallType.CONTAINER item
                    next_history_item = history_item.next
                    if next_history_item and next_history_item.call_type is CallType.CONTAINER:
                        current_parent = tree_item
                        self.insert_history_item(current_parent, next_history_item, "Enter")
                        try:
                            next(execution_history_iterator)  # skips the next history item in the iterator
                        except StopIteration as e:
                            # the execution engine does not have another item
                            return

            else:  # history_item is ReturnItem
                if current_parent is None:
                    # The reasons here can be: missing history items, items in the wrong order etc.
                    # Does not happen when using RAFCON without plugins
                    logger.error("Invalid execution history: current_parent is None")
                    return
                if history_item.call_type is CallType.EXECUTE:
                    self.insert_history_item(current_parent, history_item, "Return")
                else:  # CONTAINER
                    self.insert_history_item(current_parent, history_item, "Exit")
                    current_parent = self.history_tree_store.iter_parent(current_parent)

            is_root = False

Response: This method inserts a list of execution history items into a tree store.


Instruction:
Can you write a function in Python 3 where it
adds the child execution histories of a concurrency state.

Response:
def insert_concurrent_execution_histories(self, parent, concurrent_execution_histories):
        """Adds the child execution histories of a concurrency state.

        :param Gtk.TreeItem parent: the parent to add the next history item to
        :param list[ExecutionHistory] concurrent_execution_histories: a list of all child execution histories
        :return:
        """
        for execution_history in concurrent_execution_histories:
            if len(execution_history) >= 1:
                first_history_item = execution_history[0]
                # this is just a dummy item to have an extra parent for each branch
                # gives better overview in case that one of the child state is a simple execution state
                tree_item = self.insert_history_item(parent, first_history_item, "Concurrency Branch", dummy=True)
                self.insert_execution_history(tree_item, execution_history)


Instruction:
Can you generate the documentation for the following Python 3 function
def on_drag_data_get(self, widget, context, data, info, time):
        library_state = self._get_selected_library_state()
        import rafcon.gui.helpers.state_machine as gui_helper_state_machine
        gui_helper_state_machine.add_state_by_drag_and_drop(library_state, data)

Response: dragged state is inserted and its state_id sent to the receiver


Instruction:
How would you code a function in Python 3 to
select respective state machine of selected library in state machine manager if already open

Response:
def select_open_state_machine_of_selected_library_element(self):
        """Select respective state machine of selected library in state machine manager if already open """
        (model, row_path) = self.view.get_selection().get_selected()
        if row_path:
            physical_library_path = model[row_path][self.ITEM_STORAGE_ID]
            smm = gui_singletons.state_machine_manager_model.state_machine_manager
            sm = smm.get_open_state_machine_of_file_system_path(physical_library_path)
            if sm:
                gui_singletons.state_machine_manager_model.selected_state_machine_id = sm.state_machine_id


Instruction:
Create a Python 3 function for
removing libraries from hard drive after second confirmation

Response:
def menu_item_remove_libraries_or_root_clicked(self, menu_item):
        """Removes library from hard drive after request second confirmation"""

        menu_item_text = self.get_menu_item_text(menu_item)

        logger.info("Delete item '{0}' pressed.".format(menu_item_text))
        model, path = self.view.get_selection().get_selected()
        if path:
            # Second confirmation to delete library
            tree_m_row = self.tree_store[path]
            library_os_path, library_path, library_name, item_key = self.extract_library_properties_from_selected_row()
            # assert isinstance(tree_m_row[self.ITEM_STORAGE_ID], str)
            library_file_system_path = library_os_path

            if "root" in menu_item_text:
                button_texts = [menu_item_text + "from tree and config", "Cancel"]
                partial_message = "This will remove the library root from your configuration (config.yaml)."
            else:
                button_texts = [menu_item_text, "Cancel"]
                partial_message = "This folder will be removed from hard drive! You really wanna do that?"

            message_string = "You choose to {2} with " \
                             "\n\nlibrary tree path:   {0}" \
                             "\n\nphysical path:        {1}.\n\n\n"\
                             "{3}" \
                             "".format(os.path.join(self.convert_if_human_readable(tree_m_row[self.LIB_PATH_STORAGE_ID]),
                                                    item_key),
                                       library_file_system_path,
                                       menu_item_text.lower(),
                                       partial_message)

            width = 8*len("physical path:        " + library_file_system_path)
            dialog = RAFCONButtonDialog(message_string, button_texts, message_type=Gtk.MessageType.QUESTION,
                                        parent=self.get_root_window(), width=min(width, 1400))
            response_id = dialog.run()
            dialog.destroy()
            if response_id == 1:
                if "root" in menu_item_text:
                    logger.info("Remove library root key '{0}' from config.".format(item_key))
                    from rafcon.gui.singleton import global_config
                    library_paths = global_config.get_config_value('LIBRARY_PATHS')
                    del library_paths[tree_m_row[self.LIB_KEY_STORAGE_ID]]
                    global_config.save_configuration()
                    self.model.library_manager.refresh_libraries()
                elif "libraries" in menu_item_text:
                    logger.debug("Remove of all libraries in {} is triggered.".format(library_os_path))
                    import shutil
                    shutil.rmtree(library_os_path)
                    self.model.library_manager.refresh_libraries()
                else:

                    logger.debug("Remove of Library {} is triggered.".format(library_os_path))
                    self.model.library_manager.remove_library_from_file_system(library_path,
                                                                               library_name)
            elif response_id in [2, -4]:
                pass
            else:
                logger.warning("Response id: {} is not considered".format(response_id))

            return True
        return False


Instruction:
Implement a function in Python 3 to
extract properties library_os_path library_path library_name and tree_item_key from selected row

Response:
def extract_library_properties_from_selected_row(self):
        """ Extracts properties library_os_path, library_path, library_name and tree_item_key from tree store row """
        (model, row) = self.view.get_selection().get_selected()
        tree_item_key = model[row][self.ID_STORAGE_ID]
        library_item = model[row][self.ITEM_STORAGE_ID]
        library_path = model[row][self.LIB_PATH_STORAGE_ID]
        if isinstance(library_item, dict):  # sub-tree
            os_path = model[row][self.OS_PATH_STORAGE_ID]
            return os_path, None, None, tree_item_key  # relevant elements of sub-tree
        assert isinstance(library_item, string_types)
        library_os_path = library_item

        library_name = library_os_path.split(os.path.sep)[-1]

        return library_os_path, library_path, library_name, tree_item_key


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_selected_library_state(self):
        library_os_path, library_path, library_name, item_key = self.extract_library_properties_from_selected_row()
        if library_path is None:
            return None

        logger.debug("Link library state '{0}' (with library tree path: {2} and file system path: {1}) into state "
                     "machine.".format(str(item_key), library_os_path,
                                       self.convert_if_human_readable(str(library_path)) + "/" + str(item_key)))
        library_name = library_os_path.split(os.path.sep)[-1]
        return LibraryState(library_path, library_name, "0.1", format_folder_name_human_readable(library_name))

Response: Returns the LibraryState which was selected in the LibraryTree


Instruction:
Here you have a function in Python 3, explain what it does
def start(self, execution_history, backward_execution=False, generate_run_id=True):
        self.execution_history = execution_history
        if generate_run_id:
            self._run_id = run_id_generator()
        self.backward_execution = copy.copy(backward_execution)
        self.thread = threading.Thread(target=self.run)
        self.thread.start()

Response: Starts the execution of the state in a new thread.


Instruction:
Make a summary of the following Python 3 code
def join(self):
        if self.thread:
            self.thread.join()
            self.thread = None
        else:
            logger.debug("Cannot join {0}, as the state hasn't been started, yet or is already finished!".format(self))

Response: Waits until the state finished execution.


Instruction:
How would you explain what the following Python 3 function does
def setup_run(self):
        self.state_execution_status = StateExecutionStatus.ACTIVE
        self.preempted = False
        if not isinstance(self.input_data, dict):
            raise TypeError("input_data must be of type dict")
        if not isinstance(self.output_data, dict):
            raise TypeError("output_data must be of type dict")
        self.check_input_data_type()

Response: Sets up the state execution status and preempted state


Instruction:
Can you implement a function in Python 3 that
preempts the state of the current object.

Response:
def recursively_preempt_states(self):
        """Preempt the state
        """
        self.preempted = True
        self.paused = False
        self.started = False


Instruction:
How would you explain what the following Python 3 function does
def get_default_input_values_for_state(self, state):
        from rafcon.core.states.library_state import LibraryState
        result_dict = {}
        for input_port_key, value in state.input_data_ports.items():
            if isinstance(state, LibraryState):
                if state.use_runtime_value_input_data_ports[input_port_key]:
                    default = state.input_data_port_runtime_values[input_port_key]
                else:
                    default = value.default_value
            else:
                default = value.default_value
            # if the user sets the default value to a string starting with $, try to retrieve the value
            # from the global variable manager
            if isinstance(default, string_types) and len(default) > 0 and default[0] == '$':
                from rafcon.core.singleton import global_variable_manager as gvm
                var_name = default[1:]
                if not gvm.variable_exist(var_name):
                    logger.error("The global variable '{0}' does not exist".format(var_name))
                    global_value = None
                else:
                    global_value = gvm.get_variable(var_name)
                result_dict[value.name] = global_value
            else:
                # set input to its default value
                result_dict[value.name] = copy.copy(default)
        return result_dict

Response: Returns the default input values for a state


Instruction:
Write a Python 3 function for
creating a dictionary of output data for a state

Response:
def create_output_dictionary_for_state(state):
        """Return empty output dictionary for a state

        :param state: the state of which the output data is determined
        :return: the output data of the target state
        """
        from rafcon.core.states.library_state import LibraryState
        result_dict = {}
        for key, data_port in state.output_data_ports.items():
            if isinstance(state, LibraryState) and state.use_runtime_value_output_data_ports[key]:
                result_dict[data_port.name] = copy.copy(state.output_data_port_runtime_values[key])
            else:
                result_dict[data_port.name] = copy.copy(data_port.default_value)
        return result_dict


Instruction:
Write a Python 3 function for
adding a new input data port to the state.

Response:
def add_input_data_port(self, name, data_type=None, default_value=None, data_port_id=None):
        """Add a new input data port to the state.

        :param str name: the name of the new input data port
        :param data_type: the type of the new output data port considered of class :class:`type` or
                          :class:`str` which has to be convertible to :class:`type`
        :param default_value: the default value of the data port
        :param int data_port_id: the data_port_id of the new data port
        :return: data_port_id of new input data port
        :rtype: int
        :raises exceptions.ValueError: if name of the input port is not unique
        """
        if data_port_id is None:
            # All data port ids have to passed to the id generation as the data port id has to be unique inside a state
            data_port_id = generate_data_port_id(self.get_data_port_ids())
        self._input_data_ports[data_port_id] = InputDataPort(name, data_type, default_value, data_port_id, self)

        # Check for name uniqueness
        valid, message = self._check_data_port_name(self._input_data_ports[data_port_id])
        if not valid:
            self._input_data_ports[data_port_id].parent = None
            del self._input_data_ports[data_port_id]
            raise ValueError(message)

        return data_port_id


Instruction:
Write a Python 3 function that can
remove an input data port from the state.

Response:
def remove_input_data_port(self, data_port_id, force=False, destroy=True):
        """Remove an input data port from the state

        :param int data_port_id: the id or the output data port to remove
        :param bool force: if the removal should be forced without checking constraints
        :raises exceptions.AttributeError: if the specified input data port does not exist
        """
        if data_port_id in self._input_data_ports:
            if destroy:
                self.remove_data_flows_with_data_port_id(data_port_id)
            self._input_data_ports[data_port_id].parent = None
            return self._input_data_ports.pop(data_port_id)
        else:
            raise AttributeError("input data port with name %s does not exit", data_port_id)


Instruction:
Create a Python 3 function to
remove all data flows whose from_key or to_key equals the passed data_port_id.

Response:
def remove_data_flows_with_data_port_id(self, data_port_id):
        """Remove all data flows whose from_key or to_key equals the passed data_port_id

        :param data_port_id: the id of a data_port of which all data_flows should be removed, the id can be a input or
                            output data port id

        """
        if not self.is_root_state:
            # delete all data flows in parent related to data_port_id and self.state_id
            data_flow_ids_to_remove = []
            for data_flow_id, data_flow in self.parent.data_flows.items():
                if data_flow.from_state == self.state_id and data_flow.from_key == data_port_id or \
                        data_flow.to_state == self.state_id and data_flow.to_key == data_port_id:
                    data_flow_ids_to_remove.append(data_flow_id)

            for data_flow_id in data_flow_ids_to_remove:
                self.parent.remove_data_flow(data_flow_id)


Instruction:
Create a Python 3 function for
adding a new output data port to the state

Response:
def add_output_data_port(self, name, data_type, default_value=None, data_port_id=None):
        """Add a new output data port to the state

        :param str name: the name of the new output data port
        :param data_type: the type of the new output data port considered of class :class:`type` or
                          :class:`str` which has to be convertible to :class:`type`
        :param default_value: the default value of the data port
        :param int data_port_id: the data_port_id of the new data port
        :return: data_port_id of new output data port
        :rtype: int
        :raises exceptions.ValueError: if name of the output port is not unique
        """
        if data_port_id is None:
            # All data port ids have to passed to the id generation as the data port id has to be unique inside a state
            data_port_id = generate_data_port_id(self.get_data_port_ids())
        self._output_data_ports[data_port_id] = OutputDataPort(name, data_type, default_value, data_port_id, self)

        # Check for name uniqueness
        valid, message = self._check_data_port_name(self._output_data_ports[data_port_id])
        if not valid:
            self._output_data_ports[data_port_id].parent = None
            del self._output_data_ports[data_port_id]
            raise ValueError(message)

        return data_port_id


Instruction:
Can you tell what is the following Python 3 function doing
def remove_output_data_port(self, data_port_id, force=False, destroy=True):
        if data_port_id in self._output_data_ports:
            if destroy:
                self.remove_data_flows_with_data_port_id(data_port_id)
            self._output_data_ports[data_port_id].parent = None
            return self._output_data_ports.pop(data_port_id)
        else:
            raise AttributeError("output data port with name %s does not exit", data_port_id)

Response: Removes an output data port from the state.


Instruction:
Make a summary of the following Python 3 code
def get_io_data_port_id_from_name_and_type(self, name, data_port_type):
        if data_port_type is InputDataPort:
            for ip_id, output_port in self.input_data_ports.items():
                if output_port.name == name:
                    return ip_id
            raise AttributeError("Name '{0}' is not in input_data_ports".format(name))
        elif data_port_type is OutputDataPort:
            for op_id, output_port in self.output_data_ports.items():
                if output_port.name == name:
                    return op_id
            # 'error' is an automatically generated output port in case of errors and exception and doesn't have an id
            if name == "error":
                return
            raise AttributeError("Name '{0}' is not in output_data_ports".format(name))

Response: Returns the data_port_id of a data port with a certain name and data port type


Instruction:
Make a summary of the following Python 3 code
def get_data_port_by_id(self, data_port_id):
        if data_port_id in self.input_data_ports:
            return self.input_data_ports[data_port_id]
        elif data_port_id in self.output_data_ports:
            return self.output_data_ports[data_port_id]
        return None

Response: This method searches for the given data port id in the input and output data ports of the state and returns the data port with the searched id or None if it is not found.


Instruction:
How would you explain what the following Python 3 function does
def get_path(self, appendix=None, by_name=False):
        if by_name:
            state_identifier = self.name
        else:
            state_identifier = self.state_id

        if not self.is_root_state:
            if appendix is None:
                return self.parent.get_path(state_identifier, by_name)
            else:
                return self.parent.get_path(state_identifier + PATH_SEPARATOR + appendix, by_name)
        else:
            if appendix is None:
                return state_identifier
            else:
                return state_identifier + PATH_SEPARATOR + appendix

Response: Recursively generates the path of the state.


Instruction:
Here you have a function in Python 3, explain what it does
def get_storage_path(self, appendix=None):
        state_identifier = storage.get_storage_id_for_state(self)

        if not self.is_root_state:
            if appendix is None:
                return self.parent.get_storage_path(state_identifier)
            else:
                return self.parent.get_storage_path(state_identifier + PATH_SEPARATOR + appendix)
        else:
            if appendix is None:
                return state_identifier
            else:
                return state_identifier + PATH_SEPARATOR + appendix

Response: Recursively creates the storage path of the state.


Instruction:
Can you create a Python 3 function that
gets a reference of the state_machine the state belongs to

Response:
def get_state_machine(self):
        """Get a reference of the state_machine the state belongs to

        :rtype rafcon.core.state_machine.StateMachine
        :return: respective state machine
        """
        if self.parent:
            if self.is_root_state:
                return self.parent
            else:
                return self.parent.get_state_machine()

        return None


Instruction:
Explain what the following Python 3 code does
def add_outcome(self, name, outcome_id=None):
        if outcome_id is None:
            outcome_id = generate_outcome_id(list(self.outcomes.keys()))
        if name in self._outcomes:
            logger.error("Two outcomes cannot have the same names")
            return
        if outcome_id in self.outcomes:
            logger.error("Two outcomes cannot have the same outcome_ids")
            return
        outcome = Outcome(outcome_id, name, self)
        self._outcomes[outcome_id] = outcome
        return outcome_id

Response: Add a new outcome to the state


Instruction:
Can you generate the documentation for the following Python 3 function
def remove(self, state_element, recursive=True, force=False, destroy=True):
        if isinstance(state_element, Income):
            self.remove_income(force, destroy=destroy)
        if isinstance(state_element, Outcome):
            return self.remove_outcome(state_element.outcome_id, force=force, destroy=destroy)
        elif isinstance(state_element, InputDataPort):
            return self.remove_input_data_port(state_element.data_port_id, force, destroy=destroy)
        elif isinstance(state_element, OutputDataPort):
            return self.remove_output_data_port(state_element.data_port_id, force, destroy=destroy)
        else:
            raise ValueError("Cannot remove state_element with invalid type")

Response: Removes the state element from the state store.


Instruction:
Explain what the following Python 3 code does
def remove_outcome(self, outcome_id, force=False, destroy=True):
        if outcome_id not in self.outcomes:
            raise AttributeError("There is no outcome_id %s" % str(outcome_id))

        if not force:
            if outcome_id == -1 or outcome_id == -2:
                raise AttributeError("You cannot remove the outcomes with id -1 or -2 as a state must always be able"
                                     "to return aborted or preempted")
        # Remove internal transitions to this outcome
        self.remove_outcome_hook(outcome_id)

        # delete possible transition connected to this outcome
        if destroy and not self.is_root_state:
            for transition_id, transition in self.parent.transitions.items():
                if transition.from_outcome == outcome_id and transition.from_state == self.state_id:
                    self.parent.remove_transition(transition_id)
                    break  # found the one outgoing transition

        # delete outcome it self
        self._outcomes[outcome_id].parent = None
        return self._outcomes.pop(outcome_id)

Response: Removes an outcome from the state.


Instruction:
Explain what the following Python 3 code does
def check_child_validity(self, child):
        # Check type of child and call appropriate validity test
        if isinstance(child, Income):
            return self._check_income_validity(child)
        if isinstance(child, Outcome):
            return self._check_outcome_validity(child)
        if isinstance(child, DataPort):
            return self._check_data_port_validity(child)
        if isinstance(child, ScopedData):
            return self._check_scoped_data_validity(child)
        return False, "Invalid state element for state of type {}".format(self.__class__.__name__)

Response: Checks validity of passed child object and returns a boolean indicating if the child is valid.


Instruction:
How would you code a function in Python 3 to
check the validity of an outcome

Response:
def _check_outcome_validity(self, check_outcome):
        """Checks the validity of an outcome

        Checks whether the id or the name of the outcome is already used by another outcome within the state.

        :param rafcon.core.logical_port.Outcome check_outcome: The outcome to be checked
        :return bool validity, str message: validity is True, when the outcome is valid, False else. message gives more
            information especially if the outcome is not valid
        """
        for outcome_id, outcome in self.outcomes.items():
            # Do not compare outcome with itself when checking for existing name/id
            if check_outcome is not outcome:
                if check_outcome.outcome_id == outcome_id:
                    return False, "outcome id '{0}' existing in state".format(check_outcome.outcome_id)
                if check_outcome.name == outcome.name:
                    return False, "outcome name '{0}' existing in state".format(check_outcome.name)
        return True, "valid"


Instruction:
Can you write a function in Python 3 where it
checks the validity of a data port

Response:
def _check_data_port_validity(self, check_data_port):
        """Checks the validity of a data port

        Checks whether the data flows connected to the port do not conflict with the data types.

        :param rafcon.core.data_port.DataPort check_data_port: The data port to be checked
        :return bool validity, str message: validity is True, when the data port is valid, False else. message gives
            more information especially if the data port is not valid
        """
        valid, message = self._check_data_port_id(check_data_port)
        if not valid:
            return False, message

        valid, message = self._check_data_port_name(check_data_port)
        if not valid:
            return False, message

        # Check whether the type matches any connected data port type
        # Only relevant, if there is a parent state, otherwise the port cannot be connected to data flows
        # TODO: check of internal connections
        if not self.is_root_state:
            # Call the check in the parent state, where the data flows are stored
            return self.parent.check_data_port_connection(check_data_port)
        else:
            from rafcon.core.states.container_state import ContainerState
            if isinstance(self, ContainerState):
                return self.check_data_port_connection(check_data_port)

        return True, "valid"


Instruction:
Can you tell what is the following Python 3 function doing
def _check_data_port_id(self, data_port):
        for input_data_port_id, input_data_port in self.input_data_ports.items():
            if data_port.data_port_id == input_data_port_id and data_port is not input_data_port:
                return False, "data port id already existing in state"
        for output_data_port_id, output_data_port in self.output_data_ports.items():
            if data_port.data_port_id == output_data_port_id and data_port is not output_data_port:
                return False, "data port id already existing in state"
        return True, "valid"

Response: Checks the validity of a data port id


Instruction:
Write a Python 3 script for
checking the validity of a data port name

Response:
def _check_data_port_name(self, data_port):
        """Checks the validity of a data port name

        Checks whether the name of the given data port is already used by anther data port within the state. Names
        must be unique with input data ports and output data ports.

        :param rafcon.core.data_port.DataPort data_port: The data port to be checked
        :return bool validity, str message: validity is True, when the data port is valid, False else. message gives
            more information especially if the data port is not valid
        """
        if data_port.data_port_id in self.input_data_ports:
            for input_data_port in self.input_data_ports.values():
                if data_port.name == input_data_port.name and data_port is not input_data_port:
                    return False, "data port name already existing in state's input data ports"

        elif data_port.data_port_id in self.output_data_ports:
            for output_data_port in self.output_data_ports.values():
                if data_port.name == output_data_port.name and data_port is not output_data_port:
                    return False, "data port name already existing in state's output data ports"

        return True, "valid"


Instruction:
Write a Python 3 script to
check the input data types of the state and generates an error message if they are not of the specified type.

Response:
def check_input_data_type(self):
        """Check the input data types of the state

        Checks all input data ports if the handed data is not of the specified type and generate an error logger message
        with details of the found type conflict.
        """
        for data_port in self.input_data_ports.values():
            if data_port.name in self.input_data and self.input_data[data_port.name] is not None:
                #check for class
                if not isinstance(self.input_data[data_port.name], data_port.data_type):
                    logger.error("{0} had an data port error: Input of execute function must be of type '{1}' not '{2}'"
                                 " as current value '{3}'".format(self, data_port.data_type.__name__,
                                                               type(self.input_data[data_port.name]).__name__,
                                                               self.input_data[data_port.name]))


Instruction:
Implement a Python 3 function for
checking the output data types of the state and generates an error if they are not of the specified type

Response:
def check_output_data_type(self):
        """Check the output data types of the state

        Checks all output data ports if the handed data is not of the specified type and generate an error logger
        message with details of the found type conflict.
        """
        for data_port in self.output_data_ports.values():
            if data_port.name in self.output_data and self.output_data[data_port.name] is not None:
                # check for class
                if not isinstance(self.output_data[data_port.name], data_port.data_type):
                    logger.error("{0} had an data port error: Output of execute function must be of type '{1}' not "
                                 "'{2}' as current value {3}".format(self, data_port.data_type.__name__,
                                                               type(self.output_data[data_port.name]).__name__,
                                                               self.output_data[data_port.name]))


Instruction:
Can you create a Python 3 function that
changes the id of the state to a new id.

Response:
def change_state_id(self, state_id=None):
        """Changes the id of the state to a new id

        If no state_id is passed as parameter, a new state id is generated.

        :param str state_id: The new state id of the state
        :return:
        """
        if state_id is None:
            state_id = state_id_generator(used_state_ids=[self.state_id])
        if not self.is_root_state and not self.is_root_state_of_library:
            used_ids = list(self.parent.states.keys()) + [self.parent.state_id, self.state_id]
            if state_id in used_ids:
                state_id = state_id_generator(used_state_ids=used_ids)

        self._state_id = state_id


Instruction:
Can you create a Python 3 function that
retrieves an entry of the semantic data.

Response:
def get_semantic_data(self, path_as_list):
        """ Retrieves an entry of the semantic data.

        :param list path_as_list: The path in the vividict to retrieve the value from
        :return:
        """
        target_dict = self.semantic_data
        for path_element in path_as_list:
            if path_element in target_dict:
                target_dict = target_dict[path_element]
            else:
                raise KeyError("The state with name {1} and id {2} holds no semantic data with path {0}."
                               "".format(path_as_list[:path_as_list.index(path_element) + 1], self.name, self.state_id))

        return target_dict


Instruction:
How would you implement a function in Python 3 that
adds a semantic data entry.

Response:
def add_semantic_data(self, path_as_list, value, key):
        """ Adds a semantic data entry.

        :param list path_as_list: The path in the vividict to enter the value
        :param value: The value of the new entry.
        :param key: The key of the new entry.
        :return:
        """
        assert isinstance(key, string_types)
        target_dict = self.get_semantic_data(path_as_list)
        target_dict[key] = value
        return path_as_list + [key]


Instruction:
How would you implement a function in Python 3 that
removes an entry from the semantic data vividict.

Response:
def remove_semantic_data(self, path_as_list):
        """ Removes a entry from the semantic data vividict.

        :param list path_as_list: The path of the vividict to delete.
        :return: removed value or dict
        """
        if len(path_as_list) == 0:
            raise AttributeError("The argument path_as_list is empty but but the method remove_semantic_data needs a "
                                 "valid path to remove a vividict item.")
        target_dict = self.get_semantic_data(path_as_list[0:-1])
        removed_element = target_dict[path_as_list[-1]]
        del target_dict[path_as_list[-1]]
        return removed_element


Instruction:
Create a Python 3 function to
remove all the state elements.

Response:
def destroy(self, recursive):
        """ Removes all the state elements.

        :param recursive: Flag wether to destroy all state elements which are removed
        """
        for in_key in list(self.input_data_ports.keys()):
            self.remove_input_data_port(in_key, force=True, destroy=recursive)

        for out_key in list(self.output_data_ports.keys()):
            self.remove_output_data_port(out_key, force=True, destroy=recursive)

        if self._income:
            self.remove_income(force=True, destroy=recursive)

        for outcome_key in list(self.outcomes.keys()):
            self.remove_outcome(outcome_key, force=True, destroy=recursive)


Instruction:
Can you generate the documentation for the following Python 3 function
def input_data_ports(self, input_data_ports):
        if not isinstance(input_data_ports, dict):
            raise TypeError("input_data_ports must be of type dict")
        if [port_id for port_id, port in input_data_ports.items() if not port_id == port.data_port_id]:
            raise AttributeError("The key of the input dictionary and the id of the data port do not match")

        # This is a fix for older state machines, which didn't distinguish between input and output ports
        for port_id, port in input_data_ports.items():
            if not isinstance(port, InputDataPort):
                if isinstance(port, DataPort):
                    port = InputDataPort(port.name, port.data_type, port.default_value, port.data_port_id)
                    input_data_ports[port_id] = port
                else:
                    raise TypeError("Elements of input_data_ports must be of type InputDataPort, given: {0}".format(
                        type(port).__name__))

        old_input_data_ports = self._input_data_ports
        self._input_data_ports = input_data_ports
        for port_id, port in input_data_ports.items():
            try:
                port.parent = self
            except ValueError:
                self._input_data_ports = old_input_data_ports
                raise

        # check that all old_input_data_ports are no more referencing self as there parent
        for old_input_data_port in old_input_data_ports.values():
            if old_input_data_port not in self._input_data_ports.values() and old_input_data_port.parent is self:
                old_input_data_port.parent = None

Response: Property for the _input_data_ports field


Instruction:
Can you tell what is the following Python 3 function doing
def outcomes(self, outcomes):
        if not isinstance(outcomes, dict):
            raise TypeError("outcomes must be of type dict")
        if [outcome_id for outcome_id, outcome in outcomes.items() if not isinstance(outcome, Outcome)]:
            raise TypeError("element of outcomes must be of type Outcome")
        if [outcome_id for outcome_id, outcome in outcomes.items() if not outcome_id == outcome.outcome_id]:
            raise AttributeError("The key of the outcomes dictionary and the id of the outcome do not match")

        old_outcomes = self.outcomes
        self._outcomes = outcomes
        for outcome_id, outcome in outcomes.items():
            try:
                outcome.parent = self
            except ValueError:
                self._outcomes = old_outcomes
                raise

        # aborted and preempted must always exist
        if -1 not in outcomes:
            self._outcomes[-1] = Outcome(outcome_id=-1, name="aborted", parent=self)
        if -2 not in outcomes:
            self._outcomes[-2] = Outcome(outcome_id=-2, name="preempted", parent=self)

        # check that all old_outcomes are no more referencing self as there parent
        for old_outcome in old_outcomes.values():
            if old_outcome not in iter(list(self._outcomes.values())) and old_outcome.parent is self:
                old_outcome.parent = None

Response: Setters for _outcomes field


Instruction:
Here you have a function in Python 3, explain what it does
def is_root_state_of_library(self):
        from rafcon.core.states.library_state import LibraryState
        return isinstance(self.parent, LibraryState)

Response: Returns True if the state is the root state of a library state and False otherwise


Instruction:
Write a Python 3 script to
return the next upper library root state in the state_copy.

Response:
def get_next_upper_library_root_state(self):
        """ Get next upper library root state

        The method recursively checks state parent states till finding a StateMachine as parent or a library root state.
        If self is a LibraryState the next upper library root state is searched and it is not handed self.state_copy.

        :return library root state (Execution or ContainerState) or None if self is not a library root state or
        inside of such
        :rtype rafcon.core.states.library_state.State:
        """
        from rafcon.core.state_machine import StateMachine

        if self.is_root_state_of_library:
            return self

        state = self
        while state.parent is not None and not isinstance(state.parent, StateMachine):
            if state.parent.is_root_state_of_library:
                return state.parent
            state = state.parent
        return None


Instruction:
How would you code a function in Python 3 to
find state_copy of uppermost LibraryState Method checks if there is a parent library root state and assigns it to the current library root state till there is no further parent library root state till there is no further parent library root state.

Response:
def get_uppermost_library_root_state(self):
        """Find state_copy of uppermost LibraryState

        Method checks if there is a parent library root state and assigns it to be the current library root state till
        there is no further parent library root state.
        """

        library_root_state = self.get_next_upper_library_root_state()
        parent_library_root_state = library_root_state
        # initial a library root state has to be found and if there is no further parent root state
        # parent_library_root_state and library_root_state are no more identical
        while parent_library_root_state and library_root_state is parent_library_root_state:
            if library_root_state:
                parent_library_root_state = library_root_state.parent.get_next_upper_library_root_state()

            if parent_library_root_state:
                library_root_state = parent_library_root_state

        return library_root_state


Instruction:
Write a Python 3 function for
finalizing state This method is called when the run method finishes :param rafcon.core.logical_port.Outcome outcome: final outcome of the state :return: Nothing for the moment

Response:
def finalize(self, outcome=None):
        """Finalize state

        This method is called when the run method finishes

        :param rafcon.core.logical_port.Outcome outcome: final outcome of the state
        :return: Nothing for the moment
        """

        # Set the final outcome of the state
        if outcome is not None:
            self.final_outcome = outcome

        # If we are within a concurrency state, we have to notify it about our finalization
        if self.concurrency_queue:
            self.concurrency_queue.put(self.state_id)

        logger.debug("Finished execution of {0}: {1}".format(self, self.final_outcome))

        return None


Instruction:
Implement a Python 3 function for
constructing an undirected multigraph from a list containing data on weighted edges.

Response:
def graph_from_edges(edges):
    """ Constructs an undirected multigraph from a list containing data on
    weighted edges.

    Parameters
    ----------
    edges : list
        List of tuples each containing first node, second node, weight, key.

    Returns
    -------
    M : :class:`networkx.classes.multigraph.MultiGraph
    """

    M = nx.MultiGraph()

    for e in edges:

        n0, n1, weight, key = e

        M.add_edge(n0, n1, weight=weight, key=key)

    return M


Instruction:
Here you have a function in Python 3, explain what it does
def busmap_from_psql(network, session, scn_name):

    def fetch():

        query = session.query(EgoGridPfHvBusmap.bus0, EgoGridPfHvBusmap.bus1).\
            filter(EgoGridPfHvBusmap.scn_name == scn_name)

        return dict(query.all())

    busmap = fetch()

    # TODO: Or better try/except/finally
    if not busmap:
        print('Busmap does not exist and will be created.\n')

        cpu_cores = input('cpu_cores (default 4): ') or '4'

        busmap_by_shortest_path(network, session, scn_name,
                                fromlvl=[110], tolvl=[220, 380, 400, 450],
                                cpu_cores=int(cpu_cores))
        busmap = fetch()

    return busmap

Response: Returns a dict containing all the bus_ids of all network components in a given scenario.


Instruction:
Explain what the following Python 3 code does
def kmean_clustering(network, n_clusters=10, load_cluster=False,
                     line_length_factor=1.25,
                     remove_stubs=False, use_reduced_coordinates=False,
                     bus_weight_tocsv=None, bus_weight_fromcsv=None,
                     n_init=10, max_iter=300, tol=1e-4,
                     n_jobs=1):
    """ Main function of the k-mean clustering approach. Maps an original
    network to a new one with adjustable number of nodes and new coordinates.

    Parameters
    ----------
    network : :class:`pypsa.Network
        Container for all network components.

    n_clusters : int
        Desired number of clusters.

    load_cluster : boolean
        Loads cluster coordinates from a former calculation.

    line_length_factor : float
        Factor to multiply the crow-flies distance between new buses in order
        to get new line lengths.

    remove_stubs: boolean
        Removes stubs and stubby trees (i.e. sequentially reducing dead-ends).

    use_reduced_coordinates: boolean
        If True, do not average cluster coordinates, but take from busmap.

    bus_weight_tocsv : str
        Creates a bus weighting based on conventional generation and load
        and save it to a csv file.

    bus_weight_fromcsv : str
        Loads a bus weighting from a csv file to apply it to the clustering
        algorithm.

    Returns
    -------
    network : pypsa.Network object
        Container for all network components.
    """
    def weighting_for_scenario(x, save=None):
        """
        """
        b_i = x.index
        g = normed(gen.reindex(b_i, fill_value=0))
        l = normed(load.reindex(b_i, fill_value=0))

        w = g + l
        weight = ((w * (100000. / w.max())).astype(int)
                  ).reindex(network.buses.index, fill_value=1)

        if save:
            weight.to_csv(save)

        return weight

    def normed(x):
        return (x / x.sum()).fillna(0.)

    print('start k-mean clustering')
    # prepare k-mean
    # k-means clustering (first try)
    network.generators.control = "PV"
    network.storage_units.control[network.storage_units.carrier == \
                                  'extendable_storage'] = "PV"
    network.buses['v_nom'] = 380.
    # problem our lines have no v_nom. this is implicitly defined by the
    # connected buses:
    network.lines["v_nom"] = network.lines.bus0.map(network.buses.v_nom)

    # adjust the x of the lines which are not 380.
    lines_v_nom_b = network.lines.v_nom != 380
    network.lines.loc[lines_v_nom_b, 'x'] *= \
        (380. / network.lines.loc[lines_v_nom_b, 'v_nom'])**2
    network.lines.loc[lines_v_nom_b, 'v_nom'] = 380.

    trafo_index = network.transformers.index
    transformer_voltages = \
        pd.concat([network.transformers.bus0.map(network.buses.v_nom),
                   network.transformers.bus1.map(network.buses.v_nom)], axis=1)

    network.import_components_from_dataframe(
        network.transformers.loc[:, [
                'bus0', 'bus1', 'x', 's_nom', 'capital_cost', 'sub_network', 's_nom_total']]
        .assign(x=network.transformers.x * (380. /
                transformer_voltages.max(axis=1))**2, length = 1)
        .set_index('T' + trafo_index),
        'Line')
    network.transformers.drop(trafo_index, inplace=True)

    for attr in network.transformers_t:
        network.transformers_t[attr] = network.transformers_t[attr]\
            .reindex(columns=[])

    # remove stubs
    if remove_stubs:
        network.determine_network_topology()
        busmap = busmap_by_stubs(network)
        network.generators['weight'] = network.generators['p_nom']
        aggregate_one_ports = components.one_port_components.copy()
        aggregate_one_ports.discard('Generator')
        # reset coordinates to the new reduced guys, rather than taking an
        # average (copied from pypsa.networkclustering)
        if use_reduced_coordinates:
            # TODO : FIX THIS HACK THAT HAS UNEXPECTED SIDE-EFFECTS,
            # i.e. network is changed in place!!
            network.buses.loc[busmap.index, ['x', 'y']
                              ] = network.buses.loc[busmap, ['x', 'y']].values

        clustering = get_clustering_from_busmap(
            network,
            busmap,
            aggregate_generators_weighted=True,
            aggregate_one_ports=aggregate_one_ports,
            line_length_factor=line_length_factor)
        network = clustering.network

    # define weighting based on conventional 'old' generator spatial
    # distribution
    non_conv_types = {
        'biomass',
        'wind_onshore',
        'wind_offshore',
        'solar',
        'geothermal',
        'load shedding',
        'extendable_storage'}
    # Attention: network.generators.carrier.unique()
    gen = (network.generators.loc[(network.generators.carrier
                                   .isin(non_conv_types) == False)]
           .groupby('bus').p_nom.sum()
                                .reindex(network.buses.index, fill_value=0.) +
           network.storage_units
                                .loc[(network.storage_units.carrier
                                      .isin(non_conv_types) == False)]
                  .groupby('bus').p_nom.sum()
                  .reindex(network.buses.index, fill_value=0.))

    load = network.loads_t.p_set.mean().groupby(network.loads.bus).sum()

    # k-mean clustering

    # busmap = busmap_by_kmeans(network, bus_weightings=pd.Series(np.repeat(1,
    #       len(network.buses)), index=network.buses.index) , n_clusters= 10)
    # State whether to create a bus weighting and save it, create or not save
    # it, or use a bus weighting from a csv file
    if bus_weight_tocsv is not None:
        weight = weighting_for_scenario(x=network.buses, save=bus_weight_tocsv)
    elif bus_weight_fromcsv is not None:
        weight = pd.Series.from_csv(bus_weight_fromcsv)
        weight.index = weight.index.astype(str)
    else:
        weight = weighting_for_scenario(x=network.buses, save=False)

    busmap = busmap_by_kmeans(
        network,
        bus_weightings=pd.Series(weight),
        n_clusters=n_clusters,
        load_cluster=load_cluster,
        n_init=n_init,
        max_iter=max_iter,
        tol=tol,
        n_jobs=n_jobs)

    # ToDo change function in order to use bus_strategies or similar
    network.generators['weight'] = network.generators['p_nom']
    aggregate_one_ports = components.one_port_components.copy()
    aggregate_one_ports.discard('Generator')
    clustering = get_clustering_from_busmap(
        network,
        busmap,
        aggregate_generators_weighted=True,
        aggregate_one_ports=aggregate_one_ports)

    return clustering

Response: K - mean clustering algorithm.


Instruction:
Here you have a function in Python 3, explain what it does
def register_actions(self, shortcut_manager):
        super(DescriptionEditorController, self).register_actions(shortcut_manager)
        shortcut_manager.add_callback_for_action("abort", self._abort)

Response: Register callback methods for triggered actions


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

        self.view.connect('meta_data_changed', self._meta_data_changed)
        self.focus_changed_handler_id = self.view.editor.connect('focus-changed', self._move_focused_item_into_viewport)
        self.view.editor.connect("drag-data-received", self.on_drag_data_received)
        self.drag_motion_handler_id = self.view.editor.connect("drag-motion", self.on_drag_motion)

        self.setup_canvas()

Response: Called when the View was registered


Instruction:
Can you implement a function in Python 3 that
registers callback methods for triggered actions.

Response:
def register_actions(self, shortcut_manager):
        """Register callback methods for triggered actions

        :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
            between shortcuts and actions.
        """
        shortcut_manager.add_callback_for_action("add", partial(self._add_new_state, state_type=StateType.EXECUTION))
        shortcut_manager.add_callback_for_action("add_execution_state", partial(self._add_new_state,
                                                                                state_type=StateType.EXECUTION))
        shortcut_manager.add_callback_for_action("add_hierarchy_state", partial(self._add_new_state,
                                                                                state_type=StateType.HIERARCHY))
        shortcut_manager.add_callback_for_action("add_barrier_state", partial(self._add_new_state,
                                                                              state_type=StateType.BARRIER_CONCURRENCY))
        shortcut_manager.add_callback_for_action("add_preemptive_state", partial(self._add_new_state,
                                                                                state_type=StateType.PREEMPTION_CONCURRENCY))

        shortcut_manager.add_callback_for_action("add_output", partial(self._add_data_port_to_selected_state,
                                                                       data_port_type='OUTPUT'))
        shortcut_manager.add_callback_for_action("add_input", partial(self._add_data_port_to_selected_state,
                                                                      data_port_type='INPUT'))
        shortcut_manager.add_callback_for_action("add_scoped_variable", self._add_scoped_variable_to_selected_state)
        shortcut_manager.add_callback_for_action("add_outcome", self._add_outcome_to_selected_state)

        shortcut_manager.add_callback_for_action("delete", self._remove_selected_elements)

        shortcut_manager.add_callback_for_action("copy", self._copy_selection)
        shortcut_manager.add_callback_for_action("paste", self._paste_clipboard)
        shortcut_manager.add_callback_for_action("cut", self._cut_selection)

        shortcut_manager.add_callback_for_action('show_data_flows', self.update_view)
        shortcut_manager.add_callback_for_action('show_data_values', self.update_view)
        shortcut_manager.add_callback_for_action('data_flow_mode', self.data_flow_mode)
        shortcut_manager.add_callback_for_action('show_aborted_preempted', self.update_view)


Instruction:
Can you tell what is the following Python 3 function doing
def on_drag_data_received(self, widget, context, x, y, data, info, time):
        state_id_insert = data.get_text()
        parent_m = self.model.selection.get_selected_state()
        if not isinstance(parent_m, ContainerStateModel):
            return
        state_v = self.canvas.get_view_for_model(parent_m.states[state_id_insert])
        pos_start = state_v.model.get_meta_data_editor()['rel_pos']
        motion = InMotion(state_v, self.view.editor)
        motion.start_move(self.view.editor.get_matrix_i2v(state_v).transform_point(pos_start[0], pos_start[1]))
        motion.move((x, y))
        motion.stop_move()
        state_v.model.set_meta_data_editor('rel_pos', motion.item.position)
        self.canvas.wait_for_update(trigger_update=True)
        self._meta_data_changed(None, state_v.model, 'append_to_last_change', True)

Response: Handles the drag data received from the LibraryTree and moves the state to the position of the mouse.


Instruction:
How would you explain what the following Python 3 function does
def on_drag_motion(self, widget, context, x, y, time):
        hovered_item = ItemFinder(self.view.editor).get_item_at_point((x, y))
        if isinstance(hovered_item, NameView):
            hovered_item = hovered_item.parent
        if hovered_item is None:
            self.view.editor.unselect_all()
        elif isinstance(hovered_item.model, ContainerStateModel):
            if len(self.view.editor.selected_items) == 1 and hovered_item in self.view.editor.selected_items:
                return
            if len(self.view.editor.selected_items) > 0:
                self.view.editor.unselect_all()

            if not rafcon.gui.singleton.global_gui_config.get_config_value('DRAG_N_DROP_WITH_FOCUS'):
                self.view.editor.handler_block(self.focus_changed_handler_id)
            self.view.editor.focused_item = hovered_item
            if not rafcon.gui.singleton.global_gui_config.get_config_value('DRAG_N_DROP_WITH_FOCUS'):
                self.view.editor.handler_unblock(self.focus_changed_handler_id)

Response: Changes the selection on mouse over during drag motion


Instruction:
Given the following Python 3 function, write the documentation
def _add_new_state(self, *event, **kwargs):
        if react_to_event(self.view, self.view.editor, event):
            state_type = StateType.EXECUTION if 'state_type' not in kwargs else kwargs['state_type']
            return gui_helper_state_machine.add_new_state(self.model, state_type)

Response: Triggered when the add new state is clicked.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _copy_selection(self, *event):
        if react_to_event(self.view, self.view.editor, event):
            logger.debug("copy selection")
            global_clipboard.copy(self.model.selection)
            return True

Response: Copies the current selection to the clipboard.


Instruction:
Write a Python 3 function that can
cut the current selection and copies it to the clipboard.

Response:
def _cut_selection(self, *event):
        """Cuts the current selection and copys it to the clipboard.
        """
        if react_to_event(self.view, self.view.editor, event):
            logger.debug("cut selection")
            global_clipboard.cut(self.model.selection)
            return True


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _paste_clipboard(self, *event):
        if react_to_event(self.view, self.view.editor, event):
            logger.debug("Paste")
            gui_helper_state_machine.paste_into_selected_state(self.model)
            return True

Response: Paste the current clipboard into the current selection if the current selection is a container state.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _move_focused_item_into_viewport(self, view, focused_item):
        self.view.editor.handler_block(self.drag_motion_handler_id)
        self.move_item_into_viewport(focused_item)
        self.view.editor.handler_unblock(self.drag_motion_handler_id)

Response: Called when an item is focused moves the item into the viewport


Instruction:
Write a Python 3 function for
moving the item into the viewport.

Response:
def move_item_into_viewport(self, item):
        """Causes the `item` to be moved into the viewport

        The zoom factor and the position of the viewport are updated to move the `item` into the viewport. If `item`
        is not a `StateView`, the parental `StateView` is moved into the viewport.

        :param StateView | ConnectionView | PortView item: The item to be moved into the viewport
        """
        if not item:
            return
        HORIZONTAL = 0
        VERTICAL = 1
        if not isinstance(item, Item):
            state_v = item.parent
        elif not isinstance(item, StateView):
            state_v = self.canvas.get_parent(item)
        else:
            state_v = item
        viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height
        state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height)
        min_relative_size = min(viewport_size[i] / state_size[i] for i in [HORIZONTAL, VERTICAL])

        if min_relative_size != 1:
            # Allow margin around state
            margin_relative = 1. / gui_constants.BORDER_WIDTH_STATE_SIZE_FACTOR
            zoom_factor = min_relative_size * (1 - margin_relative)
            if zoom_factor > 1:
                zoom_base = 4
                zoom_factor = max(1, math.log(zoom_factor*zoom_base, zoom_base))
            self.view.editor.zoom(zoom_factor)
            # The zoom operation must be performed before the pan operation to work on updated GtkAdjustments (scroll
            # bars)
            self.canvas.wait_for_update()

        state_pos = self.view.editor.get_matrix_i2v(state_v).transform_point(0, 0)
        state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height)
        viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height

        # Calculate offset around state so that the state is centered in the viewport
        padding_offset_horizontal = (viewport_size[HORIZONTAL] - state_size[HORIZONTAL]) / 2.
        padding_offset_vertical = (viewport_size[VERTICAL] - state_size[VERTICAL]) / 2.
        self.view.editor.hadjustment.set_value(state_pos[HORIZONTAL] - padding_offset_horizontal)
        self.view.editor.vadjustment.set_value(state_pos[VERTICAL] - padding_offset_vertical)


Instruction:
Write a Python 3 script for
cleaning up when state machine is being destructed

Response:
def state_machine_destruction(self, model, prop_name, info):
        """ Clean up when state machine is being destructed """
        if self.model is model:  # only used for the state machine destruction case
            self.canvas.get_view_for_model(self.root_state_m).remove()


Instruction:
Can you implement a function in Python 3 that
handles the meta data of the affected state

Response:
def meta_changed_notify_after(self, state_machine_m, _, info):
        """Handle notification about the change of a state's meta data

        The meta data of the affected state(s) are read and the view updated accordingly.
        :param StateMachineModel state_machine_m: Always the state machine model belonging to this editor
        :param str _: Always "state_meta_signal"
        :param dict info: Information about the change, contains the MetaSignalMessage in the 'arg' key value
        """
        meta_signal_message = info['arg']
        if meta_signal_message.origin == "graphical_editor_gaphas":  # Ignore changes caused by ourself
            return
        if meta_signal_message.origin == "load_meta_data":  # Meta data can't be applied, as the view has not yet
            return                                          # been created
        notification = meta_signal_message.notification
        if not notification:    # For changes applied to the root state, there are always two notifications
            return              # Ignore the one with less information
        if self.model.ongoing_complex_actions:
            return

        model = notification.model
        view = self.canvas.get_view_for_model(model)

        if meta_signal_message.change == 'show_content':
            library_state_m = model
            library_state_v = view
            if library_state_m.meta['gui']['show_content'] is not library_state_m.show_content():
                logger.warning("The content of the LibraryState won't be shown, because "
                               "MAX_VISIBLE_LIBRARY_HIERARCHY is 1.")
            if library_state_m.show_content():
                if not library_state_m.state_copy_initialized:
                    logger.warning("Show library content without initialized state copy does not work {0}"
                                   "".format(library_state_m))
                logger.debug("Show content of {}".format(library_state_m.state))
                gui_helper_meta_data.scale_library_content(library_state_m)
                self.add_state_view_for_model(library_state_m.state_copy, view,
                                              hierarchy_level=library_state_v.hierarchy_level + 1)
            else:
                logger.debug("Hide content of {}".format(library_state_m.state))
                state_copy_v = self.canvas.get_view_for_model(library_state_m.state_copy)
                if state_copy_v:
                    state_copy_v.remove()
        else:
            if isinstance(view, StateView):
                view.apply_meta_data(recursive=meta_signal_message.affects_children)
            else:
                view.apply_meta_data()

        self.canvas.request_update(view, matrix=True)
        self.canvas.wait_for_update()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def state_machine_change_after(self, model, prop_name, info):

        if 'method_name' in info and info['method_name'] == 'root_state_change':
            method_name, model, result, arguments, instance = self._extract_info_data(info['kwargs'])

            if self.model.ongoing_complex_actions:
                return

            # The method causing the change raised an exception, thus nothing was changed
            if (isinstance(result, string_types) and "CRASH" in result) or isinstance(result, Exception):
                return

            # avoid to remove views of elements of states which parent state is destroyed recursively
            if 'remove' in method_name:
                # for remove the model is always a state and in case of remove_state it is the container_state
                # that performs the operation therefore if is_about_to_be_destroyed_recursively is False
                # the child state can be removed and for True ignored because its parent will create a notification
                if model.is_about_to_be_destroyed_recursively:
                    return

            # only react to the notification if the model is a model, which has to be drawn
            # if it is a model inside a library state, this is eventually not the case
            if isinstance(model, AbstractStateModel):
                library_root_state = model.state.get_next_upper_library_root_state()
                if library_root_state:
                    parent_library_root_state_m = self.model.get_state_model_by_path(library_root_state.get_path())
                    if not parent_library_root_state_m.parent.show_content():
                        return

            if method_name == 'state_execution_status':
                state_v = self.canvas.get_view_for_model(model)
                if state_v:  # Children of LibraryStates are not modeled, yet
                    self.canvas.request_update(state_v, matrix=False)
            elif method_name == 'add_state':
                new_state = arguments[1]
                new_state_m = model.states[new_state.state_id]
                self.add_state_view_with_meta_data_for_model(new_state_m, model)
                if not self.perform_drag_and_drop:
                    self.canvas.wait_for_update()
            elif method_name == 'remove_state':
                state_v = self.canvas.get_view_for_core_element(result)
                if state_v:
                    parent_v = self.canvas.get_parent(state_v)
                    state_v.remove()
                    if parent_v:
                        self.canvas.request_update(parent_v)
                    self.canvas.wait_for_update()

            # ----------------------------------
            #           TRANSITIONS
            # ----------------------------------
            elif method_name == 'add_transition':
                transitions_models = model.transitions
                transition_id = result
                for transition_m in transitions_models:
                    if transition_m.transition.transition_id == transition_id:
                        self.add_transition_view_for_model(transition_m, model)
                        self.canvas.wait_for_update()
                        break
            elif method_name == 'remove_transition':
                transition_v = self.canvas.get_view_for_core_element(result)
                if transition_v:
                    state_m = model
                    state_v = self.canvas.get_view_for_model(state_m)
                    transition_v.remove()
                    self.canvas.request_update(state_v, matrix=False)
                    self.canvas.wait_for_update()
            elif method_name == 'transition_change':
                transition_m = model
                transition_v = self.canvas.get_view_for_model(transition_m)
                self._reconnect_transition(transition_v, transition_m, transition_m.parent)
                self.canvas.wait_for_update()

            # ----------------------------------
            #           DATA FLOW
            # ----------------------------------
            elif method_name == 'add_data_flow':
                data_flow_models = model.data_flows
                data_flow_id = result
                for data_flow_m in data_flow_models:
                    if data_flow_m.data_flow.data_flow_id == data_flow_id:
                        self.add_data_flow_view_for_model(data_flow_m, model)
                        self.canvas.wait_for_update()
                        break
            elif method_name == 'remove_data_flow':
                data_flow_v = self.canvas.get_view_for_core_element(result)
                if data_flow_v:
                    state_m = model
                    state_v = self.canvas.get_view_for_model(state_m)
                    self.canvas.request_update(state_v, matrix=False)
                    data_flow_v.remove()
                    self.canvas.wait_for_update()
            elif method_name == 'data_flow_change':
                data_flow_m = model
                data_flow_v = self.canvas.get_view_for_model(data_flow_m)
                self._reconnect_data_flow(data_flow_v, data_flow_m, data_flow_m.parent)
                self.canvas.wait_for_update()

            # ----------------------------------
            #           OUTCOMES
            # ----------------------------------
            elif method_name == 'add_outcome':
                state_m = model
                state_v = self.canvas.get_view_for_model(state_m)
                for outcome_m in state_m.outcomes:
                    if outcome_m.outcome.outcome_id == result:
                        state_v.add_outcome(outcome_m)
                        self.canvas.request_update(state_v, matrix=False)
                        self.canvas.wait_for_update()
                        break
            elif method_name == 'remove_outcome':
                state_m = model
                state_v = self.canvas.get_view_for_model(state_m)
                if state_v is None:
                    logger.debug("no state_v found for method_name '{}'".format(method_name))
                else:
                    outcome_v = self.canvas.get_view_for_core_element(result)
                    if outcome_v:
                        state_v.remove_outcome(outcome_v)
                        self.canvas.request_update(state_v, matrix=False)
                        self.canvas.wait_for_update()

            # ----------------------------------
            #           DATA PORTS
            # ----------------------------------
            elif method_name == 'add_input_data_port':
                state_m = model
                state_v = self.canvas.get_view_for_model(state_m)
                for input_data_port_m in state_m.input_data_ports:
                    if input_data_port_m.data_port.data_port_id == result:
                        state_v.add_input_port(input_data_port_m)
                        self.canvas.request_update(state_v, matrix=False)
                        self.canvas.wait_for_update()
                        break
            elif method_name == 'add_output_data_port':
                state_m = model
                state_v = self.canvas.get_view_for_model(state_m)
                for output_data_port_m in state_m.output_data_ports:
                    if output_data_port_m.data_port.data_port_id == result:
                        state_v.add_output_port(output_data_port_m)
                        self.canvas.request_update(state_v, matrix=False)
                        self.canvas.wait_for_update()
                        break
            elif method_name == 'remove_input_data_port':
                state_m = model
                state_v = self.canvas.get_view_for_model(state_m)
                if state_v is None:
                    logger.debug("no state_v found for method_name '{}'".format(method_name))
                else:
                    input_port_v = self.canvas.get_view_for_core_element(result)
                    if input_port_v:
                        state_v.remove_input_port(input_port_v)
                        self.canvas.request_update(state_v, matrix=False)
                        self.canvas.wait_for_update()
            elif method_name == 'remove_output_data_port':
                state_m = model
                state_v = self.canvas.get_view_for_model(state_m)
                if state_v is None:
                    logger.debug("no state_v found for method_name '{}'".format(method_name))
                else:
                    output_port_v = self.canvas.get_view_for_core_element(result)
                    if output_port_v:
                        state_v.remove_output_port(output_port_v)
                        self.canvas.request_update(state_v, matrix=False)
                        self.canvas.wait_for_update()
            elif method_name in ['data_type', 'change_data_type']:
                pass
            elif method_name == 'default_value':
                pass

            # ----------------------------------
            #         SCOPED VARIABLES
            # ----------------------------------
            elif method_name == 'add_scoped_variable':
                state_m = model
                state_v = self.canvas.get_view_for_model(state_m)
                for scoped_variable_m in state_m.scoped_variables:
                    if scoped_variable_m.scoped_variable.data_port_id == result:
                        state_v.add_scoped_variable(scoped_variable_m)
                        self.canvas.request_update(state_v, matrix=False)
                        self.canvas.wait_for_update()
                        break
            elif method_name == 'remove_scoped_variable':
                state_m = model
                state_v = self.canvas.get_view_for_model(state_m)
                if state_v is None:
                    logger.debug("no state_v found for method_name '{}'".format(method_name))
                else:
                    scoped_variable_v = self.canvas.get_view_for_core_element(result)
                    if scoped_variable_v:
                        state_v.remove_scoped_variable(scoped_variable_v)
                        self.canvas.request_update(state_v, matrix=False)
                        self.canvas.wait_for_update()

            # ----------------------------------
            #        STATE MISCELLANEOUS
            # ----------------------------------
            elif method_name == 'name':
                # The name of a state was changed
                if not isinstance(model, AbstractStateModel):
                    parent_model = model.parent
                # The name of a port (input, output, scoped var, outcome) was changed
                else:
                    parent_model = model
                state_v = self.canvas.get_view_for_model(parent_model)
                if parent_model is model:
                    state_v.name_view.name = arguments[1]
                    self.canvas.request_update(state_v.name_view, matrix=False)
                else:
                    self.canvas.request_update(state_v, matrix=False)
                self.canvas.wait_for_update()
            elif method_name == 'parent':
                pass
            elif method_name == 'description':
                pass
            elif method_name == 'script_text':
                pass
            # TODO handle the following method calls -> for now those are explicit (in the past implicit) ignored
            # TODO -> correct the complex actions which are used in some test (by test calls or by adapting the model)
            elif method_name in ['input_data_ports', 'output_data_ports', 'outcomes',
                                 'change_root_state_type', 'change_state_type',
                                 'group_states', 'ungroup_state', 'substitute_state']:
                pass
            else:
                known_ignore_list = ['set_input_runtime_value', 'set_use_input_runtime_value',  # from library State
                                     'set_output_runtime_value', 'set_use_output_runtime_value',
                                     'input_data_port_runtime_values', 'use_runtime_value_input_data_ports',
                                     'output_data_port_runtime_values', 'use_runtime_value_output_data_ports',
                                     'semantic_data', 'add_semantic_data', 'remove_semantic_data',
                                     'remove_income']
                if method_name not in known_ignore_list:
                    logger.warning("Method {0} not caught in GraphicalViewer, details: {1}".format(method_name, info))

            if method_name in ['add_state', 'add_transition', 'add_data_flow', 'add_outcome', 'add_input_data_port',
                               'add_output_data_port', 'add_scoped_variable', 'data_flow_change', 'transition_change']:
                try:
                    self._meta_data_changed(None, model, 'append_to_last_change', True)
                except Exception as e:
                    logger.exception('Error while trying to emit meta data signal {0} {1}'.format(e, model))

Response: Called when any state machine changes within the state machine


Instruction:
Create a Python 3 function for
focusing a state view of respective state model

Response:
def set_focus_to_state_model(self, state_m, ratio_requested=0.8):
        """ Focus a state view of respective state model
        :param rafcon.gui.model.state state_m: Respective state model of state view to be focused
        :param ratio_requested: Minimum ratio of the screen which is requested, so can be more
        :return:
        """
        state_machine_m = self.model
        state_v = self.canvas.get_view_for_model(state_m)
        if state_v is None:
            logger.warning('There is no view for state model {0}'.format(state_m))
        self.move_item_into_viewport(state_v)
        # check_relative size in view and call it again if the state is still very small
        state_v = self.canvas.get_view_for_model(state_machine_m.root_state)
        state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height)
        viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height
        if state_size[0] < ratio_requested*viewport_size[0] and state_size[1] < ratio_requested*viewport_size[1]:
            self.set_focus_to_state_model(state_m, ratio_requested)


Instruction:
Given the following Python 3 function, write the documentation
def add_state_view_for_model(self, state_m, parent_v=None, rel_pos=(0, 0), size=(100, 100), hierarchy_level=1):
        assert isinstance(state_m, AbstractStateModel)
        state_meta = state_m.get_meta_data_editor()

        # Use default values if no size information is stored
        if not gui_helper_meta_data.contains_geometric_info(state_meta['size']):
            state_meta = state_m.set_meta_data_editor('size', size)

        size = state_meta['size']

        # Use default values if no position information is stored
        if not gui_helper_meta_data.contains_geometric_info(state_meta['rel_pos']):
            state_meta = state_m.set_meta_data_editor('rel_pos', rel_pos)

        rel_pos = state_meta['rel_pos']

        if isinstance(state_m, LibraryStateModel):
            if not state_m.meta_data_was_scaled:
                gui_helper_meta_data.scale_library_ports_meta_data(state_m, gaphas_editor=True)

        state_v = StateView(state_m, size, hierarchy_level)

        # Draw state above data flows and NameView but beneath transitions
        num_data_flows = len(state_m.state.parent.data_flows) if isinstance(state_m.parent, ContainerStateModel) else 0
        index = 1 if not parent_v else num_data_flows + 1
        # if self.model.root_state is state_m:
        #     print("init root_state", state_m, state_v)
        # else:
        #     print("init state", state_m, state_v)
        # print([hash(elem) for elem in state_m.state.outcomes.values()])
        self.canvas.add(state_v, parent_v, index=index)
        state_v.matrix.translate(*rel_pos)

        state_v.add_income(state_m.income)

        for outcome_m in state_m.outcomes:
            state_v.add_outcome(outcome_m)

        for input_port_m in state_m.input_data_ports:
            state_v.add_input_port(input_port_m)

        for output_port_m in state_m.output_data_ports:
            state_v.add_output_port(output_port_m)

        if parent_v is not None:
            # Keep state within parent
            pass

        if isinstance(state_m, LibraryStateModel) and state_m.show_content() and state_m.state_copy_initialized:
            gui_helper_meta_data.scale_library_content(state_m)
            self.add_state_view_for_model(state_m.state_copy, state_v, hierarchy_level=hierarchy_level + 1)

        elif isinstance(state_m, ContainerStateModel):
            num_child_state = 0

            for scoped_variable_m in state_m.scoped_variables:
                state_v.add_scoped_variable(scoped_variable_m)

            for child_state_m in state_m.states.values():
                # generate optional meta data for child state - not used if valid meta data already in child state model
                child_rel_pos, child_size = gui_helper_meta_data.generate_default_state_meta_data(state_m, self.canvas,
                                                                                num_child_state)
                num_child_state += 1

                self.add_state_view_for_model(child_state_m, state_v, child_rel_pos, child_size, hierarchy_level + 1)

            for transition_m in state_m.transitions:
                self.add_transition_view_for_model(transition_m, state_m)

            for data_flow_m in state_m.data_flows:
                self.add_data_flow_view_for_model(data_flow_m, state_m)

        return state_v

Response: Adds a new state view for the given state model.


Instruction:
How would you explain what the following Python 3 function does
def add_transition_view_for_model(self, transition_m, parent_state_m):
        parent_state_v = self.canvas.get_view_for_model(parent_state_m)

        hierarchy_level = parent_state_v.hierarchy_level
        transition_v = TransitionView(transition_m, hierarchy_level)

        # Draw transition above all other state elements
        self.canvas.add(transition_v, parent_state_v, index=None)

        self._connect_transition_to_ports(transition_m, transition_v, parent_state_m, parent_state_v)

        return transition_v

Response: Creates a TransitionView from the given transition_m and adds it to the canvas.


Instruction:
Here you have a function in Python 3, explain what it does
def add_data_flow_view_for_model(self, data_flow_m, parent_state_m):
        parent_state_v = self.canvas.get_view_for_model(parent_state_m)

        hierarchy_level = parent_state_v.hierarchy_level
        data_flow_v = DataFlowView(data_flow_m, hierarchy_level)

        # Draw data flow above NameView but beneath all other state elements
        self.canvas.add(data_flow_v, parent_state_v, index=1)
        self._connect_data_flow_to_ports(data_flow_m, data_flow_v, parent_state_m)

Response: Adds a data flow view to the canvas


Instruction:
Can you generate the documentation for the following Python 3 function
def react_to_event(self, event):
        if not react_to_event(self.view, self.view.editor, event):
            return False
        if not rafcon.gui.singleton.state_machine_manager_model.selected_state_machine_id == \
                self.model.state_machine.state_machine_id:
            return False
        return True

Response: Checks whether the given event should be handled by the state machine manager


Instruction:
Write a Python 3 function that can
initialize the Lavalink node.

Response:
async def initialize(bot: Bot, host, password, rest_port, ws_port, timeout=30):
    """
    Initializes the websocket connection to the lavalink player.

    .. important::

        This function must only be called AFTER the bot has received its
        "on_ready" event!

    Parameters
    ----------
    bot : Bot
        An instance of a discord.py `Bot` object.
    host : str
        The hostname or IP address of the Lavalink node.
    password : str
        The password of the Lavalink node.
    rest_port : int
        The port of the REST API on the Lavalink node.
    ws_port : int
        The websocket port on the Lavalink Node.
    timeout : int
        Amount of time to allow retries to occur, ``None`` is considered forever.
    """
    global _loop
    _loop = bot.loop

    player_manager.user_id = bot.user.id
    player_manager.channel_finder_func = bot.get_channel
    register_event_listener(_handle_event)
    register_update_listener(_handle_update)

    lavalink_node = node.Node(
        _loop,
        dispatch,
        bot._connection._get_websocket,
        host,
        password,
        port=ws_port,
        rest=rest_port,
        user_id=player_manager.user_id,
        num_shards=bot.shard_count if bot.shard_count is not None else 1,
    )

    await lavalink_node.connect(timeout=timeout)

    bot.add_listener(node.on_socket_response)
    bot.add_listener(_on_guild_remove, name="on_guild_remove")

    return lavalink_node


Instruction:
Create a Python 3 function for
connecting to a discord voice channel.

Response:
async def connect(channel: discord.VoiceChannel):
    """
    Connects to a discord voice channel.

    This is the publicly exposed way to connect to a discord voice channel.
    The :py:func:`initialize` function must be called first!

    Parameters
    ----------
    channel

    Returns
    -------
    Player
        The created Player object.

    Raises
    ------
    IndexError
        If there are no available lavalink nodes ready to connect to discord.
    """
    node_ = node.get_node(channel.guild.id)
    p = await node_.player_manager.create_player(channel)
    return p


Instruction:
Here you have a function in Python 3, explain what it does
def register_event_listener(coro):
    if not asyncio.iscoroutinefunction(coro):
        raise TypeError("Function is not a coroutine.")

    if coro not in _event_listeners:
        _event_listeners.append(coro)

Response: Registers a coroutine function that will receive lavalink event information.


Instruction:
Write a Python 3 function that can
register a coroutine to receive lavalink player update information.

Response:
def register_update_listener(coro):
    """
    Registers a coroutine to receive lavalink player update information.

    This coroutine will accept a two arguments: an instance of :py:class:`Player`
    and an instance of :py:class:`PlayerState`.

    Parameters
    ----------
    coro

    Raises
    ------
    TypeError
        If ``coro`` is not a coroutine.
    """
    if not asyncio.iscoroutinefunction(coro):
        raise TypeError("Function is not a coroutine.")

    if coro not in _update_listeners:
        _update_listeners.append(coro)


Instruction:
Create a Python 3 function to
register a coroutine to receive lavalink server stats information.

Response:
def register_stats_listener(coro):
    """
    Registers a coroutine to receive lavalink server stats information.

    This coroutine will accept a single argument which will be an instance
    of :py:class:`Stats`.

    Parameters
    ----------
    coro

    Raises
    ------
    TypeError
        If ``coro`` is not a coroutine.
    """
    if not asyncio.iscoroutinefunction(coro):
        raise TypeError("Function is not a coroutine.")

    if coro not in _stats_listeners:
        _stats_listeners.append(coro)


Instruction:
Implement a function in Python 3 to
remove all references to the current model and the current selection and clear the attribute cache.

Response:
def prepare_destruction(self):
        """Get rid of circular references"""
        self._tool = None
        self._painter = None
        self.relieve_model(self._selection)
        self._selection = None
        # clear observer class attributes, also see ExtendenController.destroy()
        self._Observer__PROP_TO_METHS.clear()
        self._Observer__METH_TO_PROPS.clear()
        self._Observer__PAT_TO_METHS.clear()
        self._Observer__METH_TO_PAT.clear()
        self._Observer__PAT_METH_TO_KWARGS.clear()


Instruction:
Can you implement a function in Python 3 that
finds item with port closest to specified position. List of items to be ignored can be specified with `exclude` parameter. Tuple is returned - found item - closest, connectable port - closest point on found port (in view coordinates) :Parameters: vpos Position specified in view coordinates. distance Max distance from point to a port (default 10) exclude Set of items to ignore.

Response:
def get_port_at_point(self, vpos, distance=10, exclude=None, exclude_port_fun=None):
        """
        Find item with port closest to specified position.

        List of items to be ignored can be specified with `exclude`
        parameter.

        Tuple is returned

        - found item
        - closest, connectable port
        - closest point on found port (in view coordinates)

        :Parameters:
         vpos
            Position specified in view coordinates.
         distance
            Max distance from point to a port (default 10)
         exclude
            Set of items to ignore.
        """
        # Method had to be inherited, as the base method has a bug:
        # It misses the statement max_dist = d
        v2i = self.get_matrix_v2i
        vx, vy = vpos

        max_dist = distance
        port = None
        glue_pos = None
        item = None

        rect = (vx - distance, vy - distance, distance * 2, distance * 2)
        items = self.get_items_in_rectangle(rect, reverse=True)
        for i in items:
            if exclude and i in exclude:
                continue
            for p in i.ports():
                if not p.connectable:
                    continue
                if exclude_port_fun and exclude_port_fun(p):
                    continue

                ix, iy = v2i(i).transform_point(vx, vy)
                pg, d = p.glue((ix, iy))
                if d > max_dist:
                    continue

                max_dist = d
                item = i
                port = p

                # transform coordinates from connectable item space to view
                # space
                i2v = self.get_matrix_i2v(i).transform_point
                glue_pos = i2v(*pg)

        return item, port, glue_pos


Instruction:
Can you implement a function in Python 3 that
returns the item at the given position.

Response:
def get_item_at_point_exclude(self, pos, selected=True, exclude=None):
        """
        Return the topmost item located at ``pos`` (x, y).

        Parameters:
         - selected: if False returns first non-selected item
         - exclude: if specified don't check for these items
        """
        items = self._qtree.find_intersect((pos[0], pos[1], 1, 1))
        for item in self._canvas.sort(items, reverse=True):
            if not selected and item in self.selected_items:
                continue  # skip selected items
            if item in exclude:
                continue

            v2i = self.get_matrix_v2i(item)
            ix, iy = v2i.transform_point(*pos)
            if item.point((ix, iy)) < 0.5:
                return item
        return None


Instruction:
Given the following Python 3 function, write the documentation
def queue_draw_item(self, *items):
        gaphas_items = []
        for item in items:
            if isinstance(item, Element):
                gaphas_items.append(item)
            else:
                try:
                    gaphas_items.append(item.parent)
                except AttributeError:
                    pass
        super(ExtendedGtkView, self).queue_draw_item(*gaphas_items)

Response: Extends the base class method to allow Ports to be passed as item