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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
random_ipv6 | () | Generates a random ipv6 address;; useful for testing. | Generates a random ipv6 address;; useful for testing. | def random_ipv6():
"""Generates a random ipv6 address;; useful for testing."""
return ':'.join('{0:x}'.format(random.randint(0, 2 ** 16 - 1)) for i in range(8)) | [
"def",
"random_ipv6",
"(",
")",
":",
"return",
"':'",
".",
"join",
"(",
"'{0:x}'",
".",
"format",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"2",
"**",
"16",
"-",
"1",
")",
")",
"for",
"i",
"in",
"range",
"(",
"8",
")",
")"
] | [
255,
0
] | [
257,
85
] | python | en | ['en', 'cy', 'en'] | True |
random_loopback_ip | () | Generates a random loopback ipv4 address;; useful for testing. | Generates a random loopback ipv4 address;; useful for testing. | def random_loopback_ip():
"""Generates a random loopback ipv4 address;; useful for testing."""
return "127.{}.{}.{}".format(random_int(255), random_int(255), random_int(255)) | [
"def",
"random_loopback_ip",
"(",
")",
":",
"return",
"\"127.{}.{}.{}\"",
".",
"format",
"(",
"random_int",
"(",
"255",
")",
",",
"random_int",
"(",
"255",
")",
",",
"random_int",
"(",
"255",
")",
")"
] | [
260,
0
] | [
262,
83
] | python | en | ['en', 'cy', 'en'] | True |
random_utf8 | (*args, **kwargs) | This function exists due to a bug in ChromeDriver that throws an
exception when a character outside of the BMP is sent to `send_keys`.
Code pulled from http://stackoverflow.com/a/3220210.
| This function exists due to a bug in ChromeDriver that throws an
exception when a character outside of the BMP is sent to `send_keys`.
Code pulled from http://stackoverflow.com/a/3220210.
| def random_utf8(*args, **kwargs):
"""This function exists due to a bug in ChromeDriver that throws an
exception when a character outside of the BMP is sent to `send_keys`.
Code pulled from http://stackoverflow.com/a/3220210.
"""
pattern = re.compile('[^\u0000-\uD7FF\uE000-\uFFFF]', re.UNICODE)
l... | [
"def",
"random_utf8",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'[^\\u0000-\\uD7FF\\uE000-\\uFFFF]'",
",",
"re",
".",
"UNICODE",
")",
"length",
"=",
"args",
"[",
"0",
"]",
"if",
"len",
"(",
"args",... | [
265,
0
] | [
274,
19
] | python | en | ['en', 'en', 'en'] | True |
update_payload | (payload, fields, kwargs) | Takes a list of fields and adds their kwargs value to payload if defined.
If the payload has an existing value and not_provided is the kwarg value for that key,
the existing key/value are stripped from the payload.
| Takes a list of fields and adds their kwargs value to payload if defined.
If the payload has an existing value and not_provided is the kwarg value for that key,
the existing key/value are stripped from the payload.
| def update_payload(payload, fields, kwargs):
"""Takes a list of fields and adds their kwargs value to payload if defined.
If the payload has an existing value and not_provided is the kwarg value for that key,
the existing key/value are stripped from the payload.
"""
not_provided_as_kwarg = 'xx_UPDAT... | [
"def",
"update_payload",
"(",
"payload",
",",
"fields",
",",
"kwargs",
")",
":",
"not_provided_as_kwarg",
"=",
"'xx_UPDATE_PAYLOAD_FIELD_NOT_PROVIDED_AS_KWARG_xx'",
"for",
"field",
"in",
"fields",
":",
"field_val",
"=",
"kwargs",
".",
"get",
"(",
"field",
",",
"no... | [
289,
0
] | [
301,
18
] | python | en | ['en', 'en', 'en'] | True |
class_name_to_kw_arg | (class_name) | ClassName' -> 'class_name | ClassName' -> 'class_name | def class_name_to_kw_arg(class_name):
"""'ClassName' -> 'class_name'"""
first_pass = re.sub(r'([a-z])([A-Z0-9])', r'\1_\2', class_name)
second_pass = re.sub(r'([0-9])([a-zA-Z])', r'\1_\2', first_pass).lower()
return second_pass.replace('v2_', '') | [
"def",
"class_name_to_kw_arg",
"(",
"class_name",
")",
":",
"first_pass",
"=",
"re",
".",
"sub",
"(",
"r'([a-z])([A-Z0-9])'",
",",
"r'\\1_\\2'",
",",
"class_name",
")",
"second_pass",
"=",
"re",
".",
"sub",
"(",
"r'([0-9])([a-zA-Z])'",
",",
"r'\\1_\\2'",
",",
... | [
346,
0
] | [
350,
41
] | python | en | ['en', 'en', 'en'] | True |
are_same_endpoint | (first, second) | Equivalence check of two urls, stripped of query parameters | Equivalence check of two urls, stripped of query parameters | def are_same_endpoint(first, second):
"""Equivalence check of two urls, stripped of query parameters"""
def strip(url):
return url.replace('www.', '').split('?')[0]
return strip(first) == strip(second) | [
"def",
"are_same_endpoint",
"(",
"first",
",",
"second",
")",
":",
"def",
"strip",
"(",
"url",
")",
":",
"return",
"url",
".",
"replace",
"(",
"'www.'",
",",
"''",
")",
".",
"split",
"(",
"'?'",
")",
"[",
"0",
"]",
"return",
"strip",
"(",
"first",
... | [
357,
0
] | [
363,
40
] | python | en | ['en', 'en', 'en'] | True |
utcnow | () | Provide a wrapped copy of the built-in utcnow that can be easily mocked. | Provide a wrapped copy of the built-in utcnow that can be easily mocked. | def utcnow():
"""Provide a wrapped copy of the built-in utcnow that can be easily mocked."""
return datetime.utcnow() | [
"def",
"utcnow",
"(",
")",
":",
"return",
"datetime",
".",
"utcnow",
"(",
")"
] | [
366,
0
] | [
368,
28
] | python | en | ['en', 'en', 'en'] | True |
seconds_since_date_string | (date_str, fmt='%Y-%m-%dT%H:%M:%S.%fZ', default_tz=UTC()) | Return the number of seconds since the date and time indicated by a date
string and its corresponding format string.
:param date_str: string representing a date and time.
:param fmt: Formatting string - by default, this value is set to parse
date strings originating from awx API response data.
... | Return the number of seconds since the date and time indicated by a date
string and its corresponding format string. | def seconds_since_date_string(date_str, fmt='%Y-%m-%dT%H:%M:%S.%fZ', default_tz=UTC()):
"""Return the number of seconds since the date and time indicated by a date
string and its corresponding format string.
:param date_str: string representing a date and time.
:param fmt: Formatting string - by defaul... | [
"def",
"seconds_since_date_string",
"(",
"date_str",
",",
"fmt",
"=",
"'%Y-%m-%dT%H:%M:%S.%fZ'",
",",
"default_tz",
"=",
"UTC",
"(",
")",
")",
":",
"parsed_datetime",
"=",
"datetime",
".",
"strptime",
"(",
"date_str",
",",
"fmt",
")",
"if",
"not",
"parsed_date... | [
386,
0
] | [
405,
34
] | python | en | ['en', 'en', 'en'] | True |
args_string_to_list | (args) | Converts cmdline arg string to list of args. The reverse of subprocess.list2cmdline()
heavily inspired by robot.utils.argumentparser.cmdline2list()
| Converts cmdline arg string to list of args. The reverse of subprocess.list2cmdline()
heavily inspired by robot.utils.argumentparser.cmdline2list()
| def args_string_to_list(args):
"""Converts cmdline arg string to list of args. The reverse of subprocess.list2cmdline()
heavily inspired by robot.utils.argumentparser.cmdline2list()
"""
lexer = shlex.shlex(args, posix=True)
lexer.escapedquotes = '"\''
lexer.commenters = ''
lexer.whitespace_... | [
"def",
"args_string_to_list",
"(",
"args",
")",
":",
"lexer",
"=",
"shlex",
".",
"shlex",
"(",
"args",
",",
"posix",
"=",
"True",
")",
"lexer",
".",
"escapedquotes",
"=",
"'\"\\''",
"lexer",
".",
"commenters",
"=",
"''",
"lexer",
".",
"whitespace_split",
... | [
416,
0
] | [
424,
53
] | python | en | ['en', 'en', 'en'] | True |
delete_old_scheduled_jobs | (apps: StateApps, schema_editor: DatabaseSchemaEditor) | Delete any old scheduled jobs, to handle changes in the format of
send_email. Ideally, we'd translate the jobs, but it's not really
worth the development effort to save a few invitation reminders
and day2 followup emails.
| Delete any old scheduled jobs, to handle changes in the format of
send_email. Ideally, we'd translate the jobs, but it's not really
worth the development effort to save a few invitation reminders
and day2 followup emails.
| def delete_old_scheduled_jobs(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
"""Delete any old scheduled jobs, to handle changes in the format of
send_email. Ideally, we'd translate the jobs, but it's not really
worth the development effort to save a few invitation reminders
and day2 fol... | [
"def",
"delete_old_scheduled_jobs",
"(",
"apps",
":",
"StateApps",
",",
"schema_editor",
":",
"DatabaseSchemaEditor",
")",
"->",
"None",
":",
"ScheduledJob",
"=",
"apps",
".",
"get_model",
"(",
"\"zerver\"",
",",
"\"ScheduledJob\"",
")",
"ScheduledJob",
".",
"obje... | [
6,
0
] | [
13,
39
] | python | en | ['en', 'en', 'en'] | True |
build_iter_view | (matches) | Build an iterable view from the value returned by `find_matches()`. | Build an iterable view from the value returned by `find_matches()`. | def build_iter_view(matches):
"""Build an iterable view from the value returned by `find_matches()`."""
if callable(matches):
return _FactoryIterableView(matches)
if not isinstance(matches, collections_abc.Sequence):
matches = list(matches)
return _SequenceIterableView(matches) | [
"def",
"build_iter_view",
"(",
"matches",
")",
":",
"if",
"callable",
"(",
"matches",
")",
":",
"return",
"_FactoryIterableView",
"(",
"matches",
")",
"if",
"not",
"isinstance",
"(",
"matches",
",",
"collections_abc",
".",
"Sequence",
")",
":",
"matches",
"=... | [
142,
0
] | [
148,
41
] | python | en | ['en', 'en', 'en'] | True |
DirectedGraph.copy | (self) | Return a shallow copy of this graph. | Return a shallow copy of this graph. | def copy(self):
"""Return a shallow copy of this graph."""
other = DirectedGraph()
other._vertices = set(self._vertices)
other._forwards = {k: set(v) for k, v in self._forwards.items()}
other._backwards = {k: set(v) for k, v in self._backwards.items()}
return other | [
"def",
"copy",
"(",
"self",
")",
":",
"other",
"=",
"DirectedGraph",
"(",
")",
"other",
".",
"_vertices",
"=",
"set",
"(",
"self",
".",
"_vertices",
")",
"other",
".",
"_forwards",
"=",
"{",
"k",
":",
"set",
"(",
"v",
")",
"for",
"k",
",",
"v",
... | [
20,
4
] | [
26,
20
] | python | en | ['en', 'en', 'en'] | True |
DirectedGraph.add | (self, key) | Add a new vertex to the graph. | Add a new vertex to the graph. | def add(self, key):
"""Add a new vertex to the graph."""
if key in self._vertices:
raise ValueError("vertex exists")
self._vertices.add(key)
self._forwards[key] = set()
self._backwards[key] = set() | [
"def",
"add",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"_vertices",
":",
"raise",
"ValueError",
"(",
"\"vertex exists\"",
")",
"self",
".",
"_vertices",
".",
"add",
"(",
"key",
")",
"self",
".",
"_forwards",
"[",
"key",
"]",... | [
28,
4
] | [
34,
36
] | python | en | ['en', 'en', 'en'] | True |
DirectedGraph.remove | (self, key) | Remove a vertex from the graph, disconnecting all edges from/to it. | Remove a vertex from the graph, disconnecting all edges from/to it. | def remove(self, key):
"""Remove a vertex from the graph, disconnecting all edges from/to it."""
self._vertices.remove(key)
for f in self._forwards.pop(key):
self._backwards[f].remove(key)
for t in self._backwards.pop(key):
self._forwards[t].remove(key) | [
"def",
"remove",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_vertices",
".",
"remove",
"(",
"key",
")",
"for",
"f",
"in",
"self",
".",
"_forwards",
".",
"pop",
"(",
"key",
")",
":",
"self",
".",
"_backwards",
"[",
"f",
"]",
".",
"remove",
... | [
36,
4
] | [
42,
41
] | python | en | ['en', 'en', 'en'] | True |
DirectedGraph.connect | (self, f, t) | Connect two existing vertices.
Nothing happens if the vertices are already connected.
| Connect two existing vertices. | def connect(self, f, t):
"""Connect two existing vertices.
Nothing happens if the vertices are already connected.
"""
if t not in self._vertices:
raise KeyError(t)
self._forwards[f].add(t)
self._backwards[t].add(f) | [
"def",
"connect",
"(",
"self",
",",
"f",
",",
"t",
")",
":",
"if",
"t",
"not",
"in",
"self",
".",
"_vertices",
":",
"raise",
"KeyError",
"(",
"t",
")",
"self",
".",
"_forwards",
"[",
"f",
"]",
".",
"add",
"(",
"t",
")",
"self",
".",
"_backwards... | [
47,
4
] | [
55,
33
] | python | en | ['nl', 'en', 'en'] | True |
_FactoryIterableView.for_preference | (self) | Provide an candidate iterable for `get_preference()` | Provide an candidate iterable for `get_preference()` | def for_preference(self):
"""Provide an candidate iterable for `get_preference()`"""
return self._factory() | [
"def",
"for_preference",
"(",
"self",
")",
":",
"return",
"self",
".",
"_factory",
"(",
")"
] | [
96,
4
] | [
98,
30
] | python | en | ['en', 'en', 'en'] | True |
_FactoryIterableView.excluding | (self, candidates) | Create a new instance excluding specified candidates. | Create a new instance excluding specified candidates. | def excluding(self, candidates):
"""Create a new instance excluding specified candidates."""
def factory():
return (c for c in self._factory() if c not in candidates)
return type(self)(factory) | [
"def",
"excluding",
"(",
"self",
",",
"candidates",
")",
":",
"def",
"factory",
"(",
")",
":",
"return",
"(",
"c",
"for",
"c",
"in",
"self",
".",
"_factory",
"(",
")",
"if",
"c",
"not",
"in",
"candidates",
")",
"return",
"type",
"(",
"self",
")",
... | [
100,
4
] | [
106,
34
] | python | en | ['en', 'en', 'en'] | True |
_SequenceIterableView.for_preference | (self) | Provide an candidate iterable for `get_preference()` | Provide an candidate iterable for `get_preference()` | def for_preference(self):
"""Provide an candidate iterable for `get_preference()`"""
return self._sequence | [
"def",
"for_preference",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sequence"
] | [
133,
4
] | [
135,
29
] | python | en | ['en', 'en', 'en'] | True |
_SequenceIterableView.excluding | (self, candidates) | Create a new instance excluding specified candidates. | Create a new instance excluding specified candidates. | def excluding(self, candidates):
"""Create a new instance excluding specified candidates."""
return type(self)([c for c in self._sequence if c not in candidates]) | [
"def",
"excluding",
"(",
"self",
",",
"candidates",
")",
":",
"return",
"type",
"(",
"self",
")",
"(",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"_sequence",
"if",
"c",
"not",
"in",
"candidates",
"]",
")"
] | [
137,
4
] | [
139,
77
] | python | en | ['en', 'en', 'en'] | True |
PCABinaryProjections.__init__ | (self, hash_name, projection_count, training_set) |
Computes principal components for training vector set. Uses
first projection_count principal components for projections.
Training set must be either a numpy matrix or a list of
numpy vectors.
|
Computes principal components for training vector set. Uses
first projection_count principal components for projections. | def __init__(self, hash_name, projection_count, training_set):
"""
Computes principal components for training vector set. Uses
first projection_count principal components for projections.
Training set must be either a numpy matrix or a list of
numpy vectors.
"""
... | [
"def",
"__init__",
"(",
"self",
",",
"hash_name",
",",
"projection_count",
",",
"training_set",
")",
":",
"super",
"(",
"PCABinaryProjections",
",",
"self",
")",
".",
"__init__",
"(",
"hash_name",
")",
"self",
".",
"projection_count",
"=",
"projection_count",
... | [
40,
4
] | [
85,
34
] | python | en | ['en', 'error', 'th'] | False |
PCABinaryProjections.reset | (self, dim) | Resets / Initializes the hash for the specified dimension. | Resets / Initializes the hash for the specified dimension. | def reset(self, dim):
""" Resets / Initializes the hash for the specified dimension. """
if self.dim != dim:
raise Exception('PCA hash is trained for specific dimension!') | [
"def",
"reset",
"(",
"self",
",",
"dim",
")",
":",
"if",
"self",
".",
"dim",
"!=",
"dim",
":",
"raise",
"Exception",
"(",
"'PCA hash is trained for specific dimension!'",
")"
] | [
87,
4
] | [
90,
74
] | python | en | ['en', 'en', 'en'] | True |
PCABinaryProjections.hash_vector | (self, v, querying=False) |
Hashes the vector and returns the binary bucket key as string.
|
Hashes the vector and returns the binary bucket key as string.
| def hash_vector(self, v, querying=False):
"""
Hashes the vector and returns the binary bucket key as string.
"""
if scipy.sparse.issparse(v):
# If vector is sparse, make sure we have the CSR representation
# of the projection matrix
if self.components_... | [
"def",
"hash_vector",
"(",
"self",
",",
"v",
",",
"querying",
"=",
"False",
")",
":",
"if",
"scipy",
".",
"sparse",
".",
"issparse",
"(",
"v",
")",
":",
"# If vector is sparse, make sure we have the CSR representation",
"# of the projection matrix",
"if",
"self",
... | [
92,
4
] | [
110,
71
] | python | en | ['en', 'error', 'th'] | False |
PCABinaryProjections.get_config | (self) |
Returns pickle-serializable configuration struct for storage.
|
Returns pickle-serializable configuration struct for storage.
| def get_config(self):
"""
Returns pickle-serializable configuration struct for storage.
"""
# Fill this dict with config data
return {
'hash_name': self.hash_name,
'dim': self.dim,
'projection_count': self.projection_count,
'compone... | [
"def",
"get_config",
"(",
"self",
")",
":",
"# Fill this dict with config data",
"return",
"{",
"'hash_name'",
":",
"self",
".",
"hash_name",
",",
"'dim'",
":",
"self",
".",
"dim",
",",
"'projection_count'",
":",
"self",
".",
"projection_count",
",",
"'component... | [
112,
4
] | [
122,
9
] | python | en | ['en', 'error', 'th'] | False |
PCABinaryProjections.apply_config | (self, config) |
Applies config
|
Applies config
| def apply_config(self, config):
"""
Applies config
"""
self.hash_name = config['hash_name']
self.dim = config['dim']
self.projection_count = config['projection_count']
self.components = config['components'] | [
"def",
"apply_config",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"hash_name",
"=",
"config",
"[",
"'hash_name'",
"]",
"self",
".",
"dim",
"=",
"config",
"[",
"'dim'",
"]",
"self",
".",
"projection_count",
"=",
"config",
"[",
"'projection_count'",
... | [
124,
4
] | [
131,
46
] | python | en | ['en', 'error', 'th'] | False |
ConditionalDensity.plot2d | (self, x_cond=[0, 1, 2], ylim=(-8, 8), resolution=100, mode='pdf', show=True, prefix='', numpyfig=False) | Generates a 3d surface plot of the fitted conditional distribution if x and y are 1-dimensional each
Args:
xlim: 2-tuple specifying the x axis limits
ylim: 2-tuple specifying the y axis limits
resolution: integer specifying the resolution of plot
| Generates a 3d surface plot of the fitted conditional distribution if x and y are 1-dimensional each | def plot2d(self, x_cond=[0, 1, 2], ylim=(-8, 8), resolution=100, mode='pdf', show=True, prefix='', numpyfig=False):
""" Generates a 3d surface plot of the fitted conditional distribution if x and y are 1-dimensional each
Args:
xlim: 2-tuple specifying the x axis limits
ylim: 2-tuple spe... | [
"def",
"plot2d",
"(",
"self",
",",
"x_cond",
"=",
"[",
"0",
",",
"1",
",",
"2",
"]",
",",
"ylim",
"=",
"(",
"-",
"8",
",",
"8",
")",
",",
"resolution",
"=",
"100",
",",
"mode",
"=",
"'pdf'",
",",
"show",
"=",
"True",
",",
"prefix",
"=",
"''... | [
316,
2
] | [
367,
14
] | python | en | ['en', 'en', 'en'] | True |
ConditionalDensity.plot3d | (self, xlim=(-5, 5), ylim=(-8, 8), resolution=100, show=False, numpyfig=False) | Generates a 3d surface plot of the fitted conditional distribution if x and y are 1-dimensional each
Args:
xlim: 2-tuple specifying the x axis limits
ylim: 2-tuple specifying the y axis limits
resolution: integer specifying the resolution of plot
| Generates a 3d surface plot of the fitted conditional distribution if x and y are 1-dimensional each | def plot3d(self, xlim=(-5, 5), ylim=(-8, 8), resolution=100, show=False, numpyfig=False):
""" Generates a 3d surface plot of the fitted conditional distribution if x and y are 1-dimensional each
Args:
xlim: 2-tuple specifying the x axis limits
ylim: 2-tuple specifying the y axis limits
resolu... | [
"def",
"plot3d",
"(",
"self",
",",
"xlim",
"=",
"(",
"-",
"5",
",",
"5",
")",
",",
"ylim",
"=",
"(",
"-",
"8",
",",
"8",
")",
",",
"resolution",
"=",
"100",
",",
"show",
"=",
"False",
",",
"numpyfig",
"=",
"False",
")",
":",
"assert",
"self",... | [
369,
2
] | [
410,
14
] | python | en | ['en', 'en', 'en'] | True |
set_cores | (cores=0) |
doesn't do anything for serial
|
doesn't do anything for serial
| def set_cores(cores=0):
"""
doesn't do anything for serial
"""
pass | [
"def",
"set_cores",
"(",
"cores",
"=",
"0",
")",
":",
"pass"
] | [
6,
0
] | [
10,
8
] | python | en | ['en', 'error', 'th'] | False |
HashPermutations.__init__ | (self, hash_name) | Just keeps the name. | Just keeps the name. | def __init__(self, hash_name):
""" Just keeps the name. """
super(HashPermutations, self).__init__(hash_name)
self.permutation = Permutation()
self.child_hashes = []
self.dim = None | [
"def",
"__init__",
"(",
"self",
",",
"hash_name",
")",
":",
"super",
"(",
"HashPermutations",
",",
"self",
")",
".",
"__init__",
"(",
"hash_name",
")",
"self",
".",
"permutation",
"=",
"Permutation",
"(",
")",
"self",
".",
"child_hashes",
"=",
"[",
"]",
... | [
53,
4
] | [
58,
23
] | python | en | ['en', 'en', 'en'] | True |
HashPermutations.reset | (self, dim) | Resets / Initializes the hash for the specified dimension. | Resets / Initializes the hash for the specified dimension. | def reset(self, dim):
""" Resets / Initializes the hash for the specified dimension. """
self.dim = dim
# Reset all child hashes
for child_hash in self.child_hashes:
child_hash['hash'].reset(dim)
child_hash['bucket_keys'] = {} | [
"def",
"reset",
"(",
"self",
",",
"dim",
")",
":",
"self",
".",
"dim",
"=",
"dim",
"# Reset all child hashes",
"for",
"child_hash",
"in",
"self",
".",
"child_hashes",
":",
"child_hash",
"[",
"'hash'",
"]",
".",
"reset",
"(",
"dim",
")",
"child_hash",
"["... | [
60,
4
] | [
66,
42
] | python | en | ['en', 'en', 'en'] | True |
HashPermutations.hash_vector | (self, v, querying=False) |
Hashes the vector and returns the bucket key as string.
|
Hashes the vector and returns the bucket key as string.
| def hash_vector(self, v, querying=False):
"""
Hashes the vector and returns the bucket key as string.
"""
bucket_keys = []
if querying:
# If we are querying, use the permuted indexes to get bucket keys
for child_hash in self.child_hashes:
... | [
"def",
"hash_vector",
"(",
"self",
",",
"v",
",",
"querying",
"=",
"False",
")",
":",
"bucket_keys",
"=",
"[",
"]",
"if",
"querying",
":",
"# If we are querying, use the permuted indexes to get bucket keys",
"for",
"child_hash",
"in",
"self",
".",
"child_hashes",
... | [
68,
4
] | [
105,
26
] | python | en | ['en', 'error', 'th'] | False |
HashPermutations.get_config | (self) |
Returns pickle-serializable configuration struct for storage.
|
Returns pickle-serializable configuration struct for storage.
| def get_config(self):
"""
Returns pickle-serializable configuration struct for storage.
"""
return {
'hash_name': self.hash_name,
'dim': self.dim
} | [
"def",
"get_config",
"(",
"self",
")",
":",
"return",
"{",
"'hash_name'",
":",
"self",
".",
"hash_name",
",",
"'dim'",
":",
"self",
".",
"dim",
"}"
] | [
107,
4
] | [
114,
9
] | python | en | ['en', 'error', 'th'] | False |
HashPermutations.apply_config | (self, config) |
Applies config
|
Applies config
| def apply_config(self, config):
"""
Applies config
"""
self.hash_name = config['hash_name']
self.dim = config['dim'] | [
"def",
"apply_config",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"hash_name",
"=",
"config",
"[",
"'hash_name'",
"]",
"self",
".",
"dim",
"=",
"config",
"[",
"'dim'",
"]"
] | [
116,
4
] | [
121,
32
] | python | en | ['en', 'error', 'th'] | False |
HashPermutations.add_child_hash | (self, child_hash, permute_config) |
Adds specified child hash with specified configuration.
The hash must be one of the binary types.
permute_config is a dict in the following format:
permute_config = { "num_permutation":50,
"beam_size":10,
"num_neighbour":100
... |
Adds specified child hash with specified configuration.
The hash must be one of the binary types. | def add_child_hash(self, child_hash, permute_config):
"""
Adds specified child hash with specified configuration.
The hash must be one of the binary types.
permute_config is a dict in the following format:
permute_config = { "num_permutation":50,
"beam... | [
"def",
"add_child_hash",
"(",
"self",
",",
"child_hash",
",",
"permute_config",
")",
":",
"# Hash must generate binary keys",
"if",
"not",
"(",
"isinstance",
"(",
"child_hash",
",",
"PCABinaryProjections",
")",
"or",
"isinstance",
"(",
"child_hash",
",",
"RandomBina... | [
123,
4
] | [
141,
99
] | python | en | ['en', 'error', 'th'] | False |
HashPermutations.build_permuted_index | (self) |
Build PermutedIndex for all your binary hashings.
PermutedIndex would be used to find the neighbour bucket key
in terms of Hamming distance. Permute_configs is nested dict
in the following format:
permuted_config = {"<hash_name>":
{ "num_permutation":5... |
Build PermutedIndex for all your binary hashings.
PermutedIndex would be used to find the neighbour bucket key
in terms of Hamming distance. Permute_configs is nested dict
in the following format:
permuted_config = {"<hash_name>":
{ "num_permutation":5... | def build_permuted_index(self):
"""
Build PermutedIndex for all your binary hashings.
PermutedIndex would be used to find the neighbour bucket key
in terms of Hamming distance. Permute_configs is nested dict
in the following format:
permuted_config = {"<hash_name>":
... | [
"def",
"build_permuted_index",
"(",
"self",
")",
":",
"for",
"child_hash",
"in",
"self",
".",
"child_hashes",
":",
"# Get config values for child hash",
"config",
"=",
"child_hash",
"[",
"'config'",
"]",
"num_permutation",
"=",
"config",
"[",
"'num_permutation'",
"]... | [
143,
4
] | [
170,
109
] | python | en | ['en', 'error', 'th'] | False |
BaseViewRestriction.mark_as_passed | (self, request) |
Update the session data in the request to mark the user as having passed this
view restriction
|
Update the session data in the request to mark the user as having passed this
view restriction
| def mark_as_passed(self, request):
"""
Update the session data in the request to mark the user as having passed this
view restriction
"""
has_existing_session = (settings.SESSION_COOKIE_NAME in request.COOKIES)
passed_restrictions = request.session.setdefault(self.passed_... | [
"def",
"mark_as_passed",
"(",
"self",
",",
"request",
")",
":",
"has_existing_session",
"=",
"(",
"settings",
".",
"SESSION_COOKIE_NAME",
"in",
"request",
".",
"COOKIES",
")",
"passed_restrictions",
"=",
"request",
".",
"session",
".",
"setdefault",
"(",
"self",... | [
50,
4
] | [
63,
41
] | python | en | ['en', 'error', 'th'] | False |
Indexed.get_indexed_instance | (self) |
If the indexed model uses multi table inheritance, override this method
to return the instance in its most specific class so it reindexes properly.
|
If the indexed model uses multi table inheritance, override this method
to return the instance in its most specific class so it reindexes properly.
| def get_indexed_instance(self):
"""
If the indexed model uses multi table inheritance, override this method
to return the instance in its most specific class so it reindexes properly.
"""
return self | [
"def",
"get_indexed_instance",
"(",
"self",
")",
":",
"return",
"self"
] | [
87,
4
] | [
92,
19
] | python | en | ['en', 'error', 'th'] | False |
RelatedFields.select_on_queryset | (self, queryset) |
This method runs either prefetch_related or select_related on the queryset
to improve indexing speed of the relation.
It decides which method to call based on the number of related objects:
- single (eg ForeignKey, OneToOne), it runs select_related
- multiple (eg ManyToMany, ... |
This method runs either prefetch_related or select_related on the queryset
to improve indexing speed of the relation. | def select_on_queryset(self, queryset):
"""
This method runs either prefetch_related or select_related on the queryset
to improve indexing speed of the relation.
It decides which method to call based on the number of related objects:
- single (eg ForeignKey, OneToOne), it runs ... | [
"def",
"select_on_queryset",
"(",
"self",
",",
"queryset",
")",
":",
"try",
":",
"field",
"=",
"self",
".",
"get_field",
"(",
"queryset",
".",
"model",
")",
"except",
"FieldDoesNotExist",
":",
"return",
"queryset",
"if",
"isinstance",
"(",
"field",
",",
"R... | [
300,
4
] | [
329,
23
] | python | en | ['en', 'error', 'th'] | False |
read_setup_file | (filename) | Reads a Setup file and returns Extension instances. | Reads a Setup file and returns Extension instances. | def read_setup_file(filename):
"""Reads a Setup file and returns Extension instances."""
from distutils.sysconfig import (parse_makefile, expand_makefile_vars,
_variable_rx)
from distutils.text_file import TextFile
from distutils.util import split_quoted
# Firs... | [
"def",
"read_setup_file",
"(",
"filename",
")",
":",
"from",
"distutils",
".",
"sysconfig",
"import",
"(",
"parse_makefile",
",",
"expand_makefile_vars",
",",
"_variable_rx",
")",
"from",
"distutils",
".",
"text_file",
"import",
"TextFile",
"from",
"distutils",
".... | [
140,
0
] | [
239,
21
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.ensure_timezone | (self) |
Ensure the connection's timezone is set to `self.timezone_name` and
return whether it changed or not.
|
Ensure the connection's timezone is set to `self.timezone_name` and
return whether it changed or not.
| def ensure_timezone(self):
"""
Ensure the connection's timezone is set to `self.timezone_name` and
return whether it changed or not.
"""
return False | [
"def",
"ensure_timezone",
"(",
"self",
")",
":",
"return",
"False"
] | [
102,
4
] | [
107,
20
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.timezone | (self) |
Time zone for datetimes stored as naive values in the database.
Returns a tzinfo object or None.
This is only needed when time zone support is enabled and the database
doesn't support time zones. (When the database supports time zones,
the adapter handles aware datetimes so Dj... |
Time zone for datetimes stored as naive values in the database. | def timezone(self):
"""
Time zone for datetimes stored as naive values in the database.
Returns a tzinfo object or None.
This is only needed when time zone support is enabled and the database
doesn't support time zones. (When the database supports time zones,
the adapte... | [
"def",
"timezone",
"(",
"self",
")",
":",
"if",
"not",
"settings",
".",
"USE_TZ",
":",
"return",
"None",
"elif",
"self",
".",
"features",
".",
"supports_timezones",
":",
"return",
"None",
"elif",
"self",
".",
"settings_dict",
"[",
"'TIME_ZONE'",
"]",
"is",... | [
110,
4
] | [
127,
65
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.timezone_name | (self) |
Name of the time zone of the database connection.
|
Name of the time zone of the database connection.
| def timezone_name(self):
"""
Name of the time zone of the database connection.
"""
if not settings.USE_TZ:
return settings.TIME_ZONE
elif self.settings_dict['TIME_ZONE'] is None:
return 'UTC'
else:
return self.settings_dict['TIME_ZONE'] | [
"def",
"timezone_name",
"(",
"self",
")",
":",
"if",
"not",
"settings",
".",
"USE_TZ",
":",
"return",
"settings",
".",
"TIME_ZONE",
"elif",
"self",
".",
"settings_dict",
"[",
"'TIME_ZONE'",
"]",
"is",
"None",
":",
"return",
"'UTC'",
"else",
":",
"return",
... | [
130,
4
] | [
139,
50
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.get_connection_params | (self) | Returns a dict of parameters suitable for get_new_connection. | Returns a dict of parameters suitable for get_new_connection. | def get_connection_params(self):
"""Returns a dict of parameters suitable for get_new_connection."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a get_connection_params() method') | [
"def",
"get_connection_params",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseWrapper may require a get_connection_params() method'",
")"
] | [
155,
4
] | [
157,
115
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.get_new_connection | (self, conn_params) | Opens a connection to the database. | Opens a connection to the database. | def get_new_connection(self, conn_params):
"""Opens a connection to the database."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a get_new_connection() method') | [
"def",
"get_new_connection",
"(",
"self",
",",
"conn_params",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseWrapper may require a get_new_connection() method'",
")"
] | [
159,
4
] | [
161,
112
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.init_connection_state | (self) | Initializes the database connection settings. | Initializes the database connection settings. | def init_connection_state(self):
"""Initializes the database connection settings."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require an init_connection_state() method') | [
"def",
"init_connection_state",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseWrapper may require an init_connection_state() method'",
")"
] | [
163,
4
] | [
165,
116
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.create_cursor | (self, name=None) | Creates a cursor. Assumes that a connection is established. | Creates a cursor. Assumes that a connection is established. | def create_cursor(self, name=None):
"""Creates a cursor. Assumes that a connection is established."""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a create_cursor() method') | [
"def",
"create_cursor",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseWrapper may require a create_cursor() method'",
")"
] | [
167,
4
] | [
169,
107
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.connect | (self) | Connects to the database. Assumes that the connection is closed. | Connects to the database. Assumes that the connection is closed. | def connect(self):
"""Connects to the database. Assumes that the connection is closed."""
# Check for invalid configurations.
self.check_settings()
# In case the previous connection was closed while in an atomic block
self.in_atomic_block = False
self.savepoint_ids = []
... | [
"def",
"connect",
"(",
"self",
")",
":",
"# Check for invalid configurations.",
"self",
".",
"check_settings",
"(",
")",
"# In case the previous connection was closed while in an atomic block",
"self",
".",
"in_atomic_block",
"=",
"False",
"self",
".",
"savepoint_ids",
"=",... | [
173,
4
] | [
193,
31
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseWrapper.ensure_connection | (self) |
Guarantees that a connection to the database is established.
|
Guarantees that a connection to the database is established.
| def ensure_connection(self):
"""
Guarantees that a connection to the database is established.
"""
if self.connection is None:
with self.wrap_database_errors:
self.connect() | [
"def",
"ensure_connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"connection",
"is",
"None",
":",
"with",
"self",
".",
"wrap_database_errors",
":",
"self",
".",
"connect",
"(",
")"
] | [
206,
4
] | [
212,
30
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper._prepare_cursor | (self, cursor) |
Validate the connection is usable and perform database cursor wrapping.
|
Validate the connection is usable and perform database cursor wrapping.
| def _prepare_cursor(self, cursor):
"""
Validate the connection is usable and perform database cursor wrapping.
"""
self.validate_thread_sharing()
if self.queries_logged:
wrapped_cursor = self.make_debug_cursor(cursor)
else:
wrapped_cursor = self.ma... | [
"def",
"_prepare_cursor",
"(",
"self",
",",
"cursor",
")",
":",
"self",
".",
"validate_thread_sharing",
"(",
")",
"if",
"self",
".",
"queries_logged",
":",
"wrapped_cursor",
"=",
"self",
".",
"make_debug_cursor",
"(",
"cursor",
")",
"else",
":",
"wrapped_curso... | [
216,
4
] | [
225,
29
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.cursor | (self) |
Creates a cursor, opening a connection if necessary.
|
Creates a cursor, opening a connection if necessary.
| def cursor(self):
"""
Creates a cursor, opening a connection if necessary.
"""
return self._cursor() | [
"def",
"cursor",
"(",
"self",
")",
":",
"return",
"self",
".",
"_cursor",
"(",
")"
] | [
249,
4
] | [
253,
29
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.commit | (self) |
Commits a transaction and resets the dirty flag.
|
Commits a transaction and resets the dirty flag.
| def commit(self):
"""
Commits a transaction and resets the dirty flag.
"""
self.validate_thread_sharing()
self.validate_no_atomic_block()
self._commit()
# A successful commit means that the database connection works.
self.errors_occurred = False
se... | [
"def",
"commit",
"(",
"self",
")",
":",
"self",
".",
"validate_thread_sharing",
"(",
")",
"self",
".",
"validate_no_atomic_block",
"(",
")",
"self",
".",
"_commit",
"(",
")",
"# A successful commit means that the database connection works.",
"self",
".",
"errors_occur... | [
255,
4
] | [
264,
57
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.rollback | (self) |
Rolls back a transaction and resets the dirty flag.
|
Rolls back a transaction and resets the dirty flag.
| def rollback(self):
"""
Rolls back a transaction and resets the dirty flag.
"""
self.validate_thread_sharing()
self.validate_no_atomic_block()
self._rollback()
# A successful rollback means that the database connection works.
self.errors_occurred = False
... | [
"def",
"rollback",
"(",
"self",
")",
":",
"self",
".",
"validate_thread_sharing",
"(",
")",
"self",
".",
"validate_no_atomic_block",
"(",
")",
"self",
".",
"_rollback",
"(",
")",
"# A successful rollback means that the database connection works.",
"self",
".",
"errors... | [
266,
4
] | [
276,
31
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.close | (self) |
Closes the connection to the database.
|
Closes the connection to the database.
| def close(self):
"""
Closes the connection to the database.
"""
self.validate_thread_sharing()
self.run_on_commit = []
# Don't call validate_no_atomic_block() to avoid making it difficult
# to get rid of a connection in an invalid state. The next connect()
... | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"validate_thread_sharing",
"(",
")",
"self",
".",
"run_on_commit",
"=",
"[",
"]",
"# Don't call validate_no_atomic_block() to avoid making it difficult",
"# to get rid of a connection in an invalid state. The next connect()",
... | [
278,
4
] | [
297,
38
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.savepoint | (self) |
Creates a savepoint inside the current transaction. Returns an
identifier for the savepoint that will be used for the subsequent
rollback or commit. Does nothing if savepoints are not supported.
|
Creates a savepoint inside the current transaction. Returns an
identifier for the savepoint that will be used for the subsequent
rollback or commit. Does nothing if savepoints are not supported.
| def savepoint(self):
"""
Creates a savepoint inside the current transaction. Returns an
identifier for the savepoint that will be used for the subsequent
rollback or commit. Does nothing if savepoints are not supported.
"""
if not self._savepoint_allowed():
re... | [
"def",
"savepoint",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_savepoint_allowed",
"(",
")",
":",
"return",
"thread_ident",
"=",
"thread",
".",
"get_ident",
"(",
")",
"tid",
"=",
"str",
"(",
"thread_ident",
")",
".",
"replace",
"(",
"'-'",
",",... | [
319,
4
] | [
337,
18
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.savepoint_rollback | (self, sid) |
Rolls back to a savepoint. Does nothing if savepoints are not supported.
|
Rolls back to a savepoint. Does nothing if savepoints are not supported.
| def savepoint_rollback(self, sid):
"""
Rolls back to a savepoint. Does nothing if savepoints are not supported.
"""
if not self._savepoint_allowed():
return
self.validate_thread_sharing()
self._savepoint_rollback(sid)
# Remove any callbacks registere... | [
"def",
"savepoint_rollback",
"(",
"self",
",",
"sid",
")",
":",
"if",
"not",
"self",
".",
"_savepoint_allowed",
"(",
")",
":",
"return",
"self",
".",
"validate_thread_sharing",
"(",
")",
"self",
".",
"_savepoint_rollback",
"(",
"sid",
")",
"# Remove any callba... | [
339,
4
] | [
352,
9
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.savepoint_commit | (self, sid) |
Releases a savepoint. Does nothing if savepoints are not supported.
|
Releases a savepoint. Does nothing if savepoints are not supported.
| def savepoint_commit(self, sid):
"""
Releases a savepoint. Does nothing if savepoints are not supported.
"""
if not self._savepoint_allowed():
return
self.validate_thread_sharing()
self._savepoint_commit(sid) | [
"def",
"savepoint_commit",
"(",
"self",
",",
"sid",
")",
":",
"if",
"not",
"self",
".",
"_savepoint_allowed",
"(",
")",
":",
"return",
"self",
".",
"validate_thread_sharing",
"(",
")",
"self",
".",
"_savepoint_commit",
"(",
"sid",
")"
] | [
354,
4
] | [
362,
35
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.clean_savepoints | (self) |
Resets the counter used to generate unique savepoint ids in this thread.
|
Resets the counter used to generate unique savepoint ids in this thread.
| def clean_savepoints(self):
"""
Resets the counter used to generate unique savepoint ids in this thread.
"""
self.savepoint_state = 0 | [
"def",
"clean_savepoints",
"(",
"self",
")",
":",
"self",
".",
"savepoint_state",
"=",
"0"
] | [
364,
4
] | [
368,
32
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper._set_autocommit | (self, autocommit) |
Backend-specific implementation to enable or disable autocommit.
|
Backend-specific implementation to enable or disable autocommit.
| def _set_autocommit(self, autocommit):
"""
Backend-specific implementation to enable or disable autocommit.
"""
raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a _set_autocommit() method') | [
"def",
"_set_autocommit",
"(",
"self",
",",
"autocommit",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseWrapper may require a _set_autocommit() method'",
")"
] | [
372,
4
] | [
376,
109
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.get_autocommit | (self) |
Check the autocommit state.
|
Check the autocommit state.
| def get_autocommit(self):
"""
Check the autocommit state.
"""
self.ensure_connection()
return self.autocommit | [
"def",
"get_autocommit",
"(",
"self",
")",
":",
"self",
".",
"ensure_connection",
"(",
")",
"return",
"self",
".",
"autocommit"
] | [
380,
4
] | [
385,
30
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.set_autocommit | (self, autocommit, force_begin_transaction_with_broken_autocommit=False) |
Enable or disable autocommit.
The usual way to start a transaction is to turn autocommit off.
SQLite does not properly start a transaction when disabling
autocommit. To avoid this buggy behavior and to actually enter a new
transaction, an explcit BEGIN is required. Using
... |
Enable or disable autocommit. | def set_autocommit(self, autocommit, force_begin_transaction_with_broken_autocommit=False):
"""
Enable or disable autocommit.
The usual way to start a transaction is to turn autocommit off.
SQLite does not properly start a transaction when disabling
autocommit. To avoid this bug... | [
"def",
"set_autocommit",
"(",
"self",
",",
"autocommit",
",",
"force_begin_transaction_with_broken_autocommit",
"=",
"False",
")",
":",
"self",
".",
"validate_no_atomic_block",
"(",
")",
"self",
".",
"ensure_connection",
"(",
")",
"start_transaction_under_autocommit",
"... | [
387,
4
] | [
416,
62
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.get_rollback | (self) |
Get the "needs rollback" flag -- for *advanced use* only.
|
Get the "needs rollback" flag -- for *advanced use* only.
| def get_rollback(self):
"""
Get the "needs rollback" flag -- for *advanced use* only.
"""
if not self.in_atomic_block:
raise TransactionManagementError(
"The rollback flag doesn't work outside of an 'atomic' block.")
return self.needs_rollback | [
"def",
"get_rollback",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"in_atomic_block",
":",
"raise",
"TransactionManagementError",
"(",
"\"The rollback flag doesn't work outside of an 'atomic' block.\"",
")",
"return",
"self",
".",
"needs_rollback"
] | [
418,
4
] | [
425,
34
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.set_rollback | (self, rollback) |
Set or unset the "needs rollback" flag -- for *advanced use* only.
|
Set or unset the "needs rollback" flag -- for *advanced use* only.
| def set_rollback(self, rollback):
"""
Set or unset the "needs rollback" flag -- for *advanced use* only.
"""
if not self.in_atomic_block:
raise TransactionManagementError(
"The rollback flag doesn't work outside of an 'atomic' block.")
self.needs_rollb... | [
"def",
"set_rollback",
"(",
"self",
",",
"rollback",
")",
":",
"if",
"not",
"self",
".",
"in_atomic_block",
":",
"raise",
"TransactionManagementError",
"(",
"\"The rollback flag doesn't work outside of an 'atomic' block.\"",
")",
"self",
".",
"needs_rollback",
"=",
"rol... | [
427,
4
] | [
434,
38
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.validate_no_atomic_block | (self) |
Raise an error if an atomic block is active.
|
Raise an error if an atomic block is active.
| def validate_no_atomic_block(self):
"""
Raise an error if an atomic block is active.
"""
if self.in_atomic_block:
raise TransactionManagementError(
"This is forbidden when an 'atomic' block is active.") | [
"def",
"validate_no_atomic_block",
"(",
"self",
")",
":",
"if",
"self",
".",
"in_atomic_block",
":",
"raise",
"TransactionManagementError",
"(",
"\"This is forbidden when an 'atomic' block is active.\"",
")"
] | [
436,
4
] | [
442,
70
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.constraint_checks_disabled | (self) |
Context manager that disables foreign key constraint checking.
|
Context manager that disables foreign key constraint checking.
| def constraint_checks_disabled(self):
"""
Context manager that disables foreign key constraint checking.
"""
disabled = self.disable_constraint_checking()
try:
yield
finally:
if disabled:
self.enable_constraint_checking() | [
"def",
"constraint_checks_disabled",
"(",
"self",
")",
":",
"disabled",
"=",
"self",
".",
"disable_constraint_checking",
"(",
")",
"try",
":",
"yield",
"finally",
":",
"if",
"disabled",
":",
"self",
".",
"enable_constraint_checking",
"(",
")"
] | [
453,
4
] | [
462,
49
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.disable_constraint_checking | (self) |
Backends can implement as needed to temporarily disable foreign key
constraint checking. Should return True if the constraints were
disabled and will need to be reenabled.
|
Backends can implement as needed to temporarily disable foreign key
constraint checking. Should return True if the constraints were
disabled and will need to be reenabled.
| def disable_constraint_checking(self):
"""
Backends can implement as needed to temporarily disable foreign key
constraint checking. Should return True if the constraints were
disabled and will need to be reenabled.
"""
return False | [
"def",
"disable_constraint_checking",
"(",
"self",
")",
":",
"return",
"False"
] | [
464,
4
] | [
470,
20
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.enable_constraint_checking | (self) |
Backends can implement as needed to re-enable foreign key constraint
checking.
|
Backends can implement as needed to re-enable foreign key constraint
checking.
| def enable_constraint_checking(self):
"""
Backends can implement as needed to re-enable foreign key constraint
checking.
"""
pass | [
"def",
"enable_constraint_checking",
"(",
"self",
")",
":",
"pass"
] | [
472,
4
] | [
477,
12
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.check_constraints | (self, table_names=None) |
Backends can override this method if they can apply constraint
checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an
IntegrityError if any invalid foreign key references are encountered.
|
Backends can override this method if they can apply constraint
checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an
IntegrityError if any invalid foreign key references are encountered.
| def check_constraints(self, table_names=None):
"""
Backends can override this method if they can apply constraint
checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an
IntegrityError if any invalid foreign key references are encountered.
"""
pass | [
"def",
"check_constraints",
"(",
"self",
",",
"table_names",
"=",
"None",
")",
":",
"pass"
] | [
479,
4
] | [
485,
12
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.is_usable | (self) |
Tests if the database connection is usable.
This function may assume that self.connection is not None.
Actual implementations should take care not to raise exceptions
as that may prevent Django from recycling unusable connections.
|
Tests if the database connection is usable. | def is_usable(self):
"""
Tests if the database connection is usable.
This function may assume that self.connection is not None.
Actual implementations should take care not to raise exceptions
as that may prevent Django from recycling unusable connections.
"""
ra... | [
"def",
"is_usable",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"subclasses of BaseDatabaseWrapper may require an is_usable() method\"",
")"
] | [
489,
4
] | [
499,
82
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.close_if_unusable_or_obsolete | (self) |
Closes the current connection if unrecoverable errors have occurred,
or if it outlived its maximum age.
|
Closes the current connection if unrecoverable errors have occurred,
or if it outlived its maximum age.
| def close_if_unusable_or_obsolete(self):
"""
Closes the current connection if unrecoverable errors have occurred,
or if it outlived its maximum age.
"""
if self.connection is not None:
# If the application didn't restore the original autocommit setting,
# ... | [
"def",
"close_if_unusable_or_obsolete",
"(",
"self",
")",
":",
"if",
"self",
".",
"connection",
"is",
"not",
"None",
":",
"# If the application didn't restore the original autocommit setting,",
"# don't take chances, drop the connection.",
"if",
"self",
".",
"get_autocommit",
... | [
501,
4
] | [
524,
22
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.validate_thread_sharing | (self) |
Validates that the connection isn't accessed by another thread than the
one which originally created it, unless the connection was explicitly
authorized to be shared between threads (via the `allow_thread_sharing`
property). Raises an exception if the validation fails.
|
Validates that the connection isn't accessed by another thread than the
one which originally created it, unless the connection was explicitly
authorized to be shared between threads (via the `allow_thread_sharing`
property). Raises an exception if the validation fails.
| def validate_thread_sharing(self):
"""
Validates that the connection isn't accessed by another thread than the
one which originally created it, unless the connection was explicitly
authorized to be shared between threads (via the `allow_thread_sharing`
property). Raises an except... | [
"def",
"validate_thread_sharing",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"allow_thread_sharing",
"or",
"self",
".",
"_thread_ident",
"==",
"thread",
".",
"get_ident",
"(",
")",
")",
":",
"raise",
"DatabaseError",
"(",
"\"DatabaseWrapper objects cr... | [
528,
4
] | [
542,
13
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.prepare_database | (self) |
Hook to do any database check or preparation, generally called before
migrating a project or an app.
|
Hook to do any database check or preparation, generally called before
migrating a project or an app.
| def prepare_database(self):
"""
Hook to do any database check or preparation, generally called before
migrating a project or an app.
"""
pass | [
"def",
"prepare_database",
"(",
"self",
")",
":",
"pass"
] | [
546,
4
] | [
551,
12
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.wrap_database_errors | (self) |
Context manager and decorator that re-throws backend-specific database
exceptions using Django's common wrappers.
|
Context manager and decorator that re-throws backend-specific database
exceptions using Django's common wrappers.
| def wrap_database_errors(self):
"""
Context manager and decorator that re-throws backend-specific database
exceptions using Django's common wrappers.
"""
return DatabaseErrorWrapper(self) | [
"def",
"wrap_database_errors",
"(",
"self",
")",
":",
"return",
"DatabaseErrorWrapper",
"(",
"self",
")"
] | [
554,
4
] | [
559,
41
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.chunked_cursor | (self) |
Return a cursor that tries to avoid caching in the database (if
supported by the database), otherwise return a regular cursor.
|
Return a cursor that tries to avoid caching in the database (if
supported by the database), otherwise return a regular cursor.
| def chunked_cursor(self):
"""
Return a cursor that tries to avoid caching in the database (if
supported by the database), otherwise return a regular cursor.
"""
return self.cursor() | [
"def",
"chunked_cursor",
"(",
"self",
")",
":",
"return",
"self",
".",
"cursor",
"(",
")"
] | [
561,
4
] | [
566,
28
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.make_debug_cursor | (self, cursor) |
Creates a cursor that logs all queries in self.queries_log.
|
Creates a cursor that logs all queries in self.queries_log.
| def make_debug_cursor(self, cursor):
"""
Creates a cursor that logs all queries in self.queries_log.
"""
return utils.CursorDebugWrapper(cursor, self) | [
"def",
"make_debug_cursor",
"(",
"self",
",",
"cursor",
")",
":",
"return",
"utils",
".",
"CursorDebugWrapper",
"(",
"cursor",
",",
"self",
")"
] | [
568,
4
] | [
572,
53
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.make_cursor | (self, cursor) |
Creates a cursor without debug logging.
|
Creates a cursor without debug logging.
| def make_cursor(self, cursor):
"""
Creates a cursor without debug logging.
"""
return utils.CursorWrapper(cursor, self) | [
"def",
"make_cursor",
"(",
"self",
",",
"cursor",
")",
":",
"return",
"utils",
".",
"CursorWrapper",
"(",
"cursor",
",",
"self",
")"
] | [
574,
4
] | [
578,
48
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.temporary_connection | (self) |
Context manager that ensures that a connection is established, and
if it opened one, closes it to avoid leaving a dangling connection.
This is useful for operations outside of the request-response cycle.
Provides a cursor: with self.temporary_connection() as cursor: ...
|
Context manager that ensures that a connection is established, and
if it opened one, closes it to avoid leaving a dangling connection.
This is useful for operations outside of the request-response cycle. | def temporary_connection(self):
"""
Context manager that ensures that a connection is established, and
if it opened one, closes it to avoid leaving a dangling connection.
This is useful for operations outside of the request-response cycle.
Provides a cursor: with self.temporary_... | [
"def",
"temporary_connection",
"(",
"self",
")",
":",
"must_close",
"=",
"self",
".",
"connection",
"is",
"None",
"cursor",
"=",
"self",
".",
"cursor",
"(",
")",
"try",
":",
"yield",
"cursor",
"finally",
":",
"cursor",
".",
"close",
"(",
")",
"if",
"mu... | [
581,
4
] | [
596,
28
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper._nodb_connection | (self) |
Return an alternative connection to be used when there is no need to access
the main database, specifically for test db creation/deletion.
This also prevents the production database from being exposed to
potential child threads while (or after) the test database is destroyed.
Re... |
Return an alternative connection to be used when there is no need to access
the main database, specifically for test db creation/deletion.
This also prevents the production database from being exposed to
potential child threads while (or after) the test database is destroyed.
Re... | def _nodb_connection(self):
"""
Return an alternative connection to be used when there is no need to access
the main database, specifically for test db creation/deletion.
This also prevents the production database from being exposed to
potential child threads while (or after) the... | [
"def",
"_nodb_connection",
"(",
"self",
")",
":",
"settings_dict",
"=",
"self",
".",
"settings_dict",
".",
"copy",
"(",
")",
"settings_dict",
"[",
"'NAME'",
"]",
"=",
"None",
"nodb_connection",
"=",
"self",
".",
"__class__",
"(",
"settings_dict",
",",
"alias... | [
599,
4
] | [
613,
30
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper._start_transaction_under_autocommit | (self) |
Only required when autocommits_when_autocommit_is_off = True.
|
Only required when autocommits_when_autocommit_is_off = True.
| def _start_transaction_under_autocommit(self):
"""
Only required when autocommits_when_autocommit_is_off = True.
"""
raise NotImplementedError(
'subclasses of BaseDatabaseWrapper may require a '
'_start_transaction_under_autocommit() method'
) | [
"def",
"_start_transaction_under_autocommit",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseDatabaseWrapper may require a '",
"'_start_transaction_under_autocommit() method'",
")"
] | [
615,
4
] | [
622,
9
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.schema_editor | (self, *args, **kwargs) |
Returns a new instance of this backend's SchemaEditor.
|
Returns a new instance of this backend's SchemaEditor.
| def schema_editor(self, *args, **kwargs):
"""
Returns a new instance of this backend's SchemaEditor.
"""
if self.SchemaEditorClass is None:
raise NotImplementedError(
'The SchemaEditorClass attribute of this database wrapper is still None')
return self... | [
"def",
"schema_editor",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"SchemaEditorClass",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'The SchemaEditorClass attribute of this database wrapper is still None'",
")",
... | [
624,
4
] | [
631,
60
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseWrapper.copy | (self, alias=None, allow_thread_sharing=None) |
Return a copy of this connection.
For tests that require two connections to the same database.
|
Return a copy of this connection. | def copy(self, alias=None, allow_thread_sharing=None):
"""
Return a copy of this connection.
For tests that require two connections to the same database.
"""
settings_dict = copy.deepcopy(self.settings_dict)
if alias is None:
alias = self.alias
if all... | [
"def",
"copy",
"(",
"self",
",",
"alias",
"=",
"None",
",",
"allow_thread_sharing",
"=",
"None",
")",
":",
"settings_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"settings_dict",
")",
"if",
"alias",
"is",
"None",
":",
"alias",
"=",
"self",
".... | [
652,
4
] | [
663,
69
] | python | en | ['en', 'error', 'th'] | False |
mkdir | (path, reset=False) | Checks if directory exists and if not, create one.
Parameters
----------
reset: erase the content of the directory if exists
Returns
-------
the path
| Checks if directory exists and if not, create one. | def mkdir(path, reset=False):
"""Checks if directory exists and if not, create one.
Parameters
----------
reset: erase the content of the directory if exists
Returns
-------
the path
"""
if reset and os.path.exists(path):
shutil.rmtree(path)
try:
os.makedirs(pa... | [
"def",
"mkdir",
"(",
"path",
",",
"reset",
"=",
"False",
")",
":",
"if",
"reset",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"e... | [
120,
0
] | [
138,
15
] | python | en | ['en', 'en', 'en'] | True |
del_empty_dirs | (s_dir) | Delete empty directories. | Delete empty directories. | def del_empty_dirs(s_dir):
"""Delete empty directories."""
b_empty = True
for s_target in os.listdir(s_dir):
s_path = os.path.join(s_dir, s_target)
if os.path.isdir(s_path):
if not del_empty_dirs(s_path):
b_empty = False
else:
b_empty = False
... | [
"def",
"del_empty_dirs",
"(",
"s_dir",
")",
":",
"b_empty",
"=",
"True",
"for",
"s_target",
"in",
"os",
".",
"listdir",
"(",
"s_dir",
")",
":",
"s_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"s_dir",
",",
"s_target",
")",
"if",
"os",
".",
"pat... | [
141,
0
] | [
153,
18
] | python | en | ['en', 'nl', 'en'] | True |
findfiles | (root_dir, endswith) | Finds all files with a specific ending in a directory
Parameters
----------
root_dir : str
The directory to search fo
endswith : str
The file ending (e.g. '.hgt'
Returns
-------
the list of files
| Finds all files with a specific ending in a directory | def findfiles(root_dir, endswith):
"""Finds all files with a specific ending in a directory
Parameters
----------
root_dir : str
The directory to search fo
endswith : str
The file ending (e.g. '.hgt'
Returns
-------
the list of files
"""
out = []
for dirpath, ... | [
"def",
"findfiles",
"(",
"root_dir",
",",
"endswith",
")",
":",
"out",
"=",
"[",
"]",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"root_dir",
")",
":",
"for",
"filename",
"in",
"[",
"f",
"for",
"f",
"in",
"fil... | [
156,
0
] | [
174,
14
] | python | en | ['en', 'en', 'en'] | True |
get_lock | () | Get multiprocessing lock. | Get multiprocessing lock. | def get_lock():
"""Get multiprocessing lock."""
global lock
if lock is None:
# Global Lock
if cfg.PARAMS.get('use_mp_spawn', False):
lock = multiprocessing.get_context('spawn').Lock()
else:
lock = multiprocessing.Lock()
return lock | [
"def",
"get_lock",
"(",
")",
":",
"global",
"lock",
"if",
"lock",
"is",
"None",
":",
"# Global Lock",
"if",
"cfg",
".",
"PARAMS",
".",
"get",
"(",
"'use_mp_spawn'",
",",
"False",
")",
":",
"lock",
"=",
"multiprocessing",
".",
"get_context",
"(",
"'spawn'... | [
177,
0
] | [
186,
15
] | python | en | ['en', 'la', 'en'] | True |
get_dl_verify_data | (section) | Returns a pandas DataFrame with all known download object hashes.
The returned dictionary resolves str: cache_obj_name (without section)
to a tuple int(size) and bytes(sha256)
| Returns a pandas DataFrame with all known download object hashes. | def get_dl_verify_data(section):
"""Returns a pandas DataFrame with all known download object hashes.
The returned dictionary resolves str: cache_obj_name (without section)
to a tuple int(size) and bytes(sha256)
"""
verify_key = 'dl_verify_data_' + section
if cfg.DATA.get(verify_key) is not No... | [
"def",
"get_dl_verify_data",
"(",
"section",
")",
":",
"verify_key",
"=",
"'dl_verify_data_'",
"+",
"section",
"if",
"cfg",
".",
"DATA",
".",
"get",
"(",
"verify_key",
")",
"is",
"not",
"None",
":",
"return",
"cfg",
".",
"DATA",
"[",
"verify_key",
"]",
"... | [
189,
0
] | [
268,
15
] | python | en | ['en', 'en', 'en'] | True |
_call_dl_func | (dl_func, cache_path) | Helper so the actual call to downloads can be overridden
| Helper so the actual call to downloads can be overridden
| def _call_dl_func(dl_func, cache_path):
"""Helper so the actual call to downloads can be overridden
"""
return dl_func(cache_path) | [
"def",
"_call_dl_func",
"(",
"dl_func",
",",
"cache_path",
")",
":",
"return",
"dl_func",
"(",
"cache_path",
")"
] | [
271,
0
] | [
274,
30
] | python | en | ['en', 'en', 'en'] | True |
_cached_download_helper | (cache_obj_name, dl_func, reset=False) | Helper function for downloads.
Takes care of checking if the file is already cached.
Only calls the actual download function when no cached version exists.
| Helper function for downloads. | def _cached_download_helper(cache_obj_name, dl_func, reset=False):
"""Helper function for downloads.
Takes care of checking if the file is already cached.
Only calls the actual download function when no cached version exists.
"""
cache_dir = cfg.PATHS['dl_cache_dir']
cache_ro = cfg.PARAMS['dl_c... | [
"def",
"_cached_download_helper",
"(",
"cache_obj_name",
",",
"dl_func",
",",
"reset",
"=",
"False",
")",
":",
"cache_dir",
"=",
"cfg",
".",
"PATHS",
"[",
"'dl_cache_dir'",
"]",
"cache_ro",
"=",
"cfg",
".",
"PARAMS",
"[",
"'dl_cache_readonly'",
"]",
"# A lot o... | [
277,
0
] | [
338,
21
] | python | en | ['da', 'en', 'en'] | True |
_verified_download_helper | (cache_obj_name, dl_func, reset=False) | Helper function for downloads.
Verifies the size and hash of the downloaded file against the included
list of known static files.
Uses _cached_download_helper to perform the actual download.
| Helper function for downloads. | def _verified_download_helper(cache_obj_name, dl_func, reset=False):
"""Helper function for downloads.
Verifies the size and hash of the downloaded file against the included
list of known static files.
Uses _cached_download_helper to perform the actual download.
"""
path = _cached_download_help... | [
"def",
"_verified_download_helper",
"(",
"cache_obj_name",
",",
"dl_func",
",",
"reset",
"=",
"False",
")",
":",
"path",
"=",
"_cached_download_helper",
"(",
"cache_obj_name",
",",
"dl_func",
",",
"reset",
")",
"try",
":",
"dl_verify",
"=",
"cfg",
".",
"PARAMS... | [
341,
0
] | [
379,
15
] | python | en | ['da', 'en', 'en'] | True |
_requests_urlretrieve | (url, path, reporthook, auth=None, timeout=None) | Implements the required features of urlretrieve on top of requests
| Implements the required features of urlretrieve on top of requests
| def _requests_urlretrieve(url, path, reporthook, auth=None, timeout=None):
"""Implements the required features of urlretrieve on top of requests
"""
chunk_size = 128 * 1024
chunk_count = 0
with requests.get(url, stream=True, auth=auth, timeout=timeout) as r:
if r.status_code != 200:
... | [
"def",
"_requests_urlretrieve",
"(",
"url",
",",
"path",
",",
"reporthook",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"chunk_size",
"=",
"128",
"*",
"1024",
"chunk_count",
"=",
"0",
"with",
"requests",
".",
"get",
"(",
"url",
","... | [
382,
0
] | [
410,
44
] | python | en | ['en', 'en', 'en'] | True |
_classic_urlretrieve | (url, path, reporthook, auth=None, timeout=None) | Thin wrapper around pythons urllib urlretrieve
| Thin wrapper around pythons urllib urlretrieve
| def _classic_urlretrieve(url, path, reporthook, auth=None, timeout=None):
"""Thin wrapper around pythons urllib urlretrieve
"""
ourl = url
if auth:
u = urlparse(url)
if '@' not in u.netloc:
netloc = auth[0] + ':' + auth[1] + '@' + u.netloc
url = u._replace(netloc... | [
"def",
"_classic_urlretrieve",
"(",
"url",
",",
"path",
",",
"reporthook",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"ourl",
"=",
"url",
"if",
"auth",
":",
"u",
"=",
"urlparse",
"(",
"url",
")",
"if",
"'@'",
"not",
"in",
"u",... | [
413,
0
] | [
435,
49
] | python | en | ['en', 'de', 'en'] | True |
url_exists | (url) | Checks if a given a URL exists or not. | Checks if a given a URL exists or not. | def url_exists(url):
"""Checks if a given a URL exists or not."""
request = requests.get(url)
return request.status_code < 400 | [
"def",
"url_exists",
"(",
"url",
")",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"return",
"request",
".",
"status_code",
"<",
"400"
] | [
462,
0
] | [
465,
36
] | python | en | ['en', 'en', 'en'] | True |
_ftps_retrieve | (url, path, reporthook, auth=None, timeout=None) | Wrapper around ftplib to download from FTPS server
| Wrapper around ftplib to download from FTPS server
| def _ftps_retrieve(url, path, reporthook, auth=None, timeout=None):
""" Wrapper around ftplib to download from FTPS server
"""
if not auth:
raise DownloadCredentialsMissingException('No authentication '
'credentials given!')
upar = urlparse(url... | [
"def",
"_ftps_retrieve",
"(",
"url",
",",
"path",
",",
"reporthook",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"auth",
":",
"raise",
"DownloadCredentialsMissingException",
"(",
"'No authentication '",
"'credentials given!'",
"... | [
468,
0
] | [
509,
20
] | python | en | ['en', 'en', 'en'] | True |
_get_url_cache_name | (url) | Returns the cache name for any given url.
| Returns the cache name for any given url.
| def _get_url_cache_name(url):
"""Returns the cache name for any given url.
"""
res = urlparse(url)
return res.netloc.split(':', 1)[0] + res.path | [
"def",
"_get_url_cache_name",
"(",
"url",
")",
":",
"res",
"=",
"urlparse",
"(",
"url",
")",
"return",
"res",
".",
"netloc",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"0",
"]",
"+",
"res",
".",
"path"
] | [
512,
0
] | [
517,
49
] | python | en | ['en', 'en', 'en'] | True |
oggm_urlretrieve | (url, cache_obj_name=None, reset=False,
reporthook=None, auth=None, timeout=None) | Wrapper around urlretrieve, to implement our caching logic.
Instead of accepting a destination path, it decided where to store the file
and returns the local path.
auth is expected to be either a tuple of ('username', 'password') or None.
| Wrapper around urlretrieve, to implement our caching logic. | def oggm_urlretrieve(url, cache_obj_name=None, reset=False,
reporthook=None, auth=None, timeout=None):
"""Wrapper around urlretrieve, to implement our caching logic.
Instead of accepting a destination path, it decided where to store the file
and returns the local path.
auth is exp... | [
"def",
"oggm_urlretrieve",
"(",
"url",
",",
"cache_obj_name",
"=",
"None",
",",
"reset",
"=",
"False",
",",
"reporthook",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"cache_obj_name",
"is",
"None",
":",
"cache_obj_... | [
520,
0
] | [
545,
65
] | python | en | ['en', 'en', 'en'] | True |
_progress_urlretrieve | (url, cache_name=None, reset=False,
auth=None, timeout=None) | Downloads a file, returns its local path, and shows a progressbar. | Downloads a file, returns its local path, and shows a progressbar. | def _progress_urlretrieve(url, cache_name=None, reset=False,
auth=None, timeout=None):
"""Downloads a file, returns its local path, and shows a progressbar."""
try:
from progressbar import DataTransferBar, UnknownLength
pbar = None
def _upd(count, size, total)... | [
"def",
"_progress_urlretrieve",
"(",
"url",
",",
"cache_name",
"=",
"None",
",",
"reset",
"=",
"False",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"from",
"progressbar",
"import",
"DataTransferBar",
",",
"UnknownLength",
"... | [
548,
0
] | [
578,
72
] | python | en | ['en', 'en', 'en'] | True |
_aws_file_download_unlocked | (aws_path, cache_name=None, reset=False) | Download a file from the AWS drive s3://astgtmv2/
**Note:** you need AWS credentials for this to work.
Parameters
----------
aws_path: path relative to s3://astgtmv2/
| Download a file from the AWS drive s3://astgtmv2/ | def _aws_file_download_unlocked(aws_path, cache_name=None, reset=False):
"""Download a file from the AWS drive s3://astgtmv2/
**Note:** you need AWS credentials for this to work.
Parameters
----------
aws_path: path relative to s3://astgtmv2/
"""
while aws_path.startswith('/'):
aw... | [
"def",
"_aws_file_download_unlocked",
"(",
"aws_path",
",",
"cache_name",
"=",
"None",
",",
"reset",
"=",
"False",
")",
":",
"while",
"aws_path",
".",
"startswith",
"(",
"'/'",
")",
":",
"aws_path",
"=",
"aws_path",
"[",
"1",
":",
"]",
"if",
"cache_name",
... | [
586,
0
] | [
607,
65
] | python | en | ['en', 'en', 'en'] | True |
file_downloader | (www_path, retry_max=5, cache_name=None,
reset=False, auth=None, timeout=None) | A slightly better downloader: it tries more than once. | A slightly better downloader: it tries more than once. | def file_downloader(www_path, retry_max=5, cache_name=None,
reset=False, auth=None, timeout=None):
"""A slightly better downloader: it tries more than once."""
local_path = None
retry_counter = 0
while retry_counter <= retry_max:
# Try to download
try:
re... | [
"def",
"file_downloader",
"(",
"www_path",
",",
"retry_max",
"=",
"5",
",",
"cache_name",
"=",
"None",
",",
"reset",
"=",
"False",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"local_path",
"=",
"None",
"retry_counter",
"=",
"0",
"w... | [
610,
0
] | [
687,
21
] | python | en | ['en', 'en', 'en'] | True |
locked_func | (func) | To decorate a function that needs to be locked for multiprocessing | To decorate a function that needs to be locked for multiprocessing | def locked_func(func):
"""To decorate a function that needs to be locked for multiprocessing"""
@wraps(func)
def wrapper(*args, **kwargs):
with get_lock():
return func(*args, **kwargs)
return wrapper | [
"def",
"locked_func",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"get_lock",
"(",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | [
690,
0
] | [
696,
18
] | python | en | ['en', 'en', 'en'] | True |
file_extractor | (file_path) | For archives with only one file inside extract the file to tmpdir. | For archives with only one file inside extract the file to tmpdir. | def file_extractor(file_path):
"""For archives with only one file inside extract the file to tmpdir."""
filename, file_extension = os.path.splitext(file_path)
# Second one for tar.gz files
f2, ex2 = os.path.splitext(filename)
if ex2 == '.tar':
filename, file_extension = f2, '.tar.gz'
bn... | [
"def",
"file_extractor",
"(",
"file_path",
")",
":",
"filename",
",",
"file_extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_path",
")",
"# Second one for tar.gz files",
"f2",
",",
"ex2",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename... | [
699,
0
] | [
779,
17
] | python | en | ['en', 'en', 'en'] | True |
download_with_authentication | (wwwfile, key) | Uses credentials from a local .netrc file to download files
This is function is currently used for TanDEM-X and ASTER
Parameters
----------
wwwfile : str
path to the file to download
key : str
the machine to to look at in the .netrc file
Returns
-------
| Uses credentials from a local .netrc file to download files | def download_with_authentication(wwwfile, key):
""" Uses credentials from a local .netrc file to download files
This is function is currently used for TanDEM-X and ASTER
Parameters
----------
wwwfile : str
path to the file to download
key : str
the machine to to look at in the ... | [
"def",
"download_with_authentication",
"(",
"wwwfile",
",",
"key",
")",
":",
"# Check the cache first. Use dummy download function to assure nothing is",
"# tried to be downloaded without credentials:",
"def",
"_always_none",
"(",
"foo",
")",
":",
"return",
"None",
"cache_obj_nam... | [
782,
0
] | [
828,
20
] | python | en | ['en', 'en', 'en'] | True |
_download_oggm_files_unlocked | () | Checks if the demo data is already on the cache and downloads it. | Checks if the demo data is already on the cache and downloads it. | def _download_oggm_files_unlocked():
"""Checks if the demo data is already on the cache and downloads it."""
zip_url = 'https://github.com/%s/archive/%s.zip' % \
(SAMPLE_DATA_GH_REPO, SAMPLE_DATA_COMMIT)
odir = os.path.join(cfg.CACHE_DIR)
sdir = os.path.join(cfg.CACHE_DIR,
... | [
"def",
"_download_oggm_files_unlocked",
"(",
")",
":",
"zip_url",
"=",
"'https://github.com/%s/archive/%s.zip'",
"%",
"(",
"SAMPLE_DATA_GH_REPO",
",",
"SAMPLE_DATA_COMMIT",
")",
"odir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cfg",
".",
"CACHE_DIR",
")",
"sdir"... | [
836,
0
] | [
865,
14
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.