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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
BaseDatabaseWrapper.check_constraints | (self, table_names=None) |
Backends can override this method if they can apply constraint
checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an
IntegrityError if any invalid foreign key references are encountered.
|
Backends can override this method if they can apply constraint
checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an
IntegrityError if any invalid foreign key references are encountered.
| def check_constraints(self, table_names=None):
"""
Backends can override this method if they can apply constraint
checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an
IntegrityError if any invalid foreign key references are encountered.
"""
pass | [
"def",
"check_constraints",
"(",
"self",
",",
"table_names",
"=",
"None",
")",
":",
"pass"
] | [
479,
4
] | [
485,
12
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.is_usable | (self) |
Test if the database connection is usable.
This method may assume that self.connection is not None.
Actual implementations should take care not to raise exceptions
as that may prevent Django from recycling unusable connections.
|
Test if the database connection is usable. | def is_usable(self):
"""
Test if the database connection is usable.
This method may assume that self.connection is not None.
Actual implementations should take care not to raise exceptions
as that may prevent Django from recycling unusable connections.
"""
raise... | [
"def",
"is_usable",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"subclasses of BaseDatabaseWrapper may require an is_usable() method\"",
")"
] | [
489,
4
] | [
499,
82
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.close_if_unusable_or_obsolete | (self) |
Close the current connection if unrecoverable errors have occurred
or if it outlived its maximum age.
|
Close the current connection if unrecoverable errors have occurred
or if it outlived its maximum age.
| def close_if_unusable_or_obsolete(self):
"""
Close the current connection if unrecoverable errors have occurred
or if it outlived its maximum age.
"""
if self.connection is not None:
# If the application didn't restore the original autocommit setting,
# do... | [
"def",
"close_if_unusable_or_obsolete",
"(",
"self",
")",
":",
"if",
"self",
".",
"connection",
"is",
"not",
"None",
":",
"# If the application didn't restore the original autocommit setting,",
"# don't take chances, drop the connection.",
"if",
"self",
".",
"get_autocommit",
... | [
501,
4
] | [
524,
22
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.validate_thread_sharing | (self) |
Validate that the connection isn't accessed by another thread than the
one which originally created it, unless the connection was explicitly
authorized to be shared between threads (via the `inc_thread_sharing()`
method). Raise an exception if the validation fails.
|
Validate that the connection isn't accessed by another thread than the
one which originally created it, unless the connection was explicitly
authorized to be shared between threads (via the `inc_thread_sharing()`
method). Raise an exception if the validation fails.
| def validate_thread_sharing(self):
"""
Validate that the connection isn't accessed by another thread than the
one which originally created it, unless the connection was explicitly
authorized to be shared between threads (via the `inc_thread_sharing()`
method). Raise an exception ... | [
"def",
"validate_thread_sharing",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"allow_thread_sharing",
"or",
"self",
".",
"_thread_ident",
"==",
"_thread",
".",
"get_ident",
"(",
")",
")",
":",
"raise",
"DatabaseError",
"(",
"\"DatabaseWrapper objects c... | [
543,
4
] | [
557,
13
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.prepare_database | (self) |
Hook to do any database check or preparation, generally called before
migrating a project or an app.
|
Hook to do any database check or preparation, generally called before
migrating a project or an app.
| def prepare_database(self):
"""
Hook to do any database check or preparation, generally called before
migrating a project or an app.
"""
pass | [
"def",
"prepare_database",
"(",
"self",
")",
":",
"pass"
] | [
561,
4
] | [
566,
12
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.wrap_database_errors | (self) |
Context manager and decorator that re-throws backend-specific database
exceptions using Django's common wrappers.
|
Context manager and decorator that re-throws backend-specific database
exceptions using Django's common wrappers.
| def wrap_database_errors(self):
"""
Context manager and decorator that re-throws backend-specific database
exceptions using Django's common wrappers.
"""
return DatabaseErrorWrapper(self) | [
"def",
"wrap_database_errors",
"(",
"self",
")",
":",
"return",
"DatabaseErrorWrapper",
"(",
"self",
")"
] | [
569,
4
] | [
574,
41
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.chunked_cursor | (self) |
Return a cursor that tries to avoid caching in the database (if
supported by the database), otherwise return a regular cursor.
|
Return a cursor that tries to avoid caching in the database (if
supported by the database), otherwise return a regular cursor.
| def chunked_cursor(self):
"""
Return a cursor that tries to avoid caching in the database (if
supported by the database), otherwise return a regular cursor.
"""
return self.cursor() | [
"def",
"chunked_cursor",
"(",
"self",
")",
":",
"return",
"self",
".",
"cursor",
"(",
")"
] | [
576,
4
] | [
581,
28
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.make_debug_cursor | (self, cursor) | Create a cursor that logs all queries in self.queries_log. | Create a cursor that logs all queries in self.queries_log. | def make_debug_cursor(self, cursor):
"""Create a cursor that logs all queries in self.queries_log."""
return utils.CursorDebugWrapper(cursor, self) | [
"def",
"make_debug_cursor",
"(",
"self",
",",
"cursor",
")",
":",
"return",
"utils",
".",
"CursorDebugWrapper",
"(",
"cursor",
",",
"self",
")"
] | [
583,
4
] | [
585,
53
] | python | en | ['en', 'gd', 'en'] | True |
BaseDatabaseWrapper.make_cursor | (self, cursor) | Create a cursor without debug logging. | Create a cursor without debug logging. | def make_cursor(self, cursor):
"""Create a cursor without debug logging."""
return utils.CursorWrapper(cursor, self) | [
"def",
"make_cursor",
"(",
"self",
",",
"cursor",
")",
":",
"return",
"utils",
".",
"CursorWrapper",
"(",
"cursor",
",",
"self",
")"
] | [
587,
4
] | [
589,
48
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.temporary_connection | (self) |
Context manager that ensures that a connection is established, and
if it opened one, closes it to avoid leaving a dangling connection.
This is useful for operations outside of the request-response cycle.
Provide a cursor: with self.temporary_connection() as cursor: ...
|
Context manager that ensures that a connection is established, and
if it opened one, closes it to avoid leaving a dangling connection.
This is useful for operations outside of the request-response cycle. | def temporary_connection(self):
"""
Context manager that ensures that a connection is established, and
if it opened one, closes it to avoid leaving a dangling connection.
This is useful for operations outside of the request-response cycle.
Provide a cursor: with self.temporary_c... | [
"def",
"temporary_connection",
"(",
"self",
")",
":",
"must_close",
"=",
"self",
".",
"connection",
"is",
"None",
"try",
":",
"with",
"self",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"yield",
"cursor",
"finally",
":",
"if",
"must_close",
":",
"self"... | [
592,
4
] | [
606,
28
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper._nodb_cursor | (self) |
Return a cursor from an alternative connection to be used when there is
no need to access the main database, specifically for test db
creation/deletion. This also prevents the production database from
being exposed to potential child threads while (or after) the test
database is... |
Return a cursor from an alternative connection to be used when there is
no need to access the main database, specifically for test db
creation/deletion. This also prevents the production database from
being exposed to potential child threads while (or after) the test
database is... | def _nodb_cursor(self):
"""
Return a cursor from an alternative connection to be used when there is
no need to access the main database, specifically for test db
creation/deletion. This also prevents the production database from
being exposed to potential child threads while (or ... | [
"def",
"_nodb_cursor",
"(",
"self",
")",
":",
"conn",
"=",
"self",
".",
"__class__",
"(",
"{",
"*",
"*",
"self",
".",
"settings_dict",
",",
"'NAME'",
":",
"None",
"}",
",",
"alias",
"=",
"NO_DB_ALIAS",
")",
"try",
":",
"with",
"conn",
".",
"cursor",
... | [
609,
4
] | [
622,
24
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.schema_editor | (self, *args, **kwargs) |
Return a new instance of this backend's SchemaEditor.
|
Return a new instance of this backend's SchemaEditor.
| def schema_editor(self, *args, **kwargs):
"""
Return a new instance of this backend's SchemaEditor.
"""
if self.SchemaEditorClass is None:
raise NotImplementedError(
'The SchemaEditorClass attribute of this database wrapper is still None')
return self.... | [
"def",
"schema_editor",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"SchemaEditorClass",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'The SchemaEditorClass attribute of this database wrapper is still None'",
")",
... | [
624,
4
] | [
631,
60
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.execute_wrapper | (self, wrapper) |
Return a context manager under which the wrapper is applied to suitable
database query executions.
|
Return a context manager under which the wrapper is applied to suitable
database query executions.
| def execute_wrapper(self, wrapper):
"""
Return a context manager under which the wrapper is applied to suitable
database query executions.
"""
self.execute_wrappers.append(wrapper)
try:
yield
finally:
self.execute_wrappers.pop() | [
"def",
"execute_wrapper",
"(",
"self",
",",
"wrapper",
")",
":",
"self",
".",
"execute_wrappers",
".",
"append",
"(",
"wrapper",
")",
"try",
":",
"yield",
"finally",
":",
"self",
".",
"execute_wrappers",
".",
"pop",
"(",
")"
] | [
655,
4
] | [
664,
39
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.copy | (self, alias=None) |
Return a copy of this connection.
For tests that require two connections to the same database.
|
Return a copy of this connection. | def copy(self, alias=None):
"""
Return a copy of this connection.
For tests that require two connections to the same database.
"""
settings_dict = copy.deepcopy(self.settings_dict)
if alias is None:
alias = self.alias
return type(self)(settings_dict, ... | [
"def",
"copy",
"(",
"self",
",",
"alias",
"=",
"None",
")",
":",
"settings_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"settings_dict",
")",
"if",
"alias",
"is",
"None",
":",
"alias",
"=",
"self",
".",
"alias",
"return",
"type",
"(",
"self... | [
666,
4
] | [
675,
47
] | python | en | ['en', 'error', 'th'] | False |
Bazaar.is_commit_id_equal | (cls, dest, name) | Always assume the versions don't match | Always assume the versions don't match | def is_commit_id_equal(cls, dest, name):
# type: (str, Optional[str]) -> bool
"""Always assume the versions don't match"""
return False | [
"def",
"is_commit_id_equal",
"(",
"cls",
",",
"dest",
",",
"name",
")",
":",
"# type: (str, Optional[str]) -> bool",
"return",
"False"
] | [
89,
4
] | [
92,
20
] | python | en | ['en', 'en', 'en'] | True |
pkg_resources_distribution_for_wheel | (wheel_zip, name, location) | Get a pkg_resources distribution given a wheel.
:raises UnsupportedWheel: on any errors
| Get a pkg_resources distribution given a wheel. | def pkg_resources_distribution_for_wheel(wheel_zip, name, location):
# type: (ZipFile, str, str) -> Distribution
"""Get a pkg_resources distribution given a wheel.
:raises UnsupportedWheel: on any errors
"""
info_dir, _ = parse_wheel(wheel_zip, name)
metadata_files = [p for p in wheel_zip.name... | [
"def",
"pkg_resources_distribution_for_wheel",
"(",
"wheel_zip",
",",
"name",
",",
"location",
")",
":",
"# type: (ZipFile, str, str) -> Distribution",
"info_dir",
",",
"_",
"=",
"parse_wheel",
"(",
"wheel_zip",
",",
"name",
")",
"metadata_files",
"=",
"[",
"p",
"fo... | [
42,
0
] | [
63,
88
] | python | en | ['en', 'en', 'en'] | True |
parse_wheel | (wheel_zip, name) | Extract information from the provided wheel, ensuring it meets basic
standards.
Returns the name of the .dist-info directory and the parsed WHEEL metadata.
| Extract information from the provided wheel, ensuring it meets basic
standards. | def parse_wheel(wheel_zip, name):
# type: (ZipFile, str) -> Tuple[str, Message]
"""Extract information from the provided wheel, ensuring it meets basic
standards.
Returns the name of the .dist-info directory and the parsed WHEEL metadata.
"""
try:
info_dir = wheel_dist_info_dir(wheel_zi... | [
"def",
"parse_wheel",
"(",
"wheel_zip",
",",
"name",
")",
":",
"# type: (ZipFile, str) -> Tuple[str, Message]",
"try",
":",
"info_dir",
"=",
"wheel_dist_info_dir",
"(",
"wheel_zip",
",",
"name",
")",
"metadata",
"=",
"wheel_metadata",
"(",
"wheel_zip",
",",
"info_di... | [
66,
0
] | [
82,
29
] | python | en | ['en', 'en', 'en'] | True |
wheel_dist_info_dir | (source, name) | Returns the name of the contained .dist-info directory.
Raises AssertionError or UnsupportedWheel if not found, >1 found, or
it doesn't match the provided name.
| Returns the name of the contained .dist-info directory. | def wheel_dist_info_dir(source, name):
# type: (ZipFile, str) -> str
"""Returns the name of the contained .dist-info directory.
Raises AssertionError or UnsupportedWheel if not found, >1 found, or
it doesn't match the provided name.
"""
# Zip file path separators must be /
subdirs = {p.spli... | [
"def",
"wheel_dist_info_dir",
"(",
"source",
",",
"name",
")",
":",
"# type: (ZipFile, str) -> str",
"# Zip file path separators must be /",
"subdirs",
"=",
"{",
"p",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"[",
"0",
"]",
"for",
"p",
"in",
"source",
".",
... | [
85,
0
] | [
116,
19
] | python | en | ['en', 'en', 'en'] | True |
wheel_metadata | (source, dist_info_dir) | Return the WHEEL metadata of an extracted wheel, if possible.
Otherwise, raise UnsupportedWheel.
| Return the WHEEL metadata of an extracted wheel, if possible.
Otherwise, raise UnsupportedWheel.
| def wheel_metadata(source, dist_info_dir):
# type: (ZipFile, str) -> Message
"""Return the WHEEL metadata of an extracted wheel, if possible.
Otherwise, raise UnsupportedWheel.
"""
path = f"{dist_info_dir}/WHEEL"
# Zip file path separators must be /
wheel_contents = read_wheel_metadata_file(... | [
"def",
"wheel_metadata",
"(",
"source",
",",
"dist_info_dir",
")",
":",
"# type: (ZipFile, str) -> Message",
"path",
"=",
"f\"{dist_info_dir}/WHEEL\"",
"# Zip file path separators must be /",
"wheel_contents",
"=",
"read_wheel_metadata_file",
"(",
"source",
",",
"path",
")",
... | [
129,
0
] | [
146,
40
] | python | en | ['en', 'en', 'en'] | True |
wheel_version | (wheel_data) | Given WHEEL metadata, return the parsed Wheel-Version.
Otherwise, raise UnsupportedWheel.
| Given WHEEL metadata, return the parsed Wheel-Version.
Otherwise, raise UnsupportedWheel.
| def wheel_version(wheel_data):
# type: (Message) -> Tuple[int, ...]
"""Given WHEEL metadata, return the parsed Wheel-Version.
Otherwise, raise UnsupportedWheel.
"""
version_text = wheel_data["Wheel-Version"]
if version_text is None:
raise UnsupportedWheel("WHEEL is missing Wheel-Version"... | [
"def",
"wheel_version",
"(",
"wheel_data",
")",
":",
"# type: (Message) -> Tuple[int, ...]",
"version_text",
"=",
"wheel_data",
"[",
"\"Wheel-Version\"",
"]",
"if",
"version_text",
"is",
"None",
":",
"raise",
"UnsupportedWheel",
"(",
"\"WHEEL is missing Wheel-Version\"",
... | [
149,
0
] | [
163,
69
] | python | en | ['en', 'de', 'en'] | True |
check_compatibility | (version, name) | Raises errors or warns if called with an incompatible Wheel-Version.
pip should refuse to install a Wheel-Version that's a major series
ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when
installing a version only minor version ahead (e.g 1.2 > 1.1).
version: a 2-tuple representing a Whe... | Raises errors or warns if called with an incompatible Wheel-Version. | def check_compatibility(version, name):
# type: (Tuple[int, ...], str) -> None
"""Raises errors or warns if called with an incompatible Wheel-Version.
pip should refuse to install a Wheel-Version that's a major series
ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when
installing a ve... | [
"def",
"check_compatibility",
"(",
"version",
",",
"name",
")",
":",
"# type: (Tuple[int, ...], str) -> None",
"if",
"version",
"[",
"0",
"]",
">",
"VERSION_COMPATIBLE",
"[",
"0",
"]",
":",
"raise",
"UnsupportedWheel",
"(",
"\"{}'s Wheel-Version ({}) is not compatible w... | [
166,
0
] | [
188,
9
] | python | en | ['en', 'en', 'en'] | True |
create_model | (
image_size,
labels,
model_type=XModelType.CENTERNET,
backbone=XModelBackbone.EFFICIENTNETB0,
mode=XModelMode.CONCAT,
pretrained_backbone=True,
) |
Creates a new TensorFlow model.
:param image_size: image height and width
:param labels: number of labels
:param backbone: backbone to be used for creating a new model (pre-trained if available)
:return: new model (XCenternetModel)
|
Creates a new TensorFlow model. | def create_model(
image_size,
labels,
model_type=XModelType.CENTERNET,
backbone=XModelBackbone.EFFICIENTNETB0,
mode=XModelMode.CONCAT,
pretrained_backbone=True,
):
"""
Creates a new TensorFlow model.
:param image_size: image height and width
:param labels: number of labels
:... | [
"def",
"create_model",
"(",
"image_size",
",",
"labels",
",",
"model_type",
"=",
"XModelType",
".",
"CENTERNET",
",",
"backbone",
"=",
"XModelBackbone",
".",
"EFFICIENTNETB0",
",",
"mode",
"=",
"XModelMode",
".",
"CONCAT",
",",
"pretrained_backbone",
"=",
"True"... | [
17,
0
] | [
34,
61
] | python | en | ['en', 'error', 'th'] | False |
load_and_update_model | (model_dir: str, labels: int, model_type: XModelType, feature_layer="features") |
Loads model from given directory and update it to the new number of labels.
:param model_dir: directory with model in TensorFlow SavedModel format
:param labels: number of labels in the new model
:param model_type:
:return: loadel model (XCenternetModel)
|
Loads model from given directory and update it to the new number of labels. | def load_and_update_model(model_dir: str, labels: int, model_type: XModelType, feature_layer="features"):
"""
Loads model from given directory and update it to the new number of labels.
:param model_dir: directory with model in TensorFlow SavedModel format
:param labels: number of labels in the new mod... | [
"def",
"load_and_update_model",
"(",
"model_dir",
":",
"str",
",",
"labels",
":",
"int",
",",
"model_type",
":",
"XModelType",
",",
"feature_layer",
"=",
"\"features\"",
")",
":",
"input",
",",
"features",
"=",
"_load_backbone",
"(",
"model_dir",
",",
"feature... | [
37,
0
] | [
47,
61
] | python | en | ['en', 'error', 'th'] | False |
load_pretrained_weights | (model, weights_path, reset_heads=True) |
Loads pretrained weights for given model by name. By default, the heads are reset to default values.
The heads in a new model might have a same shape as in the pretrained one. But we should not keep them
and instead train the from scratch.
:param model: Non-trained model.
:param weights_path: Path... |
Loads pretrained weights for given model by name. By default, the heads are reset to default values.
The heads in a new model might have a same shape as in the pretrained one. But we should not keep them
and instead train the from scratch. | def load_pretrained_weights(model, weights_path, reset_heads=True):
"""
Loads pretrained weights for given model by name. By default, the heads are reset to default values.
The heads in a new model might have a same shape as in the pretrained one. But we should not keep them
and instead train the from s... | [
"def",
"load_pretrained_weights",
"(",
"model",
",",
"weights_path",
",",
"reset_heads",
"=",
"True",
")",
":",
"def",
"load",
"(",
")",
":",
"model",
".",
"load_weights",
"(",
"weights_path",
",",
"by_name",
"=",
"True",
",",
"skip_mismatch",
"=",
"True",
... | [
50,
0
] | [
79,
50
] | python | en | ['en', 'error', 'th'] | False |
tokenize | (sql, encoding=None) | Tokenize sql.
Tokenize *sql* using the :class:`Lexer` and return a 2-tuple stream
of ``(token type, value)`` items.
| Tokenize sql. | def tokenize(sql, encoding=None):
"""Tokenize sql.
Tokenize *sql* using the :class:`Lexer` and return a 2-tuple stream
of ``(token type, value)`` items.
"""
return Lexer().get_tokens(sql, encoding) | [
"def",
"tokenize",
"(",
"sql",
",",
"encoding",
"=",
"None",
")",
":",
"return",
"Lexer",
"(",
")",
".",
"get_tokens",
"(",
"sql",
",",
"encoding",
")"
] | [
75,
0
] | [
81,
44
] | python | nl | ['nl', 'sl', 'tr'] | False |
Lexer.get_tokens | (text, encoding=None) |
Return an iterable of (tokentype, value) pairs generated from
`text`. If `unfiltered` is set to `True`, the filtering mechanism
is bypassed even if filters are defined.
Also preprocess the text, i.e. expand tabs and strip it if
wanted and applies registered filters.
Sp... |
Return an iterable of (tokentype, value) pairs generated from
`text`. If `unfiltered` is set to `True`, the filtering mechanism
is bypassed even if filters are defined. | def get_tokens(text, encoding=None):
"""
Return an iterable of (tokentype, value) pairs generated from
`text`. If `unfiltered` is set to `True`, the filtering mechanism
is bypassed even if filters are defined.
Also preprocess the text, i.e. expand tabs and strip it if
wa... | [
"def",
"get_tokens",
"(",
"text",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"TextIOBase",
")",
":",
"text",
"=",
"text",
".",
"read",
"(",
")",
"if",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"pass",
"elif... | [
27,
4
] | [
72,
40
] | python | en | ['en', 'error', 'th'] | False |
popen_wrapper | (args, stdout_encoding='utf-8') |
Friendly wrapper around Popen.
Return stdout output, stderr output, and OS status code.
|
Friendly wrapper around Popen. | def popen_wrapper(args, stdout_encoding='utf-8'):
"""
Friendly wrapper around Popen.
Return stdout output, stderr output, and OS status code.
"""
try:
p = run(args, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt')
except OSError as err:
raise CommandError('Error executing %s... | [
"def",
"popen_wrapper",
"(",
"args",
",",
"stdout_encoding",
"=",
"'utf-8'",
")",
":",
"try",
":",
"p",
"=",
"run",
"(",
"args",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"close_fds",
"=",
"os",
".",
"name",
"!=",
"'nt'",
")",
"e... | [
12,
0
] | [
26,
5
] | python | en | ['en', 'error', 'th'] | False |
handle_extensions | (extensions) |
Organize multiple extensions that are separated with commas or passed by
using --extension/-e multiple times.
For example: running 'django-admin makemessages -e js,txt -e xhtml -a'
would result in an extension list: ['.js', '.txt', '.xhtml']
>>> handle_extensions(['.html', 'html,js,py,py,py,.py',... |
Organize multiple extensions that are separated with commas or passed by
using --extension/-e multiple times. | def handle_extensions(extensions):
"""
Organize multiple extensions that are separated with commas or passed by
using --extension/-e multiple times.
For example: running 'django-admin makemessages -e js,txt -e xhtml -a'
would result in an extension list: ['.js', '.txt', '.xhtml']
>>> handle_ex... | [
"def",
"handle_extensions",
"(",
"extensions",
")",
":",
"ext_list",
"=",
"[",
"]",
"for",
"ext",
"in",
"extensions",
":",
"ext_list",
".",
"extend",
"(",
"ext",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
")",
"for",
... | [
29,
0
] | [
48,
24
] | python | en | ['en', 'error', 'th'] | False |
get_random_secret_key | () |
Return a 50 character random string usable as a SECRET_KEY setting value.
|
Return a 50 character random string usable as a SECRET_KEY setting value.
| def get_random_secret_key():
"""
Return a 50 character random string usable as a SECRET_KEY setting value.
"""
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
return get_random_string(50, chars) | [
"def",
"get_random_secret_key",
"(",
")",
":",
"chars",
"=",
"'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'",
"return",
"get_random_string",
"(",
"50",
",",
"chars",
")"
] | [
76,
0
] | [
81,
39
] | python | en | ['en', 'error', 'th'] | False |
parse_apps_and_model_labels | (labels) |
Parse a list of "app_label.ModelName" or "app_label" strings into actual
objects and return a two-element tuple:
(set of model classes, set of app_configs).
Raise a CommandError if some specified models or apps don't exist.
|
Parse a list of "app_label.ModelName" or "app_label" strings into actual
objects and return a two-element tuple:
(set of model classes, set of app_configs).
Raise a CommandError if some specified models or apps don't exist.
| def parse_apps_and_model_labels(labels):
"""
Parse a list of "app_label.ModelName" or "app_label" strings into actual
objects and return a two-element tuple:
(set of model classes, set of app_configs).
Raise a CommandError if some specified models or apps don't exist.
"""
apps = set()
... | [
"def",
"parse_apps_and_model_labels",
"(",
"labels",
")",
":",
"apps",
"=",
"set",
"(",
")",
"models",
"=",
"set",
"(",
")",
"for",
"label",
"in",
"labels",
":",
"if",
"'.'",
"in",
"label",
":",
"try",
":",
"model",
"=",
"installed_apps",
".",
"get_mod... | [
84,
0
] | [
108,
23
] | python | en | ['en', 'error', 'th'] | False |
get_command_line_option | (argv, option) |
Return the value of a command line option (which should include leading
dashes, e.g. '--testrunner') from an argument list. Return None if the
option wasn't passed or if the argument list couldn't be parsed.
|
Return the value of a command line option (which should include leading
dashes, e.g. '--testrunner') from an argument list. Return None if the
option wasn't passed or if the argument list couldn't be parsed.
| def get_command_line_option(argv, option):
"""
Return the value of a command line option (which should include leading
dashes, e.g. '--testrunner') from an argument list. Return None if the
option wasn't passed or if the argument list couldn't be parsed.
"""
parser = CommandParser(add_help=False... | [
"def",
"get_command_line_option",
"(",
"argv",
",",
"option",
")",
":",
"parser",
"=",
"CommandParser",
"(",
"add_help",
"=",
"False",
",",
"allow_abbrev",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"option",
",",
"dest",
"=",
"'value'",
")",
"... | [
111,
0
] | [
124,
28
] | python | en | ['en', 'error', 'th'] | False |
normalize_path_patterns | (patterns) | Normalize an iterable of glob style patterns based on OS. | Normalize an iterable of glob style patterns based on OS. | def normalize_path_patterns(patterns):
"""Normalize an iterable of glob style patterns based on OS."""
patterns = [os.path.normcase(p) for p in patterns]
dir_suffixes = {'%s*' % path_sep for path_sep in {'/', os.sep}}
norm_patterns = []
for pattern in patterns:
for dir_suffix in dir_suffixes... | [
"def",
"normalize_path_patterns",
"(",
"patterns",
")",
":",
"patterns",
"=",
"[",
"os",
".",
"path",
".",
"normcase",
"(",
"p",
")",
"for",
"p",
"in",
"patterns",
"]",
"dir_suffixes",
"=",
"{",
"'%s*'",
"%",
"path_sep",
"for",
"path_sep",
"in",
"{",
"... | [
127,
0
] | [
139,
24
] | python | en | ['en', 'en', 'en'] | True |
is_ignored_path | (path, ignore_patterns) |
Check if the given path should be ignored or not based on matching
one of the glob style `ignore_patterns`.
|
Check if the given path should be ignored or not based on matching
one of the glob style `ignore_patterns`.
| def is_ignored_path(path, ignore_patterns):
"""
Check if the given path should be ignored or not based on matching
one of the glob style `ignore_patterns`.
"""
path = Path(path)
def ignore(pattern):
return fnmatch.fnmatchcase(path.name, pattern) or fnmatch.fnmatchcase(str(path), pattern... | [
"def",
"is_ignored_path",
"(",
"path",
",",
"ignore_patterns",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"def",
"ignore",
"(",
"pattern",
")",
":",
"return",
"fnmatch",
".",
"fnmatchcase",
"(",
"path",
".",
"name",
",",
"pattern",
")",
"or",
"fn... | [
142,
0
] | [
152,
87
] | python | en | ['en', 'error', 'th'] | False |
_save | (im, fp, tile, bufsize=0) | Helper to save image based on tile list
:param im: Image object.
:param fp: File object.
:param tile: Tile list.
:param bufsize: Optional buffer size
| Helper to save image based on tile list | def _save(im, fp, tile, bufsize=0):
"""Helper to save image based on tile list
:param im: Image object.
:param fp: File object.
:param tile: Tile list.
:param bufsize: Optional buffer size
"""
im.load()
if not hasattr(im, "encoderconfig"):
im.encoderconfig = ()
tile.sort(ke... | [
"def",
"_save",
"(",
"im",
",",
"fp",
",",
"tile",
",",
"bufsize",
"=",
"0",
")",
":",
"im",
".",
"load",
"(",
")",
"if",
"not",
"hasattr",
"(",
"im",
",",
"\"encoderconfig\"",
")",
":",
"im",
".",
"encoderconfig",
"=",
"(",
")",
"tile",
".",
"... | [
477,
0
] | [
540,
18
] | python | en | ['en', 'da', 'en'] | True |
_safe_read | (fp, size) |
Reads large blocks in a safe way. Unlike fp.read(n), this function
doesn't trust the user. If the requested size is larger than
SAFEBLOCK, the file is read block by block.
:param fp: File handle. Must implement a <b>read</b> method.
:param size: Number of bytes to read.
:returns: A string c... |
Reads large blocks in a safe way. Unlike fp.read(n), this function
doesn't trust the user. If the requested size is larger than
SAFEBLOCK, the file is read block by block. | def _safe_read(fp, size):
"""
Reads large blocks in a safe way. Unlike fp.read(n), this function
doesn't trust the user. If the requested size is larger than
SAFEBLOCK, the file is read block by block.
:param fp: File handle. Must implement a <b>read</b> method.
:param size: Number of bytes ... | [
"def",
"_safe_read",
"(",
"fp",
",",
"size",
")",
":",
"if",
"size",
"<=",
"0",
":",
"return",
"b\"\"",
"if",
"size",
"<=",
"SAFEBLOCK",
":",
"data",
"=",
"fp",
".",
"read",
"(",
"size",
")",
"if",
"len",
"(",
"data",
")",
"<",
"size",
":",
"ra... | [
543,
0
] | [
572,
25
] | python | en | ['en', 'error', 'th'] | False |
ImageFile.__init__ | (self, fp=None, filename=None) | A list of tile descriptors, or ``None`` | A list of tile descriptors, or ``None`` | def __init__(self, fp=None, filename=None):
super().__init__()
self._min_frame = 0
self.custom_mimetype = None
self.tile = None
""" A list of tile descriptors, or ``None`` """
self.readonly = 1 # until we know better
self.decoderconfig = ()
self.deco... | [
"def",
"__init__",
"(",
"self",
",",
"fp",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_min_frame",
"=",
"0",
"self",
".",
"custom_mimetype",
"=",
"None",
"self",
".",
"tile",
"="... | [
91,
4
] | [
136,
17
] | python | en | ['en', 'fr', 'en'] | True |
ImageFile.verify | (self) | Check file integrity | Check file integrity | def verify(self):
"""Check file integrity"""
# raise exception if something's wrong. must be called
# directly after open, and closes file when finished.
if self._exclusive_fp:
self.fp.close()
self.fp = None | [
"def",
"verify",
"(",
"self",
")",
":",
"# raise exception if something's wrong. must be called",
"# directly after open, and closes file when finished.",
"if",
"self",
".",
"_exclusive_fp",
":",
"self",
".",
"fp",
".",
"close",
"(",
")",
"self",
".",
"fp",
"=",
"Non... | [
144,
4
] | [
151,
22
] | python | en | ['en', 'en', 'en'] | True |
ImageFile.load | (self) | Load image data based on tile list | Load image data based on tile list | def load(self):
"""Load image data based on tile list"""
if self.tile is None:
raise OSError("cannot load this image")
pixel = Image.Image.load(self)
if not self.tile:
return pixel
self.map = None
use_mmap = self.filename and len(self.tile) == 1... | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"self",
".",
"tile",
"is",
"None",
":",
"raise",
"OSError",
"(",
"\"cannot load this image\"",
")",
"pixel",
"=",
"Image",
".",
"Image",
".",
"load",
"(",
"self",
")",
"if",
"not",
"self",
".",
"tile",
":",... | [
153,
4
] | [
275,
37
] | python | en | ['en', 'da', 'en'] | True |
StubImageFile._load | (self) | (Hook) Find actual image loader. | (Hook) Find actual image loader. | def _load(self):
"""(Hook) Find actual image loader."""
raise NotImplementedError("StubImageFile subclass must implement _load") | [
"def",
"_load",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"StubImageFile subclass must implement _load\"",
")"
] | [
333,
4
] | [
335,
80
] | python | en | ['en', 'da', 'en'] | True |
Parser.reset | (self) |
(Consumer) Reset the parser. Note that you can only call this
method immediately after you've created a parser; parser
instances cannot be reused.
|
(Consumer) Reset the parser. Note that you can only call this
method immediately after you've created a parser; parser
instances cannot be reused.
| def reset(self):
"""
(Consumer) Reset the parser. Note that you can only call this
method immediately after you've created a parser; parser
instances cannot be reused.
"""
assert self.data is None, "cannot reuse parsers" | [
"def",
"reset",
"(",
"self",
")",
":",
"assert",
"self",
".",
"data",
"is",
"None",
",",
"\"cannot reuse parsers\""
] | [
351,
4
] | [
357,
56
] | python | en | ['en', 'error', 'th'] | False |
Parser.feed | (self, data) |
(Consumer) Feed data to the parser.
:param data: A string buffer.
:exception OSError: If the parser failed to parse the image file.
|
(Consumer) Feed data to the parser. | def feed(self, data):
"""
(Consumer) Feed data to the parser.
:param data: A string buffer.
:exception OSError: If the parser failed to parse the image file.
"""
# collect data
if self.finished:
return
if self.data is None:
self.... | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"# collect data",
"if",
"self",
".",
"finished",
":",
"return",
"if",
"self",
".",
"data",
"is",
"None",
":",
"self",
".",
"data",
"=",
"data",
"else",
":",
"self",
".",
"data",
"=",
"self",
".",
... | [
359,
4
] | [
437,
31
] | python | en | ['en', 'error', 'th'] | False |
Parser.close | (self) |
(Consumer) Close the stream.
:returns: An image object.
:exception OSError: If the parser failed to parse the image file either
because it cannot be identified or cannot be
decoded.
|
(Consumer) Close the stream. | def close(self):
"""
(Consumer) Close the stream.
:returns: An image object.
:exception OSError: If the parser failed to parse the image file either
because it cannot be identified or cannot be
decoded.
"""
# finish... | [
"def",
"close",
"(",
"self",
")",
":",
"# finish decoding",
"if",
"self",
".",
"decoder",
":",
"# get rid of what's left in the buffers",
"self",
".",
"feed",
"(",
"b\"\"",
")",
"self",
".",
"data",
"=",
"self",
".",
"decoder",
"=",
"None",
"if",
"not",
"s... | [
445,
4
] | [
471,
25
] | python | en | ['en', 'error', 'th'] | False |
PyDecoder.init | (self, args) |
Override to perform decoder specific initialization
:param args: Array of args items from the tile entry
:returns: None
|
Override to perform decoder specific initialization | def init(self, args):
"""
Override to perform decoder specific initialization
:param args: Array of args items from the tile entry
:returns: None
"""
self.args = args | [
"def",
"init",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"args",
"=",
"args"
] | [
603,
4
] | [
610,
24
] | python | en | ['en', 'error', 'th'] | False |
PyDecoder.decode | (self, buffer) |
Override to perform the decoding process.
:param buffer: A bytes object with the data to be decoded.
:returns: A tuple of ``(bytes consumed, errcode)``.
If finished with decoding return <0 for the bytes consumed.
Err codes are from :data:`.ImageFile.ERRORS`.
|
Override to perform the decoding process. | def decode(self, buffer):
"""
Override to perform the decoding process.
:param buffer: A bytes object with the data to be decoded.
:returns: A tuple of ``(bytes consumed, errcode)``.
If finished with decoding return <0 for the bytes consumed.
Err codes are from :... | [
"def",
"decode",
"(",
"self",
",",
"buffer",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
616,
4
] | [
625,
35
] | python | en | ['en', 'error', 'th'] | False |
PyDecoder.cleanup | (self) |
Override to perform decoder specific cleanup
:returns: None
|
Override to perform decoder specific cleanup | def cleanup(self):
"""
Override to perform decoder specific cleanup
:returns: None
"""
pass | [
"def",
"cleanup",
"(",
"self",
")",
":",
"pass"
] | [
627,
4
] | [
633,
12
] | python | en | ['en', 'error', 'th'] | False |
PyDecoder.setfd | (self, fd) |
Called from ImageFile to set the python file-like object
:param fd: A python file-like object
:returns: None
|
Called from ImageFile to set the python file-like object | def setfd(self, fd):
"""
Called from ImageFile to set the python file-like object
:param fd: A python file-like object
:returns: None
"""
self.fd = fd | [
"def",
"setfd",
"(",
"self",
",",
"fd",
")",
":",
"self",
".",
"fd",
"=",
"fd"
] | [
635,
4
] | [
642,
20
] | python | en | ['en', 'error', 'th'] | False |
PyDecoder.setimage | (self, im, extents=None) |
Called from ImageFile to set the core output image for the decoder
:param im: A core image object
:param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
for this tile
:returns: None
|
Called from ImageFile to set the core output image for the decoder | def setimage(self, im, extents=None):
"""
Called from ImageFile to set the core output image for the decoder
:param im: A core image object
:param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
for this tile
:returns: None
"""
# follow... | [
"def",
"setimage",
"(",
"self",
",",
"im",
",",
"extents",
"=",
"None",
")",
":",
"# following c code",
"self",
".",
"im",
"=",
"im",
"if",
"extents",
":",
"(",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
")",
"=",
"extents",
"else",
":",
"(",
"x0",
... | [
644,
4
] | [
677,
64
] | python | en | ['en', 'error', 'th'] | False |
PyDecoder.set_as_raw | (self, data, rawmode=None) |
Convenience method to set the internal image from a stream of raw data
:param data: Bytes to be set
:param rawmode: The rawmode to be used for the decoder.
If not specified, it will default to the mode of the image
:returns: None
|
Convenience method to set the internal image from a stream of raw data | def set_as_raw(self, data, rawmode=None):
"""
Convenience method to set the internal image from a stream of raw data
:param data: Bytes to be set
:param rawmode: The rawmode to be used for the decoder.
If not specified, it will default to the mode of the image
:retur... | [
"def",
"set_as_raw",
"(",
"self",
",",
"data",
",",
"rawmode",
"=",
"None",
")",
":",
"if",
"not",
"rawmode",
":",
"rawmode",
"=",
"self",
".",
"mode",
"d",
"=",
"Image",
".",
"_getdecoder",
"(",
"self",
".",
"mode",
",",
"\"raw\"",
",",
"(",
"rawm... | [
679,
4
] | [
698,
56
] | python | en | ['en', 'error', 'th'] | False |
Cutout.__call__ | (self, img) | cutout_image | cutout_image | def __call__(self, img):
""" cutout_image """
h, w = img.shape[:2]
mask = np.ones((h, w), np.float32)
for n in range(self.n_holes):
y = np.random.randint(h)
x = np.random.randint(w)
y1 = np.clip(y - self.length // 2, 0, h)
y2 = np.clip(y ... | [
"def",
"__call__",
"(",
"self",
",",
"img",
")",
":",
"h",
",",
"w",
"=",
"img",
".",
"shape",
"[",
":",
"2",
"]",
"mask",
"=",
"np",
".",
"ones",
"(",
"(",
"h",
",",
"w",
")",
",",
"np",
".",
"float32",
")",
"for",
"n",
"in",
"range",
"(... | [
25,
4
] | [
40,
18
] | python | en | ['fr', 'ny', 'en'] | False |
get_user_agent | () |
Provides the `USER_AGENT` string that is passed to the Cloudinary servers.
Prepends `USER_PLATFORM` if it is defined.
:returns: the user agent
:rtype: str
|
Provides the `USER_AGENT` string that is passed to the Cloudinary servers.
Prepends `USER_PLATFORM` if it is defined. | def get_user_agent():
"""
Provides the `USER_AGENT` string that is passed to the Cloudinary servers.
Prepends `USER_PLATFORM` if it is defined.
:returns: the user agent
:rtype: str
"""
if USER_PLATFORM == "":
return USER_AGENT
else:
return USER_PLATFORM + " " + USER_AG... | [
"def",
"get_user_agent",
"(",
")",
":",
"if",
"USER_PLATFORM",
"==",
"\"\"",
":",
"return",
"USER_AGENT",
"else",
":",
"return",
"USER_PLATFORM",
"+",
"\" \"",
"+",
"USER_AGENT"
] | [
57,
0
] | [
69,
47
] | python | en | ['en', 'error', 'th'] | False |
_run | (args) | TODO(praneetdutta): Formalize train sub-routine
| TODO(praneetdutta): Formalize train sub-routine
| def _run(args):
""" TODO(praneetdutta): Formalize train sub-routine
"""
with tf.Session() as sess:
env = gym.make(args[0].environment)
env = StackFrameEnv(env, args[0].frame_stack,
args[0].img_height, args[0].img_width)
state = env.reset()
num_actions = env.action_space.n
if args[0].mode ... | [
"def",
"_run",
"(",
"args",
")",
":",
"with",
"tf",
".",
"Session",
"(",
")",
"as",
"sess",
":",
"env",
"=",
"gym",
".",
"make",
"(",
"args",
"[",
"0",
"]",
".",
"environment",
")",
"env",
"=",
"StackFrameEnv",
"(",
"env",
",",
"args",
"[",
"0"... | [
39,
0
] | [
127,
28
] | python | en | ['en', 'it', 'sw'] | False |
_parse_arguments | (argv) | Parse command-line arguments. | Parse command-line arguments. | def _parse_arguments(argv):
"""Parse command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--img_width',
help='Width of desired image observation',
type=float,
default=128)
parser.add_argument(
'--img_height',
help='Height of desired image obser... | [
"def",
"_parse_arguments",
"(",
"argv",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--img_width'",
",",
"help",
"=",
"'Width of desired image observation'",
",",
"type",
"=",
"float",
",",
"default"... | [
130,
0
] | [
215,
38
] | python | en | ['en', 'fr', 'en'] | True |
StaticFilesHandlerMixin._should_handle | (self, path) |
Check if the path should be handled. Ignore the path if:
* the host is provided as part of the base_url
* the request's path isn't under the media path (or equal)
|
Check if the path should be handled. Ignore the path if:
* the host is provided as part of the base_url
* the request's path isn't under the media path (or equal)
| def _should_handle(self, path):
"""
Check if the path should be handled. Ignore the path if:
* the host is provided as part of the base_url
* the request's path isn't under the media path (or equal)
"""
return path.startswith(self.base_url[2]) and not self.base_url[1] | [
"def",
"_should_handle",
"(",
"self",
",",
"path",
")",
":",
"return",
"path",
".",
"startswith",
"(",
"self",
".",
"base_url",
"[",
"2",
"]",
")",
"and",
"not",
"self",
".",
"base_url",
"[",
"1",
"]"
] | [
31,
4
] | [
37,
73
] | python | en | ['en', 'error', 'th'] | False |
StaticFilesHandlerMixin.file_path | (self, url) |
Return the relative path to the media file on disk for the given URL.
|
Return the relative path to the media file on disk for the given URL.
| def file_path(self, url):
"""
Return the relative path to the media file on disk for the given URL.
"""
relative_url = url[len(self.base_url[2]):]
return url2pathname(relative_url) | [
"def",
"file_path",
"(",
"self",
",",
"url",
")",
":",
"relative_url",
"=",
"url",
"[",
"len",
"(",
"self",
".",
"base_url",
"[",
"2",
"]",
")",
":",
"]",
"return",
"url2pathname",
"(",
"relative_url",
")"
] | [
39,
4
] | [
44,
41
] | python | en | ['en', 'error', 'th'] | False |
StaticFilesHandlerMixin.serve | (self, request) | Serve the request path. | Serve the request path. | def serve(self, request):
"""Serve the request path."""
return serve(request, self.file_path(request.path), insecure=True) | [
"def",
"serve",
"(",
"self",
",",
"request",
")",
":",
"return",
"serve",
"(",
"request",
",",
"self",
".",
"file_path",
"(",
"request",
".",
"path",
")",
",",
"insecure",
"=",
"True",
")"
] | [
46,
4
] | [
48,
74
] | python | en | ['en', 'en', 'en'] | True |
shquote | (arg) | Quote an argument for later parsing by shlex.split() | Quote an argument for later parsing by shlex.split() | def shquote(arg):
"""Quote an argument for later parsing by shlex.split()"""
for c in '"', "'", "\\", "#":
if c in arg:
return repr(arg)
if arg.split() != [arg]:
return repr(arg)
return arg | [
"def",
"shquote",
"(",
"arg",
")",
":",
"for",
"c",
"in",
"'\"'",
",",
"\"'\"",
",",
"\"\\\\\"",
",",
"\"#\"",
":",
"if",
"c",
"in",
"arg",
":",
"return",
"repr",
"(",
"arg",
")",
"if",
"arg",
".",
"split",
"(",
")",
"!=",
"[",
"arg",
"]",
":... | [
7,
0
] | [
14,
14
] | python | en | ['en', 'en', 'en'] | True |
SessionStore.flush | (self) |
Remove the current session data from the database and regenerate the
key.
|
Remove the current session data from the database and regenerate the
key.
| def flush(self):
"""
Remove the current session data from the database and regenerate the
key.
"""
self.clear()
self.delete(self.session_key)
self._session_key = None | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"delete",
"(",
"self",
".",
"session_key",
")",
"self",
".",
"_session_key",
"=",
"None"
] | [
57,
4
] | [
64,
32
] | python | en | ['en', 'error', 'th'] | False |
split_and_convert_string | (string_tensor) | Splits and converts string tensor into dense float tensor.
Given string tensor, splits string by delimiter, converts to and returns
dense float tensor.
Args:
string_tensor: tf.string tensor.
Returns:
tf.float64 tensor split along delimiter.
| Splits and converts string tensor into dense float tensor. | def split_and_convert_string(string_tensor):
"""Splits and converts string tensor into dense float tensor.
Given string tensor, splits string by delimiter, converts to and returns
dense float tensor.
Args:
string_tensor: tf.string tensor.
Returns:
tf.float64 tensor split along del... | [
"def",
"split_and_convert_string",
"(",
"string_tensor",
")",
":",
"# Split string tensor into a sparse tensor based on delimiter",
"split_string",
"=",
"tf",
".",
"string_split",
"(",
"source",
"=",
"tf",
".",
"expand_dims",
"(",
"input",
"=",
"string_tensor",
",",
"ax... | [
14,
0
] | [
48,
30
] | python | en | ['en', 'en', 'en'] | True |
convert_sequences_from_strings_to_floats | (features, column_list, seq_len) | Converts sequences from single strings to a sequence of floats.
Given features dictionary and feature column names list, convert features
from strings to a sequence of floats.
Args:
features: Dictionary of tensors of our features as tf.strings.
column_list: List of column names of our feat... | Converts sequences from single strings to a sequence of floats. | def convert_sequences_from_strings_to_floats(features, column_list, seq_len):
"""Converts sequences from single strings to a sequence of floats.
Given features dictionary and feature column names list, convert features
from strings to a sequence of floats.
Args:
features: Dictionary of tensors... | [
"def",
"convert_sequences_from_strings_to_floats",
"(",
"features",
",",
"column_list",
",",
"seq_len",
")",
":",
"for",
"column",
"in",
"column_list",
":",
"features",
"[",
"column",
"]",
"=",
"split_and_convert_string",
"(",
"features",
"[",
"column",
"]",
")",
... | [
51,
0
] | [
70,
19
] | python | en | ['en', 'en', 'en'] | True |
decode_csv | (value_column, seq_len) | Decodes CSV file into tensors.
Given single string tensor and sequence length, returns features dictionary
of tensors and labels tensor.
Args:
value_column: tf.string tensor of shape () compromising entire line of
CSV file.
seq_len: Number of timesteps in sequence.
Returns... | Decodes CSV file into tensors. | def decode_csv(value_column, seq_len):
"""Decodes CSV file into tensors.
Given single string tensor and sequence length, returns features dictionary
of tensors and labels tensor.
Args:
value_column: tf.string tensor of shape () compromising entire line of
CSV file.
seq_len:... | [
"def",
"decode_csv",
"(",
"value_column",
",",
"seq_len",
")",
":",
"columns",
"=",
"tf",
".",
"decode_csv",
"(",
"records",
"=",
"value_column",
",",
"record_defaults",
"=",
"DEFAULTS",
",",
"field_delim",
"=",
"\",\"",
")",
"features",
"=",
"dict",
"(",
... | [
73,
0
] | [
101,
27
] | python | en | ['en', 'en', 'pt'] | True |
read_dataset | (filename, mode, batch_size, seq_len) | Reads CSV time series dataset using tf.data, doing necessary preprocessing.
Given filename, mode, batch size and other parameters, read CSV dataset using
Dataset API, apply necessary preprocessing, and return an input function to
the Estimator API.
Args:
filename: The file pattern that we want... | Reads CSV time series dataset using tf.data, doing necessary preprocessing. | def read_dataset(filename, mode, batch_size, seq_len):
"""Reads CSV time series dataset using tf.data, doing necessary preprocessing.
Given filename, mode, batch size and other parameters, read CSV dataset using
Dataset API, apply necessary preprocessing, and return an input function to
the Estimator A... | [
"def",
"read_dataset",
"(",
"filename",
",",
"mode",
",",
"batch_size",
",",
"seq_len",
")",
":",
"def",
"_input_fn",
"(",
")",
":",
"\"\"\"Wrapper input function to be used by Estimator API to get data tensors.\n\n Returns:\n Batched dataset object of dictionary ... | [
104,
0
] | [
160,
20
] | python | en | ['en', 'en', 'en'] | True |
create_LSTM_stack | (lstm_hidden_units) | Create LSTM stacked cells.
Given list of LSTM hidden units return `MultiRNNCell`.
Args:
lstm_hidden_units: List of integers for the number of hidden units in each
layer.
Returns:
`MultiRNNCell` object of stacked LSTM layers.
| Create LSTM stacked cells. | def create_LSTM_stack(lstm_hidden_units):
"""Create LSTM stacked cells.
Given list of LSTM hidden units return `MultiRNNCell`.
Args:
lstm_hidden_units: List of integers for the number of hidden units in each
layer.
Returns:
`MultiRNNCell` object of stacked LSTM layers.
"""
# First create a ... | [
"def",
"create_LSTM_stack",
"(",
"lstm_hidden_units",
")",
":",
"# First create a list of LSTM cell objects using our list of lstm hidden",
"# unit sizes",
"lstm_cells",
"=",
"[",
"tf",
".",
"contrib",
".",
"rnn",
".",
"BasicLSTMCell",
"(",
"num_units",
"=",
"units",
",",... | [
163,
0
] | [
189,
27
] | python | en | ['en', 'en', 'en'] | True |
sequence_to_one_model | (features, labels, mode, params) | Custom Estimator model function for sequence to one.
Given dictionary of feature tensors, labels tensor, Estimator mode, and
dictionary for parameters, return EstimatorSpec object for custom Estimator.
Args:
features: Dictionary of feature tensors.
labels: Labels tensor or None.
mo... | Custom Estimator model function for sequence to one. | def sequence_to_one_model(features, labels, mode, params):
"""Custom Estimator model function for sequence to one.
Given dictionary of feature tensors, labels tensor, Estimator mode, and
dictionary for parameters, return EstimatorSpec object for custom Estimator.
Args:
features: Dictionary of ... | [
"def",
"sequence_to_one_model",
"(",
"features",
",",
"labels",
",",
"mode",
",",
"params",
")",
":",
"# Get input sequence tensor into correct shape",
"# Stack all of the features into a 3-D tensor",
"X",
"=",
"tf",
".",
"stack",
"(",
"values",
"=",
"[",
"features",
... | [
193,
0
] | [
261,
38
] | python | en | ['en', 'en', 'en'] | True |
fix_shape_and_type_for_serving | (placeholder) | Fixes the shape and type of serving input strings.
Given placeholder tensor, return parsed and processed feature tensor.
Args:
placeholder: Placeholder tensor holding raw data from serving input
function.
Returns:
Parsed and processed feature tensor.
| Fixes the shape and type of serving input strings. | def fix_shape_and_type_for_serving(placeholder):
"""Fixes the shape and type of serving input strings.
Given placeholder tensor, return parsed and processed feature tensor.
Args:
placeholder: Placeholder tensor holding raw data from serving input
function.
Returns:
Parsed an... | [
"def",
"fix_shape_and_type_for_serving",
"(",
"placeholder",
")",
":",
"cur_batch_size",
"=",
"tf",
".",
"shape",
"(",
"input",
"=",
"placeholder",
",",
"out_type",
"=",
"tf",
".",
"int64",
")",
"[",
"0",
"]",
"# String split each string in batch and output values f... | [
265,
0
] | [
294,
25
] | python | en | ['en', 'en', 'en'] | True |
get_shape_and_set_modified_shape_2D | (tensor, additional_dimension_sizes) | Fixes the shape and type of serving input strings.
Given feature tensor and additional dimension size, sequence length,
fixes dynamic shape ambiguity of last dimension so that we will be able to
use it in our DNN (since tf.layers.dense require the last dimension to be
known).
Args:
tensor:... | Fixes the shape and type of serving input strings. | def get_shape_and_set_modified_shape_2D(tensor, additional_dimension_sizes):
"""Fixes the shape and type of serving input strings.
Given feature tensor and additional dimension size, sequence length,
fixes dynamic shape ambiguity of last dimension so that we will be able to
use it in our DNN (since tf.... | [
"def",
"get_shape_and_set_modified_shape_2D",
"(",
"tensor",
",",
"additional_dimension_sizes",
")",
":",
"# Get static shape for tensor and convert it to list",
"shape",
"=",
"tensor",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"# Set outer shape to additional_dim... | [
297,
0
] | [
322,
17
] | python | en | ['en', 'en', 'en'] | True |
serving_input_fn | (seq_len) | Serving input function.
Given the sequence length, return ServingInputReceiver object.
Args:
seq_len: Number of timesteps in sequence.
Returns:
ServingInputReceiver object containing features and receiver tensors.
| Serving input function. | def serving_input_fn(seq_len):
"""Serving input function.
Given the sequence length, return ServingInputReceiver object.
Args:
seq_len: Number of timesteps in sequence.
Returns:
ServingInputReceiver object containing features and receiver tensors.
"""
# Create placeholders to ... | [
"def",
"serving_input_fn",
"(",
"seq_len",
")",
":",
"# Create placeholders to accept the data sent to the model at serving time",
"# All features come in as a batch of strings, shape = (batch_size,),",
"# this was so because of passing the arrays to online ml-engine prediction",
"feature_placehol... | [
325,
0
] | [
355,
69
] | python | en | ['en', 'en', 'en'] | True |
connection_from_url | (url, **kw) |
Given a url, return an :class:`.ConnectionPool` instance of its host.
This is a shortcut for not having to parse out the scheme, host, and port
of the url before creating an :class:`.ConnectionPool` instance.
:param url:
Absolute URL string that must include the scheme. Port is optional.
... |
Given a url, return an :class:`.ConnectionPool` instance of its host. | def connection_from_url(url, **kw):
"""
Given a url, return an :class:`.ConnectionPool` instance of its host.
This is a shortcut for not having to parse out the scheme, host, and port
of the url before creating an :class:`.ConnectionPool` instance.
:param url:
Absolute URL string that must... | [
"def",
"connection_from_url",
"(",
"url",
",",
"*",
"*",
"kw",
")",
":",
"scheme",
",",
"host",
",",
"port",
"=",
"get_host",
"(",
"url",
")",
"port",
"=",
"port",
"or",
"port_by_scheme",
".",
"get",
"(",
"scheme",
",",
"80",
")",
"if",
"scheme",
"... | [
1023,
0
] | [
1048,
56
] | python | en | ['en', 'error', 'th'] | False |
_normalize_host | (host, scheme) |
Normalize hosts for comparisons and use with sockets.
|
Normalize hosts for comparisons and use with sockets.
| def _normalize_host(host, scheme):
"""
Normalize hosts for comparisons and use with sockets.
"""
host = normalize_host(host, scheme)
# httplib doesn't like it when we include brackets in IPv6 addresses
# Specifically, if we include brackets but also pass the port then
# httplib crazily dou... | [
"def",
"_normalize_host",
"(",
"host",
",",
"scheme",
")",
":",
"host",
"=",
"normalize_host",
"(",
"host",
",",
"scheme",
")",
"# httplib doesn't like it when we include brackets in IPv6 addresses",
"# Specifically, if we include brackets but also pass the port then",
"# httplib... | [
1051,
0
] | [
1066,
15
] | python | en | ['en', 'error', 'th'] | False |
ConnectionPool.close | (self) |
Close all pooled connections and disable the pool.
|
Close all pooled connections and disable the pool.
| def close(self):
"""
Close all pooled connections and disable the pool.
"""
pass | [
"def",
"close",
"(",
"self",
")",
":",
"pass"
] | [
92,
4
] | [
96,
12
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool._new_conn | (self) |
Return a fresh :class:`HTTPConnection`.
|
Return a fresh :class:`HTTPConnection`.
| def _new_conn(self):
"""
Return a fresh :class:`HTTPConnection`.
"""
self.num_connections += 1
log.debug(
"Starting new HTTP connection (%d): %s:%s",
self.num_connections,
self.host,
self.port or "80",
)
conn = self... | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"self",
".",
"num_connections",
"+=",
"1",
"log",
".",
"debug",
"(",
"\"Starting new HTTP connection (%d): %s:%s\"",
",",
"self",
".",
"num_connections",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
"or",
"\"... | [
221,
4
] | [
240,
19
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool._get_conn | (self, timeout=None) |
Get a connection. Will return a pooled connection if one is available.
If no connections are available and :prop:`.block` is ``False``, then a
fresh connection is returned.
:param timeout:
Seconds to wait before giving up and raising
:class:`urllib3.exceptions.... |
Get a connection. Will return a pooled connection if one is available. | def _get_conn(self, timeout=None):
"""
Get a connection. Will return a pooled connection if one is available.
If no connections are available and :prop:`.block` is ``False``, then a
fresh connection is returned.
:param timeout:
Seconds to wait before giving up and r... | [
"def",
"_get_conn",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"conn",
"=",
"None",
"try",
":",
"conn",
"=",
"self",
".",
"pool",
".",
"get",
"(",
"block",
"=",
"self",
".",
"block",
",",
"timeout",
"=",
"timeout",
")",
"except",
"Attribut... | [
242,
4
] | [
279,
39
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool._put_conn | (self, conn) |
Put a connection back into the pool.
:param conn:
Connection object for the current host and port as returned by
:meth:`._new_conn` or :meth:`._get_conn`.
If the pool is already full, the connection is closed and discarded
because we exceeded maxsize. If connec... |
Put a connection back into the pool. | def _put_conn(self, conn):
"""
Put a connection back into the pool.
:param conn:
Connection object for the current host and port as returned by
:meth:`._new_conn` or :meth:`._get_conn`.
If the pool is already full, the connection is closed and discarded
... | [
"def",
"_put_conn",
"(",
"self",
",",
"conn",
")",
":",
"try",
":",
"self",
".",
"pool",
".",
"put",
"(",
"conn",
",",
"block",
"=",
"False",
")",
"return",
"# Everything is dandy, done.",
"except",
"AttributeError",
":",
"# self.pool is None.",
"pass",
"exc... | [
281,
4
] | [
307,
24
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool._validate_conn | (self, conn) |
Called right before a request is made, after the socket is created.
|
Called right before a request is made, after the socket is created.
| def _validate_conn(self, conn):
"""
Called right before a request is made, after the socket is created.
"""
pass | [
"def",
"_validate_conn",
"(",
"self",
",",
"conn",
")",
":",
"pass"
] | [
309,
4
] | [
313,
12
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool._get_timeout | (self, timeout) | Helper that always returns a :class:`urllib3.util.Timeout` | Helper that always returns a :class:`urllib3.util.Timeout` | def _get_timeout(self, timeout):
"""Helper that always returns a :class:`urllib3.util.Timeout`"""
if timeout is _Default:
return self.timeout.clone()
if isinstance(timeout, Timeout):
return timeout.clone()
else:
# User passed us an int/float. This is ... | [
"def",
"_get_timeout",
"(",
"self",
",",
"timeout",
")",
":",
"if",
"timeout",
"is",
"_Default",
":",
"return",
"self",
".",
"timeout",
".",
"clone",
"(",
")",
"if",
"isinstance",
"(",
"timeout",
",",
"Timeout",
")",
":",
"return",
"timeout",
".",
"clo... | [
319,
4
] | [
329,
46
] | python | en | ['en', 'lb', 'en'] | True |
HTTPConnectionPool._raise_timeout | (self, err, url, timeout_value) | Is the error actually a timeout? Will raise a ReadTimeout or pass | Is the error actually a timeout? Will raise a ReadTimeout or pass | def _raise_timeout(self, err, url, timeout_value):
"""Is the error actually a timeout? Will raise a ReadTimeout or pass"""
if isinstance(err, SocketTimeout):
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % timeout_value
)
# See t... | [
"def",
"_raise_timeout",
"(",
"self",
",",
"err",
",",
"url",
",",
"timeout_value",
")",
":",
"if",
"isinstance",
"(",
"err",
",",
"SocketTimeout",
")",
":",
"raise",
"ReadTimeoutError",
"(",
"self",
",",
"url",
",",
"\"Read timed out. (read timeout=%s)\"",
"%... | [
331,
4
] | [
354,
13
] | python | en | ['en', 'en', 'en'] | True |
HTTPConnectionPool._make_request | (
self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
) |
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same ... |
Perform a request on a given urllib connection object taken from our
pool. | def _make_request(
self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw
):
"""
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:... | [
"def",
"_make_request",
"(",
"self",
",",
"conn",
",",
"method",
",",
"url",
",",
"timeout",
"=",
"_Default",
",",
"chunked",
"=",
"False",
",",
"*",
"*",
"httplib_request_kw",
")",
":",
"self",
".",
"num_requests",
"+=",
"1",
"timeout_obj",
"=",
"self",... | [
356,
4
] | [
473,
31
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool.close | (self) |
Close all pooled connections and disable the pool.
|
Close all pooled connections and disable the pool.
| def close(self):
"""
Close all pooled connections and disable the pool.
"""
if self.pool is None:
return
# Disable access to the pool
old_pool, self.pool = self.pool, None
try:
while True:
conn = old_pool.get(block=False)
... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"pool",
"is",
"None",
":",
"return",
"# Disable access to the pool",
"old_pool",
",",
"self",
".",
"pool",
"=",
"self",
".",
"pool",
",",
"None",
"try",
":",
"while",
"True",
":",
"conn",
"=",
... | [
478,
4
] | [
494,
16
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool.is_same_host | (self, url) |
Check if the given ``url`` is a member of the same host as this
connection pool.
|
Check if the given ``url`` is a member of the same host as this
connection pool.
| def is_same_host(self, url):
"""
Check if the given ``url`` is a member of the same host as this
connection pool.
"""
if url.startswith("/"):
return True
# TODO: Add optional support for socket.gethostbyname checking.
scheme, host, port = get_host(url... | [
"def",
"is_same_host",
"(",
"self",
",",
"url",
")",
":",
"if",
"url",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"return",
"True",
"# TODO: Add optional support for socket.gethostbyname checking.",
"scheme",
",",
"host",
",",
"port",
"=",
"get_host",
"(",
"url"... | [
496,
4
] | [
515,
74
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnectionPool.urlopen | (
self,
method,
url,
body=None,
headers=None,
retries=None,
redirect=True,
assert_same_host=True,
timeout=_Default,
pool_timeout=None,
release_conn=None,
chunked=False,
body_pos=None,
**response_kw
) |
Get a connection from the pool and perform an HTTP request. This is the
lowest level call for making a request, so you'll need to specify all
the raw details.
.. note::
More commonly, it's appropriate to use a convenience method provided
by :class:`.RequestMethod... |
Get a connection from the pool and perform an HTTP request. This is the
lowest level call for making a request, so you'll need to specify all
the raw details. | def urlopen(
self,
method,
url,
body=None,
headers=None,
retries=None,
redirect=True,
assert_same_host=True,
timeout=_Default,
pool_timeout=None,
release_conn=None,
chunked=False,
body_pos=None,
**response_kw... | [
"def",
"urlopen",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"retries",
"=",
"None",
",",
"redirect",
"=",
"True",
",",
"assert_same_host",
"=",
"True",
",",
"timeout",
"=",
"_Default",
",",
"p... | [
517,
4
] | [
861,
23
] | python | en | ['en', 'error', 'th'] | False |
HTTPSConnectionPool._prepare_conn | (self, conn) |
Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
and establish the tunnel if proxy is used.
|
Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
and establish the tunnel if proxy is used.
| def _prepare_conn(self, conn):
"""
Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
and establish the tunnel if proxy is used.
"""
if isinstance(conn, VerifiedHTTPSConnection):
conn.set_cert(
key_file=self.key_file,
... | [
"def",
"_prepare_conn",
"(",
"self",
",",
"conn",
")",
":",
"if",
"isinstance",
"(",
"conn",
",",
"VerifiedHTTPSConnection",
")",
":",
"conn",
".",
"set_cert",
"(",
"key_file",
"=",
"self",
".",
"key_file",
",",
"key_password",
"=",
"self",
".",
"key_passw... | [
930,
4
] | [
948,
19
] | python | en | ['en', 'error', 'th'] | False |
HTTPSConnectionPool._prepare_proxy | (self, conn) |
Establishes a tunnel connection through HTTP CONNECT.
Tunnel connection is established early because otherwise httplib would
improperly set Host: header to proxy's IP:port.
|
Establishes a tunnel connection through HTTP CONNECT. | def _prepare_proxy(self, conn):
"""
Establishes a tunnel connection through HTTP CONNECT.
Tunnel connection is established early because otherwise httplib would
improperly set Host: header to proxy's IP:port.
"""
conn.set_tunnel(self._proxy_host, self.port, self.proxy_h... | [
"def",
"_prepare_proxy",
"(",
"self",
",",
"conn",
")",
":",
"conn",
".",
"set_tunnel",
"(",
"self",
".",
"_proxy_host",
",",
"self",
".",
"port",
",",
"self",
".",
"proxy_headers",
")",
"if",
"self",
".",
"proxy",
".",
"scheme",
"==",
"\"https\"",
":"... | [
950,
4
] | [
963,
22
] | python | en | ['en', 'error', 'th'] | False |
HTTPSConnectionPool._new_conn | (self) |
Return a fresh :class:`http.client.HTTPSConnection`.
|
Return a fresh :class:`http.client.HTTPSConnection`.
| def _new_conn(self):
"""
Return a fresh :class:`http.client.HTTPSConnection`.
"""
self.num_connections += 1
log.debug(
"Starting new HTTPS connection (%d): %s:%s",
self.num_connections,
self.host,
self.port or "443",
)
... | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"self",
".",
"num_connections",
"+=",
"1",
"log",
".",
"debug",
"(",
"\"Starting new HTTPS connection (%d): %s:%s\"",
",",
"self",
".",
"num_connections",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
"or",
"\... | [
965,
4
] | [
999,
39
] | python | en | ['en', 'error', 'th'] | False |
HTTPSConnectionPool._validate_conn | (self, conn) |
Called right before a request is made, after the socket is created.
|
Called right before a request is made, after the socket is created.
| def _validate_conn(self, conn):
"""
Called right before a request is made, after the socket is created.
"""
super(HTTPSConnectionPool, self)._validate_conn(conn)
# Force connect early to allow us to validate the connection.
if not getattr(conn, "sock", None): # AppEngin... | [
"def",
"_validate_conn",
"(",
"self",
",",
"conn",
")",
":",
"super",
"(",
"HTTPSConnectionPool",
",",
"self",
")",
".",
"_validate_conn",
"(",
"conn",
")",
"# Force connect early to allow us to validate the connection.",
"if",
"not",
"getattr",
"(",
"conn",
",",
... | [
1001,
4
] | [
1020,
13
] | python | en | ['en', 'error', 'th'] | False |
split_identifier | (identifier) |
Split an SQL identifier into a two element tuple of (namespace, name).
The identifier could be a table, column, or sequence name might be prefixed
by a namespace.
|
Split an SQL identifier into a two element tuple of (namespace, name). | def split_identifier(identifier):
"""
Split an SQL identifier into a two element tuple of (namespace, name).
The identifier could be a table, column, or sequence name might be prefixed
by a namespace.
"""
try:
namespace, name = identifier.split('"."')
except ValueError:
name... | [
"def",
"split_identifier",
"(",
"identifier",
")",
":",
"try",
":",
"namespace",
",",
"name",
"=",
"identifier",
".",
"split",
"(",
"'\".\"'",
")",
"except",
"ValueError",
":",
"namespace",
",",
"name",
"=",
"''",
",",
"identifier",
"return",
"namespace",
... | [
181,
0
] | [
192,
48
] | python | en | ['en', 'error', 'th'] | False |
truncate_name | (identifier, length=None, hash_len=4) |
Shorten an SQL identifier to a repeatable mangled version with the given
length.
If a quote stripped name contains a namespace, e.g. USERNAME"."TABLE,
truncate the table portion only.
|
Shorten an SQL identifier to a repeatable mangled version with the given
length. | def truncate_name(identifier, length=None, hash_len=4):
"""
Shorten an SQL identifier to a repeatable mangled version with the given
length.
If a quote stripped name contains a namespace, e.g. USERNAME"."TABLE,
truncate the table portion only.
"""
namespace, name = split_identifier(identifi... | [
"def",
"truncate_name",
"(",
"identifier",
",",
"length",
"=",
"None",
",",
"hash_len",
"=",
"4",
")",
":",
"namespace",
",",
"name",
"=",
"split_identifier",
"(",
"identifier",
")",
"if",
"length",
"is",
"None",
"or",
"len",
"(",
"name",
")",
"<=",
"l... | [
195,
0
] | [
209,
98
] | python | en | ['en', 'error', 'th'] | False |
names_digest | (*args, length) |
Generate a 32-bit digest of a set of arguments that can be used to shorten
identifying names.
|
Generate a 32-bit digest of a set of arguments that can be used to shorten
identifying names.
| def names_digest(*args, length):
"""
Generate a 32-bit digest of a set of arguments that can be used to shorten
identifying names.
"""
h = hashlib.md5()
for arg in args:
h.update(arg.encode())
return h.hexdigest()[:length] | [
"def",
"names_digest",
"(",
"*",
"args",
",",
"length",
")",
":",
"h",
"=",
"hashlib",
".",
"md5",
"(",
")",
"for",
"arg",
"in",
"args",
":",
"h",
".",
"update",
"(",
"arg",
".",
"encode",
"(",
")",
")",
"return",
"h",
".",
"hexdigest",
"(",
")... | [
212,
0
] | [
220,
33
] | python | en | ['en', 'error', 'th'] | False |
format_number | (value, max_digits, decimal_places) |
Format a number into a string with the requisite number of digits and
decimal places.
|
Format a number into a string with the requisite number of digits and
decimal places.
| def format_number(value, max_digits, decimal_places):
"""
Format a number into a string with the requisite number of digits and
decimal places.
"""
if value is None:
return None
context = decimal.getcontext().copy()
if max_digits is not None:
context.prec = max_digits
if ... | [
"def",
"format_number",
"(",
"value",
",",
"max_digits",
",",
"decimal_places",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"context",
"=",
"decimal",
".",
"getcontext",
"(",
")",
".",
"copy",
"(",
")",
"if",
"max_digits",
"is",
"not",
... | [
223,
0
] | [
238,
31
] | python | en | ['en', 'error', 'th'] | False |
strip_quotes | (table_name) |
Strip quotes off of quoted table names to make them safe for use in index
names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
scheme) becomes 'USER"."TABLE'.
|
Strip quotes off of quoted table names to make them safe for use in index
names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
scheme) becomes 'USER"."TABLE'.
| def strip_quotes(table_name):
"""
Strip quotes off of quoted table names to make them safe for use in index
names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
scheme) becomes 'USER"."TABLE'.
"""
has_quotes = table_name.startswith('"') and table_name.endswith('"')
retu... | [
"def",
"strip_quotes",
"(",
"table_name",
")",
":",
"has_quotes",
"=",
"table_name",
".",
"startswith",
"(",
"'\"'",
")",
"and",
"table_name",
".",
"endswith",
"(",
"'\"'",
")",
"return",
"table_name",
"[",
"1",
":",
"-",
"1",
"]",
"if",
"has_quotes",
"e... | [
241,
0
] | [
248,
57
] | python | en | ['en', 'error', 'th'] | False |
find_module | (module, paths=None) | Just like 'imp.find_module()', but with package support | Just like 'imp.find_module()', but with package support | def find_module(module, paths=None):
"""Just like 'imp.find_module()', but with package support"""
parts = module.split('.')
while parts:
part = parts.pop(0)
f, path, (suffix, mode, kind) = info = imp.find_module(part, paths)
if kind == PKG_DIRECTORY:
parts = parts or ... | [
"def",
"find_module",
"(",
"module",
",",
"paths",
"=",
"None",
")",
":",
"parts",
"=",
"module",
".",
"split",
"(",
"'.'",
")",
"while",
"parts",
":",
"part",
"=",
"parts",
".",
"pop",
"(",
"0",
")",
"f",
",",
"path",
",",
"(",
"suffix",
",",
... | [
81,
0
] | [
97,
15
] | python | en | ['en', 'en', 'en'] | True |
get_module_constant | (module, symbol, default=-1, paths=None) | Find 'module' by searching 'paths', and extract 'symbol'
Return 'None' if 'module' does not exist on 'paths', or it does not define
'symbol'. If the module defines 'symbol' as a constant, return the
constant. Otherwise, return 'default'. | Find 'module' by searching 'paths', and extract 'symbol' | def get_module_constant(module, symbol, default=-1, paths=None):
"""Find 'module' by searching 'paths', and extract 'symbol'
Return 'None' if 'module' does not exist on 'paths', or it does not define
'symbol'. If the module defines 'symbol' as a constant, return the
constant. Otherwise, return 'defau... | [
"def",
"get_module_constant",
"(",
"module",
",",
"symbol",
",",
"default",
"=",
"-",
"1",
",",
"paths",
"=",
"None",
")",
":",
"try",
":",
"f",
",",
"path",
",",
"(",
"suffix",
",",
"mode",
",",
"kind",
")",
"=",
"find_module",
"(",
"module",
",",... | [
100,
0
] | [
131,
50
] | python | en | ['en', 'en', 'en'] | True |
extract_constant | (code, symbol, default=-1) | Extract the constant value of 'symbol' from 'code'
If the name 'symbol' is bound to a constant value by the Python code
object 'code', return that value. If 'symbol' is bound to an expression,
return 'default'. Otherwise, return 'None'.
Return value is based on the first assignment to 'symbol'. 'sy... | Extract the constant value of 'symbol' from 'code' | def extract_constant(code, symbol, default=-1):
"""Extract the constant value of 'symbol' from 'code'
If the name 'symbol' is bound to a constant value by the Python code
object 'code', return that value. If 'symbol' is bound to an expression,
return 'default'. Otherwise, return 'None'.
Return v... | [
"def",
"extract_constant",
"(",
"code",
",",
"symbol",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"symbol",
"not",
"in",
"code",
".",
"co_names",
":",
"# name's not there, can't possibly be an assignment",
"return",
"None",
"name_idx",
"=",
"list",
"(",
"c... | [
134,
0
] | [
167,
27
] | python | en | ['en', 'en', 'en'] | True |
_update_globals | () |
Patch the globals to remove the objects not available on some platforms.
XXX it'd be better to test assertions about bytecode instead.
|
Patch the globals to remove the objects not available on some platforms. | def _update_globals():
"""
Patch the globals to remove the objects not available on some platforms.
XXX it'd be better to test assertions about bytecode instead.
"""
if not sys.platform.startswith('java') and sys.platform != 'cli':
return
incompatible = 'extract_constant', 'get_module_... | [
"def",
"_update_globals",
"(",
")",
":",
"if",
"not",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'java'",
")",
"and",
"sys",
".",
"platform",
"!=",
"'cli'",
":",
"return",
"incompatible",
"=",
"'extract_constant'",
",",
"'get_module_constant'",
"for",
... | [
170,
0
] | [
182,
28
] | python | en | ['en', 'error', 'th'] | False |
Require.full_name | (self) | Return full package/distribution name, w/version | Return full package/distribution name, w/version | def full_name(self):
"""Return full package/distribution name, w/version"""
if self.requested_version is not None:
return '%s-%s' % (self.name, self.requested_version)
return self.name | [
"def",
"full_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"requested_version",
"is",
"not",
"None",
":",
"return",
"'%s-%s'",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"requested_version",
")",
"return",
"self",
".",
"name"
] | [
31,
4
] | [
35,
24
] | python | en | ['en', 'en', 'en'] | True |
Require.version_ok | (self, version) | Is 'version' sufficiently up-to-date? | Is 'version' sufficiently up-to-date? | def version_ok(self, version):
"""Is 'version' sufficiently up-to-date?"""
return self.attribute is None or self.format is None or \
str(version) != "unknown" and version >= self.requested_version | [
"def",
"version_ok",
"(",
"self",
",",
"version",
")",
":",
"return",
"self",
".",
"attribute",
"is",
"None",
"or",
"self",
".",
"format",
"is",
"None",
"or",
"str",
"(",
"version",
")",
"!=",
"\"unknown\"",
"and",
"version",
">=",
"self",
".",
"reques... | [
37,
4
] | [
40,
75
] | python | en | ['en', 'en', 'en'] | True |
Require.get_version | (self, paths=None, default="unknown") | Get version number of installed module, 'None', or 'default'
Search 'paths' for module. If not found, return 'None'. If found,
return the extracted version attribute, or 'default' if no version
attribute was specified, or the value cannot be determined without
importing the module. T... | Get version number of installed module, 'None', or 'default' | def get_version(self, paths=None, default="unknown"):
"""Get version number of installed module, 'None', or 'default'
Search 'paths' for module. If not found, return 'None'. If found,
return the extracted version attribute, or 'default' if no version
attribute was specified, or the va... | [
"def",
"get_version",
"(",
"self",
",",
"paths",
"=",
"None",
",",
"default",
"=",
"\"unknown\"",
")",
":",
"if",
"self",
".",
"attribute",
"is",
"None",
":",
"try",
":",
"f",
",",
"p",
",",
"i",
"=",
"find_module",
"(",
"self",
".",
"module",
",",... | [
42,
4
] | [
67,
16
] | python | en | ['en', 'en', 'en'] | True |
Require.is_present | (self, paths=None) | Return true if dependency is present on 'paths | Return true if dependency is present on 'paths | def is_present(self, paths=None):
"""Return true if dependency is present on 'paths'"""
return self.get_version(paths) is not None | [
"def",
"is_present",
"(",
"self",
",",
"paths",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_version",
"(",
"paths",
")",
"is",
"not",
"None"
] | [
69,
4
] | [
71,
50
] | python | en | ['en', 'af', 'en'] | True |
Require.is_current | (self, paths=None) | Return true if dependency is present and up-to-date on 'paths | Return true if dependency is present and up-to-date on 'paths | def is_current(self, paths=None):
"""Return true if dependency is present and up-to-date on 'paths'"""
version = self.get_version(paths)
if version is None:
return False
return self.version_ok(version) | [
"def",
"is_current",
"(",
"self",
",",
"paths",
"=",
"None",
")",
":",
"version",
"=",
"self",
".",
"get_version",
"(",
"paths",
")",
"if",
"version",
"is",
"None",
":",
"return",
"False",
"return",
"self",
".",
"version_ok",
"(",
"version",
")"
] | [
73,
4
] | [
78,
39
] | python | en | ['en', 'en', 'en'] | True |
ContainerIO.__init__ | (self, file, offset, length) |
Create file object.
:param file: Existing file.
:param offset: Start of region, in bytes.
:param length: Size of region, in bytes.
|
Create file object. | def __init__(self, file, offset, length):
"""
Create file object.
:param file: Existing file.
:param offset: Start of region, in bytes.
:param length: Size of region, in bytes.
"""
self.fh = file
self.pos = 0
self.offset = offset
self.leng... | [
"def",
"__init__",
"(",
"self",
",",
"file",
",",
"offset",
",",
"length",
")",
":",
"self",
".",
"fh",
"=",
"file",
"self",
".",
"pos",
"=",
"0",
"self",
".",
"offset",
"=",
"offset",
"self",
".",
"length",
"=",
"length",
"self",
".",
"fh",
".",... | [
26,
4
] | [
38,
28
] | python | en | ['en', 'error', 'th'] | False |
ContainerIO.seek | (self, offset, mode=io.SEEK_SET) |
Move file pointer.
:param offset: Offset in bytes.
:param mode: Starting position. Use 0 for beginning of region, 1
for current offset, and 2 for end of region. You cannot move
the pointer outside the defined region.
|
Move file pointer. | def seek(self, offset, mode=io.SEEK_SET):
"""
Move file pointer.
:param offset: Offset in bytes.
:param mode: Starting position. Use 0 for beginning of region, 1
for current offset, and 2 for end of region. You cannot move
the pointer outside the defined region.
... | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"mode",
"=",
"io",
".",
"SEEK_SET",
")",
":",
"if",
"mode",
"==",
"1",
":",
"self",
".",
"pos",
"=",
"self",
".",
"pos",
"+",
"offset",
"elif",
"mode",
"==",
"2",
":",
"self",
".",
"pos",
"=",
"... | [
46,
4
] | [
63,
44
] | python | en | ['en', 'error', 'th'] | False |
ContainerIO.tell | (self) |
Get current file pointer.
:returns: Offset from start of region, in bytes.
|
Get current file pointer. | def tell(self):
"""
Get current file pointer.
:returns: Offset from start of region, in bytes.
"""
return self.pos | [
"def",
"tell",
"(",
"self",
")",
":",
"return",
"self",
".",
"pos"
] | [
65,
4
] | [
71,
23
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.