project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
zihuitang/medical_AI_platform | pydoc.py | HTMLDoc.docclass | docclass | Produce HTML documentation for a class object. | [
"Produce",
"HTML",
"documentation",
"for",
"a",
"class",
"object."
] | def docclass(self, object, name=None, mod=None, funcs={}, classes={}, *ignored):
realname = object.__name__
name = name or realname
bases = object.__bases__
contents = []
push = contents.append
class HorizontalRule:
def __init__(self):
self.needone = 0
def maybe(se... | ['def', 'docclass(self,', 'object,', 'name=None,', 'mod=None,', 'funcs={},', 'classes={},', '*ignored):', 'realname', '=', 'object.__name__', 'name', '=', 'name', 'or', 'realname', 'bases', '=', 'object.__bases__', 'contents', '=', '[]', 'push', '=', 'contents.append', 'class', 'HorizontalRule:', 'def', '__init__(self)... | 281,227 |
facebookresearch/minihack | wiki.py | load_json | load_json | Load a file containing a json object per line into a list of dicts. | [
"Load",
"a",
"file",
"containing",
"a",
"json",
"object",
"per",
"line",
"into",
"a",
"list",
"of",
"dicts."
] | def load_json(file_name: str) -> list:
with open(file_name, 'r') as json_file:
input_json = []
for line in json_file:
input_json.append(json.loads(line))
return input_json | ['def', 'load_json(file_name:', 'str)', '->', 'list:', 'with', 'open(file_name,', "'r')", 'as', 'json_file:', 'input_json', '=', '[]', 'for', 'line', 'in', 'json_file:', 'input_json.append(json.loads(line))', 'return', 'input_json'] | 670,735 |
irapha/replayed_distillation | yale.py | read_data_set | read_data_set | Loads the yale dataset as image lists, shuffles and separates into train/test sets. | [
"Loads",
"the",
"yale",
"dataset",
"as",
"image",
"lists,",
"shuffles",
"and",
"separates",
"into",
"train/test",
"sets."
] | def read_data_set(image_dir):
if not gfile.Exists(image_dir):
raise Exception("Image directory '" + image_dir + "' not found.")
base_classes = listdir(image_dir)
class_count = len(base_classes)
result = {'train': {'images': [], 'labels': []}, 'test': {'images': [], 'labels': []}}
total_image... | ['def', 'read_data_set(image_dir):', 'if', 'not', 'gfile.Exists(image_dir):', 'raise', 'Exception("Image', 'directory', '\'"', '+', 'image_dir', '+', '"\'', 'not', 'found.")', 'base_classes', '=', 'listdir(image_dir)', 'class_count', '=', 'len(base_classes)', 'result', '=', "{'train':", "{'images':", '[],', "'labels':"... | 840,246 |
rudranil723/mini-main | dates.py | MonthMixin.get_month_format | get_month_format | Get a month format string in strptime syntax to be used to parse the month from url variables. | [
"Get",
"a",
"month",
"format",
"string",
"in",
"strptime",
"syntax",
"to",
"be",
"used",
"to",
"parse",
"the",
"month",
"from",
"url",
"variables."
] | def get_month_format(self):
return self.month_format | ['def', 'get_month_format(self):', 'return', 'self.month_format'] | 316,877 |
microsoft/maro | utils.py | get_input_range | get_input_range | Get the tick input range in string format. | [
"Get",
"the",
"tick",
"input",
"range",
"in",
"string",
"format."
] | def get_input_range(start_tick: str, end_tick: str) -> str:
return '(' + ', '.join([f"'{i}'" for i in range(int(start_tick), int(end_tick))]) + ')' | ['def', 'get_input_range(start_tick:', 'str,', 'end_tick:', 'str)', '->', 'str:', 'return', "'('", '+', "',", '\'.join([f"\'{i}\'"', 'for', 'i', 'in', 'range(int(start_tick),', 'int(end_tick))])', '+', "')'"] | 628,321 |
RasaHQ/rasa | visualize.py | add_subparser | add_subparser | Add all visualization parsers. | [
"Add",
"all",
"visualization",
"parsers."
] | def add_subparser(subparsers: SubParsersAction, parents: List[argparse.ArgumentParser]) -> None:
visualize_parser = subparsers.add_parser('visualize', parents=parents, conflict_handler='resolve', formatter_class=argparse.ArgumentDefaultsHelpFormatter, help='Visualize stories.')
visualize_parser.set_defaults(fun... | ['def', 'add_subparser(subparsers:', 'SubParsersAction,', 'parents:', 'List[argparse.ArgumentParser])', '->', 'None:', 'visualize_parser', '=', "subparsers.add_parser('visualize',", 'parents=parents,', "conflict_handler='resolve',", 'formatter_class=argparse.ArgumentDefaultsHelpFormatter,', "help='Visualize", "stories.... | 836,637 |
sktime/sktime | test_hpfilter.py | test_HPFilter_wrapper | test_HPFilter_wrapper | Verify that the wrapped HPFilter estimator agrees with statsmodel. | [
"Verify",
"that",
"the",
"wrapped",
"HPFilter",
"estimator",
"agrees",
"with",
"statsmodel."
] | def test_HPFilter_wrapper():
import statsmodels.api as sm
from sktime.transformations.series.hpfilter import HPFilter as _HPFilter
dta = sm.datasets.macrodata.load_pandas().data
index = pd.date_range(start='1959Q1', end='2009Q4', freq='Q')
dta.set_index(index, inplace=True)
sm_cycle = sm.tsa.fil... | ['def', 'test_HPFilter_wrapper():', 'import', 'statsmodels.api', 'as', 'sm', 'from', 'sktime.transformations.series.hpfilter', 'import', 'HPFilter', 'as', '_HPFilter', 'dta', '=', 'sm.datasets.macrodata.load_pandas().data', 'index', '=', "pd.date_range(start='1959Q1',", "end='2009Q4',", "freq='Q')", 'dta.set_index(inde... | 877,966 |
cesium-ml/cesium | test_lomb_scargle_features.py | test_scatter_res_raw | test_scatter_res_raw | Test feature that measures scatter of Lomb-Scargle residuals. | [
"Test",
"feature",
"that",
"measures",
"scatter",
"of",
"Lomb-Scargle",
"residuals."
] | def test_scatter_res_raw():
(times, values, errors) = irregular_random()
lomb_model = lomb_scargle.lomb_scargle_model(times, values, errors)
residuals = values - lomb_model['freq_fits'][0]['model']
resid_mad = np.median(np.abs(residuals - np.median(residuals)))
value_mad = np.median(np.abs(values - ... | ['def', 'test_scatter_res_raw():', '(times,', 'values,', 'errors)', '=', 'irregular_random()', 'lomb_model', '=', 'lomb_scargle.lomb_scargle_model(times,', 'values,', 'errors)', 'residuals', '=', 'values', '-', "lomb_model['freq_fits'][0]['model']", 'resid_mad', '=', 'np.median(np.abs(residuals', '-', 'np.median(residu... | 476,680 |
flavioschneider/rl-transfer- | test_sac.py | test_sac_to | test_sac_to | Test moving Sac between CPU and GPU. | [
"Test",
"moving",
"Sac",
"between",
"CPU",
"and",
"GPU."
] | def test_sac_to():
env = normalize(GymEnv('InvertedDoublePendulum-v2', max_episode_length=100))
deterministic.set_seed(0)
policy = TanhGaussianMLPPolicy(env_spec=env.spec, hidden_sizes=[32, 32], hidden_nonlinearity=torch.nn.ReLU, output_nonlinearity=None, min_std=np.exp(-20.0), max_std=np.exp(2.0))
qf1 ... | ['def', 'test_sac_to():', 'env', '=', "normalize(GymEnv('InvertedDoublePendulum-v2',", 'max_episode_length=100))', 'deterministic.set_seed(0)', 'policy', '=', 'TanhGaussianMLPPolicy(env_spec=env.spec,', 'hidden_sizes=[32,', '32],', 'hidden_nonlinearity=torch.nn.ReLU,', 'output_nonlinearity=None,', 'min_std=np.exp(-20.0... | 861,819 |
Katja-M/Python_NaturalLanguageProcessing | tgrep.py | unique_ancestors | unique_ancestors | Returns the list of all nodes dominating the given node, where there is only a single path of descent. | [
"Returns",
"the",
"list",
"of",
"all",
"nodes",
"dominating",
"the",
"given",
"node,",
"where",
"there",
"is",
"only",
"a",
"single",
"path",
"of",
"descent."
] | def unique_ancestors(node):
results = []
try:
current = node.parent()
except AttributeError:
return results
while current and len(current) == 1:
results.append(current)
current = current.parent()
return results | ['def', 'unique_ancestors(node):', 'results', '=', '[]', 'try:', 'current', '=', 'node.parent()', 'except', 'AttributeError:', 'return', 'results', 'while', 'current', 'and', 'len(current)', '==', '1:', 'results.append(current)', 'current', '=', 'current.parent()', 'return', 'results'] | 865,895 |
gunthercox/ChatterBot | test_core.py | TestMaskedArrayMethods.test_clip | test_clip | Tests clip on MaskedArrays. | [
"Tests",
"clip",
"on",
"MaskedArrays."
] | def test_clip(self):
x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878, 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, 7.712, 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
m = np.array([0, 1, 0, 1, 0, 0... | ['def', 'test_clip(self):', 'x', '=', 'np.array([8.375,', '7.545,', '8.828,', '8.5,', '1.757,', '5.928,', '8.43,', '7.78,', '9.865,', '5.878,', '8.979,', '4.732,', '3.012,', '6.022,', '5.095,', '3.116,', '5.238,', '3.957,', '6.04,', '9.63,', '7.712,', '3.382,', '4.489,', '6.479,', '7.189,', '9.645,', '5.395,', '4.961,'... | 532,048 |
open-mmlab/mmtracking | siamrpn.py | SiamRPN.init_weights | init_weights | Initialize the weights of modules in single object tracker. | [
"Initialize",
"the",
"weights",
"of",
"modules",
"in",
"single",
"object",
"tracker."
] | def init_weights(self):
if self.with_backbone:
self.backbone.init_weights()
if self.with_neck:
for m in self.neck.modules():
if isinstance(m, _ConvNd) or isinstance(m, _BatchNorm):
m.reset_parameters()
if self.with_head:
for m in self.head.modules():
... | ['def', 'init_weights(self):', 'if', 'self.with_backbone:', 'self.backbone.init_weights()', 'if', 'self.with_neck:', 'for', 'm', 'in', 'self.neck.modules():', 'if', 'isinstance(m,', '_ConvNd)', 'or', 'isinstance(m,', '_BatchNorm):', 'm.reset_parameters()', 'if', 'self.with_head:', 'for', 'm', 'in', 'self.head.modules()... | 625,850 |
chainer/chainer | cumprod.py | cumprod | cumprod | Cumulative prod of array elements over a given axis. | [
"Cumulative",
"prod",
"of",
"array",
"elements",
"over",
"a",
"given",
"axis."
] | def cumprod(x, axis=None):
return Cumprod(axis).apply((x,))[0] | ['def', 'cumprod(x,', 'axis=None):', 'return', 'Cumprod(axis).apply((x,))[0]'] | 477,308 |
microsoft/maro | parsers.py | parse_global_order_proportion | parse_global_order_proportion | Parse specified configuration, and generate order proportion. | [
"Parse",
"specified",
"configuration,",
"and",
"generate",
"order",
"proportion."
] | def parse_global_order_proportion(conf: dict, total_container: int, max_tick: int, start_tick: int=0) -> np.ndarray:
durations: int = max_tick - start_tick
order_proportion = np.zeros(durations, dtype='i')
period: int = conf['period']
noise: Union[float, int] = conf['sample_noise']
sample_nodes: lis... | ['def', 'parse_global_order_proportion(conf:', 'dict,', 'total_container:', 'int,', 'max_tick:', 'int,', 'start_tick:', 'int=0)', '->', 'np.ndarray:', 'durations:', 'int', '=', 'max_tick', '-', 'start_tick', 'order_proportion', '=', 'np.zeros(durations,', "dtype='i')", 'period:', 'int', '=', "conf['period']", 'noise:',... | 628,436 |
google-research/tensor2robot | tensorspec_utils.py | filter_spec_structure_by_dataset | filter_spec_structure_by_dataset | Subset of flattened spec structure whose dataset matches dataset_key. | [
"Subset",
"of",
"flattened",
"spec",
"structure",
"whose",
"dataset",
"matches",
"dataset_key."
] | def filter_spec_structure_by_dataset(spec_structure, dataset_key, filter_none=True):
flattened_spec_structure = flatten_spec_structure(spec_structure, filter_none)
return TensorSpecStruct([key_value for key_value in flattened_spec_structure.items() if key_value[1].dataset_key == dataset_key or not dataset_key]) | ['def', 'filter_spec_structure_by_dataset(spec_structure,', 'dataset_key,', 'filter_none=True):', 'flattened_spec_structure', '=', 'flatten_spec_structure(spec_structure,', 'filter_none)', 'return', 'TensorSpecStruct([key_value', 'for', 'key_value', 'in', 'flattened_spec_structure.items()', 'if', 'key_value[1].dataset_... | 908,474 |
Kvatsx/Artificial-Intelligence-Assignments | _base.py | _AxesBase.get_xgridlines | get_xgridlines | Get the x grid lines as a list of `Line2D` instances. | [
"Get",
"the",
"x",
"grid",
"lines",
"as",
"a",
"list",
"of",
"`Line2D`",
"instances."
] | def get_xgridlines(self):
return cbook.silent_list('Line2D xgridline', self.xaxis.get_gridlines()) | ['def', 'get_xgridlines(self):', 'return', "cbook.silent_list('Line2D", "xgridline',", 'self.xaxis.get_gridlines())'] | 1,033 |
mariacer/cl_in_rnns | copy_data.py | CopyTask.get_identifier | get_identifier | Returns the name of the dataset. | [
"Returns",
"the",
"name",
"of",
"the",
"dataset."
] | def get_identifier(self):
return 'Copy' | ['def', 'get_identifier(self):', 'return', "'Copy'"] | 122,758 |
myothida/Supervised-Machine-Learning | test_ridge.py | test_lbfgs_solver_error | test_lbfgs_solver_error | Test that LBFGS solver raises ConvergenceWarning. | [
"Test",
"that",
"LBFGS",
"solver",
"raises",
"ConvergenceWarning."
] | def test_lbfgs_solver_error():
X = np.array([[1, -1], [1, 1]])
y = np.array([-10000000000.0, 10000000000.0])
model = Ridge(alpha=0.01, solver='lbfgs', fit_intercept=False, tol=1e-12, positive=True, max_iter=1)
with pytest.warns(ConvergenceWarning, match='lbfgs solver did not converge'):
model.fi... | ['def', 'test_lbfgs_solver_error():', 'X', '=', 'np.array([[1,', '-1],', '[1,', '1]])', 'y', '=', 'np.array([-10000000000.0,', '10000000000.0])', 'model', '=', 'Ridge(alpha=0.01,', "solver='lbfgs',", 'fit_intercept=False,', 'tol=1e-12,', 'positive=True,', 'max_iter=1)', 'with', 'pytest.warns(ConvergenceWarning,', "matc... | 364,171 |
eong2012/fritz-image-segmentation | data_generator.py | ADE20KGenerator.load_mask | load_mask | Load an image segmentation mask. | [
"Load",
"an",
"image",
"segmentation",
"mask."
] | def load_mask(self, mask_path):
return numpy.array(PIL.Image.open(mask_path).resize(self.image_size)).astype('float') | ['def', 'load_mask(self,', 'mask_path):', 'return', "numpy.array(PIL.Image.open(mask_path).resize(self.image_size)).astype('float')"] | 564,521 |
bradfitz/scanningcabinet | main.py | delete_doc_and_images | delete_doc_and_images | Deletes the document and its images. | [
"Deletes",
"the",
"document",
"and",
"its",
"images."
] | def delete_doc_and_images(user, doc):
scans = MediaObject.get(doc.pages)
for scan in scans:
blobstore.delete(scan.blob.key())
def tx():
db.delete(doc)
scans = MediaObject.get(doc.pages)
for scan in scans:
user.media_objects -= 1
db.delete(scan)
... | ['def', 'delete_doc_and_images(user,', 'doc):', 'scans', '=', 'MediaObject.get(doc.pages)', 'for', 'scan', 'in', 'scans:', 'blobstore.delete(scan.blob.key())', 'def', 'tx():', 'db.delete(doc)', 'scans', '=', 'MediaObject.get(doc.pages)', 'for', 'scan', 'in', 'scans:', 'user.media_objects', '-=', '1', 'db.delete(scan)',... | 329,426 |
microsoft/maro | common.py | get_topologies | get_topologies | Get topology list of specified built-in scenario name. | [
"Get",
"topology",
"list",
"of",
"specified",
"built-in",
"scenario",
"name."
] | def get_topologies(scenario: str) -> List[str]:
scenario_topology_root = f'{scenarios_root_folder}/{scenario}/{topologies_folder}'
if not os.path.exists(scenario_topology_root):
return []
try:
(_, topologies, _) = next(os.walk(scenario_topology_root))
topologies = sorted(topologies)
... | ['def', 'get_topologies(scenario:', 'str)', '->', 'List[str]:', 'scenario_topology_root', '=', "f'{scenarios_root_folder}/{scenario}/{topologies_folder}'", 'if', 'not', 'os.path.exists(scenario_topology_root):', 'return', '[]', 'try:', '(_,', 'topologies,', '_)', '=', 'next(os.walk(scenario_topology_root))', 'topologie... | 628,690 |
Eric3911/OpenAGI | ssl_models.py | SpeechEncDecSelfSupervisedModel.forward | forward | Forward pass of the model. | [
"Forward",
"pass",
"of",
"the",
"model."
] | def forward(self, input_signal=None, input_signal_length=None, processed_signal=None, processed_signal_length=None):
if self.is_access_enabled():
self.reset_registry()
if hasattr(self, '_in_validation_step'):
in_validation_step = self._in_validation_step
else:
in_validation_step = Fa... | ['def', 'forward(self,', 'input_signal=None,', 'input_signal_length=None,', 'processed_signal=None,', 'processed_signal_length=None):', 'if', 'self.is_access_enabled():', 'self.reset_registry()', 'if', 'hasattr(self,', "'_in_validation_step'):", 'in_validation_step', '=', 'self._in_validation_step', 'else:', 'in_valida... | 272,513 |
myothida/Supervised-Machine-Learning | test_parallel.py | test_nested_exception_dispatch | test_nested_exception_dispatch | Ensure errors for nested joblib cases gets propagated We rely on the Python 3 built-in __cause__ system that already report this kind of information to the user. | [
"Ensure",
"errors",
"for",
"nested",
"joblib",
"cases",
"gets",
"propagated",
"We",
"rely",
"on",
"the",
"Python",
"3",
"built-in",
"__cause__",
"system",
"that",
"already",
"report",
"this",
"kind",
"of",
"information",
"to",
"the",
"user."
] | def test_nested_exception_dispatch(backend):
with raises(ValueError) as excinfo:
Parallel(n_jobs=2, backend=backend)((delayed(nested_function_outer)(i) for i in range(30)))
report_lines = format_exception(excinfo.type, excinfo.value, excinfo.tb)
report = ''.join(report_lines)
assert 'nested_func... | ['def', 'test_nested_exception_dispatch(backend):', 'with', 'raises(ValueError)', 'as', 'excinfo:', 'Parallel(n_jobs=2,', 'backend=backend)((delayed(nested_function_outer)(i)', 'for', 'i', 'in', 'range(30)))', 'report_lines', '=', 'format_exception(excinfo.type,', 'excinfo.value,', 'excinfo.tb)', 'report', '=', "''.joi... | 361,583 |
tobegit3hub/deep_image_model | embeddings_ops.py | categorical_variable | categorical_variable | Creates an embedding for categorical variable with given number of classes. | [
"Creates",
"an",
"embedding",
"for",
"categorical",
"variable",
"with",
"given",
"number",
"of",
"classes."
] | def categorical_variable(tensor_in, n_classes, embedding_size, name):
with vs.variable_scope(name):
embeddings = vs.get_variable(name + '_embeddings', [n_classes, embedding_size])
return embedding_lookup(embeddings, tensor_in) | ['def', 'categorical_variable(tensor_in,', 'n_classes,', 'embedding_size,', 'name):', 'with', 'vs.variable_scope(name):', 'embeddings', '=', 'vs.get_variable(name', '+', "'_embeddings',", '[n_classes,', 'embedding_size])', 'return', 'embedding_lookup(embeddings,', 'tensor_in)'] | 181,847 |
weimin17/Object-Detection_HelmetDetection | export_tflite_ssd_graph_lib.py | get_const_center_size_encoded_anchors | get_const_center_size_encoded_anchors | Exports center-size encoded anchors as a constant tensor. | [
"Exports",
"center-size",
"encoded",
"anchors",
"as",
"a",
"constant",
"tensor."
] | def get_const_center_size_encoded_anchors(anchors):
anchor_boxlist = box_list.BoxList(anchors)
(y, x, h, w) = anchor_boxlist.get_center_coordinates_and_sizes()
num_anchors = y.get_shape().as_list()
with tf.Session() as sess:
(y_out, x_out, h_out, w_out) = sess.run([y, x, h, w])
encoded_ancho... | ['def', 'get_const_center_size_encoded_anchors(anchors):', 'anchor_boxlist', '=', 'box_list.BoxList(anchors)', '(y,', 'x,', 'h,', 'w)', '=', 'anchor_boxlist.get_center_coordinates_and_sizes()', 'num_anchors', '=', 'y.get_shape().as_list()', 'with', 'tf.Session()', 'as', 'sess:', '(y_out,', 'x_out,', 'h_out,', 'w_out)',... | 751,468 |
Yuting-Gao/DisCo-pytorch | c3d.py | get_10x_lr_params | get_10x_lr_params | This generator returns all the parameters for the last fc layer of the net. | [
"This",
"generator",
"returns",
"all",
"the",
"parameters",
"for",
"the",
"last",
"fc",
"layer",
"of",
"the",
"net."
] | def get_10x_lr_params(model):
b = [model.fc8]
for j in range(len(b)):
for k in b[j].parameters():
if k.requires_grad:
yield k | ['def', 'get_10x_lr_params(model):', 'b', '=', '[model.fc8]', 'for', 'j', 'in', 'range(len(b)):', 'for', 'k', 'in', 'b[j].parameters():', 'if', 'k.requires_grad:', 'yield', 'k'] | 187,560 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | _pylab_helpers.py | Gcf.has_fignum | has_fignum | Return *True* if figure *num* exists. | [
"Return",
"*True*",
"if",
"figure",
"*num*",
"exists."
] | def has_fignum(cls, num):
return num in cls.figs | ['def', 'has_fignum(cls,', 'num):', 'return', 'num', 'in', 'cls.figs'] | 450,957 |
microsoft/MASS | xnli.py | XNLI.eval | eval | Evaluate on XNLI validation and test sets, for all languages. | [
"Evaluate",
"on",
"XNLI",
"validation",
"and",
"test",
"sets,",
"for",
"all",
"languages."
] | def eval(self):
params = self.params
self.embedder.eval()
self.proj.eval()
scores = OrderedDict({'epoch': self.epoch})
for splt in ['valid', 'test']:
for lang in XNLI_LANGS:
lang_id = params.lang2id[lang]
valid = 0
total = 0
for batch in self.g... | ['def', 'eval(self):', 'params', '=', 'self.params', 'self.embedder.eval()', 'self.proj.eval()', 'scores', '=', "OrderedDict({'epoch':", 'self.epoch})', 'for', 'splt', 'in', "['valid',", "'test']:", 'for', 'lang', 'in', 'XNLI_LANGS:', 'lang_id', '=', 'params.lang2id[lang]', 'valid', '=', '0', 'total', '=', '0', 'for', ... | 646,080 |
open-mmlab/mmselfsup | utils.py | TickHelper.set_data_interval | set_data_interval | Set the data interval to (*vmin*, *vmax*). | [
"Set",
"the",
"data",
"interval",
"to",
"(*vmin*,",
"*vmax*)."
] | def set_data_interval(self, vmin: float, vmax: float) -> None:
self.axis.set_data_interval(vmin, vmax) | ['def', 'set_data_interval(self,', 'vmin:', 'float,', 'vmax:', 'float)', '->', 'None:', 'self.axis.set_data_interval(vmin,', 'vmax)'] | 240,508 |
lopez-lab/PyRAI2MD | callbacks.py | lr_step_reduction | lr_step_reduction | Make learning rate schedule function for step reduction. | [
"Make",
"learning",
"rate",
"schedule",
"function",
"for",
"step",
"reduction."
] | def lr_step_reduction(learning_rate_step=[0.001, 0.0001, 1e-05], epoch_step_reduction=[500, 1000, 5000], use=None):
learning_rate_abs = np.cumsum(np.array(epoch_step_reduction))
def lr_out_step(epoch):
learning_rate = float(learning_rate_step[-1])
le = np.array(learning_rate_abs)
lr = n... | ['def', 'lr_step_reduction(learning_rate_step=[0.001,', '0.0001,', '1e-05],', 'epoch_step_reduction=[500,', '1000,', '5000],', 'use=None):', 'learning_rate_abs', '=', 'np.cumsum(np.array(epoch_step_reduction))', 'def', 'lr_out_step(epoch):', 'learning_rate', '=', 'float(learning_rate_step[-1])', 'le', '=', 'np.array(le... | 297,144 |
MRSRL/complex-networks-release | tf_util.py | fft2c | fft2c | Centered FFT2 on second and third dimensions. | [
"Centered",
"FFT2",
"on",
"second",
"and",
"third",
"dimensions."
] | def fft2c(im, name='fft2c', do_orthonorm=True):
with tf.name_scope(name):
im_out = im
dims = tf.shape(im_out)
if do_orthonorm:
fftscale = tf.sqrt(tf.cast(dims[1] * dims[2], dtype=tf.float32))
else:
fftscale = 1.0
fftscale = tf.cast(fftscale, dtype=tf.c... | ['def', 'fft2c(im,', "name='fft2c',", 'do_orthonorm=True):', 'with', 'tf.name_scope(name):', 'im_out', '=', 'im', 'dims', '=', 'tf.shape(im_out)', 'if', 'do_orthonorm:', 'fftscale', '=', 'tf.sqrt(tf.cast(dims[1]', '*', 'dims[2],', 'dtype=tf.float32))', 'else:', 'fftscale', '=', '1.0', 'fftscale', '=', 'tf.cast(fftscale... | 467,280 |
saghul/evergreen | socketpair.py | socketpair | socketpair | Emulate the Unix socketpair() function on Windows. | [
"Emulate",
"the",
"Unix",
"socketpair()",
"function",
"on",
"Windows."
] | def socketpair(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0):
lsock = socket.socket(family, type, proto)
lsock.bind(('localhost', 0))
lsock.listen(1)
(addr, port) = lsock.getsockname()
csock = socket.socket(family, type, proto)
csock.setblocking(False)
try:
csock.connect((... | ['def', 'socketpair(family=socket.AF_INET,', 'type=socket.SOCK_STREAM,', 'proto=0):', 'lsock', '=', 'socket.socket(family,', 'type,', 'proto)', "lsock.bind(('localhost',", '0))', 'lsock.listen(1)', '(addr,', 'port)', '=', 'lsock.getsockname()', 'csock', '=', 'socket.socket(family,', 'type,', 'proto)', 'csock.setblockin... | 178,465 |
apeterswu/RL4NMT | problem.py | Text2TextProblem.generator | generator | Generator for the training and evaluation data. | [
"Generator",
"for",
"the",
"training",
"and",
"evaluation",
"data."
] | def generator(self, data_dir, tmp_dir, is_training):
raise NotImplementedError() | ['def', 'generator(self,', 'data_dir,', 'tmp_dir,', 'is_training):', 'raise', 'NotImplementedError()'] | 330,912 |
deepmind/dm_control | engine.py | Physics.contexts | contexts | Returns a `Contexts` namedtuple, used in `Camera`s and rendering code. | [
"Returns",
"a",
"`Contexts`",
"namedtuple,",
"used",
"in",
"`Camera`s",
"and",
"rendering",
"code."
] | def contexts(self):
with self._contexts_lock:
if not self._contexts:
self._make_rendering_contexts()
return self._contexts | ['def', 'contexts(self):', 'with', 'self._contexts_lock:', 'if', 'not', 'self._contexts:', 'self._make_rendering_contexts()', 'return', 'self._contexts'] | 166,169 |
replit-archive/empythoned | fix_urllib.py | FixUrllib.transform_dot | transform_dot | Transform for calls to module members in code. | [
"Transform",
"for",
"calls",
"to",
"module",
"members",
"in",
"code."
] | def transform_dot(self, node, results):
module_dot = results.get('bare_with_attr')
member = results.get('member')
new_name = None
if isinstance(member, list):
member = member[0]
for change in MAPPING[module_dot.value]:
if member.value in change[1]:
new_name = change[0]
... | ['def', 'transform_dot(self,', 'node,', 'results):', 'module_dot', '=', "results.get('bare_with_attr')", 'member', '=', "results.get('member')", 'new_name', '=', 'None', 'if', 'isinstance(member,', 'list):', 'member', '=', 'member[0]', 'for', 'change', 'in', 'MAPPING[module_dot.value]:', 'if', 'member.value', 'in', 'ch... | 176,840 |
AndrewSpano/BSc-Thesis | plot_utils.py | get_hf_mlm_losses | get_hf_mlm_losses | Reads the train/val losses from tensorboard log files produced by Hugging Face and returns them. | [
"Reads",
"the",
"train/val",
"losses",
"from",
"tensorboard",
"log",
"files",
"produced",
"by",
"Hugging",
"Face",
"and",
"returns",
"them."
] | def get_hf_mlm_losses(logdir: Path) -> Tuple[List[float], List[float]]:
(train_losses, val_losses) = ([], [])
tb_files = glob.glob(f'{logdir}/events.out.tfevents.*') + glob.glob(f'{logdir}/*/events.out.tfevents.*')
for tb_out in tb_files:
for e in EventFileLoader(tb_out).Load():
if len(e... | ['def', 'get_hf_mlm_losses(logdir:', 'Path)', '->', 'Tuple[List[float],', 'List[float]]:', '(train_losses,', 'val_losses)', '=', '([],', '[])', 'tb_files', '=', "glob.glob(f'{logdir}/events.out.tfevents.*')", '+', "glob.glob(f'{logdir}/*/events.out.tfevents.*')", 'for', 'tb_out', 'in', 'tb_files:', 'for', 'e', 'in', 'E... | 410,086 |
43Carrig/recurrent_neural_networks_practice | variable_scope.py | VariableScope.global_variables | global_variables | Get this scope's global variables. | [
"Get",
"this",
"scope's",
"global",
"variables."
] | def global_variables(self):
return self.get_collection(ops.GraphKeys.GLOBAL_VARIABLES) | ['def', 'global_variables(self):', 'return', 'self.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)'] | 339,142 |
yinyunie/ScenePriors | dataset_base.py | FrameData.collate | collate | Given a list objects `batch` of class `cls`, collates them into a batched representation suitable for processing with deep networks. | [
"Given",
"a",
"list",
"objects",
"`batch`",
"of",
"class",
"`cls`,",
"collates",
"them",
"into",
"a",
"batched",
"representation",
"suitable",
"for",
"processing",
"with",
"deep",
"networks."
] | def collate(cls, batch):
elem = batch[0]
if isinstance(elem, cls):
pointcloud_ids = [id(el.sequence_point_cloud) for el in batch]
id_to_idx = defaultdict(list)
for (i, pc_id) in enumerate(pointcloud_ids):
id_to_idx[pc_id].append(i)
sequence_point_cloud = []
se... | ['def', 'collate(cls,', 'batch):', 'elem', '=', 'batch[0]', 'if', 'isinstance(elem,', 'cls):', 'pointcloud_ids', '=', '[id(el.sequence_point_cloud)', 'for', 'el', 'in', 'batch]', 'id_to_idx', '=', 'defaultdict(list)', 'for', '(i,', 'pc_id)', 'in', 'enumerate(pointcloud_ids):', 'id_to_idx[pc_id].append(i)', 'sequence_po... | 329,628 |
nilearn/nilearn | test_resampling.py | rotation | rotation | Returns a rotation 3x3 matrix. | [
"Returns",
"a",
"rotation",
"3x3",
"matrix."
] | def rotation(theta, phi):
cos = np.cos
sin = np.sin
a1 = np.array([[cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]])
a2 = np.array([[1, 0, 0], [0, cos(phi), -sin(phi)], [0, sin(phi), cos(phi)]])
return np.dot(a1, a2) | ['def', 'rotation(theta,', 'phi):', 'cos', '=', 'np.cos', 'sin', '=', 'np.sin', 'a1', '=', 'np.array([[cos(theta),', '-sin(theta),', '0],', '[sin(theta),', 'cos(theta),', '0],', '[0,', '0,', '1]])', 'a2', '=', 'np.array([[1,', '0,', '0],', '[0,', 'cos(phi),', '-sin(phi)],', '[0,', 'sin(phi),', 'cos(phi)]])', 'return', ... | 723,918 |
Su-informatics-lab/DSTG | layers.py | get_layer_uid | get_layer_uid | Helper function, assigns unique layer IDs. | [
"Helper",
"function,",
"assigns",
"unique",
"layer",
"IDs."
] | def get_layer_uid(layer_name=''):
if layer_name not in _LAYER_UIDS:
_LAYER_UIDS[layer_name] = 1
return 1
else:
_LAYER_UIDS[layer_name] += 1
return _LAYER_UIDS[layer_name] | ['def', "get_layer_uid(layer_name=''):", 'if', 'layer_name', 'not', 'in', '_LAYER_UIDS:', '_LAYER_UIDS[layer_name]', '=', '1', 'return', '1', 'else:', '_LAYER_UIDS[layer_name]', '+=', '1', 'return', '_LAYER_UIDS[layer_name]'] | 173,974 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | timeseries.py | TimeseriesToyProblem.num_target_timestamps | num_target_timestamps | Number of timestamps to include in the target. | [
"Number",
"of",
"timestamps",
"to",
"include",
"in",
"the",
"target."
] | def num_target_timestamps(self):
return 2 | ['def', 'num_target_timestamps(self):', 'return', '2'] | 965,042 |
rudranil723/mini-main | DateTime.py | safegmtime | safegmtime | gmtime with a safety zone. | [
"gmtime",
"with",
"a",
"safety",
"zone."
] | def safegmtime(t):
try:
return gmtime(t)
except (ValueError, OverflowError):
raise TimeError('The time %f is beyond the range of this Python implementation.' % float(t)) | ['def', 'safegmtime(t):', 'try:', 'return', 'gmtime(t)', 'except', '(ValueError,', 'OverflowError):', 'raise', "TimeError('The", 'time', '%f', 'is', 'beyond', 'the', 'range', 'of', 'this', 'Python', "implementation.'", '%', 'float(t))'] | 314,529 |
iffiX/machin | save_env.py | SaveEnv.remove_trials_older_than | remove_trials_older_than | By default this function removes all trials started one hour earlier than current time. | [
"By",
"default",
"this",
"function",
"removes",
"all",
"trials",
"started",
"one",
"hour",
"earlier",
"than",
"current",
"time."
] | def remove_trials_older_than(self, diff_day: int=0, diff_hour: int=1, diff_minute: int=0, diff_second: int=0):
trial_list = [f for f in os.listdir(self.env_root)]
current_time = datetime.now()
diff_threshold = timedelta(days=diff_day, hours=diff_hour, minutes=diff_minute, seconds=diff_second)
for file i... | ['def', 'remove_trials_older_than(self,', 'diff_day:', 'int=0,', 'diff_hour:', 'int=1,', 'diff_minute:', 'int=0,', 'diff_second:', 'int=0):', 'trial_list', '=', '[f', 'for', 'f', 'in', 'os.listdir(self.env_root)]', 'current_time', '=', 'datetime.now()', 'diff_threshold', '=', 'timedelta(days=diff_day,', 'hours=diff_hou... | 620,465 |
aeon-toolkit/aeon | test_panel_converters.py | test_from_nested_to_multi_index | test_from_nested_to_multi_index | Test from_nested_to_multi_index for correctness. | [
"Test",
"from_nested_to_multi_index",
"for",
"correctness."
] | def test_from_nested_to_multi_index(n_instances, n_channels, n_timepoints):
(nested, _) = make_nested_dataframe_data(n_instances, n_channels, n_timepoints)
mi_df = from_nested_to_multi_index(nested, instance_index='case_id', time_index='reading_id')
assert isinstance(mi_df, pd.DataFrame)
assert mi_df.sh... | ['def', 'test_from_nested_to_multi_index(n_instances,', 'n_channels,', 'n_timepoints):', '(nested,', '_)', '=', 'make_nested_dataframe_data(n_instances,', 'n_channels,', 'n_timepoints)', 'mi_df', '=', 'from_nested_to_multi_index(nested,', "instance_index='case_id',", "time_index='reading_id')", 'assert', 'isinstance(mi... | 399,426 |
scikit-learn/scikit-learn | plot_outlier_detection_bench.py | make_estimator | make_estimator | Create an outlier detection estimator based on its name. | [
"Create",
"an",
"outlier",
"detection",
"estimator",
"based",
"on",
"its",
"name."
] | def make_estimator(name, categorical_columns=None, iforest_kw=None, lof_kw=None):
if name == 'LOF':
outlier_detector = LocalOutlierFactor(**lof_kw or {})
if categorical_columns is None:
preprocessor = RobustScaler()
else:
preprocessor = ColumnTransformer(transformers=... | ['def', 'make_estimator(name,', 'categorical_columns=None,', 'iforest_kw=None,', 'lof_kw=None):', 'if', 'name', '==', "'LOF':", 'outlier_detector', '=', 'LocalOutlierFactor(**lof_kw', 'or', '{})', 'if', 'categorical_columns', 'is', 'None:', 'preprocessor', '=', 'RobustScaler()', 'else:', 'preprocessor', '=', "ColumnTra... | 848,193 |
nicknochnack/RealTimeSignLanguageTFJS | utils.py | ConvertAllInputsToTensors | ConvertAllInputsToTensors | A decorator to convert all function's inputs into tensors. | [
"A",
"decorator",
"to",
"convert",
"all",
"function's",
"inputs",
"into",
"tensors."
] | def ConvertAllInputsToTensors(func):
def FuncWrapper(*args):
tensors = [tf.convert_to_tensor(value=a) for a in args]
return func(*tensors)
return FuncWrapper | ['def', 'ConvertAllInputsToTensors(func):', 'def', 'FuncWrapper(*args):', 'tensors', '=', '[tf.convert_to_tensor(value=a)', 'for', 'a', 'in', 'args]', 'return', 'func(*tensors)', 'return', 'FuncWrapper'] | 851,387 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | MethodContent.acceptDo | acceptDo | Accept and process a do-while block. | [
"Accept",
"and",
"process",
"a",
"do-while",
"block."
] | def acceptDo(self, node, memo):
(blkNode, parNode) = node.children
whileStat = self.factory.statement('while', fs=FS.lsrc, parent=self)
whileStat.expr.right = 'True'
whileStat.walk(blkNode, memo)
fs = FS.l + ' ' + 'not ({right}):'
ifStat = self.factory.statement('if', fs=fs, parent=whileStat)
... | ['def', 'acceptDo(self,', 'node,', 'memo):', '(blkNode,', 'parNode)', '=', 'node.children', 'whileStat', '=', "self.factory.statement('while',", 'fs=FS.lsrc,', 'parent=self)', 'whileStat.expr.right', '=', "'True'", 'whileStat.walk(blkNode,', 'memo)', 'fs', '=', 'FS.l', '+', "'", "'", '+', "'not", "({right}):'", 'ifStat... | 17,094 |
caiiiac/Machine-Learning-with-Python | _base.py | _AxesBase.yaxis_inverted | yaxis_inverted | Returns *True* if the y-axis is inverted. | [
"Returns",
"*True*",
"if",
"the",
"y-axis",
"is",
"inverted."
] | def yaxis_inverted(self):
(bottom, top) = self.get_ylim()
return top < bottom | ['def', 'yaxis_inverted(self):', '(bottom,', 'top)', '=', 'self.get_ylim()', 'return', 'top', '<', 'bottom'] | 716,318 |
Wuziyi616/Artificial_Intelligence_Project1 | image_utils.py | read_gray_image | read_gray_image | Read in a gray scale image. | [
"Read",
"in",
"a",
"gray",
"scale",
"image."
] | def read_gray_image(path):
image = cv2.imread(path, 0)
return image | ['def', 'read_gray_image(path):', 'image', '=', 'cv2.imread(path,', '0)', 'return', 'image'] | 92,079 |
feast-dev/feast | feature_store.py | FeatureStore.write_to_online_store | write_to_online_store | Persists a dataframe to the online store. | [
"Persists",
"a",
"dataframe",
"to",
"the",
"online",
"store."
] | def write_to_online_store(self, feature_view_name: str, df: pd.DataFrame, allow_registry_cache: bool=True):
try:
feature_view = self.get_stream_feature_view(feature_view_name, allow_registry_cache=allow_registry_cache)
except FeatureViewNotFoundException:
feature_view = self.get_feature_view(fea... | ['def', 'write_to_online_store(self,', 'feature_view_name:', 'str,', 'df:', 'pd.DataFrame,', 'allow_registry_cache:', 'bool=True):', 'try:', 'feature_view', '=', 'self.get_stream_feature_view(feature_view_name,', 'allow_registry_cache=allow_registry_cache)', 'except', 'FeatureViewNotFoundException:', 'feature_view', '=... | 544,252 |
sandialabs/bcnn | dataset.py | get_train_data | get_train_data | Loads or creates train data. | [
"Loads",
"or",
"creates",
"train",
"data."
] | def get_train_data(data_dir):
print('in get_train_data')
os.makedirs(data_dir, exist_ok=True)
train_path = data_dir + '/train.npy'
valid_path = data_dir + '/valid.npy'
train_targets_path = data_dir + '/train_targets.npy'
valid_targets_path = data_dir + '/valid_targets.npy'
try:
train... | ['def', 'get_train_data(data_dir):', "print('in", "get_train_data')", 'os.makedirs(data_dir,', 'exist_ok=True)', 'train_path', '=', 'data_dir', '+', "'/train.npy'", 'valid_path', '=', 'data_dir', '+', "'/valid.npy'", 'train_targets_path', '=', 'data_dir', '+', "'/train_targets.npy'", 'valid_targets_path', '=', 'data_di... | 105,967 |
mkusner/grammarVAE | opt.py | check_for_x_over_absX | check_for_x_over_absX | Convert x/abs(x) into sign(x). | [
"Convert",
"x/abs(x)",
"into",
"sign(x)."
] | def check_for_x_over_absX(numerators, denominators):
for den in list(denominators):
if den.owner and den.owner.op == T.abs_ and (den.owner.inputs[0] in numerators):
if den.owner.inputs[0].type.dtype.startswith('complex'):
pass
else:
denominators.remove... | ['def', 'check_for_x_over_absX(numerators,', 'denominators):', 'for', 'den', 'in', 'list(denominators):', 'if', 'den.owner', 'and', 'den.owner.op', '==', 'T.abs_', 'and', '(den.owner.inputs[0]', 'in', 'numerators):', 'if', "den.owner.inputs[0].type.dtype.startswith('complex'):", 'pass', 'else:', 'denominators.remove(de... | 579,923 |
zihuitang/medical_AI_platform | __init__.py | Entry.selection_range | selection_range | Set the selection from START to END (not included). | [
"Set",
"the",
"selection",
"from",
"START",
"to",
"END",
"(not",
"included)."
] | def selection_range(self, start, end):
self.tk.call(self._w, 'selection', 'range', start, end) | ['def', 'selection_range(self,', 'start,', 'end):', 'self.tk.call(self._w,', "'selection',", "'range',", 'start,', 'end)'] | 284,265 |
sek788432/Waymo-2D-Object-Detection | datum_io.py | ReadPairFromFile | ReadPairFromFile | Helper function to load data from a DatumPairProto format in a file. | [
"Helper",
"function",
"to",
"load",
"data",
"from",
"a",
"DatumPairProto",
"format",
"in",
"a",
"file."
] | def ReadPairFromFile(file_path):
with tf.io.gfile.GFile(file_path, 'rb') as f:
return ParsePairFromString(f.read()) | ['def', 'ReadPairFromFile(file_path):', 'with', 'tf.io.gfile.GFile(file_path,', "'rb')", 'as', 'f:', 'return', 'ParsePairFromString(f.read())'] | 974,230 |
neokarn/computer_vision | cpp_lint.py | GetPreviousNonBlankLine | GetPreviousNonBlankLine | Return the most recent non-blank line and its line number. | [
"Return",
"the",
"most",
"recent",
"non-blank",
"line",
"and",
"its",
"line",
"number."
] | def GetPreviousNonBlankLine(clean_lines, linenum):
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline):
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1) | ['def', 'GetPreviousNonBlankLine(clean_lines,', 'linenum):', 'prevlinenum', '=', 'linenum', '-', '1', 'while', 'prevlinenum', '>=', '0:', 'prevline', '=', 'clean_lines.elided[prevlinenum]', 'if', 'not', 'IsBlankLine(prevline):', 'return', '(prevline,', 'prevlinenum)', 'prevlinenum', '-=', '1', 'return', "('',", '-1)'] | 472,881 |
Ruturaj123/Flowchart-Detection | gcs_smoke.py | create_examples | create_examples | Create ExampleProto's containing data. | [
"Create",
"ExampleProto's",
"containing",
"data."
] | def create_examples(num_examples, input_mean):
ids = np.arange(num_examples).reshape([num_examples, 1])
inputs = np.random.randn(num_examples, 1) + input_mean
target = inputs - input_mean
examples = []
for row in range(num_examples):
ex = example_pb2.Example()
ex.features.feature['id... | ['def', 'create_examples(num_examples,', 'input_mean):', 'ids', '=', 'np.arange(num_examples).reshape([num_examples,', '1])', 'inputs', '=', 'np.random.randn(num_examples,', '1)', '+', 'input_mean', 'target', '=', 'inputs', '-', 'input_mean', 'examples', '=', '[]', 'for', 'row', 'in', 'range(num_examples):', 'ex', '=',... | 606,773 |
LLNL/Abmarl | state.py | MazePlacementState.cluster_barriers | cluster_barriers | If True, then prioritize placing barriers near the target agent. | [
"If",
"True,",
"then",
"prioritize",
"placing",
"barriers",
"near",
"the",
"target",
"agent."
] | def cluster_barriers(self):
return self._cluster_barriers | ['def', 'cluster_barriers(self):', 'return', 'self._cluster_barriers'] | 405,802 |
lhotse-speech/lhotse | cmu_kids.py | cmu_kids | cmu_kids | CMU Kids corpus data preparation. | [
"CMU",
"Kids",
"corpus",
"data",
"preparation."
] | def cmu_kids(corpus_dir: Pathlike, output_dir: Pathlike, absolute_paths: Optional[bool]=False):
prepare_cmu_kids(corpus_dir, output_dir=output_dir, absolute_paths=absolute_paths) | ['def', 'cmu_kids(corpus_dir:', 'Pathlike,', 'output_dir:', 'Pathlike,', 'absolute_paths:', 'Optional[bool]=False):', 'prepare_cmu_kids(corpus_dir,', 'output_dir=output_dir,', 'absolute_paths=absolute_paths)'] | 600,591 |
myothida/Supervised-Machine-Learning | c_parser_wrapper.py | ensure_dtype_objs | ensure_dtype_objs | Ensure we have either None, a dtype object, or a dictionary mapping to dtype objects. | [
"Ensure",
"we",
"have",
"either",
"None,",
"a",
"dtype",
"object,",
"or",
"a",
"dictionary",
"mapping",
"to",
"dtype",
"objects."
] | def ensure_dtype_objs(dtype: DtypeArg | dict[Hashable, DtypeArg] | None) -> DtypeObj | dict[Hashable, DtypeObj] | None:
if isinstance(dtype, defaultdict):
default_dtype = pandas_dtype(dtype.default_factory())
dtype_converted: defaultdict = defaultdict(lambda : default_dtype)
for key in dtype... | ['def', 'ensure_dtype_objs(dtype:', 'DtypeArg', '|', 'dict[Hashable,', 'DtypeArg]', '|', 'None)', '->', 'DtypeObj', '|', 'dict[Hashable,', 'DtypeObj]', '|', 'None:', 'if', 'isinstance(dtype,', 'defaultdict):', 'default_dtype', '=', 'pandas_dtype(dtype.default_factory())', 'dtype_converted:', 'defaultdict', '=', 'defaul... | 443,455 |
PKU-Alignment/safe-rlhf | logger.py | set_logger_level | set_logger_level | Set the logger level. | [
"Set",
"the",
"logger",
"level."
] | def set_logger_level(level: LoggerLevel | None=None) -> None:
level = level or os.getenv('LOGLEVEL')
if level is None:
return
level = level.upper()
if is_main_process():
print(f'Set logger level to {level}.')
logging.basicConfig(level=level)
_LOGGER.setLevel(level)
logging.ge... | ['def', 'set_logger_level(level:', 'LoggerLevel', '|', 'None=None)', '->', 'None:', 'level', '=', 'level', 'or', "os.getenv('LOGLEVEL')", 'if', 'level', 'is', 'None:', 'return', 'level', '=', 'level.upper()', 'if', 'is_main_process():', "print(f'Set", 'logger', 'level', 'to', "{level}.')", 'logging.basicConfig(level=le... | 829,114 |
Ruturaj123/Flowchart-Detection | binomial.py | Binomial.probs | probs | Probability of drawing a `1`. | [
"Probability",
"of",
"drawing",
"a",
"`1`."
] | def probs(self):
return self._probs | ['def', 'probs(self):', 'return', 'self._probs'] | 602,885 |
jason718/game-feature-learning | test_coord_map.py | TestCoordMap.test_rect | test_rect | Anisotropic mapping is equivalent to its isotropic parts. | [
"Anisotropic",
"mapping",
"is",
"equivalent",
"to",
"its",
"isotropic",
"parts."
] | def test_rect(self):
n3x3 = coord_net_spec(ks=3, stride=1, pad=0)
n5x5 = coord_net_spec(ks=5, stride=2, pad=10)
n3x5 = coord_net_spec(ks=[3, 5], stride=[1, 2], pad=[0, 10])
(ax_3x3, a_3x3, b_3x3) = coord_map_from_to(n3x3.deconv, n3x3.data)
(ax_5x5, a_5x5, b_5x5) = coord_map_from_to(n5x5.deconv, n5x5... | ['def', 'test_rect(self):', 'n3x3', '=', 'coord_net_spec(ks=3,', 'stride=1,', 'pad=0)', 'n5x5', '=', 'coord_net_spec(ks=5,', 'stride=2,', 'pad=10)', 'n3x5', '=', 'coord_net_spec(ks=[3,', '5],', 'stride=[1,', '2],', 'pad=[0,', '10])', '(ax_3x3,', 'a_3x3,', 'b_3x3)', '=', 'coord_map_from_to(n3x3.deconv,', 'n3x3.data)', '... | 199,491 |
tensorlayer/TensorLayerX | utils.py | del_file | del_file | Delete a file by given file path. | [
"Delete",
"a",
"file",
"by",
"given",
"file",
"path."
] | def del_file(filepath):
os.remove(filepath) | ['def', 'del_file(filepath):', 'os.remove(filepath)'] | 923,762 |
swisscom/cleanerversion | test_models.py | PrefetchingHistoricTests.test_reverse_fk_simple_prefetch_with_historic_versions | test_reverse_fk_simple_prefetch_with_historic_versions | prefetch_related with simple lookup. | [
"prefetch_related",
"with",
"simple",
"lookup."
] | def test_reverse_fk_simple_prefetch_with_historic_versions(self):
historic_cities_qs = City.objects.as_of(self.time1).filter(name='city.v1').prefetch_related('team_set', 'team_set__player_set')
with self.assertNumQueries(3):
historic_cities = list(historic_cities_qs)
self.assertEquals(1, len(his... | ['def', 'test_reverse_fk_simple_prefetch_with_historic_versions(self):', 'historic_cities_qs', '=', "City.objects.as_of(self.time1).filter(name='city.v1').prefetch_related('team_set',", "'team_set__player_set')", 'with', 'self.assertNumQueries(3):', 'historic_cities', '=', 'list(historic_cities_qs)', 'self.assertEquals... | 122,461 |
ryu-ed/SpaceInvaders_Ros | draw_py.py | draw_aaline | draw_aaline | draw anti-aliased line between two endpoints. | [
"draw",
"anti-aliased",
"line",
"between",
"two",
"endpoints."
] | def draw_aaline(surf, color, from_point, to_point, blend=True):
line = [from_point[0], from_point[1], to_point[0], to_point[1]]
return _clip_and_draw_aaline(surf, surf.get_clip(), color, line, blend) | ['def', 'draw_aaline(surf,', 'color,', 'from_point,', 'to_point,', 'blend=True):', 'line', '=', '[from_point[0],', 'from_point[1],', 'to_point[0],', 'to_point[1]]', 'return', '_clip_and_draw_aaline(surf,', 'surf.get_clip(),', 'color,', 'line,', 'blend)'] | 368,713 |
KalleHallden/InstaAutomator | _tifffile.py | read_cz_lsm_scan_info | read_cz_lsm_scan_info | Read LSM scan information from file and return as Record. | [
"Read",
"LSM",
"scan",
"information",
"from",
"file",
"and",
"return",
"as",
"Record."
] | def read_cz_lsm_scan_info(fh):
block = Record()
blocks = [block]
unpack = struct.unpack
if 268435456 != struct.unpack('<I', fh.read(4))[0]:
raise ValueError('not a lsm_scan_info structure')
fh.read(8)
while True:
(entry, dtype, size) = unpack('<III', fh.read(12))
if dtype... | ['def', 'read_cz_lsm_scan_info(fh):', 'block', '=', 'Record()', 'blocks', '=', '[block]', 'unpack', '=', 'struct.unpack', 'if', '268435456', '!=', "struct.unpack('<I',", 'fh.read(4))[0]:', 'raise', "ValueError('not", 'a', 'lsm_scan_info', "structure')", 'fh.read(8)', 'while', 'True:', '(entry,', 'dtype,', 'size)', '=',... | 230,012 |
43Carrig/recurrent_neural_networks_practice | __init__.py | level_warning | level_warning | Returns True if warning logging is turned on. | [
"Returns",
"True",
"if",
"warning",
"logging",
"is",
"turned",
"on."
] | def level_warning():
return get_verbosity() >= WARNING | ['def', 'level_warning():', 'return', 'get_verbosity()', '>=', 'WARNING'] | 309,692 |
deepmind/dm_control | task.py | Task.get_reward | get_reward | Calculates the reward signal given the physics state. | [
"Calculates",
"the",
"reward",
"signal",
"given",
"the",
"physics",
"state."
] | def get_reward(self, physics):
raise NotImplementedError | ['def', 'get_reward(self,', 'physics):', 'raise', 'NotImplementedError'] | 164,984 |
hsahovic/poke-env | player.py | Player.reset_battles | reset_battles | Resets the player's inner battle tracker. | [
"Resets",
"the",
"player's",
"inner",
"battle",
"tracker."
] | def reset_battles(self):
for battle in list(self._battles.values()):
if not battle.finished:
raise EnvironmentError("Can not reset player's battles while they are still running")
self._battles = {} | ['def', 'reset_battles(self):', 'for', 'battle', 'in', 'list(self._battles.values()):', 'if', 'not', 'battle.finished:', 'raise', 'EnvironmentError("Can', 'not', 'reset', "player's", 'battles', 'while', 'they', 'are', 'still', 'running")', 'self._battles', '=', '{}'] | 782,167 |
google/deepvariant | dv_utils.py | example_label | example_label | Gets the label field from example as a string. | [
"Gets",
"the",
"label",
"field",
"from",
"example",
"as",
"a",
"string."
] | def example_label(example):
return int(example.features.feature['label'].int64_list.value[0]) | ['def', 'example_label(example):', 'return', "int(example.features.feature['label'].int64_list.value[0])"] | 540,269 |
google/deepvariant | modeling.py | DeepVariantSlimModel.make_ops_and_estimator | make_ops_and_estimator | Make EstimatorSpec for the current model. | [
"Make",
"EstimatorSpec",
"for",
"the",
"current",
"model."
] | def make_ops_and_estimator(self, features, endpoints, labels, logits, predictions, total_loss, mode, params):
(train_op, host_call) = self._model_fn_train(mode=mode, total_loss=total_loss, batches_per_epoch=params.get('batches_per_epoch', None), num_epochs_per_decay=FLAGS.num_epochs_per_decay, initial_learning_rate... | ['def', 'make_ops_and_estimator(self,', 'features,', 'endpoints,', 'labels,', 'logits,', 'predictions,', 'total_loss,', 'mode,', 'params):', '(train_op,', 'host_call)', '=', 'self._model_fn_train(mode=mode,', 'total_loss=total_loss,', "batches_per_epoch=params.get('batches_per_epoch',", 'None),', 'num_epochs_per_decay=... | 540,365 |
sandialabs/bcnn | dataset.py | reconstruct | reconstruct | Reconstructs a 4D numpy array from its generated chunks. | [
"Reconstructs",
"a",
"4D",
"numpy",
"array",
"from",
"its",
"generated",
"chunks."
] | def reconstruct(arr, coords, shape, window):
new = np.zeros(shape)
count = np.zeros(shape)
for (chunk, coord) in zip(arr, coords):
new[coord[0]:coord[0] + window[0], coord[1]:coord[1] + window[1], coord[2]:coord[2] + window[2], :] += chunk
count[coord[0]:coord[0] + window[0], coord[1]:coord[... | ['def', 'reconstruct(arr,', 'coords,', 'shape,', 'window):', 'new', '=', 'np.zeros(shape)', 'count', '=', 'np.zeros(shape)', 'for', '(chunk,', 'coord)', 'in', 'zip(arr,', 'coords):', 'new[coord[0]:coord[0]', '+', 'window[0],', 'coord[1]:coord[1]', '+', 'window[1],', 'coord[2]:coord[2]', '+', 'window[2],', ':]', '+=', '... | 105,962 |
som-shahlab/femr | tools.py | save_to_pkl | save_to_pkl | Save object to Pickle file. | [
"Save",
"object",
"to",
"Pickle",
"file."
] | def save_to_pkl(object_to_save, path_to_file: str):
os.makedirs(os.path.dirname(path_to_file), exist_ok=True)
with open(path_to_file, 'wb') as fd:
pickle.dump(object_to_save, fd) | ['def', 'save_to_pkl(object_to_save,', 'path_to_file:', 'str):', 'os.makedirs(os.path.dirname(path_to_file),', 'exist_ok=True)', 'with', 'open(path_to_file,', "'wb')", 'as', 'fd:', 'pickle.dump(object_to_save,', 'fd)'] | 179,832 |
weimin17/Object-Detection_HelmetDetection | model_construction.py | create_discriminator | create_discriminator | Create the Discriminator model specified by the FLAGS and hparams. | [
"Create",
"the",
"Discriminator",
"model",
"specified",
"by",
"the",
"FLAGS",
"and",
"hparams."
] | def create_discriminator(hparams, sequence, is_training, reuse=None, initial_state=None, inputs=None, present=None):
if FLAGS.discriminator_model == 'cnn':
predictions = cnn.discriminator(hparams, sequence, is_training=is_training, reuse=reuse)
elif FLAGS.discriminator_model == 'fnn':
prediction... | ['def', 'create_discriminator(hparams,', 'sequence,', 'is_training,', 'reuse=None,', 'initial_state=None,', 'inputs=None,', 'present=None):', 'if', 'FLAGS.discriminator_model', '==', "'cnn':", 'predictions', '=', 'cnn.discriminator(hparams,', 'sequence,', 'is_training=is_training,', 'reuse=reuse)', 'elif', 'FLAGS.discr... | 763,752 |
thaines/helit | gaussian.py | Gaussian.getCovariance | getCovariance | Returns the covariance matrix. | [
"Returns",
"the",
"covariance",
"matrix."
] | def getCovariance(self):
if self.covariance is None:
self.covariance = numpy.linalg.inv(self.precision)
return self.covariance | ['def', 'getCovariance(self):', 'if', 'self.covariance', 'is', 'None:', 'self.covariance', '=', 'numpy.linalg.inv(self.precision)', 'return', 'self.covariance'] | 591,644 |
carbonati/variational-zoo | utils.py | pad_images | pad_images | Pads and concatenates a list of images. | [
"Pads",
"and",
"concatenates",
"a",
"list",
"of",
"images."
] | def pad_images(images, pad_size=1, pad_value=0, axis=0):
num_images = len(images)
pad_shape = list(images[0].shape)
pad_shape[axis] = pad_size
x_pad = np.ones(pad_shape, dtype=images[0].dtype) * pad_value
images_padded = []
for (i, img) in enumerate(images):
images_padded.append(img)
... | ['def', 'pad_images(images,', 'pad_size=1,', 'pad_value=0,', 'axis=0):', 'num_images', '=', 'len(images)', 'pad_shape', '=', 'list(images[0].shape)', 'pad_shape[axis]', '=', 'pad_size', 'x_pad', '=', 'np.ones(pad_shape,', 'dtype=images[0].dtype)', '*', 'pad_value', 'images_padded', '=', '[]', 'for', '(i,', 'img)', 'in'... | 379,264 |
facebookresearch/CompilerGym | connection.py | ManagedConnection.service_is_down | service_is_down | Return true if the service subprocess has terminated. | [
"Return",
"true",
"if",
"the",
"service",
"subprocess",
"has",
"terminated."
] | def service_is_down(self) -> bool:
return self.process.poll() is not None | ['def', 'service_is_down(self)', '->', 'bool:', 'return', 'self.process.poll()', 'is', 'not', 'None'] | 126,226 |
Bismarrck/kcon | database.py | Database.split | split | Split this database into training set and testing set. | [
"Split",
"this",
"database",
"into",
"training",
"set",
"and",
"testing",
"set."
] | def split(self, test_size=0.2, random_state=None):
random_state = random_state or SEED
(ids_for_training, ids_for_testing) = train_test_split(list(range(1, len(self) + 1)), test_size=test_size, random_state=random_state)
self._splitted = True
self._id_list[ModeKeys.TRAIN] = ids_for_training
self._id... | ['def', 'split(self,', 'test_size=0.2,', 'random_state=None):', 'random_state', '=', 'random_state', 'or', 'SEED', '(ids_for_training,', 'ids_for_testing)', '=', 'train_test_split(list(range(1,', 'len(self)', '+', '1)),', 'test_size=test_size,', 'random_state=random_state)', 'self._splitted', '=', 'True', 'self._id_lis... | 247,487 |
rifqind/Agent-Programs-3KS1 | test_interactiveshell.py | TestModules.test_extraneous_loads | test_extraneous_loads | Test we're not loading modules on startup that we shouldn't. | [
"Test",
"we're",
"not",
"loading",
"modules",
"on",
"startup",
"that",
"we",
"shouldn't."
] | def test_extraneous_loads(self):
self.mktmp("import sys\nprint('numpy' in sys.modules)\nprint('ipyparallel' in sys.modules)\nprint('ipykernel' in sys.modules)\n")
out = 'False\nFalse\nFalse\n'
tt.ipexec_validate(self.fname, out) | ['def', 'test_extraneous_loads(self):', 'self.mktmp("import', "sys\\nprint('numpy'", 'in', "sys.modules)\\nprint('ipyparallel'", 'in', "sys.modules)\\nprint('ipykernel'", 'in', 'sys.modules)\\n")', 'out', '=', "'False\\nFalse\\nFalse\\n'", 'tt.ipexec_validate(self.fname,', 'out)'] | 41,444 |
caiiiac/Machine-Learning-with-Python | _validators.py | validate_bool_kwarg | validate_bool_kwarg | Ensures that argument passed in arg_name is of type bool. | [
"Ensures",
"that",
"argument",
"passed",
"in",
"arg_name",
"is",
"of",
"type",
"bool."
] | def validate_bool_kwarg(value, arg_name):
if not (is_bool(value) or value is None):
raise ValueError('For argument "%s" expected type bool, received type %s.' % (arg_name, type(value).__name__))
return value | ['def', 'validate_bool_kwarg(value,', 'arg_name):', 'if', 'not', '(is_bool(value)', 'or', 'value', 'is', 'None):', 'raise', "ValueError('For", 'argument', '"%s"', 'expected', 'type', 'bool,', 'received', 'type', "%s.'", '%', '(arg_name,', 'type(value).__name__))', 'return', 'value'] | 718,596 |
zihuitang/medical_AI_platform | operator.py | le | le | Same as a <= b. | [
"Same",
"as",
"a",
"<=",
"b."
] | def le(a, b):
return a <= b | ['def', 'le(a,', 'b):', 'return', 'a', '<=', 'b'] | 280,876 |
HDI-Project/ATM | test_worker.py | test_select_hyperpartition | test_select_hyperpartition | This won't test that BTB is working correctly, just that the ATM-BTB connection is working. | [
"This",
"won't",
"test",
"that",
"BTB",
"is",
"working",
"correctly,",
"just",
"that",
"the",
"ATM-BTB",
"connection",
"is",
"working."
] | def test_select_hyperpartition(worker):
worker.db.get_hyperpartitions = Mock(return_value=[Mock(id=1)])
clf_mock = Mock(hyperpartition_id=1, cv_judgment_metric=0.5)
worker.db.get_classifiers = Mock(return_value=[clf_mock])
worker.selector.select = Mock(return_value=1)
hp = worker.select_hyperpartiti... | ['def', 'test_select_hyperpartition(worker):', 'worker.db.get_hyperpartitions', '=', 'Mock(return_value=[Mock(id=1)])', 'clf_mock', '=', 'Mock(hyperpartition_id=1,', 'cv_judgment_metric=0.5)', 'worker.db.get_classifiers', '=', 'Mock(return_value=[clf_mock])', 'worker.selector.select', '=', 'Mock(return_value=1)', 'hp',... | 402,736 |
equalitie/learn2ban | feature_cycling_user_agent.py | FeatureCyclingUserAgent.compute | compute | retrieve the ip dictionary and compute the average for each ip to determine the change rate of UA per IP. | [
"retrieve",
"the",
"ip",
"dictionary",
"and",
"compute",
"the",
"average",
"for",
"each",
"ip",
"to",
"determine",
"the",
"change",
"rate",
"of",
"UA",
"per",
"IP."
] | def compute(self):
ip_recs = self._ip_sieve.ordered_records()
for cur_ip_rec in ip_recs:
ua_request_map = {}
total_requests = 0
highest_percentage_UA = 0
for payload in ip_recs[cur_ip_rec]:
cur_UA = payload.get_UA()
if cur_UA not in ua_request_map:
... | ['def', 'compute(self):', 'ip_recs', '=', 'self._ip_sieve.ordered_records()', 'for', 'cur_ip_rec', 'in', 'ip_recs:', 'ua_request_map', '=', '{}', 'total_requests', '=', '0', 'highest_percentage_UA', '=', '0', 'for', 'payload', 'in', 'ip_recs[cur_ip_rec]:', 'cur_UA', '=', 'payload.get_UA()', 'if', 'cur_UA', 'not', 'in',... | 587,816 |
googleapis/python-aiplatform | lit.py | _TensorFlowLitModel.output_spec | output_spec | Return a spec describing model outputs. | [
"Return",
"a",
"spec",
"describing",
"model",
"outputs."
] | def output_spec(self) -> lit_types.Spec:
output_spec_dict = dict(self._output_types)
if self.attribution_explainer:
output_spec_dict['feature_attribution'] = lit_types.FeatureSalience(signed=True)
return output_spec_dict | ['def', 'output_spec(self)', '->', 'lit_types.Spec:', 'output_spec_dict', '=', 'dict(self._output_types)', 'if', 'self.attribution_explainer:', "output_spec_dict['feature_attribution']", '=', 'lit_types.FeatureSalience(signed=True)', 'return', 'output_spec_dict'] | 809,901 |
intel/neural-compressor | rerange_quantized_concat.py | RerangeQuantizedConcat.do_transformation | do_transformation | Apply the rerange quantized ConcatV2 transform. | [
"Apply",
"the",
"rerange",
"quantized",
"ConcatV2",
"transform."
] | def do_transformation(self):
for (_, node) in enumerate(self.input_graph.node):
if node.op != 'QuantizedConcatV2':
continue
quantized_conv_nodes = []
can_rerange = self._analyze_concat_node_recursively(quantized_conv_nodes, node)
if not can_rerange:
continue
... | ['def', 'do_transformation(self):', 'for', '(_,', 'node)', 'in', 'enumerate(self.input_graph.node):', 'if', 'node.op', '!=', "'QuantizedConcatV2':", 'continue', 'quantized_conv_nodes', '=', '[]', 'can_rerange', '=', 'self._analyze_concat_node_recursively(quantized_conv_nodes,', 'node)', 'if', 'not', 'can_rerange:', 'co... | 737,852 |
f-dangel/cockpit | utils.py | set_up_problem | set_up_problem | Create DeepOBS problem with neural network, and set to train mode. | [
"Create",
"DeepOBS",
"problem",
"with",
"neural",
"network,",
"and",
"set",
"to",
"train",
"mode."
] | def set_up_problem(tproblem_cls, batch_size=5, seed=None, l2_reg=0.0):
if seed is not None:
set_deepobs_seed(seed)
tproblem = tproblem_cls(batch_size, l2_reg=l2_reg)
tproblem.set_up()
tproblem.train_init_op()
return tproblem | ['def', 'set_up_problem(tproblem_cls,', 'batch_size=5,', 'seed=None,', 'l2_reg=0.0):', 'if', 'seed', 'is', 'not', 'None:', 'set_deepobs_seed(seed)', 'tproblem', '=', 'tproblem_cls(batch_size,', 'l2_reg=l2_reg)', 'tproblem.set_up()', 'tproblem.train_init_op()', 'return', 'tproblem'] | 493,261 |
meidachen/STPLS3D | cindex.py | Cursor.extent | extent | Return the source range (the range of text) occupied by the entity pointed at by the cursor. | [
"Return",
"the",
"source",
"range",
"(the",
"range",
"of",
"text)",
"occupied",
"by",
"the",
"entity",
"pointed",
"at",
"by",
"the",
"cursor."
] | def extent(self):
if not hasattr(self, '_extent'):
self._extent = conf.lib.clang_getCursorExtent(self)
return self._extent | ['def', 'extent(self):', 'if', 'not', 'hasattr(self,', "'_extent'):", 'self._extent', '=', 'conf.lib.clang_getCursorExtent(self)', 'return', 'self._extent'] | 909,140 |
weimin17/Object-Detection_HelmetDetection | dataset.py | get_num_class | get_num_class | Returns an integer for the number of label classes. | [
"Returns",
"an",
"integer",
"for",
"the",
"number",
"of",
"label",
"classes."
] | def get_num_class(dataset):
if dataset == DATASET_IMDB:
return imdb.NUM_CLASS
else:
raise ValueError('unsupported dataset: ' + dataset) | ['def', 'get_num_class(dataset):', 'if', 'dataset', '==', 'DATASET_IMDB:', 'return', 'imdb.NUM_CLASS', 'else:', 'raise', "ValueError('unsupported", 'dataset:', "'", '+', 'dataset)'] | 752,701 |
tangyuhao/DAVIS-2016-Chanllege-Solution | ssd_vgg_512.py | SSDNet.arg_scope_caffe | arg_scope_caffe | Caffe arg_scope used for weights importing. | [
"Caffe",
"arg_scope",
"used",
"for",
"weights",
"importing."
] | def arg_scope_caffe(self, caffe_scope):
return ssd_arg_scope_caffe(caffe_scope) | ['def', 'arg_scope_caffe(self,', 'caffe_scope):', 'return', 'ssd_arg_scope_caffe(caffe_scope)'] | 498,341 |
open-mmlab/mmtracking | base.py | BaseMultiObjectTracker.with_reid | with_reid | bool: whether the framework has a reid model. | [
"bool:",
"whether",
"the",
"framework",
"has",
"a",
"reid",
"model."
] | def with_reid(self):
return hasattr(self, 'reid') and self.reid is not None | ['def', 'with_reid(self):', 'return', 'hasattr(self,', "'reid')", 'and', 'self.reid', 'is', 'not', 'None'] | 625,806 |
benhoyle/patentparser | core.py | Claim.json | json | Provide words as JSON. | [
"Provide",
"words",
"as",
"JSON."
] | def json(self):
words = [{'id': i, 'word': word, 'pos': part, 'np': np} for (i, (word, part, np)) in list(enumerate(self.word_data))]
return {'claim': {'words': words}} | ['def', 'json(self):', 'words', '=', "[{'id':", 'i,', "'word':", 'word,', "'pos':", 'part,', "'np':", 'np}', 'for', '(i,', '(word,', 'part,', 'np))', 'in', 'list(enumerate(self.word_data))]', 'return', "{'claim':", "{'words':", 'words}}'] | 764,417 |
tobegit3hub/deep_image_model | reroute.py | reroute_b2a_outputs | reroute_b2a_outputs | Re-route all the outputs of sgv1 to sgv0 (see _reroute_outputs). | [
"Re-route",
"all",
"the",
"outputs",
"of",
"sgv1",
"to",
"sgv0",
"(see",
"_reroute_outputs)."
] | def reroute_b2a_outputs(sgv0, sgv1):
return _reroute_sgv_outputs(sgv0, sgv1, _RerouteMode.b2a) | ['def', 'reroute_b2a_outputs(sgv0,', 'sgv1):', 'return', '_reroute_sgv_outputs(sgv0,', 'sgv1,', '_RerouteMode.b2a)'] | 181,343 |
KalleHallden/InstaAutomator | watchmedo.py | parse_patterns | parse_patterns | Parses pattern argument specs and returns a two-tuple of (patterns, ignore_patterns). | [
"Parses",
"pattern",
"argument",
"specs",
"and",
"returns",
"a",
"two-tuple",
"of",
"(patterns,",
"ignore_patterns)."
] | def parse_patterns(patterns_spec, ignore_patterns_spec, separator=';'):
patterns = patterns_spec.split(separator)
ignore_patterns = ignore_patterns_spec.split(separator)
if ignore_patterns == ['']:
ignore_patterns = []
return (patterns, ignore_patterns) | ['def', 'parse_patterns(patterns_spec,', 'ignore_patterns_spec,', "separator=';'):", 'patterns', '=', 'patterns_spec.split(separator)', 'ignore_patterns', '=', 'ignore_patterns_spec.split(separator)', 'if', 'ignore_patterns', '==', "['']:", 'ignore_patterns', '=', '[]', 'return', '(patterns,', 'ignore_patterns)'] | 245,079 |
alibaba-mmai-research/HiCo | tal_tools.py | epic_video_post_process | epic_video_post_process | Post processing for part videos in epic dataset. | [
"Post",
"processing",
"for",
"part",
"videos",
"in",
"epic",
"dataset."
] | def epic_video_post_process(cfg, video_list, result_dict, epoch, norm=False):
select_score = cfg.LOCALIZATION.POST_PROCESS.SELECT_SCORE
score_type = cfg.LOCALIZATION.POST_PROCESS.SCORE_TYPE
clr_power = cfg.LOCALIZATION.POST_PROCESS.CLR_POWER
reg_power = cfg.LOCALIZATION.POST_PROCESS.REG_POWER
tca_po... | ['def', 'epic_video_post_process(cfg,', 'video_list,', 'result_dict,', 'epoch,', 'norm=False):', 'select_score', '=', 'cfg.LOCALIZATION.POST_PROCESS.SELECT_SCORE', 'score_type', '=', 'cfg.LOCALIZATION.POST_PROCESS.SCORE_TYPE', 'clr_power', '=', 'cfg.LOCALIZATION.POST_PROCESS.CLR_POWER', 'reg_power', '=', 'cfg.LOCALIZAT... | 206,298 |
wutong8023/CoLL | training_args.py | TrainingArguments.world_size | world_size | The number of processes used in parallel. | [
"The",
"number",
"of",
"processes",
"used",
"in",
"parallel."
] | def world_size(self):
if is_torch_tpu_available():
return xm.xrt_world_size()
elif is_sagemaker_mp_enabled():
return smp.dp_size()
elif is_sagemaker_dp_enabled():
return sm_dist.get_world_size()
elif self.local_rank != -1:
return torch.distributed.get_world_size()
ret... | ['def', 'world_size(self):', 'if', 'is_torch_tpu_available():', 'return', 'xm.xrt_world_size()', 'elif', 'is_sagemaker_mp_enabled():', 'return', 'smp.dp_size()', 'elif', 'is_sagemaker_dp_enabled():', 'return', 'sm_dist.get_world_size()', 'elif', 'self.local_rank', '!=', '-1:', 'return', 'torch.distributed.get_world_siz... | 496,518 |
lhotse-speech/lhotse | serialization.py | LazyMixin.is_lazy | is_lazy | Indicates whether this manifest was opened in lazy (read-on-the-fly) mode or not. | [
"Indicates",
"whether",
"this",
"manifest",
"was",
"opened",
"in",
"lazy",
"(read-on-the-fly)",
"mode",
"or",
"not."
] | def is_lazy(self) -> bool:
return not isinstance(self.data, (dict, list, tuple)) | ['def', 'is_lazy(self)', '->', 'bool:', 'return', 'not', 'isinstance(self.data,', '(dict,', 'list,', 'tuple))'] | 600,416 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | XView.xview | xview | Query and change the horizontal position of the view. | [
"Query",
"and",
"change",
"the",
"horizontal",
"position",
"of",
"the",
"view."
] | def xview(self, *args):
res = self.tk.call(self._w, 'xview', *args)
if not args:
return self._getdoubles(res) | ['def', 'xview(self,', '*args):', 'res', '=', 'self.tk.call(self._w,', "'xview',", '*args)', 'if', 'not', 'args:', 'return', 'self._getdoubles(res)'] | 376,877 |
explosion/spaCy | test_matcher_logic.py | test_issue2569 | test_issue2569 | Test that operator + is greedy. | [
"Test",
"that",
"operator",
"+",
"is",
"greedy."
] | def test_issue2569(en_tokenizer):
doc = en_tokenizer('It is May 15, 1993.')
doc.ents = [Span(doc, 2, 6, label=doc.vocab.strings['DATE'])]
matcher = Matcher(doc.vocab)
matcher.add('RULE', [[{'ENT_TYPE': 'DATE', 'OP': '+'}]])
matched = [doc[start:end] for (_, start, end) in matcher(doc)]
matched =... | ['def', 'test_issue2569(en_tokenizer):', 'doc', '=', "en_tokenizer('It", 'is', 'May', '15,', "1993.')", 'doc.ents', '=', '[Span(doc,', '2,', '6,', "label=doc.vocab.strings['DATE'])]", 'matcher', '=', 'Matcher(doc.vocab)', "matcher.add('RULE',", "[[{'ENT_TYPE':", "'DATE',", "'OP':", "'+'}]])", 'matched', '=', '[doc[star... | 894,214 |
Ruturaj123/Flowchart-Detection | pooling_ops_test.py | NCHWToNHWC | NCHWToNHWC | Convert the input from NCHW format to NHWC. | [
"Convert",
"the",
"input",
"from",
"NCHW",
"format",
"to",
"NHWC."
] | def NCHWToNHWC(input_tensor):
if isinstance(input_tensor, ops.Tensor):
return array_ops.transpose(input_tensor, [0, 2, 3, 1])
else:
return [input_tensor[0], input_tensor[2], input_tensor[3], input_tensor[1]] | ['def', 'NCHWToNHWC(input_tensor):', 'if', 'isinstance(input_tensor,', 'ops.Tensor):', 'return', 'array_ops.transpose(input_tensor,', '[0,', '2,', '3,', '1])', 'else:', 'return', '[input_tensor[0],', 'input_tensor[2],', 'input_tensor[3],', 'input_tensor[1]]'] | 586,789 |
43Carrig/recurrent_neural_networks_practice | well_known_types.py | Timestamp.ToDatetime | ToDatetime | Converts Timestamp to datetime. | [
"Converts",
"Timestamp",
"to",
"datetime."
] | def ToDatetime(self):
return datetime.utcfromtimestamp(self.seconds + self.nanos / float(_NANOS_PER_SECOND)) | ['def', 'ToDatetime(self):', 'return', 'datetime.utcfromtimestamp(self.seconds', '+', 'self.nanos', '/', 'float(_NANOS_PER_SECOND))'] | 310,007 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.