Instruction:
Make a summary of the following Python 3 code
def post_init(setup_config):
    logger.info("Run post-initiation hook of {} plugin.".format(__file__.split(os.path.sep)[-2]))

    from . import core_template_observer
    # Example 1: initiate observer some elements of the execution engine
    core_template_observer.ExecutionEngineObserver()

    # Example 2: initiate observer execution status
    core_template_observer.ExecutionStatusObserver()

    from . import gtkmvc_template_observer
    # Example 3: gtkmvc3 general modification observer
    # initiate observer of root_state model-object which already implements a power full recursive notification pattern
    gtkmvc_template_observer.RootStateModificationObserver()

    # Example 4: gtkmvc3 meta signal observer
    gtkmvc_template_observer.MetaSignalModificationObserver()

Response: This function is called by the plugin after the plugin is initialized.


Instruction:
Can you write a function in Python 3 where it
removes all models of states that have a state model with parent relation in the list The function filters the list of models, so that for no model in the list, one of it (grand-)parents is also in the list. E.g. if the input models consists of a hierarchy state with two of its child states, the resulting list only contains the hierarchy state. :param set models: The set of selected models :return: The reduced set of selected models :rtype: set

Response:
def reduce_to_parent_states(models):
    """Remove all models of states that have a state model with parent relation in the list

    The function filters the list of models, so that for no model in the list, one of it (grand-)parents is also in
    the list. E.g. if the input models consists of a hierarchy state with two of its child states, the resulting list
    only contains the hierarchy state.

    :param set models: The set of selected models
    :return: The reduced set of selected models
    :rtype: set
    """
    models = set(models)  # Ensure that models is a set and that we do not operate on the parameter itself
    models_to_remove = set()
    # check all models
    for model in models:
        parent_m = model.parent
        # check if any (grand-)parent is already in the selection, if so, remove the child
        while parent_m is not None:
            if parent_m in models:
                models_to_remove.add(model)
                break
            parent_m = parent_m.parent
    for model in models_to_remove:
        models.remove(model)
    if models_to_remove:
        logger.debug("The selection has been reduced, as it may not contain elements whose children are also selected")
    return models


Instruction:
How would you explain what the following Python 3 function does
def extend_selection():
    from rafcon.gui.singleton import main_window_controller
    currently_pressed_keys = main_window_controller.currently_pressed_keys if main_window_controller else set()
    if any(key in currently_pressed_keys for key in [constants.EXTEND_SELECTION_KEY,
                                                     constants.EXTEND_SELECTION_KEY_ALT]):
        return True
    return False

Response: Checks if the selection is to be extended


Instruction:
Write a Python 3 function for
checking types of passed models for correctness and in case raise exception

Response:
def _check_model_types(self, models):
        """ Check types of passed models for correctness and in case raise exception

        :rtype: set
        :returns: set of models that are valid for the class"""
        if not hasattr(models, "__iter__"):
            models = {models}
        if not all([isinstance(model, (AbstractStateModel, StateElementModel)) for model in models]):
            raise TypeError("The selection supports only models with base class AbstractStateModel or "
                            "StateElementModel, see handed elements {0}".format(models))
        return models if isinstance(models, set) else set(models)


Instruction:
Write a Python 3 script to
add the passed models to the selection

Response:
def add(self, models):
        """ Adds the passed model(s) to the selection"""
        if models is None:
            return

        models = self._check_model_types(models)
        self._selected.update(models)
        self._selected = reduce_to_parent_states(self._selected)


Instruction:
How would you implement a function in Python 3 that
removes the passed model from the selection

Response:
def remove(self, models):
        """ Removed the passed model(s) from the selection"""
        models = self._check_model_types(models)
        for model in models:
            if model in self._selected:
                self._selected.remove(model)


Instruction:
Write a Python 3 function for
setting the selection to the passed model s

Response:
def set(self, models):
        """ Sets the selection to the passed model(s) """
        # Do not add None values to selection
        if models is None:
            models = set()

        models = self._check_model_types(models)
        if len(models) > 1:
            models = reduce_to_parent_states(models)

        self._selected = set(models)


Instruction:
Write a Python 3 function that can
handle the selection for a specific core_class elements of a specific TreeStore.

Response:
def handle_prepared_selection_of_core_class_elements(self, core_class, models):
        """Handles the selection for TreeStore widgets maintaining lists of a specific `core_class` elements

        If widgets hold a TreeStore with elements of a specific `core_class`, the local selection of that element
        type is handled by that widget. This method is called to integrate the local selection with the overall
        selection of the state machine.

        If no modifier key (indicating to extend the selection) is pressed, the state machine selection is set to the
        passed selection. If the selection is to be extended, the state machine collection will consist of the widget
        selection plus all previously selected elements not having the core class `core_class`.

        :param State | StateElement core_class: The core class of the elements the widget handles
        :param models: The list of models that are currently being selected locally
        """
        if extend_selection():
            self._selected.difference_update(self.get_selected_elements_of_core_class(core_class))
        else:
            self._selected.clear()

        models = self._check_model_types(models)
        if len(models) > 1:
            models = reduce_to_parent_states(models)

        self._selected.update(models)


Instruction:
How would you implement a function in Python 3 that
handles the new selection for generic widgets.

Response:
def handle_new_selection(self, models):
        """Handles the selection for generic widgets

        This is a helper method for generic widgets that want to modify the selection. These widgets can pass a list
        of newly selected (or clicked on) models.

        The method looks at the previous selection, the passed models and the list of pressed (modifier) keys:

        * If no modifier key is pressed, the previous selection is cleared and the new selection is set to the passed
          models
        * If the extend-selection modifier key is pressed, elements of `models` that are _not_ in the previous
          selection are selected, those that are in the previous selection are deselected

        :param models: The list of models that are newly selected/clicked on
        """
        models = self._check_model_types(models)

        if extend_selection():
            already_selected_elements = models & self._selected
            newly_selected_elements = models - self._selected
            self._selected.difference_update(already_selected_elements)
            self._selected.update(newly_selected_elements)
        else:
            self._selected = models
        self._selected = reduce_to_parent_states(self._selected)


Instruction:
Here you have a function in Python 3, explain what it does
def focus(self, model):
        if model is None:
            del self.focus
            return

        self._check_model_types(model)
        self.add(model)
        focus_msg = FocusSignalMsg(model, self._focus)
        self._focus = model
        self._selected.add(model)
        self._selected = reduce_to_parent_states(self._selected)
        self.focus_signal.emit(focus_msg)

Response: Sets the passed model as focused element


Instruction:
Can you tell what is the following Python 3 function doing
def update_core_element_lists(self):
        def get_selected_elements_of_core_class(core_class):
            return set(element for element in self._selected if isinstance(element.core_element, core_class))
        self._states = get_selected_elements_of_core_class(State)
        self._transitions = get_selected_elements_of_core_class(Transition)
        self._data_flows = get_selected_elements_of_core_class(DataFlow)
        self._input_data_ports = get_selected_elements_of_core_class(InputDataPort)
        self._output_data_ports = get_selected_elements_of_core_class(OutputDataPort)
        self._scoped_variables = get_selected_elements_of_core_class(ScopedVariable)
        self._outcomes = get_selected_elements_of_core_class(Outcome)

Response: Maintains inner lists of selected elements with a specific core element class


Instruction:
Here you have a function in Python 3, explain what it does
def get_selected_elements_of_core_class(self, core_element_type):
        if core_element_type is Outcome:
            return self.outcomes
        elif core_element_type is InputDataPort:
            return self.input_data_ports
        elif core_element_type is OutputDataPort:
            return self.output_data_ports
        elif core_element_type is ScopedVariable:
            return self.scoped_variables
        elif core_element_type is Transition:
            return self.transitions
        elif core_element_type is DataFlow:
            return self.data_flows
        elif core_element_type is State:
            return self.states
        raise RuntimeError("Invalid core element type: " + core_element_type)

Response: Returns all selected elements of the specified core element type as state element class


Instruction:
Write a Python 3 function that can
check whether the given model is selected by the user.

Response:
def is_selected(self, model):
        """Checks whether the given model is selected

        :param model:
        :return: True if the model is within the selection, False else
        :rtype: bool
        """
        if model is None:
            return len(self._selected) == 0
        return model in self._selected


Instruction:
How would you explain what the following Python 3 function does
def execute_command_with_path_in_process(command, path, shell=False, cwd=None, logger=None):
    if logger is None:
        logger = _logger
    logger.debug("Opening path with command: {0} {1}".format(command, path))
    # This splits the command in a matter so that the command gets called in a separate shell and thus
    # does not lock the window.
    args = shlex.split('{0} "{1}"'.format(command, path))
    try:
        subprocess.Popen(args, shell=shell, cwd=cwd)
        return True
    except OSError as e:
        logger.error('The operating system raised an error: {}'.format(e))
    return False

Response: Executes a specific command in a separate process with a path as argument.


Instruction:
Can you implement a function in Python 3 that
executes a specific command in a separate process

Response:
def execute_command_in_process(command, shell=False, cwd=None, logger=None):
    """ Executes a specific command in a separate process

    :param command: the command to be executed
    :param bool shell: Whether to use a shell
    :param str cwd: The working directory of the command
    :param logger: optional logger instance which can be handed from other module
    :return: None
    """
    if logger is None:
        logger = _logger
    logger.debug("Run shell command: {0}".format(command))
    try:
        subprocess.Popen(command, shell=shell, cwd=cwd)
        return True
    except OSError as e:
        logger.error('The operating system raised an error: {}'.format(e))
    return False


Instruction:
Create a Python 3 function for
adding models for each child state of the state

Response:
def _load_child_state_models(self, load_meta_data):
        """Adds models for each child state of the state

        :param bool load_meta_data: Whether to load the meta data of the child state
        """
        self.states = {}
        # Create model for each child class
        child_states = self.state.states
        for child_state in child_states.values():
            # Create hierarchy
            model_class = get_state_model_class_for_state(child_state)
            if model_class is not None:
                self._add_model(self.states, child_state, model_class, child_state.state_id, load_meta_data)
            else:
                logger.error("Unknown state type '{type:s}'. Cannot create model.".format(type=type(child_state)))


Instruction:
How would you explain what the following Python 3 function does
def _load_scoped_variable_models(self):
        self.scoped_variables = []
        for scoped_variable in self.state.scoped_variables.values():
            self._add_model(self.scoped_variables, scoped_variable, ScopedVariableModel)

Response: Adds models for each scoped variable in the state


Instruction:
Write a Python 3 function for
adding models for each data flow in the state

Response:
def _load_data_flow_models(self):
        """ Adds models for each data flow of the state """
        self.data_flows = []
        for data_flow in self.state.data_flows.values():
            self._add_model(self.data_flows, data_flow, DataFlowModel)


Instruction:
How would you explain what the following Python 3 function does
def _load_transition_models(self):
        self.transitions = []
        for transition in self.state.transitions.values():
            self._add_model(self.transitions, transition, TransitionModel)

Response: Loads the transition models for each state


Instruction:
How would you code a function in Python 3 to
prepare the model for destruction.

Response:
def prepare_destruction(self, recursive=True):
        """Prepares the model for destruction

        Recursively un-registers all observers and removes references to child models. Extends the destroy method of
        the base class by child elements of a container state.
        """
        # logger.verbose("Prepare destruction container state ...")
        if recursive:
            for scoped_variable in self.scoped_variables:
                scoped_variable.prepare_destruction()
            for connection in self.transitions[:] + self.data_flows[:]:
                connection.prepare_destruction()
            for state in self.states.values():
                state.prepare_destruction(recursive)
        del self.scoped_variables[:]
        del self.transitions[:]
        del self.data_flows[:]
        self.states.clear()
        self.scoped_variables = None
        self.transitions = None
        self.data_flows = None
        self.states = None
        super(ContainerStateModel, self).prepare_destruction(recursive)


Instruction:
Create a Python 3 function to
return the scoped variable model for the given data port id

Response:
def get_scoped_variable_m(self, data_port_id):
        """Returns the scoped variable model for the given data port id

        :param data_port_id: The data port id to search for
        :return: The model of the scoped variable with the given id
        """
        for scoped_variable_m in self.scoped_variables:
            if scoped_variable_m.scoped_variable.data_port_id == data_port_id:
                return scoped_variable_m
        return None


Instruction:
How would you implement a function in Python 3 that
searches and returns the model of a data port

Response:
def get_data_port_m(self, data_port_id):
        """Searches and returns the model of a data port of a given state

        The method searches a port with the given id in the data ports of the given state model. If the state model
        is a container state, not only the input and output data ports are looked at, but also the scoped variables.

        :param data_port_id: The data port id to be searched
        :return: The model of the data port or None if it is not found
        """

        for scoped_var_m in self.scoped_variables:
            if scoped_var_m.scoped_variable.data_port_id == data_port_id:
                return scoped_var_m

        return StateModel.get_data_port_m(self, data_port_id)


Instruction:
Given the following Python 3 function, write the documentation
def get_transition_m(self, transition_id):
        for transition_m in self.transitions:
            if transition_m.transition.transition_id == transition_id:
                return transition_m
        return None

Response: Searches and returns the transition model with the given id


Instruction:
Can you write a function in Python 3 where it
searches and returns the data flow model with the given id

Response:
def get_data_flow_m(self, data_flow_id):
        """Searches and return the data flow model with the given in the given container state model

        :param data_flow_id: The data flow id to be searched
        :return: The model of the data flow or None if it is not found
        """
        for data_flow_m in self.data_flows:
            if data_flow_m.data_flow.data_flow_id == data_flow_id:
                return data_flow_m
        return None


Instruction:
Here you have a function in Python 3, explain what it does
def store_meta_data(self, copy_path=None):
        super(ContainerStateModel, self).store_meta_data(copy_path)
        for state_key, state in self.states.items():
            state.store_meta_data(copy_path)

Response: Store meta data of container states to the filesystem


Instruction:
How would you code a function in Python 3 to
dismiss current meta data and copy meta data from given state model

Response:
def copy_meta_data_from_state_m(self, source_state_m):
        """Dismiss current meta data and copy meta data from given state model

        In addition to the state model method, also the meta data of container states is copied. Then, the meta data
        of child states are recursively copied.

        :param source_state_m: State model to load the meta data from
        """
        for scoped_variable_m in self.scoped_variables:
            source_scoped_variable_m = source_state_m.get_scoped_variable_m(
                scoped_variable_m.scoped_variable.data_port_id)
            scoped_variable_m.meta = deepcopy(source_scoped_variable_m.meta)

        for transition_m in self.transitions:
            source_transition_m = source_state_m.get_transition_m(transition_m.transition.transition_id)
            transition_m.meta = deepcopy(source_transition_m.meta)

        for data_flow_m in self.data_flows:
            source_data_flow_m = source_state_m.get_data_flow_m(data_flow_m.data_flow.data_flow_id)
            data_flow_m.meta = deepcopy(source_data_flow_m.meta)

        for state_key, state in self.states.items():
            state.copy_meta_data_from_state_m(source_state_m.states[state_key])

        super(ContainerStateModel, self).copy_meta_data_from_state_m(source_state_m)


Instruction:
Given the following Python 3 function, write the documentation
def _generate_element_meta_data(self, meta_data):
        super(ContainerStateModel, self)._generate_element_meta_data(meta_data)
        for transition_m in self.transitions:
            self._copy_element_meta_data_to_meta_file_data(meta_data, transition_m, "transition",
                                                           transition_m.transition.transition_id)
        for data_flow_m in self.data_flows:
            self._copy_element_meta_data_to_meta_file_data(meta_data, data_flow_m, "data_flow",
                                                           data_flow_m.data_flow.data_flow_id)
        for scoped_variable_m in self.scoped_variables:
            self._copy_element_meta_data_to_meta_file_data(meta_data, scoped_variable_m, "scoped_variable",
                                                           scoped_variable_m.scoped_variable.data_port_id)

Response: Generate meta data for the container state elements and add it to the given meta data dictionary.


Instruction:
Create a Python 3 function to
show a user dialog for a specific folder selection

Response:
def open_folder(query, default_path=None):
    """Shows a user dialog for folder selection

    A dialog is opened with the prompt `query`. The current path is set to the last path that was opened/created. The
    roots of all libraries is added to the list of shortcut folders.

    :param str query: Prompt asking the user for a specific folder
    :param str default_path: Path to use if user does not specify one
    :return: Path selected by the user or `default_path` if no path was specified or None if none of the paths is valid
    :rtype: str
    """
    from gi.repository import Gtk
    from os.path import expanduser, pathsep, dirname, isdir
    from rafcon.gui.singleton import main_window_controller
    from rafcon.gui.runtime_config import global_runtime_config
    last_path = global_runtime_config.get_config_value('LAST_PATH_OPEN_SAVE', "")
    selected_filename = None
    if last_path and isdir(last_path):
        selected_filename = last_path.split(pathsep)[-1]
        last_path = dirname(last_path)
    else:
        last_path = expanduser('~')

    dialog = Gtk.FileChooserDialog(query,
                                   None,
                                   Gtk.FileChooserAction.SELECT_FOLDER,
                                   (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                    Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
    # Allows confirming with Enter and double-click
    dialog.set_default_response(Gtk.ResponseType.OK)
    if main_window_controller:
        dialog.set_transient_for(main_window_controller.view.get_top_widget())
    dialog.set_current_folder(last_path)
    if selected_filename is not None:
        dialog.select_filename(selected_filename)

    dialog.set_show_hidden(False)

    # Add library roots to list of shortcut folders
    add_library_root_path_to_shortcut_folders_of_dialog(dialog)

    response = dialog.run()

    if response != Gtk.ResponseType.OK:
        dialog.destroy()
        if default_path and os.path.isdir(default_path):
            return default_path
        return None

    path = dialog.get_filename()
    dialog.destroy()

    if os.path.isdir(path):
        global_runtime_config.set_config_value('LAST_PATH_OPEN_SAVE', path)
        return path
    return None


Instruction:
Can you implement a function in Python 3 that
shows a user dialog to create a new folder.

Response:
def create_folder(query, default_name=None, default_path=None):
    """Shows a user dialog for folder creation

    A dialog is opened with the prompt `query`. The current path is set to the last path that was opened/created. The
    roots of all libraries is added to the list of shortcut folders.

    :param str query: Prompt asking the user for a specific folder
    :param str default_name: Default name of the folder to be created
    :param str default_path: Path in which the folder is created if the user doesn't specify a path
    :return: Path created by the user or `default_path`\`default_name` if no path was specified or None if none of the
      paths is valid
    :rtype: str
    """
    from gi.repository import Gtk
    from os.path import expanduser, dirname, join, exists, isdir
    from rafcon.core.storage.storage import STATEMACHINE_FILE
    from rafcon.gui.singleton import main_window_controller
    from rafcon.gui.runtime_config import global_runtime_config
    last_path = global_runtime_config.get_config_value('LAST_PATH_OPEN_SAVE', "")

    if last_path and isdir(last_path) and not exists(join(last_path, STATEMACHINE_FILE)):
        pass
    elif last_path:
        last_path = dirname(last_path)
    else:
        last_path = expanduser('~')

    dialog = Gtk.FileChooserDialog(query,
                                   None,
                                   Gtk.FileChooserAction.CREATE_FOLDER,
                                   (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                    Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
    # Allows confirming with Enter and double-click
    dialog.set_default_response(Gtk.ResponseType.OK)
    if main_window_controller:
        dialog.set_transient_for(main_window_controller.view.get_top_widget())
    dialog.set_current_folder(last_path)
    if default_name:
        dialog.set_current_name(default_name)
    dialog.set_show_hidden(False)

    # Add library roots to list of shortcut folders
    add_library_root_path_to_shortcut_folders_of_dialog(dialog)

    response = dialog.run()

    if response != Gtk.ResponseType.OK:
        dialog.destroy()
        if default_path and default_name:
            default = os.path.join(default_path, default_name)
            if os.path.isdir(default):
                return default
        return None

    path = dialog.get_filename()
    dialog.destroy()

    if os.path.isdir(path):
        global_runtime_config.set_config_value('LAST_PATH_OPEN_SAVE', path)
        return path
    return None


Instruction:
Create a Python 3 function to
create a new state - machine when the user clicks on the + next to the tabs

Response:
def add_state_machine(widget, event=None):
    """Create a new state-machine when the user clicks on the '+' next to the tabs"""
    logger.debug("Creating new state-machine...")
    root_state = HierarchyState("new root state")
    state_machine = StateMachine(root_state)
    rafcon.core.singleton.state_machine_manager.add_state_machine(state_machine)


Instruction:
Write a Python 3 function for
calling when the View was registered

Response:
def register_view(self, view):
        """Called when the View was registered"""
        super(StateMachinesEditorController, self).register_view(view)
        self.view['notebook'].connect('switch-page', self.on_switch_page)

        # Add all already open state machines
        for state_machine in self.model.state_machines.values():
            self.add_graphical_state_machine_editor(state_machine)


Instruction:
Make a summary of the following Python 3 code
def register_actions(self, shortcut_manager):
        shortcut_manager.add_callback_for_action('close', self.on_close_shortcut)

        # Call register_action of parent in order to register actions for child controllers
        super(StateMachinesEditorController, self).register_actions(shortcut_manager)

Response: Register callback methods fot triggered actions.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def close_state_machine(self, widget, page_number, event=None):
        page = widget.get_nth_page(page_number)
        for tab_info in self.tabs.values():
            if tab_info['page'] is page:
                state_machine_m = tab_info['state_machine_m']
                self.on_close_clicked(event, state_machine_m, None, force=False)
                return

Response: Triggered when the close button in the tab is clicked


Instruction:
Here you have a function in Python 3, explain what it does
def on_close_shortcut(self, *args):
        state_machine_m = self.model.get_selected_state_machine_model()
        if state_machine_m is None:
            return
        self.on_close_clicked(None, state_machine_m, None, force=False)

Response: Close selected state machine


Instruction:
Here you have a function in Python 3, explain what it does
def add_graphical_state_machine_editor(self, state_machine_m):
        assert isinstance(state_machine_m, StateMachineModel)

        sm_id = state_machine_m.state_machine.state_machine_id
        logger.debug("Create new graphical editor for state machine with id %s" % str(sm_id))

        graphical_editor_view = GraphicalEditorGaphasView(state_machine_m)
        graphical_editor_ctrl = GraphicalEditorGaphasController(state_machine_m, graphical_editor_view)

        self.add_controller(sm_id, graphical_editor_ctrl)

        tab, tab_label = create_tab_header('', self.on_close_clicked, self.on_mouse_right_click,
                                           state_machine_m, 'refused')
        set_tab_label_texts(tab_label, state_machine_m, state_machine_m.state_machine.marked_dirty)

        page = graphical_editor_view['main_frame']

        self.view.notebook.append_page(page, tab)
        self.view.notebook.set_tab_reorderable(page, True)
        page.show_all()

        self.tabs[sm_id] = {'page': page,
                            'state_machine_m': state_machine_m,
                            'file_system_path': state_machine_m.state_machine.file_system_path,
                            'marked_dirty': state_machine_m.state_machine.marked_dirty,
                            'root_state_name': state_machine_m.state_machine.root_state.name}

        self.observe_model(state_machine_m)
        graphical_editor_view.show()
        self.view.notebook.show()
        self.last_focused_state_machine_ids.append(sm_id)

Response: Add a new state machine to the state machine view


Instruction:
Given the following Python 3 function, write the documentation
def notification_selected_sm_changed(self, model, prop_name, info):
        selected_state_machine_id = self.model.selected_state_machine_id
        if selected_state_machine_id is None:
            return

        page_id = self.get_page_num(selected_state_machine_id)

        # to retrieve the current tab colors
        number_of_pages = self.view["notebook"].get_n_pages()
        old_label_colors = list(range(number_of_pages))
        for p in range(number_of_pages):
            page = self.view["notebook"].get_nth_page(p)
            label = self.view["notebook"].get_tab_label(page).get_child().get_children()[0]

            # old_label_colors[p] = label.get_style().fg[Gtk.StateType.NORMAL]
            old_label_colors[p] = label.get_style_context().get_color(Gtk.StateType.NORMAL)

        if not self.view.notebook.get_current_page() == page_id:
            self.view.notebook.set_current_page(page_id)

        # set the old colors
        for p in range(number_of_pages):
            page = self.view["notebook"].get_nth_page(p)
            label = self.view["notebook"].get_tab_label(page).get_child().get_children()[0]
            # Gtk TODO
            style = label.get_style_context()

Response: When a new state machine is selected make sure the tab is open


Instruction:
Can you write a function in Python 3 where it
updates the tab label if needed because system path root state name or marked_dirty flag changed .

Response:
def update_state_machine_tab_label(self, state_machine_m):
        """ Updates tab label if needed because system path, root state name or marked_dirty flag changed

        :param StateMachineModel state_machine_m: State machine model that has changed
        :return:
        """
        sm_id = state_machine_m.state_machine.state_machine_id
        if sm_id in self.tabs:
            sm = state_machine_m.state_machine
            # create new tab label if tab label properties are not up to date
            if not self.tabs[sm_id]['marked_dirty'] == sm.marked_dirty or \
                    not self.tabs[sm_id]['file_system_path'] == sm.file_system_path or \
                    not self.tabs[sm_id]['root_state_name'] == sm.root_state.name:

                label = self.view["notebook"].get_tab_label(self.tabs[sm_id]["page"]).get_child().get_children()[0]
                set_tab_label_texts(label, state_machine_m, unsaved_changes=sm.marked_dirty)

                self.tabs[sm_id]['file_system_path'] = sm.file_system_path
                self.tabs[sm_id]['marked_dirty'] = sm.marked_dirty
                self.tabs[sm_id]['root_state_name'] = sm.root_state.name
        else:
            logger.warning("State machine '{0}' tab label can not be updated there is no tab.".format(sm_id))


Instruction:
Write a Python 3 function that can
trigger when the close button of a state machine tab is clicked

Response:
def on_close_clicked(self, event, state_machine_m, result, force=False):
        """Triggered when the close button of a state machine tab is clicked

        Closes state machine if it is saved. Otherwise gives the user the option to 'Close without Saving' or to 'Cancel
        the Close Operation'

        :param state_machine_m: The selected state machine model.
        """
        from rafcon.core.singleton import state_machine_execution_engine, state_machine_manager
        force = True if event is not None and hasattr(event, 'state') \
                        and event.get_state() & Gdk.ModifierType.SHIFT_MASK \
                        and event.get_state() & Gdk.ModifierType.CONTROL_MASK else force

        def remove_state_machine_m():
            state_machine_id = state_machine_m.state_machine.state_machine_id
            if state_machine_id in self.model.state_machine_manager.state_machines:
                self.model.state_machine_manager.remove_state_machine(state_machine_id)

        def push_sm_running_dialog():

            message_string = "The state machine is still running. Are you sure you want to close?"
            dialog = RAFCONButtonDialog(message_string, ["Stop and close", "Cancel"],
                                        message_type=Gtk.MessageType.QUESTION, parent=self.get_root_window())
            response_id = dialog.run()
            dialog.destroy()
            if response_id == 1:
                logger.debug("State machine execution is being stopped")
                state_machine_execution_engine.stop()
                state_machine_execution_engine.join()
                # wait for gui is needed; otherwise the signals related to the execution engine cannot
                # be processed properly by the state machine under destruction
                rafcon.gui.utils.wait_for_gui()
                remove_state_machine_m()
                return True
            elif response_id == 2:
                logger.debug("State machine execution will keep running")
            return False

        def push_sm_dirty_dialog():

            sm_id = state_machine_m.state_machine.state_machine_id
            root_state_name = state_machine_m.root_state.state.name
            message_string = "There are unsaved changes in the state machine '{0}' with id {1}. Do you want to close " \
                             "the state machine anyway?".format(root_state_name, sm_id)
            dialog = RAFCONButtonDialog(message_string, ["Close without saving", "Cancel"],
                                        message_type=Gtk.MessageType.QUESTION, parent=self.get_root_window())
            response_id = dialog.run()
            dialog.destroy()
            if response_id == 1:  # Close without saving pressed
                remove_state_machine_m()
                return True
            else:
                logger.debug("Closing of state machine canceled")
            return False

        # sm running
        if not state_machine_execution_engine.finished_or_stopped() and \
                state_machine_manager.active_state_machine_id == state_machine_m.state_machine.state_machine_id:
            return push_sm_running_dialog()
        # close is forced -> sm not saved
        elif force:
            remove_state_machine_m()
            return True
        # sm dirty -> save sm request dialog
        elif state_machine_m.state_machine.marked_dirty:
            return push_sm_dirty_dialog()
        else:
            remove_state_machine_m()
            return True


Instruction:
Explain what the following Python 3 code does
def close_all_pages(self):
        state_machine_m_list = [tab['state_machine_m'] for tab in self.tabs.values()]
        for state_machine_m in state_machine_m_list:
            self.on_close_clicked(None, state_machine_m, None, force=True)

Response: Closes all tabs of the state machines editor.


Instruction:
Make a summary of the following Python 3 code
def refresh_state_machines(self, state_machine_ids):
        # remember current selected state machine id
        currently_selected_sm_id = None
        if self.model.get_selected_state_machine_model():
            currently_selected_sm_id = self.model.get_selected_state_machine_model().state_machine.state_machine_id

        # create a dictionary from state machine id to state machine path and one for tab page number for recovery
        state_machine_path_by_sm_id = {}
        page_num_by_sm_id = {}
        for sm_id, sm in self.model.state_machine_manager.state_machines.items():
            # the sm.base_path is only None if the state machine has never been loaded or saved before
            if sm_id in state_machine_ids and sm.file_system_path is not None:
                state_machine_path_by_sm_id[sm_id] = sm.file_system_path
                page_num_by_sm_id[sm_id] = self.get_page_num(sm_id)

        # close all state machine in list and remember if one was not closed
        for sm_id in state_machine_ids:
            was_closed = self.on_close_clicked(None, self.model.state_machines[sm_id], None, force=True)
            if not was_closed and sm_id in page_num_by_sm_id:
                logger.info("State machine with id {0} will not be re-open because was not closed.".format(sm_id))
                del state_machine_path_by_sm_id[sm_id]
                del page_num_by_sm_id[sm_id]

        # reload state machines from file system
        try:
            self.model.state_machine_manager.open_state_machines(state_machine_path_by_sm_id)
        except AttributeError as e:
            logger.warning("Not all state machines were re-open because {0}".format(e))
        import rafcon.gui.utils
        rafcon.gui.utils.wait_for_gui()  # TODO check again this is needed  to secure that all sm-models are generated

        # recover tab arrangement
        self.rearrange_state_machines(page_num_by_sm_id)

        # recover initial selected state machine and case handling if now state machine is open anymore
        if currently_selected_sm_id:
            # case if only unsaved state machines are open
            if currently_selected_sm_id in self.model.state_machine_manager.state_machines:
                self.set_active_state_machine(currently_selected_sm_id)

Response: Refreshes the state machine tabs with the given list of state machines.


Instruction:
Can you tell what is the following Python 3 function doing
def refresh_all_state_machines(self):
        self.refresh_state_machines(list(self.model.state_machine_manager.state_machines.keys()))

Response: Refreshes all state machines tabs


Instruction:
Implement a function in Python 3 to
switch the state machine execution engine for the main window controller listens to.

Response:
def switch_state_machine_execution_engine(self, new_state_machine_execution_engine):
        """
        Switch the state machine execution engine the main window controller listens to.
        :param new_state_machine_execution_engine: the new state machine execution engine for this controller
        :return:
        """
        # relieve old one
        self.relieve_model(self.state_machine_execution_model)

        # register new
        self.state_machine_execution_model = new_state_machine_execution_engine
        self.observe_model(self.state_machine_execution_model)


Instruction:
Implement a Python 3 function for
marking all state machines with execution - running style class.

Response:
def execution_engine_model_changed(self, model, prop_name, info):
        """High light active state machine. """

        notebook = self.view['notebook']
        active_state_machine_id = self.model.state_machine_manager.active_state_machine_id

        if active_state_machine_id is None:
            # un-mark all state machine that are marked with execution-running style class
            for tab in self.tabs.values():
                label = notebook.get_tab_label(tab['page']).get_child().get_children()[0]
                if label.get_style_context().has_class(constants.execution_running_style_class):
                    label.get_style_context().remove_class(constants.execution_running_style_class)
        else:
            # mark active state machine with execution-running style class
            page = self.get_page_for_state_machine_id(active_state_machine_id)
            if page:
                label = notebook.get_tab_label(page).get_child().get_children()[0]
                label.get_style_context().add_class(constants.execution_running_style_class)


Instruction:
Implement a Python 3 function for
returning a tuple that holds the state as yaml - strings and its meta data in a dictionary.

Response:
def get_state_tuple(state, state_m=None):
    """ Generates a tuple that holds the state as yaml-strings and its meta data in a dictionary.
    The tuple consists of:
    [0] json_str for state,
    [1] dict of child_state tuples,
    [2] dict of model_meta-data of self and elements
    [3] path of state in state machine
    [4] script_text
    [5] file system path
    [6] semantic data
    #   states-meta - [state-, transitions-, data_flows-, outcomes-, inputs-, outputs-, scopes, states-meta]

    :param rafcon.core.states.state.State state: The state that should be stored
    :return: state_tuple tuple
    """
    state_str = json.dumps(state, cls=JSONObjectEncoder,
                           indent=4, check_circular=False, sort_keys=True)

    state_tuples_dict = {}
    if isinstance(state, ContainerState):
        # print(state.states, "\n")
        for child_state_id, child_state in state.states.items():
            # print("child_state: %s" % child_state_id, child_state, "\n")
            state_tuples_dict[child_state_id] = get_state_tuple(child_state)

    state_meta_dict = {} if state_m is None else get_state_element_meta(state_m)

    script_content = state.script.script if isinstance(state, ExecutionState) else None

    state_tuple = (state_str, state_tuples_dict, state_meta_dict, state.get_path(), script_content,
                   state.file_system_path, copy.deepcopy(state.semantic_data))

    return state_tuple


Instruction:
Make a summary of the following Python 3 code
def meta_dump_or_deepcopy(meta):
    if DEBUG_META_REFERENCES:  # debug copy
        from rafcon.gui.helpers.meta_data import meta_data_reference_check
        meta_data_reference_check(meta)
    return copy.deepcopy(meta)

Response: Function to observe meta data vivi - dict copy process and to debug it at one point


Instruction:
Explain what the following Python 3 code does
def undo(self):
        # logger.verbose("#H# STATE_MACHINE_UNDO STARTED")
        state = self.state_machine.root_state

        self.set_root_state_to_version(state, self.before_storage)

Response:
General Undo that takes all elements in the parent and
        and sets the state to the root state.


Instruction:
Implement a function in Python 3 to
get the ImageSurface object if possible and return it.

Response:
def get_cached_image(self, width, height, zoom, parameters=None, clear=False):
        """Get ImageSurface object, if possible, cached

        The method checks whether the image was already rendered. This is done by comparing the passed size and
        parameters with those of the last image. If they are equal, the cached image is returned. Otherwise,
        a new ImageSurface with the specified dimensions is created and returned.
        :param width: The width of the image
        :param height: The height of the image
        :param zoom: The current scale/zoom factor
        :param parameters: The parameters used for the image
        :param clear: If True, the cache is emptied, thus the image won't be retrieved from cache
        :returns: The flag is True when the image is retrieved from the cache, otherwise False; The cached image
          surface or a blank one with the desired size; The zoom parameter when the image was stored
        :rtype: bool, ImageSurface, float
        """
        global MAX_ALLOWED_AREA
        if not parameters:
            parameters = {}

        if self.__compare_parameters(width, height, zoom, parameters) and not clear:
            return True, self.__image, self.__zoom

        # Restrict image surface size to prevent excessive use of memory
        while True:
            try:
                self.__limiting_multiplicator = 1
                area = width * zoom * self.__zoom_multiplicator * height * zoom * self.__zoom_multiplicator
                if area > MAX_ALLOWED_AREA:
                    self.__limiting_multiplicator = sqrt(MAX_ALLOWED_AREA / area)

                image = ImageSurface(self.__format, int(ceil(width * zoom * self.multiplicator)),
                                     int(ceil(height * zoom * self.multiplicator)))
                break  # If we reach this point, the area was successfully allocated and we can break the loop
            except Error:
                MAX_ALLOWED_AREA *= 0.8

        self.__set_cached_image(image, width, height, zoom, parameters)
        return False, self.__image, zoom


Instruction:
Can you write a function in Python 3 where it
draws a cached image on the context

Response:
def copy_image_to_context(self, context, position, rotation=0, zoom=None):
        """Draw a cached image on the context

        :param context: The Cairo context to draw on
        :param position: The position od the image
        """
        if not zoom:
            zoom = self.__zoom
        zoom_multiplicator = zoom * self.multiplicator
        context.save()
        context.scale(1. / zoom_multiplicator, 1. / zoom_multiplicator)

        image_position = round(position[0] * zoom_multiplicator), round(position[1] * zoom_multiplicator)
        context.translate(*image_position)
        context.rotate(rotation)
        context.set_source_surface(self.__image, 0, 0)

        context.paint()
        context.restore()


Instruction:
Can you create a Python 3 function that
creates a temporary cairo context for the image surface

Response:
def get_context_for_image(self, zoom):
        """Creates a temporary cairo context for the image surface

        :param zoom: The current scaling factor
        :return: Cairo context to draw on
        """
        cairo_context = Context(self.__image)
        cairo_context.scale(zoom * self.multiplicator, zoom * self.multiplicator)
        return cairo_context


Instruction:
Make a summary of the following Python 3 code
def __compare_parameters(self, width, height, zoom, parameters):

        # Deactivated caching
        if not global_gui_config.get_config_value('ENABLE_CACHING', True):
            return False

        # Empty cache
        if not self.__image:
            return False

        # Changed image size
        if self.__width != width or self.__height != height:
            return False

        # Current zoom greater then prepared zoom
        if zoom > self.__zoom * self.__zoom_multiplicator:
            return False

        # Current zoom much smaller than prepared zoom, causes high memory usage and imperfect anti-aliasing
        if zoom < self.__zoom / self.__zoom_multiplicator:
            return False

        # Changed drawing parameter
        for key in parameters:
            try:
                if key not in self.__last_parameters or self.__last_parameters[key] != parameters[key]:
                    return False
            except (AttributeError, ValueError):
                # Some values cannot be compared and raise an exception on comparison (e.g. numpy.ndarray). In this
                # case, just return False and do not cache.
                try:
                    # Catch at least the ndarray-case, as this could occure relatively often
                    import numpy
                    if isinstance(self.__last_parameters[key], numpy.ndarray):
                        return numpy.array_equal(self.__last_parameters[key], parameters[key])
                except ImportError:
                    return False
                return False

        return True

Response: Compare the parameters of a cached image with the current image size and the current zoom and the parameters used for the image.


Instruction:
Make a summary of the following Python 3 code
def post_setup_plugins(parser_result):
    if not isinstance(parser_result, dict):
        parser_result = vars(parser_result)
    plugins.run_post_inits(parser_result)

Response: Calls the post init hubs


Instruction:
Can you create a Python 3 function that
ensures that the environmental variable RAFCON_LIB_PATH is existent and sets up the internal version of the object.

Response:
def setup_environment():
    """Ensures that the environmental variable RAFCON_LIB_PATH is existent
    """
    try:
        from gi.repository import GLib
        user_data_folder = GLib.get_user_data_dir()
    except ImportError:
        user_data_folder = join(os.path.expanduser("~"), ".local", "share")
    rafcon_root_path = dirname(realpath(rafcon.__file__))
    user_library_folder = join(user_data_folder, "rafcon", "libraries")

    # The RAFCON_LIB_PATH points to a path with common RAFCON libraries
    # If the env variable is not set, we have to determine it. In the future, this should always be
    # ~/.local/share/rafcon/libraries, but for backward compatibility, also a relative RAFCON path is supported
    if not os.environ.get('RAFCON_LIB_PATH', None):
        if exists(user_library_folder):
            os.environ['RAFCON_LIB_PATH'] = user_library_folder
        else:
            os.environ['RAFCON_LIB_PATH'] = join(dirname(dirname(rafcon_root_path)), 'share', 'libraries')

    # Install dummy _ builtin function in case i18.setup_l10n() is not called
    if sys.version_info >= (3,):
        import builtins as builtins23
    else:
        import __builtin__ as builtins23
    if "_" not in builtins23.__dict__:
        builtins23.__dict__["_"] = lambda s: s


Instruction:
Implement a Python 3 function for
setting up the argument parser with the required arguments

Response:
def setup_argument_parser():
    """Sets up teh parser with the required arguments

    :return: The parser object
    """
    default_config_path = filesystem.get_default_config_path()
    filesystem.create_path(default_config_path)

    parser = core_singletons.argument_parser
    parser.add_argument('-o', '--open', type=parse_state_machine_path, dest='state_machine_path', metavar='path',
                        nargs='+', help="specify directories of state-machines that shall be opened. The path must "
                                        "contain a statemachine.json file")
    parser.add_argument('-c', '--config', type=config_path, metavar='path', dest='config_path',
                        default=default_config_path, nargs='?', const=default_config_path,
                        help="path to the configuration file config.yaml. Use 'None' to prevent the generation of "
                             "a config file and use the default configuration. Default: {0}".format(default_config_path))
    parser.add_argument('-r', '--remote', action='store_true', help="remote control mode")
    parser.add_argument('-s', '--start_state_path', metavar='path', dest='start_state_path', default=None, nargs='?',
                        help="path within a state machine to the state that should be launched. The state path "
                             "consists of state ids (e.g. QPOXGD/YVWJKZ whereof QPOXGD is the root state and YVWJKZ "
                             "it's child state to start from).")
    return parser


Instruction:
Implement a function in Python 3 to
load the core configuration from the specified path and uses its content for further setup

Response:
def setup_configuration(config_path):
    """Loads the core configuration from the specified path and uses its content for further setup

    :param config_path: Path to the core config file
    """
    if config_path is not None:
        config_path, config_file = filesystem.separate_folder_path_and_file_name(config_path)
        global_config.load(config_file=config_file, path=config_path)
    else:
        global_config.load(path=config_path)

    # Initialize libraries
    core_singletons.library_manager.initialize()


Instruction:
Write a Python 3 script to
execute the specified state machine

Response:
def open_state_machine(state_machine_path):
    """Executes the specified state machine

    :param str state_machine_path: The file path to the state machine
    :return StateMachine: The loaded state machine
    """
    sm = storage.load_state_machine_from_path(state_machine_path)
    core_singletons.state_machine_manager.add_state_machine(sm)

    return sm


Instruction:
Explain what the following Python 3 code does
def wait_for_state_machine_finished(state_machine):
    global _user_abort

    from rafcon.core.states.execution_state import ExecutionState
    if not isinstance(state_machine.root_state, ExecutionState):
        while len(state_machine.execution_histories[0]) < 1:
            time.sleep(0.1)
    else:
        time.sleep(0.5)

    while state_machine.root_state.state_execution_status is not StateExecutionStatus.INACTIVE:
        try:
            state_machine.root_state.concurrency_queue.get(timeout=1)
            # this check triggers if the state machine could not be stopped in the signal handler
            if _user_abort:
                return
        except Empty:
            pass
        # no logger output here to make it easier for the parser
        logger.verbose("RAFCON live signal")

Response: wait for a state machine to finish its execution


Instruction:
Implement a function in Python 3 to
stop the reactor if the state machine has finished.

Response:
def stop_reactor_on_state_machine_finish(state_machine):
    """ Wait for a state machine to be finished and stops the reactor

    :param state_machine: the state machine to synchronize with
    """
    wait_for_state_machine_finished(state_machine)
    from twisted.internet import reactor
    if reactor.running:
        plugins.run_hook("pre_destruction")
        reactor.callFromThread(reactor.stop)


Instruction:
Given the following Python 3 function, write the documentation
async def wait_until_ready(
        self, timeout: Optional[float] = None, no_raise: bool = False
    ) -> bool:
        """
        Waits for the underlying node to become ready.

        If no_raise is set, returns false when a timeout occurs instead of propogating TimeoutError.
        A timeout of None means to wait indefinitely.
        """
        if self.node.ready.is_set():
            return True

        try:
            return await self.node.wait_until_ready(timeout=timeout)
        except asyncio.TimeoutError:
            if no_raise:
                return False
            else:
                raise

Response: Waits until the underlying node is ready.


Instruction:
How would you implement a function in Python 3 that
connects to the voice channel associated with this Player.

Response:
async def connect(self):
        """
        Connects to the voice channel associated with this Player.
        """
        await self.node.join_voice_channel(self.channel.guild.id, self.channel.id)


Instruction:
How would you explain what the following Python 3 function does
async def move_to(self, channel: discord.VoiceChannel):
        if channel.guild != self.channel.guild:
            raise TypeError("Cannot move to a different guild.")

        self.channel = channel
        await self.connect()

Response: Moves this player to a voice channel.


Instruction:
How would you code a function in Python 3 to
disconnect this player from its voice channel.

Response:
async def disconnect(self, requested=True):
        """
        Disconnects this player from it's voice channel.
        """
        if self.state == PlayerState.DISCONNECTING:
            return

        await self.update_state(PlayerState.DISCONNECTING)
        if not requested:
            log.debug(
                f"Forcing player disconnect for guild {self.channel.guild.id}"
                f" due to player manager request."
            )

        guild_id = self.channel.guild.id
        voice_ws = self.node.get_voice_ws(guild_id)

        if not voice_ws.closed:
            await voice_ws.voice_state(guild_id, None)

        await self.node.destroy_guild(guild_id)
        await self.close()

        self.manager.remove_player(self)


Instruction:
Given the following Python 3 function, write the documentation
async def handle_event(self, event: "node.LavalinkEvents", extra):
        if event == LavalinkEvents.TRACK_END:
            if extra == TrackEndReason.FINISHED:
                await self.play()
            else:
                self._is_playing = False

Response: Handles various events related to a given event.


Instruction:
Explain what the following Python 3 code does
async def handle_player_update(self, state: "node.PlayerState"):
        if state.position > self.position:
            self._is_playing = True
        self.position = state.position

Response: Handles player updates from lavalink.


Instruction:
Write a Python 3 script to
add a track to the queue.

Response:
def add(self, requester: discord.User, track: Track):
        """
        Adds a track to the queue.

        Parameters
        ----------
        requester : discord.User
            User who requested the track.
        track : Track
            Result from any of the lavalink track search methods.
        """
        track.requester = requester
        self.queue.append(track)


Instruction:
Can you create a Python 3 function that
starts playback from lavalink.

Response:
async def play(self):
        """
        Starts playback from lavalink.
        """
        if self.repeat and self.current is not None:
            self.queue.append(self.current)

        self.current = None
        self.position = 0
        self._paused = False

        if not self.queue:
            await self.stop()
        else:
            self._is_playing = True
            if self.shuffle:
                track = self.queue.pop(randrange(len(self.queue)))
            else:
                track = self.queue.pop(0)

            self.current = track
            log.debug("Assigned current.")
            await self.node.play(self.channel.guild.id, track)


Instruction:
Can you tell what is the following Python 3 function doing
async def stop(self):
        await self.node.stop(self.channel.guild.id)
        self.queue = []
        self.current = None
        self.position = 0
        self._paused = False

Response: Stops playback from lavalink.


Instruction:
How would you code a function in Python 3 to
pause the current song.

Response:
async def pause(self, pause: bool = True):
        """
        Pauses the current song.

        Parameters
        ----------
        pause : bool
            Set to ``False`` to resume.
        """
        self._paused = pause
        await self.node.pause(self.channel.guild.id, pause)


Instruction:
Given the following Python 3 function, write the documentation
async def set_volume(self, volume: int):
        self._volume = max(min(volume, 150), 0)
        await self.node.volume(self.channel.guild.id, self.volume)

Response: Sets the volume of the current object.


Instruction:
Create a Python 3 function to
seek to a position.

Response:
async def seek(self, position: int):
        """
        If the track allows it, seeks to a position.

        Parameters
        ----------
        position : int
            Between 0 and track length.
        """
        if self.current.seekable:
            position = max(min(position, self.current.length), 0)
            await self.node.seek(self.channel.guild.id, position)


Instruction:
Implement a function in Python 3 to
create a new Player object for the given channel.

Response:
async def create_player(self, channel: discord.VoiceChannel) -> Player:
        """
        Connects to a discord voice channel.

        This function is safe to repeatedly call as it will return an existing
        player if there is one.

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

        Returns
        -------
        Player
            The created Player object.
        """
        if self._already_in_guild(channel):
            p = self.get_player(channel.guild.id)
            await p.move_to(channel)
        else:
            p = Player(self, channel)
            await p.connect()
            self._player_dict[channel.guild.id] = p
            await self.refresh_player_state(p)
        return p


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_player(self, guild_id: int) -> Player:
        if guild_id in self._player_dict:
            return self._player_dict[guild_id]
        raise KeyError("No such player for that guild.")

Response: Gets a Player object from a guild ID.


Instruction:
Given the following Python 3 function, write the documentation
def resource_filename(package_or_requirement, resource_name):
    if pkg_resources.resource_exists(package_or_requirement, resource_name):
        return pkg_resources.resource_filename(package_or_requirement, resource_name)

    path = _search_in_share_folders(package_or_requirement, resource_name)

    if path:
        return path

    raise RuntimeError("Resource {} not found in {}".format(package_or_requirement, resource_name))

Response:
Similar to pkg_resources. resource_filename but also looks in a predefined list of paths to find the resource in which the resource is found via pkg_resources
   .


Instruction:
How would you code a function in Python 3 to
return True if the resource exists in the resource tree otherwise False.

Response:
def resource_exists(package_or_requirement, resource_name):
    """
    Similar to pkg_resources.resource_exists but if the resource it not found via pkg_resources
    it also looks in a predefined list of paths in order to find the resource

    :param package_or_requirement: the module in which the resource resides
    :param resource_name: the name of the resource
    :return: a flag if the file exists
    :rtype: bool
    """
    if pkg_resources.resource_exists(package_or_requirement, resource_name):
        return True

    path = _search_in_share_folders(package_or_requirement, resource_name)

    return True if path else False


Instruction:
Make a summary of the following Python 3 code
def resource_string(package_or_requirement, resource_name):
    with open(resource_filename(package_or_requirement, resource_name), 'r') as resource_file:
        return resource_file.read()

Response: Returns the content of a resource in the order they were found


Instruction:
Explain what the following Python 3 code does
def load_plugins():
    plugins = os.environ.get('RAFCON_PLUGIN_PATH', '')
    plugin_list = set(plugins.split(os.pathsep))
    global plugin_dict
    for plugin_path in plugin_list:
        if not plugin_path:
            continue
        plugin_path = os.path.expandvars(os.path.expanduser(plugin_path)).strip()
        if not os.path.exists(plugin_path):
            logger.error("The specified plugin path does not exist: {}".format(plugin_path))
            continue
        dir_name, plugin_name = os.path.split(plugin_path.rstrip('/'))
        logger.info("Found plugin '{}' at {}".format(plugin_name, plugin_path))
        sys.path.insert(0, dir_name)
        if plugin_name in plugin_dict:
            logger.error("Plugin '{}' already loaded".format(plugin_name))
        else:
            try:
                module = importlib.import_module(plugin_name)
                plugin_dict[plugin_name] = module
                logger.info("Successfully loaded plugin '{}'".format(plugin_name))
            except ImportError as e:
                logger.error("Could not import plugin '{}': {}\n{}".format(plugin_name, e, str(traceback.format_exc())))

Response: Loads all plugins specified in the RAFCON_PLUGIN_PATH environment variable and stores them in the global plugin_dict.


Instruction:
Write a Python 3 function that can
run the passed hook on all registered plugins ArcGIS plugins

Response:
def run_hook(hook_name, *args, **kwargs):
    """Runs the passed hook on all registered plugins

    The function checks, whether the hook is available in the plugin.

    :param hook_name: Name of the hook, corresponds to the function name being called
    :param args: Arguments
    :param kwargs: Keyword arguments
    """
    for module in plugin_dict.values():
        if hasattr(module, "hooks") and callable(getattr(module.hooks, hook_name, None)):
            getattr(module.hooks, hook_name)(*args, **kwargs)


Instruction:
Write a Python 3 function that can
determine the model class required for holding a given state instance

Response:
def get_state_model_class_for_state(state):
    """Determines the model required for the given state class

    :param state: Instance of a state (ExecutionState, BarrierConcurrencyState, ...)
    :return: The model class required for holding such a state instance
    """
    from rafcon.gui.models.state import StateModel
    from rafcon.gui.models.container_state import ContainerStateModel
    from rafcon.gui.models.library_state import LibraryStateModel
    if isinstance(state, ContainerState):
        return ContainerStateModel
    elif isinstance(state, LibraryState):
        return LibraryStateModel
    elif isinstance(state, State):
        return StateModel
    else:
        logger.warning("There is not model for state of type {0} {1}".format(type(state), state))
        return None


Instruction:
Explain what the following Python 3 code does
def update_is_start(self):
        self.is_start = self.state.is_root_state or \
                        self.parent is None or \
                        isinstance(self.parent.state, LibraryState) or \
                        self.state.state_id == self.state.parent.start_state_id

Response:
Updates the is_start property of the state
 initCause


Instruction:
Implement a Python 3 function for
preparing the model for destruction.

Response:
def prepare_destruction(self, recursive=True):
        """Prepares the model for destruction

        Recursively un-registers all observers and removes references to child models
        """
        if self.state is None:
            logger.verbose("Multiple calls of prepare destruction for {0}".format(self))
        self.destruction_signal.emit()
        try:
            self.unregister_observer(self)
        except KeyError:  # Might happen if the observer was already unregistered
            logger.verbose("Observer already unregistered!")
            pass
        if recursive:
            if self.income:
                self.income.prepare_destruction()
            for port in self.input_data_ports[:] + self.output_data_ports[:] + self.outcomes[:]:
                port.prepare_destruction()
        del self.input_data_ports[:]
        del self.output_data_ports[:]
        del self.outcomes[:]
        self.state = None
        self.input_data_ports = None
        self.output_data_ports = None
        self.income = None
        self.outcomes = None
        # History TODO: these are needed by the modification history
        # self.action_signal = None
        # self.meta_signal = None
        # self.destruction_signal = None
        self.observe = None
        super(AbstractStateModel, self).prepare_destruction()


Instruction:
Explain what the following Python 3 code does
def get_state_machine_m(self, two_factor_check=True):
        from rafcon.gui.singleton import state_machine_manager_model
        state_machine = self.state.get_state_machine()
        if state_machine:
            if state_machine.state_machine_id in state_machine_manager_model.state_machines:
                sm_m = state_machine_manager_model.state_machines[state_machine.state_machine_id]
                if not two_factor_check or sm_m.get_state_model_by_path(self.state.get_path()) is self:
                    return sm_m
                else:
                    logger.debug("State model requesting its state machine model parent seems to be obsolete. "
                                 "This is a hint to duplicated models and dirty coding")

        return None

Response: Get the respective state machine model


Instruction:
How would you implement a function in Python 3 that
returns the input data port model for the given data port id

Response:
def get_input_data_port_m(self, data_port_id):
        """Returns the input data port model for the given data port id

        :param data_port_id: The data port id to search for
        :return: The model of the data port with the given id
        """
        for data_port_m in self.input_data_ports:
            if data_port_m.data_port.data_port_id == data_port_id:
                return data_port_m
        return None


Instruction:
Make a summary of the following Python 3 code
def get_output_data_port_m(self, data_port_id):
        for data_port_m in self.output_data_ports:
            if data_port_m.data_port.data_port_id == data_port_id:
                return data_port_m
        return None

Response: Returns the output data port model for the given data port id


Instruction:
Create a Python 3 function to
search and returns the model of a data port of a given state model

Response:
def get_data_port_m(self, data_port_id):
        """Searches and returns the model of a data port of a given state

        The method searches a port with the given id in the data ports of the given state model. If the state model
        is a container state, not only the input and output data ports are looked at, but also the scoped variables.

        :param data_port_id: The data port id to be searched
        :return: The model of the data port or None if it is not found
        """
        from itertools import chain
        data_ports_m = chain(self.input_data_ports, self.output_data_ports)
        for data_port_m in data_ports_m:
            if data_port_m.data_port.data_port_id == data_port_id:
                return data_port_m
        return None


Instruction:
Given the following Python 3 function, write the documentation
def get_outcome_m(self, outcome_id):
        for outcome_m in self.outcomes:
            if outcome_m.outcome.outcome_id == outcome_id:
                return outcome_m
        return False

Response: Returns the outcome model with the given id


Instruction:
Can you generate a brief explanation for the following Python 3 code
def meta_changed(self, model, prop_name, info):
        msg = info.arg
        # print("meta_changed state: ", model, prop_name, info)
        if msg.notification is None:
            # Meta data of this state was changed, add information about notification to the signal message
            notification = Notification(model, prop_name, info)
            msg = msg._replace(notification=notification)
            # print("DONE0 ", msg)

        if self.parent is not None:
            # Notify parent about change of meta data
            info.arg = msg
            self.parent.meta_changed(model, prop_name, info)
            # print("DONE1 ", msg)
        elif not msg.change.startswith('sm_notification_'):  # Prevent recursive call
            # If we are the root state, inform the state machine model by emitting our own meta signal.
            # To make the signal distinguishable for a change of meta data to our state, the change property of
            # the message is prepended with 'sm_notification_'
            msg = msg._replace(change='sm_notification_' + msg.change)
            self.meta_signal.emit(msg)
            # print("DONE2 ", msg)
        else:
            # print("DONE3 NOTHING")
            pass

Response: This method notifies the parent state about changes made to the meta data of the current state of the object.


Instruction:
How would you code a function in Python 3 to
load the meta data of the state model from the file system.

Response:
def load_meta_data(self, path=None):
        """Load meta data of state model from the file system

        The meta data of the state model is loaded from the file system and stored in the meta property of the model.
        Existing meta data is removed. Also the meta data of all state elements (data ports, outcomes,
        etc) are loaded, as those stored in the same file as the meta data of the state.

        This is either called on the __init__ of a new state model or if a state model for a container state is created,
        which then calls load_meta_data for all its children.

        :param str path: Optional file system path to the meta data file. If not given, the path will be derived from
            the state's path on the filesystem
        :return: if meta data file was loaded True otherwise False
        :rtype: bool
        """
        # TODO: for an Execution state this method is called for each hierarchy level again and again, still?? check it!
        # print("1AbstractState_load_meta_data: ", path, not path)
        if not path:
            path = self.state.file_system_path
        # print("2AbstractState_load_meta_data: ", path)
        if path is None:
            self.meta = Vividict({})
            return False
        path_meta_data = os.path.join(path, storage.FILE_NAME_META_DATA)

        # TODO: Should be removed with next minor release
        if not os.path.exists(path_meta_data):
            logger.debug("Because meta data was not found in {0} use backup option {1}"
                         "".format(path_meta_data, os.path.join(path, storage.FILE_NAME_META_DATA_OLD)))
            path_meta_data = os.path.join(path, storage.FILE_NAME_META_DATA_OLD)
            # TODO use the following logger message to debug meta data load process and to avoid maybe repetitive loads
            # if not os.path.exists(path_meta_data):
            #     logger.info("path not found {0}".format(path_meta_data))

        try:
            # print("try to load meta data from {0} for state {1}".format(path_meta_data, self.state))
            tmp_meta = storage.load_data_file(path_meta_data)
        except ValueError as e:
            # if no element which is newly generated log a warning
            # if os.path.exists(os.path.dirname(path)):
            #     logger.debug("Because '{1}' meta data of {0} was not loaded properly.".format(self, e))
            if not path.startswith(constants.RAFCON_TEMP_PATH_STORAGE) and not os.path.exists(os.path.dirname(path)):
                logger.debug("Because '{1}' meta data of {0} was not loaded properly.".format(self, e))
            tmp_meta = {}

        # JSON returns a dict, which must be converted to a Vividict
        tmp_meta = Vividict(tmp_meta)

        if tmp_meta:
            self._parse_for_element_meta_data(tmp_meta)
            # assign the meta data to the state
            self.meta = tmp_meta
            self.meta_signal.emit(MetaSignalMsg("load_meta_data", "all", True))
            return True
        else:
            # print("nothing to parse", tmp_meta)
            return False


Instruction:
Write a Python 3 script for
storing the meta data of the state model to the file system.

Response:
def store_meta_data(self, copy_path=None):
        """Save meta data of state model to the file system

        This method generates a dictionary of the meta data of the state together with the meta data of all state
        elements (data ports, outcomes, etc.) and stores it on the filesystem.
        Secure that the store meta data method is called after storing the core data otherwise the last_stored_path is
        maybe wrong or None.
        The copy path is considered to be a state machine file system path but not the current one but e.g.
        of a as copy saved state machine. The meta data will be stored in respective relative state folder in the state
        machine  hierarchy. This folder has to exist.
        Dues the core elements of the state machine has to be stored first.

        :param str copy_path: Optional copy path if meta data is not stored to the file system path of state machine
        """
        if copy_path:
            meta_file_path_json = os.path.join(copy_path, self.state.get_storage_path(), storage.FILE_NAME_META_DATA)
        else:
            if self.state.file_system_path is None:
                logger.error("Meta data of {0} can be stored temporary arbitrary but by default first after the "
                             "respective state was stored and a file system path is set.".format(self))
                return
            meta_file_path_json = os.path.join(self.state.file_system_path, storage.FILE_NAME_META_DATA)
        meta_data = deepcopy(self.meta)
        self._generate_element_meta_data(meta_data)
        storage_utils.write_dict_to_json(meta_data, meta_file_path_json)


Instruction:
Create a Python 3 function to
dismiss current meta data and copy meta data from given state model

Response:
def copy_meta_data_from_state_m(self, source_state_m):
        """Dismiss current meta data and copy meta data from given state model

        The meta data of the given state model is used as meta data for this state. Also the meta data of all state
        elements (data ports, outcomes, etc.) is overwritten with the meta data of the elements of the given state.

        :param source_state_m: State model to load the meta data from
        """

        self.meta = deepcopy(source_state_m.meta)

        for input_data_port_m in self.input_data_ports:
            source_data_port_m = source_state_m.get_input_data_port_m(input_data_port_m.data_port.data_port_id)
            input_data_port_m.meta = deepcopy(source_data_port_m.meta)
        for output_data_port_m in self.output_data_ports:
            source_data_port_m = source_state_m.get_output_data_port_m(output_data_port_m.data_port.data_port_id)
            output_data_port_m.meta = deepcopy(source_data_port_m.meta)
        for outcome_m in self.outcomes:
            source_outcome_m = source_state_m.get_outcome_m(outcome_m.outcome.outcome_id)
            outcome_m.meta = deepcopy(source_outcome_m.meta)
        self.income.meta = deepcopy(source_state_m.income.meta)

        self.meta_signal.emit(MetaSignalMsg("copy_state_m", "all", True))


Instruction:
Write a Python 3 function that can
load meta data for state elements in the state meta data file.

Response:
def _parse_for_element_meta_data(self, meta_data):
        """Load meta data for state elements

        The meta data of the state meta data file also contains the meta data for state elements (data ports,
        outcomes, etc). This method parses the loaded meta data for each state element model. The meta data of the
        elements is removed from the passed dictionary.

        :param meta_data: Dictionary of loaded meta data
        """
        # print("_parse meta data", meta_data)
        for data_port_m in self.input_data_ports:
            self._copy_element_meta_data_from_meta_file_data(meta_data, data_port_m, "input_data_port",
                                                             data_port_m.data_port.data_port_id)
        for data_port_m in self.output_data_ports:
            self._copy_element_meta_data_from_meta_file_data(meta_data, data_port_m, "output_data_port",
                                                             data_port_m.data_port.data_port_id)
        for outcome_m in self.outcomes:
            self._copy_element_meta_data_from_meta_file_data(meta_data, outcome_m, "outcome",
                                                             outcome_m.outcome.outcome_id)
        if "income" in meta_data:
            if "gui" in meta_data and "editor_gaphas" in meta_data["gui"] and \
                    "income" in meta_data["gui"]["editor_gaphas"]:  # chain necessary to prevent key generation
                del meta_data["gui"]["editor_gaphas"]["income"]
        elif "gui" in meta_data and "editor_gaphas" in meta_data["gui"] and \
                "income" in meta_data["gui"]["editor_gaphas"]:  # chain necessary to prevent key generation in meta data
            meta_data["income"]["gui"]["editor_gaphas"] = meta_data["gui"]["editor_gaphas"]["income"]
            del meta_data["gui"]["editor_gaphas"]["income"]
        self._copy_element_meta_data_from_meta_file_data(meta_data, self.income, "income", "")


Instruction:
Given the following Python 3 function, write the documentation
def _copy_element_meta_data_from_meta_file_data(meta_data, element_m, element_name, element_id):
        meta_data_element_id = element_name + str(element_id)
        meta_data_element = meta_data[meta_data_element_id]
        # print(meta_data_element_id, element_m, meta_data_element)
        element_m.meta = meta_data_element
        del meta_data[meta_data_element_id]

Response: Helper method to copy the meta data of the given element from the given meta data dictionary.


Instruction:
Write a Python 3 script for
generating meta data for state elements and add it to the given meta data dictionary.

Response:
def _generate_element_meta_data(self, meta_data):
        """Generate meta data for state elements and add it to the given dictionary

        This method retrieves the meta data of the state elements (data ports, outcomes, etc) and adds it to the
        given meta data dictionary.

        :param meta_data: Dictionary of meta data
        """
        for data_port_m in self.input_data_ports:
            self._copy_element_meta_data_to_meta_file_data(meta_data, data_port_m, "input_data_port",
                                                           data_port_m.data_port.data_port_id)
        for data_port_m in self.output_data_ports:
            self._copy_element_meta_data_to_meta_file_data(meta_data, data_port_m, "output_data_port",
                                                           data_port_m.data_port.data_port_id)
        for outcome_m in self.outcomes:
            self._copy_element_meta_data_to_meta_file_data(meta_data, outcome_m, "outcome",
                                                           outcome_m.outcome.outcome_id)

        self._copy_element_meta_data_to_meta_file_data(meta_data, self.income, "income", "")


Instruction:
Explain what the following Python 3 code does
def save_file_data(self, path):
        sm = self.model.state.get_state_machine()
        if sm.marked_dirty and not self.saved_initial:
            try:
                # Save the file before opening it to update the applied changes. Use option create_full_path=True
                # to assure that temporary state_machines' script files are saved to
                # (their path doesnt exist when not saved)
                filesystem.write_file(os.path.join(path, storage.SCRIPT_FILE),
                                      self.view.get_text(), create_full_path=True)
            except IOError as e:
                # Only happens if the file doesnt exist yet and would be written to the temp folder.
                # The method write_file doesnt create the path
                logger.error('The operating system raised an error: {}'.format(e))
            self.saved_initial = True

Response: Saves the file data to the given path.


Instruction:
Implement a function in Python 3 to
load the script file and sets the script text.

Response:
def load_and_set_file_content(self, file_system_path):
        """ Implements the abstract method of the ExternalEditor class.
        """
        content = filesystem.read_file(file_system_path, storage.SCRIPT_FILE)
        if content is not None:
            self.set_script_text(content)


Instruction:
Implement a function in Python 3 to
trigger when the Apply button in source editor is clicked.

Response:
def apply_clicked(self, button):
        """Triggered when the Apply button in the source editor is clicked.

        """
        if isinstance(self.model.state, LibraryState):
            logger.warning("It is not allowed to modify libraries.")
            self.view.set_text("")
            return

        # Ugly workaround to give user at least some feedback about the parser
        # Without the loop, this function would block the GTK main loop and the log message would appear after the
        # function has finished
        # TODO: run parser in separate thread
        while Gtk.events_pending():
            Gtk.main_iteration_do(False)

        # get script
        current_text = self.view.get_text()

        # Directly apply script if linter was deactivated
        if not self.view['pylint_check_button'].get_active():
            self.set_script_text(current_text)
            return

        logger.debug("Parsing execute script...")
        with open(self.tmp_file, "w") as text_file:
            text_file.write(current_text)

        # clear astroid module cache, see http://stackoverflow.com/questions/22241435/pylint-discard-cached-file-state
        MANAGER.astroid_cache.clear()
        lint_config_file = resource_filename(rafcon.__name__, "pylintrc")
        args = ["--rcfile={}".format(lint_config_file)]  # put your own here
        with contextlib.closing(StringIO()) as dummy_buffer:
            json_report = JSONReporter(dummy_buffer.getvalue())
            try:
                lint.Run([self.tmp_file] + args, reporter=json_report, exit=False)
            except:
                logger.exception("Could not run linter to check script")
        os.remove(self.tmp_file)

        if json_report.messages:
            def on_message_dialog_response_signal(widget, response_id):
                if response_id == 1:
                    self.set_script_text(current_text)
                else:
                    logger.debug("The script was not saved")
                widget.destroy()

            message_string = "Are you sure that you want to save this file?\n\nThe following errors were found:"

            line = None
            for message in json_report.messages:
                (error_string, line) = self.format_error_string(message)
                message_string += "\n\n" + error_string

            # focus line of error
            if line:
                tbuffer = self.view.get_buffer()
                start_iter = tbuffer.get_start_iter()
                start_iter.set_line(int(line)-1)
                tbuffer.place_cursor(start_iter)
                message_string += "\n\nThe line was focused in the source editor."
                self.view.scroll_to_cursor_onscreen()

            # select state to show source editor
            sm_m = state_machine_manager_model.get_state_machine_model(self.model)
            if sm_m.selection.get_selected_state() is not self.model:
                sm_m.selection.set(self.model)

            dialog = RAFCONButtonDialog(message_string, ["Save with errors", "Do not save"],
                               on_message_dialog_response_signal,
                               message_type=Gtk.MessageType.WARNING, parent=self.get_root_window())
            result = dialog.run()
        else:
            self.set_script_text(current_text)


Instruction:
Can you tell what is the following Python 3 function doing
def split_text(text_to_split):
        assert isinstance(text_to_split, string_types)
        try:
            time, rest = text_to_split.split(': ', 1)
            source, message = rest.split(':', 1)
        except ValueError:
            time = source = ""
            message = text_to_split
        return time.strip(), source.strip(), message.strip()

Response: Split the debug text into two parts Time Log Name Debug message


Instruction:
Can you create a Python 3 function that
updates auto scroll mode.

Response:
def update_auto_scroll_mode(self):
        """ Register or un-register signals for follow mode """
        if self._enables['CONSOLE_FOLLOW_LOGGING']:
            if self._auto_scroll_handler_id is None:
                self._auto_scroll_handler_id = self.text_view.connect("size-allocate", self._auto_scroll)
        else:
            if self._auto_scroll_handler_id is not None:
                self.text_view.disconnect(self._auto_scroll_handler_id)
                self._auto_scroll_handler_id = None


Instruction:
Implement a function in Python 3 to
scroll to the end of the text view

Response:
def _auto_scroll(self, *args):
        """ Scroll to the end of the text view """
        adj = self['scrollable'].get_vadjustment()
        adj.set_value(adj.get_upper() - adj.get_page_size())


Instruction:
Explain what the following Python 3 code does
def get_line_number_next_to_cursor_with_string_within(self, s):
        line_number, _ = self.get_cursor_position()
        text_buffer = self.text_view.get_buffer()
        line_iter = text_buffer.get_iter_at_line(line_number)

        # find closest before line with string within
        before_line_number = None
        while line_iter.backward_line():
            if s in self.get_text_of_line(line_iter):
                before_line_number = line_iter.get_line()
                break

        # find closest after line with string within
        after_line_number = None
        while line_iter.forward_line():
            if s in self.get_text_of_line(line_iter):
                after_line_number = line_iter.get_line()
                break

        # take closest one to current position
        if after_line_number is not None and before_line_number is None:
            return after_line_number, after_line_number - line_number
        elif before_line_number is not None and after_line_number is None:
            return before_line_number, line_number - before_line_number
        elif after_line_number is not None and before_line_number is not None:
            after_distance = after_line_number - line_number
            before_distance = line_number - before_line_number
            if after_distance < before_distance:
                return after_line_number, after_distance
            else:
                return before_line_number, before_distance
        else:
            return None, None

Response: Find the line number next occurrence of a string with respect to the cursor position.


Instruction:
Can you write a function in Python 3 where it
sets a global variable in the local variable cache

Response:
def set_variable(self, key, value, per_reference=False, access_key=None, data_type=None):
        """Sets a global variable

        :param key: the key of the global variable to be set
        :param value: the new value of the global variable
        :param per_reference: a flag to decide if the variable should be stored per reference or per value
        :param access_key: if the variable was explicitly locked with the  rafcon.state lock_variable
        :raises exceptions.RuntimeError: if a wrong access key is passed
        """
        key = str(key)  # Ensure that we have the same string type for all keys (under Python2 and 3!)
        if self.variable_exist(key):
            if data_type is None:
                data_type = self.__global_variable_type_dictionary[key]
        else:
            if data_type is None:
                data_type = type(None)
        assert isinstance(data_type, type)
        self.check_value_and_type(value, data_type)

        with self.__global_lock:
            unlock = True
            if self.variable_exist(key):
                if self.is_locked(key) and self.__access_keys[key] != access_key:
                    raise RuntimeError("Wrong access key for accessing global variable")
                elif self.is_locked(key):
                    unlock = False
                else:
                    access_key = self.lock_variable(key, block=True)
            else:
                self.__variable_locks[key] = Lock()
                access_key = self.lock_variable(key, block=True)

            # --- variable locked
            if per_reference:
                self.__global_variable_dictionary[key] = value
                self.__global_variable_type_dictionary[key] = data_type
                self.__variable_references[key] = True
            else:
                self.__global_variable_dictionary[key] = copy.deepcopy(value)
                self.__global_variable_type_dictionary[key] = data_type
                self.__variable_references[key] = False
            # --- release variable

            if unlock:
                self.unlock_variable(key, access_key)

        logger.debug("Global variable '{}' was set to value '{}' with type '{}'".format(key, value, data_type.__name__))


Instruction:
Here you have a function in Python 3, explain what it does
def get_variable(self, key, per_reference=None, access_key=None, default=None):
        key = str(key)
        if self.variable_exist(key):
            unlock = True
            if self.is_locked(key):
                if self.__access_keys[key] == access_key:
                    unlock = False
                else:
                    if not access_key:
                        access_key = self.lock_variable(key, block=True)
                    else:
                        raise RuntimeError("Wrong access key for accessing global variable")
            else:
                access_key = self.lock_variable(key, block=True)

            # --- variable locked
            if self.variable_can_be_referenced(key):
                if per_reference or per_reference is None:
                    return_value = self.__global_variable_dictionary[key]
                else:
                    return_value = copy.deepcopy(self.__global_variable_dictionary[key])
            else:
                if per_reference:
                    self.unlock_variable(key, access_key)
                    raise RuntimeError("Variable cannot be accessed by reference")
                else:
                    return_value = copy.deepcopy(self.__global_variable_dictionary[key])
            # --- release variable

            if unlock:
                self.unlock_variable(key, access_key)
            return return_value
        else:
            # logger.warning("Global variable '{0}' not existing, returning default value".format(key))
            return default

Response: Fetches the value of a global variable in the local variable cache.


Instruction:
How would you implement a function in Python 3 that
checks whether the value of the variable can be returned by reference by reference

Response:
def variable_can_be_referenced(self, key):
        """Checks whether the value of the variable can be returned by reference

        :param str key: Name of the variable
        :return: True if value of variable can be returned by reference, False else
        """
        key = str(key)
        return key in self.__variable_references and self.__variable_references[key]


Instruction:
Make a summary of the following Python 3 code
def delete_variable(self, key):
        key = str(key)
        if self.is_locked(key):
            raise RuntimeError("Global variable is locked")

        with self.__global_lock:
            if key in self.__global_variable_dictionary:
                access_key = self.lock_variable(key, block=True)
                del self.__global_variable_dictionary[key]
                self.unlock_variable(key, access_key)
                del self.__variable_locks[key]
                del self.__variable_references[key]
            else:
                raise AttributeError("Global variable %s does not exist!" % str(key))

        logger.debug("Global variable %s was deleted!" % str(key))

Response: Deletes a global variable in the local variable cache.


Instruction:
Implement a Python 3 function for
locking a global variable in blocking mode

Response:
def lock_variable(self, key, block=False):
        """Locks a global variable

        :param key: the key of the global variable to be locked
        :param block: a flag to specify if to wait for locking the variable in blocking mode
        """
        key = str(key)
        # watch out for releasing the __dictionary_lock properly
        try:
            if key in self.__variable_locks:
                # acquire without arguments is blocking
                lock_successful = self.__variable_locks[key].acquire(False)
                if lock_successful or block:
                    if (not lock_successful) and block:  # case: lock could not be acquired => wait for it as block=True
                        duration = 0.
                        loop_time = 0.1
                        while not self.__variable_locks[key].acquire(False):
                            time.sleep(loop_time)
                            duration += loop_time
                            if int(duration*10) % 20 == 0:
                                # while loops informs the user about long locked variables
                                logger.verbose("Variable '{2}' is locked and thread {0} waits already {1} seconds to "
                                               "access it.".format(currentThread(), duration, key))
                    access_key = global_variable_id_generator()
                    self.__access_keys[key] = access_key
                    return access_key
                else:
                    logger.warning("Global variable {} already locked".format(str(key)))
                    return False
            else:
                logger.error("Global variable key {} does not exist".format(str(key)))
                return False
        except Exception as e:
            logger.error("Exception thrown: {}".format(str(e)))
            return False


Instruction:
Explain what the following Python 3 code does
def unlock_variable(self, key, access_key, force=False):
        key = str(key)
        if self.__access_keys[key] == access_key or force:
            if key in self.__variable_locks:
                if self.is_locked(key):
                    self.__variable_locks[key].release()
                    return True
                else:
                    logger.error("Global variable {} is not locked, thus cannot unlock it".format(str(key)))
                    return False
            else:
                raise AttributeError("Global variable %s does not exist!" % str(key))
        else:
            raise RuntimeError("Wrong access key for accessing global variable")

Response: Unlocks a global variable with the given key.


Instruction:
How would you explain what the following Python 3 function does
def set_locked_variable(self, key, access_key, value):
        return self.set_variable(key, value, per_reference=False, access_key=access_key)

Response: Set an already locked global variable


Instruction:
Implement a function in Python 3 to
return the value of a global variable that is already locked by the given key

Response:
def get_locked_variable(self, key, access_key):
        """Returns the value of an global variable that is already locked

        :param key: the key of the global variable
        :param access_key: the access_key to the global variable that is already locked
        """
        return self.get_variable(key, per_reference=False, access_key=access_key)