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
Currentvalue.offset
(self)
The amount of space, in pixels, between the current value label and the slider. The 'offset' property is a number and may be specified as: - An int or float Returns ------- int|float
The amount of space, in pixels, between the current value label and the slider. The 'offset' property is a number and may be specified as: - An int or float
def offset(self): """ The amount of space, in pixels, between the current value label and the slider. The 'offset' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["offset"]
[ "def", "offset", "(", "self", ")", ":", "return", "self", "[", "\"offset\"", "]" ]
[ 61, 4 ]
[ 73, 29 ]
python
en
['en', 'error', 'th']
False
Currentvalue.prefix
(self)
When currentvalue.visible is true, this sets the prefix of the label. The 'prefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
When currentvalue.visible is true, this sets the prefix of the label. The 'prefix' property is a string and must be specified as: - A string - A number that will be converted to a string
def prefix(self): """ When currentvalue.visible is true, this sets the prefix of the label. The 'prefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["prefix"]
[ "def", "prefix", "(", "self", ")", ":", "return", "self", "[", "\"prefix\"", "]" ]
[ 82, 4 ]
[ 95, 29 ]
python
en
['en', 'error', 'th']
False
Currentvalue.suffix
(self)
When currentvalue.visible is true, this sets the suffix of the label. The 'suffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
When currentvalue.visible is true, this sets the suffix of the label. The 'suffix' property is a string and must be specified as: - A string - A number that will be converted to a string
def suffix(self): """ When currentvalue.visible is true, this sets the suffix of the label. The 'suffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["suffix"]
[ "def", "suffix", "(", "self", ")", ":", "return", "self", "[", "\"suffix\"", "]" ]
[ 104, 4 ]
[ 117, 29 ]
python
en
['en', 'error', 'th']
False
Currentvalue.visible
(self)
Shows the currently-selected value above the slider. The 'visible' property must be specified as a bool (either True, or False) Returns ------- bool
Shows the currently-selected value above the slider. The 'visible' property must be specified as a bool (either True, or False)
def visible(self): """ Shows the currently-selected value above the slider. The 'visible' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["visible"]
[ "def", "visible", "(", "self", ")", ":", "return", "self", "[", "\"visible\"", "]" ]
[ 126, 4 ]
[ 137, 30 ]
python
en
['en', 'error', 'th']
False
Currentvalue.xanchor
(self)
The alignment of the value readout relative to the length of the slider. The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'center', 'right'] Returns ------- Any
The alignment of the value readout relative to the length of the slider. The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'center', 'right']
def xanchor(self): """ The alignment of the value readout relative to the length of the slider. The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'center', 'right'] Returns ------- Any """ return self["xanchor"]
[ "def", "xanchor", "(", "self", ")", ":", "return", "self", "[", "\"xanchor\"", "]" ]
[ 146, 4 ]
[ 159, 30 ]
python
en
['en', 'error', 'th']
False
Currentvalue.__init__
( self, arg=None, font=None, offset=None, prefix=None, suffix=None, visible=None, xanchor=None, **kwargs )
Construct a new Currentvalue object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.slider.Currentvalue` font Sets the font of the current value label text. offset The amount of space, in pixels, between the current value label and the slider. prefix When currentvalue.visible is true, this sets the prefix of the label. suffix When currentvalue.visible is true, this sets the suffix of the label. visible Shows the currently-selected value above the slider. xanchor The alignment of the value readout relative to the length of the slider. Returns ------- Currentvalue
Construct a new Currentvalue object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.slider.Currentvalue` font Sets the font of the current value label text. offset The amount of space, in pixels, between the current value label and the slider. prefix When currentvalue.visible is true, this sets the prefix of the label. suffix When currentvalue.visible is true, this sets the suffix of the label. visible Shows the currently-selected value above the slider. xanchor The alignment of the value readout relative to the length of the slider.
def __init__( self, arg=None, font=None, offset=None, prefix=None, suffix=None, visible=None, xanchor=None, **kwargs ): """ Construct a new Currentvalue object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.slider.Currentvalue` font Sets the font of the current value label text. offset The amount of space, in pixels, between the current value label and the slider. prefix When currentvalue.visible is true, this sets the prefix of the label. suffix When currentvalue.visible is true, this sets the suffix of the label. visible Shows the currently-selected value above the slider. xanchor The alignment of the value readout relative to the length of the slider. Returns ------- Currentvalue """ super(Currentvalue, self).__init__("currentvalue") 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.slider.Currentvalue constructor must be a dict or an instance of :class:`plotly.graph_objs.layout.slider.Currentvalue`""" ) # 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("offset", None) _v = offset if offset is not None else _v if _v is not None: self["offset"] = _v _v = arg.pop("prefix", None) _v = prefix if prefix is not None else _v if _v is not None: self["prefix"] = _v _v = arg.pop("suffix", None) _v = suffix if suffix is not None else _v if _v is not None: self["suffix"] = _v _v = arg.pop("visible", None) _v = visible if visible is not None else _v if _v is not None: self["visible"] = _v _v = arg.pop("xanchor", None) _v = xanchor if xanchor is not None else _v if _v is not None: self["xanchor"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "font", "=", "None", ",", "offset", "=", "None", ",", "prefix", "=", "None", ",", "suffix", "=", "None", ",", "visible", "=", "None", ",", "xanchor", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Currentvalue", ",", "self", ")", ".", "__init__", "(", "\"currentvalue\"", ")", "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.slider.Currentvalue \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.layout.slider.Currentvalue`\"\"\"", ")", "# 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", "(", "\"offset\"", ",", "None", ")", "_v", "=", "offset", "if", "offset", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"offset\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"prefix\"", ",", "None", ")", "_v", "=", "prefix", "if", "prefix", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"prefix\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"suffix\"", ",", "None", ")", "_v", "=", "suffix", "if", "suffix", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"suffix\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"visible\"", ",", "None", ")", "_v", "=", "visible", "if", "visible", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"visible\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"xanchor\"", ",", "None", ")", "_v", "=", "xanchor", "if", "xanchor", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"xanchor\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 188, 4 ]
[ 289, 34 ]
python
en
['en', 'error', 'th']
False
WizardDictAgent.tokenize
(self, text, building=False)
Returns a sequence of tokens from the iterable.
Returns a sequence of tokens from the iterable.
def tokenize(self, text, building=False): """ Returns a sequence of tokens from the iterable. """ if self.lower: text = text.lower() if self.tokenizer == 're': return self.re_tokenize(text) elif self.tokenizer == 'whitespace': return text.split(' ') word_tokens = ( text.replace('.', ' . ') .replace('. . .', '...') .replace(',', ' , ') .replace(';', ' ; ') .replace(':', ' : ') .replace('!', ' ! ') .replace('?', ' ? ') .replace(' ', ' ') .replace(' ', ' ') .strip() .split(" ") ) return word_tokens
[ "def", "tokenize", "(", "self", ",", "text", ",", "building", "=", "False", ")", ":", "if", "self", ".", "lower", ":", "text", "=", "text", ".", "lower", "(", ")", "if", "self", ".", "tokenizer", "==", "'re'", ":", "return", "self", ".", "re_tokenize", "(", "text", ")", "elif", "self", ".", "tokenizer", "==", "'whitespace'", ":", "return", "text", ".", "split", "(", "' '", ")", "word_tokens", "=", "(", "text", ".", "replace", "(", "'.'", ",", "' . '", ")", ".", "replace", "(", "'. . .'", ",", "'...'", ")", ".", "replace", "(", "','", ",", "' , '", ")", ".", "replace", "(", "';'", ",", "' ; '", ")", ".", "replace", "(", "':'", ",", "' : '", ")", ".", "replace", "(", "'!'", ",", "' ! '", ")", ".", "replace", "(", "'?'", ",", "' ? '", ")", ".", "replace", "(", "' '", ",", "' '", ")", ".", "replace", "(", "' '", ",", "' '", ")", ".", "strip", "(", ")", ".", "split", "(", "\" \"", ")", ")", "return", "word_tokens" ]
[ 64, 4 ]
[ 91, 26 ]
python
en
['en', 'error', 'th']
False
WizardDictAgent.re_tokenize
(self, text)
This splits along whitespace and punctuation and keeps the newline as a token in the returned list.
This splits along whitespace and punctuation and keeps the newline as a token in the returned list.
def re_tokenize(self, text): """ This splits along whitespace and punctuation and keeps the newline as a token in the returned list. """ return RETOK.findall(text)
[ "def", "re_tokenize", "(", "self", ",", "text", ")", ":", "return", "RETOK", ".", "findall", "(", "text", ")" ]
[ 93, 4 ]
[ 98, 34 ]
python
en
['en', 'error', 'th']
False
CmdUnconnectedConnect.func
(self)
Uses the Django admin api. Note that unlogged-in commands have a unique position in that their `func()` receives a session object instead of a `source_object` like all other types of logged-in commands (this is because there is no object yet before the account has logged in)
Uses the Django admin api. Note that unlogged-in commands have a unique position in that their `func()` receives a session object instead of a `source_object` like all other types of logged-in commands (this is because there is no object yet before the account has logged in)
def func(self): """ Uses the Django admin api. Note that unlogged-in commands have a unique position in that their `func()` receives a session object instead of a `source_object` like all other types of logged-in commands (this is because there is no object yet before the account has logged in) """ session = self.caller arglist = self.arglist if not arglist or len(arglist) < 2: session.msg("\n\r Usage (without <>): connect <email> <password>") return email = arglist[0] password = arglist[1] # Match an email address to an account. account = AccountDB.objects.get_account_from_email(email) # No accountname match if not account: string = "The email '%s' does not match any accounts." % email string += "\n\r\n\rIf you are new you should first create a new account " string += "using the 'create' command." session.msg(string) return # We have at least one result, so we can check the password. if not account[0].check_password(password): session.msg("Incorrect password.") return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0] == account.name for tup in bans) or any(tup[2].match(session.address[0]) for tup in bans if tup[2])): # this is a banned IP or name! string = "|rYou have been banned and cannot continue from here." string += "\nIf you feel this ban is in error, please email an admin.|x" session.msg(string) session.execute_cmd("quit") return # actually do the login. This will call all hooks. session.sessionhandler.login(session, account)
[ "def", "func", "(", "self", ")", ":", "session", "=", "self", ".", "caller", "arglist", "=", "self", ".", "arglist", "if", "not", "arglist", "or", "len", "(", "arglist", ")", "<", "2", ":", "session", ".", "msg", "(", "\"\\n\\r Usage (without <>): connect <email> <password>\"", ")", "return", "email", "=", "arglist", "[", "0", "]", "password", "=", "arglist", "[", "1", "]", "# Match an email address to an account.", "account", "=", "AccountDB", ".", "objects", ".", "get_account_from_email", "(", "email", ")", "# No accountname match", "if", "not", "account", ":", "string", "=", "\"The email '%s' does not match any accounts.\"", "%", "email", "string", "+=", "\"\\n\\r\\n\\rIf you are new you should first create a new account \"", "string", "+=", "\"using the 'create' command.\"", "session", ".", "msg", "(", "string", ")", "return", "# We have at least one result, so we can check the password.", "if", "not", "account", "[", "0", "]", ".", "check_password", "(", "password", ")", ":", "session", ".", "msg", "(", "\"Incorrect password.\"", ")", "return", "# Check IP and/or name bans", "bans", "=", "ServerConfig", ".", "objects", ".", "conf", "(", "\"server_bans\"", ")", "if", "bans", "and", "(", "any", "(", "tup", "[", "0", "]", "==", "account", ".", "name", "for", "tup", "in", "bans", ")", "or", "any", "(", "tup", "[", "2", "]", ".", "match", "(", "session", ".", "address", "[", "0", "]", ")", "for", "tup", "in", "bans", "if", "tup", "[", "2", "]", ")", ")", ":", "# this is a banned IP or name!", "string", "=", "\"|rYou have been banned and cannot continue from here.\"", "string", "+=", "\"\\nIf you feel this ban is in error, please email an admin.|x\"", "session", ".", "msg", "(", "string", ")", "session", ".", "execute_cmd", "(", "\"quit\"", ")", "return", "# actually do the login. This will call all hooks.", "session", ".", "sessionhandler", ".", "login", "(", "session", ",", "account", ")" ]
[ 73, 4 ]
[ 117, 54 ]
python
en
['en', 'error', 'th']
False
CmdUnconnectedCreate.parse
(self)
The parser must handle the multiple-word account name enclosed in quotes: connect "Long name with many words" [email protected] mypassw
The parser must handle the multiple-word account name enclosed in quotes: connect "Long name with many words" my
def parse(self): """ The parser must handle the multiple-word account name enclosed in quotes: connect "Long name with many words" [email protected] mypassw """ super(CmdUnconnectedCreate, self).parse() self.accountinfo = [] if len(self.arglist) < 3: return if len(self.arglist) > 3: # this means we have a multi_word accountname. pop from the back. password = self.arglist.pop() email = self.arglist.pop() # what remains is the accountname. accountname = " ".join(self.arglist) else: accountname, email, password = self.arglist accountname = accountname.replace('"', '') # remove " accountname = accountname.replace("'", "") self.accountinfo = (accountname, email, password)
[ "def", "parse", "(", "self", ")", ":", "super", "(", "CmdUnconnectedCreate", ",", "self", ")", ".", "parse", "(", ")", "self", ".", "accountinfo", "=", "[", "]", "if", "len", "(", "self", ".", "arglist", ")", "<", "3", ":", "return", "if", "len", "(", "self", ".", "arglist", ")", ">", "3", ":", "# this means we have a multi_word accountname. pop from the back.", "password", "=", "self", ".", "arglist", ".", "pop", "(", ")", "email", "=", "self", ".", "arglist", ".", "pop", "(", ")", "# what remains is the accountname.", "accountname", "=", "\" \"", ".", "join", "(", "self", ".", "arglist", ")", "else", ":", "accountname", ",", "email", ",", "password", "=", "self", ".", "arglist", "accountname", "=", "accountname", ".", "replace", "(", "'\"'", ",", "''", ")", "# remove \"", "accountname", "=", "accountname", ".", "replace", "(", "\"'\"", ",", "\"\"", ")", "self", ".", "accountinfo", "=", "(", "accountname", ",", "email", ",", "password", ")" ]
[ 134, 4 ]
[ 156, 57 ]
python
en
['en', 'error', 'th']
False
CmdUnconnectedCreate.func
(self)
Do checks and create account
Do checks and create account
def func(self): """Do checks and create account""" session = self.caller try: accountname, email, password = self.accountinfo except ValueError: string = "\n\r Usage (without <>): create \"<accountname>\" <email> <password>" session.msg(string) return if not email or not password: session.msg("\n\r You have to supply an e-mail address followed by a password.") return if not utils.validate_email_address(email): # check so the email at least looks ok. session.msg("'%s' is not a valid e-mail address." % email) return # sanity checks if not re.findall(r"^[\w. @+\-']+$", accountname) or not (0 < len(accountname) <= 30): # this echoes the restrictions made by django's auth # module (except not allowing spaces, for convenience of # logging in). string = "\n\r Accountname can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_/' only." session.msg(string) return # strip excessive spaces in accountname accountname = re.sub(r"\s+", " ", accountname).strip() if AccountDB.objects.filter(username__iexact=accountname): # account already exists (we also ignore capitalization here) session.msg("Sorry, there is already an account with the name '%s'." % accountname) return if AccountDB.objects.get_account_from_email(email): # email already set on an account session.msg("Sorry, there is already an account with that email address.") return # Reserve accountnames found in GUEST_LIST if settings.GUEST_LIST and accountname.lower() in (guest.lower() for guest in settings.GUEST_LIST): string = "\n\r That name is reserved. Please choose another Accountname." session.msg(string) return if not re.findall(r"^[\w. @+\-']+$", password) or not (3 < len(password)): string = "\n\r Password should be longer than 3 characters. Letters, spaces, digits and @/./+/-/_/' only." \ "\nFor best security, make it longer than 8 characters. You can also use a phrase of" \ "\nmany words if you enclose the password in double quotes." session.msg(string) return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0] == accountname.lower() for tup in bans) or any(tup[2].match(session.address) for tup in bans if tup[2])): # this is a banned IP or name! string = "|rYou have been banned and cannot continue from here." \ "\nIf you feel this ban is in error, please email an admin.|x" session.msg(string) session.sessionhandler.disconnect(session, "Good bye! Disconnecting.") return # everything's ok. Create the new player account. try: permissions = settings.PERMISSION_ACCOUNT_DEFAULT typeclass = settings.BASE_CHARACTER_TYPECLASS new_account = default_unloggedin._create_account(session, accountname, password, permissions, email=email) if new_account: if MULTISESSION_MODE < 2: default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME) default_unloggedin._create_character(session, new_account, typeclass, default_home, permissions) # tell the caller everything went well. string = "A new account '%s' was created. Welcome!" if " " in accountname: string += "\n\nYou can now log in with the command 'connect \"%s\" <your password>'." else: string += "\n\nYou can now log with the command 'connect %s <your password>'." session.msg(string % (accountname, email)) except Exception: # We are in the middle between logged in and -not, so we have # to handle tracebacks ourselves at this point. If we don't, # we won't see any errors at all. session.msg("An error occurred. Please e-mail an admin if the problem persists.") logger.log_trace() raise
[ "def", "func", "(", "self", ")", ":", "session", "=", "self", ".", "caller", "try", ":", "accountname", ",", "email", ",", "password", "=", "self", ".", "accountinfo", "except", "ValueError", ":", "string", "=", "\"\\n\\r Usage (without <>): create \\\"<accountname>\\\" <email> <password>\"", "session", ".", "msg", "(", "string", ")", "return", "if", "not", "email", "or", "not", "password", ":", "session", ".", "msg", "(", "\"\\n\\r You have to supply an e-mail address followed by a password.\"", ")", "return", "if", "not", "utils", ".", "validate_email_address", "(", "email", ")", ":", "# check so the email at least looks ok.", "session", ".", "msg", "(", "\"'%s' is not a valid e-mail address.\"", "%", "email", ")", "return", "# sanity checks", "if", "not", "re", ".", "findall", "(", "r\"^[\\w. @+\\-']+$\"", ",", "accountname", ")", "or", "not", "(", "0", "<", "len", "(", "accountname", ")", "<=", "30", ")", ":", "# this echoes the restrictions made by django's auth", "# module (except not allowing spaces, for convenience of", "# logging in).", "string", "=", "\"\\n\\r Accountname can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_/' only.\"", "session", ".", "msg", "(", "string", ")", "return", "# strip excessive spaces in accountname", "accountname", "=", "re", ".", "sub", "(", "r\"\\s+\"", ",", "\" \"", ",", "accountname", ")", ".", "strip", "(", ")", "if", "AccountDB", ".", "objects", ".", "filter", "(", "username__iexact", "=", "accountname", ")", ":", "# account already exists (we also ignore capitalization here)", "session", ".", "msg", "(", "\"Sorry, there is already an account with the name '%s'.\"", "%", "accountname", ")", "return", "if", "AccountDB", ".", "objects", ".", "get_account_from_email", "(", "email", ")", ":", "# email already set on an account", "session", ".", "msg", "(", "\"Sorry, there is already an account with that email address.\"", ")", "return", "# Reserve accountnames found in GUEST_LIST", "if", "settings", ".", "GUEST_LIST", "and", "accountname", ".", "lower", "(", ")", "in", "(", "guest", ".", "lower", "(", ")", "for", "guest", "in", "settings", ".", "GUEST_LIST", ")", ":", "string", "=", "\"\\n\\r That name is reserved. Please choose another Accountname.\"", "session", ".", "msg", "(", "string", ")", "return", "if", "not", "re", ".", "findall", "(", "r\"^[\\w. @+\\-']+$\"", ",", "password", ")", "or", "not", "(", "3", "<", "len", "(", "password", ")", ")", ":", "string", "=", "\"\\n\\r Password should be longer than 3 characters. Letters, spaces, digits and @/./+/-/_/' only.\"", "\"\\nFor best security, make it longer than 8 characters. You can also use a phrase of\"", "\"\\nmany words if you enclose the password in double quotes.\"", "session", ".", "msg", "(", "string", ")", "return", "# Check IP and/or name bans", "bans", "=", "ServerConfig", ".", "objects", ".", "conf", "(", "\"server_bans\"", ")", "if", "bans", "and", "(", "any", "(", "tup", "[", "0", "]", "==", "accountname", ".", "lower", "(", ")", "for", "tup", "in", "bans", ")", "or", "any", "(", "tup", "[", "2", "]", ".", "match", "(", "session", ".", "address", ")", "for", "tup", "in", "bans", "if", "tup", "[", "2", "]", ")", ")", ":", "# this is a banned IP or name!", "string", "=", "\"|rYou have been banned and cannot continue from here.\"", "\"\\nIf you feel this ban is in error, please email an admin.|x\"", "session", ".", "msg", "(", "string", ")", "session", ".", "sessionhandler", ".", "disconnect", "(", "session", ",", "\"Good bye! Disconnecting.\"", ")", "return", "# everything's ok. Create the new player account.", "try", ":", "permissions", "=", "settings", ".", "PERMISSION_ACCOUNT_DEFAULT", "typeclass", "=", "settings", ".", "BASE_CHARACTER_TYPECLASS", "new_account", "=", "default_unloggedin", ".", "_create_account", "(", "session", ",", "accountname", ",", "password", ",", "permissions", ",", "email", "=", "email", ")", "if", "new_account", ":", "if", "MULTISESSION_MODE", "<", "2", ":", "default_home", "=", "ObjectDB", ".", "objects", ".", "get_id", "(", "settings", ".", "DEFAULT_HOME", ")", "default_unloggedin", ".", "_create_character", "(", "session", ",", "new_account", ",", "typeclass", ",", "default_home", ",", "permissions", ")", "# tell the caller everything went well.", "string", "=", "\"A new account '%s' was created. Welcome!\"", "if", "\" \"", "in", "accountname", ":", "string", "+=", "\"\\n\\nYou can now log in with the command 'connect \\\"%s\\\" <your password>'.\"", "else", ":", "string", "+=", "\"\\n\\nYou can now log with the command 'connect %s <your password>'.\"", "session", ".", "msg", "(", "string", "%", "(", "accountname", ",", "email", ")", ")", "except", "Exception", ":", "# We are in the middle between logged in and -not, so we have", "# to handle tracebacks ourselves at this point. If we don't,", "# we won't see any errors at all.", "session", ".", "msg", "(", "\"An error occurred. Please e-mail an admin if the problem persists.\"", ")", "logger", ".", "log_trace", "(", ")", "raise" ]
[ 158, 4 ]
[ 239, 17 ]
python
en
['en', 'mi', 'en']
True
CmdUnconnectedQuit.func
(self)
Simply close the connection.
Simply close the connection.
def func(self): """Simply close the connection.""" session = self.caller session.sessionhandler.disconnect(session, "Good bye! Disconnecting.")
[ "def", "func", "(", "self", ")", ":", "session", "=", "self", ".", "caller", "session", ".", "sessionhandler", ".", "disconnect", "(", "session", ",", "\"Good bye! Disconnecting.\"", ")" ]
[ 252, 4 ]
[ 255, 78 ]
python
en
['en', 'en', 'en']
True
CmdUnconnectedLook.func
(self)
Show the connect screen.
Show the connect screen.
def func(self): """Show the connect screen.""" self.caller.msg(CONNECTION_SCREEN)
[ "def", "func", "(", "self", ")", ":", "self", ".", "caller", ".", "msg", "(", "CONNECTION_SCREEN", ")" ]
[ 269, 4 ]
[ 271, 42 ]
python
en
['en', 'en', 'en']
True
UnloggedinCmdSet.at_cmdset_creation
(self)
Populate the cmdset
Populate the cmdset
def at_cmdset_creation(self): """Populate the cmdset""" self.add(CmdUnconnectedConnect()) self.add(CmdUnconnectedCreate()) self.add(CmdUnconnectedQuit()) self.add(CmdUnconnectedLook()) self.add(CmdUnconnectedHelp())
[ "def", "at_cmdset_creation", "(", "self", ")", ":", "self", ".", "add", "(", "CmdUnconnectedConnect", "(", ")", ")", "self", ".", "add", "(", "CmdUnconnectedCreate", "(", ")", ")", "self", ".", "add", "(", "CmdUnconnectedQuit", "(", ")", ")", "self", ".", "add", "(", "CmdUnconnectedLook", "(", ")", ")", "self", ".", "add", "(", "CmdUnconnectedHelp", "(", ")", ")" ]
[ 325, 4 ]
[ 331, 38 ]
python
en
['en', 'zh', 'en']
True
Textfont.color
(self)
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 list or array of any of the above Returns ------- str|numpy.ndarray
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 list or array of any of the above
def color(self): """ 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 list or array of any of the above Returns ------- str|numpy.ndarray """ return self["color"]
[ "def", "color", "(", "self", ")", ":", "return", "self", "[", "\"color\"", "]" ]
[ 15, 4 ]
[ 64, 28 ]
python
en
['en', 'error', 'th']
False
Textfont.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\"", "]" ]
[ 73, 4 ]
[ 84, 31 ]
python
en
['en', 'error', 'th']
False
Textfont.family
(self)
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". The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray
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". The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above
def family(self): """ 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". The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["family"]
[ "def", "family", "(", "self", ")", ":", "return", "self", "[", "\"family\"", "]" ]
[ 93, 4 ]
[ 116, 29 ]
python
en
['en', 'error', 'th']
False
Textfont.familysrc
(self)
Sets the source reference on Chart Studio Cloud for family . The 'familysrc' 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 family . The 'familysrc' property must be specified as a string or as a plotly.grid_objs.Column object
def familysrc(self): """ Sets the source reference on Chart Studio Cloud for family . The 'familysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["familysrc"]
[ "def", "familysrc", "(", "self", ")", ":", "return", "self", "[", "\"familysrc\"", "]" ]
[ 125, 4 ]
[ 136, 32 ]
python
en
['en', 'error', 'th']
False
Textfont.size
(self)
The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray
The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above
def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray """ return self["size"]
[ "def", "size", "(", "self", ")", ":", "return", "self", "[", "\"size\"", "]" ]
[ 145, 4 ]
[ 155, 27 ]
python
en
['en', 'error', 'th']
False
Textfont.sizesrc
(self)
Sets the source reference on Chart Studio Cloud for size . The 'sizesrc' 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 size . The 'sizesrc' property must be specified as a string or as a plotly.grid_objs.Column object
def sizesrc(self): """ Sets the source reference on Chart Studio Cloud for size . The 'sizesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["sizesrc"]
[ "def", "sizesrc", "(", "self", ")", ":", "return", "self", "[", "\"sizesrc\"", "]" ]
[ 164, 4 ]
[ 175, 30 ]
python
en
['en', 'error', 'th']
False
Textfont.__init__
( self, arg=None, color=None, colorsrc=None, family=None, familysrc=None, size=None, sizesrc=None, **kwargs )
Construct a new Textfont object Sets the font used for `textinfo`. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.funnelarea.Textfont` color colorsrc Sets the source reference on Chart Studio Cloud for 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". familysrc Sets the source reference on Chart Studio Cloud for family . size sizesrc Sets the source reference on Chart Studio Cloud for size . Returns ------- Textfont
Construct a new Textfont object Sets the font used for `textinfo`.
def __init__( self, arg=None, color=None, colorsrc=None, family=None, familysrc=None, size=None, sizesrc=None, **kwargs ): """ Construct a new Textfont object Sets the font used for `textinfo`. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.funnelarea.Textfont` color colorsrc Sets the source reference on Chart Studio Cloud for 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". familysrc Sets the source reference on Chart Studio Cloud for family . size sizesrc Sets the source reference on Chart Studio Cloud for size . Returns ------- Textfont """ super(Textfont, self).__init__("textfont") 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.funnelarea.Textfont constructor must be a dict or an instance of :class:`plotly.graph_objs.funnelarea.Textfont`""" ) # 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("color", None) _v = color if color is not None else _v if _v is not None: self["color"] = _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("family", None) _v = family if family is not None else _v if _v is not None: self["family"] = _v _v = arg.pop("familysrc", None) _v = familysrc if familysrc is not None else _v if _v is not None: self["familysrc"] = _v _v = arg.pop("size", None) _v = size if size is not None else _v if _v is not None: self["size"] = _v _v = arg.pop("sizesrc", None) _v = sizesrc if sizesrc is not None else _v if _v is not None: self["sizesrc"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "color", "=", "None", ",", "colorsrc", "=", "None", ",", "family", "=", "None", ",", "familysrc", "=", "None", ",", "size", "=", "None", ",", "sizesrc", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Textfont", ",", "self", ")", ".", "__init__", "(", "\"textfont\"", ")", "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.funnelarea.Textfont \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.funnelarea.Textfont`\"\"\"", ")", "# 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", "(", "\"color\"", ",", "None", ")", "_v", "=", "color", "if", "color", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"color\"", "]", "=", "_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", "(", "\"family\"", ",", "None", ")", "_v", "=", "family", "if", "family", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"family\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"familysrc\"", ",", "None", ")", "_v", "=", "familysrc", "if", "familysrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"familysrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"size\"", ",", "None", ")", "_v", "=", "size", "if", "size", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"size\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"sizesrc\"", ",", "None", ")", "_v", "=", "sizesrc", "if", "sizesrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"sizesrc\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 215, 4 ]
[ 329, 34 ]
python
en
['en', 'error', 'th']
False
register_ledger_nym
(request: web.BaseRequest)
Request handler for registering a NYM with the ledger. Args: request: aiohttp request object
Request handler for registering a NYM with the ledger.
async def register_ledger_nym(request: web.BaseRequest): """ Request handler for registering a NYM with the ledger. Args: request: aiohttp request object """ context = request.app["request_context"] ledger = await context.inject(BaseLedger, required=False) if not ledger: raise web.HTTPForbidden() did = request.query.get("did") verkey = request.query.get("verkey") if not did or not verkey: raise web.HTTPBadRequest() alias, role = request.query.get("alias"), request.query.get("role") success = False async with ledger: try: await ledger.register_nym(did, verkey, alias, role) success = True except LedgerTransactionError as e: raise web.HTTPForbidden(text=e.message) return web.json_response({"success": success})
[ "async", "def", "register_ledger_nym", "(", "request", ":", "web", ".", "BaseRequest", ")", ":", "context", "=", "request", ".", "app", "[", "\"request_context\"", "]", "ledger", "=", "await", "context", ".", "inject", "(", "BaseLedger", ",", "required", "=", "False", ")", "if", "not", "ledger", ":", "raise", "web", ".", "HTTPForbidden", "(", ")", "did", "=", "request", ".", "query", ".", "get", "(", "\"did\"", ")", "verkey", "=", "request", ".", "query", ".", "get", "(", "\"verkey\"", ")", "if", "not", "did", "or", "not", "verkey", ":", "raise", "web", ".", "HTTPBadRequest", "(", ")", "alias", ",", "role", "=", "request", ".", "query", ".", "get", "(", "\"alias\"", ")", ",", "request", ".", "query", ".", "get", "(", "\"role\"", ")", "success", "=", "False", "async", "with", "ledger", ":", "try", ":", "await", "ledger", ".", "register_nym", "(", "did", ",", "verkey", ",", "alias", ",", "role", ")", "success", "=", "True", "except", "LedgerTransactionError", "as", "e", ":", "raise", "web", ".", "HTTPForbidden", "(", "text", "=", "e", ".", "message", ")", "return", "web", ".", "json_response", "(", "{", "\"success\"", ":", "success", "}", ")" ]
[ 23, 0 ]
[ 48, 50 ]
python
en
['en', 'error', 'th']
False
get_did_verkey
(request: web.BaseRequest)
Request handler for getting a verkey for a DID from the ledger. Args: request: aiohttp request object
Request handler for getting a verkey for a DID from the ledger.
async def get_did_verkey(request: web.BaseRequest): """ Request handler for getting a verkey for a DID from the ledger. Args: request: aiohttp request object """ context = request.app["request_context"] ledger = await context.inject(BaseLedger, required=False) if not ledger: raise web.HTTPForbidden() did = request.query.get("did") if not did: raise web.HTTPBadRequest() async with ledger: r = await ledger.get_key_for_did(did) return web.json_response({"verkey": r})
[ "async", "def", "get_did_verkey", "(", "request", ":", "web", ".", "BaseRequest", ")", ":", "context", "=", "request", ".", "app", "[", "\"request_context\"", "]", "ledger", "=", "await", "context", ".", "inject", "(", "BaseLedger", ",", "required", "=", "False", ")", "if", "not", "ledger", ":", "raise", "web", ".", "HTTPForbidden", "(", ")", "did", "=", "request", ".", "query", ".", "get", "(", "\"did\"", ")", "if", "not", "did", ":", "raise", "web", ".", "HTTPBadRequest", "(", ")", "async", "with", "ledger", ":", "r", "=", "await", "ledger", ".", "get_key_for_did", "(", "did", ")", "return", "web", ".", "json_response", "(", "{", "\"verkey\"", ":", "r", "}", ")" ]
[ 58, 0 ]
[ 76, 43 ]
python
en
['en', 'error', 'th']
False
get_did_endpoint
(request: web.BaseRequest)
Request handler for getting a verkey for a DID from the ledger. Args: request: aiohttp request object
Request handler for getting a verkey for a DID from the ledger.
async def get_did_endpoint(request: web.BaseRequest): """ Request handler for getting a verkey for a DID from the ledger. Args: request: aiohttp request object """ context = request.app["request_context"] ledger = await context.inject(BaseLedger, required=False) if not ledger: raise web.HTTPForbidden() did = request.query.get("did") if not did: raise web.HTTPBadRequest() async with ledger: r = await ledger.get_endpoint_for_did(did) return web.json_response({"endpoint": r})
[ "async", "def", "get_did_endpoint", "(", "request", ":", "web", ".", "BaseRequest", ")", ":", "context", "=", "request", ".", "app", "[", "\"request_context\"", "]", "ledger", "=", "await", "context", ".", "inject", "(", "BaseLedger", ",", "required", "=", "False", ")", "if", "not", "ledger", ":", "raise", "web", ".", "HTTPForbidden", "(", ")", "did", "=", "request", ".", "query", ".", "get", "(", "\"did\"", ")", "if", "not", "did", ":", "raise", "web", ".", "HTTPBadRequest", "(", ")", "async", "with", "ledger", ":", "r", "=", "await", "ledger", ".", "get_endpoint_for_did", "(", "did", ")", "return", "web", ".", "json_response", "(", "{", "\"endpoint\"", ":", "r", "}", ")" ]
[ 86, 0 ]
[ 104, 45 ]
python
en
['en', 'error', 'th']
False
register
(app: web.Application)
Register routes.
Register routes.
async def register(app: web.Application): """Register routes.""" app.add_routes( [ web.post("/ledger/register-nym", register_ledger_nym), web.get("/ledger/did-verkey", get_did_verkey), web.get("/ledger/did-endpoint", get_did_endpoint) ] )
[ "async", "def", "register", "(", "app", ":", "web", ".", "Application", ")", ":", "app", ".", "add_routes", "(", "[", "web", ".", "post", "(", "\"/ledger/register-nym\"", ",", "register_ledger_nym", ")", ",", "web", ".", "get", "(", "\"/ledger/did-verkey\"", ",", "get_did_verkey", ")", ",", "web", ".", "get", "(", "\"/ledger/did-endpoint\"", ",", "get_did_endpoint", ")", "]", ")" ]
[ 107, 0 ]
[ 116, 5 ]
python
en
['en', 'fr', 'en']
False
Title.font
(self)
Sets this color bar's title font. Note that the title's font used to be set 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.streamtube.colorbar.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.streamtube.colorbar.title.Font
Sets this color bar's title font. Note that the title's font used to be set 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.streamtube.colorbar.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 color bar's title font. Note that the title's font used to be set 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.streamtube.colorbar.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.streamtube.colorbar.title.Font """ return self["font"]
[ "def", "font", "(", "self", ")", ":", "return", "self", "[", "\"font\"", "]" ]
[ 15, 4 ]
[ 53, 27 ]
python
en
['en', 'error', 'th']
False
Title.side
(self)
Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- Any
Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom']
def side(self): """ Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- Any """ return self["side"]
[ "def", "side", "(", "self", ")", ":", "return", "self", "[", "\"side\"", "]" ]
[ 62, 4 ]
[ 76, 27 ]
python
en
['en', 'error', 'th']
False
Title.text
(self)
Sets the title of the color bar. 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 the color bar. 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 the color bar. 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\"", "]" ]
[ 85, 4 ]
[ 99, 27 ]
python
en
['en', 'error', 'th']
False
Title.__init__
(self, arg=None, font=None, side=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.streamtube.colorbar.Title` font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. 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.streamtube.colorbar.Title` font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. 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, side=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.streamtube.colorbar.Title` font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. 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.streamtube.colorbar.Title constructor must be a dict or an instance of :class:`plotly.graph_objs.streamtube.colorbar.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("side", None) _v = side if side is not None else _v if _v is not None: self["side"] = _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", ",", "side", "=", "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.streamtube.colorbar.Title \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.streamtube.colorbar.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", "(", "\"side\"", ",", "None", ")", "_v", "=", "side", "if", "side", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"side\"", "]", "=", "_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" ]
[ 126, 4 ]
[ 203, 34 ]
python
en
['en', 'error', 'th']
False
Dashboard.get_box
(self, box_id)
Returns box from box_id number.
Returns box from box_id number.
def get_box(self, box_id): """Returns box from box_id number.""" box_ids_to_path = self._compute_box_ids() loc_in_dashboard = self["layout"] if box_id not in box_ids_to_path.keys(): raise _plotly_utils.exceptions.PlotlyError(ID_NOT_VALID_MESSAGE) for first_second in box_ids_to_path[box_id]: loc_in_dashboard = loc_in_dashboard[first_second] return loc_in_dashboard
[ "def", "get_box", "(", "self", ",", "box_id", ")", ":", "box_ids_to_path", "=", "self", ".", "_compute_box_ids", "(", ")", "loc_in_dashboard", "=", "self", "[", "\"layout\"", "]", "if", "box_id", "not", "in", "box_ids_to_path", ".", "keys", "(", ")", ":", "raise", "_plotly_utils", ".", "exceptions", ".", "PlotlyError", "(", "ID_NOT_VALID_MESSAGE", ")", "for", "first_second", "in", "box_ids_to_path", "[", "box_id", "]", ":", "loc_in_dashboard", "=", "loc_in_dashboard", "[", "first_second", "]", "return", "loc_in_dashboard" ]
[ 327, 4 ]
[ 336, 31 ]
python
en
['en', 'en', 'en']
True
Dashboard.get_preview
(self)
Returns JSON or HTML respresentation of the dashboard. If IPython is not imported, returns a pretty print of the dashboard dict. Otherwise, returns an IPython.core.display.HTML display of the dashboard. The algorithm used to build the HTML preview involves going through the paths of the node generator of the dashboard. The paths of the dashboard are sequenced through from shorter to longer and whether it's a box or container that lies at the end of the path determines the action. If it's a container, draw a line in the figure to divide the current box into two and store the specs of the resulting two boxes. If the path points to a terminal box (often containing a plot), then draw the box id in the center of the box. It's important to note that these box ids are generated on-the-fly and they do not necessarily stay assigned to the boxes they were once assigned to.
Returns JSON or HTML respresentation of the dashboard.
def get_preview(self): """ Returns JSON or HTML respresentation of the dashboard. If IPython is not imported, returns a pretty print of the dashboard dict. Otherwise, returns an IPython.core.display.HTML display of the dashboard. The algorithm used to build the HTML preview involves going through the paths of the node generator of the dashboard. The paths of the dashboard are sequenced through from shorter to longer and whether it's a box or container that lies at the end of the path determines the action. If it's a container, draw a line in the figure to divide the current box into two and store the specs of the resulting two boxes. If the path points to a terminal box (often containing a plot), then draw the box id in the center of the box. It's important to note that these box ids are generated on-the-fly and they do not necessarily stay assigned to the boxes they were once assigned to. """ if IPython is None: pprint.pprint(self) return elif self["layout"] is None: return IPython.display.HTML(dashboard_html) top_left_x = 0 top_left_y = 0 box_w = MASTER_WIDTH box_h = MASTER_HEIGHT html_figure = dashboard_html box_ids_to_path = self._compute_box_ids() # used to store info about box dimensions path_to_box_specs = {} first_box_specs = { "top_left_x": top_left_x, "top_left_y": top_left_y, "box_w": box_w, "box_h": box_h, } # uses tuples to store paths as for hashable keys path_to_box_specs[("first",)] = first_box_specs # generate all paths all_nodes, all_paths = self._make_all_nodes_and_paths() max_path_len = max(len(path) for path in all_paths) for path_len in range(1, max_path_len + 1): for path in [path for path in all_paths if len(path) == path_len]: current_box_specs = path_to_box_specs[path] if self._path_to_box(path)["type"] == "split": fill_percent = self._path_to_box(path)["size"] direction = self._path_to_box(path)["direction"] is_horizontal = direction == "horizontal" top_left_x = current_box_specs["top_left_x"] top_left_y = current_box_specs["top_left_y"] box_w = current_box_specs["box_w"] box_h = current_box_specs["box_h"] html_figure = _draw_line_through_box( html_figure, top_left_x, top_left_y, box_w, box_h, is_horizontal=is_horizontal, direction=direction, fill_percent=fill_percent, ) # determine the specs for resulting two box split if is_horizontal: new_top_left_x = top_left_x new_top_left_y = top_left_y new_box_w = box_w * (fill_percent / 100.0) new_box_h = box_h new_top_left_x_2 = top_left_x + new_box_w new_top_left_y_2 = top_left_y new_box_w_2 = box_w * ((100 - fill_percent) / 100.0) new_box_h_2 = box_h else: new_top_left_x = top_left_x new_top_left_y = top_left_y new_box_w = box_w new_box_h = box_h * (fill_percent / 100.0) new_top_left_x_2 = top_left_x new_top_left_y_2 = top_left_y + box_h * (fill_percent / 100.0) new_box_w_2 = box_w new_box_h_2 = box_h * ((100 - fill_percent) / 100.0) first_box_specs = { "top_left_x": top_left_x, "top_left_y": top_left_y, "box_w": new_box_w, "box_h": new_box_h, } second_box_specs = { "top_left_x": new_top_left_x_2, "top_left_y": new_top_left_y_2, "box_w": new_box_w_2, "box_h": new_box_h_2, } path_to_box_specs[path + ("first",)] = first_box_specs path_to_box_specs[path + ("second",)] = second_box_specs elif self._path_to_box(path)["type"] == "box": for box_id in box_ids_to_path: if box_ids_to_path[box_id] == path: number = box_id html_figure = _add_html_text( html_figure, number, path_to_box_specs[path]["top_left_x"], path_to_box_specs[path]["top_left_y"], path_to_box_specs[path]["box_w"], path_to_box_specs[path]["box_h"], ) # display HTML representation return IPython.display.HTML(html_figure)
[ "def", "get_preview", "(", "self", ")", ":", "if", "IPython", "is", "None", ":", "pprint", ".", "pprint", "(", "self", ")", "return", "elif", "self", "[", "\"layout\"", "]", "is", "None", ":", "return", "IPython", ".", "display", ".", "HTML", "(", "dashboard_html", ")", "top_left_x", "=", "0", "top_left_y", "=", "0", "box_w", "=", "MASTER_WIDTH", "box_h", "=", "MASTER_HEIGHT", "html_figure", "=", "dashboard_html", "box_ids_to_path", "=", "self", ".", "_compute_box_ids", "(", ")", "# used to store info about box dimensions", "path_to_box_specs", "=", "{", "}", "first_box_specs", "=", "{", "\"top_left_x\"", ":", "top_left_x", ",", "\"top_left_y\"", ":", "top_left_y", ",", "\"box_w\"", ":", "box_w", ",", "\"box_h\"", ":", "box_h", ",", "}", "# uses tuples to store paths as for hashable keys", "path_to_box_specs", "[", "(", "\"first\"", ",", ")", "]", "=", "first_box_specs", "# generate all paths", "all_nodes", ",", "all_paths", "=", "self", ".", "_make_all_nodes_and_paths", "(", ")", "max_path_len", "=", "max", "(", "len", "(", "path", ")", "for", "path", "in", "all_paths", ")", "for", "path_len", "in", "range", "(", "1", ",", "max_path_len", "+", "1", ")", ":", "for", "path", "in", "[", "path", "for", "path", "in", "all_paths", "if", "len", "(", "path", ")", "==", "path_len", "]", ":", "current_box_specs", "=", "path_to_box_specs", "[", "path", "]", "if", "self", ".", "_path_to_box", "(", "path", ")", "[", "\"type\"", "]", "==", "\"split\"", ":", "fill_percent", "=", "self", ".", "_path_to_box", "(", "path", ")", "[", "\"size\"", "]", "direction", "=", "self", ".", "_path_to_box", "(", "path", ")", "[", "\"direction\"", "]", "is_horizontal", "=", "direction", "==", "\"horizontal\"", "top_left_x", "=", "current_box_specs", "[", "\"top_left_x\"", "]", "top_left_y", "=", "current_box_specs", "[", "\"top_left_y\"", "]", "box_w", "=", "current_box_specs", "[", "\"box_w\"", "]", "box_h", "=", "current_box_specs", "[", "\"box_h\"", "]", "html_figure", "=", "_draw_line_through_box", "(", "html_figure", ",", "top_left_x", ",", "top_left_y", ",", "box_w", ",", "box_h", ",", "is_horizontal", "=", "is_horizontal", ",", "direction", "=", "direction", ",", "fill_percent", "=", "fill_percent", ",", ")", "# determine the specs for resulting two box split", "if", "is_horizontal", ":", "new_top_left_x", "=", "top_left_x", "new_top_left_y", "=", "top_left_y", "new_box_w", "=", "box_w", "*", "(", "fill_percent", "/", "100.0", ")", "new_box_h", "=", "box_h", "new_top_left_x_2", "=", "top_left_x", "+", "new_box_w", "new_top_left_y_2", "=", "top_left_y", "new_box_w_2", "=", "box_w", "*", "(", "(", "100", "-", "fill_percent", ")", "/", "100.0", ")", "new_box_h_2", "=", "box_h", "else", ":", "new_top_left_x", "=", "top_left_x", "new_top_left_y", "=", "top_left_y", "new_box_w", "=", "box_w", "new_box_h", "=", "box_h", "*", "(", "fill_percent", "/", "100.0", ")", "new_top_left_x_2", "=", "top_left_x", "new_top_left_y_2", "=", "top_left_y", "+", "box_h", "*", "(", "fill_percent", "/", "100.0", ")", "new_box_w_2", "=", "box_w", "new_box_h_2", "=", "box_h", "*", "(", "(", "100", "-", "fill_percent", ")", "/", "100.0", ")", "first_box_specs", "=", "{", "\"top_left_x\"", ":", "top_left_x", ",", "\"top_left_y\"", ":", "top_left_y", ",", "\"box_w\"", ":", "new_box_w", ",", "\"box_h\"", ":", "new_box_h", ",", "}", "second_box_specs", "=", "{", "\"top_left_x\"", ":", "new_top_left_x_2", ",", "\"top_left_y\"", ":", "new_top_left_y_2", ",", "\"box_w\"", ":", "new_box_w_2", ",", "\"box_h\"", ":", "new_box_h_2", ",", "}", "path_to_box_specs", "[", "path", "+", "(", "\"first\"", ",", ")", "]", "=", "first_box_specs", "path_to_box_specs", "[", "path", "+", "(", "\"second\"", ",", ")", "]", "=", "second_box_specs", "elif", "self", ".", "_path_to_box", "(", "path", ")", "[", "\"type\"", "]", "==", "\"box\"", ":", "for", "box_id", "in", "box_ids_to_path", ":", "if", "box_ids_to_path", "[", "box_id", "]", "==", "path", ":", "number", "=", "box_id", "html_figure", "=", "_add_html_text", "(", "html_figure", ",", "number", ",", "path_to_box_specs", "[", "path", "]", "[", "\"top_left_x\"", "]", ",", "path_to_box_specs", "[", "path", "]", "[", "\"top_left_y\"", "]", ",", "path_to_box_specs", "[", "path", "]", "[", "\"box_w\"", "]", ",", "path_to_box_specs", "[", "path", "]", "[", "\"box_h\"", "]", ",", ")", "# display HTML representation", "return", "IPython", ".", "display", ".", "HTML", "(", "html_figure", ")" ]
[ 338, 4 ]
[ 466, 48 ]
python
en
['en', 'error', 'th']
False
Dashboard.insert
(self, box, side="above", box_id=None, fill_percent=50)
Insert a box into your dashboard layout. :param (dict) box: the box you are inserting into the dashboard. :param (str) side: specifies where your new box is going to be placed relative to the given 'box_id'. Valid values are 'above', 'below', 'left', and 'right'. :param (int) box_id: the box id which is used as a reference for the insertion of the new box. Box ids are memoryless numbers that are generated on-the-fly and assigned to boxes in the layout each time .get_preview() is run. :param (float) fill_percent: specifies the percentage of the container box from the given 'side' that the new box occupies. For example if you apply the method\n .insert(box=new_box, box_id=2, side='left', fill_percent=20)\n to a dashboard object, a new box is inserted 20% from the left side of the box with id #2. Run .get_preview() to see the box ids assigned to each box in the dashboard layout. Default = 50 Example: ``` import plotly.dashboard_objs as dashboard box_a = { 'type': 'box', 'boxType': 'plot', 'fileId': 'username:some#', 'title': 'box a' } my_dboard = dashboard.Dashboard() my_dboard.insert(box_a) my_dboard.insert(box_a, 'left', 1) my_dboard.insert(box_a, 'below', 2) my_dboard.insert(box_a, 'right', 3) my_dboard.insert(box_a, 'above', 4, fill_percent=20) my_dboard.get_preview() ```
Insert a box into your dashboard layout.
def insert(self, box, side="above", box_id=None, fill_percent=50): """ Insert a box into your dashboard layout. :param (dict) box: the box you are inserting into the dashboard. :param (str) side: specifies where your new box is going to be placed relative to the given 'box_id'. Valid values are 'above', 'below', 'left', and 'right'. :param (int) box_id: the box id which is used as a reference for the insertion of the new box. Box ids are memoryless numbers that are generated on-the-fly and assigned to boxes in the layout each time .get_preview() is run. :param (float) fill_percent: specifies the percentage of the container box from the given 'side' that the new box occupies. For example if you apply the method\n .insert(box=new_box, box_id=2, side='left', fill_percent=20)\n to a dashboard object, a new box is inserted 20% from the left side of the box with id #2. Run .get_preview() to see the box ids assigned to each box in the dashboard layout. Default = 50 Example: ``` import plotly.dashboard_objs as dashboard box_a = { 'type': 'box', 'boxType': 'plot', 'fileId': 'username:some#', 'title': 'box a' } my_dboard = dashboard.Dashboard() my_dboard.insert(box_a) my_dboard.insert(box_a, 'left', 1) my_dboard.insert(box_a, 'below', 2) my_dboard.insert(box_a, 'right', 3) my_dboard.insert(box_a, 'above', 4, fill_percent=20) my_dboard.get_preview() ``` """ box_ids_to_path = self._compute_box_ids() # doesn't need box_id or side specified for first box if self["layout"] is None: self["layout"] = _container( box, _empty_box(), size=MASTER_HEIGHT, sizeUnit="px" ) else: if box_id is None: raise _plotly_utils.exceptions.PlotlyError( "Make sure the box_id is specfied if there is at least " "one box in your dashboard." ) if box_id not in box_ids_to_path: raise _plotly_utils.exceptions.PlotlyError(ID_NOT_VALID_MESSAGE) if fill_percent < 0 or fill_percent > 100: raise _plotly_utils.exceptions.PlotlyError( "fill_percent must be a number between 0 and 100 " "inclusive" ) if side == "above": old_box = self.get_box(box_id) self._insert( _container(box, old_box, direction="vertical", size=fill_percent), box_ids_to_path[box_id], ) elif side == "below": old_box = self.get_box(box_id) self._insert( _container( old_box, box, direction="vertical", size=100 - fill_percent ), box_ids_to_path[box_id], ) elif side == "left": old_box = self.get_box(box_id) self._insert( _container(box, old_box, direction="horizontal", size=fill_percent), box_ids_to_path[box_id], ) elif side == "right": old_box = self.get_box(box_id) self._insert( _container( old_box, box, direction="horizontal", size=100 - fill_percent ), box_ids_to_path[box_id], ) else: raise _plotly_utils.exceptions.PlotlyError( "If there is at least one box in your dashboard, you " "must specify a valid side value. You must choose from " "'above', 'below', 'left', and 'right'." ) self._set_dashboard_size()
[ "def", "insert", "(", "self", ",", "box", ",", "side", "=", "\"above\"", ",", "box_id", "=", "None", ",", "fill_percent", "=", "50", ")", ":", "box_ids_to_path", "=", "self", ".", "_compute_box_ids", "(", ")", "# doesn't need box_id or side specified for first box", "if", "self", "[", "\"layout\"", "]", "is", "None", ":", "self", "[", "\"layout\"", "]", "=", "_container", "(", "box", ",", "_empty_box", "(", ")", ",", "size", "=", "MASTER_HEIGHT", ",", "sizeUnit", "=", "\"px\"", ")", "else", ":", "if", "box_id", "is", "None", ":", "raise", "_plotly_utils", ".", "exceptions", ".", "PlotlyError", "(", "\"Make sure the box_id is specfied if there is at least \"", "\"one box in your dashboard.\"", ")", "if", "box_id", "not", "in", "box_ids_to_path", ":", "raise", "_plotly_utils", ".", "exceptions", ".", "PlotlyError", "(", "ID_NOT_VALID_MESSAGE", ")", "if", "fill_percent", "<", "0", "or", "fill_percent", ">", "100", ":", "raise", "_plotly_utils", ".", "exceptions", ".", "PlotlyError", "(", "\"fill_percent must be a number between 0 and 100 \"", "\"inclusive\"", ")", "if", "side", "==", "\"above\"", ":", "old_box", "=", "self", ".", "get_box", "(", "box_id", ")", "self", ".", "_insert", "(", "_container", "(", "box", ",", "old_box", ",", "direction", "=", "\"vertical\"", ",", "size", "=", "fill_percent", ")", ",", "box_ids_to_path", "[", "box_id", "]", ",", ")", "elif", "side", "==", "\"below\"", ":", "old_box", "=", "self", ".", "get_box", "(", "box_id", ")", "self", ".", "_insert", "(", "_container", "(", "old_box", ",", "box", ",", "direction", "=", "\"vertical\"", ",", "size", "=", "100", "-", "fill_percent", ")", ",", "box_ids_to_path", "[", "box_id", "]", ",", ")", "elif", "side", "==", "\"left\"", ":", "old_box", "=", "self", ".", "get_box", "(", "box_id", ")", "self", ".", "_insert", "(", "_container", "(", "box", ",", "old_box", ",", "direction", "=", "\"horizontal\"", ",", "size", "=", "fill_percent", ")", ",", "box_ids_to_path", "[", "box_id", "]", ",", ")", "elif", "side", "==", "\"right\"", ":", "old_box", "=", "self", ".", "get_box", "(", "box_id", ")", "self", ".", "_insert", "(", "_container", "(", "old_box", ",", "box", ",", "direction", "=", "\"horizontal\"", ",", "size", "=", "100", "-", "fill_percent", ")", ",", "box_ids_to_path", "[", "box_id", "]", ",", ")", "else", ":", "raise", "_plotly_utils", ".", "exceptions", ".", "PlotlyError", "(", "\"If there is at least one box in your dashboard, you \"", "\"must specify a valid side value. You must choose from \"", "\"'above', 'below', 'left', and 'right'.\"", ")", "self", ".", "_set_dashboard_size", "(", ")" ]
[ 468, 4 ]
[ 564, 34 ]
python
en
['en', 'error', 'th']
False
Dashboard.remove
(self, box_id)
Remove a box from the dashboard by its box_id. Example: ``` import plotly.dashboard_objs as dashboard box_a = { 'type': 'box', 'boxType': 'plot', 'fileId': 'username:some#', 'title': 'box a' } my_dboard = dashboard.Dashboard() my_dboard.insert(box_a) my_dboard.remove(1) my_dboard.get_preview() ```
Remove a box from the dashboard by its box_id.
def remove(self, box_id): """ Remove a box from the dashboard by its box_id. Example: ``` import plotly.dashboard_objs as dashboard box_a = { 'type': 'box', 'boxType': 'plot', 'fileId': 'username:some#', 'title': 'box a' } my_dboard = dashboard.Dashboard() my_dboard.insert(box_a) my_dboard.remove(1) my_dboard.get_preview() ``` """ box_ids_to_path = self._compute_box_ids() if box_id not in box_ids_to_path: raise _plotly_utils.exceptions.PlotlyError(ID_NOT_VALID_MESSAGE) path = box_ids_to_path[box_id] if path != ("first",): container_for_box_id = self._path_to_box(path[:-1]) if path[-1] == "first": adjacent_path = "second" elif path[-1] == "second": adjacent_path = "first" adjacent_box = container_for_box_id[adjacent_path] self._insert(adjacent_box, path[:-1]) else: self["layout"] = None self._set_dashboard_size()
[ "def", "remove", "(", "self", ",", "box_id", ")", ":", "box_ids_to_path", "=", "self", ".", "_compute_box_ids", "(", ")", "if", "box_id", "not", "in", "box_ids_to_path", ":", "raise", "_plotly_utils", ".", "exceptions", ".", "PlotlyError", "(", "ID_NOT_VALID_MESSAGE", ")", "path", "=", "box_ids_to_path", "[", "box_id", "]", "if", "path", "!=", "(", "\"first\"", ",", ")", ":", "container_for_box_id", "=", "self", ".", "_path_to_box", "(", "path", "[", ":", "-", "1", "]", ")", "if", "path", "[", "-", "1", "]", "==", "\"first\"", ":", "adjacent_path", "=", "\"second\"", "elif", "path", "[", "-", "1", "]", "==", "\"second\"", ":", "adjacent_path", "=", "\"first\"", "adjacent_box", "=", "container_for_box_id", "[", "adjacent_path", "]", "self", ".", "_insert", "(", "adjacent_box", ",", "path", "[", ":", "-", "1", "]", ")", "else", ":", "self", "[", "\"layout\"", "]", "=", "None", "self", ".", "_set_dashboard_size", "(", ")" ]
[ 566, 4 ]
[ 604, 34 ]
python
en
['en', 'error', 'th']
False
Dashboard.swap
(self, box_id_1, box_id_2)
Swap two boxes with their specified ids. Example: ``` import plotly.dashboard_objs as dashboard box_a = { 'type': 'box', 'boxType': 'plot', 'fileId': 'username:first#', 'title': 'box a' } box_b = { 'type': 'box', 'boxType': 'plot', 'fileId': 'username:second#', 'title': 'box b' } my_dboard = dashboard.Dashboard() my_dboard.insert(box_a) my_dboard.insert(box_b, 'above', 1) # check box at box id 1 box_at_1 = my_dboard.get_box(1) print(box_at_1) my_dboard.swap(1, 2) box_after_swap = my_dboard.get_box(1) print(box_after_swap) ```
Swap two boxes with their specified ids.
def swap(self, box_id_1, box_id_2): """ Swap two boxes with their specified ids. Example: ``` import plotly.dashboard_objs as dashboard box_a = { 'type': 'box', 'boxType': 'plot', 'fileId': 'username:first#', 'title': 'box a' } box_b = { 'type': 'box', 'boxType': 'plot', 'fileId': 'username:second#', 'title': 'box b' } my_dboard = dashboard.Dashboard() my_dboard.insert(box_a) my_dboard.insert(box_b, 'above', 1) # check box at box id 1 box_at_1 = my_dboard.get_box(1) print(box_at_1) my_dboard.swap(1, 2) box_after_swap = my_dboard.get_box(1) print(box_after_swap) ``` """ box_ids_to_path = self._compute_box_ids() box_a = self.get_box(box_id_1) box_b = self.get_box(box_id_2) box_a_path = box_ids_to_path[box_id_1] box_b_path = box_ids_to_path[box_id_2] for pairs in [(box_a_path, box_b), (box_b_path, box_a)]: loc_in_dashboard = self["layout"] for first_second in pairs[0][:-1]: loc_in_dashboard = loc_in_dashboard[first_second] loc_in_dashboard[pairs[0][-1]] = pairs[1]
[ "def", "swap", "(", "self", ",", "box_id_1", ",", "box_id_2", ")", ":", "box_ids_to_path", "=", "self", ".", "_compute_box_ids", "(", ")", "box_a", "=", "self", ".", "get_box", "(", "box_id_1", ")", "box_b", "=", "self", ".", "get_box", "(", "box_id_2", ")", "box_a_path", "=", "box_ids_to_path", "[", "box_id_1", "]", "box_b_path", "=", "box_ids_to_path", "[", "box_id_2", "]", "for", "pairs", "in", "[", "(", "box_a_path", ",", "box_b", ")", ",", "(", "box_b_path", ",", "box_a", ")", "]", ":", "loc_in_dashboard", "=", "self", "[", "\"layout\"", "]", "for", "first_second", "in", "pairs", "[", "0", "]", "[", ":", "-", "1", "]", ":", "loc_in_dashboard", "=", "loc_in_dashboard", "[", "first_second", "]", "loc_in_dashboard", "[", "pairs", "[", "0", "]", "[", "-", "1", "]", "]", "=", "pairs", "[", "1", "]" ]
[ 606, 4 ]
[ 653, 53 ]
python
en
['en', 'error', 'th']
False
Projection.x
(self)
The 'x' property is an instance of X that may be specified as: - An instance of :class:`plotly.graph_objs.scatter3d.projection.X` - A dict of string/value properties that will be passed to the X constructor Supported dict properties: opacity Sets the projection color. scale Sets the scale factor determining the size of the projection marker points. show Sets whether or not projections are shown along the x axis. Returns ------- plotly.graph_objs.scatter3d.projection.X
The 'x' property is an instance of X that may be specified as: - An instance of :class:`plotly.graph_objs.scatter3d.projection.X` - A dict of string/value properties that will be passed to the X constructor Supported dict properties: opacity Sets the projection color. scale Sets the scale factor determining the size of the projection marker points. show Sets whether or not projections are shown along the x axis.
def x(self): """ The 'x' property is an instance of X that may be specified as: - An instance of :class:`plotly.graph_objs.scatter3d.projection.X` - A dict of string/value properties that will be passed to the X constructor Supported dict properties: opacity Sets the projection color. scale Sets the scale factor determining the size of the projection marker points. show Sets whether or not projections are shown along the x axis. Returns ------- plotly.graph_objs.scatter3d.projection.X """ return self["x"]
[ "def", "x", "(", "self", ")", ":", "return", "self", "[", "\"x\"", "]" ]
[ 15, 4 ]
[ 38, 24 ]
python
en
['en', 'error', 'th']
False
Projection.y
(self)
The 'y' property is an instance of Y that may be specified as: - An instance of :class:`plotly.graph_objs.scatter3d.projection.Y` - A dict of string/value properties that will be passed to the Y constructor Supported dict properties: opacity Sets the projection color. scale Sets the scale factor determining the size of the projection marker points. show Sets whether or not projections are shown along the y axis. Returns ------- plotly.graph_objs.scatter3d.projection.Y
The 'y' property is an instance of Y that may be specified as: - An instance of :class:`plotly.graph_objs.scatter3d.projection.Y` - A dict of string/value properties that will be passed to the Y constructor Supported dict properties: opacity Sets the projection color. scale Sets the scale factor determining the size of the projection marker points. show Sets whether or not projections are shown along the y axis.
def y(self): """ The 'y' property is an instance of Y that may be specified as: - An instance of :class:`plotly.graph_objs.scatter3d.projection.Y` - A dict of string/value properties that will be passed to the Y constructor Supported dict properties: opacity Sets the projection color. scale Sets the scale factor determining the size of the projection marker points. show Sets whether or not projections are shown along the y axis. Returns ------- plotly.graph_objs.scatter3d.projection.Y """ return self["y"]
[ "def", "y", "(", "self", ")", ":", "return", "self", "[", "\"y\"", "]" ]
[ 47, 4 ]
[ 70, 24 ]
python
en
['en', 'error', 'th']
False
Projection.z
(self)
The 'z' property is an instance of Z that may be specified as: - An instance of :class:`plotly.graph_objs.scatter3d.projection.Z` - A dict of string/value properties that will be passed to the Z constructor Supported dict properties: opacity Sets the projection color. scale Sets the scale factor determining the size of the projection marker points. show Sets whether or not projections are shown along the z axis. Returns ------- plotly.graph_objs.scatter3d.projection.Z
The 'z' property is an instance of Z that may be specified as: - An instance of :class:`plotly.graph_objs.scatter3d.projection.Z` - A dict of string/value properties that will be passed to the Z constructor Supported dict properties: opacity Sets the projection color. scale Sets the scale factor determining the size of the projection marker points. show Sets whether or not projections are shown along the z axis.
def z(self): """ The 'z' property is an instance of Z that may be specified as: - An instance of :class:`plotly.graph_objs.scatter3d.projection.Z` - A dict of string/value properties that will be passed to the Z constructor Supported dict properties: opacity Sets the projection color. scale Sets the scale factor determining the size of the projection marker points. show Sets whether or not projections are shown along the z axis. Returns ------- plotly.graph_objs.scatter3d.projection.Z """ return self["z"]
[ "def", "z", "(", "self", ")", ":", "return", "self", "[", "\"z\"", "]" ]
[ 79, 4 ]
[ 102, 24 ]
python
en
['en', 'error', 'th']
False
Projection.__init__
(self, arg=None, x=None, y=None, z=None, **kwargs)
Construct a new Projection object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatter3d.Projection` x :class:`plotly.graph_objects.scatter3d.projection.X` instance or dict with compatible properties y :class:`plotly.graph_objects.scatter3d.projection.Y` instance or dict with compatible properties z :class:`plotly.graph_objects.scatter3d.projection.Z` instance or dict with compatible properties Returns ------- Projection
Construct a new Projection object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatter3d.Projection` x :class:`plotly.graph_objects.scatter3d.projection.X` instance or dict with compatible properties y :class:`plotly.graph_objects.scatter3d.projection.Y` instance or dict with compatible properties z :class:`plotly.graph_objects.scatter3d.projection.Z` instance or dict with compatible properties
def __init__(self, arg=None, x=None, y=None, z=None, **kwargs): """ Construct a new Projection object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatter3d.Projection` x :class:`plotly.graph_objects.scatter3d.projection.X` instance or dict with compatible properties y :class:`plotly.graph_objects.scatter3d.projection.Y` instance or dict with compatible properties z :class:`plotly.graph_objects.scatter3d.projection.Z` instance or dict with compatible properties Returns ------- Projection """ super(Projection, self).__init__("projection") 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.scatter3d.Projection constructor must be a dict or an instance of :class:`plotly.graph_objs.scatter3d.Projection`""" ) # 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("x", None) _v = x if x is not None else _v if _v is not None: self["x"] = _v _v = arg.pop("y", None) _v = y if y is not None else _v if _v is not None: self["y"] = _v _v = arg.pop("z", None) _v = z if z is not None else _v if _v is not None: self["z"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "x", "=", "None", ",", "y", "=", "None", ",", "z", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Projection", ",", "self", ")", ".", "__init__", "(", "\"projection\"", ")", "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.scatter3d.Projection \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.scatter3d.Projection`\"\"\"", ")", "# 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", "(", "\"x\"", ",", "None", ")", "_v", "=", "x", "if", "x", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"x\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"y\"", ",", "None", ")", "_v", "=", "y", "if", "y", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"y\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"z\"", ",", "None", ")", "_v", "=", "z", "if", "z", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"z\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 124, 4 ]
[ 196, 34 ]
python
en
['en', 'error', 'th']
False
doesCommitteeExist
(committee)
Args: committee: list of information about a committee. Returns: boolean which is true if and only if the committee is in the CSV file.
Args: committee: list of information about a committee.
def doesCommitteeExist(committee): """ Args: committee: list of information about a committee. Returns: boolean which is true if and only if the committee is in the CSV file. """ emailFile = CSVHandler(EMAIL_FILE_LOCATION) contents = emailFile.read() isInList = False print(committee) for x in contents: print(x) if(x[0] == committee[0]): isInList = True return isInList
[ "def", "doesCommitteeExist", "(", "committee", ")", ":", "emailFile", "=", "CSVHandler", "(", "EMAIL_FILE_LOCATION", ")", "contents", "=", "emailFile", ".", "read", "(", ")", "isInList", "=", "False", "print", "(", "committee", ")", "for", "x", "in", "contents", ":", "print", "(", "x", ")", "if", "(", "x", "[", "0", "]", "==", "committee", "[", "0", "]", ")", ":", "isInList", "=", "True", "return", "isInList" ]
[ 9, 0 ]
[ 26, 19 ]
python
en
['en', 'error', 'th']
False
SelfFeedingModel.encode_dia_y
(self, y_vecs)
Encodes a tensor of vectorized candidates. :param y_vecs: a [bs, seq_len] or [bs, num_cands, seq_len](?) of vectorized candidates
Encodes a tensor of vectorized candidates.
def encode_dia_y(self, y_vecs): """ Encodes a tensor of vectorized candidates. :param y_vecs: a [bs, seq_len] or [bs, num_cands, seq_len](?) of vectorized candidates """ if y_vecs.dim() == 2: y_enc = self.y_dia_head(self.y_dia_encoder(y_vecs)) elif y_vecs.dim() == 3: oldshape = y_vecs.shape y_vecs = y_vecs.reshape(oldshape[0] * oldshape[1], oldshape[2]) y_enc = self.y_dia_head(self.y_dia_encoder(y_vecs)) y_enc = y_enc.reshape(oldshape[0], oldshape[1], -1) return y_enc
[ "def", "encode_dia_y", "(", "self", ",", "y_vecs", ")", ":", "if", "y_vecs", ".", "dim", "(", ")", "==", "2", ":", "y_enc", "=", "self", ".", "y_dia_head", "(", "self", ".", "y_dia_encoder", "(", "y_vecs", ")", ")", "elif", "y_vecs", ".", "dim", "(", ")", "==", "3", ":", "oldshape", "=", "y_vecs", ".", "shape", "y_vecs", "=", "y_vecs", ".", "reshape", "(", "oldshape", "[", "0", "]", "*", "oldshape", "[", "1", "]", ",", "oldshape", "[", "2", "]", ")", "y_enc", "=", "self", ".", "y_dia_head", "(", "self", ".", "y_dia_encoder", "(", "y_vecs", ")", ")", "y_enc", "=", "y_enc", ".", "reshape", "(", "oldshape", "[", "0", "]", ",", "oldshape", "[", "1", "]", ",", "-", "1", ")", "return", "y_enc" ]
[ 131, 4 ]
[ 145, 20 ]
python
en
['en', 'error', 'th']
False
SelfFeedingModel.score_similarity
(self, context_h, cand_h)
Returns the dot product of encoded contexts and encoded candidates.
Returns the dot product of encoded contexts and encoded candidates.
def score_similarity(self, context_h, cand_h): """ Returns the dot product of encoded contexts and encoded candidates. """ if self.opt['normalize_sent_emb']: context_h /= context_h.norm(2, dim=1, keepdim=True) cand_h /= cand_h.norm(2, dim=1, keepdim=True) if cand_h.dim() == 2: scores = torch.matmul(context_h, cand_h.t()) elif cand_h.dim() == 3: scores = torch.bmm(context_h.unsqueeze(1), cand_h.transpose(1, 2)).squeeze( 1 ) else: raise RuntimeError( 'Unexpected candidate dimensions {}' ''.format(cand_h.dim()) ) return scores
[ "def", "score_similarity", "(", "self", ",", "context_h", ",", "cand_h", ")", ":", "if", "self", ".", "opt", "[", "'normalize_sent_emb'", "]", ":", "context_h", "/=", "context_h", ".", "norm", "(", "2", ",", "dim", "=", "1", ",", "keepdim", "=", "True", ")", "cand_h", "/=", "cand_h", ".", "norm", "(", "2", ",", "dim", "=", "1", ",", "keepdim", "=", "True", ")", "if", "cand_h", ".", "dim", "(", ")", "==", "2", ":", "scores", "=", "torch", ".", "matmul", "(", "context_h", ",", "cand_h", ".", "t", "(", ")", ")", "elif", "cand_h", ".", "dim", "(", ")", "==", "3", ":", "scores", "=", "torch", ".", "bmm", "(", "context_h", ".", "unsqueeze", "(", "1", ")", ",", "cand_h", ".", "transpose", "(", "1", ",", "2", ")", ")", ".", "squeeze", "(", "1", ")", "else", ":", "raise", "RuntimeError", "(", "'Unexpected candidate dimensions {}'", "''", ".", "format", "(", "cand_h", ".", "dim", "(", ")", ")", ")", "return", "scores" ]
[ 155, 4 ]
[ 174, 21 ]
python
en
['en', 'error', 'th']
False
test_n_minus_f_pool_processes_attrib
(looper, nodeSet, sdk_pool_handle, sdk_wallet_steward)
The pool N-f nodes should be able to process ATTRIB txn. https://jira.hyperledger.org/browse/INDY-245
The pool N-f nodes should be able to process ATTRIB txn. https://jira.hyperledger.org/browse/INDY-245
def test_n_minus_f_pool_processes_attrib(looper, nodeSet, sdk_pool_handle, sdk_wallet_steward): """ The pool N-f nodes should be able to process ATTRIB txn. https://jira.hyperledger.org/browse/INDY-245 """ make_pool_n_minus_f_nodes(looper, nodeSet) sdk_add_raw_attribute(looper, sdk_pool_handle, sdk_wallet_steward, 'foo', 'bar')
[ "def", "test_n_minus_f_pool_processes_attrib", "(", "looper", ",", "nodeSet", ",", "sdk_pool_handle", ",", "sdk_wallet_steward", ")", ":", "make_pool_n_minus_f_nodes", "(", "looper", ",", "nodeSet", ")", "sdk_add_raw_attribute", "(", "looper", ",", "sdk_pool_handle", ",", "sdk_wallet_steward", ",", "'foo'", ",", "'bar'", ")" ]
[ 4, 0 ]
[ 13, 84 ]
python
en
['en', 'error', 'th']
False
Font.color
(self)
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 Returns ------- str
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
def color(self): """ 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 Returns ------- str """ return self["color"]
[ "def", "color", "(", "self", ")", ":", "return", "self", "[", "\"color\"", "]" ]
[ 15, 4 ]
[ 63, 28 ]
python
en
['en', 'error', 'th']
False
Font.family
(self)
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". The 'family' property is a string and must be specified as: - A non-empty string Returns ------- str
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". The 'family' property is a string and must be specified as: - A non-empty string
def family(self): """ 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". The 'family' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["family"]
[ "def", "family", "(", "self", ")", ":", "return", "self", "[", "\"family\"", "]" ]
[ 72, 4 ]
[ 94, 29 ]
python
en
['en', 'error', 'th']
False
Font.size
(self)
The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] Returns ------- int|float
The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf]
def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] Returns ------- int|float """ return self["size"]
[ "def", "size", "(", "self", ")", ":", "return", "self", "[", "\"size\"", "]" ]
[ 103, 4 ]
[ 112, 27 ]
python
en
['en', 'error', 'th']
False
Font.__init__
(self, arg=None, color=None, family=None, size=None, **kwargs)
Construct a new Font object Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatterpolargl .marker.colorbar.title.Font` 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 ------- Font
Construct a new Font object Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute.
def __init__(self, arg=None, color=None, family=None, size=None, **kwargs): """ Construct a new Font object Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatterpolargl .marker.colorbar.title.Font` 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 ------- Font """ super(Font, self).__init__("font") 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.scatterpolargl.marker.colorbar.title.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.scatterpolargl.marker.colorbar.title.Font`""" ) # 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("color", None) _v = color if color is not None else _v if _v is not None: self["color"] = _v _v = arg.pop("family", None) _v = family if family is not None else _v if _v is not None: self["family"] = _v _v = arg.pop("size", None) _v = size if size is not None else _v if _v is not None: self["size"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "color", "=", "None", ",", "family", "=", "None", ",", "size", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Font", ",", "self", ")", ".", "__init__", "(", "\"font\"", ")", "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.scatterpolargl.marker.colorbar.title.Font \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.scatterpolargl.marker.colorbar.title.Font`\"\"\"", ")", "# 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", "(", "\"color\"", ",", "None", ")", "_v", "=", "color", "if", "color", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"color\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"family\"", ",", "None", ")", "_v", "=", "family", "if", "family", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"family\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"size\"", ",", "None", ")", "_v", "=", "size", "if", "size", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"size\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 143, 4 ]
[ 227, 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\"", "]" ]
[ 27, 4 ]
[ 44, 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\"", "]" ]
[ 53, 4 ]
[ 69, 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\"", "]" ]
[ 78, 4 ]
[ 92, 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\"", "]" ]
[ 101, 4 ]
[ 117, 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\"", "]" ]
[ 126, 4 ]
[ 140, 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 scatter3d.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 scatter3d.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 scatter3d.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\"", "]" ]
[ 149, 4 ]
[ 205, 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\"", "]" ]
[ 214, 4 ]
[ 232, 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\"", "]" ]
[ 241, 4 ]
[ 286, 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\"", "]" ]
[ 295, 4 ]
[ 306, 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\"", "]" ]
[ 315, 4 ]
[ 330, 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] Returns ------- int|float
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]
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] Returns ------- int|float """ return self["width"]
[ "def", "width", "(", "self", ")", ":", "return", "self", "[", "\"width\"", "]" ]
[ 339, 4 ]
[ 350, 28 ]
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, **kwargs )
Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatter3d.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. Returns ------- Line
Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatter3d.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.
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, **kwargs ): """ Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatter3d.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. 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.scatter3d.marker.Line constructor must be a dict or an instance of :class:`plotly.graph_objs.scatter3d.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 # 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", ",", "*", "*", "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.scatter3d.marker.Line \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.scatter3d.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", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 439, 4 ]
[ 625, 34 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.__init__
(self, context: InjectionContext)
Initialize a ConnectionManager. Args: context: The context for this connection manager
Initialize a ConnectionManager.
def __init__(self, context: InjectionContext): """ Initialize a ConnectionManager. Args: context: The context for this connection manager """ self._context = context self._logger = logging.getLogger(__name__)
[ "def", "__init__", "(", "self", ",", "context", ":", "InjectionContext", ")", ":", "self", ".", "_context", "=", "context", "self", ".", "_logger", "=", "logging", ".", "getLogger", "(", "__name__", ")" ]
[ 43, 4 ]
[ 51, 50 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.context
(self)
Accessor for the current injection context. Returns: The injection context for this connection manager
Accessor for the current injection context.
def context(self) -> InjectionContext: """ Accessor for the current injection context. Returns: The injection context for this connection manager """ return self._context
[ "def", "context", "(", "self", ")", "->", "InjectionContext", ":", "return", "self", ".", "_context" ]
[ 54, 4 ]
[ 62, 28 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.create_invitation
( self, my_label: str = None, my_endpoint: str = None, their_role: str = None, accept: str = None, public: bool = False, multi_use: bool = False, alias: str = None, )
Generate new connection invitation. This interaction represents an out-of-band communication channel. In the future and in practice, these sort of invitations will be received over any number of channels such as SMS, Email, QR Code, NFC, etc. Structure of an invite message: :: { "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/connections/1.0/invitation", "label": "Alice", "did": "did:sov:QmWbsNYhMrjHiqZDTUTEJs" } Or, in the case of a peer DID: :: { "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/connections/1.0/invitation", "label": "Alice", "did": "did:peer:oiSqsNYhMrjHiqZDTUthsw", "recipientKeys": ["8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K"], "serviceEndpoint": "https://example.com/endpoint" } Currently, only peer DID is supported. Args: my_label: label for this connection my_endpoint: endpoint where other party can reach me their_role: a role to assign the connection accept: set to 'auto' to auto-accept a corresponding connection request public: set to True to create an invitation from the public DID multi_use: set to True to create an invitation for multiple use alias: optional alias to apply to connection for later use Returns: A tuple of the new `ConnectionRecord` and `ConnectionInvitation` instances
Generate new connection invitation.
async def create_invitation( self, my_label: str = None, my_endpoint: str = None, their_role: str = None, accept: str = None, public: bool = False, multi_use: bool = False, alias: str = None, ) -> Tuple[ConnectionRecord, ConnectionInvitation]: """ Generate new connection invitation. This interaction represents an out-of-band communication channel. In the future and in practice, these sort of invitations will be received over any number of channels such as SMS, Email, QR Code, NFC, etc. Structure of an invite message: :: { "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/connections/1.0/invitation", "label": "Alice", "did": "did:sov:QmWbsNYhMrjHiqZDTUTEJs" } Or, in the case of a peer DID: :: { "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/connections/1.0/invitation", "label": "Alice", "did": "did:peer:oiSqsNYhMrjHiqZDTUthsw", "recipientKeys": ["8HH5gYEeNc3z7PYXmd54d4x6qAfCNrqQqEB3nS7Zfu7K"], "serviceEndpoint": "https://example.com/endpoint" } Currently, only peer DID is supported. Args: my_label: label for this connection my_endpoint: endpoint where other party can reach me their_role: a role to assign the connection accept: set to 'auto' to auto-accept a corresponding connection request public: set to True to create an invitation from the public DID multi_use: set to True to create an invitation for multiple use alias: optional alias to apply to connection for later use Returns: A tuple of the new `ConnectionRecord` and `ConnectionInvitation` instances """ if not my_label: my_label = self.context.settings.get("default_label") wallet: BaseWallet = await self.context.inject(BaseWallet) if public: if not self.context.settings.get("public_invites"): raise ConnectionManagerError("Public invitations are not enabled") public_did = await wallet.get_public_did() if not public_did: raise ConnectionManagerError( "Cannot create public invitation with no public DID" ) if multi_use: raise ConnectionManagerError( "Cannot use public and multi_use at the same time" ) # FIXME - allow ledger instance to format public DID with prefix? invitation = ConnectionInvitation( label=my_label, did=f"did:sov:{public_did.did}" ) return None, invitation invitation_mode = ConnectionRecord.INVITATION_MODE_ONCE if multi_use: invitation_mode = ConnectionRecord.INVITATION_MODE_MULTI if not my_endpoint: my_endpoint = self.context.settings.get("default_endpoint") if not accept and self.context.settings.get("debug.auto_accept_requests"): accept = ConnectionRecord.ACCEPT_AUTO # Create and store new invitation key connection_key = await wallet.create_signing_key() # Create connection record connection = ConnectionRecord( initiator=ConnectionRecord.INITIATOR_SELF, invitation_key=connection_key.verkey, their_role=their_role, state=ConnectionRecord.STATE_INVITATION, accept=accept, invitation_mode=invitation_mode, alias=alias, ) await connection.save(self.context, reason="Created new invitation") # Create connection invitation message # Note: Need to split this into two stages to support inbound routing of invites # Would want to reuse create_did_document and convert the result invitation = ConnectionInvitation( label=my_label, recipient_keys=[connection_key.verkey], endpoint=my_endpoint ) await connection.attach_invitation(self.context, invitation) return connection, invitation
[ "async", "def", "create_invitation", "(", "self", ",", "my_label", ":", "str", "=", "None", ",", "my_endpoint", ":", "str", "=", "None", ",", "their_role", ":", "str", "=", "None", ",", "accept", ":", "str", "=", "None", ",", "public", ":", "bool", "=", "False", ",", "multi_use", ":", "bool", "=", "False", ",", "alias", ":", "str", "=", "None", ",", ")", "->", "Tuple", "[", "ConnectionRecord", ",", "ConnectionInvitation", "]", ":", "if", "not", "my_label", ":", "my_label", "=", "self", ".", "context", ".", "settings", ".", "get", "(", "\"default_label\"", ")", "wallet", ":", "BaseWallet", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseWallet", ")", "if", "public", ":", "if", "not", "self", ".", "context", ".", "settings", ".", "get", "(", "\"public_invites\"", ")", ":", "raise", "ConnectionManagerError", "(", "\"Public invitations are not enabled\"", ")", "public_did", "=", "await", "wallet", ".", "get_public_did", "(", ")", "if", "not", "public_did", ":", "raise", "ConnectionManagerError", "(", "\"Cannot create public invitation with no public DID\"", ")", "if", "multi_use", ":", "raise", "ConnectionManagerError", "(", "\"Cannot use public and multi_use at the same time\"", ")", "# FIXME - allow ledger instance to format public DID with prefix?", "invitation", "=", "ConnectionInvitation", "(", "label", "=", "my_label", ",", "did", "=", "f\"did:sov:{public_did.did}\"", ")", "return", "None", ",", "invitation", "invitation_mode", "=", "ConnectionRecord", ".", "INVITATION_MODE_ONCE", "if", "multi_use", ":", "invitation_mode", "=", "ConnectionRecord", ".", "INVITATION_MODE_MULTI", "if", "not", "my_endpoint", ":", "my_endpoint", "=", "self", ".", "context", ".", "settings", ".", "get", "(", "\"default_endpoint\"", ")", "if", "not", "accept", "and", "self", ".", "context", ".", "settings", ".", "get", "(", "\"debug.auto_accept_requests\"", ")", ":", "accept", "=", "ConnectionRecord", ".", "ACCEPT_AUTO", "# Create and store new invitation key", "connection_key", "=", "await", "wallet", ".", "create_signing_key", "(", ")", "# Create connection record", "connection", "=", "ConnectionRecord", "(", "initiator", "=", "ConnectionRecord", ".", "INITIATOR_SELF", ",", "invitation_key", "=", "connection_key", ".", "verkey", ",", "their_role", "=", "their_role", ",", "state", "=", "ConnectionRecord", ".", "STATE_INVITATION", ",", "accept", "=", "accept", ",", "invitation_mode", "=", "invitation_mode", ",", "alias", "=", "alias", ",", ")", "await", "connection", ".", "save", "(", "self", ".", "context", ",", "reason", "=", "\"Created new invitation\"", ")", "# Create connection invitation message", "# Note: Need to split this into two stages to support inbound routing of invites", "# Would want to reuse create_did_document and convert the result", "invitation", "=", "ConnectionInvitation", "(", "label", "=", "my_label", ",", "recipient_keys", "=", "[", "connection_key", ".", "verkey", "]", ",", "endpoint", "=", "my_endpoint", ")", "await", "connection", ".", "attach_invitation", "(", "self", ".", "context", ",", "invitation", ")", "return", "connection", ",", "invitation" ]
[ 64, 4 ]
[ 178, 37 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.receive_invitation
( self, invitation: ConnectionInvitation, their_role: str = None, accept: str = None, alias: str = None, )
Create a new connection record to track a received invitation. Args: invitation: The `ConnectionInvitation` to store their_role: The role assigned to this connection accept: set to 'auto' to auto-accept the invitation alias: optional alias to set on the record Returns: The new `ConnectionRecord` instance
Create a new connection record to track a received invitation.
async def receive_invitation( self, invitation: ConnectionInvitation, their_role: str = None, accept: str = None, alias: str = None, ) -> ConnectionRecord: """ Create a new connection record to track a received invitation. Args: invitation: The `ConnectionInvitation` to store their_role: The role assigned to this connection accept: set to 'auto' to auto-accept the invitation alias: optional alias to set on the record Returns: The new `ConnectionRecord` instance """ if not invitation.did: if not invitation.recipient_keys: raise ConnectionManagerError("Invitation must contain recipient key(s)") if not invitation.endpoint: raise ConnectionManagerError("Invitation must contain an endpoint") if accept is None and self.context.settings.get("debug.auto_accept_invites"): accept = ConnectionRecord.ACCEPT_AUTO # Create connection record connection = ConnectionRecord( initiator=ConnectionRecord.INITIATOR_EXTERNAL, invitation_key=invitation.recipient_keys and invitation.recipient_keys[0], their_label=invitation.label, their_role=their_role, state=ConnectionRecord.STATE_INVITATION, accept=accept, alias=alias, ) await connection.save( self.context, reason="Created new connection record from invitation", log_params={"invitation": invitation, "role": their_role}, ) # Save the invitation for later processing await connection.attach_invitation(self.context, invitation) if connection.accept == connection.ACCEPT_AUTO: request = await self.create_request(connection) responder: BaseResponder = await self._context.inject( BaseResponder, required=False ) if responder: await responder.send(request, connection_id=connection.connection_id) # refetch connection for accurate state connection = await ConnectionRecord.retrieve_by_id( self._context, connection.connection_id ) else: self._logger.debug("Connection invitation will await acceptance") return connection
[ "async", "def", "receive_invitation", "(", "self", ",", "invitation", ":", "ConnectionInvitation", ",", "their_role", ":", "str", "=", "None", ",", "accept", ":", "str", "=", "None", ",", "alias", ":", "str", "=", "None", ",", ")", "->", "ConnectionRecord", ":", "if", "not", "invitation", ".", "did", ":", "if", "not", "invitation", ".", "recipient_keys", ":", "raise", "ConnectionManagerError", "(", "\"Invitation must contain recipient key(s)\"", ")", "if", "not", "invitation", ".", "endpoint", ":", "raise", "ConnectionManagerError", "(", "\"Invitation must contain an endpoint\"", ")", "if", "accept", "is", "None", "and", "self", ".", "context", ".", "settings", ".", "get", "(", "\"debug.auto_accept_invites\"", ")", ":", "accept", "=", "ConnectionRecord", ".", "ACCEPT_AUTO", "# Create connection record", "connection", "=", "ConnectionRecord", "(", "initiator", "=", "ConnectionRecord", ".", "INITIATOR_EXTERNAL", ",", "invitation_key", "=", "invitation", ".", "recipient_keys", "and", "invitation", ".", "recipient_keys", "[", "0", "]", ",", "their_label", "=", "invitation", ".", "label", ",", "their_role", "=", "their_role", ",", "state", "=", "ConnectionRecord", ".", "STATE_INVITATION", ",", "accept", "=", "accept", ",", "alias", "=", "alias", ",", ")", "await", "connection", ".", "save", "(", "self", ".", "context", ",", "reason", "=", "\"Created new connection record from invitation\"", ",", "log_params", "=", "{", "\"invitation\"", ":", "invitation", ",", "\"role\"", ":", "their_role", "}", ",", ")", "# Save the invitation for later processing", "await", "connection", ".", "attach_invitation", "(", "self", ".", "context", ",", "invitation", ")", "if", "connection", ".", "accept", "==", "connection", ".", "ACCEPT_AUTO", ":", "request", "=", "await", "self", ".", "create_request", "(", "connection", ")", "responder", ":", "BaseResponder", "=", "await", "self", ".", "_context", ".", "inject", "(", "BaseResponder", ",", "required", "=", "False", ")", "if", "responder", ":", "await", "responder", ".", "send", "(", "request", ",", "connection_id", "=", "connection", ".", "connection_id", ")", "# refetch connection for accurate state", "connection", "=", "await", "ConnectionRecord", ".", "retrieve_by_id", "(", "self", ".", "_context", ",", "connection", ".", "connection_id", ")", "else", ":", "self", ".", "_logger", ".", "debug", "(", "\"Connection invitation will await acceptance\"", ")", "return", "connection" ]
[ 180, 4 ]
[ 243, 25 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.create_request
( self, connection: ConnectionRecord, my_label: str = None, my_endpoint: str = None, )
Create a new connection request for a previously-received invitation. Args: connection: The `ConnectionRecord` representing the invitation to accept my_label: My label my_endpoint: My endpoint Returns: A new `ConnectionRequest` message to send to the other agent
Create a new connection request for a previously-received invitation.
async def create_request( self, connection: ConnectionRecord, my_label: str = None, my_endpoint: str = None, ) -> ConnectionRequest: """ Create a new connection request for a previously-received invitation. Args: connection: The `ConnectionRecord` representing the invitation to accept my_label: My label my_endpoint: My endpoint Returns: A new `ConnectionRequest` message to send to the other agent """ wallet: BaseWallet = await self.context.inject(BaseWallet) if connection.my_did: my_info = await wallet.get_local_did(connection.my_did) else: # Create new DID for connection my_info = await wallet.create_local_did() connection.my_did = my_info.did # Create connection request message if not my_endpoint: my_endpoints = [self.context.settings.get("default_endpoint")] my_endpoints.extend(self.context.settings.get("additional_endpoints")) did_doc = await self.create_did_document( my_info, connection.inbound_connection_id, my_endpoints ) if not my_label: my_label = self.context.settings.get("default_label") request = ConnectionRequest( label=my_label, connection=ConnectionDetail(did=connection.my_did, did_doc=did_doc), ) # Update connection state connection.request_id = request._id connection.state = ConnectionRecord.STATE_REQUEST await connection.save(self.context, reason="Created connection request") return request
[ "async", "def", "create_request", "(", "self", ",", "connection", ":", "ConnectionRecord", ",", "my_label", ":", "str", "=", "None", ",", "my_endpoint", ":", "str", "=", "None", ",", ")", "->", "ConnectionRequest", ":", "wallet", ":", "BaseWallet", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseWallet", ")", "if", "connection", ".", "my_did", ":", "my_info", "=", "await", "wallet", ".", "get_local_did", "(", "connection", ".", "my_did", ")", "else", ":", "# Create new DID for connection", "my_info", "=", "await", "wallet", ".", "create_local_did", "(", ")", "connection", ".", "my_did", "=", "my_info", ".", "did", "# Create connection request message", "if", "not", "my_endpoint", ":", "my_endpoints", "=", "[", "self", ".", "context", ".", "settings", ".", "get", "(", "\"default_endpoint\"", ")", "]", "my_endpoints", ".", "extend", "(", "self", ".", "context", ".", "settings", ".", "get", "(", "\"additional_endpoints\"", ")", ")", "did_doc", "=", "await", "self", ".", "create_did_document", "(", "my_info", ",", "connection", ".", "inbound_connection_id", ",", "my_endpoints", ")", "if", "not", "my_label", ":", "my_label", "=", "self", ".", "context", ".", "settings", ".", "get", "(", "\"default_label\"", ")", "request", "=", "ConnectionRequest", "(", "label", "=", "my_label", ",", "connection", "=", "ConnectionDetail", "(", "did", "=", "connection", ".", "my_did", ",", "did_doc", "=", "did_doc", ")", ",", ")", "# Update connection state", "connection", ".", "request_id", "=", "request", ".", "_id", "connection", ".", "state", "=", "ConnectionRecord", ".", "STATE_REQUEST", "await", "connection", ".", "save", "(", "self", ".", "context", ",", "reason", "=", "\"Created connection request\"", ")", "return", "request" ]
[ 245, 4 ]
[ 291, 22 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.receive_request
( self, request: ConnectionRequest, receipt: MessageReceipt )
Receive and store a connection request. Args: request: The `ConnectionRequest` to accept receipt: The message receipt Returns: The new or updated `ConnectionRecord` instance
Receive and store a connection request.
async def receive_request( self, request: ConnectionRequest, receipt: MessageReceipt ) -> ConnectionRecord: """ Receive and store a connection request. Args: request: The `ConnectionRequest` to accept receipt: The message receipt Returns: The new or updated `ConnectionRecord` instance """ ConnectionRecord.log_state( self.context, "Receiving connection request", {"request": request} ) connection = None connection_key = None # Determine what key will need to sign the response if receipt.recipient_did_public: wallet: BaseWallet = await self.context.inject(BaseWallet) my_info = await wallet.get_local_did(receipt.recipient_did) connection_key = my_info.verkey else: connection_key = receipt.recipient_verkey try: connection = await ConnectionRecord.retrieve_by_invitation_key( self.context, connection_key, ConnectionRecord.INITIATOR_SELF ) except StorageNotFoundError: raise ConnectionManagerError( "No invitation found for pairwise connection" ) invitation = None if connection: invitation = await connection.retrieve_invitation(self.context) connection_key = connection.invitation_key ConnectionRecord.log_state( self.context, "Found invitation", {"invitation": invitation} ) if connection.is_multiuse_invitation: wallet: BaseWallet = await self.context.inject(BaseWallet) my_info = await wallet.create_local_did() new_connection = ConnectionRecord( initiator=ConnectionRecord.INITIATOR_MULTIUSE, invitation_key=connection_key, my_did=my_info.did, state=ConnectionRecord.STATE_INVITATION, accept=connection.accept, their_role=connection.their_role, ) await new_connection.save( self.context, reason="Received connection request from multi-use invitation DID", ) connection = new_connection conn_did_doc = request.connection.did_doc if not conn_did_doc: raise ConnectionManagerError( "No DIDDoc provided; cannot connect to public DID" ) if request.connection.did != conn_did_doc.did: raise ConnectionManagerError( "Connection DID does not match DIDDoc id", error_code=ProblemReportReason.REQUEST_NOT_ACCEPTED, ) await self.store_did_document(conn_did_doc) if connection: connection.their_label = request.label connection.their_did = request.connection.did connection.state = ConnectionRecord.STATE_REQUEST await connection.save( self.context, reason="Received connection request from invitation" ) elif not self.context.settings.get("public_invites"): raise ConnectionManagerError("Public invitations are not enabled") else: my_info = await wallet.create_local_did() connection = ConnectionRecord( initiator=ConnectionRecord.INITIATOR_EXTERNAL, invitation_key=connection_key, my_did=my_info.did, their_did=request.connection.did, their_label=request.label, state=ConnectionRecord.STATE_REQUEST, ) if self.context.settings.get("debug.auto_accept_requests"): connection.accept = ConnectionRecord.ACCEPT_AUTO await connection.save( self.context, reason="Received connection request from public DID" ) # Attach the connection request so it can be found and responded to await connection.attach_request(self.context, request) if connection.accept == ConnectionRecord.ACCEPT_AUTO: response = await self.create_response(connection) responder: BaseResponder = await self._context.inject( BaseResponder, required=False ) if responder: await responder.send_reply( response, connection_id=connection.connection_id ) # refetch connection for accurate state connection = await ConnectionRecord.retrieve_by_id( self._context, connection.connection_id ) else: self._logger.debug("Connection request will await acceptance") return connection
[ "async", "def", "receive_request", "(", "self", ",", "request", ":", "ConnectionRequest", ",", "receipt", ":", "MessageReceipt", ")", "->", "ConnectionRecord", ":", "ConnectionRecord", ".", "log_state", "(", "self", ".", "context", ",", "\"Receiving connection request\"", ",", "{", "\"request\"", ":", "request", "}", ")", "connection", "=", "None", "connection_key", "=", "None", "# Determine what key will need to sign the response", "if", "receipt", ".", "recipient_did_public", ":", "wallet", ":", "BaseWallet", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseWallet", ")", "my_info", "=", "await", "wallet", ".", "get_local_did", "(", "receipt", ".", "recipient_did", ")", "connection_key", "=", "my_info", ".", "verkey", "else", ":", "connection_key", "=", "receipt", ".", "recipient_verkey", "try", ":", "connection", "=", "await", "ConnectionRecord", ".", "retrieve_by_invitation_key", "(", "self", ".", "context", ",", "connection_key", ",", "ConnectionRecord", ".", "INITIATOR_SELF", ")", "except", "StorageNotFoundError", ":", "raise", "ConnectionManagerError", "(", "\"No invitation found for pairwise connection\"", ")", "invitation", "=", "None", "if", "connection", ":", "invitation", "=", "await", "connection", ".", "retrieve_invitation", "(", "self", ".", "context", ")", "connection_key", "=", "connection", ".", "invitation_key", "ConnectionRecord", ".", "log_state", "(", "self", ".", "context", ",", "\"Found invitation\"", ",", "{", "\"invitation\"", ":", "invitation", "}", ")", "if", "connection", ".", "is_multiuse_invitation", ":", "wallet", ":", "BaseWallet", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseWallet", ")", "my_info", "=", "await", "wallet", ".", "create_local_did", "(", ")", "new_connection", "=", "ConnectionRecord", "(", "initiator", "=", "ConnectionRecord", ".", "INITIATOR_MULTIUSE", ",", "invitation_key", "=", "connection_key", ",", "my_did", "=", "my_info", ".", "did", ",", "state", "=", "ConnectionRecord", ".", "STATE_INVITATION", ",", "accept", "=", "connection", ".", "accept", ",", "their_role", "=", "connection", ".", "their_role", ",", ")", "await", "new_connection", ".", "save", "(", "self", ".", "context", ",", "reason", "=", "\"Received connection request from multi-use invitation DID\"", ",", ")", "connection", "=", "new_connection", "conn_did_doc", "=", "request", ".", "connection", ".", "did_doc", "if", "not", "conn_did_doc", ":", "raise", "ConnectionManagerError", "(", "\"No DIDDoc provided; cannot connect to public DID\"", ")", "if", "request", ".", "connection", ".", "did", "!=", "conn_did_doc", ".", "did", ":", "raise", "ConnectionManagerError", "(", "\"Connection DID does not match DIDDoc id\"", ",", "error_code", "=", "ProblemReportReason", ".", "REQUEST_NOT_ACCEPTED", ",", ")", "await", "self", ".", "store_did_document", "(", "conn_did_doc", ")", "if", "connection", ":", "connection", ".", "their_label", "=", "request", ".", "label", "connection", ".", "their_did", "=", "request", ".", "connection", ".", "did", "connection", ".", "state", "=", "ConnectionRecord", ".", "STATE_REQUEST", "await", "connection", ".", "save", "(", "self", ".", "context", ",", "reason", "=", "\"Received connection request from invitation\"", ")", "elif", "not", "self", ".", "context", ".", "settings", ".", "get", "(", "\"public_invites\"", ")", ":", "raise", "ConnectionManagerError", "(", "\"Public invitations are not enabled\"", ")", "else", ":", "my_info", "=", "await", "wallet", ".", "create_local_did", "(", ")", "connection", "=", "ConnectionRecord", "(", "initiator", "=", "ConnectionRecord", ".", "INITIATOR_EXTERNAL", ",", "invitation_key", "=", "connection_key", ",", "my_did", "=", "my_info", ".", "did", ",", "their_did", "=", "request", ".", "connection", ".", "did", ",", "their_label", "=", "request", ".", "label", ",", "state", "=", "ConnectionRecord", ".", "STATE_REQUEST", ",", ")", "if", "self", ".", "context", ".", "settings", ".", "get", "(", "\"debug.auto_accept_requests\"", ")", ":", "connection", ".", "accept", "=", "ConnectionRecord", ".", "ACCEPT_AUTO", "await", "connection", ".", "save", "(", "self", ".", "context", ",", "reason", "=", "\"Received connection request from public DID\"", ")", "# Attach the connection request so it can be found and responded to", "await", "connection", ".", "attach_request", "(", "self", ".", "context", ",", "request", ")", "if", "connection", ".", "accept", "==", "ConnectionRecord", ".", "ACCEPT_AUTO", ":", "response", "=", "await", "self", ".", "create_response", "(", "connection", ")", "responder", ":", "BaseResponder", "=", "await", "self", ".", "_context", ".", "inject", "(", "BaseResponder", ",", "required", "=", "False", ")", "if", "responder", ":", "await", "responder", ".", "send_reply", "(", "response", ",", "connection_id", "=", "connection", ".", "connection_id", ")", "# refetch connection for accurate state", "connection", "=", "await", "ConnectionRecord", ".", "retrieve_by_id", "(", "self", ".", "_context", ",", "connection", ".", "connection_id", ")", "else", ":", "self", ".", "_logger", ".", "debug", "(", "\"Connection request will await acceptance\"", ")", "return", "connection" ]
[ 293, 4 ]
[ 413, 25 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.create_response
( self, connection: ConnectionRecord, my_endpoint: str = None )
Create a connection response for a received connection request. Args: connection: The `ConnectionRecord` with a pending connection request my_endpoint: The endpoint I can be reached at Returns: A tuple of the updated `ConnectionRecord` new `ConnectionResponse` message
Create a connection response for a received connection request.
async def create_response( self, connection: ConnectionRecord, my_endpoint: str = None ) -> ConnectionResponse: """ Create a connection response for a received connection request. Args: connection: The `ConnectionRecord` with a pending connection request my_endpoint: The endpoint I can be reached at Returns: A tuple of the updated `ConnectionRecord` new `ConnectionResponse` message """ ConnectionRecord.log_state( self.context, "Creating connection response", {"connection_id": connection.connection_id}, ) if connection.state not in ( connection.STATE_REQUEST, connection.STATE_RESPONSE, ): raise ConnectionManagerError( "Connection is not in the request or response state" ) request = await connection.retrieve_request(self.context) wallet: BaseWallet = await self.context.inject(BaseWallet) if connection.my_did: my_info = await wallet.get_local_did(connection.my_did) else: my_info = await wallet.create_local_did() connection.my_did = my_info.did # Create connection response message if not my_endpoint: my_endpoints = [self.context.settings.get("default_endpoint")] my_endpoints.extend(self.context.settings.get("additional_endpoints")) did_doc = await self.create_did_document( my_info, connection.inbound_connection_id, my_endpoints ) response = ConnectionResponse( connection=ConnectionDetail(did=my_info.did, did_doc=did_doc) ) # Assign thread information response.assign_thread_from(request) # Sign connection field using the invitation key wallet: BaseWallet = await self.context.inject(BaseWallet) await response.sign_field("connection", connection.invitation_key, wallet) # Update connection state connection.state = ConnectionRecord.STATE_RESPONSE await connection.save( self.context, reason="Created connection response", log_params={"response": response}, ) return response
[ "async", "def", "create_response", "(", "self", ",", "connection", ":", "ConnectionRecord", ",", "my_endpoint", ":", "str", "=", "None", ")", "->", "ConnectionResponse", ":", "ConnectionRecord", ".", "log_state", "(", "self", ".", "context", ",", "\"Creating connection response\"", ",", "{", "\"connection_id\"", ":", "connection", ".", "connection_id", "}", ",", ")", "if", "connection", ".", "state", "not", "in", "(", "connection", ".", "STATE_REQUEST", ",", "connection", ".", "STATE_RESPONSE", ",", ")", ":", "raise", "ConnectionManagerError", "(", "\"Connection is not in the request or response state\"", ")", "request", "=", "await", "connection", ".", "retrieve_request", "(", "self", ".", "context", ")", "wallet", ":", "BaseWallet", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseWallet", ")", "if", "connection", ".", "my_did", ":", "my_info", "=", "await", "wallet", ".", "get_local_did", "(", "connection", ".", "my_did", ")", "else", ":", "my_info", "=", "await", "wallet", ".", "create_local_did", "(", ")", "connection", ".", "my_did", "=", "my_info", ".", "did", "# Create connection response message", "if", "not", "my_endpoint", ":", "my_endpoints", "=", "[", "self", ".", "context", ".", "settings", ".", "get", "(", "\"default_endpoint\"", ")", "]", "my_endpoints", ".", "extend", "(", "self", ".", "context", ".", "settings", ".", "get", "(", "\"additional_endpoints\"", ")", ")", "did_doc", "=", "await", "self", ".", "create_did_document", "(", "my_info", ",", "connection", ".", "inbound_connection_id", ",", "my_endpoints", ")", "response", "=", "ConnectionResponse", "(", "connection", "=", "ConnectionDetail", "(", "did", "=", "my_info", ".", "did", ",", "did_doc", "=", "did_doc", ")", ")", "# Assign thread information", "response", ".", "assign_thread_from", "(", "request", ")", "# Sign connection field using the invitation key", "wallet", ":", "BaseWallet", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseWallet", ")", "await", "response", ".", "sign_field", "(", "\"connection\"", ",", "connection", ".", "invitation_key", ",", "wallet", ")", "# Update connection state", "connection", ".", "state", "=", "ConnectionRecord", ".", "STATE_RESPONSE", "await", "connection", ".", "save", "(", "self", ".", "context", ",", "reason", "=", "\"Created connection response\"", ",", "log_params", "=", "{", "\"response\"", ":", "response", "}", ",", ")", "return", "response" ]
[ 415, 4 ]
[ 475, 23 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.accept_response
( self, response: ConnectionResponse, receipt: MessageReceipt )
Accept a connection response. Process a ConnectionResponse message by looking up the connection request and setting up the pairwise connection. Args: response: The `ConnectionResponse` to accept receipt: The message receipt Returns: The updated `ConnectionRecord` representing the connection Raises: ConnectionManagerError: If there is no DID associated with the connection response ConnectionManagerError: If the corresponding connection is not at the request or response stage
Accept a connection response.
async def accept_response( self, response: ConnectionResponse, receipt: MessageReceipt ) -> ConnectionRecord: """ Accept a connection response. Process a ConnectionResponse message by looking up the connection request and setting up the pairwise connection. Args: response: The `ConnectionResponse` to accept receipt: The message receipt Returns: The updated `ConnectionRecord` representing the connection Raises: ConnectionManagerError: If there is no DID associated with the connection response ConnectionManagerError: If the corresponding connection is not at the request or response stage """ connection = None if response._thread: # identify the request by the thread ID try: connection = await ConnectionRecord.retrieve_by_request_id( self.context, response._thread_id ) except StorageNotFoundError: pass if not connection and receipt.sender_did: # identify connection by the DID they used for us try: connection = await ConnectionRecord.retrieve_by_did( self.context, receipt.sender_did, receipt.recipient_did ) except StorageNotFoundError: pass if not connection: raise ConnectionManagerError( "No corresponding connection request found", error_code=ProblemReportReason.RESPONSE_NOT_ACCEPTED, ) if connection.state not in ( ConnectionRecord.STATE_REQUEST, ConnectionRecord.STATE_RESPONSE, ): raise ConnectionManagerError( f"Cannot accept connection response for connection" " in state: {connection.state}" ) their_did = response.connection.did conn_did_doc = response.connection.did_doc if not conn_did_doc: raise ConnectionManagerError( "No DIDDoc provided; cannot connect to public DID" ) if their_did != conn_did_doc.did: raise ConnectionManagerError("Connection DID does not match DIDDoc id") await self.store_did_document(conn_did_doc) connection.their_did = their_did connection.state = ConnectionRecord.STATE_RESPONSE await connection.save(self.context, reason="Accepted connection response") return connection
[ "async", "def", "accept_response", "(", "self", ",", "response", ":", "ConnectionResponse", ",", "receipt", ":", "MessageReceipt", ")", "->", "ConnectionRecord", ":", "connection", "=", "None", "if", "response", ".", "_thread", ":", "# identify the request by the thread ID", "try", ":", "connection", "=", "await", "ConnectionRecord", ".", "retrieve_by_request_id", "(", "self", ".", "context", ",", "response", ".", "_thread_id", ")", "except", "StorageNotFoundError", ":", "pass", "if", "not", "connection", "and", "receipt", ".", "sender_did", ":", "# identify connection by the DID they used for us", "try", ":", "connection", "=", "await", "ConnectionRecord", ".", "retrieve_by_did", "(", "self", ".", "context", ",", "receipt", ".", "sender_did", ",", "receipt", ".", "recipient_did", ")", "except", "StorageNotFoundError", ":", "pass", "if", "not", "connection", ":", "raise", "ConnectionManagerError", "(", "\"No corresponding connection request found\"", ",", "error_code", "=", "ProblemReportReason", ".", "RESPONSE_NOT_ACCEPTED", ",", ")", "if", "connection", ".", "state", "not", "in", "(", "ConnectionRecord", ".", "STATE_REQUEST", ",", "ConnectionRecord", ".", "STATE_RESPONSE", ",", ")", ":", "raise", "ConnectionManagerError", "(", "f\"Cannot accept connection response for connection\"", "\" in state: {connection.state}\"", ")", "their_did", "=", "response", ".", "connection", ".", "did", "conn_did_doc", "=", "response", ".", "connection", ".", "did_doc", "if", "not", "conn_did_doc", ":", "raise", "ConnectionManagerError", "(", "\"No DIDDoc provided; cannot connect to public DID\"", ")", "if", "their_did", "!=", "conn_did_doc", ".", "did", ":", "raise", "ConnectionManagerError", "(", "\"Connection DID does not match DIDDoc id\"", ")", "await", "self", ".", "store_did_document", "(", "conn_did_doc", ")", "connection", ".", "their_did", "=", "their_did", "connection", ".", "state", "=", "ConnectionRecord", ".", "STATE_RESPONSE", "await", "connection", ".", "save", "(", "self", ".", "context", ",", "reason", "=", "\"Accepted connection response\"", ")", "return", "connection" ]
[ 477, 4 ]
[ 550, 25 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.create_static_connection
( self, my_did: str = None, my_seed: str = None, their_did: str = None, their_seed: str = None, their_verkey: str = None, their_endpoint: str = None, their_role: str = None, alias: str = None, )
Register a new static connection (for use by the test suite). Args: my_did: override the DID used in the connection my_seed: provide a seed used to generate our DID and keys their_did: provide the DID used by the other party their_seed: provide a seed used to generate their DID and keys their_verkey: provide the verkey used by the other party their_endpoint: their URL endpoint for routing messages their_role: their role in this connection alias: an alias for this connection record Returns: The new `ConnectionRecord` instance
Register a new static connection (for use by the test suite).
async def create_static_connection( self, my_did: str = None, my_seed: str = None, their_did: str = None, their_seed: str = None, their_verkey: str = None, their_endpoint: str = None, their_role: str = None, alias: str = None, ) -> ConnectionRecord: """ Register a new static connection (for use by the test suite). Args: my_did: override the DID used in the connection my_seed: provide a seed used to generate our DID and keys their_did: provide the DID used by the other party their_seed: provide a seed used to generate their DID and keys their_verkey: provide the verkey used by the other party their_endpoint: their URL endpoint for routing messages their_role: their role in this connection alias: an alias for this connection record Returns: The new `ConnectionRecord` instance """ wallet: BaseWallet = await self.context.inject(BaseWallet) # seed and DID optional my_info = await wallet.create_local_did(my_seed, my_did) # must provide their DID and verkey if the seed is not known if (not their_did or not their_verkey) and not their_seed: raise ConnectionManagerError( "Either a verkey or seed must be provided for the other party" ) if not their_did: their_did = seed_to_did(their_seed) if not their_verkey: their_verkey_bin, _ = create_keypair(their_seed) their_verkey = bytes_to_b58(their_verkey_bin) their_info = DIDInfo(their_did, their_verkey, {}) # Create connection record connection = ConnectionRecord( initiator=ConnectionRecord.INITIATOR_SELF, invitation_mode=ConnectionRecord.INVITATION_MODE_STATIC, my_did=my_info.did, their_did=their_info.did, their_role=their_role, state=ConnectionRecord.STATE_ACTIVE, alias=alias, ) await connection.save(self.context, reason="Created new static connection") # Synthesize their DID doc did_doc = await self.create_did_document(their_info, None, [their_endpoint]) await self.store_did_document(did_doc) return connection
[ "async", "def", "create_static_connection", "(", "self", ",", "my_did", ":", "str", "=", "None", ",", "my_seed", ":", "str", "=", "None", ",", "their_did", ":", "str", "=", "None", ",", "their_seed", ":", "str", "=", "None", ",", "their_verkey", ":", "str", "=", "None", ",", "their_endpoint", ":", "str", "=", "None", ",", "their_role", ":", "str", "=", "None", ",", "alias", ":", "str", "=", "None", ",", ")", "->", "ConnectionRecord", ":", "wallet", ":", "BaseWallet", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseWallet", ")", "# seed and DID optional", "my_info", "=", "await", "wallet", ".", "create_local_did", "(", "my_seed", ",", "my_did", ")", "# must provide their DID and verkey if the seed is not known", "if", "(", "not", "their_did", "or", "not", "their_verkey", ")", "and", "not", "their_seed", ":", "raise", "ConnectionManagerError", "(", "\"Either a verkey or seed must be provided for the other party\"", ")", "if", "not", "their_did", ":", "their_did", "=", "seed_to_did", "(", "their_seed", ")", "if", "not", "their_verkey", ":", "their_verkey_bin", ",", "_", "=", "create_keypair", "(", "their_seed", ")", "their_verkey", "=", "bytes_to_b58", "(", "their_verkey_bin", ")", "their_info", "=", "DIDInfo", "(", "their_did", ",", "their_verkey", ",", "{", "}", ")", "# Create connection record", "connection", "=", "ConnectionRecord", "(", "initiator", "=", "ConnectionRecord", ".", "INITIATOR_SELF", ",", "invitation_mode", "=", "ConnectionRecord", ".", "INVITATION_MODE_STATIC", ",", "my_did", "=", "my_info", ".", "did", ",", "their_did", "=", "their_info", ".", "did", ",", "their_role", "=", "their_role", ",", "state", "=", "ConnectionRecord", ".", "STATE_ACTIVE", ",", "alias", "=", "alias", ",", ")", "await", "connection", ".", "save", "(", "self", ".", "context", ",", "reason", "=", "\"Created new static connection\"", ")", "# Synthesize their DID doc", "did_doc", "=", "await", "self", ".", "create_did_document", "(", "their_info", ",", "None", ",", "[", "their_endpoint", "]", ")", "await", "self", ".", "store_did_document", "(", "did_doc", ")", "return", "connection" ]
[ 552, 4 ]
[ 613, 25 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.find_connection
( self, their_did: str, my_did: str = None, my_verkey: str = None, auto_complete=False, )
Look up existing connection information for a sender verkey. Args: their_did: Their DID my_did: My DID my_verkey: My verkey auto_complete: Should this connection automatically be promoted to active Returns: The located `ConnectionRecord`, if any
Look up existing connection information for a sender verkey.
async def find_connection( self, their_did: str, my_did: str = None, my_verkey: str = None, auto_complete=False, ) -> ConnectionRecord: """ Look up existing connection information for a sender verkey. Args: their_did: Their DID my_did: My DID my_verkey: My verkey auto_complete: Should this connection automatically be promoted to active Returns: The located `ConnectionRecord`, if any """ # self._log_state( # "Finding connection", # {"their_did": their_did, "my_did": my_did, "my_verkey": my_verkey}, # ) connection = None if their_did: try: connection = await ConnectionRecord.retrieve_by_did( self.context, their_did, my_did ) except StorageNotFoundError: pass if ( connection and connection.state == ConnectionRecord.STATE_RESPONSE and auto_complete ): connection.state = ConnectionRecord.STATE_ACTIVE await connection.save(self.context, reason="Connection promoted to active") elif connection and connection.state == ConnectionRecord.STATE_INACTIVE: connection.state = ConnectionRecord.STATE_ACTIVE await connection.save(self.context, reason="Connection restored to active") if not connection and my_verkey: try: connection = await ConnectionRecord.retrieve_by_invitation_key( self.context, my_verkey, ConnectionRecord.INITIATOR_SELF ) except StorageError: pass return connection
[ "async", "def", "find_connection", "(", "self", ",", "their_did", ":", "str", ",", "my_did", ":", "str", "=", "None", ",", "my_verkey", ":", "str", "=", "None", ",", "auto_complete", "=", "False", ",", ")", "->", "ConnectionRecord", ":", "# self._log_state(", "# \"Finding connection\",", "# {\"their_did\": their_did, \"my_did\": my_did, \"my_verkey\": my_verkey},", "# )", "connection", "=", "None", "if", "their_did", ":", "try", ":", "connection", "=", "await", "ConnectionRecord", ".", "retrieve_by_did", "(", "self", ".", "context", ",", "their_did", ",", "my_did", ")", "except", "StorageNotFoundError", ":", "pass", "if", "(", "connection", "and", "connection", ".", "state", "==", "ConnectionRecord", ".", "STATE_RESPONSE", "and", "auto_complete", ")", ":", "connection", ".", "state", "=", "ConnectionRecord", ".", "STATE_ACTIVE", "await", "connection", ".", "save", "(", "self", ".", "context", ",", "reason", "=", "\"Connection promoted to active\"", ")", "elif", "connection", "and", "connection", ".", "state", "==", "ConnectionRecord", ".", "STATE_INACTIVE", ":", "connection", ".", "state", "=", "ConnectionRecord", ".", "STATE_ACTIVE", "await", "connection", ".", "save", "(", "self", ".", "context", ",", "reason", "=", "\"Connection restored to active\"", ")", "if", "not", "connection", "and", "my_verkey", ":", "try", ":", "connection", "=", "await", "ConnectionRecord", ".", "retrieve_by_invitation_key", "(", "self", ".", "context", ",", "my_verkey", ",", "ConnectionRecord", ".", "INITIATOR_SELF", ")", "except", "StorageError", ":", "pass", "return", "connection" ]
[ 615, 4 ]
[ 668, 25 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.find_inbound_connection
( self, receipt: MessageReceipt )
Deserialize an incoming message and further populate the request context. Args: receipt: The message receipt Returns: The `ConnectionRecord` associated with the expanded message, if any
Deserialize an incoming message and further populate the request context.
async def find_inbound_connection( self, receipt: MessageReceipt ) -> ConnectionRecord: """ Deserialize an incoming message and further populate the request context. Args: receipt: The message receipt Returns: The `ConnectionRecord` associated with the expanded message, if any """ cache_key = None connection = None resolved = False if receipt.sender_verkey and receipt.recipient_verkey: cache_key = ( f"connection_by_verkey::{receipt.sender_verkey}" f"::{receipt.recipient_verkey}" ) cache: BaseCache = await self.context.inject(BaseCache, required=False) if cache: async with cache.acquire(cache_key) as entry: if entry.result: cached = entry.result receipt.sender_did = cached["sender_did"] receipt.recipient_did_public = cached["recipient_did_public"] receipt.recipient_did = cached["recipient_did"] connection = await ConnectionRecord.retrieve_by_id( self.context, cached["id"] ) else: connection = await self.resolve_inbound_connection(receipt) if connection: cache_val = { "id": connection.connection_id, "sender_did": receipt.sender_did, "recipient_did": receipt.recipient_did, "recipient_did_public": receipt.recipient_did_public, } await entry.set_result(cache_val, 3600) resolved = True if not connection and not resolved: connection = await self.resolve_inbound_connection(receipt) return connection
[ "async", "def", "find_inbound_connection", "(", "self", ",", "receipt", ":", "MessageReceipt", ")", "->", "ConnectionRecord", ":", "cache_key", "=", "None", "connection", "=", "None", "resolved", "=", "False", "if", "receipt", ".", "sender_verkey", "and", "receipt", ".", "recipient_verkey", ":", "cache_key", "=", "(", "f\"connection_by_verkey::{receipt.sender_verkey}\"", "f\"::{receipt.recipient_verkey}\"", ")", "cache", ":", "BaseCache", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseCache", ",", "required", "=", "False", ")", "if", "cache", ":", "async", "with", "cache", ".", "acquire", "(", "cache_key", ")", "as", "entry", ":", "if", "entry", ".", "result", ":", "cached", "=", "entry", ".", "result", "receipt", ".", "sender_did", "=", "cached", "[", "\"sender_did\"", "]", "receipt", ".", "recipient_did_public", "=", "cached", "[", "\"recipient_did_public\"", "]", "receipt", ".", "recipient_did", "=", "cached", "[", "\"recipient_did\"", "]", "connection", "=", "await", "ConnectionRecord", ".", "retrieve_by_id", "(", "self", ".", "context", ",", "cached", "[", "\"id\"", "]", ")", "else", ":", "connection", "=", "await", "self", ".", "resolve_inbound_connection", "(", "receipt", ")", "if", "connection", ":", "cache_val", "=", "{", "\"id\"", ":", "connection", ".", "connection_id", ",", "\"sender_did\"", ":", "receipt", ".", "sender_did", ",", "\"recipient_did\"", ":", "receipt", ".", "recipient_did", ",", "\"recipient_did_public\"", ":", "receipt", ".", "recipient_did_public", ",", "}", "await", "entry", ".", "set_result", "(", "cache_val", ",", "3600", ")", "resolved", "=", "True", "if", "not", "connection", "and", "not", "resolved", ":", "connection", "=", "await", "self", ".", "resolve_inbound_connection", "(", "receipt", ")", "return", "connection" ]
[ 670, 4 ]
[ 718, 25 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.resolve_inbound_connection
( self, receipt: MessageReceipt )
Populate the receipt DID information and find the related `ConnectionRecord`. Args: receipt: The message receipt Returns: The `ConnectionRecord` associated with the expanded message, if any
Populate the receipt DID information and find the related `ConnectionRecord`.
async def resolve_inbound_connection( self, receipt: MessageReceipt ) -> ConnectionRecord: """ Populate the receipt DID information and find the related `ConnectionRecord`. Args: receipt: The message receipt Returns: The `ConnectionRecord` associated with the expanded message, if any """ if receipt.sender_verkey: try: receipt.sender_did = await self.find_did_for_key(receipt.sender_verkey) except StorageNotFoundError: self._logger.warning( "No corresponding DID found for sender verkey: %s", receipt.sender_verkey, ) if receipt.recipient_verkey: try: wallet: BaseWallet = await self.context.inject(BaseWallet) my_info = await wallet.get_local_did_for_verkey( receipt.recipient_verkey ) receipt.recipient_did = my_info.did if "public" in my_info.metadata and my_info.metadata["public"] is True: receipt.recipient_did_public = True except InjectorError: self._logger.warning( "Cannot resolve recipient verkey, no wallet defined by " "context: %s", receipt.recipient_verkey, ) except WalletNotFoundError: self._logger.warning( "No corresponding DID found for recipient verkey: %s", receipt.recipient_verkey, ) return await self.find_connection( receipt.sender_did, receipt.recipient_did, receipt.recipient_verkey, True, )
[ "async", "def", "resolve_inbound_connection", "(", "self", ",", "receipt", ":", "MessageReceipt", ")", "->", "ConnectionRecord", ":", "if", "receipt", ".", "sender_verkey", ":", "try", ":", "receipt", ".", "sender_did", "=", "await", "self", ".", "find_did_for_key", "(", "receipt", ".", "sender_verkey", ")", "except", "StorageNotFoundError", ":", "self", ".", "_logger", ".", "warning", "(", "\"No corresponding DID found for sender verkey: %s\"", ",", "receipt", ".", "sender_verkey", ",", ")", "if", "receipt", ".", "recipient_verkey", ":", "try", ":", "wallet", ":", "BaseWallet", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseWallet", ")", "my_info", "=", "await", "wallet", ".", "get_local_did_for_verkey", "(", "receipt", ".", "recipient_verkey", ")", "receipt", ".", "recipient_did", "=", "my_info", ".", "did", "if", "\"public\"", "in", "my_info", ".", "metadata", "and", "my_info", ".", "metadata", "[", "\"public\"", "]", "is", "True", ":", "receipt", ".", "recipient_did_public", "=", "True", "except", "InjectorError", ":", "self", ".", "_logger", ".", "warning", "(", "\"Cannot resolve recipient verkey, no wallet defined by \"", "\"context: %s\"", ",", "receipt", ".", "recipient_verkey", ",", ")", "except", "WalletNotFoundError", ":", "self", ".", "_logger", ".", "warning", "(", "\"No corresponding DID found for recipient verkey: %s\"", ",", "receipt", ".", "recipient_verkey", ",", ")", "return", "await", "self", ".", "find_connection", "(", "receipt", ".", "sender_did", ",", "receipt", ".", "recipient_did", ",", "receipt", ".", "recipient_verkey", ",", "True", ",", ")" ]
[ 720, 4 ]
[ 766, 9 ]
python
en
['en', 'error', 'th']
False
ConnectionManager.create_did_document
( self, did_info: DIDInfo, inbound_connection_id: str = None, svc_endpoints: Sequence[str] = [], )
Create our DID document for a given DID. Args: did_info: The DID information (DID and verkey) used in the connection inbound_connection_id: The ID of the inbound routing connection to use svc_endpoints: Custom endpoints for the DID Document Returns: The prepared `DIDDoc` instance
Create our DID document for a given DID.
async def create_did_document( self, did_info: DIDInfo, inbound_connection_id: str = None, svc_endpoints: Sequence[str] = [], ) -> DIDDoc: """Create our DID document for a given DID. Args: did_info: The DID information (DID and verkey) used in the connection inbound_connection_id: The ID of the inbound routing connection to use svc_endpoints: Custom endpoints for the DID Document Returns: The prepared `DIDDoc` instance """ did_doc = DIDDoc(did=did_info.did) did_controller = did_info.did did_key = did_info.verkey pk = PublicKey( did_info.did, "1", did_key, PublicKeyType.ED25519_SIG_2018, did_controller, True, ) did_doc.set(pk) router_id = inbound_connection_id routing_keys = [] router_idx = 1 while router_id: # look up routing connection information router = await ConnectionRecord.retrieve_by_id(self.context, router_id) if router.state != ConnectionRecord.STATE_ACTIVE: raise ConnectionManagerError( f"Router connection not active: {router_id}" ) routing_doc = await self.fetch_did_document(router.their_did) if not routing_doc.service: raise ConnectionManagerError( f"No services defined by routing DIDDoc: {router_id}" ) for service in routing_doc.service.values(): if not service.endpoint: raise ConnectionManagerError( "Routing DIDDoc service has no service endpoint" ) if not service.recip_keys: raise ConnectionManagerError( "Routing DIDDoc service has no recipient key(s)" ) rk = PublicKey( did_info.did, f"routing-{router_idx}", service.recip_keys[0].value, PublicKeyType.ED25519_SIG_2018, did_controller, True, ) routing_keys.append(rk) svc_endpoints = [service.endpoint] break router_id = router.inbound_connection_id for endpoint_index, svc_endpoint in enumerate(svc_endpoints): endpoint_ident = "indy" if endpoint_index == 0 else f'indy{endpoint_index}' service = Service( did_info.did, endpoint_ident, "IndyAgent", [pk], routing_keys, svc_endpoint ) did_doc.set(service) return did_doc
[ "async", "def", "create_did_document", "(", "self", ",", "did_info", ":", "DIDInfo", ",", "inbound_connection_id", ":", "str", "=", "None", ",", "svc_endpoints", ":", "Sequence", "[", "str", "]", "=", "[", "]", ",", ")", "->", "DIDDoc", ":", "did_doc", "=", "DIDDoc", "(", "did", "=", "did_info", ".", "did", ")", "did_controller", "=", "did_info", ".", "did", "did_key", "=", "did_info", ".", "verkey", "pk", "=", "PublicKey", "(", "did_info", ".", "did", ",", "\"1\"", ",", "did_key", ",", "PublicKeyType", ".", "ED25519_SIG_2018", ",", "did_controller", ",", "True", ",", ")", "did_doc", ".", "set", "(", "pk", ")", "router_id", "=", "inbound_connection_id", "routing_keys", "=", "[", "]", "router_idx", "=", "1", "while", "router_id", ":", "# look up routing connection information", "router", "=", "await", "ConnectionRecord", ".", "retrieve_by_id", "(", "self", ".", "context", ",", "router_id", ")", "if", "router", ".", "state", "!=", "ConnectionRecord", ".", "STATE_ACTIVE", ":", "raise", "ConnectionManagerError", "(", "f\"Router connection not active: {router_id}\"", ")", "routing_doc", "=", "await", "self", ".", "fetch_did_document", "(", "router", ".", "their_did", ")", "if", "not", "routing_doc", ".", "service", ":", "raise", "ConnectionManagerError", "(", "f\"No services defined by routing DIDDoc: {router_id}\"", ")", "for", "service", "in", "routing_doc", ".", "service", ".", "values", "(", ")", ":", "if", "not", "service", ".", "endpoint", ":", "raise", "ConnectionManagerError", "(", "\"Routing DIDDoc service has no service endpoint\"", ")", "if", "not", "service", ".", "recip_keys", ":", "raise", "ConnectionManagerError", "(", "\"Routing DIDDoc service has no recipient key(s)\"", ")", "rk", "=", "PublicKey", "(", "did_info", ".", "did", ",", "f\"routing-{router_idx}\"", ",", "service", ".", "recip_keys", "[", "0", "]", ".", "value", ",", "PublicKeyType", ".", "ED25519_SIG_2018", ",", "did_controller", ",", "True", ",", ")", "routing_keys", ".", "append", "(", "rk", ")", "svc_endpoints", "=", "[", "service", ".", "endpoint", "]", "break", "router_id", "=", "router", ".", "inbound_connection_id", "for", "endpoint_index", ",", "svc_endpoint", "in", "enumerate", "(", "svc_endpoints", ")", ":", "endpoint_ident", "=", "\"indy\"", "if", "endpoint_index", "==", "0", "else", "f'indy{endpoint_index}'", "service", "=", "Service", "(", "did_info", ".", "did", ",", "endpoint_ident", ",", "\"IndyAgent\"", ",", "[", "pk", "]", ",", "routing_keys", ",", "svc_endpoint", ")", "did_doc", ".", "set", "(", "service", ")", "return", "did_doc" ]
[ 768, 4 ]
[ 848, 22 ]
python
en
['en', 'en', 'en']
True
ConnectionManager.fetch_did_document
(self, did: str)
Retrieve a DID Document for a given DID. Args: did: The DID to search for
Retrieve a DID Document for a given DID.
async def fetch_did_document(self, did: str) -> DIDDoc: """Retrieve a DID Document for a given DID. Args: did: The DID to search for """ storage: BaseStorage = await self.context.inject(BaseStorage) record = await storage.search_records( self.RECORD_TYPE_DID_DOC, {"did": did} ).fetch_single() return DIDDoc.from_json(record.value)
[ "async", "def", "fetch_did_document", "(", "self", ",", "did", ":", "str", ")", "->", "DIDDoc", ":", "storage", ":", "BaseStorage", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseStorage", ")", "record", "=", "await", "storage", ".", "search_records", "(", "self", ".", "RECORD_TYPE_DID_DOC", ",", "{", "\"did\"", ":", "did", "}", ")", ".", "fetch_single", "(", ")", "return", "DIDDoc", ".", "from_json", "(", "record", ".", "value", ")" ]
[ 850, 4 ]
[ 860, 45 ]
python
en
['en', 'en', 'en']
True
ConnectionManager.store_did_document
(self, did_doc: DIDDoc)
Store a DID document. Args: did_doc: The `DIDDoc` instance to be persisted
Store a DID document.
async def store_did_document(self, did_doc: DIDDoc): """Store a DID document. Args: did_doc: The `DIDDoc` instance to be persisted """ assert did_doc.did storage: BaseStorage = await self.context.inject(BaseStorage) try: record = await self.fetch_did_document(did_doc.did) except StorageNotFoundError: record = StorageRecord( self.RECORD_TYPE_DID_DOC, did_doc.to_json(), {"did": did_doc.did} ) await storage.add_record(record) else: await storage.update_record_value(record, did_doc.value) await self.remove_keys_for_did(did_doc.did) for key in did_doc.pubkey.values(): if key.controller == did_doc.did: await self.add_key_for_did(did_doc.did, key.value)
[ "async", "def", "store_did_document", "(", "self", ",", "did_doc", ":", "DIDDoc", ")", ":", "assert", "did_doc", ".", "did", "storage", ":", "BaseStorage", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseStorage", ")", "try", ":", "record", "=", "await", "self", ".", "fetch_did_document", "(", "did_doc", ".", "did", ")", "except", "StorageNotFoundError", ":", "record", "=", "StorageRecord", "(", "self", ".", "RECORD_TYPE_DID_DOC", ",", "did_doc", ".", "to_json", "(", ")", ",", "{", "\"did\"", ":", "did_doc", ".", "did", "}", ")", "await", "storage", ".", "add_record", "(", "record", ")", "else", ":", "await", "storage", ".", "update_record_value", "(", "record", ",", "did_doc", ".", "value", ")", "await", "self", ".", "remove_keys_for_did", "(", "did_doc", ".", "did", ")", "for", "key", "in", "did_doc", ".", "pubkey", ".", "values", "(", ")", ":", "if", "key", ".", "controller", "==", "did_doc", ".", "did", ":", "await", "self", ".", "add_key_for_did", "(", "did_doc", ".", "did", ",", "key", ".", "value", ")" ]
[ 862, 4 ]
[ 882, 66 ]
python
en
['en', 'en', 'en']
True
ConnectionManager.add_key_for_did
(self, did: str, key: str)
Store a verkey for lookup against a DID. Args: did: The DID to associate with this key key: The verkey to be added
Store a verkey for lookup against a DID.
async def add_key_for_did(self, did: str, key: str): """Store a verkey for lookup against a DID. Args: did: The DID to associate with this key key: The verkey to be added """ record = StorageRecord(self.RECORD_TYPE_DID_KEY, key, {"did": did, "key": key}) storage: BaseStorage = await self.context.inject(BaseStorage) await storage.add_record(record)
[ "async", "def", "add_key_for_did", "(", "self", ",", "did", ":", "str", ",", "key", ":", "str", ")", ":", "record", "=", "StorageRecord", "(", "self", ".", "RECORD_TYPE_DID_KEY", ",", "key", ",", "{", "\"did\"", ":", "did", ",", "\"key\"", ":", "key", "}", ")", "storage", ":", "BaseStorage", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseStorage", ")", "await", "storage", ".", "add_record", "(", "record", ")" ]
[ 884, 4 ]
[ 893, 40 ]
python
en
['en', 'en', 'en']
True
ConnectionManager.find_did_for_key
(self, key: str)
Find the DID previously associated with a key. Args: key: The verkey to look up
Find the DID previously associated with a key.
async def find_did_for_key(self, key: str) -> str: """Find the DID previously associated with a key. Args: key: The verkey to look up """ storage: BaseStorage = await self.context.inject(BaseStorage) record = await storage.search_records( self.RECORD_TYPE_DID_KEY, {"key": key} ).fetch_single() return record.tags["did"]
[ "async", "def", "find_did_for_key", "(", "self", ",", "key", ":", "str", ")", "->", "str", ":", "storage", ":", "BaseStorage", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseStorage", ")", "record", "=", "await", "storage", ".", "search_records", "(", "self", ".", "RECORD_TYPE_DID_KEY", ",", "{", "\"key\"", ":", "key", "}", ")", ".", "fetch_single", "(", ")", "return", "record", ".", "tags", "[", "\"did\"", "]" ]
[ 895, 4 ]
[ 905, 33 ]
python
en
['en', 'en', 'en']
True
ConnectionManager.remove_keys_for_did
(self, did: str)
Remove all keys associated with a DID. Args: did: The DID to remove keys for
Remove all keys associated with a DID.
async def remove_keys_for_did(self, did: str): """Remove all keys associated with a DID. Args: did: The DID to remove keys for """ storage: BaseStorage = await self.context.inject(BaseStorage) keys = await storage.search_records( self.RECORD_TYPE_DID_KEY, {"did": did} ).fetch_all() for record in keys: await storage.delete_record(record)
[ "async", "def", "remove_keys_for_did", "(", "self", ",", "did", ":", "str", ")", ":", "storage", ":", "BaseStorage", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseStorage", ")", "keys", "=", "await", "storage", ".", "search_records", "(", "self", ".", "RECORD_TYPE_DID_KEY", ",", "{", "\"did\"", ":", "did", "}", ")", ".", "fetch_all", "(", ")", "for", "record", "in", "keys", ":", "await", "storage", ".", "delete_record", "(", "record", ")" ]
[ 907, 4 ]
[ 918, 47 ]
python
en
['en', 'en', 'en']
True
ConnectionManager.get_connection_targets
( self, *, connection_id: str = None, connection: ConnectionRecord = None )
Create a connection target from a `ConnectionRecord`. Args: connection_id: The connection ID to search for connection: The connection record itself, if already available
Create a connection target from a `ConnectionRecord`.
async def get_connection_targets( self, *, connection_id: str = None, connection: ConnectionRecord = None ): """Create a connection target from a `ConnectionRecord`. Args: connection_id: The connection ID to search for connection: The connection record itself, if already available """ if not connection_id: connection_id = connection.connection_id cache: BaseCache = await self.context.inject(BaseCache, required=False) cache_key = f"connection_target::{connection_id}" if cache: async with cache.acquire(cache_key) as entry: if entry.result: targets = [ ConnectionTarget.deserialize(row) for row in entry.result ] else: if not connection: connection = await ConnectionRecord.retrieve_by_id( self.context, connection_id ) targets = await self.fetch_connection_targets(connection) await entry.set_result([row.serialize() for row in targets], 3600) else: targets = await self.fetch_connection_targets(connection) return targets
[ "async", "def", "get_connection_targets", "(", "self", ",", "*", ",", "connection_id", ":", "str", "=", "None", ",", "connection", ":", "ConnectionRecord", "=", "None", ")", ":", "if", "not", "connection_id", ":", "connection_id", "=", "connection", ".", "connection_id", "cache", ":", "BaseCache", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseCache", ",", "required", "=", "False", ")", "cache_key", "=", "f\"connection_target::{connection_id}\"", "if", "cache", ":", "async", "with", "cache", ".", "acquire", "(", "cache_key", ")", "as", "entry", ":", "if", "entry", ".", "result", ":", "targets", "=", "[", "ConnectionTarget", ".", "deserialize", "(", "row", ")", "for", "row", "in", "entry", ".", "result", "]", "else", ":", "if", "not", "connection", ":", "connection", "=", "await", "ConnectionRecord", ".", "retrieve_by_id", "(", "self", ".", "context", ",", "connection_id", ")", "targets", "=", "await", "self", ".", "fetch_connection_targets", "(", "connection", ")", "await", "entry", ".", "set_result", "(", "[", "row", ".", "serialize", "(", ")", "for", "row", "in", "targets", "]", ",", "3600", ")", "else", ":", "targets", "=", "await", "self", ".", "fetch_connection_targets", "(", "connection", ")", "return", "targets" ]
[ 920, 4 ]
[ 948, 22 ]
python
en
['en', 'en', 'en']
True
ConnectionManager.fetch_connection_targets
( self, connection: ConnectionRecord )
Get a list of connection target from a `ConnectionRecord`. Args: connection: The connection record (with associated `DIDDoc`) used to generate the connection target
Get a list of connection target from a `ConnectionRecord`.
async def fetch_connection_targets( self, connection: ConnectionRecord ) -> Sequence[ConnectionTarget]: """Get a list of connection target from a `ConnectionRecord`. Args: connection: The connection record (with associated `DIDDoc`) used to generate the connection target """ if not connection.my_did: self._logger.debug("No local DID associated with connection") return None wallet: BaseWallet = await self.context.inject(BaseWallet) my_info = await wallet.get_local_did(connection.my_did) results = None if ( connection.state in (connection.STATE_INVITATION, connection.STATE_REQUEST) and connection.initiator == connection.INITIATOR_EXTERNAL ): invitation = await connection.retrieve_invitation(self.context) if invitation.did: # populate recipient keys and endpoint from the ledger ledger: BaseLedger = await self.context.inject( BaseLedger, required=False ) if not ledger: raise ConnectionManagerError( "Cannot resolve DID without ledger instance" ) async with ledger: endpoint = await ledger.get_endpoint_for_did(invitation.did) recipient_keys = [await ledger.get_key_for_did(invitation.did)] routing_keys = [] else: endpoint = invitation.endpoint recipient_keys = invitation.recipient_keys routing_keys = invitation.routing_keys results = [ ConnectionTarget( did=connection.their_did, endpoint=endpoint, label=invitation.label, recipient_keys=recipient_keys, routing_keys=routing_keys, sender_key=my_info.verkey, ) ] else: if not connection.their_did: self._logger.debug("No target DID associated with connection") return None doc = await self.fetch_did_document(connection.their_did) results = self.diddoc_connection_targets( doc, my_info.verkey, connection.their_label ) return results
[ "async", "def", "fetch_connection_targets", "(", "self", ",", "connection", ":", "ConnectionRecord", ")", "->", "Sequence", "[", "ConnectionTarget", "]", ":", "if", "not", "connection", ".", "my_did", ":", "self", ".", "_logger", ".", "debug", "(", "\"No local DID associated with connection\"", ")", "return", "None", "wallet", ":", "BaseWallet", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseWallet", ")", "my_info", "=", "await", "wallet", ".", "get_local_did", "(", "connection", ".", "my_did", ")", "results", "=", "None", "if", "(", "connection", ".", "state", "in", "(", "connection", ".", "STATE_INVITATION", ",", "connection", ".", "STATE_REQUEST", ")", "and", "connection", ".", "initiator", "==", "connection", ".", "INITIATOR_EXTERNAL", ")", ":", "invitation", "=", "await", "connection", ".", "retrieve_invitation", "(", "self", ".", "context", ")", "if", "invitation", ".", "did", ":", "# populate recipient keys and endpoint from the ledger", "ledger", ":", "BaseLedger", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseLedger", ",", "required", "=", "False", ")", "if", "not", "ledger", ":", "raise", "ConnectionManagerError", "(", "\"Cannot resolve DID without ledger instance\"", ")", "async", "with", "ledger", ":", "endpoint", "=", "await", "ledger", ".", "get_endpoint_for_did", "(", "invitation", ".", "did", ")", "recipient_keys", "=", "[", "await", "ledger", ".", "get_key_for_did", "(", "invitation", ".", "did", ")", "]", "routing_keys", "=", "[", "]", "else", ":", "endpoint", "=", "invitation", ".", "endpoint", "recipient_keys", "=", "invitation", ".", "recipient_keys", "routing_keys", "=", "invitation", ".", "routing_keys", "results", "=", "[", "ConnectionTarget", "(", "did", "=", "connection", ".", "their_did", ",", "endpoint", "=", "endpoint", ",", "label", "=", "invitation", ".", "label", ",", "recipient_keys", "=", "recipient_keys", ",", "routing_keys", "=", "routing_keys", ",", "sender_key", "=", "my_info", ".", "verkey", ",", ")", "]", "else", ":", "if", "not", "connection", ".", "their_did", ":", "self", ".", "_logger", ".", "debug", "(", "\"No target DID associated with connection\"", ")", "return", "None", "doc", "=", "await", "self", ".", "fetch_did_document", "(", "connection", ".", "their_did", ")", "results", "=", "self", ".", "diddoc_connection_targets", "(", "doc", ",", "my_info", ".", "verkey", ",", "connection", ".", "their_label", ")", "return", "results" ]
[ 950, 4 ]
[ 1011, 22 ]
python
en
['en', 'en', 'en']
True
ConnectionManager.diddoc_connection_targets
( self, doc: DIDDoc, sender_verkey: str, their_label: str = None )
Get a list of connection targets from a DID Document. Args: doc: The DID Document to create the target from sender_verkey: The verkey we are using their_label: The connection label they are using
Get a list of connection targets from a DID Document.
def diddoc_connection_targets( self, doc: DIDDoc, sender_verkey: str, their_label: str = None ) -> Sequence[ConnectionTarget]: """Get a list of connection targets from a DID Document. Args: doc: The DID Document to create the target from sender_verkey: The verkey we are using their_label: The connection label they are using """ if not doc: raise ConnectionManagerError("No DIDDoc provided for connection target") if not doc.did: raise ConnectionManagerError("DIDDoc has no DID") if not doc.service: raise ConnectionManagerError("No services defined by DIDDoc") targets = [] for service in doc.service.values(): if service.recip_keys: targets.append( ConnectionTarget( did=doc.did, endpoint=service.endpoint, label=their_label, recipient_keys=[ key.value for key in (service.recip_keys or ()) ], routing_keys=[ key.value for key in (service.routing_keys or ()) ], sender_key=sender_verkey, ) ) return targets
[ "def", "diddoc_connection_targets", "(", "self", ",", "doc", ":", "DIDDoc", ",", "sender_verkey", ":", "str", ",", "their_label", ":", "str", "=", "None", ")", "->", "Sequence", "[", "ConnectionTarget", "]", ":", "if", "not", "doc", ":", "raise", "ConnectionManagerError", "(", "\"No DIDDoc provided for connection target\"", ")", "if", "not", "doc", ".", "did", ":", "raise", "ConnectionManagerError", "(", "\"DIDDoc has no DID\"", ")", "if", "not", "doc", ".", "service", ":", "raise", "ConnectionManagerError", "(", "\"No services defined by DIDDoc\"", ")", "targets", "=", "[", "]", "for", "service", "in", "doc", ".", "service", ".", "values", "(", ")", ":", "if", "service", ".", "recip_keys", ":", "targets", ".", "append", "(", "ConnectionTarget", "(", "did", "=", "doc", ".", "did", ",", "endpoint", "=", "service", ".", "endpoint", ",", "label", "=", "their_label", ",", "recipient_keys", "=", "[", "key", ".", "value", "for", "key", "in", "(", "service", ".", "recip_keys", "or", "(", ")", ")", "]", ",", "routing_keys", "=", "[", "key", ".", "value", "for", "key", "in", "(", "service", ".", "routing_keys", "or", "(", ")", ")", "]", ",", "sender_key", "=", "sender_verkey", ",", ")", ")", "return", "targets" ]
[ 1013, 4 ]
[ 1048, 22 ]
python
en
['en', 'en', 'en']
True
ConnectionManager.establish_inbound
( self, connection: ConnectionRecord, inbound_connection_id: str, outbound_handler )
Assign the inbound routing connection for a connection record. Returns: the current routing state (request or done)
Assign the inbound routing connection for a connection record.
async def establish_inbound( self, connection: ConnectionRecord, inbound_connection_id: str, outbound_handler ) -> str: """Assign the inbound routing connection for a connection record. Returns: the current routing state (request or done) """ # The connection must have a verkey, but in the case of a received # invitation we might not have created one yet wallet: BaseWallet = await self.context.inject(BaseWallet) if connection.my_did: my_info = await wallet.get_local_did(connection.my_did) else: # Create new DID for connection my_info = await wallet.create_local_did() connection.my_did = my_info.did try: router = await ConnectionRecord.retrieve_by_id( self.context, inbound_connection_id ) except StorageNotFoundError: raise ConnectionManagerError( f"Routing connection not found: {inbound_connection_id}" ) if not router.is_ready: raise ConnectionManagerError( f"Routing connection is not ready: {inbound_connection_id}" ) connection.inbound_connection_id = inbound_connection_id route_mgr = RoutingManager(self.context) await route_mgr.send_create_route( inbound_connection_id, my_info.verkey, outbound_handler ) connection.routing_state = ConnectionRecord.ROUTING_STATE_REQUEST await connection.save(self.context) return connection.routing_state
[ "async", "def", "establish_inbound", "(", "self", ",", "connection", ":", "ConnectionRecord", ",", "inbound_connection_id", ":", "str", ",", "outbound_handler", ")", "->", "str", ":", "# The connection must have a verkey, but in the case of a received", "# invitation we might not have created one yet", "wallet", ":", "BaseWallet", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseWallet", ")", "if", "connection", ".", "my_did", ":", "my_info", "=", "await", "wallet", ".", "get_local_did", "(", "connection", ".", "my_did", ")", "else", ":", "# Create new DID for connection", "my_info", "=", "await", "wallet", ".", "create_local_did", "(", ")", "connection", ".", "my_did", "=", "my_info", ".", "did", "try", ":", "router", "=", "await", "ConnectionRecord", ".", "retrieve_by_id", "(", "self", ".", "context", ",", "inbound_connection_id", ")", "except", "StorageNotFoundError", ":", "raise", "ConnectionManagerError", "(", "f\"Routing connection not found: {inbound_connection_id}\"", ")", "if", "not", "router", ".", "is_ready", ":", "raise", "ConnectionManagerError", "(", "f\"Routing connection is not ready: {inbound_connection_id}\"", ")", "connection", ".", "inbound_connection_id", "=", "inbound_connection_id", "route_mgr", "=", "RoutingManager", "(", "self", ".", "context", ")", "await", "route_mgr", ".", "send_create_route", "(", "inbound_connection_id", ",", "my_info", ".", "verkey", ",", "outbound_handler", ")", "connection", ".", "routing_state", "=", "ConnectionRecord", ".", "ROUTING_STATE_REQUEST", "await", "connection", ".", "save", "(", "self", ".", "context", ")", "return", "connection", ".", "routing_state" ]
[ 1050, 4 ]
[ 1090, 39 ]
python
en
['en', 'en', 'en']
True
ConnectionManager.update_inbound
( self, inbound_connection_id: str, recip_verkey: str, routing_state: str )
Activate connections once a route has been established. Looks up pending connections associated with the inbound routing connection and marks the routing as complete.
Activate connections once a route has been established.
async def update_inbound( self, inbound_connection_id: str, recip_verkey: str, routing_state: str ): """Activate connections once a route has been established. Looks up pending connections associated with the inbound routing connection and marks the routing as complete. """ conns = await ConnectionRecord.query( self.context, {"inbound_connection_id": inbound_connection_id} ) wallet: BaseWallet = await self.context.inject(BaseWallet) for connection in conns: # check the recipient key if not connection.my_did: continue conn_info = await wallet.get_local_did(connection.my_did) if conn_info.verkey == recip_verkey: connection.routing_state = routing_state await connection.save(self.context)
[ "async", "def", "update_inbound", "(", "self", ",", "inbound_connection_id", ":", "str", ",", "recip_verkey", ":", "str", ",", "routing_state", ":", "str", ")", ":", "conns", "=", "await", "ConnectionRecord", ".", "query", "(", "self", ".", "context", ",", "{", "\"inbound_connection_id\"", ":", "inbound_connection_id", "}", ")", "wallet", ":", "BaseWallet", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseWallet", ")", "for", "connection", "in", "conns", ":", "# check the recipient key", "if", "not", "connection", ".", "my_did", ":", "continue", "conn_info", "=", "await", "wallet", ".", "get_local_did", "(", "connection", ".", "my_did", ")", "if", "conn_info", ".", "verkey", "==", "recip_verkey", ":", "connection", ".", "routing_state", "=", "routing_state", "await", "connection", ".", "save", "(", "self", ".", "context", ")" ]
[ 1092, 4 ]
[ 1112, 51 ]
python
en
['en', 'en', 'en']
True
_make_argparse_table
(class_)
Build the reStructuredText table containing the args and descriptions.
Build the reStructuredText table containing the args and descriptions.
def _make_argparse_table(class_): """ Build the reStructuredText table containing the args and descriptions. """ readme = [] parser = ParlaiParser(False, False) class_.add_cmdline_args(parser, partial_opt=None) # group by whatever ArgumentGroups there are for ag in parser._action_groups: actions = [] # get options defined within only this group for action in ag._group_actions: if hasattr(action, 'hidden') and action.hidden: # some options are marked hidden continue if action.dest == argparse.SUPPRESS or action.dest == 'help': continue action_strings = ", ".join(f'`{a}`' for a in action.option_strings) description = [] if action.help: h = action.help if not h[0].isupper(): h = h[0].upper() + h[1:] h = h.replace("%(default)s", str(action.default)) description += [h] # list choices if there are any if action.choices: description += [ "Choices: " + ", ".join(f'`{c}`' for c in action.choices) + "." ] # list default and recommended values. default_value = "" if action.default is not None and action.default is not argparse.SUPPRESS: default_value += f"Default: ``{action.default}``. " if hasattr(action, 'recommended') and action.recommended: default_value += f"Recommended: ``{action.recommended}``. " # special escape for a few args which use a literal newline as their default if default_value: default_value = default_value.replace("\n", "\\n") description.append(default_value) description = "\n".join(description) # escape for the fact that we're inserting this inside a table description = description.replace("\n", "\n \n ") actions.append((action_strings, description)) if not actions: continue readme.append(f'__{ag.title}__\n\n') readme.append("| Argument | Description |\n") readme.append("|----------|----------|\n") for row in actions: text = "| " + " | ".join(row) + " |" text = text.replace("\n", "<br>") readme.append(f"{text}\n") readme.append("\n\n") return readme
[ "def", "_make_argparse_table", "(", "class_", ")", ":", "readme", "=", "[", "]", "parser", "=", "ParlaiParser", "(", "False", ",", "False", ")", "class_", ".", "add_cmdline_args", "(", "parser", ",", "partial_opt", "=", "None", ")", "# group by whatever ArgumentGroups there are", "for", "ag", "in", "parser", ".", "_action_groups", ":", "actions", "=", "[", "]", "# get options defined within only this group", "for", "action", "in", "ag", ".", "_group_actions", ":", "if", "hasattr", "(", "action", ",", "'hidden'", ")", "and", "action", ".", "hidden", ":", "# some options are marked hidden", "continue", "if", "action", ".", "dest", "==", "argparse", ".", "SUPPRESS", "or", "action", ".", "dest", "==", "'help'", ":", "continue", "action_strings", "=", "\", \"", ".", "join", "(", "f'`{a}`'", "for", "a", "in", "action", ".", "option_strings", ")", "description", "=", "[", "]", "if", "action", ".", "help", ":", "h", "=", "action", ".", "help", "if", "not", "h", "[", "0", "]", ".", "isupper", "(", ")", ":", "h", "=", "h", "[", "0", "]", ".", "upper", "(", ")", "+", "h", "[", "1", ":", "]", "h", "=", "h", ".", "replace", "(", "\"%(default)s\"", ",", "str", "(", "action", ".", "default", ")", ")", "description", "+=", "[", "h", "]", "# list choices if there are any", "if", "action", ".", "choices", ":", "description", "+=", "[", "\"Choices: \"", "+", "\", \"", ".", "join", "(", "f'`{c}`'", "for", "c", "in", "action", ".", "choices", ")", "+", "\".\"", "]", "# list default and recommended values.", "default_value", "=", "\"\"", "if", "action", ".", "default", "is", "not", "None", "and", "action", ".", "default", "is", "not", "argparse", ".", "SUPPRESS", ":", "default_value", "+=", "f\"Default: ``{action.default}``. \"", "if", "hasattr", "(", "action", ",", "'recommended'", ")", "and", "action", ".", "recommended", ":", "default_value", "+=", "f\"Recommended: ``{action.recommended}``. \"", "# special escape for a few args which use a literal newline as their default", "if", "default_value", ":", "default_value", "=", "default_value", ".", "replace", "(", "\"\\n\"", ",", "\"\\\\n\"", ")", "description", ".", "append", "(", "default_value", ")", "description", "=", "\"\\n\"", ".", "join", "(", "description", ")", "# escape for the fact that we're inserting this inside a table", "description", "=", "description", ".", "replace", "(", "\"\\n\"", ",", "\"\\n \\n \"", ")", "actions", ".", "append", "(", "(", "action_strings", ",", "description", ")", ")", "if", "not", "actions", ":", "continue", "readme", ".", "append", "(", "f'__{ag.title}__\\n\\n'", ")", "readme", ".", "append", "(", "\"| Argument | Description |\\n\"", ")", "readme", ".", "append", "(", "\"|----------|----------|\\n\"", ")", "for", "row", "in", "actions", ":", "text", "=", "\"| \"", "+", "\" | \"", ".", "join", "(", "row", ")", "+", "\" |\"", "text", "=", "text", ".", "replace", "(", "\"\\n\"", ",", "\"<br>\"", ")", "readme", ".", "append", "(", "f\"{text}\\n\"", ")", "readme", ".", "append", "(", "\"\\n\\n\"", ")", "return", "readme" ]
[ 21, 0 ]
[ 79, 17 ]
python
en
['en', 'error', 'th']
False
prepare_agent_readme
(agent)
Load agent readme, add title if necessary. :param agent: string indicating agent module :return: agent's readme
Load agent readme, add title if necessary.
def prepare_agent_readme(agent): """ Load agent readme, add title if necessary. :param agent: string indicating agent module :return: agent's readme """ readme_path = f'{os.path.join(parlai.agents.__path__[0], agent)}/README.md' if not os.path.exists(readme_path): raise RuntimeError(f'Agent {agent} must have README.md') with open(readme_path) as f: readme = f.readlines() if '# ' not in readme[0]: readme[0] = f'# {agent}' # try to import all of the agents and look for their classes root = os.path.join(parlai.agents.__path__[0], agent) submodules = pkgutil.iter_modules([root]) for sm in submodules: # look in the main folder if not (sm.name == agent or sm.name == 'agents'): continue module_name = f'parlai.agents.{agent}.{sm.name}' module = importlib.import_module(module_name) for itemname in dir(module): # skip all private items if itemname.startswith('_'): continue item = getattr(module, itemname) # avoid catching TorchAgent/TorchRankerAgent/... if ( inspect.isclass(item) and issubclass(item, parlai.core.agents.Agent) and hasattr(item, 'add_cmdline_args') and not inspect.isabstract(item) ): # gather all the options options = _make_argparse_table(item) if options: # if there were no options, don't mention it readme.append(f"## {itemname} Options\n\n") readme += options return readme
[ "def", "prepare_agent_readme", "(", "agent", ")", ":", "readme_path", "=", "f'{os.path.join(parlai.agents.__path__[0], agent)}/README.md'", "if", "not", "os", ".", "path", ".", "exists", "(", "readme_path", ")", ":", "raise", "RuntimeError", "(", "f'Agent {agent} must have README.md'", ")", "with", "open", "(", "readme_path", ")", "as", "f", ":", "readme", "=", "f", ".", "readlines", "(", ")", "if", "'# '", "not", "in", "readme", "[", "0", "]", ":", "readme", "[", "0", "]", "=", "f'# {agent}'", "# try to import all of the agents and look for their classes", "root", "=", "os", ".", "path", ".", "join", "(", "parlai", ".", "agents", ".", "__path__", "[", "0", "]", ",", "agent", ")", "submodules", "=", "pkgutil", ".", "iter_modules", "(", "[", "root", "]", ")", "for", "sm", "in", "submodules", ":", "# look in the main folder", "if", "not", "(", "sm", ".", "name", "==", "agent", "or", "sm", ".", "name", "==", "'agents'", ")", ":", "continue", "module_name", "=", "f'parlai.agents.{agent}.{sm.name}'", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "for", "itemname", "in", "dir", "(", "module", ")", ":", "# skip all private items", "if", "itemname", ".", "startswith", "(", "'_'", ")", ":", "continue", "item", "=", "getattr", "(", "module", ",", "itemname", ")", "# avoid catching TorchAgent/TorchRankerAgent/...", "if", "(", "inspect", ".", "isclass", "(", "item", ")", "and", "issubclass", "(", "item", ",", "parlai", ".", "core", ".", "agents", ".", "Agent", ")", "and", "hasattr", "(", "item", ",", "'add_cmdline_args'", ")", "and", "not", "inspect", ".", "isabstract", "(", "item", ")", ")", ":", "# gather all the options", "options", "=", "_make_argparse_table", "(", "item", ")", "if", "options", ":", "# if there were no options, don't mention it", "readme", ".", "append", "(", "f\"## {itemname} Options\\n\\n\"", ")", "readme", "+=", "options", "return", "readme" ]
[ 82, 0 ]
[ 129, 17 ]
python
en
['en', 'error', 'th']
False
write_all_agents
()
Write list of agents to fout. :param fout: file object to write to
Write list of agents to fout.
def write_all_agents(): """ Write list of agents to fout. :param fout: file object to write to """ os.makedirs('agent_refs', exist_ok=True) agents = [name for _, name, _ in pkgutil.iter_modules(parlai.agents.__path__)] for agent in agents: with open(f'agent_refs/{agent}.md', 'w') as fout: fout.write(''.join(prepare_agent_readme(agent)))
[ "def", "write_all_agents", "(", ")", ":", "os", ".", "makedirs", "(", "'agent_refs'", ",", "exist_ok", "=", "True", ")", "agents", "=", "[", "name", "for", "_", ",", "name", ",", "_", "in", "pkgutil", ".", "iter_modules", "(", "parlai", ".", "agents", ".", "__path__", ")", "]", "for", "agent", "in", "agents", ":", "with", "open", "(", "f'agent_refs/{agent}.md'", ",", "'w'", ")", "as", "fout", ":", "fout", ".", "write", "(", "''", ".", "join", "(", "prepare_agent_readme", "(", "agent", ")", ")", ")" ]
[ 132, 0 ]
[ 143, 60 ]
python
en
['en', 'error', 'th']
False
roles
(request)
Combination of all roles. Example: - roles=[A, B, C] ==> [(A), (B), (C), (A, B), (A, C), (B, C), (A, B, C)]
Combination of all roles.
def roles(request): ''' Combination of all roles. Example: - roles=[A, B, C] ==> [(A), (B), (C), (A, B), (A, C), (B, C), (A, B, C)] ''' return request.param
[ "def", "roles", "(", "request", ")", ":", "return", "request", ".", "param" ]
[ 46, 0 ]
[ 54, 24 ]
python
en
['en', 'error', 'th']
False
signatures
(request, roles)
Combinations of all signature types and signature count. Example: - roles=[A, B] - sig_count=1..3 =>[(), (A: 1), (B:1), (A: 2), (B: 2), (A: 3), (B: 3), (A:1, B: 1), (A:2, B: 1), (A:1, B: 2), (A:2, B: 2), (A:1, B: 3), (A:3, B: 1), (A:3, B: 3), (A:2, B: 3), (A:3, B: 2)]
Combinations of all signature types and signature count.
def signatures(request, roles): ''' Combinations of all signature types and signature count. Example: - roles=[A, B] - sig_count=1..3 =>[(), (A: 1), (B:1), (A: 2), (B: 2), (A: 3), (B: 3), (A:1, B: 1), (A:2, B: 1), (A:1, B: 2), (A:2, B: 2), (A:1, B: 3), (A:3, B: 1), (A:3, B: 3), (A:2, B: 3), (A:3, B: 2)] ''' max_sig_count = getValueFromModule(request, "MAX_SIG_COUNT", 3) all_sigs_count = list(range(1, max_sig_count)) return [ {role: sig_count for role, sig_count in zip(roles, sigs_count)} for sigs_count in product(all_sigs_count, repeat=len(roles)) ]
[ "def", "signatures", "(", "request", ",", "roles", ")", ":", "max_sig_count", "=", "getValueFromModule", "(", "request", ",", "\"MAX_SIG_COUNT\"", ",", "3", ")", "all_sigs_count", "=", "list", "(", "range", "(", "1", ",", "max_sig_count", ")", ")", "return", "[", "{", "role", ":", "sig_count", "for", "role", ",", "sig_count", "in", "zip", "(", "roles", ",", "sigs_count", ")", "}", "for", "sigs_count", "in", "product", "(", "all_sigs_count", ",", "repeat", "=", "len", "(", "roles", ")", ")", "]" ]
[ 58, 0 ]
[ 76, 5 ]
python
en
['en', 'error', 'th']
False
GetGTestRootDir
(gmock_root)
Returns the root directory of Google Test.
Returns the root directory of Google Test.
def GetGTestRootDir(gmock_root): """Returns the root directory of Google Test.""" return os.path.join(gmock_root, '../googletest')
[ "def", "GetGTestRootDir", "(", "gmock_root", ")", ":", "return", "os", ".", "path", ".", "join", "(", "gmock_root", ",", "'../googletest'", ")" ]
[ 90, 0 ]
[ 93, 50 ]
python
en
['en', 'en', 'en']
True
ValidateGMockRootDir
(gmock_root)
Makes sure gmock_root points to a valid gmock root directory. The function aborts the program on failure.
Makes sure gmock_root points to a valid gmock root directory.
def ValidateGMockRootDir(gmock_root): """Makes sure gmock_root points to a valid gmock root directory. The function aborts the program on failure. """ gtest.ValidateGTestRootDir(GetGTestRootDir(gmock_root)) gtest.VerifyFileExists(gmock_root, GMOCK_H_SEED) gtest.VerifyFileExists(gmock_root, GMOCK_ALL_CC_SEED)
[ "def", "ValidateGMockRootDir", "(", "gmock_root", ")", ":", "gtest", ".", "ValidateGTestRootDir", "(", "GetGTestRootDir", "(", "gmock_root", ")", ")", "gtest", ".", "VerifyFileExists", "(", "gmock_root", ",", "GMOCK_H_SEED", ")", "gtest", ".", "VerifyFileExists", "(", "gmock_root", ",", "GMOCK_ALL_CC_SEED", ")" ]
[ 96, 0 ]
[ 104, 55 ]
python
en
['en', 'en', 'en']
True
ValidateOutputDir
(output_dir)
Makes sure output_dir points to a valid output directory. The function aborts the program on failure.
Makes sure output_dir points to a valid output directory.
def ValidateOutputDir(output_dir): """Makes sure output_dir points to a valid output directory. The function aborts the program on failure. """ gtest.VerifyOutputFile(output_dir, gtest.GTEST_H_OUTPUT) gtest.VerifyOutputFile(output_dir, GMOCK_H_OUTPUT) gtest.VerifyOutputFile(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT)
[ "def", "ValidateOutputDir", "(", "output_dir", ")", ":", "gtest", ".", "VerifyOutputFile", "(", "output_dir", ",", "gtest", ".", "GTEST_H_OUTPUT", ")", "gtest", ".", "VerifyOutputFile", "(", "output_dir", ",", "GMOCK_H_OUTPUT", ")", "gtest", ".", "VerifyOutputFile", "(", "output_dir", ",", "GMOCK_GTEST_ALL_CC_OUTPUT", ")" ]
[ 107, 0 ]
[ 115, 63 ]
python
en
['en', 'en', 'en']
True
FuseGMockH
(gmock_root, output_dir)
Scans folder gmock_root to generate gmock/gmock.h in output_dir.
Scans folder gmock_root to generate gmock/gmock.h in output_dir.
def FuseGMockH(gmock_root, output_dir): """Scans folder gmock_root to generate gmock/gmock.h in output_dir.""" output_file = file(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w') processed_files = sets.Set() # Holds all gmock headers we've processed. def ProcessFile(gmock_header_path): """Processes the given gmock header file.""" # We don't process the same header twice. if gmock_header_path in processed_files: return processed_files.add(gmock_header_path) # Reads each line in the given gmock header. for line in file(os.path.join(gmock_root, gmock_header_path), 'r'): m = INCLUDE_GMOCK_FILE_REGEX.match(line) if m: # It's '#include "gmock/..."' - let's process it recursively. ProcessFile('include/' + m.group(1)) else: m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line) if m: # It's '#include "gtest/foo.h"'. We translate it to # "gtest/gtest.h", regardless of what foo is, since all # gtest headers are fused into gtest/gtest.h. # There is no need to #include gtest.h twice. if not gtest.GTEST_H_SEED in processed_files: processed_files.add(gtest.GTEST_H_SEED) output_file.write('#include "%s"\n' % (gtest.GTEST_H_OUTPUT,)) else: # Otherwise we copy the line unchanged to the output file. output_file.write(line) ProcessFile(GMOCK_H_SEED) output_file.close()
[ "def", "FuseGMockH", "(", "gmock_root", ",", "output_dir", ")", ":", "output_file", "=", "file", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "GMOCK_H_OUTPUT", ")", ",", "'w'", ")", "processed_files", "=", "sets", ".", "Set", "(", ")", "# Holds all gmock headers we've processed.", "def", "ProcessFile", "(", "gmock_header_path", ")", ":", "\"\"\"Processes the given gmock header file.\"\"\"", "# We don't process the same header twice.", "if", "gmock_header_path", "in", "processed_files", ":", "return", "processed_files", ".", "add", "(", "gmock_header_path", ")", "# Reads each line in the given gmock header.", "for", "line", "in", "file", "(", "os", ".", "path", ".", "join", "(", "gmock_root", ",", "gmock_header_path", ")", ",", "'r'", ")", ":", "m", "=", "INCLUDE_GMOCK_FILE_REGEX", ".", "match", "(", "line", ")", "if", "m", ":", "# It's '#include \"gmock/...\"' - let's process it recursively.", "ProcessFile", "(", "'include/'", "+", "m", ".", "group", "(", "1", ")", ")", "else", ":", "m", "=", "gtest", ".", "INCLUDE_GTEST_FILE_REGEX", ".", "match", "(", "line", ")", "if", "m", ":", "# It's '#include \"gtest/foo.h\"'. We translate it to", "# \"gtest/gtest.h\", regardless of what foo is, since all", "# gtest headers are fused into gtest/gtest.h.", "# There is no need to #include gtest.h twice.", "if", "not", "gtest", ".", "GTEST_H_SEED", "in", "processed_files", ":", "processed_files", ".", "add", "(", "gtest", ".", "GTEST_H_SEED", ")", "output_file", ".", "write", "(", "'#include \"%s\"\\n'", "%", "(", "gtest", ".", "GTEST_H_OUTPUT", ",", ")", ")", "else", ":", "# Otherwise we copy the line unchanged to the output file.", "output_file", ".", "write", "(", "line", ")", "ProcessFile", "(", "GMOCK_H_SEED", ")", "output_file", ".", "close", "(", ")" ]
[ 118, 0 ]
[ 155, 21 ]
python
en
['en', 'en', 'en']
True
FuseGMockAllCcToFile
(gmock_root, output_file)
Scans folder gmock_root to fuse gmock-all.cc into output_file.
Scans folder gmock_root to fuse gmock-all.cc into output_file.
def FuseGMockAllCcToFile(gmock_root, output_file): """Scans folder gmock_root to fuse gmock-all.cc into output_file.""" processed_files = sets.Set() def ProcessFile(gmock_source_file): """Processes the given gmock source file.""" # We don't process the same #included file twice. if gmock_source_file in processed_files: return processed_files.add(gmock_source_file) # Reads each line in the given gmock source file. for line in file(os.path.join(gmock_root, gmock_source_file), 'r'): m = INCLUDE_GMOCK_FILE_REGEX.match(line) if m: # It's '#include "gmock/foo.h"'. We treat it as '#include # "gmock/gmock.h"', as all other gmock headers are being fused # into gmock.h and cannot be #included directly. # There is no need to #include "gmock/gmock.h" more than once. if not GMOCK_H_SEED in processed_files: processed_files.add(GMOCK_H_SEED) output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,)) else: m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line) if m: # It's '#include "gtest/..."'. # There is no need to #include gtest.h as it has been # #included by gtest-all.cc. pass else: m = gtest.INCLUDE_SRC_FILE_REGEX.match(line) if m: # It's '#include "src/foo"' - let's process it recursively. ProcessFile(m.group(1)) else: # Otherwise we copy the line unchanged to the output file. output_file.write(line) ProcessFile(GMOCK_ALL_CC_SEED)
[ "def", "FuseGMockAllCcToFile", "(", "gmock_root", ",", "output_file", ")", ":", "processed_files", "=", "sets", ".", "Set", "(", ")", "def", "ProcessFile", "(", "gmock_source_file", ")", ":", "\"\"\"Processes the given gmock source file.\"\"\"", "# We don't process the same #included file twice.", "if", "gmock_source_file", "in", "processed_files", ":", "return", "processed_files", ".", "add", "(", "gmock_source_file", ")", "# Reads each line in the given gmock source file.", "for", "line", "in", "file", "(", "os", ".", "path", ".", "join", "(", "gmock_root", ",", "gmock_source_file", ")", ",", "'r'", ")", ":", "m", "=", "INCLUDE_GMOCK_FILE_REGEX", ".", "match", "(", "line", ")", "if", "m", ":", "# It's '#include \"gmock/foo.h\"'. We treat it as '#include", "# \"gmock/gmock.h\"', as all other gmock headers are being fused", "# into gmock.h and cannot be #included directly.", "# There is no need to #include \"gmock/gmock.h\" more than once.", "if", "not", "GMOCK_H_SEED", "in", "processed_files", ":", "processed_files", ".", "add", "(", "GMOCK_H_SEED", ")", "output_file", ".", "write", "(", "'#include \"%s\"\\n'", "%", "(", "GMOCK_H_OUTPUT", ",", ")", ")", "else", ":", "m", "=", "gtest", ".", "INCLUDE_GTEST_FILE_REGEX", ".", "match", "(", "line", ")", "if", "m", ":", "# It's '#include \"gtest/...\"'.", "# There is no need to #include gtest.h as it has been", "# #included by gtest-all.cc.", "pass", "else", ":", "m", "=", "gtest", ".", "INCLUDE_SRC_FILE_REGEX", ".", "match", "(", "line", ")", "if", "m", ":", "# It's '#include \"src/foo\"' - let's process it recursively.", "ProcessFile", "(", "m", ".", "group", "(", "1", ")", ")", "else", ":", "# Otherwise we copy the line unchanged to the output file.", "output_file", ".", "write", "(", "line", ")", "ProcessFile", "(", "GMOCK_ALL_CC_SEED", ")" ]
[ 158, 0 ]
[ 200, 32 ]
python
en
['en', 'en', 'en']
True
FuseGMockGTestAllCc
(gmock_root, output_dir)
Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir.
Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir.
def FuseGMockGTestAllCc(gmock_root, output_dir): """Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir.""" output_file = file(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w') # First, fuse gtest-all.cc into gmock-gtest-all.cc. gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file) # Next, append fused gmock-all.cc to gmock-gtest-all.cc. FuseGMockAllCcToFile(gmock_root, output_file) output_file.close()
[ "def", "FuseGMockGTestAllCc", "(", "gmock_root", ",", "output_dir", ")", ":", "output_file", "=", "file", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "GMOCK_GTEST_ALL_CC_OUTPUT", ")", ",", "'w'", ")", "# First, fuse gtest-all.cc into gmock-gtest-all.cc.", "gtest", ".", "FuseGTestAllCcToFile", "(", "GetGTestRootDir", "(", "gmock_root", ")", ",", "output_file", ")", "# Next, append fused gmock-all.cc to gmock-gtest-all.cc.", "FuseGMockAllCcToFile", "(", "gmock_root", ",", "output_file", ")", "output_file", ".", "close", "(", ")" ]
[ 203, 0 ]
[ 211, 21 ]
python
en
['en', 'en', 'en']
True
FuseGMock
(gmock_root, output_dir)
Fuses gtest.h, gmock.h, and gmock-gtest-all.h.
Fuses gtest.h, gmock.h, and gmock-gtest-all.h.
def FuseGMock(gmock_root, output_dir): """Fuses gtest.h, gmock.h, and gmock-gtest-all.h.""" ValidateGMockRootDir(gmock_root) ValidateOutputDir(output_dir) gtest.FuseGTestH(GetGTestRootDir(gmock_root), output_dir) FuseGMockH(gmock_root, output_dir) FuseGMockGTestAllCc(gmock_root, output_dir)
[ "def", "FuseGMock", "(", "gmock_root", ",", "output_dir", ")", ":", "ValidateGMockRootDir", "(", "gmock_root", ")", "ValidateOutputDir", "(", "output_dir", ")", "gtest", ".", "FuseGTestH", "(", "GetGTestRootDir", "(", "gmock_root", ")", ",", "output_dir", ")", "FuseGMockH", "(", "gmock_root", ",", "output_dir", ")", "FuseGMockGTestAllCc", "(", "gmock_root", ",", "output_dir", ")" ]
[ 214, 0 ]
[ 222, 45 ]
python
en
['en', 'en', 'en']
True
QueuedOutboundMessage.__init__
( self, context: InjectionContext, message: OutboundMessage, target: ConnectionTarget, transport_id: str, )
Initialize the queued outbound message.
Initialize the queued outbound message.
def __init__( self, context: InjectionContext, message: OutboundMessage, target: ConnectionTarget, transport_id: str, ): """Initialize the queued outbound message.""" self.context = context self.endpoint = target and target.endpoint self.error: Exception = None self.message = message self.payload: Union[str, bytes] = None self.retries = None self.retry_at: float = None self.state = self.STATE_NEW self.target = target self.task: asyncio.Task = None self.transport_id: str = transport_id
[ "def", "__init__", "(", "self", ",", "context", ":", "InjectionContext", ",", "message", ":", "OutboundMessage", ",", "target", ":", "ConnectionTarget", ",", "transport_id", ":", "str", ",", ")", ":", "self", ".", "context", "=", "context", "self", ".", "endpoint", "=", "target", "and", "target", ".", "endpoint", "self", ".", "error", ":", "Exception", "=", "None", "self", ".", "message", "=", "message", "self", ".", "payload", ":", "Union", "[", "str", ",", "bytes", "]", "=", "None", "self", ".", "retries", "=", "None", "self", ".", "retry_at", ":", "float", "=", "None", "self", ".", "state", "=", "self", ".", "STATE_NEW", "self", ".", "target", "=", "target", "self", ".", "task", ":", "asyncio", ".", "Task", "=", "None", "self", ".", "transport_id", ":", "str", "=", "transport_id" ]
[ 39, 4 ]
[ 57, 45 ]
python
en
['en', 'en', 'en']
True
OutboundTransportManager.__init__
( self, context: InjectionContext, handle_not_delivered: Callable = None )
Initialize a `OutboundTransportManager` instance. Args: context: The application context handle_not_delivered: An optional handler for undelivered messages
Initialize a `OutboundTransportManager` instance.
def __init__( self, context: InjectionContext, handle_not_delivered: Callable = None ): """ Initialize a `OutboundTransportManager` instance. Args: context: The application context handle_not_delivered: An optional handler for undelivered messages """ self.context = context self.loop = asyncio.get_event_loop() self.handle_not_delivered = handle_not_delivered self.outbound_buffer = [] self.outbound_event = asyncio.Event() self.outbound_new = [] self.registered_schemes = {} self.registered_transports = {} self.running_transports = {} self.task_queue = TaskQueue(max_active=200) self._process_task: asyncio.Task = None
[ "def", "__init__", "(", "self", ",", "context", ":", "InjectionContext", ",", "handle_not_delivered", ":", "Callable", "=", "None", ")", ":", "self", ".", "context", "=", "context", "self", ".", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "self", ".", "handle_not_delivered", "=", "handle_not_delivered", "self", ".", "outbound_buffer", "=", "[", "]", "self", ".", "outbound_event", "=", "asyncio", ".", "Event", "(", ")", "self", ".", "outbound_new", "=", "[", "]", "self", ".", "registered_schemes", "=", "{", "}", "self", ".", "registered_transports", "=", "{", "}", "self", ".", "running_transports", "=", "{", "}", "self", ".", "task_queue", "=", "TaskQueue", "(", "max_active", "=", "200", ")", "self", ".", "_process_task", ":", "asyncio", ".", "Task", "=", "None" ]
[ 63, 4 ]
[ 84, 47 ]
python
en
['en', 'error', 'th']
False
OutboundTransportManager.setup
(self)
Perform setup operations.
Perform setup operations.
async def setup(self): """Perform setup operations.""" outbound_transports = ( self.context.settings.get("transport.outbound_configs") or [] ) for outbound_transport in outbound_transports: self.register(outbound_transport)
[ "async", "def", "setup", "(", "self", ")", ":", "outbound_transports", "=", "(", "self", ".", "context", ".", "settings", ".", "get", "(", "\"transport.outbound_configs\"", ")", "or", "[", "]", ")", "for", "outbound_transport", "in", "outbound_transports", ":", "self", ".", "register", "(", "outbound_transport", ")" ]
[ 86, 4 ]
[ 92, 45 ]
python
en
['en', 'bg', 'en']
True
OutboundTransportManager.register
(self, module: str)
Register a new outbound transport by module path. Args: module: Module name to register Raises: OutboundTransportRegistrationError: If the imported class cannot be located OutboundTransportRegistrationError: If the imported class does not specify a schemes attribute OutboundTransportRegistrationError: If the scheme has already been registered
Register a new outbound transport by module path.
def register(self, module: str) -> str: """ Register a new outbound transport by module path. Args: module: Module name to register Raises: OutboundTransportRegistrationError: If the imported class cannot be located OutboundTransportRegistrationError: If the imported class does not specify a schemes attribute OutboundTransportRegistrationError: If the scheme has already been registered """ try: imported_class = ClassLoader.load_subclass_of( BaseOutboundTransport, module, MODULE_BASE_PATH ) except (ModuleLoadError, ClassNotFoundError): raise OutboundTransportRegistrationError( f"Outbound transport module {module} could not be resolved." ) return self.register_class(imported_class)
[ "def", "register", "(", "self", ",", "module", ":", "str", ")", "->", "str", ":", "try", ":", "imported_class", "=", "ClassLoader", ".", "load_subclass_of", "(", "BaseOutboundTransport", ",", "module", ",", "MODULE_BASE_PATH", ")", "except", "(", "ModuleLoadError", ",", "ClassNotFoundError", ")", ":", "raise", "OutboundTransportRegistrationError", "(", "f\"Outbound transport module {module} could not be resolved.\"", ")", "return", "self", ".", "register_class", "(", "imported_class", ")" ]
[ 94, 4 ]
[ 119, 50 ]
python
en
['en', 'error', 'th']
False
OutboundTransportManager.register_class
( self, transport_class: Type[BaseOutboundTransport], transport_id: str = None )
Register a new outbound transport class. Args: transport_class: Transport class to register Raises: OutboundTransportRegistrationError: If the imported class does not specify a schemes attribute OutboundTransportRegistrationError: If the scheme has already been registered
Register a new outbound transport class.
def register_class( self, transport_class: Type[BaseOutboundTransport], transport_id: str = None ) -> str: """ Register a new outbound transport class. Args: transport_class: Transport class to register Raises: OutboundTransportRegistrationError: If the imported class does not specify a schemes attribute OutboundTransportRegistrationError: If the scheme has already been registered """ try: schemes = transport_class.schemes except AttributeError: raise OutboundTransportRegistrationError( f"Imported class {transport_class} does not " + "specify a required 'schemes' attribute" ) if not transport_id: transport_id = transport_class.__qualname__ for scheme in schemes: if scheme in self.registered_schemes: # A scheme can only be registered once raise OutboundTransportRegistrationError( f"Cannot register transport '{transport_id}'" f"for '{scheme}' scheme because the scheme" "has already been registered" ) self.registered_transports[transport_id] = transport_class for scheme in schemes: self.registered_schemes[scheme] = transport_id return transport_id
[ "def", "register_class", "(", "self", ",", "transport_class", ":", "Type", "[", "BaseOutboundTransport", "]", ",", "transport_id", ":", "str", "=", "None", ")", "->", "str", ":", "try", ":", "schemes", "=", "transport_class", ".", "schemes", "except", "AttributeError", ":", "raise", "OutboundTransportRegistrationError", "(", "f\"Imported class {transport_class} does not \"", "+", "\"specify a required 'schemes' attribute\"", ")", "if", "not", "transport_id", ":", "transport_id", "=", "transport_class", ".", "__qualname__", "for", "scheme", "in", "schemes", ":", "if", "scheme", "in", "self", ".", "registered_schemes", ":", "# A scheme can only be registered once", "raise", "OutboundTransportRegistrationError", "(", "f\"Cannot register transport '{transport_id}'\"", "f\"for '{scheme}' scheme because the scheme\"", "\"has already been registered\"", ")", "self", ".", "registered_transports", "[", "transport_id", "]", "=", "transport_class", "for", "scheme", "in", "schemes", ":", "self", ".", "registered_schemes", "[", "scheme", "]", "=", "transport_id", "return", "transport_id" ]
[ 121, 4 ]
[ 161, 27 ]
python
en
['en', 'error', 'th']
False
OutboundTransportManager.start_transport
(self, transport_id: str)
Start a registered transport.
Start a registered transport.
async def start_transport(self, transport_id: str): """Start a registered transport.""" transport = self.registered_transports[transport_id]() transport.collector = await self.context.inject(Collector, required=False) await transport.start() self.running_transports[transport_id] = transport
[ "async", "def", "start_transport", "(", "self", ",", "transport_id", ":", "str", ")", ":", "transport", "=", "self", ".", "registered_transports", "[", "transport_id", "]", "(", ")", "transport", ".", "collector", "=", "await", "self", ".", "context", ".", "inject", "(", "Collector", ",", "required", "=", "False", ")", "await", "transport", ".", "start", "(", ")", "self", ".", "running_transports", "[", "transport_id", "]", "=", "transport" ]
[ 163, 4 ]
[ 168, 57 ]
python
en
['en', 'da', 'en']
True
OutboundTransportManager.start
(self)
Start all transports and feed messages from the queue.
Start all transports and feed messages from the queue.
async def start(self): """Start all transports and feed messages from the queue.""" for transport_id in self.registered_transports: self.task_queue.run(self.start_transport(transport_id))
[ "async", "def", "start", "(", "self", ")", ":", "for", "transport_id", "in", "self", ".", "registered_transports", ":", "self", ".", "task_queue", ".", "run", "(", "self", ".", "start_transport", "(", "transport_id", ")", ")" ]
[ 170, 4 ]
[ 173, 67 ]
python
en
['en', 'en', 'en']
True