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/core/states/state.py | State._check_outcome_validity | def _check_outcome_validity(self, check_outcome):
"""Checks the validity of an outcome
Checks whether the id or the name of the outcome is already used by another outcome within the state.
:param rafcon.core.logical_port.Outcome check_outcome: The outcome to be checked
:return bool validity, str message: validity is True, when the outcome is valid, False else. message gives more
information especially if the outcome is not valid
"""
for outcome_id, outcome in self.outcomes.items():
# Do not compare outcome with itself when checking for existing name/id
if check_outcome is not outcome:
if check_outcome.outcome_id == outcome_id:
return False, "outcome id '{0}' existing in state".format(check_outcome.outcome_id)
if check_outcome.name == outcome.name:
return False, "outcome name '{0}' existing in state".format(check_outcome.name)
return True, "valid" | python | def _check_outcome_validity(self, check_outcome):
"""Checks the validity of an outcome
Checks whether the id or the name of the outcome is already used by another outcome within the state.
:param rafcon.core.logical_port.Outcome check_outcome: The outcome to be checked
:return bool validity, str message: validity is True, when the outcome is valid, False else. message gives more
information especially if the outcome is not valid
"""
for outcome_id, outcome in self.outcomes.items():
# Do not compare outcome with itself when checking for existing name/id
if check_outcome is not outcome:
if check_outcome.outcome_id == outcome_id:
return False, "outcome id '{0}' existing in state".format(check_outcome.outcome_id)
if check_outcome.name == outcome.name:
return False, "outcome name '{0}' existing in state".format(check_outcome.name)
return True, "valid" | [
"def",
"_check_outcome_validity",
"(",
"self",
",",
"check_outcome",
")",
":",
"for",
"outcome_id",
",",
"outcome",
"in",
"self",
".",
"outcomes",
".",
"items",
"(",
")",
":",
"# Do not compare outcome with itself when checking for existing name/id",
"if",
"check_outcom... | Checks the validity of an outcome
Checks whether the id or the name of the outcome is already used by another outcome within the state.
:param rafcon.core.logical_port.Outcome check_outcome: The outcome to be checked
:return bool validity, str message: validity is True, when the outcome is valid, False else. message gives more
information especially if the outcome is not valid | [
"Checks",
"the",
"validity",
"of",
"an",
"outcome"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L751-L767 | train | 40,700 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State._check_data_port_validity | def _check_data_port_validity(self, check_data_port):
"""Checks the validity of a data port
Checks whether the data flows connected to the port do not conflict with the data types.
:param rafcon.core.data_port.DataPort check_data_port: The data port to be checked
:return bool validity, str message: validity is True, when the data port is valid, False else. message gives
more information especially if the data port is not valid
"""
valid, message = self._check_data_port_id(check_data_port)
if not valid:
return False, message
valid, message = self._check_data_port_name(check_data_port)
if not valid:
return False, message
# Check whether the type matches any connected data port type
# Only relevant, if there is a parent state, otherwise the port cannot be connected to data flows
# TODO: check of internal connections
if not self.is_root_state:
# Call the check in the parent state, where the data flows are stored
return self.parent.check_data_port_connection(check_data_port)
else:
from rafcon.core.states.container_state import ContainerState
if isinstance(self, ContainerState):
return self.check_data_port_connection(check_data_port)
return True, "valid" | python | def _check_data_port_validity(self, check_data_port):
"""Checks the validity of a data port
Checks whether the data flows connected to the port do not conflict with the data types.
:param rafcon.core.data_port.DataPort check_data_port: The data port to be checked
:return bool validity, str message: validity is True, when the data port is valid, False else. message gives
more information especially if the data port is not valid
"""
valid, message = self._check_data_port_id(check_data_port)
if not valid:
return False, message
valid, message = self._check_data_port_name(check_data_port)
if not valid:
return False, message
# Check whether the type matches any connected data port type
# Only relevant, if there is a parent state, otherwise the port cannot be connected to data flows
# TODO: check of internal connections
if not self.is_root_state:
# Call the check in the parent state, where the data flows are stored
return self.parent.check_data_port_connection(check_data_port)
else:
from rafcon.core.states.container_state import ContainerState
if isinstance(self, ContainerState):
return self.check_data_port_connection(check_data_port)
return True, "valid" | [
"def",
"_check_data_port_validity",
"(",
"self",
",",
"check_data_port",
")",
":",
"valid",
",",
"message",
"=",
"self",
".",
"_check_data_port_id",
"(",
"check_data_port",
")",
"if",
"not",
"valid",
":",
"return",
"False",
",",
"message",
"valid",
",",
"messa... | Checks the validity of a data port
Checks whether the data flows connected to the port do not conflict with the data types.
:param rafcon.core.data_port.DataPort check_data_port: The data port to be checked
:return bool validity, str message: validity is True, when the data port is valid, False else. message gives
more information especially if the data port is not valid | [
"Checks",
"the",
"validity",
"of",
"a",
"data",
"port"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L769-L797 | train | 40,701 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.check_input_data_type | def check_input_data_type(self):
"""Check the input data types of the state
Checks all input data ports if the handed data is not of the specified type and generate an error logger message
with details of the found type conflict.
"""
for data_port in self.input_data_ports.values():
if data_port.name in self.input_data and self.input_data[data_port.name] is not None:
#check for class
if not isinstance(self.input_data[data_port.name], data_port.data_type):
logger.error("{0} had an data port error: Input of execute function must be of type '{1}' not '{2}'"
" as current value '{3}'".format(self, data_port.data_type.__name__,
type(self.input_data[data_port.name]).__name__,
self.input_data[data_port.name])) | python | def check_input_data_type(self):
"""Check the input data types of the state
Checks all input data ports if the handed data is not of the specified type and generate an error logger message
with details of the found type conflict.
"""
for data_port in self.input_data_ports.values():
if data_port.name in self.input_data and self.input_data[data_port.name] is not None:
#check for class
if not isinstance(self.input_data[data_port.name], data_port.data_type):
logger.error("{0} had an data port error: Input of execute function must be of type '{1}' not '{2}'"
" as current value '{3}'".format(self, data_port.data_type.__name__,
type(self.input_data[data_port.name]).__name__,
self.input_data[data_port.name])) | [
"def",
"check_input_data_type",
"(",
"self",
")",
":",
"for",
"data_port",
"in",
"self",
".",
"input_data_ports",
".",
"values",
"(",
")",
":",
"if",
"data_port",
".",
"name",
"in",
"self",
".",
"input_data",
"and",
"self",
".",
"input_data",
"[",
"data_po... | Check the input data types of the state
Checks all input data ports if the handed data is not of the specified type and generate an error logger message
with details of the found type conflict. | [
"Check",
"the",
"input",
"data",
"types",
"of",
"the",
"state"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L839-L852 | train | 40,702 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.check_output_data_type | def check_output_data_type(self):
"""Check the output data types of the state
Checks all output data ports if the handed data is not of the specified type and generate an error logger
message with details of the found type conflict.
"""
for data_port in self.output_data_ports.values():
if data_port.name in self.output_data and self.output_data[data_port.name] is not None:
# check for class
if not isinstance(self.output_data[data_port.name], data_port.data_type):
logger.error("{0} had an data port error: Output of execute function must be of type '{1}' not "
"'{2}' as current value {3}".format(self, data_port.data_type.__name__,
type(self.output_data[data_port.name]).__name__,
self.output_data[data_port.name])) | python | def check_output_data_type(self):
"""Check the output data types of the state
Checks all output data ports if the handed data is not of the specified type and generate an error logger
message with details of the found type conflict.
"""
for data_port in self.output_data_ports.values():
if data_port.name in self.output_data and self.output_data[data_port.name] is not None:
# check for class
if not isinstance(self.output_data[data_port.name], data_port.data_type):
logger.error("{0} had an data port error: Output of execute function must be of type '{1}' not "
"'{2}' as current value {3}".format(self, data_port.data_type.__name__,
type(self.output_data[data_port.name]).__name__,
self.output_data[data_port.name])) | [
"def",
"check_output_data_type",
"(",
"self",
")",
":",
"for",
"data_port",
"in",
"self",
".",
"output_data_ports",
".",
"values",
"(",
")",
":",
"if",
"data_port",
".",
"name",
"in",
"self",
".",
"output_data",
"and",
"self",
".",
"output_data",
"[",
"dat... | Check the output data types of the state
Checks all output data ports if the handed data is not of the specified type and generate an error logger
message with details of the found type conflict. | [
"Check",
"the",
"output",
"data",
"types",
"of",
"the",
"state"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L854-L867 | train | 40,703 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.change_state_id | def change_state_id(self, state_id=None):
"""Changes the id of the state to a new id
If no state_id is passed as parameter, a new state id is generated.
:param str state_id: The new state id of the state
:return:
"""
if state_id is None:
state_id = state_id_generator(used_state_ids=[self.state_id])
if not self.is_root_state and not self.is_root_state_of_library:
used_ids = list(self.parent.states.keys()) + [self.parent.state_id, self.state_id]
if state_id in used_ids:
state_id = state_id_generator(used_state_ids=used_ids)
self._state_id = state_id | python | def change_state_id(self, state_id=None):
"""Changes the id of the state to a new id
If no state_id is passed as parameter, a new state id is generated.
:param str state_id: The new state id of the state
:return:
"""
if state_id is None:
state_id = state_id_generator(used_state_ids=[self.state_id])
if not self.is_root_state and not self.is_root_state_of_library:
used_ids = list(self.parent.states.keys()) + [self.parent.state_id, self.state_id]
if state_id in used_ids:
state_id = state_id_generator(used_state_ids=used_ids)
self._state_id = state_id | [
"def",
"change_state_id",
"(",
"self",
",",
"state_id",
"=",
"None",
")",
":",
"if",
"state_id",
"is",
"None",
":",
"state_id",
"=",
"state_id_generator",
"(",
"used_state_ids",
"=",
"[",
"self",
".",
"state_id",
"]",
")",
"if",
"not",
"self",
".",
"is_r... | Changes the id of the state to a new id
If no state_id is passed as parameter, a new state id is generated.
:param str state_id: The new state id of the state
:return: | [
"Changes",
"the",
"id",
"of",
"the",
"state",
"to",
"a",
"new",
"id"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L877-L892 | train | 40,704 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.get_semantic_data | def get_semantic_data(self, path_as_list):
""" Retrieves an entry of the semantic data.
:param list path_as_list: The path in the vividict to retrieve the value from
:return:
"""
target_dict = self.semantic_data
for path_element in path_as_list:
if path_element in target_dict:
target_dict = target_dict[path_element]
else:
raise KeyError("The state with name {1} and id {2} holds no semantic data with path {0}."
"".format(path_as_list[:path_as_list.index(path_element) + 1], self.name, self.state_id))
return target_dict | python | def get_semantic_data(self, path_as_list):
""" Retrieves an entry of the semantic data.
:param list path_as_list: The path in the vividict to retrieve the value from
:return:
"""
target_dict = self.semantic_data
for path_element in path_as_list:
if path_element in target_dict:
target_dict = target_dict[path_element]
else:
raise KeyError("The state with name {1} and id {2} holds no semantic data with path {0}."
"".format(path_as_list[:path_as_list.index(path_element) + 1], self.name, self.state_id))
return target_dict | [
"def",
"get_semantic_data",
"(",
"self",
",",
"path_as_list",
")",
":",
"target_dict",
"=",
"self",
".",
"semantic_data",
"for",
"path_element",
"in",
"path_as_list",
":",
"if",
"path_element",
"in",
"target_dict",
":",
"target_dict",
"=",
"target_dict",
"[",
"p... | Retrieves an entry of the semantic data.
:param list path_as_list: The path in the vividict to retrieve the value from
:return: | [
"Retrieves",
"an",
"entry",
"of",
"the",
"semantic",
"data",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L910-L924 | train | 40,705 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.add_semantic_data | def add_semantic_data(self, path_as_list, value, key):
""" Adds a semantic data entry.
:param list path_as_list: The path in the vividict to enter the value
:param value: The value of the new entry.
:param key: The key of the new entry.
:return:
"""
assert isinstance(key, string_types)
target_dict = self.get_semantic_data(path_as_list)
target_dict[key] = value
return path_as_list + [key] | python | def add_semantic_data(self, path_as_list, value, key):
""" Adds a semantic data entry.
:param list path_as_list: The path in the vividict to enter the value
:param value: The value of the new entry.
:param key: The key of the new entry.
:return:
"""
assert isinstance(key, string_types)
target_dict = self.get_semantic_data(path_as_list)
target_dict[key] = value
return path_as_list + [key] | [
"def",
"add_semantic_data",
"(",
"self",
",",
"path_as_list",
",",
"value",
",",
"key",
")",
":",
"assert",
"isinstance",
"(",
"key",
",",
"string_types",
")",
"target_dict",
"=",
"self",
".",
"get_semantic_data",
"(",
"path_as_list",
")",
"target_dict",
"[",
... | Adds a semantic data entry.
:param list path_as_list: The path in the vividict to enter the value
:param value: The value of the new entry.
:param key: The key of the new entry.
:return: | [
"Adds",
"a",
"semantic",
"data",
"entry",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L927-L938 | train | 40,706 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.remove_semantic_data | def remove_semantic_data(self, path_as_list):
""" Removes a entry from the semantic data vividict.
:param list path_as_list: The path of the vividict to delete.
:return: removed value or dict
"""
if len(path_as_list) == 0:
raise AttributeError("The argument path_as_list is empty but but the method remove_semantic_data needs a "
"valid path to remove a vividict item.")
target_dict = self.get_semantic_data(path_as_list[0:-1])
removed_element = target_dict[path_as_list[-1]]
del target_dict[path_as_list[-1]]
return removed_element | python | def remove_semantic_data(self, path_as_list):
""" Removes a entry from the semantic data vividict.
:param list path_as_list: The path of the vividict to delete.
:return: removed value or dict
"""
if len(path_as_list) == 0:
raise AttributeError("The argument path_as_list is empty but but the method remove_semantic_data needs a "
"valid path to remove a vividict item.")
target_dict = self.get_semantic_data(path_as_list[0:-1])
removed_element = target_dict[path_as_list[-1]]
del target_dict[path_as_list[-1]]
return removed_element | [
"def",
"remove_semantic_data",
"(",
"self",
",",
"path_as_list",
")",
":",
"if",
"len",
"(",
"path_as_list",
")",
"==",
"0",
":",
"raise",
"AttributeError",
"(",
"\"The argument path_as_list is empty but but the method remove_semantic_data needs a \"",
"\"valid path to remove... | Removes a entry from the semantic data vividict.
:param list path_as_list: The path of the vividict to delete.
:return: removed value or dict | [
"Removes",
"a",
"entry",
"from",
"the",
"semantic",
"data",
"vividict",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L941-L953 | train | 40,707 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.input_data_ports | def input_data_ports(self, input_data_ports):
"""Property for the _input_data_ports field
See Property.
:param dict input_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type
:class:`rafcon.core.state_elements.data_port.InputDataPort`
:raises exceptions.TypeError: if the input_data_ports parameter has the wrong type
:raises exceptions.AttributeError: if the key of the input dictionary and the id of the data port do not match
"""
if not isinstance(input_data_ports, dict):
raise TypeError("input_data_ports must be of type dict")
if [port_id for port_id, port in input_data_ports.items() if not port_id == port.data_port_id]:
raise AttributeError("The key of the input dictionary and the id of the data port do not match")
# This is a fix for older state machines, which didn't distinguish between input and output ports
for port_id, port in input_data_ports.items():
if not isinstance(port, InputDataPort):
if isinstance(port, DataPort):
port = InputDataPort(port.name, port.data_type, port.default_value, port.data_port_id)
input_data_ports[port_id] = port
else:
raise TypeError("Elements of input_data_ports must be of type InputDataPort, given: {0}".format(
type(port).__name__))
old_input_data_ports = self._input_data_ports
self._input_data_ports = input_data_ports
for port_id, port in input_data_ports.items():
try:
port.parent = self
except ValueError:
self._input_data_ports = old_input_data_ports
raise
# check that all old_input_data_ports are no more referencing self as there parent
for old_input_data_port in old_input_data_ports.values():
if old_input_data_port not in self._input_data_ports.values() and old_input_data_port.parent is self:
old_input_data_port.parent = None | python | def input_data_ports(self, input_data_ports):
"""Property for the _input_data_ports field
See Property.
:param dict input_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type
:class:`rafcon.core.state_elements.data_port.InputDataPort`
:raises exceptions.TypeError: if the input_data_ports parameter has the wrong type
:raises exceptions.AttributeError: if the key of the input dictionary and the id of the data port do not match
"""
if not isinstance(input_data_ports, dict):
raise TypeError("input_data_ports must be of type dict")
if [port_id for port_id, port in input_data_ports.items() if not port_id == port.data_port_id]:
raise AttributeError("The key of the input dictionary and the id of the data port do not match")
# This is a fix for older state machines, which didn't distinguish between input and output ports
for port_id, port in input_data_ports.items():
if not isinstance(port, InputDataPort):
if isinstance(port, DataPort):
port = InputDataPort(port.name, port.data_type, port.default_value, port.data_port_id)
input_data_ports[port_id] = port
else:
raise TypeError("Elements of input_data_ports must be of type InputDataPort, given: {0}".format(
type(port).__name__))
old_input_data_ports = self._input_data_ports
self._input_data_ports = input_data_ports
for port_id, port in input_data_ports.items():
try:
port.parent = self
except ValueError:
self._input_data_ports = old_input_data_ports
raise
# check that all old_input_data_ports are no more referencing self as there parent
for old_input_data_port in old_input_data_ports.values():
if old_input_data_port not in self._input_data_ports.values() and old_input_data_port.parent is self:
old_input_data_port.parent = None | [
"def",
"input_data_ports",
"(",
"self",
",",
"input_data_ports",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_data_ports",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"input_data_ports must be of type dict\"",
")",
"if",
"[",
"port_id",
"for",
"port_id... | Property for the _input_data_ports field
See Property.
:param dict input_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type
:class:`rafcon.core.state_elements.data_port.InputDataPort`
:raises exceptions.TypeError: if the input_data_ports parameter has the wrong type
:raises exceptions.AttributeError: if the key of the input dictionary and the id of the data port do not match | [
"Property",
"for",
"the",
"_input_data_ports",
"field"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L1052-L1089 | train | 40,708 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.output_data_ports | def output_data_ports(self, output_data_ports):
""" Setter for _output_data_ports field
See property
:param dict output_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type
:class:`rafcon.core.state_elements.data_port.OutputDataPort`
:raises exceptions.TypeError: if the output_data_ports parameter has the wrong type
:raises exceptions.AttributeError: if the key of the output dictionary and the id of the data port do not match
"""
if not isinstance(output_data_ports, dict):
raise TypeError("output_data_ports must be of type dict")
if [port_id for port_id, port in output_data_ports.items() if not port_id == port.data_port_id]:
raise AttributeError("The key of the output dictionary and the id of the data port do not match")
# This is a fix for older state machines, which didn't distinguish between input and output ports
for port_id, port in output_data_ports.items():
if not isinstance(port, OutputDataPort):
if isinstance(port, DataPort):
port = OutputDataPort(port.name, port.data_type, port.default_value, port.data_port_id)
output_data_ports[port_id] = port
else:
raise TypeError("Elements of output_data_ports must be of type OutputDataPort, given: {0}".format(
type(port).__name__))
old_output_data_ports = self._output_data_ports
self._output_data_ports = output_data_ports
for port_id, port in output_data_ports.items():
try:
port.parent = self
except ValueError:
self._output_data_ports = old_output_data_ports
raise
# check that all old_output_data_ports are no more referencing self as there parent
for old_output_data_port in old_output_data_ports.values():
if old_output_data_port not in self._output_data_ports.values() and old_output_data_port.parent is self:
old_output_data_port.parent = None | python | def output_data_ports(self, output_data_ports):
""" Setter for _output_data_ports field
See property
:param dict output_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type
:class:`rafcon.core.state_elements.data_port.OutputDataPort`
:raises exceptions.TypeError: if the output_data_ports parameter has the wrong type
:raises exceptions.AttributeError: if the key of the output dictionary and the id of the data port do not match
"""
if not isinstance(output_data_ports, dict):
raise TypeError("output_data_ports must be of type dict")
if [port_id for port_id, port in output_data_ports.items() if not port_id == port.data_port_id]:
raise AttributeError("The key of the output dictionary and the id of the data port do not match")
# This is a fix for older state machines, which didn't distinguish between input and output ports
for port_id, port in output_data_ports.items():
if not isinstance(port, OutputDataPort):
if isinstance(port, DataPort):
port = OutputDataPort(port.name, port.data_type, port.default_value, port.data_port_id)
output_data_ports[port_id] = port
else:
raise TypeError("Elements of output_data_ports must be of type OutputDataPort, given: {0}".format(
type(port).__name__))
old_output_data_ports = self._output_data_ports
self._output_data_ports = output_data_ports
for port_id, port in output_data_ports.items():
try:
port.parent = self
except ValueError:
self._output_data_ports = old_output_data_ports
raise
# check that all old_output_data_ports are no more referencing self as there parent
for old_output_data_port in old_output_data_ports.values():
if old_output_data_port not in self._output_data_ports.values() and old_output_data_port.parent is self:
old_output_data_port.parent = None | [
"def",
"output_data_ports",
"(",
"self",
",",
"output_data_ports",
")",
":",
"if",
"not",
"isinstance",
"(",
"output_data_ports",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"output_data_ports must be of type dict\"",
")",
"if",
"[",
"port_id",
"for",
"por... | Setter for _output_data_ports field
See property
:param dict output_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type
:class:`rafcon.core.state_elements.data_port.OutputDataPort`
:raises exceptions.TypeError: if the output_data_ports parameter has the wrong type
:raises exceptions.AttributeError: if the key of the output dictionary and the id of the data port do not match | [
"Setter",
"for",
"_output_data_ports",
"field"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L1110-L1147 | train | 40,709 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.income | def income(self, income):
"""Setter for the state's income"""
if not isinstance(income, Income):
raise ValueError("income must be of type Income")
old_income = self.income
self._income = income
try:
income.parent = self
except ValueError:
self._income = old_income
raise | python | def income(self, income):
"""Setter for the state's income"""
if not isinstance(income, Income):
raise ValueError("income must be of type Income")
old_income = self.income
self._income = income
try:
income.parent = self
except ValueError:
self._income = old_income
raise | [
"def",
"income",
"(",
"self",
",",
"income",
")",
":",
"if",
"not",
"isinstance",
"(",
"income",
",",
"Income",
")",
":",
"raise",
"ValueError",
"(",
"\"income must be of type Income\"",
")",
"old_income",
"=",
"self",
".",
"income",
"self",
".",
"_income",
... | Setter for the state's income | [
"Setter",
"for",
"the",
"state",
"s",
"income"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L1161-L1172 | train | 40,710 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.outcomes | def outcomes(self, outcomes):
""" Setter for _outcomes field
See property.
:param dict outcomes: Dictionary outcomes[outcome_id] that maps :class:`int` outcome_ids onto values of type
:class:`rafcon.core.state_elements.logical_port.Outcome`
:raises exceptions.TypeError: if outcomes parameter has the wrong type
:raises exceptions.AttributeError: if the key of the outcome dictionary and the id of the outcome do not match
"""
if not isinstance(outcomes, dict):
raise TypeError("outcomes must be of type dict")
if [outcome_id for outcome_id, outcome in outcomes.items() if not isinstance(outcome, Outcome)]:
raise TypeError("element of outcomes must be of type Outcome")
if [outcome_id for outcome_id, outcome in outcomes.items() if not outcome_id == outcome.outcome_id]:
raise AttributeError("The key of the outcomes dictionary and the id of the outcome do not match")
old_outcomes = self.outcomes
self._outcomes = outcomes
for outcome_id, outcome in outcomes.items():
try:
outcome.parent = self
except ValueError:
self._outcomes = old_outcomes
raise
# aborted and preempted must always exist
if -1 not in outcomes:
self._outcomes[-1] = Outcome(outcome_id=-1, name="aborted", parent=self)
if -2 not in outcomes:
self._outcomes[-2] = Outcome(outcome_id=-2, name="preempted", parent=self)
# check that all old_outcomes are no more referencing self as there parent
for old_outcome in old_outcomes.values():
if old_outcome not in iter(list(self._outcomes.values())) and old_outcome.parent is self:
old_outcome.parent = None | python | def outcomes(self, outcomes):
""" Setter for _outcomes field
See property.
:param dict outcomes: Dictionary outcomes[outcome_id] that maps :class:`int` outcome_ids onto values of type
:class:`rafcon.core.state_elements.logical_port.Outcome`
:raises exceptions.TypeError: if outcomes parameter has the wrong type
:raises exceptions.AttributeError: if the key of the outcome dictionary and the id of the outcome do not match
"""
if not isinstance(outcomes, dict):
raise TypeError("outcomes must be of type dict")
if [outcome_id for outcome_id, outcome in outcomes.items() if not isinstance(outcome, Outcome)]:
raise TypeError("element of outcomes must be of type Outcome")
if [outcome_id for outcome_id, outcome in outcomes.items() if not outcome_id == outcome.outcome_id]:
raise AttributeError("The key of the outcomes dictionary and the id of the outcome do not match")
old_outcomes = self.outcomes
self._outcomes = outcomes
for outcome_id, outcome in outcomes.items():
try:
outcome.parent = self
except ValueError:
self._outcomes = old_outcomes
raise
# aborted and preempted must always exist
if -1 not in outcomes:
self._outcomes[-1] = Outcome(outcome_id=-1, name="aborted", parent=self)
if -2 not in outcomes:
self._outcomes[-2] = Outcome(outcome_id=-2, name="preempted", parent=self)
# check that all old_outcomes are no more referencing self as there parent
for old_outcome in old_outcomes.values():
if old_outcome not in iter(list(self._outcomes.values())) and old_outcome.parent is self:
old_outcome.parent = None | [
"def",
"outcomes",
"(",
"self",
",",
"outcomes",
")",
":",
"if",
"not",
"isinstance",
"(",
"outcomes",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"outcomes must be of type dict\"",
")",
"if",
"[",
"outcome_id",
"for",
"outcome_id",
",",
"outcome",
"... | Setter for _outcomes field
See property.
:param dict outcomes: Dictionary outcomes[outcome_id] that maps :class:`int` outcome_ids onto values of type
:class:`rafcon.core.state_elements.logical_port.Outcome`
:raises exceptions.TypeError: if outcomes parameter has the wrong type
:raises exceptions.AttributeError: if the key of the outcome dictionary and the id of the outcome do not match | [
"Setter",
"for",
"_outcomes",
"field"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L1192-L1227 | train | 40,711 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.get_next_upper_library_root_state | def get_next_upper_library_root_state(self):
""" Get next upper library root state
The method recursively checks state parent states till finding a StateMachine as parent or a library root state.
If self is a LibraryState the next upper library root state is searched and it is not handed self.state_copy.
:return library root state (Execution or ContainerState) or None if self is not a library root state or
inside of such
:rtype rafcon.core.states.library_state.State:
"""
from rafcon.core.state_machine import StateMachine
if self.is_root_state_of_library:
return self
state = self
while state.parent is not None and not isinstance(state.parent, StateMachine):
if state.parent.is_root_state_of_library:
return state.parent
state = state.parent
return None | python | def get_next_upper_library_root_state(self):
""" Get next upper library root state
The method recursively checks state parent states till finding a StateMachine as parent or a library root state.
If self is a LibraryState the next upper library root state is searched and it is not handed self.state_copy.
:return library root state (Execution or ContainerState) or None if self is not a library root state or
inside of such
:rtype rafcon.core.states.library_state.State:
"""
from rafcon.core.state_machine import StateMachine
if self.is_root_state_of_library:
return self
state = self
while state.parent is not None and not isinstance(state.parent, StateMachine):
if state.parent.is_root_state_of_library:
return state.parent
state = state.parent
return None | [
"def",
"get_next_upper_library_root_state",
"(",
"self",
")",
":",
"from",
"rafcon",
".",
"core",
".",
"state_machine",
"import",
"StateMachine",
"if",
"self",
".",
"is_root_state_of_library",
":",
"return",
"self",
"state",
"=",
"self",
"while",
"state",
".",
"... | Get next upper library root state
The method recursively checks state parent states till finding a StateMachine as parent or a library root state.
If self is a LibraryState the next upper library root state is searched and it is not handed self.state_copy.
:return library root state (Execution or ContainerState) or None if self is not a library root state or
inside of such
:rtype rafcon.core.states.library_state.State: | [
"Get",
"next",
"upper",
"library",
"root",
"state"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L1419-L1439 | train | 40,712 |
DLR-RM/RAFCON | source/rafcon/core/states/state.py | State.get_uppermost_library_root_state | def get_uppermost_library_root_state(self):
"""Find state_copy of uppermost LibraryState
Method checks if there is a parent library root state and assigns it to be the current library root state till
there is no further parent library root state.
"""
library_root_state = self.get_next_upper_library_root_state()
parent_library_root_state = library_root_state
# initial a library root state has to be found and if there is no further parent root state
# parent_library_root_state and library_root_state are no more identical
while parent_library_root_state and library_root_state is parent_library_root_state:
if library_root_state:
parent_library_root_state = library_root_state.parent.get_next_upper_library_root_state()
if parent_library_root_state:
library_root_state = parent_library_root_state
return library_root_state | python | def get_uppermost_library_root_state(self):
"""Find state_copy of uppermost LibraryState
Method checks if there is a parent library root state and assigns it to be the current library root state till
there is no further parent library root state.
"""
library_root_state = self.get_next_upper_library_root_state()
parent_library_root_state = library_root_state
# initial a library root state has to be found and if there is no further parent root state
# parent_library_root_state and library_root_state are no more identical
while parent_library_root_state and library_root_state is parent_library_root_state:
if library_root_state:
parent_library_root_state = library_root_state.parent.get_next_upper_library_root_state()
if parent_library_root_state:
library_root_state = parent_library_root_state
return library_root_state | [
"def",
"get_uppermost_library_root_state",
"(",
"self",
")",
":",
"library_root_state",
"=",
"self",
".",
"get_next_upper_library_root_state",
"(",
")",
"parent_library_root_state",
"=",
"library_root_state",
"# initial a library root state has to be found and if there is no further ... | Find state_copy of uppermost LibraryState
Method checks if there is a parent library root state and assigns it to be the current library root state till
there is no further parent library root state. | [
"Find",
"state_copy",
"of",
"uppermost",
"LibraryState"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L1441-L1459 | train | 40,713 |
openego/eTraGo | etrago/cluster/networkclustering.py | cluster_on_extra_high_voltage | def cluster_on_extra_high_voltage(network, busmap, with_time=True):
""" Main function of the EHV-Clustering approach. Creates a new clustered
pypsa.Network given a busmap mapping all bus_ids to other bus_ids of the
same network.
Parameters
----------
network : pypsa.Network
Container for all network components.
busmap : dict
Maps old bus_ids to new bus_ids.
with_time : bool
If true time-varying data will also be aggregated.
Returns
-------
network : pypsa.Network
Container for all network components of the clustered network.
"""
network_c = Network()
buses = aggregatebuses(
network, busmap, {
'x': _leading(
busmap, network.buses), 'y': _leading(
busmap, network.buses)})
# keep attached lines
lines = network.lines.copy()
mask = lines.bus0.isin(buses.index)
lines = lines.loc[mask, :]
# keep attached links
links = network.links.copy()
mask = links.bus0.isin(buses.index)
links = links.loc[mask, :]
# keep attached transformer
transformers = network.transformers.copy()
mask = transformers.bus0.isin(buses.index)
transformers = transformers.loc[mask, :]
io.import_components_from_dataframe(network_c, buses, "Bus")
io.import_components_from_dataframe(network_c, lines, "Line")
io.import_components_from_dataframe(network_c, links, "Link")
io.import_components_from_dataframe(network_c, transformers, "Transformer")
if with_time:
network_c.snapshots = network.snapshots
network_c.set_snapshots(network.snapshots)
network_c.snapshot_weightings = network.snapshot_weightings.copy()
# dealing with generators
network.generators.control = "PV"
network.generators['weight'] = 1
new_df, new_pnl = aggregategenerators(network, busmap, with_time)
io.import_components_from_dataframe(network_c, new_df, 'Generator')
for attr, df in iteritems(new_pnl):
io.import_series_from_dataframe(network_c, df, 'Generator', attr)
# dealing with all other components
aggregate_one_ports = components.one_port_components.copy()
aggregate_one_ports.discard('Generator')
for one_port in aggregate_one_ports:
new_df, new_pnl = aggregateoneport(
network, busmap, component=one_port, with_time=with_time)
io.import_components_from_dataframe(network_c, new_df, one_port)
for attr, df in iteritems(new_pnl):
io.import_series_from_dataframe(network_c, df, one_port, attr)
network_c.determine_network_topology()
return network_c | python | def cluster_on_extra_high_voltage(network, busmap, with_time=True):
""" Main function of the EHV-Clustering approach. Creates a new clustered
pypsa.Network given a busmap mapping all bus_ids to other bus_ids of the
same network.
Parameters
----------
network : pypsa.Network
Container for all network components.
busmap : dict
Maps old bus_ids to new bus_ids.
with_time : bool
If true time-varying data will also be aggregated.
Returns
-------
network : pypsa.Network
Container for all network components of the clustered network.
"""
network_c = Network()
buses = aggregatebuses(
network, busmap, {
'x': _leading(
busmap, network.buses), 'y': _leading(
busmap, network.buses)})
# keep attached lines
lines = network.lines.copy()
mask = lines.bus0.isin(buses.index)
lines = lines.loc[mask, :]
# keep attached links
links = network.links.copy()
mask = links.bus0.isin(buses.index)
links = links.loc[mask, :]
# keep attached transformer
transformers = network.transformers.copy()
mask = transformers.bus0.isin(buses.index)
transformers = transformers.loc[mask, :]
io.import_components_from_dataframe(network_c, buses, "Bus")
io.import_components_from_dataframe(network_c, lines, "Line")
io.import_components_from_dataframe(network_c, links, "Link")
io.import_components_from_dataframe(network_c, transformers, "Transformer")
if with_time:
network_c.snapshots = network.snapshots
network_c.set_snapshots(network.snapshots)
network_c.snapshot_weightings = network.snapshot_weightings.copy()
# dealing with generators
network.generators.control = "PV"
network.generators['weight'] = 1
new_df, new_pnl = aggregategenerators(network, busmap, with_time)
io.import_components_from_dataframe(network_c, new_df, 'Generator')
for attr, df in iteritems(new_pnl):
io.import_series_from_dataframe(network_c, df, 'Generator', attr)
# dealing with all other components
aggregate_one_ports = components.one_port_components.copy()
aggregate_one_ports.discard('Generator')
for one_port in aggregate_one_ports:
new_df, new_pnl = aggregateoneport(
network, busmap, component=one_port, with_time=with_time)
io.import_components_from_dataframe(network_c, new_df, one_port)
for attr, df in iteritems(new_pnl):
io.import_series_from_dataframe(network_c, df, one_port, attr)
network_c.determine_network_topology()
return network_c | [
"def",
"cluster_on_extra_high_voltage",
"(",
"network",
",",
"busmap",
",",
"with_time",
"=",
"True",
")",
":",
"network_c",
"=",
"Network",
"(",
")",
"buses",
"=",
"aggregatebuses",
"(",
"network",
",",
"busmap",
",",
"{",
"'x'",
":",
"_leading",
"(",
"bu... | Main function of the EHV-Clustering approach. Creates a new clustered
pypsa.Network given a busmap mapping all bus_ids to other bus_ids of the
same network.
Parameters
----------
network : pypsa.Network
Container for all network components.
busmap : dict
Maps old bus_ids to new bus_ids.
with_time : bool
If true time-varying data will also be aggregated.
Returns
-------
network : pypsa.Network
Container for all network components of the clustered network. | [
"Main",
"function",
"of",
"the",
"EHV",
"-",
"Clustering",
"approach",
".",
"Creates",
"a",
"new",
"clustered",
"pypsa",
".",
"Network",
"given",
"a",
"busmap",
"mapping",
"all",
"bus_ids",
"to",
"other",
"bus_ids",
"of",
"the",
"same",
"network",
"."
] | 2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9 | https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/cluster/networkclustering.py#L65-L141 | train | 40,714 |
openego/eTraGo | etrago/cluster/networkclustering.py | graph_from_edges | def graph_from_edges(edges):
""" Constructs an undirected multigraph from a list containing data on
weighted edges.
Parameters
----------
edges : list
List of tuples each containing first node, second node, weight, key.
Returns
-------
M : :class:`networkx.classes.multigraph.MultiGraph
"""
M = nx.MultiGraph()
for e in edges:
n0, n1, weight, key = e
M.add_edge(n0, n1, weight=weight, key=key)
return M | python | def graph_from_edges(edges):
""" Constructs an undirected multigraph from a list containing data on
weighted edges.
Parameters
----------
edges : list
List of tuples each containing first node, second node, weight, key.
Returns
-------
M : :class:`networkx.classes.multigraph.MultiGraph
"""
M = nx.MultiGraph()
for e in edges:
n0, n1, weight, key = e
M.add_edge(n0, n1, weight=weight, key=key)
return M | [
"def",
"graph_from_edges",
"(",
"edges",
")",
":",
"M",
"=",
"nx",
".",
"MultiGraph",
"(",
")",
"for",
"e",
"in",
"edges",
":",
"n0",
",",
"n1",
",",
"weight",
",",
"key",
"=",
"e",
"M",
".",
"add_edge",
"(",
"n0",
",",
"n1",
",",
"weight",
"="... | Constructs an undirected multigraph from a list containing data on
weighted edges.
Parameters
----------
edges : list
List of tuples each containing first node, second node, weight, key.
Returns
-------
M : :class:`networkx.classes.multigraph.MultiGraph | [
"Constructs",
"an",
"undirected",
"multigraph",
"from",
"a",
"list",
"containing",
"data",
"on",
"weighted",
"edges",
"."
] | 2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9 | https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/cluster/networkclustering.py#L144-L166 | train | 40,715 |
openego/eTraGo | etrago/cluster/networkclustering.py | gen | def gen(nodes, n, graph):
# TODO There could be a more convenient way of doing this. This generators
# single purpose is to prepare data for multiprocessing's starmap function.
""" Generator for applying multiprocessing.
Parameters
----------
nodes : list
List of nodes in the system.
n : int
Number of desired multiprocessing units.
graph : :class:`networkx.classes.multigraph.MultiGraph
Graph representation of an electrical grid.
Returns
-------
None
"""
g = graph.copy()
for i in range(0, len(nodes), n):
yield (nodes[i:i + n], g) | python | def gen(nodes, n, graph):
# TODO There could be a more convenient way of doing this. This generators
# single purpose is to prepare data for multiprocessing's starmap function.
""" Generator for applying multiprocessing.
Parameters
----------
nodes : list
List of nodes in the system.
n : int
Number of desired multiprocessing units.
graph : :class:`networkx.classes.multigraph.MultiGraph
Graph representation of an electrical grid.
Returns
-------
None
"""
g = graph.copy()
for i in range(0, len(nodes), n):
yield (nodes[i:i + n], g) | [
"def",
"gen",
"(",
"nodes",
",",
"n",
",",
"graph",
")",
":",
"# TODO There could be a more convenient way of doing this. This generators",
"# single purpose is to prepare data for multiprocessing's starmap function.",
"g",
"=",
"graph",
".",
"copy",
"(",
")",
"for",
"i",
"... | Generator for applying multiprocessing.
Parameters
----------
nodes : list
List of nodes in the system.
n : int
Number of desired multiprocessing units.
graph : :class:`networkx.classes.multigraph.MultiGraph
Graph representation of an electrical grid.
Returns
-------
None | [
"Generator",
"for",
"applying",
"multiprocessing",
"."
] | 2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9 | https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/cluster/networkclustering.py#L169-L193 | train | 40,716 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController.on_drag_data_received | def on_drag_data_received(self, widget, context, x, y, data, info, time):
"""Receives state_id from LibraryTree and moves the state to the position of the mouse
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:param data: SelectionData: contains state_id
:param info:
:param time:
"""
state_id_insert = data.get_text()
parent_m = self.model.selection.get_selected_state()
if not isinstance(parent_m, ContainerStateModel):
return
state_v = self.canvas.get_view_for_model(parent_m.states[state_id_insert])
pos_start = state_v.model.get_meta_data_editor()['rel_pos']
motion = InMotion(state_v, self.view.editor)
motion.start_move(self.view.editor.get_matrix_i2v(state_v).transform_point(pos_start[0], pos_start[1]))
motion.move((x, y))
motion.stop_move()
state_v.model.set_meta_data_editor('rel_pos', motion.item.position)
self.canvas.wait_for_update(trigger_update=True)
self._meta_data_changed(None, state_v.model, 'append_to_last_change', True) | python | def on_drag_data_received(self, widget, context, x, y, data, info, time):
"""Receives state_id from LibraryTree and moves the state to the position of the mouse
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:param data: SelectionData: contains state_id
:param info:
:param time:
"""
state_id_insert = data.get_text()
parent_m = self.model.selection.get_selected_state()
if not isinstance(parent_m, ContainerStateModel):
return
state_v = self.canvas.get_view_for_model(parent_m.states[state_id_insert])
pos_start = state_v.model.get_meta_data_editor()['rel_pos']
motion = InMotion(state_v, self.view.editor)
motion.start_move(self.view.editor.get_matrix_i2v(state_v).transform_point(pos_start[0], pos_start[1]))
motion.move((x, y))
motion.stop_move()
state_v.model.set_meta_data_editor('rel_pos', motion.item.position)
self.canvas.wait_for_update(trigger_update=True)
self._meta_data_changed(None, state_v.model, 'append_to_last_change', True) | [
"def",
"on_drag_data_received",
"(",
"self",
",",
"widget",
",",
"context",
",",
"x",
",",
"y",
",",
"data",
",",
"info",
",",
"time",
")",
":",
"state_id_insert",
"=",
"data",
".",
"get_text",
"(",
")",
"parent_m",
"=",
"self",
".",
"model",
".",
"s... | Receives state_id from LibraryTree and moves the state to the position of the mouse
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:param data: SelectionData: contains state_id
:param info:
:param time: | [
"Receives",
"state_id",
"from",
"LibraryTree",
"and",
"moves",
"the",
"state",
"to",
"the",
"position",
"of",
"the",
"mouse"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L161-L184 | train | 40,717 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController.on_drag_motion | def on_drag_motion(self, widget, context, x, y, time):
"""Changes the selection on mouse over during drag motion
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:param time:
"""
hovered_item = ItemFinder(self.view.editor).get_item_at_point((x, y))
if isinstance(hovered_item, NameView):
hovered_item = hovered_item.parent
if hovered_item is None:
self.view.editor.unselect_all()
elif isinstance(hovered_item.model, ContainerStateModel):
if len(self.view.editor.selected_items) == 1 and hovered_item in self.view.editor.selected_items:
return
if len(self.view.editor.selected_items) > 0:
self.view.editor.unselect_all()
if not rafcon.gui.singleton.global_gui_config.get_config_value('DRAG_N_DROP_WITH_FOCUS'):
self.view.editor.handler_block(self.focus_changed_handler_id)
self.view.editor.focused_item = hovered_item
if not rafcon.gui.singleton.global_gui_config.get_config_value('DRAG_N_DROP_WITH_FOCUS'):
self.view.editor.handler_unblock(self.focus_changed_handler_id) | python | def on_drag_motion(self, widget, context, x, y, time):
"""Changes the selection on mouse over during drag motion
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:param time:
"""
hovered_item = ItemFinder(self.view.editor).get_item_at_point((x, y))
if isinstance(hovered_item, NameView):
hovered_item = hovered_item.parent
if hovered_item is None:
self.view.editor.unselect_all()
elif isinstance(hovered_item.model, ContainerStateModel):
if len(self.view.editor.selected_items) == 1 and hovered_item in self.view.editor.selected_items:
return
if len(self.view.editor.selected_items) > 0:
self.view.editor.unselect_all()
if not rafcon.gui.singleton.global_gui_config.get_config_value('DRAG_N_DROP_WITH_FOCUS'):
self.view.editor.handler_block(self.focus_changed_handler_id)
self.view.editor.focused_item = hovered_item
if not rafcon.gui.singleton.global_gui_config.get_config_value('DRAG_N_DROP_WITH_FOCUS'):
self.view.editor.handler_unblock(self.focus_changed_handler_id) | [
"def",
"on_drag_motion",
"(",
"self",
",",
"widget",
",",
"context",
",",
"x",
",",
"y",
",",
"time",
")",
":",
"hovered_item",
"=",
"ItemFinder",
"(",
"self",
".",
"view",
".",
"editor",
")",
".",
"get_item_at_point",
"(",
"(",
"x",
",",
"y",
")",
... | Changes the selection on mouse over during drag motion
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:param time: | [
"Changes",
"the",
"selection",
"on",
"mouse",
"over",
"during",
"drag",
"motion"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L187-L211 | train | 40,718 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController._copy_selection | def _copy_selection(self, *event):
"""Copies the current selection to the clipboard.
"""
if react_to_event(self.view, self.view.editor, event):
logger.debug("copy selection")
global_clipboard.copy(self.model.selection)
return True | python | def _copy_selection(self, *event):
"""Copies the current selection to the clipboard.
"""
if react_to_event(self.view, self.view.editor, event):
logger.debug("copy selection")
global_clipboard.copy(self.model.selection)
return True | [
"def",
"_copy_selection",
"(",
"self",
",",
"*",
"event",
")",
":",
"if",
"react_to_event",
"(",
"self",
".",
"view",
",",
"self",
".",
"view",
".",
"editor",
",",
"event",
")",
":",
"logger",
".",
"debug",
"(",
"\"copy selection\"",
")",
"global_clipboa... | Copies the current selection to the clipboard. | [
"Copies",
"the",
"current",
"selection",
"to",
"the",
"clipboard",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L231-L237 | train | 40,719 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController._cut_selection | def _cut_selection(self, *event):
"""Cuts the current selection and copys it to the clipboard.
"""
if react_to_event(self.view, self.view.editor, event):
logger.debug("cut selection")
global_clipboard.cut(self.model.selection)
return True | python | def _cut_selection(self, *event):
"""Cuts the current selection and copys it to the clipboard.
"""
if react_to_event(self.view, self.view.editor, event):
logger.debug("cut selection")
global_clipboard.cut(self.model.selection)
return True | [
"def",
"_cut_selection",
"(",
"self",
",",
"*",
"event",
")",
":",
"if",
"react_to_event",
"(",
"self",
".",
"view",
",",
"self",
".",
"view",
".",
"editor",
",",
"event",
")",
":",
"logger",
".",
"debug",
"(",
"\"cut selection\"",
")",
"global_clipboard... | Cuts the current selection and copys it to the clipboard. | [
"Cuts",
"the",
"current",
"selection",
"and",
"copys",
"it",
"to",
"the",
"clipboard",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L240-L246 | train | 40,720 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController._paste_clipboard | def _paste_clipboard(self, *event):
"""Paste the current clipboard into the current selection if the current selection is a container state.
"""
if react_to_event(self.view, self.view.editor, event):
logger.debug("Paste")
gui_helper_state_machine.paste_into_selected_state(self.model)
return True | python | def _paste_clipboard(self, *event):
"""Paste the current clipboard into the current selection if the current selection is a container state.
"""
if react_to_event(self.view, self.view.editor, event):
logger.debug("Paste")
gui_helper_state_machine.paste_into_selected_state(self.model)
return True | [
"def",
"_paste_clipboard",
"(",
"self",
",",
"*",
"event",
")",
":",
"if",
"react_to_event",
"(",
"self",
".",
"view",
",",
"self",
".",
"view",
".",
"editor",
",",
"event",
")",
":",
"logger",
".",
"debug",
"(",
"\"Paste\"",
")",
"gui_helper_state_machi... | Paste the current clipboard into the current selection if the current selection is a container state. | [
"Paste",
"the",
"current",
"clipboard",
"into",
"the",
"current",
"selection",
"if",
"the",
"current",
"selection",
"is",
"a",
"container",
"state",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L249-L255 | train | 40,721 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController._move_focused_item_into_viewport | def _move_focused_item_into_viewport(self, view, focused_item):
"""Called when an item is focused, moves the item into the viewport
:param view:
:param StateView | ConnectionView | PortView focused_item: The focused item
"""
self.view.editor.handler_block(self.drag_motion_handler_id)
self.move_item_into_viewport(focused_item)
self.view.editor.handler_unblock(self.drag_motion_handler_id) | python | def _move_focused_item_into_viewport(self, view, focused_item):
"""Called when an item is focused, moves the item into the viewport
:param view:
:param StateView | ConnectionView | PortView focused_item: The focused item
"""
self.view.editor.handler_block(self.drag_motion_handler_id)
self.move_item_into_viewport(focused_item)
self.view.editor.handler_unblock(self.drag_motion_handler_id) | [
"def",
"_move_focused_item_into_viewport",
"(",
"self",
",",
"view",
",",
"focused_item",
")",
":",
"self",
".",
"view",
".",
"editor",
".",
"handler_block",
"(",
"self",
".",
"drag_motion_handler_id",
")",
"self",
".",
"move_item_into_viewport",
"(",
"focused_ite... | Called when an item is focused, moves the item into the viewport
:param view:
:param StateView | ConnectionView | PortView focused_item: The focused item | [
"Called",
"when",
"an",
"item",
"is",
"focused",
"moves",
"the",
"item",
"into",
"the",
"viewport"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L257-L265 | train | 40,722 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController.move_item_into_viewport | def move_item_into_viewport(self, item):
"""Causes the `item` to be moved into the viewport
The zoom factor and the position of the viewport are updated to move the `item` into the viewport. If `item`
is not a `StateView`, the parental `StateView` is moved into the viewport.
:param StateView | ConnectionView | PortView item: The item to be moved into the viewport
"""
if not item:
return
HORIZONTAL = 0
VERTICAL = 1
if not isinstance(item, Item):
state_v = item.parent
elif not isinstance(item, StateView):
state_v = self.canvas.get_parent(item)
else:
state_v = item
viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height
state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height)
min_relative_size = min(viewport_size[i] / state_size[i] for i in [HORIZONTAL, VERTICAL])
if min_relative_size != 1:
# Allow margin around state
margin_relative = 1. / gui_constants.BORDER_WIDTH_STATE_SIZE_FACTOR
zoom_factor = min_relative_size * (1 - margin_relative)
if zoom_factor > 1:
zoom_base = 4
zoom_factor = max(1, math.log(zoom_factor*zoom_base, zoom_base))
self.view.editor.zoom(zoom_factor)
# The zoom operation must be performed before the pan operation to work on updated GtkAdjustments (scroll
# bars)
self.canvas.wait_for_update()
state_pos = self.view.editor.get_matrix_i2v(state_v).transform_point(0, 0)
state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height)
viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height
# Calculate offset around state so that the state is centered in the viewport
padding_offset_horizontal = (viewport_size[HORIZONTAL] - state_size[HORIZONTAL]) / 2.
padding_offset_vertical = (viewport_size[VERTICAL] - state_size[VERTICAL]) / 2.
self.view.editor.hadjustment.set_value(state_pos[HORIZONTAL] - padding_offset_horizontal)
self.view.editor.vadjustment.set_value(state_pos[VERTICAL] - padding_offset_vertical) | python | def move_item_into_viewport(self, item):
"""Causes the `item` to be moved into the viewport
The zoom factor and the position of the viewport are updated to move the `item` into the viewport. If `item`
is not a `StateView`, the parental `StateView` is moved into the viewport.
:param StateView | ConnectionView | PortView item: The item to be moved into the viewport
"""
if not item:
return
HORIZONTAL = 0
VERTICAL = 1
if not isinstance(item, Item):
state_v = item.parent
elif not isinstance(item, StateView):
state_v = self.canvas.get_parent(item)
else:
state_v = item
viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height
state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height)
min_relative_size = min(viewport_size[i] / state_size[i] for i in [HORIZONTAL, VERTICAL])
if min_relative_size != 1:
# Allow margin around state
margin_relative = 1. / gui_constants.BORDER_WIDTH_STATE_SIZE_FACTOR
zoom_factor = min_relative_size * (1 - margin_relative)
if zoom_factor > 1:
zoom_base = 4
zoom_factor = max(1, math.log(zoom_factor*zoom_base, zoom_base))
self.view.editor.zoom(zoom_factor)
# The zoom operation must be performed before the pan operation to work on updated GtkAdjustments (scroll
# bars)
self.canvas.wait_for_update()
state_pos = self.view.editor.get_matrix_i2v(state_v).transform_point(0, 0)
state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height)
viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height
# Calculate offset around state so that the state is centered in the viewport
padding_offset_horizontal = (viewport_size[HORIZONTAL] - state_size[HORIZONTAL]) / 2.
padding_offset_vertical = (viewport_size[VERTICAL] - state_size[VERTICAL]) / 2.
self.view.editor.hadjustment.set_value(state_pos[HORIZONTAL] - padding_offset_horizontal)
self.view.editor.vadjustment.set_value(state_pos[VERTICAL] - padding_offset_vertical) | [
"def",
"move_item_into_viewport",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"item",
":",
"return",
"HORIZONTAL",
"=",
"0",
"VERTICAL",
"=",
"1",
"if",
"not",
"isinstance",
"(",
"item",
",",
"Item",
")",
":",
"state_v",
"=",
"item",
".",
"parent"... | Causes the `item` to be moved into the viewport
The zoom factor and the position of the viewport are updated to move the `item` into the viewport. If `item`
is not a `StateView`, the parental `StateView` is moved into the viewport.
:param StateView | ConnectionView | PortView item: The item to be moved into the viewport | [
"Causes",
"the",
"item",
"to",
"be",
"moved",
"into",
"the",
"viewport"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L267-L309 | train | 40,723 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController.state_machine_destruction | def state_machine_destruction(self, model, prop_name, info):
""" Clean up when state machine is being destructed """
if self.model is model: # only used for the state machine destruction case
self.canvas.get_view_for_model(self.root_state_m).remove() | python | def state_machine_destruction(self, model, prop_name, info):
""" Clean up when state machine is being destructed """
if self.model is model: # only used for the state machine destruction case
self.canvas.get_view_for_model(self.root_state_m).remove() | [
"def",
"state_machine_destruction",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"if",
"self",
".",
"model",
"is",
"model",
":",
"# only used for the state machine destruction case",
"self",
".",
"canvas",
".",
"get_view_for_model",
"(",
"se... | Clean up when state machine is being destructed | [
"Clean",
"up",
"when",
"state",
"machine",
"is",
"being",
"destructed"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L316-L319 | train | 40,724 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController.meta_changed_notify_after | def meta_changed_notify_after(self, state_machine_m, _, info):
"""Handle notification about the change of a state's meta data
The meta data of the affected state(s) are read and the view updated accordingly.
:param StateMachineModel state_machine_m: Always the state machine model belonging to this editor
:param str _: Always "state_meta_signal"
:param dict info: Information about the change, contains the MetaSignalMessage in the 'arg' key value
"""
meta_signal_message = info['arg']
if meta_signal_message.origin == "graphical_editor_gaphas": # Ignore changes caused by ourself
return
if meta_signal_message.origin == "load_meta_data": # Meta data can't be applied, as the view has not yet
return # been created
notification = meta_signal_message.notification
if not notification: # For changes applied to the root state, there are always two notifications
return # Ignore the one with less information
if self.model.ongoing_complex_actions:
return
model = notification.model
view = self.canvas.get_view_for_model(model)
if meta_signal_message.change == 'show_content':
library_state_m = model
library_state_v = view
if library_state_m.meta['gui']['show_content'] is not library_state_m.show_content():
logger.warning("The content of the LibraryState won't be shown, because "
"MAX_VISIBLE_LIBRARY_HIERARCHY is 1.")
if library_state_m.show_content():
if not library_state_m.state_copy_initialized:
logger.warning("Show library content without initialized state copy does not work {0}"
"".format(library_state_m))
logger.debug("Show content of {}".format(library_state_m.state))
gui_helper_meta_data.scale_library_content(library_state_m)
self.add_state_view_for_model(library_state_m.state_copy, view,
hierarchy_level=library_state_v.hierarchy_level + 1)
else:
logger.debug("Hide content of {}".format(library_state_m.state))
state_copy_v = self.canvas.get_view_for_model(library_state_m.state_copy)
if state_copy_v:
state_copy_v.remove()
else:
if isinstance(view, StateView):
view.apply_meta_data(recursive=meta_signal_message.affects_children)
else:
view.apply_meta_data()
self.canvas.request_update(view, matrix=True)
self.canvas.wait_for_update() | python | def meta_changed_notify_after(self, state_machine_m, _, info):
"""Handle notification about the change of a state's meta data
The meta data of the affected state(s) are read and the view updated accordingly.
:param StateMachineModel state_machine_m: Always the state machine model belonging to this editor
:param str _: Always "state_meta_signal"
:param dict info: Information about the change, contains the MetaSignalMessage in the 'arg' key value
"""
meta_signal_message = info['arg']
if meta_signal_message.origin == "graphical_editor_gaphas": # Ignore changes caused by ourself
return
if meta_signal_message.origin == "load_meta_data": # Meta data can't be applied, as the view has not yet
return # been created
notification = meta_signal_message.notification
if not notification: # For changes applied to the root state, there are always two notifications
return # Ignore the one with less information
if self.model.ongoing_complex_actions:
return
model = notification.model
view = self.canvas.get_view_for_model(model)
if meta_signal_message.change == 'show_content':
library_state_m = model
library_state_v = view
if library_state_m.meta['gui']['show_content'] is not library_state_m.show_content():
logger.warning("The content of the LibraryState won't be shown, because "
"MAX_VISIBLE_LIBRARY_HIERARCHY is 1.")
if library_state_m.show_content():
if not library_state_m.state_copy_initialized:
logger.warning("Show library content without initialized state copy does not work {0}"
"".format(library_state_m))
logger.debug("Show content of {}".format(library_state_m.state))
gui_helper_meta_data.scale_library_content(library_state_m)
self.add_state_view_for_model(library_state_m.state_copy, view,
hierarchy_level=library_state_v.hierarchy_level + 1)
else:
logger.debug("Hide content of {}".format(library_state_m.state))
state_copy_v = self.canvas.get_view_for_model(library_state_m.state_copy)
if state_copy_v:
state_copy_v.remove()
else:
if isinstance(view, StateView):
view.apply_meta_data(recursive=meta_signal_message.affects_children)
else:
view.apply_meta_data()
self.canvas.request_update(view, matrix=True)
self.canvas.wait_for_update() | [
"def",
"meta_changed_notify_after",
"(",
"self",
",",
"state_machine_m",
",",
"_",
",",
"info",
")",
":",
"meta_signal_message",
"=",
"info",
"[",
"'arg'",
"]",
"if",
"meta_signal_message",
".",
"origin",
"==",
"\"graphical_editor_gaphas\"",
":",
"# Ignore changes c... | Handle notification about the change of a state's meta data
The meta data of the affected state(s) are read and the view updated accordingly.
:param StateMachineModel state_machine_m: Always the state machine model belonging to this editor
:param str _: Always "state_meta_signal"
:param dict info: Information about the change, contains the MetaSignalMessage in the 'arg' key value | [
"Handle",
"notification",
"about",
"the",
"change",
"of",
"a",
"state",
"s",
"meta",
"data"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L322-L370 | train | 40,725 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController.add_transition_view_for_model | def add_transition_view_for_model(self, transition_m, parent_state_m):
"""Creates a `TransitionView` and adds it to the canvas
The method creates a`TransitionView` from the given `TransitionModel `transition_m` and adds it to the canvas.
:param TransitionModel transition_m: The transition for which a view is to be created
:param ContainerStateModel parent_state_m: The parental `StateModel` of the transition
"""
parent_state_v = self.canvas.get_view_for_model(parent_state_m)
hierarchy_level = parent_state_v.hierarchy_level
transition_v = TransitionView(transition_m, hierarchy_level)
# Draw transition above all other state elements
self.canvas.add(transition_v, parent_state_v, index=None)
self._connect_transition_to_ports(transition_m, transition_v, parent_state_m, parent_state_v)
return transition_v | python | def add_transition_view_for_model(self, transition_m, parent_state_m):
"""Creates a `TransitionView` and adds it to the canvas
The method creates a`TransitionView` from the given `TransitionModel `transition_m` and adds it to the canvas.
:param TransitionModel transition_m: The transition for which a view is to be created
:param ContainerStateModel parent_state_m: The parental `StateModel` of the transition
"""
parent_state_v = self.canvas.get_view_for_model(parent_state_m)
hierarchy_level = parent_state_v.hierarchy_level
transition_v = TransitionView(transition_m, hierarchy_level)
# Draw transition above all other state elements
self.canvas.add(transition_v, parent_state_v, index=None)
self._connect_transition_to_ports(transition_m, transition_v, parent_state_m, parent_state_v)
return transition_v | [
"def",
"add_transition_view_for_model",
"(",
"self",
",",
"transition_m",
",",
"parent_state_m",
")",
":",
"parent_state_v",
"=",
"self",
".",
"canvas",
".",
"get_view_for_model",
"(",
"parent_state_m",
")",
"hierarchy_level",
"=",
"parent_state_v",
".",
"hierarchy_le... | Creates a `TransitionView` and adds it to the canvas
The method creates a`TransitionView` from the given `TransitionModel `transition_m` and adds it to the canvas.
:param TransitionModel transition_m: The transition for which a view is to be created
:param ContainerStateModel parent_state_m: The parental `StateModel` of the transition | [
"Creates",
"a",
"TransitionView",
"and",
"adds",
"it",
"to",
"the",
"canvas"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L834-L852 | train | 40,726 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController.add_data_flow_view_for_model | def add_data_flow_view_for_model(self, data_flow_m, parent_state_m):
"""Creates a `DataFlowView` and adds it to the canvas
The method creates a`DataFlowView` from the given `DataFlowModel `data_flow_m` and adds it to the canvas.
:param DataFlowModel data_flow_m: The data flow for which a view is to be created
:param ContainerStateModel parent_state_m: The parental `StateModel` of the data flow
"""
parent_state_v = self.canvas.get_view_for_model(parent_state_m)
hierarchy_level = parent_state_v.hierarchy_level
data_flow_v = DataFlowView(data_flow_m, hierarchy_level)
# Draw data flow above NameView but beneath all other state elements
self.canvas.add(data_flow_v, parent_state_v, index=1)
self._connect_data_flow_to_ports(data_flow_m, data_flow_v, parent_state_m) | python | def add_data_flow_view_for_model(self, data_flow_m, parent_state_m):
"""Creates a `DataFlowView` and adds it to the canvas
The method creates a`DataFlowView` from the given `DataFlowModel `data_flow_m` and adds it to the canvas.
:param DataFlowModel data_flow_m: The data flow for which a view is to be created
:param ContainerStateModel parent_state_m: The parental `StateModel` of the data flow
"""
parent_state_v = self.canvas.get_view_for_model(parent_state_m)
hierarchy_level = parent_state_v.hierarchy_level
data_flow_v = DataFlowView(data_flow_m, hierarchy_level)
# Draw data flow above NameView but beneath all other state elements
self.canvas.add(data_flow_v, parent_state_v, index=1)
self._connect_data_flow_to_ports(data_flow_m, data_flow_v, parent_state_m) | [
"def",
"add_data_flow_view_for_model",
"(",
"self",
",",
"data_flow_m",
",",
"parent_state_m",
")",
":",
"parent_state_v",
"=",
"self",
".",
"canvas",
".",
"get_view_for_model",
"(",
"parent_state_m",
")",
"hierarchy_level",
"=",
"parent_state_v",
".",
"hierarchy_leve... | Creates a `DataFlowView` and adds it to the canvas
The method creates a`DataFlowView` from the given `DataFlowModel `data_flow_m` and adds it to the canvas.
:param DataFlowModel data_flow_m: The data flow for which a view is to be created
:param ContainerStateModel parent_state_m: The parental `StateModel` of the data flow | [
"Creates",
"a",
"DataFlowView",
"and",
"adds",
"it",
"to",
"the",
"canvas"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L855-L870 | train | 40,727 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/graphical_editor_gaphas.py | GraphicalEditorController.react_to_event | def react_to_event(self, event):
"""Check whether the given event should be handled
Checks, whether the editor widget has the focus and whether the selected state machine corresponds to the
state machine of this editor.
:param event: GTK event object
:return: True if the event should be handled, else False
:rtype: bool
"""
if not react_to_event(self.view, self.view.editor, event):
return False
if not rafcon.gui.singleton.state_machine_manager_model.selected_state_machine_id == \
self.model.state_machine.state_machine_id:
return False
return True | python | def react_to_event(self, event):
"""Check whether the given event should be handled
Checks, whether the editor widget has the focus and whether the selected state machine corresponds to the
state machine of this editor.
:param event: GTK event object
:return: True if the event should be handled, else False
:rtype: bool
"""
if not react_to_event(self.view, self.view.editor, event):
return False
if not rafcon.gui.singleton.state_machine_manager_model.selected_state_machine_id == \
self.model.state_machine.state_machine_id:
return False
return True | [
"def",
"react_to_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"react_to_event",
"(",
"self",
".",
"view",
",",
"self",
".",
"view",
".",
"editor",
",",
"event",
")",
":",
"return",
"False",
"if",
"not",
"rafcon",
".",
"gui",
".",
"single... | Check whether the given event should be handled
Checks, whether the editor widget has the focus and whether the selected state machine corresponds to the
state machine of this editor.
:param event: GTK event object
:return: True if the event should be handled, else False
:rtype: bool | [
"Check",
"whether",
"the",
"given",
"event",
"should",
"be",
"handled"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L1008-L1023 | train | 40,728 |
Cog-Creators/Red-Lavalink | lavalink/lavalink.py | initialize | async def initialize(bot: Bot, host, password, rest_port, ws_port, timeout=30):
"""
Initializes the websocket connection to the lavalink player.
.. important::
This function must only be called AFTER the bot has received its
"on_ready" event!
Parameters
----------
bot : Bot
An instance of a discord.py `Bot` object.
host : str
The hostname or IP address of the Lavalink node.
password : str
The password of the Lavalink node.
rest_port : int
The port of the REST API on the Lavalink node.
ws_port : int
The websocket port on the Lavalink Node.
timeout : int
Amount of time to allow retries to occur, ``None`` is considered forever.
"""
global _loop
_loop = bot.loop
player_manager.user_id = bot.user.id
player_manager.channel_finder_func = bot.get_channel
register_event_listener(_handle_event)
register_update_listener(_handle_update)
lavalink_node = node.Node(
_loop,
dispatch,
bot._connection._get_websocket,
host,
password,
port=ws_port,
rest=rest_port,
user_id=player_manager.user_id,
num_shards=bot.shard_count if bot.shard_count is not None else 1,
)
await lavalink_node.connect(timeout=timeout)
bot.add_listener(node.on_socket_response)
bot.add_listener(_on_guild_remove, name="on_guild_remove")
return lavalink_node | python | async def initialize(bot: Bot, host, password, rest_port, ws_port, timeout=30):
"""
Initializes the websocket connection to the lavalink player.
.. important::
This function must only be called AFTER the bot has received its
"on_ready" event!
Parameters
----------
bot : Bot
An instance of a discord.py `Bot` object.
host : str
The hostname or IP address of the Lavalink node.
password : str
The password of the Lavalink node.
rest_port : int
The port of the REST API on the Lavalink node.
ws_port : int
The websocket port on the Lavalink Node.
timeout : int
Amount of time to allow retries to occur, ``None`` is considered forever.
"""
global _loop
_loop = bot.loop
player_manager.user_id = bot.user.id
player_manager.channel_finder_func = bot.get_channel
register_event_listener(_handle_event)
register_update_listener(_handle_update)
lavalink_node = node.Node(
_loop,
dispatch,
bot._connection._get_websocket,
host,
password,
port=ws_port,
rest=rest_port,
user_id=player_manager.user_id,
num_shards=bot.shard_count if bot.shard_count is not None else 1,
)
await lavalink_node.connect(timeout=timeout)
bot.add_listener(node.on_socket_response)
bot.add_listener(_on_guild_remove, name="on_guild_remove")
return lavalink_node | [
"async",
"def",
"initialize",
"(",
"bot",
":",
"Bot",
",",
"host",
",",
"password",
",",
"rest_port",
",",
"ws_port",
",",
"timeout",
"=",
"30",
")",
":",
"global",
"_loop",
"_loop",
"=",
"bot",
".",
"loop",
"player_manager",
".",
"user_id",
"=",
"bot"... | Initializes the websocket connection to the lavalink player.
.. important::
This function must only be called AFTER the bot has received its
"on_ready" event!
Parameters
----------
bot : Bot
An instance of a discord.py `Bot` object.
host : str
The hostname or IP address of the Lavalink node.
password : str
The password of the Lavalink node.
rest_port : int
The port of the REST API on the Lavalink node.
ws_port : int
The websocket port on the Lavalink Node.
timeout : int
Amount of time to allow retries to occur, ``None`` is considered forever. | [
"Initializes",
"the",
"websocket",
"connection",
"to",
"the",
"lavalink",
"player",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/lavalink.py#L34-L83 | train | 40,729 |
Cog-Creators/Red-Lavalink | lavalink/lavalink.py | register_event_listener | def register_event_listener(coro):
"""
Registers a coroutine to receive lavalink event information.
This coroutine will accept three arguments: :py:class:`Player`,
:py:class:`LavalinkEvents`, and possibly an extra. The value of the extra depends
on the value of the second argument.
If the second argument is :py:attr:`LavalinkEvents.TRACK_END`, the extra will
be a :py:class:`TrackEndReason`.
If the second argument is :py:attr:`LavalinkEvents.TRACK_EXCEPTION`, the extra
will be an error string.
If the second argument is :py:attr:`LavalinkEvents.TRACK_STUCK`, the extra will
be the threshold milliseconds that the track has been stuck for.
If the second argument is :py:attr:`LavalinkEvents.TRACK_START`, the extra will be
a :py:class:`Track` object.
If the second argument is any other value, the third argument will not exist.
Parameters
----------
coro
A coroutine function that accepts the arguments listed above.
Raises
------
TypeError
If ``coro`` is not a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("Function is not a coroutine.")
if coro not in _event_listeners:
_event_listeners.append(coro) | python | def register_event_listener(coro):
"""
Registers a coroutine to receive lavalink event information.
This coroutine will accept three arguments: :py:class:`Player`,
:py:class:`LavalinkEvents`, and possibly an extra. The value of the extra depends
on the value of the second argument.
If the second argument is :py:attr:`LavalinkEvents.TRACK_END`, the extra will
be a :py:class:`TrackEndReason`.
If the second argument is :py:attr:`LavalinkEvents.TRACK_EXCEPTION`, the extra
will be an error string.
If the second argument is :py:attr:`LavalinkEvents.TRACK_STUCK`, the extra will
be the threshold milliseconds that the track has been stuck for.
If the second argument is :py:attr:`LavalinkEvents.TRACK_START`, the extra will be
a :py:class:`Track` object.
If the second argument is any other value, the third argument will not exist.
Parameters
----------
coro
A coroutine function that accepts the arguments listed above.
Raises
------
TypeError
If ``coro`` is not a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("Function is not a coroutine.")
if coro not in _event_listeners:
_event_listeners.append(coro) | [
"def",
"register_event_listener",
"(",
"coro",
")",
":",
"if",
"not",
"asyncio",
".",
"iscoroutinefunction",
"(",
"coro",
")",
":",
"raise",
"TypeError",
"(",
"\"Function is not a coroutine.\"",
")",
"if",
"coro",
"not",
"in",
"_event_listeners",
":",
"_event_list... | Registers a coroutine to receive lavalink event information.
This coroutine will accept three arguments: :py:class:`Player`,
:py:class:`LavalinkEvents`, and possibly an extra. The value of the extra depends
on the value of the second argument.
If the second argument is :py:attr:`LavalinkEvents.TRACK_END`, the extra will
be a :py:class:`TrackEndReason`.
If the second argument is :py:attr:`LavalinkEvents.TRACK_EXCEPTION`, the extra
will be an error string.
If the second argument is :py:attr:`LavalinkEvents.TRACK_STUCK`, the extra will
be the threshold milliseconds that the track has been stuck for.
If the second argument is :py:attr:`LavalinkEvents.TRACK_START`, the extra will be
a :py:class:`Track` object.
If the second argument is any other value, the third argument will not exist.
Parameters
----------
coro
A coroutine function that accepts the arguments listed above.
Raises
------
TypeError
If ``coro`` is not a coroutine. | [
"Registers",
"a",
"coroutine",
"to",
"receive",
"lavalink",
"event",
"information",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/lavalink.py#L126-L162 | train | 40,730 |
Cog-Creators/Red-Lavalink | lavalink/lavalink.py | register_update_listener | def register_update_listener(coro):
"""
Registers a coroutine to receive lavalink player update information.
This coroutine will accept a two arguments: an instance of :py:class:`Player`
and an instance of :py:class:`PlayerState`.
Parameters
----------
coro
Raises
------
TypeError
If ``coro`` is not a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("Function is not a coroutine.")
if coro not in _update_listeners:
_update_listeners.append(coro) | python | def register_update_listener(coro):
"""
Registers a coroutine to receive lavalink player update information.
This coroutine will accept a two arguments: an instance of :py:class:`Player`
and an instance of :py:class:`PlayerState`.
Parameters
----------
coro
Raises
------
TypeError
If ``coro`` is not a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("Function is not a coroutine.")
if coro not in _update_listeners:
_update_listeners.append(coro) | [
"def",
"register_update_listener",
"(",
"coro",
")",
":",
"if",
"not",
"asyncio",
".",
"iscoroutinefunction",
"(",
"coro",
")",
":",
"raise",
"TypeError",
"(",
"\"Function is not a coroutine.\"",
")",
"if",
"coro",
"not",
"in",
"_update_listeners",
":",
"_update_l... | Registers a coroutine to receive lavalink player update information.
This coroutine will accept a two arguments: an instance of :py:class:`Player`
and an instance of :py:class:`PlayerState`.
Parameters
----------
coro
Raises
------
TypeError
If ``coro`` is not a coroutine. | [
"Registers",
"a",
"coroutine",
"to",
"receive",
"lavalink",
"player",
"update",
"information",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/lavalink.py#L211-L231 | train | 40,731 |
Cog-Creators/Red-Lavalink | lavalink/lavalink.py | register_stats_listener | def register_stats_listener(coro):
"""
Registers a coroutine to receive lavalink server stats information.
This coroutine will accept a single argument which will be an instance
of :py:class:`Stats`.
Parameters
----------
coro
Raises
------
TypeError
If ``coro`` is not a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("Function is not a coroutine.")
if coro not in _stats_listeners:
_stats_listeners.append(coro) | python | def register_stats_listener(coro):
"""
Registers a coroutine to receive lavalink server stats information.
This coroutine will accept a single argument which will be an instance
of :py:class:`Stats`.
Parameters
----------
coro
Raises
------
TypeError
If ``coro`` is not a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("Function is not a coroutine.")
if coro not in _stats_listeners:
_stats_listeners.append(coro) | [
"def",
"register_stats_listener",
"(",
"coro",
")",
":",
"if",
"not",
"asyncio",
".",
"iscoroutinefunction",
"(",
"coro",
")",
":",
"raise",
"TypeError",
"(",
"\"Function is not a coroutine.\"",
")",
"if",
"coro",
"not",
"in",
"_stats_listeners",
":",
"_stats_list... | Registers a coroutine to receive lavalink server stats information.
This coroutine will accept a single argument which will be an instance
of :py:class:`Stats`.
Parameters
----------
coro
Raises
------
TypeError
If ``coro`` is not a coroutine. | [
"Registers",
"a",
"coroutine",
"to",
"receive",
"lavalink",
"server",
"stats",
"information",
"."
] | 5b3fc6eb31ee5db8bd2b633a523cf69749957111 | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/lavalink.py#L268-L288 | train | 40,732 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/view.py | ExtendedGtkView.prepare_destruction | def prepare_destruction(self):
"""Get rid of circular references"""
self._tool = None
self._painter = None
self.relieve_model(self._selection)
self._selection = None
# clear observer class attributes, also see ExtendenController.destroy()
self._Observer__PROP_TO_METHS.clear()
self._Observer__METH_TO_PROPS.clear()
self._Observer__PAT_TO_METHS.clear()
self._Observer__METH_TO_PAT.clear()
self._Observer__PAT_METH_TO_KWARGS.clear() | python | def prepare_destruction(self):
"""Get rid of circular references"""
self._tool = None
self._painter = None
self.relieve_model(self._selection)
self._selection = None
# clear observer class attributes, also see ExtendenController.destroy()
self._Observer__PROP_TO_METHS.clear()
self._Observer__METH_TO_PROPS.clear()
self._Observer__PAT_TO_METHS.clear()
self._Observer__METH_TO_PAT.clear()
self._Observer__PAT_METH_TO_KWARGS.clear() | [
"def",
"prepare_destruction",
"(",
"self",
")",
":",
"self",
".",
"_tool",
"=",
"None",
"self",
".",
"_painter",
"=",
"None",
"self",
".",
"relieve_model",
"(",
"self",
".",
"_selection",
")",
"self",
".",
"_selection",
"=",
"None",
"# clear observer class a... | Get rid of circular references | [
"Get",
"rid",
"of",
"circular",
"references"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/view.py#L41-L52 | train | 40,733 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/view.py | ExtendedGtkView.get_port_at_point | def get_port_at_point(self, vpos, distance=10, exclude=None, exclude_port_fun=None):
"""
Find item with port closest to specified position.
List of items to be ignored can be specified with `exclude`
parameter.
Tuple is returned
- found item
- closest, connectable port
- closest point on found port (in view coordinates)
:Parameters:
vpos
Position specified in view coordinates.
distance
Max distance from point to a port (default 10)
exclude
Set of items to ignore.
"""
# Method had to be inherited, as the base method has a bug:
# It misses the statement max_dist = d
v2i = self.get_matrix_v2i
vx, vy = vpos
max_dist = distance
port = None
glue_pos = None
item = None
rect = (vx - distance, vy - distance, distance * 2, distance * 2)
items = self.get_items_in_rectangle(rect, reverse=True)
for i in items:
if exclude and i in exclude:
continue
for p in i.ports():
if not p.connectable:
continue
if exclude_port_fun and exclude_port_fun(p):
continue
ix, iy = v2i(i).transform_point(vx, vy)
pg, d = p.glue((ix, iy))
if d > max_dist:
continue
max_dist = d
item = i
port = p
# transform coordinates from connectable item space to view
# space
i2v = self.get_matrix_i2v(i).transform_point
glue_pos = i2v(*pg)
return item, port, glue_pos | python | def get_port_at_point(self, vpos, distance=10, exclude=None, exclude_port_fun=None):
"""
Find item with port closest to specified position.
List of items to be ignored can be specified with `exclude`
parameter.
Tuple is returned
- found item
- closest, connectable port
- closest point on found port (in view coordinates)
:Parameters:
vpos
Position specified in view coordinates.
distance
Max distance from point to a port (default 10)
exclude
Set of items to ignore.
"""
# Method had to be inherited, as the base method has a bug:
# It misses the statement max_dist = d
v2i = self.get_matrix_v2i
vx, vy = vpos
max_dist = distance
port = None
glue_pos = None
item = None
rect = (vx - distance, vy - distance, distance * 2, distance * 2)
items = self.get_items_in_rectangle(rect, reverse=True)
for i in items:
if exclude and i in exclude:
continue
for p in i.ports():
if not p.connectable:
continue
if exclude_port_fun and exclude_port_fun(p):
continue
ix, iy = v2i(i).transform_point(vx, vy)
pg, d = p.glue((ix, iy))
if d > max_dist:
continue
max_dist = d
item = i
port = p
# transform coordinates from connectable item space to view
# space
i2v = self.get_matrix_i2v(i).transform_point
glue_pos = i2v(*pg)
return item, port, glue_pos | [
"def",
"get_port_at_point",
"(",
"self",
",",
"vpos",
",",
"distance",
"=",
"10",
",",
"exclude",
"=",
"None",
",",
"exclude_port_fun",
"=",
"None",
")",
":",
"# Method had to be inherited, as the base method has a bug:",
"# It misses the statement max_dist = d",
"v2i",
... | Find item with port closest to specified position.
List of items to be ignored can be specified with `exclude`
parameter.
Tuple is returned
- found item
- closest, connectable port
- closest point on found port (in view coordinates)
:Parameters:
vpos
Position specified in view coordinates.
distance
Max distance from point to a port (default 10)
exclude
Set of items to ignore. | [
"Find",
"item",
"with",
"port",
"closest",
"to",
"specified",
"position",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/view.py#L59-L115 | train | 40,734 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/view.py | ExtendedGtkView.queue_draw_item | def queue_draw_item(self, *items):
"""Extends the base class method to allow Ports to be passed as item
:param items: Items that are to be redrawn
"""
gaphas_items = []
for item in items:
if isinstance(item, Element):
gaphas_items.append(item)
else:
try:
gaphas_items.append(item.parent)
except AttributeError:
pass
super(ExtendedGtkView, self).queue_draw_item(*gaphas_items) | python | def queue_draw_item(self, *items):
"""Extends the base class method to allow Ports to be passed as item
:param items: Items that are to be redrawn
"""
gaphas_items = []
for item in items:
if isinstance(item, Element):
gaphas_items.append(item)
else:
try:
gaphas_items.append(item.parent)
except AttributeError:
pass
super(ExtendedGtkView, self).queue_draw_item(*gaphas_items) | [
"def",
"queue_draw_item",
"(",
"self",
",",
"*",
"items",
")",
":",
"gaphas_items",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"if",
"isinstance",
"(",
"item",
",",
"Element",
")",
":",
"gaphas_items",
".",
"append",
"(",
"item",
")",
"else",
... | Extends the base class method to allow Ports to be passed as item
:param items: Items that are to be redrawn | [
"Extends",
"the",
"base",
"class",
"method",
"to",
"allow",
"Ports",
"to",
"be",
"passed",
"as",
"item"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/view.py#L163-L177 | train | 40,735 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/view.py | ExtendedGtkView.select_item | def select_item(self, items):
""" Select an items. This adds `items` to the set of selected items. """
if not items:
return
elif not hasattr(items, "__iter__"):
items = (items,)
selection_changed = False
with self._suppress_selection_events():
for item in items:
self.queue_draw_item(item)
if item is not None and item.model not in self._selection:
self._selection.add(item.model)
selection_changed = True
if selection_changed:
self.emit('selection-changed', self._get_selected_items()) | python | def select_item(self, items):
""" Select an items. This adds `items` to the set of selected items. """
if not items:
return
elif not hasattr(items, "__iter__"):
items = (items,)
selection_changed = False
with self._suppress_selection_events():
for item in items:
self.queue_draw_item(item)
if item is not None and item.model not in self._selection:
self._selection.add(item.model)
selection_changed = True
if selection_changed:
self.emit('selection-changed', self._get_selected_items()) | [
"def",
"select_item",
"(",
"self",
",",
"items",
")",
":",
"if",
"not",
"items",
":",
"return",
"elif",
"not",
"hasattr",
"(",
"items",
",",
"\"__iter__\"",
")",
":",
"items",
"=",
"(",
"items",
",",
")",
"selection_changed",
"=",
"False",
"with",
"sel... | Select an items. This adds `items` to the set of selected items. | [
"Select",
"an",
"items",
".",
"This",
"adds",
"items",
"to",
"the",
"set",
"of",
"selected",
"items",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/view.py#L221-L235 | train | 40,736 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/view.py | ExtendedGtkView.unselect_item | def unselect_item(self, item):
""" Unselect an item. """
self.queue_draw_item(item)
if item.model in self._selection:
with self._suppress_selection_events():
self._selection.remove(item.model)
self.emit('selection-changed', self._get_selected_items()) | python | def unselect_item(self, item):
""" Unselect an item. """
self.queue_draw_item(item)
if item.model in self._selection:
with self._suppress_selection_events():
self._selection.remove(item.model)
self.emit('selection-changed', self._get_selected_items()) | [
"def",
"unselect_item",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"queue_draw_item",
"(",
"item",
")",
"if",
"item",
".",
"model",
"in",
"self",
".",
"_selection",
":",
"with",
"self",
".",
"_suppress_selection_events",
"(",
")",
":",
"self",
".",... | Unselect an item. | [
"Unselect",
"an",
"item",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/view.py#L237-L243 | train | 40,737 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/view.py | ExtendedGtkView.unselect_all | def unselect_all(self):
""" Clearing the selected_item also clears the focused_item. """
items = self._get_selected_items()
with self._suppress_selection_events():
self._selection.clear()
self.queue_draw_item(*items)
self.emit('selection-changed', self._get_selected_items()) | python | def unselect_all(self):
""" Clearing the selected_item also clears the focused_item. """
items = self._get_selected_items()
with self._suppress_selection_events():
self._selection.clear()
self.queue_draw_item(*items)
self.emit('selection-changed', self._get_selected_items()) | [
"def",
"unselect_all",
"(",
"self",
")",
":",
"items",
"=",
"self",
".",
"_get_selected_items",
"(",
")",
"with",
"self",
".",
"_suppress_selection_events",
"(",
")",
":",
"self",
".",
"_selection",
".",
"clear",
"(",
")",
"self",
".",
"queue_draw_item",
"... | Clearing the selected_item also clears the focused_item. | [
"Clearing",
"the",
"selected_item",
"also",
"clears",
"the",
"focused_item",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/view.py#L245-L251 | train | 40,738 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/view.py | ExtendedGtkView.handle_new_selection | def handle_new_selection(self, items):
""" Determines the selection
The selection is based on the previous selection, the currently pressed keys and the passes newly selected items
:param items: The newly selected item(s)
"""
if items is None:
items = ()
elif not hasattr(items, "__iter__"):
items = (items,)
models = set(item.model for item in items)
self._selection.handle_new_selection(models) | python | def handle_new_selection(self, items):
""" Determines the selection
The selection is based on the previous selection, the currently pressed keys and the passes newly selected items
:param items: The newly selected item(s)
"""
if items is None:
items = ()
elif not hasattr(items, "__iter__"):
items = (items,)
models = set(item.model for item in items)
self._selection.handle_new_selection(models) | [
"def",
"handle_new_selection",
"(",
"self",
",",
"items",
")",
":",
"if",
"items",
"is",
"None",
":",
"items",
"=",
"(",
")",
"elif",
"not",
"hasattr",
"(",
"items",
",",
"\"__iter__\"",
")",
":",
"items",
"=",
"(",
"items",
",",
")",
"models",
"=",
... | Determines the selection
The selection is based on the previous selection, the currently pressed keys and the passes newly selected items
:param items: The newly selected item(s) | [
"Determines",
"the",
"selection"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/view.py#L257-L269 | train | 40,739 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/view.py | ExtendedGtkView._get_focused_item | def _get_focused_item(self):
""" Returns the currently focused item """
focused_model = self._selection.focus
if not focused_model:
return None
return self.canvas.get_view_for_model(focused_model) | python | def _get_focused_item(self):
""" Returns the currently focused item """
focused_model = self._selection.focus
if not focused_model:
return None
return self.canvas.get_view_for_model(focused_model) | [
"def",
"_get_focused_item",
"(",
"self",
")",
":",
"focused_model",
"=",
"self",
".",
"_selection",
".",
"focus",
"if",
"not",
"focused_model",
":",
"return",
"None",
"return",
"self",
".",
"canvas",
".",
"get_view_for_model",
"(",
"focused_model",
")"
] | Returns the currently focused item | [
"Returns",
"the",
"currently",
"focused",
"item"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/view.py#L280-L285 | train | 40,740 |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/view.py | ExtendedGtkView._set_focused_item | def _set_focused_item(self, item):
""" Sets the focus to the passed item"""
if not item:
return self._del_focused_item()
if item.model is not self._selection.focus:
self.queue_draw_item(self._focused_item, item)
self._selection.focus = item.model
self.emit('focus-changed', item) | python | def _set_focused_item(self, item):
""" Sets the focus to the passed item"""
if not item:
return self._del_focused_item()
if item.model is not self._selection.focus:
self.queue_draw_item(self._focused_item, item)
self._selection.focus = item.model
self.emit('focus-changed', item) | [
"def",
"_set_focused_item",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"item",
":",
"return",
"self",
".",
"_del_focused_item",
"(",
")",
"if",
"item",
".",
"model",
"is",
"not",
"self",
".",
"_selection",
".",
"focus",
":",
"self",
".",
"queue_d... | Sets the focus to the passed item | [
"Sets",
"the",
"focus",
"to",
"the",
"passed",
"item"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/view.py#L287-L295 | train | 40,741 |
DLR-RM/RAFCON | source/rafcon/utils/execution_log.py | log_to_ganttplot | def log_to_ganttplot(execution_history_items):
"""
Example how to use the DataFrame representation
"""
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import numpy as np
d = log_to_DataFrame(execution_history_items)
# de-duplicate states and make mapping from state to idx
unique_states, idx = np.unique(d.path_by_name, return_index=True)
ordered_unique_states = np.array(d.path_by_name)[np.sort(idx)]
name2idx = {k: i for i, k in enumerate(ordered_unique_states)}
calldate = dates.date2num(d.timestamp_call.dt.to_pydatetime())
returndate = dates.date2num(d.timestamp_return.dt.to_pydatetime())
state2color = {'HierarchyState': 'k',
'ExecutionState': 'g',
'BarrierConcurrencyState': 'y',
'PreemptiveConcurrencyState': 'y'}
fig, ax = plt.subplots(1, 1)
ax.barh(bottom=[name2idx[k] for k in d.path_by_name], width=returndate-calldate,
left=calldate, align='center', color=[state2color[s] for s in d.state_type], lw=0.0)
plt.yticks(list(range(len(ordered_unique_states))), ordered_unique_states) | python | def log_to_ganttplot(execution_history_items):
"""
Example how to use the DataFrame representation
"""
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import numpy as np
d = log_to_DataFrame(execution_history_items)
# de-duplicate states and make mapping from state to idx
unique_states, idx = np.unique(d.path_by_name, return_index=True)
ordered_unique_states = np.array(d.path_by_name)[np.sort(idx)]
name2idx = {k: i for i, k in enumerate(ordered_unique_states)}
calldate = dates.date2num(d.timestamp_call.dt.to_pydatetime())
returndate = dates.date2num(d.timestamp_return.dt.to_pydatetime())
state2color = {'HierarchyState': 'k',
'ExecutionState': 'g',
'BarrierConcurrencyState': 'y',
'PreemptiveConcurrencyState': 'y'}
fig, ax = plt.subplots(1, 1)
ax.barh(bottom=[name2idx[k] for k in d.path_by_name], width=returndate-calldate,
left=calldate, align='center', color=[state2color[s] for s in d.state_type], lw=0.0)
plt.yticks(list(range(len(ordered_unique_states))), ordered_unique_states) | [
"def",
"log_to_ganttplot",
"(",
"execution_history_items",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"matplotlib",
".",
"dates",
"as",
"dates",
"import",
"numpy",
"as",
"np",
"d",
"=",
"log_to_DataFrame",
"(",
"execution_history_items... | Example how to use the DataFrame representation | [
"Example",
"how",
"to",
"use",
"the",
"DataFrame",
"representation"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/execution_log.py#L373-L399 | train | 40,742 |
DLR-RM/RAFCON | source/rafcon/utils/gui_functions.py | call_gui_callback | def call_gui_callback(callback, *args, **kwargs):
"""Wrapper method for GLib.idle_add
This method is intended as replacement for idle_add. It wraps the method with a callback option. The advantage is
that this way, the call is blocking. The method return, when the callback method has been called and executed.
:param callback: The callback method, e.g. on_open_activate
:param args: The parameters to be passed to the callback method
"""
from future.utils import raise_
from threading import Condition
import sys
from rafcon.utils import log
global exception_info, result
from gi.repository import GLib
condition = Condition()
exception_info = None
@log.log_exceptions()
def fun():
"""Call callback and notify condition variable
"""
global exception_info, result
result = None
try:
result = callback(*args)
except:
# Exception within this asynchronously called function won't reach pytest. This is why we have to store
# the information about the exception to re-raise it at the end of the synchronous call.
exception_info = sys.exc_info()
finally: # Finally is also executed in the case of exceptions
condition.acquire()
condition.notify()
condition.release()
if "priority" in kwargs:
priority = kwargs["priority"]
else:
priority = GLib.PRIORITY_LOW
condition.acquire()
GLib.idle_add(fun, priority=priority)
# Wait for the condition to be notified
# TODO: implement timeout that raises an exception
condition.wait()
condition.release()
if exception_info:
e_type, e_value, e_traceback = exception_info
raise_(e_type, e_value, e_traceback)
return result | python | def call_gui_callback(callback, *args, **kwargs):
"""Wrapper method for GLib.idle_add
This method is intended as replacement for idle_add. It wraps the method with a callback option. The advantage is
that this way, the call is blocking. The method return, when the callback method has been called and executed.
:param callback: The callback method, e.g. on_open_activate
:param args: The parameters to be passed to the callback method
"""
from future.utils import raise_
from threading import Condition
import sys
from rafcon.utils import log
global exception_info, result
from gi.repository import GLib
condition = Condition()
exception_info = None
@log.log_exceptions()
def fun():
"""Call callback and notify condition variable
"""
global exception_info, result
result = None
try:
result = callback(*args)
except:
# Exception within this asynchronously called function won't reach pytest. This is why we have to store
# the information about the exception to re-raise it at the end of the synchronous call.
exception_info = sys.exc_info()
finally: # Finally is also executed in the case of exceptions
condition.acquire()
condition.notify()
condition.release()
if "priority" in kwargs:
priority = kwargs["priority"]
else:
priority = GLib.PRIORITY_LOW
condition.acquire()
GLib.idle_add(fun, priority=priority)
# Wait for the condition to be notified
# TODO: implement timeout that raises an exception
condition.wait()
condition.release()
if exception_info:
e_type, e_value, e_traceback = exception_info
raise_(e_type, e_value, e_traceback)
return result | [
"def",
"call_gui_callback",
"(",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"future",
".",
"utils",
"import",
"raise_",
"from",
"threading",
"import",
"Condition",
"import",
"sys",
"from",
"rafcon",
".",
"utils",
"import",
"lo... | Wrapper method for GLib.idle_add
This method is intended as replacement for idle_add. It wraps the method with a callback option. The advantage is
that this way, the call is blocking. The method return, when the callback method has been called and executed.
:param callback: The callback method, e.g. on_open_activate
:param args: The parameters to be passed to the callback method | [
"Wrapper",
"method",
"for",
"GLib",
".",
"idle_add"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/gui_functions.py#L24-L73 | train | 40,743 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/label.py | create_tab_header_label | def create_tab_header_label(tab_name, icons):
"""Create the tab header labels for notebook tabs. If USE_ICONS_AS_TAB_LABELS is set to True in the gui_config,
icons are used as headers. Otherwise, the titles of the tabs are rotated by 90 degrees.
:param tab_name: The label text of the tab, written in small letters and separated by underscores, e.g. states_tree
:param icons: A dict mapping each tab_name to its corresponding icon
:return: The GTK Eventbox holding the tab label
"""
tooltip_event_box = Gtk.EventBox()
tooltip_event_box.set_tooltip_text(tab_name)
tab_label = Gtk.Label()
if global_gui_config.get_config_value('USE_ICONS_AS_TAB_LABELS', True):
tab_label.set_markup('<span font_desc="%s %s">&#x%s;</span>' %
(constants.ICON_FONT,
constants.FONT_SIZE_BIG,
icons[tab_name]))
else:
tab_label.set_text(get_widget_title(tab_name))
tab_label.set_angle(90)
tab_label.show()
tooltip_event_box.add(tab_label)
tooltip_event_box.set_visible_window(False)
tooltip_event_box.show()
return tooltip_event_box | python | def create_tab_header_label(tab_name, icons):
"""Create the tab header labels for notebook tabs. If USE_ICONS_AS_TAB_LABELS is set to True in the gui_config,
icons are used as headers. Otherwise, the titles of the tabs are rotated by 90 degrees.
:param tab_name: The label text of the tab, written in small letters and separated by underscores, e.g. states_tree
:param icons: A dict mapping each tab_name to its corresponding icon
:return: The GTK Eventbox holding the tab label
"""
tooltip_event_box = Gtk.EventBox()
tooltip_event_box.set_tooltip_text(tab_name)
tab_label = Gtk.Label()
if global_gui_config.get_config_value('USE_ICONS_AS_TAB_LABELS', True):
tab_label.set_markup('<span font_desc="%s %s">&#x%s;</span>' %
(constants.ICON_FONT,
constants.FONT_SIZE_BIG,
icons[tab_name]))
else:
tab_label.set_text(get_widget_title(tab_name))
tab_label.set_angle(90)
tab_label.show()
tooltip_event_box.add(tab_label)
tooltip_event_box.set_visible_window(False)
tooltip_event_box.show()
return tooltip_event_box | [
"def",
"create_tab_header_label",
"(",
"tab_name",
",",
"icons",
")",
":",
"tooltip_event_box",
"=",
"Gtk",
".",
"EventBox",
"(",
")",
"tooltip_event_box",
".",
"set_tooltip_text",
"(",
"tab_name",
")",
"tab_label",
"=",
"Gtk",
".",
"Label",
"(",
")",
"if",
... | Create the tab header labels for notebook tabs. If USE_ICONS_AS_TAB_LABELS is set to True in the gui_config,
icons are used as headers. Otherwise, the titles of the tabs are rotated by 90 degrees.
:param tab_name: The label text of the tab, written in small letters and separated by underscores, e.g. states_tree
:param icons: A dict mapping each tab_name to its corresponding icon
:return: The GTK Eventbox holding the tab label | [
"Create",
"the",
"tab",
"header",
"labels",
"for",
"notebook",
"tabs",
".",
"If",
"USE_ICONS_AS_TAB_LABELS",
"is",
"set",
"to",
"True",
"in",
"the",
"gui_config",
"icons",
"are",
"used",
"as",
"headers",
".",
"Otherwise",
"the",
"titles",
"of",
"the",
"tabs"... | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/label.py#L26-L49 | train | 40,744 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/label.py | create_button_label | def create_button_label(icon, font_size=constants.FONT_SIZE_NORMAL):
"""Create a button label with a chosen icon.
:param icon: The icon
:param font_size: The size of the icon
:return: The created label
"""
label = Gtk.Label()
set_label_markup(label, '&#x' + icon + ';', constants.ICON_FONT, font_size)
label.show()
return label | python | def create_button_label(icon, font_size=constants.FONT_SIZE_NORMAL):
"""Create a button label with a chosen icon.
:param icon: The icon
:param font_size: The size of the icon
:return: The created label
"""
label = Gtk.Label()
set_label_markup(label, '&#x' + icon + ';', constants.ICON_FONT, font_size)
label.show()
return label | [
"def",
"create_button_label",
"(",
"icon",
",",
"font_size",
"=",
"constants",
".",
"FONT_SIZE_NORMAL",
")",
":",
"label",
"=",
"Gtk",
".",
"Label",
"(",
")",
"set_label_markup",
"(",
"label",
",",
"'&#x'",
"+",
"icon",
"+",
"';'",
",",
"constants",
".",
... | Create a button label with a chosen icon.
:param icon: The icon
:param font_size: The size of the icon
:return: The created label | [
"Create",
"a",
"button",
"label",
"with",
"a",
"chosen",
"icon",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/label.py#L157-L167 | train | 40,745 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/label.py | get_widget_title | def get_widget_title(tab_label_text):
"""Transform Notebook tab label to title by replacing underscores with white spaces and capitalizing the first
letter of each word.
:param tab_label_text: The string of the tab label to be transformed
:return: The transformed title as a string
"""
title = ''
title_list = tab_label_text.split('_')
for word in title_list:
title += word.upper() + ' '
title.strip()
return title | python | def get_widget_title(tab_label_text):
"""Transform Notebook tab label to title by replacing underscores with white spaces and capitalizing the first
letter of each word.
:param tab_label_text: The string of the tab label to be transformed
:return: The transformed title as a string
"""
title = ''
title_list = tab_label_text.split('_')
for word in title_list:
title += word.upper() + ' '
title.strip()
return title | [
"def",
"get_widget_title",
"(",
"tab_label_text",
")",
":",
"title",
"=",
"''",
"title_list",
"=",
"tab_label_text",
".",
"split",
"(",
"'_'",
")",
"for",
"word",
"in",
"title_list",
":",
"title",
"+=",
"word",
".",
"upper",
"(",
")",
"+",
"' '",
"title"... | Transform Notebook tab label to title by replacing underscores with white spaces and capitalizing the first
letter of each word.
:param tab_label_text: The string of the tab label to be transformed
:return: The transformed title as a string | [
"Transform",
"Notebook",
"tab",
"label",
"to",
"title",
"by",
"replacing",
"underscores",
"with",
"white",
"spaces",
"and",
"capitalizing",
"the",
"first",
"letter",
"of",
"each",
"word",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/label.py#L183-L195 | train | 40,746 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/label.py | get_notebook_tab_title | def get_notebook_tab_title(notebook, page_num):
"""Helper function that gets a notebook's tab title given its page number
:param notebook: The GTK notebook
:param page_num: The page number of the tab, for which the title is required
:return: The title of the tab
"""
child = notebook.get_nth_page(page_num)
tab_label_eventbox = notebook.get_tab_label(child)
return get_widget_title(tab_label_eventbox.get_tooltip_text()) | python | def get_notebook_tab_title(notebook, page_num):
"""Helper function that gets a notebook's tab title given its page number
:param notebook: The GTK notebook
:param page_num: The page number of the tab, for which the title is required
:return: The title of the tab
"""
child = notebook.get_nth_page(page_num)
tab_label_eventbox = notebook.get_tab_label(child)
return get_widget_title(tab_label_eventbox.get_tooltip_text()) | [
"def",
"get_notebook_tab_title",
"(",
"notebook",
",",
"page_num",
")",
":",
"child",
"=",
"notebook",
".",
"get_nth_page",
"(",
"page_num",
")",
"tab_label_eventbox",
"=",
"notebook",
".",
"get_tab_label",
"(",
"child",
")",
"return",
"get_widget_title",
"(",
"... | Helper function that gets a notebook's tab title given its page number
:param notebook: The GTK notebook
:param page_num: The page number of the tab, for which the title is required
:return: The title of the tab | [
"Helper",
"function",
"that",
"gets",
"a",
"notebook",
"s",
"tab",
"title",
"given",
"its",
"page",
"number"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/label.py#L208-L217 | train | 40,747 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/label.py | set_notebook_title | def set_notebook_title(notebook, page_num, title_label):
"""Set the title of a GTK notebook to one of its tab's titles
:param notebook: The GTK notebook
:param page_num: The page number of a specific tab
:param title_label: The GTK label holding the notebook's title
:return: The new title of the notebook
"""
text = get_notebook_tab_title(notebook, page_num)
set_label_markup(title_label, text, constants.INTERFACE_FONT, constants.FONT_SIZE_BIG, constants.LETTER_SPACING_1PT)
return text | python | def set_notebook_title(notebook, page_num, title_label):
"""Set the title of a GTK notebook to one of its tab's titles
:param notebook: The GTK notebook
:param page_num: The page number of a specific tab
:param title_label: The GTK label holding the notebook's title
:return: The new title of the notebook
"""
text = get_notebook_tab_title(notebook, page_num)
set_label_markup(title_label, text, constants.INTERFACE_FONT, constants.FONT_SIZE_BIG, constants.LETTER_SPACING_1PT)
return text | [
"def",
"set_notebook_title",
"(",
"notebook",
",",
"page_num",
",",
"title_label",
")",
":",
"text",
"=",
"get_notebook_tab_title",
"(",
"notebook",
",",
"page_num",
")",
"set_label_markup",
"(",
"title_label",
",",
"text",
",",
"constants",
".",
"INTERFACE_FONT",... | Set the title of a GTK notebook to one of its tab's titles
:param notebook: The GTK notebook
:param page_num: The page number of a specific tab
:param title_label: The GTK label holding the notebook's title
:return: The new title of the notebook | [
"Set",
"the",
"title",
"of",
"a",
"GTK",
"notebook",
"to",
"one",
"of",
"its",
"tab",
"s",
"titles"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/label.py#L220-L230 | train | 40,748 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/label.py | create_menu_box_with_icon_and_label | def create_menu_box_with_icon_and_label(label_text):
""" Creates a MenuItem box, which is a replacement for the former ImageMenuItem. The box contains, a label
for the icon and one for the text.
:param label_text: The text, which is displayed for the text label
:return:
"""
box = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 10)
box.set_border_width(0)
icon_label = Gtk.Label()
text_label = Gtk.AccelLabel.new(label_text)
text_label.set_xalign(0)
box.pack_start(icon_label, False, False, 0)
box.pack_start(text_label, True, True, 0)
return box, icon_label, text_label | python | def create_menu_box_with_icon_and_label(label_text):
""" Creates a MenuItem box, which is a replacement for the former ImageMenuItem. The box contains, a label
for the icon and one for the text.
:param label_text: The text, which is displayed for the text label
:return:
"""
box = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 10)
box.set_border_width(0)
icon_label = Gtk.Label()
text_label = Gtk.AccelLabel.new(label_text)
text_label.set_xalign(0)
box.pack_start(icon_label, False, False, 0)
box.pack_start(text_label, True, True, 0)
return box, icon_label, text_label | [
"def",
"create_menu_box_with_icon_and_label",
"(",
"label_text",
")",
":",
"box",
"=",
"Gtk",
".",
"Box",
".",
"new",
"(",
"Gtk",
".",
"Orientation",
".",
"HORIZONTAL",
",",
"10",
")",
"box",
".",
"set_border_width",
"(",
"0",
")",
"icon_label",
"=",
"Gtk"... | Creates a MenuItem box, which is a replacement for the former ImageMenuItem. The box contains, a label
for the icon and one for the text.
:param label_text: The text, which is displayed for the text label
:return: | [
"Creates",
"a",
"MenuItem",
"box",
"which",
"is",
"a",
"replacement",
"for",
"the",
"former",
"ImageMenuItem",
".",
"The",
"box",
"contains",
"a",
"label",
"for",
"the",
"icon",
"and",
"one",
"for",
"the",
"text",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/label.py#L233-L248 | train | 40,749 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/label.py | set_window_size_and_position | def set_window_size_and_position(window, window_key):
"""Adjust GTK Window's size, position and maximized state according to the corresponding values in the
runtime_config file. The maximize method is triggered last to restore also the last stored size and position of the
window. If the runtime_config does not exist, or the corresponding values are missing in the file, default values
for the window size are used, and the mouse position is used to adjust the window's position.
:param window: The GTK Window to be adjusted
:param window_key: The window's key stored in the runtime config file
"""
size = global_runtime_config.get_config_value(window_key + '_WINDOW_SIZE')
position = global_runtime_config.get_config_value(window_key + '_WINDOW_POS')
maximized = global_runtime_config.get_config_value(window_key + '_WINDOW_MAXIMIZED')
# un-maximize here on purpose otherwise resize and reposition fails
if not maximized:
window.unmaximize()
if not size:
size = constants.WINDOW_SIZE[window_key + '_WINDOW']
window.resize(*size)
if position:
position = (max(0, position[0]), max(0, position[1]))
screen_width = Gdk.Screen.width()
screen_height = Gdk.Screen.height()
if position[0] < screen_width and position[1] < screen_height:
window.move(*position)
else:
window.set_position(Gtk.WindowPosition.MOUSE)
if maximized:
window.maximize()
window.show() | python | def set_window_size_and_position(window, window_key):
"""Adjust GTK Window's size, position and maximized state according to the corresponding values in the
runtime_config file. The maximize method is triggered last to restore also the last stored size and position of the
window. If the runtime_config does not exist, or the corresponding values are missing in the file, default values
for the window size are used, and the mouse position is used to adjust the window's position.
:param window: The GTK Window to be adjusted
:param window_key: The window's key stored in the runtime config file
"""
size = global_runtime_config.get_config_value(window_key + '_WINDOW_SIZE')
position = global_runtime_config.get_config_value(window_key + '_WINDOW_POS')
maximized = global_runtime_config.get_config_value(window_key + '_WINDOW_MAXIMIZED')
# un-maximize here on purpose otherwise resize and reposition fails
if not maximized:
window.unmaximize()
if not size:
size = constants.WINDOW_SIZE[window_key + '_WINDOW']
window.resize(*size)
if position:
position = (max(0, position[0]), max(0, position[1]))
screen_width = Gdk.Screen.width()
screen_height = Gdk.Screen.height()
if position[0] < screen_width and position[1] < screen_height:
window.move(*position)
else:
window.set_position(Gtk.WindowPosition.MOUSE)
if maximized:
window.maximize()
window.show() | [
"def",
"set_window_size_and_position",
"(",
"window",
",",
"window_key",
")",
":",
"size",
"=",
"global_runtime_config",
".",
"get_config_value",
"(",
"window_key",
"+",
"'_WINDOW_SIZE'",
")",
"position",
"=",
"global_runtime_config",
".",
"get_config_value",
"(",
"wi... | Adjust GTK Window's size, position and maximized state according to the corresponding values in the
runtime_config file. The maximize method is triggered last to restore also the last stored size and position of the
window. If the runtime_config does not exist, or the corresponding values are missing in the file, default values
for the window size are used, and the mouse position is used to adjust the window's position.
:param window: The GTK Window to be adjusted
:param window_key: The window's key stored in the runtime config file | [
"Adjust",
"GTK",
"Window",
"s",
"size",
"position",
"and",
"maximized",
"state",
"according",
"to",
"the",
"corresponding",
"values",
"in",
"the",
"runtime_config",
"file",
".",
"The",
"maximize",
"method",
"is",
"triggered",
"last",
"to",
"restore",
"also",
"... | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/label.py#L257-L287 | train | 40,750 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/label.py | react_to_event | def react_to_event(view, widget, event):
"""Checks whether the widget is supposed to react to passed event
The function is intended for callback methods registering to shortcut actions. As several widgets can register to
the same shortcut, only the one having the focus should react to it.
:param gtkmvc3.View view: The view in which the widget is registered
:param Gtk.Widget widget: The widget that subscribed to the shortcut action, should be the top widget of the view
:param event: The event that caused the callback
:return: Whether the widget is supposed to react to the event or not
:rtype: bool
"""
# See
# http://pyGtk.org/pygtk2reference/class-gtkwidget.html#method-gtkwidget--is-focus and
# http://pyGtk.org/pygtk2reference/class-gtkwidget.html#method-gtkwidget--has-focus
# for detailed information about the difference between is_focus() and has_focus()
if not view: # view needs to be initialized
return False
# widget parameter must be set and a Gtk.Widget
if not isinstance(widget, Gtk.Widget):
return False
# Either the widget itself or one of its children must be the focus widget within their toplevel
child_is_focus = False if not isinstance(widget, Gtk.Container) else bool(widget.get_focus_child())
if not child_is_focus and not widget.is_focus():
return False
def has_focus(widget):
"""Checks whether `widget` or one of its children ``has_focus()`` is ``True``
:param Gtk.Widget widget: The widget to be checked
:return: If any (child) widget has the global input focus
"""
if widget.has_focus():
return True
if not isinstance(widget, Gtk.Container):
return False
return any(has_focus(child) for child in widget.get_children())
# Either, for any of widget or its children, has_focus must be True, in this case the widget has the global focus.
if has_focus(widget):
return True
# Or the callback was not triggered by a shortcut, but e.g. a mouse click or a call from a test.
# If the callback was triggered by a shortcut action, the event has at least a length of two and the second
# element is a Gdk.ModifierType
if len(event) < 2 or (len(event) >= 2 and not isinstance(event[1], Gdk.ModifierType)):
return True
return False | python | def react_to_event(view, widget, event):
"""Checks whether the widget is supposed to react to passed event
The function is intended for callback methods registering to shortcut actions. As several widgets can register to
the same shortcut, only the one having the focus should react to it.
:param gtkmvc3.View view: The view in which the widget is registered
:param Gtk.Widget widget: The widget that subscribed to the shortcut action, should be the top widget of the view
:param event: The event that caused the callback
:return: Whether the widget is supposed to react to the event or not
:rtype: bool
"""
# See
# http://pyGtk.org/pygtk2reference/class-gtkwidget.html#method-gtkwidget--is-focus and
# http://pyGtk.org/pygtk2reference/class-gtkwidget.html#method-gtkwidget--has-focus
# for detailed information about the difference between is_focus() and has_focus()
if not view: # view needs to be initialized
return False
# widget parameter must be set and a Gtk.Widget
if not isinstance(widget, Gtk.Widget):
return False
# Either the widget itself or one of its children must be the focus widget within their toplevel
child_is_focus = False if not isinstance(widget, Gtk.Container) else bool(widget.get_focus_child())
if not child_is_focus and not widget.is_focus():
return False
def has_focus(widget):
"""Checks whether `widget` or one of its children ``has_focus()`` is ``True``
:param Gtk.Widget widget: The widget to be checked
:return: If any (child) widget has the global input focus
"""
if widget.has_focus():
return True
if not isinstance(widget, Gtk.Container):
return False
return any(has_focus(child) for child in widget.get_children())
# Either, for any of widget or its children, has_focus must be True, in this case the widget has the global focus.
if has_focus(widget):
return True
# Or the callback was not triggered by a shortcut, but e.g. a mouse click or a call from a test.
# If the callback was triggered by a shortcut action, the event has at least a length of two and the second
# element is a Gdk.ModifierType
if len(event) < 2 or (len(event) >= 2 and not isinstance(event[1], Gdk.ModifierType)):
return True
return False | [
"def",
"react_to_event",
"(",
"view",
",",
"widget",
",",
"event",
")",
":",
"# See",
"# http://pyGtk.org/pygtk2reference/class-gtkwidget.html#method-gtkwidget--is-focus and",
"# http://pyGtk.org/pygtk2reference/class-gtkwidget.html#method-gtkwidget--has-focus",
"# for detailed information... | Checks whether the widget is supposed to react to passed event
The function is intended for callback methods registering to shortcut actions. As several widgets can register to
the same shortcut, only the one having the focus should react to it.
:param gtkmvc3.View view: The view in which the widget is registered
:param Gtk.Widget widget: The widget that subscribed to the shortcut action, should be the top widget of the view
:param event: The event that caused the callback
:return: Whether the widget is supposed to react to the event or not
:rtype: bool | [
"Checks",
"whether",
"the",
"widget",
"is",
"supposed",
"to",
"react",
"to",
"passed",
"event"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/label.py#L290-L335 | train | 40,751 |
DLR-RM/RAFCON | source/rafcon/gui/helpers/label.py | is_event_of_key_string | def is_event_of_key_string(event, key_string):
"""Condition check if key string represent the key value of handed event and whether the event is of right type
The function checks for constructed event tuple that are generated by the rafcon.gui.shortcut_manager.ShortcutManager.
:param tuple event: Event tuple generated by the ShortcutManager
:param str key_string: Key string parsed to a key value and for condition check
"""
return len(event) >= 2 and not isinstance(event[1], Gdk.ModifierType) and event[0] == Gtk.accelerator_parse(key_string)[0] | python | def is_event_of_key_string(event, key_string):
"""Condition check if key string represent the key value of handed event and whether the event is of right type
The function checks for constructed event tuple that are generated by the rafcon.gui.shortcut_manager.ShortcutManager.
:param tuple event: Event tuple generated by the ShortcutManager
:param str key_string: Key string parsed to a key value and for condition check
"""
return len(event) >= 2 and not isinstance(event[1], Gdk.ModifierType) and event[0] == Gtk.accelerator_parse(key_string)[0] | [
"def",
"is_event_of_key_string",
"(",
"event",
",",
"key_string",
")",
":",
"return",
"len",
"(",
"event",
")",
">=",
"2",
"and",
"not",
"isinstance",
"(",
"event",
"[",
"1",
"]",
",",
"Gdk",
".",
"ModifierType",
")",
"and",
"event",
"[",
"0",
"]",
"... | Condition check if key string represent the key value of handed event and whether the event is of right type
The function checks for constructed event tuple that are generated by the rafcon.gui.shortcut_manager.ShortcutManager.
:param tuple event: Event tuple generated by the ShortcutManager
:param str key_string: Key string parsed to a key value and for condition check | [
"Condition",
"check",
"if",
"key",
"string",
"represent",
"the",
"key",
"value",
"of",
"handed",
"event",
"and",
"whether",
"the",
"event",
"is",
"of",
"right",
"type"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/label.py#L338-L345 | train | 40,752 |
DLR-RM/RAFCON | source/rafcon/utils/decorators.py | avoid_parallel_execution | def avoid_parallel_execution(func):
"""A decorator to avoid the parallel execution of a function.
If the function is currently called, the second call is just skipped.
:param func: The function to decorate
:return:
"""
def func_wrapper(*args, **kwargs):
if not getattr(func, "currently_executing", False):
func.currently_executing = True
try:
return func(*args, **kwargs)
finally:
func.currently_executing = False
else:
logger.verbose("Avoid parallel execution of function {}".format(func))
return func_wrapper | python | def avoid_parallel_execution(func):
"""A decorator to avoid the parallel execution of a function.
If the function is currently called, the second call is just skipped.
:param func: The function to decorate
:return:
"""
def func_wrapper(*args, **kwargs):
if not getattr(func, "currently_executing", False):
func.currently_executing = True
try:
return func(*args, **kwargs)
finally:
func.currently_executing = False
else:
logger.verbose("Avoid parallel execution of function {}".format(func))
return func_wrapper | [
"def",
"avoid_parallel_execution",
"(",
"func",
")",
":",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"getattr",
"(",
"func",
",",
"\"currently_executing\"",
",",
"False",
")",
":",
"func",
".",
"currently_execu... | A decorator to avoid the parallel execution of a function.
If the function is currently called, the second call is just skipped.
:param func: The function to decorate
:return: | [
"A",
"decorator",
"to",
"avoid",
"the",
"parallel",
"execution",
"of",
"a",
"function",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/decorators.py#L21-L38 | train | 40,753 |
DLR-RM/RAFCON | source/rafcon/core/states/library_state.py | LibraryState.run | def run(self):
""" This defines the sequence of actions that are taken when the library state is executed
It basically just calls the run method of the container state
:return:
"""
self.state_execution_status = StateExecutionStatus.ACTIVE
logger.debug("Entering library state '{0}' with name '{1}'".format(self.library_name, self.name))
# self.state_copy.parent = self.parent
self.state_copy._run_id = self._run_id
self.state_copy.input_data = self.input_data
self.state_copy.output_data = self.output_data
self.state_copy.execution_history = self.execution_history
self.state_copy.backward_execution = self.backward_execution
self.state_copy.run()
logger.debug("Exiting library state '{0}' with name '{1}'".format(self.library_name, self.name))
self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE
self.finalize(self.state_copy.final_outcome) | python | def run(self):
""" This defines the sequence of actions that are taken when the library state is executed
It basically just calls the run method of the container state
:return:
"""
self.state_execution_status = StateExecutionStatus.ACTIVE
logger.debug("Entering library state '{0}' with name '{1}'".format(self.library_name, self.name))
# self.state_copy.parent = self.parent
self.state_copy._run_id = self._run_id
self.state_copy.input_data = self.input_data
self.state_copy.output_data = self.output_data
self.state_copy.execution_history = self.execution_history
self.state_copy.backward_execution = self.backward_execution
self.state_copy.run()
logger.debug("Exiting library state '{0}' with name '{1}'".format(self.library_name, self.name))
self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE
self.finalize(self.state_copy.final_outcome) | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"state_execution_status",
"=",
"StateExecutionStatus",
".",
"ACTIVE",
"logger",
".",
"debug",
"(",
"\"Entering library state '{0}' with name '{1}'\"",
".",
"format",
"(",
"self",
".",
"library_name",
",",
"self",
"... | This defines the sequence of actions that are taken when the library state is executed
It basically just calls the run method of the container state
:return: | [
"This",
"defines",
"the",
"sequence",
"of",
"actions",
"that",
"are",
"taken",
"when",
"the",
"library",
"state",
"is",
"executed"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/library_state.py#L210-L227 | train | 40,754 |
DLR-RM/RAFCON | source/rafcon/core/states/library_state.py | LibraryState.remove_outcome | def remove_outcome(self, outcome_id, force=False, destroy=True):
"""Overwrites the remove_outcome method of the State class. Prevents user from removing a
outcome from the library state.
For further documentation, look at the State class.
:raises exceptions.NotImplementedError: in any case
"""
if force:
return State.remove_outcome(self, outcome_id, force, destroy)
else:
raise NotImplementedError("Remove outcome is not implemented for library state {}".format(self)) | python | def remove_outcome(self, outcome_id, force=False, destroy=True):
"""Overwrites the remove_outcome method of the State class. Prevents user from removing a
outcome from the library state.
For further documentation, look at the State class.
:raises exceptions.NotImplementedError: in any case
"""
if force:
return State.remove_outcome(self, outcome_id, force, destroy)
else:
raise NotImplementedError("Remove outcome is not implemented for library state {}".format(self)) | [
"def",
"remove_outcome",
"(",
"self",
",",
"outcome_id",
",",
"force",
"=",
"False",
",",
"destroy",
"=",
"True",
")",
":",
"if",
"force",
":",
"return",
"State",
".",
"remove_outcome",
"(",
"self",
",",
"outcome_id",
",",
"force",
",",
"destroy",
")",
... | Overwrites the remove_outcome method of the State class. Prevents user from removing a
outcome from the library state.
For further documentation, look at the State class.
:raises exceptions.NotImplementedError: in any case | [
"Overwrites",
"the",
"remove_outcome",
"method",
"of",
"the",
"State",
"class",
".",
"Prevents",
"user",
"from",
"removing",
"a",
"outcome",
"from",
"the",
"library",
"state",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/library_state.py#L259-L270 | train | 40,755 |
DLR-RM/RAFCON | source/rafcon/core/states/library_state.py | LibraryState.remove_output_data_port | def remove_output_data_port(self, data_port_id, force=False, destroy=True):
"""Overwrites the remove_output_data_port method of the State class. Prevents user from removing a
output data port from the library state.
For further documentation, look at the State class.
:param bool force: True if the removal should be forced
:raises exceptions.NotImplementedError: in the removal is not forced
"""
if force:
return State.remove_output_data_port(self, data_port_id, force, destroy)
else:
raise NotImplementedError("Remove output data port is not implemented for library state {}".format(self)) | python | def remove_output_data_port(self, data_port_id, force=False, destroy=True):
"""Overwrites the remove_output_data_port method of the State class. Prevents user from removing a
output data port from the library state.
For further documentation, look at the State class.
:param bool force: True if the removal should be forced
:raises exceptions.NotImplementedError: in the removal is not forced
"""
if force:
return State.remove_output_data_port(self, data_port_id, force, destroy)
else:
raise NotImplementedError("Remove output data port is not implemented for library state {}".format(self)) | [
"def",
"remove_output_data_port",
"(",
"self",
",",
"data_port_id",
",",
"force",
"=",
"False",
",",
"destroy",
"=",
"True",
")",
":",
"if",
"force",
":",
"return",
"State",
".",
"remove_output_data_port",
"(",
"self",
",",
"data_port_id",
",",
"force",
",",... | Overwrites the remove_output_data_port method of the State class. Prevents user from removing a
output data port from the library state.
For further documentation, look at the State class.
:param bool force: True if the removal should be forced
:raises exceptions.NotImplementedError: in the removal is not forced | [
"Overwrites",
"the",
"remove_output_data_port",
"method",
"of",
"the",
"State",
"class",
".",
"Prevents",
"user",
"from",
"removing",
"a",
"output",
"data",
"port",
"from",
"the",
"library",
"state",
"."
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/library_state.py#L309-L320 | train | 40,756 |
DLR-RM/RAFCON | source/rafcon/core/states/library_state.py | LibraryState.library_hierarchy_depth | def library_hierarchy_depth(self):
""" Calculates the library hierarchy depth
Counting starts at the current library state. So if the there is no upper library state the depth is one.
:return: library hierarchy depth
:rtype: int
"""
current_library_hierarchy_depth = 1
library_root_state = self.get_next_upper_library_root_state()
while library_root_state is not None:
current_library_hierarchy_depth += 1
library_root_state = library_root_state.parent.get_next_upper_library_root_state()
return current_library_hierarchy_depth | python | def library_hierarchy_depth(self):
""" Calculates the library hierarchy depth
Counting starts at the current library state. So if the there is no upper library state the depth is one.
:return: library hierarchy depth
:rtype: int
"""
current_library_hierarchy_depth = 1
library_root_state = self.get_next_upper_library_root_state()
while library_root_state is not None:
current_library_hierarchy_depth += 1
library_root_state = library_root_state.parent.get_next_upper_library_root_state()
return current_library_hierarchy_depth | [
"def",
"library_hierarchy_depth",
"(",
"self",
")",
":",
"current_library_hierarchy_depth",
"=",
"1",
"library_root_state",
"=",
"self",
".",
"get_next_upper_library_root_state",
"(",
")",
"while",
"library_root_state",
"is",
"not",
"None",
":",
"current_library_hierarchy... | Calculates the library hierarchy depth
Counting starts at the current library state. So if the there is no upper library state the depth is one.
:return: library hierarchy depth
:rtype: int | [
"Calculates",
"the",
"library",
"hierarchy",
"depth"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/library_state.py#L567-L580 | train | 40,757 |
DLR-RM/RAFCON | source/rafcon/core/config.py | Config.load | def load(self, config_file=None, path=None):
"""Loads the configuration from a specific file
:param config_file: the name of the config file
:param path: the path to the config file
"""
if config_file is None:
if path is None:
path, config_file = split(resource_filename(__name__, CONFIG_FILE))
else:
config_file = CONFIG_FILE
super(Config, self).load(config_file, path) | python | def load(self, config_file=None, path=None):
"""Loads the configuration from a specific file
:param config_file: the name of the config file
:param path: the path to the config file
"""
if config_file is None:
if path is None:
path, config_file = split(resource_filename(__name__, CONFIG_FILE))
else:
config_file = CONFIG_FILE
super(Config, self).load(config_file, path) | [
"def",
"load",
"(",
"self",
",",
"config_file",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"if",
"config_file",
"is",
"None",
":",
"if",
"path",
"is",
"None",
":",
"path",
",",
"config_file",
"=",
"split",
"(",
"resource_filename",
"(",
"__name__... | Loads the configuration from a specific file
:param config_file: the name of the config file
:param path: the path to the config file | [
"Loads",
"the",
"configuration",
"from",
"a",
"specific",
"file"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/config.py#L81-L92 | train | 40,758 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_editor/state_editor.py | StateEditorController.state_type_changed | def state_type_changed(self, model, prop_name, info):
"""Reopen state editor when state type is changed
When the type of the observed state changes, a new model is created. The look of this controller's view
depends on the kind of model. Therefore, we have to destroy this editor and open a new one with the new model.
"""
msg = info['arg']
# print(self.__class__.__name__, "state_type_changed check", info)
if msg.action in ['change_state_type', 'change_root_state_type'] and msg.after:
# print(self.__class__.__name__, "state_type_changed")
import rafcon.gui.singleton as gui_singletons
msg = info['arg']
new_state_m = msg.affected_models[-1]
states_editor_ctrl = gui_singletons.main_window_controller.get_controller('states_editor_ctrl')
states_editor_ctrl.recreate_state_editor(self.model, new_state_m) | python | def state_type_changed(self, model, prop_name, info):
"""Reopen state editor when state type is changed
When the type of the observed state changes, a new model is created. The look of this controller's view
depends on the kind of model. Therefore, we have to destroy this editor and open a new one with the new model.
"""
msg = info['arg']
# print(self.__class__.__name__, "state_type_changed check", info)
if msg.action in ['change_state_type', 'change_root_state_type'] and msg.after:
# print(self.__class__.__name__, "state_type_changed")
import rafcon.gui.singleton as gui_singletons
msg = info['arg']
new_state_m = msg.affected_models[-1]
states_editor_ctrl = gui_singletons.main_window_controller.get_controller('states_editor_ctrl')
states_editor_ctrl.recreate_state_editor(self.model, new_state_m) | [
"def",
"state_type_changed",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"msg",
"=",
"info",
"[",
"'arg'",
"]",
"# print(self.__class__.__name__, \"state_type_changed check\", info)",
"if",
"msg",
".",
"action",
"in",
"[",
"'change_state_type... | Reopen state editor when state type is changed
When the type of the observed state changes, a new model is created. The look of this controller's view
depends on the kind of model. Therefore, we have to destroy this editor and open a new one with the new model. | [
"Reopen",
"state",
"editor",
"when",
"state",
"type",
"is",
"changed"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/state_editor.py#L179-L193 | train | 40,759 |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_editor/state_editor.py | StateEditorController.state_destruction | def state_destruction(self, model, prop_name, info):
""" Close state editor when state is being destructed """
import rafcon.gui.singleton as gui_singletons
states_editor_ctrl = gui_singletons.main_window_controller.get_controller('states_editor_ctrl')
state_identifier = states_editor_ctrl.get_state_identifier(self.model)
states_editor_ctrl.close_page(state_identifier, delete=True) | python | def state_destruction(self, model, prop_name, info):
""" Close state editor when state is being destructed """
import rafcon.gui.singleton as gui_singletons
states_editor_ctrl = gui_singletons.main_window_controller.get_controller('states_editor_ctrl')
state_identifier = states_editor_ctrl.get_state_identifier(self.model)
states_editor_ctrl.close_page(state_identifier, delete=True) | [
"def",
"state_destruction",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"import",
"rafcon",
".",
"gui",
".",
"singleton",
"as",
"gui_singletons",
"states_editor_ctrl",
"=",
"gui_singletons",
".",
"main_window_controller",
".",
"get_controll... | Close state editor when state is being destructed | [
"Close",
"state",
"editor",
"when",
"state",
"is",
"being",
"destructed"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_editor/state_editor.py#L196-L201 | train | 40,760 |
DLR-RM/RAFCON | source/rafcon/gui/models/state_machine.py | StateMachineModel.meta_changed | def meta_changed(self, model, prop_name, info):
"""When the meta was changed, we have to set the dirty flag, as the changes are unsaved"""
self.state_machine.marked_dirty = True
msg = info.arg
if model is not self and msg.change.startswith('sm_notification_'): # Signal was caused by the root state
# Emit state_meta_signal to inform observing controllers about changes made to the meta data within the
# state machine
# -> removes mark of "sm_notification_"-prepend to mark root-state msg forwarded to state machine label
msg = msg._replace(change=msg.change.replace('sm_notification_', '', 1))
self.state_meta_signal.emit(msg) | python | def meta_changed(self, model, prop_name, info):
"""When the meta was changed, we have to set the dirty flag, as the changes are unsaved"""
self.state_machine.marked_dirty = True
msg = info.arg
if model is not self and msg.change.startswith('sm_notification_'): # Signal was caused by the root state
# Emit state_meta_signal to inform observing controllers about changes made to the meta data within the
# state machine
# -> removes mark of "sm_notification_"-prepend to mark root-state msg forwarded to state machine label
msg = msg._replace(change=msg.change.replace('sm_notification_', '', 1))
self.state_meta_signal.emit(msg) | [
"def",
"meta_changed",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"self",
".",
"state_machine",
".",
"marked_dirty",
"=",
"True",
"msg",
"=",
"info",
".",
"arg",
"if",
"model",
"is",
"not",
"self",
"and",
"msg",
".",
"change",
... | When the meta was changed, we have to set the dirty flag, as the changes are unsaved | [
"When",
"the",
"meta",
"was",
"changed",
"we",
"have",
"to",
"set",
"the",
"dirty",
"flag",
"as",
"the",
"changes",
"are",
"unsaved"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/state_machine.py#L215-L224 | train | 40,761 |
DLR-RM/RAFCON | source/rafcon/gui/models/state_machine.py | StateMachineModel.action_signal_triggered | def action_signal_triggered(self, model, prop_name, info):
"""When the action was performed, we have to set the dirty flag, as the changes are unsaved"""
# print("ACTION_signal_triggered state machine: ", model, prop_name, info)
self.state_machine.marked_dirty = True
msg = info.arg
if model is not self and msg.action.startswith('sm_notification_'): # Signal was caused by the root state
# Emit state_action_signal to inform observing controllers about changes made to the state within the
# state machine
# print("DONE1 S", self.state_machine.state_machine_id, msg, model)
# -> removes mark of "sm_notification_"-prepend to mark root-state msg forwarded to state machine label
msg = msg._replace(action=msg.action.replace('sm_notification_', '', 1))
self.state_action_signal.emit(msg)
# print("FINISH DONE1 S", self.state_machine.state_machine_id, msg)
else:
# print("DONE2 S", self.state_machine.state_machine_id, msg)
pass | python | def action_signal_triggered(self, model, prop_name, info):
"""When the action was performed, we have to set the dirty flag, as the changes are unsaved"""
# print("ACTION_signal_triggered state machine: ", model, prop_name, info)
self.state_machine.marked_dirty = True
msg = info.arg
if model is not self and msg.action.startswith('sm_notification_'): # Signal was caused by the root state
# Emit state_action_signal to inform observing controllers about changes made to the state within the
# state machine
# print("DONE1 S", self.state_machine.state_machine_id, msg, model)
# -> removes mark of "sm_notification_"-prepend to mark root-state msg forwarded to state machine label
msg = msg._replace(action=msg.action.replace('sm_notification_', '', 1))
self.state_action_signal.emit(msg)
# print("FINISH DONE1 S", self.state_machine.state_machine_id, msg)
else:
# print("DONE2 S", self.state_machine.state_machine_id, msg)
pass | [
"def",
"action_signal_triggered",
"(",
"self",
",",
"model",
",",
"prop_name",
",",
"info",
")",
":",
"# print(\"ACTION_signal_triggered state machine: \", model, prop_name, info)",
"self",
".",
"state_machine",
".",
"marked_dirty",
"=",
"True",
"msg",
"=",
"info",
".",... | When the action was performed, we have to set the dirty flag, as the changes are unsaved | [
"When",
"the",
"action",
"was",
"performed",
"we",
"have",
"to",
"set",
"the",
"dirty",
"flag",
"as",
"the",
"changes",
"are",
"unsaved"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/state_machine.py#L227-L242 | train | 40,762 |
DLR-RM/RAFCON | source/rafcon/gui/models/state_machine.py | StateMachineModel.load_meta_data | def load_meta_data(self, path=None, recursively=True):
"""Load meta data of state machine model from the file system
The meta data of the state machine model is loaded from the file system and stored in the meta property of the
model. Existing meta data is removed. Also the meta data of root state and children is loaded.
:param str path: Optional path to the meta data file. If not given, the path will be derived from the state
machine's path on the filesystem
"""
meta_data_path = path if path is not None else self.state_machine.file_system_path
if meta_data_path:
path_meta_data = os.path.join(meta_data_path, storage.FILE_NAME_META_DATA)
try:
tmp_meta = storage.load_data_file(path_meta_data)
except ValueError:
tmp_meta = {}
else:
tmp_meta = {}
# JSON returns a dict, which must be converted to a Vividict
tmp_meta = Vividict(tmp_meta)
if recursively:
root_state_path = None if not path else os.path.join(path, self.root_state.state.state_id)
self.root_state.load_meta_data(root_state_path)
if tmp_meta:
# assign the meta data to the state
self.meta = tmp_meta
self.meta_signal.emit(MetaSignalMsg("load_meta_data", "all", True)) | python | def load_meta_data(self, path=None, recursively=True):
"""Load meta data of state machine model from the file system
The meta data of the state machine model is loaded from the file system and stored in the meta property of the
model. Existing meta data is removed. Also the meta data of root state and children is loaded.
:param str path: Optional path to the meta data file. If not given, the path will be derived from the state
machine's path on the filesystem
"""
meta_data_path = path if path is not None else self.state_machine.file_system_path
if meta_data_path:
path_meta_data = os.path.join(meta_data_path, storage.FILE_NAME_META_DATA)
try:
tmp_meta = storage.load_data_file(path_meta_data)
except ValueError:
tmp_meta = {}
else:
tmp_meta = {}
# JSON returns a dict, which must be converted to a Vividict
tmp_meta = Vividict(tmp_meta)
if recursively:
root_state_path = None if not path else os.path.join(path, self.root_state.state.state_id)
self.root_state.load_meta_data(root_state_path)
if tmp_meta:
# assign the meta data to the state
self.meta = tmp_meta
self.meta_signal.emit(MetaSignalMsg("load_meta_data", "all", True)) | [
"def",
"load_meta_data",
"(",
"self",
",",
"path",
"=",
"None",
",",
"recursively",
"=",
"True",
")",
":",
"meta_data_path",
"=",
"path",
"if",
"path",
"is",
"not",
"None",
"else",
"self",
".",
"state_machine",
".",
"file_system_path",
"if",
"meta_data_path"... | Load meta data of state machine model from the file system
The meta data of the state machine model is loaded from the file system and stored in the meta property of the
model. Existing meta data is removed. Also the meta data of root state and children is loaded.
:param str path: Optional path to the meta data file. If not given, the path will be derived from the state
machine's path on the filesystem | [
"Load",
"meta",
"data",
"of",
"state",
"machine",
"model",
"from",
"the",
"file",
"system"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/state_machine.py#L341-L372 | train | 40,763 |
DLR-RM/RAFCON | source/rafcon/gui/models/state_machine.py | StateMachineModel.store_meta_data | def store_meta_data(self, copy_path=None):
"""Save meta data of the state machine model to the file system
This method generates a dictionary of the meta data of the state machine and stores it on the filesystem.
:param str copy_path: Optional, if the path is specified, it will be used instead of the file system path
"""
if copy_path:
meta_file_json = os.path.join(copy_path, storage.FILE_NAME_META_DATA)
else:
meta_file_json = os.path.join(self.state_machine.file_system_path, storage.FILE_NAME_META_DATA)
storage_utils.write_dict_to_json(self.meta, meta_file_json)
self.root_state.store_meta_data(copy_path) | python | def store_meta_data(self, copy_path=None):
"""Save meta data of the state machine model to the file system
This method generates a dictionary of the meta data of the state machine and stores it on the filesystem.
:param str copy_path: Optional, if the path is specified, it will be used instead of the file system path
"""
if copy_path:
meta_file_json = os.path.join(copy_path, storage.FILE_NAME_META_DATA)
else:
meta_file_json = os.path.join(self.state_machine.file_system_path, storage.FILE_NAME_META_DATA)
storage_utils.write_dict_to_json(self.meta, meta_file_json)
self.root_state.store_meta_data(copy_path) | [
"def",
"store_meta_data",
"(",
"self",
",",
"copy_path",
"=",
"None",
")",
":",
"if",
"copy_path",
":",
"meta_file_json",
"=",
"os",
".",
"path",
".",
"join",
"(",
"copy_path",
",",
"storage",
".",
"FILE_NAME_META_DATA",
")",
"else",
":",
"meta_file_json",
... | Save meta data of the state machine model to the file system
This method generates a dictionary of the meta data of the state machine and stores it on the filesystem.
:param str copy_path: Optional, if the path is specified, it will be used instead of the file system path | [
"Save",
"meta",
"data",
"of",
"the",
"state",
"machine",
"model",
"to",
"the",
"file",
"system"
] | 24942ef1a904531f49ab8830a1dbb604441be498 | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/state_machine.py#L374-L388 | train | 40,764 |
dmcc/PyStanfordDependencies | StanfordDependencies/StanfordDependencies.py | StanfordDependencies._raise_on_bad_jar_filename | def _raise_on_bad_jar_filename(jar_filename):
"""Ensure that jar_filename is a valid path to a jar file."""
if jar_filename is None:
return
if not isinstance(jar_filename, string_type):
raise TypeError("jar_filename is not a string: %r" % jar_filename)
if not os.path.exists(jar_filename):
raise ValueError("jar_filename does not exist: %r" % jar_filename) | python | def _raise_on_bad_jar_filename(jar_filename):
"""Ensure that jar_filename is a valid path to a jar file."""
if jar_filename is None:
return
if not isinstance(jar_filename, string_type):
raise TypeError("jar_filename is not a string: %r" % jar_filename)
if not os.path.exists(jar_filename):
raise ValueError("jar_filename does not exist: %r" % jar_filename) | [
"def",
"_raise_on_bad_jar_filename",
"(",
"jar_filename",
")",
":",
"if",
"jar_filename",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"jar_filename",
",",
"string_type",
")",
":",
"raise",
"TypeError",
"(",
"\"jar_filename is not a string: %r\"",
"%... | Ensure that jar_filename is a valid path to a jar file. | [
"Ensure",
"that",
"jar_filename",
"is",
"a",
"valid",
"path",
"to",
"a",
"jar",
"file",
"."
] | 43d8f38a19e40087f273330087918c87df6d4d8f | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/StanfordDependencies.py#L175-L184 | train | 40,765 |
dmcc/PyStanfordDependencies | StanfordDependencies/StanfordDependencies.py | StanfordDependencies.get_jar_url | def get_jar_url(version=None):
"""Get the URL to a Stanford CoreNLP jar file with a specific
version. These jars come from Maven since the Maven version is
smaller than the full CoreNLP distributions. Defaults to
DEFAULT_CORENLP_VERSION."""
if version is None:
version = DEFAULT_CORENLP_VERSION
try:
string_type = basestring
except NameError:
string_type = str
if not isinstance(version, string_type):
raise TypeError("Version must be a string or None (got %r)." %
version)
jar_filename = 'stanford-corenlp-%s.jar' % version
return 'http://search.maven.org/remotecontent?filepath=' + \
'edu/stanford/nlp/stanford-corenlp/%s/%s' % (version,
jar_filename) | python | def get_jar_url(version=None):
"""Get the URL to a Stanford CoreNLP jar file with a specific
version. These jars come from Maven since the Maven version is
smaller than the full CoreNLP distributions. Defaults to
DEFAULT_CORENLP_VERSION."""
if version is None:
version = DEFAULT_CORENLP_VERSION
try:
string_type = basestring
except NameError:
string_type = str
if not isinstance(version, string_type):
raise TypeError("Version must be a string or None (got %r)." %
version)
jar_filename = 'stanford-corenlp-%s.jar' % version
return 'http://search.maven.org/remotecontent?filepath=' + \
'edu/stanford/nlp/stanford-corenlp/%s/%s' % (version,
jar_filename) | [
"def",
"get_jar_url",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"DEFAULT_CORENLP_VERSION",
"try",
":",
"string_type",
"=",
"basestring",
"except",
"NameError",
":",
"string_type",
"=",
"str",
"if",
"not",
"isi... | Get the URL to a Stanford CoreNLP jar file with a specific
version. These jars come from Maven since the Maven version is
smaller than the full CoreNLP distributions. Defaults to
DEFAULT_CORENLP_VERSION. | [
"Get",
"the",
"URL",
"to",
"a",
"Stanford",
"CoreNLP",
"jar",
"file",
"with",
"a",
"specific",
"version",
".",
"These",
"jars",
"come",
"from",
"Maven",
"since",
"the",
"Maven",
"version",
"is",
"smaller",
"than",
"the",
"full",
"CoreNLP",
"distributions",
... | 43d8f38a19e40087f273330087918c87df6d4d8f | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/StanfordDependencies.py#L187-L206 | train | 40,766 |
dmcc/PyStanfordDependencies | StanfordDependencies/JPypeBackend.py | JPypeBackend.convert_tree | def convert_tree(self, ptb_tree, representation='basic',
include_punct=True, include_erased=False,
add_lemmas=False, universal=True):
"""Arguments are as in StanfordDependencies.convert_trees but with
the addition of add_lemmas. If add_lemmas=True, we will run the
Stanford CoreNLP lemmatizer and fill in the lemma field."""
self._raise_on_bad_input(ptb_tree)
self._raise_on_bad_representation(representation)
tree = self.treeReader(ptb_tree)
if tree is None:
raise ValueError("Invalid Penn Treebank tree: %r" % ptb_tree)
deps = self._get_deps(tree, include_punct, representation,
universal=universal)
tagged_yield = self._listify(tree.taggedYield())
indices_to_words = dict(enumerate(tagged_yield, 1))
sentence = Sentence()
covered_indices = set()
def add_token(index, form, head, deprel, extra):
tag = indices_to_words[index].tag()
if add_lemmas:
lemma = self.stem(form, tag)
else:
lemma = None
token = Token(index=index, form=form, lemma=lemma, cpos=tag,
pos=tag, feats=None, head=head, deprel=deprel,
phead=None, pdeprel=None, extra=extra)
sentence.append(token)
# add token for each dependency
for dep in deps:
index = dep.dep().index()
head = dep.gov().index()
deprel = dep.reln().toString()
form = indices_to_words[index].value()
dep_is_copy = dep.dep().copyCount()
gov_is_copy = dep.gov().copyCount()
if dep_is_copy or gov_is_copy:
extra = {}
if dep_is_copy:
extra['dep_is_copy'] = dep_is_copy
if gov_is_copy:
extra['gov_is_copy'] = gov_is_copy
else:
extra = None
add_token(index, form, head, deprel, extra)
covered_indices.add(index)
if include_erased:
# see if there are any tokens that were erased
# and add them as well
all_indices = set(indices_to_words.keys())
for index in all_indices - covered_indices:
form = indices_to_words[index].value()
if not include_punct and not self.puncFilter(form):
continue
add_token(index, form, head=0, deprel='erased', extra=None)
# erased generally disrupt the ordering of the sentence
sentence.sort()
if representation == 'basic':
sentence.renumber()
return sentence | python | def convert_tree(self, ptb_tree, representation='basic',
include_punct=True, include_erased=False,
add_lemmas=False, universal=True):
"""Arguments are as in StanfordDependencies.convert_trees but with
the addition of add_lemmas. If add_lemmas=True, we will run the
Stanford CoreNLP lemmatizer and fill in the lemma field."""
self._raise_on_bad_input(ptb_tree)
self._raise_on_bad_representation(representation)
tree = self.treeReader(ptb_tree)
if tree is None:
raise ValueError("Invalid Penn Treebank tree: %r" % ptb_tree)
deps = self._get_deps(tree, include_punct, representation,
universal=universal)
tagged_yield = self._listify(tree.taggedYield())
indices_to_words = dict(enumerate(tagged_yield, 1))
sentence = Sentence()
covered_indices = set()
def add_token(index, form, head, deprel, extra):
tag = indices_to_words[index].tag()
if add_lemmas:
lemma = self.stem(form, tag)
else:
lemma = None
token = Token(index=index, form=form, lemma=lemma, cpos=tag,
pos=tag, feats=None, head=head, deprel=deprel,
phead=None, pdeprel=None, extra=extra)
sentence.append(token)
# add token for each dependency
for dep in deps:
index = dep.dep().index()
head = dep.gov().index()
deprel = dep.reln().toString()
form = indices_to_words[index].value()
dep_is_copy = dep.dep().copyCount()
gov_is_copy = dep.gov().copyCount()
if dep_is_copy or gov_is_copy:
extra = {}
if dep_is_copy:
extra['dep_is_copy'] = dep_is_copy
if gov_is_copy:
extra['gov_is_copy'] = gov_is_copy
else:
extra = None
add_token(index, form, head, deprel, extra)
covered_indices.add(index)
if include_erased:
# see if there are any tokens that were erased
# and add them as well
all_indices = set(indices_to_words.keys())
for index in all_indices - covered_indices:
form = indices_to_words[index].value()
if not include_punct and not self.puncFilter(form):
continue
add_token(index, form, head=0, deprel='erased', extra=None)
# erased generally disrupt the ordering of the sentence
sentence.sort()
if representation == 'basic':
sentence.renumber()
return sentence | [
"def",
"convert_tree",
"(",
"self",
",",
"ptb_tree",
",",
"representation",
"=",
"'basic'",
",",
"include_punct",
"=",
"True",
",",
"include_erased",
"=",
"False",
",",
"add_lemmas",
"=",
"False",
",",
"universal",
"=",
"True",
")",
":",
"self",
".",
"_rai... | Arguments are as in StanfordDependencies.convert_trees but with
the addition of add_lemmas. If add_lemmas=True, we will run the
Stanford CoreNLP lemmatizer and fill in the lemma field. | [
"Arguments",
"are",
"as",
"in",
"StanfordDependencies",
".",
"convert_trees",
"but",
"with",
"the",
"addition",
"of",
"add_lemmas",
".",
"If",
"add_lemmas",
"=",
"True",
"we",
"will",
"run",
"the",
"Stanford",
"CoreNLP",
"lemmatizer",
"and",
"fill",
"in",
"the... | 43d8f38a19e40087f273330087918c87df6d4d8f | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/JPypeBackend.py#L86-L149 | train | 40,767 |
dmcc/PyStanfordDependencies | StanfordDependencies/JPypeBackend.py | JPypeBackend.stem | def stem(self, form, tag):
"""Returns the stem of word with specific form and part-of-speech
tag according to the Stanford lemmatizer. Lemmas are cached."""
key = (form, tag)
if key not in self.lemma_cache:
lemma = self.stemmer(*key).word()
self.lemma_cache[key] = lemma
return self.lemma_cache[key] | python | def stem(self, form, tag):
"""Returns the stem of word with specific form and part-of-speech
tag according to the Stanford lemmatizer. Lemmas are cached."""
key = (form, tag)
if key not in self.lemma_cache:
lemma = self.stemmer(*key).word()
self.lemma_cache[key] = lemma
return self.lemma_cache[key] | [
"def",
"stem",
"(",
"self",
",",
"form",
",",
"tag",
")",
":",
"key",
"=",
"(",
"form",
",",
"tag",
")",
"if",
"key",
"not",
"in",
"self",
".",
"lemma_cache",
":",
"lemma",
"=",
"self",
".",
"stemmer",
"(",
"*",
"key",
")",
".",
"word",
"(",
... | Returns the stem of word with specific form and part-of-speech
tag according to the Stanford lemmatizer. Lemmas are cached. | [
"Returns",
"the",
"stem",
"of",
"word",
"with",
"specific",
"form",
"and",
"part",
"-",
"of",
"-",
"speech",
"tag",
"according",
"to",
"the",
"Stanford",
"lemmatizer",
".",
"Lemmas",
"are",
"cached",
"."
] | 43d8f38a19e40087f273330087918c87df6d4d8f | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/JPypeBackend.py#L150-L157 | train | 40,768 |
dmcc/PyStanfordDependencies | StanfordDependencies/JPypeBackend.py | JPypeBackend._get_deps | def _get_deps(self, tree, include_punct, representation, universal):
"""Get a list of dependencies from a Stanford Tree for a specific
Stanford Dependencies representation."""
if universal:
converter = self.universal_converter
if self.universal_converter == self.converter:
import warnings
warnings.warn("This jar doesn't support universal "
"dependencies, falling back to Stanford "
"Dependencies. To suppress this message, "
"call with universal=False")
else:
converter = self.converter
if include_punct:
egs = converter(tree, self.acceptFilter)
else:
egs = converter(tree)
if representation == 'basic':
deps = egs.typedDependencies()
elif representation == 'collapsed':
deps = egs.typedDependenciesCollapsed(True)
elif representation == 'CCprocessed':
deps = egs.typedDependenciesCCprocessed(True)
else:
# _raise_on_bad_representation should ensure that this
# assertion doesn't fail
assert representation == 'collapsedTree'
deps = egs.typedDependenciesCollapsedTree()
return self._listify(deps) | python | def _get_deps(self, tree, include_punct, representation, universal):
"""Get a list of dependencies from a Stanford Tree for a specific
Stanford Dependencies representation."""
if universal:
converter = self.universal_converter
if self.universal_converter == self.converter:
import warnings
warnings.warn("This jar doesn't support universal "
"dependencies, falling back to Stanford "
"Dependencies. To suppress this message, "
"call with universal=False")
else:
converter = self.converter
if include_punct:
egs = converter(tree, self.acceptFilter)
else:
egs = converter(tree)
if representation == 'basic':
deps = egs.typedDependencies()
elif representation == 'collapsed':
deps = egs.typedDependenciesCollapsed(True)
elif representation == 'CCprocessed':
deps = egs.typedDependenciesCCprocessed(True)
else:
# _raise_on_bad_representation should ensure that this
# assertion doesn't fail
assert representation == 'collapsedTree'
deps = egs.typedDependenciesCollapsedTree()
return self._listify(deps) | [
"def",
"_get_deps",
"(",
"self",
",",
"tree",
",",
"include_punct",
",",
"representation",
",",
"universal",
")",
":",
"if",
"universal",
":",
"converter",
"=",
"self",
".",
"universal_converter",
"if",
"self",
".",
"universal_converter",
"==",
"self",
".",
... | Get a list of dependencies from a Stanford Tree for a specific
Stanford Dependencies representation. | [
"Get",
"a",
"list",
"of",
"dependencies",
"from",
"a",
"Stanford",
"Tree",
"for",
"a",
"specific",
"Stanford",
"Dependencies",
"representation",
"."
] | 43d8f38a19e40087f273330087918c87df6d4d8f | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/JPypeBackend.py#L159-L190 | train | 40,769 |
dmcc/PyStanfordDependencies | StanfordDependencies/JPypeBackend.py | JPypeBackend._listify | def _listify(collection):
"""This is a workaround where Collections are no longer iterable
when using JPype."""
new_list = []
for index in range(len(collection)):
new_list.append(collection[index])
return new_list | python | def _listify(collection):
"""This is a workaround where Collections are no longer iterable
when using JPype."""
new_list = []
for index in range(len(collection)):
new_list.append(collection[index])
return new_list | [
"def",
"_listify",
"(",
"collection",
")",
":",
"new_list",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"collection",
")",
")",
":",
"new_list",
".",
"append",
"(",
"collection",
"[",
"index",
"]",
")",
"return",
"new_list"
] | This is a workaround where Collections are no longer iterable
when using JPype. | [
"This",
"is",
"a",
"workaround",
"where",
"Collections",
"are",
"no",
"longer",
"iterable",
"when",
"using",
"JPype",
"."
] | 43d8f38a19e40087f273330087918c87df6d4d8f | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/JPypeBackend.py#L193-L199 | train | 40,770 |
dmcc/PyStanfordDependencies | StanfordDependencies/CoNLL.py | Token.as_conll | def as_conll(self):
"""Represent this Token as a line as a string in CoNLL-X format."""
def get(field):
value = getattr(self, field)
if value is None:
value = '_'
elif field == 'feats':
value = '|'.join(value)
return str(value)
return '\t'.join([get(field) for field in FIELD_NAMES]) | python | def as_conll(self):
"""Represent this Token as a line as a string in CoNLL-X format."""
def get(field):
value = getattr(self, field)
if value is None:
value = '_'
elif field == 'feats':
value = '|'.join(value)
return str(value)
return '\t'.join([get(field) for field in FIELD_NAMES]) | [
"def",
"as_conll",
"(",
"self",
")",
":",
"def",
"get",
"(",
"field",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"field",
")",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"'_'",
"elif",
"field",
"==",
"'feats'",
":",
"value",
"=",
"... | Represent this Token as a line as a string in CoNLL-X format. | [
"Represent",
"this",
"Token",
"as",
"a",
"line",
"as",
"a",
"string",
"in",
"CoNLL",
"-",
"X",
"format",
"."
] | 43d8f38a19e40087f273330087918c87df6d4d8f | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/CoNLL.py#L74-L83 | train | 40,771 |
dmcc/PyStanfordDependencies | StanfordDependencies/CoNLL.py | Token.from_conll | def from_conll(this_class, text):
"""Construct a Token from a line in CoNLL-X format."""
fields = text.split('\t')
fields[0] = int(fields[0]) # index
fields[6] = int(fields[6]) # head index
if fields[5] != '_': # feats
fields[5] = tuple(fields[5].split('|'))
fields = [value if value != '_' else None for value in fields]
fields.append(None) # for extra
return this_class(**dict(zip(FIELD_NAMES_PLUS, fields))) | python | def from_conll(this_class, text):
"""Construct a Token from a line in CoNLL-X format."""
fields = text.split('\t')
fields[0] = int(fields[0]) # index
fields[6] = int(fields[6]) # head index
if fields[5] != '_': # feats
fields[5] = tuple(fields[5].split('|'))
fields = [value if value != '_' else None for value in fields]
fields.append(None) # for extra
return this_class(**dict(zip(FIELD_NAMES_PLUS, fields))) | [
"def",
"from_conll",
"(",
"this_class",
",",
"text",
")",
":",
"fields",
"=",
"text",
".",
"split",
"(",
"'\\t'",
")",
"fields",
"[",
"0",
"]",
"=",
"int",
"(",
"fields",
"[",
"0",
"]",
")",
"# index",
"fields",
"[",
"6",
"]",
"=",
"int",
"(",
... | Construct a Token from a line in CoNLL-X format. | [
"Construct",
"a",
"Token",
"from",
"a",
"line",
"in",
"CoNLL",
"-",
"X",
"format",
"."
] | 43d8f38a19e40087f273330087918c87df6d4d8f | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/CoNLL.py#L85-L94 | train | 40,772 |
dmcc/PyStanfordDependencies | StanfordDependencies/CoNLL.py | Sentence.as_asciitree | def as_asciitree(self, str_func=None):
"""Represent this Sentence as an ASCII tree string. Requires
the asciitree package. A default token stringifier is provided
but for custom formatting, specify a str_func which should take
a single Token and return a string."""
import asciitree
from collections import defaultdict
children = defaultdict(list)
# since erased nodes may be missing, multiple tokens may have same
# index (CCprocessed), etc.
token_to_index = {}
roots = []
for token in self:
children[token.head].append(token)
token_to_index[token] = token.index
if token.head == 0:
roots.append(token)
assert roots, "Couldn't find root Token(s)"
if len(roots) > 1:
# multiple roots so we make a fake one to be their parent
root = Token(0, 'ROOT', 'ROOT-LEMMA', 'ROOT-CPOS', 'ROOT-POS',
None, None, 'ROOT-DEPREL', None, None, None)
token_to_index[root] = 0
children[0] = roots
else:
root = roots[0]
def child_func(token):
index = token_to_index[token]
return children[index]
if not str_func:
def str_func(token):
return ' %s [%s]' % (token.form, token.deprel)
return asciitree.draw_tree(root, child_func, str_func) | python | def as_asciitree(self, str_func=None):
"""Represent this Sentence as an ASCII tree string. Requires
the asciitree package. A default token stringifier is provided
but for custom formatting, specify a str_func which should take
a single Token and return a string."""
import asciitree
from collections import defaultdict
children = defaultdict(list)
# since erased nodes may be missing, multiple tokens may have same
# index (CCprocessed), etc.
token_to_index = {}
roots = []
for token in self:
children[token.head].append(token)
token_to_index[token] = token.index
if token.head == 0:
roots.append(token)
assert roots, "Couldn't find root Token(s)"
if len(roots) > 1:
# multiple roots so we make a fake one to be their parent
root = Token(0, 'ROOT', 'ROOT-LEMMA', 'ROOT-CPOS', 'ROOT-POS',
None, None, 'ROOT-DEPREL', None, None, None)
token_to_index[root] = 0
children[0] = roots
else:
root = roots[0]
def child_func(token):
index = token_to_index[token]
return children[index]
if not str_func:
def str_func(token):
return ' %s [%s]' % (token.form, token.deprel)
return asciitree.draw_tree(root, child_func, str_func) | [
"def",
"as_asciitree",
"(",
"self",
",",
"str_func",
"=",
"None",
")",
":",
"import",
"asciitree",
"from",
"collections",
"import",
"defaultdict",
"children",
"=",
"defaultdict",
"(",
"list",
")",
"# since erased nodes may be missing, multiple tokens may have same",
"# ... | Represent this Sentence as an ASCII tree string. Requires
the asciitree package. A default token stringifier is provided
but for custom formatting, specify a str_func which should take
a single Token and return a string. | [
"Represent",
"this",
"Sentence",
"as",
"an",
"ASCII",
"tree",
"string",
".",
"Requires",
"the",
"asciitree",
"package",
".",
"A",
"default",
"token",
"stringifier",
"is",
"provided",
"but",
"for",
"custom",
"formatting",
"specify",
"a",
"str_func",
"which",
"s... | 43d8f38a19e40087f273330087918c87df6d4d8f | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/CoNLL.py#L120-L155 | train | 40,773 |
dmcc/PyStanfordDependencies | StanfordDependencies/CoNLL.py | Sentence.from_conll | def from_conll(this_class, stream):
"""Construct a Sentence. stream is an iterable over strings where
each string is a line in CoNLL-X format. If there are multiple
sentences in this stream, we only return the first one."""
stream = iter(stream)
sentence = this_class()
for line in stream:
line = line.strip()
if line:
sentence.append(Token.from_conll(line))
elif sentence:
return sentence
return sentence | python | def from_conll(this_class, stream):
"""Construct a Sentence. stream is an iterable over strings where
each string is a line in CoNLL-X format. If there are multiple
sentences in this stream, we only return the first one."""
stream = iter(stream)
sentence = this_class()
for line in stream:
line = line.strip()
if line:
sentence.append(Token.from_conll(line))
elif sentence:
return sentence
return sentence | [
"def",
"from_conll",
"(",
"this_class",
",",
"stream",
")",
":",
"stream",
"=",
"iter",
"(",
"stream",
")",
"sentence",
"=",
"this_class",
"(",
")",
"for",
"line",
"in",
"stream",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
":",
... | Construct a Sentence. stream is an iterable over strings where
each string is a line in CoNLL-X format. If there are multiple
sentences in this stream, we only return the first one. | [
"Construct",
"a",
"Sentence",
".",
"stream",
"is",
"an",
"iterable",
"over",
"strings",
"where",
"each",
"string",
"is",
"a",
"line",
"in",
"CoNLL",
"-",
"X",
"format",
".",
"If",
"there",
"are",
"multiple",
"sentences",
"in",
"this",
"stream",
"we",
"on... | 43d8f38a19e40087f273330087918c87df6d4d8f | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/CoNLL.py#L194-L206 | train | 40,774 |
dmcc/PyStanfordDependencies | StanfordDependencies/CoNLL.py | Corpus.from_conll | def from_conll(this_class, stream):
"""Construct a Corpus. stream is an iterable over strings where
each string is a line in CoNLL-X format."""
stream = iter(stream)
corpus = this_class()
while 1:
# read until we get an empty sentence
sentence = Sentence.from_conll(stream)
if sentence:
corpus.append(sentence)
else:
break
return corpus | python | def from_conll(this_class, stream):
"""Construct a Corpus. stream is an iterable over strings where
each string is a line in CoNLL-X format."""
stream = iter(stream)
corpus = this_class()
while 1:
# read until we get an empty sentence
sentence = Sentence.from_conll(stream)
if sentence:
corpus.append(sentence)
else:
break
return corpus | [
"def",
"from_conll",
"(",
"this_class",
",",
"stream",
")",
":",
"stream",
"=",
"iter",
"(",
"stream",
")",
"corpus",
"=",
"this_class",
"(",
")",
"while",
"1",
":",
"# read until we get an empty sentence",
"sentence",
"=",
"Sentence",
".",
"from_conll",
"(",
... | Construct a Corpus. stream is an iterable over strings where
each string is a line in CoNLL-X format. | [
"Construct",
"a",
"Corpus",
".",
"stream",
"is",
"an",
"iterable",
"over",
"strings",
"where",
"each",
"string",
"is",
"a",
"line",
"in",
"CoNLL",
"-",
"X",
"format",
"."
] | 43d8f38a19e40087f273330087918c87df6d4d8f | https://github.com/dmcc/PyStanfordDependencies/blob/43d8f38a19e40087f273330087918c87df6d4d8f/StanfordDependencies/CoNLL.py#L277-L289 | train | 40,775 |
juju-solutions/charms.reactive | charms/reactive/relations.py | endpoint_from_name | def endpoint_from_name(endpoint_name):
"""The object used for interacting with the named relations, or None.
"""
if endpoint_name is None:
return None
factory = relation_factory(endpoint_name)
if factory:
return factory.from_name(endpoint_name) | python | def endpoint_from_name(endpoint_name):
"""The object used for interacting with the named relations, or None.
"""
if endpoint_name is None:
return None
factory = relation_factory(endpoint_name)
if factory:
return factory.from_name(endpoint_name) | [
"def",
"endpoint_from_name",
"(",
"endpoint_name",
")",
":",
"if",
"endpoint_name",
"is",
"None",
":",
"return",
"None",
"factory",
"=",
"relation_factory",
"(",
"endpoint_name",
")",
"if",
"factory",
":",
"return",
"factory",
".",
"from_name",
"(",
"endpoint_na... | The object used for interacting with the named relations, or None. | [
"The",
"object",
"used",
"for",
"interacting",
"with",
"the",
"named",
"relations",
"or",
"None",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L47-L54 | train | 40,776 |
juju-solutions/charms.reactive | charms/reactive/relations.py | endpoint_from_flag | def endpoint_from_flag(flag):
"""The object used for interacting with relations tied to a flag, or None.
"""
relation_name = None
value = _get_flag_value(flag)
if isinstance(value, dict) and 'relation' in value:
# old-style RelationBase
relation_name = value['relation']
elif flag.startswith('endpoint.'):
# new-style Endpoint
relation_name = flag.split('.')[1]
elif '.' in flag:
# might be an unprefixed new-style Endpoint
relation_name = flag.split('.')[0]
if relation_name not in hookenv.relation_types():
return None
if relation_name:
factory = relation_factory(relation_name)
if factory:
return factory.from_flag(flag)
return None | python | def endpoint_from_flag(flag):
"""The object used for interacting with relations tied to a flag, or None.
"""
relation_name = None
value = _get_flag_value(flag)
if isinstance(value, dict) and 'relation' in value:
# old-style RelationBase
relation_name = value['relation']
elif flag.startswith('endpoint.'):
# new-style Endpoint
relation_name = flag.split('.')[1]
elif '.' in flag:
# might be an unprefixed new-style Endpoint
relation_name = flag.split('.')[0]
if relation_name not in hookenv.relation_types():
return None
if relation_name:
factory = relation_factory(relation_name)
if factory:
return factory.from_flag(flag)
return None | [
"def",
"endpoint_from_flag",
"(",
"flag",
")",
":",
"relation_name",
"=",
"None",
"value",
"=",
"_get_flag_value",
"(",
"flag",
")",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"'relation'",
"in",
"value",
":",
"# old-style RelationBase",
"relat... | The object used for interacting with relations tied to a flag, or None. | [
"The",
"object",
"used",
"for",
"interacting",
"with",
"relations",
"tied",
"to",
"a",
"flag",
"or",
"None",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L65-L85 | train | 40,777 |
juju-solutions/charms.reactive | charms/reactive/relations.py | relation_factory | def relation_factory(relation_name):
"""Get the RelationFactory for the given relation name.
Looks for a RelationFactory in the first file matching:
``$CHARM_DIR/hooks/relations/{interface}/{provides,requires,peer}.py``
"""
role, interface = hookenv.relation_to_role_and_interface(relation_name)
if not (role and interface):
hookenv.log('Unable to determine role and interface for relation '
'{}'.format(relation_name), hookenv.ERROR)
return None
return _find_relation_factory(_relation_module(role, interface)) | python | def relation_factory(relation_name):
"""Get the RelationFactory for the given relation name.
Looks for a RelationFactory in the first file matching:
``$CHARM_DIR/hooks/relations/{interface}/{provides,requires,peer}.py``
"""
role, interface = hookenv.relation_to_role_and_interface(relation_name)
if not (role and interface):
hookenv.log('Unable to determine role and interface for relation '
'{}'.format(relation_name), hookenv.ERROR)
return None
return _find_relation_factory(_relation_module(role, interface)) | [
"def",
"relation_factory",
"(",
"relation_name",
")",
":",
"role",
",",
"interface",
"=",
"hookenv",
".",
"relation_to_role_and_interface",
"(",
"relation_name",
")",
"if",
"not",
"(",
"role",
"and",
"interface",
")",
":",
"hookenv",
".",
"log",
"(",
"'Unable ... | Get the RelationFactory for the given relation name.
Looks for a RelationFactory in the first file matching:
``$CHARM_DIR/hooks/relations/{interface}/{provides,requires,peer}.py`` | [
"Get",
"the",
"RelationFactory",
"for",
"the",
"given",
"relation",
"name",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L121-L132 | train | 40,778 |
juju-solutions/charms.reactive | charms/reactive/relations.py | _relation_module | def _relation_module(role, interface):
"""
Return module for relation based on its role and interface, or None.
Prefers new location (reactive/relations) over old (hooks/relations).
"""
_append_path(hookenv.charm_dir())
_append_path(os.path.join(hookenv.charm_dir(), 'hooks'))
base_module = 'relations.{}.{}'.format(interface, role)
for module in ('reactive.{}'.format(base_module), base_module):
if module in sys.modules:
break
try:
importlib.import_module(module)
break
except ImportError:
continue
else:
hookenv.log('Unable to find implementation for relation: '
'{} of {}'.format(role, interface), hookenv.ERROR)
return None
return sys.modules[module] | python | def _relation_module(role, interface):
"""
Return module for relation based on its role and interface, or None.
Prefers new location (reactive/relations) over old (hooks/relations).
"""
_append_path(hookenv.charm_dir())
_append_path(os.path.join(hookenv.charm_dir(), 'hooks'))
base_module = 'relations.{}.{}'.format(interface, role)
for module in ('reactive.{}'.format(base_module), base_module):
if module in sys.modules:
break
try:
importlib.import_module(module)
break
except ImportError:
continue
else:
hookenv.log('Unable to find implementation for relation: '
'{} of {}'.format(role, interface), hookenv.ERROR)
return None
return sys.modules[module] | [
"def",
"_relation_module",
"(",
"role",
",",
"interface",
")",
":",
"_append_path",
"(",
"hookenv",
".",
"charm_dir",
"(",
")",
")",
"_append_path",
"(",
"os",
".",
"path",
".",
"join",
"(",
"hookenv",
".",
"charm_dir",
"(",
")",
",",
"'hooks'",
")",
"... | Return module for relation based on its role and interface, or None.
Prefers new location (reactive/relations) over old (hooks/relations). | [
"Return",
"module",
"for",
"relation",
"based",
"on",
"its",
"role",
"and",
"interface",
"or",
"None",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L135-L156 | train | 40,779 |
juju-solutions/charms.reactive | charms/reactive/relations.py | _find_relation_factory | def _find_relation_factory(module):
"""
Attempt to find a RelationFactory subclass in the module.
Note: RelationFactory and RelationBase are ignored so they may
be imported to be used as base classes without fear.
"""
if not module:
return None
# All the RelationFactory subclasses
candidates = [o for o in (getattr(module, attr) for attr in dir(module))
if (o is not RelationFactory and
o is not RelationBase and
isclass(o) and
issubclass(o, RelationFactory))]
# Filter out any factories that are superclasses of another factory
# (none of the other factories subclass it). This usually makes
# the explict check for RelationBase and RelationFactory unnecessary.
candidates = [c1 for c1 in candidates
if not any(issubclass(c2, c1) for c2 in candidates
if c1 is not c2)]
if not candidates:
hookenv.log('No RelationFactory found in {}'.format(module.__name__),
hookenv.WARNING)
return None
if len(candidates) > 1:
raise RuntimeError('Too many RelationFactory found in {}'
''.format(module.__name__))
return candidates[0] | python | def _find_relation_factory(module):
"""
Attempt to find a RelationFactory subclass in the module.
Note: RelationFactory and RelationBase are ignored so they may
be imported to be used as base classes without fear.
"""
if not module:
return None
# All the RelationFactory subclasses
candidates = [o for o in (getattr(module, attr) for attr in dir(module))
if (o is not RelationFactory and
o is not RelationBase and
isclass(o) and
issubclass(o, RelationFactory))]
# Filter out any factories that are superclasses of another factory
# (none of the other factories subclass it). This usually makes
# the explict check for RelationBase and RelationFactory unnecessary.
candidates = [c1 for c1 in candidates
if not any(issubclass(c2, c1) for c2 in candidates
if c1 is not c2)]
if not candidates:
hookenv.log('No RelationFactory found in {}'.format(module.__name__),
hookenv.WARNING)
return None
if len(candidates) > 1:
raise RuntimeError('Too many RelationFactory found in {}'
''.format(module.__name__))
return candidates[0] | [
"def",
"_find_relation_factory",
"(",
"module",
")",
":",
"if",
"not",
"module",
":",
"return",
"None",
"# All the RelationFactory subclasses",
"candidates",
"=",
"[",
"o",
"for",
"o",
"in",
"(",
"getattr",
"(",
"module",
",",
"attr",
")",
"for",
"attr",
"in... | Attempt to find a RelationFactory subclass in the module.
Note: RelationFactory and RelationBase are ignored so they may
be imported to be used as base classes without fear. | [
"Attempt",
"to",
"find",
"a",
"RelationFactory",
"subclass",
"in",
"the",
"module",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L159-L192 | train | 40,780 |
juju-solutions/charms.reactive | charms/reactive/relations.py | relation_call | def relation_call(method, relation_name=None, flag=None, state=None, *args):
"""Invoke a method on the class implementing a relation via the CLI"""
if relation_name:
relation = relation_from_name(relation_name)
if relation is None:
raise ValueError('Relation not found: %s' % relation_name)
elif flag or state:
relation = relation_from_flag(flag or state)
if relation is None:
raise ValueError('Relation not found: %s' % (flag or state))
else:
raise ValueError('Must specify either relation_name or flag')
result = getattr(relation, method)(*args)
if isinstance(relation, RelationBase) and method == 'conversations':
# special case for conversations to make them work from CLI
result = [c.scope for c in result]
return result | python | def relation_call(method, relation_name=None, flag=None, state=None, *args):
"""Invoke a method on the class implementing a relation via the CLI"""
if relation_name:
relation = relation_from_name(relation_name)
if relation is None:
raise ValueError('Relation not found: %s' % relation_name)
elif flag or state:
relation = relation_from_flag(flag or state)
if relation is None:
raise ValueError('Relation not found: %s' % (flag or state))
else:
raise ValueError('Must specify either relation_name or flag')
result = getattr(relation, method)(*args)
if isinstance(relation, RelationBase) and method == 'conversations':
# special case for conversations to make them work from CLI
result = [c.scope for c in result]
return result | [
"def",
"relation_call",
"(",
"method",
",",
"relation_name",
"=",
"None",
",",
"flag",
"=",
"None",
",",
"state",
"=",
"None",
",",
"*",
"args",
")",
":",
"if",
"relation_name",
":",
"relation",
"=",
"relation_from_name",
"(",
"relation_name",
")",
"if",
... | Invoke a method on the class implementing a relation via the CLI | [
"Invoke",
"a",
"method",
"on",
"the",
"class",
"implementing",
"a",
"relation",
"via",
"the",
"CLI"
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L888-L904 | train | 40,781 |
juju-solutions/charms.reactive | charms/reactive/relations.py | RelationBase.from_flag | def from_flag(cls, flag):
"""
Find relation implementation in the current charm, based on the
name of an active flag.
You should not use this method directly.
Use :func:`endpoint_from_flag` instead.
"""
value = _get_flag_value(flag)
if value is None:
return None
relation_name = value['relation']
conversations = Conversation.load(value['conversations'])
return cls.from_name(relation_name, conversations) | python | def from_flag(cls, flag):
"""
Find relation implementation in the current charm, based on the
name of an active flag.
You should not use this method directly.
Use :func:`endpoint_from_flag` instead.
"""
value = _get_flag_value(flag)
if value is None:
return None
relation_name = value['relation']
conversations = Conversation.load(value['conversations'])
return cls.from_name(relation_name, conversations) | [
"def",
"from_flag",
"(",
"cls",
",",
"flag",
")",
":",
"value",
"=",
"_get_flag_value",
"(",
"flag",
")",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"relation_name",
"=",
"value",
"[",
"'relation'",
"]",
"conversations",
"=",
"Conversation",
".",
... | Find relation implementation in the current charm, based on the
name of an active flag.
You should not use this method directly.
Use :func:`endpoint_from_flag` instead. | [
"Find",
"relation",
"implementation",
"in",
"the",
"current",
"charm",
"based",
"on",
"the",
"name",
"of",
"an",
"active",
"flag",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L341-L354 | train | 40,782 |
juju-solutions/charms.reactive | charms/reactive/relations.py | RelationBase.from_name | def from_name(cls, relation_name, conversations=None):
"""
Find relation implementation in the current charm, based on the
name of the relation.
:return: A Relation instance, or None
"""
if relation_name is None:
return None
relation_class = cls._cache.get(relation_name)
if relation_class:
return relation_class(relation_name, conversations)
role, interface = hookenv.relation_to_role_and_interface(relation_name)
if role and interface:
relation_class = cls._find_impl(role, interface)
if relation_class:
cls._cache[relation_name] = relation_class
return relation_class(relation_name, conversations)
return None | python | def from_name(cls, relation_name, conversations=None):
"""
Find relation implementation in the current charm, based on the
name of the relation.
:return: A Relation instance, or None
"""
if relation_name is None:
return None
relation_class = cls._cache.get(relation_name)
if relation_class:
return relation_class(relation_name, conversations)
role, interface = hookenv.relation_to_role_and_interface(relation_name)
if role and interface:
relation_class = cls._find_impl(role, interface)
if relation_class:
cls._cache[relation_name] = relation_class
return relation_class(relation_name, conversations)
return None | [
"def",
"from_name",
"(",
"cls",
",",
"relation_name",
",",
"conversations",
"=",
"None",
")",
":",
"if",
"relation_name",
"is",
"None",
":",
"return",
"None",
"relation_class",
"=",
"cls",
".",
"_cache",
".",
"get",
"(",
"relation_name",
")",
"if",
"relati... | Find relation implementation in the current charm, based on the
name of the relation.
:return: A Relation instance, or None | [
"Find",
"relation",
"implementation",
"in",
"the",
"current",
"charm",
"based",
"on",
"the",
"name",
"of",
"the",
"relation",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L357-L375 | train | 40,783 |
juju-solutions/charms.reactive | charms/reactive/relations.py | RelationBase._find_impl | def _find_impl(cls, role, interface):
"""
Find relation implementation based on its role and interface.
"""
module = _relation_module(role, interface)
if not module:
return None
return cls._find_subclass(module) | python | def _find_impl(cls, role, interface):
"""
Find relation implementation based on its role and interface.
"""
module = _relation_module(role, interface)
if not module:
return None
return cls._find_subclass(module) | [
"def",
"_find_impl",
"(",
"cls",
",",
"role",
",",
"interface",
")",
":",
"module",
"=",
"_relation_module",
"(",
"role",
",",
"interface",
")",
"if",
"not",
"module",
":",
"return",
"None",
"return",
"cls",
".",
"_find_subclass",
"(",
"module",
")"
] | Find relation implementation based on its role and interface. | [
"Find",
"relation",
"implementation",
"based",
"on",
"its",
"role",
"and",
"interface",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L378-L385 | train | 40,784 |
juju-solutions/charms.reactive | charms/reactive/relations.py | RelationBase.conversation | def conversation(self, scope=None):
"""
Get a single conversation, by scope, that this relation is currently handling.
If the scope is not given, the correct scope is inferred by the current
hook execution context. If there is no current hook execution context, it
is assume that there is only a single global conversation scope for this
relation. If this relation's scope is not global and there is no current
hook execution context, then an error is raised.
"""
if scope is None:
if self.scope is scopes.UNIT:
scope = hookenv.remote_unit()
elif self.scope is scopes.SERVICE:
scope = hookenv.remote_service_name()
else:
scope = self.scope
if scope is None:
raise ValueError('Unable to determine default scope: no current hook or global scope')
for conversation in self._conversations:
if conversation.scope == scope:
return conversation
else:
raise ValueError("Conversation with scope '%s' not found" % scope) | python | def conversation(self, scope=None):
"""
Get a single conversation, by scope, that this relation is currently handling.
If the scope is not given, the correct scope is inferred by the current
hook execution context. If there is no current hook execution context, it
is assume that there is only a single global conversation scope for this
relation. If this relation's scope is not global and there is no current
hook execution context, then an error is raised.
"""
if scope is None:
if self.scope is scopes.UNIT:
scope = hookenv.remote_unit()
elif self.scope is scopes.SERVICE:
scope = hookenv.remote_service_name()
else:
scope = self.scope
if scope is None:
raise ValueError('Unable to determine default scope: no current hook or global scope')
for conversation in self._conversations:
if conversation.scope == scope:
return conversation
else:
raise ValueError("Conversation with scope '%s' not found" % scope) | [
"def",
"conversation",
"(",
"self",
",",
"scope",
"=",
"None",
")",
":",
"if",
"scope",
"is",
"None",
":",
"if",
"self",
".",
"scope",
"is",
"scopes",
".",
"UNIT",
":",
"scope",
"=",
"hookenv",
".",
"remote_unit",
"(",
")",
"elif",
"self",
".",
"sc... | Get a single conversation, by scope, that this relation is currently handling.
If the scope is not given, the correct scope is inferred by the current
hook execution context. If there is no current hook execution context, it
is assume that there is only a single global conversation scope for this
relation. If this relation's scope is not global and there is no current
hook execution context, then an error is raised. | [
"Get",
"a",
"single",
"conversation",
"by",
"scope",
"that",
"this",
"relation",
"is",
"currently",
"handling",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L413-L436 | train | 40,785 |
juju-solutions/charms.reactive | charms/reactive/relations.py | Conversation.relation_ids | def relation_ids(self):
"""
The set of IDs of the specific relation instances that this conversation
is communicating with.
"""
if self.scope == scopes.GLOBAL:
# the namespace is the relation name and this conv speaks for all
# connected instances of that relation
return hookenv.relation_ids(self.namespace)
else:
# the namespace is the relation ID
return [self.namespace] | python | def relation_ids(self):
"""
The set of IDs of the specific relation instances that this conversation
is communicating with.
"""
if self.scope == scopes.GLOBAL:
# the namespace is the relation name and this conv speaks for all
# connected instances of that relation
return hookenv.relation_ids(self.namespace)
else:
# the namespace is the relation ID
return [self.namespace] | [
"def",
"relation_ids",
"(",
"self",
")",
":",
"if",
"self",
".",
"scope",
"==",
"scopes",
".",
"GLOBAL",
":",
"# the namespace is the relation name and this conv speaks for all",
"# connected instances of that relation",
"return",
"hookenv",
".",
"relation_ids",
"(",
"sel... | The set of IDs of the specific relation instances that this conversation
is communicating with. | [
"The",
"set",
"of",
"IDs",
"of",
"the",
"specific",
"relation",
"instances",
"that",
"this",
"conversation",
"is",
"communicating",
"with",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L577-L588 | train | 40,786 |
juju-solutions/charms.reactive | charms/reactive/relations.py | Conversation.join | def join(cls, scope):
"""
Get or create a conversation for the given scope and active hook context.
The current remote unit for the active hook context will be added to
the conversation.
Note: This uses :mod:`charmhelpers.core.unitdata` and requires that
:meth:`~charmhelpers.core.unitdata.Storage.flush` be called.
"""
relation_name = hookenv.relation_type()
relation_id = hookenv.relation_id()
unit = hookenv.remote_unit()
service = hookenv.remote_service_name()
if scope is scopes.UNIT:
scope = unit
namespace = relation_id
elif scope is scopes.SERVICE:
scope = service
namespace = relation_id
else:
namespace = relation_name
key = cls._key(namespace, scope)
data = unitdata.kv().get(key, {'namespace': namespace, 'scope': scope, 'units': []})
conversation = cls.deserialize(data)
conversation.units.add(unit)
unitdata.kv().set(key, cls.serialize(conversation))
return conversation | python | def join(cls, scope):
"""
Get or create a conversation for the given scope and active hook context.
The current remote unit for the active hook context will be added to
the conversation.
Note: This uses :mod:`charmhelpers.core.unitdata` and requires that
:meth:`~charmhelpers.core.unitdata.Storage.flush` be called.
"""
relation_name = hookenv.relation_type()
relation_id = hookenv.relation_id()
unit = hookenv.remote_unit()
service = hookenv.remote_service_name()
if scope is scopes.UNIT:
scope = unit
namespace = relation_id
elif scope is scopes.SERVICE:
scope = service
namespace = relation_id
else:
namespace = relation_name
key = cls._key(namespace, scope)
data = unitdata.kv().get(key, {'namespace': namespace, 'scope': scope, 'units': []})
conversation = cls.deserialize(data)
conversation.units.add(unit)
unitdata.kv().set(key, cls.serialize(conversation))
return conversation | [
"def",
"join",
"(",
"cls",
",",
"scope",
")",
":",
"relation_name",
"=",
"hookenv",
".",
"relation_type",
"(",
")",
"relation_id",
"=",
"hookenv",
".",
"relation_id",
"(",
")",
"unit",
"=",
"hookenv",
".",
"remote_unit",
"(",
")",
"service",
"=",
"hooken... | Get or create a conversation for the given scope and active hook context.
The current remote unit for the active hook context will be added to
the conversation.
Note: This uses :mod:`charmhelpers.core.unitdata` and requires that
:meth:`~charmhelpers.core.unitdata.Storage.flush` be called. | [
"Get",
"or",
"create",
"a",
"conversation",
"for",
"the",
"given",
"scope",
"and",
"active",
"hook",
"context",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L591-L618 | train | 40,787 |
juju-solutions/charms.reactive | charms/reactive/relations.py | Conversation.depart | def depart(self):
"""
Remove the current remote unit, for the active hook context, from
this conversation. This should be called from a `-departed` hook.
"""
unit = hookenv.remote_unit()
self.units.remove(unit)
if self.units:
unitdata.kv().set(self.key, self.serialize(self))
else:
unitdata.kv().unset(self.key) | python | def depart(self):
"""
Remove the current remote unit, for the active hook context, from
this conversation. This should be called from a `-departed` hook.
"""
unit = hookenv.remote_unit()
self.units.remove(unit)
if self.units:
unitdata.kv().set(self.key, self.serialize(self))
else:
unitdata.kv().unset(self.key) | [
"def",
"depart",
"(",
"self",
")",
":",
"unit",
"=",
"hookenv",
".",
"remote_unit",
"(",
")",
"self",
".",
"units",
".",
"remove",
"(",
"unit",
")",
"if",
"self",
".",
"units",
":",
"unitdata",
".",
"kv",
"(",
")",
".",
"set",
"(",
"self",
".",
... | Remove the current remote unit, for the active hook context, from
this conversation. This should be called from a `-departed` hook. | [
"Remove",
"the",
"current",
"remote",
"unit",
"for",
"the",
"active",
"hook",
"context",
"from",
"this",
"conversation",
".",
"This",
"should",
"be",
"called",
"from",
"a",
"-",
"departed",
"hook",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L620-L630 | train | 40,788 |
juju-solutions/charms.reactive | charms/reactive/relations.py | Conversation.serialize | def serialize(cls, conversation):
"""
Serialize a conversation instance for storage.
"""
return {
'namespace': conversation.namespace,
'units': sorted(conversation.units),
'scope': conversation.scope,
} | python | def serialize(cls, conversation):
"""
Serialize a conversation instance for storage.
"""
return {
'namespace': conversation.namespace,
'units': sorted(conversation.units),
'scope': conversation.scope,
} | [
"def",
"serialize",
"(",
"cls",
",",
"conversation",
")",
":",
"return",
"{",
"'namespace'",
":",
"conversation",
".",
"namespace",
",",
"'units'",
":",
"sorted",
"(",
"conversation",
".",
"units",
")",
",",
"'scope'",
":",
"conversation",
".",
"scope",
",... | Serialize a conversation instance for storage. | [
"Serialize",
"a",
"conversation",
"instance",
"for",
"storage",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L640-L648 | train | 40,789 |
juju-solutions/charms.reactive | charms/reactive/relations.py | Conversation.load | def load(cls, keys):
"""
Load a set of conversations by their keys.
"""
conversations = []
for key in keys:
conversation = unitdata.kv().get(key)
if conversation:
conversations.append(cls.deserialize(conversation))
return conversations | python | def load(cls, keys):
"""
Load a set of conversations by their keys.
"""
conversations = []
for key in keys:
conversation = unitdata.kv().get(key)
if conversation:
conversations.append(cls.deserialize(conversation))
return conversations | [
"def",
"load",
"(",
"cls",
",",
"keys",
")",
":",
"conversations",
"=",
"[",
"]",
"for",
"key",
"in",
"keys",
":",
"conversation",
"=",
"unitdata",
".",
"kv",
"(",
")",
".",
"get",
"(",
"key",
")",
"if",
"conversation",
":",
"conversations",
".",
"... | Load a set of conversations by their keys. | [
"Load",
"a",
"set",
"of",
"conversations",
"by",
"their",
"keys",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L651-L660 | train | 40,790 |
juju-solutions/charms.reactive | charms/reactive/relations.py | Conversation.set_state | def set_state(self, state):
"""
Activate and put this conversation into the given state.
The relation name will be interpolated in the state name, and it is
recommended that it be included to avoid conflicts with states from
other relations. For example::
conversation.set_state('{relation_name}.state')
If called from a converation handling the relation "foo", this will
activate the "foo.state" state, and will add this conversation to
that state.
Note: This uses :mod:`charmhelpers.core.unitdata` and requires that
:meth:`~charmhelpers.core.unitdata.Storage.flush` be called.
"""
state = state.format(relation_name=self.relation_name)
value = _get_flag_value(state, {
'relation': self.relation_name,
'conversations': [],
})
if self.key not in value['conversations']:
value['conversations'].append(self.key)
set_flag(state, value) | python | def set_state(self, state):
"""
Activate and put this conversation into the given state.
The relation name will be interpolated in the state name, and it is
recommended that it be included to avoid conflicts with states from
other relations. For example::
conversation.set_state('{relation_name}.state')
If called from a converation handling the relation "foo", this will
activate the "foo.state" state, and will add this conversation to
that state.
Note: This uses :mod:`charmhelpers.core.unitdata` and requires that
:meth:`~charmhelpers.core.unitdata.Storage.flush` be called.
"""
state = state.format(relation_name=self.relation_name)
value = _get_flag_value(state, {
'relation': self.relation_name,
'conversations': [],
})
if self.key not in value['conversations']:
value['conversations'].append(self.key)
set_flag(state, value) | [
"def",
"set_state",
"(",
"self",
",",
"state",
")",
":",
"state",
"=",
"state",
".",
"format",
"(",
"relation_name",
"=",
"self",
".",
"relation_name",
")",
"value",
"=",
"_get_flag_value",
"(",
"state",
",",
"{",
"'relation'",
":",
"self",
".",
"relatio... | Activate and put this conversation into the given state.
The relation name will be interpolated in the state name, and it is
recommended that it be included to avoid conflicts with states from
other relations. For example::
conversation.set_state('{relation_name}.state')
If called from a converation handling the relation "foo", this will
activate the "foo.state" state, and will add this conversation to
that state.
Note: This uses :mod:`charmhelpers.core.unitdata` and requires that
:meth:`~charmhelpers.core.unitdata.Storage.flush` be called. | [
"Activate",
"and",
"put",
"this",
"conversation",
"into",
"the",
"given",
"state",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L662-L686 | train | 40,791 |
juju-solutions/charms.reactive | charms/reactive/relations.py | Conversation.remove_state | def remove_state(self, state):
"""
Remove this conversation from the given state, and potentially
deactivate the state if no more conversations are in it.
The relation name will be interpolated in the state name, and it is
recommended that it be included to avoid conflicts with states from
other relations. For example::
conversation.remove_state('{relation_name}.state')
If called from a converation handling the relation "foo", this will
remove the conversation from the "foo.state" state, and, if no more
conversations are in this the state, will deactivate it.
"""
state = state.format(relation_name=self.relation_name)
value = _get_flag_value(state)
if not value:
return
if self.key in value['conversations']:
value['conversations'].remove(self.key)
if value['conversations']:
set_flag(state, value)
else:
clear_flag(state) | python | def remove_state(self, state):
"""
Remove this conversation from the given state, and potentially
deactivate the state if no more conversations are in it.
The relation name will be interpolated in the state name, and it is
recommended that it be included to avoid conflicts with states from
other relations. For example::
conversation.remove_state('{relation_name}.state')
If called from a converation handling the relation "foo", this will
remove the conversation from the "foo.state" state, and, if no more
conversations are in this the state, will deactivate it.
"""
state = state.format(relation_name=self.relation_name)
value = _get_flag_value(state)
if not value:
return
if self.key in value['conversations']:
value['conversations'].remove(self.key)
if value['conversations']:
set_flag(state, value)
else:
clear_flag(state) | [
"def",
"remove_state",
"(",
"self",
",",
"state",
")",
":",
"state",
"=",
"state",
".",
"format",
"(",
"relation_name",
"=",
"self",
".",
"relation_name",
")",
"value",
"=",
"_get_flag_value",
"(",
"state",
")",
"if",
"not",
"value",
":",
"return",
"if",... | Remove this conversation from the given state, and potentially
deactivate the state if no more conversations are in it.
The relation name will be interpolated in the state name, and it is
recommended that it be included to avoid conflicts with states from
other relations. For example::
conversation.remove_state('{relation_name}.state')
If called from a converation handling the relation "foo", this will
remove the conversation from the "foo.state" state, and, if no more
conversations are in this the state, will deactivate it. | [
"Remove",
"this",
"conversation",
"from",
"the",
"given",
"state",
"and",
"potentially",
"deactivate",
"the",
"state",
"if",
"no",
"more",
"conversations",
"are",
"in",
"it",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L688-L712 | train | 40,792 |
juju-solutions/charms.reactive | charms/reactive/relations.py | Conversation.is_state | def is_state(self, state):
"""
Test if this conversation is in the given state.
"""
state = state.format(relation_name=self.relation_name)
value = _get_flag_value(state)
if not value:
return False
return self.key in value['conversations'] | python | def is_state(self, state):
"""
Test if this conversation is in the given state.
"""
state = state.format(relation_name=self.relation_name)
value = _get_flag_value(state)
if not value:
return False
return self.key in value['conversations'] | [
"def",
"is_state",
"(",
"self",
",",
"state",
")",
":",
"state",
"=",
"state",
".",
"format",
"(",
"relation_name",
"=",
"self",
".",
"relation_name",
")",
"value",
"=",
"_get_flag_value",
"(",
"state",
")",
"if",
"not",
"value",
":",
"return",
"False",
... | Test if this conversation is in the given state. | [
"Test",
"if",
"this",
"conversation",
"is",
"in",
"the",
"given",
"state",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L714-L722 | train | 40,793 |
juju-solutions/charms.reactive | charms/reactive/relations.py | Conversation.toggle_state | def toggle_state(self, state, active=TOGGLE):
"""
Toggle the given state for this conversation.
The state will be set ``active`` is ``True``, otherwise the state will be removed.
If ``active`` is not given, it will default to the inverse of the current state
(i.e., ``False`` if the state is currently set, ``True`` if it is not; essentially
toggling the state).
For example::
conv.toggle_state('{relation_name}.foo', value=='foo')
This will set the state if ``value`` is equal to ``foo``.
"""
if active is TOGGLE:
active = not self.is_state(state)
if active:
self.set_state(state)
else:
self.remove_state(state) | python | def toggle_state(self, state, active=TOGGLE):
"""
Toggle the given state for this conversation.
The state will be set ``active`` is ``True``, otherwise the state will be removed.
If ``active`` is not given, it will default to the inverse of the current state
(i.e., ``False`` if the state is currently set, ``True`` if it is not; essentially
toggling the state).
For example::
conv.toggle_state('{relation_name}.foo', value=='foo')
This will set the state if ``value`` is equal to ``foo``.
"""
if active is TOGGLE:
active = not self.is_state(state)
if active:
self.set_state(state)
else:
self.remove_state(state) | [
"def",
"toggle_state",
"(",
"self",
",",
"state",
",",
"active",
"=",
"TOGGLE",
")",
":",
"if",
"active",
"is",
"TOGGLE",
":",
"active",
"=",
"not",
"self",
".",
"is_state",
"(",
"state",
")",
"if",
"active",
":",
"self",
".",
"set_state",
"(",
"stat... | Toggle the given state for this conversation.
The state will be set ``active`` is ``True``, otherwise the state will be removed.
If ``active`` is not given, it will default to the inverse of the current state
(i.e., ``False`` if the state is currently set, ``True`` if it is not; essentially
toggling the state).
For example::
conv.toggle_state('{relation_name}.foo', value=='foo')
This will set the state if ``value`` is equal to ``foo``. | [
"Toggle",
"the",
"given",
"state",
"for",
"this",
"conversation",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L724-L745 | train | 40,794 |
juju-solutions/charms.reactive | charms/reactive/relations.py | Conversation.set_local | def set_local(self, key=None, value=None, data=None, **kwdata):
"""
Locally store some data associated with this conversation.
Data can be passed in either as a single dict, or as key-word args.
For example, if you need to store the previous value of a remote field
to determine if it has changed, you can use the following::
prev = conversation.get_local('field')
curr = conversation.get_remote('field')
if prev != curr:
handle_change(prev, curr)
conversation.set_local('field', curr)
Note: This uses :mod:`charmhelpers.core.unitdata` and requires that
:meth:`~charmhelpers.core.unitdata.Storage.flush` be called.
:param str key: The name of a field to set.
:param value: A value to set. This value must be json serializable.
:param dict data: A mapping of keys to values.
:param **kwdata: A mapping of keys to values, as keyword arguments.
"""
if data is None:
data = {}
if key is not None:
data[key] = value
data.update(kwdata)
if not data:
return
unitdata.kv().update(data, prefix='%s.%s.' % (self.key, 'local-data')) | python | def set_local(self, key=None, value=None, data=None, **kwdata):
"""
Locally store some data associated with this conversation.
Data can be passed in either as a single dict, or as key-word args.
For example, if you need to store the previous value of a remote field
to determine if it has changed, you can use the following::
prev = conversation.get_local('field')
curr = conversation.get_remote('field')
if prev != curr:
handle_change(prev, curr)
conversation.set_local('field', curr)
Note: This uses :mod:`charmhelpers.core.unitdata` and requires that
:meth:`~charmhelpers.core.unitdata.Storage.flush` be called.
:param str key: The name of a field to set.
:param value: A value to set. This value must be json serializable.
:param dict data: A mapping of keys to values.
:param **kwdata: A mapping of keys to values, as keyword arguments.
"""
if data is None:
data = {}
if key is not None:
data[key] = value
data.update(kwdata)
if not data:
return
unitdata.kv().update(data, prefix='%s.%s.' % (self.key, 'local-data')) | [
"def",
"set_local",
"(",
"self",
",",
"key",
"=",
"None",
",",
"value",
"=",
"None",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwdata",
")",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"if",
"key",
"is",
"not",
"None",
":",
"... | Locally store some data associated with this conversation.
Data can be passed in either as a single dict, or as key-word args.
For example, if you need to store the previous value of a remote field
to determine if it has changed, you can use the following::
prev = conversation.get_local('field')
curr = conversation.get_remote('field')
if prev != curr:
handle_change(prev, curr)
conversation.set_local('field', curr)
Note: This uses :mod:`charmhelpers.core.unitdata` and requires that
:meth:`~charmhelpers.core.unitdata.Storage.flush` be called.
:param str key: The name of a field to set.
:param value: A value to set. This value must be json serializable.
:param dict data: A mapping of keys to values.
:param **kwdata: A mapping of keys to values, as keyword arguments. | [
"Locally",
"store",
"some",
"data",
"associated",
"with",
"this",
"conversation",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/relations.py#L802-L832 | train | 40,795 |
juju-solutions/charms.reactive | charms/reactive/flags.py | register_trigger | def register_trigger(when=None, when_not=None, set_flag=None, clear_flag=None):
"""
Register a trigger to set or clear a flag when a given flag is set.
Note: Flag triggers are handled at the same time that the given flag is set.
:param str when: Flag to trigger on when it is set.
:param str when_not: Flag to trigger on when it is cleared.
:param str set_flag: If given, this flag will be set when `when` is set.
:param str clear_flag: If given, this flag will be cleared when `when` is set.
Note: Exactly one of either `when` or `when_not`, and at least one of
`set_flag` or `clear_flag` must be provided.
"""
if not any((when, when_not)):
raise ValueError('Must provide one of when or when_not')
if all((when, when_not)):
raise ValueError('Only one of when or when_not can be provided')
if not any((set_flag, clear_flag)):
raise ValueError('Must provide at least one of set_flag or clear_flag')
trigger = _get_trigger(when, when_not)
if set_flag and set_flag not in trigger['set_flag']:
trigger['set_flag'].append(set_flag)
if clear_flag and clear_flag not in trigger['clear_flag']:
trigger['clear_flag'].append(clear_flag)
_save_trigger(when, when_not, trigger) | python | def register_trigger(when=None, when_not=None, set_flag=None, clear_flag=None):
"""
Register a trigger to set or clear a flag when a given flag is set.
Note: Flag triggers are handled at the same time that the given flag is set.
:param str when: Flag to trigger on when it is set.
:param str when_not: Flag to trigger on when it is cleared.
:param str set_flag: If given, this flag will be set when `when` is set.
:param str clear_flag: If given, this flag will be cleared when `when` is set.
Note: Exactly one of either `when` or `when_not`, and at least one of
`set_flag` or `clear_flag` must be provided.
"""
if not any((when, when_not)):
raise ValueError('Must provide one of when or when_not')
if all((when, when_not)):
raise ValueError('Only one of when or when_not can be provided')
if not any((set_flag, clear_flag)):
raise ValueError('Must provide at least one of set_flag or clear_flag')
trigger = _get_trigger(when, when_not)
if set_flag and set_flag not in trigger['set_flag']:
trigger['set_flag'].append(set_flag)
if clear_flag and clear_flag not in trigger['clear_flag']:
trigger['clear_flag'].append(clear_flag)
_save_trigger(when, when_not, trigger) | [
"def",
"register_trigger",
"(",
"when",
"=",
"None",
",",
"when_not",
"=",
"None",
",",
"set_flag",
"=",
"None",
",",
"clear_flag",
"=",
"None",
")",
":",
"if",
"not",
"any",
"(",
"(",
"when",
",",
"when_not",
")",
")",
":",
"raise",
"ValueError",
"(... | Register a trigger to set or clear a flag when a given flag is set.
Note: Flag triggers are handled at the same time that the given flag is set.
:param str when: Flag to trigger on when it is set.
:param str when_not: Flag to trigger on when it is cleared.
:param str set_flag: If given, this flag will be set when `when` is set.
:param str clear_flag: If given, this flag will be cleared when `when` is set.
Note: Exactly one of either `when` or `when_not`, and at least one of
`set_flag` or `clear_flag` must be provided. | [
"Register",
"a",
"trigger",
"to",
"set",
"or",
"clear",
"a",
"flag",
"when",
"a",
"given",
"flag",
"is",
"set",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/flags.py#L144-L169 | train | 40,796 |
juju-solutions/charms.reactive | charms/reactive/flags.py | get_flags | def get_flags():
"""
Return a list of all flags which are set.
"""
flags = unitdata.kv().getrange('reactive.states.', strip=True) or {}
return sorted(flags.keys()) | python | def get_flags():
"""
Return a list of all flags which are set.
"""
flags = unitdata.kv().getrange('reactive.states.', strip=True) or {}
return sorted(flags.keys()) | [
"def",
"get_flags",
"(",
")",
":",
"flags",
"=",
"unitdata",
".",
"kv",
"(",
")",
".",
"getrange",
"(",
"'reactive.states.'",
",",
"strip",
"=",
"True",
")",
"or",
"{",
"}",
"return",
"sorted",
"(",
"flags",
".",
"keys",
"(",
")",
")"
] | Return a list of all flags which are set. | [
"Return",
"a",
"list",
"of",
"all",
"flags",
"which",
"are",
"set",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/flags.py#L215-L220 | train | 40,797 |
juju-solutions/charms.reactive | charms/reactive/bus.py | dispatch | def dispatch(restricted=False):
"""
Dispatch registered handlers.
When dispatching in restricted mode, only matching hook handlers are executed.
Handlers are dispatched according to the following rules:
* Handlers are repeatedly tested and invoked in iterations, until the system
settles into quiescence (that is, until no new handlers match to be invoked).
* In the first iteration, :func:`@hook <charms.reactive.decorators.hook>`
and :func:`@action <charms.reactive.decorators.action>` handlers will
be invoked, if they match.
* In subsequent iterations, other handlers are invoked, if they match.
* Added flags will not trigger new handlers until the next iteration,
to ensure that chained flags are invoked in a predictable order.
* Removed flags will cause the current set of matched handlers to be
re-tested, to ensure that no handler is invoked after its matching
flag has been removed.
* Other than the guarantees mentioned above, the order in which matching
handlers are invoked is undefined.
* Flags are preserved between hook and action invocations, and all matching
handlers are re-invoked for every hook and action. There are
:doc:`decorators <charms.reactive.decorators>` and
:doc:`helpers <charms.reactive.helpers>`
to prevent unnecessary reinvocations, such as
:func:`~charms.reactive.decorators.only_once`.
"""
FlagWatch.reset()
def _test(to_test):
return list(filter(lambda h: h.test(), to_test))
def _invoke(to_invoke):
while to_invoke:
unitdata.kv().set('reactive.dispatch.removed_state', False)
for handler in list(to_invoke):
to_invoke.remove(handler)
hookenv.log('Invoking reactive handler: %s' % handler.id(), level=hookenv.INFO)
handler.invoke()
if unitdata.kv().get('reactive.dispatch.removed_state'):
# re-test remaining handlers
to_invoke = _test(to_invoke)
break
FlagWatch.commit()
tracer().start_dispatch()
# When in restricted context, only run hooks for that context.
if restricted:
unitdata.kv().set('reactive.dispatch.phase', 'restricted')
hook_handlers = _test(Handler.get_handlers())
tracer().start_dispatch_phase('restricted', hook_handlers)
_invoke(hook_handlers)
return
unitdata.kv().set('reactive.dispatch.phase', 'hooks')
hook_handlers = _test(Handler.get_handlers())
tracer().start_dispatch_phase('hooks', hook_handlers)
_invoke(hook_handlers)
unitdata.kv().set('reactive.dispatch.phase', 'other')
for i in range(100):
FlagWatch.iteration(i)
other_handlers = _test(Handler.get_handlers())
if i == 0:
tracer().start_dispatch_phase('other', other_handlers)
tracer().start_dispatch_iteration(i, other_handlers)
if not other_handlers:
break
_invoke(other_handlers)
FlagWatch.reset() | python | def dispatch(restricted=False):
"""
Dispatch registered handlers.
When dispatching in restricted mode, only matching hook handlers are executed.
Handlers are dispatched according to the following rules:
* Handlers are repeatedly tested and invoked in iterations, until the system
settles into quiescence (that is, until no new handlers match to be invoked).
* In the first iteration, :func:`@hook <charms.reactive.decorators.hook>`
and :func:`@action <charms.reactive.decorators.action>` handlers will
be invoked, if they match.
* In subsequent iterations, other handlers are invoked, if they match.
* Added flags will not trigger new handlers until the next iteration,
to ensure that chained flags are invoked in a predictable order.
* Removed flags will cause the current set of matched handlers to be
re-tested, to ensure that no handler is invoked after its matching
flag has been removed.
* Other than the guarantees mentioned above, the order in which matching
handlers are invoked is undefined.
* Flags are preserved between hook and action invocations, and all matching
handlers are re-invoked for every hook and action. There are
:doc:`decorators <charms.reactive.decorators>` and
:doc:`helpers <charms.reactive.helpers>`
to prevent unnecessary reinvocations, such as
:func:`~charms.reactive.decorators.only_once`.
"""
FlagWatch.reset()
def _test(to_test):
return list(filter(lambda h: h.test(), to_test))
def _invoke(to_invoke):
while to_invoke:
unitdata.kv().set('reactive.dispatch.removed_state', False)
for handler in list(to_invoke):
to_invoke.remove(handler)
hookenv.log('Invoking reactive handler: %s' % handler.id(), level=hookenv.INFO)
handler.invoke()
if unitdata.kv().get('reactive.dispatch.removed_state'):
# re-test remaining handlers
to_invoke = _test(to_invoke)
break
FlagWatch.commit()
tracer().start_dispatch()
# When in restricted context, only run hooks for that context.
if restricted:
unitdata.kv().set('reactive.dispatch.phase', 'restricted')
hook_handlers = _test(Handler.get_handlers())
tracer().start_dispatch_phase('restricted', hook_handlers)
_invoke(hook_handlers)
return
unitdata.kv().set('reactive.dispatch.phase', 'hooks')
hook_handlers = _test(Handler.get_handlers())
tracer().start_dispatch_phase('hooks', hook_handlers)
_invoke(hook_handlers)
unitdata.kv().set('reactive.dispatch.phase', 'other')
for i in range(100):
FlagWatch.iteration(i)
other_handlers = _test(Handler.get_handlers())
if i == 0:
tracer().start_dispatch_phase('other', other_handlers)
tracer().start_dispatch_iteration(i, other_handlers)
if not other_handlers:
break
_invoke(other_handlers)
FlagWatch.reset() | [
"def",
"dispatch",
"(",
"restricted",
"=",
"False",
")",
":",
"FlagWatch",
".",
"reset",
"(",
")",
"def",
"_test",
"(",
"to_test",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"h",
":",
"h",
".",
"test",
"(",
")",
",",
"to_test",
")",
... | Dispatch registered handlers.
When dispatching in restricted mode, only matching hook handlers are executed.
Handlers are dispatched according to the following rules:
* Handlers are repeatedly tested and invoked in iterations, until the system
settles into quiescence (that is, until no new handlers match to be invoked).
* In the first iteration, :func:`@hook <charms.reactive.decorators.hook>`
and :func:`@action <charms.reactive.decorators.action>` handlers will
be invoked, if they match.
* In subsequent iterations, other handlers are invoked, if they match.
* Added flags will not trigger new handlers until the next iteration,
to ensure that chained flags are invoked in a predictable order.
* Removed flags will cause the current set of matched handlers to be
re-tested, to ensure that no handler is invoked after its matching
flag has been removed.
* Other than the guarantees mentioned above, the order in which matching
handlers are invoked is undefined.
* Flags are preserved between hook and action invocations, and all matching
handlers are re-invoked for every hook and action. There are
:doc:`decorators <charms.reactive.decorators>` and
:doc:`helpers <charms.reactive.helpers>`
to prevent unnecessary reinvocations, such as
:func:`~charms.reactive.decorators.only_once`. | [
"Dispatch",
"registered",
"handlers",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/bus.py#L314-L392 | train | 40,798 |
juju-solutions/charms.reactive | charms/reactive/bus.py | discover | def discover():
"""
Discover handlers based on convention.
Handlers will be loaded from the following directories and their subdirectories:
* ``$CHARM_DIR/reactive/``
* ``$CHARM_DIR/hooks/reactive/``
* ``$CHARM_DIR/hooks/relations/``
They can be Python files, in which case they will be imported and decorated
functions registered. Or they can be executables, in which case they must
adhere to the :class:`ExternalHandler` protocol.
"""
# Add $CHARM_DIR and $CHARM_DIR/hooks to sys.path so
# 'import reactive.leadership', 'import relations.pgsql' works
# as expected, as well as relative imports like 'import ..leadership'
# or 'from . import leadership'. Without this, it becomes difficult
# for layers to access APIs provided by other layers. This addition
# needs to remain in effect, in case discovered modules are doing
# late imports.
_append_path(hookenv.charm_dir())
_append_path(os.path.join(hookenv.charm_dir(), 'hooks'))
for search_dir in ('reactive', 'hooks/reactive', 'hooks/relations'):
search_path = os.path.join(hookenv.charm_dir(), search_dir)
for dirpath, dirnames, filenames in os.walk(search_path):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
_register_handlers_from_file(search_path, filepath) | python | def discover():
"""
Discover handlers based on convention.
Handlers will be loaded from the following directories and their subdirectories:
* ``$CHARM_DIR/reactive/``
* ``$CHARM_DIR/hooks/reactive/``
* ``$CHARM_DIR/hooks/relations/``
They can be Python files, in which case they will be imported and decorated
functions registered. Or they can be executables, in which case they must
adhere to the :class:`ExternalHandler` protocol.
"""
# Add $CHARM_DIR and $CHARM_DIR/hooks to sys.path so
# 'import reactive.leadership', 'import relations.pgsql' works
# as expected, as well as relative imports like 'import ..leadership'
# or 'from . import leadership'. Without this, it becomes difficult
# for layers to access APIs provided by other layers. This addition
# needs to remain in effect, in case discovered modules are doing
# late imports.
_append_path(hookenv.charm_dir())
_append_path(os.path.join(hookenv.charm_dir(), 'hooks'))
for search_dir in ('reactive', 'hooks/reactive', 'hooks/relations'):
search_path = os.path.join(hookenv.charm_dir(), search_dir)
for dirpath, dirnames, filenames in os.walk(search_path):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
_register_handlers_from_file(search_path, filepath) | [
"def",
"discover",
"(",
")",
":",
"# Add $CHARM_DIR and $CHARM_DIR/hooks to sys.path so",
"# 'import reactive.leadership', 'import relations.pgsql' works",
"# as expected, as well as relative imports like 'import ..leadership'",
"# or 'from . import leadership'. Without this, it becomes difficult",
... | Discover handlers based on convention.
Handlers will be loaded from the following directories and their subdirectories:
* ``$CHARM_DIR/reactive/``
* ``$CHARM_DIR/hooks/reactive/``
* ``$CHARM_DIR/hooks/relations/``
They can be Python files, in which case they will be imported and decorated
functions registered. Or they can be executables, in which case they must
adhere to the :class:`ExternalHandler` protocol. | [
"Discover",
"handlers",
"based",
"on",
"convention",
"."
] | e37e781432e77c12b63d2c739bd6cd70d3230c3a | https://github.com/juju-solutions/charms.reactive/blob/e37e781432e77c12b63d2c739bd6cd70d3230c3a/charms/reactive/bus.py#L395-L424 | train | 40,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.