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
get_level_tags
()
Return the message level tags.
Return the message level tags.
def get_level_tags(): """ Return the message level tags. """ return { **constants.DEFAULT_TAGS, **getattr(settings, 'MESSAGE_TAGS', {}), }
[ "def", "get_level_tags", "(", ")", ":", "return", "{", "*", "*", "constants", ".", "DEFAULT_TAGS", ",", "*", "*", "getattr", "(", "settings", ",", "'MESSAGE_TAGS'", ",", "{", "}", ")", ",", "}" ]
[ 4, 0 ]
[ 11, 5 ]
python
en
['en', 'error', 'th']
False
build_wheel_pep517
( name, # type: str backend, # type: Pep517HookCaller metadata_directory, # type: str tempd, # type: str )
Build one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None.
Build one InstallRequirement using the PEP 517 build process.
def build_wheel_pep517( name, # type: str backend, # type: Pep517HookCaller metadata_directory, # type: str tempd, # type: str ): # type: (...) -> Optional[str] """Build one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, retur...
[ "def", "build_wheel_pep517", "(", "name", ",", "# type: str", "backend", ",", "# type: Pep517HookCaller", "metadata_directory", ",", "# type: str", "tempd", ",", "# type: str", ")", ":", "# type: (...) -> Optional[str]", "assert", "metadata_directory", "is", "not", "None"...
[ 11, 0 ]
[ 37, 42 ]
python
en
['en', 'en', 'en']
True
attach_enctype_error_multidict
(request)
Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed.
Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed.
def attach_enctype_error_multidict(request): """Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed. """ oldcls = request.files.__class__ class newcls(oldcls): def __getitem__(self, key...
[ "def", "attach_enctype_error_multidict", "(", "request", ")", ":", "oldcls", "=", "request", ".", "files", ".", "__class__", "class", "newcls", "(", "oldcls", ")", ":", "def", "__getitem__", "(", "self", ",", "key", ")", ":", "try", ":", "return", "oldcls"...
[ 73, 0 ]
[ 89, 36 ]
python
en
['en', 'en', 'en']
True
explain_template_loading_attempts
(app, template, attempts)
This should help developers understand what failed
This should help developers understand what failed
def explain_template_loading_attempts(app, template, attempts): """This should help developers understand what failed""" info = ['Locating template "%s":' % template] total_found = 0 blueprint = None reqctx = _request_ctx_stack.top if reqctx is not None and reqctx.request.blueprint is not None: ...
[ "def", "explain_template_loading_attempts", "(", "app", ",", "template", ",", "attempts", ")", ":", "info", "=", "[", "'Locating template \"%s\":'", "%", "template", "]", "total_found", "=", "0", "blueprint", "=", "None", "reqctx", "=", "_request_ctx_stack", ".", ...
[ 109, 0 ]
[ 154, 36 ]
python
en
['en', 'en', 'en']
True
_has_level_handler
(logger)
Check if there is a handler in the logging chain that will handle the given logger's effective level.
Check if there is a handler in the logging chain that will handle the given logger's effective level.
def _has_level_handler(logger): """Check if there is a handler in the logging chain that will handle the given logger's effective level. """ level = logger.getEffectiveLevel() current = logger while current: if any(handler.level <= level for handler in current.handlers): ret...
[ "def", "_has_level_handler", "(", "logger", ")", ":", "level", "=", "logger", ".", "getEffectiveLevel", "(", ")", "current", "=", "logger", "while", "current", ":", "if", "any", "(", "handler", ".", "level", "<=", "level", "for", "handler", "in", "current"...
[ 83, 0 ]
[ 99, 16 ]
python
en
['en', 'en', 'en']
True
_log
(type, message, *args, **kwargs)
Log a message to the 'werkzeug' logger. The logger is created the first time it is needed. If there is no level set, it is set to :data:`logging.INFO`. If there is no handler for the logger's effective level, a :class:`logging.StreamHandler` is added.
Log a message to the 'werkzeug' logger.
def _log(type, message, *args, **kwargs): """Log a message to the 'werkzeug' logger. The logger is created the first time it is needed. If there is no level set, it is set to :data:`logging.INFO`. If there is no handler for the logger's effective level, a :class:`logging.StreamHandler` is added. ...
[ "def", "_log", "(", "type", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "_logger", "if", "_logger", "is", "None", ":", "_logger", "=", "logging", ".", "getLogger", "(", "\"werkzeug\"", ")", "if", "_logger", ".", "le...
[ 102, 0 ]
[ 121, 61 ]
python
en
['en', 'en', 'en']
True
_parse_signature
(func)
Return a signature object for the function.
Return a signature object for the function.
def _parse_signature(func): """Return a signature object for the function.""" if hasattr(func, "im_func"): func = func.im_func # if we have a cached validator for this function, return it parse = _signature_cache.get(func) if parse is not None: return parse # inspect the functi...
[ "def", "_parse_signature", "(", "func", ")", ":", "if", "hasattr", "(", "func", ",", "\"im_func\"", ")", ":", "func", "=", "func", ".", "im_func", "# if we have a cached validator for this function, return it", "parse", "=", "_signature_cache", ".", "get", "(", "f...
[ 124, 0 ]
[ 199, 16 ]
python
en
['en', 'en', 'en']
True
_date_to_unix
(arg)
Converts a timetuple, integer or datetime object into the seconds from epoch in utc.
Converts a timetuple, integer or datetime object into the seconds from epoch in utc.
def _date_to_unix(arg): """Converts a timetuple, integer or datetime object into the seconds from epoch in utc. """ if isinstance(arg, datetime): arg = arg.utctimetuple() elif isinstance(arg, integer_types + (float,)): return int(arg) year, month, day, hour, minute, second = arg[...
[ "def", "_date_to_unix", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "datetime", ")", ":", "arg", "=", "arg", ".", "utctimetuple", "(", ")", "elif", "isinstance", "(", "arg", ",", "integer_types", "+", "(", "float", ",", ")", ")", ":", ...
[ 202, 0 ]
[ 215, 18 ]
python
en
['en', 'en', 'en']
True
_cookie_parse_impl
(b)
Lowlevel cookie parsing facility that operates on bytes.
Lowlevel cookie parsing facility that operates on bytes.
def _cookie_parse_impl(b): """Lowlevel cookie parsing facility that operates on bytes.""" i = 0 n = len(b) while i < n: match = _cookie_re.search(b + b";", i) if not match: break key = match.group("key").strip() value = match.group("val") or b"" i = ...
[ "def", "_cookie_parse_impl", "(", "b", ")", ":", "i", "=", "0", "n", "=", "len", "(", "b", ")", "while", "i", "<", "n", ":", "match", "=", "_cookie_re", ".", "search", "(", "b", "+", "b\";\"", ",", "i", ")", "if", "not", "match", ":", "break", ...
[ 323, 0 ]
[ 339, 62 ]
python
en
['en', 'en', 'en']
True
_easteregg
(app=None)
Like the name says. But who knows how it works?
Like the name says. But who knows how it works?
def _easteregg(app=None): """Like the name says. But who knows how it works?""" def bzzzzzzz(gyver): import base64 import zlib return zlib.decompress(base64.b64decode(gyver)).decode("ascii") gyver = u"\n".join( [ x + (77 - len(x)) * u" " for x in b...
[ "def", "_easteregg", "(", "app", "=", "None", ")", ":", "def", "bzzzzzzz", "(", "gyver", ")", ":", "import", "base64", "import", "zlib", "return", "zlib", ".", "decompress", "(", "base64", ".", "b64decode", "(", "gyver", ")", ")", ".", "decode", "(", ...
[ 401, 0 ]
[ 483, 22 ]
python
en
['en', 'en', 'en']
True
SetEncoder._componentSortKey
(componentAndType)
Sort SET components by tag Sort depending on the actual Choice value (dynamic sort)
Sort SET components by tag
def _componentSortKey(componentAndType): """Sort SET components by tag Sort depending on the actual Choice value (dynamic sort) """ component, asn1Spec = componentAndType if asn1Spec is None: compType = component else: compType = asn1Spec ...
[ "def", "_componentSortKey", "(", "componentAndType", ")", ":", "component", ",", "asn1Spec", "=", "componentAndType", "if", "asn1Spec", "is", "None", ":", "compType", "=", "component", "else", ":", "compType", "=", "asn1Spec", "if", "compType", ".", "typeId", ...
[ 15, 4 ]
[ 42, 34 ]
python
en
['en', 'en', 'en']
True
encode_string
(boundary, name, value)
Returns ``name`` and ``value`` encoded as a multipart/form-data variable. ``boundary`` is the boundary string used throughout a single request to separate variables.
Returns ``name`` and ``value`` encoded as a multipart/form-data variable. ``boundary`` is the boundary string used throughout a single request to separate variables.
def encode_string(boundary, name, value): """Returns ``name`` and ``value`` encoded as a multipart/form-data variable. ``boundary`` is the boundary string used throughout a single request to separate variables.""" return MultipartParam(name, value).encode(boundary)
[ "def", "encode_string", "(", "boundary", ",", "name", ",", "value", ")", ":", "return", "MultipartParam", "(", "name", ",", "value", ")", ".", "encode", "(", "boundary", ")" ]
[ 303, 0 ]
[ 308, 55 ]
python
en
['en', 'en', 'en']
True
encode_file_header
(boundary, paramname, filesize, filename=None, filetype=None)
Returns the leading data for a multipart/form-data field that contains file data. ``boundary`` is the boundary string used throughout a single request to separate variables. ``paramname`` is the name of the variable in this request. ``filesize`` is the size of the file data. ``filename`` if ...
Returns the leading data for a multipart/form-data field that contains file data.
def encode_file_header(boundary, paramname, filesize, filename=None, filetype=None): """Returns the leading data for a multipart/form-data field that contains file data. ``boundary`` is the boundary string used throughout a single request to separate variables. ``paramname`` is the name of the var...
[ "def", "encode_file_header", "(", "boundary", ",", "paramname", ",", "filesize", ",", "filename", "=", "None", ",", "filetype", "=", "None", ")", ":", "return", "MultipartParam", "(", "paramname", ",", "filesize", "=", "filesize", ",", "filename", "=", "file...
[ 311, 0 ]
[ 331, 65 ]
python
en
['en', 'en', 'en']
True
get_body_size
(params, boundary)
Returns the number of bytes that the multipart/form-data encoding of ``params`` will be.
Returns the number of bytes that the multipart/form-data encoding of ``params`` will be.
def get_body_size(params, boundary): """Returns the number of bytes that the multipart/form-data encoding of ``params`` will be.""" size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params)) return size + len(boundary) + 6
[ "def", "get_body_size", "(", "params", ",", "boundary", ")", ":", "size", "=", "sum", "(", "p", ".", "get_size", "(", "boundary", ")", "for", "p", "in", "MultipartParam", ".", "from_params", "(", "params", ")", ")", "return", "size", "+", "len", "(", ...
[ 334, 0 ]
[ 338, 35 ]
python
en
['en', 'en', 'en']
True
get_headers
(params, boundary)
Returns a dictionary with Content-Type and Content-Length headers for the multipart/form-data encoding of ``params``.
Returns a dictionary with Content-Type and Content-Length headers for the multipart/form-data encoding of ``params``.
def get_headers(params, boundary): """Returns a dictionary with Content-Type and Content-Length headers for the multipart/form-data encoding of ``params``.""" headers = {} boundary = quote_plus(boundary) headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary headers['Content-Len...
[ "def", "get_headers", "(", "params", ",", "boundary", ")", ":", "headers", "=", "{", "}", "boundary", "=", "quote_plus", "(", "boundary", ")", "headers", "[", "'Content-Type'", "]", "=", "\"multipart/form-data; boundary=%s\"", "%", "boundary", "headers", "[", ...
[ 341, 0 ]
[ 348, 18 ]
python
en
['en', 'en', 'en']
True
multipart_encode
(params, boundary=None, cb=None)
Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parameter value. The file-like objects must support .read() and ei...
Encode ``params`` as multipart/form-data.
def multipart_encode(params, boundary=None, cb=None): """Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parame...
[ "def", "multipart_encode", "(", "params", ",", "boundary", "=", "None", ",", "cb", "=", "None", ")", ":", "if", "boundary", "is", "None", ":", "boundary", "=", "gen_boundary", "(", ")", "else", ":", "boundary", "=", "quote_plus", "(", "boundary", ")", ...
[ 407, 0 ]
[ 455, 59 ]
python
en
['en', 'en', 'en']
True
MultipartParam.from_file
(cls, paramname, filename)
Returns a new MultipartParam object constructed from the local file at ``filename``. ``filesize`` is determined by os.path.getsize(``filename``) ``filetype`` is determined by mimetypes.guess_type(``filename``)[0] ``filename`` is set to os.path.basename(``filename``)
Returns a new MultipartParam object constructed from the local file at ``filename``.
def from_file(cls, paramname, filename): """Returns a new MultipartParam object constructed from the local file at ``filename``. ``filesize`` is determined by os.path.getsize(``filename``) ``filetype`` is determined by mimetypes.guess_type(``filename``)[0] ``filename`` is set ...
[ "def", "from_file", "(", "cls", ",", "paramname", ",", "filename", ")", ":", "return", "cls", "(", "paramname", ",", "filename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", ",", "filetype", "=", "mimetypes", ".", "guess_type", "(", "...
[ 163, 4 ]
[ 177, 48 ]
python
en
['en', 'en', 'en']
True
MultipartParam.from_params
(cls, params)
Returns a list of MultipartParam objects from a sequence of name, value pairs, MultipartParam instances, or from a mapping of names to values The values may be strings or file objects, or MultipartParam objects. MultipartParam object names must match the given names in the name,...
Returns a list of MultipartParam objects from a sequence of name, value pairs, MultipartParam instances, or from a mapping of names to values
def from_params(cls, params): """Returns a list of MultipartParam objects from a sequence of name, value pairs, MultipartParam instances, or from a mapping of names to values The values may be strings or file objects, or MultipartParam objects. MultipartParam object names must m...
[ "def", "from_params", "(", "cls", ",", "params", ")", ":", "if", "hasattr", "(", "params", ",", "'items'", ")", ":", "params", "=", "params", ".", "items", "(", ")", "retval", "=", "[", "]", "for", "item", "in", "params", ":", "if", "isinstance", "...
[ 180, 4 ]
[ 213, 21 ]
python
en
['en', 'en', 'en']
True
MultipartParam.encode_hdr
(self, boundary)
Returns the header of the encoding of this parameter
Returns the header of the encoding of this parameter
def encode_hdr(self, boundary): """Returns the header of the encoding of this parameter""" boundary = encode_and_quote(boundary) headers = ["--%s" % boundary] if self.filename: disposition = 'form-data; name="%s"; filename="%s"' % ( self.name, to_string(self...
[ "def", "encode_hdr", "(", "self", ",", "boundary", ")", ":", "boundary", "=", "encode_and_quote", "(", "boundary", ")", "headers", "=", "[", "\"--%s\"", "%", "boundary", "]", "if", "self", ".", "filename", ":", "disposition", "=", "'form-data; name=\"%s\"; fil...
[ 215, 4 ]
[ 239, 35 ]
python
en
['en', 'en', 'en']
True
MultipartParam.encode
(self, boundary)
Returns the string encoding of this parameter
Returns the string encoding of this parameter
def encode(self, boundary): """Returns the string encoding of this parameter""" if self.value is None: value = self.fileobj.read() else: value = self.value if re.search(to_bytes("^--%s$" % re.escape(boundary)), value, re.M): raise ValueError("boundary...
[ "def", "encode", "(", "self", ",", "boundary", ")", ":", "if", "self", ".", "value", "is", "None", ":", "value", "=", "self", ".", "fileobj", ".", "read", "(", ")", "else", ":", "value", "=", "self", ".", "value", "if", "re", ".", "search", "(", ...
[ 241, 4 ]
[ 251, 68 ]
python
en
['en', 'en', 'en']
True
MultipartParam.iter_encode
(self, boundary, blocksize=4096)
Yields the encoding of this parameter If self.fileobj is set, then blocks of ``blocksize`` bytes are read and yielded.
Yields the encoding of this parameter If self.fileobj is set, then blocks of ``blocksize`` bytes are read and yielded.
def iter_encode(self, boundary, blocksize=4096): """Yields the encoding of this parameter If self.fileobj is set, then blocks of ``blocksize`` bytes are read and yielded.""" total = self.get_size(boundary) current = 0 if self.value is not None: block = self.en...
[ "def", "iter_encode", "(", "self", ",", "boundary", ",", "blocksize", "=", "4096", ")", ":", "total", "=", "self", ".", "get_size", "(", "boundary", ")", "current", "=", "0", "if", "self", ".", "value", "is", "not", "None", ":", "block", "=", "self",...
[ 253, 4 ]
[ 290, 49 ]
python
en
['en', 'en', 'en']
True
MultipartParam.get_size
(self, boundary)
Returns the size in bytes that this param will be when encoded with the given boundary.
Returns the size in bytes that this param will be when encoded with the given boundary.
def get_size(self, boundary): """Returns the size in bytes that this param will be when encoded with the given boundary.""" if self.filesize is not None: valuesize = self.filesize else: valuesize = len(self.value) return len(self.encode_hdr(boundary)) + 2...
[ "def", "get_size", "(", "self", ",", "boundary", ")", ":", "if", "self", ".", "filesize", "is", "not", "None", ":", "valuesize", "=", "self", ".", "filesize", "else", ":", "valuesize", "=", "len", "(", "self", ".", "value", ")", "return", "len", "(",...
[ 292, 4 ]
[ 300, 61 ]
python
en
['en', 'en', 'en']
True
multipart_yielder.next
(self)
generator function to yield multipart/form-data representation of parameters
generator function to yield multipart/form-data representation of parameters
def next(self): """generator function to yield multipart/form-data representation of parameters""" if self.param_iter is not None: try: block = advance_iterator(self.param_iter) self.current += len(block) if self.cb: ...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "param_iter", "is", "not", "None", ":", "try", ":", "block", "=", "advance_iterator", "(", "self", ".", "param_iter", ")", "self", ".", "current", "+=", "len", "(", "block", ")", "if", "self", ...
[ 369, 4 ]
[ 398, 37 ]
python
en
['en', 'en', 'en']
True
calculate_basic_statistics
(comparison_table: pandas.DataFrame)
Calculates basic statistics related to the mutations found in the comparison table. Parameters ---------- comparison_table Returns -------
Calculates basic statistics related to the mutations found in the comparison table. Parameters ---------- comparison_table
def calculate_basic_statistics(comparison_table: pandas.DataFrame)->pandas.DataFrame: """ Calculates basic statistics related to the mutations found in the comparison table. Parameters ---------- comparison_table Returns ------- """ sample_columns = [i for i in comparison_table.columns if '-' in i] referen...
[ "def", "calculate_basic_statistics", "(", "comparison_table", ":", "pandas", ".", "DataFrame", ")", "->", "pandas", ".", "DataFrame", ":", "sample_columns", "=", "[", "i", "for", "i", "in", "comparison_table", ".", "columns", "if", "'-'", "in", "i", "]", "re...
[ 6, 0 ]
[ 39, 31 ]
python
en
['en', 'error', 'th']
False
parse_bdist_wininst
(name)
Return (base,pyversion) or (None,None) for possible .exe name
Return (base,pyversion) or (None,None) for possible .exe name
def parse_bdist_wininst(name): """Return (base,pyversion) or (None,None) for possible .exe name""" lower = name.lower() base, py_ver, plat = None, None, None if lower.endswith('.exe'): if lower.endswith('.win32.exe'): base = name[:-10] plat = 'win32' elif lower....
[ "def", "parse_bdist_wininst", "(", "name", ")", ":", "lower", "=", "name", ".", "lower", "(", ")", "base", ",", "py_ver", ",", "plat", "=", "None", ",", "None", ",", "None", "if", "lower", ".", "endswith", "(", "'.exe'", ")", ":", "if", "lower", "....
[ 58, 0 ]
[ 79, 29 ]
python
en
['en', 'en', 'en']
True
distros_for_url
(url, metadata=None)
Yield egg or source distribution objects that might be found at a URL
Yield egg or source distribution objects that might be found at a URL
def distros_for_url(url, metadata=None): """Yield egg or source distribution objects that might be found at a URL""" base, fragment = egg_info_for_url(url) for dist in distros_for_location(url, base, metadata): yield dist if fragment: match = EGG_FRAGMENT.match(fragment) if match...
[ "def", "distros_for_url", "(", "url", ",", "metadata", "=", "None", ")", ":", "base", ",", "fragment", "=", "egg_info_for_url", "(", "url", ")", "for", "dist", "in", "distros_for_location", "(", "url", ",", "base", ",", "metadata", ")", ":", "yield", "di...
[ 93, 0 ]
[ 104, 26 ]
python
en
['en', 'en', 'en']
True
distros_for_location
(location, basename, metadata=None)
Yield egg or source distribution objects based on basename
Yield egg or source distribution objects based on basename
def distros_for_location(location, basename, metadata=None): """Yield egg or source distribution objects based on basename""" if basename.endswith('.egg.zip'): basename = basename[:-4] # strip the .zip if basename.endswith('.egg') and '-' in basename: # only one, unambiguous interpretation ...
[ "def", "distros_for_location", "(", "location", ",", "basename", ",", "metadata", "=", "None", ")", ":", "if", "basename", ".", "endswith", "(", "'.egg.zip'", ")", ":", "basename", "=", "basename", "[", ":", "-", "4", "]", "# strip the .zip", "if", "basena...
[ 107, 0 ]
[ 137, 13 ]
python
en
['en', 'en', 'en']
True
distros_for_filename
(filename, metadata=None)
Yield possible egg or source distribution objects based on a filename
Yield possible egg or source distribution objects based on a filename
def distros_for_filename(filename, metadata=None): """Yield possible egg or source distribution objects based on a filename""" return distros_for_location( normalize_path(filename), os.path.basename(filename), metadata )
[ "def", "distros_for_filename", "(", "filename", ",", "metadata", "=", "None", ")", ":", "return", "distros_for_location", "(", "normalize_path", "(", "filename", ")", ",", "os", ".", "path", ".", "basename", "(", "filename", ")", ",", "metadata", ")" ]
[ 140, 0 ]
[ 144, 5 ]
python
en
['en', 'en', 'en']
True
interpret_distro_name
( location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None )
Generate alternative interpretations of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before passing it to this routine!
Generate alternative interpretations of a source distro name
def interpret_distro_name( location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None ): """Generate alternative interpretations of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before pa...
[ "def", "interpret_distro_name", "(", "location", ",", "basename", ",", "metadata", ",", "py_version", "=", "None", ",", "precedence", "=", "SOURCE_DIST", ",", "platform", "=", "None", ")", ":", "# Generate alternative interpretations of a source distro name", "# Because...
[ 147, 0 ]
[ 179, 9 ]
python
en
['en', 'it', 'en']
True
unique_everseen
(iterable, key=None)
List unique elements, preserving order. Remember all elements ever seen.
List unique elements, preserving order. Remember all elements ever seen.
def unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in six.mov...
[ "def", "unique_everseen", "(", "iterable", ",", "key", "=", "None", ")", ":", "# unique_everseen('AAAABBBCCDAABBB') --> A B C D", "# unique_everseen('ABBCcAD', str.lower) --> A B C D", "seen", "=", "set", "(", ")", "seen_add", "=", "seen", ".", "add", "if", "key", "is...
[ 183, 0 ]
[ 198, 29 ]
python
ca
['ca', 'ca', 'en']
True
unique_values
(func)
Wrap a function returning an iterable such that the resulting iterable only ever yields unique items.
Wrap a function returning an iterable such that the resulting iterable only ever yields unique items.
def unique_values(func): """ Wrap a function returning an iterable such that the resulting iterable only ever yields unique items. """ @wraps(func) def wrapper(*args, **kwargs): return unique_everseen(func(*args, **kwargs)) return wrapper
[ "def", "unique_values", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "unique_everseen", "(", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "...
[ 201, 0 ]
[ 211, 18 ]
python
en
['en', 'error', 'th']
False
find_external_links
(url, page)
Find rel="homepage" and rel="download" links in `page`, yielding URLs
Find rel="homepage" and rel="download" links in `page`, yielding URLs
def find_external_links(url, page): """Find rel="homepage" and rel="download" links in `page`, yielding URLs""" for match in REL.finditer(page): tag, rel = match.groups() rels = set(map(str.strip, rel.lower().split(','))) if 'homepage' in rels or 'download' in rels: for matc...
[ "def", "find_external_links", "(", "url", ",", "page", ")", ":", "for", "match", "in", "REL", ".", "finditer", "(", "page", ")", ":", "tag", ",", "rel", "=", "match", ".", "groups", "(", ")", "rels", "=", "set", "(", "map", "(", "str", ".", "stri...
[ 219, 0 ]
[ 234, 75 ]
python
en
['en', 'en', 'en']
True
htmldecode
(text)
Decode HTML entities in the given text.
Decode HTML entities in the given text.
def htmldecode(text): """Decode HTML entities in the given text.""" return entity_sub(decode_entity, text)
[ "def", "htmldecode", "(", "text", ")", ":", "return", "entity_sub", "(", "decode_entity", ",", "text", ")" ]
[ 939, 0 ]
[ 941, 42 ]
python
en
['en', 'en', 'en']
True
_encode_auth
(auth)
A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> str(_encode_auth('username%3Apassword')) 'dXNlcm5hbWU6cGFzc3dvcmQ=' Long auth strings should not cause a newline to be inserted. >>> long_auth = 'username:' + 'password'*10 >>> chr(1...
A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> str(_encode_auth('username%3Apassword')) 'dXNlcm5hbWU6cGFzc3dvcmQ='
def _encode_auth(auth): """ A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> str(_encode_auth('username%3Apassword')) 'dXNlcm5hbWU6cGFzc3dvcmQ=' Long auth strings should not cause a newline to be inserted. >>> long_auth = 'username:...
[ "def", "_encode_auth", "(", "auth", ")", ":", "auth_s", "=", "urllib", ".", "parse", ".", "unquote", "(", "auth", ")", "# convert to bytes", "auth_bytes", "=", "auth_s", ".", "encode", "(", ")", "# use the legacy interface for Python 2.3 support", "encoded_bytes", ...
[ 959, 0 ]
[ 979, 36 ]
python
en
['en', 'error', 'th']
False
open_with_auth
(url, opener=urllib.request.urlopen)
Open a urllib2 request, handling HTTP authentication
Open a urllib2 request, handling HTTP authentication
def open_with_auth(url, opener=urllib.request.urlopen): """Open a urllib2 request, handling HTTP authentication""" scheme, netloc, path, params, query, frag = urllib.parse.urlparse(url) # Double scheme does not raise on Mac OS X as revealed by a # failing test. We would expect "nonnumeric port". Refs ...
[ "def", "open_with_auth", "(", "url", ",", "opener", "=", "urllib", ".", "request", ".", "urlopen", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "frag", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")"...
[ 1037, 0 ]
[ 1079, 13 ]
python
en
['en', 'lb', 'en']
True
local_open
(url)
Read a local path, with special support for directories
Read a local path, with special support for directories
def local_open(url): """Read a local path, with special support for directories""" scheme, server, path, param, query, frag = urllib.parse.urlparse(url) filename = urllib.request.url2pathname(path) if os.path.isfile(filename): return urllib.request.urlopen(url) elif path.endswith('/') and os...
[ "def", "local_open", "(", "url", ")", ":", "scheme", ",", "server", ",", "path", ",", "param", ",", "query", ",", "frag", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "filename", "=", "urllib", ".", "request", ".", "url2pathname", "...
[ 1090, 0 ]
[ 1118, 77 ]
python
en
['en', 'en', 'en']
True
ContentChecker.feed
(self, block)
Feed a block of data to the hash.
Feed a block of data to the hash.
def feed(self, block): """ Feed a block of data to the hash. """ return
[ "def", "feed", "(", "self", ",", "block", ")", ":", "return" ]
[ 242, 4 ]
[ 246, 14 ]
python
en
['en', 'error', 'th']
False
ContentChecker.is_valid
(self)
Check the hash. Return False if validation fails.
Check the hash. Return False if validation fails.
def is_valid(self): """ Check the hash. Return False if validation fails. """ return True
[ "def", "is_valid", "(", "self", ")", ":", "return", "True" ]
[ 248, 4 ]
[ 252, 19 ]
python
en
['en', 'error', 'th']
False
ContentChecker.report
(self, reporter, template)
Call reporter with information about the checker (hash name) substituted into the template.
Call reporter with information about the checker (hash name) substituted into the template.
def report(self, reporter, template): """ Call reporter with information about the checker (hash name) substituted into the template. """ return
[ "def", "report", "(", "self", ",", "reporter", ",", "template", ")", ":", "return" ]
[ 254, 4 ]
[ 259, 14 ]
python
en
['en', 'error', 'th']
False
HashChecker.from_url
(cls, url)
Construct a (possibly null) ContentChecker from a URL
Construct a (possibly null) ContentChecker from a URL
def from_url(cls, url): "Construct a (possibly null) ContentChecker from a URL" fragment = urllib.parse.urlparse(url)[-1] if not fragment: return ContentChecker() match = cls.pattern.search(fragment) if not match: return ContentChecker() return cls...
[ "def", "from_url", "(", "cls", ",", "url", ")", ":", "fragment", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "[", "-", "1", "]", "if", "not", "fragment", ":", "return", "ContentChecker", "(", ")", "match", "=", "cls", ".", "patte...
[ 274, 4 ]
[ 282, 39 ]
python
en
['en', 'en', 'en']
True
PackageIndex.process_url
(self, url, retrieve=False)
Evaluate a URL as a possible download, and maybe retrieve it
Evaluate a URL as a possible download, and maybe retrieve it
def process_url(self, url, retrieve=False): """Evaluate a URL as a possible download, and maybe retrieve it""" if url in self.scanned_urls and not retrieve: return self.scanned_urls[url] = True if not URL_SCHEME(url): self.process_filename(url) return ...
[ "def", "process_url", "(", "self", ",", "url", ",", "retrieve", "=", "False", ")", ":", "if", "url", "in", "self", ".", "scanned_urls", "and", "not", "retrieve", ":", "return", "self", ".", "scanned_urls", "[", "url", "]", "=", "True", "if", "not", "...
[ 319, 4 ]
[ 368, 48 ]
python
en
['en', 'en', 'en']
True
PackageIndex.process_index
(self, url, page)
Process the contents of a PyPI page
Process the contents of a PyPI page
def process_index(self, url, page): """Process the contents of a PyPI page""" def scan(link): # Process a URL to see if it's for a package page if link.startswith(self.index_url): parts = list(map( urllib.parse.unquote, link[len(self.index_url...
[ "def", "process_index", "(", "self", ",", "url", ",", "page", ")", ":", "def", "scan", "(", "link", ")", ":", "# Process a URL to see if it's for a package page", "if", "link", ".", "startswith", "(", "self", ".", "index_url", ")", ":", "parts", "=", "list",...
[ 425, 4 ]
[ 466, 21 ]
python
en
['en', 'en', 'en']
True
PackageIndex.check_hash
(self, checker, filename, tfp)
checker is a ContentChecker
checker is a ContentChecker
def check_hash(self, checker, filename, tfp): """ checker is a ContentChecker """ checker.report( self.debug, "Validating %%s checksum for %s" % filename) if not checker.is_valid(): tfp.close() os.unlink(filename) raise ...
[ "def", "check_hash", "(", "self", ",", "checker", ",", "filename", ",", "tfp", ")", ":", "checker", ".", "report", "(", "self", ".", "debug", ",", "\"Validating %%s checksum for %s\"", "%", "filename", ")", "if", "not", "checker", ".", "is_valid", "(", ")"...
[ 507, 4 ]
[ 521, 13 ]
python
en
['en', 'error', 'th']
False
PackageIndex.add_find_links
(self, urls)
Add `urls` to the list that will be prescanned for searches
Add `urls` to the list that will be prescanned for searches
def add_find_links(self, urls): """Add `urls` to the list that will be prescanned for searches""" for url in urls: if ( self.to_scan is None # if we have already "gone online" or not URL_SCHEME(url) # or it's a local file/directory or url.sta...
[ "def", "add_find_links", "(", "self", ",", "urls", ")", ":", "for", "url", "in", "urls", ":", "if", "(", "self", ".", "to_scan", "is", "None", "# if we have already \"gone online\"", "or", "not", "URL_SCHEME", "(", "url", ")", "# or it's a local file/directory",...
[ 523, 4 ]
[ 536, 40 ]
python
en
['en', 'en', 'en']
True
PackageIndex.prescan
(self)
Scan urls scheduled for prescanning (e.g. --find-links)
Scan urls scheduled for prescanning (e.g. --find-links)
def prescan(self): """Scan urls scheduled for prescanning (e.g. --find-links)""" if self.to_scan: list(map(self.scan_url, self.to_scan)) self.to_scan = None
[ "def", "prescan", "(", "self", ")", ":", "if", "self", ".", "to_scan", ":", "list", "(", "map", "(", "self", ".", "scan_url", ",", "self", ".", "to_scan", ")", ")", "self", ".", "to_scan", "=", "None" ]
[ 538, 4 ]
[ 542, 27 ]
python
en
['en', 'de', 'en']
True
PackageIndex.download
(self, spec, tmpdir)
Locate and/or download `spec` to `tmpdir`, returning a local path `spec` may be a ``Requirement`` object, or a string containing a URL, an existing local filename, or a project/version requirement spec (i.e. the string form of a ``Requirement`` object). If it is the URL of a .py file w...
Locate and/or download `spec` to `tmpdir`, returning a local path
def download(self, spec, tmpdir): """Locate and/or download `spec` to `tmpdir`, returning a local path `spec` may be a ``Requirement`` object, or a string containing a URL, an existing local filename, or a project/version requirement spec (i.e. the string form of a ``Requirement`` objec...
[ "def", "download", "(", "self", ",", "spec", ",", "tmpdir", ")", ":", "if", "not", "isinstance", "(", "spec", ",", "Requirement", ")", ":", "scheme", "=", "URL_SCHEME", "(", "spec", ")", "if", "scheme", ":", "# It's a url, download it to tmpdir", "found", ...
[ 554, 4 ]
[ 586, 79 ]
python
en
['en', 'en', 'en']
True
PackageIndex.fetch_distribution
( self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None)
Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `force_scan` flag is set, the requirement is searched for in the (online) package index as well as the locally installed packages. If a di...
Obtain a distribution suitable for fulfilling `requirement`
def fetch_distribution( self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None): """Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the ...
[ "def", "fetch_distribution", "(", "self", ",", "requirement", ",", "tmpdir", ",", "force_scan", "=", "False", ",", "source", "=", "False", ",", "develop_ok", "=", "False", ",", "local_index", "=", "None", ")", ":", "# process a Requirement", "self", ".", "in...
[ 588, 4 ]
[ 662, 62 ]
python
en
['en', 'en', 'en']
True
PackageIndex.fetch
(self, requirement, tmpdir, force_scan=False, source=False)
Obtain a file suitable for fulfilling `requirement` DEPRECATED; use the ``fetch_distribution()`` method now instead. For backward compatibility, this routine is identical but returns the ``location`` of the downloaded distribution instead of a distribution object.
Obtain a file suitable for fulfilling `requirement`
def fetch(self, requirement, tmpdir, force_scan=False, source=False): """Obtain a file suitable for fulfilling `requirement` DEPRECATED; use the ``fetch_distribution()`` method now instead. For backward compatibility, this routine is identical but returns the ``location`` of the downlo...
[ "def", "fetch", "(", "self", ",", "requirement", ",", "tmpdir", ",", "force_scan", "=", "False", ",", "source", "=", "False", ")", ":", "dist", "=", "self", ".", "fetch_distribution", "(", "requirement", ",", "tmpdir", ",", "force_scan", ",", "source", "...
[ 664, 4 ]
[ 675, 19 ]
python
en
['en', 'en', 'en']
True
PyPIConfig.__init__
(self)
Load from ~/.pypirc
Load from ~/.pypirc
def __init__(self): """ Load from ~/.pypirc """ defaults = dict.fromkeys(['username', 'password', 'repository'], '') configparser.RawConfigParser.__init__(self, defaults) rc = os.path.join(os.path.expanduser('~'), '.pypirc') if os.path.exists(rc): sel...
[ "def", "__init__", "(", "self", ")", ":", "defaults", "=", "dict", ".", "fromkeys", "(", "[", "'username'", ",", "'password'", ",", "'repository'", "]", ",", "''", ")", "configparser", ".", "RawConfigParser", ".", "__init__", "(", "self", ",", "defaults", ...
[ 1000, 4 ]
[ 1009, 25 ]
python
en
['en', 'error', 'th']
False
PyPIConfig.find_credential
(self, url)
If the URL indicated appears to be a repository defined in this config, return the credential for that repository.
If the URL indicated appears to be a repository defined in this config, return the credential for that repository.
def find_credential(self, url): """ If the URL indicated appears to be a repository defined in this config, return the credential for that repository. """ for repository, cred in self.creds_by_repository.items(): if url.startswith(repository): return c...
[ "def", "find_credential", "(", "self", ",", "url", ")", ":", "for", "repository", ",", "cred", "in", "self", ".", "creds_by_repository", ".", "items", "(", ")", ":", "if", "url", ".", "startswith", "(", "repository", ")", ":", "return", "cred" ]
[ 1027, 4 ]
[ 1034, 27 ]
python
en
['en', 'error', 'th']
False
get_pin_and_cookie_name
(app)
Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`. Second item in the resulting tuple is the cookie name for ...
Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`.
def get_pin_and_cookie_name(app): """Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`. Second item in th...
[ "def", "get_pin_and_cookie_name", "(", "app", ")", ":", "pin", "=", "os", ".", "environ", ".", "get", "(", "\"WERKZEUG_DEBUG_PIN\"", ")", "rv", "=", "None", "num", "=", "None", "# Pin was explicitly disabled", "if", "pin", "==", "\"off\"", ":", "return", "No...
[ 147, 0 ]
[ 227, 26 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.pin_cookie_name
(self)
The name of the pin cookie.
The name of the pin cookie.
def pin_cookie_name(self): """The name of the pin cookie.""" if not hasattr(self, "_pin_cookie"): self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app) return self._pin_cookie
[ "def", "pin_cookie_name", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_pin_cookie\"", ")", ":", "self", ".", "_pin", ",", "self", ".", "_pin_cookie", "=", "get_pin_and_cookie_name", "(", "self", ".", "app", ")", "return", "self", ...
[ 319, 4 ]
[ 323, 31 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.debug_application
(self, environ, start_response)
Run the application and conserve the traceback frames.
Run the application and conserve the traceback frames.
def debug_application(self, environ, start_response): """Run the application and conserve the traceback frames.""" app_iter = None try: app_iter = self.app(environ, start_response) for item in app_iter: yield item if hasattr(app_iter, "close"):...
[ "def", "debug_application", "(", "self", ",", "environ", ",", "start_response", ")", ":", "app_iter", "=", "None", "try", ":", "app_iter", "=", "self", ".", "app", "(", "environ", ",", "start_response", ")", "for", "item", "in", "app_iter", ":", "yield", ...
[ 325, 4 ]
[ 372, 49 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.execute_command
(self, request, command, frame)
Execute a command in a console.
Execute a command in a console.
def execute_command(self, request, command, frame): """Execute a command in a console.""" return Response(frame.console.eval(command), mimetype="text/html")
[ "def", "execute_command", "(", "self", ",", "request", ",", "command", ",", "frame", ")", ":", "return", "Response", "(", "frame", ".", "console", ".", "eval", "(", "command", ")", ",", "mimetype", "=", "\"text/html\"", ")" ]
[ 374, 4 ]
[ 376, 74 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.display_console
(self, request)
Display a standalone shell.
Display a standalone shell.
def display_console(self, request): """Display a standalone shell.""" if 0 not in self.frames: if self.console_init_func is None: ns = {} else: ns = dict(self.console_init_func()) ns.setdefault("app", self.app) self.frames[0...
[ "def", "display_console", "(", "self", ",", "request", ")", ":", "if", "0", "not", "in", "self", ".", "frames", ":", "if", "self", ".", "console_init_func", "is", "None", ":", "ns", "=", "{", "}", "else", ":", "ns", "=", "dict", "(", "self", ".", ...
[ 378, 4 ]
[ 391, 9 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.paste_traceback
(self, request, traceback)
Paste the traceback and return a JSON response.
Paste the traceback and return a JSON response.
def paste_traceback(self, request, traceback): """Paste the traceback and return a JSON response.""" rv = traceback.paste() return Response(json.dumps(rv), mimetype="application/json")
[ "def", "paste_traceback", "(", "self", ",", "request", ",", "traceback", ")", ":", "rv", "=", "traceback", ".", "paste", "(", ")", "return", "Response", "(", "json", ".", "dumps", "(", "rv", ")", ",", "mimetype", "=", "\"application/json\"", ")" ]
[ 393, 4 ]
[ 396, 68 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.get_resource
(self, request, filename)
Return a static resource from the shared folder.
Return a static resource from the shared folder.
def get_resource(self, request, filename): """Return a static resource from the shared folder.""" filename = join("shared", basename(filename)) try: data = pkgutil.get_data(__package__, filename) except OSError: data = None if data is not None: ...
[ "def", "get_resource", "(", "self", ",", "request", ",", "filename", ")", ":", "filename", "=", "join", "(", "\"shared\"", ",", "basename", "(", "filename", ")", ")", "try", ":", "data", "=", "pkgutil", ".", "get_data", "(", "__package__", ",", "filename...
[ 398, 4 ]
[ 408, 48 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.check_pin_trust
(self, environ)
Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be taken.
Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be taken.
def check_pin_trust(self, environ): """Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be...
[ "def", "check_pin_trust", "(", "self", ",", "environ", ")", ":", "if", "self", ".", "pin", "is", "None", ":", "return", "True", "val", "=", "parse_cookie", "(", "environ", ")", ".", "get", "(", "self", ".", "pin_cookie_name", ")", "if", "not", "val", ...
[ 410, 4 ]
[ 426, 49 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.pin_auth
(self, request)
Authenticates with the pin.
Authenticates with the pin.
def pin_auth(self, request): """Authenticates with the pin.""" exhausted = False auth = False trust = self.check_pin_trust(request.environ) # If the trust return value is `None` it means that the cookie is # set but the stored pin hash value is bad. This means that the ...
[ "def", "pin_auth", "(", "self", ",", "request", ")", ":", "exhausted", "=", "False", "auth", "=", "False", "trust", "=", "self", ".", "check_pin_trust", "(", "request", ".", "environ", ")", "# If the trust return value is `None` it means that the cookie is", "# set ...
[ 432, 4 ]
[ 477, 17 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.log_pin_request
(self)
Log the pin if needed.
Log the pin if needed.
def log_pin_request(self): """Log the pin if needed.""" if self.pin_logging and self.pin is not None: _log( "info", " * To enable the debugger you need to enter the security pin:" ) _log("info", " * Debugger pin code: %s" % self.pin) return Res...
[ "def", "log_pin_request", "(", "self", ")", ":", "if", "self", ".", "pin_logging", "and", "self", ".", "pin", "is", "not", "None", ":", "_log", "(", "\"info\"", ",", "\" * To enable the debugger you need to enter the security pin:\"", ")", "_log", "(", "\"info\"",...
[ 479, 4 ]
[ 486, 27 ]
python
en
['en', 'en', 'en']
True
DebuggedApplication.__call__
(self, environ, start_response)
Dispatch the requests.
Dispatch the requests.
def __call__(self, environ, start_response): """Dispatch the requests.""" # important: don't ever access a function here that reads the incoming # form data! Otherwise the application won't have access to that data # any more! request = Request(environ) response = self.d...
[ "def", "__call__", "(", "self", ",", "environ", ",", "start_response", ")", ":", "# important: don't ever access a function here that reads the incoming", "# form data! Otherwise the application won't have access to that data", "# any more!", "request", "=", "Request", "(", "envir...
[ 488, 4 ]
[ 523, 48 ]
python
en
['en', 'en', 'en']
True
read_quizfile
(quizfile)
Reads the quiz file into a big dictionary.
Reads the quiz file into a big dictionary.
def read_quizfile(quizfile): "Reads the quiz file into a big dictionary." try: with open(quizfile) as f: linelist = f.readlines() except IOError: questionlist = None else: questionlist = [] # Splits the line into category:question*answers match groups. ...
[ "def", "read_quizfile", "(", "quizfile", ")", ":", "try", ":", "with", "open", "(", "quizfile", ")", "as", "f", ":", "linelist", "=", "f", ".", "readlines", "(", ")", "except", "IOError", ":", "questionlist", "=", "None", "else", ":", "questionlist", "...
[ 8, 0 ]
[ 24, 23 ]
python
en
['en', 'en', 'en']
True
update_hint
(factory)
Create a hint for an answer.
Create a hint for an answer.
def update_hint(factory): "Create a hint for an answer." hint = list(factory.hint) answer = factory.answer count = 0 while count < 3: index = random.randrange(len(answer)) if hint[index] == "_": hint[index] = answer[index] count += 1 factory.hint = "".joi...
[ "def", "update_hint", "(", "factory", ")", ":", "hint", "=", "list", "(", "factory", ".", "hint", ")", "answer", "=", "factory", ".", "answer", "count", "=", "0", "while", "count", "<", "3", ":", "index", "=", "random", ".", "randrange", "(", "len", ...
[ 27, 0 ]
[ 38, 32 ]
python
en
['en', 'en', 'en']
True
command_quiz
(bot, user, channel, args)
A very basic quiz bot. No hints, no points. Usage: quiz [on|off|<delay>].
A very basic quiz bot. No hints, no points. Usage: quiz [on|off|<delay>].
def command_quiz(bot, user, channel, args): "A very basic quiz bot. No hints, no points. Usage: quiz [on|off|<delay>]." # TODO: delay = 25 if args == "hint" or args == "clue": update_hint(bot.factory) return bot.say(channel, bot.factory.hint) elif args == "on": bot.factory.q...
[ "def", "command_quiz", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "# TODO:", "delay", "=", "25", "if", "args", "==", "\"hint\"", "or", "args", "==", "\"clue\"", ":", "update_hint", "(", "bot", ".", "factory", ")", "return", "bot", ...
[ 41, 0 ]
[ 81, 29 ]
python
en
['es', 'en', 'en']
True
report
(crawler, file=None)
Print a report on all completed URLs.
Print a report on all completed URLs.
def report(crawler, file=None): """Print a report on all completed URLs.""" t1 = crawler.t1 or time.time() dt = t1 - crawler.t0 if dt and crawler.max_tasks: speed = len(crawler.done) / dt / crawler.max_tasks else: speed = 0 stats = Stats() print('*** Report ***', file=file) ...
[ "def", "report", "(", "crawler", ",", "file", "=", "None", ")", ":", "t1", "=", "crawler", ".", "t1", "or", "time", ".", "time", "(", ")", "dt", "=", "t1", "-", "crawler", ".", "t0", "if", "dt", "and", "crawler", ".", "max_tasks", ":", "speed", ...
[ 19, 0 ]
[ 47, 57 ]
python
en
['en', 'en', 'en']
True
fetcher_report
(fetcher, stats, file=None)
Print a report on the state for this URL. Also update the Stats instance.
Print a report on the state for this URL.
def fetcher_report(fetcher, stats, file=None): """Print a report on the state for this URL. Also update the Stats instance. """ if fetcher.task is not None: if not fetcher.task.done(): stats.add('pending') print(fetcher.url, 'pending', file=file) return ...
[ "def", "fetcher_report", "(", "fetcher", ",", "stats", ",", "file", "=", "None", ")", ":", "if", "fetcher", ".", "task", "is", "not", "None", ":", "if", "not", "fetcher", ".", "task", ".", "done", "(", ")", ":", "stats", ".", "add", "(", "'pending'...
[ 50, 0 ]
[ 100, 24 ]
python
en
['en', 'en', 'en']
True
CurrentSiteManager._get_field_name
(self)
Return self.__field_name or 'site' or 'sites'.
Return self.__field_name or 'site' or 'sites'.
def _get_field_name(self): """ Return self.__field_name or 'site' or 'sites'. """ if not self.__field_name: try: self.model._meta.get_field('site') except FieldDoesNotExist: self.__field_name = 'sites' else: self.__fiel...
[ "def", "_get_field_name", "(", "self", ")", ":", "if", "not", "self", ".", "__field_name", ":", "try", ":", "self", ".", "model", ".", "_meta", ".", "get_field", "(", "'site'", ")", "except", "FieldDoesNotExist", ":", "self", ".", "__field_name", "=", "'...
[ 46, 4 ]
[ 56, 32 ]
python
en
['en', 'en', 'en']
True
threadsafe_generator
(f)
A decorator that takes a generator function and makes it thread-safe.
A decorator that takes a generator function and makes it thread-safe.
def threadsafe_generator(f): """A decorator that takes a generator function and makes it thread-safe. """ def g(*a, **kw): return threadsafe_iter(f(*a, **kw)) return g
[ "def", "threadsafe_generator", "(", "f", ")", ":", "def", "g", "(", "*", "a", ",", "*", "*", "kw", ")", ":", "return", "threadsafe_iter", "(", "f", "(", "*", "a", ",", "*", "*", "kw", ")", ")", "return", "g" ]
[ 32, 0 ]
[ 37, 12 ]
python
en
['en', 'en', 'en']
True
localize
(value)
Force a value to be rendered as a localized value, regardless of the value of ``settings.USE_L10N``.
Force a value to be rendered as a localized value, regardless of the value of ``settings.USE_L10N``.
def localize(value): """ Force a value to be rendered as a localized value, regardless of the value of ``settings.USE_L10N``. """ return str(formats.localize(value, use_l10n=True))
[ "def", "localize", "(", "value", ")", ":", "return", "str", "(", "formats", ".", "localize", "(", "value", ",", "use_l10n", "=", "True", ")", ")" ]
[ 7, 0 ]
[ 12, 54 ]
python
en
['en', 'error', 'th']
False
unlocalize
(value)
Force a value to be rendered as a non-localized value, regardless of the value of ``settings.USE_L10N``.
Force a value to be rendered as a non-localized value, regardless of the value of ``settings.USE_L10N``.
def unlocalize(value): """ Force a value to be rendered as a non-localized value, regardless of the value of ``settings.USE_L10N``. """ return str(formats.localize(value, use_l10n=False))
[ "def", "unlocalize", "(", "value", ")", ":", "return", "str", "(", "formats", ".", "localize", "(", "value", ",", "use_l10n", "=", "False", ")", ")" ]
[ 16, 0 ]
[ 21, 55 ]
python
en
['en', 'error', 'th']
False
localize_tag
(parser, token)
Force or prevents localization of values, regardless of the value of `settings.USE_L10N`. Sample usage:: {% localize off %} var pi = {{ 3.1415 }}; {% endlocalize %}
Force or prevents localization of values, regardless of the value of `settings.USE_L10N`.
def localize_tag(parser, token): """ Force or prevents localization of values, regardless of the value of `settings.USE_L10N`. Sample usage:: {% localize off %} var pi = {{ 3.1415 }}; {% endlocalize %} """ use_l10n = None bits = list(token.split_contents()) ...
[ "def", "localize_tag", "(", "parser", ",", "token", ")", ":", "use_l10n", "=", "None", "bits", "=", "list", "(", "token", ".", "split_contents", "(", ")", ")", "if", "len", "(", "bits", ")", "==", "1", ":", "use_l10n", "=", "True", "elif", "len", "...
[ 41, 0 ]
[ 62, 43 ]
python
en
['en', 'error', 'th']
False
publish_feedback
(feedback)
pull_feedback Starts pulling messages from subscription - receive callback function from calling module - initiate the pull providing the callback function
pull_feedback
def publish_feedback(feedback): # TODO: Publish the feedback object to the feedback topic # END TODO """pull_feedback Starts pulling messages from subscription - receive callback function from calling module - initiate the pull providing the callback function """
[ "def", "publish_feedback", "(", "feedback", ")", ":", "# TODO: Publish the feedback object to the feedback topic", "# END TODO" ]
[ 57, 0 ]
[ 73, 3 ]
python
en
['en', 'cy', 'en']
False
interpret
(marker, execution_context=None)
Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping
Interpret a marker and return a result depending on environment.
def interpret(marker, execution_context=None): """ Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping """ try: exp...
[ "def", "interpret", "(", "marker", ",", "execution_context", "=", "None", ")", ":", "try", ":", "expr", ",", "rest", "=", "parse_marker", "(", "marker", ")", "except", "Exception", "as", "e", ":", "raise", "SyntaxError", "(", "'Unable to interpret marker synta...
[ 111, 0 ]
[ 129, 44 ]
python
en
['en', 'error', 'th']
False
Evaluator.evaluate
(self, expr, context)
Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context.
Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context.
def evaluate(self, expr, context): """ Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context. """ if isinstance(expr, string_types): if expr[0] in '\'"': result = expr[1:-1] else: ...
[ "def", "evaluate", "(", "self", ",", "expr", ",", "context", ")", ":", "if", "isinstance", "(", "expr", ",", "string_types", ")", ":", "if", "expr", "[", "0", "]", "in", "'\\'\"'", ":", "result", "=", "expr", "[", "1", ":", "-", "1", "]", "else",...
[ 48, 4 ]
[ 73, 21 ]
python
en
['en', 'error', 'th']
False
generic_inlineformset_factory
(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, ...
Return a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively.
Return a ``GenericInlineFormSet`` for the given kwargs.
def generic_inlineformset_factory(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=...
[ "def", "generic_inlineformset_factory", "(", "model", ",", "form", "=", "ModelForm", ",", "formset", "=", "BaseGenericInlineFormSet", ",", "ct_field", "=", "\"content_type\"", ",", "fk_field", "=", "\"object_id\"", ",", "fields", "=", "None", ",", "exclude", "=", ...
[ 51, 0 ]
[ 83, 18 ]
python
en
['en', 'error', 'th']
False
getLogger
(name: str)
logging.getLogger, but ensures our VerboseLogger class is returned
logging.getLogger, but ensures our VerboseLogger class is returned
def getLogger(name: str) -> VerboseLogger: """logging.getLogger, but ensures our VerboseLogger class is returned""" return cast(VerboseLogger, logging.getLogger(name))
[ "def", "getLogger", "(", "name", ":", "str", ")", "->", "VerboseLogger", ":", "return", "cast", "(", "VerboseLogger", ",", "logging", ".", "getLogger", "(", "name", ")", ")" ]
[ 25, 0 ]
[ 27, 55 ]
python
en
['en', 'en', 'en']
True
init_logging
()
Register our VerboseLogger and VERBOSE log level. Should be called before any calls to getLogger(), i.e. in pip._internal.__init__
Register our VerboseLogger and VERBOSE log level.
def init_logging() -> None: """Register our VerboseLogger and VERBOSE log level. Should be called before any calls to getLogger(), i.e. in pip._internal.__init__ """ logging.setLoggerClass(VerboseLogger) logging.addLevelName(VERBOSE, "VERBOSE")
[ "def", "init_logging", "(", ")", "->", "None", ":", "logging", ".", "setLoggerClass", "(", "VerboseLogger", ")", "logging", ".", "addLevelName", "(", "VERBOSE", ",", "\"VERBOSE\"", ")" ]
[ 30, 0 ]
[ 37, 44 ]
python
en
['en', 'da', 'en']
True
_download_and_clean_file
(filename, url)
Downloads data from url, and makes changes to match the CSV format. The CSVs may use spaces after the comma delimters (non-standard) or include rows which do not represent well-formed examples. This function strips out some of these problems. Args: filename: filename to save url to url: UR...
Downloads data from url, and makes changes to match the CSV format.
def _download_and_clean_file(filename, url): """Downloads data from url, and makes changes to match the CSV format. The CSVs may use spaces after the comma delimters (non-standard) or include rows which do not represent well-formed examples. This function strips out some of these problems. Args: ...
[ "def", "_download_and_clean_file", "(", "filename", ",", "url", ")", ":", "temp_file", ",", "_", "=", "urllib", ".", "request", ".", "urlretrieve", "(", "url", ")", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "temp_file", ",", "'r'", ")",...
[ 100, 0 ]
[ 123, 33 ]
python
en
['en', 'en', 'en']
True
download
(data_dir)
Downloads census data if it is not already present. Args: data_dir: directory where we will access/save the census data
Downloads census data if it is not already present.
def download(data_dir): """Downloads census data if it is not already present. Args: data_dir: directory where we will access/save the census data """ tf.io.gfile.makedirs(data_dir) training_file_path = os.path.join(data_dir, TRAINING_FILE) if not tf.io.gfile.exists(training_file_path): ...
[ "def", "download", "(", "data_dir", ")", ":", "tf", ".", "io", ".", "gfile", ".", "makedirs", "(", "data_dir", ")", "training_file_path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "TRAINING_FILE", ")", "if", "not", "tf", ".", "io", "...
[ 126, 0 ]
[ 142, 45 ]
python
en
['en', 'en', 'en']
True
preprocess
(dataframe)
Converts categorical features to numeric. Removes unused columns. Args: dataframe: Pandas dataframe with raw data Returns: Dataframe with preprocessed data
Converts categorical features to numeric. Removes unused columns.
def preprocess(dataframe): """Converts categorical features to numeric. Removes unused columns. Args: dataframe: Pandas dataframe with raw data Returns: Dataframe with preprocessed data """ dataframe = dataframe.drop(columns=UNUSED_COLUMNS) # Convert integer valued (numeric) colum...
[ "def", "preprocess", "(", "dataframe", ")", ":", "dataframe", "=", "dataframe", ".", "drop", "(", "columns", "=", "UNUSED_COLUMNS", ")", "# Convert integer valued (numeric) columns to floating point", "numeric_columns", "=", "dataframe", ".", "select_dtypes", "(", "[", ...
[ 145, 0 ]
[ 165, 20 ]
python
en
['en', 'en', 'en']
True
standardize
(dataframe)
Scales numerical columns using their means and standard deviation to get z-scores: the mean of each numerical column becomes 0, and the standard deviation becomes 1. This can help the model converge during training. Args: dataframe: Pandas dataframe Returns: Input dataframe with the numeri...
Scales numerical columns using their means and standard deviation to get z-scores: the mean of each numerical column becomes 0, and the standard deviation becomes 1. This can help the model converge during training.
def standardize(dataframe): """Scales numerical columns using their means and standard deviation to get z-scores: the mean of each numerical column becomes 0, and the standard deviation becomes 1. This can help the model converge during training. Args: dataframe: Pandas dataframe Returns: ...
[ "def", "standardize", "(", "dataframe", ")", ":", "dtypes", "=", "list", "(", "zip", "(", "dataframe", ".", "dtypes", ".", "index", ",", "map", "(", "str", ",", "dataframe", ".", "dtypes", ")", ")", ")", "# Normalize numeric columns.", "for", "column", "...
[ 168, 0 ]
[ 185, 20 ]
python
en
['en', 'en', 'en']
True
load_data
()
Loads data into preprocessed (train_x, train_y, eval_y, eval_y) dataframes. Returns: A tuple (train_x, train_y, eval_x, eval_y), where train_x and eval_x are Pandas dataframes with features for training and train_y and eval_y are numpy arrays with the corresponding labels.
Loads data into preprocessed (train_x, train_y, eval_y, eval_y) dataframes.
def load_data(): """Loads data into preprocessed (train_x, train_y, eval_y, eval_y) dataframes. Returns: A tuple (train_x, train_y, eval_x, eval_y), where train_x and eval_x are Pandas dataframes with features for training and train_y and eval_y are numpy arrays with the corresponding lab...
[ "def", "load_data", "(", ")", ":", "# Download Census dataset: Training and eval csv files.", "training_file_path", ",", "eval_file_path", "=", "download", "(", "DATA_DIR", ")", "# This census data uses the value '?' for missing entries. We use", "# na_values to", "# find ? and set i...
[ 188, 0 ]
[ 227, 43 ]
python
en
['en', 'es', 'en']
True
JSONWebSignatureSerializer.dumps
(self, obj, salt=None, header_fields=None)
Like :meth:`.Serializer.dumps` but creates a JSON Web Signature. It also allows for specifying additional fields to be included in the JWS header.
Like :meth:`.Serializer.dumps` but creates a JSON Web Signature. It also allows for specifying additional fields to be included in the JWS header.
def dumps(self, obj, salt=None, header_fields=None): """Like :meth:`.Serializer.dumps` but creates a JSON Web Signature. It also allows for specifying additional fields to be included in the JWS header. """ header = self.make_header(header_fields) signer = self.make_signe...
[ "def", "dumps", "(", "self", ",", "obj", ",", "salt", "=", "None", ",", "header_fields", "=", "None", ")", ":", "header", "=", "self", ".", "make_header", "(", "header_fields", ")", "signer", "=", "self", ".", "make_signer", "(", "salt", ",", "self", ...
[ 128, 4 ]
[ 135, 58 ]
python
en
['en', 'en', 'en']
True
JSONWebSignatureSerializer.loads
(self, s, salt=None, return_header=False)
Reverse of :meth:`dumps`. If requested via ``return_header`` it will return a tuple of payload and header.
Reverse of :meth:`dumps`. If requested via ``return_header`` it will return a tuple of payload and header.
def loads(self, s, salt=None, return_header=False): """Reverse of :meth:`dumps`. If requested via ``return_header`` it will return a tuple of payload and header. """ payload, header = self.load_payload( self.make_signer(salt, self.algorithm).unsign(want_bytes(s)), ...
[ "def", "loads", "(", "self", ",", "s", ",", "salt", "=", "None", ",", "return_header", "=", "False", ")", ":", "payload", ",", "header", "=", "self", ".", "load_payload", "(", "self", ".", "make_signer", "(", "salt", ",", "self", ".", "algorithm", ")...
[ 137, 4 ]
[ 149, 22 ]
python
en
['en', 'en', 'en']
True
_contains_egg_info
(s)
Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1
Determine whether the string looks like an egg_info.
def _contains_egg_info(s): # type: (str) -> bool """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s))
[ "def", "_contains_egg_info", "(", "s", ")", ":", "# type: (str) -> bool", "return", "bool", "(", "_egg_info_re", ".", "search", "(", "s", ")", ")" ]
[ 36, 0 ]
[ 42, 39 ]
python
en
['en', 'en', 'en']
True
_should_build
( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate )
Return whether an InstallRequirement should be built into a wheel.
Return whether an InstallRequirement should be built into a wheel.
def _should_build( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate ): # type: (...) -> bool """Return whether an InstallRequirement should be built into a wheel.""" if req.constraint: # never build requirements that are mer...
[ "def", "_should_build", "(", "req", ",", "# type: InstallRequirement", "need_wheel", ",", "# type: bool", "check_binary_allowed", ",", "# type: BinaryAllowedPredicate", ")", ":", "# type: (...) -> bool", "if", "req", ".", "constraint", ":", "# never build requirements that ar...
[ 45, 0 ]
[ 90, 15 ]
python
en
['en', 'en', 'en']
True
_should_cache
( req, # type: InstallRequirement )
Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built.
Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built.
def _should_cache( req, # type: InstallRequirement ): # type: (...) -> Optional[bool] """ Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built. """ if re...
[ "def", "_should_cache", "(", "req", ",", "# type: InstallRequirement", ")", ":", "# type: (...) -> Optional[bool]", "if", "req", ".", "editable", "or", "not", "req", ".", "source_dir", ":", "# never cache editable requirements", "return", "False", "if", "req", ".", ...
[ 112, 0 ]
[ 142, 16 ]
python
en
['en', 'error', 'th']
False
_get_cache_dir
( req, # type: InstallRequirement wheel_cache, # type: WheelCache )
Return the persistent or temporary cache directory where the built wheel need to be stored.
Return the persistent or temporary cache directory where the built wheel need to be stored.
def _get_cache_dir( req, # type: InstallRequirement wheel_cache, # type: WheelCache ): # type: (...) -> str """Return the persistent or temporary cache directory where the built wheel need to be stored. """ cache_available = bool(wheel_cache.cache_dir) assert req.link if cache_avai...
[ "def", "_get_cache_dir", "(", "req", ",", "# type: InstallRequirement", "wheel_cache", ",", "# type: WheelCache", ")", ":", "# type: (...) -> str", "cache_available", "=", "bool", "(", "wheel_cache", ".", "cache_dir", ")", "assert", "req", ".", "link", "if", "cache_...
[ 145, 0 ]
[ 159, 20 ]
python
en
['en', 'en', 'en']
True
_build_one
( req, # type: InstallRequirement output_dir, # type: str verify, # type: bool build_options, # type: List[str] global_options, # type: List[str] )
Build one wheel. :return: The filename of the built wheel, or None if the build failed.
Build one wheel.
def _build_one( req, # type: InstallRequirement output_dir, # type: str verify, # type: bool build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> Optional[str] """Build one wheel. :return: The filename of the built wheel, or None if the build faile...
[ "def", "_build_one", "(", "req", ",", "# type: InstallRequirement", "output_dir", ",", "# type: str", "verify", ",", "# type: bool", "build_options", ",", "# type: List[str]", "global_options", ",", "# type: List[str]", ")", ":", "# type: (...) -> Optional[str]", "try", "...
[ 199, 0 ]
[ 231, 21 ]
python
en
['en', 'sr', 'en']
True
build
( requirements, # type: Iterable[InstallRequirement] wheel_cache, # type: WheelCache verify, # type: bool build_options, # type: List[str] global_options, # type: List[str] )
Build wheels. :return: The list of InstallRequirement that succeeded to build and the list of InstallRequirement that failed to build.
Build wheels.
def build( requirements, # type: Iterable[InstallRequirement] wheel_cache, # type: WheelCache verify, # type: bool build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> BuildResult """Build wheels. :return: The list of InstallRequirement that succee...
[ "def", "build", "(", "requirements", ",", "# type: Iterable[InstallRequirement]", "wheel_cache", ",", "# type: WheelCache", "verify", ",", "# type: bool", "build_options", ",", "# type: List[str]", "global_options", ",", "# type: List[str]", ")", ":", "# type: (...) -> BuildR...
[ 309, 0 ]
[ 359, 42 ]
python
en
['en', 'sr', 'en']
False
do_get_available_languages
(parser, token)
Store a list of available languages in the context. Usage:: {% get_available_languages as languages %} {% for language in languages %} ... {% endfor %} This puts settings.LANGUAGES into the named variable.
Store a list of available languages in the context.
def do_get_available_languages(parser, token): """ Store a list of available languages in the context. Usage:: {% get_available_languages as languages %} {% for language in languages %} ... {% endfor %} This puts settings.LANGUAGES into the named variable. """ ...
[ "def", "do_get_available_languages", "(", "parser", ",", "token", ")", ":", "# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments", "args", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "args", ")", ...
[ 198, 0 ]
[ 215, 45 ]
python
en
['en', 'error', 'th']
False
do_get_language_info
(parser, token)
Store the language information dictionary for the given language code in a context variable. Usage:: {% get_language_info for LANGUAGE_CODE as l %} {{ l.code }} {{ l.name }} {{ l.name_translated }} {{ l.name_local }} {{ l.bidi|yesno:"bi-directional,uni-dire...
Store the language information dictionary for the given language code in a context variable.
def do_get_language_info(parser, token): """ Store the language information dictionary for the given language code in a context variable. Usage:: {% get_language_info for LANGUAGE_CODE as l %} {{ l.code }} {{ l.name }} {{ l.name_translated }} {{ l.name_local }} ...
[ "def", "do_get_language_info", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "args", ")", "!=", "5", "or", "args", "[", "1", "]", "!=", "'for'", "or", "args", "[", "3", "]", "!=", ...
[ 219, 0 ]
[ 236, 71 ]
python
en
['en', 'error', 'th']
False
do_get_language_info_list
(parser, token)
Store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style list (or any sequence of sequences whose first items are language codes). Usage:: {% get_lang...
Store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style list (or any sequence of sequences whose first items are language codes).
def do_get_language_info_list(parser, token): """ Store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style list (or any sequence of sequences whose first items a...
[ "def", "do_get_language_info_list", "(", "parser", ",", "token", ")", ":", "args", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "args", ")", "!=", "5", "or", "args", "[", "1", "]", "!=", "'for'", "or", "args", "[", "3", "]", "!=...
[ 240, 0 ]
[ 261, 75 ]
python
en
['en', 'error', 'th']
False
do_get_current_language
(parser, token)
Store the current language in the context. Usage:: {% get_current_language as language %} This fetches the currently active language and puts its value into the ``language`` context variable.
Store the current language in the context.
def do_get_current_language(parser, token): """ Store the current language in the context. Usage:: {% get_current_language as language %} This fetches the currently active language and puts its value into the ``language`` context variable. """ # token.split_contents() isn't useful...
[ "def", "do_get_current_language", "(", "parser", ",", "token", ")", ":", "# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments", "args", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "args", ")", "!=...
[ 286, 0 ]
[ 301, 42 ]
python
en
['en', 'error', 'th']
False
do_get_current_language_bidi
(parser, token)
Store the current language layout in the context. Usage:: {% get_current_language_bidi as bidi %} This fetches the currently active language's layout and puts its value into the ``bidi`` context variable. True indicates right-to-left layout, otherwise left-to-right.
Store the current language layout in the context.
def do_get_current_language_bidi(parser, token): """ Store the current language layout in the context. Usage:: {% get_current_language_bidi as bidi %} This fetches the currently active language's layout and puts its value into the ``bidi`` context variable. True indicates right-to-left la...
[ "def", "do_get_current_language_bidi", "(", "parser", ",", "token", ")", ":", "# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments", "args", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "args", ")", ...
[ 305, 0 ]
[ 321, 46 ]
python
en
['en', 'error', 'th']
False
do_translate
(parser, token)
Mark a string for translation and translate the string for the current language. Usage:: {% translate "this is a test" %} This marks the string for translation so it will be pulled out by makemessages into the .po files and runs the string through the translation engine. There i...
Mark a string for translation and translate the string for the current language.
def do_translate(parser, token): """ Mark a string for translation and translate the string for the current language. Usage:: {% translate "this is a test" %} This marks the string for translation so it will be pulled out by makemessages into the .po files and runs the string through ...
[ "def", "do_translate", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "<", "2", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes at least one argument\"", "%", "bits", "[", ...
[ 326, 0 ]
[ 415, 70 ]
python
en
['en', 'error', 'th']
False
do_block_translate
(parser, token)
Translate a block of text with parameters. Usage:: {% blocktranslate with bar=foo|filter boo=baz|filter %} This is {{ bar }} and {{ boo }}. {% endblocktranslate %} Additionally, this supports pluralization:: {% blocktranslate count count=var|length %} There is {{...
Translate a block of text with parameters.
def do_block_translate(parser, token): """ Translate a block of text with parameters. Usage:: {% blocktranslate with bar=foo|filter boo=baz|filter %} This is {{ bar }} and {{ boo }}. {% endblocktranslate %} Additionally, this supports pluralization:: {% blocktranslate...
[ "def", "do_block_translate", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "options", "=", "{", "}", "remaining_bits", "=", "bits", "[", "1", ":", "]", "asvar", "=", "None", "while", "remaining_bits", ":", ...
[ 420, 0 ]
[ 539, 60 ]
python
en
['en', 'error', 'th']
False
language
(parser, token)
Enable the given language just for this block. Usage:: {% language "de" %} This is {{ bar }} and {{ boo }}. {% endlanguage %}
Enable the given language just for this block.
def language(parser, token): """ Enable the given language just for this block. Usage:: {% language "de" %} This is {{ bar }} and {{ boo }}. {% endlanguage %} """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argu...
[ "def", "language", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "!=", "2", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes one argument (language)\"", "%", "bits", "[", ...
[ 543, 0 ]
[ 559, 43 ]
python
en
['en', 'error', 'th']
False
preprocessing_judgement
(pred, bias)
前処理判断 :pred bias: model.predict()の戻り値 :return: 未定
前処理判断 :pred bias: model.predict()の戻り値 :return: 未定
def preprocessing_judgement(pred, bias): """ 前処理判断 :pred bias: model.predict()の戻り値 :return: 未定 """ # 判断がtargetだったら if pred[0].argmax() == 0: result = bias_judgement(score=max(pred[0]), threshold=bias) else: result = 'not_target' return result
[ "def", "preprocessing_judgement", "(", "pred", ",", "bias", ")", ":", "# 判断がtargetだったら", "if", "pred", "[", "0", "]", ".", "argmax", "(", ")", "==", "0", ":", "result", "=", "bias_judgement", "(", "score", "=", "max", "(", "pred", "[", "0", "]", ")",...
[ 5, 0 ]
[ 17, 17 ]
python
en
['en', 'error', 'th']
False
SetEncoder._componentSortKey
(componentAndType)
Sort SET components by tag Sort regardless of the Choice value (static sort)
Sort SET components by tag
def _componentSortKey(componentAndType): """Sort SET components by tag Sort regardless of the Choice value (static sort) """ component, asn1Spec = componentAndType if asn1Spec is None: asn1Spec = component if asn1Spec.typeId == univ.Choice.typeId and not as...
[ "def", "_componentSortKey", "(", "componentAndType", ")", ":", "component", ",", "asn1Spec", "=", "componentAndType", "if", "asn1Spec", "is", "None", ":", "asn1Spec", "=", "component", "if", "asn1Spec", ".", "typeId", "==", "univ", ".", "Choice", ".", "typeId"...
[ 144, 4 ]
[ 160, 34 ]
python
en
['en', 'en', 'en']
True