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
_called_with_wrong_args
(f)
Check whether calling a function raised a ``TypeError`` because the call failed or because something in the function raised the error. :param f: The function that was called. :return: ``True`` if the call failed.
Check whether calling a function raised a ``TypeError`` because the call failed or because something in the function raised the error.
def _called_with_wrong_args(f): """Check whether calling a function raised a ``TypeError`` because the call failed or because something in the function raised the error. :param f: The function that was called. :return: ``True`` if the call failed. """ tb = sys.exc_info()[2] try: ...
[ "def", "_called_with_wrong_args", "(", "f", ")", ":", "tb", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "try", ":", "while", "tb", "is", "not", "None", ":", "if", "tb", ".", "tb_frame", ".", "f_code", "is", "f", ".", "__code__", ":", "#...
[ 323, 0 ]
[ 346, 14 ]
python
en
['en', 'en', 'en']
True
http_date
(timestamp=None)
Return the current date and time formatted for a message header.
Return the current date and time formatted for a message header.
def http_date(timestamp=None): """Return the current date and time formatted for a message header.""" if timestamp is None: timestamp = time.time() s = email.utils.formatdate(timestamp, localtime=False, usegmt=True) return s
[ "def", "http_date", "(", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "time", ".", "time", "(", ")", "s", "=", "email", ".", "utils", ".", "formatdate", "(", "timestamp", ",", "localtime", "=", "False", ...
[ 446, 0 ]
[ 451, 12 ]
python
en
['en', 'en', 'en']
True
daemonize
(enable_stdio_inheritance=False)
\ Standard daemonization of a process. http://www.svbug.com/documentation/comp.unix.programmer-FAQ/faq_2.html#SEC16
\ Standard daemonization of a process. http://www.svbug.com/documentation/comp.unix.programmer-FAQ/faq_2.html#SEC16
def daemonize(enable_stdio_inheritance=False): """\ Standard daemonization of a process. http://www.svbug.com/documentation/comp.unix.programmer-FAQ/faq_2.html#SEC16 """ if 'GUNICORN_FD' not in os.environ: if os.fork(): os._exit(0) os.setsid() if os.fork(): ...
[ "def", "daemonize", "(", "enable_stdio_inheritance", "=", "False", ")", ":", "if", "'GUNICORN_FD'", "not", "in", "os", ".", "environ", ":", "if", "os", ".", "fork", "(", ")", ":", "os", ".", "_exit", "(", "0", ")", "os", ".", "setsid", "(", ")", "i...
[ 458, 0 ]
[ 538, 35 ]
python
en
['en', 'ja', 'hi']
False
to_bytestring
(value, encoding="utf8")
Converts a string argument to a byte string
Converts a string argument to a byte string
def to_bytestring(value, encoding="utf8"): """Converts a string argument to a byte string""" if isinstance(value, bytes): return value if not isinstance(value, str): raise TypeError('%r is not a string' % value) return value.encode(encoding)
[ "def", "to_bytestring", "(", "value", ",", "encoding", "=", "\"utf8\"", ")", ":", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "return", "value", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "raise", "TypeError", "(", "'%...
[ 556, 0 ]
[ 563, 33 ]
python
en
['en', 'en', 'en']
True
get_app_template_dirs
(dirname)
Return an iterable of paths of directories to load app templates from. dirname is the name of the subdirectory containing templates inside installed applications.
Return an iterable of paths of directories to load app templates from.
def get_app_template_dirs(dirname): """ Return an iterable of paths of directories to load app templates from. dirname is the name of the subdirectory containing templates inside installed applications. """ template_dirs = [] for app_config in apps.get_app_configs(): if not app_conf...
[ "def", "get_app_template_dirs", "(", "dirname", ")", ":", "template_dirs", "=", "[", "]", "for", "app_config", "in", "apps", ".", "get_app_configs", "(", ")", ":", "if", "not", "app_config", ".", "path", ":", "continue", "template_dir", "=", "os", ".", "pa...
[ 92, 0 ]
[ 107, 31 ]
python
en
['en', 'error', 'th']
False
EngineHandler.__init__
(self, templates=None)
templates is an optional list of template engine definitions (structured like settings.TEMPLATES).
templates is an optional list of template engine definitions (structured like settings.TEMPLATES).
def __init__(self, templates=None): """ templates is an optional list of template engine definitions (structured like settings.TEMPLATES). """ self._templates = templates self._engines = {}
[ "def", "__init__", "(", "self", ",", "templates", "=", "None", ")", ":", "self", ".", "_templates", "=", "templates", "self", ".", "_engines", "=", "{", "}" ]
[ 17, 4 ]
[ 23, 26 ]
python
en
['en', 'error', 'th']
False
EditMessageSideEffectsTest._login_and_send_original_stream_message
( self, content: str, enable_online_push_notifications: bool = False )
Note our conventions here: Hamlet is our logged in user (and sender). Cordelia is the receiver we care about. Scotland is the stream we send messages to.
Note our conventions here:
def _login_and_send_original_stream_message( self, content: str, enable_online_push_notifications: bool = False ) -> int: """ Note our conventions here: Hamlet is our logged in user (and sender). Cordelia is the receiver we care about. Scotland is the str...
[ "def", "_login_and_send_original_stream_message", "(", "self", ",", "content", ":", "str", ",", "enable_online_push_notifications", ":", "bool", "=", "False", ")", "->", "int", ":", "hamlet", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "cordelia", ...
[ 45, 4 ]
[ 71, 25 ]
python
en
['en', 'error', 'th']
False
EditMessageSideEffectsTest._get_queued_data_for_message_update
( self, message_id: int, content: str, expect_short_circuit: bool = False )
This function updates a message with a post to /json/messages/(message_id). By using mocks, we are able to capture two pieces of data: enqueue_kwargs: These are the arguments passed in to maybe_enqueue_notifications. queue_messages: These a...
This function updates a message with a post to /json/messages/(message_id).
def _get_queued_data_for_message_update( self, message_id: int, content: str, expect_short_circuit: bool = False ) -> Dict[str, Any]: """ This function updates a message with a post to /json/messages/(message_id). By using mocks, we are able to capture two pieces of data: ...
[ "def", "_get_queued_data_for_message_update", "(", "self", ",", "message_id", ":", "int", ",", "content", ":", "str", ",", "expect_short_circuit", ":", "bool", "=", "False", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "url", "=", "\"/json/messages/\...
[ 73, 4 ]
[ 139, 9 ]
python
en
['en', 'error', 'th']
False
EditMessageSideEffectsTest._turn_on_stream_push_for_cordelia
(self)
conventions: Cordelia is the message receiver we care about. Scotland is our stream.
conventions: Cordelia is the message receiver we care about. Scotland is our stream.
def _turn_on_stream_push_for_cordelia(self) -> None: """ conventions: Cordelia is the message receiver we care about. Scotland is our stream. """ cordelia = self.example_user("cordelia") stream = self.subscribe(cordelia, "Scotland") recipient = str...
[ "def", "_turn_on_stream_push_for_cordelia", "(", "self", ")", "->", "None", ":", "cordelia", "=", "self", ".", "example_user", "(", "\"cordelia\"", ")", "stream", "=", "self", ".", "subscribe", "(", "cordelia", ",", "\"Scotland\"", ")", "recipient", "=", "stre...
[ 217, 4 ]
[ 231, 36 ]
python
en
['en', 'error', 'th']
False
EditMessageSideEffectsTest._cordelia_connected_to_zulip
(self)
Right now the easiest way to make Cordelia look connected to Zulip is to mock the function below. This is a bit blunt, as it affects other users too, but we only really look at Cordelia's data, anyway.
Right now the easiest way to make Cordelia look connected to Zulip is to mock the function below.
def _cordelia_connected_to_zulip(self) -> Any: """ Right now the easiest way to make Cordelia look connected to Zulip is to mock the function below. This is a bit blunt, as it affects other users too, but we only really look at Cordelia's data, anyway. """ return...
[ "def", "_cordelia_connected_to_zulip", "(", "self", ")", "->", "Any", ":", "return", "mock", ".", "patch", "(", "\"zerver.tornado.event_queue.receiver_is_off_zulip\"", ",", "return_value", "=", "False", ",", ")" ]
[ 243, 4 ]
[ 254, 9 ]
python
en
['en', 'error', 'th']
False
ApiritifScriptGenerator._gen_replace_dialogs
(self)
Generates the call to DialogsManager to replace dialogs
Generates the call to DialogsManager to replace dialogs
def _gen_replace_dialogs(self): """ Generates the call to DialogsManager to replace dialogs """ method = "dialogs_replace" self.selenium_extras.add(method) return [ gen_empty_line_stmt(), ast_call( func=ast_attr(method)) ]
[ "def", "_gen_replace_dialogs", "(", "self", ")", ":", "method", "=", "\"dialogs_replace\"", "self", ".", "selenium_extras", ".", "add", "(", "method", ")", "return", "[", "gen_empty_line_stmt", "(", ")", ",", "ast_call", "(", "func", "=", "ast_attr", "(", "m...
[ 816, 4 ]
[ 826, 9 ]
python
en
['en', 'error', 'th']
False
new_date
(d)
Generate a safe date from a datetime.date object.
Generate a safe date from a datetime.date object.
def new_date(d): "Generate a safe date from a datetime.date object." return date(d.year, d.month, d.day)
[ "def", "new_date", "(", "d", ")", ":", "return", "date", "(", "d", ".", "year", ",", "d", ".", "month", ",", "d", ".", "day", ")" ]
[ 39, 0 ]
[ 41, 39 ]
python
en
['en', 'en', 'en']
True
new_datetime
(d)
Generate a safe datetime from a datetime.date or datetime.datetime object.
Generate a safe datetime from a datetime.date or datetime.datetime object.
def new_datetime(d): """ Generate a safe datetime from a datetime.date or datetime.datetime object. """ kw = [d.year, d.month, d.day] if isinstance(d, real_datetime): kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo]) return datetime(*kw)
[ "def", "new_datetime", "(", "d", ")", ":", "kw", "=", "[", "d", ".", "year", ",", "d", ".", "month", ",", "d", ".", "day", "]", "if", "isinstance", "(", "d", ",", "real_datetime", ")", ":", "kw", ".", "extend", "(", "[", "d", ".", "hour", ","...
[ 44, 0 ]
[ 51, 24 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_table_list
(self, cursor)
Returns a list of table and view names in the current database.
Returns a list of table and view names in the current database.
def get_table_list(self, cursor): """ Returns a list of table and view names in the current database. """ cursor.execute("SELECT TABLE_NAME, 't' FROM USER_TABLES UNION ALL " "SELECT VIEW_NAME, 'v' FROM USER_VIEWS") return [TableInfo(row[0].lower(), row[1]) ...
[ "def", "get_table_list", "(", "self", ",", "cursor", ")", ":", "cursor", ".", "execute", "(", "\"SELECT TABLE_NAME, 't' FROM USER_TABLES UNION ALL \"", "\"SELECT VIEW_NAME, 'v' FROM USER_VIEWS\"", ")", "return", "[", "TableInfo", "(", "row", "[", "0", "]", ".", "lower...
[ 45, 4 ]
[ 51, 79 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_table_description
(self, cursor, table_name)
Returns a description of the table, with the DB-API cursor.description interface.
Returns a description of the table, with the DB-API cursor.description interface.
def get_table_description(self, cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." # user_tab_columns gives data default for columns cursor.execute(""" SELECT column_name, data_default, ...
[ "def", "get_table_description", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "# user_tab_columns gives data default for columns", "cursor", ".", "execute", "(", "\"\"\"\n SELECT\n column_name,\n data_default,\n CASE\n ...
[ 53, 4 ]
[ 86, 26 ]
python
en
['en', 'fr', 'en']
True
DatabaseIntrospection.table_name_converter
(self, name)
Table name comparison is case insensitive under Oracle
Table name comparison is case insensitive under Oracle
def table_name_converter(self, name): "Table name comparison is case insensitive under Oracle" return name.lower()
[ "def", "table_name_converter", "(", "self", ",", "name", ")", ":", "return", "name", ".", "lower", "(", ")" ]
[ 88, 4 ]
[ 90, 27 ]
python
en
['en', 'en', 'en']
True
DatabaseIntrospection._name_to_index
(self, cursor, table_name)
Returns a dictionary of {field_name: field_index} for the given table. Indexes are 0-based.
Returns a dictionary of {field_name: field_index} for the given table. Indexes are 0-based.
def _name_to_index(self, cursor, table_name): """ Returns a dictionary of {field_name: field_index} for the given table. Indexes are 0-based. """ return {d[0]: i for i, d in enumerate(self.get_table_description(cursor, table_name))}
[ "def", "_name_to_index", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "return", "{", "d", "[", "0", "]", ":", "i", "for", "i", ",", "d", "in", "enumerate", "(", "self", ".", "get_table_description", "(", "cursor", ",", "table_name", ")", ...
[ 92, 4 ]
[ 97, 94 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_relations
(self, cursor, table_name)
Returns a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table.
Returns a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table.
def get_relations(self, cursor, table_name): """ Returns a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table. """ table_name = table_name.upper() cursor.execute(""" SELECT ta.column_name, tb.table_name,...
[ "def", "get_relations", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "table_name", "=", "table_name", ".", "upper", "(", ")", "cursor", ".", "execute", "(", "\"\"\"\n SELECT ta.column_name, tb.table_name, tb.column_name\n FROM user_constraints, USER_CONS...
[ 99, 4 ]
[ 122, 24 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_constraints
(self, cursor, table_name)
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
def get_constraints(self, cursor, table_name): """ Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Loop over the constraints, getting PKs, uniques, and checks cursor.execute(""" SELECT ...
[ "def", "get_constraints", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "constraints", "=", "{", "}", "# Loop over the constraints, getting PKs, uniques, and checks", "cursor", ".", "execute", "(", "\"\"\"\n SELECT\n user_constraints.constra...
[ 170, 4 ]
[ 287, 26 ]
python
en
['en', 'error', 'th']
False
make_msgid
(idstring=None, domain=None)
Returns a string suitable for RFC 5322 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. Optional domain if given provides the portion of the message id after the '@'. It defa...
Returns a string suitable for RFC 5322 compliant Message-ID, e.g:
def make_msgid(idstring=None, domain=None): """Returns a string suitable for RFC 5322 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. Optional domain if given provides the ...
[ "def", "make_msgid", "(", "idstring", "=", "None", ",", "domain", "=", "None", ")", ":", "timeval", "=", "time", ".", "time", "(", ")", "utcdate", "=", "time", ".", "strftime", "(", "'%Y%m%d%H%M%S'", ",", "time", ".", "gmtime", "(", "timeval", ")", "...
[ 45, 0 ]
[ 67, 16 ]
python
en
['en', 'en', 'en']
True
forbid_multi_line_headers
(name, val, encoding)
Forbids multi-line headers, to prevent header injection.
Forbids multi-line headers, to prevent header injection.
def forbid_multi_line_headers(name, val, encoding): """Forbids multi-line headers, to prevent header injection.""" encoding = encoding or settings.DEFAULT_CHARSET val = force_text(val) if '\n' in val or '\r' in val: raise BadHeaderError("Header values can't contain newlines (got %r for header %r...
[ "def", "forbid_multi_line_headers", "(", "name", ",", "val", ",", "encoding", ")", ":", "encoding", "=", "encoding", "or", "settings", ".", "DEFAULT_CHARSET", "val", "=", "force_text", "(", "val", ")", "if", "'\\n'", "in", "val", "or", "'\\r'", "in", "val"...
[ 86, 0 ]
[ 102, 25 ]
python
en
['nb', 'en', 'en']
True
split_addr
(addr, encoding)
Split the address into local part and domain, properly encoded. When non-ascii characters are present in the local part, it must be MIME-word encoded. The domain name must be idna-encoded if it contains non-ascii characters.
Split the address into local part and domain, properly encoded.
def split_addr(addr, encoding): """ Split the address into local part and domain, properly encoded. When non-ascii characters are present in the local part, it must be MIME-word encoded. The domain name must be idna-encoded if it contains non-ascii characters. """ if '@' in addr: lo...
[ "def", "split_addr", "(", "addr", ",", "encoding", ")", ":", "if", "'@'", "in", "addr", ":", "localpart", ",", "domain", "=", "addr", ".", "split", "(", "'@'", ",", "1", ")", "# Try to get the simplest encoding - ascii if possible so that", "# to@example.com doesn...
[ 105, 0 ]
[ 126, 30 ]
python
en
['en', 'error', 'th']
False
sanitize_address
(addr, encoding)
Format a pair of (name, address) or an email address string.
Format a pair of (name, address) or an email address string.
def sanitize_address(addr, encoding): """ Format a pair of (name, address) or an email address string. """ if not isinstance(addr, tuple): addr = parseaddr(force_text(addr)) nm, addr = addr localpart, domain = None, None nm = Header(nm, encoding).encode() try: addr.encode...
[ "def", "sanitize_address", "(", "addr", ",", "encoding", ")", ":", "if", "not", "isinstance", "(", "addr", ",", "tuple", ")", ":", "addr", "=", "parseaddr", "(", "force_text", "(", "addr", ")", ")", "nm", ",", "addr", "=", "addr", "localpart", ",", "...
[ 129, 0 ]
[ 164, 23 ]
python
en
['en', 'error', 'th']
False
MIMEMixin.as_string
(self, unixfrom=False, linesep='\n')
Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '. See bug #13433 for details.
Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header.
def as_string(self, unixfrom=False, linesep='\n'): """Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '. ...
[ "def", "as_string", "(", "self", ",", "unixfrom", "=", "False", ",", "linesep", "=", "'\\n'", ")", ":", "fp", "=", "six", ".", "StringIO", "(", ")", "g", "=", "generator", ".", "Generator", "(", "fp", ",", "mangle_from_", "=", "False", ")", "if", "...
[ 168, 4 ]
[ 182, 28 ]
python
en
['en', 'en', 'en']
True
EmailMessage.__init__
(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, cc=None, reply_to=None)
Initialize a single email message (which can be sent to multiple recipients). All strings used to create the message can be unicode strings (or UTF-8 bytestrings). The SafeMIMEText class will handle any necessary encoding conversions.
Initialize a single email message (which can be sent to multiple recipients).
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, cc=None, reply_to=None): """ Initialize a single email message (which can be sent to multiple recipients). All strings used to c...
[ "def", "__init__", "(", "self", ",", "subject", "=", "''", ",", "body", "=", "''", ",", "from_email", "=", "None", ",", "to", "=", "None", ",", "bcc", "=", "None", ",", "connection", "=", "None", ",", "attachments", "=", "None", ",", "headers", "="...
[ 250, 4 ]
[ 290, 36 ]
python
en
['en', 'error', 'th']
False
EmailMessage.recipients
(self)
Returns a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries).
Returns a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries).
def recipients(self): """ Returns a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries). """ return [email for email in (self.to + self.cc + self.bcc) if email]
[ "def", "recipients", "(", "self", ")", ":", "return", "[", "email", "for", "email", "in", "(", "self", ".", "to", "+", "self", ".", "cc", "+", "self", ".", "bcc", ")", "if", "email", "]" ]
[ 328, 4 ]
[ 333, 75 ]
python
en
['en', 'error', 'th']
False
EmailMessage.send
(self, fail_silently=False)
Sends the email message.
Sends the email message.
def send(self, fail_silently=False): """Sends the email message.""" if not self.recipients(): # Don't bother creating the network connection if there's nobody to # send to. return 0 return self.get_connection(fail_silently).send_messages([self])
[ "def", "send", "(", "self", ",", "fail_silently", "=", "False", ")", ":", "if", "not", "self", ".", "recipients", "(", ")", ":", "# Don't bother creating the network connection if there's nobody to", "# send to.", "return", "0", "return", "self", ".", "get_connectio...
[ 335, 4 ]
[ 341, 71 ]
python
en
['en', 'en', 'en']
True
EmailMessage.attach
(self, filename=None, content=None, mimetype=None)
Attaches a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass it is inserted directly into the resulting message attachments. For a text/* mimetype (guessed or specif...
Attaches a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided.
def attach(self, filename=None, content=None, mimetype=None): """ Attaches a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass it is inserted directly into the resulti...
[ "def", "attach", "(", "self", ",", "filename", "=", "None", ",", "content", "=", "None", ",", "mimetype", "=", "None", ")", ":", "if", "isinstance", "(", "filename", ",", "MIMEBase", ")", ":", "assert", "content", "is", "None", "assert", "mimetype", "i...
[ 343, 4 ]
[ 378, 66 ]
python
en
['en', 'error', 'th']
False
EmailMessage.attach_file
(self, path, mimetype=None)
Attaches a file from the filesystem. The mimetype will be set to the DEFAULT_ATTACHMENT_MIME_TYPE if it is not specified and cannot be guessed. For a text/* mimetype (guessed or specified), the file's content will be decoded as UTF-8. If that fails, the mimetype will be set to...
Attaches a file from the filesystem.
def attach_file(self, path, mimetype=None): """ Attaches a file from the filesystem. The mimetype will be set to the DEFAULT_ATTACHMENT_MIME_TYPE if it is not specified and cannot be guessed. For a text/* mimetype (guessed or specified), the file's content will be decod...
[ "def", "attach_file", "(", "self", ",", "path", ",", "mimetype", "=", "None", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "file", ":", "content", "=", "file",...
[ 380, 4 ]
[ 395, 52 ]
python
en
['en', 'error', 'th']
False
EmailMessage._create_mime_attachment
(self, content, mimetype)
Converts the content, mimetype pair into a MIME attachment object. If the mimetype is message/rfc822, content may be an email.Message or EmailMessage object, as well as a str.
Converts the content, mimetype pair into a MIME attachment object.
def _create_mime_attachment(self, content, mimetype): """ Converts the content, mimetype pair into a MIME attachment object. If the mimetype is message/rfc822, content may be an email.Message or EmailMessage object, as well as a str. """ basetype, subtype = mimetype.spli...
[ "def", "_create_mime_attachment", "(", "self", ",", "content", ",", "mimetype", ")", ":", "basetype", ",", "subtype", "=", "mimetype", ".", "split", "(", "'/'", ",", "1", ")", "if", "basetype", "==", "'text'", ":", "encoding", "=", "self", ".", "encoding...
[ 414, 4 ]
[ 442, 25 ]
python
en
['en', 'error', 'th']
False
EmailMessage._create_attachment
(self, filename, content, mimetype=None)
Converts the filename, content, mimetype triple into a MIME attachment object.
Converts the filename, content, mimetype triple into a MIME attachment object.
def _create_attachment(self, filename, content, mimetype=None): """ Converts the filename, content, mimetype triple into a MIME attachment object. """ attachment = self._create_mime_attachment(content, mimetype) if filename: try: filename.encod...
[ "def", "_create_attachment", "(", "self", ",", "filename", ",", "content", ",", "mimetype", "=", "None", ")", ":", "attachment", "=", "self", ".", "_create_mime_attachment", "(", "content", ",", "mimetype", ")", "if", "filename", ":", "try", ":", "filename",...
[ 444, 4 ]
[ 459, 25 ]
python
en
['en', 'error', 'th']
False
EmailMultiAlternatives.__init__
(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, alternatives=None, cc=None, reply_to=None)
Initialize a single email message (which can be sent to multiple recipients). All strings used to create the message can be unicode strings (or UTF-8 bytestrings). The SafeMIMEText class will handle any necessary encoding conversions.
Initialize a single email message (which can be sent to multiple recipients).
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, alternatives=None, cc=None, reply_to=None): """ Initialize a single email message (which can be sent to multiple recipients). Al...
[ "def", "__init__", "(", "self", ",", "subject", "=", "''", ",", "body", "=", "''", ",", "from_email", "=", "None", ",", "to", "=", "None", ",", "bcc", "=", "None", ",", "connection", "=", "None", ",", "attachments", "=", "None", ",", "headers", "="...
[ 470, 4 ]
[ 485, 46 ]
python
en
['en', 'error', 'th']
False
EmailMultiAlternatives.attach_alternative
(self, content, mimetype)
Attach an alternative content representation.
Attach an alternative content representation.
def attach_alternative(self, content, mimetype): """Attach an alternative content representation.""" assert content is not None assert mimetype is not None self.alternatives.append((content, mimetype))
[ "def", "attach_alternative", "(", "self", ",", "content", ",", "mimetype", ")", ":", "assert", "content", "is", "not", "None", "assert", "mimetype", "is", "not", "None", "self", ".", "alternatives", ".", "append", "(", "(", "content", ",", "mimetype", ")",...
[ 487, 4 ]
[ 491, 53 ]
python
en
['en', 'lb', 'en']
True
mapping
(data_source, geom_name='geom', layer_key=0, multi_geom=False)
Given a DataSource, generates a dictionary that may be used for invoking the LayerMapping utility. Keyword Arguments: `geom_name` => The name of the geometry field to use for the model. `layer_key` => The key for specifying which layer in the DataSource to use; defaults to 0 (the first l...
Given a DataSource, generates a dictionary that may be used for invoking the LayerMapping utility.
def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False): """ Given a DataSource, generates a dictionary that may be used for invoking the LayerMapping utility. Keyword Arguments: `geom_name` => The name of the geometry field to use for the model. `layer_key` => The key for ...
[ "def", "mapping", "(", "data_source", ",", "geom_name", "=", "'geom'", ",", "layer_key", "=", "0", ",", "multi_geom", "=", "False", ")", ":", "if", "isinstance", "(", "data_source", ",", "six", ".", "string_types", ")", ":", "# Instantiating the DataSource fro...
[ 14, 0 ]
[ 49, 19 ]
python
en
['en', 'error', 'th']
False
ogrinspect
(*args, **kwargs)
Given a data source (either a string or a DataSource object) and a string model name this function will generate a GeoDjango model. Usage: >>> from django.contrib.gis.utils import ogrinspect >>> ogrinspect('/path/to/shapefile.shp','NewModel') ...will print model definition to stout or p...
Given a data source (either a string or a DataSource object) and a string model name this function will generate a GeoDjango model.
def ogrinspect(*args, **kwargs): """ Given a data source (either a string or a DataSource object) and a string model name this function will generate a GeoDjango model. Usage: >>> from django.contrib.gis.utils import ogrinspect >>> ogrinspect('/path/to/shapefile.shp','NewModel') ...will p...
[ "def", "ogrinspect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "'\\n'", ".", "join", "(", "s", "for", "s", "in", "_ogrinspect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
[ 52, 0 ]
[ 120, 61 ]
python
en
['en', 'error', 'th']
False
_ogrinspect
(data_source, model_name, geom_name='geom', layer_key=0, srid=None, multi_geom=False, name_field=None, imports=True, decimal=False, blank=False, null=False)
Helper routine for `ogrinspect` that generates GeoDjango models corresponding to the given data source. See the `ogrinspect` docstring for more details.
Helper routine for `ogrinspect` that generates GeoDjango models corresponding to the given data source. See the `ogrinspect` docstring for more details.
def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=None, multi_geom=False, name_field=None, imports=True, decimal=False, blank=False, null=False): """ Helper routine for `ogrinspect` that generates GeoDjango models corresponding to the given data sou...
[ "def", "_ogrinspect", "(", "data_source", ",", "model_name", ",", "geom_name", "=", "'geom'", ",", "layer_key", "=", "0", ",", "srid", "=", "None", ",", "multi_geom", "=", "False", ",", "name_field", "=", "None", ",", "imports", "=", "True", ",", "decima...
[ 123, 0 ]
[ 238, 56 ]
python
en
['en', 'error', 'th']
False
Local._get_context_id
(self)
Get the ID we should use for looking up variables
Get the ID we should use for looking up variables
def _get_context_id(self): """ Get the ID we should use for looking up variables """ # Prevent a circular reference from .sync import AsyncToSync, SyncToAsync # First, pull the current task if we can context_id = SyncToAsync.get_current_task() context_is_...
[ "def", "_get_context_id", "(", "self", ")", ":", "# Prevent a circular reference", "from", ".", "sync", "import", "AsyncToSync", ",", "SyncToAsync", "# First, pull the current task if we can", "context_id", "=", "SyncToAsync", ".", "get_current_task", "(", ")", "context_i...
[ 45, 4 ]
[ 79, 25 ]
python
en
['en', 'error', 'th']
False
ExecutionContext.frame
(self)
Return frame associated with this execution context.
Return frame associated with this execution context.
def frame(self) -> Optional['Frame']: """Return frame associated with this execution context.""" return self._frame
[ "def", "frame", "(", "self", ")", "->", "Optional", "[", "'Frame'", "]", ":", "return", "self", ".", "_frame" ]
[ 42, 4 ]
[ 44, 26 ]
python
en
['en', 'en', 'en']
True
ExecutionContext.evaluate
(self, pageFunction: str, *args: Any, force_expr: bool = False)
Execute ``pageFunction`` on this context. Details see :meth:`pyppeteer.page.Page.evaluate`.
Execute ``pageFunction`` on this context.
async def evaluate(self, pageFunction: str, *args: Any, force_expr: bool = False) -> Any: """Execute ``pageFunction`` on this context. Details see :meth:`pyppeteer.page.Page.evaluate`. """ handle = await self.evaluateHandle( pageFunction, *args, force_...
[ "async", "def", "evaluate", "(", "self", ",", "pageFunction", ":", "str", ",", "*", "args", ":", "Any", ",", "force_expr", ":", "bool", "=", "False", ")", "->", "Any", ":", "handle", "=", "await", "self", ".", "evaluateHandle", "(", "pageFunction", ","...
[ 46, 4 ]
[ 63, 21 ]
python
en
['en', 'en', 'en']
True
ExecutionContext.evaluateHandle
(self, pageFunction: str, *args: Any, # noqa: C901 force_expr: bool = False)
Execute ``pageFunction`` on this context. Details see :meth:`pyppeteer.page.Page.evaluateHandle`.
Execute ``pageFunction`` on this context.
async def evaluateHandle(self, pageFunction: str, *args: Any, # noqa: C901 force_expr: bool = False) -> 'JSHandle': """Execute ``pageFunction`` on this context. Details see :meth:`pyppeteer.page.Page.evaluateHandle`. """ suffix = f'//# sourceURL={EVALUATION...
[ "async", "def", "evaluateHandle", "(", "self", ",", "pageFunction", ":", "str", ",", "*", "args", ":", "Any", ",", "# noqa: C901", "force_expr", ":", "bool", "=", "False", ")", "->", "'JSHandle'", ":", "suffix", "=", "f'//# sourceURL={EVALUATION_SCRIPT_URL}'", ...
[ 65, 4 ]
[ 114, 54 ]
python
en
['en', 'en', 'en']
True
ExecutionContext.queryObjects
(self, prototypeHandle: 'JSHandle')
Send query. Details see :meth:`pyppeteer.page.Page.queryObjects`.
Send query.
async def queryObjects(self, prototypeHandle: 'JSHandle') -> 'JSHandle': """Send query. Details see :meth:`pyppeteer.page.Page.queryObjects`. """ if prototypeHandle._disposed: raise ElementHandleError('Prototype JSHandle is disposed!') if not prototypeHandle._remoteO...
[ "async", "def", "queryObjects", "(", "self", ",", "prototypeHandle", ":", "'JSHandle'", ")", "->", "'JSHandle'", ":", "if", "prototypeHandle", ".", "_disposed", ":", "raise", "ElementHandleError", "(", "'Prototype JSHandle is disposed!'", ")", "if", "not", "prototyp...
[ 134, 4 ]
[ 147, 65 ]
python
en
['es', 'gl', 'en']
False
JSHandle.executionContext
(self)
Get execution context of this handle.
Get execution context of this handle.
def executionContext(self) -> ExecutionContext: """Get execution context of this handle.""" return self._context
[ "def", "executionContext", "(", "self", ")", "->", "ExecutionContext", ":", "return", "self", ".", "_context" ]
[ 165, 4 ]
[ 167, 28 ]
python
en
['en', 'en', 'en']
True
JSHandle.getProperty
(self, propertyName: str)
Get property value of ``propertyName``.
Get property value of ``propertyName``.
async def getProperty(self, propertyName: str) -> 'JSHandle': """Get property value of ``propertyName``.""" objectHandle = await self._context.evaluateHandle( '''(object, propertyName) => { const result = {__proto__: null}; result[propertyName] = object[proper...
[ "async", "def", "getProperty", "(", "self", ",", "propertyName", ":", "str", ")", "->", "'JSHandle'", ":", "objectHandle", "=", "await", "self", ".", "_context", ".", "evaluateHandle", "(", "'''(object, propertyName) => {\n const result = {__proto__: null};...
[ 169, 4 ]
[ 180, 21 ]
python
en
['en', 'en', 'en']
True
JSHandle.getProperties
(self)
Get all properties of this handle.
Get all properties of this handle.
async def getProperties(self) -> Dict[str, 'JSHandle']: """Get all properties of this handle.""" response = await self._client.send('Runtime.getProperties', { 'objectId': self._remoteObject.get('objectId', ''), 'ownProperties': True, }) result = dict() for...
[ "async", "def", "getProperties", "(", "self", ")", "->", "Dict", "[", "str", ",", "'JSHandle'", "]", ":", "response", "=", "await", "self", ".", "_client", ".", "send", "(", "'Runtime.getProperties'", ",", "{", "'objectId'", ":", "self", ".", "_remoteObjec...
[ 182, 4 ]
[ 194, 21 ]
python
en
['en', 'en', 'en']
True
JSHandle.jsonValue
(self)
Get Jsonized value of this object.
Get Jsonized value of this object.
async def jsonValue(self) -> Dict: """Get Jsonized value of this object.""" objectId = self._remoteObject.get('objectId') if objectId: response = await self._client.send('Runtime.callFunctionOn', { 'functionDeclaration': 'function() { return this; }', ...
[ "async", "def", "jsonValue", "(", "self", ")", "->", "Dict", ":", "objectId", "=", "self", ".", "_remoteObject", ".", "get", "(", "'objectId'", ")", "if", "objectId", ":", "response", "=", "await", "self", ".", "_client", ".", "send", "(", "'Runtime.call...
[ 196, 4 ]
[ 207, 63 ]
python
en
['en', 'en', 'en']
True
JSHandle.asElement
(self)
Return either null or the object handle itself.
Return either null or the object handle itself.
def asElement(self) -> Optional['ElementHandle']: """Return either null or the object handle itself.""" return None
[ "def", "asElement", "(", "self", ")", "->", "Optional", "[", "'ElementHandle'", "]", ":", "return", "None" ]
[ 209, 4 ]
[ 211, 19 ]
python
en
['en', 'en', 'en']
True
JSHandle.dispose
(self)
Stop referencing the handle.
Stop referencing the handle.
async def dispose(self) -> None: """Stop referencing the handle.""" if self._disposed: return self._disposed = True try: await helper.releaseObject(self._client, self._remoteObject) except Exception as e: debugError(logger, e)
[ "async", "def", "dispose", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_disposed", ":", "return", "self", ".", "_disposed", "=", "True", "try", ":", "await", "helper", ".", "releaseObject", "(", "self", ".", "_client", ",", "self", ".", ...
[ 213, 4 ]
[ 221, 33 ]
python
en
['en', 'en', 'en']
True
JSHandle.toString
(self)
Get string representation.
Get string representation.
def toString(self) -> str: """Get string representation.""" if self._remoteObject.get('objectId'): _type = (self._remoteObject.get('subtype') or self._remoteObject.get('type')) return f'JSHandle@{_type}' return 'JSHandle:{}'.format( helper...
[ "def", "toString", "(", "self", ")", "->", "str", ":", "if", "self", ".", "_remoteObject", ".", "get", "(", "'objectId'", ")", ":", "_type", "=", "(", "self", ".", "_remoteObject", ".", "get", "(", "'subtype'", ")", "or", "self", ".", "_remoteObject", ...
[ 223, 4 ]
[ 230, 61 ]
python
en
['en', 'kk', 'en']
True
WorkerTest.test_push_notifications_worker
(self)
The push notifications system has its own comprehensive test suite, so we can limit ourselves to simple unit testing the queue processor, without going deeper into the system - by mocking the handle_push_notification functions to immediately produce the effect we want, to test its handl...
The push notifications system has its own comprehensive test suite, so we can limit ourselves to simple unit testing the queue processor, without going deeper into the system - by mocking the handle_push_notification functions to immediately produce the effect we want, to test its handl...
def test_push_notifications_worker(self) -> None: """ The push notifications system has its own comprehensive test suite, so we can limit ourselves to simple unit testing the queue processor, without going deeper into the system - by mocking the handle_push_notification functions...
[ "def", "test_push_notifications_worker", "(", "self", ")", "->", "None", ":", "fake_client", "=", "self", ".", "FakeClient", "(", ")", "def", "fake_publish", "(", "queue_name", ":", "str", ",", "event", ":", "Dict", "[", "str", ",", "Any", "]", ",", "pro...
[ 227, 4 ]
[ 299, 17 ]
python
en
['en', 'error', 'th']
False
WorkerTest.test_email_sending_worker_retries
(self)
Tests the retry_send_email_failures decorator to make sure it retries sending the email 3 times and then gives up.
Tests the retry_send_email_failures decorator to make sure it retries sending the email 3 times and then gives up.
def test_email_sending_worker_retries(self) -> None: """Tests the retry_send_email_failures decorator to make sure it retries sending the email 3 times and then gives up.""" fake_client = self.FakeClient() data = { "template_prefix": "zerver/emails/confirm_new_email", ...
[ "def", "test_email_sending_worker_retries", "(", "self", ")", "->", "None", ":", "fake_client", "=", "self", ".", "FakeClient", "(", ")", "data", "=", "{", "\"template_prefix\"", ":", "\"zerver/emails/confirm_new_email\"", ",", "\"to_emails\"", ":", "[", "self", "...
[ 399, 4 ]
[ 431, 71 ]
python
en
['en', 'en', 'en']
True
RandomBinaryProjections.__init__
(self, hash_name, projection_count, rand_seed=None)
Creates projection_count random vectors, that are used for projections thus working as normals of random hyperplanes. Each random vector / hyperplane will result in one bit of hash. So if you for example decide to use projection_count=10, the bucket keys will have 10 digits and...
Creates projection_count random vectors, that are used for projections thus working as normals of random hyperplanes. Each random vector / hyperplane will result in one bit of hash.
def __init__(self, hash_name, projection_count, rand_seed=None): """ Creates projection_count random vectors, that are used for projections thus working as normals of random hyperplanes. Each random vector / hyperplane will result in one bit of hash. So if you for example decide...
[ "def", "__init__", "(", "self", ",", "hash_name", ",", "projection_count", ",", "rand_seed", "=", "None", ")", ":", "super", "(", "RandomBinaryProjections", ",", "self", ")", ".", "__init__", "(", "hash_name", ")", "self", ".", "projection_count", "=", "proj...
[ 38, 4 ]
[ 52, 31 ]
python
en
['en', 'error', 'th']
False
RandomBinaryProjections.reset
(self, dim)
Resets / Initializes the hash for the specified dimension.
Resets / Initializes the hash for the specified dimension.
def reset(self, dim): """ Resets / Initializes the hash for the specified dimension. """ if self.dim != dim: self.dim = dim self.normals = self.rand.randn(self.projection_count, dim)
[ "def", "reset", "(", "self", ",", "dim", ")", ":", "if", "self", ".", "dim", "!=", "dim", ":", "self", ".", "dim", "=", "dim", "self", ".", "normals", "=", "self", ".", "rand", ".", "randn", "(", "self", ".", "projection_count", ",", "dim", ")" ]
[ 54, 4 ]
[ 58, 70 ]
python
en
['en', 'en', 'en']
True
RandomBinaryProjections.hash_vector
(self, v, querying=False)
Hashes the vector and returns the binary bucket key as string.
Hashes the vector and returns the binary bucket key as string.
def hash_vector(self, v, querying=False): """ Hashes the vector and returns the binary bucket key as string. """ if scipy.sparse.issparse(v): # If vector is sparse, make sure we have the CSR representation # of the projection matrix if self.normals_csr...
[ "def", "hash_vector", "(", "self", ",", "v", ",", "querying", "=", "False", ")", ":", "if", "scipy", ".", "sparse", ".", "issparse", "(", "v", ")", ":", "# If vector is sparse, make sure we have the CSR representation", "# of the projection matrix", "if", "self", ...
[ 60, 4 ]
[ 78, 71 ]
python
en
['en', 'error', 'th']
False
RandomBinaryProjections.get_config
(self)
Returns pickle-serializable configuration struct for storage.
Returns pickle-serializable configuration struct for storage.
def get_config(self): """ Returns pickle-serializable configuration struct for storage. """ # Fill this dict with config data return { 'hash_name': self.hash_name, 'dim': self.dim, 'projection_count': self.projection_count, 'normals...
[ "def", "get_config", "(", "self", ")", ":", "# Fill this dict with config data", "return", "{", "'hash_name'", ":", "self", ".", "hash_name", ",", "'dim'", ":", "self", ".", "dim", ",", "'projection_count'", ":", "self", ".", "projection_count", ",", "'normals'"...
[ 80, 4 ]
[ 90, 9 ]
python
en
['en', 'error', 'th']
False
RandomBinaryProjections.apply_config
(self, config)
Applies config
Applies config
def apply_config(self, config): """ Applies config """ self.hash_name = config['hash_name'] self.dim = config['dim'] self.projection_count = config['projection_count'] self.normals = config['normals']
[ "def", "apply_config", "(", "self", ",", "config", ")", ":", "self", ".", "hash_name", "=", "config", "[", "'hash_name'", "]", "self", ".", "dim", "=", "config", "[", "'dim'", "]", "self", ".", "projection_count", "=", "config", "[", "'projection_count'", ...
[ 92, 4 ]
[ 99, 40 ]
python
en
['en', 'error', 'th']
False
fill_edit_history_entries
(message_history: List[Dict[str, Any]], message: Message)
This fills out the message edit history entries from the database, which are designed to have the minimum data possible, to instead have the current topic + content as of that time, plus data on whatever changed. This makes it much simpler to do future processing. Note that this mutates what is pa...
This fills out the message edit history entries from the database, which are designed to have the minimum data possible, to instead have the current topic + content as of that time, plus data on whatever changed. This makes it much simpler to do future processing.
def fill_edit_history_entries(message_history: List[Dict[str, Any]], message: Message) -> None: """This fills out the message edit history entries from the database, which are designed to have the minimum data possible, to instead have the current topic + content as of that time, plus data on whatever c...
[ "def", "fill_edit_history_entries", "(", "message_history", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ",", "message", ":", "Message", ")", "->", "None", ":", "prev_content", "=", "message", ".", "content", "prev_rendered_content", "=", "mes...
[ 21, 0 ]
[ 66, 5 ]
python
en
['en', 'en', 'en']
True
send_response_message
( bot_id: int, message_info: Dict[str, Any], response_data: Dict[str, Any] )
bot_id is the user_id of the bot sending the response message_info is used to address the message and should have these fields: type - "stream" or "private" display_recipient - like we have in other message events topic - see get_topic_from_message_info response_data is what the b...
bot_id is the user_id of the bot sending the response
def send_response_message( bot_id: int, message_info: Dict[str, Any], response_data: Dict[str, Any] ) -> None: """ bot_id is the user_id of the bot sending the response message_info is used to address the message and should have these fields: type - "stream" or "private" display_recipie...
[ "def", "send_response_message", "(", "bot_id", ":", "int", ",", "message_info", ":", "Dict", "[", "str", ",", "Any", "]", ",", "response_data", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "message_type", "=", "message_info", "[", ...
[ 152, 0 ]
[ 204, 5 ]
python
en
['en', 'error', 'th']
False
do_rest_call
( base_url: str, event: Dict[str, Any], service_handler: OutgoingWebhookServiceInterface, )
Returns response of call if no exception occurs.
Returns response of call if no exception occurs.
def do_rest_call( base_url: str, event: Dict[str, Any], service_handler: OutgoingWebhookServiceInterface, ) -> Optional[Response]: """Returns response of call if no exception occurs.""" try: start_time = perf_counter() response = service_handler.make_request( base_url, ...
[ "def", "do_rest_call", "(", "base_url", ":", "str", ",", "event", ":", "Dict", "[", "str", ",", "Any", "]", ",", "service_handler", ":", "OutgoingWebhookServiceInterface", ",", ")", "->", "Optional", "[", "Response", "]", ":", "try", ":", "start_time", "="...
[ 320, 0 ]
[ 398, 19 ]
python
en
['en', 'en', 'en']
True
GenericOutgoingWebhookService.make_request
(self, base_url: str, event: Dict[str, Any])
We send a simple version of the message to outgoing webhooks, since most of them really only need `content` and a few other fields. We may eventually allow certain bots to get more information, but that's not a high priority. We do send the gravatar info to the clients...
We send a simple version of the message to outgoing webhooks, since most of them really only need `content` and a few other fields. We may eventually allow certain bots to get more information, but that's not a high priority. We do send the gravatar info to the clients...
def make_request(self, base_url: str, event: Dict[str, Any]) -> Optional[Response]: """ We send a simple version of the message to outgoing webhooks, since most of them really only need `content` and a few other fields. We may eventually allow certain bots to get more informatio...
[ "def", "make_request", "(", "self", ",", "base_url", ":", "str", ",", "event", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Optional", "[", "Response", "]", ":", "message_dict", "=", "MessageDict", ".", "finalize_payload", "(", "event", "[", "...
[ 51, 4 ]
[ 77, 61 ]
python
en
['en', 'error', 'th']
False
update_test_databases_if_required
(rebuild_test_database: bool = False)
Checks whether the zulip_test_template database template, is consistent with our database migrations; if not, it updates it in the fastest way possible: * If all we need to do is add some migrations, just runs those migrations on the template database. * Otherwise, we rebuild the test template da...
Checks whether the zulip_test_template database template, is consistent with our database migrations; if not, it updates it in the fastest way possible:
def update_test_databases_if_required(rebuild_test_database: bool = False) -> None: """Checks whether the zulip_test_template database template, is consistent with our database migrations; if not, it updates it in the fastest way possible: * If all we need to do is add some migrations, just runs those ...
[ "def", "update_test_databases_if_required", "(", "rebuild_test_database", ":", "bool", "=", "False", ")", "->", "None", ":", "test_template_db_status", "=", "TEST_DATABASE", ".", "template_status", "(", ")", "if", "test_template_db_status", "==", "\"needs_rebuild\"", ":...
[ 254, 0 ]
[ 285, 46 ]
python
en
['en', 'en', 'en']
True
destroy_leaked_test_databases
(expiry_time: int = 60 * 60)
The logic in zerver/lib/test_runner.py tries to delete all the temporary test databases generated by test-backend threads, but it cannot guarantee it handles all race conditions correctly. This is a catch-all function designed to delete any that might have been leaked due to crashes (etc.). The high-l...
The logic in zerver/lib/test_runner.py tries to delete all the temporary test databases generated by test-backend threads, but it cannot guarantee it handles all race conditions correctly. This is a catch-all function designed to delete any that might have been leaked due to crashes (etc.). The high-l...
def destroy_leaked_test_databases(expiry_time: int = 60 * 60) -> int: """The logic in zerver/lib/test_runner.py tries to delete all the temporary test databases generated by test-backend threads, but it cannot guarantee it handles all race conditions correctly. This is a catch-all function designed to ...
[ "def", "destroy_leaked_test_databases", "(", "expiry_time", ":", "int", "=", "60", "*", "60", ")", "->", "int", ":", "files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "UUID_VAR_DIR", ",", "TEMPLATE_DATABASE_DIR", ",", "\"*\"", ...
[ 323, 0 ]
[ 374, 33 ]
python
en
['en', 'en', 'en']
True
reset_zulip_test_database
()
This function is used to reset the zulip_test database fastest way possible, i.e. First, it deletes the database and then clones it from zulip_test_template. This function is used with puppeteer tests, so it can quickly reset the test database after each run.
This function is used to reset the zulip_test database fastest way possible, i.e. First, it deletes the database and then clones it from zulip_test_template. This function is used with puppeteer tests, so it can quickly reset the test database after each run.
def reset_zulip_test_database() -> None: """ This function is used to reset the zulip_test database fastest way possible, i.e. First, it deletes the database and then clones it from zulip_test_template. This function is used with puppeteer tests, so it can quickly reset the test database after each ...
[ "def", "reset_zulip_test_database", "(", ")", "->", "None", ":", "from", "zerver", ".", "lib", ".", "test_runner", "import", "destroy_test_databases", "# Make sure default database is 'zulip_test'.", "assert", "connections", "[", "\"default\"", "]", ".", "settings_dict", ...
[ 390, 0 ]
[ 433, 22 ]
python
en
['en', 'error', 'th']
False
Database.template_status
(self)
NOTE: We immediately update the digest, assuming our callers will do what it takes to run the migrations. Ideally our callers would just do it themselves AFTER the migrations actually succeeded, but the caller codepaths are kind of complicated here. ...
NOTE: We immediately update the digest, assuming our callers will do what it takes to run the migrations.
def template_status(self) -> str: # This function returns a status string specifying the type of # state the template db is in and thus the kind of action required. if not self.database_exists(): # TODO: It's possible that `database_exists` will # return `False` eve...
[ "def", "template_status", "(", "self", ")", "->", "str", ":", "# This function returns a status string specifying the type of", "# state the template db is in and thus the kind of action required.", "if", "not", "self", ".", "database_exists", "(", ")", ":", "# TODO: It's possibl...
[ 176, 4 ]
[ 219, 24 ]
python
en
['en', 'error', 'th']
False
iDRACUpdate._get_scp_path
(self, catalog_dir)
:param catalog_dir: object for Folder containing Catalog on share. :param catalog_dir: FileOnShare. :returns: returns a tuple containing remote scp path(full) and the scp file name
:param catalog_dir: object for Folder containing Catalog on share. :param catalog_dir: FileOnShare. :returns: returns a tuple containing remote scp path(full) and the scp file name
def _get_scp_path(self, catalog_dir): """ :param catalog_dir: object for Folder containing Catalog on share. :param catalog_dir: FileOnShare. :returns: returns a tuple containing remote scp path(full) and the scp file name """ catalog_path_str = catalog_dir.remo...
[ "def", "_get_scp_path", "(", "self", ",", "catalog_dir", ")", ":", "catalog_path_str", "=", "catalog_dir", ".", "remote_full_path", "scp_file", "=", "'scp_'", "+", "self", ".", "entity", ".", "ServiceTag", "+", "'_'", "+", "datetime", ".", "now", "(", ")", ...
[ 321, 4 ]
[ 332, 35 ]
python
en
['en', 'ja', 'th']
False
iDRACUpdate.update_from_repo_usingscp_redfish
(self, catalog_dir, catalog_file, mount_point, apply_update=True, reboot_needed=False, job_wait=True)
Performs firmware update on target server using scp RepositoyUpdate attribute :param catalog_dir: object for Folder containing Catalog on share. :param catalog_dir: FileOnShare. :param catalog_file: Catalog file name :param catalog_file: str. :param mount_point: local shar...
Performs firmware update on target server using scp RepositoyUpdate attribute :param catalog_dir: object for Folder containing Catalog on share. :param catalog_dir: FileOnShare. :param catalog_file: Catalog file name :param catalog_file: str. :param mount_point: local shar...
def update_from_repo_usingscp_redfish(self, catalog_dir, catalog_file, mount_point, apply_update=True, reboot_needed=False, job_wait=True): """Performs firmware update on target server using scp RepositoyUpdate attribute :param catalog_dir: object for Folde...
[ "def", "update_from_repo_usingscp_redfish", "(", "self", ",", "catalog_dir", ",", "catalog_file", ",", "mount_point", ",", "apply_update", "=", "True", ",", "reboot_needed", "=", "False", ",", "job_wait", "=", "True", ")", ":", "(", "scp_path", ",", "scp_file", ...
[ 334, 4 ]
[ 365, 20 ]
python
en
['en', 'en', 'en']
True
iDRACUpdate.edit_xml_file
(self, file_location, attr_val_dict)
Edit and save exported scp's attributes which are passed in attr_val_dict :param file_location: locally mounted location(full path) of the exported scp . :param file_location: str. :param attr_val_dict: attribute and value pairs as dict :param attr_val_dict: dict. :returns...
Edit and save exported scp's attributes which are passed in attr_val_dict :param file_location: locally mounted location(full path) of the exported scp . :param file_location: str. :param attr_val_dict: attribute and value pairs as dict :param attr_val_dict: dict. :returns...
def edit_xml_file(self, file_location, attr_val_dict): """Edit and save exported scp's attributes which are passed in attr_val_dict :param file_location: locally mounted location(full path) of the exported scp . :param file_location: str. :param attr_val_dict: attribute and value p...
[ "def", "edit_xml_file", "(", "self", ",", "file_location", ",", "attr_val_dict", ")", ":", "tree", "=", "ET", ".", "parse", "(", "file_location", ")", "root", "=", "tree", ".", "getroot", "(", ")", "for", "attr", "in", "attr_val_dict", ":", "xpath", "=",...
[ 367, 4 ]
[ 384, 14 ]
python
en
['en', 'en', 'en']
True
build_clib.check_library_list
(self, libraries)
Ensure that the list of libraries is valid. `library` is presumably provided as a command option 'libraries'. This method checks that it is a list of 2-tuples, where the tuples are (library_name, build_info_dict). Raise DistutilsSetupError if the structure is invalid anywhere; ...
Ensure that the list of libraries is valid.
def check_library_list(self, libraries): """Ensure that the list of libraries is valid. `library` is presumably provided as a command option 'libraries'. This method checks that it is a list of 2-tuples, where the tuples are (library_name, build_info_dict). Raise DistutilsSetup...
[ "def", "check_library_list", "(", "self", ",", "libraries", ")", ":", "if", "not", "isinstance", "(", "libraries", ",", "list", ")", ":", "raise", "DistutilsSetupError", "(", "\"'libraries' option must be a list of tuples\"", ")", "for", "lib", "in", "libraries", ...
[ 117, 4 ]
[ 150, 58 ]
python
en
['en', 'en', 'en']
True
ip_address
(address)
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address obje...
Take an IP string/int and return an object of the correct type.
def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An...
[ "def", "ip_address", "(", "address", ")", ":", "try", ":", "return", "IPv4Address", "(", "address", ")", "except", "(", "AddressValueError", ",", "NetmaskValueError", ")", ":", "pass", "try", ":", "return", "IPv6Address", "(", "address", ")", "except", "(", ...
[ 134, 0 ]
[ 167, 29 ]
python
en
['en', 'en', 'en']
True
ip_network
(address, strict=True)
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Network or IPv6Network objec...
Take an IP string/int and return an object of the correct type.
def ip_network(address, strict=True): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns...
[ "def", "ip_network", "(", "address", ",", "strict", "=", "True", ")", ":", "try", ":", "return", "IPv4Network", "(", "address", ",", "strict", ")", "except", "(", "AddressValueError", ",", "NetmaskValueError", ")", ":", "pass", "try", ":", "return", "IPv6N...
[ 170, 0 ]
[ 203, 29 ]
python
en
['en', 'en', 'en']
True
ip_interface
(address)
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface ...
Take an IP string/int and return an object of the correct type.
def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: ...
[ "def", "ip_interface", "(", "address", ")", ":", "try", ":", "return", "IPv4Interface", "(", "address", ")", "except", "(", "AddressValueError", ",", "NetmaskValueError", ")", ":", "pass", "try", ":", "return", "IPv6Interface", "(", "address", ")", "except", ...
[ 206, 0 ]
[ 238, 29 ]
python
en
['en', 'en', 'en']
True
v4_int_to_packed
(address)
Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the integer is negative or too large to be an ...
Represent an address as 4 packed bytes in network (big-endian) order.
def v4_int_to_packed(address): """Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the inte...
[ "def", "v4_int_to_packed", "(", "address", ")", ":", "try", ":", "return", "_compat_to_bytes", "(", "address", ",", "4", ",", "'big'", ")", "except", "(", "struct", ".", "error", ",", "OverflowError", ")", ":", "raise", "ValueError", "(", "\"Address negative...
[ 241, 0 ]
[ 258, 66 ]
python
en
['en', 'en', 'en']
True
v6_int_to_packed
(address)
Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order.
Represent an address as 16 packed bytes in network (big-endian) order.
def v6_int_to_packed(address): """Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order. """ try: return _compat_t...
[ "def", "v6_int_to_packed", "(", "address", ")", ":", "try", ":", "return", "_compat_to_bytes", "(", "address", ",", "16", ",", "'big'", ")", "except", "(", "struct", ".", "error", ",", "OverflowError", ")", ":", "raise", "ValueError", "(", "\"Address negativ...
[ 261, 0 ]
[ 274, 66 ]
python
en
['en', 'en', 'en']
True
_split_optional_netmask
(address)
Helper to split the netmask and raise AddressValueError if needed
Helper to split the netmask and raise AddressValueError if needed
def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = _compat_str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr
[ "def", "_split_optional_netmask", "(", "address", ")", ":", "addr", "=", "_compat_str", "(", "address", ")", ".", "split", "(", "'/'", ")", "if", "len", "(", "addr", ")", ">", "2", ":", "raise", "AddressValueError", "(", "\"Only one '/' permitted in %r\"", "...
[ 277, 0 ]
[ 282, 15 ]
python
en
['en', 'fi', 'en']
True
_find_address_range
(addresses)
Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence.
Find a sequence of sorted deduplicated IPv#Address.
def _find_address_range(addresses): """Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence. """ it = iter(addresses) first = last = next(it) for ip in...
[ "def", "_find_address_range", "(", "addresses", ")", ":", "it", "=", "iter", "(", "addresses", ")", "first", "=", "last", "=", "next", "(", "it", ")", "for", "ip", "in", "it", ":", "if", "ip", ".", "_ip", "!=", "last", ".", "_ip", "+", "1", ":", ...
[ 285, 0 ]
[ 302, 21 ]
python
en
['en', 'en', 'en']
True
_count_righthand_zero_bits
(number, bits)
Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number.
Count the number of zero bits on the right hand side.
def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return...
[ "def", "_count_righthand_zero_bits", "(", "number", ",", "bits", ")", ":", "if", "number", "==", "0", ":", "return", "bits", "return", "min", "(", "bits", ",", "_compat_bit_length", "(", "~", "number", "&", "(", "number", "-", "1", ")", ")", ")" ]
[ 305, 0 ]
[ 318, 64 ]
python
en
['en', 'en', 'en']
True
summarize_address_range
(first, last)
Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +NORMALIZE_WHITESPACE [IPv4Network('192.0.2...
Summarize a network range given the first and last IP addresses.
def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +N...
[ "def", "summarize_address_range", "(", "first", ",", "last", ")", ":", "if", "(", "not", "(", "isinstance", "(", "first", ",", "_BaseAddress", ")", "and", "isinstance", "(", "last", ",", "_BaseAddress", ")", ")", ")", ":", "raise", "TypeError", "(", "'fi...
[ 321, 0 ]
[ 373, 17 ]
python
en
['en', 'en', 'en']
True
_collapse_addresses_internal
(addresses)
Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_internal([ip1, ip2, ip3, ip4]) -> ...
Loops through the addresses, collapsing concurrent netblocks.
def _collapse_addresses_internal(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse...
[ "def", "_collapse_addresses_internal", "(", "addresses", ")", ":", "# First merge", "to_merge", "=", "list", "(", "addresses", ")", "subnets", "=", "{", "}", "while", "to_merge", ":", "net", "=", "to_merge", ".", "pop", "(", ")", "supernet", "=", "net", "....
[ 376, 0 ]
[ 422, 18 ]
python
en
['en', 'en', 'en']
True
collapse_addresses
(addresses)
Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: ...
Collapse a list of IP objects.
def collapse_addresses(addresses): """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network...
[ "def", "collapse_addresses", "(", "addresses", ")", ":", "addrs", "=", "[", "]", "ips", "=", "[", "]", "nets", "=", "[", "]", "# split IP addresses and networks", "for", "ip", "in", "addresses", ":", "if", "isinstance", "(", "ip", ",", "_BaseAddress", ")",...
[ 425, 0 ]
[ 476, 53 ]
python
en
['en', 'en', 'en']
True
get_mixed_type_key
(obj)
Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may...
Return a key suitable for sorting between networks and addresses.
def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There a...
[ "def", "get_mixed_type_key", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "_BaseNetwork", ")", ":", "return", "obj", ".", "_get_networks_key", "(", ")", "elif", "isinstance", "(", "obj", ",", "_BaseAddress", ")", ":", "return", "obj", ".", ...
[ 479, 0 ]
[ 501, 25 ]
python
en
['en', 'en', 'en']
True
_IPAddressBase.exploded
(self)
Return the longhand version of the IP address as a string.
Return the longhand version of the IP address as a string.
def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string()
[ "def", "exploded", "(", "self", ")", ":", "return", "self", ".", "_explode_shorthand_ip_string", "(", ")" ]
[ 511, 4 ]
[ 513, 50 ]
python
en
['en', 'en', 'en']
True
_IPAddressBase.compressed
(self)
Return the shorthand version of the IP address as a string.
Return the shorthand version of the IP address as a string.
def compressed(self): """Return the shorthand version of the IP address as a string.""" return _compat_str(self)
[ "def", "compressed", "(", "self", ")", ":", "return", "_compat_str", "(", "self", ")" ]
[ 516, 4 ]
[ 518, 32 ]
python
en
['en', 'en', 'en']
True
_IPAddressBase.reverse_pointer
(self)
The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' ...
The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'
def reverse_pointer(self): """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0....
[ "def", "reverse_pointer", "(", "self", ")", ":", "return", "self", ".", "_reverse_pointer", "(", ")" ]
[ 521, 4 ]
[ 529, 38 ]
python
en
['en', 'en', 'en']
True
_IPAddressBase._ip_int_from_prefix
(cls, prefixlen)
Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer.
Turn the prefix length into a bitwise netmask
def _ip_int_from_prefix(cls, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen)
[ "def", "_ip_int_from_prefix", "(", "cls", ",", "prefixlen", ")", ":", "return", "cls", ".", "_ALL_ONES", "^", "(", "cls", ".", "_ALL_ONES", ">>", "prefixlen", ")" ]
[ 556, 4 ]
[ 566, 59 ]
python
en
['en', 'haw', 'en']
True
_IPAddressBase._prefix_from_ip_int
(cls, ip_int)
Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones
Return prefix length from the bitwise netmask.
def _prefix_from_ip_int(cls, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & o...
[ "def", "_prefix_from_ip_int", "(", "cls", ",", "ip_int", ")", ":", "trailing_zeroes", "=", "_count_righthand_zero_bits", "(", "ip_int", ",", "cls", ".", "_max_prefixlen", ")", "prefixlen", "=", "cls", ".", "_max_prefixlen", "-", "trailing_zeroes", "leading_ones", ...
[ 569, 4 ]
[ 591, 24 ]
python
en
['en', 'en', 'en']
True
_IPAddressBase._prefix_from_prefix_string
(cls, prefixlen_str)
Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask
Return prefix length from a numeric string
def _prefix_from_prefix_string(cls, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask ...
[ "def", "_prefix_from_prefix_string", "(", "cls", ",", "prefixlen_str", ")", ":", "# int allows a leading +/- as well as surrounding whitespace,", "# so we ensure that isn't the case", "if", "not", "_BaseV4", ".", "_DECIMAL_DIGITS", ".", "issuperset", "(", "prefixlen_str", ")", ...
[ 599, 4 ]
[ 621, 24 ]
python
en
['en', 'en', 'en']
True
_IPAddressBase._prefix_from_ip_string
(cls, ip_str)
Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask
Turn a netmask/hostmask string into a prefix length
def _prefix_from_ip_string(cls, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask...
[ "def", "_prefix_from_ip_string", "(", "cls", ",", "ip_str", ")", ":", "# Parse the netmask/hostmask like an IP address.", "try", ":", "ip_int", "=", "cls", ".", "_ip_int_from_string", "(", "ip_str", ")", "except", "AddressValueError", ":", "cls", ".", "_report_invalid...
[ 624, 4 ]
[ 655, 47 ]
python
en
['en', 'haw', 'en']
True
_BaseNetwork.hosts
(self)
Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses.
Generate Iterator over usable hosts in a network.
def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in _compat_range(networ...
[ "def", "hosts", "(", "self", ")", ":", "network", "=", "int", "(", "self", ".", "network_address", ")", "broadcast", "=", "int", "(", "self", ".", "broadcast_address", ")", "for", "x", "in", "_compat_range", "(", "network", "+", "1", ",", "broadcast", ...
[ 739, 4 ]
[ 749, 40 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.overlaps
(self, other)
Tell if self is partly contained in other.
Tell if self is partly contained in other.
def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self)))
[ "def", "overlaps", "(", "self", ",", "other", ")", ":", "return", "self", ".", "network_address", "in", "other", "or", "(", "self", ".", "broadcast_address", "in", "other", "or", "(", "other", ".", "network_address", "in", "self", "or", "(", "other", "."...
[ 809, 4 ]
[ 814, 54 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.num_addresses
(self)
Number of hosts in the current subnet.
Number of hosts in the current subnet.
def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1
[ "def", "num_addresses", "(", "self", ")", ":", "return", "int", "(", "self", ".", "broadcast_address", ")", "-", "int", "(", "self", ".", "network_address", ")", "+", "1" ]
[ 846, 4 ]
[ 848, 74 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.address_exclude
(self, other)
Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') list(addr1.address_exclude(addr2)) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/...
Remove an address from a larger block.
def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') list(addr1.address_exclude(addr2)) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/3...
[ "def", "address_exclude", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "_version", "==", "other", ".", "_version", ":", "raise", "TypeError", "(", "\"%s and %s are not of the same version\"", "%", "(", "self", ",", "other", ")", ")", "if", ...
[ 862, 4 ]
[ 935, 49 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.compare_networks
(self, other)
Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._i...
Compare two IP objects.
def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can ea...
[ "def", "compare_networks", "(", "self", ",", "other", ")", ":", "# does this need to raise a ValueError?", "if", "self", ".", "_version", "!=", "other", ".", "_version", ":", "raise", "TypeError", "(", "'%s and %s are not of the same type'", "%", "(", "self", ",", ...
[ 937, 4 ]
[ 983, 16 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork._get_networks_key
(self)
Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort().
Network-only key function.
def _get_networks_key(self): """Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort(). """ return (self._version, self.network_address, self.netmask)
[ "def", "_get_networks_key", "(", "self", ")", ":", "return", "(", "self", ".", "_version", ",", "self", ".", "network_address", ",", "self", ".", "netmask", ")" ]
[ 985, 4 ]
[ 993, 66 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.subnets
(self, prefixlen_diff=1, new_prefix=None)
The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length ...
The subnets which join to make the current subnet.
def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: pre...
[ "def", "subnets", "(", "self", ",", "prefixlen_diff", "=", "1", ",", "new_prefix", "=", "None", ")", ":", "if", "self", ".", "_prefixlen", "==", "self", ".", "_max_prefixlen", ":", "yield", "self", "return", "if", "new_prefix", "is", "not", "None", ":", ...
[ 995, 4 ]
[ 1046, 25 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.supernet
(self, prefixlen_diff=1, new_prefix=None)
The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. ...
The supernet containing the current network.
def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of ...
[ "def", "supernet", "(", "self", ",", "prefixlen_diff", "=", "1", ",", "new_prefix", "=", "None", ")", ":", "if", "self", ".", "_prefixlen", "==", "0", ":", "return", "self", "if", "new_prefix", "is", "not", "None", ":", "if", "new_prefix", ">", "self",...
[ 1048, 4 ]
[ 1086, 27 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.is_multicast
(self)
Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details.
Test if the address is reserved for multicast use.
def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return (self.network_address.is_multicast and self.broadcast_address.i...
[ "def", "is_multicast", "(", "self", ")", ":", "return", "(", "self", ".", "network_address", ".", "is_multicast", "and", "self", ".", "broadcast_address", ".", "is_multicast", ")" ]
[ 1089, 4 ]
[ 1098, 52 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.subnet_of
(self, other)
Return True if this network is a subnet of other.
Return True if this network is a subnet of other.
def subnet_of(self, other): """Return True if this network is a subnet of other.""" return self._is_subnet_of(self, other)
[ "def", "subnet_of", "(", "self", ",", "other", ")", ":", "return", "self", ".", "_is_subnet_of", "(", "self", ",", "other", ")" ]
[ 1113, 4 ]
[ 1115, 46 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.supernet_of
(self, other)
Return True if this network is a supernet of other.
Return True if this network is a supernet of other.
def supernet_of(self, other): """Return True if this network is a supernet of other.""" return self._is_subnet_of(other, self)
[ "def", "supernet_of", "(", "self", ",", "other", ")", ":", "return", "self", ".", "_is_subnet_of", "(", "other", ",", "self", ")" ]
[ 1117, 4 ]
[ 1119, 46 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.is_reserved
(self)
Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges.
Test if the address is otherwise IETF reserved.
def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserv...
[ "def", "is_reserved", "(", "self", ")", ":", "return", "(", "self", ".", "network_address", ".", "is_reserved", "and", "self", ".", "broadcast_address", ".", "is_reserved", ")" ]
[ 1122, 4 ]
[ 1131, 51 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.is_link_local
(self)
Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291.
Test if the address is reserved for link-local.
def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return (self.network_address.is_link_local and self.broadcast_address.is_link_local)
[ "def", "is_link_local", "(", "self", ")", ":", "return", "(", "self", ".", "network_address", ".", "is_link_local", "and", "self", ".", "broadcast_address", ".", "is_link_local", ")" ]
[ 1134, 4 ]
[ 1142, 53 ]
python
en
['en', 'en', 'en']
True
_BaseNetwork.is_private
(self)
Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry.
Test if this address is allocated for private networks.
def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return (self.network_address.is_private and sel...
[ "def", "is_private", "(", "self", ")", ":", "return", "(", "self", ".", "network_address", ".", "is_private", "and", "self", ".", "broadcast_address", ".", "is_private", ")" ]
[ 1145, 4 ]
[ 1154, 50 ]
python
en
['en', 'en', 'en']
True