repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
DLR-RM/RAFCON
source/rafcon/gui/helpers/state_machine.py
substitute_selected_state
def substitute_selected_state(state, as_template=False, keep_name=False): """ Substitute the selected state with the handed state :param rafcon.core.states.state.State state: A state of any functional type that derives from State :param bool as_template: The flag determines if a handed the state of type LibraryState is insert as template :return: """ # print("substitute_selected_state", state, as_template) assert isinstance(state, State) from rafcon.core.states.barrier_concurrency_state import DeciderState if isinstance(state, DeciderState): raise ValueError("State of type DeciderState can not be substituted.") smm_m = rafcon.gui.singleton.state_machine_manager_model if not smm_m.selected_state_machine_id: logger.error("Selected state machine can not be found, please select a state within a state machine first.") return False selection = smm_m.state_machines[smm_m.selected_state_machine_id].selection selected_state_m = selection.get_selected_state() if len(selection.states) != 1: logger.error("Please select exactly one state for the substitution") return False if is_selection_inside_of_library_state(selected_elements=[selected_state_m]): logger.warning("Substitute is not performed because target state is inside of a library state.") return gui_helper_state.substitute_state_as(selected_state_m, state, as_template, keep_name) return True
python
def substitute_selected_state(state, as_template=False, keep_name=False): """ Substitute the selected state with the handed state :param rafcon.core.states.state.State state: A state of any functional type that derives from State :param bool as_template: The flag determines if a handed the state of type LibraryState is insert as template :return: """ # print("substitute_selected_state", state, as_template) assert isinstance(state, State) from rafcon.core.states.barrier_concurrency_state import DeciderState if isinstance(state, DeciderState): raise ValueError("State of type DeciderState can not be substituted.") smm_m = rafcon.gui.singleton.state_machine_manager_model if not smm_m.selected_state_machine_id: logger.error("Selected state machine can not be found, please select a state within a state machine first.") return False selection = smm_m.state_machines[smm_m.selected_state_machine_id].selection selected_state_m = selection.get_selected_state() if len(selection.states) != 1: logger.error("Please select exactly one state for the substitution") return False if is_selection_inside_of_library_state(selected_elements=[selected_state_m]): logger.warning("Substitute is not performed because target state is inside of a library state.") return gui_helper_state.substitute_state_as(selected_state_m, state, as_template, keep_name) return True
[ "def", "substitute_selected_state", "(", "state", ",", "as_template", "=", "False", ",", "keep_name", "=", "False", ")", ":", "# print(\"substitute_selected_state\", state, as_template)", "assert", "isinstance", "(", "state", ",", "State", ")", "from", "rafcon", ".", ...
Substitute the selected state with the handed state :param rafcon.core.states.state.State state: A state of any functional type that derives from State :param bool as_template: The flag determines if a handed the state of type LibraryState is insert as template :return:
[ "Substitute", "the", "selected", "state", "with", "the", "handed", "state" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/state_machine.py#L947-L976
train
40,300
DLR-RM/RAFCON
source/rafcon/core/state_elements/transition.py
Transition.modify_origin
def modify_origin(self, from_state, from_outcome): """Set both from_state and from_outcome at the same time to modify transition origin :param str from_state: State id of the origin state :param int from_outcome: Outcome id of the origin port :raises exceptions.ValueError: If parameters have wrong types or the new transition is not valid """ if not (from_state is None and from_outcome is None): if not isinstance(from_state, string_types): raise ValueError("Invalid transition origin port: from_state must be a string") if not isinstance(from_outcome, int): raise ValueError("Invalid transition origin port: from_outcome must be of type int") old_from_state = self.from_state old_from_outcome = self.from_outcome self._from_state = from_state self._from_outcome = from_outcome valid, message = self._check_validity() if not valid: self._from_state = old_from_state self._from_outcome = old_from_outcome raise ValueError("The transition origin could not be changed: {0}".format(message))
python
def modify_origin(self, from_state, from_outcome): """Set both from_state and from_outcome at the same time to modify transition origin :param str from_state: State id of the origin state :param int from_outcome: Outcome id of the origin port :raises exceptions.ValueError: If parameters have wrong types or the new transition is not valid """ if not (from_state is None and from_outcome is None): if not isinstance(from_state, string_types): raise ValueError("Invalid transition origin port: from_state must be a string") if not isinstance(from_outcome, int): raise ValueError("Invalid transition origin port: from_outcome must be of type int") old_from_state = self.from_state old_from_outcome = self.from_outcome self._from_state = from_state self._from_outcome = from_outcome valid, message = self._check_validity() if not valid: self._from_state = old_from_state self._from_outcome = old_from_outcome raise ValueError("The transition origin could not be changed: {0}".format(message))
[ "def", "modify_origin", "(", "self", ",", "from_state", ",", "from_outcome", ")", ":", "if", "not", "(", "from_state", "is", "None", "and", "from_outcome", "is", "None", ")", ":", "if", "not", "isinstance", "(", "from_state", ",", "string_types", ")", ":",...
Set both from_state and from_outcome at the same time to modify transition origin :param str from_state: State id of the origin state :param int from_outcome: Outcome id of the origin port :raises exceptions.ValueError: If parameters have wrong types or the new transition is not valid
[ "Set", "both", "from_state", "and", "from_outcome", "at", "the", "same", "time", "to", "modify", "transition", "origin" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/state_elements/transition.py#L112-L134
train
40,301
DLR-RM/RAFCON
source/rafcon/core/state_elements/transition.py
Transition.modify_target
def modify_target(self, to_state, to_outcome=None): """Set both to_state and to_outcome at the same time to modify transition target :param str to_state: State id of the target state :param int to_outcome: Outcome id of the target port :raises exceptions.ValueError: If parameters have wrong types or the new transition is not valid """ if not (to_state is None and (to_outcome is not int and to_outcome is not None)): if not isinstance(to_state, string_types): raise ValueError("Invalid transition target port: to_state must be a string") if not isinstance(to_outcome, int) and to_outcome is not None: raise ValueError("Invalid transition target port: to_outcome must be of type int or None (if to_state " "is of type str)") old_to_state = self.to_state old_to_outcome = self.to_outcome self._to_state = to_state self._to_outcome = to_outcome valid, message = self._check_validity() if not valid: self._to_state = old_to_state self._to_outcome = old_to_outcome raise ValueError("The transition target could not be changed: {0}".format(message))
python
def modify_target(self, to_state, to_outcome=None): """Set both to_state and to_outcome at the same time to modify transition target :param str to_state: State id of the target state :param int to_outcome: Outcome id of the target port :raises exceptions.ValueError: If parameters have wrong types or the new transition is not valid """ if not (to_state is None and (to_outcome is not int and to_outcome is not None)): if not isinstance(to_state, string_types): raise ValueError("Invalid transition target port: to_state must be a string") if not isinstance(to_outcome, int) and to_outcome is not None: raise ValueError("Invalid transition target port: to_outcome must be of type int or None (if to_state " "is of type str)") old_to_state = self.to_state old_to_outcome = self.to_outcome self._to_state = to_state self._to_outcome = to_outcome valid, message = self._check_validity() if not valid: self._to_state = old_to_state self._to_outcome = old_to_outcome raise ValueError("The transition target could not be changed: {0}".format(message))
[ "def", "modify_target", "(", "self", ",", "to_state", ",", "to_outcome", "=", "None", ")", ":", "if", "not", "(", "to_state", "is", "None", "and", "(", "to_outcome", "is", "not", "int", "and", "to_outcome", "is", "not", "None", ")", ")", ":", "if", "...
Set both to_state and to_outcome at the same time to modify transition target :param str to_state: State id of the target state :param int to_outcome: Outcome id of the target port :raises exceptions.ValueError: If parameters have wrong types or the new transition is not valid
[ "Set", "both", "to_state", "and", "to_outcome", "at", "the", "same", "time", "to", "modify", "transition", "target" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/state_elements/transition.py#L138-L161
train
40,302
DLR-RM/RAFCON
source/rafcon/gui/controllers/global_variable_manager.py
GlobalVariableManagerController.global_variable_is_editable
def global_variable_is_editable(self, gv_name, intro_message='edit'): """Check whether global variable is locked :param str gv_name: Name of global variable to be checked :param str intro_message: Message which is used form a useful logger error message if needed :return: """ if self.model.global_variable_manager.is_locked(gv_name): logger.error("{1} of global variable '{0}' is not possible, as it is locked".format(gv_name, intro_message)) return False return True
python
def global_variable_is_editable(self, gv_name, intro_message='edit'): """Check whether global variable is locked :param str gv_name: Name of global variable to be checked :param str intro_message: Message which is used form a useful logger error message if needed :return: """ if self.model.global_variable_manager.is_locked(gv_name): logger.error("{1} of global variable '{0}' is not possible, as it is locked".format(gv_name, intro_message)) return False return True
[ "def", "global_variable_is_editable", "(", "self", ",", "gv_name", ",", "intro_message", "=", "'edit'", ")", ":", "if", "self", ".", "model", ".", "global_variable_manager", ".", "is_locked", "(", "gv_name", ")", ":", "logger", ".", "error", "(", "\"{1} of glo...
Check whether global variable is locked :param str gv_name: Name of global variable to be checked :param str intro_message: Message which is used form a useful logger error message if needed :return:
[ "Check", "whether", "global", "variable", "is", "locked" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/global_variable_manager.py#L96-L106
train
40,303
DLR-RM/RAFCON
source/rafcon/gui/controllers/global_variable_manager.py
GlobalVariableManagerController.on_add
def on_add(self, widget, data=None): """Create a global variable with default value and select its row Triggered when the add button in the global variables tab is clicked. """ gv_name = "new_global_%s" % self.global_variable_counter self.global_variable_counter += 1 try: self.model.global_variable_manager.set_variable(gv_name, None) except (RuntimeError, AttributeError, TypeError) as e: logger.warning("Addition of new global variable '{0}' failed: {1}".format(gv_name, e)) self.select_entry(gv_name) return True
python
def on_add(self, widget, data=None): """Create a global variable with default value and select its row Triggered when the add button in the global variables tab is clicked. """ gv_name = "new_global_%s" % self.global_variable_counter self.global_variable_counter += 1 try: self.model.global_variable_manager.set_variable(gv_name, None) except (RuntimeError, AttributeError, TypeError) as e: logger.warning("Addition of new global variable '{0}' failed: {1}".format(gv_name, e)) self.select_entry(gv_name) return True
[ "def", "on_add", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "gv_name", "=", "\"new_global_%s\"", "%", "self", ".", "global_variable_counter", "self", ".", "global_variable_counter", "+=", "1", "try", ":", "self", ".", "model", ".", "gl...
Create a global variable with default value and select its row Triggered when the add button in the global variables tab is clicked.
[ "Create", "a", "global", "variable", "with", "default", "value", "and", "select", "its", "row" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/global_variable_manager.py#L108-L120
train
40,304
DLR-RM/RAFCON
source/rafcon/gui/controllers/global_variable_manager.py
GlobalVariableManagerController.on_lock
def on_lock(self, widget, data=None): """Locks respective selected core element""" path_list = None if self.view is not None: model, path_list = self.tree_view.get_selection().get_selected_rows() models = [self.list_store[path][self.MODEL_STORAGE_ID] for path in path_list] if path_list else [] if models: if len(models) > 1: self._logger.warning("Please select only one element to be locked.") try: self.model.global_variable_manager.lock_variable(models[0]) except AttributeError as e: self._logger.warning("The respective core element of {1}.list_store couldn't be locked. -> {0}" "".format(e, self.__class__.__name__)) return True else: self._logger.warning("Please select an element to be locked.")
python
def on_lock(self, widget, data=None): """Locks respective selected core element""" path_list = None if self.view is not None: model, path_list = self.tree_view.get_selection().get_selected_rows() models = [self.list_store[path][self.MODEL_STORAGE_ID] for path in path_list] if path_list else [] if models: if len(models) > 1: self._logger.warning("Please select only one element to be locked.") try: self.model.global_variable_manager.lock_variable(models[0]) except AttributeError as e: self._logger.warning("The respective core element of {1}.list_store couldn't be locked. -> {0}" "".format(e, self.__class__.__name__)) return True else: self._logger.warning("Please select an element to be locked.")
[ "def", "on_lock", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "path_list", "=", "None", "if", "self", ".", "view", "is", "not", "None", ":", "model", ",", "path_list", "=", "self", ".", "tree_view", ".", "get_selection", "(", ")",...
Locks respective selected core element
[ "Locks", "respective", "selected", "core", "element" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/global_variable_manager.py#L122-L138
train
40,305
DLR-RM/RAFCON
source/rafcon/gui/controllers/global_variable_manager.py
GlobalVariableManagerController.remove_core_element
def remove_core_element(self, model): """Remove respective core element of handed global variable name :param str model: String that is the key/gv_name of core element which should be removed :return: """ gv_name = model if self.global_variable_is_editable(gv_name, "Deletion"): try: self.model.global_variable_manager.delete_variable(gv_name) except AttributeError as e: logger.warning("The respective global variable '{1}' couldn't be removed. -> {0}" "".format(e, model))
python
def remove_core_element(self, model): """Remove respective core element of handed global variable name :param str model: String that is the key/gv_name of core element which should be removed :return: """ gv_name = model if self.global_variable_is_editable(gv_name, "Deletion"): try: self.model.global_variable_manager.delete_variable(gv_name) except AttributeError as e: logger.warning("The respective global variable '{1}' couldn't be removed. -> {0}" "".format(e, model))
[ "def", "remove_core_element", "(", "self", ",", "model", ")", ":", "gv_name", "=", "model", "if", "self", ".", "global_variable_is_editable", "(", "gv_name", ",", "\"Deletion\"", ")", ":", "try", ":", "self", ".", "model", ".", "global_variable_manager", ".", ...
Remove respective core element of handed global variable name :param str model: String that is the key/gv_name of core element which should be removed :return:
[ "Remove", "respective", "core", "element", "of", "handed", "global", "variable", "name" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/global_variable_manager.py#L158-L170
train
40,306
DLR-RM/RAFCON
source/rafcon/gui/controllers/global_variable_manager.py
GlobalVariableManagerController.assign_notification_from_gvm
def assign_notification_from_gvm(self, model, prop_name, info): """Handles gtkmvc3 notification from global variable manager Calls update of whole list store in case new variable was added. Avoids to run updates without reasonable change. Holds tree store and updates row elements if is-locked or global variable value changes. """ if info['method_name'] in ['set_locked_variable'] or info['result'] is Exception: return if info['method_name'] in ['lock_variable', 'unlock_variable']: key = info.kwargs.get('key', info.args[1]) if len(info.args) > 1 else info.kwargs['key'] if key in self.list_store_iterators: gv_row_path = self.list_store.get_path(self.list_store_iterators[key]) self.list_store[gv_row_path][self.IS_LOCKED_AS_STRING_STORAGE_ID] = \ str(self.model.global_variable_manager.is_locked(key)) elif info['method_name'] in ['set_variable', 'delete_variable']: if info['method_name'] == 'set_variable': key = info.kwargs.get('key', info.args[1]) if len(info.args) > 1 else info.kwargs['key'] if key in self.list_store_iterators: gv_row_path = self.list_store.get_path(self.list_store_iterators[key]) self.list_store[gv_row_path][self.VALUE_AS_STRING_STORAGE_ID] = \ str(self.model.global_variable_manager.get_representation(key)) self.list_store[gv_row_path][self.DATA_TYPE_AS_STRING_STORAGE_ID] = \ self.model.global_variable_manager.get_data_type(key).__name__ return self.update_global_variables_list_store() else: logger.warning('Notification that is not handled')
python
def assign_notification_from_gvm(self, model, prop_name, info): """Handles gtkmvc3 notification from global variable manager Calls update of whole list store in case new variable was added. Avoids to run updates without reasonable change. Holds tree store and updates row elements if is-locked or global variable value changes. """ if info['method_name'] in ['set_locked_variable'] or info['result'] is Exception: return if info['method_name'] in ['lock_variable', 'unlock_variable']: key = info.kwargs.get('key', info.args[1]) if len(info.args) > 1 else info.kwargs['key'] if key in self.list_store_iterators: gv_row_path = self.list_store.get_path(self.list_store_iterators[key]) self.list_store[gv_row_path][self.IS_LOCKED_AS_STRING_STORAGE_ID] = \ str(self.model.global_variable_manager.is_locked(key)) elif info['method_name'] in ['set_variable', 'delete_variable']: if info['method_name'] == 'set_variable': key = info.kwargs.get('key', info.args[1]) if len(info.args) > 1 else info.kwargs['key'] if key in self.list_store_iterators: gv_row_path = self.list_store.get_path(self.list_store_iterators[key]) self.list_store[gv_row_path][self.VALUE_AS_STRING_STORAGE_ID] = \ str(self.model.global_variable_manager.get_representation(key)) self.list_store[gv_row_path][self.DATA_TYPE_AS_STRING_STORAGE_ID] = \ self.model.global_variable_manager.get_data_type(key).__name__ return self.update_global_variables_list_store() else: logger.warning('Notification that is not handled')
[ "def", "assign_notification_from_gvm", "(", "self", ",", "model", ",", "prop_name", ",", "info", ")", ":", "if", "info", "[", "'method_name'", "]", "in", "[", "'set_locked_variable'", "]", "or", "info", "[", "'result'", "]", "is", "Exception", ":", "return",...
Handles gtkmvc3 notification from global variable manager Calls update of whole list store in case new variable was added. Avoids to run updates without reasonable change. Holds tree store and updates row elements if is-locked or global variable value changes.
[ "Handles", "gtkmvc3", "notification", "from", "global", "variable", "manager" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/global_variable_manager.py#L286-L314
train
40,307
DLR-RM/RAFCON
source/rafcon/gui/controllers/global_variable_manager.py
GlobalVariableManagerController.update_global_variables_list_store
def update_global_variables_list_store(self): """Updates the global variable list store Triggered after creation or deletion of a variable has taken place. """ # logger.info("update") self.list_store_iterators = {} self.list_store.clear() keys = self.model.global_variable_manager.get_all_keys() keys.sort() for key in keys: iter = self.list_store.append([key, self.model.global_variable_manager.get_data_type(key).__name__, str(self.model.global_variable_manager.get_representation(key)), str(self.model.global_variable_manager.is_locked(key)), ]) self.list_store_iterators[key] = iter
python
def update_global_variables_list_store(self): """Updates the global variable list store Triggered after creation or deletion of a variable has taken place. """ # logger.info("update") self.list_store_iterators = {} self.list_store.clear() keys = self.model.global_variable_manager.get_all_keys() keys.sort() for key in keys: iter = self.list_store.append([key, self.model.global_variable_manager.get_data_type(key).__name__, str(self.model.global_variable_manager.get_representation(key)), str(self.model.global_variable_manager.is_locked(key)), ]) self.list_store_iterators[key] = iter
[ "def", "update_global_variables_list_store", "(", "self", ")", ":", "# logger.info(\"update\")", "self", ".", "list_store_iterators", "=", "{", "}", "self", ".", "list_store", ".", "clear", "(", ")", "keys", "=", "self", ".", "model", ".", "global_variable_manager...
Updates the global variable list store Triggered after creation or deletion of a variable has taken place.
[ "Updates", "the", "global", "variable", "list", "store" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/global_variable_manager.py#L316-L332
train
40,308
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/canvas.py
MyCanvas.get_view_for_id
def get_view_for_id(self, view_class, element_id, parent_item=None): """Searches and returns the View for the given id and type :param view_class: The view type to search for :param element_id: The id of element of the searched view :param gaphas.item.Item parent_item: Restrict the search to this parent item :return: The view for the given id or None if not found """ from rafcon.gui.mygaphas.items.state import StateView from rafcon.gui.mygaphas.items.connection import DataFlowView, TransitionView if parent_item is None: items = self.get_all_items() else: items = self.get_children(parent_item) for item in items: if view_class is StateView and isinstance(item, StateView) and item.model.state.state_id == element_id: return item if view_class is TransitionView and isinstance(item, TransitionView) and \ item.model.transition.transition_id == element_id: return item if view_class is DataFlowView and isinstance(item, DataFlowView) and \ item.model.data_flow.data_flow_id == element_id: return item return None
python
def get_view_for_id(self, view_class, element_id, parent_item=None): """Searches and returns the View for the given id and type :param view_class: The view type to search for :param element_id: The id of element of the searched view :param gaphas.item.Item parent_item: Restrict the search to this parent item :return: The view for the given id or None if not found """ from rafcon.gui.mygaphas.items.state import StateView from rafcon.gui.mygaphas.items.connection import DataFlowView, TransitionView if parent_item is None: items = self.get_all_items() else: items = self.get_children(parent_item) for item in items: if view_class is StateView and isinstance(item, StateView) and item.model.state.state_id == element_id: return item if view_class is TransitionView and isinstance(item, TransitionView) and \ item.model.transition.transition_id == element_id: return item if view_class is DataFlowView and isinstance(item, DataFlowView) and \ item.model.data_flow.data_flow_id == element_id: return item return None
[ "def", "get_view_for_id", "(", "self", ",", "view_class", ",", "element_id", ",", "parent_item", "=", "None", ")", ":", "from", "rafcon", ".", "gui", ".", "mygaphas", ".", "items", ".", "state", "import", "StateView", "from", "rafcon", ".", "gui", ".", "...
Searches and returns the View for the given id and type :param view_class: The view type to search for :param element_id: The id of element of the searched view :param gaphas.item.Item parent_item: Restrict the search to this parent item :return: The view for the given id or None if not found
[ "Searches", "and", "returns", "the", "View", "for", "the", "given", "id", "and", "type" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/canvas.py#L121-L144
train
40,309
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/canvas.py
MyCanvas.wait_for_update
def wait_for_update(self, trigger_update=False): """Update canvas and handle all events in the gtk queue :param bool trigger_update: Whether to call update_now() or not """ if trigger_update: self.update_now() from gi.repository import Gtk from gi.repository import GLib from threading import Event event = Event() # Handle all events from gaphas, but not from gtkmvc3 # Make use of the priority, which is higher for gaphas then for gtkmvc3 def priority_handled(event): event.set() priority = (GLib.PRIORITY_HIGH_IDLE + GLib.PRIORITY_DEFAULT_IDLE) / 2 # idle_add is necessary here, as we do not want to block the user from interacting with the GUI # while gaphas is redrawing GLib.idle_add(priority_handled, event, priority=priority) while not event.is_set(): Gtk.main_iteration()
python
def wait_for_update(self, trigger_update=False): """Update canvas and handle all events in the gtk queue :param bool trigger_update: Whether to call update_now() or not """ if trigger_update: self.update_now() from gi.repository import Gtk from gi.repository import GLib from threading import Event event = Event() # Handle all events from gaphas, but not from gtkmvc3 # Make use of the priority, which is higher for gaphas then for gtkmvc3 def priority_handled(event): event.set() priority = (GLib.PRIORITY_HIGH_IDLE + GLib.PRIORITY_DEFAULT_IDLE) / 2 # idle_add is necessary here, as we do not want to block the user from interacting with the GUI # while gaphas is redrawing GLib.idle_add(priority_handled, event, priority=priority) while not event.is_set(): Gtk.main_iteration()
[ "def", "wait_for_update", "(", "self", ",", "trigger_update", "=", "False", ")", ":", "if", "trigger_update", ":", "self", ".", "update_now", "(", ")", "from", "gi", ".", "repository", "import", "Gtk", "from", "gi", ".", "repository", "import", "GLib", "fr...
Update canvas and handle all events in the gtk queue :param bool trigger_update: Whether to call update_now() or not
[ "Update", "canvas", "and", "handle", "all", "events", "in", "the", "gtk", "queue" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/canvas.py#L146-L168
train
40,310
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/canvas.py
ItemProjection._get_value
def _get_value(self): """ Return two delegating variables. Each variable should contain a value attribute with the real value. """ x, y = self._point.x, self._point.y self._px, self._py = self._item_point.canvas.get_matrix_i2i(self._item_point, self._item_target).transform_point(x, y) return self._px, self._py
python
def _get_value(self): """ Return two delegating variables. Each variable should contain a value attribute with the real value. """ x, y = self._point.x, self._point.y self._px, self._py = self._item_point.canvas.get_matrix_i2i(self._item_point, self._item_target).transform_point(x, y) return self._px, self._py
[ "def", "_get_value", "(", "self", ")", ":", "x", ",", "y", "=", "self", ".", "_point", ".", "x", ",", "self", ".", "_point", ".", "y", "self", ".", "_px", ",", "self", ".", "_py", "=", "self", ".", "_item_point", ".", "canvas", ".", "get_matrix_i...
Return two delegating variables. Each variable should contain a value attribute with the real value.
[ "Return", "two", "delegating", "variables", ".", "Each", "variable", "should", "contain", "a", "value", "attribute", "with", "the", "real", "value", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/canvas.py#L211-L219
train
40,311
DLR-RM/RAFCON
source/rafcon/utils/type_helpers.py
convert_string_to_type
def convert_string_to_type(string_value): """Converts a string into a type or class :param string_value: the string to be converted, e.g. "int" :return: The type derived from string_value, e.g. int """ # If the parameter is already a type, return it if string_value in ['None', type(None).__name__]: return type(None) if isinstance(string_value, type) or isclass(string_value): return string_value # Get object associated with string # First check whether we are having a built in type (int, str, etc) if sys.version_info >= (3,): import builtins as builtins23 else: import __builtin__ as builtins23 if hasattr(builtins23, string_value): obj = getattr(builtins23, string_value) if type(obj) is type: return obj # If not, try to locate the module try: obj = locate(string_value) except ErrorDuringImport as e: raise ValueError("Unknown type '{0}'".format(e)) # Check whether object is a type if type(obj) is type: return locate(string_value) # Check whether object is a class if isclass(obj): return obj # Raise error if none is the case raise ValueError("Unknown type '{0}'".format(string_value))
python
def convert_string_to_type(string_value): """Converts a string into a type or class :param string_value: the string to be converted, e.g. "int" :return: The type derived from string_value, e.g. int """ # If the parameter is already a type, return it if string_value in ['None', type(None).__name__]: return type(None) if isinstance(string_value, type) or isclass(string_value): return string_value # Get object associated with string # First check whether we are having a built in type (int, str, etc) if sys.version_info >= (3,): import builtins as builtins23 else: import __builtin__ as builtins23 if hasattr(builtins23, string_value): obj = getattr(builtins23, string_value) if type(obj) is type: return obj # If not, try to locate the module try: obj = locate(string_value) except ErrorDuringImport as e: raise ValueError("Unknown type '{0}'".format(e)) # Check whether object is a type if type(obj) is type: return locate(string_value) # Check whether object is a class if isclass(obj): return obj # Raise error if none is the case raise ValueError("Unknown type '{0}'".format(string_value))
[ "def", "convert_string_to_type", "(", "string_value", ")", ":", "# If the parameter is already a type, return it", "if", "string_value", "in", "[", "'None'", ",", "type", "(", "None", ")", ".", "__name__", "]", ":", "return", "type", "(", "None", ")", "if", "isi...
Converts a string into a type or class :param string_value: the string to be converted, e.g. "int" :return: The type derived from string_value, e.g. int
[ "Converts", "a", "string", "into", "a", "type", "or", "class" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/type_helpers.py#L33-L70
train
40,312
DLR-RM/RAFCON
source/rafcon/utils/type_helpers.py
convert_string_value_to_type_value
def convert_string_value_to_type_value(string_value, data_type): """Helper function to convert a given string to a given data type :param str string_value: the string to convert :param type data_type: the target data type :return: the converted value """ from ast import literal_eval try: if data_type in (str, type(None)): converted_value = str(string_value) elif data_type == int: converted_value = int(string_value) elif data_type == float: converted_value = float(string_value) elif data_type == bool: converted_value = bool(literal_eval(string_value)) elif data_type in (list, dict, tuple): converted_value = literal_eval(string_value) if type(converted_value) != data_type: raise ValueError("Invalid syntax: {0}".format(string_value)) elif data_type == object: try: converted_value = literal_eval(string_value) except (ValueError, SyntaxError): converted_value = literal_eval('"' + string_value + '"') elif isinstance(data_type, type): # Try native type conversion converted_value = data_type(string_value) elif isclass(data_type): # Call class constructor converted_value = data_type(string_value) else: raise ValueError("No conversion from string '{0}' to data type '{0}' defined".format( string_value, data_type.__name__)) except (ValueError, SyntaxError, TypeError) as e: raise AttributeError("Can't convert '{0}' to type '{1}': {2}".format(string_value, data_type.__name__, e)) return converted_value
python
def convert_string_value_to_type_value(string_value, data_type): """Helper function to convert a given string to a given data type :param str string_value: the string to convert :param type data_type: the target data type :return: the converted value """ from ast import literal_eval try: if data_type in (str, type(None)): converted_value = str(string_value) elif data_type == int: converted_value = int(string_value) elif data_type == float: converted_value = float(string_value) elif data_type == bool: converted_value = bool(literal_eval(string_value)) elif data_type in (list, dict, tuple): converted_value = literal_eval(string_value) if type(converted_value) != data_type: raise ValueError("Invalid syntax: {0}".format(string_value)) elif data_type == object: try: converted_value = literal_eval(string_value) except (ValueError, SyntaxError): converted_value = literal_eval('"' + string_value + '"') elif isinstance(data_type, type): # Try native type conversion converted_value = data_type(string_value) elif isclass(data_type): # Call class constructor converted_value = data_type(string_value) else: raise ValueError("No conversion from string '{0}' to data type '{0}' defined".format( string_value, data_type.__name__)) except (ValueError, SyntaxError, TypeError) as e: raise AttributeError("Can't convert '{0}' to type '{1}': {2}".format(string_value, data_type.__name__, e)) return converted_value
[ "def", "convert_string_value_to_type_value", "(", "string_value", ",", "data_type", ")", ":", "from", "ast", "import", "literal_eval", "try", ":", "if", "data_type", "in", "(", "str", ",", "type", "(", "None", ")", ")", ":", "converted_value", "=", "str", "(...
Helper function to convert a given string to a given data type :param str string_value: the string to convert :param type data_type: the target data type :return: the converted value
[ "Helper", "function", "to", "convert", "a", "given", "string", "to", "a", "given", "data", "type" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/type_helpers.py#L73-L109
train
40,313
DLR-RM/RAFCON
source/rafcon/utils/type_helpers.py
type_inherits_of_type
def type_inherits_of_type(inheriting_type, base_type): """Checks whether inheriting_type inherits from base_type :param str inheriting_type: :param str base_type: :return: True is base_type is base of inheriting_type """ assert isinstance(inheriting_type, type) or isclass(inheriting_type) assert isinstance(base_type, type) or isclass(base_type) if inheriting_type == base_type: return True else: if len(inheriting_type.__bases__) != 1: return False return type_inherits_of_type(inheriting_type.__bases__[0], base_type)
python
def type_inherits_of_type(inheriting_type, base_type): """Checks whether inheriting_type inherits from base_type :param str inheriting_type: :param str base_type: :return: True is base_type is base of inheriting_type """ assert isinstance(inheriting_type, type) or isclass(inheriting_type) assert isinstance(base_type, type) or isclass(base_type) if inheriting_type == base_type: return True else: if len(inheriting_type.__bases__) != 1: return False return type_inherits_of_type(inheriting_type.__bases__[0], base_type)
[ "def", "type_inherits_of_type", "(", "inheriting_type", ",", "base_type", ")", ":", "assert", "isinstance", "(", "inheriting_type", ",", "type", ")", "or", "isclass", "(", "inheriting_type", ")", "assert", "isinstance", "(", "base_type", ",", "type", ")", "or", ...
Checks whether inheriting_type inherits from base_type :param str inheriting_type: :param str base_type: :return: True is base_type is base of inheriting_type
[ "Checks", "whether", "inheriting_type", "inherits", "from", "base_type" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/type_helpers.py#L112-L127
train
40,314
openego/eTraGo
etrago/tools/io.py
clear_results_db
def clear_results_db(session): '''Used to clear the result tables in the OEDB. Caution! This deletes EVERY RESULT SET!''' from egoio.db_tables.model_draft import EgoGridPfHvResultBus as BusResult,\ EgoGridPfHvResultBusT as BusTResult,\ EgoGridPfHvResultStorage as StorageResult,\ EgoGridPfHvResultStorageT as StorageTResult,\ EgoGridPfHvResultGenerator as GeneratorResult,\ EgoGridPfHvResultGeneratorT as GeneratorTResult,\ EgoGridPfHvResultLine as LineResult,\ EgoGridPfHvResultLineT as LineTResult,\ EgoGridPfHvResultLoad as LoadResult,\ EgoGridPfHvResultLoadT as LoadTResult,\ EgoGridPfHvResultTransformer as TransformerResult,\ EgoGridPfHvResultTransformerT as TransformerTResult,\ EgoGridPfHvResultMeta as ResultMeta print('Are you sure that you want to clear all results in the OEDB?') choice = '' while choice not in ['y', 'n']: choice = input('(y/n): ') if choice == 'y': print('Are you sure?') choice2 = '' while choice2 not in ['y', 'n']: choice2 = input('(y/n): ') if choice2 == 'y': print('Deleting all results...') session.query(BusResult).delete() session.query(BusTResult).delete() session.query(StorageResult).delete() session.query(StorageTResult).delete() session.query(GeneratorResult).delete() session.query(GeneratorTResult).delete() session.query(LoadResult).delete() session.query(LoadTResult).delete() session.query(LineResult).delete() session.query(LineTResult).delete() session.query(TransformerResult).delete() session.query(TransformerTResult).delete() session.query(ResultMeta).delete() session.commit() else: print('Deleting aborted!') else: print('Deleting aborted!')
python
def clear_results_db(session): '''Used to clear the result tables in the OEDB. Caution! This deletes EVERY RESULT SET!''' from egoio.db_tables.model_draft import EgoGridPfHvResultBus as BusResult,\ EgoGridPfHvResultBusT as BusTResult,\ EgoGridPfHvResultStorage as StorageResult,\ EgoGridPfHvResultStorageT as StorageTResult,\ EgoGridPfHvResultGenerator as GeneratorResult,\ EgoGridPfHvResultGeneratorT as GeneratorTResult,\ EgoGridPfHvResultLine as LineResult,\ EgoGridPfHvResultLineT as LineTResult,\ EgoGridPfHvResultLoad as LoadResult,\ EgoGridPfHvResultLoadT as LoadTResult,\ EgoGridPfHvResultTransformer as TransformerResult,\ EgoGridPfHvResultTransformerT as TransformerTResult,\ EgoGridPfHvResultMeta as ResultMeta print('Are you sure that you want to clear all results in the OEDB?') choice = '' while choice not in ['y', 'n']: choice = input('(y/n): ') if choice == 'y': print('Are you sure?') choice2 = '' while choice2 not in ['y', 'n']: choice2 = input('(y/n): ') if choice2 == 'y': print('Deleting all results...') session.query(BusResult).delete() session.query(BusTResult).delete() session.query(StorageResult).delete() session.query(StorageTResult).delete() session.query(GeneratorResult).delete() session.query(GeneratorTResult).delete() session.query(LoadResult).delete() session.query(LoadTResult).delete() session.query(LineResult).delete() session.query(LineTResult).delete() session.query(TransformerResult).delete() session.query(TransformerTResult).delete() session.query(ResultMeta).delete() session.commit() else: print('Deleting aborted!') else: print('Deleting aborted!')
[ "def", "clear_results_db", "(", "session", ")", ":", "from", "egoio", ".", "db_tables", ".", "model_draft", "import", "EgoGridPfHvResultBus", "as", "BusResult", ",", "EgoGridPfHvResultBusT", "as", "BusTResult", ",", "EgoGridPfHvResultStorage", "as", "StorageResult", "...
Used to clear the result tables in the OEDB. Caution! This deletes EVERY RESULT SET!
[ "Used", "to", "clear", "the", "result", "tables", "in", "the", "OEDB", ".", "Caution!", "This", "deletes", "EVERY", "RESULT", "SET!" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L407-L452
train
40,315
openego/eTraGo
etrago/tools/io.py
run_sql_script
def run_sql_script(conn, scriptname='results_md2grid.sql'): """This function runs .sql scripts in the folder 'sql_scripts' """ script_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), 'sql_scripts')) script_str = open(os.path.join(script_dir, scriptname)).read() conn.execution_options(autocommit=True).execute(script_str) return
python
def run_sql_script(conn, scriptname='results_md2grid.sql'): """This function runs .sql scripts in the folder 'sql_scripts' """ script_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), 'sql_scripts')) script_str = open(os.path.join(script_dir, scriptname)).read() conn.execution_options(autocommit=True).execute(script_str) return
[ "def", "run_sql_script", "(", "conn", ",", "scriptname", "=", "'results_md2grid.sql'", ")", ":", "script_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",...
This function runs .sql scripts in the folder 'sql_scripts'
[ "This", "function", "runs", ".", "sql", "scripts", "in", "the", "folder", "sql_scripts" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L693-L701
train
40,316
openego/eTraGo
etrago/tools/io.py
distance
def distance(x0, x1, y0, y1): """ Function that calculates the square of the distance between two points. Parameters ----- x0: x - coordinate of point 0 x1: x - coordinate of point 1 y0: y - coordinate of point 0 y1: y - coordinate of point 1 Returns ------ distance : float square of distance """ # Calculate square of the distance between two points (Pythagoras) distance = (x1.values- x0.values)*(x1.values- x0.values)\ + (y1.values- y0.values)*(y1.values- y0.values) return distance
python
def distance(x0, x1, y0, y1): """ Function that calculates the square of the distance between two points. Parameters ----- x0: x - coordinate of point 0 x1: x - coordinate of point 1 y0: y - coordinate of point 0 y1: y - coordinate of point 1 Returns ------ distance : float square of distance """ # Calculate square of the distance between two points (Pythagoras) distance = (x1.values- x0.values)*(x1.values- x0.values)\ + (y1.values- y0.values)*(y1.values- y0.values) return distance
[ "def", "distance", "(", "x0", ",", "x1", ",", "y0", ",", "y1", ")", ":", "# Calculate square of the distance between two points (Pythagoras)", "distance", "=", "(", "x1", ".", "values", "-", "x0", ".", "values", ")", "*", "(", "x1", ".", "values", "-", "x0...
Function that calculates the square of the distance between two points. Parameters ----- x0: x - coordinate of point 0 x1: x - coordinate of point 1 y0: y - coordinate of point 0 y1: y - coordinate of point 1 Returns ------ distance : float square of distance
[ "Function", "that", "calculates", "the", "square", "of", "the", "distance", "between", "two", "points", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L831-L853
train
40,317
openego/eTraGo
etrago/tools/io.py
calc_nearest_point
def calc_nearest_point(bus1, network): """ Function that finds the geographical nearest point in a network from a given bus. Parameters ----- bus1: float id of bus network: Pypsa network container network including the comparable buses Returns ------ bus0 : float bus_id of nearest point """ bus1_index = network.buses.index[network.buses.index == bus1] forbidden_buses = np.append( bus1_index.values, network.lines.bus1[ network.lines.bus0 == bus1].values) forbidden_buses = np.append( forbidden_buses, network.lines.bus0[network.lines.bus1 == bus1].values) forbidden_buses = np.append( forbidden_buses, network.links.bus0[network.links.bus1 == bus1].values) forbidden_buses = np.append( forbidden_buses, network.links.bus1[network.links.bus0 == bus1].values) x0 = network.buses.x[network.buses.index.isin(bus1_index)] y0 = network.buses.y[network.buses.index.isin(bus1_index)] comparable_buses = network.buses[~network.buses.index.isin( forbidden_buses)] x1 = comparable_buses.x y1 = comparable_buses.y distance = (x1.values - x0.values)*(x1.values - x0.values) + \ (y1.values - y0.values)*(y1.values - y0.values) min_distance = distance.min() bus0 = comparable_buses[(((x1.values - x0.values)*(x1.values - x0.values ) + (y1.values - y0.values)*(y1.values - y0.values)) == min_distance)] bus0 = bus0.index[bus0.index == bus0.index.max()] bus0 = ''.join(bus0.values) return bus0
python
def calc_nearest_point(bus1, network): """ Function that finds the geographical nearest point in a network from a given bus. Parameters ----- bus1: float id of bus network: Pypsa network container network including the comparable buses Returns ------ bus0 : float bus_id of nearest point """ bus1_index = network.buses.index[network.buses.index == bus1] forbidden_buses = np.append( bus1_index.values, network.lines.bus1[ network.lines.bus0 == bus1].values) forbidden_buses = np.append( forbidden_buses, network.lines.bus0[network.lines.bus1 == bus1].values) forbidden_buses = np.append( forbidden_buses, network.links.bus0[network.links.bus1 == bus1].values) forbidden_buses = np.append( forbidden_buses, network.links.bus1[network.links.bus0 == bus1].values) x0 = network.buses.x[network.buses.index.isin(bus1_index)] y0 = network.buses.y[network.buses.index.isin(bus1_index)] comparable_buses = network.buses[~network.buses.index.isin( forbidden_buses)] x1 = comparable_buses.x y1 = comparable_buses.y distance = (x1.values - x0.values)*(x1.values - x0.values) + \ (y1.values - y0.values)*(y1.values - y0.values) min_distance = distance.min() bus0 = comparable_buses[(((x1.values - x0.values)*(x1.values - x0.values ) + (y1.values - y0.values)*(y1.values - y0.values)) == min_distance)] bus0 = bus0.index[bus0.index == bus0.index.max()] bus0 = ''.join(bus0.values) return bus0
[ "def", "calc_nearest_point", "(", "bus1", ",", "network", ")", ":", "bus1_index", "=", "network", ".", "buses", ".", "index", "[", "network", ".", "buses", ".", "index", "==", "bus1", "]", "forbidden_buses", "=", "np", ".", "append", "(", "bus1_index", "...
Function that finds the geographical nearest point in a network from a given bus. Parameters ----- bus1: float id of bus network: Pypsa network container network including the comparable buses Returns ------ bus0 : float bus_id of nearest point
[ "Function", "that", "finds", "the", "geographical", "nearest", "point", "in", "a", "network", "from", "a", "given", "bus", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L856-L912
train
40,318
openego/eTraGo
etrago/tools/io.py
ScenarioBase.map_ormclass
def map_ormclass(self, name): """ Populate _mapped attribute with orm class Parameters ---------- name : str Component part of orm class name. Concatenated with _prefix. """ try: self._mapped[name] = getattr(self._pkg, self._prefix + name) except AttributeError: print('Warning: Relation %s does not exist.' % name)
python
def map_ormclass(self, name): """ Populate _mapped attribute with orm class Parameters ---------- name : str Component part of orm class name. Concatenated with _prefix. """ try: self._mapped[name] = getattr(self._pkg, self._prefix + name) except AttributeError: print('Warning: Relation %s does not exist.' % name)
[ "def", "map_ormclass", "(", "self", ",", "name", ")", ":", "try", ":", "self", ".", "_mapped", "[", "name", "]", "=", "getattr", "(", "self", ".", "_pkg", ",", "self", ".", "_prefix", "+", "name", ")", "except", "AttributeError", ":", "print", "(", ...
Populate _mapped attribute with orm class Parameters ---------- name : str Component part of orm class name. Concatenated with _prefix.
[ "Populate", "_mapped", "attribute", "with", "orm", "class" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L127-L140
train
40,319
openego/eTraGo
etrago/tools/io.py
NetworkScenario.configure_timeindex
def configure_timeindex(self): """ Construct a DateTimeIndex with the queried temporal resolution, start- and end_snapshot. """ try: ormclass = self._mapped['TempResolution'] if self.version: tr = self.session.query(ormclass).filter( ormclass.temp_id == self.temp_id).filter( ormclass.version == self.version).one() else: tr = self.session.query(ormclass).filter( ormclass.temp_id == self.temp_id).one() except (KeyError, NoResultFound): print('temp_id %s does not exist.' % self.temp_id) timeindex = pd.DatetimeIndex(start=tr.start_time, periods=tr.timesteps, freq=tr.resolution) self.timeindex = timeindex[self.start_snapshot - 1: self.end_snapshot] """ pandas.tseries.index.DateTimeIndex : Index of snapshots or timesteps. """
python
def configure_timeindex(self): """ Construct a DateTimeIndex with the queried temporal resolution, start- and end_snapshot. """ try: ormclass = self._mapped['TempResolution'] if self.version: tr = self.session.query(ormclass).filter( ormclass.temp_id == self.temp_id).filter( ormclass.version == self.version).one() else: tr = self.session.query(ormclass).filter( ormclass.temp_id == self.temp_id).one() except (KeyError, NoResultFound): print('temp_id %s does not exist.' % self.temp_id) timeindex = pd.DatetimeIndex(start=tr.start_time, periods=tr.timesteps, freq=tr.resolution) self.timeindex = timeindex[self.start_snapshot - 1: self.end_snapshot] """ pandas.tseries.index.DateTimeIndex : Index of snapshots or timesteps. """
[ "def", "configure_timeindex", "(", "self", ")", ":", "try", ":", "ormclass", "=", "self", ".", "_mapped", "[", "'TempResolution'", "]", "if", "self", ".", "version", ":", "tr", "=", "self", ".", "session", ".", "query", "(", "ormclass", ")", ".", "filt...
Construct a DateTimeIndex with the queried temporal resolution, start- and end_snapshot.
[ "Construct", "a", "DateTimeIndex", "with", "the", "queried", "temporal", "resolution", "start", "-", "and", "end_snapshot", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L186-L210
train
40,320
openego/eTraGo
etrago/tools/io.py
NetworkScenario.fetch_by_relname
def fetch_by_relname(self, name): """ Construct DataFrame with component data from filtered table data. Parameters ---------- name : str Component name. Returns ------- pd.DataFrame Component data. """ ormclass = self._mapped[name] query = self.session.query(ormclass) if name != carr_ormclass: query = query.filter( ormclass.scn_name == self.scn_name) if self.version: query = query.filter(ormclass.version == self.version) # TODO: Naming is not consistent. Change in database required. if name == 'Transformer': name = 'Trafo' df = pd.read_sql(query.statement, self.session.bind, index_col=name.lower() + '_id') if name == 'Link': df['bus0'] = df.bus0.astype(int) df['bus1'] = df.bus1.astype(int) if 'source' in df: df.source = df.source.map(self.id_to_source()) return df
python
def fetch_by_relname(self, name): """ Construct DataFrame with component data from filtered table data. Parameters ---------- name : str Component name. Returns ------- pd.DataFrame Component data. """ ormclass = self._mapped[name] query = self.session.query(ormclass) if name != carr_ormclass: query = query.filter( ormclass.scn_name == self.scn_name) if self.version: query = query.filter(ormclass.version == self.version) # TODO: Naming is not consistent. Change in database required. if name == 'Transformer': name = 'Trafo' df = pd.read_sql(query.statement, self.session.bind, index_col=name.lower() + '_id') if name == 'Link': df['bus0'] = df.bus0.astype(int) df['bus1'] = df.bus1.astype(int) if 'source' in df: df.source = df.source.map(self.id_to_source()) return df
[ "def", "fetch_by_relname", "(", "self", ",", "name", ")", ":", "ormclass", "=", "self", ".", "_mapped", "[", "name", "]", "query", "=", "self", ".", "session", ".", "query", "(", "ormclass", ")", "if", "name", "!=", "carr_ormclass", ":", "query", "=", ...
Construct DataFrame with component data from filtered table data. Parameters ---------- name : str Component name. Returns ------- pd.DataFrame Component data.
[ "Construct", "DataFrame", "with", "component", "data", "from", "filtered", "table", "data", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L223-L262
train
40,321
openego/eTraGo
etrago/tools/io.py
NetworkScenario.series_fetch_by_relname
def series_fetch_by_relname(self, name, column): """ Construct DataFrame with component timeseries data from filtered table data. Parameters ---------- name : str Component name. column : str Component field with timevarying data. Returns ------- pd.DataFrame Component data. """ ormclass = self._mapped[name] # TODO: This is implemented in a not very robust way. id_column = re.findall(r'[A-Z][^A-Z]*', name)[0] + '_' + 'id' id_column = id_column.lower() query = self.session.query( getattr(ormclass, id_column), getattr(ormclass, column)[self.start_snapshot: self.end_snapshot]. label(column)).filter(and_( ormclass.scn_name == self.scn_name, ormclass.temp_id == self.temp_id)) if self.version: query = query.filter(ormclass.version == self.version) df = pd.io.sql.read_sql(query.statement, self.session.bind, columns=[column], index_col=id_column) df.index = df.index.astype(str) # change of format to fit pypsa df = df[column].apply(pd.Series).transpose() try: assert not df.empty df.index = self.timeindex except AssertionError: print("No data for %s in column %s." % (name, column)) return df
python
def series_fetch_by_relname(self, name, column): """ Construct DataFrame with component timeseries data from filtered table data. Parameters ---------- name : str Component name. column : str Component field with timevarying data. Returns ------- pd.DataFrame Component data. """ ormclass = self._mapped[name] # TODO: This is implemented in a not very robust way. id_column = re.findall(r'[A-Z][^A-Z]*', name)[0] + '_' + 'id' id_column = id_column.lower() query = self.session.query( getattr(ormclass, id_column), getattr(ormclass, column)[self.start_snapshot: self.end_snapshot]. label(column)).filter(and_( ormclass.scn_name == self.scn_name, ormclass.temp_id == self.temp_id)) if self.version: query = query.filter(ormclass.version == self.version) df = pd.io.sql.read_sql(query.statement, self.session.bind, columns=[column], index_col=id_column) df.index = df.index.astype(str) # change of format to fit pypsa df = df[column].apply(pd.Series).transpose() try: assert not df.empty df.index = self.timeindex except AssertionError: print("No data for %s in column %s." % (name, column)) return df
[ "def", "series_fetch_by_relname", "(", "self", ",", "name", ",", "column", ")", ":", "ormclass", "=", "self", ".", "_mapped", "[", "name", "]", "# TODO: This is implemented in a not very robust way.", "id_column", "=", "re", ".", "findall", "(", "r'[A-Z][^A-Z]*'", ...
Construct DataFrame with component timeseries data from filtered table data. Parameters ---------- name : str Component name. column : str Component field with timevarying data. Returns ------- pd.DataFrame Component data.
[ "Construct", "DataFrame", "with", "component", "timeseries", "data", "from", "filtered", "table", "data", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L264-L313
train
40,322
openego/eTraGo
etrago/tools/io.py
NetworkScenario.build_network
def build_network(self, network=None, *args, **kwargs): """ Core method to construct PyPSA Network object. """ # TODO: build_network takes care of divergences in database design and # future PyPSA changes from PyPSA's v0.6 on. This concept should be # replaced, when the oedb has a revision system in place, because # sometime this will break!!! if network != None: network = network else: network = pypsa.Network() network.set_snapshots(self.timeindex) timevarying_override = False if pypsa.__version__ == '0.11.0': old_to_new_name = {'Generator': {'p_min_pu_fixed': 'p_min_pu', 'p_max_pu_fixed': 'p_max_pu', 'source': 'carrier', 'dispatch': 'former_dispatch'}, 'Bus': {'current_type': 'carrier'}, 'Transformer': {'trafo_id': 'transformer_id'}, 'Storage': {'p_min_pu_fixed': 'p_min_pu', 'p_max_pu_fixed': 'p_max_pu', 'soc_cyclic': 'cyclic_state_of_charge', 'soc_initial': 'state_of_charge_initial', 'source': 'carrier'}} timevarying_override = True else: old_to_new_name = {'Storage': {'soc_cyclic': 'cyclic_state_of_charge', 'soc_initial': 'state_of_charge_initial'}} for comp, comp_t_dict in self.config.items(): # TODO: This is confusing, should be fixed in db pypsa_comp_name = 'StorageUnit' if comp == 'Storage' else comp df = self.fetch_by_relname(comp) if comp in old_to_new_name: tmp = old_to_new_name[comp] df.rename(columns=tmp, inplace=True) network.import_components_from_dataframe(df, pypsa_comp_name) if comp_t_dict: for comp_t, columns in comp_t_dict.items(): for col in columns: df_series = self.series_fetch_by_relname(comp_t, col) # TODO: VMagPuSet is not implemented. if timevarying_override and comp == 'Generator' \ and not df_series.empty: idx = df[df.former_dispatch == 'flexible'].index idx = [i for i in idx if i in df_series.columns] df_series.drop(idx, axis=1, inplace=True) try: pypsa.io.import_series_from_dataframe( network, df_series, pypsa_comp_name, col) except (ValueError, AttributeError): print("Series %s of component %s could not be " "imported" % (col, pypsa_comp_name)) # populate carrier attribute in PyPSA network network.import_components_from_dataframe( self.fetch_by_relname(carr_ormclass), 'Carrier') self.network = network return network
python
def build_network(self, network=None, *args, **kwargs): """ Core method to construct PyPSA Network object. """ # TODO: build_network takes care of divergences in database design and # future PyPSA changes from PyPSA's v0.6 on. This concept should be # replaced, when the oedb has a revision system in place, because # sometime this will break!!! if network != None: network = network else: network = pypsa.Network() network.set_snapshots(self.timeindex) timevarying_override = False if pypsa.__version__ == '0.11.0': old_to_new_name = {'Generator': {'p_min_pu_fixed': 'p_min_pu', 'p_max_pu_fixed': 'p_max_pu', 'source': 'carrier', 'dispatch': 'former_dispatch'}, 'Bus': {'current_type': 'carrier'}, 'Transformer': {'trafo_id': 'transformer_id'}, 'Storage': {'p_min_pu_fixed': 'p_min_pu', 'p_max_pu_fixed': 'p_max_pu', 'soc_cyclic': 'cyclic_state_of_charge', 'soc_initial': 'state_of_charge_initial', 'source': 'carrier'}} timevarying_override = True else: old_to_new_name = {'Storage': {'soc_cyclic': 'cyclic_state_of_charge', 'soc_initial': 'state_of_charge_initial'}} for comp, comp_t_dict in self.config.items(): # TODO: This is confusing, should be fixed in db pypsa_comp_name = 'StorageUnit' if comp == 'Storage' else comp df = self.fetch_by_relname(comp) if comp in old_to_new_name: tmp = old_to_new_name[comp] df.rename(columns=tmp, inplace=True) network.import_components_from_dataframe(df, pypsa_comp_name) if comp_t_dict: for comp_t, columns in comp_t_dict.items(): for col in columns: df_series = self.series_fetch_by_relname(comp_t, col) # TODO: VMagPuSet is not implemented. if timevarying_override and comp == 'Generator' \ and not df_series.empty: idx = df[df.former_dispatch == 'flexible'].index idx = [i for i in idx if i in df_series.columns] df_series.drop(idx, axis=1, inplace=True) try: pypsa.io.import_series_from_dataframe( network, df_series, pypsa_comp_name, col) except (ValueError, AttributeError): print("Series %s of component %s could not be " "imported" % (col, pypsa_comp_name)) # populate carrier attribute in PyPSA network network.import_components_from_dataframe( self.fetch_by_relname(carr_ormclass), 'Carrier') self.network = network return network
[ "def", "build_network", "(", "self", ",", "network", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO: build_network takes care of divergences in database design and", "# future PyPSA changes from PyPSA's v0.6 on. This concept should be", "# replaced, w...
Core method to construct PyPSA Network object.
[ "Core", "method", "to", "construct", "PyPSA", "Network", "object", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L315-L404
train
40,323
DLR-RM/RAFCON
source/rafcon/core/states/preemptive_concurrency_state.py
PreemptiveConcurrencyState.run
def run(self): """ This defines the sequence of actions that are taken when the preemptive concurrency state is executed :return: """ logger.debug("Starting execution of {0}{1}".format(self, " (backwards)" if self.backward_execution else "")) self.setup_run() try: concurrency_history_item = self.setup_forward_or_backward_execution() concurrency_queue = self.start_child_states(concurrency_history_item) ####################################################### # wait for the first threads to finish ####################################################### finished_thread_id = concurrency_queue.get() finisher_state = self.states[finished_thread_id] finisher_state.join() # preempt all child states if not self.backward_execution: for state_id, state in self.states.items(): state.recursively_preempt_states() # join all states for history_index, state in enumerate(self.states.values()): self.join_state(state, history_index, concurrency_history_item) self.add_state_execution_output_to_scoped_data(state.output_data, state) self.update_scoped_variables_with_output_dictionary(state.output_data, state) # add the data of the first state now to overwrite data of the preempted states self.add_state_execution_output_to_scoped_data(finisher_state.output_data, finisher_state) self.update_scoped_variables_with_output_dictionary(finisher_state.output_data, finisher_state) ####################################################### # handle backward execution case ####################################################### if self.states[finished_thread_id].backward_execution: return self.finalize_backward_execution() else: self.backward_execution = False ####################################################### # handle no transition ####################################################### transition = self.get_transition_for_outcome(self.states[finished_thread_id], self.states[finished_thread_id].final_outcome) if transition is None: # final outcome is set here transition = self.handle_no_transition(self.states[finished_thread_id]) # it the transition is still None, then the state was preempted or aborted, in this case return if transition is None: self.output_data["error"] = RuntimeError("state aborted") else: if 'error' in self.states[finished_thread_id].output_data: self.output_data["error"] = self.states[finished_thread_id].output_data['error'] self.final_outcome = self.outcomes[transition.to_outcome] return self.finalize_concurrency_state(self.final_outcome) except Exception as e: logger.error("{0} had an internal error: {1}\n{2}".format(self, str(e), str(traceback.format_exc()))) self.output_data["error"] = e self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE return self.finalize(Outcome(-1, "aborted"))
python
def run(self): """ This defines the sequence of actions that are taken when the preemptive concurrency state is executed :return: """ logger.debug("Starting execution of {0}{1}".format(self, " (backwards)" if self.backward_execution else "")) self.setup_run() try: concurrency_history_item = self.setup_forward_or_backward_execution() concurrency_queue = self.start_child_states(concurrency_history_item) ####################################################### # wait for the first threads to finish ####################################################### finished_thread_id = concurrency_queue.get() finisher_state = self.states[finished_thread_id] finisher_state.join() # preempt all child states if not self.backward_execution: for state_id, state in self.states.items(): state.recursively_preempt_states() # join all states for history_index, state in enumerate(self.states.values()): self.join_state(state, history_index, concurrency_history_item) self.add_state_execution_output_to_scoped_data(state.output_data, state) self.update_scoped_variables_with_output_dictionary(state.output_data, state) # add the data of the first state now to overwrite data of the preempted states self.add_state_execution_output_to_scoped_data(finisher_state.output_data, finisher_state) self.update_scoped_variables_with_output_dictionary(finisher_state.output_data, finisher_state) ####################################################### # handle backward execution case ####################################################### if self.states[finished_thread_id].backward_execution: return self.finalize_backward_execution() else: self.backward_execution = False ####################################################### # handle no transition ####################################################### transition = self.get_transition_for_outcome(self.states[finished_thread_id], self.states[finished_thread_id].final_outcome) if transition is None: # final outcome is set here transition = self.handle_no_transition(self.states[finished_thread_id]) # it the transition is still None, then the state was preempted or aborted, in this case return if transition is None: self.output_data["error"] = RuntimeError("state aborted") else: if 'error' in self.states[finished_thread_id].output_data: self.output_data["error"] = self.states[finished_thread_id].output_data['error'] self.final_outcome = self.outcomes[transition.to_outcome] return self.finalize_concurrency_state(self.final_outcome) except Exception as e: logger.error("{0} had an internal error: {1}\n{2}".format(self, str(e), str(traceback.format_exc()))) self.output_data["error"] = e self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE return self.finalize(Outcome(-1, "aborted"))
[ "def", "run", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Starting execution of {0}{1}\"", ".", "format", "(", "self", ",", "\" (backwards)\"", "if", "self", ".", "backward_execution", "else", "\"\"", ")", ")", "self", ".", "setup_run", "(", ")", ...
This defines the sequence of actions that are taken when the preemptive concurrency state is executed :return:
[ "This", "defines", "the", "sequence", "of", "actions", "that", "are", "taken", "when", "the", "preemptive", "concurrency", "state", "is", "executed" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/preemptive_concurrency_state.py#L45-L108
train
40,324
DLR-RM/RAFCON
source/rafcon/core/states/preemptive_concurrency_state.py
PreemptiveConcurrencyState._check_transition_validity
def _check_transition_validity(self, check_transition): """ Transition of BarrierConcurrencyStates must least fulfill the condition of a ContainerState. Start transitions are forbidden in the ConcurrencyState :param check_transition: the transition to check for validity :return: """ valid, message = super(PreemptiveConcurrencyState, self)._check_transition_validity(check_transition) if not valid: return False, message # Only transitions to the parent state are allowed if check_transition.to_state != self.state_id: return False, "Only transitions to the parent state are allowed" return True, message
python
def _check_transition_validity(self, check_transition): """ Transition of BarrierConcurrencyStates must least fulfill the condition of a ContainerState. Start transitions are forbidden in the ConcurrencyState :param check_transition: the transition to check for validity :return: """ valid, message = super(PreemptiveConcurrencyState, self)._check_transition_validity(check_transition) if not valid: return False, message # Only transitions to the parent state are allowed if check_transition.to_state != self.state_id: return False, "Only transitions to the parent state are allowed" return True, message
[ "def", "_check_transition_validity", "(", "self", ",", "check_transition", ")", ":", "valid", ",", "message", "=", "super", "(", "PreemptiveConcurrencyState", ",", "self", ")", ".", "_check_transition_validity", "(", "check_transition", ")", "if", "not", "valid", ...
Transition of BarrierConcurrencyStates must least fulfill the condition of a ContainerState. Start transitions are forbidden in the ConcurrencyState :param check_transition: the transition to check for validity :return:
[ "Transition", "of", "BarrierConcurrencyStates", "must", "least", "fulfill", "the", "condition", "of", "a", "ContainerState", ".", "Start", "transitions", "are", "forbidden", "in", "the", "ConcurrencyState" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/preemptive_concurrency_state.py#L110-L126
train
40,325
DLR-RM/RAFCON
source/rafcon/gui/models/modification_history.py
ModificationsHistoryModel.recover_specific_version
def recover_specific_version(self, pointer_on_version_to_recover): """ Recovers a specific version of the all_time_history element by doing several undos and redos. :param pointer_on_version_to_recover: the id of the list element which is to recover :return: """ # search for traceable path -> list of action to undo and list of action to redo logger.info("Going to history status #{0}".format(pointer_on_version_to_recover)) undo_redo_list = self.modifications.get_undo_redo_list_from_active_trail_history_item_to_version_id(pointer_on_version_to_recover) logger.debug("Multiple undo and redo to reach modification history element of version {0} " "-> undo-redo-list is: {1}".format(pointer_on_version_to_recover, undo_redo_list)) # logger.debug("acquire lock 1 - for multiple action {0}".format(self.modifications.trail_pointer)) self.state_machine_model.storage_lock.acquire() # logger.debug("acquired lock 1 - for multiple action {0}".format(self.modifications.trail_pointer)) for elem in undo_redo_list: if elem[1] == 'undo': # do undo self._undo(elem[0]) else: # do redo self._redo(elem[0]) self.modifications.reorganize_trail_history_for_version_id(pointer_on_version_to_recover) self.change_count += 1 # logger.debug("release lock 1 - for multiple action {0}".format(self.modifications.trail_pointer)) self.state_machine_model.storage_lock.release()
python
def recover_specific_version(self, pointer_on_version_to_recover): """ Recovers a specific version of the all_time_history element by doing several undos and redos. :param pointer_on_version_to_recover: the id of the list element which is to recover :return: """ # search for traceable path -> list of action to undo and list of action to redo logger.info("Going to history status #{0}".format(pointer_on_version_to_recover)) undo_redo_list = self.modifications.get_undo_redo_list_from_active_trail_history_item_to_version_id(pointer_on_version_to_recover) logger.debug("Multiple undo and redo to reach modification history element of version {0} " "-> undo-redo-list is: {1}".format(pointer_on_version_to_recover, undo_redo_list)) # logger.debug("acquire lock 1 - for multiple action {0}".format(self.modifications.trail_pointer)) self.state_machine_model.storage_lock.acquire() # logger.debug("acquired lock 1 - for multiple action {0}".format(self.modifications.trail_pointer)) for elem in undo_redo_list: if elem[1] == 'undo': # do undo self._undo(elem[0]) else: # do redo self._redo(elem[0]) self.modifications.reorganize_trail_history_for_version_id(pointer_on_version_to_recover) self.change_count += 1 # logger.debug("release lock 1 - for multiple action {0}".format(self.modifications.trail_pointer)) self.state_machine_model.storage_lock.release()
[ "def", "recover_specific_version", "(", "self", ",", "pointer_on_version_to_recover", ")", ":", "# search for traceable path -> list of action to undo and list of action to redo", "logger", ".", "info", "(", "\"Going to history status #{0}\"", ".", "format", "(", "pointer_on_versio...
Recovers a specific version of the all_time_history element by doing several undos and redos. :param pointer_on_version_to_recover: the id of the list element which is to recover :return:
[ "Recovers", "a", "specific", "version", "of", "the", "all_time_history", "element", "by", "doing", "several", "undos", "and", "redos", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/modification_history.py#L153-L178
train
40,326
DLR-RM/RAFCON
source/rafcon/gui/models/modification_history.py
ModificationsHistory.get_undo_redo_list_from_active_trail_history_item_to_version_id
def get_undo_redo_list_from_active_trail_history_item_to_version_id(self, version_id): """Perform fast search from currently active branch to specific version_id and collect all recovery steps. """ all_trail_action = [a.version_id for a in self.single_trail_history() if a is not None] all_active_action = self.get_all_active_actions() undo_redo_list = [] _undo_redo_list = [] intermediate_version_id = version_id if self.with_verbose: logger.verbose("Version_id : {0} in".format(intermediate_version_id)) logger.verbose("Active actions: {0} in: {1}".format(all_active_action, intermediate_version_id in all_active_action)) logger.verbose("Trail actions : {0} in: {1}".format(all_trail_action, intermediate_version_id in all_trail_action)) if intermediate_version_id not in all_trail_action: # get undo to come from version_id to trail_action while intermediate_version_id not in all_trail_action: _undo_redo_list.insert(0, (intermediate_version_id, 'redo')) intermediate_version_id = self.all_time_history[intermediate_version_id].prev_id intermediate_goal_version_id = intermediate_version_id else: intermediate_goal_version_id = version_id intermediate_version_id = self.trail_history[self.trail_pointer].version_id if self.with_verbose: logger.verbose("Version_id : {0} {1}".format(intermediate_goal_version_id, intermediate_version_id)) logger.verbose("Active actions: {0} in: {1}".format(all_active_action, intermediate_version_id in all_active_action)) logger.verbose("Trail actions : {0} in: {1}".format(all_trail_action, intermediate_version_id in all_trail_action)) # collect undo and redo on trail if intermediate_goal_version_id in all_active_action: # collect needed undo to reach intermediate version while not intermediate_version_id == intermediate_goal_version_id: undo_redo_list.append((intermediate_version_id, 'undo')) intermediate_version_id = self.all_time_history[intermediate_version_id].prev_id elif intermediate_goal_version_id in all_trail_action: # collect needed redo to reach intermediate version while not intermediate_version_id == intermediate_goal_version_id: intermediate_version_id = self.all_time_history[intermediate_version_id].next_id undo_redo_list.append((intermediate_version_id, 'redo')) for elem in _undo_redo_list: undo_redo_list.append(elem) return undo_redo_list
python
def get_undo_redo_list_from_active_trail_history_item_to_version_id(self, version_id): """Perform fast search from currently active branch to specific version_id and collect all recovery steps. """ all_trail_action = [a.version_id for a in self.single_trail_history() if a is not None] all_active_action = self.get_all_active_actions() undo_redo_list = [] _undo_redo_list = [] intermediate_version_id = version_id if self.with_verbose: logger.verbose("Version_id : {0} in".format(intermediate_version_id)) logger.verbose("Active actions: {0} in: {1}".format(all_active_action, intermediate_version_id in all_active_action)) logger.verbose("Trail actions : {0} in: {1}".format(all_trail_action, intermediate_version_id in all_trail_action)) if intermediate_version_id not in all_trail_action: # get undo to come from version_id to trail_action while intermediate_version_id not in all_trail_action: _undo_redo_list.insert(0, (intermediate_version_id, 'redo')) intermediate_version_id = self.all_time_history[intermediate_version_id].prev_id intermediate_goal_version_id = intermediate_version_id else: intermediate_goal_version_id = version_id intermediate_version_id = self.trail_history[self.trail_pointer].version_id if self.with_verbose: logger.verbose("Version_id : {0} {1}".format(intermediate_goal_version_id, intermediate_version_id)) logger.verbose("Active actions: {0} in: {1}".format(all_active_action, intermediate_version_id in all_active_action)) logger.verbose("Trail actions : {0} in: {1}".format(all_trail_action, intermediate_version_id in all_trail_action)) # collect undo and redo on trail if intermediate_goal_version_id in all_active_action: # collect needed undo to reach intermediate version while not intermediate_version_id == intermediate_goal_version_id: undo_redo_list.append((intermediate_version_id, 'undo')) intermediate_version_id = self.all_time_history[intermediate_version_id].prev_id elif intermediate_goal_version_id in all_trail_action: # collect needed redo to reach intermediate version while not intermediate_version_id == intermediate_goal_version_id: intermediate_version_id = self.all_time_history[intermediate_version_id].next_id undo_redo_list.append((intermediate_version_id, 'redo')) for elem in _undo_redo_list: undo_redo_list.append(elem) return undo_redo_list
[ "def", "get_undo_redo_list_from_active_trail_history_item_to_version_id", "(", "self", ",", "version_id", ")", ":", "all_trail_action", "=", "[", "a", ".", "version_id", "for", "a", "in", "self", ".", "single_trail_history", "(", ")", "if", "a", "is", "not", "None...
Perform fast search from currently active branch to specific version_id and collect all recovery steps.
[ "Perform", "fast", "search", "from", "currently", "active", "branch", "to", "specific", "version_id", "and", "collect", "all", "recovery", "steps", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/modification_history.py#L1019-L1067
train
40,327
DLR-RM/RAFCON
source/rafcon/gui/controllers/main_window.py
MainWindowController.set_pane_position
def set_pane_position(self, config_id): """Adjusts the position of a GTK Pane to a value stored in the runtime config file. If there was no value stored, the pane's position is set to a default value. :param config_id: The pane identifier saved in the runtime config file """ default_pos = constants.DEFAULT_PANE_POS[config_id] position = global_runtime_config.get_config_value(config_id, default_pos) pane_id = constants.PANE_ID[config_id] self.view[pane_id].set_position(position)
python
def set_pane_position(self, config_id): """Adjusts the position of a GTK Pane to a value stored in the runtime config file. If there was no value stored, the pane's position is set to a default value. :param config_id: The pane identifier saved in the runtime config file """ default_pos = constants.DEFAULT_PANE_POS[config_id] position = global_runtime_config.get_config_value(config_id, default_pos) pane_id = constants.PANE_ID[config_id] self.view[pane_id].set_position(position)
[ "def", "set_pane_position", "(", "self", ",", "config_id", ")", ":", "default_pos", "=", "constants", ".", "DEFAULT_PANE_POS", "[", "config_id", "]", "position", "=", "global_runtime_config", ".", "get_config_value", "(", "config_id", ",", "default_pos", ")", "pan...
Adjusts the position of a GTK Pane to a value stored in the runtime config file. If there was no value stored, the pane's position is set to a default value. :param config_id: The pane identifier saved in the runtime config file
[ "Adjusts", "the", "position", "of", "a", "GTK", "Pane", "to", "a", "value", "stored", "in", "the", "runtime", "config", "file", ".", "If", "there", "was", "no", "value", "stored", "the", "pane", "s", "position", "is", "set", "to", "a", "default", "valu...
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/main_window.py#L350-L359
train
40,328
DLR-RM/RAFCON
source/rafcon/gui/controllers/main_window.py
MainWindowController.model_changed
def model_changed(self, model, prop_name, info): """ Highlight buttons according actual execution status. Furthermore it triggers the label redraw of the active state machine. """ # TODO: find nice solution # this in only required if the GUI is terminated via Ctrl+C signal if not self.view: # this means that the main window is currently under destruction return execution_engine = rafcon.core.singleton.state_machine_execution_engine label_string = str(execution_engine.status.execution_mode) label_string = label_string.replace("STATE_MACHINE_EXECUTION_STATUS.", "") self.view['execution_status_label'].set_text(label_string) current_execution_mode = execution_engine.status.execution_mode if current_execution_mode is StateMachineExecutionStatus.STARTED: self.view['step_buttons'].hide() self._set_single_button_active('button_start_shortcut') elif current_execution_mode is StateMachineExecutionStatus.PAUSED: self.view['step_buttons'].hide() self._set_single_button_active('button_pause_shortcut') elif execution_engine.finished_or_stopped(): self.view['step_buttons'].hide() self._set_single_button_active('button_stop_shortcut') else: # all step modes self.view['step_buttons'].show() self._set_single_button_active('button_step_mode_shortcut')
python
def model_changed(self, model, prop_name, info): """ Highlight buttons according actual execution status. Furthermore it triggers the label redraw of the active state machine. """ # TODO: find nice solution # this in only required if the GUI is terminated via Ctrl+C signal if not self.view: # this means that the main window is currently under destruction return execution_engine = rafcon.core.singleton.state_machine_execution_engine label_string = str(execution_engine.status.execution_mode) label_string = label_string.replace("STATE_MACHINE_EXECUTION_STATUS.", "") self.view['execution_status_label'].set_text(label_string) current_execution_mode = execution_engine.status.execution_mode if current_execution_mode is StateMachineExecutionStatus.STARTED: self.view['step_buttons'].hide() self._set_single_button_active('button_start_shortcut') elif current_execution_mode is StateMachineExecutionStatus.PAUSED: self.view['step_buttons'].hide() self._set_single_button_active('button_pause_shortcut') elif execution_engine.finished_or_stopped(): self.view['step_buttons'].hide() self._set_single_button_active('button_stop_shortcut') else: # all step modes self.view['step_buttons'].show() self._set_single_button_active('button_step_mode_shortcut')
[ "def", "model_changed", "(", "self", ",", "model", ",", "prop_name", ",", "info", ")", ":", "# TODO: find nice solution", "# this in only required if the GUI is terminated via Ctrl+C signal", "if", "not", "self", ".", "view", ":", "# this means that the main window is current...
Highlight buttons according actual execution status. Furthermore it triggers the label redraw of the active state machine.
[ "Highlight", "buttons", "according", "actual", "execution", "status", ".", "Furthermore", "it", "triggers", "the", "label", "redraw", "of", "the", "active", "state", "machine", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/main_window.py#L362-L390
train
40,329
DLR-RM/RAFCON
source/rafcon/gui/controllers/main_window.py
MainWindowController.focus_notebook_page_of_controller
def focus_notebook_page_of_controller(self, controller): """Puts the focus on the given child controller The method implements focus request of the notebooks in left side-bar of the main window. Thereby it is the master-function of focus pattern of the notebooks in left side-bar. Actual pattern is: * Execution-History is put to focus any time requested (request occur at the moment when the state-machine is started and stopped. * Modification-History one time focused while and one time after execution if requested. :param controller The controller which request to be focused. """ # TODO think about to may substitute Controller- by View-objects it is may the better design if controller not in self.get_child_controllers(): return # logger.info("focus controller {0}".format(controller)) if not self.modification_history_was_focused and isinstance(controller, ModificationHistoryTreeController) and \ self.view is not None: self.view.bring_tab_to_the_top('history') self.modification_history_was_focused = True if self.view is not None and isinstance(controller, ExecutionHistoryTreeController): self.view.bring_tab_to_the_top('execution_history') self.modification_history_was_focused = False
python
def focus_notebook_page_of_controller(self, controller): """Puts the focus on the given child controller The method implements focus request of the notebooks in left side-bar of the main window. Thereby it is the master-function of focus pattern of the notebooks in left side-bar. Actual pattern is: * Execution-History is put to focus any time requested (request occur at the moment when the state-machine is started and stopped. * Modification-History one time focused while and one time after execution if requested. :param controller The controller which request to be focused. """ # TODO think about to may substitute Controller- by View-objects it is may the better design if controller not in self.get_child_controllers(): return # logger.info("focus controller {0}".format(controller)) if not self.modification_history_was_focused and isinstance(controller, ModificationHistoryTreeController) and \ self.view is not None: self.view.bring_tab_to_the_top('history') self.modification_history_was_focused = True if self.view is not None and isinstance(controller, ExecutionHistoryTreeController): self.view.bring_tab_to_the_top('execution_history') self.modification_history_was_focused = False
[ "def", "focus_notebook_page_of_controller", "(", "self", ",", "controller", ")", ":", "# TODO think about to may substitute Controller- by View-objects it is may the better design", "if", "controller", "not", "in", "self", ".", "get_child_controllers", "(", ")", ":", "return", ...
Puts the focus on the given child controller The method implements focus request of the notebooks in left side-bar of the main window. Thereby it is the master-function of focus pattern of the notebooks in left side-bar. Actual pattern is: * Execution-History is put to focus any time requested (request occur at the moment when the state-machine is started and stopped. * Modification-History one time focused while and one time after execution if requested. :param controller The controller which request to be focused.
[ "Puts", "the", "focus", "on", "the", "given", "child", "controller" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/main_window.py#L408-L432
train
40,330
DLR-RM/RAFCON
source/rafcon/gui/controllers/main_window.py
MainWindowController.on_notebook_tab_switch
def on_notebook_tab_switch(self, notebook, page, page_num, title_label, window, notebook_identifier): """Triggered whenever a left-bar notebook tab is changed. Updates the title of the corresponding notebook and updates the title of the left-bar window in case un-docked. :param notebook: The GTK notebook where a tab-change occurred :param page_num: The page number of the currently-selected tab :param title_label: The label holding the notebook's title :param window: The left-bar window, for which the title should be changed :param notebook_identifier: A string identifying whether the notebook is the upper or the lower one """ title = gui_helper_label.set_notebook_title(notebook, page_num, title_label) window.reset_title(title, notebook_identifier) self.on_switch_page_check_collapse_button(notebook, page_num)
python
def on_notebook_tab_switch(self, notebook, page, page_num, title_label, window, notebook_identifier): """Triggered whenever a left-bar notebook tab is changed. Updates the title of the corresponding notebook and updates the title of the left-bar window in case un-docked. :param notebook: The GTK notebook where a tab-change occurred :param page_num: The page number of the currently-selected tab :param title_label: The label holding the notebook's title :param window: The left-bar window, for which the title should be changed :param notebook_identifier: A string identifying whether the notebook is the upper or the lower one """ title = gui_helper_label.set_notebook_title(notebook, page_num, title_label) window.reset_title(title, notebook_identifier) self.on_switch_page_check_collapse_button(notebook, page_num)
[ "def", "on_notebook_tab_switch", "(", "self", ",", "notebook", ",", "page", ",", "page_num", ",", "title_label", ",", "window", ",", "notebook_identifier", ")", ":", "title", "=", "gui_helper_label", ".", "set_notebook_title", "(", "notebook", ",", "page_num", "...
Triggered whenever a left-bar notebook tab is changed. Updates the title of the corresponding notebook and updates the title of the left-bar window in case un-docked. :param notebook: The GTK notebook where a tab-change occurred :param page_num: The page number of the currently-selected tab :param title_label: The label holding the notebook's title :param window: The left-bar window, for which the title should be changed :param notebook_identifier: A string identifying whether the notebook is the upper or the lower one
[ "Triggered", "whenever", "a", "left", "-", "bar", "notebook", "tab", "is", "changed", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/main_window.py#L575-L588
train
40,331
DLR-RM/RAFCON
source/rafcon/gui/controllers/main_window.py
MainWindowController._on_key_press
def _on_key_press(self, widget, event): """Updates the currently pressed keys In addition, the sidebars are toggled if <Ctrl><Tab> is pressed. :param Gtk.Widget widget: The main window :param Gdk.Event event: The key press event """ self.currently_pressed_keys.add(event.keyval) if event.keyval in [Gdk.KEY_Tab, Gdk.KEY_ISO_Left_Tab] and event.state & Gdk.ModifierType.CONTROL_MASK: self.toggle_sidebars()
python
def _on_key_press(self, widget, event): """Updates the currently pressed keys In addition, the sidebars are toggled if <Ctrl><Tab> is pressed. :param Gtk.Widget widget: The main window :param Gdk.Event event: The key press event """ self.currently_pressed_keys.add(event.keyval) if event.keyval in [Gdk.KEY_Tab, Gdk.KEY_ISO_Left_Tab] and event.state & Gdk.ModifierType.CONTROL_MASK: self.toggle_sidebars()
[ "def", "_on_key_press", "(", "self", ",", "widget", ",", "event", ")", ":", "self", ".", "currently_pressed_keys", ".", "add", "(", "event", ".", "keyval", ")", "if", "event", ".", "keyval", "in", "[", "Gdk", ".", "KEY_Tab", ",", "Gdk", ".", "KEY_ISO_L...
Updates the currently pressed keys In addition, the sidebars are toggled if <Ctrl><Tab> is pressed. :param Gtk.Widget widget: The main window :param Gdk.Event event: The key press event
[ "Updates", "the", "currently", "pressed", "keys" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/main_window.py#L627-L637
train
40,332
DLR-RM/RAFCON
source/rafcon/gui/controllers/main_window.py
MainWindowController.prepare_destruction
def prepare_destruction(self): """Saves current configuration of windows and panes to the runtime config file, before RAFCON is closed.""" plugins.run_hook("pre_destruction") logger.debug("Saving runtime config to {0}".format(global_runtime_config.config_file_path)) # store pane last positions for key, widget_name in constants.PANE_ID.items(): global_runtime_config.store_widget_properties(self.view[widget_name], key.replace('_POS', '')) # store hidden or undocked widget flags correctly -> make them independent for restoring for window_key in constants.UNDOCKABLE_WINDOW_KEYS: hidden = False if not global_runtime_config.get_config_value(window_key + "_WINDOW_UNDOCKED"): hidden = getattr(self, window_key.lower() + '_hidden') global_runtime_config.set_config_value(window_key + '_HIDDEN', hidden) global_runtime_config.save_configuration() # state-editor will relieve it's model => it won't observe the state machine manager any more self.get_controller('states_editor_ctrl').prepare_destruction() # avoid new state editor TODO tbd (deleted) rafcon.core.singleton.state_machine_manager.delete_all_state_machines() rafcon.core.singleton.library_manager.prepare_destruction() # gtkmvc installs a global glade custom handler that holds a reference to the last created View class, # preventing it from being destructed. By installing a dummy callback handler, after all views have been # created, the old handler is being removed and with it the reference, allowing all Views to be destructed. # Gtk TODO: check if necessary and search for replacement # try: # from gtk import glade # def dummy(*args, **kwargs): # pass # glade.set_custom_handler(dummy) # except ImportError: # pass # Recursively destroys the main window self.destroy() from rafcon.gui.clipboard import global_clipboard global_clipboard.destroy() gui_singletons.main_window_controller = None
python
def prepare_destruction(self): """Saves current configuration of windows and panes to the runtime config file, before RAFCON is closed.""" plugins.run_hook("pre_destruction") logger.debug("Saving runtime config to {0}".format(global_runtime_config.config_file_path)) # store pane last positions for key, widget_name in constants.PANE_ID.items(): global_runtime_config.store_widget_properties(self.view[widget_name], key.replace('_POS', '')) # store hidden or undocked widget flags correctly -> make them independent for restoring for window_key in constants.UNDOCKABLE_WINDOW_KEYS: hidden = False if not global_runtime_config.get_config_value(window_key + "_WINDOW_UNDOCKED"): hidden = getattr(self, window_key.lower() + '_hidden') global_runtime_config.set_config_value(window_key + '_HIDDEN', hidden) global_runtime_config.save_configuration() # state-editor will relieve it's model => it won't observe the state machine manager any more self.get_controller('states_editor_ctrl').prepare_destruction() # avoid new state editor TODO tbd (deleted) rafcon.core.singleton.state_machine_manager.delete_all_state_machines() rafcon.core.singleton.library_manager.prepare_destruction() # gtkmvc installs a global glade custom handler that holds a reference to the last created View class, # preventing it from being destructed. By installing a dummy callback handler, after all views have been # created, the old handler is being removed and with it the reference, allowing all Views to be destructed. # Gtk TODO: check if necessary and search for replacement # try: # from gtk import glade # def dummy(*args, **kwargs): # pass # glade.set_custom_handler(dummy) # except ImportError: # pass # Recursively destroys the main window self.destroy() from rafcon.gui.clipboard import global_clipboard global_clipboard.destroy() gui_singletons.main_window_controller = None
[ "def", "prepare_destruction", "(", "self", ")", ":", "plugins", ".", "run_hook", "(", "\"pre_destruction\"", ")", "logger", ".", "debug", "(", "\"Saving runtime config to {0}\"", ".", "format", "(", "global_runtime_config", ".", "config_file_path", ")", ")", "# stor...
Saves current configuration of windows and panes to the runtime config file, before RAFCON is closed.
[ "Saves", "current", "configuration", "of", "windows", "and", "panes", "to", "the", "runtime", "config", "file", "before", "RAFCON", "is", "closed", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/main_window.py#L647-L688
train
40,333
DLR-RM/RAFCON
source/rafcon/core/states/concurrency_state.py
ConcurrencyState.setup_forward_or_backward_execution
def setup_forward_or_backward_execution(self): """ Sets up the execution of the concurrency states dependent on if the state is executed forward of backward. :return: """ if self.backward_execution: # pop the return item of this concurrency state to get the correct scoped data last_history_item = self.execution_history.pop_last_item() assert isinstance(last_history_item, ReturnItem) self.scoped_data = last_history_item.scoped_data # get the concurrency item for the children execution historys concurrency_history_item = self.execution_history.get_last_history_item() assert isinstance(concurrency_history_item, ConcurrencyItem) else: # forward_execution self.execution_history.push_call_history_item(self, CallType.CONTAINER, self, self.input_data) concurrency_history_item = self.execution_history.push_concurrency_history_item(self, len(self.states)) return concurrency_history_item
python
def setup_forward_or_backward_execution(self): """ Sets up the execution of the concurrency states dependent on if the state is executed forward of backward. :return: """ if self.backward_execution: # pop the return item of this concurrency state to get the correct scoped data last_history_item = self.execution_history.pop_last_item() assert isinstance(last_history_item, ReturnItem) self.scoped_data = last_history_item.scoped_data # get the concurrency item for the children execution historys concurrency_history_item = self.execution_history.get_last_history_item() assert isinstance(concurrency_history_item, ConcurrencyItem) else: # forward_execution self.execution_history.push_call_history_item(self, CallType.CONTAINER, self, self.input_data) concurrency_history_item = self.execution_history.push_concurrency_history_item(self, len(self.states)) return concurrency_history_item
[ "def", "setup_forward_or_backward_execution", "(", "self", ")", ":", "if", "self", ".", "backward_execution", ":", "# pop the return item of this concurrency state to get the correct scoped data", "last_history_item", "=", "self", ".", "execution_history", ".", "pop_last_item", ...
Sets up the execution of the concurrency states dependent on if the state is executed forward of backward. :return:
[ "Sets", "up", "the", "execution", "of", "the", "concurrency", "states", "dependent", "on", "if", "the", "state", "is", "executed", "forward", "of", "backward", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/concurrency_state.py#L61-L78
train
40,334
DLR-RM/RAFCON
source/rafcon/core/states/concurrency_state.py
ConcurrencyState.start_child_states
def start_child_states(self, concurrency_history_item, do_not_start_state=None): """ Utility function to start all child states of the concurrency state. :param concurrency_history_item: each concurrent child branch gets an execution history stack of this concurrency history item :param do_not_start_state: optionally the id of a state can be passed, that must not be started (e.g. in the case of the barrier concurrency state the decider state) :return: """ self.state_execution_status = StateExecutionStatus.EXECUTE_CHILDREN # actually the queue is not needed in the barrier concurrency case # to avoid code duplication both concurrency states have the same start child function concurrency_queue = queue.Queue(maxsize=0) # infinite Queue size for index, state in enumerate(self.states.values()): if state is not do_not_start_state: state.input_data = self.get_inputs_for_state(state) state.output_data = self.create_output_dictionary_for_state(state) state.concurrency_queue = concurrency_queue state.concurrency_queue_id = index state.generate_run_id() if not self.backward_execution: # care for the history items; this item is only for execution visualization concurrency_history_item.execution_histories[index].push_call_history_item( state, CallType.EXECUTE, self, state.input_data) else: # backward execution last_history_item = concurrency_history_item.execution_histories[index].pop_last_item() assert isinstance(last_history_item, ReturnItem) state.start(concurrency_history_item.execution_histories[index], self.backward_execution, False) return concurrency_queue
python
def start_child_states(self, concurrency_history_item, do_not_start_state=None): """ Utility function to start all child states of the concurrency state. :param concurrency_history_item: each concurrent child branch gets an execution history stack of this concurrency history item :param do_not_start_state: optionally the id of a state can be passed, that must not be started (e.g. in the case of the barrier concurrency state the decider state) :return: """ self.state_execution_status = StateExecutionStatus.EXECUTE_CHILDREN # actually the queue is not needed in the barrier concurrency case # to avoid code duplication both concurrency states have the same start child function concurrency_queue = queue.Queue(maxsize=0) # infinite Queue size for index, state in enumerate(self.states.values()): if state is not do_not_start_state: state.input_data = self.get_inputs_for_state(state) state.output_data = self.create_output_dictionary_for_state(state) state.concurrency_queue = concurrency_queue state.concurrency_queue_id = index state.generate_run_id() if not self.backward_execution: # care for the history items; this item is only for execution visualization concurrency_history_item.execution_histories[index].push_call_history_item( state, CallType.EXECUTE, self, state.input_data) else: # backward execution last_history_item = concurrency_history_item.execution_histories[index].pop_last_item() assert isinstance(last_history_item, ReturnItem) state.start(concurrency_history_item.execution_histories[index], self.backward_execution, False) return concurrency_queue
[ "def", "start_child_states", "(", "self", ",", "concurrency_history_item", ",", "do_not_start_state", "=", "None", ")", ":", "self", ".", "state_execution_status", "=", "StateExecutionStatus", ".", "EXECUTE_CHILDREN", "# actually the queue is not needed in the barrier concurren...
Utility function to start all child states of the concurrency state. :param concurrency_history_item: each concurrent child branch gets an execution history stack of this concurrency history item :param do_not_start_state: optionally the id of a state can be passed, that must not be started (e.g. in the case of the barrier concurrency state the decider state) :return:
[ "Utility", "function", "to", "start", "all", "child", "states", "of", "the", "concurrency", "state", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/concurrency_state.py#L80-L112
train
40,335
DLR-RM/RAFCON
source/rafcon/core/states/concurrency_state.py
ConcurrencyState.join_state
def join_state(self, state, history_index, concurrency_history_item): """ a utility function to join a state :param state: the state to join :param history_index: the index of the execution history stack in the concurrency history item for the given state :param concurrency_history_item: the concurrency history item that stores the execution history stacks of all children :return: """ state.join() if state.backward_execution: self.backward_execution = True state.state_execution_status = StateExecutionStatus.INACTIVE # care for the history items if not self.backward_execution: state.concurrency_queue = None # add the data of all child states to the scoped data and the scoped variables state.execution_history.push_return_history_item(state, CallType.EXECUTE, self, state.output_data) else: last_history_item = concurrency_history_item.execution_histories[history_index].pop_last_item() assert isinstance(last_history_item, CallItem)
python
def join_state(self, state, history_index, concurrency_history_item): """ a utility function to join a state :param state: the state to join :param history_index: the index of the execution history stack in the concurrency history item for the given state :param concurrency_history_item: the concurrency history item that stores the execution history stacks of all children :return: """ state.join() if state.backward_execution: self.backward_execution = True state.state_execution_status = StateExecutionStatus.INACTIVE # care for the history items if not self.backward_execution: state.concurrency_queue = None # add the data of all child states to the scoped data and the scoped variables state.execution_history.push_return_history_item(state, CallType.EXECUTE, self, state.output_data) else: last_history_item = concurrency_history_item.execution_histories[history_index].pop_last_item() assert isinstance(last_history_item, CallItem)
[ "def", "join_state", "(", "self", ",", "state", ",", "history_index", ",", "concurrency_history_item", ")", ":", "state", ".", "join", "(", ")", "if", "state", ".", "backward_execution", ":", "self", ".", "backward_execution", "=", "True", "state", ".", "sta...
a utility function to join a state :param state: the state to join :param history_index: the index of the execution history stack in the concurrency history item for the given state :param concurrency_history_item: the concurrency history item that stores the execution history stacks of all children :return:
[ "a", "utility", "function", "to", "join", "a", "state" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/concurrency_state.py#L114-L136
train
40,336
DLR-RM/RAFCON
source/rafcon/core/states/concurrency_state.py
ConcurrencyState.finalize_backward_execution
def finalize_backward_execution(self): """ Utility function to finalize the backward execution of the concurrency state. :return: """ # backward_execution needs to be True to signal the parent container state the backward execution self.backward_execution = True # pop the ConcurrencyItem as we are leaving the barrier concurrency state last_history_item = self.execution_history.pop_last_item() assert isinstance(last_history_item, ConcurrencyItem) last_history_item = self.execution_history.pop_last_item() assert isinstance(last_history_item, CallItem) # this copy is convenience and not required here self.scoped_data = last_history_item.scoped_data self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE return self.finalize()
python
def finalize_backward_execution(self): """ Utility function to finalize the backward execution of the concurrency state. :return: """ # backward_execution needs to be True to signal the parent container state the backward execution self.backward_execution = True # pop the ConcurrencyItem as we are leaving the barrier concurrency state last_history_item = self.execution_history.pop_last_item() assert isinstance(last_history_item, ConcurrencyItem) last_history_item = self.execution_history.pop_last_item() assert isinstance(last_history_item, CallItem) # this copy is convenience and not required here self.scoped_data = last_history_item.scoped_data self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE return self.finalize()
[ "def", "finalize_backward_execution", "(", "self", ")", ":", "# backward_execution needs to be True to signal the parent container state the backward execution", "self", ".", "backward_execution", "=", "True", "# pop the ConcurrencyItem as we are leaving the barrier concurrency state", "la...
Utility function to finalize the backward execution of the concurrency state. :return:
[ "Utility", "function", "to", "finalize", "the", "backward", "execution", "of", "the", "concurrency", "state", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/concurrency_state.py#L138-L154
train
40,337
DLR-RM/RAFCON
source/rafcon/core/states/concurrency_state.py
ConcurrencyState.finalize_concurrency_state
def finalize_concurrency_state(self, outcome): """ Utility function to finalize the forward execution of the concurrency state. :param outcome: :return: """ final_outcome = outcome self.write_output_data() self.check_output_data_type() self.execution_history.push_return_history_item(self, CallType.CONTAINER, self, self.output_data) self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE singleton.state_machine_execution_engine._modify_run_to_states(self) if self.preempted: final_outcome = Outcome(-2, "preempted") return self.finalize(final_outcome)
python
def finalize_concurrency_state(self, outcome): """ Utility function to finalize the forward execution of the concurrency state. :param outcome: :return: """ final_outcome = outcome self.write_output_data() self.check_output_data_type() self.execution_history.push_return_history_item(self, CallType.CONTAINER, self, self.output_data) self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE singleton.state_machine_execution_engine._modify_run_to_states(self) if self.preempted: final_outcome = Outcome(-2, "preempted") return self.finalize(final_outcome)
[ "def", "finalize_concurrency_state", "(", "self", ",", "outcome", ")", ":", "final_outcome", "=", "outcome", "self", ".", "write_output_data", "(", ")", "self", ".", "check_output_data_type", "(", ")", "self", ".", "execution_history", ".", "push_return_history_item...
Utility function to finalize the forward execution of the concurrency state. :param outcome: :return:
[ "Utility", "function", "to", "finalize", "the", "forward", "execution", "of", "the", "concurrency", "state", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/concurrency_state.py#L156-L172
train
40,338
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/items/line.py
PerpLine._head_length
def _head_length(self, port): """Distance from the center of the port to the perpendicular waypoint""" if not port: return 0. parent_state_v = self.get_parent_state_v() if parent_state_v is port.parent: # port of connection's parent state return port.port_size[1] return max(port.port_size[1] * 1.5, self._calc_line_width() / 1.3)
python
def _head_length(self, port): """Distance from the center of the port to the perpendicular waypoint""" if not port: return 0. parent_state_v = self.get_parent_state_v() if parent_state_v is port.parent: # port of connection's parent state return port.port_size[1] return max(port.port_size[1] * 1.5, self._calc_line_width() / 1.3)
[ "def", "_head_length", "(", "self", ",", "port", ")", ":", "if", "not", "port", ":", "return", "0.", "parent_state_v", "=", "self", ".", "get_parent_state_v", "(", ")", "if", "parent_state_v", "is", "port", ".", "parent", ":", "# port of connection's parent st...
Distance from the center of the port to the perpendicular waypoint
[ "Distance", "from", "the", "center", "of", "the", "port", "to", "the", "perpendicular", "waypoint" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/line.py#L309-L316
train
40,339
DLR-RM/RAFCON
source/rafcon/gui/controllers/state_editor/io_data_port_list.py
DataPortListController.on_use_runtime_value_toggled
def on_use_runtime_value_toggled(self, widget, path): """Try to set the use runtime value flag to the newly entered one """ try: data_port_id = self.list_store[path][self.ID_STORAGE_ID] self.toggle_runtime_value_usage(data_port_id) except TypeError as e: logger.exception("Error while trying to change the use_runtime_value flag")
python
def on_use_runtime_value_toggled(self, widget, path): """Try to set the use runtime value flag to the newly entered one """ try: data_port_id = self.list_store[path][self.ID_STORAGE_ID] self.toggle_runtime_value_usage(data_port_id) except TypeError as e: logger.exception("Error while trying to change the use_runtime_value flag")
[ "def", "on_use_runtime_value_toggled", "(", "self", ",", "widget", ",", "path", ")", ":", "try", ":", "data_port_id", "=", "self", ".", "list_store", "[", "path", "]", "[", "self", ".", "ID_STORAGE_ID", "]", "self", ".", "toggle_runtime_value_usage", "(", "d...
Try to set the use runtime value flag to the newly entered one
[ "Try", "to", "set", "the", "use", "runtime", "value", "flag", "to", "the", "newly", "entered", "one" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/io_data_port_list.py#L124-L131
train
40,340
DLR-RM/RAFCON
source/rafcon/gui/controllers/state_editor/io_data_port_list.py
DataPortListController._default_value_cell_data_func
def _default_value_cell_data_func(self, tree_view_column, cell, model, iter, data=None): """Function set renderer properties for every single cell independently The function controls the editable and color scheme for every cell in the default value column according the use_runtime_value flag and whether the state is a library state. :param tree_view_column: the Gtk.TreeViewColumn to be rendered :param cell: the current CellRenderer :param model: the Gtk.ListStore or TreeStore that is the model for TreeView :param iter: an iterator over the rows of the TreeStore/Gtk.ListStore Model :param data: optional data to be passed: see http://dumbmatter.com/2012/02/some-notes-on-porting-from-pygtk-to-pygobject/ """ if isinstance(self.model.state, LibraryState): use_runtime_value = model.get_value(iter, self.USE_RUNTIME_VALUE_STORAGE_ID) if use_runtime_value: cell.set_property("editable", True) cell.set_property('text', model.get_value(iter, self.RUNTIME_VALUE_STORAGE_ID)) cell.set_property('foreground', "white") else: cell.set_property("editable", False) cell.set_property('text', model.get_value(iter, self.DEFAULT_VALUE_STORAGE_ID)) cell.set_property('foreground', "dark grey") return
python
def _default_value_cell_data_func(self, tree_view_column, cell, model, iter, data=None): """Function set renderer properties for every single cell independently The function controls the editable and color scheme for every cell in the default value column according the use_runtime_value flag and whether the state is a library state. :param tree_view_column: the Gtk.TreeViewColumn to be rendered :param cell: the current CellRenderer :param model: the Gtk.ListStore or TreeStore that is the model for TreeView :param iter: an iterator over the rows of the TreeStore/Gtk.ListStore Model :param data: optional data to be passed: see http://dumbmatter.com/2012/02/some-notes-on-porting-from-pygtk-to-pygobject/ """ if isinstance(self.model.state, LibraryState): use_runtime_value = model.get_value(iter, self.USE_RUNTIME_VALUE_STORAGE_ID) if use_runtime_value: cell.set_property("editable", True) cell.set_property('text', model.get_value(iter, self.RUNTIME_VALUE_STORAGE_ID)) cell.set_property('foreground', "white") else: cell.set_property("editable", False) cell.set_property('text', model.get_value(iter, self.DEFAULT_VALUE_STORAGE_ID)) cell.set_property('foreground', "dark grey") return
[ "def", "_default_value_cell_data_func", "(", "self", ",", "tree_view_column", ",", "cell", ",", "model", ",", "iter", ",", "data", "=", "None", ")", ":", "if", "isinstance", "(", "self", ".", "model", ".", "state", ",", "LibraryState", ")", ":", "use_runti...
Function set renderer properties for every single cell independently The function controls the editable and color scheme for every cell in the default value column according the use_runtime_value flag and whether the state is a library state. :param tree_view_column: the Gtk.TreeViewColumn to be rendered :param cell: the current CellRenderer :param model: the Gtk.ListStore or TreeStore that is the model for TreeView :param iter: an iterator over the rows of the TreeStore/Gtk.ListStore Model :param data: optional data to be passed: see http://dumbmatter.com/2012/02/some-notes-on-porting-from-pygtk-to-pygobject/
[ "Function", "set", "renderer", "properties", "for", "every", "single", "cell", "independently" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/io_data_port_list.py#L178-L201
train
40,341
DLR-RM/RAFCON
source/rafcon/gui/controllers/state_editor/io_data_port_list.py
DataPortListController._reload_data_port_list_store
def _reload_data_port_list_store(self): """Reloads the input data port list store from the data port models""" tmp = self._get_new_list_store() for data_port_m in self.data_port_model_list: data_port_id = data_port_m.data_port.data_port_id data_type = data_port_m.data_port.data_type # get name of type (e.g. ndarray) data_type_name = data_type.__name__ # get module of type, e.g. numpy data_type_module = data_type.__module__ # if the type is not a builtin type, also show the module if data_type_module not in ['__builtin__', 'builtins']: data_type_name = data_type_module + '.' + data_type_name if data_port_m.data_port.default_value is None: default_value = "None" else: default_value = data_port_m.data_port.default_value if not isinstance(self.model.state, LibraryState): tmp.append([data_port_m.data_port.name, data_type_name, str(default_value), data_port_id, None, None, data_port_m]) else: use_runtime_value, runtime_value = self.get_data_port_runtime_configuration(data_port_id) tmp.append([data_port_m.data_port.name, data_type_name, str(default_value), data_port_id, bool(use_runtime_value), str(runtime_value), data_port_m, ]) tms = Gtk.TreeModelSort(model=tmp) tms.set_sort_column_id(0, Gtk.SortType.ASCENDING) tms.set_sort_func(0, compare_variables) tms.sort_column_changed() tmp = tms self.list_store.clear() for elem in tmp: self.list_store.append(elem[:])
python
def _reload_data_port_list_store(self): """Reloads the input data port list store from the data port models""" tmp = self._get_new_list_store() for data_port_m in self.data_port_model_list: data_port_id = data_port_m.data_port.data_port_id data_type = data_port_m.data_port.data_type # get name of type (e.g. ndarray) data_type_name = data_type.__name__ # get module of type, e.g. numpy data_type_module = data_type.__module__ # if the type is not a builtin type, also show the module if data_type_module not in ['__builtin__', 'builtins']: data_type_name = data_type_module + '.' + data_type_name if data_port_m.data_port.default_value is None: default_value = "None" else: default_value = data_port_m.data_port.default_value if not isinstance(self.model.state, LibraryState): tmp.append([data_port_m.data_port.name, data_type_name, str(default_value), data_port_id, None, None, data_port_m]) else: use_runtime_value, runtime_value = self.get_data_port_runtime_configuration(data_port_id) tmp.append([data_port_m.data_port.name, data_type_name, str(default_value), data_port_id, bool(use_runtime_value), str(runtime_value), data_port_m, ]) tms = Gtk.TreeModelSort(model=tmp) tms.set_sort_column_id(0, Gtk.SortType.ASCENDING) tms.set_sort_func(0, compare_variables) tms.sort_column_changed() tmp = tms self.list_store.clear() for elem in tmp: self.list_store.append(elem[:])
[ "def", "_reload_data_port_list_store", "(", "self", ")", ":", "tmp", "=", "self", ".", "_get_new_list_store", "(", ")", "for", "data_port_m", "in", "self", ".", "data_port_model_list", ":", "data_port_id", "=", "data_port_m", ".", "data_port", ".", "data_port_id",...
Reloads the input data port list store from the data port models
[ "Reloads", "the", "input", "data", "port", "list", "store", "from", "the", "data", "port", "models" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/io_data_port_list.py#L203-L243
train
40,342
DLR-RM/RAFCON
source/rafcon/gui/controllers/state_editor/io_data_port_list.py
DataPortListController._apply_new_data_port_name
def _apply_new_data_port_name(self, path, new_name): """Applies the new name of the data port defined by path :param str path: The path identifying the edited data port :param str new_name: New name """ try: data_port_id = self.list_store[path][self.ID_STORAGE_ID] if self.state_data_port_dict[data_port_id].name != new_name: self.state_data_port_dict[data_port_id].name = new_name except (TypeError, ValueError) as e: logger.exception("Error while trying to change data port name")
python
def _apply_new_data_port_name(self, path, new_name): """Applies the new name of the data port defined by path :param str path: The path identifying the edited data port :param str new_name: New name """ try: data_port_id = self.list_store[path][self.ID_STORAGE_ID] if self.state_data_port_dict[data_port_id].name != new_name: self.state_data_port_dict[data_port_id].name = new_name except (TypeError, ValueError) as e: logger.exception("Error while trying to change data port name")
[ "def", "_apply_new_data_port_name", "(", "self", ",", "path", ",", "new_name", ")", ":", "try", ":", "data_port_id", "=", "self", ".", "list_store", "[", "path", "]", "[", "self", ".", "ID_STORAGE_ID", "]", "if", "self", ".", "state_data_port_dict", "[", "...
Applies the new name of the data port defined by path :param str path: The path identifying the edited data port :param str new_name: New name
[ "Applies", "the", "new", "name", "of", "the", "data", "port", "defined", "by", "path" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/io_data_port_list.py#L245-L256
train
40,343
DLR-RM/RAFCON
source/rafcon/gui/controllers/state_editor/io_data_port_list.py
DataPortListController._apply_new_data_port_type
def _apply_new_data_port_type(self, path, new_data_type_str): """Applies the new data type of the data port defined by path :param str path: The path identifying the edited data port :param str new_data_type_str: New data type as str """ try: data_port_id = self.list_store[path][self.ID_STORAGE_ID] if self.state_data_port_dict[data_port_id].data_type.__name__ != new_data_type_str: self.state_data_port_dict[data_port_id].change_data_type(new_data_type_str) except ValueError as e: logger.exception("Error while changing data type")
python
def _apply_new_data_port_type(self, path, new_data_type_str): """Applies the new data type of the data port defined by path :param str path: The path identifying the edited data port :param str new_data_type_str: New data type as str """ try: data_port_id = self.list_store[path][self.ID_STORAGE_ID] if self.state_data_port_dict[data_port_id].data_type.__name__ != new_data_type_str: self.state_data_port_dict[data_port_id].change_data_type(new_data_type_str) except ValueError as e: logger.exception("Error while changing data type")
[ "def", "_apply_new_data_port_type", "(", "self", ",", "path", ",", "new_data_type_str", ")", ":", "try", ":", "data_port_id", "=", "self", ".", "list_store", "[", "path", "]", "[", "self", ".", "ID_STORAGE_ID", "]", "if", "self", ".", "state_data_port_dict", ...
Applies the new data type of the data port defined by path :param str path: The path identifying the edited data port :param str new_data_type_str: New data type as str
[ "Applies", "the", "new", "data", "type", "of", "the", "data", "port", "defined", "by", "path" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/io_data_port_list.py#L258-L269
train
40,344
DLR-RM/RAFCON
source/rafcon/gui/controllers/state_editor/io_data_port_list.py
DataPortListController._apply_new_data_port_default_value
def _apply_new_data_port_default_value(self, path, new_default_value_str): """Applies the new default value of the data port defined by path :param str path: The path identifying the edited variable :param str new_default_value_str: New default value as string """ try: data_port_id = self.list_store[path][self.ID_STORAGE_ID] if isinstance(self.model.state, LibraryState): # this always has to be true, as the runtime value column can only be edited # if the use_runtime_value flag is True if self.list_store[path][self.USE_RUNTIME_VALUE_STORAGE_ID]: self.set_data_port_runtime_value(data_port_id, new_default_value_str) else: if str(self.state_data_port_dict[data_port_id].default_value) != new_default_value_str: self.state_data_port_dict[data_port_id].default_value = new_default_value_str except (TypeError, AttributeError) as e: logger.exception("Error while changing default value")
python
def _apply_new_data_port_default_value(self, path, new_default_value_str): """Applies the new default value of the data port defined by path :param str path: The path identifying the edited variable :param str new_default_value_str: New default value as string """ try: data_port_id = self.list_store[path][self.ID_STORAGE_ID] if isinstance(self.model.state, LibraryState): # this always has to be true, as the runtime value column can only be edited # if the use_runtime_value flag is True if self.list_store[path][self.USE_RUNTIME_VALUE_STORAGE_ID]: self.set_data_port_runtime_value(data_port_id, new_default_value_str) else: if str(self.state_data_port_dict[data_port_id].default_value) != new_default_value_str: self.state_data_port_dict[data_port_id].default_value = new_default_value_str except (TypeError, AttributeError) as e: logger.exception("Error while changing default value")
[ "def", "_apply_new_data_port_default_value", "(", "self", ",", "path", ",", "new_default_value_str", ")", ":", "try", ":", "data_port_id", "=", "self", ".", "list_store", "[", "path", "]", "[", "self", ".", "ID_STORAGE_ID", "]", "if", "isinstance", "(", "self"...
Applies the new default value of the data port defined by path :param str path: The path identifying the edited variable :param str new_default_value_str: New default value as string
[ "Applies", "the", "new", "default", "value", "of", "the", "data", "port", "defined", "by", "path" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/io_data_port_list.py#L271-L288
train
40,345
DLR-RM/RAFCON
source/rafcon/gui/controllers/state_editor/io_data_port_list.py
DataPortListController._data_ports_changed
def _data_ports_changed(self, model): """Reload list store and reminds selection when the model was changed""" if not isinstance(model, AbstractStateModel): return # store port selection path_list = None if self.view is not None: model, path_list = self.tree_view.get_selection().get_selected_rows() selected_data_port_ids = [self.list_store[path[0]][self.ID_STORAGE_ID] for path in path_list] if path_list else [] self._reload_data_port_list_store() # recover port selection if selected_data_port_ids: [self.select_entry(selected_data_port_id, False) for selected_data_port_id in selected_data_port_ids]
python
def _data_ports_changed(self, model): """Reload list store and reminds selection when the model was changed""" if not isinstance(model, AbstractStateModel): return # store port selection path_list = None if self.view is not None: model, path_list = self.tree_view.get_selection().get_selected_rows() selected_data_port_ids = [self.list_store[path[0]][self.ID_STORAGE_ID] for path in path_list] if path_list else [] self._reload_data_port_list_store() # recover port selection if selected_data_port_ids: [self.select_entry(selected_data_port_id, False) for selected_data_port_id in selected_data_port_ids]
[ "def", "_data_ports_changed", "(", "self", ",", "model", ")", ":", "if", "not", "isinstance", "(", "model", ",", "AbstractStateModel", ")", ":", "return", "# store port selection", "path_list", "=", "None", "if", "self", ".", "view", "is", "not", "None", ":"...
Reload list store and reminds selection when the model was changed
[ "Reload", "list", "store", "and", "reminds", "selection", "when", "the", "model", "was", "changed" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/io_data_port_list.py#L290-L302
train
40,346
DLR-RM/RAFCON
source/rafcon/gui/controllers/state_editor/io_data_port_list.py
InputPortListController.runtime_values_changed
def runtime_values_changed(self, model, prop_name, info): """Handle cases for the library runtime values""" if ("_input_runtime_value" in info.method_name or info.method_name in ['use_runtime_value_input_data_ports', 'input_data_port_runtime_values']) and \ self.model is model: self._data_ports_changed(model)
python
def runtime_values_changed(self, model, prop_name, info): """Handle cases for the library runtime values""" if ("_input_runtime_value" in info.method_name or info.method_name in ['use_runtime_value_input_data_ports', 'input_data_port_runtime_values']) and \ self.model is model: self._data_ports_changed(model)
[ "def", "runtime_values_changed", "(", "self", ",", "model", ",", "prop_name", ",", "info", ")", ":", "if", "(", "\"_input_runtime_value\"", "in", "info", ".", "method_name", "or", "info", ".", "method_name", "in", "[", "'use_runtime_value_input_data_ports'", ",", ...
Handle cases for the library runtime values
[ "Handle", "cases", "for", "the", "library", "runtime", "values" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/io_data_port_list.py#L325-L331
train
40,347
DLR-RM/RAFCON
source/rafcon/gui/controllers/state_editor/io_data_port_list.py
OutputPortListController.add_new_data_port
def add_new_data_port(self): """Add a new port with default values and select it""" try: new_data_port_ids = gui_helper_state_machine.add_data_port_to_selected_states('OUTPUT', int, [self.model]) if new_data_port_ids: self.select_entry(new_data_port_ids[self.model.state]) except ValueError: pass
python
def add_new_data_port(self): """Add a new port with default values and select it""" try: new_data_port_ids = gui_helper_state_machine.add_data_port_to_selected_states('OUTPUT', int, [self.model]) if new_data_port_ids: self.select_entry(new_data_port_ids[self.model.state]) except ValueError: pass
[ "def", "add_new_data_port", "(", "self", ")", ":", "try", ":", "new_data_port_ids", "=", "gui_helper_state_machine", ".", "add_data_port_to_selected_states", "(", "'OUTPUT'", ",", "int", ",", "[", "self", ".", "model", "]", ")", "if", "new_data_port_ids", ":", "...
Add a new port with default values and select it
[ "Add", "a", "new", "port", "with", "default", "values", "and", "select", "it" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/io_data_port_list.py#L420-L427
train
40,348
DLR-RM/RAFCON
source/rafcon/gui/shortcut_manager.py
ShortcutManager.add_callback_for_action
def add_callback_for_action(self, action, callback): """Adds a callback function to an action The method checks whether both action and callback are valid. If so, the callback is added to the list of functions called when the action is triggered. :param str action: An action like 'add', 'copy', 'info' :param callback: A callback function, which is called when action is triggered. It retrieves the event as parameter :return: True is the parameters are valid and the callback is registered, False else :rtype: bool """ if hasattr(callback, '__call__'): # Is the callback really a function? if action not in self.__action_to_callbacks: self.__action_to_callbacks[action] = [] self.__action_to_callbacks[action].append(callback) controller = None try: controller = callback.__self__ except AttributeError: try: # Needed when callback was wrapped using functools.partial controller = callback.func.__self__ except AttributeError: pass if controller: if controller not in self.__controller_action_callbacks: self.__controller_action_callbacks[controller] = {} if action not in self.__controller_action_callbacks[controller]: self.__controller_action_callbacks[controller][action] = [] self.__controller_action_callbacks[controller][action].append(callback) return True
python
def add_callback_for_action(self, action, callback): """Adds a callback function to an action The method checks whether both action and callback are valid. If so, the callback is added to the list of functions called when the action is triggered. :param str action: An action like 'add', 'copy', 'info' :param callback: A callback function, which is called when action is triggered. It retrieves the event as parameter :return: True is the parameters are valid and the callback is registered, False else :rtype: bool """ if hasattr(callback, '__call__'): # Is the callback really a function? if action not in self.__action_to_callbacks: self.__action_to_callbacks[action] = [] self.__action_to_callbacks[action].append(callback) controller = None try: controller = callback.__self__ except AttributeError: try: # Needed when callback was wrapped using functools.partial controller = callback.func.__self__ except AttributeError: pass if controller: if controller not in self.__controller_action_callbacks: self.__controller_action_callbacks[controller] = {} if action not in self.__controller_action_callbacks[controller]: self.__controller_action_callbacks[controller][action] = [] self.__controller_action_callbacks[controller][action].append(callback) return True
[ "def", "add_callback_for_action", "(", "self", ",", "action", ",", "callback", ")", ":", "if", "hasattr", "(", "callback", ",", "'__call__'", ")", ":", "# Is the callback really a function?", "if", "action", "not", "in", "self", ".", "__action_to_callbacks", ":", ...
Adds a callback function to an action The method checks whether both action and callback are valid. If so, the callback is added to the list of functions called when the action is triggered. :param str action: An action like 'add', 'copy', 'info' :param callback: A callback function, which is called when action is triggered. It retrieves the event as parameter :return: True is the parameters are valid and the callback is registered, False else :rtype: bool
[ "Adds", "a", "callback", "function", "to", "an", "action" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/shortcut_manager.py#L72-L106
train
40,349
DLR-RM/RAFCON
source/rafcon/gui/shortcut_manager.py
ShortcutManager.remove_callback_for_action
def remove_callback_for_action(self, action, callback): """ Remove a callback for a specific action This is mainly for cleanup purposes or a plugin that replaces a GUI widget. :param str action: the cation of which the callback is going to be remove :param callback: the callback to be removed """ if action in self.__action_to_callbacks: if callback in self.__action_to_callbacks[action]: self.__action_to_callbacks[action].remove(callback)
python
def remove_callback_for_action(self, action, callback): """ Remove a callback for a specific action This is mainly for cleanup purposes or a plugin that replaces a GUI widget. :param str action: the cation of which the callback is going to be remove :param callback: the callback to be removed """ if action in self.__action_to_callbacks: if callback in self.__action_to_callbacks[action]: self.__action_to_callbacks[action].remove(callback)
[ "def", "remove_callback_for_action", "(", "self", ",", "action", ",", "callback", ")", ":", "if", "action", "in", "self", ".", "__action_to_callbacks", ":", "if", "callback", "in", "self", ".", "__action_to_callbacks", "[", "action", "]", ":", "self", ".", "...
Remove a callback for a specific action This is mainly for cleanup purposes or a plugin that replaces a GUI widget. :param str action: the cation of which the callback is going to be remove :param callback: the callback to be removed
[ "Remove", "a", "callback", "for", "a", "specific", "action" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/shortcut_manager.py#L108-L118
train
40,350
DLR-RM/RAFCON
source/rafcon/gui/controllers/state_editor/linkage_list.py
LinkageListController.check_info_on_no_update_flags
def check_info_on_no_update_flags(self, info): """Stop updates while multi-actions""" # TODO that could need a second clean up # avoid updates because of state destruction if 'before' in info and info['method_name'] == "remove_state": if info.instance is self.model.state: self.no_update_state_destruction = True else: # if the state it self is removed lock the widget to never run updates and relieve all models removed_state_id = info.args[1] if len(info.args) > 1 else info.kwargs['state_id'] if removed_state_id == self.model.state.state_id or \ not self.model.state.is_root_state and removed_state_id == self.model.parent.state.state_id: self.no_update_self_or_parent_state_destruction = True self.relieve_all_models() elif 'after' in info and info['method_name'] == "remove_state": if info.instance.state_id == self.model.state.state_id: self.no_update_state_destruction = False # reduce NotificationOverview generations by the fact that after could cause False and before could cause True if not self.no_update_state_destruction and not self.no_update_self_or_parent_state_destruction and \ (not self.no_update and 'before' in info or 'after' in info and self.no_update): return overview = NotificationOverview(info, False, self.__class__.__name__) # The method causing the change raised an exception, thus nothing was changed and updates are allowed if 'after' in info and isinstance(overview['result'][-1], Exception): self.no_update = False self.no_update_state_destruction = False # self.no_update_self_or_parent_state_destruction = False return if overview['method_name'][-1] in ['group_states', 'ungroup_state', "change_state_type", "change_root_state_type"]: instance_is_self = self.model.state is overview['instance'][-1] instance_is_parent = self.model.parent and self.model.parent.state is overview['instance'][-1] instance_is_parent_parent = self.model.parent and self.model.parent.parent and self.model.parent.parent.state is overview['instance'][-1] # print("no update flag: ", True if 'before' in info and (instance_is_self or instance_is_parent or instance_is_parent_parent) else False) if instance_is_self or instance_is_parent or instance_is_parent_parent: self.no_update = True if 'before' in info else False if overview['prop_name'][-1] == 'state' and overview['method_name'][-1] in ["change_state_type"] and \ self.model.get_state_machine_m() is not None: changed_model = self.model.get_state_machine_m().get_state_model_by_path(overview['args'][-1][1].get_path()) if changed_model not in self._model_observed: self.observe_model(changed_model)
python
def check_info_on_no_update_flags(self, info): """Stop updates while multi-actions""" # TODO that could need a second clean up # avoid updates because of state destruction if 'before' in info and info['method_name'] == "remove_state": if info.instance is self.model.state: self.no_update_state_destruction = True else: # if the state it self is removed lock the widget to never run updates and relieve all models removed_state_id = info.args[1] if len(info.args) > 1 else info.kwargs['state_id'] if removed_state_id == self.model.state.state_id or \ not self.model.state.is_root_state and removed_state_id == self.model.parent.state.state_id: self.no_update_self_or_parent_state_destruction = True self.relieve_all_models() elif 'after' in info and info['method_name'] == "remove_state": if info.instance.state_id == self.model.state.state_id: self.no_update_state_destruction = False # reduce NotificationOverview generations by the fact that after could cause False and before could cause True if not self.no_update_state_destruction and not self.no_update_self_or_parent_state_destruction and \ (not self.no_update and 'before' in info or 'after' in info and self.no_update): return overview = NotificationOverview(info, False, self.__class__.__name__) # The method causing the change raised an exception, thus nothing was changed and updates are allowed if 'after' in info and isinstance(overview['result'][-1], Exception): self.no_update = False self.no_update_state_destruction = False # self.no_update_self_or_parent_state_destruction = False return if overview['method_name'][-1] in ['group_states', 'ungroup_state', "change_state_type", "change_root_state_type"]: instance_is_self = self.model.state is overview['instance'][-1] instance_is_parent = self.model.parent and self.model.parent.state is overview['instance'][-1] instance_is_parent_parent = self.model.parent and self.model.parent.parent and self.model.parent.parent.state is overview['instance'][-1] # print("no update flag: ", True if 'before' in info and (instance_is_self or instance_is_parent or instance_is_parent_parent) else False) if instance_is_self or instance_is_parent or instance_is_parent_parent: self.no_update = True if 'before' in info else False if overview['prop_name'][-1] == 'state' and overview['method_name'][-1] in ["change_state_type"] and \ self.model.get_state_machine_m() is not None: changed_model = self.model.get_state_machine_m().get_state_model_by_path(overview['args'][-1][1].get_path()) if changed_model not in self._model_observed: self.observe_model(changed_model)
[ "def", "check_info_on_no_update_flags", "(", "self", ",", "info", ")", ":", "# TODO that could need a second clean up", "# avoid updates because of state destruction", "if", "'before'", "in", "info", "and", "info", "[", "'method_name'", "]", "==", "\"remove_state\"", ":", ...
Stop updates while multi-actions
[ "Stop", "updates", "while", "multi", "-", "actions" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/linkage_list.py#L82-L127
train
40,351
DLR-RM/RAFCON
source/rafcon/gui/controllers/state_editor/linkage_list.py
LinkageListController.before_notification_state_machine_observation_control
def before_notification_state_machine_observation_control(self, model, prop_name, info): """Check for multi-actions and set respective no update flags. """ if is_execution_status_update_notification_from_state_machine_model(prop_name, info): return # do not update while multi-actions self.check_info_on_no_update_flags(info)
python
def before_notification_state_machine_observation_control(self, model, prop_name, info): """Check for multi-actions and set respective no update flags. """ if is_execution_status_update_notification_from_state_machine_model(prop_name, info): return # do not update while multi-actions self.check_info_on_no_update_flags(info)
[ "def", "before_notification_state_machine_observation_control", "(", "self", ",", "model", ",", "prop_name", ",", "info", ")", ":", "if", "is_execution_status_update_notification_from_state_machine_model", "(", "prop_name", ",", "info", ")", ":", "return", "# do not update ...
Check for multi-actions and set respective no update flags.
[ "Check", "for", "multi", "-", "actions", "and", "set", "respective", "no", "update", "flags", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/linkage_list.py#L155-L160
train
40,352
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/cache/value_cache.py
ValueCache.store_value
def store_value(self, name, value, parameters=None): """Stores the value of a certain variable The value of a variable with name 'name' is stored together with the parameters that were used for the calculation. :param str name: The name of the variable :param value: The value to be cached :param dict parameters: The parameters on which the value depends """ if not isinstance(parameters, dict): raise TypeError("parameters must be a dict") hash = self._parameter_hash(parameters) if name not in self._cache: self._cache[name] = {} self._cache[name][hash.hexdigest()] = value
python
def store_value(self, name, value, parameters=None): """Stores the value of a certain variable The value of a variable with name 'name' is stored together with the parameters that were used for the calculation. :param str name: The name of the variable :param value: The value to be cached :param dict parameters: The parameters on which the value depends """ if not isinstance(parameters, dict): raise TypeError("parameters must be a dict") hash = self._parameter_hash(parameters) if name not in self._cache: self._cache[name] = {} self._cache[name][hash.hexdigest()] = value
[ "def", "store_value", "(", "self", ",", "name", ",", "value", ",", "parameters", "=", "None", ")", ":", "if", "not", "isinstance", "(", "parameters", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"parameters must be a dict\"", ")", "hash", "=", "self...
Stores the value of a certain variable The value of a variable with name 'name' is stored together with the parameters that were used for the calculation. :param str name: The name of the variable :param value: The value to be cached :param dict parameters: The parameters on which the value depends
[ "Stores", "the", "value", "of", "a", "certain", "variable" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/cache/value_cache.py#L42-L57
train
40,353
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/cache/value_cache.py
ValueCache.get_value
def get_value(self, name, parameters=None): """Return the value of a cached variable if applicable The value of the variable 'name' is returned, if no parameters are passed or if all parameters are identical to the ones stored for the variable. :param str name: Name of teh variable :param dict parameters: Current parameters or None if parameters do not matter :return: The cached value of the variable or None if the parameters differ """ if not isinstance(parameters, dict): raise TypeError("parameters must a dict") if name not in self._cache: return None hash = self._parameter_hash(parameters) hashdigest = hash.hexdigest() return self._cache[name].get(hashdigest, None)
python
def get_value(self, name, parameters=None): """Return the value of a cached variable if applicable The value of the variable 'name' is returned, if no parameters are passed or if all parameters are identical to the ones stored for the variable. :param str name: Name of teh variable :param dict parameters: Current parameters or None if parameters do not matter :return: The cached value of the variable or None if the parameters differ """ if not isinstance(parameters, dict): raise TypeError("parameters must a dict") if name not in self._cache: return None hash = self._parameter_hash(parameters) hashdigest = hash.hexdigest() return self._cache[name].get(hashdigest, None)
[ "def", "get_value", "(", "self", ",", "name", ",", "parameters", "=", "None", ")", ":", "if", "not", "isinstance", "(", "parameters", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"parameters must a dict\"", ")", "if", "name", "not", "in", "self", ...
Return the value of a cached variable if applicable The value of the variable 'name' is returned, if no parameters are passed or if all parameters are identical to the ones stored for the variable. :param str name: Name of teh variable :param dict parameters: Current parameters or None if parameters do not matter :return: The cached value of the variable or None if the parameters differ
[ "Return", "the", "value", "of", "a", "cached", "variable", "if", "applicable" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/cache/value_cache.py#L59-L75
train
40,354
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/cache/value_cache.py
ValueCache._normalize_number_values
def _normalize_number_values(self, parameters): """Assures equal precision for all number values""" for key, value in parameters.items(): if isinstance(value, (int, float)): parameters[key] = str(Decimal(value).normalize(self._context))
python
def _normalize_number_values(self, parameters): """Assures equal precision for all number values""" for key, value in parameters.items(): if isinstance(value, (int, float)): parameters[key] = str(Decimal(value).normalize(self._context))
[ "def", "_normalize_number_values", "(", "self", ",", "parameters", ")", ":", "for", "key", ",", "value", "in", "parameters", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "(", "int", ",", "float", ")", ")", ":", "parameters", "[",...
Assures equal precision for all number values
[ "Assures", "equal", "precision", "for", "all", "number", "values" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/cache/value_cache.py#L83-L87
train
40,355
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/tree_view_controller.py
AbstractTreeViewController.get_view_selection
def get_view_selection(self): """Get actual tree selection object and all respective models of selected rows""" if not self.MODEL_STORAGE_ID: return None, None # avoid selection requests on empty tree views -> case warnings in gtk3 if len(self.store) == 0: paths = [] else: model, paths = self._tree_selection.get_selected_rows() # get all related models for selection from respective tree store field selected_model_list = [] for path in paths: model = self.store[path][self.MODEL_STORAGE_ID] selected_model_list.append(model) return self._tree_selection, selected_model_list
python
def get_view_selection(self): """Get actual tree selection object and all respective models of selected rows""" if not self.MODEL_STORAGE_ID: return None, None # avoid selection requests on empty tree views -> case warnings in gtk3 if len(self.store) == 0: paths = [] else: model, paths = self._tree_selection.get_selected_rows() # get all related models for selection from respective tree store field selected_model_list = [] for path in paths: model = self.store[path][self.MODEL_STORAGE_ID] selected_model_list.append(model) return self._tree_selection, selected_model_list
[ "def", "get_view_selection", "(", "self", ")", ":", "if", "not", "self", ".", "MODEL_STORAGE_ID", ":", "return", "None", ",", "None", "# avoid selection requests on empty tree views -> case warnings in gtk3", "if", "len", "(", "self", ".", "store", ")", "==", "0", ...
Get actual tree selection object and all respective models of selected rows
[ "Get", "actual", "tree", "selection", "object", "and", "all", "respective", "models", "of", "selected", "rows" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L101-L117
train
40,356
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/tree_view_controller.py
AbstractTreeViewController.state_machine_selection_changed
def state_machine_selection_changed(self, state_machine_m, signal_name, signal_msg): """Notify tree view about state machine selection""" if self.CORE_ELEMENT_CLASS in signal_msg.arg.affected_core_element_classes: self.update_selection_sm_prior()
python
def state_machine_selection_changed(self, state_machine_m, signal_name, signal_msg): """Notify tree view about state machine selection""" if self.CORE_ELEMENT_CLASS in signal_msg.arg.affected_core_element_classes: self.update_selection_sm_prior()
[ "def", "state_machine_selection_changed", "(", "self", ",", "state_machine_m", ",", "signal_name", ",", "signal_msg", ")", ":", "if", "self", ".", "CORE_ELEMENT_CLASS", "in", "signal_msg", ".", "arg", ".", "affected_core_element_classes", ":", "self", ".", "update_s...
Notify tree view about state machine selection
[ "Notify", "tree", "view", "about", "state", "machine", "selection" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L141-L144
train
40,357
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/tree_view_controller.py
AbstractTreeViewController.remove_action_callback
def remove_action_callback(self, *event): """Callback method for remove action The method checks whether a shortcut ('Delete') is in the gui config model which shadow the delete functionality of maybe active a entry widget. If a entry widget is active the remove callback return with None. """ if react_to_event(self.view, self.tree_view, event) and \ not (self.active_entry_widget and not is_event_of_key_string(event, 'Delete')): self.on_remove(None) return True
python
def remove_action_callback(self, *event): """Callback method for remove action The method checks whether a shortcut ('Delete') is in the gui config model which shadow the delete functionality of maybe active a entry widget. If a entry widget is active the remove callback return with None. """ if react_to_event(self.view, self.tree_view, event) and \ not (self.active_entry_widget and not is_event_of_key_string(event, 'Delete')): self.on_remove(None) return True
[ "def", "remove_action_callback", "(", "self", ",", "*", "event", ")", ":", "if", "react_to_event", "(", "self", ".", "view", ",", "self", ".", "tree_view", ",", "event", ")", "and", "not", "(", "self", ".", "active_entry_widget", "and", "not", "is_event_of...
Callback method for remove action The method checks whether a shortcut ('Delete') is in the gui config model which shadow the delete functionality of maybe active a entry widget. If a entry widget is active the remove callback return with None.
[ "Callback", "method", "for", "remove", "action" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L192-L201
train
40,358
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/tree_view_controller.py
AbstractTreeViewController._apply_value_on_edited_and_focus_out
def _apply_value_on_edited_and_focus_out(self, renderer, apply_method): """Sets up the renderer to apply changed when loosing focus The default behaviour for the focus out event dismisses the changes in the renderer. Therefore we setup handlers for that event, applying the changes. :param Gtk.CellRendererText renderer: The cell renderer who's changes are to be applied on focus out events :param apply_method: The callback method applying the newly entered value """ assert isinstance(renderer, Gtk.CellRenderer) def remove_all_handler(renderer): """Remove all handler for given renderer and its editable :param renderer: Renderer of the respective column which is edit by a entry widget, at the moment """ def remove_handler(widget, data_name): """Remove handler from given widget :param Gtk.Widget widget: Widget from which a handler is to be removed :param data_name: Name of the data of the widget in which the handler id is stored """ handler_id = getattr(widget, data_name) if widget.handler_is_connected(handler_id): widget.disconnect(handler_id) editable = getattr(renderer, "editable") remove_handler(editable, "focus_out_handler_id") remove_handler(editable, "cursor_move_handler_id") remove_handler(editable, "insert_at_cursor_handler_id") remove_handler(editable, "entry_widget_expose_event_handler_id") remove_handler(renderer, "editing_cancelled_handler_id") def on_focus_out(entry, event): """Applies the changes to the entry :param Gtk.Entry entry: The entry that was focused out :param Gtk.Event event: Event object with information about the event """ renderer.remove_all_handler(renderer) if renderer.ctrl.get_path() is None: return # Originally we had to use idle_add to prevent core dumps: # https://mail.gnome.org/archives/gtk-perl-list/2005-September/msg00143.html # Gtk TODO: use idle_add if there are problems apply_method(renderer.ctrl.get_path(), entry.get_text()) def on_cursor_move_in_entry_widget(entry, step, count, extend_selection): """Trigger scroll bar adjustments according active entry widgets cursor change """ self.tree_view_keypress_callback(entry, None) def on_editing_started(renderer, editable, path): """Connects the a handler for the focus-out-event of the current editable :param Gtk.CellRendererText renderer: The cell renderer who's editing was started :param Gtk.CellEditable editable: interface for editing the current TreeView cell :param str path: the path identifying the edited cell """ # secure scrollbar adjustments on active cell ctrl = renderer.ctrl [path, focus_column] = ctrl.tree_view.get_cursor() if path: ctrl.tree_view.scroll_to_cell(path, ctrl.widget_columns[ctrl.widget_columns.index(focus_column)], use_align=False) editing_cancelled_handler_id = renderer.connect('editing-canceled', on_editing_canceled) focus_out_handler_id = editable.connect('focus-out-event', on_focus_out) cursor_move_handler_id = editable.connect('move-cursor', on_cursor_move_in_entry_widget) insert_at_cursor_handler_id = editable.connect("insert-at-cursor", on_cursor_move_in_entry_widget) entry_widget_expose_event_handler_id = editable.connect("draw", self.on_entry_widget_draw_event) # Store reference to editable and signal handler ids for later access when removing the handlers # see https://gitlab.gnome.org/GNOME/accerciser/commit/036689e70304a9e98ce31238dfad2432ad4c78ea # originally with renderer.set_data() # renderer.set_data("editable", editable) setattr(renderer, "editable", editable) setattr(renderer, "editing_cancelled_handler_id", editing_cancelled_handler_id) # editable setattr(editable, "focus_out_handler_id", focus_out_handler_id) setattr(editable, "cursor_move_handler_id", cursor_move_handler_id) setattr(editable, "insert_at_cursor_handler_id", insert_at_cursor_handler_id) setattr(editable, "entry_widget_expose_event_handler_id", entry_widget_expose_event_handler_id) ctrl.active_entry_widget = editable def on_edited(renderer, path, new_value_str): """Calls the apply method with the new value :param Gtk.CellRendererText renderer: The cell renderer that was edited :param str path: The path string of the renderer :param str new_value_str: The new value as string """ renderer.remove_all_handler(renderer) apply_method(path, new_value_str) renderer.ctrl.active_entry_widget = None def on_editing_canceled(renderer): """Disconnects the focus-out-event handler of cancelled editable :param Gtk.CellRendererText renderer: The cell renderer who's editing was cancelled """ remove_all_handler(renderer) renderer.ctrl.active_entry_widget = None renderer.remove_all_handler = remove_all_handler renderer.ctrl = self # renderer.connect('editing-started', on_editing_started) # renderer.connect('edited', on_edited) self.__attached_renderers.append(renderer) self.connect_signal(renderer, 'editing-started', on_editing_started) self.connect_signal(renderer, 'edited', on_edited)
python
def _apply_value_on_edited_and_focus_out(self, renderer, apply_method): """Sets up the renderer to apply changed when loosing focus The default behaviour for the focus out event dismisses the changes in the renderer. Therefore we setup handlers for that event, applying the changes. :param Gtk.CellRendererText renderer: The cell renderer who's changes are to be applied on focus out events :param apply_method: The callback method applying the newly entered value """ assert isinstance(renderer, Gtk.CellRenderer) def remove_all_handler(renderer): """Remove all handler for given renderer and its editable :param renderer: Renderer of the respective column which is edit by a entry widget, at the moment """ def remove_handler(widget, data_name): """Remove handler from given widget :param Gtk.Widget widget: Widget from which a handler is to be removed :param data_name: Name of the data of the widget in which the handler id is stored """ handler_id = getattr(widget, data_name) if widget.handler_is_connected(handler_id): widget.disconnect(handler_id) editable = getattr(renderer, "editable") remove_handler(editable, "focus_out_handler_id") remove_handler(editable, "cursor_move_handler_id") remove_handler(editable, "insert_at_cursor_handler_id") remove_handler(editable, "entry_widget_expose_event_handler_id") remove_handler(renderer, "editing_cancelled_handler_id") def on_focus_out(entry, event): """Applies the changes to the entry :param Gtk.Entry entry: The entry that was focused out :param Gtk.Event event: Event object with information about the event """ renderer.remove_all_handler(renderer) if renderer.ctrl.get_path() is None: return # Originally we had to use idle_add to prevent core dumps: # https://mail.gnome.org/archives/gtk-perl-list/2005-September/msg00143.html # Gtk TODO: use idle_add if there are problems apply_method(renderer.ctrl.get_path(), entry.get_text()) def on_cursor_move_in_entry_widget(entry, step, count, extend_selection): """Trigger scroll bar adjustments according active entry widgets cursor change """ self.tree_view_keypress_callback(entry, None) def on_editing_started(renderer, editable, path): """Connects the a handler for the focus-out-event of the current editable :param Gtk.CellRendererText renderer: The cell renderer who's editing was started :param Gtk.CellEditable editable: interface for editing the current TreeView cell :param str path: the path identifying the edited cell """ # secure scrollbar adjustments on active cell ctrl = renderer.ctrl [path, focus_column] = ctrl.tree_view.get_cursor() if path: ctrl.tree_view.scroll_to_cell(path, ctrl.widget_columns[ctrl.widget_columns.index(focus_column)], use_align=False) editing_cancelled_handler_id = renderer.connect('editing-canceled', on_editing_canceled) focus_out_handler_id = editable.connect('focus-out-event', on_focus_out) cursor_move_handler_id = editable.connect('move-cursor', on_cursor_move_in_entry_widget) insert_at_cursor_handler_id = editable.connect("insert-at-cursor", on_cursor_move_in_entry_widget) entry_widget_expose_event_handler_id = editable.connect("draw", self.on_entry_widget_draw_event) # Store reference to editable and signal handler ids for later access when removing the handlers # see https://gitlab.gnome.org/GNOME/accerciser/commit/036689e70304a9e98ce31238dfad2432ad4c78ea # originally with renderer.set_data() # renderer.set_data("editable", editable) setattr(renderer, "editable", editable) setattr(renderer, "editing_cancelled_handler_id", editing_cancelled_handler_id) # editable setattr(editable, "focus_out_handler_id", focus_out_handler_id) setattr(editable, "cursor_move_handler_id", cursor_move_handler_id) setattr(editable, "insert_at_cursor_handler_id", insert_at_cursor_handler_id) setattr(editable, "entry_widget_expose_event_handler_id", entry_widget_expose_event_handler_id) ctrl.active_entry_widget = editable def on_edited(renderer, path, new_value_str): """Calls the apply method with the new value :param Gtk.CellRendererText renderer: The cell renderer that was edited :param str path: The path string of the renderer :param str new_value_str: The new value as string """ renderer.remove_all_handler(renderer) apply_method(path, new_value_str) renderer.ctrl.active_entry_widget = None def on_editing_canceled(renderer): """Disconnects the focus-out-event handler of cancelled editable :param Gtk.CellRendererText renderer: The cell renderer who's editing was cancelled """ remove_all_handler(renderer) renderer.ctrl.active_entry_widget = None renderer.remove_all_handler = remove_all_handler renderer.ctrl = self # renderer.connect('editing-started', on_editing_started) # renderer.connect('edited', on_edited) self.__attached_renderers.append(renderer) self.connect_signal(renderer, 'editing-started', on_editing_started) self.connect_signal(renderer, 'edited', on_edited)
[ "def", "_apply_value_on_edited_and_focus_out", "(", "self", ",", "renderer", ",", "apply_method", ")", ":", "assert", "isinstance", "(", "renderer", ",", "Gtk", ".", "CellRenderer", ")", "def", "remove_all_handler", "(", "renderer", ")", ":", "\"\"\"Remove all handl...
Sets up the renderer to apply changed when loosing focus The default behaviour for the focus out event dismisses the changes in the renderer. Therefore we setup handlers for that event, applying the changes. :param Gtk.CellRendererText renderer: The cell renderer who's changes are to be applied on focus out events :param apply_method: The callback method applying the newly entered value
[ "Sets", "up", "the", "renderer", "to", "apply", "changed", "when", "loosing", "focus" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L232-L341
train
40,359
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/tree_view_controller.py
ListViewController.on_remove
def on_remove(self, widget, data=None): """Removes respective selected core elements and select the next one""" path_list = None if self.view is not None: model, path_list = self.tree_view.get_selection().get_selected_rows() old_path = self.get_path() models = [self.list_store[path][self.MODEL_STORAGE_ID] for path in path_list] if path_list else [] if models: try: self.remove_core_elements(models) except AttributeError as e: self._logger.warning("The respective core element of {1}.list_store couldn't be removed. -> {0}" "".format(e, self.__class__.__name__)) if len(self.list_store) > 0: self.tree_view.set_cursor(min(old_path[0], len(self.list_store) - 1)) return True else: self._logger.warning("Please select an element to be removed.")
python
def on_remove(self, widget, data=None): """Removes respective selected core elements and select the next one""" path_list = None if self.view is not None: model, path_list = self.tree_view.get_selection().get_selected_rows() old_path = self.get_path() models = [self.list_store[path][self.MODEL_STORAGE_ID] for path in path_list] if path_list else [] if models: try: self.remove_core_elements(models) except AttributeError as e: self._logger.warning("The respective core element of {1}.list_store couldn't be removed. -> {0}" "".format(e, self.__class__.__name__)) if len(self.list_store) > 0: self.tree_view.set_cursor(min(old_path[0], len(self.list_store) - 1)) return True else: self._logger.warning("Please select an element to be removed.")
[ "def", "on_remove", "(", "self", ",", "widget", ",", "data", "=", "None", ")", ":", "path_list", "=", "None", "if", "self", ".", "view", "is", "not", "None", ":", "model", ",", "path_list", "=", "self", ".", "tree_view", ".", "get_selection", "(", ")...
Removes respective selected core elements and select the next one
[ "Removes", "respective", "selected", "core", "elements", "and", "select", "the", "next", "one" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L465-L483
train
40,360
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/tree_view_controller.py
ListViewController.get_state_machine_selection
def get_state_machine_selection(self): """An abstract getter method for state machine selection The method maybe has to be re-implemented by inherit classes and hands generally a filtered set of selected elements. :return: selection object it self, filtered set of selected elements :rtype: rafcon.gui.selection.Selection, set """ sm_selection = self.model.get_state_machine_m().selection if self.model.get_state_machine_m() else None return sm_selection, sm_selection.get_selected_elements_of_core_class(self.CORE_ELEMENT_CLASS) if sm_selection else set()
python
def get_state_machine_selection(self): """An abstract getter method for state machine selection The method maybe has to be re-implemented by inherit classes and hands generally a filtered set of selected elements. :return: selection object it self, filtered set of selected elements :rtype: rafcon.gui.selection.Selection, set """ sm_selection = self.model.get_state_machine_m().selection if self.model.get_state_machine_m() else None return sm_selection, sm_selection.get_selected_elements_of_core_class(self.CORE_ELEMENT_CLASS) if sm_selection else set()
[ "def", "get_state_machine_selection", "(", "self", ")", ":", "sm_selection", "=", "self", ".", "model", ".", "get_state_machine_m", "(", ")", ".", "selection", "if", "self", ".", "model", ".", "get_state_machine_m", "(", ")", "else", "None", "return", "sm_sele...
An abstract getter method for state machine selection The method maybe has to be re-implemented by inherit classes and hands generally a filtered set of selected elements. :return: selection object it self, filtered set of selected elements :rtype: rafcon.gui.selection.Selection, set
[ "An", "abstract", "getter", "method", "for", "state", "machine", "selection" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L485-L495
train
40,361
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/tree_view_controller.py
ListViewController._handle_double_click
def _handle_double_click(self, event): """ Double click with left mouse button focuses the element""" if event.get_button()[1] == 1: # Left mouse button path_info = self.tree_view.get_path_at_pos(int(event.x), int(event.y)) if path_info: # Valid entry was clicked on path = path_info[0] iter = self.list_store.get_iter(path) model = self.list_store.get_value(iter, self.MODEL_STORAGE_ID) selection = self.model.get_state_machine_m().selection selection.focus = model
python
def _handle_double_click(self, event): """ Double click with left mouse button focuses the element""" if event.get_button()[1] == 1: # Left mouse button path_info = self.tree_view.get_path_at_pos(int(event.x), int(event.y)) if path_info: # Valid entry was clicked on path = path_info[0] iter = self.list_store.get_iter(path) model = self.list_store.get_value(iter, self.MODEL_STORAGE_ID) selection = self.model.get_state_machine_m().selection selection.focus = model
[ "def", "_handle_double_click", "(", "self", ",", "event", ")", ":", "if", "event", ".", "get_button", "(", ")", "[", "1", "]", "==", "1", ":", "# Left mouse button", "path_info", "=", "self", ".", "tree_view", ".", "get_path_at_pos", "(", "int", "(", "ev...
Double click with left mouse button focuses the element
[ "Double", "click", "with", "left", "mouse", "button", "focuses", "the", "element" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L577-L586
train
40,362
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/tree_view_controller.py
TreeViewController.iter_tree_with_handed_function
def iter_tree_with_handed_function(self, function, *function_args): """Iterate tree view with condition check function""" def iter_all_children(row_iter, function, function_args): if isinstance(row_iter, Gtk.TreeIter): function(row_iter, *function_args) for n in reversed(range(self.tree_store.iter_n_children(row_iter))): child_iter = self.tree_store.iter_nth_child(row_iter, n) iter_all_children(child_iter, function, function_args) else: self._logger.warning("Iter has to be TreeIter -> handed argument is: {0}".format(row_iter)) # iter on root level of tree next_iter = self.tree_store.get_iter_first() while next_iter: iter_all_children(next_iter, function, function_args) next_iter = self.tree_store.iter_next(next_iter)
python
def iter_tree_with_handed_function(self, function, *function_args): """Iterate tree view with condition check function""" def iter_all_children(row_iter, function, function_args): if isinstance(row_iter, Gtk.TreeIter): function(row_iter, *function_args) for n in reversed(range(self.tree_store.iter_n_children(row_iter))): child_iter = self.tree_store.iter_nth_child(row_iter, n) iter_all_children(child_iter, function, function_args) else: self._logger.warning("Iter has to be TreeIter -> handed argument is: {0}".format(row_iter)) # iter on root level of tree next_iter = self.tree_store.get_iter_first() while next_iter: iter_all_children(next_iter, function, function_args) next_iter = self.tree_store.iter_next(next_iter)
[ "def", "iter_tree_with_handed_function", "(", "self", ",", "function", ",", "*", "function_args", ")", ":", "def", "iter_all_children", "(", "row_iter", ",", "function", ",", "function_args", ")", ":", "if", "isinstance", "(", "row_iter", ",", "Gtk", ".", "Tre...
Iterate tree view with condition check function
[ "Iterate", "tree", "view", "with", "condition", "check", "function" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L758-L773
train
40,363
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/tree_view_controller.py
TreeViewController.update_selection_sm_prior_condition
def update_selection_sm_prior_condition(self, state_row_iter, selected_model_list, sm_selected_model_list): """State machine prior update of tree selection for one tree model row""" selected_path = self.tree_store.get_path(state_row_iter) tree_model_row = self.tree_store[selected_path] model = tree_model_row[self.MODEL_STORAGE_ID] if model not in sm_selected_model_list and model in selected_model_list: self._tree_selection.unselect_iter(state_row_iter) elif model in sm_selected_model_list and model not in selected_model_list: self.tree_view.expand_to_path(selected_path) self._tree_selection.select_iter(state_row_iter)
python
def update_selection_sm_prior_condition(self, state_row_iter, selected_model_list, sm_selected_model_list): """State machine prior update of tree selection for one tree model row""" selected_path = self.tree_store.get_path(state_row_iter) tree_model_row = self.tree_store[selected_path] model = tree_model_row[self.MODEL_STORAGE_ID] if model not in sm_selected_model_list and model in selected_model_list: self._tree_selection.unselect_iter(state_row_iter) elif model in sm_selected_model_list and model not in selected_model_list: self.tree_view.expand_to_path(selected_path) self._tree_selection.select_iter(state_row_iter)
[ "def", "update_selection_sm_prior_condition", "(", "self", ",", "state_row_iter", ",", "selected_model_list", ",", "sm_selected_model_list", ")", ":", "selected_path", "=", "self", ".", "tree_store", ".", "get_path", "(", "state_row_iter", ")", "tree_model_row", "=", ...
State machine prior update of tree selection for one tree model row
[ "State", "machine", "prior", "update", "of", "tree", "selection", "for", "one", "tree", "model", "row" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L775-L785
train
40,364
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/tree_view_controller.py
TreeViewController.update_selection_self_prior_condition
def update_selection_self_prior_condition(self, state_row_iter, sm_selected_model_set, selected_model_list): """Tree view prior update of one model in the state machine selection""" selected_path = self.tree_store.get_path(state_row_iter) tree_model_row = self.tree_store[selected_path] model = tree_model_row[self.MODEL_STORAGE_ID] if model in sm_selected_model_set and model not in selected_model_list: sm_selected_model_set.remove(model) elif model not in sm_selected_model_set and model in selected_model_list: sm_selected_model_set.add(model)
python
def update_selection_self_prior_condition(self, state_row_iter, sm_selected_model_set, selected_model_list): """Tree view prior update of one model in the state machine selection""" selected_path = self.tree_store.get_path(state_row_iter) tree_model_row = self.tree_store[selected_path] model = tree_model_row[self.MODEL_STORAGE_ID] if model in sm_selected_model_set and model not in selected_model_list: sm_selected_model_set.remove(model) elif model not in sm_selected_model_set and model in selected_model_list: sm_selected_model_set.add(model)
[ "def", "update_selection_self_prior_condition", "(", "self", ",", "state_row_iter", ",", "sm_selected_model_set", ",", "selected_model_list", ")", ":", "selected_path", "=", "self", ".", "tree_store", ".", "get_path", "(", "state_row_iter", ")", "tree_model_row", "=", ...
Tree view prior update of one model in the state machine selection
[ "Tree", "view", "prior", "update", "of", "one", "model", "in", "the", "state", "machine", "selection" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/tree_view_controller.py#L787-L796
train
40,365
DLR-RM/RAFCON
source/rafcon/gui/helpers/meta_data.py
contains_geometric_info
def contains_geometric_info(var): """ Check whether the passed variable is a tuple with two floats or integers """ return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)
python
def contains_geometric_info(var): """ Check whether the passed variable is a tuple with two floats or integers """ return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)
[ "def", "contains_geometric_info", "(", "var", ")", ":", "return", "isinstance", "(", "var", ",", "tuple", ")", "and", "len", "(", "var", ")", "==", "2", "and", "all", "(", "isinstance", "(", "val", ",", "(", "int", ",", "float", ")", ")", "for", "v...
Check whether the passed variable is a tuple with two floats or integers
[ "Check", "whether", "the", "passed", "variable", "is", "a", "tuple", "with", "two", "floats", "or", "integers" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/meta_data.py#L55-L57
train
40,366
DLR-RM/RAFCON
source/rafcon/gui/helpers/meta_data.py
generate_default_state_meta_data
def generate_default_state_meta_data(parent_state_m, canvas=None, num_child_state=None, gaphas_editor=True): """Generate default meta data for a child state according its parent state The function could work with the handed num_child_state if all child state are not drawn, till now. The method checks if the parents meta data is consistent in canvas state view and model if a canvas instance is handed. :param rafcon.gui.models.container_state.ContainerStateModel parent_state_m: Model of the state were the child should be drawn into :param rafcon.gui.mygaphas.canvas.MyCanvas canvas: canvas instance the state will be drawn into :param int num_child_state: Number of child states already drawn in canvas parent state view :return child relative pos (tuple) in parent and it size (tuple) """ parent_size = parent_state_m.get_meta_data_editor()['size'] if not contains_geometric_info(parent_size): raise ValueError("Invalid state size: {}".format(parent_size)) # use handed number of child states and otherwise take number of child states from parent state model num_child_state = len(parent_state_m.states) if num_child_state is None else num_child_state # check if respective canvas is handed if meta data of parent canvas view is consistent with model if canvas is not None: parent_state_v = canvas.get_view_for_model(parent_state_m) if not (parent_state_v.width, parent_state_v.height) == parent_size: logger.warning("Size meta data of model {0} is different to gaphas {1}" "".format((parent_state_v.width, parent_state_v.height), parent_size)) # Calculate default positions for the child states # Make the inset from the top left corner parent_state_width, parent_state_height = parent_size new_state_side_size = min(parent_state_width * 0.2, parent_state_height * 0.2) child_width = new_state_side_size child_height = new_state_side_size child_size = (child_width, child_height) child_spacing = max(child_size) * 1.2 parent_margin = cal_margin(parent_size) # print("parent size", parent_size, parent_margin) max_cols = (parent_state_width - 2*parent_margin) // child_spacing (row, col) = divmod(num_child_state, max_cols) max_rows = (parent_state_height - 2*parent_margin - 0.5*child_spacing) // (1.5*child_spacing) (overlapping, row) = divmod(row, max_rows) overlapping_step = 0.5*parent_margin max_overlaps_x = (parent_state_width - 2*parent_margin - child_width - (parent_margin + (max_cols - 1) * child_spacing + child_spacing - child_width)) // overlapping_step max_overlaps_y = (parent_state_height - 2*parent_margin - child_height - child_spacing * (1.5 * (max_rows - 1) + 1)) // overlapping_step # handle case of less space TODO check again not perfect, maybe that can be done more simple max_overlaps_x = 0 if max_overlaps_x < 0 else max_overlaps_x max_overlaps_y = 0 if max_overlaps_y < 0 else max_overlaps_y max_overlaps = min(max_overlaps_x, max_overlaps_y) + 1 overlapping = divmod(overlapping, max_overlaps)[1] child_rel_pos_x = parent_margin + col * child_spacing + child_spacing - child_width + overlapping*overlapping_step child_rel_pos_y = child_spacing * (1.5 * row + 1.) + overlapping*overlapping_step return (child_rel_pos_x, child_rel_pos_y), (new_state_side_size, new_state_side_size)
python
def generate_default_state_meta_data(parent_state_m, canvas=None, num_child_state=None, gaphas_editor=True): """Generate default meta data for a child state according its parent state The function could work with the handed num_child_state if all child state are not drawn, till now. The method checks if the parents meta data is consistent in canvas state view and model if a canvas instance is handed. :param rafcon.gui.models.container_state.ContainerStateModel parent_state_m: Model of the state were the child should be drawn into :param rafcon.gui.mygaphas.canvas.MyCanvas canvas: canvas instance the state will be drawn into :param int num_child_state: Number of child states already drawn in canvas parent state view :return child relative pos (tuple) in parent and it size (tuple) """ parent_size = parent_state_m.get_meta_data_editor()['size'] if not contains_geometric_info(parent_size): raise ValueError("Invalid state size: {}".format(parent_size)) # use handed number of child states and otherwise take number of child states from parent state model num_child_state = len(parent_state_m.states) if num_child_state is None else num_child_state # check if respective canvas is handed if meta data of parent canvas view is consistent with model if canvas is not None: parent_state_v = canvas.get_view_for_model(parent_state_m) if not (parent_state_v.width, parent_state_v.height) == parent_size: logger.warning("Size meta data of model {0} is different to gaphas {1}" "".format((parent_state_v.width, parent_state_v.height), parent_size)) # Calculate default positions for the child states # Make the inset from the top left corner parent_state_width, parent_state_height = parent_size new_state_side_size = min(parent_state_width * 0.2, parent_state_height * 0.2) child_width = new_state_side_size child_height = new_state_side_size child_size = (child_width, child_height) child_spacing = max(child_size) * 1.2 parent_margin = cal_margin(parent_size) # print("parent size", parent_size, parent_margin) max_cols = (parent_state_width - 2*parent_margin) // child_spacing (row, col) = divmod(num_child_state, max_cols) max_rows = (parent_state_height - 2*parent_margin - 0.5*child_spacing) // (1.5*child_spacing) (overlapping, row) = divmod(row, max_rows) overlapping_step = 0.5*parent_margin max_overlaps_x = (parent_state_width - 2*parent_margin - child_width - (parent_margin + (max_cols - 1) * child_spacing + child_spacing - child_width)) // overlapping_step max_overlaps_y = (parent_state_height - 2*parent_margin - child_height - child_spacing * (1.5 * (max_rows - 1) + 1)) // overlapping_step # handle case of less space TODO check again not perfect, maybe that can be done more simple max_overlaps_x = 0 if max_overlaps_x < 0 else max_overlaps_x max_overlaps_y = 0 if max_overlaps_y < 0 else max_overlaps_y max_overlaps = min(max_overlaps_x, max_overlaps_y) + 1 overlapping = divmod(overlapping, max_overlaps)[1] child_rel_pos_x = parent_margin + col * child_spacing + child_spacing - child_width + overlapping*overlapping_step child_rel_pos_y = child_spacing * (1.5 * row + 1.) + overlapping*overlapping_step return (child_rel_pos_x, child_rel_pos_y), (new_state_side_size, new_state_side_size)
[ "def", "generate_default_state_meta_data", "(", "parent_state_m", ",", "canvas", "=", "None", ",", "num_child_state", "=", "None", ",", "gaphas_editor", "=", "True", ")", ":", "parent_size", "=", "parent_state_m", ".", "get_meta_data_editor", "(", ")", "[", "'size...
Generate default meta data for a child state according its parent state The function could work with the handed num_child_state if all child state are not drawn, till now. The method checks if the parents meta data is consistent in canvas state view and model if a canvas instance is handed. :param rafcon.gui.models.container_state.ContainerStateModel parent_state_m: Model of the state were the child should be drawn into :param rafcon.gui.mygaphas.canvas.MyCanvas canvas: canvas instance the state will be drawn into :param int num_child_state: Number of child states already drawn in canvas parent state view :return child relative pos (tuple) in parent and it size (tuple)
[ "Generate", "default", "meta", "data", "for", "a", "child", "state", "according", "its", "parent", "state" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/meta_data.py#L108-L166
train
40,367
DLR-RM/RAFCON
source/rafcon/gui/helpers/meta_data.py
add_boundary_clearance
def add_boundary_clearance(left, right, top, bottom, frame, clearance=0.1): """Increase boundary size The function increase the space between top and bottom and between left and right parameters. The increase performed on the biggest size/frame so max(size boundary, size frame) :param float left: lower x-axis value :param float right: upper x-axis value :param float top: lower y-axis value :param float bottom: upper y-axis value :param dict frame: Dictionary with size and rel_pos tuples :param float clearance: Percentage 0.01 = 1% of clearance :return: """ # print("old boundary", left, right, top, bottom) width = right - left width = frame['size'][0] if width < frame['size'][0] else width left -= 0.5 * clearance * width left = 0 if left < 0 else left right += 0.5 * clearance * width height = bottom - top height = frame['size'][1] if height < frame['size'][1] else height top -= 0.5 * clearance * height top = 0 if top < 0 else top bottom += 0.5 * clearance * height # print("new boundary", left, right, top, bottom) return left, right, top, bottom
python
def add_boundary_clearance(left, right, top, bottom, frame, clearance=0.1): """Increase boundary size The function increase the space between top and bottom and between left and right parameters. The increase performed on the biggest size/frame so max(size boundary, size frame) :param float left: lower x-axis value :param float right: upper x-axis value :param float top: lower y-axis value :param float bottom: upper y-axis value :param dict frame: Dictionary with size and rel_pos tuples :param float clearance: Percentage 0.01 = 1% of clearance :return: """ # print("old boundary", left, right, top, bottom) width = right - left width = frame['size'][0] if width < frame['size'][0] else width left -= 0.5 * clearance * width left = 0 if left < 0 else left right += 0.5 * clearance * width height = bottom - top height = frame['size'][1] if height < frame['size'][1] else height top -= 0.5 * clearance * height top = 0 if top < 0 else top bottom += 0.5 * clearance * height # print("new boundary", left, right, top, bottom) return left, right, top, bottom
[ "def", "add_boundary_clearance", "(", "left", ",", "right", ",", "top", ",", "bottom", ",", "frame", ",", "clearance", "=", "0.1", ")", ":", "# print(\"old boundary\", left, right, top, bottom)", "width", "=", "right", "-", "left", "width", "=", "frame", "[", ...
Increase boundary size The function increase the space between top and bottom and between left and right parameters. The increase performed on the biggest size/frame so max(size boundary, size frame) :param float left: lower x-axis value :param float right: upper x-axis value :param float top: lower y-axis value :param float bottom: upper y-axis value :param dict frame: Dictionary with size and rel_pos tuples :param float clearance: Percentage 0.01 = 1% of clearance :return:
[ "Increase", "boundary", "size" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/meta_data.py#L226-L254
train
40,368
DLR-RM/RAFCON
source/rafcon/gui/helpers/meta_data.py
cal_frame_according_boundaries
def cal_frame_according_boundaries(left, right, top, bottom, parent_size, gaphas_editor=True, group=True): """ Generate margin and relative position and size handed boundary parameter and parent size """ # print("parent_size ->", parent_size) margin = cal_margin(parent_size) # Add margin and ensure that the upper left corner is within the state if group: # frame of grouped state rel_pos = max(left - margin, 0), max(top - margin, 0) # Add margin and ensure that the lower right corner is within the state size = (min(right - left + 2 * margin, parent_size[0] - rel_pos[0]), min(bottom - top + 2 * margin, parent_size[1] - rel_pos[1])) else: # frame inside of state # rel_pos = max(margin, 0), max(margin, 0) rel_pos = left, top size = right - left, bottom - top return margin, rel_pos, size
python
def cal_frame_according_boundaries(left, right, top, bottom, parent_size, gaphas_editor=True, group=True): """ Generate margin and relative position and size handed boundary parameter and parent size """ # print("parent_size ->", parent_size) margin = cal_margin(parent_size) # Add margin and ensure that the upper left corner is within the state if group: # frame of grouped state rel_pos = max(left - margin, 0), max(top - margin, 0) # Add margin and ensure that the lower right corner is within the state size = (min(right - left + 2 * margin, parent_size[0] - rel_pos[0]), min(bottom - top + 2 * margin, parent_size[1] - rel_pos[1])) else: # frame inside of state # rel_pos = max(margin, 0), max(margin, 0) rel_pos = left, top size = right - left, bottom - top return margin, rel_pos, size
[ "def", "cal_frame_according_boundaries", "(", "left", ",", "right", ",", "top", ",", "bottom", ",", "parent_size", ",", "gaphas_editor", "=", "True", ",", "group", "=", "True", ")", ":", "# print(\"parent_size ->\", parent_size)", "margin", "=", "cal_margin", "(",...
Generate margin and relative position and size handed boundary parameter and parent size
[ "Generate", "margin", "and", "relative", "position", "and", "size", "handed", "boundary", "parameter", "and", "parent", "size" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/meta_data.py#L336-L353
train
40,369
DLR-RM/RAFCON
source/rafcon/gui/helpers/meta_data.py
offset_rel_pos_of_all_models_in_dict
def offset_rel_pos_of_all_models_in_dict(models_dict, pos_offset, gaphas_editor=True): """ Add position offset to all handed models in dict""" # print("\n", "#"*30, "offset models", pos_offset, "#"*30) # Update relative position of states within the container in order to maintain their absolute position for child_state_m in models_dict['states'].values(): old_rel_pos = child_state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['rel_pos'] # print("old_rel_pos", old_rel_pos, child_state_m) child_state_m.set_meta_data_editor('rel_pos', add_pos(old_rel_pos, pos_offset), from_gaphas=gaphas_editor) # print("new_rel_pos", child_state_m.get_meta_data_editor(for_gaphas=gaphas_editor), child_state_m) # Do the same for scoped variable if not gaphas_editor: for scoped_variable_m in models_dict['scoped_variables'].values(): old_rel_pos = scoped_variable_m.get_meta_data_editor(for_gaphas=gaphas_editor)['inner_rel_pos'] scoped_variable_m.set_meta_data_editor('inner_rel_pos', add_pos(old_rel_pos, pos_offset), gaphas_editor) # Do the same for all connections (transitions and data flows) connection_models = list(models_dict['transitions'].values()) + list(models_dict['data_flows'].values()) for connection_m in connection_models: old_waypoints = connection_m.get_meta_data_editor(for_gaphas=gaphas_editor)['waypoints'] new_waypoints = [] for waypoint in old_waypoints: from rafcon.gui.models.data_flow import DataFlowModel if isinstance(connection_m, DataFlowModel) and gaphas_editor: new_waypoints.append(add_pos(waypoint, (pos_offset[0], -pos_offset[1]))) else: new_waypoints.append(add_pos(waypoint, pos_offset)) connection_m.set_meta_data_editor('waypoints', new_waypoints, from_gaphas=gaphas_editor)
python
def offset_rel_pos_of_all_models_in_dict(models_dict, pos_offset, gaphas_editor=True): """ Add position offset to all handed models in dict""" # print("\n", "#"*30, "offset models", pos_offset, "#"*30) # Update relative position of states within the container in order to maintain their absolute position for child_state_m in models_dict['states'].values(): old_rel_pos = child_state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['rel_pos'] # print("old_rel_pos", old_rel_pos, child_state_m) child_state_m.set_meta_data_editor('rel_pos', add_pos(old_rel_pos, pos_offset), from_gaphas=gaphas_editor) # print("new_rel_pos", child_state_m.get_meta_data_editor(for_gaphas=gaphas_editor), child_state_m) # Do the same for scoped variable if not gaphas_editor: for scoped_variable_m in models_dict['scoped_variables'].values(): old_rel_pos = scoped_variable_m.get_meta_data_editor(for_gaphas=gaphas_editor)['inner_rel_pos'] scoped_variable_m.set_meta_data_editor('inner_rel_pos', add_pos(old_rel_pos, pos_offset), gaphas_editor) # Do the same for all connections (transitions and data flows) connection_models = list(models_dict['transitions'].values()) + list(models_dict['data_flows'].values()) for connection_m in connection_models: old_waypoints = connection_m.get_meta_data_editor(for_gaphas=gaphas_editor)['waypoints'] new_waypoints = [] for waypoint in old_waypoints: from rafcon.gui.models.data_flow import DataFlowModel if isinstance(connection_m, DataFlowModel) and gaphas_editor: new_waypoints.append(add_pos(waypoint, (pos_offset[0], -pos_offset[1]))) else: new_waypoints.append(add_pos(waypoint, pos_offset)) connection_m.set_meta_data_editor('waypoints', new_waypoints, from_gaphas=gaphas_editor)
[ "def", "offset_rel_pos_of_all_models_in_dict", "(", "models_dict", ",", "pos_offset", ",", "gaphas_editor", "=", "True", ")", ":", "# print(\"\\n\", \"#\"*30, \"offset models\", pos_offset, \"#\"*30)", "# Update relative position of states within the container in order to maintain their ab...
Add position offset to all handed models in dict
[ "Add", "position", "offset", "to", "all", "handed", "models", "in", "dict" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/meta_data.py#L356-L383
train
40,370
DLR-RM/RAFCON
source/rafcon/gui/helpers/meta_data.py
scale_library_ports_meta_data
def scale_library_ports_meta_data(state_m, gaphas_editor=True): """Scale the ports of library model accordingly relative to state_copy meta size. The function assumes that the meta data of ports of the state_copy of the library was copied to respective elements in the library and that those was not adjusted before. """ if state_m.meta_data_was_scaled: return state_m.income.set_meta_data_editor('rel_pos', state_m.state_copy.income.get_meta_data_editor()['rel_pos']) # print("scale_library_ports_meta_data ", state_m.get_meta_data_editor()['size'], \) # state_m.state_copy.get_meta_data_editor()['size'] factor = divide_two_vectors(state_m.get_meta_data_editor()['size'], state_m.state_copy.get_meta_data_editor()['size']) # print("scale_library_ports_meta_data -> resize_state_port_meta", factor) if contains_geometric_info(factor): resize_state_port_meta(state_m, factor, True) state_m.meta_data_was_scaled = True else: logger.info("Skip resize of library ports meta data {0}".format(state_m))
python
def scale_library_ports_meta_data(state_m, gaphas_editor=True): """Scale the ports of library model accordingly relative to state_copy meta size. The function assumes that the meta data of ports of the state_copy of the library was copied to respective elements in the library and that those was not adjusted before. """ if state_m.meta_data_was_scaled: return state_m.income.set_meta_data_editor('rel_pos', state_m.state_copy.income.get_meta_data_editor()['rel_pos']) # print("scale_library_ports_meta_data ", state_m.get_meta_data_editor()['size'], \) # state_m.state_copy.get_meta_data_editor()['size'] factor = divide_two_vectors(state_m.get_meta_data_editor()['size'], state_m.state_copy.get_meta_data_editor()['size']) # print("scale_library_ports_meta_data -> resize_state_port_meta", factor) if contains_geometric_info(factor): resize_state_port_meta(state_m, factor, True) state_m.meta_data_was_scaled = True else: logger.info("Skip resize of library ports meta data {0}".format(state_m))
[ "def", "scale_library_ports_meta_data", "(", "state_m", ",", "gaphas_editor", "=", "True", ")", ":", "if", "state_m", ".", "meta_data_was_scaled", ":", "return", "state_m", ".", "income", ".", "set_meta_data_editor", "(", "'rel_pos'", ",", "state_m", ".", "state_c...
Scale the ports of library model accordingly relative to state_copy meta size. The function assumes that the meta data of ports of the state_copy of the library was copied to respective elements in the library and that those was not adjusted before.
[ "Scale", "the", "ports", "of", "library", "model", "accordingly", "relative", "to", "state_copy", "meta", "size", ".", "The", "function", "assumes", "that", "the", "meta", "data", "of", "ports", "of", "the", "state_copy", "of", "the", "library", "was", "copi...
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/meta_data.py#L387-L406
train
40,371
DLR-RM/RAFCON
source/rafcon/gui/helpers/meta_data.py
resize_state_port_meta
def resize_state_port_meta(state_m, factor, gaphas_editor=True): """ Resize data and logical ports relative positions """ # print("scale ports", factor, state_m, gaphas_editor) if not gaphas_editor and isinstance(state_m, ContainerStateModel): port_models = state_m.input_data_ports[:] + state_m.output_data_ports[:] + state_m.scoped_variables[:] else: port_models = state_m.input_data_ports[:] + state_m.output_data_ports[:] + state_m.outcomes[:] port_models += state_m.scoped_variables[:] if isinstance(state_m, ContainerStateModel) else [] _resize_port_models_list(port_models, 'rel_pos' if gaphas_editor else 'inner_rel_pos', factor, gaphas_editor) resize_income_of_state_m(state_m, factor, gaphas_editor)
python
def resize_state_port_meta(state_m, factor, gaphas_editor=True): """ Resize data and logical ports relative positions """ # print("scale ports", factor, state_m, gaphas_editor) if not gaphas_editor and isinstance(state_m, ContainerStateModel): port_models = state_m.input_data_ports[:] + state_m.output_data_ports[:] + state_m.scoped_variables[:] else: port_models = state_m.input_data_ports[:] + state_m.output_data_ports[:] + state_m.outcomes[:] port_models += state_m.scoped_variables[:] if isinstance(state_m, ContainerStateModel) else [] _resize_port_models_list(port_models, 'rel_pos' if gaphas_editor else 'inner_rel_pos', factor, gaphas_editor) resize_income_of_state_m(state_m, factor, gaphas_editor)
[ "def", "resize_state_port_meta", "(", "state_m", ",", "factor", ",", "gaphas_editor", "=", "True", ")", ":", "# print(\"scale ports\", factor, state_m, gaphas_editor)", "if", "not", "gaphas_editor", "and", "isinstance", "(", "state_m", ",", "ContainerStateModel", ")", "...
Resize data and logical ports relative positions
[ "Resize", "data", "and", "logical", "ports", "relative", "positions" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/meta_data.py#L490-L500
train
40,372
DLR-RM/RAFCON
source/rafcon/gui/helpers/meta_data.py
resize_state_meta
def resize_state_meta(state_m, factor, gaphas_editor=True): """ Resize state meta data recursive what includes also LibraryStateModels meta data and its internal state_copy """ # print("START RESIZE OF STATE", state_m.get_meta_data_editor(for_gaphas=gaphas_editor), state_m) old_rel_pos = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['rel_pos'] # print("old_rel_pos state", old_rel_pos, state_m.core_element) state_m.set_meta_data_editor('rel_pos', mult_two_vectors(factor, old_rel_pos), from_gaphas=gaphas_editor) # print("new_rel_pos state", state_m.get_meta_data_editor(for_gaphas=gaphas_editor), state_m.core_element) # print("resize factor", factor, state_m, state_m.meta) old_size = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['size'] # print("old_size", old_size, type(old_size)) state_m.set_meta_data_editor('size', mult_two_vectors(factor, old_size), from_gaphas=gaphas_editor) # print("new_size", state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['size']) if gaphas_editor: old_rel_pos = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['name']['rel_pos'] state_m.set_meta_data_editor('name.rel_pos', mult_two_vectors(factor, old_rel_pos), from_gaphas=gaphas_editor) old_size = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['name']['size'] state_m.set_meta_data_editor('name.size', mult_two_vectors(factor, old_size), from_gaphas=gaphas_editor) if isinstance(state_m, LibraryStateModel): # print("LIBRARY", state_m) if gaphas_editor and state_m.state_copy_initialized: if state_m.meta_data_was_scaled: resize_state_port_meta(state_m, factor, gaphas_editor) else: scale_library_ports_meta_data(state_m, gaphas_editor) if state_m.state_copy_initialized: resize_state_meta(state_m.state_copy, factor, gaphas_editor) # print("END LIBRARY RESIZE") else: # print("resize_state_meta -> resize_state_port_meta") resize_state_port_meta(state_m, factor, gaphas_editor) if isinstance(state_m, ContainerStateModel): _resize_connection_models_list(state_m.transitions[:] + state_m.data_flows[:], factor, gaphas_editor) for child_state_m in state_m.states.values(): resize_state_meta(child_state_m, factor, gaphas_editor)
python
def resize_state_meta(state_m, factor, gaphas_editor=True): """ Resize state meta data recursive what includes also LibraryStateModels meta data and its internal state_copy """ # print("START RESIZE OF STATE", state_m.get_meta_data_editor(for_gaphas=gaphas_editor), state_m) old_rel_pos = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['rel_pos'] # print("old_rel_pos state", old_rel_pos, state_m.core_element) state_m.set_meta_data_editor('rel_pos', mult_two_vectors(factor, old_rel_pos), from_gaphas=gaphas_editor) # print("new_rel_pos state", state_m.get_meta_data_editor(for_gaphas=gaphas_editor), state_m.core_element) # print("resize factor", factor, state_m, state_m.meta) old_size = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['size'] # print("old_size", old_size, type(old_size)) state_m.set_meta_data_editor('size', mult_two_vectors(factor, old_size), from_gaphas=gaphas_editor) # print("new_size", state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['size']) if gaphas_editor: old_rel_pos = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['name']['rel_pos'] state_m.set_meta_data_editor('name.rel_pos', mult_two_vectors(factor, old_rel_pos), from_gaphas=gaphas_editor) old_size = state_m.get_meta_data_editor(for_gaphas=gaphas_editor)['name']['size'] state_m.set_meta_data_editor('name.size', mult_two_vectors(factor, old_size), from_gaphas=gaphas_editor) if isinstance(state_m, LibraryStateModel): # print("LIBRARY", state_m) if gaphas_editor and state_m.state_copy_initialized: if state_m.meta_data_was_scaled: resize_state_port_meta(state_m, factor, gaphas_editor) else: scale_library_ports_meta_data(state_m, gaphas_editor) if state_m.state_copy_initialized: resize_state_meta(state_m.state_copy, factor, gaphas_editor) # print("END LIBRARY RESIZE") else: # print("resize_state_meta -> resize_state_port_meta") resize_state_port_meta(state_m, factor, gaphas_editor) if isinstance(state_m, ContainerStateModel): _resize_connection_models_list(state_m.transitions[:] + state_m.data_flows[:], factor, gaphas_editor) for child_state_m in state_m.states.values(): resize_state_meta(child_state_m, factor, gaphas_editor)
[ "def", "resize_state_meta", "(", "state_m", ",", "factor", ",", "gaphas_editor", "=", "True", ")", ":", "# print(\"START RESIZE OF STATE\", state_m.get_meta_data_editor(for_gaphas=gaphas_editor), state_m)", "old_rel_pos", "=", "state_m", ".", "get_meta_data_editor", "(", "for_g...
Resize state meta data recursive what includes also LibraryStateModels meta data and its internal state_copy
[ "Resize", "state", "meta", "data", "recursive", "what", "includes", "also", "LibraryStateModels", "meta", "data", "and", "its", "internal", "state_copy" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/meta_data.py#L503-L540
train
40,373
DLR-RM/RAFCON
source/rafcon/gui/helpers/meta_data.py
offset_rel_pos_of_models_meta_data_according_parent_state
def offset_rel_pos_of_models_meta_data_according_parent_state(models_dict): """ Offset meta data of state elements according the area used indicated by the state meta data. The offset_rel_pos_of_models_meta_data_according_parent_state offset the position of all handed old elements in the dictionary. :param models_dict: dict that hold lists of meta data with state attribute consistent keys :return: """ old_parent_rel_pos = models_dict['state'].get_meta_data_editor()['rel_pos'] offset_rel_pos_of_all_models_in_dict(models_dict, pos_offset=old_parent_rel_pos) return True
python
def offset_rel_pos_of_models_meta_data_according_parent_state(models_dict): """ Offset meta data of state elements according the area used indicated by the state meta data. The offset_rel_pos_of_models_meta_data_according_parent_state offset the position of all handed old elements in the dictionary. :param models_dict: dict that hold lists of meta data with state attribute consistent keys :return: """ old_parent_rel_pos = models_dict['state'].get_meta_data_editor()['rel_pos'] offset_rel_pos_of_all_models_in_dict(models_dict, pos_offset=old_parent_rel_pos) return True
[ "def", "offset_rel_pos_of_models_meta_data_according_parent_state", "(", "models_dict", ")", ":", "old_parent_rel_pos", "=", "models_dict", "[", "'state'", "]", ".", "get_meta_data_editor", "(", ")", "[", "'rel_pos'", "]", "offset_rel_pos_of_all_models_in_dict", "(", "model...
Offset meta data of state elements according the area used indicated by the state meta data. The offset_rel_pos_of_models_meta_data_according_parent_state offset the position of all handed old elements in the dictionary. :param models_dict: dict that hold lists of meta data with state attribute consistent keys :return:
[ "Offset", "meta", "data", "of", "state", "elements", "according", "the", "area", "used", "indicated", "by", "the", "state", "meta", "data", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/meta_data.py#L563-L575
train
40,374
DLR-RM/RAFCON
source/rafcon/gui/helpers/meta_data.py
get_closest_sibling_state
def get_closest_sibling_state(state_m, from_logical_port=None): """ Calculate the closest sibling also from optional logical port of handed state model :param StateModel state_m: Reference State model the closest sibling state should be find for :param str from_logical_port: The logical port of handed state model to be used as reference. :rtype: tuple :return: distance, StateModel of closest state """ if not state_m.parent: logger.warning("A state can not have a closest sibling state if it has not parent as {0}".format(state_m)) return margin = cal_margin(state_m.parent.get_meta_data_editor()['size']) pos = state_m.get_meta_data_editor()['rel_pos'] size = state_m.get_meta_data_editor()['size'] # otherwise measure from reference state itself if from_logical_port in ["outcome", "income"]: size = (margin, margin) if from_logical_port == "outcome": outcomes_m = [outcome_m for outcome_m in state_m.outcomes if outcome_m.outcome.outcome_id >= 0] free_outcomes_m = [oc_m for oc_m in outcomes_m if not state_m.state.parent.get_transition_for_outcome(state_m.state, oc_m.outcome)] if free_outcomes_m: outcome_m = free_outcomes_m[0] else: outcome_m = outcomes_m[0] pos = add_pos(pos, outcome_m.get_meta_data_editor()['rel_pos']) elif from_logical_port == "income": pos = add_pos(pos, state_m.income.get_meta_data_editor()['rel_pos']) min_distance = None for sibling_state_m in state_m.parent.states.values(): if sibling_state_m is state_m: continue sibling_pos = sibling_state_m.get_meta_data_editor()['rel_pos'] sibling_size = sibling_state_m.get_meta_data_editor()['size'] distance = geometry.cal_dist_between_2_coord_frame_aligned_boxes(pos, size, sibling_pos, sibling_size) if not min_distance or min_distance[0] > distance: min_distance = (distance, sibling_state_m) return min_distance
python
def get_closest_sibling_state(state_m, from_logical_port=None): """ Calculate the closest sibling also from optional logical port of handed state model :param StateModel state_m: Reference State model the closest sibling state should be find for :param str from_logical_port: The logical port of handed state model to be used as reference. :rtype: tuple :return: distance, StateModel of closest state """ if not state_m.parent: logger.warning("A state can not have a closest sibling state if it has not parent as {0}".format(state_m)) return margin = cal_margin(state_m.parent.get_meta_data_editor()['size']) pos = state_m.get_meta_data_editor()['rel_pos'] size = state_m.get_meta_data_editor()['size'] # otherwise measure from reference state itself if from_logical_port in ["outcome", "income"]: size = (margin, margin) if from_logical_port == "outcome": outcomes_m = [outcome_m for outcome_m in state_m.outcomes if outcome_m.outcome.outcome_id >= 0] free_outcomes_m = [oc_m for oc_m in outcomes_m if not state_m.state.parent.get_transition_for_outcome(state_m.state, oc_m.outcome)] if free_outcomes_m: outcome_m = free_outcomes_m[0] else: outcome_m = outcomes_m[0] pos = add_pos(pos, outcome_m.get_meta_data_editor()['rel_pos']) elif from_logical_port == "income": pos = add_pos(pos, state_m.income.get_meta_data_editor()['rel_pos']) min_distance = None for sibling_state_m in state_m.parent.states.values(): if sibling_state_m is state_m: continue sibling_pos = sibling_state_m.get_meta_data_editor()['rel_pos'] sibling_size = sibling_state_m.get_meta_data_editor()['size'] distance = geometry.cal_dist_between_2_coord_frame_aligned_boxes(pos, size, sibling_pos, sibling_size) if not min_distance or min_distance[0] > distance: min_distance = (distance, sibling_state_m) return min_distance
[ "def", "get_closest_sibling_state", "(", "state_m", ",", "from_logical_port", "=", "None", ")", ":", "if", "not", "state_m", ".", "parent", ":", "logger", ".", "warning", "(", "\"A state can not have a closest sibling state if it has not parent as {0}\"", ".", "format", ...
Calculate the closest sibling also from optional logical port of handed state model :param StateModel state_m: Reference State model the closest sibling state should be find for :param str from_logical_port: The logical port of handed state model to be used as reference. :rtype: tuple :return: distance, StateModel of closest state
[ "Calculate", "the", "closest", "sibling", "also", "from", "optional", "logical", "port", "of", "handed", "state", "model" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/meta_data.py#L792-L834
train
40,375
DLR-RM/RAFCON
source/rafcon/gui/clipboard.py
Clipboard.get_action_arguments
def get_action_arguments(self, target_state_m): """ Collect argument attributes for action signal Use non empty list dict to create arguments for action signal msg and logger messages. The action parent model can be different then the target state model because logical and data port changes also may influence the linkage, see action-module (undo/redo). :param rafcon.gui.models.abstract_state.AbstractStateModel target_state_m: State model of target of action :return: dict with lists of elements part of the action, action parent model """ non_empty_lists_dict = {key: elems for key, elems in self.model_copies.items() if elems} port_attrs = ['input_data_ports', 'output_data_ports', 'scoped_variables', 'outcomes'] port_is_pasted = any([key in non_empty_lists_dict for key in port_attrs]) return non_empty_lists_dict, target_state_m.parent if target_state_m.parent and port_is_pasted else target_state_m
python
def get_action_arguments(self, target_state_m): """ Collect argument attributes for action signal Use non empty list dict to create arguments for action signal msg and logger messages. The action parent model can be different then the target state model because logical and data port changes also may influence the linkage, see action-module (undo/redo). :param rafcon.gui.models.abstract_state.AbstractStateModel target_state_m: State model of target of action :return: dict with lists of elements part of the action, action parent model """ non_empty_lists_dict = {key: elems for key, elems in self.model_copies.items() if elems} port_attrs = ['input_data_ports', 'output_data_ports', 'scoped_variables', 'outcomes'] port_is_pasted = any([key in non_empty_lists_dict for key in port_attrs]) return non_empty_lists_dict, target_state_m.parent if target_state_m.parent and port_is_pasted else target_state_m
[ "def", "get_action_arguments", "(", "self", ",", "target_state_m", ")", ":", "non_empty_lists_dict", "=", "{", "key", ":", "elems", "for", "key", ",", "elems", "in", "self", ".", "model_copies", ".", "items", "(", ")", "if", "elems", "}", "port_attrs", "="...
Collect argument attributes for action signal Use non empty list dict to create arguments for action signal msg and logger messages. The action parent model can be different then the target state model because logical and data port changes also may influence the linkage, see action-module (undo/redo). :param rafcon.gui.models.abstract_state.AbstractStateModel target_state_m: State model of target of action :return: dict with lists of elements part of the action, action parent model
[ "Collect", "argument", "attributes", "for", "action", "signal" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/clipboard.py#L56-L69
train
40,376
DLR-RM/RAFCON
source/rafcon/gui/clipboard.py
Clipboard.cut
def cut(self, selection, smart_selection_adaption=False): """Cuts all selected items and copy them to the clipboard using smart selection adaptation by default :param selection: the current selection :param bool smart_selection_adaption: flag to enable smart selection adaptation mode :return: """ assert isinstance(selection, Selection) import rafcon.gui.helpers.state_machine as gui_helper_state_machine if gui_helper_state_machine.is_selection_inside_of_library_state(selected_elements=selection.get_all()): logger.warning("Cut is not performed because elements inside of a library state are selected.") return selection_dict_of_copied_models, parent_m = self.__create_core_and_model_object_copies( selection, smart_selection_adaption) non_empty_lists_dict, action_parent_m = self.get_action_arguments(parent_m if parent_m else None) action_parent_m.action_signal.emit(ActionSignalMsg(action='cut', origin='clipboard', action_parent_m=action_parent_m, affected_models=[], after=False, kwargs={'remove': non_empty_lists_dict})) for models in selection_dict_of_copied_models.values(): gui_helper_state_machine.delete_core_elements_of_models(models, destroy=True, recursive=True, force=False) affected_models = [model for models in non_empty_lists_dict.values() for model in models] action_parent_m.action_signal.emit(ActionSignalMsg(action='cut', origin='clipboard', action_parent_m=action_parent_m, affected_models=affected_models, after=True))
python
def cut(self, selection, smart_selection_adaption=False): """Cuts all selected items and copy them to the clipboard using smart selection adaptation by default :param selection: the current selection :param bool smart_selection_adaption: flag to enable smart selection adaptation mode :return: """ assert isinstance(selection, Selection) import rafcon.gui.helpers.state_machine as gui_helper_state_machine if gui_helper_state_machine.is_selection_inside_of_library_state(selected_elements=selection.get_all()): logger.warning("Cut is not performed because elements inside of a library state are selected.") return selection_dict_of_copied_models, parent_m = self.__create_core_and_model_object_copies( selection, smart_selection_adaption) non_empty_lists_dict, action_parent_m = self.get_action_arguments(parent_m if parent_m else None) action_parent_m.action_signal.emit(ActionSignalMsg(action='cut', origin='clipboard', action_parent_m=action_parent_m, affected_models=[], after=False, kwargs={'remove': non_empty_lists_dict})) for models in selection_dict_of_copied_models.values(): gui_helper_state_machine.delete_core_elements_of_models(models, destroy=True, recursive=True, force=False) affected_models = [model for models in non_empty_lists_dict.values() for model in models] action_parent_m.action_signal.emit(ActionSignalMsg(action='cut', origin='clipboard', action_parent_m=action_parent_m, affected_models=affected_models, after=True))
[ "def", "cut", "(", "self", ",", "selection", ",", "smart_selection_adaption", "=", "False", ")", ":", "assert", "isinstance", "(", "selection", ",", "Selection", ")", "import", "rafcon", ".", "gui", ".", "helpers", ".", "state_machine", "as", "gui_helper_state...
Cuts all selected items and copy them to the clipboard using smart selection adaptation by default :param selection: the current selection :param bool smart_selection_adaption: flag to enable smart selection adaptation mode :return:
[ "Cuts", "all", "selected", "items", "and", "copy", "them", "to", "the", "clipboard", "using", "smart", "selection", "adaptation", "by", "default" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/clipboard.py#L88-L118
train
40,377
DLR-RM/RAFCON
source/rafcon/gui/clipboard.py
Clipboard.reset_clipboard
def reset_clipboard(self): """ Resets the clipboard, so that old elements do not pollute the new selection that is copied into the clipboard. :return: """ # reset selections for state_element_attr in ContainerState.state_element_attrs: self.model_copies[state_element_attr] = [] # reset parent state_id the copied elements are taken from self.copy_parent_state_id = None self.reset_clipboard_mapping_dicts()
python
def reset_clipboard(self): """ Resets the clipboard, so that old elements do not pollute the new selection that is copied into the clipboard. :return: """ # reset selections for state_element_attr in ContainerState.state_element_attrs: self.model_copies[state_element_attr] = [] # reset parent state_id the copied elements are taken from self.copy_parent_state_id = None self.reset_clipboard_mapping_dicts()
[ "def", "reset_clipboard", "(", "self", ")", ":", "# reset selections", "for", "state_element_attr", "in", "ContainerState", ".", "state_element_attrs", ":", "self", ".", "model_copies", "[", "state_element_attr", "]", "=", "[", "]", "# reset parent state_id the copied e...
Resets the clipboard, so that old elements do not pollute the new selection that is copied into the clipboard. :return:
[ "Resets", "the", "clipboard", "so", "that", "old", "elements", "do", "not", "pollute", "the", "new", "selection", "that", "is", "copied", "into", "the", "clipboard", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/clipboard.py#L321-L334
train
40,378
DLR-RM/RAFCON
source/rafcon/gui/clipboard.py
Clipboard.do_selection_reduction_to_one_parent
def do_selection_reduction_to_one_parent(selection): """ Find and reduce selection to one parent state. :param selection: :return: state model which is parent of selection or None if root state """ all_models_selected = selection.get_all() # check if all elements selected are on one hierarchy level -> TODO or in future are parts of sibling?! # if not take the state with the most siblings as the copy root parent_m_count_dict = {} for model in all_models_selected: parent_m_count_dict[model.parent] = parent_m_count_dict[model.parent] + 1 if model.parent in parent_m_count_dict else 1 parent_m = None current_count_parent = 0 for possible_parent_m, count in parent_m_count_dict.items(): parent_m = possible_parent_m if current_count_parent < count else parent_m # if root no parent exist and only on model can be selected if len(selection.states) == 1 and selection.get_selected_state().state.is_root_state: parent_m = None # kick all selection except root_state if len(all_models_selected) > 1: selection.set(selection.get_selected_state()) if parent_m is not None: # check and reduce selection for model in all_models_selected: if model.parent is not parent_m: selection.remove(model) return parent_m
python
def do_selection_reduction_to_one_parent(selection): """ Find and reduce selection to one parent state. :param selection: :return: state model which is parent of selection or None if root state """ all_models_selected = selection.get_all() # check if all elements selected are on one hierarchy level -> TODO or in future are parts of sibling?! # if not take the state with the most siblings as the copy root parent_m_count_dict = {} for model in all_models_selected: parent_m_count_dict[model.parent] = parent_m_count_dict[model.parent] + 1 if model.parent in parent_m_count_dict else 1 parent_m = None current_count_parent = 0 for possible_parent_m, count in parent_m_count_dict.items(): parent_m = possible_parent_m if current_count_parent < count else parent_m # if root no parent exist and only on model can be selected if len(selection.states) == 1 and selection.get_selected_state().state.is_root_state: parent_m = None # kick all selection except root_state if len(all_models_selected) > 1: selection.set(selection.get_selected_state()) if parent_m is not None: # check and reduce selection for model in all_models_selected: if model.parent is not parent_m: selection.remove(model) return parent_m
[ "def", "do_selection_reduction_to_one_parent", "(", "selection", ")", ":", "all_models_selected", "=", "selection", ".", "get_all", "(", ")", "# check if all elements selected are on one hierarchy level -> TODO or in future are parts of sibling?!", "# if not take the state with the most ...
Find and reduce selection to one parent state. :param selection: :return: state model which is parent of selection or None if root state
[ "Find", "and", "reduce", "selection", "to", "one", "parent", "state", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/clipboard.py#L343-L372
train
40,379
DLR-RM/RAFCON
source/rafcon/gui/clipboard.py
Clipboard.__create_core_and_model_object_copies
def __create_core_and_model_object_copies(self, selection, smart_selection_adaption): """Copy all elements of a selection. The method copies all objects and modifies the selection before copying the elements if the smart flag is true. The smart selection adaption is by default enabled. In any case the selection is reduced to have one parent state that is used as the root of copy, except a root state it self is selected. :param Selection selection: an arbitrary selection, whose elements should be copied .param bool smart_selection_adaption: flag to enable smart selection adaptation mode :return: dictionary of selected models copied, parent model of copy """ all_models_selected = selection.get_all() if not all_models_selected: logger.warning("Nothing to copy because state machine selection is empty.") return parent_m = self.do_selection_reduction_to_one_parent(selection) self.copy_parent_state_id = parent_m.state.state_id if parent_m else None if smart_selection_adaption: self.do_smart_selection_adaption(selection, parent_m) # store all lists of selection selected_models_dict = {} for state_element_attr in ContainerState.state_element_attrs: selected_models_dict[state_element_attr] = list(getattr(selection, state_element_attr)) # delete old models self.destroy_all_models_in_dict(self.model_copies) # copy all selected elements self.model_copies = deepcopy(selected_models_dict) new_content_of_clipboard = ', '.join(["{0} {1}".format(len(elems), key if len(elems) > 1 else key[:-1]) for key, elems in self.model_copies.items() if elems]) logger.info("The new content is {0}".format(new_content_of_clipboard.replace('_', ' '))) return selected_models_dict, parent_m
python
def __create_core_and_model_object_copies(self, selection, smart_selection_adaption): """Copy all elements of a selection. The method copies all objects and modifies the selection before copying the elements if the smart flag is true. The smart selection adaption is by default enabled. In any case the selection is reduced to have one parent state that is used as the root of copy, except a root state it self is selected. :param Selection selection: an arbitrary selection, whose elements should be copied .param bool smart_selection_adaption: flag to enable smart selection adaptation mode :return: dictionary of selected models copied, parent model of copy """ all_models_selected = selection.get_all() if not all_models_selected: logger.warning("Nothing to copy because state machine selection is empty.") return parent_m = self.do_selection_reduction_to_one_parent(selection) self.copy_parent_state_id = parent_m.state.state_id if parent_m else None if smart_selection_adaption: self.do_smart_selection_adaption(selection, parent_m) # store all lists of selection selected_models_dict = {} for state_element_attr in ContainerState.state_element_attrs: selected_models_dict[state_element_attr] = list(getattr(selection, state_element_attr)) # delete old models self.destroy_all_models_in_dict(self.model_copies) # copy all selected elements self.model_copies = deepcopy(selected_models_dict) new_content_of_clipboard = ', '.join(["{0} {1}".format(len(elems), key if len(elems) > 1 else key[:-1]) for key, elems in self.model_copies.items() if elems]) logger.info("The new content is {0}".format(new_content_of_clipboard.replace('_', ' '))) return selected_models_dict, parent_m
[ "def", "__create_core_and_model_object_copies", "(", "self", ",", "selection", ",", "smart_selection_adaption", ")", ":", "all_models_selected", "=", "selection", ".", "get_all", "(", ")", "if", "not", "all_models_selected", ":", "logger", ".", "warning", "(", "\"No...
Copy all elements of a selection. The method copies all objects and modifies the selection before copying the elements if the smart flag is true. The smart selection adaption is by default enabled. In any case the selection is reduced to have one parent state that is used as the root of copy, except a root state it self is selected. :param Selection selection: an arbitrary selection, whose elements should be copied .param bool smart_selection_adaption: flag to enable smart selection adaptation mode :return: dictionary of selected models copied, parent model of copy
[ "Copy", "all", "elements", "of", "a", "selection", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/clipboard.py#L452-L489
train
40,380
DLR-RM/RAFCON
source/rafcon/gui/clipboard.py
Clipboard.destroy_all_models_in_dict
def destroy_all_models_in_dict(target_dict): """ Method runs the prepare destruction method of models which are assumed in list or tuple as values within a dict """ if target_dict: for model_list in target_dict.values(): if isinstance(model_list, (list, tuple)): for model in model_list: model.prepare_destruction() if model._parent: model._parent = None else: raise Exception("wrong data in clipboard")
python
def destroy_all_models_in_dict(target_dict): """ Method runs the prepare destruction method of models which are assumed in list or tuple as values within a dict """ if target_dict: for model_list in target_dict.values(): if isinstance(model_list, (list, tuple)): for model in model_list: model.prepare_destruction() if model._parent: model._parent = None else: raise Exception("wrong data in clipboard")
[ "def", "destroy_all_models_in_dict", "(", "target_dict", ")", ":", "if", "target_dict", ":", "for", "model_list", "in", "target_dict", ".", "values", "(", ")", ":", "if", "isinstance", "(", "model_list", ",", "(", "list", ",", "tuple", ")", ")", ":", "for"...
Method runs the prepare destruction method of models which are assumed in list or tuple as values within a dict
[ "Method", "runs", "the", "prepare", "destruction", "method", "of", "models", "which", "are", "assumed", "in", "list", "or", "tuple", "as", "values", "within", "a", "dict" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/clipboard.py#L492-L504
train
40,381
DLR-RM/RAFCON
source/rafcon/gui/clipboard.py
Clipboard.destroy
def destroy(self): """ Destroys the clipboard by relieving all model references. """ self.destroy_all_models_in_dict(self.model_copies) self.model_copies = None self.copy_parent_state_id = None self.outcome_id_mapping_dict = None self.port_id_mapping_dict = None self.state_id_mapping_dict = None
python
def destroy(self): """ Destroys the clipboard by relieving all model references. """ self.destroy_all_models_in_dict(self.model_copies) self.model_copies = None self.copy_parent_state_id = None self.outcome_id_mapping_dict = None self.port_id_mapping_dict = None self.state_id_mapping_dict = None
[ "def", "destroy", "(", "self", ")", ":", "self", ".", "destroy_all_models_in_dict", "(", "self", ".", "model_copies", ")", "self", ".", "model_copies", "=", "None", "self", ".", "copy_parent_state_id", "=", "None", "self", ".", "outcome_id_mapping_dict", "=", ...
Destroys the clipboard by relieving all model references.
[ "Destroys", "the", "clipboard", "by", "relieving", "all", "model", "references", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/clipboard.py#L506-L514
train
40,382
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
extend_extents
def extend_extents(extents, factor=1.1): """Extend a given bounding box The bounding box (x1, y1, x2, y2) is centrally stretched by the given factor. :param extents: The bound box extents :param factor: The factor for stretching :return: (x1, y1, x2, y2) of the extended bounding box """ width = extents[2] - extents[0] height = extents[3] - extents[1] add_width = (factor - 1) * width add_height = (factor - 1) * height x1 = extents[0] - add_width / 2 x2 = extents[2] + add_width / 2 y1 = extents[1] - add_height / 2 y2 = extents[3] + add_height / 2 return x1, y1, x2, y2
python
def extend_extents(extents, factor=1.1): """Extend a given bounding box The bounding box (x1, y1, x2, y2) is centrally stretched by the given factor. :param extents: The bound box extents :param factor: The factor for stretching :return: (x1, y1, x2, y2) of the extended bounding box """ width = extents[2] - extents[0] height = extents[3] - extents[1] add_width = (factor - 1) * width add_height = (factor - 1) * height x1 = extents[0] - add_width / 2 x2 = extents[2] + add_width / 2 y1 = extents[1] - add_height / 2 y2 = extents[3] + add_height / 2 return x1, y1, x2, y2
[ "def", "extend_extents", "(", "extents", ",", "factor", "=", "1.1", ")", ":", "width", "=", "extents", "[", "2", "]", "-", "extents", "[", "0", "]", "height", "=", "extents", "[", "3", "]", "-", "extents", "[", "1", "]", "add_width", "=", "(", "f...
Extend a given bounding box The bounding box (x1, y1, x2, y2) is centrally stretched by the given factor. :param extents: The bound box extents :param factor: The factor for stretching :return: (x1, y1, x2, y2) of the extended bounding box
[ "Extend", "a", "given", "bounding", "box" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L22-L39
train
40,383
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
calc_rel_pos_to_parent
def calc_rel_pos_to_parent(canvas, item, handle): """This method calculates the relative position of the given item's handle to its parent :param canvas: Canvas to find relative position in :param item: Item to find relative position to parent :param handle: Handle of item to find relative position to :return: Relative position (x, y) """ from gaphas.item import NW if isinstance(item, ConnectionView): return item.canvas.get_matrix_i2i(item, item.parent).transform_point(*handle.pos) parent = canvas.get_parent(item) if parent: return item.canvas.get_matrix_i2i(item, parent).transform_point(*handle.pos) else: return item.canvas.get_matrix_i2c(item).transform_point(*item.handles()[NW].pos)
python
def calc_rel_pos_to_parent(canvas, item, handle): """This method calculates the relative position of the given item's handle to its parent :param canvas: Canvas to find relative position in :param item: Item to find relative position to parent :param handle: Handle of item to find relative position to :return: Relative position (x, y) """ from gaphas.item import NW if isinstance(item, ConnectionView): return item.canvas.get_matrix_i2i(item, item.parent).transform_point(*handle.pos) parent = canvas.get_parent(item) if parent: return item.canvas.get_matrix_i2i(item, parent).transform_point(*handle.pos) else: return item.canvas.get_matrix_i2c(item).transform_point(*item.handles()[NW].pos)
[ "def", "calc_rel_pos_to_parent", "(", "canvas", ",", "item", ",", "handle", ")", ":", "from", "gaphas", ".", "item", "import", "NW", "if", "isinstance", "(", "item", ",", "ConnectionView", ")", ":", "return", "item", ".", "canvas", ".", "get_matrix_i2i", "...
This method calculates the relative position of the given item's handle to its parent :param canvas: Canvas to find relative position in :param item: Item to find relative position to parent :param handle: Handle of item to find relative position to :return: Relative position (x, y)
[ "This", "method", "calculates", "the", "relative", "position", "of", "the", "given", "item", "s", "handle", "to", "its", "parent" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L42-L59
train
40,384
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
assert_exactly_one_true
def assert_exactly_one_true(bool_list): """This method asserts that only one value of the provided list is True. :param bool_list: List of booleans to check :return: True if only one value is True, False otherwise """ assert isinstance(bool_list, list) counter = 0 for item in bool_list: if item: counter += 1 return counter == 1
python
def assert_exactly_one_true(bool_list): """This method asserts that only one value of the provided list is True. :param bool_list: List of booleans to check :return: True if only one value is True, False otherwise """ assert isinstance(bool_list, list) counter = 0 for item in bool_list: if item: counter += 1 return counter == 1
[ "def", "assert_exactly_one_true", "(", "bool_list", ")", ":", "assert", "isinstance", "(", "bool_list", ",", "list", ")", "counter", "=", "0", "for", "item", "in", "bool_list", ":", "if", "item", ":", "counter", "+=", "1", "return", "counter", "==", "1" ]
This method asserts that only one value of the provided list is True. :param bool_list: List of booleans to check :return: True if only one value is True, False otherwise
[ "This", "method", "asserts", "that", "only", "one", "value", "of", "the", "provided", "list", "is", "True", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L62-L73
train
40,385
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
get_state_id_for_port
def get_state_id_for_port(port): """This method returns the state ID of the state containing the given port :param port: Port to check for containing state ID :return: State ID of state containing port """ parent = port.parent from rafcon.gui.mygaphas.items.state import StateView if isinstance(parent, StateView): return parent.model.state.state_id
python
def get_state_id_for_port(port): """This method returns the state ID of the state containing the given port :param port: Port to check for containing state ID :return: State ID of state containing port """ parent = port.parent from rafcon.gui.mygaphas.items.state import StateView if isinstance(parent, StateView): return parent.model.state.state_id
[ "def", "get_state_id_for_port", "(", "port", ")", ":", "parent", "=", "port", ".", "parent", "from", "rafcon", ".", "gui", ".", "mygaphas", ".", "items", ".", "state", "import", "StateView", "if", "isinstance", "(", "parent", ",", "StateView", ")", ":", ...
This method returns the state ID of the state containing the given port :param port: Port to check for containing state ID :return: State ID of state containing port
[ "This", "method", "returns", "the", "state", "ID", "of", "the", "state", "containing", "the", "given", "port" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L76-L85
train
40,386
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
get_port_for_handle
def get_port_for_handle(handle, state): """Looks for and returns the PortView to the given handle in the provided state :param handle: Handle to look for port :param state: State containing handle and port :returns: PortView for handle """ from rafcon.gui.mygaphas.items.state import StateView if isinstance(state, StateView): if state.income.handle == handle: return state.income else: for outcome in state.outcomes: if outcome.handle == handle: return outcome for input in state.inputs: if input.handle == handle: return input for output in state.outputs: if output.handle == handle: return output for scoped in state.scoped_variables: if scoped.handle == handle: return scoped
python
def get_port_for_handle(handle, state): """Looks for and returns the PortView to the given handle in the provided state :param handle: Handle to look for port :param state: State containing handle and port :returns: PortView for handle """ from rafcon.gui.mygaphas.items.state import StateView if isinstance(state, StateView): if state.income.handle == handle: return state.income else: for outcome in state.outcomes: if outcome.handle == handle: return outcome for input in state.inputs: if input.handle == handle: return input for output in state.outputs: if output.handle == handle: return output for scoped in state.scoped_variables: if scoped.handle == handle: return scoped
[ "def", "get_port_for_handle", "(", "handle", ",", "state", ")", ":", "from", "rafcon", ".", "gui", ".", "mygaphas", ".", "items", ".", "state", "import", "StateView", "if", "isinstance", "(", "state", ",", "StateView", ")", ":", "if", "state", ".", "inco...
Looks for and returns the PortView to the given handle in the provided state :param handle: Handle to look for port :param state: State containing handle and port :returns: PortView for handle
[ "Looks", "for", "and", "returns", "the", "PortView", "to", "the", "given", "handle", "in", "the", "provided", "state" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L88-L111
train
40,387
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
create_new_connection
def create_new_connection(from_port, to_port): """Checks the type of connection and tries to create it If bot port are logical port,s a transition is created. If both ports are data ports (including scoped variable), then a data flow is added. An error log is created, when the types are not compatible. :param from_port: The starting port of the connection :param to_port: The end point of the connection :return: True if a new connection was added """ from rafcon.gui.mygaphas.items.ports import ScopedVariablePortView, LogicPortView, DataPortView if isinstance(from_port, LogicPortView) and isinstance(to_port, LogicPortView): return add_transition_to_state(from_port, to_port) elif isinstance(from_port, (DataPortView, ScopedVariablePortView)) and \ isinstance(to_port, (DataPortView, ScopedVariablePortView)): return add_data_flow_to_state(from_port, to_port) # Both ports are not None elif from_port and to_port: logger.error("Connection of non-compatible ports: {0} and {1}".format(type(from_port), type(to_port))) return False
python
def create_new_connection(from_port, to_port): """Checks the type of connection and tries to create it If bot port are logical port,s a transition is created. If both ports are data ports (including scoped variable), then a data flow is added. An error log is created, when the types are not compatible. :param from_port: The starting port of the connection :param to_port: The end point of the connection :return: True if a new connection was added """ from rafcon.gui.mygaphas.items.ports import ScopedVariablePortView, LogicPortView, DataPortView if isinstance(from_port, LogicPortView) and isinstance(to_port, LogicPortView): return add_transition_to_state(from_port, to_port) elif isinstance(from_port, (DataPortView, ScopedVariablePortView)) and \ isinstance(to_port, (DataPortView, ScopedVariablePortView)): return add_data_flow_to_state(from_port, to_port) # Both ports are not None elif from_port and to_port: logger.error("Connection of non-compatible ports: {0} and {1}".format(type(from_port), type(to_port))) return False
[ "def", "create_new_connection", "(", "from_port", ",", "to_port", ")", ":", "from", "rafcon", ".", "gui", ".", "mygaphas", ".", "items", ".", "ports", "import", "ScopedVariablePortView", ",", "LogicPortView", ",", "DataPortView", "if", "isinstance", "(", "from_p...
Checks the type of connection and tries to create it If bot port are logical port,s a transition is created. If both ports are data ports (including scoped variable), then a data flow is added. An error log is created, when the types are not compatible. :param from_port: The starting port of the connection :param to_port: The end point of the connection :return: True if a new connection was added
[ "Checks", "the", "type", "of", "connection", "and", "tries", "to", "create", "it" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L114-L135
train
40,388
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
add_data_flow_to_state
def add_data_flow_to_state(from_port, to_port): """Interface method between Gaphas and RAFCON core for adding data flows The method checks the types of the given ports and their relation. From this the necessary parameters for the add_dat_flow method of the RAFCON core are determined. Also the parent state is derived from the ports. :param from_port: Port from which the data flow starts :param to_port: Port to which the data flow goes to :return: True if a data flow was added, False if an error occurred """ from rafcon.gui.mygaphas.items.ports import InputPortView, OutputPortView, ScopedVariablePortView from rafcon.gui.models.container_state import ContainerStateModel from_state_v = from_port.parent to_state_v = to_port.parent from_state_m = from_state_v.model to_state_m = to_state_v.model from_state_id = from_state_m.state.state_id to_state_id = to_state_m.state.state_id from_port_id = from_port.port_id to_port_id = to_port.port_id if not isinstance(from_port, (InputPortView, OutputPortView, ScopedVariablePortView)) or \ not isinstance(from_port, (InputPortView, OutputPortView, ScopedVariablePortView)): logger.error("Data flows only exist between data ports (input, output, scope). Given: {0} and {1}".format(type( from_port), type(to_port))) return False responsible_parent_m = None # from parent to child if isinstance(from_state_m, ContainerStateModel) and \ check_if_dict_contains_object_reference_in_values(to_state_m.state, from_state_m.state.states): responsible_parent_m = from_state_m # from child to parent elif isinstance(to_state_m, ContainerStateModel) and \ check_if_dict_contains_object_reference_in_values(from_state_m.state, to_state_m.state.states): responsible_parent_m = to_state_m # from parent to parent elif isinstance(from_state_m, ContainerStateModel) and from_state_m.state is to_state_m.state: responsible_parent_m = from_state_m # == to_state_m # from child to child elif (not from_state_m.state.is_root_state) and (not to_state_m.state.is_root_state) \ and from_state_m.state is not to_state_m.state \ and from_state_m.parent.state.state_id and to_state_m.parent.state.state_id: responsible_parent_m = from_state_m.parent if not isinstance(responsible_parent_m, ContainerStateModel): logger.error("Data flows only exist in container states (e.g. hierarchy states)") return False try: responsible_parent_m.state.add_data_flow(from_state_id, from_port_id, to_state_id, to_port_id) return True except (ValueError, AttributeError, TypeError) as e: logger.error("Data flow couldn't be added: {0}".format(e)) return False
python
def add_data_flow_to_state(from_port, to_port): """Interface method between Gaphas and RAFCON core for adding data flows The method checks the types of the given ports and their relation. From this the necessary parameters for the add_dat_flow method of the RAFCON core are determined. Also the parent state is derived from the ports. :param from_port: Port from which the data flow starts :param to_port: Port to which the data flow goes to :return: True if a data flow was added, False if an error occurred """ from rafcon.gui.mygaphas.items.ports import InputPortView, OutputPortView, ScopedVariablePortView from rafcon.gui.models.container_state import ContainerStateModel from_state_v = from_port.parent to_state_v = to_port.parent from_state_m = from_state_v.model to_state_m = to_state_v.model from_state_id = from_state_m.state.state_id to_state_id = to_state_m.state.state_id from_port_id = from_port.port_id to_port_id = to_port.port_id if not isinstance(from_port, (InputPortView, OutputPortView, ScopedVariablePortView)) or \ not isinstance(from_port, (InputPortView, OutputPortView, ScopedVariablePortView)): logger.error("Data flows only exist between data ports (input, output, scope). Given: {0} and {1}".format(type( from_port), type(to_port))) return False responsible_parent_m = None # from parent to child if isinstance(from_state_m, ContainerStateModel) and \ check_if_dict_contains_object_reference_in_values(to_state_m.state, from_state_m.state.states): responsible_parent_m = from_state_m # from child to parent elif isinstance(to_state_m, ContainerStateModel) and \ check_if_dict_contains_object_reference_in_values(from_state_m.state, to_state_m.state.states): responsible_parent_m = to_state_m # from parent to parent elif isinstance(from_state_m, ContainerStateModel) and from_state_m.state is to_state_m.state: responsible_parent_m = from_state_m # == to_state_m # from child to child elif (not from_state_m.state.is_root_state) and (not to_state_m.state.is_root_state) \ and from_state_m.state is not to_state_m.state \ and from_state_m.parent.state.state_id and to_state_m.parent.state.state_id: responsible_parent_m = from_state_m.parent if not isinstance(responsible_parent_m, ContainerStateModel): logger.error("Data flows only exist in container states (e.g. hierarchy states)") return False try: responsible_parent_m.state.add_data_flow(from_state_id, from_port_id, to_state_id, to_port_id) return True except (ValueError, AttributeError, TypeError) as e: logger.error("Data flow couldn't be added: {0}".format(e)) return False
[ "def", "add_data_flow_to_state", "(", "from_port", ",", "to_port", ")", ":", "from", "rafcon", ".", "gui", ".", "mygaphas", ".", "items", ".", "ports", "import", "InputPortView", ",", "OutputPortView", ",", "ScopedVariablePortView", "from", "rafcon", ".", "gui",...
Interface method between Gaphas and RAFCON core for adding data flows The method checks the types of the given ports and their relation. From this the necessary parameters for the add_dat_flow method of the RAFCON core are determined. Also the parent state is derived from the ports. :param from_port: Port from which the data flow starts :param to_port: Port to which the data flow goes to :return: True if a data flow was added, False if an error occurred
[ "Interface", "method", "between", "Gaphas", "and", "RAFCON", "core", "for", "adding", "data", "flows" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L138-L197
train
40,389
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
add_transition_to_state
def add_transition_to_state(from_port, to_port): """Interface method between Gaphas and RAFCON core for adding transitions The method checks the types of the given ports (IncomeView or OutcomeView) and from this determines the necessary parameters for the add_transition method of the RAFCON core. Also the parent state is derived from the ports. :param from_port: Port from which the transition starts :param to_port: Port to which the transition goes to :return: True if a transition was added, False if an error occurred """ from rafcon.gui.mygaphas.items.ports import IncomeView, OutcomeView from_state_v = from_port.parent to_state_v = to_port.parent from_state_m = from_state_v.model to_state_m = to_state_v.model # Gather necessary information to create transition from_state_id = from_state_m.state.state_id to_state_id = to_state_m.state.state_id responsible_parent_m = None # Start transition if isinstance(from_port, IncomeView): from_state_id = None from_outcome_id = None responsible_parent_m = from_state_m # Transition from parent income to child income if isinstance(to_port, IncomeView): to_outcome_id = None # Transition from parent income to parent outcome elif isinstance(to_port, OutcomeView): to_outcome_id = to_port.outcome_id elif isinstance(from_port, OutcomeView): from_outcome_id = from_port.outcome_id # Transition from child outcome to child income if isinstance(to_port, IncomeView): responsible_parent_m = from_state_m.parent to_outcome_id = None # Transition from child outcome to parent outcome elif isinstance(to_port, OutcomeView): responsible_parent_m = to_state_m to_outcome_id = to_port.outcome_id else: raise ValueError("Invalid port type") from rafcon.gui.models.container_state import ContainerStateModel if not responsible_parent_m: logger.error("Transitions only exist between incomes and outcomes. Given: {0} and {1}".format(type( from_port), type(to_port))) return False elif not isinstance(responsible_parent_m, ContainerStateModel): logger.error("Transitions only exist in container states (e.g. hierarchy states)") return False try: t_id = responsible_parent_m.state.add_transition(from_state_id, from_outcome_id, to_state_id, to_outcome_id) if from_state_id == to_state_id: gui_helper_meta_data.insert_self_transition_meta_data(responsible_parent_m.states[from_state_id], t_id, combined_action=True) return True except (ValueError, AttributeError, TypeError) as e: logger.error("Transition couldn't be added: {0}".format(e)) return False
python
def add_transition_to_state(from_port, to_port): """Interface method between Gaphas and RAFCON core for adding transitions The method checks the types of the given ports (IncomeView or OutcomeView) and from this determines the necessary parameters for the add_transition method of the RAFCON core. Also the parent state is derived from the ports. :param from_port: Port from which the transition starts :param to_port: Port to which the transition goes to :return: True if a transition was added, False if an error occurred """ from rafcon.gui.mygaphas.items.ports import IncomeView, OutcomeView from_state_v = from_port.parent to_state_v = to_port.parent from_state_m = from_state_v.model to_state_m = to_state_v.model # Gather necessary information to create transition from_state_id = from_state_m.state.state_id to_state_id = to_state_m.state.state_id responsible_parent_m = None # Start transition if isinstance(from_port, IncomeView): from_state_id = None from_outcome_id = None responsible_parent_m = from_state_m # Transition from parent income to child income if isinstance(to_port, IncomeView): to_outcome_id = None # Transition from parent income to parent outcome elif isinstance(to_port, OutcomeView): to_outcome_id = to_port.outcome_id elif isinstance(from_port, OutcomeView): from_outcome_id = from_port.outcome_id # Transition from child outcome to child income if isinstance(to_port, IncomeView): responsible_parent_m = from_state_m.parent to_outcome_id = None # Transition from child outcome to parent outcome elif isinstance(to_port, OutcomeView): responsible_parent_m = to_state_m to_outcome_id = to_port.outcome_id else: raise ValueError("Invalid port type") from rafcon.gui.models.container_state import ContainerStateModel if not responsible_parent_m: logger.error("Transitions only exist between incomes and outcomes. Given: {0} and {1}".format(type( from_port), type(to_port))) return False elif not isinstance(responsible_parent_m, ContainerStateModel): logger.error("Transitions only exist in container states (e.g. hierarchy states)") return False try: t_id = responsible_parent_m.state.add_transition(from_state_id, from_outcome_id, to_state_id, to_outcome_id) if from_state_id == to_state_id: gui_helper_meta_data.insert_self_transition_meta_data(responsible_parent_m.states[from_state_id], t_id, combined_action=True) return True except (ValueError, AttributeError, TypeError) as e: logger.error("Transition couldn't be added: {0}".format(e)) return False
[ "def", "add_transition_to_state", "(", "from_port", ",", "to_port", ")", ":", "from", "rafcon", ".", "gui", ".", "mygaphas", ".", "items", ".", "ports", "import", "IncomeView", ",", "OutcomeView", "from_state_v", "=", "from_port", ".", "parent", "to_state_v", ...
Interface method between Gaphas and RAFCON core for adding transitions The method checks the types of the given ports (IncomeView or OutcomeView) and from this determines the necessary parameters for the add_transition method of the RAFCON core. Also the parent state is derived from the ports. :param from_port: Port from which the transition starts :param to_port: Port to which the transition goes to :return: True if a transition was added, False if an error occurred
[ "Interface", "method", "between", "Gaphas", "and", "RAFCON", "core", "for", "adding", "transitions" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L200-L265
train
40,390
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
get_relative_positions_of_waypoints
def get_relative_positions_of_waypoints(transition_v): """This method takes the waypoints of a connection and returns all relative positions of these waypoints. :param canvas: Canvas to check relative position in :param transition_v: Transition view to extract all relative waypoint positions :return: List with all relative positions of the given transition """ handles_list = transition_v.handles() rel_pos_list = [] for handle in handles_list: if handle in transition_v.end_handles(include_waypoints=True): continue rel_pos = transition_v.canvas.get_matrix_i2i(transition_v, transition_v.parent).transform_point(*handle.pos) rel_pos_list.append(rel_pos) return rel_pos_list
python
def get_relative_positions_of_waypoints(transition_v): """This method takes the waypoints of a connection and returns all relative positions of these waypoints. :param canvas: Canvas to check relative position in :param transition_v: Transition view to extract all relative waypoint positions :return: List with all relative positions of the given transition """ handles_list = transition_v.handles() rel_pos_list = [] for handle in handles_list: if handle in transition_v.end_handles(include_waypoints=True): continue rel_pos = transition_v.canvas.get_matrix_i2i(transition_v, transition_v.parent).transform_point(*handle.pos) rel_pos_list.append(rel_pos) return rel_pos_list
[ "def", "get_relative_positions_of_waypoints", "(", "transition_v", ")", ":", "handles_list", "=", "transition_v", ".", "handles", "(", ")", "rel_pos_list", "=", "[", "]", "for", "handle", "in", "handles_list", ":", "if", "handle", "in", "transition_v", ".", "end...
This method takes the waypoints of a connection and returns all relative positions of these waypoints. :param canvas: Canvas to check relative position in :param transition_v: Transition view to extract all relative waypoint positions :return: List with all relative positions of the given transition
[ "This", "method", "takes", "the", "waypoints", "of", "a", "connection", "and", "returns", "all", "relative", "positions", "of", "these", "waypoints", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L268-L282
train
40,391
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
update_meta_data_for_transition_waypoints
def update_meta_data_for_transition_waypoints(graphical_editor_view, transition_v, last_waypoint_list, publish=True): """This method updates the relative position meta data of the transitions waypoints if they changed :param graphical_editor_view: Graphical Editor the change occurred in :param transition_v: Transition that changed :param last_waypoint_list: List of waypoints before change :param bool publish: Whether to publish the changes using the meta signal """ from rafcon.gui.mygaphas.items.connection import TransitionView assert isinstance(transition_v, TransitionView) transition_m = transition_v.model waypoint_list = get_relative_positions_of_waypoints(transition_v) if waypoint_list != last_waypoint_list: transition_m.set_meta_data_editor('waypoints', waypoint_list) if publish: graphical_editor_view.emit('meta_data_changed', transition_m, "waypoints", False)
python
def update_meta_data_for_transition_waypoints(graphical_editor_view, transition_v, last_waypoint_list, publish=True): """This method updates the relative position meta data of the transitions waypoints if they changed :param graphical_editor_view: Graphical Editor the change occurred in :param transition_v: Transition that changed :param last_waypoint_list: List of waypoints before change :param bool publish: Whether to publish the changes using the meta signal """ from rafcon.gui.mygaphas.items.connection import TransitionView assert isinstance(transition_v, TransitionView) transition_m = transition_v.model waypoint_list = get_relative_positions_of_waypoints(transition_v) if waypoint_list != last_waypoint_list: transition_m.set_meta_data_editor('waypoints', waypoint_list) if publish: graphical_editor_view.emit('meta_data_changed', transition_m, "waypoints", False)
[ "def", "update_meta_data_for_transition_waypoints", "(", "graphical_editor_view", ",", "transition_v", ",", "last_waypoint_list", ",", "publish", "=", "True", ")", ":", "from", "rafcon", ".", "gui", ".", "mygaphas", ".", "items", ".", "connection", "import", "Transi...
This method updates the relative position meta data of the transitions waypoints if they changed :param graphical_editor_view: Graphical Editor the change occurred in :param transition_v: Transition that changed :param last_waypoint_list: List of waypoints before change :param bool publish: Whether to publish the changes using the meta signal
[ "This", "method", "updates", "the", "relative", "position", "meta", "data", "of", "the", "transitions", "waypoints", "if", "they", "changed" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L285-L302
train
40,392
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
update_meta_data_for_port
def update_meta_data_for_port(graphical_editor_view, item, handle): """This method updates the meta data of the states ports if they changed. :param graphical_editor_view: Graphical Editor the change occurred in :param item: State the port was moved in :param handle: Handle of moved port or None if all ports are to be updated """ from rafcon.gui.mygaphas.items.ports import IncomeView, OutcomeView, InputPortView, OutputPortView, \ ScopedVariablePortView for port in item.get_all_ports(): if not handle or handle is port.handle: rel_pos = (port.handle.pos.x.value, port.handle.pos.y.value) if isinstance(port, (IncomeView, OutcomeView, InputPortView, OutputPortView, ScopedVariablePortView)): port_m = port.model cur_rel_pos = port_m.get_meta_data_editor()['rel_pos'] if rel_pos != cur_rel_pos: port_m.set_meta_data_editor('rel_pos', rel_pos) if handle: graphical_editor_view.emit('meta_data_changed', port_m, "position", True) else: continue if handle: # If we were supposed to update the meta data of a specific port, we can stop here break
python
def update_meta_data_for_port(graphical_editor_view, item, handle): """This method updates the meta data of the states ports if they changed. :param graphical_editor_view: Graphical Editor the change occurred in :param item: State the port was moved in :param handle: Handle of moved port or None if all ports are to be updated """ from rafcon.gui.mygaphas.items.ports import IncomeView, OutcomeView, InputPortView, OutputPortView, \ ScopedVariablePortView for port in item.get_all_ports(): if not handle or handle is port.handle: rel_pos = (port.handle.pos.x.value, port.handle.pos.y.value) if isinstance(port, (IncomeView, OutcomeView, InputPortView, OutputPortView, ScopedVariablePortView)): port_m = port.model cur_rel_pos = port_m.get_meta_data_editor()['rel_pos'] if rel_pos != cur_rel_pos: port_m.set_meta_data_editor('rel_pos', rel_pos) if handle: graphical_editor_view.emit('meta_data_changed', port_m, "position", True) else: continue if handle: # If we were supposed to update the meta data of a specific port, we can stop here break
[ "def", "update_meta_data_for_port", "(", "graphical_editor_view", ",", "item", ",", "handle", ")", ":", "from", "rafcon", ".", "gui", ".", "mygaphas", ".", "items", ".", "ports", "import", "IncomeView", ",", "OutcomeView", ",", "InputPortView", ",", "OutputPortV...
This method updates the meta data of the states ports if they changed. :param graphical_editor_view: Graphical Editor the change occurred in :param item: State the port was moved in :param handle: Handle of moved port or None if all ports are to be updated
[ "This", "method", "updates", "the", "meta", "data", "of", "the", "states", "ports", "if", "they", "changed", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L305-L329
train
40,393
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
update_meta_data_for_name_view
def update_meta_data_for_name_view(graphical_editor_view, name_v, publish=True): """This method updates the meta data of a name view. :param graphical_editor_view: Graphical Editor view the change occurred in :param name_v: The name view which has been changed/moved :param publish: Whether to publish the changes of the meta data """ from gaphas.item import NW rel_pos = calc_rel_pos_to_parent(graphical_editor_view.editor.canvas, name_v, name_v.handles()[NW]) state_v = graphical_editor_view.editor.canvas.get_parent(name_v) state_v.model.set_meta_data_editor('name.size', (name_v.width, name_v.height)) state_v.model.set_meta_data_editor('name.rel_pos', rel_pos) if publish: graphical_editor_view.emit('meta_data_changed', state_v.model, "name_size", False)
python
def update_meta_data_for_name_view(graphical_editor_view, name_v, publish=True): """This method updates the meta data of a name view. :param graphical_editor_view: Graphical Editor view the change occurred in :param name_v: The name view which has been changed/moved :param publish: Whether to publish the changes of the meta data """ from gaphas.item import NW rel_pos = calc_rel_pos_to_parent(graphical_editor_view.editor.canvas, name_v, name_v.handles()[NW]) state_v = graphical_editor_view.editor.canvas.get_parent(name_v) state_v.model.set_meta_data_editor('name.size', (name_v.width, name_v.height)) state_v.model.set_meta_data_editor('name.rel_pos', rel_pos) if publish: graphical_editor_view.emit('meta_data_changed', state_v.model, "name_size", False)
[ "def", "update_meta_data_for_name_view", "(", "graphical_editor_view", ",", "name_v", ",", "publish", "=", "True", ")", ":", "from", "gaphas", ".", "item", "import", "NW", "rel_pos", "=", "calc_rel_pos_to_parent", "(", "graphical_editor_view", ".", "editor", ".", ...
This method updates the meta data of a name view. :param graphical_editor_view: Graphical Editor view the change occurred in :param name_v: The name view which has been changed/moved :param publish: Whether to publish the changes of the meta data
[ "This", "method", "updates", "the", "meta", "data", "of", "a", "name", "view", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L332-L348
train
40,394
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_helper.py
update_meta_data_for_state_view
def update_meta_data_for_state_view(graphical_editor_view, state_v, affects_children=False, publish=True): """This method updates the meta data of a state view :param graphical_editor_view: Graphical Editor view the change occurred in :param state_v: The state view which has been changed/moved :param affects_children: Whether the children of the state view have been resized or not :param publish: Whether to publish the changes of the meta data """ from gaphas.item import NW # Update all port meta data to match with new position and size of parent update_meta_data_for_port(graphical_editor_view, state_v, None) if affects_children: update_meta_data_for_name_view(graphical_editor_view, state_v.name_view, publish=False) for transition_v in state_v.get_transitions(): update_meta_data_for_transition_waypoints(graphical_editor_view, transition_v, None, publish=False) for child_state_v in state_v.child_state_views(): update_meta_data_for_state_view(graphical_editor_view, child_state_v, True, publish=False) rel_pos = calc_rel_pos_to_parent(graphical_editor_view.editor.canvas, state_v, state_v.handles()[NW]) state_v.model.set_meta_data_editor('size', (state_v.width, state_v.height)) state_v.model.set_meta_data_editor('rel_pos', rel_pos) if publish: graphical_editor_view.emit('meta_data_changed', state_v.model, "size", affects_children)
python
def update_meta_data_for_state_view(graphical_editor_view, state_v, affects_children=False, publish=True): """This method updates the meta data of a state view :param graphical_editor_view: Graphical Editor view the change occurred in :param state_v: The state view which has been changed/moved :param affects_children: Whether the children of the state view have been resized or not :param publish: Whether to publish the changes of the meta data """ from gaphas.item import NW # Update all port meta data to match with new position and size of parent update_meta_data_for_port(graphical_editor_view, state_v, None) if affects_children: update_meta_data_for_name_view(graphical_editor_view, state_v.name_view, publish=False) for transition_v in state_v.get_transitions(): update_meta_data_for_transition_waypoints(graphical_editor_view, transition_v, None, publish=False) for child_state_v in state_v.child_state_views(): update_meta_data_for_state_view(graphical_editor_view, child_state_v, True, publish=False) rel_pos = calc_rel_pos_to_parent(graphical_editor_view.editor.canvas, state_v, state_v.handles()[NW]) state_v.model.set_meta_data_editor('size', (state_v.width, state_v.height)) state_v.model.set_meta_data_editor('rel_pos', rel_pos) if publish: graphical_editor_view.emit('meta_data_changed', state_v.model, "size", affects_children)
[ "def", "update_meta_data_for_state_view", "(", "graphical_editor_view", ",", "state_v", ",", "affects_children", "=", "False", ",", "publish", "=", "True", ")", ":", "from", "gaphas", ".", "item", "import", "NW", "# Update all port meta data to match with new position and...
This method updates the meta data of a state view :param graphical_editor_view: Graphical Editor view the change occurred in :param state_v: The state view which has been changed/moved :param affects_children: Whether the children of the state view have been resized or not :param publish: Whether to publish the changes of the meta data
[ "This", "method", "updates", "the", "meta", "data", "of", "a", "state", "view" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_helper.py#L351-L377
train
40,395
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/items/state.py
StateView.remove
def remove(self): """Remove recursively all children and then the StateView itself """ self.canvas.get_first_view().unselect_item(self) for child in self.canvas.get_children(self)[:]: child.remove() self.remove_income() for outcome_v in self.outcomes[:]: self.remove_outcome(outcome_v) for input_port_v in self.inputs[:]: self.remove_input_port(input_port_v) for output_port_v in self.outputs[:]: self.remove_output_port(output_port_v) for scoped_variable_port_v in self.scoped_variables[:]: self.remove_scoped_variable(scoped_variable_port_v) self.remove_keep_rect_within_constraint_from_parent() for constraint in self._constraints[:]: self.canvas.solver.remove_constraint(constraint) self._constraints.remove(constraint) self.canvas.remove(self)
python
def remove(self): """Remove recursively all children and then the StateView itself """ self.canvas.get_first_view().unselect_item(self) for child in self.canvas.get_children(self)[:]: child.remove() self.remove_income() for outcome_v in self.outcomes[:]: self.remove_outcome(outcome_v) for input_port_v in self.inputs[:]: self.remove_input_port(input_port_v) for output_port_v in self.outputs[:]: self.remove_output_port(output_port_v) for scoped_variable_port_v in self.scoped_variables[:]: self.remove_scoped_variable(scoped_variable_port_v) self.remove_keep_rect_within_constraint_from_parent() for constraint in self._constraints[:]: self.canvas.solver.remove_constraint(constraint) self._constraints.remove(constraint) self.canvas.remove(self)
[ "def", "remove", "(", "self", ")", ":", "self", ".", "canvas", ".", "get_first_view", "(", ")", ".", "unselect_item", "(", "self", ")", "for", "child", "in", "self", ".", "canvas", ".", "get_children", "(", "self", ")", "[", ":", "]", ":", "child", ...
Remove recursively all children and then the StateView itself
[ "Remove", "recursively", "all", "children", "and", "then", "the", "StateView", "itself" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/state.py#L187-L209
train
40,396
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/items/state.py
StateView.show_content
def show_content(self, with_content=False): """Checks if the state is a library with the `show_content` flag set :param with_content: If this parameter is `True`, the method return only True if the library represents a ContainerState :return: Whether the content of a library state is shown """ if isinstance(self.model, LibraryStateModel) and self.model.show_content(): return not with_content or isinstance(self.model.state_copy, ContainerStateModel) return False
python
def show_content(self, with_content=False): """Checks if the state is a library with the `show_content` flag set :param with_content: If this parameter is `True`, the method return only True if the library represents a ContainerState :return: Whether the content of a library state is shown """ if isinstance(self.model, LibraryStateModel) and self.model.show_content(): return not with_content or isinstance(self.model.state_copy, ContainerStateModel) return False
[ "def", "show_content", "(", "self", ",", "with_content", "=", "False", ")", ":", "if", "isinstance", "(", "self", ".", "model", ",", "LibraryStateModel", ")", "and", "self", ".", "model", ".", "show_content", "(", ")", ":", "return", "not", "with_content",...
Checks if the state is a library with the `show_content` flag set :param with_content: If this parameter is `True`, the method return only True if the library represents a ContainerState :return: Whether the content of a library state is shown
[ "Checks", "if", "the", "state", "is", "a", "library", "with", "the", "show_content", "flag", "set" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/state.py#L336-L345
train
40,397
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/items/state.py
StateView._calculate_port_pos_on_line
def _calculate_port_pos_on_line(self, port_num, side_length, port_width=None): """Calculate the position of a port on a line The position depends on the number of element. Elements are equally spaced. If the end of the line is reached, ports are stacked. :param int port_num: The number of the port of that type :param float side_length: The length of the side the element is placed on :param float port_width: The width of one port :return: The position on the line for the given port :rtype: float """ if port_width is None: port_width = 2 * self.border_width border_size = self.border_width pos = 0.5 * border_size + port_num * port_width outermost_pos = max(side_length / 2., side_length - 0.5 * border_size - port_width) pos = min(pos, outermost_pos) return pos
python
def _calculate_port_pos_on_line(self, port_num, side_length, port_width=None): """Calculate the position of a port on a line The position depends on the number of element. Elements are equally spaced. If the end of the line is reached, ports are stacked. :param int port_num: The number of the port of that type :param float side_length: The length of the side the element is placed on :param float port_width: The width of one port :return: The position on the line for the given port :rtype: float """ if port_width is None: port_width = 2 * self.border_width border_size = self.border_width pos = 0.5 * border_size + port_num * port_width outermost_pos = max(side_length / 2., side_length - 0.5 * border_size - port_width) pos = min(pos, outermost_pos) return pos
[ "def", "_calculate_port_pos_on_line", "(", "self", ",", "port_num", ",", "side_length", ",", "port_width", "=", "None", ")", ":", "if", "port_width", "is", "None", ":", "port_width", "=", "2", "*", "self", ".", "border_width", "border_size", "=", "self", "."...
Calculate the position of a port on a line The position depends on the number of element. Elements are equally spaced. If the end of the line is reached, ports are stacked. :param int port_num: The number of the port of that type :param float side_length: The length of the side the element is placed on :param float port_width: The width of one port :return: The position on the line for the given port :rtype: float
[ "Calculate", "the", "position", "of", "a", "port", "on", "a", "line" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/state.py#L796-L813
train
40,398
DLR-RM/RAFCON
source/rafcon/utils/storage_utils.py
load_objects_from_json
def load_objects_from_json(path, as_dict=False): """Loads a dictionary from a json file. :param path: The relative path of the json file. :return: The dictionary specified in the json file """ f = open(path, 'r') if as_dict: result = json.load(f) else: result = json.load(f, cls=JSONObjectDecoder, substitute_modules=substitute_modules) f.close() return result
python
def load_objects_from_json(path, as_dict=False): """Loads a dictionary from a json file. :param path: The relative path of the json file. :return: The dictionary specified in the json file """ f = open(path, 'r') if as_dict: result = json.load(f) else: result = json.load(f, cls=JSONObjectDecoder, substitute_modules=substitute_modules) f.close() return result
[ "def", "load_objects_from_json", "(", "path", ",", "as_dict", "=", "False", ")", ":", "f", "=", "open", "(", "path", ",", "'r'", ")", "if", "as_dict", ":", "result", "=", "json", ".", "load", "(", "f", ")", "else", ":", "result", "=", "json", ".", ...
Loads a dictionary from a json file. :param path: The relative path of the json file. :return: The dictionary specified in the json file
[ "Loads", "a", "dictionary", "from", "a", "json", "file", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/storage_utils.py#L116-L128
train
40,399