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
PaymentProvider.initiate_payment
(self, order: Order)
Create a payment to the provider. Implement this in your subclass. Should return a URL to which the user is redirected to actually pay the order.
Create a payment to the provider.
def initiate_payment(self, order: Order) -> str: """Create a payment to the provider. Implement this in your subclass. Should return a URL to which the user is redirected to actually pay the order."""
[ "def", "initiate_payment", "(", "self", ",", "order", ":", "Order", ")", "->", "str", ":" ]
[ 19, 4 ]
[ 23, 51 ]
python
en
['en', 'en', 'en']
True
PaymentProvider.handle_success_request
(self)
Handle incoming payment success request from the payment provider. Implement this in your subclass. If everything goes smoothly, should redirect the client back to the UI return URL.
Handle incoming payment success request from the payment provider.
def handle_success_request(self) -> HttpResponse: """Handle incoming payment success request from the payment provider. Implement this in your subclass. If everything goes smoothly, should redirect the client back to the UI return URL.""" raise NotImplementedError
[ "def", "handle_success_request", "(", "self", ")", "->", "HttpResponse", ":", "raise", "NotImplementedError" ]
[ 25, 4 ]
[ 30, 33 ]
python
en
['en', 'en', 'en']
True
PaymentProvider.handle_failure_request
(self)
Handle incoming payment failure request from the payment provider. Override this in your subclass if you need to handle failure requests. When everything goes smoothly, should redirect the client back to the UI return URL.
Handle incoming payment failure request from the payment provider.
def handle_failure_request(self) -> HttpResponse: """Handle incoming payment failure request from the payment provider. Override this in your subclass if you need to handle failure requests. When everything goes smoothly, should redirect the client back to the UI return URL.""" ...
[ "def", "handle_failure_request", "(", "self", ")", "->", "HttpResponse", ":", "return", "HttpResponseNotFound", "(", ")" ]
[ 32, 4 ]
[ 38, 37 ]
python
en
['en', 'en', 'en']
True
PaymentProvider.handle_notify_request
(self)
Handle incoming notify request from the payment provider. Override this in your subclass if you need to handle notify requests.
Handle incoming notify request from the payment provider.
def handle_notify_request(self) -> HttpResponse: """Handle incoming notify request from the payment provider. Override this in your subclass if you need to handle notify requests.""" return HttpResponseNotFound()
[ "def", "handle_notify_request", "(", "self", ")", "->", "HttpResponse", ":", "return", "HttpResponseNotFound", "(", ")" ]
[ 40, 4 ]
[ 44, 37 ]
python
en
['en', 'en', 'en']
True
PaymentProvider.get_success_url
(self)
Create the full URL where user is redirected after a successful payment By default adds the UI return URL to the final URL as a query parameter. If the provider does not support that, you should use get_respa_success_url() instead, override extract_ui_return_url() and handle the UI retu...
Create the full URL where user is redirected after a successful payment
def get_success_url(self) -> str: """Create the full URL where user is redirected after a successful payment By default adds the UI return URL to the final URL as a query parameter. If the provider does not support that, you should use get_respa_success_url() instead, override extract_u...
[ "def", "get_success_url", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_get_final_return_url", "(", "self", ".", "get_respa_success_url", "(", ")", ")" ]
[ 46, 4 ]
[ 54, 71 ]
python
en
['en', 'en', 'en']
True
PaymentProvider.get_failure_url
(self)
Create the full URL where user is redirected after a failed payment By default adds the UI return URL to the final URL as a query parameter. If the provider does not support that, you should use get_respa_failure_url() instead, override extract_ui_return_url() and handle the UI return U...
Create the full URL where user is redirected after a failed payment
def get_failure_url(self) -> str: """Create the full URL where user is redirected after a failed payment By default adds the UI return URL to the final URL as a query parameter. If the provider does not support that, you should use get_respa_failure_url() instead, override extract_ui_re...
[ "def", "get_failure_url", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_get_final_return_url", "(", "self", ".", "get_respa_failure_url", "(", ")", ")" ]
[ 56, 4 ]
[ 64, 71 ]
python
en
['en', 'en', 'en']
True
PaymentProvider.extract_ui_return_url
(self)
Parse and return where client is redirected after payment has been registered Can be overriden in subclass if the provider does not support the added extra query parameters in the return URL redirect.
Parse and return where client is redirected after payment has been registered
def extract_ui_return_url(self) -> str: """Parse and return where client is redirected after payment has been registered Can be overriden in subclass if the provider does not support the added extra query parameters in the return URL redirect. """ return '' if not self.request e...
[ "def", "extract_ui_return_url", "(", "self", ")", "->", "str", ":", "return", "''", "if", "not", "self", ".", "request", "else", "self", ".", "request", ".", "GET", ".", "get", "(", "self", ".", "ui_return_url_param_name", ",", "''", ")" ]
[ 75, 4 ]
[ 81, 98 ]
python
en
['en', 'en', 'en']
True
PaymentProvider.ui_redirect_success
(self, order: Order = None)
Redirect back to UI after a successful payment This should be used after a successful payment instead of the standard Django redirect.
Redirect back to UI after a successful payment
def ui_redirect_success(self, order: Order = None) -> HttpResponse: """Redirect back to UI after a successful payment This should be used after a successful payment instead of the standard Django redirect. """ ui_return_url = self.extract_ui_return_url() if ui_return_url...
[ "def", "ui_redirect_success", "(", "self", ",", "order", ":", "Order", "=", "None", ")", "->", "HttpResponse", ":", "ui_return_url", "=", "self", ".", "extract_ui_return_url", "(", ")", "if", "ui_return_url", ":", "return", "self", ".", "_redirect_to_ui", "(",...
[ 83, 4 ]
[ 93, 96 ]
python
en
['en', 'en', 'en']
True
PaymentProvider.ui_redirect_failure
(self, order: Order = None)
Redirect back to UI after a failed payment This should be used after a failed payment instead of the standard Django redirect.
Redirect back to UI after a failed payment
def ui_redirect_failure(self, order: Order = None) -> HttpResponse: """Redirect back to UI after a failed payment This should be used after a failed payment instead of the standard Django redirect. """ ui_return_url = self.extract_ui_return_url() if ui_return_url: ...
[ "def", "ui_redirect_failure", "(", "self", ",", "order", ":", "Order", "=", "None", ")", "->", "HttpResponse", ":", "ui_return_url", "=", "self", ".", "extract_ui_return_url", "(", ")", "if", "ui_return_url", ":", "return", "self", ".", "_redirect_to_ui", "(",...
[ 95, 4 ]
[ 105, 103 ]
python
en
['en', 'en', 'en']
True
one_click_unsubscribe_link
(user_profile: UserProfile, email_type: str)
Generate a unique link that a logged-out user can visit to unsubscribe from Zulip e-mails without having to first log in.
Generate a unique link that a logged-out user can visit to unsubscribe from Zulip e-mails without having to first log in.
def one_click_unsubscribe_link(user_profile: UserProfile, email_type: str) -> str: """ Generate a unique link that a logged-out user can visit to unsubscribe from Zulip e-mails without having to first log in. """ return create_confirmation_link( user_profile, Confirmation.UNSUBSCRIBE, url_ar...
[ "def", "one_click_unsubscribe_link", "(", "user_profile", ":", "UserProfile", ",", "email_type", ":", "str", ")", "->", "str", ":", "return", "create_confirmation_link", "(", "user_profile", ",", "Confirmation", ".", "UNSUBSCRIBE", ",", "url_args", "=", "{", "\"em...
[ 162, 0 ]
[ 169, 5 ]
python
en
['en', 'error', 'th']
False
validate_key
(creation_key: Optional[str])
Get the record for this key, raising InvalidCreationKey if non-None but invalid.
Get the record for this key, raising InvalidCreationKey if non-None but invalid.
def validate_key(creation_key: Optional[str]) -> Optional["RealmCreationKey"]: """Get the record for this key, raising InvalidCreationKey if non-None but invalid.""" if creation_key is None: return None try: key_record = RealmCreationKey.objects.get(creation_key=creation_key) except Real...
[ "def", "validate_key", "(", "creation_key", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "\"RealmCreationKey\"", "]", ":", "if", "creation_key", "is", "None", ":", "return", "None", "try", ":", "key_record", "=", "RealmCreationKey", ".", "ob...
[ 181, 0 ]
[ 192, 21 ]
python
en
['en', 'en', 'en']
True
FormHmacTests.test_textfield_hash
(self)
Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas).
Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas).
def test_textfield_hash(self): """ Regression test for #10034: the hash generation function should ignore leading/trailing whitespace so as to be friendly to broken browsers that submit it (usually in textareas). """ f1 = HashTestForm({'name': 'joe', 'bio': 'Speaking espa...
[ "def", "test_textfield_hash", "(", "self", ")", ":", "f1", "=", "HashTestForm", "(", "{", "'name'", ":", "'joe'", ",", "'bio'", ":", "'Speaking español.'}", ")", "", "f2", "=", "HashTestForm", "(", "{", "'name'", ":", "' joe'", ",", "'bio'", ":", "'Spea...
[ 163, 4 ]
[ 173, 38 ]
python
en
['en', 'error', 'th']
False
FormHmacTests.test_empty_permitted
(self)
Regression test for #10643: the security hash should allow forms with empty_permitted = True, or forms where data has not changed.
Regression test for #10643: the security hash should allow forms with empty_permitted = True, or forms where data has not changed.
def test_empty_permitted(self): """ Regression test for #10643: the security hash should allow forms with empty_permitted = True, or forms where data has not changed. """ f1 = HashTestBlankForm({}) f2 = HashTestForm({}, empty_permitted=True) hash1 = utils.form_hma...
[ "def", "test_empty_permitted", "(", "self", ")", ":", "f1", "=", "HashTestBlankForm", "(", "{", "}", ")", "f2", "=", "HashTestForm", "(", "{", "}", ",", "empty_permitted", "=", "True", ")", "hash1", "=", "utils", ".", "form_hmac", "(", "f1", ")", "hash...
[ 175, 4 ]
[ 184, 38 ]
python
en
['en', 'error', 'th']
False
get_field_size
(name)
Extract the size number from a "varchar(11)" type name
Extract the size number from a "varchar(11)" type name
def get_field_size(name): """ Extract the size number from a "varchar(11)" type name """ m = field_size_re.search(name) return int(m.group(1)) if m else None
[ "def", "get_field_size", "(", "name", ")", ":", "m", "=", "field_size_re", ".", "search", "(", "name", ")", "return", "int", "(", "m", ".", "group", "(", "1", ")", ")", "if", "m", "else", "None" ]
[ 8, 0 ]
[ 11, 41 ]
python
en
['en', 'en', 'en']
True
DatabaseIntrospection.get_table_list
(self, cursor)
Returns a list of table and view names in the current database.
Returns a list of table and view names in the current database.
def get_table_list(self, cursor): """ Returns a list of table and view names in the current database. """ # Skip the sqlite_sequence system table used for autoincrement key # generation. cursor.execute(""" SELECT name, type FROM sqlite_master WHERE...
[ "def", "get_table_list", "(", "self", ",", "cursor", ")", ":", "# Skip the sqlite_sequence system table used for autoincrement key", "# generation.", "cursor", ".", "execute", "(", "\"\"\"\n SELECT name, type FROM sqlite_master\n WHERE type in ('table', 'view') AND ...
[ 55, 4 ]
[ 65, 74 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_table_description
(self, cursor, table_name)
Returns a description of the table, with the DB-API cursor.description interface.
Returns a description of the table, with the DB-API cursor.description interface.
def get_table_description(self, cursor, table_name): "Returns a description of the table, with the DB-API cursor.description interface." return [FieldInfo(info['name'], info['type'], None, info['size'], None, None, info['null_ok']) for info in self._table_info(cursor, table_name)]
[ "def", "get_table_description", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "return", "[", "FieldInfo", "(", "info", "[", "'name'", "]", ",", "info", "[", "'type'", "]", ",", "None", ",", "info", "[", "'size'", "]", ",", "None", ",", "No...
[ 67, 4 ]
[ 70, 83 ]
python
en
['en', 'fr', 'en']
True
DatabaseIntrospection.column_name_converter
(self, name)
SQLite will in some cases, e.g. when returning columns from views and subselects, return column names in 'alias."column"' format instead of simply 'column'. Affects SQLite < 3.7.15, fixed by http://www.sqlite.org/src/info/5526e0aa3c
SQLite will in some cases, e.g. when returning columns from views and subselects, return column names in 'alias."column"' format instead of simply 'column'.
def column_name_converter(self, name): """ SQLite will in some cases, e.g. when returning columns from views and subselects, return column names in 'alias."column"' format instead of simply 'column'. Affects SQLite < 3.7.15, fixed by http://www.sqlite.org/src/info/5526e0aa3c ...
[ "def", "column_name_converter", "(", "self", ",", "name", ")", ":", "# TODO: remove when SQLite < 3.7.15 is sufficiently old.", "# 3.7.13 ships in Debian stable as of 2014-03-21.", "if", "self", ".", "connection", ".", "Database", ".", "sqlite_version_info", "<", "(", "3", ...
[ 72, 4 ]
[ 85, 23 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_relations
(self, cursor, table_name)
Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based.
Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based.
def get_relations(self, cursor, table_name): """ Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based. """ # Dictionary of relations to return relations = {} # Schema...
[ "def", "get_relations", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "# Dictionary of relations to return", "relations", "=", "{", "}", "# Schema for this table", "cursor", ".", "execute", "(", "\"SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s\"",...
[ 87, 4 ]
[ 135, 24 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_key_columns
(self, cursor, table_name)
Returns a list of (column_name, referenced_table_name, referenced_column_name) for all key columns in given table.
Returns a list of (column_name, referenced_table_name, referenced_column_name) for all key columns in given table.
def get_key_columns(self, cursor, table_name): """ Returns a list of (column_name, referenced_table_name, referenced_column_name) for all key columns in given table. """ key_columns = [] # Schema for this table cursor.execute("SELECT sql FROM sqlite_master WHERE ...
[ "def", "get_key_columns", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "key_columns", "=", "[", "]", "# Schema for this table", "cursor", ".", "execute", "(", "\"SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s\"", ",", "[", "table_name", ",",...
[ 137, 4 ]
[ 164, 26 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_primary_key_column
(self, cursor, table_name)
Get the column name of the primary key for the given table.
Get the column name of the primary key for the given table.
def get_primary_key_column(self, cursor, table_name): """ Get the column name of the primary key for the given table. """ # Don't use PRAGMA because that causes issues with some transactions cursor.execute("SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s", [table_...
[ "def", "get_primary_key_column", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "# Don't use PRAGMA because that causes issues with some transactions", "cursor", ".", "execute", "(", "\"SELECT sql FROM sqlite_master WHERE tbl_name = %s AND type = %s\"", ",", "[", "table...
[ 185, 4 ]
[ 201, 19 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_constraints
(self, cursor, table_name)
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
def get_constraints(self, cursor, table_name): """ Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Get the index info cursor.execute("PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name)) ...
[ "def", "get_constraints", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "constraints", "=", "{", "}", "# Get the index info", "cursor", ".", "execute", "(", "\"PRAGMA index_list(%s)\"", "%", "self", ".", "connection", ".", "ops", ".", "quote_name", ...
[ 213, 4 ]
[ 249, 26 ]
python
en
['en', 'error', 'th']
False
NullFkOrderingTests.test_ordering_across_null_fk
(self)
Regression test for #7512 ordering across nullable Foreign Keys shouldn't exclude results
Regression test for #7512
def test_ordering_across_null_fk(self): """ Regression test for #7512 ordering across nullable Foreign Keys shouldn't exclude results """ author_1 = Author.objects.create(name='Tom Jones') author_2 = Author.objects.create(name='Bob Smith') Article.objects.create(...
[ "def", "test_ordering_across_null_fk", "(", "self", ")", ":", "author_1", "=", "Author", ".", "objects", ".", "create", "(", "name", "=", "'Tom Jones'", ")", "author_2", "=", "Author", ".", "objects", ".", "create", "(", "name", "=", "'Bob Smith'", ")", "A...
[ 9, 4 ]
[ 41, 62 ]
python
en
['en', 'error', 'th']
False
InitialSQLTests.test_initial_sql
(self)
As pointed out by #14661, test data loaded by custom SQL can't be relied upon; as a result, the test framework flushes the data contents before every test. This test validates that this has occurred.
As pointed out by #14661, test data loaded by custom SQL can't be relied upon; as a result, the test framework flushes the data contents before every test. This test validates that this has occurred.
def test_initial_sql(self): """ As pointed out by #14661, test data loaded by custom SQL can't be relied upon; as a result, the test framework flushes the data contents before every test. This test validates that this has occurred. """ self.assertEqual(Simple.obje...
[ "def", "test_initial_sql", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "Simple", ".", "objects", ".", "count", "(", ")", ",", "0", ")" ]
[ 14, 4 ]
[ 21, 51 ]
python
en
['en', 'error', 'th']
False
InitialSQLTests.test_custom_sql
(self)
Simulate the custom SQL loading by migrate.
Simulate the custom SQL loading by migrate.
def test_custom_sql(self): """ Simulate the custom SQL loading by migrate. """ connection = connections[DEFAULT_DB_ALIAS] custom_sql = custom_sql_for_model(Simple, no_style(), connection) with connection.cursor() as cursor: for sql in custom_sql: ...
[ "def", "test_custom_sql", "(", "self", ")", ":", "connection", "=", "connections", "[", "DEFAULT_DB_ALIAS", "]", "custom_sql", "=", "custom_sql_for_model", "(", "Simple", ",", "no_style", "(", ")", ",", "connection", ")", "with", "connection", ".", "cursor", "...
[ 23, 4 ]
[ 36, 9 ]
python
en
['en', 'error', 'th']
False
InitialSQLTests.test_custom_sql_debug
(self)
Same test, ensure that CursorDebugWrapper doesn't alter sql loading (#3485).
Same test, ensure that CursorDebugWrapper doesn't alter sql loading (#3485).
def test_custom_sql_debug(self): """ Same test, ensure that CursorDebugWrapper doesn't alter sql loading (#3485). """ self.test_custom_sql()
[ "def", "test_custom_sql_debug", "(", "self", ")", ":", "self", ".", "test_custom_sql", "(", ")" ]
[ 39, 4 ]
[ 44, 30 ]
python
en
['en', 'error', 'th']
False
xor_hex_strings
(bytes_a: str, bytes_b: str)
Given two hex strings of equal length, return a hex string with the bitwise xor of the two hex strings.
Given two hex strings of equal length, return a hex string with the bitwise xor of the two hex strings.
def xor_hex_strings(bytes_a: str, bytes_b: str) -> str: """Given two hex strings of equal length, return a hex string with the bitwise xor of the two hex strings.""" assert len(bytes_a) == len(bytes_b) return "".join(f"{int(x, 16) ^ int(y, 16):x}" for x, y in zip(bytes_a, bytes_b))
[ "def", "xor_hex_strings", "(", "bytes_a", ":", "str", ",", "bytes_b", ":", "str", ")", "->", "str", ":", "assert", "len", "(", "bytes_a", ")", "==", "len", "(", "bytes_b", ")", "return", "\"\"", ".", "join", "(", "f\"{int(x, 16) ^ int(y, 16):x}\"", "for", ...
[ 13, 0 ]
[ 17, 84 ]
python
en
['en', 'en', 'en']
True
ascii_to_hex
(input_string: str)
Given an ascii string, encode it as a hex string
Given an ascii string, encode it as a hex string
def ascii_to_hex(input_string: str) -> str: """Given an ascii string, encode it as a hex string""" return input_string.encode().hex()
[ "def", "ascii_to_hex", "(", "input_string", ":", "str", ")", "->", "str", ":", "return", "input_string", ".", "encode", "(", ")", ".", "hex", "(", ")" ]
[ 20, 0 ]
[ 22, 38 ]
python
en
['en', 'en', 'en']
True
hex_to_ascii
(input_string: str)
Given a hex array, decode it back to a string
Given a hex array, decode it back to a string
def hex_to_ascii(input_string: str) -> str: """Given a hex array, decode it back to a string""" return bytes.fromhex(input_string).decode()
[ "def", "hex_to_ascii", "(", "input_string", ":", "str", ")", "->", "str", ":", "return", "bytes", ".", "fromhex", "(", "input_string", ")", ".", "decode", "(", ")" ]
[ 25, 0 ]
[ 27, 47 ]
python
en
['en', 'en', 'en']
True
version_lt
(ver1: str, ver2: str)
Compare two Zulip-style version strings. Versions are dot-separated sequences of decimal integers, followed by arbitrary trailing decoration. Comparison is lexicographic on the integer sequences, and refuses to guess how any trailing decoration compares to any other, to further numerals, or t...
Compare two Zulip-style version strings.
def version_lt(ver1: str, ver2: str) -> Optional[bool]: """ Compare two Zulip-style version strings. Versions are dot-separated sequences of decimal integers, followed by arbitrary trailing decoration. Comparison is lexicographic on the integer sequences, and refuses to guess how any trailing ...
[ "def", "version_lt", "(", "ver1", ":", "str", ",", "ver2", ":", "str", ")", "->", "Optional", "[", "bool", "]", ":", "num1", ",", "rest1", "=", "pop_numerals", "(", "ver1", ")", "num2", ",", "rest2", "=", "pop_numerals", "(", "ver2", ")", "if", "no...
[ 21, 0 ]
[ 60, 15 ]
python
en
['en', 'error', 'th']
False
DatabaseWrapper.check_constraints
(self, table_names=None)
Check constraints by setting them to immediate. Return them to deferred afterward.
Check constraints by setting them to immediate. Return them to deferred afterward.
def check_constraints(self, table_names=None): """ Check constraints by setting them to immediate. Return them to deferred afterward. """ self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE') self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
[ "def", "check_constraints", "(", "self", ",", "table_names", "=", "None", ")", ":", "self", ".", "cursor", "(", ")", ".", "execute", "(", "'SET CONSTRAINTS ALL IMMEDIATE'", ")", "self", ".", "cursor", "(", ")", ".", "execute", "(", "'SET CONSTRAINTS ALL DEFERR...
[ 296, 4 ]
[ 302, 61 ]
python
en
['en', 'error', 'th']
False
FormatStylePlaceholderCursor._output_type_handler
(cursor, name, defaultType, length, precision, scale)
Called for each db column fetched from cursors. Return numbers as the appropriate Python type.
Called for each db column fetched from cursors. Return numbers as the appropriate Python type.
def _output_type_handler(cursor, name, defaultType, length, precision, scale): """ Called for each db column fetched from cursors. Return numbers as the appropriate Python type. """ if defaultType == Database.NUMBER: if scale == -127: if precision == 0...
[ "def", "_output_type_handler", "(", "cursor", ",", "name", ",", "defaultType", ",", "length", ",", "precision", ",", "scale", ")", ":", "if", "defaultType", "==", "Database", ".", "NUMBER", ":", "if", "scale", "==", "-", "127", ":", "if", "precision", "=...
[ 417, 4 ]
[ 447, 13 ]
python
en
['en', 'error', 'th']
False
_py_interpreter_range
(py_version)
Yield Python versions in descending order. After the latest version, the major-only version will be yielded, and then all following versions up to 'end'.
Yield Python versions in descending order.
def _py_interpreter_range(py_version): """ Yield Python versions in descending order. After the latest version, the major-only version will be yielded, and then all following versions up to 'end'. """ yield "py{major}{minor}".format(major=py_version[0], minor=py_version[1]) yield "py{major}...
[ "def", "_py_interpreter_range", "(", "py_version", ")", ":", "yield", "\"py{major}{minor}\"", ".", "format", "(", "major", "=", "py_version", "[", "0", "]", ",", "minor", "=", "py_version", "[", "1", "]", ")", "yield", "\"py{major}\"", ".", "format", "(", ...
[ 175, 0 ]
[ 185, 73 ]
python
en
['en', 'error', 'th']
False
_independent_tags
(interpreter, py_version, platforms)
Return the sequence of tags that are consistent across implementations. The tags consist of: - py*-none-<platform> - <interpreter>-none-any - py*-none-any
Return the sequence of tags that are consistent across implementations.
def _independent_tags(interpreter, py_version, platforms): """ Return the sequence of tags that are consistent across implementations. The tags consist of: - py*-none-<platform> - <interpreter>-none-any - py*-none-any """ for version in _py_interpreter_range(py_version): for pla...
[ "def", "_independent_tags", "(", "interpreter", ",", "py_version", ",", "platforms", ")", ":", "for", "version", "in", "_py_interpreter_range", "(", "py_version", ")", ":", "for", "platform_", "in", "platforms", ":", "yield", "Tag", "(", "version", ",", "\"non...
[ 188, 0 ]
[ 202, 41 ]
python
en
['en', 'error', 'th']
False
sys_tags
()
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(): """ 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. """ py_version = sys.version_info[:2] interpreter_name = _interpreter_name() if platform.system...
[ "def", "sys_tags", "(", ")", ":", "py_version", "=", "sys", ".", "version_info", "[", ":", "2", "]", "interpreter_name", "=", "_interpreter_name", "(", ")", "if", "platform", ".", "system", "(", ")", "==", "\"Darwin\"", ":", "platforms", "=", "_mac_platfor...
[ 371, 0 ]
[ 403, 17 ]
python
en
['en', 'error', 'th']
False
MultiTableInheritanceProxyTest.test_model_subclass_proxy
(self)
Deleting an instance of a model proxying a multi-table inherited subclass should cascade delete down the whole inheritance chain (see #18083).
Deleting an instance of a model proxying a multi-table inherited subclass should cascade delete down the whole inheritance chain (see #18083).
def test_model_subclass_proxy(self): """ Deleting an instance of a model proxying a multi-table inherited subclass should cascade delete down the whole inheritance chain (see #18083). """ instance = ConcreteModelSubclassProxy.objects.create() instance.delete() ...
[ "def", "test_model_subclass_proxy", "(", "self", ")", ":", "instance", "=", "ConcreteModelSubclassProxy", ".", "objects", ".", "create", "(", ")", "instance", ".", "delete", "(", ")", "self", ".", "assertEqual", "(", "0", ",", "ConcreteModelSubclassProxy", ".", ...
[ 36, 4 ]
[ 46, 58 ]
python
en
['en', 'error', 'th']
False
is_double_callable
(application)
Tests to see if an application is a legacy-style (double-callable) application.
Tests to see if an application is a legacy-style (double-callable) application.
def is_double_callable(application): """ Tests to see if an application is a legacy-style (double-callable) application. """ # Look for a hint on the object first if getattr(application, "_asgi_single_callable", False): return False if getattr(application, "_asgi_double_callable", False)...
[ "def", "is_double_callable", "(", "application", ")", ":", "# Look for a hint on the object first", "if", "getattr", "(", "application", ",", "\"_asgi_single_callable\"", ",", "False", ")", ":", "return", "False", "if", "getattr", "(", "application", ",", "\"_asgi_dou...
[ 4, 0 ]
[ 23, 55 ]
python
en
['en', 'error', 'th']
False
double_to_single_callable
(application)
Transforms a double-callable ASGI application into a single-callable one.
Transforms a double-callable ASGI application into a single-callable one.
def double_to_single_callable(application): """ Transforms a double-callable ASGI application into a single-callable one. """ async def new_application(scope, receive, send): instance = application(scope) return await instance(receive, send) return new_application
[ "def", "double_to_single_callable", "(", "application", ")", ":", "async", "def", "new_application", "(", "scope", ",", "receive", ",", "send", ")", ":", "instance", "=", "application", "(", "scope", ")", "return", "await", "instance", "(", "receive", ",", "...
[ 26, 0 ]
[ 35, 26 ]
python
en
['en', 'error', 'th']
False
guarantee_single_callable
(application)
Takes either a single- or double-callable application and always returns it in single-callable style. Use this to add backwards compatibility for ASGI 2.0 applications to your server/test harness/etc.
Takes either a single- or double-callable application and always returns it in single-callable style. Use this to add backwards compatibility for ASGI 2.0 applications to your server/test harness/etc.
def guarantee_single_callable(application): """ Takes either a single- or double-callable application and always returns it in single-callable style. Use this to add backwards compatibility for ASGI 2.0 applications to your server/test harness/etc. """ if is_double_callable(application): ...
[ "def", "guarantee_single_callable", "(", "application", ")", ":", "if", "is_double_callable", "(", "application", ")", ":", "application", "=", "double_to_single_callable", "(", "application", ")", "return", "application" ]
[ 38, 0 ]
[ 46, 22 ]
python
en
['en', 'error', 'th']
False
TestArchiveMessagesGeneral.test_expired_messages_in_each_realm
(self)
General test for archiving expired messages properly with multiple realms involved
General test for archiving expired messages properly with multiple realms involved
def test_expired_messages_in_each_realm(self) -> None: """General test for archiving expired messages properly with multiple realms involved""" # Make some expired messages in MIT: expired_mit_msg_ids = self._make_mit_messages( 5, timezone_now() - timedelta(days=M...
[ "def", "test_expired_messages_in_each_realm", "(", "self", ")", "->", "None", ":", "# Make some expired messages in MIT:", "expired_mit_msg_ids", "=", "self", ".", "_make_mit_messages", "(", "5", ",", "timezone_now", "(", ")", "-", "timedelta", "(", "days", "=", "MI...
[ 206, 4 ]
[ 235, 72 ]
python
en
['en', 'en', 'en']
True
TestArchiveMessagesGeneral.test_expired_messages_in_one_realm
(self)
Test with a retention policy set for only the MIT realm
Test with a retention policy set for only the MIT realm
def test_expired_messages_in_one_realm(self) -> None: """Test with a retention policy set for only the MIT realm""" self._set_realm_message_retention_value(self.zulip_realm, -1) # Make some expired messages in MIT: expired_mit_msg_ids = self._make_mit_messages( 5, ...
[ "def", "test_expired_messages_in_one_realm", "(", "self", ")", "->", "None", ":", "self", ".", "_set_realm_message_retention_value", "(", "self", ".", "zulip_realm", ",", "-", "1", ")", "# Make some expired messages in MIT:", "expired_mit_msg_ids", "=", "self", ".", "...
[ 237, 4 ]
[ 271, 83 ]
python
en
['en', 'en', 'en']
True
TestArchiveMessagesGeneral.test_cross_realm_personal_message_archiving
(self)
Check that cross-realm personal messages get correctly archived.
Check that cross-realm personal messages get correctly archived.
def test_cross_realm_personal_message_archiving(self) -> None: """Check that cross-realm personal messages get correctly archived. """ msg_ids = [self._send_cross_realm_personal_message() for i in range(1, 7)] usermsg_ids = self._get_usermessage_ids(msg_ids) # Make the message expired on...
[ "def", "test_cross_realm_personal_message_archiving", "(", "self", ")", "->", "None", ":", "msg_ids", "=", "[", "self", ".", "_send_cross_realm_personal_message", "(", ")", "for", "i", "in", "range", "(", "1", ",", "7", ")", "]", "usermsg_ids", "=", "self", ...
[ 299, 4 ]
[ 307, 55 ]
python
en
['en', 'en', 'en']
True
TestArchiveMessagesGeneral.test_archiving_interrupted
(self)
Check that queries get rolled back to a consistent state if archiving gets interrupted in the middle of processing a chunk.
Check that queries get rolled back to a consistent state if archiving gets interrupted in the middle of processing a chunk.
def test_archiving_interrupted(self) -> None: """Check that queries get rolled back to a consistent state if archiving gets interrupted in the middle of processing a chunk.""" expired_msg_ids = self._make_expired_zulip_messages(7) expired_usermsg_ids = self._get_usermessage_ids(expired_m...
[ "def", "test_archiving_interrupted", "(", "self", ")", "->", "None", ":", "expired_msg_ids", "=", "self", ".", "_make_expired_zulip_messages", "(", "7", ")", "expired_usermsg_ids", "=", "self", ".", "_get_usermessage_ids", "(", "expired_msg_ids", ")", "# Insert an exc...
[ 309, 4 ]
[ 335, 13 ]
python
en
['en', 'en', 'en']
True
TestArchiveMessagesGeneral.test_archive_message_tool
(self)
End-to-end test of the archiving tool, directly calling archive_messages.
End-to-end test of the archiving tool, directly calling archive_messages.
def test_archive_message_tool(self) -> None: """End-to-end test of the archiving tool, directly calling archive_messages.""" # Make some expired messages in MIT: expired_mit_msg_ids = self._make_mit_messages( 5, timezone_now() - timedelta(days=MIT_REALM_DAYS + 1),...
[ "def", "test_archive_message_tool", "(", "self", ")", "->", "None", ":", "# Make some expired messages in MIT:", "expired_mit_msg_ids", "=", "self", ".", "_make_mit_messages", "(", "5", ",", "timezone_now", "(", ")", "-", "timedelta", "(", "days", "=", "MIT_REALM_DA...
[ 337, 4 ]
[ 366, 72 ]
python
en
['en', 'en', 'en']
True
TestArchiveMessagesGeneral.test_archiving_attachments
(self)
End-to-end test for the logic for archiving attachments. This test is hard to read without first reading _send_messages_with_attachments
End-to-end test for the logic for archiving attachments. This test is hard to read without first reading _send_messages_with_attachments
def test_archiving_attachments(self) -> None: """End-to-end test for the logic for archiving attachments. This test is hard to read without first reading _send_messages_with_attachments""" msgs_ids = self._send_messages_with_attachments() # First, confirm deleting the oldest message ...
[ "def", "test_archiving_attachments", "(", "self", ")", "->", "None", ":", "msgs_ids", "=", "self", ".", "_send_messages_with_attachments", "(", ")", "# First, confirm deleting the oldest message", "# (`expired_message_id`) creates ArchivedAttachment objects", "# and associates that...
[ 368, 4 ]
[ 428, 9 ]
python
en
['en', 'en', 'en']
True
MoveMessageToArchiveGeneral.test_archiving_messages_multiple_realms
(self)
Verifies that move_messages_to_archive works correctly if called on messages in multiple realms.
Verifies that move_messages_to_archive works correctly if called on messages in multiple realms.
def test_archiving_messages_multiple_realms(self) -> None: """ Verifies that move_messages_to_archive works correctly if called on messages in multiple realms. """ iago = self.example_user("iago") othello = self.example_user("othello") cordelia = self.lear_user("...
[ "def", "test_archiving_messages_multiple_realms", "(", "self", ")", "->", "None", ":", "iago", "=", "self", ".", "example_user", "(", "\"iago\"", ")", "othello", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "cordelia", "=", "self", ".", "lear_use...
[ 628, 4 ]
[ 649, 56 ]
python
en
['en', 'error', 'th']
False
TestGetRealmAndStreamsForArchiving.fix_ordering_of_result
(self, result: List[Tuple[Realm, List[Stream]]])
This is a helper for giving the structure returned by get_realms_and_streams_for_archiving a consistent ordering.
This is a helper for giving the structure returned by get_realms_and_streams_for_archiving a consistent ordering.
def fix_ordering_of_result(self, result: List[Tuple[Realm, List[Stream]]]) -> None: """ This is a helper for giving the structure returned by get_realms_and_streams_for_archiving a consistent ordering. """ # Sort the list of tuples by realm id: result.sort(key=lambda x: x...
[ "def", "fix_ordering_of_result", "(", "self", ",", "result", ":", "List", "[", "Tuple", "[", "Realm", ",", "List", "[", "Stream", "]", "]", "]", ")", "->", "None", ":", "# Sort the list of tuples by realm id:", "result", ".", "sort", "(", "key", "=", "lamb...
[ 894, 4 ]
[ 904, 59 ]
python
en
['en', 'error', 'th']
False
TestGetRealmAndStreamsForArchiving.simple_get_realms_and_streams_for_archiving
(self)
This is an implementation of the function we're testing, but using the obvious, unoptimized algorithm. We can use this for additional verification of correctness, by comparing the output of the two implementations.
This is an implementation of the function we're testing, but using the obvious, unoptimized algorithm. We can use this for additional verification of correctness, by comparing the output of the two implementations.
def simple_get_realms_and_streams_for_archiving(self) -> List[Tuple[Realm, List[Stream]]]: """ This is an implementation of the function we're testing, but using the obvious, unoptimized algorithm. We can use this for additional verification of correctness, by comparing the output of the...
[ "def", "simple_get_realms_and_streams_for_archiving", "(", "self", ")", "->", "List", "[", "Tuple", "[", "Realm", ",", "List", "[", "Stream", "]", "]", "]", ":", "result", "=", "[", "]", "for", "realm", "in", "Realm", ".", "objects", ".", "all", "(", "...
[ 906, 4 ]
[ 927, 21 ]
python
en
['en', 'error', 'th']
False
TestDoDeleteMessages.test_old_event_format_processed_correctly
(self)
do_delete_messages used to send events with users in dict format {"id": <int>}. We have a block in process_notification to deal with that old format, that should be deleted in a later release. This test is meant to ensure correctness of that block.
do_delete_messages used to send events with users in dict format {"id": <int>}. We have a block in process_notification to deal with that old format, that should be deleted in a later release. This test is meant to ensure correctness of that block.
def test_old_event_format_processed_correctly(self) -> None: """ do_delete_messages used to send events with users in dict format {"id": <int>}. We have a block in process_notification to deal with that old format, that should be deleted in a later release. This test is meant to ensure c...
[ "def", "test_old_event_format_processed_correctly", "(", "self", ")", "->", "None", ":", "realm", "=", "get_realm", "(", "\"zulip\"", ")", "cordelia", "=", "self", ".", "example_user", "(", "\"cordelia\"", ")", "hamlet", "=", "self", ".", "example_user", "(", ...
[ 1064, 4 ]
[ 1087, 74 ]
python
en
['en', 'error', 'th']
False
get_template
(template_name, dirs=None)
Returns a compiled Template object for the given template name, handling template inheritance recursively.
Returns a compiled Template object for the given template name, handling template inheritance recursively.
def get_template(template_name, dirs=None): """ Returns a compiled Template object for the given template name, handling template inheritance recursively. """ template, origin = find_template(template_name, dirs) if not hasattr(template, 'render'): # template needs to be compiled ...
[ "def", "get_template", "(", "template_name", ",", "dirs", "=", "None", ")", ":", "template", ",", "origin", "=", "find_template", "(", "template_name", ",", "dirs", ")", "if", "not", "hasattr", "(", "template", ",", "'render'", ")", ":", "# template needs to...
[ 145, 0 ]
[ 154, 19 ]
python
en
['en', 'error', 'th']
False
get_template_from_string
(source, origin=None, name=None)
Returns a compiled Template object for the given template code, handling template inheritance recursively.
Returns a compiled Template object for the given template code, handling template inheritance recursively.
def get_template_from_string(source, origin=None, name=None): """ Returns a compiled Template object for the given template code, handling template inheritance recursively. """ return Template(source, origin, name)
[ "def", "get_template_from_string", "(", "source", ",", "origin", "=", "None", ",", "name", "=", "None", ")", ":", "return", "Template", "(", "source", ",", "origin", ",", "name", ")" ]
[ 157, 0 ]
[ 162, 41 ]
python
en
['en', 'error', 'th']
False
render_to_string
(template_name, dictionary=None, context_instance=None, dirs=None)
Loads the given template_name and renders it with the given dictionary as context. The template_name may be a string to load a single template using get_template, or it may be a tuple to use select_template to find one of the templates in the list. Returns a string.
Loads the given template_name and renders it with the given dictionary as context. The template_name may be a string to load a single template using get_template, or it may be a tuple to use select_template to find one of the templates in the list. Returns a string.
def render_to_string(template_name, dictionary=None, context_instance=None, dirs=None): """ Loads the given template_name and renders it with the given dictionary as context. The template_name may be a string to load a single template using get_template, or it may be a tuple to use ...
[ "def", "render_to_string", "(", "template_name", ",", "dictionary", "=", "None", ",", "context_instance", "=", "None", ",", "dirs", "=", "None", ")", ":", "if", "isinstance", "(", "template_name", ",", "(", "list", ",", "tuple", ")", ")", ":", "t", "=", ...
[ 165, 0 ]
[ 184, 41 ]
python
en
['en', 'error', 'th']
False
select_template
(template_name_list, dirs=None)
Given a list of template names, returns the first that can be loaded.
Given a list of template names, returns the first that can be loaded.
def select_template(template_name_list, dirs=None): "Given a list of template names, returns the first that can be loaded." if not template_name_list: raise TemplateDoesNotExist("No template names provided") not_found = [] for template_name in template_name_list: try: return ...
[ "def", "select_template", "(", "template_name_list", ",", "dirs", "=", "None", ")", ":", "if", "not", "template_name_list", ":", "raise", "TemplateDoesNotExist", "(", "\"No template names provided\"", ")", "not_found", "=", "[", "]", "for", "template_name", "in", ...
[ 187, 0 ]
[ 200, 52 ]
python
en
['en', 'en', 'en']
True
BaseLoader.load_template_source
(self, template_name, template_dirs=None)
Returns a tuple containing the source and origin for the given template name.
Returns a tuple containing the source and origin for the given template name.
def load_template_source(self, template_name, template_dirs=None): """ Returns a tuple containing the source and origin for the given template name. """ raise NotImplementedError('subclasses of BaseLoader must provide a load_template_source() method')
[ "def", "load_template_source", "(", "self", ",", "template_name", ",", "template_dirs", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseLoader must provide a load_template_source() method'", ")" ]
[ 58, 4 ]
[ 64, 106 ]
python
en
['en', 'error', 'th']
False
BaseLoader.reset
(self)
Resets any state maintained by the loader instance (e.g., cached templates or cached loader modules).
Resets any state maintained by the loader instance (e.g., cached templates or cached loader modules).
def reset(self): """ Resets any state maintained by the loader instance (e.g., cached templates or cached loader modules). """ pass
[ "def", "reset", "(", "self", ")", ":", "pass" ]
[ 66, 4 ]
[ 72, 12 ]
python
en
['en', 'error', 'th']
False
Node.__init__
(self, children=None, connector=None, negated=False)
Constructs a new Node. If no connector is given, the default will be used.
Constructs a new Node. If no connector is given, the default will be used.
def __init__(self, children=None, connector=None, negated=False): """ Constructs a new Node. If no connector is given, the default will be used. """ 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"...
[ 18, 4 ]
[ 25, 30 ]
python
en
['en', 'error', 'th']
False
Node._new_instance
(cls, children=None, connector=None, negated=False)
This is called to create a new instance of this class when we need new Nodes (or subclasses) in the internal code in this class. Normally, it just shadows __init__(). However, subclasses with an __init__ signature that is not an extension of Node.__init__ might need to implement this ...
This is called to create a new instance of this class when we need new Nodes (or subclasses) in the internal code in this class. Normally, it just shadows __init__(). However, subclasses with an __init__ signature that is not an extension of Node.__init__ might need to implement this ...
def _new_instance(cls, children=None, connector=None, negated=False): """ This is called to create a new instance of this class when we need new Nodes (or subclasses) in the internal code in this class. Normally, it just shadows __init__(). However, subclasses with an __init__ signature ...
[ "def", "_new_instance", "(", "cls", ",", "children", "=", "None", ",", "connector", "=", "None", ",", "negated", "=", "False", ")", ":", "obj", "=", "Node", "(", "children", ",", "connector", ",", "negated", ")", "obj", ".", "__class__", "=", "cls", ...
[ 30, 4 ]
[ 41, 18 ]
python
en
['en', 'error', 'th']
False
Node.__deepcopy__
(self, memodict)
Utility method used by copy.deepcopy().
Utility method used by copy.deepcopy().
def __deepcopy__(self, memodict): """ Utility method used by copy.deepcopy(). """ obj = Node(connector=self.connector, negated=self.negated) obj.__class__ = self.__class__ obj.children = copy.deepcopy(self.children, memodict) return obj
[ "def", "__deepcopy__", "(", "self", ",", "memodict", ")", ":", "obj", "=", "Node", "(", "connector", "=", "self", ".", "connector", ",", "negated", "=", "self", ".", "negated", ")", "obj", ".", "__class__", "=", "self", ".", "__class__", "obj", ".", ...
[ 53, 4 ]
[ 60, 18 ]
python
en
['en', 'error', 'th']
False
Node.__len__
(self)
The size of a node if the number of children it has.
The size of a node if the number of children it has.
def __len__(self): """ The size of a node if the number of children it has. """ return len(self.children)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "children", ")" ]
[ 62, 4 ]
[ 66, 33 ]
python
en
['en', 'error', 'th']
False
Node.__bool__
(self)
For truth value testing.
For truth value testing.
def __bool__(self): """ For truth value testing. """ return bool(self.children)
[ "def", "__bool__", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "children", ")" ]
[ 68, 4 ]
[ 72, 34 ]
python
en
['en', 'error', 'th']
False
Node.__contains__
(self, other)
Returns True is 'other' is a direct child of this instance.
Returns True is 'other' is a direct child of this instance.
def __contains__(self, other): """ Returns True is 'other' is a direct child of this instance. """ return other in self.children
[ "def", "__contains__", "(", "self", ",", "other", ")", ":", "return", "other", "in", "self", ".", "children" ]
[ 77, 4 ]
[ 81, 37 ]
python
en
['en', 'error', 'th']
False
Node._prepare_data
(self, data)
A subclass hook for doing subclass specific transformations of the given data on combine() or add().
A subclass hook for doing subclass specific transformations of the given data on combine() or add().
def _prepare_data(self, data): """ A subclass hook for doing subclass specific transformations of the given data on combine() or add(). """ return data
[ "def", "_prepare_data", "(", "self", ",", "data", ")", ":", "return", "data" ]
[ 83, 4 ]
[ 88, 19 ]
python
en
['en', 'error', 'th']
False
Node.add
(self, data, conn_type, squash=True)
Combines 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. ...
Combines 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): """ Combines 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 tre...
[ "def", "add", "(", "self", ",", "data", ",", "conn_type", ",", "squash", "=", "True", ")", ":", "if", "data", "in", "self", ".", "children", ":", "return", "data", "data", "=", "self", ".", "_prepare_data", "(", "data", ")", "if", "not", "squash", ...
[ 90, 4 ]
[ 133, 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" ]
[ 135, 4 ]
[ 139, 39 ]
python
en
['en', 'error', 'th']
False
build_instance
(Model, data, db)
Build a model instance. If the model instance doesn't have a primary key and the model supports natural keys, try to retrieve it from the database.
Build a model instance.
def build_instance(Model, data, db): """ Build a model instance. If the model instance doesn't have a primary key and the model supports natural keys, try to retrieve it from the database. """ obj = Model(**data) if (obj.pk is None and hasattr(Model, 'natural_key') and hasattr(M...
[ "def", "build_instance", "(", "Model", ",", "data", ",", "db", ")", ":", "obj", "=", "Model", "(", "*", "*", "data", ")", "if", "(", "obj", ".", "pk", "is", "None", "and", "hasattr", "(", "Model", ",", "'natural_key'", ")", "and", "hasattr", "(", ...
[ 182, 0 ]
[ 197, 14 ]
python
en
['en', 'error', 'th']
False
Serializer.serialize
(self, queryset, **options)
Serialize a queryset.
Serialize a queryset.
def serialize(self, queryset, **options): """ Serialize a queryset. """ self.options = options self.stream = options.pop("stream", six.StringIO()) self.selected_fields = options.pop("fields", None) self.use_natural_keys = options.pop("use_natural_keys", False) ...
[ "def", "serialize", "(", "self", ",", "queryset", ",", "*", "*", "options", ")", ":", "self", ".", "options", "=", "options", "self", ".", "stream", "=", "options", ".", "pop", "(", "\"stream\"", ",", "six", ".", "StringIO", "(", ")", ")", "self", ...
[ 34, 4 ]
[ 72, 30 ]
python
en
['en', 'error', 'th']
False
Serializer.start_serialization
(self)
Called when serializing of the queryset starts.
Called when serializing of the queryset starts.
def start_serialization(self): """ Called when serializing of the queryset starts. """ raise NotImplementedError('subclasses of Serializer must provide a start_serialization() method')
[ "def", "start_serialization", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of Serializer must provide a start_serialization() method'", ")" ]
[ 74, 4 ]
[ 78, 105 ]
python
en
['en', 'error', 'th']
False
Serializer.end_serialization
(self)
Called when serializing of the queryset ends.
Called when serializing of the queryset ends.
def end_serialization(self): """ Called when serializing of the queryset ends. """ pass
[ "def", "end_serialization", "(", "self", ")", ":", "pass" ]
[ 80, 4 ]
[ 84, 12 ]
python
en
['en', 'error', 'th']
False
Serializer.start_object
(self, obj)
Called when serializing of an object starts.
Called when serializing of an object starts.
def start_object(self, obj): """ Called when serializing of an object starts. """ raise NotImplementedError('subclasses of Serializer must provide a start_object() method')
[ "def", "start_object", "(", "self", ",", "obj", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of Serializer must provide a start_object() method'", ")" ]
[ 86, 4 ]
[ 90, 98 ]
python
en
['en', 'error', 'th']
False
Serializer.end_object
(self, obj)
Called when serializing of an object ends.
Called when serializing of an object ends.
def end_object(self, obj): """ Called when serializing of an object ends. """ pass
[ "def", "end_object", "(", "self", ",", "obj", ")", ":", "pass" ]
[ 92, 4 ]
[ 96, 12 ]
python
en
['en', 'error', 'th']
False
Serializer.handle_field
(self, obj, field)
Called to handle each individual (non-relational) field on an object.
Called to handle each individual (non-relational) field on an object.
def handle_field(self, obj, field): """ Called to handle each individual (non-relational) field on an object. """ raise NotImplementedError('subclasses of Serializer must provide an handle_field() method')
[ "def", "handle_field", "(", "self", ",", "obj", ",", "field", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of Serializer must provide an handle_field() method'", ")" ]
[ 98, 4 ]
[ 102, 99 ]
python
en
['en', 'error', 'th']
False
Serializer.handle_fk_field
(self, obj, field)
Called to handle a ForeignKey field.
Called to handle a ForeignKey field.
def handle_fk_field(self, obj, field): """ Called to handle a ForeignKey field. """ raise NotImplementedError('subclasses of Serializer must provide an handle_fk_field() method')
[ "def", "handle_fk_field", "(", "self", ",", "obj", ",", "field", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of Serializer must provide an handle_fk_field() method'", ")" ]
[ 104, 4 ]
[ 108, 102 ]
python
en
['en', 'error', 'th']
False
Serializer.handle_m2m_field
(self, obj, field)
Called to handle a ManyToManyField.
Called to handle a ManyToManyField.
def handle_m2m_field(self, obj, field): """ Called to handle a ManyToManyField. """ raise NotImplementedError('subclasses of Serializer must provide an handle_m2m_field() method')
[ "def", "handle_m2m_field", "(", "self", ",", "obj", ",", "field", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of Serializer must provide an handle_m2m_field() method'", ")" ]
[ 110, 4 ]
[ 114, 103 ]
python
en
['en', 'error', 'th']
False
Serializer.getvalue
(self)
Return the fully serialized queryset (or None if the output stream is not seekable).
Return the fully serialized queryset (or None if the output stream is not seekable).
def getvalue(self): """ Return the fully serialized queryset (or None if the output stream is not seekable). """ if callable(getattr(self.stream, 'getvalue', None)): return self.stream.getvalue()
[ "def", "getvalue", "(", "self", ")", ":", "if", "callable", "(", "getattr", "(", "self", ".", "stream", ",", "'getvalue'", ",", "None", ")", ")", ":", "return", "self", ".", "stream", ".", "getvalue", "(", ")" ]
[ 116, 4 ]
[ 122, 41 ]
python
en
['en', 'error', 'th']
False
Deserializer.__init__
(self, stream_or_string, **options)
Init this serializer given a stream or a string
Init this serializer given a stream or a string
def __init__(self, stream_or_string, **options): """ Init this serializer given a stream or a string """ self.options = options if isinstance(stream_or_string, six.string_types): self.stream = six.StringIO(stream_or_string) else: self.stream = stre...
[ "def", "__init__", "(", "self", ",", "stream_or_string", ",", "*", "*", "options", ")", ":", "self", ".", "options", "=", "options", "if", "isinstance", "(", "stream_or_string", ",", "six", ".", "string_types", ")", ":", "self", ".", "stream", "=", "six"...
[ 130, 4 ]
[ 138, 42 ]
python
en
['en', 'error', 'th']
False
Deserializer.__next__
(self)
Iteration iterface -- return the next item in the stream
Iteration iterface -- return the next item in the stream
def __next__(self): """Iteration iterface -- return the next item in the stream""" raise NotImplementedError('subclasses of Deserializer must provide a __next__() method')
[ "def", "__next__", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of Deserializer must provide a __next__() method'", ")" ]
[ 143, 4 ]
[ 145, 96 ]
python
en
['en', 'en', 'en']
True
make_confidence_report_spsa
( filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, report_path=REPORT_PATH, nb_iter=NB_ITER_SPSA, spsa_samples=SPSA_SAMPLES, spsa_iters=SPSA.DEFAULT_SPSA_ITERS, )
Load a saved model, gather its predictions, and save a confidence report. This function works by running a single MaxConfidence attack on each example, using SPSA as the underyling optimizer. This is not intended to be a strong generic attack. It is intended to be a test to uncover gradient maski...
Load a saved model, gather its predictions, and save a confidence report.
def make_confidence_report_spsa( filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, report_path=REPORT_PATH, nb_iter=NB_ITER_SPSA, spsa_samples=SPSA_SAMPLES, spsa_iters=SPSA.DEFAULT_SPS...
[ "def", "make_confidence_report_spsa", "(", "filepath", ",", "train_start", "=", "TRAIN_START", ",", "train_end", "=", "TRAIN_END", ",", "test_start", "=", "TEST_START", ",", "test_end", "=", "TEST_END", ",", "batch_size", "=", "BATCH_SIZE", ",", "which_set", "=", ...
[ 58, 0 ]
[ 150, 5 ]
python
en
['en', 'error', 'th']
False
main
(argv=None)
Make a confidence report and save it to disk.
Make a confidence report and save it to disk.
def main(argv=None): """ Make a confidence report and save it to disk. """ try: _name_of_script, filepath = argv except ValueError: raise ValueError(argv) make_confidence_report_spsa( filepath=filepath, test_start=FLAGS.test_start, test_end=FLAGS.test_end,...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "try", ":", "_name_of_script", ",", "filepath", "=", "argv", "except", "ValueError", ":", "raise", "ValueError", "(", "argv", ")", "make_confidence_report_spsa", "(", "filepath", "=", "filepath", ",", "test_...
[ 153, 0 ]
[ 171, 5 ]
python
en
['en', 'error', 'th']
False
TemplateLoaderTests.test_include_missing_template
(self)
Tests that the correct template is identified as not existing when {% include %} specifies a template that does not exist.
Tests that the correct template is identified as not existing when {% include %} specifies a template that does not exist.
def test_include_missing_template(self): """ Tests that the correct template is identified as not existing when {% include %} specifies a template that does not exist. """ load_name = 'test_include_error.html' r = None try: tmpl = loader.select_templat...
[ "def", "test_include_missing_template", "(", "self", ")", ":", "load_name", "=", "'test_include_error.html'", "r", "=", "None", "try", ":", "tmpl", "=", "loader", ".", "select_template", "(", "[", "load_name", "]", ")", "r", "=", "tmpl", ".", "render", "(", ...
[ 267, 4 ]
[ 279, 100 ]
python
en
['en', 'error', 'th']
False
TemplateLoaderTests.test_extends_include_missing_baseloader
(self)
Tests that the correct template is identified as not existing when {% extends %} specifies a template that does exist, but that template has an {% include %} of something that does not exist. See #12787.
Tests that the correct template is identified as not existing when {% extends %} specifies a template that does exist, but that template has an {% include %} of something that does not exist. See #12787.
def test_extends_include_missing_baseloader(self): """ Tests that the correct template is identified as not existing when {% extends %} specifies a template that does exist, but that template has an {% include %} of something that does not exist. See #12787. """ l...
[ "def", "test_extends_include_missing_baseloader", "(", "self", ")", ":", "load_name", "=", "'test_extends_error.html'", "tmpl", "=", "loader", ".", "get_template", "(", "load_name", ")", "r", "=", "None", "try", ":", "r", "=", "tmpl", ".", "render", "(", "temp...
[ 288, 4 ]
[ 302, 100 ]
python
en
['en', 'error', 'th']
False
TemplateLoaderTests.test_extends_include_missing_cachedloader
(self)
Same as test_extends_include_missing_baseloader, only tests behavior of the cached loader instead of BaseLoader.
Same as test_extends_include_missing_baseloader, only tests behavior of the cached loader instead of BaseLoader.
def test_extends_include_missing_cachedloader(self): """ Same as test_extends_include_missing_baseloader, only tests behavior of the cached loader instead of BaseLoader. """ cache_loader = cached.Loader(('',)) cache_loader._cached_loaders = (app_directories.Loader(),) ...
[ "def", "test_extends_include_missing_cachedloader", "(", "self", ")", ":", "cache_loader", "=", "cached", ".", "Loader", "(", "(", "''", ",", ")", ")", "cache_loader", ".", "_cached_loaders", "=", "(", "app_directories", ".", "Loader", "(", ")", ",", ")", "w...
[ 305, 4 ]
[ 329, 104 ]
python
en
['en', 'error', 'th']
False
TemplateLoaderTests.test_include_template_argument
(self)
Support any render() supporting object
Support any render() supporting object
def test_include_template_argument(self): """ Support any render() supporting object """ ctx = Context({ 'tmpl': Template('This worked!'), }) outer_tmpl = Template('{% include tmpl %}') output = outer_tmpl.render(ctx) self.assertEqual(output, '...
[ "def", "test_include_template_argument", "(", "self", ")", ":", "ctx", "=", "Context", "(", "{", "'tmpl'", ":", "Template", "(", "'This worked!'", ")", ",", "}", ")", "outer_tmpl", "=", "Template", "(", "'{% include tmpl %}'", ")", "output", "=", "outer_tmpl",...
[ 331, 4 ]
[ 340, 48 ]
python
en
['en', 'error', 'th']
False
TemplateLoaderTests.test_include_immediate_missing
(self)
Regression test for #16417 -- {% include %} tag raises TemplateDoesNotExist at compile time if TEMPLATE_DEBUG is True Test that an {% include %} tag with a literal string referencing a template that does not exist does not raise an exception at parse time.
Regression test for #16417 -- {% include %} tag raises TemplateDoesNotExist at compile time if TEMPLATE_DEBUG is True
def test_include_immediate_missing(self): """ Regression test for #16417 -- {% include %} tag raises TemplateDoesNotExist at compile time if TEMPLATE_DEBUG is True Test that an {% include %} tag with a literal string referencing a template that does not exist does not raise an exception...
[ "def", "test_include_immediate_missing", "(", "self", ")", ":", "tmpl", "=", "Template", "(", "'{% include \"this_does_not_exist.html\" %}'", ")", "self", ".", "assertIsInstance", "(", "tmpl", ",", "Template", ")" ]
[ 343, 4 ]
[ 352, 45 ]
python
en
['en', 'error', 'th']
False
TemplateRegressionTests.test_no_wrapped_exception
(self)
The template system doesn't wrap exceptions, but annotates them. Refs #16770
The template system doesn't wrap exceptions, but annotates them. Refs #16770
def test_no_wrapped_exception(self): """ The template system doesn't wrap exceptions, but annotates them. Refs #16770 """ c = Context({"coconuts": lambda: 42 / 0}) t = Template("{{ coconuts }}") with self.assertRaises(ZeroDivisionError) as cm: t.render...
[ "def", "test_no_wrapped_exception", "(", "self", ")", ":", "c", "=", "Context", "(", "{", "\"coconuts\"", ":", "lambda", ":", "42", "/", "0", "}", ")", "t", "=", "Template", "(", "\"{{ coconuts }}\"", ")", "with", "self", ".", "assertRaises", "(", "ZeroD...
[ 409, 4 ]
[ 419, 73 ]
python
en
['en', 'error', 'th']
False
TemplateRegressionTests.test_cache_fragment_cache
(self)
When a cache called "template_fragments" is present, the cache tag will use it in preference to 'default'
When a cache called "template_fragments" is present, the cache tag will use it in preference to 'default'
def test_cache_fragment_cache(self): """ When a cache called "template_fragments" is present, the cache tag will use it in preference to 'default' """ t1 = Template('{% load cache %}{% cache 1 fragment %}foo{% endcache %}') t2 = Template('{% load cache %}{% cache 1 fragme...
[ "def", "test_cache_fragment_cache", "(", "self", ")", ":", "t1", "=", "Template", "(", "'{% load cache %}{% cache 1 fragment %}foo{% endcache %}'", ")", "t2", "=", "Template", "(", "'{% load cache %}{% cache 1 fragment using=\"default\" %}bar{% endcache %}'", ")", "ctx", "=", ...
[ 464, 4 ]
[ 477, 35 ]
python
en
['en', 'error', 'th']
False
TemplateRegressionTests.test_cache_missing_backend
(self)
When a cache that doesn't exist is specified, the cache tag will raise a TemplateSyntaxError
When a cache that doesn't exist is specified, the cache tag will raise a TemplateSyntaxError
def test_cache_missing_backend(self): """ When a cache that doesn't exist is specified, the cache tag will raise a TemplateSyntaxError '""" t = Template('{% load cache %}{% cache 1 backend using="unknown" %}bar{% endcache %}') ctx = Context() with self.assertRais...
[ "def", "test_cache_missing_backend", "(", "self", ")", ":", "t", "=", "Template", "(", "'{% load cache %}{% cache 1 backend using=\"unknown\" %}bar{% endcache %}'", ")", "ctx", "=", "Context", "(", ")", "with", "self", ".", "assertRaises", "(", "TemplateSyntaxError", ")...
[ 479, 4 ]
[ 488, 25 ]
python
en
['en', 'error', 'th']
False
TemplateRegressionTests.test_ifchanged_render_once
(self)
Test for ticket #19890. The content of ifchanged template tag was rendered twice.
Test for ticket #19890. The content of ifchanged template tag was rendered twice.
def test_ifchanged_render_once(self): """ Test for ticket #19890. The content of ifchanged template tag was rendered twice.""" template = Template('{% ifchanged %}{% cycle "1st time" "2nd time" %}{% endifchanged %}') output = template.render(Context({})) self.assertEqual(output, ...
[ "def", "test_ifchanged_render_once", "(", "self", ")", ":", "template", "=", "Template", "(", "'{% ifchanged %}{% cycle \"1st time\" \"2nd time\" %}{% endifchanged %}'", ")", "output", "=", "template", ".", "render", "(", "Context", "(", "{", "}", ")", ")", "self", ...
[ 490, 4 ]
[ 495, 44 ]
python
en
['en', 'en', 'en']
True
TemplateRegressionTests.test_super_errors
(self)
Test behavior of the raise errors into included blocks. See #18169
Test behavior of the raise errors into included blocks. See #18169
def test_super_errors(self): """ Test behavior of the raise errors into included blocks. See #18169 """ t = loader.get_template('included_content.html') with self.assertRaises(urlresolvers.NoReverseMatch): t.render(Context({}))
[ "def", "test_super_errors", "(", "self", ")", ":", "t", "=", "loader", ".", "get_template", "(", "'included_content.html'", ")", "with", "self", ".", "assertRaises", "(", "urlresolvers", ".", "NoReverseMatch", ")", ":", "t", ".", "render", "(", "Context", "(...
[ 497, 4 ]
[ 504, 33 ]
python
en
['en', 'error', 'th']
False
TemplateRegressionTests.test_debug_tag_non_ascii
(self)
Test non-ASCII model representation in debug output (#23060).
Test non-ASCII model representation in debug output (#23060).
def test_debug_tag_non_ascii(self): """ Test non-ASCII model representation in debug output (#23060). """ Group.objects.create(name="清風") c1 = Context({"objs": Group.objects.all()}) t1 = Template('{% debug %}') self.assertIn("清風", t1.render(c1))
[ "def", "test_debug_tag_non_ascii", "(", "self", ")", ":", "Group", ".", "objects", ".", "create", "(", "name", "=", "\"清風\")", "", "c1", "=", "Context", "(", "{", "\"objs\"", ":", "Group", ".", "objects", ".", "all", "(", ")", "}", ")", "t1", "=", ...
[ 506, 4 ]
[ 513, 46 ]
python
en
['en', 'error', 'th']
False
RedisCache.clear
(self)
Helper for clearing all the keys in a database. Use with caution!
Helper for clearing all the keys in a database. Use with caution!
def clear(self): """Helper for clearing all the keys in a database. Use with caution!""" for key in self.conn.keys(): self.conn.delete(key)
[ "def", "clear", "(", "self", ")", ":", "for", "key", "in", "self", ".", "conn", ".", "keys", "(", ")", ":", "self", ".", "conn", ".", "delete", "(", "key", ")" ]
[ 24, 4 ]
[ 28, 33 ]
python
en
['en', 'en', 'en']
True
RedisCache.close
(self)
Redis uses connection pooling, no need to close the connection.
Redis uses connection pooling, no need to close the connection.
def close(self): """Redis uses connection pooling, no need to close the connection.""" pass
[ "def", "close", "(", "self", ")", ":", "pass" ]
[ 30, 4 ]
[ 32, 12 ]
python
en
['en', 'en', 'en']
True
render
(request, template_name, context=None, content_type=None, status=None, using=None)
Return a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments.
Return a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments.
def render(request, template_name, context=None, content_type=None, status=None, using=None): """ Return a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ content = loader.render_to_string(template_name, context...
[ "def", "render", "(", "request", ",", "template_name", ",", "context", "=", "None", ",", "content_type", "=", "None", ",", "status", "=", "None", ",", "using", "=", "None", ")", ":", "content", "=", "loader", ".", "render_to_string", "(", "template_name", ...
[ 13, 0 ]
[ 19, 54 ]
python
en
['en', 'error', 'th']
False
redirect
(to, *args, permanent=False, **kwargs)
Return an HttpResponseRedirect to the appropriate URL for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urls.reverse()` will be used to reverse-resolve the name. ...
Return an HttpResponseRedirect to the appropriate URL for the arguments passed.
def redirect(to, *args, permanent=False, **kwargs): """ Return an HttpResponseRedirect to the appropriate URL for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urls.reverse()`...
[ "def", "redirect", "(", "to", ",", "*", "args", ",", "permanent", "=", "False", ",", "*", "*", "kwargs", ")", ":", "redirect_class", "=", "HttpResponsePermanentRedirect", "if", "permanent", "else", "HttpResponseRedirect", "return", "redirect_class", "(", "resolv...
[ 22, 0 ]
[ 40, 59 ]
python
en
['en', 'error', 'th']
False
_get_queryset
(klass)
Return a QuerySet or a Manager. Duck typing in action: any class with a `get()` method (for get_object_or_404) or a `filter()` method (for get_list_or_404) might do the job.
Return a QuerySet or a Manager. Duck typing in action: any class with a `get()` method (for get_object_or_404) or a `filter()` method (for get_list_or_404) might do the job.
def _get_queryset(klass): """ Return a QuerySet or a Manager. Duck typing in action: any class with a `get()` method (for get_object_or_404) or a `filter()` method (for get_list_or_404) might do the job. """ # If it is a model class or anything else with ._default_manager if hasattr(klas...
[ "def", "_get_queryset", "(", "klass", ")", ":", "# If it is a model class or anything else with ._default_manager", "if", "hasattr", "(", "klass", ",", "'_default_manager'", ")", ":", "return", "klass", ".", "_default_manager", ".", "all", "(", ")", "return", "klass" ...
[ 43, 0 ]
[ 53, 16 ]
python
en
['en', 'error', 'th']
False
get_object_or_404
(klass, *args, **kwargs)
Use get() to return an object, or raise a Http404 exception if the object does not exist. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query. Like with QuerySet.get(), MultipleObjectsReturned is raised if more than o...
Use get() to return an object, or raise a Http404 exception if the object does not exist.
def get_object_or_404(klass, *args, **kwargs): """ Use get() to return an object, or raise a Http404 exception if the object does not exist. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query. Like with QuerySet.get()...
[ "def", "get_object_or_404", "(", "klass", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "queryset", "=", "_get_queryset", "(", "klass", ")", "if", "not", "hasattr", "(", "queryset", ",", "'get'", ")", ":", "klass__name", "=", "klass", ".", "__na...
[ 56, 0 ]
[ 77, 90 ]
python
en
['en', 'error', 'th']
False
get_list_or_404
(klass, *args, **kwargs)
Use filter() to return a list of objects, or raise a Http404 exception if the list is empty. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the filter() query.
Use filter() to return a list of objects, or raise a Http404 exception if the list is empty.
def get_list_or_404(klass, *args, **kwargs): """ Use filter() to return a list of objects, or raise a Http404 exception if the list is empty. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the filter() query. """ queryset = _g...
[ "def", "get_list_or_404", "(", "klass", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "queryset", "=", "_get_queryset", "(", "klass", ")", "if", "not", "hasattr", "(", "queryset", ",", "'filter'", ")", ":", "klass__name", "=", "klass", ".", "__n...
[ 80, 0 ]
[ 98, 19 ]
python
en
['en', 'error', 'th']
False
resolve_url
(to, *args, **kwargs)
Return a URL appropriate for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urls.reverse()` will be used to reverse-resolve the name. * A URL, which will be returne...
Return a URL appropriate for the arguments passed.
def resolve_url(to, *args, **kwargs): """ Return a URL appropriate for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urls.reverse()` will be used to reverse-resolve the ...
[ "def", "resolve_url", "(", "to", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# If it's a model, use get_absolute_url()", "if", "hasattr", "(", "to", ",", "'get_absolute_url'", ")", ":", "return", "to", ".", "get_absolute_url", "(", ")", "if", "isin...
[ 101, 0 ]
[ 140, 13 ]
python
en
['en', 'error', 'th']
False
sanitize_name
(value: str)
Sanitizes a value to be safe to store in a Linux filesystem, in S3, and in a URL. So Unicode is allowed, but not special characters other than ".", "-", and "_". This implementation is based on django.utils.text.slugify; it is modified by: * adding '.' and '_' to the list of allowed character...
Sanitizes a value to be safe to store in a Linux filesystem, in S3, and in a URL. So Unicode is allowed, but not special characters other than ".", "-", and "_".
def sanitize_name(value: str) -> str: """ Sanitizes a value to be safe to store in a Linux filesystem, in S3, and in a URL. So Unicode is allowed, but not special characters other than ".", "-", and "_". This implementation is based on django.utils.text.slugify; it is modified by: * adding...
[ "def", "sanitize_name", "(", "value", ":", "str", ")", "->", "str", ":", "value", "=", "unicodedata", ".", "normalize", "(", "\"NFKC\"", ",", "value", ")", "value", "=", "re", ".", "sub", "(", "r\"[^\\w\\s._-]\"", ",", "\"\"", ",", "value", ",", "flags...
[ 81, 0 ]
[ 96, 27 ]
python
en
['en', 'error', 'th']
False
Optimization.__init__
(self, dual_formulation_object, sess, optimization_params)
Initialize the class variables. Args: dual_formulation_object: Instance of DualFormulation that contains the dual variables and objective sess: tf session to be used to run optimization_params: Dictionary with the following eig_num_iter - Number of iteratio...
Initialize the class variables.
def __init__(self, dual_formulation_object, sess, optimization_params): """Initialize the class variables. Args: dual_formulation_object: Instance of DualFormulation that contains the dual variables and objective sess: tf session to be used to run optimization_...
[ "def", "__init__", "(", "self", ",", "dual_formulation_object", ",", "sess", ",", "optimization_params", ")", ":", "self", ".", "sess", "=", "sess", "self", ".", "dual_object", "=", "dual_formulation_object", "self", ".", "params", "=", "optimization_params", "s...
[ 23, 4 ]
[ 55, 39 ]
python
en
['en', 'en', 'en']
True
Optimization.tf_min_eig_vec
(self)
Function for min eigen vector using tf's full eigen decomposition.
Function for min eigen vector using tf's full eigen decomposition.
def tf_min_eig_vec(self): """Function for min eigen vector using tf's full eigen decomposition.""" # Full eigen decomposition requires the explicit psd matrix M _, matrix_m = self.dual_object.get_full_psd_matrix() [eig_vals, eig_vectors] = tf.self_adjoint_eig(matrix_m) index = tf...
[ "def", "tf_min_eig_vec", "(", "self", ")", ":", "# Full eigen decomposition requires the explicit psd matrix M", "_", ",", "matrix_m", "=", "self", ".", "dual_object", ".", "get_full_psd_matrix", "(", ")", "[", "eig_vals", ",", "eig_vectors", "]", "=", "tf", ".", ...
[ 57, 4 ]
[ 63, 87 ]
python
de
['de', 'no', 'nl']
False
Optimization.tf_smooth_eig_vec
(self)
Function that returns smoothed version of min eigen vector.
Function that returns smoothed version of min eigen vector.
def tf_smooth_eig_vec(self): """Function that returns smoothed version of min eigen vector.""" _, matrix_m = self.dual_object.get_full_psd_matrix() # Easier to think in terms of max so negating the matrix [eig_vals, eig_vectors] = tf.self_adjoint_eig(-matrix_m) exp_eig_vals = tf....
[ "def", "tf_smooth_eig_vec", "(", "self", ")", ":", "_", ",", "matrix_m", "=", "self", ".", "dual_object", ".", "get_full_psd_matrix", "(", ")", "# Easier to think in terms of max so negating the matrix", "[", "eig_vals", ",", "eig_vectors", "]", "=", "tf", ".", "s...
[ 65, 4 ]
[ 81, 9 ]
python
en
['en', 'en', 'en']
True