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
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
Msg.__senders_get
(self)
Getter. Allows for value = self.sender
Getter. Allows for value = self.sender
def __senders_get(self): "Getter. Allows for value = self.sender" return list(self.db_sender_accounts.all()) + \ list(self.db_sender_objects.all()) + \ list(self.db_sender_scripts.all()) + \ self.extra_senders
[ "def", "__senders_get", "(", "self", ")", ":", "return", "list", "(", "self", ".", "db_sender_accounts", ".", "all", "(", ")", ")", "+", "list", "(", "self", ".", "db_sender_objects", ".", "all", "(", ")", ")", "+", "list", "(", "self", ".", "db_sender_scripts", ".", "all", "(", ")", ")", "+", "self", ".", "extra_senders" ]
[ 155, 4 ]
[ 160, 30 ]
python
da
['da', 'no', 'en']
False
Msg.__senders_set
(self, senders)
Setter. Allows for self.sender = value
Setter. Allows for self.sender = value
def __senders_set(self, senders): "Setter. Allows for self.sender = value" for sender in make_iter(senders): if not sender: continue if isinstance(sender, basestring): self.db_sender_external = sender self.extra_senders.append(sender) self.save(update_fields=["db_sender_external"]) continue if not hasattr(sender, "__dbclass__"): raise ValueError("This is a not a typeclassed object!") clsname = sender.__dbclass__.__name__ if clsname == "ObjectDB": self.db_sender_objects.add(sender) elif clsname == "AccountDB": self.db_sender_accounts.add(sender) elif clsname == "ScriptDB": self.db_sender_scripts.add(sender)
[ "def", "__senders_set", "(", "self", ",", "senders", ")", ":", "for", "sender", "in", "make_iter", "(", "senders", ")", ":", "if", "not", "sender", ":", "continue", "if", "isinstance", "(", "sender", ",", "basestring", ")", ":", "self", ".", "db_sender_external", "=", "sender", "self", ".", "extra_senders", ".", "append", "(", "sender", ")", "self", ".", "save", "(", "update_fields", "=", "[", "\"db_sender_external\"", "]", ")", "continue", "if", "not", "hasattr", "(", "sender", ",", "\"__dbclass__\"", ")", ":", "raise", "ValueError", "(", "\"This is a not a typeclassed object!\"", ")", "clsname", "=", "sender", ".", "__dbclass__", ".", "__name__", "if", "clsname", "==", "\"ObjectDB\"", ":", "self", ".", "db_sender_objects", ".", "add", "(", "sender", ")", "elif", "clsname", "==", "\"AccountDB\"", ":", "self", ".", "db_sender_accounts", ".", "add", "(", "sender", ")", "elif", "clsname", "==", "\"ScriptDB\"", ":", "self", ".", "db_sender_scripts", ".", "add", "(", "sender", ")" ]
[ 163, 4 ]
[ 181, 50 ]
python
da
['da', 'no', 'en']
False
Msg.__senders_del
(self)
Deleter. Clears all senders
Deleter. Clears all senders
def __senders_del(self): "Deleter. Clears all senders" self.db_sender_accounts.clear() self.db_sender_objects.clear() self.db_sender_scripts.clear() self.db_sender_external = "" self.extra_senders = [] self.save()
[ "def", "__senders_del", "(", "self", ")", ":", "self", ".", "db_sender_accounts", ".", "clear", "(", ")", "self", ".", "db_sender_objects", ".", "clear", "(", ")", "self", ".", "db_sender_scripts", ".", "clear", "(", ")", "self", ".", "db_sender_external", "=", "\"\"", "self", ".", "extra_senders", "=", "[", "]", "self", ".", "save", "(", ")" ]
[ 184, 4 ]
[ 191, 19 ]
python
af
['en', 'af', 'it']
False
Msg.remove_sender
(self, senders)
Remove a single sender or a list of senders. Args: senders (Account, Object, str or list): Senders to remove.
Remove a single sender or a list of senders.
def remove_sender(self, senders): """ Remove a single sender or a list of senders. Args: senders (Account, Object, str or list): Senders to remove. """ for sender in make_iter(senders): if not sender: continue if isinstance(sender, basestring): self.db_sender_external = "" self.save(update_fields=["db_sender_external"]) if not hasattr(sender, "__dbclass__"): raise ValueError("This is a not a typeclassed object!") clsname = sender.__dbclass__.__name__ if clsname == "ObjectDB": self.db_sender_objects.remove(sender) elif clsname == "AccountDB": self.db_sender_accounts.remove(sender) elif clsname == "ScriptDB": self.db_sender_accounts.remove(sender)
[ "def", "remove_sender", "(", "self", ",", "senders", ")", ":", "for", "sender", "in", "make_iter", "(", "senders", ")", ":", "if", "not", "sender", ":", "continue", "if", "isinstance", "(", "sender", ",", "basestring", ")", ":", "self", ".", "db_sender_external", "=", "\"\"", "self", ".", "save", "(", "update_fields", "=", "[", "\"db_sender_external\"", "]", ")", "if", "not", "hasattr", "(", "sender", ",", "\"__dbclass__\"", ")", ":", "raise", "ValueError", "(", "\"This is a not a typeclassed object!\"", ")", "clsname", "=", "sender", ".", "__dbclass__", ".", "__name__", "if", "clsname", "==", "\"ObjectDB\"", ":", "self", ".", "db_sender_objects", ".", "remove", "(", "sender", ")", "elif", "clsname", "==", "\"AccountDB\"", ":", "self", ".", "db_sender_accounts", ".", "remove", "(", "sender", ")", "elif", "clsname", "==", "\"ScriptDB\"", ":", "self", ".", "db_sender_accounts", ".", "remove", "(", "sender", ")" ]
[ 194, 4 ]
[ 216, 54 ]
python
en
['en', 'error', 'th']
False
Msg.__receivers_get
(self)
Getter. Allows for value = self.receivers. Returns four lists of receivers: accounts, objects, scripts and channels.
Getter. Allows for value = self.receivers. Returns four lists of receivers: accounts, objects, scripts and channels.
def __receivers_get(self): """ Getter. Allows for value = self.receivers. Returns four lists of receivers: accounts, objects, scripts and channels. """ return list(self.db_receivers_accounts.all()) + \ list(self.db_receivers_objects.all()) + \ list(self.db_receivers_scripts.all()) + \ list(self.db_receivers_channels.all())
[ "def", "__receivers_get", "(", "self", ")", ":", "return", "list", "(", "self", ".", "db_receivers_accounts", ".", "all", "(", ")", ")", "+", "list", "(", "self", ".", "db_receivers_objects", ".", "all", "(", ")", ")", "+", "list", "(", "self", ".", "db_receivers_scripts", ".", "all", "(", ")", ")", "+", "list", "(", "self", ".", "db_receivers_channels", ".", "all", "(", ")", ")" ]
[ 220, 4 ]
[ 228, 50 ]
python
en
['en', 'error', 'th']
False
Msg.__receivers_set
(self, receivers)
Setter. Allows for self.receivers = value. This appends a new receiver to the message.
Setter. Allows for self.receivers = value. This appends a new receiver to the message.
def __receivers_set(self, receivers): """ Setter. Allows for self.receivers = value. This appends a new receiver to the message. """ for receiver in make_iter(receivers): if not receiver: continue if not hasattr(receiver, "__dbclass__"): raise ValueError("This is a not a typeclassed object!") clsname = receiver.__dbclass__.__name__ if clsname == "ObjectDB": self.db_receivers_objects.add(receiver) elif clsname == "AccountDB": self.db_receivers_accounts.add(receiver) elif clsname == "ScriptDB": self.db_receivers_scripts.add(receiver) elif clsname == "ChannelDB": self.db_receivers_channels.add(receiver)
[ "def", "__receivers_set", "(", "self", ",", "receivers", ")", ":", "for", "receiver", "in", "make_iter", "(", "receivers", ")", ":", "if", "not", "receiver", ":", "continue", "if", "not", "hasattr", "(", "receiver", ",", "\"__dbclass__\"", ")", ":", "raise", "ValueError", "(", "\"This is a not a typeclassed object!\"", ")", "clsname", "=", "receiver", ".", "__dbclass__", ".", "__name__", "if", "clsname", "==", "\"ObjectDB\"", ":", "self", ".", "db_receivers_objects", ".", "add", "(", "receiver", ")", "elif", "clsname", "==", "\"AccountDB\"", ":", "self", ".", "db_receivers_accounts", ".", "add", "(", "receiver", ")", "elif", "clsname", "==", "\"ScriptDB\"", ":", "self", ".", "db_receivers_scripts", ".", "add", "(", "receiver", ")", "elif", "clsname", "==", "\"ChannelDB\"", ":", "self", ".", "db_receivers_channels", ".", "add", "(", "receiver", ")" ]
[ 231, 4 ]
[ 249, 56 ]
python
en
['en', 'error', 'th']
False
Msg.__receivers_del
(self)
Deleter. Clears all receivers
Deleter. Clears all receivers
def __receivers_del(self): "Deleter. Clears all receivers" self.db_receivers_accounts.clear() self.db_receivers_objects.clear() self.db_receivers_scripts.clear() self.db_receivers_channels.clear() self.save()
[ "def", "__receivers_del", "(", "self", ")", ":", "self", ".", "db_receivers_accounts", ".", "clear", "(", ")", "self", ".", "db_receivers_objects", ".", "clear", "(", ")", "self", ".", "db_receivers_scripts", ".", "clear", "(", ")", "self", ".", "db_receivers_channels", ".", "clear", "(", ")", "self", ".", "save", "(", ")" ]
[ 252, 4 ]
[ 258, 19 ]
python
en
['en', 'en', 'en']
True
Msg.remove_receiver
(self, receivers)
Remove a single receiver or a list of receivers. Args: receivers (Account, Object, Script, Channel or list): Receiver to remove.
Remove a single receiver or a list of receivers.
def remove_receiver(self, receivers): """ Remove a single receiver or a list of receivers. Args: receivers (Account, Object, Script, Channel or list): Receiver to remove. """ for receiver in make_iter(receivers): if not receiver: continue if not hasattr(receiver, "__dbclass__"): raise ValueError("This is a not a typeclassed object!") clsname = receiver.__dbclass__.__name__ if clsname == "ObjectDB": self.db_receivers_objects.remove(receiver) elif clsname == "AccountDB": self.db_receivers_accounts.remove(receiver) elif clsname == "ScriptDB": self.db_receivers_scripts.remove(receiver) elif clsname == "ChannelDB": self.db_receivers_channels.remove(receiver)
[ "def", "remove_receiver", "(", "self", ",", "receivers", ")", ":", "for", "receiver", "in", "make_iter", "(", "receivers", ")", ":", "if", "not", "receiver", ":", "continue", "if", "not", "hasattr", "(", "receiver", ",", "\"__dbclass__\"", ")", ":", "raise", "ValueError", "(", "\"This is a not a typeclassed object!\"", ")", "clsname", "=", "receiver", ".", "__dbclass__", ".", "__name__", "if", "clsname", "==", "\"ObjectDB\"", ":", "self", ".", "db_receivers_objects", ".", "remove", "(", "receiver", ")", "elif", "clsname", "==", "\"AccountDB\"", ":", "self", ".", "db_receivers_accounts", ".", "remove", "(", "receiver", ")", "elif", "clsname", "==", "\"ScriptDB\"", ":", "self", ".", "db_receivers_scripts", ".", "remove", "(", "receiver", ")", "elif", "clsname", "==", "\"ChannelDB\"", ":", "self", ".", "db_receivers_channels", ".", "remove", "(", "receiver", ")" ]
[ 261, 4 ]
[ 282, 59 ]
python
en
['en', 'error', 'th']
False
Msg.__channels_get
(self)
Getter. Allows for value = self.channels. Returns a list of channels.
Getter. Allows for value = self.channels. Returns a list of channels.
def __channels_get(self): "Getter. Allows for value = self.channels. Returns a list of channels." return self.db_receivers_channels.all()
[ "def", "__channels_get", "(", "self", ")", ":", "return", "self", ".", "db_receivers_channels", ".", "all", "(", ")" ]
[ 286, 4 ]
[ 288, 47 ]
python
en
['en', 'en', 'en']
True
Msg.__channels_set
(self, value)
Setter. Allows for self.channels = value. Requires a channel to be added.
Setter. Allows for self.channels = value. Requires a channel to be added.
def __channels_set(self, value): """ Setter. Allows for self.channels = value. Requires a channel to be added. """ for val in (v for v in make_iter(value) if v): self.db_receivers_channels.add(val)
[ "def", "__channels_set", "(", "self", ",", "value", ")", ":", "for", "val", "in", "(", "v", "for", "v", "in", "make_iter", "(", "value", ")", "if", "v", ")", ":", "self", ".", "db_receivers_channels", ".", "add", "(", "val", ")" ]
[ 291, 4 ]
[ 297, 47 ]
python
en
['en', 'error', 'th']
False
Msg.__channels_del
(self)
Deleter. Allows for del self.channels
Deleter. Allows for del self.channels
def __channels_del(self): "Deleter. Allows for del self.channels" self.db_receivers_channels.clear() self.save()
[ "def", "__channels_del", "(", "self", ")", ":", "self", ".", "db_receivers_channels", ".", "clear", "(", ")", "self", ".", "save", "(", ")" ]
[ 300, 4 ]
[ 303, 19 ]
python
ca
['ca', 'en', 'it']
False
Msg.__hide_from_get
(self)
Getter. Allows for value = self.hide_from. Returns 3 lists of accounts, objects and channels
Getter. Allows for value = self.hide_from. Returns 3 lists of accounts, objects and channels
def __hide_from_get(self): """ Getter. Allows for value = self.hide_from. Returns 3 lists of accounts, objects and channels """ return self.db_hide_from_accounts.all(), self.db_hide_from_objects.all(), self.db_hide_from_channels.all()
[ "def", "__hide_from_get", "(", "self", ")", ":", "return", "self", ".", "db_hide_from_accounts", ".", "all", "(", ")", ",", "self", ".", "db_hide_from_objects", ".", "all", "(", ")", ",", "self", ".", "db_hide_from_channels", ".", "all", "(", ")" ]
[ 306, 4 ]
[ 311, 114 ]
python
en
['en', 'error', 'th']
False
Msg.__hide_from_set
(self, hiders)
Setter. Allows for self.hide_from = value. Will append to hiders
Setter. Allows for self.hide_from = value. Will append to hiders
def __hide_from_set(self, hiders): "Setter. Allows for self.hide_from = value. Will append to hiders" for hider in make_iter(hiders): if not hider: continue if not hasattr(hider, "__dbclass__"): raise ValueError("This is a not a typeclassed object!") clsname = hider.__dbclass__.__name__ if clsname == "AccountDB": self.db_hide_from_accounts.add(hider.__dbclass__) elif clsname == "ObjectDB": self.db_hide_from_objects.add(hider.__dbclass__) elif clsname == "ChannelDB": self.db_hide_from_channels.add(hider.__dbclass__)
[ "def", "__hide_from_set", "(", "self", ",", "hiders", ")", ":", "for", "hider", "in", "make_iter", "(", "hiders", ")", ":", "if", "not", "hider", ":", "continue", "if", "not", "hasattr", "(", "hider", ",", "\"__dbclass__\"", ")", ":", "raise", "ValueError", "(", "\"This is a not a typeclassed object!\"", ")", "clsname", "=", "hider", ".", "__dbclass__", ".", "__name__", "if", "clsname", "==", "\"AccountDB\"", ":", "self", ".", "db_hide_from_accounts", ".", "add", "(", "hider", ".", "__dbclass__", ")", "elif", "clsname", "==", "\"ObjectDB\"", ":", "self", ".", "db_hide_from_objects", ".", "add", "(", "hider", ".", "__dbclass__", ")", "elif", "clsname", "==", "\"ChannelDB\"", ":", "self", ".", "db_hide_from_channels", ".", "add", "(", "hider", ".", "__dbclass__", ")" ]
[ 314, 4 ]
[ 327, 65 ]
python
en
['en', 'en', 'en']
True
Msg.__hide_from_del
(self)
Deleter. Allows for del self.hide_from_senders
Deleter. Allows for del self.hide_from_senders
def __hide_from_del(self): "Deleter. Allows for del self.hide_from_senders" self.db_hide_from_accounts.clear() self.db_hide_from_objects.clear() self.db_hide_from_channels.clear() self.save()
[ "def", "__hide_from_del", "(", "self", ")", ":", "self", ".", "db_hide_from_accounts", ".", "clear", "(", ")", "self", ".", "db_hide_from_objects", ".", "clear", "(", ")", "self", ".", "db_hide_from_channels", ".", "clear", "(", ")", "self", ".", "save", "(", ")" ]
[ 330, 4 ]
[ 335, 19 ]
python
en
['es', 'en', 'it']
False
Msg.__str__
(self)
This handles what is shown when e.g. printing the message
This handles what is shown when e.g. printing the message
def __str__(self): "This handles what is shown when e.g. printing the message" senders = ",".join(obj.key for obj in self.senders) receivers = ",".join(["[%s]" % obj.key for obj in self.channels] + [obj.key for obj in self.receivers]) return "%s->%s: %s" % (senders, receivers, crop(self.message, width=40))
[ "def", "__str__", "(", "self", ")", ":", "senders", "=", "\",\"", ".", "join", "(", "obj", ".", "key", "for", "obj", "in", "self", ".", "senders", ")", "receivers", "=", "\",\"", ".", "join", "(", "[", "\"[%s]\"", "%", "obj", ".", "key", "for", "obj", "in", "self", ".", "channels", "]", "+", "[", "obj", ".", "key", "for", "obj", "in", "self", ".", "receivers", "]", ")", "return", "\"%s->%s: %s\"", "%", "(", "senders", ",", "receivers", ",", "crop", "(", "self", ".", "message", ",", "width", "=", "40", ")", ")" ]
[ 342, 4 ]
[ 346, 80 ]
python
en
['en', 'en', 'en']
True
Msg.access
(self, accessing_obj, access_type='read', default=False)
Checks lock access. Args: accessing_obj (Object or Account): The object trying to gain access. access_type (str, optional): The type of lock access to check. default (bool): Fallback to use if `access_type` lock is not defined. Returns: result (bool): If access was granted or not.
Checks lock access.
def access(self, accessing_obj, access_type='read', default=False): """ Checks lock access. Args: accessing_obj (Object or Account): The object trying to gain access. access_type (str, optional): The type of lock access to check. default (bool): Fallback to use if `access_type` lock is not defined. Returns: result (bool): If access was granted or not. """ return self.locks.check(accessing_obj, access_type=access_type, default=default)
[ "def", "access", "(", "self", ",", "accessing_obj", ",", "access_type", "=", "'read'", ",", "default", "=", "False", ")", ":", "return", "self", ".", "locks", ".", "check", "(", "accessing_obj", ",", "access_type", "=", "access_type", ",", "default", "=", "default", ")" ]
[ 348, 4 ]
[ 362, 73 ]
python
en
['en', 'error', 'th']
False
TempMsg.__init__
(self, senders=None, receivers=None, channels=None, message="", header="", type="", lockstring="", hide_from=None)
Creates the temp message. Args: senders (any or list, optional): Senders of the message. receivers (Account, Object, Channel or list, optional): Receivers of this message. channels (Channel or list, optional): Channels to send to. message (str, optional): Message to send. header (str, optional): Header of message. type (str, optional): Message class, if any. lockstring (str, optional): Lock for the message. hide_from (Account, Object, Channel or list, optional): Entities to hide this message from.
Creates the temp message.
def __init__(self, senders=None, receivers=None, channels=None, message="", header="", type="", lockstring="", hide_from=None): """ Creates the temp message. Args: senders (any or list, optional): Senders of the message. receivers (Account, Object, Channel or list, optional): Receivers of this message. channels (Channel or list, optional): Channels to send to. message (str, optional): Message to send. header (str, optional): Header of message. type (str, optional): Message class, if any. lockstring (str, optional): Lock for the message. hide_from (Account, Object, Channel or list, optional): Entities to hide this message from. """ self.senders = senders and make_iter(senders) or [] self.receivers = receivers and make_iter(receivers) or [] self.channels = channels and make_iter(channels) or [] self.type = type self.header = header self.message = message self.lock_storage = lockstring self.hide_from = hide_from and make_iter(hide_from) or [] self.date_created = timezone.now()
[ "def", "__init__", "(", "self", ",", "senders", "=", "None", ",", "receivers", "=", "None", ",", "channels", "=", "None", ",", "message", "=", "\"\"", ",", "header", "=", "\"\"", ",", "type", "=", "\"\"", ",", "lockstring", "=", "\"\"", ",", "hide_from", "=", "None", ")", ":", "self", ".", "senders", "=", "senders", "and", "make_iter", "(", "senders", ")", "or", "[", "]", "self", ".", "receivers", "=", "receivers", "and", "make_iter", "(", "receivers", ")", "or", "[", "]", "self", ".", "channels", "=", "channels", "and", "make_iter", "(", "channels", ")", "or", "[", "]", "self", ".", "type", "=", "type", "self", ".", "header", "=", "header", "self", ".", "message", "=", "message", "self", ".", "lock_storage", "=", "lockstring", "self", ".", "hide_from", "=", "hide_from", "and", "make_iter", "(", "hide_from", ")", "or", "[", "]", "self", ".", "date_created", "=", "timezone", ".", "now", "(", ")" ]
[ 379, 4 ]
[ 402, 42 ]
python
en
['en', 'error', 'th']
False
TempMsg.__str__
(self)
This handles what is shown when e.g. printing the message.
This handles what is shown when e.g. printing the message.
def __str__(self): """ This handles what is shown when e.g. printing the message. """ senders = ",".join(obj.key for obj in self.senders) receivers = ",".join(["[%s]" % obj.key for obj in self.channels] + [obj.key for obj in self.receivers]) return "%s->%s: %s" % (senders, receivers, crop(self.message, width=40))
[ "def", "__str__", "(", "self", ")", ":", "senders", "=", "\",\"", ".", "join", "(", "obj", ".", "key", "for", "obj", "in", "self", ".", "senders", ")", "receivers", "=", "\",\"", ".", "join", "(", "[", "\"[%s]\"", "%", "obj", ".", "key", "for", "obj", "in", "self", ".", "channels", "]", "+", "[", "obj", ".", "key", "for", "obj", "in", "self", ".", "receivers", "]", ")", "return", "\"%s->%s: %s\"", "%", "(", "senders", ",", "receivers", ",", "crop", "(", "self", ".", "message", ",", "width", "=", "40", ")", ")" ]
[ 408, 4 ]
[ 414, 80 ]
python
en
['en', 'error', 'th']
False
TempMsg.remove_sender
(self, sender)
Remove a sender or a list of senders. Args: sender (Object, Account, str or list): Senders to remove.
Remove a sender or a list of senders.
def remove_sender(self, sender): """ Remove a sender or a list of senders. Args: sender (Object, Account, str or list): Senders to remove. """ for o in make_iter(sender): try: self.senders.remove(o) except ValueError: pass
[ "def", "remove_sender", "(", "self", ",", "sender", ")", ":", "for", "o", "in", "make_iter", "(", "sender", ")", ":", "try", ":", "self", ".", "senders", ".", "remove", "(", "o", ")", "except", "ValueError", ":", "pass" ]
[ 416, 4 ]
[ 428, 20 ]
python
en
['en', 'error', 'th']
False
TempMsg.remove_receiver
(self, receiver)
Remove a receiver or a list of receivers Args: receiver (Object, Account, Channel, str or list): Receivers to remove.
Remove a receiver or a list of receivers
def remove_receiver(self, receiver): """ Remove a receiver or a list of receivers Args: receiver (Object, Account, Channel, str or list): Receivers to remove. """ for o in make_iter(receiver): try: self.senders.remove(o) except ValueError: pass
[ "def", "remove_receiver", "(", "self", ",", "receiver", ")", ":", "for", "o", "in", "make_iter", "(", "receiver", ")", ":", "try", ":", "self", ".", "senders", ".", "remove", "(", "o", ")", "except", "ValueError", ":", "pass" ]
[ 430, 4 ]
[ 442, 20 ]
python
en
['en', 'error', 'th']
False
TempMsg.access
(self, accessing_obj, access_type='read', default=False)
Checks lock access. Args: accessing_obj (Object or Account): The object trying to gain access. access_type (str, optional): The type of lock access to check. default (bool): Fallback to use if `access_type` lock is not defined. Returns: result (bool): If access was granted or not.
Checks lock access.
def access(self, accessing_obj, access_type='read', default=False): """ Checks lock access. Args: accessing_obj (Object or Account): The object trying to gain access. access_type (str, optional): The type of lock access to check. default (bool): Fallback to use if `access_type` lock is not defined. Returns: result (bool): If access was granted or not. """ return self.locks.check(accessing_obj, access_type=access_type, default=default)
[ "def", "access", "(", "self", ",", "accessing_obj", ",", "access_type", "=", "'read'", ",", "default", "=", "False", ")", ":", "return", "self", ".", "locks", ".", "check", "(", "accessing_obj", ",", "access_type", "=", "access_type", ",", "default", "=", "default", ")" ]
[ 444, 4 ]
[ 458, 73 ]
python
en
['en', 'error', 'th']
False
SubscriptionHandler.__init__
(self, obj)
Initialize the handler Attr: obj (ChannelDB): The channel the handler sits on.
Initialize the handler
def __init__(self, obj): """ Initialize the handler Attr: obj (ChannelDB): The channel the handler sits on. """ self.obj = obj self._cache = None
[ "def", "__init__", "(", "self", ",", "obj", ")", ":", "self", ".", "obj", "=", "obj", "self", ".", "_cache", "=", "None" ]
[ 474, 4 ]
[ 483, 26 ]
python
en
['en', 'error', 'th']
False
SubscriptionHandler.has
(self, entity)
Check if the given entity subscribe to this channel Args: entity (str, Account or Object): The entity to return. If a string, it assumed to be the key or the #dbref of the entity. Returns: subscriber (Account, Object or None): The given subscriber.
Check if the given entity subscribe to this channel
def has(self, entity): """ Check if the given entity subscribe to this channel Args: entity (str, Account or Object): The entity to return. If a string, it assumed to be the key or the #dbref of the entity. Returns: subscriber (Account, Object or None): The given subscriber. """ if self._cache is None: self._recache() return entity in self._cache
[ "def", "has", "(", "self", ",", "entity", ")", ":", "if", "self", ".", "_cache", "is", "None", ":", "self", ".", "_recache", "(", ")", "return", "entity", "in", "self", ".", "_cache" ]
[ 491, 4 ]
[ 507, 36 ]
python
en
['en', 'error', 'th']
False
SubscriptionHandler.add
(self, entity)
Subscribe an entity to this channel. Args: entity (Account, Object or list): The entity or list of entities to subscribe to this channel. Note: No access-checking is done here, this must have been done before calling this method. Also no hooks will be called.
Subscribe an entity to this channel.
def add(self, entity): """ Subscribe an entity to this channel. Args: entity (Account, Object or list): The entity or list of entities to subscribe to this channel. Note: No access-checking is done here, this must have been done before calling this method. Also no hooks will be called. """ global _CHANNELHANDLER if not _CHANNELHANDLER: from evennia.comms.channelhandler import CHANNEL_HANDLER as _CHANNELHANDLER for subscriber in make_iter(entity): if subscriber: clsname = subscriber.__dbclass__.__name__ # chooses the right type if clsname == "ObjectDB": self.obj.db_object_subscriptions.add(subscriber) elif clsname == "AccountDB": self.obj.db_account_subscriptions.add(subscriber) _CHANNELHANDLER._cached_cmdsets.pop(subscriber, None) self._recache()
[ "def", "add", "(", "self", ",", "entity", ")", ":", "global", "_CHANNELHANDLER", "if", "not", "_CHANNELHANDLER", ":", "from", "evennia", ".", "comms", ".", "channelhandler", "import", "CHANNEL_HANDLER", "as", "_CHANNELHANDLER", "for", "subscriber", "in", "make_iter", "(", "entity", ")", ":", "if", "subscriber", ":", "clsname", "=", "subscriber", ".", "__dbclass__", ".", "__name__", "# chooses the right type", "if", "clsname", "==", "\"ObjectDB\"", ":", "self", ".", "obj", ".", "db_object_subscriptions", ".", "add", "(", "subscriber", ")", "elif", "clsname", "==", "\"AccountDB\"", ":", "self", ".", "obj", ".", "db_account_subscriptions", ".", "add", "(", "subscriber", ")", "_CHANNELHANDLER", ".", "_cached_cmdsets", ".", "pop", "(", "subscriber", ",", "None", ")", "self", ".", "_recache", "(", ")" ]
[ 509, 4 ]
[ 535, 23 ]
python
en
['en', 'error', 'th']
False
SubscriptionHandler.remove
(self, entity)
Remove a subscriber from the channel. Args: entity (Account, Object or list): The entity or entities to un-subscribe from the channel.
Remove a subscriber from the channel.
def remove(self, entity): """ Remove a subscriber from the channel. Args: entity (Account, Object or list): The entity or entities to un-subscribe from the channel. """ global _CHANNELHANDLER if not _CHANNELHANDLER: from evennia.comms.channelhandler import CHANNEL_HANDLER as _CHANNELHANDLER for subscriber in make_iter(entity): if subscriber: clsname = subscriber.__dbclass__.__name__ # chooses the right type if clsname == "AccountDB": self.obj.db_account_subscriptions.remove(entity) elif clsname == "ObjectDB": self.obj.db_object_subscriptions.remove(entity) _CHANNELHANDLER._cached_cmdsets.pop(subscriber, None) self._recache()
[ "def", "remove", "(", "self", ",", "entity", ")", ":", "global", "_CHANNELHANDLER", "if", "not", "_CHANNELHANDLER", ":", "from", "evennia", ".", "comms", ".", "channelhandler", "import", "CHANNEL_HANDLER", "as", "_CHANNELHANDLER", "for", "subscriber", "in", "make_iter", "(", "entity", ")", ":", "if", "subscriber", ":", "clsname", "=", "subscriber", ".", "__dbclass__", ".", "__name__", "# chooses the right type", "if", "clsname", "==", "\"AccountDB\"", ":", "self", ".", "obj", ".", "db_account_subscriptions", ".", "remove", "(", "entity", ")", "elif", "clsname", "==", "\"ObjectDB\"", ":", "self", ".", "obj", ".", "db_object_subscriptions", ".", "remove", "(", "entity", ")", "_CHANNELHANDLER", ".", "_cached_cmdsets", ".", "pop", "(", "subscriber", ",", "None", ")", "self", ".", "_recache", "(", ")" ]
[ 537, 4 ]
[ 558, 23 ]
python
en
['en', 'error', 'th']
False
SubscriptionHandler.all
(self)
Get all subscriptions to this channel. Returns: subscribers (list): The subscribers. This may be a mix of Accounts and Objects!
Get all subscriptions to this channel.
def all(self): """ Get all subscriptions to this channel. Returns: subscribers (list): The subscribers. This may be a mix of Accounts and Objects! """ if self._cache is None: self._recache() return self._cache
[ "def", "all", "(", "self", ")", ":", "if", "self", ".", "_cache", "is", "None", ":", "self", ".", "_recache", "(", ")", "return", "self", ".", "_cache" ]
[ 560, 4 ]
[ 571, 26 ]
python
en
['en', 'error', 'th']
False
SubscriptionHandler.online
(self)
Get all online accounts from our cache Returns: subscribers (list): Subscribers who are online or are puppeted by an online account.
Get all online accounts from our cache Returns: subscribers (list): Subscribers who are online or are puppeted by an online account.
def online(self): """ Get all online accounts from our cache Returns: subscribers (list): Subscribers who are online or are puppeted by an online account. """ subs = [] recache_needed = False for obj in self.all(): from django.core.exceptions import ObjectDoesNotExist try: if hasattr(obj, 'account') and obj.account: obj = obj.account if not obj.is_connected: continue except ObjectDoesNotExist: # a subscribed object has already been deleted. Mark that we need a recache and ignore it recache_needed = True continue subs.append(obj) if recache_needed: self._recache() return subs
[ "def", "online", "(", "self", ")", ":", "subs", "=", "[", "]", "recache_needed", "=", "False", "for", "obj", "in", "self", ".", "all", "(", ")", ":", "from", "django", ".", "core", ".", "exceptions", "import", "ObjectDoesNotExist", "try", ":", "if", "hasattr", "(", "obj", ",", "'account'", ")", "and", "obj", ".", "account", ":", "obj", "=", "obj", ".", "account", "if", "not", "obj", ".", "is_connected", ":", "continue", "except", "ObjectDoesNotExist", ":", "# a subscribed object has already been deleted. Mark that we need a recache and ignore it", "recache_needed", "=", "True", "continue", "subs", ".", "append", "(", "obj", ")", "if", "recache_needed", ":", "self", ".", "_recache", "(", ")", "return", "subs" ]
[ 574, 4 ]
[ 597, 19 ]
python
en
['en', 'error', 'th']
False
SubscriptionHandler.clear
(self)
Remove all subscribers from channel.
Remove all subscribers from channel.
def clear(self): """ Remove all subscribers from channel. """ self.obj.db_account_subscriptions.clear() self.obj.db_object_subscriptions.clear() self._cache = None
[ "def", "clear", "(", "self", ")", ":", "self", ".", "obj", ".", "db_account_subscriptions", ".", "clear", "(", ")", "self", ".", "obj", ".", "db_object_subscriptions", ".", "clear", "(", ")", "self", ".", "_cache", "=", "None" ]
[ 599, 4 ]
[ 606, 26 ]
python
en
['en', 'error', 'th']
False
ChannelDB.__str__
(self)
Echoes the text representation of the channel.
Echoes the text representation of the channel.
def __str__(self): "Echoes the text representation of the channel." return "Channel '%s' (%s)" % (self.key, self.db.desc)
[ "def", "__str__", "(", "self", ")", ":", "return", "\"Channel '%s' (%s)\"", "%", "(", "self", ".", "key", ",", "self", ".", "db", ".", "desc", ")" ]
[ 639, 4 ]
[ 641, 61 ]
python
en
['en', 'en', 'en']
True
SuppressGA.__init__
(self, protocol)
Initialize suppression of GO-AHEADs. Args: protocol (Protocol): The active protocol instance.
Initialize suppression of GO-AHEADs.
def __init__(self, protocol): """ Initialize suppression of GO-AHEADs. Args: protocol (Protocol): The active protocol instance. """ self.protocol = protocol self.protocol.protocol_flags["NOGOAHEAD"] = True # tell the client that we prefer to suppress GA ... self.protocol.will(SUPPRESS_GA).addCallbacks(self.will_suppress_ga, self.wont_suppress_ga)
[ "def", "__init__", "(", "self", ",", "protocol", ")", ":", "self", ".", "protocol", "=", "protocol", "self", ".", "protocol", ".", "protocol_flags", "[", "\"NOGOAHEAD\"", "]", "=", "True", "# tell the client that we prefer to suppress GA ...", "self", ".", "protocol", ".", "will", "(", "SUPPRESS_GA", ")", ".", "addCallbacks", "(", "self", ".", "will_suppress_ga", ",", "self", ".", "wont_suppress_ga", ")" ]
[ 30, 4 ]
[ 42, 98 ]
python
en
['en', 'error', 'th']
False
SuppressGA.wont_suppress_ga
(self, option)
Called when client requests to not suppress GA. Args: option (Option): Not used.
Called when client requests to not suppress GA.
def wont_suppress_ga(self, option): """ Called when client requests to not suppress GA. Args: option (Option): Not used. """ self.protocol.protocol_flags["NOGOAHEAD"] = False self.protocol.handshake_done()
[ "def", "wont_suppress_ga", "(", "self", ",", "option", ")", ":", "self", ".", "protocol", ".", "protocol_flags", "[", "\"NOGOAHEAD\"", "]", "=", "False", "self", ".", "protocol", ".", "handshake_done", "(", ")" ]
[ 44, 4 ]
[ 53, 38 ]
python
en
['en', 'error', 'th']
False
SuppressGA.will_suppress_ga
(self, option)
Client will suppress GA Args: option (Option): Not used.
Client will suppress GA
def will_suppress_ga(self, option): """ Client will suppress GA Args: option (Option): Not used. """ self.protocol.protocol_flags["NOGOAHEAD"] = True self.protocol.handshake_done()
[ "def", "will_suppress_ga", "(", "self", ",", "option", ")", ":", "self", ".", "protocol", ".", "protocol_flags", "[", "\"NOGOAHEAD\"", "]", "=", "True", "self", ".", "protocol", ".", "handshake_done", "(", ")" ]
[ 55, 4 ]
[ 64, 38 ]
python
en
['en', 'error', 'th']
False
fuse_conv_bn
(conv, bn)
During inference, the functionary of batch norm layers is turned off but only the mean and var alone channels are used, which exposes the chance to fuse it with the preceding conv layers to save computations and simplify network structures.
During inference, the functionary of batch norm layers is turned off but only the mean and var alone channels are used, which exposes the chance to fuse it with the preceding conv layers to save computations and simplify network structures.
def fuse_conv_bn(conv, bn): """During inference, the functionary of batch norm layers is turned off but only the mean and var alone channels are used, which exposes the chance to fuse it with the preceding conv layers to save computations and simplify network structures.""" conv_w = conv.weight conv_b = conv.bias if conv.bias is not None else torch.zeros_like( bn.running_mean) factor = bn.weight / torch.sqrt(bn.running_var + bn.eps) conv.weight = nn.Parameter(conv_w * factor.reshape([conv.out_channels, 1, 1, 1])) conv.bias = nn.Parameter((conv_b - bn.running_mean) * factor + bn.bias) return conv
[ "def", "fuse_conv_bn", "(", "conv", ",", "bn", ")", ":", "conv_w", "=", "conv", ".", "weight", "conv_b", "=", "conv", ".", "bias", "if", "conv", ".", "bias", "is", "not", "None", "else", "torch", ".", "zeros_like", "(", "bn", ".", "running_mean", ")", "factor", "=", "bn", ".", "weight", "/", "torch", ".", "sqrt", "(", "bn", ".", "running_var", "+", "bn", ".", "eps", ")", "conv", ".", "weight", "=", "nn", ".", "Parameter", "(", "conv_w", "*", "factor", ".", "reshape", "(", "[", "conv", ".", "out_channels", ",", "1", ",", "1", ",", "1", "]", ")", ")", "conv", ".", "bias", "=", "nn", ".", "Parameter", "(", "(", "conv_b", "-", "bn", ".", "running_mean", ")", "*", "factor", "+", "bn", ".", "bias", ")", "return", "conv" ]
[ 9, 0 ]
[ 22, 15 ]
python
en
['en', 'en', 'en']
True
Line.color
(self)
Sets the color of the line enclosing each sector. 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
Sets the color of the line enclosing each sector. 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): """ Sets the color of the line enclosing each sector. 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 ]
[ 65, 28 ]
python
en
['en', 'error', 'th']
False
Line.width
(self)
Sets the width (in px) of the line enclosing each sector. 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 line enclosing each sector. 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 line enclosing each sector. 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\"", "]" ]
[ 74, 4 ]
[ 85, 28 ]
python
en
['en', 'error', 'th']
False
Line.__init__
(self, arg=None, color=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.indicator.gauge.bar.Line` color Sets the color of the line enclosing each sector. width Sets the width (in px) of the line enclosing each sector. Returns ------- Line
Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.indicator.gauge.bar.Line` color Sets the color of the line enclosing each sector. width Sets the width (in px) of the line enclosing each sector.
def __init__(self, arg=None, color=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.indicator.gauge.bar.Line` color Sets the color of the line enclosing each sector. width Sets the width (in px) of the line enclosing each sector. 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.indicator.gauge.bar.Line constructor must be a dict or an instance of :class:`plotly.graph_objs.indicator.gauge.bar.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("color", None) _v = color if color is not None else _v if _v is not None: self["color"] = _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", ",", "color", "=", "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.indicator.gauge.bar.Line \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.indicator.gauge.bar.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", "(", "\"color\"", ",", "None", ")", "_v", "=", "color", "if", "color", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"color\"", "]", "=", "_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" ]
[ 103, 4 ]
[ 167, 34 ]
python
en
['en', 'error', 'th']
False
getImageByTag
(tag)
Check if an image with a given tag exists. No side-effects. Idempotent. Handles ImageNotFound and APIError exceptions, but only reraises APIError.
Check if an image with a given tag exists. No side-effects. Idempotent. Handles ImageNotFound and APIError exceptions, but only reraises APIError.
def getImageByTag(tag): '''Check if an image with a given tag exists. No side-effects. Idempotent. Handles ImageNotFound and APIError exceptions, but only reraises APIError. ''' require_str("tag", tag) image = None try: image = client.images.get(tag) print("Found image", tag, "...") except ImageNotFound: print("Image", tag, "does not exist ...") except APIError as exc: eprint("Unhandled error while getting image", tag) raise exc return image
[ "def", "getImageByTag", "(", "tag", ")", ":", "require_str", "(", "\"tag\"", ",", "tag", ")", "image", "=", "None", "try", ":", "image", "=", "client", ".", "images", ".", "get", "(", "tag", ")", "print", "(", "\"Found image\"", ",", "tag", ",", "\"...\"", ")", "except", "ImageNotFound", ":", "print", "(", "\"Image\"", ",", "tag", ",", "\"does not exist ...\"", ")", "except", "APIError", "as", "exc", ":", "eprint", "(", "\"Unhandled error while getting image\"", ",", "tag", ")", "raise", "exc", "return", "image" ]
[ 19, 0 ]
[ 35, 16 ]
python
en
['en', 'en', 'en']
True
getImage
(path, dockerfile, tag)
Check if an image with a given tag exists. If not, build an image from using a given dockerfile in a given path, tagging it with a given tag. No extra side effects. Handles and reraises BuildError, TypeError, and APIError exceptions.
Check if an image with a given tag exists. If not, build an image from using a given dockerfile in a given path, tagging it with a given tag. No extra side effects. Handles and reraises BuildError, TypeError, and APIError exceptions.
def getImage(path, dockerfile, tag): '''Check if an image with a given tag exists. If not, build an image from using a given dockerfile in a given path, tagging it with a given tag. No extra side effects. Handles and reraises BuildError, TypeError, and APIError exceptions. ''' image = getImageByTag(tag) if not image: # Build an Image using the dockerfile in the path try: image = client.images.build( path=path, dockerfile=dockerfile, tag=tag ) except BuildError as exc: eprint("Failed to build docker image") raise exc except TypeError as exc: eprint("You must give a path to the build environemnt.") raise exc except APIError as exc: eprint("Unhandled error while building image", tag) raise exc return image
[ "def", "getImage", "(", "path", ",", "dockerfile", ",", "tag", ")", ":", "image", "=", "getImageByTag", "(", "tag", ")", "if", "not", "image", ":", "# Build an Image using the dockerfile in the path", "try", ":", "image", "=", "client", ".", "images", ".", "build", "(", "path", "=", "path", ",", "dockerfile", "=", "dockerfile", ",", "tag", "=", "tag", ")", "except", "BuildError", "as", "exc", ":", "eprint", "(", "\"Failed to build docker image\"", ")", "raise", "exc", "except", "TypeError", "as", "exc", ":", "eprint", "(", "\"You must give a path to the build environemnt.\"", ")", "raise", "exc", "except", "APIError", "as", "exc", ":", "eprint", "(", "\"Unhandled error while building image\"", ",", "tag", ")", "raise", "exc", "return", "image" ]
[ 37, 0 ]
[ 63, 16 ]
python
en
['en', 'en', 'en']
True
runContainer
(image, **kwargs)
Run a docker container using a given image; passing keyword arguments documented to be accepted by docker's client.containers.run function No extra side effects. Handles and reraises ContainerError, ImageNotFound, and APIError exceptions.
Run a docker container using a given image; passing keyword arguments documented to be accepted by docker's client.containers.run function No extra side effects. Handles and reraises ContainerError, ImageNotFound, and APIError exceptions.
def runContainer(image, **kwargs): '''Run a docker container using a given image; passing keyword arguments documented to be accepted by docker's client.containers.run function No extra side effects. Handles and reraises ContainerError, ImageNotFound, and APIError exceptions. ''' container = None try: container = client.containers.run(image, **kwargs) if "name" in kwargs.keys(): print("Container", kwargs["name"], "is now running.") except ContainerError as exc: eprint("Failed to run container") raise exc except ImageNotFound as exc: eprint("Failed to find image to run as a docker container") raise exc except APIError as exc: eprint("Unhandled error") raise exc return container
[ "def", "runContainer", "(", "image", ",", "*", "*", "kwargs", ")", ":", "container", "=", "None", "try", ":", "container", "=", "client", ".", "containers", ".", "run", "(", "image", ",", "*", "*", "kwargs", ")", "if", "\"name\"", "in", "kwargs", ".", "keys", "(", ")", ":", "print", "(", "\"Container\"", ",", "kwargs", "[", "\"name\"", "]", ",", "\"is now running.\"", ")", "except", "ContainerError", "as", "exc", ":", "eprint", "(", "\"Failed to run container\"", ")", "raise", "exc", "except", "ImageNotFound", "as", "exc", ":", "eprint", "(", "\"Failed to find image to run as a docker container\"", ")", "raise", "exc", "except", "APIError", "as", "exc", ":", "eprint", "(", "\"Unhandled error\"", ")", "raise", "exc", "return", "container" ]
[ 65, 0 ]
[ 86, 20 ]
python
en
['en', 'en', 'en']
True
getContainer
(name_or_id)
Get the container with the given name or ID (str). No side effects. Idempotent. Returns None if the container does not exist. Otherwise, the continer is returned
Get the container with the given name or ID (str). No side effects. Idempotent. Returns None if the container does not exist. Otherwise, the continer is returned
def getContainer(name_or_id): '''Get the container with the given name or ID (str). No side effects. Idempotent. Returns None if the container does not exist. Otherwise, the continer is returned''' require_str("name_or_id", name_or_id) container = None try: container = client.containers.get(name_or_id) except NotFound as exc: # Return None when the container is not found pass except APIError as exc: eprint("Unhandled error") raise exc return container
[ "def", "getContainer", "(", "name_or_id", ")", ":", "require_str", "(", "\"name_or_id\"", ",", "name_or_id", ")", "container", "=", "None", "try", ":", "container", "=", "client", ".", "containers", ".", "get", "(", "name_or_id", ")", "except", "NotFound", "as", "exc", ":", "# Return None when the container is not found", "pass", "except", "APIError", "as", "exc", ":", "eprint", "(", "\"Unhandled error\"", ")", "raise", "exc", "return", "container" ]
[ 88, 0 ]
[ 104, 20 ]
python
en
['en', 'en', 'en']
True
containerIsRunning
(name_or_id)
Check if container with the given name or ID (str) is running. No side effects. Idempotent. Returns True if running, False if not.
Check if container with the given name or ID (str) is running. No side effects. Idempotent. Returns True if running, False if not.
def containerIsRunning(name_or_id): '''Check if container with the given name or ID (str) is running. No side effects. Idempotent. Returns True if running, False if not.''' require_str("name_or_id", name_or_id) try: container = getContainer(name_or_id) # Refer to the latest status list here: https://docs.docker.com/engine/ # api/v1.33/#operation/ContainerList if container: if container.status == 'created': return False elif container.status == 'restarting': return True elif container.status == 'running': return True elif container.status == 'removing': return False elif container.status == 'paused': return False elif container.status == 'exited': return False elif container.status == 'dead': return False else: return False except NotFound as exc: return False return False
[ "def", "containerIsRunning", "(", "name_or_id", ")", ":", "require_str", "(", "\"name_or_id\"", ",", "name_or_id", ")", "try", ":", "container", "=", "getContainer", "(", "name_or_id", ")", "# Refer to the latest status list here: https://docs.docker.com/engine/", "# api/v1.33/#operation/ContainerList", "if", "container", ":", "if", "container", ".", "status", "==", "'created'", ":", "return", "False", "elif", "container", ".", "status", "==", "'restarting'", ":", "return", "True", "elif", "container", ".", "status", "==", "'running'", ":", "return", "True", "elif", "container", ".", "status", "==", "'removing'", ":", "return", "False", "elif", "container", ".", "status", "==", "'paused'", ":", "return", "False", "elif", "container", ".", "status", "==", "'exited'", ":", "return", "False", "elif", "container", ".", "status", "==", "'dead'", ":", "return", "False", "else", ":", "return", "False", "except", "NotFound", "as", "exc", ":", "return", "False", "return", "False" ]
[ 106, 0 ]
[ 135, 16 ]
python
en
['en', 'en', 'en']
True
getContainerByTag
(tag)
Check if a container with a given tag exists. No side-effects. Idempotent. Handles NotFound and APIError exceptions, but only reraises APIError. Returns None if the container is not found. Otherwise, returns the container.
Check if a container with a given tag exists. No side-effects. Idempotent. Handles NotFound and APIError exceptions, but only reraises APIError. Returns None if the container is not found. Otherwise, returns the container.
def getContainerByTag(tag): '''Check if a container with a given tag exists. No side-effects. Idempotent. Handles NotFound and APIError exceptions, but only reraises APIError. Returns None if the container is not found. Otherwise, returns the container.''' require_str("tag", tag) container = None try: container = client.containers.get(tag) print("Found container", tag, "...") except NotFound: #print("Container", tag, "does not exist ...") pass except APIError as exc: eprint("Unhandled error while getting container", tag) raise exc return container
[ "def", "getContainerByTag", "(", "tag", ")", ":", "require_str", "(", "\"tag\"", ",", "tag", ")", "container", "=", "None", "try", ":", "container", "=", "client", ".", "containers", ".", "get", "(", "tag", ")", "print", "(", "\"Found container\"", ",", "tag", ",", "\"...\"", ")", "except", "NotFound", ":", "#print(\"Container\", tag, \"does not exist ...\")", "pass", "except", "APIError", "as", "exc", ":", "eprint", "(", "\"Unhandled error while getting container\"", ",", "tag", ")", "raise", "exc", "return", "container" ]
[ 137, 0 ]
[ 155, 20 ]
python
en
['en', 'en', 'en']
True
removeContainer
(tag)
Check if a container with a given tag exists. Kill it if it exists. No extra side effects. Handles and reraises TypeError, and APIError exceptions.
Check if a container with a given tag exists. Kill it if it exists. No extra side effects. Handles and reraises TypeError, and APIError exceptions.
def removeContainer(tag): '''Check if a container with a given tag exists. Kill it if it exists. No extra side effects. Handles and reraises TypeError, and APIError exceptions. ''' container = getContainerByTag(tag) if container: # Build an Image using the dockerfile in the path try: container.remove(force=True) #print("Removed container", tag, "...") except APIError as exc: eprint("Unhandled error while removing container", tag) raise exc
[ "def", "removeContainer", "(", "tag", ")", ":", "container", "=", "getContainerByTag", "(", "tag", ")", "if", "container", ":", "# Build an Image using the dockerfile in the path", "try", ":", "container", ".", "remove", "(", "force", "=", "True", ")", "#print(\"Removed container\", tag, \"...\")", "except", "APIError", "as", "exc", ":", "eprint", "(", "\"Unhandled error while removing container\"", ",", "tag", ")", "raise", "exc" ]
[ 157, 0 ]
[ 171, 21 ]
python
en
['en', 'en', 'en']
True
startIndyPool
(**kwargs)
Start the indy_pool docker container iff it is not already running. See <indy-sdk>/ci/indy-pool.dockerfile for details. Idempotent. Simply ensures that the indy_pool container is up and running.
Start the indy_pool docker container iff it is not already running. See <indy-sdk>/ci/indy-pool.dockerfile for details. Idempotent. Simply ensures that the indy_pool container is up and running.
def startIndyPool(**kwargs): '''Start the indy_pool docker container iff it is not already running. See <indy-sdk>/ci/indy-pool.dockerfile for details. Idempotent. Simply ensures that the indy_pool container is up and running.''' # TODO: Decide if we need a separate docker container for testing and one for # development. The indy_sdk tests setup and teardown "indy_pool" on # ports 9701-9708. Perhaps we need an "indy_dev_pool" on 9709-9716? I'm # not quite sure where all of our dependencies are on port 9701-9708. # If the test harness (mocks) are hardcoding 9701-9708, then an # indy_dev_pool on different ports will not work. print("Starting indy_pool ...") # Check if indy_pool is running if containerIsRunning("indy_pool"): print("... already running") exit(0) else: # If the container already exists and isn't running, force remove it and # readd it. This is brute force, but is sufficient and simple. container = getContainer("indy_pool") if container: container.remove(force=True) # Build and run indy_pool if it is not already running # Build the indy_pool image from the dockerfile in: # /vagrant/indy-sdk/ci/indy-pool.dockerfile # # In shell using docker cli: # cd /vagrant/indy-sdk # sudo docker build -f ci/indy-pool.dockerfile -t indy_pool . # # NOTE: https://jira.hyperledger.org/browse/IS-406 prevents indy_pool from # starting on the `rc` branch. Apply the patch in the Jira issue to # overcome this problem. try: # indy-sdk won't be in /vagrant if the indy-sdk is cloned to a directory outside # the Vagrant project. Regardless of where indy-sdk is cloned, it will be found # in /src/indy-sdk in the Vagrant VM. image = getImage(path="/src/indy-sdk", dockerfile="ci/indy-pool.dockerfile", tag="indy_pool") except TypeError as exc: image = getImage(path="/vagrant/indy-sdk", dockerfile="ci/indy-pool.dockerfile", tag="indy_pool") except: print("Failed to find indy-pool.dockerfile in /vagrant/indy-sdk or /src/indy-sdk") # Run a container using the image # # In shell using docker cli: # sudo docker run -itd -p 9701-9708:9701-9708 indy_pool # # NOTE: {'2222/tcp': 3333} is sufficient. A tuple of (address, port) if you # want to specify the host interface. container = runContainer(image, ports={ '9701/tcp': ('0.0.0.0', 9701), '9702/tcp': ('0.0.0.0', 9702), '9703/tcp': ('0.0.0.0', 9703), '9704/tcp': ('0.0.0.0', 9704), '9705/tcp': ('0.0.0.0', 9705), '9706/tcp': ('0.0.0.0', 9706), '9707/tcp': ('0.0.0.0', 9707), '9708/tcp': ('0.0.0.0', 9708) }, detach=True, name="indy_pool" ) print("...started")
[ "def", "startIndyPool", "(", "*", "*", "kwargs", ")", ":", "# TODO: Decide if we need a separate docker container for testing and one for", "# development. The indy_sdk tests setup and teardown \"indy_pool\" on", "# ports 9701-9708. Perhaps we need an \"indy_dev_pool\" on 9709-9716? I'm", "# not quite sure where all of our dependencies are on port 9701-9708.", "# If the test harness (mocks) are hardcoding 9701-9708, then an", "# indy_dev_pool on different ports will not work.", "print", "(", "\"Starting indy_pool ...\"", ")", "# Check if indy_pool is running", "if", "containerIsRunning", "(", "\"indy_pool\"", ")", ":", "print", "(", "\"... already running\"", ")", "exit", "(", "0", ")", "else", ":", "# If the container already exists and isn't running, force remove it and", "# readd it. This is brute force, but is sufficient and simple.", "container", "=", "getContainer", "(", "\"indy_pool\"", ")", "if", "container", ":", "container", ".", "remove", "(", "force", "=", "True", ")", "# Build and run indy_pool if it is not already running", "# Build the indy_pool image from the dockerfile in:", "# /vagrant/indy-sdk/ci/indy-pool.dockerfile", "# ", "# In shell using docker cli:", "# cd /vagrant/indy-sdk", "# sudo docker build -f ci/indy-pool.dockerfile -t indy_pool .", "#", "# NOTE: https://jira.hyperledger.org/browse/IS-406 prevents indy_pool from", "# starting on the `rc` branch. Apply the patch in the Jira issue to", "# overcome this problem.", "try", ":", "# indy-sdk won't be in /vagrant if the indy-sdk is cloned to a directory outside", "# the Vagrant project. Regardless of where indy-sdk is cloned, it will be found", "# in /src/indy-sdk in the Vagrant VM.", "image", "=", "getImage", "(", "path", "=", "\"/src/indy-sdk\"", ",", "dockerfile", "=", "\"ci/indy-pool.dockerfile\"", ",", "tag", "=", "\"indy_pool\"", ")", "except", "TypeError", "as", "exc", ":", "image", "=", "getImage", "(", "path", "=", "\"/vagrant/indy-sdk\"", ",", "dockerfile", "=", "\"ci/indy-pool.dockerfile\"", ",", "tag", "=", "\"indy_pool\"", ")", "except", ":", "print", "(", "\"Failed to find indy-pool.dockerfile in /vagrant/indy-sdk or /src/indy-sdk\"", ")", "# Run a container using the image", "#", "# In shell using docker cli:", "# sudo docker run -itd -p 9701-9708:9701-9708 indy_pool", "#", "# NOTE: {'2222/tcp': 3333} is sufficient. A tuple of (address, port) if you", "# want to specify the host interface. ", "container", "=", "runContainer", "(", "image", ",", "ports", "=", "{", "'9701/tcp'", ":", "(", "'0.0.0.0'", ",", "9701", ")", ",", "'9702/tcp'", ":", "(", "'0.0.0.0'", ",", "9702", ")", ",", "'9703/tcp'", ":", "(", "'0.0.0.0'", ",", "9703", ")", ",", "'9704/tcp'", ":", "(", "'0.0.0.0'", ",", "9704", ")", ",", "'9705/tcp'", ":", "(", "'0.0.0.0'", ",", "9705", ")", ",", "'9706/tcp'", ":", "(", "'0.0.0.0'", ",", "9706", ")", ",", "'9707/tcp'", ":", "(", "'0.0.0.0'", ",", "9707", ")", ",", "'9708/tcp'", ":", "(", "'0.0.0.0'", ",", "9708", ")", "}", ",", "detach", "=", "True", ",", "name", "=", "\"indy_pool\"", ")", "print", "(", "\"...started\"", ")" ]
[ 173, 0 ]
[ 241, 23 ]
python
en
['en', 'en', 'en']
True
stopIndyPool
(**kwargs)
Stop (docker rm) the indy_pool docker container stopped/removed. Idempotent. Simply ensures that the indy_pool container is stopped/removed.
Stop (docker rm) the indy_pool docker container stopped/removed. Idempotent. Simply ensures that the indy_pool container is stopped/removed.
def stopIndyPool(**kwargs): '''Stop (docker rm) the indy_pool docker container stopped/removed. Idempotent. Simply ensures that the indy_pool container is stopped/removed. ''' print("Stopping...") try: removeContainer("indy_pool") print("...stopped") except Exception as exc: eprint("...Failed to stop") raise exc
[ "def", "stopIndyPool", "(", "*", "*", "kwargs", ")", ":", "print", "(", "\"Stopping...\"", ")", "try", ":", "removeContainer", "(", "\"indy_pool\"", ")", "print", "(", "\"...stopped\"", ")", "except", "Exception", "as", "exc", ":", "eprint", "(", "\"...Failed to stop\"", ")", "raise", "exc" ]
[ 243, 0 ]
[ 253, 15 ]
python
en
['en', 'en', 'en']
True
statusIndyPool
(**kwargs)
Return the status of the indy_pool docker container. Idempotent.
Return the status of the indy_pool docker container. Idempotent.
def statusIndyPool(**kwargs): '''Return the status of the indy_pool docker container. Idempotent.''' if containerIsRunning("indy_pool"): print("running") else: print("not running")
[ "def", "statusIndyPool", "(", "*", "*", "kwargs", ")", ":", "if", "containerIsRunning", "(", "\"indy_pool\"", ")", ":", "print", "(", "\"running\"", ")", "else", ":", "print", "(", "\"not running\"", ")" ]
[ 255, 0 ]
[ 260, 28 ]
python
en
['en', 'en', 'en']
True
restartIndyPool
(**kwargs)
Restart the indy_pool docker container. Idempotent. Ensures that the indy_pool container is a new running instance.
Restart the indy_pool docker container. Idempotent. Ensures that the indy_pool container is a new running instance.
def restartIndyPool(**kwargs): '''Restart the indy_pool docker container. Idempotent. Ensures that the indy_pool container is a new running instance.''' print("Restarting...") try: stopIndyPool() startIndyPool() print("...restarted") except Exception as exc: eprint("...failed to restart") raise exc
[ "def", "restartIndyPool", "(", "*", "*", "kwargs", ")", ":", "print", "(", "\"Restarting...\"", ")", "try", ":", "stopIndyPool", "(", ")", "startIndyPool", "(", ")", "print", "(", "\"...restarted\"", ")", "except", "Exception", "as", "exc", ":", "eprint", "(", "\"...failed to restart\"", ")", "raise", "exc" ]
[ 262, 0 ]
[ 272, 15 ]
python
en
['en', 'en', 'en']
True
KITTI2Waymo.get_file_names
(self)
Get file names of waymo raw data.
Get file names of waymo raw data.
def get_file_names(self): """Get file names of waymo raw data.""" self.waymo_tfrecord_pathnames = sorted( glob(join(self.waymo_tfrecords_dir, '*.tfrecord'))) print(len(self.waymo_tfrecord_pathnames), 'tfrecords found.')
[ "def", "get_file_names", "(", "self", ")", ":", "self", ".", "waymo_tfrecord_pathnames", "=", "sorted", "(", "glob", "(", "join", "(", "self", ".", "waymo_tfrecords_dir", ",", "'*.tfrecord'", ")", ")", ")", "print", "(", "len", "(", "self", ".", "waymo_tfrecord_pathnames", ")", ",", "'tfrecords found.'", ")" ]
[ 76, 4 ]
[ 80, 69 ]
python
en
['en', 'jv', 'en']
True
KITTI2Waymo.create_folder
(self)
Create folder for data conversion.
Create folder for data conversion.
def create_folder(self): """Create folder for data conversion.""" mmcv.mkdir_or_exist(self.waymo_results_save_dir)
[ "def", "create_folder", "(", "self", ")", ":", "mmcv", ".", "mkdir_or_exist", "(", "self", ".", "waymo_results_save_dir", ")" ]
[ 82, 4 ]
[ 84, 56 ]
python
da
['da', 'it', 'en']
False
KITTI2Waymo.parse_objects
(self, kitti_result, T_k2w, context_name, frame_timestamp_micros)
Parse one prediction with several instances in kitti format and convert them to `Object` proto. Args: kitti_result (dict): Predictions in kitti format. - name (np.ndarray): Class labels of predictions. - dimensions (np.ndarray): Height, width, length of boxes. - location (np.ndarray): Bottom center of boxes (x, y, z). - rotation_y (np.ndarray): Orientation of boxes. - score (np.ndarray): Scores of predictions. T_k2w (np.ndarray): Transformation matrix from kitti to waymo. context_name (str): Context name of the frame. frame_timestamp_micros (int): Frame timestamp. Returns: :obj:`Object`: Predictions in waymo dataset Object proto.
Parse one prediction with several instances in kitti format and convert them to `Object` proto.
def parse_objects(self, kitti_result, T_k2w, context_name, frame_timestamp_micros): """Parse one prediction with several instances in kitti format and convert them to `Object` proto. Args: kitti_result (dict): Predictions in kitti format. - name (np.ndarray): Class labels of predictions. - dimensions (np.ndarray): Height, width, length of boxes. - location (np.ndarray): Bottom center of boxes (x, y, z). - rotation_y (np.ndarray): Orientation of boxes. - score (np.ndarray): Scores of predictions. T_k2w (np.ndarray): Transformation matrix from kitti to waymo. context_name (str): Context name of the frame. frame_timestamp_micros (int): Frame timestamp. Returns: :obj:`Object`: Predictions in waymo dataset Object proto. """ def parse_one_object(instance_idx): """Parse one instance in kitti format and convert them to `Object` proto. Args: instance_idx (int): Index of the instance to be converted. Returns: :obj:`Object`: Predicted instance in waymo dataset \ Object proto. """ cls = kitti_result['name'][instance_idx] length = round(kitti_result['dimensions'][instance_idx, 0], 4) height = round(kitti_result['dimensions'][instance_idx, 1], 4) width = round(kitti_result['dimensions'][instance_idx, 2], 4) x = round(kitti_result['location'][instance_idx, 0], 4) y = round(kitti_result['location'][instance_idx, 1], 4) z = round(kitti_result['location'][instance_idx, 2], 4) rotation_y = round(kitti_result['rotation_y'][instance_idx], 4) score = round(kitti_result['score'][instance_idx], 4) # y: downwards; move box origin from bottom center (kitti) to # true center (waymo) y -= height / 2 # frame transformation: kitti -> waymo x, y, z = self.transform(T_k2w, x, y, z) # different conventions heading = -(rotation_y + np.pi / 2) while heading < -np.pi: heading += 2 * np.pi while heading > np.pi: heading -= 2 * np.pi box = label_pb2.Label.Box() box.center_x = x box.center_y = y box.center_z = z box.length = length box.width = width box.height = height box.heading = heading o = metrics_pb2.Object() o.object.box.CopyFrom(box) o.object.type = self.k2w_cls_map[cls] o.score = score o.context_name = context_name o.frame_timestamp_micros = frame_timestamp_micros return o objects = metrics_pb2.Objects() for instance_idx in range(len(kitti_result['name'])): o = parse_one_object(instance_idx) objects.objects.append(o) return objects
[ "def", "parse_objects", "(", "self", ",", "kitti_result", ",", "T_k2w", ",", "context_name", ",", "frame_timestamp_micros", ")", ":", "def", "parse_one_object", "(", "instance_idx", ")", ":", "\"\"\"Parse one instance in kitti format and convert them to `Object`\n proto.\n\n Args:\n instance_idx (int): Index of the instance to be converted.\n\n Returns:\n :obj:`Object`: Predicted instance in waymo dataset \\\n Object proto.\n \"\"\"", "cls", "=", "kitti_result", "[", "'name'", "]", "[", "instance_idx", "]", "length", "=", "round", "(", "kitti_result", "[", "'dimensions'", "]", "[", "instance_idx", ",", "0", "]", ",", "4", ")", "height", "=", "round", "(", "kitti_result", "[", "'dimensions'", "]", "[", "instance_idx", ",", "1", "]", ",", "4", ")", "width", "=", "round", "(", "kitti_result", "[", "'dimensions'", "]", "[", "instance_idx", ",", "2", "]", ",", "4", ")", "x", "=", "round", "(", "kitti_result", "[", "'location'", "]", "[", "instance_idx", ",", "0", "]", ",", "4", ")", "y", "=", "round", "(", "kitti_result", "[", "'location'", "]", "[", "instance_idx", ",", "1", "]", ",", "4", ")", "z", "=", "round", "(", "kitti_result", "[", "'location'", "]", "[", "instance_idx", ",", "2", "]", ",", "4", ")", "rotation_y", "=", "round", "(", "kitti_result", "[", "'rotation_y'", "]", "[", "instance_idx", "]", ",", "4", ")", "score", "=", "round", "(", "kitti_result", "[", "'score'", "]", "[", "instance_idx", "]", ",", "4", ")", "# y: downwards; move box origin from bottom center (kitti) to", "# true center (waymo)", "y", "-=", "height", "/", "2", "# frame transformation: kitti -> waymo", "x", ",", "y", ",", "z", "=", "self", ".", "transform", "(", "T_k2w", ",", "x", ",", "y", ",", "z", ")", "# different conventions", "heading", "=", "-", "(", "rotation_y", "+", "np", ".", "pi", "/", "2", ")", "while", "heading", "<", "-", "np", ".", "pi", ":", "heading", "+=", "2", "*", "np", ".", "pi", "while", "heading", ">", "np", ".", "pi", ":", "heading", "-=", "2", "*", "np", ".", "pi", "box", "=", "label_pb2", ".", "Label", ".", "Box", "(", ")", "box", ".", "center_x", "=", "x", "box", ".", "center_y", "=", "y", "box", ".", "center_z", "=", "z", "box", ".", "length", "=", "length", "box", ".", "width", "=", "width", "box", ".", "height", "=", "height", "box", ".", "heading", "=", "heading", "o", "=", "metrics_pb2", ".", "Object", "(", ")", "o", ".", "object", ".", "box", ".", "CopyFrom", "(", "box", ")", "o", ".", "object", ".", "type", "=", "self", ".", "k2w_cls_map", "[", "cls", "]", "o", ".", "score", "=", "score", "o", ".", "context_name", "=", "context_name", "o", ".", "frame_timestamp_micros", "=", "frame_timestamp_micros", "return", "o", "objects", "=", "metrics_pb2", ".", "Objects", "(", ")", "for", "instance_idx", "in", "range", "(", "len", "(", "kitti_result", "[", "'name'", "]", ")", ")", ":", "o", "=", "parse_one_object", "(", "instance_idx", ")", "objects", ".", "objects", ".", "append", "(", "o", ")", "return", "objects" ]
[ 86, 4 ]
[ 166, 22 ]
python
en
['en', 'en', 'en']
True
KITTI2Waymo.convert_one
(self, file_idx)
Convert action for single file. Args: file_idx (int): Index of the file to be converted.
Convert action for single file.
def convert_one(self, file_idx): """Convert action for single file. Args: file_idx (int): Index of the file to be converted. """ file_pathname = self.waymo_tfrecord_pathnames[file_idx] file_data = tf.data.TFRecordDataset(file_pathname, compression_type='') for frame_num, frame_data in enumerate(file_data): frame = open_dataset.Frame() frame.ParseFromString(bytearray(frame_data.numpy())) filename = f'{self.prefix}{file_idx:03d}{frame_num:03d}' for camera in frame.context.camera_calibrations: # FRONT = 1, see dataset.proto for details if camera.name == 1: T_front_cam_to_vehicle = np.array( camera.extrinsic.transform).reshape(4, 4) T_k2w = T_front_cam_to_vehicle @ self.T_ref_to_front_cam context_name = frame.context.name frame_timestamp_micros = frame.timestamp_micros if filename in self.name2idx: kitti_result = \ self.kitti_result_files[self.name2idx[filename]] objects = self.parse_objects(kitti_result, T_k2w, context_name, frame_timestamp_micros) else: print(filename, 'not found.') objects = metrics_pb2.Objects() with open( join(self.waymo_results_save_dir, f'{filename}.bin'), 'wb') as f: f.write(objects.SerializeToString())
[ "def", "convert_one", "(", "self", ",", "file_idx", ")", ":", "file_pathname", "=", "self", ".", "waymo_tfrecord_pathnames", "[", "file_idx", "]", "file_data", "=", "tf", ".", "data", ".", "TFRecordDataset", "(", "file_pathname", ",", "compression_type", "=", "''", ")", "for", "frame_num", ",", "frame_data", "in", "enumerate", "(", "file_data", ")", ":", "frame", "=", "open_dataset", ".", "Frame", "(", ")", "frame", ".", "ParseFromString", "(", "bytearray", "(", "frame_data", ".", "numpy", "(", ")", ")", ")", "filename", "=", "f'{self.prefix}{file_idx:03d}{frame_num:03d}'", "for", "camera", "in", "frame", ".", "context", ".", "camera_calibrations", ":", "# FRONT = 1, see dataset.proto for details", "if", "camera", ".", "name", "==", "1", ":", "T_front_cam_to_vehicle", "=", "np", ".", "array", "(", "camera", ".", "extrinsic", ".", "transform", ")", ".", "reshape", "(", "4", ",", "4", ")", "T_k2w", "=", "T_front_cam_to_vehicle", "@", "self", ".", "T_ref_to_front_cam", "context_name", "=", "frame", ".", "context", ".", "name", "frame_timestamp_micros", "=", "frame", ".", "timestamp_micros", "if", "filename", "in", "self", ".", "name2idx", ":", "kitti_result", "=", "self", ".", "kitti_result_files", "[", "self", ".", "name2idx", "[", "filename", "]", "]", "objects", "=", "self", ".", "parse_objects", "(", "kitti_result", ",", "T_k2w", ",", "context_name", ",", "frame_timestamp_micros", ")", "else", ":", "print", "(", "filename", ",", "'not found.'", ")", "objects", "=", "metrics_pb2", ".", "Objects", "(", ")", "with", "open", "(", "join", "(", "self", ".", "waymo_results_save_dir", ",", "f'{filename}.bin'", ")", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "objects", ".", "SerializeToString", "(", ")", ")" ]
[ 168, 4 ]
[ 206, 52 ]
python
en
['en', 'en', 'en']
True
KITTI2Waymo.convert
(self)
Convert action.
Convert action.
def convert(self): """Convert action.""" print('Start converting ...') mmcv.track_parallel_progress(self.convert_one, range(len(self)), self.workers) print('\nFinished ...') # combine all files into one .bin pathnames = sorted(glob(join(self.waymo_results_save_dir, '*.bin'))) combined = self.combine(pathnames) with open(self.waymo_results_final_path, 'wb') as f: f.write(combined.SerializeToString())
[ "def", "convert", "(", "self", ")", ":", "print", "(", "'Start converting ...'", ")", "mmcv", ".", "track_parallel_progress", "(", "self", ".", "convert_one", ",", "range", "(", "len", "(", "self", ")", ")", ",", "self", ".", "workers", ")", "print", "(", "'\\nFinished ...'", ")", "# combine all files into one .bin", "pathnames", "=", "sorted", "(", "glob", "(", "join", "(", "self", ".", "waymo_results_save_dir", ",", "'*.bin'", ")", ")", ")", "combined", "=", "self", ".", "combine", "(", "pathnames", ")", "with", "open", "(", "self", ".", "waymo_results_final_path", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "combined", ".", "SerializeToString", "(", ")", ")" ]
[ 208, 4 ]
[ 220, 49 ]
python
en
['en', 'lb', 'en']
False
KITTI2Waymo.__len__
(self)
Length of the filename list.
Length of the filename list.
def __len__(self): """Length of the filename list.""" return len(self.waymo_tfrecord_pathnames)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "waymo_tfrecord_pathnames", ")" ]
[ 222, 4 ]
[ 224, 49 ]
python
en
['en', 'en', 'en']
True
KITTI2Waymo.transform
(self, T, x, y, z)
Transform the coordinates with matrix T. Args: T (np.ndarray): Transformation matrix. x(float): Coordinate in x axis. y(float): Coordinate in y axis. z(float): Coordinate in z axis. Returns: list: Coordinates after transformation.
Transform the coordinates with matrix T.
def transform(self, T, x, y, z): """Transform the coordinates with matrix T. Args: T (np.ndarray): Transformation matrix. x(float): Coordinate in x axis. y(float): Coordinate in y axis. z(float): Coordinate in z axis. Returns: list: Coordinates after transformation. """ pt_bef = np.array([x, y, z, 1.0]).reshape(4, 1) pt_aft = np.matmul(T, pt_bef) return pt_aft[:3].flatten().tolist()
[ "def", "transform", "(", "self", ",", "T", ",", "x", ",", "y", ",", "z", ")", ":", "pt_bef", "=", "np", ".", "array", "(", "[", "x", ",", "y", ",", "z", ",", "1.0", "]", ")", ".", "reshape", "(", "4", ",", "1", ")", "pt_aft", "=", "np", ".", "matmul", "(", "T", ",", "pt_bef", ")", "return", "pt_aft", "[", ":", "3", "]", ".", "flatten", "(", ")", ".", "tolist", "(", ")" ]
[ 226, 4 ]
[ 240, 44 ]
python
en
['en', 'ca', 'en']
True
KITTI2Waymo.combine
(self, pathnames)
Combine predictions in waymo format for each sample together. Args: pathnames (str): Paths to save predictions. Returns: :obj:`Objects`: Combined predictions in Objects proto.
Combine predictions in waymo format for each sample together.
def combine(self, pathnames): """Combine predictions in waymo format for each sample together. Args: pathnames (str): Paths to save predictions. Returns: :obj:`Objects`: Combined predictions in Objects proto. """ combined = metrics_pb2.Objects() for pathname in pathnames: objects = metrics_pb2.Objects() with open(pathname, 'rb') as f: objects.ParseFromString(f.read()) for o in objects.objects: combined.objects.append(o) return combined
[ "def", "combine", "(", "self", ",", "pathnames", ")", ":", "combined", "=", "metrics_pb2", ".", "Objects", "(", ")", "for", "pathname", "in", "pathnames", ":", "objects", "=", "metrics_pb2", ".", "Objects", "(", ")", "with", "open", "(", "pathname", ",", "'rb'", ")", "as", "f", ":", "objects", ".", "ParseFromString", "(", "f", ".", "read", "(", ")", ")", "for", "o", "in", "objects", ".", "objects", ":", "combined", ".", "objects", ".", "append", "(", "o", ")", "return", "combined" ]
[ 242, 4 ]
[ 260, 23 ]
python
en
['en', 'en', 'en']
True
getenv
()
Get current environment and add PYTHONPATH. Returns: env (dict): Environment global dict.
Get current environment and add PYTHONPATH.
def getenv(): """ Get current environment and add PYTHONPATH. Returns: env (dict): Environment global dict. """ sep = ";" if _is_windows() else ":" env = os.environ.copy() env['PYTHONPATH'] = sep.join(sys.path) return env
[ "def", "getenv", "(", ")", ":", "sep", "=", "\";\"", "if", "_is_windows", "(", ")", "else", "\":\"", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "env", "[", "'PYTHONPATH'", "]", "=", "sep", ".", "join", "(", "sys", ".", "path", ")", "return", "env" ]
[ 19, 0 ]
[ 30, 14 ]
python
en
['en', 'error', 'th']
False
AMPServerFactory.logPrefix
(self)
How this is named in logs
How this is named in logs
def logPrefix(self): "How this is named in logs" return "AMP"
[ "def", "logPrefix", "(", "self", ")", ":", "return", "\"AMP\"" ]
[ 42, 4 ]
[ 44, 20 ]
python
en
['en', 'en', 'en']
True
AMPServerFactory.__init__
(self, portal)
Initialize the factory. This is called as the Portal service starts. Args: portal (Portal): The Evennia Portal service instance. protocol (Protocol): The protocol the factory creates instances of.
Initialize the factory. This is called as the Portal service starts.
def __init__(self, portal): """ Initialize the factory. This is called as the Portal service starts. Args: portal (Portal): The Evennia Portal service instance. protocol (Protocol): The protocol the factory creates instances of. """ self.portal = portal self.protocol = AMPServerProtocol self.broadcasts = [] self.server_connection = None self.launcher_connection = None self.disconnect_callbacks = {} self.server_connect_callbacks = []
[ "def", "__init__", "(", "self", ",", "portal", ")", ":", "self", ".", "portal", "=", "portal", "self", ".", "protocol", "=", "AMPServerProtocol", "self", ".", "broadcasts", "=", "[", "]", "self", ".", "server_connection", "=", "None", "self", ".", "launcher_connection", "=", "None", "self", ".", "disconnect_callbacks", "=", "{", "}", "self", ".", "server_connect_callbacks", "=", "[", "]" ]
[ 46, 4 ]
[ 62, 42 ]
python
en
['en', 'error', 'th']
False
AMPServerFactory.buildProtocol
(self, addr)
Start a new connection, and store it on the service object. Args: addr (str): Connection address. Not used. Returns: protocol (Protocol): The created protocol.
Start a new connection, and store it on the service object.
def buildProtocol(self, addr): """ Start a new connection, and store it on the service object. Args: addr (str): Connection address. Not used. Returns: protocol (Protocol): The created protocol. """ self.portal.amp_protocol = AMPServerProtocol() self.portal.amp_protocol.factory = self return self.portal.amp_protocol
[ "def", "buildProtocol", "(", "self", ",", "addr", ")", ":", "self", ".", "portal", ".", "amp_protocol", "=", "AMPServerProtocol", "(", ")", "self", ".", "portal", ".", "amp_protocol", ".", "factory", "=", "self", "return", "self", ".", "portal", ".", "amp_protocol" ]
[ 64, 4 ]
[ 77, 39 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.connectionLost
(self, reason)
Set up a simple callback mechanism to let the amp-server wait for a connection to close.
Set up a simple callback mechanism to let the amp-server wait for a connection to close.
def connectionLost(self, reason): """ Set up a simple callback mechanism to let the amp-server wait for a connection to close. """ # wipe broadcast and data memory super(AMPServerProtocol, self).connectionLost(reason) if self.factory.server_connection == self: self.factory.server_connection = None self.factory.portal.server_info_dict = {} if self.factory.launcher_connection == self: self.factory.launcher_connection = None callback, args, kwargs = self.factory.disconnect_callbacks.pop(self, (None, None, None)) if callback: try: callback(*args, **kwargs) except Exception: logger.log_trace()
[ "def", "connectionLost", "(", "self", ",", "reason", ")", ":", "# wipe broadcast and data memory", "super", "(", "AMPServerProtocol", ",", "self", ")", ".", "connectionLost", "(", "reason", ")", "if", "self", ".", "factory", ".", "server_connection", "==", "self", ":", "self", ".", "factory", ".", "server_connection", "=", "None", "self", ".", "factory", ".", "portal", ".", "server_info_dict", "=", "{", "}", "if", "self", ".", "factory", ".", "launcher_connection", "==", "self", ":", "self", ".", "factory", ".", "launcher_connection", "=", "None", "callback", ",", "args", ",", "kwargs", "=", "self", ".", "factory", ".", "disconnect_callbacks", ".", "pop", "(", "self", ",", "(", "None", ",", "None", ",", "None", ")", ")", "if", "callback", ":", "try", ":", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "logger", ".", "log_trace", "(", ")" ]
[ 85, 4 ]
[ 103, 34 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.get_status
(self)
Return status for the Evennia infrastructure. Returns: status (tuple): The portal/server status and pids (portal_live, server_live, portal_PID, server_PID).
Return status for the Evennia infrastructure.
def get_status(self): """ Return status for the Evennia infrastructure. Returns: status (tuple): The portal/server status and pids (portal_live, server_live, portal_PID, server_PID). """ server_connected = bool(self.factory.server_connection and self.factory.server_connection.transport.connected) portal_info_dict = self.factory.portal.get_info_dict() server_info_dict = self.factory.portal.server_info_dict server_pid = self.factory.portal.server_process_id portal_pid = os.getpid() return (True, server_connected, portal_pid, server_pid, portal_info_dict, server_info_dict)
[ "def", "get_status", "(", "self", ")", ":", "server_connected", "=", "bool", "(", "self", ".", "factory", ".", "server_connection", "and", "self", ".", "factory", ".", "server_connection", ".", "transport", ".", "connected", ")", "portal_info_dict", "=", "self", ".", "factory", ".", "portal", ".", "get_info_dict", "(", ")", "server_info_dict", "=", "self", ".", "factory", ".", "portal", ".", "server_info_dict", "server_pid", "=", "self", ".", "factory", ".", "portal", ".", "server_process_id", "portal_pid", "=", "os", ".", "getpid", "(", ")", "return", "(", "True", ",", "server_connected", ",", "portal_pid", ",", "server_pid", ",", "portal_info_dict", ",", "server_info_dict", ")" ]
[ 105, 4 ]
[ 120, 99 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.data_to_server
(self, command, sessid, **kwargs)
Send data across the wire to the Server. Args: command (AMP Command): A protocol send command. sessid (int): A unique Session id. Returns: deferred (deferred or None): A deferred with an errback. Notes: Data will be sent across the wire pickled as a tuple (sessid, kwargs).
Send data across the wire to the Server.
def data_to_server(self, command, sessid, **kwargs): """ Send data across the wire to the Server. Args: command (AMP Command): A protocol send command. sessid (int): A unique Session id. Returns: deferred (deferred or None): A deferred with an errback. Notes: Data will be sent across the wire pickled as a tuple (sessid, kwargs). """ if self.factory.server_connection: return self.factory.server_connection.callRemote( command, packed_data=amp.dumps((sessid, kwargs))).addErrback( self.errback, command.key) else: # if no server connection is available, broadcast return self.broadcast(command, sessid, packed_data=amp.dumps((sessid, kwargs)))
[ "def", "data_to_server", "(", "self", ",", "command", ",", "sessid", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "factory", ".", "server_connection", ":", "return", "self", ".", "factory", ".", "server_connection", ".", "callRemote", "(", "command", ",", "packed_data", "=", "amp", ".", "dumps", "(", "(", "sessid", ",", "kwargs", ")", ")", ")", ".", "addErrback", "(", "self", ".", "errback", ",", "command", ".", "key", ")", "else", ":", "# if no server connection is available, broadcast", "return", "self", ".", "broadcast", "(", "command", ",", "sessid", ",", "packed_data", "=", "amp", ".", "dumps", "(", "(", "sessid", ",", "kwargs", ")", ")", ")" ]
[ 122, 4 ]
[ 144, 91 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.start_server
(self, server_twistd_cmd)
(Re-)Launch the Evennia server. Args: server_twisted_cmd (list): The server start instruction to pass to POpen to start the server.
(Re-)Launch the Evennia server.
def start_server(self, server_twistd_cmd): """ (Re-)Launch the Evennia server. Args: server_twisted_cmd (list): The server start instruction to pass to POpen to start the server. """ # start the Server process = None with open(settings.SERVER_LOG_FILE, 'a') as logfile: # we link stdout to a file in order to catch # eventual errors happening before the Server has # opened its logger. try: if _is_windows(): # Windows requires special care create_no_window = 0x08000000 process = Popen(server_twistd_cmd, env=getenv(), bufsize=-1, stdout=logfile, stderr=STDOUT, creationflags=create_no_window) else: process = Popen(server_twistd_cmd, env=getenv(), bufsize=-1, stdout=logfile, stderr=STDOUT) except Exception: logger.log_trace() self.factory.portal.server_twistd_cmd = server_twistd_cmd logfile.flush() if process and not _is_windows(): # avoid zombie-process on Unix/BSD process.wait() return
[ "def", "start_server", "(", "self", ",", "server_twistd_cmd", ")", ":", "# start the Server", "process", "=", "None", "with", "open", "(", "settings", ".", "SERVER_LOG_FILE", ",", "'a'", ")", "as", "logfile", ":", "# we link stdout to a file in order to catch", "# eventual errors happening before the Server has", "# opened its logger.", "try", ":", "if", "_is_windows", "(", ")", ":", "# Windows requires special care", "create_no_window", "=", "0x08000000", "process", "=", "Popen", "(", "server_twistd_cmd", ",", "env", "=", "getenv", "(", ")", ",", "bufsize", "=", "-", "1", ",", "stdout", "=", "logfile", ",", "stderr", "=", "STDOUT", ",", "creationflags", "=", "create_no_window", ")", "else", ":", "process", "=", "Popen", "(", "server_twistd_cmd", ",", "env", "=", "getenv", "(", ")", ",", "bufsize", "=", "-", "1", ",", "stdout", "=", "logfile", ",", "stderr", "=", "STDOUT", ")", "except", "Exception", ":", "logger", ".", "log_trace", "(", ")", "self", ".", "factory", ".", "portal", ".", "server_twistd_cmd", "=", "server_twistd_cmd", "logfile", ".", "flush", "(", ")", "if", "process", "and", "not", "_is_windows", "(", ")", ":", "# avoid zombie-process on Unix/BSD", "process", ".", "wait", "(", ")", "return" ]
[ 146, 4 ]
[ 180, 14 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.wait_for_disconnect
(self, callback, *args, **kwargs)
Add a callback for when this connection is lost. Args: callback (callable): Will be called with *args, **kwargs once this protocol is disconnected.
Add a callback for when this connection is lost.
def wait_for_disconnect(self, callback, *args, **kwargs): """ Add a callback for when this connection is lost. Args: callback (callable): Will be called with *args, **kwargs once this protocol is disconnected. """ self.factory.disconnect_callbacks[self] = (callback, args, kwargs)
[ "def", "wait_for_disconnect", "(", "self", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "factory", ".", "disconnect_callbacks", "[", "self", "]", "=", "(", "callback", ",", "args", ",", "kwargs", ")" ]
[ 182, 4 ]
[ 191, 74 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.wait_for_server_connect
(self, callback, *args, **kwargs)
Add a callback for when the Server is sure to have connected. Args: callback (callable): Will be called with *args, **kwargs once the Server handshake with Portal is complete.
Add a callback for when the Server is sure to have connected.
def wait_for_server_connect(self, callback, *args, **kwargs): """ Add a callback for when the Server is sure to have connected. Args: callback (callable): Will be called with *args, **kwargs once the Server handshake with Portal is complete. """ self.factory.server_connect_callbacks.append((callback, args, kwargs))
[ "def", "wait_for_server_connect", "(", "self", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "factory", ".", "server_connect_callbacks", ".", "append", "(", "(", "callback", ",", "args", ",", "kwargs", ")", ")" ]
[ 193, 4 ]
[ 202, 78 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.stop_server
(self, mode='shutdown')
Shut down server in one or more modes. Args: mode (str): One of 'shutdown', 'reload' or 'reset'.
Shut down server in one or more modes.
def stop_server(self, mode='shutdown'): """ Shut down server in one or more modes. Args: mode (str): One of 'shutdown', 'reload' or 'reset'. """ if mode == 'reload': self.send_AdminPortal2Server(amp.DUMMYSESSION, operation=amp.SRELOAD) elif mode == 'reset': self.send_AdminPortal2Server(amp.DUMMYSESSION, operation=amp.SRESET) elif mode == 'shutdown': self.send_AdminPortal2Server(amp.DUMMYSESSION, operation=amp.SSHUTD) self.factory.portal.server_restart_mode = mode
[ "def", "stop_server", "(", "self", ",", "mode", "=", "'shutdown'", ")", ":", "if", "mode", "==", "'reload'", ":", "self", ".", "send_AdminPortal2Server", "(", "amp", ".", "DUMMYSESSION", ",", "operation", "=", "amp", ".", "SRELOAD", ")", "elif", "mode", "==", "'reset'", ":", "self", ".", "send_AdminPortal2Server", "(", "amp", ".", "DUMMYSESSION", ",", "operation", "=", "amp", ".", "SRESET", ")", "elif", "mode", "==", "'shutdown'", ":", "self", ".", "send_AdminPortal2Server", "(", "amp", ".", "DUMMYSESSION", ",", "operation", "=", "amp", ".", "SSHUTD", ")", "self", ".", "factory", ".", "portal", ".", "server_restart_mode", "=", "mode" ]
[ 204, 4 ]
[ 218, 54 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.send_Status2Launcher
(self)
Send a status stanza to the launcher.
Send a status stanza to the launcher.
def send_Status2Launcher(self): """ Send a status stanza to the launcher. """ if self.factory.launcher_connection: self.factory.launcher_connection.callRemote( amp.MsgStatus, status=amp.dumps(self.get_status())).addErrback( self.errback, amp.MsgStatus.key)
[ "def", "send_Status2Launcher", "(", "self", ")", ":", "if", "self", ".", "factory", ".", "launcher_connection", ":", "self", ".", "factory", ".", "launcher_connection", ".", "callRemote", "(", "amp", ".", "MsgStatus", ",", "status", "=", "amp", ".", "dumps", "(", "self", ".", "get_status", "(", ")", ")", ")", ".", "addErrback", "(", "self", ".", "errback", ",", "amp", ".", "MsgStatus", ".", "key", ")" ]
[ 222, 4 ]
[ 231, 60 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.send_MsgPortal2Server
(self, session, **kwargs)
Access method called by the Portal and executed on the Portal. Args: session (session): Session kwargs (any, optional): Optional data. Returns: deferred (Deferred): Asynchronous return.
Access method called by the Portal and executed on the Portal.
def send_MsgPortal2Server(self, session, **kwargs): """ Access method called by the Portal and executed on the Portal. Args: session (session): Session kwargs (any, optional): Optional data. Returns: deferred (Deferred): Asynchronous return. """ return self.data_to_server(amp.MsgPortal2Server, session.sessid, **kwargs)
[ "def", "send_MsgPortal2Server", "(", "self", ",", "session", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "data_to_server", "(", "amp", ".", "MsgPortal2Server", ",", "session", ".", "sessid", ",", "*", "*", "kwargs", ")" ]
[ 233, 4 ]
[ 245, 82 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.send_AdminPortal2Server
(self, session, operation="", **kwargs)
Send Admin instructions from the Portal to the Server. Executed on the Portal. Args: session (Session): Session. operation (char, optional): Identifier for the server operation, as defined by the global variables in `evennia/server/amp.py`. data (str or dict, optional): Data used in the administrative operation.
Send Admin instructions from the Portal to the Server. Executed on the Portal.
def send_AdminPortal2Server(self, session, operation="", **kwargs): """ Send Admin instructions from the Portal to the Server. Executed on the Portal. Args: session (Session): Session. operation (char, optional): Identifier for the server operation, as defined by the global variables in `evennia/server/amp.py`. data (str or dict, optional): Data used in the administrative operation. """ return self.data_to_server(amp.AdminPortal2Server, session.sessid, operation=operation, **kwargs)
[ "def", "send_AdminPortal2Server", "(", "self", ",", "session", ",", "operation", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "data_to_server", "(", "amp", ".", "AdminPortal2Server", ",", "session", ".", "sessid", ",", "operation", "=", "operation", ",", "*", "*", "kwargs", ")" ]
[ 247, 4 ]
[ 260, 65 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.portal_receive_status
(self, status)
Returns run-status for the server/portal. Args: status (str): Not used. Returns: status (dict): The status is a tuple (portal_running, server_running, portal_pid, server_pid).
Returns run-status for the server/portal.
def portal_receive_status(self, status): """ Returns run-status for the server/portal. Args: status (str): Not used. Returns: status (dict): The status is a tuple (portal_running, server_running, portal_pid, server_pid). """ return {"status": amp.dumps(self.get_status())}
[ "def", "portal_receive_status", "(", "self", ",", "status", ")", ":", "return", "{", "\"status\"", ":", "amp", ".", "dumps", "(", "self", ".", "get_status", "(", ")", ")", "}" ]
[ 266, 4 ]
[ 277, 55 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.portal_receive_launcher2portal
(self, operation, arguments)
Receives message arriving from evennia_launcher. This method is executed on the Portal. Args: operation (str): The action to perform. arguments (str): Possible argument to the instruction, or the empty string. Returns: result (dict): The result back to the launcher. Notes: This is the entrypoint for controlling the entire Evennia system from the evennia launcher. It can obviously only accessed when the Portal is already up and running.
Receives message arriving from evennia_launcher. This method is executed on the Portal.
def portal_receive_launcher2portal(self, operation, arguments): """ Receives message arriving from evennia_launcher. This method is executed on the Portal. Args: operation (str): The action to perform. arguments (str): Possible argument to the instruction, or the empty string. Returns: result (dict): The result back to the launcher. Notes: This is the entrypoint for controlling the entire Evennia system from the evennia launcher. It can obviously only accessed when the Portal is already up and running. """ self.factory.launcher_connection = self _, server_connected, _, _, _, _ = self.get_status() # logger.log_msg("Evennia Launcher->Portal operation %s received" % (ord(operation))) if operation == amp.SSTART: # portal start #15 # first, check if server is already running if not server_connected: self.wait_for_server_connect(self.send_Status2Launcher) self.start_server(amp.loads(arguments)) elif operation == amp.SRELOAD: # reload server #14 if server_connected: # We let the launcher restart us once they get the signal self.factory.server_connection.wait_for_disconnect( self.send_Status2Launcher) self.stop_server(mode='reload') else: self.wait_for_server_connect(self.send_Status2Launcher) self.start_server(amp.loads(arguments)) elif operation == amp.SRESET: # reload server #19 if server_connected: self.factory.server_connection.wait_for_disconnect( self.send_Status2Launcher) self.stop_server(mode='reset') else: self.wait_for_server_connect(self.send_Status2Launcher) self.start_server(amp.loads(arguments)) elif operation == amp.SSHUTD: # server-only shutdown #17 if server_connected: self.factory.server_connection.wait_for_disconnect( self.send_Status2Launcher) self.stop_server(mode='shutdown') elif operation == amp.PSHUTD: # portal + server shutdown #16 if server_connected: self.factory.server_connection.wait_for_disconnect( self.factory.portal.shutdown ) else: self.factory.portal.shutdown() else: raise Exception("operation %(op)s not recognized." % {'op': operation}) return {}
[ "def", "portal_receive_launcher2portal", "(", "self", ",", "operation", ",", "arguments", ")", ":", "self", ".", "factory", ".", "launcher_connection", "=", "self", "_", ",", "server_connected", ",", "_", ",", "_", ",", "_", ",", "_", "=", "self", ".", "get_status", "(", ")", "# logger.log_msg(\"Evennia Launcher->Portal operation %s received\" % (ord(operation)))", "if", "operation", "==", "amp", ".", "SSTART", ":", "# portal start #15", "# first, check if server is already running", "if", "not", "server_connected", ":", "self", ".", "wait_for_server_connect", "(", "self", ".", "send_Status2Launcher", ")", "self", ".", "start_server", "(", "amp", ".", "loads", "(", "arguments", ")", ")", "elif", "operation", "==", "amp", ".", "SRELOAD", ":", "# reload server #14", "if", "server_connected", ":", "# We let the launcher restart us once they get the signal", "self", ".", "factory", ".", "server_connection", ".", "wait_for_disconnect", "(", "self", ".", "send_Status2Launcher", ")", "self", ".", "stop_server", "(", "mode", "=", "'reload'", ")", "else", ":", "self", ".", "wait_for_server_connect", "(", "self", ".", "send_Status2Launcher", ")", "self", ".", "start_server", "(", "amp", ".", "loads", "(", "arguments", ")", ")", "elif", "operation", "==", "amp", ".", "SRESET", ":", "# reload server #19", "if", "server_connected", ":", "self", ".", "factory", ".", "server_connection", ".", "wait_for_disconnect", "(", "self", ".", "send_Status2Launcher", ")", "self", ".", "stop_server", "(", "mode", "=", "'reset'", ")", "else", ":", "self", ".", "wait_for_server_connect", "(", "self", ".", "send_Status2Launcher", ")", "self", ".", "start_server", "(", "amp", ".", "loads", "(", "arguments", ")", ")", "elif", "operation", "==", "amp", ".", "SSHUTD", ":", "# server-only shutdown #17", "if", "server_connected", ":", "self", ".", "factory", ".", "server_connection", ".", "wait_for_disconnect", "(", "self", ".", "send_Status2Launcher", ")", "self", ".", "stop_server", "(", "mode", "=", "'shutdown'", ")", "elif", "operation", "==", "amp", ".", "PSHUTD", ":", "# portal + server shutdown #16", "if", "server_connected", ":", "self", ".", "factory", ".", "server_connection", ".", "wait_for_disconnect", "(", "self", ".", "factory", ".", "portal", ".", "shutdown", ")", "else", ":", "self", ".", "factory", ".", "portal", ".", "shutdown", "(", ")", "else", ":", "raise", "Exception", "(", "\"operation %(op)s not recognized.\"", "%", "{", "'op'", ":", "operation", "}", ")", "return", "{", "}" ]
[ 281, 4 ]
[ 345, 17 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.portal_receive_server2portal
(self, packed_data)
Receives message arriving to Portal from Server. This method is executed on the Portal. Args: packed_data (str): Pickled data (sessid, kwargs) coming over the wire.
Receives message arriving to Portal from Server. This method is executed on the Portal.
def portal_receive_server2portal(self, packed_data): """ Receives message arriving to Portal from Server. This method is executed on the Portal. Args: packed_data (str): Pickled data (sessid, kwargs) coming over the wire. """ try: sessid, kwargs = self.data_in(packed_data) session = self.factory.portal.sessions.get(sessid, None) if session: self.factory.portal.sessions.data_out(session, **kwargs) except Exception: logger.log_trace("packed_data len {}".format(len(packed_data))) return {}
[ "def", "portal_receive_server2portal", "(", "self", ",", "packed_data", ")", ":", "try", ":", "sessid", ",", "kwargs", "=", "self", ".", "data_in", "(", "packed_data", ")", "session", "=", "self", ".", "factory", ".", "portal", ".", "sessions", ".", "get", "(", "sessid", ",", "None", ")", "if", "session", ":", "self", ".", "factory", ".", "portal", ".", "sessions", ".", "data_out", "(", "session", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "logger", ".", "log_trace", "(", "\"packed_data len {}\"", ".", "format", "(", "len", "(", "packed_data", ")", ")", ")", "return", "{", "}" ]
[ 349, 4 ]
[ 365, 17 ]
python
en
['en', 'error', 'th']
False
AMPServerProtocol.portal_receive_adminserver2portal
(self, packed_data)
Receives and handles admin operations sent to the Portal This is executed on the Portal. Args: packed_data (str): Data received, a pickled tuple (sessid, kwargs).
def portal_receive_adminserver2portal(self, packed_data): """ Receives and handles admin operations sent to the Portal This is executed on the Portal. Args: packed_data (str): Data received, a pickled tuple (sessid, kwargs). """ self.factory.server_connection = self sessid, kwargs = self.data_in(packed_data) operation = kwargs.pop("operation") portal_sessionhandler = self.factory.portal.sessions if operation == amp.SLOGIN: # server_session_login # a session has authenticated; sync it. session = portal_sessionhandler.get(sessid) if session: portal_sessionhandler.server_logged_in(session, kwargs.get("sessiondata")) elif operation == amp.SDISCONN: # server_session_disconnect # the server is ordering to disconnect the session session = portal_sessionhandler.get(sessid) if session: portal_sessionhandler.server_disconnect(session, reason=kwargs.get("reason")) elif operation == amp.SDISCONNALL: # server_session_disconnect_all # server orders all sessions to disconnect portal_sessionhandler.server_disconnect_all(reason=kwargs.get("reason")) elif operation == amp.SRELOAD: # server reload self.factory.server_connection.wait_for_disconnect( self.start_server, self.factory.portal.server_twistd_cmd) self.stop_server(mode='reload') elif operation == amp.SRESET: # server reset self.factory.server_connection.wait_for_disconnect( self.start_server, self.factory.portal.server_twistd_cmd) self.stop_server(mode='reset') elif operation == amp.SSHUTD: # server-only shutdown self.stop_server(mode='shutdown') elif operation == amp.PSHUTD: # full server+server shutdown self.factory.server_connection.wait_for_disconnect( self.factory.portal.shutdown) self.stop_server(mode='shutdown') elif operation == amp.PSYNC: # portal sync # Server has (re-)connected and wants the session data from portal self.factory.portal.server_info_dict = kwargs.get("info_dict", {}) self.factory.portal.server_process_id = kwargs.get("spid", None) # this defaults to 'shutdown' or whatever value set in server_stop server_restart_mode = self.factory.portal.server_restart_mode sessdata = self.factory.portal.sessions.get_all_sync_data() self.send_AdminPortal2Server(amp.DUMMYSESSION, amp.PSYNC, server_restart_mode=server_restart_mode, sessiondata=sessdata) self.factory.portal.sessions.at_server_connection() if self.factory.server_connection: # this is an indication the server has successfully connected, so # we trigger any callbacks (usually to tell the launcher server is up) for callback, args, kwargs in self.factory.server_connect_callbacks: try: callback(*args, **kwargs) except Exception: logger.log_trace() self.factory.server_connect_callbacks = [] elif operation == amp.SSYNC: # server_session_sync # server wants to save session data to the portal, # maybe because it's about to shut down. portal_sessionhandler.server_session_sync(kwargs.get("sessiondata"), kwargs.get("clean", True)) # set a flag in case we are about to shut down soon self.factory.server_restart_mode = True elif operation == amp.SCONN: # server_force_connection (for irc/etc) portal_sessionhandler.server_connect(**kwargs) else: raise Exception("operation %(op)s not recognized." % {'op': operation}) return {}
[ "def", "portal_receive_adminserver2portal", "(", "self", ",", "packed_data", ")", ":", "self", ".", "factory", ".", "server_connection", "=", "self", "sessid", ",", "kwargs", "=", "self", ".", "data_in", "(", "packed_data", ")", "operation", "=", "kwargs", ".", "pop", "(", "\"operation\"", ")", "portal_sessionhandler", "=", "self", ".", "factory", ".", "portal", ".", "sessions", "if", "operation", "==", "amp", ".", "SLOGIN", ":", "# server_session_login", "# a session has authenticated; sync it.", "session", "=", "portal_sessionhandler", ".", "get", "(", "sessid", ")", "if", "session", ":", "portal_sessionhandler", ".", "server_logged_in", "(", "session", ",", "kwargs", ".", "get", "(", "\"sessiondata\"", ")", ")", "elif", "operation", "==", "amp", ".", "SDISCONN", ":", "# server_session_disconnect", "# the server is ordering to disconnect the session", "session", "=", "portal_sessionhandler", ".", "get", "(", "sessid", ")", "if", "session", ":", "portal_sessionhandler", ".", "server_disconnect", "(", "session", ",", "reason", "=", "kwargs", ".", "get", "(", "\"reason\"", ")", ")", "elif", "operation", "==", "amp", ".", "SDISCONNALL", ":", "# server_session_disconnect_all", "# server orders all sessions to disconnect", "portal_sessionhandler", ".", "server_disconnect_all", "(", "reason", "=", "kwargs", ".", "get", "(", "\"reason\"", ")", ")", "elif", "operation", "==", "amp", ".", "SRELOAD", ":", "# server reload", "self", ".", "factory", ".", "server_connection", ".", "wait_for_disconnect", "(", "self", ".", "start_server", ",", "self", ".", "factory", ".", "portal", ".", "server_twistd_cmd", ")", "self", ".", "stop_server", "(", "mode", "=", "'reload'", ")", "elif", "operation", "==", "amp", ".", "SRESET", ":", "# server reset", "self", ".", "factory", ".", "server_connection", ".", "wait_for_disconnect", "(", "self", ".", "start_server", ",", "self", ".", "factory", ".", "portal", ".", "server_twistd_cmd", ")", "self", ".", "stop_server", "(", "mode", "=", "'reset'", ")", "elif", "operation", "==", "amp", ".", "SSHUTD", ":", "# server-only shutdown", "self", ".", "stop_server", "(", "mode", "=", "'shutdown'", ")", "elif", "operation", "==", "amp", ".", "PSHUTD", ":", "# full server+server shutdown", "self", ".", "factory", ".", "server_connection", ".", "wait_for_disconnect", "(", "self", ".", "factory", ".", "portal", ".", "shutdown", ")", "self", ".", "stop_server", "(", "mode", "=", "'shutdown'", ")", "elif", "operation", "==", "amp", ".", "PSYNC", ":", "# portal sync", "# Server has (re-)connected and wants the session data from portal", "self", ".", "factory", ".", "portal", ".", "server_info_dict", "=", "kwargs", ".", "get", "(", "\"info_dict\"", ",", "{", "}", ")", "self", ".", "factory", ".", "portal", ".", "server_process_id", "=", "kwargs", ".", "get", "(", "\"spid\"", ",", "None", ")", "# this defaults to 'shutdown' or whatever value set in server_stop", "server_restart_mode", "=", "self", ".", "factory", ".", "portal", ".", "server_restart_mode", "sessdata", "=", "self", ".", "factory", ".", "portal", ".", "sessions", ".", "get_all_sync_data", "(", ")", "self", ".", "send_AdminPortal2Server", "(", "amp", ".", "DUMMYSESSION", ",", "amp", ".", "PSYNC", ",", "server_restart_mode", "=", "server_restart_mode", ",", "sessiondata", "=", "sessdata", ")", "self", ".", "factory", ".", "portal", ".", "sessions", ".", "at_server_connection", "(", ")", "if", "self", ".", "factory", ".", "server_connection", ":", "# this is an indication the server has successfully connected, so", "# we trigger any callbacks (usually to tell the launcher server is up)", "for", "callback", ",", "args", ",", "kwargs", "in", "self", ".", "factory", ".", "server_connect_callbacks", ":", "try", ":", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "logger", ".", "log_trace", "(", ")", "self", ".", "factory", ".", "server_connect_callbacks", "=", "[", "]", "elif", "operation", "==", "amp", ".", "SSYNC", ":", "# server_session_sync", "# server wants to save session data to the portal,", "# maybe because it's about to shut down.", "portal_sessionhandler", ".", "server_session_sync", "(", "kwargs", ".", "get", "(", "\"sessiondata\"", ")", ",", "kwargs", ".", "get", "(", "\"clean\"", ",", "True", ")", ")", "# set a flag in case we are about to shut down soon", "self", ".", "factory", ".", "server_restart_mode", "=", "True", "elif", "operation", "==", "amp", ".", "SCONN", ":", "# server_force_connection (for irc/etc)", "portal_sessionhandler", ".", "server_connect", "(", "*", "*", "kwargs", ")", "else", ":", "raise", "Exception", "(", "\"operation %(op)s not recognized.\"", "%", "{", "'op'", ":", "operation", "}", ")", "return", "{", "}" ]
[ 369, 4 ]
[ 457, 17 ]
python
en
['en', 'error', 'th']
False
Line.color
(self)
Sets the line color. 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
Sets the line color. 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): """ Sets the line color. 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 ]
[ 65, 28 ]
python
en
['en', 'error', 'th']
False
Line.dash
(self)
Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). The 'dash' property is an enumeration that may be specified as: - One of the following dash styles: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'] - A string containing a dash length list in pixels or percentages (e.g. '5px 10px 2px 2px', '5, 10, 2, 2', '10% 20% 40%', etc.) Returns ------- str
Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). The 'dash' property is an enumeration that may be specified as: - One of the following dash styles: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'] - A string containing a dash length list in pixels or percentages (e.g. '5px 10px 2px 2px', '5, 10, 2, 2', '10% 20% 40%', etc.)
def dash(self): """ Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). The 'dash' property is an enumeration that may be specified as: - One of the following dash styles: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'] - A string containing a dash length list in pixels or percentages (e.g. '5px 10px 2px 2px', '5, 10, 2, 2', '10% 20% 40%', etc.) Returns ------- str """ return self["dash"]
[ "def", "dash", "(", "self", ")", ":", "return", "self", "[", "\"dash\"", "]" ]
[ 74, 4 ]
[ 91, 27 ]
python
en
['en', 'error', 'th']
False
Line.shape
(self)
Determines the line shape. With "spline" the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes. The 'shape' property is an enumeration that may be specified as: - One of the following enumeration values: ['linear', 'spline'] Returns ------- Any
Determines the line shape. With "spline" the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes. The 'shape' property is an enumeration that may be specified as: - One of the following enumeration values: ['linear', 'spline']
def shape(self): """ Determines the line shape. With "spline" the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes. The 'shape' property is an enumeration that may be specified as: - One of the following enumeration values: ['linear', 'spline'] Returns ------- Any """ return self["shape"]
[ "def", "shape", "(", "self", ")", ":", "return", "self", "[", "\"shape\"", "]" ]
[ 100, 4 ]
[ 114, 28 ]
python
en
['en', 'error', 'th']
False
Line.smoothing
(self)
Has an effect only if `shape` is set to "spline" Sets the amount of smoothing. 0 corresponds to no smoothing (equivalent to a "linear" shape). The 'smoothing' property is a number and may be specified as: - An int or float in the interval [0, 1.3] Returns ------- int|float
Has an effect only if `shape` is set to "spline" Sets the amount of smoothing. 0 corresponds to no smoothing (equivalent to a "linear" shape). The 'smoothing' property is a number and may be specified as: - An int or float in the interval [0, 1.3]
def smoothing(self): """ Has an effect only if `shape` is set to "spline" Sets the amount of smoothing. 0 corresponds to no smoothing (equivalent to a "linear" shape). The 'smoothing' property is a number and may be specified as: - An int or float in the interval [0, 1.3] Returns ------- int|float """ return self["smoothing"]
[ "def", "smoothing", "(", "self", ")", ":", "return", "self", "[", "\"smoothing\"", "]" ]
[ 123, 4 ]
[ 136, 32 ]
python
en
['en', 'error', 'th']
False
Line.width
(self)
Sets the line width (in px). 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 line width (in px). 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 line width (in px). 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\"", "]" ]
[ 145, 4 ]
[ 156, 28 ]
python
en
['en', 'error', 'th']
False
Line.__init__
( self, arg=None, color=None, dash=None, shape=None, smoothing=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.scattercarpet.Line` color Sets the line color. dash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). shape Determines the line shape. With "spline" the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes. smoothing Has an effect only if `shape` is set to "spline" Sets the amount of smoothing. 0 corresponds to no smoothing (equivalent to a "linear" shape). width Sets the line width (in px). Returns ------- Line
Construct a new Line object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scattercarpet.Line` color Sets the line color. dash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). shape Determines the line shape. With "spline" the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes. smoothing Has an effect only if `shape` is set to "spline" Sets the amount of smoothing. 0 corresponds to no smoothing (equivalent to a "linear" shape). width Sets the line width (in px).
def __init__( self, arg=None, color=None, dash=None, shape=None, smoothing=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.scattercarpet.Line` color Sets the line color. dash Sets the dash style of lines. Set to a dash type string ("solid", "dot", "dash", "longdash", "dashdot", or "longdashdot") or a dash length list in px (eg "5px,10px,2px,2px"). shape Determines the line shape. With "spline" the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes. smoothing Has an effect only if `shape` is set to "spline" Sets the amount of smoothing. 0 corresponds to no smoothing (equivalent to a "linear" shape). width Sets the line width (in px). 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.scattercarpet.Line constructor must be a dict or an instance of :class:`plotly.graph_objs.scattercarpet.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("color", None) _v = color if color is not None else _v if _v is not None: self["color"] = _v _v = arg.pop("dash", None) _v = dash if dash is not None else _v if _v is not None: self["dash"] = _v _v = arg.pop("shape", None) _v = shape if shape is not None else _v if _v is not None: self["shape"] = _v _v = arg.pop("smoothing", None) _v = smoothing if smoothing is not None else _v if _v is not None: self["smoothing"] = _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", ",", "color", "=", "None", ",", "dash", "=", "None", ",", "shape", "=", "None", ",", "smoothing", "=", "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.scattercarpet.Line \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.scattercarpet.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", "(", "\"color\"", ",", "None", ")", "_v", "=", "color", "if", "color", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"color\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"dash\"", ",", "None", ")", "_v", "=", "dash", "if", "dash", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"dash\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"shape\"", ",", "None", ")", "_v", "=", "shape", "if", "shape", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"shape\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"smoothing\"", ",", "None", ")", "_v", "=", "smoothing", "if", "smoothing", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"smoothing\"", "]", "=", "_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" ]
[ 186, 4 ]
[ 283, 34 ]
python
en
['en', 'error', 'th']
False
_mkdirp
(directory)
Equivalent to mkdir -p.
Equivalent to mkdir -p.
def _mkdirp(directory): """ Equivalent to mkdir -p. """ if not os.path.exists(directory): os.makedirs(directory)
[ "def", "_mkdirp", "(", "directory", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "directory", ")" ]
[ 35, 0 ]
[ 40, 30 ]
python
en
['en', 'error', 'th']
False
Stream.maxpoints
(self)
Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. The 'maxpoints' property is a number and may be specified as: - An int or float in the interval [0, 10000] Returns ------- int|float
Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. The 'maxpoints' property is a number and may be specified as: - An int or float in the interval [0, 10000]
def maxpoints(self): """ Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. The 'maxpoints' property is a number and may be specified as: - An int or float in the interval [0, 10000] Returns ------- int|float """ return self["maxpoints"]
[ "def", "maxpoints", "(", "self", ")", ":", "return", "self", "[", "\"maxpoints\"", "]" ]
[ 15, 4 ]
[ 28, 32 ]
python
en
['en', 'error', 'th']
False
Stream.token
(self)
The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. The 'token' property is a string and must be specified as: - A non-empty string Returns ------- str
The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. The 'token' property is a string and must be specified as: - A non-empty string
def token(self): """ The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. The 'token' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["token"]
[ "def", "token", "(", "self", ")", ":", "return", "self", "[", "\"token\"", "]" ]
[ 37, 4 ]
[ 50, 28 ]
python
en
['en', 'error', 'th']
False
Stream.__init__
(self, arg=None, maxpoints=None, token=None, **kwargs)
Construct a new Stream object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.cone.Stream` maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. Returns ------- Stream
Construct a new Stream object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.cone.Stream` maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details.
def __init__(self, arg=None, maxpoints=None, token=None, **kwargs): """ Construct a new Stream object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.cone.Stream` maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. Returns ------- Stream """ super(Stream, self).__init__("stream") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.cone.Stream constructor must be a dict or an instance of :class:`plotly.graph_objs.cone.Stream`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("maxpoints", None) _v = maxpoints if maxpoints is not None else _v if _v is not None: self["maxpoints"] = _v _v = arg.pop("token", None) _v = token if token is not None else _v if _v is not None: self["token"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "maxpoints", "=", "None", ",", "token", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Stream", ",", "self", ")", ".", "__init__", "(", "\"stream\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.cone.Stream \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.cone.Stream`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"maxpoints\"", ",", "None", ")", "_v", "=", "maxpoints", "if", "maxpoints", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"maxpoints\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"token\"", ",", "None", ")", "_v", "=", "token", "if", "token", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"token\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 72, 4 ]
[ 139, 34 ]
python
en
['en', 'error', 'th']
False
validate_table
(table_text, font_colors)
Table-specific validations Check that font_colors is supplied correctly (1, 3, or len(text) colors). :raises: (PlotlyError) If font_colors is supplied incorretly. See FigureFactory.create_table() for params
Table-specific validations
def validate_table(table_text, font_colors): """ Table-specific validations Check that font_colors is supplied correctly (1, 3, or len(text) colors). :raises: (PlotlyError) If font_colors is supplied incorretly. See FigureFactory.create_table() for params """ font_colors_len_options = [1, 3, len(table_text)] if len(font_colors) not in font_colors_len_options: raise exceptions.PlotlyError( "Oops, font_colors should be a list " "of length 1, 3 or len(text)" )
[ "def", "validate_table", "(", "table_text", ",", "font_colors", ")", ":", "font_colors_len_options", "=", "[", "1", ",", "3", ",", "len", "(", "table_text", ")", "]", "if", "len", "(", "font_colors", ")", "not", "in", "font_colors_len_options", ":", "raise", "exceptions", ".", "PlotlyError", "(", "\"Oops, font_colors should be a list \"", "\"of length 1, 3 or len(text)\"", ")" ]
[ 8, 0 ]
[ 23, 9 ]
python
en
['en', 'error', 'th']
False
create_table
( table_text, colorscale=None, font_colors=None, index=False, index_title="", annotation_offset=0.45, height_constant=30, hoverinfo="none", **kwargs )
Function that creates data tables. See also the plotly.graph_objects trace :class:`plotly.graph_objects.Table` :param (pandas.Dataframe | list[list]) text: data for table. :param (str|list[list]) colorscale: Colorscale for table where the color at value 0 is the header color, .5 is the first table color and 1 is the second table color. (Set .5 and 1 to avoid the striped table effect). Default=[[0, '#66b2ff'], [.5, '#d9d9d9'], [1, '#ffffff']] :param (list) font_colors: Color for fonts in table. Can be a single color, three colors, or a color for each row in the table. Default=['#000000'] (black text for the entire table) :param (int) height_constant: Constant multiplied by # of rows to create table height. Default=30. :param (bool) index: Create (header-colored) index column index from Pandas dataframe or list[0] for each list in text. Default=False. :param (string) index_title: Title for index column. Default=''. :param kwargs: kwargs passed through plotly.graph_objs.Heatmap. These kwargs describe other attributes about the annotated Heatmap trace such as the colorscale. For more information on valid kwargs call help(plotly.graph_objs.Heatmap) Example 1: Simple Plotly Table >>> from plotly.figure_factory import create_table >>> text = [['Country', 'Year', 'Population'], ... ['US', 2000, 282200000], ... ['Canada', 2000, 27790000], ... ['US', 2010, 309000000], ... ['Canada', 2010, 34000000]] >>> table = create_table(text) >>> table.show() Example 2: Table with Custom Coloring >>> from plotly.figure_factory import create_table >>> text = [['Country', 'Year', 'Population'], ... ['US', 2000, 282200000], ... ['Canada', 2000, 27790000], ... ['US', 2010, 309000000], ... ['Canada', 2010, 34000000]] >>> table = create_table(text, ... colorscale=[[0, '#000000'], ... [.5, '#80beff'], ... [1, '#cce5ff']], ... font_colors=['#ffffff', '#000000', ... '#000000']) >>> table.show() Example 3: Simple Plotly Table with Pandas >>> from plotly.figure_factory import create_table >>> import pandas as pd >>> df = pd.read_csv('http://www.stat.ubc.ca/~jenny/notOcto/STAT545A/examples/gapminder/data/gapminderDataFiveYear.txt', sep='\t') >>> df_p = df[0:25] >>> table_simple = create_table(df_p) >>> table_simple.show()
Function that creates data tables.
def create_table( table_text, colorscale=None, font_colors=None, index=False, index_title="", annotation_offset=0.45, height_constant=30, hoverinfo="none", **kwargs ): """ Function that creates data tables. See also the plotly.graph_objects trace :class:`plotly.graph_objects.Table` :param (pandas.Dataframe | list[list]) text: data for table. :param (str|list[list]) colorscale: Colorscale for table where the color at value 0 is the header color, .5 is the first table color and 1 is the second table color. (Set .5 and 1 to avoid the striped table effect). Default=[[0, '#66b2ff'], [.5, '#d9d9d9'], [1, '#ffffff']] :param (list) font_colors: Color for fonts in table. Can be a single color, three colors, or a color for each row in the table. Default=['#000000'] (black text for the entire table) :param (int) height_constant: Constant multiplied by # of rows to create table height. Default=30. :param (bool) index: Create (header-colored) index column index from Pandas dataframe or list[0] for each list in text. Default=False. :param (string) index_title: Title for index column. Default=''. :param kwargs: kwargs passed through plotly.graph_objs.Heatmap. These kwargs describe other attributes about the annotated Heatmap trace such as the colorscale. For more information on valid kwargs call help(plotly.graph_objs.Heatmap) Example 1: Simple Plotly Table >>> from plotly.figure_factory import create_table >>> text = [['Country', 'Year', 'Population'], ... ['US', 2000, 282200000], ... ['Canada', 2000, 27790000], ... ['US', 2010, 309000000], ... ['Canada', 2010, 34000000]] >>> table = create_table(text) >>> table.show() Example 2: Table with Custom Coloring >>> from plotly.figure_factory import create_table >>> text = [['Country', 'Year', 'Population'], ... ['US', 2000, 282200000], ... ['Canada', 2000, 27790000], ... ['US', 2010, 309000000], ... ['Canada', 2010, 34000000]] >>> table = create_table(text, ... colorscale=[[0, '#000000'], ... [.5, '#80beff'], ... [1, '#cce5ff']], ... font_colors=['#ffffff', '#000000', ... '#000000']) >>> table.show() Example 3: Simple Plotly Table with Pandas >>> from plotly.figure_factory import create_table >>> import pandas as pd >>> df = pd.read_csv('http://www.stat.ubc.ca/~jenny/notOcto/STAT545A/examples/gapminder/data/gapminderDataFiveYear.txt', sep='\t') >>> df_p = df[0:25] >>> table_simple = create_table(df_p) >>> table_simple.show() """ # Avoiding mutables in the call signature colorscale = ( colorscale if colorscale is not None else [[0, "#00083e"], [0.5, "#ededee"], [1, "#ffffff"]] ) font_colors = ( font_colors if font_colors is not None else ["#ffffff", "#000000", "#000000"] ) validate_table(table_text, font_colors) table_matrix = _Table( table_text, colorscale, font_colors, index, index_title, annotation_offset, **kwargs ).get_table_matrix() annotations = _Table( table_text, colorscale, font_colors, index, index_title, annotation_offset, **kwargs ).make_table_annotations() trace = dict( type="heatmap", z=table_matrix, opacity=0.75, colorscale=colorscale, showscale=False, hoverinfo=hoverinfo, **kwargs ) data = [trace] layout = dict( annotations=annotations, height=len(table_matrix) * height_constant + 50, margin=dict(t=0, b=0, r=0, l=0), yaxis=dict( autorange="reversed", zeroline=False, gridwidth=2, ticks="", dtick=1, tick0=0.5, showticklabels=False, ), xaxis=dict( zeroline=False, gridwidth=2, ticks="", dtick=1, tick0=-0.5, showticklabels=False, ), ) return graph_objs.Figure(data=data, layout=layout)
[ "def", "create_table", "(", "table_text", ",", "colorscale", "=", "None", ",", "font_colors", "=", "None", ",", "index", "=", "False", ",", "index_title", "=", "\"\"", ",", "annotation_offset", "=", "0.45", ",", "height_constant", "=", "30", ",", "hoverinfo", "=", "\"none\"", ",", "*", "*", "kwargs", ")", ":", "# Avoiding mutables in the call signature", "colorscale", "=", "(", "colorscale", "if", "colorscale", "is", "not", "None", "else", "[", "[", "0", ",", "\"#00083e\"", "]", ",", "[", "0.5", ",", "\"#ededee\"", "]", ",", "[", "1", ",", "\"#ffffff\"", "]", "]", ")", "font_colors", "=", "(", "font_colors", "if", "font_colors", "is", "not", "None", "else", "[", "\"#ffffff\"", ",", "\"#000000\"", ",", "\"#000000\"", "]", ")", "validate_table", "(", "table_text", ",", "font_colors", ")", "table_matrix", "=", "_Table", "(", "table_text", ",", "colorscale", ",", "font_colors", ",", "index", ",", "index_title", ",", "annotation_offset", ",", "*", "*", "kwargs", ")", ".", "get_table_matrix", "(", ")", "annotations", "=", "_Table", "(", "table_text", ",", "colorscale", ",", "font_colors", ",", "index", ",", "index_title", ",", "annotation_offset", ",", "*", "*", "kwargs", ")", ".", "make_table_annotations", "(", ")", "trace", "=", "dict", "(", "type", "=", "\"heatmap\"", ",", "z", "=", "table_matrix", ",", "opacity", "=", "0.75", ",", "colorscale", "=", "colorscale", ",", "showscale", "=", "False", ",", "hoverinfo", "=", "hoverinfo", ",", "*", "*", "kwargs", ")", "data", "=", "[", "trace", "]", "layout", "=", "dict", "(", "annotations", "=", "annotations", ",", "height", "=", "len", "(", "table_matrix", ")", "*", "height_constant", "+", "50", ",", "margin", "=", "dict", "(", "t", "=", "0", ",", "b", "=", "0", ",", "r", "=", "0", ",", "l", "=", "0", ")", ",", "yaxis", "=", "dict", "(", "autorange", "=", "\"reversed\"", ",", "zeroline", "=", "False", ",", "gridwidth", "=", "2", ",", "ticks", "=", "\"\"", ",", "dtick", "=", "1", ",", "tick0", "=", "0.5", ",", "showticklabels", "=", "False", ",", ")", ",", "xaxis", "=", "dict", "(", "zeroline", "=", "False", ",", "gridwidth", "=", "2", ",", "ticks", "=", "\"\"", ",", "dtick", "=", "1", ",", "tick0", "=", "-", "0.5", ",", "showticklabels", "=", "False", ",", ")", ",", ")", "return", "graph_objs", ".", "Figure", "(", "data", "=", "data", ",", "layout", "=", "layout", ")" ]
[ 26, 0 ]
[ 165, 54 ]
python
en
['en', 'error', 'th']
False
_Table.get_table_matrix
(self)
Create z matrix to make heatmap with striped table coloring :rtype (list[list]) table_matrix: z matrix to make heatmap with striped table coloring.
Create z matrix to make heatmap with striped table coloring
def get_table_matrix(self): """ Create z matrix to make heatmap with striped table coloring :rtype (list[list]) table_matrix: z matrix to make heatmap with striped table coloring. """ header = [0] * len(self.table_text[0]) odd_row = [0.5] * len(self.table_text[0]) even_row = [1] * len(self.table_text[0]) table_matrix = [None] * len(self.table_text) table_matrix[0] = header for i in range(1, len(self.table_text), 2): table_matrix[i] = odd_row for i in range(2, len(self.table_text), 2): table_matrix[i] = even_row if self.index: for array in table_matrix: array[0] = 0 return table_matrix
[ "def", "get_table_matrix", "(", "self", ")", ":", "header", "=", "[", "0", "]", "*", "len", "(", "self", ".", "table_text", "[", "0", "]", ")", "odd_row", "=", "[", "0.5", "]", "*", "len", "(", "self", ".", "table_text", "[", "0", "]", ")", "even_row", "=", "[", "1", "]", "*", "len", "(", "self", ".", "table_text", "[", "0", "]", ")", "table_matrix", "=", "[", "None", "]", "*", "len", "(", "self", ".", "table_text", ")", "table_matrix", "[", "0", "]", "=", "header", "for", "i", "in", "range", "(", "1", ",", "len", "(", "self", ".", "table_text", ")", ",", "2", ")", ":", "table_matrix", "[", "i", "]", "=", "odd_row", "for", "i", "in", "range", "(", "2", ",", "len", "(", "self", ".", "table_text", ")", ",", "2", ")", ":", "table_matrix", "[", "i", "]", "=", "even_row", "if", "self", ".", "index", ":", "for", "array", "in", "table_matrix", ":", "array", "[", "0", "]", "=", "0", "return", "table_matrix" ]
[ 200, 4 ]
[ 219, 27 ]
python
en
['en', 'error', 'th']
False
_Table.get_table_font_color
(self)
Fill font-color array. Table text color can vary by row so this extends a single color or creates an array to set a header color and two alternating colors to create the striped table pattern. :rtype (list[list]) all_font_colors: list of font colors for each row in table.
Fill font-color array.
def get_table_font_color(self): """ Fill font-color array. Table text color can vary by row so this extends a single color or creates an array to set a header color and two alternating colors to create the striped table pattern. :rtype (list[list]) all_font_colors: list of font colors for each row in table. """ if len(self.font_colors) == 1: all_font_colors = self.font_colors * len(self.table_text) elif len(self.font_colors) == 3: all_font_colors = list(range(len(self.table_text))) all_font_colors[0] = self.font_colors[0] for i in range(1, len(self.table_text), 2): all_font_colors[i] = self.font_colors[1] for i in range(2, len(self.table_text), 2): all_font_colors[i] = self.font_colors[2] elif len(self.font_colors) == len(self.table_text): all_font_colors = self.font_colors else: all_font_colors = ["#000000"] * len(self.table_text) return all_font_colors
[ "def", "get_table_font_color", "(", "self", ")", ":", "if", "len", "(", "self", ".", "font_colors", ")", "==", "1", ":", "all_font_colors", "=", "self", ".", "font_colors", "*", "len", "(", "self", ".", "table_text", ")", "elif", "len", "(", "self", ".", "font_colors", ")", "==", "3", ":", "all_font_colors", "=", "list", "(", "range", "(", "len", "(", "self", ".", "table_text", ")", ")", ")", "all_font_colors", "[", "0", "]", "=", "self", ".", "font_colors", "[", "0", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "self", ".", "table_text", ")", ",", "2", ")", ":", "all_font_colors", "[", "i", "]", "=", "self", ".", "font_colors", "[", "1", "]", "for", "i", "in", "range", "(", "2", ",", "len", "(", "self", ".", "table_text", ")", ",", "2", ")", ":", "all_font_colors", "[", "i", "]", "=", "self", ".", "font_colors", "[", "2", "]", "elif", "len", "(", "self", ".", "font_colors", ")", "==", "len", "(", "self", ".", "table_text", ")", ":", "all_font_colors", "=", "self", ".", "font_colors", "else", ":", "all_font_colors", "=", "[", "\"#000000\"", "]", "*", "len", "(", "self", ".", "table_text", ")", "return", "all_font_colors" ]
[ 221, 4 ]
[ 245, 30 ]
python
en
['en', 'error', 'th']
False
_Table.make_table_annotations
(self)
Generate annotations to fill in table text :rtype (list) annotations: list of annotations for each cell of the table.
Generate annotations to fill in table text
def make_table_annotations(self): """ Generate annotations to fill in table text :rtype (list) annotations: list of annotations for each cell of the table. """ table_matrix = _Table.get_table_matrix(self) all_font_colors = _Table.get_table_font_color(self) annotations = [] for n, row in enumerate(self.table_text): for m, val in enumerate(row): # Bold text in header and index format_text = ( "<b>" + str(val) + "</b>" if n == 0 or self.index and m < 1 else str(val) ) # Match font color of index to font color of header font_color = ( self.font_colors[0] if self.index and m == 0 else all_font_colors[n] ) annotations.append( graph_objs.layout.Annotation( text=format_text, x=self.x[m] - self.annotation_offset, y=self.y[n], xref="x1", yref="y1", align="left", xanchor="left", font=dict(color=font_color), showarrow=False, ) ) return annotations
[ "def", "make_table_annotations", "(", "self", ")", ":", "table_matrix", "=", "_Table", ".", "get_table_matrix", "(", "self", ")", "all_font_colors", "=", "_Table", ".", "get_table_font_color", "(", "self", ")", "annotations", "=", "[", "]", "for", "n", ",", "row", "in", "enumerate", "(", "self", ".", "table_text", ")", ":", "for", "m", ",", "val", "in", "enumerate", "(", "row", ")", ":", "# Bold text in header and index", "format_text", "=", "(", "\"<b>\"", "+", "str", "(", "val", ")", "+", "\"</b>\"", "if", "n", "==", "0", "or", "self", ".", "index", "and", "m", "<", "1", "else", "str", "(", "val", ")", ")", "# Match font color of index to font color of header", "font_color", "=", "(", "self", ".", "font_colors", "[", "0", "]", "if", "self", ".", "index", "and", "m", "==", "0", "else", "all_font_colors", "[", "n", "]", ")", "annotations", ".", "append", "(", "graph_objs", ".", "layout", ".", "Annotation", "(", "text", "=", "format_text", ",", "x", "=", "self", ".", "x", "[", "m", "]", "-", "self", ".", "annotation_offset", ",", "y", "=", "self", ".", "y", "[", "n", "]", ",", "xref", "=", "\"x1\"", ",", "yref", "=", "\"y1\"", ",", "align", "=", "\"left\"", ",", "xanchor", "=", "\"left\"", ",", "font", "=", "dict", "(", "color", "=", "font_color", ")", ",", "showarrow", "=", "False", ",", ")", ")", "return", "annotations" ]
[ 247, 4 ]
[ 282, 26 ]
python
en
['en', 'error', 'th']
False
_get_menu_prototype
(caller)
Return currently active menu prototype.
Return currently active menu prototype.
def _get_menu_prototype(caller): """Return currently active menu prototype.""" prototype = None if hasattr(caller.ndb._menutree, "olc_prototype"): prototype = caller.ndb._menutree.olc_prototype if not prototype: caller.ndb._menutree.olc_prototype = prototype = {} caller.ndb._menutree.olc_new = True return prototype
[ "def", "_get_menu_prototype", "(", "caller", ")", ":", "prototype", "=", "None", "if", "hasattr", "(", "caller", ".", "ndb", ".", "_menutree", ",", "\"olc_prototype\"", ")", ":", "prototype", "=", "caller", ".", "ndb", ".", "_menutree", ".", "olc_prototype", "if", "not", "prototype", ":", "caller", ".", "ndb", ".", "_menutree", ".", "olc_prototype", "=", "prototype", "=", "{", "}", "caller", ".", "ndb", ".", "_menutree", ".", "olc_new", "=", "True", "return", "prototype" ]
[ 36, 0 ]
[ 44, 20 ]
python
en
['en', 'nl', 'en']
True
_get_flat_menu_prototype
(caller, refresh=False, validate=False)
Return prototype where parent values are included
Return prototype where parent values are included
def _get_flat_menu_prototype(caller, refresh=False, validate=False): """Return prototype where parent values are included""" flat_prototype = None if not refresh and hasattr(caller.ndb._menutree, "olc_flat_prototype"): flat_prototype = caller.ndb._menutree.olc_flat_prototype if not flat_prototype: prot = _get_menu_prototype(caller) caller.ndb._menutree.olc_flat_prototype = \ flat_prototype = spawner.flatten_prototype(prot, validate=validate) return flat_prototype
[ "def", "_get_flat_menu_prototype", "(", "caller", ",", "refresh", "=", "False", ",", "validate", "=", "False", ")", ":", "flat_prototype", "=", "None", "if", "not", "refresh", "and", "hasattr", "(", "caller", ".", "ndb", ".", "_menutree", ",", "\"olc_flat_prototype\"", ")", ":", "flat_prototype", "=", "caller", ".", "ndb", ".", "_menutree", ".", "olc_flat_prototype", "if", "not", "flat_prototype", ":", "prot", "=", "_get_menu_prototype", "(", "caller", ")", "caller", ".", "ndb", ".", "_menutree", ".", "olc_flat_prototype", "=", "flat_prototype", "=", "spawner", ".", "flatten_prototype", "(", "prot", ",", "validate", "=", "validate", ")", "return", "flat_prototype" ]
[ 47, 0 ]
[ 56, 25 ]
python
en
['en', 'en', 'en']
True
_get_unchanged_inherited
(caller, protname)
Return prototype values inherited from parent(s), which are not replaced in child
Return prototype values inherited from parent(s), which are not replaced in child
def _get_unchanged_inherited(caller, protname): """Return prototype values inherited from parent(s), which are not replaced in child""" prototype = _get_menu_prototype(caller) if protname in prototype: return protname[protname], False else: flattened = _get_flat_menu_prototype(caller) if protname in flattened: return protname[protname], True return None, False
[ "def", "_get_unchanged_inherited", "(", "caller", ",", "protname", ")", ":", "prototype", "=", "_get_menu_prototype", "(", "caller", ")", "if", "protname", "in", "prototype", ":", "return", "protname", "[", "protname", "]", ",", "False", "else", ":", "flattened", "=", "_get_flat_menu_prototype", "(", "caller", ")", "if", "protname", "in", "flattened", ":", "return", "protname", "[", "protname", "]", ",", "True", "return", "None", ",", "False" ]
[ 59, 0 ]
[ 68, 22 ]
python
en
['en', 'en', 'en']
True
_set_menu_prototype
(caller, prototype)
Set the prototype with existing one
Set the prototype with existing one
def _set_menu_prototype(caller, prototype): """Set the prototype with existing one""" caller.ndb._menutree.olc_prototype = prototype caller.ndb._menutree.olc_new = False return prototype
[ "def", "_set_menu_prototype", "(", "caller", ",", "prototype", ")", ":", "caller", ".", "ndb", ".", "_menutree", ".", "olc_prototype", "=", "prototype", "caller", ".", "ndb", ".", "_menutree", ".", "olc_new", "=", "False", "return", "prototype" ]
[ 71, 0 ]
[ 75, 20 ]
python
en
['en', 'en', 'en']
True
_is_new_prototype
(caller)
Check if prototype is marked as new or was loaded from a saved one.
Check if prototype is marked as new or was loaded from a saved one.
def _is_new_prototype(caller): """Check if prototype is marked as new or was loaded from a saved one.""" return hasattr(caller.ndb._menutree, "olc_new")
[ "def", "_is_new_prototype", "(", "caller", ")", ":", "return", "hasattr", "(", "caller", ".", "ndb", ".", "_menutree", ",", "\"olc_new\"", ")" ]
[ 78, 0 ]
[ 80, 51 ]
python
en
['en', 'en', 'en']
True
_format_option_value
(prop, required=False, prototype=None, cropper=None)
Format wizard option values. Args: prop (str): Name or value to format. required (bool, optional): The option is required. prototype (dict, optional): If given, `prop` will be considered a key in this prototype. cropper (callable, optional): A function to crop the value to a certain width. Returns: value (str): The formatted value.
Format wizard option values.
def _format_option_value(prop, required=False, prototype=None, cropper=None): """ Format wizard option values. Args: prop (str): Name or value to format. required (bool, optional): The option is required. prototype (dict, optional): If given, `prop` will be considered a key in this prototype. cropper (callable, optional): A function to crop the value to a certain width. Returns: value (str): The formatted value. """ if prototype is not None: prop = prototype.get(prop, '') out = prop if callable(prop): if hasattr(prop, '__name__'): out = "<{}>".format(prop.__name__) else: out = repr(prop) if utils.is_iter(prop): out = ", ".join(str(pr) for pr in prop) if not out and required: out = "|rrequired" if out: return " ({}|n)".format(cropper(out) if cropper else utils.crop(out, _MENU_CROP_WIDTH)) return ""
[ "def", "_format_option_value", "(", "prop", ",", "required", "=", "False", ",", "prototype", "=", "None", ",", "cropper", "=", "None", ")", ":", "if", "prototype", "is", "not", "None", ":", "prop", "=", "prototype", ".", "get", "(", "prop", ",", "''", ")", "out", "=", "prop", "if", "callable", "(", "prop", ")", ":", "if", "hasattr", "(", "prop", ",", "'__name__'", ")", ":", "out", "=", "\"<{}>\"", ".", "format", "(", "prop", ".", "__name__", ")", "else", ":", "out", "=", "repr", "(", "prop", ")", "if", "utils", ".", "is_iter", "(", "prop", ")", ":", "out", "=", "\", \"", ".", "join", "(", "str", "(", "pr", ")", "for", "pr", "in", "prop", ")", "if", "not", "out", "and", "required", ":", "out", "=", "\"|rrequired\"", "if", "out", ":", "return", "\" ({}|n)\"", ".", "format", "(", "cropper", "(", "out", ")", "if", "cropper", "else", "utils", ".", "crop", "(", "out", ",", "_MENU_CROP_WIDTH", ")", ")", "return", "\"\"" ]
[ 83, 0 ]
[ 111, 13 ]
python
en
['en', 'error', 'th']
False
_set_prototype_value
(caller, field, value, parse=True)
Set prototype's field in a safe way.
Set prototype's field in a safe way.
def _set_prototype_value(caller, field, value, parse=True): """Set prototype's field in a safe way.""" prototype = _get_menu_prototype(caller) prototype[field] = value caller.ndb._menutree.olc_prototype = prototype return prototype
[ "def", "_set_prototype_value", "(", "caller", ",", "field", ",", "value", ",", "parse", "=", "True", ")", ":", "prototype", "=", "_get_menu_prototype", "(", "caller", ")", "prototype", "[", "field", "]", "=", "value", "caller", ".", "ndb", ".", "_menutree", ".", "olc_prototype", "=", "prototype", "return", "prototype" ]
[ 114, 0 ]
[ 119, 20 ]
python
en
['en', 'en', 'en']
True
_set_property
(caller, raw_string, **kwargs)
Add or update a property. To be called by the 'goto' option variable. Args: caller (Object, Account): The user of the wizard. raw_string (str): Input from user on given node - the new value to set. Kwargs: test_parse (bool): If set (default True), parse raw_string for protfuncs and obj-refs and try to run result through literal_eval. The parser will be run in 'testing' mode and any parsing errors will shown to the user. Note that this is just for testing, the original given string will be what is inserted. prop (str): Property name to edit with `raw_string`. processor (callable): Converts `raw_string` to a form suitable for saving. next_node (str): Where to redirect to after this has run. Returns: next_node (str): Next node to go to.
Add or update a property. To be called by the 'goto' option variable.
def _set_property(caller, raw_string, **kwargs): """ Add or update a property. To be called by the 'goto' option variable. Args: caller (Object, Account): The user of the wizard. raw_string (str): Input from user on given node - the new value to set. Kwargs: test_parse (bool): If set (default True), parse raw_string for protfuncs and obj-refs and try to run result through literal_eval. The parser will be run in 'testing' mode and any parsing errors will shown to the user. Note that this is just for testing, the original given string will be what is inserted. prop (str): Property name to edit with `raw_string`. processor (callable): Converts `raw_string` to a form suitable for saving. next_node (str): Where to redirect to after this has run. Returns: next_node (str): Next node to go to. """ prop = kwargs.get("prop", "prototype_key") processor = kwargs.get("processor", None) next_node = kwargs.get("next_node", None) if callable(processor): try: value = processor(raw_string) except Exception as err: caller.msg("Could not set {prop} to {value} ({err})".format( prop=prop.replace("_", "-").capitalize(), value=raw_string, err=str(err))) # this means we'll re-run the current node. return None else: value = raw_string if not value: return next_node prototype = _set_prototype_value(caller, prop, value) caller.ndb._menutree.olc_prototype = prototype try: # TODO simple way to get rid of the u'' markers in list reprs, remove this when on py3. repr_value = json.dumps(value) except Exception: repr_value = value out = [" Set {prop} to {value} ({typ}).".format(prop=prop, value=repr_value, typ=type(value))] if kwargs.get("test_parse", True): out.append(" Simulating prototype-func parsing ...") err, parsed_value = protlib.protfunc_parser(value, testing=True) if err: out.append(" |yPython `literal_eval` warning: {}|n".format(err)) if parsed_value != value: out.append(" |g(Example-)value when parsed ({}):|n {}".format( type(parsed_value), parsed_value)) else: out.append(" |gNo change when parsed.") caller.msg("\n".join(out)) return next_node
[ "def", "_set_property", "(", "caller", ",", "raw_string", ",", "*", "*", "kwargs", ")", ":", "prop", "=", "kwargs", ".", "get", "(", "\"prop\"", ",", "\"prototype_key\"", ")", "processor", "=", "kwargs", ".", "get", "(", "\"processor\"", ",", "None", ")", "next_node", "=", "kwargs", ".", "get", "(", "\"next_node\"", ",", "None", ")", "if", "callable", "(", "processor", ")", ":", "try", ":", "value", "=", "processor", "(", "raw_string", ")", "except", "Exception", "as", "err", ":", "caller", ".", "msg", "(", "\"Could not set {prop} to {value} ({err})\"", ".", "format", "(", "prop", "=", "prop", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", ".", "capitalize", "(", ")", ",", "value", "=", "raw_string", ",", "err", "=", "str", "(", "err", ")", ")", ")", "# this means we'll re-run the current node.", "return", "None", "else", ":", "value", "=", "raw_string", "if", "not", "value", ":", "return", "next_node", "prototype", "=", "_set_prototype_value", "(", "caller", ",", "prop", ",", "value", ")", "caller", ".", "ndb", ".", "_menutree", ".", "olc_prototype", "=", "prototype", "try", ":", "# TODO simple way to get rid of the u'' markers in list reprs, remove this when on py3.", "repr_value", "=", "json", ".", "dumps", "(", "value", ")", "except", "Exception", ":", "repr_value", "=", "value", "out", "=", "[", "\" Set {prop} to {value} ({typ}).\"", ".", "format", "(", "prop", "=", "prop", ",", "value", "=", "repr_value", ",", "typ", "=", "type", "(", "value", ")", ")", "]", "if", "kwargs", ".", "get", "(", "\"test_parse\"", ",", "True", ")", ":", "out", ".", "append", "(", "\" Simulating prototype-func parsing ...\"", ")", "err", ",", "parsed_value", "=", "protlib", ".", "protfunc_parser", "(", "value", ",", "testing", "=", "True", ")", "if", "err", ":", "out", ".", "append", "(", "\" |yPython `literal_eval` warning: {}|n\"", ".", "format", "(", "err", ")", ")", "if", "parsed_value", "!=", "value", ":", "out", ".", "append", "(", "\" |g(Example-)value when parsed ({}):|n {}\"", ".", "format", "(", "type", "(", "parsed_value", ")", ",", "parsed_value", ")", ")", "else", ":", "out", ".", "append", "(", "\" |gNo change when parsed.\"", ")", "caller", ".", "msg", "(", "\"\\n\"", ".", "join", "(", "out", ")", ")", "return", "next_node" ]
[ 122, 0 ]
[ 185, 20 ]
python
en
['en', 'error', 'th']
False
_wizard_options
(curr_node, prev_node, next_node, color="|W", search=False)
Creates default navigation options available in the wizard.
Creates default navigation options available in the wizard.
def _wizard_options(curr_node, prev_node, next_node, color="|W", search=False): """Creates default navigation options available in the wizard.""" options = [] if prev_node: options.append({"key": ("|wB|Wack", "b"), "desc": "{color}({node})|n".format( color=color, node=prev_node.replace("_", "-")), "goto": "node_{}".format(prev_node)}) if next_node: options.append({"key": ("|wF|Worward", "f"), "desc": "{color}({node})|n".format( color=color, node=next_node.replace("_", "-")), "goto": "node_{}".format(next_node)}) options.append({"key": ("|wI|Wndex", "i"), "goto": "node_index"}) if curr_node: options.append({"key": ("|wV|Walidate prototype", "validate", "v"), "goto": ("node_validate_prototype", {"back": curr_node})}) if search: options.append({"key": ("|wSE|Warch objects", "search object", "search", "se"), "goto": ("node_search_object", {"back": curr_node})}) return options
[ "def", "_wizard_options", "(", "curr_node", ",", "prev_node", ",", "next_node", ",", "color", "=", "\"|W\"", ",", "search", "=", "False", ")", ":", "options", "=", "[", "]", "if", "prev_node", ":", "options", ".", "append", "(", "{", "\"key\"", ":", "(", "\"|wB|Wack\"", ",", "\"b\"", ")", ",", "\"desc\"", ":", "\"{color}({node})|n\"", ".", "format", "(", "color", "=", "color", ",", "node", "=", "prev_node", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", ")", ",", "\"goto\"", ":", "\"node_{}\"", ".", "format", "(", "prev_node", ")", "}", ")", "if", "next_node", ":", "options", ".", "append", "(", "{", "\"key\"", ":", "(", "\"|wF|Worward\"", ",", "\"f\"", ")", ",", "\"desc\"", ":", "\"{color}({node})|n\"", ".", "format", "(", "color", "=", "color", ",", "node", "=", "next_node", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", ")", ",", "\"goto\"", ":", "\"node_{}\"", ".", "format", "(", "next_node", ")", "}", ")", "options", ".", "append", "(", "{", "\"key\"", ":", "(", "\"|wI|Wndex\"", ",", "\"i\"", ")", ",", "\"goto\"", ":", "\"node_index\"", "}", ")", "if", "curr_node", ":", "options", ".", "append", "(", "{", "\"key\"", ":", "(", "\"|wV|Walidate prototype\"", ",", "\"validate\"", ",", "\"v\"", ")", ",", "\"goto\"", ":", "(", "\"node_validate_prototype\"", ",", "{", "\"back\"", ":", "curr_node", "}", ")", "}", ")", "if", "search", ":", "options", ".", "append", "(", "{", "\"key\"", ":", "(", "\"|wSE|Warch objects\"", ",", "\"search object\"", ",", "\"search\"", ",", "\"se\"", ")", ",", "\"goto\"", ":", "(", "\"node_search_object\"", ",", "{", "\"back\"", ":", "curr_node", "}", ")", "}", ")", "return", "options" ]
[ 188, 0 ]
[ 212, 18 ]
python
en
['en', 'en', 'en']
True
_path_cropper
(pythonpath)
Crop path to only the last component
Crop path to only the last component
def _path_cropper(pythonpath): "Crop path to only the last component" return pythonpath.split('.')[-1]
[ "def", "_path_cropper", "(", "pythonpath", ")", ":", "return", "pythonpath", ".", "split", "(", "'.'", ")", "[", "-", "1", "]" ]
[ 219, 0 ]
[ 221, 36 ]
python
en
['en', 'en', 'en']
True
_validate_prototype
(prototype)
Run validation on prototype
Run validation on prototype
def _validate_prototype(prototype): """Run validation on prototype""" txt = protlib.prototype_to_str(prototype) errors = "\n\n|g No validation errors found.|n (but errors could still happen at spawn-time)" err = False try: # validate, don't spawn spawner.spawn(prototype, only_validate=True) except RuntimeError as err: errors = "\n\n|r{}|n".format(err) err = True except RuntimeWarning as err: errors = "\n\n|y{}|n".format(err) err = True text = (txt + errors) return err, text
[ "def", "_validate_prototype", "(", "prototype", ")", ":", "txt", "=", "protlib", ".", "prototype_to_str", "(", "prototype", ")", "errors", "=", "\"\\n\\n|g No validation errors found.|n (but errors could still happen at spawn-time)\"", "err", "=", "False", "try", ":", "# validate, don't spawn", "spawner", ".", "spawn", "(", "prototype", ",", "only_validate", "=", "True", ")", "except", "RuntimeError", "as", "err", ":", "errors", "=", "\"\\n\\n|r{}|n\"", ".", "format", "(", "err", ")", "err", "=", "True", "except", "RuntimeWarning", "as", "err", ":", "errors", "=", "\"\\n\\n|y{}|n\"", ".", "format", "(", "err", ")", "err", "=", "True", "text", "=", "(", "txt", "+", "errors", ")", "return", "err", ",", "text" ]
[ 224, 0 ]
[ 241, 20 ]
python
en
['en', 'fi', 'en']
True
_format_list_actions
(*args, **kwargs)
Create footer text for nodes with extra list actions Args: actions (str): Available actions. The first letter of the action name will be assumed to be a shortcut. Kwargs: prefix (str): Default prefix to use. Returns: string (str): Formatted footer for adding to the node text.
Create footer text for nodes with extra list actions
def _format_list_actions(*args, **kwargs): """Create footer text for nodes with extra list actions Args: actions (str): Available actions. The first letter of the action name will be assumed to be a shortcut. Kwargs: prefix (str): Default prefix to use. Returns: string (str): Formatted footer for adding to the node text. """ actions = [] prefix = kwargs.get('prefix', "|WSelect with |w<num>|W. Other actions:|n ") for action in args: actions.append("|w{}|n|W{} |w<num>|n".format(action[0], action[1:])) return prefix + " |W|||n ".join(actions)
[ "def", "_format_list_actions", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "actions", "=", "[", "]", "prefix", "=", "kwargs", ".", "get", "(", "'prefix'", ",", "\"|WSelect with |w<num>|W. Other actions:|n \"", ")", "for", "action", "in", "args", ":", "actions", ".", "append", "(", "\"|w{}|n|W{} |w<num>|n\"", ".", "format", "(", "action", "[", "0", "]", ",", "action", "[", "1", ":", "]", ")", ")", "return", "prefix", "+", "\" |W|||n \"", ".", "join", "(", "actions", ")" ]
[ 267, 0 ]
[ 283, 44 ]
python
en
['en', 'en', 'en']
True