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
Response.text
(self)
Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to m...
Content of the response, in unicode.
def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of ...
[ "def", "text", "(", "self", ")", ":", "# Try charset from content-type", "content", "=", "None", "encoding", "=", "self", ".", "encoding", "if", "not", "self", ".", "content", ":", "return", "str", "(", "''", ")", "# Fallback to auto-detected encoding.", "if", ...
[ 836, 4 ]
[ 871, 22 ]
python
en
['en', 'en', 'en']
True
Response.json
(self, **kwargs)
r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json.
r"""Returns the json-encoded content of a response, if any.
def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json. """ if not self.encoding and self.content and len(self.co...
[ "def", "json", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "encoding", "and", "self", ".", "content", "and", "len", "(", "self", ".", "content", ")", ">", "3", ":", "# No encoding set. JSON RFC 4627 section 3 states we should ex...
[ 873, 4 ]
[ 897, 53 ]
python
en
['en', 'en', 'en']
True
Response.links
(self)
Returns the parsed header links of the response, if any.
Returns the parsed header links of the response, if any.
def links(self): """Returns the parsed header links of the response, if any.""" header = self.headers.get('link') # l = MultiDict() l = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel') or link.ge...
[ "def", "links", "(", "self", ")", ":", "header", "=", "self", ".", "headers", ".", "get", "(", "'link'", ")", "# l = MultiDict()", "l", "=", "{", "}", "if", "header", ":", "links", "=", "parse_header_links", "(", "header", ")", "for", "link", "in", "...
[ 900, 4 ]
[ 915, 16 ]
python
en
['en', 'en', 'en']
True
Response.raise_for_status
(self)
Raises stored :class:`HTTPError`, if one occurred.
Raises stored :class:`HTTPError`, if one occurred.
def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = '' if isinstance(self.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn'...
[ "def", "raise_for_status", "(", "self", ")", ":", "http_error_msg", "=", "''", "if", "isinstance", "(", "self", ".", "reason", ",", "bytes", ")", ":", "# We attempt to decode utf-8 first because some servers", "# choose to localize their reason strings. If the string", "# i...
[ 917, 4 ]
[ 940, 58 ]
python
en
['en', 'en', 'en']
True
Response.close
(self)
Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.*
Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again.
def close(self): """Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.* """ if not self._content_consumed: self.raw.close() ...
[ "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "_content_consumed", ":", "self", ".", "raw", ".", "close", "(", ")", "release_conn", "=", "getattr", "(", "self", ".", "raw", ",", "'release_conn'", ",", "None", ")", "if", "release_conn...
[ 942, 4 ]
[ 953, 26 ]
python
en
['en', 'en', 'en']
True
Log.add_logger
(cls, service_name, base_color="white", **kwargs)
Creates a new child ServiceLog instance.
Creates a new child ServiceLog instance.
def add_logger(cls, service_name, base_color="white", **kwargs): """Creates a new child ServiceLog instance.""" _self = cls() parent = kwargs.pop("parent", _self.parent_logger) logger = ServiceLog(service_name, base_color, parent=parent, **kwargs) _self.loggers.append(logger) ...
[ "def", "add_logger", "(", "cls", ",", "service_name", ",", "base_color", "=", "\"white\"", ",", "*", "*", "kwargs", ")", ":", "_self", "=", "cls", "(", ")", "parent", "=", "kwargs", ".", "pop", "(", "\"parent\"", ",", "_self", ".", "parent_logger", ")"...
[ 28, 4 ]
[ 34, 21 ]
python
en
['en', 'en', 'en']
True
Log.get_logger
(cls, service_name)
Retrieves a child logger by service name.
Retrieves a child logger by service name.
def get_logger(cls, service_name): """Retrieves a child logger by service name.""" _self = cls() logger = next((i for i in _self.loggers if i.service_name == service_name)) return logger
[ "def", "get_logger", "(", "cls", ",", "service_name", ")", ":", "_self", "=", "cls", "(", ")", "logger", "=", "next", "(", "(", "i", "for", "i", "in", "_self", ".", "loggers", "if", "i", ".", "service_name", "==", "service_name", ")", ")", "return", ...
[ 37, 4 ]
[ 41, 21 ]
python
en
['en', 'en', 'en']
True
ServiceLog.load_handler
(self)
Loads Logging Module Formatting.
Loads Logging Module Formatting.
def load_handler(self): """Loads Logging Module Formatting.""" self.log = logging.getLogger() if not self.log.hasHandlers(): self.log.setLevel(logging.DEBUG) self.log_handler = RotatingFileHandler( str(self.LOG_FILE), mode="a", ...
[ "def", "load_handler", "(", "self", ")", ":", "self", ".", "log", "=", "logging", ".", "getLogger", "(", ")", "if", "not", "self", ".", "log", ".", "hasHandlers", "(", ")", ":", "self", ".", "log", ".", "setLevel", "(", "logging", ".", "DEBUG", ")"...
[ 74, 4 ]
[ 91, 89 ]
python
en
['it', 'fy', 'en']
False
ServiceLog.parse_msg
(self, msg, accent_color=None)
Parses any color codes accordingly. :param str msg: :param str accent_color: (Default value = None) :return: Parsed Message :rtype: str
Parses any color codes accordingly.
def parse_msg(self, msg, accent_color=None): """Parses any color codes accordingly. :param str msg: :param str accent_color: (Default value = None) :return: Parsed Message :rtype: str """ msg_special = re.findall(r"\$(.*?)\[(.*?)\]", msg) color = accent...
[ "def", "parse_msg", "(", "self", ",", "msg", ",", "accent_color", "=", "None", ")", ":", "msg_special", "=", "re", ".", "findall", "(", "r\"\\$(.*?)\\[(.*?)\\]\"", ",", "msg", ")", "color", "=", "accent_color", "or", "self", ".", "accent_color", "special", ...
[ 93, 4 ]
[ 117, 29 ]
python
en
['en', 'en', 'en']
True
ServiceLog.get_parents
(self, names=[])
Retrieve all parents.
Retrieve all parents.
def get_parents(self, names=[]): """Retrieve all parents.""" if len(names) == 0: names = [self.service_name] if self.parent: names.insert(0, self.parent.service_name) names = self.parent.get_parents(names) return names
[ "def", "get_parents", "(", "self", ",", "names", "=", "[", "]", ")", ":", "if", "len", "(", "names", ")", "==", "0", ":", "names", "=", "[", "self", ".", "service_name", "]", "if", "self", ".", "parent", ":", "names", ".", "insert", "(", "0", "...
[ 119, 4 ]
[ 126, 20 ]
python
en
['en', 'pt', 'en']
True
ServiceLog.get_service
(self, **kwargs)
Retrieves formatted service title. :param **kwargs: :return: formatted title :rtype: str
Retrieves formatted service title.
def get_service(self, **kwargs): """Retrieves formatted service title. :param **kwargs: :return: formatted title :rtype: str """ if not self.show_title: return f"{self.parent.get_service(bold=True)}" color = kwargs.pop("fg", self.base_color) ...
[ "def", "get_service", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "show_title", ":", "return", "f\"{self.parent.get_service(bold=True)}\"", "color", "=", "kwargs", ".", "pop", "(", "\"fg\"", ",", "self", ".", "base_color", ")", ...
[ 128, 4 ]
[ 143, 20 ]
python
en
['en', 'en', 'en']
True
ServiceLog.iter_formatted
(self, message, **kwargs)
Iterate formatted message tuple into styled string. Args: message (tuple): tuple as (msg, style)
Iterate formatted message tuple into styled string.
def iter_formatted(self, message, **kwargs): """Iterate formatted message tuple into styled string. Args: message (tuple): tuple as (msg, style) """ if isinstance(message, str): message, _ = self.parse_msg(message) for msg in message: text, m...
[ "def", "iter_formatted", "(", "self", ",", "message", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "message", ",", "str", ")", ":", "message", ",", "_", "=", "self", ".", "parse_msg", "(", "message", ")", "for", "msg", "in", "message",...
[ 145, 4 ]
[ 157, 45 ]
python
en
['en', 'en', 'en']
True
ServiceLog.echo
(self, msg, **kwargs)
Prints msg to stdout. :param str msg: message to print :param **kwargs:
Prints msg to stdout.
def echo(self, msg, **kwargs): """Prints msg to stdout. :param str msg: message to print :param **kwargs: """ title_color = kwargs.pop("title_color", self.base_color) title_bold = kwargs.pop("title_bold", True) accent_color = kwargs.pop("accent", self.accent_col...
[ "def", "echo", "(", "self", ",", "msg", ",", "*", "*", "kwargs", ")", ":", "title_color", "=", "kwargs", ".", "pop", "(", "\"title_color\"", ",", "self", ".", "base_color", ")", "title_bold", "=", "kwargs", ".", "pop", "(", "\"title_bold\"", ",", "True...
[ 159, 4 ]
[ 191, 30 ]
python
en
['en', 'en', 'en']
True
ServiceLog.info
(self, msg, **kwargs)
Prints message with info formatting. :param msg: :param **kwargs: :return: method to print msg :rtype: method
Prints message with info formatting.
def info(self, msg, **kwargs): """Prints message with info formatting. :param msg: :param **kwargs: :return: method to print msg :rtype: method """ return self.echo(msg, log="info", **kwargs)
[ "def", "info", "(", "self", ",", "msg", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "echo", "(", "msg", ",", "log", "=", "\"info\"", ",", "*", "*", "kwargs", ")" ]
[ 193, 4 ]
[ 202, 51 ]
python
en
['en', 'en', 'en']
True
ServiceLog.title
(self, msg, **kwargs)
Prints bolded info message. Args: msg (str): Message
Prints bolded info message.
def title(self, msg, **kwargs): """Prints bolded info message. Args: msg (str): Message """ return self.info(f"\n{msg}", bold=True)
[ "def", "title", "(", "self", ",", "msg", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "info", "(", "f\"\\n{msg}\"", ",", "bold", "=", "True", ")" ]
[ 204, 4 ]
[ 211, 47 ]
python
en
['en', 'en', 'en']
True
ServiceLog.error
(self, msg, exception=None, **kwargs)
Prints message with error formatting. :param msg: :param **kwargs: :return: method to print msg :rtype: method
Prints message with error formatting.
def error(self, msg, exception=None, **kwargs): """Prints message with error formatting. :param msg: :param **kwargs: :return: method to print msg :rtype: method """ bold = kwargs.pop("bold", (exception != None)) self.echo( msg, l...
[ "def", "error", "(", "self", ",", "msg", ",", "exception", "=", "None", ",", "*", "*", "kwargs", ")", ":", "bold", "=", "kwargs", ".", "pop", "(", "\"bold\"", ",", "(", "exception", "!=", "None", ")", ")", "self", ".", "echo", "(", "msg", ",", ...
[ 213, 4 ]
[ 234, 44 ]
python
en
['en', 'en', 'en']
True
ServiceLog.warn
(self, msg, **kwargs)
Prints message with warn formatting. :param msg: :param **kwargs: :return: method to print msg :rtype: method
Prints message with warn formatting.
def warn(self, msg, **kwargs): """Prints message with warn formatting. :param msg: :param **kwargs: :return: method to print msg :rtype: method """ return self.echo(msg, log="warning", title_color="red", title_bold=True)
[ "def", "warn", "(", "self", ",", "msg", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "echo", "(", "msg", ",", "log", "=", "\"warning\"", ",", "title_color", "=", "\"red\"", ",", "title_bold", "=", "True", ")" ]
[ 236, 4 ]
[ 245, 80 ]
python
en
['en', 'en', 'en']
True
ServiceLog.exception
(self, error, **kwargs)
Prints message with exception formatting. :param error: :param **kwargs: :return: method to print msg :rtype: method
Prints message with exception formatting.
def exception(self, error, **kwargs): """Prints message with exception formatting. :param error: :param **kwargs: :return: method to print msg :rtype: method """ name = type(error).__name__ msg = f"{name}: {str(error)}" return self.echo(msg, log=...
[ "def", "exception", "(", "self", ",", "error", ",", "*", "*", "kwargs", ")", ":", "name", "=", "type", "(", "error", ")", ".", "__name__", "msg", "=", "f\"{name}: {str(error)}\"", "return", "self", ".", "echo", "(", "msg", ",", "log", "=", "\"exception...
[ 247, 4 ]
[ 258, 99 ]
python
en
['en', 'en', 'en']
True
ServiceLog.success
(self, msg, **kwargs)
Prints message with success formatting. :param msg: :param **kwargs: :return: method to print msg :rtype: method :return: method to print msg :rtype: method
Prints message with success formatting.
def success(self, msg, **kwargs): """Prints message with success formatting. :param msg: :param **kwargs: :return: method to print msg :rtype: method :return: method to print msg :rtype: method """ message = f"\u2714 {msg}" return self.ec...
[ "def", "success", "(", "self", ",", "msg", ",", "*", "*", "kwargs", ")", ":", "message", "=", "f\"\\u2714 {msg}\"", "return", "self", ".", "echo", "(", "message", ",", "log", "=", "\"info\"", ",", "fg", "=", "\"green\"", ",", "*", "*", "kwargs", ")" ...
[ 260, 4 ]
[ 272, 67 ]
python
en
['en', 'en', 'en']
True
ServiceLog.debug
(self, msg, **kwargs)
Prints message with debug formatting. :param msg: :param **kwargs: :return: method to log msg :rtype: method
Prints message with debug formatting.
def debug(self, msg, **kwargs): """Prints message with debug formatting. :param msg: :param **kwargs: :return: method to log msg :rtype: method """ if self.stdout: with self.silent(): return self.debug(msg, **kwargs) self.echo...
[ "def", "debug", "(", "self", ",", "msg", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "stdout", ":", "with", "self", ".", "silent", "(", ")", ":", "return", "self", ".", "debug", "(", "msg", ",", "*", "*", "kwargs", ")", "self", ".", ...
[ 274, 4 ]
[ 287, 18 ]
python
en
['en', 'ceb', 'en']
True
SessionManager.encode
(self, session_dict)
Returns the given session dictionary serialized and encoded as a string.
Returns the given session dictionary serialized and encoded as a string.
def encode(self, session_dict): """ Returns the given session dictionary serialized and encoded as a string. """ return SessionStore().encode(session_dict)
[ "def", "encode", "(", "self", ",", "session_dict", ")", ":", "return", "SessionStore", "(", ")", ".", "encode", "(", "session_dict", ")" ]
[ 8, 4 ]
[ 12, 50 ]
python
en
['en', 'error', 'th']
False
RecursiveM2MTests.test_recursive_m2m_all
(self)
Test that m2m relations are reported correctly
Test that m2m relations are reported correctly
def test_recursive_m2m_all(self): """ Test that m2m relations are reported correctly """ # Who is friends with Anne? self.assertQuerysetEqual( self.a.friends.all(), [ "Bill", "Chuck", "David" ], attrgetter("name"...
[ "def", "test_recursive_m2m_all", "(", "self", ")", ":", "# Who is friends with Anne?", "self", ".", "assertQuerysetEqual", "(", "self", ".", "a", ".", "friends", ".", "all", "(", ")", ",", "[", "\"Bill\"", ",", "\"Chuck\"", ",", "\"David\"", "]", ",", "attrg...
[ 22, 4 ]
[ 58, 9 ]
python
en
['en', 'en', 'en']
True
RecursiveM2MTests.test_recursive_m2m_reverse_add
(self)
Test reverse m2m relation is consistent
Test reverse m2m relation is consistent
def test_recursive_m2m_reverse_add(self): """ Test reverse m2m relation is consistent """ # Bill is already friends with Anne - add Anne again, but in the # reverse direction self.b.friends.add(self.a) # Who is friends with Anne? self.assertQuerysetEqual( se...
[ "def", "test_recursive_m2m_reverse_add", "(", "self", ")", ":", "# Bill is already friends with Anne - add Anne again, but in the", "# reverse direction", "self", ".", "b", ".", "friends", ".", "add", "(", "self", ".", "a", ")", "# Who is friends with Anne?", "self", ".",...
[ 60, 4 ]
[ 83, 9 ]
python
en
['en', 'en', 'en']
True
RecursiveM2MTests.test_recursive_m2m_remove
(self)
Test that we can remove items from an m2m relationship
Test that we can remove items from an m2m relationship
def test_recursive_m2m_remove(self): """ Test that we can remove items from an m2m relationship """ # Remove Anne from Bill's friends self.b.friends.remove(self.a) # Who is friends with Anne? self.assertQuerysetEqual( self.a.friends.all(), [ "Chuck",...
[ "def", "test_recursive_m2m_remove", "(", "self", ")", ":", "# Remove Anne from Bill's friends", "self", ".", "b", ".", "friends", ".", "remove", "(", "self", ".", "a", ")", "# Who is friends with Anne?", "self", ".", "assertQuerysetEqual", "(", "self", ".", "a", ...
[ 85, 4 ]
[ 103, 9 ]
python
en
['en', 'en', 'en']
True
RecursiveM2MTests.test_recursive_m2m_clear
(self)
Tests the clear method works as expected on m2m fields
Tests the clear method works as expected on m2m fields
def test_recursive_m2m_clear(self): """ Tests the clear method works as expected on m2m fields """ # Clear Anne's group of friends self.a.friends.clear() # Who is friends with Anne? self.assertQuerysetEqual( self.a.friends.all(), [] ) # Reverse rela...
[ "def", "test_recursive_m2m_clear", "(", "self", ")", ":", "# Clear Anne's group of friends", "self", ".", "a", ".", "friends", ".", "clear", "(", ")", "# Who is friends with Anne?", "self", ".", "assertQuerysetEqual", "(", "self", ".", "a", ".", "friends", ".", ...
[ 105, 4 ]
[ 131, 9 ]
python
en
['en', 'en', 'en']
True
RecursiveM2MTests.test_recursive_m2m_add_via_related_name
(self)
Tests that we can add m2m relations via the related_name attribute
Tests that we can add m2m relations via the related_name attribute
def test_recursive_m2m_add_via_related_name(self): """ Tests that we can add m2m relations via the related_name attribute """ # David is idolized by Anne and Chuck - add in reverse direction self.d.stalkers.add(self.a) # Who are Anne's idols? self.assertQuerysetEqual( ...
[ "def", "test_recursive_m2m_add_via_related_name", "(", "self", ")", ":", "# David is idolized by Anne and Chuck - add in reverse direction", "self", ".", "d", ".", "stalkers", ".", "add", "(", "self", ".", "a", ")", "# Who are Anne's idols?", "self", ".", "assertQuerysetE...
[ 133, 4 ]
[ 151, 9 ]
python
en
['en', 'en', 'en']
True
RecursiveM2MTests.test_recursive_m2m_add_in_both_directions
(self)
Check that adding the same relation twice results in a single relation
Check that adding the same relation twice results in a single relation
def test_recursive_m2m_add_in_both_directions(self): """ Check that adding the same relation twice results in a single relation """ # Ann idolizes David self.a.idols.add(self.d) # David is idolized by Anne self.d.stalkers.add(self.a) # Who are Anne's idols? sel...
[ "def", "test_recursive_m2m_add_in_both_directions", "(", "self", ")", ":", "# Ann idolizes David", "self", ".", "a", ".", "idols", ".", "add", "(", "self", ".", "d", ")", "# David is idolized by Anne", "self", ".", "d", ".", "stalkers", ".", "add", "(", "self"...
[ 153, 4 ]
[ 172, 55 ]
python
en
['en', 'en', 'en']
True
RecursiveM2MTests.test_recursive_m2m_related_to_self
(self)
Check the expected behavior when an instance is related to itself
Check the expected behavior when an instance is related to itself
def test_recursive_m2m_related_to_self(self): """ Check the expected behavior when an instance is related to itself """ # Ann idolizes herself self.a.idols.add(self.a) # Who are Anne's idols? self.assertQuerysetEqual( self.a.idols.all(), [ "Anne", ...
[ "def", "test_recursive_m2m_related_to_self", "(", "self", ")", ":", "# Ann idolizes herself", "self", ".", "a", ".", "idols", ".", "add", "(", "self", ".", "a", ")", "# Who are Anne's idols?", "self", ".", "assertQuerysetEqual", "(", "self", ".", "a", ".", "id...
[ 174, 4 ]
[ 194, 9 ]
python
en
['en', 'en', 'en']
True
NoneMetadataError.__init__
(self, dist, metadata_name)
:param dist: A Distribution object. :param metadata_name: The name of the metadata being accessed (can be "METADATA" or "PKG-INFO").
:param dist: A Distribution object. :param metadata_name: The name of the metadata being accessed (can be "METADATA" or "PKG-INFO").
def __init__(self, dist, metadata_name): # type: (Distribution, str) -> None """ :param dist: A Distribution object. :param metadata_name: The name of the metadata being accessed (can be "METADATA" or "PKG-INFO"). """ self.dist = dist self.metadata_nam...
[ "def", "__init__", "(", "self", ",", "dist", ",", "metadata_name", ")", ":", "# type: (Distribution, str) -> None", "self", ".", "dist", "=", "dist", "self", ".", "metadata_name", "=", "metadata_name" ]
[ 44, 4 ]
[ 52, 42 ]
python
en
['en', 'error', 'th']
False
HashError.body
(self)
Return a summary of me for display under the heading. This default implementation simply prints a description of the triggering requirement. :param req: The InstallRequirement that provoked this error, with its link already populated by the resolver's _populate_link().
Return a summary of me for display under the heading.
def body(self): """Return a summary of me for display under the heading. This default implementation simply prints a description of the triggering requirement. :param req: The InstallRequirement that provoked this error, with its link already populated by the resolver's _po...
[ "def", "body", "(", "self", ")", ":", "return", "' {}'", ".", "format", "(", "self", ".", "_requirement_name", "(", ")", ")" ]
[ 142, 4 ]
[ 152, 56 ]
python
en
['en', 'en', 'en']
True
HashError._requirement_name
(self)
Return a description of the requirement that triggered me. This default implementation returns long description of the req, with line numbers
Return a description of the requirement that triggered me.
def _requirement_name(self): """Return a description of the requirement that triggered me. This default implementation returns long description of the req, with line numbers """ return str(self.req) if self.req else 'unknown package'
[ "def", "_requirement_name", "(", "self", ")", ":", "return", "str", "(", "self", ".", "req", ")", "if", "self", ".", "req", "else", "'unknown package'" ]
[ 157, 4 ]
[ 164, 63 ]
python
en
['en', 'en', 'en']
True
HashMissing.__init__
(self, gotten_hash)
:param gotten_hash: The hash of the (possibly malicious) archive we just downloaded
:param gotten_hash: The hash of the (possibly malicious) archive we just downloaded
def __init__(self, gotten_hash): """ :param gotten_hash: The hash of the (possibly malicious) archive we just downloaded """ self.gotten_hash = gotten_hash
[ "def", "__init__", "(", "self", ",", "gotten_hash", ")", ":", "self", ".", "gotten_hash", "=", "gotten_hash" ]
[ 197, 4 ]
[ 202, 38 ]
python
en
['en', 'error', 'th']
False
HashMismatch.__init__
(self, allowed, gots)
:param allowed: A dict of algorithm names pointing to lists of allowed hex digests :param gots: A dict of algorithm names pointing to hashes we actually got from the files under suspicion
:param allowed: A dict of algorithm names pointing to lists of allowed hex digests :param gots: A dict of algorithm names pointing to hashes we actually got from the files under suspicion
def __init__(self, allowed, gots): """ :param allowed: A dict of algorithm names pointing to lists of allowed hex digests :param gots: A dict of algorithm names pointing to hashes we actually got from the files under suspicion """ self.allowed = allowed ...
[ "def", "__init__", "(", "self", ",", "allowed", ",", "gots", ")", ":", "self", ".", "allowed", "=", "allowed", "self", ".", "gots", "=", "gots" ]
[ 246, 4 ]
[ 254, 24 ]
python
en
['en', 'error', 'th']
False
HashMismatch._hash_comparison
(self)
Return a comparison of actual and expected hash values. Example:: Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde or 123451234512345123451234512345123451234512345 Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef ...
Return a comparison of actual and expected hash values.
def _hash_comparison(self): """ Return a comparison of actual and expected hash values. Example:: Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde or 123451234512345123451234512345123451234512345 Got bcdefbcdefb...
[ "def", "_hash_comparison", "(", "self", ")", ":", "def", "hash_then_or", "(", "hash_name", ")", ":", "# For now, all the decent hashes have 6-char names, so we can get", "# away with hard-coding space literals.", "return", "chain", "(", "[", "hash_name", "]", ",", "repeat",...
[ 260, 4 ]
[ 283, 31 ]
python
en
['en', 'error', 'th']
False
check_password
(environ, username, password)
Authenticates against Django's auth database mod_wsgi docs specify None, True, False as return value depending on whether the user exists and authenticates.
Authenticates against Django's auth database
def check_password(environ, username, password): """ Authenticates against Django's auth database mod_wsgi docs specify None, True, False as return value depending on whether the user exists and authenticates. """ UserModel = auth.get_user_model() # db connection state is managed similarly...
[ "def", "check_password", "(", "environ", ",", "username", ",", "password", ")", ":", "UserModel", "=", "auth", ".", "get_user_model", "(", ")", "# db connection state is managed similarly to the wsgi handler", "# as mod_wsgi may call these functions outside of a request/response ...
[ 5, 0 ]
[ 27, 34 ]
python
en
['en', 'error', 'th']
False
groups_for_user
(environ, username)
Authorizes a user based on groups
Authorizes a user based on groups
def groups_for_user(environ, username): """ Authorizes a user based on groups """ UserModel = auth.get_user_model() db.reset_queries() try: try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: return [] ...
[ "def", "groups_for_user", "(", "environ", ",", "username", ")", ":", "UserModel", "=", "auth", ".", "get_user_model", "(", ")", "db", ".", "reset_queries", "(", ")", "try", ":", "try", ":", "user", "=", "UserModel", ".", "_default_manager", ".", "get_by_na...
[ 30, 0 ]
[ 47, 34 ]
python
en
['en', 'error', 'th']
False
test_disallowed_methods
(all_user_types_api_client, list_url, detail_url)
Tests that only safe methods are allowed to purpose list and detail endpoints.
Tests that only safe methods are allowed to purpose list and detail endpoints.
def test_disallowed_methods(all_user_types_api_client, list_url, detail_url): """ Tests that only safe methods are allowed to purpose list and detail endpoints. """ check_only_safe_methods_allowed(all_user_types_api_client, (list_url, detail_url))
[ "def", "test_disallowed_methods", "(", "all_user_types_api_client", ",", "list_url", ",", "detail_url", ")", ":", "check_only_safe_methods_allowed", "(", "all_user_types_api_client", ",", "(", "list_url", ",", "detail_url", ")", ")" ]
[ 21, 0 ]
[ 25, 86 ]
python
en
['en', 'error', 'th']
False
construct_instance
(form, instance, fields=None, exclude=None)
Construct and return a model instance from the bound ``form``'s ``cleaned_data``, but do not save the returned instance to the database.
Construct and return a model instance from the bound ``form``'s ``cleaned_data``, but do not save the returned instance to the database.
def construct_instance(form, instance, fields=None, exclude=None): """ Construct and return a model instance from the bound ``form``'s ``cleaned_data``, but do not save the returned instance to the database. """ from django.db import models opts = instance._meta cleaned_data = form.cleaned_...
[ "def", "construct_instance", "(", "form", ",", "instance", ",", "fields", "=", "None", ",", "exclude", "=", "None", ")", ":", "from", "django", ".", "db", "import", "models", "opts", "=", "instance", ".", "_meta", "cleaned_data", "=", "form", ".", "clean...
[ 30, 0 ]
[ 66, 19 ]
python
en
['en', 'error', 'th']
False
model_to_dict
(instance, fields=None, exclude=None)
Return a dict containing the data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, return only the named. ``exclude`` is an optional list of field names. If provided, exclude the named from the returned ...
Return a dict containing the data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument.
def model_to_dict(instance, fields=None, exclude=None): """ Return a dict containing the data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, return only the named. ``exclude`` is an optional list of fie...
[ "def", "model_to_dict", "(", "instance", ",", "fields", "=", "None", ",", "exclude", "=", "None", ")", ":", "opts", "=", "instance", ".", "_meta", "data", "=", "{", "}", "for", "f", "in", "chain", "(", "opts", ".", "concrete_fields", ",", "opts", "."...
[ 71, 0 ]
[ 93, 15 ]
python
en
['en', 'error', 'th']
False
apply_limit_choices_to_to_formfield
(formfield)
Apply limit_choices_to to the formfield's queryset if needed.
Apply limit_choices_to to the formfield's queryset if needed.
def apply_limit_choices_to_to_formfield(formfield): """Apply limit_choices_to to the formfield's queryset if needed.""" if hasattr(formfield, 'queryset') and hasattr(formfield, 'get_limit_choices_to'): limit_choices_to = formfield.get_limit_choices_to() if limit_choices_to is not None: ...
[ "def", "apply_limit_choices_to_to_formfield", "(", "formfield", ")", ":", "if", "hasattr", "(", "formfield", ",", "'queryset'", ")", "and", "hasattr", "(", "formfield", ",", "'get_limit_choices_to'", ")", ":", "limit_choices_to", "=", "formfield", ".", "get_limit_ch...
[ 96, 0 ]
[ 101, 84 ]
python
en
['en', 'en', 'en']
True
fields_for_model
(model, fields=None, exclude=None, widgets=None, formfield_callback=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None, *, apply_limit_choices_to=True)
Return a dictionary containing form fields for the given model. ``fields`` is an optional list of field names. If provided, return only the named fields. ``exclude`` is an optional list of field names. If provided, exclude the named fields from the returned fields, even if they are listed in the ...
Return a dictionary containing form fields for the given model.
def fields_for_model(model, fields=None, exclude=None, widgets=None, formfield_callback=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None, *, apply_limit_choices_to=True): """ Return a dictionary cont...
[ "def", "fields_for_model", "(", "model", ",", "fields", "=", "None", ",", "exclude", "=", "None", ",", "widgets", "=", "None", ",", "formfield_callback", "=", "None", ",", "localized_fields", "=", "None", ",", "labels", "=", "None", ",", "help_texts", "=",...
[ 104, 0 ]
[ 190, 21 ]
python
en
['en', 'error', 'th']
False
modelform_factory
(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None)
Return a ModelForm containing form fields for the given model. You can optionally pass a `form` argument to use as a starting point for constructing the ModelForm. ``fields`` is an optional list of field names. If provided, include only the named fields in the returned fields. If omitted or '__all...
Return a ModelForm containing form fields for the given model. You can optionally pass a `form` argument to use as a starting point for constructing the ModelForm.
def modelform_factory(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None): """ Return a ModelForm containing form f...
[ "def", "modelform_factory", "(", "model", ",", "form", "=", "ModelForm", ",", "fields", "=", "None", ",", "exclude", "=", "None", ",", "formfield_callback", "=", "None", ",", "widgets", "=", "None", ",", "localized_fields", "=", "None", ",", "labels", "=",...
[ 473, 0 ]
[ 553, 60 ]
python
en
['en', 'error', 'th']
False
modelformset_factory
(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, lab...
Return a FormSet class for the given Django model class.
Return a FormSet class for the given Django model class.
def modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, ...
[ "def", "modelformset_factory", "(", "model", ",", "form", "=", "ModelForm", ",", "formfield_callback", "=", "None", ",", "formset", "=", "BaseModelFormSet", ",", "extra", "=", "1", ",", "can_delete", "=", "False", ",", "can_order", "=", "False", ",", "max_nu...
[ 858, 0 ]
[ 882, 18 ]
python
en
['en', 'en', 'en']
True
_get_foreign_key
(parent_model, model, fk_name=None, can_fail=False)
Find and return the ForeignKey from model to parent if there is one (return None if can_fail is True and no such field exists). If fk_name is provided, assume it is the name of the ForeignKey field. Unless can_fail is True, raise an exception if there isn't a ForeignKey from model to parent_model. ...
Find and return the ForeignKey from model to parent if there is one (return None if can_fail is True and no such field exists). If fk_name is provided, assume it is the name of the ForeignKey field. Unless can_fail is True, raise an exception if there isn't a ForeignKey from model to parent_model. ...
def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False): """ Find and return the ForeignKey from model to parent if there is one (return None if can_fail is True and no such field exists). If fk_name is provided, assume it is the name of the ForeignKey field. Unless can_fail is True,...
[ "def", "_get_foreign_key", "(", "parent_model", ",", "model", ",", "fk_name", "=", "None", ",", "can_fail", "=", "False", ")", ":", "# avoid circular import", "from", "django", ".", "db", ".", "models", "import", "ForeignKey", "opts", "=", "model", ".", "_me...
[ 987, 0 ]
[ 1039, 13 ]
python
en
['en', 'error', 'th']
False
inlineformset_factory
(parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, widgets=None, validate_max=F...
Return an ``InlineFormSet`` for the given kwargs. ``fk_name`` must be provided if ``model`` has more than one ``ForeignKey`` to ``parent_model``.
Return an ``InlineFormSet`` for the given kwargs.
def inlineformset_factory(parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, wid...
[ "def", "inlineformset_factory", "(", "parent_model", ",", "model", ",", "form", "=", "ModelForm", ",", "formset", "=", "BaseInlineFormSet", ",", "fk_name", "=", "None", ",", "fields", "=", "None", ",", "exclude", "=", "None", ",", "extra", "=", "3", ",", ...
[ 1042, 0 ]
[ 1081, 18 ]
python
en
['en', 'error', 'th']
False
BaseModelForm._get_validation_exclusions
(self)
For backwards-compatibility, exclude several types of fields from model validation. See tickets #12507, #12521, #12553.
For backwards-compatibility, exclude several types of fields from model validation. See tickets #12507, #12521, #12553.
def _get_validation_exclusions(self): """ For backwards-compatibility, exclude several types of fields from model validation. See tickets #12507, #12521, #12553. """ exclude = [] # Build up a list of fields that should be excluded from model field # validation and...
[ "def", "_get_validation_exclusions", "(", "self", ")", ":", "exclude", "=", "[", "]", "# Build up a list of fields that should be excluded from model field", "# validation and unique checks.", "for", "f", "in", "self", ".", "instance", ".", "_meta", ".", "fields", ":", ...
[ 308, 4 ]
[ 347, 22 ]
python
en
['en', 'error', 'th']
False
BaseModelForm.validate_unique
(self)
Call the instance's validate_unique() method and update the form's validation errors if any were raised.
Call the instance's validate_unique() method and update the form's validation errors if any were raised.
def validate_unique(self): """ Call the instance's validate_unique() method and update the form's validation errors if any were raised. """ exclude = self._get_validation_exclusions() try: self.instance.validate_unique(exclude=exclude) except Validatio...
[ "def", "validate_unique", "(", "self", ")", ":", "exclude", "=", "self", ".", "_get_validation_exclusions", "(", ")", "try", ":", "self", ".", "instance", ".", "validate_unique", "(", "exclude", "=", "exclude", ")", "except", "ValidationError", "as", "e", ":...
[ 411, 4 ]
[ 420, 34 ]
python
en
['en', 'error', 'th']
False
BaseModelForm._save_m2m
(self)
Save the many-to-many fields and generic relations for this form.
Save the many-to-many fields and generic relations for this form.
def _save_m2m(self): """ Save the many-to-many fields and generic relations for this form. """ cleaned_data = self.cleaned_data exclude = self._meta.exclude fields = self._meta.fields opts = self.instance._meta # Note that for historical reasons we want to...
[ "def", "_save_m2m", "(", "self", ")", ":", "cleaned_data", "=", "self", ".", "cleaned_data", "exclude", "=", "self", ".", "_meta", ".", "exclude", "fields", "=", "self", ".", "_meta", ".", "fields", "opts", "=", "self", ".", "instance", ".", "_meta", "...
[ 422, 4 ]
[ 441, 69 ]
python
en
['en', 'error', 'th']
False
BaseModelForm.save
(self, commit=True)
Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance.
Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance.
def save(self, commit=True): """ Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance. """ if self.errors: raise...
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "if", "self", ".", "errors", ":", "raise", "ValueError", "(", "\"The %s could not be %s because the data didn't validate.\"", "%", "(", "self", ".", "instance", ".", "_meta", ".", "object_name", ...
[ 443, 4 ]
[ 464, 28 ]
python
en
['en', 'error', 'th']
False
BaseModelFormSet.initial_form_count
(self)
Return the number of forms that are required in this FormSet.
Return the number of forms that are required in this FormSet.
def initial_form_count(self): """Return the number of forms that are required in this FormSet.""" if not self.is_bound: return len(self.get_queryset()) return super().initial_form_count()
[ "def", "initial_form_count", "(", "self", ")", ":", "if", "not", "self", ".", "is_bound", ":", "return", "len", "(", "self", ".", "get_queryset", "(", ")", ")", "return", "super", "(", ")", ".", "initial_form_count", "(", ")" ]
[ 573, 4 ]
[ 577, 43 ]
python
en
['en', 'en', 'en']
True
BaseModelFormSet._get_to_python
(self, field)
If the field is a related field, fetch the concrete field's (that is, the ultimate pointed-to field's) to_python.
If the field is a related field, fetch the concrete field's (that is, the ultimate pointed-to field's) to_python.
def _get_to_python(self, field): """ If the field is a related field, fetch the concrete field's (that is, the ultimate pointed-to field's) to_python. """ while field.remote_field is not None: field = field.remote_field.get_related_field() return field.to_pyth...
[ "def", "_get_to_python", "(", "self", ",", "field", ")", ":", "while", "field", ".", "remote_field", "is", "not", "None", ":", "field", "=", "field", ".", "remote_field", ".", "get_related_field", "(", ")", "return", "field", ".", "to_python" ]
[ 584, 4 ]
[ 591, 30 ]
python
en
['en', 'error', 'th']
False
BaseModelFormSet.save_new
(self, form, commit=True)
Save and return a new model instance for the given form.
Save and return a new model instance for the given form.
def save_new(self, form, commit=True): """Save and return a new model instance for the given form.""" return form.save(commit=commit)
[ "def", "save_new", "(", "self", ",", "form", ",", "commit", "=", "True", ")", ":", "return", "form", ".", "save", "(", "commit", "=", "commit", ")" ]
[ 646, 4 ]
[ 648, 39 ]
python
en
['en', 'en', 'en']
True
BaseModelFormSet.save_existing
(self, form, instance, commit=True)
Save and return an existing model instance for the given form.
Save and return an existing model instance for the given form.
def save_existing(self, form, instance, commit=True): """Save and return an existing model instance for the given form.""" return form.save(commit=commit)
[ "def", "save_existing", "(", "self", ",", "form", ",", "instance", ",", "commit", "=", "True", ")", ":", "return", "form", ".", "save", "(", "commit", "=", "commit", ")" ]
[ 650, 4 ]
[ 652, 39 ]
python
en
['en', 'en', 'en']
True
BaseModelFormSet.delete_existing
(self, obj, commit=True)
Deletes an existing model instance.
Deletes an existing model instance.
def delete_existing(self, obj, commit=True): """Deletes an existing model instance.""" if commit: obj.delete()
[ "def", "delete_existing", "(", "self", ",", "obj", ",", "commit", "=", "True", ")", ":", "if", "commit", ":", "obj", ".", "delete", "(", ")" ]
[ 654, 4 ]
[ 657, 24 ]
python
en
['en', 'en', 'en']
True
BaseModelFormSet.save
(self, commit=True)
Save model instances for every form, adding and changing instances as necessary, and return the list of instances.
Save model instances for every form, adding and changing instances as necessary, and return the list of instances.
def save(self, commit=True): """ Save model instances for every form, adding and changing instances as necessary, and return the list of instances. """ if not commit: self.saved_forms = [] def save_m2m(): for form in self.saved_forms: ...
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "if", "not", "commit", ":", "self", ".", "saved_forms", "=", "[", "]", "def", "save_m2m", "(", ")", ":", "for", "form", "in", "self", ".", "saved_forms", ":", "form", ".", "save_m2m"...
[ 659, 4 ]
[ 671, 81 ]
python
en
['en', 'error', 'th']
False
BaseModelFormSet.add_fields
(self, form, index)
Add a hidden field for the object's primary key.
Add a hidden field for the object's primary key.
def add_fields(self, form, index): """Add a hidden field for the object's primary key.""" from django.db.models import AutoField, OneToOneField, ForeignKey self._pk_field = pk = self.model._meta.pk # If a pk isn't editable, then it won't be on the form, so we need to # add it her...
[ "def", "add_fields", "(", "self", ",", "form", ",", "index", ")", ":", "from", "django", ".", "db", ".", "models", "import", "AutoField", ",", "OneToOneField", ",", "ForeignKey", "self", ".", "_pk_field", "=", "pk", "=", "self", ".", "model", ".", "_me...
[ 814, 4 ]
[ 855, 39 ]
python
en
['en', 'en', 'en']
True
ModelChoiceField.get_limit_choices_to
(self)
Return ``limit_choices_to`` for this form field. If it is a callable, invoke it and return the result.
Return ``limit_choices_to`` for this form field.
def get_limit_choices_to(self): """ Return ``limit_choices_to`` for this form field. If it is a callable, invoke it and return the result. """ if callable(self.limit_choices_to): return self.limit_choices_to() return self.limit_choices_to
[ "def", "get_limit_choices_to", "(", "self", ")", ":", "if", "callable", "(", "self", ".", "limit_choices_to", ")", ":", "return", "self", ".", "limit_choices_to", "(", ")", "return", "self", ".", "limit_choices_to" ]
[ 1184, 4 ]
[ 1192, 36 ]
python
en
['en', 'error', 'th']
False
ModelChoiceField.label_from_instance
(self, obj)
Convert objects into strings and generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices.
Convert objects into strings and generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices.
def label_from_instance(self, obj): """ Convert objects into strings and generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices. """ return str(obj)
[ "def", "label_from_instance", "(", "self", ",", "obj", ")", ":", "return", "str", "(", "obj", ")" ]
[ 1212, 4 ]
[ 1218, 23 ]
python
en
['en', 'error', 'th']
False
ModelMultipleChoiceField._check_values
(self, value)
Given a list of possible PK values, return a QuerySet of the corresponding objects. Raise a ValidationError if a given value is invalid (not a valid PK, not in the queryset, etc.)
Given a list of possible PK values, return a QuerySet of the corresponding objects. Raise a ValidationError if a given value is invalid (not a valid PK, not in the queryset, etc.)
def _check_values(self, value): """ Given a list of possible PK values, return a QuerySet of the corresponding objects. Raise a ValidationError if a given value is invalid (not a valid PK, not in the queryset, etc.) """ key = self.to_field_name or 'pk' # deduplica...
[ "def", "_check_values", "(", "self", ",", "value", ")", ":", "key", "=", "self", ".", "to_field_name", "or", "'pk'", "# deduplicate given values to avoid creating many querysets or", "# requiring the database backend deduplicate efficiently.", "try", ":", "value", "=", "fro...
[ 1301, 4 ]
[ 1336, 17 ]
python
en
['en', 'error', 'th']
False
user_data_dir
(appname=None, appauthor=None, version=None, roaming=False)
r"""Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically ...
r"""Return full path to the user-specific data dir for this application.
def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of ...
[ "def", "user_data_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "roaming", "=", "False", ")", ":", "if", "system", "==", "\"win32\"", ":", "if", "appauthor", "is", "None", ":", "appauthor", "=", "ap...
[ 48, 0 ]
[ 100, 15 ]
python
en
['en', 'en', 'en']
True
site_data_dir
(appname=None, appauthor=None, version=None, multipath=False)
r"""Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically ...
r"""Return full path to the user-shared data dir for this application.
def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): r"""Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of ...
[ "def", "site_data_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "multipath", "=", "False", ")", ":", "if", "system", "==", "\"win32\"", ":", "if", "appauthor", "is", "None", ":", "appauthor", "=", "...
[ 103, 0 ]
[ 166, 15 ]
python
en
['en', 'en', 'en']
True
user_config_dir
(appname=None, appauthor=None, version=None, roaming=False)
r"""Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically ...
r"""Return full path to the user-specific config dir for this application.
def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name...
[ "def", "user_config_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "roaming", "=", "False", ")", ":", "if", "system", "in", "[", "\"win32\"", ",", "\"darwin\"", "]", ":", "path", "=", "user_data_dir", ...
[ 169, 0 ]
[ 206, 15 ]
python
en
['en', 'en', 'en']
True
site_config_dir
(appname=None, appauthor=None, version=None, multipath=False)
r"""Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically ...
r"""Return full path to the user-shared data dir for this application.
def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): r"""Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name o...
[ "def", "site_config_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "multipath", "=", "False", ")", ":", "if", "system", "in", "[", "\"win32\"", ",", "\"darwin\"", "]", ":", "path", "=", "site_data_dir"...
[ 211, 0 ]
[ 260, 15 ]
python
en
['en', 'en', 'en']
True
user_cache_dir
(appname=None, appauthor=None, version=None, opinion=True)
r"""Return full path to the user-specific cache dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically ...
r"""Return full path to the user-specific cache dir for this application.
def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific cache dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of...
[ "def", "user_cache_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "opinion", "=", "True", ")", ":", "if", "system", "==", "\"win32\"", ":", "if", "appauthor", "is", "None", ":", "appauthor", "=", "ap...
[ 263, 0 ]
[ 321, 15 ]
python
en
['en', 'en', 'en']
True
user_state_dir
(appname=None, appauthor=None, version=None, roaming=False)
r"""Return full path to the user-specific state dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically ...
r"""Return full path to the user-specific state dir for this application.
def user_state_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific state dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name o...
[ "def", "user_state_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "roaming", "=", "False", ")", ":", "if", "system", "in", "[", "\"win32\"", ",", "\"darwin\"", "]", ":", "path", "=", "user_data_dir", ...
[ 324, 0 ]
[ 363, 15 ]
python
en
['en', 'en', 'en']
True
user_log_dir
(appname=None, appauthor=None, version=None, opinion=True)
r"""Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically ...
r"""Return full path to the user-specific log dir for this application.
def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the...
[ "def", "user_log_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "opinion", "=", "True", ")", ":", "if", "system", "==", "\"darwin\"", ":", "path", "=", "os", ".", "path", ".", "join", "(", "os", ...
[ 366, 0 ]
[ 414, 15 ]
python
en
['en', 'en', 'en']
True
_get_win_folder_from_registry
(csidl_name)
This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names.
This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names.
def _get_win_folder_from_registry(csidl_name): """This is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. """ if PY3: import winreg as _winreg else: import _winreg shell_folder_name = { "CS...
[ "def", "_get_win_folder_from_registry", "(", "csidl_name", ")", ":", "if", "PY3", ":", "import", "winreg", "as", "_winreg", "else", ":", "import", "_winreg", "shell_folder_name", "=", "{", "\"CSIDL_APPDATA\"", ":", "\"AppData\"", ",", "\"CSIDL_COMMON_APPDATA\"", ":"...
[ 465, 0 ]
[ 486, 14 ]
python
en
['en', 'en', 'en']
True
_win_path_to_bytes
(path)
Encode Windows paths to bytes. Only used on Python 2. Motivation is to be consistent with other operating systems where paths are also returned as bytes. This avoids problems mixing bytes and Unicode elsewhere in the codebase. For more details and discussion see <https://github.com/pypa/pip/issues/3463...
Encode Windows paths to bytes. Only used on Python 2.
def _win_path_to_bytes(path): """Encode Windows paths to bytes. Only used on Python 2. Motivation is to be consistent with other operating systems where paths are also returned as bytes. This avoids problems mixing bytes and Unicode elsewhere in the codebase. For more details and discussion see <ht...
[ "def", "_win_path_to_bytes", "(", "path", ")", ":", "for", "encoding", "in", "(", "'ASCII'", ",", "'MBCS'", ")", ":", "try", ":", "return", "path", ".", "encode", "(", "encoding", ")", "except", "(", "UnicodeEncodeError", ",", "LookupError", ")", ":", "p...
[ 580, 0 ]
[ 595, 15 ]
python
en
['en', 'en', 'en']
True
pretty_name
(name)
Convert 'first_name' to 'First name'.
Convert 'first_name' to 'First name'.
def pretty_name(name): """Convert 'first_name' to 'First name'.""" if not name: return '' return name.replace('_', ' ').capitalize()
[ "def", "pretty_name", "(", "name", ")", ":", "if", "not", "name", ":", "return", "''", "return", "name", ".", "replace", "(", "'_'", ",", "' '", ")", ".", "capitalize", "(", ")" ]
[ 10, 0 ]
[ 14, 46 ]
python
en
['en', 'en', 'en']
True
flatatt
(attrs)
Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary ...
Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary ...
def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. It is assumed that the keys do not need to be XML-escaped...
[ "def", "flatatt", "(", "attrs", ")", ":", "key_value_attrs", "=", "[", "]", "boolean_attrs", "=", "[", "]", "for", "attr", ",", "value", "in", "attrs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "if", "val...
[ 17, 0 ]
[ 40, 5 ]
python
en
['en', 'error', 'th']
False
from_current_timezone
(value)
When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes.
When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes.
def from_current_timezone(value): """ When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes. """ if settings.USE_TZ and value is not None and timezone.is_naive(value): current_timezone = timezone.get_current_timezone() try: ...
[ "def", "from_current_timezone", "(", "value", ")", ":", "if", "settings", ".", "USE_TZ", "and", "value", "is", "not", "None", "and", "timezone", ".", "is_naive", "(", "value", ")", ":", "current_timezone", "=", "timezone", ".", "get_current_timezone", "(", "...
[ 150, 0 ]
[ 167, 16 ]
python
en
['en', 'error', 'th']
False
to_current_timezone
(value)
When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display.
When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display.
def to_current_timezone(value): """ When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display. """ if settings.USE_TZ and value is not None and timezone.is_aware(value): return timezone.make_naive(value) return value
[ "def", "to_current_timezone", "(", "value", ")", ":", "if", "settings", ".", "USE_TZ", "and", "value", "is", "not", "None", "and", "timezone", ".", "is_aware", "(", "value", ")", ":", "return", "timezone", ".", "make_naive", "(", "value", ")", "return", ...
[ 170, 0 ]
[ 177, 16 ]
python
en
['en', 'error', 'th']
False
MigrationLoader.migrations_module
(cls, app_label)
Return the path to the migrations module for the specified app_label and a boolean indicating if the module is specified in settings.MIGRATION_MODULE.
Return the path to the migrations module for the specified app_label and a boolean indicating if the module is specified in settings.MIGRATION_MODULE.
def migrations_module(cls, app_label): """ Return the path to the migrations module for the specified app_label and a boolean indicating if the module is specified in settings.MIGRATION_MODULE. """ if app_label in settings.MIGRATION_MODULES: return settings.MI...
[ "def", "migrations_module", "(", "cls", ",", "app_label", ")", ":", "if", "app_label", "in", "settings", ".", "MIGRATION_MODULES", ":", "return", "settings", ".", "MIGRATION_MODULES", "[", "app_label", "]", ",", "True", "else", ":", "app_package_name", "=", "a...
[ 51, 4 ]
[ 61, 78 ]
python
en
['en', 'error', 'th']
False
MigrationLoader.load_disk
(self)
Load the migrations from all INSTALLED_APPS from disk.
Load the migrations from all INSTALLED_APPS from disk.
def load_disk(self): """Load the migrations from all INSTALLED_APPS from disk.""" self.disk_migrations = {} self.unmigrated_apps = set() self.migrated_apps = set() for app_config in apps.get_app_configs(): # Get the migrations module directory module_name,...
[ "def", "load_disk", "(", "self", ")", ":", "self", ".", "disk_migrations", "=", "{", "}", "self", ".", "unmigrated_apps", "=", "set", "(", ")", "self", ".", "migrated_apps", "=", "set", "(", ")", "for", "app_config", "in", "apps", ".", "get_app_configs",...
[ 63, 4 ]
[ 123, 17 ]
python
en
['en', 'en', 'en']
True
MigrationLoader.get_migration
(self, app_label, name_prefix)
Return the named migration or raise NodeNotFoundError.
Return the named migration or raise NodeNotFoundError.
def get_migration(self, app_label, name_prefix): """Return the named migration or raise NodeNotFoundError.""" return self.graph.nodes[app_label, name_prefix]
[ "def", "get_migration", "(", "self", ",", "app_label", ",", "name_prefix", ")", ":", "return", "self", ".", "graph", ".", "nodes", "[", "app_label", ",", "name_prefix", "]" ]
[ 125, 4 ]
[ 127, 55 ]
python
en
['en', 'en', 'en']
True
MigrationLoader.get_migration_by_prefix
(self, app_label, name_prefix)
Return the migration(s) which match the given app label and name_prefix.
Return the migration(s) which match the given app label and name_prefix.
def get_migration_by_prefix(self, app_label, name_prefix): """ Return the migration(s) which match the given app label and name_prefix. """ # Do the search results = [] for migration_app_label, migration_name in self.disk_migrations: if migration_app_label == ...
[ "def", "get_migration_by_prefix", "(", "self", ",", "app_label", ",", "name_prefix", ")", ":", "# Do the search", "results", "=", "[", "]", "for", "migration_app_label", ",", "migration_name", "in", "self", ".", "disk_migrations", ":", "if", "migration_app_label", ...
[ 129, 4 ]
[ 145, 51 ]
python
en
['en', 'error', 'th']
False
MigrationLoader.add_internal_dependencies
(self, key, migration)
Internal dependencies need to be added first to ensure `__first__` dependencies find the correct root node.
Internal dependencies need to be added first to ensure `__first__` dependencies find the correct root node.
def add_internal_dependencies(self, key, migration): """ Internal dependencies need to be added first to ensure `__first__` dependencies find the correct root node. """ for parent in migration.dependencies: # Ignore __first__ references to the same app. if...
[ "def", "add_internal_dependencies", "(", "self", ",", "key", ",", "migration", ")", ":", "for", "parent", "in", "migration", ".", "dependencies", ":", "# Ignore __first__ references to the same app.", "if", "parent", "[", "0", "]", "==", "key", "[", "0", "]", ...
[ 175, 4 ]
[ 183, 87 ]
python
en
['en', 'error', 'th']
False
MigrationLoader.build_graph
(self)
Build a migration dependency graph using both the disk and database. You'll need to rebuild the graph if you apply migrations. This isn't usually a problem as generally migration stuff runs in a one-shot process.
Build a migration dependency graph using both the disk and database. You'll need to rebuild the graph if you apply migrations. This isn't usually a problem as generally migration stuff runs in a one-shot process.
def build_graph(self): """ Build a migration dependency graph using both the disk and database. You'll need to rebuild the graph if you apply migrations. This isn't usually a problem as generally migration stuff runs in a one-shot process. """ # Load disk data sel...
[ "def", "build_graph", "(", "self", ")", ":", "# Load disk data", "self", ".", "load_disk", "(", ")", "# Load database data", "if", "self", ".", "connection", "is", "None", ":", "self", ".", "applied_migrations", "=", "{", "}", "else", ":", "recorder", "=", ...
[ 198, 4 ]
[ 274, 38 ]
python
en
['en', 'error', 'th']
False
MigrationLoader.check_consistent_history
(self, connection)
Raise InconsistentMigrationHistory if any applied migrations have unapplied dependencies.
Raise InconsistentMigrationHistory if any applied migrations have unapplied dependencies.
def check_consistent_history(self, connection): """ Raise InconsistentMigrationHistory if any applied migrations have unapplied dependencies. """ recorder = MigrationRecorder(connection) applied = recorder.applied_migrations() for migration in applied: ...
[ "def", "check_consistent_history", "(", "self", ",", "connection", ")", ":", "recorder", "=", "MigrationRecorder", "(", "connection", ")", "applied", "=", "recorder", ".", "applied_migrations", "(", ")", "for", "migration", "in", "applied", ":", "# If the migratio...
[ 276, 4 ]
[ 300, 21 ]
python
en
['en', 'error', 'th']
False
MigrationLoader.detect_conflicts
(self)
Look through the loaded graph and detect any conflicts - apps with more than one leaf migration. Return a dict of the app labels that conflict with the migration names that conflict.
Look through the loaded graph and detect any conflicts - apps with more than one leaf migration. Return a dict of the app labels that conflict with the migration names that conflict.
def detect_conflicts(self): """ Look through the loaded graph and detect any conflicts - apps with more than one leaf migration. Return a dict of the app labels that conflict with the migration names that conflict. """ seen_apps = {} conflicting_apps = set() ...
[ "def", "detect_conflicts", "(", "self", ")", ":", "seen_apps", "=", "{", "}", "conflicting_apps", "=", "set", "(", ")", "for", "app_label", ",", "migration_name", "in", "self", ".", "graph", ".", "leaf_nodes", "(", ")", ":", "if", "app_label", "in", "see...
[ 302, 4 ]
[ 314, 82 ]
python
en
['en', 'error', 'th']
False
MigrationLoader.project_state
(self, nodes=None, at_end=True)
Return a ProjectState object representing the most recent state that the loaded migrations represent. See graph.make_state() for the meaning of "nodes" and "at_end".
Return a ProjectState object representing the most recent state that the loaded migrations represent.
def project_state(self, nodes=None, at_end=True): """ Return a ProjectState object representing the most recent state that the loaded migrations represent. See graph.make_state() for the meaning of "nodes" and "at_end". """ return self.graph.make_state(nodes=nodes, at_en...
[ "def", "project_state", "(", "self", ",", "nodes", "=", "None", ",", "at_end", "=", "True", ")", ":", "return", "self", ".", "graph", ".", "make_state", "(", "nodes", "=", "nodes", ",", "at_end", "=", "at_end", ",", "real_apps", "=", "list", "(", "se...
[ 316, 4 ]
[ 323, 102 ]
python
en
['en', 'error', 'th']
False
walk_revctrl
(dirname='')
Find all files under revision control
Find all files under revision control
def walk_revctrl(dirname=''): """Find all files under revision control""" for ep in pkg_resources.iter_entry_points('setuptools.file_finders'): for item in ep.load()(dirname): yield item
[ "def", "walk_revctrl", "(", "dirname", "=", "''", ")", ":", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "'setuptools.file_finders'", ")", ":", "for", "item", "in", "ep", ".", "load", "(", ")", "(", "dirname", ")", ":", "yield", "it...
[ 16, 0 ]
[ 20, 22 ]
python
en
['en', 'en', 'en']
True
sdist.make_distribution
(self)
Workaround for #516
Workaround for #516
def make_distribution(self): """ Workaround for #516 """ with self._remove_os_link(): orig.sdist.make_distribution(self)
[ "def", "make_distribution", "(", "self", ")", ":", "with", "self", ".", "_remove_os_link", "(", ")", ":", "orig", ".", "sdist", ".", "make_distribution", "(", "self", ")" ]
[ 72, 4 ]
[ 77, 46 ]
python
en
['en', 'error', 'th']
False
sdist._remove_os_link
()
In a context, remove and restore os.link if it exists
In a context, remove and restore os.link if it exists
def _remove_os_link(): """ In a context, remove and restore os.link if it exists """ class NoValue: pass orig_val = getattr(os, 'link', NoValue) try: del os.link except Exception: pass try: yield fi...
[ "def", "_remove_os_link", "(", ")", ":", "class", "NoValue", ":", "pass", "orig_val", "=", "getattr", "(", "os", ",", "'link'", ",", "NoValue", ")", "try", ":", "del", "os", ".", "link", "except", "Exception", ":", "pass", "try", ":", "yield", "finally...
[ 81, 4 ]
[ 98, 45 ]
python
en
['en', 'error', 'th']
False
sdist._add_defaults_python
(self)
getting python files
getting python files
def _add_defaults_python(self): """getting python files""" if self.distribution.has_pure_modules(): build_py = self.get_finalized_command('build_py') self.filelist.extend(build_py.get_source_files()) self._add_data_files(self._safe_data_files(build_py))
[ "def", "_add_defaults_python", "(", "self", ")", ":", "if", "self", ".", "distribution", ".", "has_pure_modules", "(", ")", ":", "build_py", "=", "self", ".", "get_finalized_command", "(", "'build_py'", ")", "self", ".", "filelist", ".", "extend", "(", "buil...
[ 131, 4 ]
[ 136, 65 ]
python
en
['en', 'en', 'en']
True
sdist._safe_data_files
(self, build_py)
Extracting data_files from build_py is known to cause infinite recursion errors when `include_package_data` is enabled, so suppress it in that case.
Extracting data_files from build_py is known to cause infinite recursion errors when `include_package_data` is enabled, so suppress it in that case.
def _safe_data_files(self, build_py): """ Extracting data_files from build_py is known to cause infinite recursion errors when `include_package_data` is enabled, so suppress it in that case. """ if self.distribution.include_package_data: return () retu...
[ "def", "_safe_data_files", "(", "self", ",", "build_py", ")", ":", "if", "self", ".", "distribution", ".", "include_package_data", ":", "return", "(", ")", "return", "build_py", ".", "data_files" ]
[ 138, 4 ]
[ 146, 34 ]
python
en
['en', 'error', 'th']
False
sdist._add_data_files
(self, data_files)
Add data files as found in build_py.data_files.
Add data files as found in build_py.data_files.
def _add_data_files(self, data_files): """ Add data files as found in build_py.data_files. """ self.filelist.extend( os.path.join(src_dir, name) for _, src_dir, _, filenames in data_files for name in filenames )
[ "def", "_add_data_files", "(", "self", ",", "data_files", ")", ":", "self", ".", "filelist", ".", "extend", "(", "os", ".", "path", ".", "join", "(", "src_dir", ",", "name", ")", "for", "_", ",", "src_dir", ",", "_", ",", "filenames", "in", "data_fil...
[ 148, 4 ]
[ 156, 9 ]
python
en
['en', 'error', 'th']
False
sdist.read_manifest
(self)
Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution.
Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution.
def read_manifest(self): """Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution. """ log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest, 'rb') ...
[ "def", "read_manifest", "(", "self", ")", ":", "log", ".", "info", "(", "\"reading manifest file '%s'\"", ",", "self", ".", "manifest", ")", "manifest", "=", "open", "(", "self", ".", "manifest", ",", "'rb'", ")", "for", "line", "in", "manifest", ":", "#...
[ 200, 4 ]
[ 220, 24 ]
python
en
['en', 'en', 'en']
True
sdist.check_license
(self)
Checks if license_file' or 'license_files' is configured and adds any valid paths to 'self.filelist'.
Checks if license_file' or 'license_files' is configured and adds any valid paths to 'self.filelist'.
def check_license(self): """Checks if license_file' or 'license_files' is configured and adds any valid paths to 'self.filelist'. """ files = ordered_set.OrderedSet() opts = self.distribution.get_option_dict('metadata') # ignore the source of the value _, licen...
[ "def", "check_license", "(", "self", ")", ":", "files", "=", "ordered_set", ".", "OrderedSet", "(", ")", "opts", "=", "self", ".", "distribution", ".", "get_option_dict", "(", "'metadata'", ")", "# ignore the source of the value", "_", ",", "license_file", "=", ...
[ 222, 4 ]
[ 251, 35 ]
python
en
['en', 'en', 'en']
True
mapping
(data_source, geom_name='geom', layer_key=0, multi_geom=False)
Given a DataSource, generate 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 la...
Given a DataSource, generate 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, generate 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 s...
[ "def", "mapping", "(", "data_source", ",", "geom_name", "=", "'geom'", ",", "layer_key", "=", "0", ",", "multi_geom", "=", "False", ")", ":", "if", "isinstance", "(", "data_source", ",", "str", ")", ":", "# Instantiating the DataSource from the string.", "data_s...
[ 12, 0 ]
[ 47, 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", "(", "_ogrinspect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
[ 50, 0 ]
[ 118, 50 ]
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...
[ 121, 0 ]
[ 236, 66 ]
python
en
['en', 'error', 'th']
False
install_scripts.write_script
(self, script_name, contents, mode="t", *ignored)
Write an executable file to the scripts directory
Write an executable file to the scripts directory
def write_script(self, script_name, contents, mode="t", *ignored): """Write an executable file to the scripts directory""" from setuptools.command.easy_install import chmod, current_umask log.info("Installing %s script to %s", script_name, self.install_dir) target = os.path.join(self.in...
[ "def", "write_script", "(", "self", ",", "script_name", ",", "contents", ",", "mode", "=", "\"t\"", ",", "*", "ignored", ")", ":", "from", "setuptools", ".", "command", ".", "easy_install", "import", "chmod", ",", "current_umask", "log", ".", "info", "(", ...
[ 53, 4 ]
[ 67, 39 ]
python
en
['en', 'en', 'en']
True
PostGISCreation.sql_indexes_for_field
(self, model, f, style)
Return any spatial index creation SQL for the field.
Return any spatial index creation SQL for the field.
def sql_indexes_for_field(self, model, f, style): "Return any spatial index creation SQL for the field." from django.contrib.gis.db.models.fields import GeometryField output = super(PostGISCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): ...
[ "def", "sql_indexes_for_field", "(", "self", ",", "model", ",", "f", ",", "style", ")", ":", "from", "django", ".", "contrib", ".", "gis", ".", "db", ".", "models", ".", "fields", "import", "GeometryField", "output", "=", "super", "(", "PostGISCreation", ...
[ 19, 4 ]
[ 76, 21 ]
python
en
['en', 'en', 'en']
True
GeoModelAdmin.media
(self)
Injects OpenLayers JavaScript into the admin.
Injects OpenLayers JavaScript into the admin.
def media(self): "Injects OpenLayers JavaScript into the admin." media = super(GeoModelAdmin, self).media media.add_js([self.openlayers_url]) media.add_js(self.extra_js) return media
[ "def", "media", "(", "self", ")", ":", "media", "=", "super", "(", "GeoModelAdmin", ",", "self", ")", ".", "media", "media", ".", "add_js", "(", "[", "self", ".", "openlayers_url", "]", ")", "media", ".", "add_js", "(", "self", ".", "extra_js", ")", ...
[ 44, 4 ]
[ 49, 20 ]
python
en
['en', 'en', 'en']
True
GeoModelAdmin.formfield_for_dbfield
(self, db_field, **kwargs)
Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing).
Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing).
def formfield_for_dbfield(self, db_field, **kwargs): """ Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing). """ if isinstance(db_field, models.GeometryField) and db_field.dim < 3...
[ "def", "formfield_for_dbfield", "(", "self", ",", "db_field", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "db_field", ",", "models", ".", "GeometryField", ")", "and", "db_field", ".", "dim", "<", "3", ":", "kwargs", ".", "pop", "(", "'r...
[ 51, 4 ]
[ 63, 87 ]
python
en
['en', 'error', 'th']
False
GeoModelAdmin.get_map_widget
(self, db_field)
Returns a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class.
Returns a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class.
def get_map_widget(self, db_field): """ Returns a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class. """ is_collection = db_field.geom_type in ('MULTIPOINT', 'MULTILINESTRING', '...
[ "def", "get_map_widget", "(", "self", ",", "db_field", ")", ":", "is_collection", "=", "db_field", ".", "geom_type", "in", "(", "'MULTIPOINT'", ",", "'MULTILINESTRING'", ",", "'MULTIPOLYGON'", ",", "'GEOMETRYCOLLECTION'", ")", "if", "is_collection", ":", "if", "...
[ 65, 4 ]
[ 123, 20 ]
python
en
['en', 'error', 'th']
False
mnist_tutorial_cw
( train_start=0, train_end=60000, test_start=0, test_end=10000, viz_enabled=VIZ_ENABLED, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, source_samples=SOURCE_SAMPLES, learning_rate=LEARNING_RATE, attack_iterations=ATTACK_ITERATIONS, model_path=MODEL_PATH, targeted=TARGETED, ...
MNIST tutorial for Carlini and Wagner's attack :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param viz_enabled: (boolean) activate p...
MNIST tutorial for Carlini and Wagner's attack :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param viz_enabled: (boolean) activate p...
def mnist_tutorial_cw( train_start=0, train_end=60000, test_start=0, test_end=10000, viz_enabled=VIZ_ENABLED, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, source_samples=SOURCE_SAMPLES, learning_rate=LEARNING_RATE, attack_iterations=ATTACK_ITERATIONS, model_path=MODEL_PATH, ...
[ "def", "mnist_tutorial_cw", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "viz_enabled", "=", "VIZ_ENABLED", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_S...
[ 40, 0 ]
[ 250, 17 ]
python
en
['en', 'error', 'th']
False
HtmlTreeBranch.staircase_text
(self)
produces representation of a node in staircase-like format: html body.main-section p#intro
produces representation of a node in staircase-like format:
def staircase_text(self) -> str: """ produces representation of a node in staircase-like format: html body.main-section p#intro """ res = "\n" indent = " " * 4 for t in self.tags: res += indent + t.text() + "\n...
[ "def", "staircase_text", "(", "self", ")", "->", "str", ":", "res", "=", "\"\\n\"", "indent", "=", "\" \"", "*", "4", "for", "t", "in", "self", ".", "tags", ":", "res", "+=", "indent", "+", "t", ".", "text", "(", ")", "+", "\"\\n\"", "indent", "+...
[ 29, 4 ]
[ 43, 18 ]
python
en
['en', 'error', 'th']
False
HtmlTreeBranch.text
(self)
produces one-line representation of branch: html body.main-section p#intro
produces one-line representation of branch:
def text(self) -> str: """ produces one-line representation of branch: html body.main-section p#intro """ return " ".join(t.text() for t in self.tags)
[ "def", "text", "(", "self", ")", "->", "str", ":", "return", "\" \"", ".", "join", "(", "t", ".", "text", "(", ")", "for", "t", "in", "self", ".", "tags", ")" ]
[ 45, 4 ]
[ 51, 52 ]
python
en
['en', 'error', 'th']
False