Instruction:
Can you generate a brief explanation for the following Python 3 code
def calc_nearest_point(bus1, network):

    bus1_index = network.buses.index[network.buses.index == bus1]

    forbidden_buses = np.append(
        bus1_index.values, network.lines.bus1[
                network.lines.bus0 == bus1].values)

    forbidden_buses = np.append(
        forbidden_buses, network.lines.bus0[network.lines.bus1 == bus1].values)

    forbidden_buses = np.append(
        forbidden_buses, network.links.bus0[network.links.bus1 == bus1].values)

    forbidden_buses = np.append(
        forbidden_buses, network.links.bus1[network.links.bus0 == bus1].values)

    x0 = network.buses.x[network.buses.index.isin(bus1_index)]

    y0 = network.buses.y[network.buses.index.isin(bus1_index)]

    comparable_buses = network.buses[~network.buses.index.isin(
            forbidden_buses)]

    x1 = comparable_buses.x

    y1 = comparable_buses.y

    distance = (x1.values - x0.values)*(x1.values - x0.values) + \
        (y1.values - y0.values)*(y1.values - y0.values)

    min_distance = distance.min()

    bus0 = comparable_buses[(((x1.values - x0.values)*(x1.values - x0.values
        ) + (y1.values - y0.values)*(y1.values - y0.values)) == min_distance)]
    bus0 = bus0.index[bus0.index == bus0.index.max()]
    bus0 = ''.join(bus0.values)

    return bus0

Response: Function that finds the geographical nearest point in a network from a given bus.


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

        try:
            self._mapped[name] = getattr(self._pkg, self._prefix + name)

        except AttributeError:
            print('Warning: Relation %s does not exist.' % name)

Response: Populate the _mapped attribute with orm class name.


Instruction:
Write a Python 3 function that can
construct a DatetimeIndex with the queried temporal resolution start - and end - snapshot.

Response:
def configure_timeindex(self):
        """ Construct a DateTimeIndex with the queried temporal resolution,
        start- and end_snapshot. """

        try:

            ormclass = self._mapped['TempResolution']
            if self.version:
                tr = self.session.query(ormclass).filter(
                    ormclass.temp_id == self.temp_id).filter(
                        ormclass.version == self.version).one()
            else:
                tr = self.session.query(ormclass).filter(
                    ormclass.temp_id == self.temp_id).one()

        except (KeyError, NoResultFound):
            print('temp_id %s does not exist.' % self.temp_id)

        timeindex = pd.DatetimeIndex(start=tr.start_time,
                                     periods=tr.timesteps,
                                     freq=tr.resolution)

        self.timeindex = timeindex[self.start_snapshot - 1: self.end_snapshot]
        """ pandas.tseries.index.DateTimeIndex :
                Index of snapshots or timesteps. """


Instruction:
Can you implement a function in Python 3 that
fetches DataFrame with component data from filtered table data.

Response:
def fetch_by_relname(self, name):
        """ Construct DataFrame with component data from filtered table data.

        Parameters
        ----------
        name : str
            Component name.

        Returns
        -------
        pd.DataFrame
            Component data.
        """

        ormclass = self._mapped[name]
        query = self.session.query(ormclass)

        if name != carr_ormclass:

            query = query.filter(
                ormclass.scn_name == self.scn_name)

        if self.version:
            query = query.filter(ormclass.version == self.version)

        # TODO: Naming is not consistent. Change in database required.
        if name == 'Transformer':
            name = 'Trafo'

        df = pd.read_sql(query.statement,
                         self.session.bind,
                         index_col=name.lower() + '_id')
        if name == 'Link':
            df['bus0'] = df.bus0.astype(int)
            df['bus1'] = df.bus1.astype(int)

        if 'source' in df:
            df.source = df.source.map(self.id_to_source())

        return df


Instruction:
Write a Python 3 script to
fetch series data from filtered by component name and column.

Response:
def series_fetch_by_relname(self, name, column):
        """ Construct DataFrame with component timeseries data from filtered
        table data.

        Parameters
        ----------
        name : str
            Component name.
        column : str
            Component field with timevarying data.

        Returns
        -------
        pd.DataFrame
            Component data.
        """

        ormclass = self._mapped[name]

        # TODO: This is implemented in a not very robust way.
        id_column = re.findall(r'[A-Z][^A-Z]*', name)[0] + '_' + 'id'
        id_column = id_column.lower()

        query = self.session.query(
            getattr(ormclass, id_column),
            getattr(ormclass, column)[self.start_snapshot: self.end_snapshot].
            label(column)).filter(and_(
                ormclass.scn_name == self.scn_name,
                ormclass.temp_id == self.temp_id))

        if self.version:
            query = query.filter(ormclass.version == self.version)

        df = pd.io.sql.read_sql(query.statement,
                                self.session.bind,
                                columns=[column],
                                index_col=id_column)

        df.index = df.index.astype(str)

        # change of format to fit pypsa
        df = df[column].apply(pd.Series).transpose()

        try:
            assert not df.empty
            df.index = self.timeindex
        except AssertionError:
            print("No data for %s in column %s." % (name, column))

        return df


Instruction:
How would you explain what the following Python 3 function does
def build_network(self, network=None, *args, **kwargs):
        # TODO: build_network takes care of divergences in database design and
        # future PyPSA changes from PyPSA's v0.6 on. This concept should be
        # replaced, when the oedb has a revision system in place, because
        # sometime this will break!!!

        if network != None:
            network = network

        else:
            network = pypsa.Network()
            network.set_snapshots(self.timeindex)

        timevarying_override = False

        if pypsa.__version__ == '0.11.0':
            old_to_new_name = {'Generator':
                               {'p_min_pu_fixed': 'p_min_pu',
                                'p_max_pu_fixed': 'p_max_pu',
                                'source': 'carrier',
                                'dispatch': 'former_dispatch'},
                               'Bus':
                               {'current_type': 'carrier'},
                               'Transformer':
                               {'trafo_id': 'transformer_id'},
                               'Storage':
                               {'p_min_pu_fixed': 'p_min_pu',
                                'p_max_pu_fixed': 'p_max_pu',
                                'soc_cyclic': 'cyclic_state_of_charge',
                                'soc_initial': 'state_of_charge_initial',
                                'source': 'carrier'}}

            timevarying_override = True

        else:

            old_to_new_name = {'Storage':
                               {'soc_cyclic': 'cyclic_state_of_charge',
                                'soc_initial': 'state_of_charge_initial'}}

        for comp, comp_t_dict in self.config.items():

            # TODO: This is confusing, should be fixed in db
            pypsa_comp_name = 'StorageUnit' if comp == 'Storage' else comp

            df = self.fetch_by_relname(comp)

            if comp in old_to_new_name:

                tmp = old_to_new_name[comp]
                df.rename(columns=tmp, inplace=True)

            network.import_components_from_dataframe(df, pypsa_comp_name)

            if comp_t_dict:

                for comp_t, columns in comp_t_dict.items():

                    for col in columns:

                        df_series = self.series_fetch_by_relname(comp_t, col)

                        # TODO: VMagPuSet is not implemented.
                        if timevarying_override and comp == 'Generator' \
                        and not df_series.empty:
                            idx = df[df.former_dispatch == 'flexible'].index
                            idx = [i for i in idx if i in df_series.columns]
                            df_series.drop(idx, axis=1, inplace=True)

                        try:

                            pypsa.io.import_series_from_dataframe(
                                network,
                                df_series,
                                pypsa_comp_name,
                                col)

                        except (ValueError, AttributeError):
                            print("Series %s of component %s could not be "
                                  "imported" % (col, pypsa_comp_name))

        # populate carrier attribute in PyPSA network
        network.import_components_from_dataframe(
            self.fetch_by_relname(carr_ormclass), 'Carrier')

        self.network = network

        return network

Response: Build a PyPSA Network object.


Instruction:
Make a summary of the following Python 3 code
def run(self):
        logger.debug("Starting execution of {0}{1}".format(self, " (backwards)" if self.backward_execution else ""))
        self.setup_run()

        try:
            concurrency_history_item = self.setup_forward_or_backward_execution()
            concurrency_queue = self.start_child_states(concurrency_history_item)

            #######################################################
            # wait for the first threads to finish
            #######################################################
            finished_thread_id = concurrency_queue.get()
            finisher_state = self.states[finished_thread_id]
            finisher_state.join()

            # preempt all child states
            if not self.backward_execution:
                for state_id, state in self.states.items():
                    state.recursively_preempt_states()
            # join all states
            for history_index, state in enumerate(self.states.values()):
                self.join_state(state, history_index, concurrency_history_item)
                self.add_state_execution_output_to_scoped_data(state.output_data, state)
                self.update_scoped_variables_with_output_dictionary(state.output_data, state)

            # add the data of the first state now to overwrite data of the preempted states
            self.add_state_execution_output_to_scoped_data(finisher_state.output_data, finisher_state)
            self.update_scoped_variables_with_output_dictionary(finisher_state.output_data, finisher_state)
            #######################################################
            # handle backward execution case
            #######################################################
            if self.states[finished_thread_id].backward_execution:
                return self.finalize_backward_execution()

            else:
                self.backward_execution = False

            #######################################################
            # handle no transition
            #######################################################
            transition = self.get_transition_for_outcome(self.states[finished_thread_id],
                                                         self.states[finished_thread_id].final_outcome)
            if transition is None:
                # final outcome is set here
                transition = self.handle_no_transition(self.states[finished_thread_id])
            # it the transition is still None, then the state was preempted or aborted, in this case return
            if transition is None:
                self.output_data["error"] = RuntimeError("state aborted")
            else:
                if 'error' in self.states[finished_thread_id].output_data:
                    self.output_data["error"] = self.states[finished_thread_id].output_data['error']
                self.final_outcome = self.outcomes[transition.to_outcome]

            return self.finalize_concurrency_state(self.final_outcome)

        except Exception as e:
            logger.error("{0} had an internal error: {1}\n{2}".format(self, str(e), str(traceback.format_exc())))
            self.output_data["error"] = e
            self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE
            return self.finalize(Outcome(-1, "aborted"))

Response: This method starts the concurrency state execution process


Instruction:
Can you tell what is the following Python 3 function doing
def _check_transition_validity(self, check_transition):
        valid, message = super(PreemptiveConcurrencyState, self)._check_transition_validity(check_transition)
        if not valid:
            return False, message

        # Only transitions to the parent state are allowed

        if check_transition.to_state != self.state_id:
            return False, "Only transitions to the parent state are allowed"

        return True, message

Response: Check validity of a transition of BarrierConcurrencyState.


Instruction:
How would you implement a function in Python 3 that
prepares the model for destruction Unregisters itself from the state machine and the root state machine and the modification history.

Response:
def prepare_destruction(self):
        """Prepares the model for destruction

        Un-registers itself as observer from the state machine and the root state
        """
        try:
            self.relieve_model(self.state_machine_model)
            assert self.__buffered_root_state_model is self.state_machine_model.root_state
            self.relieve_model(self.__buffered_root_state_model)
            self.state_machine_model = None
            self.__buffered_root_state_model = None
            self.modifications.prepare_destruction()
        except KeyError:  # Might happen if the observer was already unregistered
            pass
        if self.active_action:
            try:
                self.active_action.prepare_destruction()
            except Exception as e:
                logger.exception("The modification history has had left over an active-action and "
                                 "could not destroy it {0}.".format(e))
            self.active_action = None


Instruction:
Implement a function in Python 3 to
recover a specific version of the all_time_history element by doing several undos and redos.

Response:
def recover_specific_version(self, pointer_on_version_to_recover):
        """ Recovers a specific version of the all_time_history element by doing several undos and redos.

        :param pointer_on_version_to_recover: the id of the list element which is to recover
        :return:
        """
        # search for traceable path -> list of action to undo and list of action to redo
        logger.info("Going to history status #{0}".format(pointer_on_version_to_recover))
        undo_redo_list = self.modifications.get_undo_redo_list_from_active_trail_history_item_to_version_id(pointer_on_version_to_recover)
        logger.debug("Multiple undo and redo to reach modification history element of version {0} "
                     "-> undo-redo-list is: {1}".format(pointer_on_version_to_recover, undo_redo_list))
        # logger.debug("acquire lock 1 - for multiple action {0}".format(self.modifications.trail_pointer))
        self.state_machine_model.storage_lock.acquire()
        # logger.debug("acquired lock 1 - for multiple action {0}".format(self.modifications.trail_pointer))
        for elem in undo_redo_list:
            if elem[1] == 'undo':
                # do undo
                self._undo(elem[0])
            else:
                # do redo
                self._redo(elem[0])

        self.modifications.reorganize_trail_history_for_version_id(pointer_on_version_to_recover)
        self.change_count += 1
        # logger.debug("release lock 1 - for multiple action {0}".format(self.modifications.trail_pointer))
        self.state_machine_model.storage_lock.release()


Instruction:
Write a Python 3 script to
perform fast search from currently active branch to specific version_id and collect all recovery steps.

Response:
def get_undo_redo_list_from_active_trail_history_item_to_version_id(self, version_id):
        """Perform fast search from currently active branch to specific version_id and collect all recovery steps.
        """
        all_trail_action = [a.version_id for a in self.single_trail_history() if a is not None]
        all_active_action = self.get_all_active_actions()
        undo_redo_list = []
        _undo_redo_list = []

        intermediate_version_id = version_id
        if self.with_verbose:
            logger.verbose("Version_id    : {0} in".format(intermediate_version_id))
            logger.verbose("Active actions: {0} in: {1}".format(all_active_action,
                                                                intermediate_version_id in all_active_action))
            logger.verbose("Trail actions : {0} in: {1}".format(all_trail_action,
                                                                intermediate_version_id in all_trail_action))

        if intermediate_version_id not in all_trail_action:
            # get undo to come from version_id to trail_action
            while intermediate_version_id not in all_trail_action:
                _undo_redo_list.insert(0, (intermediate_version_id, 'redo'))
                intermediate_version_id = self.all_time_history[intermediate_version_id].prev_id
            intermediate_goal_version_id = intermediate_version_id
        else:
            intermediate_goal_version_id = version_id
        intermediate_version_id = self.trail_history[self.trail_pointer].version_id
        if self.with_verbose:
            logger.verbose("Version_id    : {0} {1}".format(intermediate_goal_version_id, intermediate_version_id))
            logger.verbose("Active actions: {0} in: {1}".format(all_active_action,
                                                                intermediate_version_id in all_active_action))
            logger.verbose("Trail actions : {0} in: {1}".format(all_trail_action,
                                                                intermediate_version_id in all_trail_action))

        # collect undo and redo on trail
        if intermediate_goal_version_id in all_active_action:
            # collect needed undo to reach intermediate version
            while not intermediate_version_id == intermediate_goal_version_id:
                undo_redo_list.append((intermediate_version_id, 'undo'))
                intermediate_version_id = self.all_time_history[intermediate_version_id].prev_id

        elif intermediate_goal_version_id in all_trail_action:
            # collect needed redo to reach intermediate version
            while not intermediate_version_id == intermediate_goal_version_id:
                intermediate_version_id = self.all_time_history[intermediate_version_id].next_id
                undo_redo_list.append((intermediate_version_id, 'redo'))

        for elem in _undo_redo_list:
            undo_redo_list.append(elem)

        return undo_redo_list


Instruction:
Implement a Python 3 function for
adjusting the position of a GTK Pane to a value stored in the runtime config file.

Response:
def set_pane_position(self, config_id):
        """Adjusts the position of a GTK Pane to a value stored in the runtime config file. If there was no value
        stored, the pane's position is set to a default value.

        :param config_id: The pane identifier saved in the runtime config file
        """
        default_pos = constants.DEFAULT_PANE_POS[config_id]
        position = global_runtime_config.get_config_value(config_id, default_pos)
        pane_id = constants.PANE_ID[config_id]
        self.view[pane_id].set_position(position)


Instruction:
Implement a Python 3 function for
highlighting buttons according actual execution status.

Response:
def model_changed(self, model, prop_name, info):
        """ Highlight buttons according actual execution status. Furthermore it triggers the label redraw of the active
        state machine.
        """

        # TODO: find nice solution
        # this in only required if the GUI is terminated via Ctrl+C signal
        if not self.view:
            # this means that the main window is currently under destruction
            return

        execution_engine = rafcon.core.singleton.state_machine_execution_engine
        label_string = str(execution_engine.status.execution_mode)
        label_string = label_string.replace("STATE_MACHINE_EXECUTION_STATUS.", "")
        self.view['execution_status_label'].set_text(label_string)

        current_execution_mode = execution_engine.status.execution_mode
        if current_execution_mode is StateMachineExecutionStatus.STARTED:
            self.view['step_buttons'].hide()
            self._set_single_button_active('button_start_shortcut')
        elif current_execution_mode is StateMachineExecutionStatus.PAUSED:
            self.view['step_buttons'].hide()
            self._set_single_button_active('button_pause_shortcut')
        elif execution_engine.finished_or_stopped():
            self.view['step_buttons'].hide()
            self._set_single_button_active('button_stop_shortcut')
        else:  # all step modes
            self.view['step_buttons'].show()
            self._set_single_button_active('button_step_mode_shortcut')


Instruction:
Write a Python 3 script to
put the focus on the given child controller.

Response:
def focus_notebook_page_of_controller(self, controller):
        """Puts the focus on the given child controller

        The method implements focus request of the notebooks in left side-bar of the main window. Thereby it is the
        master-function of focus pattern of the notebooks in left side-bar.

        Actual pattern is:
        * Execution-History is put to focus any time requested (request occur at the moment when the state-machine
        is started and stopped.
        * Modification-History one time focused while and one time after execution if requested.

        :param controller The controller which request to be focused.
        """
        # TODO think about to may substitute Controller- by View-objects it is may the better design
        if controller not in self.get_child_controllers():
            return
        # logger.info("focus controller {0}".format(controller))
        if not self.modification_history_was_focused and isinstance(controller, ModificationHistoryTreeController) and \
                self.view is not None:
            self.view.bring_tab_to_the_top('history')
            self.modification_history_was_focused = True

        if self.view is not None and isinstance(controller, ExecutionHistoryTreeController):
            self.view.bring_tab_to_the_top('execution_history')
            self.modification_history_was_focused = False


Instruction:
Write a Python 3 script to
trigger whenever a left - bar notebook tab is changed.

Response:
def on_notebook_tab_switch(self, notebook, page, page_num, title_label, window, notebook_identifier):
        """Triggered whenever a left-bar notebook tab is changed.

        Updates the title of the corresponding notebook and updates the title of the left-bar window in case un-docked.

        :param notebook: The GTK notebook where a tab-change occurred
        :param page_num: The page number of the currently-selected tab
        :param title_label: The label holding the notebook's title
        :param window: The left-bar window, for which the title should be changed
        :param notebook_identifier: A string identifying whether the notebook is the upper or the lower one
        """
        title = gui_helper_label.set_notebook_title(notebook, page_num, title_label)
        window.reset_title(title, notebook_identifier)
        self.on_switch_page_check_collapse_button(notebook, page_num)


Instruction:
Can you tell what is the following Python 3 function doing
def _on_key_press(self, widget, event):
        self.currently_pressed_keys.add(event.keyval)
        if event.keyval in [Gdk.KEY_Tab, Gdk.KEY_ISO_Left_Tab] and event.state & Gdk.ModifierType.CONTROL_MASK:
            self.toggle_sidebars()

Response: Updates the currently pressed keys


Instruction:
Implement a function in Python 3 to
save the current configuration of windows panes and state machines to the runtime config file before RAFCON is closed.

Response:
def prepare_destruction(self):
        """Saves current configuration of windows and panes to the runtime config file, before RAFCON is closed."""
        plugins.run_hook("pre_destruction")

        logger.debug("Saving runtime config to {0}".format(global_runtime_config.config_file_path))

        # store pane last positions
        for key, widget_name in constants.PANE_ID.items():
            global_runtime_config.store_widget_properties(self.view[widget_name], key.replace('_POS', ''))

        # store hidden or undocked widget flags correctly -> make them independent for restoring
        for window_key in constants.UNDOCKABLE_WINDOW_KEYS:
            hidden = False
            if not global_runtime_config.get_config_value(window_key + "_WINDOW_UNDOCKED"):
                hidden = getattr(self, window_key.lower() + '_hidden')
            global_runtime_config.set_config_value(window_key + '_HIDDEN', hidden)

        global_runtime_config.save_configuration()

        # state-editor will relieve it's model => it won't observe the state machine manager any more
        self.get_controller('states_editor_ctrl').prepare_destruction()  # avoid new state editor TODO tbd (deleted)
        rafcon.core.singleton.state_machine_manager.delete_all_state_machines()
        rafcon.core.singleton.library_manager.prepare_destruction()

        # gtkmvc installs a global glade custom handler that holds a reference to the last created View class,
        # preventing it from being destructed. By installing a dummy callback handler, after all views have been
        # created, the old handler is being removed and with it the reference, allowing all Views to be destructed.

        # Gtk TODO: check if necessary and search for replacement
        # try:
        #     from gtk import glade
        #     def dummy(*args, **kwargs):
        #         pass
        #     glade.set_custom_handler(dummy)
        # except ImportError:
        #     pass

        # Recursively destroys the main window
        self.destroy()
        from rafcon.gui.clipboard import global_clipboard
        global_clipboard.destroy()
        gui_singletons.main_window_controller = None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def setup_forward_or_backward_execution(self):
        if self.backward_execution:
            # pop the return item of this concurrency state to get the correct scoped data
            last_history_item = self.execution_history.pop_last_item()
            assert isinstance(last_history_item, ReturnItem)
            self.scoped_data = last_history_item.scoped_data
            # get the concurrency item for the children execution historys
            concurrency_history_item = self.execution_history.get_last_history_item()
            assert isinstance(concurrency_history_item, ConcurrencyItem)

        else:  # forward_execution
            self.execution_history.push_call_history_item(self, CallType.CONTAINER, self, self.input_data)
            concurrency_history_item = self.execution_history.push_concurrency_history_item(self, len(self.states))
        return concurrency_history_item

Response: Sets up the execution of the concurrency states dependent on if the state is executed forward of backward.


Instruction:
Explain what the following Python 3 code does
def finalize_concurrency_state(self, outcome):
        final_outcome = outcome
        self.write_output_data()
        self.check_output_data_type()
        self.execution_history.push_return_history_item(self, CallType.CONTAINER, self, self.output_data)
        self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE

        singleton.state_machine_execution_engine._modify_run_to_states(self)

        if self.preempted:
            final_outcome = Outcome(-2, "preempted")
        return self.finalize(final_outcome)

Response: This function is called by the concurrency state machine when the concurrency state is complete.


Instruction:
Given the following Python 3 function, write the documentation
def _head_length(self, port):
        if not port:
            return 0.
        parent_state_v = self.get_parent_state_v()
        if parent_state_v is port.parent:  # port of connection's parent state
            return port.port_size[1]
        return max(port.port_size[1] * 1.5, self._calc_line_width() / 1.3)

Response: Return the length of the head of the port.


Instruction:
Can you implement a function in Python 3 that
calls when the View was registered

Response:
def register_view(self, view):
        """Called when the View was registered"""
        super(DataPortListController, self).register_view(view)

        view['name_col'].add_attribute(view['name_text'], 'text', self.NAME_STORAGE_ID)
        view['data_type_col'].add_attribute(view['data_type_text'], 'text', self.DATA_TYPE_NAME_STORAGE_ID)
        if not isinstance(self.model.state, LibraryState) and self.model.state.get_next_upper_library_root_state() is None:
            view['name_text'].set_property("editable", True)
            view['data_type_text'].set_property("editable", True)

        # in the linkage overview the the default value is not shown
        if isinstance(view, InputPortsListView) or isinstance(view, OutputPortsListView):
            view['default_value_col'].add_attribute(view['default_value_text'], 'text', self.DEFAULT_VALUE_STORAGE_ID)
            self._apply_value_on_edited_and_focus_out(view['default_value_text'], self._apply_new_data_port_default_value)
            view['default_value_col'].set_cell_data_func(view['default_value_text'],
                                                         self._default_value_cell_data_func)
            if isinstance(self.model.state, LibraryState):
                view['default_value_col'].set_title("Used value")
            if self.model.state.get_next_upper_library_root_state() is None:  # never enabled means it is disabled
                view['default_value_text'].set_property("editable", True)

        self._apply_value_on_edited_and_focus_out(view['name_text'], self._apply_new_data_port_name)
        self._apply_value_on_edited_and_focus_out(view['data_type_text'], self._apply_new_data_port_type)

        if isinstance(self.model.state, LibraryState):
            view['use_runtime_value_toggle'] = Gtk.CellRendererToggle()
            view['use_runtime_value_col'] = Gtk.TreeViewColumn("Use Runtime Value")
            view['use_runtime_value_col'].set_property("sizing", Gtk.TreeViewColumnSizing.AUTOSIZE)
            view.get_top_widget().append_column(view['use_runtime_value_col'])
            view['use_runtime_value_col'].pack_start(view['use_runtime_value_toggle'], True)
            view['use_runtime_value_col'].add_attribute(view['use_runtime_value_toggle'], 'active',
                                                        self.USE_RUNTIME_VALUE_STORAGE_ID)
            if self.model.state.get_next_upper_library_root_state() is None:
                view['use_runtime_value_toggle'].set_property("activatable", True)
                view['use_runtime_value_toggle'].connect("toggled", self.on_use_runtime_value_toggled)

        self._reload_data_port_list_store()


Instruction:
How would you implement a function in Python 3 that
tries to set the use runtime value flag to the newly entered one

Response:
def on_use_runtime_value_toggled(self, widget, path):
        """Try to set the use runtime value flag to the newly entered one
        """
        try:
            data_port_id = self.list_store[path][self.ID_STORAGE_ID]
            self.toggle_runtime_value_usage(data_port_id)
        except TypeError as e:
            logger.exception("Error while trying to change the use_runtime_value flag")


Instruction:
Can you generate the documentation for the following Python 3 function
def _default_value_cell_data_func(self, tree_view_column, cell, model, iter, data=None):
        if isinstance(self.model.state, LibraryState):
            use_runtime_value = model.get_value(iter, self.USE_RUNTIME_VALUE_STORAGE_ID)
            if use_runtime_value:
                cell.set_property("editable", True)
                cell.set_property('text', model.get_value(iter, self.RUNTIME_VALUE_STORAGE_ID))
                cell.set_property('foreground', "white")
            else:
                cell.set_property("editable", False)
                cell.set_property('text', model.get_value(iter, self.DEFAULT_VALUE_STORAGE_ID))
                cell.set_property('foreground', "dark grey")

        return

Response: Function set renderer properties for every single cell independently


Instruction:
Can you create a Python 3 function that
reloads the input data port list store from the data port models

Response:
def _reload_data_port_list_store(self):
        """Reloads the input data port list store from the data port models"""

        tmp = self._get_new_list_store()
        for data_port_m in self.data_port_model_list:
            data_port_id = data_port_m.data_port.data_port_id
            data_type = data_port_m.data_port.data_type
            # get name of type (e.g. ndarray)
            data_type_name = data_type.__name__
            # get module of type, e.g. numpy
            data_type_module = data_type.__module__
            # if the type is not a builtin type, also show the module
            if data_type_module not in ['__builtin__', 'builtins']:
                data_type_name = data_type_module + '.' + data_type_name
            if data_port_m.data_port.default_value is None:
                default_value = "None"
            else:
                default_value = data_port_m.data_port.default_value

            if not isinstance(self.model.state, LibraryState):
                tmp.append([data_port_m.data_port.name, data_type_name, str(default_value), data_port_id,
                            None, None, data_port_m])
            else:
                use_runtime_value, runtime_value = self.get_data_port_runtime_configuration(data_port_id)
                tmp.append([data_port_m.data_port.name,
                            data_type_name,
                            str(default_value),
                            data_port_id,
                            bool(use_runtime_value),
                            str(runtime_value),
                            data_port_m,
                            ])

        tms = Gtk.TreeModelSort(model=tmp)
        tms.set_sort_column_id(0, Gtk.SortType.ASCENDING)
        tms.set_sort_func(0, compare_variables)
        tms.sort_column_changed()
        tmp = tms
        self.list_store.clear()
        for elem in tmp:
            self.list_store.append(elem[:])


Instruction:
Write a Python 3 script for
applying the new name of the data port defined by path to the state data port.

Response:
def _apply_new_data_port_name(self, path, new_name):
        """Applies the new name of the data port defined by path

        :param str path: The path identifying the edited data port
        :param str new_name: New name
        """
        try:
            data_port_id = self.list_store[path][self.ID_STORAGE_ID]
            if self.state_data_port_dict[data_port_id].name != new_name:
                self.state_data_port_dict[data_port_id].name = new_name
        except (TypeError, ValueError) as e:
            logger.exception("Error while trying to change data port name")


Instruction:
Write a Python 3 function for
applying the new data type of the data port defined by path

Response:
def _apply_new_data_port_type(self, path, new_data_type_str):
        """Applies the new data type of the data port defined by path

        :param str path: The path identifying the edited data port
        :param str new_data_type_str: New data type as str
        """
        try:
            data_port_id = self.list_store[path][self.ID_STORAGE_ID]
            if self.state_data_port_dict[data_port_id].data_type.__name__ != new_data_type_str:
                self.state_data_port_dict[data_port_id].change_data_type(new_data_type_str)
        except ValueError as e:
            logger.exception("Error while changing data type")


Instruction:
Create a Python 3 function to
apply the new default value of the data port defined by path

Response:
def _apply_new_data_port_default_value(self, path, new_default_value_str):
        """Applies the new default value of the data port defined by path

        :param str path: The path identifying the edited variable
        :param str new_default_value_str: New default value as string
        """
        try:
            data_port_id = self.list_store[path][self.ID_STORAGE_ID]
            if isinstance(self.model.state, LibraryState):
                # this always has to be true, as the runtime value column can only be edited
                # if the use_runtime_value flag is True
                if self.list_store[path][self.USE_RUNTIME_VALUE_STORAGE_ID]:
                    self.set_data_port_runtime_value(data_port_id, new_default_value_str)
            else:
                if str(self.state_data_port_dict[data_port_id].default_value) != new_default_value_str:
                    self.state_data_port_dict[data_port_id].default_value = new_default_value_str
        except (TypeError, AttributeError) as e:
            logger.exception("Error while changing default value")


Instruction:
Here you have a function in Python 3, explain what it does
def _data_ports_changed(self, model):
        if not isinstance(model, AbstractStateModel):
            return
        # store port selection
        path_list = None
        if self.view is not None:
            model, path_list = self.tree_view.get_selection().get_selected_rows()
        selected_data_port_ids = [self.list_store[path[0]][self.ID_STORAGE_ID] for path in path_list] if path_list else []
        self._reload_data_port_list_store()
        # recover port selection
        if selected_data_port_ids:
            [self.select_entry(selected_data_port_id, False) for selected_data_port_id in selected_data_port_ids]

Response: Reload list store and reminds selection when the model was changed


Instruction:
How would you implement a function in Python 3 that
handles cases for the library runtime values

Response:
def runtime_values_changed(self, model, prop_name, info):
        """Handle cases for the library runtime values"""
        if ("_input_runtime_value" in info.method_name or
                info.method_name in ['use_runtime_value_input_data_ports',
                                     'input_data_port_runtime_values']) and \
                self.model is model:
            self._data_ports_changed(model)


Instruction:
Write a Python 3 function that can
add a new data port with default values and select it

Response:
def add_new_data_port(self):
        """Add a new port with default values and select it"""
        try:
            new_data_port_ids = gui_helper_state_machine.add_data_port_to_selected_states('OUTPUT', int, [self.model])
            if new_data_port_ids:
                self.select_entry(new_data_port_ids[self.model.state])
        except ValueError:
            pass


Instruction:
Given the following Python 3 function, write the documentation
def add_callback_for_action(self, action, callback):
        if hasattr(callback, '__call__'):  # Is the callback really a function?
            if action not in self.__action_to_callbacks:
                self.__action_to_callbacks[action] = []
            self.__action_to_callbacks[action].append(callback)

            controller = None
            try:
                controller = callback.__self__
            except AttributeError:
                try:
                    # Needed when callback was wrapped using functools.partial
                    controller = callback.func.__self__
                except AttributeError:
                    pass

            if controller:
                if controller not in self.__controller_action_callbacks:
                    self.__controller_action_callbacks[controller] = {}
                if action not in self.__controller_action_callbacks[controller]:
                    self.__controller_action_callbacks[controller][action] = []
                self.__controller_action_callbacks[controller][action].append(callback)

            return True

Response: Adds a callback function to an action.


Instruction:
Given the following Python 3 function, write the documentation
def remove_callback_for_action(self, action, callback):
        if action in self.__action_to_callbacks:
            if callback in self.__action_to_callbacks[action]:
                self.__action_to_callbacks[action].remove(callback)

Response: Remove a callback for a specific action


Instruction:
Make a summary of the following Python 3 code
def trigger_action(self, action, key_value, modifier_mask):
        res = False
        if action in self.__action_to_callbacks:
            for callback_function in self.__action_to_callbacks[action]:
                try:
                    ret = callback_function(key_value, modifier_mask)
                    # If at least one controller returns True, the whole result becomes True
                    res |= (False if ret is None else ret)
                except Exception as e:
                    logger.exception('Exception while calling callback methods for action "{0}": {1}'.format(action, e))
        return res

Response: Calls the appropriate callback function(s) for the given action and returns a boolean indicating whether a callback was triggered.


Instruction:
Here you have a function in Python 3, explain what it does
def check_info_on_no_update_flags(self, info):
        # TODO that could need a second clean up
        # avoid updates because of state destruction
        if 'before' in info and info['method_name'] == "remove_state":
            if info.instance is self.model.state:
                self.no_update_state_destruction = True
            else:
                # if the state it self is removed lock the widget to never run updates and relieve all models
                removed_state_id = info.args[1] if len(info.args) > 1 else info.kwargs['state_id']
                if removed_state_id == self.model.state.state_id or \
                        not self.model.state.is_root_state and removed_state_id == self.model.parent.state.state_id:
                    self.no_update_self_or_parent_state_destruction = True
                    self.relieve_all_models()

        elif 'after' in info and info['method_name'] == "remove_state":
            if info.instance.state_id == self.model.state.state_id:
                self.no_update_state_destruction = False

        # reduce NotificationOverview generations by the fact that after could cause False and before could cause True
        if not self.no_update_state_destruction and not self.no_update_self_or_parent_state_destruction and \
                (not self.no_update and 'before' in info or 'after' in info and self.no_update):
            return
        overview = NotificationOverview(info, False, self.__class__.__name__)

        # The method causing the change raised an exception, thus nothing was changed and updates are allowed
        if 'after' in info and isinstance(overview['result'][-1], Exception):
            self.no_update = False
            self.no_update_state_destruction = False
            # self.no_update_self_or_parent_state_destruction = False
            return

        if overview['method_name'][-1] in ['group_states', 'ungroup_state', "change_state_type",
                                           "change_root_state_type"]:
            instance_is_self = self.model.state is overview['instance'][-1]
            instance_is_parent = self.model.parent and self.model.parent.state is overview['instance'][-1]
            instance_is_parent_parent = self.model.parent and self.model.parent.parent and self.model.parent.parent.state is overview['instance'][-1]
            # print("no update flag: ", True if 'before' in info and (instance_is_self or instance_is_parent or instance_is_parent_parent) else False)
            if instance_is_self or instance_is_parent or instance_is_parent_parent:
                self.no_update = True if 'before' in info else False

            if overview['prop_name'][-1] == 'state' and overview['method_name'][-1] in ["change_state_type"] and \
                    self.model.get_state_machine_m() is not None:
                changed_model = self.model.get_state_machine_m().get_state_model_by_path(overview['args'][-1][1].get_path())
                if changed_model not in self._model_observed:
                    self.observe_model(changed_model)

Response: Stop updates while multi - actions are allowed


Instruction:
Can you tell what is the following Python 3 function doing
def before_notification_state_machine_observation_control(self, model, prop_name, info):
        if is_execution_status_update_notification_from_state_machine_model(prop_name, info):
            return
        # do not update while multi-actions
        self.check_info_on_no_update_flags(info)

Response: Check for multi - actions and set respective no update flags.


Instruction:
Can you generate the documentation for the following Python 3 function
def store_value(self, name, value, parameters=None):
        if not isinstance(parameters, dict):
            raise TypeError("parameters must be a dict")
        hash = self._parameter_hash(parameters)
        if name not in self._cache:
            self._cache[name] = {}
        self._cache[name][hash.hexdigest()] = value

Response: Stores the value of a certain variable with name with the given value and parameters.


Instruction:
How would you explain what the following Python 3 function does
def get_value(self, name, parameters=None):
        if not isinstance(parameters, dict):
            raise TypeError("parameters must a dict")
        if name not in self._cache:
            return None
        hash = self._parameter_hash(parameters)
        hashdigest = hash.hexdigest()
        return self._cache[name].get(hashdigest, None)

Response: Return the value of a cached variable if applicable


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _normalize_number_values(self, parameters):
        for key, value in parameters.items():
            if isinstance(value, (int, float)):
                parameters[key] = str(Decimal(value).normalize(self._context))

Response: Assures equal precision for all number values


Instruction:
Here you have a function in Python 3, explain what it does
def register_view(self, view):
        super(AbstractTreeViewController, self).register_view(view)
        self.signal_handlers.append((self._tree_selection,
                                     self._tree_selection.connect('changed', self.selection_changed)))
        # self.handler_ids.append((self.tree_view,
        #                          self.tree_view.connect('key-press-event', self.tree_view_keypress_callback)))
        self.tree_view.connect('key-release-event', self.on_key_release_event)
        self.tree_view.connect('button-release-event', self.tree_view_keypress_callback)
        # key press is needed for tab motion but needs to be registered already here TODO why?
        self.tree_view.connect('key-press-event', self.tree_view_keypress_callback)
        self._tree_selection.set_mode(Gtk.SelectionMode.MULTIPLE)
        self.update_selection_sm_prior()

Response: Register callbacks for button press events and selection changed


Instruction:
Implement a Python 3 function for
getting actual tree selection object and all respective models of selected rows

Response:
def get_view_selection(self):
        """Get actual tree selection object and all respective models of selected rows"""
        if not self.MODEL_STORAGE_ID:
            return None, None

        # avoid selection requests on empty tree views -> case warnings in gtk3
        if len(self.store) == 0:
            paths = []
        else:
            model, paths = self._tree_selection.get_selected_rows()

        # get all related models for selection from respective tree store field
        selected_model_list = []
        for path in paths:
            model = self.store[path][self.MODEL_STORAGE_ID]
            selected_model_list.append(model)
        return self._tree_selection, selected_model_list


Instruction:
Can you generate the documentation for the following Python 3 function
def get_selections(self):
        sm_selection, sm_filtered_selected_model_set = self.get_state_machine_selection()
        tree_selection, selected_model_list = self.get_view_selection()
        return tree_selection, selected_model_list, sm_selection, sm_filtered_selected_model_set

Response: Get current model selection status in state machine selection and view selection of the widget


Instruction:
Can you write a function in Python 3 where it
notifies tree view about state machine selection

Response:
def state_machine_selection_changed(self, state_machine_m, signal_name, signal_msg):
        """Notify tree view about state machine selection"""
        if self.CORE_ELEMENT_CLASS in signal_msg.arg.affected_core_element_classes:
            self.update_selection_sm_prior()


Instruction:
Make a summary of the following Python 3 code
def add_action_callback(self, *event):
        if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None:
            self.on_add(None)
            return True

Response: Callback method for add action


Instruction:
Can you generate a brief explanation for the following Python 3 code
def cut_action_callback(self, *event):
        if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None:
            sm_selection, sm_selected_model_list = self.get_state_machine_selection()
            # only list specific elements are cut by widget
            if sm_selection is not None:
                sm_selection.set(sm_selected_model_list)
                global_clipboard.cut(sm_selection)
                return True

Response: Callback method for cut action


Instruction:
Can you generate the documentation for the following Python 3 function
def _apply_value_on_edited_and_focus_out(self, renderer, apply_method):
        assert isinstance(renderer, Gtk.CellRenderer)

        def remove_all_handler(renderer):
            """Remove all handler for given renderer and its editable

            :param renderer: Renderer of the respective column which is edit by a entry widget, at the moment
            """
            def remove_handler(widget, data_name):
                """Remove handler from given widget

                :param Gtk.Widget widget: Widget from which a handler is to be removed
                :param data_name: Name of the data of the widget in which the handler id is stored
                """
                handler_id = getattr(widget, data_name)
                if widget.handler_is_connected(handler_id):
                    widget.disconnect(handler_id)

            editable = getattr(renderer, "editable")
            remove_handler(editable, "focus_out_handler_id")
            remove_handler(editable, "cursor_move_handler_id")
            remove_handler(editable, "insert_at_cursor_handler_id")
            remove_handler(editable, "entry_widget_expose_event_handler_id")
            remove_handler(renderer, "editing_cancelled_handler_id")

        def on_focus_out(entry, event):
            """Applies the changes to the entry

            :param Gtk.Entry entry: The entry that was focused out
            :param Gtk.Event event: Event object with information about the event
            """
            renderer.remove_all_handler(renderer)
            if renderer.ctrl.get_path() is None:
                return
            # Originally we had to use idle_add to prevent core dumps:
            # https://mail.gnome.org/archives/gtk-perl-list/2005-September/msg00143.html
            # Gtk TODO: use idle_add if there are problems
            apply_method(renderer.ctrl.get_path(), entry.get_text())

        def on_cursor_move_in_entry_widget(entry, step, count, extend_selection):
            """Trigger scroll bar adjustments according active entry widgets cursor change
            """
            self.tree_view_keypress_callback(entry, None)

        def on_editing_started(renderer, editable, path):
            """Connects the a handler for the focus-out-event of the current editable

            :param Gtk.CellRendererText renderer: The cell renderer who's editing was started
            :param Gtk.CellEditable editable: interface for editing the current TreeView cell
            :param str path: the path identifying the edited cell
            """
            # secure scrollbar adjustments on active cell
            ctrl = renderer.ctrl
            [path, focus_column] = ctrl.tree_view.get_cursor()
            if path:
                ctrl.tree_view.scroll_to_cell(path, ctrl.widget_columns[ctrl.widget_columns.index(focus_column)],
                                              use_align=False)

            editing_cancelled_handler_id = renderer.connect('editing-canceled', on_editing_canceled)
            focus_out_handler_id = editable.connect('focus-out-event', on_focus_out)
            cursor_move_handler_id = editable.connect('move-cursor', on_cursor_move_in_entry_widget)
            insert_at_cursor_handler_id = editable.connect("insert-at-cursor", on_cursor_move_in_entry_widget)
            entry_widget_expose_event_handler_id = editable.connect("draw", self.on_entry_widget_draw_event)
            # Store reference to editable and signal handler ids for later access when removing the handlers
            # see https://gitlab.gnome.org/GNOME/accerciser/commit/036689e70304a9e98ce31238dfad2432ad4c78ea
            # originally with renderer.set_data()
            # renderer.set_data("editable", editable)
            setattr(renderer, "editable", editable)
            setattr(renderer, "editing_cancelled_handler_id", editing_cancelled_handler_id)
            # editable
            setattr(editable, "focus_out_handler_id", focus_out_handler_id)
            setattr(editable, "cursor_move_handler_id", cursor_move_handler_id)
            setattr(editable, "insert_at_cursor_handler_id", insert_at_cursor_handler_id)
            setattr(editable, "entry_widget_expose_event_handler_id", entry_widget_expose_event_handler_id)
            ctrl.active_entry_widget = editable

        def on_edited(renderer, path, new_value_str):
            """Calls the apply method with the new value

            :param Gtk.CellRendererText renderer: The cell renderer that was edited
            :param str path: The path string of the renderer
            :param str new_value_str: The new value as string
            """
            renderer.remove_all_handler(renderer)
            apply_method(path, new_value_str)
            renderer.ctrl.active_entry_widget = None

        def on_editing_canceled(renderer):
            """Disconnects the focus-out-event handler of cancelled editable

            :param Gtk.CellRendererText renderer: The cell renderer who's editing was cancelled
            """
            remove_all_handler(renderer)
            renderer.ctrl.active_entry_widget = None

        renderer.remove_all_handler = remove_all_handler
        renderer.ctrl = self
        # renderer.connect('editing-started', on_editing_started)
        # renderer.connect('edited', on_edited)
        self.__attached_renderers.append(renderer)
        self.connect_signal(renderer, 'editing-started', on_editing_started)
        self.connect_signal(renderer, 'edited', on_edited)

Response: Set up the renderer to apply changes when loosing focus out


Instruction:
Can you generate the documentation for the following Python 3 function
def tree_view_keypress_callback(self, widget, event):
        current_row_path, current_focused_column = self.tree_view.get_cursor()
        # print(current_row_path, current_focused_column)
        if isinstance(widget, Gtk.TreeView) and not self.active_entry_widget:  # avoid jumps for active entry widget
            pass
            # cursor motion/selection changes (e.g. also by button release event)
            # if current_row_path is not None and len(current_row_path) == 1 and isinstance(current_row_path[0], int):
            #     self.tree_view.scroll_to_cell(current_row_path[0], current_focused_column, use_align=True)
            # # else:
            # #     self._logger.debug("A ListViewController aspects a current_row_path of dimension 1 with integer but"
            # #                        " it is {0} and column is {1}".format(current_row_path, current_focused_column))
        elif isinstance(widget, Gtk.Entry) and self.view.scrollbar_widget is not None:
            # calculate the position of the scrollbar to be always centered with the entry widget cursor
            # TODO check how to get sufficient the scroll-offset in the entry widget -> some times zero when not
            # TODO the scrollbar is one step behind cursor -> so jump from pos1 to end works not perfect
            entry_widget_scroll_offset, entry_widget_cursor_position, entry_widget_text_length = \
                widget.get_properties(*["scroll-offset", "cursor-position", "text-length"])
            cell_rect_of_entry_widget = widget.get_allocation()

            horizontal_scroll_bar = self.view.scrollbar_widget.get_hscrollbar()
            # entry_widget_text_length must be greater than zero otherwise DevisionByZero Exception
            if horizontal_scroll_bar is not None and float(entry_widget_text_length) > 0:
                adjustment = horizontal_scroll_bar.get_adjustment()
                layout_pixel_width = widget.get_layout().get_pixel_size()[0]
                # print("rel_pos pices", cell_rect_of_entry_widget.x,)
                #     int(layout_pixel_width*float(entry_widget_cursor_position)/float(entry_widget_text_length))
                rel_pos = cell_rect_of_entry_widget.x - entry_widget_scroll_offset + \
                    int(layout_pixel_width*float(entry_widget_cursor_position)/float(entry_widget_text_length))

                # optimize rel_pos for better user support
                bounds = widget.get_selection_bounds()
                if bounds and bounds[1] - bounds[0] == len(widget.get_text()):
                    # if text is fully selected stay in front as far as possible
                    rel_pos = cell_rect_of_entry_widget.x
                    if self._horizontal_scrollbar_stay_in_front_if_possible():
                        return True
                else:
                    # try to stay long at the beginning of the columns if the columns fully fit in
                    rel_space = adjustment.get_page_size() - cell_rect_of_entry_widget.x
                    if cell_rect_of_entry_widget.x + widget.get_layout().get_pixel_size()[0] < \
                            adjustment.get_page_size():
                        rel_pos = 0.
                    elif rel_space and rel_pos <= rel_space:
                        # accelerate the showing of the first columns
                        rel_pos = rel_pos + rel_pos*3.*(rel_pos - rel_space)/adjustment.get_page_size()
                        rel_pos = 0. if rel_pos <= 0 else rel_pos
                    else:
                        # and jump to the end of the scroller space if close to the upper limit
                        rel_pos = adjustment.get_upper() if rel_pos + 2*entry_widget_scroll_offset > adjustment.get_upper() else rel_pos
                self._put_horizontal_scrollbar_onto_rel_pos(rel_pos)

Response: This method is called by the key press event handler to adapt the tree view and controller behavior according to the key release events.


Instruction:
Make a summary of the following Python 3 code
def register_view(self, view):
        super(ListViewController, self).register_view(view)
        self.tree_view.connect('button_press_event', self.mouse_click)

Response: Register callbacks for button press events and selection changed


Instruction:
Create a Python 3 function to
remove respective selected core elements and select the next one

Response:
def on_remove(self, widget, data=None):
        """Removes respective selected core elements and select the next one"""

        path_list = None
        if self.view is not None:
            model, path_list = self.tree_view.get_selection().get_selected_rows()
        old_path = self.get_path()
        models = [self.list_store[path][self.MODEL_STORAGE_ID] for path in path_list] if path_list else []
        if models:
            try:
                self.remove_core_elements(models)
            except AttributeError as e:
                self._logger.warning("The respective core element of {1}.list_store couldn't be removed. -> {0}"
                                  "".format(e, self.__class__.__name__))
            if len(self.list_store) > 0:
                self.tree_view.set_cursor(min(old_path[0], len(self.list_store) - 1))
            return True
        else:
            self._logger.warning("Please select an element to be removed.")


Instruction:
Write a Python 3 script for
implementing mouse click events explicit iloilo

Response:
def mouse_click(self, widget, event=None):
        """Implements shift- and control-key handling features for mouse button press events explicit

         The method is implements a fully defined mouse pattern to use shift- and control-key for multi-selection in a
         TreeView and a ListStore as model. It avoid problems caused by special renderer types like the text combo
         renderer by stopping the callback handler to continue with notifications.

        :param Gtk.Object widget: Object which is the source of the event
        :param Gtk.Event event: Event generated by mouse click
        :rtype: bool
        """

        if event.type == Gdk.EventType.BUTTON_PRESS:
            pthinfo = self.tree_view.get_path_at_pos(int(event.x), int(event.y))

            if not bool(event.get_state() & Gdk.ModifierType.CONTROL_MASK) \
                    and not bool(event.get_state() & Gdk.ModifierType.SHIFT_MASK) and \
                    event.type == Gdk.EventType.BUTTON_PRESS and event.get_button()[1] == 3:
                if pthinfo is not None:
                    model, paths = self._tree_selection.get_selected_rows()
                    # print(paths)
                    if pthinfo[0] not in paths:
                        # self._logger.info("force single selection for right click")
                        self.tree_view.set_cursor(pthinfo[0])
                        self._last_path_selection = pthinfo[0]
                    else:
                        # self._logger.info("single- or multi-selection for right click")
                        pass
                    self.on_right_click_menu()
                    return True

            if (bool(event.get_state() & Gdk.ModifierType.CONTROL_MASK) or \
                bool(event.get_state() & Gdk.ModifierType.SHIFT_MASK)) and \
                    event.type == Gdk.EventType.BUTTON_PRESS and event.get_button()[1] == 3:
                return True

            if not bool(event.get_state() & Gdk.ModifierType.SHIFT_MASK) and event.get_button()[1] == 1:
                if pthinfo is not None:
                    # self._logger.info("last select row {}".format(pthinfo[0]))
                    self._last_path_selection = pthinfo[0]
                # else:
                #     self._logger.info("deselect rows")
                #     self.tree_selection.unselect_all()

            if bool(event.get_state() & Gdk.ModifierType.SHIFT_MASK) and event.get_button()[1] == 1:
                # self._logger.info("SHIFT adjust selection range")
                model, paths = self._tree_selection.get_selected_rows()
                # print(model, paths, pthinfo[0])
                if paths and pthinfo and pthinfo[0]:
                    if self._last_path_selection[0] <= pthinfo[0][0]:
                        new_row_ids_selected = list(range(self._last_path_selection[0], pthinfo[0][0]+1))
                    else:
                        new_row_ids_selected = list(range(self._last_path_selection[0], pthinfo[0][0]-1, -1))
                    # self._logger.info("range to select {0}, {1}".format(new_row_ids_selected, model))
                    self._tree_selection.unselect_all()
                    for path in new_row_ids_selected:
                        self._tree_selection.select_path(path)
                    return True
                else:
                    # self._logger.info("nothing selected {}".format(model))
                    if pthinfo and pthinfo[0]:
                        self._last_path_selection = pthinfo[0]

            if bool(event.get_state() & Gdk.ModifierType.CONTROL_MASK) and event.get_button()[1] == 1:
                # self._logger.info("CONTROL adjust selection range")
                model, paths = self._tree_selection.get_selected_rows()
                # print(model, paths, pthinfo[0])
                if paths and pthinfo and pthinfo[0]:
                    if pthinfo[0] in paths:
                        self._tree_selection.unselect_path(pthinfo[0])
                    else:
                        self._tree_selection.select_path(pthinfo[0])
                    return True
                elif pthinfo and pthinfo[0]:
                    self._tree_selection.select_path(pthinfo[0])
                    return True

        elif event.type == Gdk.EventType._2BUTTON_PRESS:
            self._handle_double_click(event)


Instruction:
Can you implement a function in Python 3 that
doubles click with left mouse button focuses the element

Response:
def _handle_double_click(self, event):
        """ Double click with left mouse button focuses the element"""
        if event.get_button()[1] == 1:  # Left mouse button
            path_info = self.tree_view.get_path_at_pos(int(event.x), int(event.y))
            if path_info:  # Valid entry was clicked on
                path = path_info[0]
                iter = self.list_store.get_iter(path)
                model = self.list_store.get_value(iter, self.MODEL_STORAGE_ID)
                selection = self.model.get_state_machine_m().selection
                selection.focus = model


Instruction:
Can you implement a function in Python 3 that
updates state machine prior update of tree selection

Response:
def update_selection_sm_prior(self):
        """State machine prior update of tree selection"""
        if self._do_selection_update:
            return
        self._do_selection_update = True
        tree_selection, selected_model_list, sm_selection, sm_selected_model_list = self.get_selections()
        if tree_selection is not None:
            for path, row in enumerate(self.list_store):
                model = row[self.MODEL_STORAGE_ID]
                if model not in sm_selected_model_list and model in selected_model_list:
                    tree_selection.unselect_path(Gtk.TreePath.new_from_indices([path]))
                if model in sm_selected_model_list and model not in selected_model_list:
                    tree_selection.select_path(Gtk.TreePath.new_from_indices([path]))

        self._do_selection_update = False


Instruction:
Can you create a Python 3 function that
updates tree view prior of state machine selection

Response:
def update_selection_self_prior(self):
        """Tree view prior update of state machine selection"""
        if self._do_selection_update:
            return
        self._do_selection_update = True
        tree_selection, selected_model_list, sm_selection, sm_selected_model_list = self.get_selections()
        if isinstance(sm_selection, Selection):
            sm_selection.handle_prepared_selection_of_core_class_elements(self.CORE_ELEMENT_CLASS, selected_model_list)
        self._do_selection_update = False


Instruction:
Can you implement a function in Python 3 that
selects the row entry belonging to the given core_element_id by cursor or tree selection

Response:
def select_entry(self, core_element_id, by_cursor=True):
        """Selects the row entry belonging to the given core_element_id by cursor or tree selection"""
        for row_num, element_row in enumerate(self.list_store):
            # Compare data port ids
            if element_row[self.ID_STORAGE_ID] == core_element_id:
                if by_cursor:
                    self.tree_view.set_cursor(row_num)
                else:
                    self.tree_view.get_selection().select_path((row_num, ))
                break


Instruction:
Make a summary of the following Python 3 code
def get_path_for_core_element(self, core_element_id):
        for row_num, element_row in enumerate(self.list_store):
            # Compare data port ids
            if element_row[self.ID_STORAGE_ID] == core_element_id:
                return row_num,

Response: Get the path to the row representing the core element described by handed core_element_id


Instruction:
Given the following Python 3 function, write the documentation
def tree_view_keypress_callback(self, widget, event):
        # self._logger.info("key_value: " + str(event.keyval if event is not None else ''))
        if event and "GDK_KEY_PRESS" == event.type.value_name \
                and (event.keyval == Gdk.KEY_Tab or event.keyval == Gdk.KEY_ISO_Left_Tab):
            [path, focus_column] = self.tree_view.get_cursor()
            if not path:
                return False
            self.tree_view_keypress_callback.__func__.core_element_id = self.store[path][self.ID_STORAGE_ID]

            # finish active edit process
            if self.active_entry_widget is not None:
                text = self.active_entry_widget.get_buffer().get_text()
                if focus_column in self.widget_columns:
                    focus_column.get_cells()[0].emit('edited', path[0], text)

            # row could be updated by other call_backs caused by emitting 'edited' signal but selection stays an editable neighbor
            path = self.get_path_for_core_element(self.tree_view_keypress_callback.__func__.core_element_id)
            if event.keyval == Gdk.KEY_Tab:
                # logger.info("move right")
                direction = +1
            else:
                # logger.info("move left")
                direction = -1

            # get next row_id for focus
            if direction < 0 and focus_column is self.widget_columns[0] \
                    or direction > 0 and focus_column is self.widget_columns[-1]:
                if direction < 0 < path[0] or direction > 0 and not path[0] + 1 > len(self.store):
                    next_row = path[0] + direction
                else:
                    return False
            else:
                next_row = path[0]
            # get next column_id for focus
            focus_column_id = self.widget_columns.index(focus_column)
            if focus_column_id is not None:
                # search all columns for next editable cell renderer
                next_focus_column_id = 0
                for index in range(len(self.tree_view.get_model())):
                    test_id = focus_column_id + direction * index + direction
                    next_focus_column_id = test_id % len(self.widget_columns)
                    if test_id > len(self.widget_columns) - 1 or test_id < 0:
                        next_row = path[0] + direction
                        if next_row < 0 or next_row > len(self.tree_view.get_model()) - 1:
                            return False

                    if self.widget_columns[next_focus_column_id].get_cells()[0].get_property('editable'):
                        break
            else:
                return False

            del self.tree_view_keypress_callback.__func__.core_element_id
            # self._logger.info("self.tree_view.scroll_to_cell(next_row={0}, self.widget_columns[{1}] , use_align={2})"
            #              "".format(next_row, next_focus_column_id, False))
            # self.tree_view.scroll_to_cell(next_row, self.widget_columns[next_focus_column_id], use_align=False)
            self.tree_view.set_cursor_on_cell(Gtk.TreePath.new_from_indices([next_row]), self.widget_columns[
                next_focus_column_id], focus_cell=None, start_editing=True)
            return True
        else:
            super(ListViewController, self).tree_view_keypress_callback(widget, event)

Response: This method is called by the key press event handler for the tree view. It is used to create a new list item and edit process.


Instruction:
Explain what the following Python 3 code does
def iter_tree_with_handed_function(self, function, *function_args):
        def iter_all_children(row_iter, function, function_args):
            if isinstance(row_iter, Gtk.TreeIter):
                function(row_iter, *function_args)
                for n in reversed(range(self.tree_store.iter_n_children(row_iter))):
                    child_iter = self.tree_store.iter_nth_child(row_iter, n)
                    iter_all_children(child_iter, function, function_args)
            else:
                self._logger.warning("Iter has to be TreeIter -> handed argument is: {0}".format(row_iter))

        # iter on root level of tree
        next_iter = self.tree_store.get_iter_first()
        while next_iter:
            iter_all_children(next_iter, function, function_args)
            next_iter = self.tree_store.iter_next(next_iter)

Response: Iterate tree view with condition check function


Instruction:
How would you code a function in Python 3 to
update tree selection prior condition of tree model row

Response:
def update_selection_sm_prior_condition(self, state_row_iter, selected_model_list, sm_selected_model_list):
        """State machine prior update of tree selection for one tree model row"""
        selected_path = self.tree_store.get_path(state_row_iter)
        tree_model_row = self.tree_store[selected_path]
        model = tree_model_row[self.MODEL_STORAGE_ID]

        if model not in sm_selected_model_list and model in selected_model_list:
            self._tree_selection.unselect_iter(state_row_iter)
        elif model in sm_selected_model_list and model not in selected_model_list:
            self.tree_view.expand_to_path(selected_path)
            self._tree_selection.select_iter(state_row_iter)


Instruction:
Given the following Python 3 function, write the documentation
def update_selection_self_prior_condition(self, state_row_iter, sm_selected_model_set, selected_model_list):
        selected_path = self.tree_store.get_path(state_row_iter)
        tree_model_row = self.tree_store[selected_path]
        model = tree_model_row[self.MODEL_STORAGE_ID]

        if model in sm_selected_model_set and model not in selected_model_list:
            sm_selected_model_set.remove(model)
        elif model not in sm_selected_model_set and model in selected_model_list:
            sm_selected_model_set.add(model)

Response: Tree view prior update of one model in the state machine selection


Instruction:
How would you implement a function in Python 3 that
updates tree view prior of state machine selection

Response:
def update_selection_self_prior(self):
        """Tree view prior update of state machine selection"""
        if self._do_selection_update:
            return
        self._do_selection_update = True
        tree_selection, selected_model_list, sm_selection, sm_selected_model_set = self.get_selections()
        if isinstance(sm_selection, Selection):
            # current sm_selected_model_set will be updated and hand it back
            self.iter_tree_with_handed_function(self.update_selection_self_prior_condition,
                                                sm_selected_model_set, selected_model_list)
            sm_selection.handle_prepared_selection_of_core_class_elements(self.CORE_ELEMENT_CLASS, sm_selected_model_set)
            # TODO check if we can solve the difference that occurs e.g. while complex actions?, or same state paths!
            # -> models in selection for core element not in the tree the function iter tree + condition tolerates this
            if not set(selected_model_list) == sm_selected_model_set:
                self._logger.verbose("Difference between tree view selection: \n{0} \nand state machine selection: "
                                     "\n{1}".format(set(selected_model_list), sm_selected_model_set))

        # TODO check why sometimes not consistent with sm selection. e.g while modification history test
        if self.check_selection_consistency(sm_check=False):
            self.update_selection_sm_prior()
        self._do_selection_update = False


Instruction:
Here you have a function in Python 3, explain what it does
def update_selection_sm_prior(self):
        if self._do_selection_update:
            return
        self._do_selection_update = True
        tree_selection, selected_model_list, sm_selection, sm_selected_model_list = self.get_selections()
        if tree_selection is not None:
            # self._logger.info("SM SELECTION IS: {2}\n{0}, \n{1}".format(selected_model_list, sm_selected_model_list,
            #                                                             tree_selection.get_mode()))
            self.iter_tree_with_handed_function(self.update_selection_sm_prior_condition,
                                                selected_model_list, sm_selected_model_list)
            self.check_selection_consistency()
        self._do_selection_update = False

Response: State machine prior update of tree selection


Instruction:
Can you write a function in Python 3 where it
selects the row entry belonging to the given core_element_id by cursor or tree selection

Response:
def select_entry(self, core_element_id, by_cursor=True):
        """Selects the row entry belonging to the given core_element_id by cursor or tree selection"""
        path = self.get_path_for_core_element(core_element_id)
        if path:
            if by_cursor:
                self.tree_view.set_cursor(path)
            else:
                self.tree_view.get_selection().select_path(path)
        else:
            self._logger.warning("Path not valid: {0} (by_cursor {1})".format(str(core_element_id), str(by_cursor)))


Instruction:
Write a Python 3 script to
check whether the passed variable is a tuple with two floats or integers

Response:
def contains_geometric_info(var):
    """ Check whether the passed variable is a tuple with two floats or integers """
    return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)


Instruction:
Create a Python 3 function to
generate default meta data for a child state according its parent state model

Response:
def generate_default_state_meta_data(parent_state_m, canvas=None, num_child_state=None, gaphas_editor=True):
    """Generate default meta data for a child state according its parent state

    The function could work with the handed num_child_state if all child state are not drawn, till now.
    The method checks if the parents meta data is consistent in canvas state view and model if a canvas instance is
    handed.

    :param rafcon.gui.models.container_state.ContainerStateModel parent_state_m: Model of the state were the child
                                                                                should be drawn into
    :param rafcon.gui.mygaphas.canvas.MyCanvas canvas: canvas instance the state will be drawn into
    :param int num_child_state: Number of child states already drawn in canvas parent state view
    :return child relative pos (tuple) in parent and it size (tuple)
    """
    parent_size = parent_state_m.get_meta_data_editor()['size']
    if not contains_geometric_info(parent_size):
        raise ValueError("Invalid state size: {}".format(parent_size))

    # use handed number of child states and otherwise take number of child states from parent state model
    num_child_state = len(parent_state_m.states) if num_child_state is None else num_child_state

    # check if respective canvas is handed if meta data of parent canvas view is consistent with model
    if canvas is not None:
        parent_state_v = canvas.get_view_for_model(parent_state_m)
        if not (parent_state_v.width, parent_state_v.height) == parent_size:
            logger.warning("Size meta data of model {0} is different to gaphas {1}"
                           "".format((parent_state_v.width, parent_state_v.height), parent_size))

    # Calculate default positions for the child states
    # Make the inset from the top left corner
    parent_state_width, parent_state_height = parent_size
    new_state_side_size = min(parent_state_width * 0.2, parent_state_height * 0.2)

    child_width = new_state_side_size
    child_height = new_state_side_size
    child_size = (child_width, child_height)
    child_spacing = max(child_size) * 1.2

    parent_margin = cal_margin(parent_size)
    # print("parent size", parent_size, parent_margin)
    max_cols = (parent_state_width - 2*parent_margin) // child_spacing
    (row, col) = divmod(num_child_state, max_cols)

    max_rows = (parent_state_height - 2*parent_margin - 0.5*child_spacing) // (1.5*child_spacing)
    (overlapping, row) = divmod(row, max_rows)

    overlapping_step = 0.5*parent_margin
    max_overlaps_x = (parent_state_width - 2*parent_margin - child_width -
                      (parent_margin + (max_cols - 1) * child_spacing + child_spacing - child_width)) // overlapping_step
    max_overlaps_y = (parent_state_height - 2*parent_margin - child_height -
                      child_spacing * (1.5 * (max_rows - 1) + 1)) // overlapping_step
    # handle case of less space TODO check again not perfect, maybe that can be done more simple
    max_overlaps_x = 0 if max_overlaps_x < 0 else max_overlaps_x
    max_overlaps_y = 0 if max_overlaps_y < 0 else max_overlaps_y
    max_overlaps = min(max_overlaps_x, max_overlaps_y) + 1
    overlapping = divmod(overlapping, max_overlaps)[1]

    child_rel_pos_x = parent_margin + col * child_spacing + child_spacing - child_width + overlapping*overlapping_step
    child_rel_pos_y = child_spacing * (1.5 * row + 1.) + overlapping*overlapping_step
    return (child_rel_pos_x, child_rel_pos_y), (new_state_side_size, new_state_side_size)


Instruction:
Can you generate the documentation for the following Python 3 function
def add_boundary_clearance(left, right, top, bottom, frame, clearance=0.1):

    # print("old boundary", left, right, top, bottom)
    width = right - left
    width = frame['size'][0] if width < frame['size'][0] else width
    left -= 0.5 * clearance * width
    left = 0 if left < 0 else left
    right += 0.5 * clearance * width

    height = bottom - top
    height = frame['size'][1] if height < frame['size'][1] else height
    top -= 0.5 * clearance * height
    top = 0 if top < 0 else top
    bottom += 0.5 * clearance * height
    # print("new boundary", left, right, top, bottom)
    return left, right, top, bottom

Response: Increase the space between left and right and top and bottom and the function increase the space between left and right and between top and bottom and between left and right parameters.


Instruction:
Create a Python 3 function for
getting boundaries of all models in a dictionary.

Response:
def get_boundaries_of_elements_in_dict(models_dict, clearance=0.):
    """ Get boundaries of all handed models

    The function checks all model meta data positions to increase boundary starting with a state or scoped variables.
    It is finally iterated over all states, data and logical port models and linkage if sufficient for respective
    graphical editor. At the end a clearance is added to the boundary if needed e.g. to secure size for opengl.

    :param models_dict: dict of all handed models
    :return: tuple of left, right, top and bottom value
    """

    # Determine initial outer coordinates
    right = 0.
    bottom = 0.
    if 'states' in models_dict and models_dict['states']:
        left = list(models_dict['states'].items())[0][1].get_meta_data_editor()['rel_pos'][0]
        top = list(models_dict['states'].items())[0][1].get_meta_data_editor()['rel_pos'][1]
    elif 'scoped_variables' in models_dict and models_dict['scoped_variables']:
        left = list(models_dict['scoped_variables'].items())[0][1].get_meta_data_editor()['inner_rel_pos'][0]
        top = list(models_dict['scoped_variables'].items())[0][1].get_meta_data_editor()['inner_rel_pos'][1]
    else:
        all_ports = list(models_dict['input_data_ports'].values()) + list(models_dict['output_data_ports'].values()) + \
                    list(models_dict['scoped_variables'].values()) + list(models_dict['outcomes'].values())
        if len(set([port_m.core_element.parent for port_m in all_ports])) == 1:
            logger.info("Only one parent {0} {1}".format(all_ports[0].core_element.parent, all_ports[0].parent.get_meta_data_editor()))
        if all_ports:
            left = all_ports[0].parent.get_meta_data_editor()['rel_pos'][0]
            top = all_ports[0].parent.get_meta_data_editor()['rel_pos'][1]
        else:
            raise ValueError("Get boundary method does not aspects all list elements empty in dictionary. {0}"
                             "".format(models_dict))

    def cal_max(max_x, max_y, rel_pos, size):
        max_x = size[0] + rel_pos[0] if size[0] + rel_pos[0] > max_x else max_x
        max_y = rel_pos[1] + size[1] if rel_pos[1] + size[1] > max_y else max_y
        return max_x, max_y

    def cal_min(min_x, min_y, rel_pos, size):
        min_x = rel_pos[0] if rel_pos[0] < min_x else min_x
        min_y = rel_pos[1] if rel_pos[1] < min_y else min_y
        return min_x, min_y

    # Finally take into account all relevant elements in models_dict
    # -> states, scoped variables (maybe input- and output- data ports) and transitions and data flows are relevant
    parts = ['states', 'transitions', 'data_flows']
    for key in parts:
        elems_dict = models_dict[key]
        rel_positions = []
        for model in elems_dict.values():
            _size = (0., 0.)
            if key == 'states':
                rel_positions = [model.get_meta_data_editor()['rel_pos']]
                _size = model.get_meta_data_editor()['size']
                # print(key, rel_positions, _size)
            elif key in ['scoped_variables', 'input_data_ports', 'output_data_ports']:
                rel_positions = [model.get_meta_data_editor()['inner_rel_pos']]
                # TODO check to take the ports size into account
                # print(key, rel_positions, _size)
            elif key in ['transitions', 'data_flows']:
                if key is "data_flows":
                    # take into account the meta data positions of opengl if there is some (always in opengl format)
                    rel_positions = mirror_waypoints(deepcopy(model.get_meta_data_editor()))['waypoints']
                else:
                    rel_positions = model.get_meta_data_editor()['waypoints']
                # print(key, rel_positions, _size, model.meta)

            for rel_position in rel_positions:
                # check for empty fields and ignore them at this point
                if not contains_geometric_info(rel_position):
                    continue
                right, bottom = cal_max(right, bottom, rel_position, _size)
                left, top = cal_min(left, top, rel_position, _size)
                # print("new edges:", left, right, top, bottom, key)

    # increase of boundary results into bigger estimated size and finally stronger reduction of original element sizes
    left, right, top, bottom = add_boundary_clearance(left, right, top, bottom, {'size': (0., 0.)}, clearance)
    return left, right, top, bottom


Instruction:
Can you tell what is the following Python 3 function doing
def cal_frame_according_boundaries(left, right, top, bottom, parent_size, gaphas_editor=True, group=True):
    # print("parent_size ->", parent_size)
    margin = cal_margin(parent_size)
    # Add margin and ensure that the upper left corner is within the state
    if group:
        # frame of grouped state
        rel_pos = max(left - margin, 0), max(top - margin, 0)
        # Add margin and ensure that the lower right corner is within the state
        size = (min(right - left + 2 * margin, parent_size[0] - rel_pos[0]),
                min(bottom - top + 2 * margin, parent_size[1] - rel_pos[1]))
    else:
        # frame inside of state
        # rel_pos = max(margin, 0), max(margin, 0)
        rel_pos = left, top
        size = right - left, bottom - top

    return margin, rel_pos, size

Response: Generate margin relative position and size handed boundary parameter and parent size


Instruction:
Can you write a function in Python 3 where it
adds relative position offset to all handed models in dict

Response:
def offset_rel_pos_of_all_models_in_dict(models_dict, pos_offset, gaphas_editor=True):
    """ Add position offset to all handed models in dict"""
    # print("\n", "#"*30, "offset models", pos_offset, "#"*30)
    # Update relative position of states within the container in order to maintain their absolute position
    for child_state_m in models_dict['states'].values():
        old_rel_pos = child_state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['rel_pos']
        # print("old_rel_pos", old_rel_pos, child_state_m)
        child_state_m.set_meta_data_editor('rel_pos', add_pos(old_rel_pos, pos_offset), from_gaphas=gaphas_editor)
        # print("new_rel_pos", child_state_m.get_meta_data_editor(for_gaphas=gaphas_editor), child_state_m)

    # Do the same for scoped variable
    if not gaphas_editor:
        for scoped_variable_m in models_dict['scoped_variables'].values():
            old_rel_pos = scoped_variable_m.get_meta_data_editor(for_gaphas=gaphas_editor)['inner_rel_pos']
            scoped_variable_m.set_meta_data_editor('inner_rel_pos', add_pos(old_rel_pos, pos_offset), gaphas_editor)

    # Do the same for all connections (transitions and data flows)
    connection_models = list(models_dict['transitions'].values()) + list(models_dict['data_flows'].values())
    for connection_m in connection_models:
        old_waypoints = connection_m.get_meta_data_editor(for_gaphas=gaphas_editor)['waypoints']
        new_waypoints = []
        for waypoint in old_waypoints:
            from rafcon.gui.models.data_flow import DataFlowModel
            if isinstance(connection_m, DataFlowModel) and gaphas_editor:
                new_waypoints.append(add_pos(waypoint, (pos_offset[0], -pos_offset[1])))
            else:
                new_waypoints.append(add_pos(waypoint, pos_offset))
        connection_m.set_meta_data_editor('waypoints', new_waypoints, from_gaphas=gaphas_editor)


Instruction:
Can you create a Python 3 function that
scales the ports of the library model accordingly relative to the state_copy meta size.

Response:
def scale_library_ports_meta_data(state_m, gaphas_editor=True):
    """Scale the ports of library model accordingly relative to state_copy meta size.

    The function assumes that the meta data of ports of the state_copy of the library was copied to
    respective elements in the library and that those was not adjusted before.
    """
    if state_m.meta_data_was_scaled:
        return
    state_m.income.set_meta_data_editor('rel_pos', state_m.state_copy.income.get_meta_data_editor()['rel_pos'])
    # print("scale_library_ports_meta_data ", state_m.get_meta_data_editor()['size'], \)
    #     state_m.state_copy.get_meta_data_editor()['size']
    factor = divide_two_vectors(state_m.get_meta_data_editor()['size'],
                                state_m.state_copy.get_meta_data_editor()['size'])

    # print("scale_library_ports_meta_data -> resize_state_port_meta", factor)
    if contains_geometric_info(factor):
        resize_state_port_meta(state_m, factor, True)
        state_m.meta_data_was_scaled = True
    else:
        logger.info("Skip resize of library ports meta data {0}".format(state_m))


Instruction:
Can you create a Python 3 function that
scales the meta data of the content of a LibraryStateModel to fit the current size of the LibraryStateModel.

Response:
def scale_library_content(library_state_m, gaphas_editor=True):
    """Scales the meta data of the content of a LibraryState

    The contents of the `LibraryStateModel` `library_state_m` (i.e., the `state_copy` and all it children/state
    elements) to fit the current size of the `LibraryStateModel`.

    :param LibraryStateModel library_state_m: The library who's content is to be resized
    :param bool gaphas_editor: Whether to use the meta data for the GraphicalEditor using gaphas (default: True)
    """
    assert isinstance(library_state_m, LibraryStateModel)
    # For library states with an ExecutionState as state_copy, scaling does not make sense
    if not isinstance(library_state_m.state_copy, ContainerStateModel):
        return

    # use same size for state copy and put rel_pos to zero
    library_meta = library_state_m.get_meta_data_editor(gaphas_editor)
    state_copy_meta = library_state_m.state_copy.set_meta_data_editor('size', library_meta['size'], gaphas_editor)
    library_state_m.state_copy.set_meta_data_editor('rel_pos', (0., 0.), from_gaphas=gaphas_editor)

    # work around that gaphas draws in state_copy coordinates (which is not shown) -> reduce state copy size
    if gaphas_editor:
        library_state_margin = cal_margin(state_copy_meta['size'])
        state_copy_size = subtract_pos(state_copy_meta['size'], (2*library_state_margin, 2*library_state_margin))
        library_state_m.state_copy.set_meta_data_editor('size', state_copy_size, gaphas_editor)

    # if meta data has empty fields put default data on state meta data
    if model_has_empty_meta(library_state_m.state_copy) and \
            not put_default_meta_data_on_state_m_recursively(library_state_m.state_copy, library_state_m,
                                                             only_child_states=True):
        return

    # prepare resize by collecting all state elements in the models_dict
    # do resize in respect to state copy
    # (opengl same size as library state and in case of gaphas reduced by library state margin)
    models_dict = {'state': library_state_m.state_copy}
    for state_element_key in library_state_m.state_copy.state.state_element_attrs:
        state_element_list = getattr(library_state_m.state_copy, state_element_key)
        # Some models are hold in a gtkmvc3.support.wrappers.ObsListWrapper, not a list
        if hasattr(state_element_list, 'keys'):
            state_element_list = state_element_list.values()
        models_dict[state_element_key] = {elem.core_element.core_element_id: elem for elem in state_element_list}

    # perform final resize
    resize_factor = (1., 1.)
    try:
        if not models_dict['states'] and (not models_dict['scoped_variables'] or gaphas_editor):
            logger.info("Skip scaling for empty root state {0}.".format(library_state_m.state))
        else:
            resize_factor = scale_meta_data_according_state(models_dict, fill_up=True)
    except:
        logger.exception("Scale library content of {0} cause a problem.".format(library_state_m.state))
    finally:
        resize_income_of_state_m(library_state_m.state_copy, resize_factor, gaphas_editor)


Instruction:
Make a summary of the following Python 3 code
def resize_state_port_meta(state_m, factor, gaphas_editor=True):
    # print("scale ports", factor, state_m, gaphas_editor)
    if not gaphas_editor and isinstance(state_m, ContainerStateModel):
        port_models = state_m.input_data_ports[:] + state_m.output_data_ports[:] + state_m.scoped_variables[:]
    else:
        port_models = state_m.input_data_ports[:] + state_m.output_data_ports[:] + state_m.outcomes[:]
        port_models += state_m.scoped_variables[:] if isinstance(state_m, ContainerStateModel) else []
    _resize_port_models_list(port_models, 'rel_pos' if gaphas_editor else 'inner_rel_pos', factor, gaphas_editor)

    resize_income_of_state_m(state_m, factor, gaphas_editor)

Response: Resize data and logical ports relative positions