Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
TestCmdSetMergers.test_order
(self)
Merge in reverse- and forward orders, same priorities
Merge in reverse- and forward orders, same priorities
def test_order(self): "Merge in reverse- and forward orders, same priorities" a, b, c, d = self.cmdset_a, self.cmdset_b, self.cmdset_c, self.cmdset_d cmdset_f = d + c + b + a # merge in reverse order of priority self.assertEqual(cmdset_f.priority, 0) self.assertEqual(cmdset_f.mergetype, "Union") self.assertEqual(len(cmdset_f.commands), 4) self.assertTrue(all(True for cmd in cmdset_f.commands if cmd.from_cmdset == "A")) cmdset_f = a + b + c + d # merge in order of priority self.assertEqual(cmdset_f.priority, 0) self.assertEqual(cmdset_f.mergetype, "Union") self.assertEqual(len(cmdset_f.commands), 4) # duplicates setting from A transfers self.assertTrue(all(True for cmd in cmdset_f.commands if cmd.from_cmdset == "D"))
[ "def", "test_order", "(", "self", ")", ":", "a", ",", "b", ",", "c", ",", "d", "=", "self", ".", "cmdset_a", ",", "self", ".", "cmdset_b", ",", "self", ".", "cmdset_c", ",", "self", ".", "cmdset_d", "cmdset_f", "=", "d", "+", "c", "+", "b", "+", "a", "# merge in reverse order of priority", "self", ".", "assertEqual", "(", "cmdset_f", ".", "priority", ",", "0", ")", "self", ".", "assertEqual", "(", "cmdset_f", ".", "mergetype", ",", "\"Union\"", ")", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "4", ")", "self", ".", "assertTrue", "(", "all", "(", "True", "for", "cmd", "in", "cmdset_f", ".", "commands", "if", "cmd", ".", "from_cmdset", "==", "\"A\"", ")", ")", "cmdset_f", "=", "a", "+", "b", "+", "c", "+", "d", "# merge in order of priority", "self", ".", "assertEqual", "(", "cmdset_f", ".", "priority", ",", "0", ")", "self", ".", "assertEqual", "(", "cmdset_f", ".", "mergetype", ",", "\"Union\"", ")", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "4", ")", "# duplicates setting from A transfers", "self", ".", "assertTrue", "(", "all", "(", "True", "for", "cmd", "in", "cmdset_f", ".", "commands", "if", "cmd", ".", "from_cmdset", "==", "\"D\"", ")", ")" ]
[ 160, 4 ]
[ 172, 89 ]
python
en
['en', 'af', 'en']
True
TestCmdSetMergers.test_priority_order
(self)
Merge in reverse- and forward order with well-defined prioritities
Merge in reverse- and forward order with well-defined prioritities
def test_priority_order(self): "Merge in reverse- and forward order with well-defined prioritities" a, b, c, d = self.cmdset_a, self.cmdset_b, self.cmdset_c, self.cmdset_d a.priority = 2 b.priority = 1 c.priority = 0 d.priority = -1 cmdset_f = d + c + b + a # merge in reverse order of priority self.assertEqual(cmdset_f.priority, 2) self.assertEqual(cmdset_f.mergetype, "Union") self.assertEqual(len(cmdset_f.commands), 4) self.assertTrue(all(True for cmd in cmdset_f.commands if cmd.from_cmdset == "A")) cmdset_f = a + b + c + d # merge in order of priority self.assertEqual(cmdset_f.priority, 2) self.assertEqual(cmdset_f.mergetype, "Union") self.assertEqual(len(cmdset_f.commands), 4) self.assertTrue(all(True for cmd in cmdset_f.commands if cmd.from_cmdset == "A"))
[ "def", "test_priority_order", "(", "self", ")", ":", "a", ",", "b", ",", "c", ",", "d", "=", "self", ".", "cmdset_a", ",", "self", ".", "cmdset_b", ",", "self", ".", "cmdset_c", ",", "self", ".", "cmdset_d", "a", ".", "priority", "=", "2", "b", ".", "priority", "=", "1", "c", ".", "priority", "=", "0", "d", ".", "priority", "=", "-", "1", "cmdset_f", "=", "d", "+", "c", "+", "b", "+", "a", "# merge in reverse order of priority", "self", ".", "assertEqual", "(", "cmdset_f", ".", "priority", ",", "2", ")", "self", ".", "assertEqual", "(", "cmdset_f", ".", "mergetype", ",", "\"Union\"", ")", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "4", ")", "self", ".", "assertTrue", "(", "all", "(", "True", "for", "cmd", "in", "cmdset_f", ".", "commands", "if", "cmd", ".", "from_cmdset", "==", "\"A\"", ")", ")", "cmdset_f", "=", "a", "+", "b", "+", "c", "+", "d", "# merge in order of priority", "self", ".", "assertEqual", "(", "cmdset_f", ".", "priority", ",", "2", ")", "self", ".", "assertEqual", "(", "cmdset_f", ".", "mergetype", ",", "\"Union\"", ")", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "4", ")", "self", ".", "assertTrue", "(", "all", "(", "True", "for", "cmd", "in", "cmdset_f", ".", "commands", "if", "cmd", ".", "from_cmdset", "==", "\"A\"", ")", ")" ]
[ 174, 4 ]
[ 190, 89 ]
python
en
['en', 'en', 'en']
True
TestCmdSetMergers.test_option_transfer
(self)
Test transfer of cmdset options
Test transfer of cmdset options
def test_option_transfer(self): "Test transfer of cmdset options" a, b, c, d = self.cmdset_a, self.cmdset_b, self.cmdset_c, self.cmdset_d # the options should pass through since none of the other cmdsets care # to change the setting from None. a.no_exits = True a.no_objs = True a.no_channels = True a.duplicates = True cmdset_f = d + c + b + a # reverse, same-prio self.assertTrue(cmdset_f.no_exits) self.assertTrue(cmdset_f.no_objs) self.assertTrue(cmdset_f.no_channels) self.assertTrue(cmdset_f.duplicates) self.assertEqual(len(cmdset_f.commands), 8) cmdset_f = a + b + c + d # forward, same-prio self.assertTrue(cmdset_f.no_exits) self.assertTrue(cmdset_f.no_objs) self.assertTrue(cmdset_f.no_channels) self.assertFalse(cmdset_f.duplicates) self.assertEqual(len(cmdset_f.commands), 4) a.priority = 2 b.priority = 1 c.priority = 0 d.priority = -1 cmdset_f = d + c + b + a # reverse, A top priority self.assertTrue(cmdset_f.no_exits) self.assertTrue(cmdset_f.no_objs) self.assertTrue(cmdset_f.no_channels) self.assertTrue(cmdset_f.duplicates) self.assertEqual(len(cmdset_f.commands), 4) cmdset_f = a + b + c + d # forward, A top priority. This never happens in practice. self.assertTrue(cmdset_f.no_exits) self.assertTrue(cmdset_f.no_objs) self.assertTrue(cmdset_f.no_channels) self.assertTrue(cmdset_f.duplicates) self.assertEqual(len(cmdset_f.commands), 4) a.priority = -1 b.priority = 0 c.priority = 1 d.priority = 2 cmdset_f = d + c + b + a # reverse, A low prio. This never happens in practice. self.assertTrue(cmdset_f.no_exits) self.assertTrue(cmdset_f.no_objs) self.assertTrue(cmdset_f.no_channels) self.assertFalse(cmdset_f.duplicates) self.assertEqual(len(cmdset_f.commands), 4) cmdset_f = a + b + c + d # forward, A low prio self.assertTrue(cmdset_f.no_exits) self.assertTrue(cmdset_f.no_objs) self.assertTrue(cmdset_f.no_channels) self.assertFalse(cmdset_f.duplicates) self.assertEqual(len(cmdset_f.commands), 4) c.no_exits = False b.no_objs = False d.duplicates = False # higher-prio sets will change the option up the chain cmdset_f = a + b + c + d # forward, A low prio self.assertFalse(cmdset_f.no_exits) self.assertFalse(cmdset_f.no_objs) self.assertTrue(cmdset_f.no_channels) self.assertFalse(cmdset_f.duplicates) self.assertEqual(len(cmdset_f.commands), 4) a.priority = 0 b.priority = 0 c.priority = 0 d.priority = 0 c.duplicates = True cmdset_f = d + b + c + a # two last mergers duplicates=True self.assertEqual(len(cmdset_f.commands), 10)
[ "def", "test_option_transfer", "(", "self", ")", ":", "a", ",", "b", ",", "c", ",", "d", "=", "self", ".", "cmdset_a", ",", "self", ".", "cmdset_b", ",", "self", ".", "cmdset_c", ",", "self", ".", "cmdset_d", "# the options should pass through since none of the other cmdsets care", "# to change the setting from None.", "a", ".", "no_exits", "=", "True", "a", ".", "no_objs", "=", "True", "a", ".", "no_channels", "=", "True", "a", ".", "duplicates", "=", "True", "cmdset_f", "=", "d", "+", "c", "+", "b", "+", "a", "# reverse, same-prio", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_exits", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_objs", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_channels", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "duplicates", ")", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "8", ")", "cmdset_f", "=", "a", "+", "b", "+", "c", "+", "d", "# forward, same-prio", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_exits", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_objs", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_channels", ")", "self", ".", "assertFalse", "(", "cmdset_f", ".", "duplicates", ")", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "4", ")", "a", ".", "priority", "=", "2", "b", ".", "priority", "=", "1", "c", ".", "priority", "=", "0", "d", ".", "priority", "=", "-", "1", "cmdset_f", "=", "d", "+", "c", "+", "b", "+", "a", "# reverse, A top priority", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_exits", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_objs", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_channels", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "duplicates", ")", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "4", ")", "cmdset_f", "=", "a", "+", "b", "+", "c", "+", "d", "# forward, A top priority. This never happens in practice.", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_exits", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_objs", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_channels", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "duplicates", ")", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "4", ")", "a", ".", "priority", "=", "-", "1", "b", ".", "priority", "=", "0", "c", ".", "priority", "=", "1", "d", ".", "priority", "=", "2", "cmdset_f", "=", "d", "+", "c", "+", "b", "+", "a", "# reverse, A low prio. This never happens in practice.", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_exits", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_objs", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_channels", ")", "self", ".", "assertFalse", "(", "cmdset_f", ".", "duplicates", ")", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "4", ")", "cmdset_f", "=", "a", "+", "b", "+", "c", "+", "d", "# forward, A low prio", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_exits", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_objs", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_channels", ")", "self", ".", "assertFalse", "(", "cmdset_f", ".", "duplicates", ")", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "4", ")", "c", ".", "no_exits", "=", "False", "b", ".", "no_objs", "=", "False", "d", ".", "duplicates", "=", "False", "# higher-prio sets will change the option up the chain", "cmdset_f", "=", "a", "+", "b", "+", "c", "+", "d", "# forward, A low prio", "self", ".", "assertFalse", "(", "cmdset_f", ".", "no_exits", ")", "self", ".", "assertFalse", "(", "cmdset_f", ".", "no_objs", ")", "self", ".", "assertTrue", "(", "cmdset_f", ".", "no_channels", ")", "self", ".", "assertFalse", "(", "cmdset_f", ".", "duplicates", ")", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "4", ")", "a", ".", "priority", "=", "0", "b", ".", "priority", "=", "0", "c", ".", "priority", "=", "0", "d", ".", "priority", "=", "0", "c", ".", "duplicates", "=", "True", "cmdset_f", "=", "d", "+", "b", "+", "c", "+", "a", "# two last mergers duplicates=True", "self", ".", "assertEqual", "(", "len", "(", "cmdset_f", ".", "commands", ")", ",", "10", ")" ]
[ 192, 4 ]
[ 261, 52 ]
python
en
['en', 'no', 'en']
True
TestGetAndMergeCmdSets.set_cmdsets
(self, obj, *args)
Set cmdets on obj in the order given in *args
Set cmdets on obj in the order given in *args
def set_cmdsets(self, obj, *args): "Set cmdets on obj in the order given in *args" for cmdset in args: obj.cmdset.add(cmdset)
[ "def", "set_cmdsets", "(", "self", ",", "obj", ",", "*", "args", ")", ":", "for", "cmdset", "in", "args", ":", "obj", ".", "cmdset", ".", "add", "(", "cmdset", ")" ]
[ 286, 4 ]
[ 289, 34 ]
python
en
['en', 'en', 'en']
True
_dummy_process
(text, *args, **kwargs)
Pass-through processor
Pass-through processor
def _dummy_process(text, *args, **kwargs): "Pass-through processor" return text
[ "def", "_dummy_process", "(", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "text" ]
[ 187, 0 ]
[ 189, 15 ]
python
en
['en', 'pt', 'en']
False
ordered_permutation_regex
(sentence)
Builds a regex that matches 'ordered permutations' of a sentence's words. Args: sentence (str): The sentence to build a match pattern to Returns: regex (re object): Compiled regex object represented the possible ordered permutations of the sentence, from longest to shortest. Example: The sdesc_regex for an sdesc of " very tall man" will result in the following allowed permutations, regex-matched in inverse order of length (case-insensitive): "the very tall man", "the very tall", "very tall man", "very tall", "the very", "tall man", "the", "very", "tall", and "man". We also add regex to make sure it also accepts num-specifiers, like /2-tall.
Builds a regex that matches 'ordered permutations' of a sentence's words.
def ordered_permutation_regex(sentence): """ Builds a regex that matches 'ordered permutations' of a sentence's words. Args: sentence (str): The sentence to build a match pattern to Returns: regex (re object): Compiled regex object represented the possible ordered permutations of the sentence, from longest to shortest. Example: The sdesc_regex for an sdesc of " very tall man" will result in the following allowed permutations, regex-matched in inverse order of length (case-insensitive): "the very tall man", "the very tall", "very tall man", "very tall", "the very", "tall man", "the", "very", "tall", and "man". We also add regex to make sure it also accepts num-specifiers, like /2-tall. """ # escape {#nnn} markers from sentence, replace with nnn sentence = _RE_REF.sub(r"\1", sentence) # escape {##nnn} markers, replace with nnn sentence = _RE_REF_LANG.sub(r"\1", sentence) # escape self-ref marker from sentence sentence = _RE_SELF_REF.sub(r"", sentence) # ordered permutation algorithm words = sentence.split() combinations = itertools.product((True, False), repeat=len(words)) solution = [] for combination in combinations: comb = [] for iword, word in enumerate(words): if combination[iword]: comb.append(word) elif comb: break if comb: solution.append(_PREFIX + r"[0-9]*%s*%s(?=\W|$)+" % (_NUM_SEP, re_escape(" ".join(comb)).rstrip("\\"))) # combine into a match regex, first matching the longest down to the shortest components regex = r"|".join(sorted(set(solution), key=len, reverse=True)) return regex
[ "def", "ordered_permutation_regex", "(", "sentence", ")", ":", "# escape {#nnn} markers from sentence, replace with nnn", "sentence", "=", "_RE_REF", ".", "sub", "(", "r\"\\1\"", ",", "sentence", ")", "# escape {##nnn} markers, replace with nnn", "sentence", "=", "_RE_REF_LANG", ".", "sub", "(", "r\"\\1\"", ",", "sentence", ")", "# escape self-ref marker from sentence", "sentence", "=", "_RE_SELF_REF", ".", "sub", "(", "r\"\"", ",", "sentence", ")", "# ordered permutation algorithm", "words", "=", "sentence", ".", "split", "(", ")", "combinations", "=", "itertools", ".", "product", "(", "(", "True", ",", "False", ")", ",", "repeat", "=", "len", "(", "words", ")", ")", "solution", "=", "[", "]", "for", "combination", "in", "combinations", ":", "comb", "=", "[", "]", "for", "iword", ",", "word", "in", "enumerate", "(", "words", ")", ":", "if", "combination", "[", "iword", "]", ":", "comb", ".", "append", "(", "word", ")", "elif", "comb", ":", "break", "if", "comb", ":", "solution", ".", "append", "(", "_PREFIX", "+", "r\"[0-9]*%s*%s(?=\\W|$)+\"", "%", "(", "_NUM_SEP", ",", "re_escape", "(", "\" \"", ".", "join", "(", "comb", ")", ")", ".", "rstrip", "(", "\"\\\\\"", ")", ")", ")", "# combine into a match regex, first matching the longest down to the shortest components", "regex", "=", "r\"|\"", ".", "join", "(", "sorted", "(", "set", "(", "solution", ")", ",", "key", "=", "len", ",", "reverse", "=", "True", ")", ")", "return", "regex" ]
[ 195, 0 ]
[ 241, 16 ]
python
en
['en', 'error', 'th']
False
regex_tuple_from_key_alias
(obj)
This will build a regex tuple for any object, not just from those with sdesc/recog handlers. It's used as a legacy mechanism for being able to mix this contrib with objects not using sdescs, but note that creating the ordered permutation regex dynamically for every object will add computational overhead. Args: obj (Object): This object's key and eventual aliases will be used to build the tuple. Returns: regex_tuple (tuple): A tuple (ordered_permutation_regex, obj, key/alias)
This will build a regex tuple for any object, not just from those with sdesc/recog handlers. It's used as a legacy mechanism for being able to mix this contrib with objects not using sdescs, but note that creating the ordered permutation regex dynamically for every object will add computational overhead.
def regex_tuple_from_key_alias(obj): """ This will build a regex tuple for any object, not just from those with sdesc/recog handlers. It's used as a legacy mechanism for being able to mix this contrib with objects not using sdescs, but note that creating the ordered permutation regex dynamically for every object will add computational overhead. Args: obj (Object): This object's key and eventual aliases will be used to build the tuple. Returns: regex_tuple (tuple): A tuple (ordered_permutation_regex, obj, key/alias) """ return (re.compile(ordered_permutation_regex(" ".join([obj.key] + obj.aliases.all())), _RE_FLAGS), obj, obj.key)
[ "def", "regex_tuple_from_key_alias", "(", "obj", ")", ":", "return", "(", "re", ".", "compile", "(", "ordered_permutation_regex", "(", "\" \"", ".", "join", "(", "[", "obj", ".", "key", "]", "+", "obj", ".", "aliases", ".", "all", "(", ")", ")", ")", ",", "_RE_FLAGS", ")", ",", "obj", ",", "obj", ".", "key", ")" ]
[ 244, 0 ]
[ 263, 20 ]
python
en
['en', 'error', 'th']
False
parse_language
(speaker, emote)
Parse the emote for language. This is used with a plugin for handling languages. Args: speaker (Object): The object speaking. emote (str): An emote possibly containing language references. Returns: (emote, mapping) (tuple): A tuple where the `emote` is the emote string with all says (including quotes) replaced with reference markers on the form {##n} where n is a running number. The `mapping` is a dictionary between the markers and a tuple (langname, saytext), where langname can be None. Raises: LanguageError: If an invalid language was specified. Notes: Note that no errors are raised if the wrong language identifier is given. This data, together with the identity of the speaker, is intended to be used by the "listener" later, since with this information the language skill of the speaker can be offset to the language skill of the listener to determine how much information is actually conveyed.
Parse the emote for language. This is used with a plugin for handling languages.
def parse_language(speaker, emote): """ Parse the emote for language. This is used with a plugin for handling languages. Args: speaker (Object): The object speaking. emote (str): An emote possibly containing language references. Returns: (emote, mapping) (tuple): A tuple where the `emote` is the emote string with all says (including quotes) replaced with reference markers on the form {##n} where n is a running number. The `mapping` is a dictionary between the markers and a tuple (langname, saytext), where langname can be None. Raises: LanguageError: If an invalid language was specified. Notes: Note that no errors are raised if the wrong language identifier is given. This data, together with the identity of the speaker, is intended to be used by the "listener" later, since with this information the language skill of the speaker can be offset to the language skill of the listener to determine how much information is actually conveyed. """ # escape mapping syntax on the form {##id} if it exists already in emote, # if so it is replaced with just "id". emote = _RE_REF_LANG.sub(r"\1", emote) errors = [] mapping = {} for imatch, say_match in enumerate(reversed(list(_RE_LANGUAGE.finditer(emote)))): # process matches backwards to be able to replace # in-place without messing up indexes for future matches # note that saytext includes surrounding "...". langname, saytext = say_match.groups() istart, iend = say_match.start(), say_match.end() # the key is simply the running match in the emote key = "##%i" % imatch # replace say with ref markers in emote emote = emote[:istart] + "{%s}" % key + emote[iend:] mapping[key] = (langname, saytext) if errors: # catch errors and report raise LanguageError("\n".join(errors)) # at this point all says have been replaced with {##nn} markers # and mapping maps 1:1 to this. return emote, mapping
[ "def", "parse_language", "(", "speaker", ",", "emote", ")", ":", "# escape mapping syntax on the form {##id} if it exists already in emote,", "# if so it is replaced with just \"id\".", "emote", "=", "_RE_REF_LANG", ".", "sub", "(", "r\"\\1\"", ",", "emote", ")", "errors", "=", "[", "]", "mapping", "=", "{", "}", "for", "imatch", ",", "say_match", "in", "enumerate", "(", "reversed", "(", "list", "(", "_RE_LANGUAGE", ".", "finditer", "(", "emote", ")", ")", ")", ")", ":", "# process matches backwards to be able to replace", "# in-place without messing up indexes for future matches", "# note that saytext includes surrounding \"...\".", "langname", ",", "saytext", "=", "say_match", ".", "groups", "(", ")", "istart", ",", "iend", "=", "say_match", ".", "start", "(", ")", ",", "say_match", ".", "end", "(", ")", "# the key is simply the running match in the emote", "key", "=", "\"##%i\"", "%", "imatch", "# replace say with ref markers in emote", "emote", "=", "emote", "[", ":", "istart", "]", "+", "\"{%s}\"", "%", "key", "+", "emote", "[", "iend", ":", "]", "mapping", "[", "key", "]", "=", "(", "langname", ",", "saytext", ")", "if", "errors", ":", "# catch errors and report", "raise", "LanguageError", "(", "\"\\n\"", ".", "join", "(", "errors", ")", ")", "# at this point all says have been replaced with {##nn} markers", "# and mapping maps 1:1 to this.", "return", "emote", ",", "mapping" ]
[ 266, 0 ]
[ 321, 25 ]
python
en
['en', 'error', 'th']
False
parse_sdescs_and_recogs
(sender, candidates, string, search_mode=False)
Read a raw emote and parse it into an intermediary format for distributing to all observers. Args: sender (Object): The object sending the emote. This object's recog data will be considered in the parsing. candidates (iterable): A list of objects valid for referencing in the emote. string (str): The string (like an emote) we want to analyze for keywords. search_mode (bool, optional): If `True`, the "emote" is a query string we want to analyze. If so, the return value is changed. Returns: (emote, mapping) (tuple): If `search_mode` is `False` (default), a tuple where the emote is the emote string, with all references replaced with internal-representation {#dbref} markers and mapping is a dictionary `{"#dbref":obj, ...}`. result (list): If `search_mode` is `True` we are performing a search query on `string`, looking for a specific object. A list with zero, one or more matches. Raises: EmoteException: For various ref-matching errors. Notes: The parser analyzes and should understand the following _PREFIX-tagged structures in the emote: - self-reference (/me) - recogs (any part of it) stored on emoter, matching obj in `candidates`. - sdesc (any part of it) from any obj in `candidates`. - N-sdesc, N-recog separating multi-matches (1-tall, 2-tall) - says, "..." are
Read a raw emote and parse it into an intermediary format for distributing to all observers.
def parse_sdescs_and_recogs(sender, candidates, string, search_mode=False): """ Read a raw emote and parse it into an intermediary format for distributing to all observers. Args: sender (Object): The object sending the emote. This object's recog data will be considered in the parsing. candidates (iterable): A list of objects valid for referencing in the emote. string (str): The string (like an emote) we want to analyze for keywords. search_mode (bool, optional): If `True`, the "emote" is a query string we want to analyze. If so, the return value is changed. Returns: (emote, mapping) (tuple): If `search_mode` is `False` (default), a tuple where the emote is the emote string, with all references replaced with internal-representation {#dbref} markers and mapping is a dictionary `{"#dbref":obj, ...}`. result (list): If `search_mode` is `True` we are performing a search query on `string`, looking for a specific object. A list with zero, one or more matches. Raises: EmoteException: For various ref-matching errors. Notes: The parser analyzes and should understand the following _PREFIX-tagged structures in the emote: - self-reference (/me) - recogs (any part of it) stored on emoter, matching obj in `candidates`. - sdesc (any part of it) from any obj in `candidates`. - N-sdesc, N-recog separating multi-matches (1-tall, 2-tall) - says, "..." are """ # Load all candidate regex tuples [(regex, obj, sdesc/recog),...] candidate_regexes = \ ([(_RE_SELF_REF, sender, sender.sdesc.get())] if hasattr(sender, "sdesc") else []) + \ ([sender.recog.get_regex_tuple(obj) for obj in candidates] if hasattr(sender, "recog") else []) + \ [obj.sdesc.get_regex_tuple() for obj in candidates if hasattr(obj, "sdesc")] + \ [regex_tuple_from_key_alias(obj) # handle objects without sdescs for obj in candidates if not (hasattr(obj, "recog") and hasattr(obj, "sdesc"))] # filter out non-found data candidate_regexes = [tup for tup in candidate_regexes if tup] # escape mapping syntax on the form {#id} if it exists already in emote, # if so it is replaced with just "id". string = _RE_REF.sub(r"\1", string) # escape loose { } brackets since this will clash with formatting string = _RE_LEFT_BRACKETS.sub("{{", string) string = _RE_RIGHT_BRACKETS.sub("}}", string) # we now loop over all references and analyze them mapping = {} errors = [] obj = None nmatches = 0 for marker_match in reversed(list(_RE_OBJ_REF_START.finditer(string))): # we scan backwards so we can replace in-situ without messing # up later occurrences. Given a marker match, query from # start index forward for all candidates. # first see if there is a number given (e.g. 1-tall) num_identifier, _ = marker_match.groups("") # return "" if no match, rather than None istart0 = marker_match.start() istart = istart0 # loop over all candidate regexes and match against the string following the match matches = ((reg.match(string[istart:]), obj, text) for reg, obj, text in candidate_regexes) # score matches by how long part of the string was matched matches = [(match.end() if match else -1, obj, text) for match, obj, text in matches] maxscore = max(score for score, obj, text in matches) # we have a valid maxscore, extract all matches with this value bestmatches = [(obj, text) for score, obj, text in matches if maxscore == score != -1] nmatches = len(bestmatches) if not nmatches: # no matches obj = None nmatches = 0 elif nmatches == 1: # an exact match. obj = bestmatches[0][0] nmatches = 1 elif all(bestmatches[0][0].id == obj.id for obj, text in bestmatches): # multi-match but all matches actually reference the same # obj (could happen with clashing recogs + sdescs) obj = bestmatches[0][0] nmatches = 1 else: # multi-match. # was a numerical identifier given to help us separate the multi-match? inum = min(max(0, int(num_identifier) - 1), nmatches - 1) if num_identifier else None if inum is not None: # A valid inum is given. Use this to separate data. obj = bestmatches[inum][0] nmatches = 1 else: # no identifier given - a real multimatch. obj = bestmatches if search_mode: # single-object search mode. Don't continue loop. break elif nmatches == 0: errors.append(_EMOTE_NOMATCH_ERROR.format(ref=marker_match.group())) elif nmatches == 1: key = "#%i" % obj.id string = string[:istart0] + "{%s}" % key + string[istart + maxscore:] mapping[key] = obj else: refname = marker_match.group() reflist = ["%s%s%s (%s%s)" % (inum + 1, _NUM_SEP, _RE_PREFIX.sub("", refname), text, " (%s)" % sender.key if sender == ob else "") for inum, (ob, text) in enumerate(obj)] errors.append(_EMOTE_MULTIMATCH_ERROR.format( ref=marker_match.group(), reflist="\n ".join(reflist))) if search_mode: # return list of object(s) matching if nmatches == 0: return [] elif nmatches == 1: return [obj] else: return [tup[0] for tup in obj] if errors: # make sure to not let errors through. raise EmoteError("\n".join(errors)) # at this point all references have been replaced with {#xxx} markers and the mapping contains # a 1:1 mapping between those inline markers and objects. return string, mapping
[ "def", "parse_sdescs_and_recogs", "(", "sender", ",", "candidates", ",", "string", ",", "search_mode", "=", "False", ")", ":", "# Load all candidate regex tuples [(regex, obj, sdesc/recog),...]", "candidate_regexes", "=", "(", "[", "(", "_RE_SELF_REF", ",", "sender", ",", "sender", ".", "sdesc", ".", "get", "(", ")", ")", "]", "if", "hasattr", "(", "sender", ",", "\"sdesc\"", ")", "else", "[", "]", ")", "+", "(", "[", "sender", ".", "recog", ".", "get_regex_tuple", "(", "obj", ")", "for", "obj", "in", "candidates", "]", "if", "hasattr", "(", "sender", ",", "\"recog\"", ")", "else", "[", "]", ")", "+", "[", "obj", ".", "sdesc", ".", "get_regex_tuple", "(", ")", "for", "obj", "in", "candidates", "if", "hasattr", "(", "obj", ",", "\"sdesc\"", ")", "]", "+", "[", "regex_tuple_from_key_alias", "(", "obj", ")", "# handle objects without sdescs", "for", "obj", "in", "candidates", "if", "not", "(", "hasattr", "(", "obj", ",", "\"recog\"", ")", "and", "hasattr", "(", "obj", ",", "\"sdesc\"", ")", ")", "]", "# filter out non-found data", "candidate_regexes", "=", "[", "tup", "for", "tup", "in", "candidate_regexes", "if", "tup", "]", "# escape mapping syntax on the form {#id} if it exists already in emote,", "# if so it is replaced with just \"id\".", "string", "=", "_RE_REF", ".", "sub", "(", "r\"\\1\"", ",", "string", ")", "# escape loose { } brackets since this will clash with formatting", "string", "=", "_RE_LEFT_BRACKETS", ".", "sub", "(", "\"{{\"", ",", "string", ")", "string", "=", "_RE_RIGHT_BRACKETS", ".", "sub", "(", "\"}}\"", ",", "string", ")", "# we now loop over all references and analyze them", "mapping", "=", "{", "}", "errors", "=", "[", "]", "obj", "=", "None", "nmatches", "=", "0", "for", "marker_match", "in", "reversed", "(", "list", "(", "_RE_OBJ_REF_START", ".", "finditer", "(", "string", ")", ")", ")", ":", "# we scan backwards so we can replace in-situ without messing", "# up later occurrences. Given a marker match, query from", "# start index forward for all candidates.", "# first see if there is a number given (e.g. 1-tall)", "num_identifier", ",", "_", "=", "marker_match", ".", "groups", "(", "\"\"", ")", "# return \"\" if no match, rather than None", "istart0", "=", "marker_match", ".", "start", "(", ")", "istart", "=", "istart0", "# loop over all candidate regexes and match against the string following the match", "matches", "=", "(", "(", "reg", ".", "match", "(", "string", "[", "istart", ":", "]", ")", ",", "obj", ",", "text", ")", "for", "reg", ",", "obj", ",", "text", "in", "candidate_regexes", ")", "# score matches by how long part of the string was matched", "matches", "=", "[", "(", "match", ".", "end", "(", ")", "if", "match", "else", "-", "1", ",", "obj", ",", "text", ")", "for", "match", ",", "obj", ",", "text", "in", "matches", "]", "maxscore", "=", "max", "(", "score", "for", "score", ",", "obj", ",", "text", "in", "matches", ")", "# we have a valid maxscore, extract all matches with this value", "bestmatches", "=", "[", "(", "obj", ",", "text", ")", "for", "score", ",", "obj", ",", "text", "in", "matches", "if", "maxscore", "==", "score", "!=", "-", "1", "]", "nmatches", "=", "len", "(", "bestmatches", ")", "if", "not", "nmatches", ":", "# no matches", "obj", "=", "None", "nmatches", "=", "0", "elif", "nmatches", "==", "1", ":", "# an exact match.", "obj", "=", "bestmatches", "[", "0", "]", "[", "0", "]", "nmatches", "=", "1", "elif", "all", "(", "bestmatches", "[", "0", "]", "[", "0", "]", ".", "id", "==", "obj", ".", "id", "for", "obj", ",", "text", "in", "bestmatches", ")", ":", "# multi-match but all matches actually reference the same", "# obj (could happen with clashing recogs + sdescs)", "obj", "=", "bestmatches", "[", "0", "]", "[", "0", "]", "nmatches", "=", "1", "else", ":", "# multi-match.", "# was a numerical identifier given to help us separate the multi-match?", "inum", "=", "min", "(", "max", "(", "0", ",", "int", "(", "num_identifier", ")", "-", "1", ")", ",", "nmatches", "-", "1", ")", "if", "num_identifier", "else", "None", "if", "inum", "is", "not", "None", ":", "# A valid inum is given. Use this to separate data.", "obj", "=", "bestmatches", "[", "inum", "]", "[", "0", "]", "nmatches", "=", "1", "else", ":", "# no identifier given - a real multimatch.", "obj", "=", "bestmatches", "if", "search_mode", ":", "# single-object search mode. Don't continue loop.", "break", "elif", "nmatches", "==", "0", ":", "errors", ".", "append", "(", "_EMOTE_NOMATCH_ERROR", ".", "format", "(", "ref", "=", "marker_match", ".", "group", "(", ")", ")", ")", "elif", "nmatches", "==", "1", ":", "key", "=", "\"#%i\"", "%", "obj", ".", "id", "string", "=", "string", "[", ":", "istart0", "]", "+", "\"{%s}\"", "%", "key", "+", "string", "[", "istart", "+", "maxscore", ":", "]", "mapping", "[", "key", "]", "=", "obj", "else", ":", "refname", "=", "marker_match", ".", "group", "(", ")", "reflist", "=", "[", "\"%s%s%s (%s%s)\"", "%", "(", "inum", "+", "1", ",", "_NUM_SEP", ",", "_RE_PREFIX", ".", "sub", "(", "\"\"", ",", "refname", ")", ",", "text", ",", "\" (%s)\"", "%", "sender", ".", "key", "if", "sender", "==", "ob", "else", "\"\"", ")", "for", "inum", ",", "(", "ob", ",", "text", ")", "in", "enumerate", "(", "obj", ")", "]", "errors", ".", "append", "(", "_EMOTE_MULTIMATCH_ERROR", ".", "format", "(", "ref", "=", "marker_match", ".", "group", "(", ")", ",", "reflist", "=", "\"\\n \"", ".", "join", "(", "reflist", ")", ")", ")", "if", "search_mode", ":", "# return list of object(s) matching", "if", "nmatches", "==", "0", ":", "return", "[", "]", "elif", "nmatches", "==", "1", ":", "return", "[", "obj", "]", "else", ":", "return", "[", "tup", "[", "0", "]", "for", "tup", "in", "obj", "]", "if", "errors", ":", "# make sure to not let errors through.", "raise", "EmoteError", "(", "\"\\n\"", ".", "join", "(", "errors", ")", ")", "# at this point all references have been replaced with {#xxx} markers and the mapping contains", "# a 1:1 mapping between those inline markers and objects.", "return", "string", ",", "mapping" ]
[ 324, 0 ]
[ 463, 26 ]
python
en
['en', 'error', 'th']
False
send_emote
(sender, receivers, emote, anonymous_add="first")
Main access function for distribute an emote. Args: sender (Object): The one sending the emote. receivers (iterable): Receivers of the emote. These will also form the basis for which sdescs are 'valid' to use in the emote. emote (str): The raw emote string as input by emoter. anonymous_add (str or None, optional): If `sender` is not self-referencing in the emote, this will auto-add `sender`'s data to the emote. Possible values are - None: No auto-add at anonymous emote - 'last': Add sender to the end of emote as [sender] - 'first': Prepend sender to start of emote.
Main access function for distribute an emote.
def send_emote(sender, receivers, emote, anonymous_add="first"): """ Main access function for distribute an emote. Args: sender (Object): The one sending the emote. receivers (iterable): Receivers of the emote. These will also form the basis for which sdescs are 'valid' to use in the emote. emote (str): The raw emote string as input by emoter. anonymous_add (str or None, optional): If `sender` is not self-referencing in the emote, this will auto-add `sender`'s data to the emote. Possible values are - None: No auto-add at anonymous emote - 'last': Add sender to the end of emote as [sender] - 'first': Prepend sender to start of emote. """ try: emote, obj_mapping = parse_sdescs_and_recogs(sender, receivers, emote) emote, language_mapping = parse_language(sender, emote) except (EmoteError, LanguageError) as err: # handle all error messages, don't hide actual coding errors sender.msg(err.message) return # we escape the object mappings since we'll do the language ones first # (the text could have nested object mappings). emote = _RE_REF.sub(r"{{#\1}}", emote) if anonymous_add and not "#%i" % sender.id in obj_mapping: # no self-reference in the emote - add to the end key = "#%i" % sender.id obj_mapping[key] = sender if anonymous_add == 'first': possessive = "" if emote.startswith('\'') else " " emote = "%s%s%s" % ("{{%s}}" % key, possessive, emote) else: emote = "%s [%s]" % (emote, "{{%s}}" % key) # broadcast emote to everyone for receiver in receivers: # first handle the language mapping, which always produce different keys ##nn receiver_lang_mapping = {} try: process_language = receiver.process_language except AttributeError: process_language = _dummy_process for key, (langname, saytext) in language_mapping.iteritems(): # color says receiver_lang_mapping[key] = process_language(saytext, sender, langname) # map the language {##num} markers. This will convert the escaped sdesc markers on # the form {{#num}} to {#num} markers ready to sdescmat in the next step. sendemote = emote.format(**receiver_lang_mapping) # handle sdesc mappings. we make a temporary copy that we can modify try: process_sdesc = receiver.process_sdesc except AttributeError: process_sdesc = _dummy_process try: process_recog = receiver.process_recog except AttributeError: process_recog = _dummy_process try: recog_get = receiver.recog.get receiver_sdesc_mapping = dict((ref, process_recog(recog_get(obj), obj)) for ref, obj in obj_mapping.items()) except AttributeError: receiver_sdesc_mapping = dict((ref, process_sdesc(obj.sdesc.get(), obj) if hasattr(obj, "sdesc") else process_sdesc(obj.key, obj)) for ref, obj in obj_mapping.items()) # make sure receiver always sees their real name rkey = "#%i" % receiver.id if rkey in receiver_sdesc_mapping: receiver_sdesc_mapping[rkey] = process_sdesc(receiver.key, receiver) # do the template replacement of the sdesc/recog {#num} markers receiver.msg(sendemote.format(**receiver_sdesc_mapping))
[ "def", "send_emote", "(", "sender", ",", "receivers", ",", "emote", ",", "anonymous_add", "=", "\"first\"", ")", ":", "try", ":", "emote", ",", "obj_mapping", "=", "parse_sdescs_and_recogs", "(", "sender", ",", "receivers", ",", "emote", ")", "emote", ",", "language_mapping", "=", "parse_language", "(", "sender", ",", "emote", ")", "except", "(", "EmoteError", ",", "LanguageError", ")", "as", "err", ":", "# handle all error messages, don't hide actual coding errors", "sender", ".", "msg", "(", "err", ".", "message", ")", "return", "# we escape the object mappings since we'll do the language ones first", "# (the text could have nested object mappings).", "emote", "=", "_RE_REF", ".", "sub", "(", "r\"{{#\\1}}\"", ",", "emote", ")", "if", "anonymous_add", "and", "not", "\"#%i\"", "%", "sender", ".", "id", "in", "obj_mapping", ":", "# no self-reference in the emote - add to the end", "key", "=", "\"#%i\"", "%", "sender", ".", "id", "obj_mapping", "[", "key", "]", "=", "sender", "if", "anonymous_add", "==", "'first'", ":", "possessive", "=", "\"\"", "if", "emote", ".", "startswith", "(", "'\\''", ")", "else", "\" \"", "emote", "=", "\"%s%s%s\"", "%", "(", "\"{{%s}}\"", "%", "key", ",", "possessive", ",", "emote", ")", "else", ":", "emote", "=", "\"%s [%s]\"", "%", "(", "emote", ",", "\"{{%s}}\"", "%", "key", ")", "# broadcast emote to everyone", "for", "receiver", "in", "receivers", ":", "# first handle the language mapping, which always produce different keys ##nn", "receiver_lang_mapping", "=", "{", "}", "try", ":", "process_language", "=", "receiver", ".", "process_language", "except", "AttributeError", ":", "process_language", "=", "_dummy_process", "for", "key", ",", "(", "langname", ",", "saytext", ")", "in", "language_mapping", ".", "iteritems", "(", ")", ":", "# color says", "receiver_lang_mapping", "[", "key", "]", "=", "process_language", "(", "saytext", ",", "sender", ",", "langname", ")", "# map the language {##num} markers. This will convert the escaped sdesc markers on", "# the form {{#num}} to {#num} markers ready to sdescmat in the next step.", "sendemote", "=", "emote", ".", "format", "(", "*", "*", "receiver_lang_mapping", ")", "# handle sdesc mappings. we make a temporary copy that we can modify", "try", ":", "process_sdesc", "=", "receiver", ".", "process_sdesc", "except", "AttributeError", ":", "process_sdesc", "=", "_dummy_process", "try", ":", "process_recog", "=", "receiver", ".", "process_recog", "except", "AttributeError", ":", "process_recog", "=", "_dummy_process", "try", ":", "recog_get", "=", "receiver", ".", "recog", ".", "get", "receiver_sdesc_mapping", "=", "dict", "(", "(", "ref", ",", "process_recog", "(", "recog_get", "(", "obj", ")", ",", "obj", ")", ")", "for", "ref", ",", "obj", "in", "obj_mapping", ".", "items", "(", ")", ")", "except", "AttributeError", ":", "receiver_sdesc_mapping", "=", "dict", "(", "(", "ref", ",", "process_sdesc", "(", "obj", ".", "sdesc", ".", "get", "(", ")", ",", "obj", ")", "if", "hasattr", "(", "obj", ",", "\"sdesc\"", ")", "else", "process_sdesc", "(", "obj", ".", "key", ",", "obj", ")", ")", "for", "ref", ",", "obj", "in", "obj_mapping", ".", "items", "(", ")", ")", "# make sure receiver always sees their real name", "rkey", "=", "\"#%i\"", "%", "receiver", ".", "id", "if", "rkey", "in", "receiver_sdesc_mapping", ":", "receiver_sdesc_mapping", "[", "rkey", "]", "=", "process_sdesc", "(", "receiver", ".", "key", ",", "receiver", ")", "# do the template replacement of the sdesc/recog {#num} markers", "receiver", ".", "msg", "(", "sendemote", ".", "format", "(", "*", "*", "receiver_sdesc_mapping", ")", ")" ]
[ 466, 0 ]
[ 544, 64 ]
python
en
['en', 'error', 'th']
False
SdescHandler.__init__
(self, obj)
Initialize the handler Args: obj (Object): The entity on which this handler is stored.
Initialize the handler
def __init__(self, obj): """ Initialize the handler Args: obj (Object): The entity on which this handler is stored. """ self.obj = obj self.sdesc = "" self.sdesc_regex = "" self._cache()
[ "def", "__init__", "(", "self", ",", "obj", ")", ":", "self", ".", "obj", "=", "obj", "self", ".", "sdesc", "=", "\"\"", "self", ".", "sdesc_regex", "=", "\"\"", "self", ".", "_cache", "(", ")" ]
[ 565, 4 ]
[ 576, 21 ]
python
en
['en', 'error', 'th']
False
SdescHandler._cache
(self)
Cache data from storage
Cache data from storage
def _cache(self): """ Cache data from storage """ self.sdesc = self.obj.attributes.get("_sdesc", default="") sdesc_regex = self.obj.attributes.get("_sdesc_regex", default="") self.sdesc_regex = re.compile(sdesc_regex, _RE_FLAGS)
[ "def", "_cache", "(", "self", ")", ":", "self", ".", "sdesc", "=", "self", ".", "obj", ".", "attributes", ".", "get", "(", "\"_sdesc\"", ",", "default", "=", "\"\"", ")", "sdesc_regex", "=", "self", ".", "obj", ".", "attributes", ".", "get", "(", "\"_sdesc_regex\"", ",", "default", "=", "\"\"", ")", "self", ".", "sdesc_regex", "=", "re", ".", "compile", "(", "sdesc_regex", ",", "_RE_FLAGS", ")" ]
[ 578, 4 ]
[ 585, 61 ]
python
en
['en', 'error', 'th']
False
SdescHandler.add
(self, sdesc, max_length=60)
Add a new sdesc to object, replacing the old one. Args: sdesc (str): The sdesc to set. This may be stripped of control sequences before setting. max_length (int, optional): The max limit of the sdesc. Returns: sdesc (str): The actually set sdesc. Raises: SdescError: If the sdesc is empty, can not be set or is longer than `max_length`.
Add a new sdesc to object, replacing the old one.
def add(self, sdesc, max_length=60): """ Add a new sdesc to object, replacing the old one. Args: sdesc (str): The sdesc to set. This may be stripped of control sequences before setting. max_length (int, optional): The max limit of the sdesc. Returns: sdesc (str): The actually set sdesc. Raises: SdescError: If the sdesc is empty, can not be set or is longer than `max_length`. """ # strip emote components from sdesc sdesc = _RE_REF.sub(r"\1", _RE_REF_LANG.sub(r"\1", _RE_SELF_REF.sub(r"", _RE_LANGUAGE.sub(r"", _RE_OBJ_REF_START.sub(r"", sdesc))))) # make an sdesc clean of ANSI codes cleaned_sdesc = ansi.strip_ansi(sdesc) if not cleaned_sdesc: raise SdescError("Short desc cannot be empty.") if len(cleaned_sdesc) > max_length: raise SdescError("Short desc can max be %i chars long (was %i chars)." % (max_length, len(cleaned_sdesc))) # store to attributes sdesc_regex = ordered_permutation_regex(cleaned_sdesc) self.obj.attributes.add("_sdesc", sdesc) self.obj.attributes.add("_sdesc_regex", sdesc_regex) # local caching self.sdesc = sdesc self.sdesc_regex = re.compile(sdesc_regex, _RE_FLAGS) return sdesc
[ "def", "add", "(", "self", ",", "sdesc", ",", "max_length", "=", "60", ")", ":", "# strip emote components from sdesc", "sdesc", "=", "_RE_REF", ".", "sub", "(", "r\"\\1\"", ",", "_RE_REF_LANG", ".", "sub", "(", "r\"\\1\"", ",", "_RE_SELF_REF", ".", "sub", "(", "r\"\"", ",", "_RE_LANGUAGE", ".", "sub", "(", "r\"\"", ",", "_RE_OBJ_REF_START", ".", "sub", "(", "r\"\"", ",", "sdesc", ")", ")", ")", ")", ")", "# make an sdesc clean of ANSI codes", "cleaned_sdesc", "=", "ansi", ".", "strip_ansi", "(", "sdesc", ")", "if", "not", "cleaned_sdesc", ":", "raise", "SdescError", "(", "\"Short desc cannot be empty.\"", ")", "if", "len", "(", "cleaned_sdesc", ")", ">", "max_length", ":", "raise", "SdescError", "(", "\"Short desc can max be %i chars long (was %i chars).\"", "%", "(", "max_length", ",", "len", "(", "cleaned_sdesc", ")", ")", ")", "# store to attributes", "sdesc_regex", "=", "ordered_permutation_regex", "(", "cleaned_sdesc", ")", "self", ".", "obj", ".", "attributes", ".", "add", "(", "\"_sdesc\"", ",", "sdesc", ")", "self", ".", "obj", ".", "attributes", ".", "add", "(", "\"_sdesc_regex\"", ",", "sdesc_regex", ")", "# local caching", "self", ".", "sdesc", "=", "sdesc", "self", ".", "sdesc_regex", "=", "re", ".", "compile", "(", "sdesc_regex", ",", "_RE_FLAGS", ")", "return", "sdesc" ]
[ 587, 4 ]
[ 628, 20 ]
python
en
['en', 'error', 'th']
False
SdescHandler.get
(self)
Simple getter. The sdesc should never be allowed to be empty, but if it is we must fall back to the key.
Simple getter. The sdesc should never be allowed to be empty, but if it is we must fall back to the key.
def get(self): """ Simple getter. The sdesc should never be allowed to be empty, but if it is we must fall back to the key. """ return self.sdesc or self.obj.key
[ "def", "get", "(", "self", ")", ":", "return", "self", ".", "sdesc", "or", "self", ".", "obj", ".", "key" ]
[ 630, 4 ]
[ 636, 41 ]
python
en
['en', 'error', 'th']
False
SdescHandler.get_regex_tuple
(self)
Return data for sdesc/recog handling Returns: tup (tuple): tuple (sdesc_regex, obj, sdesc)
Return data for sdesc/recog handling
def get_regex_tuple(self): """ Return data for sdesc/recog handling Returns: tup (tuple): tuple (sdesc_regex, obj, sdesc) """ return self.sdesc_regex, self.obj, self.sdesc
[ "def", "get_regex_tuple", "(", "self", ")", ":", "return", "self", ".", "sdesc_regex", ",", "self", ".", "obj", ",", "self", ".", "sdesc" ]
[ 638, 4 ]
[ 646, 53 ]
python
en
['en', 'error', 'th']
False
RecogHandler.__init__
(self, obj)
Initialize the handler Args: obj (Object): The entity on which this handler is stored.
Initialize the handler
def __init__(self, obj): """ Initialize the handler Args: obj (Object): The entity on which this handler is stored. """ self.obj = obj # mappings self.ref2recog = {} self.obj2regex = {} self.obj2recog = {} self._cache()
[ "def", "__init__", "(", "self", ",", "obj", ")", ":", "self", ".", "obj", "=", "obj", "# mappings", "self", ".", "ref2recog", "=", "{", "}", "self", ".", "obj2regex", "=", "{", "}", "self", ".", "obj2recog", "=", "{", "}", "self", ".", "_cache", "(", ")" ]
[ 663, 4 ]
[ 676, 21 ]
python
en
['en', 'error', 'th']
False
RecogHandler._cache
(self)
Load data to handler cache
Load data to handler cache
def _cache(self): """ Load data to handler cache """ self.ref2recog = self.obj.attributes.get("_recog_ref2recog", default={}) obj2regex = self.obj.attributes.get("_recog_obj2regex", default={}) obj2recog = self.obj.attributes.get("_recog_obj2recog", default={}) self.obj2regex = dict((obj, re.compile(regex, _RE_FLAGS)) for obj, regex in obj2regex.items() if obj) self.obj2recog = dict((obj, recog) for obj, recog in obj2recog.items() if obj)
[ "def", "_cache", "(", "self", ")", ":", "self", ".", "ref2recog", "=", "self", ".", "obj", ".", "attributes", ".", "get", "(", "\"_recog_ref2recog\"", ",", "default", "=", "{", "}", ")", "obj2regex", "=", "self", ".", "obj", ".", "attributes", ".", "get", "(", "\"_recog_obj2regex\"", ",", "default", "=", "{", "}", ")", "obj2recog", "=", "self", ".", "obj", ".", "attributes", ".", "get", "(", "\"_recog_obj2recog\"", ",", "default", "=", "{", "}", ")", "self", ".", "obj2regex", "=", "dict", "(", "(", "obj", ",", "re", ".", "compile", "(", "regex", ",", "_RE_FLAGS", ")", ")", "for", "obj", ",", "regex", "in", "obj2regex", ".", "items", "(", ")", "if", "obj", ")", "self", ".", "obj2recog", "=", "dict", "(", "(", "obj", ",", "recog", ")", "for", "obj", ",", "recog", "in", "obj2recog", ".", "items", "(", ")", "if", "obj", ")" ]
[ 678, 4 ]
[ 688, 73 ]
python
en
['en', 'error', 'th']
False
RecogHandler.add
(self, obj, recog, max_length=60)
Assign a custom recog (nick) to the given object. Args: obj (Object): The object ot associate with the recog string. This is usually determined from the sdesc in the room by a call to parse_sdescs_and_recogs, but can also be given. recog (str): The replacement string to use with this object. max_length (int, optional): The max length of the recog string. Returns: recog (str): The (possibly cleaned up) recog string actually set. Raises: SdescError: When recog could not be set or sdesc longer than `max_length`.
Assign a custom recog (nick) to the given object.
def add(self, obj, recog, max_length=60): """ Assign a custom recog (nick) to the given object. Args: obj (Object): The object ot associate with the recog string. This is usually determined from the sdesc in the room by a call to parse_sdescs_and_recogs, but can also be given. recog (str): The replacement string to use with this object. max_length (int, optional): The max length of the recog string. Returns: recog (str): The (possibly cleaned up) recog string actually set. Raises: SdescError: When recog could not be set or sdesc longer than `max_length`. """ if not obj.access(self.obj, "enable_recog", default=True): raise SdescError("This person is unrecognizeable.") # strip emote components from recog recog = _RE_REF.sub( r"\1", _RE_REF_LANG.sub( r"\1", _RE_SELF_REF.sub( r"", _RE_LANGUAGE.sub( r"", _RE_OBJ_REF_START.sub(r"", recog))))) # make an recog clean of ANSI codes cleaned_recog = ansi.strip_ansi(recog) if not cleaned_recog: raise SdescError("Recog string cannot be empty.") if len(cleaned_recog) > max_length: raise RecogError("Recog string cannot be longer than %i chars (was %i chars)" % (max_length, len(cleaned_recog))) # mapping #dbref:obj key = "#%i" % obj.id self.obj.attributes.get("_recog_ref2recog", default={})[key] = recog self.obj.attributes.get("_recog_obj2recog", default={})[obj] = recog regex = ordered_permutation_regex(cleaned_recog) self.obj.attributes.get("_recog_obj2regex", default={})[obj] = regex # local caching self.ref2recog[key] = recog self.obj2recog[obj] = recog self.obj2regex[obj] = re.compile(regex, _RE_FLAGS) return recog
[ "def", "add", "(", "self", ",", "obj", ",", "recog", ",", "max_length", "=", "60", ")", ":", "if", "not", "obj", ".", "access", "(", "self", ".", "obj", ",", "\"enable_recog\"", ",", "default", "=", "True", ")", ":", "raise", "SdescError", "(", "\"This person is unrecognizeable.\"", ")", "# strip emote components from recog", "recog", "=", "_RE_REF", ".", "sub", "(", "r\"\\1\"", ",", "_RE_REF_LANG", ".", "sub", "(", "r\"\\1\"", ",", "_RE_SELF_REF", ".", "sub", "(", "r\"\"", ",", "_RE_LANGUAGE", ".", "sub", "(", "r\"\"", ",", "_RE_OBJ_REF_START", ".", "sub", "(", "r\"\"", ",", "recog", ")", ")", ")", ")", ")", "# make an recog clean of ANSI codes", "cleaned_recog", "=", "ansi", ".", "strip_ansi", "(", "recog", ")", "if", "not", "cleaned_recog", ":", "raise", "SdescError", "(", "\"Recog string cannot be empty.\"", ")", "if", "len", "(", "cleaned_recog", ")", ">", "max_length", ":", "raise", "RecogError", "(", "\"Recog string cannot be longer than %i chars (was %i chars)\"", "%", "(", "max_length", ",", "len", "(", "cleaned_recog", ")", ")", ")", "# mapping #dbref:obj", "key", "=", "\"#%i\"", "%", "obj", ".", "id", "self", ".", "obj", ".", "attributes", ".", "get", "(", "\"_recog_ref2recog\"", ",", "default", "=", "{", "}", ")", "[", "key", "]", "=", "recog", "self", ".", "obj", ".", "attributes", ".", "get", "(", "\"_recog_obj2recog\"", ",", "default", "=", "{", "}", ")", "[", "obj", "]", "=", "recog", "regex", "=", "ordered_permutation_regex", "(", "cleaned_recog", ")", "self", ".", "obj", ".", "attributes", ".", "get", "(", "\"_recog_obj2regex\"", ",", "default", "=", "{", "}", ")", "[", "obj", "]", "=", "regex", "# local caching", "self", ".", "ref2recog", "[", "key", "]", "=", "recog", "self", ".", "obj2recog", "[", "obj", "]", "=", "recog", "self", ".", "obj2regex", "[", "obj", "]", "=", "re", ".", "compile", "(", "regex", ",", "_RE_FLAGS", ")", "return", "recog" ]
[ 690, 4 ]
[ 739, 20 ]
python
en
['en', 'error', 'th']
False
RecogHandler.get
(self, obj)
Get recog replacement string, if one exists, otherwise get sdesc and as a last resort, the object's key. Args: obj (Object): The object, whose sdesc to replace Returns: recog (str): The replacement string to use. Notes: This method will respect a "enable_recog" lock set on `obj` (True by default) in order to turn off recog mechanism. This is useful for adding masks/hoods etc.
Get recog replacement string, if one exists, otherwise get sdesc and as a last resort, the object's key.
def get(self, obj): """ Get recog replacement string, if one exists, otherwise get sdesc and as a last resort, the object's key. Args: obj (Object): The object, whose sdesc to replace Returns: recog (str): The replacement string to use. Notes: This method will respect a "enable_recog" lock set on `obj` (True by default) in order to turn off recog mechanism. This is useful for adding masks/hoods etc. """ if obj.access(self.obj, "enable_recog", default=True): # check an eventual recog_masked lock on the object # to avoid revealing masked characters. If lock # does not exist, pass automatically. return self.obj2recog.get(obj, obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key) else: # recog_mask log not passed, disable recog return obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key
[ "def", "get", "(", "self", ",", "obj", ")", ":", "if", "obj", ".", "access", "(", "self", ".", "obj", ",", "\"enable_recog\"", ",", "default", "=", "True", ")", ":", "# check an eventual recog_masked lock on the object", "# to avoid revealing masked characters. If lock", "# does not exist, pass automatically.", "return", "self", ".", "obj2recog", ".", "get", "(", "obj", ",", "obj", ".", "sdesc", ".", "get", "(", ")", "if", "hasattr", "(", "obj", ",", "\"sdesc\"", ")", "else", "obj", ".", "key", ")", "else", ":", "# recog_mask log not passed, disable recog", "return", "obj", ".", "sdesc", ".", "get", "(", ")", "if", "hasattr", "(", "obj", ",", "\"sdesc\"", ")", "else", "obj", ".", "key" ]
[ 741, 4 ]
[ 764, 72 ]
python
en
['en', 'error', 'th']
False
RecogHandler.remove
(self, obj)
Clear recog for a given object. Args: obj (Object): The object for which to remove recog.
Clear recog for a given object.
def remove(self, obj): """ Clear recog for a given object. Args: obj (Object): The object for which to remove recog. """ if obj in self.obj2recog: del self.obj.db._recog_obj2recog[obj] del self.obj.db._recog_obj2regex[obj] del self.obj.db._recog_ref2recog["#%i" % obj.id] self._cache()
[ "def", "remove", "(", "self", ",", "obj", ")", ":", "if", "obj", "in", "self", ".", "obj2recog", ":", "del", "self", ".", "obj", ".", "db", ".", "_recog_obj2recog", "[", "obj", "]", "del", "self", ".", "obj", ".", "db", ".", "_recog_obj2regex", "[", "obj", "]", "del", "self", ".", "obj", ".", "db", ".", "_recog_ref2recog", "[", "\"#%i\"", "%", "obj", ".", "id", "]", "self", ".", "_cache", "(", ")" ]
[ 766, 4 ]
[ 777, 21 ]
python
en
['en', 'error', 'th']
False
RecogHandler.get_regex_tuple
(self, obj)
Returns: rec (tuple): Tuple (recog_regex, obj, recog)
Returns: rec (tuple): Tuple (recog_regex, obj, recog)
def get_regex_tuple(self, obj): """ Returns: rec (tuple): Tuple (recog_regex, obj, recog) """ if obj in self.obj2recog and obj.access(self.obj, "enable_recog", default=True): return self.obj2regex[obj], obj, self.obj2regex[obj] return None
[ "def", "get_regex_tuple", "(", "self", ",", "obj", ")", ":", "if", "obj", "in", "self", ".", "obj2recog", "and", "obj", ".", "access", "(", "self", ".", "obj", ",", "\"enable_recog\"", ",", "default", "=", "True", ")", ":", "return", "self", ".", "obj2regex", "[", "obj", "]", ",", "obj", ",", "self", ".", "obj2regex", "[", "obj", "]", "return", "None" ]
[ 779, 4 ]
[ 786, 19 ]
python
en
['en', 'error', 'th']
False
RPCommand.parse
(self)
strip extra whitespace
strip extra whitespace
def parse(self): "strip extra whitespace" self.args = self.args.strip()
[ "def", "parse", "(", "self", ")", ":", "self", ".", "args", "=", "self", ".", "args", ".", "strip", "(", ")" ]
[ 796, 4 ]
[ 798, 37 ]
python
en
['en', 'el-Latn', 'en']
True
CmdEmote.func
(self)
Perform the emote.
Perform the emote.
def func(self): "Perform the emote." if not self.args: self.caller.msg("What do you want to do?") else: # we also include ourselves here. emote = self.args targets = self.caller.location.contents if not emote.endswith((".", "?", "!")): # If emote is not punctuated, emote = "%s." % emote # add a full-stop for good measure. send_emote(self.caller, targets, emote, anonymous_add='first')
[ "def", "func", "(", "self", ")", ":", "if", "not", "self", ".", "args", ":", "self", ".", "caller", ".", "msg", "(", "\"What do you want to do?\"", ")", "else", ":", "# we also include ourselves here.", "emote", "=", "self", ".", "args", "targets", "=", "self", ".", "caller", ".", "location", ".", "contents", "if", "not", "emote", ".", "endswith", "(", "(", "\".\"", ",", "\"?\"", ",", "\"!\"", ")", ")", ":", "# If emote is not punctuated,", "emote", "=", "\"%s.\"", "%", "emote", "# add a full-stop for good measure.", "send_emote", "(", "self", ".", "caller", ",", "targets", ",", "emote", ",", "anonymous_add", "=", "'first'", ")" ]
[ 826, 4 ]
[ 836, 74 ]
python
en
['en', 'en', 'en']
True
CmdSay.func
(self)
Run the say command
Run the say command
def func(self): "Run the say command" caller = self.caller if not self.args: caller.msg("Say what?") return # calling the speech hook on the location speech = caller.location.at_before_say(self.args) # preparing the speech with sdesc/speech parsing. speech = "/me says, \"{speech}\"".format(speech=speech) targets = self.caller.location.contents send_emote(self.caller, targets, speech, anonymous_add=None)
[ "def", "func", "(", "self", ")", ":", "caller", "=", "self", ".", "caller", "if", "not", "self", ".", "args", ":", "caller", ".", "msg", "(", "\"Say what?\"", ")", "return", "# calling the speech hook on the location", "speech", "=", "caller", ".", "location", ".", "at_before_say", "(", "self", ".", "args", ")", "# preparing the speech with sdesc/speech parsing.", "speech", "=", "\"/me says, \\\"{speech}\\\"\"", ".", "format", "(", "speech", "=", "speech", ")", "targets", "=", "self", ".", "caller", ".", "location", ".", "contents", "send_emote", "(", "self", ".", "caller", ",", "targets", ",", "speech", ",", "anonymous_add", "=", "None", ")" ]
[ 853, 4 ]
[ 867, 68 ]
python
en
['en', 'en', 'en']
True
CmdSdesc.func
(self)
Assign the sdesc
Assign the sdesc
def func(self): "Assign the sdesc" caller = self.caller if not self.args: caller.msg("Usage: sdesc <sdesc-text>") return else: # strip non-alfanum chars from end of sdesc sdesc = _RE_CHAREND.sub("", self.args) try: sdesc = caller.sdesc.add(sdesc) except SdescError as err: caller.msg(err) return caller.msg("%s's sdesc was set to '%s'." % (caller.key, sdesc))
[ "def", "func", "(", "self", ")", ":", "caller", "=", "self", ".", "caller", "if", "not", "self", ".", "args", ":", "caller", ".", "msg", "(", "\"Usage: sdesc <sdesc-text>\"", ")", "return", "else", ":", "# strip non-alfanum chars from end of sdesc", "sdesc", "=", "_RE_CHAREND", ".", "sub", "(", "\"\"", ",", "self", ".", "args", ")", "try", ":", "sdesc", "=", "caller", ".", "sdesc", ".", "add", "(", "sdesc", ")", "except", "SdescError", "as", "err", ":", "caller", ".", "msg", "(", "err", ")", "return", "caller", ".", "msg", "(", "\"%s's sdesc was set to '%s'.\"", "%", "(", "caller", ".", "key", ",", "sdesc", ")", ")" ]
[ 883, 4 ]
[ 897, 75 ]
python
en
['en', 'pt', 'en']
True
CmdPose.parse
(self)
Extract the "default" alternative to the pose.
Extract the "default" alternative to the pose.
def parse(self): """ Extract the "default" alternative to the pose. """ args = self.args.strip() default = args.startswith("default") reset = args.startswith("reset") if default: args = re.sub(r"^default", "", args) if reset: args = re.sub(r"^reset", "", args) target = None if "=" in args: target, args = [part.strip() for part in args.split("=", 1)] self.target = target self.reset = reset self.default = default self.args = args.strip()
[ "def", "parse", "(", "self", ")", ":", "args", "=", "self", ".", "args", ".", "strip", "(", ")", "default", "=", "args", ".", "startswith", "(", "\"default\"", ")", "reset", "=", "args", ".", "startswith", "(", "\"reset\"", ")", "if", "default", ":", "args", "=", "re", ".", "sub", "(", "r\"^default\"", ",", "\"\"", ",", "args", ")", "if", "reset", ":", "args", "=", "re", ".", "sub", "(", "r\"^reset\"", ",", "\"\"", ",", "args", ")", "target", "=", "None", "if", "\"=\"", "in", "args", ":", "target", ",", "args", "=", "[", "part", ".", "strip", "(", ")", "for", "part", "in", "args", ".", "split", "(", "\"=\"", ",", "1", ")", "]", "self", ".", "target", "=", "target", "self", ".", "reset", "=", "reset", "self", ".", "default", "=", "default", "self", ".", "args", "=", "args", ".", "strip", "(", ")" ]
[ 927, 4 ]
[ 945, 32 ]
python
en
['en', 'error', 'th']
False
CmdPose.func
(self)
Create the pose
Create the pose
def func(self): "Create the pose" caller = self.caller pose = self.args target = self.target if not pose and not self.reset: caller.msg("Usage: pose <pose-text> OR pose obj = <pose-text>") return if not pose.endswith("."): pose = "%s." % pose if target: # affect something else target = caller.search(target) if not target: return if not target.access(caller, "edit"): caller.msg("You can't pose that.") return else: target = caller if not target.attributes.has("pose"): caller.msg("%s cannot be posed." % target.key) return target_name = target.sdesc.get() if hasattr(target, "sdesc") else target.key # set the pose if self.reset: pose = target.db.pose_default target.db.pose = pose elif self.default: target.db.pose_default = pose caller.msg("Default pose is now '%s %s'." % (target_name, pose)) return else: # set the pose. We do one-time ref->sdesc mapping here. parsed, mapping = parse_sdescs_and_recogs(caller, caller.location.contents, pose) mapping = dict((ref, obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key) for ref, obj in mapping.iteritems()) pose = parsed.format(**mapping) if len(target_name) + len(pose) > 60: caller.msg("Your pose '%s' is too long." % pose) return target.db.pose = pose caller.msg("Pose will read '%s %s'." % (target_name, pose))
[ "def", "func", "(", "self", ")", ":", "caller", "=", "self", ".", "caller", "pose", "=", "self", ".", "args", "target", "=", "self", ".", "target", "if", "not", "pose", "and", "not", "self", ".", "reset", ":", "caller", ".", "msg", "(", "\"Usage: pose <pose-text> OR pose obj = <pose-text>\"", ")", "return", "if", "not", "pose", ".", "endswith", "(", "\".\"", ")", ":", "pose", "=", "\"%s.\"", "%", "pose", "if", "target", ":", "# affect something else", "target", "=", "caller", ".", "search", "(", "target", ")", "if", "not", "target", ":", "return", "if", "not", "target", ".", "access", "(", "caller", ",", "\"edit\"", ")", ":", "caller", ".", "msg", "(", "\"You can't pose that.\"", ")", "return", "else", ":", "target", "=", "caller", "if", "not", "target", ".", "attributes", ".", "has", "(", "\"pose\"", ")", ":", "caller", ".", "msg", "(", "\"%s cannot be posed.\"", "%", "target", ".", "key", ")", "return", "target_name", "=", "target", ".", "sdesc", ".", "get", "(", ")", "if", "hasattr", "(", "target", ",", "\"sdesc\"", ")", "else", "target", ".", "key", "# set the pose", "if", "self", ".", "reset", ":", "pose", "=", "target", ".", "db", ".", "pose_default", "target", ".", "db", ".", "pose", "=", "pose", "elif", "self", ".", "default", ":", "target", ".", "db", ".", "pose_default", "=", "pose", "caller", ".", "msg", "(", "\"Default pose is now '%s %s'.\"", "%", "(", "target_name", ",", "pose", ")", ")", "return", "else", ":", "# set the pose. We do one-time ref->sdesc mapping here.", "parsed", ",", "mapping", "=", "parse_sdescs_and_recogs", "(", "caller", ",", "caller", ".", "location", ".", "contents", ",", "pose", ")", "mapping", "=", "dict", "(", "(", "ref", ",", "obj", ".", "sdesc", ".", "get", "(", ")", "if", "hasattr", "(", "obj", ",", "\"sdesc\"", ")", "else", "obj", ".", "key", ")", "for", "ref", ",", "obj", "in", "mapping", ".", "iteritems", "(", ")", ")", "pose", "=", "parsed", ".", "format", "(", "*", "*", "mapping", ")", "if", "len", "(", "target_name", ")", "+", "len", "(", "pose", ")", ">", "60", ":", "caller", ".", "msg", "(", "\"Your pose '%s' is too long.\"", "%", "pose", ")", "return", "target", ".", "db", ".", "pose", "=", "pose", "caller", ".", "msg", "(", "\"Pose will read '%s %s'.\"", "%", "(", "target_name", ",", "pose", ")", ")" ]
[ 947, 4 ]
[ 995, 67 ]
python
en
['en', 'sm', 'en']
True
CmdRecog.parse
(self)
Parse for the sdesc as alias structure
Parse for the sdesc as alias structure
def parse(self): "Parse for the sdesc as alias structure" if " as " in self.args: self.sdesc, self.alias = [part.strip() for part in self.args.split(" as ", 2)] elif self.args: # try to split by space instead try: self.sdesc, self.alias = [part.strip() for part in self.args.split(None, 1)] except ValueError: self.sdesc, self.alias = self.args.strip(), ""
[ "def", "parse", "(", "self", ")", ":", "if", "\" as \"", "in", "self", ".", "args", ":", "self", ".", "sdesc", ",", "self", ".", "alias", "=", "[", "part", ".", "strip", "(", ")", "for", "part", "in", "self", ".", "args", ".", "split", "(", "\" as \"", ",", "2", ")", "]", "elif", "self", ".", "args", ":", "# try to split by space instead", "try", ":", "self", ".", "sdesc", ",", "self", ".", "alias", "=", "[", "part", ".", "strip", "(", ")", "for", "part", "in", "self", ".", "args", ".", "split", "(", "None", ",", "1", ")", "]", "except", "ValueError", ":", "self", ".", "sdesc", ",", "self", ".", "alias", "=", "self", ".", "args", ".", "strip", "(", ")", ",", "\"\"" ]
[ 1017, 4 ]
[ 1026, 62 ]
python
en
['en', 'en', 'en']
True
CmdRecog.func
(self)
Assign the recog
Assign the recog
def func(self): "Assign the recog" caller = self.caller if not self.args: caller.msg("Usage: recog <sdesc> as <alias> or forget <alias>") return sdesc = self.sdesc alias = self.alias.rstrip(".?!") prefixed_sdesc = sdesc if sdesc.startswith(_PREFIX) else _PREFIX + sdesc candidates = caller.location.contents matches = parse_sdescs_and_recogs(caller, candidates, prefixed_sdesc, search_mode=True) nmatches = len(matches) # handle 0, 1 and >1 matches if nmatches == 0: caller.msg(_EMOTE_NOMATCH_ERROR.format(ref=sdesc)) elif nmatches > 1: reflist = ["%s%s%s (%s%s)" % (inum + 1, _NUM_SEP, _RE_PREFIX.sub("", sdesc), caller.recog.get(obj), " (%s)" % caller.key if caller == obj else "") for inum, obj in enumerate(matches)] caller.msg(_EMOTE_MULTIMATCH_ERROR.format(ref=sdesc, reflist="\n ".join(reflist))) else: obj = matches[0] if not obj.access(self.obj, "enable_recog", default=True): # don't apply recog if object doesn't allow it (e.g. by being masked). caller.msg("Can't recognize someone who is masked.") return if self.cmdstring == "forget": # remove existing recog caller.recog.remove(obj) caller.msg("%s will now know only '%s'." % (caller.key, obj.recog.get(obj))) else: sdesc = obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key try: alias = caller.recog.add(obj, alias) except RecogError as err: caller.msg(err) return caller.msg("%s will now remember |w%s|n as |w%s|n." % (caller.key, sdesc, alias))
[ "def", "func", "(", "self", ")", ":", "caller", "=", "self", ".", "caller", "if", "not", "self", ".", "args", ":", "caller", ".", "msg", "(", "\"Usage: recog <sdesc> as <alias> or forget <alias>\"", ")", "return", "sdesc", "=", "self", ".", "sdesc", "alias", "=", "self", ".", "alias", ".", "rstrip", "(", "\".?!\"", ")", "prefixed_sdesc", "=", "sdesc", "if", "sdesc", ".", "startswith", "(", "_PREFIX", ")", "else", "_PREFIX", "+", "sdesc", "candidates", "=", "caller", ".", "location", ".", "contents", "matches", "=", "parse_sdescs_and_recogs", "(", "caller", ",", "candidates", ",", "prefixed_sdesc", ",", "search_mode", "=", "True", ")", "nmatches", "=", "len", "(", "matches", ")", "# handle 0, 1 and >1 matches", "if", "nmatches", "==", "0", ":", "caller", ".", "msg", "(", "_EMOTE_NOMATCH_ERROR", ".", "format", "(", "ref", "=", "sdesc", ")", ")", "elif", "nmatches", ">", "1", ":", "reflist", "=", "[", "\"%s%s%s (%s%s)\"", "%", "(", "inum", "+", "1", ",", "_NUM_SEP", ",", "_RE_PREFIX", ".", "sub", "(", "\"\"", ",", "sdesc", ")", ",", "caller", ".", "recog", ".", "get", "(", "obj", ")", ",", "\" (%s)\"", "%", "caller", ".", "key", "if", "caller", "==", "obj", "else", "\"\"", ")", "for", "inum", ",", "obj", "in", "enumerate", "(", "matches", ")", "]", "caller", ".", "msg", "(", "_EMOTE_MULTIMATCH_ERROR", ".", "format", "(", "ref", "=", "sdesc", ",", "reflist", "=", "\"\\n \"", ".", "join", "(", "reflist", ")", ")", ")", "else", ":", "obj", "=", "matches", "[", "0", "]", "if", "not", "obj", ".", "access", "(", "self", ".", "obj", ",", "\"enable_recog\"", ",", "default", "=", "True", ")", ":", "# don't apply recog if object doesn't allow it (e.g. by being masked).", "caller", ".", "msg", "(", "\"Can't recognize someone who is masked.\"", ")", "return", "if", "self", ".", "cmdstring", "==", "\"forget\"", ":", "# remove existing recog", "caller", ".", "recog", ".", "remove", "(", "obj", ")", "caller", ".", "msg", "(", "\"%s will now know only '%s'.\"", "%", "(", "caller", ".", "key", ",", "obj", ".", "recog", ".", "get", "(", "obj", ")", ")", ")", "else", ":", "sdesc", "=", "obj", ".", "sdesc", ".", "get", "(", ")", "if", "hasattr", "(", "obj", ",", "\"sdesc\"", ")", "else", "obj", ".", "key", "try", ":", "alias", "=", "caller", ".", "recog", ".", "add", "(", "obj", ",", "alias", ")", "except", "RecogError", "as", "err", ":", "caller", ".", "msg", "(", "err", ")", "return", "caller", ".", "msg", "(", "\"%s will now remember |w%s|n as |w%s|n.\"", "%", "(", "caller", ".", "key", ",", "sdesc", ",", "alias", ")", ")" ]
[ 1028, 4 ]
[ 1066, 97 ]
python
en
['en', 'en', 'en']
True
ContribRPObject.at_object_creation
(self)
Called at initial creation.
Called at initial creation.
def at_object_creation(self): """ Called at initial creation. """ super(ContribRPObject, self).at_object_creation # emoting/recog data self.db.pose = "" self.db.pose_default = "is here."
[ "def", "at_object_creation", "(", "self", ")", ":", "super", "(", "ContribRPObject", ",", "self", ")", ".", "at_object_creation", "# emoting/recog data", "self", ".", "db", ".", "pose", "=", "\"\"", "self", ".", "db", ".", "pose_default", "=", "\"is here.\"" ]
[ 1140, 4 ]
[ 1148, 41 ]
python
en
['en', 'error', 'th']
False
ContribRPObject.search
(self, searchdata, global_search=False, use_nicks=True, typeclass=None, location=None, attribute_name=None, quiet=False, exact=False, candidates=None, nofound_string=None, multimatch_string=None, use_dbref=None)
Returns an Object matching a search string/condition, taking sdescs into account. Perform a standard object search in the database, handling multiple results and lack thereof gracefully. By default, only objects in the current `location` of `self` or its inventory are searched for. Args: searchdata (str or obj): Primary search criterion. Will be matched against `object.key` (with `object.aliases` second) unless the keyword attribute_name specifies otherwise. **Special strings:** - `#<num>`: search by unique dbref. This is always a global search. - `me,self`: self-reference to this object - `<num>-<string>` - can be used to differentiate between multiple same-named matches global_search (bool): Search all objects globally. This is overruled by `location` keyword. use_nicks (bool): Use nickname-replace (nicktype "object") on `searchdata`. typeclass (str or Typeclass, or list of either): Limit search only to `Objects` with this typeclass. May be a list of typeclasses for a broader search. location (Object or list): Specify a location or multiple locations to search. Note that this is used to query the *contents* of a location and will not match for the location itself - if you want that, don't set this or use `candidates` to specify exactly which objects should be searched. attribute_name (str): Define which property to search. If set, no key+alias search will be performed. This can be used to search database fields (db_ will be automatically appended), and if that fails, it will try to return objects having Attributes with this name and value equal to searchdata. A special use is to search for "key" here if you want to do a key-search without including aliases. quiet (bool): don't display default error messages - this tells the search method that the user wants to handle all errors themselves. It also changes the return value type, see below. exact (bool): if unset (default) - prefers to match to beginning of string rather than not matching at all. If set, requires exact matching of entire string. candidates (list of objects): this is an optional custom list of objects to search (filter) between. It is ignored if `global_search` is given. If not set, this list will automatically be defined to include the location, the contents of location and the caller's contents (inventory). nofound_string (str): optional custom string for not-found error message. multimatch_string (str): optional custom string for multimatch error header. use_dbref (bool or None): If None, only turn off use_dbref if we are of a lower permission than Builder. Otherwise, honor the True/False value. Returns: match (Object, None or list): will return an Object/None if `quiet=False`, otherwise it will return a list of 0, 1 or more matches. Notes: To find Accounts, use eg. `evennia.account_search`. If `quiet=False`, error messages will be handled by `settings.SEARCH_AT_RESULT` and echoed automatically (on error, return will be `None`). If `quiet=True`, the error messaging is assumed to be handled by the caller.
Returns an Object matching a search string/condition, taking sdescs into account.
def search(self, searchdata, global_search=False, use_nicks=True, typeclass=None, location=None, attribute_name=None, quiet=False, exact=False, candidates=None, nofound_string=None, multimatch_string=None, use_dbref=None): """ Returns an Object matching a search string/condition, taking sdescs into account. Perform a standard object search in the database, handling multiple results and lack thereof gracefully. By default, only objects in the current `location` of `self` or its inventory are searched for. Args: searchdata (str or obj): Primary search criterion. Will be matched against `object.key` (with `object.aliases` second) unless the keyword attribute_name specifies otherwise. **Special strings:** - `#<num>`: search by unique dbref. This is always a global search. - `me,self`: self-reference to this object - `<num>-<string>` - can be used to differentiate between multiple same-named matches global_search (bool): Search all objects globally. This is overruled by `location` keyword. use_nicks (bool): Use nickname-replace (nicktype "object") on `searchdata`. typeclass (str or Typeclass, or list of either): Limit search only to `Objects` with this typeclass. May be a list of typeclasses for a broader search. location (Object or list): Specify a location or multiple locations to search. Note that this is used to query the *contents* of a location and will not match for the location itself - if you want that, don't set this or use `candidates` to specify exactly which objects should be searched. attribute_name (str): Define which property to search. If set, no key+alias search will be performed. This can be used to search database fields (db_ will be automatically appended), and if that fails, it will try to return objects having Attributes with this name and value equal to searchdata. A special use is to search for "key" here if you want to do a key-search without including aliases. quiet (bool): don't display default error messages - this tells the search method that the user wants to handle all errors themselves. It also changes the return value type, see below. exact (bool): if unset (default) - prefers to match to beginning of string rather than not matching at all. If set, requires exact matching of entire string. candidates (list of objects): this is an optional custom list of objects to search (filter) between. It is ignored if `global_search` is given. If not set, this list will automatically be defined to include the location, the contents of location and the caller's contents (inventory). nofound_string (str): optional custom string for not-found error message. multimatch_string (str): optional custom string for multimatch error header. use_dbref (bool or None): If None, only turn off use_dbref if we are of a lower permission than Builder. Otherwise, honor the True/False value. Returns: match (Object, None or list): will return an Object/None if `quiet=False`, otherwise it will return a list of 0, 1 or more matches. Notes: To find Accounts, use eg. `evennia.account_search`. If `quiet=False`, error messages will be handled by `settings.SEARCH_AT_RESULT` and echoed automatically (on error, return will be `None`). If `quiet=True`, the error messaging is assumed to be handled by the caller. """ is_string = isinstance(searchdata, basestring) if is_string: # searchdata is a string; wrap some common self-references if searchdata.lower() in ("here", ): return [self.location] if quiet else self.location if searchdata.lower() in ("me", "self",): return [self] if quiet else self if use_nicks: # do nick-replacement on search searchdata = self.nicks.nickreplace(searchdata, categories=("object", "account"), include_account=True) if(global_search or (is_string and searchdata.startswith("#") and len(searchdata) > 1 and searchdata[1:].isdigit())): # only allow exact matching if searching the entire database # or unique #dbrefs exact = True elif candidates is None: # no custom candidates given - get them automatically if location: # location(s) were given candidates = [] for obj in make_iter(location): candidates.extend(obj.contents) else: # local search. Candidates are taken from # self.contents, self.location and # self.location.contents location = self.location candidates = self.contents if location: candidates = candidates + [location] + location.contents else: # normally we don't need this since we are # included in location.contents candidates.append(self) # the sdesc-related substitution is_builder = self.locks.check_lockstring(self, "perm(Builder)") use_dbref = is_builder if use_dbref is None else use_dbref def search_obj(string): return ObjectDB.objects.object_search(string, attribute_name=attribute_name, typeclass=typeclass, candidates=candidates, exact=exact, use_dbref=use_dbref) if candidates: candidates = parse_sdescs_and_recogs(self, candidates, _PREFIX + searchdata, search_mode=True) results = [] for candidate in candidates: # we search by candidate keys here; this allows full error # management and use of all kwargs - we will use searchdata # in eventual error reporting later (not their keys). Doing # it like this e.g. allows for use of the typeclass kwarg # limiter. results.extend(search_obj(candidate.key)) if not results and is_builder: # builders get a chance to search only by key+alias results = search_obj(searchdata) else: # global searches / #drefs end up here. Global searches are # only done in code, so is controlled, #dbrefs are turned off # for non-Builders. results = search_obj(searchdata) if quiet: return results return _AT_SEARCH_RESULT(results, self, query=searchdata, nofound_string=nofound_string, multimatch_string=multimatch_string)
[ "def", "search", "(", "self", ",", "searchdata", ",", "global_search", "=", "False", ",", "use_nicks", "=", "True", ",", "typeclass", "=", "None", ",", "location", "=", "None", ",", "attribute_name", "=", "None", ",", "quiet", "=", "False", ",", "exact", "=", "False", ",", "candidates", "=", "None", ",", "nofound_string", "=", "None", ",", "multimatch_string", "=", "None", ",", "use_dbref", "=", "None", ")", ":", "is_string", "=", "isinstance", "(", "searchdata", ",", "basestring", ")", "if", "is_string", ":", "# searchdata is a string; wrap some common self-references", "if", "searchdata", ".", "lower", "(", ")", "in", "(", "\"here\"", ",", ")", ":", "return", "[", "self", ".", "location", "]", "if", "quiet", "else", "self", ".", "location", "if", "searchdata", ".", "lower", "(", ")", "in", "(", "\"me\"", ",", "\"self\"", ",", ")", ":", "return", "[", "self", "]", "if", "quiet", "else", "self", "if", "use_nicks", ":", "# do nick-replacement on search", "searchdata", "=", "self", ".", "nicks", ".", "nickreplace", "(", "searchdata", ",", "categories", "=", "(", "\"object\"", ",", "\"account\"", ")", ",", "include_account", "=", "True", ")", "if", "(", "global_search", "or", "(", "is_string", "and", "searchdata", ".", "startswith", "(", "\"#\"", ")", "and", "len", "(", "searchdata", ")", ">", "1", "and", "searchdata", "[", "1", ":", "]", ".", "isdigit", "(", ")", ")", ")", ":", "# only allow exact matching if searching the entire database", "# or unique #dbrefs", "exact", "=", "True", "elif", "candidates", "is", "None", ":", "# no custom candidates given - get them automatically", "if", "location", ":", "# location(s) were given", "candidates", "=", "[", "]", "for", "obj", "in", "make_iter", "(", "location", ")", ":", "candidates", ".", "extend", "(", "obj", ".", "contents", ")", "else", ":", "# local search. Candidates are taken from", "# self.contents, self.location and", "# self.location.contents", "location", "=", "self", ".", "location", "candidates", "=", "self", ".", "contents", "if", "location", ":", "candidates", "=", "candidates", "+", "[", "location", "]", "+", "location", ".", "contents", "else", ":", "# normally we don't need this since we are", "# included in location.contents", "candidates", ".", "append", "(", "self", ")", "# the sdesc-related substitution", "is_builder", "=", "self", ".", "locks", ".", "check_lockstring", "(", "self", ",", "\"perm(Builder)\"", ")", "use_dbref", "=", "is_builder", "if", "use_dbref", "is", "None", "else", "use_dbref", "def", "search_obj", "(", "string", ")", ":", "return", "ObjectDB", ".", "objects", ".", "object_search", "(", "string", ",", "attribute_name", "=", "attribute_name", ",", "typeclass", "=", "typeclass", ",", "candidates", "=", "candidates", ",", "exact", "=", "exact", ",", "use_dbref", "=", "use_dbref", ")", "if", "candidates", ":", "candidates", "=", "parse_sdescs_and_recogs", "(", "self", ",", "candidates", ",", "_PREFIX", "+", "searchdata", ",", "search_mode", "=", "True", ")", "results", "=", "[", "]", "for", "candidate", "in", "candidates", ":", "# we search by candidate keys here; this allows full error", "# management and use of all kwargs - we will use searchdata", "# in eventual error reporting later (not their keys). Doing", "# it like this e.g. allows for use of the typeclass kwarg", "# limiter.", "results", ".", "extend", "(", "search_obj", "(", "candidate", ".", "key", ")", ")", "if", "not", "results", "and", "is_builder", ":", "# builders get a chance to search only by key+alias", "results", "=", "search_obj", "(", "searchdata", ")", "else", ":", "# global searches / #drefs end up here. Global searches are", "# only done in code, so is controlled, #dbrefs are turned off", "# for non-Builders.", "results", "=", "search_obj", "(", "searchdata", ")", "if", "quiet", ":", "return", "results", "return", "_AT_SEARCH_RESULT", "(", "results", ",", "self", ",", "query", "=", "searchdata", ",", "nofound_string", "=", "nofound_string", ",", "multimatch_string", "=", "multimatch_string", ")" ]
[ 1150, 4 ]
[ 1301, 100 ]
python
en
['en', 'error', 'th']
False
ContribRPObject.get_display_name
(self, looker, **kwargs)
Displays the name of the object in a viewer-aware manner. Args: looker (TypedObject): The object or account that is looking at/getting inforamtion for this object. Kwargs: pose (bool): Include the pose (if available) in the return. Returns: name (str): A string of the sdesc containing the name of the object, if this is defined. including the DBREF if this user is privileged to control said object. Notes: The RPObject version doesn't add color to its display.
Displays the name of the object in a viewer-aware manner.
def get_display_name(self, looker, **kwargs): """ Displays the name of the object in a viewer-aware manner. Args: looker (TypedObject): The object or account that is looking at/getting inforamtion for this object. Kwargs: pose (bool): Include the pose (if available) in the return. Returns: name (str): A string of the sdesc containing the name of the object, if this is defined. including the DBREF if this user is privileged to control said object. Notes: The RPObject version doesn't add color to its display. """ idstr = "(#%s)" % self.id if self.access(looker, access_type='control') else "" if looker == self: sdesc = self.key else: try: recog = looker.recog.get(self) except AttributeError: recog = None sdesc = recog or (hasattr(self, "sdesc") and self.sdesc.get()) or self.key pose = " %s" % (self.db.pose or "") if kwargs.get("pose", False) else "" return "%s%s%s" % (sdesc, idstr, pose)
[ "def", "get_display_name", "(", "self", ",", "looker", ",", "*", "*", "kwargs", ")", ":", "idstr", "=", "\"(#%s)\"", "%", "self", ".", "id", "if", "self", ".", "access", "(", "looker", ",", "access_type", "=", "'control'", ")", "else", "\"\"", "if", "looker", "==", "self", ":", "sdesc", "=", "self", ".", "key", "else", ":", "try", ":", "recog", "=", "looker", ".", "recog", ".", "get", "(", "self", ")", "except", "AttributeError", ":", "recog", "=", "None", "sdesc", "=", "recog", "or", "(", "hasattr", "(", "self", ",", "\"sdesc\"", ")", "and", "self", ".", "sdesc", ".", "get", "(", ")", ")", "or", "self", ".", "key", "pose", "=", "\" %s\"", "%", "(", "self", ".", "db", ".", "pose", "or", "\"\"", ")", "if", "kwargs", ".", "get", "(", "\"pose\"", ",", "False", ")", "else", "\"\"", "return", "\"%s%s%s\"", "%", "(", "sdesc", ",", "idstr", ",", "pose", ")" ]
[ 1303, 4 ]
[ 1334, 46 ]
python
en
['en', 'error', 'th']
False
ContribRPObject.return_appearance
(self, looker)
This formats a description. It is the hook a 'look' command should call. Args: looker (Object): Object doing the looking.
This formats a description. It is the hook a 'look' command should call.
def return_appearance(self, looker): """ This formats a description. It is the hook a 'look' command should call. Args: looker (Object): Object doing the looking. """ if not looker: return "" # get and identify all objects visible = (con for con in self.contents if con != looker and con.access(looker, "view")) exits, users, things = [], [], [] for con in visible: key = con.get_display_name(looker, pose=True) if con.destination: exits.append(key) elif con.has_account: users.append(key) else: things.append(key) # get description, build string string = "|c%s|n\n" % self.get_display_name(looker, pose=True) desc = self.db.desc if desc: string += "%s" % desc if exits: string += "\n|wExits:|n " + ", ".join(exits) if users or things: string += "\n " + "\n ".join(users + things) return string
[ "def", "return_appearance", "(", "self", ",", "looker", ")", ":", "if", "not", "looker", ":", "return", "\"\"", "# get and identify all objects", "visible", "=", "(", "con", "for", "con", "in", "self", ".", "contents", "if", "con", "!=", "looker", "and", "con", ".", "access", "(", "looker", ",", "\"view\"", ")", ")", "exits", ",", "users", ",", "things", "=", "[", "]", ",", "[", "]", ",", "[", "]", "for", "con", "in", "visible", ":", "key", "=", "con", ".", "get_display_name", "(", "looker", ",", "pose", "=", "True", ")", "if", "con", ".", "destination", ":", "exits", ".", "append", "(", "key", ")", "elif", "con", ".", "has_account", ":", "users", ".", "append", "(", "key", ")", "else", ":", "things", ".", "append", "(", "key", ")", "# get description, build string", "string", "=", "\"|c%s|n\\n\"", "%", "self", ".", "get_display_name", "(", "looker", ",", "pose", "=", "True", ")", "desc", "=", "self", ".", "db", ".", "desc", "if", "desc", ":", "string", "+=", "\"%s\"", "%", "desc", "if", "exits", ":", "string", "+=", "\"\\n|wExits:|n \"", "+", "\", \"", ".", "join", "(", "exits", ")", "if", "users", "or", "things", ":", "string", "+=", "\"\\n \"", "+", "\"\\n \"", ".", "join", "(", "users", "+", "things", ")", "return", "string" ]
[ 1336, 4 ]
[ 1367, 21 ]
python
en
['en', 'error', 'th']
False
ContribRPCharacter.get_display_name
(self, looker, **kwargs)
Displays the name of the object in a viewer-aware manner. Args: looker (TypedObject): The object or account that is looking at/getting inforamtion for this object. Kwargs: pose (bool): Include the pose (if available) in the return. Returns: name (str): A string of the sdesc containing the name of the object, if this is defined. including the DBREF if this user is privileged to control said object. Notes: The RPCharacter version of this method colors its display to make characters stand out from other objects.
Displays the name of the object in a viewer-aware manner.
def get_display_name(self, looker, **kwargs): """ Displays the name of the object in a viewer-aware manner. Args: looker (TypedObject): The object or account that is looking at/getting inforamtion for this object. Kwargs: pose (bool): Include the pose (if available) in the return. Returns: name (str): A string of the sdesc containing the name of the object, if this is defined. including the DBREF if this user is privileged to control said object. Notes: The RPCharacter version of this method colors its display to make characters stand out from other objects. """ idstr = "(#%s)" % self.id if self.access(looker, access_type='control') else "" if looker == self: sdesc = self.key else: try: recog = looker.recog.get(self) except AttributeError: recog = None sdesc = recog or (hasattr(self, "sdesc") and self.sdesc.get()) or self.key pose = " %s" % (self.db.pose or "is here.") if kwargs.get("pose", False) else "" return "|c%s|n%s%s" % (sdesc, idstr, pose)
[ "def", "get_display_name", "(", "self", ",", "looker", ",", "*", "*", "kwargs", ")", ":", "idstr", "=", "\"(#%s)\"", "%", "self", ".", "id", "if", "self", ".", "access", "(", "looker", ",", "access_type", "=", "'control'", ")", "else", "\"\"", "if", "looker", "==", "self", ":", "sdesc", "=", "self", ".", "key", "else", ":", "try", ":", "recog", "=", "looker", ".", "recog", ".", "get", "(", "self", ")", "except", "AttributeError", ":", "recog", "=", "None", "sdesc", "=", "recog", "or", "(", "hasattr", "(", "self", ",", "\"sdesc\"", ")", "and", "self", ".", "sdesc", ".", "get", "(", ")", ")", "or", "self", ".", "key", "pose", "=", "\" %s\"", "%", "(", "self", ".", "db", ".", "pose", "or", "\"is here.\"", ")", "if", "kwargs", ".", "get", "(", "\"pose\"", ",", "False", ")", "else", "\"\"", "return", "\"|c%s|n%s%s\"", "%", "(", "sdesc", ",", "idstr", ",", "pose", ")" ]
[ 1390, 4 ]
[ 1422, 50 ]
python
en
['en', 'error', 'th']
False
ContribRPCharacter.at_object_creation
(self)
Called at initial creation.
Called at initial creation.
def at_object_creation(self): """ Called at initial creation. """ super(ContribRPCharacter, self).at_object_creation() self.db._sdesc = "" self.db._sdesc_regex = "" self.db._recog_ref2recog = {} self.db._recog_obj2regex = {} self.db._recog_obj2recog = {} self.cmdset.add(RPSystemCmdSet, permanent=True) # initializing sdesc self.sdesc.add("A normal person")
[ "def", "at_object_creation", "(", "self", ")", ":", "super", "(", "ContribRPCharacter", ",", "self", ")", ".", "at_object_creation", "(", ")", "self", ".", "db", ".", "_sdesc", "=", "\"\"", "self", ".", "db", ".", "_sdesc_regex", "=", "\"\"", "self", ".", "db", ".", "_recog_ref2recog", "=", "{", "}", "self", ".", "db", ".", "_recog_obj2regex", "=", "{", "}", "self", ".", "db", ".", "_recog_obj2recog", "=", "{", "}", "self", ".", "cmdset", ".", "add", "(", "RPSystemCmdSet", ",", "permanent", "=", "True", ")", "# initializing sdesc", "self", ".", "sdesc", ".", "add", "(", "\"A normal person\"", ")" ]
[ 1424, 4 ]
[ 1439, 41 ]
python
en
['en', 'error', 'th']
False
ContribRPCharacter.process_sdesc
(self, sdesc, obj, **kwargs)
Allows to customize how your sdesc is displayed (primarily by changing colors). Args: sdesc (str): The sdesc to display. obj (Object): The object to which the adjoining sdesc belongs. If this object is equal to yourself, then you are viewing yourself (and sdesc is your key). This is not used by default. Returns: sdesc (str): The processed sdesc ready for display.
Allows to customize how your sdesc is displayed (primarily by changing colors).
def process_sdesc(self, sdesc, obj, **kwargs): """ Allows to customize how your sdesc is displayed (primarily by changing colors). Args: sdesc (str): The sdesc to display. obj (Object): The object to which the adjoining sdesc belongs. If this object is equal to yourself, then you are viewing yourself (and sdesc is your key). This is not used by default. Returns: sdesc (str): The processed sdesc ready for display. """ return "|b%s|n" % sdesc
[ "def", "process_sdesc", "(", "self", ",", "sdesc", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "return", "\"|b%s|n\"", "%", "sdesc" ]
[ 1441, 4 ]
[ 1458, 31 ]
python
en
['en', 'error', 'th']
False
ContribRPCharacter.process_recog
(self, recog, obj, **kwargs)
Allows to customize how a recog string is displayed. Args: recog (str): The recog string. It has already been translated from the original sdesc at this point. obj (Object): The object the recog:ed string belongs to. This is not used by default. Returns: recog (str): The modified recog string.
Allows to customize how a recog string is displayed.
def process_recog(self, recog, obj, **kwargs): """ Allows to customize how a recog string is displayed. Args: recog (str): The recog string. It has already been translated from the original sdesc at this point. obj (Object): The object the recog:ed string belongs to. This is not used by default. Returns: recog (str): The modified recog string. """ return self.process_sdesc(recog, obj)
[ "def", "process_recog", "(", "self", ",", "recog", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "process_sdesc", "(", "recog", ",", "obj", ")" ]
[ 1460, 4 ]
[ 1474, 45 ]
python
en
['en', 'error', 'th']
False
ContribRPCharacter.process_language
(self, text, speaker, language, **kwargs)
Allows to process the spoken text, for example by obfuscating language based on your and the speaker's language skills. Also a good place to put coloring. Args: text (str): The text to process. speaker (Object): The object delivering the text. language (str): An identifier string for the language. Return: text (str): The optionally processed text. Notes: This is designed to work together with a string obfuscator such as the `obfuscate_language` or `obfuscate_whisper` in the evennia.contrib.rplanguage module.
Allows to process the spoken text, for example by obfuscating language based on your and the speaker's language skills. Also a good place to put coloring.
def process_language(self, text, speaker, language, **kwargs): """ Allows to process the spoken text, for example by obfuscating language based on your and the speaker's language skills. Also a good place to put coloring. Args: text (str): The text to process. speaker (Object): The object delivering the text. language (str): An identifier string for the language. Return: text (str): The optionally processed text. Notes: This is designed to work together with a string obfuscator such as the `obfuscate_language` or `obfuscate_whisper` in the evennia.contrib.rplanguage module. """ return "%s|w%s|n" % ("|W(%s)" % language if language else "", text)
[ "def", "process_language", "(", "self", ",", "text", ",", "speaker", ",", "language", ",", "*", "*", "kwargs", ")", ":", "return", "\"%s|w%s|n\"", "%", "(", "\"|W(%s)\"", "%", "language", "if", "language", "else", "\"\"", ",", "text", ")" ]
[ 1476, 4 ]
[ 1497, 75 ]
python
en
['en', 'error', 'th']
False
basic_auth
(username, password)
Creates the basic auth value to be used in an authorization header. This is mostly copied from the requests library. :param (str) username: A Plotly username. :param (str) password: The password for the given Plotly username. :returns: (str) An 'authorization' header for use in a request header.
Creates the basic auth value to be used in an authorization header.
def basic_auth(username, password): """ Creates the basic auth value to be used in an authorization header. This is mostly copied from the requests library. :param (str) username: A Plotly username. :param (str) password: The password for the given Plotly username. :returns: (str) An 'authorization' header for use in a request header. """ if isinstance(username, str): username = username.encode("latin1") if isinstance(password, str): password = password.encode("latin1") return "Basic " + to_native_ascii_string( b64encode(b":".join((username, password))).strip() )
[ "def", "basic_auth", "(", "username", ",", "password", ")", ":", "if", "isinstance", "(", "username", ",", "str", ")", ":", "username", "=", "username", ".", "encode", "(", "\"latin1\"", ")", "if", "isinstance", "(", "password", ",", "str", ")", ":", "password", "=", "password", ".", "encode", "(", "\"latin1\"", ")", "return", "\"Basic \"", "+", "to_native_ascii_string", "(", "b64encode", "(", "b\":\"", ".", "join", "(", "(", "username", ",", "password", ")", ")", ")", ".", "strip", "(", ")", ")" ]
[ 21, 0 ]
[ 40, 5 ]
python
en
['en', 'error', 'th']
False
Identity.__init__
(self, identifier: Identifier, endorser: Identifier = None, verkey=None, role=None, last_synced=None, seq_no=None)
:param identifier: :param endorser: :param verkey: :param role: If role is explicitly passed as `null` then in the request to ledger, `role` key would be sent as None which would stop the Identity's ability to do any privileged actions. If role is not passed, `role` key will not be included in the request to the ledger :param last_synced: :param seq_no:
def __init__(self, identifier: Identifier, endorser: Identifier = None, verkey=None, role=None, last_synced=None, seq_no=None): """ :param identifier: :param endorser: :param verkey: :param role: If role is explicitly passed as `null` then in the request to ledger, `role` key would be sent as None which would stop the Identity's ability to do any privileged actions. If role is not passed, `role` key will not be included in the request to the ledger :param last_synced: :param seq_no: """ self.identity = DidIdentity(identifier, verkey=verkey) self.endorser = endorser # if role and role not in (ENDORSER, STEWARD): if not Authoriser.isValidRole(self.correctRole(role)): raise AttributeError("Invalid role {}".format(role)) self._role = role # timestamp for when the ledger was last checked for key replacement or # revocation self.last_synced = last_synced # sequence number of the latest key management transaction for this # identifier self.seqNo = seq_no
[ "def", "__init__", "(", "self", ",", "identifier", ":", "Identifier", ",", "endorser", ":", "Identifier", "=", "None", ",", "verkey", "=", "None", ",", "role", "=", "None", ",", "last_synced", "=", "None", ",", "seq_no", "=", "None", ")", ":", "self", ".", "identity", "=", "DidIdentity", "(", "identifier", ",", "verkey", "=", "verkey", ")", "self", ".", "endorser", "=", "endorser", "# if role and role not in (ENDORSER, STEWARD):", "if", "not", "Authoriser", ".", "isValidRole", "(", "self", ".", "correctRole", "(", "role", ")", ")", ":", "raise", "AttributeError", "(", "\"Invalid role {}\"", ".", "format", "(", "role", ")", ")", "self", ".", "_role", "=", "role", "# timestamp for when the ledger was last checked for key replacement or", "# revocation", "self", ".", "last_synced", "=", "last_synced", "# sequence number of the latest key management transaction for this", "# identifier", "self", ".", "seqNo", "=", "seq_no" ]
[ 12, 4 ]
[ 46, 27 ]
python
en
['en', 'error', 'th']
False
Stream.maxpoints
(self)
Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. The 'maxpoints' property is a number and may be specified as: - An int or float in the interval [0, 10000] Returns ------- int|float
Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. The 'maxpoints' property is a number and may be specified as: - An int or float in the interval [0, 10000]
def maxpoints(self): """ Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. The 'maxpoints' property is a number and may be specified as: - An int or float in the interval [0, 10000] Returns ------- int|float """ return self["maxpoints"]
[ "def", "maxpoints", "(", "self", ")", ":", "return", "self", "[", "\"maxpoints\"", "]" ]
[ 15, 4 ]
[ 28, 32 ]
python
en
['en', 'error', 'th']
False
Stream.token
(self)
The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. The 'token' property is a string and must be specified as: - A non-empty string Returns ------- str
The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. The 'token' property is a string and must be specified as: - A non-empty string
def token(self): """ The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. The 'token' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["token"]
[ "def", "token", "(", "self", ")", ":", "return", "self", "[", "\"token\"", "]" ]
[ 37, 4 ]
[ 50, 28 ]
python
en
['en', 'error', 'th']
False
Stream.__init__
(self, arg=None, maxpoints=None, token=None, **kwargs)
Construct a new Stream object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.parcats.Stream` maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. Returns ------- Stream
Construct a new Stream object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.parcats.Stream` maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details.
def __init__(self, arg=None, maxpoints=None, token=None, **kwargs): """ Construct a new Stream object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.parcats.Stream` maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. Returns ------- Stream """ super(Stream, self).__init__("stream") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.parcats.Stream constructor must be a dict or an instance of :class:`plotly.graph_objs.parcats.Stream`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("maxpoints", None) _v = maxpoints if maxpoints is not None else _v if _v is not None: self["maxpoints"] = _v _v = arg.pop("token", None) _v = token if token is not None else _v if _v is not None: self["token"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "maxpoints", "=", "None", ",", "token", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Stream", ",", "self", ")", ".", "__init__", "(", "\"stream\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.parcats.Stream \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.parcats.Stream`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"maxpoints\"", ",", "None", ")", "_v", "=", "maxpoints", "if", "maxpoints", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"maxpoints\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"token\"", ",", "None", ")", "_v", "=", "token", "if", "token", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"token\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 72, 4 ]
[ 140, 34 ]
python
en
['en', 'error', 'th']
False
Line.autocolorscale
(self)
Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. Has an effect only if in `marker.line.color`is set to a numerical array. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. The 'autocolorscale' property must be specified as a bool (either True, or False) Returns ------- bool
Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. Has an effect only if in `marker.line.color`is set to a numerical array. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. The 'autocolorscale' property must be specified as a bool (either True, or False)
def autocolorscale(self): """ Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. Has an effect only if in `marker.line.color`is set to a numerical array. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. The 'autocolorscale' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["autocolorscale"]
[ "def", "autocolorscale", "(", "self", ")", ":", "return", "self", "[", "\"autocolorscale\"", "]" ]
[ 28, 4 ]
[ 45, 37 ]
python
en
['en', 'error', 'th']
False
Line.cauto
(self)
Determines whether or not the color domain is computed with respect to the input data (here in `marker.line.color`) or the bounds set in `marker.line.cmin` and `marker.line.cmax` Has an effect only if in `marker.line.color`is set to a numerical array. Defaults to `false` when `marker.line.cmin` and `marker.line.cmax` are set by the user. The 'cauto' property must be specified as a bool (either True, or False) Returns ------- bool
Determines whether or not the color domain is computed with respect to the input data (here in `marker.line.color`) or the bounds set in `marker.line.cmin` and `marker.line.cmax` Has an effect only if in `marker.line.color`is set to a numerical array. Defaults to `false` when `marker.line.cmin` and `marker.line.cmax` are set by the user. The 'cauto' property must be specified as a bool (either True, or False)
def cauto(self): """ Determines whether or not the color domain is computed with respect to the input data (here in `marker.line.color`) or the bounds set in `marker.line.cmin` and `marker.line.cmax` Has an effect only if in `marker.line.color`is set to a numerical array. Defaults to `false` when `marker.line.cmin` and `marker.line.cmax` are set by the user. The 'cauto' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["cauto"]
[ "def", "cauto", "(", "self", ")", ":", "return", "self", "[", "\"cauto\"", "]" ]
[ 54, 4 ]
[ 70, 28 ]
python
en
['en', 'error', 'th']
False
Line.cmax
(self)
Sets the upper bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmin` must be set as well. The 'cmax' property is a number and may be specified as: - An int or float Returns ------- int|float
Sets the upper bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmin` must be set as well. The 'cmax' property is a number and may be specified as: - An int or float
def cmax(self): """ Sets the upper bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmin` must be set as well. The 'cmax' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["cmax"]
[ "def", "cmax", "(", "self", ")", ":", "return", "self", "[", "\"cmax\"", "]" ]
[ 79, 4 ]
[ 93, 27 ]
python
en
['en', 'error', 'th']
False
Line.cmid
(self)
Sets the mid-point of the color domain by scaling `marker.line.cmin` and/or `marker.line.cmax` to be equidistant to this point. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color`. Has no effect when `marker.line.cauto` is `false`. The 'cmid' property is a number and may be specified as: - An int or float Returns ------- int|float
Sets the mid-point of the color domain by scaling `marker.line.cmin` and/or `marker.line.cmax` to be equidistant to this point. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color`. Has no effect when `marker.line.cauto` is `false`. The 'cmid' property is a number and may be specified as: - An int or float
def cmid(self): """ Sets the mid-point of the color domain by scaling `marker.line.cmin` and/or `marker.line.cmax` to be equidistant to this point. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color`. Has no effect when `marker.line.cauto` is `false`. The 'cmid' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["cmid"]
[ "def", "cmid", "(", "self", ")", ":", "return", "self", "[", "\"cmid\"", "]" ]
[ 102, 4 ]
[ 118, 27 ]
python
en
['en', 'error', 'th']
False
Line.cmin
(self)
Sets the lower bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmax` must be set as well. The 'cmin' property is a number and may be specified as: - An int or float Returns ------- int|float
Sets the lower bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmax` must be set as well. The 'cmin' property is a number and may be specified as: - An int or float
def cmin(self): """ Sets the lower bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmax` must be set as well. The 'cmin' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["cmin"]
[ "def", "cmin", "(", "self", ")", ":", "return", "self", "[", "\"cmin\"", "]" ]
[ 127, 4 ]
[ 141, 27 ]
python
en
['en', 'error', 'th']
False
Line.color
(self)
Sets themarker.linecolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A number that will be interpreted as a color according to scatterternary.marker.line.colorscale - A list or array of any of the above Returns ------- str|numpy.ndarray
Sets themarker.linecolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A number that will be interpreted as a color according to scatterternary.marker.line.colorscale - A list or array of any of the above
def color(self): """ Sets themarker.linecolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A number that will be interpreted as a color according to scatterternary.marker.line.colorscale - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["color"]
[ "def", "color", "(", "self", ")", ":", "return", "self", "[", "\"color\"", "]" ]
[ 150, 4 ]
[ 206, 28 ]
python
en
['en', 'error', 'th']
False
Line.coloraxis
(self)
Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. The 'coloraxis' property is an identifier of a particular subplot, of type 'coloraxis', that may be specified as the string 'coloraxis' optionally followed by an integer >= 1 (e.g. 'coloraxis', 'coloraxis1', 'coloraxis2', 'coloraxis3', etc.) Returns ------- str
Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. The 'coloraxis' property is an identifier of a particular subplot, of type 'coloraxis', that may be specified as the string 'coloraxis' optionally followed by an integer >= 1 (e.g. 'coloraxis', 'coloraxis1', 'coloraxis2', 'coloraxis3', etc.)
def coloraxis(self): """ Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. The 'coloraxis' property is an identifier of a particular subplot, of type 'coloraxis', that may be specified as the string 'coloraxis' optionally followed by an integer >= 1 (e.g. 'coloraxis', 'coloraxis1', 'coloraxis2', 'coloraxis3', etc.) Returns ------- str """ return self["coloraxis"]
[ "def", "coloraxis", "(", "self", ")", ":", "return", "self", "[", "\"coloraxis\"", "]" ]
[ 215, 4 ]
[ 233, 32 ]
python
en
['en', 'error', 'th']
False
Line.colorscale
(self)
Sets the colorscale. Has an effect only if in `marker.line.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,Reds,Bl ues,Picnic,Rainbow,Portland,Jet,Hot,Blackbody,Earth,Electric,Vi ridis,Cividis. The 'colorscale' property is a colorscale and may be specified as: - A list of colors that will be spaced evenly to create the colorscale. Many predefined colorscale lists are included in the sequential, diverging, and cyclical modules in the plotly.colors package. - A list of 2-element lists where the first element is the normalized color level value (starting at 0 and ending at 1), and the second item is a valid color string. (e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']]) - One of the following named colorscales: ['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance', 'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg', 'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl', 'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric', 'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys', 'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet', 'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges', 'orrd', 'oryel', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd']. Appending '_r' to a named colorscale reverses it. Returns ------- str
Sets the colorscale. Has an effect only if in `marker.line.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,Reds,Bl ues,Picnic,Rainbow,Portland,Jet,Hot,Blackbody,Earth,Electric,Vi ridis,Cividis. The 'colorscale' property is a colorscale and may be specified as: - A list of colors that will be spaced evenly to create the colorscale. Many predefined colorscale lists are included in the sequential, diverging, and cyclical modules in the plotly.colors package. - A list of 2-element lists where the first element is the normalized color level value (starting at 0 and ending at 1), and the second item is a valid color string. (e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']]) - One of the following named colorscales: ['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance', 'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg', 'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl', 'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric', 'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys', 'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet', 'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges', 'orrd', 'oryel', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd']. Appending '_r' to a named colorscale reverses it.
def colorscale(self): """ Sets the colorscale. Has an effect only if in `marker.line.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,Reds,Bl ues,Picnic,Rainbow,Portland,Jet,Hot,Blackbody,Earth,Electric,Vi ridis,Cividis. The 'colorscale' property is a colorscale and may be specified as: - A list of colors that will be spaced evenly to create the colorscale. Many predefined colorscale lists are included in the sequential, diverging, and cyclical modules in the plotly.colors package. - A list of 2-element lists where the first element is the normalized color level value (starting at 0 and ending at 1), and the second item is a valid color string. (e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']]) - One of the following named colorscales: ['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance', 'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg', 'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl', 'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric', 'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys', 'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet', 'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges', 'orrd', 'oryel', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd']. Appending '_r' to a named colorscale reverses it. Returns ------- str """ return self["colorscale"]
[ "def", "colorscale", "(", "self", ")", ":", "return", "self", "[", "\"colorscale\"", "]" ]
[ 242, 4 ]
[ 287, 33 ]
python
en
['en', 'error', 'th']
False
Line.colorsrc
(self)
Sets the source reference on Chart Studio Cloud for color . The 'colorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for color . The 'colorsrc' property must be specified as a string or as a plotly.grid_objs.Column object
def colorsrc(self): """ Sets the source reference on Chart Studio Cloud for color . The 'colorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["colorsrc"]
[ "def", "colorsrc", "(", "self", ")", ":", "return", "self", "[", "\"colorsrc\"", "]" ]
[ 296, 4 ]
[ 307, 31 ]
python
en
['en', 'error', 'th']
False
Line.reversescale
(self)
Reverses the color mapping if true. Has an effect only if in `marker.line.color`is set to a numerical array. If true, `marker.line.cmin` will correspond to the last color in the array and `marker.line.cmax` will correspond to the first color. The 'reversescale' property must be specified as a bool (either True, or False) Returns ------- bool
Reverses the color mapping if true. Has an effect only if in `marker.line.color`is set to a numerical array. If true, `marker.line.cmin` will correspond to the last color in the array and `marker.line.cmax` will correspond to the first color. The 'reversescale' property must be specified as a bool (either True, or False)
def reversescale(self): """ Reverses the color mapping if true. Has an effect only if in `marker.line.color`is set to a numerical array. If true, `marker.line.cmin` will correspond to the last color in the array and `marker.line.cmax` will correspond to the first color. The 'reversescale' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["reversescale"]
[ "def", "reversescale", "(", "self", ")", ":", "return", "self", "[", "\"reversescale\"", "]" ]
[ 316, 4 ]
[ 331, 35 ]
python
en
['en', 'error', 'th']
False
Line.width
(self)
Sets the width (in px) of the lines bounding the marker points. The 'width' property is a number and may be specified as: - An int or float in the interval [0, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray
Sets the width (in px) of the lines bounding the marker points. The 'width' property is a number and may be specified as: - An int or float in the interval [0, inf] - A tuple, list, or one-dimensional numpy array of the above
def width(self): """ Sets the width (in px) of the lines bounding the marker points. The 'width' property is a number and may be specified as: - An int or float in the interval [0, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray """ return self["width"]
[ "def", "width", "(", "self", ")", ":", "return", "self", "[", "\"width\"", "]" ]
[ 340, 4 ]
[ 352, 28 ]
python
en
['en', 'error', 'th']
False
Line.widthsrc
(self)
Sets the source reference on Chart Studio Cloud for width . The 'widthsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for width . The 'widthsrc' property must be specified as a string or as a plotly.grid_objs.Column object
def widthsrc(self): """ Sets the source reference on Chart Studio Cloud for width . The 'widthsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["widthsrc"]
[ "def", "widthsrc", "(", "self", ")", ":", "return", "self", "[", "\"widthsrc\"", "]" ]
[ 361, 4 ]
[ 372, 31 ]
python
en
['en', 'error', 'th']
False
Line.__init__
( self, arg=None, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, color=None, coloraxis=None, colorscale=None, colorsrc=None, reversescale=None, width=None, widthsrc=None, **kwargs )
Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatterternary.marker.Line` autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. Has an effect only if in `marker.line.color`is set to a numerical array. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here in `marker.line.color`) or the bounds set in `marker.line.cmin` and `marker.line.cmax` Has an effect only if in `marker.line.color`is set to a numerical array. Defaults to `false` when `marker.line.cmin` and `marker.line.cmax` are set by the user. cmax Sets the upper bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `marker.line.cmin` and/or `marker.line.cmax` to be equidistant to this point. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color`. Has no effect when `marker.line.cauto` is `false`. cmin Sets the lower bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmax` must be set as well. color Sets themarker.linecolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorscale Sets the colorscale. Has an effect only if in `marker.line.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. colorsrc Sets the source reference on Chart Studio Cloud for color . reversescale Reverses the color mapping if true. Has an effect only if in `marker.line.color`is set to a numerical array. If true, `marker.line.cmin` will correspond to the last color in the array and `marker.line.cmax` will correspond to the first color. width Sets the width (in px) of the lines bounding the marker points. widthsrc Sets the source reference on Chart Studio Cloud for width . Returns ------- Line
Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatterternary.marker.Line` autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. Has an effect only if in `marker.line.color`is set to a numerical array. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here in `marker.line.color`) or the bounds set in `marker.line.cmin` and `marker.line.cmax` Has an effect only if in `marker.line.color`is set to a numerical array. Defaults to `false` when `marker.line.cmin` and `marker.line.cmax` are set by the user. cmax Sets the upper bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `marker.line.cmin` and/or `marker.line.cmax` to be equidistant to this point. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color`. Has no effect when `marker.line.cauto` is `false`. cmin Sets the lower bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmax` must be set as well. color Sets themarker.linecolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorscale Sets the colorscale. Has an effect only if in `marker.line.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. colorsrc Sets the source reference on Chart Studio Cloud for color . reversescale Reverses the color mapping if true. Has an effect only if in `marker.line.color`is set to a numerical array. If true, `marker.line.cmin` will correspond to the last color in the array and `marker.line.cmax` will correspond to the first color. width Sets the width (in px) of the lines bounding the marker points. widthsrc Sets the source reference on Chart Studio Cloud for width .
def __init__( self, arg=None, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, color=None, coloraxis=None, colorscale=None, colorsrc=None, reversescale=None, width=None, widthsrc=None, **kwargs ): """ Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatterternary.marker.Line` autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. Has an effect only if in `marker.line.color`is set to a numerical array. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here in `marker.line.color`) or the bounds set in `marker.line.cmin` and `marker.line.cmax` Has an effect only if in `marker.line.color`is set to a numerical array. Defaults to `false` when `marker.line.cmin` and `marker.line.cmax` are set by the user. cmax Sets the upper bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `marker.line.cmin` and/or `marker.line.cmax` to be equidistant to this point. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color`. Has no effect when `marker.line.cauto` is `false`. cmin Sets the lower bound of the color domain. Has an effect only if in `marker.line.color`is set to a numerical array. Value should have the same units as in `marker.line.color` and if set, `marker.line.cmax` must be set as well. color Sets themarker.linecolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.line.cmin` and `marker.line.cmax` if set. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorscale Sets the colorscale. Has an effect only if in `marker.line.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. colorsrc Sets the source reference on Chart Studio Cloud for color . reversescale Reverses the color mapping if true. Has an effect only if in `marker.line.color`is set to a numerical array. If true, `marker.line.cmin` will correspond to the last color in the array and `marker.line.cmax` will correspond to the first color. width Sets the width (in px) of the lines bounding the marker points. widthsrc Sets the source reference on Chart Studio Cloud for width . Returns ------- Line """ super(Line, self).__init__("line") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.scatterternary.marker.Line constructor must be a dict or an instance of :class:`plotly.graph_objs.scatterternary.marker.Line`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("autocolorscale", None) _v = autocolorscale if autocolorscale is not None else _v if _v is not None: self["autocolorscale"] = _v _v = arg.pop("cauto", None) _v = cauto if cauto is not None else _v if _v is not None: self["cauto"] = _v _v = arg.pop("cmax", None) _v = cmax if cmax is not None else _v if _v is not None: self["cmax"] = _v _v = arg.pop("cmid", None) _v = cmid if cmid is not None else _v if _v is not None: self["cmid"] = _v _v = arg.pop("cmin", None) _v = cmin if cmin is not None else _v if _v is not None: self["cmin"] = _v _v = arg.pop("color", None) _v = color if color is not None else _v if _v is not None: self["color"] = _v _v = arg.pop("coloraxis", None) _v = coloraxis if coloraxis is not None else _v if _v is not None: self["coloraxis"] = _v _v = arg.pop("colorscale", None) _v = colorscale if colorscale is not None else _v if _v is not None: self["colorscale"] = _v _v = arg.pop("colorsrc", None) _v = colorsrc if colorsrc is not None else _v if _v is not None: self["colorsrc"] = _v _v = arg.pop("reversescale", None) _v = reversescale if reversescale is not None else _v if _v is not None: self["reversescale"] = _v _v = arg.pop("width", None) _v = width if width is not None else _v if _v is not None: self["width"] = _v _v = arg.pop("widthsrc", None) _v = widthsrc if widthsrc is not None else _v if _v is not None: self["widthsrc"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "autocolorscale", "=", "None", ",", "cauto", "=", "None", ",", "cmax", "=", "None", ",", "cmid", "=", "None", ",", "cmin", "=", "None", ",", "color", "=", "None", ",", "coloraxis", "=", "None", ",", "colorscale", "=", "None", ",", "colorsrc", "=", "None", ",", "reversescale", "=", "None", ",", "width", "=", "None", ",", "widthsrc", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Line", ",", "self", ")", ".", "__init__", "(", "\"line\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.scatterternary.marker.Line \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.scatterternary.marker.Line`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"autocolorscale\"", ",", "None", ")", "_v", "=", "autocolorscale", "if", "autocolorscale", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"autocolorscale\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"cauto\"", ",", "None", ")", "_v", "=", "cauto", "if", "cauto", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"cauto\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"cmax\"", ",", "None", ")", "_v", "=", "cmax", "if", "cmax", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"cmax\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"cmid\"", ",", "None", ")", "_v", "=", "cmid", "if", "cmid", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"cmid\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"cmin\"", ",", "None", ")", "_v", "=", "cmin", "if", "cmin", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"cmin\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"color\"", ",", "None", ")", "_v", "=", "color", "if", "color", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"color\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"coloraxis\"", ",", "None", ")", "_v", "=", "coloraxis", "if", "coloraxis", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"coloraxis\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"colorscale\"", ",", "None", ")", "_v", "=", "colorscale", "if", "colorscale", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"colorscale\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"colorsrc\"", ",", "None", ")", "_v", "=", "colorsrc", "if", "colorsrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"colorsrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"reversescale\"", ",", "None", ")", "_v", "=", "reversescale", "if", "reversescale", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"reversescale\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"width\"", ",", "None", ")", "_v", "=", "width", "if", "width", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"width\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"widthsrc\"", ",", "None", ")", "_v", "=", "widthsrc", "if", "widthsrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"widthsrc\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 464, 4 ]
[ 658, 34 ]
python
en
['en', 'error', 'th']
False
Surface.count
(self)
Sets the number of iso-surfaces between minimum and maximum iso-values. By default this value is 2 meaning that only minimum and maximum surfaces would be drawn. The 'count' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 9223372036854775807] Returns ------- int
Sets the number of iso-surfaces between minimum and maximum iso-values. By default this value is 2 meaning that only minimum and maximum surfaces would be drawn. The 'count' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 9223372036854775807]
def count(self): """ Sets the number of iso-surfaces between minimum and maximum iso-values. By default this value is 2 meaning that only minimum and maximum surfaces would be drawn. The 'count' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 9223372036854775807] Returns ------- int """ return self["count"]
[ "def", "count", "(", "self", ")", ":", "return", "self", "[", "\"count\"", "]" ]
[ 15, 4 ]
[ 29, 28 ]
python
en
['en', 'error', 'th']
False
Surface.fill
(self)
Sets the fill ratio of the iso-surface. The default fill value of the surface is 1 meaning that they are entirely shaded. On the other hand Applying a `fill` ratio less than one would allow the creation of openings parallel to the edges. The 'fill' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float
Sets the fill ratio of the iso-surface. The default fill value of the surface is 1 meaning that they are entirely shaded. On the other hand Applying a `fill` ratio less than one would allow the creation of openings parallel to the edges. The 'fill' property is a number and may be specified as: - An int or float in the interval [0, 1]
def fill(self): """ Sets the fill ratio of the iso-surface. The default fill value of the surface is 1 meaning that they are entirely shaded. On the other hand Applying a `fill` ratio less than one would allow the creation of openings parallel to the edges. The 'fill' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["fill"]
[ "def", "fill", "(", "self", ")", ":", "return", "self", "[", "\"fill\"", "]" ]
[ 38, 4 ]
[ 52, 27 ]
python
en
['en', 'error', 'th']
False
Surface.pattern
(self)
Sets the surface pattern of the iso-surface 3-D sections. The default pattern of the surface is `all` meaning that the rest of surface elements would be shaded. The check options (either 1 or 2) could be used to draw half of the squares on the surface. Using various combinations of capital `A`, `B`, `C`, `D` and `E` may also be used to reduce the number of triangles on the iso-surfaces and creating other patterns of interest. The 'pattern' property is a flaglist and may be specified as a string containing: - Any combination of ['A', 'B', 'C', 'D', 'E'] joined with '+' characters (e.g. 'A+B') OR exactly one of ['all', 'odd', 'even'] (e.g. 'even') Returns ------- Any
Sets the surface pattern of the iso-surface 3-D sections. The default pattern of the surface is `all` meaning that the rest of surface elements would be shaded. The check options (either 1 or 2) could be used to draw half of the squares on the surface. Using various combinations of capital `A`, `B`, `C`, `D` and `E` may also be used to reduce the number of triangles on the iso-surfaces and creating other patterns of interest. The 'pattern' property is a flaglist and may be specified as a string containing: - Any combination of ['A', 'B', 'C', 'D', 'E'] joined with '+' characters (e.g. 'A+B') OR exactly one of ['all', 'odd', 'even'] (e.g. 'even')
def pattern(self): """ Sets the surface pattern of the iso-surface 3-D sections. The default pattern of the surface is `all` meaning that the rest of surface elements would be shaded. The check options (either 1 or 2) could be used to draw half of the squares on the surface. Using various combinations of capital `A`, `B`, `C`, `D` and `E` may also be used to reduce the number of triangles on the iso-surfaces and creating other patterns of interest. The 'pattern' property is a flaglist and may be specified as a string containing: - Any combination of ['A', 'B', 'C', 'D', 'E'] joined with '+' characters (e.g. 'A+B') OR exactly one of ['all', 'odd', 'even'] (e.g. 'even') Returns ------- Any """ return self["pattern"]
[ "def", "pattern", "(", "self", ")", ":", "return", "self", "[", "\"pattern\"", "]" ]
[ 61, 4 ]
[ 81, 30 ]
python
en
['en', 'error', 'th']
False
Surface.show
(self)
Hides/displays surfaces between minimum and maximum iso-values. The 'show' property must be specified as a bool (either True, or False) Returns ------- bool
Hides/displays surfaces between minimum and maximum iso-values. The 'show' property must be specified as a bool (either True, or False)
def show(self): """ Hides/displays surfaces between minimum and maximum iso-values. The 'show' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["show"]
[ "def", "show", "(", "self", ")", ":", "return", "self", "[", "\"show\"", "]" ]
[ 90, 4 ]
[ 101, 27 ]
python
en
['en', 'error', 'th']
False
Surface.__init__
( self, arg=None, count=None, fill=None, pattern=None, show=None, **kwargs )
Construct a new Surface object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.isosurface.Surface` count Sets the number of iso-surfaces between minimum and maximum iso-values. By default this value is 2 meaning that only minimum and maximum surfaces would be drawn. fill Sets the fill ratio of the iso-surface. The default fill value of the surface is 1 meaning that they are entirely shaded. On the other hand Applying a `fill` ratio less than one would allow the creation of openings parallel to the edges. pattern Sets the surface pattern of the iso-surface 3-D sections. The default pattern of the surface is `all` meaning that the rest of surface elements would be shaded. The check options (either 1 or 2) could be used to draw half of the squares on the surface. Using various combinations of capital `A`, `B`, `C`, `D` and `E` may also be used to reduce the number of triangles on the iso-surfaces and creating other patterns of interest. show Hides/displays surfaces between minimum and maximum iso-values. Returns ------- Surface
Construct a new Surface object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.isosurface.Surface` count Sets the number of iso-surfaces between minimum and maximum iso-values. By default this value is 2 meaning that only minimum and maximum surfaces would be drawn. fill Sets the fill ratio of the iso-surface. The default fill value of the surface is 1 meaning that they are entirely shaded. On the other hand Applying a `fill` ratio less than one would allow the creation of openings parallel to the edges. pattern Sets the surface pattern of the iso-surface 3-D sections. The default pattern of the surface is `all` meaning that the rest of surface elements would be shaded. The check options (either 1 or 2) could be used to draw half of the squares on the surface. Using various combinations of capital `A`, `B`, `C`, `D` and `E` may also be used to reduce the number of triangles on the iso-surfaces and creating other patterns of interest. show Hides/displays surfaces between minimum and maximum iso-values.
def __init__( self, arg=None, count=None, fill=None, pattern=None, show=None, **kwargs ): """ Construct a new Surface object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.isosurface.Surface` count Sets the number of iso-surfaces between minimum and maximum iso-values. By default this value is 2 meaning that only minimum and maximum surfaces would be drawn. fill Sets the fill ratio of the iso-surface. The default fill value of the surface is 1 meaning that they are entirely shaded. On the other hand Applying a `fill` ratio less than one would allow the creation of openings parallel to the edges. pattern Sets the surface pattern of the iso-surface 3-D sections. The default pattern of the surface is `all` meaning that the rest of surface elements would be shaded. The check options (either 1 or 2) could be used to draw half of the squares on the surface. Using various combinations of capital `A`, `B`, `C`, `D` and `E` may also be used to reduce the number of triangles on the iso-surfaces and creating other patterns of interest. show Hides/displays surfaces between minimum and maximum iso-values. Returns ------- Surface """ super(Surface, self).__init__("surface") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.isosurface.Surface constructor must be a dict or an instance of :class:`plotly.graph_objs.isosurface.Surface`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("count", None) _v = count if count is not None else _v if _v is not None: self["count"] = _v _v = arg.pop("fill", None) _v = fill if fill is not None else _v if _v is not None: self["fill"] = _v _v = arg.pop("pattern", None) _v = pattern if pattern is not None else _v if _v is not None: self["pattern"] = _v _v = arg.pop("show", None) _v = show if show is not None else _v if _v is not None: self["show"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "count", "=", "None", ",", "fill", "=", "None", ",", "pattern", "=", "None", ",", "show", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Surface", ",", "self", ")", ".", "__init__", "(", "\"surface\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.isosurface.Surface \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.isosurface.Surface`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"count\"", ",", "None", ")", "_v", "=", "count", "if", "count", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"count\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"fill\"", ",", "None", ")", "_v", "=", "fill", "if", "fill", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"fill\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"pattern\"", ",", "None", ")", "_v", "=", "pattern", "if", "pattern", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"pattern\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"show\"", ",", "None", ")", "_v", "=", "show", "if", "show", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"show\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 137, 4 ]
[ 229, 34 ]
python
en
['en', 'error', 'th']
False
repeat
(tensor, K)
[B, ...] => [B*K, ...] #-- Important --# Used unsqueeze and transpose to avoid [K*B] when using torch.Tensor.repeat
[B, ...] => [B*K, ...]
def repeat(tensor, K): """ [B, ...] => [B*K, ...] #-- Important --# Used unsqueeze and transpose to avoid [K*B] when using torch.Tensor.repeat """ if isinstance(tensor, torch.Tensor): B, *size = tensor.size() # repeat_size = [1] + [K] + [1] * (tensor.dim() - 1) # tensor = tensor.unsqueeze(1).repeat(*repeat_size).view(B * K, *size) expand_size = B, K, *size tensor = tensor.unsqueeze(1).expand(*expand_size).contiguous().view(B * K, *size) return tensor elif isinstance(tensor, list): out = [] for x in tensor: for _ in range(K): out.append(x.copy()) return out
[ "def", "repeat", "(", "tensor", ",", "K", ")", ":", "if", "isinstance", "(", "tensor", ",", "torch", ".", "Tensor", ")", ":", "B", ",", "", "*", "size", "=", "tensor", ".", "size", "(", ")", "# repeat_size = [1] + [K] + [1] * (tensor.dim() - 1)", "# tensor = tensor.unsqueeze(1).repeat(*repeat_size).view(B * K, *size)", "expand_size", "=", "B", ",", "K", ",", "", "*", "size", "tensor", "=", "tensor", ".", "unsqueeze", "(", "1", ")", ".", "expand", "(", "*", "expand_size", ")", ".", "contiguous", "(", ")", ".", "view", "(", "B", "*", "K", ",", "*", "size", ")", "return", "tensor", "elif", "isinstance", "(", "tensor", ",", "list", ")", ":", "out", "=", "[", "]", "for", "x", "in", "tensor", ":", "for", "_", "in", "range", "(", "K", ")", ":", "out", ".", "append", "(", "x", ".", "copy", "(", ")", ")", "return", "out" ]
[ 225, 0 ]
[ 244, 18 ]
python
en
['en', 'error', 'th']
False
ParallelDecoder.__init__
(self, embed_size=300, enc_hidden_size=512, dec_hidden_size=512, n_mixture=5, threshold=0.15, task='QG')
Parallel Decoder for Focus Selector
Parallel Decoder for Focus Selector
def __init__(self, embed_size=300, enc_hidden_size=512, dec_hidden_size=512, n_mixture=5, threshold=0.15, task='QG'): """Parallel Decoder for Focus Selector""" super().__init__() self.mixture_embedding = nn.Embedding(n_mixture, embed_size) # input_size = embed_size self.enc_hidden_size = enc_hidden_size self.dec_hidden_size = dec_hidden_size self.out_mlp = nn.Sequential( nn.Linear(enc_hidden_size + dec_hidden_size + embed_size, dec_hidden_size), nn.Tanh(), nn.Linear(dec_hidden_size, 1), ) self.threshold = threshold
[ "def", "__init__", "(", "self", ",", "embed_size", "=", "300", ",", "enc_hidden_size", "=", "512", ",", "dec_hidden_size", "=", "512", ",", "n_mixture", "=", "5", ",", "threshold", "=", "0.15", ",", "task", "=", "'QG'", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "mixture_embedding", "=", "nn", ".", "Embedding", "(", "n_mixture", ",", "embed_size", ")", "# input_size = embed_size", "self", ".", "enc_hidden_size", "=", "enc_hidden_size", "self", ".", "dec_hidden_size", "=", "dec_hidden_size", "self", ".", "out_mlp", "=", "nn", ".", "Sequential", "(", "nn", ".", "Linear", "(", "enc_hidden_size", "+", "dec_hidden_size", "+", "embed_size", ",", "dec_hidden_size", ")", ",", "nn", ".", "Tanh", "(", ")", ",", "nn", ".", "Linear", "(", "dec_hidden_size", ",", "1", ")", ",", ")", "self", ".", "threshold", "=", "threshold" ]
[ 87, 4 ]
[ 104, 34 ]
python
en
['da', 'en', 'en']
True
ValidatorInfoHandler.process_action
(self, request: Request)
For keeping output format
For keeping output format
def process_action(self, request: Request): self._validate_request_type(request) identifier, req_id, operation = get_request_data(request) logger.debug("Transaction {} with type {} started" .format(req_id, request.txn_type)) result = generate_action_result(request) result[DATA] = self.info_tool.info # Memory profiler needs only for debug purposes, # because collecting memory info it's a very long time operation # result[DATA].update(self.info_tool.memory_profiler) """For keeping output format""" result[DATA].update({'Memory_profiler': []}) result[DATA].update(self.info_tool._generate_software_info()) result[DATA].update(self.info_tool.extractions) # ToDo: also can be a long time operation, because we use external tools result[DATA].update(self.info_tool.node_disk_size) logger.debug("Transaction {} with type {} finished" .format(req_id, request.txn_type)) return result
[ "def", "process_action", "(", "self", ",", "request", ":", "Request", ")", ":", "self", ".", "_validate_request_type", "(", "request", ")", "identifier", ",", "req_id", ",", "operation", "=", "get_request_data", "(", "request", ")", "logger", ".", "debug", "(", "\"Transaction {} with type {} started\"", ".", "format", "(", "req_id", ",", "request", ".", "txn_type", ")", ")", "result", "=", "generate_action_result", "(", "request", ")", "result", "[", "DATA", "]", "=", "self", ".", "info_tool", ".", "info", "# Memory profiler needs only for debug purposes,", "# because collecting memory info it's a very long time operation", "# result[DATA].update(self.info_tool.memory_profiler)", "result", "[", "DATA", "]", ".", "update", "(", "{", "'Memory_profiler'", ":", "[", "]", "}", ")", "result", "[", "DATA", "]", ".", "update", "(", "self", ".", "info_tool", ".", "_generate_software_info", "(", ")", ")", "result", "[", "DATA", "]", ".", "update", "(", "self", ".", "info_tool", ".", "extractions", ")", "# ToDo: also can be a long time operation, because we use external tools", "result", "[", "DATA", "]", ".", "update", "(", "self", ".", "info_tool", ".", "node_disk_size", ")", "logger", ".", "debug", "(", "\"Transaction {} with type {} finished\"", ".", "format", "(", "req_id", ",", "request", ".", "txn_type", ")", ")", "return", "result" ]
[ 33, 4 ]
[ 51, 21 ]
python
en
['en', 'en', 'en']
True
PleaseAckDecorator.__init__
( self, message_id: str = None, on: Sequence[str] = None, )
Initialize a PleaseAckDecorator instance. Args: message_id: identifier of message to acknowledge, if not current message on: list of tokens describing circumstances for acknowledgement.
Initialize a PleaseAckDecorator instance.
def __init__( self, message_id: str = None, on: Sequence[str] = None, ): """ Initialize a PleaseAckDecorator instance. Args: message_id: identifier of message to acknowledge, if not current message on: list of tokens describing circumstances for acknowledgement. """ super().__init__() self.message_id = message_id self.on = list(on) if on else None
[ "def", "__init__", "(", "self", ",", "message_id", ":", "str", "=", "None", ",", "on", ":", "Sequence", "[", "str", "]", "=", "None", ",", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "message_id", "=", "message_id", "self", ".", "on", "=", "list", "(", "on", ")", "if", "on", "else", "None" ]
[ 18, 4 ]
[ 33, 42 ]
python
en
['en', 'error', 'th']
False
TestInjectionContext.test_settings_init
(self)
Test settings initialization.
Test settings initialization.
def test_settings_init(self): """Test settings initialization.""" assert self.test_instance.scope_name == self.test_instance.ROOT_SCOPE for key in self.test_settings: assert key in self.test_instance.settings assert self.test_instance.settings[key] == self.test_settings[key]
[ "def", "test_settings_init", "(", "self", ")", ":", "assert", "self", ".", "test_instance", ".", "scope_name", "==", "self", ".", "test_instance", ".", "ROOT_SCOPE", "for", "key", "in", "self", ".", "test_settings", ":", "assert", "key", "in", "self", ".", "test_instance", ".", "settings", "assert", "self", ".", "test_instance", ".", "settings", "[", "key", "]", "==", "self", ".", "test_settings", "[", "key", "]" ]
[ 14, 4 ]
[ 19, 78 ]
python
en
['en', 'fy', 'en']
True
TestInjectionContext.test_simple_scope
(self)
Test scope entrance and exit.
Test scope entrance and exit.
def test_simple_scope(self): """Test scope entrance and exit.""" with self.assertRaises(InjectionContextError): self.test_instance.start_scope(None) with self.assertRaises(InjectionContextError): self.test_instance.start_scope(self.test_instance.ROOT_SCOPE) context = self.test_instance.start_scope(self.test_scope) assert context.scope_name == self.test_scope with self.assertRaises(InjectionContextError): context.start_scope(self.test_instance.ROOT_SCOPE) assert self.test_instance.scope_name == self.test_instance.ROOT_SCOPE
[ "def", "test_simple_scope", "(", "self", ")", ":", "with", "self", ".", "assertRaises", "(", "InjectionContextError", ")", ":", "self", ".", "test_instance", ".", "start_scope", "(", "None", ")", "with", "self", ".", "assertRaises", "(", "InjectionContextError", ")", ":", "self", ".", "test_instance", ".", "start_scope", "(", "self", ".", "test_instance", ".", "ROOT_SCOPE", ")", "context", "=", "self", ".", "test_instance", ".", "start_scope", "(", "self", ".", "test_scope", ")", "assert", "context", ".", "scope_name", "==", "self", ".", "test_scope", "with", "self", ".", "assertRaises", "(", "InjectionContextError", ")", ":", "context", ".", "start_scope", "(", "self", ".", "test_instance", ".", "ROOT_SCOPE", ")", "assert", "self", ".", "test_instance", ".", "scope_name", "==", "self", ".", "test_instance", ".", "ROOT_SCOPE" ]
[ 21, 4 ]
[ 31, 77 ]
python
en
['en', 'en', 'en']
True
TestInjectionContext.test_settings_scope
(self)
Test scoped settings.
Test scoped settings.
def test_settings_scope(self): """Test scoped settings.""" upd_settings = {self.test_key: "NEWVAL"} context = self.test_instance.start_scope(self.test_scope, upd_settings) assert context.settings[self.test_key] == "NEWVAL" assert self.test_instance.settings[self.test_key] == self.test_value root = context.injector_for_scope(context.ROOT_SCOPE) assert root.settings[self.test_key] == self.test_value
[ "def", "test_settings_scope", "(", "self", ")", ":", "upd_settings", "=", "{", "self", ".", "test_key", ":", "\"NEWVAL\"", "}", "context", "=", "self", ".", "test_instance", ".", "start_scope", "(", "self", ".", "test_scope", ",", "upd_settings", ")", "assert", "context", ".", "settings", "[", "self", ".", "test_key", "]", "==", "\"NEWVAL\"", "assert", "self", ".", "test_instance", ".", "settings", "[", "self", ".", "test_key", "]", "==", "self", ".", "test_value", "root", "=", "context", ".", "injector_for_scope", "(", "context", ".", "ROOT_SCOPE", ")", "assert", "root", ".", "settings", "[", "self", ".", "test_key", "]", "==", "self", ".", "test_value" ]
[ 33, 4 ]
[ 40, 62 ]
python
en
['en', 'fy', 'en']
True
TestInjectionContext.test_inject_simple
(self)
Test a basic injection.
Test a basic injection.
async def test_inject_simple(self): """Test a basic injection.""" assert (await self.test_instance.inject(str, required=False)) is None with self.assertRaises(InjectorError): await self.test_instance.inject(str) self.test_instance.injector.bind_instance(str, self.test_value) assert (await self.test_instance.inject(str)) is self.test_value
[ "async", "def", "test_inject_simple", "(", "self", ")", ":", "assert", "(", "await", "self", ".", "test_instance", ".", "inject", "(", "str", ",", "required", "=", "False", ")", ")", "is", "None", "with", "self", ".", "assertRaises", "(", "InjectorError", ")", ":", "await", "self", ".", "test_instance", ".", "inject", "(", "str", ")", "self", ".", "test_instance", ".", "injector", ".", "bind_instance", "(", "str", ",", "self", ".", "test_value", ")", "assert", "(", "await", "self", ".", "test_instance", ".", "inject", "(", "str", ")", ")", "is", "self", ".", "test_value" ]
[ 42, 4 ]
[ 48, 72 ]
python
en
['sl', 'en', 'en']
True
TestInjectionContext.test_inject_scope
(self)
Test a scoped injection.
Test a scoped injection.
async def test_inject_scope(self): """Test a scoped injection.""" context = self.test_instance.start_scope(self.test_scope) assert (await context.inject(str, required=False)) is None context.injector.bind_instance(str, self.test_value) assert (await context.inject(str)) is self.test_value assert (await self.test_instance.inject(str, required=False)) is None root = context.injector_for_scope(context.ROOT_SCOPE) assert (await root.inject(str, required=False)) is None
[ "async", "def", "test_inject_scope", "(", "self", ")", ":", "context", "=", "self", ".", "test_instance", ".", "start_scope", "(", "self", ".", "test_scope", ")", "assert", "(", "await", "context", ".", "inject", "(", "str", ",", "required", "=", "False", ")", ")", "is", "None", "context", ".", "injector", ".", "bind_instance", "(", "str", ",", "self", ".", "test_value", ")", "assert", "(", "await", "context", ".", "inject", "(", "str", ")", ")", "is", "self", ".", "test_value", "assert", "(", "await", "self", ".", "test_instance", ".", "inject", "(", "str", ",", "required", "=", "False", ")", ")", "is", "None", "root", "=", "context", ".", "injector_for_scope", "(", "context", ".", "ROOT_SCOPE", ")", "assert", "(", "await", "root", ".", "inject", "(", "str", ",", "required", "=", "False", ")", ")", "is", "None" ]
[ 50, 4 ]
[ 58, 63 ]
python
en
['en', 'en', 'en']
True
Title.font
(self)
Sets this axis' title font. Note that the title's font used to be customized by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.layout.ternary.aaxis.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- plotly.graph_objs.layout.ternary.aaxis.title.Font
Sets this axis' title font. Note that the title's font used to be customized by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.layout.ternary.aaxis.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size
def font(self): """ Sets this axis' title font. Note that the title's font used to be customized by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.layout.ternary.aaxis.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- plotly.graph_objs.layout.ternary.aaxis.title.Font """ return self["font"]
[ "def", "font", "(", "self", ")", ":", "return", "self", "[", "\"font\"", "]" ]
[ 15, 4 ]
[ 53, 27 ]
python
en
['en', 'error', 'th']
False
Title.text
(self)
Sets the title of this axis. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
Sets the title of this axis. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string
def text(self): """ Sets the title of this axis. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"]
[ "def", "text", "(", "self", ")", ":", "return", "self", "[", "\"text\"", "]" ]
[ 62, 4 ]
[ 76, 27 ]
python
en
['en', 'error', 'th']
False
Title.__init__
(self, arg=None, font=None, text=None, **kwargs)
Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.ternary.aaxis.Title` font Sets this axis' title font. Note that the title's font used to be customized by the now deprecated `titlefont` attribute. text Sets the title of this axis. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. Returns ------- Title
Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.ternary.aaxis.Title` font Sets this axis' title font. Note that the title's font used to be customized by the now deprecated `titlefont` attribute. text Sets the title of this axis. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated.
def __init__(self, arg=None, font=None, text=None, **kwargs): """ Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.ternary.aaxis.Title` font Sets this axis' title font. Note that the title's font used to be customized by the now deprecated `titlefont` attribute. text Sets the title of this axis. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. Returns ------- Title """ super(Title, self).__init__("title") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.layout.ternary.aaxis.Title constructor must be a dict or an instance of :class:`plotly.graph_objs.layout.ternary.aaxis.Title`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("font", None) _v = font if font is not None else _v if _v is not None: self["font"] = _v _v = arg.pop("text", None) _v = text if text is not None else _v if _v is not None: self["text"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "font", "=", "None", ",", "text", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Title", ",", "self", ")", ".", "__init__", "(", "\"title\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.layout.ternary.aaxis.Title \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.layout.ternary.aaxis.Title`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"font\"", ",", "None", ")", "_v", "=", "font", "if", "font", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"font\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"text\"", ",", "None", ")", "_v", "=", "text", "if", "text", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"text\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 98, 4 ]
[ 166, 34 ]
python
en
['en', 'error', 'th']
False
BaseFigure.__init__
( self, data=None, layout_plotly=None, frames=None, skip_invalid=False, **kwargs )
Construct a BaseFigure object Parameters ---------- data One of: - A list or tuple of trace objects (or dicts that can be coerced into trace objects) - If `data` is a dict that contains a 'data', 'layout', or 'frames' key then these values are used to construct the figure. - If `data` is a `BaseFigure` instance then the `data`, `layout`, and `frames` properties are extracted from the input figure layout_plotly The plotly layout dict. Note: this property is named `layout_plotly` rather than `layout` to deconflict it with the `layout` constructor parameter of the `widgets.DOMWidget` ipywidgets class, as the `BaseFigureWidget` class is a subclass of both BaseFigure and widgets.DOMWidget. If the `data` property is a BaseFigure instance, or a dict that contains a 'layout' key, then this property is ignored. frames A list or tuple of `plotly.graph_objs.Frame` objects (or dicts that can be coerced into Frame objects) If the `data` property is a BaseFigure instance, or a dict that contains a 'frames' key, then this property is ignored. skip_invalid: bool If True, invalid properties in the figure specification will be skipped silently. If False (default) invalid properties in the figure specification will result in a ValueError Raises ------ ValueError if a property in the specification of data, layout, or frames is invalid AND skip_invalid is False
Construct a BaseFigure object
def __init__( self, data=None, layout_plotly=None, frames=None, skip_invalid=False, **kwargs ): """ Construct a BaseFigure object Parameters ---------- data One of: - A list or tuple of trace objects (or dicts that can be coerced into trace objects) - If `data` is a dict that contains a 'data', 'layout', or 'frames' key then these values are used to construct the figure. - If `data` is a `BaseFigure` instance then the `data`, `layout`, and `frames` properties are extracted from the input figure layout_plotly The plotly layout dict. Note: this property is named `layout_plotly` rather than `layout` to deconflict it with the `layout` constructor parameter of the `widgets.DOMWidget` ipywidgets class, as the `BaseFigureWidget` class is a subclass of both BaseFigure and widgets.DOMWidget. If the `data` property is a BaseFigure instance, or a dict that contains a 'layout' key, then this property is ignored. frames A list or tuple of `plotly.graph_objs.Frame` objects (or dicts that can be coerced into Frame objects) If the `data` property is a BaseFigure instance, or a dict that contains a 'frames' key, then this property is ignored. skip_invalid: bool If True, invalid properties in the figure specification will be skipped silently. If False (default) invalid properties in the figure specification will result in a ValueError Raises ------ ValueError if a property in the specification of data, layout, or frames is invalid AND skip_invalid is False """ from .validators import DataValidator, LayoutValidator, FramesValidator super(BaseFigure, self).__init__() # Initialize validation self._validate = kwargs.pop("_validate", True) # Assign layout_plotly to layout # ------------------------------ # See docstring note for explanation layout = layout_plotly # Subplot properties # ------------------ # These properties are used by the tools.make_subplots logic. # We initialize them to None here, before checking if the input data # object is a BaseFigure, or a dict with _grid_str and _grid_ref # properties, in which case we bring over the _grid* properties of # the input self._grid_str = None self._grid_ref = None # Handle case where data is a Figure or Figure-like dict # ------------------------------------------------------ if isinstance(data, BaseFigure): # Bring over subplot fields self._grid_str = data._grid_str self._grid_ref = data._grid_ref # Extract data, layout, and frames data, layout, frames = data.data, data.layout, data.frames elif isinstance(data, dict) and ( "data" in data or "layout" in data or "frames" in data ): # Bring over subplot fields self._grid_str = data.get("_grid_str", None) self._grid_ref = data.get("_grid_ref", None) # Extract data, layout, and frames data, layout, frames = ( data.get("data", None), data.get("layout", None), data.get("frames", None), ) # Handle data (traces) # -------------------- # ### Construct data validator ### # This is the validator that handles importing sequences of trace # objects self._data_validator = DataValidator(set_uid=self._set_trace_uid) # ### Import traces ### data = self._data_validator.validate_coerce( data, skip_invalid=skip_invalid, _validate=self._validate ) # ### Save tuple of trace objects ### self._data_objs = data # ### Import clone of trace properties ### # The _data property is a list of dicts containing the properties # explicitly set by the user for each trace. self._data = [deepcopy(trace._props) for trace in data] # ### Create data defaults ### # _data_defaults is a tuple of dicts, one for each trace. When # running in a widget context, these defaults are populated with # all property values chosen by the Plotly.js library that # aren't explicitly specified by the user. # # Note: No property should exist in both the _data and # _data_defaults for the same trace. self._data_defaults = [{} for _ in data] # ### Reparent trace objects ### for trace_ind, trace in enumerate(data): # By setting the trace's parent to be this figure, we tell the # trace object to use the figure's _data and _data_defaults # dicts to get/set it's properties, rather than using the trace # object's internal _orphan_props dict. trace._parent = self # We clear the orphan props since the trace no longer needs then trace._orphan_props.clear() # Set trace index trace._trace_ind = trace_ind # Layout # ------ # ### Construct layout validator ### # This is the validator that handles importing Layout objects self._layout_validator = LayoutValidator() # ### Import Layout ### self._layout_obj = self._layout_validator.validate_coerce( layout, skip_invalid=skip_invalid, _validate=self._validate ) # ### Import clone of layout properties ### self._layout = deepcopy(self._layout_obj._props) # ### Initialize layout defaults dict ### self._layout_defaults = {} # ### Reparent layout object ### self._layout_obj._orphan_props.clear() self._layout_obj._parent = self # Config # ------ # Pass along default config to the front end. For now this just # ensures that the plotly domain url gets passed to the front end. # In the future we can extend this to allow the user to supply # arbitrary config options like in plotly.offline.plot/iplot. But # this will require a fair amount of testing to determine which # options are compatible with FigureWidget. from plotly.offline.offline import _get_jconfig self._config = _get_jconfig(None) # Frames # ------ # ### Construct frames validator ### # This is the validator that handles importing sequences of frame # objects self._frames_validator = FramesValidator() # ### Import frames ### self._frame_objs = self._frames_validator.validate_coerce( frames, skip_invalid=skip_invalid ) # Note: Because frames are not currently supported in the widget # context, we don't need to follow the pattern above and create # _frames and _frame_defaults properties and then reparent the # frames. The figure doesn't need to be notified of # changes to the properties in the frames object hierarchy. # Context manager # --------------- # ### batch mode indicator ### # Flag that indicates whether we're currently inside a batch_*() # context self._in_batch_mode = False # ### Batch trace edits ### # Dict from trace indexes to trace edit dicts. These trace edit dicts # are suitable as `data` elements of Plotly.animate, but not # the Plotly.update (See `_build_update_params_from_batch`) self._batch_trace_edits = OrderedDict() # ### Batch layout edits ### # Dict from layout properties to new layout values. This dict is # directly suitable for use in Plotly.animate and Plotly.update self._batch_layout_edits = OrderedDict() # Animation property validators # ----------------------------- from . import animation self._animation_duration_validator = animation.DurationValidator() self._animation_easing_validator = animation.EasingValidator() # Template # -------- # ### Check for default template ### self._initialize_layout_template() # Process kwargs # -------------- for k, v in kwargs.items(): if k in self: self[k] = v elif not skip_invalid: raise TypeError("invalid Figure property: {}".format(k))
[ "def", "__init__", "(", "self", ",", "data", "=", "None", ",", "layout_plotly", "=", "None", ",", "frames", "=", "None", ",", "skip_invalid", "=", "False", ",", "*", "*", "kwargs", ")", ":", "from", ".", "validators", "import", "DataValidator", ",", "LayoutValidator", ",", "FramesValidator", "super", "(", "BaseFigure", ",", "self", ")", ".", "__init__", "(", ")", "# Initialize validation", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Assign layout_plotly to layout", "# ------------------------------", "# See docstring note for explanation", "layout", "=", "layout_plotly", "# Subplot properties", "# ------------------", "# These properties are used by the tools.make_subplots logic.", "# We initialize them to None here, before checking if the input data", "# object is a BaseFigure, or a dict with _grid_str and _grid_ref", "# properties, in which case we bring over the _grid* properties of", "# the input", "self", ".", "_grid_str", "=", "None", "self", ".", "_grid_ref", "=", "None", "# Handle case where data is a Figure or Figure-like dict", "# ------------------------------------------------------", "if", "isinstance", "(", "data", ",", "BaseFigure", ")", ":", "# Bring over subplot fields", "self", ".", "_grid_str", "=", "data", ".", "_grid_str", "self", ".", "_grid_ref", "=", "data", ".", "_grid_ref", "# Extract data, layout, and frames", "data", ",", "layout", ",", "frames", "=", "data", ".", "data", ",", "data", ".", "layout", ",", "data", ".", "frames", "elif", "isinstance", "(", "data", ",", "dict", ")", "and", "(", "\"data\"", "in", "data", "or", "\"layout\"", "in", "data", "or", "\"frames\"", "in", "data", ")", ":", "# Bring over subplot fields", "self", ".", "_grid_str", "=", "data", ".", "get", "(", "\"_grid_str\"", ",", "None", ")", "self", ".", "_grid_ref", "=", "data", ".", "get", "(", "\"_grid_ref\"", ",", "None", ")", "# Extract data, layout, and frames", "data", ",", "layout", ",", "frames", "=", "(", "data", ".", "get", "(", "\"data\"", ",", "None", ")", ",", "data", ".", "get", "(", "\"layout\"", ",", "None", ")", ",", "data", ".", "get", "(", "\"frames\"", ",", "None", ")", ",", ")", "# Handle data (traces)", "# --------------------", "# ### Construct data validator ###", "# This is the validator that handles importing sequences of trace", "# objects", "self", ".", "_data_validator", "=", "DataValidator", "(", "set_uid", "=", "self", ".", "_set_trace_uid", ")", "# ### Import traces ###", "data", "=", "self", ".", "_data_validator", ".", "validate_coerce", "(", "data", ",", "skip_invalid", "=", "skip_invalid", ",", "_validate", "=", "self", ".", "_validate", ")", "# ### Save tuple of trace objects ###", "self", ".", "_data_objs", "=", "data", "# ### Import clone of trace properties ###", "# The _data property is a list of dicts containing the properties", "# explicitly set by the user for each trace.", "self", ".", "_data", "=", "[", "deepcopy", "(", "trace", ".", "_props", ")", "for", "trace", "in", "data", "]", "# ### Create data defaults ###", "# _data_defaults is a tuple of dicts, one for each trace. When", "# running in a widget context, these defaults are populated with", "# all property values chosen by the Plotly.js library that", "# aren't explicitly specified by the user.", "#", "# Note: No property should exist in both the _data and", "# _data_defaults for the same trace.", "self", ".", "_data_defaults", "=", "[", "{", "}", "for", "_", "in", "data", "]", "# ### Reparent trace objects ###", "for", "trace_ind", ",", "trace", "in", "enumerate", "(", "data", ")", ":", "# By setting the trace's parent to be this figure, we tell the", "# trace object to use the figure's _data and _data_defaults", "# dicts to get/set it's properties, rather than using the trace", "# object's internal _orphan_props dict.", "trace", ".", "_parent", "=", "self", "# We clear the orphan props since the trace no longer needs then", "trace", ".", "_orphan_props", ".", "clear", "(", ")", "# Set trace index", "trace", ".", "_trace_ind", "=", "trace_ind", "# Layout", "# ------", "# ### Construct layout validator ###", "# This is the validator that handles importing Layout objects", "self", ".", "_layout_validator", "=", "LayoutValidator", "(", ")", "# ### Import Layout ###", "self", ".", "_layout_obj", "=", "self", ".", "_layout_validator", ".", "validate_coerce", "(", "layout", ",", "skip_invalid", "=", "skip_invalid", ",", "_validate", "=", "self", ".", "_validate", ")", "# ### Import clone of layout properties ###", "self", ".", "_layout", "=", "deepcopy", "(", "self", ".", "_layout_obj", ".", "_props", ")", "# ### Initialize layout defaults dict ###", "self", ".", "_layout_defaults", "=", "{", "}", "# ### Reparent layout object ###", "self", ".", "_layout_obj", ".", "_orphan_props", ".", "clear", "(", ")", "self", ".", "_layout_obj", ".", "_parent", "=", "self", "# Config", "# ------", "# Pass along default config to the front end. For now this just", "# ensures that the plotly domain url gets passed to the front end.", "# In the future we can extend this to allow the user to supply", "# arbitrary config options like in plotly.offline.plot/iplot. But", "# this will require a fair amount of testing to determine which", "# options are compatible with FigureWidget.", "from", "plotly", ".", "offline", ".", "offline", "import", "_get_jconfig", "self", ".", "_config", "=", "_get_jconfig", "(", "None", ")", "# Frames", "# ------", "# ### Construct frames validator ###", "# This is the validator that handles importing sequences of frame", "# objects", "self", ".", "_frames_validator", "=", "FramesValidator", "(", ")", "# ### Import frames ###", "self", ".", "_frame_objs", "=", "self", ".", "_frames_validator", ".", "validate_coerce", "(", "frames", ",", "skip_invalid", "=", "skip_invalid", ")", "# Note: Because frames are not currently supported in the widget", "# context, we don't need to follow the pattern above and create", "# _frames and _frame_defaults properties and then reparent the", "# frames. The figure doesn't need to be notified of", "# changes to the properties in the frames object hierarchy.", "# Context manager", "# ---------------", "# ### batch mode indicator ###", "# Flag that indicates whether we're currently inside a batch_*()", "# context", "self", ".", "_in_batch_mode", "=", "False", "# ### Batch trace edits ###", "# Dict from trace indexes to trace edit dicts. These trace edit dicts", "# are suitable as `data` elements of Plotly.animate, but not", "# the Plotly.update (See `_build_update_params_from_batch`)", "self", ".", "_batch_trace_edits", "=", "OrderedDict", "(", ")", "# ### Batch layout edits ###", "# Dict from layout properties to new layout values. This dict is", "# directly suitable for use in Plotly.animate and Plotly.update", "self", ".", "_batch_layout_edits", "=", "OrderedDict", "(", ")", "# Animation property validators", "# -----------------------------", "from", ".", "import", "animation", "self", ".", "_animation_duration_validator", "=", "animation", ".", "DurationValidator", "(", ")", "self", ".", "_animation_easing_validator", "=", "animation", ".", "EasingValidator", "(", ")", "# Template", "# --------", "# ### Check for default template ###", "self", ".", "_initialize_layout_template", "(", ")", "# Process kwargs", "# --------------", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", "in", "self", ":", "self", "[", "k", "]", "=", "v", "elif", "not", "skip_invalid", ":", "raise", "TypeError", "(", "\"invalid Figure property: {}\"", ".", "format", "(", "k", ")", ")" ]
[ 43, 4 ]
[ 270, 72 ]
python
en
['en', 'error', 'th']
False
BaseFigure.__reduce__
(self)
Custom implementation of reduce is used to support deep copying and pickling
Custom implementation of reduce is used to support deep copying and pickling
def __reduce__(self): """ Custom implementation of reduce is used to support deep copying and pickling """ props = self.to_dict() props["_grid_str"] = self._grid_str props["_grid_ref"] = self._grid_ref return (self.__class__, (props,))
[ "def", "__reduce__", "(", "self", ")", ":", "props", "=", "self", ".", "to_dict", "(", ")", "props", "[", "\"_grid_str\"", "]", "=", "self", ".", "_grid_str", "props", "[", "\"_grid_ref\"", "]", "=", "self", ".", "_grid_ref", "return", "(", "self", ".", "__class__", ",", "(", "props", ",", ")", ")" ]
[ 274, 4 ]
[ 282, 41 ]
python
en
['en', 'error', 'th']
False
BaseFigure.__setattr__
(self, prop, value)
Parameters ---------- prop : str The name of a direct child of this object value New property value Returns ------- None
Parameters ---------- prop : str The name of a direct child of this object value New property value Returns ------- None
def __setattr__(self, prop, value): """ Parameters ---------- prop : str The name of a direct child of this object value New property value Returns ------- None """ if prop.startswith("_") or hasattr(self, prop): # Let known properties and private properties through super(BaseFigure, self).__setattr__(prop, value) else: # Raise error on unknown public properties raise AttributeError(prop)
[ "def", "__setattr__", "(", "self", ",", "prop", ",", "value", ")", ":", "if", "prop", ".", "startswith", "(", "\"_\"", ")", "or", "hasattr", "(", "self", ",", "prop", ")", ":", "# Let known properties and private properties through", "super", "(", "BaseFigure", ",", "self", ")", ".", "__setattr__", "(", "prop", ",", "value", ")", "else", ":", "# Raise error on unknown public properties", "raise", "AttributeError", "(", "prop", ")" ]
[ 325, 4 ]
[ 342, 38 ]
python
en
['en', 'error', 'th']
False
BaseFigure.__repr__
(self)
Customize Figure representation when displayed in the terminal/notebook
Customize Figure representation when displayed in the terminal/notebook
def __repr__(self): """ Customize Figure representation when displayed in the terminal/notebook """ props = self.to_plotly_json() # Elide template template_props = props.get("layout", {}).get("template", {}) if template_props: props["layout"]["template"] = "..." repr_str = BasePlotlyType._build_repr_for_class( props=props, class_name=self.__class__.__name__ ) return repr_str
[ "def", "__repr__", "(", "self", ")", ":", "props", "=", "self", ".", "to_plotly_json", "(", ")", "# Elide template", "template_props", "=", "props", ".", "get", "(", "\"layout\"", ",", "{", "}", ")", ".", "get", "(", "\"template\"", ",", "{", "}", ")", "if", "template_props", ":", "props", "[", "\"layout\"", "]", "[", "\"template\"", "]", "=", "\"...\"", "repr_str", "=", "BasePlotlyType", ".", "_build_repr_for_class", "(", "props", "=", "props", ",", "class_name", "=", "self", ".", "__class__", ".", "__name__", ")", "return", "repr_str" ]
[ 403, 4 ]
[ 419, 23 ]
python
en
['en', 'error', 'th']
False
BaseFigure._repr_html_
(self)
Customize html representation
Customize html representation
def _repr_html_(self): """ Customize html representation """ bundle = self._repr_mimebundle_() if "text/html" in bundle: return bundle["text/html"] else: return self.to_html(full_html=False, include_plotlyjs="cdn")
[ "def", "_repr_html_", "(", "self", ")", ":", "bundle", "=", "self", ".", "_repr_mimebundle_", "(", ")", "if", "\"text/html\"", "in", "bundle", ":", "return", "bundle", "[", "\"text/html\"", "]", "else", ":", "return", "self", ".", "to_html", "(", "full_html", "=", "False", ",", "include_plotlyjs", "=", "\"cdn\"", ")" ]
[ 421, 4 ]
[ 429, 72 ]
python
en
['en', 'error', 'th']
False
BaseFigure._repr_mimebundle_
(self, include=None, exclude=None, validate=True, **kwargs)
Return mimebundle corresponding to default renderer.
Return mimebundle corresponding to default renderer.
def _repr_mimebundle_(self, include=None, exclude=None, validate=True, **kwargs): """ Return mimebundle corresponding to default renderer. """ import plotly.io as pio renderer_str = pio.renderers.default renderers = pio._renderers.renderers renderer_names = renderers._validate_coerce_renderers(renderer_str) renderers_list = [renderers[name] for name in renderer_names] from plotly.io._utils import validate_coerce_fig_to_dict from plotly.io._renderers import MimetypeRenderer fig_dict = validate_coerce_fig_to_dict(self, validate) # Mimetype renderers bundle = {} for renderer in renderers_list: if isinstance(renderer, MimetypeRenderer): bundle.update(renderer.to_mimebundle(fig_dict)) return bundle
[ "def", "_repr_mimebundle_", "(", "self", ",", "include", "=", "None", ",", "exclude", "=", "None", ",", "validate", "=", "True", ",", "*", "*", "kwargs", ")", ":", "import", "plotly", ".", "io", "as", "pio", "renderer_str", "=", "pio", ".", "renderers", ".", "default", "renderers", "=", "pio", ".", "_renderers", ".", "renderers", "renderer_names", "=", "renderers", ".", "_validate_coerce_renderers", "(", "renderer_str", ")", "renderers_list", "=", "[", "renderers", "[", "name", "]", "for", "name", "in", "renderer_names", "]", "from", "plotly", ".", "io", ".", "_utils", "import", "validate_coerce_fig_to_dict", "from", "plotly", ".", "io", ".", "_renderers", "import", "MimetypeRenderer", "fig_dict", "=", "validate_coerce_fig_to_dict", "(", "self", ",", "validate", ")", "# Mimetype renderers", "bundle", "=", "{", "}", "for", "renderer", "in", "renderers_list", ":", "if", "isinstance", "(", "renderer", ",", "MimetypeRenderer", ")", ":", "bundle", ".", "update", "(", "renderer", ".", "to_mimebundle", "(", "fig_dict", ")", ")", "return", "bundle" ]
[ 431, 4 ]
[ 450, 21 ]
python
en
['en', 'error', 'th']
False
BaseFigure._ipython_display_
(self)
Handle rich display of figures in ipython contexts
Handle rich display of figures in ipython contexts
def _ipython_display_(self): """ Handle rich display of figures in ipython contexts """ import plotly.io as pio if pio.renderers.render_on_display and pio.renderers.default: pio.show(self) else: print(repr(self))
[ "def", "_ipython_display_", "(", "self", ")", ":", "import", "plotly", ".", "io", "as", "pio", "if", "pio", ".", "renderers", ".", "render_on_display", "and", "pio", ".", "renderers", ".", "default", ":", "pio", ".", "show", "(", "self", ")", "else", ":", "print", "(", "repr", "(", "self", ")", ")" ]
[ 452, 4 ]
[ 461, 29 ]
python
en
['en', 'error', 'th']
False
BaseFigure.update
(self, dict1=None, overwrite=False, **kwargs)
Update the properties of the figure with a dict and/or with keyword arguments. This recursively updates the structure of the figure object with the values in the input dict / keyword arguments. Parameters ---------- dict1 : dict Dictionary of properties to be updated overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. kwargs : Keyword/value pair of properties to be updated Examples -------- >>> import plotly.graph_objs as go >>> fig = go.Figure(data=[{'y': [1, 2, 3]}]) >>> fig.update(data=[{'y': [4, 5, 6]}]) # doctest: +ELLIPSIS Figure(...) >>> fig.to_plotly_json() # doctest: +SKIP {'data': [{'type': 'scatter', 'uid': 'e86a7c7a-346a-11e8-8aa8-a0999b0c017b', 'y': array([4, 5, 6], dtype=int32)}], 'layout': {}} >>> fig = go.Figure(layout={'xaxis': ... {'color': 'green', ... 'range': [0, 1]}}) >>> fig.update({'layout': {'xaxis': {'color': 'pink'}}}) # doctest: +ELLIPSIS Figure(...) >>> fig.to_plotly_json() # doctest: +SKIP {'data': [], 'layout': {'xaxis': {'color': 'pink', 'range': [0, 1]}}} Returns ------- BaseFigure Updated figure
Update the properties of the figure with a dict and/or with keyword arguments.
def update(self, dict1=None, overwrite=False, **kwargs): """ Update the properties of the figure with a dict and/or with keyword arguments. This recursively updates the structure of the figure object with the values in the input dict / keyword arguments. Parameters ---------- dict1 : dict Dictionary of properties to be updated overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. kwargs : Keyword/value pair of properties to be updated Examples -------- >>> import plotly.graph_objs as go >>> fig = go.Figure(data=[{'y': [1, 2, 3]}]) >>> fig.update(data=[{'y': [4, 5, 6]}]) # doctest: +ELLIPSIS Figure(...) >>> fig.to_plotly_json() # doctest: +SKIP {'data': [{'type': 'scatter', 'uid': 'e86a7c7a-346a-11e8-8aa8-a0999b0c017b', 'y': array([4, 5, 6], dtype=int32)}], 'layout': {}} >>> fig = go.Figure(layout={'xaxis': ... {'color': 'green', ... 'range': [0, 1]}}) >>> fig.update({'layout': {'xaxis': {'color': 'pink'}}}) # doctest: +ELLIPSIS Figure(...) >>> fig.to_plotly_json() # doctest: +SKIP {'data': [], 'layout': {'xaxis': {'color': 'pink', 'range': [0, 1]}}} Returns ------- BaseFigure Updated figure """ with self.batch_update(): for d in [dict1, kwargs]: if d: for k, v in d.items(): update_target = self[k] if update_target == () or overwrite: if k == "data": # Overwrite all traces as special due to # restrictions on trace assignment self.data = () self.add_traces(v) else: # Accept v self[k] = v elif ( isinstance(update_target, BasePlotlyType) and isinstance(v, (dict, BasePlotlyType)) ) or ( isinstance(update_target, tuple) and isinstance(update_target[0], BasePlotlyType) ): BaseFigure._perform_update(self[k], v) else: self[k] = v return self
[ "def", "update", "(", "self", ",", "dict1", "=", "None", ",", "overwrite", "=", "False", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "batch_update", "(", ")", ":", "for", "d", "in", "[", "dict1", ",", "kwargs", "]", ":", "if", "d", ":", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "update_target", "=", "self", "[", "k", "]", "if", "update_target", "==", "(", ")", "or", "overwrite", ":", "if", "k", "==", "\"data\"", ":", "# Overwrite all traces as special due to", "# restrictions on trace assignment", "self", ".", "data", "=", "(", ")", "self", ".", "add_traces", "(", "v", ")", "else", ":", "# Accept v", "self", "[", "k", "]", "=", "v", "elif", "(", "isinstance", "(", "update_target", ",", "BasePlotlyType", ")", "and", "isinstance", "(", "v", ",", "(", "dict", ",", "BasePlotlyType", ")", ")", ")", "or", "(", "isinstance", "(", "update_target", ",", "tuple", ")", "and", "isinstance", "(", "update_target", "[", "0", "]", ",", "BasePlotlyType", ")", ")", ":", "BaseFigure", ".", "_perform_update", "(", "self", "[", "k", "]", ",", "v", ")", "else", ":", "self", "[", "k", "]", "=", "v", "return", "self" ]
[ 463, 4 ]
[ 534, 19 ]
python
en
['en', 'error', 'th']
False
BaseFigure.pop
(self, key, *args)
Remove the value associated with the specified key and return it Parameters ---------- key: str Property name dflt The default value to return if key was not found in figure Returns ------- value The removed value that was previously associated with key Raises ------ KeyError If key is not in object and no dflt argument specified
Remove the value associated with the specified key and return it
def pop(self, key, *args): """ Remove the value associated with the specified key and return it Parameters ---------- key: str Property name dflt The default value to return if key was not found in figure Returns ------- value The removed value that was previously associated with key Raises ------ KeyError If key is not in object and no dflt argument specified """ # Handle default if key not in self and args: return args[0] elif key in self: val = self[key] self[key] = None return val else: raise KeyError(key)
[ "def", "pop", "(", "self", ",", "key", ",", "*", "args", ")", ":", "# Handle default", "if", "key", "not", "in", "self", "and", "args", ":", "return", "args", "[", "0", "]", "elif", "key", "in", "self", ":", "val", "=", "self", "[", "key", "]", "self", "[", "key", "]", "=", "None", "return", "val", "else", ":", "raise", "KeyError", "(", "key", ")" ]
[ 536, 4 ]
[ 565, 31 ]
python
en
['en', 'error', 'th']
False
BaseFigure.data
(self)
The `data` property is a tuple of the figure's trace objects Returns ------- tuple[BaseTraceType]
The `data` property is a tuple of the figure's trace objects
def data(self): """ The `data` property is a tuple of the figure's trace objects Returns ------- tuple[BaseTraceType] """ return self["data"]
[ "def", "data", "(", "self", ")", ":", "return", "self", "[", "\"data\"", "]" ]
[ 570, 4 ]
[ 578, 27 ]
python
en
['en', 'error', 'th']
False
BaseFigure.select_traces
(self, selector=None, row=None, col=None, secondary_y=None)
Select traces from a particular subplot cell and/or traces that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all traces are selected. row, col: int or None (default None) Subplot row and column index of traces to select. To select traces by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all traces are selected. secondary_y: boolean or None (default None) * If True, only select traces associated with the secondary y-axis of the subplot. * If False, only select traces associated with the primary y-axis of the subplot. * If None (the default), do not filter traces based on secondary y-axis. To select traces by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the traces that satisfy all of the specified selection criteria
Select traces from a particular subplot cell and/or traces that satisfy custom selection criteria.
def select_traces(self, selector=None, row=None, col=None, secondary_y=None): """ Select traces from a particular subplot cell and/or traces that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all traces are selected. row, col: int or None (default None) Subplot row and column index of traces to select. To select traces by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all traces are selected. secondary_y: boolean or None (default None) * If True, only select traces associated with the secondary y-axis of the subplot. * If False, only select traces associated with the primary y-axis of the subplot. * If None (the default), do not filter traces based on secondary y-axis. To select traces by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the traces that satisfy all of the specified selection criteria """ if not selector: selector = {} if row is not None or col is not None or secondary_y is not None: grid_ref = self._validate_get_grid_ref() filter_by_subplot = True if row is None and col is not None: # All rows for column grid_subplot_ref_tuples = [ref_row[col - 1] for ref_row in grid_ref] elif col is None and row is not None: # All columns for row grid_subplot_ref_tuples = grid_ref[row - 1] elif col is not None and row is not None: # Single grid cell grid_subplot_ref_tuples = [grid_ref[row - 1][col - 1]] else: # row and col are None, secondary_y not None grid_subplot_ref_tuples = [ refs for refs_row in grid_ref for refs in refs_row ] # Collect list of subplot refs, taking secondary_y into account grid_subplot_refs = [] for refs in grid_subplot_ref_tuples: if not refs: continue if secondary_y is not True: grid_subplot_refs.append(refs[0]) if secondary_y is not False and len(refs) > 1: grid_subplot_refs.append(refs[1]) else: filter_by_subplot = False grid_subplot_refs = None return self._perform_select_traces( filter_by_subplot, grid_subplot_refs, selector )
[ "def", "select_traces", "(", "self", ",", "selector", "=", "None", ",", "row", "=", "None", ",", "col", "=", "None", ",", "secondary_y", "=", "None", ")", ":", "if", "not", "selector", ":", "selector", "=", "{", "}", "if", "row", "is", "not", "None", "or", "col", "is", "not", "None", "or", "secondary_y", "is", "not", "None", ":", "grid_ref", "=", "self", ".", "_validate_get_grid_ref", "(", ")", "filter_by_subplot", "=", "True", "if", "row", "is", "None", "and", "col", "is", "not", "None", ":", "# All rows for column", "grid_subplot_ref_tuples", "=", "[", "ref_row", "[", "col", "-", "1", "]", "for", "ref_row", "in", "grid_ref", "]", "elif", "col", "is", "None", "and", "row", "is", "not", "None", ":", "# All columns for row", "grid_subplot_ref_tuples", "=", "grid_ref", "[", "row", "-", "1", "]", "elif", "col", "is", "not", "None", "and", "row", "is", "not", "None", ":", "# Single grid cell", "grid_subplot_ref_tuples", "=", "[", "grid_ref", "[", "row", "-", "1", "]", "[", "col", "-", "1", "]", "]", "else", ":", "# row and col are None, secondary_y not None", "grid_subplot_ref_tuples", "=", "[", "refs", "for", "refs_row", "in", "grid_ref", "for", "refs", "in", "refs_row", "]", "# Collect list of subplot refs, taking secondary_y into account", "grid_subplot_refs", "=", "[", "]", "for", "refs", "in", "grid_subplot_ref_tuples", ":", "if", "not", "refs", ":", "continue", "if", "secondary_y", "is", "not", "True", ":", "grid_subplot_refs", ".", "append", "(", "refs", "[", "0", "]", ")", "if", "secondary_y", "is", "not", "False", "and", "len", "(", "refs", ")", ">", "1", ":", "grid_subplot_refs", ".", "append", "(", "refs", "[", "1", "]", ")", "else", ":", "filter_by_subplot", "=", "False", "grid_subplot_refs", "=", "None", "return", "self", ".", "_perform_select_traces", "(", "filter_by_subplot", ",", "grid_subplot_refs", ",", "selector", ")" ]
[ 718, 4 ]
[ 793, 9 ]
python
en
['en', 'error', 'th']
False
BaseFigure.for_each_trace
(self, fn, selector=None, row=None, col=None, secondary_y=None)
Apply a function to all traces that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single trace object. selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all traces are selected. row, col: int or None (default None) Subplot row and column index of traces to select. To select traces by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all traces are selected. secondary_y: boolean or None (default None) * If True, only select traces associated with the secondary y-axis of the subplot. * If False, only select traces associated with the primary y-axis of the subplot. * If None (the default), do not filter traces based on secondary y-axis. To select traces by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on
Apply a function to all traces that satisfy the specified selection criteria
def for_each_trace(self, fn, selector=None, row=None, col=None, secondary_y=None): """ Apply a function to all traces that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single trace object. selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all traces are selected. row, col: int or None (default None) Subplot row and column index of traces to select. To select traces by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all traces are selected. secondary_y: boolean or None (default None) * If True, only select traces associated with the secondary y-axis of the subplot. * If False, only select traces associated with the primary y-axis of the subplot. * If None (the default), do not filter traces based on secondary y-axis. To select traces by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on """ for trace in self.select_traces( selector=selector, row=row, col=col, secondary_y=secondary_y ): fn(trace) return self
[ "def", "for_each_trace", "(", "self", ",", "fn", ",", "selector", "=", "None", ",", "row", "=", "None", ",", "col", "=", "None", ",", "secondary_y", "=", "None", ")", ":", "for", "trace", "in", "self", ".", "select_traces", "(", "selector", "=", "selector", ",", "row", "=", "row", ",", "col", "=", "col", ",", "secondary_y", "=", "secondary_y", ")", ":", "fn", "(", "trace", ")", "return", "self" ]
[ 834, 4 ]
[ 876, 19 ]
python
en
['en', 'error', 'th']
False
BaseFigure.update_traces
( self, patch=None, selector=None, row=None, col=None, secondary_y=None, overwrite=False, **kwargs )
Perform a property update operation on all traces that satisfy the specified selection criteria Parameters ---------- patch: dict or None (default None) Dictionary of property updates to be applied to all traces that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all traces are selected. row, col: int or None (default None) Subplot row and column index of traces to select. To select traces by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all traces are selected. secondary_y: boolean or None (default None) * If True, only select traces associated with the secondary y-axis of the subplot. * If False, only select traces associated with the primary y-axis of the subplot. * If None (the default), do not filter traces based on secondary y-axis. To select traces by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. **kwargs Additional property updates to apply to each selected trace. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on
Perform a property update operation on all traces that satisfy the specified selection criteria
def update_traces( self, patch=None, selector=None, row=None, col=None, secondary_y=None, overwrite=False, **kwargs ): """ Perform a property update operation on all traces that satisfy the specified selection criteria Parameters ---------- patch: dict or None (default None) Dictionary of property updates to be applied to all traces that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all traces are selected. row, col: int or None (default None) Subplot row and column index of traces to select. To select traces by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all traces are selected. secondary_y: boolean or None (default None) * If True, only select traces associated with the secondary y-axis of the subplot. * If False, only select traces associated with the primary y-axis of the subplot. * If None (the default), do not filter traces based on secondary y-axis. To select traces by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. **kwargs Additional property updates to apply to each selected trace. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for trace in self.select_traces( selector=selector, row=row, col=col, secondary_y=secondary_y ): trace.update(patch, overwrite=overwrite, **kwargs) return self
[ "def", "update_traces", "(", "self", ",", "patch", "=", "None", ",", "selector", "=", "None", ",", "row", "=", "None", ",", "col", "=", "None", ",", "secondary_y", "=", "None", ",", "overwrite", "=", "False", ",", "*", "*", "kwargs", ")", ":", "for", "trace", "in", "self", ".", "select_traces", "(", "selector", "=", "selector", ",", "row", "=", "row", ",", "col", "=", "col", ",", "secondary_y", "=", "secondary_y", ")", ":", "trace", ".", "update", "(", "patch", ",", "overwrite", "=", "overwrite", ",", "*", "*", "kwargs", ")", "return", "self" ]
[ 878, 4 ]
[ 938, 19 ]
python
en
['en', 'error', 'th']
False
BaseFigure.update_layout
(self, dict1=None, overwrite=False, **kwargs)
Update the properties of the figure's layout with a dict and/or with keyword arguments. This recursively updates the structure of the original layout with the values in the input dict / keyword arguments. Parameters ---------- dict1 : dict Dictionary of properties to be updated overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. kwargs : Keyword/value pair of properties to be updated Returns ------- BaseFigure The Figure object that the update_layout method was called on
Update the properties of the figure's layout with a dict and/or with keyword arguments.
def update_layout(self, dict1=None, overwrite=False, **kwargs): """ Update the properties of the figure's layout with a dict and/or with keyword arguments. This recursively updates the structure of the original layout with the values in the input dict / keyword arguments. Parameters ---------- dict1 : dict Dictionary of properties to be updated overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. kwargs : Keyword/value pair of properties to be updated Returns ------- BaseFigure The Figure object that the update_layout method was called on """ self.layout.update(dict1, overwrite=overwrite, **kwargs) return self
[ "def", "update_layout", "(", "self", ",", "dict1", "=", "None", ",", "overwrite", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "layout", ".", "update", "(", "dict1", ",", "overwrite", "=", "overwrite", ",", "*", "*", "kwargs", ")", "return", "self" ]
[ 940, 4 ]
[ 965, 19 ]
python
en
['en', 'error', 'th']
False
BaseFigure._select_layout_subplots_by_prefix
( self, prefix, selector=None, row=None, col=None, secondary_y=None )
Helper called by code generated select_* methods
Helper called by code generated select_* methods
def _select_layout_subplots_by_prefix( self, prefix, selector=None, row=None, col=None, secondary_y=None ): """ Helper called by code generated select_* methods """ if row is not None or col is not None or secondary_y is not None: # Build mapping from container keys ('xaxis2', 'scene4', etc.) # to (row, col, secondary_y) triplets grid_ref = self._validate_get_grid_ref() container_to_row_col = {} for r, subplot_row in enumerate(grid_ref): for c, subplot_refs in enumerate(subplot_row): if not subplot_refs: continue # collect primary keys for i, subplot_ref in enumerate(subplot_refs): for layout_key in subplot_ref.layout_keys: if layout_key.startswith(prefix): is_secondary_y = i == 1 container_to_row_col[layout_key] = ( r + 1, c + 1, is_secondary_y, ) else: container_to_row_col = None # Natural sort keys so that xaxis20 is after xaxis3 layout_keys = _natural_sort_strings(list(self.layout)) for k in layout_keys: if k.startswith(prefix) and self.layout[k] is not None: # Filter by row/col if ( row is not None and container_to_row_col.get(k, (None, None, None))[0] != row ): # row specified and this is not a match continue elif ( col is not None and container_to_row_col.get(k, (None, None, None))[1] != col ): # col specified and this is not a match continue elif ( secondary_y is not None and container_to_row_col.get(k, (None, None, None))[2] != secondary_y ): continue # Filter by selector if not self._selector_matches(self.layout[k], selector): continue yield self.layout[k]
[ "def", "_select_layout_subplots_by_prefix", "(", "self", ",", "prefix", ",", "selector", "=", "None", ",", "row", "=", "None", ",", "col", "=", "None", ",", "secondary_y", "=", "None", ")", ":", "if", "row", "is", "not", "None", "or", "col", "is", "not", "None", "or", "secondary_y", "is", "not", "None", ":", "# Build mapping from container keys ('xaxis2', 'scene4', etc.)", "# to (row, col, secondary_y) triplets", "grid_ref", "=", "self", ".", "_validate_get_grid_ref", "(", ")", "container_to_row_col", "=", "{", "}", "for", "r", ",", "subplot_row", "in", "enumerate", "(", "grid_ref", ")", ":", "for", "c", ",", "subplot_refs", "in", "enumerate", "(", "subplot_row", ")", ":", "if", "not", "subplot_refs", ":", "continue", "# collect primary keys", "for", "i", ",", "subplot_ref", "in", "enumerate", "(", "subplot_refs", ")", ":", "for", "layout_key", "in", "subplot_ref", ".", "layout_keys", ":", "if", "layout_key", ".", "startswith", "(", "prefix", ")", ":", "is_secondary_y", "=", "i", "==", "1", "container_to_row_col", "[", "layout_key", "]", "=", "(", "r", "+", "1", ",", "c", "+", "1", ",", "is_secondary_y", ",", ")", "else", ":", "container_to_row_col", "=", "None", "# Natural sort keys so that xaxis20 is after xaxis3", "layout_keys", "=", "_natural_sort_strings", "(", "list", "(", "self", ".", "layout", ")", ")", "for", "k", "in", "layout_keys", ":", "if", "k", ".", "startswith", "(", "prefix", ")", "and", "self", ".", "layout", "[", "k", "]", "is", "not", "None", ":", "# Filter by row/col", "if", "(", "row", "is", "not", "None", "and", "container_to_row_col", ".", "get", "(", "k", ",", "(", "None", ",", "None", ",", "None", ")", ")", "[", "0", "]", "!=", "row", ")", ":", "# row specified and this is not a match", "continue", "elif", "(", "col", "is", "not", "None", "and", "container_to_row_col", ".", "get", "(", "k", ",", "(", "None", ",", "None", ",", "None", ")", ")", "[", "1", "]", "!=", "col", ")", ":", "# col specified and this is not a match", "continue", "elif", "(", "secondary_y", "is", "not", "None", "and", "container_to_row_col", ".", "get", "(", "k", ",", "(", "None", ",", "None", ",", "None", ")", ")", "[", "2", "]", "!=", "secondary_y", ")", ":", "continue", "# Filter by selector", "if", "not", "self", ".", "_selector_matches", "(", "self", ".", "layout", "[", "k", "]", ",", "selector", ")", ":", "continue", "yield", "self", ".", "layout", "[", "k", "]" ]
[ 967, 4 ]
[ 1027, 36 ]
python
en
['en', 'error', 'th']
False
BaseFigure._select_annotations_like
( self, prop, selector=None, row=None, col=None, secondary_y=None )
Helper to select annotation-like elements from a layout object array. Compatible with layout.annotations, layout.shapes, and layout.images
Helper to select annotation-like elements from a layout object array. Compatible with layout.annotations, layout.shapes, and layout.images
def _select_annotations_like( self, prop, selector=None, row=None, col=None, secondary_y=None ): """ Helper to select annotation-like elements from a layout object array. Compatible with layout.annotations, layout.shapes, and layout.images """ xref_to_col = {} yref_to_row = {} yref_to_secondary_y = {} if isinstance(row, int) or isinstance(col, int) or secondary_y is not None: grid_ref = self._validate_get_grid_ref() for r, subplot_row in enumerate(grid_ref): for c, subplot_refs in enumerate(subplot_row): if not subplot_refs: continue for i, subplot_ref in enumerate(subplot_refs): if subplot_ref.subplot_type == "xy": is_secondary_y = i == 1 xaxis, yaxis = subplot_ref.layout_keys xref = xaxis.replace("axis", "") yref = yaxis.replace("axis", "") xref_to_col[xref] = c + 1 yref_to_row[yref] = r + 1 yref_to_secondary_y[yref] = is_secondary_y for obj in self.layout[prop]: # Filter by row if col is not None and xref_to_col.get(obj.xref, None) != col: continue # Filter by col if row is not None and yref_to_row.get(obj.yref, None) != row: continue # Filter by secondary y if ( secondary_y is not None and yref_to_secondary_y.get(obj.yref, None) != secondary_y ): continue # Filter by selector if not self._selector_matches(obj, selector): continue yield obj
[ "def", "_select_annotations_like", "(", "self", ",", "prop", ",", "selector", "=", "None", ",", "row", "=", "None", ",", "col", "=", "None", ",", "secondary_y", "=", "None", ")", ":", "xref_to_col", "=", "{", "}", "yref_to_row", "=", "{", "}", "yref_to_secondary_y", "=", "{", "}", "if", "isinstance", "(", "row", ",", "int", ")", "or", "isinstance", "(", "col", ",", "int", ")", "or", "secondary_y", "is", "not", "None", ":", "grid_ref", "=", "self", ".", "_validate_get_grid_ref", "(", ")", "for", "r", ",", "subplot_row", "in", "enumerate", "(", "grid_ref", ")", ":", "for", "c", ",", "subplot_refs", "in", "enumerate", "(", "subplot_row", ")", ":", "if", "not", "subplot_refs", ":", "continue", "for", "i", ",", "subplot_ref", "in", "enumerate", "(", "subplot_refs", ")", ":", "if", "subplot_ref", ".", "subplot_type", "==", "\"xy\"", ":", "is_secondary_y", "=", "i", "==", "1", "xaxis", ",", "yaxis", "=", "subplot_ref", ".", "layout_keys", "xref", "=", "xaxis", ".", "replace", "(", "\"axis\"", ",", "\"\"", ")", "yref", "=", "yaxis", ".", "replace", "(", "\"axis\"", ",", "\"\"", ")", "xref_to_col", "[", "xref", "]", "=", "c", "+", "1", "yref_to_row", "[", "yref", "]", "=", "r", "+", "1", "yref_to_secondary_y", "[", "yref", "]", "=", "is_secondary_y", "for", "obj", "in", "self", ".", "layout", "[", "prop", "]", ":", "# Filter by row", "if", "col", "is", "not", "None", "and", "xref_to_col", ".", "get", "(", "obj", ".", "xref", ",", "None", ")", "!=", "col", ":", "continue", "# Filter by col", "if", "row", "is", "not", "None", "and", "yref_to_row", ".", "get", "(", "obj", ".", "yref", ",", "None", ")", "!=", "row", ":", "continue", "# Filter by secondary y", "if", "(", "secondary_y", "is", "not", "None", "and", "yref_to_secondary_y", ".", "get", "(", "obj", ".", "yref", ",", "None", ")", "!=", "secondary_y", ")", ":", "continue", "# Filter by selector", "if", "not", "self", ".", "_selector_matches", "(", "obj", ",", "selector", ")", ":", "continue", "yield", "obj" ]
[ 1029, 4 ]
[ 1076, 21 ]
python
en
['en', 'error', 'th']
False
BaseFigure.plotly_restyle
(self, restyle_data, trace_indexes=None, **kwargs)
Perform a Plotly restyle operation on the figure's traces Parameters ---------- restyle_data : dict Dict of trace style updates. Keys are strings that specify the properties to be updated. Nested properties are expressed by joining successive keys on '.' characters (e.g. 'marker.color'). Values may be scalars or lists. When values are scalars, that scalar value is applied to all traces specified by the `trace_indexes` parameter. When values are lists, the restyle operation will cycle through the elements of the list as it cycles through the traces specified by the `trace_indexes` parameter. Caution: To use plotly_restyle to update a list property (e.g. the `x` property of the scatter trace), the property value should be a scalar list containing the list to update with. For example, the following command would be used to update the 'x' property of the first trace to the list [1, 2, 3] >>> import plotly.graph_objects as go >>> fig = go.Figure(go.Scatter(x=[2, 4, 6])) >>> fig.plotly_restyle({'x': [[1, 2, 3]]}, 0) trace_indexes : int or list of int Trace index, or list of trace indexes, that the restyle operation applies to. Defaults to all trace indexes. Returns ------- None
Perform a Plotly restyle operation on the figure's traces
def plotly_restyle(self, restyle_data, trace_indexes=None, **kwargs): """ Perform a Plotly restyle operation on the figure's traces Parameters ---------- restyle_data : dict Dict of trace style updates. Keys are strings that specify the properties to be updated. Nested properties are expressed by joining successive keys on '.' characters (e.g. 'marker.color'). Values may be scalars or lists. When values are scalars, that scalar value is applied to all traces specified by the `trace_indexes` parameter. When values are lists, the restyle operation will cycle through the elements of the list as it cycles through the traces specified by the `trace_indexes` parameter. Caution: To use plotly_restyle to update a list property (e.g. the `x` property of the scatter trace), the property value should be a scalar list containing the list to update with. For example, the following command would be used to update the 'x' property of the first trace to the list [1, 2, 3] >>> import plotly.graph_objects as go >>> fig = go.Figure(go.Scatter(x=[2, 4, 6])) >>> fig.plotly_restyle({'x': [[1, 2, 3]]}, 0) trace_indexes : int or list of int Trace index, or list of trace indexes, that the restyle operation applies to. Defaults to all trace indexes. Returns ------- None """ # Normalize trace indexes # ----------------------- trace_indexes = self._normalize_trace_indexes(trace_indexes) # Handle source_view_id # --------------------- # If not None, the source_view_id is the UID of the frontend # Plotly.js view that initially triggered this restyle operation # (e.g. the user clicked on the legend to hide a trace). We pass # this UID along so that the frontend views can determine whether # they need to apply the restyle operation on themselves. source_view_id = kwargs.get("source_view_id", None) # Perform restyle on trace dicts # ------------------------------ restyle_changes = self._perform_plotly_restyle(restyle_data, trace_indexes) if restyle_changes: # The restyle operation resulted in a change to some trace # properties, so we dispatch change callbacks and send the # restyle message to the frontend (if any) msg_kwargs = ( {"source_view_id": source_view_id} if source_view_id is not None else {} ) self._send_restyle_msg( restyle_changes, trace_indexes=trace_indexes, **msg_kwargs ) self._dispatch_trace_change_callbacks(restyle_changes, trace_indexes)
[ "def", "plotly_restyle", "(", "self", ",", "restyle_data", ",", "trace_indexes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Normalize trace indexes", "# -----------------------", "trace_indexes", "=", "self", ".", "_normalize_trace_indexes", "(", "trace_indexes", ")", "# Handle source_view_id", "# ---------------------", "# If not None, the source_view_id is the UID of the frontend", "# Plotly.js view that initially triggered this restyle operation", "# (e.g. the user clicked on the legend to hide a trace). We pass", "# this UID along so that the frontend views can determine whether", "# they need to apply the restyle operation on themselves.", "source_view_id", "=", "kwargs", ".", "get", "(", "\"source_view_id\"", ",", "None", ")", "# Perform restyle on trace dicts", "# ------------------------------", "restyle_changes", "=", "self", ".", "_perform_plotly_restyle", "(", "restyle_data", ",", "trace_indexes", ")", "if", "restyle_changes", ":", "# The restyle operation resulted in a change to some trace", "# properties, so we dispatch change callbacks and send the", "# restyle message to the frontend (if any)", "msg_kwargs", "=", "(", "{", "\"source_view_id\"", ":", "source_view_id", "}", "if", "source_view_id", "is", "not", "None", "else", "{", "}", ")", "self", ".", "_send_restyle_msg", "(", "restyle_changes", ",", "trace_indexes", "=", "trace_indexes", ",", "*", "*", "msg_kwargs", ")", "self", ".", "_dispatch_trace_change_callbacks", "(", "restyle_changes", ",", "trace_indexes", ")" ]
[ 1133, 4 ]
[ 1200, 81 ]
python
en
['en', 'error', 'th']
False
BaseFigure._perform_plotly_restyle
(self, restyle_data, trace_indexes)
Perform a restyle operation on the figure's traces data and return the changes that were applied Parameters ---------- restyle_data : dict[str, any] See docstring for plotly_restyle trace_indexes : list[int] List of trace indexes that restyle operation applies to Returns ------- restyle_changes: dict[str, any] Subset of restyle_data including only the keys / values that resulted in a change to the figure's traces data
Perform a restyle operation on the figure's traces data and return the changes that were applied
def _perform_plotly_restyle(self, restyle_data, trace_indexes): """ Perform a restyle operation on the figure's traces data and return the changes that were applied Parameters ---------- restyle_data : dict[str, any] See docstring for plotly_restyle trace_indexes : list[int] List of trace indexes that restyle operation applies to Returns ------- restyle_changes: dict[str, any] Subset of restyle_data including only the keys / values that resulted in a change to the figure's traces data """ # Initialize restyle changes # -------------------------- # This will be a subset of the restyle_data including only the # keys / values that are changed in the figure's trace data restyle_changes = {} # Process each key # ---------------- for key_path_str, v in restyle_data.items(): # Track whether any of the new values are cause a change in # self._data any_vals_changed = False for i, trace_ind in enumerate(trace_indexes): if trace_ind >= len(self._data): raise ValueError( "Trace index {trace_ind} out of range".format( trace_ind=trace_ind ) ) # Get new value for this particular trace trace_v = v[i % len(v)] if isinstance(v, list) else v if trace_v is not Undefined: # Get trace being updated trace_obj = self.data[trace_ind] # Validate key_path_str if not BaseFigure._is_key_path_compatible(key_path_str, trace_obj): trace_class = trace_obj.__class__.__name__ raise ValueError( """ Invalid property path '{key_path_str}' for trace class {trace_class} """.format( key_path_str=key_path_str, trace_class=trace_class ) ) # Apply set operation for this trace and thist value val_changed = BaseFigure._set_in( self._data[trace_ind], key_path_str, trace_v ) # Update any_vals_changed status any_vals_changed = any_vals_changed or val_changed if any_vals_changed: restyle_changes[key_path_str] = v return restyle_changes
[ "def", "_perform_plotly_restyle", "(", "self", ",", "restyle_data", ",", "trace_indexes", ")", ":", "# Initialize restyle changes", "# --------------------------", "# This will be a subset of the restyle_data including only the", "# keys / values that are changed in the figure's trace data", "restyle_changes", "=", "{", "}", "# Process each key", "# ----------------", "for", "key_path_str", ",", "v", "in", "restyle_data", ".", "items", "(", ")", ":", "# Track whether any of the new values are cause a change in", "# self._data", "any_vals_changed", "=", "False", "for", "i", ",", "trace_ind", "in", "enumerate", "(", "trace_indexes", ")", ":", "if", "trace_ind", ">=", "len", "(", "self", ".", "_data", ")", ":", "raise", "ValueError", "(", "\"Trace index {trace_ind} out of range\"", ".", "format", "(", "trace_ind", "=", "trace_ind", ")", ")", "# Get new value for this particular trace", "trace_v", "=", "v", "[", "i", "%", "len", "(", "v", ")", "]", "if", "isinstance", "(", "v", ",", "list", ")", "else", "v", "if", "trace_v", "is", "not", "Undefined", ":", "# Get trace being updated", "trace_obj", "=", "self", ".", "data", "[", "trace_ind", "]", "# Validate key_path_str", "if", "not", "BaseFigure", ".", "_is_key_path_compatible", "(", "key_path_str", ",", "trace_obj", ")", ":", "trace_class", "=", "trace_obj", ".", "__class__", ".", "__name__", "raise", "ValueError", "(", "\"\"\"\nInvalid property path '{key_path_str}' for trace class {trace_class}\n\"\"\"", ".", "format", "(", "key_path_str", "=", "key_path_str", ",", "trace_class", "=", "trace_class", ")", ")", "# Apply set operation for this trace and thist value", "val_changed", "=", "BaseFigure", ".", "_set_in", "(", "self", ".", "_data", "[", "trace_ind", "]", ",", "key_path_str", ",", "trace_v", ")", "# Update any_vals_changed status", "any_vals_changed", "=", "any_vals_changed", "or", "val_changed", "if", "any_vals_changed", ":", "restyle_changes", "[", "key_path_str", "]", "=", "v", "return", "restyle_changes" ]
[ 1202, 4 ]
[ 1271, 30 ]
python
en
['en', 'error', 'th']
False
BaseFigure._restyle_child
(self, child, key_path_str, val)
Process restyle operation on a child trace object Note: This method name/signature must match the one in BasePlotlyType. BasePlotlyType objects call their parent's _restyle_child method without knowing whether their parent is a BasePlotlyType or a BaseFigure. Parameters ---------- child : BaseTraceType Child being restyled key_path_str : str A key path string (e.g. 'foo.bar[0]') val Restyle value Returns ------- None
Process restyle operation on a child trace object
def _restyle_child(self, child, key_path_str, val): """ Process restyle operation on a child trace object Note: This method name/signature must match the one in BasePlotlyType. BasePlotlyType objects call their parent's _restyle_child method without knowing whether their parent is a BasePlotlyType or a BaseFigure. Parameters ---------- child : BaseTraceType Child being restyled key_path_str : str A key path string (e.g. 'foo.bar[0]') val Restyle value Returns ------- None """ # Compute trace index # ------------------- trace_index = child._trace_ind # Not in batch mode # ----------------- # Dispatch change callbacks and send restyle message if not self._in_batch_mode: send_val = [val] restyle = {key_path_str: send_val} self._send_restyle_msg(restyle, trace_indexes=trace_index) self._dispatch_trace_change_callbacks(restyle, [trace_index]) # In batch mode # ------------- # Add key_path_str/val to saved batch edits else: if trace_index not in self._batch_trace_edits: self._batch_trace_edits[trace_index] = OrderedDict() self._batch_trace_edits[trace_index][key_path_str] = val
[ "def", "_restyle_child", "(", "self", ",", "child", ",", "key_path_str", ",", "val", ")", ":", "# Compute trace index", "# -------------------", "trace_index", "=", "child", ".", "_trace_ind", "# Not in batch mode", "# -----------------", "# Dispatch change callbacks and send restyle message", "if", "not", "self", ".", "_in_batch_mode", ":", "send_val", "=", "[", "val", "]", "restyle", "=", "{", "key_path_str", ":", "send_val", "}", "self", ".", "_send_restyle_msg", "(", "restyle", ",", "trace_indexes", "=", "trace_index", ")", "self", ".", "_dispatch_trace_change_callbacks", "(", "restyle", ",", "[", "trace_index", "]", ")", "# In batch mode", "# -------------", "# Add key_path_str/val to saved batch edits", "else", ":", "if", "trace_index", "not", "in", "self", ".", "_batch_trace_edits", ":", "self", ".", "_batch_trace_edits", "[", "trace_index", "]", "=", "OrderedDict", "(", ")", "self", ".", "_batch_trace_edits", "[", "trace_index", "]", "[", "key_path_str", "]", "=", "val" ]
[ 1273, 4 ]
[ 1315, 68 ]
python
en
['en', 'error', 'th']
False
BaseFigure._normalize_trace_indexes
(self, trace_indexes)
Input trace index specification and return list of the specified trace indexes Parameters ---------- trace_indexes : None or int or list[int] Returns ------- list[int]
Input trace index specification and return list of the specified trace indexes
def _normalize_trace_indexes(self, trace_indexes): """ Input trace index specification and return list of the specified trace indexes Parameters ---------- trace_indexes : None or int or list[int] Returns ------- list[int] """ if trace_indexes is None: trace_indexes = list(range(len(self.data))) if not isinstance(trace_indexes, (list, tuple)): trace_indexes = [trace_indexes] return list(trace_indexes)
[ "def", "_normalize_trace_indexes", "(", "self", ",", "trace_indexes", ")", ":", "if", "trace_indexes", "is", "None", ":", "trace_indexes", "=", "list", "(", "range", "(", "len", "(", "self", ".", "data", ")", ")", ")", "if", "not", "isinstance", "(", "trace_indexes", ",", "(", "list", ",", "tuple", ")", ")", ":", "trace_indexes", "=", "[", "trace_indexes", "]", "return", "list", "(", "trace_indexes", ")" ]
[ 1317, 4 ]
[ 1334, 34 ]
python
en
['en', 'error', 'th']
False
BaseFigure._str_to_dict_path
(key_path_str)
Convert a key path string into a tuple of key path elements Parameters ---------- key_path_str : str Key path string, where nested keys are joined on '.' characters and array indexes are specified using brackets (e.g. 'foo.bar[1]') Returns ------- tuple[str | int]
Convert a key path string into a tuple of key path elements
def _str_to_dict_path(key_path_str): """ Convert a key path string into a tuple of key path elements Parameters ---------- key_path_str : str Key path string, where nested keys are joined on '.' characters and array indexes are specified using brackets (e.g. 'foo.bar[1]') Returns ------- tuple[str | int] """ if ( isinstance(key_path_str, string_types) and "." not in key_path_str and "[" not in key_path_str and "_" not in key_path_str ): # Fast path for common case that avoids regular expressions return (key_path_str,) elif isinstance(key_path_str, tuple): # Nothing to do return key_path_str else: # Split string on periods. # e.g. 'foo.bar_baz[1]' -> ['foo', 'bar_baz[1]'] key_path = key_path_str.split(".") # Split out bracket indexes. # e.g. ['foo', 'bar_baz[1]'] -> ['foo', 'bar_baz', '1'] key_path2 = [] for key in key_path: match = BaseFigure._bracket_re.match(key) if match: key_path2.extend(match.groups()) else: key_path2.append(key) # Split out underscore # e.g. ['foo', 'bar_baz', '1'] -> ['foo', 'bar', 'baz', '1'] key_path3 = [] underscore_props = BaseFigure._valid_underscore_properties for key in key_path2: if "_" in key[1:]: # For valid properties that contain underscores (error_x) # replace the underscores with hyphens to protect them # from being split up for under_prop, hyphen_prop in underscore_props.items(): key = key.replace(under_prop, hyphen_prop) # Split key on underscores key = key.split("_") # Replace hyphens with underscores to restore properties # that include underscores for i in range(len(key)): key[i] = key[i].replace("-", "_") key_path3.extend(key) else: key_path3.append(key) # Convert elements to ints if possible. # e.g. ['foo', 'bar', '0'] -> ['foo', 'bar', 0] for i in range(len(key_path3)): try: key_path3[i] = int(key_path3[i]) except ValueError as _: pass return tuple(key_path3)
[ "def", "_str_to_dict_path", "(", "key_path_str", ")", ":", "if", "(", "isinstance", "(", "key_path_str", ",", "string_types", ")", "and", "\".\"", "not", "in", "key_path_str", "and", "\"[\"", "not", "in", "key_path_str", "and", "\"_\"", "not", "in", "key_path_str", ")", ":", "# Fast path for common case that avoids regular expressions", "return", "(", "key_path_str", ",", ")", "elif", "isinstance", "(", "key_path_str", ",", "tuple", ")", ":", "# Nothing to do", "return", "key_path_str", "else", ":", "# Split string on periods.", "# e.g. 'foo.bar_baz[1]' -> ['foo', 'bar_baz[1]']", "key_path", "=", "key_path_str", ".", "split", "(", "\".\"", ")", "# Split out bracket indexes.", "# e.g. ['foo', 'bar_baz[1]'] -> ['foo', 'bar_baz', '1']", "key_path2", "=", "[", "]", "for", "key", "in", "key_path", ":", "match", "=", "BaseFigure", ".", "_bracket_re", ".", "match", "(", "key", ")", "if", "match", ":", "key_path2", ".", "extend", "(", "match", ".", "groups", "(", ")", ")", "else", ":", "key_path2", ".", "append", "(", "key", ")", "# Split out underscore", "# e.g. ['foo', 'bar_baz', '1'] -> ['foo', 'bar', 'baz', '1']", "key_path3", "=", "[", "]", "underscore_props", "=", "BaseFigure", ".", "_valid_underscore_properties", "for", "key", "in", "key_path2", ":", "if", "\"_\"", "in", "key", "[", "1", ":", "]", ":", "# For valid properties that contain underscores (error_x)", "# replace the underscores with hyphens to protect them", "# from being split up", "for", "under_prop", ",", "hyphen_prop", "in", "underscore_props", ".", "items", "(", ")", ":", "key", "=", "key", ".", "replace", "(", "under_prop", ",", "hyphen_prop", ")", "# Split key on underscores", "key", "=", "key", ".", "split", "(", "\"_\"", ")", "# Replace hyphens with underscores to restore properties", "# that include underscores", "for", "i", "in", "range", "(", "len", "(", "key", ")", ")", ":", "key", "[", "i", "]", "=", "key", "[", "i", "]", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "key_path3", ".", "extend", "(", "key", ")", "else", ":", "key_path3", ".", "append", "(", "key", ")", "# Convert elements to ints if possible.", "# e.g. ['foo', 'bar', '0'] -> ['foo', 'bar', 0]", "for", "i", "in", "range", "(", "len", "(", "key_path3", ")", ")", ":", "try", ":", "key_path3", "[", "i", "]", "=", "int", "(", "key_path3", "[", "i", "]", ")", "except", "ValueError", "as", "_", ":", "pass", "return", "tuple", "(", "key_path3", ")" ]
[ 1337, 4 ]
[ 1409, 35 ]
python
en
['en', 'error', 'th']
False
BaseFigure._set_in
(d, key_path_str, v)
Set a value in a nested dict using a key path string (e.g. 'foo.bar[0]') Parameters ---------- d : dict Input dict to set property in key_path_str : str Key path string, where nested keys are joined on '.' characters and array indexes are specified using brackets (e.g. 'foo.bar[1]') v New value Returns ------- bool True if set resulted in modification of dict (i.e. v was not already present at the specified location), False otherwise.
Set a value in a nested dict using a key path string (e.g. 'foo.bar[0]')
def _set_in(d, key_path_str, v): """ Set a value in a nested dict using a key path string (e.g. 'foo.bar[0]') Parameters ---------- d : dict Input dict to set property in key_path_str : str Key path string, where nested keys are joined on '.' characters and array indexes are specified using brackets (e.g. 'foo.bar[1]') v New value Returns ------- bool True if set resulted in modification of dict (i.e. v was not already present at the specified location), False otherwise. """ # Validate inputs # --------------- assert isinstance(d, dict) # Compute key path # ---------------- # Convert the key_path_str into a tuple of key paths # e.g. 'foo.bar[0]' -> ('foo', 'bar', 0) key_path = BaseFigure._str_to_dict_path(key_path_str) # Initialize val_parent # --------------------- # This variable will be assigned to the parent of the next key path # element currently being processed val_parent = d # Initialize parent dict or list of value to be assigned # ----------------------------------------------------- for kp, key_path_el in enumerate(key_path[:-1]): # Extend val_parent list if needed if isinstance(val_parent, list) and isinstance(key_path_el, int): while len(val_parent) <= key_path_el: val_parent.append(None) elif isinstance(val_parent, dict) and key_path_el not in val_parent: if isinstance(key_path[kp + 1], int): val_parent[key_path_el] = [] else: val_parent[key_path_el] = {} val_parent = val_parent[key_path_el] # Assign value to to final parent dict or list # -------------------------------------------- # ### Get reference to final key path element ### last_key = key_path[-1] # ### Track whether assignment alters parent ### val_changed = False # v is Undefined # -------------- # Don't alter val_parent if v is Undefined: pass # v is None # --------- # Check whether we can remove key from parent elif v is None: if isinstance(val_parent, dict): if last_key in val_parent: # Parent is a dict and has last_key as a current key so # we can pop the key, which alters parent val_parent.pop(last_key) val_changed = True elif isinstance(val_parent, list): if isinstance(last_key, int) and 0 <= last_key < len(val_parent): # Parent is a list and last_key is a valid index so we # can set the element value to None val_parent[last_key] = None val_changed = True else: # Unsupported parent type (numpy array for example) raise ValueError( """ Cannot remove element of type {typ} at location {raw_key}""".format( typ=type(val_parent), raw_key=key_path_str ) ) # v is a valid value # ------------------ # Check whether parent should be updated else: if isinstance(val_parent, dict): if last_key not in val_parent or not BasePlotlyType._vals_equal( val_parent[last_key], v ): # Parent is a dict and does not already contain the # value v at key last_key val_parent[last_key] = v val_changed = True elif isinstance(val_parent, list): if isinstance(last_key, int): # Extend list with Nones if needed so that last_key is # in bounds while len(val_parent) <= last_key: val_parent.append(None) if not BasePlotlyType._vals_equal(val_parent[last_key], v): # Parent is a list and does not already contain the # value v at index last_key val_parent[last_key] = v val_changed = True else: # Unsupported parent type (numpy array for example) raise ValueError( """ Cannot set element of type {typ} at location {raw_key}""".format( typ=type(val_parent), raw_key=key_path_str ) ) return val_changed
[ "def", "_set_in", "(", "d", ",", "key_path_str", ",", "v", ")", ":", "# Validate inputs", "# ---------------", "assert", "isinstance", "(", "d", ",", "dict", ")", "# Compute key path", "# ----------------", "# Convert the key_path_str into a tuple of key paths", "# e.g. 'foo.bar[0]' -> ('foo', 'bar', 0)", "key_path", "=", "BaseFigure", ".", "_str_to_dict_path", "(", "key_path_str", ")", "# Initialize val_parent", "# ---------------------", "# This variable will be assigned to the parent of the next key path", "# element currently being processed", "val_parent", "=", "d", "# Initialize parent dict or list of value to be assigned", "# -----------------------------------------------------", "for", "kp", ",", "key_path_el", "in", "enumerate", "(", "key_path", "[", ":", "-", "1", "]", ")", ":", "# Extend val_parent list if needed", "if", "isinstance", "(", "val_parent", ",", "list", ")", "and", "isinstance", "(", "key_path_el", ",", "int", ")", ":", "while", "len", "(", "val_parent", ")", "<=", "key_path_el", ":", "val_parent", ".", "append", "(", "None", ")", "elif", "isinstance", "(", "val_parent", ",", "dict", ")", "and", "key_path_el", "not", "in", "val_parent", ":", "if", "isinstance", "(", "key_path", "[", "kp", "+", "1", "]", ",", "int", ")", ":", "val_parent", "[", "key_path_el", "]", "=", "[", "]", "else", ":", "val_parent", "[", "key_path_el", "]", "=", "{", "}", "val_parent", "=", "val_parent", "[", "key_path_el", "]", "# Assign value to to final parent dict or list", "# --------------------------------------------", "# ### Get reference to final key path element ###", "last_key", "=", "key_path", "[", "-", "1", "]", "# ### Track whether assignment alters parent ###", "val_changed", "=", "False", "# v is Undefined", "# --------------", "# Don't alter val_parent", "if", "v", "is", "Undefined", ":", "pass", "# v is None", "# ---------", "# Check whether we can remove key from parent", "elif", "v", "is", "None", ":", "if", "isinstance", "(", "val_parent", ",", "dict", ")", ":", "if", "last_key", "in", "val_parent", ":", "# Parent is a dict and has last_key as a current key so", "# we can pop the key, which alters parent", "val_parent", ".", "pop", "(", "last_key", ")", "val_changed", "=", "True", "elif", "isinstance", "(", "val_parent", ",", "list", ")", ":", "if", "isinstance", "(", "last_key", ",", "int", ")", "and", "0", "<=", "last_key", "<", "len", "(", "val_parent", ")", ":", "# Parent is a list and last_key is a valid index so we", "# can set the element value to None", "val_parent", "[", "last_key", "]", "=", "None", "val_changed", "=", "True", "else", ":", "# Unsupported parent type (numpy array for example)", "raise", "ValueError", "(", "\"\"\"\n Cannot remove element of type {typ} at location {raw_key}\"\"\"", ".", "format", "(", "typ", "=", "type", "(", "val_parent", ")", ",", "raw_key", "=", "key_path_str", ")", ")", "# v is a valid value", "# ------------------", "# Check whether parent should be updated", "else", ":", "if", "isinstance", "(", "val_parent", ",", "dict", ")", ":", "if", "last_key", "not", "in", "val_parent", "or", "not", "BasePlotlyType", ".", "_vals_equal", "(", "val_parent", "[", "last_key", "]", ",", "v", ")", ":", "# Parent is a dict and does not already contain the", "# value v at key last_key", "val_parent", "[", "last_key", "]", "=", "v", "val_changed", "=", "True", "elif", "isinstance", "(", "val_parent", ",", "list", ")", ":", "if", "isinstance", "(", "last_key", ",", "int", ")", ":", "# Extend list with Nones if needed so that last_key is", "# in bounds", "while", "len", "(", "val_parent", ")", "<=", "last_key", ":", "val_parent", ".", "append", "(", "None", ")", "if", "not", "BasePlotlyType", ".", "_vals_equal", "(", "val_parent", "[", "last_key", "]", ",", "v", ")", ":", "# Parent is a list and does not already contain the", "# value v at index last_key", "val_parent", "[", "last_key", "]", "=", "v", "val_changed", "=", "True", "else", ":", "# Unsupported parent type (numpy array for example)", "raise", "ValueError", "(", "\"\"\"\n Cannot set element of type {typ} at location {raw_key}\"\"\"", ".", "format", "(", "typ", "=", "type", "(", "val_parent", ")", ",", "raw_key", "=", "key_path_str", ")", ")", "return", "val_changed" ]
[ 1412, 4 ]
[ 1537, 26 ]
python
en
['en', 'error', 'th']
False
BaseFigure.add_trace
(self, trace, row=None, col=None, secondary_y=None)
Add a trace to the figure Parameters ---------- trace : BaseTraceType or dict Either: - An instances of a trace classe from the plotly.graph_objs package (e.g plotly.graph_objs.Scatter, plotly.graph_objs.Bar) - or a dicts where: - The 'type' property specifies the trace type (e.g. 'scatter', 'bar', 'area', etc.). If the dict has no 'type' property then 'scatter' is assumed. - All remaining properties are passed to the constructor of the specified trace type. row : int or None (default None) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.subplots.make_subplots` col : int or None (default None) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.subplots.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. * The trace argument is a 2D cartesian trace (scatter, bar, etc.) Returns ------- BaseFigure The Figure that add_trace was called on Examples -------- >>> from plotly import subplots >>> import plotly.graph_objs as go Add two Scatter traces to a figure >>> fig = go.Figure() >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2])) # doctest: +ELLIPSIS Figure(...) >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2])) # doctest: +ELLIPSIS Figure(...) Add two Scatter traces to vertically stacked subplots >>> fig = subplots.make_subplots(rows=2) >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1) # doctest: +ELLIPSIS Figure(...) >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1) # doctest: +ELLIPSIS Figure(...)
Add a trace to the figure
def add_trace(self, trace, row=None, col=None, secondary_y=None): """ Add a trace to the figure Parameters ---------- trace : BaseTraceType or dict Either: - An instances of a trace classe from the plotly.graph_objs package (e.g plotly.graph_objs.Scatter, plotly.graph_objs.Bar) - or a dicts where: - The 'type' property specifies the trace type (e.g. 'scatter', 'bar', 'area', etc.). If the dict has no 'type' property then 'scatter' is assumed. - All remaining properties are passed to the constructor of the specified trace type. row : int or None (default None) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.subplots.make_subplots` col : int or None (default None) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.subplots.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. * The trace argument is a 2D cartesian trace (scatter, bar, etc.) Returns ------- BaseFigure The Figure that add_trace was called on Examples -------- >>> from plotly import subplots >>> import plotly.graph_objs as go Add two Scatter traces to a figure >>> fig = go.Figure() >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2])) # doctest: +ELLIPSIS Figure(...) >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2])) # doctest: +ELLIPSIS Figure(...) Add two Scatter traces to vertically stacked subplots >>> fig = subplots.make_subplots(rows=2) >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1) # doctest: +ELLIPSIS Figure(...) >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1) # doctest: +ELLIPSIS Figure(...) """ # Make sure we have both row and col or neither if row is not None and col is None: raise ValueError( "Received row parameter but not col.\n" "row and col must be specified together" ) elif col is not None and row is None: raise ValueError( "Received col parameter but not row.\n" "row and col must be specified together" ) return self.add_traces( data=[trace], rows=[row] if row is not None else None, cols=[col] if col is not None else None, secondary_ys=[secondary_y] if secondary_y is not None else None, )
[ "def", "add_trace", "(", "self", ",", "trace", ",", "row", "=", "None", ",", "col", "=", "None", ",", "secondary_y", "=", "None", ")", ":", "# Make sure we have both row and col or neither", "if", "row", "is", "not", "None", "and", "col", "is", "None", ":", "raise", "ValueError", "(", "\"Received row parameter but not col.\\n\"", "\"row and col must be specified together\"", ")", "elif", "col", "is", "not", "None", "and", "row", "is", "None", ":", "raise", "ValueError", "(", "\"Received col parameter but not row.\\n\"", "\"row and col must be specified together\"", ")", "return", "self", ".", "add_traces", "(", "data", "=", "[", "trace", "]", ",", "rows", "=", "[", "row", "]", "if", "row", "is", "not", "None", "else", "None", ",", "cols", "=", "[", "col", "]", "if", "col", "is", "not", "None", "else", "None", ",", "secondary_ys", "=", "[", "secondary_y", "]", "if", "secondary_y", "is", "not", "None", "else", "None", ",", ")" ]
[ 1569, 4 ]
[ 1652, 9 ]
python
en
['en', 'error', 'th']
False
BaseFigure.add_traces
(self, data, rows=None, cols=None, secondary_ys=None)
Add traces to the figure Parameters ---------- data : list[BaseTraceType or dict] A list of trace specifications to be added. Trace specifications may be either: - Instances of trace classes from the plotly.graph_objs package (e.g plotly.graph_objs.Scatter, plotly.graph_objs.Bar) - Dicts where: - The 'type' property specifies the trace type (e.g. 'scatter', 'bar', 'area', etc.). If the dict has no 'type' property then 'scatter' is assumed. - All remaining properties are passed to the constructor of the specified trace type. rows : None, list[int], or int (default None) List of subplot row indexes (starting from 1) for the traces to be added. Only valid if figure was created using `plotly.tools.make_subplots` If a single integer is passed, all traces will be added to row number cols : None or list[int] (default None) List of subplot column indexes (starting from 1) for the traces to be added. Only valid if figure was created using `plotly.tools.make_subplots` If a single integer is passed, all traces will be added to column number secondary_ys: None or list[boolean] (default None) List of secondary_y booleans for traces to be added. See the docstring for `add_trace` for more info. Returns ------- BaseFigure The Figure that add_traces was called on Examples -------- >>> from plotly import subplots >>> import plotly.graph_objs as go Add two Scatter traces to a figure >>> fig = go.Figure() >>> fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]), ... go.Scatter(x=[1,2,3], y=[2,1,2])]) # doctest: +ELLIPSIS Figure(...) Add two Scatter traces to vertically stacked subplots >>> fig = subplots.make_subplots(rows=2) >>> fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]), ... go.Scatter(x=[1,2,3], y=[2,1,2])], ... rows=[1, 2], cols=[1, 1]) # doctest: +ELLIPSIS Figure(...)
Add traces to the figure
def add_traces(self, data, rows=None, cols=None, secondary_ys=None): """ Add traces to the figure Parameters ---------- data : list[BaseTraceType or dict] A list of trace specifications to be added. Trace specifications may be either: - Instances of trace classes from the plotly.graph_objs package (e.g plotly.graph_objs.Scatter, plotly.graph_objs.Bar) - Dicts where: - The 'type' property specifies the trace type (e.g. 'scatter', 'bar', 'area', etc.). If the dict has no 'type' property then 'scatter' is assumed. - All remaining properties are passed to the constructor of the specified trace type. rows : None, list[int], or int (default None) List of subplot row indexes (starting from 1) for the traces to be added. Only valid if figure was created using `plotly.tools.make_subplots` If a single integer is passed, all traces will be added to row number cols : None or list[int] (default None) List of subplot column indexes (starting from 1) for the traces to be added. Only valid if figure was created using `plotly.tools.make_subplots` If a single integer is passed, all traces will be added to column number secondary_ys: None or list[boolean] (default None) List of secondary_y booleans for traces to be added. See the docstring for `add_trace` for more info. Returns ------- BaseFigure The Figure that add_traces was called on Examples -------- >>> from plotly import subplots >>> import plotly.graph_objs as go Add two Scatter traces to a figure >>> fig = go.Figure() >>> fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]), ... go.Scatter(x=[1,2,3], y=[2,1,2])]) # doctest: +ELLIPSIS Figure(...) Add two Scatter traces to vertically stacked subplots >>> fig = subplots.make_subplots(rows=2) >>> fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]), ... go.Scatter(x=[1,2,3], y=[2,1,2])], ... rows=[1, 2], cols=[1, 1]) # doctest: +ELLIPSIS Figure(...) """ # Validate traces data = self._data_validator.validate_coerce(data) # Set trace indexes for ind, new_trace in enumerate(data): new_trace._trace_ind = ind + len(self.data) # Allow integers as inputs to subplots int_type = _get_int_type() if isinstance(rows, int_type): rows = [rows] * len(data) if isinstance(cols, int_type): cols = [cols] * len(data) # Validate rows / cols n = len(data) BaseFigure._validate_rows_cols("rows", n, rows) BaseFigure._validate_rows_cols("cols", n, cols) # Make sure we have both rows and cols or neither if rows is not None and cols is None: raise ValueError( "Received rows parameter but not cols.\n" "rows and cols must be specified together" ) elif cols is not None and rows is None: raise ValueError( "Received cols parameter but not rows.\n" "rows and cols must be specified together" ) # Process secondary_ys defaults if secondary_ys is not None and rows is None: # Default rows/cols to 1s if secondary_ys specified but not rows # or cols rows = [1] * len(secondary_ys) cols = rows elif secondary_ys is None and rows is not None: # Default secondary_ys to Nones if secondary_ys is not specified # but not rows and cols are specified secondary_ys = [None] * len(rows) # Apply rows / cols if rows is not None: for trace, row, col, secondary_y in zip(data, rows, cols, secondary_ys): self._set_trace_grid_position(trace, row, col, secondary_y) # Make deep copy of trace data (Optimize later if needed) new_traces_data = [deepcopy(trace._props) for trace in data] # Update trace parent for trace in data: trace._parent = self trace._orphan_props.clear() # Update python side # Use extend instead of assignment so we don't trigger serialization self._data.extend(new_traces_data) self._data_defaults = self._data_defaults + [{} for _ in data] self._data_objs = self._data_objs + data # Update messages self._send_addTraces_msg(new_traces_data) return self
[ "def", "add_traces", "(", "self", ",", "data", ",", "rows", "=", "None", ",", "cols", "=", "None", ",", "secondary_ys", "=", "None", ")", ":", "# Validate traces", "data", "=", "self", ".", "_data_validator", ".", "validate_coerce", "(", "data", ")", "# Set trace indexes", "for", "ind", ",", "new_trace", "in", "enumerate", "(", "data", ")", ":", "new_trace", ".", "_trace_ind", "=", "ind", "+", "len", "(", "self", ".", "data", ")", "# Allow integers as inputs to subplots", "int_type", "=", "_get_int_type", "(", ")", "if", "isinstance", "(", "rows", ",", "int_type", ")", ":", "rows", "=", "[", "rows", "]", "*", "len", "(", "data", ")", "if", "isinstance", "(", "cols", ",", "int_type", ")", ":", "cols", "=", "[", "cols", "]", "*", "len", "(", "data", ")", "# Validate rows / cols", "n", "=", "len", "(", "data", ")", "BaseFigure", ".", "_validate_rows_cols", "(", "\"rows\"", ",", "n", ",", "rows", ")", "BaseFigure", ".", "_validate_rows_cols", "(", "\"cols\"", ",", "n", ",", "cols", ")", "# Make sure we have both rows and cols or neither", "if", "rows", "is", "not", "None", "and", "cols", "is", "None", ":", "raise", "ValueError", "(", "\"Received rows parameter but not cols.\\n\"", "\"rows and cols must be specified together\"", ")", "elif", "cols", "is", "not", "None", "and", "rows", "is", "None", ":", "raise", "ValueError", "(", "\"Received cols parameter but not rows.\\n\"", "\"rows and cols must be specified together\"", ")", "# Process secondary_ys defaults", "if", "secondary_ys", "is", "not", "None", "and", "rows", "is", "None", ":", "# Default rows/cols to 1s if secondary_ys specified but not rows", "# or cols", "rows", "=", "[", "1", "]", "*", "len", "(", "secondary_ys", ")", "cols", "=", "rows", "elif", "secondary_ys", "is", "None", "and", "rows", "is", "not", "None", ":", "# Default secondary_ys to Nones if secondary_ys is not specified", "# but not rows and cols are specified", "secondary_ys", "=", "[", "None", "]", "*", "len", "(", "rows", ")", "# Apply rows / cols", "if", "rows", "is", "not", "None", ":", "for", "trace", ",", "row", ",", "col", ",", "secondary_y", "in", "zip", "(", "data", ",", "rows", ",", "cols", ",", "secondary_ys", ")", ":", "self", ".", "_set_trace_grid_position", "(", "trace", ",", "row", ",", "col", ",", "secondary_y", ")", "# Make deep copy of trace data (Optimize later if needed)", "new_traces_data", "=", "[", "deepcopy", "(", "trace", ".", "_props", ")", "for", "trace", "in", "data", "]", "# Update trace parent", "for", "trace", "in", "data", ":", "trace", ".", "_parent", "=", "self", "trace", ".", "_orphan_props", ".", "clear", "(", ")", "# Update python side", "# Use extend instead of assignment so we don't trigger serialization", "self", ".", "_data", ".", "extend", "(", "new_traces_data", ")", "self", ".", "_data_defaults", "=", "self", ".", "_data_defaults", "+", "[", "{", "}", "for", "_", "in", "data", "]", "self", ".", "_data_objs", "=", "self", ".", "_data_objs", "+", "data", "# Update messages", "self", ".", "_send_addTraces_msg", "(", "new_traces_data", ")", "return", "self" ]
[ 1654, 4 ]
[ 1784, 19 ]
python
en
['en', 'error', 'th']
False
BaseFigure.print_grid
(self)
Print a visual layout of the figure's axes arrangement. This is only valid for figures that are created with plotly.tools.make_subplots.
Print a visual layout of the figure's axes arrangement. This is only valid for figures that are created with plotly.tools.make_subplots.
def print_grid(self): """ Print a visual layout of the figure's axes arrangement. This is only valid for figures that are created with plotly.tools.make_subplots. """ if self._grid_str is None: raise Exception( "Use plotly.tools.make_subplots " "to create a subplot grid." ) print(self._grid_str)
[ "def", "print_grid", "(", "self", ")", ":", "if", "self", ".", "_grid_str", "is", "None", ":", "raise", "Exception", "(", "\"Use plotly.tools.make_subplots \"", "\"to create a subplot grid.\"", ")", "print", "(", "self", ".", "_grid_str", ")" ]
[ 1788, 4 ]
[ 1798, 29 ]
python
en
['en', 'error', 'th']
False
BaseFigure.append_trace
(self, trace, row, col)
Add a trace to the figure bound to axes at the specified row, col index. A row, col index grid is generated for figures created with plotly.tools.make_subplots, and can be viewed with the `print_grid` method Parameters ---------- trace The data trace to be bound row: int Subplot row index (see Figure.print_grid) col: int Subplot column index (see Figure.print_grid) Examples -------- >>> from plotly import tools >>> import plotly.graph_objs as go >>> # stack two subplots vertically >>> fig = tools.make_subplots(rows=2) This is the format of your plot grid: [ (1,1) x1,y1 ] [ (2,1) x2,y2 ] >>> fig.append_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1) >>> fig.append_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1)
Add a trace to the figure bound to axes at the specified row, col index.
def append_trace(self, trace, row, col): """ Add a trace to the figure bound to axes at the specified row, col index. A row, col index grid is generated for figures created with plotly.tools.make_subplots, and can be viewed with the `print_grid` method Parameters ---------- trace The data trace to be bound row: int Subplot row index (see Figure.print_grid) col: int Subplot column index (see Figure.print_grid) Examples -------- >>> from plotly import tools >>> import plotly.graph_objs as go >>> # stack two subplots vertically >>> fig = tools.make_subplots(rows=2) This is the format of your plot grid: [ (1,1) x1,y1 ] [ (2,1) x2,y2 ] >>> fig.append_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1) >>> fig.append_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1) """ warnings.warn( """\ The append_trace method is deprecated and will be removed in a future version. Please use the add_trace method with the row and col parameters. """, DeprecationWarning, ) self.add_trace(trace=trace, row=row, col=col)
[ "def", "append_trace", "(", "self", ",", "trace", ",", "row", ",", "col", ")", ":", "warnings", ".", "warn", "(", "\"\"\"\\\nThe append_trace method is deprecated and will be removed in a future version.\nPlease use the add_trace method with the row and col parameters.\n\"\"\"", ",", "DeprecationWarning", ",", ")", "self", ".", "add_trace", "(", "trace", "=", "trace", ",", "row", "=", "row", ",", "col", "=", "col", ")" ]
[ 1800, 4 ]
[ 1841, 53 ]
python
en
['en', 'error', 'th']
False
BaseFigure.get_subplot
(self, row, col, secondary_y=False)
Return an object representing the subplot at the specified row and column. May only be used on Figures created using plotly.tools.make_subplots Parameters ---------- row: int 1-based index of subplot row col: int 1-based index of subplot column secondary_y: bool If True, select the subplot that consists of the x-axis and the secondary y-axis at the specified row/col. Only valid if the subplot at row/col is an 2D cartesian subplot that was created with a secondary y-axis. See the docstring for the specs argument to make_subplots for more info on creating a subplot with a secondary y-axis. Returns ------- subplot * None: if subplot is empty * plotly.graph_objs.layout.Scene: if subplot type is 'scene' * plotly.graph_objs.layout.Polar: if subplot type is 'polar' * plotly.graph_objs.layout.Ternary: if subplot type is 'ternary' * plotly.graph_objs.layout.Mapbox: if subplot type is 'ternary' * SubplotDomain namedtuple with `x` and `y` fields: if subplot type is 'domain'. - x: length 2 list of the subplot start and stop width - y: length 2 list of the subplot start and stop height * SubplotXY namedtuple with `xaxis` and `yaxis` fields: if subplot type is 'xy'. - xaxis: plotly.graph_objs.layout.XAxis instance for subplot - yaxis: plotly.graph_objs.layout.YAxis instance for subplot
Return an object representing the subplot at the specified row and column. May only be used on Figures created using plotly.tools.make_subplots
def get_subplot(self, row, col, secondary_y=False): """ Return an object representing the subplot at the specified row and column. May only be used on Figures created using plotly.tools.make_subplots Parameters ---------- row: int 1-based index of subplot row col: int 1-based index of subplot column secondary_y: bool If True, select the subplot that consists of the x-axis and the secondary y-axis at the specified row/col. Only valid if the subplot at row/col is an 2D cartesian subplot that was created with a secondary y-axis. See the docstring for the specs argument to make_subplots for more info on creating a subplot with a secondary y-axis. Returns ------- subplot * None: if subplot is empty * plotly.graph_objs.layout.Scene: if subplot type is 'scene' * plotly.graph_objs.layout.Polar: if subplot type is 'polar' * plotly.graph_objs.layout.Ternary: if subplot type is 'ternary' * plotly.graph_objs.layout.Mapbox: if subplot type is 'ternary' * SubplotDomain namedtuple with `x` and `y` fields: if subplot type is 'domain'. - x: length 2 list of the subplot start and stop width - y: length 2 list of the subplot start and stop height * SubplotXY namedtuple with `xaxis` and `yaxis` fields: if subplot type is 'xy'. - xaxis: plotly.graph_objs.layout.XAxis instance for subplot - yaxis: plotly.graph_objs.layout.YAxis instance for subplot """ from plotly.subplots import _get_grid_subplot return _get_grid_subplot(self, row, col, secondary_y)
[ "def", "get_subplot", "(", "self", ",", "row", ",", "col", ",", "secondary_y", "=", "False", ")", ":", "from", "plotly", ".", "subplots", "import", "_get_grid_subplot", "return", "_get_grid_subplot", "(", "self", ",", "row", ",", "col", ",", "secondary_y", ")" ]
[ 1865, 4 ]
[ 1903, 61 ]
python
en
['en', 'error', 'th']
False