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
ModelState.from_model
(cls, model, exclude_rels=False)
Given a model, return a ModelState representing it.
Given a model, return a ModelState representing it.
def from_model(cls, model, exclude_rels=False): """Given a model, return a ModelState representing it.""" # Deconstruct the fields fields = [] for field in model._meta.local_fields: if getattr(field, "remote_field", None) and exclude_rels: continue ...
[ "def", "from_model", "(", "cls", ",", "model", ",", "exclude_rels", "=", "False", ")", ":", "# Deconstruct the fields", "fields", "=", "[", "]", "for", "field", "in", "model", ".", "_meta", ".", "local_fields", ":", "if", "getattr", "(", "field", ",", "\...
[ 401, 4 ]
[ 527, 9 ]
python
en
['en', 'en', 'en']
True
ModelState.construct_managers
(self)
Deep-clone the managers using deconstruction.
Deep-clone the managers using deconstruction.
def construct_managers(self): """Deep-clone the managers using deconstruction.""" # Sort all managers by their creation counter sorted_managers = sorted(self.managers, key=lambda v: v[1].creation_counter) for mgr_name, manager in sorted_managers: as_manager, manager_path, qs_...
[ "def", "construct_managers", "(", "self", ")", ":", "# Sort all managers by their creation counter", "sorted_managers", "=", "sorted", "(", "self", ".", "managers", ",", "key", "=", "lambda", "v", ":", "v", "[", "1", "]", ".", "creation_counter", ")", "for", "...
[ 529, 4 ]
[ 540, 62 ]
python
en
['en', 'en', 'en']
True
ModelState.clone
(self)
Return an exact copy of this ModelState.
Return an exact copy of this ModelState.
def clone(self): """Return an exact copy of this ModelState.""" return self.__class__( app_label=self.app_label, name=self.name, fields=list(self.fields), # Since options are shallow-copied here, operations such as # AddIndex must replace their...
[ "def", "clone", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "app_label", "=", "self", ".", "app_label", ",", "name", "=", "self", ".", "name", ",", "fields", "=", "list", "(", "self", ".", "fields", ")", ",", "# Since options are sh...
[ 542, 4 ]
[ 554, 9 ]
python
en
['en', 'en', 'en']
True
ModelState.render
(self, apps)
Create a Model object from our current state into the given apps.
Create a Model object from our current state into the given apps.
def render(self, apps): """Create a Model object from our current state into the given apps.""" # First, make a Meta object meta_contents = {'app_label': self.app_label, 'apps': apps, **self.options} meta = type("Meta", (), meta_contents) # Then, work out our bases try: ...
[ "def", "render", "(", "self", ",", "apps", ")", ":", "# First, make a Meta object", "meta_contents", "=", "{", "'app_label'", ":", "self", ".", "app_label", ",", "'apps'", ":", "apps", ",", "*", "*", "self", ".", "options", "}", "meta", "=", "type", "(",...
[ 556, 4 ]
[ 577, 43 ]
python
en
['en', 'en', 'en']
True
GeoModelAdmin.media
(self)
Injects OpenLayers JavaScript into the admin.
Injects OpenLayers JavaScript into the admin.
def media(self): "Injects OpenLayers JavaScript into the admin." return super().media + Media(js=[self.openlayers_url] + self.extra_js)
[ "def", "media", "(", "self", ")", ":", "return", "super", "(", ")", ".", "media", "+", "Media", "(", "js", "=", "[", "self", ".", "openlayers_url", "]", "+", "self", ".", "extra_js", ")" ]
[ 47, 4 ]
[ 49, 78 ]
python
en
['en', 'en', 'en']
True
GeoModelAdmin.formfield_for_dbfield
(self, db_field, request, **kwargs)
Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing).
Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing).
def formfield_for_dbfield(self, db_field, request, **kwargs): """ Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing). """ if isinstance(db_field, models.GeometryField) and db_fiel...
[ "def", "formfield_for_dbfield", "(", "self", ",", "db_field", ",", "request", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "db_field", ",", "models", ".", "GeometryField", ")", "and", "db_field", ".", "dim", "<", "3", ":", "# Setting the wid...
[ 51, 4 ]
[ 62, 77 ]
python
en
['en', 'error', 'th']
False
GeoModelAdmin.get_map_widget
(self, db_field)
Return a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class.
Return a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class.
def get_map_widget(self, db_field): """ Return a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class. """ is_collection = db_field.geom_type in ('MULTIPOINT', 'MULTILINESTRING', 'M...
[ "def", "get_map_widget", "(", "self", ",", "db_field", ")", ":", "is_collection", "=", "db_field", ".", "geom_type", "in", "(", "'MULTIPOINT'", ",", "'MULTILINESTRING'", ",", "'MULTIPOLYGON'", ",", "'GEOMETRYCOLLECTION'", ")", "if", "is_collection", ":", "if", "...
[ 64, 4 ]
[ 123, 20 ]
python
en
['en', 'error', 'th']
False
UserAdmin.get_form
(self, request, obj=None, **kwargs)
Use special form during user creation
Use special form during user creation
def get_form(self, request, obj=None, **kwargs): """ Use special form during user creation """ defaults = {} if obj is None: defaults['form'] = self.add_form defaults.update(kwargs) return super(UserAdmin, self).get_form(request, obj, **defaults)
[ "def", "get_form", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "defaults", "=", "{", "}", "if", "obj", "is", "None", ":", "defaults", "[", "'form'", "]", "=", "self", ".", "add_form", "defaults", ".", ...
[ 69, 4 ]
[ 77, 72 ]
python
en
['en', 'error', 'th']
False
UserAdmin.response_add
(self, request, obj, post_url_continue=None)
Determines the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow.
Determines the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow.
def response_add(self, request, obj, post_url_continue=None): """ Determines the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow. """ # We should allow furthe...
[ "def", "response_add", "(", "self", ",", "request", ",", "obj", ",", "post_url_continue", "=", "None", ")", ":", "# We should allow further modification of the user just added i.e. the", "# 'Save' button should behave like the 'Save and continue editing'", "# button except in two sce...
[ 165, 4 ]
[ 179, 69 ]
python
en
['en', 'error', 'th']
False
Person.get_full_name
(self)
Get the full name of the person
Get the full name of the person
def get_full_name(self): """ Get the full name of the person """ return self._get_full_name()
[ "def", "get_full_name", "(", "self", ")", ":", "return", "self", ".", "_get_full_name", "(", ")" ]
[ 41, 4 ]
[ 45, 36 ]
python
en
['en', 'error', 'th']
False
add_stderr_logger
(level=logging.DEBUG)
Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding it.
Helper for quickly adding a StreamHandler to the logger. Useful for debugging.
def add_stderr_logger(level=logging.DEBUG): """ Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding it. """ # This method needs to be in this __init__.py to get the __name__ correct # even if urllib3 is vendored within another pack...
[ "def", "add_stderr_logger", "(", "level", "=", "logging", ".", "DEBUG", ")", ":", "# This method needs to be in this __init__.py to get the __name__ correct", "# even if urllib3 is vendored within another package.", "logger", "=", "logging", ".", "getLogger", "(", "__name__", "...
[ 46, 0 ]
[ 61, 18 ]
python
en
['en', 'error', 'th']
False
disable_warnings
(category=exceptions.HTTPWarning)
Helper for quickly disabling all urllib3 warnings.
Helper for quickly disabling all urllib3 warnings.
def disable_warnings(category=exceptions.HTTPWarning): """ Helper for quickly disabling all urllib3 warnings. """ warnings.simplefilter("ignore", category)
[ "def", "disable_warnings", "(", "category", "=", "exceptions", ".", "HTTPWarning", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ",", "category", ")" ]
[ 81, 0 ]
[ 85, 45 ]
python
en
['en', 'error', 'th']
False
getTreeWalker
(treeType, implementation=None, **kwargs)
Get a TreeWalker class for various types of tree with built-in support :arg str treeType: the name of the tree type required (case-insensitive). Supported values are: * "dom": The xml.dom.minidom DOM implementation * "etree": A generic walker for tree implementations exposing an ...
Get a TreeWalker class for various types of tree with built-in support
def getTreeWalker(treeType, implementation=None, **kwargs): """Get a TreeWalker class for various types of tree with built-in support :arg str treeType: the name of the tree type required (case-insensitive). Supported values are: * "dom": The xml.dom.minidom DOM implementation * "etree...
[ "def", "getTreeWalker", "(", "treeType", ",", "implementation", "=", "None", ",", "*", "*", "kwargs", ")", ":", "treeType", "=", "treeType", ".", "lower", "(", ")", "if", "treeType", "not", "in", "treeWalkerCache", ":", "if", "treeType", "==", "\"dom\"", ...
[ 20, 0 ]
[ 61, 40 ]
python
en
['en', 'en', 'en']
True
pprint
(walker)
Pretty printer for tree walkers Takes a TreeWalker instance and pretty prints the output of walking the tree. :arg walker: a TreeWalker instance
Pretty printer for tree walkers
def pprint(walker): """Pretty printer for tree walkers Takes a TreeWalker instance and pretty prints the output of walking the tree. :arg walker: a TreeWalker instance """ output = [] indent = 0 for token in concatenateCharacterTokens(walker): type = token["type"] if type ...
[ "def", "pprint", "(", "walker", ")", ":", "output", "=", "[", "]", "indent", "=", "0", "for", "token", "in", "concatenateCharacterTokens", "(", "walker", ")", ":", "type", "=", "token", "[", "\"type\"", "]", "if", "type", "in", "(", "\"StartTag\"", ","...
[ 79, 0 ]
[ 153, 28 ]
python
en
['en', 'en', 'en']
True
Interact.sqs_interact_processing
(self, event, dummy)
This function always return True to discard the message in all case.
def sqs_interact_processing(self, event, dummy): """ This function always return True to discard the message in all case. """ event = json.loads(event["body"]) if "OpType" not in event: log.warning("Can't understand SQS message! (Missing 'OpType' required member of...
[ "def", "sqs_interact_processing", "(", "self", ",", "event", ",", "dummy", ")", ":", "event", "=", "json", ".", "loads", "(", "event", "[", "\"body\"", "]", ")", "if", "\"OpType\"", "not", "in", "event", ":", "log", ".", "warning", "(", "\"Can't understa...
[ 539, 4 ]
[ 574, 19 ]
python
en
['en', 'error', 'th']
False
Interact.pregenerate_interact_data
(self)
In order to keep the API Gateway fast, we pre-compute some data during the the processing of the Main Lambda function.
In order to keep the API Gateway fast, we pre-compute some data during the the processing of the Main Lambda function.
def pregenerate_interact_data(self): """ In order to keep the API Gateway fast, we pre-compute some data during the the processing of the Main Lambda function. """ interact_precomputed_data = { "data": {} } for api in self.commands.keys(): ...
[ "def", "pregenerate_interact_data", "(", "self", ")", ":", "interact_precomputed_data", "=", "{", "\"data\"", ":", "{", "}", "}", "for", "api", "in", "self", ".", "commands", ".", "keys", "(", ")", ":", "cmd", "=", "self", ".", "commands", "[", "api", ...
[ 577, 4 ]
[ 588, 63 ]
python
en
['en', 'en', 'en']
True
Join.as_sql
(self, compiler, connection)
Generate the full LEFT OUTER JOIN sometable ON sometable.somecol = othertable.othercol, params clause for this join.
Generate the full LEFT OUTER JOIN sometable ON sometable.somecol = othertable.othercol, params clause for this join.
def as_sql(self, compiler, connection): """ Generate the full LEFT OUTER JOIN sometable ON sometable.somecol = othertable.othercol, params clause for this join. """ join_conditions = [] params = [] qn = compiler.quote_name_unless_alias qn2 = con...
[ "def", "as_sql", "(", "self", ",", "compiler", ",", "connection", ")", ":", "join_conditions", "=", "[", "]", "params", "=", "[", "]", "qn", "=", "compiler", ".", "quote_name_unless_alias", "qn2", "=", "connection", ".", "ops", ".", "quote_name", "# Add a ...
[ 60, 4 ]
[ 103, 26 ]
python
en
['en', 'error', 'th']
False
uts46_remap
(domain, std3_rules=True, transitional=False)
Re-map the characters in the string according to UTS46 processing.
Re-map the characters in the string according to UTS46 processing.
def uts46_remap(domain, std3_rules=True, transitional=False): """Re-map the characters in the string according to UTS46 processing.""" from .uts46data import uts46data output = u"" try: for pos, char in enumerate(domain): code_point = ord(char) uts46row = uts46data[code_p...
[ "def", "uts46_remap", "(", "domain", ",", "std3_rules", "=", "True", ",", "transitional", "=", "False", ")", ":", "from", ".", "uts46data", "import", "uts46data", "output", "=", "u\"\"", "try", ":", "for", "pos", ",", "char", "in", "enumerate", "(", "dom...
[ 313, 0 ]
[ 338, 54 ]
python
en
['en', 'en', 'en']
True
initial_password
(email: str)
Given an email address, returns the initial password for that account, as created by populate_db.
Given an email address, returns the initial password for that account, as created by populate_db.
def initial_password(email: str) -> Optional[str]: """Given an email address, returns the initial password for that account, as created by populate_db.""" if settings.INITIAL_PASSWORD_SALT is not None: encoded_key = (settings.INITIAL_PASSWORD_SALT + email).encode("utf-8") digest = hashlib.s...
[ "def", "initial_password", "(", "email", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "if", "settings", ".", "INITIAL_PASSWORD_SALT", "is", "not", "None", ":", "encoded_key", "=", "(", "settings", ".", "INITIAL_PASSWORD_SALT", "+", "email", ")", ...
[ 7, 0 ]
[ 17, 19 ]
python
en
['en', 'en', 'en']
True
Timeout.reset
(self)
Reset the timeout to the current instant.
Reset the timeout to the current instant.
def reset(self): """ Reset the timeout to the current instant. """ self.start = time.time()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "start", "=", "time", ".", "time", "(", ")" ]
[ 24, 4 ]
[ 28, 32 ]
python
en
['en', 'error', 'th']
False
EventedTimeout.check
(self, reset=True)
Check if we're timed out; if we are, call the `on_timeout` callback and reset the timeout (if `reset` is set). :param reset: Whether to reset the timeout when ticking. :type reset: bool :return: A tuple of a boolean and the retval of `on_timeout`. :rtype: tuple[bool, o...
Check if we're timed out; if we are, call the `on_timeout` callback and reset the timeout (if `reset` is set).
def check(self, reset=True): """ Check if we're timed out; if we are, call the `on_timeout` callback and reset the timeout (if `reset` is set). :param reset: Whether to reset the timeout when ticking. :type reset: bool :return: A tuple of a boolean and the retval of `on...
[ "def", "check", "(", "self", ",", "reset", "=", "True", ")", ":", "if", "self", ".", "timed_out", ":", "if", "reset", ":", "self", ".", "reset", "(", ")", "return", "(", "True", ",", "self", ".", "on_timeout", "(", ")", ")", "return", "(", "False...
[ 41, 4 ]
[ 56, 28 ]
python
en
['en', 'error', 'th']
False
TestUtilsChecksums.check_output
(self, function, value, output=None)
Check that function(value) equals output. If output is None, check that function(value) equals value.
Check that function(value) equals output. If output is None, check that function(value) equals value.
def check_output(self, function, value, output=None): """ Check that function(value) equals output. If output is None, check that function(value) equals value. """ if output is None: output = value self.assertEqual(function(value), output)
[ "def", "check_output", "(", "self", ",", "function", ",", "value", ",", "output", "=", "None", ")", ":", "if", "output", "is", "None", ":", "output", "=", "value", "self", ".", "assertEqual", "(", "function", "(", "value", ")", ",", "output", ")" ]
[ 7, 4 ]
[ 14, 49 ]
python
en
['en', 'error', 'th']
False
DefaultLoader.test_loader
(self)
Normal module existence can be tested
Normal module existence can be tested
def test_loader(self): "Normal module existence can be tested" test_module = import_module('utils_tests.test_module') test_no_submodule = import_module( 'utils_tests.test_no_submodule') # An importable child self.assertTrue(module_has_submodule(test_module, 'good_mod...
[ "def", "test_loader", "(", "self", ")", ":", "test_module", "=", "import_module", "(", "'utils_tests.test_module'", ")", "test_no_submodule", "=", "import_module", "(", "'utils_tests.test_no_submodule'", ")", "# An importable child", "self", ".", "assertTrue", "(", "mod...
[ 25, 4 ]
[ 55, 53 ]
python
en
['en', 'en', 'en']
True
EggLoader.test_shallow_loader
(self)
Module existence can be tested inside eggs
Module existence can be tested inside eggs
def test_shallow_loader(self): "Module existence can be tested inside eggs" egg_name = '%s/test_egg.egg' % self.egg_dir with extend_sys_path(egg_name): egg_module = import_module('egg_module') # An importable child self.assertTrue(module_has_submodule(egg_mod...
[ "def", "test_shallow_loader", "(", "self", ")", ":", "egg_name", "=", "'%s/test_egg.egg'", "%", "self", ".", "egg_dir", "with", "extend_sys_path", "(", "egg_name", ")", ":", "egg_module", "=", "import_module", "(", "'egg_module'", ")", "# An importable child", "se...
[ 73, 4 ]
[ 90, 86 ]
python
en
['en', 'en', 'en']
True
EggLoader.test_deep_loader
(self)
Modules deep inside an egg can still be tested for existence
Modules deep inside an egg can still be tested for existence
def test_deep_loader(self): "Modules deep inside an egg can still be tested for existence" egg_name = '%s/test_egg.egg' % self.egg_dir with extend_sys_path(egg_name): egg_module = import_module('egg_module.sub1.sub2') # An importable child self.assertTrue(mod...
[ "def", "test_deep_loader", "(", "self", ")", ":", "egg_name", "=", "'%s/test_egg.egg'", "%", "self", ".", "egg_dir", "with", "extend_sys_path", "(", "egg_name", ")", ":", "egg_module", "=", "import_module", "(", "'egg_module.sub1.sub2'", ")", "# An importable child"...
[ 92, 4 ]
[ 109, 96 ]
python
en
['en', 'en', 'en']
True
ModuleImportTestCase.test_import_error_traceback
(self)
Test preserving the original traceback on an ImportError.
Test preserving the original traceback on an ImportError.
def test_import_error_traceback(self): """Test preserving the original traceback on an ImportError.""" try: import_by_path('test_module.bad_module.content') except ImproperlyConfigured: traceback = sys.exc_info()[2] self.assertIsNotNone(traceback.tb_next.tb_next,...
[ "def", "test_import_error_traceback", "(", "self", ")", ":", "try", ":", "import_by_path", "(", "'test_module.bad_module.content'", ")", "except", "ImproperlyConfigured", ":", "traceback", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "self", ".", "asser...
[ 125, 4 ]
[ 133, 72 ]
python
en
['en', 'en', 'en']
True
ListMixinTest.test01_getslice
(self)
Slice retrieval
Slice retrieval
def test01_getslice(self): 'Slice retrieval' pl, ul = self.lists_of_len() for i in self.limits_plus(1): self.assertEqual(pl[i:], ul[i:], 'slice [%d:]' % (i)) self.assertEqual(pl[:i], ul[:i], 'slice [:%d]' % (i)) for j in self.limits_plus(1): s...
[ "def", "test01_getslice", "(", "self", ")", ":", "pl", ",", "ul", "=", "self", ".", "lists_of_len", "(", ")", "for", "i", "in", "self", ".", "limits_plus", "(", "1", ")", ":", "self", ".", "assertEqual", "(", "pl", "[", "i", ":", "]", ",", "ul", ...
[ 76, 4 ]
[ 93, 68 ]
python
en
['en', 'sk', 'it']
False
ListMixinTest.test02_setslice
(self)
Slice assignment
Slice assignment
def test02_setslice(self): 'Slice assignment' def setfcn(x, i, j, k, L): x[i:j:k] = range(L) pl, ul = self.lists_of_len() for slen in range(self.limit + 1): ssl = nextRange(slen) ul[:] = ssl pl[:] = ssl self.assertEqual(pl, ul[:...
[ "def", "test02_setslice", "(", "self", ")", ":", "def", "setfcn", "(", "x", ",", "i", ",", "j", ",", "k", ",", "L", ")", ":", "x", "[", "i", ":", "j", ":", "k", "]", "=", "range", "(", "L", ")", "pl", ",", "ul", "=", "self", ".", "lists_o...
[ 95, 4 ]
[ 149, 69 ]
python
en
['en', 'en', 'en']
False
ListMixinTest.test03_delslice
(self)
Delete slice
Delete slice
def test03_delslice(self): 'Delete slice' for Len in range(self.limit): pl, ul = self.lists_of_len(Len) del pl[:] del ul[:] self.assertEqual(pl[:], ul[:], 'del slice [:]') for i in range(-Len - 1, Len + 1): pl, ul = self.lists_o...
[ "def", "test03_delslice", "(", "self", ")", ":", "for", "Len", "in", "range", "(", "self", ".", "limit", ")", ":", "pl", ",", "ul", "=", "self", ".", "lists_of_len", "(", "Len", ")", "del", "pl", "[", ":", "]", "del", "ul", "[", ":", "]", "self...
[ 151, 4 ]
[ 193, 72 ]
python
et
['et', 'sl', 'sw']
False
ListMixinTest.test04_get_set_del_single
(self)
Get/set/delete single item
Get/set/delete single item
def test04_get_set_del_single(self): 'Get/set/delete single item' pl, ul = self.lists_of_len() for i in self.limits_plus(0): self.assertEqual(pl[i], ul[i], 'get single item [%d]' % i) for i in self.limits_plus(0): pl, ul = self.lists_of_len() pl[i] = ...
[ "def", "test04_get_set_del_single", "(", "self", ")", ":", "pl", ",", "ul", "=", "self", ".", "lists_of_len", "(", ")", "for", "i", "in", "self", ".", "limits_plus", "(", "0", ")", ":", "self", ".", "assertEqual", "(", "pl", "[", "i", "]", ",", "ul...
[ 195, 4 ]
[ 211, 70 ]
python
da
['et', 'da', 'en']
False
ListMixinTest.test05_out_of_range_exceptions
(self)
Out of range exceptions
Out of range exceptions
def test05_out_of_range_exceptions(self): 'Out of range exceptions' def setfcn(x, i): x[i] = 20 def getfcn(x, i): return x[i] def delfcn(x, i): del x[i] pl, ul = self.lists_of_len() for i in (-1 - self.limit, self.limit): ...
[ "def", "test05_out_of_range_exceptions", "(", "self", ")", ":", "def", "setfcn", "(", "x", ",", "i", ")", ":", "x", "[", "i", "]", "=", "20", "def", "getfcn", "(", "x", ",", "i", ")", ":", "return", "x", "[", "i", "]", "def", "delfcn", "(", "x"...
[ 213, 4 ]
[ 227, 56 ]
python
en
['en', 'en', 'en']
True
ListMixinTest.test06_list_methods
(self)
List methods
List methods
def test06_list_methods(self): 'List methods' pl, ul = self.lists_of_len() pl.append(40) ul.append(40) self.assertEqual(pl[:], ul[:], 'append') pl.extend(range(50, 55)) ul.extend(range(50, 55)) self.assertEqual(pl[:], ul[:], 'extend') pl.reverse(...
[ "def", "test06_list_methods", "(", "self", ")", ":", "pl", ",", "ul", "=", "self", ".", "lists_of_len", "(", ")", "pl", ".", "append", "(", "40", ")", "ul", ".", "append", "(", "40", ")", "self", ".", "assertEqual", "(", "pl", "[", ":", "]", ",",...
[ 229, 4 ]
[ 285, 56 ]
python
en
['en', 'et', 'en']
False
ListMixinTest.test07_allowed_types
(self)
Type-restricted list
Type-restricted list
def test07_allowed_types(self): 'Type-restricted list' pl, ul = self.lists_of_len() ul._allowed = six.integer_types ul[1] = 50 ul[:2] = [60, 70, 80] def setfcn(x, i, v): x[i] = v self.assertRaises(TypeError, setfcn, ul, 2, 'hello') self.assert...
[ "def", "test07_allowed_types", "(", "self", ")", ":", "pl", ",", "ul", "=", "self", ".", "lists_of_len", "(", ")", "ul", ".", "_allowed", "=", "six", ".", "integer_types", "ul", "[", "1", "]", "=", "50", "ul", "[", ":", "2", "]", "=", "[", "60", ...
[ 287, 4 ]
[ 297, 86 ]
python
en
['en', 'en', 'en']
False
ListMixinTest.test08_min_length
(self)
Length limits
Length limits
def test08_min_length(self): 'Length limits' pl, ul = self.lists_of_len() ul._minlength = 1 def delfcn(x, i): del x[:i] def setfcn(x, i): x[:i] = [] for i in range(self.limit - ul._minlength + 1, self.limit + 1): self.assertRaises(Val...
[ "def", "test08_min_length", "(", "self", ")", ":", "pl", ",", "ul", "=", "self", ".", "lists_of_len", "(", ")", "ul", ".", "_minlength", "=", "1", "def", "delfcn", "(", "x", ",", "i", ")", ":", "del", "x", "[", ":", "i", "]", "def", "setfcn", "...
[ 299, 4 ]
[ 317, 52 ]
python
en
['en', 'bg', 'en']
False
ListMixinTest.test09_iterable_check
(self)
Error on assigning non-iterable to slice
Error on assigning non-iterable to slice
def test09_iterable_check(self): 'Error on assigning non-iterable to slice' pl, ul = self.lists_of_len(self.limit + 1) def setfcn(x, i, v): x[i] = v self.assertRaises(TypeError, setfcn, ul, slice(0, 3, 2), 2)
[ "def", "test09_iterable_check", "(", "self", ")", ":", "pl", ",", "ul", "=", "self", ".", "lists_of_len", "(", "self", ".", "limit", "+", "1", ")", "def", "setfcn", "(", "x", ",", "i", ",", "v", ")", ":", "x", "[", "i", "]", "=", "v", "self", ...
[ 319, 4 ]
[ 325, 67 ]
python
en
['en', 'en', 'en']
True
ListMixinTest.test10_checkindex
(self)
Index check
Index check
def test10_checkindex(self): 'Index check' pl, ul = self.lists_of_len() for i in self.limits_plus(0): if i < 0: self.assertEqual(ul._checkindex(i), i + self.limit, '_checkindex(neg index)') else: self.assertEqual(ul._checkindex(i), i, '_che...
[ "def", "test10_checkindex", "(", "self", ")", ":", "pl", ",", "ul", "=", "self", ".", "lists_of_len", "(", ")", "for", "i", "in", "self", ".", "limits_plus", "(", "0", ")", ":", "if", "i", "<", "0", ":", "self", ".", "assertEqual", "(", "ul", "."...
[ 327, 4 ]
[ 340, 69 ]
python
en
['en', 'en', 'en']
False
getrgb
(color)
Convert a color string to an RGB tuple. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception. .. versionadded:: 1.1.4 :param color: A color string :return: ``(red, green, blue[, alpha])``
Convert a color string to an RGB tuple. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception.
def getrgb(color): """ Convert a color string to an RGB tuple. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception. .. versionadded:: 1.1.4 :param color: A color string :return: ``(red, green, blue[, alpha])`` """ color = color.lower() rgb = col...
[ "def", "getrgb", "(", "color", ")", ":", "color", "=", "color", ".", "lower", "(", ")", "rgb", "=", "colormap", ".", "get", "(", "color", ",", "None", ")", "if", "rgb", ":", "if", "isinstance", "(", "rgb", ",", "tuple", ")", ":", "return", "rgb",...
[ 24, 0 ]
[ 115, 59 ]
python
en
['en', 'error', 'th']
False
getcolor
(color, mode)
Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a greyscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception. .. versionadded:: 1.1.4 :param color: A color string :return: ``(grayl...
Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a greyscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception.
def getcolor(color, mode): """ Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a greyscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception. .. versionadded:: 1.1.4 :param color: A ...
[ "def", "getcolor", "(", "color", ",", "mode", ")", ":", "# same as getrgb, but converts the result to the given mode", "color", ",", "alpha", "=", "getrgb", "(", "color", ")", ",", "255", "if", "len", "(", "color", ")", "==", "4", ":", "color", ",", "alpha",...
[ 118, 0 ]
[ 144, 16 ]
python
en
['en', 'error', 'th']
False
_unique_everseen
(iterable, key=None)
List unique elements, preserving order. Remember all elements ever seen.
List unique elements, preserving order. Remember all elements ever seen.
def _unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in filter...
[ "def", "_unique_everseen", "(", "iterable", ",", "key", "=", "None", ")", ":", "# unique_everseen('AAAABBBCCDAABBB') --> A B C D", "# unique_everseen('ABBCcAD', str.lower) --> A B C D", "seen", "=", "set", "(", ")", "seen_add", "=", "seen", ".", "add", "if", "key", "i...
[ 244, 0 ]
[ 259, 29 ]
python
ca
['ca', 'ca', 'en']
True
build_py.run
(self)
Build modules, packages, and copy data files to build directory
Build modules, packages, and copy data files to build directory
def run(self): """Build modules, packages, and copy data files to build directory""" if not self.py_modules and not self.packages: return if self.py_modules: self.build_modules() if self.packages: self.build_packages() self.build_package_...
[ "def", "run", "(", "self", ")", ":", "if", "not", "self", ".", "py_modules", "and", "not", "self", ".", "packages", ":", "return", "if", "self", ".", "py_modules", ":", "self", ".", "build_modules", "(", ")", "if", "self", ".", "packages", ":", "self...
[ 47, 4 ]
[ 65, 78 ]
python
en
['en', 'en', 'en']
True
build_py.__getattr__
(self, attr)
lazily compute data files
lazily compute data files
def __getattr__(self, attr): "lazily compute data files" if attr == 'data_files': self.data_files = self._get_data_files() return self.data_files return orig.build_py.__getattr__(self, attr)
[ "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "if", "attr", "==", "'data_files'", ":", "self", ".", "data_files", "=", "self", ".", "_get_data_files", "(", ")", "return", "self", ".", "data_files", "return", "orig", ".", "build_py", ".", "__g...
[ 67, 4 ]
[ 72, 52 ]
python
it
['it', 'it', 'it']
True
build_py._get_data_files
(self)
Generate list of '(package,src_dir,build_dir,filenames)' tuples
Generate list of '(package,src_dir,build_dir,filenames)' tuples
def _get_data_files(self): """Generate list of '(package,src_dir,build_dir,filenames)' tuples""" self.analyze_manifest() return list(map(self._get_pkg_data_files, self.packages or ()))
[ "def", "_get_data_files", "(", "self", ")", ":", "self", ".", "analyze_manifest", "(", ")", "return", "list", "(", "map", "(", "self", ".", "_get_pkg_data_files", ",", "self", ".", "packages", "or", "(", ")", ")", ")" ]
[ 84, 4 ]
[ 87, 71 ]
python
en
['en', 'af', 'en']
True
build_py.find_data_files
(self, package, src_dir)
Return filenames for package's data files in 'src_dir
Return filenames for package's data files in 'src_dir
def find_data_files(self, package, src_dir): """Return filenames for package's data files in 'src_dir'""" patterns = self._get_platform_patterns( self.package_data, package, src_dir, ) globs_expanded = map(glob, patterns) # flatten the expanded...
[ "def", "find_data_files", "(", "self", ",", "package", ",", "src_dir", ")", ":", "patterns", "=", "self", ".", "_get_platform_patterns", "(", "self", ".", "package_data", ",", "package", ",", "src_dir", ",", ")", "globs_expanded", "=", "map", "(", "glob", ...
[ 103, 4 ]
[ 118, 63 ]
python
en
['en', 'no', 'en']
True
build_py.build_package_data
(self)
Copy data files into build directory
Copy data files into build directory
def build_package_data(self): """Copy data files into build directory""" for package, src_dir, build_dir, filenames in self.data_files: for filename in filenames: target = os.path.join(build_dir, filename) self.mkpath(os.path.dirname(target)) s...
[ "def", "build_package_data", "(", "self", ")", ":", "for", "package", ",", "src_dir", ",", "build_dir", ",", "filenames", "in", "self", ".", "data_files", ":", "for", "filename", "in", "filenames", ":", "target", "=", "os", ".", "path", ".", "join", "(",...
[ 120, 4 ]
[ 132, 53 ]
python
en
['en', 'en', 'en']
True
build_py.check_package
(self, package, package_dir)
Check namespace packages' __init__ for declare_namespace
Check namespace packages' __init__ for declare_namespace
def check_package(self, package, package_dir): """Check namespace packages' __init__ for declare_namespace""" try: return self.packages_checked[package] except KeyError: pass init_py = orig.build_py.check_package(self, package, package_dir) self.packages_...
[ "def", "check_package", "(", "self", ",", "package", ",", "package_dir", ")", ":", "try", ":", "return", "self", ".", "packages_checked", "[", "package", "]", "except", "KeyError", ":", "pass", "init_py", "=", "orig", ".", "build_py", ".", "check_package", ...
[ 161, 4 ]
[ 189, 22 ]
python
en
['es', 'en', 'en']
True
build_py.exclude_data_files
(self, package, src_dir, files)
Filter filenames for package's data files in 'src_dir
Filter filenames for package's data files in 'src_dir
def exclude_data_files(self, package, src_dir, files): """Filter filenames for package's data files in 'src_dir'""" files = list(files) patterns = self._get_platform_patterns( self.exclude_package_data, package, src_dir, ) match_groups = ( ...
[ "def", "exclude_data_files", "(", "self", ",", "package", ",", "src_dir", ",", "files", ")", ":", "files", "=", "list", "(", "files", ")", "patterns", "=", "self", ".", "_get_platform_patterns", "(", "self", ".", "exclude_package_data", ",", "package", ",", ...
[ 201, 4 ]
[ 222, 46 ]
python
en
['en', 'en', 'en']
True
build_py._get_platform_patterns
(spec, package, src_dir)
yield platform-specific path patterns (suitable for glob or fn_match) from a glob-based spec (such as self.package_data or self.exclude_package_data) matching package in src_dir.
yield platform-specific path patterns (suitable for glob or fn_match) from a glob-based spec (such as self.package_data or self.exclude_package_data) matching package in src_dir.
def _get_platform_patterns(spec, package, src_dir): """ yield platform-specific path patterns (suitable for glob or fn_match) from a glob-based spec (such as self.package_data or self.exclude_package_data) matching package in src_dir. """ raw_patterns = itertools....
[ "def", "_get_platform_patterns", "(", "spec", ",", "package", ",", "src_dir", ")", ":", "raw_patterns", "=", "itertools", ".", "chain", "(", "spec", ".", "get", "(", "''", ",", "[", "]", ")", ",", "spec", ".", "get", "(", "package", ",", "[", "]", ...
[ 225, 4 ]
[ 240, 9 ]
python
en
['en', 'error', 'th']
False
glob
(pathname, recursive=False)
Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. If recursive is true, the pattern '**' will match any files ...
Return a list of paths matching a pathname pattern.
def glob(pathname, recursive=False): """Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. If recursive is ...
[ "def", "glob", "(", "pathname", ",", "recursive", "=", "False", ")", ":", "return", "list", "(", "iglob", "(", "pathname", ",", "recursive", "=", "recursive", ")", ")" ]
[ 15, 0 ]
[ 26, 53 ]
python
en
['en', 'en', 'en']
True
iglob
(pathname, recursive=False)
Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. If recursive is true, the pattern '**' wi...
Return an iterator which yields the paths matching a pathname pattern.
def iglob(pathname, recursive=False): """Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. However, unlike fnmatch, filenames starting with a dot are special cases that are not matched by '*' and '?' patterns. ...
[ "def", "iglob", "(", "pathname", ",", "recursive", "=", "False", ")", ":", "it", "=", "_iglob", "(", "pathname", ",", "recursive", ")", "if", "recursive", "and", "_isrecursive", "(", "pathname", ")", ":", "s", "=", "next", "(", "it", ")", "# skip empty...
[ 29, 0 ]
[ 44, 13 ]
python
en
['en', 'en', 'en']
True
escape
(pathname)
Escape all special characters.
Escape all special characters.
def escape(pathname): """Escape all special characters. """ # Escaping is done by wrapping any of "*?[" between square brackets. # Metacharacters do not work in the drive part and shouldn't be escaped. drive, pathname = os.path.splitdrive(pathname) if isinstance(pathname, bytes): pathnam...
[ "def", "escape", "(", "pathname", ")", ":", "# Escaping is done by wrapping any of \"*?[\" between square brackets.", "# Metacharacters do not work in the drive part and shouldn't be escaped.", "drive", ",", "pathname", "=", "os", ".", "path", ".", "splitdrive", "(", "pathname", ...
[ 163, 0 ]
[ 173, 27 ]
python
en
['en', 'en', 'en']
True
memoize
(func, cache, num_args)
Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be usable as dictionary keys. Only the first num_args are considered when creating the key.
Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be usable as dictionary keys.
def memoize(func, cache, num_args): """ Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be usable as dictionary keys. Only the first num_args are considered when creating the key. """ warnings.warn("memoize wrapper is dep...
[ "def", "memoize", "(", "func", ",", "cache", ",", "num_args", ")", ":", "warnings", ".", "warn", "(", "\"memoize wrapper is deprecated and will be removed in \"", "\"Django 1.9. Use django.utils.lru_cache instead.\"", ",", "RemovedInDjango19Warning", ",", "stacklevel", "=", ...
[ 20, 0 ]
[ 40, 18 ]
python
en
['en', 'error', 'th']
False
lazy
(func, *resultclasses)
Turns any callable into a lazy evaluated callable. You need to give result classes or types -- at least one is needed so that the automatic forcing of the lazy evaluation code is triggered. Results are not memoized; the function is evaluated on every access.
Turns any callable into a lazy evaluated callable. You need to give result classes or types -- at least one is needed so that the automatic forcing of the lazy evaluation code is triggered. Results are not memoized; the function is evaluated on every access.
def lazy(func, *resultclasses): """ Turns any callable into a lazy evaluated callable. You need to give result classes or types -- at least one is needed so that the automatic forcing of the lazy evaluation code is triggered. Results are not memoized; the function is evaluated on every access. "...
[ "def", "lazy", "(", "func", ",", "*", "resultclasses", ")", ":", "@", "total_ordering", "class", "__proxy__", "(", "Promise", ")", ":", "\"\"\"\n Encapsulate a function call and act as a proxy for methods that are\n called on the result of that function. The function ...
[ 71, 0 ]
[ 198, 22 ]
python
en
['en', 'error', 'th']
False
allow_lazy
(func, *resultclasses)
A decorator that allows a function to be called with one or more lazy arguments. If none of the args are lazy, the function is evaluated immediately, otherwise a __proxy__ is returned that will evaluate the function when needed.
A decorator that allows a function to be called with one or more lazy arguments. If none of the args are lazy, the function is evaluated immediately, otherwise a __proxy__ is returned that will evaluate the function when needed.
def allow_lazy(func, *resultclasses): """ A decorator that allows a function to be called with one or more lazy arguments. If none of the args are lazy, the function is evaluated immediately, otherwise a __proxy__ is returned that will evaluate the function when needed. """ @wraps(func) ...
[ "def", "allow_lazy", "(", "func", ",", "*", "resultclasses", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "arg", "in", "list", "(", "args", ")", "+", "list", "(", "six", ...
[ 205, 0 ]
[ 220, 18 ]
python
en
['en', 'error', 'th']
False
partition
(predicate, values)
Splits the values into two sets, based on the return value of the function (True/False). e.g.: >>> partition(lambda x: x > 3, range(5)) [0, 1, 2, 3], [4]
Splits the values into two sets, based on the return value of the function (True/False). e.g.:
def partition(predicate, values): """ Splits the values into two sets, based on the return value of the function (True/False). e.g.: >>> partition(lambda x: x > 3, range(5)) [0, 1, 2, 3], [4] """ results = ([], []) for item in values: results[predicate(item)].append(item...
[ "def", "partition", "(", "predicate", ",", "values", ")", ":", "results", "=", "(", "[", "]", ",", "[", "]", ")", "for", "item", "in", "values", ":", "results", "[", "predicate", "(", "item", ")", "]", ".", "append", "(", "item", ")", "return", "...
[ 403, 0 ]
[ 414, 18 ]
python
en
['en', 'error', 'th']
False
LazyObject._setup
(self)
Must be implemented by subclasses to initialize the wrapped object.
Must be implemented by subclasses to initialize the wrapped object.
def _setup(self): """ Must be implemented by subclasses to initialize the wrapped object. """ raise NotImplementedError('subclasses of LazyObject must provide a _setup() method')
[ "def", "_setup", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of LazyObject must provide a _setup() method'", ")" ]
[ 266, 4 ]
[ 270, 92 ]
python
en
['en', 'error', 'th']
False
SimpleLazyObject.__init__
(self, func)
Pass in a callable that returns the object to be wrapped. If copies are made of the resulting SimpleLazyObject, which can happen in various circumstances within Django, then you must ensure that the callable can be safely run more than once and will return the same value. ...
Pass in a callable that returns the object to be wrapped.
def __init__(self, func): """ Pass in a callable that returns the object to be wrapped. If copies are made of the resulting SimpleLazyObject, which can happen in various circumstances within Django, then you must ensure that the callable can be safely run more than once and will...
[ "def", "__init__", "(", "self", ",", "func", ")", ":", "self", ".", "__dict__", "[", "'_setupfunc'", "]", "=", "func", "_super", "(", "SimpleLazyObject", ",", "self", ")", ".", "__init__", "(", ")" ]
[ 348, 4 ]
[ 358, 49 ]
python
en
['en', 'error', 'th']
False
fix_upload_links
(data: TableData, message_table: TableName)
Because the URLs for uploaded files encode the realm ID of the organization being imported (which is only determined at import time), we need to rewrite the URLs of links to uploaded files during the import process.
Because the URLs for uploaded files encode the realm ID of the organization being imported (which is only determined at import time), we need to rewrite the URLs of links to uploaded files during the import process.
def fix_upload_links(data: TableData, message_table: TableName) -> None: """ Because the URLs for uploaded files encode the realm ID of the organization being imported (which is only determined at import time), we need to rewrite the URLs of links to uploaded files during the import process. """...
[ "def", "fix_upload_links", "(", "data", ":", "TableData", ",", "message_table", ":", "TableName", ")", "->", "None", ":", "for", "message", "in", "data", "[", "message_table", "]", ":", "if", "message", "[", "\"has_attachment\"", "]", "is", "True", ":", "f...
[ 158, 0 ]
[ 173, 25 ]
python
en
['en', 'error', 'th']
False
create_subscription_events
(data: TableData, realm_id: int)
When the export data doesn't contain the table `zerver_realmauditlog`, this function creates RealmAuditLog objects for `subscription_created` type event for all the existing Stream subscriptions. This is needed for all the export tools which do not include the table `zerver_realmauditlog` (Slack, ...
When the export data doesn't contain the table `zerver_realmauditlog`, this function creates RealmAuditLog objects for `subscription_created` type event for all the existing Stream subscriptions.
def create_subscription_events(data: TableData, realm_id: int) -> None: """ When the export data doesn't contain the table `zerver_realmauditlog`, this function creates RealmAuditLog objects for `subscription_created` type event for all the existing Stream subscriptions. This is needed for all the ...
[ "def", "create_subscription_events", "(", "data", ":", "TableData", ",", "realm_id", ":", "int", ")", "->", "None", ":", "all_subscription_logs", "=", "[", "]", "event_last_message_id", "=", "get_last_message_id", "(", ")", "event_time", "=", "timezone_now", "(", ...
[ 176, 0 ]
[ 216, 60 ]
python
en
['en', 'error', 'th']
False
fix_service_tokens
(data: TableData, table: TableName)
The tokens in the services are created by 'generate_api_key'. As the tokens are unique, they should be re-created for the imports.
The tokens in the services are created by 'generate_api_key'. As the tokens are unique, they should be re-created for the imports.
def fix_service_tokens(data: TableData, table: TableName) -> None: """ The tokens in the services are created by 'generate_api_key'. As the tokens are unique, they should be re-created for the imports. """ for item in data[table]: item["token"] = generate_api_key()
[ "def", "fix_service_tokens", "(", "data", ":", "TableData", ",", "table", ":", "TableName", ")", "->", "None", ":", "for", "item", "in", "data", "[", "table", "]", ":", "item", "[", "\"token\"", "]", "=", "generate_api_key", "(", ")" ]
[ 219, 0 ]
[ 225, 42 ]
python
en
['en', 'error', 'th']
False
process_huddle_hash
(data: TableData, table: TableName)
Build new huddle hashes with the updated ids of the users
Build new huddle hashes with the updated ids of the users
def process_huddle_hash(data: TableData, table: TableName) -> None: """ Build new huddle hashes with the updated ids of the users """ for huddle in data[table]: user_id_list = id_map_to_list["huddle_to_user_list"][huddle["id"]] huddle["huddle_hash"] = get_huddle_hash(user_id_list)
[ "def", "process_huddle_hash", "(", "data", ":", "TableData", ",", "table", ":", "TableName", ")", "->", "None", ":", "for", "huddle", "in", "data", "[", "table", "]", ":", "user_id_list", "=", "id_map_to_list", "[", "\"huddle_to_user_list\"", "]", "[", "hudd...
[ 228, 0 ]
[ 234, 61 ]
python
en
['en', 'error', 'th']
False
get_huddles_from_subscription
(data: TableData, table: TableName)
Extract the IDs of the user_profiles involved in a huddle from the subscription object This helps to generate a unique huddle hash from the updated user_profile ids
Extract the IDs of the user_profiles involved in a huddle from the subscription object This helps to generate a unique huddle hash from the updated user_profile ids
def get_huddles_from_subscription(data: TableData, table: TableName) -> None: """ Extract the IDs of the user_profiles involved in a huddle from the subscription object This helps to generate a unique huddle hash from the updated user_profile ids """ id_map_to_list["huddle_to_user_list"] = { ...
[ "def", "get_huddles_from_subscription", "(", "data", ":", "TableData", ",", "table", ":", "TableName", ")", "->", "None", ":", "id_map_to_list", "[", "\"huddle_to_user_list\"", "]", "=", "{", "value", ":", "[", "]", "for", "value", "in", "ID_MAP", "[", "\"re...
[ 237, 0 ]
[ 249, 100 ]
python
en
['en', 'error', 'th']
False
fix_customprofilefield
(data: TableData)
In CustomProfileField with 'field_type' like 'USER', the IDs need to be re-mapped.
In CustomProfileField with 'field_type' like 'USER', the IDs need to be re-mapped.
def fix_customprofilefield(data: TableData) -> None: """ In CustomProfileField with 'field_type' like 'USER', the IDs need to be re-mapped. """ field_type_USER_id_list = [] for item in data["zerver_customprofilefield"]: if item["field_type"] == CustomProfileField.USER: field_...
[ "def", "fix_customprofilefield", "(", "data", ":", "TableData", ")", "->", "None", ":", "field_type_USER_id_list", "=", "[", "]", "for", "item", "in", "data", "[", "\"zerver_customprofilefield\"", "]", ":", "if", "item", "[", "\"field_type\"", "]", "==", "Cust...
[ 252, 0 ]
[ 272, 62 ]
python
en
['en', 'error', 'th']
False
fix_message_rendered_content
( realm: Realm, sender_map: Dict[int, Record], messages: List[Record] )
This function sets the rendered_content of all the messages after the messages have been imported from a non-Zulip platform.
This function sets the rendered_content of all the messages after the messages have been imported from a non-Zulip platform.
def fix_message_rendered_content( realm: Realm, sender_map: Dict[int, Record], messages: List[Record] ) -> None: """ This function sets the rendered_content of all the messages after the messages have been imported from a non-Zulip platform. """ for message in messages: if message["rende...
[ "def", "fix_message_rendered_content", "(", "realm", ":", "Realm", ",", "sender_map", ":", "Dict", "[", "int", ",", "Record", "]", ",", "messages", ":", "List", "[", "Record", "]", ")", "->", "None", ":", "for", "message", "in", "messages", ":", "if", ...
[ 275, 0 ]
[ 361, 13 ]
python
en
['en', 'error', 'th']
False
current_table_ids
(data: TableData, table: TableName)
Returns the ids present in the current table
Returns the ids present in the current table
def current_table_ids(data: TableData, table: TableName) -> List[int]: """ Returns the ids present in the current table """ id_list = [] for item in data[table]: id_list.append(item["id"]) return id_list
[ "def", "current_table_ids", "(", "data", ":", "TableData", ",", "table", ":", "TableName", ")", "->", "List", "[", "int", "]", ":", "id_list", "=", "[", "]", "for", "item", "in", "data", "[", "table", "]", ":", "id_list", ".", "append", "(", "item", ...
[ 364, 0 ]
[ 371, 18 ]
python
en
['en', 'error', 'th']
False
allocate_ids
(model_class: Any, count: int)
Increases the sequence number for a given table by the amount of objects being imported into that table. Hence, this gives a reserved range of IDs to import the converted Slack objects into the tables.
Increases the sequence number for a given table by the amount of objects being imported into that table. Hence, this gives a reserved range of IDs to import the converted Slack objects into the tables.
def allocate_ids(model_class: Any, count: int) -> List[int]: """ Increases the sequence number for a given table by the amount of objects being imported into that table. Hence, this gives a reserved range of IDs to import the converted Slack objects into the tables. """ conn = connection.cursor(...
[ "def", "allocate_ids", "(", "model_class", ":", "Any", ",", "count", ":", "int", ")", "->", "List", "[", "int", "]", ":", "conn", "=", "connection", ".", "cursor", "(", ")", "sequence", "=", "idseq", "(", "model_class", ")", "conn", ".", "execute", "...
[ 384, 0 ]
[ 396, 38 ]
python
en
['en', 'error', 'th']
False
convert_to_id_fields
(data: TableData, table: TableName, field_name: Field)
When Django gives us dict objects via model_to_dict, the foreign key fields are `foo`, but we want `foo_id` for the bulk insert. This function handles the simple case where we simply rename the fields. For cases where we need to munge ids in the database, see re_map_foreign_keys.
When Django gives us dict objects via model_to_dict, the foreign key fields are `foo`, but we want `foo_id` for the bulk insert. This function handles the simple case where we simply rename the fields. For cases where we need to munge ids in the database, see re_map_foreign_keys.
def convert_to_id_fields(data: TableData, table: TableName, field_name: Field) -> None: """ When Django gives us dict objects via model_to_dict, the foreign key fields are `foo`, but we want `foo_id` for the bulk insert. This function handles the simple case where we simply rename the fields. For c...
[ "def", "convert_to_id_fields", "(", "data", ":", "TableData", ",", "table", ":", "TableName", ",", "field_name", ":", "Field", ")", "->", "None", ":", "for", "item", "in", "data", "[", "table", "]", ":", "item", "[", "field_name", "+", "\"_id\"", "]", ...
[ 399, 0 ]
[ 409, 28 ]
python
en
['en', 'error', 'th']
False
re_map_foreign_keys
( data: TableData, table: TableName, field_name: Field, related_table: TableName, verbose: bool = False, id_field: bool = False, recipient_field: bool = False, reaction_field: bool = False, )
This is a wrapper function for all the realm data tables and only avatar and attachment records need to be passed through the internal function because of the difference in data format (TableData corresponding to realm data tables and List[Record] corresponding to the avatar and attachment records) ...
This is a wrapper function for all the realm data tables and only avatar and attachment records need to be passed through the internal function because of the difference in data format (TableData corresponding to realm data tables and List[Record] corresponding to the avatar and attachment records) ...
def re_map_foreign_keys( data: TableData, table: TableName, field_name: Field, related_table: TableName, verbose: bool = False, id_field: bool = False, recipient_field: bool = False, reaction_field: bool = False, ) -> None: """ This is a wrapper function for all the realm data ta...
[ "def", "re_map_foreign_keys", "(", "data", ":", "TableData", ",", "table", ":", "TableName", ",", "field_name", ":", "Field", ",", "related_table", ":", "TableName", ",", "verbose", ":", "bool", "=", "False", ",", "id_field", ":", "bool", "=", "False", ","...
[ 412, 0 ]
[ 441, 5 ]
python
en
['en', 'error', 'th']
False
re_map_foreign_keys_internal
( data_table: List[Record], table: TableName, field_name: Field, related_table: TableName, verbose: bool = False, id_field: bool = False, recipient_field: bool = False, reaction_field: bool = False, )
We occasionally need to assign new ids to rows during the import/export process, to accommodate things like existing rows already being in tables. See bulk_import_client for more context. The tricky part is making sure that foreign key references are in sync with the new ids, and this fixer funct...
We occasionally need to assign new ids to rows during the import/export process, to accommodate things like existing rows already being in tables. See bulk_import_client for more context.
def re_map_foreign_keys_internal( data_table: List[Record], table: TableName, field_name: Field, related_table: TableName, verbose: bool = False, id_field: bool = False, recipient_field: bool = False, reaction_field: bool = False, ) -> None: """ We occasionally need to assign new...
[ "def", "re_map_foreign_keys_internal", "(", "data_table", ":", "List", "[", "Record", "]", ",", "table", ":", "TableName", ",", "field_name", ":", "Field", ",", "related_table", ":", "TableName", ",", "verbose", ":", "bool", "=", "False", ",", "id_field", ":...
[ 444, 0 ]
[ 500, 41 ]
python
en
['en', 'error', 'th']
False
re_map_foreign_keys_many_to_many
( data: TableData, table: TableName, field_name: Field, related_table: TableName, verbose: bool = False, )
We need to assign new ids to rows during the import/export process. The tricky part is making sure that foreign key references are in sync with the new ids, and this wrapper function does the re-mapping only for ManyToMany fields.
We need to assign new ids to rows during the import/export process.
def re_map_foreign_keys_many_to_many( data: TableData, table: TableName, field_name: Field, related_table: TableName, verbose: bool = False, ) -> None: """ We need to assign new ids to rows during the import/export process. The tricky part is making sure that foreign key references ...
[ "def", "re_map_foreign_keys_many_to_many", "(", "data", ":", "TableData", ",", "table", ":", "TableName", ",", "field_name", ":", "Field", ",", "related_table", ":", "TableName", ",", "verbose", ":", "bool", "=", "False", ",", ")", "->", "None", ":", "for", ...
[ 503, 0 ]
[ 524, 28 ]
python
en
['en', 'error', 'th']
False
re_map_foreign_keys_many_to_many_internal
( table: TableName, field_name: Field, related_table: TableName, old_id_list: List[int], verbose: bool = False, )
This is an internal function for tables with ManyToMany fields, which takes the old ID list of the ManyToMany relation and returns the new updated ID list.
This is an internal function for tables with ManyToMany fields, which takes the old ID list of the ManyToMany relation and returns the new updated ID list.
def re_map_foreign_keys_many_to_many_internal( table: TableName, field_name: Field, related_table: TableName, old_id_list: List[int], verbose: bool = False, ) -> List[int]: """ This is an internal function for tables with ManyToMany fields, which takes the old ID list of the ManyToMany r...
[ "def", "re_map_foreign_keys_many_to_many_internal", "(", "table", ":", "TableName", ",", "field_name", ":", "Field", ",", "related_table", ":", "TableName", ",", "old_id_list", ":", "List", "[", "int", "]", ",", "verbose", ":", "bool", "=", "False", ",", ")", ...
[ 527, 0 ]
[ 551, 22 ]
python
en
['en', 'error', 'th']
False
fix_realm_authentication_bitfield
(data: TableData, table: TableName, field_name: Field)
Used to fixup the authentication_methods bitfield to be a string
Used to fixup the authentication_methods bitfield to be a string
def fix_realm_authentication_bitfield(data: TableData, table: TableName, field_name: Field) -> None: """Used to fixup the authentication_methods bitfield to be a string""" for item in data[table]: values_as_bitstring = "".join("1" if field[1] else "0" for field in item[field_name]) values_as_int...
[ "def", "fix_realm_authentication_bitfield", "(", "data", ":", "TableData", ",", "table", ":", "TableName", ",", "field_name", ":", "Field", ")", "->", "None", ":", "for", "item", "in", "data", "[", "table", "]", ":", "values_as_bitstring", "=", "\"\"", ".", ...
[ 560, 0 ]
[ 565, 40 ]
python
en
['en', 'en', 'en']
True
remove_denormalized_recipient_column_from_data
(data: TableData)
The recipient column shouldn't be imported, we'll set the correct values when Recipient table gets imported.
The recipient column shouldn't be imported, we'll set the correct values when Recipient table gets imported.
def remove_denormalized_recipient_column_from_data(data: TableData) -> None: """ The recipient column shouldn't be imported, we'll set the correct values when Recipient table gets imported. """ for stream_dict in data["zerver_stream"]: if "recipient" in stream_dict: del stream_di...
[ "def", "remove_denormalized_recipient_column_from_data", "(", "data", ":", "TableData", ")", "->", "None", ":", "for", "stream_dict", "in", "data", "[", "\"zerver_stream\"", "]", ":", "if", "\"recipient\"", "in", "stream_dict", ":", "del", "stream_dict", "[", "\"r...
[ 568, 0 ]
[ 583, 40 ]
python
en
['en', 'error', 'th']
False
get_db_table
(model_class: Any)
E.g. (RealmDomain -> 'zerver_realmdomain')
E.g. (RealmDomain -> 'zerver_realmdomain')
def get_db_table(model_class: Any) -> str: """E.g. (RealmDomain -> 'zerver_realmdomain')""" return model_class._meta.db_table
[ "def", "get_db_table", "(", "model_class", ":", "Any", ")", "->", "str", ":", "return", "model_class", ".", "_meta", ".", "db_table" ]
[ 586, 0 ]
[ 588, 37 ]
python
de
['de', 'mg', 'ur']
False
get_incoming_message_ids
(import_dir: Path, sort_by_date: bool)
This function reads in our entire collection of message ids, which can be millions of integers for some installations. And then we sort the list. This is necessary to ensure that the sort order of incoming ids matches the sort order of date_sent, which isn't always guaranteed by our utilities ...
This function reads in our entire collection of message ids, which can be millions of integers for some installations. And then we sort the list. This is necessary to ensure that the sort order of incoming ids matches the sort order of date_sent, which isn't always guaranteed by our utilities ...
def get_incoming_message_ids(import_dir: Path, sort_by_date: bool) -> List[int]: """ This function reads in our entire collection of message ids, which can be millions of integers for some installations. And then we sort the list. This is necessary to ensure that the sort order of incoming ids matc...
[ "def", "get_incoming_message_ids", "(", "import_dir", ":", "Path", ",", "sort_by_date", ":", "bool", ")", "->", "List", "[", "int", "]", ":", "if", "sort_by_date", ":", "tups", ":", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", "=", "[", "]...
[ 1261, 0 ]
[ 1316, 22 ]
python
en
['en', 'error', 'th']
False
get_cache_with_key
( keyfunc: Callable[..., str], cache_name: Optional[str] = None, )
The main goal of this function getting value from the cache like in the "cache_with_key". A cache value can contain any data including the "None", so here used exception for case if value isn't found in the cache.
The main goal of this function getting value from the cache like in the "cache_with_key". A cache value can contain any data including the "None", so here used exception for case if value isn't found in the cache.
def get_cache_with_key( keyfunc: Callable[..., str], cache_name: Optional[str] = None, ) -> Callable[[FuncT], FuncT]: """ The main goal of this function getting value from the cache like in the "cache_with_key". A cache value can contain any data including the "None", so here used exception for ...
[ "def", "get_cache_with_key", "(", "keyfunc", ":", "Callable", "[", "...", ",", "str", "]", ",", "cache_name", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "Callable", "[", "[", "FuncT", "]", ",", "FuncT", "]", ":", "def", "decorator...
[ 131, 0 ]
[ 158, 20 ]
python
en
['en', 'error', 'th']
False
cache_with_key
( keyfunc: Callable[..., str], cache_name: Optional[str] = None, timeout: Optional[int] = None, with_statsd_key: Optional[str] = None, )
Decorator which applies Django caching to a function. Decorator argument is a function which computes a cache key from the original function's arguments. You are responsible for avoiding collisions with other uses of this decorator or other uses of caching.
Decorator which applies Django caching to a function.
def cache_with_key( keyfunc: Callable[..., str], cache_name: Optional[str] = None, timeout: Optional[int] = None, with_statsd_key: Optional[str] = None, ) -> Callable[[FuncT], FuncT]: """Decorator which applies Django caching to a function. Decorator argument is a function which computes a cach...
[ "def", "cache_with_key", "(", "keyfunc", ":", "Callable", "[", "...", ",", "str", "]", ",", "cache_name", ":", "Optional", "[", "str", "]", "=", "None", ",", "timeout", ":", "Optional", "[", "int", "]", "=", "None", ",", "with_statsd_key", ":", "Option...
[ 161, 0 ]
[ 211, 20 ]
python
en
['en', 'en', 'en']
True
safe_cache_get_many
(keys: List[str], cache_name: Optional[str] = None)
Variant of cache_get_many that drops any keys that fail validation, rather than throwing an exception visible to the caller.
Variant of cache_get_many that drops any keys that fail validation, rather than throwing an exception visible to the caller.
def safe_cache_get_many(keys: List[str], cache_name: Optional[str] = None) -> Dict[str, Any]: """Variant of cache_get_many that drops any keys that fail validation, rather than throwing an exception visible to the caller.""" try: # Almost always the keys will all be correct, so we just try ...
[ "def", "safe_cache_get_many", "(", "keys", ":", "List", "[", "str", "]", ",", "cache_name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "try", ":", "# Almost always the keys will all be correct, so we j...
[ 277, 0 ]
[ 291, 52 ]
python
en
['en', 'en', 'en']
True
safe_cache_set_many
( items: Dict[str, Any], cache_name: Optional[str] = None, timeout: Optional[int] = None )
Variant of cache_set_many that drops saving any keys that fail validation, rather than throwing an exception visible to the caller.
Variant of cache_set_many that drops saving any keys that fail validation, rather than throwing an exception visible to the caller.
def safe_cache_set_many( items: Dict[str, Any], cache_name: Optional[str] = None, timeout: Optional[int] = None ) -> None: """Variant of cache_set_many that drops saving any keys that fail validation, rather than throwing an exception visible to the caller.""" try: # Almost always the keys w...
[ "def", "safe_cache_set_many", "(", "items", ":", "Dict", "[", "str", ",", "Any", "]", ",", "cache_name", ":", "Optional", "[", "str", "]", "=", "None", ",", "timeout", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "None", ":", "try", ":...
[ 308, 0 ]
[ 326, 62 ]
python
en
['en', 'en', 'en']
True
ignore_unhashable_lru_cache
( maxsize: int = 128, typed: bool = False )
This is a wrapper over lru_cache function. It adds following features on top of lru_cache: * It will not cache result of functions with unhashable arguments. * It will clear cache whenever zerver.lib.cache.KEY_PREFIX changes.
This is a wrapper over lru_cache function. It adds following features on top of lru_cache:
def ignore_unhashable_lru_cache( maxsize: int = 128, typed: bool = False ) -> Callable[[FuncT], FuncT]: """ This is a wrapper over lru_cache function. It adds following features on top of lru_cache: * It will not cache result of functions with unhashable arguments. * It will clear cache...
[ "def", "ignore_unhashable_lru_cache", "(", "maxsize", ":", "int", "=", "128", ",", "typed", ":", "bool", "=", "False", ")", "->", "Callable", "[", "[", "FuncT", "]", ",", "FuncT", "]", ":", "internal_decorator", "=", "lru_cache", "(", "maxsize", "=", "ma...
[ 738, 0 ]
[ 786, 20 ]
python
en
['en', 'error', 'th']
False
dict_to_items_tuple
(user_function: Callable[..., Any])
Wrapper that converts any dict args to dict item tuples.
Wrapper that converts any dict args to dict item tuples.
def dict_to_items_tuple(user_function: Callable[..., Any]) -> Callable[..., Any]: """Wrapper that converts any dict args to dict item tuples.""" def dict_to_tuple(arg: Any) -> Any: if isinstance(arg, dict): return tuple(sorted(arg.items())) return arg def wrapper(*args: Any, **...
[ "def", "dict_to_items_tuple", "(", "user_function", ":", "Callable", "[", "...", ",", "Any", "]", ")", "->", "Callable", "[", "...", ",", "Any", "]", ":", "def", "dict_to_tuple", "(", "arg", ":", "Any", ")", "->", "Any", ":", "if", "isinstance", "(", ...
[ 789, 0 ]
[ 801, 18 ]
python
en
['en', 'en', 'en']
True
items_tuple_to_dict
(user_function: Callable[..., Any])
Wrapper that converts any dict items tuple args to dicts.
Wrapper that converts any dict items tuple args to dicts.
def items_tuple_to_dict(user_function: Callable[..., Any]) -> Callable[..., Any]: """Wrapper that converts any dict items tuple args to dicts.""" def dict_items_to_dict(arg: Any) -> Any: if isinstance(arg, tuple): try: return dict(arg) except TypeError: ...
[ "def", "items_tuple_to_dict", "(", "user_function", ":", "Callable", "[", "...", ",", "Any", "]", ")", "->", "Callable", "[", "...", ",", "Any", "]", ":", "def", "dict_items_to_dict", "(", "arg", ":", "Any", ")", "->", "Any", ":", "if", "isinstance", "...
[ 804, 0 ]
[ 820, 18 ]
python
en
['en', 'en', 'en']
True
PermWrapperTests.test_permwrapper_in
(self)
Test that 'something' in PermWrapper works as expected.
Test that 'something' in PermWrapper works as expected.
def test_permwrapper_in(self): """ Test that 'something' in PermWrapper works as expected. """ perms = PermWrapper(MockUser()) # Works for modules and full permissions. self.assertTrue('mockapp' in perms) self.assertFalse('nonexisting' in perms) self.asser...
[ "def", "test_permwrapper_in", "(", "self", ")", ":", "perms", "=", "PermWrapper", "(", "MockUser", "(", ")", ")", "# Works for modules and full permissions.", "self", ".", "assertTrue", "(", "'mockapp'", "in", "perms", ")", "self", ".", "assertFalse", "(", "'non...
[ 41, 4 ]
[ 50, 56 ]
python
en
['en', 'error', 'th']
False
PermWrapperTests.test_permlookupdict_in
(self)
No endless loops if accessed with 'in' - refs #18979.
No endless loops if accessed with 'in' - refs #18979.
def test_permlookupdict_in(self): """ No endless loops if accessed with 'in' - refs #18979. """ pldict = PermLookupDict(MockUser(), 'mockapp') with self.assertRaises(TypeError): self.EQLimiterObject() in pldict
[ "def", "test_permlookupdict_in", "(", "self", ")", ":", "pldict", "=", "PermLookupDict", "(", "MockUser", "(", ")", ",", "'mockapp'", ")", "with", "self", ".", "assertRaises", "(", "TypeError", ")", ":", "self", ".", "EQLimiterObject", "(", ")", "in", "pld...
[ 52, 4 ]
[ 58, 44 ]
python
en
['en', 'error', 'th']
False
DatabaseValidation.check_field_type
(self, field, field_type)
MySQL has the following field length restriction: No character (varchar) fields can have a length exceeding 255 characters if they have a unique index on them. MySQL doesn't support a database index on some data types.
MySQL has the following field length restriction: No character (varchar) fields can have a length exceeding 255 characters if they have a unique index on them. MySQL doesn't support a database index on some data types.
def check_field_type(self, field, field_type): """ MySQL has the following field length restriction: No character (varchar) fields can have a length exceeding 255 characters if they have a unique index on them. MySQL doesn't support a database index on some data types. ""...
[ "def", "check_field_type", "(", "self", ",", "field", ",", "field_type", ")", ":", "errors", "=", "[", "]", "if", "(", "field_type", ".", "startswith", "(", "'varchar'", ")", "and", "field", ".", "unique", "and", "(", "field", ".", "max_length", "is", ...
[ 28, 4 ]
[ 59, 21 ]
python
en
['en', 'error', 'th']
False
all_frames
(im, func=None)
Applies a given function to all frames in an image or a list of images. The frames are returned as a list of separate images. :param im: An image, or a list of images. :param func: The function to apply to all of the image frames. :returns: A list of images.
Applies a given function to all frames in an image or a list of images. The frames are returned as a list of separate images.
def all_frames(im, func=None): """ Applies a given function to all frames in an image or a list of images. The frames are returned as a list of separate images. :param im: An image, or a list of images. :param func: The function to apply to all of the image frames. :returns: A list of images. ...
[ "def", "all_frames", "(", "im", ",", "func", "=", "None", ")", ":", "if", "not", "isinstance", "(", "im", ",", "list", ")", ":", "im", "=", "[", "im", "]", "ims", "=", "[", "]", "for", "imSequence", "in", "im", ":", "current", "=", "imSequence", ...
[ 55, 0 ]
[ 74, 52 ]
python
en
['en', 'error', 'th']
False
CookieStorage._get
(self, *args, **kwargs)
Retrieve a list of messages from the messages cookie. If the not_finished sentinel value is found at the end of the message list, remove it and return a result indicating that not all messages were retrieved by this storage.
Retrieve a list of messages from the messages cookie. If the not_finished sentinel value is found at the end of the message list, remove it and return a result indicating that not all messages were retrieved by this storage.
def _get(self, *args, **kwargs): """ Retrieve a list of messages from the messages cookie. If the not_finished sentinel value is found at the end of the message list, remove it and return a result indicating that not all messages were retrieved by this storage. """ ...
[ "def", "_get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "request", ".", "COOKIES", ".", "get", "(", "self", ".", "cookie_name", ")", "messages", "=", "self", ".", "_decode", "(", "data", ")", "al...
[ 62, 4 ]
[ 75, 38 ]
python
en
['en', 'error', 'th']
False
CookieStorage._update_cookie
(self, encoded_data, response)
Either set the cookie with the encoded data if there is any data to store, or delete the cookie.
Either set the cookie with the encoded data if there is any data to store, or delete the cookie.
def _update_cookie(self, encoded_data, response): """ Either set the cookie with the encoded data if there is any data to store, or delete the cookie. """ if encoded_data: response.set_cookie( self.cookie_name, encoded_data, domain=sett...
[ "def", "_update_cookie", "(", "self", ",", "encoded_data", ",", "response", ")", ":", "if", "encoded_data", ":", "response", ".", "set_cookie", "(", "self", ".", "cookie_name", ",", "encoded_data", ",", "domain", "=", "settings", ".", "SESSION_COOKIE_DOMAIN", ...
[ 77, 4 ]
[ 91, 91 ]
python
en
['en', 'error', 'th']
False
CookieStorage._store
(self, messages, response, remove_oldest=True, *args, **kwargs)
Store the messages to a cookie and return a list of any messages which could not be stored. If the encoded data is larger than ``max_cookie_size``, remove messages until the data fits (these are the messages which are returned), and add the not_finished sentinel value to indica...
Store the messages to a cookie and return a list of any messages which could not be stored.
def _store(self, messages, response, remove_oldest=True, *args, **kwargs): """ Store the messages to a cookie and return a list of any messages which could not be stored. If the encoded data is larger than ``max_cookie_size``, remove messages until the data fits (these are the m...
[ "def", "_store", "(", "self", ",", "messages", ",", "response", ",", "remove_oldest", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "unstored_messages", "=", "[", "]", "encoded_data", "=", "self", ".", "_encode", "(", "messages", ")...
[ 93, 4 ]
[ 120, 32 ]
python
en
['en', 'error', 'th']
False
CookieStorage._hash
(self, value)
Create an HMAC/SHA1 hash based on the value and the project setting's SECRET_KEY, modified to make it unique for the present purpose.
Create an HMAC/SHA1 hash based on the value and the project setting's SECRET_KEY, modified to make it unique for the present purpose.
def _hash(self, value): """ Create an HMAC/SHA1 hash based on the value and the project setting's SECRET_KEY, modified to make it unique for the present purpose. """ key_salt = 'django.contrib.messages' return salted_hmac(key_salt, value).hexdigest()
[ "def", "_hash", "(", "self", ",", "value", ")", ":", "key_salt", "=", "'django.contrib.messages'", "return", "salted_hmac", "(", "key_salt", ",", "value", ")", ".", "hexdigest", "(", ")" ]
[ 122, 4 ]
[ 128, 55 ]
python
en
['en', 'error', 'th']
False
CookieStorage._encode
(self, messages, encode_empty=False)
Return an encoded version of the messages list which can be stored as plain text. Since the data will be retrieved from the client-side, the encoded data also contains a hash to ensure that the data was not tampered with.
Return an encoded version of the messages list which can be stored as plain text.
def _encode(self, messages, encode_empty=False): """ Return an encoded version of the messages list which can be stored as plain text. Since the data will be retrieved from the client-side, the encoded data also contains a hash to ensure that the data was not tampered with. ...
[ "def", "_encode", "(", "self", ",", "messages", ",", "encode_empty", "=", "False", ")", ":", "if", "messages", "or", "encode_empty", ":", "encoder", "=", "MessageEncoder", "(", "separators", "=", "(", "','", ",", "':'", ")", ")", "value", "=", "encoder",...
[ 130, 4 ]
[ 141, 55 ]
python
en
['en', 'error', 'th']
False
CookieStorage._decode
(self, data)
Safely decode an encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, return None.
Safely decode an encoded text stream back into a list of messages.
def _decode(self, data): """ Safely decode an encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, return None. """ if not data: return None bits = data.split('$', 1) ...
[ "def", "_decode", "(", "self", ",", "data", ")", ":", "if", "not", "data", ":", "return", "None", "bits", "=", "data", ".", "split", "(", "'$'", ",", "1", ")", "if", "len", "(", "bits", ")", "==", "2", ":", "hash", ",", "value", "=", "bits", ...
[ 143, 4 ]
[ 165, 19 ]
python
en
['en', 'error', 'th']
False
LayerMapping.__init__
(self, model, data, mapping, layer=0, source_srs=None, encoding='utf-8', transaction_mode='commit_on_success', transform=True, unique=None, using=None)
A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage.
A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage.
def __init__(self, model, data, mapping, layer=0, source_srs=None, encoding='utf-8', transaction_mode='commit_on_success', transform=True, unique=None, using=None): """ A LayerMapping object is initialized using the given Model (not an instance), ...
[ "def", "__init__", "(", "self", ",", "model", ",", "data", ",", "mapping", ",", "layer", "=", "0", ",", "source_srs", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "transaction_mode", "=", "'commit_on_success'", ",", "transform", "=", "True", ",", "...
[ 83, 4 ]
[ 152, 87 ]
python
en
['en', 'error', 'th']
False
LayerMapping.check_fid_range
(self, fid_range)
Check the `fid_range` keyword.
Check the `fid_range` keyword.
def check_fid_range(self, fid_range): "Check the `fid_range` keyword." if fid_range: if isinstance(fid_range, (tuple, list)): return slice(*fid_range) elif isinstance(fid_range, slice): return fid_range else: raise TypeE...
[ "def", "check_fid_range", "(", "self", ",", "fid_range", ")", ":", "if", "fid_range", ":", "if", "isinstance", "(", "fid_range", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "slice", "(", "*", "fid_range", ")", "elif", "isinstance", "(", "f...
[ 155, 4 ]
[ 165, 23 ]
python
en
['en', 'hmn', 'en']
True
LayerMapping.check_layer
(self)
Check the Layer metadata and ensure that it's compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer.
Check the Layer metadata and ensure that it's compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer.
def check_layer(self): """ Check the Layer metadata and ensure that it's compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer. """ # The geometry field of the model is set here. ...
[ "def", "check_layer", "(", "self", ")", ":", "# The geometry field of the model is set here.", "# TODO: Support more than one geometry field / model. However, this", "# depends on the GDAL Driver in use.", "self", ".", "geom_field", "=", "False", "self", ".", "fields", "=", "{",...
[ 167, 4 ]
[ 262, 48 ]
python
en
['en', 'error', 'th']
False
LayerMapping.check_srs
(self, source_srs)
Check the compatibility of the given spatial reference object.
Check the compatibility of the given spatial reference object.
def check_srs(self, source_srs): "Check the compatibility of the given spatial reference object." if isinstance(source_srs, SpatialReference): sr = source_srs elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()): sr = source_srs.srs elif isinstance...
[ "def", "check_srs", "(", "self", ",", "source_srs", ")", ":", "if", "isinstance", "(", "source_srs", ",", "SpatialReference", ")", ":", "sr", "=", "source_srs", "elif", "isinstance", "(", "source_srs", ",", "self", ".", "spatial_backend", ".", "spatial_ref_sys...
[ 264, 4 ]
[ 280, 21 ]
python
en
['en', 'en', 'en']
True
LayerMapping.check_unique
(self, unique)
Check the `unique` keyword parameter -- may be a sequence or string.
Check the `unique` keyword parameter -- may be a sequence or string.
def check_unique(self, unique): "Check the `unique` keyword parameter -- may be a sequence or string." if isinstance(unique, (list, tuple)): # List of fields to determine uniqueness with for attr in unique: if attr not in self.mapping: raise Va...
[ "def", "check_unique", "(", "self", ",", "unique", ")", ":", "if", "isinstance", "(", "unique", ",", "(", "list", ",", "tuple", ")", ")", ":", "# List of fields to determine uniqueness with", "for", "attr", "in", "unique", ":", "if", "attr", "not", "in", "...
[ 282, 4 ]
[ 294, 97 ]
python
en
['en', 'en', 'en']
True
LayerMapping.feature_kwargs
(self, feat)
Given an OGR Feature, return a dictionary of keyword arguments for constructing the mapped model.
Given an OGR Feature, return a dictionary of keyword arguments for constructing the mapped model.
def feature_kwargs(self, feat): """ Given an OGR Feature, return a dictionary of keyword arguments for constructing the mapped model. """ # The keyword arguments for model construction. kwargs = {} # Incrementing through each model field and OGR field in the ...
[ "def", "feature_kwargs", "(", "self", ",", "feat", ")", ":", "# The keyword arguments for model construction.", "kwargs", "=", "{", "}", "# Incrementing through each model field and OGR field in the", "# dictionary mapping.", "for", "field_name", ",", "ogr_name", "in", "self"...
[ 297, 4 ]
[ 328, 21 ]
python
en
['en', 'error', 'th']
False
LayerMapping.unique_kwargs
(self, kwargs)
Given the feature keyword arguments (from `feature_kwargs`), construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.
Given the feature keyword arguments (from `feature_kwargs`), construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.
def unique_kwargs(self, kwargs): """ Given the feature keyword arguments (from `feature_kwargs`), construct and return the uniqueness keyword arguments -- a subset of the feature kwargs. """ if isinstance(self.unique, str): return {self.unique: kwargs[self.uni...
[ "def", "unique_kwargs", "(", "self", ",", "kwargs", ")", ":", "if", "isinstance", "(", "self", ".", "unique", ",", "str", ")", ":", "return", "{", "self", ".", "unique", ":", "kwargs", "[", "self", ".", "unique", "]", "}", "else", ":", "return", "{...
[ 330, 4 ]
[ 339, 60 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_ogr_field
(self, ogr_field, model_field)
Verify if the OGR Field contents are acceptable to the model field. If they are, return the verified value, otherwise raise an exception.
Verify if the OGR Field contents are acceptable to the model field. If they are, return the verified value, otherwise raise an exception.
def verify_ogr_field(self, ogr_field, model_field): """ Verify if the OGR Field contents are acceptable to the model field. If they are, return the verified value, otherwise raise an exception. """ if (isinstance(ogr_field, OFTString) and isinstance(model_field, (...
[ "def", "verify_ogr_field", "(", "self", ",", "ogr_field", ",", "model_field", ")", ":", "if", "(", "isinstance", "(", "ogr_field", ",", "OFTString", ")", "and", "isinstance", "(", "model_field", ",", "(", "models", ".", "CharField", ",", "models", ".", "Te...
[ 342, 4 ]
[ 397, 18 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_fk
(self, feat, rel_model, rel_mapping)
Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping.
Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping.
def verify_fk(self, feat, rel_model, rel_mapping): """ Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping. """ # TODO: It is expensive to retrieve a model for every record -- # explore if an efficient...
[ "def", "verify_fk", "(", "self", ",", "feat", ",", "rel_model", ",", "rel_mapping", ")", ":", "# TODO: It is expensive to retrieve a model for every record --", "# explore if an efficient mechanism exists for caching related", "# ForeignKey models.", "# Constructing and verifying the...
[ 399, 4 ]
[ 420, 13 ]
python
en
['en', 'error', 'th']
False