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 |
|---|---|---|---|---|---|---|---|---|
jshilong/DDQ | dynamic_mask_head.py | DynamicMaskHead.init_weights | init_weights | Use xavier initialization for all weight parameter and set classification head bias as a specific value when use focal loss. | [
"Use",
"xavier",
"initialization",
"for",
"all",
"weight",
"parameter",
"and",
"set",
"classification",
"head",
"bias",
"as",
"a",
"specific",
"value",
"when",
"use",
"focal",
"loss."
] | def init_weights(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
nn.init.constant_(self.conv_logits.bias, 0.0) | ['def', 'init_weights(self):', 'for', 'p', 'in', 'self.parameters():', 'if', 'p.dim()', '>', '1:', 'nn.init.xavier_uniform_(p)', 'nn.init.constant_(self.conv_logits.bias,', '0.0)'] | 516,251 |
jason718/game-feature-learning | cpp_lint.py | RemoveMultiLineComments | RemoveMultiLineComments | Removes multiline (c-style) comments from lines. | [
"Removes",
"multiline",
"(c-style)",
"comments",
"from",
"lines."
] | def RemoveMultiLineComments(filename, lines, error):
lineix = 0
while lineix < len(lines):
lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
if lineix_begin >= len(lines):
return
lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
if lineix_end >= ... | ['def', 'RemoveMultiLineComments(filename,', 'lines,', 'error):', 'lineix', '=', '0', 'while', 'lineix', '<', 'len(lines):', 'lineix_begin', '=', 'FindNextMultiLineCommentStart(lines,', 'lineix)', 'if', 'lineix_begin', '>=', 'len(lines):', 'return', 'lineix_end', '=', 'FindNextMultiLineCommentEnd(lines,', 'lineix_begin... | 199,515 |
tensorflow/quantum | pqc_test.py | PQCTest.test_pqc_repetitions_error | test_pqc_repetitions_error | Test that invalid repetitions error properly. | [
"Test",
"that",
"invalid",
"repetitions",
"error",
"properly."
] | def test_pqc_repetitions_error(self):
symbol = sympy.Symbol('alpha')
qubit = cirq.GridQubit(0, 0)
learnable_flip = cirq.Circuit(cirq.X(qubit) ** symbol)
with self.assertRaisesRegex(TypeError, expected_regex='positive integer value'):
pqc.PQC(learnable_flip, cirq.Z(qubit), repetitions='junk')
... | ['def', 'test_pqc_repetitions_error(self):', 'symbol', '=', "sympy.Symbol('alpha')", 'qubit', '=', 'cirq.GridQubit(0,', '0)', 'learnable_flip', '=', 'cirq.Circuit(cirq.X(qubit)', '**', 'symbol)', 'with', 'self.assertRaisesRegex(TypeError,', "expected_regex='positive", 'integer', "value'):", 'pqc.PQC(learnable_flip,', '... | 835,444 |
autoai-org/CVTron | trainer_m.py | get_inputs | get_inputs | Dequeues batch and constructs inputs to object detection model. | [
"Dequeues",
"batch",
"and",
"constructs",
"inputs",
"to",
"object",
"detection",
"model."
] | def get_inputs(input_queue, num_classes, merge_multiple_label_boxes=False):
read_data_list = input_queue.dequeue()
label_id_offset = 1
def extract_images_and_targets(read_data):
image = read_data[fields.InputDataFields.image]
key = ''
if fields.InputDataFields.source_id in read_data... | ['def', 'get_inputs(input_queue,', 'num_classes,', 'merge_multiple_label_boxes=False):', 'read_data_list', '=', 'input_queue.dequeue()', 'label_id_offset', '=', '1', 'def', 'extract_images_and_targets(read_data):', 'image', '=', 'read_data[fields.InputDataFields.image]', 'key', '=', "''", 'if', 'fields.InputDataFields.... | 524,099 |
atulkum/object_detection | dataset.py | prepare_train_pascal_data | prepare_train_pascal_data | Prepare relevant PASCAL data for training the model. | [
"Prepare",
"relevant",
"PASCAL",
"data",
"for",
"training",
"the",
"model."
] | def prepare_train_pascal_data(args):
(image_dir, annotation_dir, data_dir) = (args.train_pascal_image_dir, args.train_pascal_annotation_dir, args.train_pascal_data_dir)
batch_size = args.batch_size
basic_model = args.basic_model
num_roi = args.num_roi
files = os.listdir(annotation_dir)
img_ids =... | ['def', 'prepare_train_pascal_data(args):', '(image_dir,', 'annotation_dir,', 'data_dir)', '=', '(args.train_pascal_image_dir,', 'args.train_pascal_annotation_dir,', 'args.train_pascal_data_dir)', 'batch_size', '=', 'args.batch_size', 'basic_model', '=', 'args.basic_model', 'num_roi', '=', 'args.num_roi', 'files', '=',... | 744,983 |
google/balloon-learning-environment | standard_atmosphere.py | Atmosphere.reset | reset | Resets and samples a new atmosphere. | [
"Resets",
"and",
"samples",
"a",
"new",
"atmosphere."
] | def reset(self, key: jnp.ndarray) -> None:
alpha = jax.random.uniform(key).item()
self._lapse_rates = (1 - alpha) * self._LAPSE_RATES_LOW + alpha * self._LAPSE_RATES_HIGH
self._initialize_temperature_transitions()
self._initialize_pressure_transitions() | ['def', 'reset(self,', 'key:', 'jnp.ndarray)', '->', 'None:', 'alpha', '=', 'jax.random.uniform(key).item()', 'self._lapse_rates', '=', '(1', '-', 'alpha)', '*', 'self._LAPSE_RATES_LOW', '+', 'alpha', '*', 'self._LAPSE_RATES_HIGH', 'self._initialize_temperature_transitions()', 'self._initialize_pressure_transitions()'] | 422,421 |
enuguru/artificial_intelligence_and_machine_learning | markers.py | Evaluator.get_handler | get_handler | Get a handler for the specified AST node type. | [
"Get",
"a",
"handler",
"for",
"the",
"specified",
"AST",
"node",
"type."
] | def get_handler(self, node_type):
return getattr(self, 'do_%s' % node_type, None) | ['def', 'get_handler(self,', 'node_type):', 'return', 'getattr(self,', "'do_%s'", '%', 'node_type,', 'None)'] | 163,523 |
microsoft/nlp-recipes | sequence_classification.py | SequenceClassifier.predict | predict | Scores a dataset using a fine-tuned model and a given dataloader. | [
"Scores",
"a",
"dataset",
"using",
"a",
"fine-tuned",
"model",
"and",
"a",
"given",
"dataloader."
] | def predict(self, test_dataloader, num_gpus=None, gpu_ids=None, verbose=True):
preds = list(super().predict(eval_dataloader=test_dataloader, get_inputs=Processor.get_inputs, num_gpus=num_gpus, gpu_ids=gpu_ids, verbose=verbose))
preds = np.concatenate(preds)
return np.argmax(preds, axis=1) | ['def', 'predict(self,', 'test_dataloader,', 'num_gpus=None,', 'gpu_ids=None,', 'verbose=True):', 'preds', '=', 'list(super().predict(eval_dataloader=test_dataloader,', 'get_inputs=Processor.get_inputs,', 'num_gpus=num_gpus,', 'gpu_ids=gpu_ids,', 'verbose=verbose))', 'preds', '=', 'np.concatenate(preds)', 'return', 'np... | 731,330 |
matsu0228/nlp-jp | connection.py | MWSConnection.get_last_updated_time_for_recommendations | get_last_updated_time_for_recommendations | Checks whether there are active recommendations for each category for the given marketplace, and if there are, returns the time when recommendations were last updated for each category. | [
"Checks",
"whether",
"there",
"are",
"active",
"recommendations",
"for",
"each",
"category",
"for",
"the",
"given",
"marketplace,",
"and",
"if",
"there",
"are,",
"returns",
"the",
"time",
"when",
"recommendations",
"were",
"last",
"updated",
"for",
"each",
"cate... | def get_last_updated_time_for_recommendations(self, request, response, **kw):
return self._post_request(request, kw, response) | ['def', 'get_last_updated_time_for_recommendations(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)'] | 784,984 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nav_env.py | GridWorld.set_r_obj | set_r_obj | Sets the SwiftshaderRenderer object used for rendering. | [
"Sets",
"the",
"SwiftshaderRenderer",
"object",
"used",
"for",
"rendering."
] | def set_r_obj(self, r_obj):
self.r_obj = r_obj | ['def', 'set_r_obj(self,', 'r_obj):', 'self.r_obj', '=', 'r_obj'] | 47,226 |
mj-will/nessai | test_model.py | test_parameter_in_bounds | test_parameter_in_bounds | Test parameter in bounds method. | [
"Test",
"parameter",
"in",
"bounds",
"method."
] | def test_parameter_in_bounds(model):
x = np.array([0, 0.5, 1, 3])
model.names = ['x', 'y']
model.bounds = {'x': [0, 1], 'y': [0, 4]}
val = Model.parameter_in_bounds(model, x, 'x')
np.testing.assert_array_equal(val, np.array([True, True, True, False])) | ['def', 'test_parameter_in_bounds(model):', 'x', '=', 'np.array([0,', '0.5,', '1,', '3])', 'model.names', '=', "['x',", "'y']", 'model.bounds', '=', "{'x':", '[0,', '1],', "'y':", '[0,', '4]}', 'val', '=', 'Model.parameter_in_bounds(model,', 'x,', "'x')", 'np.testing.assert_array_equal(val,', 'np.array([True,', 'True,'... | 292,295 |
sarnsdev/social-alignment-data-mining | test_hashing.py | test_bound_methods_hash | test_bound_methods_hash | Make sure that calling the same method on two different instances of the same class does resolve to the same hashes. | [
"Make",
"sure",
"that",
"calling",
"the",
"same",
"method",
"on",
"two",
"different",
"instances",
"of",
"the",
"same",
"class",
"does",
"resolve",
"to",
"the",
"same",
"hashes."
] | def test_bound_methods_hash():
a = Klass()
b = Klass()
assert hash(filter_args(a.f, [], (1,))) == hash(filter_args(b.f, [], (1,))) | ['def', 'test_bound_methods_hash():', 'a', '=', 'Klass()', 'b', '=', 'Klass()', 'assert', 'hash(filter_args(a.f,', '[],', '(1,)))', '==', 'hash(filter_args(b.f,', '[],', '(1,)))'] | 352,539 |
ducphucnguyen/TransferLearningWFN | vggish_input.py | waveform_to_examples | waveform_to_examples | Converts audio waveform into an array of examples for VGGish. | [
"Converts",
"audio",
"waveform",
"into",
"an",
"array",
"of",
"examples",
"for",
"VGGish."
] | def waveform_to_examples(data, sample_rate):
if len(data.shape) > 1:
data = np.mean(data, axis=1)
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
log_mel = mel_features.log_mel_spectrogram(data, audio_sample_rate=vggish_param... | ['def', 'waveform_to_examples(data,', 'sample_rate):', 'if', 'len(data.shape)', '>', '1:', 'data', '=', 'np.mean(data,', 'axis=1)', 'if', 'sample_rate', '!=', 'vggish_params.SAMPLE_RATE:', 'data', '=', 'resampy.resample(data,', 'sample_rate,', 'vggish_params.SAMPLE_RATE)', 'log_mel', '=', 'mel_features.log_mel_spectrog... | 905,005 |
muhanzhang/D-VAE | nlinalg.py | EighGrad.perform | perform | Implements the "reverse-mode" gradient for the eigensystem of a square matrix. | [
"Implements",
"the",
"\"reverse-mode\"",
"gradient",
"for",
"the",
"eigensystem",
"of",
"a",
"square",
"matrix."
] | def perform(self, node, inputs, outputs):
(x, w, v, W, V) = inputs
N = x.shape[0]
outer = numpy.outer
def G(n):
return sum((v[:, m] * V.T[n].dot(v[:, m]) / (w[n] - w[m]) for m in xrange(N) if m != n))
g = sum((outer(v[:, n], v[:, n] * W[n] + G(n)) for n in xrange(N)))
out = self.tri0(g)... | ['def', 'perform(self,', 'node,', 'inputs,', 'outputs):', '(x,', 'w,', 'v,', 'W,', 'V)', '=', 'inputs', 'N', '=', 'x.shape[0]', 'outer', '=', 'numpy.outer', 'def', 'G(n):', 'return', 'sum((v[:,', 'm]', '*', 'V.T[n].dot(v[:,', 'm])', '/', '(w[n]', '-', 'w[m])', 'for', 'm', 'in', 'xrange(N)', 'if', 'm', '!=', 'n))', 'g',... | 525,509 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | core.py | Command.collect_usage_pieces | collect_usage_pieces | Returns all the pieces that go into the usage line and returns it as a list of strings. | [
"Returns",
"all",
"the",
"pieces",
"that",
"go",
"into",
"the",
"usage",
"line",
"and",
"returns",
"it",
"as",
"a",
"list",
"of",
"strings."
] | def collect_usage_pieces(self, ctx):
rv = [self.options_metavar]
for param in self.get_params(ctx):
rv.extend(param.get_usage_pieces(ctx))
return rv | ['def', 'collect_usage_pieces(self,', 'ctx):', 'rv', '=', '[self.options_metavar]', 'for', 'param', 'in', 'self.get_params(ctx):', 'rv.extend(param.get_usage_pieces(ctx))', 'return', 'rv'] | 101,828 |
OpenMDAO/OpenMDAO-Framework | dumpcase.py | DumpCaseRecorder.get_iterator | get_iterator | Doesn't really make sense to have a case iterator for dump files, so just return None. | [
"Doesn't",
"really",
"make",
"sense",
"to",
"have",
"a",
"case",
"iterator",
"for",
"dump",
"files,",
"so",
"just",
"return",
"None."
] | def get_iterator(self):
return None | ['def', 'get_iterator(self):', 'return', 'None'] | 275,351 |
loicmarie/hands-detection | cifar10_eval.py | evaluate | evaluate | Eval CIFAR-10 for a number of steps. | [
"Eval",
"CIFAR-10",
"for",
"a",
"number",
"of",
"steps."
] | def evaluate():
with tf.Graph().as_default() as g:
eval_data = FLAGS.eval_data == 'test'
(images, labels) = cifar10.inputs(eval_data=eval_data)
logits = cifar10.inference(images)
top_k_op = tf.nn.in_top_k(logits, labels, 1)
variable_averages = tf.train.ExponentialMovingAverag... | ['def', 'evaluate():', 'with', 'tf.Graph().as_default()', 'as', 'g:', 'eval_data', '=', 'FLAGS.eval_data', '==', "'test'", '(images,', 'labels)', '=', 'cifar10.inputs(eval_data=eval_data)', 'logits', '=', 'cifar10.inference(images)', 'top_k_op', '=', 'tf.nn.in_top_k(logits,', 'labels,', '1)', 'variable_averages', '=', ... | 575,570 |
rishab-sharma/object_detection | np_box_mask_list_ops.py | box_list_to_box_mask_list | box_list_to_box_mask_list | Converts a BoxList containing 'masks' into a BoxMaskList. | [
"Converts",
"a",
"BoxList",
"containing",
"'masks'",
"into",
"a",
"BoxMaskList."
] | def box_list_to_box_mask_list(boxlist):
if not boxlist.has_field('masks'):
raise ValueError('boxlist does not contain mask field.')
box_mask_list = np_box_mask_list.BoxMaskList(box_data=boxlist.get(), mask_data=boxlist.get_field('masks'))
extra_fields = boxlist.get_extra_fields()
for key in extr... | ['def', 'box_list_to_box_mask_list(boxlist):', 'if', 'not', "boxlist.has_field('masks'):", 'raise', "ValueError('boxlist", 'does', 'not', 'contain', 'mask', "field.')", 'box_mask_list', '=', 'np_box_mask_list.BoxMaskList(box_data=boxlist.get(),', "mask_data=boxlist.get_field('masks'))", 'extra_fields', '=', 'boxlist.ge... | 793,356 |
weimin17/Object-Detection_HelmetDetection | model.py | Model.train_step | train_step | Train network using standard gradient descent. | [
"Train",
"network",
"using",
"standard",
"gradient",
"descent."
] | def train_step(self, sess, observations, internal_state, actions, rewards, terminated, pads, avg_episode_reward=0, greedy_episode_reward=0):
outputs = [self.raw_loss, self.gradient_ops, self.summary]
feed_dict = {self.internal_state: internal_state, self.rewards: rewards, self.terminated: terminated, self.pads:... | ['def', 'train_step(self,', 'sess,', 'observations,', 'internal_state,', 'actions,', 'rewards,', 'terminated,', 'pads,', 'avg_episode_reward=0,', 'greedy_episode_reward=0):', 'outputs', '=', '[self.raw_loss,', 'self.gradient_ops,', 'self.summary]', 'feed_dict', '=', '{self.internal_state:', 'internal_state,', 'self.rew... | 752,482 |
bhrnjica/ObjectDetection | fp16util.py | convert_network | convert_network | Converts a network's parameters and buffers to dtype. | [
"Converts",
"a",
"network's",
"parameters",
"and",
"buffers",
"to",
"dtype."
] | def convert_network(network, dtype):
for module in network.modules():
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True:
continue
convert_module(module, dtype)
return network | ['def', 'convert_network(network,', 'dtype):', 'for', 'module', 'in', 'network.modules():', 'if', 'isinstance(module,', 'torch.nn.modules.batchnorm._BatchNorm)', 'and', 'module.affine', 'is', 'True:', 'continue', 'convert_module(module,', 'dtype)', 'return', 'network'] | 744,390 |
rudranil723/mini-main | autopep8.py | extended_blank_lines | extended_blank_lines | Check for missing blank lines after class declaration. | [
"Check",
"for",
"missing",
"blank",
"lines",
"after",
"class",
"declaration."
] | def extended_blank_lines(logical_line, blank_lines, blank_before, indent_level, previous_logical):
if previous_logical.startswith('def '):
if blank_lines and pycodestyle.DOCSTRING_REGEX.match(logical_line):
yield (0, 'E303 too many blank lines ({})'.format(blank_lines))
elif pycodestyle.DOCS... | ['def', 'extended_blank_lines(logical_line,', 'blank_lines,', 'blank_before,', 'indent_level,', 'previous_logical):', 'if', "previous_logical.startswith('def", "'):", 'if', 'blank_lines', 'and', 'pycodestyle.DOCSTRING_REGEX.match(logical_line):', 'yield', '(0,', "'E303", 'too', 'many', 'blank', 'lines', "({})'.format(b... | 313,856 |
triaquae/triaquae | base.py | AppCommand.handle_app | handle_app | Perform the command's actions for ``app``, which will be the Python module corresponding to an application name given on the command line. | [
"Perform",
"the",
"command's",
"actions",
"for",
"``app``,",
"which",
"will",
"be",
"the",
"Python",
"module",
"corresponding",
"to",
"an",
"application",
"name",
"given",
"on",
"the",
"command",
"line."
] | def handle_app(self, app, **options):
raise NotImplementedError() | ['def', 'handle_app(self,', 'app,', '**options):', 'raise', 'NotImplementedError()'] | 358,341 |
glory20h/FitHuBERT | utils.py | freeze_model | freeze_model | Freeze all parameters in a model. | [
"Freeze",
"all",
"parameters",
"in",
"a",
"model."
] | def freeze_model(model):
for param in model.parameters():
param.requires_grad = False | ['def', 'freeze_model(model):', 'for', 'param', 'in', 'model.parameters():', 'param.requires_grad', '=', 'False'] | 210,980 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | dsn.py | add_similarity_loss | add_similarity_loss | Adds a loss encouraging the shared encoding from each domain to be similar. | [
"Adds",
"a",
"loss",
"encouraging",
"the",
"shared",
"encoding",
"from",
"each",
"domain",
"to",
"be",
"similar."
] | def add_similarity_loss(method_name, source_samples, target_samples, params, scope=None):
weight = dsn_loss_coefficient(params) * params['gamma_weight']
method = getattr(losses, method_name)
method(source_samples, target_samples, weight, scope) | ['def', 'add_similarity_loss(method_name,', 'source_samples,', 'target_samples,', 'params,', 'scope=None):', 'weight', '=', 'dsn_loss_coefficient(params)', '*', "params['gamma_weight']", 'method', '=', 'getattr(losses,', 'method_name)', 'method(source_samples,', 'target_samples,', 'weight,', 'scope)'] | 47,929 |
rudranil723/mini-main | test_lines.py | test_markerfacecolor_fillstyle | test_markerfacecolor_fillstyle | Test that markerfacecolor does not override fillstyle='none'. | [
"Test",
"that",
"markerfacecolor",
"does",
"not",
"override",
"fillstyle='none'."
] | def test_markerfacecolor_fillstyle():
(l,) = plt.plot([1, 3, 2], marker=MarkerStyle('o', fillstyle='none'), markerfacecolor='red')
assert l.get_fillstyle() == 'none'
assert l.get_markerfacecolor() == 'none' | ['def', 'test_markerfacecolor_fillstyle():', '(l,)', '=', 'plt.plot([1,', '3,', '2],', "marker=MarkerStyle('o',", "fillstyle='none'),", "markerfacecolor='red')", 'assert', 'l.get_fillstyle()', '==', "'none'", 'assert', 'l.get_markerfacecolor()', '==', "'none'"] | 320,286 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | progress.py | Progress.Add | Add | Increments internal current_size by size. | [
"Increments",
"internal",
"current_size",
"by",
"size."
] | def Add(self, size):
self.current_size += size | ['def', 'Add(self,', 'size):', 'self.current_size', '+=', 'size'] | 112,586 |
aasimkhan0207/computer_vision | program.py | merge_config | merge_config | Merge config into global config. | [
"Merge",
"config",
"into",
"global",
"config."
] | def merge_config(config):
for (key, value) in config.items():
if '.' not in key:
if isinstance(value, dict) and key in global_config:
global_config[key].update(value)
else:
global_config[key] = value
else:
sub_keys = key.split('.')
... | ['def', 'merge_config(config):', 'for', '(key,', 'value)', 'in', 'config.items():', 'if', "'.'", 'not', 'in', 'key:', 'if', 'isinstance(value,', 'dict)', 'and', 'key', 'in', 'global_config:', 'global_config[key].update(value)', 'else:', 'global_config[key]', '=', 'value', 'else:', 'sub_keys', '=', "key.split('.')", 'as... | 474,771 |
ChenhongyiYang/PGD | auto_augment.py | random_negative | random_negative | Randomly negate value based on random_negative_prob. | [
"Randomly",
"negate",
"value",
"based",
"on",
"random_negative_prob."
] | def random_negative(value, random_negative_prob):
return -value if np.random.rand() < random_negative_prob else value | ['def', 'random_negative(value,', 'random_negative_prob):', 'return', '-value', 'if', 'np.random.rand()', '<', 'random_negative_prob', 'else', 'value'] | 767,887 |
deepmind/dm_control | hopper.py | Physics.speed | speed | Returns horizontal speed of the Hopper. | [
"Returns",
"horizontal",
"speed",
"of",
"the",
"Hopper."
] | def speed(self):
return self.named.data.sensordata['torso_subtreelinvel'][0] | ['def', 'speed(self):', 'return', "self.named.data.sensordata['torso_subtreelinvel'][0]"] | 165,468 |
kubeflow/pipelines | utils.py | get_tabnet_trainer_pipeline_and_parameters | get_tabnet_trainer_pipeline_and_parameters | Get the TabNet training pipeline. | [
"Get",
"the",
"TabNet",
"training",
"pipeline."
] | def get_tabnet_trainer_pipeline_and_parameters(project: str, location: str, root_dir: str, target_column: str, prediction_type: str, learning_rate: float, transform_config: Optional[str]=None, dataset_level_custom_transformation_definitions: Optional[List[Dict[str, Any]]]=None, dataset_level_transformations: Optional[L... | ['def', 'get_tabnet_trainer_pipeline_and_parameters(project:', 'str,', 'location:', 'str,', 'root_dir:', 'str,', 'target_column:', 'str,', 'prediction_type:', 'str,', 'learning_rate:', 'float,', 'transform_config:', 'Optional[str]=None,', 'dataset_level_custom_transformation_definitions:', 'Optional[List[Dict[str,', 'A... | 770,859 |
AranGarcia/ArtificialQuest | world3renderer.py | GameMap.getterrain | getterrain | Gets current value in the data matrix of the map. | [
"Gets",
"current",
"value",
"in",
"the",
"data",
"matrix",
"of",
"the",
"map."
] | def getterrain(self, coords):
return self.gamemap.matrix[coords[1]][coords[0]] | ['def', 'getterrain(self,', 'coords):', 'return', 'self.gamemap.matrix[coords[1]][coords[0]]'] | 70,479 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | conftest.py | simple_date_range_series | simple_date_range_series | Series with date range index and random data for test purposes. | [
"Series",
"with",
"date",
"range",
"index",
"and",
"random",
"data",
"for",
"test",
"purposes."
] | def simple_date_range_series():
def _simple_date_range_series(start, end, freq='D'):
rng = date_range(start, end, freq=freq)
return Series(np.random.randn(len(rng)), index=rng)
return _simple_date_range_series | ['def', 'simple_date_range_series():', 'def', '_simple_date_range_series(start,', 'end,', "freq='D'):", 'rng', '=', 'date_range(start,', 'end,', 'freq=freq)', 'return', 'Series(np.random.randn(len(rng)),', 'index=rng)', 'return', '_simple_date_range_series'] | 83,530 |
5taku/tensorflow_object_detection_helper_tool | per_image_vrd_evaluation.py | PerImageVRDEvaluation.compute_detection_tp_fp | compute_detection_tp_fp | Evaluates VRD as being tp, fp from a single image. | [
"Evaluates",
"VRD",
"as",
"being",
"tp,",
"fp",
"from",
"a",
"single",
"image."
] | def compute_detection_tp_fp(self, detected_box_tuples, detected_scores, detected_class_tuples, groundtruth_box_tuples, groundtruth_class_tuples):
(scores, tp_fp_labels) = self._compute_tp_fp(detected_box_tuples=detected_box_tuples, detected_scores=detected_scores, detected_class_tuples=detected_class_tuples, ground... | ['def', 'compute_detection_tp_fp(self,', 'detected_box_tuples,', 'detected_scores,', 'detected_class_tuples,', 'groundtruth_box_tuples,', 'groundtruth_class_tuples):', '(scores,', 'tp_fp_labels)', '=', 'self._compute_tp_fp(detected_box_tuples=detected_box_tuples,', 'detected_scores=detected_scores,', 'detected_class_tu... | 923,299 |
weimin17/Object-Detection_HelmetDetection | map_utils.py | make_map | make_map | Returns a map structure. | [
"Returns",
"a",
"map",
"structure."
] | def make_map(padding, resolution, vertex=None, sc=1.0):
(min_, max_) = _get_xy_bounding_box(vertex * sc, padding=padding)
sz = np.ceil((max_ - min_ + 1) / resolution).astype(np.int32)
max_ = min_ + sz * resolution - 1
map = utils.Foo(origin=min_, size=sz, max=max_, resolution=resolution, padding=padding... | ['def', 'make_map(padding,', 'resolution,', 'vertex=None,', 'sc=1.0):', '(min_,', 'max_)', '=', '_get_xy_bounding_box(vertex', '*', 'sc,', 'padding=padding)', 'sz', '=', 'np.ceil((max_', '-', 'min_', '+', '1)', '/', 'resolution).astype(np.int32)', 'max_', '=', 'min_', '+', 'sz', '*', 'resolution', '-', '1', 'map', '=',... | 749,480 |
tueimage/essential-skills | scrollview.py | ScrollView.volume | volume | The volume plotted by the ScrollView object. | [
"The",
"volume",
"plotted",
"by",
"the",
"ScrollView",
"object."
] | def volume(self):
return self._volume | ['def', 'volume(self):', 'return', 'self._volume'] | 563,379 |
QData/deepWordBug | __init__.py | Reader.new_document | new_document | Create and return a new empty document tree (root node). | [
"Create",
"and",
"return",
"a",
"new",
"empty",
"document",
"tree",
"(root",
"node)."
] | def new_document(self):
document = utils.new_document(self.source.source_path, self.settings)
return document | ['def', 'new_document(self):', 'document', '=', 'utils.new_document(self.source.source_path,', 'self.settings)', 'return', 'document'] | 542,243 |
srai-lab/srai | generate_api.py | write_file | write_file | Writes dummy file with reference to a module. | [
"Writes",
"dummy",
"file",
"with",
"reference",
"to",
"a",
"module."
] | def write_file(file_path: Path) -> None:
root_path = file_path.relative_to(MODULE_DIRECTORY_PATH)
print(f'Loading imports from {root_path}')
(classes, functions, module_docstring) = _read_imports_from_file(file_path)
is_module = len(root_path.parts) == 1
operational_path = file_path
if is_module... | ['def', 'write_file(file_path:', 'Path)', '->', 'None:', 'root_path', '=', 'file_path.relative_to(MODULE_DIRECTORY_PATH)', "print(f'Loading", 'imports', 'from', "{root_path}')", '(classes,', 'functions,', 'module_docstring)', '=', '_read_imports_from_file(file_path)', 'is_module', '=', 'len(root_path.parts)', '==', '1'... | 371,838 |
intelligent-environments-lab/CityLearn | building.py | Building.heating_storage | heating_storage | Hot water storage object for space heating. | [
"Hot",
"water",
"storage",
"object",
"for",
"space",
"heating."
] | def heating_storage(self) -> StorageTank:
return self.__heating_storage | ['def', 'heating_storage(self)', '->', 'StorageTank:', 'return', 'self.__heating_storage'] | 105,284 |
farjon/Leaf-Counting | keypoints.py | bbox_transform | bbox_transform | Compute bounding-box regression targets for an image. | [
"Compute",
"bounding-box",
"regression",
"targets",
"for",
"an",
"image."
] | def bbox_transform(anchors, gt_boxes, mean=None, std=None):
if mean is None:
mean = np.array([0, 0, 0, 0])
if std is None:
std = np.array([0.2, 0.2, 0.2, 0.2])
if isinstance(mean, (list, tuple)):
mean = np.array(mean)
elif not isinstance(mean, np.ndarray):
raise ValueErro... | ['def', 'bbox_transform(anchors,', 'gt_boxes,', 'mean=None,', 'std=None):', 'if', 'mean', 'is', 'None:', 'mean', '=', 'np.array([0,', '0,', '0,', '0])', 'if', 'std', 'is', 'None:', 'std', '=', 'np.array([0.2,', '0.2,', '0.2,', '0.2])', 'if', 'isinstance(mean,', '(list,', 'tuple)):', 'mean', '=', 'np.array(mean)', 'elif... | 262,039 |
devashish-patel/webcam-motion-detector | regexopt.py | regex_opt_inner | regex_opt_inner | Return a regex that matches any string in the sorted list of strings. | [
"Return",
"a",
"regex",
"that",
"matches",
"any",
"string",
"in",
"the",
"sorted",
"list",
"of",
"strings."
] | def regex_opt_inner(strings, open_paren):
close_paren = open_paren and ')' or ''
if not strings:
return ''
first = strings[0]
if len(strings) == 1:
return open_paren + escape(first) + close_paren
if not first:
return open_paren + regex_opt_inner(strings[1:], '(?:') + '?' + cl... | ['def', 'regex_opt_inner(strings,', 'open_paren):', 'close_paren', '=', 'open_paren', 'and', "')'", 'or', "''", 'if', 'not', 'strings:', 'return', "''", 'first', '=', 'strings[0]', 'if', 'len(strings)', '==', '1:', 'return', 'open_paren', '+', 'escape(first)', '+', 'close_paren', 'if', 'not', 'first:', 'return', 'open_... | 984,119 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | utils.py | visualize_voxel_scatter | visualize_voxel_scatter | Function to visualize voxel (scatter). | [
"Function",
"to",
"visualize",
"voxel",
"(scatter)."
] | def visualize_voxel_scatter(points, vis_size=128):
points = np.rint(points)
points = np.swapaxes(points, 0, 2)
fig = p.figure(figsize=(1, 1), dpi=vis_size)
ax = fig.add_subplot(111, projection='3d')
x = []
y = []
z = []
(x_dimension, y_dimension, z_dimension) = points.shape
for i in ... | ['def', 'visualize_voxel_scatter(points,', 'vis_size=128):', 'points', '=', 'np.rint(points)', 'points', '=', 'np.swapaxes(points,', '0,', '2)', 'fig', '=', 'p.figure(figsize=(1,', '1),', 'dpi=vis_size)', 'ax', '=', 'fig.add_subplot(111,', "projection='3d')", 'x', '=', '[]', 'y', '=', '[]', 'z', '=', '[]', '(x_dimensio... | 26,444 |
microsoft/nlp-recipes | beam.py | Beam.get_hyp | get_hyp | Walk back to construct the full hypothesis. | [
"Walk",
"back",
"to",
"construct",
"the",
"full",
"hypothesis."
] | def get_hyp(self, timestep, k):
(hyp, attn) = ([], [])
for j in range(len(self.prev_ks[:timestep]) - 1, -1, -1):
hyp.append(self.next_ys[j + 1][k])
attn.append(self.attn[j][k])
k = self.prev_ks[j][k]
return (hyp[::-1], torch.stack(attn[::-1])) | ['def', 'get_hyp(self,', 'timestep,', 'k):', '(hyp,', 'attn)', '=', '([],', '[])', 'for', 'j', 'in', 'range(len(self.prev_ks[:timestep])', '-', '1,', '-1,', '-1):', 'hyp.append(self.next_ys[j', '+', '1][k])', 'attn.append(self.attn[j][k])', 'k', '=', 'self.prev_ks[j][k]', 'return', '(hyp[::-1],', 'torch.stack(attn[::-1... | 731,335 |
zihuitang/medical_AI_platform | _markupbase.py | ParserBase.getpos | getpos | Return current line number and offset. | [
"Return",
"current",
"line",
"number",
"and",
"offset."
] | def getpos(self):
return (self.lineno, self.offset) | ['def', 'getpos(self):', 'return', '(self.lineno,', 'self.offset)'] | 281,868 |
danaugrs/huskarl | dqn.py | DQN.push | push | Stores the transition in memory. | [
"Stores",
"the",
"transition",
"in",
"memory."
] | def push(self, transition, instance=0):
self.memory.put(transition) | ['def', 'push(self,', 'transition,', 'instance=0):', 'self.memory.put(transition)'] | 206,811 |
xvjiarui/VFS | test_augmentations.py | TestAugumentations.check_normalize | check_normalize | Check if the origin_imgs are normalized correctly into result_imgs in a given norm_cfg. | [
"Check",
"if",
"the",
"origin_imgs",
"are",
"normalized",
"correctly",
"into",
"result_imgs",
"in",
"a",
"given",
"norm_cfg."
] | def check_normalize(origin_imgs, result_imgs, norm_cfg):
target_imgs = result_imgs.copy()
target_imgs *= norm_cfg['std']
target_imgs += norm_cfg['mean']
if norm_cfg['to_bgr']:
target_imgs = target_imgs[..., ::-1].copy()
assert_array_almost_equal(origin_imgs, target_imgs, decimal=4) | ['def', 'check_normalize(origin_imgs,', 'result_imgs,', 'norm_cfg):', 'target_imgs', '=', 'result_imgs.copy()', 'target_imgs', '*=', "norm_cfg['std']", 'target_imgs', '+=', "norm_cfg['mean']", 'if', "norm_cfg['to_bgr']:", 'target_imgs', '=', 'target_imgs[...,', '::-1].copy()', 'assert_array_almost_equal(origin_imgs,', ... | 379,701 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | ga_lib.py | mutate_single | mutate_single | Mutate a single code string. | [
"Mutate",
"a",
"single",
"code",
"string."
] | def mutate_single(code_tokens, mutation_rate):
if len(code_tokens) <= 1:
return code_tokens
if code_tokens[-1] == '_':
raise ValueError('`code_tokens` must end with EOS symbol.')
else:
cs = Individual(code_tokens)
eos = []
mutated = False
for pos in range(len(cs)):
... | ['def', 'mutate_single(code_tokens,', 'mutation_rate):', 'if', 'len(code_tokens)', '<=', '1:', 'return', 'code_tokens', 'if', 'code_tokens[-1]', '==', "'_':", 'raise', "ValueError('`code_tokens`", 'must', 'end', 'with', 'EOS', "symbol.')", 'else:', 'cs', '=', 'Individual(code_tokens)', 'eos', '=', '[]', 'mutated', '=',... | 52,720 |
ashwin-phadke/cvplayground | autoaugment_utils.py | select_and_apply_random_policy | select_and_apply_random_policy | Select a random policy from `policies` and apply it to `image`. | [
"Select",
"a",
"random",
"policy",
"from",
"`policies`",
"and",
"apply",
"it",
"to",
"`image`."
] | def select_and_apply_random_policy(policies, image, bboxes):
policy_to_select = tf.random_uniform([], maxval=len(policies), dtype=tf.int32)
for (i, policy) in enumerate(policies):
(image, bboxes) = tf.cond(tf.equal(i, policy_to_select), lambda selected_policy=policy: selected_policy(image, bboxes), lamb... | ['def', 'select_and_apply_random_policy(policies,', 'image,', 'bboxes):', 'policy_to_select', '=', 'tf.random_uniform([],', 'maxval=len(policies),', 'dtype=tf.int32)', 'for', '(i,', 'policy)', 'in', 'enumerate(policies):', '(image,', 'bboxes)', '=', 'tf.cond(tf.equal(i,', 'policy_to_select),', 'lambda', 'selected_polic... | 510,529 |
Kvatsx/Artificial-Intelligence-Assignments | triangulation.py | Triangulation.get_masked_triangles | get_masked_triangles | Return an array of triangles that are not masked. | [
"Return",
"an",
"array",
"of",
"triangles",
"that",
"are",
"not",
"masked."
] | def get_masked_triangles(self):
if self.mask is not None:
return self.triangles.compress(1 - self.mask, axis=0)
else:
return self.triangles | ['def', 'get_masked_triangles(self):', 'if', 'self.mask', 'is', 'not', 'None:', 'return', 'self.triangles.compress(1', '-', 'self.mask,', 'axis=0)', 'else:', 'return', 'self.triangles'] | 1,579 |
openvinotoolkit/training_extensions | create_mvtec_ad_json_annotations.py | create_task_annotations | create_task_annotations | Create MVTec AD categories for a given task. | [
"Create",
"MVTec",
"AD",
"categories",
"for",
"a",
"given",
"task."
] | def create_task_annotations(task: str, data_path: str, annotation_path: str) -> None:
annotation_path = os.path.join(annotation_path, task)
os.makedirs(annotation_path, exist_ok=True)
for split in ['train', 'val', 'test']:
if task == 'classification':
create_json_items = create_classific... | ['def', 'create_task_annotations(task:', 'str,', 'data_path:', 'str,', 'annotation_path:', 'str)', '->', 'None:', 'annotation_path', '=', 'os.path.join(annotation_path,', 'task)', 'os.makedirs(annotation_path,', 'exist_ok=True)', 'for', 'split', 'in', "['train',", "'val',", "'test']:", 'if', 'task', '==', "'classificat... | 903,921 |
flavioschneider/rl-transfer- | uniform_control_policy.py | UniformControlPolicy.get_action | get_action | Get single action from this policy for the input observation. | [
"Get",
"single",
"action",
"from",
"this",
"policy",
"for",
"the",
"input",
"observation."
] | def get_action(self, observation):
return (self.action_space.sample(), dict()) | ['def', 'get_action(self,', 'observation):', 'return', '(self.action_space.sample(),', 'dict())'] | 861,513 |
sek788432/Waymo-2D-Object-Detection | target_assigner_test.py | CenterNetBoxTargetAssignerTest.test_assign_size_and_offset_targets | test_assign_size_and_offset_targets | Test the assign_size_and_offset_targets function. | [
"Test",
"the",
"assign_size_and_offset_targets",
"function."
] | def test_assign_size_and_offset_targets(self):
def graph_fn():
box_batch = [tf.constant([self._box_center, self._box_lower_left]), tf.constant([self._box_center_offset]), tf.constant([self._box_center_small, self._box_odd_coordinates])]
assigner = targetassigner.CenterNetBoxTargetAssigner(4)
... | ['def', 'test_assign_size_and_offset_targets(self):', 'def', 'graph_fn():', 'box_batch', '=', '[tf.constant([self._box_center,', 'self._box_lower_left]),', 'tf.constant([self._box_center_offset]),', 'tf.constant([self._box_center_small,', 'self._box_odd_coordinates])]', 'assigner', '=', 'targetassigner.CenterNetBoxTarg... | 974,928 |
AlexGeControl/Artificial-Intelligence-01-Graph-Search-02-Pacman | __init__.py | find_eggs_in_zip | find_eggs_in_zip | Find eggs in zip files; possibly multiple nested eggs. | [
"Find",
"eggs",
"in",
"zip",
"files;",
"possibly",
"multiple",
"nested",
"eggs."
] | def find_eggs_in_zip(importer, path_item, only=False):
if importer.archive.endswith('.whl'):
return
metadata = EggMetadata(importer)
if metadata.has_metadata('PKG-INFO'):
yield Distribution.from_filename(path_item, metadata=metadata)
if only:
return
for subitem in metadata.re... | ['def', 'find_eggs_in_zip(importer,', 'path_item,', 'only=False):', 'if', "importer.archive.endswith('.whl'):", 'return', 'metadata', '=', 'EggMetadata(importer)', 'if', "metadata.has_metadata('PKG-INFO'):", 'yield', 'Distribution.from_filename(path_item,', 'metadata=metadata)', 'if', 'only:', 'return', 'for', 'subitem... | 35,446 |
Katja-M/Python_NaturalLanguageProcessing | polar.py | PolarAxes.get_theta_offset | get_theta_offset | Get the offset for the location of 0 in radians. | [
"Get",
"the",
"offset",
"for",
"the",
"location",
"of",
"0",
"in",
"radians."
] | def get_theta_offset(self):
return self._theta_offset.get_matrix()[0, 2] | ['def', 'get_theta_offset(self):', 'return', 'self._theta_offset.get_matrix()[0,', '2]'] | 865,330 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjDataWrapper.efc_J_rowadr | efc_J_rowadr | row start address in colind array (njmax x 1). | [
"row",
"start",
"address",
"in",
"colind",
"array",
"(njmax",
"x",
"1)."
] | def efc_J_rowadr(self):
return util.buf_to_npy(self._ptr.contents.efc_J_rowadr, (self._model.njmax,)) | ['def', 'efc_J_rowadr(self):', 'return', 'util.buf_to_npy(self._ptr.contents.efc_J_rowadr,', '(self._model.njmax,))'] | 440,582 |
siddhanthaldar/PyTorch_Object_Detection | multibox_loss.py | MultiBoxLoss.cross_entropy_loss | cross_entropy_loss | Cross entropy loss w/o averaging across all samples. | [
"Cross",
"entropy",
"loss",
"w/o",
"averaging",
"across",
"all",
"samples."
] | def cross_entropy_loss(self, x, y):
xmax = x.data.max()
print('x y size {} {}'.format(x.size(), y.size()))
log_sum_exp = torch.log(torch.sum(torch.exp(x - xmax), 1)) + xmax
print('log_sum_exp {}'.format(log_sum_exp.size()))
return log_sum_exp - x.gather(1, y.view(-1, 1)) | ['def', 'cross_entropy_loss(self,', 'x,', 'y):', 'xmax', '=', 'x.data.max()', "print('x", 'y', 'size', '{}', "{}'.format(x.size(),", 'y.size()))', 'log_sum_exp', '=', 'torch.log(torch.sum(torch.exp(x', '-', 'xmax),', '1))', '+', 'xmax', "print('log_sum_exp", "{}'.format(log_sum_exp.size()))", 'return', 'log_sum_exp', '... | 815,587 |
hamza-murad/AALU | discovery_v2.py | QueryTermAggregationResult.from_dict | from_dict | Initialize a QueryTermAggregationResult object from a json dictionary. | [
"Initialize",
"a",
"QueryTermAggregationResult",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult':
args = {}
valid_keys = ['key', 'matching_results', 'aggregations']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for class QueryTermAggregationResult: ' + ', ... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'QueryTermAggregationResult':", 'args', '=', '{}', 'valid_keys', '=', "['key',", "'matching_results',", "'aggregations']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', '... | 5,780 |
rudranil723/mini-main | test_asof.py | date_range_frame | date_range_frame | Fixture for DataFrame of ints with date_range index Columns are ['A', 'B']. | [
"Fixture",
"for",
"DataFrame",
"of",
"ints",
"with",
"date_range",
"index",
"Columns",
"are",
"['A',",
"'B']."
] | def date_range_frame():
N = 50
rng = date_range('1/1/1990', periods=N, freq='53s')
return DataFrame({'A': np.arange(N), 'B': np.arange(N)}, index=rng) | ['def', 'date_range_frame():', 'N', '=', '50', 'rng', '=', "date_range('1/1/1990',", 'periods=N,', "freq='53s')", 'return', "DataFrame({'A':", 'np.arange(N),', "'B':", 'np.arange(N)},', 'index=rng)'] | 267,495 |
MLBazaar/MLPrimitives | utils.py | image_transform | image_transform | Apply a function image by image. | [
"Apply",
"a",
"function",
"image",
"by",
"image."
] | def image_transform(X, function, reshape_before=False, reshape_after=False, width=None, height=None, **kwargs):
if not callable(function):
function = import_object(function)
elif not callable(function):
raise ValueError('function must be a str or a callable')
flat_image = len(X[0].shape) == ... | ['def', 'image_transform(X,', 'function,', 'reshape_before=False,', 'reshape_after=False,', 'width=None,', 'height=None,', '**kwargs):', 'if', 'not', 'callable(function):', 'function', '=', 'import_object(function)', 'elif', 'not', 'callable(function):', 'raise', "ValueError('function", 'must', 'be', 'a', 'str', 'or', ... | 630,643 |
zzndream/ShipRSImageNet | recall.py | print_recall_summary | print_recall_summary | Print recalls in a table. | [
"Print",
"recalls",
"in",
"a",
"table."
] | def print_recall_summary(recalls, proposal_nums, iou_thrs, row_idxs=None, col_idxs=None, logger=None):
proposal_nums = np.array(proposal_nums, dtype=np.int32)
iou_thrs = np.array(iou_thrs)
if row_idxs is None:
row_idxs = np.arange(proposal_nums.size)
if col_idxs is None:
col_idxs = np.ar... | ['def', 'print_recall_summary(recalls,', 'proposal_nums,', 'iou_thrs,', 'row_idxs=None,', 'col_idxs=None,', 'logger=None):', 'proposal_nums', '=', 'np.array(proposal_nums,', 'dtype=np.int32)', 'iou_thrs', '=', 'np.array(iou_thrs)', 'if', 'row_idxs', 'is', 'None:', 'row_idxs', '=', 'np.arange(proposal_nums.size)', 'if',... | 901,186 |
Naurislv/P12.1-Semantic-Segmentation | helper.py | preprocessing | preprocessing | Preprocess images and labels for training. | [
"Preprocess",
"images",
"and",
"labels",
"for",
"training."
] | def preprocessing(images, labels):
(images, _) = augmentation.RANDOM_BRIGHTNESS(images, min_bright=-50, max_bright=40)
(images, _) = augmentation.RANDOM_NOISE(images, amount=15, noise_chance=0.5)
for (idx, (img, lbl)) in enumerate(zip(images, labels)):
(im_augm, _) = augmentation.RANDOM_BLUR(img, bl... | ['def', 'preprocessing(images,', 'labels):', '(images,', '_)', '=', 'augmentation.RANDOM_BRIGHTNESS(images,', 'min_bright=-50,', 'max_bright=40)', '(images,', '_)', '=', 'augmentation.RANDOM_NOISE(images,', 'amount=15,', 'noise_chance=0.5)', 'for', '(idx,', '(img,', 'lbl))', 'in', 'enumerate(zip(images,', 'labels)):', ... | 777,001 |
openai/gym | multi_discrete.py | MultiDiscrete.contains | contains | Return boolean specifying if x is a valid member of this space. | [
"Return",
"boolean",
"specifying",
"if",
"x",
"is",
"a",
"valid",
"member",
"of",
"this",
"space."
] | def contains(self, x) -> bool:
if isinstance(x, Sequence):
x = np.array(x)
return bool(isinstance(x, np.ndarray) and x.shape == self.shape and (x.dtype != object) and np.all(0 <= x) and np.all(x < self.nvec)) | ['def', 'contains(self,', 'x)', '->', 'bool:', 'if', 'isinstance(x,', 'Sequence):', 'x', '=', 'np.array(x)', 'return', 'bool(isinstance(x,', 'np.ndarray)', 'and', 'x.shape', '==', 'self.shape', 'and', '(x.dtype', '!=', 'object)', 'and', 'np.all(0', '<=', 'x)', 'and', 'np.all(x', '<', 'self.nvec))'] | 234,190 |
OpenMDAO/OpenMDAO-Framework | domain.py | DomainObj.shape | shape | List of coordinate index limits for each zone. | [
"List",
"of",
"coordinate",
"index",
"limits",
"for",
"each",
"zone."
] | def shape(self):
return [zone.shape for zone in self.zones] | ['def', 'shape(self):', 'return', '[zone.shape', 'for', 'zone', 'in', 'self.zones]'] | 275,452 |
AxeldeRomblay/MLBox | test_drift_threshold.py | test_sync_fit_drift_threshold | test_sync_fit_drift_threshold | Test method sync_fit of drift_threshold module. | [
"Test",
"method",
"sync_fit",
"of",
"drift_threshold",
"module."
] | def test_sync_fit_drift_threshold():
df_train = pd.read_csv('data_for_tests/clean_train.csv')
df_test = pd.read_csv('data_for_tests/clean_test.csv')
estimator = RandomForestClassifier(n_estimators=50, n_jobs=-1, max_features=1.0, min_samples_leaf=5, max_depth=5)
score = sync_fit(df_train, df_test, estim... | ['def', 'test_sync_fit_drift_threshold():', 'df_train', '=', "pd.read_csv('data_for_tests/clean_train.csv')", 'df_test', '=', "pd.read_csv('data_for_tests/clean_test.csv')", 'estimator', '=', 'RandomForestClassifier(n_estimators=50,', 'n_jobs=-1,', 'max_features=1.0,', 'min_samples_leaf=5,', 'max_depth=5)', 'score', '=... | 630,031 |
AgnostiqHQ/covalent | results_test.py | test_result_post_process | test_result_post_process | Test client-side post-processing of results. | [
"Test",
"client-side",
"post-processing",
"of",
"results."
] | def test_result_post_process(mocker):
import covalent as ct
@ct.electron
def construct_cu_slab(x):
return x
@ct.electron
def compute_system_energy(x):
return x
@ct.electron
def construct_n_molecule(x):
return x
@ct.electron
def get_relaxed_slab(x):
... | ['def', 'test_result_post_process(mocker):', 'import', 'covalent', 'as', 'ct', '@ct.electron', 'def', 'construct_cu_slab(x):', 'return', 'x', '@ct.electron', 'def', 'compute_system_energy(x):', 'return', 'x', '@ct.electron', 'def', 'construct_n_molecule(x):', 'return', 'x', '@ct.electron', 'def', 'get_relaxed_slab(x):'... | 489,827 |
ViTAE-Transformer/ViTDet | bucketing_bbox_coder.py | BucketingBBoxCoder.encode | encode | Get bucketing estimation and fine regression targets during training. | [
"Get",
"bucketing",
"estimation",
"and",
"fine",
"regression",
"targets",
"during",
"training."
] | def encode(self, bboxes, gt_bboxes):
assert bboxes.size(0) == gt_bboxes.size(0)
assert bboxes.size(-1) == gt_bboxes.size(-1) == 4
encoded_bboxes = bbox2bucket(bboxes, gt_bboxes, self.num_buckets, self.scale_factor, self.offset_topk, self.offset_upperbound, self.cls_ignore_neighbor)
return encoded_bboxes | ['def', 'encode(self,', 'bboxes,', 'gt_bboxes):', 'assert', 'bboxes.size(0)', '==', 'gt_bboxes.size(0)', 'assert', 'bboxes.size(-1)', '==', 'gt_bboxes.size(-1)', '==', '4', 'encoded_bboxes', '=', 'bbox2bucket(bboxes,', 'gt_bboxes,', 'self.num_buckets,', 'self.scale_factor,', 'self.offset_topk,', 'self.offset_upperbound... | 945,259 |
caiiiac/Machine-Learning-with-Python | twenty_newsgroups.py | download_20newsgroups | download_20newsgroups | Download the 20 newsgroups data and stored it as a zipped pickle. | [
"Download",
"the",
"20",
"newsgroups",
"data",
"and",
"stored",
"it",
"as",
"a",
"zipped",
"pickle."
] | def download_20newsgroups(target_dir, cache_path):
archive_path = os.path.join(target_dir, ARCHIVE_NAME)
train_path = os.path.join(target_dir, TRAIN_FOLDER)
test_path = os.path.join(target_dir, TEST_FOLDER)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
if os.path.exists(archive_... | ['def', 'download_20newsgroups(target_dir,', 'cache_path):', 'archive_path', '=', 'os.path.join(target_dir,', 'ARCHIVE_NAME)', 'train_path', '=', 'os.path.join(target_dir,', 'TRAIN_FOLDER)', 'test_path', '=', 'os.path.join(target_dir,', 'TEST_FOLDER)', 'if', 'not', 'os.path.exists(target_dir):', 'os.makedirs(target_dir... | 720,512 |
myothida/Supervised-Machine-Learning | text_file.py | TextFile.readlines | readlines | Read and return the list of all logical lines remaining in the current file. | [
"Read",
"and",
"return",
"the",
"list",
"of",
"all",
"logical",
"lines",
"remaining",
"in",
"the",
"current",
"file."
] | def readlines(self):
lines = []
while True:
line = self.readline()
if line is None:
return lines
lines.append(line) | ['def', 'readlines(self):', 'lines', '=', '[]', 'while', 'True:', 'line', '=', 'self.readline()', 'if', 'line', 'is', 'None:', 'return', 'lines', 'lines.append(line)'] | 447,140 |
cristiand391/cs50ai | tictactoe.py | terminal | terminal | Returns True if game is over, False otherwise. | [
"Returns",
"True",
"if",
"game",
"is",
"over,",
"False",
"otherwise."
] | def terminal(board):
if winner(board) != None:
return True
for row in board:
for cell in row:
if cell == EMPTY:
return False
return True | ['def', 'terminal(board):', 'if', 'winner(board)', '!=', 'None:', 'return', 'True', 'for', 'row', 'in', 'board:', 'for', 'cell', 'in', 'row:', 'if', 'cell', '==', 'EMPTY:', 'return', 'False', 'return', 'True'] | 192,146 |
rainer85ah/ComputerVision | helpers.py | vis_hybrid_image | vis_hybrid_image | Visualize a hybrid image by progressively downsampling the image and concatenating all of the images together. | [
"Visualize",
"a",
"hybrid",
"image",
"by",
"progressively",
"downsampling",
"the",
"image",
"and",
"concatenating",
"all",
"of",
"the",
"images",
"together."
] | def vis_hybrid_image(hybrid_image):
hybrid_image = hybrid_image / 255.0
scales = 5
scale_factor = 0.5
padding = 5
original_height = hybrid_image.shape[0]
num_colors = 1 if hybrid_image.ndim == 2 else 3
output = np.copy(hybrid_image)
cur_image = np.copy(hybrid_image)
for scale in rang... | ['def', 'vis_hybrid_image(hybrid_image):', 'hybrid_image', '=', 'hybrid_image', '/', '255.0', 'scales', '=', '5', 'scale_factor', '=', '0.5', 'padding', '=', '5', 'original_height', '=', 'hybrid_image.shape[0]', 'num_colors', '=', '1', 'if', 'hybrid_image.ndim', '==', '2', 'else', '3', 'output', '=', 'np.copy(hybrid_im... | 472,077 |
weimin17/Object-Detection_HelmetDetection | data_utils.py | resize_images | resize_images | Resize images to new dimensions. | [
"Resize",
"images",
"to",
"new",
"dimensions."
] | def resize_images(images, new_width, new_height):
resized_images = np.zeros([images.shape[0], new_width, new_height], dtype=np.float32)
for i in range(images.shape[0]):
resized_images[i, :, :] = imresize(images[i, :, :], [new_width, new_height], interp='bilinear', mode=None)
return resized_images | ['def', 'resize_images(images,', 'new_width,', 'new_height):', 'resized_images', '=', 'np.zeros([images.shape[0],', 'new_width,', 'new_height],', 'dtype=np.float32)', 'for', 'i', 'in', 'range(images.shape[0]):', 'resized_images[i,', ':,', ':]', '=', 'imresize(images[i,', ':,', ':],', '[new_width,', 'new_height],', "int... | 763,339 |
43Carrig/recurrent_neural_networks_practice | __init__.py | ABSLLogger.warn | warn | Logs 'msg % args' with severity 'WARN'. | [
"Logs",
"'msg",
"%",
"args'",
"with",
"severity",
"'WARN'."
] | def warn(self, msg, *args, **kwargs):
if six.PY3:
warnings.warn("The 'warn' method is deprecated, use 'warning' instead", DeprecationWarning, 2)
self.log(logging.WARN, msg, *args, **kwargs) | ['def', 'warn(self,', 'msg,', '*args,', '**kwargs):', 'if', 'six.PY3:', 'warnings.warn("The', "'warn'", 'method', 'is', 'deprecated,', 'use', "'warning'", 'instead",', 'DeprecationWarning,', '2)', 'self.log(logging.WARN,', 'msg,', '*args,', '**kwargs)'] | 309,714 |
rifqind/Agent-Programs-3KS1 | mistune.py | escape_link | escape_link | Remove dangerous URL schemes like javascript: and escape afterwards. | [
"Remove",
"dangerous",
"URL",
"schemes",
"like",
"javascript:",
"and",
"escape",
"afterwards."
] | def escape_link(url):
lower_url = url.lower().strip('\x00\x1a \n\r\t')
for scheme in _scheme_blacklist:
if re.sub('[^A-Za-z0-9\\/:]+', '', lower_url).startswith(scheme):
return ''
return escape(url, quote=True, smart_amp=False) | ['def', 'escape_link(url):', 'lower_url', '=', "url.lower().strip('\\x00\\x1a", "\\n\\r\\t')", 'for', 'scheme', 'in', '_scheme_blacklist:', 'if', "re.sub('[^A-Za-z0-9\\\\/:]+',", "'',", 'lower_url).startswith(scheme):', 'return', "''", 'return', 'escape(url,', 'quote=True,', 'smart_amp=False)'] | 40,472 |
THUNLP-MT/THUCC | bottle.py | cookie_is_encoded | cookie_is_encoded | Return True if the argument looks like a encoded cookie. | [
"Return",
"True",
"if",
"the",
"argument",
"looks",
"like",
"a",
"encoded",
"cookie."
] | def cookie_is_encoded(data):
return bool(data.startswith(tob('!')) and tob('?') in data) | ['def', 'cookie_is_encoded(data):', 'return', "bool(data.startswith(tob('!'))", 'and', "tob('?')", 'in', 'data)'] | 916,473 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | __init__.py | FCompiler.get_flags | get_flags | List of flags common to all compiler types. | [
"List",
"of",
"flags",
"common",
"to",
"all",
"compiler",
"types."
] | def get_flags(self):
return [] + self.pic_flags | ['def', 'get_flags(self):', 'return', '[]', '+', 'self.pic_flags'] | 102,729 |
devashish-patel/webcam-motion-detector | retrying.py | Retrying.fixed_sleep | fixed_sleep | Sleep a fixed amount of time between each retry. | [
"Sleep",
"a",
"fixed",
"amount",
"of",
"time",
"between",
"each",
"retry."
] | def fixed_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
return self._wait_fixed | ['def', 'fixed_sleep(self,', 'previous_attempt_number,', 'delay_since_first_attempt_ms):', 'return', 'self._wait_fixed'] | 983,100 |
devashish-patel/webcam-motion-detector | check.py | get_missing_reqs | get_missing_reqs | Return all of the requirements of `dist` that aren't present in `installed_dists`. | [
"Return",
"all",
"of",
"the",
"requirements",
"of",
"`dist`",
"that",
"aren't",
"present",
"in",
"`installed_dists`."
] | def get_missing_reqs(dist, installed_dists):
installed_names = set((d.project_name.lower() for d in installed_dists))
missing_requirements = set()
for requirement in dist.requires():
if requirement.project_name.lower() not in installed_names:
missing_requirements.add(requirement)
... | ['def', 'get_missing_reqs(dist,', 'installed_dists):', 'installed_names', '=', 'set((d.project_name.lower()', 'for', 'd', 'in', 'installed_dists))', 'missing_requirements', '=', 'set()', 'for', 'requirement', 'in', 'dist.requires():', 'if', 'requirement.project_name.lower()', 'not', 'in', 'installed_names:', 'missing_r... | 982,856 |
kornia/kornia | test_linalg.py | euler_angles_to_rotation_matrix | euler_angles_to_rotation_matrix | Create a rotation matrix from x, y, z angles. | [
"Create",
"a",
"rotation",
"matrix",
"from",
"x,",
"y,",
"z",
"angles."
] | def euler_angles_to_rotation_matrix(x, y, z):
assert x.dim() == 1, x.shape
assert x.shape == y.shape == z.shape
(ones, zeros) = (torch.ones_like(x), torch.zeros_like(x))
rx_tmp = [ones, zeros, zeros, zeros, zeros, torch.cos(x), -torch.sin(x), zeros, zeros, torch.sin(x), torch.cos(x), zeros, zeros, zeros... | ['def', 'euler_angles_to_rotation_matrix(x,', 'y,', 'z):', 'assert', 'x.dim()', '==', '1,', 'x.shape', 'assert', 'x.shape', '==', 'y.shape', '==', 'z.shape', '(ones,', 'zeros)', '=', '(torch.ones_like(x),', 'torch.zeros_like(x))', 'rx_tmp', '=', '[ones,', 'zeros,', 'zeros,', 'zeros,', 'zeros,', 'torch.cos(x),', '-torch... | 622,333 |
cszhilu1998/SelfDZSR | base_options.py | BaseOptions.initialize | initialize | Define the common options that are used in both training and test. | [
"Define",
"the",
"common",
"options",
"that",
"are",
"used",
"in",
"both",
"training",
"and",
"test."
] | def initialize(self, parser):
parser.add_argument('--dataroot', type=str, default='')
parser.add_argument('--dataset_name', type=str, default=['eth'], nargs='+')
parser.add_argument('--max_dataset_size', type=int, default=inf)
parser.add_argument('--scale', type=int, default=2, help='Super-resolution sc... | ['def', 'initialize(self,', 'parser):', "parser.add_argument('--dataroot',", 'type=str,', "default='')", "parser.add_argument('--dataset_name',", 'type=str,', "default=['eth'],", "nargs='+')", "parser.add_argument('--max_dataset_size',", 'type=int,', 'default=inf)', "parser.add_argument('--scale',", 'type=int,', 'defau... | 342,320 |
triaquae/triaquae | asn1.py | DerSequence.hasInts | hasInts | Return the number of items in this sequence that are numbers. | [
"Return",
"the",
"number",
"of",
"items",
"in",
"this",
"sequence",
"that",
"are",
"numbers."
] | def hasInts(self):
return len(filter(isInt, self._seq)) | ['def', 'hasInts(self):', 'return', 'len(filter(isInt,', 'self._seq))'] | 356,395 |
MycroftAI/mycroft-core | test_skill_loader.py | TestSkillLoader.test_skill_reload | test_skill_reload | Test reloading a skill that was modified. | [
"Test",
"reloading",
"a",
"skill",
"that",
"was",
"modified."
] | def test_skill_reload(self):
self.loader.instance = Mock()
self.loader.loaded = True
self.loader.last_loaded = 0
with patch(self.mock_package + 'time') as time_mock:
time_mock.return_value = 100
with patch(self.mock_package + 'SettingsMetaUploader'):
self.loader.reload()
... | ['def', 'test_skill_reload(self):', 'self.loader.instance', '=', 'Mock()', 'self.loader.loaded', '=', 'True', 'self.loader.last_loaded', '=', '0', 'with', 'patch(self.mock_package', '+', "'time')", 'as', 'time_mock:', 'time_mock.return_value', '=', '100', 'with', 'patch(self.mock_package', '+', "'SettingsMetaUploader')... | 290,971 |
enuguru/artificial_intelligence_and_machine_learning | test_helpers.py | StdStreamCapturingMixin.stderr | stderr | Return the data written to stderr during the test. | [
"Return",
"the",
"data",
"written",
"to",
"stderr",
"during",
"the",
"test."
] | def stderr(self):
return self.captured_stderr.getvalue() | ['def', 'stderr(self):', 'return', 'self.captured_stderr.getvalue()'] | 157,649 |
aws/sagemaker-python-sdk | model.py | ChainerModel.prepare_container_def | prepare_container_def | Return a container definition with framework configuration set in model environment. | [
"Return",
"a",
"container",
"definition",
"with",
"framework",
"configuration",
"set",
"in",
"model",
"environment."
] | def prepare_container_def(self, instance_type=None, accelerator_type=None, serverless_inference_config=None):
deploy_image = self.image_uri
if not deploy_image:
if instance_type is None and serverless_inference_config is None:
raise ValueError('Must supply either an instance type (for choosi... | ['def', 'prepare_container_def(self,', 'instance_type=None,', 'accelerator_type=None,', 'serverless_inference_config=None):', 'deploy_image', '=', 'self.image_uri', 'if', 'not', 'deploy_image:', 'if', 'instance_type', 'is', 'None', 'and', 'serverless_inference_config', 'is', 'None:', 'raise', "ValueError('Must", 'suppl... | 829,810 |
nguyenvdat/CS221 | graderUtil.py | Grader.addManualPart | addManualPart | Add a manual part. | [
"Add",
"a",
"manual",
"part."
] | def addManualPart(self, name, maxPoints, extraCredit=False, description=''):
self.assertNewName(name)
part = Part(name, None, maxPoints, None, extraCredit, description, basic=False)
self.parts.append(part) | ['def', 'addManualPart(self,', 'name,', 'maxPoints,', 'extraCredit=False,', "description=''):", 'self.assertNewName(name)', 'part', '=', 'Part(name,', 'None,', 'maxPoints,', 'None,', 'extraCredit,', 'description,', 'basic=False)', 'self.parts.append(part)'] | 227,587 |
triaquae/triaquae | html.py | strip_entities | strip_entities | Returns the given HTML with all entities (&something;) stripped. | [
"Returns",
"the",
"given",
"HTML",
"with",
"all",
"entities",
"(&something;)",
"stripped."
] | def strip_entities(value):
return re.sub('&(?:\\w+|#\\d+);', '', force_text(value)) | ['def', 'strip_entities(value):', 'return', "re.sub('&(?:\\\\w+|#\\\\d+);',", "'',", 'force_text(value))'] | 424,127 |
scottemmons/rvs | visualize.py | aggregate_performance | aggregate_performance | Combine the performance vectors and their attributes into one DataFrame. | [
"Combine",
"the",
"performance",
"vectors",
"and",
"their",
"attributes",
"into",
"one",
"DataFrame."
] | def aggregate_performance(performance_vecs: Union[np.ndarray, List[np.ndarray]], attribute_dicts: List[Dict[str, Union[int, float, str]]], performance_metric: str) -> pd.DataFrame:
assert len(performance_vecs) == len(attribute_dicts), 'Must have one attribute dict per performance vec'
df = pd.DataFrame()
fo... | ['def', 'aggregate_performance(performance_vecs:', 'Union[np.ndarray,', 'List[np.ndarray]],', 'attribute_dicts:', 'List[Dict[str,', 'Union[int,', 'float,', 'str]]],', 'performance_metric:', 'str)', '->', 'pd.DataFrame:', 'assert', 'len(performance_vecs)', '==', 'len(attribute_dicts),', "'Must", 'have', 'one', 'attribut... | 327,041 |
microsoft/InnerEye-DeepLearning | test_lightning_containers.py | test_file_system_with_subfolders | test_file_system_with_subfolders | Test if a subfolder can be created within the output folder structure, for use with cross validation. | [
"Test",
"if",
"a",
"subfolder",
"can",
"be",
"created",
"within",
"the",
"output",
"folder",
"structure,",
"for",
"use",
"with",
"cross",
"validation."
] | def test_file_system_with_subfolders(test_output_dirs: OutputFolderForTests) -> None:
model = DummyModel()
model.set_output_to(test_output_dirs.root_dir)
container = InnerEyeContainer(model)
assert container.file_system_config == model.file_system_config
runner = MLRunner(model_config=model)
run... | ['def', 'test_file_system_with_subfolders(test_output_dirs:', 'OutputFolderForTests)', '->', 'None:', 'model', '=', 'DummyModel()', 'model.set_output_to(test_output_dirs.root_dir)', 'container', '=', 'InnerEyeContainer(model)', 'assert', 'container.file_system_config', '==', 'model.file_system_config', 'runner', '=', '... | 613,585 |
voxel51/fiftyone | dataset.py | Dataset.delete_group_slice | delete_group_slice | Deletes all samples in the given group slice from the dataset. | [
"Deletes",
"all",
"samples",
"in",
"the",
"given",
"group",
"slice",
"from",
"the",
"dataset."
] | def delete_group_slice(self, name):
if self.media_type != fom.GROUP:
raise ValueError('Dataset has no groups')
if name not in self._doc.group_media_types:
raise ValueError("Dataset has no group slice '%s'" % name)
self.delete_samples(self.select_group_slices(name))
self._doc.group_media_... | ['def', 'delete_group_slice(self,', 'name):', 'if', 'self.media_type', '!=', 'fom.GROUP:', 'raise', "ValueError('Dataset", 'has', 'no', "groups')", 'if', 'name', 'not', 'in', 'self._doc.group_media_types:', 'raise', 'ValueError("Dataset', 'has', 'no', 'group', 'slice', '\'%s\'"', '%', 'name)', 'self.delete_samples(self... | 582,914 |
googleapis/python-aiplatform | _vision_models.py | ImageCaptioningModel.get_captions | get_captions | Generates captions for a given image. | [
"Generates",
"captions",
"for",
"a",
"given",
"image."
] | def get_captions(self, image: Image, *, number_of_results: int=1, language: str='en') -> List[str]:
instance = {'image': {'bytesBase64Encoded': image._as_base64_string()}}
parameters = {'sampleCount': number_of_results, 'language': language}
response = self._endpoint.predict(instances=[instance], parameters... | ['def', 'get_captions(self,', 'image:', 'Image,', '*,', 'number_of_results:', 'int=1,', 'language:', "str='en')", '->', 'List[str]:', 'instance', '=', "{'image':", "{'bytesBase64Encoded':", 'image._as_base64_string()}}', 'parameters', '=', "{'sampleCount':", 'number_of_results,', "'language':", 'language}', 'response',... | 863,210 |
Ruturaj123/Flowchart-Detection | model_fn_test.py | EstimatorSpecEvalTest.testTupleMetric | testTupleMetric | Tests that no errors are raised when a metric is tuple-valued. | [
"Tests",
"that",
"no",
"errors",
"are",
"raised",
"when",
"a",
"metric",
"is",
"tuple-valued."
] | def testTupleMetric(self):
with ops.Graph().as_default(), self.test_session():
loss = constant_op.constant(1.0)
model_fn.EstimatorSpec(mode=model_fn.ModeKeys.EVAL, loss=loss, eval_metric_ops={'some_metric': ((loss, loss, (constant_op.constant(2), loss)), control_flow_ops.no_op())}) | ['def', 'testTupleMetric(self):', 'with', 'ops.Graph().as_default(),', 'self.test_session():', 'loss', '=', 'constant_op.constant(1.0)', 'model_fn.EstimatorSpec(mode=model_fn.ModeKeys.EVAL,', 'loss=loss,', "eval_metric_ops={'some_metric':", '((loss,', 'loss,', '(constant_op.constant(2),', 'loss)),', 'control_flow_ops.n... | 605,187 |
neu-spiral/GraphTransferLearning-NEU | random_walks.py | Graph.get_alias_edge | get_alias_edge | Get the alias edge setup lists for a given edge. | [
"Get",
"the",
"alias",
"edge",
"setup",
"lists",
"for",
"a",
"given",
"edge."
] | def get_alias_edge(self, src, dst):
G = self.G
p = self.p
q = self.q
unnormalized_probs = []
for dst_nbr in sorted(G.neighbors(dst)):
if dst_nbr == src:
unnormalized_probs.append(G[dst][dst_nbr]['weight'] / p)
elif G.has_edge(dst_nbr, src):
unnormalized_probs.... | ['def', 'get_alias_edge(self,', 'src,', 'dst):', 'G', '=', 'self.G', 'p', '=', 'self.p', 'q', '=', 'self.q', 'unnormalized_probs', '=', '[]', 'for', 'dst_nbr', 'in', 'sorted(G.neighbors(dst)):', 'if', 'dst_nbr', '==', 'src:', "unnormalized_probs.append(G[dst][dst_nbr]['weight']", '/', 'p)', 'elif', 'G.has_edge(dst_nbr,... | 580,809 |
mohitsewak/DeepReinforcementLearning | Q_Learning.py | BehaviorPolicy.return_epsilon_greedy_policy | return_epsilon_greedy_policy | Epsilon-Greedy Policy Implementation This is the implementation of the Epsilon-Greedy policy as returned by the getPolicy method when "epsilon-greedy" policy type is selected. | [
"Epsilon-Greedy",
"Policy",
"Implementation",
"This",
"is",
"the",
"implementation",
"of",
"the",
"Epsilon-Greedy",
"policy",
"as",
"returned",
"by",
"the",
"getPolicy",
"method",
"when",
"\"epsilon-greedy\"",
"policy",
"type",
"is",
"selected."
] | def return_epsilon_greedy_policy(self):
def choose_action_by_epsilon_greedy(values_of_all_possible_actions):
logger.debug('Taking e-greedy action for action values' + str(values_of_all_possible_actions))
prob_taking_best_action_only = 1 - self.epsilon
prob_taking_any_random_action = self.ep... | ['def', 'return_epsilon_greedy_policy(self):', 'def', 'choose_action_by_epsilon_greedy(values_of_all_possible_actions):', "logger.debug('Taking", 'e-greedy', 'action', 'for', 'action', "values'", '+', 'str(values_of_all_possible_actions))', 'prob_taking_best_action_only', '=', '1', '-', 'self.epsilon', 'prob_taking_any... | 539,355 |
pcko1/Deep-Drug-Coder | ddc_v3.py | timed | timed | Timer decorator to benchmark functions. | [
"Timer",
"decorator",
"to",
"benchmark",
"functions."
] | def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
tstart = datetime.now()
result = func(*args, **kwargs)
elapsed = (datetime.now() - tstart).microseconds / 1000000.0
print('Elapsed time: %.3f seconds.' % elapsed)
return result
return wrapper | ['def', 'timed(func):', '@wraps(func)', 'def', 'wrapper(*args,', '**kwargs):', 'tstart', '=', 'datetime.now()', 'result', '=', 'func(*args,', '**kwargs)', 'elapsed', '=', '(datetime.now()', '-', 'tstart).microseconds', '/', '1000000.0', "print('Elapsed", 'time:', '%.3f', "seconds.'", '%', 'elapsed)', 'return', 'result'... | 517,014 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | scopes.py | add_arg_scope | add_arg_scope | Decorates a function with args so it can be used within an arg_scope. | [
"Decorates",
"a",
"function",
"with",
"args",
"so",
"it",
"can",
"be",
"used",
"within",
"an",
"arg_scope."
] | def add_arg_scope(func):
@functools.wraps(func)
def func_with_args(*args, **kwargs):
current_scope = _current_arg_scope()
current_args = kwargs
key_func = (func.__module__, func.__name__)
if key_func in current_scope:
current_args = current_scope[key_func].copy()
... | ['def', 'add_arg_scope(func):', '@functools.wraps(func)', 'def', 'func_with_args(*args,', '**kwargs):', 'current_scope', '=', '_current_arg_scope()', 'current_args', '=', 'kwargs', 'key_func', '=', '(func.__module__,', 'func.__name__)', 'if', 'key_func', 'in', 'current_scope:', 'current_args', '=', 'current_scope[key_f... | 55,362 |
devashish-patel/webcam-motion-detector | __init__.py | compose_all | compose_all | Parse all YAML documents in a stream and produce corresponding representation trees. | [
"Parse",
"all",
"YAML",
"documents",
"in",
"a",
"stream",
"and",
"produce",
"corresponding",
"representation",
"trees."
] | def compose_all(stream, Loader=Loader):
loader = Loader(stream)
try:
while loader.check_node():
yield loader.get_node()
finally:
loader.dispose() | ['def', 'compose_all(stream,', 'Loader=Loader):', 'loader', '=', 'Loader(stream)', 'try:', 'while', 'loader.check_node():', 'yield', 'loader.get_node()', 'finally:', 'loader.dispose()'] | 985,405 |
gunthercox/ChatterBot | default.py | QueryParser.remove_plugin_class | remove_plugin_class | Removes any plugins of the given class from this parser. | [
"Removes",
"any",
"plugins",
"of",
"the",
"given",
"class",
"from",
"this",
"parser."
] | def remove_plugin_class(self, cls):
self.plugins = [pi for pi in self.plugins if not isinstance(pi, cls)] | ['def', 'remove_plugin_class(self,', 'cls):', 'self.plugins', '=', '[pi', 'for', 'pi', 'in', 'self.plugins', 'if', 'not', 'isinstance(pi,', 'cls)]'] | 484,623 |
43Carrig/recurrent_neural_networks_practice | mnist.py | loss | loss | Calculates the loss from the logits and the labels. | [
"Calculates",
"the",
"loss",
"from",
"the",
"logits",
"and",
"the",
"labels."
] | def loss(logits, labels):
labels = tf.to_int64(labels)
return tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) | ['def', 'loss(logits,', 'labels):', 'labels', '=', 'tf.to_int64(labels)', 'return', 'tf.losses.sparse_softmax_cross_entropy(labels=labels,', 'logits=logits)'] | 335,718 |
devashish-patel/webcam-motion-detector | dist.py | write_pkg_info | write_pkg_info | Write the PKG-INFO file into the release tree. | [
"Write",
"the",
"PKG-INFO",
"file",
"into",
"the",
"release",
"tree."
] | def write_pkg_info(self, base_dir):
with open(os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8') as pkg_info:
self.write_pkg_file(pkg_info) | ['def', 'write_pkg_info(self,', 'base_dir):', 'with', 'open(os.path.join(base_dir,', "'PKG-INFO'),", "'w',", "encoding='UTF-8')", 'as', 'pkg_info:', 'self.write_pkg_file(pkg_info)'] | 984,553 |
SamsungLabs/imvoxelnet | lyft_eval.py | lyft_eval | lyft_eval | Evaluation API for Lyft dataset. | [
"Evaluation",
"API",
"for",
"Lyft",
"dataset."
] | def lyft_eval(lyft, data_root, res_path, eval_set, output_dir, logger=None):
gts = load_lyft_gts(lyft, data_root, eval_set, logger)
predictions = load_lyft_predictions(res_path)
class_names = get_class_names(gts)
print('Calculating mAP@0.5:0.95...')
iou_thresholds = [0.5, 0.55, 0.6, 0.65, 0.7, 0.75,... | ['def', 'lyft_eval(lyft,', 'data_root,', 'res_path,', 'eval_set,', 'output_dir,', 'logger=None):', 'gts', '=', 'load_lyft_gts(lyft,', 'data_root,', 'eval_set,', 'logger)', 'predictions', '=', 'load_lyft_predictions(res_path)', 'class_names', '=', 'get_class_names(gts)', "print('Calculating", "mAP@0.5:0.95...')", 'iou_t... | 611,879 |
KennthShang/HostG | data.py | preprocess_adj | preprocess_adj | Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation. | [
"Preprocessing",
"of",
"adjacency",
"matrix",
"for",
"simple",
"GCN",
"model",
"and",
"conversion",
"to",
"tuple",
"representation."
] | def preprocess_adj(adj):
adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))
return sparse_to_tuple(adj_normalized) | ['def', 'preprocess_adj(adj):', 'adj_normalized', '=', 'normalize_adj(adj', '+', 'sp.eye(adj.shape[0]))', 'return', 'sparse_to_tuple(adj_normalized)'] | 206,745 |
voxel51/fiftyone | utils.py | UniqueFilenameMaker.get_output_path | get_output_path | Returns a unique output path. | [
"Returns",
"a",
"unique",
"output",
"path."
] | def get_output_path(self, input_path=None, output_ext=None):
found_input = bool(input_path)
if found_input:
input_path = fos.normalize_path(input_path)
if self.idempotent and input_path in self._filepath_map:
return self._filepath_map[input_path]
self._idx += 1
if not found_i... | ['def', 'get_output_path(self,', 'input_path=None,', 'output_ext=None):', 'found_input', '=', 'bool(input_path)', 'if', 'found_input:', 'input_path', '=', 'fos.normalize_path(input_path)', 'if', 'self.idempotent', 'and', 'input_path', 'in', 'self._filepath_map:', 'return', 'self._filepath_map[input_path]', 'self._idx',... | 583,467 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.