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/views/logging_console.py | LoggingConsoleView.get_line_number_next_to_cursor_with_string_within | def get_line_number_next_to_cursor_with_string_within(self, s):
""" Find the closest occurrence of a string with respect to the cursor position in the text view """
line_number, _ = self.get_cursor_position()
text_buffer = self.text_view.get_buffer()
line_iter = text_buffer.get_iter_at_line(line_number)
# find closest before line with string within
before_line_number = None
while line_iter.backward_line():
if s in self.get_text_of_line(line_iter):
before_line_number = line_iter.get_line()
break
# find closest after line with string within
after_line_number = None
while line_iter.forward_line():
if s in self.get_text_of_line(line_iter):
after_line_number = line_iter.get_line()
break
# take closest one to current position
if after_line_number is not None and before_line_number is None:
return after_line_number, after_line_number - line_number
elif before_line_number is not None and after_line_number is None:
return before_line_number, line_number - before_line_number
elif after_line_number is not None and before_line_number is not None:
after_distance = after_line_number - line_number
before_distance = line_number - before_line_number
if after_distance < before_distance:
return after_line_number, after_distance
else:
return before_line_number, before_distance
else:
return None, None | python | def get_line_number_next_to_cursor_with_string_within(self, s):
""" Find the closest occurrence of a string with respect to the cursor position in the text view """
line_number, _ = self.get_cursor_position()
text_buffer = self.text_view.get_buffer()
line_iter = text_buffer.get_iter_at_line(line_number)
# find closest before line with string within
before_line_number = None
while line_iter.backward_line():
if s in self.get_text_of_line(line_iter):
before_line_number = line_iter.get_line()
break
# find closest after line with string within
after_line_number = None
while line_iter.forward_line():
if s in self.get_text_of_line(line_iter):
after_line_number = line_iter.get_line()
break
# take closest one to current position
if after_line_number is not None and before_line_number is None:
return after_line_number, after_line_number - line_number
elif before_line_number is not None and after_line_number is None:
return before_line_number, line_number - before_line_number
elif after_line_number is not None and before_line_number is not None:
after_distance = after_line_number - line_number
before_distance = line_number - before_line_number
if after_distance < before_distance:
return after_line_number, after_distance
else:
return before_line_number, before_distance
else:
return None, None | [
"def",
"get_line_number_next_to_cursor_with_string_within",
"(",
"self",
",",
"s",
")",
":",
"line_number",
",",
"_",
"=",
"self",
".",
"get_cursor_position",
"(",
")",
"text_buffer",
"=",
"self",
".",
"text_view",
".",
"get_buffer",
"(",
")",
"line_iter",
"=",
... | Find the closest occurrence of a string with respect to the cursor position in the text view | [
"Find",
"the",
"closest",
"occurrence",
"of",
"a",
"string",
"with",
"respect",
"to",
"the",
"cursor",
"position",
"in",
"the",
"text",
"view"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/logging_console.py#L209-L242 | train | 40,200 |
DLR-RM/RAFCON | source/rafcon/core/global_variable_manager.py | GlobalVariableManager.set_variable | def set_variable(self, key, value, per_reference=False, access_key=None, data_type=None):
"""Sets a global variable
:param key: the key of the global variable to be set
:param value: the new value of the global variable
:param per_reference: a flag to decide if the variable should be stored per reference or per value
:param access_key: if the variable was explicitly locked with the rafcon.state lock_variable
:raises exceptions.RuntimeError: if a wrong access key is passed
"""
key = str(key) # Ensure that we have the same string type for all keys (under Python2 and 3!)
if self.variable_exist(key):
if data_type is None:
data_type = self.__global_variable_type_dictionary[key]
else:
if data_type is None:
data_type = type(None)
assert isinstance(data_type, type)
self.check_value_and_type(value, data_type)
with self.__global_lock:
unlock = True
if self.variable_exist(key):
if self.is_locked(key) and self.__access_keys[key] != access_key:
raise RuntimeError("Wrong access key for accessing global variable")
elif self.is_locked(key):
unlock = False
else:
access_key = self.lock_variable(key, block=True)
else:
self.__variable_locks[key] = Lock()
access_key = self.lock_variable(key, block=True)
# --- variable locked
if per_reference:
self.__global_variable_dictionary[key] = value
self.__global_variable_type_dictionary[key] = data_type
self.__variable_references[key] = True
else:
self.__global_variable_dictionary[key] = copy.deepcopy(value)
self.__global_variable_type_dictionary[key] = data_type
self.__variable_references[key] = False
# --- release variable
if unlock:
self.unlock_variable(key, access_key)
logger.debug("Global variable '{}' was set to value '{}' with type '{}'".format(key, value, data_type.__name__)) | python | def set_variable(self, key, value, per_reference=False, access_key=None, data_type=None):
"""Sets a global variable
:param key: the key of the global variable to be set
:param value: the new value of the global variable
:param per_reference: a flag to decide if the variable should be stored per reference or per value
:param access_key: if the variable was explicitly locked with the rafcon.state lock_variable
:raises exceptions.RuntimeError: if a wrong access key is passed
"""
key = str(key) # Ensure that we have the same string type for all keys (under Python2 and 3!)
if self.variable_exist(key):
if data_type is None:
data_type = self.__global_variable_type_dictionary[key]
else:
if data_type is None:
data_type = type(None)
assert isinstance(data_type, type)
self.check_value_and_type(value, data_type)
with self.__global_lock:
unlock = True
if self.variable_exist(key):
if self.is_locked(key) and self.__access_keys[key] != access_key:
raise RuntimeError("Wrong access key for accessing global variable")
elif self.is_locked(key):
unlock = False
else:
access_key = self.lock_variable(key, block=True)
else:
self.__variable_locks[key] = Lock()
access_key = self.lock_variable(key, block=True)
# --- variable locked
if per_reference:
self.__global_variable_dictionary[key] = value
self.__global_variable_type_dictionary[key] = data_type
self.__variable_references[key] = True
else:
self.__global_variable_dictionary[key] = copy.deepcopy(value)
self.__global_variable_type_dictionary[key] = data_type
self.__variable_references[key] = False
# --- release variable
if unlock:
self.unlock_variable(key, access_key)
logger.debug("Global variable '{}' was set to value '{}' with type '{}'".format(key, value, data_type.__name__)) | [
"def",
"set_variable",
"(",
"self",
",",
"key",
",",
"value",
",",
"per_reference",
"=",
"False",
",",
"access_key",
"=",
"None",
",",
"data_type",
"=",
"None",
")",
":",
"key",
"=",
"str",
"(",
"key",
")",
"# Ensure that we have the same string type for all k... | Sets a global variable
:param key: the key of the global variable to be set
:param value: the new value of the global variable
:param per_reference: a flag to decide if the variable should be stored per reference or per value
:param access_key: if the variable was explicitly locked with the rafcon.state lock_variable
:raises exceptions.RuntimeError: if a wrong access key is passed | [
"Sets",
"a",
"global",
"variable"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L56-L102 | train | 40,201 |
DLR-RM/RAFCON | source/rafcon/core/global_variable_manager.py | GlobalVariableManager.get_variable | def get_variable(self, key, per_reference=None, access_key=None, default=None):
"""Fetches the value of a global variable
:param key: the key of the global variable to be fetched
:param bool per_reference: a flag to decide if the variable should be stored per reference or per value
:param access_key: if the variable was explicitly locked with the rafcon.state lock_variable
:param default: a value to be returned if the key does not exist
:return: The value stored at in the global variable key
:raises exceptions.RuntimeError: if a wrong access key is passed or the variable cannot be accessed by reference
"""
key = str(key)
if self.variable_exist(key):
unlock = True
if self.is_locked(key):
if self.__access_keys[key] == access_key:
unlock = False
else:
if not access_key:
access_key = self.lock_variable(key, block=True)
else:
raise RuntimeError("Wrong access key for accessing global variable")
else:
access_key = self.lock_variable(key, block=True)
# --- variable locked
if self.variable_can_be_referenced(key):
if per_reference or per_reference is None:
return_value = self.__global_variable_dictionary[key]
else:
return_value = copy.deepcopy(self.__global_variable_dictionary[key])
else:
if per_reference:
self.unlock_variable(key, access_key)
raise RuntimeError("Variable cannot be accessed by reference")
else:
return_value = copy.deepcopy(self.__global_variable_dictionary[key])
# --- release variable
if unlock:
self.unlock_variable(key, access_key)
return return_value
else:
# logger.warning("Global variable '{0}' not existing, returning default value".format(key))
return default | python | def get_variable(self, key, per_reference=None, access_key=None, default=None):
"""Fetches the value of a global variable
:param key: the key of the global variable to be fetched
:param bool per_reference: a flag to decide if the variable should be stored per reference or per value
:param access_key: if the variable was explicitly locked with the rafcon.state lock_variable
:param default: a value to be returned if the key does not exist
:return: The value stored at in the global variable key
:raises exceptions.RuntimeError: if a wrong access key is passed or the variable cannot be accessed by reference
"""
key = str(key)
if self.variable_exist(key):
unlock = True
if self.is_locked(key):
if self.__access_keys[key] == access_key:
unlock = False
else:
if not access_key:
access_key = self.lock_variable(key, block=True)
else:
raise RuntimeError("Wrong access key for accessing global variable")
else:
access_key = self.lock_variable(key, block=True)
# --- variable locked
if self.variable_can_be_referenced(key):
if per_reference or per_reference is None:
return_value = self.__global_variable_dictionary[key]
else:
return_value = copy.deepcopy(self.__global_variable_dictionary[key])
else:
if per_reference:
self.unlock_variable(key, access_key)
raise RuntimeError("Variable cannot be accessed by reference")
else:
return_value = copy.deepcopy(self.__global_variable_dictionary[key])
# --- release variable
if unlock:
self.unlock_variable(key, access_key)
return return_value
else:
# logger.warning("Global variable '{0}' not existing, returning default value".format(key))
return default | [
"def",
"get_variable",
"(",
"self",
",",
"key",
",",
"per_reference",
"=",
"None",
",",
"access_key",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"key",
"=",
"str",
"(",
"key",
")",
"if",
"self",
".",
"variable_exist",
"(",
"key",
")",
":",
... | Fetches the value of a global variable
:param key: the key of the global variable to be fetched
:param bool per_reference: a flag to decide if the variable should be stored per reference or per value
:param access_key: if the variable was explicitly locked with the rafcon.state lock_variable
:param default: a value to be returned if the key does not exist
:return: The value stored at in the global variable key
:raises exceptions.RuntimeError: if a wrong access key is passed or the variable cannot be accessed by reference | [
"Fetches",
"the",
"value",
"of",
"a",
"global",
"variable"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L104-L147 | train | 40,202 |
DLR-RM/RAFCON | source/rafcon/core/global_variable_manager.py | GlobalVariableManager.variable_can_be_referenced | def variable_can_be_referenced(self, key):
"""Checks whether the value of the variable can be returned by reference
:param str key: Name of the variable
:return: True if value of variable can be returned by reference, False else
"""
key = str(key)
return key in self.__variable_references and self.__variable_references[key] | python | def variable_can_be_referenced(self, key):
"""Checks whether the value of the variable can be returned by reference
:param str key: Name of the variable
:return: True if value of variable can be returned by reference, False else
"""
key = str(key)
return key in self.__variable_references and self.__variable_references[key] | [
"def",
"variable_can_be_referenced",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"str",
"(",
"key",
")",
"return",
"key",
"in",
"self",
".",
"__variable_references",
"and",
"self",
".",
"__variable_references",
"[",
"key",
"]"
] | Checks whether the value of the variable can be returned by reference
:param str key: Name of the variable
:return: True if value of variable can be returned by reference, False else | [
"Checks",
"whether",
"the",
"value",
"of",
"the",
"variable",
"can",
"be",
"returned",
"by",
"reference"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L149-L156 | train | 40,203 |
DLR-RM/RAFCON | source/rafcon/core/global_variable_manager.py | GlobalVariableManager.delete_variable | def delete_variable(self, key):
"""Deletes a global variable
:param key: the key of the global variable to be deleted
:raises exceptions.AttributeError: if the global variable does not exist
"""
key = str(key)
if self.is_locked(key):
raise RuntimeError("Global variable is locked")
with self.__global_lock:
if key in self.__global_variable_dictionary:
access_key = self.lock_variable(key, block=True)
del self.__global_variable_dictionary[key]
self.unlock_variable(key, access_key)
del self.__variable_locks[key]
del self.__variable_references[key]
else:
raise AttributeError("Global variable %s does not exist!" % str(key))
logger.debug("Global variable %s was deleted!" % str(key)) | python | def delete_variable(self, key):
"""Deletes a global variable
:param key: the key of the global variable to be deleted
:raises exceptions.AttributeError: if the global variable does not exist
"""
key = str(key)
if self.is_locked(key):
raise RuntimeError("Global variable is locked")
with self.__global_lock:
if key in self.__global_variable_dictionary:
access_key = self.lock_variable(key, block=True)
del self.__global_variable_dictionary[key]
self.unlock_variable(key, access_key)
del self.__variable_locks[key]
del self.__variable_references[key]
else:
raise AttributeError("Global variable %s does not exist!" % str(key))
logger.debug("Global variable %s was deleted!" % str(key)) | [
"def",
"delete_variable",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"str",
"(",
"key",
")",
"if",
"self",
".",
"is_locked",
"(",
"key",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Global variable is locked\"",
")",
"with",
"self",
".",
"__global_lock",... | Deletes a global variable
:param key: the key of the global variable to be deleted
:raises exceptions.AttributeError: if the global variable does not exist | [
"Deletes",
"a",
"global",
"variable"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L159-L179 | train | 40,204 |
DLR-RM/RAFCON | source/rafcon/core/global_variable_manager.py | GlobalVariableManager.lock_variable | def lock_variable(self, key, block=False):
"""Locks a global variable
:param key: the key of the global variable to be locked
:param block: a flag to specify if to wait for locking the variable in blocking mode
"""
key = str(key)
# watch out for releasing the __dictionary_lock properly
try:
if key in self.__variable_locks:
# acquire without arguments is blocking
lock_successful = self.__variable_locks[key].acquire(False)
if lock_successful or block:
if (not lock_successful) and block: # case: lock could not be acquired => wait for it as block=True
duration = 0.
loop_time = 0.1
while not self.__variable_locks[key].acquire(False):
time.sleep(loop_time)
duration += loop_time
if int(duration*10) % 20 == 0:
# while loops informs the user about long locked variables
logger.verbose("Variable '{2}' is locked and thread {0} waits already {1} seconds to "
"access it.".format(currentThread(), duration, key))
access_key = global_variable_id_generator()
self.__access_keys[key] = access_key
return access_key
else:
logger.warning("Global variable {} already locked".format(str(key)))
return False
else:
logger.error("Global variable key {} does not exist".format(str(key)))
return False
except Exception as e:
logger.error("Exception thrown: {}".format(str(e)))
return False | python | def lock_variable(self, key, block=False):
"""Locks a global variable
:param key: the key of the global variable to be locked
:param block: a flag to specify if to wait for locking the variable in blocking mode
"""
key = str(key)
# watch out for releasing the __dictionary_lock properly
try:
if key in self.__variable_locks:
# acquire without arguments is blocking
lock_successful = self.__variable_locks[key].acquire(False)
if lock_successful or block:
if (not lock_successful) and block: # case: lock could not be acquired => wait for it as block=True
duration = 0.
loop_time = 0.1
while not self.__variable_locks[key].acquire(False):
time.sleep(loop_time)
duration += loop_time
if int(duration*10) % 20 == 0:
# while loops informs the user about long locked variables
logger.verbose("Variable '{2}' is locked and thread {0} waits already {1} seconds to "
"access it.".format(currentThread(), duration, key))
access_key = global_variable_id_generator()
self.__access_keys[key] = access_key
return access_key
else:
logger.warning("Global variable {} already locked".format(str(key)))
return False
else:
logger.error("Global variable key {} does not exist".format(str(key)))
return False
except Exception as e:
logger.error("Exception thrown: {}".format(str(e)))
return False | [
"def",
"lock_variable",
"(",
"self",
",",
"key",
",",
"block",
"=",
"False",
")",
":",
"key",
"=",
"str",
"(",
"key",
")",
"# watch out for releasing the __dictionary_lock properly",
"try",
":",
"if",
"key",
"in",
"self",
".",
"__variable_locks",
":",
"# acqui... | Locks a global variable
:param key: the key of the global variable to be locked
:param block: a flag to specify if to wait for locking the variable in blocking mode | [
"Locks",
"a",
"global",
"variable"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L182-L216 | train | 40,205 |
DLR-RM/RAFCON | source/rafcon/core/global_variable_manager.py | GlobalVariableManager.unlock_variable | def unlock_variable(self, key, access_key, force=False):
"""Unlocks a global variable
:param key: the key of the global variable to be unlocked
:param access_key: the access key to be able to unlock the global variable
:param force: if the variable should be unlocked forcefully
:raises exceptions.AttributeError: if the global variable does not exist
:raises exceptions.RuntimeError: if the wrong access key is passed
"""
key = str(key)
if self.__access_keys[key] == access_key or force:
if key in self.__variable_locks:
if self.is_locked(key):
self.__variable_locks[key].release()
return True
else:
logger.error("Global variable {} is not locked, thus cannot unlock it".format(str(key)))
return False
else:
raise AttributeError("Global variable %s does not exist!" % str(key))
else:
raise RuntimeError("Wrong access key for accessing global variable") | python | def unlock_variable(self, key, access_key, force=False):
"""Unlocks a global variable
:param key: the key of the global variable to be unlocked
:param access_key: the access key to be able to unlock the global variable
:param force: if the variable should be unlocked forcefully
:raises exceptions.AttributeError: if the global variable does not exist
:raises exceptions.RuntimeError: if the wrong access key is passed
"""
key = str(key)
if self.__access_keys[key] == access_key or force:
if key in self.__variable_locks:
if self.is_locked(key):
self.__variable_locks[key].release()
return True
else:
logger.error("Global variable {} is not locked, thus cannot unlock it".format(str(key)))
return False
else:
raise AttributeError("Global variable %s does not exist!" % str(key))
else:
raise RuntimeError("Wrong access key for accessing global variable") | [
"def",
"unlock_variable",
"(",
"self",
",",
"key",
",",
"access_key",
",",
"force",
"=",
"False",
")",
":",
"key",
"=",
"str",
"(",
"key",
")",
"if",
"self",
".",
"__access_keys",
"[",
"key",
"]",
"==",
"access_key",
"or",
"force",
":",
"if",
"key",
... | Unlocks a global variable
:param key: the key of the global variable to be unlocked
:param access_key: the access key to be able to unlock the global variable
:param force: if the variable should be unlocked forcefully
:raises exceptions.AttributeError: if the global variable does not exist
:raises exceptions.RuntimeError: if the wrong access key is passed | [
"Unlocks",
"a",
"global",
"variable"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L219-L240 | train | 40,206 |
DLR-RM/RAFCON | source/rafcon/core/global_variable_manager.py | GlobalVariableManager.set_locked_variable | def set_locked_variable(self, key, access_key, value):
"""Set an already locked global variable
:param key: the key of the global variable to be set
:param access_key: the access key to the already locked global variable
:param value: the new value of the global variable
"""
return self.set_variable(key, value, per_reference=False, access_key=access_key) | python | def set_locked_variable(self, key, access_key, value):
"""Set an already locked global variable
:param key: the key of the global variable to be set
:param access_key: the access key to the already locked global variable
:param value: the new value of the global variable
"""
return self.set_variable(key, value, per_reference=False, access_key=access_key) | [
"def",
"set_locked_variable",
"(",
"self",
",",
"key",
",",
"access_key",
",",
"value",
")",
":",
"return",
"self",
".",
"set_variable",
"(",
"key",
",",
"value",
",",
"per_reference",
"=",
"False",
",",
"access_key",
"=",
"access_key",
")"
] | Set an already locked global variable
:param key: the key of the global variable to be set
:param access_key: the access key to the already locked global variable
:param value: the new value of the global variable | [
"Set",
"an",
"already",
"locked",
"global",
"variable"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L243-L250 | train | 40,207 |
DLR-RM/RAFCON | source/rafcon/core/global_variable_manager.py | GlobalVariableManager.get_locked_variable | def get_locked_variable(self, key, access_key):
"""Returns the value of an global variable that is already locked
:param key: the key of the global variable
:param access_key: the access_key to the global variable that is already locked
"""
return self.get_variable(key, per_reference=False, access_key=access_key) | python | def get_locked_variable(self, key, access_key):
"""Returns the value of an global variable that is already locked
:param key: the key of the global variable
:param access_key: the access_key to the global variable that is already locked
"""
return self.get_variable(key, per_reference=False, access_key=access_key) | [
"def",
"get_locked_variable",
"(",
"self",
",",
"key",
",",
"access_key",
")",
":",
"return",
"self",
".",
"get_variable",
"(",
"key",
",",
"per_reference",
"=",
"False",
",",
"access_key",
"=",
"access_key",
")"
] | Returns the value of an global variable that is already locked
:param key: the key of the global variable
:param access_key: the access_key to the global variable that is already locked | [
"Returns",
"the",
"value",
"of",
"an",
"global",
"variable",
"that",
"is",
"already",
"locked"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L252-L258 | train | 40,208 |
DLR-RM/RAFCON | source/rafcon/core/global_variable_manager.py | GlobalVariableManager.is_locked | def is_locked(self, key):
"""Returns the status of the lock of a global variable
:param key: the unique key of the global variable
:return:
"""
key = str(key)
if key in self.__variable_locks:
return self.__variable_locks[key].locked()
return False | python | def is_locked(self, key):
"""Returns the status of the lock of a global variable
:param key: the unique key of the global variable
:return:
"""
key = str(key)
if key in self.__variable_locks:
return self.__variable_locks[key].locked()
return False | [
"def",
"is_locked",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"str",
"(",
"key",
")",
"if",
"key",
"in",
"self",
".",
"__variable_locks",
":",
"return",
"self",
".",
"__variable_locks",
"[",
"key",
"]",
".",
"locked",
"(",
")",
"return",
"False"... | Returns the status of the lock of a global variable
:param key: the unique key of the global variable
:return: | [
"Returns",
"the",
"status",
"of",
"the",
"lock",
"of",
"a",
"global",
"variable"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L278-L287 | train | 40,209 |
DLR-RM/RAFCON | source/rafcon/core/global_variable_manager.py | GlobalVariableManager.global_variable_dictionary | def global_variable_dictionary(self):
"""Property for the _global_variable_dictionary field"""
dict_copy = {}
for key, value in self.__global_variable_dictionary.items():
if key in self.__variable_references and self.__variable_references[key]:
dict_copy[key] = value
else:
dict_copy[key] = copy.deepcopy(value)
return dict_copy | python | def global_variable_dictionary(self):
"""Property for the _global_variable_dictionary field"""
dict_copy = {}
for key, value in self.__global_variable_dictionary.items():
if key in self.__variable_references and self.__variable_references[key]:
dict_copy[key] = value
else:
dict_copy[key] = copy.deepcopy(value)
return dict_copy | [
"def",
"global_variable_dictionary",
"(",
"self",
")",
":",
"dict_copy",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__global_variable_dictionary",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
".",
"__variable_references",
"and"... | Property for the _global_variable_dictionary field | [
"Property",
"for",
"the",
"_global_variable_dictionary",
"field"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L310-L319 | train | 40,210 |
DLR-RM/RAFCON | source/rafcon/core/global_variable_manager.py | GlobalVariableManager.check_value_and_type | def check_value_and_type(value, data_type):
"""Checks if a given value is of a specific type
:param value: the value to check
:param data_type: the type to be checked upon
:return:
"""
if value is not None and data_type is not type(None):
# if not isinstance(value, data_type):
if not type_inherits_of_type(data_type, type(value)):
raise TypeError(
"Value: '{0}' is not of data type: '{1}', value type: {2}".format(value, data_type, type(value))) | python | def check_value_and_type(value, data_type):
"""Checks if a given value is of a specific type
:param value: the value to check
:param data_type: the type to be checked upon
:return:
"""
if value is not None and data_type is not type(None):
# if not isinstance(value, data_type):
if not type_inherits_of_type(data_type, type(value)):
raise TypeError(
"Value: '{0}' is not of data type: '{1}', value type: {2}".format(value, data_type, type(value))) | [
"def",
"check_value_and_type",
"(",
"value",
",",
"data_type",
")",
":",
"if",
"value",
"is",
"not",
"None",
"and",
"data_type",
"is",
"not",
"type",
"(",
"None",
")",
":",
"# if not isinstance(value, data_type):",
"if",
"not",
"type_inherits_of_type",
"(",
"dat... | Checks if a given value is of a specific type
:param value: the value to check
:param data_type: the type to be checked upon
:return: | [
"Checks",
"if",
"a",
"given",
"value",
"is",
"of",
"a",
"specific",
"type"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L341-L352 | train | 40,211 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/connector.py | RectanglePointPort.glue | def glue(self, pos):
"""Calculates the distance between the given position and the port
:param (float, float) pos: Distance to this position is calculated
:return: Distance to port
:rtype: float
"""
# Distance between border of rectangle and point
# Equation from http://stackoverflow.com/a/18157551/3568069
dx = max(self.point.x - self.width / 2. - pos[0], 0, pos[0] - (self.point.x + self.width / 2.))
dy = max(self.point.y - self.height / 2. - pos[1], 0, pos[1] - (self.point.y + self.height / 2.))
dist = sqrt(dx*dx + dy*dy)
return self.point, dist | python | def glue(self, pos):
"""Calculates the distance between the given position and the port
:param (float, float) pos: Distance to this position is calculated
:return: Distance to port
:rtype: float
"""
# Distance between border of rectangle and point
# Equation from http://stackoverflow.com/a/18157551/3568069
dx = max(self.point.x - self.width / 2. - pos[0], 0, pos[0] - (self.point.x + self.width / 2.))
dy = max(self.point.y - self.height / 2. - pos[1], 0, pos[1] - (self.point.y + self.height / 2.))
dist = sqrt(dx*dx + dy*dy)
return self.point, dist | [
"def",
"glue",
"(",
"self",
",",
"pos",
")",
":",
"# Distance between border of rectangle and point",
"# Equation from http://stackoverflow.com/a/18157551/3568069",
"dx",
"=",
"max",
"(",
"self",
".",
"point",
".",
"x",
"-",
"self",
".",
"width",
"/",
"2.",
"-",
"... | Calculates the distance between the given position and the port
:param (float, float) pos: Distance to this position is calculated
:return: Distance to port
:rtype: float | [
"Calculates",
"the",
"distance",
"between",
"the",
"given",
"position",
"and",
"the",
"port"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/connector.py#L43-L55 | train | 40,212 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController.on_preliminary_config_changed | def on_preliminary_config_changed(self, config_m, prop_name, info):
"""Callback when a preliminary config value has been changed
Mainly collects information, delegates handling further to _handle_config_update
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'preliminary_config'
:param dict info: Information e.g. about the changed config key
"""
self.check_for_preliminary_config()
method_name = info['method_name'] # __setitem__, __delitem__, clear, ...
if method_name in ['__setitem__', '__delitem__']:
config_key = info['args'][0]
self._handle_config_update(config_m, config_key)
# Probably the preliminary config has been cleared, update corresponding list stores
elif config_m is self.core_config_model:
self.update_core_config_list_store()
self.update_libraries_list_store()
else:
self.update_gui_config_list_store()
self.update_shortcut_settings() | python | def on_preliminary_config_changed(self, config_m, prop_name, info):
"""Callback when a preliminary config value has been changed
Mainly collects information, delegates handling further to _handle_config_update
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'preliminary_config'
:param dict info: Information e.g. about the changed config key
"""
self.check_for_preliminary_config()
method_name = info['method_name'] # __setitem__, __delitem__, clear, ...
if method_name in ['__setitem__', '__delitem__']:
config_key = info['args'][0]
self._handle_config_update(config_m, config_key)
# Probably the preliminary config has been cleared, update corresponding list stores
elif config_m is self.core_config_model:
self.update_core_config_list_store()
self.update_libraries_list_store()
else:
self.update_gui_config_list_store()
self.update_shortcut_settings() | [
"def",
"on_preliminary_config_changed",
"(",
"self",
",",
"config_m",
",",
"prop_name",
",",
"info",
")",
":",
"self",
".",
"check_for_preliminary_config",
"(",
")",
"method_name",
"=",
"info",
"[",
"'method_name'",
"]",
"# __setitem__, __delitem__, clear, ...",
"if",... | Callback when a preliminary config value has been changed
Mainly collects information, delegates handling further to _handle_config_update
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'preliminary_config'
:param dict info: Information e.g. about the changed config key | [
"Callback",
"when",
"a",
"preliminary",
"config",
"value",
"has",
"been",
"changed"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L136-L158 | train | 40,213 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._handle_config_update | def _handle_config_update(self, config_m, config_key):
"""Handles changes in config values
The method ensure that the correct list stores are updated with the new values.
:param ConfigModel config_m: The config model that has been changed
:param config_key: The config key who's value has been changed
:return:
"""
if config_key == "LIBRARY_PATHS":
self.update_libraries_list_store()
if config_key == "SHORTCUTS":
self.update_shortcut_settings()
else:
self.update_config_value(config_m, config_key) | python | def _handle_config_update(self, config_m, config_key):
"""Handles changes in config values
The method ensure that the correct list stores are updated with the new values.
:param ConfigModel config_m: The config model that has been changed
:param config_key: The config key who's value has been changed
:return:
"""
if config_key == "LIBRARY_PATHS":
self.update_libraries_list_store()
if config_key == "SHORTCUTS":
self.update_shortcut_settings()
else:
self.update_config_value(config_m, config_key) | [
"def",
"_handle_config_update",
"(",
"self",
",",
"config_m",
",",
"config_key",
")",
":",
"if",
"config_key",
"==",
"\"LIBRARY_PATHS\"",
":",
"self",
".",
"update_libraries_list_store",
"(",
")",
"if",
"config_key",
"==",
"\"SHORTCUTS\"",
":",
"self",
".",
"upd... | Handles changes in config values
The method ensure that the correct list stores are updated with the new values.
:param ConfigModel config_m: The config model that has been changed
:param config_key: The config key who's value has been changed
:return: | [
"Handles",
"changes",
"in",
"config",
"values"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L160-L175 | train | 40,214 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController.update_all | def update_all(self):
"""Shorthand method to update all collection information
"""
self.update_path_labels()
self.update_core_config_list_store()
self.update_gui_config_list_store()
self.update_libraries_list_store()
self.update_shortcut_settings()
self.check_for_preliminary_config() | python | def update_all(self):
"""Shorthand method to update all collection information
"""
self.update_path_labels()
self.update_core_config_list_store()
self.update_gui_config_list_store()
self.update_libraries_list_store()
self.update_shortcut_settings()
self.check_for_preliminary_config() | [
"def",
"update_all",
"(",
"self",
")",
":",
"self",
".",
"update_path_labels",
"(",
")",
"self",
".",
"update_core_config_list_store",
"(",
")",
"self",
".",
"update_gui_config_list_store",
"(",
")",
"self",
".",
"update_libraries_list_store",
"(",
")",
"self",
... | Shorthand method to update all collection information | [
"Shorthand",
"method",
"to",
"update",
"all",
"collection",
"information"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L177-L185 | train | 40,215 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController.check_for_preliminary_config | def check_for_preliminary_config(self):
"""Activates the 'Apply' button if there are preliminary changes
"""
if any([self.model.preliminary_config, self.gui_config_model.preliminary_config]):
self.view['apply_button'].set_sensitive(True)
else:
self.view['apply_button'].set_sensitive(False) | python | def check_for_preliminary_config(self):
"""Activates the 'Apply' button if there are preliminary changes
"""
if any([self.model.preliminary_config, self.gui_config_model.preliminary_config]):
self.view['apply_button'].set_sensitive(True)
else:
self.view['apply_button'].set_sensitive(False) | [
"def",
"check_for_preliminary_config",
"(",
"self",
")",
":",
"if",
"any",
"(",
"[",
"self",
".",
"model",
".",
"preliminary_config",
",",
"self",
".",
"gui_config_model",
".",
"preliminary_config",
"]",
")",
":",
"self",
".",
"view",
"[",
"'apply_button'",
... | Activates the 'Apply' button if there are preliminary changes | [
"Activates",
"the",
"Apply",
"button",
"if",
"there",
"are",
"preliminary",
"changes"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L187-L193 | train | 40,216 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController.update_path_labels | def update_path_labels(self):
"""Update labels showing config paths
"""
self.view['core_label'].set_text("Core Config Path: " + str(self.core_config_model.config.config_file_path))
self.view['gui_label'].set_text("GUI Config Path: " + str(self.gui_config_model.config.config_file_path)) | python | def update_path_labels(self):
"""Update labels showing config paths
"""
self.view['core_label'].set_text("Core Config Path: " + str(self.core_config_model.config.config_file_path))
self.view['gui_label'].set_text("GUI Config Path: " + str(self.gui_config_model.config.config_file_path)) | [
"def",
"update_path_labels",
"(",
"self",
")",
":",
"self",
".",
"view",
"[",
"'core_label'",
"]",
".",
"set_text",
"(",
"\"Core Config Path: \"",
"+",
"str",
"(",
"self",
".",
"core_config_model",
".",
"config",
".",
"config_file_path",
")",
")",
"self",
".... | Update labels showing config paths | [
"Update",
"labels",
"showing",
"config",
"paths"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L195-L199 | train | 40,217 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController.update_config_value | def update_config_value(self, config_m, config_key):
"""Updates the corresponding list store of a changed config value
:param ConfigModel config_m: The config model that has been changed
:param str config_key: The config key who's value has been changed
"""
config_value = config_m.get_current_config_value(config_key)
if config_m is self.core_config_model:
list_store = self.core_list_store
elif config_m is self.gui_config_model:
list_store = self.gui_list_store
else:
return
self._update_list_store_entry(list_store, config_key, config_value) | python | def update_config_value(self, config_m, config_key):
"""Updates the corresponding list store of a changed config value
:param ConfigModel config_m: The config model that has been changed
:param str config_key: The config key who's value has been changed
"""
config_value = config_m.get_current_config_value(config_key)
if config_m is self.core_config_model:
list_store = self.core_list_store
elif config_m is self.gui_config_model:
list_store = self.gui_list_store
else:
return
self._update_list_store_entry(list_store, config_key, config_value) | [
"def",
"update_config_value",
"(",
"self",
",",
"config_m",
",",
"config_key",
")",
":",
"config_value",
"=",
"config_m",
".",
"get_current_config_value",
"(",
"config_key",
")",
"if",
"config_m",
"is",
"self",
".",
"core_config_model",
":",
"list_store",
"=",
"... | Updates the corresponding list store of a changed config value
:param ConfigModel config_m: The config model that has been changed
:param str config_key: The config key who's value has been changed | [
"Updates",
"the",
"corresponding",
"list",
"store",
"of",
"a",
"changed",
"config",
"value"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L201-L214 | train | 40,218 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._update_list_store_entry | def _update_list_store_entry(self, list_store, config_key, config_value):
"""Helper method to update a list store
:param Gtk.ListStore list_store: List store to be updated
:param str config_key: Config key to search for
:param config_value: New config value
:returns: Row of list store that has been updated
:rtype: int
"""
for row_num, row in enumerate(list_store):
if row[self.KEY_STORAGE_ID] == config_key:
row[self.VALUE_STORAGE_ID] = str(config_value)
row[self.TOGGLE_VALUE_STORAGE_ID] = config_value
return row_num | python | def _update_list_store_entry(self, list_store, config_key, config_value):
"""Helper method to update a list store
:param Gtk.ListStore list_store: List store to be updated
:param str config_key: Config key to search for
:param config_value: New config value
:returns: Row of list store that has been updated
:rtype: int
"""
for row_num, row in enumerate(list_store):
if row[self.KEY_STORAGE_ID] == config_key:
row[self.VALUE_STORAGE_ID] = str(config_value)
row[self.TOGGLE_VALUE_STORAGE_ID] = config_value
return row_num | [
"def",
"_update_list_store_entry",
"(",
"self",
",",
"list_store",
",",
"config_key",
",",
"config_value",
")",
":",
"for",
"row_num",
",",
"row",
"in",
"enumerate",
"(",
"list_store",
")",
":",
"if",
"row",
"[",
"self",
".",
"KEY_STORAGE_ID",
"]",
"==",
"... | Helper method to update a list store
:param Gtk.ListStore list_store: List store to be updated
:param str config_key: Config key to search for
:param config_value: New config value
:returns: Row of list store that has been updated
:rtype: int | [
"Helper",
"method",
"to",
"update",
"a",
"list",
"store"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L216-L229 | train | 40,219 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._update_list_store | def _update_list_store(config_m, list_store, ignore_keys=None):
"""Generic method to create list store for a given config model
:param ConfigModel config_m: Config model to read into list store
:param Gtk.ListStore list_store: List store to be filled
:param list ignore_keys: List of keys that should be ignored
"""
ignore_keys = [] if ignore_keys is None else ignore_keys
list_store.clear()
for config_key in sorted(config_m.config.keys):
if config_key in ignore_keys:
continue
config_value = config_m.get_current_config_value(config_key)
# (config_key, text, text_visible, toggle_activatable, toggle_visible, text_editable, toggle_state)
if isinstance(config_value, bool):
list_store.append((str(config_key), str(config_value), False, True, True, False, config_value))
else:
list_store.append((str(config_key), str(config_value), True, False, False, True, config_value)) | python | def _update_list_store(config_m, list_store, ignore_keys=None):
"""Generic method to create list store for a given config model
:param ConfigModel config_m: Config model to read into list store
:param Gtk.ListStore list_store: List store to be filled
:param list ignore_keys: List of keys that should be ignored
"""
ignore_keys = [] if ignore_keys is None else ignore_keys
list_store.clear()
for config_key in sorted(config_m.config.keys):
if config_key in ignore_keys:
continue
config_value = config_m.get_current_config_value(config_key)
# (config_key, text, text_visible, toggle_activatable, toggle_visible, text_editable, toggle_state)
if isinstance(config_value, bool):
list_store.append((str(config_key), str(config_value), False, True, True, False, config_value))
else:
list_store.append((str(config_key), str(config_value), True, False, False, True, config_value)) | [
"def",
"_update_list_store",
"(",
"config_m",
",",
"list_store",
",",
"ignore_keys",
"=",
"None",
")",
":",
"ignore_keys",
"=",
"[",
"]",
"if",
"ignore_keys",
"is",
"None",
"else",
"ignore_keys",
"list_store",
".",
"clear",
"(",
")",
"for",
"config_key",
"in... | Generic method to create list store for a given config model
:param ConfigModel config_m: Config model to read into list store
:param Gtk.ListStore list_store: List store to be filled
:param list ignore_keys: List of keys that should be ignored | [
"Generic",
"method",
"to",
"create",
"list",
"store",
"for",
"a",
"given",
"config",
"model"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L232-L249 | train | 40,220 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController.update_libraries_list_store | def update_libraries_list_store(self):
"""Creates the list store for the libraries
"""
self.library_list_store.clear()
libraries = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True, default={})
library_names = sorted(libraries.keys())
for library_name in library_names:
library_path = libraries[library_name]
self.library_list_store.append((library_name, library_path)) | python | def update_libraries_list_store(self):
"""Creates the list store for the libraries
"""
self.library_list_store.clear()
libraries = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True, default={})
library_names = sorted(libraries.keys())
for library_name in library_names:
library_path = libraries[library_name]
self.library_list_store.append((library_name, library_path)) | [
"def",
"update_libraries_list_store",
"(",
"self",
")",
":",
"self",
".",
"library_list_store",
".",
"clear",
"(",
")",
"libraries",
"=",
"self",
".",
"core_config_model",
".",
"get_current_config_value",
"(",
"\"LIBRARY_PATHS\"",
",",
"use_preliminary",
"=",
"True"... | Creates the list store for the libraries | [
"Creates",
"the",
"list",
"store",
"for",
"the",
"libraries"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L261-L269 | train | 40,221 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController.update_shortcut_settings | def update_shortcut_settings(self):
"""Creates the list store for the shortcuts
"""
self.shortcut_list_store.clear()
shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True, default={})
actions = sorted(shortcuts.keys())
for action in actions:
keys = shortcuts[action]
self.shortcut_list_store.append((str(action), str(keys))) | python | def update_shortcut_settings(self):
"""Creates the list store for the shortcuts
"""
self.shortcut_list_store.clear()
shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True, default={})
actions = sorted(shortcuts.keys())
for action in actions:
keys = shortcuts[action]
self.shortcut_list_store.append((str(action), str(keys))) | [
"def",
"update_shortcut_settings",
"(",
"self",
")",
":",
"self",
".",
"shortcut_list_store",
".",
"clear",
"(",
")",
"shortcuts",
"=",
"self",
".",
"gui_config_model",
".",
"get_current_config_value",
"(",
"\"SHORTCUTS\"",
",",
"use_preliminary",
"=",
"True",
","... | Creates the list store for the shortcuts | [
"Creates",
"the",
"list",
"store",
"for",
"the",
"shortcuts"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L271-L279 | train | 40,222 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._select_row_by_column_value | def _select_row_by_column_value(tree_view, list_store, column, value):
"""Helper method to select a tree view row
:param Gtk.TreeView tree_view: Tree view who's row is to be selected
:param Gtk.ListStore list_store: List store of the tree view
:param int column: Column in which the value is searched
:param value: Value to search for
:returns: Row of list store that has selected
:rtype: int
"""
for row_num, iter_elem in enumerate(list_store):
if iter_elem[column] == value:
tree_view.set_cursor(row_num)
return row_num | python | def _select_row_by_column_value(tree_view, list_store, column, value):
"""Helper method to select a tree view row
:param Gtk.TreeView tree_view: Tree view who's row is to be selected
:param Gtk.ListStore list_store: List store of the tree view
:param int column: Column in which the value is searched
:param value: Value to search for
:returns: Row of list store that has selected
:rtype: int
"""
for row_num, iter_elem in enumerate(list_store):
if iter_elem[column] == value:
tree_view.set_cursor(row_num)
return row_num | [
"def",
"_select_row_by_column_value",
"(",
"tree_view",
",",
"list_store",
",",
"column",
",",
"value",
")",
":",
"for",
"row_num",
",",
"iter_elem",
"in",
"enumerate",
"(",
"list_store",
")",
":",
"if",
"iter_elem",
"[",
"column",
"]",
"==",
"value",
":",
... | Helper method to select a tree view row
:param Gtk.TreeView tree_view: Tree view who's row is to be selected
:param Gtk.ListStore list_store: List store of the tree view
:param int column: Column in which the value is searched
:param value: Value to search for
:returns: Row of list store that has selected
:rtype: int | [
"Helper",
"method",
"to",
"select",
"a",
"tree",
"view",
"row"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L282-L295 | train | 40,223 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._on_add_library | def _on_add_library(self, *event):
"""Callback method handling the addition of a new library
"""
self.view['library_tree_view'].grab_focus()
if react_to_event(self.view, self.view['library_tree_view'], event):
temp_library_name = "<LIB_NAME_%s>" % self._lib_counter
self._lib_counter += 1
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
library_config[temp_library_name] = "<LIB_PATH>"
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
self._select_row_by_column_value(self.view['library_tree_view'], self.library_list_store,
self.KEY_STORAGE_ID, temp_library_name)
return True | python | def _on_add_library(self, *event):
"""Callback method handling the addition of a new library
"""
self.view['library_tree_view'].grab_focus()
if react_to_event(self.view, self.view['library_tree_view'], event):
temp_library_name = "<LIB_NAME_%s>" % self._lib_counter
self._lib_counter += 1
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
library_config[temp_library_name] = "<LIB_PATH>"
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
self._select_row_by_column_value(self.view['library_tree_view'], self.library_list_store,
self.KEY_STORAGE_ID, temp_library_name)
return True | [
"def",
"_on_add_library",
"(",
"self",
",",
"*",
"event",
")",
":",
"self",
".",
"view",
"[",
"'library_tree_view'",
"]",
".",
"grab_focus",
"(",
")",
"if",
"react_to_event",
"(",
"self",
".",
"view",
",",
"self",
".",
"view",
"[",
"'library_tree_view'",
... | Callback method handling the addition of a new library | [
"Callback",
"method",
"handling",
"the",
"addition",
"of",
"a",
"new",
"library"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L297-L310 | train | 40,224 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._on_remove_library | def _on_remove_library(self, *event):
"""Callback method handling the removal of an existing library
"""
self.view['library_tree_view'].grab_focus()
if react_to_event(self.view, self.view['library_tree_view'], event):
path = self.view["library_tree_view"].get_cursor()[0]
if path is not None:
library_name = self.library_list_store[int(path[0])][0]
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
del library_config[library_name]
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
if len(self.library_list_store) > 0:
self.view['library_tree_view'].set_cursor(min(path[0], len(self.library_list_store) - 1))
return True | python | def _on_remove_library(self, *event):
"""Callback method handling the removal of an existing library
"""
self.view['library_tree_view'].grab_focus()
if react_to_event(self.view, self.view['library_tree_view'], event):
path = self.view["library_tree_view"].get_cursor()[0]
if path is not None:
library_name = self.library_list_store[int(path[0])][0]
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
del library_config[library_name]
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
if len(self.library_list_store) > 0:
self.view['library_tree_view'].set_cursor(min(path[0], len(self.library_list_store) - 1))
return True | [
"def",
"_on_remove_library",
"(",
"self",
",",
"*",
"event",
")",
":",
"self",
".",
"view",
"[",
"'library_tree_view'",
"]",
".",
"grab_focus",
"(",
")",
"if",
"react_to_event",
"(",
"self",
".",
"view",
",",
"self",
".",
"view",
"[",
"'library_tree_view'"... | Callback method handling the removal of an existing library | [
"Callback",
"method",
"handling",
"the",
"removal",
"of",
"an",
"existing",
"library"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L312-L326 | train | 40,225 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._on_checkbox_toggled | def _on_checkbox_toggled(self, renderer, path, config_m, config_list_store):
"""Callback method handling a config toggle event
:param Gtk.CellRenderer renderer: Cell renderer that has been toggled
:param path: Path within the list store
:param ConfigModel config_m: The config model related to the toggle option
:param Gtk.ListStore config_list_store: The list store related to the toggle option
"""
config_key = config_list_store[int(path)][self.KEY_STORAGE_ID]
config_value = bool(config_list_store[int(path)][self.TOGGLE_VALUE_STORAGE_ID])
config_value ^= True
config_m.set_preliminary_config_value(config_key, config_value) | python | def _on_checkbox_toggled(self, renderer, path, config_m, config_list_store):
"""Callback method handling a config toggle event
:param Gtk.CellRenderer renderer: Cell renderer that has been toggled
:param path: Path within the list store
:param ConfigModel config_m: The config model related to the toggle option
:param Gtk.ListStore config_list_store: The list store related to the toggle option
"""
config_key = config_list_store[int(path)][self.KEY_STORAGE_ID]
config_value = bool(config_list_store[int(path)][self.TOGGLE_VALUE_STORAGE_ID])
config_value ^= True
config_m.set_preliminary_config_value(config_key, config_value) | [
"def",
"_on_checkbox_toggled",
"(",
"self",
",",
"renderer",
",",
"path",
",",
"config_m",
",",
"config_list_store",
")",
":",
"config_key",
"=",
"config_list_store",
"[",
"int",
"(",
"path",
")",
"]",
"[",
"self",
".",
"KEY_STORAGE_ID",
"]",
"config_value",
... | Callback method handling a config toggle event
:param Gtk.CellRenderer renderer: Cell renderer that has been toggled
:param path: Path within the list store
:param ConfigModel config_m: The config model related to the toggle option
:param Gtk.ListStore config_list_store: The list store related to the toggle option | [
"Callback",
"method",
"handling",
"a",
"config",
"toggle",
"event"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L328-L339 | train | 40,226 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._on_import_config | def _on_import_config(self, *args):
"""Callback method the the import button was clicked
Shows a dialog allowing to import an existing configuration file
"""
def handle_import(dialog_text, path_name):
chooser = Gtk.FileChooserDialog(dialog_text, None,
Gtk.FileChooserAction.SAVE,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT))
chooser.set_current_folder(path_name)
response = chooser.run()
if response == Gtk.ResponseType.ACCEPT:
# get_filename() returns the whole file path inclusively the filename
config_file = chooser.get_filename()
config_path = dirname(config_file)
self._last_path = config_path
config_dict = yaml_configuration.config.load_dict_from_yaml(config_file)
config_type = config_dict.get("TYPE")
if config_type == "SM_CONFIG":
del config_dict["TYPE"]
self.core_config_model.update_config(config_dict, config_file)
logger.info("Imported Core Config from {0}".format(config_file))
elif config_type == "GUI_CONFIG":
del config_dict["TYPE"]
self.gui_config_model.update_config(config_dict, config_file)
logger.info("Imported GUI Config from {0}".format(config_file))
else:
logger.error("{0} is not a valid config file".format(config_file))
elif response == Gtk.ResponseType.CANCEL:
logger.info("Import of configuration cancelled")
chooser.destroy()
handle_import("Import Config Config from", self._last_path)
self.check_for_preliminary_config()
self.update_path_labels() | python | def _on_import_config(self, *args):
"""Callback method the the import button was clicked
Shows a dialog allowing to import an existing configuration file
"""
def handle_import(dialog_text, path_name):
chooser = Gtk.FileChooserDialog(dialog_text, None,
Gtk.FileChooserAction.SAVE,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT))
chooser.set_current_folder(path_name)
response = chooser.run()
if response == Gtk.ResponseType.ACCEPT:
# get_filename() returns the whole file path inclusively the filename
config_file = chooser.get_filename()
config_path = dirname(config_file)
self._last_path = config_path
config_dict = yaml_configuration.config.load_dict_from_yaml(config_file)
config_type = config_dict.get("TYPE")
if config_type == "SM_CONFIG":
del config_dict["TYPE"]
self.core_config_model.update_config(config_dict, config_file)
logger.info("Imported Core Config from {0}".format(config_file))
elif config_type == "GUI_CONFIG":
del config_dict["TYPE"]
self.gui_config_model.update_config(config_dict, config_file)
logger.info("Imported GUI Config from {0}".format(config_file))
else:
logger.error("{0} is not a valid config file".format(config_file))
elif response == Gtk.ResponseType.CANCEL:
logger.info("Import of configuration cancelled")
chooser.destroy()
handle_import("Import Config Config from", self._last_path)
self.check_for_preliminary_config()
self.update_path_labels() | [
"def",
"_on_import_config",
"(",
"self",
",",
"*",
"args",
")",
":",
"def",
"handle_import",
"(",
"dialog_text",
",",
"path_name",
")",
":",
"chooser",
"=",
"Gtk",
".",
"FileChooserDialog",
"(",
"dialog_text",
",",
"None",
",",
"Gtk",
".",
"FileChooserAction... | Callback method the the import button was clicked
Shows a dialog allowing to import an existing configuration file | [
"Callback",
"method",
"the",
"the",
"import",
"button",
"was",
"clicked"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L354-L390 | train | 40,227 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._on_export_config | def _on_export_config(self, *args):
"""Callback method the the export button was clicked
Shows dialogs allowing to export the configurations into separate files
"""
response = self._config_chooser_dialog("Export configuration",
"Please select the configuration file(s) to be exported:")
if response == Gtk.ResponseType.REJECT:
return
def handle_export(dialog_text, path, config_m):
chooser = Gtk.FileChooserDialog(dialog_text, None,
Gtk.FileChooserAction.SAVE,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_SAVE_AS, Gtk.ResponseType.ACCEPT))
chooser.set_current_folder(path)
response = chooser.run()
if response == Gtk.ResponseType.ACCEPT:
config_file = chooser.get_filename()
if not config_file:
logger.error("Configuration could not be exported! Invalid file name!")
else:
if ".yaml" not in config_file:
config_file += ".yaml"
if config_m.preliminary_config:
logger.warning("There are changes in the configuration that have not yet been applied. These "
"changes will not be exported.")
self._last_path = dirname(config_file)
config_dict = config_m.as_dict()
config_copy = yaml_configuration.config.DefaultConfig(str(config_dict))
config_copy.config_file_path = config_file
config_copy.path = self._last_path
try:
config_copy.save_configuration()
logger.info("Configuration exported to {}" .format(config_file))
except IOError:
logger.error("Cannot open file '{}' for writing".format(config_file))
elif response == Gtk.ResponseType.CANCEL:
logger.warning("Export Config canceled!")
chooser.destroy()
if self._core_checkbox.get_active():
handle_export("Select file for core configuration", self._last_path, self.core_config_model)
if self._gui_checkbox.get_active():
handle_export("Select file for GUI configuration.", self._last_path, self.gui_config_model) | python | def _on_export_config(self, *args):
"""Callback method the the export button was clicked
Shows dialogs allowing to export the configurations into separate files
"""
response = self._config_chooser_dialog("Export configuration",
"Please select the configuration file(s) to be exported:")
if response == Gtk.ResponseType.REJECT:
return
def handle_export(dialog_text, path, config_m):
chooser = Gtk.FileChooserDialog(dialog_text, None,
Gtk.FileChooserAction.SAVE,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_SAVE_AS, Gtk.ResponseType.ACCEPT))
chooser.set_current_folder(path)
response = chooser.run()
if response == Gtk.ResponseType.ACCEPT:
config_file = chooser.get_filename()
if not config_file:
logger.error("Configuration could not be exported! Invalid file name!")
else:
if ".yaml" not in config_file:
config_file += ".yaml"
if config_m.preliminary_config:
logger.warning("There are changes in the configuration that have not yet been applied. These "
"changes will not be exported.")
self._last_path = dirname(config_file)
config_dict = config_m.as_dict()
config_copy = yaml_configuration.config.DefaultConfig(str(config_dict))
config_copy.config_file_path = config_file
config_copy.path = self._last_path
try:
config_copy.save_configuration()
logger.info("Configuration exported to {}" .format(config_file))
except IOError:
logger.error("Cannot open file '{}' for writing".format(config_file))
elif response == Gtk.ResponseType.CANCEL:
logger.warning("Export Config canceled!")
chooser.destroy()
if self._core_checkbox.get_active():
handle_export("Select file for core configuration", self._last_path, self.core_config_model)
if self._gui_checkbox.get_active():
handle_export("Select file for GUI configuration.", self._last_path, self.gui_config_model) | [
"def",
"_on_export_config",
"(",
"self",
",",
"*",
"args",
")",
":",
"response",
"=",
"self",
".",
"_config_chooser_dialog",
"(",
"\"Export configuration\"",
",",
"\"Please select the configuration file(s) to be exported:\"",
")",
"if",
"response",
"==",
"Gtk",
".",
"... | Callback method the the export button was clicked
Shows dialogs allowing to export the configurations into separate files | [
"Callback",
"method",
"the",
"the",
"export",
"button",
"was",
"clicked"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L392-L437 | train | 40,228 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._on_library_name_changed | def _on_library_name_changed(self, renderer, path, new_library_name):
"""Callback handling a change of a library name
:param Gtk.CellRenderer renderer: Cell renderer showing the library name
:param path: Path of library within the list store
:param str new_library_name: New library name
"""
old_library_name = self.library_list_store[int(path)][self.KEY_STORAGE_ID]
if old_library_name == new_library_name:
return
library_path = self.library_list_store[int(path)][self.VALUE_STORAGE_ID]
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
del library_config[old_library_name]
library_config[new_library_name] = library_path
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
self._select_row_by_column_value(self.view['library_tree_view'], self.library_list_store,
self.KEY_STORAGE_ID, new_library_name) | python | def _on_library_name_changed(self, renderer, path, new_library_name):
"""Callback handling a change of a library name
:param Gtk.CellRenderer renderer: Cell renderer showing the library name
:param path: Path of library within the list store
:param str new_library_name: New library name
"""
old_library_name = self.library_list_store[int(path)][self.KEY_STORAGE_ID]
if old_library_name == new_library_name:
return
library_path = self.library_list_store[int(path)][self.VALUE_STORAGE_ID]
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
del library_config[old_library_name]
library_config[new_library_name] = library_path
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
self._select_row_by_column_value(self.view['library_tree_view'], self.library_list_store,
self.KEY_STORAGE_ID, new_library_name) | [
"def",
"_on_library_name_changed",
"(",
"self",
",",
"renderer",
",",
"path",
",",
"new_library_name",
")",
":",
"old_library_name",
"=",
"self",
".",
"library_list_store",
"[",
"int",
"(",
"path",
")",
"]",
"[",
"self",
".",
"KEY_STORAGE_ID",
"]",
"if",
"ol... | Callback handling a change of a library name
:param Gtk.CellRenderer renderer: Cell renderer showing the library name
:param path: Path of library within the list store
:param str new_library_name: New library name | [
"Callback",
"handling",
"a",
"change",
"of",
"a",
"library",
"name"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L494-L512 | train | 40,229 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._on_library_path_changed | def _on_library_path_changed(self, renderer, path, new_library_path):
"""Callback handling a change of a library path
:param Gtk.CellRenderer renderer: Cell renderer showing the library path
:param path: Path of library within the list store
:param str new_library_path: New library path
"""
library_name = self.library_list_store[int(path)][self.KEY_STORAGE_ID]
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
library_config[library_name] = new_library_path
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
self._select_row_by_column_value(self.view['library_tree_view'], self.library_list_store,
self.KEY_STORAGE_ID, library_name) | python | def _on_library_path_changed(self, renderer, path, new_library_path):
"""Callback handling a change of a library path
:param Gtk.CellRenderer renderer: Cell renderer showing the library path
:param path: Path of library within the list store
:param str new_library_path: New library path
"""
library_name = self.library_list_store[int(path)][self.KEY_STORAGE_ID]
library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
default={})
library_config[library_name] = new_library_path
self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
self._select_row_by_column_value(self.view['library_tree_view'], self.library_list_store,
self.KEY_STORAGE_ID, library_name) | [
"def",
"_on_library_path_changed",
"(",
"self",
",",
"renderer",
",",
"path",
",",
"new_library_path",
")",
":",
"library_name",
"=",
"self",
".",
"library_list_store",
"[",
"int",
"(",
"path",
")",
"]",
"[",
"self",
".",
"KEY_STORAGE_ID",
"]",
"library_config... | Callback handling a change of a library path
:param Gtk.CellRenderer renderer: Cell renderer showing the library path
:param path: Path of library within the list store
:param str new_library_path: New library path | [
"Callback",
"handling",
"a",
"change",
"of",
"a",
"library",
"path"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L514-L528 | train | 40,230 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._on_shortcut_changed | def _on_shortcut_changed(self, renderer, path, new_shortcuts):
"""Callback handling a change of a shortcut
:param Gtk.CellRenderer renderer: Cell renderer showing the shortcut
:param path: Path of shortcuts within the list store
:param str new_shortcuts: New shortcuts
"""
action = self.shortcut_list_store[int(path)][self.KEY_STORAGE_ID]
old_shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True)[action]
from ast import literal_eval
try:
new_shortcuts = literal_eval(new_shortcuts)
if not isinstance(new_shortcuts, list) and \
not all([isinstance(shortcut, string_types) for shortcut in new_shortcuts]):
raise ValueError()
except (ValueError, SyntaxError):
logger.warning("Shortcuts must be a list of strings")
new_shortcuts = old_shortcuts
shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True, default={})
shortcuts[action] = new_shortcuts
self.gui_config_model.set_preliminary_config_value("SHORTCUTS", shortcuts)
self._select_row_by_column_value(self.view['shortcut_tree_view'], self.shortcut_list_store,
self.KEY_STORAGE_ID, action) | python | def _on_shortcut_changed(self, renderer, path, new_shortcuts):
"""Callback handling a change of a shortcut
:param Gtk.CellRenderer renderer: Cell renderer showing the shortcut
:param path: Path of shortcuts within the list store
:param str new_shortcuts: New shortcuts
"""
action = self.shortcut_list_store[int(path)][self.KEY_STORAGE_ID]
old_shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True)[action]
from ast import literal_eval
try:
new_shortcuts = literal_eval(new_shortcuts)
if not isinstance(new_shortcuts, list) and \
not all([isinstance(shortcut, string_types) for shortcut in new_shortcuts]):
raise ValueError()
except (ValueError, SyntaxError):
logger.warning("Shortcuts must be a list of strings")
new_shortcuts = old_shortcuts
shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True, default={})
shortcuts[action] = new_shortcuts
self.gui_config_model.set_preliminary_config_value("SHORTCUTS", shortcuts)
self._select_row_by_column_value(self.view['shortcut_tree_view'], self.shortcut_list_store,
self.KEY_STORAGE_ID, action) | [
"def",
"_on_shortcut_changed",
"(",
"self",
",",
"renderer",
",",
"path",
",",
"new_shortcuts",
")",
":",
"action",
"=",
"self",
".",
"shortcut_list_store",
"[",
"int",
"(",
"path",
")",
"]",
"[",
"self",
".",
"KEY_STORAGE_ID",
"]",
"old_shortcuts",
"=",
"... | Callback handling a change of a shortcut
:param Gtk.CellRenderer renderer: Cell renderer showing the shortcut
:param path: Path of shortcuts within the list store
:param str new_shortcuts: New shortcuts | [
"Callback",
"handling",
"a",
"change",
"of",
"a",
"shortcut"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L530-L554 | train | 40,231 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._on_config_value_changed | def _on_config_value_changed(self, renderer, path, new_value, config_m, list_store):
"""Callback handling a change of a config value
:param Gtk.CellRenderer renderer: Cell renderer showing the shortcut
:param path: Path of shortcuts within the list store
:param ConfigModel config_m: The config model that is to be changed
:param Gtk.ListStore list_store: The list store that is to be changed
"""
config_key = list_store[int(path)][self.KEY_STORAGE_ID]
old_value = config_m.get_current_config_value(config_key, use_preliminary=True)
if old_value == new_value:
return
# Try to maintain the correct data type, which is extracted from the old value
if isinstance(old_value, bool):
if new_value in ["True", "true"]:
new_value = True
elif new_value in ["False", "false"]:
new_value = False
else:
logger.warning("'{}' must be a boolean value".format(config_key))
new_value = old_value
elif isinstance(old_value, (int, float)):
try:
new_value = int(new_value)
except ValueError:
try:
new_value = float(new_value)
except ValueError:
logger.warning("'{}' must be a numeric value".format(config_key))
new_value = old_value
config_m.set_preliminary_config_value(config_key, new_value) | python | def _on_config_value_changed(self, renderer, path, new_value, config_m, list_store):
"""Callback handling a change of a config value
:param Gtk.CellRenderer renderer: Cell renderer showing the shortcut
:param path: Path of shortcuts within the list store
:param ConfigModel config_m: The config model that is to be changed
:param Gtk.ListStore list_store: The list store that is to be changed
"""
config_key = list_store[int(path)][self.KEY_STORAGE_ID]
old_value = config_m.get_current_config_value(config_key, use_preliminary=True)
if old_value == new_value:
return
# Try to maintain the correct data type, which is extracted from the old value
if isinstance(old_value, bool):
if new_value in ["True", "true"]:
new_value = True
elif new_value in ["False", "false"]:
new_value = False
else:
logger.warning("'{}' must be a boolean value".format(config_key))
new_value = old_value
elif isinstance(old_value, (int, float)):
try:
new_value = int(new_value)
except ValueError:
try:
new_value = float(new_value)
except ValueError:
logger.warning("'{}' must be a numeric value".format(config_key))
new_value = old_value
config_m.set_preliminary_config_value(config_key, new_value) | [
"def",
"_on_config_value_changed",
"(",
"self",
",",
"renderer",
",",
"path",
",",
"new_value",
",",
"config_m",
",",
"list_store",
")",
":",
"config_key",
"=",
"list_store",
"[",
"int",
"(",
"path",
")",
"]",
"[",
"self",
".",
"KEY_STORAGE_ID",
"]",
"old_... | Callback handling a change of a config value
:param Gtk.CellRenderer renderer: Cell renderer showing the shortcut
:param path: Path of shortcuts within the list store
:param ConfigModel config_m: The config model that is to be changed
:param Gtk.ListStore list_store: The list store that is to be changed | [
"Callback",
"handling",
"a",
"change",
"of",
"a",
"config",
"value"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L556-L589 | train | 40,232 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/preferences_window.py | PreferencesWindowController._config_chooser_dialog | def _config_chooser_dialog(self, title_text, description):
"""Dialog to select which config shall be exported
:param title_text: Title text
:param description: Description
"""
dialog = Gtk.Dialog(title_text, self.view["preferences_window"],
flags=0, buttons=
(Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT,
Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))
label = Gtk.Label(label=description)
label.set_padding(xpad=10, ypad=10)
dialog.vbox.pack_start(label, True, True, 0)
label.show()
self._gui_checkbox = Gtk.CheckButton(label="GUI Config")
dialog.vbox.pack_start(self._gui_checkbox, True, True, 0)
self._gui_checkbox.show()
self._core_checkbox = Gtk.CheckButton(label="Core Config")
self._core_checkbox.show()
dialog.vbox.pack_start(self._core_checkbox, True, True, 0)
response = dialog.run()
dialog.destroy()
return response | python | def _config_chooser_dialog(self, title_text, description):
"""Dialog to select which config shall be exported
:param title_text: Title text
:param description: Description
"""
dialog = Gtk.Dialog(title_text, self.view["preferences_window"],
flags=0, buttons=
(Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT,
Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))
label = Gtk.Label(label=description)
label.set_padding(xpad=10, ypad=10)
dialog.vbox.pack_start(label, True, True, 0)
label.show()
self._gui_checkbox = Gtk.CheckButton(label="GUI Config")
dialog.vbox.pack_start(self._gui_checkbox, True, True, 0)
self._gui_checkbox.show()
self._core_checkbox = Gtk.CheckButton(label="Core Config")
self._core_checkbox.show()
dialog.vbox.pack_start(self._core_checkbox, True, True, 0)
response = dialog.run()
dialog.destroy()
return response | [
"def",
"_config_chooser_dialog",
"(",
"self",
",",
"title_text",
",",
"description",
")",
":",
"dialog",
"=",
"Gtk",
".",
"Dialog",
"(",
"title_text",
",",
"self",
".",
"view",
"[",
"\"preferences_window\"",
"]",
",",
"flags",
"=",
"0",
",",
"buttons",
"="... | Dialog to select which config shall be exported
:param title_text: Title text
:param description: Description | [
"Dialog",
"to",
"select",
"which",
"config",
"shall",
"be",
"exported"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/preferences_window.py#L591-L613 | train | 40,233 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_editor/data_flows.py | StateDataFlowsListController.remove_core_element | def remove_core_element(self, model):
"""Remove respective core element of handed data flow model
:param DataFlowModel model: Data Flow model which core element should be removed
:return:
"""
assert model.data_flow.parent is self.model.state or model.data_flow.parent is self.model.parent.state
gui_helper_state_machine.delete_core_element_of_model(model) | python | def remove_core_element(self, model):
"""Remove respective core element of handed data flow model
:param DataFlowModel model: Data Flow model which core element should be removed
:return:
"""
assert model.data_flow.parent is self.model.state or model.data_flow.parent is self.model.parent.state
gui_helper_state_machine.delete_core_element_of_model(model) | [
"def",
"remove_core_element",
"(",
"self",
",",
"model",
")",
":",
"assert",
"model",
".",
"data_flow",
".",
"parent",
"is",
"self",
".",
"model",
".",
"state",
"or",
"model",
".",
"data_flow",
".",
"parent",
"is",
"self",
".",
"model",
".",
"parent",
... | Remove respective core element of handed data flow model
:param DataFlowModel model: Data Flow model which core element should be removed
:return: | [
"Remove",
"respective",
"core",
"element",
"of",
"handed",
"data",
"flow",
"model"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/data_flows.py#L243-L250 | train | 40,234 |
DLR-RM/RAFCON | source/rafcon/core/state_machine.py | StateMachine.start | def start(self):
"""Starts the execution of the root state.
"""
# load default input data for the state
self._root_state.input_data = self._root_state.get_default_input_values_for_state(self._root_state)
self._root_state.output_data = self._root_state.create_output_dictionary_for_state(self._root_state)
new_execution_history = self._add_new_execution_history()
new_execution_history.push_state_machine_start_history_item(self, run_id_generator())
self._root_state.start(new_execution_history) | python | def start(self):
"""Starts the execution of the root state.
"""
# load default input data for the state
self._root_state.input_data = self._root_state.get_default_input_values_for_state(self._root_state)
self._root_state.output_data = self._root_state.create_output_dictionary_for_state(self._root_state)
new_execution_history = self._add_new_execution_history()
new_execution_history.push_state_machine_start_history_item(self, run_id_generator())
self._root_state.start(new_execution_history) | [
"def",
"start",
"(",
"self",
")",
":",
"# load default input data for the state",
"self",
".",
"_root_state",
".",
"input_data",
"=",
"self",
".",
"_root_state",
".",
"get_default_input_values_for_state",
"(",
"self",
".",
"_root_state",
")",
"self",
".",
"_root_sta... | Starts the execution of the root state. | [
"Starts",
"the",
"execution",
"of",
"the",
"root",
"state",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/state_machine.py#L138-L146 | train | 40,235 |
DLR-RM/RAFCON | source/rafcon/core/state_machine.py | StateMachine.join | def join(self):
"""Wait for root state to finish execution"""
self._root_state.join()
# execution finished, close execution history log file (if present)
if len(self._execution_histories) > 0:
if self._execution_histories[-1].execution_history_storage is not None:
set_read_and_writable_for_all = global_config.get_config_value("EXECUTION_LOG_SET_READ_AND_WRITABLE_FOR_ALL", False)
self._execution_histories[-1].execution_history_storage.close(set_read_and_writable_for_all)
from rafcon.core.states.state import StateExecutionStatus
self._root_state.state_execution_status = StateExecutionStatus.INACTIVE | python | def join(self):
"""Wait for root state to finish execution"""
self._root_state.join()
# execution finished, close execution history log file (if present)
if len(self._execution_histories) > 0:
if self._execution_histories[-1].execution_history_storage is not None:
set_read_and_writable_for_all = global_config.get_config_value("EXECUTION_LOG_SET_READ_AND_WRITABLE_FOR_ALL", False)
self._execution_histories[-1].execution_history_storage.close(set_read_and_writable_for_all)
from rafcon.core.states.state import StateExecutionStatus
self._root_state.state_execution_status = StateExecutionStatus.INACTIVE | [
"def",
"join",
"(",
"self",
")",
":",
"self",
".",
"_root_state",
".",
"join",
"(",
")",
"# execution finished, close execution history log file (if present)",
"if",
"len",
"(",
"self",
".",
"_execution_histories",
")",
">",
"0",
":",
"if",
"self",
".",
"_execut... | Wait for root state to finish execution | [
"Wait",
"for",
"root",
"state",
"to",
"finish",
"execution"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/state_machine.py#L148-L157 | train | 40,236 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/items/ports.py | PortView._draw_container_state_port | def _draw_container_state_port(self, context, direction, color, transparency):
"""Draw the port of a container state
Connector for container states are split in an inner connector and an outer connector.
:param context: Cairo context
:param direction: The direction the port is pointing to
:param color: Desired color of the port
:param float transparency: The level of transparency
"""
c = context
width, height = self.port_size
c.set_line_width(self.port_side_size / constants.BORDER_WIDTH_OUTLINE_WIDTH_FACTOR *
self._port_image_cache.multiplicator)
# Save/restore context, as we move and rotate the connector to the desired pose
cur_point = c.get_current_point()
c.save()
c.rel_move_to(self.port_side_size / 2., self.port_side_size / 2.)
PortView._rotate_context(c, direction)
PortView._draw_inner_connector(c, width, height)
c.restore()
if self.connected_incoming:
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
else:
c.set_source_rgb(*gui_config.gtk_colors['PORT_UNCONNECTED'].to_floats())
c.fill_preserve()
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
c.stroke()
c.move_to(*cur_point)
c.save()
c.rel_move_to(self.port_side_size / 2., self.port_side_size / 2.)
PortView._rotate_context(c, direction)
PortView._draw_outer_connector(c, width, height)
c.restore()
if self.connected_outgoing:
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
else:
c.set_source_rgb(*gui_config.gtk_colors['PORT_UNCONNECTED'].to_floats())
c.fill_preserve()
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
c.stroke() | python | def _draw_container_state_port(self, context, direction, color, transparency):
"""Draw the port of a container state
Connector for container states are split in an inner connector and an outer connector.
:param context: Cairo context
:param direction: The direction the port is pointing to
:param color: Desired color of the port
:param float transparency: The level of transparency
"""
c = context
width, height = self.port_size
c.set_line_width(self.port_side_size / constants.BORDER_WIDTH_OUTLINE_WIDTH_FACTOR *
self._port_image_cache.multiplicator)
# Save/restore context, as we move and rotate the connector to the desired pose
cur_point = c.get_current_point()
c.save()
c.rel_move_to(self.port_side_size / 2., self.port_side_size / 2.)
PortView._rotate_context(c, direction)
PortView._draw_inner_connector(c, width, height)
c.restore()
if self.connected_incoming:
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
else:
c.set_source_rgb(*gui_config.gtk_colors['PORT_UNCONNECTED'].to_floats())
c.fill_preserve()
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
c.stroke()
c.move_to(*cur_point)
c.save()
c.rel_move_to(self.port_side_size / 2., self.port_side_size / 2.)
PortView._rotate_context(c, direction)
PortView._draw_outer_connector(c, width, height)
c.restore()
if self.connected_outgoing:
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
else:
c.set_source_rgb(*gui_config.gtk_colors['PORT_UNCONNECTED'].to_floats())
c.fill_preserve()
c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
c.stroke() | [
"def",
"_draw_container_state_port",
"(",
"self",
",",
"context",
",",
"direction",
",",
"color",
",",
"transparency",
")",
":",
"c",
"=",
"context",
"width",
",",
"height",
"=",
"self",
".",
"port_size",
"c",
".",
"set_line_width",
"(",
"self",
".",
"port... | Draw the port of a container state
Connector for container states are split in an inner connector and an outer connector.
:param context: Cairo context
:param direction: The direction the port is pointing to
:param color: Desired color of the port
:param float transparency: The level of transparency | [
"Draw",
"the",
"port",
"of",
"a",
"container",
"state"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/ports.py#L419-L464 | train | 40,237 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/items/ports.py | PortView._draw_single_connector | def _draw_single_connector(context, width, height):
"""Draw the connector for execution states
Connector for execution states can only be connected to the outside. Thus the connector fills the whole
border of the state.
:param context: Cairo context
:param float port_size: The side length of the port
"""
c = context
# Current pos is center
# Arrow is drawn upright
arrow_height = height / 2.0
# First move to bottom left corner
c.rel_move_to(-width / 2., height / 2.)
# Draw line to bottom right corner
c.rel_line_to(width, 0)
# Draw line to upper right corner
c.rel_line_to(0, -(height - arrow_height))
# Draw line to center top (arrow)
c.rel_line_to(-width / 2., -arrow_height)
# Draw line to upper left corner
c.rel_line_to(-width / 2., arrow_height)
# Draw line back to the origin (lower left corner)
c.close_path() | python | def _draw_single_connector(context, width, height):
"""Draw the connector for execution states
Connector for execution states can only be connected to the outside. Thus the connector fills the whole
border of the state.
:param context: Cairo context
:param float port_size: The side length of the port
"""
c = context
# Current pos is center
# Arrow is drawn upright
arrow_height = height / 2.0
# First move to bottom left corner
c.rel_move_to(-width / 2., height / 2.)
# Draw line to bottom right corner
c.rel_line_to(width, 0)
# Draw line to upper right corner
c.rel_line_to(0, -(height - arrow_height))
# Draw line to center top (arrow)
c.rel_line_to(-width / 2., -arrow_height)
# Draw line to upper left corner
c.rel_line_to(-width / 2., arrow_height)
# Draw line back to the origin (lower left corner)
c.close_path() | [
"def",
"_draw_single_connector",
"(",
"context",
",",
"width",
",",
"height",
")",
":",
"c",
"=",
"context",
"# Current pos is center",
"# Arrow is drawn upright",
"arrow_height",
"=",
"height",
"/",
"2.0",
"# First move to bottom left corner",
"c",
".",
"rel_move_to",
... | Draw the connector for execution states
Connector for execution states can only be connected to the outside. Thus the connector fills the whole
border of the state.
:param context: Cairo context
:param float port_size: The side length of the port | [
"Draw",
"the",
"connector",
"for",
"execution",
"states"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/ports.py#L483-L509 | train | 40,238 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/items/ports.py | PortView._draw_inner_connector | def _draw_inner_connector(context, width, height):
"""Draw the connector for container states
Connector for container states can be connected from the inside and the outside. Thus the connector is split
in two parts: A rectangle on the inside and an arrow on the outside. This methods draws the inner rectangle.
:param context: Cairo context
:param float port_size: The side length of the port
"""
c = context
# Current pos is center
# Arrow is drawn upright
gap = height / 6.
connector_height = (height - gap) / 2.
# First move to bottom left corner
c.rel_move_to(-width / 2., height / 2.)
# Draw inner connector (rectangle)
c.rel_line_to(width, 0)
c.rel_line_to(0, -connector_height)
c.rel_line_to(-width, 0)
c.close_path() | python | def _draw_inner_connector(context, width, height):
"""Draw the connector for container states
Connector for container states can be connected from the inside and the outside. Thus the connector is split
in two parts: A rectangle on the inside and an arrow on the outside. This methods draws the inner rectangle.
:param context: Cairo context
:param float port_size: The side length of the port
"""
c = context
# Current pos is center
# Arrow is drawn upright
gap = height / 6.
connector_height = (height - gap) / 2.
# First move to bottom left corner
c.rel_move_to(-width / 2., height / 2.)
# Draw inner connector (rectangle)
c.rel_line_to(width, 0)
c.rel_line_to(0, -connector_height)
c.rel_line_to(-width, 0)
c.close_path() | [
"def",
"_draw_inner_connector",
"(",
"context",
",",
"width",
",",
"height",
")",
":",
"c",
"=",
"context",
"# Current pos is center",
"# Arrow is drawn upright",
"gap",
"=",
"height",
"/",
"6.",
"connector_height",
"=",
"(",
"height",
"-",
"gap",
")",
"/",
"2... | Draw the connector for container states
Connector for container states can be connected from the inside and the outside. Thus the connector is split
in two parts: A rectangle on the inside and an arrow on the outside. This methods draws the inner rectangle.
:param context: Cairo context
:param float port_size: The side length of the port | [
"Draw",
"the",
"connector",
"for",
"container",
"states"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/ports.py#L512-L535 | train | 40,239 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/items/ports.py | PortView._draw_outer_connector | def _draw_outer_connector(context, width, height):
"""Draw the outer connector for container states
Connector for container states can be connected from the inside and the outside. Thus the connector is split
in two parts: A rectangle on the inside and an arrow on the outside. This method draws the outer arrow.
:param context: Cairo context
:param float port_size: The side length of the port
"""
c = context
# Current pos is center
# Arrow is drawn upright
arrow_height = height / 2.5
gap = height / 6.
connector_height = (height - gap) / 2.
# Move to bottom left corner of outer connector
c.rel_move_to(-width / 2., -gap / 2.)
# Draw line to bottom right corner
c.rel_line_to(width, 0)
# Draw line to upper right corner
c.rel_line_to(0, -(connector_height - arrow_height))
# Draw line to center top (arrow)
c.rel_line_to(-width / 2., -arrow_height)
# Draw line to upper left corner
c.rel_line_to(-width / 2., arrow_height)
# Draw line back to the origin (lower left corner)
c.close_path() | python | def _draw_outer_connector(context, width, height):
"""Draw the outer connector for container states
Connector for container states can be connected from the inside and the outside. Thus the connector is split
in two parts: A rectangle on the inside and an arrow on the outside. This method draws the outer arrow.
:param context: Cairo context
:param float port_size: The side length of the port
"""
c = context
# Current pos is center
# Arrow is drawn upright
arrow_height = height / 2.5
gap = height / 6.
connector_height = (height - gap) / 2.
# Move to bottom left corner of outer connector
c.rel_move_to(-width / 2., -gap / 2.)
# Draw line to bottom right corner
c.rel_line_to(width, 0)
# Draw line to upper right corner
c.rel_line_to(0, -(connector_height - arrow_height))
# Draw line to center top (arrow)
c.rel_line_to(-width / 2., -arrow_height)
# Draw line to upper left corner
c.rel_line_to(-width / 2., arrow_height)
# Draw line back to the origin (lower left corner)
c.close_path() | [
"def",
"_draw_outer_connector",
"(",
"context",
",",
"width",
",",
"height",
")",
":",
"c",
"=",
"context",
"# Current pos is center",
"# Arrow is drawn upright",
"arrow_height",
"=",
"height",
"/",
"2.5",
"gap",
"=",
"height",
"/",
"6.",
"connector_height",
"=",
... | Draw the outer connector for container states
Connector for container states can be connected from the inside and the outside. Thus the connector is split
in two parts: A rectangle on the inside and an arrow on the outside. This method draws the outer arrow.
:param context: Cairo context
:param float port_size: The side length of the port | [
"Draw",
"the",
"outer",
"connector",
"for",
"container",
"states"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/ports.py#L538-L567 | train | 40,240 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/items/ports.py | PortView._rotate_context | def _rotate_context(context, direction):
"""Moves the current position to 'position' and rotates the context according to 'direction'
:param context: Cairo context
:param direction: Direction enum
"""
if direction is Direction.UP:
pass
elif direction is Direction.RIGHT:
context.rotate(deg2rad(90))
elif direction is Direction.DOWN:
context.rotate(deg2rad(180))
elif direction is Direction.LEFT:
context.rotate(deg2rad(-90)) | python | def _rotate_context(context, direction):
"""Moves the current position to 'position' and rotates the context according to 'direction'
:param context: Cairo context
:param direction: Direction enum
"""
if direction is Direction.UP:
pass
elif direction is Direction.RIGHT:
context.rotate(deg2rad(90))
elif direction is Direction.DOWN:
context.rotate(deg2rad(180))
elif direction is Direction.LEFT:
context.rotate(deg2rad(-90)) | [
"def",
"_rotate_context",
"(",
"context",
",",
"direction",
")",
":",
"if",
"direction",
"is",
"Direction",
".",
"UP",
":",
"pass",
"elif",
"direction",
"is",
"Direction",
".",
"RIGHT",
":",
"context",
".",
"rotate",
"(",
"deg2rad",
"(",
"90",
")",
")",
... | Moves the current position to 'position' and rotates the context according to 'direction'
:param context: Cairo context
:param direction: Direction enum | [
"Moves",
"the",
"current",
"position",
"to",
"position",
"and",
"rotates",
"the",
"context",
"according",
"to",
"direction"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/ports.py#L589-L602 | train | 40,241 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/items/ports.py | ScopedVariablePortView.draw_name | def draw_name(self, context, transparency, only_calculate_size=False):
"""Draws the name of the port
Offers the option to only calculate the size of the name.
:param context: The context to draw on
:param transparency: The transparency of the text
:param only_calculate_size: Whether to only calculate the size
:return: Size of the name
:rtype: float, float
"""
c = context
cairo_context = c
if isinstance(c, CairoBoundingBoxContext):
cairo_context = c._cairo
# c.set_antialias(Antialias.GOOD)
side_length = self.port_side_size
layout = PangoCairo.create_layout(cairo_context)
font_name = constants.INTERFACE_FONT
font_size = gap_draw_helper.FONT_SIZE
font = FontDescription(font_name + " " + str(font_size))
layout.set_font_description(font)
layout.set_text(self.name, -1)
ink_extents, logical_extents = layout.get_extents()
extents = [extent / float(SCALE) for extent in [logical_extents.x, logical_extents.y,
logical_extents.width, logical_extents.height]]
real_name_size = extents[2], extents[3]
desired_height = side_length * 0.75
scale_factor = real_name_size[1] / desired_height
# Determine the size of the text, increase the width to have more margin left and right of the text
margin = side_length / 4.
name_size = real_name_size[0] / scale_factor, desired_height
name_size_with_margin = name_size[0] + margin * 2, name_size[1] + margin * 2
# Only the size is required, stop here
if only_calculate_size:
return name_size_with_margin
# Current position is the center of the port rectangle
c.save()
if self.side is SnappedSide.RIGHT or self.side is SnappedSide.LEFT:
c.rotate(deg2rad(-90))
c.rel_move_to(-name_size[0] / 2, -name_size[1] / 2)
c.scale(1. / scale_factor, 1. / scale_factor)
c.rel_move_to(-extents[0], -extents[1])
c.set_source_rgba(*gap_draw_helper.get_col_rgba(self.text_color, transparency))
PangoCairo.update_layout(cairo_context, layout)
PangoCairo.show_layout(cairo_context, layout)
c.restore()
return name_size_with_margin | python | def draw_name(self, context, transparency, only_calculate_size=False):
"""Draws the name of the port
Offers the option to only calculate the size of the name.
:param context: The context to draw on
:param transparency: The transparency of the text
:param only_calculate_size: Whether to only calculate the size
:return: Size of the name
:rtype: float, float
"""
c = context
cairo_context = c
if isinstance(c, CairoBoundingBoxContext):
cairo_context = c._cairo
# c.set_antialias(Antialias.GOOD)
side_length = self.port_side_size
layout = PangoCairo.create_layout(cairo_context)
font_name = constants.INTERFACE_FONT
font_size = gap_draw_helper.FONT_SIZE
font = FontDescription(font_name + " " + str(font_size))
layout.set_font_description(font)
layout.set_text(self.name, -1)
ink_extents, logical_extents = layout.get_extents()
extents = [extent / float(SCALE) for extent in [logical_extents.x, logical_extents.y,
logical_extents.width, logical_extents.height]]
real_name_size = extents[2], extents[3]
desired_height = side_length * 0.75
scale_factor = real_name_size[1] / desired_height
# Determine the size of the text, increase the width to have more margin left and right of the text
margin = side_length / 4.
name_size = real_name_size[0] / scale_factor, desired_height
name_size_with_margin = name_size[0] + margin * 2, name_size[1] + margin * 2
# Only the size is required, stop here
if only_calculate_size:
return name_size_with_margin
# Current position is the center of the port rectangle
c.save()
if self.side is SnappedSide.RIGHT or self.side is SnappedSide.LEFT:
c.rotate(deg2rad(-90))
c.rel_move_to(-name_size[0] / 2, -name_size[1] / 2)
c.scale(1. / scale_factor, 1. / scale_factor)
c.rel_move_to(-extents[0], -extents[1])
c.set_source_rgba(*gap_draw_helper.get_col_rgba(self.text_color, transparency))
PangoCairo.update_layout(cairo_context, layout)
PangoCairo.show_layout(cairo_context, layout)
c.restore()
return name_size_with_margin | [
"def",
"draw_name",
"(",
"self",
",",
"context",
",",
"transparency",
",",
"only_calculate_size",
"=",
"False",
")",
":",
"c",
"=",
"context",
"cairo_context",
"=",
"c",
"if",
"isinstance",
"(",
"c",
",",
"CairoBoundingBoxContext",
")",
":",
"cairo_context",
... | Draws the name of the port
Offers the option to only calculate the size of the name.
:param context: The context to draw on
:param transparency: The transparency of the text
:param only_calculate_size: Whether to only calculate the size
:return: Size of the name
:rtype: float, float | [
"Draws",
"the",
"name",
"of",
"the",
"port"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/ports.py#L771-L826 | train | 40,242 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/items/ports.py | ScopedVariablePortView._draw_rectangle_path | def _draw_rectangle_path(self, context, width, height, only_get_extents=False):
"""Draws the rectangle path for the port
The rectangle is correctly rotated. Height therefore refers to the border thickness and width to the length
of the port.
:param context: The context to draw on
:param float width: The width of the rectangle
:param float height: The height of the rectangle
"""
c = context
# Current position is the center of the rectangle
c.save()
if self.side is SnappedSide.LEFT or self.side is SnappedSide.RIGHT:
c.rotate(deg2rad(90))
c.rel_move_to(-width / 2., - height / 2.)
c.rel_line_to(width, 0)
c.rel_line_to(0, height)
c.rel_line_to(-width, 0)
c.close_path()
c.restore()
if only_get_extents:
extents = c.path_extents()
c.new_path()
return extents | python | def _draw_rectangle_path(self, context, width, height, only_get_extents=False):
"""Draws the rectangle path for the port
The rectangle is correctly rotated. Height therefore refers to the border thickness and width to the length
of the port.
:param context: The context to draw on
:param float width: The width of the rectangle
:param float height: The height of the rectangle
"""
c = context
# Current position is the center of the rectangle
c.save()
if self.side is SnappedSide.LEFT or self.side is SnappedSide.RIGHT:
c.rotate(deg2rad(90))
c.rel_move_to(-width / 2., - height / 2.)
c.rel_line_to(width, 0)
c.rel_line_to(0, height)
c.rel_line_to(-width, 0)
c.close_path()
c.restore()
if only_get_extents:
extents = c.path_extents()
c.new_path()
return extents | [
"def",
"_draw_rectangle_path",
"(",
"self",
",",
"context",
",",
"width",
",",
"height",
",",
"only_get_extents",
"=",
"False",
")",
":",
"c",
"=",
"context",
"# Current position is the center of the rectangle",
"c",
".",
"save",
"(",
")",
"if",
"self",
".",
"... | Draws the rectangle path for the port
The rectangle is correctly rotated. Height therefore refers to the border thickness and width to the length
of the port.
:param context: The context to draw on
:param float width: The width of the rectangle
:param float height: The height of the rectangle | [
"Draws",
"the",
"rectangle",
"path",
"for",
"the",
"port"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/ports.py#L828-L854 | train | 40,243 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/items/ports.py | ScopedVariablePortView._get_port_center_position | def _get_port_center_position(self, width):
"""Calculates the center position of the port rectangle
The port itself can be positioned in the corner, the center of the port rectangle however is restricted by
the width of the rectangle. This method therefore calculates the center, depending on the position of the
port and the width of the rectangle.
:param float width: The width of the rectangle
:return: The center position of the rectangle
:rtype: float, float
"""
x, y = self.pos.x.value, self.pos.y.value
if self.side is SnappedSide.TOP or self.side is SnappedSide.BOTTOM:
if x - width / 2. < 0:
x = width / 2
elif x + width / 2. > self.parent.width:
x = self.parent.width - width / 2.
else:
if y - width / 2. < 0:
y = width / 2
elif y + width / 2. > self.parent.height:
y = self.parent.height - width / 2.
return x, y | python | def _get_port_center_position(self, width):
"""Calculates the center position of the port rectangle
The port itself can be positioned in the corner, the center of the port rectangle however is restricted by
the width of the rectangle. This method therefore calculates the center, depending on the position of the
port and the width of the rectangle.
:param float width: The width of the rectangle
:return: The center position of the rectangle
:rtype: float, float
"""
x, y = self.pos.x.value, self.pos.y.value
if self.side is SnappedSide.TOP or self.side is SnappedSide.BOTTOM:
if x - width / 2. < 0:
x = width / 2
elif x + width / 2. > self.parent.width:
x = self.parent.width - width / 2.
else:
if y - width / 2. < 0:
y = width / 2
elif y + width / 2. > self.parent.height:
y = self.parent.height - width / 2.
return x, y | [
"def",
"_get_port_center_position",
"(",
"self",
",",
"width",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"pos",
".",
"x",
".",
"value",
",",
"self",
".",
"pos",
".",
"y",
".",
"value",
"if",
"self",
".",
"side",
"is",
"SnappedSide",
".",
"TOP",
... | Calculates the center position of the port rectangle
The port itself can be positioned in the corner, the center of the port rectangle however is restricted by
the width of the rectangle. This method therefore calculates the center, depending on the position of the
port and the width of the rectangle.
:param float width: The width of the rectangle
:return: The center position of the rectangle
:rtype: float, float | [
"Calculates",
"the",
"center",
"position",
"of",
"the",
"port",
"rectangle"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/ports.py#L856-L877 | train | 40,244 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.get_current_state_m | def get_current_state_m(self):
"""Returns the state model of the currently open tab"""
page_id = self.view.notebook.get_current_page()
if page_id == -1:
return None
page = self.view.notebook.get_nth_page(page_id)
state_identifier = self.get_state_identifier_for_page(page)
return self.tabs[state_identifier]['state_m'] | python | def get_current_state_m(self):
"""Returns the state model of the currently open tab"""
page_id = self.view.notebook.get_current_page()
if page_id == -1:
return None
page = self.view.notebook.get_nth_page(page_id)
state_identifier = self.get_state_identifier_for_page(page)
return self.tabs[state_identifier]['state_m'] | [
"def",
"get_current_state_m",
"(",
"self",
")",
":",
"page_id",
"=",
"self",
".",
"view",
".",
"notebook",
".",
"get_current_page",
"(",
")",
"if",
"page_id",
"==",
"-",
"1",
":",
"return",
"None",
"page",
"=",
"self",
".",
"view",
".",
"notebook",
"."... | Returns the state model of the currently open tab | [
"Returns",
"the",
"state",
"model",
"of",
"the",
"currently",
"open",
"tab"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L190-L197 | train | 40,245 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.state_machine_manager_notification | def state_machine_manager_notification(self, model, property, info):
"""Triggered whenever a new state machine is created, or an existing state machine is selected.
"""
if self.current_state_machine_m is not None:
selection = self.current_state_machine_m.selection
if len(selection.states) > 0:
self.activate_state_tab(selection.get_selected_state()) | python | def state_machine_manager_notification(self, model, property, info):
"""Triggered whenever a new state machine is created, or an existing state machine is selected.
"""
if self.current_state_machine_m is not None:
selection = self.current_state_machine_m.selection
if len(selection.states) > 0:
self.activate_state_tab(selection.get_selected_state()) | [
"def",
"state_machine_manager_notification",
"(",
"self",
",",
"model",
",",
"property",
",",
"info",
")",
":",
"if",
"self",
".",
"current_state_machine_m",
"is",
"not",
"None",
":",
"selection",
"=",
"self",
".",
"current_state_machine_m",
".",
"selection",
"i... | Triggered whenever a new state machine is created, or an existing state machine is selected. | [
"Triggered",
"whenever",
"a",
"new",
"state",
"machine",
"is",
"created",
"or",
"an",
"existing",
"state",
"machine",
"is",
"selected",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L224-L230 | train | 40,246 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.clean_up_tabs | def clean_up_tabs(self):
""" Method remove state-tabs for those no state machine exists anymore.
"""
tabs_to_close = []
for state_identifier, tab_dict in list(self.tabs.items()):
if tab_dict['sm_id'] not in self.model.state_machine_manager.state_machines:
tabs_to_close.append(state_identifier)
for state_identifier, tab_dict in list(self.closed_tabs.items()):
if tab_dict['sm_id'] not in self.model.state_machine_manager.state_machines:
tabs_to_close.append(state_identifier)
for state_identifier in tabs_to_close:
self.close_page(state_identifier, delete=True) | python | def clean_up_tabs(self):
""" Method remove state-tabs for those no state machine exists anymore.
"""
tabs_to_close = []
for state_identifier, tab_dict in list(self.tabs.items()):
if tab_dict['sm_id'] not in self.model.state_machine_manager.state_machines:
tabs_to_close.append(state_identifier)
for state_identifier, tab_dict in list(self.closed_tabs.items()):
if tab_dict['sm_id'] not in self.model.state_machine_manager.state_machines:
tabs_to_close.append(state_identifier)
for state_identifier in tabs_to_close:
self.close_page(state_identifier, delete=True) | [
"def",
"clean_up_tabs",
"(",
"self",
")",
":",
"tabs_to_close",
"=",
"[",
"]",
"for",
"state_identifier",
",",
"tab_dict",
"in",
"list",
"(",
"self",
".",
"tabs",
".",
"items",
"(",
")",
")",
":",
"if",
"tab_dict",
"[",
"'sm_id'",
"]",
"not",
"in",
"... | Method remove state-tabs for those no state machine exists anymore. | [
"Method",
"remove",
"state",
"-",
"tabs",
"for",
"those",
"no",
"state",
"machine",
"exists",
"anymore",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L232-L243 | train | 40,247 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.state_machines_set_notification | def state_machines_set_notification(self, model, prop_name, info):
"""Observe all open state machines and their root states
"""
if info['method_name'] == '__setitem__':
state_machine_m = info.args[1]
self.observe_model(state_machine_m) | python | def state_machines_set_notification(self, model, prop_name, info):
"""Observe all open state machines and their root states
"""
if info['method_name'] == '__setitem__':
state_machine_m = info.args[1]
self.observe_model(state_machine_m) | [
"def",
"state_machines_set_notification",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"if",
"info",
"[",
"'method_name'",
"]",
"==",
"'__setitem__'",
":",
"state_machine_m",
"=",
"info",
".",
"args",
"[",
"1",
"]",
"self",
".",
"obs... | Observe all open state machines and their root states | [
"Observe",
"all",
"open",
"state",
"machines",
"and",
"their",
"root",
"states"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L246-L251 | train | 40,248 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.state_machines_del_notification | def state_machines_del_notification(self, model, prop_name, info):
"""Relive models of closed state machine
"""
if info['method_name'] == '__delitem__':
state_machine_m = info["result"]
try:
self.relieve_model(state_machine_m)
except KeyError:
pass
self.clean_up_tabs() | python | def state_machines_del_notification(self, model, prop_name, info):
"""Relive models of closed state machine
"""
if info['method_name'] == '__delitem__':
state_machine_m = info["result"]
try:
self.relieve_model(state_machine_m)
except KeyError:
pass
self.clean_up_tabs() | [
"def",
"state_machines_del_notification",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"if",
"info",
"[",
"'method_name'",
"]",
"==",
"'__delitem__'",
":",
"state_machine_m",
"=",
"info",
"[",
"\"result\"",
"]",
"try",
":",
"self",
"."... | Relive models of closed state machine | [
"Relive",
"models",
"of",
"closed",
"state",
"machine"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L254-L263 | train | 40,249 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.add_state_editor | def add_state_editor(self, state_m):
"""Triggered whenever a state is selected.
:param state_m: The selected state model.
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier in self.closed_tabs:
state_editor_ctrl = self.closed_tabs[state_identifier]['controller']
state_editor_view = state_editor_ctrl.view
handler_id = self.closed_tabs[state_identifier]['source_code_changed_handler_id']
source_code_view_is_dirty = self.closed_tabs[state_identifier]['source_code_view_is_dirty']
del self.closed_tabs[state_identifier] # pages not in self.closed_tabs and self.tabs at the same time
else:
state_editor_view = StateEditorView()
if isinstance(state_m, LibraryStateModel):
state_editor_view['main_notebook_1'].set_current_page(
state_editor_view['main_notebook_1'].page_num(state_editor_view.page_dict["Data Linkage"]))
state_editor_ctrl = StateEditorController(state_m, state_editor_view)
self.add_controller(state_identifier, state_editor_ctrl)
if state_editor_ctrl.get_controller('source_ctrl') and state_m.state.get_next_upper_library_root_state() is None:
# observe changed to set the mark dirty flag
handler_id = state_editor_view.source_view.get_buffer().connect('changed', self.script_text_changed,
state_m)
self.view.get_top_widget().connect('draw', state_editor_view.source_view.on_draw)
else:
handler_id = None
source_code_view_is_dirty = False
(tab, inner_label, sticky_button) = create_tab_header('', self.on_tab_close_clicked,
self.on_toggle_sticky_clicked, state_m)
set_tab_label_texts(inner_label, state_m, source_code_view_is_dirty)
state_editor_view.get_top_widget().title_label = inner_label
state_editor_view.get_top_widget().sticky_button = sticky_button
page_content = state_editor_view.get_top_widget()
page_id = self.view.notebook.prepend_page(page_content, tab)
page = self.view.notebook.get_nth_page(page_id)
self.view.notebook.set_tab_reorderable(page, True)
page.show_all()
self.view.notebook.show()
self.tabs[state_identifier] = {'page': page, 'state_m': state_m,
'controller': state_editor_ctrl, 'sm_id': self.model.selected_state_machine_id,
'is_sticky': False,
'source_code_view_is_dirty': source_code_view_is_dirty,
'source_code_changed_handler_id': handler_id}
return page_id | python | def add_state_editor(self, state_m):
"""Triggered whenever a state is selected.
:param state_m: The selected state model.
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier in self.closed_tabs:
state_editor_ctrl = self.closed_tabs[state_identifier]['controller']
state_editor_view = state_editor_ctrl.view
handler_id = self.closed_tabs[state_identifier]['source_code_changed_handler_id']
source_code_view_is_dirty = self.closed_tabs[state_identifier]['source_code_view_is_dirty']
del self.closed_tabs[state_identifier] # pages not in self.closed_tabs and self.tabs at the same time
else:
state_editor_view = StateEditorView()
if isinstance(state_m, LibraryStateModel):
state_editor_view['main_notebook_1'].set_current_page(
state_editor_view['main_notebook_1'].page_num(state_editor_view.page_dict["Data Linkage"]))
state_editor_ctrl = StateEditorController(state_m, state_editor_view)
self.add_controller(state_identifier, state_editor_ctrl)
if state_editor_ctrl.get_controller('source_ctrl') and state_m.state.get_next_upper_library_root_state() is None:
# observe changed to set the mark dirty flag
handler_id = state_editor_view.source_view.get_buffer().connect('changed', self.script_text_changed,
state_m)
self.view.get_top_widget().connect('draw', state_editor_view.source_view.on_draw)
else:
handler_id = None
source_code_view_is_dirty = False
(tab, inner_label, sticky_button) = create_tab_header('', self.on_tab_close_clicked,
self.on_toggle_sticky_clicked, state_m)
set_tab_label_texts(inner_label, state_m, source_code_view_is_dirty)
state_editor_view.get_top_widget().title_label = inner_label
state_editor_view.get_top_widget().sticky_button = sticky_button
page_content = state_editor_view.get_top_widget()
page_id = self.view.notebook.prepend_page(page_content, tab)
page = self.view.notebook.get_nth_page(page_id)
self.view.notebook.set_tab_reorderable(page, True)
page.show_all()
self.view.notebook.show()
self.tabs[state_identifier] = {'page': page, 'state_m': state_m,
'controller': state_editor_ctrl, 'sm_id': self.model.selected_state_machine_id,
'is_sticky': False,
'source_code_view_is_dirty': source_code_view_is_dirty,
'source_code_changed_handler_id': handler_id}
return page_id | [
"def",
"add_state_editor",
"(",
"self",
",",
"state_m",
")",
":",
"state_identifier",
"=",
"self",
".",
"get_state_identifier",
"(",
"state_m",
")",
"if",
"state_identifier",
"in",
"self",
".",
"closed_tabs",
":",
"state_editor_ctrl",
"=",
"self",
".",
"closed_t... | Triggered whenever a state is selected.
:param state_m: The selected state model. | [
"Triggered",
"whenever",
"a",
"state",
"is",
"selected",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L285-L333 | train | 40,250 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.script_text_changed | def script_text_changed(self, text_buffer, state_m):
""" Update gui elements according text buffer changes
Checks if the dirty flag needs to be set and the tab label to be updated.
:param TextBuffer text_buffer: Text buffer of the edited script
:param rafcon.gui.models.state.StateModel state_m: The state model related to the text buffer
:return:
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier in self.tabs:
tab_list = self.tabs
elif state_identifier in self.closed_tabs:
tab_list = self.closed_tabs
else:
logger.warning('It was tried to check a source script of a state with no state-editor')
return
if tab_list[state_identifier]['controller'].get_controller('source_ctrl') is None:
logger.warning('It was tried to check a source script of a state with no source-editor')
return
current_text = tab_list[state_identifier]['controller'].get_controller('source_ctrl').view.get_text()
old_is_dirty = tab_list[state_identifier]['source_code_view_is_dirty']
source_script_state_m = state_m.state_copy if isinstance(state_m, LibraryStateModel) else state_m
# remove next two lines and tab is also set dirty for source scripts inside of a LibraryState (maybe in future)
if isinstance(state_m, LibraryStateModel) or state_m.state.get_next_upper_library_root_state() is not None:
return
if source_script_state_m.state.script_text == current_text:
tab_list[state_identifier]['source_code_view_is_dirty'] = False
else:
tab_list[state_identifier]['source_code_view_is_dirty'] = True
if old_is_dirty is not tab_list[state_identifier]['source_code_view_is_dirty']:
self.update_tab_label(source_script_state_m) | python | def script_text_changed(self, text_buffer, state_m):
""" Update gui elements according text buffer changes
Checks if the dirty flag needs to be set and the tab label to be updated.
:param TextBuffer text_buffer: Text buffer of the edited script
:param rafcon.gui.models.state.StateModel state_m: The state model related to the text buffer
:return:
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier in self.tabs:
tab_list = self.tabs
elif state_identifier in self.closed_tabs:
tab_list = self.closed_tabs
else:
logger.warning('It was tried to check a source script of a state with no state-editor')
return
if tab_list[state_identifier]['controller'].get_controller('source_ctrl') is None:
logger.warning('It was tried to check a source script of a state with no source-editor')
return
current_text = tab_list[state_identifier]['controller'].get_controller('source_ctrl').view.get_text()
old_is_dirty = tab_list[state_identifier]['source_code_view_is_dirty']
source_script_state_m = state_m.state_copy if isinstance(state_m, LibraryStateModel) else state_m
# remove next two lines and tab is also set dirty for source scripts inside of a LibraryState (maybe in future)
if isinstance(state_m, LibraryStateModel) or state_m.state.get_next_upper_library_root_state() is not None:
return
if source_script_state_m.state.script_text == current_text:
tab_list[state_identifier]['source_code_view_is_dirty'] = False
else:
tab_list[state_identifier]['source_code_view_is_dirty'] = True
if old_is_dirty is not tab_list[state_identifier]['source_code_view_is_dirty']:
self.update_tab_label(source_script_state_m) | [
"def",
"script_text_changed",
"(",
"self",
",",
"text_buffer",
",",
"state_m",
")",
":",
"state_identifier",
"=",
"self",
".",
"get_state_identifier",
"(",
"state_m",
")",
"if",
"state_identifier",
"in",
"self",
".",
"tabs",
":",
"tab_list",
"=",
"self",
".",
... | Update gui elements according text buffer changes
Checks if the dirty flag needs to be set and the tab label to be updated.
:param TextBuffer text_buffer: Text buffer of the edited script
:param rafcon.gui.models.state.StateModel state_m: The state model related to the text buffer
:return: | [
"Update",
"gui",
"elements",
"according",
"text",
"buffer",
"changes"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L348-L380 | train | 40,251 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.destroy_page | def destroy_page(self, tab_dict):
""" Destroys desired page
Disconnects the page from signals and removes interconnection to parent-controller or observables.
:param tab_dict: Tab-dictionary that holds all necessary information of a page and state-editor.
"""
# logger.info("destroy page %s" % tab_dict['controller'].model.state.get_path())
if tab_dict['source_code_changed_handler_id'] is not None:
handler_id = tab_dict['source_code_changed_handler_id']
if tab_dict['controller'].view.source_view.get_buffer().handler_is_connected(handler_id):
tab_dict['controller'].view.source_view.get_buffer().disconnect(handler_id)
else:
logger.warning("Source code changed handler of state {0} was already removed.".format(tab_dict['state_m']))
self.remove_controller(tab_dict['controller']) | python | def destroy_page(self, tab_dict):
""" Destroys desired page
Disconnects the page from signals and removes interconnection to parent-controller or observables.
:param tab_dict: Tab-dictionary that holds all necessary information of a page and state-editor.
"""
# logger.info("destroy page %s" % tab_dict['controller'].model.state.get_path())
if tab_dict['source_code_changed_handler_id'] is not None:
handler_id = tab_dict['source_code_changed_handler_id']
if tab_dict['controller'].view.source_view.get_buffer().handler_is_connected(handler_id):
tab_dict['controller'].view.source_view.get_buffer().disconnect(handler_id)
else:
logger.warning("Source code changed handler of state {0} was already removed.".format(tab_dict['state_m']))
self.remove_controller(tab_dict['controller']) | [
"def",
"destroy_page",
"(",
"self",
",",
"tab_dict",
")",
":",
"# logger.info(\"destroy page %s\" % tab_dict['controller'].model.state.get_path())",
"if",
"tab_dict",
"[",
"'source_code_changed_handler_id'",
"]",
"is",
"not",
"None",
":",
"handler_id",
"=",
"tab_dict",
"[",... | Destroys desired page
Disconnects the page from signals and removes interconnection to parent-controller or observables.
:param tab_dict: Tab-dictionary that holds all necessary information of a page and state-editor. | [
"Destroys",
"desired",
"page"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L382-L396 | train | 40,252 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.close_page | def close_page(self, state_identifier, delete=True):
"""Closes the desired page
The page belonging to the state with the specified state_identifier is closed. If the deletion flag is set to
False, the controller of the page is stored for later usage.
:param state_identifier: Identifier of the page's state
:param delete: Whether to delete the controller (deletion is necessary if teh state is deleted)
"""
# delete old controller references
if delete and state_identifier in self.closed_tabs:
self.destroy_page(self.closed_tabs[state_identifier])
del self.closed_tabs[state_identifier]
# check for open page of state
if state_identifier in self.tabs:
page_to_close = self.tabs[state_identifier]['page']
current_page_id = self.view.notebook.page_num(page_to_close)
if not delete:
self.closed_tabs[state_identifier] = self.tabs[state_identifier]
else:
self.destroy_page(self.tabs[state_identifier])
del self.tabs[state_identifier]
# Finally remove the page, this triggers the callback handles on_switch_page
self.view.notebook.remove_page(current_page_id) | python | def close_page(self, state_identifier, delete=True):
"""Closes the desired page
The page belonging to the state with the specified state_identifier is closed. If the deletion flag is set to
False, the controller of the page is stored for later usage.
:param state_identifier: Identifier of the page's state
:param delete: Whether to delete the controller (deletion is necessary if teh state is deleted)
"""
# delete old controller references
if delete and state_identifier in self.closed_tabs:
self.destroy_page(self.closed_tabs[state_identifier])
del self.closed_tabs[state_identifier]
# check for open page of state
if state_identifier in self.tabs:
page_to_close = self.tabs[state_identifier]['page']
current_page_id = self.view.notebook.page_num(page_to_close)
if not delete:
self.closed_tabs[state_identifier] = self.tabs[state_identifier]
else:
self.destroy_page(self.tabs[state_identifier])
del self.tabs[state_identifier]
# Finally remove the page, this triggers the callback handles on_switch_page
self.view.notebook.remove_page(current_page_id) | [
"def",
"close_page",
"(",
"self",
",",
"state_identifier",
",",
"delete",
"=",
"True",
")",
":",
"# delete old controller references",
"if",
"delete",
"and",
"state_identifier",
"in",
"self",
".",
"closed_tabs",
":",
"self",
".",
"destroy_page",
"(",
"self",
"."... | Closes the desired page
The page belonging to the state with the specified state_identifier is closed. If the deletion flag is set to
False, the controller of the page is stored for later usage.
:param state_identifier: Identifier of the page's state
:param delete: Whether to delete the controller (deletion is necessary if teh state is deleted) | [
"Closes",
"the",
"desired",
"page"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L398-L422 | train | 40,253 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.find_page_of_state_m | def find_page_of_state_m(self, state_m):
"""Return the identifier and page of a given state model
:param state_m: The state model to be searched
:return: page containing the state and the state_identifier
"""
for state_identifier, page_info in list(self.tabs.items()):
if page_info['state_m'] is state_m:
return page_info['page'], state_identifier
return None, None | python | def find_page_of_state_m(self, state_m):
"""Return the identifier and page of a given state model
:param state_m: The state model to be searched
:return: page containing the state and the state_identifier
"""
for state_identifier, page_info in list(self.tabs.items()):
if page_info['state_m'] is state_m:
return page_info['page'], state_identifier
return None, None | [
"def",
"find_page_of_state_m",
"(",
"self",
",",
"state_m",
")",
":",
"for",
"state_identifier",
",",
"page_info",
"in",
"list",
"(",
"self",
".",
"tabs",
".",
"items",
"(",
")",
")",
":",
"if",
"page_info",
"[",
"'state_m'",
"]",
"is",
"state_m",
":",
... | Return the identifier and page of a given state model
:param state_m: The state model to be searched
:return: page containing the state and the state_identifier | [
"Return",
"the",
"identifier",
"and",
"page",
"of",
"a",
"given",
"state",
"model"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L424-L433 | train | 40,254 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.on_tab_close_clicked | def on_tab_close_clicked(self, event, state_m):
"""Triggered when the states-editor close button is clicked
Closes the tab.
:param state_m: The desired state model (the selected state)
"""
[page, state_identifier] = self.find_page_of_state_m(state_m)
if page:
self.close_page(state_identifier, delete=False) | python | def on_tab_close_clicked(self, event, state_m):
"""Triggered when the states-editor close button is clicked
Closes the tab.
:param state_m: The desired state model (the selected state)
"""
[page, state_identifier] = self.find_page_of_state_m(state_m)
if page:
self.close_page(state_identifier, delete=False) | [
"def",
"on_tab_close_clicked",
"(",
"self",
",",
"event",
",",
"state_m",
")",
":",
"[",
"page",
",",
"state_identifier",
"]",
"=",
"self",
".",
"find_page_of_state_m",
"(",
"state_m",
")",
"if",
"page",
":",
"self",
".",
"close_page",
"(",
"state_identifier... | Triggered when the states-editor close button is clicked
Closes the tab.
:param state_m: The desired state model (the selected state) | [
"Triggered",
"when",
"the",
"states",
"-",
"editor",
"close",
"button",
"is",
"clicked"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L435-L444 | train | 40,255 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.on_toggle_sticky_clicked | def on_toggle_sticky_clicked(self, event, state_m):
"""Callback for the "toggle-sticky-check-button" emitted by custom TabLabel widget.
"""
[page, state_identifier] = self.find_page_of_state_m(state_m)
if not page:
return
self.tabs[state_identifier]['is_sticky'] = not self.tabs[state_identifier]['is_sticky']
page.sticky_button.set_active(self.tabs[state_identifier]['is_sticky']) | python | def on_toggle_sticky_clicked(self, event, state_m):
"""Callback for the "toggle-sticky-check-button" emitted by custom TabLabel widget.
"""
[page, state_identifier] = self.find_page_of_state_m(state_m)
if not page:
return
self.tabs[state_identifier]['is_sticky'] = not self.tabs[state_identifier]['is_sticky']
page.sticky_button.set_active(self.tabs[state_identifier]['is_sticky']) | [
"def",
"on_toggle_sticky_clicked",
"(",
"self",
",",
"event",
",",
"state_m",
")",
":",
"[",
"page",
",",
"state_identifier",
"]",
"=",
"self",
".",
"find_page_of_state_m",
"(",
"state_m",
")",
"if",
"not",
"page",
":",
"return",
"self",
".",
"tabs",
"[",
... | Callback for the "toggle-sticky-check-button" emitted by custom TabLabel widget. | [
"Callback",
"for",
"the",
"toggle",
"-",
"sticky",
"-",
"check",
"-",
"button",
"emitted",
"by",
"custom",
"TabLabel",
"widget",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L446-L453 | train | 40,256 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.close_all_pages | def close_all_pages(self):
"""Closes all tabs of the states editor"""
states_to_be_closed = []
for state_identifier in self.tabs:
states_to_be_closed.append(state_identifier)
for state_identifier in states_to_be_closed:
self.close_page(state_identifier, delete=False) | python | def close_all_pages(self):
"""Closes all tabs of the states editor"""
states_to_be_closed = []
for state_identifier in self.tabs:
states_to_be_closed.append(state_identifier)
for state_identifier in states_to_be_closed:
self.close_page(state_identifier, delete=False) | [
"def",
"close_all_pages",
"(",
"self",
")",
":",
"states_to_be_closed",
"=",
"[",
"]",
"for",
"state_identifier",
"in",
"self",
".",
"tabs",
":",
"states_to_be_closed",
".",
"append",
"(",
"state_identifier",
")",
"for",
"state_identifier",
"in",
"states_to_be_clo... | Closes all tabs of the states editor | [
"Closes",
"all",
"tabs",
"of",
"the",
"states",
"editor"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L455-L461 | train | 40,257 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.close_pages_for_specific_sm_id | def close_pages_for_specific_sm_id(self, sm_id):
"""Closes all tabs of the states editor for a specific sm_id"""
states_to_be_closed = []
for state_identifier in self.tabs:
state_m = self.tabs[state_identifier]["state_m"]
if state_m.state.get_state_machine().state_machine_id == sm_id:
states_to_be_closed.append(state_identifier)
for state_identifier in states_to_be_closed:
self.close_page(state_identifier, delete=False) | python | def close_pages_for_specific_sm_id(self, sm_id):
"""Closes all tabs of the states editor for a specific sm_id"""
states_to_be_closed = []
for state_identifier in self.tabs:
state_m = self.tabs[state_identifier]["state_m"]
if state_m.state.get_state_machine().state_machine_id == sm_id:
states_to_be_closed.append(state_identifier)
for state_identifier in states_to_be_closed:
self.close_page(state_identifier, delete=False) | [
"def",
"close_pages_for_specific_sm_id",
"(",
"self",
",",
"sm_id",
")",
":",
"states_to_be_closed",
"=",
"[",
"]",
"for",
"state_identifier",
"in",
"self",
".",
"tabs",
":",
"state_m",
"=",
"self",
".",
"tabs",
"[",
"state_identifier",
"]",
"[",
"\"state_m\""... | Closes all tabs of the states editor for a specific sm_id | [
"Closes",
"all",
"tabs",
"of",
"the",
"states",
"editor",
"for",
"a",
"specific",
"sm_id"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L463-L471 | train | 40,258 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.on_switch_page | def on_switch_page(self, notebook, page_pointer, page_num, user_param1=None):
"""Update state selection when the active tab was changed
"""
page = notebook.get_nth_page(page_num)
# find state of selected tab
for tab_info in list(self.tabs.values()):
if tab_info['page'] is page:
state_m = tab_info['state_m']
sm_id = state_m.state.get_state_machine().state_machine_id
selected_state_m = self.current_state_machine_m.selection.get_selected_state()
# If the state of the selected tab is not in the selection, set it there
if selected_state_m is not state_m and sm_id in self.model.state_machine_manager.state_machines:
self.model.selected_state_machine_id = sm_id
self.current_state_machine_m.selection.set(state_m)
return | python | def on_switch_page(self, notebook, page_pointer, page_num, user_param1=None):
"""Update state selection when the active tab was changed
"""
page = notebook.get_nth_page(page_num)
# find state of selected tab
for tab_info in list(self.tabs.values()):
if tab_info['page'] is page:
state_m = tab_info['state_m']
sm_id = state_m.state.get_state_machine().state_machine_id
selected_state_m = self.current_state_machine_m.selection.get_selected_state()
# If the state of the selected tab is not in the selection, set it there
if selected_state_m is not state_m and sm_id in self.model.state_machine_manager.state_machines:
self.model.selected_state_machine_id = sm_id
self.current_state_machine_m.selection.set(state_m)
return | [
"def",
"on_switch_page",
"(",
"self",
",",
"notebook",
",",
"page_pointer",
",",
"page_num",
",",
"user_param1",
"=",
"None",
")",
":",
"page",
"=",
"notebook",
".",
"get_nth_page",
"(",
"page_num",
")",
"# find state of selected tab",
"for",
"tab_info",
"in",
... | Update state selection when the active tab was changed | [
"Update",
"state",
"selection",
"when",
"the",
"active",
"tab",
"was",
"changed"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L473-L489 | train | 40,259 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.activate_state_tab | def activate_state_tab(self, state_m):
"""Opens the tab for the specified state model
The tab with the given state model is opened or set to foreground.
:param state_m: The desired state model (the selected state)
"""
# The current shown state differs from the desired one
current_state_m = self.get_current_state_m()
if current_state_m is not state_m:
state_identifier = self.get_state_identifier(state_m)
# The desired state is not open, yet
if state_identifier not in self.tabs:
# add tab for desired state
page_id = self.add_state_editor(state_m)
self.view.notebook.set_current_page(page_id)
# bring tab for desired state into foreground
else:
page = self.tabs[state_identifier]['page']
page_id = self.view.notebook.page_num(page)
self.view.notebook.set_current_page(page_id)
self.keep_only_sticked_and_selected_tabs() | python | def activate_state_tab(self, state_m):
"""Opens the tab for the specified state model
The tab with the given state model is opened or set to foreground.
:param state_m: The desired state model (the selected state)
"""
# The current shown state differs from the desired one
current_state_m = self.get_current_state_m()
if current_state_m is not state_m:
state_identifier = self.get_state_identifier(state_m)
# The desired state is not open, yet
if state_identifier not in self.tabs:
# add tab for desired state
page_id = self.add_state_editor(state_m)
self.view.notebook.set_current_page(page_id)
# bring tab for desired state into foreground
else:
page = self.tabs[state_identifier]['page']
page_id = self.view.notebook.page_num(page)
self.view.notebook.set_current_page(page_id)
self.keep_only_sticked_and_selected_tabs() | [
"def",
"activate_state_tab",
"(",
"self",
",",
"state_m",
")",
":",
"# The current shown state differs from the desired one",
"current_state_m",
"=",
"self",
".",
"get_current_state_m",
"(",
")",
"if",
"current_state_m",
"is",
"not",
"state_m",
":",
"state_identifier",
... | Opens the tab for the specified state model
The tab with the given state model is opened or set to foreground.
:param state_m: The desired state model (the selected state) | [
"Opens",
"the",
"tab",
"for",
"the",
"specified",
"state",
"model"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L491-L514 | train | 40,260 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.keep_only_sticked_and_selected_tabs | def keep_only_sticked_and_selected_tabs(self):
"""Close all tabs, except the currently active one and all sticked ones"""
# Only if the user didn't deactivate this behaviour
if not global_gui_config.get_config_value('KEEP_ONLY_STICKY_STATES_OPEN', True):
return
page_id = self.view.notebook.get_current_page()
# No tabs are open
if page_id == -1:
return
page = self.view.notebook.get_nth_page(page_id)
current_state_identifier = self.get_state_identifier_for_page(page)
states_to_be_closed = []
# Iterate over all tabs
for state_identifier, tab_info in list(self.tabs.items()):
# If the tab is currently open, keep it open
if current_state_identifier == state_identifier:
continue
# If the tab is sticky, keep it open
if tab_info['is_sticky']:
continue
# Otherwise close it
states_to_be_closed.append(state_identifier)
for state_identifier in states_to_be_closed:
self.close_page(state_identifier, delete=False) | python | def keep_only_sticked_and_selected_tabs(self):
"""Close all tabs, except the currently active one and all sticked ones"""
# Only if the user didn't deactivate this behaviour
if not global_gui_config.get_config_value('KEEP_ONLY_STICKY_STATES_OPEN', True):
return
page_id = self.view.notebook.get_current_page()
# No tabs are open
if page_id == -1:
return
page = self.view.notebook.get_nth_page(page_id)
current_state_identifier = self.get_state_identifier_for_page(page)
states_to_be_closed = []
# Iterate over all tabs
for state_identifier, tab_info in list(self.tabs.items()):
# If the tab is currently open, keep it open
if current_state_identifier == state_identifier:
continue
# If the tab is sticky, keep it open
if tab_info['is_sticky']:
continue
# Otherwise close it
states_to_be_closed.append(state_identifier)
for state_identifier in states_to_be_closed:
self.close_page(state_identifier, delete=False) | [
"def",
"keep_only_sticked_and_selected_tabs",
"(",
"self",
")",
":",
"# Only if the user didn't deactivate this behaviour",
"if",
"not",
"global_gui_config",
".",
"get_config_value",
"(",
"'KEEP_ONLY_STICKY_STATES_OPEN'",
",",
"True",
")",
":",
"return",
"page_id",
"=",
"se... | Close all tabs, except the currently active one and all sticked ones | [
"Close",
"all",
"tabs",
"except",
"the",
"currently",
"active",
"one",
"and",
"all",
"sticked",
"ones"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L516-L543 | train | 40,261 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.selection_notification | def selection_notification(self, model, property, info):
"""If a single state is selected, open the corresponding tab"""
if model is not self.current_state_machine_m or len(self.current_state_machine_m.ongoing_complex_actions) > 0:
return
state_machine_m = model
assert isinstance(state_machine_m.selection, Selection)
if len(state_machine_m.selection.states) == 1 and len(state_machine_m.selection) == 1:
self.activate_state_tab(state_machine_m.selection.get_selected_state()) | python | def selection_notification(self, model, property, info):
"""If a single state is selected, open the corresponding tab"""
if model is not self.current_state_machine_m or len(self.current_state_machine_m.ongoing_complex_actions) > 0:
return
state_machine_m = model
assert isinstance(state_machine_m.selection, Selection)
if len(state_machine_m.selection.states) == 1 and len(state_machine_m.selection) == 1:
self.activate_state_tab(state_machine_m.selection.get_selected_state()) | [
"def",
"selection_notification",
"(",
"self",
",",
"model",
",",
"property",
",",
"info",
")",
":",
"if",
"model",
"is",
"not",
"self",
".",
"current_state_machine_m",
"or",
"len",
"(",
"self",
".",
"current_state_machine_m",
".",
"ongoing_complex_actions",
")",... | If a single state is selected, open the corresponding tab | [
"If",
"a",
"single",
"state",
"is",
"selected",
"open",
"the",
"corresponding",
"tab"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L546-L553 | train | 40,262 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.notify_state_name_change | def notify_state_name_change(self, model, prop_name, info):
"""Checks whether the name of a state was changed and change the tab label accordingly
"""
# avoid updates or checks because of execution status updates
if is_execution_status_update_notification_from_state_machine_model(prop_name, info):
return
overview = NotificationOverview(info, False, self.__class__.__name__)
changed_model = overview['model'][-1]
method_name = overview['method_name'][-1]
if isinstance(changed_model, AbstractStateModel) and method_name in ['name', 'script_text']:
self.update_tab_label(changed_model) | python | def notify_state_name_change(self, model, prop_name, info):
"""Checks whether the name of a state was changed and change the tab label accordingly
"""
# avoid updates or checks because of execution status updates
if is_execution_status_update_notification_from_state_machine_model(prop_name, info):
return
overview = NotificationOverview(info, False, self.__class__.__name__)
changed_model = overview['model'][-1]
method_name = overview['method_name'][-1]
if isinstance(changed_model, AbstractStateModel) and method_name in ['name', 'script_text']:
self.update_tab_label(changed_model) | [
"def",
"notify_state_name_change",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"# avoid updates or checks because of execution status updates",
"if",
"is_execution_status_update_notification_from_state_machine_model",
"(",
"prop_name",
",",
"info",
")",
... | Checks whether the name of a state was changed and change the tab label accordingly | [
"Checks",
"whether",
"the",
"name",
"of",
"a",
"state",
"was",
"changed",
"and",
"change",
"the",
"tab",
"label",
"accordingly"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L556-L567 | train | 40,263 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.update_tab_label | def update_tab_label(self, state_m):
"""Update all tab labels
:param rafcon.state_machine.states.state.State state_m: State model who's tab label is to be updated
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier not in self.tabs and state_identifier not in self.closed_tabs:
return
tab_info = self.tabs[state_identifier] if state_identifier in self.tabs else self.closed_tabs[state_identifier]
page = tab_info['page']
set_tab_label_texts(page.title_label, state_m, tab_info['source_code_view_is_dirty']) | python | def update_tab_label(self, state_m):
"""Update all tab labels
:param rafcon.state_machine.states.state.State state_m: State model who's tab label is to be updated
"""
state_identifier = self.get_state_identifier(state_m)
if state_identifier not in self.tabs and state_identifier not in self.closed_tabs:
return
tab_info = self.tabs[state_identifier] if state_identifier in self.tabs else self.closed_tabs[state_identifier]
page = tab_info['page']
set_tab_label_texts(page.title_label, state_m, tab_info['source_code_view_is_dirty']) | [
"def",
"update_tab_label",
"(",
"self",
",",
"state_m",
")",
":",
"state_identifier",
"=",
"self",
".",
"get_state_identifier",
"(",
"state_m",
")",
"if",
"state_identifier",
"not",
"in",
"self",
".",
"tabs",
"and",
"state_identifier",
"not",
"in",
"self",
"."... | Update all tab labels
:param rafcon.state_machine.states.state.State state_m: State model who's tab label is to be updated | [
"Update",
"all",
"tab",
"labels"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L569-L579 | train | 40,264 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.get_state_identifier_for_page | def get_state_identifier_for_page(self, page):
"""Return the state identifier for a given page
"""
for identifier, page_info in list(self.tabs.items()):
if page_info["page"] is page: # reference comparison on purpose
return identifier | python | def get_state_identifier_for_page(self, page):
"""Return the state identifier for a given page
"""
for identifier, page_info in list(self.tabs.items()):
if page_info["page"] is page: # reference comparison on purpose
return identifier | [
"def",
"get_state_identifier_for_page",
"(",
"self",
",",
"page",
")",
":",
"for",
"identifier",
",",
"page_info",
"in",
"list",
"(",
"self",
".",
"tabs",
".",
"items",
"(",
")",
")",
":",
"if",
"page_info",
"[",
"\"page\"",
"]",
"is",
"page",
":",
"# ... | Return the state identifier for a given page | [
"Return",
"the",
"state",
"identifier",
"for",
"a",
"given",
"page"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L581-L586 | train | 40,265 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/states_editor.py | StatesEditorController.rename_selected_state | def rename_selected_state(self, key_value, modifier_mask):
"""Callback method for shortcut action rename
Searches for a single selected state model and open the according page. Page is created if it is not
existing. Then the rename method of the state controller is called.
:param key_value:
:param modifier_mask:
"""
selection = self.current_state_machine_m.selection
if len(selection.states) == 1 and len(selection) == 1:
selected_state = selection.get_selected_state()
self.activate_state_tab(selected_state)
_, state_identifier = self.find_page_of_state_m(selected_state)
state_controller = self.tabs[state_identifier]['controller']
state_controller.rename() | python | def rename_selected_state(self, key_value, modifier_mask):
"""Callback method for shortcut action rename
Searches for a single selected state model and open the according page. Page is created if it is not
existing. Then the rename method of the state controller is called.
:param key_value:
:param modifier_mask:
"""
selection = self.current_state_machine_m.selection
if len(selection.states) == 1 and len(selection) == 1:
selected_state = selection.get_selected_state()
self.activate_state_tab(selected_state)
_, state_identifier = self.find_page_of_state_m(selected_state)
state_controller = self.tabs[state_identifier]['controller']
state_controller.rename() | [
"def",
"rename_selected_state",
"(",
"self",
",",
"key_value",
",",
"modifier_mask",
")",
":",
"selection",
"=",
"self",
".",
"current_state_machine_m",
".",
"selection",
"if",
"len",
"(",
"selection",
".",
"states",
")",
"==",
"1",
"and",
"len",
"(",
"selec... | Callback method for shortcut action rename
Searches for a single selected state model and open the according page. Page is created if it is not
existing. Then the rename method of the state controller is called.
:param key_value:
:param modifier_mask: | [
"Callback",
"method",
"for",
"shortcut",
"action",
"rename"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L588-L603 | train | 40,266 |
DLR-RM/RAFCON | source/rafcon/core/id_generator.py | generate_semantic_data_key | def generate_semantic_data_key(used_semantic_keys):
""" Create a new and unique semantic data key
:param list used_semantic_keys: Handed list of keys already in use
:rtype: str
:return: semantic_data_id
"""
semantic_data_id_counter = -1
while True:
semantic_data_id_counter += 1
if "semantic data key " + str(semantic_data_id_counter) not in used_semantic_keys:
break
return "semantic data key " + str(semantic_data_id_counter) | python | def generate_semantic_data_key(used_semantic_keys):
""" Create a new and unique semantic data key
:param list used_semantic_keys: Handed list of keys already in use
:rtype: str
:return: semantic_data_id
"""
semantic_data_id_counter = -1
while True:
semantic_data_id_counter += 1
if "semantic data key " + str(semantic_data_id_counter) not in used_semantic_keys:
break
return "semantic data key " + str(semantic_data_id_counter) | [
"def",
"generate_semantic_data_key",
"(",
"used_semantic_keys",
")",
":",
"semantic_data_id_counter",
"=",
"-",
"1",
"while",
"True",
":",
"semantic_data_id_counter",
"+=",
"1",
"if",
"\"semantic data key \"",
"+",
"str",
"(",
"semantic_data_id_counter",
")",
"not",
"... | Create a new and unique semantic data key
:param list used_semantic_keys: Handed list of keys already in use
:rtype: str
:return: semantic_data_id | [
"Create",
"a",
"new",
"and",
"unique",
"semantic",
"data",
"key"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/id_generator.py#L90-L102 | train | 40,267 |
DLR-RM/RAFCON | source/rafcon/core/id_generator.py | state_id_generator | def state_id_generator(size=STATE_ID_LENGTH, chars=string.ascii_uppercase, used_state_ids=None):
""" Create a new and unique state id
Generates an id for a state. It randomly samples from random ascii uppercase letters size times
and concatenates them. If the id already exists it draws a new one.
:param size: the length of the generated keys
:param chars: the set of characters a sample draws from
:param list used_state_ids: Handed list of ids already in use
:rtype: str
:return: new_state_id
"""
new_state_id = ''.join(random.choice(chars) for x in range(size))
while used_state_ids is not None and new_state_id in used_state_ids:
new_state_id = ''.join(random.choice(chars) for x in range(size))
return new_state_id | python | def state_id_generator(size=STATE_ID_LENGTH, chars=string.ascii_uppercase, used_state_ids=None):
""" Create a new and unique state id
Generates an id for a state. It randomly samples from random ascii uppercase letters size times
and concatenates them. If the id already exists it draws a new one.
:param size: the length of the generated keys
:param chars: the set of characters a sample draws from
:param list used_state_ids: Handed list of ids already in use
:rtype: str
:return: new_state_id
"""
new_state_id = ''.join(random.choice(chars) for x in range(size))
while used_state_ids is not None and new_state_id in used_state_ids:
new_state_id = ''.join(random.choice(chars) for x in range(size))
return new_state_id | [
"def",
"state_id_generator",
"(",
"size",
"=",
"STATE_ID_LENGTH",
",",
"chars",
"=",
"string",
".",
"ascii_uppercase",
",",
"used_state_ids",
"=",
"None",
")",
":",
"new_state_id",
"=",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"chars",
")",
"f... | Create a new and unique state id
Generates an id for a state. It randomly samples from random ascii uppercase letters size times
and concatenates them. If the id already exists it draws a new one.
:param size: the length of the generated keys
:param chars: the set of characters a sample draws from
:param list used_state_ids: Handed list of ids already in use
:rtype: str
:return: new_state_id | [
"Create",
"a",
"new",
"and",
"unique",
"state",
"id"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/id_generator.py#L125-L140 | train | 40,268 |
DLR-RM/RAFCON | source/rafcon/core/id_generator.py | global_variable_id_generator | def global_variable_id_generator(size=10, chars=string.ascii_uppercase):
""" Create a new and unique global variable id
Generates an id for a global variable. It randomly samples from random ascii uppercase letters size times
and concatenates them. If the id already exists it draws a new one.
:param size: the length of the generated keys
:param chars: the set of characters a sample draws from
"""
new_global_variable_id = ''.join(random.choice(chars) for x in range(size))
while new_global_variable_id in used_global_variable_ids:
new_global_variable_id = ''.join(random.choice(chars) for x in range(size))
used_global_variable_ids.append(new_global_variable_id)
return new_global_variable_id | python | def global_variable_id_generator(size=10, chars=string.ascii_uppercase):
""" Create a new and unique global variable id
Generates an id for a global variable. It randomly samples from random ascii uppercase letters size times
and concatenates them. If the id already exists it draws a new one.
:param size: the length of the generated keys
:param chars: the set of characters a sample draws from
"""
new_global_variable_id = ''.join(random.choice(chars) for x in range(size))
while new_global_variable_id in used_global_variable_ids:
new_global_variable_id = ''.join(random.choice(chars) for x in range(size))
used_global_variable_ids.append(new_global_variable_id)
return new_global_variable_id | [
"def",
"global_variable_id_generator",
"(",
"size",
"=",
"10",
",",
"chars",
"=",
"string",
".",
"ascii_uppercase",
")",
":",
"new_global_variable_id",
"=",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"chars",
")",
"for",
"x",
"in",
"range",
"(",... | Create a new and unique global variable id
Generates an id for a global variable. It randomly samples from random ascii uppercase letters size times
and concatenates them. If the id already exists it draws a new one.
:param size: the length of the generated keys
:param chars: the set of characters a sample draws from | [
"Create",
"a",
"new",
"and",
"unique",
"global",
"variable",
"id"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/id_generator.py#L143-L156 | train | 40,269 |
DLR-RM/RAFCON | source/rafcon/gui/views/graphical_editor.py | Color.set | def set(self):
"""Set the color as current OpenGL color
"""
glColor4f(self.r, self.g, self.b, self.a) | python | def set(self):
"""Set the color as current OpenGL color
"""
glColor4f(self.r, self.g, self.b, self.a) | [
"def",
"set",
"(",
"self",
")",
":",
"glColor4f",
"(",
"self",
".",
"r",
",",
"self",
".",
"g",
",",
"self",
".",
"b",
",",
"self",
".",
"a",
")"
] | Set the color as current OpenGL color | [
"Set",
"the",
"color",
"as",
"current",
"OpenGL",
"color"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/graphical_editor.py#L137-L140 | train | 40,270 |
DLR-RM/RAFCON | source/rafcon/gui/views/graphical_editor.py | GraphicalEditor.pixel_to_size_ratio | def pixel_to_size_ratio(self):
"""Calculates the ratio between pixel and OpenGL distances
OpenGL keeps its own coordinate system. This method can be used to transform between pixel and OpenGL
coordinates.
:return: pixel/size ratio
"""
left, right, _, _ = self.get_view_coordinates()
width = right - left
display_width = self.get_allocation().width
return display_width / float(width) | python | def pixel_to_size_ratio(self):
"""Calculates the ratio between pixel and OpenGL distances
OpenGL keeps its own coordinate system. This method can be used to transform between pixel and OpenGL
coordinates.
:return: pixel/size ratio
"""
left, right, _, _ = self.get_view_coordinates()
width = right - left
display_width = self.get_allocation().width
return display_width / float(width) | [
"def",
"pixel_to_size_ratio",
"(",
"self",
")",
":",
"left",
",",
"right",
",",
"_",
",",
"_",
"=",
"self",
".",
"get_view_coordinates",
"(",
")",
"width",
"=",
"right",
"-",
"left",
"display_width",
"=",
"self",
".",
"get_allocation",
"(",
")",
".",
"... | Calculates the ratio between pixel and OpenGL distances
OpenGL keeps its own coordinate system. This method can be used to transform between pixel and OpenGL
coordinates.
:return: pixel/size ratio | [
"Calculates",
"the",
"ratio",
"between",
"pixel",
"and",
"OpenGL",
"distances"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/graphical_editor.py#L295-L306 | train | 40,271 |
DLR-RM/RAFCON | source/rafcon/gui/views/graphical_editor.py | GraphicalEditor.expose_init | def expose_init(self, *args):
"""Process the drawing routine
"""
# Obtain a reference to the OpenGL drawable
# and rendering context.
gldrawable = self.get_gl_drawable()
glcontext = self.get_gl_context()
# OpenGL begin
if not gldrawable or not gldrawable.gl_begin(glcontext):
return False
# logger.debug("expose_init")
# Reset buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# Prepare name stack
glInitNames()
glPushName(0)
self.name_counter = 1
return False | python | def expose_init(self, *args):
"""Process the drawing routine
"""
# Obtain a reference to the OpenGL drawable
# and rendering context.
gldrawable = self.get_gl_drawable()
glcontext = self.get_gl_context()
# OpenGL begin
if not gldrawable or not gldrawable.gl_begin(glcontext):
return False
# logger.debug("expose_init")
# Reset buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# Prepare name stack
glInitNames()
glPushName(0)
self.name_counter = 1
return False | [
"def",
"expose_init",
"(",
"self",
",",
"*",
"args",
")",
":",
"# Obtain a reference to the OpenGL drawable",
"# and rendering context.",
"gldrawable",
"=",
"self",
".",
"get_gl_drawable",
"(",
")",
"glcontext",
"=",
"self",
".",
"get_gl_context",
"(",
")",
"# OpenG... | Process the drawing routine | [
"Process",
"the",
"drawing",
"routine"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/graphical_editor.py#L308-L330 | train | 40,272 |
DLR-RM/RAFCON | source/rafcon/gui/views/graphical_editor.py | GraphicalEditor.expose_finish | def expose_finish(self, *args):
"""Finish drawing process
"""
# Obtain a reference to the OpenGL drawable
# and rendering context.
gldrawable = self.get_gl_drawable()
# glcontext = self.get_gl_context()
if not gldrawable:
return
# Put the buffer on the screen!
if gldrawable.is_double_buffered():
gldrawable.swap_buffers()
else:
glFlush()
# OpenGL end
gldrawable.gl_end() | python | def expose_finish(self, *args):
"""Finish drawing process
"""
# Obtain a reference to the OpenGL drawable
# and rendering context.
gldrawable = self.get_gl_drawable()
# glcontext = self.get_gl_context()
if not gldrawable:
return
# Put the buffer on the screen!
if gldrawable.is_double_buffered():
gldrawable.swap_buffers()
else:
glFlush()
# OpenGL end
gldrawable.gl_end() | [
"def",
"expose_finish",
"(",
"self",
",",
"*",
"args",
")",
":",
"# Obtain a reference to the OpenGL drawable",
"# and rendering context.",
"gldrawable",
"=",
"self",
".",
"get_gl_drawable",
"(",
")",
"# glcontext = self.get_gl_context()",
"if",
"not",
"gldrawable",
":",
... | Finish drawing process | [
"Finish",
"drawing",
"process"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/graphical_editor.py#L332-L350 | train | 40,273 |
DLR-RM/RAFCON | source/rafcon/gui/views/graphical_editor.py | GraphicalEditor._write_string | def _write_string(self, string, pos_x, pos_y, height, color, bold=False, align_right=False, depth=0.):
"""Write a string
Writes a string with a simple OpenGL method in the given size at the given position.
:param string: The string to draw
:param pos_x: x starting position
:param pos_y: y starting position
:param height: desired height
:param bold: flag whether to use a bold font
:param depth: the Z layer
"""
stroke_width = height / 8.
if bold:
stroke_width = height / 5.
color.set()
self._set_closest_stroke_width(stroke_width)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
pos_y -= height
if not align_right:
glTranslatef(pos_x, pos_y, depth)
else:
width = self._string_width(string, height)
glTranslatef(pos_x - width, pos_y, depth)
font_height = 119.5 # According to https://www.opengl.org/resources/libraries/glut/spec3/node78.html
scale_factor = height / font_height
glScalef(scale_factor, scale_factor, scale_factor)
for c in string:
# glTranslatef(0, 0, 0)
glutStrokeCharacter(GLUT_STROKE_ROMAN, ord(c))
# width = glutStrokeWidth(GLUT_STROKE_ROMAN, ord(c))
glPopMatrix() | python | def _write_string(self, string, pos_x, pos_y, height, color, bold=False, align_right=False, depth=0.):
"""Write a string
Writes a string with a simple OpenGL method in the given size at the given position.
:param string: The string to draw
:param pos_x: x starting position
:param pos_y: y starting position
:param height: desired height
:param bold: flag whether to use a bold font
:param depth: the Z layer
"""
stroke_width = height / 8.
if bold:
stroke_width = height / 5.
color.set()
self._set_closest_stroke_width(stroke_width)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
pos_y -= height
if not align_right:
glTranslatef(pos_x, pos_y, depth)
else:
width = self._string_width(string, height)
glTranslatef(pos_x - width, pos_y, depth)
font_height = 119.5 # According to https://www.opengl.org/resources/libraries/glut/spec3/node78.html
scale_factor = height / font_height
glScalef(scale_factor, scale_factor, scale_factor)
for c in string:
# glTranslatef(0, 0, 0)
glutStrokeCharacter(GLUT_STROKE_ROMAN, ord(c))
# width = glutStrokeWidth(GLUT_STROKE_ROMAN, ord(c))
glPopMatrix() | [
"def",
"_write_string",
"(",
"self",
",",
"string",
",",
"pos_x",
",",
"pos_y",
",",
"height",
",",
"color",
",",
"bold",
"=",
"False",
",",
"align_right",
"=",
"False",
",",
"depth",
"=",
"0.",
")",
":",
"stroke_width",
"=",
"height",
"/",
"8.",
"if... | Write a string
Writes a string with a simple OpenGL method in the given size at the given position.
:param string: The string to draw
:param pos_x: x starting position
:param pos_y: y starting position
:param height: desired height
:param bold: flag whether to use a bold font
:param depth: the Z layer | [
"Write",
"a",
"string"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/graphical_editor.py#L704-L737 | train | 40,274 |
DLR-RM/RAFCON | source/rafcon/gui/views/graphical_editor.py | GraphicalEditor.prepare_selection | def prepare_selection(self, pos_x, pos_y, width, height):
"""Prepares the selection rendering
In order to find out the object being clicked on, the scene has to be rendered again around the clicked position
:param pos_x: x coordinate
:param pos_y: y coordinate
"""
glSelectBuffer(self.name_counter * 6)
viewport = glGetInteger(GL_VIEWPORT)
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glRenderMode(GL_SELECT)
glLoadIdentity()
if width < 1:
width = 1
if height < 1:
height = 1
pos_x += width / 2.
pos_y += height / 2.
# The system y axis is inverse to the OpenGL y axis
gluPickMatrix(pos_x, viewport[3] - pos_y + viewport[1], width, height, viewport)
self._apply_orthogonal_view() | python | def prepare_selection(self, pos_x, pos_y, width, height):
"""Prepares the selection rendering
In order to find out the object being clicked on, the scene has to be rendered again around the clicked position
:param pos_x: x coordinate
:param pos_y: y coordinate
"""
glSelectBuffer(self.name_counter * 6)
viewport = glGetInteger(GL_VIEWPORT)
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glRenderMode(GL_SELECT)
glLoadIdentity()
if width < 1:
width = 1
if height < 1:
height = 1
pos_x += width / 2.
pos_y += height / 2.
# The system y axis is inverse to the OpenGL y axis
gluPickMatrix(pos_x, viewport[3] - pos_y + viewport[1], width, height, viewport)
self._apply_orthogonal_view() | [
"def",
"prepare_selection",
"(",
"self",
",",
"pos_x",
",",
"pos_y",
",",
"width",
",",
"height",
")",
":",
"glSelectBuffer",
"(",
"self",
".",
"name_counter",
"*",
"6",
")",
"viewport",
"=",
"glGetInteger",
"(",
"GL_VIEWPORT",
")",
"glMatrixMode",
"(",
"G... | Prepares the selection rendering
In order to find out the object being clicked on, the scene has to be rendered again around the clicked position
:param pos_x: x coordinate
:param pos_y: y coordinate | [
"Prepares",
"the",
"selection",
"rendering"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/graphical_editor.py#L748-L775 | train | 40,275 |
DLR-RM/RAFCON | source/rafcon/gui/views/graphical_editor.py | GraphicalEditor.find_selection | def find_selection():
"""Finds the selected ids
After the scene has been rendered again in selection mode, this method gathers and returns the ids of the
selected object and restores the matrices.
:return: The selection stack
"""
hits = glRenderMode(GL_RENDER)
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
return hits | python | def find_selection():
"""Finds the selected ids
After the scene has been rendered again in selection mode, this method gathers and returns the ids of the
selected object and restores the matrices.
:return: The selection stack
"""
hits = glRenderMode(GL_RENDER)
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
return hits | [
"def",
"find_selection",
"(",
")",
":",
"hits",
"=",
"glRenderMode",
"(",
"GL_RENDER",
")",
"glMatrixMode",
"(",
"GL_PROJECTION",
")",
"glPopMatrix",
"(",
")",
"glMatrixMode",
"(",
"GL_MODELVIEW",
")",
"return",
"hits"
] | Finds the selected ids
After the scene has been rendered again in selection mode, this method gathers and returns the ids of the
selected object and restores the matrices.
:return: The selection stack | [
"Finds",
"the",
"selected",
"ids"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/graphical_editor.py#L778-L792 | train | 40,276 |
DLR-RM/RAFCON | source/rafcon/gui/views/graphical_editor.py | GraphicalEditor._set_closest_stroke_width | def _set_closest_stroke_width(self, width):
"""Sets the line width to the closest supported one
Not all line widths are supported. This function queries both minimum and maximum as well as the step size of
the line width and calculates the width, which is closest to the given one. This width is then set.
:param width: The desired line width
"""
# Adapt line width to zooming level
width *= self.pixel_to_size_ratio() / 6.
stroke_width_range = glGetFloatv(GL_LINE_WIDTH_RANGE)
stroke_width_granularity = glGetFloatv(GL_LINE_WIDTH_GRANULARITY)
if width < stroke_width_range[0]:
glLineWidth(stroke_width_range[0])
return
if width > stroke_width_range[1]:
glLineWidth(stroke_width_range[1])
return
glLineWidth(round(width / stroke_width_granularity) * stroke_width_granularity) | python | def _set_closest_stroke_width(self, width):
"""Sets the line width to the closest supported one
Not all line widths are supported. This function queries both minimum and maximum as well as the step size of
the line width and calculates the width, which is closest to the given one. This width is then set.
:param width: The desired line width
"""
# Adapt line width to zooming level
width *= self.pixel_to_size_ratio() / 6.
stroke_width_range = glGetFloatv(GL_LINE_WIDTH_RANGE)
stroke_width_granularity = glGetFloatv(GL_LINE_WIDTH_GRANULARITY)
if width < stroke_width_range[0]:
glLineWidth(stroke_width_range[0])
return
if width > stroke_width_range[1]:
glLineWidth(stroke_width_range[1])
return
glLineWidth(round(width / stroke_width_granularity) * stroke_width_granularity) | [
"def",
"_set_closest_stroke_width",
"(",
"self",
",",
"width",
")",
":",
"# Adapt line width to zooming level",
"width",
"*=",
"self",
".",
"pixel_to_size_ratio",
"(",
")",
"/",
"6.",
"stroke_width_range",
"=",
"glGetFloatv",
"(",
"GL_LINE_WIDTH_RANGE",
")",
"stroke_w... | Sets the line width to the closest supported one
Not all line widths are supported. This function queries both minimum and maximum as well as the step size of
the line width and calculates the width, which is closest to the given one. This width is then set.
:param width: The desired line width | [
"Sets",
"the",
"line",
"width",
"to",
"the",
"closest",
"supported",
"one"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/graphical_editor.py#L802-L822 | train | 40,277 |
DLR-RM/RAFCON | source/rafcon/gui/views/graphical_editor.py | GraphicalEditor._draw_circle | def _draw_circle(self, pos_x, pos_y, radius, depth, stroke_width=1., fill_color=None, border_color=None,
from_angle=0., to_angle=2 * pi):
"""Draws a circle
Draws a circle with a line segment a desired position with desired size.
:param float pos_x: Center x position
:param float pos_y: Center y position
:param float depth: The Z layer
:param float radius: Radius of the circle
"""
visible = False
# Check whether circle center is in the viewport
if not self.point_outside_view((pos_x, pos_y)):
visible = True
# Check whether at least on point on the border of the circle is within the viewport
if not visible:
for i in range(0, 8):
angle = 2 * pi / 8. * i
x = pos_x + cos(angle) * radius
y = pos_y + sin(angle) * radius
if not self.point_outside_view((x, y)):
visible = True
break
if not visible:
return False
angle_sum = to_angle - from_angle
if angle_sum < 0:
angle_sum = float(to_angle + 2 * pi - from_angle)
segments = self.pixel_to_size_ratio() * radius * 1.5
segments = max(4, segments)
segments = int(round(segments * angle_sum / (2. * pi)))
types = []
if fill_color is not None:
types.append(GL_POLYGON)
if border_color is not None:
types.append(GL_LINE_LOOP)
for type in types:
if type == GL_POLYGON:
fill_color.set()
else:
self._set_closest_stroke_width(stroke_width)
border_color.set()
glBegin(type)
angle = from_angle
for i in range(0, segments):
x = pos_x + cos(angle) * radius
y = pos_y + sin(angle) * radius
glVertex3f(x, y, depth)
angle += angle_sum / (segments - 1)
if angle > 2 * pi:
angle -= 2 * pi
if i == segments - 2:
angle = to_angle
glEnd()
return True | python | def _draw_circle(self, pos_x, pos_y, radius, depth, stroke_width=1., fill_color=None, border_color=None,
from_angle=0., to_angle=2 * pi):
"""Draws a circle
Draws a circle with a line segment a desired position with desired size.
:param float pos_x: Center x position
:param float pos_y: Center y position
:param float depth: The Z layer
:param float radius: Radius of the circle
"""
visible = False
# Check whether circle center is in the viewport
if not self.point_outside_view((pos_x, pos_y)):
visible = True
# Check whether at least on point on the border of the circle is within the viewport
if not visible:
for i in range(0, 8):
angle = 2 * pi / 8. * i
x = pos_x + cos(angle) * radius
y = pos_y + sin(angle) * radius
if not self.point_outside_view((x, y)):
visible = True
break
if not visible:
return False
angle_sum = to_angle - from_angle
if angle_sum < 0:
angle_sum = float(to_angle + 2 * pi - from_angle)
segments = self.pixel_to_size_ratio() * radius * 1.5
segments = max(4, segments)
segments = int(round(segments * angle_sum / (2. * pi)))
types = []
if fill_color is not None:
types.append(GL_POLYGON)
if border_color is not None:
types.append(GL_LINE_LOOP)
for type in types:
if type == GL_POLYGON:
fill_color.set()
else:
self._set_closest_stroke_width(stroke_width)
border_color.set()
glBegin(type)
angle = from_angle
for i in range(0, segments):
x = pos_x + cos(angle) * radius
y = pos_y + sin(angle) * radius
glVertex3f(x, y, depth)
angle += angle_sum / (segments - 1)
if angle > 2 * pi:
angle -= 2 * pi
if i == segments - 2:
angle = to_angle
glEnd()
return True | [
"def",
"_draw_circle",
"(",
"self",
",",
"pos_x",
",",
"pos_y",
",",
"radius",
",",
"depth",
",",
"stroke_width",
"=",
"1.",
",",
"fill_color",
"=",
"None",
",",
"border_color",
"=",
"None",
",",
"from_angle",
"=",
"0.",
",",
"to_angle",
"=",
"2",
"*",... | Draws a circle
Draws a circle with a line segment a desired position with desired size.
:param float pos_x: Center x position
:param float pos_y: Center y position
:param float depth: The Z layer
:param float radius: Radius of the circle | [
"Draws",
"a",
"circle"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/graphical_editor.py#L915-L975 | train | 40,278 |
DLR-RM/RAFCON | source/rafcon/gui/views/graphical_editor.py | GraphicalEditor._apply_orthogonal_view | def _apply_orthogonal_view(self):
"""Orthogonal view with respect to current aspect ratio
"""
left, right, bottom, top = self.get_view_coordinates()
glOrtho(left, right, bottom, top, -10, 0) | python | def _apply_orthogonal_view(self):
"""Orthogonal view with respect to current aspect ratio
"""
left, right, bottom, top = self.get_view_coordinates()
glOrtho(left, right, bottom, top, -10, 0) | [
"def",
"_apply_orthogonal_view",
"(",
"self",
")",
":",
"left",
",",
"right",
",",
"bottom",
",",
"top",
"=",
"self",
".",
"get_view_coordinates",
"(",
")",
"glOrtho",
"(",
"left",
",",
"right",
",",
"bottom",
",",
"top",
",",
"-",
"10",
",",
"0",
")... | Orthogonal view with respect to current aspect ratio | [
"Orthogonal",
"view",
"with",
"respect",
"to",
"current",
"aspect",
"ratio"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/graphical_editor.py#L1018-L1022 | train | 40,279 |
openego/eTraGo | etrago/cluster/snapshot.py | update_data_frames | def update_data_frames(network, cluster_weights, dates, hours):
""" Updates the snapshots, snapshots weights and the dataframes based on
the original data in the network and the medoids created by clustering
these original data.
Parameters
-----------
network : pyPSA network object
cluster_weights: dictionary
dates: Datetimeindex
Returns
-------
network
"""
network.snapshot_weightings = network.snapshot_weightings.loc[dates]
network.snapshots = network.snapshot_weightings.index
# set new snapshot weights from cluster_weights
snapshot_weightings = []
for i in cluster_weights.values():
x = 0
while x < hours:
snapshot_weightings.append(i)
x += 1
for i in range(len(network.snapshot_weightings)):
network.snapshot_weightings[i] = snapshot_weightings[i]
# put the snapshot in the right order
network.snapshots.sort_values()
network.snapshot_weightings.sort_index()
return network | python | def update_data_frames(network, cluster_weights, dates, hours):
""" Updates the snapshots, snapshots weights and the dataframes based on
the original data in the network and the medoids created by clustering
these original data.
Parameters
-----------
network : pyPSA network object
cluster_weights: dictionary
dates: Datetimeindex
Returns
-------
network
"""
network.snapshot_weightings = network.snapshot_weightings.loc[dates]
network.snapshots = network.snapshot_weightings.index
# set new snapshot weights from cluster_weights
snapshot_weightings = []
for i in cluster_weights.values():
x = 0
while x < hours:
snapshot_weightings.append(i)
x += 1
for i in range(len(network.snapshot_weightings)):
network.snapshot_weightings[i] = snapshot_weightings[i]
# put the snapshot in the right order
network.snapshots.sort_values()
network.snapshot_weightings.sort_index()
return network | [
"def",
"update_data_frames",
"(",
"network",
",",
"cluster_weights",
",",
"dates",
",",
"hours",
")",
":",
"network",
".",
"snapshot_weightings",
"=",
"network",
".",
"snapshot_weightings",
".",
"loc",
"[",
"dates",
"]",
"network",
".",
"snapshots",
"=",
"netw... | Updates the snapshots, snapshots weights and the dataframes based on
the original data in the network and the medoids created by clustering
these original data.
Parameters
-----------
network : pyPSA network object
cluster_weights: dictionary
dates: Datetimeindex
Returns
-------
network | [
"Updates",
"the",
"snapshots",
"snapshots",
"weights",
"and",
"the",
"dataframes",
"based",
"on",
"the",
"original",
"data",
"in",
"the",
"network",
"and",
"the",
"medoids",
"created",
"by",
"clustering",
"these",
"original",
"data",
"."
] | 2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9 | https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/cluster/snapshot.py#L145-L179 | train | 40,280 |
openego/eTraGo | etrago/cluster/snapshot.py | daily_bounds | def daily_bounds(network, snapshots):
""" This will bound the storage level to 0.5 max_level every 24th hour.
"""
sus = network.storage_units
# take every first hour of the clustered days
network.model.period_starts = network.snapshot_weightings.index[0::24]
network.model.storages = sus.index
def day_rule(m, s, p):
"""
Sets the soc of the every first hour to the soc of the last hour
of the day (i.e. + 23 hours)
"""
return (
m.state_of_charge[s, p] ==
m.state_of_charge[s, p + pd.Timedelta(hours=23)])
network.model.period_bound = po.Constraint(
network.model.storages, network.model.period_starts, rule=day_rule) | python | def daily_bounds(network, snapshots):
""" This will bound the storage level to 0.5 max_level every 24th hour.
"""
sus = network.storage_units
# take every first hour of the clustered days
network.model.period_starts = network.snapshot_weightings.index[0::24]
network.model.storages = sus.index
def day_rule(m, s, p):
"""
Sets the soc of the every first hour to the soc of the last hour
of the day (i.e. + 23 hours)
"""
return (
m.state_of_charge[s, p] ==
m.state_of_charge[s, p + pd.Timedelta(hours=23)])
network.model.period_bound = po.Constraint(
network.model.storages, network.model.period_starts, rule=day_rule) | [
"def",
"daily_bounds",
"(",
"network",
",",
"snapshots",
")",
":",
"sus",
"=",
"network",
".",
"storage_units",
"# take every first hour of the clustered days",
"network",
".",
"model",
".",
"period_starts",
"=",
"network",
".",
"snapshot_weightings",
".",
"index",
... | This will bound the storage level to 0.5 max_level every 24th hour. | [
"This",
"will",
"bound",
"the",
"storage",
"level",
"to",
"0",
".",
"5",
"max_level",
"every",
"24th",
"hour",
"."
] | 2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9 | https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/cluster/snapshot.py#L182-L202 | train | 40,281 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_editor/scoped_variable_list.py | ScopedVariableListController.on_add | def on_add(self, widget, data=None):
"""Create a new scoped variable with default values"""
if isinstance(self.model, ContainerStateModel):
try:
scoped_var_ids = gui_helper_state_machine.add_scoped_variable_to_selected_states(selected_states=[self.model])
if scoped_var_ids:
self.select_entry(scoped_var_ids[self.model.state])
except ValueError as e:
logger.warning("The scoped variable couldn't be added: {0}".format(e))
return False
return True | python | def on_add(self, widget, data=None):
"""Create a new scoped variable with default values"""
if isinstance(self.model, ContainerStateModel):
try:
scoped_var_ids = gui_helper_state_machine.add_scoped_variable_to_selected_states(selected_states=[self.model])
if scoped_var_ids:
self.select_entry(scoped_var_ids[self.model.state])
except ValueError as e:
logger.warning("The scoped variable couldn't be added: {0}".format(e))
return False
return True | [
"def",
"on_add",
"(",
"self",
",",
"widget",
",",
"data",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"model",
",",
"ContainerStateModel",
")",
":",
"try",
":",
"scoped_var_ids",
"=",
"gui_helper_state_machine",
".",
"add_scoped_variable_to_se... | Create a new scoped variable with default values | [
"Create",
"a",
"new",
"scoped",
"variable",
"with",
"default",
"values"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/scoped_variable_list.py#L137-L148 | train | 40,282 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_editor/scoped_variable_list.py | ScopedVariableListController.remove_core_element | def remove_core_element(self, model):
"""Remove respective core element of handed scoped variable model
:param ScopedVariableModel model: Scoped variable model which core element should be removed
:return:
"""
assert model.scoped_variable.parent is self.model.state
gui_helper_state_machine.delete_core_element_of_model(model) | python | def remove_core_element(self, model):
"""Remove respective core element of handed scoped variable model
:param ScopedVariableModel model: Scoped variable model which core element should be removed
:return:
"""
assert model.scoped_variable.parent is self.model.state
gui_helper_state_machine.delete_core_element_of_model(model) | [
"def",
"remove_core_element",
"(",
"self",
",",
"model",
")",
":",
"assert",
"model",
".",
"scoped_variable",
".",
"parent",
"is",
"self",
".",
"model",
".",
"state",
"gui_helper_state_machine",
".",
"delete_core_element_of_model",
"(",
"model",
")"
] | Remove respective core element of handed scoped variable model
:param ScopedVariableModel model: Scoped variable model which core element should be removed
:return: | [
"Remove",
"respective",
"core",
"element",
"of",
"handed",
"scoped",
"variable",
"model"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/scoped_variable_list.py#L150-L157 | train | 40,283 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_editor/scoped_variable_list.py | ScopedVariableListController.apply_new_scoped_variable_name | def apply_new_scoped_variable_name(self, path, new_name):
"""Applies the new name of the scoped variable defined by path
:param str path: The path identifying the edited variable
:param str new_name: New name
"""
data_port_id = self.list_store[path][self.ID_STORAGE_ID]
try:
if self.model.state.scoped_variables[data_port_id].name != new_name:
self.model.state.scoped_variables[data_port_id].name = new_name
except TypeError as e:
logger.error("Error while changing port name: {0}".format(e)) | python | def apply_new_scoped_variable_name(self, path, new_name):
"""Applies the new name of the scoped variable defined by path
:param str path: The path identifying the edited variable
:param str new_name: New name
"""
data_port_id = self.list_store[path][self.ID_STORAGE_ID]
try:
if self.model.state.scoped_variables[data_port_id].name != new_name:
self.model.state.scoped_variables[data_port_id].name = new_name
except TypeError as e:
logger.error("Error while changing port name: {0}".format(e)) | [
"def",
"apply_new_scoped_variable_name",
"(",
"self",
",",
"path",
",",
"new_name",
")",
":",
"data_port_id",
"=",
"self",
".",
"list_store",
"[",
"path",
"]",
"[",
"self",
".",
"ID_STORAGE_ID",
"]",
"try",
":",
"if",
"self",
".",
"model",
".",
"state",
... | Applies the new name of the scoped variable defined by path
:param str path: The path identifying the edited variable
:param str new_name: New name | [
"Applies",
"the",
"new",
"name",
"of",
"the",
"scoped",
"variable",
"defined",
"by",
"path"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/scoped_variable_list.py#L159-L170 | train | 40,284 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_editor/scoped_variable_list.py | ScopedVariableListController.apply_new_scoped_variable_type | def apply_new_scoped_variable_type(self, path, new_variable_type_str):
"""Applies the new data type of the scoped variable defined by path
:param str path: The path identifying the edited variable
:param str new_variable_type_str: New data type as str
"""
data_port_id = self.list_store[path][self.ID_STORAGE_ID]
try:
if self.model.state.scoped_variables[data_port_id].data_type.__name__ != new_variable_type_str:
self.model.state.scoped_variables[data_port_id].change_data_type(new_variable_type_str)
except ValueError as e:
logger.error("Error while changing data type: {0}".format(e)) | python | def apply_new_scoped_variable_type(self, path, new_variable_type_str):
"""Applies the new data type of the scoped variable defined by path
:param str path: The path identifying the edited variable
:param str new_variable_type_str: New data type as str
"""
data_port_id = self.list_store[path][self.ID_STORAGE_ID]
try:
if self.model.state.scoped_variables[data_port_id].data_type.__name__ != new_variable_type_str:
self.model.state.scoped_variables[data_port_id].change_data_type(new_variable_type_str)
except ValueError as e:
logger.error("Error while changing data type: {0}".format(e)) | [
"def",
"apply_new_scoped_variable_type",
"(",
"self",
",",
"path",
",",
"new_variable_type_str",
")",
":",
"data_port_id",
"=",
"self",
".",
"list_store",
"[",
"path",
"]",
"[",
"self",
".",
"ID_STORAGE_ID",
"]",
"try",
":",
"if",
"self",
".",
"model",
".",
... | Applies the new data type of the scoped variable defined by path
:param str path: The path identifying the edited variable
:param str new_variable_type_str: New data type as str | [
"Applies",
"the",
"new",
"data",
"type",
"of",
"the",
"scoped",
"variable",
"defined",
"by",
"path"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/scoped_variable_list.py#L172-L183 | train | 40,285 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_editor/scoped_variable_list.py | ScopedVariableListController.apply_new_scoped_variable_default_value | def apply_new_scoped_variable_default_value(self, path, new_default_value_str):
"""Applies the new default value of the scoped variable defined by path
:param str path: The path identifying the edited variable
:param str new_default_value_str: New default value as string
"""
data_port_id = self.get_list_store_row_from_cursor_selection()[self.ID_STORAGE_ID]
try:
if str(self.model.state.scoped_variables[data_port_id].default_value) != new_default_value_str:
self.model.state.scoped_variables[data_port_id].default_value = new_default_value_str
except (TypeError, AttributeError) as e:
logger.error("Error while changing default value: {0}".format(e)) | python | def apply_new_scoped_variable_default_value(self, path, new_default_value_str):
"""Applies the new default value of the scoped variable defined by path
:param str path: The path identifying the edited variable
:param str new_default_value_str: New default value as string
"""
data_port_id = self.get_list_store_row_from_cursor_selection()[self.ID_STORAGE_ID]
try:
if str(self.model.state.scoped_variables[data_port_id].default_value) != new_default_value_str:
self.model.state.scoped_variables[data_port_id].default_value = new_default_value_str
except (TypeError, AttributeError) as e:
logger.error("Error while changing default value: {0}".format(e)) | [
"def",
"apply_new_scoped_variable_default_value",
"(",
"self",
",",
"path",
",",
"new_default_value_str",
")",
":",
"data_port_id",
"=",
"self",
".",
"get_list_store_row_from_cursor_selection",
"(",
")",
"[",
"self",
".",
"ID_STORAGE_ID",
"]",
"try",
":",
"if",
"str... | Applies the new default value of the scoped variable 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",
"scoped",
"variable",
"defined",
"by",
"path"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/scoped_variable_list.py#L185-L196 | train | 40,286 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_editor/scoped_variable_list.py | ScopedVariableListController.reload_scoped_variables_list_store | def reload_scoped_variables_list_store(self):
"""Reloads the scoped variable list store from the data port models"""
if isinstance(self.model, ContainerStateModel):
tmp = self.get_new_list_store()
for sv_model in self.model.scoped_variables:
data_type = sv_model.scoped_variable.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
tmp.append([sv_model.scoped_variable.name, data_type_name,
str(sv_model.scoped_variable.default_value), sv_model.scoped_variable.data_port_id,
sv_model])
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[:])
else:
raise RuntimeError("The reload_scoped_variables_list_store function should be never called for "
"a non Container State Model") | python | def reload_scoped_variables_list_store(self):
"""Reloads the scoped variable list store from the data port models"""
if isinstance(self.model, ContainerStateModel):
tmp = self.get_new_list_store()
for sv_model in self.model.scoped_variables:
data_type = sv_model.scoped_variable.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
tmp.append([sv_model.scoped_variable.name, data_type_name,
str(sv_model.scoped_variable.default_value), sv_model.scoped_variable.data_port_id,
sv_model])
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[:])
else:
raise RuntimeError("The reload_scoped_variables_list_store function should be never called for "
"a non Container State Model") | [
"def",
"reload_scoped_variables_list_store",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"model",
",",
"ContainerStateModel",
")",
":",
"tmp",
"=",
"self",
".",
"get_new_list_store",
"(",
")",
"for",
"sv_model",
"in",
"self",
".",
"model",
"... | Reloads the scoped variable list store from the data port models | [
"Reloads",
"the",
"scoped",
"variable",
"list",
"store",
"from",
"the",
"data",
"port",
"models"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/scoped_variable_list.py#L201-L228 | train | 40,287 |
DLR-RM/RAFCON | source/rafcon/gui/backup/session.py | store_session | def store_session():
""" Stores reference backup information for all open tabs into runtime config
The backup of never stored tabs (state machines) and not stored state machine changes will be triggered a last
time to secure data lose.
"""
from rafcon.gui.singleton import state_machine_manager_model, global_runtime_config
from rafcon.gui.models.auto_backup import AutoBackupModel
from rafcon.gui.models import AbstractStateModel
from rafcon.gui.singleton import main_window_controller
# check if there are dirty state machines -> use backup file structure maybe it is already stored
for sm_m in state_machine_manager_model.state_machines.values():
if sm_m.auto_backup:
if sm_m.state_machine.marked_dirty:
sm_m.auto_backup.perform_temp_storage()
else:
# generate a backup
sm_m.auto_backup = AutoBackupModel(sm_m)
# collect order of tab state machine ids from state machines editor and find selected state machine page number
state_machines_editor_ctrl = main_window_controller.get_controller('state_machines_editor_ctrl')
number_of_pages = state_machines_editor_ctrl.view['notebook'].get_n_pages()
selected_page_number = None
list_of_tab_meta = []
for page_number in range(number_of_pages):
page = state_machines_editor_ctrl.view['notebook'].get_nth_page(page_number)
sm_id = state_machines_editor_ctrl.get_state_machine_id_for_page(page)
if sm_id == state_machine_manager_model.selected_state_machine_id:
selected_page_number = page_number
# backup state machine selection
selection_of_sm = []
for model in state_machine_manager_model.state_machines[sm_id].selection.get_all():
if isinstance(model, AbstractStateModel):
# TODO extend to full range of selection -> see core_identifier action-module
selection_of_sm.append(model.state.get_path())
list_of_tab_meta.append({'backup_meta': state_machine_manager_model.state_machines[sm_id].auto_backup.meta,
'selection': selection_of_sm})
# store final state machine backup meta data to backup session tabs and selection for the next run
global_runtime_config.set_config_value('open_tabs', list_of_tab_meta)
global_runtime_config.set_config_value('selected_state_machine_page_number', selected_page_number) | python | def store_session():
""" Stores reference backup information for all open tabs into runtime config
The backup of never stored tabs (state machines) and not stored state machine changes will be triggered a last
time to secure data lose.
"""
from rafcon.gui.singleton import state_machine_manager_model, global_runtime_config
from rafcon.gui.models.auto_backup import AutoBackupModel
from rafcon.gui.models import AbstractStateModel
from rafcon.gui.singleton import main_window_controller
# check if there are dirty state machines -> use backup file structure maybe it is already stored
for sm_m in state_machine_manager_model.state_machines.values():
if sm_m.auto_backup:
if sm_m.state_machine.marked_dirty:
sm_m.auto_backup.perform_temp_storage()
else:
# generate a backup
sm_m.auto_backup = AutoBackupModel(sm_m)
# collect order of tab state machine ids from state machines editor and find selected state machine page number
state_machines_editor_ctrl = main_window_controller.get_controller('state_machines_editor_ctrl')
number_of_pages = state_machines_editor_ctrl.view['notebook'].get_n_pages()
selected_page_number = None
list_of_tab_meta = []
for page_number in range(number_of_pages):
page = state_machines_editor_ctrl.view['notebook'].get_nth_page(page_number)
sm_id = state_machines_editor_ctrl.get_state_machine_id_for_page(page)
if sm_id == state_machine_manager_model.selected_state_machine_id:
selected_page_number = page_number
# backup state machine selection
selection_of_sm = []
for model in state_machine_manager_model.state_machines[sm_id].selection.get_all():
if isinstance(model, AbstractStateModel):
# TODO extend to full range of selection -> see core_identifier action-module
selection_of_sm.append(model.state.get_path())
list_of_tab_meta.append({'backup_meta': state_machine_manager_model.state_machines[sm_id].auto_backup.meta,
'selection': selection_of_sm})
# store final state machine backup meta data to backup session tabs and selection for the next run
global_runtime_config.set_config_value('open_tabs', list_of_tab_meta)
global_runtime_config.set_config_value('selected_state_machine_page_number', selected_page_number) | [
"def",
"store_session",
"(",
")",
":",
"from",
"rafcon",
".",
"gui",
".",
"singleton",
"import",
"state_machine_manager_model",
",",
"global_runtime_config",
"from",
"rafcon",
".",
"gui",
".",
"models",
".",
"auto_backup",
"import",
"AutoBackupModel",
"from",
"raf... | Stores reference backup information for all open tabs into runtime config
The backup of never stored tabs (state machines) and not stored state machine changes will be triggered a last
time to secure data lose. | [
"Stores",
"reference",
"backup",
"information",
"for",
"all",
"open",
"tabs",
"into",
"runtime",
"config"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/backup/session.py#L24-L66 | train | 40,288 |
DLR-RM/RAFCON | source/rafcon/utils/log.py | add_logging_level | def add_logging_level(level_name, level_num, method_name=None):
"""Add new logging level
Comprehensively adds a new logging level to the `logging` module and the currently configured logging class.
`method_name` becomes a convenience method for both `logging` itself and the class returned by
`logging.getLoggerClass()` (usually just `logging.Logger`). If `method_name` is not specified, `level_name.lower()`
is used.
:param str level_name: the level name
:param int level_num: the level number/value
:raises AttributeError: if the level
name is already an attribute of the `logging` module or if the method name is already present
Example
-------
>>> add_logging_level('TRACE', logging.DEBUG - 5)
>>> logging.getLogger(__name__).setLevel("TRACE")
>>> logging.getLogger(__name__).trace('that worked')
>>> logging.trace('so did this')
>>> logging.TRACE
5
"""
if not method_name:
method_name = level_name.lower()
if hasattr(logging, level_name):
raise AttributeError('{} already defined in logging module'.format(level_name))
if hasattr(logging, method_name):
raise AttributeError('{} already defined in logging module'.format(method_name))
if hasattr(logging.getLoggerClass(), method_name):
raise AttributeError('{} already defined in logger class'.format(method_name))
# This method was inspired by the answers to Stack Overflow post
# http://stackoverflow.com/q/2183233/2988730, especially
# http://stackoverflow.com/a/13638084/2988730
def log_for_level(self, message, *args, **kwargs):
if self.isEnabledFor(level_num):
self._log(level_num, message, args, **kwargs)
def log_to_root(message, *args, **kwargs):
logging.log(level_num, message, *args, **kwargs)
logging.addLevelName(level_num, level_name)
setattr(logging, level_name, level_num)
setattr(logging.getLoggerClass(), method_name, log_for_level)
setattr(logging, method_name, log_to_root) | python | def add_logging_level(level_name, level_num, method_name=None):
"""Add new logging level
Comprehensively adds a new logging level to the `logging` module and the currently configured logging class.
`method_name` becomes a convenience method for both `logging` itself and the class returned by
`logging.getLoggerClass()` (usually just `logging.Logger`). If `method_name` is not specified, `level_name.lower()`
is used.
:param str level_name: the level name
:param int level_num: the level number/value
:raises AttributeError: if the level
name is already an attribute of the `logging` module or if the method name is already present
Example
-------
>>> add_logging_level('TRACE', logging.DEBUG - 5)
>>> logging.getLogger(__name__).setLevel("TRACE")
>>> logging.getLogger(__name__).trace('that worked')
>>> logging.trace('so did this')
>>> logging.TRACE
5
"""
if not method_name:
method_name = level_name.lower()
if hasattr(logging, level_name):
raise AttributeError('{} already defined in logging module'.format(level_name))
if hasattr(logging, method_name):
raise AttributeError('{} already defined in logging module'.format(method_name))
if hasattr(logging.getLoggerClass(), method_name):
raise AttributeError('{} already defined in logger class'.format(method_name))
# This method was inspired by the answers to Stack Overflow post
# http://stackoverflow.com/q/2183233/2988730, especially
# http://stackoverflow.com/a/13638084/2988730
def log_for_level(self, message, *args, **kwargs):
if self.isEnabledFor(level_num):
self._log(level_num, message, args, **kwargs)
def log_to_root(message, *args, **kwargs):
logging.log(level_num, message, *args, **kwargs)
logging.addLevelName(level_num, level_name)
setattr(logging, level_name, level_num)
setattr(logging.getLoggerClass(), method_name, log_for_level)
setattr(logging, method_name, log_to_root) | [
"def",
"add_logging_level",
"(",
"level_name",
",",
"level_num",
",",
"method_name",
"=",
"None",
")",
":",
"if",
"not",
"method_name",
":",
"method_name",
"=",
"level_name",
".",
"lower",
"(",
")",
"if",
"hasattr",
"(",
"logging",
",",
"level_name",
")",
... | Add new logging level
Comprehensively adds a new logging level to the `logging` module and the currently configured logging class.
`method_name` becomes a convenience method for both `logging` itself and the class returned by
`logging.getLoggerClass()` (usually just `logging.Logger`). If `method_name` is not specified, `level_name.lower()`
is used.
:param str level_name: the level name
:param int level_num: the level number/value
:raises AttributeError: if the level
name is already an attribute of the `logging` module or if the method name is already present
Example
-------
>>> add_logging_level('TRACE', logging.DEBUG - 5)
>>> logging.getLogger(__name__).setLevel("TRACE")
>>> logging.getLogger(__name__).trace('that worked')
>>> logging.trace('so did this')
>>> logging.TRACE
5 | [
"Add",
"new",
"logging",
"level"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/log.py#L37-L83 | train | 40,289 |
DLR-RM/RAFCON | source/rafcon/utils/log.py | get_logger | def get_logger(name):
"""Returns a logger for the given name
The function is basically a wrapper for logging.getLogger and only ensures that the namespace is within "rafcon."
and that the propagation is enabled.
:param str name: The namespace of the new logger
:return: Logger object with given namespace
:rtype: logging.Logger
"""
if name in existing_loggers:
return existing_loggers[name]
# Ensure that all logger are within the RAFCON root namespace
namespace = name if name.startswith(rafcon_root + ".") else rafcon_root + "." + name
logger = logging.getLogger(namespace)
logger.propagate = True
existing_loggers[name] = logger
return logger | python | def get_logger(name):
"""Returns a logger for the given name
The function is basically a wrapper for logging.getLogger and only ensures that the namespace is within "rafcon."
and that the propagation is enabled.
:param str name: The namespace of the new logger
:return: Logger object with given namespace
:rtype: logging.Logger
"""
if name in existing_loggers:
return existing_loggers[name]
# Ensure that all logger are within the RAFCON root namespace
namespace = name if name.startswith(rafcon_root + ".") else rafcon_root + "." + name
logger = logging.getLogger(namespace)
logger.propagate = True
existing_loggers[name] = logger
return logger | [
"def",
"get_logger",
"(",
"name",
")",
":",
"if",
"name",
"in",
"existing_loggers",
":",
"return",
"existing_loggers",
"[",
"name",
"]",
"# Ensure that all logger are within the RAFCON root namespace",
"namespace",
"=",
"name",
"if",
"name",
".",
"startswith",
"(",
... | Returns a logger for the given name
The function is basically a wrapper for logging.getLogger and only ensures that the namespace is within "rafcon."
and that the propagation is enabled.
:param str name: The namespace of the new logger
:return: Logger object with given namespace
:rtype: logging.Logger | [
"Returns",
"a",
"logger",
"for",
"the",
"given",
"name"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/log.py#L100-L119 | train | 40,290 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/state_machine.py | open_state_machine | def open_state_machine(path=None, recent_opened_notification=False):
""" Open a state machine from respective file system path
:param str path: file system path to the state machine
:param bool recent_opened_notification: flags that indicates that this call also should update recently open
:rtype rafcon.core.state_machine.StateMachine
:return: opened state machine
"""
start_time = time.time()
if path is None:
if interface.open_folder_func is None:
logger.error("No function defined for opening a folder")
return
load_path = interface.open_folder_func("Please choose the folder of the state machine")
if load_path is None:
return
else:
load_path = path
if state_machine_manager.is_state_machine_open(load_path):
logger.info("State machine already open. Select state machine instance from path {0}.".format(load_path))
sm = state_machine_manager.get_open_state_machine_of_file_system_path(load_path)
gui_helper_state.gui_singletons.state_machine_manager_model.selected_state_machine_id = sm.state_machine_id
return state_machine_manager.get_open_state_machine_of_file_system_path(load_path)
state_machine = None
try:
state_machine = storage.load_state_machine_from_path(load_path)
state_machine_manager.add_state_machine(state_machine)
if recent_opened_notification:
global_runtime_config.update_recently_opened_state_machines_with(state_machine)
duration = time.time() - start_time
stat = state_machine.root_state.get_states_statistics(0)
logger.info("It took {0:.2}s to load {1} states with {2} hierarchy levels.".format(duration, stat[0], stat[1]))
except (AttributeError, ValueError, IOError) as e:
logger.error('Error while trying to open state machine: {0}'.format(e))
return state_machine | python | def open_state_machine(path=None, recent_opened_notification=False):
""" Open a state machine from respective file system path
:param str path: file system path to the state machine
:param bool recent_opened_notification: flags that indicates that this call also should update recently open
:rtype rafcon.core.state_machine.StateMachine
:return: opened state machine
"""
start_time = time.time()
if path is None:
if interface.open_folder_func is None:
logger.error("No function defined for opening a folder")
return
load_path = interface.open_folder_func("Please choose the folder of the state machine")
if load_path is None:
return
else:
load_path = path
if state_machine_manager.is_state_machine_open(load_path):
logger.info("State machine already open. Select state machine instance from path {0}.".format(load_path))
sm = state_machine_manager.get_open_state_machine_of_file_system_path(load_path)
gui_helper_state.gui_singletons.state_machine_manager_model.selected_state_machine_id = sm.state_machine_id
return state_machine_manager.get_open_state_machine_of_file_system_path(load_path)
state_machine = None
try:
state_machine = storage.load_state_machine_from_path(load_path)
state_machine_manager.add_state_machine(state_machine)
if recent_opened_notification:
global_runtime_config.update_recently_opened_state_machines_with(state_machine)
duration = time.time() - start_time
stat = state_machine.root_state.get_states_statistics(0)
logger.info("It took {0:.2}s to load {1} states with {2} hierarchy levels.".format(duration, stat[0], stat[1]))
except (AttributeError, ValueError, IOError) as e:
logger.error('Error while trying to open state machine: {0}'.format(e))
return state_machine | [
"def",
"open_state_machine",
"(",
"path",
"=",
"None",
",",
"recent_opened_notification",
"=",
"False",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"path",
"is",
"None",
":",
"if",
"interface",
".",
"open_folder_func",
"is",
"None",
"... | Open a state machine from respective file system path
:param str path: file system path to the state machine
:param bool recent_opened_notification: flags that indicates that this call also should update recently open
:rtype rafcon.core.state_machine.StateMachine
:return: opened state machine | [
"Open",
"a",
"state",
"machine",
"from",
"respective",
"file",
"system",
"path"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/state_machine.py#L82-L120 | train | 40,291 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/state_machine.py | save_state_machine | def save_state_machine(delete_old_state_machine=False, recent_opened_notification=False, as_copy=False, copy_path=None):
""" Save selected state machine
The function checks if states of the state machine has not stored script data abd triggers dialog windows to
take user input how to continue (ignoring or storing this script changes).
If the state machine file_system_path is None function save_state_machine_as is used to collect respective path and
to store the state machine.
The delete flag will remove all data in existing state machine folder (if plugins or feature use non-standard
RAFCON files this data will be removed)
:param bool delete_old_state_machine: Flag to delete existing state machine folder before storing current version
:param bool recent_opened_notification: Flag to insert path of state machine into recent opened state machine paths
:param bool as_copy: Store state machine as copy flag e.g. without assigning path to state_machine.file_system_path
:return: True if the storing was successful, False if the storing process was canceled or stopped by condition fail
:rtype bool:
"""
state_machine_manager_model = rafcon.gui.singleton.state_machine_manager_model
states_editor_ctrl = rafcon.gui.singleton.main_window_controller.get_controller('states_editor_ctrl')
state_machine_m = state_machine_manager_model.get_selected_state_machine_model()
if state_machine_m is None:
logger.warning("Can not 'save state machine' because no state machine is selected.")
return False
previous_path = state_machine_m.state_machine.file_system_path
previous_marked_dirty = state_machine_m.state_machine.marked_dirty
all_tabs = list(states_editor_ctrl.tabs.values())
all_tabs.extend(states_editor_ctrl.closed_tabs.values())
dirty_source_editor_ctrls = [tab_dict['controller'].get_controller('source_ctrl') for tab_dict in all_tabs if
tab_dict['source_code_view_is_dirty'] is True and
tab_dict['state_m'].state.get_state_machine().state_machine_id ==
state_machine_m.state_machine.state_machine_id]
for dirty_source_editor_ctrl in dirty_source_editor_ctrls:
state = dirty_source_editor_ctrl.model.state
message_string = "The source code of the state '{}' (path: {}) has not been applied yet and would " \
"therefore not be saved.\n\nDo you want to apply the changes now?" \
"".format(state.name, state.get_path())
if global_gui_config.get_config_value("AUTO_APPLY_SOURCE_CODE_CHANGES", False):
dirty_source_editor_ctrl.apply_clicked(None)
else:
dialog = RAFCONButtonDialog(message_string, ["Apply", "Ignore changes"],
message_type=Gtk.MessageType.WARNING, parent=states_editor_ctrl.get_root_window())
response_id = dialog.run()
state = dirty_source_editor_ctrl.model.state
if response_id == 1: # Apply changes
logger.debug("Applying source code changes of state '{}'".format(state.name))
dirty_source_editor_ctrl.apply_clicked(None)
elif response_id == 2: # Ignore changes
logger.debug("Ignoring source code changes of state '{}'".format(state.name))
else:
logger.warning("Response id: {} is not considered".format(response_id))
return False
dialog.destroy()
save_path = state_machine_m.state_machine.file_system_path
if not as_copy and save_path is None or as_copy and copy_path is None:
if not save_state_machine_as(as_copy=as_copy):
return False
return True
logger.debug("Saving state machine to {0}".format(save_path))
state_machine_m = state_machine_manager_model.get_selected_state_machine_model()
sm_path = state_machine_m.state_machine.file_system_path
storage.save_state_machine_to_path(state_machine_m.state_machine, copy_path if as_copy else sm_path,
delete_old_state_machine=delete_old_state_machine, as_copy=as_copy)
if recent_opened_notification:
global_runtime_config.update_recently_opened_state_machines_with(state_machine_m.state_machine)
state_machine_m.store_meta_data(copy_path=copy_path if as_copy else None)
logger.debug("Saved state machine and its meta data.")
library_manager_model.state_machine_was_stored(state_machine_m, previous_path)
return True | python | def save_state_machine(delete_old_state_machine=False, recent_opened_notification=False, as_copy=False, copy_path=None):
""" Save selected state machine
The function checks if states of the state machine has not stored script data abd triggers dialog windows to
take user input how to continue (ignoring or storing this script changes).
If the state machine file_system_path is None function save_state_machine_as is used to collect respective path and
to store the state machine.
The delete flag will remove all data in existing state machine folder (if plugins or feature use non-standard
RAFCON files this data will be removed)
:param bool delete_old_state_machine: Flag to delete existing state machine folder before storing current version
:param bool recent_opened_notification: Flag to insert path of state machine into recent opened state machine paths
:param bool as_copy: Store state machine as copy flag e.g. without assigning path to state_machine.file_system_path
:return: True if the storing was successful, False if the storing process was canceled or stopped by condition fail
:rtype bool:
"""
state_machine_manager_model = rafcon.gui.singleton.state_machine_manager_model
states_editor_ctrl = rafcon.gui.singleton.main_window_controller.get_controller('states_editor_ctrl')
state_machine_m = state_machine_manager_model.get_selected_state_machine_model()
if state_machine_m is None:
logger.warning("Can not 'save state machine' because no state machine is selected.")
return False
previous_path = state_machine_m.state_machine.file_system_path
previous_marked_dirty = state_machine_m.state_machine.marked_dirty
all_tabs = list(states_editor_ctrl.tabs.values())
all_tabs.extend(states_editor_ctrl.closed_tabs.values())
dirty_source_editor_ctrls = [tab_dict['controller'].get_controller('source_ctrl') for tab_dict in all_tabs if
tab_dict['source_code_view_is_dirty'] is True and
tab_dict['state_m'].state.get_state_machine().state_machine_id ==
state_machine_m.state_machine.state_machine_id]
for dirty_source_editor_ctrl in dirty_source_editor_ctrls:
state = dirty_source_editor_ctrl.model.state
message_string = "The source code of the state '{}' (path: {}) has not been applied yet and would " \
"therefore not be saved.\n\nDo you want to apply the changes now?" \
"".format(state.name, state.get_path())
if global_gui_config.get_config_value("AUTO_APPLY_SOURCE_CODE_CHANGES", False):
dirty_source_editor_ctrl.apply_clicked(None)
else:
dialog = RAFCONButtonDialog(message_string, ["Apply", "Ignore changes"],
message_type=Gtk.MessageType.WARNING, parent=states_editor_ctrl.get_root_window())
response_id = dialog.run()
state = dirty_source_editor_ctrl.model.state
if response_id == 1: # Apply changes
logger.debug("Applying source code changes of state '{}'".format(state.name))
dirty_source_editor_ctrl.apply_clicked(None)
elif response_id == 2: # Ignore changes
logger.debug("Ignoring source code changes of state '{}'".format(state.name))
else:
logger.warning("Response id: {} is not considered".format(response_id))
return False
dialog.destroy()
save_path = state_machine_m.state_machine.file_system_path
if not as_copy and save_path is None or as_copy and copy_path is None:
if not save_state_machine_as(as_copy=as_copy):
return False
return True
logger.debug("Saving state machine to {0}".format(save_path))
state_machine_m = state_machine_manager_model.get_selected_state_machine_model()
sm_path = state_machine_m.state_machine.file_system_path
storage.save_state_machine_to_path(state_machine_m.state_machine, copy_path if as_copy else sm_path,
delete_old_state_machine=delete_old_state_machine, as_copy=as_copy)
if recent_opened_notification:
global_runtime_config.update_recently_opened_state_machines_with(state_machine_m.state_machine)
state_machine_m.store_meta_data(copy_path=copy_path if as_copy else None)
logger.debug("Saved state machine and its meta data.")
library_manager_model.state_machine_was_stored(state_machine_m, previous_path)
return True | [
"def",
"save_state_machine",
"(",
"delete_old_state_machine",
"=",
"False",
",",
"recent_opened_notification",
"=",
"False",
",",
"as_copy",
"=",
"False",
",",
"copy_path",
"=",
"None",
")",
":",
"state_machine_manager_model",
"=",
"rafcon",
".",
"gui",
".",
"sing... | Save selected state machine
The function checks if states of the state machine has not stored script data abd triggers dialog windows to
take user input how to continue (ignoring or storing this script changes).
If the state machine file_system_path is None function save_state_machine_as is used to collect respective path and
to store the state machine.
The delete flag will remove all data in existing state machine folder (if plugins or feature use non-standard
RAFCON files this data will be removed)
:param bool delete_old_state_machine: Flag to delete existing state machine folder before storing current version
:param bool recent_opened_notification: Flag to insert path of state machine into recent opened state machine paths
:param bool as_copy: Store state machine as copy flag e.g. without assigning path to state_machine.file_system_path
:return: True if the storing was successful, False if the storing process was canceled or stopped by condition fail
:rtype bool: | [
"Save",
"selected",
"state",
"machine"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/state_machine.py#L145-L220 | train | 40,292 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/state_machine.py | save_state_machine_as | def save_state_machine_as(path=None, recent_opened_notification=False, as_copy=False):
""" Store selected state machine to path
If there is no handed path the interface dialog "create folder" is used to collect one. The state machine finally
is stored by the save_state_machine function.
:param str path: Path of state machine folder where selected state machine should be stored
:param bool recent_opened_notification: Flag to insert path of state machine into recent opened state machine paths
:param bool as_copy: Store state machine as copy flag e.g. without assigning path to state_machine.file_system_path
:return: True if successfully stored, False if the storing process was canceled or stopped by condition fail
:rtype bool:
"""
state_machine_manager_model = rafcon.gui.singleton.state_machine_manager_model
selected_state_machine_model = state_machine_manager_model.get_selected_state_machine_model()
if selected_state_machine_model is None:
logger.warning("Can not 'save state machine as' because no state machine is selected.")
return False
if path is None:
if interface.create_folder_func is None:
logger.error("No function defined for creating a folder")
return False
folder_name = selected_state_machine_model.state_machine.root_state.name
path = interface.create_folder_func("Please choose a root folder and a folder name for the state-machine. "
"The default folder name is the name of the root state.",
format_default_folder_name(folder_name))
if path is None:
logger.warning("No valid path specified")
return False
previous_path = selected_state_machine_model.state_machine.file_system_path
if not as_copy:
marked_dirty = selected_state_machine_model.state_machine.marked_dirty
recent_opened_notification = recent_opened_notification and (not previous_path == path or marked_dirty)
selected_state_machine_model.state_machine.file_system_path = path
result = save_state_machine(delete_old_state_machine=True,
recent_opened_notification=recent_opened_notification,
as_copy=as_copy, copy_path=path)
library_manager_model.state_machine_was_stored(selected_state_machine_model, previous_path)
return result | python | def save_state_machine_as(path=None, recent_opened_notification=False, as_copy=False):
""" Store selected state machine to path
If there is no handed path the interface dialog "create folder" is used to collect one. The state machine finally
is stored by the save_state_machine function.
:param str path: Path of state machine folder where selected state machine should be stored
:param bool recent_opened_notification: Flag to insert path of state machine into recent opened state machine paths
:param bool as_copy: Store state machine as copy flag e.g. without assigning path to state_machine.file_system_path
:return: True if successfully stored, False if the storing process was canceled or stopped by condition fail
:rtype bool:
"""
state_machine_manager_model = rafcon.gui.singleton.state_machine_manager_model
selected_state_machine_model = state_machine_manager_model.get_selected_state_machine_model()
if selected_state_machine_model is None:
logger.warning("Can not 'save state machine as' because no state machine is selected.")
return False
if path is None:
if interface.create_folder_func is None:
logger.error("No function defined for creating a folder")
return False
folder_name = selected_state_machine_model.state_machine.root_state.name
path = interface.create_folder_func("Please choose a root folder and a folder name for the state-machine. "
"The default folder name is the name of the root state.",
format_default_folder_name(folder_name))
if path is None:
logger.warning("No valid path specified")
return False
previous_path = selected_state_machine_model.state_machine.file_system_path
if not as_copy:
marked_dirty = selected_state_machine_model.state_machine.marked_dirty
recent_opened_notification = recent_opened_notification and (not previous_path == path or marked_dirty)
selected_state_machine_model.state_machine.file_system_path = path
result = save_state_machine(delete_old_state_machine=True,
recent_opened_notification=recent_opened_notification,
as_copy=as_copy, copy_path=path)
library_manager_model.state_machine_was_stored(selected_state_machine_model, previous_path)
return result | [
"def",
"save_state_machine_as",
"(",
"path",
"=",
"None",
",",
"recent_opened_notification",
"=",
"False",
",",
"as_copy",
"=",
"False",
")",
":",
"state_machine_manager_model",
"=",
"rafcon",
".",
"gui",
".",
"singleton",
".",
"state_machine_manager_model",
"select... | Store selected state machine to path
If there is no handed path the interface dialog "create folder" is used to collect one. The state machine finally
is stored by the save_state_machine function.
:param str path: Path of state machine folder where selected state machine should be stored
:param bool recent_opened_notification: Flag to insert path of state machine into recent opened state machine paths
:param bool as_copy: Store state machine as copy flag e.g. without assigning path to state_machine.file_system_path
:return: True if successfully stored, False if the storing process was canceled or stopped by condition fail
:rtype bool: | [
"Store",
"selected",
"state",
"machine",
"to",
"path"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/state_machine.py#L223-L264 | train | 40,293 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/state_machine.py | is_state_machine_stopped_to_proceed | def is_state_machine_stopped_to_proceed(selected_sm_id=None, root_window=None):
""" Check if state machine is stopped and in case request user by dialog how to proceed
The function checks if a specific state machine or by default all state machines have stopped or finished
execution. If a state machine is still running the user is ask by dialog window if those should be stopped or not.
:param selected_sm_id: Specific state mine to check for
:param root_window: Root window for dialog window
:return:
"""
# check if the/a state machine is still running
if not state_machine_execution_engine.finished_or_stopped():
if selected_sm_id is None or selected_sm_id == state_machine_manager.active_state_machine_id:
message_string = "A state machine is still running. This state machine can only be refreshed" \
"when not longer running."
dialog = RAFCONButtonDialog(message_string, ["Stop execution and refresh",
"Keep running and do not refresh"],
message_type=Gtk.MessageType.QUESTION,
parent=root_window)
response_id = dialog.run()
state_machine_stopped = False
if response_id == 1:
state_machine_execution_engine.stop()
state_machine_stopped = True
elif response_id == 2:
logger.debug("State machine will stay running and no refresh will be performed!")
dialog.destroy()
return state_machine_stopped
return True | python | def is_state_machine_stopped_to_proceed(selected_sm_id=None, root_window=None):
""" Check if state machine is stopped and in case request user by dialog how to proceed
The function checks if a specific state machine or by default all state machines have stopped or finished
execution. If a state machine is still running the user is ask by dialog window if those should be stopped or not.
:param selected_sm_id: Specific state mine to check for
:param root_window: Root window for dialog window
:return:
"""
# check if the/a state machine is still running
if not state_machine_execution_engine.finished_or_stopped():
if selected_sm_id is None or selected_sm_id == state_machine_manager.active_state_machine_id:
message_string = "A state machine is still running. This state machine can only be refreshed" \
"when not longer running."
dialog = RAFCONButtonDialog(message_string, ["Stop execution and refresh",
"Keep running and do not refresh"],
message_type=Gtk.MessageType.QUESTION,
parent=root_window)
response_id = dialog.run()
state_machine_stopped = False
if response_id == 1:
state_machine_execution_engine.stop()
state_machine_stopped = True
elif response_id == 2:
logger.debug("State machine will stay running and no refresh will be performed!")
dialog.destroy()
return state_machine_stopped
return True | [
"def",
"is_state_machine_stopped_to_proceed",
"(",
"selected_sm_id",
"=",
"None",
",",
"root_window",
"=",
"None",
")",
":",
"# check if the/a state machine is still running",
"if",
"not",
"state_machine_execution_engine",
".",
"finished_or_stopped",
"(",
")",
":",
"if",
... | Check if state machine is stopped and in case request user by dialog how to proceed
The function checks if a specific state machine or by default all state machines have stopped or finished
execution. If a state machine is still running the user is ask by dialog window if those should be stopped or not.
:param selected_sm_id: Specific state mine to check for
:param root_window: Root window for dialog window
:return: | [
"Check",
"if",
"state",
"machine",
"is",
"stopped",
"and",
"in",
"case",
"request",
"user",
"by",
"dialog",
"how",
"to",
"proceed"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/state_machine.py#L374-L404 | train | 40,294 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/state_machine.py | refresh_selected_state_machine | def refresh_selected_state_machine():
"""Reloads the selected state machine.
"""
selected_sm_id = rafcon.gui.singleton.state_machine_manager_model.selected_state_machine_id
selected_sm = state_machine_manager.state_machines[selected_sm_id]
state_machines_editor_ctrl = rafcon.gui.singleton.main_window_controller.get_controller('state_machines_editor_ctrl')
states_editor_ctrl = rafcon.gui.singleton.main_window_controller.get_controller('states_editor_ctrl')
if not is_state_machine_stopped_to_proceed(selected_sm_id, state_machines_editor_ctrl.get_root_window()):
return
# check if the a dirty flag is still set
all_tabs = list(states_editor_ctrl.tabs.values())
all_tabs.extend(states_editor_ctrl.closed_tabs.values())
dirty_source_editor = [tab_dict['controller'] for tab_dict in all_tabs if
tab_dict['source_code_view_is_dirty'] is True]
if selected_sm.marked_dirty or dirty_source_editor:
message_string = "Are you sure you want to reload the currently selected state machine?\n\n" \
"The following elements have been modified and not saved. " \
"These changes will get lost:"
message_string = "%s\n* State machine #%s and name '%s'" % (
message_string, str(selected_sm_id), selected_sm.root_state.name)
for ctrl in dirty_source_editor:
if ctrl.model.state.get_state_machine().state_machine_id == selected_sm_id:
message_string = "%s\n* Source code of state with name '%s' and path '%s'" % (
message_string, ctrl.model.state.name, ctrl.model.state.get_path())
dialog = RAFCONButtonDialog(message_string, ["Reload anyway", "Cancel"],
message_type=Gtk.MessageType.WARNING, parent=states_editor_ctrl.get_root_window())
response_id = dialog.run()
dialog.destroy()
if response_id == 1: # Reload anyway
pass
else:
logger.debug("Refresh of selected state machine canceled")
return
library_manager.clean_loaded_libraries()
refresh_libraries()
states_editor_ctrl.close_pages_for_specific_sm_id(selected_sm_id)
state_machines_editor_ctrl.refresh_state_machine_by_id(selected_sm_id) | python | def refresh_selected_state_machine():
"""Reloads the selected state machine.
"""
selected_sm_id = rafcon.gui.singleton.state_machine_manager_model.selected_state_machine_id
selected_sm = state_machine_manager.state_machines[selected_sm_id]
state_machines_editor_ctrl = rafcon.gui.singleton.main_window_controller.get_controller('state_machines_editor_ctrl')
states_editor_ctrl = rafcon.gui.singleton.main_window_controller.get_controller('states_editor_ctrl')
if not is_state_machine_stopped_to_proceed(selected_sm_id, state_machines_editor_ctrl.get_root_window()):
return
# check if the a dirty flag is still set
all_tabs = list(states_editor_ctrl.tabs.values())
all_tabs.extend(states_editor_ctrl.closed_tabs.values())
dirty_source_editor = [tab_dict['controller'] for tab_dict in all_tabs if
tab_dict['source_code_view_is_dirty'] is True]
if selected_sm.marked_dirty or dirty_source_editor:
message_string = "Are you sure you want to reload the currently selected state machine?\n\n" \
"The following elements have been modified and not saved. " \
"These changes will get lost:"
message_string = "%s\n* State machine #%s and name '%s'" % (
message_string, str(selected_sm_id), selected_sm.root_state.name)
for ctrl in dirty_source_editor:
if ctrl.model.state.get_state_machine().state_machine_id == selected_sm_id:
message_string = "%s\n* Source code of state with name '%s' and path '%s'" % (
message_string, ctrl.model.state.name, ctrl.model.state.get_path())
dialog = RAFCONButtonDialog(message_string, ["Reload anyway", "Cancel"],
message_type=Gtk.MessageType.WARNING, parent=states_editor_ctrl.get_root_window())
response_id = dialog.run()
dialog.destroy()
if response_id == 1: # Reload anyway
pass
else:
logger.debug("Refresh of selected state machine canceled")
return
library_manager.clean_loaded_libraries()
refresh_libraries()
states_editor_ctrl.close_pages_for_specific_sm_id(selected_sm_id)
state_machines_editor_ctrl.refresh_state_machine_by_id(selected_sm_id) | [
"def",
"refresh_selected_state_machine",
"(",
")",
":",
"selected_sm_id",
"=",
"rafcon",
".",
"gui",
".",
"singleton",
".",
"state_machine_manager_model",
".",
"selected_state_machine_id",
"selected_sm",
"=",
"state_machine_manager",
".",
"state_machines",
"[",
"selected_... | Reloads the selected state machine. | [
"Reloads",
"the",
"selected",
"state",
"machine",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/state_machine.py#L508-L549 | train | 40,295 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/state_machine.py | delete_core_element_of_model | def delete_core_element_of_model(model, raise_exceptions=False, recursive=True, destroy=True, force=False):
"""Deletes respective core element of handed model of its state machine
If the model is one of state, data flow or transition, it is tried to delete that model together with its
data from the corresponding state machine.
:param model: The model of respective core element to delete
:param bool raise_exceptions: Whether to raise exceptions or only log errors in case of failures
:param bool destroy: Access the destroy flag of the core remove methods
:return: True if successful, False else
"""
if isinstance(model, AbstractStateModel) and model.state.is_root_state:
logger.warning("Deletion is not allowed. {0} is root state of state machine.".format(model.core_element))
return False
state_m = model.parent
if state_m is None:
msg = "Model has no parent from which it could be deleted from"
if raise_exceptions:
raise ValueError(msg)
logger.error(msg)
return False
if is_selection_inside_of_library_state(selected_elements=[model]):
logger.warning("Deletion is not allowed. Element {0} is inside of a library.".format(model.core_element))
return False
assert isinstance(state_m, StateModel)
state = state_m.state
core_element = model.core_element
try:
if core_element in state:
state.remove(core_element, recursive=recursive, destroy=destroy, force=force)
return True
return False
except (AttributeError, ValueError) as e:
if raise_exceptions:
raise
logger.error("The model '{}' for core element '{}' could not be deleted: {}".format(model, core_element, e))
return False | python | def delete_core_element_of_model(model, raise_exceptions=False, recursive=True, destroy=True, force=False):
"""Deletes respective core element of handed model of its state machine
If the model is one of state, data flow or transition, it is tried to delete that model together with its
data from the corresponding state machine.
:param model: The model of respective core element to delete
:param bool raise_exceptions: Whether to raise exceptions or only log errors in case of failures
:param bool destroy: Access the destroy flag of the core remove methods
:return: True if successful, False else
"""
if isinstance(model, AbstractStateModel) and model.state.is_root_state:
logger.warning("Deletion is not allowed. {0} is root state of state machine.".format(model.core_element))
return False
state_m = model.parent
if state_m is None:
msg = "Model has no parent from which it could be deleted from"
if raise_exceptions:
raise ValueError(msg)
logger.error(msg)
return False
if is_selection_inside_of_library_state(selected_elements=[model]):
logger.warning("Deletion is not allowed. Element {0} is inside of a library.".format(model.core_element))
return False
assert isinstance(state_m, StateModel)
state = state_m.state
core_element = model.core_element
try:
if core_element in state:
state.remove(core_element, recursive=recursive, destroy=destroy, force=force)
return True
return False
except (AttributeError, ValueError) as e:
if raise_exceptions:
raise
logger.error("The model '{}' for core element '{}' could not be deleted: {}".format(model, core_element, e))
return False | [
"def",
"delete_core_element_of_model",
"(",
"model",
",",
"raise_exceptions",
"=",
"False",
",",
"recursive",
"=",
"True",
",",
"destroy",
"=",
"True",
",",
"force",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"AbstractStateModel",
")",
"a... | Deletes respective core element of handed model of its state machine
If the model is one of state, data flow or transition, it is tried to delete that model together with its
data from the corresponding state machine.
:param model: The model of respective core element to delete
:param bool raise_exceptions: Whether to raise exceptions or only log errors in case of failures
:param bool destroy: Access the destroy flag of the core remove methods
:return: True if successful, False else | [
"Deletes",
"respective",
"core",
"element",
"of",
"handed",
"model",
"of",
"its",
"state",
"machine"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/state_machine.py#L601-L639 | train | 40,296 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/state_machine.py | delete_core_elements_of_models | def delete_core_elements_of_models(models, raise_exceptions=True, recursive=True, destroy=True, force=False):
"""Deletes all respective core elements for the given models
Calls the :func:`delete_core_element_of_model` for all given models.
:param models: A single model or a list of models of respective core element to be deleted
:param bool raise_exceptions: Whether to raise exceptions or log error messages in case of an error
:param bool destroy: Access the destroy flag of the core remove methods
:return: The number of models that were successfully deleted
"""
# If only one model is given, make a list out of it
if not hasattr(models, '__iter__'):
models = [models]
return sum(delete_core_element_of_model(model, raise_exceptions, recursive=recursive, destroy=destroy, force=force)
for model in models) | python | def delete_core_elements_of_models(models, raise_exceptions=True, recursive=True, destroy=True, force=False):
"""Deletes all respective core elements for the given models
Calls the :func:`delete_core_element_of_model` for all given models.
:param models: A single model or a list of models of respective core element to be deleted
:param bool raise_exceptions: Whether to raise exceptions or log error messages in case of an error
:param bool destroy: Access the destroy flag of the core remove methods
:return: The number of models that were successfully deleted
"""
# If only one model is given, make a list out of it
if not hasattr(models, '__iter__'):
models = [models]
return sum(delete_core_element_of_model(model, raise_exceptions, recursive=recursive, destroy=destroy, force=force)
for model in models) | [
"def",
"delete_core_elements_of_models",
"(",
"models",
",",
"raise_exceptions",
"=",
"True",
",",
"recursive",
"=",
"True",
",",
"destroy",
"=",
"True",
",",
"force",
"=",
"False",
")",
":",
"# If only one model is given, make a list out of it",
"if",
"not",
"hasat... | Deletes all respective core elements for the given models
Calls the :func:`delete_core_element_of_model` for all given models.
:param models: A single model or a list of models of respective core element to be deleted
:param bool raise_exceptions: Whether to raise exceptions or log error messages in case of an error
:param bool destroy: Access the destroy flag of the core remove methods
:return: The number of models that were successfully deleted | [
"Deletes",
"all",
"respective",
"core",
"elements",
"for",
"the",
"given",
"models"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/state_machine.py#L642-L656 | train | 40,297 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/state_machine.py | is_selection_inside_of_library_state | def is_selection_inside_of_library_state(state_machine_m=None, selected_elements=None):
""" Check if handed or selected elements are inside of library state
If no state machine model or selected_elements are handed the method is searching for the selected state machine and
its selected elements. If selected_elements list is handed handed state machine model is ignored.
:param rafcon.gui.models.state_machine.StateMachineModel state_machine_m: Optional state machine model
:param list selected_elements: Optional model list that is considered to be selected
:return: True if elements inside of library state
"""
if state_machine_m is None:
state_machine_m = rafcon.gui.singleton.state_machine_manager_model.get_selected_state_machine_model()
if state_machine_m is None and selected_elements is None:
return False
selection_in_lib = []
selected_elements = state_machine_m.selection.get_all() if selected_elements is None else selected_elements
for model in selected_elements:
# check if model is element of child state or the root state (or its scoped variables) of a LibraryState
state_m = model if isinstance(model.core_element, State) else model.parent
selection_in_lib.append(state_m.state.get_next_upper_library_root_state() is not None)
# check if model is part of the shell (io-port or outcome) of a LibraryState
if not isinstance(model.core_element, State) and isinstance(state_m, LibraryStateModel):
selection_in_lib.append(True)
if any(selection_in_lib):
return True
return False | python | def is_selection_inside_of_library_state(state_machine_m=None, selected_elements=None):
""" Check if handed or selected elements are inside of library state
If no state machine model or selected_elements are handed the method is searching for the selected state machine and
its selected elements. If selected_elements list is handed handed state machine model is ignored.
:param rafcon.gui.models.state_machine.StateMachineModel state_machine_m: Optional state machine model
:param list selected_elements: Optional model list that is considered to be selected
:return: True if elements inside of library state
"""
if state_machine_m is None:
state_machine_m = rafcon.gui.singleton.state_machine_manager_model.get_selected_state_machine_model()
if state_machine_m is None and selected_elements is None:
return False
selection_in_lib = []
selected_elements = state_machine_m.selection.get_all() if selected_elements is None else selected_elements
for model in selected_elements:
# check if model is element of child state or the root state (or its scoped variables) of a LibraryState
state_m = model if isinstance(model.core_element, State) else model.parent
selection_in_lib.append(state_m.state.get_next_upper_library_root_state() is not None)
# check if model is part of the shell (io-port or outcome) of a LibraryState
if not isinstance(model.core_element, State) and isinstance(state_m, LibraryStateModel):
selection_in_lib.append(True)
if any(selection_in_lib):
return True
return False | [
"def",
"is_selection_inside_of_library_state",
"(",
"state_machine_m",
"=",
"None",
",",
"selected_elements",
"=",
"None",
")",
":",
"if",
"state_machine_m",
"is",
"None",
":",
"state_machine_m",
"=",
"rafcon",
".",
"gui",
".",
"singleton",
".",
"state_machine_manag... | Check if handed or selected elements are inside of library state
If no state machine model or selected_elements are handed the method is searching for the selected state machine and
its selected elements. If selected_elements list is handed handed state machine model is ignored.
:param rafcon.gui.models.state_machine.StateMachineModel state_machine_m: Optional state machine model
:param list selected_elements: Optional model list that is considered to be selected
:return: True if elements inside of library state | [
"Check",
"if",
"handed",
"or",
"selected",
"elements",
"are",
"inside",
"of",
"library",
"state"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/state_machine.py#L659-L684 | train | 40,298 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/state_machine.py | insert_state_into_selected_state | def insert_state_into_selected_state(state, as_template=False):
"""Adds a State to the selected state
:param state: the state which is inserted
:param as_template: If a state is a library state can be insert as template
:return: boolean: success of the insertion
"""
smm_m = rafcon.gui.singleton.state_machine_manager_model
if not isinstance(state, State):
logger.warning("A state is needed to be insert not {0}".format(state))
return False
if not smm_m.selected_state_machine_id:
logger.warning("Please select a container state within a state machine first")
return False
selection = smm_m.state_machines[smm_m.selected_state_machine_id].selection
if len(selection.states) > 1:
logger.warning("Please select exactly one state for the insertion")
return False
if len(selection.states) == 0:
logger.warning("Please select a state for the insertion")
return False
if is_selection_inside_of_library_state(selected_elements=[selection.get_selected_state()]):
logger.warning("State is not insert because target state is inside of a library state.")
return False
gui_helper_state.insert_state_as(selection.get_selected_state(), state, as_template)
return True | python | def insert_state_into_selected_state(state, as_template=False):
"""Adds a State to the selected state
:param state: the state which is inserted
:param as_template: If a state is a library state can be insert as template
:return: boolean: success of the insertion
"""
smm_m = rafcon.gui.singleton.state_machine_manager_model
if not isinstance(state, State):
logger.warning("A state is needed to be insert not {0}".format(state))
return False
if not smm_m.selected_state_machine_id:
logger.warning("Please select a container state within a state machine first")
return False
selection = smm_m.state_machines[smm_m.selected_state_machine_id].selection
if len(selection.states) > 1:
logger.warning("Please select exactly one state for the insertion")
return False
if len(selection.states) == 0:
logger.warning("Please select a state for the insertion")
return False
if is_selection_inside_of_library_state(selected_elements=[selection.get_selected_state()]):
logger.warning("State is not insert because target state is inside of a library state.")
return False
gui_helper_state.insert_state_as(selection.get_selected_state(), state, as_template)
return True | [
"def",
"insert_state_into_selected_state",
"(",
"state",
",",
"as_template",
"=",
"False",
")",
":",
"smm_m",
"=",
"rafcon",
".",
"gui",
".",
"singleton",
".",
"state_machine_manager_model",
"if",
"not",
"isinstance",
"(",
"state",
",",
"State",
")",
":",
"log... | Adds a State to the selected state
:param state: the state which is inserted
:param as_template: If a state is a library state can be insert as template
:return: boolean: success of the insertion | [
"Adds",
"a",
"State",
"to",
"the",
"selected",
"state"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/state_machine.py#L781-L813 | train | 40,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.