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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
AASHE/python-membersuite-api-client
membersuite_api_client/organizations/services.py
OrganizationService.get_individuals_for_primary_organization
def get_individuals_for_primary_organization(self, organization): """ Returns all Individuals that have `organization` as a primary org. """ if not self.client.session_id: self.client.request_session() object_query = ("SELECT Objects() FROM Individual WHERE " "PrimaryOrganization = '{}'".format( organization.membersuite_account_num)) result = self.client.execute_object_query(object_query) msql_result = result["body"]["ExecuteMSQLResult"] if msql_result["Success"]: membersuite_objects = (msql_result["ResultValue"] ["ObjectSearchResult"] ["Objects"]) else: raise ExecuteMSQLError(result=result) individuals = [] if membersuite_objects is not None: for membersuite_object in membersuite_objects["MemberSuiteObject"]: individuals.append( Individual(membersuite_object_data=membersuite_object)) return individuals
python
def get_individuals_for_primary_organization(self, organization): """ Returns all Individuals that have `organization` as a primary org. """ if not self.client.session_id: self.client.request_session() object_query = ("SELECT Objects() FROM Individual WHERE " "PrimaryOrganization = '{}'".format( organization.membersuite_account_num)) result = self.client.execute_object_query(object_query) msql_result = result["body"]["ExecuteMSQLResult"] if msql_result["Success"]: membersuite_objects = (msql_result["ResultValue"] ["ObjectSearchResult"] ["Objects"]) else: raise ExecuteMSQLError(result=result) individuals = [] if membersuite_objects is not None: for membersuite_object in membersuite_objects["MemberSuiteObject"]: individuals.append( Individual(membersuite_object_data=membersuite_object)) return individuals
[ "def", "get_individuals_for_primary_organization", "(", "self", ",", "organization", ")", ":", "if", "not", "self", ".", "client", ".", "session_id", ":", "self", ".", "client", ".", "request_session", "(", ")", "object_query", "=", "(", "\"SELECT Objects() FROM Individual WHERE \"", "\"PrimaryOrganization = '{}'\"", ".", "format", "(", "organization", ".", "membersuite_account_num", ")", ")", "result", "=", "self", ".", "client", ".", "execute_object_query", "(", "object_query", ")", "msql_result", "=", "result", "[", "\"body\"", "]", "[", "\"ExecuteMSQLResult\"", "]", "if", "msql_result", "[", "\"Success\"", "]", ":", "membersuite_objects", "=", "(", "msql_result", "[", "\"ResultValue\"", "]", "[", "\"ObjectSearchResult\"", "]", "[", "\"Objects\"", "]", ")", "else", ":", "raise", "ExecuteMSQLError", "(", "result", "=", "result", ")", "individuals", "=", "[", "]", "if", "membersuite_objects", "is", "not", "None", ":", "for", "membersuite_object", "in", "membersuite_objects", "[", "\"MemberSuiteObject\"", "]", ":", "individuals", ".", "append", "(", "Individual", "(", "membersuite_object_data", "=", "membersuite_object", ")", ")", "return", "individuals" ]
Returns all Individuals that have `organization` as a primary org.
[ "Returns", "all", "Individuals", "that", "have", "organization", "as", "a", "primary", "org", "." ]
221f5ed8bc7d4424237a4669c5af9edc11819ee9
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/organizations/services.py#L109-L140
train
20c/grainy
grainy/core.py
Namespace.match
def match(self, keys, partial=True): """ Check if the value of this namespace is matched by keys '*' is treated as wildcard Arguments: keys -- list of keys Examples: ns = Namespace("a.b.c") ns.match(["a"]) #True ns.match(["a","b"]) #True ns.match(["a","b","c"]) #True ns.match(["a","*","c"]) #True ns.match(["b","b","c"]) #False """ if not partial and len(keys) != self.length: return False c = 0 for k in keys: if c >= self.length: return False a = self.keys[c] if a != "*" and k != "*" and k != a: return False c += 1 return True
python
def match(self, keys, partial=True): """ Check if the value of this namespace is matched by keys '*' is treated as wildcard Arguments: keys -- list of keys Examples: ns = Namespace("a.b.c") ns.match(["a"]) #True ns.match(["a","b"]) #True ns.match(["a","b","c"]) #True ns.match(["a","*","c"]) #True ns.match(["b","b","c"]) #False """ if not partial and len(keys) != self.length: return False c = 0 for k in keys: if c >= self.length: return False a = self.keys[c] if a != "*" and k != "*" and k != a: return False c += 1 return True
[ "def", "match", "(", "self", ",", "keys", ",", "partial", "=", "True", ")", ":", "if", "not", "partial", "and", "len", "(", "keys", ")", "!=", "self", ".", "length", ":", "return", "False", "c", "=", "0", "for", "k", "in", "keys", ":", "if", "c", ">=", "self", ".", "length", ":", "return", "False", "a", "=", "self", ".", "keys", "[", "c", "]", "if", "a", "!=", "\"*\"", "and", "k", "!=", "\"*\"", "and", "k", "!=", "a", ":", "return", "False", "c", "+=", "1", "return", "True" ]
Check if the value of this namespace is matched by keys '*' is treated as wildcard Arguments: keys -- list of keys Examples: ns = Namespace("a.b.c") ns.match(["a"]) #True ns.match(["a","b"]) #True ns.match(["a","b","c"]) #True ns.match(["a","*","c"]) #True ns.match(["b","b","c"]) #False
[ "Check", "if", "the", "value", "of", "this", "namespace", "is", "matched", "by", "keys" ]
cd956fd4144044993abc967974a127aab07a8ef6
https://github.com/20c/grainy/blob/cd956fd4144044993abc967974a127aab07a8ef6/grainy/core.py#L81-L113
train
20c/grainy
grainy/core.py
Namespace.container
def container(self, data=None): """ Creates a dict built from the keys of this namespace Returns the dict created as well as the tail in a tuple Example: self.value = "a.b.c" container, tail = self.container() #{"a":{"b":{"c":{}}}, {} container, tail = self.container({"d":123}) #{"a":{"b":{"c":{"d":123}}}, {"d":123} """ if data is None: data = {} root = p = d = {} j = 0 k = None for k in self: d[k] = {} p = d d = d[k] if k is not None: p[k] = data return (root, p[k])
python
def container(self, data=None): """ Creates a dict built from the keys of this namespace Returns the dict created as well as the tail in a tuple Example: self.value = "a.b.c" container, tail = self.container() #{"a":{"b":{"c":{}}}, {} container, tail = self.container({"d":123}) #{"a":{"b":{"c":{"d":123}}}, {"d":123} """ if data is None: data = {} root = p = d = {} j = 0 k = None for k in self: d[k] = {} p = d d = d[k] if k is not None: p[k] = data return (root, p[k])
[ "def", "container", "(", "self", ",", "data", "=", "None", ")", ":", "if", "data", "is", "None", ":", "data", "=", "{", "}", "root", "=", "p", "=", "d", "=", "{", "}", "j", "=", "0", "k", "=", "None", "for", "k", "in", "self", ":", "d", "[", "k", "]", "=", "{", "}", "p", "=", "d", "d", "=", "d", "[", "k", "]", "if", "k", "is", "not", "None", ":", "p", "[", "k", "]", "=", "data", "return", "(", "root", ",", "p", "[", "k", "]", ")" ]
Creates a dict built from the keys of this namespace Returns the dict created as well as the tail in a tuple Example: self.value = "a.b.c" container, tail = self.container() #{"a":{"b":{"c":{}}}, {} container, tail = self.container({"d":123}) #{"a":{"b":{"c":{"d":123}}}, {"d":123}
[ "Creates", "a", "dict", "built", "from", "the", "keys", "of", "this", "namespace" ]
cd956fd4144044993abc967974a127aab07a8ef6
https://github.com/20c/grainy/blob/cd956fd4144044993abc967974a127aab07a8ef6/grainy/core.py#L115-L144
train
20c/grainy
grainy/core.py
PermissionSet.update_index
def update_index(self): """ Regenerates the permission index for this set Called everytime a rule is added / removed / modified in the set """ # update index idx = {} for _, p in sorted(self.permissions.items(), key=lambda x: str(x[0])): branch = idx parent_p = const.PERM_DENY for k in p.namespace.keys: if not k in branch: branch[k] = {"__": parent_p} branch[k].update(__implicit=True) branch = branch[k] parent_p = branch["__"] branch["__"] = p.value branch["__implicit"] = False self.index = idx # update read access map ramap = {} def update_ramap(branch_idx): r = {"__": False} for k, v in list(branch_idx.items()): if k != "__" and k != "__implicit": r[k] = update_ramap(v) if branch_idx["__"] is not None and (branch_idx["__"] & const.PERM_READ) != 0: r["__"] = True return r for k, v in list(idx.items()): ramap[k] = update_ramap(v) self.read_access_map = ramap return self.index
python
def update_index(self): """ Regenerates the permission index for this set Called everytime a rule is added / removed / modified in the set """ # update index idx = {} for _, p in sorted(self.permissions.items(), key=lambda x: str(x[0])): branch = idx parent_p = const.PERM_DENY for k in p.namespace.keys: if not k in branch: branch[k] = {"__": parent_p} branch[k].update(__implicit=True) branch = branch[k] parent_p = branch["__"] branch["__"] = p.value branch["__implicit"] = False self.index = idx # update read access map ramap = {} def update_ramap(branch_idx): r = {"__": False} for k, v in list(branch_idx.items()): if k != "__" and k != "__implicit": r[k] = update_ramap(v) if branch_idx["__"] is not None and (branch_idx["__"] & const.PERM_READ) != 0: r["__"] = True return r for k, v in list(idx.items()): ramap[k] = update_ramap(v) self.read_access_map = ramap return self.index
[ "def", "update_index", "(", "self", ")", ":", "# update index", "idx", "=", "{", "}", "for", "_", ",", "p", "in", "sorted", "(", "self", ".", "permissions", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "str", "(", "x", "[", "0", "]", ")", ")", ":", "branch", "=", "idx", "parent_p", "=", "const", ".", "PERM_DENY", "for", "k", "in", "p", ".", "namespace", ".", "keys", ":", "if", "not", "k", "in", "branch", ":", "branch", "[", "k", "]", "=", "{", "\"__\"", ":", "parent_p", "}", "branch", "[", "k", "]", ".", "update", "(", "__implicit", "=", "True", ")", "branch", "=", "branch", "[", "k", "]", "parent_p", "=", "branch", "[", "\"__\"", "]", "branch", "[", "\"__\"", "]", "=", "p", ".", "value", "branch", "[", "\"__implicit\"", "]", "=", "False", "self", ".", "index", "=", "idx", "# update read access map", "ramap", "=", "{", "}", "def", "update_ramap", "(", "branch_idx", ")", ":", "r", "=", "{", "\"__\"", ":", "False", "}", "for", "k", ",", "v", "in", "list", "(", "branch_idx", ".", "items", "(", ")", ")", ":", "if", "k", "!=", "\"__\"", "and", "k", "!=", "\"__implicit\"", ":", "r", "[", "k", "]", "=", "update_ramap", "(", "v", ")", "if", "branch_idx", "[", "\"__\"", "]", "is", "not", "None", "and", "(", "branch_idx", "[", "\"__\"", "]", "&", "const", ".", "PERM_READ", ")", "!=", "0", ":", "r", "[", "\"__\"", "]", "=", "True", "return", "r", "for", "k", ",", "v", "in", "list", "(", "idx", ".", "items", "(", ")", ")", ":", "ramap", "[", "k", "]", "=", "update_ramap", "(", "v", ")", "self", ".", "read_access_map", "=", "ramap", "return", "self", ".", "index" ]
Regenerates the permission index for this set Called everytime a rule is added / removed / modified in the set
[ "Regenerates", "the", "permission", "index", "for", "this", "set" ]
cd956fd4144044993abc967974a127aab07a8ef6
https://github.com/20c/grainy/blob/cd956fd4144044993abc967974a127aab07a8ef6/grainy/core.py#L274-L319
train
20c/grainy
grainy/core.py
PermissionSet.get_permissions
def get_permissions(self, namespace, explicit=False): """ Returns the permissions level for the specified namespace Arguments: namespace -- permissioning namespace (str) explicit -- require explicitly set permissions to the provided namespace Returns: int -- permissioning flags """ if not isinstance(namespace, Namespace): namespace = Namespace(namespace) keys = namespace.keys p, _ = self._check(keys, self.index, explicit=explicit) return p
python
def get_permissions(self, namespace, explicit=False): """ Returns the permissions level for the specified namespace Arguments: namespace -- permissioning namespace (str) explicit -- require explicitly set permissions to the provided namespace Returns: int -- permissioning flags """ if not isinstance(namespace, Namespace): namespace = Namespace(namespace) keys = namespace.keys p, _ = self._check(keys, self.index, explicit=explicit) return p
[ "def", "get_permissions", "(", "self", ",", "namespace", ",", "explicit", "=", "False", ")", ":", "if", "not", "isinstance", "(", "namespace", ",", "Namespace", ")", ":", "namespace", "=", "Namespace", "(", "namespace", ")", "keys", "=", "namespace", ".", "keys", "p", ",", "_", "=", "self", ".", "_check", "(", "keys", ",", "self", ".", "index", ",", "explicit", "=", "explicit", ")", "return", "p" ]
Returns the permissions level for the specified namespace Arguments: namespace -- permissioning namespace (str) explicit -- require explicitly set permissions to the provided namespace Returns: int -- permissioning flags
[ "Returns", "the", "permissions", "level", "for", "the", "specified", "namespace" ]
cd956fd4144044993abc967974a127aab07a8ef6
https://github.com/20c/grainy/blob/cd956fd4144044993abc967974a127aab07a8ef6/grainy/core.py#L360-L378
train
20c/grainy
grainy/core.py
PermissionSet.check
def check(self, namespace, level, explicit=False): """ Checks if the permset has permission to the specified namespace at the specified level Arguments: namespace -- permissioning namespace (str) level -- permissioning level (int) (PERM_READ for example) explicit -- require explicitly set permissions to the provided namespace Returns: bool """ return (self.get_permissions(namespace, explicit=explicit) & level) != 0
python
def check(self, namespace, level, explicit=False): """ Checks if the permset has permission to the specified namespace at the specified level Arguments: namespace -- permissioning namespace (str) level -- permissioning level (int) (PERM_READ for example) explicit -- require explicitly set permissions to the provided namespace Returns: bool """ return (self.get_permissions(namespace, explicit=explicit) & level) != 0
[ "def", "check", "(", "self", ",", "namespace", ",", "level", ",", "explicit", "=", "False", ")", ":", "return", "(", "self", ".", "get_permissions", "(", "namespace", ",", "explicit", "=", "explicit", ")", "&", "level", ")", "!=", "0" ]
Checks if the permset has permission to the specified namespace at the specified level Arguments: namespace -- permissioning namespace (str) level -- permissioning level (int) (PERM_READ for example) explicit -- require explicitly set permissions to the provided namespace Returns: bool
[ "Checks", "if", "the", "permset", "has", "permission", "to", "the", "specified", "namespace", "at", "the", "specified", "level" ]
cd956fd4144044993abc967974a127aab07a8ef6
https://github.com/20c/grainy/blob/cd956fd4144044993abc967974a127aab07a8ef6/grainy/core.py#L381-L397
train
a1ezzz/wasp-general
wasp_general/crypto/hmac.py
WHMAC.hash
def hash(self, key, message=None): """ Return digest of the given message and key :param key: secret HMAC key :param message: code (message) to authenticate :return: bytes """ hmac_obj = hmac.HMAC(key, self.__digest_generator, backend=default_backend()) if message is not None: hmac_obj.update(message) return hmac_obj.finalize()
python
def hash(self, key, message=None): """ Return digest of the given message and key :param key: secret HMAC key :param message: code (message) to authenticate :return: bytes """ hmac_obj = hmac.HMAC(key, self.__digest_generator, backend=default_backend()) if message is not None: hmac_obj.update(message) return hmac_obj.finalize()
[ "def", "hash", "(", "self", ",", "key", ",", "message", "=", "None", ")", ":", "hmac_obj", "=", "hmac", ".", "HMAC", "(", "key", ",", "self", ".", "__digest_generator", ",", "backend", "=", "default_backend", "(", ")", ")", "if", "message", "is", "not", "None", ":", "hmac_obj", ".", "update", "(", "message", ")", "return", "hmac_obj", ".", "finalize", "(", ")" ]
Return digest of the given message and key :param key: secret HMAC key :param message: code (message) to authenticate :return: bytes
[ "Return", "digest", "of", "the", "given", "message", "and", "key" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/hmac.py#L69-L80
train
mangalam-research/selenic
selenic/tables.py
Table.call_with_search_field
def call_with_search_field(self, name, callback): """ Calls a piece of code with the DOM element that corresponds to a search field of the table. If the callback causes a ``StaleElementReferenceException``, this method will refetch the search fields and try again. Consequently **the callback should be designed to be callable multiple times and should only interact with the search field passed to it.** It should not fetch or interact with other DOM elements. :param name: The name of the field to use. :param callback: The callback to call. The first parameter will be the Selenium ``WebElement`` that is the search field. """ done = False while not done: def check(*_): if name in self._search_fields: return True # Force a refetch self._found_fields = None return False self.util.wait(check) field = self._search_fields[name] try: callback(field) done = True except StaleElementReferenceException: # We force a refetch of the fields self._found_fields = None
python
def call_with_search_field(self, name, callback): """ Calls a piece of code with the DOM element that corresponds to a search field of the table. If the callback causes a ``StaleElementReferenceException``, this method will refetch the search fields and try again. Consequently **the callback should be designed to be callable multiple times and should only interact with the search field passed to it.** It should not fetch or interact with other DOM elements. :param name: The name of the field to use. :param callback: The callback to call. The first parameter will be the Selenium ``WebElement`` that is the search field. """ done = False while not done: def check(*_): if name in self._search_fields: return True # Force a refetch self._found_fields = None return False self.util.wait(check) field = self._search_fields[name] try: callback(field) done = True except StaleElementReferenceException: # We force a refetch of the fields self._found_fields = None
[ "def", "call_with_search_field", "(", "self", ",", "name", ",", "callback", ")", ":", "done", "=", "False", "while", "not", "done", ":", "def", "check", "(", "*", "_", ")", ":", "if", "name", "in", "self", ".", "_search_fields", ":", "return", "True", "# Force a refetch", "self", ".", "_found_fields", "=", "None", "return", "False", "self", ".", "util", ".", "wait", "(", "check", ")", "field", "=", "self", ".", "_search_fields", "[", "name", "]", "try", ":", "callback", "(", "field", ")", "done", "=", "True", "except", "StaleElementReferenceException", ":", "# We force a refetch of the fields", "self", ".", "_found_fields", "=", "None" ]
Calls a piece of code with the DOM element that corresponds to a search field of the table. If the callback causes a ``StaleElementReferenceException``, this method will refetch the search fields and try again. Consequently **the callback should be designed to be callable multiple times and should only interact with the search field passed to it.** It should not fetch or interact with other DOM elements. :param name: The name of the field to use. :param callback: The callback to call. The first parameter will be the Selenium ``WebElement`` that is the search field.
[ "Calls", "a", "piece", "of", "code", "with", "the", "DOM", "element", "that", "corresponds", "to", "a", "search", "field", "of", "the", "table", "." ]
2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad
https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/tables.py#L121-L154
train
olitheolix/qtmacs
qtmacs/platform_setup.py
determine_keymap
def determine_keymap(qteMain=None): """ Return the conversion from keys and modifiers to Qt constants. This mapping depends on the used OS and keyboard layout. .. warning :: This method is currently only a dummy that always returns the same mapping from characters to keys. It works fine on my Linux and Windows 7 machine using English/US keyboard layouts, but other layouts will eventually have to be supported. """ if qteMain is None: # This case should only happen for testing purposes. qte_global.Qt_key_map = default_qt_keymap qte_global.Qt_modifier_map = default_qt_modifier_map else: doc = 'Conversion table from local characters to Qt constants' qteMain.qteDefVar("Qt_key_map", default_qt_keymap, doc=doc) doc = 'Conversion table from local modifier keys to Qt constants' qteMain.qteDefVar("Qt_modifier_map", default_qt_modifier_map, doc=doc)
python
def determine_keymap(qteMain=None): """ Return the conversion from keys and modifiers to Qt constants. This mapping depends on the used OS and keyboard layout. .. warning :: This method is currently only a dummy that always returns the same mapping from characters to keys. It works fine on my Linux and Windows 7 machine using English/US keyboard layouts, but other layouts will eventually have to be supported. """ if qteMain is None: # This case should only happen for testing purposes. qte_global.Qt_key_map = default_qt_keymap qte_global.Qt_modifier_map = default_qt_modifier_map else: doc = 'Conversion table from local characters to Qt constants' qteMain.qteDefVar("Qt_key_map", default_qt_keymap, doc=doc) doc = 'Conversion table from local modifier keys to Qt constants' qteMain.qteDefVar("Qt_modifier_map", default_qt_modifier_map, doc=doc)
[ "def", "determine_keymap", "(", "qteMain", "=", "None", ")", ":", "if", "qteMain", "is", "None", ":", "# This case should only happen for testing purposes.", "qte_global", ".", "Qt_key_map", "=", "default_qt_keymap", "qte_global", ".", "Qt_modifier_map", "=", "default_qt_modifier_map", "else", ":", "doc", "=", "'Conversion table from local characters to Qt constants'", "qteMain", ".", "qteDefVar", "(", "\"Qt_key_map\"", ",", "default_qt_keymap", ",", "doc", "=", "doc", ")", "doc", "=", "'Conversion table from local modifier keys to Qt constants'", "qteMain", ".", "qteDefVar", "(", "\"Qt_modifier_map\"", ",", "default_qt_modifier_map", ",", "doc", "=", "doc", ")" ]
Return the conversion from keys and modifiers to Qt constants. This mapping depends on the used OS and keyboard layout. .. warning :: This method is currently only a dummy that always returns the same mapping from characters to keys. It works fine on my Linux and Windows 7 machine using English/US keyboard layouts, but other layouts will eventually have to be supported.
[ "Return", "the", "conversion", "from", "keys", "and", "modifiers", "to", "Qt", "constants", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/platform_setup.py#L158-L178
train
pmacosta/pexdoc
docs/support/my_module.py
func
def func(name): r""" Print your name. :param name: Name to print :type name: string .. [[[cog cog.out(exobj.get_sphinx_autodoc(width=69))]]] .. [[[end]]] """ # Raise condition evaluated in same call as exception addition pexdoc.addex(TypeError, "Argument `name` is not valid", not isinstance(name, str)) return "My name is {0}".format(name)
python
def func(name): r""" Print your name. :param name: Name to print :type name: string .. [[[cog cog.out(exobj.get_sphinx_autodoc(width=69))]]] .. [[[end]]] """ # Raise condition evaluated in same call as exception addition pexdoc.addex(TypeError, "Argument `name` is not valid", not isinstance(name, str)) return "My name is {0}".format(name)
[ "def", "func", "(", "name", ")", ":", "# Raise condition evaluated in same call as exception addition", "pexdoc", ".", "addex", "(", "TypeError", ",", "\"Argument `name` is not valid\"", ",", "not", "isinstance", "(", "name", ",", "str", ")", ")", "return", "\"My name is {0}\"", ".", "format", "(", "name", ")" ]
r""" Print your name. :param name: Name to print :type name: string .. [[[cog cog.out(exobj.get_sphinx_autodoc(width=69))]]] .. [[[end]]]
[ "r", "Print", "your", "name", "." ]
201ac243e5781347feb75896a4231429fe6da4b1
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/docs/support/my_module.py#L20-L33
train
olitheolix/qtmacs
qtmacs/extensions/qtmacsscintilla_macros.py
YankPop.disableHook
def disableHook(self, msgObj): """ Disable yank-pop. The ``enableHook`` method (see below) connects this method to the ``qtesigKeyseqComplete`` signal to catch consecutive calls to this ``yank-pop`` macro. Once the user issues a key sequence for any other macro but this one, the kill-list index will be set to a negative index, effectively disabling the macro. """ # Unpack the data structure. macroName, keysequence = msgObj.data if macroName != self.qteMacroName(): self.qteMain.qtesigKeyseqComplete.disconnect( self.disableHook) self.killListIdx = -1
python
def disableHook(self, msgObj): """ Disable yank-pop. The ``enableHook`` method (see below) connects this method to the ``qtesigKeyseqComplete`` signal to catch consecutive calls to this ``yank-pop`` macro. Once the user issues a key sequence for any other macro but this one, the kill-list index will be set to a negative index, effectively disabling the macro. """ # Unpack the data structure. macroName, keysequence = msgObj.data if macroName != self.qteMacroName(): self.qteMain.qtesigKeyseqComplete.disconnect( self.disableHook) self.killListIdx = -1
[ "def", "disableHook", "(", "self", ",", "msgObj", ")", ":", "# Unpack the data structure.", "macroName", ",", "keysequence", "=", "msgObj", ".", "data", "if", "macroName", "!=", "self", ".", "qteMacroName", "(", ")", ":", "self", ".", "qteMain", ".", "qtesigKeyseqComplete", ".", "disconnect", "(", "self", ".", "disableHook", ")", "self", ".", "killListIdx", "=", "-", "1" ]
Disable yank-pop. The ``enableHook`` method (see below) connects this method to the ``qtesigKeyseqComplete`` signal to catch consecutive calls to this ``yank-pop`` macro. Once the user issues a key sequence for any other macro but this one, the kill-list index will be set to a negative index, effectively disabling the macro.
[ "Disable", "yank", "-", "pop", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L912-L928
train
olitheolix/qtmacs
qtmacs/extensions/qtmacsscintilla_macros.py
SearchForwardMiniApplet.clearHighlighting
def clearHighlighting(self): """ Restore the original style properties of all matches. This method effectively removes all visible traces of the match highlighting. """ SCI = self.qteWidget self.qteWidget.SCISetStylingEx(0, 0, self.styleOrig) # Clear out the match set and reset the match index. self.selMatchIdx = 1 self.matchList = []
python
def clearHighlighting(self): """ Restore the original style properties of all matches. This method effectively removes all visible traces of the match highlighting. """ SCI = self.qteWidget self.qteWidget.SCISetStylingEx(0, 0, self.styleOrig) # Clear out the match set and reset the match index. self.selMatchIdx = 1 self.matchList = []
[ "def", "clearHighlighting", "(", "self", ")", ":", "SCI", "=", "self", ".", "qteWidget", "self", ".", "qteWidget", ".", "SCISetStylingEx", "(", "0", ",", "0", ",", "self", ".", "styleOrig", ")", "# Clear out the match set and reset the match index.", "self", ".", "selMatchIdx", "=", "1", "self", ".", "matchList", "=", "[", "]" ]
Restore the original style properties of all matches. This method effectively removes all visible traces of the match highlighting.
[ "Restore", "the", "original", "style", "properties", "of", "all", "matches", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L1449-L1461
train
olitheolix/qtmacs
qtmacs/extensions/qtmacsscintilla_macros.py
SearchForwardMiniApplet.highlightNextMatch
def highlightNextMatch(self): """ Select and highlight the next match in the set of matches. """ # If this method was called on an empty input field (ie. # if the user hit <ctrl>+s again) then pick the default # selection. if self.qteText.toPlainText() == '': self.qteText.setText(self.defaultChoice) return # If the mathIdx variable is out of bounds (eg. the last possible # match is already selected) then wrap it around. if self.selMatchIdx < 0: self.selMatchIdx = 0 return if self.selMatchIdx >= len(self.matchList): self.selMatchIdx = 0 return # Shorthand. SCI = self.qteWidget # Undo the highlighting of the previously selected match. start, stop = self.matchList[self.selMatchIdx - 1] line, col = SCI.lineIndexFromPosition(start) SCI.SendScintilla(SCI.SCI_STARTSTYLING, start, 0xFF) SCI.SendScintilla(SCI.SCI_SETSTYLING, stop - start, 30) # Highlight the next match. start, stop = self.matchList[self.selMatchIdx] SCI.SendScintilla(SCI.SCI_STARTSTYLING, start, 0xFF) SCI.SendScintilla(SCI.SCI_SETSTYLING, stop - start, 31) # Place the cursor at the start of the currently selected match. line, col = SCI.lineIndexFromPosition(start) SCI.setCursorPosition(line, col) self.selMatchIdx += 1
python
def highlightNextMatch(self): """ Select and highlight the next match in the set of matches. """ # If this method was called on an empty input field (ie. # if the user hit <ctrl>+s again) then pick the default # selection. if self.qteText.toPlainText() == '': self.qteText.setText(self.defaultChoice) return # If the mathIdx variable is out of bounds (eg. the last possible # match is already selected) then wrap it around. if self.selMatchIdx < 0: self.selMatchIdx = 0 return if self.selMatchIdx >= len(self.matchList): self.selMatchIdx = 0 return # Shorthand. SCI = self.qteWidget # Undo the highlighting of the previously selected match. start, stop = self.matchList[self.selMatchIdx - 1] line, col = SCI.lineIndexFromPosition(start) SCI.SendScintilla(SCI.SCI_STARTSTYLING, start, 0xFF) SCI.SendScintilla(SCI.SCI_SETSTYLING, stop - start, 30) # Highlight the next match. start, stop = self.matchList[self.selMatchIdx] SCI.SendScintilla(SCI.SCI_STARTSTYLING, start, 0xFF) SCI.SendScintilla(SCI.SCI_SETSTYLING, stop - start, 31) # Place the cursor at the start of the currently selected match. line, col = SCI.lineIndexFromPosition(start) SCI.setCursorPosition(line, col) self.selMatchIdx += 1
[ "def", "highlightNextMatch", "(", "self", ")", ":", "# If this method was called on an empty input field (ie.", "# if the user hit <ctrl>+s again) then pick the default", "# selection.", "if", "self", ".", "qteText", ".", "toPlainText", "(", ")", "==", "''", ":", "self", ".", "qteText", ".", "setText", "(", "self", ".", "defaultChoice", ")", "return", "# If the mathIdx variable is out of bounds (eg. the last possible", "# match is already selected) then wrap it around.", "if", "self", ".", "selMatchIdx", "<", "0", ":", "self", ".", "selMatchIdx", "=", "0", "return", "if", "self", ".", "selMatchIdx", ">=", "len", "(", "self", ".", "matchList", ")", ":", "self", ".", "selMatchIdx", "=", "0", "return", "# Shorthand.", "SCI", "=", "self", ".", "qteWidget", "# Undo the highlighting of the previously selected match.", "start", ",", "stop", "=", "self", ".", "matchList", "[", "self", ".", "selMatchIdx", "-", "1", "]", "line", ",", "col", "=", "SCI", ".", "lineIndexFromPosition", "(", "start", ")", "SCI", ".", "SendScintilla", "(", "SCI", ".", "SCI_STARTSTYLING", ",", "start", ",", "0xFF", ")", "SCI", ".", "SendScintilla", "(", "SCI", ".", "SCI_SETSTYLING", ",", "stop", "-", "start", ",", "30", ")", "# Highlight the next match.", "start", ",", "stop", "=", "self", ".", "matchList", "[", "self", ".", "selMatchIdx", "]", "SCI", ".", "SendScintilla", "(", "SCI", ".", "SCI_STARTSTYLING", ",", "start", ",", "0xFF", ")", "SCI", ".", "SendScintilla", "(", "SCI", ".", "SCI_SETSTYLING", ",", "stop", "-", "start", ",", "31", ")", "# Place the cursor at the start of the currently selected match.", "line", ",", "col", "=", "SCI", ".", "lineIndexFromPosition", "(", "start", ")", "SCI", ".", "setCursorPosition", "(", "line", ",", "col", ")", "self", ".", "selMatchIdx", "+=", "1" ]
Select and highlight the next match in the set of matches.
[ "Select", "and", "highlight", "the", "next", "match", "in", "the", "set", "of", "matches", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L1463-L1500
train
olitheolix/qtmacs
qtmacs/extensions/qtmacsscintilla_macros.py
QueryReplaceMiniApplet.nextMode
def nextMode(self): """ Put the search-replace macro into the next stage. The first stage is the query stage to ask the user for the string to replace, the second stage is to query the string to replace it with, and the third allows to replace or skip individual matches, or replace them all automatically. """ # Terminate the replacement procedure if the no match was found. if len(self.matchList) == 0: self.qteAbort(QtmacsMessage()) self.qteMain.qteKillMiniApplet() return self.queryMode += 1 if self.queryMode == 1: # Disconnect the text-changed slot because no real time # highlighting is necessary when entering the replacement # string, unlike when entering the string to replace. self.qteText.textChanged.disconnect(self.qteTextChanged) # Store the string to replace and clear out the query field. self.toReplace = self.qteText.toPlainText() self.qteText.clear() self.qteTextPrefix.setText('mode 1') elif self.queryMode == 2: # Mode two is to replace or skip individual matches. For # this purpose rebind the "n", "!", and <space> keys # with the respective macros to facilitate it. register = self.qteMain.qteRegisterMacro bind = self.qteMain.qteBindKeyWidget # Unbind all keys from the input widget. self.qteMain.qteUnbindAllFromWidgetObject(self.qteText) macroName = register(self.ReplaceAll, replaceMacro=True) bind('!', macroName, self.qteText) macroName = register(self.ReplaceNext, replaceMacro=True) bind('<space>', macroName, self.qteText) macroName = register(self.SkipNext, replaceMacro=True) bind('n', macroName, self.qteText) macroName = register(self.Abort, replaceMacro=True) bind('q', macroName, self.qteText) bind('<enter>', macroName, self.qteText) self.toReplaceWith = self.qteText.toPlainText() self.qteTextPrefix.setText('mode 2') self.qteText.setText('<space> to replace, <n> to skip, ' '<!> to replace all.') else: self.qteAbort(QtmacsMessage()) self.qteMain.qteKillMiniApplet()
python
def nextMode(self): """ Put the search-replace macro into the next stage. The first stage is the query stage to ask the user for the string to replace, the second stage is to query the string to replace it with, and the third allows to replace or skip individual matches, or replace them all automatically. """ # Terminate the replacement procedure if the no match was found. if len(self.matchList) == 0: self.qteAbort(QtmacsMessage()) self.qteMain.qteKillMiniApplet() return self.queryMode += 1 if self.queryMode == 1: # Disconnect the text-changed slot because no real time # highlighting is necessary when entering the replacement # string, unlike when entering the string to replace. self.qteText.textChanged.disconnect(self.qteTextChanged) # Store the string to replace and clear out the query field. self.toReplace = self.qteText.toPlainText() self.qteText.clear() self.qteTextPrefix.setText('mode 1') elif self.queryMode == 2: # Mode two is to replace or skip individual matches. For # this purpose rebind the "n", "!", and <space> keys # with the respective macros to facilitate it. register = self.qteMain.qteRegisterMacro bind = self.qteMain.qteBindKeyWidget # Unbind all keys from the input widget. self.qteMain.qteUnbindAllFromWidgetObject(self.qteText) macroName = register(self.ReplaceAll, replaceMacro=True) bind('!', macroName, self.qteText) macroName = register(self.ReplaceNext, replaceMacro=True) bind('<space>', macroName, self.qteText) macroName = register(self.SkipNext, replaceMacro=True) bind('n', macroName, self.qteText) macroName = register(self.Abort, replaceMacro=True) bind('q', macroName, self.qteText) bind('<enter>', macroName, self.qteText) self.toReplaceWith = self.qteText.toPlainText() self.qteTextPrefix.setText('mode 2') self.qteText.setText('<space> to replace, <n> to skip, ' '<!> to replace all.') else: self.qteAbort(QtmacsMessage()) self.qteMain.qteKillMiniApplet()
[ "def", "nextMode", "(", "self", ")", ":", "# Terminate the replacement procedure if the no match was found.", "if", "len", "(", "self", ".", "matchList", ")", "==", "0", ":", "self", ".", "qteAbort", "(", "QtmacsMessage", "(", ")", ")", "self", ".", "qteMain", ".", "qteKillMiniApplet", "(", ")", "return", "self", ".", "queryMode", "+=", "1", "if", "self", ".", "queryMode", "==", "1", ":", "# Disconnect the text-changed slot because no real time", "# highlighting is necessary when entering the replacement", "# string, unlike when entering the string to replace.", "self", ".", "qteText", ".", "textChanged", ".", "disconnect", "(", "self", ".", "qteTextChanged", ")", "# Store the string to replace and clear out the query field.", "self", ".", "toReplace", "=", "self", ".", "qteText", ".", "toPlainText", "(", ")", "self", ".", "qteText", ".", "clear", "(", ")", "self", ".", "qteTextPrefix", ".", "setText", "(", "'mode 1'", ")", "elif", "self", ".", "queryMode", "==", "2", ":", "# Mode two is to replace or skip individual matches. For", "# this purpose rebind the \"n\", \"!\", and <space> keys", "# with the respective macros to facilitate it.", "register", "=", "self", ".", "qteMain", ".", "qteRegisterMacro", "bind", "=", "self", ".", "qteMain", ".", "qteBindKeyWidget", "# Unbind all keys from the input widget.", "self", ".", "qteMain", ".", "qteUnbindAllFromWidgetObject", "(", "self", ".", "qteText", ")", "macroName", "=", "register", "(", "self", ".", "ReplaceAll", ",", "replaceMacro", "=", "True", ")", "bind", "(", "'!'", ",", "macroName", ",", "self", ".", "qteText", ")", "macroName", "=", "register", "(", "self", ".", "ReplaceNext", ",", "replaceMacro", "=", "True", ")", "bind", "(", "'<space>'", ",", "macroName", ",", "self", ".", "qteText", ")", "macroName", "=", "register", "(", "self", ".", "SkipNext", ",", "replaceMacro", "=", "True", ")", "bind", "(", "'n'", ",", "macroName", ",", "self", ".", "qteText", ")", "macroName", "=", "register", "(", "self", ".", "Abort", ",", "replaceMacro", "=", "True", ")", "bind", "(", "'q'", ",", "macroName", ",", "self", ".", "qteText", ")", "bind", "(", "'<enter>'", ",", "macroName", ",", "self", ".", "qteText", ")", "self", ".", "toReplaceWith", "=", "self", ".", "qteText", ".", "toPlainText", "(", ")", "self", ".", "qteTextPrefix", ".", "setText", "(", "'mode 2'", ")", "self", ".", "qteText", ".", "setText", "(", "'<space> to replace, <n> to skip, '", "'<!> to replace all.'", ")", "else", ":", "self", ".", "qteAbort", "(", "QtmacsMessage", "(", ")", ")", "self", ".", "qteMain", ".", "qteKillMiniApplet", "(", ")" ]
Put the search-replace macro into the next stage. The first stage is the query stage to ask the user for the string to replace, the second stage is to query the string to replace it with, and the third allows to replace or skip individual matches, or replace them all automatically.
[ "Put", "the", "search", "-", "replace", "macro", "into", "the", "next", "stage", ".", "The", "first", "stage", "is", "the", "query", "stage", "to", "ask", "the", "user", "for", "the", "string", "to", "replace", "the", "second", "stage", "is", "to", "query", "the", "string", "to", "replace", "it", "with", "and", "the", "third", "allows", "to", "replace", "or", "skip", "individual", "matches", "or", "replace", "them", "all", "automatically", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L1878-L1932
train
olitheolix/qtmacs
qtmacs/extensions/qtmacsscintilla_macros.py
QueryReplaceMiniApplet.replaceAll
def replaceAll(self): """ Replace all matches after the current cursor position. This method calls ``replaceSelectedText`` until it returns **False**, and then closes the mini buffer. """ while self.replaceSelected(): pass self.qteWidget.SCISetStylingEx(0, 0, self.styleOrig) self.qteMain.qteKillMiniApplet()
python
def replaceAll(self): """ Replace all matches after the current cursor position. This method calls ``replaceSelectedText`` until it returns **False**, and then closes the mini buffer. """ while self.replaceSelected(): pass self.qteWidget.SCISetStylingEx(0, 0, self.styleOrig) self.qteMain.qteKillMiniApplet()
[ "def", "replaceAll", "(", "self", ")", ":", "while", "self", ".", "replaceSelected", "(", ")", ":", "pass", "self", ".", "qteWidget", ".", "SCISetStylingEx", "(", "0", ",", "0", ",", "self", ".", "styleOrig", ")", "self", ".", "qteMain", ".", "qteKillMiniApplet", "(", ")" ]
Replace all matches after the current cursor position. This method calls ``replaceSelectedText`` until it returns **False**, and then closes the mini buffer.
[ "Replace", "all", "matches", "after", "the", "current", "cursor", "position", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L2010-L2021
train
olitheolix/qtmacs
qtmacs/extensions/qtmacsscintilla_macros.py
QueryReplaceMiniApplet.compileMatchList
def compileMatchList(self): """ Compile the list of spans of every match. """ # Get the new sub-string to search for. self.matchList = [] # Return immediately if the input field is empty. numChar = len(self.toReplace) if numChar == 0: return # Compile a list of all sub-string spans. stop = 0 text = self.qteWidget.text() while True: start = text.find(self.toReplace, stop) if start == -1: break else: stop = start + numChar self.matchList.append((start, stop))
python
def compileMatchList(self): """ Compile the list of spans of every match. """ # Get the new sub-string to search for. self.matchList = [] # Return immediately if the input field is empty. numChar = len(self.toReplace) if numChar == 0: return # Compile a list of all sub-string spans. stop = 0 text = self.qteWidget.text() while True: start = text.find(self.toReplace, stop) if start == -1: break else: stop = start + numChar self.matchList.append((start, stop))
[ "def", "compileMatchList", "(", "self", ")", ":", "# Get the new sub-string to search for.", "self", ".", "matchList", "=", "[", "]", "# Return immediately if the input field is empty.", "numChar", "=", "len", "(", "self", ".", "toReplace", ")", "if", "numChar", "==", "0", ":", "return", "# Compile a list of all sub-string spans.", "stop", "=", "0", "text", "=", "self", ".", "qteWidget", ".", "text", "(", ")", "while", "True", ":", "start", "=", "text", ".", "find", "(", "self", ".", "toReplace", ",", "stop", ")", "if", "start", "==", "-", "1", ":", "break", "else", ":", "stop", "=", "start", "+", "numChar", "self", ".", "matchList", ".", "append", "(", "(", "start", ",", "stop", ")", ")" ]
Compile the list of spans of every match.
[ "Compile", "the", "list", "of", "spans", "of", "every", "match", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L2023-L2044
train
olitheolix/qtmacs
qtmacs/extensions/qtmacsscintilla_macros.py
QueryReplaceRegexpMiniApplet.replaceSelected
def replaceSelected(self): """ Replace the currently selected string with the new one. The method return **False** if another match to the right of the cursor exists, and **True** if not (ie. when the end of the document was reached). """ SCI = self.qteWidget # Restore the original styling. self.qteWidget.SCISetStylingEx(0, 0, self.styleOrig) # Select the region spanned by the string to replace. start, stop = self.matchList[self.selMatchIdx] line1, col1 = SCI.lineIndexFromPosition(start) line2, col2 = SCI.lineIndexFromPosition(stop) SCI.setSelection(line1, col1, line2, col2) text = SCI.selectedText() text = re.sub(self.toReplace, self.toReplaceWith, text) # Replace that region with the new string and move the cursor # to the end of that string. SCI.replaceSelectedText(text) line, col = SCI.lineIndexFromPosition(start + len(text)) SCI.setCursorPosition(line, col) # Backup the new document style bits. line, col = SCI.getNumLinesAndColumns() text, style = self.qteWidget.SCIGetStyledText((0, 0, line, col)) self.styleOrig = style # Determine if this was the last entry in the match list. if len(self.matchList) == self.selMatchIdx + 1: return False else: self.highlightAllMatches() return True
python
def replaceSelected(self): """ Replace the currently selected string with the new one. The method return **False** if another match to the right of the cursor exists, and **True** if not (ie. when the end of the document was reached). """ SCI = self.qteWidget # Restore the original styling. self.qteWidget.SCISetStylingEx(0, 0, self.styleOrig) # Select the region spanned by the string to replace. start, stop = self.matchList[self.selMatchIdx] line1, col1 = SCI.lineIndexFromPosition(start) line2, col2 = SCI.lineIndexFromPosition(stop) SCI.setSelection(line1, col1, line2, col2) text = SCI.selectedText() text = re.sub(self.toReplace, self.toReplaceWith, text) # Replace that region with the new string and move the cursor # to the end of that string. SCI.replaceSelectedText(text) line, col = SCI.lineIndexFromPosition(start + len(text)) SCI.setCursorPosition(line, col) # Backup the new document style bits. line, col = SCI.getNumLinesAndColumns() text, style = self.qteWidget.SCIGetStyledText((0, 0, line, col)) self.styleOrig = style # Determine if this was the last entry in the match list. if len(self.matchList) == self.selMatchIdx + 1: return False else: self.highlightAllMatches() return True
[ "def", "replaceSelected", "(", "self", ")", ":", "SCI", "=", "self", ".", "qteWidget", "# Restore the original styling.", "self", ".", "qteWidget", ".", "SCISetStylingEx", "(", "0", ",", "0", ",", "self", ".", "styleOrig", ")", "# Select the region spanned by the string to replace.", "start", ",", "stop", "=", "self", ".", "matchList", "[", "self", ".", "selMatchIdx", "]", "line1", ",", "col1", "=", "SCI", ".", "lineIndexFromPosition", "(", "start", ")", "line2", ",", "col2", "=", "SCI", ".", "lineIndexFromPosition", "(", "stop", ")", "SCI", ".", "setSelection", "(", "line1", ",", "col1", ",", "line2", ",", "col2", ")", "text", "=", "SCI", ".", "selectedText", "(", ")", "text", "=", "re", ".", "sub", "(", "self", ".", "toReplace", ",", "self", ".", "toReplaceWith", ",", "text", ")", "# Replace that region with the new string and move the cursor", "# to the end of that string.", "SCI", ".", "replaceSelectedText", "(", "text", ")", "line", ",", "col", "=", "SCI", ".", "lineIndexFromPosition", "(", "start", "+", "len", "(", "text", ")", ")", "SCI", ".", "setCursorPosition", "(", "line", ",", "col", ")", "# Backup the new document style bits.", "line", ",", "col", "=", "SCI", ".", "getNumLinesAndColumns", "(", ")", "text", ",", "style", "=", "self", ".", "qteWidget", ".", "SCIGetStyledText", "(", "(", "0", ",", "0", ",", "line", ",", "col", ")", ")", "self", ".", "styleOrig", "=", "style", "# Determine if this was the last entry in the match list.", "if", "len", "(", "self", ".", "matchList", ")", "==", "self", ".", "selMatchIdx", "+", "1", ":", "return", "False", "else", ":", "self", ".", "highlightAllMatches", "(", ")", "return", "True" ]
Replace the currently selected string with the new one. The method return **False** if another match to the right of the cursor exists, and **True** if not (ie. when the end of the document was reached).
[ "Replace", "the", "currently", "selected", "string", "with", "the", "new", "one", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacsscintilla_macros.py#L2176-L2214
train
ashmastaflash/kal-wrapper
kalibrate/kal.py
Kal.scan_band
def scan_band(self, band, **kwargs): """Run Kalibrate for a band. Supported keyword arguments: gain -- Gain in dB device -- Index of device to be used error -- Initial frequency error in ppm """ kal_run_line = fn.build_kal_scan_band_string(self.kal_bin, band, kwargs) raw_output = subprocess.check_output(kal_run_line.split(' '), stderr=subprocess.STDOUT) kal_normalized = fn.parse_kal_scan(raw_output) return kal_normalized
python
def scan_band(self, band, **kwargs): """Run Kalibrate for a band. Supported keyword arguments: gain -- Gain in dB device -- Index of device to be used error -- Initial frequency error in ppm """ kal_run_line = fn.build_kal_scan_band_string(self.kal_bin, band, kwargs) raw_output = subprocess.check_output(kal_run_line.split(' '), stderr=subprocess.STDOUT) kal_normalized = fn.parse_kal_scan(raw_output) return kal_normalized
[ "def", "scan_band", "(", "self", ",", "band", ",", "*", "*", "kwargs", ")", ":", "kal_run_line", "=", "fn", ".", "build_kal_scan_band_string", "(", "self", ".", "kal_bin", ",", "band", ",", "kwargs", ")", "raw_output", "=", "subprocess", ".", "check_output", "(", "kal_run_line", ".", "split", "(", "' '", ")", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "kal_normalized", "=", "fn", ".", "parse_kal_scan", "(", "raw_output", ")", "return", "kal_normalized" ]
Run Kalibrate for a band. Supported keyword arguments: gain -- Gain in dB device -- Index of device to be used error -- Initial frequency error in ppm
[ "Run", "Kalibrate", "for", "a", "band", "." ]
80ee03ab7bd3172ac26b769d6b442960f3424b0e
https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/kal.py#L20-L35
train
ashmastaflash/kal-wrapper
kalibrate/kal.py
Kal.scan_channel
def scan_channel(self, channel, **kwargs): """Run Kalibrate. Supported keyword arguments: gain -- Gain in dB device -- Index of device to be used error -- Initial frequency error in ppm """ kal_run_line = fn.build_kal_scan_channel_string(self.kal_bin, channel, kwargs) raw_output = subprocess.check_output(kal_run_line.split(' '), stderr=subprocess.STDOUT) kal_normalized = fn.parse_kal_channel(raw_output) return kal_normalized
python
def scan_channel(self, channel, **kwargs): """Run Kalibrate. Supported keyword arguments: gain -- Gain in dB device -- Index of device to be used error -- Initial frequency error in ppm """ kal_run_line = fn.build_kal_scan_channel_string(self.kal_bin, channel, kwargs) raw_output = subprocess.check_output(kal_run_line.split(' '), stderr=subprocess.STDOUT) kal_normalized = fn.parse_kal_channel(raw_output) return kal_normalized
[ "def", "scan_channel", "(", "self", ",", "channel", ",", "*", "*", "kwargs", ")", ":", "kal_run_line", "=", "fn", ".", "build_kal_scan_channel_string", "(", "self", ".", "kal_bin", ",", "channel", ",", "kwargs", ")", "raw_output", "=", "subprocess", ".", "check_output", "(", "kal_run_line", ".", "split", "(", "' '", ")", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "kal_normalized", "=", "fn", ".", "parse_kal_channel", "(", "raw_output", ")", "return", "kal_normalized" ]
Run Kalibrate. Supported keyword arguments: gain -- Gain in dB device -- Index of device to be used error -- Initial frequency error in ppm
[ "Run", "Kalibrate", "." ]
80ee03ab7bd3172ac26b769d6b442960f3424b0e
https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/kal.py#L37-L52
train
a1ezzz/wasp-general
wasp_general/network/web/proto.py
WWebRequestProto.get_vars
def get_vars(self): """ Parse request path and return GET-vars :return: None or dictionary of names and tuples of values """ if self.method() != 'GET': raise RuntimeError('Unable to return get vars for non-get method') re_search = WWebRequestProto.get_vars_re.search(self.path()) if re_search is not None: return urllib.parse.parse_qs(re_search.group(1), keep_blank_values=1)
python
def get_vars(self): """ Parse request path and return GET-vars :return: None or dictionary of names and tuples of values """ if self.method() != 'GET': raise RuntimeError('Unable to return get vars for non-get method') re_search = WWebRequestProto.get_vars_re.search(self.path()) if re_search is not None: return urllib.parse.parse_qs(re_search.group(1), keep_blank_values=1)
[ "def", "get_vars", "(", "self", ")", ":", "if", "self", ".", "method", "(", ")", "!=", "'GET'", ":", "raise", "RuntimeError", "(", "'Unable to return get vars for non-get method'", ")", "re_search", "=", "WWebRequestProto", ".", "get_vars_re", ".", "search", "(", "self", ".", "path", "(", ")", ")", "if", "re_search", "is", "not", "None", ":", "return", "urllib", ".", "parse", ".", "parse_qs", "(", "re_search", ".", "group", "(", "1", ")", ",", "keep_blank_values", "=", "1", ")" ]
Parse request path and return GET-vars :return: None or dictionary of names and tuples of values
[ "Parse", "request", "path", "and", "return", "GET", "-", "vars" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/proto.py#L139-L148
train
a1ezzz/wasp-general
wasp_general/network/web/proto.py
WWebRequestProto.post_vars
def post_vars(self): """ Parse request payload and return POST-vars :return: None or dictionary of names and tuples of values """ if self.method() != 'POST': raise RuntimeError('Unable to return post vars for non-get method') content_type = self.content_type() if content_type is None or content_type.lower() != 'application/x-www-form-urlencoded': raise RuntimeError('Unable to return post vars with invalid content-type request') request_data = self.request_data() request_data = request_data.decode() if request_data is not None else '' re_search = WWebRequestProto.post_vars_re.search(request_data) if re_search is not None: return urllib.parse.parse_qs(re_search.group(1), keep_blank_values=1)
python
def post_vars(self): """ Parse request payload and return POST-vars :return: None or dictionary of names and tuples of values """ if self.method() != 'POST': raise RuntimeError('Unable to return post vars for non-get method') content_type = self.content_type() if content_type is None or content_type.lower() != 'application/x-www-form-urlencoded': raise RuntimeError('Unable to return post vars with invalid content-type request') request_data = self.request_data() request_data = request_data.decode() if request_data is not None else '' re_search = WWebRequestProto.post_vars_re.search(request_data) if re_search is not None: return urllib.parse.parse_qs(re_search.group(1), keep_blank_values=1)
[ "def", "post_vars", "(", "self", ")", ":", "if", "self", ".", "method", "(", ")", "!=", "'POST'", ":", "raise", "RuntimeError", "(", "'Unable to return post vars for non-get method'", ")", "content_type", "=", "self", ".", "content_type", "(", ")", "if", "content_type", "is", "None", "or", "content_type", ".", "lower", "(", ")", "!=", "'application/x-www-form-urlencoded'", ":", "raise", "RuntimeError", "(", "'Unable to return post vars with invalid content-type request'", ")", "request_data", "=", "self", ".", "request_data", "(", ")", "request_data", "=", "request_data", ".", "decode", "(", ")", "if", "request_data", "is", "not", "None", "else", "''", "re_search", "=", "WWebRequestProto", ".", "post_vars_re", ".", "search", "(", "request_data", ")", "if", "re_search", "is", "not", "None", ":", "return", "urllib", ".", "parse", ".", "parse_qs", "(", "re_search", ".", "group", "(", "1", ")", ",", "keep_blank_values", "=", "1", ")" ]
Parse request payload and return POST-vars :return: None or dictionary of names and tuples of values
[ "Parse", "request", "payload", "and", "return", "POST", "-", "vars" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/proto.py#L150-L166
train
a1ezzz/wasp-general
wasp_general/network/clients/virtual_dir.py
WVirtualDirectoryClient.join_path
def join_path(self, *path): """ Unite entries to generate a single path :param path: path items to unite :return: str """ path = self.directory_sep().join(path) return self.normalize_path(path)
python
def join_path(self, *path): """ Unite entries to generate a single path :param path: path items to unite :return: str """ path = self.directory_sep().join(path) return self.normalize_path(path)
[ "def", "join_path", "(", "self", ",", "*", "path", ")", ":", "path", "=", "self", ".", "directory_sep", "(", ")", ".", "join", "(", "path", ")", "return", "self", ".", "normalize_path", "(", "path", ")" ]
Unite entries to generate a single path :param path: path items to unite :return: str
[ "Unite", "entries", "to", "generate", "a", "single", "path" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/clients/virtual_dir.py#L77-L85
train
a1ezzz/wasp-general
wasp_general/network/clients/virtual_dir.py
WVirtualDirectoryClient.full_path
def full_path(self): """ Return a full path to a current session directory. A result is made by joining a start path with current session directory :return: str """ return self.normalize_path(self.directory_sep().join((self.start_path(), self.session_path())))
python
def full_path(self): """ Return a full path to a current session directory. A result is made by joining a start path with current session directory :return: str """ return self.normalize_path(self.directory_sep().join((self.start_path(), self.session_path())))
[ "def", "full_path", "(", "self", ")", ":", "return", "self", ".", "normalize_path", "(", "self", ".", "directory_sep", "(", ")", ".", "join", "(", "(", "self", ".", "start_path", "(", ")", ",", "self", ".", "session_path", "(", ")", ")", ")", ")" ]
Return a full path to a current session directory. A result is made by joining a start path with current session directory :return: str
[ "Return", "a", "full", "path", "to", "a", "current", "session", "directory", ".", "A", "result", "is", "made", "by", "joining", "a", "start", "path", "with", "current", "session", "directory" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/clients/virtual_dir.py#L105-L111
train
Chilipp/model-organization
docs/square_full.py
SquareModelOrganizer.run
def run(self, **kwargs): """ Run the model Parameters ---------- ``**kwargs`` Any other parameter for the :meth:`model_organization.ModelOrganizer.app_main` method """ from calculate import compute self.app_main(**kwargs) # get the default output name output = osp.join(self.exp_config['expdir'], 'output.dat') # save the paths in the configuration self.exp_config['output'] = output # run the model data = np.loadtxt(self.exp_config['infile']) out = compute(data) # save the output self.logger.info('Saving output data to %s', osp.relpath(output)) np.savetxt(output, out) # store some additional information in the configuration of the # experiment self.exp_config['mean'] = mean = float(out.mean()) self.exp_config['std'] = std = float(out.std()) self.logger.debug('Mean: %s, Standard deviation: %s', mean, std)
python
def run(self, **kwargs): """ Run the model Parameters ---------- ``**kwargs`` Any other parameter for the :meth:`model_organization.ModelOrganizer.app_main` method """ from calculate import compute self.app_main(**kwargs) # get the default output name output = osp.join(self.exp_config['expdir'], 'output.dat') # save the paths in the configuration self.exp_config['output'] = output # run the model data = np.loadtxt(self.exp_config['infile']) out = compute(data) # save the output self.logger.info('Saving output data to %s', osp.relpath(output)) np.savetxt(output, out) # store some additional information in the configuration of the # experiment self.exp_config['mean'] = mean = float(out.mean()) self.exp_config['std'] = std = float(out.std()) self.logger.debug('Mean: %s, Standard deviation: %s', mean, std)
[ "def", "run", "(", "self", ",", "*", "*", "kwargs", ")", ":", "from", "calculate", "import", "compute", "self", ".", "app_main", "(", "*", "*", "kwargs", ")", "# get the default output name", "output", "=", "osp", ".", "join", "(", "self", ".", "exp_config", "[", "'expdir'", "]", ",", "'output.dat'", ")", "# save the paths in the configuration", "self", ".", "exp_config", "[", "'output'", "]", "=", "output", "# run the model", "data", "=", "np", ".", "loadtxt", "(", "self", ".", "exp_config", "[", "'infile'", "]", ")", "out", "=", "compute", "(", "data", ")", "# save the output", "self", ".", "logger", ".", "info", "(", "'Saving output data to %s'", ",", "osp", ".", "relpath", "(", "output", ")", ")", "np", ".", "savetxt", "(", "output", ",", "out", ")", "# store some additional information in the configuration of the", "# experiment", "self", ".", "exp_config", "[", "'mean'", "]", "=", "mean", "=", "float", "(", "out", ".", "mean", "(", ")", ")", "self", ".", "exp_config", "[", "'std'", "]", "=", "std", "=", "float", "(", "out", ".", "std", "(", ")", ")", "self", ".", "logger", ".", "debug", "(", "'Mean: %s, Standard deviation: %s'", ",", "mean", ",", "std", ")" ]
Run the model Parameters ---------- ``**kwargs`` Any other parameter for the :meth:`model_organization.ModelOrganizer.app_main` method
[ "Run", "the", "model" ]
694d1219c7ed7e1b2b17153afa11bdc21169bca2
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/docs/square_full.py#L45-L75
train
Chilipp/model-organization
docs/square_full.py
SquareModelOrganizer.postproc
def postproc(self, close=True, **kwargs): """ Postprocess and visualize the data Parameters ---------- close: bool Close the figure at the end ``**kwargs`` Any other parameter for the :meth:`model_organization.ModelOrganizer.app_main` method """ import matplotlib.pyplot as plt import seaborn as sns # for nice plot styles self.app_main(**kwargs) # ---- load the data indata = np.loadtxt(self.exp_config['infile']) outdata = np.loadtxt(self.exp_config['output']) x_data = np.linspace(-np.pi, np.pi) # ---- make the plot fig = plt.figure() # plot input data plt.plot(x_data, indata, label='input') # plot output data plt.plot(x_data, outdata, label='squared') # draw a legend plt.legend() # use the description of the experiment as title plt.title(self.exp_config.get('description')) # ---- save the plot self.exp_config['plot'] = ofile = osp.join(self.exp_config['expdir'], 'plot.png') self.logger.info('Saving plot to %s', osp.relpath(ofile)) fig.savefig(ofile) if close: plt.close(fig)
python
def postproc(self, close=True, **kwargs): """ Postprocess and visualize the data Parameters ---------- close: bool Close the figure at the end ``**kwargs`` Any other parameter for the :meth:`model_organization.ModelOrganizer.app_main` method """ import matplotlib.pyplot as plt import seaborn as sns # for nice plot styles self.app_main(**kwargs) # ---- load the data indata = np.loadtxt(self.exp_config['infile']) outdata = np.loadtxt(self.exp_config['output']) x_data = np.linspace(-np.pi, np.pi) # ---- make the plot fig = plt.figure() # plot input data plt.plot(x_data, indata, label='input') # plot output data plt.plot(x_data, outdata, label='squared') # draw a legend plt.legend() # use the description of the experiment as title plt.title(self.exp_config.get('description')) # ---- save the plot self.exp_config['plot'] = ofile = osp.join(self.exp_config['expdir'], 'plot.png') self.logger.info('Saving plot to %s', osp.relpath(ofile)) fig.savefig(ofile) if close: plt.close(fig)
[ "def", "postproc", "(", "self", ",", "close", "=", "True", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "seaborn", "as", "sns", "# for nice plot styles", "self", ".", "app_main", "(", "*", "*", "kwargs", ")", "# ---- load the data", "indata", "=", "np", ".", "loadtxt", "(", "self", ".", "exp_config", "[", "'infile'", "]", ")", "outdata", "=", "np", ".", "loadtxt", "(", "self", ".", "exp_config", "[", "'output'", "]", ")", "x_data", "=", "np", ".", "linspace", "(", "-", "np", ".", "pi", ",", "np", ".", "pi", ")", "# ---- make the plot", "fig", "=", "plt", ".", "figure", "(", ")", "# plot input data", "plt", ".", "plot", "(", "x_data", ",", "indata", ",", "label", "=", "'input'", ")", "# plot output data", "plt", ".", "plot", "(", "x_data", ",", "outdata", ",", "label", "=", "'squared'", ")", "# draw a legend", "plt", ".", "legend", "(", ")", "# use the description of the experiment as title", "plt", ".", "title", "(", "self", ".", "exp_config", ".", "get", "(", "'description'", ")", ")", "# ---- save the plot", "self", ".", "exp_config", "[", "'plot'", "]", "=", "ofile", "=", "osp", ".", "join", "(", "self", ".", "exp_config", "[", "'expdir'", "]", ",", "'plot.png'", ")", "self", ".", "logger", ".", "info", "(", "'Saving plot to %s'", ",", "osp", ".", "relpath", "(", "ofile", ")", ")", "fig", ".", "savefig", "(", "ofile", ")", "if", "close", ":", "plt", ".", "close", "(", "fig", ")" ]
Postprocess and visualize the data Parameters ---------- close: bool Close the figure at the end ``**kwargs`` Any other parameter for the :meth:`model_organization.ModelOrganizer.app_main` method
[ "Postprocess", "and", "visualize", "the", "data" ]
694d1219c7ed7e1b2b17153afa11bdc21169bca2
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/docs/square_full.py#L77-L116
train
olitheolix/qtmacs
qtmacs/undo_stack.py
QtmacsUndoStack._push
def _push(self, undoObj: QtmacsUndoCommand): """ The actual method that adds the command object onto the stack. This method also toggles the ``nextIsRedo`` flag in the command object and, depending on its value, executes either the ``commit`` or ``reverseCommit`` method of the object. This distinction is invisible to the user but if the method is passed a copy of an older ``undoObj`` already on the stack (typically the case when called from ``undo``) then it will call the inverse command (ie a ``commit`` when the previous call was a ``reverseCommit`` and vice versa). In this manner, the undo history will contain just another command object which happens to undo a previous one, irrespective of whether the previous one was already the undoing of an even earlier one. """ self._qteStack.append(undoObj) if undoObj.nextIsRedo: undoObj.commit() else: undoObj.reverseCommit() undoObj.nextIsRedo = not undoObj.nextIsRedo
python
def _push(self, undoObj: QtmacsUndoCommand): """ The actual method that adds the command object onto the stack. This method also toggles the ``nextIsRedo`` flag in the command object and, depending on its value, executes either the ``commit`` or ``reverseCommit`` method of the object. This distinction is invisible to the user but if the method is passed a copy of an older ``undoObj`` already on the stack (typically the case when called from ``undo``) then it will call the inverse command (ie a ``commit`` when the previous call was a ``reverseCommit`` and vice versa). In this manner, the undo history will contain just another command object which happens to undo a previous one, irrespective of whether the previous one was already the undoing of an even earlier one. """ self._qteStack.append(undoObj) if undoObj.nextIsRedo: undoObj.commit() else: undoObj.reverseCommit() undoObj.nextIsRedo = not undoObj.nextIsRedo
[ "def", "_push", "(", "self", ",", "undoObj", ":", "QtmacsUndoCommand", ")", ":", "self", ".", "_qteStack", ".", "append", "(", "undoObj", ")", "if", "undoObj", ".", "nextIsRedo", ":", "undoObj", ".", "commit", "(", ")", "else", ":", "undoObj", ".", "reverseCommit", "(", ")", "undoObj", ".", "nextIsRedo", "=", "not", "undoObj", ".", "nextIsRedo" ]
The actual method that adds the command object onto the stack. This method also toggles the ``nextIsRedo`` flag in the command object and, depending on its value, executes either the ``commit`` or ``reverseCommit`` method of the object. This distinction is invisible to the user but if the method is passed a copy of an older ``undoObj`` already on the stack (typically the case when called from ``undo``) then it will call the inverse command (ie a ``commit`` when the previous call was a ``reverseCommit`` and vice versa). In this manner, the undo history will contain just another command object which happens to undo a previous one, irrespective of whether the previous one was already the undoing of an even earlier one.
[ "The", "actual", "method", "that", "adds", "the", "command", "object", "onto", "the", "stack", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/undo_stack.py#L208-L230
train
olitheolix/qtmacs
qtmacs/undo_stack.py
QtmacsUndoStack.push
def push(self, undoObj): """ Add ``undoObj`` command to stack and run its ``commit`` method. |Args| * ``undoObj`` (**QtmacsUndoCommand**): the new command object. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Check type of input arguments. if not isinstance(undoObj, QtmacsUndoCommand): raise QtmacsArgumentError('undoObj', 'QtmacsUndoCommand', inspect.stack()[0][3]) # Flag that the last action was not an undo action and push # the command to the stack. self._wasUndo = False self._push(undoObj)
python
def push(self, undoObj): """ Add ``undoObj`` command to stack and run its ``commit`` method. |Args| * ``undoObj`` (**QtmacsUndoCommand**): the new command object. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Check type of input arguments. if not isinstance(undoObj, QtmacsUndoCommand): raise QtmacsArgumentError('undoObj', 'QtmacsUndoCommand', inspect.stack()[0][3]) # Flag that the last action was not an undo action and push # the command to the stack. self._wasUndo = False self._push(undoObj)
[ "def", "push", "(", "self", ",", "undoObj", ")", ":", "# Check type of input arguments.", "if", "not", "isinstance", "(", "undoObj", ",", "QtmacsUndoCommand", ")", ":", "raise", "QtmacsArgumentError", "(", "'undoObj'", ",", "'QtmacsUndoCommand'", ",", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ")", "# Flag that the last action was not an undo action and push", "# the command to the stack.", "self", ".", "_wasUndo", "=", "False", "self", ".", "_push", "(", "undoObj", ")" ]
Add ``undoObj`` command to stack and run its ``commit`` method. |Args| * ``undoObj`` (**QtmacsUndoCommand**): the new command object. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Add", "undoObj", "command", "to", "stack", "and", "run", "its", "commit", "method", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/undo_stack.py#L232-L256
train
olitheolix/qtmacs
qtmacs/undo_stack.py
QtmacsUndoStack.undo
def undo(self): """ Undo the last command by adding its inverse action to the stack. This method automatically takes care of applying the correct inverse action when it is called consecutively (ie. without a calling ``push`` in between). The ``qtesigSavedState`` signal is triggered whenever enough undo operations have been performed to put the document back into the last saved state. ..warning: The ``qtesigSaveState`` is triggered whenever the logic of the undo operations **should** have led back to that state, but since the ``UndoStack`` only stacks and ``QtmacsUndoCommand`` objects it may well be the document is **not** in the last saved state, eg. because not all modifications were protected by undo objects, or because the ``QtmacsUndoCommand`` objects have a bug. It is therefore advisable to check in the calling class if the content is indeed identical by comparing it with a temporarily stored copy. |Args| * **None** |Signals| * ``qtesigSavedState``: the document is the last saved state. |Returns| * **None** |Raises| * **None** """ # If it is the first call to this method after a ``push`` then # reset ``qteIndex`` to the last element, otherwise just # decrease it. if not self._wasUndo: self._qteIndex = len(self._qteStack) else: self._qteIndex -= 1 # Flag that the last action was an `undo` operation. self._wasUndo = True if self._qteIndex <= 0: return # Make a copy of the command and push it to the stack. undoObj = self._qteStack[self._qteIndex - 1] undoObj = QtmacsUndoCommand(undoObj) self._push(undoObj) # If the just pushed undo object restored the last saved state # then trigger the ``qtesigSavedState`` signal and set the # _qteLastSaveUndoIndex variable again. This is necessary # because an undo command will not *remove* any elements from # the undo stack but *add* the inverse operation to the # stack. Therefore, when enough undo operations have been # performed to reach the last saved state that means that the # last addition to the stack is now implicitly the new last # save point. if (self._qteIndex - 1) == self._qteLastSavedUndoIndex: self.qtesigSavedState.emit(QtmacsMessage()) self.saveState()
python
def undo(self): """ Undo the last command by adding its inverse action to the stack. This method automatically takes care of applying the correct inverse action when it is called consecutively (ie. without a calling ``push`` in between). The ``qtesigSavedState`` signal is triggered whenever enough undo operations have been performed to put the document back into the last saved state. ..warning: The ``qtesigSaveState`` is triggered whenever the logic of the undo operations **should** have led back to that state, but since the ``UndoStack`` only stacks and ``QtmacsUndoCommand`` objects it may well be the document is **not** in the last saved state, eg. because not all modifications were protected by undo objects, or because the ``QtmacsUndoCommand`` objects have a bug. It is therefore advisable to check in the calling class if the content is indeed identical by comparing it with a temporarily stored copy. |Args| * **None** |Signals| * ``qtesigSavedState``: the document is the last saved state. |Returns| * **None** |Raises| * **None** """ # If it is the first call to this method after a ``push`` then # reset ``qteIndex`` to the last element, otherwise just # decrease it. if not self._wasUndo: self._qteIndex = len(self._qteStack) else: self._qteIndex -= 1 # Flag that the last action was an `undo` operation. self._wasUndo = True if self._qteIndex <= 0: return # Make a copy of the command and push it to the stack. undoObj = self._qteStack[self._qteIndex - 1] undoObj = QtmacsUndoCommand(undoObj) self._push(undoObj) # If the just pushed undo object restored the last saved state # then trigger the ``qtesigSavedState`` signal and set the # _qteLastSaveUndoIndex variable again. This is necessary # because an undo command will not *remove* any elements from # the undo stack but *add* the inverse operation to the # stack. Therefore, when enough undo operations have been # performed to reach the last saved state that means that the # last addition to the stack is now implicitly the new last # save point. if (self._qteIndex - 1) == self._qteLastSavedUndoIndex: self.qtesigSavedState.emit(QtmacsMessage()) self.saveState()
[ "def", "undo", "(", "self", ")", ":", "# If it is the first call to this method after a ``push`` then", "# reset ``qteIndex`` to the last element, otherwise just", "# decrease it.", "if", "not", "self", ".", "_wasUndo", ":", "self", ".", "_qteIndex", "=", "len", "(", "self", ".", "_qteStack", ")", "else", ":", "self", ".", "_qteIndex", "-=", "1", "# Flag that the last action was an `undo` operation.", "self", ".", "_wasUndo", "=", "True", "if", "self", ".", "_qteIndex", "<=", "0", ":", "return", "# Make a copy of the command and push it to the stack.", "undoObj", "=", "self", ".", "_qteStack", "[", "self", ".", "_qteIndex", "-", "1", "]", "undoObj", "=", "QtmacsUndoCommand", "(", "undoObj", ")", "self", ".", "_push", "(", "undoObj", ")", "# If the just pushed undo object restored the last saved state", "# then trigger the ``qtesigSavedState`` signal and set the", "# _qteLastSaveUndoIndex variable again. This is necessary", "# because an undo command will not *remove* any elements from", "# the undo stack but *add* the inverse operation to the", "# stack. Therefore, when enough undo operations have been", "# performed to reach the last saved state that means that the", "# last addition to the stack is now implicitly the new last", "# save point.", "if", "(", "self", ".", "_qteIndex", "-", "1", ")", "==", "self", ".", "_qteLastSavedUndoIndex", ":", "self", ".", "qtesigSavedState", ".", "emit", "(", "QtmacsMessage", "(", ")", ")", "self", ".", "saveState", "(", ")" ]
Undo the last command by adding its inverse action to the stack. This method automatically takes care of applying the correct inverse action when it is called consecutively (ie. without a calling ``push`` in between). The ``qtesigSavedState`` signal is triggered whenever enough undo operations have been performed to put the document back into the last saved state. ..warning: The ``qtesigSaveState`` is triggered whenever the logic of the undo operations **should** have led back to that state, but since the ``UndoStack`` only stacks and ``QtmacsUndoCommand`` objects it may well be the document is **not** in the last saved state, eg. because not all modifications were protected by undo objects, or because the ``QtmacsUndoCommand`` objects have a bug. It is therefore advisable to check in the calling class if the content is indeed identical by comparing it with a temporarily stored copy. |Args| * **None** |Signals| * ``qtesigSavedState``: the document is the last saved state. |Returns| * **None** |Raises| * **None**
[ "Undo", "the", "last", "command", "by", "adding", "its", "inverse", "action", "to", "the", "stack", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/undo_stack.py#L282-L350
train
olitheolix/qtmacs
qtmacs/extensions/qtmacstextedit_widget.py
UndoGenericQtmacsTextEdit.placeCursor
def placeCursor(self, pos): """ Try to place the cursor in ``line`` at ``col`` if possible. If this is not possible, then place it at the end. """ if pos > len(self.qteWidget.toPlainText()): pos = len(self.qteWidget.toPlainText()) tc = self.qteWidget.textCursor() tc.setPosition(pos) self.qteWidget.setTextCursor(tc)
python
def placeCursor(self, pos): """ Try to place the cursor in ``line`` at ``col`` if possible. If this is not possible, then place it at the end. """ if pos > len(self.qteWidget.toPlainText()): pos = len(self.qteWidget.toPlainText()) tc = self.qteWidget.textCursor() tc.setPosition(pos) self.qteWidget.setTextCursor(tc)
[ "def", "placeCursor", "(", "self", ",", "pos", ")", ":", "if", "pos", ">", "len", "(", "self", ".", "qteWidget", ".", "toPlainText", "(", ")", ")", ":", "pos", "=", "len", "(", "self", ".", "qteWidget", ".", "toPlainText", "(", ")", ")", "tc", "=", "self", ".", "qteWidget", ".", "textCursor", "(", ")", "tc", ".", "setPosition", "(", "pos", ")", "self", ".", "qteWidget", ".", "setTextCursor", "(", "tc", ")" ]
Try to place the cursor in ``line`` at ``col`` if possible. If this is not possible, then place it at the end.
[ "Try", "to", "place", "the", "cursor", "in", "line", "at", "col", "if", "possible", ".", "If", "this", "is", "not", "possible", "then", "place", "it", "at", "the", "end", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_widget.py#L99-L109
train
olitheolix/qtmacs
qtmacs/extensions/qtmacstextedit_widget.py
UndoGenericQtmacsTextEdit.reverseCommit
def reverseCommit(self): """ Reverse the document to the original state. """ print(self.after == self.before) pos = self.qteWidget.textCursor().position() self.qteWidget.setHtml(self.before) self.placeCursor(pos)
python
def reverseCommit(self): """ Reverse the document to the original state. """ print(self.after == self.before) pos = self.qteWidget.textCursor().position() self.qteWidget.setHtml(self.before) self.placeCursor(pos)
[ "def", "reverseCommit", "(", "self", ")", ":", "print", "(", "self", ".", "after", "==", "self", ".", "before", ")", "pos", "=", "self", ".", "qteWidget", ".", "textCursor", "(", ")", ".", "position", "(", ")", "self", ".", "qteWidget", ".", "setHtml", "(", "self", ".", "before", ")", "self", ".", "placeCursor", "(", "pos", ")" ]
Reverse the document to the original state.
[ "Reverse", "the", "document", "to", "the", "original", "state", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_widget.py#L125-L132
train
olitheolix/qtmacs
qtmacs/extensions/qtmacstextedit_widget.py
QtmacsTextEdit.insertFromMimeData
def insertFromMimeData(self, data): """ Paste the MIME data at the current cursor position. This method also adds another undo-object to the undo-stack. """ undoObj = UndoPaste(self, data, self.pasteCnt) self.pasteCnt += 1 self.qteUndoStack.push(undoObj)
python
def insertFromMimeData(self, data): """ Paste the MIME data at the current cursor position. This method also adds another undo-object to the undo-stack. """ undoObj = UndoPaste(self, data, self.pasteCnt) self.pasteCnt += 1 self.qteUndoStack.push(undoObj)
[ "def", "insertFromMimeData", "(", "self", ",", "data", ")", ":", "undoObj", "=", "UndoPaste", "(", "self", ",", "data", ",", "self", ".", "pasteCnt", ")", "self", ".", "pasteCnt", "+=", "1", "self", ".", "qteUndoStack", ".", "push", "(", "undoObj", ")" ]
Paste the MIME data at the current cursor position. This method also adds another undo-object to the undo-stack.
[ "Paste", "the", "MIME", "data", "at", "the", "current", "cursor", "position", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_widget.py#L322-L330
train
olitheolix/qtmacs
qtmacs/extensions/qtmacstextedit_widget.py
QtmacsTextEdit.keyPressEvent
def keyPressEvent(self, keyEvent): """ Insert the character at the current cursor position. This method also adds another undo-object to the undo-stack. """ undoObj = UndoSelfInsert(self, keyEvent.text()) self.qteUndoStack.push(undoObj)
python
def keyPressEvent(self, keyEvent): """ Insert the character at the current cursor position. This method also adds another undo-object to the undo-stack. """ undoObj = UndoSelfInsert(self, keyEvent.text()) self.qteUndoStack.push(undoObj)
[ "def", "keyPressEvent", "(", "self", ",", "keyEvent", ")", ":", "undoObj", "=", "UndoSelfInsert", "(", "self", ",", "keyEvent", ".", "text", "(", ")", ")", "self", ".", "qteUndoStack", ".", "push", "(", "undoObj", ")" ]
Insert the character at the current cursor position. This method also adds another undo-object to the undo-stack.
[ "Insert", "the", "character", "at", "the", "current", "cursor", "position", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_widget.py#L332-L339
train
vecnet/vecnet.openmalaria
vecnet/openmalaria/__init__.py
get_schema_version_from_xml
def get_schema_version_from_xml(xml): """ Get schemaVersion attribute from OpenMalaria scenario file xml - open file or content of xml document to be processed """ if isinstance(xml, six.string_types): xml = StringIO(xml) try: tree = ElementTree.parse(xml) except ParseError: # Not an XML file return None root = tree.getroot() return root.attrib.get('schemaVersion', None)
python
def get_schema_version_from_xml(xml): """ Get schemaVersion attribute from OpenMalaria scenario file xml - open file or content of xml document to be processed """ if isinstance(xml, six.string_types): xml = StringIO(xml) try: tree = ElementTree.parse(xml) except ParseError: # Not an XML file return None root = tree.getroot() return root.attrib.get('schemaVersion', None)
[ "def", "get_schema_version_from_xml", "(", "xml", ")", ":", "if", "isinstance", "(", "xml", ",", "six", ".", "string_types", ")", ":", "xml", "=", "StringIO", "(", "xml", ")", "try", ":", "tree", "=", "ElementTree", ".", "parse", "(", "xml", ")", "except", "ParseError", ":", "# Not an XML file", "return", "None", "root", "=", "tree", ".", "getroot", "(", ")", "return", "root", ".", "attrib", ".", "get", "(", "'schemaVersion'", ",", "None", ")" ]
Get schemaVersion attribute from OpenMalaria scenario file xml - open file or content of xml document to be processed
[ "Get", "schemaVersion", "attribute", "from", "OpenMalaria", "scenario", "file", "xml", "-", "open", "file", "or", "content", "of", "xml", "document", "to", "be", "processed" ]
795bc9d1b81a6c664f14879edda7a7c41188e95a
https://github.com/vecnet/vecnet.openmalaria/blob/795bc9d1b81a6c664f14879edda7a7c41188e95a/vecnet/openmalaria/__init__.py#L38-L50
train
blockstack-packages/blockstack-profiles-py
blockstack_profiles/legacy_format.py
format_account
def format_account(service_name, data): """ Given profile data and the name of a social media service, format it for the zone file. @serviceName: name of the service @data: legacy profile verification Returns the formatted account on success, as a dict. """ if "username" not in data: raise KeyError("Account is missing a username") account = { "@type": "Account", "service": service_name, "identifier": data["username"], "proofType": "http" } if (data.has_key(service_name) and data[service_name].has_key("proof") and data[service_name]["proof"].has_key("url")): account["proofUrl"] = data[service_name]["proof"]["url"] return account
python
def format_account(service_name, data): """ Given profile data and the name of a social media service, format it for the zone file. @serviceName: name of the service @data: legacy profile verification Returns the formatted account on success, as a dict. """ if "username" not in data: raise KeyError("Account is missing a username") account = { "@type": "Account", "service": service_name, "identifier": data["username"], "proofType": "http" } if (data.has_key(service_name) and data[service_name].has_key("proof") and data[service_name]["proof"].has_key("url")): account["proofUrl"] = data[service_name]["proof"]["url"] return account
[ "def", "format_account", "(", "service_name", ",", "data", ")", ":", "if", "\"username\"", "not", "in", "data", ":", "raise", "KeyError", "(", "\"Account is missing a username\"", ")", "account", "=", "{", "\"@type\"", ":", "\"Account\"", ",", "\"service\"", ":", "service_name", ",", "\"identifier\"", ":", "data", "[", "\"username\"", "]", ",", "\"proofType\"", ":", "\"http\"", "}", "if", "(", "data", ".", "has_key", "(", "service_name", ")", "and", "data", "[", "service_name", "]", ".", "has_key", "(", "\"proof\"", ")", "and", "data", "[", "service_name", "]", "[", "\"proof\"", "]", ".", "has_key", "(", "\"url\"", ")", ")", ":", "account", "[", "\"proofUrl\"", "]", "=", "data", "[", "service_name", "]", "[", "\"proof\"", "]", "[", "\"url\"", "]", "return", "account" ]
Given profile data and the name of a social media service, format it for the zone file. @serviceName: name of the service @data: legacy profile verification Returns the formatted account on success, as a dict.
[ "Given", "profile", "data", "and", "the", "name", "of", "a", "social", "media", "service", "format", "it", "for", "the", "zone", "file", "." ]
103783798df78cf0f007801e79ec6298f00b2817
https://github.com/blockstack-packages/blockstack-profiles-py/blob/103783798df78cf0f007801e79ec6298f00b2817/blockstack_profiles/legacy_format.py#L63-L91
train
a1ezzz/wasp-general
wasp_general/types/binarray.py
WBinArray.swipe
def swipe(self): """ Mirror current array value in reverse. Bits that had greater index will have lesser index, and vice-versa. This method doesn't change this array. It creates a new one and return it as a result. :return: WBinArray """ result = WBinArray(0, len(self)) for i in range(len(self)): result[len(self) - i - 1] = self[i] return result
python
def swipe(self): """ Mirror current array value in reverse. Bits that had greater index will have lesser index, and vice-versa. This method doesn't change this array. It creates a new one and return it as a result. :return: WBinArray """ result = WBinArray(0, len(self)) for i in range(len(self)): result[len(self) - i - 1] = self[i] return result
[ "def", "swipe", "(", "self", ")", ":", "result", "=", "WBinArray", "(", "0", ",", "len", "(", "self", ")", ")", "for", "i", "in", "range", "(", "len", "(", "self", ")", ")", ":", "result", "[", "len", "(", "self", ")", "-", "i", "-", "1", "]", "=", "self", "[", "i", "]", "return", "result" ]
Mirror current array value in reverse. Bits that had greater index will have lesser index, and vice-versa. This method doesn't change this array. It creates a new one and return it as a result. :return: WBinArray
[ "Mirror", "current", "array", "value", "in", "reverse", ".", "Bits", "that", "had", "greater", "index", "will", "have", "lesser", "index", "and", "vice", "-", "versa", ".", "This", "method", "doesn", "t", "change", "this", "array", ".", "It", "creates", "a", "new", "one", "and", "return", "it", "as", "a", "result", "." ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/types/binarray.py#L233-L242
train
sublee/etc
etc/__init__.py
etcd
def etcd(url=DEFAULT_URL, mock=False, **kwargs): """Creates an etcd client.""" if mock: from etc.adapters.mock import MockAdapter adapter_class = MockAdapter else: from etc.adapters.etcd import EtcdAdapter adapter_class = EtcdAdapter return Client(adapter_class(url, **kwargs))
python
def etcd(url=DEFAULT_URL, mock=False, **kwargs): """Creates an etcd client.""" if mock: from etc.adapters.mock import MockAdapter adapter_class = MockAdapter else: from etc.adapters.etcd import EtcdAdapter adapter_class = EtcdAdapter return Client(adapter_class(url, **kwargs))
[ "def", "etcd", "(", "url", "=", "DEFAULT_URL", ",", "mock", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "mock", ":", "from", "etc", ".", "adapters", ".", "mock", "import", "MockAdapter", "adapter_class", "=", "MockAdapter", "else", ":", "from", "etc", ".", "adapters", ".", "etcd", "import", "EtcdAdapter", "adapter_class", "=", "EtcdAdapter", "return", "Client", "(", "adapter_class", "(", "url", ",", "*", "*", "kwargs", ")", ")" ]
Creates an etcd client.
[ "Creates", "an", "etcd", "client", "." ]
f2be64604da5af0d7739cfacf36f55712f0fc5cb
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/__init__.py#L60-L68
train
OpenGov/og-python-utils
ogutils/functions/operators.py
repeat_call
def repeat_call(func, retries, *args, **kwargs): ''' Tries a total of 'retries' times to execute callable before failing. ''' retries = max(0, int(retries)) try_num = 0 while True: if try_num == retries: return func(*args, **kwargs) else: try: return func(*args, **kwargs) except Exception as e: if isinstance(e, KeyboardInterrupt): raise e try_num += 1
python
def repeat_call(func, retries, *args, **kwargs): ''' Tries a total of 'retries' times to execute callable before failing. ''' retries = max(0, int(retries)) try_num = 0 while True: if try_num == retries: return func(*args, **kwargs) else: try: return func(*args, **kwargs) except Exception as e: if isinstance(e, KeyboardInterrupt): raise e try_num += 1
[ "def", "repeat_call", "(", "func", ",", "retries", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "retries", "=", "max", "(", "0", ",", "int", "(", "retries", ")", ")", "try_num", "=", "0", "while", "True", ":", "if", "try_num", "==", "retries", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "if", "isinstance", "(", "e", ",", "KeyboardInterrupt", ")", ":", "raise", "e", "try_num", "+=", "1" ]
Tries a total of 'retries' times to execute callable before failing.
[ "Tries", "a", "total", "of", "retries", "times", "to", "execute", "callable", "before", "failing", "." ]
00f44927383dd1bd6348f47302c4453d56963479
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/functions/operators.py#L15-L30
train
olitheolix/qtmacs
qtmacs/type_check.py
type_check
def type_check(func_handle): """ Ensure arguments have the type specified in the annotation signature. Example:: def foo(a, b:str, c:int =0, d:(int, list)=None): pass This function accepts an arbitrary parameter for ``a``, a string for ``b``, an integer for ``c`` which defaults to 0, and either an integer or a list for ``d`` and defaults to ``None``. The decorator does not check return types and considers derived classes as valid (ie. the type check uses the Python native ``isinstance`` to do its job). For instance, if the function is defined as:: @type_check def foo(a: QtGui.QWidget): pass then the following two calls will both succeed:: foo(QtGui.QWidget()) foo(QtGui.QTextEdit()) because ``QTextEdit`` inherits ``QWidget``. .. note:: the check is skipped if the value (either passed or by default) is **None**. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ def checkType(var_name, var_val, annot): # Retrieve the annotation for this variable and determine # if the type of that variable matches with the annotation. # This annotation is stored in the dictionary ``annot`` # but contains only variables for such an annotation exists, # hence the if/else branch. if var_name in annot: # Fetch the type-annotation of the variable. var_anno = annot[var_name] # Skip the type check if the variable is none, otherwise # check if it is a derived class. The only exception from # the latter rule are binary values, because in Python # # >> isinstance(False, int) # True # # and warrants a special check. if var_val is None: type_ok = True elif (type(var_val) is bool): type_ok = (type(var_val) in var_anno) else: type_ok = True in [isinstance(var_val, _) for _ in var_anno] else: # Variable without annotation are compatible by assumption. var_anno = 'Unspecified' type_ok = True # If the check failed then raise a QtmacsArgumentError. if not type_ok: args = (var_name, func_handle.__name__, var_anno, type(var_val)) raise QtmacsArgumentError(*args) @functools.wraps(func_handle) def wrapper(*args, **kwds): # Retrieve information about all arguments passed to the function, # as well as their annotations in the function signature. argspec = inspect.getfullargspec(func_handle) # Convert all variable annotations that were not specified as a # tuple or list into one, eg. str --> will become (str,) annot = {} for key, val in argspec.annotations.items(): if isinstance(val, tuple) or isinstance(val, list): annot[key] = val else: annot[key] = val, # Note the trailing colon! # Prefix the argspec.defaults tuple with **None** elements to make # its length equal to the number of variables (for sanity in the # code below). Since **None** types are always ignored by this # decorator this change is neutral. if argspec.defaults is None: defaults = tuple([None] * len(argspec.args)) else: num_none = len(argspec.args) - len(argspec.defaults) defaults = tuple([None] * num_none) + argspec.defaults # Shorthand for the number of unnamed arguments. ofs = len(args) # Process the unnamed arguments. These are always the first ``ofs`` # elements in argspec.args. for idx, var_name in enumerate(argspec.args[:ofs]): # Look up the value in the ``args`` variable. var_val = args[idx] checkType(var_name, var_val, annot) # Process the named- and default arguments. for idx, var_name in enumerate(argspec.args[ofs:]): # Extract the argument value. If it was passed to the # function as a named (ie. keyword) argument then extract # it from ``kwds``, otherwise look it up in the tuple with # the default values. if var_name in kwds: var_val = kwds[var_name] else: var_val = defaults[idx + ofs] checkType(var_name, var_val, annot) return func_handle(*args, **kwds) return wrapper
python
def type_check(func_handle): """ Ensure arguments have the type specified in the annotation signature. Example:: def foo(a, b:str, c:int =0, d:(int, list)=None): pass This function accepts an arbitrary parameter for ``a``, a string for ``b``, an integer for ``c`` which defaults to 0, and either an integer or a list for ``d`` and defaults to ``None``. The decorator does not check return types and considers derived classes as valid (ie. the type check uses the Python native ``isinstance`` to do its job). For instance, if the function is defined as:: @type_check def foo(a: QtGui.QWidget): pass then the following two calls will both succeed:: foo(QtGui.QWidget()) foo(QtGui.QTextEdit()) because ``QTextEdit`` inherits ``QWidget``. .. note:: the check is skipped if the value (either passed or by default) is **None**. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ def checkType(var_name, var_val, annot): # Retrieve the annotation for this variable and determine # if the type of that variable matches with the annotation. # This annotation is stored in the dictionary ``annot`` # but contains only variables for such an annotation exists, # hence the if/else branch. if var_name in annot: # Fetch the type-annotation of the variable. var_anno = annot[var_name] # Skip the type check if the variable is none, otherwise # check if it is a derived class. The only exception from # the latter rule are binary values, because in Python # # >> isinstance(False, int) # True # # and warrants a special check. if var_val is None: type_ok = True elif (type(var_val) is bool): type_ok = (type(var_val) in var_anno) else: type_ok = True in [isinstance(var_val, _) for _ in var_anno] else: # Variable without annotation are compatible by assumption. var_anno = 'Unspecified' type_ok = True # If the check failed then raise a QtmacsArgumentError. if not type_ok: args = (var_name, func_handle.__name__, var_anno, type(var_val)) raise QtmacsArgumentError(*args) @functools.wraps(func_handle) def wrapper(*args, **kwds): # Retrieve information about all arguments passed to the function, # as well as their annotations in the function signature. argspec = inspect.getfullargspec(func_handle) # Convert all variable annotations that were not specified as a # tuple or list into one, eg. str --> will become (str,) annot = {} for key, val in argspec.annotations.items(): if isinstance(val, tuple) or isinstance(val, list): annot[key] = val else: annot[key] = val, # Note the trailing colon! # Prefix the argspec.defaults tuple with **None** elements to make # its length equal to the number of variables (for sanity in the # code below). Since **None** types are always ignored by this # decorator this change is neutral. if argspec.defaults is None: defaults = tuple([None] * len(argspec.args)) else: num_none = len(argspec.args) - len(argspec.defaults) defaults = tuple([None] * num_none) + argspec.defaults # Shorthand for the number of unnamed arguments. ofs = len(args) # Process the unnamed arguments. These are always the first ``ofs`` # elements in argspec.args. for idx, var_name in enumerate(argspec.args[:ofs]): # Look up the value in the ``args`` variable. var_val = args[idx] checkType(var_name, var_val, annot) # Process the named- and default arguments. for idx, var_name in enumerate(argspec.args[ofs:]): # Extract the argument value. If it was passed to the # function as a named (ie. keyword) argument then extract # it from ``kwds``, otherwise look it up in the tuple with # the default values. if var_name in kwds: var_val = kwds[var_name] else: var_val = defaults[idx + ofs] checkType(var_name, var_val, annot) return func_handle(*args, **kwds) return wrapper
[ "def", "type_check", "(", "func_handle", ")", ":", "def", "checkType", "(", "var_name", ",", "var_val", ",", "annot", ")", ":", "# Retrieve the annotation for this variable and determine", "# if the type of that variable matches with the annotation.", "# This annotation is stored in the dictionary ``annot``", "# but contains only variables for such an annotation exists,", "# hence the if/else branch.", "if", "var_name", "in", "annot", ":", "# Fetch the type-annotation of the variable.", "var_anno", "=", "annot", "[", "var_name", "]", "# Skip the type check if the variable is none, otherwise", "# check if it is a derived class. The only exception from", "# the latter rule are binary values, because in Python", "#", "# >> isinstance(False, int)", "# True", "#", "# and warrants a special check.", "if", "var_val", "is", "None", ":", "type_ok", "=", "True", "elif", "(", "type", "(", "var_val", ")", "is", "bool", ")", ":", "type_ok", "=", "(", "type", "(", "var_val", ")", "in", "var_anno", ")", "else", ":", "type_ok", "=", "True", "in", "[", "isinstance", "(", "var_val", ",", "_", ")", "for", "_", "in", "var_anno", "]", "else", ":", "# Variable without annotation are compatible by assumption.", "var_anno", "=", "'Unspecified'", "type_ok", "=", "True", "# If the check failed then raise a QtmacsArgumentError.", "if", "not", "type_ok", ":", "args", "=", "(", "var_name", ",", "func_handle", ".", "__name__", ",", "var_anno", ",", "type", "(", "var_val", ")", ")", "raise", "QtmacsArgumentError", "(", "*", "args", ")", "@", "functools", ".", "wraps", "(", "func_handle", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "# Retrieve information about all arguments passed to the function,", "# as well as their annotations in the function signature.", "argspec", "=", "inspect", ".", "getfullargspec", "(", "func_handle", ")", "# Convert all variable annotations that were not specified as a", "# tuple or list into one, eg. str --> will become (str,)", "annot", "=", "{", "}", "for", "key", ",", "val", "in", "argspec", ".", "annotations", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "tuple", ")", "or", "isinstance", "(", "val", ",", "list", ")", ":", "annot", "[", "key", "]", "=", "val", "else", ":", "annot", "[", "key", "]", "=", "val", ",", "# Note the trailing colon!", "# Prefix the argspec.defaults tuple with **None** elements to make", "# its length equal to the number of variables (for sanity in the", "# code below). Since **None** types are always ignored by this", "# decorator this change is neutral.", "if", "argspec", ".", "defaults", "is", "None", ":", "defaults", "=", "tuple", "(", "[", "None", "]", "*", "len", "(", "argspec", ".", "args", ")", ")", "else", ":", "num_none", "=", "len", "(", "argspec", ".", "args", ")", "-", "len", "(", "argspec", ".", "defaults", ")", "defaults", "=", "tuple", "(", "[", "None", "]", "*", "num_none", ")", "+", "argspec", ".", "defaults", "# Shorthand for the number of unnamed arguments.", "ofs", "=", "len", "(", "args", ")", "# Process the unnamed arguments. These are always the first ``ofs``", "# elements in argspec.args.", "for", "idx", ",", "var_name", "in", "enumerate", "(", "argspec", ".", "args", "[", ":", "ofs", "]", ")", ":", "# Look up the value in the ``args`` variable.", "var_val", "=", "args", "[", "idx", "]", "checkType", "(", "var_name", ",", "var_val", ",", "annot", ")", "# Process the named- and default arguments.", "for", "idx", ",", "var_name", "in", "enumerate", "(", "argspec", ".", "args", "[", "ofs", ":", "]", ")", ":", "# Extract the argument value. If it was passed to the", "# function as a named (ie. keyword) argument then extract", "# it from ``kwds``, otherwise look it up in the tuple with", "# the default values.", "if", "var_name", "in", "kwds", ":", "var_val", "=", "kwds", "[", "var_name", "]", "else", ":", "var_val", "=", "defaults", "[", "idx", "+", "ofs", "]", "checkType", "(", "var_name", ",", "var_val", ",", "annot", ")", "return", "func_handle", "(", "*", "args", ",", "*", "*", "kwds", ")", "return", "wrapper" ]
Ensure arguments have the type specified in the annotation signature. Example:: def foo(a, b:str, c:int =0, d:(int, list)=None): pass This function accepts an arbitrary parameter for ``a``, a string for ``b``, an integer for ``c`` which defaults to 0, and either an integer or a list for ``d`` and defaults to ``None``. The decorator does not check return types and considers derived classes as valid (ie. the type check uses the Python native ``isinstance`` to do its job). For instance, if the function is defined as:: @type_check def foo(a: QtGui.QWidget): pass then the following two calls will both succeed:: foo(QtGui.QWidget()) foo(QtGui.QTextEdit()) because ``QTextEdit`` inherits ``QWidget``. .. note:: the check is skipped if the value (either passed or by default) is **None**. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Ensure", "arguments", "have", "the", "type", "specified", "in", "the", "annotation", "signature", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/type_check.py#L41-L158
train
a1ezzz/wasp-general
wasp_general/network/service.py
WIOLoopService.start
def start(self): """ Set up handler and start loop :return: None """ timeout = self.timeout() if timeout is not None and timeout > 0: self.__loop.add_timeout(timedelta(0, timeout), self.stop) self.handler().setup_handler(self.loop()) self.loop().start() self.handler().loop_stopped()
python
def start(self): """ Set up handler and start loop :return: None """ timeout = self.timeout() if timeout is not None and timeout > 0: self.__loop.add_timeout(timedelta(0, timeout), self.stop) self.handler().setup_handler(self.loop()) self.loop().start() self.handler().loop_stopped()
[ "def", "start", "(", "self", ")", ":", "timeout", "=", "self", ".", "timeout", "(", ")", "if", "timeout", "is", "not", "None", "and", "timeout", ">", "0", ":", "self", ".", "__loop", ".", "add_timeout", "(", "timedelta", "(", "0", ",", "timeout", ")", ",", "self", ".", "stop", ")", "self", ".", "handler", "(", ")", ".", "setup_handler", "(", "self", ".", "loop", "(", ")", ")", "self", ".", "loop", "(", ")", ".", "start", "(", ")", "self", ".", "handler", "(", ")", ".", "loop_stopped", "(", ")" ]
Set up handler and start loop :return: None
[ "Set", "up", "handler", "and", "start", "loop" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/service.py#L104-L114
train
a1ezzz/wasp-general
wasp_general/network/service.py
WNativeSocketHandler.loop_stopped
def loop_stopped(self): """ Terminate socket connection because of stopping loop :return: None """ transport = self.transport() if self.server_mode() is True: transport.close_server_socket(self.config()) else: transport.close_client_socket(self.config())
python
def loop_stopped(self): """ Terminate socket connection because of stopping loop :return: None """ transport = self.transport() if self.server_mode() is True: transport.close_server_socket(self.config()) else: transport.close_client_socket(self.config())
[ "def", "loop_stopped", "(", "self", ")", ":", "transport", "=", "self", ".", "transport", "(", ")", "if", "self", ".", "server_mode", "(", ")", "is", "True", ":", "transport", ".", "close_server_socket", "(", "self", ".", "config", "(", ")", ")", "else", ":", "transport", ".", "close_client_socket", "(", "self", ".", "config", "(", ")", ")" ]
Terminate socket connection because of stopping loop :return: None
[ "Terminate", "socket", "connection", "because", "of", "stopping", "loop" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/service.py#L248-L257
train
a1ezzz/wasp-general
wasp_general/network/service.py
WZMQService.discard_queue_messages
def discard_queue_messages(self): """ Sometimes it is necessary to drop undelivered messages. These messages may be stored in different caches, for example in a zmq socket queue. With different zmq flags we can tweak zmq sockets and contexts no to keep those messages. But inside ZMQStream class there is a queue that can not be cleaned other way then the way it does in this method. So yes, it is dirty to access protected members, and yes it can be broken at any moment. And yes without correct locking procedure there is a possibility of unpredicted behaviour. But still - there is no other way to drop undelivered messages Discussion of the problem: https://github.com/zeromq/pyzmq/issues/1095 :return: None """ zmq_stream_queue = self.handler().stream()._send_queue while not zmq_stream_queue.empty(): try: zmq_stream_queue.get(False) except queue.Empty: continue zmq_stream_queue.task_done()
python
def discard_queue_messages(self): """ Sometimes it is necessary to drop undelivered messages. These messages may be stored in different caches, for example in a zmq socket queue. With different zmq flags we can tweak zmq sockets and contexts no to keep those messages. But inside ZMQStream class there is a queue that can not be cleaned other way then the way it does in this method. So yes, it is dirty to access protected members, and yes it can be broken at any moment. And yes without correct locking procedure there is a possibility of unpredicted behaviour. But still - there is no other way to drop undelivered messages Discussion of the problem: https://github.com/zeromq/pyzmq/issues/1095 :return: None """ zmq_stream_queue = self.handler().stream()._send_queue while not zmq_stream_queue.empty(): try: zmq_stream_queue.get(False) except queue.Empty: continue zmq_stream_queue.task_done()
[ "def", "discard_queue_messages", "(", "self", ")", ":", "zmq_stream_queue", "=", "self", ".", "handler", "(", ")", ".", "stream", "(", ")", ".", "_send_queue", "while", "not", "zmq_stream_queue", ".", "empty", "(", ")", ":", "try", ":", "zmq_stream_queue", ".", "get", "(", "False", ")", "except", "queue", ".", "Empty", ":", "continue", "zmq_stream_queue", ".", "task_done", "(", ")" ]
Sometimes it is necessary to drop undelivered messages. These messages may be stored in different caches, for example in a zmq socket queue. With different zmq flags we can tweak zmq sockets and contexts no to keep those messages. But inside ZMQStream class there is a queue that can not be cleaned other way then the way it does in this method. So yes, it is dirty to access protected members, and yes it can be broken at any moment. And yes without correct locking procedure there is a possibility of unpredicted behaviour. But still - there is no other way to drop undelivered messages Discussion of the problem: https://github.com/zeromq/pyzmq/issues/1095 :return: None
[ "Sometimes", "it", "is", "necessary", "to", "drop", "undelivered", "messages", ".", "These", "messages", "may", "be", "stored", "in", "different", "caches", "for", "example", "in", "a", "zmq", "socket", "queue", ".", "With", "different", "zmq", "flags", "we", "can", "tweak", "zmq", "sockets", "and", "contexts", "no", "to", "keep", "those", "messages", ".", "But", "inside", "ZMQStream", "class", "there", "is", "a", "queue", "that", "can", "not", "be", "cleaned", "other", "way", "then", "the", "way", "it", "does", "in", "this", "method", ".", "So", "yes", "it", "is", "dirty", "to", "access", "protected", "members", "and", "yes", "it", "can", "be", "broken", "at", "any", "moment", ".", "And", "yes", "without", "correct", "locking", "procedure", "there", "is", "a", "possibility", "of", "unpredicted", "behaviour", ".", "But", "still", "-", "there", "is", "no", "other", "way", "to", "drop", "undelivered", "messages" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/service.py#L402-L421
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsEventFilter.qteProcessKey
def qteProcessKey(self, event, targetObj): """ If the key completes a valid key sequence then queue the associated macro. |Args| * ``targetObj`` (**QObject**): the source of the event (see Qt documentation). * ``event_qt`` (**QKeyEvent**): information about the key event (see Qt documentation). |Returns| * **Bool**: **True** if there was at least a partial match and **False** if the key sequence was invalid. |Raises| * **None** """ # Announce the key and targeted Qtmacs widget. msgObj = QtmacsMessage((targetObj, event), None) msgObj.setSignalName('qtesigKeypressed') self.qteMain.qtesigKeypressed.emit(msgObj) # Ignore standalone <Shift>, <Ctrl>, <Win>, <Alt>, and <AltGr> # events. if event.key() in (QtCore.Qt.Key_Shift, QtCore.Qt.Key_Control, QtCore.Qt.Key_Meta, QtCore.Qt.Key_Alt, QtCore.Qt.Key_AltGr): return False # Add the latest key stroke to the current key sequence. self._keysequence.appendQKeyEvent(event) # Determine if the widget was registered with qteAddWidget isRegisteredWidget = hasattr(targetObj, '_qteAdmin') if isRegisteredWidget and hasattr(targetObj._qteAdmin, 'keyMap'): keyMap = targetObj._qteAdmin.keyMap else: keyMap = self.qteMain._qteGlobalKeyMapByReference() # See if there is a match with an entry from the key map of # the current object. If ``isPartialMatch`` is True then the # key sequence is potentially incomplete, but not invalid. # If ``macroName`` is not **None** then it is indeed complete. (macroName, isPartialMatch) = keyMap.match(self._keysequence) # Make a convenience copy of the key sequence. keyseq_copy = QtmacsKeysequence(self._keysequence) if isPartialMatch: # Reset the key combination history if a valid macro was # found so that the next key that arrives starts a new key # sequence. if macroName is None: # Report a partially completed key-sequence. msgObj = QtmacsMessage(keyseq_copy, None) msgObj.setSignalName('qtesigKeyseqPartial') self.qteMain.qtesigKeyseqPartial.emit(msgObj) else: # Execute the macro if requested. if self._qteFlagRunMacro: self.qteMain.qteRunMacro(macroName, targetObj, keyseq_copy) # Announce that the key sequence lead to a valid macro. msgObj = QtmacsMessage((macroName, keyseq_copy), None) msgObj.setSignalName('qtesigKeyseqComplete') self.qteMain.qtesigKeyseqComplete.emit(msgObj) self._keysequence.reset() else: if isRegisteredWidget: # Announce (and log) that the key sequence is invalid. However, # format the key string to Html first, eg. "<ctrl>-x i" to # "<b>&lt;Ctrl&gt;+x i</b>". tmp = keyseq_copy.toString() tmp = tmp.replace('<', '&lt;') tmp = tmp.replace('>', '&gt;') msg = 'No macro is bound to <b>{}</b>.'.format(tmp) self.qteMain.qteLogger.warning(msg) msgObj = QtmacsMessage(keyseq_copy, None) msgObj.setSignalName('qtesigKeyseqInvalid') self.qteMain.qtesigKeyseqInvalid.emit(msgObj) else: # If we are in this branch then the widet is part of the # Qtmacs widget hierachy yet was not registered with # the qteAddWidget method. In this case use the QtDelivery # macro to pass on whatever the event was (assuming # macro processing is enabled). if self._qteFlagRunMacro: self.qteMain.qteRunMacro( self.QtDelivery, targetObj, keyseq_copy) self._keysequence.reset() # Announce that Qtmacs has processed another key event. The # outcome of this processing is communicated along with the # signal. msgObj = QtmacsMessage((targetObj, keyseq_copy, macroName), None) msgObj.setSignalName('qtesigKeyparsed') self.qteMain.qtesigKeyparsed.emit(msgObj) return isPartialMatch
python
def qteProcessKey(self, event, targetObj): """ If the key completes a valid key sequence then queue the associated macro. |Args| * ``targetObj`` (**QObject**): the source of the event (see Qt documentation). * ``event_qt`` (**QKeyEvent**): information about the key event (see Qt documentation). |Returns| * **Bool**: **True** if there was at least a partial match and **False** if the key sequence was invalid. |Raises| * **None** """ # Announce the key and targeted Qtmacs widget. msgObj = QtmacsMessage((targetObj, event), None) msgObj.setSignalName('qtesigKeypressed') self.qteMain.qtesigKeypressed.emit(msgObj) # Ignore standalone <Shift>, <Ctrl>, <Win>, <Alt>, and <AltGr> # events. if event.key() in (QtCore.Qt.Key_Shift, QtCore.Qt.Key_Control, QtCore.Qt.Key_Meta, QtCore.Qt.Key_Alt, QtCore.Qt.Key_AltGr): return False # Add the latest key stroke to the current key sequence. self._keysequence.appendQKeyEvent(event) # Determine if the widget was registered with qteAddWidget isRegisteredWidget = hasattr(targetObj, '_qteAdmin') if isRegisteredWidget and hasattr(targetObj._qteAdmin, 'keyMap'): keyMap = targetObj._qteAdmin.keyMap else: keyMap = self.qteMain._qteGlobalKeyMapByReference() # See if there is a match with an entry from the key map of # the current object. If ``isPartialMatch`` is True then the # key sequence is potentially incomplete, but not invalid. # If ``macroName`` is not **None** then it is indeed complete. (macroName, isPartialMatch) = keyMap.match(self._keysequence) # Make a convenience copy of the key sequence. keyseq_copy = QtmacsKeysequence(self._keysequence) if isPartialMatch: # Reset the key combination history if a valid macro was # found so that the next key that arrives starts a new key # sequence. if macroName is None: # Report a partially completed key-sequence. msgObj = QtmacsMessage(keyseq_copy, None) msgObj.setSignalName('qtesigKeyseqPartial') self.qteMain.qtesigKeyseqPartial.emit(msgObj) else: # Execute the macro if requested. if self._qteFlagRunMacro: self.qteMain.qteRunMacro(macroName, targetObj, keyseq_copy) # Announce that the key sequence lead to a valid macro. msgObj = QtmacsMessage((macroName, keyseq_copy), None) msgObj.setSignalName('qtesigKeyseqComplete') self.qteMain.qtesigKeyseqComplete.emit(msgObj) self._keysequence.reset() else: if isRegisteredWidget: # Announce (and log) that the key sequence is invalid. However, # format the key string to Html first, eg. "<ctrl>-x i" to # "<b>&lt;Ctrl&gt;+x i</b>". tmp = keyseq_copy.toString() tmp = tmp.replace('<', '&lt;') tmp = tmp.replace('>', '&gt;') msg = 'No macro is bound to <b>{}</b>.'.format(tmp) self.qteMain.qteLogger.warning(msg) msgObj = QtmacsMessage(keyseq_copy, None) msgObj.setSignalName('qtesigKeyseqInvalid') self.qteMain.qtesigKeyseqInvalid.emit(msgObj) else: # If we are in this branch then the widet is part of the # Qtmacs widget hierachy yet was not registered with # the qteAddWidget method. In this case use the QtDelivery # macro to pass on whatever the event was (assuming # macro processing is enabled). if self._qteFlagRunMacro: self.qteMain.qteRunMacro( self.QtDelivery, targetObj, keyseq_copy) self._keysequence.reset() # Announce that Qtmacs has processed another key event. The # outcome of this processing is communicated along with the # signal. msgObj = QtmacsMessage((targetObj, keyseq_copy, macroName), None) msgObj.setSignalName('qtesigKeyparsed') self.qteMain.qtesigKeyparsed.emit(msgObj) return isPartialMatch
[ "def", "qteProcessKey", "(", "self", ",", "event", ",", "targetObj", ")", ":", "# Announce the key and targeted Qtmacs widget.", "msgObj", "=", "QtmacsMessage", "(", "(", "targetObj", ",", "event", ")", ",", "None", ")", "msgObj", ".", "setSignalName", "(", "'qtesigKeypressed'", ")", "self", ".", "qteMain", ".", "qtesigKeypressed", ".", "emit", "(", "msgObj", ")", "# Ignore standalone <Shift>, <Ctrl>, <Win>, <Alt>, and <AltGr>", "# events.", "if", "event", ".", "key", "(", ")", "in", "(", "QtCore", ".", "Qt", ".", "Key_Shift", ",", "QtCore", ".", "Qt", ".", "Key_Control", ",", "QtCore", ".", "Qt", ".", "Key_Meta", ",", "QtCore", ".", "Qt", ".", "Key_Alt", ",", "QtCore", ".", "Qt", ".", "Key_AltGr", ")", ":", "return", "False", "# Add the latest key stroke to the current key sequence.", "self", ".", "_keysequence", ".", "appendQKeyEvent", "(", "event", ")", "# Determine if the widget was registered with qteAddWidget", "isRegisteredWidget", "=", "hasattr", "(", "targetObj", ",", "'_qteAdmin'", ")", "if", "isRegisteredWidget", "and", "hasattr", "(", "targetObj", ".", "_qteAdmin", ",", "'keyMap'", ")", ":", "keyMap", "=", "targetObj", ".", "_qteAdmin", ".", "keyMap", "else", ":", "keyMap", "=", "self", ".", "qteMain", ".", "_qteGlobalKeyMapByReference", "(", ")", "# See if there is a match with an entry from the key map of", "# the current object. If ``isPartialMatch`` is True then the", "# key sequence is potentially incomplete, but not invalid.", "# If ``macroName`` is not **None** then it is indeed complete.", "(", "macroName", ",", "isPartialMatch", ")", "=", "keyMap", ".", "match", "(", "self", ".", "_keysequence", ")", "# Make a convenience copy of the key sequence.", "keyseq_copy", "=", "QtmacsKeysequence", "(", "self", ".", "_keysequence", ")", "if", "isPartialMatch", ":", "# Reset the key combination history if a valid macro was", "# found so that the next key that arrives starts a new key", "# sequence.", "if", "macroName", "is", "None", ":", "# Report a partially completed key-sequence.", "msgObj", "=", "QtmacsMessage", "(", "keyseq_copy", ",", "None", ")", "msgObj", ".", "setSignalName", "(", "'qtesigKeyseqPartial'", ")", "self", ".", "qteMain", ".", "qtesigKeyseqPartial", ".", "emit", "(", "msgObj", ")", "else", ":", "# Execute the macro if requested.", "if", "self", ".", "_qteFlagRunMacro", ":", "self", ".", "qteMain", ".", "qteRunMacro", "(", "macroName", ",", "targetObj", ",", "keyseq_copy", ")", "# Announce that the key sequence lead to a valid macro.", "msgObj", "=", "QtmacsMessage", "(", "(", "macroName", ",", "keyseq_copy", ")", ",", "None", ")", "msgObj", ".", "setSignalName", "(", "'qtesigKeyseqComplete'", ")", "self", ".", "qteMain", ".", "qtesigKeyseqComplete", ".", "emit", "(", "msgObj", ")", "self", ".", "_keysequence", ".", "reset", "(", ")", "else", ":", "if", "isRegisteredWidget", ":", "# Announce (and log) that the key sequence is invalid. However,", "# format the key string to Html first, eg. \"<ctrl>-x i\" to", "# \"<b>&lt;Ctrl&gt;+x i</b>\".", "tmp", "=", "keyseq_copy", ".", "toString", "(", ")", "tmp", "=", "tmp", ".", "replace", "(", "'<'", ",", "'&lt;'", ")", "tmp", "=", "tmp", ".", "replace", "(", "'>'", ",", "'&gt;'", ")", "msg", "=", "'No macro is bound to <b>{}</b>.'", ".", "format", "(", "tmp", ")", "self", ".", "qteMain", ".", "qteLogger", ".", "warning", "(", "msg", ")", "msgObj", "=", "QtmacsMessage", "(", "keyseq_copy", ",", "None", ")", "msgObj", ".", "setSignalName", "(", "'qtesigKeyseqInvalid'", ")", "self", ".", "qteMain", ".", "qtesigKeyseqInvalid", ".", "emit", "(", "msgObj", ")", "else", ":", "# If we are in this branch then the widet is part of the", "# Qtmacs widget hierachy yet was not registered with", "# the qteAddWidget method. In this case use the QtDelivery", "# macro to pass on whatever the event was (assuming", "# macro processing is enabled).", "if", "self", ".", "_qteFlagRunMacro", ":", "self", ".", "qteMain", ".", "qteRunMacro", "(", "self", ".", "QtDelivery", ",", "targetObj", ",", "keyseq_copy", ")", "self", ".", "_keysequence", ".", "reset", "(", ")", "# Announce that Qtmacs has processed another key event. The", "# outcome of this processing is communicated along with the", "# signal.", "msgObj", "=", "QtmacsMessage", "(", "(", "targetObj", ",", "keyseq_copy", ",", "macroName", ")", ",", "None", ")", "msgObj", ".", "setSignalName", "(", "'qtesigKeyparsed'", ")", "self", ".", "qteMain", ".", "qtesigKeyparsed", ".", "emit", "(", "msgObj", ")", "return", "isPartialMatch" ]
If the key completes a valid key sequence then queue the associated macro. |Args| * ``targetObj`` (**QObject**): the source of the event (see Qt documentation). * ``event_qt`` (**QKeyEvent**): information about the key event (see Qt documentation). |Returns| * **Bool**: **True** if there was at least a partial match and **False** if the key sequence was invalid. |Raises| * **None**
[ "If", "the", "key", "completes", "a", "valid", "key", "sequence", "then", "queue", "the", "associated", "macro", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L345-L447
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsSplitter.qteAdjustWidgetSizes
def qteAdjustWidgetSizes(self, handlePos: int=None): """ Adjust the widget size inside the splitter according to ``handlePos``. See ``pos`` argument in _qteSplitterMovedEvent for a more detailed explanation. If ``handlePos`` is **None**, then the widgets are assigne equal size. |Args| * ``handlePos`` (**int**): splitter position relative to the origin. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Do not adjust anything if there are less than two widgets. if self.count() < 2: return if self.orientation() == QtCore.Qt.Horizontal: totDim = self.size().width() - self.handleWidth() else: totDim = self.size().height() - self.handleWidth() # Assign both widgets the same size if no handle position provided. if handlePos is None: handlePos = (totDim + self.handleWidth()) // 2 # Sanity check. if not (0 <= handlePos <= totDim): return # Compute widget sizes according to handle position. newSize = [handlePos, totDim - handlePos] # Assign the widget sizes. self.setSizes(newSize)
python
def qteAdjustWidgetSizes(self, handlePos: int=None): """ Adjust the widget size inside the splitter according to ``handlePos``. See ``pos`` argument in _qteSplitterMovedEvent for a more detailed explanation. If ``handlePos`` is **None**, then the widgets are assigne equal size. |Args| * ``handlePos`` (**int**): splitter position relative to the origin. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Do not adjust anything if there are less than two widgets. if self.count() < 2: return if self.orientation() == QtCore.Qt.Horizontal: totDim = self.size().width() - self.handleWidth() else: totDim = self.size().height() - self.handleWidth() # Assign both widgets the same size if no handle position provided. if handlePos is None: handlePos = (totDim + self.handleWidth()) // 2 # Sanity check. if not (0 <= handlePos <= totDim): return # Compute widget sizes according to handle position. newSize = [handlePos, totDim - handlePos] # Assign the widget sizes. self.setSizes(newSize)
[ "def", "qteAdjustWidgetSizes", "(", "self", ",", "handlePos", ":", "int", "=", "None", ")", ":", "# Do not adjust anything if there are less than two widgets.", "if", "self", ".", "count", "(", ")", "<", "2", ":", "return", "if", "self", ".", "orientation", "(", ")", "==", "QtCore", ".", "Qt", ".", "Horizontal", ":", "totDim", "=", "self", ".", "size", "(", ")", ".", "width", "(", ")", "-", "self", ".", "handleWidth", "(", ")", "else", ":", "totDim", "=", "self", ".", "size", "(", ")", ".", "height", "(", ")", "-", "self", ".", "handleWidth", "(", ")", "# Assign both widgets the same size if no handle position provided.", "if", "handlePos", "is", "None", ":", "handlePos", "=", "(", "totDim", "+", "self", ".", "handleWidth", "(", ")", ")", "//", "2", "# Sanity check.", "if", "not", "(", "0", "<=", "handlePos", "<=", "totDim", ")", ":", "return", "# Compute widget sizes according to handle position.", "newSize", "=", "[", "handlePos", ",", "totDim", "-", "handlePos", "]", "# Assign the widget sizes.", "self", ".", "setSizes", "(", "newSize", ")" ]
Adjust the widget size inside the splitter according to ``handlePos``. See ``pos`` argument in _qteSplitterMovedEvent for a more detailed explanation. If ``handlePos`` is **None**, then the widgets are assigne equal size. |Args| * ``handlePos`` (**int**): splitter position relative to the origin. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Adjust", "the", "widget", "size", "inside", "the", "splitter", "according", "to", "handlePos", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L569-L611
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsSplitter.qteAddWidget
def qteAddWidget(self, widget): """ Add a widget to the splitter and make it visible. The only differences between this- and the native ``QSplitter.addWidget()`` method are 1. ``widget`` must have a ``QtmacsAdmin`` structure to ensure it is a ``QtmacsApplet`` or a ``QtmacsSplitter``, 2. ``widget`` is automatically made visible. Both actions are mostly for convenience because adding ``widget`` to a QtmacsSplitter is tantamount to displaying it. |Args| * ``widget`` (**QWidget**): the widget to add to the splitter. |Returns| * **None** |Raises| * **None** """ # Add ``widget`` to the splitter. self.addWidget(widget) # Show ``widget``. If it is a ``QtmacsSplitter`` instance then its # show() methods has no argument, whereas ``QtmacsApplet`` instances # have overloaded show() methods because they should not be called # unless you really know what you are doing (it will mess with Qtmacs # layout engine). if widget._qteAdmin.widgetSignature == '__QtmacsLayoutSplitter__': widget.show() else: widget.show(True) # Adjust the sizes of the widgets inside the splitter according to # the handle position. self.qteAdjustWidgetSizes()
python
def qteAddWidget(self, widget): """ Add a widget to the splitter and make it visible. The only differences between this- and the native ``QSplitter.addWidget()`` method are 1. ``widget`` must have a ``QtmacsAdmin`` structure to ensure it is a ``QtmacsApplet`` or a ``QtmacsSplitter``, 2. ``widget`` is automatically made visible. Both actions are mostly for convenience because adding ``widget`` to a QtmacsSplitter is tantamount to displaying it. |Args| * ``widget`` (**QWidget**): the widget to add to the splitter. |Returns| * **None** |Raises| * **None** """ # Add ``widget`` to the splitter. self.addWidget(widget) # Show ``widget``. If it is a ``QtmacsSplitter`` instance then its # show() methods has no argument, whereas ``QtmacsApplet`` instances # have overloaded show() methods because they should not be called # unless you really know what you are doing (it will mess with Qtmacs # layout engine). if widget._qteAdmin.widgetSignature == '__QtmacsLayoutSplitter__': widget.show() else: widget.show(True) # Adjust the sizes of the widgets inside the splitter according to # the handle position. self.qteAdjustWidgetSizes()
[ "def", "qteAddWidget", "(", "self", ",", "widget", ")", ":", "# Add ``widget`` to the splitter.", "self", ".", "addWidget", "(", "widget", ")", "# Show ``widget``. If it is a ``QtmacsSplitter`` instance then its", "# show() methods has no argument, whereas ``QtmacsApplet`` instances", "# have overloaded show() methods because they should not be called", "# unless you really know what you are doing (it will mess with Qtmacs", "# layout engine).", "if", "widget", ".", "_qteAdmin", ".", "widgetSignature", "==", "'__QtmacsLayoutSplitter__'", ":", "widget", ".", "show", "(", ")", "else", ":", "widget", ".", "show", "(", "True", ")", "# Adjust the sizes of the widgets inside the splitter according to", "# the handle position.", "self", ".", "qteAdjustWidgetSizes", "(", ")" ]
Add a widget to the splitter and make it visible. The only differences between this- and the native ``QSplitter.addWidget()`` method are 1. ``widget`` must have a ``QtmacsAdmin`` structure to ensure it is a ``QtmacsApplet`` or a ``QtmacsSplitter``, 2. ``widget`` is automatically made visible. Both actions are mostly for convenience because adding ``widget`` to a QtmacsSplitter is tantamount to displaying it. |Args| * ``widget`` (**QWidget**): the widget to add to the splitter. |Returns| * **None** |Raises| * **None**
[ "Add", "a", "widget", "to", "the", "splitter", "and", "make", "it", "visible", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L613-L654
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsSplitter.qteInsertWidget
def qteInsertWidget(self, idx, widget): """ Insert ``widget`` to the splitter at the specified ``idx`` position and make it visible. The only differences between this- and the native ``QSplitter.insertWidget()`` method are 1. ``widget`` must have a ``QtmacsAdmin`` structure to ensure it is a ``QtmacsApplet`` or a ``QtmacsSplitter``, 2. ``widget`` is automatically made visible. Both actions are mostly for convenience because adding ``widget`` to a QtmacsSplitter is tantamount to displaying it. |Args| * ``idx`` (**int**): non-negative index position. * ``widget`` (**QWidget**): the widget to insert into the splitter at position ``idx``. |Returns| * **None** |Raises| * **None** """ # Insert the widget into the splitter. self.insertWidget(idx, widget) # Show ``widget``. If it is a ``QtmacsSplitter`` instance then its # show() methods has no argument, whereas ``QtmacsApplet`` instances # have overloaded show() methods because they should not be called # unless you really know what you are doing (it will mess with Qtmacs # layout engine). if widget._qteAdmin.widgetSignature == '__QtmacsLayoutSplitter__': widget.show() else: widget.show(True) # Adjust the sizes of the widgets inside the splitter according to # the handle position. self.qteAdjustWidgetSizes()
python
def qteInsertWidget(self, idx, widget): """ Insert ``widget`` to the splitter at the specified ``idx`` position and make it visible. The only differences between this- and the native ``QSplitter.insertWidget()`` method are 1. ``widget`` must have a ``QtmacsAdmin`` structure to ensure it is a ``QtmacsApplet`` or a ``QtmacsSplitter``, 2. ``widget`` is automatically made visible. Both actions are mostly for convenience because adding ``widget`` to a QtmacsSplitter is tantamount to displaying it. |Args| * ``idx`` (**int**): non-negative index position. * ``widget`` (**QWidget**): the widget to insert into the splitter at position ``idx``. |Returns| * **None** |Raises| * **None** """ # Insert the widget into the splitter. self.insertWidget(idx, widget) # Show ``widget``. If it is a ``QtmacsSplitter`` instance then its # show() methods has no argument, whereas ``QtmacsApplet`` instances # have overloaded show() methods because they should not be called # unless you really know what you are doing (it will mess with Qtmacs # layout engine). if widget._qteAdmin.widgetSignature == '__QtmacsLayoutSplitter__': widget.show() else: widget.show(True) # Adjust the sizes of the widgets inside the splitter according to # the handle position. self.qteAdjustWidgetSizes()
[ "def", "qteInsertWidget", "(", "self", ",", "idx", ",", "widget", ")", ":", "# Insert the widget into the splitter.", "self", ".", "insertWidget", "(", "idx", ",", "widget", ")", "# Show ``widget``. If it is a ``QtmacsSplitter`` instance then its", "# show() methods has no argument, whereas ``QtmacsApplet`` instances", "# have overloaded show() methods because they should not be called", "# unless you really know what you are doing (it will mess with Qtmacs", "# layout engine).", "if", "widget", ".", "_qteAdmin", ".", "widgetSignature", "==", "'__QtmacsLayoutSplitter__'", ":", "widget", ".", "show", "(", ")", "else", ":", "widget", ".", "show", "(", "True", ")", "# Adjust the sizes of the widgets inside the splitter according to", "# the handle position.", "self", ".", "qteAdjustWidgetSizes", "(", ")" ]
Insert ``widget`` to the splitter at the specified ``idx`` position and make it visible. The only differences between this- and the native ``QSplitter.insertWidget()`` method are 1. ``widget`` must have a ``QtmacsAdmin`` structure to ensure it is a ``QtmacsApplet`` or a ``QtmacsSplitter``, 2. ``widget`` is automatically made visible. Both actions are mostly for convenience because adding ``widget`` to a QtmacsSplitter is tantamount to displaying it. |Args| * ``idx`` (**int**): non-negative index position. * ``widget`` (**QWidget**): the widget to insert into the splitter at position ``idx``. |Returns| * **None** |Raises| * **None**
[ "Insert", "widget", "to", "the", "splitter", "at", "the", "specified", "idx", "position", "and", "make", "it", "visible", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L656-L700
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.timerEvent
def timerEvent(self, event): """ Trigger the focus manager and work off all queued macros. The main purpose of using this timer event is to postpone updating the visual layout of Qtmacs until all macro code has been fully executed. Furthermore, this GUI update needs to happen in between any two macros. This method will trigger itself until all macros in the queue were executed. |Args| * ``event`` (**QTimerEvent**): Qt native event description. |Returns| * **None** |Raises| * **None** """ self.killTimer(event.timerId()) if event.timerId() == self._qteTimerRunMacro: # Declare the macro execution timer event handled. self._qteTimerRunMacro = None # If we are in this branch then the focus manager was just # executed, the event loop has updated all widgets and # cleared out all signals, and there is at least one macro # in the macro queue and/or at least one key to emulate # in the key queue. Execute the macros/keys and trigger # the focus manager after each. The macro queue is cleared # out first and the keys are only emulated if no more # macros are left. while True: if len(self._qteMacroQueue) > 0: (macroName, qteWidget, event) = self._qteMacroQueue.pop(0) self._qteRunQueuedMacro(macroName, qteWidget, event) elif len(self._qteKeyEmulationQueue) > 0: # Determine the recipient of the event. This can # be, in order of preference, the active widget in # the active applet, or just the active applet (if # it has no widget inside), or the active window # (if no applets are available). if self._qteActiveApplet is None: receiver = self.qteActiveWindow() else: if self._qteActiveApplet._qteActiveWidget is None: receiver = self._qteActiveApplet else: receiver = self._qteActiveApplet._qteActiveWidget # Call the event filter directly and trigger the focus # manager again. keysequence = self._qteKeyEmulationQueue.pop(0) self._qteEventFilter.eventFilter(receiver, keysequence) else: # If we are in this branch then no more macros are left # to run. So trigger the focus manager one more time # and then leave the while-loop. self._qteFocusManager() break self._qteFocusManager() elif event.timerId() == self.debugTimer: #win = self.qteNextWindow() #self.qteMakeWindowActive(win) #self.debugTimer = self.startTimer(1000) pass else: # Should not happen. print('Unknown timer ID') pass
python
def timerEvent(self, event): """ Trigger the focus manager and work off all queued macros. The main purpose of using this timer event is to postpone updating the visual layout of Qtmacs until all macro code has been fully executed. Furthermore, this GUI update needs to happen in between any two macros. This method will trigger itself until all macros in the queue were executed. |Args| * ``event`` (**QTimerEvent**): Qt native event description. |Returns| * **None** |Raises| * **None** """ self.killTimer(event.timerId()) if event.timerId() == self._qteTimerRunMacro: # Declare the macro execution timer event handled. self._qteTimerRunMacro = None # If we are in this branch then the focus manager was just # executed, the event loop has updated all widgets and # cleared out all signals, and there is at least one macro # in the macro queue and/or at least one key to emulate # in the key queue. Execute the macros/keys and trigger # the focus manager after each. The macro queue is cleared # out first and the keys are only emulated if no more # macros are left. while True: if len(self._qteMacroQueue) > 0: (macroName, qteWidget, event) = self._qteMacroQueue.pop(0) self._qteRunQueuedMacro(macroName, qteWidget, event) elif len(self._qteKeyEmulationQueue) > 0: # Determine the recipient of the event. This can # be, in order of preference, the active widget in # the active applet, or just the active applet (if # it has no widget inside), or the active window # (if no applets are available). if self._qteActiveApplet is None: receiver = self.qteActiveWindow() else: if self._qteActiveApplet._qteActiveWidget is None: receiver = self._qteActiveApplet else: receiver = self._qteActiveApplet._qteActiveWidget # Call the event filter directly and trigger the focus # manager again. keysequence = self._qteKeyEmulationQueue.pop(0) self._qteEventFilter.eventFilter(receiver, keysequence) else: # If we are in this branch then no more macros are left # to run. So trigger the focus manager one more time # and then leave the while-loop. self._qteFocusManager() break self._qteFocusManager() elif event.timerId() == self.debugTimer: #win = self.qteNextWindow() #self.qteMakeWindowActive(win) #self.debugTimer = self.startTimer(1000) pass else: # Should not happen. print('Unknown timer ID') pass
[ "def", "timerEvent", "(", "self", ",", "event", ")", ":", "self", ".", "killTimer", "(", "event", ".", "timerId", "(", ")", ")", "if", "event", ".", "timerId", "(", ")", "==", "self", ".", "_qteTimerRunMacro", ":", "# Declare the macro execution timer event handled.", "self", ".", "_qteTimerRunMacro", "=", "None", "# If we are in this branch then the focus manager was just", "# executed, the event loop has updated all widgets and", "# cleared out all signals, and there is at least one macro", "# in the macro queue and/or at least one key to emulate", "# in the key queue. Execute the macros/keys and trigger", "# the focus manager after each. The macro queue is cleared", "# out first and the keys are only emulated if no more", "# macros are left.", "while", "True", ":", "if", "len", "(", "self", ".", "_qteMacroQueue", ")", ">", "0", ":", "(", "macroName", ",", "qteWidget", ",", "event", ")", "=", "self", ".", "_qteMacroQueue", ".", "pop", "(", "0", ")", "self", ".", "_qteRunQueuedMacro", "(", "macroName", ",", "qteWidget", ",", "event", ")", "elif", "len", "(", "self", ".", "_qteKeyEmulationQueue", ")", ">", "0", ":", "# Determine the recipient of the event. This can", "# be, in order of preference, the active widget in", "# the active applet, or just the active applet (if", "# it has no widget inside), or the active window", "# (if no applets are available).", "if", "self", ".", "_qteActiveApplet", "is", "None", ":", "receiver", "=", "self", ".", "qteActiveWindow", "(", ")", "else", ":", "if", "self", ".", "_qteActiveApplet", ".", "_qteActiveWidget", "is", "None", ":", "receiver", "=", "self", ".", "_qteActiveApplet", "else", ":", "receiver", "=", "self", ".", "_qteActiveApplet", ".", "_qteActiveWidget", "# Call the event filter directly and trigger the focus", "# manager again.", "keysequence", "=", "self", ".", "_qteKeyEmulationQueue", ".", "pop", "(", "0", ")", "self", ".", "_qteEventFilter", ".", "eventFilter", "(", "receiver", ",", "keysequence", ")", "else", ":", "# If we are in this branch then no more macros are left", "# to run. So trigger the focus manager one more time", "# and then leave the while-loop.", "self", ".", "_qteFocusManager", "(", ")", "break", "self", ".", "_qteFocusManager", "(", ")", "elif", "event", ".", "timerId", "(", ")", "==", "self", ".", "debugTimer", ":", "#win = self.qteNextWindow()", "#self.qteMakeWindowActive(win)", "#self.debugTimer = self.startTimer(1000)", "pass", "else", ":", "# Should not happen.", "print", "(", "'Unknown timer ID'", ")", "pass" ]
Trigger the focus manager and work off all queued macros. The main purpose of using this timer event is to postpone updating the visual layout of Qtmacs until all macro code has been fully executed. Furthermore, this GUI update needs to happen in between any two macros. This method will trigger itself until all macros in the queue were executed. |Args| * ``event`` (**QTimerEvent**): Qt native event description. |Returns| * **None** |Raises| * **None**
[ "Trigger", "the", "focus", "manager", "and", "work", "off", "all", "queued", "macros", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1003-L1078
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain._qteMouseClicked
def _qteMouseClicked(self, widgetObj): """ Update the Qtmacs internal focus state as the result of a mouse click. |Args| * ``new`` (**QWidget**): the widget that received the focus. |Returns| * **None** |Raises| * **None** """ # ------------------------------------------------------------ # The following cases for widgetObj have to be distinguished: # 1: not part of the Qtmacs widget hierarchy # 2: part of the Qtmacs widget hierarchy but not registered # 3: registered with Qtmacs and an applet # 4: registered with Qtmacs and anything but an applet # ------------------------------------------------------------ # Case 1: return immediately if widgetObj is not part of the # Qtmacs widget hierarchy; otherwise, declare the applet # containing the widgetObj active. app = qteGetAppletFromWidget(widgetObj) if app is None: return else: self._qteActiveApplet = app # Case 2: unregistered widgets are activated immediately. if not hasattr(widgetObj, '_qteAdmin'): self._qteActiveApplet.qteMakeWidgetActive(widgetObj) else: if app._qteAdmin.isQtmacsApplet: # Case 3: widgetObj is a QtmacsApplet instance; do not # focus any of its widgets as the focus manager will # take care of it. self._qteActiveApplet.qteMakeWidgetActive(None) else: # Case 4: widgetObj was registered with qteAddWidget # and can thus be focused directly. self._qteActiveApplet.qteMakeWidgetActive(widgetObj) # Trigger the focus manager. self._qteFocusManager()
python
def _qteMouseClicked(self, widgetObj): """ Update the Qtmacs internal focus state as the result of a mouse click. |Args| * ``new`` (**QWidget**): the widget that received the focus. |Returns| * **None** |Raises| * **None** """ # ------------------------------------------------------------ # The following cases for widgetObj have to be distinguished: # 1: not part of the Qtmacs widget hierarchy # 2: part of the Qtmacs widget hierarchy but not registered # 3: registered with Qtmacs and an applet # 4: registered with Qtmacs and anything but an applet # ------------------------------------------------------------ # Case 1: return immediately if widgetObj is not part of the # Qtmacs widget hierarchy; otherwise, declare the applet # containing the widgetObj active. app = qteGetAppletFromWidget(widgetObj) if app is None: return else: self._qteActiveApplet = app # Case 2: unregistered widgets are activated immediately. if not hasattr(widgetObj, '_qteAdmin'): self._qteActiveApplet.qteMakeWidgetActive(widgetObj) else: if app._qteAdmin.isQtmacsApplet: # Case 3: widgetObj is a QtmacsApplet instance; do not # focus any of its widgets as the focus manager will # take care of it. self._qteActiveApplet.qteMakeWidgetActive(None) else: # Case 4: widgetObj was registered with qteAddWidget # and can thus be focused directly. self._qteActiveApplet.qteMakeWidgetActive(widgetObj) # Trigger the focus manager. self._qteFocusManager()
[ "def", "_qteMouseClicked", "(", "self", ",", "widgetObj", ")", ":", "# ------------------------------------------------------------", "# The following cases for widgetObj have to be distinguished:", "# 1: not part of the Qtmacs widget hierarchy", "# 2: part of the Qtmacs widget hierarchy but not registered", "# 3: registered with Qtmacs and an applet", "# 4: registered with Qtmacs and anything but an applet", "# ------------------------------------------------------------", "# Case 1: return immediately if widgetObj is not part of the", "# Qtmacs widget hierarchy; otherwise, declare the applet", "# containing the widgetObj active.", "app", "=", "qteGetAppletFromWidget", "(", "widgetObj", ")", "if", "app", "is", "None", ":", "return", "else", ":", "self", ".", "_qteActiveApplet", "=", "app", "# Case 2: unregistered widgets are activated immediately.", "if", "not", "hasattr", "(", "widgetObj", ",", "'_qteAdmin'", ")", ":", "self", ".", "_qteActiveApplet", ".", "qteMakeWidgetActive", "(", "widgetObj", ")", "else", ":", "if", "app", ".", "_qteAdmin", ".", "isQtmacsApplet", ":", "# Case 3: widgetObj is a QtmacsApplet instance; do not", "# focus any of its widgets as the focus manager will", "# take care of it.", "self", ".", "_qteActiveApplet", ".", "qteMakeWidgetActive", "(", "None", ")", "else", ":", "# Case 4: widgetObj was registered with qteAddWidget", "# and can thus be focused directly.", "self", ".", "_qteActiveApplet", ".", "qteMakeWidgetActive", "(", "widgetObj", ")", "# Trigger the focus manager.", "self", ".", "_qteFocusManager", "(", ")" ]
Update the Qtmacs internal focus state as the result of a mouse click. |Args| * ``new`` (**QWidget**): the widget that received the focus. |Returns| * **None** |Raises| * **None**
[ "Update", "the", "Qtmacs", "internal", "focus", "state", "as", "the", "result", "of", "a", "mouse", "click", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1286-L1335
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteFocusChanged
def qteFocusChanged(self, old, new): """ Slot for Qt native focus-changed signal to notify Qtmacs if the window was switched. .. note: This method is work in progress. """ # Do nothing if new is old. if old is new: return # If neither is None but both have the same top level # window then do nothing. if (old is not None) and (new is not None): if old.isActiveWindow() is new.isActiveWindow(): return
python
def qteFocusChanged(self, old, new): """ Slot for Qt native focus-changed signal to notify Qtmacs if the window was switched. .. note: This method is work in progress. """ # Do nothing if new is old. if old is new: return # If neither is None but both have the same top level # window then do nothing. if (old is not None) and (new is not None): if old.isActiveWindow() is new.isActiveWindow(): return
[ "def", "qteFocusChanged", "(", "self", ",", "old", ",", "new", ")", ":", "# Do nothing if new is old.", "if", "old", "is", "new", ":", "return", "# If neither is None but both have the same top level", "# window then do nothing.", "if", "(", "old", "is", "not", "None", ")", "and", "(", "new", "is", "not", "None", ")", ":", "if", "old", ".", "isActiveWindow", "(", ")", "is", "new", ".", "isActiveWindow", "(", ")", ":", "return" ]
Slot for Qt native focus-changed signal to notify Qtmacs if the window was switched. .. note: This method is work in progress.
[ "Slot", "for", "Qt", "native", "focus", "-", "changed", "signal", "to", "notify", "Qtmacs", "if", "the", "window", "was", "switched", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1337-L1352
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteIsMiniApplet
def qteIsMiniApplet(self, obj): """ Test if instance ``obj`` is a mini applet. |Args| * ``obj`` (**object**): object to test. |Returns| * **bool**: whether or not ``obj`` is the mini applet. |Raises| * **None** """ try: ret = obj._qteAdmin.isMiniApplet except AttributeError: ret = False return ret
python
def qteIsMiniApplet(self, obj): """ Test if instance ``obj`` is a mini applet. |Args| * ``obj`` (**object**): object to test. |Returns| * **bool**: whether or not ``obj`` is the mini applet. |Raises| * **None** """ try: ret = obj._qteAdmin.isMiniApplet except AttributeError: ret = False return ret
[ "def", "qteIsMiniApplet", "(", "self", ",", "obj", ")", ":", "try", ":", "ret", "=", "obj", ".", "_qteAdmin", ".", "isMiniApplet", "except", "AttributeError", ":", "ret", "=", "False", "return", "ret" ]
Test if instance ``obj`` is a mini applet. |Args| * ``obj`` (**object**): object to test. |Returns| * **bool**: whether or not ``obj`` is the mini applet. |Raises| * **None**
[ "Test", "if", "instance", "obj", "is", "a", "mini", "applet", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1407-L1428
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteNewWindow
def qteNewWindow(self, pos: QtCore.QRect=None, windowID: str=None): """ Create a new, empty window with ``windowID`` at position ``pos``. |Args| * ``pos`` (**QRect**): size and position of new window. * ``windowID`` (**str**): unique window ID. |Returns| * **QtmacsWindow**: reference to the just created window instance. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Compile a list of all window IDs. winIDList = [_._qteWindowID for _ in self._qteWindowList] # If no window ID was supplied simply count until a new and # unique ID was found. if windowID is None: cnt = 0 while str(cnt) in winIDList: cnt += 1 windowID = str(cnt) # If no position was specified use a default one. if pos is None: pos = QtCore.QRect(500, 300, 1000, 500) # Raise an error if a window with this ID already exists. if windowID in winIDList: msg = 'Window with ID <b>{}</b> already exists.'.format(windowID) raise QtmacsOtherError(msg) # Instantiate a new window object. window = QtmacsWindow(pos, windowID) # Add the new window to the window list and make it visible. self._qteWindowList.append(window) window.show() # Trigger the focus manager once the event loop is in control again. return window
python
def qteNewWindow(self, pos: QtCore.QRect=None, windowID: str=None): """ Create a new, empty window with ``windowID`` at position ``pos``. |Args| * ``pos`` (**QRect**): size and position of new window. * ``windowID`` (**str**): unique window ID. |Returns| * **QtmacsWindow**: reference to the just created window instance. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Compile a list of all window IDs. winIDList = [_._qteWindowID for _ in self._qteWindowList] # If no window ID was supplied simply count until a new and # unique ID was found. if windowID is None: cnt = 0 while str(cnt) in winIDList: cnt += 1 windowID = str(cnt) # If no position was specified use a default one. if pos is None: pos = QtCore.QRect(500, 300, 1000, 500) # Raise an error if a window with this ID already exists. if windowID in winIDList: msg = 'Window with ID <b>{}</b> already exists.'.format(windowID) raise QtmacsOtherError(msg) # Instantiate a new window object. window = QtmacsWindow(pos, windowID) # Add the new window to the window list and make it visible. self._qteWindowList.append(window) window.show() # Trigger the focus manager once the event loop is in control again. return window
[ "def", "qteNewWindow", "(", "self", ",", "pos", ":", "QtCore", ".", "QRect", "=", "None", ",", "windowID", ":", "str", "=", "None", ")", ":", "# Compile a list of all window IDs.", "winIDList", "=", "[", "_", ".", "_qteWindowID", "for", "_", "in", "self", ".", "_qteWindowList", "]", "# If no window ID was supplied simply count until a new and", "# unique ID was found.", "if", "windowID", "is", "None", ":", "cnt", "=", "0", "while", "str", "(", "cnt", ")", "in", "winIDList", ":", "cnt", "+=", "1", "windowID", "=", "str", "(", "cnt", ")", "# If no position was specified use a default one.", "if", "pos", "is", "None", ":", "pos", "=", "QtCore", ".", "QRect", "(", "500", ",", "300", ",", "1000", ",", "500", ")", "# Raise an error if a window with this ID already exists.", "if", "windowID", "in", "winIDList", ":", "msg", "=", "'Window with ID <b>{}</b> already exists.'", ".", "format", "(", "windowID", ")", "raise", "QtmacsOtherError", "(", "msg", ")", "# Instantiate a new window object.", "window", "=", "QtmacsWindow", "(", "pos", ",", "windowID", ")", "# Add the new window to the window list and make it visible.", "self", ".", "_qteWindowList", ".", "append", "(", "window", ")", "window", ".", "show", "(", ")", "# Trigger the focus manager once the event loop is in control again.", "return", "window" ]
Create a new, empty window with ``windowID`` at position ``pos``. |Args| * ``pos`` (**QRect**): size and position of new window. * ``windowID`` (**str**): unique window ID. |Returns| * **QtmacsWindow**: reference to the just created window instance. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Create", "a", "new", "empty", "window", "with", "windowID", "at", "position", "pos", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1431-L1477
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteMakeWindowActive
def qteMakeWindowActive(self, windowObj: QtmacsWindow): """ Make the window ``windowObj`` active and focus the first applet therein. |Args| * ``windowObj`` (**QtmacsWindow**): window to activate. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ if windowObj in self._qteWindowList: # This will trigger the focusChanged slot which, in # conjunction with the focus manager, will take care of # the rest. Note that ``activateWindow`` is a native Qt # method, not a Qtmacs invention. windowObj.activateWindow() else: self.qteLogger.warning('Window to activate does not exist')
python
def qteMakeWindowActive(self, windowObj: QtmacsWindow): """ Make the window ``windowObj`` active and focus the first applet therein. |Args| * ``windowObj`` (**QtmacsWindow**): window to activate. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ if windowObj in self._qteWindowList: # This will trigger the focusChanged slot which, in # conjunction with the focus manager, will take care of # the rest. Note that ``activateWindow`` is a native Qt # method, not a Qtmacs invention. windowObj.activateWindow() else: self.qteLogger.warning('Window to activate does not exist')
[ "def", "qteMakeWindowActive", "(", "self", ",", "windowObj", ":", "QtmacsWindow", ")", ":", "if", "windowObj", "in", "self", ".", "_qteWindowList", ":", "# This will trigger the focusChanged slot which, in", "# conjunction with the focus manager, will take care of", "# the rest. Note that ``activateWindow`` is a native Qt", "# method, not a Qtmacs invention.", "windowObj", ".", "activateWindow", "(", ")", "else", ":", "self", ".", "qteLogger", ".", "warning", "(", "'Window to activate does not exist'", ")" ]
Make the window ``windowObj`` active and focus the first applet therein. |Args| * ``windowObj`` (**QtmacsWindow**): window to activate. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Make", "the", "window", "windowObj", "active", "and", "focus", "the", "first", "applet", "therein", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1480-L1505
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteActiveWindow
def qteActiveWindow(self): """ Return the currently active ``QtmacsWindow`` object. If no Qtmacs window is currently active (for instance because the user is working with another application at the moment) then the method returns the first window in the window list. The method only returns **None** if the window list is empty, which is definitively a bug. |Args| * **None** |Returns| * **QtmacsWindow**: the currently active window or **None** if no window is currently active. |Raises| * **None** """ if len(self._qteWindowList) == 0: self.qteLogger.critical('The window list is empty.') return None elif len(self._qteWindowList) == 1: return self._qteWindowList[0] else: # Find the active window. for win in self._qteWindowList: if win.isActiveWindow(): return win # Return the first window if none is active. return self._qteWindowList[0]
python
def qteActiveWindow(self): """ Return the currently active ``QtmacsWindow`` object. If no Qtmacs window is currently active (for instance because the user is working with another application at the moment) then the method returns the first window in the window list. The method only returns **None** if the window list is empty, which is definitively a bug. |Args| * **None** |Returns| * **QtmacsWindow**: the currently active window or **None** if no window is currently active. |Raises| * **None** """ if len(self._qteWindowList) == 0: self.qteLogger.critical('The window list is empty.') return None elif len(self._qteWindowList) == 1: return self._qteWindowList[0] else: # Find the active window. for win in self._qteWindowList: if win.isActiveWindow(): return win # Return the first window if none is active. return self._qteWindowList[0]
[ "def", "qteActiveWindow", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_qteWindowList", ")", "==", "0", ":", "self", ".", "qteLogger", ".", "critical", "(", "'The window list is empty.'", ")", "return", "None", "elif", "len", "(", "self", ".", "_qteWindowList", ")", "==", "1", ":", "return", "self", ".", "_qteWindowList", "[", "0", "]", "else", ":", "# Find the active window.", "for", "win", "in", "self", ".", "_qteWindowList", ":", "if", "win", ".", "isActiveWindow", "(", ")", ":", "return", "win", "# Return the first window if none is active.", "return", "self", ".", "_qteWindowList", "[", "0", "]" ]
Return the currently active ``QtmacsWindow`` object. If no Qtmacs window is currently active (for instance because the user is working with another application at the moment) then the method returns the first window in the window list. The method only returns **None** if the window list is empty, which is definitively a bug. |Args| * **None** |Returns| * **QtmacsWindow**: the currently active window or **None** if no window is currently active. |Raises| * **None**
[ "Return", "the", "currently", "active", "QtmacsWindow", "object", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1507-L1543
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteNextWindow
def qteNextWindow(self): """ Return next window in cyclic order. |Args| * **None** |Returns| * **QtmacsWindow**: the next window in the Qtmacs internal window list. |Raises| * **None** """ # Get the currently active window. win = self.qteActiveWindow() if win in self._qteWindowList: # Find the index of the window in the window list and # cyclically move to the next element in this list to find # the next window object. idx = self._qteWindowList.index(win) idx = (idx + 1) % len(self._qteWindowList) return self._qteWindowList[idx] else: msg = 'qteNextWindow method found a non-existing window.' self.qteLogger.warning(msg) return None
python
def qteNextWindow(self): """ Return next window in cyclic order. |Args| * **None** |Returns| * **QtmacsWindow**: the next window in the Qtmacs internal window list. |Raises| * **None** """ # Get the currently active window. win = self.qteActiveWindow() if win in self._qteWindowList: # Find the index of the window in the window list and # cyclically move to the next element in this list to find # the next window object. idx = self._qteWindowList.index(win) idx = (idx + 1) % len(self._qteWindowList) return self._qteWindowList[idx] else: msg = 'qteNextWindow method found a non-existing window.' self.qteLogger.warning(msg) return None
[ "def", "qteNextWindow", "(", "self", ")", ":", "# Get the currently active window.", "win", "=", "self", ".", "qteActiveWindow", "(", ")", "if", "win", "in", "self", ".", "_qteWindowList", ":", "# Find the index of the window in the window list and", "# cyclically move to the next element in this list to find", "# the next window object.", "idx", "=", "self", ".", "_qteWindowList", ".", "index", "(", "win", ")", "idx", "=", "(", "idx", "+", "1", ")", "%", "len", "(", "self", ".", "_qteWindowList", ")", "return", "self", ".", "_qteWindowList", "[", "idx", "]", "else", ":", "msg", "=", "'qteNextWindow method found a non-existing window.'", "self", ".", "qteLogger", ".", "warning", "(", "msg", ")", "return", "None" ]
Return next window in cyclic order. |Args| * **None** |Returns| * **QtmacsWindow**: the next window in the Qtmacs internal window list. |Raises| * **None**
[ "Return", "next", "window", "in", "cyclic", "order", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1545-L1575
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteNextApplet
def qteNextApplet(self, numSkip: int=1, ofsApp: (QtmacsApplet, str)=None, skipInvisible: bool=True, skipVisible: bool=False, skipMiniApplet: bool=True, windowObj: QtmacsWindow=None): """ Return the next applet in cyclic order. If ``ofsApp=None`` then start cycling at the currently active applet. If ``ofsApp`` does not fit the selection criteria, then the cycling starts at the next applet in cyclic order that does. The returned applet is ``numSkip`` items in cyclic order away from the offset applet. If ``numSkip`` is positive traverse the applet list forwards, otherwise backwards. The method supports the following Boolean selection criteria: * ``skipInvisible``: ignore all invisible applets. * ``skipVisible``: ignore all visible applets. * ``skipMiniApplet``: ignore the mini applet applet. The ``ofsApp`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. |Args| * ``numSkip`` (**int**): number of applets to skip. * ``ofsApp`` (**QtmacsApplet**, **str**): applet from where to start counting. * ``skipInvisible`` (**bool**): whether or not to skip currently not shown applets. * ``skipVisible`` (**bool**): whether or not to skip currently shown applets. * ``skipMiniApplet`` (**bool**): whether or not to skip the mini applet. * ``windowObj`` (**QtmacsWindow**): the window to use when looking for applets. If **None**, then search in all windows. |Returns| * **QtmacsApplet**: either the next applet that fits the criteria, or **None** if no such applet exists. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance(ofsApp, str): ofsApp = self.qteGetAppletHandle(ofsApp) # Return immediately if the applet list is empty. if len(self._qteAppletList) == 0: return None # Sanity check: if the user requests applets that are neither # visible nor invisible then return immediately because no # such applet can possibly exist. if skipVisible and skipInvisible: return None # Make a copy of the applet list. appList = list(self._qteAppletList) # Remove all invisible applets from the list if the # skipInvisible flag is set. if skipInvisible: appList = [app for app in appList if app.qteIsVisible()] # From the list of (now guaranteed visible) applets remove # all those that are not in the specified window. if windowObj is not None: appList = [app for app in appList if app.qteParentWindow() == windowObj] # Remove all visible applets from the list if the # skipInvisible flag is set. if skipVisible: appList = [app for app in appList if not app.qteIsVisible()] # If the mini-buffer is to be skipped remove it (if a custom # mini applet even exists). if skipMiniApplet: if self._qteMiniApplet in appList: appList.remove(self._qteMiniApplet) # Return immediately if no applet satisfied all criteria. if len(appList) == 0: return None # If no offset applet was given use the currently active one. if ofsApp is None: ofsApp = self._qteActiveApplet if ofsApp in self._qteAppletList: # Determine if the offset applet is part of the pruned # list. if ofsApp in appList: # Yes: determine its index in the list. ofsIdx = appList.index(ofsApp) else: # No: traverse all applets until one is found that is # also part of the pruned list (start at ofsIdx). Then # determine its index in the list. ofsIdx = self._qteAppletList.index(ofsApp) glob_list = self._qteAppletList[ofsIdx:] glob_list += self._qteAppletList[:ofsIdx] # Compile the intersection between the global and pruned list. ofsIdx = [appList.index(_) for _ in glob_list if _ in appList] if len(ofsIdx) == 0: msg = ('No match between global and local applet list' ' --> Bug.') self.qteLogger.error(msg, stack_info=True) return None else: # Pick the first match. ofsIdx = ofsIdx[0] else: # The offset applet does not exist, eg. because the user # supplied a handle that does not point to an applet or # we are called from qteKillApplet to replace the just # removed (and active) applet. ofsIdx = 0 # Compute the index of the next applet and wrap around the # list if necessary. ofsIdx = (ofsIdx + numSkip) % len(appList) # Return a handle to the applet that meets the specified # criteria. return appList[ofsIdx]
python
def qteNextApplet(self, numSkip: int=1, ofsApp: (QtmacsApplet, str)=None, skipInvisible: bool=True, skipVisible: bool=False, skipMiniApplet: bool=True, windowObj: QtmacsWindow=None): """ Return the next applet in cyclic order. If ``ofsApp=None`` then start cycling at the currently active applet. If ``ofsApp`` does not fit the selection criteria, then the cycling starts at the next applet in cyclic order that does. The returned applet is ``numSkip`` items in cyclic order away from the offset applet. If ``numSkip`` is positive traverse the applet list forwards, otherwise backwards. The method supports the following Boolean selection criteria: * ``skipInvisible``: ignore all invisible applets. * ``skipVisible``: ignore all visible applets. * ``skipMiniApplet``: ignore the mini applet applet. The ``ofsApp`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. |Args| * ``numSkip`` (**int**): number of applets to skip. * ``ofsApp`` (**QtmacsApplet**, **str**): applet from where to start counting. * ``skipInvisible`` (**bool**): whether or not to skip currently not shown applets. * ``skipVisible`` (**bool**): whether or not to skip currently shown applets. * ``skipMiniApplet`` (**bool**): whether or not to skip the mini applet. * ``windowObj`` (**QtmacsWindow**): the window to use when looking for applets. If **None**, then search in all windows. |Returns| * **QtmacsApplet**: either the next applet that fits the criteria, or **None** if no such applet exists. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance(ofsApp, str): ofsApp = self.qteGetAppletHandle(ofsApp) # Return immediately if the applet list is empty. if len(self._qteAppletList) == 0: return None # Sanity check: if the user requests applets that are neither # visible nor invisible then return immediately because no # such applet can possibly exist. if skipVisible and skipInvisible: return None # Make a copy of the applet list. appList = list(self._qteAppletList) # Remove all invisible applets from the list if the # skipInvisible flag is set. if skipInvisible: appList = [app for app in appList if app.qteIsVisible()] # From the list of (now guaranteed visible) applets remove # all those that are not in the specified window. if windowObj is not None: appList = [app for app in appList if app.qteParentWindow() == windowObj] # Remove all visible applets from the list if the # skipInvisible flag is set. if skipVisible: appList = [app for app in appList if not app.qteIsVisible()] # If the mini-buffer is to be skipped remove it (if a custom # mini applet even exists). if skipMiniApplet: if self._qteMiniApplet in appList: appList.remove(self._qteMiniApplet) # Return immediately if no applet satisfied all criteria. if len(appList) == 0: return None # If no offset applet was given use the currently active one. if ofsApp is None: ofsApp = self._qteActiveApplet if ofsApp in self._qteAppletList: # Determine if the offset applet is part of the pruned # list. if ofsApp in appList: # Yes: determine its index in the list. ofsIdx = appList.index(ofsApp) else: # No: traverse all applets until one is found that is # also part of the pruned list (start at ofsIdx). Then # determine its index in the list. ofsIdx = self._qteAppletList.index(ofsApp) glob_list = self._qteAppletList[ofsIdx:] glob_list += self._qteAppletList[:ofsIdx] # Compile the intersection between the global and pruned list. ofsIdx = [appList.index(_) for _ in glob_list if _ in appList] if len(ofsIdx) == 0: msg = ('No match between global and local applet list' ' --> Bug.') self.qteLogger.error(msg, stack_info=True) return None else: # Pick the first match. ofsIdx = ofsIdx[0] else: # The offset applet does not exist, eg. because the user # supplied a handle that does not point to an applet or # we are called from qteKillApplet to replace the just # removed (and active) applet. ofsIdx = 0 # Compute the index of the next applet and wrap around the # list if necessary. ofsIdx = (ofsIdx + numSkip) % len(appList) # Return a handle to the applet that meets the specified # criteria. return appList[ofsIdx]
[ "def", "qteNextApplet", "(", "self", ",", "numSkip", ":", "int", "=", "1", ",", "ofsApp", ":", "(", "QtmacsApplet", ",", "str", ")", "=", "None", ",", "skipInvisible", ":", "bool", "=", "True", ",", "skipVisible", ":", "bool", "=", "False", ",", "skipMiniApplet", ":", "bool", "=", "True", ",", "windowObj", ":", "QtmacsWindow", "=", "None", ")", ":", "# If ``applet`` was specified by its ID (ie. a string) then", "# fetch the associated ``QtmacsApplet`` instance. If", "# ``applet`` is already an instance of ``QtmacsApplet`` then", "# use it directly.", "if", "isinstance", "(", "ofsApp", ",", "str", ")", ":", "ofsApp", "=", "self", ".", "qteGetAppletHandle", "(", "ofsApp", ")", "# Return immediately if the applet list is empty.", "if", "len", "(", "self", ".", "_qteAppletList", ")", "==", "0", ":", "return", "None", "# Sanity check: if the user requests applets that are neither", "# visible nor invisible then return immediately because no", "# such applet can possibly exist.", "if", "skipVisible", "and", "skipInvisible", ":", "return", "None", "# Make a copy of the applet list.", "appList", "=", "list", "(", "self", ".", "_qteAppletList", ")", "# Remove all invisible applets from the list if the", "# skipInvisible flag is set.", "if", "skipInvisible", ":", "appList", "=", "[", "app", "for", "app", "in", "appList", "if", "app", ".", "qteIsVisible", "(", ")", "]", "# From the list of (now guaranteed visible) applets remove", "# all those that are not in the specified window.", "if", "windowObj", "is", "not", "None", ":", "appList", "=", "[", "app", "for", "app", "in", "appList", "if", "app", ".", "qteParentWindow", "(", ")", "==", "windowObj", "]", "# Remove all visible applets from the list if the", "# skipInvisible flag is set.", "if", "skipVisible", ":", "appList", "=", "[", "app", "for", "app", "in", "appList", "if", "not", "app", ".", "qteIsVisible", "(", ")", "]", "# If the mini-buffer is to be skipped remove it (if a custom", "# mini applet even exists).", "if", "skipMiniApplet", ":", "if", "self", ".", "_qteMiniApplet", "in", "appList", ":", "appList", ".", "remove", "(", "self", ".", "_qteMiniApplet", ")", "# Return immediately if no applet satisfied all criteria.", "if", "len", "(", "appList", ")", "==", "0", ":", "return", "None", "# If no offset applet was given use the currently active one.", "if", "ofsApp", "is", "None", ":", "ofsApp", "=", "self", ".", "_qteActiveApplet", "if", "ofsApp", "in", "self", ".", "_qteAppletList", ":", "# Determine if the offset applet is part of the pruned", "# list.", "if", "ofsApp", "in", "appList", ":", "# Yes: determine its index in the list.", "ofsIdx", "=", "appList", ".", "index", "(", "ofsApp", ")", "else", ":", "# No: traverse all applets until one is found that is", "# also part of the pruned list (start at ofsIdx). Then", "# determine its index in the list.", "ofsIdx", "=", "self", ".", "_qteAppletList", ".", "index", "(", "ofsApp", ")", "glob_list", "=", "self", ".", "_qteAppletList", "[", "ofsIdx", ":", "]", "glob_list", "+=", "self", ".", "_qteAppletList", "[", ":", "ofsIdx", "]", "# Compile the intersection between the global and pruned list.", "ofsIdx", "=", "[", "appList", ".", "index", "(", "_", ")", "for", "_", "in", "glob_list", "if", "_", "in", "appList", "]", "if", "len", "(", "ofsIdx", ")", "==", "0", ":", "msg", "=", "(", "'No match between global and local applet list'", "' --> Bug.'", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "None", "else", ":", "# Pick the first match.", "ofsIdx", "=", "ofsIdx", "[", "0", "]", "else", ":", "# The offset applet does not exist, eg. because the user", "# supplied a handle that does not point to an applet or", "# we are called from qteKillApplet to replace the just", "# removed (and active) applet.", "ofsIdx", "=", "0", "# Compute the index of the next applet and wrap around the", "# list if necessary.", "ofsIdx", "=", "(", "ofsIdx", "+", "numSkip", ")", "%", "len", "(", "appList", ")", "# Return a handle to the applet that meets the specified", "# criteria.", "return", "appList", "[", "ofsIdx", "]" ]
Return the next applet in cyclic order. If ``ofsApp=None`` then start cycling at the currently active applet. If ``ofsApp`` does not fit the selection criteria, then the cycling starts at the next applet in cyclic order that does. The returned applet is ``numSkip`` items in cyclic order away from the offset applet. If ``numSkip`` is positive traverse the applet list forwards, otherwise backwards. The method supports the following Boolean selection criteria: * ``skipInvisible``: ignore all invisible applets. * ``skipVisible``: ignore all visible applets. * ``skipMiniApplet``: ignore the mini applet applet. The ``ofsApp`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. |Args| * ``numSkip`` (**int**): number of applets to skip. * ``ofsApp`` (**QtmacsApplet**, **str**): applet from where to start counting. * ``skipInvisible`` (**bool**): whether or not to skip currently not shown applets. * ``skipVisible`` (**bool**): whether or not to skip currently shown applets. * ``skipMiniApplet`` (**bool**): whether or not to skip the mini applet. * ``windowObj`` (**QtmacsWindow**): the window to use when looking for applets. If **None**, then search in all windows. |Returns| * **QtmacsApplet**: either the next applet that fits the criteria, or **None** if no such applet exists. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Return", "the", "next", "applet", "in", "cyclic", "order", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1672-L1809
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteRunMacro
def qteRunMacro(self, macroName: str, widgetObj: QtGui.QWidget=None, keysequence: QtmacsKeysequence=None): """ Queue a previously registered macro for execution once the event loop is idle. The reason for queuing macros in the first place, instead of running them straight away, is to ensure that the event loop updates all the widgets in between any two macros. This will avoid many spurious and hard to find bugs due to macros assuming that all user interface elements have been updated when in fact they were not. |Args| * ``macroName`` (**str**): name of macro. * ``widgetObj`` (**QWidget**): widget (if any) on which the macro should operate. * ``keysequence`` (**QtmacsKeysequence**): key sequence that triggered the macro. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Add the new macro to the queue and call qteUpdate to ensure # that the macro is processed once the event loop is idle again. self._qteMacroQueue.append((macroName, widgetObj, keysequence)) self.qteUpdate()
python
def qteRunMacro(self, macroName: str, widgetObj: QtGui.QWidget=None, keysequence: QtmacsKeysequence=None): """ Queue a previously registered macro for execution once the event loop is idle. The reason for queuing macros in the first place, instead of running them straight away, is to ensure that the event loop updates all the widgets in between any two macros. This will avoid many spurious and hard to find bugs due to macros assuming that all user interface elements have been updated when in fact they were not. |Args| * ``macroName`` (**str**): name of macro. * ``widgetObj`` (**QWidget**): widget (if any) on which the macro should operate. * ``keysequence`` (**QtmacsKeysequence**): key sequence that triggered the macro. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Add the new macro to the queue and call qteUpdate to ensure # that the macro is processed once the event loop is idle again. self._qteMacroQueue.append((macroName, widgetObj, keysequence)) self.qteUpdate()
[ "def", "qteRunMacro", "(", "self", ",", "macroName", ":", "str", ",", "widgetObj", ":", "QtGui", ".", "QWidget", "=", "None", ",", "keysequence", ":", "QtmacsKeysequence", "=", "None", ")", ":", "# Add the new macro to the queue and call qteUpdate to ensure", "# that the macro is processed once the event loop is idle again.", "self", ".", "_qteMacroQueue", ".", "append", "(", "(", "macroName", ",", "widgetObj", ",", "keysequence", ")", ")", "self", ".", "qteUpdate", "(", ")" ]
Queue a previously registered macro for execution once the event loop is idle. The reason for queuing macros in the first place, instead of running them straight away, is to ensure that the event loop updates all the widgets in between any two macros. This will avoid many spurious and hard to find bugs due to macros assuming that all user interface elements have been updated when in fact they were not. |Args| * ``macroName`` (**str**): name of macro. * ``widgetObj`` (**QWidget**): widget (if any) on which the macro should operate. * ``keysequence`` (**QtmacsKeysequence**): key sequence that triggered the macro. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Queue", "a", "previously", "registered", "macro", "for", "execution", "once", "the", "event", "loop", "is", "idle", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1812-L1844
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain._qteRunQueuedMacro
def _qteRunQueuedMacro(self, macroName: str, widgetObj: QtGui.QWidget=None, keysequence: QtmacsKeysequence=None): """ Execute the next macro in the macro queue. This method is triggered by the ``timerEvent`` in conjunction with the focus manager to ensure the event loop updates the GUI in between any two macros. .. warning:: Never call this method directly. |Args| * ``macroName`` (**str**): name of macro * ``widgetObj`` (**QWidget**): widget (if any) for which the macro applies * ``keysequence* (**QtmacsKeysequence**): key sequence that triggered the macro. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Fetch the applet holding the widget (this may be None). app = qteGetAppletFromWidget(widgetObj) # Double check that the applet still exists, unless there is # no applet (can happen when the windows are empty). if app is not None: if sip.isdeleted(app): msg = 'Ignored macro <b>{}</b> because it targeted a' msg += ' nonexistent applet.'.format(macroName) self.qteLogger.warning(msg) return # Fetch a signature compatible macro object. macroObj = self.qteGetMacroObject(macroName, widgetObj) # Log an error if no compatible macro was found. if macroObj is None: msg = 'No <b>{}</b>-macro compatible with {}:{}-type applet' msg = msg.format(macroName, app.qteAppletSignature(), widgetObj._qteAdmin.widgetSignature) self.qteLogger.warning(msg) return # Update the 'last_key_sequence' variable in case the macros, # or slots triggered by that macro, have access to it. self.qteDefVar('last_key_sequence', keysequence, doc="Last valid key sequence that triggered a macro.") # Set some variables in the macro object for convenient access # from inside the macro. if app is None: macroObj.qteApplet = macroObj.qteWidget = None else: macroObj.qteApplet = app macroObj.qteWidget = widgetObj # Run the macro and trigger the focus manager. macroObj.qtePrepareToRun()
python
def _qteRunQueuedMacro(self, macroName: str, widgetObj: QtGui.QWidget=None, keysequence: QtmacsKeysequence=None): """ Execute the next macro in the macro queue. This method is triggered by the ``timerEvent`` in conjunction with the focus manager to ensure the event loop updates the GUI in between any two macros. .. warning:: Never call this method directly. |Args| * ``macroName`` (**str**): name of macro * ``widgetObj`` (**QWidget**): widget (if any) for which the macro applies * ``keysequence* (**QtmacsKeysequence**): key sequence that triggered the macro. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Fetch the applet holding the widget (this may be None). app = qteGetAppletFromWidget(widgetObj) # Double check that the applet still exists, unless there is # no applet (can happen when the windows are empty). if app is not None: if sip.isdeleted(app): msg = 'Ignored macro <b>{}</b> because it targeted a' msg += ' nonexistent applet.'.format(macroName) self.qteLogger.warning(msg) return # Fetch a signature compatible macro object. macroObj = self.qteGetMacroObject(macroName, widgetObj) # Log an error if no compatible macro was found. if macroObj is None: msg = 'No <b>{}</b>-macro compatible with {}:{}-type applet' msg = msg.format(macroName, app.qteAppletSignature(), widgetObj._qteAdmin.widgetSignature) self.qteLogger.warning(msg) return # Update the 'last_key_sequence' variable in case the macros, # or slots triggered by that macro, have access to it. self.qteDefVar('last_key_sequence', keysequence, doc="Last valid key sequence that triggered a macro.") # Set some variables in the macro object for convenient access # from inside the macro. if app is None: macroObj.qteApplet = macroObj.qteWidget = None else: macroObj.qteApplet = app macroObj.qteWidget = widgetObj # Run the macro and trigger the focus manager. macroObj.qtePrepareToRun()
[ "def", "_qteRunQueuedMacro", "(", "self", ",", "macroName", ":", "str", ",", "widgetObj", ":", "QtGui", ".", "QWidget", "=", "None", ",", "keysequence", ":", "QtmacsKeysequence", "=", "None", ")", ":", "# Fetch the applet holding the widget (this may be None).", "app", "=", "qteGetAppletFromWidget", "(", "widgetObj", ")", "# Double check that the applet still exists, unless there is", "# no applet (can happen when the windows are empty).", "if", "app", "is", "not", "None", ":", "if", "sip", ".", "isdeleted", "(", "app", ")", ":", "msg", "=", "'Ignored macro <b>{}</b> because it targeted a'", "msg", "+=", "' nonexistent applet.'", ".", "format", "(", "macroName", ")", "self", ".", "qteLogger", ".", "warning", "(", "msg", ")", "return", "# Fetch a signature compatible macro object.", "macroObj", "=", "self", ".", "qteGetMacroObject", "(", "macroName", ",", "widgetObj", ")", "# Log an error if no compatible macro was found.", "if", "macroObj", "is", "None", ":", "msg", "=", "'No <b>{}</b>-macro compatible with {}:{}-type applet'", "msg", "=", "msg", ".", "format", "(", "macroName", ",", "app", ".", "qteAppletSignature", "(", ")", ",", "widgetObj", ".", "_qteAdmin", ".", "widgetSignature", ")", "self", ".", "qteLogger", ".", "warning", "(", "msg", ")", "return", "# Update the 'last_key_sequence' variable in case the macros,", "# or slots triggered by that macro, have access to it.", "self", ".", "qteDefVar", "(", "'last_key_sequence'", ",", "keysequence", ",", "doc", "=", "\"Last valid key sequence that triggered a macro.\"", ")", "# Set some variables in the macro object for convenient access", "# from inside the macro.", "if", "app", "is", "None", ":", "macroObj", ".", "qteApplet", "=", "macroObj", ".", "qteWidget", "=", "None", "else", ":", "macroObj", ".", "qteApplet", "=", "app", "macroObj", ".", "qteWidget", "=", "widgetObj", "# Run the macro and trigger the focus manager.", "macroObj", ".", "qtePrepareToRun", "(", ")" ]
Execute the next macro in the macro queue. This method is triggered by the ``timerEvent`` in conjunction with the focus manager to ensure the event loop updates the GUI in between any two macros. .. warning:: Never call this method directly. |Args| * ``macroName`` (**str**): name of macro * ``widgetObj`` (**QWidget**): widget (if any) for which the macro applies * ``keysequence* (**QtmacsKeysequence**): key sequence that triggered the macro. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Execute", "the", "next", "macro", "in", "the", "macro", "queue", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1847-L1912
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteNewApplet
def qteNewApplet(self, appletName: str, appletID: str=None, windowObj: QtmacsWindow=None): """ Create a new instance of ``appletName`` and assign it the ``appletID``. This method creates a new instance of ``appletName``, as registered by the ``qteRegisterApplet`` method. If an applet with ``appletID`` already exists then the method does nothing and returns **None**, otherwise the newly created instance. If ``appletID`` is **None** then the method will create an applet with the next unique ID that fits the format ``appletName_0``, eg. 'RichEditor_0', 'RichEditor_1', etc. .. note:: The applet is not automatically made visible. |Args| * ``appletName`` (**str**): name of applet to create (eg. 'LogViewer') * ``appletID`` (**str**): unique applet identifier. * ``windowObj`` (**QtmacsWindow**): the window in which the applet should be created. |Returns| * **QtmacsApplet**: applet handle or **None** if no applet was created. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Use the currently active window if none was specified. if windowObj is None: windowObj = self.qteActiveWindow() if windowObj is None: msg = 'Cannot determine the currently active window.' self.qteLogger.error(msg, stack_info=True) return # Determine an automatic applet ID if none was provided. if appletID is None: cnt = 0 while True: appletID = appletName + '_' + str(cnt) if self.qteGetAppletHandle(appletID) is None: break else: cnt += 1 # Return immediately if an applet with the same ID already # exists. if self.qteGetAppletHandle(appletID) is not None: msg = 'Applet with ID <b>{}</b> already exists'.format(appletID) self.qteLogger.error(msg, stack_info=True) return None # Verify that the requested applet class was registered # beforehand and fetch it. if appletName not in self._qteRegistryApplets: msg = 'Unknown applet <b>{}</b>'.format(appletName) self.qteLogger.error(msg, stack_info=True) return None else: cls = self._qteRegistryApplets[appletName] # Try to instantiate the class. try: app = cls(appletID) except Exception: msg = 'Applet <b>{}</b> has a faulty constructor.'.format(appletID) self.qteLogger.exception(msg, exc_info=True, stack_info=True) return None # Ensure the applet class has an applet signature. if app.qteAppletSignature() is None: msg = 'Cannot add applet <b>{}</b> '.format(app.qteAppletID()) msg += 'because it has not applet signature.' msg += ' Use self.qteSetAppletSignature in the constructor' msg += ' of the class to fix this.' self.qteLogger.error(msg, stack_info=True) return None # Add the applet to the list of instantiated Qtmacs applets. self._qteAppletList.insert(0, app) # If the new applet does not yet have an internal layout then # arrange all its children automatically. The layout used for # this is horizontal and the widgets are added in the order in # which they were registered with Qtmacs. if app.layout() is None: appLayout = QtGui.QHBoxLayout() for handle in app._qteAdmin.widgetList: appLayout.addWidget(handle) app.setLayout(appLayout) # Initially, the window does not have a parent. A parent will # be assigned automatically once the applet is made visible, # in which case it is re-parented into a QtmacsSplitter. app.qteReparent(None) # Emit the init hook for this applet. self.qteRunHook('init', QtmacsMessage(None, app)) # Return applet handle. return app
python
def qteNewApplet(self, appletName: str, appletID: str=None, windowObj: QtmacsWindow=None): """ Create a new instance of ``appletName`` and assign it the ``appletID``. This method creates a new instance of ``appletName``, as registered by the ``qteRegisterApplet`` method. If an applet with ``appletID`` already exists then the method does nothing and returns **None**, otherwise the newly created instance. If ``appletID`` is **None** then the method will create an applet with the next unique ID that fits the format ``appletName_0``, eg. 'RichEditor_0', 'RichEditor_1', etc. .. note:: The applet is not automatically made visible. |Args| * ``appletName`` (**str**): name of applet to create (eg. 'LogViewer') * ``appletID`` (**str**): unique applet identifier. * ``windowObj`` (**QtmacsWindow**): the window in which the applet should be created. |Returns| * **QtmacsApplet**: applet handle or **None** if no applet was created. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Use the currently active window if none was specified. if windowObj is None: windowObj = self.qteActiveWindow() if windowObj is None: msg = 'Cannot determine the currently active window.' self.qteLogger.error(msg, stack_info=True) return # Determine an automatic applet ID if none was provided. if appletID is None: cnt = 0 while True: appletID = appletName + '_' + str(cnt) if self.qteGetAppletHandle(appletID) is None: break else: cnt += 1 # Return immediately if an applet with the same ID already # exists. if self.qteGetAppletHandle(appletID) is not None: msg = 'Applet with ID <b>{}</b> already exists'.format(appletID) self.qteLogger.error(msg, stack_info=True) return None # Verify that the requested applet class was registered # beforehand and fetch it. if appletName not in self._qteRegistryApplets: msg = 'Unknown applet <b>{}</b>'.format(appletName) self.qteLogger.error(msg, stack_info=True) return None else: cls = self._qteRegistryApplets[appletName] # Try to instantiate the class. try: app = cls(appletID) except Exception: msg = 'Applet <b>{}</b> has a faulty constructor.'.format(appletID) self.qteLogger.exception(msg, exc_info=True, stack_info=True) return None # Ensure the applet class has an applet signature. if app.qteAppletSignature() is None: msg = 'Cannot add applet <b>{}</b> '.format(app.qteAppletID()) msg += 'because it has not applet signature.' msg += ' Use self.qteSetAppletSignature in the constructor' msg += ' of the class to fix this.' self.qteLogger.error(msg, stack_info=True) return None # Add the applet to the list of instantiated Qtmacs applets. self._qteAppletList.insert(0, app) # If the new applet does not yet have an internal layout then # arrange all its children automatically. The layout used for # this is horizontal and the widgets are added in the order in # which they were registered with Qtmacs. if app.layout() is None: appLayout = QtGui.QHBoxLayout() for handle in app._qteAdmin.widgetList: appLayout.addWidget(handle) app.setLayout(appLayout) # Initially, the window does not have a parent. A parent will # be assigned automatically once the applet is made visible, # in which case it is re-parented into a QtmacsSplitter. app.qteReparent(None) # Emit the init hook for this applet. self.qteRunHook('init', QtmacsMessage(None, app)) # Return applet handle. return app
[ "def", "qteNewApplet", "(", "self", ",", "appletName", ":", "str", ",", "appletID", ":", "str", "=", "None", ",", "windowObj", ":", "QtmacsWindow", "=", "None", ")", ":", "# Use the currently active window if none was specified.", "if", "windowObj", "is", "None", ":", "windowObj", "=", "self", ".", "qteActiveWindow", "(", ")", "if", "windowObj", "is", "None", ":", "msg", "=", "'Cannot determine the currently active window.'", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "# Determine an automatic applet ID if none was provided.", "if", "appletID", "is", "None", ":", "cnt", "=", "0", "while", "True", ":", "appletID", "=", "appletName", "+", "'_'", "+", "str", "(", "cnt", ")", "if", "self", ".", "qteGetAppletHandle", "(", "appletID", ")", "is", "None", ":", "break", "else", ":", "cnt", "+=", "1", "# Return immediately if an applet with the same ID already", "# exists.", "if", "self", ".", "qteGetAppletHandle", "(", "appletID", ")", "is", "not", "None", ":", "msg", "=", "'Applet with ID <b>{}</b> already exists'", ".", "format", "(", "appletID", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "None", "# Verify that the requested applet class was registered", "# beforehand and fetch it.", "if", "appletName", "not", "in", "self", ".", "_qteRegistryApplets", ":", "msg", "=", "'Unknown applet <b>{}</b>'", ".", "format", "(", "appletName", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "None", "else", ":", "cls", "=", "self", ".", "_qteRegistryApplets", "[", "appletName", "]", "# Try to instantiate the class.", "try", ":", "app", "=", "cls", "(", "appletID", ")", "except", "Exception", ":", "msg", "=", "'Applet <b>{}</b> has a faulty constructor.'", ".", "format", "(", "appletID", ")", "self", ".", "qteLogger", ".", "exception", "(", "msg", ",", "exc_info", "=", "True", ",", "stack_info", "=", "True", ")", "return", "None", "# Ensure the applet class has an applet signature.", "if", "app", ".", "qteAppletSignature", "(", ")", "is", "None", ":", "msg", "=", "'Cannot add applet <b>{}</b> '", ".", "format", "(", "app", ".", "qteAppletID", "(", ")", ")", "msg", "+=", "'because it has not applet signature.'", "msg", "+=", "' Use self.qteSetAppletSignature in the constructor'", "msg", "+=", "' of the class to fix this.'", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "None", "# Add the applet to the list of instantiated Qtmacs applets.", "self", ".", "_qteAppletList", ".", "insert", "(", "0", ",", "app", ")", "# If the new applet does not yet have an internal layout then", "# arrange all its children automatically. The layout used for", "# this is horizontal and the widgets are added in the order in", "# which they were registered with Qtmacs.", "if", "app", ".", "layout", "(", ")", "is", "None", ":", "appLayout", "=", "QtGui", ".", "QHBoxLayout", "(", ")", "for", "handle", "in", "app", ".", "_qteAdmin", ".", "widgetList", ":", "appLayout", ".", "addWidget", "(", "handle", ")", "app", ".", "setLayout", "(", "appLayout", ")", "# Initially, the window does not have a parent. A parent will", "# be assigned automatically once the applet is made visible,", "# in which case it is re-parented into a QtmacsSplitter.", "app", ".", "qteReparent", "(", "None", ")", "# Emit the init hook for this applet.", "self", ".", "qteRunHook", "(", "'init'", ",", "QtmacsMessage", "(", "None", ",", "app", ")", ")", "# Return applet handle.", "return", "app" ]
Create a new instance of ``appletName`` and assign it the ``appletID``. This method creates a new instance of ``appletName``, as registered by the ``qteRegisterApplet`` method. If an applet with ``appletID`` already exists then the method does nothing and returns **None**, otherwise the newly created instance. If ``appletID`` is **None** then the method will create an applet with the next unique ID that fits the format ``appletName_0``, eg. 'RichEditor_0', 'RichEditor_1', etc. .. note:: The applet is not automatically made visible. |Args| * ``appletName`` (**str**): name of applet to create (eg. 'LogViewer') * ``appletID`` (**str**): unique applet identifier. * ``windowObj`` (**QtmacsWindow**): the window in which the applet should be created. |Returns| * **QtmacsApplet**: applet handle or **None** if no applet was created. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Create", "a", "new", "instance", "of", "appletName", "and", "assign", "it", "the", "appletID", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L1915-L2022
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteAddMiniApplet
def qteAddMiniApplet(self, appletObj: QtmacsApplet): """ Install ``appletObj`` as the mini applet in the window layout. At any given point there can ever only be one mini applet in the entire Qtmacs application, irrespective of how many windows are open. Note that this method does nothing if a custom mini applet is already active. Use ``qteKillMiniApplet`` to remove that one first before installing a new one. |Args| * ``appletObj`` (**QtmacsApplet**): the new mini applet. |Returns| * **bool**: if **True** the mini applet was installed successfully. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Do nothing if a custom mini applet has already been # installed. if self._qteMiniApplet is not None: msg = 'Cannot replace mini applet more than once.' self.qteLogger.warning(msg) return False # Arrange all registered widgets inside this applet # automatically if the mini applet object did not install its # own layout. if appletObj.layout() is None: appLayout = QtGui.QHBoxLayout() for handle in appletObj._qteAdmin.widgetList: appLayout.addWidget(handle) appletObj.setLayout(appLayout) # Now that we have decided to install this mini applet, keep a # reference to it and set the mini applet flag in the # applet. This flag is necessary for some methods to separate # conventional applets from mini applets. appletObj._qteAdmin.isMiniApplet = True self._qteMiniApplet = appletObj # Shorthands. app = self._qteActiveApplet appWin = self.qteActiveWindow() # Remember which window and applet spawned this mini applet. self._qteMiniApplet._qteCallingApplet = app self._qteMiniApplet._qteCallingWindow = appWin del app # Add the mini applet to the applet registry, ie. for most # purposes the mini applet is treated like any other applet. self._qteAppletList.insert(0, self._qteMiniApplet) # Add the mini applet to the respective splitter in the window # layout and show it. appWin.qteLayoutSplitter.addWidget(self._qteMiniApplet) self._qteMiniApplet.show(True) # Give focus to first focusable widget in the mini applet # applet (if one exists) wid = self._qteMiniApplet.qteNextWidget(numSkip=0) self._qteMiniApplet.qteMakeWidgetActive(wid) self.qteMakeAppletActive(self._qteMiniApplet) # Mini applet was successfully installed. return True
python
def qteAddMiniApplet(self, appletObj: QtmacsApplet): """ Install ``appletObj`` as the mini applet in the window layout. At any given point there can ever only be one mini applet in the entire Qtmacs application, irrespective of how many windows are open. Note that this method does nothing if a custom mini applet is already active. Use ``qteKillMiniApplet`` to remove that one first before installing a new one. |Args| * ``appletObj`` (**QtmacsApplet**): the new mini applet. |Returns| * **bool**: if **True** the mini applet was installed successfully. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Do nothing if a custom mini applet has already been # installed. if self._qteMiniApplet is not None: msg = 'Cannot replace mini applet more than once.' self.qteLogger.warning(msg) return False # Arrange all registered widgets inside this applet # automatically if the mini applet object did not install its # own layout. if appletObj.layout() is None: appLayout = QtGui.QHBoxLayout() for handle in appletObj._qteAdmin.widgetList: appLayout.addWidget(handle) appletObj.setLayout(appLayout) # Now that we have decided to install this mini applet, keep a # reference to it and set the mini applet flag in the # applet. This flag is necessary for some methods to separate # conventional applets from mini applets. appletObj._qteAdmin.isMiniApplet = True self._qteMiniApplet = appletObj # Shorthands. app = self._qteActiveApplet appWin = self.qteActiveWindow() # Remember which window and applet spawned this mini applet. self._qteMiniApplet._qteCallingApplet = app self._qteMiniApplet._qteCallingWindow = appWin del app # Add the mini applet to the applet registry, ie. for most # purposes the mini applet is treated like any other applet. self._qteAppletList.insert(0, self._qteMiniApplet) # Add the mini applet to the respective splitter in the window # layout and show it. appWin.qteLayoutSplitter.addWidget(self._qteMiniApplet) self._qteMiniApplet.show(True) # Give focus to first focusable widget in the mini applet # applet (if one exists) wid = self._qteMiniApplet.qteNextWidget(numSkip=0) self._qteMiniApplet.qteMakeWidgetActive(wid) self.qteMakeAppletActive(self._qteMiniApplet) # Mini applet was successfully installed. return True
[ "def", "qteAddMiniApplet", "(", "self", ",", "appletObj", ":", "QtmacsApplet", ")", ":", "# Do nothing if a custom mini applet has already been", "# installed.", "if", "self", ".", "_qteMiniApplet", "is", "not", "None", ":", "msg", "=", "'Cannot replace mini applet more than once.'", "self", ".", "qteLogger", ".", "warning", "(", "msg", ")", "return", "False", "# Arrange all registered widgets inside this applet", "# automatically if the mini applet object did not install its", "# own layout.", "if", "appletObj", ".", "layout", "(", ")", "is", "None", ":", "appLayout", "=", "QtGui", ".", "QHBoxLayout", "(", ")", "for", "handle", "in", "appletObj", ".", "_qteAdmin", ".", "widgetList", ":", "appLayout", ".", "addWidget", "(", "handle", ")", "appletObj", ".", "setLayout", "(", "appLayout", ")", "# Now that we have decided to install this mini applet, keep a", "# reference to it and set the mini applet flag in the", "# applet. This flag is necessary for some methods to separate", "# conventional applets from mini applets.", "appletObj", ".", "_qteAdmin", ".", "isMiniApplet", "=", "True", "self", ".", "_qteMiniApplet", "=", "appletObj", "# Shorthands.", "app", "=", "self", ".", "_qteActiveApplet", "appWin", "=", "self", ".", "qteActiveWindow", "(", ")", "# Remember which window and applet spawned this mini applet.", "self", ".", "_qteMiniApplet", ".", "_qteCallingApplet", "=", "app", "self", ".", "_qteMiniApplet", ".", "_qteCallingWindow", "=", "appWin", "del", "app", "# Add the mini applet to the applet registry, ie. for most", "# purposes the mini applet is treated like any other applet.", "self", ".", "_qteAppletList", ".", "insert", "(", "0", ",", "self", ".", "_qteMiniApplet", ")", "# Add the mini applet to the respective splitter in the window", "# layout and show it.", "appWin", ".", "qteLayoutSplitter", ".", "addWidget", "(", "self", ".", "_qteMiniApplet", ")", "self", ".", "_qteMiniApplet", ".", "show", "(", "True", ")", "# Give focus to first focusable widget in the mini applet", "# applet (if one exists)", "wid", "=", "self", ".", "_qteMiniApplet", ".", "qteNextWidget", "(", "numSkip", "=", "0", ")", "self", ".", "_qteMiniApplet", ".", "qteMakeWidgetActive", "(", "wid", ")", "self", ".", "qteMakeAppletActive", "(", "self", ".", "_qteMiniApplet", ")", "# Mini applet was successfully installed.", "return", "True" ]
Install ``appletObj`` as the mini applet in the window layout. At any given point there can ever only be one mini applet in the entire Qtmacs application, irrespective of how many windows are open. Note that this method does nothing if a custom mini applet is already active. Use ``qteKillMiniApplet`` to remove that one first before installing a new one. |Args| * ``appletObj`` (**QtmacsApplet**): the new mini applet. |Returns| * **bool**: if **True** the mini applet was installed successfully. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Install", "appletObj", "as", "the", "mini", "applet", "in", "the", "window", "layout", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2025-L2098
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteKillMiniApplet
def qteKillMiniApplet(self): """ Remove the mini applet. If a different applet is to be restored/focused then call ``qteMakeAppletActive`` for that applet *after* calling this method. |Args| * **None** |Returns| * **None** |Raises| * **None** """ # Sanity check: is the handle valid? if self._qteMiniApplet is None: return # Sanity check: is it really a mini applet? if not self.qteIsMiniApplet(self._qteMiniApplet): msg = ('Mini applet does not have its mini applet flag set.' ' Ignored.') self.qteLogger.warning(msg) if self._qteMiniApplet not in self._qteAppletList: # Something is wrong because the mini applet is not part # of the applet list. msg = 'Custom mini applet not in applet list --> Bug.' self.qteLogger.warning(msg) else: # Inform the mini applet that it is about to be killed. try: self._qteMiniApplet.qteToBeKilled() except Exception: msg = 'qteToBeKilledRoutine is faulty' self.qteLogger.exception(msg, exc_info=True, stack_info=True) # Shorthands to calling window. win = self._qteMiniApplet._qteCallingWindow # We need to move the focus from the mini applet back to a # regular applet. Therefore, first look for the next # visible applet in the current window (ie. the last one # that was made active). app = self.qteNextApplet(windowObj=win) if app is not None: # Found another (visible or invisible) applet --> make # it active/visible. self.qteMakeAppletActive(app) else: # No visible applet available in this window --> look # for an invisible one. app = self.qteNextApplet(skipInvisible=False, skipVisible=True) if app is not None: # Found an invisible applet --> make it # active/visible. self.qteMakeAppletActive(app) else: # There is no other visible applet in this window. # The focus manager will therefore make a new applet # active. self._qteActiveApplet = None self._qteAppletList.remove(self._qteMiniApplet) # Close the mini applet applet and schedule it for deletion. self._qteMiniApplet.close() self._qteMiniApplet.deleteLater() # Clear the handle to the mini applet. self._qteMiniApplet = None
python
def qteKillMiniApplet(self): """ Remove the mini applet. If a different applet is to be restored/focused then call ``qteMakeAppletActive`` for that applet *after* calling this method. |Args| * **None** |Returns| * **None** |Raises| * **None** """ # Sanity check: is the handle valid? if self._qteMiniApplet is None: return # Sanity check: is it really a mini applet? if not self.qteIsMiniApplet(self._qteMiniApplet): msg = ('Mini applet does not have its mini applet flag set.' ' Ignored.') self.qteLogger.warning(msg) if self._qteMiniApplet not in self._qteAppletList: # Something is wrong because the mini applet is not part # of the applet list. msg = 'Custom mini applet not in applet list --> Bug.' self.qteLogger.warning(msg) else: # Inform the mini applet that it is about to be killed. try: self._qteMiniApplet.qteToBeKilled() except Exception: msg = 'qteToBeKilledRoutine is faulty' self.qteLogger.exception(msg, exc_info=True, stack_info=True) # Shorthands to calling window. win = self._qteMiniApplet._qteCallingWindow # We need to move the focus from the mini applet back to a # regular applet. Therefore, first look for the next # visible applet in the current window (ie. the last one # that was made active). app = self.qteNextApplet(windowObj=win) if app is not None: # Found another (visible or invisible) applet --> make # it active/visible. self.qteMakeAppletActive(app) else: # No visible applet available in this window --> look # for an invisible one. app = self.qteNextApplet(skipInvisible=False, skipVisible=True) if app is not None: # Found an invisible applet --> make it # active/visible. self.qteMakeAppletActive(app) else: # There is no other visible applet in this window. # The focus manager will therefore make a new applet # active. self._qteActiveApplet = None self._qteAppletList.remove(self._qteMiniApplet) # Close the mini applet applet and schedule it for deletion. self._qteMiniApplet.close() self._qteMiniApplet.deleteLater() # Clear the handle to the mini applet. self._qteMiniApplet = None
[ "def", "qteKillMiniApplet", "(", "self", ")", ":", "# Sanity check: is the handle valid?", "if", "self", ".", "_qteMiniApplet", "is", "None", ":", "return", "# Sanity check: is it really a mini applet?", "if", "not", "self", ".", "qteIsMiniApplet", "(", "self", ".", "_qteMiniApplet", ")", ":", "msg", "=", "(", "'Mini applet does not have its mini applet flag set.'", "' Ignored.'", ")", "self", ".", "qteLogger", ".", "warning", "(", "msg", ")", "if", "self", ".", "_qteMiniApplet", "not", "in", "self", ".", "_qteAppletList", ":", "# Something is wrong because the mini applet is not part", "# of the applet list.", "msg", "=", "'Custom mini applet not in applet list --> Bug.'", "self", ".", "qteLogger", ".", "warning", "(", "msg", ")", "else", ":", "# Inform the mini applet that it is about to be killed.", "try", ":", "self", ".", "_qteMiniApplet", ".", "qteToBeKilled", "(", ")", "except", "Exception", ":", "msg", "=", "'qteToBeKilledRoutine is faulty'", "self", ".", "qteLogger", ".", "exception", "(", "msg", ",", "exc_info", "=", "True", ",", "stack_info", "=", "True", ")", "# Shorthands to calling window.", "win", "=", "self", ".", "_qteMiniApplet", ".", "_qteCallingWindow", "# We need to move the focus from the mini applet back to a", "# regular applet. Therefore, first look for the next", "# visible applet in the current window (ie. the last one", "# that was made active).", "app", "=", "self", ".", "qteNextApplet", "(", "windowObj", "=", "win", ")", "if", "app", "is", "not", "None", ":", "# Found another (visible or invisible) applet --> make", "# it active/visible.", "self", ".", "qteMakeAppletActive", "(", "app", ")", "else", ":", "# No visible applet available in this window --> look", "# for an invisible one.", "app", "=", "self", ".", "qteNextApplet", "(", "skipInvisible", "=", "False", ",", "skipVisible", "=", "True", ")", "if", "app", "is", "not", "None", ":", "# Found an invisible applet --> make it", "# active/visible.", "self", ".", "qteMakeAppletActive", "(", "app", ")", "else", ":", "# There is no other visible applet in this window.", "# The focus manager will therefore make a new applet", "# active.", "self", ".", "_qteActiveApplet", "=", "None", "self", ".", "_qteAppletList", ".", "remove", "(", "self", ".", "_qteMiniApplet", ")", "# Close the mini applet applet and schedule it for deletion.", "self", ".", "_qteMiniApplet", ".", "close", "(", ")", "self", ".", "_qteMiniApplet", ".", "deleteLater", "(", ")", "# Clear the handle to the mini applet.", "self", ".", "_qteMiniApplet", "=", "None" ]
Remove the mini applet. If a different applet is to be restored/focused then call ``qteMakeAppletActive`` for that applet *after* calling this method. |Args| * **None** |Returns| * **None** |Raises| * **None**
[ "Remove", "the", "mini", "applet", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2100-L2175
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain._qteFindAppletInSplitter
def _qteFindAppletInSplitter(self, appletObj: QtmacsApplet, split: QtmacsSplitter): """ Return the splitter that holds ``appletObj``. This method recursively searches for ``appletObj`` in the nested splitter hierarchy of the window layout, starting at ``split``. If successful, the method returns a reference to the splitter, otherwise it returns **None**. |Args| * ``appletObj`` (**QtmacsApplet**): the applet to look for. * ``split`` (**QtmacsSplitter**): the splitter where to begin. |Returns| * **QtmacsSplitter**: the splitter that holds ``appletObj`` or **None**. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ def splitterIter(split): """ Iterator over all QtmacsSplitters. """ for idx in range(split.count()): subSplitter = split.widget(idx) subID = subSplitter._qteAdmin.widgetSignature if subID == '__QtmacsLayoutSplitter__': yield from splitterIter(subSplitter) yield split # Traverse all QtmacsSplitter until ``appletObj`` was found. for curSplit in splitterIter(split): if appletObj in curSplit.children(): return curSplit # No splitter holds ``appletObj``. return None
python
def _qteFindAppletInSplitter(self, appletObj: QtmacsApplet, split: QtmacsSplitter): """ Return the splitter that holds ``appletObj``. This method recursively searches for ``appletObj`` in the nested splitter hierarchy of the window layout, starting at ``split``. If successful, the method returns a reference to the splitter, otherwise it returns **None**. |Args| * ``appletObj`` (**QtmacsApplet**): the applet to look for. * ``split`` (**QtmacsSplitter**): the splitter where to begin. |Returns| * **QtmacsSplitter**: the splitter that holds ``appletObj`` or **None**. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ def splitterIter(split): """ Iterator over all QtmacsSplitters. """ for idx in range(split.count()): subSplitter = split.widget(idx) subID = subSplitter._qteAdmin.widgetSignature if subID == '__QtmacsLayoutSplitter__': yield from splitterIter(subSplitter) yield split # Traverse all QtmacsSplitter until ``appletObj`` was found. for curSplit in splitterIter(split): if appletObj in curSplit.children(): return curSplit # No splitter holds ``appletObj``. return None
[ "def", "_qteFindAppletInSplitter", "(", "self", ",", "appletObj", ":", "QtmacsApplet", ",", "split", ":", "QtmacsSplitter", ")", ":", "def", "splitterIter", "(", "split", ")", ":", "\"\"\"\n Iterator over all QtmacsSplitters.\n \"\"\"", "for", "idx", "in", "range", "(", "split", ".", "count", "(", ")", ")", ":", "subSplitter", "=", "split", ".", "widget", "(", "idx", ")", "subID", "=", "subSplitter", ".", "_qteAdmin", ".", "widgetSignature", "if", "subID", "==", "'__QtmacsLayoutSplitter__'", ":", "yield", "from", "splitterIter", "(", "subSplitter", ")", "yield", "split", "# Traverse all QtmacsSplitter until ``appletObj`` was found.", "for", "curSplit", "in", "splitterIter", "(", "split", ")", ":", "if", "appletObj", "in", "curSplit", ".", "children", "(", ")", ":", "return", "curSplit", "# No splitter holds ``appletObj``.", "return", "None" ]
Return the splitter that holds ``appletObj``. This method recursively searches for ``appletObj`` in the nested splitter hierarchy of the window layout, starting at ``split``. If successful, the method returns a reference to the splitter, otherwise it returns **None**. |Args| * ``appletObj`` (**QtmacsApplet**): the applet to look for. * ``split`` (**QtmacsSplitter**): the splitter where to begin. |Returns| * **QtmacsSplitter**: the splitter that holds ``appletObj`` or **None**. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Return", "the", "splitter", "that", "holds", "appletObj", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2178-L2219
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteSplitApplet
def qteSplitApplet(self, applet: (QtmacsApplet, str)=None, splitHoriz: bool=True, windowObj: QtmacsWindow=None): """ Reveal ``applet`` by splitting the space occupied by the current applet. If ``applet`` is already visible then the method does nothing. Furthermore, this method does not change the focus, ie. the currently active applet will remain active. If ``applet`` is **None** then the next invisible applet will be shown. If ``windowObj`` is **None** then the currently active window will be used. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. |Args| * ``applet`` (**QtmacsApplet**, **str**): the applet to reveal. * ``splitHoriz`` (**bool**): whether to split horizontally or vertically. * ``windowObj`` (**QtmacsWindow**): the window in which to reveal ``applet``. |Returns| * **bool**: if **True**, ``applet`` was revealed. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``newAppObj`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``newAppObj`` is already an instance of ``QtmacsApplet`` # then use it directly. if isinstance(applet, str): newAppObj = self.qteGetAppletHandle(applet) else: newAppObj = applet # Use the currently active window if none was specified. if windowObj is None: windowObj = self.qteActiveWindow() if windowObj is None: msg = 'Cannot determine the currently active window.' self.qteLogger.error(msg, stack_info=True) return # Convert ``splitHoriz`` to the respective Qt constant. if splitHoriz: splitOrientation = QtCore.Qt.Horizontal else: splitOrientation = QtCore.Qt.Vertical if newAppObj is None: # If no new applet was specified use the next available # invisible applet. newAppObj = self.qteNextApplet(skipVisible=True, skipInvisible=False) else: # Do nothing if the new applet is already visible. if newAppObj.qteIsVisible(): return False # If we still have not found an applet then there are no # invisible applets left to show. Therefore, splitting makes # no sense. if newAppObj is None: self.qteLogger.warning('All applets are already visible.') return False # If the root splitter is empty then add the new applet and # return immediately. if windowObj.qteAppletSplitter.count() == 0: windowObj.qteAppletSplitter.qteAddWidget(newAppObj) windowObj.qteAppletSplitter.setOrientation(splitOrientation) return True # ------------------------------------------------------------ # The root splitter contains at least one widget, if we got # this far. # ------------------------------------------------------------ # Shorthand to last active applet in the current window. Query # this applet with qteNextApplet method because # self._qteActiveApplet may be a mini applet, and we are only # interested in genuine applets. curApp = self.qteNextApplet(numSkip=0, windowObj=windowObj) # Get a reference to the splitter in which the currently # active applet lives. This may be the root splitter, or one # of its child splitters. split = self._qteFindAppletInSplitter( curApp, windowObj.qteAppletSplitter) if split is None: msg = 'Active applet <b>{}</b> not in the layout.' msg = msg.format(curApp.qteAppletID()) self.qteLogger.error(msg, stack_info=True) return False # If 'curApp' lives in the root splitter, and the root # splitter contains only a single element, then simply add the # new applet as the second element and return. if split is windowObj.qteAppletSplitter: if split.count() == 1: split.qteAddWidget(newAppObj) split.setOrientation(splitOrientation) return True # ------------------------------------------------------------ # The splitter (root or not) contains two widgets, if we got # this far. # ------------------------------------------------------------ # Determine the index of the applet inside the splitter. curAppIdx = split.indexOf(curApp) # Create a new splitter and populate it with 'curApp' and the # previously invisible ``newAppObj``. Then insert this new splitter at # the position where the old applet was taken from. Note: widgets are # inserted with ``qteAddWidget`` (because they are ``QtmacsApplet`` # instances), whereas splitters are added with ``insertWidget``, NOT # ``qteInsertWidget``. The reason is that splitters do not require the # extra TLC necessary for applets in terms of how and where to show # them. newSplit = QtmacsSplitter(splitOrientation, windowObj) curApp.setParent(None) newSplit.qteAddWidget(curApp) newSplit.qteAddWidget(newAppObj) split.insertWidget(curAppIdx, newSplit) # Adjust the size of two widgets in ``split`` (ie. ``newSplit`` and # whatever other widget) to take up equal space. The same adjusment is # made for ``newSplit``, but there the ``qteAddWidget`` methods have # already taken care of it. split.qteAdjustWidgetSizes() return True
python
def qteSplitApplet(self, applet: (QtmacsApplet, str)=None, splitHoriz: bool=True, windowObj: QtmacsWindow=None): """ Reveal ``applet`` by splitting the space occupied by the current applet. If ``applet`` is already visible then the method does nothing. Furthermore, this method does not change the focus, ie. the currently active applet will remain active. If ``applet`` is **None** then the next invisible applet will be shown. If ``windowObj`` is **None** then the currently active window will be used. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. |Args| * ``applet`` (**QtmacsApplet**, **str**): the applet to reveal. * ``splitHoriz`` (**bool**): whether to split horizontally or vertically. * ``windowObj`` (**QtmacsWindow**): the window in which to reveal ``applet``. |Returns| * **bool**: if **True**, ``applet`` was revealed. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``newAppObj`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``newAppObj`` is already an instance of ``QtmacsApplet`` # then use it directly. if isinstance(applet, str): newAppObj = self.qteGetAppletHandle(applet) else: newAppObj = applet # Use the currently active window if none was specified. if windowObj is None: windowObj = self.qteActiveWindow() if windowObj is None: msg = 'Cannot determine the currently active window.' self.qteLogger.error(msg, stack_info=True) return # Convert ``splitHoriz`` to the respective Qt constant. if splitHoriz: splitOrientation = QtCore.Qt.Horizontal else: splitOrientation = QtCore.Qt.Vertical if newAppObj is None: # If no new applet was specified use the next available # invisible applet. newAppObj = self.qteNextApplet(skipVisible=True, skipInvisible=False) else: # Do nothing if the new applet is already visible. if newAppObj.qteIsVisible(): return False # If we still have not found an applet then there are no # invisible applets left to show. Therefore, splitting makes # no sense. if newAppObj is None: self.qteLogger.warning('All applets are already visible.') return False # If the root splitter is empty then add the new applet and # return immediately. if windowObj.qteAppletSplitter.count() == 0: windowObj.qteAppletSplitter.qteAddWidget(newAppObj) windowObj.qteAppletSplitter.setOrientation(splitOrientation) return True # ------------------------------------------------------------ # The root splitter contains at least one widget, if we got # this far. # ------------------------------------------------------------ # Shorthand to last active applet in the current window. Query # this applet with qteNextApplet method because # self._qteActiveApplet may be a mini applet, and we are only # interested in genuine applets. curApp = self.qteNextApplet(numSkip=0, windowObj=windowObj) # Get a reference to the splitter in which the currently # active applet lives. This may be the root splitter, or one # of its child splitters. split = self._qteFindAppletInSplitter( curApp, windowObj.qteAppletSplitter) if split is None: msg = 'Active applet <b>{}</b> not in the layout.' msg = msg.format(curApp.qteAppletID()) self.qteLogger.error(msg, stack_info=True) return False # If 'curApp' lives in the root splitter, and the root # splitter contains only a single element, then simply add the # new applet as the second element and return. if split is windowObj.qteAppletSplitter: if split.count() == 1: split.qteAddWidget(newAppObj) split.setOrientation(splitOrientation) return True # ------------------------------------------------------------ # The splitter (root or not) contains two widgets, if we got # this far. # ------------------------------------------------------------ # Determine the index of the applet inside the splitter. curAppIdx = split.indexOf(curApp) # Create a new splitter and populate it with 'curApp' and the # previously invisible ``newAppObj``. Then insert this new splitter at # the position where the old applet was taken from. Note: widgets are # inserted with ``qteAddWidget`` (because they are ``QtmacsApplet`` # instances), whereas splitters are added with ``insertWidget``, NOT # ``qteInsertWidget``. The reason is that splitters do not require the # extra TLC necessary for applets in terms of how and where to show # them. newSplit = QtmacsSplitter(splitOrientation, windowObj) curApp.setParent(None) newSplit.qteAddWidget(curApp) newSplit.qteAddWidget(newAppObj) split.insertWidget(curAppIdx, newSplit) # Adjust the size of two widgets in ``split`` (ie. ``newSplit`` and # whatever other widget) to take up equal space. The same adjusment is # made for ``newSplit``, but there the ``qteAddWidget`` methods have # already taken care of it. split.qteAdjustWidgetSizes() return True
[ "def", "qteSplitApplet", "(", "self", ",", "applet", ":", "(", "QtmacsApplet", ",", "str", ")", "=", "None", ",", "splitHoriz", ":", "bool", "=", "True", ",", "windowObj", ":", "QtmacsWindow", "=", "None", ")", ":", "# If ``newAppObj`` was specified by its ID (ie. a string) then", "# fetch the associated ``QtmacsApplet`` instance. If", "# ``newAppObj`` is already an instance of ``QtmacsApplet``", "# then use it directly.", "if", "isinstance", "(", "applet", ",", "str", ")", ":", "newAppObj", "=", "self", ".", "qteGetAppletHandle", "(", "applet", ")", "else", ":", "newAppObj", "=", "applet", "# Use the currently active window if none was specified.", "if", "windowObj", "is", "None", ":", "windowObj", "=", "self", ".", "qteActiveWindow", "(", ")", "if", "windowObj", "is", "None", ":", "msg", "=", "'Cannot determine the currently active window.'", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "# Convert ``splitHoriz`` to the respective Qt constant.", "if", "splitHoriz", ":", "splitOrientation", "=", "QtCore", ".", "Qt", ".", "Horizontal", "else", ":", "splitOrientation", "=", "QtCore", ".", "Qt", ".", "Vertical", "if", "newAppObj", "is", "None", ":", "# If no new applet was specified use the next available", "# invisible applet.", "newAppObj", "=", "self", ".", "qteNextApplet", "(", "skipVisible", "=", "True", ",", "skipInvisible", "=", "False", ")", "else", ":", "# Do nothing if the new applet is already visible.", "if", "newAppObj", ".", "qteIsVisible", "(", ")", ":", "return", "False", "# If we still have not found an applet then there are no", "# invisible applets left to show. Therefore, splitting makes", "# no sense.", "if", "newAppObj", "is", "None", ":", "self", ".", "qteLogger", ".", "warning", "(", "'All applets are already visible.'", ")", "return", "False", "# If the root splitter is empty then add the new applet and", "# return immediately.", "if", "windowObj", ".", "qteAppletSplitter", ".", "count", "(", ")", "==", "0", ":", "windowObj", ".", "qteAppletSplitter", ".", "qteAddWidget", "(", "newAppObj", ")", "windowObj", ".", "qteAppletSplitter", ".", "setOrientation", "(", "splitOrientation", ")", "return", "True", "# ------------------------------------------------------------", "# The root splitter contains at least one widget, if we got", "# this far.", "# ------------------------------------------------------------", "# Shorthand to last active applet in the current window. Query", "# this applet with qteNextApplet method because", "# self._qteActiveApplet may be a mini applet, and we are only", "# interested in genuine applets.", "curApp", "=", "self", ".", "qteNextApplet", "(", "numSkip", "=", "0", ",", "windowObj", "=", "windowObj", ")", "# Get a reference to the splitter in which the currently", "# active applet lives. This may be the root splitter, or one", "# of its child splitters.", "split", "=", "self", ".", "_qteFindAppletInSplitter", "(", "curApp", ",", "windowObj", ".", "qteAppletSplitter", ")", "if", "split", "is", "None", ":", "msg", "=", "'Active applet <b>{}</b> not in the layout.'", "msg", "=", "msg", ".", "format", "(", "curApp", ".", "qteAppletID", "(", ")", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "False", "# If 'curApp' lives in the root splitter, and the root", "# splitter contains only a single element, then simply add the", "# new applet as the second element and return.", "if", "split", "is", "windowObj", ".", "qteAppletSplitter", ":", "if", "split", ".", "count", "(", ")", "==", "1", ":", "split", ".", "qteAddWidget", "(", "newAppObj", ")", "split", ".", "setOrientation", "(", "splitOrientation", ")", "return", "True", "# ------------------------------------------------------------", "# The splitter (root or not) contains two widgets, if we got", "# this far.", "# ------------------------------------------------------------", "# Determine the index of the applet inside the splitter.", "curAppIdx", "=", "split", ".", "indexOf", "(", "curApp", ")", "# Create a new splitter and populate it with 'curApp' and the", "# previously invisible ``newAppObj``. Then insert this new splitter at", "# the position where the old applet was taken from. Note: widgets are", "# inserted with ``qteAddWidget`` (because they are ``QtmacsApplet``", "# instances), whereas splitters are added with ``insertWidget``, NOT", "# ``qteInsertWidget``. The reason is that splitters do not require the", "# extra TLC necessary for applets in terms of how and where to show", "# them.", "newSplit", "=", "QtmacsSplitter", "(", "splitOrientation", ",", "windowObj", ")", "curApp", ".", "setParent", "(", "None", ")", "newSplit", ".", "qteAddWidget", "(", "curApp", ")", "newSplit", ".", "qteAddWidget", "(", "newAppObj", ")", "split", ".", "insertWidget", "(", "curAppIdx", ",", "newSplit", ")", "# Adjust the size of two widgets in ``split`` (ie. ``newSplit`` and", "# whatever other widget) to take up equal space. The same adjusment is", "# made for ``newSplit``, but there the ``qteAddWidget`` methods have", "# already taken care of it.", "split", ".", "qteAdjustWidgetSizes", "(", ")", "return", "True" ]
Reveal ``applet`` by splitting the space occupied by the current applet. If ``applet`` is already visible then the method does nothing. Furthermore, this method does not change the focus, ie. the currently active applet will remain active. If ``applet`` is **None** then the next invisible applet will be shown. If ``windowObj`` is **None** then the currently active window will be used. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. |Args| * ``applet`` (**QtmacsApplet**, **str**): the applet to reveal. * ``splitHoriz`` (**bool**): whether to split horizontally or vertically. * ``windowObj`` (**QtmacsWindow**): the window in which to reveal ``applet``. |Returns| * **bool**: if **True**, ``applet`` was revealed. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Reveal", "applet", "by", "splitting", "the", "space", "occupied", "by", "the", "current", "applet", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2222-L2363
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteReplaceAppletInLayout
def qteReplaceAppletInLayout(self, newApplet: (QtmacsApplet, str), oldApplet: (QtmacsApplet, str)=None, windowObj: QtmacsWindow=None): """ Replace ``oldApplet`` with ``newApplet`` in the window layout. If ``oldApplet`` is **None** then the currently active applet will be replaced. If ``windowObj`` is **None** then the currently active window is used. The ``oldApplet`` and ``newApplet`` parameters can either be instances of ``QtmacsApplet`` or strings denoting the applet IDs. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instances. |Args| * ``newApplet`` (**QtmacsApplet**, **str**): applet to add. * ``oldApplet`` (**QtmacsApplet**, **str**): applet to replace. * ``windowObj`` (**QtmacsWindow**): the window in which to operate. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``oldAppObj`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``oldAppObj`` is already an instance of ``QtmacsApplet`` # then use it directly. if isinstance(oldApplet, str): oldAppObj = self.qteGetAppletHandle(oldApplet) else: oldAppObj = oldApplet # If ``newAppObj`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``newAppObj`` is already an instance of ``QtmacsApplet`` # then use it directly. if isinstance(newApplet, str): newAppObj = self.qteGetAppletHandle(newApplet) else: newAppObj = newApplet # Use the currently active window if none was specified. if windowObj is None: windowObj = self.qteActiveWindow() if windowObj is None: msg = 'Cannot determine the currently active window.' self.qteLogger.warning(msg, stack_info=True) return # If the main splitter contains no applet then just add newAppObj. if windowObj.qteAppletSplitter.count() == 0: windowObj.qteAppletSplitter.qteAddWidget(newAppObj) return # If no oldAppObj was specified use the currently active one # instead. Do not use qteActiveApplet to determine it, though, # because it may point to a mini buffer. If it is, then we # need the last active Qtmacs applet. In either case, the # qteNextApplet method will take care of these distinctions. if oldAppObj is None: oldAppObj = self.qteNextApplet(numSkip=0, windowObj=windowObj) # Sanity check: the applet to replace must exist. if oldAppObj is None: msg = 'Applet to replace does not exist.' self.qteLogger.error(msg, stack_info=True) return # Sanity check: do nothing if the old- and new applet are the # same. if newAppObj is oldAppObj: return # Sanity check: do nothing if both applets are already # visible. if oldAppObj.qteIsVisible() and newAppObj.qteIsVisible(): return # Search for the splitter that contains 'oldAppObj'. split = self._qteFindAppletInSplitter( oldAppObj, windowObj.qteAppletSplitter) if split is None: msg = ('Applet <b>{}</b> not replaced because it is not' 'in the layout.'.format(oldAppObj.qteAppletID())) self.qteLogger.warning(msg) return # Determine the position of oldAppObj inside the splitter. oldAppIdx = split.indexOf(oldAppObj) # Replace oldAppObj with newAppObj but maintain the widget sizes. To do # so, first insert newAppObj into the splitter at the position of # oldAppObj. Afterwards, remove oldAppObj by re-parenting it, make # it invisible, and restore the widget sizes. sizes = split.sizes() split.qteInsertWidget(oldAppIdx, newAppObj) oldAppObj.hide(True) split.setSizes(sizes)
python
def qteReplaceAppletInLayout(self, newApplet: (QtmacsApplet, str), oldApplet: (QtmacsApplet, str)=None, windowObj: QtmacsWindow=None): """ Replace ``oldApplet`` with ``newApplet`` in the window layout. If ``oldApplet`` is **None** then the currently active applet will be replaced. If ``windowObj`` is **None** then the currently active window is used. The ``oldApplet`` and ``newApplet`` parameters can either be instances of ``QtmacsApplet`` or strings denoting the applet IDs. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instances. |Args| * ``newApplet`` (**QtmacsApplet**, **str**): applet to add. * ``oldApplet`` (**QtmacsApplet**, **str**): applet to replace. * ``windowObj`` (**QtmacsWindow**): the window in which to operate. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``oldAppObj`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``oldAppObj`` is already an instance of ``QtmacsApplet`` # then use it directly. if isinstance(oldApplet, str): oldAppObj = self.qteGetAppletHandle(oldApplet) else: oldAppObj = oldApplet # If ``newAppObj`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``newAppObj`` is already an instance of ``QtmacsApplet`` # then use it directly. if isinstance(newApplet, str): newAppObj = self.qteGetAppletHandle(newApplet) else: newAppObj = newApplet # Use the currently active window if none was specified. if windowObj is None: windowObj = self.qteActiveWindow() if windowObj is None: msg = 'Cannot determine the currently active window.' self.qteLogger.warning(msg, stack_info=True) return # If the main splitter contains no applet then just add newAppObj. if windowObj.qteAppletSplitter.count() == 0: windowObj.qteAppletSplitter.qteAddWidget(newAppObj) return # If no oldAppObj was specified use the currently active one # instead. Do not use qteActiveApplet to determine it, though, # because it may point to a mini buffer. If it is, then we # need the last active Qtmacs applet. In either case, the # qteNextApplet method will take care of these distinctions. if oldAppObj is None: oldAppObj = self.qteNextApplet(numSkip=0, windowObj=windowObj) # Sanity check: the applet to replace must exist. if oldAppObj is None: msg = 'Applet to replace does not exist.' self.qteLogger.error(msg, stack_info=True) return # Sanity check: do nothing if the old- and new applet are the # same. if newAppObj is oldAppObj: return # Sanity check: do nothing if both applets are already # visible. if oldAppObj.qteIsVisible() and newAppObj.qteIsVisible(): return # Search for the splitter that contains 'oldAppObj'. split = self._qteFindAppletInSplitter( oldAppObj, windowObj.qteAppletSplitter) if split is None: msg = ('Applet <b>{}</b> not replaced because it is not' 'in the layout.'.format(oldAppObj.qteAppletID())) self.qteLogger.warning(msg) return # Determine the position of oldAppObj inside the splitter. oldAppIdx = split.indexOf(oldAppObj) # Replace oldAppObj with newAppObj but maintain the widget sizes. To do # so, first insert newAppObj into the splitter at the position of # oldAppObj. Afterwards, remove oldAppObj by re-parenting it, make # it invisible, and restore the widget sizes. sizes = split.sizes() split.qteInsertWidget(oldAppIdx, newAppObj) oldAppObj.hide(True) split.setSizes(sizes)
[ "def", "qteReplaceAppletInLayout", "(", "self", ",", "newApplet", ":", "(", "QtmacsApplet", ",", "str", ")", ",", "oldApplet", ":", "(", "QtmacsApplet", ",", "str", ")", "=", "None", ",", "windowObj", ":", "QtmacsWindow", "=", "None", ")", ":", "# If ``oldAppObj`` was specified by its ID (ie. a string) then", "# fetch the associated ``QtmacsApplet`` instance. If", "# ``oldAppObj`` is already an instance of ``QtmacsApplet``", "# then use it directly.", "if", "isinstance", "(", "oldApplet", ",", "str", ")", ":", "oldAppObj", "=", "self", ".", "qteGetAppletHandle", "(", "oldApplet", ")", "else", ":", "oldAppObj", "=", "oldApplet", "# If ``newAppObj`` was specified by its ID (ie. a string) then", "# fetch the associated ``QtmacsApplet`` instance. If", "# ``newAppObj`` is already an instance of ``QtmacsApplet``", "# then use it directly.", "if", "isinstance", "(", "newApplet", ",", "str", ")", ":", "newAppObj", "=", "self", ".", "qteGetAppletHandle", "(", "newApplet", ")", "else", ":", "newAppObj", "=", "newApplet", "# Use the currently active window if none was specified.", "if", "windowObj", "is", "None", ":", "windowObj", "=", "self", ".", "qteActiveWindow", "(", ")", "if", "windowObj", "is", "None", ":", "msg", "=", "'Cannot determine the currently active window.'", "self", ".", "qteLogger", ".", "warning", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "# If the main splitter contains no applet then just add newAppObj.", "if", "windowObj", ".", "qteAppletSplitter", ".", "count", "(", ")", "==", "0", ":", "windowObj", ".", "qteAppletSplitter", ".", "qteAddWidget", "(", "newAppObj", ")", "return", "# If no oldAppObj was specified use the currently active one", "# instead. Do not use qteActiveApplet to determine it, though,", "# because it may point to a mini buffer. If it is, then we", "# need the last active Qtmacs applet. In either case, the", "# qteNextApplet method will take care of these distinctions.", "if", "oldAppObj", "is", "None", ":", "oldAppObj", "=", "self", ".", "qteNextApplet", "(", "numSkip", "=", "0", ",", "windowObj", "=", "windowObj", ")", "# Sanity check: the applet to replace must exist.", "if", "oldAppObj", "is", "None", ":", "msg", "=", "'Applet to replace does not exist.'", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "# Sanity check: do nothing if the old- and new applet are the", "# same.", "if", "newAppObj", "is", "oldAppObj", ":", "return", "# Sanity check: do nothing if both applets are already", "# visible.", "if", "oldAppObj", ".", "qteIsVisible", "(", ")", "and", "newAppObj", ".", "qteIsVisible", "(", ")", ":", "return", "# Search for the splitter that contains 'oldAppObj'.", "split", "=", "self", ".", "_qteFindAppletInSplitter", "(", "oldAppObj", ",", "windowObj", ".", "qteAppletSplitter", ")", "if", "split", "is", "None", ":", "msg", "=", "(", "'Applet <b>{}</b> not replaced because it is not'", "'in the layout.'", ".", "format", "(", "oldAppObj", ".", "qteAppletID", "(", ")", ")", ")", "self", ".", "qteLogger", ".", "warning", "(", "msg", ")", "return", "# Determine the position of oldAppObj inside the splitter.", "oldAppIdx", "=", "split", ".", "indexOf", "(", "oldAppObj", ")", "# Replace oldAppObj with newAppObj but maintain the widget sizes. To do", "# so, first insert newAppObj into the splitter at the position of", "# oldAppObj. Afterwards, remove oldAppObj by re-parenting it, make", "# it invisible, and restore the widget sizes.", "sizes", "=", "split", ".", "sizes", "(", ")", "split", ".", "qteInsertWidget", "(", "oldAppIdx", ",", "newAppObj", ")", "oldAppObj", ".", "hide", "(", "True", ")", "split", ".", "setSizes", "(", "sizes", ")" ]
Replace ``oldApplet`` with ``newApplet`` in the window layout. If ``oldApplet`` is **None** then the currently active applet will be replaced. If ``windowObj`` is **None** then the currently active window is used. The ``oldApplet`` and ``newApplet`` parameters can either be instances of ``QtmacsApplet`` or strings denoting the applet IDs. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instances. |Args| * ``newApplet`` (**QtmacsApplet**, **str**): applet to add. * ``oldApplet`` (**QtmacsApplet**, **str**): applet to replace. * ``windowObj`` (**QtmacsWindow**): the window in which to operate. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Replace", "oldApplet", "with", "newApplet", "in", "the", "window", "layout", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2366-L2469
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteRemoveAppletFromLayout
def qteRemoveAppletFromLayout(self, applet: (QtmacsApplet, str)): """ Remove ``applet`` from the window layout. This method removes ``applet`` and implicitly deletes obsolete (ie. half-full) splitters in the process. If ``applet`` is the only visible applet in the layout then it will be replaced with the first invisible applet. If no invisible applets are left then the method does nothing. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. If ``applet`` does not refer to an existing applet then nothing happens. |Args| * ``applet`` (**QtmacsApplet**, **str**): the applet to remove from the layout. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance(applet, str): appletObj = self.qteGetAppletHandle(applet) else: appletObj = applet # Return immediately if the applet does not exist in any splitter. for window in self._qteWindowList: split = self._qteFindAppletInSplitter( appletObj, window.qteAppletSplitter) if split is not None: break if split is None: return # If the applet lives in the main splitter and is the only # widget there it must be replaced with another applet. This # case needs to be handled separately from the other options # because every other splitter will always contain exactly two # items (ie. two applets, two splitters, or one of each). if (split is window.qteAppletSplitter) and (split.count() == 1): # Remove the existing applet object from the splitter and # hide it. split.widget(0).hide(True) # Get the next available applet to focus on. Try to find a # visible applet in the current window, and if none exists # then pick the first invisible one. If there is neither # a visible nor an invisible applet left then do nothing. nextApp = self.qteNextApplet(windowObj=window) if nextApp is None: nextApp = self.qteNextApplet(skipInvisible=False, skipVisible=True) if nextApp is None: return # Ok, we found an applet to show. split.qteAddWidget(nextApp) return # ------------------------------------------------------------ # If we got until here we know that the splitter (root or not) # contains (at least) two elements. Note: if it contains more # than two elements then there is a bug somewhere. # ------------------------------------------------------------ # Find the index of the object inside the splitter. appletIdx = split.indexOf(appletObj) # Detach the applet from the splitter and make it invisible. appletObj.hide(True) # Verify that really only one additional element is left in # the splitter. If not, then something is wrong. if split.count() != 1: msg = ('Splitter has <b>{}</b> elements left instead of' ' exactly one.'.format(split.count())) self.qteLogger.warning(msg) # Get a reference to the other widget in the splitter (either # a QtmacsSplitter or a QtmacsApplet). otherWidget = split.widget(0) # Is the other widget another splitter? if otherWidget._qteAdmin.widgetSignature == '__QtmacsLayoutSplitter__': # Yes, ``otherWidget`` is a QtmacsSplitter object, # therefore shift all its widgets over to the current # splitter. for ii in range(otherWidget.count()): # Get the next widget from that splitter. Note that we # always pick the widget at the 0'th position because # the splitter will re-index the remaining widgets # after each removal. obj = otherWidget.widget(0) if appletIdx == 0: split.qteAddWidget(obj) else: split.qteInsertWidget(1 + ii, obj) # Delete the child splitter. otherWidget.setParent(None) otherWidget.close() else: # No, ``otherWidget`` is a QtmacsApplet, therefore move it # to the parent splitter and delete the current one, # unless 'split' is the root splitter in which case # nothing happens. if split is not window.qteAppletSplitter: otherWidget.qteReparent(split.parent()) split.setParent(None) split.close()
python
def qteRemoveAppletFromLayout(self, applet: (QtmacsApplet, str)): """ Remove ``applet`` from the window layout. This method removes ``applet`` and implicitly deletes obsolete (ie. half-full) splitters in the process. If ``applet`` is the only visible applet in the layout then it will be replaced with the first invisible applet. If no invisible applets are left then the method does nothing. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. If ``applet`` does not refer to an existing applet then nothing happens. |Args| * ``applet`` (**QtmacsApplet**, **str**): the applet to remove from the layout. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance(applet, str): appletObj = self.qteGetAppletHandle(applet) else: appletObj = applet # Return immediately if the applet does not exist in any splitter. for window in self._qteWindowList: split = self._qteFindAppletInSplitter( appletObj, window.qteAppletSplitter) if split is not None: break if split is None: return # If the applet lives in the main splitter and is the only # widget there it must be replaced with another applet. This # case needs to be handled separately from the other options # because every other splitter will always contain exactly two # items (ie. two applets, two splitters, or one of each). if (split is window.qteAppletSplitter) and (split.count() == 1): # Remove the existing applet object from the splitter and # hide it. split.widget(0).hide(True) # Get the next available applet to focus on. Try to find a # visible applet in the current window, and if none exists # then pick the first invisible one. If there is neither # a visible nor an invisible applet left then do nothing. nextApp = self.qteNextApplet(windowObj=window) if nextApp is None: nextApp = self.qteNextApplet(skipInvisible=False, skipVisible=True) if nextApp is None: return # Ok, we found an applet to show. split.qteAddWidget(nextApp) return # ------------------------------------------------------------ # If we got until here we know that the splitter (root or not) # contains (at least) two elements. Note: if it contains more # than two elements then there is a bug somewhere. # ------------------------------------------------------------ # Find the index of the object inside the splitter. appletIdx = split.indexOf(appletObj) # Detach the applet from the splitter and make it invisible. appletObj.hide(True) # Verify that really only one additional element is left in # the splitter. If not, then something is wrong. if split.count() != 1: msg = ('Splitter has <b>{}</b> elements left instead of' ' exactly one.'.format(split.count())) self.qteLogger.warning(msg) # Get a reference to the other widget in the splitter (either # a QtmacsSplitter or a QtmacsApplet). otherWidget = split.widget(0) # Is the other widget another splitter? if otherWidget._qteAdmin.widgetSignature == '__QtmacsLayoutSplitter__': # Yes, ``otherWidget`` is a QtmacsSplitter object, # therefore shift all its widgets over to the current # splitter. for ii in range(otherWidget.count()): # Get the next widget from that splitter. Note that we # always pick the widget at the 0'th position because # the splitter will re-index the remaining widgets # after each removal. obj = otherWidget.widget(0) if appletIdx == 0: split.qteAddWidget(obj) else: split.qteInsertWidget(1 + ii, obj) # Delete the child splitter. otherWidget.setParent(None) otherWidget.close() else: # No, ``otherWidget`` is a QtmacsApplet, therefore move it # to the parent splitter and delete the current one, # unless 'split' is the root splitter in which case # nothing happens. if split is not window.qteAppletSplitter: otherWidget.qteReparent(split.parent()) split.setParent(None) split.close()
[ "def", "qteRemoveAppletFromLayout", "(", "self", ",", "applet", ":", "(", "QtmacsApplet", ",", "str", ")", ")", ":", "# If ``applet`` was specified by its ID (ie. a string) then", "# fetch the associated ``QtmacsApplet`` instance. If", "# ``applet`` is already an instance of ``QtmacsApplet`` then", "# use it directly.", "if", "isinstance", "(", "applet", ",", "str", ")", ":", "appletObj", "=", "self", ".", "qteGetAppletHandle", "(", "applet", ")", "else", ":", "appletObj", "=", "applet", "# Return immediately if the applet does not exist in any splitter.", "for", "window", "in", "self", ".", "_qteWindowList", ":", "split", "=", "self", ".", "_qteFindAppletInSplitter", "(", "appletObj", ",", "window", ".", "qteAppletSplitter", ")", "if", "split", "is", "not", "None", ":", "break", "if", "split", "is", "None", ":", "return", "# If the applet lives in the main splitter and is the only", "# widget there it must be replaced with another applet. This", "# case needs to be handled separately from the other options", "# because every other splitter will always contain exactly two", "# items (ie. two applets, two splitters, or one of each).", "if", "(", "split", "is", "window", ".", "qteAppletSplitter", ")", "and", "(", "split", ".", "count", "(", ")", "==", "1", ")", ":", "# Remove the existing applet object from the splitter and", "# hide it.", "split", ".", "widget", "(", "0", ")", ".", "hide", "(", "True", ")", "# Get the next available applet to focus on. Try to find a", "# visible applet in the current window, and if none exists", "# then pick the first invisible one. If there is neither", "# a visible nor an invisible applet left then do nothing.", "nextApp", "=", "self", ".", "qteNextApplet", "(", "windowObj", "=", "window", ")", "if", "nextApp", "is", "None", ":", "nextApp", "=", "self", ".", "qteNextApplet", "(", "skipInvisible", "=", "False", ",", "skipVisible", "=", "True", ")", "if", "nextApp", "is", "None", ":", "return", "# Ok, we found an applet to show.", "split", ".", "qteAddWidget", "(", "nextApp", ")", "return", "# ------------------------------------------------------------", "# If we got until here we know that the splitter (root or not)", "# contains (at least) two elements. Note: if it contains more", "# than two elements then there is a bug somewhere.", "# ------------------------------------------------------------", "# Find the index of the object inside the splitter.", "appletIdx", "=", "split", ".", "indexOf", "(", "appletObj", ")", "# Detach the applet from the splitter and make it invisible.", "appletObj", ".", "hide", "(", "True", ")", "# Verify that really only one additional element is left in", "# the splitter. If not, then something is wrong.", "if", "split", ".", "count", "(", ")", "!=", "1", ":", "msg", "=", "(", "'Splitter has <b>{}</b> elements left instead of'", "' exactly one.'", ".", "format", "(", "split", ".", "count", "(", ")", ")", ")", "self", ".", "qteLogger", ".", "warning", "(", "msg", ")", "# Get a reference to the other widget in the splitter (either", "# a QtmacsSplitter or a QtmacsApplet).", "otherWidget", "=", "split", ".", "widget", "(", "0", ")", "# Is the other widget another splitter?", "if", "otherWidget", ".", "_qteAdmin", ".", "widgetSignature", "==", "'__QtmacsLayoutSplitter__'", ":", "# Yes, ``otherWidget`` is a QtmacsSplitter object,", "# therefore shift all its widgets over to the current", "# splitter.", "for", "ii", "in", "range", "(", "otherWidget", ".", "count", "(", ")", ")", ":", "# Get the next widget from that splitter. Note that we", "# always pick the widget at the 0'th position because", "# the splitter will re-index the remaining widgets", "# after each removal.", "obj", "=", "otherWidget", ".", "widget", "(", "0", ")", "if", "appletIdx", "==", "0", ":", "split", ".", "qteAddWidget", "(", "obj", ")", "else", ":", "split", ".", "qteInsertWidget", "(", "1", "+", "ii", ",", "obj", ")", "# Delete the child splitter.", "otherWidget", ".", "setParent", "(", "None", ")", "otherWidget", ".", "close", "(", ")", "else", ":", "# No, ``otherWidget`` is a QtmacsApplet, therefore move it", "# to the parent splitter and delete the current one,", "# unless 'split' is the root splitter in which case", "# nothing happens.", "if", "split", "is", "not", "window", ".", "qteAppletSplitter", ":", "otherWidget", ".", "qteReparent", "(", "split", ".", "parent", "(", ")", ")", "split", ".", "setParent", "(", "None", ")", "split", ".", "close", "(", ")" ]
Remove ``applet`` from the window layout. This method removes ``applet`` and implicitly deletes obsolete (ie. half-full) splitters in the process. If ``applet`` is the only visible applet in the layout then it will be replaced with the first invisible applet. If no invisible applets are left then the method does nothing. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. If ``applet`` does not refer to an existing applet then nothing happens. |Args| * ``applet`` (**QtmacsApplet**, **str**): the applet to remove from the layout. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Remove", "applet", "from", "the", "window", "layout", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2472-L2596
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteKillApplet
def qteKillApplet(self, appletID: str): """ Destroy the applet with ID ``appletID``. This method removes ``appletID`` from Qtmacs permanently - no questions asked. It is the responsibility of the (macro) programmer to use it responsibly. If the applet was visible then the method also takes care of replacing with the next invisible applet, if one is available. If ``appletID`` does not refer to a valid applet then nothing happens. |Args| * ``appletID`` (**str**): name of applet to be destroyed. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Compile list of all applet IDs. ID_list = [_.qteAppletID() for _ in self._qteAppletList] if appletID not in ID_list: # Do nothing if the applet does not exist. return else: # Get a reference to the actual applet object based on the # name. idx = ID_list.index(appletID) appObj = self._qteAppletList[idx] # Mini applets are killed with a special method. if self.qteIsMiniApplet(appObj): self.qteKillMiniApplet() return # Inform the applet that it is about to be killed. appObj.qteToBeKilled() # Determine the window of the applet. window = appObj.qteParentWindow() # Get the previous invisible applet (*may* come in handy a few # lines below). newApplet = self.qteNextApplet(numSkip=-1, skipInvisible=False, skipVisible=True) # If there is no invisible applet available, or the only available # applet is the one to be killed, then set newApplet to None. if (newApplet is None) or (newApplet is appObj): newApplet = None else: self.qteReplaceAppletInLayout(newApplet, appObj, window) # Ensure that _qteActiveApplet does not point to the applet # to be killed as it will otherwise result in a dangling # pointer. if self._qteActiveApplet is appObj: self._qteActiveApplet = newApplet # Remove the applet object from the applet list. self.qteLogger.debug('Kill applet: <b>{}</b>'.format(appletID)) self._qteAppletList.remove(appObj) # Close the applet and schedule it for destruction. Explicitly # call the sip.delete() method to ensure that all signals are # *immediately* disconnected, as otherwise there is a good # chance that Qtmacs segfaults if Python/Qt thinks the slots # are still connected when really the object does not exist # anymore. appObj.close() sip.delete(appObj)
python
def qteKillApplet(self, appletID: str): """ Destroy the applet with ID ``appletID``. This method removes ``appletID`` from Qtmacs permanently - no questions asked. It is the responsibility of the (macro) programmer to use it responsibly. If the applet was visible then the method also takes care of replacing with the next invisible applet, if one is available. If ``appletID`` does not refer to a valid applet then nothing happens. |Args| * ``appletID`` (**str**): name of applet to be destroyed. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Compile list of all applet IDs. ID_list = [_.qteAppletID() for _ in self._qteAppletList] if appletID not in ID_list: # Do nothing if the applet does not exist. return else: # Get a reference to the actual applet object based on the # name. idx = ID_list.index(appletID) appObj = self._qteAppletList[idx] # Mini applets are killed with a special method. if self.qteIsMiniApplet(appObj): self.qteKillMiniApplet() return # Inform the applet that it is about to be killed. appObj.qteToBeKilled() # Determine the window of the applet. window = appObj.qteParentWindow() # Get the previous invisible applet (*may* come in handy a few # lines below). newApplet = self.qteNextApplet(numSkip=-1, skipInvisible=False, skipVisible=True) # If there is no invisible applet available, or the only available # applet is the one to be killed, then set newApplet to None. if (newApplet is None) or (newApplet is appObj): newApplet = None else: self.qteReplaceAppletInLayout(newApplet, appObj, window) # Ensure that _qteActiveApplet does not point to the applet # to be killed as it will otherwise result in a dangling # pointer. if self._qteActiveApplet is appObj: self._qteActiveApplet = newApplet # Remove the applet object from the applet list. self.qteLogger.debug('Kill applet: <b>{}</b>'.format(appletID)) self._qteAppletList.remove(appObj) # Close the applet and schedule it for destruction. Explicitly # call the sip.delete() method to ensure that all signals are # *immediately* disconnected, as otherwise there is a good # chance that Qtmacs segfaults if Python/Qt thinks the slots # are still connected when really the object does not exist # anymore. appObj.close() sip.delete(appObj)
[ "def", "qteKillApplet", "(", "self", ",", "appletID", ":", "str", ")", ":", "# Compile list of all applet IDs.", "ID_list", "=", "[", "_", ".", "qteAppletID", "(", ")", "for", "_", "in", "self", ".", "_qteAppletList", "]", "if", "appletID", "not", "in", "ID_list", ":", "# Do nothing if the applet does not exist.", "return", "else", ":", "# Get a reference to the actual applet object based on the", "# name.", "idx", "=", "ID_list", ".", "index", "(", "appletID", ")", "appObj", "=", "self", ".", "_qteAppletList", "[", "idx", "]", "# Mini applets are killed with a special method.", "if", "self", ".", "qteIsMiniApplet", "(", "appObj", ")", ":", "self", ".", "qteKillMiniApplet", "(", ")", "return", "# Inform the applet that it is about to be killed.", "appObj", ".", "qteToBeKilled", "(", ")", "# Determine the window of the applet.", "window", "=", "appObj", ".", "qteParentWindow", "(", ")", "# Get the previous invisible applet (*may* come in handy a few", "# lines below).", "newApplet", "=", "self", ".", "qteNextApplet", "(", "numSkip", "=", "-", "1", ",", "skipInvisible", "=", "False", ",", "skipVisible", "=", "True", ")", "# If there is no invisible applet available, or the only available", "# applet is the one to be killed, then set newApplet to None.", "if", "(", "newApplet", "is", "None", ")", "or", "(", "newApplet", "is", "appObj", ")", ":", "newApplet", "=", "None", "else", ":", "self", ".", "qteReplaceAppletInLayout", "(", "newApplet", ",", "appObj", ",", "window", ")", "# Ensure that _qteActiveApplet does not point to the applet", "# to be killed as it will otherwise result in a dangling", "# pointer.", "if", "self", ".", "_qteActiveApplet", "is", "appObj", ":", "self", ".", "_qteActiveApplet", "=", "newApplet", "# Remove the applet object from the applet list.", "self", ".", "qteLogger", ".", "debug", "(", "'Kill applet: <b>{}</b>'", ".", "format", "(", "appletID", ")", ")", "self", ".", "_qteAppletList", ".", "remove", "(", "appObj", ")", "# Close the applet and schedule it for destruction. Explicitly", "# call the sip.delete() method to ensure that all signals are", "# *immediately* disconnected, as otherwise there is a good", "# chance that Qtmacs segfaults if Python/Qt thinks the slots", "# are still connected when really the object does not exist", "# anymore.", "appObj", ".", "close", "(", ")", "sip", ".", "delete", "(", "appObj", ")" ]
Destroy the applet with ID ``appletID``. This method removes ``appletID`` from Qtmacs permanently - no questions asked. It is the responsibility of the (macro) programmer to use it responsibly. If the applet was visible then the method also takes care of replacing with the next invisible applet, if one is available. If ``appletID`` does not refer to a valid applet then nothing happens. |Args| * ``appletID`` (**str**): name of applet to be destroyed. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Destroy", "the", "applet", "with", "ID", "appletID", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2599-L2677
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteRunHook
def qteRunHook(self, hookName: str, msgObj: QtmacsMessage=None): """ Trigger the hook named ``hookName`` and pass on ``msgObj``. This will call all slots associated with ``hookName`` but without calling the event loop in between. Therefore, if one slots changes the state of the GUI, every subsequent slot may have difficulties determining the actual state of the GUI using Qt accessor functions. It is thus usually a good idea to either avoid manipulating the GUI directly, or call macros because Qtmacs will always run the event loop in between any two macros. .. note: the slots are executed in the order in which they were registered via ``qteConnectHook``, but there is no guarantee that this is really so. However, it is guaranteed that all slots will be triggered, even if some raise an error during the execution. |Args| * ``hookName`` (**str**): the name of the hook to trigger. * ``msgObj`` (**QtmacsMessage**): data passed to the function. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Shorthand. reg = self._qteRegistryHooks # Do nothing if there are not recipients for the hook. if hookName not in reg: return # Create an empty ``QtmacsMessage`` object if none was provided. if msgObj is None: msgObj = QtmacsMessage() # Add information about the hook that will deliver ``msgObj``. msgObj.setHookName(hookName) # Try to call each slot. Intercept any errors but ensure that # really all slots are called, irrespective of how many of them # raise an error during execution. for fun in reg[hookName]: try: fun(msgObj) except Exception as err: # Format the error message. msg = '<b>{}</b>-hook function <b>{}</b>'.format( hookName, str(fun)[1:-1]) msg += " did not execute properly." if isinstance(err, QtmacsArgumentError): msg += '<br/>' + str(err) # Log the error. self.qteLogger.exception(msg, exc_info=True, stack_info=True)
python
def qteRunHook(self, hookName: str, msgObj: QtmacsMessage=None): """ Trigger the hook named ``hookName`` and pass on ``msgObj``. This will call all slots associated with ``hookName`` but without calling the event loop in between. Therefore, if one slots changes the state of the GUI, every subsequent slot may have difficulties determining the actual state of the GUI using Qt accessor functions. It is thus usually a good idea to either avoid manipulating the GUI directly, or call macros because Qtmacs will always run the event loop in between any two macros. .. note: the slots are executed in the order in which they were registered via ``qteConnectHook``, but there is no guarantee that this is really so. However, it is guaranteed that all slots will be triggered, even if some raise an error during the execution. |Args| * ``hookName`` (**str**): the name of the hook to trigger. * ``msgObj`` (**QtmacsMessage**): data passed to the function. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Shorthand. reg = self._qteRegistryHooks # Do nothing if there are not recipients for the hook. if hookName not in reg: return # Create an empty ``QtmacsMessage`` object if none was provided. if msgObj is None: msgObj = QtmacsMessage() # Add information about the hook that will deliver ``msgObj``. msgObj.setHookName(hookName) # Try to call each slot. Intercept any errors but ensure that # really all slots are called, irrespective of how many of them # raise an error during execution. for fun in reg[hookName]: try: fun(msgObj) except Exception as err: # Format the error message. msg = '<b>{}</b>-hook function <b>{}</b>'.format( hookName, str(fun)[1:-1]) msg += " did not execute properly." if isinstance(err, QtmacsArgumentError): msg += '<br/>' + str(err) # Log the error. self.qteLogger.exception(msg, exc_info=True, stack_info=True)
[ "def", "qteRunHook", "(", "self", ",", "hookName", ":", "str", ",", "msgObj", ":", "QtmacsMessage", "=", "None", ")", ":", "# Shorthand.", "reg", "=", "self", ".", "_qteRegistryHooks", "# Do nothing if there are not recipients for the hook.", "if", "hookName", "not", "in", "reg", ":", "return", "# Create an empty ``QtmacsMessage`` object if none was provided.", "if", "msgObj", "is", "None", ":", "msgObj", "=", "QtmacsMessage", "(", ")", "# Add information about the hook that will deliver ``msgObj``.", "msgObj", ".", "setHookName", "(", "hookName", ")", "# Try to call each slot. Intercept any errors but ensure that", "# really all slots are called, irrespective of how many of them", "# raise an error during execution.", "for", "fun", "in", "reg", "[", "hookName", "]", ":", "try", ":", "fun", "(", "msgObj", ")", "except", "Exception", "as", "err", ":", "# Format the error message.", "msg", "=", "'<b>{}</b>-hook function <b>{}</b>'", ".", "format", "(", "hookName", ",", "str", "(", "fun", ")", "[", "1", ":", "-", "1", "]", ")", "msg", "+=", "\" did not execute properly.\"", "if", "isinstance", "(", "err", ",", "QtmacsArgumentError", ")", ":", "msg", "+=", "'<br/>'", "+", "str", "(", "err", ")", "# Log the error.", "self", ".", "qteLogger", ".", "exception", "(", "msg", ",", "exc_info", "=", "True", ",", "stack_info", "=", "True", ")" ]
Trigger the hook named ``hookName`` and pass on ``msgObj``. This will call all slots associated with ``hookName`` but without calling the event loop in between. Therefore, if one slots changes the state of the GUI, every subsequent slot may have difficulties determining the actual state of the GUI using Qt accessor functions. It is thus usually a good idea to either avoid manipulating the GUI directly, or call macros because Qtmacs will always run the event loop in between any two macros. .. note: the slots are executed in the order in which they were registered via ``qteConnectHook``, but there is no guarantee that this is really so. However, it is guaranteed that all slots will be triggered, even if some raise an error during the execution. |Args| * ``hookName`` (**str**): the name of the hook to trigger. * ``msgObj`` (**QtmacsMessage**): data passed to the function. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Trigger", "the", "hook", "named", "hookName", "and", "pass", "on", "msgObj", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2680-L2741
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteConnectHook
def qteConnectHook(self, hookName: str, slot: (types.FunctionType, types.MethodType)): """ Connect the method or function ``slot`` to ``hookName``. |Args| * ``hookName`` (**str**): name of the hook. * ``slot`` (**function**, **method**): the routine to execute when the hook triggers. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Shorthand. reg = self._qteRegistryHooks if hookName in reg: reg[hookName].append(slot) else: reg[hookName] = [slot]
python
def qteConnectHook(self, hookName: str, slot: (types.FunctionType, types.MethodType)): """ Connect the method or function ``slot`` to ``hookName``. |Args| * ``hookName`` (**str**): name of the hook. * ``slot`` (**function**, **method**): the routine to execute when the hook triggers. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Shorthand. reg = self._qteRegistryHooks if hookName in reg: reg[hookName].append(slot) else: reg[hookName] = [slot]
[ "def", "qteConnectHook", "(", "self", ",", "hookName", ":", "str", ",", "slot", ":", "(", "types", ".", "FunctionType", ",", "types", ".", "MethodType", ")", ")", ":", "# Shorthand.", "reg", "=", "self", ".", "_qteRegistryHooks", "if", "hookName", "in", "reg", ":", "reg", "[", "hookName", "]", ".", "append", "(", "slot", ")", "else", ":", "reg", "[", "hookName", "]", "=", "[", "slot", "]" ]
Connect the method or function ``slot`` to ``hookName``. |Args| * ``hookName`` (**str**): name of the hook. * ``slot`` (**function**, **method**): the routine to execute when the hook triggers. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Connect", "the", "method", "or", "function", "slot", "to", "hookName", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2744-L2768
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteDisconnectHook
def qteDisconnectHook(self, hookName: str, slot: (types.FunctionType, types.MethodType)): """ Disconnect ``slot`` from ``hookName``. If ``hookName`` does not exist, or ``slot`` is not connected to ``hookName`` then return **False**, otherwise disassociate ``slot`` with ``hookName`` and return **True**. |Args| * ``hookName`` (**str**): name of the hook. * ``slot`` (**function**, **method**): the routine to execute when the hook triggers. |Returns| * **bool**: **True** if ``slot`` was disconnected from ``hookName``, and **False** in all other cases. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Shorthand. reg = self._qteRegistryHooks # Return immediately if no hook with that name exists. if hookName not in reg: msg = 'There is no hook called <b>{}</b>.' self.qteLogger.info(msg.format(hookName)) return False # Return immediately if the ``slot`` is not connected to the hook. if slot not in reg[hookName]: msg = 'Slot <b>{}</b> is not connected to hook <b>{}</b>.' self.qteLogger.info(msg.format(str(slot)[1:-1], hookName)) return False # Remove ``slot`` from the list. reg[hookName].remove(slot) # If the list is now empty, then remove it altogether. if len(reg[hookName]) == 0: reg.pop(hookName) return True
python
def qteDisconnectHook(self, hookName: str, slot: (types.FunctionType, types.MethodType)): """ Disconnect ``slot`` from ``hookName``. If ``hookName`` does not exist, or ``slot`` is not connected to ``hookName`` then return **False**, otherwise disassociate ``slot`` with ``hookName`` and return **True**. |Args| * ``hookName`` (**str**): name of the hook. * ``slot`` (**function**, **method**): the routine to execute when the hook triggers. |Returns| * **bool**: **True** if ``slot`` was disconnected from ``hookName``, and **False** in all other cases. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Shorthand. reg = self._qteRegistryHooks # Return immediately if no hook with that name exists. if hookName not in reg: msg = 'There is no hook called <b>{}</b>.' self.qteLogger.info(msg.format(hookName)) return False # Return immediately if the ``slot`` is not connected to the hook. if slot not in reg[hookName]: msg = 'Slot <b>{}</b> is not connected to hook <b>{}</b>.' self.qteLogger.info(msg.format(str(slot)[1:-1], hookName)) return False # Remove ``slot`` from the list. reg[hookName].remove(slot) # If the list is now empty, then remove it altogether. if len(reg[hookName]) == 0: reg.pop(hookName) return True
[ "def", "qteDisconnectHook", "(", "self", ",", "hookName", ":", "str", ",", "slot", ":", "(", "types", ".", "FunctionType", ",", "types", ".", "MethodType", ")", ")", ":", "# Shorthand.", "reg", "=", "self", ".", "_qteRegistryHooks", "# Return immediately if no hook with that name exists.", "if", "hookName", "not", "in", "reg", ":", "msg", "=", "'There is no hook called <b>{}</b>.'", "self", ".", "qteLogger", ".", "info", "(", "msg", ".", "format", "(", "hookName", ")", ")", "return", "False", "# Return immediately if the ``slot`` is not connected to the hook.", "if", "slot", "not", "in", "reg", "[", "hookName", "]", ":", "msg", "=", "'Slot <b>{}</b> is not connected to hook <b>{}</b>.'", "self", ".", "qteLogger", ".", "info", "(", "msg", ".", "format", "(", "str", "(", "slot", ")", "[", "1", ":", "-", "1", "]", ",", "hookName", ")", ")", "return", "False", "# Remove ``slot`` from the list.", "reg", "[", "hookName", "]", ".", "remove", "(", "slot", ")", "# If the list is now empty, then remove it altogether.", "if", "len", "(", "reg", "[", "hookName", "]", ")", "==", "0", ":", "reg", ".", "pop", "(", "hookName", ")", "return", "True" ]
Disconnect ``slot`` from ``hookName``. If ``hookName`` does not exist, or ``slot`` is not connected to ``hookName`` then return **False**, otherwise disassociate ``slot`` with ``hookName`` and return **True**. |Args| * ``hookName`` (**str**): name of the hook. * ``slot`` (**function**, **method**): the routine to execute when the hook triggers. |Returns| * **bool**: **True** if ``slot`` was disconnected from ``hookName``, and **False** in all other cases. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Disconnect", "slot", "from", "hookName", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2771-L2816
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteImportModule
def qteImportModule(self, fileName: str): """ Import ``fileName`` at run-time. If ``fileName`` has no path prefix then it must be in the standard Python module path. Relative path names are possible. |Args| * ``fileName`` (**str**): file name (with full path) of module to import. |Returns| * **module**: the imported Python module, or **None** if an error occurred. |Raises| * **None** """ # Split the absolute file name into the path- and file name. path, name = os.path.split(fileName) name, ext = os.path.splitext(name) # If the file name has a path prefix then search there, otherwise # search the default paths for Python. if path == '': path = sys.path else: path = [path] # Try to locate the module. try: fp, pathname, desc = imp.find_module(name, path) except ImportError: msg = 'Could not find module <b>{}</b>.'.format(fileName) self.qteLogger.error(msg) return None # Try to import the module. try: mod = imp.load_module(name, fp, pathname, desc) return mod except ImportError: msg = 'Could not import module <b>{}</b>.'.format(fileName) self.qteLogger.error(msg) return None finally: # According to the imp documentation the file pointer # should always be closed explicitly. if fp: fp.close()
python
def qteImportModule(self, fileName: str): """ Import ``fileName`` at run-time. If ``fileName`` has no path prefix then it must be in the standard Python module path. Relative path names are possible. |Args| * ``fileName`` (**str**): file name (with full path) of module to import. |Returns| * **module**: the imported Python module, or **None** if an error occurred. |Raises| * **None** """ # Split the absolute file name into the path- and file name. path, name = os.path.split(fileName) name, ext = os.path.splitext(name) # If the file name has a path prefix then search there, otherwise # search the default paths for Python. if path == '': path = sys.path else: path = [path] # Try to locate the module. try: fp, pathname, desc = imp.find_module(name, path) except ImportError: msg = 'Could not find module <b>{}</b>.'.format(fileName) self.qteLogger.error(msg) return None # Try to import the module. try: mod = imp.load_module(name, fp, pathname, desc) return mod except ImportError: msg = 'Could not import module <b>{}</b>.'.format(fileName) self.qteLogger.error(msg) return None finally: # According to the imp documentation the file pointer # should always be closed explicitly. if fp: fp.close()
[ "def", "qteImportModule", "(", "self", ",", "fileName", ":", "str", ")", ":", "# Split the absolute file name into the path- and file name.", "path", ",", "name", "=", "os", ".", "path", ".", "split", "(", "fileName", ")", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "name", ")", "# If the file name has a path prefix then search there, otherwise", "# search the default paths for Python.", "if", "path", "==", "''", ":", "path", "=", "sys", ".", "path", "else", ":", "path", "=", "[", "path", "]", "# Try to locate the module.", "try", ":", "fp", ",", "pathname", ",", "desc", "=", "imp", ".", "find_module", "(", "name", ",", "path", ")", "except", "ImportError", ":", "msg", "=", "'Could not find module <b>{}</b>.'", ".", "format", "(", "fileName", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ")", "return", "None", "# Try to import the module.", "try", ":", "mod", "=", "imp", ".", "load_module", "(", "name", ",", "fp", ",", "pathname", ",", "desc", ")", "return", "mod", "except", "ImportError", ":", "msg", "=", "'Could not import module <b>{}</b>.'", ".", "format", "(", "fileName", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ")", "return", "None", "finally", ":", "# According to the imp documentation the file pointer", "# should always be closed explicitly.", "if", "fp", ":", "fp", ".", "close", "(", ")" ]
Import ``fileName`` at run-time. If ``fileName`` has no path prefix then it must be in the standard Python module path. Relative path names are possible. |Args| * ``fileName`` (**str**): file name (with full path) of module to import. |Returns| * **module**: the imported Python module, or **None** if an error occurred. |Raises| * **None**
[ "Import", "fileName", "at", "run", "-", "time", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2819-L2871
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteMacroNameMangling
def qteMacroNameMangling(self, macroCls): """ Convert the class name of a macro class to macro name. The name mangling inserts a '-' character after every capital letter and then lowers the entire string. Example: if the class name of ``macroCls`` is 'ThisIsAMacro' then this method will return 'this-is-a-macro', ie. every capital letter (except the first) will be prefixed with a hyphen and changed to lower case. The method returns the name mangled macro name or **None** if an error occurred. |Args| * ``macroCls`` (**QtmacsMacro**): ``QtmacsMacro``- or derived class (not an instance!) |Returns| **str**: the name mangled string or **None** if an error occurred. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Replace camel bump as hyphenated lower case string. macroName = re.sub(r"([A-Z])", r'-\1', macroCls.__name__) # If the first character of the class name was a # capital letter (likely) then the above substitution would have # resulted in a leading hyphen. Remove it. if macroName[0] == '-': macroName = macroName[1:] # Return the lower case string. return macroName.lower()
python
def qteMacroNameMangling(self, macroCls): """ Convert the class name of a macro class to macro name. The name mangling inserts a '-' character after every capital letter and then lowers the entire string. Example: if the class name of ``macroCls`` is 'ThisIsAMacro' then this method will return 'this-is-a-macro', ie. every capital letter (except the first) will be prefixed with a hyphen and changed to lower case. The method returns the name mangled macro name or **None** if an error occurred. |Args| * ``macroCls`` (**QtmacsMacro**): ``QtmacsMacro``- or derived class (not an instance!) |Returns| **str**: the name mangled string or **None** if an error occurred. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Replace camel bump as hyphenated lower case string. macroName = re.sub(r"([A-Z])", r'-\1', macroCls.__name__) # If the first character of the class name was a # capital letter (likely) then the above substitution would have # resulted in a leading hyphen. Remove it. if macroName[0] == '-': macroName = macroName[1:] # Return the lower case string. return macroName.lower()
[ "def", "qteMacroNameMangling", "(", "self", ",", "macroCls", ")", ":", "# Replace camel bump as hyphenated lower case string.", "macroName", "=", "re", ".", "sub", "(", "r\"([A-Z])\"", ",", "r'-\\1'", ",", "macroCls", ".", "__name__", ")", "# If the first character of the class name was a", "# capital letter (likely) then the above substitution would have", "# resulted in a leading hyphen. Remove it.", "if", "macroName", "[", "0", "]", "==", "'-'", ":", "macroName", "=", "macroName", "[", "1", ":", "]", "# Return the lower case string.", "return", "macroName", ".", "lower", "(", ")" ]
Convert the class name of a macro class to macro name. The name mangling inserts a '-' character after every capital letter and then lowers the entire string. Example: if the class name of ``macroCls`` is 'ThisIsAMacro' then this method will return 'this-is-a-macro', ie. every capital letter (except the first) will be prefixed with a hyphen and changed to lower case. The method returns the name mangled macro name or **None** if an error occurred. |Args| * ``macroCls`` (**QtmacsMacro**): ``QtmacsMacro``- or derived class (not an instance!) |Returns| **str**: the name mangled string or **None** if an error occurred. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Convert", "the", "class", "name", "of", "a", "macro", "class", "to", "macro", "name", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2873-L2911
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteRegisterMacro
def qteRegisterMacro(self, macroCls, replaceMacro: bool=False, macroName: str=None): """ Register a macro. If ``macroName`` is **None** then its named is deduced from its class name (see ``qteMacroNameMangling`` for details). Multiple macros with the same name can co-exist as long as their applet- and widget signatures, as reported by the ``qteAppletSignature`` and ``qteWidgetSignature`` methods, differ. If ``macroCls`` has the same name and signatures as an already registered macro then the ``replaceMacro`` flag decides: * **True**: the existing macro will be replaced for all applet- and widget signatures specified by the new macro ``macroCls``. * **False**: the ``macroCls`` will not be registered. The method returns **None** if an error occurred (eg. the macro constructor is faulty), or the macro name as a string. If a macro was already registered and not replaced (ie. ``replaceMacro``) then the macro name is returned nonetheless. .. note:: if an existing macro is replaced the old macro is not deleted (it probably should be, though). |Args| * ``macroCls`` (**QtmacsMacro**): QtmacsMacro or derived (not type checked!) * ``replaceMacro`` (**bool**): whether or not to replace an existing macro. * ``macroName`` (**str**): the name under which the macro should be registered. |Returns| **str**: the name of the just registered macro, or **None** if that failed. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Check type of input arguments. if not issubclass(macroCls, QtmacsMacro): args = ('macroCls', 'class QtmacsMacro', inspect.stack()[0][3]) raise QtmacsArgumentError(*args) # Try to instantiate the macro class. try: macroObj = macroCls() except Exception: msg = 'The macro <b>{}</b> has a faulty constructor.' msg = msg.format(macroCls.__name__) self.qteLogger.error(msg, stack_info=True) return None # The three options to determine the macro name, in order of # precedence, are: passed to this function, specified in the # macro constructor, name mangled. if macroName is None: # No macro name was passed to the function. if macroObj.qteMacroName() is None: # The macro has already named itself. macroName = self.qteMacroNameMangling(macroCls) else: # The macro name is inferred from the class name. macroName = macroObj.qteMacroName() # Let the macro know under which name it is known inside Qtmacs. macroObj._qteMacroName = macroName # Ensure the macro has applet signatures. if len(macroObj.qteAppletSignature()) == 0: msg = 'Macro <b>{}</b> has no applet signatures.'.format(macroName) self.qteLogger.error(msg, stack_info=True) return None # Ensure the macro has widget signatures. if len(macroObj.qteWidgetSignature()) == 0: msg = 'Macro <b>{}</b> has no widget signatures.'.format(macroName) self.qteLogger.error(msg, stack_info=True) return None # Flag to indicate that at least one new macro type was # registered. anyRegistered = False # Iterate over all applet signatures. for app_sig in macroObj.qteAppletSignature(): # Iterate over all widget signatures. for wid_sig in macroObj.qteWidgetSignature(): # Infer the macro name from the class name of the # passed macro object. macroNameInternal = (macroName, app_sig, wid_sig) # If a macro with this name already exists then either # replace it, or skip the registration process for the # new one. if macroNameInternal in self._qteRegistryMacros: if replaceMacro: # Remove existing macro. tmp = self._qteRegistryMacros.pop(macroNameInternal) msg = 'Replacing existing macro <b>{}</b> with new {}.' msg = msg.format(macroNameInternal, macroObj) self.qteLogger.info(msg) tmp.deleteLater() else: msg = 'Macro <b>{}</b> already exists (not replaced).' msg = msg.format(macroNameInternal) self.qteLogger.info(msg) # Macro was not registered for this widget # signature. continue # Add macro object to the registry. self._qteRegistryMacros[macroNameInternal] = macroObj msg = ('Macro <b>{}</b> successfully registered.' .format(macroNameInternal)) self.qteLogger.info(msg) anyRegistered = True # Return the name of the macro, irrespective of whether or not # it is a newly created macro, or if the old macro was kept # (in case of a name conflict). return macroName
python
def qteRegisterMacro(self, macroCls, replaceMacro: bool=False, macroName: str=None): """ Register a macro. If ``macroName`` is **None** then its named is deduced from its class name (see ``qteMacroNameMangling`` for details). Multiple macros with the same name can co-exist as long as their applet- and widget signatures, as reported by the ``qteAppletSignature`` and ``qteWidgetSignature`` methods, differ. If ``macroCls`` has the same name and signatures as an already registered macro then the ``replaceMacro`` flag decides: * **True**: the existing macro will be replaced for all applet- and widget signatures specified by the new macro ``macroCls``. * **False**: the ``macroCls`` will not be registered. The method returns **None** if an error occurred (eg. the macro constructor is faulty), or the macro name as a string. If a macro was already registered and not replaced (ie. ``replaceMacro``) then the macro name is returned nonetheless. .. note:: if an existing macro is replaced the old macro is not deleted (it probably should be, though). |Args| * ``macroCls`` (**QtmacsMacro**): QtmacsMacro or derived (not type checked!) * ``replaceMacro`` (**bool**): whether or not to replace an existing macro. * ``macroName`` (**str**): the name under which the macro should be registered. |Returns| **str**: the name of the just registered macro, or **None** if that failed. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Check type of input arguments. if not issubclass(macroCls, QtmacsMacro): args = ('macroCls', 'class QtmacsMacro', inspect.stack()[0][3]) raise QtmacsArgumentError(*args) # Try to instantiate the macro class. try: macroObj = macroCls() except Exception: msg = 'The macro <b>{}</b> has a faulty constructor.' msg = msg.format(macroCls.__name__) self.qteLogger.error(msg, stack_info=True) return None # The three options to determine the macro name, in order of # precedence, are: passed to this function, specified in the # macro constructor, name mangled. if macroName is None: # No macro name was passed to the function. if macroObj.qteMacroName() is None: # The macro has already named itself. macroName = self.qteMacroNameMangling(macroCls) else: # The macro name is inferred from the class name. macroName = macroObj.qteMacroName() # Let the macro know under which name it is known inside Qtmacs. macroObj._qteMacroName = macroName # Ensure the macro has applet signatures. if len(macroObj.qteAppletSignature()) == 0: msg = 'Macro <b>{}</b> has no applet signatures.'.format(macroName) self.qteLogger.error(msg, stack_info=True) return None # Ensure the macro has widget signatures. if len(macroObj.qteWidgetSignature()) == 0: msg = 'Macro <b>{}</b> has no widget signatures.'.format(macroName) self.qteLogger.error(msg, stack_info=True) return None # Flag to indicate that at least one new macro type was # registered. anyRegistered = False # Iterate over all applet signatures. for app_sig in macroObj.qteAppletSignature(): # Iterate over all widget signatures. for wid_sig in macroObj.qteWidgetSignature(): # Infer the macro name from the class name of the # passed macro object. macroNameInternal = (macroName, app_sig, wid_sig) # If a macro with this name already exists then either # replace it, or skip the registration process for the # new one. if macroNameInternal in self._qteRegistryMacros: if replaceMacro: # Remove existing macro. tmp = self._qteRegistryMacros.pop(macroNameInternal) msg = 'Replacing existing macro <b>{}</b> with new {}.' msg = msg.format(macroNameInternal, macroObj) self.qteLogger.info(msg) tmp.deleteLater() else: msg = 'Macro <b>{}</b> already exists (not replaced).' msg = msg.format(macroNameInternal) self.qteLogger.info(msg) # Macro was not registered for this widget # signature. continue # Add macro object to the registry. self._qteRegistryMacros[macroNameInternal] = macroObj msg = ('Macro <b>{}</b> successfully registered.' .format(macroNameInternal)) self.qteLogger.info(msg) anyRegistered = True # Return the name of the macro, irrespective of whether or not # it is a newly created macro, or if the old macro was kept # (in case of a name conflict). return macroName
[ "def", "qteRegisterMacro", "(", "self", ",", "macroCls", ",", "replaceMacro", ":", "bool", "=", "False", ",", "macroName", ":", "str", "=", "None", ")", ":", "# Check type of input arguments.", "if", "not", "issubclass", "(", "macroCls", ",", "QtmacsMacro", ")", ":", "args", "=", "(", "'macroCls'", ",", "'class QtmacsMacro'", ",", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ")", "raise", "QtmacsArgumentError", "(", "*", "args", ")", "# Try to instantiate the macro class.", "try", ":", "macroObj", "=", "macroCls", "(", ")", "except", "Exception", ":", "msg", "=", "'The macro <b>{}</b> has a faulty constructor.'", "msg", "=", "msg", ".", "format", "(", "macroCls", ".", "__name__", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "None", "# The three options to determine the macro name, in order of", "# precedence, are: passed to this function, specified in the", "# macro constructor, name mangled.", "if", "macroName", "is", "None", ":", "# No macro name was passed to the function.", "if", "macroObj", ".", "qteMacroName", "(", ")", "is", "None", ":", "# The macro has already named itself.", "macroName", "=", "self", ".", "qteMacroNameMangling", "(", "macroCls", ")", "else", ":", "# The macro name is inferred from the class name.", "macroName", "=", "macroObj", ".", "qteMacroName", "(", ")", "# Let the macro know under which name it is known inside Qtmacs.", "macroObj", ".", "_qteMacroName", "=", "macroName", "# Ensure the macro has applet signatures.", "if", "len", "(", "macroObj", ".", "qteAppletSignature", "(", ")", ")", "==", "0", ":", "msg", "=", "'Macro <b>{}</b> has no applet signatures.'", ".", "format", "(", "macroName", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "None", "# Ensure the macro has widget signatures.", "if", "len", "(", "macroObj", ".", "qteWidgetSignature", "(", ")", ")", "==", "0", ":", "msg", "=", "'Macro <b>{}</b> has no widget signatures.'", ".", "format", "(", "macroName", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "None", "# Flag to indicate that at least one new macro type was", "# registered.", "anyRegistered", "=", "False", "# Iterate over all applet signatures.", "for", "app_sig", "in", "macroObj", ".", "qteAppletSignature", "(", ")", ":", "# Iterate over all widget signatures.", "for", "wid_sig", "in", "macroObj", ".", "qteWidgetSignature", "(", ")", ":", "# Infer the macro name from the class name of the", "# passed macro object.", "macroNameInternal", "=", "(", "macroName", ",", "app_sig", ",", "wid_sig", ")", "# If a macro with this name already exists then either", "# replace it, or skip the registration process for the", "# new one.", "if", "macroNameInternal", "in", "self", ".", "_qteRegistryMacros", ":", "if", "replaceMacro", ":", "# Remove existing macro.", "tmp", "=", "self", ".", "_qteRegistryMacros", ".", "pop", "(", "macroNameInternal", ")", "msg", "=", "'Replacing existing macro <b>{}</b> with new {}.'", "msg", "=", "msg", ".", "format", "(", "macroNameInternal", ",", "macroObj", ")", "self", ".", "qteLogger", ".", "info", "(", "msg", ")", "tmp", ".", "deleteLater", "(", ")", "else", ":", "msg", "=", "'Macro <b>{}</b> already exists (not replaced).'", "msg", "=", "msg", ".", "format", "(", "macroNameInternal", ")", "self", ".", "qteLogger", ".", "info", "(", "msg", ")", "# Macro was not registered for this widget", "# signature.", "continue", "# Add macro object to the registry.", "self", ".", "_qteRegistryMacros", "[", "macroNameInternal", "]", "=", "macroObj", "msg", "=", "(", "'Macro <b>{}</b> successfully registered.'", ".", "format", "(", "macroNameInternal", ")", ")", "self", ".", "qteLogger", ".", "info", "(", "msg", ")", "anyRegistered", "=", "True", "# Return the name of the macro, irrespective of whether or not", "# it is a newly created macro, or if the old macro was kept", "# (in case of a name conflict).", "return", "macroName" ]
Register a macro. If ``macroName`` is **None** then its named is deduced from its class name (see ``qteMacroNameMangling`` for details). Multiple macros with the same name can co-exist as long as their applet- and widget signatures, as reported by the ``qteAppletSignature`` and ``qteWidgetSignature`` methods, differ. If ``macroCls`` has the same name and signatures as an already registered macro then the ``replaceMacro`` flag decides: * **True**: the existing macro will be replaced for all applet- and widget signatures specified by the new macro ``macroCls``. * **False**: the ``macroCls`` will not be registered. The method returns **None** if an error occurred (eg. the macro constructor is faulty), or the macro name as a string. If a macro was already registered and not replaced (ie. ``replaceMacro``) then the macro name is returned nonetheless. .. note:: if an existing macro is replaced the old macro is not deleted (it probably should be, though). |Args| * ``macroCls`` (**QtmacsMacro**): QtmacsMacro or derived (not type checked!) * ``replaceMacro`` (**bool**): whether or not to replace an existing macro. * ``macroName`` (**str**): the name under which the macro should be registered. |Returns| **str**: the name of the just registered macro, or **None** if that failed. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Register", "a", "macro", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2914-L3044
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteGetMacroObject
def qteGetMacroObject(self, macroName: str, widgetObj: QtGui.QWidget): """ Return macro that is name- and signature compatible with ``macroName`` and ``widgetObj``. The method considers all macros with name ``macroName`` and returns the one that matches 'best'. To determine this best match, the applet-and widget signatures of the macro are compared to those of ``widgetObj`` and picked in the following order: 1. Applet- and widget signature of both match. 2. Widget signature matches, applet signature in macro is "*" 3. Applet signature matches, widget signature in macro is "*" 4. Macro reports "*" for both its applet- and widget signature. If the macro does not fit any of these four criteria, then no compatible macro is available and the method returns **None**. |Args| * ``macroName`` (**str**): name of macro. * ``widgetObj`` (**QWidget**): widget for which a compatible macro is sought. |Returns| * **QtmacsMacro**: best matching macro, or **None**. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Determine the applet- and widget signature. This is trivial # if the widget was registered with Qtmacs because its # '_qteAdmin' attribute will provide this information. If, on # the other hand, the widget was not registered with Qtmacs # then it has no signature, yet its parent applet must because # every applet has one. The only exception when the applet # signature is therefore when there are no applets to begin # with, ie. the the window is empty. if hasattr(widgetObj, '_qteAdmin'): app_signature = widgetObj._qteAdmin.appletSignature wid_signature = widgetObj._qteAdmin.widgetSignature # Return immediately if the applet signature is None # (should be impossible). if app_signature is None: msg = 'Applet has no signature.' self.qteLogger.error(msg, stack_info=True) return None else: wid_signature = None app = qteGetAppletFromWidget(widgetObj) if app is None: app_signature = None else: app_signature = app._qteAdmin.appletSignature # Find all macros with name 'macroName'. This will produce a list of # tuples with entries (macroName, app_sig, wid_sig). name_match = [m for m in self._qteRegistryMacros if m[0] == macroName] # Find all macros with a compatible applet signature. This is # produce another list of tuples with the same format as # the name_match list (see above). app_sig_match = [_ for _ in name_match if _[1] in (app_signature, '*')] if wid_signature is None: wid_sig_match = [_ for _ in app_sig_match if _[2] == '*'] else: # Find all macros with a compatible widget signature. This is # a list of tuples, each tuple consisting of (macroName, # app_sig, wid_sig). wid_sig_match = [_ for _ in app_sig_match if _[2] in (wid_signature, '*')] # Pick a macro. if len(wid_sig_match) == 0: # No macro is compatible with either the applet- or widget # signature. return None elif len(wid_sig_match) == 1: match = wid_sig_match[0] # Exactly one macro is compatible with either the applet- # or widget signature. return self._qteRegistryMacros[match] else: # Found multiple matches. For any given macro 'name', # applet signature 'app', and widget signature 'wid' there # can be at most four macros in the list: *:*:name, # wid:*:name, *:app:name, and wid:app:name. # See if there is a macro for which both the applet and # widget signature match. tmp = [match for match in wid_sig_match if (match[1] != '*') and (match[2] != '*')] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # See if there is a macro with a matching widget signature. tmp = [match for match in wid_sig_match if match[2] != '*'] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # See if there is a macro with a matching applet signature. tmp = [match for match in wid_sig_match if match[1] != '*'] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # At this point only one possibility is left, namely a # generic macro that is applicable to arbitrary applets # and widgets, eg. NextApplet. tmp = [match for match in wid_sig_match if (match[1] == '*') and (match[2] == '*')] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # This should be impossible. msg = 'No compatible macro found - should be impossible.' self.qteLogger.error(msg, stack_info=True)
python
def qteGetMacroObject(self, macroName: str, widgetObj: QtGui.QWidget): """ Return macro that is name- and signature compatible with ``macroName`` and ``widgetObj``. The method considers all macros with name ``macroName`` and returns the one that matches 'best'. To determine this best match, the applet-and widget signatures of the macro are compared to those of ``widgetObj`` and picked in the following order: 1. Applet- and widget signature of both match. 2. Widget signature matches, applet signature in macro is "*" 3. Applet signature matches, widget signature in macro is "*" 4. Macro reports "*" for both its applet- and widget signature. If the macro does not fit any of these four criteria, then no compatible macro is available and the method returns **None**. |Args| * ``macroName`` (**str**): name of macro. * ``widgetObj`` (**QWidget**): widget for which a compatible macro is sought. |Returns| * **QtmacsMacro**: best matching macro, or **None**. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Determine the applet- and widget signature. This is trivial # if the widget was registered with Qtmacs because its # '_qteAdmin' attribute will provide this information. If, on # the other hand, the widget was not registered with Qtmacs # then it has no signature, yet its parent applet must because # every applet has one. The only exception when the applet # signature is therefore when there are no applets to begin # with, ie. the the window is empty. if hasattr(widgetObj, '_qteAdmin'): app_signature = widgetObj._qteAdmin.appletSignature wid_signature = widgetObj._qteAdmin.widgetSignature # Return immediately if the applet signature is None # (should be impossible). if app_signature is None: msg = 'Applet has no signature.' self.qteLogger.error(msg, stack_info=True) return None else: wid_signature = None app = qteGetAppletFromWidget(widgetObj) if app is None: app_signature = None else: app_signature = app._qteAdmin.appletSignature # Find all macros with name 'macroName'. This will produce a list of # tuples with entries (macroName, app_sig, wid_sig). name_match = [m for m in self._qteRegistryMacros if m[0] == macroName] # Find all macros with a compatible applet signature. This is # produce another list of tuples with the same format as # the name_match list (see above). app_sig_match = [_ for _ in name_match if _[1] in (app_signature, '*')] if wid_signature is None: wid_sig_match = [_ for _ in app_sig_match if _[2] == '*'] else: # Find all macros with a compatible widget signature. This is # a list of tuples, each tuple consisting of (macroName, # app_sig, wid_sig). wid_sig_match = [_ for _ in app_sig_match if _[2] in (wid_signature, '*')] # Pick a macro. if len(wid_sig_match) == 0: # No macro is compatible with either the applet- or widget # signature. return None elif len(wid_sig_match) == 1: match = wid_sig_match[0] # Exactly one macro is compatible with either the applet- # or widget signature. return self._qteRegistryMacros[match] else: # Found multiple matches. For any given macro 'name', # applet signature 'app', and widget signature 'wid' there # can be at most four macros in the list: *:*:name, # wid:*:name, *:app:name, and wid:app:name. # See if there is a macro for which both the applet and # widget signature match. tmp = [match for match in wid_sig_match if (match[1] != '*') and (match[2] != '*')] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # See if there is a macro with a matching widget signature. tmp = [match for match in wid_sig_match if match[2] != '*'] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # See if there is a macro with a matching applet signature. tmp = [match for match in wid_sig_match if match[1] != '*'] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # At this point only one possibility is left, namely a # generic macro that is applicable to arbitrary applets # and widgets, eg. NextApplet. tmp = [match for match in wid_sig_match if (match[1] == '*') and (match[2] == '*')] if len(tmp) > 0: match = tmp[0] return self._qteRegistryMacros[match] # This should be impossible. msg = 'No compatible macro found - should be impossible.' self.qteLogger.error(msg, stack_info=True)
[ "def", "qteGetMacroObject", "(", "self", ",", "macroName", ":", "str", ",", "widgetObj", ":", "QtGui", ".", "QWidget", ")", ":", "# Determine the applet- and widget signature. This is trivial", "# if the widget was registered with Qtmacs because its", "# '_qteAdmin' attribute will provide this information. If, on", "# the other hand, the widget was not registered with Qtmacs", "# then it has no signature, yet its parent applet must because", "# every applet has one. The only exception when the applet", "# signature is therefore when there are no applets to begin", "# with, ie. the the window is empty.", "if", "hasattr", "(", "widgetObj", ",", "'_qteAdmin'", ")", ":", "app_signature", "=", "widgetObj", ".", "_qteAdmin", ".", "appletSignature", "wid_signature", "=", "widgetObj", ".", "_qteAdmin", ".", "widgetSignature", "# Return immediately if the applet signature is None", "# (should be impossible).", "if", "app_signature", "is", "None", ":", "msg", "=", "'Applet has no signature.'", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "None", "else", ":", "wid_signature", "=", "None", "app", "=", "qteGetAppletFromWidget", "(", "widgetObj", ")", "if", "app", "is", "None", ":", "app_signature", "=", "None", "else", ":", "app_signature", "=", "app", ".", "_qteAdmin", ".", "appletSignature", "# Find all macros with name 'macroName'. This will produce a list of", "# tuples with entries (macroName, app_sig, wid_sig).", "name_match", "=", "[", "m", "for", "m", "in", "self", ".", "_qteRegistryMacros", "if", "m", "[", "0", "]", "==", "macroName", "]", "# Find all macros with a compatible applet signature. This is", "# produce another list of tuples with the same format as", "# the name_match list (see above).", "app_sig_match", "=", "[", "_", "for", "_", "in", "name_match", "if", "_", "[", "1", "]", "in", "(", "app_signature", ",", "'*'", ")", "]", "if", "wid_signature", "is", "None", ":", "wid_sig_match", "=", "[", "_", "for", "_", "in", "app_sig_match", "if", "_", "[", "2", "]", "==", "'*'", "]", "else", ":", "# Find all macros with a compatible widget signature. This is", "# a list of tuples, each tuple consisting of (macroName,", "# app_sig, wid_sig).", "wid_sig_match", "=", "[", "_", "for", "_", "in", "app_sig_match", "if", "_", "[", "2", "]", "in", "(", "wid_signature", ",", "'*'", ")", "]", "# Pick a macro.", "if", "len", "(", "wid_sig_match", ")", "==", "0", ":", "# No macro is compatible with either the applet- or widget", "# signature.", "return", "None", "elif", "len", "(", "wid_sig_match", ")", "==", "1", ":", "match", "=", "wid_sig_match", "[", "0", "]", "# Exactly one macro is compatible with either the applet-", "# or widget signature.", "return", "self", ".", "_qteRegistryMacros", "[", "match", "]", "else", ":", "# Found multiple matches. For any given macro 'name',", "# applet signature 'app', and widget signature 'wid' there", "# can be at most four macros in the list: *:*:name,", "# wid:*:name, *:app:name, and wid:app:name.", "# See if there is a macro for which both the applet and", "# widget signature match.", "tmp", "=", "[", "match", "for", "match", "in", "wid_sig_match", "if", "(", "match", "[", "1", "]", "!=", "'*'", ")", "and", "(", "match", "[", "2", "]", "!=", "'*'", ")", "]", "if", "len", "(", "tmp", ")", ">", "0", ":", "match", "=", "tmp", "[", "0", "]", "return", "self", ".", "_qteRegistryMacros", "[", "match", "]", "# See if there is a macro with a matching widget signature.", "tmp", "=", "[", "match", "for", "match", "in", "wid_sig_match", "if", "match", "[", "2", "]", "!=", "'*'", "]", "if", "len", "(", "tmp", ")", ">", "0", ":", "match", "=", "tmp", "[", "0", "]", "return", "self", ".", "_qteRegistryMacros", "[", "match", "]", "# See if there is a macro with a matching applet signature.", "tmp", "=", "[", "match", "for", "match", "in", "wid_sig_match", "if", "match", "[", "1", "]", "!=", "'*'", "]", "if", "len", "(", "tmp", ")", ">", "0", ":", "match", "=", "tmp", "[", "0", "]", "return", "self", ".", "_qteRegistryMacros", "[", "match", "]", "# At this point only one possibility is left, namely a", "# generic macro that is applicable to arbitrary applets", "# and widgets, eg. NextApplet.", "tmp", "=", "[", "match", "for", "match", "in", "wid_sig_match", "if", "(", "match", "[", "1", "]", "==", "'*'", ")", "and", "(", "match", "[", "2", "]", "==", "'*'", ")", "]", "if", "len", "(", "tmp", ")", ">", "0", ":", "match", "=", "tmp", "[", "0", "]", "return", "self", ".", "_qteRegistryMacros", "[", "match", "]", "# This should be impossible.", "msg", "=", "'No compatible macro found - should be impossible.'", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")" ]
Return macro that is name- and signature compatible with ``macroName`` and ``widgetObj``. The method considers all macros with name ``macroName`` and returns the one that matches 'best'. To determine this best match, the applet-and widget signatures of the macro are compared to those of ``widgetObj`` and picked in the following order: 1. Applet- and widget signature of both match. 2. Widget signature matches, applet signature in macro is "*" 3. Applet signature matches, widget signature in macro is "*" 4. Macro reports "*" for both its applet- and widget signature. If the macro does not fit any of these four criteria, then no compatible macro is available and the method returns **None**. |Args| * ``macroName`` (**str**): name of macro. * ``widgetObj`` (**QWidget**): widget for which a compatible macro is sought. |Returns| * **QtmacsMacro**: best matching macro, or **None**. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Return", "macro", "that", "is", "name", "-", "and", "signature", "compatible", "with", "macroName", "and", "widgetObj", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3089-L3213
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteGetAllMacroNames
def qteGetAllMacroNames(self, widgetObj: QtGui.QWidget=None): """ Return all macro names known to Qtmacs as a list. If ``widgetObj`` is **None** then the names of all registered macros are returned as a tuple. Otherwise, only those macro compatible with ``widgetObj`` are returned. See ``qteGetMacroObject`` for the definition of a compatible macro. |Args| * ``widgetObj`` (**QWidget**): widget with which the macros must be compatible. |Returns| * **tuple**: tuple of macro names. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # The keys of qteRegistryMacros are (macroObj, app_sig, # wid_sig) tuples. Get them, extract the macro names, and # remove all duplicates. macro_list = tuple(self._qteRegistryMacros.keys()) macro_list = [_[0] for _ in macro_list] macro_list = tuple(set(macro_list)) # If no widget object was supplied then omit the signature # check and return the macro list verbatim. if widgetObj is None: return macro_list else: # Use qteGetMacroObject to compile a list of macros that # are compatible with widgetObj. This list contains # (macroObj, macroName, app_sig, wid_sig) tuples. macro_list = [self.qteGetMacroObject(macroName, widgetObj) for macroName in macro_list] # Remove all elements where macroObj=None. This is the # case if no compatible macro with the specified name # could be found for widgetObj. macro_list = [_.qteMacroName() for _ in macro_list if _ is not None] return macro_list
python
def qteGetAllMacroNames(self, widgetObj: QtGui.QWidget=None): """ Return all macro names known to Qtmacs as a list. If ``widgetObj`` is **None** then the names of all registered macros are returned as a tuple. Otherwise, only those macro compatible with ``widgetObj`` are returned. See ``qteGetMacroObject`` for the definition of a compatible macro. |Args| * ``widgetObj`` (**QWidget**): widget with which the macros must be compatible. |Returns| * **tuple**: tuple of macro names. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # The keys of qteRegistryMacros are (macroObj, app_sig, # wid_sig) tuples. Get them, extract the macro names, and # remove all duplicates. macro_list = tuple(self._qteRegistryMacros.keys()) macro_list = [_[0] for _ in macro_list] macro_list = tuple(set(macro_list)) # If no widget object was supplied then omit the signature # check and return the macro list verbatim. if widgetObj is None: return macro_list else: # Use qteGetMacroObject to compile a list of macros that # are compatible with widgetObj. This list contains # (macroObj, macroName, app_sig, wid_sig) tuples. macro_list = [self.qteGetMacroObject(macroName, widgetObj) for macroName in macro_list] # Remove all elements where macroObj=None. This is the # case if no compatible macro with the specified name # could be found for widgetObj. macro_list = [_.qteMacroName() for _ in macro_list if _ is not None] return macro_list
[ "def", "qteGetAllMacroNames", "(", "self", ",", "widgetObj", ":", "QtGui", ".", "QWidget", "=", "None", ")", ":", "# The keys of qteRegistryMacros are (macroObj, app_sig,", "# wid_sig) tuples. Get them, extract the macro names, and", "# remove all duplicates.", "macro_list", "=", "tuple", "(", "self", ".", "_qteRegistryMacros", ".", "keys", "(", ")", ")", "macro_list", "=", "[", "_", "[", "0", "]", "for", "_", "in", "macro_list", "]", "macro_list", "=", "tuple", "(", "set", "(", "macro_list", ")", ")", "# If no widget object was supplied then omit the signature", "# check and return the macro list verbatim.", "if", "widgetObj", "is", "None", ":", "return", "macro_list", "else", ":", "# Use qteGetMacroObject to compile a list of macros that", "# are compatible with widgetObj. This list contains", "# (macroObj, macroName, app_sig, wid_sig) tuples.", "macro_list", "=", "[", "self", ".", "qteGetMacroObject", "(", "macroName", ",", "widgetObj", ")", "for", "macroName", "in", "macro_list", "]", "# Remove all elements where macroObj=None. This is the", "# case if no compatible macro with the specified name", "# could be found for widgetObj.", "macro_list", "=", "[", "_", ".", "qteMacroName", "(", ")", "for", "_", "in", "macro_list", "if", "_", "is", "not", "None", "]", "return", "macro_list" ]
Return all macro names known to Qtmacs as a list. If ``widgetObj`` is **None** then the names of all registered macros are returned as a tuple. Otherwise, only those macro compatible with ``widgetObj`` are returned. See ``qteGetMacroObject`` for the definition of a compatible macro. |Args| * ``widgetObj`` (**QWidget**): widget with which the macros must be compatible. |Returns| * **tuple**: tuple of macro names. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Return", "all", "macro", "names", "known", "to", "Qtmacs", "as", "a", "list", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3216-L3262
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteBindKeyGlobal
def qteBindKeyGlobal(self, keysequence, macroName: str): """ Associate ``macroName`` with ``keysequence`` in all current applets. This method will bind ``macroName`` to ``keysequence`` in the global key map and **all** local key maps. This also applies for all applets (and their constituent widgets) yet to be instantiated because they will inherit a copy of the global keymap. .. note:: This binding is signature independent. If the ``macroName`` was not registered the method returns **False**. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``macroName`` (**str**): name of macro to associate with ``keysequence``. |Returns| **bool**: **True** if the binding was successful. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. """ # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsOtherError if the conversion is impossible. keysequence = QtmacsKeysequence(keysequence) # Sanity check: the macro must have been registered # beforehand. if not self.qteIsMacroRegistered(macroName): msg = 'Cannot globally bind key to unknown macro <b>{}</b>.' msg = msg.format(macroName) self.qteLogger.error(msg, stack_info=True) return False # Insert/overwrite the key sequence and associate it with the # new macro. self._qteGlobalKeyMap.qteInsertKey(keysequence, macroName) # Now update the local key map of every applet. Note that # globally bound macros apply to every applet (hence the loop # below) and every widget therein (hence the "*" parameter for # the widget signature). for app in self._qteAppletList: self.qteBindKeyApplet(keysequence, macroName, app) return True
python
def qteBindKeyGlobal(self, keysequence, macroName: str): """ Associate ``macroName`` with ``keysequence`` in all current applets. This method will bind ``macroName`` to ``keysequence`` in the global key map and **all** local key maps. This also applies for all applets (and their constituent widgets) yet to be instantiated because they will inherit a copy of the global keymap. .. note:: This binding is signature independent. If the ``macroName`` was not registered the method returns **False**. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``macroName`` (**str**): name of macro to associate with ``keysequence``. |Returns| **bool**: **True** if the binding was successful. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. """ # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsOtherError if the conversion is impossible. keysequence = QtmacsKeysequence(keysequence) # Sanity check: the macro must have been registered # beforehand. if not self.qteIsMacroRegistered(macroName): msg = 'Cannot globally bind key to unknown macro <b>{}</b>.' msg = msg.format(macroName) self.qteLogger.error(msg, stack_info=True) return False # Insert/overwrite the key sequence and associate it with the # new macro. self._qteGlobalKeyMap.qteInsertKey(keysequence, macroName) # Now update the local key map of every applet. Note that # globally bound macros apply to every applet (hence the loop # below) and every widget therein (hence the "*" parameter for # the widget signature). for app in self._qteAppletList: self.qteBindKeyApplet(keysequence, macroName, app) return True
[ "def", "qteBindKeyGlobal", "(", "self", ",", "keysequence", ",", "macroName", ":", "str", ")", ":", "# Convert the key sequence into a QtmacsKeysequence object, or", "# raise an QtmacsOtherError if the conversion is impossible.", "keysequence", "=", "QtmacsKeysequence", "(", "keysequence", ")", "# Sanity check: the macro must have been registered", "# beforehand.", "if", "not", "self", ".", "qteIsMacroRegistered", "(", "macroName", ")", ":", "msg", "=", "'Cannot globally bind key to unknown macro <b>{}</b>.'", "msg", "=", "msg", ".", "format", "(", "macroName", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "False", "# Insert/overwrite the key sequence and associate it with the", "# new macro.", "self", ".", "_qteGlobalKeyMap", ".", "qteInsertKey", "(", "keysequence", ",", "macroName", ")", "# Now update the local key map of every applet. Note that", "# globally bound macros apply to every applet (hence the loop", "# below) and every widget therein (hence the \"*\" parameter for", "# the widget signature).", "for", "app", "in", "self", ".", "_qteAppletList", ":", "self", ".", "qteBindKeyApplet", "(", "keysequence", ",", "macroName", ",", "app", ")", "return", "True" ]
Associate ``macroName`` with ``keysequence`` in all current applets. This method will bind ``macroName`` to ``keysequence`` in the global key map and **all** local key maps. This also applies for all applets (and their constituent widgets) yet to be instantiated because they will inherit a copy of the global keymap. .. note:: This binding is signature independent. If the ``macroName`` was not registered the method returns **False**. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``macroName`` (**str**): name of macro to associate with ``keysequence``. |Returns| **bool**: **True** if the binding was successful. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed.
[ "Associate", "macroName", "with", "keysequence", "in", "all", "current", "applets", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3265-L3327
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteBindKeyApplet
def qteBindKeyApplet(self, keysequence, macroName: str, appletObj: QtmacsApplet): """ Bind ``macroName`` to all widgets in ``appletObj``. This method does not affect the key bindings of other applets, or other instances of the same applet. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``macroName`` (**str**): the macro to associated with ``keysequence``. * ``appletObj`` (**QtmacsApplet**): only widgets in this applet are affected. |Returns| * **bool**: whether or not at least one widget was successfully bound. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. """ # Convert the key sequence into a QtmacsKeysequence object, or # raise a QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence(keysequence) # Verify that Qtmacs knows a macro named 'macroName'. if not self.qteIsMacroRegistered(macroName): msg = ('Cannot bind key because the macro <b>{}</b> does' 'not exist.'.format(macroName)) self.qteLogger.error(msg, stack_info=True) return False # Bind the key also to the applet itself because it can # receive keyboard events (eg. when it is empty). appletObj._qteAdmin.keyMap.qteInsertKey(keysequence, macroName) # Update the key map of every widget inside the applet. for wid in appletObj._qteAdmin.widgetList: self.qteBindKeyWidget(keysequence, macroName, wid) return True
python
def qteBindKeyApplet(self, keysequence, macroName: str, appletObj: QtmacsApplet): """ Bind ``macroName`` to all widgets in ``appletObj``. This method does not affect the key bindings of other applets, or other instances of the same applet. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``macroName`` (**str**): the macro to associated with ``keysequence``. * ``appletObj`` (**QtmacsApplet**): only widgets in this applet are affected. |Returns| * **bool**: whether or not at least one widget was successfully bound. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. """ # Convert the key sequence into a QtmacsKeysequence object, or # raise a QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence(keysequence) # Verify that Qtmacs knows a macro named 'macroName'. if not self.qteIsMacroRegistered(macroName): msg = ('Cannot bind key because the macro <b>{}</b> does' 'not exist.'.format(macroName)) self.qteLogger.error(msg, stack_info=True) return False # Bind the key also to the applet itself because it can # receive keyboard events (eg. when it is empty). appletObj._qteAdmin.keyMap.qteInsertKey(keysequence, macroName) # Update the key map of every widget inside the applet. for wid in appletObj._qteAdmin.widgetList: self.qteBindKeyWidget(keysequence, macroName, wid) return True
[ "def", "qteBindKeyApplet", "(", "self", ",", "keysequence", ",", "macroName", ":", "str", ",", "appletObj", ":", "QtmacsApplet", ")", ":", "# Convert the key sequence into a QtmacsKeysequence object, or", "# raise a QtmacsKeysequenceError if the conversion is", "# impossible.", "keysequence", "=", "QtmacsKeysequence", "(", "keysequence", ")", "# Verify that Qtmacs knows a macro named 'macroName'.", "if", "not", "self", ".", "qteIsMacroRegistered", "(", "macroName", ")", ":", "msg", "=", "(", "'Cannot bind key because the macro <b>{}</b> does'", "'not exist.'", ".", "format", "(", "macroName", ")", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "False", "# Bind the key also to the applet itself because it can", "# receive keyboard events (eg. when it is empty).", "appletObj", ".", "_qteAdmin", ".", "keyMap", ".", "qteInsertKey", "(", "keysequence", ",", "macroName", ")", "# Update the key map of every widget inside the applet.", "for", "wid", "in", "appletObj", ".", "_qteAdmin", ".", "widgetList", ":", "self", ".", "qteBindKeyWidget", "(", "keysequence", ",", "macroName", ",", "wid", ")", "return", "True" ]
Bind ``macroName`` to all widgets in ``appletObj``. This method does not affect the key bindings of other applets, or other instances of the same applet. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``macroName`` (**str**): the macro to associated with ``keysequence``. * ``appletObj`` (**QtmacsApplet**): only widgets in this applet are affected. |Returns| * **bool**: whether or not at least one widget was successfully bound. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed.
[ "Bind", "macroName", "to", "all", "widgets", "in", "appletObj", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3330-L3385
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteBindKeyWidget
def qteBindKeyWidget(self, keysequence, macroName: str, widgetObj: QtGui.QWidget): """ Bind ``macroName`` to ``widgetObj`` and associate it with ``keysequence``. This method does not affect the key bindings of other applets and/or widgets and can be used to individualise the key bindings inside every applet instance and every widget inside that instance. Even multiple instances of the same applet type (eg. multiple text buffers) can all have individual key bindings. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``macroName`` (**str**): the macro to associated with ``keysequence``. * ``widgetObj`` (**QWidget**): determines which widgets signature to use. |Returns| * **bool**: whether or not at least one widget was successfully bound. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. * **QtmacsOtherError** if ``widgetObj`` was not added with ``qteAddWidget``. """ # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence(keysequence) # Check type of input arguments. if not hasattr(widgetObj, '_qteAdmin'): msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError(msg) # Verify that Qtmacs knows a macro named 'macroName'. if not self.qteIsMacroRegistered(macroName): msg = ('Cannot bind key to unknown macro <b>{}</b>.' .format(macroName)) self.qteLogger.error(msg, stack_info=True) return False # Associate 'keysequence' with 'macroName' for 'widgetObj'. try: widgetObj._qteAdmin.keyMap.qteInsertKey(keysequence, macroName) except AttributeError: msg = 'Received an invalid macro object.' self.qteLogger.error(msg, stack_info=True) return False return True
python
def qteBindKeyWidget(self, keysequence, macroName: str, widgetObj: QtGui.QWidget): """ Bind ``macroName`` to ``widgetObj`` and associate it with ``keysequence``. This method does not affect the key bindings of other applets and/or widgets and can be used to individualise the key bindings inside every applet instance and every widget inside that instance. Even multiple instances of the same applet type (eg. multiple text buffers) can all have individual key bindings. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``macroName`` (**str**): the macro to associated with ``keysequence``. * ``widgetObj`` (**QWidget**): determines which widgets signature to use. |Returns| * **bool**: whether or not at least one widget was successfully bound. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. * **QtmacsOtherError** if ``widgetObj`` was not added with ``qteAddWidget``. """ # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence(keysequence) # Check type of input arguments. if not hasattr(widgetObj, '_qteAdmin'): msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError(msg) # Verify that Qtmacs knows a macro named 'macroName'. if not self.qteIsMacroRegistered(macroName): msg = ('Cannot bind key to unknown macro <b>{}</b>.' .format(macroName)) self.qteLogger.error(msg, stack_info=True) return False # Associate 'keysequence' with 'macroName' for 'widgetObj'. try: widgetObj._qteAdmin.keyMap.qteInsertKey(keysequence, macroName) except AttributeError: msg = 'Received an invalid macro object.' self.qteLogger.error(msg, stack_info=True) return False return True
[ "def", "qteBindKeyWidget", "(", "self", ",", "keysequence", ",", "macroName", ":", "str", ",", "widgetObj", ":", "QtGui", ".", "QWidget", ")", ":", "# Convert the key sequence into a QtmacsKeysequence object, or", "# raise an QtmacsKeysequenceError if the conversion is", "# impossible.", "keysequence", "=", "QtmacsKeysequence", "(", "keysequence", ")", "# Check type of input arguments.", "if", "not", "hasattr", "(", "widgetObj", ",", "'_qteAdmin'", ")", ":", "msg", "=", "'<widgetObj> was probably not added with <qteAddWidget>'", "msg", "+=", "' method because it lacks the <_qteAdmin> attribute.'", "raise", "QtmacsOtherError", "(", "msg", ")", "# Verify that Qtmacs knows a macro named 'macroName'.", "if", "not", "self", ".", "qteIsMacroRegistered", "(", "macroName", ")", ":", "msg", "=", "(", "'Cannot bind key to unknown macro <b>{}</b>.'", ".", "format", "(", "macroName", ")", ")", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "False", "# Associate 'keysequence' with 'macroName' for 'widgetObj'.", "try", ":", "widgetObj", ".", "_qteAdmin", ".", "keyMap", ".", "qteInsertKey", "(", "keysequence", ",", "macroName", ")", "except", "AttributeError", ":", "msg", "=", "'Received an invalid macro object.'", "self", ".", "qteLogger", ".", "error", "(", "msg", ",", "stack_info", "=", "True", ")", "return", "False", "return", "True" ]
Bind ``macroName`` to ``widgetObj`` and associate it with ``keysequence``. This method does not affect the key bindings of other applets and/or widgets and can be used to individualise the key bindings inside every applet instance and every widget inside that instance. Even multiple instances of the same applet type (eg. multiple text buffers) can all have individual key bindings. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``macroName`` (**str**): the macro to associated with ``keysequence``. * ``widgetObj`` (**QWidget**): determines which widgets signature to use. |Returns| * **bool**: whether or not at least one widget was successfully bound. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. * **QtmacsOtherError** if ``widgetObj`` was not added with ``qteAddWidget``.
[ "Bind", "macroName", "to", "widgetObj", "and", "associate", "it", "with", "keysequence", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3388-L3456
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteUnbindKeyApplet
def qteUnbindKeyApplet(self, applet: (QtmacsApplet, str), keysequence): """ Remove ``keysequence`` bindings from all widgets inside ``applet``. This method does not affect the key bindings of other applets, or different instances of the same applet. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. If ``applet`` does not refer to an existing applet then nothing happens. |Args| * ``applet`` (**QtmacsApplet**, **str**): only widgets in this applet are affected. * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): the key sequence to remove. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. """ # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance(applet, str): appletObj = self.qteGetAppletHandle(applet) else: appletObj = applet # Return immediately if the appletObj is invalid. if appletObj is None: return # Convert the key sequence into a QtmacsKeysequence object, or # raise a QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence(keysequence) # Remove the key sequence from the applet window itself. appletObj._qteAdmin.keyMap.qteRemoveKey(keysequence) for wid in appletObj._qteAdmin.widgetList: self.qteUnbindKeyFromWidgetObject(keysequence, wid)
python
def qteUnbindKeyApplet(self, applet: (QtmacsApplet, str), keysequence): """ Remove ``keysequence`` bindings from all widgets inside ``applet``. This method does not affect the key bindings of other applets, or different instances of the same applet. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. If ``applet`` does not refer to an existing applet then nothing happens. |Args| * ``applet`` (**QtmacsApplet**, **str**): only widgets in this applet are affected. * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): the key sequence to remove. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. """ # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance(applet, str): appletObj = self.qteGetAppletHandle(applet) else: appletObj = applet # Return immediately if the appletObj is invalid. if appletObj is None: return # Convert the key sequence into a QtmacsKeysequence object, or # raise a QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence(keysequence) # Remove the key sequence from the applet window itself. appletObj._qteAdmin.keyMap.qteRemoveKey(keysequence) for wid in appletObj._qteAdmin.widgetList: self.qteUnbindKeyFromWidgetObject(keysequence, wid)
[ "def", "qteUnbindKeyApplet", "(", "self", ",", "applet", ":", "(", "QtmacsApplet", ",", "str", ")", ",", "keysequence", ")", ":", "# If ``applet`` was specified by its ID (ie. a string) then", "# fetch the associated ``QtmacsApplet`` instance. If", "# ``applet`` is already an instance of ``QtmacsApplet`` then", "# use it directly.", "if", "isinstance", "(", "applet", ",", "str", ")", ":", "appletObj", "=", "self", ".", "qteGetAppletHandle", "(", "applet", ")", "else", ":", "appletObj", "=", "applet", "# Return immediately if the appletObj is invalid.", "if", "appletObj", "is", "None", ":", "return", "# Convert the key sequence into a QtmacsKeysequence object, or", "# raise a QtmacsKeysequenceError if the conversion is", "# impossible.", "keysequence", "=", "QtmacsKeysequence", "(", "keysequence", ")", "# Remove the key sequence from the applet window itself.", "appletObj", ".", "_qteAdmin", ".", "keyMap", ".", "qteRemoveKey", "(", "keysequence", ")", "for", "wid", "in", "appletObj", ".", "_qteAdmin", ".", "widgetList", ":", "self", ".", "qteUnbindKeyFromWidgetObject", "(", "keysequence", ",", "wid", ")" ]
Remove ``keysequence`` bindings from all widgets inside ``applet``. This method does not affect the key bindings of other applets, or different instances of the same applet. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. If ``applet`` does not refer to an existing applet then nothing happens. |Args| * ``applet`` (**QtmacsApplet**, **str**): only widgets in this applet are affected. * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): the key sequence to remove. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed.
[ "Remove", "keysequence", "bindings", "from", "all", "widgets", "inside", "applet", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3459-L3519
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteUnbindKeyFromWidgetObject
def qteUnbindKeyFromWidgetObject(self, keysequence, widgetObj: QtGui.QWidget): """ Disassociate the macro triggered by ``keysequence`` from ``widgetObj``. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. This method does not affect the key bindings of other applets. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``widgetObj`` (**QWidget**): determines which widgets signature to use. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. * **QtmacsOtherError** if ``widgetObj`` was not added with ``qteAddWidget``. """ # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence(keysequence) # Check type of input arguments. if not hasattr(widgetObj, '_qteAdmin'): msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError(msg) # Remove the key sequence from the local key maps. widgetObj._qteAdmin.keyMap.qteRemoveKey(keysequence)
python
def qteUnbindKeyFromWidgetObject(self, keysequence, widgetObj: QtGui.QWidget): """ Disassociate the macro triggered by ``keysequence`` from ``widgetObj``. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. This method does not affect the key bindings of other applets. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``widgetObj`` (**QWidget**): determines which widgets signature to use. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. * **QtmacsOtherError** if ``widgetObj`` was not added with ``qteAddWidget``. """ # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence(keysequence) # Check type of input arguments. if not hasattr(widgetObj, '_qteAdmin'): msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError(msg) # Remove the key sequence from the local key maps. widgetObj._qteAdmin.keyMap.qteRemoveKey(keysequence)
[ "def", "qteUnbindKeyFromWidgetObject", "(", "self", ",", "keysequence", ",", "widgetObj", ":", "QtGui", ".", "QWidget", ")", ":", "# Convert the key sequence into a QtmacsKeysequence object, or", "# raise an QtmacsKeysequenceError if the conversion is", "# impossible.", "keysequence", "=", "QtmacsKeysequence", "(", "keysequence", ")", "# Check type of input arguments.", "if", "not", "hasattr", "(", "widgetObj", ",", "'_qteAdmin'", ")", ":", "msg", "=", "'<widgetObj> was probably not added with <qteAddWidget>'", "msg", "+=", "' method because it lacks the <_qteAdmin> attribute.'", "raise", "QtmacsOtherError", "(", "msg", ")", "# Remove the key sequence from the local key maps.", "widgetObj", ".", "_qteAdmin", ".", "keyMap", ".", "qteRemoveKey", "(", "keysequence", ")" ]
Disassociate the macro triggered by ``keysequence`` from ``widgetObj``. The ``keysequence`` can be specified either as a string (eg '<ctrl>+x <ctrl>+f'), or a list of tuples containing the constants from the ``QtCore.Qt`` name space (eg. [(ControlModifier, Key_X), (ControlModifier, Key_F)]), or as a ``QtmacsKeysequence`` object. This method does not affect the key bindings of other applets. |Args| * ``keysequence`` (**str**, **list** of **tuples**, **QtmacsKeysequence**): key sequence to activate ``macroName`` for specified ``widgetSignature``. * ``widgetObj`` (**QWidget**): determines which widgets signature to use. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsKeysequenceError** if the provided ``keysequence`` could not be parsed. * **QtmacsOtherError** if ``widgetObj`` was not added with ``qteAddWidget``.
[ "Disassociate", "the", "macro", "triggered", "by", "keysequence", "from", "widgetObj", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3522-L3569
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteUnbindAllFromApplet
def qteUnbindAllFromApplet(self, applet: (QtmacsApplet, str)): """ Restore the global key-map for all widgets inside ``applet``. This method effectively resets the key map of all widgets to the state they would be in if the widgets were newly instantiated right now. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. If ``applet`` does not refer to an existing applet then nothing happens. |Args| * ``applet`` (**QtmacsApplet**, **str**): only widgets in this applet are affected. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance(applet, str): appletObj = self.qteGetAppletHandle(applet) else: appletObj = applet # Return immediately if the appletObj is invalid. if appletObj is None: return # Remove the key sequence from the applet window itself. appletObj._qteAdmin.keyMap = self.qteCopyGlobalKeyMap() # Restore the global key-map for every widget. for wid in appletObj._qteAdmin.widgetList: wid._qteAdmin.keyMap = self.qteCopyGlobalKeyMap()
python
def qteUnbindAllFromApplet(self, applet: (QtmacsApplet, str)): """ Restore the global key-map for all widgets inside ``applet``. This method effectively resets the key map of all widgets to the state they would be in if the widgets were newly instantiated right now. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. If ``applet`` does not refer to an existing applet then nothing happens. |Args| * ``applet`` (**QtmacsApplet**, **str**): only widgets in this applet are affected. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance(applet, str): appletObj = self.qteGetAppletHandle(applet) else: appletObj = applet # Return immediately if the appletObj is invalid. if appletObj is None: return # Remove the key sequence from the applet window itself. appletObj._qteAdmin.keyMap = self.qteCopyGlobalKeyMap() # Restore the global key-map for every widget. for wid in appletObj._qteAdmin.widgetList: wid._qteAdmin.keyMap = self.qteCopyGlobalKeyMap()
[ "def", "qteUnbindAllFromApplet", "(", "self", ",", "applet", ":", "(", "QtmacsApplet", ",", "str", ")", ")", ":", "# If ``applet`` was specified by its ID (ie. a string) then", "# fetch the associated ``QtmacsApplet`` instance. If", "# ``applet`` is already an instance of ``QtmacsApplet`` then", "# use it directly.", "if", "isinstance", "(", "applet", ",", "str", ")", ":", "appletObj", "=", "self", ".", "qteGetAppletHandle", "(", "applet", ")", "else", ":", "appletObj", "=", "applet", "# Return immediately if the appletObj is invalid.", "if", "appletObj", "is", "None", ":", "return", "# Remove the key sequence from the applet window itself.", "appletObj", ".", "_qteAdmin", ".", "keyMap", "=", "self", ".", "qteCopyGlobalKeyMap", "(", ")", "# Restore the global key-map for every widget.", "for", "wid", "in", "appletObj", ".", "_qteAdmin", ".", "widgetList", ":", "wid", ".", "_qteAdmin", ".", "keyMap", "=", "self", ".", "qteCopyGlobalKeyMap", "(", ")" ]
Restore the global key-map for all widgets inside ``applet``. This method effectively resets the key map of all widgets to the state they would be in if the widgets were newly instantiated right now. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. If ``applet`` does not refer to an existing applet then nothing happens. |Args| * ``applet`` (**QtmacsApplet**, **str**): only widgets in this applet are affected. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Restore", "the", "global", "key", "-", "map", "for", "all", "widgets", "inside", "applet", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3572-L3619
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteUnbindAllFromWidgetObject
def qteUnbindAllFromWidgetObject(self, widgetObj: QtGui.QWidget): """ Reset the local key-map of ``widgetObj`` to the current global key-map. |Args| * ``widgetObj`` (**QWidget**): determines which widgets signature to use. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsOtherError** if ``widgetObj`` was not added with ``qteAddWidget``. """ # Check type of input arguments. if not hasattr(widgetObj, '_qteAdmin'): msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError(msg) # Install the global key-map for this widget. widgetObj._qteAdmin.keyMap = self.qteCopyGlobalKeyMap()
python
def qteUnbindAllFromWidgetObject(self, widgetObj: QtGui.QWidget): """ Reset the local key-map of ``widgetObj`` to the current global key-map. |Args| * ``widgetObj`` (**QWidget**): determines which widgets signature to use. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsOtherError** if ``widgetObj`` was not added with ``qteAddWidget``. """ # Check type of input arguments. if not hasattr(widgetObj, '_qteAdmin'): msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError(msg) # Install the global key-map for this widget. widgetObj._qteAdmin.keyMap = self.qteCopyGlobalKeyMap()
[ "def", "qteUnbindAllFromWidgetObject", "(", "self", ",", "widgetObj", ":", "QtGui", ".", "QWidget", ")", ":", "# Check type of input arguments.", "if", "not", "hasattr", "(", "widgetObj", ",", "'_qteAdmin'", ")", ":", "msg", "=", "'<widgetObj> was probably not added with <qteAddWidget>'", "msg", "+=", "' method because it lacks the <_qteAdmin> attribute.'", "raise", "QtmacsOtherError", "(", "msg", ")", "# Install the global key-map for this widget.", "widgetObj", ".", "_qteAdmin", ".", "keyMap", "=", "self", ".", "qteCopyGlobalKeyMap", "(", ")" ]
Reset the local key-map of ``widgetObj`` to the current global key-map. |Args| * ``widgetObj`` (**QWidget**): determines which widgets signature to use. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. * **QtmacsOtherError** if ``widgetObj`` was not added with ``qteAddWidget``.
[ "Reset", "the", "local", "key", "-", "map", "of", "widgetObj", "to", "the", "current", "global", "key", "-", "map", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3622-L3649
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteRegisterApplet
def qteRegisterApplet(self, cls, replaceApplet: bool=False): """ Register ``cls`` as an applet. The name of the applet is the class name of ``cls`` itself. For instance, if the applet was defined and registered as class NewApplet17(QtmacsApplet): ... app_name = qteRegisterApplet(NewApplet17) then the applet will be known as *NewApplet17*, which is also returned in ``app_name``. If an applet with this name already exists then ``replaceApplet`` decides whether the registration will overwrite the existing definition or ignore the registration request altogether. In the first case, none of the already instantiated applets will be affected, only newly created ones will use the new definition. .. note:: this method expects a *class*, not an instance. |Args| * ``cls`` (**class QtmacsApplet**): this must really be a class, not an instance. * ``replaceApplet`` (**bool**): if applet with same name exists, then replace it. |Returns| * **str**: name under which the applet was registered with Qtmacs. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Check type of input arguments. if not issubclass(cls, QtmacsApplet): args = ('cls', 'class QtmacsApplet', inspect.stack()[0][3]) raise QtmacsArgumentError(*args) # Extract the class name as string, because this is the name # under which the applet will be known. class_name = cls.__name__ # Issue a warning if an applet with this name already exists. if class_name in self._qteRegistryApplets: msg = 'The original applet <b>{}</b>'.format(class_name) if replaceApplet: msg += ' was redefined.' self.qteLogger.warning(msg) else: msg += ' was not redefined.' self.qteLogger.warning(msg) return class_name # Execute the classmethod __qteRegisterAppletInit__ to # allow the applet to make global initialisations that do # not depend on a particular instance, eg. the supported # file types. cls.__qteRegisterAppletInit__() # Add the class (not instance!) to the applet registry. self._qteRegistryApplets[class_name] = cls self.qteLogger.info('Applet <b>{}</b> now registered.' .format(class_name)) return class_name
python
def qteRegisterApplet(self, cls, replaceApplet: bool=False): """ Register ``cls`` as an applet. The name of the applet is the class name of ``cls`` itself. For instance, if the applet was defined and registered as class NewApplet17(QtmacsApplet): ... app_name = qteRegisterApplet(NewApplet17) then the applet will be known as *NewApplet17*, which is also returned in ``app_name``. If an applet with this name already exists then ``replaceApplet`` decides whether the registration will overwrite the existing definition or ignore the registration request altogether. In the first case, none of the already instantiated applets will be affected, only newly created ones will use the new definition. .. note:: this method expects a *class*, not an instance. |Args| * ``cls`` (**class QtmacsApplet**): this must really be a class, not an instance. * ``replaceApplet`` (**bool**): if applet with same name exists, then replace it. |Returns| * **str**: name under which the applet was registered with Qtmacs. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Check type of input arguments. if not issubclass(cls, QtmacsApplet): args = ('cls', 'class QtmacsApplet', inspect.stack()[0][3]) raise QtmacsArgumentError(*args) # Extract the class name as string, because this is the name # under which the applet will be known. class_name = cls.__name__ # Issue a warning if an applet with this name already exists. if class_name in self._qteRegistryApplets: msg = 'The original applet <b>{}</b>'.format(class_name) if replaceApplet: msg += ' was redefined.' self.qteLogger.warning(msg) else: msg += ' was not redefined.' self.qteLogger.warning(msg) return class_name # Execute the classmethod __qteRegisterAppletInit__ to # allow the applet to make global initialisations that do # not depend on a particular instance, eg. the supported # file types. cls.__qteRegisterAppletInit__() # Add the class (not instance!) to the applet registry. self._qteRegistryApplets[class_name] = cls self.qteLogger.info('Applet <b>{}</b> now registered.' .format(class_name)) return class_name
[ "def", "qteRegisterApplet", "(", "self", ",", "cls", ",", "replaceApplet", ":", "bool", "=", "False", ")", ":", "# Check type of input arguments.", "if", "not", "issubclass", "(", "cls", ",", "QtmacsApplet", ")", ":", "args", "=", "(", "'cls'", ",", "'class QtmacsApplet'", ",", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ")", "raise", "QtmacsArgumentError", "(", "*", "args", ")", "# Extract the class name as string, because this is the name", "# under which the applet will be known.", "class_name", "=", "cls", ".", "__name__", "# Issue a warning if an applet with this name already exists.", "if", "class_name", "in", "self", ".", "_qteRegistryApplets", ":", "msg", "=", "'The original applet <b>{}</b>'", ".", "format", "(", "class_name", ")", "if", "replaceApplet", ":", "msg", "+=", "' was redefined.'", "self", ".", "qteLogger", ".", "warning", "(", "msg", ")", "else", ":", "msg", "+=", "' was not redefined.'", "self", ".", "qteLogger", ".", "warning", "(", "msg", ")", "return", "class_name", "# Execute the classmethod __qteRegisterAppletInit__ to", "# allow the applet to make global initialisations that do", "# not depend on a particular instance, eg. the supported", "# file types.", "cls", ".", "__qteRegisterAppletInit__", "(", ")", "# Add the class (not instance!) to the applet registry.", "self", ".", "_qteRegistryApplets", "[", "class_name", "]", "=", "cls", "self", ".", "qteLogger", ".", "info", "(", "'Applet <b>{}</b> now registered.'", ".", "format", "(", "class_name", ")", ")", "return", "class_name" ]
Register ``cls`` as an applet. The name of the applet is the class name of ``cls`` itself. For instance, if the applet was defined and registered as class NewApplet17(QtmacsApplet): ... app_name = qteRegisterApplet(NewApplet17) then the applet will be known as *NewApplet17*, which is also returned in ``app_name``. If an applet with this name already exists then ``replaceApplet`` decides whether the registration will overwrite the existing definition or ignore the registration request altogether. In the first case, none of the already instantiated applets will be affected, only newly created ones will use the new definition. .. note:: this method expects a *class*, not an instance. |Args| * ``cls`` (**class QtmacsApplet**): this must really be a class, not an instance. * ``replaceApplet`` (**bool**): if applet with same name exists, then replace it. |Returns| * **str**: name under which the applet was registered with Qtmacs. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Register", "cls", "as", "an", "applet", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3688-L3758
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteGetAppletHandle
def qteGetAppletHandle(self, appletID: str): """ Return a handle to ``appletID``. If no applet with ID ``appletID`` exists then **None** is returned. |Args| * ``appletID`` (**str**): ID of applet. |Returns| * **QtmacsApplet**: handle to applet with ID ``appletID``. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Compile list of applet Ids. id_list = [_.qteAppletID() for _ in self._qteAppletList] # If one of the applets has ``appletID`` then return a # reference to it. if appletID in id_list: idx = id_list.index(appletID) return self._qteAppletList[idx] else: return None
python
def qteGetAppletHandle(self, appletID: str): """ Return a handle to ``appletID``. If no applet with ID ``appletID`` exists then **None** is returned. |Args| * ``appletID`` (**str**): ID of applet. |Returns| * **QtmacsApplet**: handle to applet with ID ``appletID``. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Compile list of applet Ids. id_list = [_.qteAppletID() for _ in self._qteAppletList] # If one of the applets has ``appletID`` then return a # reference to it. if appletID in id_list: idx = id_list.index(appletID) return self._qteAppletList[idx] else: return None
[ "def", "qteGetAppletHandle", "(", "self", ",", "appletID", ":", "str", ")", ":", "# Compile list of applet Ids.", "id_list", "=", "[", "_", ".", "qteAppletID", "(", ")", "for", "_", "in", "self", ".", "_qteAppletList", "]", "# If one of the applets has ``appletID`` then return a", "# reference to it.", "if", "appletID", "in", "id_list", ":", "idx", "=", "id_list", ".", "index", "(", "appletID", ")", "return", "self", ".", "_qteAppletList", "[", "idx", "]", "else", ":", "return", "None" ]
Return a handle to ``appletID``. If no applet with ID ``appletID`` exists then **None** is returned. |Args| * ``appletID`` (**str**): ID of applet. |Returns| * **QtmacsApplet**: handle to applet with ID ``appletID``. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Return", "a", "handle", "to", "appletID", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3797-L3825
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteMakeAppletActive
def qteMakeAppletActive(self, applet: (QtmacsApplet, str)): """ Make ``applet`` visible and give it the focus. If ``applet`` is not yet visible it will replace the currently active applet, otherwise only the focus will shift. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. |Args| * ``applet`` (**QtmacsApplet**, **str**): the applet to activate. |Returns| * **bool**: whether or not an applet was activated. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance(applet, str): appletObj = self.qteGetAppletHandle(applet) else: appletObj = applet # Sanity check: return if the applet does not exist. if appletObj not in self._qteAppletList: return False # If ``appletObj`` is a mini applet then double check that it # is actually installed and visible. If it is a conventional # applet then insert it into the layout. if self.qteIsMiniApplet(appletObj): if appletObj is not self._qteMiniApplet: self.qteLogger.warning('Wrong mini applet. Not activated.') print(appletObj) print(self._qteMiniApplet) return False if not appletObj.qteIsVisible(): appletObj.show(True) else: if not appletObj.qteIsVisible(): # Add the applet to the layout by replacing the # currently active applet. self.qteReplaceAppletInLayout(appletObj) # Update the qteActiveApplet pointer. Note that the actual # focusing is done exclusively in the focus manager. self._qteActiveApplet = appletObj return True
python
def qteMakeAppletActive(self, applet: (QtmacsApplet, str)): """ Make ``applet`` visible and give it the focus. If ``applet`` is not yet visible it will replace the currently active applet, otherwise only the focus will shift. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. |Args| * ``applet`` (**QtmacsApplet**, **str**): the applet to activate. |Returns| * **bool**: whether or not an applet was activated. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance(applet, str): appletObj = self.qteGetAppletHandle(applet) else: appletObj = applet # Sanity check: return if the applet does not exist. if appletObj not in self._qteAppletList: return False # If ``appletObj`` is a mini applet then double check that it # is actually installed and visible. If it is a conventional # applet then insert it into the layout. if self.qteIsMiniApplet(appletObj): if appletObj is not self._qteMiniApplet: self.qteLogger.warning('Wrong mini applet. Not activated.') print(appletObj) print(self._qteMiniApplet) return False if not appletObj.qteIsVisible(): appletObj.show(True) else: if not appletObj.qteIsVisible(): # Add the applet to the layout by replacing the # currently active applet. self.qteReplaceAppletInLayout(appletObj) # Update the qteActiveApplet pointer. Note that the actual # focusing is done exclusively in the focus manager. self._qteActiveApplet = appletObj return True
[ "def", "qteMakeAppletActive", "(", "self", ",", "applet", ":", "(", "QtmacsApplet", ",", "str", ")", ")", ":", "# If ``applet`` was specified by its ID (ie. a string) then", "# fetch the associated ``QtmacsApplet`` instance. If", "# ``applet`` is already an instance of ``QtmacsApplet`` then", "# use it directly.", "if", "isinstance", "(", "applet", ",", "str", ")", ":", "appletObj", "=", "self", ".", "qteGetAppletHandle", "(", "applet", ")", "else", ":", "appletObj", "=", "applet", "# Sanity check: return if the applet does not exist.", "if", "appletObj", "not", "in", "self", ".", "_qteAppletList", ":", "return", "False", "# If ``appletObj`` is a mini applet then double check that it", "# is actually installed and visible. If it is a conventional", "# applet then insert it into the layout.", "if", "self", ".", "qteIsMiniApplet", "(", "appletObj", ")", ":", "if", "appletObj", "is", "not", "self", ".", "_qteMiniApplet", ":", "self", ".", "qteLogger", ".", "warning", "(", "'Wrong mini applet. Not activated.'", ")", "print", "(", "appletObj", ")", "print", "(", "self", ".", "_qteMiniApplet", ")", "return", "False", "if", "not", "appletObj", ".", "qteIsVisible", "(", ")", ":", "appletObj", ".", "show", "(", "True", ")", "else", ":", "if", "not", "appletObj", ".", "qteIsVisible", "(", ")", ":", "# Add the applet to the layout by replacing the", "# currently active applet.", "self", ".", "qteReplaceAppletInLayout", "(", "appletObj", ")", "# Update the qteActiveApplet pointer. Note that the actual", "# focusing is done exclusively in the focus manager.", "self", ".", "_qteActiveApplet", "=", "appletObj", "return", "True" ]
Make ``applet`` visible and give it the focus. If ``applet`` is not yet visible it will replace the currently active applet, otherwise only the focus will shift. The ``applet`` parameter can either be an instance of ``QtmacsApplet`` or a string denoting an applet ID. In the latter case the ``qteGetAppletHandle`` method is used to fetch the respective applet instance. |Args| * ``applet`` (**QtmacsApplet**, **str**): the applet to activate. |Returns| * **bool**: whether or not an applet was activated. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Make", "applet", "visible", "and", "give", "it", "the", "focus", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3828-L3885
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteCloseQtmacs
def qteCloseQtmacs(self): """ Close Qtmacs. First kill all applets, then shut down Qtmacs. |Args| * **None** |Returns| * **None** |Raises| * **None** """ # Announce the shutdown. msgObj = QtmacsMessage() msgObj.setSignalName('qtesigCloseQtmacs') self.qtesigCloseQtmacs.emit(msgObj) # Kill all applets and update the GUI. for appName in self.qteGetAllAppletIDs(): self.qteKillApplet(appName) self._qteFocusManager() # Kill all windows and update the GUI. for window in self._qteWindowList: window.close() self._qteFocusManager() # Schedule QtmacsMain for deletion. self.deleteLater()
python
def qteCloseQtmacs(self): """ Close Qtmacs. First kill all applets, then shut down Qtmacs. |Args| * **None** |Returns| * **None** |Raises| * **None** """ # Announce the shutdown. msgObj = QtmacsMessage() msgObj.setSignalName('qtesigCloseQtmacs') self.qtesigCloseQtmacs.emit(msgObj) # Kill all applets and update the GUI. for appName in self.qteGetAllAppletIDs(): self.qteKillApplet(appName) self._qteFocusManager() # Kill all windows and update the GUI. for window in self._qteWindowList: window.close() self._qteFocusManager() # Schedule QtmacsMain for deletion. self.deleteLater()
[ "def", "qteCloseQtmacs", "(", "self", ")", ":", "# Announce the shutdown.", "msgObj", "=", "QtmacsMessage", "(", ")", "msgObj", ".", "setSignalName", "(", "'qtesigCloseQtmacs'", ")", "self", ".", "qtesigCloseQtmacs", ".", "emit", "(", "msgObj", ")", "# Kill all applets and update the GUI.", "for", "appName", "in", "self", ".", "qteGetAllAppletIDs", "(", ")", ":", "self", ".", "qteKillApplet", "(", "appName", ")", "self", ".", "_qteFocusManager", "(", ")", "# Kill all windows and update the GUI.", "for", "window", "in", "self", ".", "_qteWindowList", ":", "window", ".", "close", "(", ")", "self", ".", "_qteFocusManager", "(", ")", "# Schedule QtmacsMain for deletion.", "self", ".", "deleteLater", "(", ")" ]
Close Qtmacs. First kill all applets, then shut down Qtmacs. |Args| * **None** |Returns| * **None** |Raises| * **None**
[ "Close", "Qtmacs", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3887-L3921
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteDefVar
def qteDefVar(self, varName: str, value, module=None, doc: str=None): """ Define and document ``varName`` in an arbitrary name space. If ``module`` is **None** then ``qte_global`` will be used. .. warning: If the ``varName`` was already defined in ``module`` then its value and documentation are overwritten without warning. |Args| * ``varName`` (**str**): variable name. * ``value`` (**object**): arbitrary data to store. * ``module`` (**Python module**): the module in which the variable should be defined. * ``doc`` (**str**): documentation string for variable. |Returns| **bool**: **True** if ``varName`` could be defined in ``module``. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Use the global name space per default. if module is None: module = qte_global # Create the documentation dictionary if it does not exist # already. if not hasattr(module, '_qte__variable__docstring__dictionary__'): module._qte__variable__docstring__dictionary__ = {} # Set the variable value and documentation string. setattr(module, varName, value) module._qte__variable__docstring__dictionary__[varName] = doc return True
python
def qteDefVar(self, varName: str, value, module=None, doc: str=None): """ Define and document ``varName`` in an arbitrary name space. If ``module`` is **None** then ``qte_global`` will be used. .. warning: If the ``varName`` was already defined in ``module`` then its value and documentation are overwritten without warning. |Args| * ``varName`` (**str**): variable name. * ``value`` (**object**): arbitrary data to store. * ``module`` (**Python module**): the module in which the variable should be defined. * ``doc`` (**str**): documentation string for variable. |Returns| **bool**: **True** if ``varName`` could be defined in ``module``. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Use the global name space per default. if module is None: module = qte_global # Create the documentation dictionary if it does not exist # already. if not hasattr(module, '_qte__variable__docstring__dictionary__'): module._qte__variable__docstring__dictionary__ = {} # Set the variable value and documentation string. setattr(module, varName, value) module._qte__variable__docstring__dictionary__[varName] = doc return True
[ "def", "qteDefVar", "(", "self", ",", "varName", ":", "str", ",", "value", ",", "module", "=", "None", ",", "doc", ":", "str", "=", "None", ")", ":", "# Use the global name space per default.", "if", "module", "is", "None", ":", "module", "=", "qte_global", "# Create the documentation dictionary if it does not exist", "# already.", "if", "not", "hasattr", "(", "module", ",", "'_qte__variable__docstring__dictionary__'", ")", ":", "module", ".", "_qte__variable__docstring__dictionary__", "=", "{", "}", "# Set the variable value and documentation string.", "setattr", "(", "module", ",", "varName", ",", "value", ")", "module", ".", "_qte__variable__docstring__dictionary__", "[", "varName", "]", "=", "doc", "return", "True" ]
Define and document ``varName`` in an arbitrary name space. If ``module`` is **None** then ``qte_global`` will be used. .. warning: If the ``varName`` was already defined in ``module`` then its value and documentation are overwritten without warning. |Args| * ``varName`` (**str**): variable name. * ``value`` (**object**): arbitrary data to store. * ``module`` (**Python module**): the module in which the variable should be defined. * ``doc`` (**str**): documentation string for variable. |Returns| **bool**: **True** if ``varName`` could be defined in ``module``. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Define", "and", "document", "varName", "in", "an", "arbitrary", "name", "space", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3943-L3982
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteGetVariableDoc
def qteGetVariableDoc(self, varName: str, module=None): """ Retrieve documentation for ``varName`` defined in ``module``. If ``module`` is **None** then ``qte_global`` will be used. |Args| * ``varName`` (**str**): variable name. * ``module`` (**Python module**): the module in which the variable should be defined. |Returns| **str**: documentation string for ``varName``. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Use the global name space per default. if module is None: module = qte_global # No documentation for the variable can exists if the doc # string dictionary is undefined. if not hasattr(module, '_qte__variable__docstring__dictionary__'): return None # If the variable is undefined then return **None**. if varName not in module._qte__variable__docstring__dictionary__: return None # Return the requested value. return module._qte__variable__docstring__dictionary__[varName]
python
def qteGetVariableDoc(self, varName: str, module=None): """ Retrieve documentation for ``varName`` defined in ``module``. If ``module`` is **None** then ``qte_global`` will be used. |Args| * ``varName`` (**str**): variable name. * ``module`` (**Python module**): the module in which the variable should be defined. |Returns| **str**: documentation string for ``varName``. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Use the global name space per default. if module is None: module = qte_global # No documentation for the variable can exists if the doc # string dictionary is undefined. if not hasattr(module, '_qte__variable__docstring__dictionary__'): return None # If the variable is undefined then return **None**. if varName not in module._qte__variable__docstring__dictionary__: return None # Return the requested value. return module._qte__variable__docstring__dictionary__[varName]
[ "def", "qteGetVariableDoc", "(", "self", ",", "varName", ":", "str", ",", "module", "=", "None", ")", ":", "# Use the global name space per default.", "if", "module", "is", "None", ":", "module", "=", "qte_global", "# No documentation for the variable can exists if the doc", "# string dictionary is undefined.", "if", "not", "hasattr", "(", "module", ",", "'_qte__variable__docstring__dictionary__'", ")", ":", "return", "None", "# If the variable is undefined then return **None**.", "if", "varName", "not", "in", "module", ".", "_qte__variable__docstring__dictionary__", ":", "return", "None", "# Return the requested value.", "return", "module", ".", "_qte__variable__docstring__dictionary__", "[", "varName", "]" ]
Retrieve documentation for ``varName`` defined in ``module``. If ``module`` is **None** then ``qte_global`` will be used. |Args| * ``varName`` (**str**): variable name. * ``module`` (**Python module**): the module in which the variable should be defined. |Returns| **str**: documentation string for ``varName``. |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Retrieve", "documentation", "for", "varName", "defined", "in", "module", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L3985-L4019
train
olitheolix/qtmacs
qtmacs/qtmacsmain.py
QtmacsMain.qteEmulateKeypresses
def qteEmulateKeypresses(self, keysequence): """ Emulate the Qt key presses that define ``keysequence``. The method will put the keys into a queue and process them one by one once the event loop is idle, ie. the event loop executes all signals and macros associated with the emulated key press first before the next one is emulated. |Args| * ``keysequence`` (**QtmacsKeysequence**): the key sequence to emulate. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsOtherError if the conversion is impossible. keysequence = QtmacsKeysequence(keysequence) key_list = keysequence.toQKeyEventList() # Do nothing if the key list is empty. if len(key_list) > 0: # Add the keys to the queue which the event timer will # process. for event in key_list: self._qteKeyEmulationQueue.append(event)
python
def qteEmulateKeypresses(self, keysequence): """ Emulate the Qt key presses that define ``keysequence``. The method will put the keys into a queue and process them one by one once the event loop is idle, ie. the event loop executes all signals and macros associated with the emulated key press first before the next one is emulated. |Args| * ``keysequence`` (**QtmacsKeysequence**): the key sequence to emulate. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsOtherError if the conversion is impossible. keysequence = QtmacsKeysequence(keysequence) key_list = keysequence.toQKeyEventList() # Do nothing if the key list is empty. if len(key_list) > 0: # Add the keys to the queue which the event timer will # process. for event in key_list: self._qteKeyEmulationQueue.append(event)
[ "def", "qteEmulateKeypresses", "(", "self", ",", "keysequence", ")", ":", "# Convert the key sequence into a QtmacsKeysequence object, or", "# raise an QtmacsOtherError if the conversion is impossible.", "keysequence", "=", "QtmacsKeysequence", "(", "keysequence", ")", "key_list", "=", "keysequence", ".", "toQKeyEventList", "(", ")", "# Do nothing if the key list is empty.", "if", "len", "(", "key_list", ")", ">", "0", ":", "# Add the keys to the queue which the event timer will", "# process.", "for", "event", "in", "key_list", ":", "self", ".", "_qteKeyEmulationQueue", ".", "append", "(", "event", ")" ]
Emulate the Qt key presses that define ``keysequence``. The method will put the keys into a queue and process them one by one once the event loop is idle, ie. the event loop executes all signals and macros associated with the emulated key press first before the next one is emulated. |Args| * ``keysequence`` (**QtmacsKeysequence**): the key sequence to emulate. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Emulate", "the", "Qt", "key", "presses", "that", "define", "keysequence", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L4027-L4059
train
projectshift/shift-schema
shiftschema/schema.py
Schema.process
def process(self, model=None, context=None): """ Perform validation and filtering at the same time, return a validation result object. :param model: object or dict :param context: object, dict or None :return: shiftschema.result.Result """ self.filter(model, context) return self.validate(model, context)
python
def process(self, model=None, context=None): """ Perform validation and filtering at the same time, return a validation result object. :param model: object or dict :param context: object, dict or None :return: shiftschema.result.Result """ self.filter(model, context) return self.validate(model, context)
[ "def", "process", "(", "self", ",", "model", "=", "None", ",", "context", "=", "None", ")", ":", "self", ".", "filter", "(", "model", ",", "context", ")", "return", "self", ".", "validate", "(", "model", ",", "context", ")" ]
Perform validation and filtering at the same time, return a validation result object. :param model: object or dict :param context: object, dict or None :return: shiftschema.result.Result
[ "Perform", "validation", "and", "filtering", "at", "the", "same", "time", "return", "a", "validation", "result", "object", "." ]
07787b540d3369bb37217ffbfbe629118edaf0eb
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/schema.py#L168-L178
train
Midnighter/dependency-info
src/depinfo/info.py
get_sys_info
def get_sys_info(): """Return system information as a dict.""" blob = dict() blob["OS"] = platform.system() blob["OS-release"] = platform.release() blob["Python"] = platform.python_version() return blob
python
def get_sys_info(): """Return system information as a dict.""" blob = dict() blob["OS"] = platform.system() blob["OS-release"] = platform.release() blob["Python"] = platform.python_version() return blob
[ "def", "get_sys_info", "(", ")", ":", "blob", "=", "dict", "(", ")", "blob", "[", "\"OS\"", "]", "=", "platform", ".", "system", "(", ")", "blob", "[", "\"OS-release\"", "]", "=", "platform", ".", "release", "(", ")", "blob", "[", "\"Python\"", "]", "=", "platform", ".", "python_version", "(", ")", "return", "blob" ]
Return system information as a dict.
[ "Return", "system", "information", "as", "a", "dict", "." ]
15bcada0a1d6c047cbe10b844d5bd909ea8cc752
https://github.com/Midnighter/dependency-info/blob/15bcada0a1d6c047cbe10b844d5bd909ea8cc752/src/depinfo/info.py#L38-L44
train
Midnighter/dependency-info
src/depinfo/info.py
get_pkg_info
def get_pkg_info( package_name, additional=("pip", "flit", "pbr", "setuptools", "wheel") ): """Return build and package dependencies as a dict.""" dist_index = build_dist_index(pkg_resources.working_set) root = dist_index[package_name] tree = construct_tree(dist_index) dependencies = {pkg.name: pkg.installed_version for pkg in tree[root]} # Add the initial package itself. root = root.as_requirement() dependencies[root.name] = root.installed_version # Retrieve information on additional packages such as build tools. for name in additional: try: pkg = dist_index[name].as_requirement() dependencies[pkg.name] = pkg.installed_version except KeyError: continue return dependencies
python
def get_pkg_info( package_name, additional=("pip", "flit", "pbr", "setuptools", "wheel") ): """Return build and package dependencies as a dict.""" dist_index = build_dist_index(pkg_resources.working_set) root = dist_index[package_name] tree = construct_tree(dist_index) dependencies = {pkg.name: pkg.installed_version for pkg in tree[root]} # Add the initial package itself. root = root.as_requirement() dependencies[root.name] = root.installed_version # Retrieve information on additional packages such as build tools. for name in additional: try: pkg = dist_index[name].as_requirement() dependencies[pkg.name] = pkg.installed_version except KeyError: continue return dependencies
[ "def", "get_pkg_info", "(", "package_name", ",", "additional", "=", "(", "\"pip\"", ",", "\"flit\"", ",", "\"pbr\"", ",", "\"setuptools\"", ",", "\"wheel\"", ")", ")", ":", "dist_index", "=", "build_dist_index", "(", "pkg_resources", ".", "working_set", ")", "root", "=", "dist_index", "[", "package_name", "]", "tree", "=", "construct_tree", "(", "dist_index", ")", "dependencies", "=", "{", "pkg", ".", "name", ":", "pkg", ".", "installed_version", "for", "pkg", "in", "tree", "[", "root", "]", "}", "# Add the initial package itself.", "root", "=", "root", ".", "as_requirement", "(", ")", "dependencies", "[", "root", ".", "name", "]", "=", "root", ".", "installed_version", "# Retrieve information on additional packages such as build tools.", "for", "name", "in", "additional", ":", "try", ":", "pkg", "=", "dist_index", "[", "name", "]", ".", "as_requirement", "(", ")", "dependencies", "[", "pkg", ".", "name", "]", "=", "pkg", ".", "installed_version", "except", "KeyError", ":", "continue", "return", "dependencies" ]
Return build and package dependencies as a dict.
[ "Return", "build", "and", "package", "dependencies", "as", "a", "dict", "." ]
15bcada0a1d6c047cbe10b844d5bd909ea8cc752
https://github.com/Midnighter/dependency-info/blob/15bcada0a1d6c047cbe10b844d5bd909ea8cc752/src/depinfo/info.py#L47-L65
train
Midnighter/dependency-info
src/depinfo/info.py
print_info
def print_info(info): """Print an information dict to stdout in order.""" format_str = "{:<%d} {:>%d}" % ( max(map(len, info)), max(map(len, info.values())), ) for name in sorted(info): print(format_str.format(name, info[name]))
python
def print_info(info): """Print an information dict to stdout in order.""" format_str = "{:<%d} {:>%d}" % ( max(map(len, info)), max(map(len, info.values())), ) for name in sorted(info): print(format_str.format(name, info[name]))
[ "def", "print_info", "(", "info", ")", ":", "format_str", "=", "\"{:<%d} {:>%d}\"", "%", "(", "max", "(", "map", "(", "len", ",", "info", ")", ")", ",", "max", "(", "map", "(", "len", ",", "info", ".", "values", "(", ")", ")", ")", ",", ")", "for", "name", "in", "sorted", "(", "info", ")", ":", "print", "(", "format_str", ".", "format", "(", "name", ",", "info", "[", "name", "]", ")", ")" ]
Print an information dict to stdout in order.
[ "Print", "an", "information", "dict", "to", "stdout", "in", "order", "." ]
15bcada0a1d6c047cbe10b844d5bd909ea8cc752
https://github.com/Midnighter/dependency-info/blob/15bcada0a1d6c047cbe10b844d5bd909ea8cc752/src/depinfo/info.py#L68-L75
train
Midnighter/dependency-info
src/depinfo/info.py
print_dependencies
def print_dependencies(package_name): """Print the formatted information to standard out.""" info = get_sys_info() print("\nSystem Information") print("==================") print_info(info) info = get_pkg_info(package_name) print("\nPackage Versions") print("================") print_info(info)
python
def print_dependencies(package_name): """Print the formatted information to standard out.""" info = get_sys_info() print("\nSystem Information") print("==================") print_info(info) info = get_pkg_info(package_name) print("\nPackage Versions") print("================") print_info(info)
[ "def", "print_dependencies", "(", "package_name", ")", ":", "info", "=", "get_sys_info", "(", ")", "print", "(", "\"\\nSystem Information\"", ")", "print", "(", "\"==================\"", ")", "print_info", "(", "info", ")", "info", "=", "get_pkg_info", "(", "package_name", ")", "print", "(", "\"\\nPackage Versions\"", ")", "print", "(", "\"================\"", ")", "print_info", "(", "info", ")" ]
Print the formatted information to standard out.
[ "Print", "the", "formatted", "information", "to", "standard", "out", "." ]
15bcada0a1d6c047cbe10b844d5bd909ea8cc752
https://github.com/Midnighter/dependency-info/blob/15bcada0a1d6c047cbe10b844d5bd909ea8cc752/src/depinfo/info.py#L78-L88
train
OpenGov/og-python-utils
ogutils/web/operators.py
repeat_read_url_request
def repeat_read_url_request(url, headers=None, data=None, retries=2, logger=None): ''' Allows for repeated http requests up to retries additional times ''' if logger: logger.debug("Retrieving url content: {}".format(url)) req = urllib2.Request(url, data, headers=headers or {}) return repeat_call(lambda: urllib2.urlopen(req).read(), retries)
python
def repeat_read_url_request(url, headers=None, data=None, retries=2, logger=None): ''' Allows for repeated http requests up to retries additional times ''' if logger: logger.debug("Retrieving url content: {}".format(url)) req = urllib2.Request(url, data, headers=headers or {}) return repeat_call(lambda: urllib2.urlopen(req).read(), retries)
[ "def", "repeat_read_url_request", "(", "url", ",", "headers", "=", "None", ",", "data", "=", "None", ",", "retries", "=", "2", ",", "logger", "=", "None", ")", ":", "if", "logger", ":", "logger", ".", "debug", "(", "\"Retrieving url content: {}\"", ".", "format", "(", "url", ")", ")", "req", "=", "urllib2", ".", "Request", "(", "url", ",", "data", ",", "headers", "=", "headers", "or", "{", "}", ")", "return", "repeat_call", "(", "lambda", ":", "urllib2", ".", "urlopen", "(", "req", ")", ".", "read", "(", ")", ",", "retries", ")" ]
Allows for repeated http requests up to retries additional times
[ "Allows", "for", "repeated", "http", "requests", "up", "to", "retries", "additional", "times" ]
00f44927383dd1bd6348f47302c4453d56963479
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/web/operators.py#L6-L13
train
OpenGov/og-python-utils
ogutils/web/operators.py
repeat_read_json_url_request
def repeat_read_json_url_request(url, headers=None, data=None, retries=2, logger=None): ''' Allows for repeated http requests up to retries additional times with convienence wrapper on jsonization of response ''' if logger: logger.debug("Retrieving url json content: {}".format(url)) req = urllib2.Request(url, data=data, headers=headers or {}) return repeat_call(lambda: json.loads(urllib2.urlopen(req).read()), retries)
python
def repeat_read_json_url_request(url, headers=None, data=None, retries=2, logger=None): ''' Allows for repeated http requests up to retries additional times with convienence wrapper on jsonization of response ''' if logger: logger.debug("Retrieving url json content: {}".format(url)) req = urllib2.Request(url, data=data, headers=headers or {}) return repeat_call(lambda: json.loads(urllib2.urlopen(req).read()), retries)
[ "def", "repeat_read_json_url_request", "(", "url", ",", "headers", "=", "None", ",", "data", "=", "None", ",", "retries", "=", "2", ",", "logger", "=", "None", ")", ":", "if", "logger", ":", "logger", ".", "debug", "(", "\"Retrieving url json content: {}\"", ".", "format", "(", "url", ")", ")", "req", "=", "urllib2", ".", "Request", "(", "url", ",", "data", "=", "data", ",", "headers", "=", "headers", "or", "{", "}", ")", "return", "repeat_call", "(", "lambda", ":", "json", ".", "loads", "(", "urllib2", ".", "urlopen", "(", "req", ")", ".", "read", "(", ")", ")", ",", "retries", ")" ]
Allows for repeated http requests up to retries additional times with convienence wrapper on jsonization of response
[ "Allows", "for", "repeated", "http", "requests", "up", "to", "retries", "additional", "times", "with", "convienence", "wrapper", "on", "jsonization", "of", "response" ]
00f44927383dd1bd6348f47302c4453d56963479
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/web/operators.py#L15-L23
train
atl/py-smartdc
smartdc/machine.py
priv
def priv(x): """ Quick and dirty method to find an IP on a private network given a correctly formatted IPv4 quad. """ if x.startswith(u'172.'): return 16 <= int(x.split(u'.')[1]) < 32 return x.startswith((u'192.168.', u'10.', u'172.'))
python
def priv(x): """ Quick and dirty method to find an IP on a private network given a correctly formatted IPv4 quad. """ if x.startswith(u'172.'): return 16 <= int(x.split(u'.')[1]) < 32 return x.startswith((u'192.168.', u'10.', u'172.'))
[ "def", "priv", "(", "x", ")", ":", "if", "x", ".", "startswith", "(", "u'172.'", ")", ":", "return", "16", "<=", "int", "(", "x", ".", "split", "(", "u'.'", ")", "[", "1", "]", ")", "<", "32", "return", "x", ".", "startswith", "(", "(", "u'192.168.'", ",", "u'10.'", ",", "u'172.'", ")", ")" ]
Quick and dirty method to find an IP on a private network given a correctly formatted IPv4 quad.
[ "Quick", "and", "dirty", "method", "to", "find", "an", "IP", "on", "a", "private", "network", "given", "a", "correctly", "formatted", "IPv4", "quad", "." ]
cc5cd5910e19004cc46e376ce035affe28fc798e
https://github.com/atl/py-smartdc/blob/cc5cd5910e19004cc46e376ce035affe28fc798e/smartdc/machine.py#L7-L14
train
a1ezzz/wasp-general
wasp_general/network/transport.py
WBroadcastNetworkTransport.create_client_socket
def create_client_socket(self, config): """ Create client broadcast socket :param config: client configuration :return: socket.socket """ client_socket = WUDPNetworkNativeTransport.create_client_socket(self, config) client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) return client_socket
python
def create_client_socket(self, config): """ Create client broadcast socket :param config: client configuration :return: socket.socket """ client_socket = WUDPNetworkNativeTransport.create_client_socket(self, config) client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) return client_socket
[ "def", "create_client_socket", "(", "self", ",", "config", ")", ":", "client_socket", "=", "WUDPNetworkNativeTransport", ".", "create_client_socket", "(", "self", ",", "config", ")", "client_socket", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_BROADCAST", ",", "1", ")", "return", "client_socket" ]
Create client broadcast socket :param config: client configuration :return: socket.socket
[ "Create", "client", "broadcast", "socket" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/transport.py#L274-L282
train
AASHE/python-membersuite-api-client
membersuite_api_client/mixins.py
run_object_query
def run_object_query(client, base_object_query, start_record, limit_to, verbose=False): """inline method to take advantage of retry""" if verbose: print("[start: %d limit: %d]" % (start_record, limit_to)) start = datetime.datetime.now() result = client.execute_object_query( object_query=base_object_query, start_record=start_record, limit_to=limit_to) end = datetime.datetime.now() if verbose: print("[%s - %s]" % (start, end)) return result
python
def run_object_query(client, base_object_query, start_record, limit_to, verbose=False): """inline method to take advantage of retry""" if verbose: print("[start: %d limit: %d]" % (start_record, limit_to)) start = datetime.datetime.now() result = client.execute_object_query( object_query=base_object_query, start_record=start_record, limit_to=limit_to) end = datetime.datetime.now() if verbose: print("[%s - %s]" % (start, end)) return result
[ "def", "run_object_query", "(", "client", ",", "base_object_query", ",", "start_record", ",", "limit_to", ",", "verbose", "=", "False", ")", ":", "if", "verbose", ":", "print", "(", "\"[start: %d limit: %d]\"", "%", "(", "start_record", ",", "limit_to", ")", ")", "start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "result", "=", "client", ".", "execute_object_query", "(", "object_query", "=", "base_object_query", ",", "start_record", "=", "start_record", ",", "limit_to", "=", "limit_to", ")", "end", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "if", "verbose", ":", "print", "(", "\"[%s - %s]\"", "%", "(", "start", ",", "end", ")", ")", "return", "result" ]
inline method to take advantage of retry
[ "inline", "method", "to", "take", "advantage", "of", "retry" ]
221f5ed8bc7d4424237a4669c5af9edc11819ee9
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/mixins.py#L10-L23
train
AASHE/python-membersuite-api-client
membersuite_api_client/mixins.py
ChunkQueryMixin.get_long_query
def get_long_query(self, base_object_query, limit_to=100, max_calls=None, start_record=0, verbose=False): """ Takes a base query for all objects and recursively requests them :param str base_object_query: the base query to be executed :param int limit_to: how many rows to query for in each chunk :param int max_calls: the max calls(chunks to request) None is infinite :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects """ if verbose: print(base_object_query) record_index = start_record result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"]["ResultValue"] ["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: return [] if search_results is None: return [] result_set = search_results["MemberSuiteObject"] all_objects = self.result_to_models(result) call_count = 1 """ continue to run queries as long as we - don't exceed the call call_count - don't see results that are less than the limited length (the end) """ while call_count != max_calls and len(result_set) >= limit_to: record_index += len(result_set) # should be `limit_to` result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"] ["ResultValue"]["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: search_results = None if search_results is None: result_set = [] else: result_set = search_results["MemberSuiteObject"] all_objects += self.result_to_models(result) call_count += 1 return all_objects
python
def get_long_query(self, base_object_query, limit_to=100, max_calls=None, start_record=0, verbose=False): """ Takes a base query for all objects and recursively requests them :param str base_object_query: the base query to be executed :param int limit_to: how many rows to query for in each chunk :param int max_calls: the max calls(chunks to request) None is infinite :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects """ if verbose: print(base_object_query) record_index = start_record result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"]["ResultValue"] ["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: return [] if search_results is None: return [] result_set = search_results["MemberSuiteObject"] all_objects = self.result_to_models(result) call_count = 1 """ continue to run queries as long as we - don't exceed the call call_count - don't see results that are less than the limited length (the end) """ while call_count != max_calls and len(result_set) >= limit_to: record_index += len(result_set) # should be `limit_to` result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"] ["ResultValue"]["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: search_results = None if search_results is None: result_set = [] else: result_set = search_results["MemberSuiteObject"] all_objects += self.result_to_models(result) call_count += 1 return all_objects
[ "def", "get_long_query", "(", "self", ",", "base_object_query", ",", "limit_to", "=", "100", ",", "max_calls", "=", "None", ",", "start_record", "=", "0", ",", "verbose", "=", "False", ")", ":", "if", "verbose", ":", "print", "(", "base_object_query", ")", "record_index", "=", "start_record", "result", "=", "run_object_query", "(", "self", ".", "client", ",", "base_object_query", ",", "record_index", ",", "limit_to", ",", "verbose", ")", "obj_search_result", "=", "(", "result", "[", "'body'", "]", "[", "\"ExecuteMSQLResult\"", "]", "[", "\"ResultValue\"", "]", "[", "\"ObjectSearchResult\"", "]", ")", "if", "obj_search_result", "is", "not", "None", ":", "search_results", "=", "obj_search_result", "[", "\"Objects\"", "]", "else", ":", "return", "[", "]", "if", "search_results", "is", "None", ":", "return", "[", "]", "result_set", "=", "search_results", "[", "\"MemberSuiteObject\"", "]", "all_objects", "=", "self", ".", "result_to_models", "(", "result", ")", "call_count", "=", "1", "\"\"\"\n continue to run queries as long as we\n - don't exceed the call call_count\n - don't see results that are less than the limited length (the end)\n \"\"\"", "while", "call_count", "!=", "max_calls", "and", "len", "(", "result_set", ")", ">=", "limit_to", ":", "record_index", "+=", "len", "(", "result_set", ")", "# should be `limit_to`", "result", "=", "run_object_query", "(", "self", ".", "client", ",", "base_object_query", ",", "record_index", ",", "limit_to", ",", "verbose", ")", "obj_search_result", "=", "(", "result", "[", "'body'", "]", "[", "\"ExecuteMSQLResult\"", "]", "[", "\"ResultValue\"", "]", "[", "\"ObjectSearchResult\"", "]", ")", "if", "obj_search_result", "is", "not", "None", ":", "search_results", "=", "obj_search_result", "[", "\"Objects\"", "]", "else", ":", "search_results", "=", "None", "if", "search_results", "is", "None", ":", "result_set", "=", "[", "]", "else", ":", "result_set", "=", "search_results", "[", "\"MemberSuiteObject\"", "]", "all_objects", "+=", "self", ".", "result_to_models", "(", "result", ")", "call_count", "+=", "1", "return", "all_objects" ]
Takes a base query for all objects and recursively requests them :param str base_object_query: the base query to be executed :param int limit_to: how many rows to query for in each chunk :param int max_calls: the max calls(chunks to request) None is infinite :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects
[ "Takes", "a", "base", "query", "for", "all", "objects", "and", "recursively", "requests", "them" ]
221f5ed8bc7d4424237a4669c5af9edc11819ee9
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/mixins.py#L35-L95
train
Chilipp/model-organization
model_organization/__init__.py
ModelOrganizer.logger
def logger(self): """The logger of this organizer""" if self._experiment: return logging.getLogger('.'.join([self.name, self.experiment])) elif self._projectname: return logging.getLogger('.'.join([self.name, self.projectname])) else: return logging.getLogger('.'.join([self.name]))
python
def logger(self): """The logger of this organizer""" if self._experiment: return logging.getLogger('.'.join([self.name, self.experiment])) elif self._projectname: return logging.getLogger('.'.join([self.name, self.projectname])) else: return logging.getLogger('.'.join([self.name]))
[ "def", "logger", "(", "self", ")", ":", "if", "self", ".", "_experiment", ":", "return", "logging", ".", "getLogger", "(", "'.'", ".", "join", "(", "[", "self", ".", "name", ",", "self", ".", "experiment", "]", ")", ")", "elif", "self", ".", "_projectname", ":", "return", "logging", ".", "getLogger", "(", "'.'", ".", "join", "(", "[", "self", ".", "name", ",", "self", ".", "projectname", "]", ")", ")", "else", ":", "return", "logging", ".", "getLogger", "(", "'.'", ".", "join", "(", "[", "self", ".", "name", "]", ")", ")" ]
The logger of this organizer
[ "The", "logger", "of", "this", "organizer" ]
694d1219c7ed7e1b2b17153afa11bdc21169bca2
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/model_organization/__init__.py#L98-L105
train
Chilipp/model-organization
model_organization/__init__.py
ModelOrganizer.main
def main(cls, args=None): """ Run the organizer from the command line Parameters ---------- name: str The name of the program args: list The arguments that are parsed to the argument parser """ organizer = cls() organizer.parse_args(args) if not organizer.no_modification: organizer.config.save()
python
def main(cls, args=None): """ Run the organizer from the command line Parameters ---------- name: str The name of the program args: list The arguments that are parsed to the argument parser """ organizer = cls() organizer.parse_args(args) if not organizer.no_modification: organizer.config.save()
[ "def", "main", "(", "cls", ",", "args", "=", "None", ")", ":", "organizer", "=", "cls", "(", ")", "organizer", ".", "parse_args", "(", "args", ")", "if", "not", "organizer", ".", "no_modification", ":", "organizer", ".", "config", ".", "save", "(", ")" ]
Run the organizer from the command line Parameters ---------- name: str The name of the program args: list The arguments that are parsed to the argument parser
[ "Run", "the", "organizer", "from", "the", "command", "line" ]
694d1219c7ed7e1b2b17153afa11bdc21169bca2
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/model_organization/__init__.py#L141-L155
train
Chilipp/model-organization
model_organization/__init__.py
ModelOrganizer.start
def start(self, **kwargs): """ Start the commands of this organizer Parameters ---------- ``**kwargs`` Any keyword from the :attr:`commands` or :attr:`parser_commands` attribute Returns ------- argparse.Namespace The namespace with the commands as given in ``**kwargs`` and the return values of the corresponding method""" ts = {} ret = {} info_parts = {'info', 'get-value', 'get_value'} for cmd in self.commands: parser_cmd = self.parser_commands.get(cmd, cmd) if parser_cmd in kwargs or cmd in kwargs: kws = kwargs.get(cmd, kwargs.get(parser_cmd)) if isinstance(kws, Namespace): kws = vars(kws) func = getattr(self, cmd or 'main') ret[cmd] = func(**kws) if cmd not in info_parts: ts[cmd] = str(dt.datetime.now()) exp = self._experiment project_parts = {'setup'} projectname = self._projectname if (projectname is not None and project_parts.intersection(ts) and projectname in self.config.projects): self.config.projects[projectname]['timestamps'].update( {key: ts[key] for key in project_parts.intersection(ts)}) elif not ts: # don't make modifications for info self.no_modification = True if exp is not None and exp in self.config.experiments: projectname = self.projectname try: ts.update(self.config.projects[projectname]['timestamps']) except KeyError: pass if not self.is_archived(exp): self.config.experiments[exp]['timestamps'].update(ts) return Namespace(**ret)
python
def start(self, **kwargs): """ Start the commands of this organizer Parameters ---------- ``**kwargs`` Any keyword from the :attr:`commands` or :attr:`parser_commands` attribute Returns ------- argparse.Namespace The namespace with the commands as given in ``**kwargs`` and the return values of the corresponding method""" ts = {} ret = {} info_parts = {'info', 'get-value', 'get_value'} for cmd in self.commands: parser_cmd = self.parser_commands.get(cmd, cmd) if parser_cmd in kwargs or cmd in kwargs: kws = kwargs.get(cmd, kwargs.get(parser_cmd)) if isinstance(kws, Namespace): kws = vars(kws) func = getattr(self, cmd or 'main') ret[cmd] = func(**kws) if cmd not in info_parts: ts[cmd] = str(dt.datetime.now()) exp = self._experiment project_parts = {'setup'} projectname = self._projectname if (projectname is not None and project_parts.intersection(ts) and projectname in self.config.projects): self.config.projects[projectname]['timestamps'].update( {key: ts[key] for key in project_parts.intersection(ts)}) elif not ts: # don't make modifications for info self.no_modification = True if exp is not None and exp in self.config.experiments: projectname = self.projectname try: ts.update(self.config.projects[projectname]['timestamps']) except KeyError: pass if not self.is_archived(exp): self.config.experiments[exp]['timestamps'].update(ts) return Namespace(**ret)
[ "def", "start", "(", "self", ",", "*", "*", "kwargs", ")", ":", "ts", "=", "{", "}", "ret", "=", "{", "}", "info_parts", "=", "{", "'info'", ",", "'get-value'", ",", "'get_value'", "}", "for", "cmd", "in", "self", ".", "commands", ":", "parser_cmd", "=", "self", ".", "parser_commands", ".", "get", "(", "cmd", ",", "cmd", ")", "if", "parser_cmd", "in", "kwargs", "or", "cmd", "in", "kwargs", ":", "kws", "=", "kwargs", ".", "get", "(", "cmd", ",", "kwargs", ".", "get", "(", "parser_cmd", ")", ")", "if", "isinstance", "(", "kws", ",", "Namespace", ")", ":", "kws", "=", "vars", "(", "kws", ")", "func", "=", "getattr", "(", "self", ",", "cmd", "or", "'main'", ")", "ret", "[", "cmd", "]", "=", "func", "(", "*", "*", "kws", ")", "if", "cmd", "not", "in", "info_parts", ":", "ts", "[", "cmd", "]", "=", "str", "(", "dt", ".", "datetime", ".", "now", "(", ")", ")", "exp", "=", "self", ".", "_experiment", "project_parts", "=", "{", "'setup'", "}", "projectname", "=", "self", ".", "_projectname", "if", "(", "projectname", "is", "not", "None", "and", "project_parts", ".", "intersection", "(", "ts", ")", "and", "projectname", "in", "self", ".", "config", ".", "projects", ")", ":", "self", ".", "config", ".", "projects", "[", "projectname", "]", "[", "'timestamps'", "]", ".", "update", "(", "{", "key", ":", "ts", "[", "key", "]", "for", "key", "in", "project_parts", ".", "intersection", "(", "ts", ")", "}", ")", "elif", "not", "ts", ":", "# don't make modifications for info", "self", ".", "no_modification", "=", "True", "if", "exp", "is", "not", "None", "and", "exp", "in", "self", ".", "config", ".", "experiments", ":", "projectname", "=", "self", ".", "projectname", "try", ":", "ts", ".", "update", "(", "self", ".", "config", ".", "projects", "[", "projectname", "]", "[", "'timestamps'", "]", ")", "except", "KeyError", ":", "pass", "if", "not", "self", ".", "is_archived", "(", "exp", ")", ":", "self", ".", "config", ".", "experiments", "[", "exp", "]", "[", "'timestamps'", "]", ".", "update", "(", "ts", ")", "return", "Namespace", "(", "*", "*", "ret", ")" ]
Start the commands of this organizer Parameters ---------- ``**kwargs`` Any keyword from the :attr:`commands` or :attr:`parser_commands` attribute Returns ------- argparse.Namespace The namespace with the commands as given in ``**kwargs`` and the return values of the corresponding method
[ "Start", "the", "commands", "of", "this", "organizer" ]
694d1219c7ed7e1b2b17153afa11bdc21169bca2
https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/model_organization/__init__.py#L159-L204
train