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 |
|---|---|---|---|---|---|---|---|---|
KalleHallden/InstaAutomator | _tifffile.py | askopenfilename | askopenfilename | Return file name(s) from Tkinter's file open dialog. | [
"Return",
"file",
"name(s)",
"from",
"Tkinter's",
"file",
"open",
"dialog."
] | def askopenfilename(**kwargs):
try:
from Tkinter import Tk
import tkFileDialog as filedialog
except ImportError:
from tkinter import Tk, filedialog
root = Tk()
root.withdraw()
root.update()
filenames = filedialog.askopenfilename(**kwargs)
root.destroy()
return fil... | ['def', 'askopenfilename(**kwargs):', 'try:', 'from', 'Tkinter', 'import', 'Tk', 'import', 'tkFileDialog', 'as', 'filedialog', 'except', 'ImportError:', 'from', 'tkinter', 'import', 'Tk,', 'filedialog', 'root', '=', 'Tk()', 'root.withdraw()', 'root.update()', 'filenames', '=', 'filedialog.askopenfilename(**kwargs)', 'r... | 242,541 |
hankcs/HanLP | ontonotes_loader.py | Ontonotes.dataset_iterator | dataset_iterator | An iterator over the entire dataset, yielding all sentences processed. | [
"An",
"iterator",
"over",
"the",
"entire",
"dataset,",
"yielding",
"all",
"sentences",
"processed."
] | def dataset_iterator(self, file_path: str) -> Iterator[OntonotesSentence]:
for conll_file in self.dataset_path_iterator(file_path):
yield from self.sentence_iterator(conll_file) | ['def', 'dataset_iterator(self,', 'file_path:', 'str)', '->', 'Iterator[OntonotesSentence]:', 'for', 'conll_file', 'in', 'self.dataset_path_iterator(file_path):', 'yield', 'from', 'self.sentence_iterator(conll_file)'] | 575,820 |
OpenLake/Smart-Cams | recorder.py | start_all_threads | start_all_threads | Starts the threads of list of camera objects passed. | [
"Starts",
"the",
"threads",
"of",
"list",
"of",
"camera",
"objects",
"passed."
] | def start_all_threads(list_of_cams):
for th in list_of_cams:
th.cam_thread.start() | ['def', 'start_all_threads(list_of_cams):', 'for', 'th', 'in', 'list_of_cams:', 'th.cam_thread.start()'] | 878,573 |
flavioschneider/rl-transfer- | dqn_atari.py | dqn_atari | dqn_atari | Train DQN with PongNoFrameskip-v4 environment. | [
"Train",
"DQN",
"with",
"PongNoFrameskip-v4",
"environment."
] | def dqn_atari(ctxt=None, env=None, seed=24, n_workers=psutil.cpu_count(logical=False), max_episode_length=None, **kwargs):
assert n_workers > 0
assert env is not None
env = gym.make(env)
env = Noop(env, noop_max=30)
env = MaxAndSkip(env, skip=4)
env = EpisodicLife(env)
if 'FIRE' in env.unwra... | ['def', 'dqn_atari(ctxt=None,', 'env=None,', 'seed=24,', 'n_workers=psutil.cpu_count(logical=False),', 'max_episode_length=None,', '**kwargs):', 'assert', 'n_workers', '>', '0', 'assert', 'env', 'is', 'not', 'None', 'env', '=', 'gym.make(env)', 'env', '=', 'Noop(env,', 'noop_max=30)', 'env', '=', 'MaxAndSkip(env,', 'sk... | 861,120 |
gunthercox/ChatterBot | mapper.py | Mapper.add_properties | add_properties | Add the given dictionary of properties to this mapper, using `add_property`. | [
"Add",
"the",
"given",
"dictionary",
"of",
"properties",
"to",
"this",
"mapper,",
"using",
"`add_property`."
] | def add_properties(self, dict_of_properties):
for (key, value) in dict_of_properties.iteritems():
self.add_property(key, value) | ['def', 'add_properties(self,', 'dict_of_properties):', 'for', '(key,', 'value)', 'in', 'dict_of_properties.iteritems():', 'self.add_property(key,', 'value)'] | 481,402 |
google/deepvariant | call_variants.py | round_gls | round_gls | Returns genotype likelihoods rounded to the desired precision level. | [
"Returns",
"genotype",
"likelihoods",
"rounded",
"to",
"the",
"desired",
"precision",
"level."
] | def round_gls(gls, precision=None):
if abs(sum(gls) - 1) > 1e-06:
raise ValueError('Invalid genotype likelihoods do not sum to one: sum({}) = {}'.format(gls, sum(gls)))
if precision is None:
return gls
min_ix = 0
min_gl = gls[0]
for (ix, gl) in enumerate(gls):
if gl < min_gl:... | ['def', 'round_gls(gls,', 'precision=None):', 'if', 'abs(sum(gls)', '-', '1)', '>', '1e-06:', 'raise', "ValueError('Invalid", 'genotype', 'likelihoods', 'do', 'not', 'sum', 'to', 'one:', 'sum({})', '=', "{}'.format(gls,", 'sum(gls)))', 'if', 'precision', 'is', 'None:', 'return', 'gls', 'min_ix', '=', '0', 'min_gl', '='... | 540,244 |
ziberna/i3-py | wsbar.py | Colors.get_color | get_color | Returns a (foreground, background) tuple based on given workspace state. | [
"Returns",
"a",
"(foreground,",
"background)",
"tuple",
"based",
"on",
"given",
"workspace",
"state."
] | def get_color(self, workspace, output):
if workspace['focused']:
if output['current_workspace'] == workspace['name']:
return self.focused
else:
return self.active
if workspace['urgent']:
return self.urgent
else:
return self.inactive | ['def', 'get_color(self,', 'workspace,', 'output):', 'if', "workspace['focused']:", 'if', "output['current_workspace']", '==', "workspace['name']:", 'return', 'self.focused', 'else:', 'return', 'self.active', 'if', "workspace['urgent']:", 'return', 'self.urgent', 'else:', 'return', 'self.inactive'] | 228,212 |
HKU-BAL/Clair | selu.py | dropout_selu | dropout_selu | Dropout to a value with rescaling. | [
"Dropout",
"to",
"a",
"value",
"with",
"rescaling."
] | def dropout_selu(x, rate, alpha=-1.7580993408473766, fixedPointMean=0.0, fixedPointVar=1.0, noise_shape=None, seed=None, name=None, training=False):
def dropout_selu_impl(x, rate, alpha, noise_shape, seed, name):
keep_prob = 1.0 - rate
x = ops.convert_to_tensor(x, name='x')
if isinstance(ke... | ['def', 'dropout_selu(x,', 'rate,', 'alpha=-1.7580993408473766,', 'fixedPointMean=0.0,', 'fixedPointVar=1.0,', 'noise_shape=None,', 'seed=None,', 'name=None,', 'training=False):', 'def', 'dropout_selu_impl(x,', 'rate,', 'alpha,', 'noise_shape,', 'seed,', 'name):', 'keep_prob', '=', '1.0', '-', 'rate', 'x', '=', 'ops.co... | 487,910 |
apeterswu/RL4NMT | cipher.py | encipher_vigenere | encipher_vigenere | Encrypt plain text with given key. | [
"Encrypt",
"plain",
"text",
"with",
"given",
"key."
] | def encipher_vigenere(plaintext, plain_vocab, key):
ciphertext = []
layers = []
for i in range(len(plain_vocab)):
layers.append(ShiftEncryptionLayer(plain_vocab, i))
for (i, sentence) in enumerate(plaintext):
cipher_sentence = []
for (j, character) in enumerate(sentence):
... | ['def', 'encipher_vigenere(plaintext,', 'plain_vocab,', 'key):', 'ciphertext', '=', '[]', 'layers', '=', '[]', 'for', 'i', 'in', 'range(len(plain_vocab)):', 'layers.append(ShiftEncryptionLayer(plain_vocab,', 'i))', 'for', '(i,', 'sentence)', 'in', 'enumerate(plaintext):', 'cipher_sentence', '=', '[]', 'for', '(j,', 'ch... | 330,877 |
gunthercox/ChatterBot | visitors.py | traverse_using | traverse_using | visit the given expression structure using the given iterator of objects. | [
"visit",
"the",
"given",
"expression",
"structure",
"using",
"the",
"given",
"iterator",
"of",
"objects."
] | def traverse_using(iterator, obj, visitors):
for target in iterator:
meth = visitors.get(target.__visit_name__, None)
if meth:
meth(target)
return obj | ['def', 'traverse_using(iterator,', 'obj,', 'visitors):', 'for', 'target', 'in', 'iterator:', 'meth', '=', 'visitors.get(target.__visit_name__,', 'None)', 'if', 'meth:', 'meth(target)', 'return', 'obj'] | 535,129 |
google/deluca | breath_dataset.py | get_shuffled_and_batched_data | get_shuffled_and_batched_data | function to shuffle and batch data. | [
"function",
"to",
"shuffle",
"and",
"batch",
"data."
] | def get_shuffled_and_batched_data(dataset, batch_size, key, prng_key):
(x, y) = dataset.data[key]
x = jax.random.permutation(prng_key, x)
y = jax.random.permutation(prng_key, y)
(prng_key, _) = jax.random.split(prng_key)
num_batches = x.shape[0] // batch_size
trunc_len = num_batches * batch_size... | ['def', 'get_shuffled_and_batched_data(dataset,', 'batch_size,', 'key,', 'prng_key):', '(x,', 'y)', '=', 'dataset.data[key]', 'x', '=', 'jax.random.permutation(prng_key,', 'x)', 'y', '=', 'jax.random.permutation(prng_key,', 'y)', '(prng_key,', '_)', '=', 'jax.random.split(prng_key)', 'num_batches', '=', 'x.shape[0]', '... | 537,931 |
f-dangel/cockpit | test_utils_hists.py | test_histogramdd | test_histogramdd | Compare ``torch`` and ``numpy`` histogram function (d=2). | [
"Compare",
"``torch``",
"and",
"``numpy``",
"histogram",
"function",
"(d=2)."
] | def test_histogramdd(device):
torch.manual_seed(0)
N = 1000
bins = 20
x_data = torch.rand(N, device=device)
y_data = torch.rand(N, device=device)
epsilon = 1e-06
x_edges = torch.linspace(x_data.min() - epsilon, x_data.max() + epsilon, steps=bins + 1, device=device)
y_edges = torch.linspa... | ['def', 'test_histogramdd(device):', 'torch.manual_seed(0)', 'N', '=', '1000', 'bins', '=', '20', 'x_data', '=', 'torch.rand(N,', 'device=device)', 'y_data', '=', 'torch.rand(N,', 'device=device)', 'epsilon', '=', '1e-06', 'x_edges', '=', 'torch.linspace(x_data.min()', '-', 'epsilon,', 'x_data.max()', '+', 'epsilon,', ... | 493,343 |
hans/pyccg | logic.py | Ontology.infer_type | infer_type | Infer the type of a bound variable with name `variable_name` used in `expr`. | [
"Infer",
"the",
"type",
"of",
"a",
"bound",
"variable",
"with",
"name",
"`variable_name`",
"used",
"in",
"`expr`."
] | def infer_type(self, expr, variable_name, extra_types=None):
apparent_types = set()
extra_types = extra_types or {}
def visitor(node):
if isinstance(node, ApplicationExpression):
fn_name = node.pred.variable.name
if fn_name == variable_name:
arg_types = []
... | ['def', 'infer_type(self,', 'expr,', 'variable_name,', 'extra_types=None):', 'apparent_types', '=', 'set()', 'extra_types', '=', 'extra_types', 'or', '{}', 'def', 'visitor(node):', 'if', 'isinstance(node,', 'ApplicationExpression):', 'fn_name', '=', 'node.pred.variable.name', 'if', 'fn_name', '==', 'variable_name:', 'a... | 296,002 |
scikit-learn/scikit-learn | test_metadata_routing.py | test_estimator_puts_self_in_registry | test_estimator_puts_self_in_registry | Check that an estimator puts itself in the registry upon fit. | [
"Check",
"that",
"an",
"estimator",
"puts",
"itself",
"in",
"the",
"registry",
"upon",
"fit."
] | def test_estimator_puts_self_in_registry(estimator):
estimator.fit(X, y)
assert estimator in estimator.registry | ['def', 'test_estimator_puts_self_in_registry(estimator):', 'estimator.fit(X,', 'y)', 'assert', 'estimator', 'in', 'estimator.registry'] | 854,169 |
open-mmlab/mmdetection3d | dfm.py | DfM.with_neck_2d | with_neck_2d | Whether the detector has a 2D neck. | [
"Whether",
"the",
"detector",
"has",
"a",
"2D",
"neck."
] | def with_neck_2d(self):
return hasattr(self, 'neck_2d') and self.neck_2d is not None | ['def', 'with_neck_2d(self):', 'return', 'hasattr(self,', "'neck_2d')", 'and', 'self.neck_2d', 'is', 'not', 'None'] | 631,963 |
Ruturaj123/Flowchart-Detection | negative_binomial.py | NegativeBinomial.total_count | total_count | Number of negative trials. | [
"Number",
"of",
"negative",
"trials."
] | def total_count(self):
return self._total_count | ['def', 'total_count(self):', 'return', 'self._total_count'] | 602,907 |
QData/deepWordBug | math2html.py | TaggedBit.selfcomplete | selfcomplete | Set the self-closing tag, no contents (as in <hr/>). | [
"Set",
"the",
"self-closing",
"tag,",
"no",
"contents",
"(as",
"in",
"<hr/>)."
] | def selfcomplete(self, tag):
self.output = TaggedOutput().settag(tag, empty=True)
return self | ['def', 'selfcomplete(self,', 'tag):', 'self.output', '=', 'TaggedOutput().settag(tag,', 'empty=True)', 'return', 'self'] | 542,456 |
val-iisc/deligan | params.py | write_model_data | write_model_data | Pickels the parameters within a Lasagne model. | [
"Pickels",
"the",
"parameters",
"within",
"a",
"Lasagne",
"model."
] | def write_model_data(model, filename):
data = nn.layers.get_all_param_values(model)
filename = os.path.join('./', filename)
filename = '%s.%s' % (filename, PARAM_EXTENSION)
with open(filename, 'w') as f:
pickle.dump(data, f) | ['def', 'write_model_data(model,', 'filename):', 'data', '=', 'nn.layers.get_all_param_values(model)', 'filename', '=', "os.path.join('./',", 'filename)', 'filename', '=', "'%s.%s'", '%', '(filename,', 'PARAM_EXTENSION)', 'with', 'open(filename,', "'w')", 'as', 'f:', 'pickle.dump(data,', 'f)'] | 537,020 |
guenthermi/table-embeddings | annotation_parser.py | AnnotationParser.get_annotaions_for_all_files | get_annotaions_for_all_files | Returns annotations of all spreadsheet files in the annotation file. | [
"Returns",
"annotations",
"of",
"all",
"spreadsheet",
"files",
"in",
"the",
"annotation",
"file."
] | def get_annotaions_for_all_files(self):
result = dict()
file_name_groups = self.data.groupby('FileName')
for (i, file_name) in enumerate(file_name_groups.groups):
result[file_name] = dict()
df_file = file_name_groups.get_group(file_name)
sheet_name_groups = df_file.groupby('SheetName... | ['def', 'get_annotaions_for_all_files(self):', 'result', '=', 'dict()', 'file_name_groups', '=', "self.data.groupby('FileName')", 'for', '(i,', 'file_name)', 'in', 'enumerate(file_name_groups.groups):', 'result[file_name]', '=', 'dict()', 'df_file', '=', 'file_name_groups.get_group(file_name)', 'sheet_name_groups', '='... | 365,110 |
rifqind/Agent-Programs-3KS1 | test_nbconvertapp.py | TestNbConvertApp.test_convert_full_qualified_name | test_convert_full_qualified_name | Test that nbconvert can convert file using a full qualified name for a package, import and use it. | [
"Test",
"that",
"nbconvert",
"can",
"convert",
"file",
"using",
"a",
"full",
"qualified",
"name",
"for",
"a",
"package,",
"import",
"and",
"use",
"it."
] | def test_convert_full_qualified_name(self):
with self.create_temp_cwd():
self.copy_files_to(['notebook*.ipynb'], 'subdir')
self.nbconvert('--to nbconvert.tests.fake_exporters.MyExporter --log-level 0 ' + os.path.join('subdir', '*.ipynb'))
assert os.path.isfile(os.path.join('subdir', 'noteboo... | ['def', 'test_convert_full_qualified_name(self):', 'with', 'self.create_temp_cwd():', "self.copy_files_to(['notebook*.ipynb'],", "'subdir')", "self.nbconvert('--to", 'nbconvert.tests.fake_exporters.MyExporter', '--log-level', '0', "'", '+', "os.path.join('subdir',", "'*.ipynb'))", 'assert', "os.path.isfile(os.path.join... | 42,853 |
fudan-zvg/DeepInteraction | create_data.py | s3dis_data_prep | s3dis_data_prep | Prepare the info file for s3dis dataset. | [
"Prepare",
"the",
"info",
"file",
"for",
"s3dis",
"dataset."
] | def s3dis_data_prep(root_path, info_prefix, out_dir, workers):
indoor.create_indoor_info_file(root_path, info_prefix, out_dir, workers=workers) | ['def', 's3dis_data_prep(root_path,', 'info_prefix,', 'out_dir,', 'workers):', 'indoor.create_indoor_info_file(root_path,', 'info_prefix,', 'out_dir,', 'workers=workers)'] | 521,185 |
wuga214/Boundary-Detection-via-Convolution-Deconvolution--Network-with-BMA | tensorflow_backend.py | temporal_padding | temporal_padding | Pad the middle dimension of a 3D tensor with "padding" zeros left and right. | [
"Pad",
"the",
"middle",
"dimension",
"of",
"a",
"3D",
"tensor",
"with",
"\"padding\"",
"zeros",
"left",
"and",
"right."
] | def temporal_padding(x, padding=1):
pattern = [[0, 0], [padding, padding], [0, 0]]
return tf.pad(x, pattern) | ['def', 'temporal_padding(x,', 'padding=1):', 'pattern', '=', '[[0,', '0],', '[padding,', 'padding],', '[0,', '0]]', 'return', 'tf.pad(x,', 'pattern)'] | 107,910 |
PaddlePaddle/Paddle3D | create_bevformer_nus_infos.py | fill_trainval_infos | fill_trainval_infos | Generate the train/val infos from the raw data. | [
"Generate",
"the",
"train/val",
"infos",
"from",
"the",
"raw",
"data."
] | def fill_trainval_infos(nusc, nusc_can_bus, train_scenes, val_scenes, test=False, max_sweeps=10):
train_nusc_infos = []
val_nusc_infos = []
frame_idx = 0
msg = 'Begin to generate a info of nuScenes dataset.'
for sample_idx in logger.range(len(nusc.sample), msg=msg):
sample = nusc.sample[samp... | ['def', 'fill_trainval_infos(nusc,', 'nusc_can_bus,', 'train_scenes,', 'val_scenes,', 'test=False,', 'max_sweeps=10):', 'train_nusc_infos', '=', '[]', 'val_nusc_infos', '=', '[]', 'frame_idx', '=', '0', 'msg', '=', "'Begin", 'to', 'generate', 'a', 'info', 'of', 'nuScenes', "dataset.'", 'for', 'sample_idx', 'in', 'logge... | 778,112 |
tensorly/quantum | rotosolve_minimizer.py | RotosolveOptimizerResults.to_dict | to_dict | Transforms immutable data to mutable dictionary. | [
"Transforms",
"immutable",
"data",
"to",
"mutable",
"dictionary."
] | def to_dict(self):
return {'converged': self.converged, 'num_iterations': self.num_iterations, 'num_objective_evaluations': self.num_objective_evaluations, 'position': self.position, 'objective_value': self.objective_value, 'objective_value_prev': self.objective_value_prev, 'tolerance': self.tolerance, 'solve_param... | ['def', 'to_dict(self):', 'return', "{'converged':", 'self.converged,', "'num_iterations':", 'self.num_iterations,', "'num_objective_evaluations':", 'self.num_objective_evaluations,', "'position':", 'self.position,', "'objective_value':", 'self.objective_value,', "'objective_value_prev':", 'self.objective_value_prev,',... | 835,455 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nested_utils.py | tile_tensors | tile_tensors | Tiles a set of Tensors. | [
"Tiles",
"a",
"set",
"of",
"Tensors."
] | def tile_tensors(tensors, multiples):
def tile_fn(x):
return tf.tile(x, multiples + [1] * (x.shape.ndims - len(multiples)))
return map_nested(tile_fn, tensors) | ['def', 'tile_tensors(tensors,', 'multiples):', 'def', 'tile_fn(x):', 'return', 'tf.tile(x,', 'multiples', '+', '[1]', '*', '(x.shape.ndims', '-', 'len(multiples)))', 'return', 'map_nested(tile_fn,', 'tensors)'] | 48,380 |
FedML-AI/FedML | efficientnet.py | EfficientNet.set_swish | set_swish | Sets swish function as memory efficient (for training) or standard (for export). | [
"Sets",
"swish",
"function",
"as",
"memory",
"efficient",
"(for",
"training)",
"or",
"standard",
"(for",
"export)."
] | def set_swish(self, memory_efficient=True):
self._swish = MemoryEfficientSwish() if memory_efficient else Swish()
for block in self._blocks:
block.set_swish(memory_efficient) | ['def', 'set_swish(self,', 'memory_efficient=True):', 'self._swish', '=', 'MemoryEfficientSwish()', 'if', 'memory_efficient', 'else', 'Swish()', 'for', 'block', 'in', 'self._blocks:', 'block.set_swish(memory_efficient)'] | 545,314 |
nhsx/SynthVAE | stats.py | remove | remove | Removes the Stat of name ``name`` from the global statistics gathering. | [
"Removes",
"the",
"Stat",
"of",
"name",
"``name``",
"from",
"the",
"global",
"statistics",
"gathering."
] | def remove(name: str):
global Stats
Stats = [stat for stat in Stats if stat.name != name] | ['def', 'remove(name:', 'str):', 'global', 'Stats', 'Stats', '=', '[stat', 'for', 'stat', 'in', 'Stats', 'if', 'stat.name', '!=', 'name]'] | 906,257 |
open-mmlab/mmselfsup | simmim.py | SimMIM.reconstruct | reconstruct | The function is for image reconstruction. | [
"The",
"function",
"is",
"for",
"image",
"reconstruction."
] | def reconstruct(self, features: torch.Tensor, data_samples: Optional[List[SelfSupDataSample]]=None, **kwargs) -> SelfSupDataSample:
pred = torch.einsum('nchw->nhwc', features).detach().cpu()
mask = self.mask.detach()
p1 = int(self.backbone.patch_embed.init_input_size[0] // self.backbone.patch_resolution[0])... | ['def', 'reconstruct(self,', 'features:', 'torch.Tensor,', 'data_samples:', 'Optional[List[SelfSupDataSample]]=None,', '**kwargs)', '->', 'SelfSupDataSample:', 'pred', '=', "torch.einsum('nchw->nhwc',", 'features).detach().cpu()', 'mask', '=', 'self.mask.detach()', 'p1', '=', 'int(self.backbone.patch_embed.init_input_s... | 240,395 |
sktime/sktime | test_mlflow_sktime_model_export.py | test_signature_and_examples_saved_correctly | test_signature_and_examples_saved_correctly | Test saving of mlflow signature and example for native sktime predict method. | [
"Test",
"saving",
"of",
"mlflow",
"signature",
"and",
"example",
"for",
"native",
"sktime",
"predict",
"method."
] | def test_signature_and_examples_saved_correctly(auto_arima_model, test_data_airline, model_path, use_signature, use_example):
from mlflow.models import Model, infer_signature
from mlflow.models.utils import _read_example
from sktime.utils import mlflow_sktime
prediction = auto_arima_model.predict()
... | ['def', 'test_signature_and_examples_saved_correctly(auto_arima_model,', 'test_data_airline,', 'model_path,', 'use_signature,', 'use_example):', 'from', 'mlflow.models', 'import', 'Model,', 'infer_signature', 'from', 'mlflow.models.utils', 'import', '_read_example', 'from', 'sktime.utils', 'import', 'mlflow_sktime', 'p... | 878,058 |
arnomoonens/yarll | async_knowledge_transfer.py | AsyncKnowledgeTransfer.signal_handler | signal_handler | When a (SIGINT) signal is received, request the threads (via the master) to stop after completing an iteration. | [
"When",
"a",
"(SIGINT)",
"signal",
"is",
"received,",
"request",
"the",
"threads",
"(via",
"the",
"master)",
"to",
"stop",
"after",
"completing",
"an",
"iteration."
] | def signal_handler(self, signal, frame):
logging.info('SIGINT signal received: Requesting a stop...')
self.stop_requested = True | ['def', 'signal_handler(self,', 'signal,', 'frame):', "logging.info('SIGINT", 'signal', 'received:', 'Requesting', 'a', "stop...')", 'self.stop_requested', '=', 'True'] | 374,668 |
voxel51/fiftyone | collections.py | SampleCollection.get_field_schema | get_field_schema | Returns a schema dictionary describing the fields of the samples in the collection. | [
"Returns",
"a",
"schema",
"dictionary",
"describing",
"the",
"fields",
"of",
"the",
"samples",
"in",
"the",
"collection."
] | def get_field_schema(self, ftype=None, embedded_doc_type=None, include_private=False, flat=False):
raise NotImplementedError('Subclass must implement get_field_schema()') | ['def', 'get_field_schema(self,', 'ftype=None,', 'embedded_doc_type=None,', 'include_private=False,', 'flat=False):', 'raise', "NotImplementedError('Subclass", 'must', 'implement', "get_field_schema()')"] | 582,748 |
MRSRL/complex-networks-release | tf_util.py | fftc | fftc | Centered FFT on second to last dimension. | [
"Centered",
"FFT",
"on",
"second",
"to",
"last",
"dimension."
] | def fftc(im, name='fftc', do_orthonorm=True):
with tf.name_scope(name):
im_out = im
if do_orthonorm:
fftscale = tf.sqrt(1.0 * im_out.get_shape().as_list()[-2])
else:
fftscale = 1.0
fftscale = tf.cast(fftscale, dtype=tf.complex64)
if len(im.get_shape())... | ['def', 'fftc(im,', "name='fftc',", 'do_orthonorm=True):', 'with', 'tf.name_scope(name):', 'im_out', '=', 'im', 'if', 'do_orthonorm:', 'fftscale', '=', 'tf.sqrt(1.0', '*', 'im_out.get_shape().as_list()[-2])', 'else:', 'fftscale', '=', '1.0', 'fftscale', '=', 'tf.cast(fftscale,', 'dtype=tf.complex64)', 'if', 'len(im.get... | 467,278 |
RasaHQ/rasa | nlu_training_data_provider.py | NLUTrainingDataProvider.get_default_config | get_default_config | Returns the default config for NLU training data provider. | [
"Returns",
"the",
"default",
"config",
"for",
"NLU",
"training",
"data",
"provider."
] | def get_default_config(cls) -> Dict[Text, Any]:
return {'persist': False, 'language': None} | ['def', 'get_default_config(cls)', '->', 'Dict[Text,', 'Any]:', 'return', "{'persist':", 'False,', "'language':", 'None}'] | 837,074 |
mattgolub/recurrent-whisperer | AdaptiveGradNormClip.py | AdaptiveGradNormClip.restore | restore | Loads a previously saved AdaptiveGradNormClip state, enabling seamless restoration of gradient descent training procedure. | [
"Loads",
"a",
"previously",
"saved",
"AdaptiveGradNormClip",
"state,",
"enabling",
"seamless",
"restoration",
"of",
"gradient",
"descent",
"training",
"procedure."
] | def restore(self, restore_dir):
if self.verbose:
print('Restoring AdaptiveGradNormClip.')
restore_path = os.path.join(restore_dir, self.save_filename)
file = open(restore_path, 'rb')
restore_data = file.read()
file.close()
self.__dict__ = pickle.loads(restore_data) | ['def', 'restore(self,', 'restore_dir):', 'if', 'self.verbose:', "print('Restoring", "AdaptiveGradNormClip.')", 'restore_path', '=', 'os.path.join(restore_dir,', 'self.save_filename)', 'file', '=', 'open(restore_path,', "'rb')", 'restore_data', '=', 'file.read()', 'file.close()', 'self.__dict__', '=', 'pickle.loads(res... | 309,436 |
mj-will/nessai | test_base_sampler.py | test_checkpoint_time | test_checkpoint_time | Test checkpointing method based on time interval Make sure a file is produced and that the sampling time is updated. | [
"Test",
"checkpointing",
"method",
"based",
"on",
"time",
"interval",
"Make",
"sure",
"a",
"file",
"is",
"produced",
"and",
"that",
"the",
"sampling",
"time",
"is",
"updated."
] | def test_checkpoint_time(sampler, wait):
now = datetime.datetime.now()
sampler.checkpoint_iterations = [10]
sampler.checkpoint_on_iteration = False
sampler.checkpoint_interval = 15 * 60
sampler.sampling_start_time = now - datetime.timedelta(minutes=32)
sampler._last_checkpoint = now - datetime.t... | ['def', 'test_checkpoint_time(sampler,', 'wait):', 'now', '=', 'datetime.datetime.now()', 'sampler.checkpoint_iterations', '=', '[10]', 'sampler.checkpoint_on_iteration', '=', 'False', 'sampler.checkpoint_interval', '=', '15', '*', '60', 'sampler.sampling_start_time', '=', 'now', '-', 'datetime.timedelta(minutes=32)', ... | 292,937 |
zedom1/nlp | rc_model.py | RCModel.evaluate | evaluate | Processes and evaluates the inferred result. | [
"Processes",
"and",
"evaluates",
"the",
"inferred",
"result."
] | def evaluate(self, infer_file, ret=None, from_file=False):
def _merge_and_normalize(obj_list):
ret = {}
for obj in obj_list:
normalized = {k: normalize(v) for (k, v) in obj.items()}
ret.update(normalized)
return ret
pred_list = []
ref_list = []
objs = []
... | ['def', 'evaluate(self,', 'infer_file,', 'ret=None,', 'from_file=False):', 'def', '_merge_and_normalize(obj_list):', 'ret', '=', '{}', 'for', 'obj', 'in', 'obj_list:', 'normalized', '=', '{k:', 'normalize(v)', 'for', '(k,', 'v)', 'in', 'obj.items()}', 'ret.update(normalized)', 'return', 'ret', 'pred_list', '=', '[]', '... | 808,578 |
sek788432/Waymo-2D-Object-Detection | base_layers.py | BaseLayer.add_qweight | add_qweight | Return a quantized weight variable for the given shape. | [
"Return",
"a",
"quantized",
"weight",
"variable",
"for",
"the",
"given",
"shape."
] | def add_qweight(self, shape, num_bits=8):
if self.parameters.initializer is not None:
initializer = self.parameters.initializer
else:
initializer = tf.keras.initializers.GlorotUniform()
weight = self.add_weight('weight', shape, initializer=initializer, trainable=True)
self.add_reg_loss(w... | ['def', 'add_qweight(self,', 'shape,', 'num_bits=8):', 'if', 'self.parameters.initializer', 'is', 'not', 'None:', 'initializer', '=', 'self.parameters.initializer', 'else:', 'initializer', '=', 'tf.keras.initializers.GlorotUniform()', 'weight', '=', "self.add_weight('weight',", 'shape,', 'initializer=initializer,', 'tr... | 975,693 |
google-research/scenic | vivit.py | ViViT.add_modality_token | add_modality_token | Add modality learned tokens. | [
"Add",
"modality",
"learned",
"tokens."
] | def add_modality_token(self, x_tokens: jnp.ndarray, name: str='Encoder') -> jnp.ndarray:
if not self.use_modality_tokens:
return x_tokens
modality_token = self.param(f'{name}_modality_token_{self.modality}', nn.initializers.zeros, (1, 1, x_tokens.shape[-1]))
x_tokens = x_tokens + modality_token
... | ['def', 'add_modality_token(self,', 'x_tokens:', 'jnp.ndarray,', 'name:', "str='Encoder')", '->', 'jnp.ndarray:', 'if', 'not', 'self.use_modality_tokens:', 'return', 'x_tokens', 'modality_token', '=', "self.param(f'{name}_modality_token_{self.modality}',", 'nn.initializers.zeros,', '(1,', '1,', 'x_tokens.shape[-1]))', ... | 846,456 |
hoangminhle/hierarchical_IL_RL | mdp_obstacles.py | MazeMDP.go | go | Return the state that results from going in this direction. | [
"Return",
"the",
"state",
"that",
"results",
"from",
"going",
"in",
"this",
"direction."
] | def go(self, state, direction):
state1 = vector_add(state, direction)
return if_(state1 in self.states, state1, state) | ['def', 'go(self,', 'state,', 'direction):', 'state1', '=', 'vector_add(state,', 'direction)', 'return', 'if_(state1', 'in', 'self.states,', 'state1,', 'state)'] | 206,424 |
google-research/scenic | pretrain_utils.py | restore_model | restore_model | Restore model definition, weights and config from a checkpoint path. | [
"Restore",
"model",
"definition,",
"weights",
"and",
"config",
"from",
"a",
"checkpoint",
"path."
] | def restore_model(config: ml_collections.ConfigDict, ckpt_path: str):
rng = jax.random.PRNGKey(0)
model_cls = scenic_model.get_model_cls(config.model_name)
(data_rng, rng) = jax.random.split(rng)
dataset = train_utils.get_dataset(config, data_rng)
train_state = pretrain_utils.restore_pretrained_chec... | ['def', 'restore_model(config:', 'ml_collections.ConfigDict,', 'ckpt_path:', 'str):', 'rng', '=', 'jax.random.PRNGKey(0)', 'model_cls', '=', 'scenic_model.get_model_cls(config.model_name)', '(data_rng,', 'rng)', '=', 'jax.random.split(rng)', 'dataset', '=', 'train_utils.get_dataset(config,', 'data_rng)', 'train_state',... | 846,763 |
facebookresearch/fvcore | test_focal_loss.py | TestFocalLossStar.test_easy_ex_focal_loss_star_less_than_ce_loss | test_easy_ex_focal_loss_star_less_than_ce_loss | With gamma = 3 loss of easy examples is downweighted. | [
"With",
"gamma",
"=",
"3",
"loss",
"of",
"easy",
"examples",
"is",
"downweighted."
] | def test_easy_ex_focal_loss_star_less_than_ce_loss(self) -> None:
inputs = logit(torch.tensor([0.75, 0.8, 0.12, 0.05], dtype=torch.float32))
targets = torch.tensor([1, 1, 0, 0], dtype=torch.float32)
focal_loss_star = sigmoid_focal_loss_star(inputs, targets, gamma=3, alpha=-1)
ce_loss = F.binary_cross_en... | ['def', 'test_easy_ex_focal_loss_star_less_than_ce_loss(self)', '->', 'None:', 'inputs', '=', 'logit(torch.tensor([0.75,', '0.8,', '0.12,', '0.05],', 'dtype=torch.float32))', 'targets', '=', 'torch.tensor([1,', '1,', '0,', '0],', 'dtype=torch.float32)', 'focal_loss_star', '=', 'sigmoid_focal_loss_star(inputs,', 'target... | 565,985 |
gunthercox/ChatterBot | morph.py | PyStemmerFilter.algorithms | algorithms | Returns a list of stemming algorithms provided by the py-stemmer library. | [
"Returns",
"a",
"list",
"of",
"stemming",
"algorithms",
"provided",
"by",
"the",
"py-stemmer",
"library."
] | def algorithms(self):
import Stemmer
return Stemmer.algorithms() | ['def', 'algorithms(self):', 'import', 'Stemmer', 'return', 'Stemmer.algorithms()'] | 526,568 |
Kvatsx/Artificial-Intelligence-Assignments | core.py | read_style_directory | read_style_directory | Return dictionary of styles defined in `style_dir`. | [
"Return",
"dictionary",
"of",
"styles",
"defined",
"in",
"`style_dir`."
] | def read_style_directory(style_dir):
styles = dict()
for (path, name) in iter_style_files(style_dir):
with warnings.catch_warnings(record=True) as warns:
styles[name] = rc_params_from_file(path, use_default_template=False)
for w in warns:
message = 'In %s: %s' % (path, w.... | ['def', 'read_style_directory(style_dir):', 'styles', '=', 'dict()', 'for', '(path,', 'name)', 'in', 'iter_style_files(style_dir):', 'with', 'warnings.catch_warnings(record=True)', 'as', 'warns:', 'styles[name]', '=', 'rc_params_from_file(path,', 'use_default_template=False)', 'for', 'w', 'in', 'warns:', 'message', '='... | 1,341 |
calico/basenji | borzoi_test_genes.py | make_genes_exon | make_genes_exon | Make a BED file with each genes' exons, excluding exons overlapping across genes. | [
"Make",
"a",
"BED",
"file",
"with",
"each",
"genes'",
"exons,",
"excluding",
"exons",
"overlapping",
"across",
"genes."
] | def make_genes_exon(genes_bed_file: str, genes_gtf_file: str, out_dir: str):
genes_gtf = pygene.GTF(genes_gtf_file)
agenes_bed_file = '%s/genes_all.bed' % out_dir
agenes_bed_out = open(agenes_bed_file, 'w')
for (gene_id, gene) in genes_gtf.genes.items():
gene_intervals = IntervalTree()
f... | ['def', 'make_genes_exon(genes_bed_file:', 'str,', 'genes_gtf_file:', 'str,', 'out_dir:', 'str):', 'genes_gtf', '=', 'pygene.GTF(genes_gtf_file)', 'agenes_bed_file', '=', "'%s/genes_all.bed'", '%', 'out_dir', 'agenes_bed_out', '=', 'open(agenes_bed_file,', "'w')", 'for', '(gene_id,', 'gene)', 'in', 'genes_gtf.genes.ite... | 94,840 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | util.py | pairwise_distances | pairwise_distances | Computes the pairwise distance matrix in numpy. | [
"Computes",
"the",
"pairwise",
"distance",
"matrix",
"in",
"numpy."
] | def pairwise_distances(feature, squared=True):
triu = np.triu_indices(feature.shape[0], 1)
upper_tri_pdists = np.linalg.norm(feature[triu[1]] - feature[triu[0]], axis=1)
if squared:
upper_tri_pdists **= 2.0
num_data = feature.shape[0]
pdists = np.zeros((num_data, num_data))
pdists[np.tri... | ['def', 'pairwise_distances(feature,', 'squared=True):', 'triu', '=', 'np.triu_indices(feature.shape[0],', '1)', 'upper_tri_pdists', '=', 'np.linalg.norm(feature[triu[1]]', '-', 'feature[triu[0]],', 'axis=1)', 'if', 'squared:', 'upper_tri_pdists', '**=', '2.0', 'num_data', '=', 'feature.shape[0]', 'pdists', '=', 'np.ze... | 112,655 |
YuriyGuts/snake-ai-reinforcement | environment.py | Environment.timestep | timestep | Execute the timestep and return the new observable state. | [
"Execute",
"the",
"timestep",
"and",
"return",
"the",
"new",
"observable",
"state."
] | def timestep(self):
self.timestep_index += 1
reward = 0
old_head = self.snake.head
old_tail = self.snake.tail
if self.snake.peek_next_move() == self.fruit:
self.snake.grow()
self.generate_fruit()
old_tail = None
reward += self.rewards['ate_fruit'] * self.snake.length
... | ['def', 'timestep(self):', 'self.timestep_index', '+=', '1', 'reward', '=', '0', 'old_head', '=', 'self.snake.head', 'old_tail', '=', 'self.snake.tail', 'if', 'self.snake.peek_next_move()', '==', 'self.fruit:', 'self.snake.grow()', 'self.generate_fruit()', 'old_tail', '=', 'None', 'reward', '+=', "self.rewards['ate_fru... | 352,174 |
googleapis/python-aiplatform | client.py | IndexServiceClient.index_path | index_path | Returns a fully-qualified index string. | [
"Returns",
"a",
"fully-qualified",
"index",
"string."
] | def index_path(project: str, location: str, index: str) -> str:
return 'projects/{project}/locations/{location}/indexes/{index}'.format(project=project, location=location, index=index) | ['def', 'index_path(project:', 'str,', 'location:', 'str,', 'index:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/indexes/{index}'.format(project=project,", 'location=location,', 'index=index)'] | 812,957 |
rudranil723/mini-main | uploadhandler.py | MemoryFileUploadHandler.handle_raw_input | handle_raw_input | Use the content_length to signal whether or not this handler should be used. | [
"Use",
"the",
"content_length",
"to",
"signal",
"whether",
"or",
"not",
"this",
"handler",
"should",
"be",
"used."
] | def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
self.activated = content_length <= settings.FILE_UPLOAD_MAX_MEMORY_SIZE | ['def', 'handle_raw_input(self,', 'input_data,', 'META,', 'content_length,', 'boundary,', 'encoding=None):', 'self.activated', '=', 'content_length', '<=', 'settings.FILE_UPLOAD_MAX_MEMORY_SIZE'] | 315,554 |
pytorch/rl | env.py | Environment.reset | reset | Resets the state of the environment and returns an initial observation. | [
"Resets",
"the",
"state",
"of",
"the",
"environment",
"and",
"returns",
"an",
"initial",
"observation."
] | def reset(self):
raise NotImplementedError | ['def', 'reset(self):', 'raise', 'NotImplementedError'] | 860,671 |
kubeflow/pipelines | _container_op.py | Container.get_resource_request | get_resource_request | Get the resource request of the container. | [
"Get",
"the",
"resource",
"request",
"of",
"the",
"container."
] | def get_resource_request(self, resource_name: str) -> Optional[str]:
if not self.resources or not self.resources.requests:
return None
return self.resources.requests.get(resource_name) | ['def', 'get_resource_request(self,', 'resource_name:', 'str)', '->', 'Optional[str]:', 'if', 'not', 'self.resources', 'or', 'not', 'self.resources.requests:', 'return', 'None', 'return', 'self.resources.requests.get(resource_name)'] | 780,111 |
voxel51/fiftyone | utils.py | iter_batches | iter_batches | Iterates over the given iterable in batches. | [
"Iterates",
"over",
"the",
"given",
"iterable",
"in",
"batches."
] | def iter_batches(iterable, batch_size):
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, batch_size))
if not chunk:
return
yield chunk | ['def', 'iter_batches(iterable,', 'batch_size):', 'it', '=', 'iter(iterable)', 'while', 'True:', 'chunk', '=', 'tuple(itertools.islice(it,', 'batch_size))', 'if', 'not', 'chunk:', 'return', 'yield', 'chunk'] | 583,454 |
rlgraph/rlgraph | space.py | Space.with_time_rank | with_time_rank | Returns a deepcopy of this Space, but with `has_time_rank` set to the provided value. | [
"Returns",
"a",
"deepcopy",
"of",
"this",
"Space,",
"but",
"with",
"`has_time_rank`",
"set",
"to",
"the",
"provided",
"value."
] | def with_time_rank(self, add_time_rank=True):
return self.with_extra_ranks(add_batch_rank=None, add_time_rank=add_time_rank) | ['def', 'with_time_rank(self,', 'add_time_rank=True):', 'return', 'self.with_extra_ranks(add_batch_rank=None,', 'add_time_rank=add_time_rank)'] | 862,633 |
mme/vergeml | loader.py | Loader.read_samples | read_samples | Read n_samples starting at index from the cache. | [
"Read",
"n_samples",
"starting",
"at",
"index",
"from",
"the",
"cache."
] | def read_samples(self, split: str, index: int, n_samples: int=1) -> Sample:
samples = []
reader = self.pumps.get(split, self)
for item in reader.perform_read(split, index, n_samples):
(x, y) = item[0]
(meta, rng) = item[1]
samples.append(Sample(x, y, meta, rng))
return samples | ['def', 'read_samples(self,', 'split:', 'str,', 'index:', 'int,', 'n_samples:', 'int=1)', '->', 'Sample:', 'samples', '=', '[]', 'reader', '=', 'self.pumps.get(split,', 'self)', 'for', 'item', 'in', 'reader.perform_read(split,', 'index,', 'n_samples):', '(x,', 'y)', '=', 'item[0]', '(meta,', 'rng)', '=', 'item[1]', 'sa... | 931,557 |
mcao516/Autoregressive-VAE | autoencoder_en_attn.py | build_mask | build_mask | Build a mask for the Transformer decoder to mask all the subsequent tokens. | [
"Build",
"a",
"mask",
"for",
"the",
"Transformer",
"decoder",
"to",
"mask",
"all",
"the",
"subsequent",
"tokens."
] | def build_mask(base_mask):
assert len(base_mask.shape) == 2
(batch_size, seq_len) = (base_mask.shape[0], base_mask.shape[-1])
sub_mask = torch.tril(torch.ones([seq_len, seq_len], dtype=torch.uint8)).type_as(base_mask)
sub_mask = sub_mask.unsqueeze(0).expand(batch_size, -1, -1)
base_mask = base_mask.... | ['def', 'build_mask(base_mask):', 'assert', 'len(base_mask.shape)', '==', '2', '(batch_size,', 'seq_len)', '=', '(base_mask.shape[0],', 'base_mask.shape[-1])', 'sub_mask', '=', 'torch.tril(torch.ones([seq_len,', 'seq_len],', 'dtype=torch.uint8)).type_as(base_mask)', 'sub_mask', '=', 'sub_mask.unsqueeze(0).expand(batch_... | 420,324 |
dibyaghosh/gcsl | base_env.py | BaseDClawObjectEnv.set_state | set_state | Sets the state of the environment. | [
"Sets",
"the",
"state",
"of",
"the",
"environment."
] | def set_state(self, state: Dict[str, np.ndarray]):
self.robot.set_state({'dclaw': RobotState(qpos=state['claw_qpos'], qvel=state['claw_qvel']), 'object': RobotState(qpos=state['object_qpos'], qvel=state['object_qvel'])}) | ['def', 'set_state(self,', 'state:', 'Dict[str,', 'np.ndarray]):', "self.robot.set_state({'dclaw':", "RobotState(qpos=state['claw_qpos'],", "qvel=state['claw_qvel']),", "'object':", "RobotState(qpos=state['object_qpos'],", "qvel=state['object_qvel'])})"] | 201,854 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | data_providers_test.py | DataTest.testSVTripletIndices | testSVTripletIndices | Ensures time indices for a SV triplet batch are valid. | [
"Ensures",
"time",
"indices",
"for",
"a",
"SV",
"triplet",
"batch",
"are",
"valid."
] | def testSVTripletIndices(self):
seq_len = 600
batch_size = 36
num_views = 2
(time_indices, _) = data_providers.get_svtcn_indices(seq_len, batch_size, num_views)
with self.test_session() as sess:
np_time_indices = sess.run(time_indices)
first = np_time_indices[0]
last = np_tim... | ['def', 'testSVTripletIndices(self):', 'seq_len', '=', '600', 'batch_size', '=', '36', 'num_views', '=', '2', '(time_indices,', '_)', '=', 'data_providers.get_svtcn_indices(seq_len,', 'batch_size,', 'num_views)', 'with', 'self.test_session()', 'as', 'sess:', 'np_time_indices', '=', 'sess.run(time_indices)', 'first', '=... | 29,218 |
wyshi/Unsupervised-Structure-Learning | decoder_fn_lib.py | context_decoder_fn_inference | context_decoder_fn_inference | Simple decoder function for a sequence-to-sequence model used in the `dynamic_rnn_decoder`. | [
"Simple",
"decoder",
"function",
"for",
"a",
"sequence-to-sequence",
"model",
"used",
"in",
"the",
"`dynamic_rnn_decoder`."
] | def context_decoder_fn_inference(output_fn, encoder_state, embeddings, start_of_sequence_id, end_of_sequence_id, maximum_length, num_decoder_symbols, context_vector, dtype=dtypes.int32, name=None, decode_type='greedy'):
with ops.name_scope(name, 'simple_decoder_fn_inference', [output_fn, encoder_state, embeddings, ... | ['def', 'context_decoder_fn_inference(output_fn,', 'encoder_state,', 'embeddings,', 'start_of_sequence_id,', 'end_of_sequence_id,', 'maximum_length,', 'num_decoder_symbols,', 'context_vector,', 'dtype=dtypes.int32,', 'name=None,', "decode_type='greedy'):", 'with', 'ops.name_scope(name,', "'simple_decoder_fn_inference',... | 353,729 |
enuguru/artificial_intelligence_and_machine_learning | __init__.py | DebuggedApplication.is_trusted | is_trusted | Checks if the request passed the pin test. | [
"Checks",
"if",
"the",
"request",
"passed",
"the",
"pin",
"test."
] | def is_trusted(self, environ):
if self.pin is None:
return True
ts = parse_cookie(environ).get(self.pin_cookie_name, type=int)
if ts is None:
return False
return time.time() - PIN_TIME < ts | ['def', 'is_trusted(self,', 'environ):', 'if', 'self.pin', 'is', 'None:', 'return', 'True', 'ts', '=', 'parse_cookie(environ).get(self.pin_cookie_name,', 'type=int)', 'if', 'ts', 'is', 'None:', 'return', 'False', 'return', 'time.time()', '-', 'PIN_TIME', '<', 'ts'] | 132,785 |
openvinotoolkit/training_extensions | configurable_enum.py | ConfigurableEnum.get_values | get_values | Returns a list of values that can be used to index the Enum. | [
"Returns",
"a",
"list",
"of",
"values",
"that",
"can",
"be",
"used",
"to",
"index",
"the",
"Enum."
] | def get_values(cls) -> List[str]:
return [x.value for x in cls] | ['def', 'get_values(cls)', '->', 'List[str]:', 'return', '[x.value', 'for', 'x', 'in', 'cls]'] | 918,404 |
devashish-patel/webcam-motion-detector | libcython.py | CythonBase.print_stackframe | print_stackframe | Print a C, Cython or Python stack frame and the line of source code if available. | [
"Print",
"a",
"C,",
"Cython",
"or",
"Python",
"stack",
"frame",
"and",
"the",
"line",
"of",
"source",
"code",
"if",
"available."
] | def print_stackframe(self, frame, index, is_c=False):
selected_frame = gdb.selected_frame()
frame.select()
try:
(source_desc, lineno) = self.get_source_desc(frame)
except NoFunctionNameInFrameError:
print('#%-2d Unknown Frame (compile with -g)' % index)
return
if not is_c and... | ['def', 'print_stackframe(self,', 'frame,', 'index,', 'is_c=False):', 'selected_frame', '=', 'gdb.selected_frame()', 'frame.select()', 'try:', '(source_desc,', 'lineno)', '=', 'self.get_source_desc(frame)', 'except', 'NoFunctionNameInFrameError:', "print('#%-2d", 'Unknown', 'Frame', '(compile', 'with', "-g)'", '%', 'in... | 977,570 |
hsinyuan-huang/FusionNet-NLI | layers.py | uniform_weights | uniform_weights | Return uniform weights over non-masked input. | [
"Return",
"uniform",
"weights",
"over",
"non-masked",
"input."
] | def uniform_weights(x, x_mask):
alpha = Variable(torch.ones(x.size(0), x.size(1)))
if x.data.is_cuda:
alpha = alpha.cuda()
alpha = alpha * x_mask.eq(0).float()
alpha = alpha / alpha.sum(1).expand(alpha.size())
return alpha | ['def', 'uniform_weights(x,', 'x_mask):', 'alpha', '=', 'Variable(torch.ones(x.size(0),', 'x.size(1)))', 'if', 'x.data.is_cuda:', 'alpha', '=', 'alpha.cuda()', 'alpha', '=', 'alpha', '*', 'x_mask.eq(0).float()', 'alpha', '=', 'alpha', '/', 'alpha.sum(1).expand(alpha.size())', 'return', 'alpha'] | 214,159 |
v0lta/Complex-gated-recurrent-- | custom_cells.py | gate_phase_hirose | gate_phase_hirose | Hirose inspired gate activation filtering according to phase angle. | [
"Hirose",
"inspired",
"gate",
"activation",
"filtering",
"according",
"to",
"phase",
"angle."
] | def gate_phase_hirose(z, scope='', reuse=None):
with tf.variable_scope('phase_hirose_' + scope, reuse=reuse):
m = tf.get_variable('m', [], tf.float32, initializer=urnd_init(0.9, 1.1))
a = tf.get_variable('a', [], tf.float32, initializer=urnd_init(1.9, 2.1))
b = tf.get_variable('b', [], tf.fl... | ['def', 'gate_phase_hirose(z,', "scope='',", 'reuse=None):', 'with', "tf.variable_scope('phase_hirose_'", '+', 'scope,', 'reuse=reuse):', 'm', '=', "tf.get_variable('m',", '[],', 'tf.float32,', 'initializer=urnd_init(0.9,', '1.1))', 'a', '=', "tf.get_variable('a',", '[],', 'tf.float32,', 'initializer=urnd_init(1.9,', '... | 135,968 |
tobegit3hub/deep_image_model | user_ops.py | my_fact | my_fact | Example of overriding the generated code for an Op. | [
"Example",
"of",
"overriding",
"the",
"generated",
"code",
"for",
"an",
"Op."
] | def my_fact():
return gen_user_ops._fact() | ['def', 'my_fact():', 'return', 'gen_user_ops._fact()'] | 183,437 |
aws/sagemaker-python-sdk | monitoring_files.py | ConstraintViolations.from_string | from_string | Generates a ConstraintViolations object from an s3 uri. | [
"Generates",
"a",
"ConstraintViolations",
"object",
"from",
"an",
"s3",
"uri."
] | def from_string(cls, constraint_violations_file_string, kms_key=None, file_name=None, sagemaker_session=None):
sagemaker_session = sagemaker_session or Session()
file_name = file_name or 'constraint_violations.json'
desired_s3_uri = s3.s3_path_join('s3://', sagemaker_session.default_bucket(), sagemaker_sess... | ['def', 'from_string(cls,', 'constraint_violations_file_string,', 'kms_key=None,', 'file_name=None,', 'sagemaker_session=None):', 'sagemaker_session', '=', 'sagemaker_session', 'or', 'Session()', 'file_name', '=', 'file_name', 'or', "'constraint_violations.json'", 'desired_s3_uri', '=', "s3.s3_path_join('s3://',", 'sag... | 830,485 |
rudranil723/mini-main | bokeh_renderer.py | BokehRenderer.title | title | Set the title of a single plot. | [
"Set",
"the",
"title",
"of",
"a",
"single",
"plot."
] | def title(self, title, ax=0, color=None):
fig = self._get_figure(ax)
fig.title = title
fig.title.align = 'center'
if color is not None:
fig.title.text_color = self._convert_color(color) | ['def', 'title(self,', 'title,', 'ax=0,', 'color=None):', 'fig', '=', 'self._get_figure(ax)', 'fig.title', '=', 'title', 'fig.title.align', '=', "'center'", 'if', 'color', 'is', 'not', 'None:', 'fig.title.text_color', '=', 'self._convert_color(color)'] | 314,516 |
grayhong/self-diagnosing-gan | compute_fid_with_attr.py | compute_real_dist_stats_with_attr | compute_real_dist_stats_with_attr | Reads the image data and compute the FID mean and cov statistics for real images. | [
"Reads",
"the",
"image",
"data",
"and",
"compute",
"the",
"FID",
"mean",
"and",
"cov",
"statistics",
"for",
"real",
"images."
] | def compute_real_dist_stats_with_attr(attr, sess, batch_size, dataset=None, stats_file=None, seed=0, verbose=True, log_dir='./log', name=None):
if stats_file is None:
stats_dir = os.path.join(log_dir, 'metrics', 'fid', 'statistics')
if not os.path.exists(stats_dir):
os.makedirs(stats_dir... | ['def', 'compute_real_dist_stats_with_attr(attr,', 'sess,', 'batch_size,', 'dataset=None,', 'stats_file=None,', 'seed=0,', 'verbose=True,', "log_dir='./log',", 'name=None):', 'if', 'stats_file', 'is', 'None:', 'stats_dir', '=', 'os.path.join(log_dir,', "'metrics',", "'fid',", "'statistics')", 'if', 'not', 'os.path.exis... | 843,191 |
shanest/quantifier-rnn-learning | quantifiers.py | even_ver | even_ver | Verifies whether the number of As that are B is even. | [
"Verifies",
"whether",
"the",
"number",
"of",
"As",
"that",
"are",
"B",
"is",
"even."
] | def even_ver(seq):
num_AB = 0
for item in seq:
if np.array_equal(item, Quantifier.AB):
num_AB += 1
if num_AB % 2 == 0:
return Quantifier.T
else:
return Quantifier.F | ['def', 'even_ver(seq):', 'num_AB', '=', '0', 'for', 'item', 'in', 'seq:', 'if', 'np.array_equal(item,', 'Quantifier.AB):', 'num_AB', '+=', '1', 'if', 'num_AB', '%', '2', '==', '0:', 'return', 'Quantifier.T', 'else:', 'return', 'Quantifier.F'] | 304,011 |
intel/neural-compressor | run_inference.py | collate_fn | collate_fn | Puts each data field into a pd frame with outer dimension batch size. | [
"Puts",
"each",
"data",
"field",
"into",
"a",
"pd",
"frame",
"with",
"outer",
"dimension",
"batch",
"size."
] | def collate_fn(batch):
elem = batch[0]
if isinstance(elem, tuple):
batch = zip(*batch)
return [collate_fn(samples) for samples in batch]
elif isinstance(elem, np.ndarray):
return [list(elem) for elem in batch]
elif isinstance(elem, str) or isinstance(elem, int):
return ba... | ['def', 'collate_fn(batch):', 'elem', '=', 'batch[0]', 'if', 'isinstance(elem,', 'tuple):', 'batch', '=', 'zip(*batch)', 'return', '[collate_fn(samples)', 'for', 'samples', 'in', 'batch]', 'elif', 'isinstance(elem,', 'np.ndarray):', 'return', '[list(elem)', 'for', 'elem', 'in', 'batch]', 'elif', 'isinstance(elem,', 'st... | 737,144 |
43Carrig/recurrent_neural_networks_practice | checkpoint_management.py | remove_checkpoint | remove_checkpoint | Removes a checkpoint given by `checkpoint_prefix`. | [
"Removes",
"a",
"checkpoint",
"given",
"by",
"`checkpoint_prefix`."
] | def remove_checkpoint(checkpoint_prefix, checkpoint_format_version=saver_pb2.SaverDef.V2, meta_graph_suffix='meta'):
_delete_file_if_exists(meta_graph_filename(checkpoint_prefix, meta_graph_suffix))
if checkpoint_format_version == saver_pb2.SaverDef.V2:
_delete_file_if_exists(checkpoint_prefix + '.index... | ['def', 'remove_checkpoint(checkpoint_prefix,', 'checkpoint_format_version=saver_pb2.SaverDef.V2,', "meta_graph_suffix='meta'):", '_delete_file_if_exists(meta_graph_filename(checkpoint_prefix,', 'meta_graph_suffix))', 'if', 'checkpoint_format_version', '==', 'saver_pb2.SaverDef.V2:', '_delete_file_if_exists(checkpoint_... | 339,522 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_pulldom.py | ThoroughTestCase.test_thorough_parse | test_thorough_parse | Test some of the hard-to-reach parts of PullDOM. | [
"Test",
"some",
"of",
"the",
"hard-to-reach",
"parts",
"of",
"PullDOM."
] | def test_thorough_parse(self):
self._test_thorough(pulldom.parse(None, parser=SAXExerciser())) | ['def', 'test_thorough_parse(self):', 'self._test_thorough(pulldom.parse(None,', 'parser=SAXExerciser()))'] | 376,303 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | template.py | Method.iterParams | iterParams | Yields the parameters of this method template. | [
"Yields",
"the",
"parameters",
"of",
"this",
"method",
"template."
] | def iterParams(self):
return chain(*(h(self) for h in self.configHandlers('Param'))) | ['def', 'iterParams(self):', 'return', 'chain(*(h(self)', 'for', 'h', 'in', "self.configHandlers('Param')))"] | 16,897 |
rahlk/Bellwether | table.py | row | row | Leaps over any columns marked 'skip'. | [
"Leaps",
"over",
"any",
"columns",
"marked",
"'skip'."
] | def row(file, skip=The.reader.skip):
todo = None
for (n, line) in rows(file):
todo = todo or [col for (col, name) in enumerate(line) if not skip in name]
yield (n, [line[col] for col in todo]) | ['def', 'row(file,', 'skip=The.reader.skip):', 'todo', '=', 'None', 'for', '(n,', 'line)', 'in', 'rows(file):', 'todo', '=', 'todo', 'or', '[col', 'for', '(col,', 'name)', 'in', 'enumerate(line)', 'if', 'not', 'skip', 'in', 'name]', 'yield', '(n,', '[line[col]', 'for', 'col', 'in', 'todo])'] | 431,428 |
mideind/GreynirServer | geo.py | continent_for_country | continent_for_country | Return two-char continent code, given a two-char country code. | [
"Return",
"two-char",
"continent",
"code,",
"given",
"a",
"two-char",
"country",
"code."
] | def continent_for_country(iso_code: str) -> Optional[str]:
assert len(iso_code) == 2
iso_code = iso_code.upper()
data = _load_country_data()
if iso_code in data:
return data[iso_code].get('cc')
return None | ['def', 'continent_for_country(iso_code:', 'str)', '->', 'Optional[str]:', 'assert', 'len(iso_code)', '==', '2', 'iso_code', '=', 'iso_code.upper()', 'data', '=', '_load_country_data()', 'if', 'iso_code', 'in', 'data:', 'return', "data[iso_code].get('cc')", 'return', 'None'] | 580,950 |
secretflow/secretflow | _utils.py | cal_indexes | cal_indexes | Calculate the indexes by the given partitions. | [
"Calculate",
"the",
"indexes",
"by",
"the",
"given",
"partitions."
] | def cal_indexes(parts: Union[List[PYU], Dict[PYU, Union[float, Tuple]]], total_num: int) -> Dict[PYU, Tuple]:
assert total_num >= len(parts), f'Total samples/columns {total_num} is less than parts number {len(parts)}.'
indexes = {}
devices = None
if isinstance(parts, (list, tuple)):
for part in ... | ['def', 'cal_indexes(parts:', 'Union[List[PYU],', 'Dict[PYU,', 'Union[float,', 'Tuple]]],', 'total_num:', 'int)', '->', 'Dict[PYU,', 'Tuple]:', 'assert', 'total_num', '>=', 'len(parts),', "f'Total", 'samples/columns', '{total_num}', 'is', 'less', 'than', 'parts', 'number', "{len(parts)}.'", 'indexes', '=', '{}', 'devic... | 856,718 |
rifqind/Agent-Programs-3KS1 | png.py | Test.testPNMsbit | testPNMsbit | Test that PNM files can generates sBIT chunk. | [
"Test",
"that",
"PNM",
"files",
"can",
"generates",
"sBIT",
"chunk."
] | def testPNMsbit(self):
def do():
return _main(['testPNMsbit'])
s = BytesIO()
s.write(strtobytes('P6 8 1 1\n'))
for pixel in range(8):
s.write(struct.pack('<I', 16513 * pixel & 65793)[:3])
s.flush()
s.seek(0)
o = BytesIO()
testWithIO(s, o, do)
r = Reader(bytes=o.getva... | ['def', 'testPNMsbit(self):', 'def', 'do():', 'return', "_main(['testPNMsbit'])", 's', '=', 'BytesIO()', "s.write(strtobytes('P6", '8', '1', "1\\n'))", 'for', 'pixel', 'in', 'range(8):', "s.write(struct.pack('<I',", '16513', '*', 'pixel', '&', '65793)[:3])', 's.flush()', 's.seek(0)', 'o', '=', 'BytesIO()', 'testWithIO(... | 46,078 |
tensorflow/data-validation | csv_decoder.py | DecodeCSV.expand | expand | Decodes the input CSV records into RecordBatches. | [
"Decodes",
"the",
"input",
"CSV",
"records",
"into",
"RecordBatches."
] | def expand(self, lines: beam.pvalue.PCollection):
return lines | 'CSVToRecordBatch' >> csv_decoder.CSVToRecordBatch(column_names=self._column_names, delimiter=self._delimiter, skip_blank_lines=self._skip_blank_lines, schema=self._schema, desired_batch_size=self._desired_batch_size, multivalent_columns=self._multiva... | ['def', 'expand(self,', 'lines:', 'beam.pvalue.PCollection):', 'return', 'lines', '|', "'CSVToRecordBatch'", '>>', 'csv_decoder.CSVToRecordBatch(column_names=self._column_names,', 'delimiter=self._delimiter,', 'skip_blank_lines=self._skip_blank_lines,', 'schema=self._schema,', 'desired_batch_size=self._desired_batch_si... | 497,440 |
tobegit3hub/deep_image_model | linear_test.py | LinearRegressorTest.testRegression_TensorData | testRegression_TensorData | Tests regression using tensor data as input. | [
"Tests",
"regression",
"using",
"tensor",
"data",
"as",
"input."
] | def testRegression_TensorData(self):
def _input_fn(num_epochs=None):
features = {'age': tf.train.limit_epochs(tf.constant([[0.8], [0.15], [0.0]]), num_epochs=num_epochs), 'language': tf.SparseTensor(values=['en', 'fr', 'zh'], indices=[[0, 0], [0, 1], [2, 0]], shape=[3, 2])}
return (features, tf.con... | ['def', 'testRegression_TensorData(self):', 'def', '_input_fn(num_epochs=None):', 'features', '=', "{'age':", 'tf.train.limit_epochs(tf.constant([[0.8],', '[0.15],', '[0.0]]),', 'num_epochs=num_epochs),', "'language':", "tf.SparseTensor(values=['en',", "'fr',", "'zh'],", 'indices=[[0,', '0],', '[0,', '1],', '[2,', '0]]... | 181,779 |
santhoshkolloju/Abstractive-Summarization-With-Transfer- | layers.py | get_rnn_cell_trainable_variables | get_rnn_cell_trainable_variables | Returns the list of trainable variables of an RNN cell. | [
"Returns",
"the",
"list",
"of",
"trainable",
"variables",
"of",
"an",
"RNN",
"cell."
] | def get_rnn_cell_trainable_variables(cell):
cell_ = cell
while True:
try:
return cell_.trainable_variables
except AttributeError:
cell_ = cell._cell | ['def', 'get_rnn_cell_trainable_variables(cell):', 'cell_', '=', 'cell', 'while', 'True:', 'try:', 'return', 'cell_.trainable_variables', 'except', 'AttributeError:', 'cell_', '=', 'cell._cell'] | 405,969 |
LEAP-WS/CG3 | graph.py | Graph.get_neighs | get_neighs | obtain the list of neigbors given a node. | [
"obtain",
"the",
"list",
"of",
"neigbors",
"given",
"a",
"node."
] | def get_neighs(self, idx):
istart = self.adj_idx[idx]
iend = self.adj_idx[idx + 1]
return self.adj_list[istart:iend] | ['def', 'get_neighs(self,', 'idx):', 'istart', '=', 'self.adj_idx[idx]', 'iend', '=', 'self.adj_idx[idx', '+', '1]', 'return', 'self.adj_list[istart:iend]'] | 104,278 |
shijie-wu/crosslingual-nlp | tagging.py | WikiAnnNER.read_file | read_file | Reads an empty line seperated data (word label). | [
"Reads",
"an",
"empty",
"line",
"seperated",
"data",
"(word",
"label)."
] | def read_file(cls, filepath: str, lang: str, split: str) -> Iterator[Dict]:
words: List[str] = []
labels: List[str] = []
with open(filepath, 'r') as f:
for line in f.readlines():
line = line.strip()
if not line:
assert len(words) == len(labels)
... | ['def', 'read_file(cls,', 'filepath:', 'str,', 'lang:', 'str,', 'split:', 'str)', '->', 'Iterator[Dict]:', 'words:', 'List[str]', '=', '[]', 'labels:', 'List[str]', '=', '[]', 'with', 'open(filepath,', "'r')", 'as', 'f:', 'for', 'line', 'in', 'f.readlines():', 'line', '=', 'line.strip()', 'if', 'not', 'line:', 'assert'... | 492,043 |
ludwig-ai/ludwig | test_ray.py | TestDatasetWindowAutosizing.test_large_dataset | test_large_dataset | A large dataset should trigger windowing. | [
"A",
"large",
"dataset",
"should",
"trigger",
"windowing."
] | def test_large_dataset(self, ray_cluster_2cpu):
pipe = self.create_dataset_pipeline(self.auto_window_size * 2, window_size_bytes='auto')
for (i, window) in enumerate(self.window_gen(pipe)):
assert window.num_blocks() < self.num_partitions
if i > 100:
break | ['def', 'test_large_dataset(self,', 'ray_cluster_2cpu):', 'pipe', '=', 'self.create_dataset_pipeline(self.auto_window_size', '*', '2,', "window_size_bytes='auto')", 'for', '(i,', 'window)', 'in', 'enumerate(self.window_gen(pipe)):', 'assert', 'window.num_blocks()', '<', 'self.num_partitions', 'if', 'i', '>', '100:', 'b... | 617,284 |
xuannianz/SAPD | transform.py | translation_x | translation_x | Construct a homogeneous 2D translation matrix. | [
"Construct",
"a",
"homogeneous",
"2D",
"translation",
"matrix."
] | def translation_x(min=0, max=0, prob=0.5):
random_prob = np.random.uniform()
if random_prob > prob:
translation = random_value(min=min, max=max)
return np.array([[1, 0, translation], [0, 1], [0, 0, 1]])
else:
return identity_matrix | ['def', 'translation_x(min=0,', 'max=0,', 'prob=0.5):', 'random_prob', '=', 'np.random.uniform()', 'if', 'random_prob', '>', 'prob:', 'translation', '=', 'random_value(min=min,', 'max=max)', 'return', 'np.array([[1,', '0,', 'translation],', '[0,', '1],', '[0,', '0,', '1]])', 'else:', 'return', 'identity_matrix'] | 845,394 |
noambassat/SpeechTrainer | fancy_getopt.py | FancyGetopt.has_option | has_option | Return true if the option table for this parser has an option with long name 'long_option'. | [
"Return",
"true",
"if",
"the",
"option",
"table",
"for",
"this",
"parser",
"has",
"an",
"option",
"with",
"long",
"name",
"'long_option'."
] | def has_option(self, long_option):
return long_option in self.option_index | ['def', 'has_option(self,', 'long_option):', 'return', 'long_option', 'in', 'self.option_index'] | 896,243 |
rldotai/rl-algorithms | gtd.py | GTD.reset | reset | Reset weights, traces, and other parameters. | [
"Reset",
"weights,",
"traces,",
"and",
"other",
"parameters."
] | def reset(self):
self.e = np.zeros(self.n)
self.w = np.zeros(self.n)
self.h = np.zeros(self.n) | ['def', 'reset(self):', 'self.e', '=', 'np.zeros(self.n)', 'self.w', '=', 'np.zeros(self.n)', 'self.h', '=', 'np.zeros(self.n)'] | 841,690 |
rudranil723/mini-main | cache.py | has_vary_header | has_vary_header | Check to see if the response has a given header name in its Vary header. | [
"Check",
"to",
"see",
"if",
"the",
"response",
"has",
"a",
"given",
"header",
"name",
"in",
"its",
"Vary",
"header."
] | def has_vary_header(response, header_query):
if not response.has_header('Vary'):
return False
vary_headers = cc_delim_re.split(response['Vary'])
existing_headers = {header.lower() for header in vary_headers}
return header_query.lower() in existing_headers | ['def', 'has_vary_header(response,', 'header_query):', 'if', 'not', "response.has_header('Vary'):", 'return', 'False', 'vary_headers', '=', "cc_delim_re.split(response['Vary'])", 'existing_headers', '=', '{header.lower()', 'for', 'header', 'in', 'vary_headers}', 'return', 'header_query.lower()', 'in', 'existing_headers... | 316,622 |
LeoZDong/netAE | helper.py | log_metrics | log_metrics | Log all metrics in metrics_dict to file. | [
"Log",
"all",
"metrics",
"in",
"metrics_dict",
"to",
"file."
] | def log_metrics(metrics_dict, epoch, prnt=False):
if epoch == 0:
if not os.path.exists('logs'):
os.makedirs('logs')
for name in list(metrics_dict.keys()):
open('logs/{}.txt'.format(name), 'w+').close()
for name in list(metrics_dict.keys()):
with open('logs/{}.txt'... | ['def', 'log_metrics(metrics_dict,', 'epoch,', 'prnt=False):', 'if', 'epoch', '==', '0:', 'if', 'not', "os.path.exists('logs'):", "os.makedirs('logs')", 'for', 'name', 'in', 'list(metrics_dict.keys()):', "open('logs/{}.txt'.format(name),", "'w+').close()", 'for', 'name', 'in', 'list(metrics_dict.keys()):', 'with', "ope... | 735,896 |
intel/neural-compressor | metric.py | BaseMetric.update | update | Update the state that need to be evaluated. | [
"Update",
"the",
"state",
"that",
"need",
"to",
"be",
"evaluated."
] | def update(self, preds, labels=None, sample_weight=None):
raise NotImplementedError | ['def', 'update(self,', 'preds,', 'labels=None,', 'sample_weight=None):', 'raise', 'NotImplementedError'] | 738,804 |
Kvatsx/Artificial-Intelligence-Assignments | _dicom.py | DicomSeries.shape | shape | The shape of the data (nz, ny, nx). | [
"The",
"shape",
"of",
"the",
"data",
"(nz,",
"ny,",
"nx)."
] | def shape(self):
return self._info['shape'] | ['def', 'shape(self):', 'return', "self._info['shape']"] | 37,442 |
julianfaraone/SYQ | stats.py | StatHolder.set_print_tag | set_print_tag | Set name of stats to print. | [
"Set",
"name",
"of",
"stats",
"to",
"print."
] | def set_print_tag(self, print_tag):
self.print_tag = None if print_tag is None else set(print_tag) | ['def', 'set_print_tag(self,', 'print_tag):', 'self.print_tag', '=', 'None', 'if', 'print_tag', 'is', 'None', 'else', 'set(print_tag)'] | 906,406 |
caiiiac/Machine-Learning-with-Python | font_manager.py | get_fontconfig_fonts | get_fontconfig_fonts | List the font filenames known to `fc-list` having the given extension. | [
"List",
"the",
"font",
"filenames",
"known",
"to",
"`fc-list`",
"having",
"the",
"given",
"extension."
] | def get_fontconfig_fonts(fontext='ttf'):
fontext = get_fontext_synonyms(fontext)
return [fname for fname in _call_fc_list() if os.path.splitext(fname)[1][1:] in fontext] | ['def', "get_fontconfig_fonts(fontext='ttf'):", 'fontext', '=', 'get_fontext_synonyms(fontext)', 'return', '[fname', 'for', 'fname', 'in', '_call_fc_list()', 'if', 'os.path.splitext(fname)[1][1:]', 'in', 'fontext]'] | 715,507 |
ArtificialIntelligenceToolkit/aitk.robots | robot.py | Robot.get_time | get_time | Get the clock time of the world. | [
"Get",
"the",
"clock",
"time",
"of",
"the",
"world."
] | def get_time(self):
if self.world:
return self.world.time | ['def', 'get_time(self):', 'if', 'self.world:', 'return', 'self.world.time'] | 86,635 |
pytorch/rl | functional.py | vec_td1_return_estimate | vec_td1_return_estimate | Vectorized TD(1) return estimate. | [
"Vectorized",
"TD(1)",
"return",
"estimate."
] | def vec_td1_return_estimate(gamma, next_state_value, reward, done: torch.Tensor, terminated: torch.Tensor | None=None, rolling_gamma: Optional[bool]=None, time_dim: int=-2):
return vec_td_lambda_return_estimate(gamma=gamma, next_state_value=next_state_value, reward=reward, done=done, terminated=terminated, rolling_... | ['def', 'vec_td1_return_estimate(gamma,', 'next_state_value,', 'reward,', 'done:', 'torch.Tensor,', 'terminated:', 'torch.Tensor', '|', 'None=None,', 'rolling_gamma:', 'Optional[bool]=None,', 'time_dim:', 'int=-2):', 'return', 'vec_td_lambda_return_estimate(gamma=gamma,', 'next_state_value=next_state_value,', 'reward=r... | 859,398 |
brendanm12345/imageSequenceGeneration | optimization.py | get_polynomial_decay_schedule_with_warmup | get_polynomial_decay_schedule_with_warmup | Create a schedule with a learning rate that decreases as a polynomial decay from the initial lr set in the optimizer to end lr defined by *lr_end*, after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer. | [
"Create",
"a",
"schedule",
"with",
"a",
"learning",
"rate",
"that",
"decreases",
"as",
"a",
"polynomial",
"decay",
"from",
"the",
"initial",
"lr",
"set",
"in",
"the",
"optimizer",
"to",
"end",
"lr",
"defined",
"by",
"*lr_end*,",
"after",
"a",
"warmup",
"pe... | def get_polynomial_decay_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, lr_end=1e-07, power=1.0, last_epoch=-1):
lr_init = optimizer.defaults['lr']
if not lr_init > lr_end:
raise ValueError(f'lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})')
def lr_lambda(cur... | ['def', 'get_polynomial_decay_schedule_with_warmup(optimizer,', 'num_warmup_steps,', 'num_training_steps,', 'lr_end=1e-07,', 'power=1.0,', 'last_epoch=-1):', 'lr_init', '=', "optimizer.defaults['lr']", 'if', 'not', 'lr_init', '>', 'lr_end:', 'raise', "ValueError(f'lr_end", '({lr_end})', 'must', 'be', 'be', 'smaller', '... | 599,614 |
clips/pattern | __init__.py | Application.static | static | Yields the absolute path to the folder with static content. | [
"Yields",
"the",
"absolute",
"path",
"to",
"the",
"folder",
"with",
"static",
"content."
] | def static(self):
return os.path.join(self._path, self._static) | ['def', 'static(self):', 'return', 'os.path.join(self._path,', 'self._static)'] | 764,713 |
thaines/helit | multiclass.py | MultiModel.paramsList | paramsList | Returns a list of parameters objects used by the model - good for curiosity. | [
"Returns",
"a",
"list",
"of",
"parameters",
"objects",
"used",
"by",
"the",
"model",
"-",
"good",
"for",
"curiosity."
] | def paramsList(self):
return map(lambda x: x[1].getParams(), self.models.values()) | ['def', 'paramsList(self):', 'return', 'map(lambda', 'x:', 'x[1].getParams(),', 'self.models.values())'] | 592,509 |
dbash/zerowaste | lazy.py | LazyConfig.apply_overrides | apply_overrides | In-place override contents of cfg. | [
"In-place",
"override",
"contents",
"of",
"cfg."
] | def apply_overrides(cfg, overrides: List[str]):
def safe_update(cfg, key, value):
parts = key.split('.')
for idx in range(1, len(parts)):
prefix = '.'.join(parts[:idx])
v = OmegaConf.select(cfg, prefix, default=None)
if v is None:
break
... | ['def', 'apply_overrides(cfg,', 'overrides:', 'List[str]):', 'def', 'safe_update(cfg,', 'key,', 'value):', 'parts', '=', "key.split('.')", 'for', 'idx', 'in', 'range(1,', 'len(parts)):', 'prefix', '=', "'.'.join(parts[:idx])", 'v', '=', 'OmegaConf.select(cfg,', 'prefix,', 'default=None)', 'if', 'v', 'is', 'None:', 'bre... | 971,352 |
openvinotoolkit/training_extensions | cls_utils.py | get_cls_deploy_config | get_cls_deploy_config | Get classification deploy config. | [
"Get",
"classification",
"deploy",
"config."
] | def get_cls_deploy_config(label_schema: LabelSchemaEntity, inference_config: Dict[str, Any]):
parameters = {}
parameters['type_of_model'] = 'Classification'
parameters['converter_type'] = 'CLASSIFICATION'
parameters['model_parameters'] = inference_config
parameters['model_parameters']['labels'] = La... | ['def', 'get_cls_deploy_config(label_schema:', 'LabelSchemaEntity,', 'inference_config:', 'Dict[str,', 'Any]):', 'parameters', '=', '{}', "parameters['type_of_model']", '=', "'Classification'", "parameters['converter_type']", '=', "'CLASSIFICATION'", "parameters['model_parameters']", '=', 'inference_config', "parameter... | 917,759 |
prdiction47/Unsupervised-Deep-Learning-Templates | MiniSom.py | MiniSom.quantization | quantization | Assigns a code book (weights vector of the winning neuron) to each sample in data. | [
"Assigns",
"a",
"code",
"book",
"(weights",
"vector",
"of",
"the",
"winning",
"neuron)",
"to",
"each",
"sample",
"in",
"data."
] | def quantization(self, data):
q = zeros(data.shape)
for (i, x) in enumerate(data):
q[i] = self.weights[self.winner(x)]
return q | ['def', 'quantization(self,', 'data):', 'q', '=', 'zeros(data.shape)', 'for', '(i,', 'x)', 'in', 'enumerate(data):', 'q[i]', '=', 'self.weights[self.winner(x)]', 'return', 'q'] | 378,840 |
arshpreetsingh/quantopian-machinelearning | test_traitlets.py | test_dict_default_value | test_dict_default_value | Check that the `{}` default value of the Dict traitlet constructor is actually copied. | [
"Check",
"that",
"the",
"`{}`",
"default",
"value",
"of",
"the",
"Dict",
"traitlet",
"constructor",
"is",
"actually",
"copied."
] | def test_dict_default_value():
class Foo(HasTraits):
d1 = Dict()
d2 = Dict()
foo = Foo()
assert foo.d1 == {}
assert foo.d2 == {}
assert foo.d1 is not foo.d2 | ['def', 'test_dict_default_value():', 'class', 'Foo(HasTraits):', 'd1', '=', 'Dict()', 'd2', '=', 'Dict()', 'foo', '=', 'Foo()', 'assert', 'foo.d1', '==', '{}', 'assert', 'foo.d2', '==', '{}', 'assert', 'foo.d1', 'is', 'not', 'foo.d2'] | 893,840 |
FreshAirTonight/af2complex | struct_of_array.py | get_dtype | get_dtype | Returns Dtype for given instance of dataclass. | [
"Returns",
"Dtype",
"for",
"given",
"instance",
"of",
"dataclass."
] | def get_dtype(instance):
fields = dataclasses.fields(instance)
sets_dtype = [field.name for field in fields if field.metadata.get('sets_dtype', False)]
if sets_dtype:
assert len(sets_dtype) == 1, 'at most field can set dtype'
field_value = getattr(instance, sets_dtype[0])
elif instance.s... | ['def', 'get_dtype(instance):', 'fields', '=', 'dataclasses.fields(instance)', 'sets_dtype', '=', '[field.name', 'for', 'field', 'in', 'fields', 'if', "field.metadata.get('sets_dtype',", 'False)]', 'if', 'sets_dtype:', 'assert', 'len(sets_dtype)', '==', '1,', "'at", 'most', 'field', 'can', 'set', "dtype'", 'field_value... | 400,756 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.