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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MultiValueDict.appendlist | (self, key, value) | Appends an item to the internal list associated with key. | Appends an item to the internal list associated with key. | def appendlist(self, key, value):
"""Appends an item to the internal list associated with key."""
self.setlistdefault(key).append(value) | [
"def",
"appendlist",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"setlistdefault",
"(",
"key",
")",
".",
"append",
"(",
"value",
")"
] | [
398,
4
] | [
400,
46
] | python | en | ['en', 'en', 'en'] | True |
MultiValueDict._iteritems | (self) |
Yields (key, value) pairs, where value is the last item in the list
associated with the key.
|
Yields (key, value) pairs, where value is the last item in the list
associated with the key.
| def _iteritems(self):
"""
Yields (key, value) pairs, where value is the last item in the list
associated with the key.
"""
for key in self:
yield key, self[key] | [
"def",
"_iteritems",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
":",
"yield",
"key",
",",
"self",
"[",
"key",
"]"
] | [
402,
4
] | [
408,
32
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict._iterlists | (self) | Yields (key, list) pairs. | Yields (key, list) pairs. | def _iterlists(self):
"""Yields (key, list) pairs."""
return six.iteritems(super(MultiValueDict, self)) | [
"def",
"_iterlists",
"(",
"self",
")",
":",
"return",
"six",
".",
"iteritems",
"(",
"super",
"(",
"MultiValueDict",
",",
"self",
")",
")"
] | [
410,
4
] | [
412,
57
] | python | en | ['fr', 'hmn', 'en'] | False |
MultiValueDict._itervalues | (self) | Yield the last value on every key list. | Yield the last value on every key list. | def _itervalues(self):
"""Yield the last value on every key list."""
for key in self:
yield self[key] | [
"def",
"_itervalues",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
":",
"yield",
"self",
"[",
"key",
"]"
] | [
414,
4
] | [
417,
27
] | python | en | ['en', 'en', 'en'] | True |
MultiValueDict.copy | (self) | Returns a shallow copy of this object. | Returns a shallow copy of this object. | def copy(self):
"""Returns a shallow copy of this object."""
return copy.copy(self) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"copy",
".",
"copy",
"(",
"self",
")"
] | [
437,
4
] | [
439,
30
] | python | en | ['en', 'en', 'en'] | True |
MultiValueDict.update | (self, *args, **kwargs) |
update() extends rather than replaces existing key lists.
Also accepts keyword args.
|
update() extends rather than replaces existing key lists.
Also accepts keyword args.
| def update(self, *args, **kwargs):
"""
update() extends rather than replaces existing key lists.
Also accepts keyword args.
"""
if len(args) > 1:
raise TypeError("update expected at most 1 arguments, got %d" % len(args))
if args:
other_dict = args[... | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"update expected at most 1 arguments, got %d\"",
"%",
"len",
"(",
"args",
")",
")",
"if",
"arg... | [
441,
4
] | [
460,
50
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict.dict | (self) |
Returns current object as a dict with singular values.
|
Returns current object as a dict with singular values.
| def dict(self):
"""
Returns current object as a dict with singular values.
"""
return dict((key, self[key]) for key in self) | [
"def",
"dict",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"key",
",",
"self",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"self",
")"
] | [
462,
4
] | [
466,
53
] | python | en | ['en', 'error', 'th'] | False |
DictWrapper.__getitem__ | (self, key) |
Retrieves the real value after stripping the prefix string (if
present). If the prefix is present, pass the value through self.func
before returning, otherwise return the raw value.
|
Retrieves the real value after stripping the prefix string (if
present). If the prefix is present, pass the value through self.func
before returning, otherwise return the raw value.
| def __getitem__(self, key):
"""
Retrieves the real value after stripping the prefix string (if
present). If the prefix is present, pass the value through self.func
before returning, otherwise return the raw value.
"""
if key.startswith(self.prefix):
use_func =... | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"self",
".",
"prefix",
")",
":",
"use_func",
"=",
"True",
"key",
"=",
"key",
"[",
"len",
"(",
"self",
".",
"prefix",
")",
":",
"]",
"else",
":",
"use_fu... | [
528,
4
] | [
542,
20
] | python | en | ['en', 'error', 'th'] | False |
DeleteQuery.delete_batch | (self, pk_list, using, field=None) |
Set up and execute delete queries for all the objects in pk_list.
More than one physical query may be executed if there are a
lot of values in pk_list.
|
Set up and execute delete queries for all the objects in pk_list. | def delete_batch(self, pk_list, using, field=None):
"""
Set up and execute delete queries for all the objects in pk_list.
More than one physical query may be executed if there are a
lot of values in pk_list.
"""
if not field:
field = self.get_meta().pk
... | [
"def",
"delete_batch",
"(",
"self",
",",
"pk_list",
",",
"using",
",",
"field",
"=",
"None",
")",
":",
"if",
"not",
"field",
":",
"field",
"=",
"self",
".",
"get_meta",
"(",
")",
".",
"pk",
"for",
"offset",
"in",
"range",
"(",
"0",
",",
"len",
"(... | [
34,
4
] | [
47,
76
] | python | en | ['en', 'error', 'th'] | False |
DeleteQuery.delete_qs | (self, query, using) |
Delete the queryset in one SQL query (if possible). For simple queries
this is done by copying the query.query.where to self.query, for
complex queries by using subquery.
|
Delete the queryset in one SQL query (if possible). For simple queries
this is done by copying the query.query.where to self.query, for
complex queries by using subquery.
| def delete_qs(self, query, using):
"""
Delete the queryset in one SQL query (if possible). For simple queries
this is done by copying the query.query.where to self.query, for
complex queries by using subquery.
"""
innerq = query.query
# Make sure the inner query h... | [
"def",
"delete_qs",
"(",
"self",
",",
"query",
",",
"using",
")",
":",
"innerq",
"=",
"query",
".",
"query",
"# Make sure the inner query has at least one table in use.",
"innerq",
".",
"get_initial_alias",
"(",
")",
"# The same for our new query.",
"self",
".",
"get_... | [
49,
4
] | [
84,
56
] | python | en | ['en', 'error', 'th'] | False |
UpdateQuery._setup_query | (self) |
Runs on initialization and after cloning. Any attributes that would
normally be set in __init__ should go in here, instead, so that they
are also set up after a clone() call.
|
Runs on initialization and after cloning. Any attributes that would
normally be set in __init__ should go in here, instead, so that they
are also set up after a clone() call.
| def _setup_query(self):
"""
Runs on initialization and after cloning. Any attributes that would
normally be set in __init__ should go in here, instead, so that they
are also set up after a clone() call.
"""
self.values = []
self.related_ids = None
if not h... | [
"def",
"_setup_query",
"(",
"self",
")",
":",
"self",
".",
"values",
"=",
"[",
"]",
"self",
".",
"related_ids",
"=",
"None",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'related_updates'",
")",
":",
"self",
".",
"related_updates",
"=",
"{",
"}"
] | [
98,
4
] | [
107,
37
] | python | en | ['en', 'error', 'th'] | False |
UpdateQuery.add_update_values | (self, values) |
Convert a dictionary of field name to value mappings into an update
query. This is the entry point for the public update() method on
querysets.
|
Convert a dictionary of field name to value mappings into an update
query. This is the entry point for the public update() method on
querysets.
| def add_update_values(self, values):
"""
Convert a dictionary of field name to value mappings into an update
query. This is the entry point for the public update() method on
querysets.
"""
values_seq = []
for name, val in six.iteritems(values):
field, ... | [
"def",
"add_update_values",
"(",
"self",
",",
"values",
")",
":",
"values_seq",
"=",
"[",
"]",
"for",
"name",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"values",
")",
":",
"field",
",",
"model",
",",
"direct",
",",
"m2m",
"=",
"self",
".",
"g... | [
120,
4
] | [
138,
49
] | python | en | ['en', 'error', 'th'] | False |
UpdateQuery.add_update_fields | (self, values_seq) |
Turn a sequence of (field, model, value) triples into an update query.
Used by add_update_values() as well as the "fast" update path when
saving models.
|
Turn a sequence of (field, model, value) triples into an update query.
Used by add_update_values() as well as the "fast" update path when
saving models.
| def add_update_fields(self, values_seq):
"""
Turn a sequence of (field, model, value) triples into an update query.
Used by add_update_values() as well as the "fast" update path when
saving models.
"""
self.values.extend(values_seq) | [
"def",
"add_update_fields",
"(",
"self",
",",
"values_seq",
")",
":",
"self",
".",
"values",
".",
"extend",
"(",
"values_seq",
")"
] | [
140,
4
] | [
146,
38
] | python | en | ['en', 'error', 'th'] | False |
UpdateQuery.add_related_update | (self, model, field, value) |
Adds (name, value) to an update query for an ancestor model.
Updates are coalesced so that we only run one update query per ancestor.
|
Adds (name, value) to an update query for an ancestor model. | def add_related_update(self, model, field, value):
"""
Adds (name, value) to an update query for an ancestor model.
Updates are coalesced so that we only run one update query per ancestor.
"""
self.related_updates.setdefault(model, []).append((field, None, value)) | [
"def",
"add_related_update",
"(",
"self",
",",
"model",
",",
"field",
",",
"value",
")",
":",
"self",
".",
"related_updates",
".",
"setdefault",
"(",
"model",
",",
"[",
"]",
")",
".",
"append",
"(",
"(",
"field",
",",
"None",
",",
"value",
")",
")"
] | [
148,
4
] | [
154,
79
] | python | en | ['en', 'error', 'th'] | False |
UpdateQuery.get_related_updates | (self) |
Returns a list of query objects: one for each update required to an
ancestor model. Each query will have the same filtering conditions as
the current query but will only update a single table.
|
Returns a list of query objects: one for each update required to an
ancestor model. Each query will have the same filtering conditions as
the current query but will only update a single table.
| def get_related_updates(self):
"""
Returns a list of query objects: one for each update required to an
ancestor model. Each query will have the same filtering conditions as
the current query but will only update a single table.
"""
if not self.related_updates:
... | [
"def",
"get_related_updates",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"related_updates",
":",
"return",
"[",
"]",
"result",
"=",
"[",
"]",
"for",
"model",
",",
"values",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"related_updates",
")",
... | [
156,
4
] | [
171,
21
] | python | en | ['en', 'error', 'th'] | False |
InsertQuery.insert_values | (self, fields, objs, raw=False) |
Set up the insert query from the 'insert_values' dictionary. The
dictionary gives the model field names and their target values.
If 'raw_values' is True, the values in the 'insert_values' dictionary
are inserted directly into the query, rather than passed as SQL
parameters. Thi... |
Set up the insert query from the 'insert_values' dictionary. The
dictionary gives the model field names and their target values. | def insert_values(self, fields, objs, raw=False):
"""
Set up the insert query from the 'insert_values' dictionary. The
dictionary gives the model field names and their target values.
If 'raw_values' is True, the values in the 'insert_values' dictionary
are inserted directly into... | [
"def",
"insert_values",
"(",
"self",
",",
"fields",
",",
"objs",
",",
"raw",
"=",
"False",
")",
":",
"self",
".",
"fields",
"=",
"fields",
"self",
".",
"objs",
"=",
"objs",
"self",
".",
"raw",
"=",
"raw"
] | [
191,
4
] | [
203,
22
] | python | en | ['en', 'error', 'th'] | False |
DateQuery.add_select | (self, field_name, lookup_type, order='ASC') |
Converts the query into an extraction query.
|
Converts the query into an extraction query.
| def add_select(self, field_name, lookup_type, order='ASC'):
"""
Converts the query into an extraction query.
"""
try:
field, _, _, joins, _ = self.setup_joins(
field_name.split(LOOKUP_SEP),
self.get_meta(),
self.get_initial_alia... | [
"def",
"add_select",
"(",
"self",
",",
"field_name",
",",
"lookup_type",
",",
"order",
"=",
"'ASC'",
")",
":",
"try",
":",
"field",
",",
"_",
",",
"_",
",",
"joins",
",",
"_",
"=",
"self",
".",
"setup_joins",
"(",
"field_name",
".",
"split",
"(",
"... | [
215,
4
] | [
238,
63
] | python | en | ['en', 'error', 'th'] | False |
deprecated | (reason, replacement, gone_in, issue=None) | Helper to deprecate existing functionality.
reason:
Textual reason shown to the user about why this functionality has
been deprecated.
replacement:
Textual suggestion shown to the user about what alternative
functionality they can use.
gone_in:
The version of pip doe... | Helper to deprecate existing functionality. | def deprecated(reason, replacement, gone_in, issue=None):
# type: (str, Optional[str], Optional[str], Optional[int]) -> None
"""Helper to deprecate existing functionality.
reason:
Textual reason shown to the user about why this functionality has
been deprecated.
replacement:
Tex... | [
"def",
"deprecated",
"(",
"reason",
",",
"replacement",
",",
"gone_in",
",",
"issue",
"=",
"None",
")",
":",
"# type: (str, Optional[str], Optional[str], Optional[int]) -> None",
"# Construct a nice message.",
"# This is eagerly formatted as we want it to get logged as if someone",... | [
61,
0
] | [
103,
72
] | python | en | ['it', 'en', 'en'] | True |
sanitize_content_filename | (filename) |
Sanitize the "filename" value from a Content-Disposition header.
|
Sanitize the "filename" value from a Content-Disposition header.
| def sanitize_content_filename(filename):
# type: (str) -> str
"""
Sanitize the "filename" value from a Content-Disposition header.
"""
return os.path.basename(filename) | [
"def",
"sanitize_content_filename",
"(",
"filename",
")",
":",
"# type: (str) -> str",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")"
] | [
84,
0
] | [
89,
37
] | python | en | ['en', 'error', 'th'] | False |
parse_content_disposition | (content_disposition, default_filename) |
Parse the "filename" value from a Content-Disposition header, and
return the default filename if the result is empty.
|
Parse the "filename" value from a Content-Disposition header, and
return the default filename if the result is empty.
| def parse_content_disposition(content_disposition, default_filename):
# type: (str, str) -> str
"""
Parse the "filename" value from a Content-Disposition header, and
return the default filename if the result is empty.
"""
_type, params = cgi.parse_header(content_disposition)
filename = param... | [
"def",
"parse_content_disposition",
"(",
"content_disposition",
",",
"default_filename",
")",
":",
"# type: (str, str) -> str",
"_type",
",",
"params",
"=",
"cgi",
".",
"parse_header",
"(",
"content_disposition",
")",
"filename",
"=",
"params",
".",
"get",
"(",
"'fi... | [
92,
0
] | [
104,
39
] | python | en | ['en', 'error', 'th'] | False |
_get_http_response_filename | (resp, link) | Get an ideal filename from the given HTTP response, falling back to
the link filename if not provided.
| Get an ideal filename from the given HTTP response, falling back to
the link filename if not provided.
| def _get_http_response_filename(resp, link):
# type: (Response, Link) -> str
"""Get an ideal filename from the given HTTP response, falling back to
the link filename if not provided.
"""
filename = link.filename # fallback
# Have a look at the Content-Disposition header for a better guess
c... | [
"def",
"_get_http_response_filename",
"(",
"resp",
",",
"link",
")",
":",
"# type: (Response, Link) -> str",
"filename",
"=",
"link",
".",
"filename",
"# fallback",
"# Have a look at the Content-Disposition header for a better guess",
"content_disposition",
"=",
"resp",
".",
... | [
107,
0
] | [
128,
19
] | python | en | ['en', 'en', 'en'] | True |
DatabaseCreation._maindb_connection | (self) |
This is analogous to other backends' `_nodb_connection` property,
which allows access to an "administrative" connection which can
be used to manage the test databases.
For Oracle, the only connection that can be used for that purpose
is the main (non-test) connection.
|
This is analogous to other backends' `_nodb_connection` property,
which allows access to an "administrative" connection which can
be used to manage the test databases.
For Oracle, the only connection that can be used for that purpose
is the main (non-test) connection.
| def _maindb_connection(self):
"""
This is analogous to other backends' `_nodb_connection` property,
which allows access to an "administrative" connection which can
be used to manage the test databases.
For Oracle, the only connection that can be used for that purpose
is t... | [
"def",
"_maindb_connection",
"(",
"self",
")",
":",
"settings_dict",
"=",
"settings",
".",
"DATABASES",
"[",
"self",
".",
"connection",
".",
"alias",
"]",
"user",
"=",
"settings_dict",
".",
"get",
"(",
"'SAVED_USER'",
")",
"or",
"settings_dict",
"[",
"'USER'... | [
14,
4
] | [
27,
74
] | python | en | ['en', 'error', 'th'] | False |
DatabaseCreation._switch_to_test_user | (self, parameters) |
Switch to the user that's used for creating the test database.
Oracle doesn't have the concept of separate databases under the same
user, so a separate user is used; see _create_test_db(). The main user
is also needed for cleanup when testing is completed, so save its
credentia... |
Switch to the user that's used for creating the test database. | def _switch_to_test_user(self, parameters):
"""
Switch to the user that's used for creating the test database.
Oracle doesn't have the concept of separate databases under the same
user, so a separate user is used; see _create_test_db(). The main user
is also needed for cleanup w... | [
"def",
"_switch_to_test_user",
"(",
"self",
",",
"parameters",
")",
":",
"real_settings",
"=",
"settings",
".",
"DATABASES",
"[",
"self",
".",
"connection",
".",
"alias",
"]",
"real_settings",
"[",
"'SAVED_USER'",
"]",
"=",
"self",
".",
"connection",
".",
"s... | [
101,
4
] | [
119,
102
] | python | en | ['en', 'error', 'th'] | False |
DatabaseCreation.set_as_test_mirror | (self, primary_settings_dict) |
Set this database up to be used in testing as a mirror of a primary
database whose settings are given.
|
Set this database up to be used in testing as a mirror of a primary
database whose settings are given.
| def set_as_test_mirror(self, primary_settings_dict):
"""
Set this database up to be used in testing as a mirror of a primary
database whose settings are given.
"""
self.connection.settings_dict['USER'] = primary_settings_dict['USER']
self.connection.settings_dict['PASSWOR... | [
"def",
"set_as_test_mirror",
"(",
"self",
",",
"primary_settings_dict",
")",
":",
"self",
".",
"connection",
".",
"settings_dict",
"[",
"'USER'",
"]",
"=",
"primary_settings_dict",
"[",
"'USER'",
"]",
"self",
".",
"connection",
".",
"settings_dict",
"[",
"'PASSW... | [
121,
4
] | [
127,
85
] | python | en | ['en', 'error', 'th'] | False |
DatabaseCreation._destroy_test_db | (self, test_database_name, verbosity=1) |
Destroy a test database, prompting the user for confirmation if the
database already exists. Return the name of the test database created.
|
Destroy a test database, prompting the user for confirmation if the
database already exists. Return the name of the test database created.
| def _destroy_test_db(self, test_database_name, verbosity=1):
"""
Destroy a test database, prompting the user for confirmation if the
database already exists. Return the name of the test database created.
"""
self.connection.settings_dict['USER'] = self.connection.settings_dict['S... | [
"def",
"_destroy_test_db",
"(",
"self",
",",
"test_database_name",
",",
"verbosity",
"=",
"1",
")",
":",
"self",
".",
"connection",
".",
"settings_dict",
"[",
"'USER'",
"]",
"=",
"self",
".",
"connection",
".",
"settings_dict",
"[",
"'SAVED_USER'",
"]",
"sel... | [
166,
4
] | [
184,
39
] | python | en | ['en', 'error', 'th'] | False |
DatabaseCreation._execute_allow_fail_statements | (self, cursor, statements, parameters, verbosity, acceptable_ora_err) |
Execute statements which are allowed to fail silently if the Oracle
error code given by `acceptable_ora_err` is raised. Return True if the
statements execute without an exception, or False otherwise.
|
Execute statements which are allowed to fail silently if the Oracle
error code given by `acceptable_ora_err` is raised. Return True if the
statements execute without an exception, or False otherwise.
| def _execute_allow_fail_statements(self, cursor, statements, parameters, verbosity, acceptable_ora_err):
"""
Execute statements which are allowed to fail silently if the Oracle
error code given by `acceptable_ora_err` is raised. Return True if the
statements execute without an exception,... | [
"def",
"_execute_allow_fail_statements",
"(",
"self",
",",
"cursor",
",",
"statements",
",",
"parameters",
",",
"verbosity",
",",
"acceptable_ora_err",
")",
":",
"try",
":",
"# Statement can fail when acceptable_ora_err is not None",
"allow_quiet_fail",
"=",
"acceptable_ora... | [
282,
4
] | [
297,
24
] | python | en | ['en', 'error', 'th'] | False |
DatabaseCreation._test_settings_get | (self, key, default=None, prefixed=None) |
Return a value from the test settings dict, or a given default, or a
prefixed entry from the main settings dict.
|
Return a value from the test settings dict, or a given default, or a
prefixed entry from the main settings dict.
| def _test_settings_get(self, key, default=None, prefixed=None):
"""
Return a value from the test settings dict, or a given default, or a
prefixed entry from the main settings dict.
"""
settings_dict = self.connection.settings_dict
val = settings_dict['TEST'].get(key, defa... | [
"def",
"_test_settings_get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"prefixed",
"=",
"None",
")",
":",
"settings_dict",
"=",
"self",
".",
"connection",
".",
"settings_dict",
"val",
"=",
"settings_dict",
"[",
"'TEST'",
"]",
".",
"get",
... | [
316,
4
] | [
325,
18
] | python | en | ['en', 'error', 'th'] | False |
DatabaseCreation._get_test_db_name | (self) |
Return the 'production' DB name to get the test DB creation machinery
to work. This isn't a great deal in this case because DB names as
handled by Django don't have real counterparts in Oracle.
|
Return the 'production' DB name to get the test DB creation machinery
to work. This isn't a great deal in this case because DB names as
handled by Django don't have real counterparts in Oracle.
| def _get_test_db_name(self):
"""
Return the 'production' DB name to get the test DB creation machinery
to work. This isn't a great deal in this case because DB names as
handled by Django don't have real counterparts in Oracle.
"""
return self.connection.settings_dict['NAM... | [
"def",
"_get_test_db_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"connection",
".",
"settings_dict",
"[",
"'NAME'",
"]"
] | [
383,
4
] | [
389,
52
] | python | en | ['en', 'error', 'th'] | False |
page_not_found | (request, exception, template_name=ERROR_404_TEMPLATE_NAME) |
Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/'). It's
quoted to prevent a content injection attack.
exception
The message from the exception which triggered the 404 (... |
Default 404 handler. | def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME):
"""
Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/'). It's
quoted to prevent a content injection attack.
... | [
"def",
"page_not_found",
"(",
"request",
",",
"exception",
",",
"template_name",
"=",
"ERROR_404_TEMPLATE_NAME",
")",
":",
"exception_repr",
"=",
"exception",
".",
"__class__",
".",
"__name__",
"# Try to get an \"interesting\" exception message, if any (and not the ugly",
"# ... | [
30,
0
] | [
75,
64
] | python | en | ['en', 'error', 'th'] | False |
server_error | (request, template_name=ERROR_500_TEMPLATE_NAME) |
500 error handler.
Templates: :template:`500.html`
Context: None
|
500 error handler. | def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
"""
500 error handler.
Templates: :template:`500.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
if template_name != ERROR_500_TEMPLATE_NAME:
... | [
"def",
"server_error",
"(",
"request",
",",
"template_name",
"=",
"ERROR_500_TEMPLATE_NAME",
")",
":",
"try",
":",
"template",
"=",
"loader",
".",
"get_template",
"(",
"template_name",
")",
"except",
"TemplateDoesNotExist",
":",
"if",
"template_name",
"!=",
"ERROR... | [
79,
0
] | [
96,
53
] | python | en | ['en', 'error', 'th'] | False |
bad_request | (request, exception, template_name=ERROR_400_TEMPLATE_NAME) |
400 error handler.
Templates: :template:`400.html`
Context: None
|
400 error handler. | def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME):
"""
400 error handler.
Templates: :template:`400.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
if template_name != ERROR_400_TEMPLATE_NAME:
... | [
"def",
"bad_request",
"(",
"request",
",",
"exception",
",",
"template_name",
"=",
"ERROR_400_TEMPLATE_NAME",
")",
":",
"try",
":",
"template",
"=",
"loader",
".",
"get_template",
"(",
"template_name",
")",
"except",
"TemplateDoesNotExist",
":",
"if",
"template_na... | [
100,
0
] | [
118,
52
] | python | en | ['en', 'error', 'th'] | False |
permission_denied | (request, exception, template_name=ERROR_403_TEMPLATE_NAME) |
Permission denied (403) handler.
Templates: :template:`403.html`
Context: None
If the template does not exist, an Http403 response containing the text
"403 Forbidden" (as per RFC 7231) will be returned.
|
Permission denied (403) handler. | def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
"""
Permission denied (403) handler.
Templates: :template:`403.html`
Context: None
If the template does not exist, an Http403 response containing the text
"403 Forbidden" (as per RFC 7231) will be returned.
"... | [
"def",
"permission_denied",
"(",
"request",
",",
"exception",
",",
"template_name",
"=",
"ERROR_403_TEMPLATE_NAME",
")",
":",
"try",
":",
"template",
"=",
"loader",
".",
"get_template",
"(",
"template_name",
")",
"except",
"TemplateDoesNotExist",
":",
"if",
"templ... | [
125,
0
] | [
147,
5
] | python | en | ['en', 'error', 'th'] | False |
rehash | (path, blocksize=1 << 20) | Return (encoded_digest, length) for path using hashlib.sha256() | Return (encoded_digest, length) for path using hashlib.sha256() | def rehash(path, blocksize=1 << 20):
# type: (str, int) -> Tuple[str, str]
"""Return (encoded_digest, length) for path using hashlib.sha256()"""
h, length = hash_file(path, blocksize)
digest = 'sha256=' + urlsafe_b64encode(
h.digest()
).decode('latin1').rstrip('=')
# unicode/str python2 ... | [
"def",
"rehash",
"(",
"path",
",",
"blocksize",
"=",
"1",
"<<",
"20",
")",
":",
"# type: (str, int) -> Tuple[str, str]",
"h",
",",
"length",
"=",
"hash_file",
"(",
"path",
",",
"blocksize",
")",
"digest",
"=",
"'sha256='",
"+",
"urlsafe_b64encode",
"(",
"h",... | [
59,
0
] | [
67,
32
] | python | cy | ['da', 'cy', 'en'] | False |
csv_io_kwargs | (mode) | Return keyword arguments to properly open a CSV file
in the given mode.
| Return keyword arguments to properly open a CSV file
in the given mode.
| def csv_io_kwargs(mode):
# type: (str) -> Dict[str, Any]
"""Return keyword arguments to properly open a CSV file
in the given mode.
"""
if sys.version_info.major < 3:
return {'mode': '{}b'.format(mode)}
else:
return {'mode': mode, 'newline': ''} | [
"def",
"csv_io_kwargs",
"(",
"mode",
")",
":",
"# type: (str) -> Dict[str, Any]",
"if",
"sys",
".",
"version_info",
".",
"major",
"<",
"3",
":",
"return",
"{",
"'mode'",
":",
"'{}b'",
".",
"format",
"(",
"mode",
")",
"}",
"else",
":",
"return",
"{",
"'mo... | [
70,
0
] | [
78,
44
] | python | en | ['en', 'en', 'en'] | True |
fix_script | (path) | Replace #!python with #!/path/to/python
Return True if file was changed.
| Replace #!python with #!/path/to/python
Return True if file was changed.
| def fix_script(path):
# type: (str) -> Optional[bool]
"""Replace #!python with #!/path/to/python
Return True if file was changed.
"""
# XXX RECORD hashes will need to be updated
if os.path.isfile(path):
with open(path, 'rb') as script:
firstline = script.readline()
... | [
"def",
"fix_script",
"(",
"path",
")",
":",
"# type: (str) -> Optional[bool]",
"# XXX RECORD hashes will need to be updated",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"script",
":",
"fi... | [
81,
0
] | [
99,
15
] | python | en | ['en', 'lt', 'en'] | True |
message_about_scripts_not_on_PATH | (scripts) | Determine if any scripts are not on PATH and format a warning.
Returns a warning message if one or more scripts are not on PATH,
otherwise None.
| Determine if any scripts are not on PATH and format a warning.
Returns a warning message if one or more scripts are not on PATH,
otherwise None.
| def message_about_scripts_not_on_PATH(scripts):
# type: (Sequence[str]) -> Optional[str]
"""Determine if any scripts are not on PATH and format a warning.
Returns a warning message if one or more scripts are not on PATH,
otherwise None.
"""
if not scripts:
return None
# Group script... | [
"def",
"message_about_scripts_not_on_PATH",
"(",
"scripts",
")",
":",
"# type: (Sequence[str]) -> Optional[str]",
"if",
"not",
"scripts",
":",
"return",
"None",
"# Group scripts by the path they were installed in",
"grouped_by_dir",
"=",
"collections",
".",
"defaultdict",
"(",
... | [
142,
0
] | [
210,
31
] | python | en | ['en', 'en', 'en'] | True |
sorted_outrows | (outrows) | Return the given rows of a RECORD file in sorted order.
Each row is a 3-tuple (path, hash, size) and corresponds to a record of
a RECORD file (see PEP 376 and PEP 427 for details). For the rows
passed to this function, the size can be an integer as an int or string,
or the empty string.
| Return the given rows of a RECORD file in sorted order. | def sorted_outrows(outrows):
# type: (Iterable[InstalledCSVRow]) -> List[InstalledCSVRow]
"""Return the given rows of a RECORD file in sorted order.
Each row is a 3-tuple (path, hash, size) and corresponds to a record of
a RECORD file (see PEP 376 and PEP 427 for details). For the rows
passed to t... | [
"def",
"sorted_outrows",
"(",
"outrows",
")",
":",
"# type: (Iterable[InstalledCSVRow]) -> List[InstalledCSVRow]",
"# Normally, there should only be one row per path, in which case the",
"# second and third elements don't come into play when sorting.",
"# However, in cases in the wild where a path... | [
213,
0
] | [
230,
70
] | python | en | ['en', 'en', 'en'] | True |
get_csv_rows_for_installed | (
old_csv_rows, # type: Iterable[List[str]]
installed, # type: Dict[str, str]
changed, # type: Set[str]
generated, # type: List[str]
lib_dir, # type: str
) |
:param installed: A map from archive RECORD path to installation RECORD
path.
|
:param installed: A map from archive RECORD path to installation RECORD
path.
| def get_csv_rows_for_installed(
old_csv_rows, # type: Iterable[List[str]]
installed, # type: Dict[str, str]
changed, # type: Set[str]
generated, # type: List[str]
lib_dir, # type: str
):
# type: (...) -> List[InstalledCSVRow]
"""
:param installed: A map from archive RECORD path to i... | [
"def",
"get_csv_rows_for_installed",
"(",
"old_csv_rows",
",",
"# type: Iterable[List[str]]",
"installed",
",",
"# type: Dict[str, str]",
"changed",
",",
"# type: Set[str]",
"generated",
",",
"# type: List[str]",
"lib_dir",
",",
"# type: str",
")",
":",
"# type: (...) -> List... | [
233,
0
] | [
266,
25
] | python | en | ['en', 'error', 'th'] | False |
install_unpacked_wheel | (
name, # type: str
wheeldir, # type: str
wheel_zip, # type: ZipFile
scheme, # type: Scheme
req_description, # type: str
pycompile=True, # type: bool
warn_script_location=True, # type: bool
direct_url=None, # type: Optional[DirectUrl]
) | Install a wheel.
:param name: Name of the project to install
:param wheeldir: Base directory of the unpacked wheel
:param wheel_zip: open ZipFile for wheel being installed
:param scheme: Distutils scheme dictating the install directories
:param req_description: String used in place of the requireme... | Install a wheel. | def install_unpacked_wheel(
name, # type: str
wheeldir, # type: str
wheel_zip, # type: ZipFile
scheme, # type: Scheme
req_description, # type: str
pycompile=True, # type: bool
warn_script_location=True, # type: bool
direct_url=None, # type: Optional[DirectUrl]
):
# type: (...... | [
"def",
"install_unpacked_wheel",
"(",
"name",
",",
"# type: str",
"wheeldir",
",",
"# type: str",
"wheel_zip",
",",
"# type: ZipFile",
"scheme",
",",
"# type: Scheme",
"req_description",
",",
"# type: str",
"pycompile",
"=",
"True",
",",
"# type: bool",
"warn_script_loc... | [
287,
0
] | [
603,
46
] | python | en | ['en', 'cy', 'en'] | True |
model_loss | (y, model, mean=True) |
Define loss of TF graph
:param y: correct labels
:param model: output of the model
:param mean: boolean indicating whether should return mean of loss
or vector of losses for each input of the batch
:return: return mean of loss if True, otherwise return vector with per
... |
Define loss of TF graph
:param y: correct labels
:param model: output of the model
:param mean: boolean indicating whether should return mean of loss
or vector of losses for each input of the batch
:return: return mean of loss if True, otherwise return vector with per
... | def model_loss(y, model, mean=True):
"""
Define loss of TF graph
:param y: correct labels
:param model: output of the model
:param mean: boolean indicating whether should return mean of loss
or vector of losses for each input of the batch
:return: return mean of loss if True, ot... | [
"def",
"model_loss",
"(",
"y",
",",
"model",
",",
"mean",
"=",
"True",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This function is deprecated and will be removed on or after\"",
"\" 2019-04-05. Switch to cleverhans.train.train.\"",
")",
"op",
"=",
"model",
".",
"op",
... | [
27,
0
] | [
51,
14
] | python | en | ['en', 'error', 'th'] | False |
initialize_uninitialized_global_variables | (sess) |
Only initializes the variables of a TensorFlow session that were not
already initialized.
:param sess: the TensorFlow session
:return:
|
Only initializes the variables of a TensorFlow session that were not
already initialized.
:param sess: the TensorFlow session
:return:
| def initialize_uninitialized_global_variables(sess):
"""
Only initializes the variables of a TensorFlow session that were not
already initialized.
:param sess: the TensorFlow session
:return:
"""
# List all global variables
global_vars = tf.global_variables()
# Find initialized stat... | [
"def",
"initialize_uninitialized_global_variables",
"(",
"sess",
")",
":",
"# List all global variables",
"global_vars",
"=",
"tf",
".",
"global_variables",
"(",
")",
"# Find initialized status for all variables",
"is_var_init",
"=",
"[",
"tf",
".",
"is_variable_initialized",... | [
54,
0
] | [
75,
64
] | python | en | ['en', 'error', 'th'] | False |
train | (
sess,
loss,
x,
y,
X_train,
Y_train,
save=False,
init_all=False,
evaluate=None,
feed=None,
args=None,
rng=None,
var_list=None,
fprop_args=None,
optimizer=None,
) |
Train a TF graph.
This function is deprecated. Prefer cleverhans.train.train when possible.
cleverhans.train.train supports multiple GPUs but this function is still
needed to support legacy models that do not support calling fprop more
than once.
:param sess: TF session to use when training th... |
Train a TF graph.
This function is deprecated. Prefer cleverhans.train.train when possible.
cleverhans.train.train supports multiple GPUs but this function is still
needed to support legacy models that do not support calling fprop more
than once. | def train(
sess,
loss,
x,
y,
X_train,
Y_train,
save=False,
init_all=False,
evaluate=None,
feed=None,
args=None,
rng=None,
var_list=None,
fprop_args=None,
optimizer=None,
):
"""
Train a TF graph.
This function is deprecated. Prefer cleverhans.train.... | [
"def",
"train",
"(",
"sess",
",",
"loss",
",",
"x",
",",
"y",
",",
"X_train",
",",
"Y_train",
",",
"save",
"=",
"False",
",",
"init_all",
"=",
"False",
",",
"evaluate",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"args",
"=",
"None",
",",
"rng",
... | [
78,
0
] | [
216,
15
] | python | en | ['en', 'error', 'th'] | False |
model_eval | (sess, x, y, predictions, X_test=None, Y_test=None, feed=None, args=None) |
Compute the accuracy of a TF model on some data
:param sess: TF session to use
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:param X_test: numpy array with training inputs
:param Y_test: numpy array with training outputs
... |
Compute the accuracy of a TF model on some data
:param sess: TF session to use
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:param X_test: numpy array with training inputs
:param Y_test: numpy array with training outputs
... | def model_eval(sess, x, y, predictions, X_test=None, Y_test=None, feed=None, args=None):
"""
Compute the accuracy of a TF model on some data
:param sess: TF session to use
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:para... | [
"def",
"model_eval",
"(",
"sess",
",",
"x",
",",
"y",
",",
"predictions",
",",
"X_test",
"=",
"None",
",",
"Y_test",
"=",
"None",
",",
"feed",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"global",
"_model_eval_cache",
"args",
"=",
"_ArgsWrapper",
... | [
219,
0
] | [
287,
19
] | python | en | ['en', 'error', 'th'] | False |
tf_model_load | (sess, file_path=None) |
:param sess: the session object to restore
:param file_path: path to the restored session, if None is
taken from FLAGS.train_dir and FLAGS.filename
:return:
| def tf_model_load(sess, file_path=None):
"""
:param sess: the session object to restore
:param file_path: path to the restored session, if None is
taken from FLAGS.train_dir and FLAGS.filename
:return:
"""
with sess.as_default():
saver = tf.train.Saver()
if... | [
"def",
"tf_model_load",
"(",
"sess",
",",
"file_path",
"=",
"None",
")",
":",
"with",
"sess",
".",
"as_default",
"(",
")",
":",
"saver",
"=",
"tf",
".",
"train",
".",
"Saver",
"(",
")",
"if",
"file_path",
"is",
"None",
":",
"error",
"=",
"\"file_path... | [
293,
0
] | [
308,
15
] | python | en | ['en', 'error', 'th'] | False | |
batch_eval | (*args, **kwargs) |
Wrapper around deprecated function.
|
Wrapper around deprecated function.
| def batch_eval(*args, **kwargs):
"""
Wrapper around deprecated function.
"""
# Inside function to avoid circular import
from cleverhans.evaluation import batch_eval as new_batch_eval
warnings.warn(
"batch_eval has moved to cleverhans.evaluation. "
"batch_eval will be removed fro... | [
"def",
"batch_eval",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Inside function to avoid circular import",
"from",
"cleverhans",
".",
"evaluation",
"import",
"batch_eval",
"as",
"new_batch_eval",
"warnings",
".",
"warn",
"(",
"\"batch_eval has moved to cl... | [
311,
0
] | [
323,
42
] | python | en | ['en', 'error', 'th'] | False |
model_argmax | (sess, x, predictions, samples, feed=None) |
Helper function that computes the current class prediction
:param sess: TF session
:param x: the input placeholder
:param predictions: the model's symbolic output
:param samples: numpy array with input samples (dims must match x)
:param feed: An optional dictionary that is appended to the feedi... |
Helper function that computes the current class prediction
:param sess: TF session
:param x: the input placeholder
:param predictions: the model's symbolic output
:param samples: numpy array with input samples (dims must match x)
:param feed: An optional dictionary that is appended to the feedi... | def model_argmax(sess, x, predictions, samples, feed=None):
"""
Helper function that computes the current class prediction
:param sess: TF session
:param x: the input placeholder
:param predictions: the model's symbolic output
:param samples: numpy array with input samples (dims must match x)
... | [
"def",
"model_argmax",
"(",
"sess",
",",
"x",
",",
"predictions",
",",
"samples",
",",
"feed",
"=",
"None",
")",
":",
"feed_dict",
"=",
"{",
"x",
":",
"samples",
"}",
"if",
"feed",
"is",
"not",
"None",
":",
"feed_dict",
".",
"update",
"(",
"feed",
... | [
326,
0
] | [
346,
47
] | python | en | ['en', 'error', 'th'] | False |
l2_batch_normalize | (x, epsilon=1e-12, scope=None) |
Helper function to normalize a batch of vectors.
:param x: the input placeholder
:param epsilon: stabilizes division
:return: the batch of l2 normalized vector
|
Helper function to normalize a batch of vectors.
:param x: the input placeholder
:param epsilon: stabilizes division
:return: the batch of l2 normalized vector
| def l2_batch_normalize(x, epsilon=1e-12, scope=None):
"""
Helper function to normalize a batch of vectors.
:param x: the input placeholder
:param epsilon: stabilizes division
:return: the batch of l2 normalized vector
"""
with tf.name_scope(scope, "l2_batch_normalize") as name_scope:
... | [
"def",
"l2_batch_normalize",
"(",
"x",
",",
"epsilon",
"=",
"1e-12",
",",
"scope",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
",",
"\"l2_batch_normalize\"",
")",
"as",
"name_scope",
":",
"x_shape",
"=",
"tf",
".",
"shape",
"(",... | [
349,
0
] | [
363,
54
] | python | en | ['en', 'error', 'th'] | False |
kl_with_logits | (
p_logits, q_logits, scope=None, loss_collection=tf.GraphKeys.REGULARIZATION_LOSSES
) | Helper function to compute kl-divergence KL(p || q) | Helper function to compute kl-divergence KL(p || q) | def kl_with_logits(
p_logits, q_logits, scope=None, loss_collection=tf.GraphKeys.REGULARIZATION_LOSSES
):
"""Helper function to compute kl-divergence KL(p || q)"""
with tf.name_scope(scope, "kl_divergence") as name:
p = tf.nn.softmax(p_logits)
p_log = tf.nn.log_softmax(p_logits)
q_lo... | [
"def",
"kl_with_logits",
"(",
"p_logits",
",",
"q_logits",
",",
"scope",
"=",
"None",
",",
"loss_collection",
"=",
"tf",
".",
"GraphKeys",
".",
"REGULARIZATION_LOSSES",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
",",
"\"kl_divergence\"",
")",
"... | [
366,
0
] | [
376,
19
] | python | en | ['en', 'en', 'en'] | True |
clip_eta | (eta, ord, eps) |
Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation.
|
Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation.
| def clip_eta(eta, ord, eps):
"""
Helper function to clip the perturbation to epsilon norm ball.
:param eta: A tensor with the current perturbation.
:param ord: Order of the norm (mimics Numpy).
Possible values: np.inf, 1 or 2.
:param eps: Epsilon, bound of the perturbation.
"""
... | [
"def",
"clip_eta",
"(",
"eta",
",",
"ord",
",",
"eps",
")",
":",
"# Clipping perturbation eta to self.ord norm ball",
"if",
"ord",
"not",
"in",
"[",
"np",
".",
"inf",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"\"ord must be np.inf, 1, or 2.\"",... | [
379,
0
] | [
439,
14
] | python | en | ['en', 'error', 'th'] | False |
zero_out_clipped_grads | (grad, x, clip_min, clip_max) |
Helper function to erase entries in the gradient where the update would be
clipped.
:param grad: The gradient
:param x: The current input
:param clip_min: Minimum input component value
:param clip_max: Maximum input component value
|
Helper function to erase entries in the gradient where the update would be
clipped.
:param grad: The gradient
:param x: The current input
:param clip_min: Minimum input component value
:param clip_max: Maximum input component value
| def zero_out_clipped_grads(grad, x, clip_min, clip_max):
"""
Helper function to erase entries in the gradient where the update would be
clipped.
:param grad: The gradient
:param x: The current input
:param clip_min: Minimum input component value
:param clip_max: Maximum input component value... | [
"def",
"zero_out_clipped_grads",
"(",
"grad",
",",
"x",
",",
"clip_min",
",",
"clip_max",
")",
":",
"signed_grad",
"=",
"tf",
".",
"sign",
"(",
"grad",
")",
"# Find input components that lie at the boundary of the input range, and",
"# where the gradient points in the wrong... | [
442,
0
] | [
464,
15
] | python | en | ['en', 'error', 'th'] | False |
random_exponential | (shape, rate=1.0, dtype=tf.float32, seed=None) |
Helper function to sample from the exponential distribution, which is not
included in core TensorFlow.
:shape: shape of the sampled tensor.
:rate: (optional) rate parameter of the exponential distribution, defaults to 1.0.
:dtype: (optional) data type of the sempled tensor, defaults to tf.float32.... |
Helper function to sample from the exponential distribution, which is not
included in core TensorFlow. | def random_exponential(shape, rate=1.0, dtype=tf.float32, seed=None):
"""
Helper function to sample from the exponential distribution, which is not
included in core TensorFlow.
:shape: shape of the sampled tensor.
:rate: (optional) rate parameter of the exponential distribution, defaults to 1.0.
... | [
"def",
"random_exponential",
"(",
"shape",
",",
"rate",
"=",
"1.0",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"seed",
"=",
"None",
")",
":",
"return",
"tf",
".",
"random_gamma",
"(",
"shape",
",",
"alpha",
"=",
"1",
",",
"beta",
"=",
"1.0",
"/"... | [
467,
0
] | [
477,
83
] | python | en | ['en', 'error', 'th'] | False |
random_laplace | (shape, loc=0.0, scale=1.0, dtype=tf.float32, seed=None) |
Helper function to sample from the Laplace distribution, which is not
included in core TensorFlow.
:shape: shape of the sampled tensor.
:loc: (optional) mean of the laplace distribution, defaults to 0.0.
:scale: (optional) scale parameter of the laplace diustribution, defaults to 1.0.
:dtype: ... |
Helper function to sample from the Laplace distribution, which is not
included in core TensorFlow. | def random_laplace(shape, loc=0.0, scale=1.0, dtype=tf.float32, seed=None):
"""
Helper function to sample from the Laplace distribution, which is not
included in core TensorFlow.
:shape: shape of the sampled tensor.
:loc: (optional) mean of the laplace distribution, defaults to 0.0.
:scale: (op... | [
"def",
"random_laplace",
"(",
"shape",
",",
"loc",
"=",
"0.0",
",",
"scale",
"=",
"1.0",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"seed",
"=",
"None",
")",
":",
"z1",
"=",
"random_exponential",
"(",
"shape",
",",
"1.0",
"/",
"scale",
",",
"dty... | [
480,
0
] | [
493,
24
] | python | en | ['en', 'error', 'th'] | False |
random_lp_vector | (shape, ord, eps, dtype=tf.float32, seed=None) |
Helper function to generate uniformly random vectors from a norm ball of
radius epsilon.
:param shape: Output shape of the random sample. The shape is expected to be
of the form `(n, d1, d2, ..., dn)` where `n` is the number of
i.i.d. samples that will be drawn from a no... |
Helper function to generate uniformly random vectors from a norm ball of
radius epsilon.
:param shape: Output shape of the random sample. The shape is expected to be
of the form `(n, d1, d2, ..., dn)` where `n` is the number of
i.i.d. samples that will be drawn from a no... | def random_lp_vector(shape, ord, eps, dtype=tf.float32, seed=None):
"""
Helper function to generate uniformly random vectors from a norm ball of
radius epsilon.
:param shape: Output shape of the random sample. The shape is expected to be
of the form `(n, d1, d2, ..., dn)` where `n` is ... | [
"def",
"random_lp_vector",
"(",
"shape",
",",
"ord",
",",
"eps",
",",
"dtype",
"=",
"tf",
".",
"float32",
",",
"seed",
"=",
"None",
")",
":",
"if",
"ord",
"not",
"in",
"[",
"np",
".",
"inf",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
... | [
496,
0
] | [
543,
12
] | python | en | ['en', 'error', 'th'] | False |
model_train | (
sess,
x,
y,
predictions,
X_train,
Y_train,
save=False,
predictions_adv=None,
init_all=True,
evaluate=None,
feed=None,
args=None,
rng=None,
var_list=None,
) |
Train a TF graph
:param sess: TF session to use when training the graph
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:param X_train: numpy array with training inputs
:param Y_train: numpy array with training outputs
:... |
Train a TF graph
:param sess: TF session to use when training the graph
:param x: input placeholder
:param y: output placeholder (for labels)
:param predictions: model output predictions
:param X_train: numpy array with training inputs
:param Y_train: numpy array with training outputs
:... | def model_train(
sess,
x,
y,
predictions,
X_train,
Y_train,
save=False,
predictions_adv=None,
init_all=True,
evaluate=None,
feed=None,
args=None,
rng=None,
var_list=None,
):
"""
Train a TF graph
:param sess: TF session to use when training the graph
... | [
"def",
"model_train",
"(",
"sess",
",",
"x",
",",
"y",
",",
"predictions",
",",
"X_train",
",",
"Y_train",
",",
"save",
"=",
"False",
",",
"predictions_adv",
"=",
"None",
",",
"init_all",
"=",
"True",
",",
"evaluate",
"=",
"None",
",",
"feed",
"=",
"... | [
546,
0
] | [
668,
15
] | python | en | ['en', 'error', 'th'] | False |
infer_devices | (devices=None) |
Returns the list of devices that multi-replica code should use.
:param devices: list of string device names, e.g. ["/GPU:0"]
If the user specifies this, `infer_devices` checks that it is
valid, and then uses this user-specified list.
If the user does not specify this, infer_devices uses... |
Returns the list of devices that multi-replica code should use.
:param devices: list of string device names, e.g. ["/GPU:0"]
If the user specifies this, `infer_devices` checks that it is
valid, and then uses this user-specified list.
If the user does not specify this, infer_devices uses... | def infer_devices(devices=None):
"""
Returns the list of devices that multi-replica code should use.
:param devices: list of string device names, e.g. ["/GPU:0"]
If the user specifies this, `infer_devices` checks that it is
valid, and then uses this user-specified list.
If the user d... | [
"def",
"infer_devices",
"(",
"devices",
"=",
"None",
")",
":",
"if",
"devices",
"is",
"None",
":",
"devices",
"=",
"get_available_gpus",
"(",
")",
"if",
"len",
"(",
"devices",
")",
"==",
"0",
":",
"warnings",
".",
"warn",
"(",
"\"No GPUS, running on CPU\""... | [
671,
0
] | [
692,
18
] | python | en | ['en', 'error', 'th'] | False |
get_available_gpus | () |
Returns a list of string names of all available GPUs
|
Returns a list of string names of all available GPUs
| def get_available_gpus():
"""
Returns a list of string names of all available GPUs
"""
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == "GPU"] | [
"def",
"get_available_gpus",
"(",
")",
":",
"local_device_protos",
"=",
"device_lib",
".",
"list_local_devices",
"(",
")",
"return",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"local_device_protos",
"if",
"x",
".",
"device_type",
"==",
"\"GPU\"",
"]"
] | [
695,
0
] | [
700,
74
] | python | en | ['en', 'error', 'th'] | False |
silence | () |
Silences tensorflaw's default printed messages
|
Silences tensorflaw's default printed messages
| def silence():
"""
Silences tensorflaw's default printed messages
"""
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" | [
"def",
"silence",
"(",
")",
":",
"os",
".",
"environ",
"[",
"\"TF_CPP_MIN_LOG_LEVEL\"",
"]",
"=",
"\"3\""
] | [
703,
0
] | [
707,
44
] | python | en | ['en', 'error', 'th'] | False |
clip_by_value | (t, clip_value_min, clip_value_max, name=None) |
A wrapper for clip_by_value that casts the clipping range if needed.
|
A wrapper for clip_by_value that casts the clipping range if needed.
| def clip_by_value(t, clip_value_min, clip_value_max, name=None):
"""
A wrapper for clip_by_value that casts the clipping range if needed.
"""
def cast_clip(clip):
"""
Cast clipping range argument if needed.
"""
if t.dtype in (tf.float32, tf.float64):
if hasat... | [
"def",
"clip_by_value",
"(",
"t",
",",
"clip_value_min",
",",
"clip_value_max",
",",
"name",
"=",
"None",
")",
":",
"def",
"cast_clip",
"(",
"clip",
")",
":",
"\"\"\"\n Cast clipping range argument if needed.\n \"\"\"",
"if",
"t",
".",
"dtype",
"in",
... | [
710,
0
] | [
730,
68
] | python | en | ['en', 'error', 'th'] | False |
mul | (a, b) |
A wrapper around tf multiplication that does more automatic casting of
the input.
|
A wrapper around tf multiplication that does more automatic casting of
the input.
| def mul(a, b):
"""
A wrapper around tf multiplication that does more automatic casting of
the input.
"""
def multiply(a, b):
"""Multiplication"""
return a * b
return op_with_scalar_cast(a, b, multiply) | [
"def",
"mul",
"(",
"a",
",",
"b",
")",
":",
"def",
"multiply",
"(",
"a",
",",
"b",
")",
":",
"\"\"\"Multiplication\"\"\"",
"return",
"a",
"*",
"b",
"return",
"op_with_scalar_cast",
"(",
"a",
",",
"b",
",",
"multiply",
")"
] | [
733,
0
] | [
743,
46
] | python | en | ['en', 'error', 'th'] | False |
div | (a, b) |
A wrapper around tf division that does more automatic casting of
the input.
|
A wrapper around tf division that does more automatic casting of
the input.
| def div(a, b):
"""
A wrapper around tf division that does more automatic casting of
the input.
"""
def divide(a, b):
"""Division"""
return a / b
return op_with_scalar_cast(a, b, divide) | [
"def",
"div",
"(",
"a",
",",
"b",
")",
":",
"def",
"divide",
"(",
"a",
",",
"b",
")",
":",
"\"\"\"Division\"\"\"",
"return",
"a",
"/",
"b",
"return",
"op_with_scalar_cast",
"(",
"a",
",",
"b",
",",
"divide",
")"
] | [
746,
0
] | [
756,
44
] | python | en | ['en', 'error', 'th'] | False |
op_with_scalar_cast | (a, b, f) |
Builds the graph to compute f(a, b).
If only one of the two arguments is a scalar and the operation would
cause a type error without casting, casts the scalar to match the
tensor.
:param a: a tf-compatible array or scalar
:param b: a tf-compatible array or scalar
|
Builds the graph to compute f(a, b).
If only one of the two arguments is a scalar and the operation would
cause a type error without casting, casts the scalar to match the
tensor.
:param a: a tf-compatible array or scalar
:param b: a tf-compatible array or scalar
| def op_with_scalar_cast(a, b, f):
"""
Builds the graph to compute f(a, b).
If only one of the two arguments is a scalar and the operation would
cause a type error without casting, casts the scalar to match the
tensor.
:param a: a tf-compatible array or scalar
:param b: a tf-compatible array ... | [
"def",
"op_with_scalar_cast",
"(",
"a",
",",
"b",
",",
"f",
")",
":",
"try",
":",
"return",
"f",
"(",
"a",
",",
"b",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"pass",
"def",
"is_scalar",
"(",
"x",
")",
":",
"\"\"\"Return True if `... | [
759,
0
] | [
796,
18
] | python | en | ['en', 'error', 'th'] | False |
assert_less_equal | (*args, **kwargs) |
Wrapper for tf.assert_less_equal
Overrides tf.device so that the assert always goes on CPU.
The unwrapped version raises an exception if used with tf.device("/GPU:x").
|
Wrapper for tf.assert_less_equal
Overrides tf.device so that the assert always goes on CPU.
The unwrapped version raises an exception if used with tf.device("/GPU:x").
| def assert_less_equal(*args, **kwargs):
"""
Wrapper for tf.assert_less_equal
Overrides tf.device so that the assert always goes on CPU.
The unwrapped version raises an exception if used with tf.device("/GPU:x").
"""
with tf.device("/CPU:0"):
return tf.assert_less_equal(*args, **kwargs) | [
"def",
"assert_less_equal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"tf",
".",
"device",
"(",
"\"/CPU:0\"",
")",
":",
"return",
"tf",
".",
"assert_less_equal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
799,
0
] | [
806,
52
] | python | en | ['en', 'error', 'th'] | False |
assert_greater_equal | (*args, **kwargs) |
Wrapper for tf.assert_greater_equal.
Overrides tf.device so that the assert always goes on CPU.
The unwrapped version raises an exception if used with tf.device("/GPU:x").
|
Wrapper for tf.assert_greater_equal.
Overrides tf.device so that the assert always goes on CPU.
The unwrapped version raises an exception if used with tf.device("/GPU:x").
| def assert_greater_equal(*args, **kwargs):
"""
Wrapper for tf.assert_greater_equal.
Overrides tf.device so that the assert always goes on CPU.
The unwrapped version raises an exception if used with tf.device("/GPU:x").
"""
with tf.device("/CPU:0"):
return tf.assert_greater_equal(*args, *... | [
"def",
"assert_greater_equal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"tf",
".",
"device",
"(",
"\"/CPU:0\"",
")",
":",
"return",
"tf",
".",
"assert_greater_equal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
809,
0
] | [
816,
55
] | python | en | ['en', 'error', 'th'] | False |
assert_equal | (*args, **kwargs) |
Wrapper for tf.assert_equal.
Overrides tf.device so that the assert always goes on CPU.
The unwrapped version raises an exception if used with tf.device("/GPU:x").
|
Wrapper for tf.assert_equal.
Overrides tf.device so that the assert always goes on CPU.
The unwrapped version raises an exception if used with tf.device("/GPU:x").
| def assert_equal(*args, **kwargs):
"""
Wrapper for tf.assert_equal.
Overrides tf.device so that the assert always goes on CPU.
The unwrapped version raises an exception if used with tf.device("/GPU:x").
"""
with tf.device("/CPU:0"):
return tf.assert_equal(*args, **kwargs) | [
"def",
"assert_equal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"tf",
".",
"device",
"(",
"\"/CPU:0\"",
")",
":",
"return",
"tf",
".",
"assert_equal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
819,
0
] | [
826,
47
] | python | en | ['en', 'error', 'th'] | False |
jacobian_graph | (predictions, x, nb_classes) |
Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return:
|
Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return:
| def jacobian_graph(predictions, x, nb_classes):
"""
Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return:
"... | [
"def",
"jacobian_graph",
"(",
"predictions",
",",
"x",
",",
"nb_classes",
")",
":",
"# This function will return a list of TF gradients",
"list_derivatives",
"=",
"[",
"]",
"# Define the TF graph elements to compute our derivatives for each class",
"for",
"class_ind",
"in",
"xr... | [
829,
0
] | [
847,
27
] | python | en | ['en', 'error', 'th'] | False |
jacobian_augmentation | (
sess, x, X_sub_prev, Y_sub, grads, lmbda, aug_batch_size=512, feed=None
) |
Augment an adversary's substitute training set using the Jacobian
of a substitute model to generate new synthetic inputs.
See https://arxiv.org/abs/1602.02697 for more details.
See cleverhans_tutorials/mnist_blackbox.py for example use case
:param sess: TF session in which the substitute model is d... |
Augment an adversary's substitute training set using the Jacobian
of a substitute model to generate new synthetic inputs.
See https://arxiv.org/abs/1602.02697 for more details.
See cleverhans_tutorials/mnist_blackbox.py for example use case
:param sess: TF session in which the substitute model is d... | def jacobian_augmentation(
sess, x, X_sub_prev, Y_sub, grads, lmbda, aug_batch_size=512, feed=None
):
"""
Augment an adversary's substitute training set using the Jacobian
of a substitute model to generate new synthetic inputs.
See https://arxiv.org/abs/1602.02697 for more details.
See cleverhan... | [
"def",
"jacobian_augmentation",
"(",
"sess",
",",
"x",
",",
"X_sub_prev",
",",
"Y_sub",
",",
"grads",
",",
"lmbda",
",",
"aug_batch_size",
"=",
"512",
",",
"feed",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"x",
".",
"get_shape",
"(",
")",
")",
"==... | [
850,
0
] | [
902,
16
] | python | en | ['en', 'error', 'th'] | False |
_warn_keyword_parameter | (func_name, kwargs) |
Backwards-compatibility with Python 2.7 to allow treating 'warn' as keyword-only.
|
Backwards-compatibility with Python 2.7 to allow treating 'warn' as keyword-only.
| def _warn_keyword_parameter(func_name, kwargs):
# type: (str, Dict[str, bool]) -> bool
"""
Backwards-compatibility with Python 2.7 to allow treating 'warn' as keyword-only.
"""
if not kwargs:
return False
elif len(kwargs) > 1 or "warn" not in kwargs:
kwargs.pop("warn", None)
... | [
"def",
"_warn_keyword_parameter",
"(",
"func_name",
",",
"kwargs",
")",
":",
"# type: (str, Dict[str, bool]) -> bool",
"if",
"not",
"kwargs",
":",
"return",
"False",
"elif",
"len",
"(",
"kwargs",
")",
">",
"1",
"or",
"\"warn\"",
"not",
"in",
"kwargs",
":",
"kw... | [
119,
0
] | [
132,
25
] | python | en | ['en', 'error', 'th'] | False |
_abi3_applies | (python_version) |
Determine if the Python version supports abi3.
PEP 384 was first implemented in Python 3.2.
|
Determine if the Python version supports abi3. | def _abi3_applies(python_version):
# type: (PythonVersion) -> bool
"""
Determine if the Python version supports abi3.
PEP 384 was first implemented in Python 3.2.
"""
return len(python_version) > 1 and tuple(python_version) >= (3, 2) | [
"def",
"_abi3_applies",
"(",
"python_version",
")",
":",
"# type: (PythonVersion) -> bool",
"return",
"len",
"(",
"python_version",
")",
">",
"1",
"and",
"tuple",
"(",
"python_version",
")",
">=",
"(",
"3",
",",
"2",
")"
] | [
150,
0
] | [
157,
70
] | python | en | ['en', 'error', 'th'] | False |
cpython_tags | (
python_version=None, # type: Optional[PythonVersion]
abis=None, # type: Optional[Iterable[str]]
platforms=None, # type: Optional[Iterable[str]]
**kwargs # type: bool
) |
Yields the tags for a CPython interpreter.
The tags consist of:
- cp<python_version>-<abi>-<platform>
- cp<python_version>-abi3-<platform>
- cp<python_version>-none-<platform>
- cp<less than python_version>-abi3-<platform> # Older Python versions down to 3.2.
If python_version only speci... |
Yields the tags for a CPython interpreter. | def cpython_tags(
python_version=None, # type: Optional[PythonVersion]
abis=None, # type: Optional[Iterable[str]]
platforms=None, # type: Optional[Iterable[str]]
**kwargs # type: bool
):
# type: (...) -> Iterator[Tag]
"""
Yields the tags for a CPython interpreter.
The tags consist o... | [
"def",
"cpython_tags",
"(",
"python_version",
"=",
"None",
",",
"# type: Optional[PythonVersion]",
"abis",
"=",
"None",
",",
"# type: Optional[Iterable[str]]",
"platforms",
"=",
"None",
",",
"# type: Optional[Iterable[str]]",
"*",
"*",
"kwargs",
"# type: bool",
")",
":"... | [
197,
0
] | [
254,
57
] | python | en | ['en', 'error', 'th'] | False |
generic_tags | (
interpreter=None, # type: Optional[str]
abis=None, # type: Optional[Iterable[str]]
platforms=None, # type: Optional[Iterable[str]]
**kwargs # type: bool
) |
Yields the tags for a generic interpreter.
The tags consist of:
- <interpreter>-<abi>-<platform>
The "none" ABI will be added if it was not explicitly provided.
|
Yields the tags for a generic interpreter. | def generic_tags(
interpreter=None, # type: Optional[str]
abis=None, # type: Optional[Iterable[str]]
platforms=None, # type: Optional[Iterable[str]]
**kwargs # type: bool
):
# type: (...) -> Iterator[Tag]
"""
Yields the tags for a generic interpreter.
The tags consist of:
- <int... | [
"def",
"generic_tags",
"(",
"interpreter",
"=",
"None",
",",
"# type: Optional[str]",
"abis",
"=",
"None",
",",
"# type: Optional[Iterable[str]]",
"platforms",
"=",
"None",
",",
"# type: Optional[Iterable[str]]",
"*",
"*",
"kwargs",
"# type: bool",
")",
":",
"# type: ... | [
264,
0
] | [
292,
50
] | python | en | ['en', 'error', 'th'] | False |
_py_interpreter_range | (py_version) |
Yields Python versions in descending order.
After the latest version, the major-only version will be yielded, and then
all previous versions of that major version.
|
Yields Python versions in descending order. | def _py_interpreter_range(py_version):
# type: (PythonVersion) -> Iterator[str]
"""
Yields Python versions in descending order.
After the latest version, the major-only version will be yielded, and then
all previous versions of that major version.
"""
if len(py_version) > 1:
yield "... | [
"def",
"_py_interpreter_range",
"(",
"py_version",
")",
":",
"# type: (PythonVersion) -> Iterator[str]",
"if",
"len",
"(",
"py_version",
")",
">",
"1",
":",
"yield",
"\"py{version}\"",
".",
"format",
"(",
"version",
"=",
"_version_nodot",
"(",
"py_version",
"[",
"... | [
295,
0
] | [
308,
86
] | python | en | ['en', 'error', 'th'] | False |
compatible_tags | (
python_version=None, # type: Optional[PythonVersion]
interpreter=None, # type: Optional[str]
platforms=None, # type: Optional[Iterable[str]]
) |
Yields the sequence of tags that are compatible with a specific version of Python.
The tags consist of:
- py*-none-<platform>
- <interpreter>-none-any # ... if `interpreter` is provided.
- py*-none-any
|
Yields the sequence of tags that are compatible with a specific version of Python. | def compatible_tags(
python_version=None, # type: Optional[PythonVersion]
interpreter=None, # type: Optional[str]
platforms=None, # type: Optional[Iterable[str]]
):
# type: (...) -> Iterator[Tag]
"""
Yields the sequence of tags that are compatible with a specific version of Python.
The t... | [
"def",
"compatible_tags",
"(",
"python_version",
"=",
"None",
",",
"# type: Optional[PythonVersion]",
"interpreter",
"=",
"None",
",",
"# type: Optional[str]",
"platforms",
"=",
"None",
",",
"# type: Optional[Iterable[str]]",
")",
":",
"# type: (...) -> Iterator[Tag]",
"if"... | [
311,
0
] | [
334,
41
] | python | en | ['en', 'error', 'th'] | False |
mac_platforms | (version=None, arch=None) |
Yields the platform tags for a macOS system.
The `version` parameter is a two-item tuple specifying the macOS version to
generate platform tags for. The `arch` parameter is the CPU architecture to
generate platform tags for. Both parameters default to the appropriate value
for the current system.
... |
Yields the platform tags for a macOS system. | def mac_platforms(version=None, arch=None):
# type: (Optional[MacVersion], Optional[str]) -> Iterator[str]
"""
Yields the platform tags for a macOS system.
The `version` parameter is a two-item tuple specifying the macOS version to
generate platform tags for. The `arch` parameter is the CPU archite... | [
"def",
"mac_platforms",
"(",
"version",
"=",
"None",
",",
"arch",
"=",
"None",
")",
":",
"# type: (Optional[MacVersion], Optional[str]) -> Iterator[str]",
"version_str",
",",
"_",
",",
"cpu_arch",
"=",
"platform",
".",
"mac_ver",
"(",
")",
"# type: ignore",
"if",
... | [
376,
0
] | [
403,
13
] | python | en | ['en', 'error', 'th'] | False |
_glibc_version_string_confstr | () |
Primary implementation of glibc_version_string using os.confstr.
|
Primary implementation of glibc_version_string using os.confstr.
| def _glibc_version_string_confstr():
# type: () -> Optional[str]
"""
Primary implementation of glibc_version_string using os.confstr.
"""
# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
# to be broken or missing. This strategy is used in the standard library
# platf... | [
"def",
"_glibc_version_string_confstr",
"(",
")",
":",
"# type: () -> Optional[str]",
"# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely",
"# to be broken or missing. This strategy is used in the standard library",
"# platform module.",
"# https://github.com/python/cpython/... | [
427,
0
] | [
446,
18
] | python | en | ['en', 'error', 'th'] | False |
_glibc_version_string_ctypes | () |
Fallback implementation of glibc_version_string using ctypes.
|
Fallback implementation of glibc_version_string using ctypes.
| def _glibc_version_string_ctypes():
# type: () -> Optional[str]
"""
Fallback implementation of glibc_version_string using ctypes.
"""
try:
import ctypes
except ImportError:
return None
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
# manpage says, "... | [
"def",
"_glibc_version_string_ctypes",
"(",
")",
":",
"# type: () -> Optional[str]",
"try",
":",
"import",
"ctypes",
"except",
"ImportError",
":",
"return",
"None",
"# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen",
"# manpage says, \"If filename is NULL, then th... | [
449,
0
] | [
480,
22
] | python | en | ['en', 'error', 'th'] | False |
_platform_tags | () |
Provides the platform tags for this installation.
|
Provides the platform tags for this installation.
| def _platform_tags():
# type: () -> Iterator[str]
"""
Provides the platform tags for this installation.
"""
if platform.system() == "Darwin":
return mac_platforms()
elif platform.system() == "Linux":
return _linux_platforms()
else:
return _generic_platforms() | [
"def",
"_platform_tags",
"(",
")",
":",
"# type: () -> Iterator[str]",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"\"Darwin\"",
":",
"return",
"mac_platforms",
"(",
")",
"elif",
"platform",
".",
"system",
"(",
")",
"==",
"\"Linux\"",
":",
"return",
"_l... | [
670,
0
] | [
680,
35
] | python | en | ['en', 'error', 'th'] | False |
interpreter_name | () |
Returns the name of the running interpreter.
|
Returns the name of the running interpreter.
| def interpreter_name():
# type: () -> str
"""
Returns the name of the running interpreter.
"""
try:
name = sys.implementation.name # type: ignore
except AttributeError: # pragma: no cover
# Python 2.7 compatibility.
name = platform.python_implementation().lower()
re... | [
"def",
"interpreter_name",
"(",
")",
":",
"# type: () -> str",
"try",
":",
"name",
"=",
"sys",
".",
"implementation",
".",
"name",
"# type: ignore",
"except",
"AttributeError",
":",
"# pragma: no cover",
"# Python 2.7 compatibility.",
"name",
"=",
"platform",
".",
"... | [
683,
0
] | [
693,
52
] | python | en | ['en', 'error', 'th'] | False |
interpreter_version | (**kwargs) |
Returns the version of the running interpreter.
|
Returns the version of the running interpreter.
| def interpreter_version(**kwargs):
# type: (bool) -> str
"""
Returns the version of the running interpreter.
"""
warn = _warn_keyword_parameter("interpreter_version", kwargs)
version = _get_config_var("py_version_nodot", warn=warn)
if version:
version = str(version)
else:
... | [
"def",
"interpreter_version",
"(",
"*",
"*",
"kwargs",
")",
":",
"# type: (bool) -> str",
"warn",
"=",
"_warn_keyword_parameter",
"(",
"\"interpreter_version\"",
",",
"kwargs",
")",
"version",
"=",
"_get_config_var",
"(",
"\"py_version_nodot\"",
",",
"warn",
"=",
"w... | [
696,
0
] | [
707,
18
] | python | en | ['en', 'error', 'th'] | False |
sys_tags | (**kwargs) |
Returns the sequence of tag triples for the running interpreter.
The order of the sequence corresponds to priority order for the
interpreter, from most to least important.
|
Returns the sequence of tag triples for the running interpreter. | def sys_tags(**kwargs):
# type: (bool) -> Iterator[Tag]
"""
Returns the sequence of tag triples for the running interpreter.
The order of the sequence corresponds to priority order for the
interpreter, from most to least important.
"""
warn = _warn_keyword_parameter("sys_tags", kwargs)
... | [
"def",
"sys_tags",
"(",
"*",
"*",
"kwargs",
")",
":",
"# type: (bool) -> Iterator[Tag]",
"warn",
"=",
"_warn_keyword_parameter",
"(",
"\"sys_tags\"",
",",
"kwargs",
")",
"interp_name",
"=",
"interpreter_name",
"(",
")",
"if",
"interp_name",
"==",
"\"cp\"",
":",
... | [
719,
0
] | [
738,
17
] | python | en | ['en', 'error', 'th'] | False |
Node.__init__ | (self, children=None, connector=None, negated=False) | Construct a new Node. If no connector is given, use the default. | Construct a new Node. If no connector is given, use the default. | def __init__(self, children=None, connector=None, negated=False):
"""Construct a new Node. If no connector is given, use the default."""
self.children = children[:] if children else []
self.connector = connector or self.default
self.negated = negated | [
"def",
"__init__",
"(",
"self",
",",
"children",
"=",
"None",
",",
"connector",
"=",
"None",
",",
"negated",
"=",
"False",
")",
":",
"self",
".",
"children",
"=",
"children",
"[",
":",
"]",
"if",
"children",
"else",
"[",
"]",
"self",
".",
"connector"... | [
20,
4
] | [
24,
30
] | python | en | ['en', 'en', 'en'] | True |
Node._new_instance | (cls, children=None, connector=None, negated=False) |
Create a new instance of this class when new Nodes (or subclasses) are
needed in the internal code in this class. Normally, it just shadows
__init__(). However, subclasses with an __init__ signature that aren't
an extension of Node.__init__ might need to implement this method to
... |
Create a new instance of this class when new Nodes (or subclasses) are
needed in the internal code in this class. Normally, it just shadows
__init__(). However, subclasses with an __init__ signature that aren't
an extension of Node.__init__ might need to implement this method to
... | def _new_instance(cls, children=None, connector=None, negated=False):
"""
Create a new instance of this class when new Nodes (or subclasses) are
needed in the internal code in this class. Normally, it just shadows
__init__(). However, subclasses with an __init__ signature that aren't
... | [
"def",
"_new_instance",
"(",
"cls",
",",
"children",
"=",
"None",
",",
"connector",
"=",
"None",
",",
"negated",
"=",
"False",
")",
":",
"obj",
"=",
"Node",
"(",
"children",
",",
"connector",
",",
"negated",
")",
"obj",
".",
"__class__",
"=",
"cls",
... | [
29,
4
] | [
40,
18
] | python | en | ['en', 'error', 'th'] | False |
Node.__len__ | (self) | Return the number of children this node has. | Return the number of children this node has. | def __len__(self):
"""Return the number of children this node has."""
return len(self.children) | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"children",
")"
] | [
55,
4
] | [
57,
33
] | python | en | ['en', 'en', 'en'] | True |
Node.__bool__ | (self) | Return whether or not this node has children. | Return whether or not this node has children. | def __bool__(self):
"""Return whether or not this node has children."""
return bool(self.children) | [
"def",
"__bool__",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"children",
")"
] | [
59,
4
] | [
61,
34
] | python | en | ['en', 'en', 'en'] | True |
Node.__contains__ | (self, other) | Return True if 'other' is a direct child of this instance. | Return True if 'other' is a direct child of this instance. | def __contains__(self, other):
"""Return True if 'other' is a direct child of this instance."""
return other in self.children | [
"def",
"__contains__",
"(",
"self",
",",
"other",
")",
":",
"return",
"other",
"in",
"self",
".",
"children"
] | [
63,
4
] | [
65,
37
] | python | en | ['en', 'en', 'en'] | True |
Node.add | (self, data, conn_type, squash=True) |
Combine this tree and the data represented by data using the
connector conn_type. The combine is done by squashing the node other
away if possible.
This tree (self) will never be pushed to a child node of the
combined tree, nor will the connector or negated properties change.
... |
Combine this tree and the data represented by data using the
connector conn_type. The combine is done by squashing the node other
away if possible. | def add(self, data, conn_type, squash=True):
"""
Combine this tree and the data represented by data using the
connector conn_type. The combine is done by squashing the node other
away if possible.
This tree (self) will never be pushed to a child node of the
combined tree... | [
"def",
"add",
"(",
"self",
",",
"data",
",",
"conn_type",
",",
"squash",
"=",
"True",
")",
":",
"if",
"data",
"in",
"self",
".",
"children",
":",
"return",
"data",
"if",
"not",
"squash",
":",
"self",
".",
"children",
".",
"append",
"(",
"data",
")"... | [
77,
4
] | [
119,
23
] | python | en | ['en', 'error', 'th'] | False |
Node.negate | (self) | Negate the sense of the root connector. | Negate the sense of the root connector. | def negate(self):
"""Negate the sense of the root connector."""
self.negated = not self.negated | [
"def",
"negate",
"(",
"self",
")",
":",
"self",
".",
"negated",
"=",
"not",
"self",
".",
"negated"
] | [
121,
4
] | [
123,
39
] | python | en | ['en', 'en', 'en'] | True |
AbstractConnectionPool.__init__ | (self, minconn, maxconn, *args, **kwargs) | Initialize the connection pool.
New 'minconn' connections are created immediately calling 'connfunc'
with given parameters. The connection pool will support a maximum of
about 'maxconn' connections.
| Initialize the connection pool. | def __init__(self, minconn, maxconn, *args, **kwargs):
"""Initialize the connection pool.
New 'minconn' connections are created immediately calling 'connfunc'
with given parameters. The connection pool will support a maximum of
about 'maxconn' connections.
"""
self.minco... | [
"def",
"__init__",
"(",
"self",
",",
"minconn",
",",
"maxconn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"minconn",
"=",
"int",
"(",
"minconn",
")",
"self",
".",
"maxconn",
"=",
"int",
"(",
"maxconn",
")",
"self",
".",
"c... | [
38,
4
] | [
58,
27
] | python | en | ['en', 'en', 'en'] | True |
AbstractConnectionPool._connect | (self, key=None) | Create a new connection and assign it to 'key' if not None. | Create a new connection and assign it to 'key' if not None. | def _connect(self, key=None):
"""Create a new connection and assign it to 'key' if not None."""
conn = psycopg2.connect(*self._args, **self._kwargs)
if key is not None:
self._used[key] = conn
self._rused[id(conn)] = key
else:
self._pool.append(conn)
... | [
"def",
"_connect",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"conn",
"=",
"psycopg2",
".",
"connect",
"(",
"*",
"self",
".",
"_args",
",",
"*",
"*",
"self",
".",
"_kwargs",
")",
"if",
"key",
"is",
"not",
"None",
":",
"self",
".",
"_used",
... | [
60,
4
] | [
68,
19
] | python | en | ['en', 'en', 'en'] | True |
AbstractConnectionPool._getkey | (self) | Return a new unique key. | Return a new unique key. | def _getkey(self):
"""Return a new unique key."""
self._keys += 1
return self._keys | [
"def",
"_getkey",
"(",
"self",
")",
":",
"self",
".",
"_keys",
"+=",
"1",
"return",
"self",
".",
"_keys"
] | [
70,
4
] | [
73,
25
] | python | ca | ['fr', 'ca', 'en'] | False |
AbstractConnectionPool._getconn | (self, key=None) | Get a free connection and assign it to 'key' if not None. | Get a free connection and assign it to 'key' if not None. | def _getconn(self, key=None):
"""Get a free connection and assign it to 'key' if not None."""
if self.closed:
raise PoolError("connection pool is closed")
if key is None:
key = self._getkey()
if key in self._used:
return self._used[key]
if se... | [
"def",
"_getconn",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"PoolError",
"(",
"\"connection pool is closed\"",
")",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"self",
".",
"_getkey",
"(",
")",
"if",
... | [
75,
4
] | [
92,
37
] | python | en | ['en', 'en', 'en'] | True |
AbstractConnectionPool._putconn | (self, conn, key=None, close=False) | Put away a connection. | Put away a connection. | def _putconn(self, conn, key=None, close=False):
"""Put away a connection."""
if self.closed:
raise PoolError("connection pool is closed")
if key is None:
key = self._rused.get(id(conn))
if key is None:
raise PoolError("trying to put unkeyed c... | [
"def",
"_putconn",
"(",
"self",
",",
"conn",
",",
"key",
"=",
"None",
",",
"close",
"=",
"False",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"PoolError",
"(",
"\"connection pool is closed\"",
")",
"if",
"key",
"is",
"None",
":",
"key",
"=",
... | [
94,
4
] | [
127,
37
] | python | en | ['en', 'en', 'en'] | True |
AbstractConnectionPool._closeall | (self) | Close all connections.
Note that this can lead to some code fail badly when trying to use
an already closed connection. If you call .closeall() make sure
your code can deal with it.
| Close all connections. | def _closeall(self):
"""Close all connections.
Note that this can lead to some code fail badly when trying to use
an already closed connection. If you call .closeall() make sure
your code can deal with it.
"""
if self.closed:
raise PoolError("connection pool ... | [
"def",
"_closeall",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"PoolError",
"(",
"\"connection pool is closed\"",
")",
"for",
"conn",
"in",
"self",
".",
"_pool",
"+",
"list",
"(",
"self",
".",
"_used",
".",
"values",
"(",
")",
")... | [
129,
4
] | [
143,
26
] | python | en | ['en', 'en', 'en'] | True |
ThreadedConnectionPool.__init__ | (self, minconn, maxconn, *args, **kwargs) | Initialize the threading lock. | Initialize the threading lock. | def __init__(self, minconn, maxconn, *args, **kwargs):
"""Initialize the threading lock."""
import threading
AbstractConnectionPool.__init__(
self, minconn, maxconn, *args, **kwargs)
self._lock = threading.Lock() | [
"def",
"__init__",
"(",
"self",
",",
"minconn",
",",
"maxconn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"threading",
"AbstractConnectionPool",
".",
"__init__",
"(",
"self",
",",
"minconn",
",",
"maxconn",
",",
"*",
"args",
",",
"... | [
157,
4
] | [
162,
37
] | python | en | ['en', 'en', 'en'] | True |
ThreadedConnectionPool.getconn | (self, key=None) | Get a free connection and assign it to 'key' if not None. | Get a free connection and assign it to 'key' if not None. | def getconn(self, key=None):
"""Get a free connection and assign it to 'key' if not None."""
self._lock.acquire()
try:
return self._getconn(key)
finally:
self._lock.release() | [
"def",
"getconn",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"return",
"self",
".",
"_getconn",
"(",
"key",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | [
164,
4
] | [
170,
32
] | python | en | ['en', 'en', 'en'] | True |
ThreadedConnectionPool.putconn | (self, conn=None, key=None, close=False) | Put away an unused connection. | Put away an unused connection. | def putconn(self, conn=None, key=None, close=False):
"""Put away an unused connection."""
self._lock.acquire()
try:
self._putconn(conn, key, close)
finally:
self._lock.release() | [
"def",
"putconn",
"(",
"self",
",",
"conn",
"=",
"None",
",",
"key",
"=",
"None",
",",
"close",
"=",
"False",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_putconn",
"(",
"conn",
",",
"key",
",",
"close",
... | [
172,
4
] | [
178,
32
] | python | en | ['en', 'en', 'en'] | True |
ThreadedConnectionPool.closeall | (self) | Close all connections (even the one currently in use.) | Close all connections (even the one currently in use.) | def closeall(self):
"""Close all connections (even the one currently in use.)"""
self._lock.acquire()
try:
self._closeall()
finally:
self._lock.release() | [
"def",
"closeall",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_closeall",
"(",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | [
180,
4
] | [
186,
32
] | python | en | ['en', 'en', 'en'] | True |
SimpleTemplateResponse.__getstate__ | (self) |
Raise an exception if trying to pickle an unrendered response. Pickle
only rendered data, not the data used to construct the response.
|
Raise an exception if trying to pickle an unrendered response. Pickle
only rendered data, not the data used to construct the response.
| def __getstate__(self):
"""
Raise an exception if trying to pickle an unrendered response. Pickle
only rendered data, not the data used to construct the response.
"""
obj_dict = self.__dict__.copy()
if not self._is_rendered:
raise ContentNotRenderedError('The ... | [
"def",
"__getstate__",
"(",
"self",
")",
":",
"obj_dict",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"if",
"not",
"self",
".",
"_is_rendered",
":",
"raise",
"ContentNotRenderedError",
"(",
"'The response content must be '",
"'rendered before it can be pick... | [
44,
4
] | [
57,
23
] | python | en | ['en', 'error', 'th'] | False |
SimpleTemplateResponse.resolve_template | (self, template) | Accept a template object, path-to-template, or list of paths. | Accept a template object, path-to-template, or list of paths. | def resolve_template(self, template):
"""Accept a template object, path-to-template, or list of paths."""
if isinstance(template, (list, tuple)):
return select_template(template, using=self.using)
elif isinstance(template, str):
return get_template(template, using=self.us... | [
"def",
"resolve_template",
"(",
"self",
",",
"template",
")",
":",
"if",
"isinstance",
"(",
"template",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"select_template",
"(",
"template",
",",
"using",
"=",
"self",
".",
"using",
")",
"elif",
"... | [
59,
4
] | [
66,
27
] | python | en | ['en', 'en', 'en'] | True |
SimpleTemplateResponse.rendered_content | (self) | Return the freshly rendered content for the template and context
described by the TemplateResponse.
This *does not* set the final content of the response. To set the
response content, you must either call render(), or set the
content explicitly using the value of this property.
| Return the freshly rendered content for the template and context
described by the TemplateResponse. | def rendered_content(self):
"""Return the freshly rendered content for the template and context
described by the TemplateResponse.
This *does not* set the final content of the response. To set the
response content, you must either call render(), or set the
content explicitly usi... | [
"def",
"rendered_content",
"(",
"self",
")",
":",
"template",
"=",
"self",
".",
"resolve_template",
"(",
"self",
".",
"template_name",
")",
"context",
"=",
"self",
".",
"resolve_context",
"(",
"self",
".",
"context_data",
")",
"return",
"template",
".",
"ren... | [
72,
4
] | [
82,
54
] | python | en | ['en', 'en', 'en'] | True |
SimpleTemplateResponse.add_post_render_callback | (self, callback) | Add a new post-rendering callback.
If the response has already been rendered,
invoke the callback immediately.
| Add a new post-rendering callback. | def add_post_render_callback(self, callback):
"""Add a new post-rendering callback.
If the response has already been rendered,
invoke the callback immediately.
"""
if self._is_rendered:
callback(self)
else:
self._post_render_callbacks.append(callb... | [
"def",
"add_post_render_callback",
"(",
"self",
",",
"callback",
")",
":",
"if",
"self",
".",
"_is_rendered",
":",
"callback",
"(",
"self",
")",
"else",
":",
"self",
".",
"_post_render_callbacks",
".",
"append",
"(",
"callback",
")"
] | [
84,
4
] | [
93,
56
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.