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 |
|---|---|---|---|---|---|---|---|---|
intel/neural-compressor | config.py | _Config.onnxruntime | onnxruntime | Get the onnxruntime object. | [
"Get",
"the",
"onnxruntime",
"object."
] | def onnxruntime(self):
return self._onnxruntime | ['def', 'onnxruntime(self):', 'return', 'self._onnxruntime'] | 737,253 |
yzcjtr/GeoNet | utils.py | meshgrid | meshgrid | Construct a 2D meshgrid. | [
"Construct",
"a",
"2D",
"meshgrid."
] | def meshgrid(batch, height, width, is_homogeneous=True):
x_t = tf.matmul(tf.ones(shape=tf.stack([height, 1])), tf.transpose(tf.expand_dims(tf.linspace(-1.0, 1.0, width), 1), [1, 0]))
y_t = tf.matmul(tf.expand_dims(tf.linspace(-1.0, 1.0, height), 1), tf.ones(shape=tf.stack([1, width])))
x_t = (x_t + 1.0) * 0... | ['def', 'meshgrid(batch,', 'height,', 'width,', 'is_homogeneous=True):', 'x_t', '=', 'tf.matmul(tf.ones(shape=tf.stack([height,', '1])),', 'tf.transpose(tf.expand_dims(tf.linspace(-1.0,', '1.0,', 'width),', '1),', '[1,', '0]))', 'y_t', '=', 'tf.matmul(tf.expand_dims(tf.linspace(-1.0,', '1.0,', 'height),', '1),', 'tf.on... | 202,359 |
devashish-patel/webcam-motion-detector | named_commands.py | uppercase_word | uppercase_word | Uppercase the current (or following) word. | [
"Uppercase",
"the",
"current",
"(or",
"following)",
"word."
] | def uppercase_word(event):
buff = event.current_buffer
for i in range(event.arg):
pos = buff.document.find_next_word_ending()
words = buff.document.text_after_cursor[:pos]
buff.insert_text(words.upper(), overwrite=True) | ['def', 'uppercase_word(event):', 'buff', '=', 'event.current_buffer', 'for', 'i', 'in', 'range(event.arg):', 'pos', '=', 'buff.document.find_next_word_ending()', 'words', '=', 'buff.document.text_after_cursor[:pos]', 'buff.insert_text(words.upper(),', 'overwrite=True)'] | 983,939 |
YanZiQinKevin/object_detection | minibatch.py | get_minibatch_blob_names | get_minibatch_blob_names | Return blob names in the order in which they are read by the data loader. | [
"Return",
"blob",
"names",
"in",
"the",
"order",
"in",
"which",
"they",
"are",
"read",
"by",
"the",
"data",
"loader."
] | def get_minibatch_blob_names(is_training=True):
blob_names = ['data']
if cfg.RPN.RPN_ON:
blob_names += roi_data.rpn.get_rpn_blob_names(is_training=is_training)
elif cfg.RETINANET.RETINANET_ON:
blob_names += roi_data.retinanet.get_retinanet_blob_names(is_training=is_training)
else:
... | ['def', 'get_minibatch_blob_names(is_training=True):', 'blob_names', '=', "['data']", 'if', 'cfg.RPN.RPN_ON:', 'blob_names', '+=', 'roi_data.rpn.get_rpn_blob_names(is_training=is_training)', 'elif', 'cfg.RETINANET.RETINANET_ON:', 'blob_names', '+=', 'roi_data.retinanet.get_retinanet_blob_names(is_training=is_training)'... | 773,016 |
dgaeta/feedforward-neural-net-SDG-backprop | mnist.py | plot_rotated_image | plot_rotated_image | Plot an MNIST digit and a version rotated by 10 degrees. | [
"Plot",
"an",
"MNIST",
"digit",
"and",
"a",
"version",
"rotated",
"by",
"10",
"degrees."
] | def plot_rotated_image(image):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.matshow(image, cmap=matplotlib.cm.binary)
plt.xticks(np.array([]))
plt.yticks(np.array([]))
plt.show()
rot_image = np.zeros((28, 28))
theta = 15 * np.pi / 180
def to_xy(j, k):
return (k - 13, ... | ['def', 'plot_rotated_image(image):', 'fig', '=', 'plt.figure()', 'ax', '=', 'fig.add_subplot(1,', '1,', '1)', 'ax.matshow(image,', 'cmap=matplotlib.cm.binary)', 'plt.xticks(np.array([]))', 'plt.yticks(np.array([]))', 'plt.show()', 'rot_image', '=', 'np.zeros((28,', '28))', 'theta', '=', '15', '*', 'np.pi', '/', '180',... | 581,930 |
weimin17/Object-Detection_HelmetDetection | custom_regression.py | my_dnn_regression_fn | my_dnn_regression_fn | A model function implementing DNN regression for a custom Estimator. | [
"A",
"model",
"function",
"implementing",
"DNN",
"regression",
"for",
"a",
"custom",
"Estimator."
] | def my_dnn_regression_fn(features, labels, mode, params):
top = tf.feature_column.input_layer(features, params['feature_columns'])
for units in params.get('hidden_units', [20]):
top = tf.layers.dense(inputs=top, units=units, activation=tf.nn.relu)
output_layer = tf.layers.dense(inputs=top, units=1)
... | ['def', 'my_dnn_regression_fn(features,', 'labels,', 'mode,', 'params):', 'top', '=', 'tf.feature_column.input_layer(features,', "params['feature_columns'])", 'for', 'units', 'in', "params.get('hidden_units',", '[20]):', 'top', '=', 'tf.layers.dense(inputs=top,', 'units=units,', 'activation=tf.nn.relu)', 'output_layer'... | 760,850 |
zihuitang/medical_AI_platform | searchengine.py | SearchEngine.setcookedpat | setcookedpat | Set pattern after escaping if re. | [
"Set",
"pattern",
"after",
"escaping",
"if",
"re."
] | def setcookedpat(self, pat):
if self.isre():
pat = re.escape(pat)
self.setpat(pat) | ['def', 'setcookedpat(self,', 'pat):', 'if', 'self.isre():', 'pat', '=', 're.escape(pat)', 'self.setpat(pat)'] | 282,884 |
google-research/scenic | dataset_utils.py | load_data | load_data | Loads the metaphase dataset. | [
"Loads",
"the",
"metaphase",
"dataset."
] | def load_data(prefix, is_train=False, parallel_reads=4):
num_hosts = jax.process_count()
host_id = jax.process_index()
filenames = tf.io.matching_files(prefix + '*')
filenames_host_split = np.array_split(filenames, num_hosts)[host_id]
logging.info('Host id=%d assigned %d out of %d dataset filenames ... | ['def', 'load_data(prefix,', 'is_train=False,', 'parallel_reads=4):', 'num_hosts', '=', 'jax.process_count()', 'host_id', '=', 'jax.process_index()', 'filenames', '=', 'tf.io.matching_files(prefix', '+', "'*')", 'filenames_host_split', '=', 'np.array_split(filenames,', 'num_hosts)[host_id]', "logging.info('Host", 'id=%... | 847,378 |
bhateharsh/computer_vision | tea50_8f.py | res2net50_48w_2s | res2net50_48w_2s | Constructs a Res2Net-50_48w_2s model. | [
"Constructs",
"a",
"Res2Net-50_48w_2s",
"model."
] | def res2net50_48w_2s(pretrained=False, **kwargs):
model = Res2Net(Bottle2neck, [3, 4, 6, 3], baseWidth=48, scale=2, **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['res2net50_48w_2s']))
return model | ['def', 'res2net50_48w_2s(pretrained=False,', '**kwargs):', 'model', '=', 'Res2Net(Bottle2neck,', '[3,', '4,', '6,', '3],', 'baseWidth=48,', 'scale=2,', '**kwargs)', 'if', 'pretrained:', "model.load_state_dict(model_zoo.load_url(model_urls['res2net50_48w_2s']))", 'return', 'model'] | 473,965 |
alexkyllo/torch-wtte | test_losses.py | test_loss_fn | test_loss_fn | Test that the discrete version of the loss function returns the expected result. | [
"Test",
"that",
"the",
"discrete",
"version",
"of",
"the",
"loss",
"function",
"returns",
"the",
"expected",
"result."
] | def test_loss_fn():
tte = torch.tensor([[6, 5, 4, 3, 2], [5, 4, 3, 2, 1]])
uncensored = torch.tensor([[1, 1, 1, 1, 0], [1, 1, 1, 1, 1]])
alpha = torch.tensor([[0.9, 0.9, 0.9, 0.9, 0.9], [0.99, 0.99, 0.99, 0.99, 0.99]])
beta = torch.tensor([[0.9, 0.9, 0.9, 0.9, 0.9], [1.1, 1.1, 1.1, 1.1, 1.1]])
input... | ['def', 'test_loss_fn():', 'tte', '=', 'torch.tensor([[6,', '5,', '4,', '3,', '2],', '[5,', '4,', '3,', '2,', '1]])', 'uncensored', '=', 'torch.tensor([[1,', '1,', '1,', '1,', '0],', '[1,', '1,', '1,', '1,', '1]])', 'alpha', '=', 'torch.tensor([[0.9,', '0.9,', '0.9,', '0.9,', '0.9],', '[0.99,', '0.99,', '0.99,', '0.99,... | 355,716 |
openvinotoolkit/training_extensions | cross_entropy_loss.py | cross_entropy | cross_entropy | Calculate cross entropy for given pred, label pairs. | [
"Calculate",
"cross",
"entropy",
"for",
"given",
"pred,",
"label",
"pairs."
] | def cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None, class_weight=None, ignore_index=None):
if ignore_index is not None:
loss = F.cross_entropy(pred, label, reduction='none', weight=class_weight, ignore_index=ignore_index)
else:
loss = F.cross_entropy(pred, label, reduc... | ['def', 'cross_entropy(pred,', 'label,', 'weight=None,', "reduction='mean',", 'avg_factor=None,', 'class_weight=None,', 'ignore_index=None):', 'if', 'ignore_index', 'is', 'not', 'None:', 'loss', '=', 'F.cross_entropy(pred,', 'label,', "reduction='none',", 'weight=class_weight,', 'ignore_index=ignore_index)', 'else:', '... | 904,087 |
OpenMDAO/OpenMDAO-Framework | index.py | deep_hasattr | deep_hasattr | Returns True if the attrbute indicated by the given pathname exists; False otherwise. | [
"Returns",
"True",
"if",
"the",
"attrbute",
"indicated",
"by",
"the",
"given",
"pathname",
"exists;",
"False",
"otherwise."
] | def deep_hasattr(obj, pathname):
try:
parts = pathname.split('.')
for name in parts[:-1]:
obj = getattr(obj, name)
except Exception:
return False
return hasattr(obj, parts[-1]) | ['def', 'deep_hasattr(obj,', 'pathname):', 'try:', 'parts', '=', "pathname.split('.')", 'for', 'name', 'in', 'parts[:-1]:', 'obj', '=', 'getattr(obj,', 'name)', 'except', 'Exception:', 'return', 'False', 'return', 'hasattr(obj,', 'parts[-1])'] | 275,877 |
pedrojrv/nucml | general_utilities.py | initialize_directories | initialize_directories | Create and/or reset the given directory path. | [
"Create",
"and/or",
"reset",
"the",
"given",
"directory",
"path."
] | def initialize_directories(directory, reset=False):
if not isinstance(directory, list):
directory = [directory]
for dir in directory:
if os.path.isdir(dir) and reset:
shutil.rmtree(dir)
os.makedirs(dir, exist_ok=True) | ['def', 'initialize_directories(directory,', 'reset=False):', 'if', 'not', 'isinstance(directory,', 'list):', 'directory', '=', '[directory]', 'for', 'dir', 'in', 'directory:', 'if', 'os.path.isdir(dir)', 'and', 'reset:', 'shutil.rmtree(dir)', 'os.makedirs(dir,', 'exist_ok=True)'] | 249,634 |
tensorflow/privacy | keras_evaluation_test.py | UtilsTest.test_calculate_losses | test_calculate_losses | Test calculating the loss. | [
"Test",
"calculating",
"the",
"loss."
] | def test_calculate_losses(self):
(pred, loss) = keras_evaluation.calculate_losses(self.model, self.train_data, self.train_labels)
self.assertEqual(pred.shape, (self.ntrain, self.nclass))
self.assertEqual(loss.shape, (self.ntrain,))
(pred, loss) = keras_evaluation.calculate_losses(self.model, self.test_d... | ['def', 'test_calculate_losses(self):', '(pred,', 'loss)', '=', 'keras_evaluation.calculate_losses(self.model,', 'self.train_data,', 'self.train_labels)', 'self.assertEqual(pred.shape,', '(self.ntrain,', 'self.nclass))', 'self.assertEqual(loss.shape,', '(self.ntrain,))', '(pred,', 'loss)', '=', 'keras_evaluation.calcul... | 824,907 |
matsu0228/nlp-jp | test_ldavowpalwabbit_wrapper.py | TestLdaVowpalWabbit.test_topic_coherence | test_topic_coherence | Test LdaVowpalWabbit topic coherence. | [
"Test",
"LdaVowpalWabbit",
"topic",
"coherence."
] | def test_topic_coherence(self):
if not self.vw_path:
return
(corpus, dictionary) = get_corpus()
lda = LdaVowpalWabbit(self.vw_path, corpus=corpus, passes=10, chunksize=256, id2word=dictionary, cleanup_files=True, alpha=0.1, eta=0.1, num_topics=len(TOPIC_WORDS), random_seed=1)
lda.print_topics(5,... | ['def', 'test_topic_coherence(self):', 'if', 'not', 'self.vw_path:', 'return', '(corpus,', 'dictionary)', '=', 'get_corpus()', 'lda', '=', 'LdaVowpalWabbit(self.vw_path,', 'corpus=corpus,', 'passes=10,', 'chunksize=256,', 'id2word=dictionary,', 'cleanup_files=True,', 'alpha=0.1,', 'eta=0.1,', 'num_topics=len(TOPIC_WORD... | 786,124 |
devashish-patel/webcam-motion-detector | compat.py | getenv | getenv | Returns unicode string containing value of environment variable 'name'. | [
"Returns",
"unicode",
"string",
"containing",
"value",
"of",
"environment",
"variable",
"'name'."
] | def getenv(name, default=None):
return os.environ.get(name, default) | ['def', 'getenv(name,', 'default=None):', 'return', 'os.environ.get(name,', 'default)'] | 984,192 |
hdjang/Feature-Selective-Anchor-Free-Module-for-Single-Shot-- | mean_ap.py | print_map_summary | print_map_summary | Print mAP and results of each class. | [
"Print",
"mAP",
"and",
"results",
"of",
"each",
"class."
] | def print_map_summary(mean_ap, results, dataset=None):
num_scales = len(results[0]['ap']) if isinstance(results[0]['ap'], np.ndarray) else 1
num_classes = len(results)
recalls = np.zeros((num_scales, num_classes), dtype=np.float32)
precisions = np.zeros((num_scales, num_classes), dtype=np.float32)
a... | ['def', 'print_map_summary(mean_ap,', 'results,', 'dataset=None):', 'num_scales', '=', "len(results[0]['ap'])", 'if', "isinstance(results[0]['ap'],", 'np.ndarray)', 'else', '1', 'num_classes', '=', 'len(results)', 'recalls', '=', 'np.zeros((num_scales,', 'num_classes),', 'dtype=np.float32)', 'precisions', '=', 'np.zero... | 544,764 |
drissiya/MTTLADE | ehr.py | ClinicalConcept.equals | equals | Return whether the current tag is equal to the one provided. | [
"Return",
"whether",
"the",
"current",
"tag",
"is",
"equal",
"to",
"the",
"one",
"provided."
] | def equals(self, other, mode='strict'):
assert mode in ('strict', 'lenient')
return other.ttype == self.ttype and self.span_matches(other, mode) | ['def', 'equals(self,', 'other,', "mode='strict'):", 'assert', 'mode', 'in', "('strict',", "'lenient')", 'return', 'other.ttype', '==', 'self.ttype', 'and', 'self.span_matches(other,', 'mode)'] | 643,344 |
Katja-M/Python_NaturalLanguageProcessing | recursivedescent.py | demo | demo | A demonstration of the recursive descent parser. | [
"A",
"demonstration",
"of",
"the",
"recursive",
"descent",
"parser."
] | def demo():
from nltk import parse, CFG
grammar = CFG.fromstring("\n S -> NP VP\n NP -> Det N | Det N PP\n VP -> V NP | V NP PP\n PP -> P NP\n NP -> 'I'\n N -> 'man' | 'park' | 'telescope' | 'dog'\n Det -> 'the' | 'a'\n P -> 'in' | 'with'\n V -> 'saw'\n ")
for prod in grammar.p... | ['def', 'demo():', 'from', 'nltk', 'import', 'parse,', 'CFG', 'grammar', '=', 'CFG.fromstring("\\n', 'S', '->', 'NP', 'VP\\n', 'NP', '->', 'Det', 'N', '|', 'Det', 'N', 'PP\\n', 'VP', '->', 'V', 'NP', '|', 'V', 'NP', 'PP\\n', 'PP', '->', 'P', 'NP\\n', 'NP', '->', "'I'\\n", 'N', '->', "'man'", '|', "'park'", '|', "'teles... | 866,728 |
openvinotoolkit/training_extensions | inference.py | InferenceTask.cleanup | cleanup | Clean up work directory. | [
"Clean",
"up",
"work",
"directory."
] | def cleanup(self) -> None:
if self._work_dir_is_temp:
self._delete_scratch_space() | ['def', 'cleanup(self)', '->', 'None:', 'if', 'self._work_dir_is_temp:', 'self._delete_scratch_space()'] | 918,388 |
fcjian/LOCE | hrnet.py | HRNet.train | train | Convert the model into training mode whill keeping the normalization layer freezed. | [
"Convert",
"the",
"model",
"into",
"training",
"mode",
"whill",
"keeping",
"the",
"normalization",
"layer",
"freezed."
] | def train(self, mode=True):
super(HRNet, self).train(mode)
if mode and self.norm_eval:
for m in self.modules():
if isinstance(m, _BatchNorm):
m.eval() | ['def', 'train(self,', 'mode=True):', 'super(HRNet,', 'self).train(mode)', 'if', 'mode', 'and', 'self.norm_eval:', 'for', 'm', 'in', 'self.modules():', 'if', 'isinstance(m,', '_BatchNorm):', 'm.eval()'] | 614,388 |
rudranil723/mini-main | transforms.py | BboxBase.intersection | intersection | Return the intersection of *bbox1* and *bbox2* if they intersect, or None if they don't. | [
"Return",
"the",
"intersection",
"of",
"*bbox1*",
"and",
"*bbox2*",
"if",
"they",
"intersect,",
"or",
"None",
"if",
"they",
"don't."
] | def intersection(bbox1, bbox2):
x0 = np.maximum(bbox1.xmin, bbox2.xmin)
x1 = np.minimum(bbox1.xmax, bbox2.xmax)
y0 = np.maximum(bbox1.ymin, bbox2.ymin)
y1 = np.minimum(bbox1.ymax, bbox2.ymax)
return Bbox([[x0, y0], [x1, y1]]) if x0 <= x1 and y0 <= y1 else None | ['def', 'intersection(bbox1,', 'bbox2):', 'x0', '=', 'np.maximum(bbox1.xmin,', 'bbox2.xmin)', 'x1', '=', 'np.minimum(bbox1.xmax,', 'bbox2.xmax)', 'y0', '=', 'np.maximum(bbox1.ymin,', 'bbox2.ymin)', 'y1', '=', 'np.minimum(bbox1.ymax,', 'bbox2.ymax)', 'return', 'Bbox([[x0,', 'y0],', '[x1,', 'y1]])', 'if', 'x0', '<=', 'x1... | 319,782 |
boostcampaitech2/semantic-segmentation-level2-cv-07 | cityscapes.py | CityscapesDataset.format_results | format_results | Format the results to txt (standard format for Cityscapes evaluation). | [
"Format",
"the",
"results",
"to",
"txt",
"(standard",
"format",
"for",
"Cityscapes",
"evaluation)."
] | def format_results(self, results, txtfile_prefix=None):
assert isinstance(results, list), 'results must be a list'
assert len(results) == len(self), 'The length of results is not equal to the dataset len: {} != {}'.format(len(results), len(self))
assert isinstance(results, list), 'results must be a list'
... | ['def', 'format_results(self,', 'results,', 'txtfile_prefix=None):', 'assert', 'isinstance(results,', 'list),', "'results", 'must', 'be', 'a', "list'", 'assert', 'len(results)', '==', 'len(self),', "'The", 'length', 'of', 'results', 'is', 'not', 'equal', 'to', 'the', 'dataset', 'len:', '{}', '!=', "{}'.format(len(resul... | 856,909 |
Kvatsx/Artificial-Intelligence-Assignments | paths.py | get_ipython_package_dir | get_ipython_package_dir | Get the base directory where IPython itself is installed. | [
"Get",
"the",
"base",
"directory",
"where",
"IPython",
"itself",
"is",
"installed."
] | def get_ipython_package_dir():
ipdir = os.path.dirname(IPython.__file__)
return py3compat.cast_unicode(ipdir, fs_encoding) | ['def', 'get_ipython_package_dir():', 'ipdir', '=', 'os.path.dirname(IPython.__file__)', 'return', 'py3compat.cast_unicode(ipdir,', 'fs_encoding)'] | 37,848 |
Ixiaohuihuihui/AO2-DETR | re_fpn.py | ConvModule.forward | forward | Forward function of ConvModule. | [
"Forward",
"function",
"of",
"ConvModule."
] | def forward(self, x, activate=True, norm=True):
for layer in self.order:
if layer == 'conv':
x = self.conv(x)
elif layer == 'norm' and norm and self.with_norm:
x = self.norm(x)
elif layer == 'act' and activate and self.with_activatation:
x = self.activate(... | ['def', 'forward(self,', 'x,', 'activate=True,', 'norm=True):', 'for', 'layer', 'in', 'self.order:', 'if', 'layer', '==', "'conv':", 'x', '=', 'self.conv(x)', 'elif', 'layer', '==', "'norm'", 'and', 'norm', 'and', 'self.with_norm:', 'x', '=', 'self.norm(x)', 'elif', 'layer', '==', "'act'", 'and', 'activate', 'and', 'se... | 401,580 |
autonomousvision/differentiable_volumetric_rendering | visualize.py | visualize_data | visualize_data | Visualizes the data with regard to its type. | [
"Visualizes",
"the",
"data",
"with",
"regard",
"to",
"its",
"type."
] | def visualize_data(data, data_type, out_file):
if data_type == 'img':
if data.dim() == 3:
data = data.unsqueeze(0)
save_image(data, out_file, nrow=4)
elif data_type == 'voxels':
visualize_voxels(data, out_file=out_file)
elif data_type == 'pointcloud':
visualize_po... | ['def', 'visualize_data(data,', 'data_type,', 'out_file):', 'if', 'data_type', '==', "'img':", 'if', 'data.dim()', '==', '3:', 'data', '=', 'data.unsqueeze(0)', 'save_image(data,', 'out_file,', 'nrow=4)', 'elif', 'data_type', '==', "'voxels':", 'visualize_voxels(data,', 'out_file=out_file)', 'elif', 'data_type', '==', ... | 185,074 |
Eric3911/OpenAGI | audio_to_diar_label.py | _AudioMSDDTrainDataset.get_ms_seg_timestamps | get_ms_seg_timestamps | Get start and end time of segments in each scale. | [
"Get",
"start",
"and",
"end",
"time",
"of",
"segments",
"in",
"each",
"scale."
] | def get_ms_seg_timestamps(self, sample):
uniq_id = self.get_uniq_id_with_range(sample)
ms_seg_timestamps_list = []
max_seq_len = len(self.multiscale_timestamp_dict[uniq_id]['scale_dict'][self.scale_n - 1]['time_stamps'])
ms_seg_counts = [0 for _ in range(self.scale_n)]
for scale_idx in range(self.sc... | ['def', 'get_ms_seg_timestamps(self,', 'sample):', 'uniq_id', '=', 'self.get_uniq_id_with_range(sample)', 'ms_seg_timestamps_list', '=', '[]', 'max_seq_len', '=', "len(self.multiscale_timestamp_dict[uniq_id]['scale_dict'][self.scale_n", '-', "1]['time_stamps'])", 'ms_seg_counts', '=', '[0', 'for', '_', 'in', 'range(sel... | 272,228 |
ratschlab/dpsom | somvae_model.py | SOMVAE.reconstruction_q | reconstruction_q | Reconstructs the input from the embeddings. | [
"Reconstructs",
"the",
"input",
"from",
"the",
"embeddings."
] | def reconstruction_q(self):
if not self.mnist:
with tf.variable_scope('decoder', reuse=tf.AUTO_REUSE):
h_3 = tf.keras.layers.Dense(128, activation='relu')(self.z_q)
h_4 = tf.keras.layers.Dense(256, activation='relu')(h_3)
x_hat = tf.keras.layers.Dense(self.input_channels,... | ['def', 'reconstruction_q(self):', 'if', 'not', 'self.mnist:', 'with', "tf.variable_scope('decoder',", 'reuse=tf.AUTO_REUSE):', 'h_3', '=', 'tf.keras.layers.Dense(128,', "activation='relu')(self.z_q)", 'h_4', '=', 'tf.keras.layers.Dense(256,', "activation='relu')(h_3)", 'x_hat', '=', 'tf.keras.layers.Dense(self.input_c... | 167,020 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | prep.py | create_vocabulary | create_vocabulary | Reads text lines and generates a vocabulary. | [
"Reads",
"text",
"lines",
"and",
"generates",
"a",
"vocabulary."
] | def create_vocabulary(lines):
lines.seek(0, os.SEEK_END)
nbytes = lines.tell()
lines.seek(0, os.SEEK_SET)
vocab = {}
for (lineno, line) in enumerate(lines, start=1):
for word in words(line):
vocab.setdefault(word, 0)
vocab[word] += 1
if lineno % 100000 == 0:
... | ['def', 'create_vocabulary(lines):', 'lines.seek(0,', 'os.SEEK_END)', 'nbytes', '=', 'lines.tell()', 'lines.seek(0,', 'os.SEEK_SET)', 'vocab', '=', '{}', 'for', '(lineno,', 'line)', 'in', 'enumerate(lines,', 'start=1):', 'for', 'word', 'in', 'words(line):', 'vocab.setdefault(word,', '0)', 'vocab[word]', '+=', '1', 'if'... | 110,779 |
bhateharsh/computer_vision | cpp_lint.py | FindEndOfExpressionInLine | FindEndOfExpressionInLine | Find the position just after the matching endchar. | [
"Find",
"the",
"position",
"just",
"after",
"the",
"matching",
"endchar."
] | def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
for i in xrange(startpos, len(line)):
if line[i] == startchar:
depth += 1
elif line[i] == endchar:
depth -= 1
if depth == 0:
return (i + 1, 0)
return (-1, depth) | ['def', 'FindEndOfExpressionInLine(line,', 'startpos,', 'depth,', 'startchar,', 'endchar):', 'for', 'i', 'in', 'xrange(startpos,', 'len(line)):', 'if', 'line[i]', '==', 'startchar:', 'depth', '+=', '1', 'elif', 'line[i]', '==', 'endchar:', 'depth', '-=', '1', 'if', 'depth', '==', '0:', 'return', '(i', '+', '1,', '0)', ... | 473,310 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | sql.py | pandasSQL_builder | pandasSQL_builder | Convenience function to return the correct PandasSQL subclass based on the provided parameters. | [
"Convenience",
"function",
"to",
"return",
"the",
"correct",
"PandasSQL",
"subclass",
"based",
"on",
"the",
"provided",
"parameters."
] | def pandasSQL_builder(con, schema=None, meta=None, is_cursor=False):
con = _engine_builder(con)
if _is_sqlalchemy_connectable(con):
return SQLDatabase(con, schema=schema, meta=meta)
elif isinstance(con, string_types):
raise ImportError('Using URI string without sqlalchemy installed.')
el... | ['def', 'pandasSQL_builder(con,', 'schema=None,', 'meta=None,', 'is_cursor=False):', 'con', '=', '_engine_builder(con)', 'if', '_is_sqlalchemy_connectable(con):', 'return', 'SQLDatabase(con,', 'schema=schema,', 'meta=meta)', 'elif', 'isinstance(con,', 'string_types):', 'raise', "ImportError('Using", 'URI', 'string', 'w... | 968,045 |
thaines/helit | params_sets.py | ParamsRange.setCList | setCList | Sets the list of c values. | [
"Sets",
"the",
"list",
"of",
"c",
"values."
] | def setCList(self, c):
self.c = c | ['def', 'setCList(self,', 'c):', 'self.c', '=', 'c'] | 592,571 |
arshpreetsingh/quantopian-machinelearning | demo.py | Demo.marquee | marquee | Return the input string centered in a 'marquee'. | [
"Return",
"the",
"input",
"string",
"centered",
"in",
"a",
"'marquee'."
] | def marquee(self, txt='', width=78, mark='*'):
return marquee(txt, width, mark) | ['def', 'marquee(self,', "txt='',", 'width=78,', "mark='*'):", 'return', 'marquee(txt,', 'width,', 'mark)'] | 886,811 |
AI4Finance-Foundation/Deep-Reinforcement--for-Stock-Trading-DDPG-Algorithm-NIPS-2018 | atari_env.py | AtariEnv.restore_state | restore_state | Restore emulator state w/o system state. | [
"Restore",
"emulator",
"state",
"w/o",
"system",
"state."
] | def restore_state(self, state):
state_ref = self.ale.decodeState(state)
self.ale.restoreState(state_ref)
self.ale.deleteState(state_ref) | ['def', 'restore_state(self,', 'state):', 'state_ref', '=', 'self.ale.decodeState(state)', 'self.ale.restoreState(state_ref)', 'self.ale.deleteState(state_ref)'] | 519,382 |
kornia/kornia | image.py | Image.from_file | from_file | Construct an image tensor from a file. | [
"Construct",
"an",
"image",
"tensor",
"from",
"a",
"file."
] | def from_file(cls, file_path: str | Path) -> Image:
data: Tensor = load_image(file_path, desired_type=ImageLoadType.RGB8, device='cpu')
pixel_format = PixelFormat(color_space=ColorSpace.RGB, bit_depth=data.element_size() * 8)
layout = ImageLayout(image_size=ImageSize(height=data.shape[1], width=data.shape[2... | ['def', 'from_file(cls,', 'file_path:', 'str', '|', 'Path)', '->', 'Image:', 'data:', 'Tensor', '=', 'load_image(file_path,', 'desired_type=ImageLoadType.RGB8,', "device='cpu')", 'pixel_format', '=', 'PixelFormat(color_space=ColorSpace.RGB,', 'bit_depth=data.element_size()', '*', '8)', 'layout', '=', 'ImageLayout(image... | 622,206 |
alibaba/EasyCV | mvx_two_stage.py | MVXTwoStageDetector.with_img_rpn | with_img_rpn | bool: Whether the detector has a 2D RPN in image detector branch. | [
"bool:",
"Whether",
"the",
"detector",
"has",
"a",
"2D",
"RPN",
"in",
"image",
"detector",
"branch."
] | def with_img_rpn(self):
return hasattr(self, 'img_rpn_head') and self.img_rpn_head is not None | ['def', 'with_img_rpn(self):', 'return', 'hasattr(self,', "'img_rpn_head')", 'and', 'self.img_rpn_head', 'is', 'not', 'None'] | 546,617 |
nlp-uoregon/trankit | adapter_model_mixin.py | ModelWithHeadsAdaptersMixin.train_adapter | train_adapter | Sets the model into mode for training the given adapters. | [
"Sets",
"the",
"model",
"into",
"mode",
"for",
"training",
"the",
"given",
"adapters."
] | def train_adapter(self, adapter_names: list):
self.base_model.train_adapter(adapter_names) | ['def', 'train_adapter(self,', 'adapter_names:', 'list):', 'self.base_model.train_adapter(adapter_names)'] | 920,044 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | Interpolator.Reverse | Reverse | Looks up y and returns the corresponding value of x. | [
"Looks",
"up",
"y",
"and",
"returns",
"the",
"corresponding",
"value",
"of",
"x."
] | def Reverse(self, y):
return self._Bisect(y, self.ys, self.xs) | ['def', 'Reverse(self,', 'y):', 'return', 'self._Bisect(y,', 'self.ys,', 'self.xs)'] | 13,252 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | containers.py | WindowRenderInfo.first_visible_line | first_visible_line | Return the line number (0 based) of the input document that corresponds with the first visible line. | [
"Return",
"the",
"line",
"number",
"(0",
"based)",
"of",
"the",
"input",
"document",
"that",
"corresponds",
"with",
"the",
"first",
"visible",
"line."
] | def first_visible_line(self, after_scroll_offset: bool=False) -> int:
if after_scroll_offset:
return self.displayed_lines[self.applied_scroll_offsets.top]
else:
return self.displayed_lines[0] | ['def', 'first_visible_line(self,', 'after_scroll_offset:', 'bool=False)', '->', 'int:', 'if', 'after_scroll_offset:', 'return', 'self.displayed_lines[self.applied_scroll_offsets.top]', 'else:', 'return', 'self.displayed_lines[0]'] | 435,314 |
tonybeltramelli/Graphics-And-Vision | Pattern.py | Pattern.RightCorners | RightCorners | Set the output array of detected right corners. | [
"Set",
"the",
"output",
"array",
"of",
"detected",
"right",
"corners."
] | def RightCorners(self, value):
self.__rightCorners = value | ['def', 'RightCorners(self,', 'value):', 'self.__rightCorners', '=', 'value'] | 580,642 |
kornia/kornia | base.py | AugmentationBase3D.transform_tensor | transform_tensor | Convert any incoming (D, H, W), (C, D, H, W) and (B, C, D, H, W) into (B, C, D, H, W). | [
"Convert",
"any",
"incoming",
"(D,",
"H,",
"W),",
"(C,",
"D,",
"H,",
"W)",
"and",
"(B,",
"C,",
"D,",
"H,",
"W)",
"into",
"(B,",
"C,",
"D,",
"H,",
"W)."
] | def transform_tensor(self, input: Tensor) -> Tensor:
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
return _transform_input3d(input) | ['def', 'transform_tensor(self,', 'input:', 'Tensor)', '->', 'Tensor:', '_validate_input_dtype(input,', 'accepted_dtypes=[float16,', 'float32,', 'float64])', 'return', '_transform_input3d(input)'] | 621,542 |
sktime/sktime | test_Padder.py | test_padding_transformer | test_padding_transformer | Test the dimensions after padding. | [
"Test",
"the",
"dimensions",
"after",
"padding."
] | def test_padding_transformer():
(X_train, y_train) = load_basic_motions(split='train', return_X_y=True)
padding_transformer = PaddingTransformer()
Xt = padding_transformer.fit_transform(X_train)
data = from_nested_to_2d_array(Xt)
assert len(data.columns) == 100 * 6 | ['def', 'test_padding_transformer():', '(X_train,', 'y_train)', '=', "load_basic_motions(split='train',", 'return_X_y=True)', 'padding_transformer', '=', 'PaddingTransformer()', 'Xt', '=', 'padding_transformer.fit_transform(X_train)', 'data', '=', 'from_nested_to_2d_array(Xt)', 'assert', 'len(data.columns)', '==', '100... | 877,751 |
yekeren/Cap2Det | imgproc.py | calc_integral_image | calc_integral_image | Computes the integral image. | [
"Computes",
"the",
"integral",
"image."
] | def calc_integral_image(image):
(b, n, m, c) = utils.get_tensor_shape(image)
pad_top = tf.fill([b, 1, m, c], 0.0)
pad_left = tf.fill([b, n + 1, 1, c], 0.0)
image = tf.concat([pad_top, image], axis=1)
image = tf.concat([pad_left, image], axis=2)
cumsum = tf.cumsum(image, axis=2)
cumsum = tf.c... | ['def', 'calc_integral_image(image):', '(b,', 'n,', 'm,', 'c)', '=', 'utils.get_tensor_shape(image)', 'pad_top', '=', 'tf.fill([b,', '1,', 'm,', 'c],', '0.0)', 'pad_left', '=', 'tf.fill([b,', 'n', '+', '1,', '1,', 'c],', '0.0)', 'image', '=', 'tf.concat([pad_top,', 'image],', 'axis=1)', 'image', '=', 'tf.concat([pad_le... | 108,917 |
nilearn/nilearn | test_region_extractor.py | test_threshold_maps_ratio | test_threshold_maps_ratio | Check _threshold_maps_ratio with randomly generated maps. | [
"Check",
"_threshold_maps_ratio",
"with",
"randomly",
"generated",
"maps."
] | def test_threshold_maps_ratio(maps):
get_data(maps)[:3] = 100
maps_data = get_data(maps).copy()
thr_maps = _threshold_maps_ratio(maps, threshold=1.0)
np.testing.assert_array_equal(get_data(maps), maps_data)
assert thr_maps.shape[-1] == maps.shape[-1] | ['def', 'test_threshold_maps_ratio(maps):', 'get_data(maps)[:3]', '=', '100', 'maps_data', '=', 'get_data(maps).copy()', 'thr_maps', '=', '_threshold_maps_ratio(maps,', 'threshold=1.0)', 'np.testing.assert_array_equal(get_data(maps),', 'maps_data)', 'assert', 'thr_maps.shape[-1]', '==', 'maps.shape[-1]'] | 724,237 |
Arts-ISIT-LA/la-nlp | test_aspect_sentiment.py | test_attribute_parent_span | test_attribute_parent_span | Tests that tokens are assigned the parent span attribute as expected. | [
"Tests",
"that",
"tokens",
"are",
"assigned",
"the",
"parent",
"span",
"attribute",
"as",
"expected."
] | def test_attribute_parent_span(doc1, doc2):
assertion1 = "Span should read 'the professor was mean'"
doc1_target = 'the professor was mean'
token1 = doc1._.keywords[2]
assert token1._.parent_span.text == doc1_target, assertion1
assertion2 = 'Span should be None'
doc2_target = None
token2 = d... | ['def', 'test_attribute_parent_span(doc1,', 'doc2):', 'assertion1', '=', '"Span', 'should', 'read', "'the", 'professor', 'was', 'mean\'"', 'doc1_target', '=', "'the", 'professor', 'was', "mean'", 'token1', '=', 'doc1._.keywords[2]', 'assert', 'token1._.parent_span.text', '==', 'doc1_target,', 'assertion1', 'assertion2'... | 622,439 |
locationlabs/mockredis | test_redis.py | TestRedis.test_get_types | test_get_types | testing type conversions for set/get, hset/hget, sadd/smembers Python bools, lists, dicts are returned as strings by redis-py/redis. | [
"testing",
"type",
"conversions",
"for",
"set/get,",
"hset/hget,",
"sadd/smembers",
"Python",
"bools,",
"lists,",
"dicts",
"are",
"returned",
"as",
"strings",
"by",
"redis-py/redis."
] | def test_get_types(self):
values = list([True, False, [1, '2'], {'a': 1, 'b': 'c'}])
eq_(None, self.redis.get('key'))
for value in values:
self.redis.set('key', value)
eq_(str(value).encode('utf8'), self.redis.get('key'))
self.redis.hset('hkey', 'item', value)
eq_(str(value).... | ['def', 'test_get_types(self):', 'values', '=', 'list([True,', 'False,', '[1,', "'2'],", "{'a':", '1,', "'b':", "'c'}])", 'eq_(None,', "self.redis.get('key'))", 'for', 'value', 'in', 'values:', "self.redis.set('key',", 'value)', "eq_(str(value).encode('utf8'),", "self.redis.get('key'))", "self.redis.hset('hkey',", "'it... | 240,667 |
myothida/Supervised-Machine-Learning | conftest.py | csv_dir_path | csv_dir_path | The directory path to the data files needed for parser tests. | [
"The",
"directory",
"path",
"to",
"the",
"data",
"files",
"needed",
"for",
"parser",
"tests."
] | def csv_dir_path(datapath):
return datapath('io', 'parser', 'data') | ['def', 'csv_dir_path(datapath):', 'return', "datapath('io',", "'parser',", "'data')"] | 443,779 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | Expression.acceptSuperConstructorCall | acceptSuperConstructorCall | Accept and process a super constructor call. | [
"Accept",
"and",
"process",
"a",
"super",
"constructor",
"call."
] | def acceptSuperConstructorCall(self, node, memo):
cls = self.parents(lambda c: c.isClass).next()
fs = 'super(' + FS.l + ', self).__init__(' + FS.r + ')'
self.right = self.factory.expr(fs=fs, left=cls.name)
return self.right | ['def', 'acceptSuperConstructorCall(self,', 'node,', 'memo):', 'cls', '=', 'self.parents(lambda', 'c:', 'c.isClass).next()', 'fs', '=', "'super('", '+', 'FS.l', '+', "',", "self).__init__('", '+', 'FS.r', '+', "')'", 'self.right', '=', 'self.factory.expr(fs=fs,', 'left=cls.name)', 'return', 'self.right'] | 17,300 |
Ruturaj123/Flowchart-Detection | linear_test.py | LinearRegressorTest.testPredict_AsIterable | testPredict_AsIterable | Tests predict method with as_iterable=True. | [
"Tests",
"predict",
"method",
"with",
"as_iterable=True."
] | def testPredict_AsIterable(self):
labels = [1.0, 0.0, 0.2]
def _input_fn(num_epochs=None):
features = {'age': input_lib.limit_epochs(constant_op.constant([[0.8], [0.15], [0.0]]), num_epochs=num_epochs), 'language': sparse_tensor.SparseTensor(values=['en', 'fr', 'zh'], indices=[[0, 0], [0, 1], [2, 0]], ... | ['def', 'testPredict_AsIterable(self):', 'labels', '=', '[1.0,', '0.0,', '0.2]', 'def', '_input_fn(num_epochs=None):', 'features', '=', "{'age':", 'input_lib.limit_epochs(constant_op.constant([[0.8],', '[0.15],', '[0.0]]),', 'num_epochs=num_epochs),', "'language':", "sparse_tensor.SparseTensor(values=['en',", "'fr',", ... | 604,049 |
f-dangel/cockpit | tic.py | TIC.extensions | extensions | Return list of BackPACK extensions required for the computation. | [
"Return",
"list",
"of",
"BackPACK",
"extensions",
"required",
"for",
"the",
"computation."
] | def extensions(self, global_step):
if self.is_active(global_step):
try:
ext = [self.extensions_from_str[self._curvature]()]
except KeyError as e:
available = list(self.extensions_from_str.keys())
raise KeyError(f'{str(e)}. Available: {available}')
if self.... | ['def', 'extensions(self,', 'global_step):', 'if', 'self.is_active(global_step):', 'try:', 'ext', '=', '[self.extensions_from_str[self._curvature]()]', 'except', 'KeyError', 'as', 'e:', 'available', '=', 'list(self.extensions_from_str.keys())', 'raise', "KeyError(f'{str(e)}.", 'Available:', "{available}')", 'if', 'self... | 493,099 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | prepare.py | get_file_url | get_file_url | Get file and optionally check its hash. | [
"Get",
"file",
"and",
"optionally",
"check",
"its",
"hash."
] | def get_file_url(link, download_dir=None, hashes=None):
already_downloaded_path = None
if download_dir:
already_downloaded_path = _check_download_dir(link, download_dir, hashes)
if already_downloaded_path:
from_path = already_downloaded_path
else:
from_path = link.file_path
i... | ['def', 'get_file_url(link,', 'download_dir=None,', 'hashes=None):', 'already_downloaded_path', '=', 'None', 'if', 'download_dir:', 'already_downloaded_path', '=', '_check_download_dir(link,', 'download_dir,', 'hashes)', 'if', 'already_downloaded_path:', 'from_path', '=', 'already_downloaded_path', 'else:', 'from_path'... | 454,266 |
rudranil723/mini-main | EditServiceSecurity.py | ServiceSecurity.MapGeneric | MapGeneric | Converts generic access rights to specific rights. | [
"Converts",
"generic",
"access",
"rights",
"to",
"specific",
"rights."
] | def MapGeneric(self, guid, aceflags, mask):
return win32security.MapGenericMask(mask, (SERVICE_GENERIC_READ, SERVICE_GENERIC_WRITE, SERVICE_GENERIC_EXECUTE, win32service.SERVICE_ALL_ACCESS)) | ['def', 'MapGeneric(self,', 'guid,', 'aceflags,', 'mask):', 'return', 'win32security.MapGenericMask(mask,', '(SERVICE_GENERIC_READ,', 'SERVICE_GENERIC_WRITE,', 'SERVICE_GENERIC_EXECUTE,', 'win32service.SERVICE_ALL_ACCESS))'] | 271,253 |
k2kobayashi/crank | sinc_conv.py | BarkScale.bank | bank | Obtain initialization values for the Bark scale. | [
"Obtain",
"initialization",
"values",
"for",
"the",
"Bark",
"scale."
] | def bank(cls, channels: int, fs: float) -> torch.Tensor:
assert check_argument_types()
min_center_frequency = torch.tensor(70.0)
max_center_frequency = torch.tensor(fs * 0.45)
center_frequencies = torch.linspace(cls.convert(min_center_frequency), cls.convert(max_center_frequency), channels)
center_f... | ['def', 'bank(cls,', 'channels:', 'int,', 'fs:', 'float)', '->', 'torch.Tensor:', 'assert', 'check_argument_types()', 'min_center_frequency', '=', 'torch.tensor(70.0)', 'max_center_frequency', '=', 'torch.tensor(fs', '*', '0.45)', 'center_frequencies', '=', 'torch.linspace(cls.convert(min_center_frequency),', 'cls.conv... | 490,669 |
replit-archive/empythoned | mutex.py | mutex.test | test | Test the locked bit of the mutex. | [
"Test",
"the",
"locked",
"bit",
"of",
"the",
"mutex."
] | def test(self):
return self.locked | ['def', 'test(self):', 'return', 'self.locked'] | 177,308 |
zihuitang/medical_AI_platform | ccompiler.py | show_compilers | show_compilers | Print list of available compilers (used by the "--help-compiler" options to "build", "build_ext", "build_clib"). | [
"Print",
"list",
"of",
"available",
"compilers",
"(used",
"by",
"the",
"\"--help-compiler\"",
"options",
"to",
"\"build\",",
"\"build_ext\",",
"\"build_clib\")."
] | def show_compilers():
from distutils.fancy_getopt import FancyGetopt
compilers = []
for compiler in compiler_class.keys():
compilers.append(('compiler=' + compiler, None, compiler_class[compiler][2]))
compilers.sort()
pretty_printer = FancyGetopt(compilers)
pretty_printer.print_help('Lis... | ['def', 'show_compilers():', 'from', 'distutils.fancy_getopt', 'import', 'FancyGetopt', 'compilers', '=', '[]', 'for', 'compiler', 'in', 'compiler_class.keys():', "compilers.append(('compiler='", '+', 'compiler,', 'None,', 'compiler_class[compiler][2]))', 'compilers.sort()', 'pretty_printer', '=', 'FancyGetopt(compiler... | 282,169 |
Ruturaj123/Flowchart-Detection | skip_gram_ops_test.py | SkipGramOpsTest.test_skip_gram_sample_limit_exceeds | test_skip_gram_sample_limit_exceeds | Tests skip-gram when limit exceeds the length of the input. | [
"Tests",
"skip-gram",
"when",
"limit",
"exceeds",
"the",
"length",
"of",
"the",
"input."
] | def test_skip_gram_sample_limit_exceeds(self):
input_tensor = constant_op.constant([b'foo', b'the', b'quick', b'brown'])
(tokens, labels) = text.skip_gram_sample(input_tensor, min_skips=1, max_skips=1, start=1, limit=100)
(expected_tokens, expected_labels) = self._split_tokens_labels([(b'the', b'quick'), (b... | ['def', 'test_skip_gram_sample_limit_exceeds(self):', 'input_tensor', '=', "constant_op.constant([b'foo',", "b'the',", "b'quick',", "b'brown'])", '(tokens,', 'labels)', '=', 'text.skip_gram_sample(input_tensor,', 'min_skips=1,', 'max_skips=1,', 'start=1,', 'limit=100)', '(expected_tokens,', 'expected_labels)', '=', "se... | 604,613 |
ShuaiChenBIGR/MASSL-segmentation-framework | evaluation_lesion.py | getLesionDetection | getLesionDetection | Lesion detection metrics, both recall and F1. | [
"Lesion",
"detection",
"metrics,",
"both",
"recall",
"and",
"F1."
] | def getLesionDetection(testImage, resultImage):
ccFilter = sitk.ConnectedComponentImageFilter()
ccFilter.SetFullyConnected(True)
ccTest = ccFilter.Execute(testImage)
lResult = sitk.Multiply(ccTest, sitk.Cast(resultImage, sitk.sitkUInt32))
ccTestArray = sitk.GetArrayFromImage(ccTest)
lResultArray... | ['def', 'getLesionDetection(testImage,', 'resultImage):', 'ccFilter', '=', 'sitk.ConnectedComponentImageFilter()', 'ccFilter.SetFullyConnected(True)', 'ccTest', '=', 'ccFilter.Execute(testImage)', 'lResult', '=', 'sitk.Multiply(ccTest,', 'sitk.Cast(resultImage,', 'sitk.sitkUInt32))', 'ccTestArray', '=', 'sitk.GetArrayF... | 209,775 |
Vill-Lab/2021-TIP-IGOAS | optimizer.py | build_optimizer | build_optimizer | A function wrapper for building an optimizer. | [
"A",
"function",
"wrapper",
"for",
"building",
"an",
"optimizer."
] | def build_optimizer(model, optim='adam', lr=0.0003, weight_decay=0.0005, momentum=0.9, sgd_dampening=0, sgd_nesterov=False, rmsprop_alpha=0.99, adam_beta1=0.9, adam_beta2=0.99, staged_lr=False, new_layers='', base_lr_mult=0.1):
if optim not in AVAI_OPTIMS:
raise ValueError('Unsupported optim: {}. Must be on... | ['def', 'build_optimizer(model,', "optim='adam',", 'lr=0.0003,', 'weight_decay=0.0005,', 'momentum=0.9,', 'sgd_dampening=0,', 'sgd_nesterov=False,', 'rmsprop_alpha=0.99,', 'adam_beta1=0.9,', 'adam_beta2=0.99,', 'staged_lr=False,', "new_layers='',", 'base_lr_mult=0.1):', 'if', 'optim', 'not', 'in', 'AVAI_OPTIMS:', 'rais... | 375,501 |
Katja-M/Python_NaturalLanguageProcessing | drt.py | DrtConcatenation.replace | replace | Replace all instances of variable v with expression E in self, where v is free in self. | [
"Replace",
"all",
"instances",
"of",
"variable",
"v",
"with",
"expression",
"E",
"in",
"self,",
"where",
"v",
"is",
"free",
"in",
"self."
] | def replace(self, variable, expression, replace_bound=False, alpha_convert=True):
first = self.first
second = self.second
consequent = self.consequent
if variable in self.get_refs():
if replace_bound:
first = first.replace(variable, expression, replace_bound, alpha_convert)
... | ['def', 'replace(self,', 'variable,', 'expression,', 'replace_bound=False,', 'alpha_convert=True):', 'first', '=', 'self.first', 'second', '=', 'self.second', 'consequent', '=', 'self.consequent', 'if', 'variable', 'in', 'self.get_refs():', 'if', 'replace_bound:', 'first', '=', 'first.replace(variable,', 'expression,',... | 866,808 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | inspect.py | indentsize | indentsize | Return the indent size, in spaces, at the start of a line of text. | [
"Return",
"the",
"indent",
"size,",
"in",
"spaces,",
"at",
"the",
"start",
"of",
"a",
"line",
"of",
"text."
] | def indentsize(line):
expline = line.expandtabs()
return len(expline) - len(expline.lstrip()) | ['def', 'indentsize(line):', 'expline', '=', 'line.expandtabs()', 'return', 'len(expline)', '-', 'len(expline.lstrip())'] | 428,660 |
yehengchen/Object-Detection-and-Tracking | model.py | DarknetConv2D_BN_Leaky | DarknetConv2D_BN_Leaky | Darknet Convolution2D followed by BatchNormalization and LeakyReLU. | [
"Darknet",
"Convolution2D",
"followed",
"by",
"BatchNormalization",
"and",
"LeakyReLU."
] | def DarknetConv2D_BN_Leaky(*args, **kwargs):
no_bias_kwargs = {'use_bias': False}
no_bias_kwargs.update(kwargs)
return compose(DarknetConv2D(*args, **no_bias_kwargs), BatchNormalization(), LeakyReLU(alpha=0.1)) | ['def', 'DarknetConv2D_BN_Leaky(*args,', '**kwargs):', 'no_bias_kwargs', '=', "{'use_bias':", 'False}', 'no_bias_kwargs.update(kwargs)', 'return', 'compose(DarknetConv2D(*args,', '**no_bias_kwargs),', 'BatchNormalization(),', 'LeakyReLU(alpha=0.1))'] | 726,092 |
abakan-zz/ablog | blog.py | Post.next | next | Set next published post in chronological order. | [
"Set",
"next",
"published",
"post",
"in",
"chronological",
"order."
] | def next(self, post):
self._next = post | ['def', 'next(self,', 'post):', 'self._next', '=', 'post'] | 6,404 |
zihuitang/medical_AI_platform | tty.py | setraw | setraw | Put terminal into a raw mode. | [
"Put",
"terminal",
"into",
"a",
"raw",
"mode."
] | def setraw(fd, when=TCSAFLUSH):
mode = tcgetattr(fd)
mode[IFLAG] = mode[IFLAG] & ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON)
mode[OFLAG] = mode[OFLAG] & ~OPOST
mode[CFLAG] = mode[CFLAG] & ~(CSIZE | PARENB)
mode[CFLAG] = mode[CFLAG] | CS8
mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON | IEXTEN | ISIG)... | ['def', 'setraw(fd,', 'when=TCSAFLUSH):', 'mode', '=', 'tcgetattr(fd)', 'mode[IFLAG]', '=', 'mode[IFLAG]', '&', '~(BRKINT', '|', 'ICRNL', '|', 'INPCK', '|', 'ISTRIP', '|', 'IXON)', 'mode[OFLAG]', '=', 'mode[OFLAG]', '&', '~OPOST', 'mode[CFLAG]', '=', 'mode[CFLAG]', '&', '~(CSIZE', '|', 'PARENB)', 'mode[CFLAG]', '=', 'm... | 281,679 |
facebookresearch/CompilerGym | csmith.py | CsmithBenchmark.source | source | Return the single source file contents as a string. | [
"Return",
"the",
"single",
"source",
"file",
"contents",
"as",
"a",
"string."
] | def source(self) -> str:
return self._src.decode('utf-8') | ['def', 'source(self)', '->', 'str:', 'return', "self._src.decode('utf-8')"] | 126,175 |
devashish-patel/webcam-motion-detector | application.py | Application.document_config_options | document_config_options | Generate rST format documentation for the config options this application Returns a multiline string. | [
"Generate",
"rST",
"format",
"documentation",
"for",
"the",
"config",
"options",
"this",
"application",
"Returns",
"a",
"multiline",
"string."
] | def document_config_options(self):
return '\n'.join((c.class_config_rst_doc() for c in self._classes_inc_parents())) | ['def', 'document_config_options(self):', 'return', "'\\n'.join((c.class_config_rst_doc()", 'for', 'c', 'in', 'self._classes_inc_parents()))'] | 985,301 |
tobegit3hub/deep_image_model | distribution.py | Distribution.name | name | Name prepended to all ops created by this `Distribution`. | [
"Name",
"prepended",
"to",
"all",
"ops",
"created",
"by",
"this",
"`Distribution`."
] | def name(self):
return self._name | ['def', 'name(self):', 'return', 'self._name'] | 181,147 |
Kvatsx/Artificial-Intelligence-Assignments | cookiejar.py | DefaultCookiePolicy.set_allowed_domains | set_allowed_domains | Set the sequence of allowed domains, or None. | [
"Set",
"the",
"sequence",
"of",
"allowed",
"domains,",
"or",
"None."
] | def set_allowed_domains(self, allowed_domains):
if allowed_domains is not None:
allowed_domains = tuple(allowed_domains)
self._allowed_domains = allowed_domains | ['def', 'set_allowed_domains(self,', 'allowed_domains):', 'if', 'allowed_domains', 'is', 'not', 'None:', 'allowed_domains', '=', 'tuple(allowed_domains)', 'self._allowed_domains', '=', 'allowed_domains'] | 36,938 |
benedekrozemberczki/DANMF | danmf.py | DANMF.setup_z | setup_z | Setup target matrix for pre-training process. | [
"Setup",
"target",
"matrix",
"for",
"pre-training",
"process."
] | def setup_z(self, i):
if i == 0:
self.Z = self.A
else:
self.Z = self.V_s[i - 1] | ['def', 'setup_z(self,', 'i):', 'if', 'i', '==', '0:', 'self.Z', '=', 'self.A', 'else:', 'self.Z', '=', 'self.V_s[i', '-', '1]'] | 497,118 |
zhang614/MicroGrid | png.py | write_pnm | write_pnm | Write a Netpbm PNM/PAM file. | [
"Write",
"a",
"Netpbm",
"PNM/PAM",
"file."
] | def write_pnm(file, width, height, pixels, meta):
bitdepth = meta['bitdepth']
maxval = 2 ** bitdepth - 1
planes = meta['planes']
assert planes in (1, 2, 3, 4)
if planes in (1, 3):
if 1 == planes:
fmt = 'P5'
else:
fmt = 'P6'
header = '%s %d %d %d\n' % (... | ['def', 'write_pnm(file,', 'width,', 'height,', 'pixels,', 'meta):', 'bitdepth', '=', "meta['bitdepth']", 'maxval', '=', '2', '**', 'bitdepth', '-', '1', 'planes', '=', "meta['planes']", 'assert', 'planes', 'in', '(1,', '2,', '3,', '4)', 'if', 'planes', 'in', '(1,', '3):', 'if', '1', '==', 'planes:', 'fmt', '=', "'P5'"... | 668,580 |
unixpickle/anyrl-py | dqn_dist.py | ActionDist.atom_values | atom_values | Get the reward values for each atom. | [
"Get",
"the",
"reward",
"values",
"for",
"each",
"atom."
] | def atom_values(self):
return [self.min_val + i * self._delta for i in range(0, self.num_atoms)] | ['def', 'atom_values(self):', 'return', '[self.min_val', '+', 'i', '*', 'self._delta', 'for', 'i', 'in', 'range(0,', 'self.num_atoms)]'] | 33,605 |
alex-petrenko/sample-factory | heartbeat.py | HeartbeatStoppableEventLoopObject.on_stop | on_stop | Default implementation, likely needs to be overridden in concrete classes to add termination logic. | [
"Default",
"implementation,",
"likely",
"needs",
"to",
"be",
"overridden",
"in",
"concrete",
"classes",
"to",
"add",
"termination",
"logic."
] | def on_stop(self, *_) -> None:
log.debug(f'Stopping {self.object_id}...')
if self.event_loop.owner is self:
self.event_loop.stop()
self.heartbeat_timer.stop()
self.detach() | ['def', 'on_stop(self,', '*_)', '->', 'None:', "log.debug(f'Stopping", "{self.object_id}...')", 'if', 'self.event_loop.owner', 'is', 'self:', 'self.event_loop.stop()', 'self.heartbeat_timer.stop()', 'self.detach()'] | 329,135 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | operator.py | iand | iand | Same as a &= b. | [
"Same",
"as",
"a",
"&=",
"b."
] | def iand(a, b):
a &= b
return a | ['def', 'iand(a,', 'b):', 'a', '&=', 'b', 'return', 'a'] | 429,002 |
coder-mano/Shi-Tomasi-Corner-Detector | tarfile.py | TarInfo.fromtarfile | fromtarfile | Return the next TarInfo object from TarFile object tarfile. | [
"Return",
"the",
"next",
"TarInfo",
"object",
"from",
"TarFile",
"object",
"tarfile."
] | def fromtarfile(cls, tarfile):
buf = tarfile.fileobj.read(BLOCKSIZE)
obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors)
obj.offset = tarfile.fileobj.tell() - BLOCKSIZE
return obj._proc_member(tarfile) | ['def', 'fromtarfile(cls,', 'tarfile):', 'buf', '=', 'tarfile.fileobj.read(BLOCKSIZE)', 'obj', '=', 'cls.frombuf(buf,', 'tarfile.encoding,', 'tarfile.errors)', 'obj.offset', '=', 'tarfile.fileobj.tell()', '-', 'BLOCKSIZE', 'return', 'obj._proc_member(tarfile)'] | 900,308 |
cfernandezlab/Category-Specific-Keypoints | basis_keypoint_detector.py | get_reflection_operator | get_reflection_operator | The reflection operator is parametrized by the normal vector of the plane of symmetry passing through the origin. | [
"The",
"reflection",
"operator",
"is",
"parametrized",
"by",
"the",
"normal",
"vector",
"of",
"the",
"plane",
"of",
"symmetry",
"passing",
"through",
"the",
"origin."
] | def get_reflection_operator(n_pl):
norm_npl = torch.norm(n_pl, 2)
n_x = n_pl[0, 0] / norm_npl
n_y = torch.tensor(0.0).cuda()
n_z = n_pl[0, 1] / norm_npl
refl_mat = torch.stack([1 - 2 * n_x * n_x, -2 * n_x * n_y, -2 * n_x * n_z, -2 * n_x * n_y, 1 - 2 * n_y * n_y, -2 * n_y * n_z, -2 * n_x * n_z, -2 * ... | ['def', 'get_reflection_operator(n_pl):', 'norm_npl', '=', 'torch.norm(n_pl,', '2)', 'n_x', '=', 'n_pl[0,', '0]', '/', 'norm_npl', 'n_y', '=', 'torch.tensor(0.0).cuda()', 'n_z', '=', 'n_pl[0,', '1]', '/', 'norm_npl', 'refl_mat', '=', 'torch.stack([1', '-', '2', '*', 'n_x', '*', 'n_x,', '-2', '*', 'n_x', '*', 'n_y,', '-... | 103,219 |
kornia/kornia | line.py | ParametrizedLine.origin | origin | Return the line origin point. | [
"Return",
"the",
"line",
"origin",
"point."
] | def origin(self) -> Tensor:
return self._origin | ['def', 'origin(self)', '->', 'Tensor:', 'return', 'self._origin'] | 621,934 |
augmentedstartups/AS-One | dataset.py | Dataset.check_before_run | check_before_run | Checks if required files exist before going deeper. | [
"Checks",
"if",
"required",
"files",
"exist",
"before",
"going",
"deeper."
] | def check_before_run(self, required_files):
if isinstance(required_files, str):
required_files = [required_files]
for fpath in required_files:
if not osp.exists(fpath):
raise RuntimeError('"{}" is not found'.format(fpath)) | ['def', 'check_before_run(self,', 'required_files):', 'if', 'isinstance(required_files,', 'str):', 'required_files', '=', '[required_files]', 'for', 'fpath', 'in', 'required_files:', 'if', 'not', 'osp.exists(fpath):', 'raise', 'RuntimeError(\'"{}"', 'is', 'not', "found'.format(fpath))"] | 402,404 |
fudan-zvg/SETR | mask_pseudo_sampler.py | MaskPseudoSampler.sample | sample | Directly returns the positive and negative indices of samples. | [
"Directly",
"returns",
"the",
"positive",
"and",
"negative",
"indices",
"of",
"samples."
] | def sample(self, assign_result, masks, gt_masks, **kwargs):
pos_inds = torch.nonzero(assign_result.gt_inds > 0, as_tuple=False).squeeze(-1).unique()
neg_inds = torch.nonzero(assign_result.gt_inds == 0, as_tuple=False).squeeze(-1).unique()
gt_flags = masks.new_zeros(masks.shape[0], dtype=torch.uint8)
sam... | ['def', 'sample(self,', 'assign_result,', 'masks,', 'gt_masks,', '**kwargs):', 'pos_inds', '=', 'torch.nonzero(assign_result.gt_inds', '>', '0,', 'as_tuple=False).squeeze(-1).unique()', 'neg_inds', '=', 'torch.nonzero(assign_result.gt_inds', '==', '0,', 'as_tuple=False).squeeze(-1).unique()', 'gt_flags', '=', 'masks.ne... | 897,822 |
cnr-isti-vclab/TagLab | QtImageViewerPlus.py | QtImageViewerPlus.addNote | addNote | Insert the node to add. | [
"Insert",
"the",
"node",
"to",
"add."
] | def addNote(self, x, y):
if self.image.grid is not None and self.show_grid is True:
pos = self.mapFromGlobal(QPoint(x, y))
scenePos = self.mapToScene(pos)
self.image.grid.addNote(scenePos.x(), scenePos.y(), 'Enter note..') | ['def', 'addNote(self,', 'x,', 'y):', 'if', 'self.image.grid', 'is', 'not', 'None', 'and', 'self.show_grid', 'is', 'True:', 'pos', '=', 'self.mapFromGlobal(QPoint(x,', 'y))', 'scenePos', '=', 'self.mapToScene(pos)', 'self.image.grid.addNote(scenePos.x(),', 'scenePos.y(),', "'Enter", "note..')"] | 906,820 |
weimin17/Object-Detection_HelmetDetection | oss_setup.py | data_files | data_files | Return all non-Python files in the source directories. | [
"Return",
"all",
"non-Python",
"files",
"in",
"the",
"source",
"directories."
] | def data_files():
for root in source_roots:
for (path, _, files) in os.walk(root):
for filename in files:
if not (filename.endswith('.py') or filename.endswith('.pyc')):
yield os.path.join(path, filename) | ['def', 'data_files():', 'for', 'root', 'in', 'source_roots:', 'for', '(path,', '_,', 'files)', 'in', 'os.walk(root):', 'for', 'filename', 'in', 'files:', 'if', 'not', "(filename.endswith('.py')", 'or', "filename.endswith('.pyc')):", 'yield', 'os.path.join(path,', 'filename)'] | 760,395 |
timmeinhardt/trackformer | mot17_sequence.py | MOT17Sequence.config | config | Return config of sequence. | [
"Return",
"config",
"of",
"sequence."
] | def config(self) -> dict:
config_file = self.get_config_file_path()
assert osp.exists(config_file), f'Config file does not exist: {config_file}'
config = configparser.ConfigParser()
config.read(config_file)
return config | ['def', 'config(self)', '->', 'dict:', 'config_file', '=', 'self.get_config_file_path()', 'assert', 'osp.exists(config_file),', "f'Config", 'file', 'does', 'not', 'exist:', "{config_file}'", 'config', '=', 'configparser.ConfigParser()', 'config.read(config_file)', 'return', 'config'] | 903,618 |
sarnsdev/social-alignment-data-mining | misc_util.py | allpath | allpath | Convert a /-separated pathname to one using the OS's path separator. | [
"Convert",
"a",
"/-separated",
"pathname",
"to",
"one",
"using",
"the",
"OS's",
"path",
"separator."
] | def allpath(name):
splitted = name.split('/')
return os.path.join(*splitted) | ['def', 'allpath(name):', 'splitted', '=', "name.split('/')", 'return', 'os.path.join(*splitted)'] | 352,867 |
ELEKTRONN/elektronn3 | versioneer.py | plus_or_dot | plus_or_dot | Return a + if we don't already have one, else return a . | [
"Return",
"a",
"+",
"if",
"we",
"don't",
"already",
"have",
"one,",
"else",
"return",
"a",
"."
] | def plus_or_dot(pieces):
if '+' in pieces.get('closest-tag', ''):
return '.'
return '+' | ['def', 'plus_or_dot(pieces):', 'if', "'+'", 'in', "pieces.get('closest-tag',", "''):", 'return', "'.'", 'return', "'+'"] | 175,567 |
AndrewSpano/BSc-Thesis | data_prep_utils.py | save_pickle | save_pickle | Saves the given data in pickle format the specified location. | [
"Saves",
"the",
"given",
"data",
"in",
"pickle",
"format",
"the",
"specified",
"location."
] | def save_pickle(savepath: Path, data: object) -> None:
with open(savepath, 'wb') as fp:
pickle.dump(data, fp) | ['def', 'save_pickle(savepath:', 'Path,', 'data:', 'object)', '->', 'None:', 'with', 'open(savepath,', "'wb')", 'as', 'fp:', 'pickle.dump(data,', 'fp)'] | 410,052 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | dataset_utils.py | int64_feature | int64_feature | Returns a TF-Feature of int64s. | [
"Returns",
"a",
"TF-Feature",
"of",
"int64s."
] | def int64_feature(values):
if not isinstance(values, (tuple, list)):
values = [values]
return tf.train.Feature(int64_list=tf.train.Int64List(value=values)) | ['def', 'int64_feature(values):', 'if', 'not', 'isinstance(values,', '(tuple,', 'list)):', 'values', '=', '[values]', 'return', 'tf.train.Feature(int64_list=tf.train.Int64List(value=values))'] | 109,727 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | tiles.py | fetch_image | fetch_image | Fetches the image representation for a tile. | [
"Fetches",
"the",
"image",
"representation",
"for",
"a",
"tile."
] | def fetch_image(session, url, timeout=10):
try:
resp = session.get(url, timeout=timeout)
resp.raise_for_status()
return io.BytesIO(resp.content)
except Exception:
return None | ['def', 'fetch_image(session,', 'url,', 'timeout=10):', 'try:', 'resp', '=', 'session.get(url,', 'timeout=timeout)', 'resp.raise_for_status()', 'return', 'io.BytesIO(resp.content)', 'except', 'Exception:', 'return', 'None'] | 11,947 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | network_units.py | NetworkUnitInterface.get_layer_index | get_layer_index | Gets the index of the given named layer of the network. | [
"Gets",
"the",
"index",
"of",
"the",
"given",
"named",
"layer",
"of",
"the",
"network."
] | def get_layer_index(self, layer_name):
return [x.name for x in self.layers].index(layer_name) | ['def', 'get_layer_index(self,', 'layer_name):', 'return', '[x.name', 'for', 'x', 'in', 'self.layers].index(layer_name)'] | 111,318 |
cvjena/PartDetectorDisovery | puff.py | write_puff | write_puff | Write a single numpy array to puff format. | [
"Write",
"a",
"single",
"numpy",
"array",
"to",
"puff",
"format."
] | def write_puff(arr, name):
writer = PuffStreamedWriter(name)
writer.write_batch(arr)
writer.finish() | ['def', 'write_puff(arr,', 'name):', 'writer', '=', 'PuffStreamedWriter(name)', 'writer.write_batch(arr)', 'writer.finish()'] | 278,313 |
Kvatsx/Artificial-Intelligence-Assignments | ticker.py | LinearLocator.set_params | set_params | Set parameters within this locator. | [
"Set",
"parameters",
"within",
"this",
"locator."
] | def set_params(self, numticks=None, presets=None):
if presets is not None:
self.presets = presets
if numticks is not None:
self.numticks = numticks | ['def', 'set_params(self,', 'numticks=None,', 'presets=None):', 'if', 'presets', 'is', 'not', 'None:', 'self.presets', '=', 'presets', 'if', 'numticks', 'is', 'not', 'None:', 'self.numticks', '=', 'numticks'] | 934 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | Misc.winfo_visual | winfo_visual | Return one of the strings directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor for the colormodel of this widget. | [
"Return",
"one",
"of",
"the",
"strings",
"directcolor,",
"grayscale,",
"pseudocolor,",
"staticcolor,",
"staticgray,",
"or",
"truecolor",
"for",
"the",
"colormodel",
"of",
"this",
"widget."
] | def winfo_visual(self):
return self.tk.call('winfo', 'visual', self._w) | ['def', 'winfo_visual(self):', 'return', "self.tk.call('winfo',", "'visual',", 'self._w)'] | 376,836 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | data_providers.py | parse_sequence_to_svtcn_batch | parse_sequence_to_svtcn_batch | Parses a serialized sequence example into a batch of SVTCN data. | [
"Parses",
"a",
"serialized",
"sequence",
"example",
"into",
"a",
"batch",
"of",
"SVTCN",
"data."
] | def parse_sequence_to_svtcn_batch(serialized_example, preprocess_fn, is_training, num_views, batch_size):
(_, views, seq_len) = parse_sequence_example(serialized_example, num_views)
(time_indices, view_indices) = get_svtcn_indices(seq_len, batch_size, num_views)
combined_indices = tf.concat([tf.expand_dims(... | ['def', 'parse_sequence_to_svtcn_batch(serialized_example,', 'preprocess_fn,', 'is_training,', 'num_views,', 'batch_size):', '(_,', 'views,', 'seq_len)', '=', 'parse_sequence_example(serialized_example,', 'num_views)', '(time_indices,', 'view_indices)', '=', 'get_svtcn_indices(seq_len,', 'batch_size,', 'num_views)', 'c... | 111,992 |
Eaphan/BiProDet | fastai_optim.py | trainable_params | trainable_params | Return list of trainable params in `m`. | [
"Return",
"list",
"of",
"trainable",
"params",
"in",
"`m`."
] | def trainable_params(m: nn.Module):
res = filter(lambda p: p.requires_grad, m.parameters())
return res | ['def', 'trainable_params(m:', 'nn.Module):', 'res', '=', 'filter(lambda', 'p:', 'p.requires_grad,', 'm.parameters())', 'return', 'res'] | 461,258 |
Ruturaj123/Flowchart-Detection | dnn_testing_utils.py | mock_optimizer | mock_optimizer | Creates a mock optimizer to test the train method. | [
"Creates",
"a",
"mock",
"optimizer",
"to",
"test",
"the",
"train",
"method."
] | def mock_optimizer(testcase, hidden_units, expected_loss=None):
hidden_weights_names = [(HIDDEN_WEIGHTS_NAME_PATTERN + '/part_0:0') % i for i in range(len(hidden_units))]
hidden_biases_names = [(HIDDEN_BIASES_NAME_PATTERN + '/part_0:0') % i for i in range(len(hidden_units))]
expected_var_names = hidden_weig... | ['def', 'mock_optimizer(testcase,', 'hidden_units,', 'expected_loss=None):', 'hidden_weights_names', '=', '[(HIDDEN_WEIGHTS_NAME_PATTERN', '+', "'/part_0:0')", '%', 'i', 'for', 'i', 'in', 'range(len(hidden_units))]', 'hidden_biases_names', '=', '[(HIDDEN_BIASES_NAME_PATTERN', '+', "'/part_0:0')", '%', 'i', 'for', 'i', ... | 605,210 |
zcablii/LSKNet | rotated_reppoints_head.py | RotatedRepPointsHead.loss | loss | Loss function of CFA head. | [
"Loss",
"function",
"of",
"CFA",
"head."
] | def loss(self, cls_scores, pts_preds_init, pts_preds_refine, 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.prior_generator.num_levels
label_channels = self.cls_out_channels if self.use_sigmoid_cls el... | ['def', 'loss(self,', 'cls_scores,', 'pts_preds_init,', 'pts_preds_refine,', '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.prior_generator.num_levels', 'label_channels'... | 616,160 |
nasimrahaman/antipasti-tf | pyutils2.py | make_antipasti_untrainable | make_antipasti_untrainable | Make a parameter untrainable with Antipasti. | [
"Make",
"a",
"parameter",
"untrainable",
"with",
"Antipasti."
] | def make_antipasti_untrainable(parameters):
if hasattr(parameters, 'as_list'):
parameters = parameters.as_list()
add_to_antipasti_collection(parameters, trainable=False) | ['def', 'make_antipasti_untrainable(parameters):', 'if', 'hasattr(parameters,', "'as_list'):", 'parameters', '=', 'parameters.as_list()', 'add_to_antipasti_collection(parameters,', 'trainable=False)'] | 33,545 |
mattgolub/recurrent-whisperer | AdaptiveGradNormClip.py | AdaptiveGradNormClip.update | update | Update the log of recent gradient norms and the corresponding recommended clip value. | [
"Update",
"the",
"log",
"of",
"recent",
"gradient",
"norms",
"and",
"the",
"corresponding",
"recommended",
"clip",
"value."
] | def update(self, grad_norm):
if self.do_adaptive_clipping:
if self.step < self.sliding_window_len:
self.grad_norm_log.append(grad_norm)
else:
idx = np.mod(self.step, self.sliding_window_len)
self.grad_norm_log[idx] = grad_norm
proposed_clip_val = np.percen... | ['def', 'update(self,', 'grad_norm):', 'if', 'self.do_adaptive_clipping:', 'if', 'self.step', '<', 'self.sliding_window_len:', 'self.grad_norm_log.append(grad_norm)', 'else:', 'idx', '=', 'np.mod(self.step,', 'self.sliding_window_len)', 'self.grad_norm_log[idx]', '=', 'grad_norm', 'proposed_clip_val', '=', 'np.percenti... | 309,434 |
zihuitang/medical_AI_platform | ss1.py | SheetGUI.return_event | return_event | Callback for the Return key. | [
"Callback",
"for",
"the",
"Return",
"key."
] | def return_event(self, event):
self.change_cell()
(x, y) = self.currentxy
self.setcurrent(x, y + 1)
return 'break' | ['def', 'return_event(self,', 'event):', 'self.change_cell()', '(x,', 'y)', '=', 'self.currentxy', 'self.setcurrent(x,', 'y', '+', '1)', 'return', "'break'"] | 284,739 |
microsoft/maro | event_bind_binreader.py | EventBindBinaryReader.read_items | read_items | Read items by tick and generate related events, then insert them into EventBuffer. | [
"Read",
"items",
"by",
"tick",
"and",
"generate",
"related",
"events,",
"then",
"insert",
"them",
"into",
"EventBuffer."
] | def read_items(self, tick: int):
if self._picker:
for item in self._picker.items(tick):
self._gen_event_by_item(item, tick)
return None | ['def', 'read_items(self,', 'tick:', 'int):', 'if', 'self._picker:', 'for', 'item', 'in', 'self._picker.items(tick):', 'self._gen_event_by_item(item,', 'tick)', 'return', 'None'] | 628,697 |
cedkoffeto/artificial-intelligence | configuration.py | Configuration.set_value | set_value | Modify a value in the configuration. | [
"Modify",
"a",
"value",
"in",
"the",
"configuration."
] | def set_value(self, key, value):
self._ensure_have_load_only()
(fname, parser) = self._get_parser_to_modify()
if parser is not None:
(section, name) = _disassemble_key(key)
if not parser.has_section(section):
parser.add_section(section)
parser.set(section, name, value)
... | ['def', 'set_value(self,', 'key,', 'value):', 'self._ensure_have_load_only()', '(fname,', 'parser)', '=', 'self._get_parser_to_modify()', 'if', 'parser', 'is', 'not', 'None:', '(section,', 'name)', '=', '_disassemble_key(key)', 'if', 'not', 'parser.has_section(section):', 'parser.add_section(section)', 'parser.set(sect... | 87,827 |
Tramac/Lightweight-Segmentation | debug.py | efficientnet | efficientnet | Creates a efficientnet model. | [
"Creates",
"a",
"efficientnet",
"model."
] | def efficientnet(width_coefficient=None, depth_coefficient=None, dropout_rate=0.2, drop_connect_rate=0.2):
blocks_args = ['r1_k3_s11_e1_i32_o16_se0.25', 'r2_k3_s22_e6_i16_o24_se0.25', 'r2_k5_s22_e6_i24_o40_se0.25', 'r3_k3_s22_e6_i40_o80_se0.25', 'r3_k5_s11_e6_i80_o112_se0.25', 'r4_k5_s22_e6_i112_o192_se0.25', 'r1_k... | ['def', 'efficientnet(width_coefficient=None,', 'depth_coefficient=None,', 'dropout_rate=0.2,', 'drop_connect_rate=0.2):', 'blocks_args', '=', "['r1_k3_s11_e1_i32_o16_se0.25',", "'r2_k3_s22_e6_i16_o24_se0.25',", "'r2_k5_s22_e6_i24_o40_se0.25',", "'r3_k3_s22_e6_i40_o80_se0.25',", "'r3_k5_s11_e6_i80_o112_se0.25',", "'r4_... | 602,260 |
google-research/scenic | test_lr_schedules.py | LearningRateScchedulesTest.test_constant | test_constant | Test constant schedule works correctly. | [
"Test",
"constant",
"schedule",
"works",
"correctly."
] | def test_constant(self):
config = ml_collections.ConfigDict(dict(lr_configs={'learning_rate_schedule': 'compound', 'factors': 'constant', 'base_learning_rate': 0.1}))
lr_fn = lr_schedules.get_learning_rate_fn(config)
config = config.lr_configs
for step in range(400):
expected_learning_rate = con... | ['def', 'test_constant(self):', 'config', '=', "ml_collections.ConfigDict(dict(lr_configs={'learning_rate_schedule':", "'compound',", "'factors':", "'constant',", "'base_learning_rate':", '0.1}))', 'lr_fn', '=', 'lr_schedules.get_learning_rate_fn(config)', 'config', '=', 'config.lr_configs', 'for', 'step', 'in', 'range... | 847,654 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.