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 |
|---|---|---|---|---|---|---|---|---|
scikit-learn/scikit-learn | test_polynomial.py | test_num_combinations | test_num_combinations | Test that n_output_features_ is calculated correctly. | [
"Test",
"that",
"n_output_features_",
"is",
"calculated",
"correctly."
] | def test_num_combinations(n_features, min_degree, max_degree, interaction_only, include_bias, csr_container):
x = csr_container(([1], ([0], [n_features - 1])))
est = PolynomialFeatures(degree=max_degree, interaction_only=interaction_only, include_bias=include_bias)
est.fit(x)
num_combos = est.n_output_f... | ['def', 'test_num_combinations(n_features,', 'min_degree,', 'max_degree,', 'interaction_only,', 'include_bias,', 'csr_container):', 'x', '=', 'csr_container(([1],', '([0],', '[n_features', '-', '1])))', 'est', '=', 'PolynomialFeatures(degree=max_degree,', 'interaction_only=interaction_only,', 'include_bias=include_bias... | 854,069 |
devashish-patel/webcam-motion-detector | ipunittest.py | ipdocstring | ipdocstring | Change the function docstring via ip2py. | [
"Change",
"the",
"function",
"docstring",
"via",
"ip2py."
] | def ipdocstring(func):
if func.__doc__ is not None:
func.__doc__ = ip2py(func.__doc__)
return func | ['def', 'ipdocstring(func):', 'if', 'func.__doc__', 'is', 'not', 'None:', 'func.__doc__', '=', 'ip2py(func.__doc__)', 'return', 'func'] | 979,328 |
denisyarats/exorl | quadruped.py | Physics.target_position | target_position | Returns target position in torso frame. | [
"Returns",
"target",
"position",
"in",
"torso",
"frame."
] | def target_position(self):
torso_frame = self.named.data.xmat['torso'].reshape(3, 3)
torso_pos = self.named.data.xpos['torso']
torso_to_target = self.named.data.site_xpos['target'] - torso_pos
return torso_to_target.dot(torso_frame) | ['def', 'target_position(self):', 'torso_frame', '=', "self.named.data.xmat['torso'].reshape(3,", '3)', 'torso_pos', '=', "self.named.data.xpos['torso']", 'torso_to_target', '=', "self.named.data.site_xpos['target']", '-', 'torso_pos', 'return', 'torso_to_target.dot(torso_frame)'] | 563,598 |
aasimkhan0207/computer_vision | net_spec.py | param_name_dict | param_name_dict | Find out the correspondence between layer names and parameter names. | [
"Find",
"out",
"the",
"correspondence",
"between",
"layer",
"names",
"and",
"parameter",
"names."
] | def param_name_dict():
layer = caffe_pb2.LayerParameter()
param_names = [s for s in dir(layer) if s.endswith('_param')]
param_type_names = [type(getattr(layer, s)).__name__ for s in param_names]
param_names = [s[:-len('_param')] for s in param_names]
param_type_names = [s[:-len('Parameter')] for s i... | ['def', 'param_name_dict():', 'layer', '=', 'caffe_pb2.LayerParameter()', 'param_names', '=', '[s', 'for', 's', 'in', 'dir(layer)', 'if', "s.endswith('_param')]", 'param_type_names', '=', '[type(getattr(layer,', 's)).__name__', 'for', 's', 'in', 'param_names]', 'param_names', '=', "[s[:-len('_param')]", 'for', 's', 'in... | 472,789 |
xvjiarui/VFS | test_loading.py | TestLoading.check_keys_contain | check_keys_contain | Check if all elements in target_keys is in result_keys. | [
"Check",
"if",
"all",
"elements",
"in",
"target_keys",
"is",
"in",
"result_keys."
] | def check_keys_contain(result_keys, target_keys):
return set(target_keys).issubset(set(result_keys)) | ['def', 'check_keys_contain(result_keys,', 'target_keys):', 'return', 'set(target_keys).issubset(set(result_keys))'] | 379,705 |
NJU-LHRS/official-CMID | loss_utils.py | focal_l1_loss | focal_l1_loss | Calculate Focal L1 loss. | [
"Calculate",
"Focal",
"L1",
"loss."
] | def focal_l1_loss(pred, target, alpha=0.2, gamma=1.0, activate='sigmoid', residual=False, weight=None, reduction='mean', **kwargs):
_loss = F.l1_loss(pred, target, reduction='none')
if activate == 'tanh':
loss = _loss * torch.tanh(alpha * _loss) ** gamma
else:
loss = _loss * (2.0 * torch.sig... | ['def', 'focal_l1_loss(pred,', 'target,', 'alpha=0.2,', 'gamma=1.0,', "activate='sigmoid',", 'residual=False,', 'weight=None,', "reduction='mean',", '**kwargs):', '_loss', '=', 'F.l1_loss(pred,', 'target,', "reduction='none')", 'if', 'activate', '==', "'tanh':", 'loss', '=', '_loss', '*', 'torch.tanh(alpha', '*', '_los... | 250,195 |
atulkum/object_detection | config_util_test.py | ConfigUtilTest.testGetNumberOfClasses | testGetNumberOfClasses | Tests that number of classes can be retrieved. | [
"Tests",
"that",
"number",
"of",
"classes",
"can",
"be",
"retrieved."
] | def testGetNumberOfClasses(self):
pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config')
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
pipeline_config.model.faster_rcnn.num_classes = 20
_write_config(pipeline_config, pipeline_config_path)
configs = config_util.get_con... | ['def', 'testGetNumberOfClasses(self):', 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.model.faster_rcnn.num_classes', '=', '20', '_write_config(pipeline_config,', 'pipeline_config_path)', 'confi... | 791,946 |
YanZiQinKevin/object_detection | config_util_test.py | ConfigUtilTest.testOverwriteBatchSizeWithKeyValue | testOverwriteBatchSizeWithKeyValue | Tests that batch size is overwritten based on key/value. | [
"Tests",
"that",
"batch",
"size",
"is",
"overwritten",
"based",
"on",
"key/value."
] | def testOverwriteBatchSizeWithKeyValue(self):
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
pipeline_config.train_config.batch_size = 2
configs = self._create_and_load_test_configs(pipeline_config)
hparams = tf.contrib.training.HParams(**{'train_config.batch_size': 10})
configs = config_u... | ['def', 'testOverwriteBatchSizeWithKeyValue(self):', 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.train_config.batch_size', '=', '2', 'configs', '=', 'self._create_and_load_test_configs(pipeline_config)', 'hparams', '=', "tf.contrib.training.HParams(**{'train_config.batch_size':", ... | 792,849 |
zzndream/ShipRSImageNet | test_assigner.py | test_point_assigner_with_empty_gt | test_point_assigner_with_empty_gt | Test corner case where an image might have no true detections. | [
"Test",
"corner",
"case",
"where",
"an",
"image",
"might",
"have",
"no",
"true",
"detections."
] | def test_point_assigner_with_empty_gt():
self = PointAssigner()
points = torch.FloatTensor([[0, 0, 1], [10, 10, 1], [5, 5, 1], [32, 32, 1]])
gt_bboxes = torch.FloatTensor([])
assign_result = self.assign(points, gt_bboxes)
expected_gt_inds = torch.LongTensor([0, 0, 0, 0])
assert torch.all(assign_... | ['def', 'test_point_assigner_with_empty_gt():', 'self', '=', 'PointAssigner()', 'points', '=', 'torch.FloatTensor([[0,', '0,', '1],', '[10,', '10,', '1],', '[5,', '5,', '1],', '[32,', '32,', '1]])', 'gt_bboxes', '=', 'torch.FloatTensor([])', 'assign_result', '=', 'self.assign(points,', 'gt_bboxes)', 'expected_gt_inds',... | 933,651 |
danamyu/hedgehog_detector | network_units.py | ConvNetwork.create | create | Requires |stride|; otherwise see base class. | [
"Requires",
"|stride|;",
"otherwise",
"see",
"base",
"class."
] | def create(self, fixed_embeddings, linked_embeddings, context_tensor_arrays, attention_tensor, during_training, stride=None):
if stride is None:
raise RuntimeError("ConvNetwork needs 'stride' and must be called in the bulk feature extractor component.")
input_tensor = get_input_tensor_with_stride(fixed_... | ['def', 'create(self,', 'fixed_embeddings,', 'linked_embeddings,', 'context_tensor_arrays,', 'attention_tensor,', 'during_training,', 'stride=None):', 'if', 'stride', 'is', 'None:', 'raise', 'RuntimeError("ConvNetwork', 'needs', "'stride'", 'and', 'must', 'be', 'called', 'in', 'the', 'bulk', 'feature', 'extractor', 'co... | 590,615 |
rudranil723/mini-main | accessor.py | SparseFrameAccessor.density | density | Ratio of non-sparse points to total (dense) data points. | [
"Ratio",
"of",
"non-sparse",
"points",
"to",
"total",
"(dense)",
"data",
"points."
] | def density(self) -> float:
tmp = np.mean([column.array.density for (_, column) in self._parent.items()])
return tmp | ['def', 'density(self)', '->', 'float:', 'tmp', '=', 'np.mean([column.array.density', 'for', '(_,', 'column)', 'in', 'self._parent.items()])', 'return', 'tmp'] | 323,545 |
mit-han-lab/hardware-aware-transformers | progress_bar.py | simple_progress_bar.log | log | Log intermediate stats according to log_interval. | [
"Log",
"intermediate",
"stats",
"according",
"to",
"log_interval."
] | def log(self, stats, tag='', step=None):
self.stats = self._format_stats(stats) | ['def', 'log(self,', 'stats,', "tag='',", 'step=None):', 'self.stats', '=', 'self._format_stats(stats)'] | 576,019 |
tensorflow/agents | qtopt_cem_actions_sampler_hybrid.py | GaussianActionsSampler.sample_batch_and_clip | sample_batch_and_clip | Samples and clips a batch of actions [B, N, A] with mean and var. | [
"Samples",
"and",
"clips",
"a",
"batch",
"of",
"actions",
"[B,",
"N,",
"A]",
"with",
"mean",
"and",
"var."
] | def sample_batch_and_clip(self, num_samples, mean, var, state=None):
def sample_and_transpose(mean, var, spec):
dist = tfp.distributions.Normal(loc=mean, scale=tf.sqrt(var))
sample = tf.transpose(dist.sample(num_samples), [1, 0, 2])
return tf.cast(sample, spec.dtype)
samples = tf.nest.m... | ['def', 'sample_batch_and_clip(self,', 'num_samples,', 'mean,', 'var,', 'state=None):', 'def', 'sample_and_transpose(mean,', 'var,', 'spec):', 'dist', '=', 'tfp.distributions.Normal(loc=mean,', 'scale=tf.sqrt(var))', 'sample', '=', 'tf.transpose(dist.sample(num_samples),', '[1,', '0,', '2])', 'return', 'tf.cast(sample,... | 22,891 |
deephyper/deephyper | _introspection.py | get_init_params_as_json | get_init_params_as_json | Get the parameters of an object in a json format. | [
"Get",
"the",
"parameters",
"of",
"an",
"object",
"in",
"a",
"json",
"format."
] | def get_init_params_as_json(obj):
if hasattr(obj, '_init_params'):
base_init_params = obj._init_params
if 'self' in base_init_params:
base_init_params.pop('self')
else:
base_init_params = dict()
params = dict()
for (k, v) in base_init_params.items():
if '__' n... | ['def', 'get_init_params_as_json(obj):', 'if', 'hasattr(obj,', "'_init_params'):", 'base_init_params', '=', 'obj._init_params', 'if', "'self'", 'in', 'base_init_params:', "base_init_params.pop('self')", 'else:', 'base_init_params', '=', 'dict()', 'params', '=', 'dict()', 'for', '(k,', 'v)', 'in', 'base_init_params.item... | 520,770 |
JoyHuYY1412/Class_Imbalanced_Semi_Supervised_Learning | augmentations.py | create_cutout_mask | create_cutout_mask | Creates a zero mask used for cutout of shape `img_height` x `img_width`. | [
"Creates",
"a",
"zero",
"mask",
"used",
"for",
"cutout",
"of",
"shape",
"`img_height`",
"x",
"`img_width`."
] | def create_cutout_mask(img_height, img_width, num_channels, size):
assert img_height == img_width
height_loc = np.random.randint(low=0, high=img_height)
width_loc = np.random.randint(low=0, high=img_width)
upper_coord = (max(0, height_loc - size // 2), max(0, width_loc - size // 2))
lower_coord = (m... | ['def', 'create_cutout_mask(img_height,', 'img_width,', 'num_channels,', 'size):', 'assert', 'img_height', '==', 'img_width', 'height_loc', '=', 'np.random.randint(low=0,', 'high=img_height)', 'width_loc', '=', 'np.random.randint(low=0,', 'high=img_width)', 'upper_coord', '=', '(max(0,', 'height_loc', '-', 'size', '//'... | 122,279 |
google-research/scenic | trainer.py | eval_and_log_summary | eval_and_log_summary | Eval the model and write the summary. | [
"Eval",
"the",
"model",
"and",
"write",
"the",
"summary."
] | def eval_and_log_summary(*, train_state: utils.OptaxTrainState, writer: metric_writers.MetricWriter, iterator, eval_step_fn, eval_steps, train_iteration, num_eval_examples, compute_recall_metrics=True, text_to_video_retrieval=True):
output_dicts = {}
logging.info('Total number of eval steps is %s', eval_steps)
... | ['def', 'eval_and_log_summary(*,', 'train_state:', 'utils.OptaxTrainState,', 'writer:', 'metric_writers.MetricWriter,', 'iterator,', 'eval_step_fn,', 'eval_steps,', 'train_iteration,', 'num_eval_examples,', 'compute_recall_metrics=True,', 'text_to_video_retrieval=True):', 'output_dicts', '=', '{}', "logging.info('Total... | 847,485 |
sek788432/Waymo-2D-Object-Detection | create_cococameratraps_tfexample_main.py | create_pipeline | create_pipeline | Creates a beam pipeline for producing a COCO-CameraTraps Image dataset. | [
"Creates",
"a",
"beam",
"pipeline",
"for",
"producing",
"a",
"COCO-CameraTraps",
"Image",
"dataset."
] | def create_pipeline(pipeline, image_directory, input_annotations_file, output_tfrecord_prefix=None, num_images_per_shard=200, keep_bboxes=True):
data = load_json_data(input_annotations_file)
num_shards = int(np.ceil(float(len(data['images'])) / num_images_per_shard))
image_examples = pipeline | 'CreateColle... | ['def', 'create_pipeline(pipeline,', 'image_directory,', 'input_annotations_file,', 'output_tfrecord_prefix=None,', 'num_images_per_shard=200,', 'keep_bboxes=True):', 'data', '=', 'load_json_data(input_annotations_file)', 'num_shards', '=', "int(np.ceil(float(len(data['images']))", '/', 'num_images_per_shard))', 'image... | 974,966 |
muziyongshixin/pytorch-DCGAN-Humanface | transformed.py | crop | crop | Crop the given PIL Image. | [
"Crop",
"the",
"given",
"PIL",
"Image."
] | def crop(img, i, j, h, w):
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
return img.crop((j, i, j + w, i + h)) | ['def', 'crop(img,', 'i,', 'j,', 'h,', 'w):', 'if', 'not', '_is_pil_image(img):', 'raise', "TypeError('img", 'should', 'be', 'PIL', 'Image.', 'Got', "{}'.format(type(img)))", 'return', 'img.crop((j,', 'i,', 'j', '+', 'w,', 'i', '+', 'h))'] | 814,402 |
IRDG2OI/artus | coco_stats.py | rm_tiles_without_annot | rm_tiles_without_annot | Remove tiles without annotations. | [
"Remove",
"tiles",
"without",
"annotations."
] | def rm_tiles_without_annot(dataset):
ind_images_without_annot = dataset.df.loc[dataset.df['cat_name'] == ''].index
dataset.df.drop(index=ind_images_without_annot, inplace=True)
return dataset | ['def', 'rm_tiles_without_annot(dataset):', 'ind_images_without_annot', '=', "dataset.df.loc[dataset.df['cat_name']", '==', "''].index", 'dataset.df.drop(index=ind_images_without_annot,', 'inplace=True)', 'return', 'dataset'] | 92,204 |
zihuitang/medical_AI_platform | pydoc.py | doc | doc | Display text documentation, given an object or a path to an object. | [
"Display",
"text",
"documentation,",
"given",
"an",
"object",
"or",
"a",
"path",
"to",
"an",
"object."
] | def doc(thing, title='Python Library Documentation: %s', forceload=0, output=None):
try:
if output is None:
pager(render_doc(thing, title, forceload))
else:
output.write(render_doc(thing, title, forceload, plaintext))
except (ImportError, ErrorDuringImport) as value:
... | ['def', 'doc(thing,', "title='Python", 'Library', 'Documentation:', "%s',", 'forceload=0,', 'output=None):', 'try:', 'if', 'output', 'is', 'None:', 'pager(render_doc(thing,', 'title,', 'forceload))', 'else:', 'output.write(render_doc(thing,', 'title,', 'forceload,', 'plaintext))', 'except', '(ImportError,', 'ErrorDurin... | 281,204 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | socket.py | socket.family | family | Read-only access to the address family for this socket. | [
"Read-only",
"access",
"to",
"the",
"address",
"family",
"for",
"this",
"socket."
] | def family(self):
return _intenum_converter(super().family, AddressFamily) | ['def', 'family(self):', 'return', '_intenum_converter(super().family,', 'AddressFamily)'] | 429,492 |
IntelAI/transfer-learning | test_models.py | test_pytorch_hf_text_classification_trainer_without_val_subset | test_pytorch_hf_text_classification_trainer_without_val_subset | Tests the PyTorch Text Classification model with the Hugging Face Trainer is able to run evaluation with a test subset when a validation subset does not exist. | [
"Tests",
"the",
"PyTorch",
"Text",
"Classification",
"model",
"with",
"the",
"Hugging",
"Face",
"Trainer",
"is",
"able",
"to",
"run",
"evaluation",
"with",
"a",
"test",
"subset",
"when",
"a",
"validation",
"subset",
"does",
"not",
"exist."
] | def test_pytorch_hf_text_classification_trainer_without_val_subset(mock_downloader, mock_trainer, mock_optimizer):
model = model_factory.get_model(model_name='bert-base-cased', framework='pytorch')
mock_dataset = MagicMock()
mock_dataset.__class__ = HFTextClassificationDataset
mock_dataset.class_names =... | ['def', 'test_pytorch_hf_text_classification_trainer_without_val_subset(mock_downloader,', 'mock_trainer,', 'mock_optimizer):', 'model', '=', "model_factory.get_model(model_name='bert-base-cased',", "framework='pytorch')", 'mock_dataset', '=', 'MagicMock()', 'mock_dataset.__class__', '=', 'HFTextClassificationDataset',... | 926,748 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | tarfile.py | TarFile.makedir | makedir | Make a directory called targetpath. | [
"Make",
"a",
"directory",
"called",
"targetpath."
] | def makedir(self, tarinfo, targetpath):
try:
os.mkdir(targetpath, 448)
except EnvironmentError as e:
if e.errno != errno.EEXIST:
raise | ['def', 'makedir(self,', 'tarinfo,', 'targetpath):', 'try:', 'os.mkdir(targetpath,', '448)', 'except', 'EnvironmentError', 'as', 'e:', 'if', 'e.errno', '!=', 'errno.EEXIST:', 'raise'] | 259,369 |
ag93/Natural-Language-Processing | a2_test.py | TestA2.test_hmm_fit_transition_smoothed | test_hmm_fit_transition_smoothed | Test supervised HMM learning. | [
"Test",
"supervised",
"HMM",
"learning."
] | def test_hmm_fit_transition_smoothed(self):
model = HMM(smoothing=1)
model.fit(test_sentences, test_tags)
self.assertEqual(0.571, round(model.transition_probas['N']['V'], 3))
self.assertEqual(0.143, round(model.transition_probas['N']['D'], 3))
self.assertEqual(0.286, round(model.transition_probas['N... | ['def', 'test_hmm_fit_transition_smoothed(self):', 'model', '=', 'HMM(smoothing=1)', 'model.fit(test_sentences,', 'test_tags)', 'self.assertEqual(0.571,', "round(model.transition_probas['N']['V'],", '3))', 'self.assertEqual(0.143,', "round(model.transition_probas['N']['D'],", '3))', 'self.assertEqual(0.286,', "round(mo... | 703,705 |
PacktPublishing/Hands-On-Reinforcement-Learning-for-Games | util.py | log_floors | log_floors | For all the completed episodes in a rollout, print to standard output the attained floor numbers. | [
"For",
"all",
"the",
"completed",
"episodes",
"in",
"a",
"rollout,",
"print",
"to",
"standard",
"output",
"the",
"attained",
"floor",
"numbers."
] | def log_floors(rollout):
for t in range(1, rollout.num_steps):
for b in range(rollout.batch_size):
if rollout.dones[t, b]:
info = rollout.infos[t - 2][b]
if 'start_floor' in info:
print('start=%d floor=%d' % (info['start_floor'], info['current_... | ['def', 'log_floors(rollout):', 'for', 't', 'in', 'range(1,', 'rollout.num_steps):', 'for', 'b', 'in', 'range(rollout.batch_size):', 'if', 'rollout.dones[t,', 'b]:', 'info', '=', 'rollout.infos[t', '-', '2][b]', 'if', "'start_floor'", 'in', 'info:', "print('start=%d", "floor=%d'", '%', "(info['start_floor'],", "info['c... | 205,195 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | utils.py | tensor_bxtxn_to_list_t_bxn | tensor_bxtxn_to_list_t_bxn | Convert a numpy tensor with shape BxTxN to a length T list of numpy tensors with shape BxT. | [
"Convert",
"a",
"numpy",
"tensor",
"with",
"shape",
"BxTxN",
"to",
"a",
"length",
"T",
"list",
"of",
"numpy",
"tensors",
"with",
"shape",
"BxT."
] | def tensor_bxtxn_to_list_t_bxn(tensor_bxtxn):
values_t_bxn = []
(B, T, N) = tensor_bxtxn.shape
for t in range(T):
values_t_bxn.append(np.squeeze(tensor_bxtxn[:, t, :]))
return values_t_bxn | ['def', 'tensor_bxtxn_to_list_t_bxn(tensor_bxtxn):', 'values_t_bxn', '=', '[]', '(B,', 'T,', 'N)', '=', 'tensor_bxtxn.shape', 'for', 't', 'in', 'range(T):', 'values_t_bxn.append(np.squeeze(tensor_bxtxn[:,', 't,', ':]))', 'return', 'values_t_bxn'] | 56,124 |
apeterswu/RL4NMT | transformer.py | transformer_prepare_encoder | transformer_prepare_encoder | Prepare one shard of the model for the encoder. | [
"Prepare",
"one",
"shard",
"of",
"the",
"model",
"for",
"the",
"encoder."
] | def transformer_prepare_encoder(inputs, target_space, hparams):
ishape_static = inputs.shape.as_list()
encoder_input = inputs
encoder_padding = common_attention.embedding_to_padding(encoder_input)
ignore_padding = common_attention.attention_bias_ignore_padding(encoder_padding)
encoder_self_attention... | ['def', 'transformer_prepare_encoder(inputs,', 'target_space,', 'hparams):', 'ishape_static', '=', 'inputs.shape.as_list()', 'encoder_input', '=', 'inputs', 'encoder_padding', '=', 'common_attention.embedding_to_padding(encoder_input)', 'ignore_padding', '=', 'common_attention.attention_bias_ignore_padding(encoder_padd... | 331,172 |
LiYingwei/ghost-network | resnet_v2_101.py | resnet_v2_block | resnet_v2_block | Helper function for creating a resnet_v2 bottleneck block. | [
"Helper",
"function",
"for",
"creating",
"a",
"resnet_v2",
"bottleneck",
"block."
] | def resnet_v2_block(scope, base_depth, num_units, stride):
return resnet_utils.Block(scope, bottleneck, [{'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': 1}] * (num_units - 1) + [{'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': stride}]) | ['def', 'resnet_v2_block(scope,', 'base_depth,', 'num_units,', 'stride):', 'return', 'resnet_utils.Block(scope,', 'bottleneck,', "[{'depth':", 'base_depth', '*', '4,', "'depth_bottleneck':", 'base_depth,', "'stride':", '1}]', '*', '(num_units', '-', '1)', '+', "[{'depth':", 'base_depth', '*', '4,', "'depth_bottleneck':... | 557,940 |
instadeepai/jumanji | actor_critic.py | make_actor_critic_networks_rubiks_cube | make_actor_critic_networks_rubiks_cube | Make actor-critic networks for the `RubiksCube` environment. | [
"Make",
"actor-critic",
"networks",
"for",
"the",
"`RubiksCube`",
"environment."
] | def make_actor_critic_networks_rubiks_cube(rubiks_cube: RubiksCube, cube_embed_dim: int, step_count_embed_dim: int, dense_layer_dims: Sequence[int]) -> ActorCriticNetworks:
action_spec_num_values = np.asarray(rubiks_cube.action_spec().num_values)
num_actions = int(np.prod(action_spec_num_values))
parametric... | ['def', 'make_actor_critic_networks_rubiks_cube(rubiks_cube:', 'RubiksCube,', 'cube_embed_dim:', 'int,', 'step_count_embed_dim:', 'int,', 'dense_layer_dims:', 'Sequence[int])', '->', 'ActorCriticNetworks:', 'action_spec_num_values', '=', 'np.asarray(rubiks_cube.action_spec().num_values)', 'num_actions', '=', 'int(np.pr... | 594,633 |
jimtin/Stock_Comparison | ctypeslib.py | prep_pointer | prep_pointer | Given a ctypes pointer object, construct and attach an __array_interface__ property to it if it does not yet have one. | [
"Given",
"a",
"ctypes",
"pointer",
"object,",
"construct",
"and",
"attach",
"an",
"__array_interface__",
"property",
"to",
"it",
"if",
"it",
"does",
"not",
"yet",
"have",
"one."
] | def prep_pointer(pointer_obj, shape):
try:
pointer_obj.__array_interface__
except AttributeError:
pass
else:
return
contents = pointer_obj.contents
dtype = _dtype(type(contents))
inter = {'version': 3, 'typestr': dtype.str, 'data': (ct.addressof(contents), False), 'shape'... | ['def', 'prep_pointer(pointer_obj,', 'shape):', 'try:', 'pointer_obj.__array_interface__', 'except', 'AttributeError:', 'pass', 'else:', 'return', 'contents', '=', 'pointer_obj.contents', 'dtype', '=', '_dtype(type(contents))', 'inter', '=', "{'version':", '3,', "'typestr':", 'dtype.str,', "'data':", '(ct.addressof(con... | 386,628 |
deepmind/dm_control | basic_cmu_2019.py | cmu_humanoid_run_gaps | cmu_humanoid_run_gaps | Requires a CMU humanoid to run down a corridor with gaps. | [
"Requires",
"a",
"CMU",
"humanoid",
"to",
"run",
"down",
"a",
"corridor",
"with",
"gaps."
] | def cmu_humanoid_run_gaps(random_state=None):
walker = cmu_humanoid.CMUHumanoidPositionControlled(observable_options={'egocentric_camera': dict(enabled=True)})
arena = corr_arenas.GapsCorridor(platform_length=distributions.Uniform(0.3, 2.5), gap_length=distributions.Uniform(0.5, 1.25), corridor_width=10, corrid... | ['def', 'cmu_humanoid_run_gaps(random_state=None):', 'walker', '=', "cmu_humanoid.CMUHumanoidPositionControlled(observable_options={'egocentric_camera':", 'dict(enabled=True)})', 'arena', '=', 'corr_arenas.GapsCorridor(platform_length=distributions.Uniform(0.3,', '2.5),', 'gap_length=distributions.Uniform(0.5,', '1.25)... | 165,918 |
takuseno/d3rlpy | explorers.py | NormalNoise.sample | sample | Returns action with noise injection. | [
"Returns",
"action",
"with",
"noise",
"injection."
] | def sample(self, algo: _ActionProtocol, x: np.ndarray, step: int) -> np.ndarray:
action = algo.predict(x)
noise = np.random.normal(self._mean, self._std, size=action.shape)
if isinstance(algo.action_scaler, MinMaxActionScaler):
minimum = algo.action_scaler.minimum
maximum = algo.action_scale... | ['def', 'sample(self,', 'algo:', '_ActionProtocol,', 'x:', 'np.ndarray,', 'step:', 'int)', '->', 'np.ndarray:', 'action', '=', 'algo.predict(x)', 'noise', '=', 'np.random.normal(self._mean,', 'self._std,', 'size=action.shape)', 'if', 'isinstance(algo.action_scaler,', 'MinMaxActionScaler):', 'minimum', '=', 'algo.action... | 197,911 |
shreedharv16/Natural-Language-Processing | a4.py | average_f1s | average_f1s | Returns: The average F1 score for all NER tags, EXCLUDING the O tag. | [
"Returns:",
"The",
"average",
"F1",
"score",
"for",
"all",
"NER",
"tags,",
"EXCLUDING",
"the",
"O",
"tag."
] | def average_f1s(evaluation_matrix):
s = 0
for c in evaluation_matrix.columns:
if c != 'O':
s += evaluation_matrix.get_value('f1', c)
if len(evaluation_matrix.columns) - 1 == 0:
avg = 0
else:
avg = s / (len(evaluation_matrix.columns) - 1)
return avg | ['def', 'average_f1s(evaluation_matrix):', 's', '=', '0', 'for', 'c', 'in', 'evaluation_matrix.columns:', 'if', 'c', '!=', "'O':", 's', '+=', "evaluation_matrix.get_value('f1',", 'c)', 'if', 'len(evaluation_matrix.columns)', '-', '1', '==', '0:', 'avg', '=', '0', 'else:', 'avg', '=', 's', '/', '(len(evaluation_matrix.c... | 704,645 |
Hisakaki233/NaturalLanguageProcessing | modeling.py | reshape_from_matrix | reshape_from_matrix | Reshapes a rank 2 tensor back to its original rank >= 2 tensor. | [
"Reshapes",
"a",
"rank",
"2",
"tensor",
"back",
"to",
"its",
"original",
"rank",
">=",
"2",
"tensor."
] | def reshape_from_matrix(output_tensor, orig_shape_list):
if len(orig_shape_list) == 2:
return output_tensor
output_shape = get_shape_list(output_tensor)
orig_dims = orig_shape_list[0:-1]
width = output_shape[-1]
return tf.reshape(output_tensor, orig_dims + [width]) | ['def', 'reshape_from_matrix(output_tensor,', 'orig_shape_list):', 'if', 'len(orig_shape_list)', '==', '2:', 'return', 'output_tensor', 'output_shape', '=', 'get_shape_list(output_tensor)', 'orig_dims', '=', 'orig_shape_list[0:-1]', 'width', '=', 'output_shape[-1]', 'return', 'tf.reshape(output_tensor,', 'orig_dims', '... | 711,478 |
Shubham-786/Natural-Language-Processing | Spell_checker.py | Spell_Checker.Language_Model.smooth | smooth | Returns the smoothed (Laplace) probability of the specified ngram. | [
"Returns",
"the",
"smoothed",
"(Laplace)",
"probability",
"of",
"the",
"specified",
"ngram."
] | def smooth(self, ngram):
trimmed_ngram = ngram[0:ngram.rindex(' ')]
V = len(self.model_trimmed_dict)
upper_c = 0 if ngram not in self.model_dict else self.model_dict[ngram]
lower_c = 0 if trimmed_ngram not in self.model_trimmed_dict else self.model_trimmed_dict[trimmed_ngram]
return (upper_c + 1) / ... | ['def', 'smooth(self,', 'ngram):', 'trimmed_ngram', '=', "ngram[0:ngram.rindex('", "')]", 'V', '=', 'len(self.model_trimmed_dict)', 'upper_c', '=', '0', 'if', 'ngram', 'not', 'in', 'self.model_dict', 'else', 'self.model_dict[ngram]', 'lower_c', '=', '0', 'if', 'trimmed_ngram', 'not', 'in', 'self.model_trimmed_dict', 'e... | 706,737 |
ucas-vg/PointTinyBenchmark | mean_ap.py | eval_map | eval_map | Evaluate mAP of a dataset. | [
"Evaluate",
"mAP",
"of",
"a",
"dataset."
] | def eval_map(det_results, annotations, scale_ranges=None, iou_thr=0.5, dataset=None, logger=None, tpfp_fn=None, nproc=4):
assert len(det_results) == len(annotations)
num_imgs = len(det_results)
num_scales = len(scale_ranges) if scale_ranges is not None else 1
num_classes = len(det_results[0])
area_r... | ['def', 'eval_map(det_results,', 'annotations,', 'scale_ranges=None,', 'iou_thr=0.5,', 'dataset=None,', 'logger=None,', 'tpfp_fn=None,', 'nproc=4):', 'assert', 'len(det_results)', '==', 'len(annotations)', 'num_imgs', '=', 'len(det_results)', 'num_scales', '=', 'len(scale_ranges)', 'if', 'scale_ranges', 'is', 'not', 'N... | 781,430 |
jshankman/Artificial-Intelligence | csp.py | CSP.result | result | Perform an action and return the new state. | [
"Perform",
"an",
"action",
"and",
"return",
"the",
"new",
"state."
] | def result(self, state, action):
(var, val) = action
return state + ((var, val),) | ['def', 'result(self,', 'state,', 'action):', '(var,', 'val)', '=', 'action', 'return', 'state', '+', '((var,', 'val),)'] | 115,603 |
floydhub/object-detection-template | inputs_test.py | InputsTest.test_error_with_bad_eval_model_config | test_error_with_bad_eval_model_config | Tests that a TypeError is raised with improper eval model config. | [
"Tests",
"that",
"a",
"TypeError",
"is",
"raised",
"with",
"improper",
"eval",
"model",
"config."
] | def test_error_with_bad_eval_model_config(self):
configs = _get_configs_for_model('ssd_inception_v2_pets')
configs['model'].ssd.num_classes = 37
eval_input_fn = inputs.create_eval_input_fn(eval_config=configs['eval_config'], eval_input_config=configs['eval_input_config'], model_config=configs['eval_config']... | ['def', 'test_error_with_bad_eval_model_config(self):', 'configs', '=', "_get_configs_for_model('ssd_inception_v2_pets')", "configs['model'].ssd.num_classes", '=', '37', 'eval_input_fn', '=', "inputs.create_eval_input_fn(eval_config=configs['eval_config'],", "eval_input_config=configs['eval_input_config'],", "model_con... | 747,819 |
Katja-M/Python_NaturalLanguageProcessing | tarfile.py | ExFileObject.close | close | Close the file object. | [
"Close",
"the",
"file",
"object."
] | def close(self):
self.closed = True | ['def', 'close(self):', 'self.closed', '=', 'True'] | 868,615 |
zzndream/ShipRSImageNet | ghm_loss.py | GHMR.forward | forward | Calculate the GHM-R loss. | [
"Calculate",
"the",
"GHM-R",
"loss."
] | def forward(self, pred, target, label_weight, avg_factor=None):
mu = self.mu
edges = self.edges
mmt = self.momentum
diff = pred - target
loss = torch.sqrt(diff * diff + mu * mu) - mu
g = torch.abs(diff / torch.sqrt(mu * mu + diff * diff)).detach()
weights = torch.zeros_like(g)
valid = la... | ['def', 'forward(self,', 'pred,', 'target,', 'label_weight,', 'avg_factor=None):', 'mu', '=', 'self.mu', 'edges', '=', 'self.edges', 'mmt', '=', 'self.momentum', 'diff', '=', 'pred', '-', 'target', 'loss', '=', 'torch.sqrt(diff', '*', 'diff', '+', 'mu', '*', 'mu)', '-', 'mu', 'g', '=', 'torch.abs(diff', '/', 'torch.sqr... | 901,321 |
FederatedAI/FedVision | vars_distributed.py | VarsDistributed.get_distributed_var_by_slice | get_distributed_var_by_slice | get distributed var by conditions. | [
"get",
"distributed",
"var",
"by",
"conditions."
] | def get_distributed_var_by_slice(self, var_name):
for dist_var in self.distributed_vars:
if dist_var.slice.name == var_name:
return dist_var
return None | ['def', 'get_distributed_var_by_slice(self,', 'var_name):', 'for', 'dist_var', 'in', 'self.distributed_vars:', 'if', 'dist_var.slice.name', '==', 'var_name:', 'return', 'dist_var', 'return', 'None'] | 581,837 |
suigingin/NaturalLanguageProcessing | modeling.py | create_attention_mask_from_input_mask | create_attention_mask_from_input_mask | Create 3D attention mask from a 2D tensor mask. | [
"Create",
"3D",
"attention",
"mask",
"from",
"a",
"2D",
"tensor",
"mask."
] | def create_attention_mask_from_input_mask(from_tensor, to_mask):
from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
batch_size = from_shape[0]
from_seq_length = from_shape[1]
to_shape = get_shape_list(to_mask, expected_rank=2)
to_seq_length = to_shape[1]
to_mask = tf.cast(tf.reshape(... | ['def', 'create_attention_mask_from_input_mask(from_tensor,', 'to_mask):', 'from_shape', '=', 'get_shape_list(from_tensor,', 'expected_rank=[2,', '3])', 'batch_size', '=', 'from_shape[0]', 'from_seq_length', '=', 'from_shape[1]', 'to_shape', '=', 'get_shape_list(to_mask,', 'expected_rank=2)', 'to_seq_length', '=', 'to_... | 711,534 |
sshleifer/object_detection_kitti | model.py | Model.trust_region_step | trust_region_step | Train policy using trust region step. | [
"Train",
"policy",
"using",
"trust",
"region",
"step."
] | def trust_region_step(self, sess, observations, internal_state, actions, rewards, terminated, pads, avg_episode_reward=0):
feed_dict = {self.internal_state: internal_state, self.rewards: rewards, self.terminated: terminated, self.pads: pads, self.avg_episode_reward: avg_episode_reward}
for (action_place, action... | ['def', 'trust_region_step(self,', 'sess,', 'observations,', 'internal_state,', 'actions,', 'rewards,', 'terminated,', 'pads,', 'avg_episode_reward=0):', 'feed_dict', '=', '{self.internal_state:', 'internal_state,', 'self.rewards:', 'rewards,', 'self.terminated:', 'terminated,', 'self.pads:', 'pads,', 'self.avg_episode... | 795,348 |
nilearn/nilearn | test_signal_extraction.py | test_signals_extraction_with_labels_with_mask | test_signals_extraction_with_labels_with_mask | Test conversion between signals and images using regions defined by labels with a mask. | [
"Test",
"conversion",
"between",
"signals",
"and",
"images",
"using",
"regions",
"defined",
"by",
"labels",
"with",
"a",
"mask."
] | def test_signals_extraction_with_labels_with_mask(signals, labels_img, labels_data, mask_img, shape_3d_default):
data_img = signals_to_img_labels(signals=signals, labels_img=labels_img, mask_img=mask_img)
assert data_img.shape == shape_3d_default + (N_TIMEPOINTS,)
data = get_data(data_img)
assert abs(da... | ['def', 'test_signals_extraction_with_labels_with_mask(signals,', 'labels_img,', 'labels_data,', 'mask_img,', 'shape_3d_default):', 'data_img', '=', 'signals_to_img_labels(signals=signals,', 'labels_img=labels_img,', 'mask_img=mask_img)', 'assert', 'data_img.shape', '==', 'shape_3d_default', '+', '(N_TIMEPOINTS,)', 'da... | 724,252 |
hkzhang95/DynamicRCNN | mask_target_opr.py | mask_target_opr | mask_target_opr | Generate proposal targets for computing loss. | [
"Generate",
"proposal",
"targets",
"for",
"computing",
"loss."
] | def mask_target_opr(proposals, targets, high_threshold, low_threshold, discretization_size):
matcher = Matcher(high_threshold, low_threshold, allow_low_quality_matches=False)
labels = []
masks = []
for (proposals_per_image, targets_per_image) in zip(proposals, targets):
match_quality_matrix = bo... | ['def', 'mask_target_opr(proposals,', 'targets,', 'high_threshold,', 'low_threshold,', 'discretization_size):', 'matcher', '=', 'Matcher(high_threshold,', 'low_threshold,', 'allow_low_quality_matches=False)', 'labels', '=', '[]', 'masks', '=', '[]', 'for', '(proposals_per_image,', 'targets_per_image)', 'in', 'zip(propo... | 174,322 |
rudranil723/mini-main | __init__.py | Channel.unary_unary | unary_unary | Creates a UnaryUnaryMultiCallable for a unary-unary method. | [
"Creates",
"a",
"UnaryUnaryMultiCallable",
"for",
"a",
"unary-unary",
"method."
] | def unary_unary(self, method, request_serializer=None, response_deserializer=None):
raise NotImplementedError() | ['def', 'unary_unary(self,', 'method,', 'request_serializer=None,', 'response_deserializer=None):', 'raise', 'NotImplementedError()'] | 318,577 |
priorfire4411/artificial_intelligence | six.py | with_metaclass | with_metaclass | Create a base class with a metaclass. | [
"Create",
"a",
"base",
"class",
"with",
"a",
"metaclass."
] | def with_metaclass(meta, *bases):
class metaclass(type):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
@classmethod
def __prepare__(cls, name, this_bases):
return meta.__prepare__(name, bases)
return type.__new__(metaclass, 'temporary_class... | ['def', 'with_metaclass(meta,', '*bases):', 'class', 'metaclass(type):', 'def', '__new__(cls,', 'name,', 'this_bases,', 'd):', 'return', 'meta(name,', 'bases,', 'd)', '@classmethod', 'def', '__prepare__(cls,', 'name,', 'this_bases):', 'return', 'meta.__prepare__(name,', 'bases)', 'return', 'type.__new__(metaclass,', "'... | 74,317 |
adamshamsudeen/vision.ai | six.py | exec_ | exec_ | Execute code in a namespace. | [
"Execute",
"code",
"in",
"a",
"namespace."
] | def exec_(_code_, _globs_=None, _locs_=None):
if _globs_ is None:
frame = sys._getframe(1)
_globs_ = frame.f_globals
if _locs_ is None:
_locs_ = frame.f_locals
del frame
elif _locs_ is None:
_locs_ = _globs_
exec('exec _code_ in _globs_, _locs_') | ['def', 'exec_(_code_,', '_globs_=None,', '_locs_=None):', 'if', '_globs_', 'is', 'None:', 'frame', '=', 'sys._getframe(1)', '_globs_', '=', 'frame.f_globals', 'if', '_locs_', 'is', 'None:', '_locs_', '=', 'frame.f_locals', 'del', 'frame', 'elif', '_locs_', 'is', 'None:', '_locs_', '=', '_globs_', "exec('exec", '_code_... | 944,307 |
adamshamsudeen/vision.ai | testtools.py | ContentAccessors.lxml | lxml | Get an lxml etree if possible. | [
"Get",
"an",
"lxml",
"etree",
"if",
"possible."
] | def lxml(self):
if 'html' not in self.mimetype and 'xml' not in self.mimetype:
raise AttributeError('Not an HTML/XML response')
from lxml import etree
try:
from lxml.html import fromstring
except ImportError:
fromstring = etree.HTML
if self.mimetype == 'text/html':
re... | ['def', 'lxml(self):', 'if', "'html'", 'not', 'in', 'self.mimetype', 'and', "'xml'", 'not', 'in', 'self.mimetype:', 'raise', "AttributeError('Not", 'an', 'HTML/XML', "response')", 'from', 'lxml', 'import', 'etree', 'try:', 'from', 'lxml.html', 'import', 'fromstring', 'except', 'ImportError:', 'fromstring', '=', 'etree.... | 944,733 |
fudan-zvg/SETR | misc.py | add_prefix | add_prefix | Add prefix for dict. | [
"Add",
"prefix",
"for",
"dict."
] | def add_prefix(inputs, prefix):
outputs = dict()
for (name, value) in inputs.items():
outputs[f'{prefix}.{name}'] = value
return outputs | ['def', 'add_prefix(inputs,', 'prefix):', 'outputs', '=', 'dict()', 'for', '(name,', 'value)', 'in', 'inputs.items():', "outputs[f'{prefix}.{name}']", '=', 'value', 'return', 'outputs'] | 898,509 |
Hadishh/cs188 | eightpuzzle.py | createRandomEightPuzzle | createRandomEightPuzzle | moves: number of random moves to apply Creates a random eight puzzle by applying a series of 'moves' random moves to a solved puzzle. | [
"moves:",
"number",
"of",
"random",
"moves",
"to",
"apply",
"Creates",
"a",
"random",
"eight",
"puzzle",
"by",
"applying",
"a",
"series",
"of",
"'moves'",
"random",
"moves",
"to",
"a",
"solved",
"puzzle."
] | def createRandomEightPuzzle(moves=100):
puzzle = EightPuzzleState([0, 1, 2, 3, 4, 5, 6, 7, 8])
for i in range(moves):
puzzle = puzzle.result(random.sample(puzzle.legalMoves(), 1)[0])
return puzzle | ['def', 'createRandomEightPuzzle(moves=100):', 'puzzle', '=', 'EightPuzzleState([0,', '1,', '2,', '3,', '4,', '5,', '6,', '7,', '8])', 'for', 'i', 'in', 'range(moves):', 'puzzle', '=', 'puzzle.result(random.sample(puzzle.legalMoves(),', '1)[0])', 'return', 'puzzle'] | 224,828 |
opendilab/DI-star | lib.py | RunConfig.all_subclasses | all_subclasses | An iterator over all subclasses of `cls`. | [
"An",
"iterator",
"over",
"all",
"subclasses",
"of",
"`cls`."
] | def all_subclasses(cls):
for s in cls.__subclasses__():
yield s
for c in s.all_subclasses():
yield c | ['def', 'all_subclasses(cls):', 'for', 's', 'in', 'cls.__subclasses__():', 'yield', 's', 'for', 'c', 'in', 's.all_subclasses():', 'yield', 'c'] | 184,821 |
haibo-qiu/GFNet | lovasz_losses.py | mean | mean | nanmean compatible with generators. | [
"nanmean",
"compatible",
"with",
"generators."
] | def mean(l, ignore_nan=False, empty=0):
l = iter(l)
if ignore_nan:
l = ifilterfalse(isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
return empty
for (n, v) in enumerate(l, 2):
acc... | ['def', 'mean(l,', 'ignore_nan=False,', 'empty=0):', 'l', '=', 'iter(l)', 'if', 'ignore_nan:', 'l', '=', 'ifilterfalse(isnan,', 'l)', 'try:', 'n', '=', '1', 'acc', '=', 'next(l)', 'except', 'StopIteration:', 'if', 'empty', '==', "'raise':", 'raise', "ValueError('Empty", "mean')", 'return', 'empty', 'for', '(n,', 'v)', ... | 557,148 |
zomux/deepy | controllers.py | TrainingValidator.run | run | Run the model with validation data and return costs. | [
"Run",
"the",
"model",
"with",
"validation",
"data",
"and",
"return",
"costs."
] | def run(self, data_x):
output_vars = self.compute(*data_x)
return self._extract_costs(output_vars) | ['def', 'run(self,', 'data_x):', 'output_vars', '=', 'self.compute(*data_x)', 'return', 'self._extract_costs(output_vars)'] | 181,006 |
matsu0228/nlp-jp | vt100_output.py | Vt100_Output.erase_down | erase_down | Erases the screen from the current line down to the bottom of the screen. | [
"Erases",
"the",
"screen",
"from",
"the",
"current",
"line",
"down",
"to",
"the",
"bottom",
"of",
"the",
"screen."
] | def erase_down(self):
self.write_raw('\x1b[J') | ['def', 'erase_down(self):', "self.write_raw('\\x1b[J')"] | 804,585 |
mayurilk/Natural-Language-Processing | beam_search.py | Hypothesis.extend | extend | Return a NEW hypothesis, extended with the information from the latest step of beam search. | [
"Return",
"a",
"NEW",
"hypothesis,",
"extended",
"with",
"the",
"information",
"from",
"the",
"latest",
"step",
"of",
"beam",
"search."
] | def extend(self, token, log_prob, state, attn_dist_norescale, attn_dist, p_gen, context_vector, coverage):
return Hypothesis(tokens=self.tokens + [token], log_probs=self.log_probs + [log_prob], state=state, attn_dists_norescale=self.attn_dists_norescale + [attn_dist_norescale], attn_dists=self.attn_dists + [attn_di... | ['def', 'extend(self,', 'token,', 'log_prob,', 'state,', 'attn_dist_norescale,', 'attn_dist,', 'p_gen,', 'context_vector,', 'coverage):', 'return', 'Hypothesis(tokens=self.tokens', '+', '[token],', 'log_probs=self.log_probs', '+', '[log_prob],', 'state=state,', 'attn_dists_norescale=self.attn_dists_norescale', '+', '[a... | 700,640 |
clips/pattern | __init__.py | positive | positive | Returns True if the given sentence has a positive sentiment (polarity >= threshold). | [
"Returns",
"True",
"if",
"the",
"given",
"sentence",
"has",
"a",
"positive",
"sentiment",
"(polarity",
">=",
"threshold)."
] | def positive(s, threshold=0.1, **kwargs):
return polarity(s, **kwargs) >= threshold | ['def', 'positive(s,', 'threshold=0.1,', '**kwargs):', 'return', 'polarity(s,', '**kwargs)', '>=', 'threshold'] | 764,993 |
thatbrguy/Pedestrian-Detection | config_util_test.py | ConfigUtilTest.test_get_configs_from_pipeline_file | test_get_configs_from_pipeline_file | Test that proto configs can be read from pipeline config file. | [
"Test",
"that",
"proto",
"configs",
"can",
"be",
"read",
"from",
"pipeline",
"config",
"file."
] | def test_get_configs_from_pipeline_file(self):
pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config')
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
pipeline_config.model.faster_rcnn.num_classes = 10
pipeline_config.train_config.batch_size = 32
pipeline_config.train_in... | ['def', 'test_get_configs_from_pipeline_file(self):', 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.model.faster_rcnn.num_classes', '=', '10', 'pipeline_config.train_config.batch_size', '=', '32'... | 766,296 |
sek788432/Waymo-2D-Object-Detection | inception_v4.py | block_inception_c | block_inception_c | Builds Inception-C block for Inception v4 network. | [
"Builds",
"Inception-C",
"block",
"for",
"Inception",
"v4",
"network."
] | def block_inception_c(inputs, scope=None, reuse=None):
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockInceptionC', [inputs], reuse=reuse):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv... | ['def', 'block_inception_c(inputs,', 'scope=None,', 'reuse=None):', 'with', 'slim.arg_scope([slim.conv2d,', 'slim.avg_pool2d,', 'slim.max_pool2d],', 'stride=1,', "padding='SAME'):", 'with', 'tf.variable_scope(scope,', "'BlockInceptionC',", '[inputs],', 'reuse=reuse):', 'with', "tf.variable_scope('Branch_0'):", 'branch_... | 975,774 |
OliverKillane/NuNet-Designer | NuNetLibrary.py | Output.passforwards | passforwards | passforwards is overridden from the Neuron class, it checks for a label value, if present it calculates the loss and loss derivative. | [
"passforwards",
"is",
"overridden",
"from",
"the",
"Neuron",
"class,",
"it",
"checks",
"for",
"a",
"label",
"value,",
"if",
"present",
"it",
"calculates",
"the",
"loss",
"and",
"loss",
"derivative."
] | def passforwards(self) -> None:
if not self._labelValue is None:
(self._activationValue, self._activationDerivative) = self._activationFunction(self._inputValue, self._labelValue, self._activationConstant)
self._backpropDerivative = self._activationDerivative | ['def', 'passforwards(self)', '->', 'None:', 'if', 'not', 'self._labelValue', 'is', 'None:', '(self._activationValue,', 'self._activationDerivative)', '=', 'self._activationFunction(self._inputValue,', 'self._labelValue,', 'self._activationConstant)', 'self._backpropDerivative', '=', 'self._activationDerivative'] | 730,522 |
sleebapaul/attnGAN | losses.py | cosine_similarity | cosine_similarity | Returns cosine similarity between x1 and x2, computed along dim. | [
"Returns",
"cosine",
"similarity",
"between",
"x1",
"and",
"x2,",
"computed",
"along",
"dim."
] | def cosine_similarity(x1, x2, dim=1, eps=1e-08):
w12 = torch.sum(x1 * x2, dim)
w1 = torch.norm(x1, 2, dim)
w2 = torch.norm(x2, 2, dim)
return (w12 / (w1 * w2).clamp(min=eps)).squeeze() | ['def', 'cosine_similarity(x1,', 'x2,', 'dim=1,', 'eps=1e-08):', 'w12', '=', 'torch.sum(x1', '*', 'x2,', 'dim)', 'w1', '=', 'torch.norm(x1,', '2,', 'dim)', 'w2', '=', 'torch.norm(x2,', '2,', 'dim)', 'return', '(w12', '/', '(w1', '*', 'w2).clamp(min=eps)).squeeze()'] | 403,194 |
xingyizhou/CenterNet | pascal_voc.py | pascal_voc.image_path_from_index | image_path_from_index | Construct an image path from the image's "index" identifier. | [
"Construct",
"an",
"image",
"path",
"from",
"the",
"image's",
"\"index\"",
"identifier."
] | def image_path_from_index(self, index):
image_path = os.path.join(self._data_path, 'JPEGImages', index + self._image_ext)
assert os.path.exists(image_path), 'Path does not exist: {}'.format(image_path)
return image_path | ['def', 'image_path_from_index(self,', 'index):', 'image_path', '=', 'os.path.join(self._data_path,', "'JPEGImages',", 'index', '+', 'self._image_ext)', 'assert', 'os.path.exists(image_path),', "'Path", 'does', 'not', 'exist:', "{}'.format(image_path)", 'return', 'image_path'] | 457,666 |
hsouri/BayesianTransferLearning | dino.py | DINOLoss.update_center | update_center | Updates the center for DINO's loss using exponential moving average. | [
"Updates",
"the",
"center",
"for",
"DINO's",
"loss",
"using",
"exponential",
"moving",
"average."
] | def update_center(self, teacher_output: torch.Tensor):
batch_center = torch.sum(teacher_output, dim=0, keepdim=True)
if dist.is_available() and dist.is_initialized():
dist.all_reduce(batch_center)
batch_center = batch_center / dist.get_world_size()
batch_center = batch_center / len(teacher_o... | ['def', 'update_center(self,', 'teacher_output:', 'torch.Tensor):', 'batch_center', '=', 'torch.sum(teacher_output,', 'dim=0,', 'keepdim=True)', 'if', 'dist.is_available()', 'and', 'dist.is_initialized():', 'dist.all_reduce(batch_center)', 'batch_center', '=', 'batch_center', '/', 'dist.get_world_size()', 'batch_center... | 422,919 |
zackmcnulty/CSE_446-Machine_Learning | font_manager.py | OSXInstalledFonts | OSXInstalledFonts | Get list of font files on OS X. | [
"Get",
"list",
"of",
"font",
"files",
"on",
"OS",
"X."
] | def OSXInstalledFonts(directories=None, fontext='ttf'):
if directories is None:
directories = OSXFontDirectories
return [path for directory in directories for path in list_fonts(directory, get_fontext_synonyms(fontext))] | ['def', 'OSXInstalledFonts(directories=None,', "fontext='ttf'):", 'if', 'directories', 'is', 'None:', 'directories', '=', 'OSXFontDirectories', 'return', '[path', 'for', 'directory', 'in', 'directories', 'for', 'path', 'in', 'list_fonts(directory,', 'get_fontext_synonyms(fontext))]'] | 194,360 |
wandb/wandb | data_logging.py | ValidationDataLogger.make_predictions | make_predictions | Produce predictions by passing `validation_inputs` to `predict_fn`. | [
"Produce",
"predictions",
"by",
"passing",
"`validation_inputs`",
"to",
"`predict_fn`."
] | def make_predictions(self, predict_fn: Callable) -> Union[Sequence, Dict[str, Sequence]]:
return predict_fn(self.validation_inputs) | ['def', 'make_predictions(self,', 'predict_fn:', 'Callable)', '->', 'Union[Sequence,', 'Dict[str,', 'Sequence]]:', 'return', 'predict_fn(self.validation_inputs)'] | 941,707 |
FenHua/Robust_Logo_Detection | vfnet_head.py | VFNetHead.get_atss_targets | get_atss_targets | A wrapper for computing ATSS targets for points in multiple images. | [
"A",
"wrapper",
"for",
"computing",
"ATSS",
"targets",
"for",
"points",
"in",
"multiple",
"images."
] | def get_atss_targets(self, cls_scores, mlvl_points, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore=None):
featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
assert len(featmap_sizes) == self.anchor_generator.num_levels
device = cls_scores[0].device
(anchor_list, valid_flag_list) = self.g... | ['def', 'get_atss_targets(self,', 'cls_scores,', 'mlvl_points,', 'gt_bboxes,', 'gt_labels,', 'img_metas,', 'gt_bboxes_ignore=None):', 'featmap_sizes', '=', '[featmap.size()[-2:]', 'for', 'featmap', 'in', 'cls_scores]', 'assert', 'len(featmap_sizes)', '==', 'self.anchor_generator.num_levels', 'device', '=', 'cls_scores[... | 826,835 |
trojanguy31/NaturalLanguageProcessing | extract_features.py | convert_examples_to_features | convert_examples_to_features | Loads a data file into a list of `InputBatch`s. | [
"Loads",
"a",
"data",
"file",
"into",
"a",
"list",
"of",
"`InputBatch`s."
] | def convert_examples_to_features(examples, seq_length, tokenizer):
features = []
for (ex_index, example) in enumerate(examples):
tokens_a = tokenizer.tokenize(example.text_a)
tokens_b = None
if example.text_b:
tokens_b = tokenizer.tokenize(example.text_b)
if tokens_b:... | ['def', 'convert_examples_to_features(examples,', 'seq_length,', 'tokenizer):', 'features', '=', '[]', 'for', '(ex_index,', 'example)', 'in', 'enumerate(examples):', 'tokens_a', '=', 'tokenizer.tokenize(example.text_a)', 'tokens_b', '=', 'None', 'if', 'example.text_b:', 'tokens_b', '=', 'tokenizer.tokenize(example.text... | 710,512 |
openvinotoolkit/training_extensions | tiling.py | Tile.prepare_result | prepare_result | Prepare results dict for pipeline. | [
"Prepare",
"results",
"dict",
"for",
"pipeline."
] | def prepare_result(self, result: Dict) -> Dict:
result_template = dict(ori_filename=result['ori_filename'], filename=result['filename'], bbox_fields=result['bbox_fields'], mask_fields=result['mask_fields'], seg_fields=result['seg_fields'], img_fields=result['img_fields'])
return result_template | ['def', 'prepare_result(self,', 'result:', 'Dict)', '->', 'Dict:', 'result_template', '=', "dict(ori_filename=result['ori_filename'],", "filename=result['filename'],", "bbox_fields=result['bbox_fields'],", "mask_fields=result['mask_fields'],", "seg_fields=result['seg_fields'],", "img_fields=result['img_fields'])", 'ret... | 918,067 |
neviim/Applying_EANNs_using_Python | genetics.py | EvolutonaryAlgorithm.SavePopulation | SavePopulation | Save final population for future purposes Be aware that every line in file contains saved wages of one individual. | [
"Save",
"final",
"population",
"for",
"future",
"purposes",
"Be",
"aware",
"that",
"every",
"line",
"in",
"file",
"contains",
"saved",
"wages",
"of",
"one",
"individual."
] | def SavePopulation(cls, filename):
FilesManager.ClearFile(filename)
for individual in cls.finalPopulation:
nextLine = BuiltInTypesConverter.FloatsToString(individual.wages)
FilesManager.AddLineToFile(nextLine, filename) | ['def', 'SavePopulation(cls,', 'filename):', 'FilesManager.ClearFile(filename)', 'for', 'individual', 'in', 'cls.finalPopulation:', 'nextLine', '=', 'BuiltInTypesConverter.FloatsToString(individual.wages)', 'FilesManager.AddLineToFile(nextLine,', 'filename)'] | 401,706 |
kornia/kornia | histogram.py | marginal_pdf | marginal_pdf | Calculate the marginal probability distribution function of the input tensor based on the number of histogram bins. | [
"Calculate",
"the",
"marginal",
"probability",
"distribution",
"function",
"of",
"the",
"input",
"tensor",
"based",
"on",
"the",
"number",
"of",
"histogram",
"bins."
] | def marginal_pdf(values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor, epsilon: float=1e-10) -> Tuple[torch.Tensor, torch.Tensor]:
if not isinstance(values, torch.Tensor):
raise TypeError(f'Input values type is not a torch.Tensor. Got {type(values)}')
if not isinstance(bins, torch.Tensor):
... | ['def', 'marginal_pdf(values:', 'torch.Tensor,', 'bins:', 'torch.Tensor,', 'sigma:', 'torch.Tensor,', 'epsilon:', 'float=1e-10)', '->', 'Tuple[torch.Tensor,', 'torch.Tensor]:', 'if', 'not', 'isinstance(values,', 'torch.Tensor):', 'raise', "TypeError(f'Input", 'values', 'type', 'is', 'not', 'a', 'torch.Tensor.', 'Got', ... | 621,675 |
weimin17/Object-Detection_HelmetDetection | config_util_test.py | ConfigUtilTest.testNewTrainInputPath | testNewTrainInputPath | Tests that train input path can be overwritten with single file. | [
"Tests",
"that",
"train",
"input",
"path",
"can",
"be",
"overwritten",
"with",
"single",
"file."
] | def testNewTrainInputPath(self):
original_train_path = ['path/to/data']
new_train_path = 'another/path/to/data'
pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config')
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
reader_config = pipeline_config.train_input_reader.tf_r... | ['def', 'testNewTrainInputPath(self):', 'original_train_path', '=', "['path/to/data']", 'new_train_path', '=', "'another/path/to/data'", 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'reader_config', '=', 'pipeli... | 750,992 |
rudranil723/mini-main | lexer.py | RegexLexerMeta.process_tokendef | process_tokendef | Preprocess a dictionary of token definitions. | [
"Preprocess",
"a",
"dictionary",
"of",
"token",
"definitions."
] | def process_tokendef(cls, name, tokendefs=None):
processed = cls._all_tokens[name] = {}
tokendefs = tokendefs or cls.tokens[name]
for state in list(tokendefs):
cls._process_state(tokendefs, processed, state)
return processed | ['def', 'process_tokendef(cls,', 'name,', 'tokendefs=None):', 'processed', '=', 'cls._all_tokens[name]', '=', '{}', 'tokendefs', '=', 'tokendefs', 'or', 'cls.tokens[name]', 'for', 'state', 'in', 'list(tokendefs):', 'cls._process_state(tokendefs,', 'processed,', 'state)', 'return', 'processed'] | 268,589 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | transform.py | keywordSafeIdent | keywordSafeIdent | Validates and possibly renames a Java identifier. | [
"Validates",
"and",
"possibly",
"renames",
"a",
"Java",
"identifier."
] | def keywordSafeIdent(node, config, invalid=invalidPythonNames()):
ident = node.token.text
if ident in invalid:
node.token.text = '%s_' % ident | ['def', 'keywordSafeIdent(node,', 'config,', 'invalid=invalidPythonNames()):', 'ident', '=', 'node.token.text', 'if', 'ident', 'in', 'invalid:', 'node.token.text', '=', "'%s_'", '%', 'ident'] | 17,647 |
fmassa/vision | boxes.py | remove_small_boxes | remove_small_boxes | Remove boxes which contains at least one side smaller than min_size. | [
"Remove",
"boxes",
"which",
"contains",
"at",
"least",
"one",
"side",
"smaller",
"than",
"min_size."
] | def remove_small_boxes(boxes: Tensor, min_size: float) -> Tensor:
if not torch.jit.is_scripting() and (not torch.jit.is_tracing()):
_log_api_usage_once(remove_small_boxes)
(ws, hs) = (boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1])
keep = (ws >= min_size) & (hs >= min_size)
keep = torch.wh... | ['def', 'remove_small_boxes(boxes:', 'Tensor,', 'min_size:', 'float)', '->', 'Tensor:', 'if', 'not', 'torch.jit.is_scripting()', 'and', '(not', 'torch.jit.is_tracing()):', '_log_api_usage_once(remove_small_boxes)', '(ws,', 'hs)', '=', '(boxes[:,', '2]', '-', 'boxes[:,', '0],', 'boxes[:,', '3]', '-', 'boxes[:,', '1])', ... | 959,147 |
tusen-ai/SST | custom_3d.py | Custom3DDataset.pre_pipeline | pre_pipeline | Initialization before data preparation. | [
"Initialization",
"before",
"data",
"preparation."
] | def pre_pipeline(self, results):
results['img_fields'] = []
results['bbox3d_fields'] = []
results['pts_mask_fields'] = []
results['pts_seg_fields'] = []
results['bbox_fields'] = []
results['mask_fields'] = []
results['seg_fields'] = []
results['box_type_3d'] = self.box_type_3d
result... | ['def', 'pre_pipeline(self,', 'results):', "results['img_fields']", '=', '[]', "results['bbox3d_fields']", '=', '[]', "results['pts_mask_fields']", '=', '[]', "results['pts_seg_fields']", '=', '[]', "results['bbox_fields']", '=', '[]', "results['mask_fields']", '=', '[]', "results['seg_fields']", '=', '[]', "results['b... | 872,351 |
open-mmlab/mmdetection3d | s3dis_dataset.py | S3DISDataset.parse_ann_info | parse_ann_info | Process the `instances` in data info to `ann_info`. | [
"Process",
"the",
"`instances`",
"in",
"data",
"info",
"to",
"`ann_info`."
] | def parse_ann_info(self, info: dict) -> dict:
ann_info = super().parse_ann_info(info)
if ann_info is None:
ann_info = dict()
ann_info['gt_bboxes_3d'] = np.zeros((0, 6), dtype=np.float32)
ann_info['gt_labels_3d'] = np.zeros((0,), dtype=np.int64)
ann_info['gt_bboxes_3d'] = DepthInstanc... | ['def', 'parse_ann_info(self,', 'info:', 'dict)', '->', 'dict:', 'ann_info', '=', 'super().parse_ann_info(info)', 'if', 'ann_info', 'is', 'None:', 'ann_info', '=', 'dict()', "ann_info['gt_bboxes_3d']", '=', 'np.zeros((0,', '6),', 'dtype=np.float32)', "ann_info['gt_labels_3d']", '=', 'np.zeros((0,),', 'dtype=np.int64)',... | 631,679 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | sanitizer.py | AmortizedGaussianSanitizer.set_option | set_option | Set options for an individual tensor. | [
"Set",
"options",
"for",
"an",
"individual",
"tensor."
] | def set_option(self, tensor_name, option):
self._options[tensor_name] = option | ['def', 'set_option(self,', 'tensor_name,', 'option):', 'self._options[tensor_name]', '=', 'option'] | 53,825 |
rudranil723/mini-main | text_format.py | ParseFloat | ParseFloat | Parse a floating point number. | [
"Parse",
"a",
"floating",
"point",
"number."
] | def ParseFloat(text):
try:
return float(text)
except ValueError:
if _FLOAT_INFINITY.match(text):
if text[0] == '-':
return float('-inf')
else:
return float('inf')
elif _FLOAT_NAN.match(text):
return float('nan')
... | ['def', 'ParseFloat(text):', 'try:', 'return', 'float(text)', 'except', 'ValueError:', 'if', '_FLOAT_INFINITY.match(text):', 'if', 'text[0]', '==', "'-':", 'return', "float('-inf')", 'else:', 'return', "float('inf')", 'elif', '_FLOAT_NAN.match(text):', 'return', "float('nan')", 'else:', 'try:', 'return', "float(text.rs... | 318,324 |
EdinburghNLP/XSum | dictionary.py | Dictionary.finalize | finalize | Sort symbols by frequency in descending order, ignoring special ones. | [
"Sort",
"symbols",
"by",
"frequency",
"in",
"descending",
"order,",
"ignoring",
"special",
"ones."
] | def finalize(self):
(self.count, self.symbols) = zip(*sorted(zip(self.count, self.symbols), key=lambda x: math.inf if self.indices[x[1]] < self.nspecial else x[0], reverse=True)) | ['def', 'finalize(self):', '(self.count,', 'self.symbols)', '=', 'zip(*sorted(zip(self.count,', 'self.symbols),', 'key=lambda', 'x:', 'math.inf', 'if', 'self.indices[x[1]]', '<', 'self.nspecial', 'else', 'x[0],', 'reverse=True))'] | 374,513 |
yahyaizala/Natural-Language-Processing | Tagger.py | joint_prob | joint_prob | Returns the joint probability of the given sequence of words and tags under the HMM model. | [
"Returns",
"the",
"joint",
"probability",
"of",
"the",
"given",
"sequence",
"of",
"words",
"and",
"tags",
"under",
"the",
"HMM",
"model."
] | def joint_prob(sentence, A, B):
p = 1
global START, END, UNK, allTagCounts, perWordTagCounts, transitionCounts, emissionCounts, num_of_sentences
V = len(perWordTagCounts)
for i in range(len(sentence)):
if i == 0:
(word, tag) = sentence[i]
try:
A_prob = pow... | ['def', 'joint_prob(sentence,', 'A,', 'B):', 'p', '=', '1', 'global', 'START,', 'END,', 'UNK,', 'allTagCounts,', 'perWordTagCounts,', 'transitionCounts,', 'emissionCounts,', 'num_of_sentences', 'V', '=', 'len(perWordTagCounts)', 'for', 'i', 'in', 'range(len(sentence)):', 'if', 'i', '==', '0:', '(word,', 'tag)', '=', 's... | 708,413 |
AiIsBetter/computer_vision | ssd_mobilenet_v1_feature_extractor.py | SSDMobileNetV1FeatureExtractor.extract_features | extract_features | Extract features from preprocessed inputs. | [
"Extract",
"features",
"from",
"preprocessed",
"inputs."
] | def extract_features(self, preprocessed_inputs):
preprocessed_inputs = shape_utils.check_min_image_dim(33, preprocessed_inputs)
feature_map_layout = {'from_layer': ['Conv2d_11_pointwise', 'Conv2d_13_pointwise', '', '', '', ''], 'layer_depth': [-1, -1, 512, 256, 256, 128], 'use_explicit_padding': self._use_expli... | ['def', 'extract_features(self,', 'preprocessed_inputs):', 'preprocessed_inputs', '=', 'shape_utils.check_min_image_dim(33,', 'preprocessed_inputs)', 'feature_map_layout', '=', "{'from_layer':", "['Conv2d_11_pointwise',", "'Conv2d_13_pointwise',", "'',", "'',", "'',", "''],", "'layer_depth':", '[-1,', '-1,', '512,', '2... | 511,716 |
43Carrig/recurrent_neural_networks_practice | tree_walk.py | TreeWalk.setup | setup | All the node-specific handlers are setup at object initialization time. | [
"All",
"the",
"node-specific",
"handlers",
"are",
"setup",
"at",
"object",
"initialization",
"time."
] | def setup(self):
self.pre_handlers = pre_handlers = {}
self.post_handlers = post_handlers = {}
for name in sorted(vars(type(self))):
if name.startswith('init_'):
getattr(self, name)()
elif name.startswith('pre_'):
pre_handlers[name[4:]] = getattr(self, name)
e... | ['def', 'setup(self):', 'self.pre_handlers', '=', 'pre_handlers', '=', '{}', 'self.post_handlers', '=', 'post_handlers', '=', '{}', 'for', 'name', 'in', 'sorted(vars(type(self))):', 'if', "name.startswith('init_'):", 'getattr(self,', 'name)()', 'elif', "name.startswith('pre_'):", 'pre_handlers[name[4:]]', '=', 'getattr... | 309,788 |
kailash-turimella/NaturalLanguageProcessing | run_squad.py | get_final_text | get_final_text | Project the tokenized prediction back to the original text. | [
"Project",
"the",
"tokenized",
"prediction",
"back",
"to",
"the",
"original",
"text."
] | def get_final_text(pred_text, orig_text, do_lower_case):
def _strip_spaces(text):
ns_chars = []
ns_to_s_map = collections.OrderedDict()
for (i, c) in enumerate(text):
if c == ' ':
continue
ns_to_s_map[len(ns_chars)] = i
ns_chars.append(c)
... | ['def', 'get_final_text(pred_text,', 'orig_text,', 'do_lower_case):', 'def', '_strip_spaces(text):', 'ns_chars', '=', '[]', 'ns_to_s_map', '=', 'collections.OrderedDict()', 'for', '(i,', 'c)', 'in', 'enumerate(text):', 'if', 'c', '==', "'", "':", 'continue', 'ns_to_s_map[len(ns_chars)]', '=', 'i', 'ns_chars.append(c)',... | 798,987 |
IordachescuAnca/Artificial-Intelligence | search.py | Graph.connect | connect | Add a link from A and B of given distance, and also add the inverse link if the graph is undirected. | [
"Add",
"a",
"link",
"from",
"A",
"and",
"B",
"of",
"given",
"distance,",
"and",
"also",
"add",
"the",
"inverse",
"link",
"if",
"the",
"graph",
"is",
"undirected."
] | def connect(self, A, B, distance=1):
self.connect1(A, B, distance)
if not self.directed:
self.connect1(B, A, distance) | ['def', 'connect(self,', 'A,', 'B,', 'distance=1):', 'self.connect1(A,', 'B,', 'distance)', 'if', 'not', 'self.directed:', 'self.connect1(B,', 'A,', 'distance)'] | 117,471 |
ryu-ed/SpaceInvaders_Ros | datetime.py | datetime.utcoffset | utcoffset | Return the timezone offset in minutes east of UTC (negative west of UTC). | [
"Return",
"the",
"timezone",
"offset",
"in",
"minutes",
"east",
"of",
"UTC",
"(negative",
"west",
"of",
"UTC)."
] | def utcoffset(self):
if self._tzinfo is None:
return None
offset = self._tzinfo.utcoffset(self)
_check_utc_offset('utcoffset', offset)
return offset | ['def', 'utcoffset(self):', 'if', 'self._tzinfo', 'is', 'None:', 'return', 'None', 'offset', '=', 'self._tzinfo.utcoffset(self)', "_check_utc_offset('utcoffset',", 'offset)', 'return', 'offset'] | 395,500 |
JinliangLu96/CL_UNMT | transformer.py | get_masks | get_masks | Generate hidden states mask, and optionally an attention mask. | [
"Generate",
"hidden",
"states",
"mask,",
"and",
"optionally",
"an",
"attention",
"mask."
] | def get_masks(slen, lengths, causal):
assert lengths.max().item() <= slen
bs = lengths.size(0)
alen = torch.arange(slen, dtype=torch.long, device=lengths.device)
mask = alen < lengths[:, None]
if causal:
attn_mask = alen[None, None, :].repeat(bs, slen, 1) <= alen[None, :, None]
else:
... | ['def', 'get_masks(slen,', 'lengths,', 'causal):', 'assert', 'lengths.max().item()', '<=', 'slen', 'bs', '=', 'lengths.size(0)', 'alen', '=', 'torch.arange(slen,', 'dtype=torch.long,', 'device=lengths.device)', 'mask', '=', 'alen', '<', 'lengths[:,', 'None]', 'if', 'causal:', 'attn_mask', '=', 'alen[None,', 'None,', ':... | 123,292 |
google-research/scenic | mbt.py | MBTClassificationModel.loss_function | loss_function | Returns softmax cross entropy loss with an L2 penalty on the weights. | [
"Returns",
"softmax",
"cross",
"entropy",
"loss",
"with",
"an",
"L2",
"penalty",
"on",
"the",
"weights."
] | def loss_function(self, logits: jnp.ndarray, batch: base_model.Batch, model_params: Optional[jnp.ndarray]=None) -> float:
weights = batch.get('batch_mask')
labels = batch['label']
assert self.dataset_meta_data.get('target_is_onehot', False)
if isinstance(logits, dict):
sof_ce_loss = []
f... | ['def', 'loss_function(self,', 'logits:', 'jnp.ndarray,', 'batch:', 'base_model.Batch,', 'model_params:', 'Optional[jnp.ndarray]=None)', '->', 'float:', 'weights', '=', "batch.get('batch_mask')", 'labels', '=', "batch['label']", 'assert', "self.dataset_meta_data.get('target_is_onehot',", 'False)', 'if', 'isinstance(log... | 846,410 |
gunthercox/ChatterBot | fst.py | to_labels | to_labels | Takes a string and returns a list of bytestrings, suitable for use as a key or path in an FSA/FST graph. | [
"Takes",
"a",
"string",
"and",
"returns",
"a",
"list",
"of",
"bytestrings,",
"suitable",
"for",
"use",
"as",
"a",
"key",
"or",
"path",
"in",
"an",
"FSA/FST",
"graph."
] | def to_labels(key):
keytype = type(key)
if keytype is tuple or keytype is list:
if not all((isinstance(e, bytes_type) for e in key)):
raise TypeError('%r contains a non-bytestring' % key)
if keytype is list:
key = tuple(key)
elif isinstance(key, bytes_type):
k... | ['def', 'to_labels(key):', 'keytype', '=', 'type(key)', 'if', 'keytype', 'is', 'tuple', 'or', 'keytype', 'is', 'list:', 'if', 'not', 'all((isinstance(e,', 'bytes_type)', 'for', 'e', 'in', 'key)):', 'raise', "TypeError('%r", 'contains', 'a', "non-bytestring'", '%', 'key)', 'if', 'keytype', 'is', 'list:', 'key', '=', 'tu... | 484,326 |
alteryx/compose | object.py | LabelTimes.is_discrete | is_discrete | Whether labels are discrete. | [
"Whether",
"labels",
"are",
"discrete."
] | def is_discrete(self):
return self.target_types.eq('discrete') | ['def', 'is_discrete(self):', 'return', "self.target_types.eq('discrete')"] | 136,045 |
BigEggStudy/UC-Berkeley-CS-188-Artificial- | search.py | aStarSearch | aStarSearch | Search the node that has the lowest combined cost and heuristic first. | [
"Search",
"the",
"node",
"that",
"has",
"the",
"lowest",
"combined",
"cost",
"and",
"heuristic",
"first."
] | def aStarSearch(problem, heuristic=nullHeuristic):
queue = util.PriorityQueue()
queue.push((problem.getStartState(), [], 0), 0)
visited = dict()
while not queue.isEmpty():
(currentState, steps, existedCost) = queue.pop()
if currentState in visited and visited[currentState] <= existedCost... | ['def', 'aStarSearch(problem,', 'heuristic=nullHeuristic):', 'queue', '=', 'util.PriorityQueue()', 'queue.push((problem.getStartState(),', '[],', '0),', '0)', 'visited', '=', 'dict()', 'while', 'not', 'queue.isEmpty():', '(currentState,', 'steps,', 'existedCost)', '=', 'queue.pop()', 'if', 'currentState', 'in', 'visite... | 426,712 |
google-research/batch-ppo | configs.py | bullet_ant | bullet_ant | Configuration for PyBullet's ant task. | [
"Configuration",
"for",
"PyBullet's",
"ant",
"task."
] | def bullet_ant():
locals().update(default())
import pybullet_envs
env = 'AntBulletEnv-v0'
max_length = 1000
steps = 30000000.0
update_every = 60
return locals() | ['def', 'bullet_ant():', 'locals().update(default())', 'import', 'pybullet_envs', 'env', '=', "'AntBulletEnv-v0'", 'max_length', '=', '1000', 'steps', '=', '30000000.0', 'update_every', '=', '60', 'return', 'locals()'] | 94,943 |
rudranil723/mini-main | models.py | SpatialRefSysMixin.linear_units | linear_units | Return the linear units. | [
"Return",
"the",
"linear",
"units."
] | def linear_units(self):
return self.srs.linear_units | ['def', 'linear_units(self):', 'return', 'self.srs.linear_units'] | 314,992 |
rudranil723/mini-main | core.py | _MaskedPrintOption.set_display | set_display | Set the string to print for masked values. | [
"Set",
"the",
"string",
"to",
"print",
"for",
"masked",
"values."
] | def set_display(self, s):
self._display = s | ['def', 'set_display(self,', 's):', 'self._display', '=', 's'] | 322,899 |
marysia/thesis | D4h_array.py | identity | identity | Returns the identity element: a matrix with 1's on the diagonal. | [
"Returns",
"the",
"identity",
"element:",
"a",
"matrix",
"with",
"1's",
"on",
"the",
"diagonal."
] | def identity(p='int'):
li = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
e = D4hArray(data=np.array(li, dtype=np.int), p='mat')
return e.reparameterize(p) | ['def', "identity(p='int'):", 'li', '=', '[[1,', '0,', '0],', '[0,', '1,', '0],', '[0,', '0,', '1]]', 'e', '=', 'D4hArray(data=np.array(li,', 'dtype=np.int),', "p='mat')", 'return', 'e.reparameterize(p)'] | 354,816 |
deepmind/dm_control | primitive.py | Primitive.linear_velocity | linear_velocity | Sensor that returns the linear velocity of the prop. | [
"Sensor",
"that",
"returns",
"the",
"linear",
"velocity",
"of",
"the",
"prop."
] | def linear_velocity(self):
return self._linear_velocity | ['def', 'linear_velocity(self):', 'return', 'self._linear_velocity'] | 165,028 |
sek788432/Waymo-2D-Object-Detection | preprocessor_test.py | PreprocessorTest.testResizePadToMultipleEmptyMasks | testResizePadToMultipleEmptyMasks | Tests resizing when padding to multiple with an empty mask. | [
"Tests",
"resizing",
"when",
"padding",
"to",
"multiple",
"with",
"an",
"empty",
"mask."
] | def testResizePadToMultipleEmptyMasks(self):
def graph_fn():
image = tf.ones((200, 100, 3), dtype=tf.float32)
masks = tf.ones((0, 200, 100), dtype=tf.float32)
(_, out_masks, out_shape) = preprocessor.resize_pad_to_multiple(image, multiple=32, masks=masks)
return [out_masks, out_shap... | ['def', 'testResizePadToMultipleEmptyMasks(self):', 'def', 'graph_fn():', 'image', '=', 'tf.ones((200,', '100,', '3),', 'dtype=tf.float32)', 'masks', '=', 'tf.ones((0,', '200,', '100),', 'dtype=tf.float32)', '(_,', 'out_masks,', 'out_shape)', '=', 'preprocessor.resize_pad_to_multiple(image,', 'multiple=32,', 'masks=mas... | 974,889 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | escape.py | xhtml_unescape | xhtml_unescape | Un-escapes an XML-escaped string. | [
"Un-escapes",
"an",
"XML-escaped",
"string."
] | def xhtml_unescape(value: Union[str, bytes]) -> str:
return re.sub('&(#?)(\\w+?);', _convert_entity, _unicode(value)) | ['def', 'xhtml_unescape(value:', 'Union[str,', 'bytes])', '->', 'str:', 'return', "re.sub('&(#?)(\\\\w+?);',", '_convert_entity,', '_unicode(value))'] | 437,479 |
IndigoPurple/CrowdCount-MCNN | models.py | PreparedRequest.prepare_hooks | prepare_hooks | Prepares the given hooks. | [
"Prepares",
"the",
"given",
"hooks."
] | def prepare_hooks(self, hooks):
hooks = hooks or []
for event in hooks:
self.register_hook(event, hooks[event]) | ['def', 'prepare_hooks(self,', 'hooks):', 'hooks', '=', 'hooks', 'or', '[]', 'for', 'event', 'in', 'hooks:', 'self.register_hook(event,', 'hooks[event])'] | 139,367 |
replit-archive/empythoned | check.py | check.initialize_options | initialize_options | Sets default values for options. | [
"Sets",
"default",
"values",
"for",
"options."
] | def initialize_options(self):
self.restructuredtext = 0
self.metadata = 1
self.strict = 0
self._warnings = 0 | ['def', 'initialize_options(self):', 'self.restructuredtext', '=', '0', 'self.metadata', '=', '1', 'self.strict', '=', '0', 'self._warnings', '=', '0'] | 177,478 |
GregorKobsik/Octree-Transformer | check_sequence_length_transform.py | CheckSequenceLenghtTransform.check_single_embedding | check_single_embedding | Check the embedded sequence length given a single token embedding module. | [
"Check",
"the",
"embedded",
"sequence",
"length",
"given",
"a",
"single",
"token",
"embedding",
"module."
] | def check_single_embedding(self, val, dep, pos):
sequence_length = len(val) // self.convolution_factor
if sequence_length > self.num_positions:
return None
else:
return (val, dep, pos) | ['def', 'check_single_embedding(self,', 'val,', 'dep,', 'pos):', 'sequence_length', '=', 'len(val)', '//', 'self.convolution_factor', 'if', 'sequence_length', '>', 'self.num_positions:', 'return', 'None', 'else:', 'return', '(val,', 'dep,', 'pos)'] | 742,017 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.