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 |
|---|---|---|---|---|---|---|---|---|
yaoyao-liu/meta-transfer-learning | eval.py | evaluate | evaluate | Evaluate a model on a dataset. | [
"Evaluate",
"a",
"model",
"on",
"a",
"dataset."
] | def evaluate(sess, model, dataset, num_classes=5, num_shots=5, eval_inner_batch_size=5, eval_inner_iters=50, replacement=False, num_samples=10000, transductive=False, weight_decay_rate=1, reptile_fn=Reptile):
reptile = reptile_fn(sess, transductive=transductive, pre_step_op=weight_decay(weight_decay_rate))
tota... | ['def', 'evaluate(sess,', 'model,', 'dataset,', 'num_classes=5,', 'num_shots=5,', 'eval_inner_batch_size=5,', 'eval_inner_iters=50,', 'replacement=False,', 'num_samples=10000,', 'transductive=False,', 'weight_decay_rate=1,', 'reptile_fn=Reptile):', 'reptile', '=', 'reptile_fn(sess,', 'transductive=transductive,', 'pre_... | 633,377 |
AbdelrahmanRadwan/object-detection | eval_util.py | write_metrics | write_metrics | Write metrics to a summary directory. | [
"Write",
"metrics",
"to",
"a",
"summary",
"directory."
] | def write_metrics(metrics, global_step, summary_dir):
logging.info('Writing metrics to tf summary.')
summary_writer = tf.summary.FileWriter(summary_dir)
for key in sorted(metrics):
summary = tf.Summary(value=[tf.Summary.Value(tag=key, simple_value=metrics[key])])
summary_writer.add_summary(s... | ['def', 'write_metrics(metrics,', 'global_step,', 'summary_dir):', "logging.info('Writing", 'metrics', 'to', 'tf', "summary.')", 'summary_writer', '=', 'tf.summary.FileWriter(summary_dir)', 'for', 'key', 'in', 'sorted(metrics):', 'summary', '=', 'tf.Summary(value=[tf.Summary.Value(tag=key,', 'simple_value=metrics[key])... | 727,162 |
SuneethaG/NaturalLanguageProcessing | run_pretraining.py | get_masked_lm_output | get_masked_lm_output | Get loss and log probs for the masked LM. | [
"Get",
"loss",
"and",
"log",
"probs",
"for",
"the",
"masked",
"LM."
] | def get_masked_lm_output(bert_config, input_tensor, output_weights, positions, label_ids, label_weights):
input_tensor = gather_indexes(input_tensor, positions)
with tf.variable_scope('cls/predictions'):
with tf.variable_scope('transform'):
input_tensor = tf.layers.dense(input_tensor, units=... | ['def', 'get_masked_lm_output(bert_config,', 'input_tensor,', 'output_weights,', 'positions,', 'label_ids,', 'label_weights):', 'input_tensor', '=', 'gather_indexes(input_tensor,', 'positions)', 'with', "tf.variable_scope('cls/predictions'):", 'with', "tf.variable_scope('transform'):", 'input_tensor', '=', 'tf.layers.d... | 798,646 |
tudelft3d/SUMS-Semantic-Urban-Mesh--public | helper_tf_util.py | batch_norm_for_fc | batch_norm_for_fc | Batch normalization on FC data. | [
"Batch",
"normalization",
"on",
"FC",
"data."
] | def batch_norm_for_fc(inputs, is_training, bn_decay, scope):
return batch_norm_template(inputs, is_training, scope, [0], bn_decay) | ['def', 'batch_norm_for_fc(inputs,', 'is_training,', 'bn_decay,', 'scope):', 'return', 'batch_norm_template(inputs,', 'is_training,', 'scope,', '[0],', 'bn_decay)'] | 911,629 |
KalleHallden/InstaAutomator | compat.py | get_terminal_size | get_terminal_size | Returns a tuple (x, y) representing the width(x) and the height(y) in characters of the terminal window. | [
"Returns",
"a",
"tuple",
"(x,",
"y)",
"representing",
"the",
"width(x)",
"and",
"the",
"height(y)",
"in",
"characters",
"of",
"the",
"terminal",
"window."
] | def get_terminal_size():
return tuple(shutil.get_terminal_size()) | ['def', 'get_terminal_size():', 'return', 'tuple(shutil.get_terminal_size())'] | 231,342 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | font_manager.py | get_fontext_synonyms | get_fontext_synonyms | Return a list of file extensions extensions that are synonyms for the given file extension *fileext*. | [
"Return",
"a",
"list",
"of",
"file",
"extensions",
"extensions",
"that",
"are",
"synonyms",
"for",
"the",
"given",
"file",
"extension",
"*fileext*."
] | def get_fontext_synonyms(fontext):
return {'afm': ['afm'], 'otf': ['otf', 'ttc', 'ttf'], 'ttc': ['otf', 'ttc', 'ttf'], 'ttf': ['otf', 'ttc', 'ttf']}[fontext] | ['def', 'get_fontext_synonyms(fontext):', 'return', "{'afm':", "['afm'],", "'otf':", "['otf',", "'ttc',", "'ttf'],", "'ttc':", "['otf',", "'ttc',", "'ttf'],", "'ttf':", "['otf',", "'ttc',", "'ttf']}[fontext]"] | 450,447 |
xyc2690/Raspberry_ObjectDetection_Camera | dataset_util.py | read_dataset | read_dataset | Reads a dataset, and handles repetition and shuffling. | [
"Reads",
"a",
"dataset,",
"and",
"handles",
"repetition",
"and",
"shuffling."
] | def read_dataset(file_read_func, decode_func, input_files, config):
filenames = tf.concat([tf.matching_files(pattern) for pattern in input_files], 0)
filename_dataset = tf.data.Dataset.from_tensor_slices(filenames)
if config.shuffle:
filename_dataset = filename_dataset.shuffle(config.filenames_shuff... | ['def', 'read_dataset(file_read_func,', 'decode_func,', 'input_files,', 'config):', 'filenames', '=', 'tf.concat([tf.matching_files(pattern)', 'for', 'pattern', 'in', 'input_files],', '0)', 'filename_dataset', '=', 'tf.data.Dataset.from_tensor_slices(filenames)', 'if', 'config.shuffle:', 'filename_dataset', '=', 'filen... | 838,719 |
RLE-Foundation/rllte | diagonal_gaussian.py | DiagonalGaussian.rsample | rsample | Generates a sample_shape shaped reparameterized sample or sample_shape shaped batch of reparameterized samples if the distribution parameters are batched. | [
"Generates",
"a",
"sample_shape",
"shaped",
"reparameterized",
"sample",
"or",
"sample_shape",
"shaped",
"batch",
"of",
"reparameterized",
"samples",
"if",
"the",
"distribution",
"parameters",
"are",
"batched."
] | def rsample(self, sample_shape: th.Size=th.Size()) -> th.Tensor:
return self.dist.rsample(sample_shape) | ['def', 'rsample(self,', 'sample_shape:', 'th.Size=th.Size())', '->', 'th.Tensor:', 'return', 'self.dist.rsample(sample_shape)'] | 333,648 |
BlueMirrors/cvu | bbox.py | scale_coords | scale_coords | Rescale coords (xyxy) from processed_shape to original_shape Scale Coordinates according to image shape before pre-processing. | [
"Rescale",
"coords",
"(xyxy)",
"from",
"processed_shape",
"to",
"original_shape",
"Scale",
"Coordinates",
"according",
"to",
"image",
"shape",
"before",
"pre-processing."
] | def scale_coords(processed_shape: Tuple[int], coords: List[int], original_shape: Tuple[int], ratio_pad: Tuple[int]=None) -> List[int]:
if ratio_pad is None:
gain = min(processed_shape[0] / original_shape[0], processed_shape[1] / original_shape[1])
pad = ((processed_shape[1] - original_shape[1] * gai... | ['def', 'scale_coords(processed_shape:', 'Tuple[int],', 'coords:', 'List[int],', 'original_shape:', 'Tuple[int],', 'ratio_pad:', 'Tuple[int]=None)', '->', 'List[int]:', 'if', 'ratio_pad', 'is', 'None:', 'gain', '=', 'min(processed_shape[0]', '/', 'original_shape[0],', 'processed_shape[1]', '/', 'original_shape[1])', 'p... | 524,125 |
matsu0228/nlp-jp | reader.py | parse_json | parse_json | Parse a JSON string into a dict. | [
"Parse",
"a",
"JSON",
"string",
"into",
"a",
"dict."
] | def parse_json(s, **kwargs):
try:
nb_dict = json.loads(s, **kwargs)
except ValueError:
raise NotJSONError(('Notebook does not appear to be JSON: %r' % s)[:77] + '...')
return nb_dict | ['def', 'parse_json(s,', '**kwargs):', 'try:', 'nb_dict', '=', 'json.loads(s,', '**kwargs)', 'except', 'ValueError:', 'raise', "NotJSONError(('Notebook", 'does', 'not', 'appear', 'to', 'be', 'JSON:', "%r'", '%', 's)[:77]', '+', "'...')", 'return', 'nb_dict'] | 790,356 |
liuhuiwisdom/object_detection | box_list_ops.py | pad_or_clip_box_list | pad_or_clip_box_list | Pads or clips all fields of a BoxList. | [
"Pads",
"or",
"clips",
"all",
"fields",
"of",
"a",
"BoxList."
] | def pad_or_clip_box_list(boxlist, num_boxes, scope=None):
with tf.name_scope(scope, 'PadOrClipBoxList'):
subboxlist = box_list.BoxList(shape_utils.pad_or_clip_tensor(boxlist.get(), num_boxes))
for field in boxlist.get_extra_fields():
subfield = shape_utils.pad_or_clip_tensor(boxlist.get_... | ['def', 'pad_or_clip_box_list(boxlist,', 'num_boxes,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'PadOrClipBoxList'):", 'subboxlist', '=', 'box_list.BoxList(shape_utils.pad_or_clip_tensor(boxlist.get(),', 'num_boxes))', 'for', 'field', 'in', 'boxlist.get_extra_fields():', 'subfield', '=', 'shape_utils.pad_or_cli... | 771,161 |
jimtin/Stock_Comparison | widget_box.py | HBox | HBox | Displays multiple widgets horizontally using the flexible box model. | [
"Displays",
"multiple",
"widgets",
"horizontally",
"using",
"the",
"flexible",
"box",
"model."
] | def HBox(*pargs, **kwargs):
kwargs['orientation'] = 'horizontal'
return FlexBox(*pargs, **kwargs) | ['def', 'HBox(*pargs,', '**kwargs):', "kwargs['orientation']", '=', "'horizontal'", 'return', 'FlexBox(*pargs,', '**kwargs)'] | 385,677 |
google-research/rigl | fixed_param_test.py | FixedParamTest.test_run | test_run | Tests if the driver for shuffled training runs correctly. | [
"Tests",
"if",
"the",
"driver",
"for",
"shuffled",
"training",
"runs",
"correctly."
] | def test_run(self):
experiment_dir = tempfile.mkdtemp()
eval_flags = dict(epochs=1, experiment_dir=experiment_dir)
with flagsaver.flagsaver(**eval_flags):
fixed_param.main([])
with self.subTest(name='tf_summary_file_exists'):
outfile = path.join(experiment_dir, '*', 'events.out.tfevents.... | ['def', 'test_run(self):', 'experiment_dir', '=', 'tempfile.mkdtemp()', 'eval_flags', '=', 'dict(epochs=1,', 'experiment_dir=experiment_dir)', 'with', 'flagsaver.flagsaver(**eval_flags):', 'fixed_param.main([])', 'with', "self.subTest(name='tf_summary_file_exists'):", 'outfile', '=', 'path.join(experiment_dir,', "'*',"... | 841,390 |
jxhe/unify-parameter-efficient-tuning | conversational.py | Conversation.append_response | append_response | Append a response to the list of generated responses. | [
"Append",
"a",
"response",
"to",
"the",
"list",
"of",
"generated",
"responses."
] | def append_response(self, response: str):
self.generated_responses.append(response) | ['def', 'append_response(self,', 'response:', 'str):', 'self.generated_responses.append(response)'] | 949,426 |
nathancahill/mimicdb | connection.py | S3Connection.create_bucket | create_bucket | Add the bucket to MimicDB after successful creation. | [
"Add",
"the",
"bucket",
"to",
"MimicDB",
"after",
"successful",
"creation."
] | def create_bucket(self, *args, **kwargs):
bucket = super(S3Connection, self).create_bucket(*args, **kwargs)
if bucket:
mimicdb.backend.sadd(tpl.connection, bucket.name)
return bucket | ['def', 'create_bucket(self,', '*args,', '**kwargs):', 'bucket', '=', 'super(S3Connection,', 'self).create_bucket(*args,', '**kwargs)', 'if', 'bucket:', 'mimicdb.backend.sadd(tpl.connection,', 'bucket.name)', 'return', 'bucket'] | 286,396 |
Ruturaj123/Flowchart-Detection | cli_shared.py | get_run_start_intro | get_run_start_intro | Generate formatted intro for run-start UI. | [
"Generate",
"formatted",
"intro",
"for",
"run-start",
"UI."
] | def get_run_start_intro(run_call_count, fetches, feed_dict, tensor_filters, is_callable_runner=False):
fetch_lines = _get_fetch_names(fetches)
if not feed_dict:
feed_dict_lines = [debugger_cli_common.RichLine(' (Empty)')]
else:
feed_dict_lines = []
for feed_key in feed_dict:
... | ['def', 'get_run_start_intro(run_call_count,', 'fetches,', 'feed_dict,', 'tensor_filters,', 'is_callable_runner=False):', 'fetch_lines', '=', '_get_fetch_names(fetches)', 'if', 'not', 'feed_dict:', 'feed_dict_lines', '=', "[debugger_cli_common.RichLine('", "(Empty)')]", 'else:', 'feed_dict_lines', '=', '[]', 'for', 'fe... | 605,016 |
OmidPoursaeed/Self_supervised_Learning_Point_Clouds | evaluation_metrics.py | coverage | coverage | Computes the Coverage between two sets of point-clouds. | [
"Computes",
"the",
"Coverage",
"between",
"two",
"sets",
"of",
"point-clouds."
] | def coverage(sample_pcs, ref_pcs, batch_size, normalize=True, sess=None, verbose=False, use_sqrt=False, use_EMD=False, ret_dist=False):
(n_ref, n_pc_points, pc_dim) = ref_pcs.shape
(n_sam, n_pc_points_s, pc_dim_s) = sample_pcs.shape
if n_pc_points != n_pc_points_s or pc_dim != pc_dim_s:
raise ValueE... | ['def', 'coverage(sample_pcs,', 'ref_pcs,', 'batch_size,', 'normalize=True,', 'sess=None,', 'verbose=False,', 'use_sqrt=False,', 'use_EMD=False,', 'ret_dist=False):', '(n_ref,', 'n_pc_points,', 'pc_dim)', '=', 'ref_pcs.shape', '(n_sam,', 'n_pc_points_s,', 'pc_dim_s)', '=', 'sample_pcs.shape', 'if', 'n_pc_points', '!=',... | 342,593 |
matsu0228/nlp-jp | backend_bases.py | GraphicsContextBase.get_hatch_path | get_hatch_path | Returns a Path for the current hatch. | [
"Returns",
"a",
"Path",
"for",
"the",
"current",
"hatch."
] | def get_hatch_path(self, density=6.0):
hatch = self.get_hatch()
if hatch is None:
return None
return Path.hatch(hatch, density) | ['def', 'get_hatch_path(self,', 'density=6.0):', 'hatch', '=', 'self.get_hatch()', 'if', 'hatch', 'is', 'None:', 'return', 'None', 'return', 'Path.hatch(hatch,', 'density)'] | 788,412 |
VITA-Group/BackRazor_Neurips22 | configs.py | get_b32_config | get_b32_config | Returns the ViT-B/32 configuration. | [
"Returns",
"the",
"ViT-B/32",
"configuration."
] | def get_b32_config():
config = get_b16_config()
config.patches.size = (32, 32)
return config | ['def', 'get_b32_config():', 'config', '=', 'get_b16_config()', 'config.patches.size', '=', '(32,', '32)', 'return', 'config'] | 421,301 |
llSourcell/AI_Artist | pyparsing.py | ParserElement.setDebugActions | setDebugActions | Enable display of debugging messages while doing pattern matching. | [
"Enable",
"display",
"of",
"debugging",
"messages",
"while",
"doing",
"pattern",
"matching."
] | def setDebugActions(self, startAction, successAction, exceptionAction):
self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, exceptionAction or _defaultExceptionDebugAction)
self.debug = True
return self | ['def', 'setDebugActions(self,', 'startAction,', 'successAction,', 'exceptionAction):', 'self.debugActions', '=', '(startAction', 'or', '_defaultStartDebugAction,', 'successAction', 'or', '_defaultSuccessDebugAction,', 'exceptionAction', 'or', '_defaultExceptionDebugAction)', 'self.debug', '=', 'True', 'return', 'self'... | 414,287 |
liuhuiwisdom/object_detection | label_map_util.py | get_max_label_map_index | get_max_label_map_index | Get maximum index in label map. | [
"Get",
"maximum",
"index",
"in",
"label",
"map."
] | def get_max_label_map_index(label_map):
return max([item.id for item in label_map.item]) | ['def', 'get_max_label_map_index(label_map):', 'return', 'max([item.id', 'for', 'item', 'in', 'label_map.item])'] | 793,022 |
43Carrig/recurrent_neural_networks_practice | _flagvalues.py | FlagValues.get_help | get_help | Returns a help string for all known flags. | [
"Returns",
"a",
"help",
"string",
"for",
"all",
"known",
"flags."
] | def get_help(self, prefix='', include_special_flags=True):
flags_by_module = self.flags_by_module_dict()
if flags_by_module:
modules = sorted(flags_by_module)
main_module = sys.argv[0]
if main_module in modules:
modules.remove(main_module)
modules = [main_module] ... | ['def', 'get_help(self,', "prefix='',", 'include_special_flags=True):', 'flags_by_module', '=', 'self.flags_by_module_dict()', 'if', 'flags_by_module:', 'modules', '=', 'sorted(flags_by_module)', 'main_module', '=', 'sys.argv[0]', 'if', 'main_module', 'in', 'modules:', 'modules.remove(main_module)', 'modules', '=', '[m... | 309,639 |
yjn870/ESPCN-pytorch | imgproc.py | image_resize | image_resize | Implementation of `imresize` function in Matlab under Python language. | [
"Implementation",
"of",
"`imresize`",
"function",
"in",
"Matlab",
"under",
"Python",
"language."
] | def image_resize(image: Any, scale_factor: float, antialiasing: bool=True) -> Any:
squeeze_flag = False
if type(image).__module__ == np.__name__:
numpy_type = True
if image.ndim == 2:
image = image[:, :, None]
squeeze_flag = True
image = torch.from_numpy(image.tra... | ['def', 'image_resize(image:', 'Any,', 'scale_factor:', 'float,', 'antialiasing:', 'bool=True)', '->', 'Any:', 'squeeze_flag', '=', 'False', 'if', 'type(image).__module__', '==', 'np.__name__:', 'numpy_type', '=', 'True', 'if', 'image.ndim', '==', '2:', 'image', '=', 'image[:,', ':,', 'None]', 'squeeze_flag', '=', 'Tru... | 178,269 |
aws/sagemaker-python-sdk | coach_launcher.py | SageMakerCoachPresetLauncher.path_of_main_launcher | path_of_main_launcher | A bit of python magic to find the path of the file that launched the current process. | [
"A",
"bit",
"of",
"python",
"magic",
"to",
"find",
"the",
"path",
"of",
"the",
"file",
"that",
"launched",
"the",
"current",
"process."
] | def path_of_main_launcher(self):
main_mod = sys.modules['__main__']
try:
launcher_file = os.path.abspath(sys.modules['__main__'].__file__)
return os.path.dirname(launcher_file)
except AttributeError:
return os.getcwd() | ['def', 'path_of_main_launcher(self):', 'main_mod', '=', "sys.modules['__main__']", 'try:', 'launcher_file', '=', "os.path.abspath(sys.modules['__main__'].__file__)", 'return', 'os.path.dirname(launcher_file)', 'except', 'AttributeError:', 'return', 'os.getcwd()'] | 830,745 |
ashok-133/Computer-Vision | keras_yolo.py | space_to_depth_x2 | space_to_depth_x2 | Thin wrapper for Tensorflow space_to_depth with block_size=2. | [
"Thin",
"wrapper",
"for",
"Tensorflow",
"space_to_depth",
"with",
"block_size=2."
] | def space_to_depth_x2(x):
import tensorflow as tf
return tf.space_to_depth(x, block_size=2) | ['def', 'space_to_depth_x2(x):', 'import', 'tensorflow', 'as', 'tf', 'return', 'tf.space_to_depth(x,', 'block_size=2)'] | 469,772 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | config_util_test.py | ConfigUtilTest.testAdamOptimizerWithNewLearningRate | testAdamOptimizerWithNewLearningRate | Tests new learning rates for Adam Optimizer. | [
"Tests",
"new",
"learning",
"rates",
"for",
"Adam",
"Optimizer."
] | def testAdamOptimizerWithNewLearningRate(self):
self._assertOptimizerWithNewLearningRate('adam_optimizer') | ['def', 'testAdamOptimizerWithNewLearningRate(self):', "self._assertOptimizerWithNewLearningRate('adam_optimizer')"] | 51,810 |
IDEA-Research/detrex | dab_detr.py | DABDETR.init_weights | init_weights | Initialize weights for DAB-DETR. | [
"Initialize",
"weights",
"for",
"DAB-DETR."
] | def init_weights(self):
if self.freeze_anchor_box_centers:
self.anchor_box_embed.weight.data[:, :2].uniform_(0, 1)
self.anchor_box_embed.weight.data[:, :2] = inverse_sigmoid(self.anchor_box_embed.weight.data[:, :2])
self.anchor_box_embed.weight.data[:, :2].requires_grad = False
prior_pro... | ['def', 'init_weights(self):', 'if', 'self.freeze_anchor_box_centers:', 'self.anchor_box_embed.weight.data[:,', ':2].uniform_(0,', '1)', 'self.anchor_box_embed.weight.data[:,', ':2]', '=', 'inverse_sigmoid(self.anchor_box_embed.weight.data[:,', ':2])', 'self.anchor_box_embed.weight.data[:,', ':2].requires_grad', '=', '... | 549,877 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | distributions.py | Poisson.logp | logp | Compute the log probability for the counts in the bin, under the model. | [
"Compute",
"the",
"log",
"probability",
"for",
"the",
"counts",
"in",
"the",
"bin,",
"under",
"the",
"model."
] | def logp(self, bin_counts):
k = tf.to_float(bin_counts)
return k * self.logr - tf.exp(self.logr) - tf.lgamma(k + 1) | ['def', 'logp(self,', 'bin_counts):', 'k', '=', 'tf.to_float(bin_counts)', 'return', 'k', '*', 'self.logr', '-', 'tf.exp(self.logr)', '-', 'tf.lgamma(k', '+', '1)'] | 49,668 |
Ruturaj123/Flowchart-Detection | datum_io.py | DatumToArray | DatumToArray | Converts data saved in DatumProto to numpy array. | [
"Converts",
"data",
"saved",
"in",
"DatumProto",
"to",
"numpy",
"array."
] | def DatumToArray(datum):
return np.array(datum.float_list.value).astype(float).reshape(datum.shape.dim) | ['def', 'DatumToArray(datum):', 'return', 'np.array(datum.float_list.value).astype(float).reshape(datum.shape.dim)'] | 585,520 |
SamuelScheit/carcassonne-ai | gomoku.py | Game.render | render | Display the game observation. | [
"Display",
"the",
"game",
"observation."
] | def render(self):
self.env.render()
input('Press enter to take a step ') | ['def', 'render(self):', 'self.env.render()', "input('Press", 'enter', 'to', 'take', 'a', 'step', "')"] | 102,925 |
am-shashank/artificial-intelligence | __init__.py | FCompiler.get_libraries | get_libraries | List of compiler libraries. | [
"List",
"of",
"compiler",
"libraries."
] | def get_libraries(self):
return self.libraries[:] | ['def', 'get_libraries(self):', 'return', 'self.libraries[:]'] | 168,778 |
mkusner/grammarVAE | unify.py | Unification.merge | merge | Links all the specified vars to a Variable that represents their unification. | [
"Links",
"all",
"the",
"specified",
"vars",
"to",
"a",
"Variable",
"that",
"represents",
"their",
"unification."
] | def merge(self, new_best, *vars):
if self.inplace:
U = self
else:
U = Unification(self.inplace)
for (var, (best, pool)) in iteritems(self.unif):
U.unif[var] = (best, pool)
new_pool = set(vars)
new_pool.add(new_best)
for var in copy(new_pool):
(best, pool) ... | ['def', 'merge(self,', 'new_best,', '*vars):', 'if', 'self.inplace:', 'U', '=', 'self', 'else:', 'U', '=', 'Unification(self.inplace)', 'for', '(var,', '(best,', 'pool))', 'in', 'iteritems(self.unif):', 'U.unif[var]', '=', '(best,', 'pool)', 'new_pool', '=', 'set(vars)', 'new_pool.add(new_best)', 'for', 'var', 'in', 'c... | 579,364 |
pramodiperera/virtual-keyboard | dirtools.py | tempdir | tempdir | Create a temporary directory in a context manager. | [
"Create",
"a",
"temporary",
"directory",
"in",
"a",
"context",
"manager."
] | def tempdir():
td = tempfile.mkdtemp()
try:
yield td
finally:
shutil.rmtree(td) | ['def', 'tempdir():', 'td', '=', 'tempfile.mkdtemp()', 'try:', 'yield', 'td', 'finally:', 'shutil.rmtree(td)'] | 932,504 |
rlgraph/rlgraph | test_dqfd_agent_functionality.py | TestDQFDAgentFunctionality.test_update_online | test_update_online | Tests if joint updates from demo and online memory work. | [
"Tests",
"if",
"joint",
"updates",
"from",
"demo",
"and",
"online",
"memory",
"work."
] | def test_update_online(self):
env = OpenAIGymEnv.from_spec(self.env_spec)
agent_config = config_from_path('configs/dqfd_agent_for_cartpole.json')
agent = DQFDAgent.from_spec(agent_config, state_space=env.state_space, action_space=env.action_space)
terminals = BoolBox(add_batch_rank=True)
agent.obser... | ['def', 'test_update_online(self):', 'env', '=', 'OpenAIGymEnv.from_spec(self.env_spec)', 'agent_config', '=', "config_from_path('configs/dqfd_agent_for_cartpole.json')", 'agent', '=', 'DQFDAgent.from_spec(agent_config,', 'state_space=env.state_space,', 'action_space=env.action_space)', 'terminals', '=', 'BoolBox(add_b... | 862,679 |
scotthuang1989/object_detection_with_tensorflow | box_list_ops.py | area | area | Computes area of boxes. | [
"Computes",
"area",
"of",
"boxes."
] | def area(boxlist, scope=None):
with tf.name_scope(scope, 'Area'):
(y_min, x_min, y_max, x_max) = tf.split(value=boxlist.get(), num_or_size_splits=4, axis=1)
return tf.squeeze((y_max - y_min) * (x_max - x_min), [1]) | ['def', 'area(boxlist,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'Area'):", '(y_min,', 'x_min,', 'y_max,', 'x_max)', '=', 'tf.split(value=boxlist.get(),', 'num_or_size_splits=4,', 'axis=1)', 'return', 'tf.squeeze((y_max', '-', 'y_min)', '*', '(x_max', '-', 'x_min),', '[1])'] | 739,165 |
flow-project/flow | test_rewards.py | TestRewards.test_min_delay | test_min_delay | Test the min_delay method. | [
"Test",
"the",
"min_delay",
"method."
] | def test_min_delay(self):
vehicles = VehicleParams()
(env, _, _) = ring_road_exp_setup(vehicles=vehicles)
self.assertEqual(min_delay(env), 0)
vehicles = VehicleParams()
vehicles.add('test', num_vehicles=10)
(env, _, _) = ring_road_exp_setup(vehicles=vehicles)
self.assertAlmostEqual(min_delay... | ['def', 'test_min_delay(self):', 'vehicles', '=', 'VehicleParams()', '(env,', '_,', '_)', '=', 'ring_road_exp_setup(vehicles=vehicles)', 'self.assertEqual(min_delay(env),', '0)', 'vehicles', '=', 'VehicleParams()', "vehicles.add('test',", 'num_vehicles=10)', '(env,', '_,', '_)', '=', 'ring_road_exp_setup(vehicles=vehic... | 211,967 |
marcsto/rl | utils.py | make_loss_module | make_loss_module | Make loss module and target network updater. | [
"Make",
"loss",
"module",
"and",
"target",
"network",
"updater."
] | def make_loss_module(cfg, model):
loss_module = TD3Loss(actor_network=model[0], qvalue_network=model[1], num_qvalue_nets=2, loss_function=cfg.optim.loss_function, delay_actor=True, delay_qvalue=True, gamma=cfg.optim.gamma, action_spec=model[0][1].spec, policy_noise=cfg.optim.policy_noise, noise_clip=cfg.optim.noise... | ['def', 'make_loss_module(cfg,', 'model):', 'loss_module', '=', 'TD3Loss(actor_network=model[0],', 'qvalue_network=model[1],', 'num_qvalue_nets=2,', 'loss_function=cfg.optim.loss_function,', 'delay_actor=True,', 'delay_qvalue=True,', 'gamma=cfg.optim.gamma,', 'action_spec=model[0][1].spec,', 'policy_noise=cfg.optim.pol... | 858,261 |
N-Chandru/NaturalLanguageProcessing | modeling.py | BertConfig.from_dict | from_dict | Constructs a `BertConfig` from a Python dictionary of parameters. | [
"Constructs",
"a",
"`BertConfig`",
"from",
"a",
"Python",
"dictionary",
"of",
"parameters."
] | def from_dict(cls, json_object):
config = BertConfig(vocab_size=None)
for (key, value) in six.iteritems(json_object):
config.__dict__[key] = value
return config | ['def', 'from_dict(cls,', 'json_object):', 'config', '=', 'BertConfig(vocab_size=None)', 'for', '(key,', 'value)', 'in', 'six.iteritems(json_object):', 'config.__dict__[key]', '=', 'value', 'return', 'config'] | 713,000 |
boostcampaitech3/level2-semantic-segmentation-level2-cv-16 | dnl_head.py | DisentangledNonLocal2d.embedded_gaussian | embedded_gaussian | Embedded gaussian with temperature. | [
"Embedded",
"gaussian",
"with",
"temperature."
] | def embedded_gaussian(self, theta_x, phi_x):
pairwise_weight = torch.matmul(theta_x, phi_x)
if self.use_scale:
pairwise_weight /= torch.tensor(theta_x.shape[-1], dtype=torch.float, device=pairwise_weight.device) ** torch.tensor(0.5, device=pairwise_weight.device)
pairwise_weight /= torch.tensor(self... | ['def', 'embedded_gaussian(self,', 'theta_x,', 'phi_x):', 'pairwise_weight', '=', 'torch.matmul(theta_x,', 'phi_x)', 'if', 'self.use_scale:', 'pairwise_weight', '/=', 'torch.tensor(theta_x.shape[-1],', 'dtype=torch.float,', 'device=pairwise_weight.device)', '**', 'torch.tensor(0.5,', 'device=pairwise_weight.device)', '... | 588,815 |
alecokas/BiLatticeRNN-Confidence | model.py | Model.forward | forward | Forward pass through the model. | [
"Forward",
"pass",
"through",
"the",
"model."
] | def forward(self, lattice):
if self.is_graphemic:
if self.has_grapheme_encoding:
(grapheme_encoding, _) = self.grapheme_encoder.forward(lattice.grapheme_data)
(reduced_grapheme_info, _) = self.grapheme_attention.forward(key=self.create_key(lattice, grapheme_encoding), query=grapheme_... | ['def', 'forward(self,', 'lattice):', 'if', 'self.is_graphemic:', 'if', 'self.has_grapheme_encoding:', '(grapheme_encoding,', '_)', '=', 'self.grapheme_encoder.forward(lattice.grapheme_data)', '(reduced_grapheme_info,', '_)', '=', 'self.grapheme_attention.forward(key=self.create_key(lattice,', 'grapheme_encoding),', 'q... | 107,698 |
wutong8023/CoLL | quant_modules.py | symmetric_linear_quantization_params | symmetric_linear_quantization_params | Compute the scaling factor with the given quantization range for symmetric quantization. | [
"Compute",
"the",
"scaling",
"factor",
"with",
"the",
"given",
"quantization",
"range",
"for",
"symmetric",
"quantization."
] | def symmetric_linear_quantization_params(num_bits, saturation_min, saturation_max, per_channel=False):
with torch.no_grad():
n = 2 ** (num_bits - 1) - 1
if per_channel:
(scale, _) = torch.max(torch.stack([saturation_min.abs(), saturation_max.abs()], dim=1), dim=1)
scale = tor... | ['def', 'symmetric_linear_quantization_params(num_bits,', 'saturation_min,', 'saturation_max,', 'per_channel=False):', 'with', 'torch.no_grad():', 'n', '=', '2', '**', '(num_bits', '-', '1)', '-', '1', 'if', 'per_channel:', '(scale,', '_)', '=', 'torch.max(torch.stack([saturation_min.abs(),', 'saturation_max.abs()],', ... | 466,435 |
zcablii/LSKNet | kfiou_odm_refine_head.py | KFIoUODMRefineHead.get_bboxes | get_bboxes | Transform network output for a batch into labeled boxes. | [
"Transform",
"network",
"output",
"for",
"a",
"batch",
"into",
"labeled",
"boxes."
] | def get_bboxes(self, cls_scores, bbox_preds, img_metas, cfg=None, rescale=False, rois=None):
num_levels = len(cls_scores)
assert len(cls_scores) == len(bbox_preds)
assert rois is not None
result_list = []
for (img_id, _) in enumerate(img_metas):
cls_score_list = [cls_scores[i][img_id].detach... | ['def', 'get_bboxes(self,', 'cls_scores,', 'bbox_preds,', 'img_metas,', 'cfg=None,', 'rescale=False,', 'rois=None):', 'num_levels', '=', 'len(cls_scores)', 'assert', 'len(cls_scores)', '==', 'len(bbox_preds)', 'assert', 'rois', 'is', 'not', 'None', 'result_list', '=', '[]', 'for', '(img_id,', '_)', 'in', 'enumerate(img... | 616,114 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | data_utils.py | build_labeled_sequence | build_labeled_sequence | Builds labeled sequence from input sequence. | [
"Builds",
"labeled",
"sequence",
"from",
"input",
"sequence."
] | def build_labeled_sequence(seq, class_label, label_gain=False):
label_seq = SequenceWrapper(multivalent_tokens=seq.multivalent_tokens)
seq_len = len(seq)
final_timestep = None
for (i, timestep) in enumerate(seq):
label_timestep = label_seq.add_timestep()
if seq.multivalent_tokens:
... | ['def', 'build_labeled_sequence(seq,', 'class_label,', 'label_gain=False):', 'label_seq', '=', 'SequenceWrapper(multivalent_tokens=seq.multivalent_tokens)', 'seq_len', '=', 'len(seq)', 'final_timestep', '=', 'None', 'for', '(i,', 'timestep)', 'in', 'enumerate(seq):', 'label_timestep', '=', 'label_seq.add_timestep()', '... | 20,474 |
weimin17/Object-Detection_HelmetDetection | icp_train_demo.py | DataProducer.next_batch | next_batch | Returns a training batch. | [
"Returns",
"a",
"training",
"batch."
] | def next_batch(cls, batch_size):
source_items = []
target_items = []
for _ in range(batch_size):
source_cloud = icp_util.np_transform_cloud_xyz(cls.sample_cloud, cls.random_transform())
source_items.append(source_cloud)
dist_to_center = np.linalg.norm((source_cloud - RES_CENTER)[:, :... | ['def', 'next_batch(cls,', 'batch_size):', 'source_items', '=', '[]', 'target_items', '=', '[]', 'for', '_', 'in', 'range(batch_size):', 'source_cloud', '=', 'icp_util.np_transform_cloud_xyz(cls.sample_cloud,', 'cls.random_transform())', 'source_items.append(source_cloud)', 'dist_to_center', '=', 'np.linalg.norm((sourc... | 754,074 |
golthitarun/Natural-Language-Processing | test_positionrank.py | test_positionrank_candidate_selection | test_positionrank_candidate_selection | Test PositionRank candidate selection method. | [
"Test",
"PositionRank",
"candidate",
"selection",
"method."
] | def test_positionrank_candidate_selection():
extractor = pke.unsupervised.PositionRank()
extractor.load_document(input=test_file)
extractor.candidate_selection(grammar=grammar)
assert len(extractor.candidates) == 19 | ['def', 'test_positionrank_candidate_selection():', 'extractor', '=', 'pke.unsupervised.PositionRank()', 'extractor.load_document(input=test_file)', 'extractor.candidate_selection(grammar=grammar)', 'assert', 'len(extractor.candidates)', '==', '19'] | 663,065 |
sek788432/Waymo-2D-Object-Detection | dataset_loader.py | Bike.load_image_sequence | load_image_sequence | Returns a list of images around target index. | [
"Returns",
"a",
"list",
"of",
"images",
"around",
"target",
"index."
] | def load_image_sequence(self, target_index):
(start_index, end_index) = get_seq_start_end(target_index, self.seq_length, self.sample_every)
image_seq = []
for idx in range(start_index, end_index + 1, self.sample_every):
frame_id = self.frames[idx]
(img, cy) = self.load_image_raw(frame_id)
... | ['def', 'load_image_sequence(self,', 'target_index):', '(start_index,', 'end_index)', '=', 'get_seq_start_end(target_index,', 'self.seq_length,', 'self.sample_every)', 'image_seq', '=', '[]', 'for', 'idx', 'in', 'range(start_index,', 'end_index', '+', '1,', 'self.sample_every):', 'frame_id', '=', 'self.frames[idx]', '(... | 975,908 |
jxhe/self-training-text-generation | noise.py | NoiseLayer.word_shuffle | word_shuffle | Randomly shuffle input words. | [
"Randomly",
"shuffle",
"input",
"words."
] | def word_shuffle(self, x, l):
if self.shuffle_weight == 0:
return (x, l)
noise = np.random.uniform(0, self.shuffle_weight, size=(x.size(0) - 1, x.size(1)))
noise[0] = -1
assert self.shuffle_weight > 1
x2 = x.clone()
for i in range(len(l)):
scores = np.arange(l[i] - 1) + noise[:l[... | ['def', 'word_shuffle(self,', 'x,', 'l):', 'if', 'self.shuffle_weight', '==', '0:', 'return', '(x,', 'l)', 'noise', '=', 'np.random.uniform(0,', 'self.shuffle_weight,', 'size=(x.size(0)', '-', '1,', 'x.size(1)))', 'noise[0]', '=', '-1', 'assert', 'self.shuffle_weight', '>', '1', 'x2', '=', 'x.clone()', 'for', 'i', 'in'... | 843,858 |
fudan-zvg/SETR | hrnet.py | HRNet.init_weights | init_weights | Initialize the weights in backbone. | [
"Initialize",
"the",
"weights",
"in",
"backbone."
] | def init_weights(self, pretrained=None):
if isinstance(pretrained, str):
logger = get_root_logger()
load_checkpoint(self, pretrained, strict=False, logger=logger)
elif pretrained is None:
for m in self.modules():
if isinstance(m, nn.Conv2d):
kaiming_init(m)
... | ['def', 'init_weights(self,', 'pretrained=None):', 'if', 'isinstance(pretrained,', 'str):', 'logger', '=', 'get_root_logger()', 'load_checkpoint(self,', 'pretrained,', 'strict=False,', 'logger=logger)', 'elif', 'pretrained', 'is', 'None:', 'for', 'm', 'in', 'self.modules():', 'if', 'isinstance(m,', 'nn.Conv2d):', 'kaim... | 898,537 |
AtlantixJJ/LinearGAN | model_settings.py | get_pth_weight_path | get_pth_weight_path | Gets weight path from `MODEL_DIR/PTH_MODEL_DIR`. | [
"Gets",
"weight",
"path",
"from",
"`MODEL_DIR/PTH_MODEL_DIR`."
] | def get_pth_weight_path(weight_name):
assert isinstance(weight_name, str)
if weight_name == '':
return ''
if weight_name[-4:] != '.pth':
weight_name += '.pth'
return os.path.join(MODEL_DIR, PTH_MODEL_DIR, weight_name) | ['def', 'get_pth_weight_path(weight_name):', 'assert', 'isinstance(weight_name,', 'str)', 'if', 'weight_name', '==', "'':", 'return', "''", 'if', 'weight_name[-4:]', '!=', "'.pth':", 'weight_name', '+=', "'.pth'", 'return', 'os.path.join(MODEL_DIR,', 'PTH_MODEL_DIR,', 'weight_name)'] | 602,612 |
voidking/object-detection | shape_utils.py | pad_tensor | pad_tensor | Pads the input tensor with 0s along the first dimension up to the length. | [
"Pads",
"the",
"input",
"tensor",
"with",
"0s",
"along",
"the",
"first",
"dimension",
"up",
"to",
"the",
"length."
] | def pad_tensor(t, length):
t_rank = tf.rank(t)
t_shape = tf.shape(t)
t_d0 = t_shape[0]
pad_d0 = tf.expand_dims(length - t_d0, 0)
pad_shape = tf.cond(tf.greater(t_rank, 1), lambda : tf.concat([pad_d0, t_shape[1:]], 0), lambda : tf.expand_dims(length - t_d0, 0))
padded_t = tf.concat([t, tf.zeros(p... | ['def', 'pad_tensor(t,', 'length):', 't_rank', '=', 'tf.rank(t)', 't_shape', '=', 'tf.shape(t)', 't_d0', '=', 't_shape[0]', 'pad_d0', '=', 'tf.expand_dims(length', '-', 't_d0,', '0)', 'pad_shape', '=', 'tf.cond(tf.greater(t_rank,', '1),', 'lambda', ':', 'tf.concat([pad_d0,', 't_shape[1:]],', '0),', 'lambda', ':', 'tf.e... | 747,444 |
arshpreetsingh/quantopian-machinelearning | conftest.py | box_transpose_fail | box_transpose_fail | Fixture similar to `box` but testing both transpose cases for DataFrame, with the tranpose=True case xfailed. | [
"Fixture",
"similar",
"to",
"`box`",
"but",
"testing",
"both",
"transpose",
"cases",
"for",
"DataFrame,",
"with",
"the",
"tranpose=True",
"case",
"xfailed."
] | def box_transpose_fail(request):
return request.param | ['def', 'box_transpose_fail(request):', 'return', 'request.param'] | 890,558 |
timmeinhardt/trackformer | mot17_sequence.py | MOT17Sequence.get_det_file_path | get_det_file_path | Return public detections file of sequence. | [
"Return",
"public",
"detections",
"file",
"of",
"sequence."
] | def get_det_file_path(self) -> str:
if self._dets is None:
return ''
return osp.join(self.get_seq_path(), 'det', 'det.txt') | ['def', 'get_det_file_path(self)', '->', 'str:', 'if', 'self._dets', 'is', 'None:', 'return', "''", 'return', 'osp.join(self.get_seq_path(),', "'det',", "'det.txt')"] | 903,617 |
tinazhouhui/computer_vision | coco_evaluation_test.py | CocoDetectionEvaluationTest.testGetOneMAPWithMatchingGroundtruthAndDetections | testGetOneMAPWithMatchingGroundtruthAndDetections | Tests that mAP is calculated correctly on GT and Detections. | [
"Tests",
"that",
"mAP",
"is",
"calculated",
"correctly",
"on",
"GT",
"and",
"Detections."
] | def testGetOneMAPWithMatchingGroundtruthAndDetections(self):
coco_evaluator = coco_evaluation.CocoDetectionEvaluator(_get_categories_list())
coco_evaluator.add_single_ground_truth_image_info(image_id='image1', groundtruth_dict={standard_fields.InputDataFields.groundtruth_boxes: np.array([[100.0, 100.0, 200.0, 2... | ['def', 'testGetOneMAPWithMatchingGroundtruthAndDetections(self):', 'coco_evaluator', '=', 'coco_evaluation.CocoDetectionEvaluator(_get_categories_list())', "coco_evaluator.add_single_ground_truth_image_info(image_id='image1',", 'groundtruth_dict={standard_fields.InputDataFields.groundtruth_boxes:', 'np.array([[100.0,'... | 511,212 |
sek788432/Waymo-2D-Object-Detection | transformer.py | Transformer.encode | encode | Generate continuous representation for inputs. | [
"Generate",
"continuous",
"representation",
"for",
"inputs."
] | def encode(self, inputs, attention_bias, training):
with tf.name_scope('encode'):
embedded_inputs = self.embedding_softmax_layer(inputs)
embedded_inputs = tf.cast(embedded_inputs, self.params['dtype'])
inputs_padding = model_utils.get_padding(inputs)
attention_bias = tf.cast(attentio... | ['def', 'encode(self,', 'inputs,', 'attention_bias,', 'training):', 'with', "tf.name_scope('encode'):", 'embedded_inputs', '=', 'self.embedding_softmax_layer(inputs)', 'embedded_inputs', '=', 'tf.cast(embedded_inputs,', "self.params['dtype'])", 'inputs_padding', '=', 'model_utils.get_padding(inputs)', 'attention_bias',... | 972,864 |
zihuitang/medical_AI_platform | ipaddress.py | ip_network | ip_network | Take an IP string/int and return an object of the correct type. | [
"Take",
"an",
"IP",
"string/int",
"and",
"return",
"an",
"object",
"of",
"the",
"correct",
"type."
] | def ip_network(address, strict=True):
try:
return IPv4Network(address, strict)
except (AddressValueError, NetmaskValueError):
pass
try:
return IPv6Network(address, strict)
except (AddressValueError, NetmaskValueError):
pass
raise ValueError('%r does not appear to be a... | ['def', 'ip_network(address,', 'strict=True):', 'try:', 'return', 'IPv4Network(address,', 'strict)', 'except', '(AddressValueError,', 'NetmaskValueError):', 'pass', 'try:', 'return', 'IPv6Network(address,', 'strict)', 'except', '(AddressValueError,', 'NetmaskValueError):', 'pass', 'raise', "ValueError('%r", 'does', 'no... | 280,610 |
rifqind/Agent-Programs-3KS1 | crashhandler.py | CrashHandler.make_report | make_report | Return a string containing a crash report. | [
"Return",
"a",
"string",
"containing",
"a",
"crash",
"report."
] | def make_report(self, traceback):
sec_sep = self.section_sep
report = ['*' * 75 + '\n\n' + 'IPython post-mortem report\n\n']
rpt_add = report.append
rpt_add(sys_info())
try:
config = pformat(self.app.config)
rpt_add(sec_sep)
rpt_add('Application name: %s\n\n' % self.app_name)... | ['def', 'make_report(self,', 'traceback):', 'sec_sep', '=', 'self.section_sep', 'report', '=', "['*'", '*', '75', '+', "'\\n\\n'", '+', "'IPython", 'post-mortem', "report\\n\\n']", 'rpt_add', '=', 'report.append', 'rpt_add(sys_info())', 'try:', 'config', '=', 'pformat(self.app.config)', 'rpt_add(sec_sep)', "rpt_add('Ap... | 40,938 |
AgnostiqHQ/covalent | workflow_stack_test.py | test_stdout_stderr_redirection | test_stdout_stderr_redirection | Test whether stdout and stderr are redirected correctly. | [
"Test",
"whether",
"stdout",
"and",
"stderr",
"are",
"redirected",
"correctly."
] | def test_stdout_stderr_redirection():
import sys
@ct.electron
def test_func(a, b):
print(a)
print(b, file=sys.stderr)
return a + b
@ct.lattice
def work_func(a, b):
return test_func(a, b)
dispatch_id = ct.dispatch(work_func)(1, 2)
workflow_result = rm.get_res... | ['def', 'test_stdout_stderr_redirection():', 'import', 'sys', '@ct.electron', 'def', 'test_func(a,', 'b):', 'print(a)', 'print(b,', 'file=sys.stderr)', 'return', 'a', '+', 'b', '@ct.lattice', 'def', 'work_func(a,', 'b):', 'return', 'test_func(a,', 'b)', 'dispatch_id', '=', 'ct.dispatch(work_func)(1,', '2)', 'workflow_r... | 490,069 |
tccbj/deeplabv3_plus_RS | resnet_v1_beta.py | resnet_v1_beta_block | resnet_v1_beta_block | Helper function for creating a resnet_v1 beta variant bottleneck block. | [
"Helper",
"function",
"for",
"creating",
"a",
"resnet_v1",
"beta",
"variant",
"bottleneck",
"block."
] | def resnet_v1_beta_block(scope, base_depth, num_units, stride):
return resnet_utils.Block(scope, bottleneck, [{'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': 1, 'unit_rate': 1}] * (num_units - 1) + [{'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': stride, 'unit_rate': 1}]) | ['def', 'resnet_v1_beta_block(scope,', 'base_depth,', 'num_units,', 'stride):', 'return', 'resnet_utils.Block(scope,', 'bottleneck,', "[{'depth':", 'base_depth', '*', '4,', "'depth_bottleneck':", 'base_depth,', "'stride':", '1,', "'unit_rate':", '1}]', '*', '(num_units', '-', '1)', '+', "[{'depth':", 'base_depth', '*',... | 521,456 |
happinesslz/TANet | similarity_calculator_builder.py | build | build | Create optimizer based on config. | [
"Create",
"optimizer",
"based",
"on",
"config."
] | def build(similarity_config):
similarity_type = similarity_config.WhichOneof('region_similarity')
if similarity_type == 'rotate_iou_similarity':
return region_similarity.RotateIouSimilarity()
elif similarity_type == 'nearest_iou_similarity':
return region_similarity.NearestIouSimilarity()
... | ['def', 'build(similarity_config):', 'similarity_type', '=', "similarity_config.WhichOneof('region_similarity')", 'if', 'similarity_type', '==', "'rotate_iou_similarity':", 'return', 'region_similarity.RotateIouSimilarity()', 'elif', 'similarity_type', '==', "'nearest_iou_similarity':", 'return', 'region_similarity.Nea... | 906,859 |
tobegit3hub/deep_image_model | dataframe.py | DataFrame.columns | columns | Set of the column names. | [
"Set",
"of",
"the",
"column",
"names."
] | def columns(self):
return frozenset(self._columns.keys()) | ['def', 'columns(self):', 'return', 'frozenset(self._columns.keys())'] | 181,589 |
lllingfa/computer_vision_with_python | ar.py | draw_background | draw_background | Draw background image using a quad. | [
"Draw",
"background",
"image",
"using",
"a",
"quad."
] | def draw_background(imname):
bg_image = pygame.image.load(imname).convert()
bg_data = pygame.image.tostring(bg_image, 'RGBX', 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, glGenTextures(1... | ['def', 'draw_background(imname):', 'bg_image', '=', 'pygame.image.load(imname).convert()', 'bg_data', '=', 'pygame.image.tostring(bg_image,', "'RGBX',", '1)', 'glMatrixMode(GL_MODELVIEW)', 'glLoadIdentity()', 'glClear(GL_COLOR_BUFFER_BIT', '|', 'GL_DEPTH_BUFFER_BIT)', 'glEnable(GL_TEXTURE_2D)', 'glBindTexture(GL_TEXTU... | 514,914 |
afandi354/ComputerVision | homography.py | RansacModel.fit | fit | Fit homography to four selected correspondences. | [
"Fit",
"homography",
"to",
"four",
"selected",
"correspondences."
] | def fit(self, data):
data = data.T
fp = data[:3, :4]
tp = data[3:, :4]
return H_from_points(fp, tp) | ['def', 'fit(self,', 'data):', 'data', '=', 'data.T', 'fp', '=', 'data[:3,', ':4]', 'tp', '=', 'data[3:,', ':4]', 'return', 'H_from_points(fp,', 'tp)'] | 471,276 |
Andy-zhujunwen/FPN-Semantic-segmentation | logger.py | Logger.image_summary | image_summary | Log a list of images. | [
"Log",
"a",
"list",
"of",
"images."
] | def image_summary(self, tag, images, step):
img_summaries = []
for (i, img) in enumerate(images):
try:
s = StringIO()
except:
s = BytesIO()
scipy.misc.toimage(img).save(s, format='png')
img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=i... | ['def', 'image_summary(self,', 'tag,', 'images,', 'step):', 'img_summaries', '=', '[]', 'for', '(i,', 'img)', 'in', 'enumerate(images):', 'try:', 's', '=', 'StringIO()', 'except:', 's', '=', 'BytesIO()', 'scipy.misc.toimage(img).save(s,', "format='png')", 'img_sum', '=', 'tf.Summary.Image(encoded_image_string=s.getvalu... | 564,248 |
Alexander-Parker/youtube_nlp | jwt.py | OnDemandCredentials.before_request | before_request | Performs credential-specific before request logic. | [
"Performs",
"credential-specific",
"before",
"request",
"logic."
] | def before_request(self, request, method, url, headers):
parts = urllib.parse.urlsplit(url)
audience = urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path, '', ''))
token = self._get_jwt_for_audience(audience)
self.apply(headers, token=token) | ['def', 'before_request(self,', 'request,', 'method,', 'url,', 'headers):', 'parts', '=', 'urllib.parse.urlsplit(url)', 'audience', '=', 'urllib.parse.urlunsplit((parts.scheme,', 'parts.netloc,', 'parts.path,', "'',", "''))", 'token', '=', 'self._get_jwt_for_audience(audience)', 'self.apply(headers,', 'token=token)'] | 970,022 |
RasaHQ/rasa | telemetry.py | track_markers_parsed_count | track_markers_parsed_count | Track when markers have been successfully parsed from config. | [
"Track",
"when",
"markers",
"have",
"been",
"successfully",
"parsed",
"from",
"config."
] | def track_markers_parsed_count(marker_count: int, max_depth: int, branching_factor: int) -> None:
_track(TELEMETRY_MARKERS_PARSED_COUNT, {'marker_count': marker_count, 'max_depth': max_depth, 'branching_factor': branching_factor}) | ['def', 'track_markers_parsed_count(marker_count:', 'int,', 'max_depth:', 'int,', 'branching_factor:', 'int)', '->', 'None:', '_track(TELEMETRY_MARKERS_PARSED_COUNT,', "{'marker_count':", 'marker_count,', "'max_depth':", 'max_depth,', "'branching_factor':", 'branching_factor})'] | 836,585 |
veronica320/Zeroshot-Event-Extraction | graph.py | Graph.to_dict | to_dict | Convert a graph to a dict object :return (dict): A dictionary representing the graph, where label indices have been replaced with label strings. | [
"Convert",
"a",
"graph",
"to",
"a",
"dict",
"object",
":return",
"(dict):",
"A",
"dictionary",
"representing",
"the",
"graph,",
"where",
"label",
"indices",
"have",
"been",
"replaced",
"with",
"label",
"strings."
] | def to_dict(self):
trigger_itos = {i: s for (s, i) in self.vocabs['event_type'].items()}
role_itos = {i: s for (s, i) in self.vocabs['role_type'].items()}
triggers = [[i, j, trigger_itos[k], l] for ((i, j, k), l) in zip(self.triggers, self.trigger_scores)]
roles = [[h, i, j, role_itos[k], l] for ((h, i,... | ['def', 'to_dict(self):', 'trigger_itos', '=', '{i:', 's', 'for', '(s,', 'i)', 'in', "self.vocabs['event_type'].items()}", 'role_itos', '=', '{i:', 's', 'for', '(s,', 'i)', 'in', "self.vocabs['role_type'].items()}", 'triggers', '=', '[[i,', 'j,', 'trigger_itos[k],', 'l]', 'for', '((i,', 'j,', 'k),', 'l)', 'in', 'zip(se... | 971,236 |
tencent-ailab/TriNet | w2l_decoder.py | W2lDecoder.generate | generate | Generate a batch of inferences. | [
"Generate",
"a",
"batch",
"of",
"inferences."
] | def generate(self, models, sample, **unused):
encoder_input = {k: v for (k, v) in sample['net_input'].items() if k != 'prev_output_tokens'}
emissions = self.get_emissions(models, encoder_input)
return self.decode(emissions) | ['def', 'generate(self,', 'models,', 'sample,', '**unused):', 'encoder_input', '=', '{k:', 'v', 'for', '(k,', 'v)', 'in', "sample['net_input'].items()", 'if', 'k', '!=', "'prev_output_tokens'}", 'emissions', '=', 'self.get_emissions(models,', 'encoder_input)', 'return', 'self.decode(emissions)'] | 424,891 |
wuyuebupt/doubleheadsrcnn | make_layers.py | get_group_gn | get_group_gn | get number of groups used by GroupNorm, based on number of channels. | [
"get",
"number",
"of",
"groups",
"used",
"by",
"GroupNorm,",
"based",
"on",
"number",
"of",
"channels."
] | def get_group_gn(dim, dim_per_gp, num_groups):
assert dim_per_gp == -1 or num_groups == -1, 'GroupNorm: can only specify G or C/G.'
if dim_per_gp > 0:
assert dim % dim_per_gp == 0, 'dim: {}, dim_per_gp: {}'.format(dim, dim_per_gp)
group_gn = dim // dim_per_gp
else:
assert dim % num_g... | ['def', 'get_group_gn(dim,', 'dim_per_gp,', 'num_groups):', 'assert', 'dim_per_gp', '==', '-1', 'or', 'num_groups', '==', '-1,', "'GroupNorm:", 'can', 'only', 'specify', 'G', 'or', "C/G.'", 'if', 'dim_per_gp', '>', '0:', 'assert', 'dim', '%', 'dim_per_gp', '==', '0,', "'dim:", '{},', 'dim_per_gp:', "{}'.format(dim,", '... | 522,822 |
zihuitang/medical_AI_platform | ttk.py | Treeview.selection_toggle | selection_toggle | Toggle the selection state of each specified item. | [
"Toggle",
"the",
"selection",
"state",
"of",
"each",
"specified",
"item."
] | def selection_toggle(self, *items):
self._selection('toggle', items) | ['def', 'selection_toggle(self,', '*items):', "self._selection('toggle',", 'items)'] | 284,005 |
OpenMDAO/OpenMDAO-Framework | cover2.py | Coverage2.options | options | Add options to command line. | [
"Add",
"options",
"to",
"command",
"line."
] | def options(self, parser, env):
Plugin.options(self, parser, env)
parser.add_option('--cover2-package', action='append', default=env.get('NOSE_COVER2_PACKAGE'), metavar='PACKAGE', dest='cover2_packages', help='Restrict coverage output to selected packages [NOSE_COVER2_PACKAGE]')
parser.add_option('--cover2-... | ['def', 'options(self,', 'parser,', 'env):', 'Plugin.options(self,', 'parser,', 'env)', "parser.add_option('--cover2-package',", "action='append',", "default=env.get('NOSE_COVER2_PACKAGE'),", "metavar='PACKAGE',", "dest='cover2_packages',", "help='Restrict", 'coverage', 'output', 'to', 'selected', 'packages', "[NOSE_CO... | 275,289 |
matsu0228/nlp-jp | ldaseqmodel.py | sslm.compute_obs_deriv | compute_obs_deriv | Derivation of obs which is used in derivative function [df_obs] while optimizing. | [
"Derivation",
"of",
"obs",
"which",
"is",
"used",
"in",
"derivative",
"function",
"[df_obs]",
"while",
"optimizing."
] | def compute_obs_deriv(self, word, word_counts, totals, mean_deriv_mtx, deriv):
init_mult = 1000
T = self.num_time_slices
mean = self.mean[word]
variance = self.variance[word]
self.temp_vect = np.zeros(T)
for u in range(0, T):
self.temp_vect[u] = np.exp(mean[u + 1] + variance[u + 1] / 2)
... | ['def', 'compute_obs_deriv(self,', 'word,', 'word_counts,', 'totals,', 'mean_deriv_mtx,', 'deriv):', 'init_mult', '=', '1000', 'T', '=', 'self.num_time_slices', 'mean', '=', 'self.mean[word]', 'variance', '=', 'self.variance[word]', 'self.temp_vect', '=', 'np.zeros(T)', 'for', 'u', 'in', 'range(0,', 'T):', 'self.temp_v... | 785,850 |
octree-nn/ocnn-pytorch | octree.py | Octree.octree_grow_full | octree_grow_full | Builds the full octree, which is essentially a dense volumetric grid. | [
"Builds",
"the",
"full",
"octree,",
"which",
"is",
"essentially",
"a",
"dense",
"volumetric",
"grid."
] | def octree_grow_full(self, depth: int, update_neigh: bool=True):
assert depth <= self.full_depth, 'error'
num = 1 << 3 * depth
self.nnum[depth] = num * self.batch_size
self.nnum_nempty[depth] = num * self.batch_size
key = torch.arange(num, dtype=torch.long, device=self.device)
bs = torch.arange(... | ['def', 'octree_grow_full(self,', 'depth:', 'int,', 'update_neigh:', 'bool=True):', 'assert', 'depth', '<=', 'self.full_depth,', "'error'", 'num', '=', '1', '<<', '3', '*', 'depth', 'self.nnum[depth]', '=', 'num', '*', 'self.batch_size', 'self.nnum_nempty[depth]', '=', 'num', '*', 'self.batch_size', 'key', '=', 'torch.... | 249,932 |
voidking/object-detection | multiple_grid_anchor_generator_test.py | MultipleGridAnchorGeneratorTest.test_construct_single_anchor_grid | test_construct_single_anchor_grid | Builds a 1x1 anchor grid to test the size of the output boxes. | [
"Builds",
"a",
"1x1",
"anchor",
"grid",
"to",
"test",
"the",
"size",
"of",
"the",
"output",
"boxes."
] | def test_construct_single_anchor_grid(self):
exp_anchor_corners = [[-121, -35, 135, 29], [-249, -67, 263, 61], [-505, -131, 519, 125], [-57, -67, 71, 61], [-121, -131, 135, 125], [-249, -259, 263, 253], [-25, -131, 39, 125], [-57, -259, 71, 253], [-121, -515, 135, 509]]
box_specs_list = [[(0.5, 0.25), (1.0, 0.2... | ['def', 'test_construct_single_anchor_grid(self):', 'exp_anchor_corners', '=', '[[-121,', '-35,', '135,', '29],', '[-249,', '-67,', '263,', '61],', '[-505,', '-131,', '519,', '125],', '[-57,', '-67,', '71,', '61],', '[-121,', '-131,', '135,', '125],', '[-249,', '-259,', '263,', '253],', '[-25,', '-131,', '39,', '125],'... | 727,294 |
danamyu/hedgehog_detector | evaluation.py | calculate_segmentation_metrics | calculate_segmentation_metrics | Calculate precision/recall/f1 based on gold and annotated sentences. | [
"Calculate",
"precision/recall/f1",
"based",
"on",
"gold",
"and",
"annotated",
"sentences."
] | def calculate_segmentation_metrics(gold_corpus, annotated_corpus):
check.Eq(len(gold_corpus), len(annotated_corpus), 'Corpora are not aligned')
num_gold_tokens = 0
num_test_tokens = 0
num_correct_tokens = 0
def token_span(token):
check.Ge(token.end, token.start)
return (token.start,... | ['def', 'calculate_segmentation_metrics(gold_corpus,', 'annotated_corpus):', 'check.Eq(len(gold_corpus),', 'len(annotated_corpus),', "'Corpora", 'are', 'not', "aligned')", 'num_gold_tokens', '=', '0', 'num_test_tokens', '=', '0', 'num_correct_tokens', '=', '0', 'def', 'token_span(token):', 'check.Ge(token.end,', 'token... | 590,573 |
ArkoSharma/Artificial-Intelligence | csp.py | CSP.actions | actions | Return a list of applicable actions: non conflicting assignments to an unassigned variable. | [
"Return",
"a",
"list",
"of",
"applicable",
"actions:",
"non",
"conflicting",
"assignments",
"to",
"an",
"unassigned",
"variable."
] | def actions(self, state):
if len(state) == len(self.variables):
return []
else:
assignment = dict(state)
var = first([v for v in self.variables if v not in assignment])
return [(var, val) for val in self.domains[var] if self.nconflicts(var, val, assignment) == 0] | ['def', 'actions(self,', 'state):', 'if', 'len(state)', '==', 'len(self.variables):', 'return', '[]', 'else:', 'assignment', '=', 'dict(state)', 'var', '=', 'first([v', 'for', 'v', 'in', 'self.variables', 'if', 'v', 'not', 'in', 'assignment])', 'return', '[(var,', 'val)', 'for', 'val', 'in', 'self.domains[var]', 'if', ... | 115,659 |
nicknochnack/RealTimeSignLanguageTFJS | model_helpers_test.py | PastStopThresholdTest.test_past_stop_threshold_not_number | test_past_stop_threshold_not_number | Tests for error conditions. | [
"Tests",
"for",
"error",
"conditions."
] | def test_past_stop_threshold_not_number(self):
with self.assertRaises(ValueError):
model_helpers.past_stop_threshold('str', 1)
with self.assertRaises(ValueError):
model_helpers.past_stop_threshold('str', tf.constant(5))
with self.assertRaises(ValueError):
model_helpers.past_stop_thre... | ['def', 'test_past_stop_threshold_not_number(self):', 'with', 'self.assertRaises(ValueError):', "model_helpers.past_stop_threshold('str',", '1)', 'with', 'self.assertRaises(ValueError):', "model_helpers.past_stop_threshold('str',", 'tf.constant(5))', 'with', 'self.assertRaises(ValueError):', "model_helpers.past_stop_th... | 850,735 |
dawdleryang/object_detection | box_list_ops.py | matched_intersection | matched_intersection | Compute intersection areas between corresponding boxes in two boxlists. | [
"Compute",
"intersection",
"areas",
"between",
"corresponding",
"boxes",
"in",
"two",
"boxlists."
] | def matched_intersection(boxlist1, boxlist2, scope=None):
with tf.name_scope(scope, 'MatchedIntersection'):
(y_min1, x_min1, y_max1, x_max1) = tf.split(value=boxlist1.get(), num_or_size_splits=4, axis=1)
(y_min2, x_min2, y_max2, x_max2) = tf.split(value=boxlist2.get(), num_or_size_splits=4, axis=1)
... | ['def', 'matched_intersection(boxlist1,', 'boxlist2,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'MatchedIntersection'):", '(y_min1,', 'x_min1,', 'y_max1,', 'x_max1)', '=', 'tf.split(value=boxlist1.get(),', 'num_or_size_splits=4,', 'axis=1)', '(y_min2,', 'x_min2,', 'y_max2,', 'x_max2)', '=', 'tf.split(value=boxl... | 775,557 |
enuguru/artificial_intelligence_and_machine_learning | formparser.py | default_stream_factory | default_stream_factory | The stream factory that is used per default. | [
"The",
"stream",
"factory",
"that",
"is",
"used",
"per",
"default."
] | def default_stream_factory(total_content_length, filename, content_type, content_length=None):
if total_content_length > 1024 * 500:
return TemporaryFile('wb+')
return BytesIO() | ['def', 'default_stream_factory(total_content_length,', 'filename,', 'content_type,', 'content_length=None):', 'if', 'total_content_length', '>', '1024', '*', '500:', 'return', "TemporaryFile('wb+')", 'return', 'BytesIO()'] | 161,267 |
JxustLiao/Natural-Language-Processing | wingnus.py | WINGNUS.feature_extraction | feature_extraction | Extract features for each candidate. | [
"Extract",
"features",
"for",
"each",
"candidate."
] | def feature_extraction(self, df=None, training=False, features_set=None):
if features_set is None:
features_set = [1, 4, 6]
if df is None:
logging.warning('LoadFile._df_counts is hard coded to {}'.format(self._df_counts))
df = load_document_frequency_file(self._df_counts, delimiter='\t')... | ['def', 'feature_extraction(self,', 'df=None,', 'training=False,', 'features_set=None):', 'if', 'features_set', 'is', 'None:', 'features_set', '=', '[1,', '4,', '6]', 'if', 'df', 'is', 'None:', "logging.warning('LoadFile._df_counts", 'is', 'hard', 'coded', 'to', "{}'.format(self._df_counts))", 'df', '=', 'load_document... | 659,529 |
prof-fabriciogmc/artificial_intelligence | prepare.py | DistAbstraction.prep_for_dist | prep_for_dist | Ensure that we can get a Dist for this requirement. | [
"Ensure",
"that",
"we",
"can",
"get",
"a",
"Dist",
"for",
"this",
"requirement."
] | def prep_for_dist(self, finder):
raise NotImplementedError(self.dist) | ['def', 'prep_for_dist(self,', 'finder):', 'raise', 'NotImplementedError(self.dist)'] | 141,472 |
nicknochnack/RealTimeSignLanguageTFJS | classifier_trainer.py | run | run | Runs Image Classification model using native Keras APIs. | [
"Runs",
"Image",
"Classification",
"model",
"using",
"native",
"Keras",
"APIs."
] | def run(flags_obj: flags.FlagValues, strategy_override: tf.distribute.Strategy=None) -> Mapping[str, Any]:
params = _get_params_from_flags(flags_obj)
if params.mode == 'train_and_eval':
return train_and_eval(params, strategy_override)
elif params.mode == 'export_only':
export(params)
els... | ['def', 'run(flags_obj:', 'flags.FlagValues,', 'strategy_override:', 'tf.distribute.Strategy=None)', '->', 'Mapping[str,', 'Any]:', 'params', '=', '_get_params_from_flags(flags_obj)', 'if', 'params.mode', '==', "'train_and_eval':", 'return', 'train_and_eval(params,', 'strategy_override)', 'elif', 'params.mode', '==', "... | 851,152 |
tensorflow/agents | parallel_py_environment.py | ParallelPyEnvironment.seed | seed | Seeds the parallel environments. | [
"Seeds",
"the",
"parallel",
"environments."
] | def seed(self, seeds: Sequence[types.Seed]) -> Sequence[Any]:
if len(seeds) != len(self._envs):
raise ValueError('Number of seeds should match the number of parallel_envs.')
promises = [env.call('seed', seed) for (seed, env) in zip(seeds, self._envs)]
return [promise() for promise in promises] | ['def', 'seed(self,', 'seeds:', 'Sequence[types.Seed])', '->', 'Sequence[Any]:', 'if', 'len(seeds)', '!=', 'len(self._envs):', 'raise', "ValueError('Number", 'of', 'seeds', 'should', 'match', 'the', 'number', 'of', "parallel_envs.')", 'promises', '=', "[env.call('seed',", 'seed)', 'for', '(seed,', 'env)', 'in', 'zip(se... | 23,413 |
triaquae/triaquae | dates.py | DayMixin.get_previous_day | get_previous_day | Get the previous valid day. | [
"Get",
"the",
"previous",
"valid",
"day."
] | def get_previous_day(self, date):
return _get_next_prev(self, date, is_previous=True, period='day') | ['def', 'get_previous_day(self,', 'date):', 'return', '_get_next_prev(self,', 'date,', 'is_previous=True,', "period='day')"] | 424,350 |
cheng052/BRNet | nostem_regnet.py | NoStemRegNet.forward | forward | Forward function of backbone. | [
"Forward",
"function",
"of",
"backbone."
] | def forward(self, x):
outs = []
for (i, layer_name) in enumerate(self.res_layers):
res_layer = getattr(self, layer_name)
x = res_layer(x)
if i in self.out_indices:
outs.append(x)
return tuple(outs) | ['def', 'forward(self,', 'x):', 'outs', '=', '[]', 'for', '(i,', 'layer_name)', 'in', 'enumerate(self.res_layers):', 'res_layer', '=', 'getattr(self,', 'layer_name)', 'x', '=', 'res_layer(x)', 'if', 'i', 'in', 'self.out_indices:', 'outs.append(x)', 'return', 'tuple(outs)'] | 409,858 |
danaugrs/huskarl | dqn.py | DQN.train | train | Trains the agent for one step. | [
"Trains",
"the",
"agent",
"for",
"one",
"step."
] | def train(self, step):
if len(self.memory) == 0:
return
if self.target_update >= 1 and step % self.target_update == 0:
self.target_model.set_weights(self.model.get_weights())
elif self.target_update < 1:
mw = np.array(self.model.get_weights())
tmw = np.array(self.target_model... | ['def', 'train(self,', 'step):', 'if', 'len(self.memory)', '==', '0:', 'return', 'if', 'self.target_update', '>=', '1', 'and', 'step', '%', 'self.target_update', '==', '0:', 'self.target_model.set_weights(self.model.get_weights())', 'elif', 'self.target_update', '<', '1:', 'mw', '=', 'np.array(self.model.get_weights())... | 206,812 |
qdraw/tensorflow-object-detection-tutorial | ops.py | filter_groundtruth_with_nan_box_coordinates | filter_groundtruth_with_nan_box_coordinates | Filters out groundtruth with no bounding boxes. | [
"Filters",
"out",
"groundtruth",
"with",
"no",
"bounding",
"boxes."
] | def filter_groundtruth_with_nan_box_coordinates(tensor_dict):
groundtruth_boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes]
nan_indicator_vector = tf.greater(tf.reduce_sum(tf.to_int32(tf.is_nan(groundtruth_boxes)), reduction_indices=[1]), 0)
valid_indicator_vector = tf.logical_not(nan_indicator_... | ['def', 'filter_groundtruth_with_nan_box_coordinates(tensor_dict):', 'groundtruth_boxes', '=', 'tensor_dict[fields.InputDataFields.groundtruth_boxes]', 'nan_indicator_vector', '=', 'tf.greater(tf.reduce_sum(tf.to_int32(tf.is_nan(groundtruth_boxes)),', 'reduction_indices=[1]),', '0)', 'valid_indicator_vector', '=', 'tf.... | 921,632 |
devashish-patel/webcam-motion-detector | settings.py | Settings.strict | strict | Set whether validation should be performed strictly. | [
"Set",
"whether",
"validation",
"should",
"be",
"performed",
"strictly."
] | def strict(self, default=None):
return self._get_bool('STRICT', default, False) | ['def', 'strict(self,', 'default=None):', 'return', "self._get_bool('STRICT',", 'default,', 'False)'] | 977,081 |
MycroftAI/mycroft-core | test_intent_service.py | create_vocab_msg | create_vocab_msg | Create a message for registering an adapt keyword. | [
"Create",
"a",
"message",
"for",
"registering",
"an",
"adapt",
"keyword."
] | def create_vocab_msg(keyword, value):
return Message('register_vocab', {'entity_value': value, 'entity_type': keyword}) | ['def', 'create_vocab_msg(keyword,', 'value):', 'return', "Message('register_vocab',", "{'entity_value':", 'value,', "'entity_type':", 'keyword})'] | 290,922 |
weimin17/Object-Detection_HelmetDetection | create_kitti_tf_record.py | convert_kitti_to_tfrecords | convert_kitti_to_tfrecords | Convert the KITTI detection dataset to TFRecords. | [
"Convert",
"the",
"KITTI",
"detection",
"dataset",
"to",
"TFRecords."
] | def convert_kitti_to_tfrecords(data_dir, output_path, classes_to_use, label_map_path, validation_set_size):
label_map_dict = label_map_util.get_label_map_dict(label_map_path)
train_count = 0
val_count = 0
annotation_dir = os.path.join(data_dir, 'training', 'label_2')
image_dir = os.path.join(data_di... | ['def', 'convert_kitti_to_tfrecords(data_dir,', 'output_path,', 'classes_to_use,', 'label_map_path,', 'validation_set_size):', 'label_map_dict', '=', 'label_map_util.get_label_map_dict(label_map_path)', 'train_count', '=', '0', 'val_count', '=', '0', 'annotation_dir', '=', 'os.path.join(data_dir,', "'training',", "'lab... | 750,756 |
deepmind/dm_control | task.py | Task.get_discount_spec | get_discount_spec | Optional method to define non-scalar discounts for a `Task`. | [
"Optional",
"method",
"to",
"define",
"non-scalar",
"discounts",
"for",
"a",
"`Task`."
] | def get_discount_spec(self):
return None | ['def', 'get_discount_spec(self):', 'return', 'None'] | 164,977 |
AlekseiMaide/FeedForwardNeuralNetwork | FFNN.py | FFNN.sigmoid | sigmoid | derivative of sigmoid is 1/(1+exp(-x)) which is what expit does. | [
"derivative",
"of",
"sigmoid",
"is",
"1/(1+exp(-x))",
"which",
"is",
"what",
"expit",
"does."
] | def sigmoid(self, param):
return scipy.special.expit(param) | ['def', 'sigmoid(self,', 'param):', 'return', 'scipy.special.expit(param)'] | 582,295 |
PacktPublishing/Hands-On-Artificial--for-Banking | core.py | Context.exit | exit | Exits the application with a given exit code. | [
"Exits",
"the",
"application",
"with",
"a",
"given",
"exit",
"code."
] | def exit(self, code=0):
raise Exit(code) | ['def', 'exit(self,', 'code=0):', 'raise', 'Exit(code)'] | 234,721 |
SajalGoel/Natural-Language-Processing | test_singlerank.py | test_singlerank_candidate_weighting | test_singlerank_candidate_weighting | Test SingleRank candidate weighting method. | [
"Test",
"SingleRank",
"candidate",
"weighting",
"method."
] | def test_singlerank_candidate_weighting():
extractor = pke.unsupervised.SingleRank()
extractor.load_document(input=test_file)
extractor.candidate_selection(pos=pos)
extractor.candidate_weighting(window=10, pos=pos)
keyphrases = [k for (k, s) in extractor.get_n_best(n=3)]
assert keyphrases == ['m... | ['def', 'test_singlerank_candidate_weighting():', 'extractor', '=', 'pke.unsupervised.SingleRank()', 'extractor.load_document(input=test_file)', 'extractor.candidate_selection(pos=pos)', 'extractor.candidate_weighting(window=10,', 'pos=pos)', 'keyphrases', '=', '[k', 'for', '(k,', 's)', 'in', 'extractor.get_n_best(n=3)... | 663,200 |
BlissChapman/ICW-fMRI-GAN | dataset.py | FeatureTable.get_ids_by_expression | get_ids_by_expression | Use a PEG to parse expression and return study IDs. | [
"Use",
"a",
"PEG",
"to",
"parse",
"expression",
"and",
"return",
"study",
"IDs."
] | def get_ids_by_expression(self, expression, threshold=0.001, func=np.sum):
lexer = lp.Lexer()
lexer.build()
parser = lp.Parser(lexer, self.dataset, threshold=threshold, func=func)
parser.build()
return parser.parse(expression).keys().values | ['def', 'get_ids_by_expression(self,', 'expression,', 'threshold=0.001,', 'func=np.sum):', 'lexer', '=', 'lp.Lexer()', 'lexer.build()', 'parser', '=', 'lp.Parser(lexer,', 'self.dataset,', 'threshold=threshold,', 'func=func)', 'parser.build()', 'return', 'parser.parse(expression).keys().values'] | 597,072 |
thaines/helit | gaussian_prior.py | GaussianPrior.safe | safe | Returns true if it is possible to sample the prior, work out the probability of samples or work out the probability of samples being drawn from a collapsed sample - basically a test that there is enough information. | [
"Returns",
"true",
"if",
"it",
"is",
"possible",
"to",
"sample",
"the",
"prior,",
"work",
"out",
"the",
"probability",
"of",
"samples",
"or",
"work",
"out",
"the",
"probability",
"of",
"samples",
"being",
"drawn",
"from",
"a",
"collapsed",
"sample",
"-",
"... | def safe(self):
return self.n >= self.mu.shape[0] and self.k > 0.0 | ['def', 'safe(self):', 'return', 'self.n', '>=', 'self.mu.shape[0]', 'and', 'self.k', '>', '0.0'] | 591,678 |
Ruturaj123/Flowchart-Detection | models.py | get_rnn_model | get_rnn_model | Returns a function that creates a RNN TensorFlow subgraph. | [
"Returns",
"a",
"function",
"that",
"creates",
"a",
"RNN",
"TensorFlow",
"subgraph."
] | def get_rnn_model(rnn_size, cell_type, num_layers, input_op_fn, bidirectional, target_predictor_fn, sequence_length, initial_state, attn_length, attn_size, attn_vec_size):
def rnn_estimator(x, y):
x = input_op_fn(x)
if cell_type == 'rnn':
cell_fn = contrib_rnn.BasicRNNCell
elif ... | ['def', 'get_rnn_model(rnn_size,', 'cell_type,', 'num_layers,', 'input_op_fn,', 'bidirectional,', 'target_predictor_fn,', 'sequence_length,', 'initial_state,', 'attn_length,', 'attn_size,', 'attn_vec_size):', 'def', 'rnn_estimator(x,', 'y):', 'x', '=', 'input_op_fn(x)', 'if', 'cell_type', '==', "'rnn':", 'cell_fn', '='... | 603,793 |
kamaleshkio/Natural-Language-Processing | multipartiterank.py | MultipartiteRank.build_topic_graph | build_topic_graph | Build the Multipartite graph. | [
"Build",
"the",
"Multipartite",
"graph."
] | def build_topic_graph(self):
self.graph.add_nodes_from(self.candidates.keys())
for (node_i, node_j) in combinations(self.candidates.keys(), 2):
if self.topic_identifiers[node_i] == self.topic_identifiers[node_j]:
continue
weights = []
for p_i in self.candidates[node_i].offset... | ['def', 'build_topic_graph(self):', 'self.graph.add_nodes_from(self.candidates.keys())', 'for', '(node_i,', 'node_j)', 'in', 'combinations(self.candidates.keys(),', '2):', 'if', 'self.topic_identifiers[node_i]', '==', 'self.topic_identifiers[node_j]:', 'continue', 'weights', '=', '[]', 'for', 'p_i', 'in', 'self.candida... | 660,204 |
saysaysx/artificial-intelligence | locations.py | running_under_virtualenv | running_under_virtualenv | Return True if we're running inside a virtualenv, False otherwise. | [
"Return",
"True",
"if",
"we're",
"running",
"inside",
"a",
"virtualenv,",
"False",
"otherwise."
] | def running_under_virtualenv():
if hasattr(sys, 'real_prefix'):
return True
elif sys.prefix != getattr(sys, 'base_prefix', sys.prefix):
return True
return False | ['def', 'running_under_virtualenv():', 'if', 'hasattr(sys,', "'real_prefix'):", 'return', 'True', 'elif', 'sys.prefix', '!=', 'getattr(sys,', "'base_prefix',", 'sys.prefix):', 'return', 'True', 'return', 'False'] | 88,101 |
deephyper/deephyper | _hyperparameter.py | HpProblem.space | space | The wrapped ConfigSpace object. | [
"The",
"wrapped",
"ConfigSpace",
"object."
] | def space(self):
return self._space | ['def', 'space(self):', 'return', 'self._space'] | 520,941 |
yizheh/Chinese_Font_Transfer | msvc.py | RegistryInfo.windows_sdk | windows_sdk | Microsoft Windows/Platform SDK registry key. | [
"Microsoft",
"Windows/Platform",
"SDK",
"registry",
"key."
] | def windows_sdk(self):
return os.path.join(self.microsoft_sdk, 'Windows') | ['def', 'windows_sdk(self):', 'return', 'os.path.join(self.microsoft_sdk,', "'Windows')"] | 487,342 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.