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
nicknochnack/RealTimeSignLanguageTFJS
run_squad_helper.py
get_squad_model_to_predict
get_squad_model_to_predict
Gets a squad model to make predictions.
[ "Gets", "a", "squad", "model", "to", "make", "predictions." ]
def get_squad_model_to_predict(strategy, bert_config, checkpoint_path, input_meta_data): with strategy.scope(): tf.keras.mixed_precision.experimental.set_policy('float32') (squad_model, _) = bert_models.squad_model(bert_config, input_meta_data['max_seq_length'], hub_module_url=FLAGS.hub_module_url) ...
['def', 'get_squad_model_to_predict(strategy,', 'bert_config,', 'checkpoint_path,', 'input_meta_data):', 'with', 'strategy.scope():', "tf.keras.mixed_precision.experimental.set_policy('float32')", '(squad_model,', '_)', '=', 'bert_models.squad_model(bert_config,', "input_meta_data['max_seq_length'],", 'hub_module_url=F...
850,309
dengzelu/semantic-segmentation-pytorch
functional.py
get_stats
get_stats
Compute true positive, false positive, false negative, true negative 'pixels' for each image and each class.
[ "Compute", "true", "positive,", "false", "positive,", "false", "negative,", "true", "negative", "'pixels'", "for", "each", "image", "and", "each", "class." ]
def get_stats(output: Union[torch.LongTensor, torch.FloatTensor], target: torch.LongTensor, mode: str, ignore_index: Optional[int]=None, threshold: Optional[Union[float, List[float]]]=None, num_classes: Optional[int]=None) -> Tuple[torch.LongTensor]: if torch.is_floating_point(target): raise ValueError(f'Ta...
['def', 'get_stats(output:', 'Union[torch.LongTensor,', 'torch.FloatTensor],', 'target:', 'torch.LongTensor,', 'mode:', 'str,', 'ignore_index:', 'Optional[int]=None,', 'threshold:', 'Optional[Union[float,', 'List[float]]]=None,', 'num_classes:', 'Optional[int]=None)', '->', 'Tuple[torch.LongTensor]:', 'if', 'torch.is_f...
870,333
sek788432/Waymo-2D-Object-Detection
static_shape.py
get_dim_as_int
get_dim_as_int
Utility to get v1 or v2 TensorShape dim as an int.
[ "Utility", "to", "get", "v1", "or", "v2", "TensorShape", "dim", "as", "an", "int." ]
def get_dim_as_int(dim): try: return dim.value except AttributeError: return dim
['def', 'get_dim_as_int(dim):', 'try:', 'return', 'dim.value', 'except', 'AttributeError:', 'return', 'dim']
975,562
Eric3911/OpenAGI
test_audio_utils.py
TestAudioUtilsElements.test_toeplitz
test_toeplitz
Test construction of a Toeplitz matrix for a given signal.
[ "Test", "construction", "of", "a", "Toeplitz", "matrix", "for", "a", "given", "signal." ]
def test_toeplitz(self, num_channels: int, filter_length: int, num_samples: int): atol = 1e-06 random_seed = 42 num_batches = 10 batch_size = 8 _rng = np.random.default_rng(seed=random_seed) for n in range(num_batches): x = _rng.normal(size=(batch_size, num_channels, num_samples)) ...
['def', 'test_toeplitz(self,', 'num_channels:', 'int,', 'filter_length:', 'int,', 'num_samples:', 'int):', 'atol', '=', '1e-06', 'random_seed', '=', '42', 'num_batches', '=', '10', 'batch_size', '=', '8', '_rng', '=', 'np.random.default_rng(seed=random_seed)', 'for', 'n', 'in', 'range(num_batches):', 'x', '=', '_rng.no...
274,394
matsu0228/nlp-jp
backgroundjobs.py
BackgroundJobManager.remove
remove
Remove a finished (completed or dead) job.
[ "Remove", "a", "finished", "(completed", "or", "dead)", "job." ]
def remove(self, num): try: job = self.all[num] except KeyError: error('Job #%s not found' % num) else: stat_code = job.stat_code if stat_code == self._s_running: error('Job #%s is still running, it can not be removed.' % num) return elif stat_...
['def', 'remove(self,', 'num):', 'try:', 'job', '=', 'self.all[num]', 'except', 'KeyError:', "error('Job", '#%s', 'not', "found'", '%', 'num)', 'else:', 'stat_code', '=', 'job.stat_code', 'if', 'stat_code', '==', 'self._s_running:', "error('Job", '#%s', 'is', 'still', 'running,', 'it', 'can', 'not', 'be', "removed.'", ...
787,157
openkinome/kinoml
versioneer.py
get_cmdclass
get_cmdclass
Get the custom setuptools/distutils subclasses used by Versioneer.
[ "Get", "the", "custom", "setuptools/distutils", "subclasses", "used", "by", "Versioneer." ]
def get_cmdclass(): if 'versioneer' in sys.modules: del sys.modules['versioneer'] cmds = {} from distutils.core import Command class cmd_version(Command): description = 'report generated version string' user_options = [] boolean_options = [] def initialize_optio...
['def', 'get_cmdclass():', 'if', "'versioneer'", 'in', 'sys.modules:', 'del', "sys.modules['versioneer']", 'cmds', '=', '{}', 'from', 'distutils.core', 'import', 'Command', 'class', 'cmd_version(Command):', 'description', '=', "'report", 'generated', 'version', "string'", 'user_options', '=', '[]', 'boolean_options', '...
596,074
lazycatcat/Unsupervised-Learning
data.py
Data.load_features
load_features
Extract features from the trained VAE model.
[ "Extract", "features", "from", "the", "trained", "VAE", "model." ]
def load_features(self, data, net): net.load_state_dict(torch.load(utils.model_path())) net.eval() embeddings_list = [] labels_list = [] with torch.no_grad(): for batch in range(int(len(data.dataloader.dataset) / config.BATCH_SIZE)): (X_batch, Y_batch) = data.load_batch() ...
['def', 'load_features(self,', 'data,', 'net):', 'net.load_state_dict(torch.load(utils.model_path()))', 'net.eval()', 'embeddings_list', '=', '[]', 'labels_list', '=', '[]', 'with', 'torch.no_grad():', 'for', 'batch', 'in', 'range(int(len(data.dataloader.dataset)', '/', 'config.BATCH_SIZE)):', '(X_batch,', 'Y_batch)', ...
353,225
ryu-ed/SpaceInvaders_Ros
wheel.py
csv_io_kwargs
csv_io_kwargs
Return keyword arguments to properly open a CSV file in the given mode.
[ "Return", "keyword", "arguments", "to", "properly", "open", "a", "CSV", "file", "in", "the", "given", "mode." ]
def csv_io_kwargs(mode): if sys.version_info.major < 3: return {'mode': '{}b'.format(mode)} else: return {'mode': mode, 'newline': ''}
['def', 'csv_io_kwargs(mode):', 'if', 'sys.version_info.major', '<', '3:', 'return', "{'mode':", "'{}b'.format(mode)}", 'else:', 'return', "{'mode':", 'mode,', "'newline':", "''}"]
367,826
greydanus/pythonic_ocr
serving.py
WSGIRequestHandler.send_response
send_response
Send the response header and log the response code.
[ "Send", "the", "response", "header", "and", "log", "the", "response", "code." ]
def send_response(self, code, message=None): self.log_request(code) if message is None: message = code in self.responses and self.responses[code][0] or '' if self.request_version != 'HTTP/0.9': hdr = '%s %d %s\r\n' % (self.protocol_version, code, message) self.wfile.write(hdr.encode(...
['def', 'send_response(self,', 'code,', 'message=None):', 'self.log_request(code)', 'if', 'message', 'is', 'None:', 'message', '=', 'code', 'in', 'self.responses', 'and', 'self.responses[code][0]', 'or', "''", 'if', 'self.request_version', '!=', "'HTTP/0.9':", 'hdr', '=', "'%s", '%d', "%s\\r\\n'", '%', '(self.protocol_...
301,087
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
data_utils.py
read_tmp_file
read_tmp_file
Read from a file with the given name in our log directory or above.
[ "Read", "from", "a", "file", "with", "the", "given", "name", "in", "our", "log", "directory", "or", "above." ]
def read_tmp_file(name): dirname = os.path.dirname(log_filename) fname = os.path.join(dirname, name + '.txt') if not tf.gfile.Exists(fname): print_out('== not found file: ' + fname) fname = os.path.join(dirname, '../' + name + '.txt') if not tf.gfile.Exists(fname): print_out('== ...
['def', 'read_tmp_file(name):', 'dirname', '=', 'os.path.dirname(log_filename)', 'fname', '=', 'os.path.join(dirname,', 'name', '+', "'.txt')", 'if', 'not', 'tf.gfile.Exists(fname):', "print_out('==", 'not', 'found', 'file:', "'", '+', 'fname)', 'fname', '=', 'os.path.join(dirname,', "'../'", '+', 'name', '+', "'.txt')...
50,034
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
ga_train.py
CheckpointWriter.has_checkpoint
has_checkpoint
Checks if a checkpoint exists on disk, and if so returns True.
[ "Checks", "if", "a", "checkpoint", "exists", "on", "disk,", "and", "if", "so", "returns", "True." ]
def has_checkpoint(self): return tf.gfile.Exists(self.checkpoint_file)
['def', 'has_checkpoint(self):', 'return', 'tf.gfile.Exists(self.checkpoint_file)']
46,551
pramodiperera/virtual-keyboard
egg_info.py
FileList.global_exclude
global_exclude
Exclude all files anywhere that match the pattern.
[ "Exclude", "all", "files", "anywhere", "that", "match", "the", "pattern." ]
def global_exclude(self, pattern): match = translate_pattern(os.path.join('**', pattern)) return self._remove_files(match.match)
['def', 'global_exclude(self,', 'pattern):', 'match', '=', "translate_pattern(os.path.join('**',", 'pattern))', 'return', 'self._remove_files(match.match)']
933,090
enlite-ai/maze
hydra_helper_functions.py
check_env_and_model_instantiation
check_env_and_model_instantiation
Check if env instantiation works.
[ "Check", "if", "env", "instantiation", "works." ]
def check_env_and_model_instantiation(config_module: str, config: str, overrides: Dict[str, str]) -> None: with initialize_config_module(config_module): cfg = compose(config, overrides=[key + '=' + value for (key, value) in overrides.items()]) env_factory = EnvFactory(cfg.env, cfg.wrappers if 'wrappers'...
['def', 'check_env_and_model_instantiation(config_module:', 'str,', 'config:', 'str,', 'overrides:', 'Dict[str,', 'str])', '->', 'None:', 'with', 'initialize_config_module(config_module):', 'cfg', '=', 'compose(config,', 'overrides=[key', '+', "'='", '+', 'value', 'for', '(key,', 'value)', 'in', 'overrides.items()])', ...
647,265
google-research/scenic
test_lr_schedules.py
LearningRateScchedulesTest.test_constant_linear_warmup
test_constant_linear_warmup
Test that linear warmup schedule works correctly.
[ "Test", "that", "linear", "warmup", "schedule", "works", "correctly." ]
def test_constant_linear_warmup(self): warmup_steps = 100 warmup_alpha = 0.1 config = ml_collections.ConfigDict(dict(lr_configs={'learning_rate_schedule': 'compound', 'factors': 'constant*linear_warmup', 'base_learning_rate': 1.0, 'warmup_steps': warmup_steps, 'warmup_alpha': warmup_alpha})) lr_fn = lr_...
['def', 'test_constant_linear_warmup(self):', 'warmup_steps', '=', '100', 'warmup_alpha', '=', '0.1', 'config', '=', "ml_collections.ConfigDict(dict(lr_configs={'learning_rate_schedule':", "'compound',", "'factors':", "'constant*linear_warmup',", "'base_learning_rate':", '1.0,', "'warmup_steps':", 'warmup_steps,', "'wa...
847,655
sktime/sktime
test_all_classifiers.py
TestAllClassifiers.test_classifier_on_basic_motions
test_classifier_on_basic_motions
Test classifier on basic motions data.
[ "Test", "classifier", "on", "basic", "motions", "data." ]
def test_classifier_on_basic_motions(self, estimator_class): classname = estimator_class.__name__ if classname in basic_motions_proba.keys(): expected_probas = basic_motions_proba[classname] else: return None try: estimator_instance = estimator_class.create_test_instance(paramete...
['def', 'test_classifier_on_basic_motions(self,', 'estimator_class):', 'classname', '=', 'estimator_class.__name__', 'if', 'classname', 'in', 'basic_motions_proba.keys():', 'expected_probas', '=', 'basic_motions_proba[classname]', 'else:', 'return', 'None', 'try:', 'estimator_instance', '=', "estimator_class.create_tes...
886,040
zackmcnulty/CSE_446-Machine_Learning
backend_pgf.py
PdfPages.get_pagecount
get_pagecount
Returns the current number of pages in the multipage pdf file.
[ "Returns", "the", "current", "number", "of", "pages", "in", "the", "multipage", "pdf", "file." ]
def get_pagecount(self): return self._n_figures
['def', 'get_pagecount(self):', 'return', 'self._n_figures']
195,019
rudranil723/mini-main
pyplot.py
new_figure_manager
new_figure_manager
Create a new figure manager instance.
[ "Create", "a", "new", "figure", "manager", "instance." ]
def new_figure_manager(*args, **kwargs): _warn_if_gui_out_of_main_thread() return _get_backend_mod().new_figure_manager(*args, **kwargs)
['def', 'new_figure_manager(*args,', '**kwargs):', '_warn_if_gui_out_of_main_thread()', 'return', '_get_backend_mod().new_figure_manager(*args,', '**kwargs)']
319,582
michiyasunaga/BIFI
utils.py
resolve_max_positions
resolve_max_positions
Resolve max position constraints from multiple sources.
[ "Resolve", "max", "position", "constraints", "from", "multiple", "sources." ]
def resolve_max_positions(*args): def map_value_update(d1, d2): updated_value = copy.deepcopy(d1) for key in d2: if key not in updated_value: updated_value[key] = d2[key] else: updated_value[key] = min(d1[key], d2[key]) return updated_...
['def', 'resolve_max_positions(*args):', 'def', 'map_value_update(d1,', 'd2):', 'updated_value', '=', 'copy.deepcopy(d1)', 'for', 'key', 'in', 'd2:', 'if', 'key', 'not', 'in', 'updated_value:', 'updated_value[key]', '=', 'd2[key]', 'else:', 'updated_value[key]', '=', 'min(d1[key],', 'd2[key])', 'return', 'updated_value...
107,326
Farama-Foundation/Gymnasium
vector_envs_tutorial.py
A2C.update_parameters
update_parameters
Updates the parameters of the actor and critic networks.
[ "Updates", "the", "parameters", "of", "the", "actor", "and", "critic", "networks." ]
def update_parameters(self, critic_loss: torch.Tensor, actor_loss: torch.Tensor) -> None: self.critic_optim.zero_grad() critic_loss.backward() self.critic_optim.step() self.actor_optim.zero_grad() actor_loss.backward() self.actor_optim.step()
['def', 'update_parameters(self,', 'critic_loss:', 'torch.Tensor,', 'actor_loss:', 'torch.Tensor)', '->', 'None:', 'self.critic_optim.zero_grad()', 'critic_loss.backward()', 'self.critic_optim.step()', 'self.actor_optim.zero_grad()', 'actor_loss.backward()', 'self.actor_optim.step()']
572,956
mxbh/robust_object_detection
augmentation.py
BlurTransform.apply_segmentation
apply_segmentation
Apply no transform on the full-image segmentation.
[ "Apply", "no", "transform", "on", "the", "full-image", "segmentation." ]
def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray: return segmentation
['def', 'apply_segmentation(self,', 'segmentation:', 'np.ndarray)', '->', 'np.ndarray:', 'return', 'segmentation']
827,082
ShuLiu1993/PANet
test.py
combine_heatmaps_size_dep
combine_heatmaps_size_dep
Combines heatmaps while taking object sizes into account.
[ "Combines", "heatmaps", "while", "taking", "object", "sizes", "into", "account." ]
def combine_heatmaps_size_dep(hms_ts, ds_ts, us_ts, boxes, heur_f): assert len(hms_ts) == len(ds_ts) and len(ds_ts) == len(us_ts), 'All sets of hms must be tagged with downscaling and upscaling flags' areas = box_utils.boxes_area(boxes) sm_objs = areas < cfg.TEST.KPS_AUG.AREA_TH l_objs = areas >= cfg.TE...
['def', 'combine_heatmaps_size_dep(hms_ts,', 'ds_ts,', 'us_ts,', 'boxes,', 'heur_f):', 'assert', 'len(hms_ts)', '==', 'len(ds_ts)', 'and', 'len(ds_ts)', '==', 'len(us_ts),', "'All", 'sets', 'of', 'hms', 'must', 'be', 'tagged', 'with', 'downscaling', 'and', 'upscaling', "flags'", 'areas', '=', 'box_utils.boxes_area(boxe...
778,672
metadriverse/metadrive
effect.py
Effect.get_shader_obj
get_shader_obj
Returns a handle to the compiled shader object for a given render pass.
[ "Returns", "a", "handle", "to", "the", "compiled", "shader", "object", "for", "a", "given", "render", "pass." ]
def get_shader_obj(self, pass_id): if pass_id not in self._shader_objs: self.warn("Pass '" + pass_id + "' not found!") return False return self._shader_objs[pass_id]
['def', 'get_shader_obj(self,', 'pass_id):', 'if', 'pass_id', 'not', 'in', 'self._shader_objs:', 'self.warn("Pass', '\'"', '+', 'pass_id', '+', '"\'', 'not', 'found!")', 'return', 'False', 'return', 'self._shader_objs[pass_id]']
633,958
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
expatbuilder.py
Namespaces.start_namespace_decl_handler
start_namespace_decl_handler
Push this namespace declaration on our storage.
[ "Push", "this", "namespace", "declaration", "on", "our", "storage." ]
def start_namespace_decl_handler(self, prefix, uri): self._ns_ordered_prefixes.append((prefix, uri))
['def', 'start_namespace_decl_handler(self,', 'prefix,', 'uri):', 'self._ns_ordered_prefixes.append((prefix,', 'uri))']
377,303
ilya16/MultINN
rnn_nade.py
RnnNade.single_step
single_step
Processes the input sequences of one time step size.
[ "Processes", "the", "input", "sequences", "of", "one", "time", "step", "size." ]
def single_step(self, inputs, initial_state): (rnn_outputs, rnn_state) = self._rnn_cell(inputs, initial_state.rnn_state) with tf.variable_scope('final_outputs'): outputs_flat = self._fc_layer(rnn_outputs) with tf.variable_scope('nade_biases'): (b_enc, b_dec) = self._build_biases(outputs_flat...
['def', 'single_step(self,', 'inputs,', 'initial_state):', '(rnn_outputs,', 'rnn_state)', '=', 'self._rnn_cell(inputs,', 'initial_state.rnn_state)', 'with', "tf.variable_scope('final_outputs'):", 'outputs_flat', '=', 'self._fc_layer(rnn_outputs)', 'with', "tf.variable_scope('nade_biases'):", '(b_enc,', 'b_dec)', '=', '...
644,268
neuroailab/TDANN
array_utils.py
midpoints_from_bin_edges
midpoints_from_bin_edges
Given `be`, a set of histogram bin edges, return the array of midpoints between those edges.
[ "Given", "`be`,", "a", "set", "of", "histogram", "bin", "edges,", "return", "the", "array", "of", "midpoints", "between", "those", "edges." ]
def midpoints_from_bin_edges(be: Union[np.ndarray, List[float]]) -> np.ndarray: arr = np.array(be) width = arr[1] - arr[0] return arr[1:] - width / 2
['def', 'midpoints_from_bin_edges(be:', 'Union[np.ndarray,', 'List[float]])', '->', 'np.ndarray:', 'arr', '=', 'np.array(be)', 'width', '=', 'arr[1]', '-', 'arr[0]', 'return', 'arr[1:]', '-', 'width', '/', '2']
907,935
openvinotoolkit/training_extensions
custom_multi_label_linear_cls_head.py
CustomMultiLabelLinearClsHead.forward_train
forward_train
Forward_train fuction of CustomMultiLabelLinearClsHead.
[ "Forward_train", "fuction", "of", "CustomMultiLabelLinearClsHead." ]
def forward_train(self, cls_score, gt_label, **kwargs): img_metas = kwargs.get('img_metas', False) cls_score = self.pre_logits(cls_score) gt_label = gt_label.type_as(cls_score) cls_score = self.fc(cls_score) * self.scale valid_batch_mask = gt_label >= 0 gt_label = gt_label[valid_batch_mask,].vie...
['def', 'forward_train(self,', 'cls_score,', 'gt_label,', '**kwargs):', 'img_metas', '=', "kwargs.get('img_metas',", 'False)', 'cls_score', '=', 'self.pre_logits(cls_score)', 'gt_label', '=', 'gt_label.type_as(cls_score)', 'cls_score', '=', 'self.fc(cls_score)', '*', 'self.scale', 'valid_batch_mask', '=', 'gt_label', '...
904,048
rudranil723/mini-main
backend_bases.py
GraphicsContextBase.get_antialiased
get_antialiased
Return whether the object should try to do antialiased rendering.
[ "Return", "whether", "the", "object", "should", "try", "to", "do", "antialiased", "rendering." ]
def get_antialiased(self): return self._antialiased
['def', 'get_antialiased(self):', 'return', 'self._antialiased']
319,089
cvjena/PartDetectorDisovery
translator_softmax.py
translator_softmax
translator_softmax
Translates the softmax layers.
[ "Translates", "the", "softmax", "layers." ]
def translator_softmax(cuda_layer, output_shapes): input_shape = output_shapes[cuda_layer['inputLayers'][0]['name']] output_shapes[cuda_layer['name']] = input_shape return core_layers.SoftmaxLayer(name=cuda_layer['name'])
['def', 'translator_softmax(cuda_layer,', 'output_shapes):', 'input_shape', '=', "output_shapes[cuda_layer['inputLayers'][0]['name']]", "output_shapes[cuda_layer['name']]", '=', 'input_shape', 'return', "core_layers.SoftmaxLayer(name=cuda_layer['name'])"]
278,453
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations
cma_es_lib.py
CMASolutionDict.insert
insert
insert an entry with key ``key`` and value ``value if value is not None else {'geno':key}`` and ``self[key]['kwarg'] = kwarg if kwarg is not None`` for the further kwargs.
[ "insert", "an", "entry", "with", "key", "``key``", "and", "value", "``value", "if", "value", "is", "not", "None", "else", "{'geno':key}``", "and", "``self[key]['kwarg']", "=", "kwarg", "if", "kwarg", "is", "not", "None``", "for", "the", "further", "kwargs." ]
def insert(self, key, geno=None, iteration=None, fitness=None, value=None): if iteration is not None and iteration > self.last_iteration and (iteration % 10 < 1): self.truncate(300, iteration - 3) elif value is not None and value.get('iteration'): iteration = value['iteration'] if iterat...
['def', 'insert(self,', 'key,', 'geno=None,', 'iteration=None,', 'fitness=None,', 'value=None):', 'if', 'iteration', 'is', 'not', 'None', 'and', 'iteration', '>', 'self.last_iteration', 'and', '(iteration', '%', '10', '<', '1):', 'self.truncate(300,', 'iteration', '-', '3)', 'elif', 'value', 'is', 'not', 'None', 'and',...
433,096
tonyhuang2022/UPL
upltrainer.py
UPLTrainer.zero_shot_analyze
zero_shot_analyze
A generic predicting pipeline.
[ "A", "generic", "predicting", "pipeline." ]
def zero_shot_analyze(self, trainer_list=None): self.set_model_mode('eval') self.model.eval() self.evaluator.reset() data_loader = self.train_loader_sstrain outputs = [] image_features_list = [] img_paths = [] from tqdm import tqdm for (batch_idx, batch) in tqdm(enumerate(data_loader...
['def', 'zero_shot_analyze(self,', 'trainer_list=None):', "self.set_model_mode('eval')", 'self.model.eval()', 'self.evaluator.reset()', 'data_loader', '=', 'self.train_loader_sstrain', 'outputs', '=', '[]', 'image_features_list', '=', '[]', 'img_paths', '=', '[]', 'from', 'tqdm', 'import', 'tqdm', 'for', '(batch_idx,',...
438,601
aimclub/FEDOT
test_pipeline_builder.py
test_skip_connection_edge_to_cycle_graph
test_skip_connection_edge_to_cycle_graph
Checks that cycles are avoided even if the edge to cycle graph if manually inserted.
[ "Checks", "that", "cycles", "are", "avoided", "even", "if", "the", "edge", "to", "cycle", "graph", "if", "manually", "inserted." ]
def test_skip_connection_edge_to_cycle_graph(): pipe = PipelineBuilder().add_node('operation_b', 0).add_node('operation_c', 0).add_node('operation_b2', 1).add_node('operation_c2', 1).join_branches('operation_f').build() pipe_try_cycle = PipelineBuilder().add_node('operation_b', 0).add_node('operation_c', 0).add...
['def', 'test_skip_connection_edge_to_cycle_graph():', 'pipe', '=', "PipelineBuilder().add_node('operation_b',", "0).add_node('operation_c',", "0).add_node('operation_b2',", "1).add_node('operation_c2',", "1).join_branches('operation_f').build()", 'pipe_try_cycle', '=', "PipelineBuilder().add_node('operation_b',", "0)....
546,174
tinazhouhui/computer_vision
inputs_test.py
InputsTest.test_error_with_bad_train_config
test_error_with_bad_train_config
Tests that a TypeError is raised with improper train config.
[ "Tests", "that", "a", "TypeError", "is", "raised", "with", "improper", "train", "config." ]
def test_error_with_bad_train_config(self): configs = _get_configs_for_model('ssd_inception_v2_pets') configs['model'].ssd.num_classes = 37 train_input_fn = inputs.create_train_input_fn(train_config=configs['eval_config'], train_input_config=configs['train_input_config'], model_config=configs['model']) ...
['def', 'test_error_with_bad_train_config(self):', 'configs', '=', "_get_configs_for_model('ssd_inception_v2_pets')", "configs['model'].ssd.num_classes", '=', '37', 'train_input_fn', '=', "inputs.create_train_input_fn(train_config=configs['eval_config'],", "train_input_config=configs['train_input_config'],", "model_con...
503,466
43Carrig/recurrent_neural_networks_practice
random_ops.py
random_normal
random_normal
Outputs random values from a normal distribution.
[ "Outputs", "random", "values", "from", "a", "normal", "distribution." ]
def random_normal(shape, mean=0.0, stddev=1.0, dtype=dtypes.float32, seed=None, name=None): with ops.name_scope(name, 'random_normal', [shape, mean, stddev]) as name: shape_tensor = _ShapeTensor(shape) mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name='mean') stddev_tensor = ops.co...
['def', 'random_normal(shape,', 'mean=0.0,', 'stddev=1.0,', 'dtype=dtypes.float32,', 'seed=None,', 'name=None):', 'with', 'ops.name_scope(name,', "'random_normal',", '[shape,', 'mean,', 'stddev])', 'as', 'name:', 'shape_tensor', '=', '_ShapeTensor(shape)', 'mean_tensor', '=', 'ops.convert_to_tensor(mean,', 'dtype=dtype...
338,894
ashwanitanwar/nmt-transfer-learning-xlm-r
metrics.py
reset_meters
reset_meters
Reset Meter instances aggregated under a given *name*.
[ "Reset", "Meter", "instances", "aggregated", "under", "a", "given", "*name*." ]
def reset_meters(name: str) -> None: meters = get_meters(name) if meters is not None: meters.reset()
['def', 'reset_meters(name:', 'str)', '->', 'None:', 'meters', '=', 'get_meters(name)', 'if', 'meters', 'is', 'not', 'None:', 'meters.reset()']
732,530
bm777/object_detection
coco_tools.py
COCOEvalWrapper.GetCategoryIdList
GetCategoryIdList
Returns list of valid category ids.
[ "Returns", "list", "of", "valid", "category", "ids." ]
def GetCategoryIdList(self): return self.params.catIds
['def', 'GetCategoryIdList(self):', 'return', 'self.params.catIds']
774,397
AiIsBetter/computer_vision
config_util.py
save_pipeline_config
save_pipeline_config
Saves a pipeline config text file to disk.
[ "Saves", "a", "pipeline", "config", "text", "file", "to", "disk." ]
def save_pipeline_config(pipeline_config, directory): if not file_io.file_exists(directory): file_io.recursive_create_dir(directory) pipeline_config_path = os.path.join(directory, 'pipeline.config') config_text = text_format.MessageToString(pipeline_config) with tf.gfile.Open(pipeline_config_pat...
['def', 'save_pipeline_config(pipeline_config,', 'directory):', 'if', 'not', 'file_io.file_exists(directory):', 'file_io.recursive_create_dir(directory)', 'pipeline_config_path', '=', 'os.path.join(directory,', "'pipeline.config')", 'config_text', '=', 'text_format.MessageToString(pipeline_config)', 'with', 'tf.gfile.O...
512,183
ludwig-ai/ludwig
test_gbm.py
test_hummingbird_conversion_binary
test_hummingbird_conversion_binary
Verify that Hummingbird conversion predictions match LightGBM predictions for binary outputs.
[ "Verify", "that", "Hummingbird", "conversion", "predictions", "match", "LightGBM", "predictions", "for", "binary", "outputs." ]
def test_hummingbird_conversion_binary(tmpdir, local_backend): input_features = [number_feature(), category_feature(encoder={'reduce_output': 'sum'})] output_features = [binary_feature()] output_feature = f"{output_features[0]['name']}_probabilities" (preds_lgbm, model) = _train_and_predict_gbm(input_fe...
['def', 'test_hummingbird_conversion_binary(tmpdir,', 'local_backend):', 'input_features', '=', '[number_feature(),', "category_feature(encoder={'reduce_output':", "'sum'})]", 'output_features', '=', '[binary_feature()]', 'output_feature', '=', 'f"{output_features[0][\'name\']}_probabilities"', '(preds_lgbm,', 'model)'...
617,251
rootskar/EEGMotorImagery
signal.py
ButterBandstop.process
process
Apply the filter to data along a given axis.
[ "Apply", "the", "filter", "to", "data", "along", "a", "given", "axis." ]
def process(self, data, axis=0): return scipy.signal.filtfilt(self.b, self.a, data, axis)
['def', 'process(self,', 'data,', 'axis=0):', 'return', 'scipy.signal.filtfilt(self.b,', 'self.a,', 'data,', 'axis)']
175,361
peiyunh/wysiwyg
fastai_optim.py
OptimWrapper.step
step
Set weight decay and step optimizer.
[ "Set", "weight", "decay", "and", "step", "optimizer." ]
def step(self) -> None: if self.true_wd: for (lr, wd, pg1, pg2) in zip(self._lr, self._wd, self.opt.param_groups[::2], self.opt.param_groups[1::2]): for p in pg1['params']: p.data.mul_(1 - wd * lr) if self.bn_wd: for p in pg2['params']: ...
['def', 'step(self)', '->', 'None:', 'if', 'self.true_wd:', 'for', '(lr,', 'wd,', 'pg1,', 'pg2)', 'in', 'zip(self._lr,', 'self._wd,', 'self.opt.param_groups[::2],', 'self.opt.param_groups[1::2]):', 'for', 'p', 'in', "pg1['params']:", 'p.data.mul_(1', '-', 'wd', '*', 'lr)', 'if', 'self.bn_wd:', 'for', 'p', 'in', "pg2['p...
961,445
tensorflow/agents
nest_utils.py
split_nested_tensors
split_nested_tensors
Split batched nested tensors, on batch dim (outer dim), into a list.
[ "Split", "batched", "nested", "tensors,", "on", "batch", "dim", "(outer", "dim),", "into", "a", "list." ]
def split_nested_tensors(tensors, specs, num_or_size_splits): split_tensor_lists = [] (flat_tensors, flat_shapes) = _flatten_and_check_shape_nested_tensors(tensors, specs) for (tensor, shape) in zip(flat_tensors, flat_shapes): if tensor.shape.rank == shape.rank: raise ValueError('Can onl...
['def', 'split_nested_tensors(tensors,', 'specs,', 'num_or_size_splits):', 'split_tensor_lists', '=', '[]', '(flat_tensors,', 'flat_shapes)', '=', '_flatten_and_check_shape_nested_tensors(tensors,', 'specs)', 'for', '(tensor,', 'shape)', 'in', 'zip(flat_tensors,', 'flat_shapes):', 'if', 'tensor.shape.rank', '==', 'shap...
23,852
googleapis/python-aiplatform
uploader.py
_ByteBudgetManager.add_time_series
add_time_series
Integrates the cost of a tag proto into the byte budget.
[ "Integrates", "the", "cost", "of", "a", "tag", "proto", "into", "the", "byte", "budget." ]
def add_time_series(self, time_series_proto: tensorboard_data.TimeSeriesData): cost = time_series_proto._pb.ByteSize() + _MAX_VARINT64_LENGTH_BYTES + 1 if cost > self._byte_budget: raise _OutOfSpaceError() self._byte_budget -= cost
['def', 'add_time_series(self,', 'time_series_proto:', 'tensorboard_data.TimeSeriesData):', 'cost', '=', 'time_series_proto._pb.ByteSize()', '+', '_MAX_VARINT64_LENGTH_BYTES', '+', '1', 'if', 'cost', '>', 'self._byte_budget:', 'raise', '_OutOfSpaceError()', 'self._byte_budget', '-=', 'cost']
810,180
hitchtest/hitch
core.py
iter_params_for_processing
iter_params_for_processing
Given a sequence of parameters in the order as should be considered for processing and an iterable of parameters that exist, this returns a list in the correct order as they should be processed.
[ "Given", "a", "sequence", "of", "parameters", "in", "the", "order", "as", "should", "be", "considered", "for", "processing", "and", "an", "iterable", "of", "parameters", "that", "exist,", "this", "returns", "a", "list", "in", "the", "correct", "order", "as",...
def iter_params_for_processing(invocation_order, declaration_order): def sort_key(item): try: idx = invocation_order.index(item) except ValueError: idx = float('inf') return (not item.is_eager, idx) return sorted(declaration_order, key=sort_key)
['def', 'iter_params_for_processing(invocation_order,', 'declaration_order):', 'def', 'sort_key(item):', 'try:', 'idx', '=', 'invocation_order.index(item)', 'except', 'ValueError:', 'idx', '=', "float('inf')", 'return', '(not', 'item.is_eager,', 'idx)', 'return', 'sorted(declaration_order,', 'key=sort_key)']
206,551
nosmokingbandit/watcher
__init__.py
HTTPConnection.close
close
Close the socket underlying this connection.
[ "Close", "the", "socket", "underlying", "this", "connection." ]
def close(self): self.rfile.close() if not self.linger: self._close_kernel_socket() self.socket.close() else: pass
['def', 'close(self):', 'self.rfile.close()', 'if', 'not', 'self.linger:', 'self._close_kernel_socket()', 'self.socket.close()', 'else:', 'pass']
381,627
SALT-NLP/Adaptive-Compositional-Modules
modeling_funnel.py
upsample
upsample
Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension.
[ "Upsample", "tensor", "`x`", "to", "match", "`target_len`", "by", "repeating", "the", "tokens", "`stride`", "time", "on", "the", "sequence", "length", "dimension." ]
def upsample(x, stride, target_len, separate_cls=True, truncate_seq=False): if stride == 1: return x if separate_cls: cls = x[:, :1] x = x[:, 1:] output = torch.repeat_interleave(x, repeats=stride, dim=1) if separate_cls: if truncate_seq: output = nn.functiona...
['def', 'upsample(x,', 'stride,', 'target_len,', 'separate_cls=True,', 'truncate_seq=False):', 'if', 'stride', '==', '1:', 'return', 'x', 'if', 'separate_cls:', 'cls', '=', 'x[:,', ':1]', 'x', '=', 'x[:,', '1:]', 'output', '=', 'torch.repeat_interleave(x,', 'repeats=stride,', 'dim=1)', 'if', 'separate_cls:', 'if', 'tru...
408,769
devashish-patel/webcam-motion-detector
cookiejar.py
CookieJar.set_cookie_if_ok
set_cookie_if_ok
Set a cookie if policy says it's OK to do so.
[ "Set", "a", "cookie", "if", "policy", "says", "it's", "OK", "to", "do", "so." ]
def set_cookie_if_ok(self, cookie, request): self._cookies_lock.acquire() try: self._policy._now = self._now = int(time.time()) if self._policy.set_ok(cookie, request): self.set_cookie(cookie) finally: self._cookies_lock.release()
['def', 'set_cookie_if_ok(self,', 'cookie,', 'request):', 'self._cookies_lock.acquire()', 'try:', 'self._policy._now', '=', 'self._now', '=', 'int(time.time())', 'if', 'self._policy.set_ok(cookie,', 'request):', 'self.set_cookie(cookie)', 'finally:', 'self._cookies_lock.release()']
978,051
CYBERDEVILZ/artificial-
timer_comparison.py
ModuleTester.assert_array_equal
assert_array_equal
Checks the elementwise equality of two masked arrays.
[ "Checks", "the", "elementwise", "equality", "of", "two", "masked", "arrays." ]
def assert_array_equal(self, x, y, err_msg=''): self.assert_array_compare(self.equal, x, y, err_msg=err_msg, header='Arrays are not equal')
['def', 'assert_array_equal(self,', 'x,', 'y,', "err_msg=''):", 'self.assert_array_compare(self.equal,', 'x,', 'y,', 'err_msg=err_msg,', "header='Arrays", 'are', 'not', "equal')"]
172,537
songw-zju/Meta-RangeSeg
laserscan.py
LaserScan.size
size
Return the size of the point cloud.
[ "Return", "the", "size", "of", "the", "point", "cloud." ]
def size(self): return self.points.shape[0]
['def', 'size(self):', 'return', 'self.points.shape[0]']
632,977
mazefeng/ml
swivel.py
embeddings_with_init
embeddings_with_init
Creates and initializes the embedding tensors.
[ "Creates", "and", "initializes", "the", "embedding", "tensors." ]
def embeddings_with_init(vocab_size, embedding_dim, name): return tf.get_variable(name=name, shape=[vocab_size, embedding_dim], initializer=tf.random_normal_initializer(stddev=math.sqrt(1.0 / embedding_dim)))
['def', 'embeddings_with_init(vocab_size,', 'embedding_dim,', 'name):', 'return', 'tf.get_variable(name=name,', 'shape=[vocab_size,', 'embedding_dim],', 'initializer=tf.random_normal_initializer(stddev=math.sqrt(1.0', '/', 'embedding_dim)))']
239,612
googleapis/python-aiplatform
async_client.py
ScheduleServiceAsyncClient.from_service_account_info
from_service_account_info
Creates an instance of this client using the provided credentials info.
[ "Creates", "an", "instance", "of", "this", "client", "using", "the", "provided", "credentials", "info." ]
def from_service_account_info(cls, info: dict, *args, **kwargs): return ScheduleServiceClient.from_service_account_info.__func__(ScheduleServiceAsyncClient, info, *args, **kwargs)
['def', 'from_service_account_info(cls,', 'info:', 'dict,', '*args,', '**kwargs):', 'return', 'ScheduleServiceClient.from_service_account_info.__func__(ScheduleServiceAsyncClient,', 'info,', '*args,', '**kwargs)']
813,951
dguo98/DiffPruning
optimization_tf.py
AdamWeightDecay.from_config
from_config
Creates an optimizer from its config with WarmUp custom object.
[ "Creates", "an", "optimizer", "from", "its", "config", "with", "WarmUp", "custom", "object." ]
def from_config(cls, config): custom_objects = {'WarmUp': WarmUp} return super().from_config(config, custom_objects=custom_objects)
['def', 'from_config(cls,', 'config):', 'custom_objects', '=', "{'WarmUp':", 'WarmUp}', 'return', 'super().from_config(config,', 'custom_objects=custom_objects)']
551,085
stefan-rz/udacity-aind
solution.py
display
display
Display the values as a 2-D grid.
[ "Display", "the", "values", "as", "a", "2-D", "grid." ]
def display(values): width = 1 + max((len(values[s]) for s in boxes)) line = '+'.join(['-' * (width * 3)] * 3) for r in rows: print(''.join((values[r + c].center(width) + ('|' if c in '36' else '') for c in cols))) if r in 'CF': print(line) return
['def', 'display(values):', 'width', '=', '1', '+', 'max((len(values[s])', 'for', 's', 'in', 'boxes))', 'line', '=', "'+'.join(['-'", '*', '(width', '*', '3)]', '*', '3)', 'for', 'r', 'in', 'rows:', "print(''.join((values[r", '+', 'c].center(width)', '+', "('|'", 'if', 'c', 'in', "'36'", 'else', "'')", 'for', 'c', 'in'...
427,911
matsu0228/nlp-jp
dok.py
dok_matrix.getrow
getrow
Returns the i-th row as a (1 x n) DOK matrix.
[ "Returns", "the", "i-th", "row", "as", "a", "(1", "x", "n)", "DOK", "matrix." ]
def getrow(self, i): new = dok_matrix((1, self.shape[1]), dtype=self.dtype) dict.update(new, (((0, j), self[i, j]) for j in xrange(self.shape[1]))) return new
['def', 'getrow(self,', 'i):', 'new', '=', 'dok_matrix((1,', 'self.shape[1]),', 'dtype=self.dtype)', 'dict.update(new,', '(((0,', 'j),', 'self[i,', 'j])', 'for', 'j', 'in', 'xrange(self.shape[1])))', 'return', 'new']
805,873
vturrisi/solo-learn
mocov3.py
mocov3_loss_func
mocov3_loss_func
Computes MoCo V3's loss given a batch of queries from view 1, a batch of keys from view 2 and a queue of past elements.
[ "Computes", "MoCo", "V3's", "loss", "given", "a", "batch", "of", "queries", "from", "view", "1,", "a", "batch", "of", "keys", "from", "view", "2", "and", "a", "queue", "of", "past", "elements." ]
def mocov3_loss_func(query: torch.Tensor, key: torch.Tensor, temperature=0.2) -> torch.Tensor: n = query.size(0) device = query.device rank = dist.get_rank() if dist.is_available() and dist.is_initialized() else 0 query = F.normalize(query, dim=1) key = F.normalize(key, dim=1) key = concat_all_g...
['def', 'mocov3_loss_func(query:', 'torch.Tensor,', 'key:', 'torch.Tensor,', 'temperature=0.2)', '->', 'torch.Tensor:', 'n', '=', 'query.size(0)', 'device', '=', 'query.device', 'rank', '=', 'dist.get_rank()', 'if', 'dist.is_available()', 'and', 'dist.is_initialized()', 'else', '0', 'query', '=', 'F.normalize(query,', ...
393,565
ArdaGunay99/Key_Detection_Unsupervised_Learning
ipaddress.py
_BaseNetwork.supernet_of
supernet_of
Return True if this network is a supernet of other.
[ "Return", "True", "if", "this", "network", "is", "a", "supernet", "of", "other." ]
def supernet_of(self, other): return self._is_subnet_of(other, self)
['def', 'supernet_of(self,', 'other):', 'return', 'self._is_subnet_of(other,', 'self)']
259,137
openvinotoolkit/training_extensions
fast_rcnn.py
AVAFastRCNN.forward_infer
forward_infer
Forward function for inference without pre-proposal.
[ "Forward", "function", "for", "inference", "without", "pre-proposal." ]
def forward_infer(ctx, self, imgs, img_metas): clip_len = imgs.shape[2] img = imgs[:, :, int(clip_len / 2), :, :] (det_bboxes, det_labels) = self.detector.simple_test(img, img_metas[0]) prediction = [det_bboxes[0][det_labels[0] == 0]] prediction = self.simple_test(imgs, img_metas[0], proposals=predi...
['def', 'forward_infer(ctx,', 'self,', 'imgs,', 'img_metas):', 'clip_len', '=', 'imgs.shape[2]', 'img', '=', 'imgs[:,', ':,', 'int(clip_len', '/', '2),', ':,', ':]', '(det_bboxes,', 'det_labels)', '=', 'self.detector.simple_test(img,', 'img_metas[0])', 'prediction', '=', '[det_bboxes[0][det_labels[0]', '==', '0]]', 'pr...
903,868
rarriaza/ATPRO_HCNN
tf_utils.py
pack_inputs
pack_inputs
Pack a list of `inputs` tensors to a tuple.
[ "Pack", "a", "list", "of", "`inputs`", "tensors", "to", "a", "tuple." ]
def pack_inputs(inputs): inputs = tf.nest.flatten(inputs) outputs = [] for x in inputs: if x is None: outputs.append(tf.constant(0, shape=[], dtype=tf.int32)) else: outputs.append(x) return tuple(outputs)
['def', 'pack_inputs(inputs):', 'inputs', '=', 'tf.nest.flatten(inputs)', 'outputs', '=', '[]', 'for', 'x', 'in', 'inputs:', 'if', 'x', 'is', 'None:', 'outputs.append(tf.constant(0,', 'shape=[],', 'dtype=tf.int32))', 'else:', 'outputs.append(x)', 'return', 'tuple(outputs)']
92,679
agrabeli/artificial-intelligence
__init__.py
VersionControl.obtain
obtain
Called when installing or updating an editable package, takes the source path of the checkout.
[ "Called", "when", "installing", "or", "updating", "an", "editable", "package,", "takes", "the", "source", "path", "of", "the", "checkout." ]
def obtain(self, dest): raise NotImplementedError
['def', 'obtain(self,', 'dest):', 'raise', 'NotImplementedError']
89,975
dwf/convolupy
base.py
BaseBPropComponent.bprop
bprop
Backpropagate derivatives through this module to get derivatives with respect to this module's input.
[ "Backpropagate", "derivatives", "through", "this", "module", "to", "get", "derivatives", "with", "respect", "to", "this", "module's", "input." ]
def bprop(self, dout, inputs): dshp = 'x'.join((str(x) for x in dout.shape)) ishp = 'x'.join((str(x) for x in inputs.shape)) raise NotImplementedError('bprop(dout@%s, input@%s): %s' % (dshp, ishp, str(self.__class__)))
['def', 'bprop(self,', 'dout,', 'inputs):', 'dshp', '=', "'x'.join((str(x)", 'for', 'x', 'in', 'dout.shape))', 'ishp', '=', "'x'.join((str(x)", 'for', 'x', 'in', 'inputs.shape))', 'raise', "NotImplementedError('bprop(dout@%s,", 'input@%s):', "%s'", '%', '(dshp,', 'ishp,', 'str(self.__class__)))']
136,997
devashish-patel/webcam-motion-detector
openpy.py
open
open
Open a file in read only mode using the encoding detected by detect_encoding().
[ "Open", "a", "file", "in", "read", "only", "mode", "using", "the", "encoding", "detected", "by", "detect_encoding()." ]
def open(filename): buffer = io.open(filename, 'rb') (encoding, lines) = detect_encoding(buffer.readline) buffer.seek(0) text = TextIOWrapper(buffer, encoding, line_buffering=True) text.mode = 'r' return text
['def', 'open(filename):', 'buffer', '=', 'io.open(filename,', "'rb')", '(encoding,', 'lines)', '=', 'detect_encoding(buffer.readline)', 'buffer.seek(0)', 'text', '=', 'TextIOWrapper(buffer,', 'encoding,', 'line_buffering=True)', 'text.mode', '=', "'r'", 'return', 'text']
979,412
jxhe/unify-parameter-efficient-tuning
test_tokenization_xlm_prophetnet.py
XLMProphetNetTokenizationTest.test_convert_token_and_id
test_convert_token_and_id
Test ``_convert_token_to_id`` and ``_convert_id_to_token``.
[ "Test", "``_convert_token_to_id``", "and", "``_convert_id_to_token``." ]
def test_convert_token_and_id(self): token = '[PAD]' token_id = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id) self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token)
['def', 'test_convert_token_and_id(self):', 'token', '=', "'[PAD]'", 'token_id', '=', '0', 'self.assertEqual(self.get_tokenizer()._convert_token_to_id(token),', 'token_id)', 'self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id),', 'token)']
949,543
Jittor/JDet
gaussian_dist_loss.py
xy_wh_r_2_xy_sigma
xy_wh_r_2_xy_sigma
Convert oriented bounding box to 2-D Gaussian distribution.
[ "Convert", "oriented", "bounding", "box", "to", "2-D", "Gaussian", "distribution." ]
def xy_wh_r_2_xy_sigma(xywhr): _shape = xywhr.shape assert _shape[-1] == 5 xy = xywhr[..., :2] wh = xywhr[..., 2:4].clamp(1e-07, 10000000.0).reshape(-1, 2) r = xywhr[..., 4] cos_r = jt.cos(r) sin_r = jt.sin(r) R = jt.stack((cos_r, -sin_r, sin_r, cos_r), dim=-1).reshape(-1, 2, 2) S = ...
['def', 'xy_wh_r_2_xy_sigma(xywhr):', '_shape', '=', 'xywhr.shape', 'assert', '_shape[-1]', '==', '5', 'xy', '=', 'xywhr[...,', ':2]', 'wh', '=', 'xywhr[...,', '2:4].clamp(1e-07,', '10000000.0).reshape(-1,', '2)', 'r', '=', 'xywhr[...,', '4]', 'cos_r', '=', 'jt.cos(r)', 'sin_r', '=', 'jt.sin(r)', 'R', '=', 'jt.stack((c...
577,716
weimin17/Object-Detection_HelmetDetection
vgsl_model.py
VGSLImageModel.Build
Build
Builds the model from the separate input/layers/output spec strings.
[ "Builds", "the", "model", "from", "the", "separate", "input/layers/output", "spec", "strings." ]
def Build(self, input_pattern, input_spec, model_spec, output_spec, optimizer_type, num_preprocess_threads, reader): self.global_step = tf.Variable(0, name='global_step', trainable=False) shape = _ParseInputSpec(input_spec) (out_dims, out_func, num_classes) = _ParseOutputSpec(output_spec) self.using_ctc...
['def', 'Build(self,', 'input_pattern,', 'input_spec,', 'model_spec,', 'output_spec,', 'optimizer_type,', 'num_preprocess_threads,', 'reader):', 'self.global_step', '=', 'tf.Variable(0,', "name='global_step',", 'trainable=False)', 'shape', '=', '_ParseInputSpec(input_spec)', '(out_dims,', 'out_func,', 'num_classes)', '...
760,003
qixuxiang/mask_rcnn_ros
utils.py
Dataset.get_source_class_id
get_source_class_id
Map an internal class ID to the corresponding class ID in the source dataset.
[ "Map", "an", "internal", "class", "ID", "to", "the", "corresponding", "class", "ID", "in", "the", "source", "dataset." ]
def get_source_class_id(self, class_id, source): info = self.class_info[class_id] assert info['source'] == source return info['id']
['def', 'get_source_class_id(self,', 'class_id,', 'source):', 'info', '=', 'self.class_info[class_id]', 'assert', "info['source']", '==', 'source', 'return', "info['id']"]
645,712
Kvatsx/Artificial-Intelligence-Assignments
httpserver_test.py
BadSSLOptionsTest.test_missing_key
test_missing_key
A missing SSL key should cause an immediate exception.
[ "A", "missing", "SSL", "key", "should", "cause", "an", "immediate", "exception." ]
def test_missing_key(self): application = Application() module_dir = os.path.dirname(__file__) existing_certificate = os.path.join(module_dir, 'test.crt') existing_key = os.path.join(module_dir, 'test.key') self.assertRaises((ValueError, IOError), HTTPServer, application, ssl_options={'certfile': '/...
['def', 'test_missing_key(self):', 'application', '=', 'Application()', 'module_dir', '=', 'os.path.dirname(__file__)', 'existing_certificate', '=', 'os.path.join(module_dir,', "'test.crt')", 'existing_key', '=', 'os.path.join(module_dir,', "'test.key')", 'self.assertRaises((ValueError,', 'IOError),', 'HTTPServer,', 'a...
78,884
matsu0228/nlp-jp
tree.py
ExprStmt.get_rhs
get_rhs
Returns the right-hand-side of the equals.
[ "Returns", "the", "right-hand-side", "of", "the", "equals." ]
def get_rhs(self): return self.children[-1]
['def', 'get_rhs(self):', 'return', 'self.children[-1]']
803,165
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
template.py
Base.dumps
dumps
Dumps this template to a string.
[ "Dumps", "this", "template", "to", "a", "string." ]
def dumps(self, level=0): fd = StringIO() self.dump(fd, level) return fd.getvalue()
['def', 'dumps(self,', 'level=0):', 'fd', '=', 'StringIO()', 'self.dump(fd,', 'level)', 'return', 'fd.getvalue()']
17,041
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
template.py
Method.iterDecl
iterDecl
Yields the declaration for this method template.
[ "Yields", "the", "declaration", "for", "this", "method", "template." ]
def iterDecl(self): def formatParam(p): if 'default' in p: return '{0}={1}'.format(p['name'], p['default']) return p['name'] params = ', '.join((formatParam(param) for param in self.iterParams())) yield 'def {0}({1}):'.format(self.name, params)
['def', 'iterDecl(self):', 'def', 'formatParam(p):', 'if', "'default'", 'in', 'p:', 'return', "'{0}={1}'.format(p['name'],", "p['default'])", 'return', "p['name']", 'params', '=', "',", "'.join((formatParam(param)", 'for', 'param', 'in', 'self.iterParams()))', 'yield', "'def", "{0}({1}):'.format(self.name,", 'params)']
17,000
Ruturaj123/Flowchart-Detection
common_shapes.py
unchanged_shape
unchanged_shape
Shape function for ops that output an tensor like their first input.
[ "Shape", "function", "for", "ops", "that", "output", "an", "tensor", "like", "their", "first", "input." ]
def unchanged_shape(op): return [op.inputs[0].get_shape()]
['def', 'unchanged_shape(op):', 'return', '[op.inputs[0].get_shape()]']
605,302
yunsukim86/sockeye-transfer
utils.py
metric_value_is_better
metric_value_is_better
Returns true if new value is strictly better than old for given metric.
[ "Returns", "true", "if", "new", "value", "is", "strictly", "better", "than", "old", "for", "given", "metric." ]
def metric_value_is_better(new: float, old: float, metric: str) -> bool: if C.METRIC_MAXIMIZE[metric]: return new > old else: return new < old
['def', 'metric_value_is_better(new:', 'float,', 'old:', 'float,', 'metric:', 'str)', '->', 'bool:', 'if', 'C.METRIC_MAXIMIZE[metric]:', 'return', 'new', '>', 'old', 'else:', 'return', 'new', '<', 'old']
879,189
Farama-Foundation/Gymnasium
rescale_action.py
RescaleAction.action
action
Rescales the action affinely from [:attr:`min_action`, :attr:`max_action`] to the action space of the base environment, :attr:`env`.
[ "Rescales", "the", "action", "affinely", "from", "[:attr:`min_action`,", ":attr:`max_action`]", "to", "the", "action", "space", "of", "the", "base", "environment,", ":attr:`env`." ]
def action(self, action): assert np.all(np.greater_equal(action, self.min_action)), (action, self.min_action) assert np.all(np.less_equal(action, self.max_action)), (action, self.max_action) low = self.env.action_space.low high = self.env.action_space.high action = low + (high - low) * ((action - se...
['def', 'action(self,', 'action):', 'assert', 'np.all(np.greater_equal(action,', 'self.min_action)),', '(action,', 'self.min_action)', 'assert', 'np.all(np.less_equal(action,', 'self.max_action)),', '(action,', 'self.max_action)', 'low', '=', 'self.env.action_space.low', 'high', '=', 'self.env.action_space.high', 'acti...
573,410
victordibia/data2vis
parallel_data_provider.py
make_parallel_data_provider
make_parallel_data_provider
Creates a DataProvider that reads parallel text data.
[ "Creates", "a", "DataProvider", "that", "reads", "parallel", "text", "data." ]
def make_parallel_data_provider(data_sources_source, data_sources_target, reader=tf.TextLineReader, num_samples=None, source_delimiter=' ', target_delimiter=' ', **kwargs): decoder_source = split_tokens_decoder.SplitTokensDecoder(tokens_feature_name='source_tokens', length_feature_name='source_len', append_token='S...
['def', 'make_parallel_data_provider(data_sources_source,', 'data_sources_target,', 'reader=tf.TextLineReader,', 'num_samples=None,', "source_delimiter='", "',", "target_delimiter='", "',", '**kwargs):', 'decoder_source', '=', "split_tokens_decoder.SplitTokensDecoder(tokens_feature_name='source_tokens',", "length_featu...
126,830
salesforce/CodeRL
tokenization_flaubert.py
convert_to_unicode
convert_to_unicode
Converts `text` to Unicode (if it's not already), assuming UTF-8 input.
[ "Converts", "`text`", "to", "Unicode", "(if", "it's", "not", "already),", "assuming", "UTF-8", "input." ]
def convert_to_unicode(text): def six_ensure_text(s, encoding='utf-8', errors='strict'): if isinstance(s, six.binary_type): return s.decode(encoding, errors) elif isinstance(s, six.text_type): return s else: raise TypeError(f"not expecting type '{type(s)}...
['def', 'convert_to_unicode(text):', 'def', 'six_ensure_text(s,', "encoding='utf-8',", "errors='strict'):", 'if', 'isinstance(s,', 'six.binary_type):', 'return', 's.decode(encoding,', 'errors)', 'elif', 'isinstance(s,', 'six.text_type):', 'return', 's', 'else:', 'raise', 'TypeError(f"not', 'expecting', 'type', '\'{type...
494,614
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
ttk.py
Combobox.set
set
Sets the value of the combobox to value.
[ "Sets", "the", "value", "of", "the", "combobox", "to", "value." ]
def set(self, value): self.tk.call(self._w, 'set', value)
['def', 'set(self,', 'value):', 'self.tk.call(self._w,', "'set',", 'value)']
376,686
openvinotoolkit/training_extensions
test_task.py
TestOpenVINODetectionInferencer.test_predict
test_predict
Test predict method in OpenVINODetectionInferencer.
[ "Test", "predict", "method", "in", "OpenVINODetectionInferencer." ]
def test_predict(self, mocker): fake_output = AnnotationSceneEntity(kind=AnnotationSceneKind.ANNOTATION, annotations=[]) mock_pre_process = mocker.patch.object(OpenVINODetectionInferencer, 'pre_process', return_value=('', '')) mock_forward = mocker.patch.object(OpenVINODetectionInferencer, 'forward') mo...
['def', 'test_predict(self,', 'mocker):', 'fake_output', '=', 'AnnotationSceneEntity(kind=AnnotationSceneKind.ANNOTATION,', 'annotations=[])', 'mock_pre_process', '=', 'mocker.patch.object(OpenVINODetectionInferencer,', "'pre_process',", "return_value=('',", "''))", 'mock_forward', '=', 'mocker.patch.object(OpenVINODet...
919,342
weimin17/Object-Detection_HelmetDetection
skip_thoughts_encoder.py
SkipThoughtsEncoder.build_graph_from_config
build_graph_from_config
Builds the inference graph from a configuration object.
[ "Builds", "the", "inference", "graph", "from", "a", "configuration", "object." ]
def build_graph_from_config(self, model_config, checkpoint_path): tf.logging.info('Building model.') model = skip_thoughts_model.SkipThoughtsModel(model_config, mode='encode') model.build() saver = tf.train.Saver() return self._create_restore_fn(checkpoint_path, saver)
['def', 'build_graph_from_config(self,', 'model_config,', 'checkpoint_path):', "tf.logging.info('Building", "model.')", 'model', '=', 'skip_thoughts_model.SkipThoughtsModel(model_config,', "mode='encode')", 'model.build()', 'saver', '=', 'tf.train.Saver()', 'return', 'self._create_restore_fn(checkpoint_path,', 'saver)'...
759,595
mlcommons/medperf
views.py
BenchmarkDatasetList.get
get
Retrieve datasets associated with a benchmark instance.
[ "Retrieve", "datasets", "associated", "with", "a", "benchmark", "instance." ]
def get(self, request, pk, format=None): benchmark = self.get_object(pk) datasetgroups = benchmark.benchmarkdataset_set.all() datasets = [gp.dataset for gp in datasetgroups] datasets = self.paginate_queryset(datasets) serializer = DatasetSerializer(datasets, many=True) return self.get_paginated_...
['def', 'get(self,', 'request,', 'pk,', 'format=None):', 'benchmark', '=', 'self.get_object(pk)', 'datasetgroups', '=', 'benchmark.benchmarkdataset_set.all()', 'datasets', '=', '[gp.dataset', 'for', 'gp', 'in', 'datasetgroups]', 'datasets', '=', 'self.paginate_queryset(datasets)', 'serializer', '=', 'DatasetSerializer(...
285,175
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
memory.py
Memory.make_update_op
make_update_op
Function that creates all the update ops.
[ "Function", "that", "creates", "all", "the", "update", "ops." ]
def make_update_op(self, upd_idxs, upd_keys, upd_vals, batch_size, use_recent_idx, intended_output): mem_age_incr = self.mem_age.assign_add(tf.ones([self.memory_size], dtype=tf.float32)) with tf.control_dependencies([mem_age_incr]): mem_age_upd = tf.scatter_update(self.mem_age, upd_idxs, tf.zeros([batch...
['def', 'make_update_op(self,', 'upd_idxs,', 'upd_keys,', 'upd_vals,', 'batch_size,', 'use_recent_idx,', 'intended_output):', 'mem_age_incr', '=', 'self.mem_age.assign_add(tf.ones([self.memory_size],', 'dtype=tf.float32))', 'with', 'tf.control_dependencies([mem_age_incr]):', 'mem_age_upd', '=', 'tf.scatter_update(self....
49,584
bachiraoun/fullrmc
GroupSelector.py
RecursiveGroupSelector.willExplore
willExplore
Get whether next step the same group will be returned and explore flag is True.
[ "Get", "whether", "next", "step", "the", "same", "group", "will", "be", "returned", "and", "explore", "flag", "is", "True." ]
def willExplore(self): return self.isRecurring and self.__explore
['def', 'willExplore(self):', 'return', 'self.isRecurring', 'and', 'self.__explore']
213,854
for-ai/rl
advantages.py
ValueEstimatorBase.set_keys
set_keys
Set tensordict key names.
[ "Set", "tensordict", "key", "names." ]
def set_keys(self, **kwargs) -> None: for (key, value) in kwargs.items(): if not isinstance(value, (str, tuple)): raise ValueError(f'key name must be of type NestedKey (Union[str, Tuple[str]]) but got {type(value)}') if value is None: raise ValueError('tensordict keys cannot ...
['def', 'set_keys(self,', '**kwargs)', '->', 'None:', 'for', '(key,', 'value)', 'in', 'kwargs.items():', 'if', 'not', 'isinstance(value,', '(str,', 'tuple)):', 'raise', "ValueError(f'key", 'name', 'must', 'be', 'of', 'type', 'NestedKey', '(Union[str,', 'Tuple[str]])', 'but', 'got', "{type(value)}')", 'if', 'value', 'is...
859,388
googleapis/python-aiplatform
client.py
EndpointServiceClient.endpoint_path
endpoint_path
Returns a fully-qualified endpoint string.
[ "Returns", "a", "fully-qualified", "endpoint", "string." ]
def endpoint_path(project: str, location: str, endpoint: str) -> str: return 'projects/{project}/locations/{location}/endpoints/{endpoint}'.format(project=project, location=location, endpoint=endpoint)
['def', 'endpoint_path(project:', 'str,', 'location:', 'str,', 'endpoint:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/endpoints/{endpoint}'.format(project=project,", 'location=location,', 'endpoint=endpoint)']
812,347
deepmind/grid-cells
model.py
GridCellsRNNCell.output_size
output_size
Returns a description of the output size, without batch dimension.
[ "Returns", "a", "description", "of", "the", "output", "size,", "without", "batch", "dimension." ]
def output_size(self): return tuple([ens.n_cells for ens in self._target_ensembles] + [self._nh_bottleneck, self._nh_lstm])
['def', 'output_size(self):', 'return', 'tuple([ens.n_cells', 'for', 'ens', 'in', 'self._target_ensembles]', '+', '[self._nh_bottleneck,', 'self._nh_lstm])']
233,995
google-research/scenic
ops.py
get_select_channels
get_select_channels
Returns function to select specified channels.
[ "Returns", "function", "to", "select", "specified", "channels." ]
def get_select_channels(channels): def _select_channels(image): return tf.gather(image, channels, axis=-1) return _select_channels
['def', 'get_select_channels(channels):', 'def', '_select_channels(image):', 'return', 'tf.gather(image,', 'channels,', 'axis=-1)', 'return', '_select_channels']
846,121
textflint/textflint
pos_sample.py
POSSample.check_data
check_data
Check rare data format.
[ "Check", "rare", "data", "format." ]
def check_data(self, data): assert 'x' in data and isinstance(data['x'], list), 'x should be in data, and the type of x should be list' assert 'y' in data and isinstance(data['y'], list), 'y should be in data, and the type of y should be list'
['def', 'check_data(self,', 'data):', 'assert', "'x'", 'in', 'data', 'and', "isinstance(data['x'],", 'list),', "'x", 'should', 'be', 'in', 'data,', 'and', 'the', 'type', 'of', 'x', 'should', 'be', "list'", 'assert', "'y'", 'in', 'data', 'and', "isinstance(data['y'],", 'list),', "'y", 'should', 'be', 'in', 'data,', 'and...
913,670
irdanish11/Seq2Seq-UrduChatBot
vocabulary.py
Vocabulary.load
load
Loads the vocabulary from disk.
[ "Loads", "the", "vocabulary", "from", "disk." ]
def load(filepath): vocabulary = Vocabulary() with open(filepath, encoding='utf-8') as file: for (index, line) in enumerate(file): if index > 0: (word, count) = line.split('\t') word_int = index - 1 vocabulary.load_word(word, word_int, int(coun...
['def', 'load(filepath):', 'vocabulary', '=', 'Vocabulary()', 'with', 'open(filepath,', "encoding='utf-8')", 'as', 'file:', 'for', '(index,', 'line)', 'in', 'enumerate(file):', 'if', 'index', '>', '0:', '(word,', 'count)', '=', "line.split('\\t')", 'word_int', '=', 'index', '-', '1', 'vocabulary.load_word(word,', 'word...
876,486
ArdaGunay99/Key_Detection_Unsupervised_Learning
scale.py
get_scale_docs
get_scale_docs
Helper function for generating docstrings related to scales.
[ "Helper", "function", "for", "generating", "docstrings", "related", "to", "scales." ]
def get_scale_docs(): return _get_scale_docs()
['def', 'get_scale_docs():', 'return', '_get_scale_docs()']
257,253
TrellixVulnTeam/Unsupervised_Learning_HFI7
utils.py
get_traceback_from_context
get_traceback_from_context
Get the traceback object from the context.
[ "Get", "the", "traceback", "object", "from", "the", "context." ]
def get_traceback_from_context(context: Dict[str, Any]) -> Optional[TracebackType]: exception = context.get('exception') if exception: if hasattr(exception, '__traceback__'): return exception.__traceback__ else: return sys.exc_info()[2] return None
['def', 'get_traceback_from_context(context:', 'Dict[str,', 'Any])', '->', 'Optional[TracebackType]:', 'exception', '=', "context.get('exception')", 'if', 'exception:', 'if', 'hasattr(exception,', "'__traceback__'):", 'return', 'exception.__traceback__', 'else:', 'return', 'sys.exc_info()[2]', 'return', 'None']
435,126
ifwe/digsby
spellchecktextctrlmixin.py
add_spelling_suggestions
add_spelling_suggestions
Adds spelling suggestions to a UMenu.
[ "Adds", "spelling", "suggestions", "to", "a", "UMenu." ]
def add_spelling_suggestions(tc, menu): (position, suggestions) = tc.HitTestSuggestions(tc.ScreenToClient(wx.GetMousePosition())) for sug in suggestions: if sug != '': menu.AddItem(sug, callback=lambda sug=sug: tc.ReplaceWord(position, sug)) word = tc.GetWordAtPosition(position) if w...
['def', 'add_spelling_suggestions(tc,', 'menu):', '(position,', 'suggestions)', '=', 'tc.HitTestSuggestions(tc.ScreenToClient(wx.GetMousePosition()))', 'for', 'sug', 'in', 'suggestions:', 'if', 'sug', '!=', "'':", 'menu.AddItem(sug,', 'callback=lambda', 'sug=sug:', 'tc.ReplaceWord(position,', 'sug))', 'word', '=', 'tc....
185,274
CQCL/lambeq
ccg_type.py
CCGType.is_conjoinable
is_conjoinable
Whether the CCG type can be used to conjoin words.
[ "Whether", "the", "CCG", "type", "can", "be", "used", "to", "conjoin", "words." ]
def is_conjoinable(self) -> bool: return self in (self.CONJUNCTION, self.PUNCTUATION)
['def', 'is_conjoinable(self)', '->', 'bool:', 'return', 'self', 'in', '(self.CONJUNCTION,', 'self.PUNCTUATION)']
623,242
rifqind/Agent-Programs-3KS1
debugger.py
Pdb.print_list_lines
print_list_lines
The printing (as opposed to the parsing part of a 'list' command.
[ "The", "printing", "(as", "opposed", "to", "the", "parsing", "part", "of", "a", "'list'", "command." ]
def print_list_lines(self, filename, first, last): try: Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) src ...
['def', 'print_list_lines(self,', 'filename,', 'first,', 'last):', 'try:', 'Colors', '=', 'self.color_scheme_table.active_colors', 'ColorsNormal', '=', 'Colors.Normal', 'tpl_line', '=', "'%%s%s%%s", "%s%%s'", '%', '(Colors.lineno,', 'ColorsNormal)', 'tpl_line_em', '=', "'%%s%s%%s", "%s%%s%s'", '%', '(Colors.linenoEm,',...
40,945
voxel51/fiftyone
annotations.py
AnnotationBackend.requires_attr_values
requires_attr_values
Determines whether the list of possible values are required for attributes of the given type.
[ "Determines", "whether", "the", "list", "of", "possible", "values", "are", "required", "for", "attributes", "of", "the", "given", "type." ]
def requires_attr_values(self, attr_type): raise NotImplementedError('subclass must implement requires_attr_values()')
['def', 'requires_attr_values(self,', 'attr_type):', 'raise', "NotImplementedError('subclass", 'must', 'implement', "requires_attr_values()')"]
583,904
SergiosKar/Deep-Learning-models
colorspace.py
gray2bgr
gray2bgr
Convert a grayscale image to BGR image.
[ "Convert", "a", "grayscale", "image", "to", "BGR", "image." ]
def gray2bgr(img): img = img[..., None] if img.ndim == 2 else img out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) return out_img
['def', 'gray2bgr(img):', 'img', '=', 'img[...,', 'None]', 'if', 'img.ndim', '==', '2', 'else', 'img', 'out_img', '=', 'cv2.cvtColor(img,', 'cv2.COLOR_GRAY2BGR)', 'return', 'out_img']
518,935
myothida/Supervised-Machine-Learning
test__util.py
test_numpy_deprecation
test_numpy_deprecation
Test that 'from numpy import *' functions are deprecated.
[ "Test", "that", "'from", "numpy", "import", "*'", "functions", "are", "deprecated." ]
def test_numpy_deprecation(key): if key in ('ifft', 'diag', 'arccos'): arg = [1.0, 0.0] elif key == 'finfo': arg = float else: arg = 2 func = getattr(scipy, key) match = 'scipy\\.%s is deprecated.*2\\.0\\.0' % key with deprecated_call(match=match) as dep: func(arg...
['def', 'test_numpy_deprecation(key):', 'if', 'key', 'in', "('ifft',", "'diag',", "'arccos'):", 'arg', '=', '[1.0,', '0.0]', 'elif', 'key', '==', "'finfo':", 'arg', '=', 'float', 'else:', 'arg', '=', '2', 'func', '=', 'getattr(scipy,', 'key)', 'match', '=', "'scipy\\\\.%s", 'is', "deprecated.*2\\\\.0\\\\.0'", '%', 'key...
446,660
43Carrig/recurrent_neural_networks_practice
execute.py
make_tensor
make_tensor
Ensure v is a TensorProto.
[ "Ensure", "v", "is", "a", "TensorProto." ]
def make_tensor(v, arg_name): if isinstance(v, tensor_pb2.TensorProto): return v elif isinstance(v, six.string_types): pb = tensor_pb2.TensorProto() text_format.Merge(v, pb) return pb raise TypeError("Don't know how to convert %s to a TensorProto for argument '%s'." % (repr(v...
['def', 'make_tensor(v,', 'arg_name):', 'if', 'isinstance(v,', 'tensor_pb2.TensorProto):', 'return', 'v', 'elif', 'isinstance(v,', 'six.string_types):', 'pb', '=', 'tensor_pb2.TensorProto()', 'text_format.Merge(v,', 'pb)', 'return', 'pb', 'raise', 'TypeError("Don\'t', 'know', 'how', 'to', 'convert', '%s', 'to', 'a', 'T...
336,131
googleapis/python-aiplatform
pipeline_based_service.py
_VertexAiPipelineBasedService.list
list
Lists all PipelineJob resources associated with this Pipeline Based service.
[ "Lists", "all", "PipelineJob", "resources", "associated", "with", "this", "Pipeline", "Based", "service." ]
def list(cls, project: Optional[str]=None, location: Optional[str]=None, credentials: Optional[str]=None) -> List['_VertexAiPipelineBasedService']: filter_str = f'metadata.component_type.string_value={cls._component_identifier}' filtered_pipeline_executions = aiplatform.Execution.list(filter=filter_str, credent...
['def', 'list(cls,', 'project:', 'Optional[str]=None,', 'location:', 'Optional[str]=None,', 'credentials:', 'Optional[str]=None)', '->', "List['_VertexAiPipelineBasedService']:", 'filter_str', '=', "f'metadata.component_type.string_value={cls._component_identifier}'", 'filtered_pipeline_executions', '=', 'aiplatform.Ex...
810,314
LiangSiyuan21/Adversarial-Attacks-for-Image-and-Video--
vis_tool.py
vis_bbox
vis_bbox
Visualize bounding boxes inside image.
[ "Visualize", "bounding", "boxes", "inside", "image." ]
def vis_bbox(img, bbox, label=None, score=None, ax=None): label_names = list(VOC_BBOX_LABEL_NAMES) + ['bg'] if label is not None and (not len(bbox) == len(label)): raise ValueError('The length of label must be same as that of bbox') if score is not None and (not len(bbox) == len(score)): rai...
['def', 'vis_bbox(img,', 'bbox,', 'label=None,', 'score=None,', 'ax=None):', 'label_names', '=', 'list(VOC_BBOX_LABEL_NAMES)', '+', "['bg']", 'if', 'label', 'is', 'not', 'None', 'and', '(not', 'len(bbox)', '==', 'len(label)):', 'raise', "ValueError('The", 'length', 'of', 'label', 'must', 'be', 'same', 'as', 'that', 'of...
396,938
mme/vergeml
utils.py
dict_set_path
dict_set_path
Set the value of a dict using path syntax.
[ "Set", "the", "value", "of", "a", "dict", "using", "path", "syntax." ]
def dict_set_path(dic, path, value): cur = dic path = path.split('.') for key in path[:-1]: cur = cur.setdefault(key, {}) cur[path[-1]] = value
['def', 'dict_set_path(dic,', 'path,', 'value):', 'cur', '=', 'dic', 'path', '=', "path.split('.')", 'for', 'key', 'in', 'path[:-1]:', 'cur', '=', 'cur.setdefault(key,', '{})', 'cur[path[-1]]', '=', 'value']
931,577
fudan-zvg/DeepInteraction
waymo_converter.py
Waymo2KITTI.convert_one
convert_one
Convert action for single file.
[ "Convert", "action", "for", "single", "file." ]
def convert_one(self, file_idx): pathname = self.tfrecord_pathnames[file_idx] dataset = tf.data.TFRecordDataset(pathname, compression_type='') for (frame_idx, data) in enumerate(dataset): frame = dataset_pb2.Frame() frame.ParseFromString(bytearray(data.numpy())) if self.selected_waym...
['def', 'convert_one(self,', 'file_idx):', 'pathname', '=', 'self.tfrecord_pathnames[file_idx]', 'dataset', '=', 'tf.data.TFRecordDataset(pathname,', "compression_type='')", 'for', '(frame_idx,', 'data)', 'in', 'enumerate(dataset):', 'frame', '=', 'dataset_pb2.Frame()', 'frame.ParseFromString(bytearray(data.numpy()))',...
521,216
weimin17/Object-Detection_HelmetDetection
dataset.py
Dataset.available_subsets
available_subsets
Returns the list of available subsets.
[ "Returns", "the", "list", "of", "available", "subsets." ]
def available_subsets(self): return ['train', 'validation']
['def', 'available_subsets(self):', 'return', "['train',", "'validation']"]
763,112
adeshpande3/ReinforcementLearning
agent.py
ContinuousAgent.run
run
Run the agent for several episodes.
[ "Run", "the", "agent", "for", "several", "episodes." ]
def run(self): for episode in range(MAX_EPISODES): noise_ratio = INITIAL_ORNSTEIN_UHLENBECK_NOISE_RATIO - episode / NUMBER_OF_EXPLORATION_EPISODES if episode < NUMBER_OF_EXPLORATION_EPISODES * INITIAL_ORNSTEIN_UHLENBECK_NOISE_RATIO else 0.0 episode_rewards = 0.0 end_of_episode = False ...
['def', 'run(self):', 'for', 'episode', 'in', 'range(MAX_EPISODES):', 'noise_ratio', '=', 'INITIAL_ORNSTEIN_UHLENBECK_NOISE_RATIO', '-', 'episode', '/', 'NUMBER_OF_EXPLORATION_EPISODES', 'if', 'episode', '<', 'NUMBER_OF_EXPLORATION_EPISODES', '*', 'INITIAL_ORNSTEIN_UHLENBECK_NOISE_RATIO', 'else', '0.0', 'episode_reward...
287,173
Trusted-AI/AIX360
BRCG.py
BRCGExplainer.fit
fit
Fit model to training data.
[ "Fit", "model", "to", "training", "data." ]
def fit(self, X_train, Y_train, *argv, **kwargs): self._model.fit(X_train, Y_train, **kwargs)
['def', 'fit(self,', 'X_train,', 'Y_train,', '*argv,', '**kwargs):', 'self._model.fit(X_train,', 'Y_train,', '**kwargs)']
413,311