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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
BlockifyUI.start | (self) | Start blockify and the main update routine. | Start blockify and the main update routine. | def start(self):
"Start blockify and the main update routine."
# Try to find a Spotify process in the current DBus session.
self.connect_dbus()
# Load the blocklist, start blockify, trap some signals and unmute.
blocklist = blockify.Blocklist()
self.b = blockify.Blockify... | [
"def",
"start",
"(",
"self",
")",
":",
"# Try to find a Spotify process in the current DBus session.",
"self",
".",
"connect_dbus",
"(",
")",
"# Load the blocklist, start blockify, trap some signals and unmute.",
"blocklist",
"=",
"blockify",
".",
"Blocklist",
"(",
")",
"self... | [
301,
4
] | [
314,
40
] | python | en | ['en', 'en', 'en'] | True |
BlockifyUI.bind_signals | (self) | Binds SIGTERM, SIGINT and SIGUSR1 to custom actions. | Binds SIGTERM, SIGINT and SIGUSR1 to custom actions. | def bind_signals(self):
"Binds SIGTERM, SIGINT and SIGUSR1 to custom actions."
signal.signal(signal.SIGUSR1, lambda sig, hdl: self.b.block_current())
signal.signal(signal.SIGUSR2, lambda sig, hdl: self.b.unblock_current())
signal.signal(signal.SIGTERM, lambda sig, hdl: self.stop())
... | [
"def",
"bind_signals",
"(",
"self",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGUSR1",
",",
"lambda",
"sig",
",",
"hdl",
":",
"self",
".",
"b",
".",
"block_current",
"(",
")",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGUSR2"... | [
316,
4
] | [
321,
66
] | python | en | ['en', 'en', 'en'] | True |
BlockifyUI.stop | (self, *args) | Cleanly shut down, unmuting sound and saving the blocklist. | Cleanly shut down, unmuting sound and saving the blocklist. | def stop(self, *args):
"Cleanly shut down, unmuting sound and saving the blocklist."
self.b.stop()
log.debug("Exiting GUI.")
gtk.main_quit() | [
"def",
"stop",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"b",
".",
"stop",
"(",
")",
"log",
".",
"debug",
"(",
"\"Exiting GUI.\"",
")",
"gtk",
".",
"main_quit",
"(",
")"
] | [
323,
4
] | [
327,
23
] | python | en | ['en', 'en', 'en'] | True |
KeyValueStorage.get | (self, key) |
Get a value identified by the given key
:param key: The unique identifier
:return: The value identified by key or None if no value was found
|
Get a value identified by the given key | def get(self, key):
"""
Get a value identified by the given key
:param key: The unique identifier
:return: The value identified by key or None if no value was found
"""
raise NotImplementedError | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"raise",
"NotImplementedError"
] | [
10,
4
] | [
18,
33
] | python | en | ['en', 'error', 'th'] | False |
KeyValueStorage.set | (self, key, value) |
Store the value identified by the key
:param key: The unique identifier
:param value: Value to store
:return: bool True on success or False on failure
|
Store the value identified by the key | def set(self, key, value):
"""
Store the value identified by the key
:param key: The unique identifier
:param value: Value to store
:return: bool True on success or False on failure
"""
raise NotImplementedError | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"raise",
"NotImplementedError"
] | [
21,
4
] | [
30,
33
] | python | en | ['en', 'error', 'th'] | False |
KeyValueStorage.delete | (self, key) |
Deletes item by key
:param key: The unique identifier
:return: bool True on success or False on failure
|
Deletes item by key | def delete(self, key):
"""
Deletes item by key
:param key: The unique identifier
:return: bool True on success or False on failure
"""
raise NotImplementedError | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"raise",
"NotImplementedError"
] | [
33,
4
] | [
41,
33
] | python | en | ['en', 'error', 'th'] | False |
KeyValueStorage.clear | (self) |
Clears all entries
:return: bool True on success or False on failure
|
Clears all entries | def clear(self):
"""
Clears all entries
:return: bool True on success or False on failure
"""
raise NotImplementedError | [
"def",
"clear",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | [
44,
4
] | [
50,
33
] | python | en | ['en', 'error', 'th'] | False |
Bytecode_compat.__iter__ | (self) | Yield '(op,arg)' pair for each operation in code object 'code | Yield '(op,arg)' pair for each operation in code object 'code | def __iter__(self):
"""Yield '(op,arg)' pair for each operation in code object 'code'"""
bytes = array.array('b', self.code.co_code)
eof = len(self.code.co_code)
ptr = 0
extended_arg = 0
while ptr < eof:
op = bytes[ptr]
if op >= dis.HAVE_ARGUM... | [
"def",
"__iter__",
"(",
"self",
")",
":",
"bytes",
"=",
"array",
".",
"array",
"(",
"'b'",
",",
"self",
".",
"code",
".",
"co_code",
")",
"eof",
"=",
"len",
"(",
"self",
".",
"code",
".",
"co_code",
")",
"ptr",
"=",
"0",
"extended_arg",
"=",
"0",... | [
20,
4
] | [
47,
32
] | python | en | ['en', 'en', 'en'] | True |
get_action_mapper | (name: str) | Get action mapper instance by name. | Get action mapper instance by name. | def get_action_mapper(name: str) -> 'ActionMapper':
"""Get action mapper instance by name."""
return ACTION_MAPPERS[name]() | [
"def",
"get_action_mapper",
"(",
"name",
":",
"str",
")",
"->",
"'ActionMapper'",
":",
"return",
"ACTION_MAPPERS",
"[",
"name",
"]",
"(",
")"
] | [
43,
0
] | [
45,
33
] | python | en | ['en', 'en', 'en'] | True |
_compute_relations | (p: np.ndarray, p1: np.ndarray,
p2: np.ndarray) | Compute relation between vector p1->p2 and point p.
Returns distance from p1->p2 to p and whether p between p1 and p2.
| Compute relation between vector p1->p2 and point p. | def _compute_relations(p: np.ndarray, p1: np.ndarray,
p2: np.ndarray) -> Tuple[float, bool]:
"""Compute relation between vector p1->p2 and point p.
Returns distance from p1->p2 to p and whether p between p1 and p2.
"""
vector = p2 - p1
vector_len = (vector * vector).sum()**.5... | [
"def",
"_compute_relations",
"(",
"p",
":",
"np",
".",
"ndarray",
",",
"p1",
":",
"np",
".",
"ndarray",
",",
"p2",
":",
"np",
".",
"ndarray",
")",
"->",
"Tuple",
"[",
"float",
",",
"bool",
"]",
":",
"vector",
"=",
"p2",
"-",
"p1",
"vector_len",
"... | [
266,
0
] | [
277,
43
] | python | en | ['en', 'en', 'en'] | True |
ActionMapper.action_to_user_input | (self, action: GeneralizedAction
) | Converts actions to points and is_valid flags.
Args:
action: A list or an array representing a single action
Returns:
A pair (user_input, is_valid).
* user_input: scene_if.User that corresponds to the action.
* is_valid: a boolean flag indicating... | Converts actions to points and is_valid flags. | def action_to_user_input(self, action: GeneralizedAction
) -> Tuple[scene_if.UserInput, bool]:
"""Converts actions to points and is_valid flags.
Args:
action: A list or an array representing a single action
Returns:
A pair (user_input, is_val... | [
"def",
"action_to_user_input",
"(",
"self",
",",
"action",
":",
"GeneralizedAction",
")",
"->",
"Tuple",
"[",
"scene_if",
".",
"UserInput",
",",
"bool",
"]",
":"
] | [
92,
4
] | [
107,
11
] | python | en | ['en', 'en', 'en'] | True |
_keep | (window, windows) | Helper function for creating rolling windows. | Helper function for creating rolling windows. | def _keep(window, windows):
"""Helper function for creating rolling windows."""
windows.append(window.copy())
return -1. | [
"def",
"_keep",
"(",
"window",
",",
"windows",
")",
":",
"windows",
".",
"append",
"(",
"window",
".",
"copy",
"(",
")",
")",
"return",
"-",
"1."
] | [
14,
0
] | [
17,
12
] | python | en | ['en', 'en', 'en'] | True |
create_rolling_features_label | (series, window_size, pred_offset, pred_n=1) | Computes rolling window of the series and creates rolling window of label.
Args:
series: A Pandas Series. The indices are datetimes and the values are
numeric type.
window_size: integer; steps of historical data to use for features.
pred_offset: integer; steps into the future for prediction.
pr... | Computes rolling window of the series and creates rolling window of label. | def create_rolling_features_label(series, window_size, pred_offset, pred_n=1):
"""Computes rolling window of the series and creates rolling window of label.
Args:
series: A Pandas Series. The indices are datetimes and the values are
numeric type.
window_size: integer; steps of historical data to use ... | [
"def",
"create_rolling_features_label",
"(",
"series",
",",
"window_size",
",",
"pred_offset",
",",
"pred_n",
"=",
"1",
")",
":",
"if",
"series",
".",
"isnull",
"(",
")",
".",
"sum",
"(",
")",
">",
"0",
":",
"raise",
"ValueError",
"(",
"'Series must not co... | [
20,
0
] | [
122,
11
] | python | en | ['en', 'en', 'en'] | True |
add_aggregate_features | (df, time_series_col_names) | Compute summary statistic features for every row of dataframe. | Compute summary statistic features for every row of dataframe. | def add_aggregate_features(df, time_series_col_names):
"""Compute summary statistic features for every row of dataframe."""
x = df[time_series_col_names]
features = {}
features['mean'] = x.mean(axis=1)
features['std'] = x.std(axis=1)
features['min'] = x.min(axis=1)
features['max'] = x.max(axis=1)
percen... | [
"def",
"add_aggregate_features",
"(",
"df",
",",
"time_series_col_names",
")",
":",
"x",
"=",
"df",
"[",
"time_series_col_names",
"]",
"features",
"=",
"{",
"}",
"features",
"[",
"'mean'",
"]",
"=",
"x",
".",
"mean",
"(",
"axis",
"=",
"1",
")",
"features... | [
125,
0
] | [
137,
65
] | python | en | ['en', 'en', 'en'] | True |
is_between_dates | (dates, start=None, end=None) | Return boolean indices indicating if dates occurs between start and end. | Return boolean indices indicating if dates occurs between start and end. | def is_between_dates(dates, start=None, end=None):
"""Return boolean indices indicating if dates occurs between start and end."""
if start is None:
start = pd.to_datetime(0)
if end is None:
end = pd.to_datetime(sys.maxsize)
date_series = pd.Series(pd.to_datetime(dates))
return date_series.between(star... | [
"def",
"is_between_dates",
"(",
"dates",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"pd",
".",
"to_datetime",
"(",
"0",
")",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"pd",
".",... | [
146,
0
] | [
153,
47
] | python | en | ['en', 'en', 'en'] | True |
_count_holidays | (dates, months, weeks) | Count number of holidays spanned in prediction windows. | Count number of holidays spanned in prediction windows. | def _count_holidays(dates, months, weeks):
"""Count number of holidays spanned in prediction windows."""
cal = calendar()
holidays = cal.holidays(start=dates.min(), end=dates.max())
def count_holidays_during_month(date):
n_holidays = 0
beg = date
end = date + pd.DateOffset(months=months, weeks=week... | [
"def",
"_count_holidays",
"(",
"dates",
",",
"months",
",",
"weeks",
")",
":",
"cal",
"=",
"calendar",
"(",
")",
"holidays",
"=",
"cal",
".",
"holidays",
"(",
"start",
"=",
"dates",
".",
"min",
"(",
")",
",",
"end",
"=",
"dates",
".",
"max",
"(",
... | [
156,
0
] | [
170,
60
] | python | en | ['en', 'en', 'en'] | True |
_get_day_of_month | (x) | From a datetime object, extract day of month. | From a datetime object, extract day of month. | def _get_day_of_month(x):
"""From a datetime object, extract day of month."""
return int(x.strftime('%d')) | [
"def",
"_get_day_of_month",
"(",
"x",
")",
":",
"return",
"int",
"(",
"x",
".",
"strftime",
"(",
"'%d'",
")",
")"
] | [
173,
0
] | [
175,
30
] | python | en | ['en', 'en', 'en'] | True |
add_date_features | (df, dates, months, weeks, inplace=False) | Create features using date that is being predicted on. | Create features using date that is being predicted on. | def add_date_features(df, dates, months, weeks, inplace=False):
"""Create features using date that is being predicted on."""
if not inplace:
df = df.copy()
df['doy'] = dates.dayofyear
df['dom'] = dates.map(_get_day_of_month)
df['month'] = dates.month
df['year'] = dates.year
df['n_holidays'] = _count_h... | [
"def",
"add_date_features",
"(",
"df",
",",
"dates",
",",
"months",
",",
"weeks",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"not",
"inplace",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"df",
"[",
"'doy'",
"]",
"=",
"dates",
".",
"dayofyear",
... | [
178,
0
] | [
187,
11
] | python | en | ['en', 'en', 'en'] | True |
Metrics.calculate_rmse | (self, residuals) | Root mean squared error. | Root mean squared error. | def calculate_rmse(self, residuals):
"""Root mean squared error."""
return np.sqrt(np.mean(np.square(residuals))) | [
"def",
"calculate_rmse",
"(",
"self",
",",
"residuals",
")",
":",
"return",
"np",
".",
"sqrt",
"(",
"np",
".",
"mean",
"(",
"np",
".",
"square",
"(",
"residuals",
")",
")",
")"
] | [
201,
2
] | [
203,
49
] | python | en | ['en', 'en', 'en'] | True |
Metrics.calculate_mae | (self, residuals) | Mean absolute error. | Mean absolute error. | def calculate_mae(self, residuals):
"""Mean absolute error."""
return np.mean(np.abs(residuals)) | [
"def",
"calculate_mae",
"(",
"self",
",",
"residuals",
")",
":",
"return",
"np",
".",
"mean",
"(",
"np",
".",
"abs",
"(",
"residuals",
")",
")"
] | [
205,
2
] | [
207,
37
] | python | en | ['et', 'gd', 'en'] | False |
Metrics.calculate_malr | (self, y_true, predictions) | Mean absolute log ratio. | Mean absolute log ratio. | def calculate_malr(self, y_true, predictions):
"""Mean absolute log ratio."""
return np.mean(np.abs(np.log(1 + predictions) - np.log(1 + y_true))) | [
"def",
"calculate_malr",
"(",
"self",
",",
"y_true",
",",
"predictions",
")",
":",
"return",
"np",
".",
"mean",
"(",
"np",
".",
"abs",
"(",
"np",
".",
"log",
"(",
"1",
"+",
"predictions",
")",
"-",
"np",
".",
"log",
"(",
"1",
"+",
"y_true",
")",
... | [
209,
2
] | [
211,
72
] | python | en | ['en', 'en', 'en'] | True |
get_word_alignment | (num, force_arch=64,
_machine_word_size=MACHINE_WORD_SIZE) |
Returns alignment details for the given number based on the platform
Python is running on.
:param num:
Unsigned integral number.
:param force_arch:
If you don't want to use 64-bit unsigned chunks, set this to
anything other than 64. 32-bit chunks will be preferred then.
... |
Returns alignment details for the given number based on the platform
Python is running on. | def get_word_alignment(num, force_arch=64,
_machine_word_size=MACHINE_WORD_SIZE):
"""
Returns alignment details for the given number based on the platform
Python is running on.
:param num:
Unsigned integral number.
:param force_arch:
If you don't want to use 6... | [
"def",
"get_word_alignment",
"(",
"num",
",",
"force_arch",
"=",
"64",
",",
"_machine_word_size",
"=",
"MACHINE_WORD_SIZE",
")",
":",
"max_uint64",
"=",
"0xffffffffffffffff",
"max_uint32",
"=",
"0xffffffff",
"max_uint16",
"=",
"0xffff",
"max_uint8",
"=",
"0xff",
"... | [
37,
0
] | [
73,
35
] | python | en | ['en', 'error', 'th'] | False |
endswith_cr | (line) | Return True if line (a text or bytestring) ends with '\r'. | Return True if line (a text or bytestring) ends with '\r'. | def endswith_cr(line):
"""Return True if line (a text or bytestring) ends with '\r'."""
return line.endswith('\r' if isinstance(line, str) else b'\r') | [
"def",
"endswith_cr",
"(",
"line",
")",
":",
"return",
"line",
".",
"endswith",
"(",
"'\\r'",
"if",
"isinstance",
"(",
"line",
",",
"str",
")",
"else",
"b'\\r'",
")"
] | [
147,
0
] | [
149,
66
] | python | en | ['en', 'en', 'en'] | True |
endswith_lf | (line) | Return True if line (a text or bytestring) ends with '\n'. | Return True if line (a text or bytestring) ends with '\n'. | def endswith_lf(line):
"""Return True if line (a text or bytestring) ends with '\n'."""
return line.endswith('\n' if isinstance(line, str) else b'\n') | [
"def",
"endswith_lf",
"(",
"line",
")",
":",
"return",
"line",
".",
"endswith",
"(",
"'\\n'",
"if",
"isinstance",
"(",
"line",
",",
"str",
")",
"else",
"b'\\n'",
")"
] | [
152,
0
] | [
154,
66
] | python | en | ['en', 'en', 'en'] | True |
equals_lf | (line) | Return True if line (a text or bytestring) equals '\n'. | Return True if line (a text or bytestring) equals '\n'. | def equals_lf(line):
"""Return True if line (a text or bytestring) equals '\n'."""
return line == ('\n' if isinstance(line, str) else b'\n') | [
"def",
"equals_lf",
"(",
"line",
")",
":",
"return",
"line",
"==",
"(",
"'\\n'",
"if",
"isinstance",
"(",
"line",
",",
"str",
")",
"else",
"b'\\n'",
")"
] | [
157,
0
] | [
159,
61
] | python | en | ['en', 'en', 'en'] | True |
File.chunks | (self, chunk_size=None) |
Read the file and yield chunks of ``chunk_size`` bytes (defaults to
``File.DEFAULT_CHUNK_SIZE``).
|
Read the file and yield chunks of ``chunk_size`` bytes (defaults to
``File.DEFAULT_CHUNK_SIZE``).
| def chunks(self, chunk_size=None):
"""
Read the file and yield chunks of ``chunk_size`` bytes (defaults to
``File.DEFAULT_CHUNK_SIZE``).
"""
chunk_size = chunk_size or self.DEFAULT_CHUNK_SIZE
try:
self.seek(0)
except (AttributeError, UnsupportedOperati... | [
"def",
"chunks",
"(",
"self",
",",
"chunk_size",
"=",
"None",
")",
":",
"chunk_size",
"=",
"chunk_size",
"or",
"self",
".",
"DEFAULT_CHUNK_SIZE",
"try",
":",
"self",
".",
"seek",
"(",
"0",
")",
"except",
"(",
"AttributeError",
",",
"UnsupportedOperation",
... | [
47,
4
] | [
62,
22
] | python | en | ['en', 'error', 'th'] | False |
File.multiple_chunks | (self, chunk_size=None) |
Return ``True`` if you can expect multiple chunks.
NB: If a particular file representation is in memory, subclasses should
always return ``False`` -- there's no good reason to read from memory in
chunks.
|
Return ``True`` if you can expect multiple chunks. | def multiple_chunks(self, chunk_size=None):
"""
Return ``True`` if you can expect multiple chunks.
NB: If a particular file representation is in memory, subclasses should
always return ``False`` -- there's no good reason to read from memory in
chunks.
"""
return ... | [
"def",
"multiple_chunks",
"(",
"self",
",",
"chunk_size",
"=",
"None",
")",
":",
"return",
"self",
".",
"size",
">",
"(",
"chunk_size",
"or",
"self",
".",
"DEFAULT_CHUNK_SIZE",
")"
] | [
64,
4
] | [
72,
66
] | python | en | ['en', 'error', 'th'] | False |
get_parquet_schema | (project, dataset, table) | Return parquet schema for specified table. | Return parquet schema for specified table. | def get_parquet_schema(project, dataset, table):
'''Return parquet schema for specified table.'''
project_id = project
dataset_id = dataset
table_id = table
data_type_mapping = {
'STRING': pyarrow.string(),
'BYTES': pyarrow.string(),
'INTEGER': pyarrow.int64(),
'FLOAT... | [
"def",
"get_parquet_schema",
"(",
"project",
",",
"dataset",
",",
"table",
")",
":",
"project_id",
"=",
"project",
"dataset_id",
"=",
"dataset",
"table_id",
"=",
"table",
"data_type_mapping",
"=",
"{",
"'STRING'",
":",
"pyarrow",
".",
"string",
"(",
")",
","... | [
24,
0
] | [
50,
25
] | python | en | ['en', 'en', 'en'] | True |
run | (argv=None) | Main entry point: defines and runs the BQ extraction pipeline | Main entry point: defines and runs the BQ extraction pipeline | def run(argv=None):
'''Main entry point: defines and runs the BQ extraction pipeline'''
parser = argparse.ArgumentParser()
# Custom arguments for BigQuery SQL and GCS output location
parser.add_argument('--bql',
dest='bql',
help='BigQuery Standard SQL stat... | [
"def",
"run",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"# Custom arguments for BigQuery SQL and GCS output location",
"parser",
".",
"add_argument",
"(",
"'--bql'",
",",
"dest",
"=",
"'bql'",
",",
"help",
"=... | [
53,
0
] | [
83,
92
] | python | en | ['en', 'en', 'en'] | True |
parse_args | () | Parse arguments. | Parse arguments. | def parse_args():
"""Parse arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('-c',
'--cfg',
type=str,
required=True,
help='Overrides config file')
parser.add_argument('-l',
... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-c'",
",",
"'--cfg'",
",",
"type",
"=",
"str",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'Overrides config file'",
... | [
41,
0
] | [
93,
15
] | python | en | ['en', 'fr', 'en'] | False |
get_sweep_param_from_combinations | (clis) |
Returns:
[(run_id, overrides_dict)]. The run_id can be None if unsure what hydra
would use.
|
Returns:
[(run_id, overrides_dict)]. The run_id can be None if unsure what hydra
would use.
| def get_sweep_param_from_combinations(clis):
"""
Returns:
[(run_id, overrides_dict)]. The run_id can be None if unsure what hydra
would use.
"""
sweep_params = OrderedDict()
final_clis = {}
for cli in clis:
config_key, config_vals = cli.split('=')
if ',' not i... | [
"def",
"get_sweep_param_from_combinations",
"(",
"clis",
")",
":",
"sweep_params",
"=",
"OrderedDict",
"(",
")",
"final_clis",
"=",
"{",
"}",
"for",
"cli",
"in",
"clis",
":",
"config_key",
",",
"config_vals",
"=",
"cli",
".",
"split",
"(",
"'='",
")",
"if"... | [
96,
0
] | [
120,
74
] | python | en | ['en', 'error', 'th'] | False |
subselect_dict_keys_diff | (run_id_param_dicts) | Select keys from the param_dicts that actually change between configs. | Select keys from the param_dicts that actually change between configs. | def subselect_dict_keys_diff(run_id_param_dicts):
"""Select keys from the param_dicts that actually change between configs."""
key_vals = {}
for _, param_dict in run_id_param_dicts:
for key, val in param_dict.items():
if key not in key_vals:
key_vals[key] = []
... | [
"def",
"subselect_dict_keys_diff",
"(",
"run_id_param_dicts",
")",
":",
"key_vals",
"=",
"{",
"}",
"for",
"_",
",",
"param_dict",
"in",
"run_id_param_dicts",
":",
"for",
"key",
",",
"val",
"in",
"param_dict",
".",
"items",
"(",
")",
":",
"if",
"key",
"not"... | [
136,
0
] | [
148,
76
] | python | en | ['en', 'en', 'en'] | True |
choose_single_run | (clis, fpath, run_id) |
clis are a list of flags provided in the config overrides file.
Args:
clis: List of clis from the txt file
run_id: If known which model to run locally, the run_id of that sweep
|
clis are a list of flags provided in the config overrides file.
Args:
clis: List of clis from the txt file
run_id: If known which model to run locally, the run_id of that sweep
| def choose_single_run(clis, fpath, run_id):
"""
clis are a list of flags provided in the config overrides file.
Args:
clis: List of clis from the txt file
run_id: If known which model to run locally, the run_id of that sweep
"""
# Check if this has been run before, then we can pick t... | [
"def",
"choose_single_run",
"(",
"clis",
",",
"fpath",
",",
"run_id",
")",
":",
"# Check if this has been run before, then we can pick the overrides from",
"# the .hydra folder. Else, will have to manually construct potential",
"# combinations that will be run by hydra",
"run_id_param_dict... | [
151,
0
] | [
189,
5
] | python | en | ['en', 'error', 'th'] | False |
read_file_into_cli | (fpath, running_local=False, run_id=None) | Read cli from file into a string. | Read cli from file into a string. | def read_file_into_cli(fpath, running_local=False, run_id=None):
"""Read cli from file into a string."""
res = []
with open(fpath, 'r') as fin:
for line in fin:
args = line.split('#')[0].strip()
if len(args) == 0:
continue
res.append(args)
if r... | [
"def",
"read_file_into_cli",
"(",
"fpath",
",",
"running_local",
"=",
"False",
",",
"run_id",
"=",
"None",
")",
":",
"res",
"=",
"[",
"]",
"with",
"open",
"(",
"fpath",
",",
"'r'",
")",
"as",
"fin",
":",
"for",
"line",
"in",
"fin",
":",
"args",
"="... | [
192,
0
] | [
205,
28
] | python | en | ['en', 'en', 'en'] | True |
get_models_dir | (dpath) | Go inside the dpath to get the model dir. | Go inside the dpath to get the model dir. | def get_models_dir(dpath):
"""Go inside the dpath to get the model dir."""
runs = sorted([el for el in next(os.walk(dpath))[1] if el.isdigit()])
if len(runs) > 1:
# Ask which run to use
question = [
inquirer.List(
'run',
message='Which run to use?'... | [
"def",
"get_models_dir",
"(",
"dpath",
")",
":",
"runs",
"=",
"sorted",
"(",
"[",
"el",
"for",
"el",
"in",
"next",
"(",
"os",
".",
"walk",
"(",
"dpath",
")",
")",
"[",
"1",
"]",
"if",
"el",
".",
"isdigit",
"(",
")",
"]",
")",
"if",
"len",
"("... | [
208,
0
] | [
223,
39
] | python | en | ['en', 'en', 'en'] | True |
construct_cmd | (args) | Construct the cmd as provided in args. | Construct the cmd as provided in args. | def construct_cmd(args):
"""Construct the cmd as provided in args."""
if args.cfg:
assert args.cfg.startswith('expts'), 'Must be wrt this directory'
agent_folder = '{}/{}'.format(BASE_RUN_DIR,
args.cfg if args.cfg else 'default')
if (args.local or args.local_car... | [
"def",
"construct_cmd",
"(",
"args",
")",
":",
"if",
"args",
".",
"cfg",
":",
"assert",
"args",
".",
"cfg",
".",
"startswith",
"(",
"'expts'",
")",
",",
"'Must be wrt this directory'",
"agent_folder",
"=",
"'{}/{}'",
".",
"format",
"(",
"BASE_RUN_DIR",
",",
... | [
240,
0
] | [
308,
14
] | python | en | ['en', 'en', 'en'] | True |
_const_compare_digest_backport | (a, b) |
Compare two digests of equal length in constant time.
The digests must be of type str/bytes.
Returns True if the digests match, and False otherwise.
|
Compare two digests of equal length in constant time. | def _const_compare_digest_backport(a, b):
"""
Compare two digests of equal length in constant time.
The digests must be of type str/bytes.
Returns True if the digests match, and False otherwise.
"""
result = abs(len(a) - len(b))
for left, right in zip(bytearray(a), bytearray(b)):
re... | [
"def",
"_const_compare_digest_backport",
"(",
"a",
",",
"b",
")",
":",
"result",
"=",
"abs",
"(",
"len",
"(",
"a",
")",
"-",
"len",
"(",
"b",
")",
")",
"for",
"left",
",",
"right",
"in",
"zip",
"(",
"bytearray",
"(",
"a",
")",
",",
"bytearray",
"... | [
29,
0
] | [
39,
22
] | python | en | ['en', 'error', 'th'] | False |
assert_fingerprint | (cert, fingerprint) |
Checks if given fingerprint matches the supplied certificate.
:param cert:
Certificate as bytes object.
:param fingerprint:
Fingerprint as string of hexdigits, can be interspersed by colons.
|
Checks if given fingerprint matches the supplied certificate. | def assert_fingerprint(cert, fingerprint):
"""
Checks if given fingerprint matches the supplied certificate.
:param cert:
Certificate as bytes object.
:param fingerprint:
Fingerprint as string of hexdigits, can be interspersed by colons.
"""
fingerprint = fingerprint.replace(":... | [
"def",
"assert_fingerprint",
"(",
"cert",
",",
"fingerprint",
")",
":",
"fingerprint",
"=",
"fingerprint",
".",
"replace",
"(",
"\":\"",
",",
"\"\"",
")",
".",
"lower",
"(",
")",
"digest_length",
"=",
"len",
"(",
"fingerprint",
")",
"hashfunc",
"=",
"HASHF... | [
181,
0
] | [
207,
9
] | python | en | ['en', 'error', 'th'] | False |
resolve_cert_reqs | (candidate) |
Resolves the argument to a numeric constant, which can be passed to
the wrap_socket function/method from the ssl module.
Defaults to :data:`ssl.CERT_REQUIRED`.
If given a string it is assumed to be the name of the constant in the
:mod:`ssl` module or its abbreviation.
(So you can specify `REQUI... |
Resolves the argument to a numeric constant, which can be passed to
the wrap_socket function/method from the ssl module.
Defaults to :data:`ssl.CERT_REQUIRED`.
If given a string it is assumed to be the name of the constant in the
:mod:`ssl` module or its abbreviation.
(So you can specify `REQUI... | def resolve_cert_reqs(candidate):
"""
Resolves the argument to a numeric constant, which can be passed to
the wrap_socket function/method from the ssl module.
Defaults to :data:`ssl.CERT_REQUIRED`.
If given a string it is assumed to be the name of the constant in the
:mod:`ssl` module or its abb... | [
"def",
"resolve_cert_reqs",
"(",
"candidate",
")",
":",
"if",
"candidate",
"is",
"None",
":",
"return",
"CERT_REQUIRED",
"if",
"isinstance",
"(",
"candidate",
",",
"str",
")",
":",
"res",
"=",
"getattr",
"(",
"ssl",
",",
"candidate",
",",
"None",
")",
"i... | [
210,
0
] | [
230,
20
] | python | en | ['en', 'error', 'th'] | False |
resolve_ssl_version | (candidate) |
like resolve_cert_reqs
|
like resolve_cert_reqs
| def resolve_ssl_version(candidate):
"""
like resolve_cert_reqs
"""
if candidate is None:
return PROTOCOL_TLS
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, "PROTOCOL_" + candidate)
return res
ret... | [
"def",
"resolve_ssl_version",
"(",
"candidate",
")",
":",
"if",
"candidate",
"is",
"None",
":",
"return",
"PROTOCOL_TLS",
"if",
"isinstance",
"(",
"candidate",
",",
"str",
")",
":",
"res",
"=",
"getattr",
"(",
"ssl",
",",
"candidate",
",",
"None",
")",
"... | [
233,
0
] | [
246,
20
] | python | en | ['en', 'error', 'th'] | False |
create_urllib3_context | (
ssl_version=None, cert_reqs=None, options=None, ciphers=None
) | All arguments have the same meaning as ``ssl_wrap_socket``.
By default, this function does a lot of the same work that
``ssl.create_default_context`` does on Python 3.4+. It:
- Disables SSLv2, SSLv3, and compression
- Sets a restricted set of server ciphers
If you wish to enable SSLv3, you can do... | All arguments have the same meaning as ``ssl_wrap_socket``. | def create_urllib3_context(
ssl_version=None, cert_reqs=None, options=None, ciphers=None
):
"""All arguments have the same meaning as ``ssl_wrap_socket``.
By default, this function does a lot of the same work that
``ssl.create_default_context`` does on Python 3.4+. It:
- Disables SSLv2, SSLv3, and... | [
"def",
"create_urllib3_context",
"(",
"ssl_version",
"=",
"None",
",",
"cert_reqs",
"=",
"None",
",",
"options",
"=",
"None",
",",
"ciphers",
"=",
"None",
")",
":",
"# PROTOCOL_TLS is deprecated in Python 3.10",
"if",
"not",
"ssl_version",
"or",
"ssl_version",
"==... | [
249,
0
] | [
351,
18
] | python | en | ['en', 'en', 'en'] | True |
ssl_wrap_socket | (
sock,
keyfile=None,
certfile=None,
cert_reqs=None,
ca_certs=None,
server_hostname=None,
ssl_version=None,
ciphers=None,
ssl_context=None,
ca_cert_dir=None,
key_password=None,
ca_cert_data=None,
tls_in_tls=False,
) |
All arguments except for server_hostname, ssl_context, and ca_cert_dir have
the same meaning as they do when using :func:`ssl.wrap_socket`.
:param server_hostname:
When SNI is supported, the expected hostname of the certificate
:param ssl_context:
A pre-made :class:`SSLContext` object.... |
All arguments except for server_hostname, ssl_context, and ca_cert_dir have
the same meaning as they do when using :func:`ssl.wrap_socket`. | def ssl_wrap_socket(
sock,
keyfile=None,
certfile=None,
cert_reqs=None,
ca_certs=None,
server_hostname=None,
ssl_version=None,
ciphers=None,
ssl_context=None,
ca_cert_dir=None,
key_password=None,
ca_cert_data=None,
tls_in_tls=False,
):
"""
All arguments except... | [
"def",
"ssl_wrap_socket",
"(",
"sock",
",",
"keyfile",
"=",
"None",
",",
"certfile",
"=",
"None",
",",
"cert_reqs",
"=",
"None",
",",
"ca_certs",
"=",
"None",
",",
"server_hostname",
"=",
"None",
",",
"ssl_version",
"=",
"None",
",",
"ciphers",
"=",
"Non... | [
354,
0
] | [
453,
19
] | python | en | ['en', 'error', 'th'] | False |
is_ipaddress | (hostname) | Detects whether the hostname given is an IPv4 or IPv6 address.
Also detects IPv6 addresses with Zone IDs.
:param str hostname: Hostname to examine.
:return: True if the hostname is an IP address, False otherwise.
| Detects whether the hostname given is an IPv4 or IPv6 address.
Also detects IPv6 addresses with Zone IDs. | def is_ipaddress(hostname):
"""Detects whether the hostname given is an IPv4 or IPv6 address.
Also detects IPv6 addresses with Zone IDs.
:param str hostname: Hostname to examine.
:return: True if the hostname is an IP address, False otherwise.
"""
if not six.PY2 and isinstance(hostname, bytes):... | [
"def",
"is_ipaddress",
"(",
"hostname",
")",
":",
"if",
"not",
"six",
".",
"PY2",
"and",
"isinstance",
"(",
"hostname",
",",
"bytes",
")",
":",
"# IDN A-label bytes are ASCII compatible.",
"hostname",
"=",
"hostname",
".",
"decode",
"(",
"\"ascii\"",
")",
"ret... | [
456,
0
] | [
466,
83
] | python | en | ['en', 'en', 'en'] | True |
_is_key_file_encrypted | (key_file) | Detects if a key file is encrypted or not. | Detects if a key file is encrypted or not. | def _is_key_file_encrypted(key_file):
"""Detects if a key file is encrypted or not."""
with open(key_file, "r") as f:
for line in f:
# Look for Proc-Type: 4,ENCRYPTED
if "ENCRYPTED" in line:
return True
return False | [
"def",
"_is_key_file_encrypted",
"(",
"key_file",
")",
":",
"with",
"open",
"(",
"key_file",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"# Look for Proc-Type: 4,ENCRYPTED",
"if",
"\"ENCRYPTED\"",
"in",
"line",
":",
"return",
"True",
"r... | [
469,
0
] | [
477,
16
] | python | en | ['en', 'en', 'en'] | True |
TestNet.draw_graph | (self, model_name) |
グラフ描画
:return: 未定
|
グラフ描画
:return: 未定
| def draw_graph(self, model_name):
"""
グラフ描画
:return: 未定
"""
import inspect
import os
import matplotlib
matplotlib.use('Agg')
here = "/".join(inspect.stack()[0][1].split("/")[:-2])
data_dir = os.path.join(here, "data")
data_graphs_di... | [
"def",
"draw_graph",
"(",
"self",
",",
"model_name",
")",
":",
"import",
"inspect",
"import",
"os",
"import",
"matplotlib",
"matplotlib",
".",
"use",
"(",
"'Agg'",
")",
"here",
"=",
"\"/\"",
".",
"join",
"(",
"inspect",
".",
"stack",
"(",
")",
"[",
"0"... | [
68,
4
] | [
97,
101
] | python | en | ['en', 'error', 'th'] | False |
fax_sent | () | Define a handler for when the fax is initially sent. | Define a handler for when the fax is initially sent. | def fax_sent():
"""Define a handler for when the fax is initially sent."""
# Let's manually build some TwiML. We can choose to receive the
# fax with <Receive>, or reject with <Reject>.
twiml = """
<Response>
<Receive action="/fax/received"/>
</Response>
"""
return R... | [
"def",
"fax_sent",
"(",
")",
":",
"# Let's manually build some TwiML. We can choose to receive the",
"# fax with <Receive>, or reject with <Reject>.",
"twiml",
"=",
"\"\"\"\n <Response>\n <Receive action=\"/fax/received\"/>\n </Response>\n \"\"\"",
"return",
"Respon... | [
10,
0
] | [
20,
47
] | python | en | ['en', 'en', 'en'] | True |
fax_received | () | Define a handler for when the fax finished sending to us. | Define a handler for when the fax finished sending to us. | def fax_received():
"""Define a handler for when the fax finished sending to us."""
# We will have a URL to the contents of the fax at this point
# log the URL of the PDF received in the fax
print(request.form.get('MediaUrl'))
# Respond with empty 200/OK to Twilio
return '', 200 | [
"def",
"fax_received",
"(",
")",
":",
"# We will have a URL to the contents of the fax at this point",
"# log the URL of the PDF received in the fax",
"print",
"(",
"request",
".",
"form",
".",
"get",
"(",
"'MediaUrl'",
")",
")",
"# Respond with empty 200/OK to Twilio",
"return... | [
24,
0
] | [
31,
18
] | python | en | ['en', 'en', 'en'] | True |
get_path_info | (environ) | Return the HTTP request's PATH_INFO as a string. | Return the HTTP request's PATH_INFO as a string. | def get_path_info(environ):
"""Return the HTTP request's PATH_INFO as a string."""
path_info = get_bytes_from_wsgi(environ, 'PATH_INFO', '/')
return repercent_broken_unicode(path_info).decode() | [
"def",
"get_path_info",
"(",
"environ",
")",
":",
"path_info",
"=",
"get_bytes_from_wsgi",
"(",
"environ",
",",
"'PATH_INFO'",
",",
"'/'",
")",
"return",
"repercent_broken_unicode",
"(",
"path_info",
")",
".",
"decode",
"(",
")"
] | [
151,
0
] | [
155,
55
] | python | en | ['en', 'en', 'en'] | True |
get_script_name | (environ) |
Return the equivalent of the HTTP request's SCRIPT_NAME environment
variable. If Apache mod_rewrite is used, return what would have been
the script name prior to any rewriting (so it's the script name as seen
from the client's perspective), unless the FORCE_SCRIPT_NAME setting is
set (to anything).... |
Return the equivalent of the HTTP request's SCRIPT_NAME environment
variable. If Apache mod_rewrite is used, return what would have been
the script name prior to any rewriting (so it's the script name as seen
from the client's perspective), unless the FORCE_SCRIPT_NAME setting is
set (to anything).... | def get_script_name(environ):
"""
Return the equivalent of the HTTP request's SCRIPT_NAME environment
variable. If Apache mod_rewrite is used, return what would have been
the script name prior to any rewriting (so it's the script name as seen
from the client's perspective), unless the FORCE_SCRIPT_N... | [
"def",
"get_script_name",
"(",
"environ",
")",
":",
"if",
"settings",
".",
"FORCE_SCRIPT_NAME",
"is",
"not",
"None",
":",
"return",
"settings",
".",
"FORCE_SCRIPT_NAME",
"# If Apache's mod_rewrite had a whack at the URL, Apache set either",
"# SCRIPT_URL or REDIRECT_URL to the ... | [
158,
0
] | [
186,
31
] | python | en | ['en', 'error', 'th'] | False |
get_bytes_from_wsgi | (environ, key, default) |
Get a value from the WSGI environ dictionary as bytes.
key and default should be strings.
|
Get a value from the WSGI environ dictionary as bytes. | def get_bytes_from_wsgi(environ, key, default):
"""
Get a value from the WSGI environ dictionary as bytes.
key and default should be strings.
"""
value = environ.get(key, default)
# Non-ASCII values in the WSGI environ are arbitrarily decoded with
# ISO-8859-1. This is wrong for Django webs... | [
"def",
"get_bytes_from_wsgi",
"(",
"environ",
",",
"key",
",",
"default",
")",
":",
"value",
"=",
"environ",
".",
"get",
"(",
"key",
",",
"default",
")",
"# Non-ASCII values in the WSGI environ are arbitrarily decoded with",
"# ISO-8859-1. This is wrong for Django websites ... | [
189,
0
] | [
199,
37
] | python | en | ['en', 'error', 'th'] | False |
get_str_from_wsgi | (environ, key, default) |
Get a value from the WSGI environ dictionary as str.
key and default should be str objects.
|
Get a value from the WSGI environ dictionary as str. | def get_str_from_wsgi(environ, key, default):
"""
Get a value from the WSGI environ dictionary as str.
key and default should be str objects.
"""
value = get_bytes_from_wsgi(environ, key, default)
return value.decode(errors='replace') | [
"def",
"get_str_from_wsgi",
"(",
"environ",
",",
"key",
",",
"default",
")",
":",
"value",
"=",
"get_bytes_from_wsgi",
"(",
"environ",
",",
"key",
",",
"default",
")",
"return",
"value",
".",
"decode",
"(",
"errors",
"=",
"'replace'",
")"
] | [
202,
0
] | [
209,
41
] | python | en | ['en', 'error', 'th'] | False |
voice | () | Respond to incoming phone calls with a 'Hello world' message | Respond to incoming phone calls with a 'Hello world' message | def voice():
"""Respond to incoming phone calls with a 'Hello world' message"""
# Start our TwiML response
resp = VoiceResponse()
# Read a message aloud to the caller
resp.say("hello world!", voice='alice')
return str(resp) | [
"def",
"voice",
"(",
")",
":",
"# Start our TwiML response",
"resp",
"=",
"VoiceResponse",
"(",
")",
"# Read a message aloud to the caller",
"resp",
".",
"say",
"(",
"\"hello world!\"",
",",
"voice",
"=",
"'alice'",
")",
"return",
"str",
"(",
"resp",
")"
] | [
7,
0
] | [
15,
20
] | python | en | ['en', 'en', 'en'] | True |
_looks_like_bpo_44860 | () | The resolution to bpo-44860 will change this incorrect platlib.
See <https://bugs.python.org/issue44860>.
| The resolution to bpo-44860 will change this incorrect platlib. | def _looks_like_bpo_44860() -> bool:
"""The resolution to bpo-44860 will change this incorrect platlib.
See <https://bugs.python.org/issue44860>.
"""
from distutils.command.install import INSTALL_SCHEMES # type: ignore
try:
unix_user_platlib = INSTALL_SCHEMES["unix_user"]["platlib"]
e... | [
"def",
"_looks_like_bpo_44860",
"(",
")",
"->",
"bool",
":",
"from",
"distutils",
".",
"command",
".",
"install",
"import",
"INSTALL_SCHEMES",
"# type: ignore",
"try",
":",
"unix_user_platlib",
"=",
"INSTALL_SCHEMES",
"[",
"\"unix_user\"",
"]",
"[",
"\"platlib\"",
... | [
48,
0
] | [
59,
43
] | python | en | ['en', 'en', 'en'] | True |
_looks_like_red_hat_lib | () | Red Hat patches platlib in unix_prefix and unix_home, but not purelib.
This is the only way I can see to tell a Red Hat-patched Python.
| Red Hat patches platlib in unix_prefix and unix_home, but not purelib. | def _looks_like_red_hat_lib() -> bool:
"""Red Hat patches platlib in unix_prefix and unix_home, but not purelib.
This is the only way I can see to tell a Red Hat-patched Python.
"""
from distutils.command.install import INSTALL_SCHEMES # type: ignore
return all(
k in INSTALL_SCHEMES
... | [
"def",
"_looks_like_red_hat_lib",
"(",
")",
"->",
"bool",
":",
"from",
"distutils",
".",
"command",
".",
"install",
"import",
"INSTALL_SCHEMES",
"# type: ignore",
"return",
"all",
"(",
"k",
"in",
"INSTALL_SCHEMES",
"and",
"_looks_like_red_hat_patched_platlib_purelib",
... | [
71,
0
] | [
82,
5
] | python | en | ['en', 'en', 'en'] | True |
_looks_like_debian_scheme | () | Debian adds two additional schemes. | Debian adds two additional schemes. | def _looks_like_debian_scheme() -> bool:
"""Debian adds two additional schemes."""
from distutils.command.install import INSTALL_SCHEMES # type: ignore
return "deb_system" in INSTALL_SCHEMES and "unix_local" in INSTALL_SCHEMES | [
"def",
"_looks_like_debian_scheme",
"(",
")",
"->",
"bool",
":",
"from",
"distutils",
".",
"command",
".",
"install",
"import",
"INSTALL_SCHEMES",
"# type: ignore",
"return",
"\"deb_system\"",
"in",
"INSTALL_SCHEMES",
"and",
"\"unix_local\"",
"in",
"INSTALL_SCHEMES"
] | [
86,
0
] | [
90,
78
] | python | en | ['en', 'en', 'en'] | True |
_looks_like_red_hat_scheme | () | Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``.
Red Hat's ``00251-change-user-install-location.patch`` changes the install
command's ``prefix`` and ``exec_prefix`` to append ``"/local"``. This is
(fortunately?) done quite unconditionally, so we create a default command
object without any config... | Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``. | def _looks_like_red_hat_scheme() -> bool:
"""Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``.
Red Hat's ``00251-change-user-install-location.patch`` changes the install
command's ``prefix`` and ``exec_prefix`` to append ``"/local"``. This is
(fortunately?) done quite unconditionally, so we creat... | [
"def",
"_looks_like_red_hat_scheme",
"(",
")",
"->",
"bool",
":",
"from",
"distutils",
".",
"command",
".",
"install",
"import",
"install",
"from",
"distutils",
".",
"dist",
"import",
"Distribution",
"cmd",
":",
"Any",
"=",
"install",
"(",
"Distribution",
"(",... | [
94,
0
] | [
110,
5
] | python | en | ['en', 'en', 'en'] | True |
_looks_like_msys2_mingw_scheme | () | MSYS2 patches distutils and sysconfig to use a UNIX-like scheme.
However, MSYS2 incorrectly patches sysconfig ``nt`` scheme. The fix is
likely going to be included in their 3.10 release, so we ignore the warning.
See msys2/MINGW-packages#9319.
MSYS2 MINGW's patch uses lowercase ``"lib"`` instead of th... | MSYS2 patches distutils and sysconfig to use a UNIX-like scheme. | def _looks_like_msys2_mingw_scheme() -> bool:
"""MSYS2 patches distutils and sysconfig to use a UNIX-like scheme.
However, MSYS2 incorrectly patches sysconfig ``nt`` scheme. The fix is
likely going to be included in their 3.10 release, so we ignore the warning.
See msys2/MINGW-packages#9319.
MSYS2... | [
"def",
"_looks_like_msys2_mingw_scheme",
"(",
")",
"->",
"bool",
":",
"paths",
"=",
"sysconfig",
".",
"get_paths",
"(",
"\"nt\"",
",",
"expand",
"=",
"False",
")",
"return",
"all",
"(",
"\"Lib\"",
"not",
"in",
"p",
"and",
"\"lib\"",
"in",
"p",
"and",
"no... | [
114,
0
] | [
128,
5
] | python | en | ['en', 'en', 'en'] | True |
_looks_like_deb_system_dist_packages | (value: str) | Check if the value is Debian's APT-controlled dist-packages.
Debian's ``distutils.sysconfig.get_python_lib()`` implementation returns the
default package path controlled by APT, but does not patch ``sysconfig`` to
do the same. This is similar to the bug worked around in ``get_scheme()``,
but here the d... | Check if the value is Debian's APT-controlled dist-packages. | def _looks_like_deb_system_dist_packages(value: str) -> bool:
"""Check if the value is Debian's APT-controlled dist-packages.
Debian's ``distutils.sysconfig.get_python_lib()`` implementation returns the
default package path controlled by APT, but does not patch ``sysconfig`` to
do the same. This is sim... | [
"def",
"_looks_like_deb_system_dist_packages",
"(",
"value",
":",
"str",
")",
"->",
"bool",
":",
"if",
"not",
"_looks_like_debian_scheme",
"(",
")",
":",
"return",
"False",
"if",
"value",
"==",
"\"/usr/lib/python3/dist-packages\"",
":",
"return",
"True",
"return",
... | [
346,
0
] | [
360,
16
] | python | en | ['en', 'en', 'en'] | True |
get_purelib | () | Return the default pure-Python lib location. | Return the default pure-Python lib location. | def get_purelib() -> str:
"""Return the default pure-Python lib location."""
old = _distutils.get_purelib()
new = _sysconfig.get_purelib()
if _looks_like_deb_system_dist_packages(old):
return old
if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="purelib"):
_log_context(... | [
"def",
"get_purelib",
"(",
")",
"->",
"str",
":",
"old",
"=",
"_distutils",
".",
"get_purelib",
"(",
")",
"new",
"=",
"_sysconfig",
".",
"get_purelib",
"(",
")",
"if",
"_looks_like_deb_system_dist_packages",
"(",
"old",
")",
":",
"return",
"old",
"if",
"_w... | [
363,
0
] | [
371,
14
] | python | en | ['en', 'hmn', 'en'] | True |
get_platlib | () | Return the default platform-shared lib location. | Return the default platform-shared lib location. | def get_platlib() -> str:
"""Return the default platform-shared lib location."""
old = _distutils.get_platlib()
new = _sysconfig.get_platlib()
if _looks_like_deb_system_dist_packages(old):
return old
if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="platlib"):
_log_cont... | [
"def",
"get_platlib",
"(",
")",
"->",
"str",
":",
"old",
"=",
"_distutils",
".",
"get_platlib",
"(",
")",
"new",
"=",
"_sysconfig",
".",
"get_platlib",
"(",
")",
"if",
"_looks_like_deb_system_dist_packages",
"(",
"old",
")",
":",
"return",
"old",
"if",
"_w... | [
374,
0
] | [
382,
14
] | python | en | ['en', 'sv', 'en'] | True |
get_prefixed_libs | (prefix: str) | Return the lib locations under ``prefix``. | Return the lib locations under ``prefix``. | def get_prefixed_libs(prefix: str) -> List[str]:
"""Return the lib locations under ``prefix``."""
old_pure, old_plat = _distutils.get_prefixed_libs(prefix)
new_pure, new_plat = _sysconfig.get_prefixed_libs(prefix)
warned = [
_warn_if_mismatch(
pathlib.Path(old_pure),
pat... | [
"def",
"get_prefixed_libs",
"(",
"prefix",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"old_pure",
",",
"old_plat",
"=",
"_distutils",
".",
"get_prefixed_libs",
"(",
"prefix",
")",
"new_pure",
",",
"new_plat",
"=",
"_sysconfig",
".",
"get_prefixed_l... | [
385,
0
] | [
407,
31
] | python | en | ['en', 'mt', 'en'] | True |
_bit_list_to_bytes | (bit_list) | Converts an iterable of 1's and 0's to bytes.
Combines the list 8 at a time, treating each group of 8 bits
as a single byte.
| Converts an iterable of 1's and 0's to bytes. | def _bit_list_to_bytes(bit_list):
"""Converts an iterable of 1's and 0's to bytes.
Combines the list 8 at a time, treating each group of 8 bits
as a single byte.
"""
num_bits = len(bit_list)
byte_vals = bytearray()
for start in six.moves.xrange(0, num_bits, 8):
curr_bits = bit_list[... | [
"def",
"_bit_list_to_bytes",
"(",
"bit_list",
")",
":",
"num_bits",
"=",
"len",
"(",
"bit_list",
")",
"byte_vals",
"=",
"bytearray",
"(",
")",
"for",
"start",
"in",
"six",
".",
"moves",
".",
"xrange",
"(",
"0",
",",
"num_bits",
",",
"8",
")",
":",
"c... | [
48,
0
] | [
61,
27
] | python | en | ['en', 'en', 'en'] | True |
RsaVerifier.verify | (self, message, signature) | Verifies a message against a signature.
Args:
message: string or bytes, The message to verify. If string, will be
encoded to bytes as utf-8.
signature: string or bytes, The signature on the message. If
string, will be encoded to bytes as utf-8... | Verifies a message against a signature. | def verify(self, message, signature):
"""Verifies a message against a signature.
Args:
message: string or bytes, The message to verify. If string, will be
encoded to bytes as utf-8.
signature: string or bytes, The signature on the message. If
... | [
"def",
"verify",
"(",
"self",
",",
"message",
",",
"signature",
")",
":",
"message",
"=",
"_helpers",
".",
"_to_bytes",
"(",
"message",
",",
"encoding",
"=",
"'utf-8'",
")",
"try",
":",
"return",
"rsa",
".",
"pkcs1",
".",
"verify",
"(",
"message",
",",... | [
74,
4
] | [
91,
24
] | python | en | ['en', 'fr', 'en'] | True |
RsaVerifier.from_string | (cls, key_pem, is_x509_cert) | Construct an RsaVerifier instance from a string.
Args:
key_pem: string, public key in PEM format.
is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it
is expected to be an RSA key in PEM format.
Returns:
RsaVerifier instance.
... | Construct an RsaVerifier instance from a string. | def from_string(cls, key_pem, is_x509_cert):
"""Construct an RsaVerifier instance from a string.
Args:
key_pem: string, public key in PEM format.
is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it
is expected to be an RSA key in PEM forma... | [
"def",
"from_string",
"(",
"cls",
",",
"key_pem",
",",
"is_x509_cert",
")",
":",
"key_pem",
"=",
"_helpers",
".",
"_to_bytes",
"(",
"key_pem",
")",
"if",
"is_x509_cert",
":",
"der",
"=",
"rsa",
".",
"pem",
".",
"load_pem",
"(",
"key_pem",
",",
"'CERTIFIC... | [
94,
4
] | [
124,
26
] | python | en | ['en', 'lb', 'en'] | True |
RsaSigner.sign | (self, message) | Signs a message.
Args:
message: bytes, Message to be signed.
Returns:
string, The signature of the message for the given key.
| Signs a message. | def sign(self, message):
"""Signs a message.
Args:
message: bytes, Message to be signed.
Returns:
string, The signature of the message for the given key.
"""
message = _helpers._to_bytes(message, encoding='utf-8')
return rsa.pkcs1.sign(message, s... | [
"def",
"sign",
"(",
"self",
",",
"message",
")",
":",
"message",
"=",
"_helpers",
".",
"_to_bytes",
"(",
"message",
",",
"encoding",
"=",
"'utf-8'",
")",
"return",
"rsa",
".",
"pkcs1",
".",
"sign",
"(",
"message",
",",
"self",
".",
"_key",
",",
"'SHA... | [
137,
4
] | [
147,
60
] | python | en | ['en', 'en', 'en'] | True |
RsaSigner.from_string | (cls, key, password='notasecret') | Construct an RsaSigner instance from a string.
Args:
key: string, private key in PEM format.
password: string, password for private key file. Unused for PEM
files.
Returns:
RsaSigner instance.
Raises:
ValueError if the key ... | Construct an RsaSigner instance from a string. | def from_string(cls, key, password='notasecret'):
"""Construct an RsaSigner instance from a string.
Args:
key: string, private key in PEM format.
password: string, password for private key file. Unused for PEM
files.
Returns:
RsaSigner ... | [
"def",
"from_string",
"(",
"cls",
",",
"key",
",",
"password",
"=",
"'notasecret'",
")",
":",
"key",
"=",
"_helpers",
".",
"_from_bytes",
"(",
"key",
")",
"# pem expects str in Py3",
"marker_id",
",",
"key_bytes",
"=",
"pem",
".",
"readPemBlocksFromFile",
"(",... | [
150,
4
] | [
183,
24
] | python | en | ['en', 'en', 'en'] | True |
setup_firebase | () |
Instancia objeto de acesso do BD Firebase.
:return: o objeto do BD Firebase instanciado.
|
Instancia objeto de acesso do BD Firebase. | def setup_firebase():
"""
Instancia objeto de acesso do BD Firebase.
:return: o objeto do BD Firebase instanciado.
"""
config = {
"apiKey": environment_vars.FIREBASE_API_KEY,
"authDomain": environment_vars.FIREBASE_PROJECT_ID,
"databaseURL": environment_vars.FIREBASE_DB_URL,... | [
"def",
"setup_firebase",
"(",
")",
":",
"config",
"=",
"{",
"\"apiKey\"",
":",
"environment_vars",
".",
"FIREBASE_API_KEY",
",",
"\"authDomain\"",
":",
"environment_vars",
".",
"FIREBASE_PROJECT_ID",
",",
"\"databaseURL\"",
":",
"environment_vars",
".",
"FIREBASE_DB_U... | [
10,
0
] | [
38,
13
] | python | en | ['en', 'error', 'th'] | False |
sms_ahoy_reply | () | Respond to incoming messages with a friendly SMS. | Respond to incoming messages with a friendly SMS. | def sms_ahoy_reply():
"""Respond to incoming messages with a friendly SMS."""
# Start our response
resp = MessagingResponse()
# Add a message
resp.message("Ahoy! Thanks so much for your message.")
return str(resp) | [
"def",
"sms_ahoy_reply",
"(",
")",
":",
"# Start our response",
"resp",
"=",
"MessagingResponse",
"(",
")",
"# Add a message",
"resp",
".",
"message",
"(",
"\"Ahoy! Thanks so much for your message.\"",
")",
"return",
"str",
"(",
"resp",
")"
] | [
8,
0
] | [
16,
20
] | python | en | ['en', 'en', 'en'] | True |
file_move_safe | (old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False) |
Move a file from one location to another in the safest way possible.
First, try ``os.rename``, which is simple but will break across filesystems.
If that fails, stream manually from one file to another in pure Python.
If the destination file exists and ``allow_overwrite`` is ``False``, raise
``Fi... |
Move a file from one location to another in the safest way possible. | def file_move_safe(old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False):
"""
Move a file from one location to another in the safest way possible.
First, try ``os.rename``, which is simple but will break across filesystems.
If that fails, stream manually from one file to another in... | [
"def",
"file_move_safe",
"(",
"old_file_name",
",",
"new_file_name",
",",
"chunk_size",
"=",
"1024",
"*",
"64",
",",
"allow_overwrite",
"=",
"False",
")",
":",
"# There's no reason to move if we don't have to.",
"if",
"_samefile",
"(",
"old_file_name",
",",
"new_file_... | [
29,
0
] | [
86,
17
] | python | en | ['en', 'error', 'th'] | False |
geos_version | () | Return the string version of the GEOS library. | Return the string version of the GEOS library. | def geos_version():
"""Return the string version of the GEOS library."""
return lgeos.GEOSversion() | [
"def",
"geos_version",
"(",
")",
":",
"return",
"lgeos",
".",
"GEOSversion",
"(",
")"
] | [
164,
0
] | [
166,
30
] | python | en | ['en', 'en', 'en'] | True |
geos_version_tuple | () | Return the GEOS version as a tuple (major, minor, subminor). | Return the GEOS version as a tuple (major, minor, subminor). | def geos_version_tuple():
"""Return the GEOS version as a tuple (major, minor, subminor)."""
return get_version_tuple(geos_version().decode()) | [
"def",
"geos_version_tuple",
"(",
")",
":",
"return",
"get_version_tuple",
"(",
"geos_version",
"(",
")",
".",
"decode",
"(",
")",
")"
] | [
169,
0
] | [
171,
53
] | python | en | ['en', 'lt', 'en'] | True |
run | (argv=None) | Build and run the pipeline. | Build and run the pipeline. | def run(argv=None):
"""Build and run the pipeline."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--project',
help=('Google Cloud Project ID'),
required=True)
parser.add_argument(
'--input_topic',
help=('Google Cloud PubSub topic name '),
required=True)
k... | [
"def",
"run",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--project'",
",",
"help",
"=",
"(",
"'Google Cloud Project ID'",
")",
",",
"required",
"=",
"True",
")",
"... | [
32,
0
] | [
71,
18
] | python | en | ['en', 'en', 'en'] | True |
get_app_template_dirs | (dirname) |
Return an iterable of paths of directories to load app templates from.
dirname is the name of the subdirectory containing templates inside
installed applications.
|
Return an iterable of paths of directories to load app templates from. | def get_app_template_dirs(dirname):
"""
Return an iterable of paths of directories to load app templates from.
dirname is the name of the subdirectory containing templates inside
installed applications.
"""
template_dirs = [
Path(app_config.path) / dirname
for app_config in apps... | [
"def",
"get_app_template_dirs",
"(",
"dirname",
")",
":",
"template_dirs",
"=",
"[",
"Path",
"(",
"app_config",
".",
"path",
")",
"/",
"dirname",
"for",
"app_config",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
"if",
"app_config",
".",
"path",
"and",
"... | [
93,
0
] | [
106,
31
] | python | en | ['en', 'error', 'th'] | False |
EngineHandler.__init__ | (self, templates=None) |
templates is an optional list of template engine definitions
(structured like settings.TEMPLATES).
|
templates is an optional list of template engine definitions
(structured like settings.TEMPLATES).
| def __init__(self, templates=None):
"""
templates is an optional list of template engine definitions
(structured like settings.TEMPLATES).
"""
self._templates = templates
self._engines = {} | [
"def",
"__init__",
"(",
"self",
",",
"templates",
"=",
"None",
")",
":",
"self",
".",
"_templates",
"=",
"templates",
"self",
".",
"_engines",
"=",
"{",
"}"
] | [
16,
4
] | [
22,
26
] | python | en | ['en', 'error', 'th'] | False |
conditional_content_removal | (request, response) |
Simulate the behavior of most Web servers by removing the content of
responses for HEAD requests, 1xx, 204, and 304 responses. Ensure
compliance with RFC 7230, section 3.3.3.
|
Simulate the behavior of most Web servers by removing the content of
responses for HEAD requests, 1xx, 204, and 304 responses. Ensure
compliance with RFC 7230, section 3.3.3.
| def conditional_content_removal(request, response):
"""
Simulate the behavior of most Web servers by removing the content of
responses for HEAD requests, 1xx, 204, and 304 responses. Ensure
compliance with RFC 7230, section 3.3.3.
"""
if 100 <= response.status_code < 200 or response.status_code ... | [
"def",
"conditional_content_removal",
"(",
"request",
",",
"response",
")",
":",
"if",
"100",
"<=",
"response",
".",
"status_code",
"<",
"200",
"or",
"response",
".",
"status_code",
"in",
"(",
"204",
",",
"304",
")",
":",
"if",
"response",
".",
"streaming"... | [
98,
0
] | [
114,
19
] | python | en | ['en', 'error', 'th'] | False |
store_rendered_templates | (store, signal, sender, template, context, **kwargs) |
Store templates and contexts that are rendered.
The context is copied so that it is an accurate representation at the time
of rendering.
|
Store templates and contexts that are rendered. | def store_rendered_templates(store, signal, sender, template, context, **kwargs):
"""
Store templates and contexts that are rendered.
The context is copied so that it is an accurate representation at the time
of rendering.
"""
store.setdefault('templates', []).append(template)
if 'context' ... | [
"def",
"store_rendered_templates",
"(",
"store",
",",
"signal",
",",
"sender",
",",
"template",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"store",
".",
"setdefault",
"(",
"'templates'",
",",
"[",
"]",
")",
".",
"append",
"(",
"template",
")",
... | [
211,
0
] | [
221,
42
] | python | en | ['en', 'error', 'th'] | False |
encode_multipart | (boundary, data) |
Encode multipart POST data from a dictionary of form values.
The key will be used as the form data name; the value will be transmitted
as content. If the value is a file, the contents of the file will be sent
as an application/octet-stream; otherwise, str(value) will be sent.
|
Encode multipart POST data from a dictionary of form values. | def encode_multipart(boundary, data):
"""
Encode multipart POST data from a dictionary of form values.
The key will be used as the form data name; the value will be transmitted
as content. If the value is a file, the contents of the file will be sent
as an application/octet-stream; otherwise, str(v... | [
"def",
"encode_multipart",
"(",
"boundary",
",",
"data",
")",
":",
"lines",
"=",
"[",
"]",
"def",
"to_bytes",
"(",
"s",
")",
":",
"return",
"force_bytes",
"(",
"s",
",",
"settings",
".",
"DEFAULT_CHARSET",
")",
"# Not by any means perfect, but good enough for ou... | [
224,
0
] | [
275,
30
] | python | en | ['en', 'error', 'th'] | False |
RequestFactory._base_environ | (self, **request) |
The base environment for a request.
|
The base environment for a request.
| def _base_environ(self, **request):
"""
The base environment for a request.
"""
# This is a minimal valid WSGI environ dictionary, plus:
# - HTTP_COOKIE: for cookie support,
# - REMOTE_ADDR: often useful, see #8551.
# See https://www.python.org/dev/peps/pep-3333/#... | [
"def",
"_base_environ",
"(",
"self",
",",
"*",
"*",
"request",
")",
":",
"# This is a minimal valid WSGI environ dictionary, plus:",
"# - HTTP_COOKIE: for cookie support,",
"# - REMOTE_ADDR: often useful, see #8551.",
"# See https://www.python.org/dev/peps/pep-3333/#environ-variables",
"... | [
326,
4
] | [
355,
9
] | python | en | ['en', 'error', 'th'] | False |
RequestFactory.request | (self, **request) | Construct a generic request object. | Construct a generic request object. | def request(self, **request):
"Construct a generic request object."
return WSGIRequest(self._base_environ(**request)) | [
"def",
"request",
"(",
"self",
",",
"*",
"*",
"request",
")",
":",
"return",
"WSGIRequest",
"(",
"self",
".",
"_base_environ",
"(",
"*",
"*",
"request",
")",
")"
] | [
357,
4
] | [
359,
57
] | python | en | ['en', 'en', 'en'] | True |
RequestFactory._encode_json | (self, data, content_type) |
Return encoded JSON if data is a dict, list, or tuple and content_type
is application/json.
|
Return encoded JSON if data is a dict, list, or tuple and content_type
is application/json.
| def _encode_json(self, data, content_type):
"""
Return encoded JSON if data is a dict, list, or tuple and content_type
is application/json.
"""
should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance(data, (dict, list, tuple))
return json.dumps(data, cls=s... | [
"def",
"_encode_json",
"(",
"self",
",",
"data",
",",
"content_type",
")",
":",
"should_encode",
"=",
"JSON_CONTENT_TYPE_RE",
".",
"match",
"(",
"content_type",
")",
"and",
"isinstance",
"(",
"data",
",",
"(",
"dict",
",",
"list",
",",
"tuple",
")",
")",
... | [
373,
4
] | [
379,
81
] | python | en | ['en', 'error', 'th'] | False |
RequestFactory.get | (self, path, data=None, secure=False, **extra) | Construct a GET request. | Construct a GET request. | def get(self, path, data=None, secure=False, **extra):
"""Construct a GET request."""
data = {} if data is None else data
return self.generic('GET', path, secure=secure, **{
'QUERY_STRING': urlencode(data, doseq=True),
**extra,
}) | [
"def",
"get",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"data",
"=",
"{",
"}",
"if",
"data",
"is",
"None",
"else",
"data",
"return",
"self",
".",
"generic",
"(",
"'GET'",
... | [
392,
4
] | [
398,
10
] | python | en | ['en', 'en', 'en'] | True |
RequestFactory.post | (self, path, data=None, content_type=MULTIPART_CONTENT,
secure=False, **extra) | Construct a POST request. | Construct a POST request. | def post(self, path, data=None, content_type=MULTIPART_CONTENT,
secure=False, **extra):
"""Construct a POST request."""
data = self._encode_json({} if data is None else data, content_type)
post_data = self._encode_data(data, content_type)
return self.generic('POST', path, p... | [
"def",
"post",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"content_type",
"=",
"MULTIPART_CONTENT",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"data",
"=",
"self",
".",
"_encode_json",
"(",
"{",
"}",
"if",
"data",
... | [
400,
4
] | [
407,
51
] | python | en | ['en', 'en', 'en'] | True |
RequestFactory.head | (self, path, data=None, secure=False, **extra) | Construct a HEAD request. | Construct a HEAD request. | def head(self, path, data=None, secure=False, **extra):
"""Construct a HEAD request."""
data = {} if data is None else data
return self.generic('HEAD', path, secure=secure, **{
'QUERY_STRING': urlencode(data, doseq=True),
**extra,
}) | [
"def",
"head",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"data",
"=",
"{",
"}",
"if",
"data",
"is",
"None",
"else",
"data",
"return",
"self",
".",
"generic",
"(",
"'HEAD'",
... | [
409,
4
] | [
415,
10
] | python | en | ['en', 'en', 'en'] | True |
RequestFactory.trace | (self, path, secure=False, **extra) | Construct a TRACE request. | Construct a TRACE request. | def trace(self, path, secure=False, **extra):
"""Construct a TRACE request."""
return self.generic('TRACE', path, secure=secure, **extra) | [
"def",
"trace",
"(",
"self",
",",
"path",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"return",
"self",
".",
"generic",
"(",
"'TRACE'",
",",
"path",
",",
"secure",
"=",
"secure",
",",
"*",
"*",
"extra",
")"
] | [
417,
4
] | [
419,
66
] | python | en | ['en', 'en', 'en'] | True |
RequestFactory.options | (self, path, data='', content_type='application/octet-stream',
secure=False, **extra) | Construct an OPTIONS request. | Construct an OPTIONS request. | def options(self, path, data='', content_type='application/octet-stream',
secure=False, **extra):
"Construct an OPTIONS request."
return self.generic('OPTIONS', path, data, content_type,
secure=secure, **extra) | [
"def",
"options",
"(",
"self",
",",
"path",
",",
"data",
"=",
"''",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"return",
"self",
".",
"generic",
"(",
"'OPTIONS'",
",",
"path",
... | [
421,
4
] | [
425,
51
] | python | en | ['en', 'en', 'en'] | True |
RequestFactory.put | (self, path, data='', content_type='application/octet-stream',
secure=False, **extra) | Construct a PUT request. | Construct a PUT request. | def put(self, path, data='', content_type='application/octet-stream',
secure=False, **extra):
"""Construct a PUT request."""
data = self._encode_json(data, content_type)
return self.generic('PUT', path, data, content_type,
secure=secure, **extra) | [
"def",
"put",
"(",
"self",
",",
"path",
",",
"data",
"=",
"''",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"data",
"=",
"self",
".",
"_encode_json",
"(",
"data",
",",
"content_... | [
427,
4
] | [
432,
51
] | python | en | ['en', 'en', 'en'] | True |
RequestFactory.patch | (self, path, data='', content_type='application/octet-stream',
secure=False, **extra) | Construct a PATCH request. | Construct a PATCH request. | def patch(self, path, data='', content_type='application/octet-stream',
secure=False, **extra):
"""Construct a PATCH request."""
data = self._encode_json(data, content_type)
return self.generic('PATCH', path, data, content_type,
secure=secure, **extra) | [
"def",
"patch",
"(",
"self",
",",
"path",
",",
"data",
"=",
"''",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"data",
"=",
"self",
".",
"_encode_json",
"(",
"data",
",",
"conten... | [
434,
4
] | [
439,
51
] | python | en | ['en', 'en', 'en'] | True |
RequestFactory.delete | (self, path, data='', content_type='application/octet-stream',
secure=False, **extra) | Construct a DELETE request. | Construct a DELETE request. | def delete(self, path, data='', content_type='application/octet-stream',
secure=False, **extra):
"""Construct a DELETE request."""
data = self._encode_json(data, content_type)
return self.generic('DELETE', path, data, content_type,
secure=secure, **extr... | [
"def",
"delete",
"(",
"self",
",",
"path",
",",
"data",
"=",
"''",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"data",
"=",
"self",
".",
"_encode_json",
"(",
"data",
",",
"conte... | [
441,
4
] | [
446,
51
] | python | en | ['en', 'it', 'en'] | True |
RequestFactory.generic | (self, method, path, data='',
content_type='application/octet-stream', secure=False,
**extra) | Construct an arbitrary HTTP request. | Construct an arbitrary HTTP request. | def generic(self, method, path, data='',
content_type='application/octet-stream', secure=False,
**extra):
"""Construct an arbitrary HTTP request."""
parsed = urlparse(str(path)) # path can be lazy
data = force_bytes(data, settings.DEFAULT_CHARSET)
r = {
... | [
"def",
"generic",
"(",
"self",
",",
"method",
",",
"path",
",",
"data",
"=",
"''",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"str",
"(",
"path"... | [
448,
4
] | [
472,
32
] | python | en | ['en', 'en', 'en'] | True |
AsyncRequestFactory._base_scope | (self, **request) | The base scope for a request. | The base scope for a request. | def _base_scope(self, **request):
"""The base scope for a request."""
# This is a minimal valid ASGI scope, plus:
# - headers['cookie'] for cookie support,
# - 'client' often useful, see #8551.
scope = {
'asgi': {'version': '3.0'},
'type': 'http',
... | [
"def",
"_base_scope",
"(",
"self",
",",
"*",
"*",
"request",
")",
":",
"# This is a minimal valid ASGI scope, plus:",
"# - headers['cookie'] for cookie support,",
"# - 'client' often useful, see #8551.",
"scope",
"=",
"{",
"'asgi'",
":",
"{",
"'version'",
":",
"'3.0'",
"}... | [
489,
4
] | [
513,
20
] | python | en | ['en', 'en', 'en'] | True |
AsyncRequestFactory.request | (self, **request) | Construct a generic request object. | Construct a generic request object. | def request(self, **request):
"""Construct a generic request object."""
# This is synchronous, which means all methods on this class are.
# AsyncClient, however, has an async request function, which makes all
# its methods async.
if '_body_file' in request:
body_file ... | [
"def",
"request",
"(",
"self",
",",
"*",
"*",
"request",
")",
":",
"# This is synchronous, which means all methods on this class are.",
"# AsyncClient, however, has an async request function, which makes all",
"# its methods async.",
"if",
"'_body_file'",
"in",
"request",
":",
"b... | [
515,
4
] | [
524,
66
] | python | en | ['en', 'en', 'en'] | True |
AsyncRequestFactory.generic | (
self, method, path, data='', content_type='application/octet-stream',
secure=False, **extra,
) | Construct an arbitrary HTTP request. | Construct an arbitrary HTTP request. | def generic(
self, method, path, data='', content_type='application/octet-stream',
secure=False, **extra,
):
"""Construct an arbitrary HTTP request."""
parsed = urlparse(str(path)) # path can be lazy.
data = force_bytes(data, settings.DEFAULT_CHARSET)
s = {
... | [
"def",
"generic",
"(",
"self",
",",
"method",
",",
"path",
",",
"data",
"=",
"''",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
",",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"str",
"(",
... | [
526,
4
] | [
557,
32
] | python | en | ['en', 'en', 'en'] | True |
ClientMixin.store_exc_info | (self, **kwargs) | Store exceptions when they are generated by a view. | Store exceptions when they are generated by a view. | def store_exc_info(self, **kwargs):
"""Store exceptions when they are generated by a view."""
self.exc_info = sys.exc_info() | [
"def",
"store_exc_info",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")"
] | [
564,
4
] | [
566,
38
] | python | en | ['en', 'en', 'en'] | True |
ClientMixin.check_exception | (self, response) |
Look for a signaled exception, clear the current context exception
data, re-raise the signaled exception, and clear the signaled exception
from the local cache.
|
Look for a signaled exception, clear the current context exception
data, re-raise the signaled exception, and clear the signaled exception
from the local cache.
| def check_exception(self, response):
"""
Look for a signaled exception, clear the current context exception
data, re-raise the signaled exception, and clear the signaled exception
from the local cache.
"""
response.exc_info = self.exc_info
if self.exc_info:
... | [
"def",
"check_exception",
"(",
"self",
",",
"response",
")",
":",
"response",
".",
"exc_info",
"=",
"self",
".",
"exc_info",
"if",
"self",
".",
"exc_info",
":",
"_",
",",
"exc_value",
",",
"_",
"=",
"self",
".",
"exc_info",
"self",
".",
"exc_info",
"="... | [
568,
4
] | [
579,
31
] | python | en | ['en', 'error', 'th'] | False |
ClientMixin.session | (self) | Return the current session variables. | Return the current session variables. | def session(self):
"""Return the current session variables."""
engine = import_module(settings.SESSION_ENGINE)
cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
if cookie:
return engine.SessionStore(cookie.value)
session = engine.SessionStore()
session.s... | [
"def",
"session",
"(",
"self",
")",
":",
"engine",
"=",
"import_module",
"(",
"settings",
".",
"SESSION_ENGINE",
")",
"cookie",
"=",
"self",
".",
"cookies",
".",
"get",
"(",
"settings",
".",
"SESSION_COOKIE_NAME",
")",
"if",
"cookie",
":",
"return",
"engin... | [
582,
4
] | [
591,
22
] | python | en | ['en', 'en', 'en'] | True |
ClientMixin.login | (self, **credentials) |
Set the Factory to appear as if it has successfully logged into a site.
Return True if login is possible or False if the provided credentials
are incorrect.
|
Set the Factory to appear as if it has successfully logged into a site. | def login(self, **credentials):
"""
Set the Factory to appear as if it has successfully logged into a site.
Return True if login is possible or False if the provided credentials
are incorrect.
"""
from django.contrib.auth import authenticate
user = authenticate(*... | [
"def",
"login",
"(",
"self",
",",
"*",
"*",
"credentials",
")",
":",
"from",
"django",
".",
"contrib",
".",
"auth",
"import",
"authenticate",
"user",
"=",
"authenticate",
"(",
"*",
"*",
"credentials",
")",
"if",
"user",
":",
"self",
".",
"_login",
"(",... | [
593,
4
] | [
605,
20
] | python | en | ['en', 'error', 'th'] | False |
ClientMixin.logout | (self) | Log out the user by removing the cookies and session object. | Log out the user by removing the cookies and session object. | def logout(self):
"""Log out the user by removing the cookies and session object."""
from django.contrib.auth import get_user, logout
request = HttpRequest()
if self.session:
request.session = self.session
request.user = get_user(request)
else:
... | [
"def",
"logout",
"(",
"self",
")",
":",
"from",
"django",
".",
"contrib",
".",
"auth",
"import",
"get_user",
",",
"logout",
"request",
"=",
"HttpRequest",
"(",
")",
"if",
"self",
".",
"session",
":",
"request",
".",
"session",
"=",
"self",
".",
"sessio... | [
645,
4
] | [
656,
37
] | python | en | ['en', 'en', 'en'] | True |
Client.request | (self, **request) |
The master request method. Compose the environment dictionary and pass
to the handler, return the result of the handler. Assume defaults for
the query environment, which can be overridden using the arguments to
the request.
|
The master request method. Compose the environment dictionary and pass
to the handler, return the result of the handler. Assume defaults for
the query environment, which can be overridden using the arguments to
the request.
| def request(self, **request):
"""
The master request method. Compose the environment dictionary and pass
to the handler, return the result of the handler. Assume defaults for
the query environment, which can be overridden using the arguments to
the request.
"""
en... | [
"def",
"request",
"(",
"self",
",",
"*",
"*",
"request",
")",
":",
"environ",
"=",
"self",
".",
"_base_environ",
"(",
"*",
"*",
"request",
")",
"# Curry a data dictionary into an instance of the template renderer",
"# callback function.",
"data",
"=",
"{",
"}",
"o... | [
694,
4
] | [
736,
23
] | python | en | ['en', 'error', 'th'] | False |
Client.get | (self, path, data=None, follow=False, secure=False, **extra) | Request a response from the server using GET. | Request a response from the server using GET. | def get(self, path, data=None, follow=False, secure=False, **extra):
"""Request a response from the server using GET."""
self.extra = extra
response = super().get(path, data=data, secure=secure, **extra)
if follow:
response = self._handle_redirects(response, data=data, **extr... | [
"def",
"get",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"follow",
"=",
"False",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"self",
".",
"extra",
"=",
"extra",
"response",
"=",
"super",
"(",
")",
".",
"get",
"(... | [
738,
4
] | [
744,
23
] | python | en | ['en', 'en', 'en'] | True |
Client.post | (self, path, data=None, content_type=MULTIPART_CONTENT,
follow=False, secure=False, **extra) | Request a response from the server using POST. | Request a response from the server using POST. | def post(self, path, data=None, content_type=MULTIPART_CONTENT,
follow=False, secure=False, **extra):
"""Request a response from the server using POST."""
self.extra = extra
response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
if follow... | [
"def",
"post",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"content_type",
"=",
"MULTIPART_CONTENT",
",",
"follow",
"=",
"False",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"self",
".",
"extra",
"=",
"extra",
"respons... | [
746,
4
] | [
753,
23
] | 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.